第一次提交

This commit is contained in:
不明不惑
2026-03-03 01:23:02 +08:00
commit 3e434877e8
1053 changed files with 102411 additions and 0 deletions

View File

@@ -0,0 +1,30 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GGA_GameplayAbility.h"
#include "GCS_CombatAbility.generated.h"
class IGCS_CombatEntityInterface;
class UGCS_CombatSystemComponent;
/**
* Base combat ability.
* 基础战斗能力。
*/
UCLASS(Abstract)
class GENERICCOMBATSYSTEM_API UGCS_CombatAbility : public UGGA_GameplayAbility
{
GENERATED_BODY()
protected:
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GCS|Ability")
UGCS_CombatSystemComponent* GetCombatSystemFromActorInfo() const;
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GCS|Ability")
UObject* GetCombatEntityFromActorInfo() const;
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GCS|Ability")
TScriptInterface<IGCS_CombatEntityInterface> GetCombatEntityInterfaceFromActorInfo() const;
};

View File

@@ -0,0 +1,105 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GCS_CombatAbility.h"
#include "Combo/GCS_ComboDefinition.h"
#include "GCS_ComboAbility.generated.h"
class UGCS_CombatSystemComponent;
class UAS_Combat;
/**
* This combo ability acted as manager of sub abilities.
*/
UCLASS(Abstract, HideCategories=(Cooldowns,Input,GampelayEffects))
class GENERICCOMBATSYSTEM_API UGCS_ComboAbility : public UGCS_CombatAbility
{
GENERATED_BODY()
public:
UGCS_ComboAbility();
virtual void PreActivate(const FGameplayAbilitySpecHandle Handle, const FGameplayAbilityActorInfo* ActorInfo, const FGameplayAbilityActivationInfo ActivationInfo,
FOnGameplayAbilityEnded::FDelegate* OnGameplayAbilityEndedDelegate, const FGameplayEventData* TriggerEventData = nullptr) override;
virtual void ActivateAbility(const FGameplayAbilitySpecHandle Handle, const FGameplayAbilityActorInfo* ActorInfo, const FGameplayAbilityActivationInfo ActivationInfo,
const FGameplayEventData* TriggerEventData) override;
virtual bool CanActivateAbility(const FGameplayAbilitySpecHandle Handle, const FGameplayAbilityActorInfo* ActorInfo, const FGameplayTagContainer* SourceTags = nullptr,
const FGameplayTagContainer* TargetTags = nullptr, FGameplayTagContainer* OptionalRelevantTags = nullptr) const override;
virtual void OnGiveAbility(const FGameplayAbilityActorInfo* ActorInfo, const FGameplayAbilitySpec& Spec) override;
virtual void OnRemoveAbility(const FGameplayAbilityActorInfo* ActorInfo, const FGameplayAbilitySpec& Spec) override;
virtual void EndAbility(const FGameplayAbilitySpecHandle Handle, const FGameplayAbilityActorInfo* ActorInfo, const FGameplayAbilityActivationInfo ActivationInfo, bool bReplicateEndAbility,
bool bWasCancelled) override;
protected:
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category = "Combat Ability")
bool AllowAdvanceCombo() const;
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category = "Combat Ability")
void StartCombo(const FGameplayEventData& ComboEvent);
virtual void StartCombo_Implementation(const FGameplayEventData& ComboEvent);
/**
* Advance combo with ComboEventData as context.
* @param ComboEventData The data used as combo context. 游戏事件数据作为连击上下文。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category = "Combat Ability")
void AdvanceCombo(const FGameplayEventData& ComboEventData);
virtual void AdvanceCombo_Implementation(const FGameplayEventData& ComboEventData);
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category = "Combat Ability")
void ResetCombo();
UFUNCTION()
virtual void HandleAbilityEnd(const FAbilityEndedData& AbilityEndedData);
virtual bool SelectComboDefinition(const FGameplayEventData& ComboEventData, int32 CurrentStep, FGCS_ComboDefinition& OutDefinition);
/**
* This is where you can use the extension filed within your combo definition to apply additional rules.
* 这里你可以使用连击定义中的自定义字段来添加额外的选择规则。
* @param ComboEvent The combo event data to provide as context.连击事件数据,用作上下文参考。
* @param CurrentStep The current combo step of combat system. 当前的连击步骤。
* @param ComboDefinition The combo definition you are checking. 正在检查的连击定义。
*/
UFUNCTION(BlueprintNativeEvent, Category = "Combat Ability")
bool CanSelectedComboDefinition(const FGameplayEventData& ComboEvent, int32 CurrentStep, const FGCS_ComboDefinition& ComboDefinition) const;
virtual void HandleComboExecution(const FGameplayEventData& ComboEventData);
// virtual void GiveSubAbilities(const FGameplayAbilitySpec& CurrentSpec);
// virtual void RemoveSubAbilities();
protected:
bool bCurrentAbilityEnded = false;
//The ability current combo step was executing.
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="Combo")
FGameplayAbilitySpecHandle CurrentAbility;
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="Combo")
TSubclassOf<UGameplayAbility> CurrentAbilityClass;
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="Combo")
FGameplayAbilitySpecHandle NextAbility;
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="Combo")
TSubclassOf<UGameplayAbility> NextAbilityAbilityClass;
int32 DesiredComboStep{INDEX_NONE};
/**
* Granted potential combo abilities.
* 赋予的潜在ComboAbilities.
*/
// UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="Combo")
// TArray<FGameplayAbilitySpecHandle> AvailableAbilities;
FDelegateHandle AbilityEndedDelegateHandle;
#if WITH_EDITOR
virtual EDataValidationResult IsDataValid(class FDataValidationContext& Context) const override;
#endif
};

View File

@@ -0,0 +1,124 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "AttributeSet.h"
#include "AbilitySystemComponent.h"
#include "NativeGameplayTags.h"
#include "AS_Poise.generated.h"
namespace AS_Poise
{
GENERICCOMBATSYSTEM_API UE_DECLARE_GAMEPLAY_TAG_EXTERN(Poise)
GENERICCOMBATSYSTEM_API UE_DECLARE_GAMEPLAY_TAG_EXTERN(MaxPoise)
GENERICCOMBATSYSTEM_API UE_DECLARE_GAMEPLAY_TAG_EXTERN(PoiseRecover)
}
#define ATTRIBUTE_ACCESSORS(ClassName, PropertyName) \
GAMEPLAYATTRIBUTE_PROPERTY_GETTER(ClassName, PropertyName) \
GAMEPLAYATTRIBUTE_VALUE_GETTER(PropertyName) \
GAMEPLAYATTRIBUTE_VALUE_SETTER(PropertyName) \
GAMEPLAYATTRIBUTE_VALUE_INITTER(PropertyName)
UCLASS()
class GENERICCOMBATSYSTEM_API UAS_Poise : public UAttributeSet
{
GENERATED_BODY()
public:
UAS_Poise();
virtual void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const override;
virtual void PreAttributeChange(const FGameplayAttribute& Attribute, float& NewValue) override;
virtual void PostAttributeChange(const FGameplayAttribute& Attribute, float OldValue, float NewValue) override;
virtual bool PreGameplayEffectExecute(struct FGameplayEffectModCallbackData& Data) override;
virtual void PostGameplayEffectExecute(const FGameplayEffectModCallbackData& Data) override;
// Current Poise value of an actor.(actor的当前抗打击值)
UPROPERTY(BlueprintReadOnly, ReplicatedUsing = OnRep_Poise, Category = "Attribute|PoiseSet", Meta = (AllowPrivateAccess = true))
FGameplayAttributeData Poise{ 3 };
ATTRIBUTE_ACCESSORS(ThisClass, Poise)
// Max Poise value of an actor.(actor的最大抗打击值)
UPROPERTY(BlueprintReadOnly, ReplicatedUsing = OnRep_MaxPoise, Category = "Attribute|PoiseSet", Meta = (AllowPrivateAccess = true))
FGameplayAttributeData MaxPoise{ 3 };
ATTRIBUTE_ACCESSORS(ThisClass, MaxPoise)
// How many Poise to recover per second.(每秒恢复抗打击值)
UPROPERTY(BlueprintReadOnly, ReplicatedUsing = OnRep_PoiseRecover, Category = "Attribute|PoiseSet", Meta = (AllowPrivateAccess = true))
FGameplayAttributeData PoiseRecover{ 1 };
ATTRIBUTE_ACCESSORS(ThisClass, PoiseRecover)
UFUNCTION(BlueprintCallable,BlueprintPure,meta=(DisplayName="GetPoiseAttribute"), Category = "Attribute|PoiseSet")
static FGameplayAttribute Bp_GetPoiseAttribute();
UFUNCTION(BlueprintPure,meta=(DisplayName="GetPoise"), Category = "Attribute|PoiseSet")
float Bp_GetPoise() const;
UFUNCTION(BlueprintCallable,meta=(DisplayName="SetPoise"), Category = "Attribute|PoiseSet")
void Bp_SetPoise(float NewValue);
UFUNCTION(BlueprintCallable,meta=(DisplayName="InitPoise"), Category = "Attribute|PoiseSet")
void Bp_InitPoise(float NewValue);
UFUNCTION(BlueprintCallable,BlueprintPure,meta=(DisplayName="GetMaxPoiseAttribute"), Category = "Attribute|PoiseSet")
static FGameplayAttribute Bp_GetMaxPoiseAttribute();
UFUNCTION(BlueprintPure,meta=(DisplayName="GetMaxPoise"), Category = "Attribute|PoiseSet")
float Bp_GetMaxPoise() const;
UFUNCTION(BlueprintCallable,meta=(DisplayName="SetMaxPoise"), Category = "Attribute|PoiseSet")
void Bp_SetMaxPoise(float NewValue);
UFUNCTION(BlueprintCallable,meta=(DisplayName="InitMaxPoise"), Category = "Attribute|PoiseSet")
void Bp_InitMaxPoise(float NewValue);
UFUNCTION(BlueprintCallable,BlueprintPure,meta=(DisplayName="GetPoiseRecoverAttribute"), Category = "Attribute|PoiseSet")
static FGameplayAttribute Bp_GetPoiseRecoverAttribute();
UFUNCTION(BlueprintPure,meta=(DisplayName="GetPoiseRecover"), Category = "Attribute|PoiseSet")
float Bp_GetPoiseRecover() const;
UFUNCTION(BlueprintCallable,meta=(DisplayName="SetPoiseRecover"), Category = "Attribute|PoiseSet")
void Bp_SetPoiseRecover(float NewValue);
UFUNCTION(BlueprintCallable,meta=(DisplayName="InitPoiseRecover"), Category = "Attribute|PoiseSet")
void Bp_InitPoiseRecover(float NewValue);
protected:
/** Helper function to proportionally adjust the value of an attribute when it's associated max attribute changes. (i.e. When MaxHealth increases, Health increases by an amount that maintains the same percentage as before) */
virtual void AdjustAttributeForMaxChange(FGameplayAttributeData& AffectedAttribute, const FGameplayAttributeData& MaxAttribute, float NewMaxValue, const FGameplayAttribute& AffectedAttributeProperty);
UFUNCTION()
virtual void OnRep_Poise(const FGameplayAttributeData& OldValue);
UFUNCTION()
virtual void OnRep_MaxPoise(const FGameplayAttributeData& OldValue);
UFUNCTION()
virtual void OnRep_PoiseRecover(const FGameplayAttributeData& OldValue);
};

View File

@@ -0,0 +1,16 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GGA_AbilitySystemGlobals.h"
#include "DEPRECATED_GCS_AbilitySystemGlobals.generated.h"
UCLASS(Deprecated, meta=(DeprecationMessage="GCS_AbilitySystemGlobals is deprecated. Please use GGA_AbilitySystemGlobals instead."))
class GENERICCOMBATSYSTEM_API UDEPRECATED_GCS_AbilitySystemGlobals : public UGGA_AbilitySystemGlobals
{
GENERATED_BODY()
public:
virtual FGameplayEffectContext* AllocGameplayEffectContext() const override;
};

View File

@@ -0,0 +1,24 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GameplayEffectComponent.h"
#include "GCS_GEComponent_PredictivelyExecute.generated.h"
/**
* This component will predictively execute instant GE which treated as infinite one.
* @attention Internally will mark this effect context as local predicting context, so you can conditional apply logic in subsequent codes.
*/
UCLASS()
class GENERICCOMBATSYSTEM_API UGCS_GEComponent_PredictivelyExecute : public UGameplayEffectComponent
{
GENERATED_BODY()
public:
virtual void OnGameplayEffectApplied(FActiveGameplayEffectsContainer& ActiveGEContainer, FGameplayEffectSpec& GESpec, FPredictionKey& PredictionKey) const override;
private:
UPROPERTY(EditDefaultsOnly, Category = GCS)
bool bPredictGameplayCues{false};
};

View File

@@ -0,0 +1,74 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GCS_CombatStructLibrary.h"
#include "UObject/Object.h"
#include "GCS_GameplayEffectContext.generated.h"
/**
* The Combat related data which was carried and pass around within gameplay effect context, as one of the gameplay effect context payload.
* 战斗相关数据,在游戏效果上下文中被携带和传递,作为游戏效果上下文数据之一。
*/
USTRUCT(BlueprintType)
struct GENERICCOMBATSYSTEM_API FGCS_ContextPayload_Combat
{
GENERATED_BODY()
void SetTaggedValue(const FGameplayTag& Tag, float NewValue);
float GetTaggedValue(const FGameplayTag& Tag) const;
/**
* Indicate the effect spec owning this context was Predictively executed.
* 表示拥有此上下文的效果实例是以客户端预测方式执行的。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GCS")
bool bIsPredictingContext{false};
UPROPERTY()
FPredictionKey PredictionKey;
/**
* Attack definition data table.
* 攻击定义数据表。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GCS", meta=(RequiredAssetDataTags = "RowStructure=/Script/GenericCombatSystem.GCS_AttackDefinition"))
TObjectPtr<const UDataTable> AtkDataTable{nullptr};
/**
* Row name in the attack definition table.
* 攻击定义表中的行名。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GCS")
FName AtkRowName{NAME_None};
/**
* Bullet definition data table.
* 子弹定义数据表。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GCS", meta=(RequiredAssetDataTags = "RowStructure=/Script/GenericCombatSystem.GCS_BulletDefinition"))
TObjectPtr<const UDataTable> BulletDataTable{nullptr};
/**
* Row name in the bullet definition table.
* 子弹定义表中的行名。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GCS")
FName BulletRowName{NAME_None};
/**
* The tags added during gameplay effect apply(coming from MMC,or Execution).
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GCS")
FGameplayTagContainer DynamicTags;
/**
* Array of tagged values associated with the combat process.
* 与战斗过程关联的标记值数组。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GCS")
TArray<FGCS_TaggedValue> TaggedValues;
};

View File

@@ -0,0 +1,116 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Abilities/Tasks/AbilityTask.h"
#include "Collision/GCS_TraceStructLibrary.h"
#include "Components/SkeletalMeshComponent.h"
#include "GCS_AbilityTask_CollisionTrace.generated.h"
class UGCS_AttackRequest_Melee;
/**
* Ability task for handling collision traces in combat.
* 处理战斗中碰撞检测的能力任务。
*/
UCLASS()
class GENERICCOMBATSYSTEM_API UGCS_AbilityTask_CollisionTrace : public UAbilityTask
{
GENERATED_BODY()
public:
UGCS_AbilityTask_CollisionTrace();
/**
* Creates and activates a collision trace task.
* 创建并激活碰撞检测任务。
* @param OwningAbility The owning gameplay ability. 所属游戏能力。
* @param TaskInstanceName The name of the task instance. 任务实例名称。
* @param bAdjustVisibilityBasedAnimTickOption Whether to adjust visibility-based animation ticking. 是否调整基于可见性的动画tick。
* @return The created task. 创建的任务。
*/
UFUNCTION(BlueprintCallable, Category = "GCS|AbilityTasks", meta = (HidePin = "OwningAbility", DefaultToSelf = "OwningAbility", BlueprintInternalUseOnly = "TRUE"))
static UGCS_AbilityTask_CollisionTrace* HandleCollisionTraces(UGameplayAbility* OwningAbility, FName TaskInstanceName, bool bAdjustVisibilityBasedAnimTickOption = false);
/**
* Activates the task.
* 激活任务。
*/
virtual void Activate() override;
/**
* Called when the task is destroyed.
* 任务销毁时调用。
* @param bInOwnerFinished Whether the owner finished the task. 拥有者是否完成了任务。
*/
virtual void OnDestroy(bool bInOwnerFinished) override;
/**
* Adds a melee attack request to the task.
* 向任务添加近战攻击请求。
* @param Request The melee attack request. 近战攻击请求。
* @param SourceObject Optional source object. 可选的源对象。
*/
UFUNCTION(BlueprintCallable, Category = "GCS|AbilityTasks")
void AddMeleeRequest(const UGCS_AttackRequest_Melee* Request, UObject* SourceObject);
/**
* Removes a melee attack request from the task.
* 从任务移除近战攻击请求。
* @param Request The melee attack request. 近战攻击请求。
*/
UFUNCTION(BlueprintCallable, Category = "GCS|AbilityTasks")
void RemoveMeleeRequest(const UGCS_AttackRequest_Melee* Request);
/**
* Delegate for trace instance hit events.
* 碰撞检测实例命中事件的委托。
*/
DECLARE_DYNAMIC_MULTICAST_DELEGATE_ThreeParams(FGCS_OnTraceInstanceHitSignature, const UGCS_AttackRequest_Melee*, MeleeRequest, const FGCS_TraceHandle&, TraceHandle,
const FHitResult&,
HitResult);
/**
* Fired when a trace instance detects targets.
* 当碰撞检测实例检测到目标时触发。
*/
UPROPERTY(BlueprintAssignable)
FGCS_OnTraceInstanceHitSignature OnTargetsFound;
protected:
/**
* Handles trace instance hit events.
* 处理碰撞检测实例命中事件。
* @param TraceHandle The trace instance. 碰撞检测实例。
* @param HitResult The hit result. 命中结果。
*/
UFUNCTION()
void TraceHitCallback(const FGCS_TraceHandle& TraceHandle, const FHitResult& HitResult);
/**
* Map of melee requests to their associated trace instances.
* 近战请求及其关联碰撞检测实例的映射。
*/
TMap<TObjectPtr<const UGCS_AttackRequest_Melee>, TArray<FGCS_TraceHandle>> MeleeRequests;
/**
* Whether to adjust visibility-based animation ticking.
* 是否调整基于可见性的动画tick。
*/
UPROPERTY()
bool bAdjustAnimTickOption{false};
/**
* Whether the animation tick option was adjusted.
* 是否已调整动画tick选项。
*/
UPROPERTY()
bool bAdjustedAnimTickOption{false};
/**
* The previous animation tick option.
* 之前的动画tick选项。
*/
UPROPERTY()
EVisibilityBasedAnimTickOption PrevAnimTickOption{EVisibilityBasedAnimTickOption::AlwaysTickPose};
};

View File

@@ -0,0 +1,82 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GameplayTagContainer.h"
#include "GCS_BulletStructLibrary.h"
#include "Net/Serialization/FastArraySerializer.h"
#include "UObject/Object.h"
#include "GCS_BulletContainer.generated.h"
struct FGCS_BulletContainer;
class UGCS_BulletSystemComponent;
/**
* Structure representing an equipment entry in the container.
* 表示容器中装备条目的结构体。
* @note WIP
*/
USTRUCT(BlueprintType)
struct GENERICCOMBATSYSTEM_API FGCS_BulletEntry : public FFastArraySerializerItem
{
GENERATED_BODY()
friend FGCS_BulletContainer;
//The request id of this entry.
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GCS")
FGuid Id;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GCS")
FGCS_BulletSpawnParameters SpawnParameters;
};
/**
* Container for a list of applied equipment.
* 存储已应用装备列表的容器。
*/
USTRUCT()
struct GENERICCOMBATSYSTEM_API FGCS_BulletContainer : public FFastArraySerializer
{
GENERATED_BODY()
FGCS_BulletContainer()
: OwningComponent(nullptr)
{
}
FGCS_BulletContainer(UGCS_BulletSystemComponent* InComponent)
: OwningComponent(InComponent)
{
}
void PreReplicatedRemove(const TArrayView<int32> RemovedIndices, int32 FinalSize);
void PostReplicatedAdd(const TArrayView<int32> AddedIndices, int32 FinalSize);
void PostReplicatedChange(const TArrayView<int32> ChangedIndices, int32 FinalSize);
//~End of FFastArraySerializer contract
bool NetDeltaSerialize(FNetDeltaSerializeInfo& DeltaParms)
{
return FastArrayDeltaSerialize<FGCS_BulletEntry, FGCS_BulletContainer>(Entries, DeltaParms, *this);
}
int32 IndexOfById(const FGuid& Id) const;
UPROPERTY(VisibleAnywhere, Category="BulletSystem", meta=(ShowOnlyInnerProperties, DisplayName="Bullets"))
TArray<FGCS_BulletEntry> Entries;
UPROPERTY()
TObjectPtr<UGCS_BulletSystemComponent> OwningComponent;
};
template <>
struct TStructOpsTypeTraits<FGCS_BulletContainer> : TStructOpsTypeTraitsBase2<FGCS_BulletContainer>
{
enum { WithNetDeltaSerializer = true };
};

View File

@@ -0,0 +1,406 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GCS_BulletStructLibrary.h"
#include "GCS_EffectCauserInterface.h"
#include "GameFramework/Actor.h"
#include "GCS_BulletInstance.generated.h"
class UGCS_AttackRequest_Bullet;
class UGCS_BulletSubsystem;
class UProjectileMovementComponent;
/**
* Base class for bullet instances.
* 子弹实例的基类。
*/
UCLASS(Abstract, BlueprintType, NotBlueprintable)
class GENERICCOMBATSYSTEM_API AGCS_BulletInstance : public AActor, public IGCS_EffectCauserInterface
{
GENERATED_BODY()
friend UGCS_BulletSubsystem;
public:
/**
* Default constructor.
* 默认构造函数。
*/
AGCS_BulletInstance();
/**
* Gets lifetime replicated properties.
* 获取生命周期复制属性。
* @param OutLifetimeProps The lifetime properties. 生命周期属性。
*/
virtual void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const override;
/**
* Gets the projectile movement component.
* 获取子弹的运动组件。
* @return The projectile movement component. 运动组件。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GCS|Bullet")
UProjectileMovementComponent* GetProjectileMovementComponent() const;
/**
* Sets the bullet definition handle.
* 设置子弹定义句柄。
* @param NewHandle The new definition handle. 新定义句柄。
*/
UFUNCTION(BlueprintCallable, Category="GCS|Bullet")
void SetDefinitionHandle(UPARAM(meta=(RowType="/Script/GenericCombatSystem.GCS_BulletDefinition")) FDataTableRowHandle NewHandle);
/**
* Sets the bullet's unique ID.
* 设置子弹的唯一ID。
* @param NewId The new ID. 新ID。
*/
void SetBulletId(const FGuid& NewId);
/**
* Gets the bullet's unique ID.
* 获取子弹的唯一ID。
* @return The bullet ID. 子弹ID。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GCS|Bullet")
FGuid GetBulletId() const;
/**
* Sets the parent bullet ID for bullet chains.
* 设置子弹链的父子弹ID。
* @param NewParentId The parent bullet ID. 父子弹ID。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GCS|Bullet")
void SetParentBulletId(FGuid NewParentId);
/**
* Gets the parent bullet ID.
* 获取父子弹ID。
* @return The parent bullet ID. 父子弹ID。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GCS|Bullet")
FGuid GetParentBulletId() const;
/**
* Launches the bullet.
* 发射子弹。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GCS|Bullet")
void LaunchBullet();
/**
* Sets the hit result for the bullet.
* 设置子弹的命中结果。
* @param NewHitResult The hit result. 命中结果。
*/
UFUNCTION(BlueprintCallable, Category="GCS|Bullet", meta=(DisplayName="Set Bullet HitResult"))
void SetHitResult(const FHitResult& NewHitResult);
/**
* Gets the latest hit result.
* 获取最新的命中结果。
* @return The hit result. 命中结果。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GCS|Bullet", meta=(DisplayName="Get Bullet HitResult"))
const FHitResult& GetHitResult() const;
/**
* Checks if the bullet has gameplay authority.
* 检查子弹是否具有游戏权限。
* @return True if the bullet has authority. 如果子弹具有权限返回true。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GCS|Bullet")
bool HasGameplayAuthority() const;
/**
* Called after network initialization.
* 网络初始化后调用。
*/
virtual void PostNetInit() override;
/**
* Called after receiving network data.
* 接收网络数据后调用。
*/
virtual void PostNetReceive() override;
/**
* Handles locally predicted bullet instances.
* 处理本地预测的子弹实例。
* @param PredictedBullet The predicted bullet instance. 预测的子弹实例。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GCS|Bullet")
void FoundLocalPredictedBullet(AGCS_BulletInstance* PredictedBullet);
// Effect causer interface
/**
* Gets the gameplay effect spec handle.
* 获取游戏效果规格句柄。
* @param OutHandle The effect spec handle (output). 效果规格句柄(输出)。
* @return True if successful. 如果成功返回true。
*/
virtual bool GetEffectSpecHandle_Implementation(FGameplayEffectSpecHandle& OutHandle) override;
/**
* Gets the gameplay effect container.
* 获取游戏效果容器。
* @return The effect container. 效果容器。
*/
virtual FGGA_GameplayEffectContainer GetEffectContainer_Implementation() const override;
/**
* Gets the effect container level override.
* 获取效果容器级别覆盖。
* @return The level override. 级别覆盖。
*/
virtual int32 GetEffectContainerLevelOverride_Implementation() const override;
/**
* Sets the effect container spec.
* 设置效果容器规格。
* @param InEffectContainerSpec The effect container spec. 效果容器规格。
*/
virtual void SetEffectContainerSpec_Implementation(const FGGA_GameplayEffectContainerSpec& InEffectContainerSpec) override;
/**
* Gets the effect container spec.
* 获取效果容器规格。
* @return The effect container spec. 效果容器规格。
*/
virtual FGGA_GameplayEffectContainerSpec GetEffectContainerSpec_Implementation() const override;
/**
* Gets the effect class.
* 获取效果类。
* @return The effect class. 效果类。
*/
virtual TSubclassOf<UGameplayEffect> GetEffectClass_Implementation() const override;
/**
* Gets the effect level.
* 获取效果级别。
* @return The effect level. 效果级别。
*/
virtual int32 GetEffectLevel_Implementation() const override;
/**
* Sets the effect spec.
* 设置效果规格。
* @param InEffectSpec The effect spec. 效果规格。
*/
virtual void SetEffectSpec_Implementation(FGameplayEffectSpecHandle& InEffectSpec) override;
/**
* Gets the bullet's shape component.
* 获取子弹的形状组件。
* @return The shape component. 形状组件。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, BlueprintNativeEvent, Category="GCS|Bullet")
UShapeComponent* GetBulletShape() const;
virtual UShapeComponent* GetBulletShape_Implementation() const;
protected:
/**
* Called when the game starts or when spawned.
* 游戏开始或生成时调用。
*/
virtual void BeginPlay() override;
/**
* Called when the game ends or the bullet is destroyed.
* 游戏结束或子弹销毁时调用。
* @param EndPlayReason The reason for ending. 结束原因。
*/
virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override;
/**
* Called when the bullet is taken from the pool with a valid definition.
* 子弹从池中取出且具有有效定义时调用。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GCS|Bullet")
void OnBulletBeginPlay();
/**
* Called when the bullet is returned to the pool and deactivated.
* 子弹返回池中并停用时调用。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GCS|Bullet")
void OnBulletEndPlay();
/**
* Records the initial location and rotation of the bullet.
* 记录子弹的初始位置和旋转。
*/
UFUNCTION(BlueprintCallable, Category="GCS|Bullet")
void SetupInitialLocationAndRotation();
/**
* Refreshes the bullet's travel states.
* 刷新子弹的移动状态。
*/
UFUNCTION(BlueprintCallable, Category="GCS|Bullet")
virtual void RefreshTravelStates();
/**
* Checks if the hit result should be penetrated.
* 检查命中结果是否应穿透。
* @param InHitResult The hit result. 命中结果。
* @return True if the hit should be penetrated. 如果命中应穿透返回true。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GCS|Bullet")
virtual bool ShouldPenetrateHitResult(const FHitResult& InHitResult) const;
/**
* Checks if a bullet chain should be generated.
* 检查是否应生成子弹链。
* @return True if a bullet chain should be generated. 如果应生成子弹链返回true。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, BlueprintNativeEvent, Category="GCS|Bullet")
bool ShouldGenerateBullet();
/**
* Handles bullet chain logic on hit.
* 处理命中时的子弹链逻辑。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GCS|Bullet")
void HandleBulletHitChains();
/**
* Applies gameplay effects to the hit result.
* 对命中结果应用游戏效果。
* @param HitResult The hit result. 命中结果。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GCS|Bullet")
void ApplyGameplayEffects(FHitResult HitResult);
/**
* Called when the bullet ID is replicated.
* 子弹ID复制时调用。
* @param Prev The previous bullet ID. 之前的子弹ID。
*/
UFUNCTION()
virtual void OnRep_BulletId(FGuid Prev);
/**
* Called when the bullet definition is replicated.
* 子弹定义复制时调用。
*/
UFUNCTION()
void OnRep_BulletDefinition();
/**
* Unique ID of the bullet.
* 子弹的唯一ID。
*/
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, ReplicatedUsing=OnRep_BulletId, Category="GCS|BulletState")
FGuid BulletId;
/**
* Whether the bullet is locally predicted.
* 子弹是否为本地预测。
*/
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="GCS|BulletState")
bool bIsLocalPredicting{false};
/**
* Whether the bullet was spawned on the server.
* 子弹是否在服务器上生成。
*/
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="GCS|BulletState")
bool bServerInitiated{false};
/**
* Parent bullet ID for bullet chains.
* 子弹链的父子弹ID。
*/
UPROPERTY(VisibleAnywhere, Category="GCS|BulletState")
FGuid ParentBulletId;
/**
* The associated attack request.
* 关联的攻击请求。
*/
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="GCS|BulletState")
TObjectPtr<const UGCS_AttackRequest_Bullet> Request;
/**
* Handle to the bullet definition.
* 子弹定义的句柄。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GCS|Bullet", ReplicatedUsing=OnRep_BulletDefinition, meta=(ExposeOnSpawn))
FDataTableRowHandle DefinitionHandle;
/**
* Loaded bullet definition.
* 加载的子弹定义。
*/
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="GCS|BulletState")
FGCS_BulletDefinition Definition;
/**
* The projectile movement component.
* 子弹的运动组件。
*/
UPROPERTY(VisibleAnywhere, Category="GCS|Bullet")
TObjectPtr<UProjectileMovementComponent> ProjectileMovement;
/**
* The gameplay effect spec carried by the bullet.
* 子弹携带的游戏效果规格。
*/
UPROPERTY(VisibleAnywhere, Category="GCS|BulletState")
FGameplayEffectSpecHandle EffectSpecHandle;
/**
* The gameplay effect container spec carried by the bullet.
* 子弹携带的游戏效果容器规格。
*/
UPROPERTY(VisibleAnywhere, Category = "GCS|BulletState")
FGGA_GameplayEffectContainerSpec EffectContainerSpec;
/**
* Index for bullet chains.
* 子弹链的索引。
*/
UPROPERTY()
int32 ChainIndex{0};
/**
* Initial location of the bullet.
* 子弹的初始位置。
*/
UPROPERTY(BlueprintReadWrite, EditDefaultsOnly, Category="GCS|BulletState")
FVector InitialActorLocation;
/**
* Initial rotation of the bullet.
* 子弹的初始旋转。
*/
UPROPERTY(BlueprintReadWrite, EditDefaultsOnly, Category="GCS|BulletState")
FRotator InitialActorRotation;
/**
* The latest hit result.
* 最新的命中结果。
*/
UPROPERTY(VisibleAnywhere, Category="GCS|BulletState")
FHitResult LastHitResult;
/**
* Distance traveled by the bullet.
* 子弹的移动距离。
*/
UPROPERTY(BlueprintReadWrite, VisibleAnywhere, Category="GCS|BulletState")
double TraveledDistance{0.0f};
public:
/**
* Called every frame.
* 每帧调用。
* @param DeltaTime Time since last frame. 上一帧以来的时间。
*/
virtual void Tick(float DeltaTime) override;
};

View File

@@ -0,0 +1,351 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GCS_CombatStructLibrary.h"
#include "Runtime/Launch/Resources/Version.h"
#if ENGINE_MINOR_VERSION < 5
#include "InstancedStruct.h"
#else
#include "StructUtils/InstancedStruct.h"
#endif
#include "Collision/GCS_TraceStructLibrary.h"
#include "UObject/Object.h"
#include "GCS_BulletStructLibrary.generated.h"
class UGCS_AttackRequest_Bullet;
class UNiagaraSystem;
class AGCS_BulletInstance;
/**
* Base struct allow you to extend the bullet definition's fields using C++.
* 基础结构体允许你通过C++拓展子弹定义的字段。
*/
USTRUCT(BlueprintType, meta=(Hidden))
struct GENERICCOMBATSYSTEM_API FGCS_BulletDefinitionExtension
{
GENERATED_BODY()
};
/**
* Data structure defining bullet properties and behavior.
* 定义子弹属性和行为的数据结构。
*/
USTRUCT(BlueprintType, meta=(DisplayName="GCS Bullet Definition"))
struct GENERICCOMBATSYSTEM_API FGCS_BulletDefinition : public FTableRowBase
{
GENERATED_BODY()
/**
* The bullet actor class.
* 子弹Actor类。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Common", meta=(AllowAbstract="false"))
TSoftClassPtr<AGCS_BulletInstance> BulletActorClass;
/**
* Duration for which the bullet exists (-1 for infinite).
* 子弹存在的持续时间(-1表示无限
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Common")
float Duration{3.0};
/**
* Number of bullets fired at once.
* 一次性发射的子弹数量。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Launch Configuration", meta=(ClampMin=1, UIMin=1))
int32 BulletCount{1};
/**
* Yaw angle for bullet launch.
* 子弹发射的水平角。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Launch Configuration")
float LaunchAngle{0.0f};
/**
* Yaw angle interval between bullets.
* 子弹之间的水平角间隔。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Launch Configuration")
float LaunchAngleInterval{10.0f};
/**
* Pitch angle for bullet launch.
* 子弹发射的仰角。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Launch Configuration")
float LaunchElevationAngle{0.0f};
/**
* Distance at which bullet attenuation begins.
* 子弹开始衰减的距离。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Movement", meta=(Units="cm"))
float AttenuationRange{800.0f};
/**
* Gravity scale within the attenuation range.
* 衰减范围内的重力系数。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Movement")
float GravityScaleInRange{1.0f};
/**
* Gravity scale outside the attenuation range.
* 衰减范围外的重力系数。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Movement")
float GravityScaleOutRage{1.0f};
/**
* Initial hit radius for the bullet.
* 子弹的初始命中半径。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Movement", meta=(Units="cm"))
float InitialHitRadius{20.0f};
/**
* Final hit radius for the bullet (-1 to use initial radius).
* 子弹的最终命中半径(-1使用初始半径
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Movement", meta=(Units="cm"))
float FinalHitRadius{-1.0f};
/**
* Initial speed of the bullet.
* 子弹的初始速度。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Movement", meta=(Units="cm"))
float InitialSpeed{1500.0f};
/**
* Minimum speed of the bullet.
* 子弹的最小速度。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Movement", meta=(Units="cm"))
float MinSpeed{1500.0f};
/**
* Maximum speed of the bullet.
* 子弹的最大速度。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Movement", meta=(Units="cm"))
float MaxSpeed{1500.0f};
/**
* Handle to the attack definition for the bullet.
* 子弹的攻击定义句柄。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Attack", meta=(RowType="/Script/GenericCombatSystem.GCS_AttackDefinition"))
FDataTableRowHandle AttackDefinition;
/**
* Trace definitions for hit detection.
* 用于命中检测的碰撞检测定义。
* @note Overrides trace definitions in the bullet instance class.
* @注意 覆盖子弹实例类中的碰撞检测定义。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Trace")
TArray<FGCS_TraceDefinition> TraceDefinitions;
/**
* Visual effect for the bullet projectile (Niagara).
* 子弹的视觉效果Niagara
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="VFX")
TSoftObjectPtr<UNiagaraSystem> ProjectileFX;
/**
* Visual effect for the bullet projectile (Cascade).
* 子弹的视觉效果Cascade
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="VFX")
TSoftObjectPtr<UParticleSystem> ProjectileFX_Cascade;
/**
* Visual effect for bullet impact (Niagara).
* 子弹命中的视觉效果Niagara
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="VFX")
TSoftObjectPtr<UNiagaraSystem> ImpactFX;
/**
* Visual effect for bullet impact (Cascade).
* 子弹命中的视觉效果Cascade
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="VFX")
TSoftObjectPtr<UParticleSystem> ImpactFX_Cascade;
/**
* Sound effect for bullet impact.
* 子弹命中的音效。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="SFX")
TSoftObjectPtr<USoundBase> ImpactSFX;
/**
* Sound effect attached to the bullet projectile.
* 附着在子弹上的音效。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="SFX")
TSoftObjectPtr<USoundBase> ProjectileSFX;
/**
* Sound effect played once when the bullet spawns.
* 子弹生成时播放一次的音效。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="SFX")
TSoftObjectPtr<USoundBase> SpawnSFX;
/**
* Whether the bullet penetrates characters/pawns.
* 子弹是否穿透角色/Pawn。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Penetration")
bool bPenetrateCharacter{false};
/**
* Whether the bullet penetrates map geometry.
* 子弹是否穿透地图几何体。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Penetration")
bool bPenetrateMap{false};
/**
* Handle to the bullet definition to spawn on hit/expiration.
* 命中或失效时生成的子弹定义句柄。
* @note Cannot be the same as this bullet.
* @注意 不能与此子弹相同。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Hit Configuration", meta=(RowType="/Script/GenericCombatSystem.GCS_BulletDefinition"))
FDataTableRowHandle HitBulletDefinition;
/**
* Condition for launching bullet chains.
* 子弹链的发射条件。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Hit Configuration", meta=(Categories="GGF.Combat.Bullet.LaunchCond"))
FGameplayTag LaunchCondition{FGameplayTag::EmptyTag};
/**
* Native Instanced struct for extending the bullet definition.
* 实例化结构体用于扩充子弹定义的字段。
* @attention For C++ users only. 仅针对C++用户。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Extension")
TInstancedStruct<FGCS_BulletDefinitionExtension> NativeExtension;
/**
* Blueprint Instanced struct for extending the bullet definition.
* 实例化结构体用于扩充子弹定义的字段。
* @attention For blueprint users only. 仅针对蓝图用户。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Extension")
FInstancedStruct Extension;
/**
* Custom user settings for extending the bullet definition.
* 扩展子弹定义的自定义用户设置。
*/
UE_DEPRECATED(1.5, "Using extension field to add custom fields!")
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Deprecated", meta=(ForceInlineRow, BaseStruct = "/Script/GenericCombatSystem.GCS_UserSetting"))
TMap<FGameplayTag, FInstancedStruct> UserSettings;
/**
* Shares the hit history to sub bullet.(prevent repeat hit for whole bullet chains.)
*/
// UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Hit Configuration",meta=(Categories="GGF.Combat.Bullet.LaunchCond"))
// bool bUseSharedHitList{true};
/**
* The amount of time between a bullet hits something and when it explodes.
*/
// UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Hit Configuration", meta=(Units="s", ClampMin=0))
// float ExplosionDelay{0.0};
// Emitter will be added in next version.
// UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Emitter", meta=(RowType="/Script/GenericCombatSystem.GCS_BulletDefinition"))
// FDataTableRowHandle EmitterBulletDefinition;
//
// UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Emitter")
// float EmitterInitialWaitTime{0};
//
// UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Emitter")
// float EmitterMinShootInterval{0};
//
// UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Emitter")
// float EmitterMaxShootInterval{0};
};
/**
* Parameters for spawning bullets.
* 子弹生成参数。
*/
USTRUCT(BlueprintType)
struct GENERICCOMBATSYSTEM_API FGCS_BulletSpawnParameters
{
GENERATED_BODY()
/**
* The owner of the bullet.
* 子弹的拥有者。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GCS")
TObjectPtr<AActor> Owner{nullptr};
/**
* Handle to the bullet definition.
* 子弹定义的句柄。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GCS", meta=(RowType="/Script/GenericCombatSystem.GCS_BulletDefinition"))
FDataTableRowHandle DefinitionHandle;
/**
* Transform for spawning the bullet.
* 子弹生成时的变换。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GCS")
FTransform SpawnTransform{FTransform::Identity};
/**
* The associated attack request.
* 关联的攻击请求。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GCS")
TObjectPtr<const UGCS_AttackRequest_Bullet> Request{nullptr};
/**
* Whether the bullet is locally predicted.
* 子弹是否为本地预测。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GCS")
bool bIsLocalPredicting{false};
/**
* IDs for locally predicted bullets.
* 本地预测子弹的ID。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GCS", meta=(DisplayName="Local Predicting Bullet Ids"))
TArray<FGuid> OverrideBulletIds;
/**
* ID of the parent bullet (for bullet chains).
* 父子弹的ID用于子弹链
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GCS")
FGuid ParentId;
/**
* Returns a debug string representation.
* 返回调试字符串表示。
* @return The debug string. 调试字符串。
*/
FString ToDebugString() const;
};

View File

@@ -0,0 +1,101 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GCS_BulletStructLibrary.h"
#include "Subsystems/WorldSubsystem.h"
#include "GCS_BulletSubsystem.generated.h"
class UGCS_AttackRequest_Bullet;
class AGCS_BulletInstance;
/**
* Subsystem for managing bullet spawning and lifecycle.
* 管理子弹生成和生命周期的子系统。
*/
UCLASS()
class GENERICCOMBATSYSTEM_API UGCS_BulletSubsystem : public UWorldSubsystem
{
GENERATED_BODY()
public:
static UGCS_BulletSubsystem* Get(const UWorld* World);
/**
* Spawns bullets based on the provided parameters.
* 根据提供的参数生成子弹。
* @param SpawnParameters The spawn parameters. 生成参数。
* @return The spawned bullet instances. 生成的子弹实例。
*/
UFUNCTION(BlueprintCallable, Category="GCS|Bullet")
virtual TArray<AGCS_BulletInstance*> SpawnBullets(const FGCS_BulletSpawnParameters& SpawnParameters);
/**
* Gets the IDs of the provided bullet instances.
* 获取提供的子弹实例的ID。
* @param Instances The bullet instances. 子弹实例。
* @return The IDs of the bullets. 子弹的ID。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GCS|Bullet")
virtual TArray<FGuid> GetIdsFromBullets(TArray<AGCS_BulletInstance*> Instances);
/**
* Gets or creates bullet instances based on parameters and definition.
* 根据参数和定义获取或创建子弹实例。
* @param SpawnParameters The spawn parameters. 生成参数。
* @param Definition The bullet definition. 子弹定义。
* @return The bullet instances. 子弹实例。
*/
TArray<AGCS_BulletInstance*> GetOrCreateBulletInstances(const FGCS_BulletSpawnParameters& SpawnParameters, const FGCS_BulletDefinition& Definition);
/**
* Retrieves a bullet instance from the pool.
* 从池中获取子弹实例。
* @param BulletClass The class of the bullet. 子弹的类。
* @return The bullet instance. 子弹实例。
*/
AGCS_BulletInstance* TakeBulletFromPool(TSubclassOf<AGCS_BulletInstance> BulletClass);
/**
* Destroys a bullet by its ID.
* 根据ID销毁子弹。
* @param BulletId The bullet ID. 子弹ID。
*/
UFUNCTION(BlueprintCallable, Category="GCS|Bullet")
virtual void DestroyBullet(FGuid BulletId);
/**
* Creates a single bullet instance.
* 创建单个子弹实例。
* @param SpawnParameters The spawn parameters. 生成参数。
* @param Definition The bullet definition. 子弹定义。
* @return The created bullet instance. 创建的子弹实例。
*/
AGCS_BulletInstance* CreateBulletInstance(const FGCS_BulletSpawnParameters& SpawnParameters, const FGCS_BulletDefinition& Definition);
/**
* Loads a bullet definition from a handle.
* 从句柄加载子弹定义。
* @param Handle The bullet definition handle. 子弹定义句柄。
* @param OutDefinition The loaded definition (output). 加载的定义(输出)。
* @return True if the definition was loaded successfully. 如果定义加载成功返回true。
*/
UFUNCTION(BlueprintCallable, BlueprintPure=false, Category="GCS|Bullet", meta=(ExpandBoolAsExecs="ReturnValue"))
virtual bool LoadBulletDefinition(const FDataTableRowHandle& Handle, FGCS_BulletDefinition& OutDefinition);
/**
* Active bullet instances mapped by their IDs.
* 按ID映射的激活子弹实例。
*/
UPROPERTY()
TMap<FGuid, TObjectPtr<AGCS_BulletInstance>> BulletInstances;
/**
* Pool of bullet instances for reuse.
* 用于重用的子弹实例池。
*/
UPROPERTY()
TArray<TObjectPtr<AGCS_BulletInstance>> BulletPools;
};

View File

@@ -0,0 +1,51 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GCS_BulletStructLibrary.h"
#include "Components/ActorComponent.h"
#include "GCS_BulletSystemComponent.generated.h"
/**
* @note WIP
*/
UCLASS(Abstract, ClassGroup=(GCS), meta=(BlueprintSpawnableComponent))
class GENERICCOMBATSYSTEM_API UGCS_BulletSystemComponent : public UActorComponent
{
GENERATED_BODY()
public:
// Sets default values for this component's properties
UGCS_BulletSystemComponent();
protected:
// Called when the game starts
virtual void BeginPlay() override;
public:
/**
* Gets the bullet system component from an actor.
* 从Actor获取子弹系统组件。
* @param Actor The actor to query. 要查询的Actor。
* @return The bullet system component. 子弹系统组件。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category = "GCS|BulletSystem", Meta = (DefaultToSelf="Actor"))
static UGCS_BulletSystemComponent* GetBulletSystemComponent(const AActor* Actor);
/**
* Finds the bullet system component on an actor.
* 在Actor上查找子弹系统组件。
* @param Actor The actor to query. 要查询的Actor。
* @param Component The found component (output). 找到的组件(输出)。
* @return True if found. 如果找到返回true。
*/
UFUNCTION(BlueprintCallable, Category = "GCS|BulletSystem", Meta = (DefaultToSelf="Actor", ExpandBoolAsExecs="ReturnValue"))
static bool FindBulletSystemComponent(const AActor* Actor, UGCS_BulletSystemComponent*& Component);
UFUNCTION(BlueprintCallable, BlueprintPure, Category = "GCS|BulletSystem")
void SpawnBullet(const FGCS_BulletSpawnParameters& SpawnParameters);
// virtual TArray<AGCS_BulletInstance*> SpawnBulletInternal(const FGCS_BulletSpawnParameters& SpawnParameters);
};

View File

@@ -0,0 +1,55 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GCS_BulletInstance.h"
#include "GCS_SphereBulletInstance.generated.h"
class USphereComponent;
/**
* Bullet instance with a spherical collision shape.
* 具有球形碰撞形状的子弹实例。
*/
UCLASS(Abstract, Blueprintable)
class GENERICCOMBATSYSTEM_API AGCS_SphereBulletInstance : public AGCS_BulletInstance
{
GENERATED_BODY()
public:
/**
* Default constructor.
* 默认构造函数。
*/
AGCS_SphereBulletInstance();
/**
* Gets the bullet's shape component.
* 获取子弹的形状组件。
* @return The sphere component. 球形组件。
*/
virtual UShapeComponent* GetBulletShape_Implementation() const override;
protected:
/**
* Called when the game starts or when spawned.
* 游戏开始或生成时调用。
*/
virtual void BeginPlay() override;
/**
* The sphere component for collision detection.
* 用于碰撞检测的球形组件。
*/
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="GCS")
TObjectPtr<USphereComponent> Sphere;
public:
/**
* Called every frame.
* 每帧调用。
* @param DeltaTime Time since last frame. 上一帧以来的时间。
*/
virtual void Tick(float DeltaTime) override;
};

View File

@@ -0,0 +1,205 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GameplayTagContainer.h"
#include "GCS_TraceDelegates.h"
#include "GCS_ActorOwnedObject.h"
#include "GCS_TraceSystemComponent.h"
#include "Abilities/GameplayAbilityTypes.h"
#include "DEPRECATED_GCS_CollisionTraceInstance.generated.h"
class UPrimitiveComponent;
class UGCS_AttackRequest_Base;
class UTargetingPreset;
class UGCS_AttackRequest_Melee;
class UGCS_TraceSystemComponent;
/**
* Object for managing collision trace instances.
* 管理碰撞检测实例的对象。
*/
UCLASS(Blueprintable, AutoExpandCategories = ("GCS"), Deprecated, meta=(DeprecationMessage="CollisionTraceInstance is nolonger required since GCS 1.5!"))
class GENERICCOMBATSYSTEM_API UDEPRECATED_GCS_CollisionTraceInstance : public UGCS_ActorOwnedObject
{
GENERATED_BODY()
friend UGCS_TraceSystemComponent;
public:
/**
* Gameplay tag for the trace instance.
* 碰撞检测实例的游戏标签。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "GCS|Trace Settings", meta=(ExposeOnSpawn))
FGameplayTag TraceGameplayTag;
/**
* The primitive component used for tracing.
* 用于追踪的原始组件。
*/
UPROPERTY(BlueprintReadWrite, Category = "GCS|Trace Settings", meta=(ExposeOnSpawn))
TObjectPtr<UPrimitiveComponent> TracePrimitiveComponent;
/**
* Socket names on the primitive component for tracing.
* 原始组件上用于追踪的插槽名称。
*/
UPROPERTY(BlueprintReadWrite, Category = "GCS|Trace Settings", meta=(ExposeOnSpawn))
TArray<FName> TracePrimitiveComponentSocketNames;
/**
* Targeting preset for fetching target actors.
* 用于获取目标Actor的目标预设。
*/
UPROPERTY(BlueprintReadWrite, EditAnywhere, Category="GCS|Trace Settings", meta=(ExposeOnSpawn))
TObjectPtr<UTargetingPreset> TargetingPreset;
/**
* The actor that created this trace instance.
* 创建此碰撞检测实例的Actor。
*/
UPROPERTY(BlueprintReadOnly, Category = "GCS|Trace Settings")
TObjectPtr<AActor> TraceOwner = nullptr;
/**
* Associated information for this trace.
* 此碰撞检测的关联信息。
*/
UPROPERTY(VisibleAnywhere, Transient, Category = "GCS|Trace State")
FGameplayEventData TraceInformation;
/**
* Delegate for trace hit events.
* 碰撞检测命中事件的委托。
*/
UPROPERTY(BlueprintAssignable, BlueprintCallable)
FGCS_OnTraceHitSignature OnHit;
/**
* Delegate for trace state change events.
* 碰撞检测状态更改事件的委托。
*/
UPROPERTY(BlueprintAssignable, BlueprintCallable)
FGCS_OnTraceStateChangedSignature OnTraceStateChangedEvent;
/**
* The active duration of the trace instance.
* 碰撞检测实例的激活时间。
*/
UPROPERTY(BlueprintReadOnly, Category="GCS|Trace State")
float ActiveTime{0.0f};
/**
* Broadcasts a hit event.
* 广播命中事件。
* @param HitResult The hit result. 命中结果。
*/
UFUNCTION(BlueprintCallable, Category="GCS|Trace")
void BroadcastHit(const FHitResult& HitResult);
/**
* Broadcasts a state change event.
* 广播状态更改事件。
* @param bNewState The new state. 新状态。
*/
void BroadcastStateChanged(bool bNewState);
protected:
/**
* Initializes the trace instance.
* 初始化碰撞检测实例。
*/
UFUNCTION(BlueprintNativeEvent, Category = "GCS|Trace", meta=(BlueprintProtected))
void OnTraceBeginPlay();
virtual void OnTraceBeginPlay_Implementation();
/**
* Cleans up the trace instance.
* 清理碰撞检测实例。
* @note The instance is returned to the cache pool instead of being destroyed.
* @注意 实例被返回到缓存池而不是销毁。
*/
UFUNCTION(BlueprintNativeEvent, Category = "GCS|Trace", meta=(BlueprintProtected))
void OnTraceEndPlay();
virtual void OnTraceEndPlay_Implementation();
/**
* Handles trace ticking.
* 处理碰撞检测的tick。
* @param DeltaSeconds Time since last frame. 上一帧以来的时间。
*/
UFUNCTION(BlueprintNativeEvent, Category = "GCS|Trace", meta=(BlueprintProtected))
void OnTraceTick(float DeltaSeconds);
virtual void OnTraceTick_Implementation(float DeltaSeconds);
/**
* Handles trace state changes.
* 处理碰撞检测状态更改。
* @param bNewState The new state. 新状态。
*/
UFUNCTION(BlueprintNativeEvent, Category = "GCS|Trace", meta=(BlueprintProtected))
void OnTraceStateChanged(bool bNewState);
virtual void OnTraceStateChanged_Implementation(bool bNewState);
/**
* Actors hit during the active duration.
* 激活期间命中的Actor。
*/
UPROPERTY(BlueprintReadWrite, EditDefaultsOnly, Category="GCS|Trace State", AdvancedDisplay)
TArray<TObjectPtr<AActor>> HitActors;
public:
/**
* Sets the trace mesh information.
* 设置碰撞检测网格信息。
* @param NewPrimitiveComponent The new primitive component. 新原始组件。
* @param PrimitiveComponentSocketNames The socket names. 插槽名称。
*/
UFUNCTION(BlueprintCallable, Category = "GCS|Trace")
void SetTraceMeshInfo(UPrimitiveComponent* NewPrimitiveComponent, TArray<FName> PrimitiveComponentSocketNames);
/**
* Checks if an actor can be hit.
* 检查是否可以命中Actor。
* @param ActorToCheck The actor to check. 要检查的Actor。
* @return True if the actor can be hit. 如果可以命中返回true。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, BlueprintNativeEvent, Category="GCS|Trace")
bool CanHitActor(const AActor* ActorToCheck) const;
bool CanHitActor_Implementation(const AActor* ActorToCheck) const;
/**
* Gets the source actor for the trace.
* 获取碰撞检测的源Actor。
* @return The source actor (e.g., weapon, bullet, or trace owner). 源Actor例如武器、子弹或TraceOwner
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category = "GCS|Trace")
AActor* GetTraceSourceActor() const;
/**
* Toggles the trace state.
* 切换碰撞检测状态。
* @param bNewState The new state (active traces tick and attempt to hit). 新状态激活的追踪会tick并尝试命中
*/
UFUNCTION(BlueprintCallable, Category = "GCS|Trace")
void ToggleTraceState(bool bNewState);
/**
* Indicates if the trace is active.
* 表示碰撞检测是否激活。
*/
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "GCS|Trace")
bool bTraceActive{false};
protected:
/**
* Handles trace hit events.
* 处理碰撞检测命中事件。
* @param HitResult The hit result. 命中结果。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category = "GCS|Trace", meta=(BlueprintProtected))
void OnTraceHit(const FHitResult& HitResult);
virtual void OnTraceHit_Implementation(const FHitResult& HitResult);
};

View File

@@ -0,0 +1,115 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GCS_TraceStructLibrary.h"
#include "Engine/CancellableAsyncAction.h"
#include "GCS_AsyncAction_CollisionTrace.generated.h"
class UGCS_TraceSystemComponent;
/**
* Async action for setting up and listening to collision trace hits.
* 设置并监听碰撞检测命中的异步动作。
*/
UCLASS()
class GENERICCOMBATSYSTEM_API UGCS_AsyncAction_CollisionTrace : public UCancellableAsyncAction
{
GENERATED_BODY()
public:
/**
* Creates and activates trace instances from definitions and listens for hits.
* 从定义创建并激活碰撞检测实例并监听命中。
* @param TraceSystem The collision trace system component. 碰撞检测系统组件。
* @param TraceDefinitions The traces definitions will be created and added to collision trace system. 要新建的碰撞实例的定义。
* @param PrimitiveComponent The primitive component for tracing. 用于追踪的原始组件。
* @param OptionalSourceObject The optional source object. 可选的源对象.
* @return The async action instance. 异步动作实例。
*/
UFUNCTION(BlueprintCallable, BlueprintCosmetic, Category="GUIS", meta = (WorldContext = "WorldContextObject", BlueprintInternalUseOnly = "true"))
static UGCS_AsyncAction_CollisionTrace* SetupAndListenForCollisionTraceHit(UGCS_TraceSystemComponent* TraceSystem, const TArray<FGCS_TraceDefinition>& TraceDefinitions,
UPrimitiveComponent* PrimitiveComponent, UObject* OptionalSourceObject = nullptr);
/**
* Activates the async action.
* 激活异步动作。
*/
virtual void Activate() override;
/**
* Cancels the async action.
* 取消异步动作。
*/
virtual void Cancel() override;
/**
* Delegate for collision trace hit events.
* 碰撞检测命中事件的委托。
*/
DECLARE_DYNAMIC_MULTICAST_DELEGATE_TwoParams(FCollisionTraceSignature, const FGCS_TraceHandle, Handle, const FHitResult&, HitResult);
/**
* Called before trace instances are activated.
* 在激活碰撞检测实例前调用。
*/
/**
* Called before trace instances are activated.
* 在激活碰撞检测实例前调用。
*/
UPROPERTY(BlueprintAssignable)
FCollisionTraceSignature BeforeActive;
/**
* Fired when a trace instance hits something.
* 当碰撞检测实例命中某物时触发。
*/
UPROPERTY(BlueprintAssignable)
FCollisionTraceSignature OnHit;
protected:
/**
* Handles trace instance hit events.
* 处理碰撞检测实例命中事件。
* @param TraceHandle The trace instance. 碰撞检测实例。
* @param HitResult The hit result. 命中结果。
*/
UFUNCTION()
void TraceHitCallback(const FGCS_TraceHandle& TraceHandle, const FHitResult& HitResult);
/**
* The collision system component.
* 碰撞系统组件。
*/
UPROPERTY()
TWeakObjectPtr<UGCS_TraceSystemComponent> TraceSystem;
/**
* The primitive component for tracing.
* 用于追踪的原始组件。
*/
UPROPERTY()
TWeakObjectPtr<UPrimitiveComponent> SourceComponent;
/**
* The optional source object.
* 可选的源对象。
*/
UPROPERTY()
TWeakObjectPtr<UObject> SourceObject;
/**
* The trace definitions to create.
* 要创建的碰撞检测定义。
*/
UPROPERTY()
TArray<FGCS_TraceDefinition> TraceDefinitions;
/**
* The monitored trace instances.
* 监听的碰撞检测实例。
*/
UPROPERTY()
TArray<FGCS_TraceHandle> TraceHandles;
};

View File

@@ -0,0 +1,24 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GCS_TraceStructLibrary.h"
#include "UObject/Object.h"
#include "GCS_TraceDelegates.generated.h"
/**
* Delegate for trace instance hit events.
* 碰撞检测实例命中事件的委托。
*/
UDELEGATE()
DECLARE_DYNAMIC_MULTICAST_DELEGATE_TwoParams(FGCS_OnTraceHitSignature, const FGCS_TraceHandle&, TraceHandle, const FHitResult&, HitResult);
UDELEGATE()
DECLARE_DYNAMIC_MULTICAST_DELEGATE_TwoParams(FGCS_OnTraceStateChangedSignature, const FGCS_TraceHandle&, TraceHandle, bool, bNewState);
UDELEGATE()
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FGCS_OnTraceStartedSignature, const FGCS_TraceHandle&, TraceHandle);
UDELEGATE()
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FGCS_OnTraceStoppedSignature, const FGCS_TraceHandle&, TraceHandle);

View File

@@ -0,0 +1,40 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "UObject/Object.h"
#include "GCS_TraceEnumLibrary.generated.h"
UENUM()
enum class EGCS_CollisionShapeType : uint8
{
Sphere,
Box,
Capsule
};
UENUM()
enum class EGCS_TraceSweepType : uint8
{
ByChannel,
ByObject,
ByProfile
};
UENUM()
enum class EGCS_TraceTickType : uint8
{
Default,
FixedFrameRate,
DistanceBased
};
UENUM()
enum class EGCS_TraceExecutionState : uint8
{
InProgress,
Stopped,
PendingStop
};

View File

@@ -0,0 +1,29 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GCS_TraceStructLibrary.h"
#include "Kismet/BlueprintFunctionLibrary.h"
#include "GCS_TraceFunctionLibrary.generated.h"
/**
* Blueprint function library for trace system utilities.
* 碰撞检测系统工具的蓝图函数库。
*/
UCLASS()
class GENERICCOMBATSYSTEM_API UGCS_TraceFunctionLibrary : public UBlueprintFunctionLibrary
{
GENERATED_BODY()
public:
/**
* Filter definitions with trace tag matches TagToMatch.
* 筛选与指定标签匹配的碰撞检测定义。
* @param Definitions The definitions to filter. 要筛选的定义。
* @param TagToMatch The tag to check. 要检查的标签。
* @return Matching definitions. 匹配的定义。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category = "GCS|TraceSystem|Utilities", Meta = (DefaultToSelf="Actor"))
static TArray<FGCS_TraceDefinition> FilterTraceDefinitionsByTag(const TArray<FGCS_TraceDefinition>& Definitions, const FGameplayTag& TagToMatch);
};

View File

@@ -0,0 +1,469 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GameplayTagContainer.h"
#include "CollisionShape.h"
#include "CollisionQueryParams.h"
#include "Collision/GCS_TraceEnumLibrary.h"
#include "Engine/DataTable.h"
#include "StructUtils/InstancedStruct.h"
#include "UObject/Object.h"
#include "GCS_TraceStructLibrary.generated.h"
class UTargetingPreset;
class UGCS_TraceSystemComponent;
USTRUCT(BlueprintType)
struct FGCS_TraceSweepSetting
{
GENERATED_BODY()
/**
* The type of sweep to perform for collision detection.
* 执行碰撞检测的扫描类型。
*/
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "GCS")
EGCS_TraceSweepType SweepType = EGCS_TraceSweepType::ByChannel;
/**
* The collision channel to use for channel-based sweeping.
* 用于基于通道扫描的碰撞通道。
*/
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "GCS",
meta = (EditCondition = "SweepType == EGCS_TraceSweepType::ByChannel", EditConditionHides))
TEnumAsByte<ECollisionChannel> TraceChannel = ECC_Visibility;
/**
* The object types to use for object-based sweeping.
* 用于基于对象扫描的对象类型。
*/
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "GCS",
meta = (EditCondition = "SweepType == EGCS_TraceSweepType::ByObject", EditConditionHides))
TArray<TEnumAsByte<ECollisionChannel>> ObjectTypes;
/**
* The collision profile name to use for profile-based sweeping.
* 用于基于配置扫描的碰撞配置名称。
*/
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "GCS",
meta = (EditCondition = "SweepType == EGCS_TraceSweepType::ByProfile", EditConditionHides))
FName ProfileName = NAME_None;
/**
* Whether to trace against complex collision.
* 是否对复杂碰撞进行追踪。
*/
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "GCS")
bool bTraceComplex = false;
};
/**
* Build collision shape by static parameters
* 通过静态参数构建碰撞形状。
* 在SourceComponent空间内的静态形状。
*/
USTRUCT(meta = (Hidden, DisplayName = "Collision Shape"))
struct GENERICCOMBATSYSTEM_API FGCS_CollisionShape
{
GENERATED_BODY()
virtual ~FGCS_CollisionShape() = default;
virtual bool InitializeShape(const UPrimitiveComponent* SourceComponent);
virtual FTransform GetTransform(const UPrimitiveComponent* SourceComponent, const float& Time) const;
virtual FCollisionShape GetDynamicCollisionShape(const UPrimitiveComponent* SourceComponent, const float& Time) const;
};
/**
* Build collision shape by static parameters
* 通过静态参数构建碰撞形状。
* 在SourceComponent空间内的静态形状。
*/
USTRUCT(meta = (DisplayName = "Collision Shape (Static)"))
struct GENERICCOMBATSYSTEM_API FGCS_CollisionShape_Static : public FGCS_CollisionShape
{
GENERATED_BODY()
/**
* The type of collision shape to use.
* 要使用的碰撞形状类型。
*/
UPROPERTY(EditAnywhere, Category = "GCS")
EGCS_CollisionShapeType ShapeType = EGCS_CollisionShapeType::Sphere;
/**
* The orientation/rotation of the collision shape.
* 碰撞形状的方向/旋转。
*/
UPROPERTY(EditAnywhere, Category = "GCS",
meta = (EditCondition = "ShapeType != EGCS_CollisionShapeType::Sphere", EditConditionHides))
FRotator Orientation = FRotator::ZeroRotator;
/**
* The position offset of the collision shape.
* 碰撞形状的位置偏移。
*/
UPROPERTY(EditAnywhere, Category = "GCS")
FVector Offset = FVector::ZeroVector;
/**
* The radius of the sphere or capsule.
* 球体或胶囊体的半径。
*/
UPROPERTY(EditAnywhere, Category = "GCS",
meta = (EditCondition = "ShapeType != EGCS_CollisionShapeType::Box", EditConditionHides))
float Radius = 10.f;
/**
* The half height of the capsule.
* 胶囊体的半高。
*/
UPROPERTY(EditAnywhere, Category = "GCS",
meta = (EditCondition = "ShapeType == EGCS_CollisionShapeType::Capsule", EditConditionHides))
float HalfHeight = 10.f;
/**
* The half size of the box.
* 盒子的半尺寸。
*/
UPROPERTY(EditAnywhere, Category = "GCS",
meta = (EditCondition = "ShapeType == EGCS_CollisionShapeType::Box", EditConditionHides))
FVector HalfSize = FVector(10.f, 10.f, 10.f);
virtual bool InitializeShape(const UPrimitiveComponent* SourceComponent) override;
virtual FTransform GetTransform(const UPrimitiveComponent* SourceComponent, const float& Time) const override;
virtual FCollisionShape GetDynamicCollisionShape(const UPrimitiveComponent* SourceComponent, const float& Time) const override;
};
/**
* Build dynamic collision shape by binding to shape component(Box/Sphere/Capsule).
* 通过绑定Shape组件(Box/Sphere/Capsule)构建动态碰撞形状。
* 在SourceComponent空间内的与SourceComponent进行匹配的形状。
*/
USTRUCT(meta = (DisplayName = "Collision Shape (Shape Based)"))
struct GENERICCOMBATSYSTEM_API FGCS_CollisionShape_ShapeBased : public FGCS_CollisionShape
{
GENERATED_BODY()
/**
* The type of collision shape to use.
* 要使用的碰撞形状类型。
*/
UPROPERTY(EditAnywhere, Category = "GCS")
EGCS_CollisionShapeType ShapeType = EGCS_CollisionShapeType::Sphere;
/**
* The orientation/rotation of the collision shape.
* 碰撞形状的方向/旋转。
*/
UPROPERTY(EditAnywhere, Category = "GCS",
meta = (EditCondition = "ShapeType != EGCS_CollisionShapeType::Sphere", EditConditionHides))
FRotator Orientation = FRotator::ZeroRotator;
UPROPERTY(EditAnywhere, Category = "GCS")
FVector Offset = FVector::ZeroVector;
UPROPERTY()
float Radius = 10.f;
UPROPERTY()
float HalfHeight = 10.f;
UPROPERTY()
FVector HalfSize = FVector(10.f, 10.f, 10.f);
virtual bool InitializeShape(const UPrimitiveComponent* SourceComponent) override;
virtual FTransform GetTransform(const UPrimitiveComponent* SourceComponent, const float& Time) const override;
virtual FCollisionShape GetDynamicCollisionShape(const UPrimitiveComponent* SourceComponent, const float& Time) const override;
};
/**
* 在SourceComponent空间内跟随SourceComponent的某Socket/Bone运动的形状。
*/
USTRUCT(meta = (DisplayName = "Collision Shape (Attached)"))
struct GENERICCOMBATSYSTEM_API FGCS_CollisionShape_Attached : public FGCS_CollisionShape_Static
{
GENERATED_BODY()
/**
* Name of the socket or bone the shape will be attached to.
* 形状将附加到的插槽或骨骼的名称。
*/
UPROPERTY(EditAnywhere, Category="GCS")
FName SocketOrBoneName;
virtual bool InitializeShape(const UPrimitiveComponent* SourceComponent) override;
virtual FTransform GetTransform(const UPrimitiveComponent* SourceComponent, const float& Time) const override;
};
/**
* Build dynamic capsule collision shape by mesh's sockets.
* 通过网格的指定Sockets构建动态碰撞形状。
*/
USTRUCT(meta = (DisplayName = "Collision Shape (Socket Based)"))
struct GENERICCOMBATSYSTEM_API FGCS_CollisionShape_SocketBased : public FGCS_CollisionShape
{
GENERATED_BODY()
/**
* The name of the starting socket on the mesh.
* 网格上起始插槽的名称。
*/
UPROPERTY(EditAnywhere, Category = "GCS")
FName MeshSocketStart = TEXT("TrailStart");
/**
* The name of the ending socket on the mesh.
* 网格上结束插槽的名称。
*/
UPROPERTY(EditAnywhere, Category = "GCS")
FName MeshSocketEnd = TEXT("TrailEnd");
/**
* Additional length offset for the socket-based shape.
* 基于插槽的形状的额外长度偏移。
*/
UPROPERTY(EditAnywhere, Category = "GCS")
float MeshSocketLengthOffset = 0;
/**
* The radius of the capsule.
* 胶囊体的半径。
*/
UPROPERTY(EditAnywhere, Category = "GCS")
float Radius = 10.f;
/**
* The orientation/rotation of the collision shape.
* 碰撞形状的方向/旋转。
*/
UPROPERTY()
FRotator Orientation = FRotator::ZeroRotator;
/**
* The position offset of the collision shape.
* 碰撞形状的位置偏移。
*/
UPROPERTY()
FVector Offset = FVector::ZeroVector;
/**
* The half height of the capsule.
* 胶囊体的半高。
*/
UPROPERTY()
float HalfHeight = 10.f;
virtual FTransform GetTransform(const UPrimitiveComponent* SourceComponent, const float& Time) const override;
virtual bool InitializeShape(const UPrimitiveComponent* SourceComponent) override;
virtual FCollisionShape GetDynamicCollisionShape(const UPrimitiveComponent* SourceComponent, const float& Time) const override;
};
/**
* Structure for defining collision trace instances.
* 定义碰撞检测实例的结构。
*/
USTRUCT(BlueprintType)
struct GENERICCOMBATSYSTEM_API FGCS_TraceDefinition : public FTableRowBase
{
GENERATED_BODY()
FGCS_TraceDefinition();
/**
* Tag used as Trace identifier.
* 此Trace的Tag标识。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Trace Settings", meta=(Categories="GGF.Combat.Trace"))
FGameplayTag TraceTag;
/**
* Defines the shape used for detecting hit results.
* 定义用于获取命中结果的形状。
*/
UPROPERTY(EditAnywhere, Category = "Trace Settings", meta=(ExcludeBaseStruct, BaseStruct = "/Script/GenericCombatSystem.GCS_CollisionShape"))
FInstancedStruct CollisionShape{FInstancedStruct::Make(FGCS_CollisionShape_Static())};
/**
* Settings for the sweep operation.
* 扫描操作的设置。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Trace Settings")
FGCS_TraceSweepSetting SweepSetting;
/**
* The type of tick policy to use for this trace.
* 此Trace使用的tick策略类型。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Trace Settings")
EGCS_TraceTickType TraceTickType{EGCS_TraceTickType::FixedFrameRate};
/**
* The fixed frame rate for ticking when using FixedFrameRate policy.
* 使用固定帧率策略时的固定帧率。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Trace Settings",
meta = (EditCondition = "TraceTickType == EGCS_TraceTickType::FixedFrameRate", EditConditionHides))
int32 FixedTickFrameRate = 30;
/**
* The distance threshold for ticking when using DistanceBased policy.
* 使用基于距离策略时的距离阈值。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Trace Settings",
meta = (EditCondition = "TraceTickType == EGCS_TraceTickType::DistanceBased", EditConditionHides))
int32 DistanceTickThreshold = 30;
/**
* The angle threshold for ticking when using DistanceBased policy (in degrees).
* 使用基于距离策略时的角度阈值(度)。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Trace Settings",
meta = (EditCondition = "TraceTickType == EGCS_TraceTickType::DistanceBased", EditConditionHides))
float AngleTickThreshold = 15.0f; // Degrees
bool IsValidDefinition() const;
FString ToString() const;
};
/**
* Simple struct used for trace query.
*/
USTRUCT(BlueprintType)
struct GENERICCOMBATSYSTEM_API FGCS_TraceHandle
{
GENERATED_BODY()
/**
* The gameplay tag identifying this trace.
* 标识此Trace的游戏标签。
*/
UPROPERTY(BlueprintReadOnly, Category = "GCS")
FGameplayTag TraceTag;
/**
* The unique GUID for this trace instance.
* 此Trace实例的唯一GUID。
*/
UPROPERTY(BlueprintReadOnly, Category = "GCS")
FGuid Guid;
/**
* The source object that created this trace.
* 创建此Trace的源对象。
*/
UPROPERTY(BlueprintReadOnly, Category = "GCS")
TWeakObjectPtr<UObject> SourceObject;
bool IsValidHandle() const;
// Equality operator
friend bool operator==(const FGCS_TraceHandle& A, const FGCS_TraceHandle& B)
{
return A.TraceTag == B.TraceTag &&
A.Guid == B.Guid &&
A.SourceObject == B.SourceObject;
}
// Inequality operator
friend bool operator!=(const FGCS_TraceHandle& A, const FGCS_TraceHandle& B)
{
return !(A == B);
}
// Hash function for TMap/TSet
friend uint32 GetTypeHash(const FGCS_TraceHandle& Handle)
{
uint32 Hash = GetTypeHash(Handle.TraceTag);
Hash = HashCombine(Hash, GetTypeHash(Handle.Guid));
Hash = HashCombine(Hash, GetTypeHash(Handle.SourceObject));
return Hash;
}
FString ToDebugString() const
{
FString TagName = TraceTag.ToString();
if (TraceTag.IsValid())
{
TArray<FString> TagNames;
TraceTag.ToString().ParseIntoArray(TagNames,TEXT("."));
if (TagNames.Num() > 0)
{
TagName = TagNames.Last();
}
}
return FString::Printf(TEXT("%s;%s"), *TagName, SourceObject.IsValid() ? *GetNameSafe(SourceObject.Get()) : TEXT("None"));
}
};
// 补帧数据.
struct FGCS_TraceSubTick
{
FTransform StartTransform;
FTransform EndTransform;
FTransform AverageTransform;
};
USTRUCT(BlueprintType)
struct FGCS_TraceState
{
GENERATED_BODY()
void ChangeExecutionState(bool bNewTraceState, bool bStopImmediate = true);
void UpdatePreviousTransform(const FTransform& Transform);
// Get the world space transform of this trace.
FTransform GetCurrentTransform() const;
// Begin Runtime references
UPROPERTY()
UWorld* World{nullptr};
UPROPERTY()
TObjectPtr<UPrimitiveComponent> SourceComponent{nullptr};
UPROPERTY()
TObjectPtr<UGCS_TraceSystemComponent> OwningSystem{nullptr};
// End Runtime references
// Begin Static Data
FGCS_TraceSweepSetting SweepSetting;
// End Static Data
// Begin runtime data
FGCS_TraceHandle Handle;
bool IsPendingRemoval = false;
// The modified dynamic shape.
FInstancedStruct Shape;
TArray<FTransform, TFixedAllocator<2>> TransformsOverTime;
EGCS_TraceExecutionState ExecutionState = EGCS_TraceExecutionState::Stopped;
FCollisionShape CollisionShapeOverTime;
TArray<FGCS_TraceSubTick> SubTicks;
EGCS_TraceTickType TickPolicy;
float TickInterval = 1 / 30;
float AngleThreshold = 15.0f; // Degrees
bool bShouldTickThisFrame = false;
float TimeSinceLastTick = 0;
// how long this state active?
//
float TimeSinceActive = 0;
int32 TotalTickNumDuringExecution = 0;
TArray<TObjectPtr<AActor>> HitActors;
FCollisionQueryParams CollisionParams;
FCollisionResponseParams ResponseParams;
FCollisionObjectQueryParams ObjectQueryParams;
// End runtime data
};

View File

@@ -0,0 +1,60 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GCS_TraceStructLibrary.h"
#include "DrawDebugHelpers.h"
#include "WorldCollision.h"
#include "Kismet/KismetSystemLibrary.h"
#include "Subsystems/WorldSubsystem.h"
#include "GCS_TraceSubsystem.generated.h"
UCLASS()
class GENERICCOMBATSYSTEM_API UGCS_TraceSubsystem : public UTickableWorldSubsystem
{
GENERATED_BODY()
public:
virtual void Initialize(FSubsystemCollectionBase& Collection) override;
virtual void Tick(float DeltaTime) override;
virtual bool IsTickable() const override { return true; }
virtual TStatId GetStatId() const override { return TStatId(); }
FCriticalSection CriticalSection;
bool IsValidStateIdx(int32 StateIdx) const;
FGCS_TraceState& GetTraceStateAt(int Index);
int32 AddTraceState();
void RemoveTraceState(int Idx, FGuid Guid);
protected:
TArray<FGCS_TraceState> TraceStates;
bool RemovalLock = false;
uint32 TickIdx = 0;
void RemoveTraceStateAt(int Idx, FGuid Guid);
void PreTraceTick(const float DeltaTime);
void PostTraceTick();
// 计算所有用于碰撞检测的必须数据。
virtual void PrepareSubTicks(const float DeltaTime);
virtual void PerformSubTicks(const float DeltaTime);
static void PerformAsyncTrace(const FTransform& StartTransform, const FTransform& EndTransform, const FTransform& AverageTransform, UWorld* World,
const FGCS_TraceSweepSetting& TraceSettings,
const FCollisionShape& CollisionShape, const FCollisionQueryParams& CollisionParams,
const FCollisionResponseParams& CollisionResponseParams,
const FCollisionObjectQueryParams& ObjectQueryParams, const FTraceDelegate* InDelegate = nullptr);
virtual void HandleTraceResults(const FTraceHandle& InTraceHandle, FTraceDatum& InTraceDatum, int32 TraceStateIdx, uint32 InTickIdx, float InShapeTime);
#if ENABLE_DRAW_DEBUG
static void DrawDebug(const FVector& Start, const FVector& End, const FQuat& Rot, TArray<FHitResult> Hits, const FCollisionShape& CollisionShape, const UWorld* World,
const EDrawDebugTrace::Type DrawDebugType, float DrawDebugTime, const FLinearColor& DrawDebugColor, const FLinearColor& DrawDebugHitColor);
#endif
// 新增用于批量移除的Pending列表避免边遍历边修改
TArray<TPair<int32, FGuid>> PendingRemovals;
};

View File

@@ -0,0 +1,312 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Components/ActorComponent.h"
#include "GameplayTagContainer.h"
#include "GCS_TraceDelegates.h"
#include "GCS_TraceStructLibrary.h"
#include "GCS_TraceSystemComponent.generated.h"
class UGCS_TraceSubsystem;
class UPrimitiveComponent;
DECLARE_DYNAMIC_MULTICAST_DELEGATE(FGCS_OnTraceSystemDestroyedSignature);
/**
* Component for managing collision trace instances.
* 管理碰撞检测实例的组件。
*/
UCLASS(ClassGroup=(GCS), meta=(BlueprintSpawnableComponent, PrioritizeCategories="GCS"), Blueprintable, HideCategories=(Sockets, Navigation, Tags, ComponentTick, ComponentReplication,
Cooking, AssetUserData, Replication))
class GENERICCOMBATSYSTEM_API UGCS_TraceSystemComponent : public UActorComponent
{
GENERATED_BODY()
friend UGCS_TraceSubsystem;
public:
/**
* Default constructor.
* 默认构造函数。
*/
UGCS_TraceSystemComponent(const FObjectInitializer& ObjectInitializer);
/**
* Gets the collision trace system component from an actor.
* 从Actor获取碰撞检测系统组件。
* @param Actor The actor to query. 要查询的Actor。
* @return The collision trace system component. 碰撞检测系统组件。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category = "GCS|TraceSystem", Meta = (DefaultToSelf="Actor"))
static UGCS_TraceSystemComponent* GetTraceSystemComponent(const AActor* Actor);
/**
* Finds the collision trace system component on an actor.
* 在Actor上查找碰撞检测系统组件。
* @param Actor The actor to query. 要查询的Actor。
* @param Component The found component (output). 找到的组件(输出)。
* @return True if found. 如果找到返回true。
*/
UFUNCTION(BlueprintCallable, Category = "GCS|TraceSystem", Meta = (DefaultToSelf="Actor", ExpandBoolAsExecs="ReturnValue"))
static bool FindTraceSystemComponent(const AActor* Actor, UGCS_TraceSystemComponent*& Component);
/**
* Initializes the collision trace system.
* 初始化碰撞检测系统。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category = "GCS|TraceSystem", meta=(DisplayName="Initialize Trace System"))
void OnInitialize();
virtual void OnInitialize_Implementation();
/**
* Deinitializes the collision trace system.
* 取消初始化碰撞检测系统。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category = "GCS|TraceSystem", meta=(DisplayName="Deinitialize Trace System"))
void OnDeinitialize();
virtual void OnDeinitialize_Implementation();
/**
* Creates trace instances from definitions.
* 从定义创建碰撞检测实例。
* @param Definitions The trace definitions. 碰撞检测定义。
* @param SourceComponent The primitive component for tracing. 用于追踪的原始组件。
* @param SourceObject The source object. 源对象。
* @return The created trace instances. 创建的碰撞检测实例。
*/
UFUNCTION(BlueprintCallable, Category = "GCS|TraceSystem")
TArray<FGCS_TraceHandle> AddTracesByDefinitions(const TArray<FGCS_TraceDefinition>& Definitions, UPrimitiveComponent* SourceComponent, UObject* SourceObject);
/**
* Creates trace instances from data table row handles.
* 从数据表行句柄创建碰撞检测实例。
* @param DefinitionHandles The data table row handles for trace definitions. 碰撞检测定义的数据表行句柄。
* @param SourceComponent The primitive component for tracing. 用于追踪的原始组件。
* @param SourceObject The source object. 源对象。
* @return The created trace instances. 创建的碰撞检测实例。
*/
UFUNCTION(BlueprintCallable, Category = "GCS|TraceSystem")
TArray<FGCS_TraceHandle> AddTracesByDefinitionHandles(UPARAM(meta=(RowType="/Script/GenericCombatSystem.GCS_CollisionTraceDefinition"))
const TArray<FDataTableRowHandle>& DefinitionHandles, UPrimitiveComponent* SourceComponent, UObject* SourceObject);
/**
* Creates a single trace instance from a definition.
* 从定义创建单个碰撞检测实例。
* @param Definition The trace definition. 碰撞检测定义。
* @param SourceComponent The primitive component for tracing. 用于追踪的原始组件。
* @param SourceObject The source object. 源对象。
* @return The created trace instance. 创建的碰撞检测实例。
*/
UFUNCTION(BlueprintCallable, Category = "GCS|TraceSystem")
FGCS_TraceHandle AddTraceByDefinition(const FGCS_TraceDefinition& Definition, UPrimitiveComponent* SourceComponent, UObject* SourceObject);
/**
* Starts traces by tags and source object.
* 通过标签和源对象启动碰撞检测。
* @param TraceTags The gameplay tags to match. 要匹配的游戏标签。
* @param SourceObject The source object. 源对象。
* @return The started trace instances. 启动的碰撞检测实例。
*/
UFUNCTION(BlueprintCallable, Category = "GCS|TraceSystem")
TArray<FGCS_TraceHandle> StartTracesByTagsAndSource(const FGameplayTagContainer& TraceTags, const UObject* SourceObject);
/**
* Starts multiple traces by their handles.
* 通过句柄启动多个碰撞检测。
* @param TraceHandles The trace handles to start. 要启动的碰撞检测句柄。
*/
UFUNCTION(BlueprintCallable, Category = "GCS|TraceSystem")
void StartTracesByHandles(const TArray<FGCS_TraceHandle>& TraceHandles);
/**
* Starts a single trace by its handle.
* 通过句柄启动单个碰撞检测。
* @param TraceHandle The trace handle to start. 要启动的碰撞检测句柄。
*/
UFUNCTION(BlueprintCallable, Category = "GCS|TraceSystem")
void StartTraceByHandle(const FGCS_TraceHandle& TraceHandle);
/**
* Stops multiple traces by their handles.
* 通过句柄停止多个碰撞检测。
* @param TraceHandles The trace handles to stop. 要停止的碰撞检测句柄。
*/
UFUNCTION(BlueprintCallable, Category = "GCS|TraceSystem")
void StopTracesByHandles(const TArray<FGCS_TraceHandle>& TraceHandles);
/**
* Stops a single trace by its handle.
* 通过句柄停止单个碰撞检测。
* @param TraceHandle The trace handle to stop. 要停止的碰撞检测句柄。
*/
UFUNCTION(BlueprintCallable, Category = "GCS|TraceSystem")
void StopTraceByHandle(const FGCS_TraceHandle& TraceHandle);
/**
* Removes a trace by its handle.
* 通过句柄移除碰撞检测。
* @param TraceHandle The trace handle to remove. 要移除的碰撞检测句柄。
*/
UFUNCTION(BlueprintCallable, Category = "GCS|TraceSystem")
void RemoveTraceByHandle(const FGCS_TraceHandle& TraceHandle);
/**
* Clears all active and cached trace instances.
* 清除所有激活和缓存的碰撞检测实例。
* @note OnTraceEndPlay event is not fired. OnTraceEndPlay事件不会触发。
*/
UFUNCTION(BlueprintCallable, Category = "GCS|TraceSystem")
void RemoveAllTraces();
/**
* Gets all trace handles with the specified tag.
* 获取具有指定标签的所有碰撞检测句柄。
* @param TraceToFind The gameplay tag to search for. 要搜索的游戏标签。
* @return Array of trace handles with the specified tag. 具有指定标签的碰撞检测句柄数组。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category = "GCS|TraceSystem")
TArray<FGCS_TraceHandle> GetTraceHandlesByTag(FGameplayTag TraceToFind) const;
/**
* Gets all trace handles created by the specified source object.
* 获取由指定源对象创建的所有碰撞检测句柄。
* @param SourceObject The source object to search for. 要搜索的源对象。
* @return Array of trace handles from the specified source. 来自指定源的碰撞检测句柄数组。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category = "GCS|TraceSystem")
TArray<FGCS_TraceHandle> GetTraceHandlesBySource(const UObject* SourceObject) const;
/**
* Gets all trace handles with the specified tags and source object.
* 获取具有指定标签和源对象的所有碰撞检测句柄。
* @param TraceTags The gameplay tags to match. 要匹配的游戏标签。
* @param SourceObject The source object to match. 要匹配的源对象。
* @return Array of trace handles matching the criteria. 匹配条件的碰撞检测句柄数组。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category = "GCS|TraceSystem")
TArray<FGCS_TraceHandle> GetTraceHandlesByTagsAndSource(const FGameplayTagContainer& TraceTags, const UObject* SourceObject) const;
/**
* Gets the source actor for the specified trace handle.
* 获取指定碰撞检测句柄的源Actor。
* @param TraceHandle The trace handle to query. 要查询的碰撞检测句柄。
* @return The source actor, or nullptr if not found. 源Actor如果未找到则返回nullptr。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category = "GCS|TraceSystem")
AActor* GetTraceSourceActor(const FGCS_TraceHandle& TraceHandle) const;
/**
* Gets the source component for the specified trace handle.
* 获取指定碰撞检测句柄的源组件。
* @param TraceHandle The trace handle to query. 要查询的碰撞检测句柄。
* @return The source component, or nullptr if not found. 源组件如果未找到则返回nullptr。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category = "GCS|TraceSystem")
UPrimitiveComponent* GetTraceSourceComponent(const FGCS_TraceHandle& TraceHandle) const;
/**
* Checks if the specified trace is currently active.
* 检查指定的碰撞检测当前是否激活。
* @param TraceHandle The trace handle to check. 要检查的碰撞检测句柄。
* @return True if the trace is active. 如果碰撞检测激活则返回true。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category = "GCS|TraceSystem")
bool IsTraceActive(const FGCS_TraceHandle& TraceHandle) const;
virtual TArray<FGCS_TraceHandle> StartTraces(const FGameplayTagContainer& TraceTags, const UObject* SourceObject);
virtual TArray<FGCS_TraceHandle> AddTraces(const TArray<FGCS_TraceDefinition>& Definitions, UPrimitiveComponent* SourceComponent, UObject* SourceObject);
virtual TArray<FGCS_TraceHandle> AddTraces(const TArray<FDataTableRowHandle>& DefinitionHandles, UPrimitiveComponent* SourceComponent, UObject* SourceObject);
virtual FGCS_TraceHandle AddTrace(const FGCS_TraceDefinition& TraceDefinition, UPrimitiveComponent* SourceComponent, UObject* SourceObject);
virtual FGCS_TraceHandle AddTrace(const FDataTableRowHandle& TraceDefinitionHandle, UPrimitiveComponent* SourceComponent, UObject* SourceObject);
virtual void StartTraces(const TArray<FGCS_TraceHandle>& TraceHandles);
virtual void StartTrace(const FGCS_TraceHandle& TraceHandle);
virtual void StopTraces(const TArray<FGCS_TraceHandle>& TraceHandles);
virtual void StopTrace(const FGCS_TraceHandle& TraceHandle);
virtual void RemoveTraces(const TArray<FGCS_TraceHandle>& TraceHandles);
virtual void RemoveTrace(const FGCS_TraceHandle& TraceHandle);
/**
* Event fired when a trace hits something.
* 当碰撞检测命中某物时触发的事件。
*/
UPROPERTY(BlueprintAssignable, Category = "GCS|TraceSystem")
FGCS_OnTraceHitSignature OnTraceHitEvent;
/**
* Event fired when a trace state changes.
* 当碰撞检测状态改变时触发的事件。
*/
UPROPERTY(BlueprintAssignable, Category = "GCS|TraceSystem")
FGCS_OnTraceStateChangedSignature OnTraceStateChangedEvent;
/**
* Event fired when a trace starts.
* 当碰撞检测开始时触发的事件。
*/
UPROPERTY(BlueprintAssignable, Category = "GCS|TraceSystem")
FGCS_OnTraceStartedSignature OnTraceStartedEvent;
/**
* Event fired when a trace stops.
* 当碰撞检测停止时触发的事件。
*/
UPROPERTY(BlueprintAssignable, Category = "GCS|TraceSystem")
FGCS_OnTraceStoppedSignature OnTraceStoppedEvent;
/**
* Event fired when the trace system is destroyed.
* 当碰撞检测系统被销毁时触发的事件。
*/
FGCS_OnTraceSystemDestroyedSignature OnDestroyedEvent;
protected:
virtual void OnTraceHitDetected(const FGCS_TraceHandle& TraceHandle, const TArray<FHitResult>& HitResults, const float DeltaTime, const uint32 TickIdx);
virtual void OnTraceStateChanged(const FGCS_TraceHandle& TraceHandle, bool bNewState);
/**
* Called when the game starts.
* 游戏开始时调用。
*/
virtual void BeginPlay() override;
/**
* Called when the game ends.
* 游戏结束时调用。
* @param EndPlayReason The reason for ending. 结束原因。
*/
virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override;
virtual void OnComponentDestroyed(bool bDestroyingHierarchy) override;
/**
* Whether to auto-initialize on BeginPlay and deinitialize on EndPlay.
* 是否在BeginPlay时自动初始化在EndPlay时自动取消初始化。
*/
UPROPERTY(EditAnywhere, Category = "GCS|TraceSystem")
bool bAutoInitialize{true};
/**
* Default trace definitions created on BeginPlay.
* 在BeginPlay时创建的默认碰撞检测定义。
* @note SourceComponent will be the actor's main mesh. 源组件会是Actor的主要mesh。
*/
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "GCS|TraceSystem", meta=(TitleProperty="TraceTag"))
TArray<FGCS_TraceDefinition> TraceDefinitions;
FCriticalSection TraceDoneScopeLock;
TMap<FGCS_TraceHandle, int32> HandleToStateIdx;
TMultiMap<FGameplayTag, FGCS_TraceHandle> TagToHandles;
bool bInitialized = false;
};

View File

@@ -0,0 +1,49 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GCS_CombatStructLibrary.h"
#include "Engine/DataAsset.h"
#include "GCS_AbilityActionSetSettings.generated.h"
class UGCS_LayeredMontageSelectionSet;
/**
* Data asset for defining ability action sets.
* 定义能力动作集的数据资产。
*/
UCLASS(BlueprintType, Const, meta=(DisplayName="GCS Ability Action Set"))
class GENERICCOMBATSYSTEM_API UGCS_AbilityActionSetSettings : public UDataAsset
{
GENERATED_BODY()
public:
/**
* Selects the best ability actions based on tags.
* 根据标签选择最佳能力动作。
* @param SourceTags Tags for the source. 来源标签。
* @param TargetTags Tags for the target. 目标标签。
* @param AbilityTags Tags for the ability. 能力标签。
* @param Actions The matched ability actions (output). 匹配的能力动作(输出)。
* @return True if selection is successful. 如果选择成功返回true。
*/
UFUNCTION(BlueprintCallable, BlueprintPure=false, Category = "GCS", meta=(AutoCreateRefTerm="TargetTags"))
bool SelectBestAbilityActions(const FGameplayTagContainer& SourceTags, const FGameplayTagContainer& TargetTags, const FGameplayTagContainer& AbilityTags, TArray<FGCS_AbilityAction>& Actions) const;
/**
* Array of ability action sets.
* 能力动作集数组。
*/
UPROPERTY(EditAnywhere, Category="GCS", meta=(TitleProperty="AbilityTag"))
TArray<FGCS_AbilityActionSet> ActionSets;
#if WITH_EDITORONLY_DATA
/**
* Called before saving in the editor.
* 编辑器中保存前调用。
* @param SaveContext The save context. 保存上下文。
*/
virtual void PreSave(FObjectPreSaveContext SaveContext) override;
#endif
};

View File

@@ -0,0 +1,142 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GameplayEffect.h"
#include "Engine/DataTable.h"
#include "GameplayTagContainer.h"
#include "GGA_AbilitySystemStructLibrary.h"
#include "Runtime/Launch/Resources/Version.h"
#if ENGINE_MINOR_VERSION < 5
#include "InstancedStruct.h"
#else
#include "StructUtils/InstancedStruct.h"
#endif
#include "GCS_AttackDefinition.generated.h"
/**
* Base struct allow you to extend the attack definition's fields using C++.
* 基础结构体允许你通过C++拓展攻击定义的字段。
*/
USTRUCT(BlueprintType, meta=(Hidden))
struct GENERICCOMBATSYSTEM_API FGCS_AttackDefinitionExtension
{
GENERATED_BODY()
};
/**
* Structure defining an attack's properties.
* 定义攻击属性的结构。
*/
USTRUCT(BlueprintType, meta=(DisplayName="GCS Attack Definition"))
struct GENERICCOMBATSYSTEM_API FGCS_AttackDefinition : public FTableRowBase
{
GENERATED_BODY()
/**
* Tags describing the attack (e.g., Melee/Ranged, Slash/Strike).
* 描述攻击的标签(例如近战/远程、劈砍/打击)。
* @note Added as dynamic AssetTags to the gameplay effect spec.
* @注意 作为动态AssetTags添加到游戏效果规格。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Common")
FGameplayTagContainer AttackTags;
/**
* SetByCaller tag-to-float mappings for gameplay effect specs.
* 用于游戏效果规格的SetByCaller标签到浮点映射。
* @note Usage is flexible (e.g., damage correction factors).
* @注意 使用灵活(例如伤害修正系数)。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Common", meta=(ForceInlineRow))
TMap<FGameplayTag, float> SetByCallerMagnitudes;
/**
* Gameplay effect to apply to the hit target.
* 应用于命中目标的游戏效果。
* @note Modified during attack request processing.
* @注意 在攻击请求处理期间修改。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Gameplay Effects")
TSoftClassPtr<UGameplayEffect> TargetEffectClass;
/**
* Level of the target gameplay effect.
* 目标游戏效果的等级。
* @note If < 1, uses the ability's level.
* @注意 如果<1使用能力的等级。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Gameplay Effects")
int32 TargetEffectClassLevel{1};
/**
* Effect container to apply to the target.
* 应用于目标的效果容器。
* @note Used for instant targeting; ability level determines effect level.
* @注意 用于即时目标;能力等级决定效果等级。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Gameplay Effects", meta=(ForceInlineRow))
FGGA_GameplayEffectContainer TargetEffectContainer;
/**
* Gameplay cues to trigger on the target upon hit.
* 命中目标时触发的游戏反馈。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Gameplay Cues", meta=(Categories="GameplayCue"))
TArray<FGameplayTag> TargetGameplayCues;
/**
* Knockback distance applied to the target.
* 应用于目标的击退距离。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "HitReaction", meta=(Units="cm"))
float KnockbackDistance{100};
/**
* Multiplier for knockback effect.
* 击退效果的倍增器。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "HitReaction", meta=(ClampMin=1))
float KnockbackMultiplier{1};
/**
* Duration of animation stall on hit (disabled if <= 0).
* 命中时动画停滞的持续时间(<=0时禁用
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Feedback", meta=(ClampMin=0, Units="s"))
float HitStallingDuration{0};
/**
* Play rate factor for hit animation.
* 命中动画的播放速率因子。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Feedback", meta=(ClampMin=0.1, ClampMax=0.9))
float HitPlayRateFactor{0.1};
/**
* Native Instanced struct for extending the attack definition.
* 实例化结构体用于扩充攻击定义的字段。
* @attention For C++ users only. 仅针对C++用户。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Extension")
TInstancedStruct<FGCS_AttackDefinitionExtension> NativeExtension;
/**
* Blueprint Instanced struct for extending the attack definition.
* 实例化结构体用于扩充攻击定义的字段。
* @attention For blueprint users only. 仅针对蓝图用户。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Extension")
FInstancedStruct Extension;
/**
* User-defined settings for the attack.
* 攻击的用户定义设置。
*/
UE_DEPRECATED(1.5, "Using extension field to add custom fields!")
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Deprecated", meta=(ForceInlineRow, BaseStruct = "/Script/GenericCombatSystem.GCS_UserSetting"))
TMap<FGameplayTag, FInstancedStruct> UserSettings;
};

View File

@@ -0,0 +1,224 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GameplayTagContainer.h"
#include "Bullet/GCS_BulletStructLibrary.h"
#include "GCS_AttackDefinition.h"
#include "UObject/Object.h"
#include "GCS_AttackRequest.generated.h"
/**
* Base class for all attack request types.
* 所有攻击请求类型的基类。
*/
UCLASS(Abstract, Blueprintable, BlueprintType, Const, DefaultToInstanced, EditInlineNew, meta=(DisplayName="GCS Attack Request"))
class UGCS_AttackRequest_Base : public UObject
{
GENERATED_BODY()
public:
/**
* Gets the attack definition handle.
* 获取攻击定义句柄。
* @return The attack definition handle. 攻击定义句柄。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, BlueprintNativeEvent, Category="GCS|Attack")
FDataTableRowHandle GetAttackDefinitionHandle() const;
/**
* Gets the attack definition.
* 获取攻击定义。
* @return The attack definition. 攻击定义。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GCS|Attack")
FGCS_AttackDefinition GetAttackDefinition() const;
};
/**
* Attack request for melee attacks.
* 近战攻击请求。
*/
UCLASS(meta=(DisplayName="GCS Attack Request (Melee)"))
class GENERICCOMBATSYSTEM_API UGCS_AttackRequest_Melee : public UGCS_AttackRequest_Base
{
GENERATED_BODY()
public:
/**
* Gets the attack definition handle.
* 获取攻击定义句柄。
* @return The attack definition handle. 攻击定义句柄。
*/
virtual FDataTableRowHandle GetAttackDefinitionHandle_Implementation() const override;
/**
* Tags for traces activated during the notify state.
* 在通知状态期间激活的追踪标签。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category="Attack")
FGameplayTagContainer TracesToControl;
protected:
/**
* Handle to the attack definition.
* 攻击定义的句柄。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category="Attack", meta=(RowType="/Script/GenericCombatSystem.GCS_AttackDefinition"))
FDataTableRowHandle AttackDefinitionHandle;
};
/**
* Enum for ability targeting source types.
* 能力目标来源类型的枚举。
*/
UENUM(BlueprintType)
enum class EGCS_AbilityTargetingSourceType : uint8
{
/**
* From the player's camera towards camera focus.
* 从玩家相机朝向相机焦点。
*/
CameraTowardsFocus,
/**
* From the pawn's location/socket, in the pawn's orientation.
* 从Pawn的位置/插槽沿Pawn的朝向。
*/
PawnForward,
/**
* From the pawn's location/socket, oriented towards camera focus.
* 从Pawn的位置/插槽,朝向相机焦点。
*/
PawnTowardsFocus,
/**
* From the weapon's location/socket, in the pawn's orientation.
* 从武器的位置/插槽沿Pawn的朝向。
*/
WeaponForward,
/**
* From the weapon's location/socket, towards camera focus.
* 从武器的位置/插槽,朝向相机焦点。
*/
WeaponTowardsFocus,
/**
* Custom targeting, requires overriding GetTargetingTransform.
* 自定义目标需重写GetTargetingTransform。
*/
Custom
};
/**
* Attack request for firing bullets.
* 发射子弹的攻击请求。
*/
UCLASS(Blueprintable, BlueprintType, Const, EditInlineNew, meta=(DisplayName="GCS Attack Request (Bullet)"))
class GENERICCOMBATSYSTEM_API UGCS_AttackRequest_Bullet : public UGCS_AttackRequest_Base
{
GENERATED_BODY()
public:
/**
* Gets the bullet definition.
* 获取子弹定义。
* @return The bullet definition. 子弹定义。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category = "GCS|Attack")
FGCS_BulletDefinition GetBulletDefinition() const;
/**
* Gets the attack definition handle.
* 获取攻击定义句柄。
* @return The attack definition handle. 攻击定义句柄。
*/
virtual FDataTableRowHandle GetAttackDefinitionHandle_Implementation() const override;
/**
* Gets the targeting transform for the attack.
* 获取攻击的目标变换。
* @param SourcePawn The source pawn. 来源Pawn。
* @param Source The targeting source type. 目标来源类型。
* @return The targeting transform. 目标变换。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, BlueprintNativeEvent, Category = "GCS|Attack")
FTransform GetTargetingTransform(APawn* SourcePawn, EGCS_AbilityTargetingSourceType Source) const;
/**
* Gets the weapon targeting source location.
* 获取武器目标来源位置。
* @param SourcePawn The source pawn. 来源Pawn。
* @return The weapon source location. 武器来源位置。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, BlueprintNativeEvent, Category = "GCS|Attack")
FVector GetWeaponTargetingSourceLocation(APawn* SourcePawn) const;
/**
* Gets the pawn targeting source location.
* 获取Pawn目标来源位置。
* @param SourcePawn The source pawn. 来源Pawn。
* @return The pawn source location. Pawn来源位置。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, BlueprintNativeEvent, Category = "GCS|Attack")
FVector GetPawnTargetingSourceLocation(APawn* SourcePawn) const;
/**
* Handle to the bullet definition.
* 子弹定义的句柄。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = Parameters, meta=(RowType="/Script/GenericCombatSystem.GCS_BulletDefinition"))
FDataTableRowHandle BulletDefinitionHandle;
/**
* Type of targeting source for the attack.
* 攻击的目标来源类型。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, meta = (ExposeOnSpawn = true), Category = Parameters)
EGCS_AbilityTargetingSourceType TargetingSourceType{EGCS_AbilityTargetingSourceType::PawnForward};
/**
* Tag name for looking up the source component.
* 用于查找来源组件的标签名称。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, meta = (ExposeOnSpawn = true), Category = Parameters, meta=(EditCondition="TargetingSourceType != EGCS_AbilityTargetingSourceType::CameraTowardsFocus"))
FName SourceComponentLookupTagName{NAME_None};
/**
* Source socket name, falls back to source location if not found.
* 来源插槽名称,如果未找到则回退到来源位置。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, meta = (ExposeOnSpawn = true), Category = Parameters, meta=(EditCondition="TargetingSourceType != EGCS_AbilityTargetingSourceType::CameraTowardsFocus"))
FName SourceSocketName{NAME_None};
/**
* Weapon socket name, falls back to source location if not found.
* 武器插槽名称,如果未找到则回退到来源位置。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, meta = (ExposeOnSpawn = true), Category = Parameters, meta=(EditCondition="TargetingSourceType != EGCS_AbilityTargetingSourceType::CameraTowardsFocus"))
FName SourceWeaponSocketName{NAME_None};
/**
* Additional offset to the source location.
* 来源位置的附加偏移。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, meta = (ExposeOnSpawn = true), Category = Parameters)
FVector LocationOffset{FVector::Zero()};
/**
* Whether targeting is required for the attack.
* 攻击是否需要目标。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = Parameters)
bool bRequireTargeting{false};
/**
* Targeting preset for the attack.
* 攻击的目标预设。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = Parameters)
TObjectPtr<UTargetingPreset> TargetingPreset;
};

View File

@@ -0,0 +1,205 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GameplayEffectTypes.h"
#include "GCS_CombatStructLibrary.h"
#include "Net/Serialization/FastArraySerializer.h"
#include "UObject/Object.h"
#include "GCS_AttackResult.generated.h"
class UGCS_AttackRequest_Melee;
class UGCS_CombatFlow;
class UGCS_CombatSystemComponent;
/**
* Structure representing the result of a processed attack.
* 表示已处理攻击结果的结构。
*/
USTRUCT(BlueprintType)
struct GENERICCOMBATSYSTEM_API FGCS_AttackResult : public FFastArraySerializerItem
{
GENERATED_BODY()
void PostReplicatedAdd(const struct FGCS_AttackResultContainer& InArray);
/**
* Deprecated.
* 已经弃用。
*/
UE_DEPRECATED(1.5, "Use TaggedValues within FGCS_ContextPayload_Combat")
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="GCS", NotReplicated, meta=(DeprecatedProperty, DeprecationMessage="Use TaggedValues within FGCS_ContextPayload_Combat!"))
TArray<FGCS_TaggedValue> TaggedValues;
/**
* Optional object related to the attack.
* 与攻击相关的可选对象。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GCS")
TObjectPtr<const UObject> OptionalObject;
/**
* Context handle for the gameplay effect.
* 游戏效果的上下文句柄。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GCS")
FGameplayEffectContextHandle EffectContextHandle;
/**
* Aggregated source tags for the attack.
* 攻击的聚合来源标签。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GCS")
FGameplayTagContainer AggregatedSourceTags;
/**
* Aggregated target tags for the attack.
* 攻击的聚合目标标签。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GCS")
FGameplayTagContainer AggregatedTargetTags;
/**
* Whether the attack result has been consumed.
* 攻击结果是否已被消耗。
*/
UPROPERTY(NotReplicated)
bool bConsumed{false};
/**
* Indicates this attack result was found in existing processed array with same prediction key.
* 表示此攻击结果在已处理攻击结果列表中有相同的预测Key。
*/
UPROPERTY(NotReplicated)
bool bWasPredicated{false};
/**
* Indicates this attack result was replicated via fast array serializer.
* 表示此攻击结果是经由fast array serializer同步而来。
*/
UPROPERTY(NotReplicated)
bool bWasReplicated{false};
};
/**
* Container for storing combat results with network serialization.
* 用于存储战斗结果的容器,支持网络序列化。
*/
USTRUCT(BlueprintType)
struct GENERICCOMBATSYSTEM_API FGCS_AttackResultContainer : public FFastArraySerializer
{
GENERATED_BODY()
/**
* Default constructor.
* 默认构造函数。
*/
FGCS_AttackResultContainer();
/**
* Constructor with combat flow and max size.
* 带有战斗流程和最大尺寸的构造函数。
* @param InCombatFlow The combat flow instance. 战斗流程实例。
* @param InMaxSize The maximum size of the container. 容器最大尺寸。
*/
FGCS_AttackResultContainer(UGCS_CombatFlow* InCombatFlow, int32 InMaxSize);
/**
* Constructor with combat system component and max size.
* 带有战斗系统组件和最大尺寸的构造函数。
* @param InCombatSystemComponent The combat system component. 战斗系统组件。
* @param InMaxSize The maximum size of the container. 容器最大尺寸。
*/
FGCS_AttackResultContainer(UGCS_CombatSystemComponent* InCombatSystemComponent, int32 InMaxSize);
/**
* Sets the owning combat system component.
* 设置所属战斗系统组件。
* @param InCombatSystemComponent The combat system component. 战斗系统组件。
*/
void SetOwningCombatSystem(UGCS_CombatSystemComponent* InCombatSystemComponent) { CombatSystemComponent = InCombatSystemComponent; }
/**
* Sets the combat flow.
* 设置战斗流程。
* @param InCombatFlow The combat flow instance. 战斗流程实例。
*/
void SetCombatFlow(UGCS_CombatFlow* InCombatFlow) { CombatFlow = InCombatFlow; }
/**
* Adds a new attack result entry to the container.
* 向容器添加新的攻击结果条目。
* @param NewEntry The attack result to add. 要添加的攻击结果。
*/
void AddEntry(FGCS_AttackResult& NewEntry);
/**
* Handles post-replication addition of entries.
* 处理条目添加后的复制。
* @param AddedIndices The indices of added entries. 添加的条目索引。
* @param FinalSize The final size of the container. 容器最终尺寸。
*/
void PostReplicatedAdd(const TArrayView<int32> AddedIndices, int32 FinalSize);
/**
* Handles post-replication changes to entries.
* 处理条目更改后的复制。
* @param ChangedIndices The indices of changed entries. 更改的条目索引。
* @param FinalSize The final size of the container. 容器最终尺寸。
*/
void PostReplicatedChange(const TArrayView<int32>& ChangedIndices, int32 FinalSize);
/**
* Serializes the container for network replication.
* 为网络复制序列化容器。
* @param DeltaParms The network serialization parameters. 网络序列化参数。
* @return True if serialization is successful. 如果序列化成功返回true。
*/
bool NetDeltaSerialize(FNetDeltaSerializeInfo& DeltaParms)
{
return FastArrayDeltaSerialize<FGCS_AttackResult, FGCS_AttackResultContainer>(Results, DeltaParms, *this);
}
bool HasPredictedResultWithPredictedKey(FPredictionKey PredictionKey) const;
private:
/**
* Reference to the combat flow instance.
* 战斗流程实例的引用。
*/
UPROPERTY()
TObjectPtr<UGCS_CombatFlow> CombatFlow;
/**
* Reference to the combat system component.
* 战斗系统组件的引用。
*/
UPROPERTY()
TObjectPtr<UGCS_CombatSystemComponent> CombatSystemComponent;
/**
* List of attack results.
* 攻击结果列表。
*/
UPROPERTY()
TArray<FGCS_AttackResult> Results;
/**
* Maximum size of the container.
* 容器最大尺寸。
*/
UPROPERTY()
int32 MaxSize;
};
template <>
struct TStructOpsTypeTraits<FGCS_AttackResultContainer> : TStructOpsTypeTraitsBase2<FGCS_AttackResultContainer>
{
enum
{
WithNetDeltaSerializer = true,
};
};

View File

@@ -0,0 +1,287 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GCS_AttackResult.h"
#include "UObject/Object.h"
#include "GCS_AttackResultProcessor.generated.h"
UENUM()
enum class EGCS_AttackResultProcessorPolicy
{
//execute when non-predicting cross all server and clients.
Default,
//execute in predicting client first,then server and other clients.same as default is not predicting.
LocalPredicted,
//execute only on server side.
ServerOnly
};
/**
* Base class for processing attack results.
* 处理攻击结果的基类。
*/
UCLASS(EditInlineNew, DefaultToInstanced, BlueprintType, Blueprintable, Abstract, Const)
class GENERICCOMBATSYSTEM_API UGCS_AttackResultProcessor : public UObject
{
GENERATED_BODY()
public:
/**
* Processes an incoming attack result.
* 处理传入的攻击结果。
* @param AttackResult The attack result to process. 要处理的攻击结果。
*/
UFUNCTION(BlueprintCallable, Category="GCS")
virtual bool ProcessIncomingAttackResult(const FGCS_AttackResult& AttackResult);
/**
* Gets the world context for the processor.
* 获取处理器的世界上下文。
* @return The world context. 世界上下文。
*/
virtual UWorld* GetWorld() const override;
UFUNCTION(BlueprintCallable, BlueprintPure, BlueprintNativeEvent, Category="GCS")
EGCS_AttackResultProcessorPolicy GetExecutePolicy() const;
#if WITH_EDITOR
bool GetEditorEnableState() const { return bEditorDebugEnabled; };
#endif
protected:
/**
* Indicate how this processor will be executed cross network.
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category="GCS")
EGCS_AttackResultProcessorPolicy ExecutePolicy{EGCS_AttackResultProcessorPolicy::Default};
/**
* Handles the incoming attack result.
* 处理传入的攻击结果。
* @param AttackResult The attack result to handle. 要处理的攻击结果。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GCS")
void HandleIncomingAttackResult(const FGCS_AttackResult& AttackResult) const;
virtual void HandleIncomingAttackResult_Implementation(const FGCS_AttackResult& AttackResult) const;
/**
* Gets the owning actor.
* 获取所属演员。
* @return The owning actor. 所属演员。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GCS")
AActor* GetOwningActor() const;
/**
* Gets the owning ability system component.
* 获取所属能力系统组件。
* @return The ability system component. 能力系统组件。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GCS")
UAbilitySystemComponent* GetOwningAbilitySystemComponent() const;
/**
* Gets the editor-friendly name for the processor.
* 获取处理器的编辑器友好名称。
* @return The editor-friendly name. 编辑器友好名称。
*/
UFUNCTION(BlueprintNativeEvent, Category="GCS")
FString GetEditorFriendlyName() const;
virtual FString GetEditorFriendlyName_Implementation() const;
#if WITH_EDITORONLY_DATA
/**
* Allowing toggle on/off this processor for debugging purpose.
* 允许你开关此处理器,用于调试。
*/
UPROPERTY(EditAnywhere, Category="GCS")
bool bEditorDebugEnabled{true};
/**
* Editor-friendly name for the processor.
* 处理器的编辑器友好名称。
*/
UPROPERTY(VisibleAnywhere, Category=AlwaysHidden)
FString EditorFriendlyName;
// UPROPERTY(EditAnywhere, Category="GCS")
// bool bPrintDebugString{false};
/**
* Called before saving in the editor.
* 编辑器中保存前调用。
* @param SaveContext The save context. 保存上下文。
*/
virtual void PreSave(FObjectPreSaveContext SaveContext) override;
#endif
};
/**
* Attack result processor with tag requirements.
* 具有标签要求的攻击结果处理器。
*/
UCLASS(Abstract)
class UGCS_AttackResultProcessor_WithTagRequirement : public UGCS_AttackResultProcessor
{
GENERATED_BODY()
public:
/**
* Processes an incoming attack result with tag requirements.
* 处理具有标签要求的传入攻击结果。
* @param AttackResult The attack result to process. 要处理的攻击结果。
*/
virtual bool ProcessIncomingAttackResult(const FGCS_AttackResult& AttackResult) override;
protected:
/**
* Source tag query for filtering attack results.
* 用于过滤攻击结果的来源标签查询。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category="GCS")
FGameplayTagQuery SourceTagQuery;
/**
* Target tag query for filtering attack results.
* 用于过滤攻击结果的目标标签查询。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category="GCS")
FGameplayTagQuery TargetTagQuery;
/**
* Gets the description of the source tag query.
* 获取来源标签查询的描述。
* @return The source tag query description. 来源标签查询描述。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GCS")
FString GetSourceTagQueryDesc() const;
/**
* Gets the description of the target tag query.
* 获取目标标签查询的描述。
* @return The target tag query description. 目标标签查询描述。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GCS")
FString GetTargetTagQueryDesc() const;
};
/**
* Processor for handling death-related attack results.
* 处理与死亡相关的攻击结果的处理器。
*/
UCLASS()
class UGCS_AttackResultProcessor_Death : public UGCS_AttackResultProcessor
{
GENERATED_BODY()
public:
/**
* Handles death-related attack results.
* 处理与死亡相关的攻击结果。
* @param AttackResult The attack result to handle. 要处理的攻击结果。
*/
virtual void HandleIncomingAttackResult_Implementation(const FGCS_AttackResult& AttackResult) const override;
};
/**
* Processor for converting attack results to gameplay events.
* 将攻击结果转换为游戏事件的处理器。
* @note Only executes for server pawn or local controller pawn. The dynamic tags added to effect context will be merged as Instigator Tags.
* @注意 仅对服务器Pawn或本地控制器Pawn执行。 添加到Effect Context的动态标签会被合并为Instigator Tags。
*/
UCLASS()
class UGCS_AttackResultProcessor_GameplayEvent : public UGCS_AttackResultProcessor_WithTagRequirement
{
GENERATED_BODY()
protected:
/**
* Handles attack results by converting to gameplay events.
* 通过转换为游戏事件处理攻击结果。
* @param AttackResult The attack result to handle. 要处理的攻击结果。
*/
virtual void HandleIncomingAttackResult_Implementation(const FGCS_AttackResult& AttackResult) const override;
/**
* Gets the editor-friendly name for the processor.
* 获取处理器的编辑器友好名称。
* @return The editor-friendly name. 编辑器友好名称。
*/
virtual FString GetEditorFriendlyName_Implementation() const override;
/**
* Whether to send the event to the attacker.
* 是否将事件发送给攻击者。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category="GCS")
bool bSendToAttacker{false};
/**
* Gameplay tags to trigger as events.
* 作为事件触发的游戏标签。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category="GCS")
TArray<FGameplayTag> EventTriggers;
};
/**
* Processor for triggering gameplay cues from attack results.
* 从攻击结果触发游戏反馈的处理器。
* @note Cues do not replicate as attack results are replicated.
* @注意 反馈不复制,因为攻击结果已复制。
*/
UCLASS()
class UGCS_AttackResultProcessor_GameplayCue : public UGCS_AttackResultProcessor_WithTagRequirement
{
GENERATED_BODY()
protected:
/**
* Handles attack results by triggering gameplay cues.
* 通过触发游戏反馈处理攻击结果。
* @param AttackResult The attack result to handle. 要处理的攻击结果。
*/
virtual void HandleIncomingAttackResult_Implementation(const FGCS_AttackResult& AttackResult) const override;
/**
* Gets the editor-friendly name for the processor.
* 获取处理器的编辑器友好名称。
* @return The editor-friendly name. 编辑器友好名称。
*/
virtual FString GetEditorFriendlyName_Implementation() const override;
/**
* Modifies gameplay cue parameters before execution.
* 在执行前修改游戏反馈参数。
* @param ParametersToModify The parameters to modify. 要修改的参数。
*/
UFUNCTION(BlueprintImplementableEvent, Category="GCS")
void ModifyGameplayCueParametersBeforeExecute(UPARAM(ref)
FGameplayCueParameters& ParametersToModify) const;
/**
* Gameplay cues to trigger.
* 要触发的游戏反馈。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category="GCS", meta=(Categories="GameplayCue"))
TArray<FGameplayTag> GameplayCues;
/**
* Tag for finding raw magnitude in TaggedValues.
* 在TaggedValues中查找原始幅度的标签。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category="GCS")
FGameplayTag RawMagnitudeTag;
/**
* Tag for finding normalized magnitude in TaggedValues.
* 在TaggedValues中查找归一化幅度的标签。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category="GCS")
FGameplayTag NormalizedMagnitudeTag;
};

View File

@@ -0,0 +1,114 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GameplayTagContainer.h"
#include "GCS_ActorOwnedObject.h"
#include "GCS_AttackResult.h"
#include "GGA_GameplayAttributeStructLibrary.h"
#include "GCS_CombatFlow.generated.h"
class UGCS_AttackResultProcessor;
class UGCS_CombatSystemComponent;
/**
* Combat flow for processing incoming attacks.
* 处理传入攻击的战斗流程。
* @note Typically one instance per character type (e.g., human, quadruped, mechanical).
* @注意 通常每种角色类型一个实例(例如人类、四足动物、机械)。
*/
UCLASS(Abstract, BlueprintType, Blueprintable, DefaultToInstanced, EditInlineNew, CollapseCategories, meta=(DisplayName="GCS Combat Flow"))
class GENERICCOMBATSYSTEM_API UGCS_CombatFlow : public UGCS_ActorOwnedObject
{
GENERATED_BODY()
public:
/**
* Default constructor.
* 默认构造函数。
*/
UGCS_CombatFlow();
/**
* Retrieves lifetime replicated properties.
* 获取生命周期复制属性。
* @param OutLifetimeProps The lifetime properties. 生命周期属性。
*/
virtual void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const override;
/**
* Checks if networking is supported.
* 检查是否支持网络。
* @return True if supported. 如果支持返回true。
*/
virtual bool IsSupportedForNetworking() const override { return true; }
/**
* Gets the actor owning this combat flow.
* 获取拥有此战斗流程的演员。
* @return The owning actor. 所属演员。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category = "GCS|Combat Flow")
AActor* GetFlowOwner() const { return Owner; }
/**
* Initializes the combat flow with an owner.
* 使用拥有者初始化战斗流程。
* @param NewOwner The owning actor. 所属演员。
*/
void Initialize(AActor* NewOwner);
/**
* Adds dynamic tags to a gameplay effect spec.
* 为游戏效果规格添加动态标签。
* @note Requires GGA_AbilitySystemGlobals as default AbilitySystemGlobals.
* @注意 需要将GGA_AbilitySystemGlobals设置为默认AbilitySystemGlobals。
* @param Spec The gameplay effect spec. 游戏效果规格。
* @param AbilitySystemComponent The ability system component. 能力系统组件。
* @param OutDynamicTagsAppendToSpec The tags to append (output). 要附加的标签(输出)。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GCS|Combat Flow")
void HandlePreGameplayEffectSpecApply(const FGameplayEffectSpec& Spec, UAbilitySystemComponent* AbilitySystemComponent, FGameplayTagContainer& OutDynamicTagsAppendToSpec);
/**
* Handles gameplay effect execution.
* 处理游戏效果执行。
* @param Payload The effect modification data. 效果修改数据。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GCS|Combat Flow")
void HandleGameplayEffectExecute(const FGGA_GameplayEffectModCallbackData& Payload);
virtual void HandleGameplayEffectExecute_Implementation(const FGGA_GameplayEffectModCallbackData& Payload);
/**
* Handles attack results across the network.
* 在网络上处理攻击结果。
* @note Default implementation calls result processors.
* @注意 默认实现调用结果处理器。
* @param Payload The attack result. 攻击结果。
*/
UFUNCTION(BlueprintNativeEvent, BlueprintCallable, Category = "GCS|Combat Flow")
void HandleAttackResult(const FGCS_AttackResult& Payload);
protected:
/**
* The actor owning this combat flow.
* 拥有此战斗流程的演员。
*/
UPROPERTY()
TObjectPtr<AActor> Owner;
/**
* Reference to the owning combat system component.
* 所属战斗系统组件的引用。
*/
UPROPERTY(BlueprintReadOnly, Category = "GCS|Combat Flow", meta=(BlueprintProtected))
TObjectPtr<UGCS_CombatSystemComponent> CombatComponent;
/**
* List of attack result processors for handling attack results.
* 处理攻击结果的攻击结果处理器列表。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Instanced, Category = "GCS|Combat Flow Settings", meta=(TitleProperty="EditorFriendlyName"))
TArray<TObjectPtr<UGCS_AttackResultProcessor>> AttackResultProcessors;
};

View File

@@ -0,0 +1,107 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GameplayTagContainer.h"
#include "Engine/DataTable.h"
#include "StructUtils/InstancedStruct.h"
#include "GCS_ComboDefinition.generated.h"
/**
* Base struct allow you to extend the combo definition's fields using C++.
* 基础结构体允许你通过C++拓展连击定义的字段。
*/
USTRUCT(BlueprintType, meta=(Hidden))
struct GENERICCOMBATSYSTEM_API FGCS_ComboDefinitionExtension
{
GENERATED_BODY()
};
/**
*
*/
USTRUCT(BlueprintType)
struct FGCS_ComboDefinition : public FTableRowBase
{
GENERATED_BODY()
public:
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Combo")
TSoftClassPtr<class UGameplayAbility> AbilityClass;
/**
* Will reset the combo step if this row was selected.(Only works if MinComboStep > 0)
* 此行选中则会重置连招步骤。(仅在MinComboStep > 0时生效。)
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Combo")
bool bResetComboStep{false};
/**
* When Current Combo Step > this value, this won't be selected. 0 means no restriction.
* How many combo steps required to select this combo.
* 至少执行过几次combo才能选择此行作为下一个combo。0代表入口。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Requirements", meta=(ClampMin=0))
int32 MinComboStep = 0;
/**
* The combo event data's event tag must equals to this tag if set, otherwise this combo won't be selected!.
* 若有值连击事件数据的event tag必须与此值相等否则该连击不会被选择。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Requirements")
FGameplayTag EventTag;
/**
* The combo event data's instigator tags mush matches this Query if set, otherwise this combo won't be selected!
* 若有值连击事件数据的instigator tags必须匹配此查询否则该连击不会被选择。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Requirements")
FGameplayTagQuery EventInstigatorTagQuery;
/**
* The tags owned by the ability system component of the pawn must much this query if set otherwise this combo won't be selected!
* 若有值Pawn的技能组件所拥有的Tags必须满足此查询否则该连击不会被选择。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Requirements")
FGameplayTagQuery TagQuery;
/**
* Should try if this ability can be activated before select it?
* 是否在选择Ability之前测试是否可激活
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Activation")
bool bRunActivationTest{false};
/**
* Should abort the whole combo or just skip this selection when activation test failed?
* 若激活测试失败是放弃整个Combo还是跳过此选择
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Activation", meta=(EditCondition="bRunActivationTest"))
bool bAbortIfActivationTestFailed{false};
/**
* Native Instanced struct for extending the combo definition.
* 实例化结构体用于扩充连击定义的字段。
* @attention For C++ users only. 仅针对C++用户。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Extension")
TInstancedStruct<FGCS_ComboDefinitionExtension> NativeExtension;
/**
* Blueprint Instanced struct for extending the combo definition.
* 实例化结构体用于扩充连击定义的字段。
* @attention For blueprint users only. 仅针对蓝图用户。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Extension")
FInstancedStruct Extension;
#if WITH_EDITORONLY_DATA
/**
* Description for developers in the editor.
* 编辑器中用于开发者的描述。
*/
UPROPERTY(EditAnywhere, Category = "Editor")
FString DevDescription;
#endif
};

View File

@@ -0,0 +1,25 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "UObject/Object.h"
#include "GCS_ActorOwnedObject.generated.h"
/**
* Base class for objects owned by an actor.
* 演员拥有的对象的基类。
*/
UCLASS(NotBlueprintable, Abstract)
class GENERICCOMBATSYSTEM_API UGCS_ActorOwnedObject : public UObject
{
GENERATED_BODY()
public:
/**
* Gets the world context for the object.
* 获取对象的世界上下文。
* @return The world context. 世界上下文。
*/
virtual UWorld* GetWorld() const override;
};

View File

@@ -0,0 +1,199 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GameplayTagContainer.h"
#include "GCS_CombatStructLibrary.h"
#include "UObject/Interface.h"
#include "GCS_CombatEntityInterface.generated.h"
class USceneComponent;
/**
* Interface for actors or components involved in combat.
* 参与战斗的演员或组件的接口。
* @note Use helper function "GetCombatInterface" for access.
* @注意 使用辅助函数"GetCombatInterface"访问。
*/
UINTERFACE(MinimalAPI, BlueprintType, Blueprintable)
class UGCS_CombatEntityInterface : public UInterface
{
GENERATED_BODY()
};
/**
* Combat interface for handling combat-related functionality.
* 处理战斗相关功能的接口。
* @note Implementing objects should group related functionality.
* @注意 实现对象应分组相关功能。
*/
class GENERICCOMBATSYSTEM_API IGCS_CombatEntityInterface
{
GENERATED_BODY()
public:
/**
* Gets the current combat target actor.
* 获取当前战斗目标演员。
* @return The combat target actor. 战斗目标演员。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GCS|Combat")
AActor* GetCombatTargetActor() const;
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GCS|Combat")
const UDataTable* GetComboDefinitionTable() const;
/**
* Gets the current combat target object as a scene component.
* 获取当前战斗目标对象的场景组件。
* @return The combat target scene component. 战斗目标场景组件。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GCS|Combat")
USceneComponent* GetCombatTargetObject() const;
/**
* Queries ability actions based on tags.
* 根据标签查询能力动作。
* @param AbilityTags Tags for the ability. 能力标签。
* @param SourceTags Source tags for filtering. 来源标签。
* @param TargetTags Target tags for filtering. 目标标签。
* @param AbilityActions The matching ability actions (output). 匹配的能力动作(输出)。
* @return True if valid results are found. 如果找到有效结果返回true。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GCS|Combat",
meta=(ExpandBoolAsExecs="ReturnValue", DeprecatedFunction, DeprecationMessage="QueryAbilityActionsByContext as it is more reliable!"))
bool QueryAbilityActions(FGameplayTagContainer AbilityTags, FGameplayTagContainer SourceTags, FGameplayTagContainer TargetTags, TArray<FGCS_AbilityAction>& AbilityActions);
/**
* Queries ability actions based on tags and context object.
* 根据上下文和标签查询能力动作。
* @param Context An optional Context object, Usually the source object if called from ability.
* @param AbilityTags Tags for the ability. 能力标签。
* @param SourceTags Source tags for filtering. 来源标签。
* @param TargetTags Target tags for filtering. 目标标签。
* @param AbilityActions The matching ability actions (output). 匹配的能力动作(输出)。
* @return True if valid results are found. 如果找到有效结果返回true。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GCS|Combat", meta=(ExpandBoolAsExecs="ReturnValue"))
bool QueryAbilityActionsByContext(UObject* Context, FGameplayTagContainer AbilityTags, FGameplayTagContainer SourceTags, FGameplayTagContainer TargetTags,
TArray<FGCS_AbilityAction>& AbilityActions);
/**
* Queries a weapon based on a tag query.
* 根据标签查询武器。
* @param Query The tag query for filtering. 标签查询。
* @return The object implementing GCS_WeaponInterface. 实现武器接口的对象。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GCS|Combat", meta=(DisplayName="Query Weapon"))
UObject* QueryWeapon(const FGameplayTagQuery& Query) const;
/**
* Sets the character's rotation mode (e.g., strafe).
* 设置角色的旋转模式(例如靶向移动)。
* @param NewRotationMode The new rotation mode. 新旋转模式。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GCS|Movement")
void SetRotationMode(FGameplayTag NewRotationMode);
/**
* Gets the current rotation mode.
* 获取当前旋转模式。
* @return The current rotation mode. 当前旋转模式。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GCS|Movement")
FGameplayTag GetRotationMode() const;
/**
* Sets the movement set (e.g., ADS, Guard).
* 设置运动集(例如瞄准、防御)。
* @param NewMovementSet The new movement set. 新运动集。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GCS|Movement")
void SetMovementSet(FGameplayTag NewMovementSet);
/**
* Gets the current movement set.
* 获取当前运动集。
* @return The current movement set. 当前运动集。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GCS|Movement")
FGameplayTag GetMovementSet() const;
/**
* Sets the movement state (e.g., walk, jog, sprint).
* 设置运动状态(例如走、跑、疾跑)。
* @param NewMovementState The new movement state. 新运动状态。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GCS|Movement")
void SetMovementState(FGameplayTag NewMovementState);
/**
* Gets the current movement state.
* 获取当前运动状态。
* @return The current movement state. 当前运动状态。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GCS|Movement")
FGameplayTag GetMovementState() const;
/**
* Initiates the death process (e.g., disable collision, drop weapons).
* 启动死亡流程(例如禁用碰撞、丢弃武器)。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GCS|Lifecycle")
void StartDeath();
/**
* Finalizes the death process (e.g., ragdoll, destroy actor).
* 完成死亡流程(例如布娃娃、销毁演员)。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GCS|Lifecycle")
void FinishDeath();
/**
* Checks if the character is dead.
* 检查角色是否死亡。
* @return True if the character is dead. 如果角色死亡返回true。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GCS|Lifecycle")
bool IsDead() const;
/**
* Gets the movement input direction.
* 获取移动输入方向。
* @return The movement input direction. 移动输入方向。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GCS|Input")
FVector GetMovementIntent() const;
/**
* Gets the current used weapon. (You may have multiple weapon active at the same time, use this interface to get the current one.)
* 获取当前使用的武器。( 你可能有多个武器同时激活,使用此接口获取当前使用的那一个。)
* @param Context Optional context for querying. 可选查询上下文。
* @return The object implementing GCS_WeaponInterface. 实现武器接口的对象。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GCS|Weapon")
UObject* GetCurrentWeapon(UObject* Context = nullptr) const;
/**
* Set the current used weapon.(You may have multiple weapon active at the same time, use this interface to set the current one.)
* 设置当前使用的武器。(你可能有多个武器同时激活,使用此接口设置当前使用的那一个。)
* @note This is not for weapon switching, only used to mark which weapon will be used for next action(Press X to use primary weapon/Y to use secondary weapon.). 这并非用于武器切换仅用于标识当前使用的哪个武器比如X使用主武器Y使用副武器在使用之前设置到底是哪一个。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GCS|Weapon")
void SetCurrentWeapon(UObject* Weapon);
/**
* Gets the relative transform for a mesh attached to a socket.
* 获取附加到插槽的网格的相对变换。
* @param InSkeletalMeshComponent The skeletal mesh component. 骨骼网格组件。
* @param StaticMesh The static mesh. 静态网格。
* @param SkeletalMesh The skeletal mesh. 骨骼网格。
* @param SocketName The socket name. 插槽名称。
* @param OutTransform The relative transform (output). 相对变换(输出)。
* @return True if transform is provided. 如果提供变换返回true。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, BlueprintPure=false, Category="GCS|Weapon", meta=(ExpandBoolAsExecs="ReturnValue"))
bool GetRelativeTransformToSocket(const USkeletalMeshComponent* InSkeletalMeshComponent, const UStaticMesh* StaticMesh, const USkeletalMesh* SkeletalMesh, FName SocketName,
FTransform& OutTransform) const;
};

View File

@@ -0,0 +1,95 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "UObject/Object.h"
#include "GCS_CombatEnumLibrary.generated.h"
/**
* Enum for basic directional inputs.
* 基本方向输入的枚举。
*/
UENUM(BlueprintType)
enum class EGCS_Direction : uint8
{
/**
* Forward direction.
* 前进方向。
*/
Forward,
/**
* Backward direction.
* 后退方向。
*/
Backward,
/**
* Left direction.
* 左方向。
*/
Left,
/**
* Right direction.
* 右方向。
*/
Right
};
/**
* Enum for eight-directional inputs.
* 八方向输入的枚举。
*/
UENUM(BlueprintType)
enum class EGCS_Direction_8 : uint8
{
/**
* Forward direction.
* 前进方向。
*/
Forward,
/**
* Forward-left direction.
* 前左方向。
*/
Forward_Left,
/**
* Forward-right direction.
* 前右方向。
*/
Forward_Right,
/**
* Backward direction.
* 后退方向。
*/
Backward,
/**
* Backward-left direction.
* 后左方向。
*/
Backward_Left,
/**
* Backward-right direction.
* 后右方向。
*/
Backward_Right,
/**
* Left direction.
* 左方向。
*/
Left,
/**
* Right direction.
* 右方向。
*/
Right
};

View File

@@ -0,0 +1,230 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GameplayEffect.h"
#include "GameplayTagContainer.h"
#include "StructUtils/InstancedStruct.h"
#include "UObject/Object.h"
#include "GCS_CombatStructLibrary.generated.h"
class UTargetingPreset;
class UAnimMontage;
/**
* Structure for tagged value pairs.
* 标记值对的结构。
*/
USTRUCT(BlueprintType)
struct GENERICCOMBATSYSTEM_API FGCS_TaggedValue
{
GENERATED_BODY()
/**
* The gameplay tag for the attribute.
* 属性的游戏标签。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GCS")
FGameplayTag Attribute;
/**
* The value applied to the attribute.
* 应用于属性的值。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GCS")
float Value{0};
};
USTRUCT(BlueprintType, meta=(Hidden))
struct GENERICCOMBATSYSTEM_API FGCS_AbilityActionExtension
{
GENERATED_BODY()
};
/**
* Structure for ability actions.
* 能力动作的结构。
*/
USTRUCT(BlueprintType)
struct GENERICCOMBATSYSTEM_API FGCS_AbilityAction
{
GENERATED_BODY()
/**
* The animation montage to play.
* 要播放的动画蒙太奇。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Animation")
TObjectPtr<UAnimMontage> Animation;
/**
* The playback rate for the montage.
* 蒙太奇的播放速率。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Animation")
float PlayRate{1.f};
/**
* The starting section name for the montage.
* 蒙太奇的起始片段名称。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Animation")
FName StartSection{NAME_None};
/**
* Whether to stop the montage when the ability ends.
* 能力结束时是否停止蒙太奇。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Animation")
bool bStopWhenAbilityEnds{true};
/**
* Indicate if the selected anim sequence has root motion enabled.(It was auto calculated during save.)
* 标识选择的动画序列是启用了根运动。(保存时自动设置。)
*/
UPROPERTY(VisibleAnywhere, Category = "Animation", Meta=(EditCondition=False, EditConditionHides))
bool bHasRootMotion{false};
/**
* Scale for animation root motion translation.
* 动画根运动平移的缩放。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Animation")
float AnimRootMotionTranslationScale{1.f};
/**
* Start time for the montage in seconds.
* 蒙太奇的起始时间(秒)。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Animation")
float StartTimeSeconds{0.f};
/**
* Whether to allow interruption after blend out.
* 是否允许在混合结束时中断。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Animation")
bool bAllowInterruptAfterBlendOut{false};
/**
* Gameplay effect for ability cost.
* 能力消耗的游戏效果。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "GameplayEffects")
TSubclassOf<UGameplayEffect> CostGameplayEffect;
/**
* Allowing C++ users to add custom fields to ability action.
* 允许C++用户添加自定义字段到AbilityAction。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Extension")
TInstancedStruct<FGCS_AbilityActionExtension> Extension;
#if WITH_EDITORONLY_DATA
/**
* Editor-friendly name for the ability action.
* 能力动作的编辑器友好名称。
*/
UPROPERTY(VisibleAnywhere, Category=AlwaysHidden, Meta=(EditCondition=False, EditConditionHides))
FString EditorFriendlyName;
#endif
};
/**
* Structure for ability actions with tag queries.
* 带有标签查询的能力动作结构。
*/
USTRUCT(BlueprintType)
struct GENERICCOMBATSYSTEM_API FGCS_AbilityActionsWithQuery
{
GENERATED_BODY()
/**
* Source tag query for filtering.
* 用于过滤的来源标签查询。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "GCS")
FGameplayTagQuery SourceTagQuery;
/**
* Target tag query for filtering.
* 用于过滤的目标标签查询。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "GCS")
FGameplayTagQuery TargetTagQuery;
/**
* Array of ability actions.
* 能力动作数组。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "GCS", meta=(TitleProperty="EditorFriendlyName"))
TArray<FGCS_AbilityAction> Actions;
#if WITH_EDITORONLY_DATA
/**
* Editor-friendly name for the action set.
* 动作集的编辑器友好名称。
*/
UPROPERTY(VisibleAnywhere, Category=AlwaysHidden, Meta=(EditCondition=False, EditConditionHides))
FString EditorFriendlyName;
#endif
};
/**
* Structure for ability action sets.
* 能力动作集的结构。
*/
USTRUCT(BlueprintType)
struct GENERICCOMBATSYSTEM_API FGCS_AbilityActionSet
{
GENERATED_BODY()
/**
* The gameplay tag for the ability.
* 能力的游戏标签。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "GCS")
FGameplayTag AbilityTag;
/**
* Array of ability actions.
* 能力动作数组。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "GCS", meta=(TitleProperty="EditorFriendlyName"))
TArray<FGCS_AbilityAction> Actions;
/**
* Layered action sets for conditional selection based on tags.
* 基于标签条件选择的层次动作集。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "GCS", meta=(TitleProperty="EditorFriendlyName"))
TArray<FGCS_AbilityActionsWithQuery> Layered;
};
/**
* Base structure for user settings.
* 用户设置的基结构。
*/
USTRUCT(BlueprintType)
struct UE_DEPRECATED(1.5, "Using Extension field insted of this one.") GENERICCOMBATSYSTEM_API FGCS_UserSetting
{
GENERATED_BODY()
};
/**
* User settings structure for tag-to-float mappings.
* 标签到浮点映射的用户设置结构。
*/
USTRUCT(BlueprintType)
struct UE_DEPRECATED(1.5, "this sample also deprecated due to FGCS_UserSetting was deprecated.") FGCS_UserSetting_Attributes : public FGCS_UserSetting
{
GENERATED_BODY()
/**
* Map of gameplay tags to float attributes.
* 游戏标签到浮点属性的映射。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="UserSettings")
TMap<FGameplayTag, float> Attributes;
};

View File

@@ -0,0 +1,411 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GGA_AbilitySystemGlobals.h"
#include "CombatFlow/GCS_AttackResult.h"
#include "GCS_CombatSystemComponent.generated.h"
class UGCS_CombatFlow;
/**
* Structure for requesting montage playback.
* 请求蒙太奇播放的结构。
*/
USTRUCT(BlueprintType)
struct GENERICCOMBATSYSTEM_API FGCS_PlayMontageRequest
{
GENERATED_BODY()
/**
* The animation montage to play.
* 要播放的动画蒙太奇。
*/
UPROPERTY(BlueprintReadWrite, EditAnywhere, Category="GCS")
TObjectPtr<UAnimMontage> AnimMontage{nullptr};
/**
* The playback rate for the montage.
* 蒙太奇的播放速率。
*/
UPROPERTY(BlueprintReadWrite, EditAnywhere, Category="GCS")
float PlayRate{1.0f};
/**
* The starting section name for the montage.
* 蒙太奇的起始片段名称。
*/
UPROPERTY(BlueprintReadWrite, EditAnywhere, Category="GCS")
FName StartSectionName{NAME_None};
/**
* The scale for root motion translation.
* 根运动平移的缩放。
*/
UPROPERTY(BlueprintReadWrite, EditAnywhere, Category="GCS")
float RootTranslationScale{1.0f};
/**
* The start time for the montage in seconds.
* 蒙太奇的起始时间(秒)。
*/
UPROPERTY(BlueprintReadWrite, EditAnywhere, Category="GCS")
float StartTimeSeconds{0.0f};
};
/**
* Structure for predicted montage information.
* 预测蒙太奇信息的结构。
*/
USTRUCT()
struct FGCS_PredictedMontageInfo
{
GENERATED_BODY()
/**
* The animation montage.
* 动画蒙太奇。
*/
UPROPERTY()
TObjectPtr<UAnimMontage> AnimMontage{nullptr};
/**
* The playback rate.
* 播放速率。
*/
UPROPERTY()
float PlayRate{1.0f};
/**
* The starting section name.
* 起始片段名称。
*/
UPROPERTY()
FName StartSectionName{NAME_None};
/**
* The time the montage was triggered.
* 蒙太奇触发的时间。
*/
UPROPERTY()
float TriggeredTime{0.0f};
};
/**
* Structure for replicated montage information.
* 复制蒙太奇信息的结构。
*/
USTRUCT()
struct FGCS_ReplicatedMontageInfo
{
GENERATED_BODY()
/**
* The animation montage.
* 动画蒙太奇。
*/
UPROPERTY()
TObjectPtr<UAnimMontage> AnimMontage{nullptr};
/**
* The playback rate.
* 播放速率。
*/
UPROPERTY()
float PlayRate{1.0f};
/**
* The starting section name.
* 起始片段名称。
*/
UPROPERTY()
FName StartSectionName{NAME_None};
/**
* The time the montage was triggered.
* 蒙太奇触发的时间。
*/
UPROPERTY()
float TriggeredTime{0.0f};
};
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FGCS_ComboStepChangedEventSignature, int32, PrevComboStep);
/**
* Component for handling offensive and defensive combat behaviors.
* 处理进攻和防御战斗行为的组件。
*/
UCLASS(ClassGroup=GCS, Blueprintable, BlueprintType, AutoExpandCategories=("GCS"), meta=(BlueprintSpawnableComponent))
class GENERICCOMBATSYSTEM_API UGCS_CombatSystemComponent : public UActorComponent, public IGGA_AbilitySystemGlobalsEventReceiver
{
GENERATED_BODY()
friend UGCS_CombatFlow;
public:
/**
* Default constructor.
* 默认构造函数。
*/
UGCS_CombatSystemComponent();
/**
* Initializes the component.
* 初始化组件。
*/
virtual void InitializeComponent() override;
/**
* Called when the game starts.
* 游戏开始时调用。
*/
virtual void BeginPlay() override;
/**
* Called when the game ends.
* 游戏结束时调用。
* @param EndPlayReason The reason for ending. 结束原因。
*/
virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override;
/**
* Retrieves lifetime replicated properties.
* 获取生命周期复制属性。
* @param OutLifetimeProps The lifetime properties. 生命周期属性。
*/
virtual void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const override;
/**
* Gets the combat system component for an actor.
* 获取演员的战斗系统组件。
* @param Actor The actor to query. 要查询的演员。
* @return The combat system component. 战斗系统组件。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category = "GCS|Combat", Meta = (DefaultToSelf="Actor"))
static UGCS_CombatSystemComponent* GetCombatSystemComponent(const AActor* Actor);
/**
* Finds the combat system component for an actor.
* 查找演员的战斗系统组件。
* @param Actor The actor to query. 要查询的演员。
* @param CombatComponent The found component (output). 找到的组件(输出)。
* @return True if found. 如果找到返回true。
*/
UFUNCTION(BlueprintCallable, Category = "GCS|Combat", Meta = (DefaultToSelf="Actor", ExpandBoolAsExecs = "ReturnValue"))
static bool FindCombatSystemComponent(const AActor* Actor, UGCS_CombatSystemComponent*& CombatComponent);
/**
* Finds a typed combat system component for an actor.
* 查找演员的特定类型战斗系统组件。
* @param Actor The actor to query. 要查询的演员。
* @param DesiredClass The desired component class. 期望的组件类。
* @param Component The found component (output). 找到的组件(输出)。
* @return True if found. 如果找到返回true。
*/
UFUNCTION(BlueprintCallable, Category = "GCS|Combat", meta=(DefaultToSelf="Actor", DeterminesOutputType="DesiredClass", DynamicOutputParam="Component", ExpandBoolAsExecs="ReturnValue"))
static bool FindTypedCombatSystemComponent(AActor* Actor, TSubclassOf<UGCS_CombatSystemComponent> DesiredClass, UGCS_CombatSystemComponent*& Component);
/**
* Gets the combat flow for handling incoming attacks.
* 获取处理传入攻击的战斗流程。
* @return The combat flow instance. 战斗流程实例。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category = "GCS|Combat", meta=(DisplayName="Get Combat Flow"))
UGCS_CombatFlow* GetCombatFlow() const;
/**
* Registers an attack result.
* 注册攻击结果。
* @param Payload The attack result to register. 要注册的攻击结果。
*/
UFUNCTION(BlueprintCallable, Category="GCS|Combat")
void RegisterAttackResult(UPARAM(ref)
FGCS_AttackResult& Payload);
/**
* Gets the last processed attack result.
* 获取最后处理的攻击结果。
* @return The last attack result. 最后攻击结果。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category = "GCS|Combat")
FGCS_AttackResult GetLastProcessedAttackResult() const;
/**
* Sets the last processed attack result.
* 设置最后处理的攻击结果。
* @param Payload The attack result to set. 要设置的攻击结果。
*/
UFUNCTION(BlueprintCallable, Category = "GCS|Combat")
void SetLastProcessedAttackResult(const FGCS_AttackResult& Payload);
/**
* Plays a predictable montage for a target combat system component.
* 为目标战斗系统组件播放可预测的蒙太奇。
* @param TargetCSC The target combat system component. 目标战斗系统组件。
* @param Request The montage play request. 蒙太奇播放请求。
*/
UFUNCTION(BlueprintCallable, Category="GCS|Combat")
void PlayPredictableMontageForTarget(UGCS_CombatSystemComponent* TargetCSC, FGCS_PlayMontageRequest Request);
/**
* Server RPC to play a predictable montage for a target.
* 为目标播放可预测蒙太奇的服务器RPC。
* @param TargetCSC The target combat system component. 目标战斗系统组件。
* @param Request The montage play request. 蒙太奇播放请求。
*/
UFUNCTION(Server, Reliable, BlueprintCallable, Category="GCS|Combat")
void ServerPlayPredictableMontageForTarget(UGCS_CombatSystemComponent* TargetCSC, FGCS_PlayMontageRequest Request);
/**
* Sets the replicated montage information.
* 设置复制的蒙太奇信息。
* @param Request The montage play request. 蒙太奇播放请求。
*/
void SetReplicatedMontage(const FGCS_PlayMontageRequest& Request);
/**
* Timer handle for montage-related operations.
* 蒙太奇相关操作的计时器句柄。
*/
FTimerHandle TimerHandle;
/**
* Handles replication of montage information.
* 处理蒙太奇信息的复制。
*/
UFUNCTION()
void OnRep_ReplicatedMontageInfo();
/**
* Plays a predicted montage.
* 播放预测的蒙太奇。
* @param Request The montage play request. 蒙太奇播放请求。
*/
void PlayPredictedMontage(const FGCS_PlayMontageRequest& Request);
/**
* Gets the character's skeletal mesh component.
* 获取角色的骨骼网格组件。
* @return The skeletal mesh component. 骨骼网格组件。
*/
USkeletalMeshComponent* GetCharacterMeshComponent() const;
protected:
/**
* Handles pre-gameplay effect spec application.
* 处理游戏效果规格应用前逻辑。
* @param Spec The gameplay effect spec. 游戏效果规格。
* @param AbilitySystemComponent The ability system component. 能力系统组件。
*/
virtual void OnGlobalPreGameplayEffectSpecApply(FGameplayEffectSpec& Spec, UAbilitySystemComponent* AbilitySystemComponent) override;
/**
* Handles replication of the combat flow.
* 处理战斗流程的复制。
*/
UFUNCTION()
void OnRep_CombatFlow();
/**
* The class of the combat flow to instantiate.
* 要实例化的战斗流程类。
*/
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "GCS|Combat Settings")
TSubclassOf<UGCS_CombatFlow> CombatFlowClass;
/**
* The instantiated combat flow.
* 实例化的战斗流程。
*/
UPROPERTY(VisibleAnywhere, ReplicatedUsing=OnRep_CombatFlow, Category = "GCS|Combat State", meta=(ShowInnerProperties))
TObjectPtr<UGCS_CombatFlow> CombatFlow;
/**
* The last attack result processed by the combat flow.
* 战斗流程处理的最后攻击结果。
*/
UPROPERTY(VisibleAnywhere, Category = "GCS|Combat State")
FGCS_AttackResult LastProcessedAttackResult;
/**
* Container for attack results.
* 攻击结果容器。
*/
UPROPERTY(VisibleAnywhere, Replicated, Category="GCS|Combat State")
FGCS_AttackResultContainer AttackResultContainer;
/**
* Replicated montage information.
* 复制的蒙太奇信息。
*/
UPROPERTY(VisibleAnywhere, ReplicatedUsing=OnRep_ReplicatedMontageInfo, Category = "GCS|Combat State")
FGCS_ReplicatedMontageInfo ReplicatedMontageInfo;
/**
* Predicted montage information.
* 预测的蒙太奇信息。
*/
UPROPERTY(VisibleAnywhere, Category = "GCS|Combat State")
FGCS_PredictedMontageInfo PredictedMontageInfo;
#pragma region Combo System
public:
/**
* Get the current combo step.
* @return The current combo step.
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GMS|Combat")
int32 GetComboStep() const;
UFUNCTION(BlueprintCallable, Category="GCS|Combat")
void UpdateComboStep(int32 NewComboStep);
UFUNCTION(BlueprintCallable, Category="GCS|Combat")
virtual void ResetComboState();
/**
* Event for combo step changed.
* 连击步骤变更事件。
*/
UPROPERTY(BlueprintAssignable, Category="Event")
FGCS_ComboStepChangedEventSignature OnComboStepChangedEvent;
private:
void UpdateComboStep(int32 NewComboStep, bool bSendRpc);
UFUNCTION()
void OnReplicated_ComboStep(int32 PrevComboStep);
/**
* Client RPC to set the combo step.
* 客户端RPC设置运动集。
* @param NewComboStep combo step. 新运动集。
*/
UFUNCTION(Client, Reliable, WithValidation)
void ClientUpdateComboStep(int32 NewComboStep);
/**
* Server RPC to set the combo step.
* 服务器RPC设置运动集。
* @param NewComboStep The new combo step. 新运动集。
*/
UFUNCTION(Server, Reliable, WithValidation)
void ServerUpdateComboStep(int32 NewComboStep);
protected:
virtual bool ClientUpdateComboStep_Validate(int32 NewComboStep);
virtual bool ServerUpdateComboStep_Validate(int32 NewComboStep);
UFUNCTION(BlueprintNativeEvent, Category="GMS|Combat")
void OnComboStepChanged(int32 PrevComboStep);
virtual void OnComboStepChanged_Implementation(int32 PrevComboStep);
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, ReplicatedUsing=OnReplicated_ComboStep, Category = "GCS|Combat State")
int32 ComboStep{0};
private:
#pragma endregion
};

View File

@@ -0,0 +1,40 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Engine/DeveloperSettings.h"
#include "GCS_CombatSystemSettings.generated.h"
/**
* Settings for the combat system.
* 战斗系统的设置。
*/
UCLASS(Config=Game, DefaultConfig)
class GENERICCOMBATSYSTEM_API UGCS_CombatSystemSettings : public UDeveloperSettings
{
GENERATED_BODY()
public:
/**
* Gets the combat system settings instance.
* 获取战斗系统设置实例。
* @return The combat system settings. 战斗系统设置。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GCS")
static const UGCS_CombatSystemSettings* Get();
/**
* Tag name for querying the main skeletal mesh component.
* 查询主要骨骼网格组件的标签名称。
*/
UPROPERTY(Config, EditAnywhere, BlueprintReadOnly, NoClear, Category="Common", meta=(DisplayName="Main Mesh Lookup Tag Name"))
FName CharacterMeshLookupTag{TEXT("Main")};
/**
* Disables affiliation checks for debugging (allows cross-team damage).
* 禁用归属检查以进行调试(允许跨队伍伤害)。
*/
UPROPERTY(Config, EditAnywhere, BlueprintReadOnly, NoClear, Category="Debug")
bool bDisableAffiliationCheck{false};
};

View File

@@ -0,0 +1,105 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GameplayEffectTypes.h"
#include "GameplayTagContainer.h"
#include "GGA_AbilitySystemStructLibrary.h"
#include "UObject/Interface.h"
#include "GCS_EffectCauserInterface.generated.h"
class UGameplayEffect;
/**
* Interface for objects that cause gameplay effects based on combat impact.
* 基于战斗影响产生游戏效果的对象的接口。
*/
UINTERFACE(MinimalAPI, BlueprintType, Blueprintable)
class UGCS_EffectCauserInterface : public UInterface
{
GENERATED_BODY()
};
/**
* Interface for effect causers (e.g., bullets, weapons, traps).
* 效果触发者(例如子弹、武器、陷阱)的接口。
*/
class GENERICCOMBATSYSTEM_API IGCS_EffectCauserInterface
{
GENERATED_BODY()
public:
/**
* Gets a pre-existing gameplay effect spec handle.
* 获取预存在的游戏效果规格句柄。
* @param OutHandle The effect spec handle (output). 效果规格句柄(输出)。
* @return True if a handle is provided. 如果提供句柄返回true。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GCS|Combat")
bool GetEffectSpecHandle(FGameplayEffectSpecHandle& OutHandle);
virtual bool GetEffectSpecHandle_Implementation(FGameplayEffectSpecHandle& OutHandle) = 0;
/**
* Gets the effect container.
* 获取效果容器。
* @return The effect container. 效果容器。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GCS|Combat")
FGGA_GameplayEffectContainer GetEffectContainer();
virtual FGGA_GameplayEffectContainer GetEffectContainer_Implementation() const = 0;
/**
* Gets the effect container level override.
* 获取效果容器等级覆盖。
* @return The level override. 等级覆盖。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GCS|Combat")
int32 GetEffectContainerLevelOverride() const;
virtual int32 GetEffectContainerLevelOverride_Implementation() const = 0;
/**
* Sets the effect container spec.
* 设置效果容器规格。
* @param InEffectContainerSpec The effect container spec. 效果容器规格。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GCS|Combat")
void SetEffectContainerSpec(const FGGA_GameplayEffectContainerSpec& InEffectContainerSpec);
virtual void SetEffectContainerSpec_Implementation(const FGGA_GameplayEffectContainerSpec& InEffectContainerSpec) = 0;
/**
* Gets the effect container spec.
* 获取效果容器规格。
* @return The effect container spec. 效果容器规格。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GCS|Combat")
FGGA_GameplayEffectContainerSpec GetEffectContainerSpec() const;
virtual FGGA_GameplayEffectContainerSpec GetEffectContainerSpec_Implementation() const = 0;
/**
* Gets the gameplay effect class.
* 获取游戏效果类。
* @return The gameplay effect class. 游戏效果类。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GCS|Combat")
TSubclassOf<UGameplayEffect> GetEffectClass() const;
virtual TSubclassOf<UGameplayEffect> GetEffectClass_Implementation() const = 0;
/**
* Gets the effect level.
* 获取效果等级。
* @return The effect level. 效果等级。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GCS|Combat")
int32 GetEffectLevel() const;
virtual int32 GetEffectLevel_Implementation() const = 0;
/**
* Sets the gameplay effect spec for later use.
* 设置游戏效果规格以供后续使用。
* @param InEffectSpec The effect spec to set. 要设置的效果规格。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GCS|Combat")
void SetEffectSpec(UPARAM(ref) FGameplayEffectSpecHandle& InEffectSpec);
virtual void SetEffectSpec_Implementation(FGameplayEffectSpecHandle& InEffectSpec) = 0;
};

View File

@@ -0,0 +1,14 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "UObject/Object.h"
#include "NativeGameplayTags.h"
namespace GCS_BulletLaunch
{
GENERICCOMBATSYSTEM_API UE_DECLARE_GAMEPLAY_TAG_EXTERN(Always)
GENERICCOMBATSYSTEM_API UE_DECLARE_GAMEPLAY_TAG_EXTERN(DidNotHitPawn)
GENERICCOMBATSYSTEM_API UE_DECLARE_GAMEPLAY_TAG_EXTERN(HitPawn)
}

View File

@@ -0,0 +1,50 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "UObject/Object.h"
DECLARE_STATS_GROUP(TEXT("GCS"), STATGROUP_GCS, STATCAT_Advanced)
GENERICCOMBATSYSTEM_API DECLARE_LOG_CATEGORY_EXTERN(LogGCS, Log, All)
GENERICCOMBATSYSTEM_API DECLARE_LOG_CATEGORY_EXTERN(LogGCS_Targeting, Log, All)
GENERICCOMBATSYSTEM_API DECLARE_LOG_CATEGORY_EXTERN(LogGCS_Collision, Log, All)
GENERICCOMBATSYSTEM_API DECLARE_LOG_CATEGORY_EXTERN(LogGCS_Trace, Log, All)
/**
* Gets the context string for logging purposes.
* 获取用于日志记录的上下文字符串。
* @param ContextObject The object providing the context (optional). 提供上下文的对象(可选)。
* @return The context string. 上下文字符串。
*/
GENERICCOMBATSYSTEM_API FString GetGCSLogContextString(const UObject* ContextObject = nullptr);
GENERICCOMBATSYSTEM_API FString GetClientServerContextString(UObject* ContextObject = nullptr);
#define GCS_LOG(Verbosity, Format, ...) \
{ \
UE_LOG(LogGCS, Verbosity, TEXT("%S: %s"),__FUNCTION__, *FString::Printf(TEXT(Format), ##__VA_ARGS__)) \
}
#define GCS_CLOG(Verbosity, Format, ...) \
{ \
UE_LOG(LogGCS, Verbosity, TEXT("%S: ctx(%s) %s"),__FUNCTION__, *GetGCSLogContextString(this), *FString::Printf(TEXT(Format), ##__VA_ARGS__)) \
}
#define GCS_CLOG_Trace(Verbosity, Format, ...) \
{ \
UE_LOG(LogGCS, Verbosity, TEXT("%S: ctx(%s) %s"),__FUNCTION__, *GetGCSLogContextString(this), *FString::Printf(TEXT(Format), ##__VA_ARGS__)) \
}
#define GCS_OWNED_CLOG(LogOwner,Verbosity, Format, ...) \
{ \
UE_LOG(LogGCS, Verbosity, TEXT("%S: ctx(%s) %s"),__FUNCTION__, *GetGCSLogContextString(LogOwner), *FString::Printf(TEXT(Format), ##__VA_ARGS__)) \
}
#define GCS_VLOG(Verbosity, Format, ...) UE_VLOG(GetOwner(), LogGAIS_Command, Verbosity, Format, ##__VA_ARGS__)

View File

@@ -0,0 +1,12 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Modules/ModuleManager.h"
class FGenericCombatSystemModule : public IModuleInterface
{
public:
virtual void StartupModule() override;
virtual void ShutdownModule() override;
};

View File

@@ -0,0 +1,47 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Animation/AnimNotifies/AnimNotifyState.h"
#include "GCS_ANS_AttackTrace.generated.h"
class UGCS_AttackRequest_Melee;
/**
* Animation notify state for melee attack tracing.
* 近战攻击追踪的动画通知状态。
*/
UCLASS(BlueprintType, Blueprintable, HideDropdown)
class GENERICCOMBATSYSTEM_API UGCS_ANS_AttackTrace : public UAnimNotifyState
{
GENERATED_BODY()
protected:
/**
* Default constructor.
* 默认构造函数。
*/
UGCS_ANS_AttackTrace(const FObjectInitializer& ObjectInitializer);
/**
* Called after properties are initialized.
* 属性初始化后调用。
*/
virtual void PostInitProperties() override;
/**
* The melee attack request instance.
* 近战攻击请求实例。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Instanced, Category=Parameters)
TObjectPtr<UGCS_AttackRequest_Melee> AttackRequest;
#if WITH_EDITORONLY_DATA
/**
* Called before saving to validate data.
* 保存前调用以验证数据。
*/
virtual void PreSave(FObjectPreSaveContext SaveContext) override;
#endif
};

View File

@@ -0,0 +1,50 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Animation/AnimNotifies/AnimNotifyState.h"
#include "GCS_ANS_BulletTrace.generated.h"
class UGCS_AttackRequest_Bullet;
class UTargetingPreset;
/**
* Animation notify state for bullet attack tracing.
* 子弹攻击追踪的动画通知状态。
*/
UCLASS(BlueprintType, Blueprintable, HideDropdown)
class GENERICCOMBATSYSTEM_API UGCS_ANS_BulletTrace : public UAnimNotifyState
{
GENERATED_BODY()
public:
/**
* Default constructor.
* 默认构造函数。
*/
UGCS_ANS_BulletTrace(const FObjectInitializer& ObjectInitializer);
/**
* The bullet attack request instance.
* 子弹攻击请求实例。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Instanced, Category=Parameters)
TObjectPtr<UGCS_AttackRequest_Bullet> AttackRequest;
#if WITH_EDITOR
/**
* Validates data for the notify.
* 验证通知数据。
* @param Context The validation context. 验证上下文。
* @return The validation result. 验证结果。
*/
virtual EDataValidationResult IsDataValid(FDataValidationContext& Context) const override;
/**
* Called before saving to validate data.
* 保存前调用以验证数据。
*/
virtual void PreSave(FObjectPreSaveContext SaveContext) override;
#endif
};

View File

@@ -0,0 +1,74 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Animation/AnimNotifies/AnimNotify.h"
#include "Animation/AnimNotifies/AnimNotifyState.h"
#include "GCS_ANS_MovementCancellation.generated.h"
/**
* Animation notify state to disable montage root motion when moving.
* 当角色移动时禁用蒙太奇根运动的动画通知状态。
*/
UCLASS(BlueprintType, Blueprintable, Abstract, HideDropdown)
class GENERICCOMBATSYSTEM_API UGCS_ANS_MovementCancellation : public UAnimNotifyState
{
GENERATED_BODY()
public:
/**
* Default constructor.
* 默认构造函数。
*/
UGCS_ANS_MovementCancellation(const FObjectInitializer& ObjectInitializer);
/**
* Called when the notify begins.
* 通知开始时调用。
* @param BranchingPointPayload The notify payload. 通知载荷。
*/
virtual void BranchingPointNotifyBegin(FBranchingPointNotifyPayload& BranchingPointPayload) override;
/**
* Called each frame during the notify.
* 通知期间每帧调用。
* @param BranchingPointPayload The notify payload. 通知载荷。
* @param FrameDeltaTime Time since last frame. 上一帧以来的时间。
*/
virtual void BranchingPointNotifyTick(FBranchingPointNotifyPayload& BranchingPointPayload, float FrameDeltaTime) override;
/**
* Called when the notify ends.
* 通知结束时调用。
* @param BranchingPointPayload The notify payload. 通知载荷。
*/
virtual void BranchingPointNotifyEnd(FBranchingPointNotifyPayload& BranchingPointPayload) override;
protected:
/**
* Checks if the skeletal mesh is moving.
* 检查骨骼网格是否在移动。
* @param MeshComp The skeletal mesh component. 骨骼网格组件。
* @return True if moving. 如果在移动返回true。
*/
UFUNCTION(BlueprintNativeEvent)
bool IsMoving(USkeletalMeshComponent* MeshComp) const;
virtual bool IsMoving_Implementation(USkeletalMeshComponent* MeshComp) const;
/**
* Indicates if root motion is disabled.
* 表示根运动是否被禁用。
*/
bool IsRootMotionDisabled{false};
#if WITH_EDITOR
/**
* Checks if the notify can be placed on an animation.
* 检查通知是否可以放置在动画上。
* @param Animation The animation sequence. 动画序列。
* @return True if valid. 如果有效返回true。
*/
virtual bool CanBePlaced(UAnimSequenceBase* Animation) const override;
#endif
};

View File

@@ -0,0 +1,74 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Perception/AIPerceptionTypes.h"
#include "Tasks/TargetingFilterTask_BasicFilterTemplate.h"
#include "GCS_TargetingFilterTask_Affiliation.generated.h"
/**
* Filters targets based on team affiliation.
* 根据队伍归属过滤目标。
*/
UCLASS(meta=(DisplayName="GCS:FilterTask (Affiliation)"))
class GENERICCOMBATSYSTEM_API UGCS_TargetingFilterTask_Affiliation : public UTargetingFilterTask_BasicFilterTemplate
{
GENERATED_BODY()
protected:
/**
* Affiliation filter settings.
* 归属过滤设置。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Filter")
FAISenseAffiliationFilter DetectionByAffiliation;
/**
* Whether to check for CombatTeamAgentInterface.
* 是否检查CombatTeamAgentInterface。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Filter")
bool bLookCombatTeamAgentInterface{true};
/**
* Whether to check for GenericTeamAgentInterface.
* 是否检查GenericTeamAgentInterface。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Filter")
bool bLookGenericTeamAgentInterface{true};
/**
* Whether to ignore target actor who has no team assigned(teamId:255)
* 是否忽略没有队伍的目标即TeamId为255
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Filter")
bool bIgnoreTargetWithNoTeam{true};
/**
* Determines if a target should be filtered based on affiliation.
* 根据归属确定是否应过滤目标。
* @param TargetingHandle The targeting request handle. 目标请求句柄。
* @param TargetData The target data. 目标数据。
* @return True if the target should be filtered. 如果应过滤目标返回true。
*/
virtual bool ShouldFilterTarget(const FTargetingRequestHandle& TargetingHandle, const FTargetingDefaultResultData& TargetData) const override;
/**
* Gets the source team ID.
* 获取来源队伍ID。
* @param TargetingHandle The targeting request handle. 目标请求句柄。
* @param TargetData The target data. 目标数据。
* @return The source team ID. 来源队伍ID。
*/
virtual FGenericTeamId GetSourceTeamId(const FTargetingRequestHandle& TargetingHandle, const FTargetingDefaultResultData& TargetData) const;
/**
* Gets the target team ID.
* 获取目标队伍ID。
* @param TargetingHandle The targeting request handle. 目标请求句柄。
* @param TargetData The target data. 目标数据。
* @return The target team ID. 目标队伍ID。
*/
virtual FGenericTeamId GetTargetTeamId(const FTargetingRequestHandle& TargetingHandle, const FTargetingDefaultResultData& TargetData) const;
};

View File

@@ -0,0 +1,27 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Tasks/TargetingFilterTask_BasicFilterTemplate.h"
#include "GCS_TargetingFilterTask_IsDead.generated.h"
/**
* Filters out dead targets.
* 过滤掉已死亡的目标。
*/
UCLASS(meta=(DisplayName="GCS:FilterTask (IsDead)"))
class GENERICCOMBATSYSTEM_API UGCS_TargetingFilterTask_IsDead : public UTargetingFilterTask_BasicFilterTemplate
{
GENERATED_BODY()
protected:
/**
* Determines if a target should be filtered based on death state.
* 根据死亡状态确定是否应过滤目标。
* @param TargetingHandle The targeting request handle. 目标请求句柄。
* @param TargetData The target data. 目标数据。
* @return True if the target is dead and should be filtered. 如果目标已死亡且应过滤返回true。
*/
virtual bool ShouldFilterTarget(const FTargetingRequestHandle& TargetingHandle, const FTargetingDefaultResultData& TargetData) const override;
};

View File

@@ -0,0 +1,50 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GameplayTagContainer.h"
#include "Tasks/TargetingFilterTask_BasicFilterTemplate.h"
#include "GCS_TargetingFilterTask_TagsRequirements.generated.h"
/**
* Filters targets based on a gameplay tag query.
* 根据游戏标签查询过滤目标。
*/
UCLASS(meta=(DisplayName="GCS:FilterTask (TagsRequirements)"))
class GENERICCOMBATSYSTEM_API UGCS_TargetingFilterTask_TagsRequirements : public UTargetingFilterTask_BasicFilterTemplate
{
GENERATED_BODY()
protected:
/**
* Whether to invert the filter result.
* 是否反转过滤结果。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Filter")
bool bInvert{false};
/**
* The tag query that targets must match.
* 目标必须匹配的标签查询。
* @note If empty, no filtering is applied. 如果为空,不应用过滤。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Filter", meta = (DisplayName = "Query Must Match"))
FGameplayTagQuery TagQuery;
/**
* Whether to fall back to GameplayTagAssetInterface if AbilitySystemComponent fails.
* 如果AbilitySystemComponent失败是否回退到GameplayTagAssetInterface。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Filter")
bool bLookingForTagAssetInterface{false};
/**
* Determines if a target should be filtered.
* 确定是否应过滤目标。
* @param TargetingHandle The targeting request handle. 目标请求句柄。
* @param TargetData The target data. 目标数据。
* @return True if the target should be filtered. 如果应过滤目标返回true。
*/
virtual bool ShouldFilterTarget(const FTargetingRequestHandle& TargetingHandle, const FTargetingDefaultResultData& TargetData) const override;
};

View File

@@ -0,0 +1,29 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Tasks/TargetingFilterTask_BasicFilterTemplate.h"
#include "GCS_TargetingFilterTask_TraceInstance.generated.h"
/**
* Filters targets based on the CanHitActor check of a collision trace instance.
* 根据碰撞检测实例的CanHitActor检查过滤目标。
* @note Requires SourceObject to be a collision trace instance.
* @注意 需要SourceObject是碰撞检测实例。
*/
UCLASS(meta=(DisplayName="GCS:Filter Task (TraceInstance CanHitActor)"))
class GENERICCOMBATSYSTEM_API UGCS_TargetingFilterTask_TraceInstance : public UTargetingFilterTask_BasicFilterTemplate
{
GENERATED_BODY()
protected:
/**
* Determines if a target should be filtered.
* 确定是否应过滤目标。
* @param TargetingHandle The targeting request handle. 目标请求句柄。
* @param TargetData The target data. 目标数据。
* @return True if the target should be filtered. 如果应过滤目标返回true。
*/
virtual bool ShouldFilterTarget(const FTargetingRequestHandle& TargetingHandle, const FTargetingDefaultResultData& TargetData) const override;
};

View File

@@ -0,0 +1,59 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Abilities/GameplayAbilityTargetTypes.h"
#include "Kismet/BlueprintFunctionLibrary.h"
#include "Types/TargetingSystemTypes.h"
#include "GCS_TargetingFunctionLibrary.generated.h"
/**
* Extended library for targeting system utilities.
* 目标系统实用程序的扩展库。
*/
UCLASS()
class GENERICCOMBATSYSTEM_API UGCS_TargetingFunctionLibrary : public UBlueprintFunctionLibrary
{
GENERATED_BODY()
public:
/**
* Gets the targeting source context for a targeting request handle.
* 获取目标请求句柄的目标源上下文。
* @param TargetingHandle The targeting request handle. 目标请求句柄。
* @return The targeting source context. 目标源上下文。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category = "GCS|Targeting System | Targeting Types")
static FTargetingSourceContext GetTargetingSourceContext(FTargetingRequestHandle TargetingHandle);
UFUNCTION(BlueprintCallable, BlueprintPure, Category = "GCS|Targeting System | Targeting Types")
static FString GetTargetingSourceContextDebugString(FTargetingRequestHandle TargetingHandle);
/**
* Gets the actor targets from a targeting request handle.
* 从目标请求句柄获取Actor目标。
* @param TargetingHandle The targeting request handle. 目标请求句柄。
* @param Targets The actor targets (output). Actor目标输出
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category = "GCS|Targeting System | Targeting Results")
static void GetTargetingResultsActors(FTargetingRequestHandle TargetingHandle, TArray<AActor*>& Targets);
/**
* Gets the hit results for a targeting handle.
* 获取目标句柄的命中结果。
* @param TargetingHandle The targeting request handle. 目标请求句柄。
* @param OutTargets The hit results (output). 命中结果(输出)。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category = "GCS|Targeting System | Targeting Results")
static void GetTargetingResults(FTargetingRequestHandle TargetingHandle, TArray<FHitResult>& OutTargets);
/**
* Converts targeting location info to a source context.
* 将目标位置信息转换为源上下文。
* @param LocationInfo The targeting location info. 目标位置信息。
* @return The targeting source context. 目标源上下文。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category = "GCS|Targeting System")
static FTargetingSourceContext ConvertTargetingLocationInfoToSourceContext(FGameplayAbilityTargetingLocationInfo LocationInfo);
};

View File

@@ -0,0 +1,77 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "UObject/Interface.h"
#include "GCS_TargetingSourceInterface.generated.h"
/**
* Interface for objects providing targeting system information.
* 为目标系统提供信息的对象的接口。
* @note Used to provide additional targeting data.
* @注意 用于提供额外的目标数据。
*/
UINTERFACE(MinimalAPI, BlueprintType, Blueprintable)
class UGCS_TargetingSourceInterface : public UInterface
{
GENERATED_BODY()
};
/**
* Interface for targeting source objects.
* 目标源对象的接口。
*/
class GENERICCOMBATSYSTEM_API IGCS_TargetingSourceInterface
{
GENERATED_BODY()
public:
/**
* Gets the trace level for dynamic tracing.
* 获取动态追踪的追踪级别。
* @return The trace level. 追踪级别。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GCS|Trace")
float GetTraceLevel() const;
virtual float GetTraceLevel_Implementation() const = 0;
/**
* Gets the trace direction for targeting.
* 获取目标的追踪方向。
* @param OutDirection The trace direction (output). 追踪方向(输出)。
* @return True if a direction is provided. 如果提供方向返回true。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GCS|Trace")
bool GetTraceDirection(FVector& OutDirection) const;
virtual bool GetTraceDirection_Implementation(FVector& OutDirection) const = 0;
/**
* Gets the swept trace rotation for capsule or box traces.
* 获取胶囊或盒体追踪的旋转。
* @param OutRotation The rotation (output). 旋转(输出)。
* @return True if a rotation is provided. 如果提供旋转返回true。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category = "GCS|Trace")
bool GetSweptTraceRotation(FRotator& OutRotation) const;
virtual bool GetSweptTraceRotation_Implementation(FRotator& OutRotation) const = 0;
/**
* Gets the shape component for trace properties.
* 获取追踪属性的形状组件。
* @param OutShape The shape component (output). 形状组件(输出)。
* @return True if a shape component is provided. 如果提供形状组件返回true。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GCS|Trace")
bool GetTraceShape(UShapeComponent*& OutShape) const;
virtual bool GetTraceShape_Implementation(UShapeComponent*& OutShape) const = 0;
/**
* Gets additional actors to ignore during tracing.
* 获取追踪期间忽略的额外Actor。
* @return Array of actors to ignore. 忽略的Actor数组。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GCS|Trace")
TArray<AActor*> GetAdditionalActorsToIgnore() const;
virtual TArray<AActor*> GetAdditionalActorsToIgnore_Implementation() const = 0;
};

View File

@@ -0,0 +1,248 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Components/PawnComponent.h"
#include "GCS_TargetingSystemComponent.generated.h"
class UTargetingPreset;
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FGCS_OnTargetLockOnSignature, AActor*, NewTargetActor);
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FGCS_OnTargetLockOffSignature, AActor*, PrevTargetActor);
/**
* Component for managing combat targeting.
* 管理战斗目标的组件。
*/
UCLASS(ClassGroup=(GCS), AutoExpandCategories=("GCS"), meta=(BlueprintSpawnableComponent), Blueprintable)
class GENERICCOMBATSYSTEM_API UGCS_TargetingSystemComponent : public UPawnComponent
{
GENERATED_BODY()
public:
/**
* Default constructor.
* 默认构造函数。
*/
UGCS_TargetingSystemComponent(const FObjectInitializer& ObjectInitializer);
/**
* Gets the targeting system component from an actor.
* 从Actor获取目标系统组件。
* @param Actor The actor to query. 要查询的Actor。
* @return The targeting system component. 目标系统组件。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category = "GCS|Targeting", Meta = (DefaultToSelf="Actor"))
static UGCS_TargetingSystemComponent* GetTargetingSystemComponent(const AActor* Actor);
/**
* Retrieves lifetime replicated properties.
* 获取生命周期复制属性。
* @param OutLifetimeProps The lifetime properties. 生命周期属性。
*/
virtual void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const override;
protected:
/**
* Called when the game starts.
* 游戏开始时调用。
*/
virtual void BeginPlay() override;
/**
* The currently targeted actor.
* 当前目标Actor。
*/
UPROPERTY(VisibleInstanceOnly, BlueprintReadWrite, Replicated, Category = "GCS|Targeting")
TObjectPtr<AActor> TargetedActor = nullptr;
/**
* List of potential target actors (server-side only).
* 潜在目标Actor列表仅限服务器
*/
UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = "GCS|Targeting", meta=(AllowPrivateAccess=true))
TArray<TObjectPtr<AActor>> PotentialTargets;
/**
* Whether to automatically update potential targets based on tick rate.
* 是否根据tick频率自动更新潜在目标。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "GCS|Targeting", meta=(AllowPrivateAccess=true))
bool bAutoUpdatePotentialTargets{true};
/**
* Targeting preset for searching and filtering targets.
* 用于搜索和过滤目标的目标预设。
* @note The component's owner is the SourceActor, and the component is the SourceObject.
* @注意 组件的Owner作为SourceActor组件本身作为SourceObject。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "GCS|Targeting", meta=(AllowPrivateAccess=true))
TObjectPtr<UTargetingPreset> TargetingPreset;
/**
* Flag to indicate we should be using async targeting
* 是否使用异步定位?
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "GCS|Targeting", meta=(AllowPrivateAccess=true))
bool bUseAsyncTargeting{true};
public:
/**
* Called every frame.
* 每帧调用。
* @param DeltaTime Time since last frame. 上一帧以来的时间。
* @param TickType The type of tick. tick类型。
* @param ThisTickFunction The tick function. tick函数。
*/
virtual void TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) override;
/**
* Refreshes targeting based on the delta time.
* 根据时间增量刷新目标。
* @param DeltaTime Time since last frame. 上一帧以来的时间。
*/
virtual void RefreshTargeting(float DeltaTime);
/**
* Forces collection of potential targets and selects the best one.
* 强制收集潜在目标并选择最佳目标。
*/
UFUNCTION(BlueprintCallable, Category = "GCS|Targeting")
void SearchForActorToTarget();
/**
* Selects the closest actor from potential targets within a radius.
* 从潜在目标中选择指定范围内最近的Actor。
* @param Radius The search radius. 搜索半径。
* @return The closest actor. 最近的Actor。
*/
UFUNCTION(BlueprintCallable, Category = "GCS|Targeting")
AActor* SelectClosestActorFromPotentialTargets(float Radius = 100) const;
/**
* Filters actors using a targeting preset.
* 使用目标预设过滤Actor。
* @param InTargetingPreset The targeting preset. 目标预设。
* @param InTargets The input targets. 输入目标。
* @param OutActors The filtered actors (output). 过滤后的Actor输出
* @return True if filtering succeeded. 如果过滤成功返回true。
*/
UFUNCTION(BlueprintCallable, Category = "GCS|Targeting", meta=(ExpandBoolAsExecs="ReturnValue"))
bool FilterActorsWithPreset(UTargetingPreset* InTargetingPreset, const TArray<AActor*> InTargets, TArray<AActor*>& OutActors);
/**
* Selects a target from potential targets.
* 从潜在目标中选择一个目标。
*/
virtual void SelectFromPotentialTargets();
/**
* Switches to a new target based on direction.
* 根据方向切换到新目标。
* @param RightDirection Whether to switch to the right. 是否向右切换。
*/
UFUNCTION(BlueprintCallable, Category = "GCS|Targeting")
void StaticSwitchToNewTarget(bool RightDirection);
/**
* Refreshes the list of potential targets using the targeting preset.
* 使用目标预设刷新潜在目标列表。
*/
virtual void RefreshPotentialTargets();
/**
* Checks if an actor can be targeted.
* 检查Actor是否可以被目标。
* @param ActorToTarget The actor to check. 要检查的Actor。
* @return True if the actor can be targeted. 如果Actor可被目标返回true。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category = "GCS|Targeting")
bool CanBeTargeted(AActor* ActorToTarget);
virtual bool CanBeTargeted_Implementation(AActor* ActorToTarget);
/**
* Gets the currently targeted actor.
* 获取当前目标Actor。
* @return The targeted actor. 目标Actor。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category = "GCS|Targeting")
FORCEINLINE AActor* GetTargetedActor() { return TargetedActor; }
/**
* Sets the targeted actor.
* 设置目标Actor。
* @param NewActor The new target actor. 新目标Actor。
*/
UFUNCTION(BlueprintCallable, Category = "GCS|Targeting")
void SetTargetedActor(AActor* NewActor);
private:
/**
* Sets the targeted actor with optional RPC.
* 设置目标Actor可选择是否发送RPC。
* @param NewActor The new target actor. 新目标Actor。
* @param bSendRpc Whether to send RPC. 是否发送RPC。
*/
void SetTargetedActor(AActor* NewActor, bool bSendRpc);
/**
* Client RPC to set the targeted actor.
* 设置目标Actor的客户端RPC。
* @param NewActor The new target actor. 新目标Actor。
*/
UFUNCTION(Client, Reliable)
void ClientSetTargetedActor(AActor* NewActor);
virtual void ClientSetTargetedActor_Implementation(AActor* NewActor);
/**
* Server RPC to set the targeted actor.
* 设置目标Actor的服务器RPC。
* @param NewActor The new target actor. 新目标Actor。
*/
UFUNCTION(Server, Reliable)
void ServerSetTargetedActor(AActor* NewActor);
virtual void ServerSetTargetedActor_Implementation(AActor* NewActor);
protected:
/**
* Handles target lock-off events.
* 处理目标解锁事件。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category = "GCS|Targeting")
void OnLockOff();
virtual void OnLockOff_Implementation();
/**
* Handles target lock-on events.
* 处理目标锁定事件。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category = "GCS|Targeting")
void OnLockOn();
virtual void OnLockOn_Implementation();
/**
* Delegate for target lock-on events.
* 目标锁定事件的委托。
*/
UPROPERTY(BlueprintAssignable, Category="GCS|Targeting")
FGCS_OnTargetLockOnSignature OnTargetLockOnEvent;
/**
* Delegate for target lock-off events.
* 目标解锁事件的委托。
*/
UPROPERTY(BlueprintAssignable, Category="GCS|Targeting")
FGCS_OnTargetLockOffSignature OnTargetLockOffEvent;
/**
* Calculates the view angle to a target actor.
* 计算到目标Actor的视角角度。
* @param TargetActor The target actor. 目标Actor。
* @return The view angle. 视角角度。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category = "GCS|Targeting")
virtual float CalculateViewAngle(const AActor* TargetActor);
};

View File

@@ -0,0 +1,132 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CollisionShape.h"
#include "Engine/CollisionProfile.h"
#include "Types/TargetingSystemTypes.h"
#include "ScalableFloat.h"
#include "Tasks/TargetingTask.h"
#include "UObject/Object.h"
#include "GCS_TargetingSelectionTask_LineTrace.generated.h"
class UTargetingSubsystem;
struct FCollisionQueryParams;
struct FTargetingDebugInfo;
struct FTargetingDefaultResultData;
struct FTargetingRequestHandle;
struct FTraceDatum;
struct FTraceHandle;
/**
* @class UGCS_TargetingSelectionTask_LineTrace
* Selection task that can perform a synchronous or asynchronous line trace, always generate hit results.
* to find all targets up to the first blocking hit (or its end point).
*/
UCLASS(Blueprintable, meta=(DisplayName="GCS:SelectionTask (Line Trace)"))
class GENERICCOMBATSYSTEM_API UGCS_TargetingSelectionTask_LineTrace : public UTargetingTask
{
GENERATED_BODY()
public:
UGCS_TargetingSelectionTask_LineTrace(const FObjectInitializer& ObjectInitializer);
/** Evaluation function called by derived classes to process the targeting request */
virtual void Execute(const FTargetingRequestHandle& TargetingHandle) const override;
protected:
/** Native Event to get the source location for the Trace */
UFUNCTION(BlueprintCallable, BlueprintPure, BlueprintCallable, BlueprintPure, BlueprintNativeEvent, Category = "Target Trace Selection")
FVector GetSourceLocation(const FTargetingRequestHandle& TargetingHandle) const;
/** Native Event to get a source location offset for the Trace */
UFUNCTION(BlueprintCallable, BlueprintPure, BlueprintNativeEvent, Category = "Target Trace Selection")
FVector GetSourceOffset(const FTargetingRequestHandle& TargetingHandle) const;
/**
* Native Event to get the direction for the Trace
* Default will use pawn's control rotation or fallback to actor forward direction.
*/
UFUNCTION(BlueprintCallable, BlueprintPure, BlueprintNativeEvent, Category = "Target Trace Selection")
FVector GetTraceDirection(const FTargetingRequestHandle& TargetingHandle) const;
/** Native Event to get the length for the Trace */
UFUNCTION(BlueprintCallable, BlueprintPure, BlueprintNativeEvent, Category = "Target Trace Selection")
float GetTraceLength(const FTargetingRequestHandle& TargetingHandle) const;
UFUNCTION(BlueprintCallable, BlueprintPure, BlueprintNativeEvent, Category = "Target Trace Selection")
float GetTraceLevel(const FTargetingRequestHandle& TargetingHandle) const;
/** Native Event to get additional actors the Trace should ignore */
UFUNCTION(BlueprintCallable, BlueprintPure, BlueprintNativeEvent, Category = "Target Trace Selection")
void GetAdditionalActorsToIgnore(const FTargetingRequestHandle& TargetingHandle, TArray<AActor*>& OutAdditionalActorsToIgnore) const;
protected:
/** Method to process the trace task immediately */
void ExecuteImmediateTrace(const FTargetingRequestHandle& TargetingHandle) const;
/** Method to process the trace task asynchronously */
void ExecuteAsyncTrace(const FTargetingRequestHandle& TargetingHandle) const;
/** Callback for an async trace */
void HandleAsyncTraceComplete(const FTraceHandle& InTraceHandle, FTraceDatum& InTraceDatum, FTargetingRequestHandle TargetingHandle) const;
/** Method to take the hit results and store them in the targeting result data */
void ProcessHitResults(const FTargetingRequestHandle& TargetingHandle, const TArray<FHitResult>& Hits) const;
/** Setup CollisionQueryParams for the trace */
void InitCollisionParams(const FTargetingRequestHandle& TargetingHandle, FCollisionQueryParams& OutParams) const;
protected:
/** The trace channel to use */
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Target Trace Selection | Collision Data")
TEnumAsByte<ETraceTypeQuery> TraceChannel;
/** The collision profile name to use instead of trace channel (does not work for async traces) */
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Target Trace Selection | Collision Data")
FCollisionProfileName CollisionProfileName;
/** The default trace length to use if GetTraceLength is not overridden by a child */
UPROPERTY(EditAnywhere, BlueprintReadOnly, BlueprintReadOnly, Category = "Target Trace Selection | Trace Data")
FScalableFloat DefaultTraceLength = 10.0f;
/** The default source location offset used by GetSourceOffset */
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Target Trace Selection | Trace Data")
FVector DefaultSourceOffset = FVector::ZeroVector;
/** Indicates the trace should perform a complex trace */
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Target Trace Selection | Trace Data")
uint8 bComplexTrace : 1;
/** Indicates the trace should ignore the source actor */
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Target Trace Selection | Trace Data")
uint8 bIgnoreSourceActor : 1;
/** Indicates the trace should ignore the source actor */
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Target Trace Selection | Trace Data")
uint8 bIgnoreInstigatorActor : 1;
// If there were no hits, add a default HitResult at the end of the trace
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Target Trace Selection | Trace Data")
uint8 bGenerateDefaultHitResult : 1;
protected:
#if WITH_EDITOR
virtual bool CanEditChange(const FProperty* InProperty) const override;
#endif
/** Debug Helper Methods */
#if ENABLE_DRAW_DEBUG
private:
virtual void DrawDebug(UTargetingSubsystem* TargetingSubsystem, FTargetingDebugInfo& Info, const FTargetingRequestHandle& TargetingHandle, float XOffset, float YOffset,
int32 MinTextRowsToAdvance) const override;
/** Draw debug info showing the results of the shape trace used for targeting. */
virtual void DrawDebugTrace(const FTargetingRequestHandle TargetingHandle, const FVector& StartLocation, const FVector& EndLocation, const bool bHit, const TArray<FHitResult>& Hits) const;
void BuildTraceResultsDebugString(const FTargetingRequestHandle& TargetingHandle, const TArray<FTargetingDefaultResultData>& TargetResults) const;
void ResetTraceResultsDebugString(const FTargetingRequestHandle& TargetingHandle) const;
#endif // ENABLE_DRAW_DEBUG
/** ~Debug Helper Methods */
};

View File

@@ -0,0 +1,67 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Tasks/TargetingSelectionTask_Trace.h"
#include "GCS_TargetingSelectionTask_TraceExt.generated.h"
class UDEPRECATED_GCS_CollisionTraceInstance;
/**
* @class UGCS_TargetingSelectionTask_TraceExt
* Specialized version of SelectionTask_Trace,Allow passing data via source object to Trace execution.
* @attention SourceObject should be provided and implement GCS_TargetingSourceInterface.
*/
UCLASS(meta=(DisplayName="GCS:SelectionTask (Trace)"))
class GENERICCOMBATSYSTEM_API UGCS_TargetingSelectionTask_TraceExt : public UTargetingSelectionTask_Trace
{
GENERATED_BODY()
public:
virtual void Execute(const FTargetingRequestHandle& TargetingHandle) const override;
protected:
/**
* If ticked, user context's source location as trace source location.
* Or it will try to get context's source actor location first,then fall back to context's source location.
* 如果勾选会使用上下文的源位置作为Trace的源位置。
* 否则它会先从上下文的源Actor上获取位置如果没有Actor则回退到上下文的源位置。
*/
UPROPERTY(EditAnywhere, Category = "Target Trace Selection | Trace Data")
bool bUseContextLocationAsSourceLocation{false};
virtual FVector GetSourceLocation_Implementation(const FTargetingRequestHandle& TargetingHandle) const override;
virtual FVector GetTraceDirection_Implementation(const FTargetingRequestHandle& TargetingHandle) const override;
virtual void GetAdditionalActorsToIgnore_Implementation(const FTargetingRequestHandle& TargetingHandle, TArray<AActor*>& OutAdditionalActorsToIgnore) const override;
/** Native Event to get the source location for the Trace */
UE_DEPRECATED(1.5, "CollisionTraceInstance no longer required!")
UFUNCTION(BlueprintNativeEvent, Category = "Target Trace Selection", meta=(DeprecatedFunction))
UDEPRECATED_GCS_CollisionTraceInstance* GetSourceTraceInstance(const FTargetingRequestHandle& TargetingHandle) const;
UFUNCTION(BlueprintNativeEvent, Category = "Target Trace Selection")
float GetTraceLevel(const FTargetingRequestHandle& TargetingHandle) const;
UPROPERTY(EditAnywhere, Category = "Target Trace Selection | Trace Data")
bool bTraceLengthLevel{true};
virtual float GetTraceLength_Implementation(const FTargetingRequestHandle& TargetingHandle) const override;
UPROPERTY(EditAnywhere, Category = "Target Trace Selection | Swept Data")
bool bSweptTraceRadiusLevel{true};
virtual float GetSweptTraceRadius_Implementation(const FTargetingRequestHandle& TargetingHandle) const override;
UPROPERTY(EditAnywhere, Category = "Target Trace Selection | Swept Data")
bool bSweptTraceCapsuleHalfHeightLevel{true};
virtual float GetSweptTraceCapsuleHalfHeight_Implementation(const FTargetingRequestHandle& TargetingHandle) const override;
UPROPERTY(EditAnywhere, Category = "Target Trace Selection | Swept Data")
bool bSweptTraceBoxHalfExtentLevel{true};
virtual FVector GetSweptTraceBoxHalfExtents_Implementation(const FTargetingRequestHandle& TargetingHandle) const override;
};

View File

@@ -0,0 +1,55 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GCS_TargetingSelectionTask_TraceExt.h"
#include "GCS_TargetingSelectionTask_TraceExt_BindShape.generated.h"
class UShapeComponent;
UENUM(BlueprintType)
enum class EGCS_TraceDataModifyType :uint8
{
None UMETA(DisplayName="None"),
Add UMETA(DisplayName="Add"),
Multiply UMETA(DisplayName = "Multiply"),
};
/**
*
*/
UCLASS(meta=(DisplayName="GCS:SelectionTask (Trace Bind Shape)"))
class GENERICCOMBATSYSTEM_API UGCS_TargetingSelectionTask_TraceExt_BindShape : public UGCS_TargetingSelectionTask_TraceExt
{
GENERATED_BODY()
public:
virtual void Execute(const FTargetingRequestHandle& TargetingHandle) const override;
protected:
UPROPERTY(EditAnywhere, Category = "Target Trace Selection | Trace Data")
EGCS_TraceDataModifyType SweptTraceRadiusModType{EGCS_TraceDataModifyType::None};
virtual float GetSweptTraceRadius_Implementation(const FTargetingRequestHandle& TargetingHandle) const override;
UPROPERTY(EditAnywhere, Category = "Target Trace Selection | Swept Data")
EGCS_TraceDataModifyType SweptTraceCapsuleHalfHeightModType{EGCS_TraceDataModifyType::None};
virtual float GetSweptTraceCapsuleHalfHeight_Implementation(const FTargetingRequestHandle& TargetingHandle) const override;
UPROPERTY(EditAnywhere, Category = "Target Trace Selection | Swept Data")
EGCS_TraceDataModifyType SweptTraceBoxHalfExtentModType{EGCS_TraceDataModifyType::None};
virtual FVector GetSweptTraceBoxHalfExtents_Implementation(const FTargetingRequestHandle& TargetingHandle) const override;
virtual UShapeComponent* GetTraceShape(const FTargetingRequestHandle& TargetingHandle) const;
virtual FRotator GetSweptTraceRotation_Implementation(const FTargetingRequestHandle& TargetingHandle) const override;
public:
#if WITH_EDITORONLY_DATA
virtual EDataValidationResult IsDataValid(class FDataValidationContext& Context) const override;
#endif
};

View File

@@ -0,0 +1,99 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GCS_CombatTeamAgentInterface.h"
#include "Components/ActorComponent.h"
#include "GCS_CombatTeamAgentComponent.generated.h"
/**
* Component for managing combat team affiliations.
* 管理战斗队伍归属的组件。
*/
UCLASS(ClassGroup=(GCS), meta=(BlueprintSpawnableComponent), AutoExpandCategories=(GCS))
class GENERICCOMBATSYSTEM_API UGCS_CombatTeamAgentComponent : public UActorComponent, public IGCS_CombatTeamAgentInterface
{
GENERATED_BODY()
public:
/**
* Default constructor.
* 默认构造函数。
*/
UGCS_CombatTeamAgentComponent();
/**
* Retrieves lifetime replicated properties.
* 获取生命周期复制属性。
* @param OutLifetimeProps The lifetime properties. 生命周期属性。
*/
virtual void GetLifetimeReplicatedProps(TArray<class FLifetimeProperty>& OutLifetimeProps) const override;
/**
* Gets the delegate for team ID changes.
* 获取队伍ID更改的委托。
* @return The team ID changed delegate. 队伍ID更改委托。
*/
virtual FGCS_CombatTeamIdChangedSignature* GetOnTeamIdChangedDelegate() override;
/**
* Gets the current combat team ID.
* 获取当前战斗队伍ID。
* @return The combat team ID. 战斗队伍ID。
*/
virtual FGenericTeamId GetCombatTeamId_Implementation() const override;
/**
* Sets the combat team ID.
* 设置战斗队伍ID。
* @param NewTeamId The new team ID. 新队伍ID。
*/
virtual void SetCombatTeamId_Implementation(FGenericTeamId NewTeamId) override;
/**
* Handles replication of the combat team ID.
* 处理战斗队伍ID的复制。
* @param OldTeamID The previous team ID. 旧队伍ID。
*/
UFUNCTION()
void OnRep_CombatTeamId(FGenericTeamId OldTeamID);
/**
* Delegate for team ID change events.
* 队伍ID更改事件的委托。
*/
UPROPERTY(BlueprintAssignable, Category="GCS")
FGCS_CombatTeamIdChangedSignature OnTeamIdChangedEvent;
protected:
/**
* Called when the game starts.
* 游戏开始时调用。
*/
virtual void BeginPlay() override;
/**
* The current team ID of this agent.
* 此代理的当前队伍ID。
*/
UPROPERTY(EditAnywhere, Category="GCS", ReplicatedUsing=OnRep_CombatTeamId)
FGenericTeamId CombatTeamId;
/**
* Whether to assign the team ID to the controller.
* 是否将队伍ID分配给控制器。
*/
UPROPERTY(EditAnywhere, Category="GCS")
bool bAssignTeamIdToController{true};
public:
/**
* Called every frame.
* 每帧调用。
* @param DeltaTime Time since last frame. 上一帧以来的时间。
* @param TickType The type of tick. tick类型。
* @param ThisTickFunction The tick function. tick函数。
*/
virtual void TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) override;
};

View File

@@ -0,0 +1,82 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GenericTeamAgentInterface.h"
#include "UObject/Interface.h"
#include "GCS_CombatTeamAgentInterface.generated.h"
/**
* Delegate for team ID change events.
* 队伍ID更改事件的委托。
*/
DECLARE_DYNAMIC_MULTICAST_DELEGATE_ThreeParams(FGCS_CombatTeamIdChangedSignature, UObject*, ObjectChangingTeam, FGenericTeamId, OldTeamID, FGenericTeamId, NewTeamID);
/**
* Interface for combat team agents.
* 战斗队伍代理的接口。
*/
UINTERFACE(MinimalAPI, BlueprintType, Blueprintable)
class UGCS_CombatTeamAgentInterface : public UInterface
{
GENERATED_BODY()
};
/**
* Interface for managing combat team affiliations.
* 管理战斗队伍归属的接口。
*/
class GENERICCOMBATSYSTEM_API IGCS_CombatTeamAgentInterface
{
GENERATED_BODY()
public:
/**
* Sets the combat team ID.
* 设置战斗队伍ID。
* @note Default implementation converts to GenericTeamAgentInterface.
* @注意 默认实现转换为GenericTeamAgentInterface。
* @param NewTeamId The new team ID. 新队伍ID。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GCS|CombatTeam")
void SetCombatTeamId(FGenericTeamId NewTeamId);
virtual void SetCombatTeamId_Implementation(FGenericTeamId NewTeamId);
/**
* Gets the current combat team ID.
* 获取当前战斗队伍ID。
* @return The combat team ID. 战斗队伍ID。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GCS|CombatTeam")
FGenericTeamId GetCombatTeamId() const;
virtual FGenericTeamId GetCombatTeamId_Implementation() const;
/**
* Gets the delegate for team ID changes.
* 获取队伍ID更改的委托。
* @return The team ID changed delegate. 队伍ID更改委托。
*/
virtual FGCS_CombatTeamIdChangedSignature* GetOnTeamIdChangedDelegate() = 0;
/**
* Conditionally broadcasts team change events.
* 有条件地广播队伍更改事件。
* @param This The combat team agent interface. 战斗队伍代理接口。
* @param OldTeamID The previous team ID. 旧队伍ID。
* @param NewTeamID The new team ID. 新队伍ID。
*/
static void ConditionalBroadcastTeamChanged(TScriptInterface<IGCS_CombatTeamAgentInterface> This, FGenericTeamId OldTeamID, FGenericTeamId NewTeamID);
/**
* Gets the team changed delegate with validation.
* 获取经过验证的队伍更改委托。
* @return The team changed delegate. 队伍更改委托。
*/
FGCS_CombatTeamIdChangedSignature& GetTeamChangedDelegateChecked()
{
FGCS_CombatTeamIdChangedSignature* Result = GetOnTeamIdChangedDelegate();
check(Result);
return *Result;
}
};

View File

@@ -0,0 +1,22 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Kismet/BlueprintFunctionLibrary.h"
#include "GCS_AttackDefinitionFunctionLibrary.generated.h"
/**
*
*/
UCLASS()
class GENERICCOMBATSYSTEM_API UGCS_AttackDefinitionFunctionLibrary : public UBlueprintFunctionLibrary
{
GENERATED_BODY()
public:
#if WITH_EDITOR
UFUNCTION(BlueprintCallable, Category = "Editor Scripting | DataTable", DisplayName = "MigrateAttackDefinitionTable")
static void MigrateAttackDefinitionTable(UDataTable* InTable);
#endif
};

View File

@@ -0,0 +1,309 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GCS_CombatEnumLibrary.h"
#include "GenericTeamAgentInterface.h"
#include "GCS_CombatStructLibrary.h"
#include "AbilitySystem/GCS_GameplayEffectContext.h"
#include "CombatFlow/GCS_AttackDefinition.h"
#include "Kismet/BlueprintFunctionLibrary.h"
#include "GCS_CombatFunctionLibrary.generated.h"
class UGCS_AttackRequest_Base;
class IGCS_CombatTeamAgentInterface;
class IGCS_WeaponInterface;
class IGCS_CombatEntityInterface;
/**
* Utility functions for combat-related operations.
* 战斗相关操作的实用函数。
*/
UCLASS()
class GENERICCOMBATSYSTEM_API UGCS_CombatFunctionLibrary : public UBlueprintFunctionLibrary
{
GENERATED_BODY()
public:
/**
* Gets the combat team agent interface from an actor or its components.
* 从Actor或其组件获取战斗队伍代理接口。
* @param Actor The actor to query. 要查询的Actor。
* @return The combat team agent interface. 战斗队伍代理接口。
*/
UFUNCTION(BlueprintCallable, Category="GCS|CombatTeam", meta=(DefaultToSelf="Actor"))
static TScriptInterface<IGCS_CombatTeamAgentInterface> GetCombatTeamAgentInterface(AActor* Actor);
/**
* Finds the combat team agent interface on an actor or its components.
* 在Actor或其组件上查找战斗队伍代理接口。
* @param Actor The actor to query. 要查询的Actor。
* @param OutInterface The found interface (output). 找到的接口(输出)。
* @return True if found. 如果找到返回true。
*/
UFUNCTION(BlueprintCallable, Category="GCS|CombatTeam", meta=(DefaultToSelf="Actor", ExpandBoolAsExecs="ReturnValue"))
static bool FindCombatTeamAgentInterface(AActor* Actor, TScriptInterface<IGCS_CombatTeamAgentInterface>& OutInterface);
/**
* Gets the combat interface from an actor or its components.
* 从Actor或其组件获取战斗接口。
* @param Actor The actor to query. 要查询的Actor。
* @return The combat interface. 战斗接口。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category = "GCS", meta=(DefaultToSelf="Actor"))
static TScriptInterface<IGCS_CombatEntityInterface> GetCombatEntityInterface(AActor* Actor);
/**
* Gets the implementer(entity) of the combat interface.
* 获取战斗接口的实现者。
* @param Actor The actor to query. 要查询的Actor。
* @return The object implementing the combat interface. 实现战斗接口的对象。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category = "GCS", meta=(DefaultToSelf="Actor"))
static UObject* GetCombatEntity(AActor* Actor);
/**
* Gets the weapon interface from an actor or its components.
* 从Actor或其组件获取武器接口。
* @param Actor The actor to query. 要查询的Actor。
* @return The weapon interface. 武器接口。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category = "GCS", meta=(DefaultToSelf="Actor"))
static TScriptInterface<IGCS_WeaponInterface> GetWeaponInterface(AActor* Actor);
/**
* Gets the main skeletal mesh component from an actor.
* 从Actor获取主要骨骼网格组件。
* @param Actor The actor to query. 要查询的Actor。
* @param OverrideMeshLookupTag Optional override tag for lookup. 可选的覆盖查找标签。
* @return The skeletal mesh component. 骨骼网格组件。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category = "GCS", meta=(DefaultToSelf="Actor"))
static USkeletalMeshComponent* GetMainCharacterMeshComponent(AActor* Actor, FName OverrideMeshLookupTag = NAME_None);
/**
* Gets the main mesh component from an actor.
* 从Actor获取主要网格组件。
* @param Actor The actor to query. 要查询的Actor。
* @param OverrideMeshLookupTag Optional override tag for lookup. 可选的覆盖查找标签。
* @return The mesh component. 网格组件。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category = "GCS", meta=(DefaultToSelf="Actor"))
static UMeshComponent* GetMainMeshComponent(AActor* Actor, FName OverrideMeshLookupTag = NAME_None);
/**
* Gets socket names with a specified prefix from a component.
* 从组件获取具有指定前缀的插槽名称。
* @param Component The component to query. 要查询的组件。
* @param Prefix The prefix to match. 要匹配的前缀。
* @param SearchCase The case sensitivity for the search. 搜索的大小写敏感性。
* @return Array of matching socket names. 匹配的插槽名称数组。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category = "GCS")
static TArray<FName> GetSocketNamesWithPrefix(const USceneComponent* Component, FString Prefix, ESearchCase::Type SearchCase);
/**
* Finds the combat interface on an actor or its components.
* 在Actor或其组件上查找战斗接口。
* @param Actor The actor to query. 要查询的Actor。
* @param OutInterface The found interface (output). 找到的接口(输出)。
* @return True if found. 如果找到返回true。
*/
UFUNCTION(BlueprintCallable, Category = "GCS", meta=(DefaultToSelf="Actor", ExpandBoolAsExecs="ReturnValue"))
static bool FindCombatInterface(AActor* Actor, TScriptInterface<IGCS_CombatEntityInterface>& OutInterface);
/**
* Finds the weapon interface on an actor or its components.
* 在Actor或其组件上查找武器接口。
* @param Actor The actor to query. 要查询的Actor。
* @param OutInterface The found interface (output). 找到的接口(输出)。
* @return True if found. 如果找到返回true。
*/
UFUNCTION(BlueprintCallable, Category = "GCS", meta=(DefaultToSelf="Actor", ExpandBoolAsExecs="ReturnValue"))
static bool FindWeaponInterface(AActor* Actor, TScriptInterface<IGCS_WeaponInterface>& OutInterface);
/**
* Calculates the angle between two actors.
* 计算两个Actor之间的角度。
* @param From The source actor. 来源Actor。
* @param To The target actor. 目标Actor。
* @return The angle as a rotator. 角度(旋转器)。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GCS")
static FRotator CalculateAngleBetweenActors(const AActor* From, const AActor* To);
/**
* Check team relationship using CombatTeamAgentInterface.
* @param A The first actor.
* @param B The second actor.
* @return True if both actors are in the same team.
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GCS")
static bool IsSameCombatTeam(const AActor* A, const AActor* B);
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GCS")
static FGenericTeamId GetCombatTeamId(const AActor* Actor);
static FGenericTeamId QueryCombatTeamId(const AActor* Actor, bool bCombatAgent = true, bool bGenericAgent = true);
/**
* Determines the direction from an angle.
* 从角度确定方向。
* @param Angle The input angle. 输入角度。
* @return The direction enum. 方向枚举。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GCS")
static EGCS_Direction CalculateDirectionFromAngle(const float Angle);
/**
* Selects a montage based on direction.
* 根据方向选择蒙太奇。
* @param Direction The direction enum. 方向枚举。
* @param Montages Array of montages to choose from. 可选的蒙太奇数组。
* @return The selected montage. 选中的蒙太奇。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GCS")
static TSoftObjectPtr<UAnimMontage> SelectMontageByDirection(EGCS_Direction Direction, TArray<TSoftObjectPtr<UAnimMontage>> Montages);
/**
* Adds a tagged value to an array.
* 向数组添加标记值。
* @param TaggedValues The tagged values array (modified). 标记值数组(修改)。
* @param Tag The gameplay tag. 游戏标签。
* @param ValueToAdd The value to add. 要添加的值。
*/
UFUNCTION(BlueprintCallable, BlueprintPure=false, Category="GCS", meta=(DeprecatedFunction, DeprecationMessage="Use Set Tagged Value To Combat Payload."))
static void AddTaggedValue(UPARAM(ref)
TArray<FGCS_TaggedValue>& TaggedValues, FGameplayTag Tag, float ValueToAdd);
/**
* Gets a tagged value from an array.
* 从数组获取标记值。
* @param TaggedValues The tagged values array. 标记值数组。
* @param Tag The gameplay tag to find. 要查找的游戏标签。
* @return The associated value. 关联值。
*/
UFUNCTION(BlueprintCallable, BlueprintPure=false, Category="GCS", meta=(DeprecatedFunction, DeprecationMessage="Use Get Tagged Value From Combat Payload."))
static float GetTaggedValue(const TArray<FGCS_TaggedValue> TaggedValues, FGameplayTag Tag);
/**
* Filters a gameplay tag container based on another container.
* 根据另一个容器过滤游戏标签容器。
* @param TagContainer The container to filter. 要过滤的容器。
* @param OtherContainer The container to filter against. 过滤依据的容器。
* @return The filtered tag container. 过滤后的标签容器。
*/
UFUNCTION(BlueprintCallable, BlueprintPure=false, Category="GCS")
static FGameplayTagContainer FilterGameplayTagContainer(const FGameplayTagContainer& TagContainer, FGameplayTagContainer OtherContainer);
/**
* Adds an attack definition handle to a gameplay effect spec.
* 将攻击定义句柄添加到游戏效果规格。
* @param SpecHandle The effect spec handle. 效果规格句柄。
* @param AttackHandle The attack definition handle. 攻击定义句柄。
* @return The modified effect spec handle. 修改后的效果规格句柄。
*/
UFUNCTION(BlueprintCallable, BlueprintPure=false, Category="GCS")
static FGameplayEffectSpecHandle AddAttackHandleToGameplayEffectSpec(FGameplayEffectSpecHandle SpecHandle, FDataTableRowHandle AttackHandle);
/**
* Adds an attack definition to a gameplay effect spec.
* 将攻击定义添加到游戏效果规格。
* @param SpecHandle The effect spec handle. 效果规格句柄。
* @param AtkDefinition The attack definition. 攻击定义。
* @return The modified effect spec handle. 修改后的效果规格句柄。
*/
UFUNCTION(BlueprintCallable, BlueprintPure=false, Category="GCS")
static FGameplayEffectSpecHandle AddAttackDefinitionToGameplayEffectSpec(FGameplayEffectSpecHandle SpecHandle, const FGCS_AttackDefinition& AtkDefinition);
/**
* Adds an attack definition handle to a gameplay effect container spec.
* 将攻击定义句柄添加到游戏效果容器规格。
* @param ContainerSpec The effect container spec. 效果容器规格。
* @param AttackHandle The attack definition handle. 攻击定义句柄。
*/
UFUNCTION(BlueprintCallable, BlueprintPure=false, Category="GCS")
static void AddAttackHandleToGameplayEffectContainerSpec(FGGA_GameplayEffectContainerSpec ContainerSpec, FDataTableRowHandle AttackHandle);
/**
* Sets the attack definition handle in an effect context.
* 在效果上下文中设置攻击定义句柄。
* @param EffectContext The effect context. 效果上下文。
* @param Handle The attack definition handle. 攻击定义句柄。
*/
UFUNCTION(BlueprintCallable, Category = "Ability|EffectContext", Meta = (DisplayName = "Set Attack Definition Handle"))
static void EffectContextSetAttackDefinitionHandle(FGameplayEffectContextHandle EffectContext, UPARAM(meta=(RowType="/Script/GenericCombatSystem.GCS_AttackDefinition"))
FDataTableRowHandle Handle);
/**
* Gets the combat payload required by GCS within effect context.
* 获取效果上下文中GCS所需的数据荷载。
* @param EffectContext The effect context. 效果上下文。
* @return The required data payload within GameplayEffectContext for GCS. GCS在GameplayEffectContext中所需的数据何在。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="Ability|EffectContext", Meta = (DisplayName = "Get Combat Payload"))
static FGCS_ContextPayload_Combat EffectContextGetCombatPayload(FGameplayEffectContextHandle EffectContext);
// Quicker access to Combat payload.
static FGCS_ContextPayload_Combat* EffectContextGetMutableCombatPayload(const FGameplayEffectContextHandle& EffectContext);
/**
* Add single tag to the DynamicTags within combat payload.
* 获取战斗数据中的动态标签。
* @param EffectContext The effect context. 效果上下文。
* @param TagToAdd The tag to add. 要添加的标签。
*/
UFUNCTION(BlueprintCallable, Category="Ability|EffectContext", Meta = (DisplayName = "Add Tag To Combat Payload"))
static void EffectContextAddTagToCombatPayload(FGameplayEffectContextHandle EffectContext, FGameplayTag TagToAdd);
/**
* Shortcut to get the dynamic tags within combat payload.
* 获取战斗数据中的动态标签。
* @param EffectContext The effect context. 效果上下文。
* @param OutTags The dynamic tags. 动态标签。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="Ability|EffectContext", meta=( DisplayName="Get DynamicTags From Combat Payload"))
static void EffectContextGetDynamicTagsFromCombatPayload(FGameplayEffectContextHandle EffectContext, FGameplayTagContainer& OutTags);
/**
* Sets a tagged value to combat payload
* 向战斗数据添加以标签关联的数值。
* @param EffectContext The effect context. 效果上下文。
* @param Tag The gameplay tag. 游戏标签。
* @param NewValue The value to set. 要设置的值。
*/
UFUNCTION(BlueprintCallable, BlueprintPure=false, Category="Ability|EffectContext", meta=( DisplayName="Set Tagged Value To Combat Payload"))
static void EffectContextSetTaggedValueToCombatPayload(FGameplayEffectContextHandle EffectContext, FGameplayTag Tag, float NewValue);
/**
* Gets a tagged value from combat payload.
* 从战斗数据获取以标签关联的数值
* @param EffectContext The effect context. 效果上下文。
* @param Tag The gameplay tag to find. 要查找的游戏标签。
* @return The associated value,0 if not found. 关联值,没找到就返回0。
*/
UFUNCTION(BlueprintCallable, BlueprintPure=false, Category="Ability|EffectContext", meta=( DisplayName="Get Tagged Value From Combat Payload"))
static float EffectContextGetTaggedValueFromCombatPayload(FGameplayEffectContextHandle EffectContext, FGameplayTag Tag);
/**
* Gets the attack definition handle from an effect context.
* 从效果上下文中获取攻击定义句柄。
* @param EffectContext The effect context. 效果上下文。
* @return The attack definition handle. 攻击定义句柄。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="Ability|EffectContext", Meta = (DisplayName = "Get Attack Definition Handle"))
static FDataTableRowHandle EffectContextGetAttackDefinitionHandle(FGameplayEffectContextHandle EffectContext);
UFUNCTION(BlueprintCallable, BlueprintPure, Category="Ability|EffectContext", Meta = (DisplayName = "Is Predicting Context"))
static bool EffectContextGetIsPredictingContext(FGameplayEffectContextHandle EffectContext);
/**
* Gets the attack definition from an effect context.
* 从效果上下文中获取攻击定义。
* @param EffectContext The effect context. 效果上下文。
* @return The attack definition. 攻击定义。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="Ability|EffectContext", Meta = (DisplayName = "Get Attack Definition"))
static FGCS_AttackDefinition EffectContextGetAttackDefinition(FGameplayEffectContextHandle EffectContext);
};

View File

@@ -0,0 +1,84 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Engine/DataAsset.h"
#include "GCS_AttachmentRelationshipMapping.generated.h"
class USkeleton;
class USkeletalMesh;
class UStaticMesh;
class USkeletalMeshComponent;
/**
* Deprecated!! Use SocketRelationshipMapping from GGS!
* 弃用了使用GGS中的SocketRelationshipMapping。
*/
USTRUCT(BlueprintType)
struct FGCS_AttachmentRelationship
{
GENERATED_BODY()
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GGS")
TSoftObjectPtr<UStaticMesh> StaticMesh;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GGS")
TSoftObjectPtr<USkeletalMesh> SkeletalMesh;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GGS")
FName SocketName{NAME_None};
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GGS")
FTransform RelativeTransform;
#if WITH_EDITORONLY_DATA
UPROPERTY(EditAnywhere, Category="GGS", meta=(EditCondition=false, EditConditionHides))
FString EditorFriendlyName;
#endif
};
/**
* Deprecated!! Use SocketRelationshipMapping from GGS!
* 弃用了使用GGS中的SocketRelationshipMapping。
*/
UCLASS(BlueprintType, Const)
class GENERICCOMBATSYSTEM_API UGCS_AttachmentRelationshipMapping : public UDataAsset
{
GENERATED_BODY()
public:
/**
* @param InSkeletalMeshComponent The parent skeletal mesh component that need to be attached to.
* @param InStaticMesh The static mesh you want to attach.
* @param InSkeletalMesh The skeletal mesh you want to attach.
* @param InSocketName The socket name you want to attach.
* @param OutRelationship The result attachment relationship.
* @return true if any matching found.
*/
UFUNCTION(BlueprintCallable,BlueprintPure=False, Category="GGS|Utilities",meta=(DeprecatedFunction,DeprecationMessage="Use SocketRelationshipMapping from GGS!"))
bool FindRelationshipForMesh(UPARAM(meta=(DisplayName="In Parent Mesh")) const USkeletalMeshComponent* InSkeletalMeshComponent, const UStaticMesh* InStaticMesh, const USkeletalMesh* InSkeletalMesh, FName InSocketName,
FGCS_AttachmentRelationship& OutRelationship) const;
/**
* Will restrict this mapping to CompatibleSkeletons, or no restriction if left empty.
*/
UPROPERTY(EditAnywhere, Category="GGS")
TArray<TSoftObjectPtr<USkeleton>> CompatibleSkeletons;
UPROPERTY(EditAnywhere, Category="GGS")
TArray<FString> CompatibleSkeletonNames;
UPROPERTY(EditAnywhere, Category="GGS")
bool bUseNameMatching{true};
UPROPERTY(EditAnywhere, Category="GGS", meta=(TitleProperty="EditorFriendlyName"))
TArray<FGCS_AttachmentRelationship> Relationships;
#if WITH_EDITOR
virtual void PreSave(FObjectPreSaveContext SaveContext) override;
virtual EDataValidationResult IsDataValid(class FDataValidationContext& Context) const override;
#endif
};

View File

@@ -0,0 +1,217 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GameplayTagAssetInterface.h"
#include "GCS_CombatStructLibrary.h"
#include "GCS_WeaponInterface.h"
#include "Collision/GCS_TraceStructLibrary.h"
#include "GameFramework/Actor.h"
#include "GCS_WeaponActor.generated.h"
/**
* Delegate for weapon active state changes.
* 武器激活状态更改的委托。
*/
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FGCS_WeaponActiveStateChangedSignature, bool, bIsActive);
/**
* Default implementation of the weapon interface as an actor.
* 作为Actor的武器接口默认实现。
* @note Extend this class for custom weapon logic. 扩展此类以实现自定义武器逻辑。
*/
UCLASS(BlueprintType, Blueprintable, Abstract, ClassGroup=(GCS))
class GENERICCOMBATSYSTEM_API AGCS_WeaponActor : public AActor, public IGCS_WeaponInterface, public IGameplayTagAssetInterface
{
GENERATED_BODY()
public:
/**
* Default constructor.
* 默认构造函数。
*/
AGCS_WeaponActor(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get());
/**
* Gets the pawn owning this weapon.
* 获取拥有此武器的Pawn。
* @return The owning pawn. 所属Pawn。
*/
virtual APawn* GetWeaponOwner_Implementation() const override;
/**
* Gets the gameplay tags associated with the weapon.
* 获取与武器关联的游戏标签。
* @return The weapon's gameplay tags. 武器游戏标签。
*/
virtual const FGameplayTagContainer GetWeaponTags_Implementation() const override;
/**
* Retrieves lifetime replicated properties.
* 获取生命周期复制属性。
* @param OutLifetimeProps The lifetime properties. 生命周期属性。
*/
virtual void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const override;
/**
* Sets the weapon's active state.
* 设置武器的激活状态。
* @param bNewActive The new active state. 新激活状态。
*/
virtual void SetWeaponActive_Implementation(bool bNewActive) override;
/**
* Checks if the weapon is active.
* 检查武器是否激活。
* @return True if the weapon is active. 如果武器激活返回true。
*/
virtual bool IsWeaponActive_Implementation() const override;
/**
* Gets the main primitive component of the weapon.
* 获取武器的主要原始组件。
* @return The primitive component. 原始组件。
*/
virtual UPrimitiveComponent* GetPrimitiveComponent_Implementation() const override;
/**
* Gets the owned gameplay tags.
* 获取拥有的游戏标签。
* @param TagContainer The gameplay tag container (output). 游戏标签容器(输出)。
*/
virtual void GetOwnedGameplayTags(FGameplayTagContainer& TagContainer) const override;
protected:
/**
* Called when the game starts.
* 游戏开始时调用。
*/
virtual void BeginPlay() override;
/**
* Called when the game ends.
* 游戏结束时调用。
* @param EndPlayReason The reason for ending. 结束原因。
*/
virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override;
/**
* Handles weapon active state changes.
* 处理武器激活状态变化。
* @param Prev The previous active state. 之前的激活状态。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category = "GCS|Weapon")
void OnWeaponActiveStateChanged(bool Prev);
/**
* Refreshes trace instances and registers/unregisters trace events.
* 刷新碰撞检测实例并注册/取消注册碰撞事件。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GCS|WeaponTrace", meta=(BlueprintProtected))
void RefreshTraceInstance();
virtual void RefreshTraceInstance_Implementation();
/**
* Allow you to customize the source object used for weapon traces.
* 允许你自定义用于武器碰撞检测的源对象。
* @note The source object is the weapon itself by default. 默认是武器本身就是源对象.
* @return The object used as source object for weapon trace.
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GCS|WeaponTrace", meta=(BlueprintProtected))
UObject* GetSourceObjectForTrace();
virtual UObject* GetSourceObjectForTrace_Implementation();
/**
* Allow you to customize the source component used for different weapon traces.
* 允许你自定义用于不同武器碰撞检测的源组件。
* @note The source component is the weapon primitive component by default. 默认是武器的PrimitiveComponent就是源组件.
* @return The component used as source component for weapon trace.
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GCS|WeaponTrace", meta=(BlueprintProtected))
UPrimitiveComponent* GetSourceComponentForTrace(const FGameplayTag& TraceTag) const;
virtual UPrimitiveComponent* GetSourceComponentForTrace_Implementation(const FGameplayTag& TraceTag) const;
/**
* Handles weapon trace hits.
* 处理武器碰撞命中。
* @param TraceHandle The collision trace instance. 碰撞检测实例。
* @param HitResult The hit result. 命中结果。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GCS|WeaponTrace")
void OnAnyTraceHit(const FGCS_TraceHandle& TraceHandle, const FHitResult& HitResult);
/**
* Handles trace state changes.
* 处理碰撞状态变化。
* @param TraceHandle The collision trace instance. 碰撞检测实例。
* @param NewState The new state. 新状态。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GCS|WeaponTrace")
void OnAnyTraceStateChanged(const FGCS_TraceHandle& TraceHandle, bool NewState);
/**
* Delegate for weapon active state changes.
* 武器激活状态更改的委托。
*/
UPROPERTY(BlueprintAssignable)
FGCS_WeaponActiveStateChangedSignature OnWeaponActiveStateChangedEvent;
public:
/**
* Called every frame.
* 每帧调用。
* @param DeltaSeconds Time since last frame. 上一帧以来的时间。
*/
virtual void Tick(float DeltaSeconds) override;
protected:
/**
* Gameplay tags for the weapon.
* 武器的游戏标签。
*/
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "WeaponSetting")
FGameplayTagContainer WeaponTags;
/**
* List of collision trace settings created when the weapon is activated.
* 武器激活时创建的碰撞检测设置列表。
*/
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "WeaponSetting|Trace")
TArray<FGCS_TraceDefinition> TraceDefinitions;
/**
* Tag name for looking up the mesh component.
* 查找网格组件的标签名称。
*/
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category="WeaponSetting")
FName WeaponMeshTagName{TEXT("WeaponMesh")};
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category="WeaponSetting", meta=(RequiredAssetDataTags = "RowStructure=/Script/GenericCombatSystem.GCS_ComboDefinition"))
bool bGiveAbilitiesFromComboDefinitionTable{true};
/**
* The combo definition table associated with this weapon.
* 与此武器关联的连击定义表。
*/
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category="WeaponSetting", meta=(RequiredAssetDataTags = "RowStructure=/Script/GenericCombatSystem.GCS_ComboDefinition"))
TObjectPtr<const UDataTable> ComboDefinitionTable{nullptr};
/**
* Traces associated with this weapon.
* 与该武器关联的碰撞检测.
*/
UPROPERTY(VisibleInstanceOnly, BlueprintReadOnly, Category="WeaponState")
TArray<FGCS_TraceHandle> TraceHandles;
/**
* Indicates if the weapon is active.
* 表示武器是否激活。
*/
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, ReplicatedUsing = OnWeaponActiveStateChanged, Category = "WeaponState")
bool bWeaponActive;
#if WITH_EDITOR
virtual EDataValidationResult IsDataValid(class FDataValidationContext& Context) const override;
#endif
};

View File

@@ -0,0 +1,96 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GameplayTagContainer.h"
#include "UObject/Interface.h"
#include "GCS_WeaponInterface.generated.h"
class APawn;
class AActor;
/**
* Interface for objects acting as weapons.
* 作为武器的对象的接口。
*/
UINTERFACE()
class UGCS_WeaponInterface : public UInterface
{
GENERATED_BODY()
};
/**
* Interface for weapon-related functionality.
* 武器相关功能的接口。
*/
class GENERICCOMBATSYSTEM_API IGCS_WeaponInterface
{
GENERATED_BODY()
public:
/**
* Gets the pawn owning this weapon.
* 获取拥有此武器的Pawn。
* @return The owning pawn. 所属Pawn。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GCS|Weapon")
APawn* GetWeaponOwner() const;
/**
* Gets the gameplay tags associated with the weapon.
* 获取与武器关联的游戏标签。
* @return The weapon's gameplay tags. 武器游戏标签。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GCS|Weapon")
const FGameplayTagContainer GetWeaponTags() const;
/**
* Sets the weapon's active state.
* 设置武器的激活状态。
* @param bNewActive The new active state. 新激活状态。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category = "GCS|Weapon")
void SetWeaponActive(bool bNewActive);
/**
* Checks if the weapon is active.
* 检查武器是否激活。
* @return True if the weapon is active. 如果武器激活返回true。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category = "GCS|Weapon")
bool IsWeaponActive() const;
/**
* Gets the main primitive component of the weapon.
* 获取武器的主要原始组件。
* @return The primitive component. 原始组件。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category = "GCS|Weapon")
UPrimitiveComponent* GetPrimitiveComponent() const;
virtual UPrimitiveComponent* GetPrimitiveComponent_Implementation() const;
/**
* Gets the targeting start transform for ranged weapons.
* 获取远程武器的目标起始变换。
* @return The targeting start transform. 目标起始变换。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GCS|Weapon", meta=(DisplayName="Get Targeting Start Transform"))
FTransform GCS_GetTargetingStartTransform() const;
/**
* Toggles targeting for the weapon.
* 切换武器的目标状态。
* @param bEnable Whether to enable targeting. 是否启用目标。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GCS|Weapon", meta=(DisplayName="Toggle Targeting"))
void GCS_ToggleTargeting(bool bEnable);
/**
* Toggles trails for the weapon.
* 开关武器拖尾。
* @param bEnable Whether to enable trails. 是否启用武器拖尾
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GCS|Weapon", meta=(DisplayName="Toggle Trail"))
void ToggleTrail(bool bEnable);
};