ezEngine Release 26.9
Loading...
Searching...
No Matches
ezAiVoxelNavigationComponent Class Reference

#include <VoxelNavigationComponent.h>

Inheritance diagram for ezAiVoxelNavigationComponent:

Public Member Functions

virtual void SerializeComponent (ezWorldWriter &inout_stream) const override
 Override this to save the current state of the component to the given stream.
 
virtual void DeserializeComponent (ezWorldReader &inout_stream) override
 Override this to load the current state of the component from the given stream.
 
void SetDestination (const ezVec3 &vGlobalPos)
 Sets the target position to navigate towards.
 
void SetDestinationDirect (const ezVec3 &vGlobalPos)
 [ scriptable ]
 
void CancelNavigation ()
 Stops all navigation.
 
ezEnum< ezAiVoxelNavigationComponentStateGetState () const
 Returns the current navigation state.
 
void SetNavigationTargetReference (const char *szReference)
 
void SetNavigationTarget (ezGameObjectHandle hObject)
 [ scriptable ]
 
ezAngle TurnTowards (const ezVec3 &vDirection)
 [ scriptable ]
 
ezAngle GetTurnAngleTowards (const ezVec3 &vDirection) const
 [ scriptable ]
 
bool IsNavigating () const
 Returns true if the component is currently navigating along a path.
 
bool IsApproachingDestination () const
 [ scriptable ]
 
bool FindRandomPointAroundSphere (const ezVec3 &vCenter, float fRadius, ezUInt32 uiMaxAttempts, ezVec3 &out_vPoint)
 [ scriptable ]
 
bool GetValidCellNearby (const ezVec3 &vStart, float fSearchRadius, ezVec3 &out_vPoint) const
 [ scriptable ]
 
- Public Member Functions inherited from ezComponent
void SetActiveFlag (bool bEnabled)
 Sets the active flag of the component, which affects its active state.
 
bool GetActiveFlag () const
 Checks whether the 'active flag' is set on this component. Note that this does not mean that the component is also 'active'.
 
bool IsActive () const
 Checks whether this component is in an active state.
 
bool IsActiveAndInitialized () const
 Returns whether this component is active and initialized.
 
bool IsActiveAndSimulating () const
 Whether the component is currently active and simulation has been started as well.
 
ezComponentManagerBaseGetOwningManager ()
 Returns the corresponding manager for this component.
 
const ezComponentManagerBaseGetOwningManager () const
 Returns the corresponding manager for this component.
 
ezGameObjectGetOwner ()
 Returns the owner game object if the component is attached to one or nullptr.
 
const ezGameObjectGetOwner () const
 Returns the owner game object if the component is attached to one or nullptr.
 
ezWorldGetWorld ()
 Returns the corresponding world for this component.
 
const ezWorldGetWorld () const
 Returns the corresponding world for this component.
 
ezComponentHandle GetHandle () const
 Returns a handle to this component.
 
ezUInt32 GetUniqueID () const
 Returns the unique id for this component.
 
void SetUniqueID (ezUInt32 uiUniqueID)
 Sets the unique id for this component.
 
void EnsureInitialized ()
 Ensures that the component is initialized. Must only be called from another component's Initialize callback.
 
void EnsureSimulationStarted ()
 Ensures that the OnSimulationStarted method has been called. Must only be called from another component's OnSimulationStarted callback.
 
EZ_ALWAYS_INLINE bool SendMessage (ezMessage &ref_msg)
 Sends a message to this component.
 
EZ_ALWAYS_INLINE bool SendMessage (ezMessage &ref_msg) const
 
void PostMessage (const ezMessage &msg, ezTime delay=ezTime::MakeZero(), ezObjectMsgQueueType::Enum queueType=ezObjectMsgQueueType::NextFrame) const
 Queues the message for the given phase. The message is processed after the given delay in the corresponding phase.
 
virtual bool HandlesMessage (const ezMessage &msg) const
 Returns whether the given Message is handled by this component.
 
void SetUserFlag (ezUInt8 uiFlagIndex, bool bSet)
 Be careful to check which flags may already be in use by base classes.
 
bool GetUserFlag (ezUInt8 uiFlagIndex) const
 Retrieves a custom flag. Index must be between 0 and 7.
 
void SetCreatedByPrefab ()
 Adds ezObjectFlags::CreatedByPrefab to the component. See the flag for details.
 
bool WasCreatedByPrefab () const
 Checks whether the ezObjectFlags::CreatedByPrefab flag is set on this component.
 
void DeleteComponent ()
 Deletes this component. Note that the component will be invalidated first and the actual deletion is postponed.
 
- Public Member Functions inherited from ezReflectedClass
virtual const ezRTTIGetDynamicRTTI () const
 
bool IsInstanceOf (const ezRTTI *pType) const
 Returns whether the type of this instance is of the given type or derived from it.
 
template<typename T >
EZ_ALWAYS_INLINE bool IsInstanceOf () const
 Returns whether the type of this instance is of the given type or derived from it.
 

Public Attributes

float m_fSpeed = 5.0f
 [ property ] Target movement speed.
 
float m_fAcceleration = 3.0f
 [ property ] How fast to gain speed.
 
float m_fDeceleration = 8.0f
 [ property ] How fast to brake.
 
float m_fReachedDistance = 1.0f
 [ property ] Distance at which destination is considered reached.
 
bool m_bApplySteering = true
 [ property ] Whether to apply movement to the game object.
 
float m_fLookAheadDistance = 3.0f
 [ property ] How far ahead along the path to steer towards, instead of snapping onto waypoints.
 
float m_fMaxPathOffset = 3.0f
 [ property ] Max distance the visual position may stray from the path before being pulled back.
 
float m_fCorridorCorrectionRate = 8.0f
 [ property ] How fast the visual position is pulled back into the corridor once it exceeds MaxPathOffset.
 
ezAngle m_MaxAngularSpeed = ezAngle::MakeFromDegree(180.0f)
 [ property ] Maximum turning speed, used both while path-following and by TurnTowards().
 
float m_fBankAmount = 3.0f
 [ property ] How strongly to bank/tilt into turns while path-following. 0 disables banking; negative flips the bank direction.
 
ezAngle m_MaxBankAngle = ezAngle::MakeFromDegree(30.0f)
 [ property ] Maximum bank/tilt angle while turning.
 
ezBitflags< ezAiVoxelNavigationDebugFlags > m_DebugFlags
 [ property ]
 

Protected Member Functions

virtual void OnSimulationStarted () override
 This method is called once for active components, at the start of the next world update, but only when the world is simulated.
 
void Update ()
 
void MoveAlongPath (float fTimeDiff)
 
void DecelerateToStop (float fTimeDiff)
 
void SteerAndBank (const ezVec3 &vDesiredDir, float fTimeDiff)
 
float ComputeBrakingDistance (float fSpeed) const
 Distance needed to brake from fSpeed down to zero at m_fDeceleration.
 
float GetRemainingDistance () const
 Approximate remaining distance along the current path, or 0 if not navigating.
 
ezVec3 ApplyCorridorClamp (const ezVec3 &vCandidate, float fTimeDiff) const
 
- Protected Member Functions inherited from ezComponent
 ezComponent ()
 Keep the constructor private or protected in derived classes, so it cannot be called manually.
 
bool IsDynamic () const
 Returns whether this component is dynamic and thus can only be attached to dynamic game objects.
 
virtual ezWorldModuleTypeId GetTypeId () const =0
 
virtual ezComponentMode::Enum GetMode () const =0
 
virtual void Initialize ()
 Can be overridden for basic initialization that depends on a valid hierarchy and position.
 
virtual void Deinitialize ()
 This method is called before the component is destroyed. A derived type can override this method to do common de-initialization work.
 
virtual void OnActivated ()
 This method is called when the component gets activated.
 
virtual void OnDeactivated ()
 This method is called when the component gets deactivated.
 
void EnableUnhandledMessageHandler (bool enable)
 By default disabled. Enable to have OnUnhandledMessage() called for every unhandled message.
 
virtual bool OnUnhandledMessage (ezMessage &msg, bool bWasPostedMsg)
 When EnableUnhandledMessageHandler() was activated, this is called for all messages for which there is no dedicated message handler.
 
virtual bool OnUnhandledMessage (ezMessage &msg, bool bWasPostedMsg) const
 When EnableUnhandledMessageHandler() was activated, this is called for all messages for which there is no dedicated message handler.
 
bool IsInitialized () const
 
bool IsInitializing () const
 
bool IsSimulationStarted () const
 

Protected Attributes

ezAiVoxelNavigation m_Navigation
 
ezEnum< ezAiVoxelNavigationComponentStatem_State
 
ezGameObjectHandle m_hNavigationTarget
 
ezVec3 m_vVelocity = ezVec3::MakeZero()
 
ezVec3 m_vSteerPosition = ezVec3::MakeZero()
 
ezQuat m_qSteerRotation = ezQuat::MakeIdentity()
 
ezVec3 m_vPathPosition = ezVec3::MakeZero()
 Ground truth: always on the path, always in a free voxel.
 
float m_fPathSpeed = 0.0f
 Accel/decel-smoothed scalar speed for m_vPathPosition.
 
bool m_bPathPositionInitialized = false
 Not serialized; re-snapped to a valid voxel on first navigation each sim run.
 
float m_fVoxelSize = 0.5f
 Cached voxel size of the grid being navigated; refreshed on each SetDestination(). Not serialized. The initial value is only a fallback used before the first successful path.
 
ezUInt8 m_uiSkipNextFrames = 0
 
ezVec3 m_vLastPathTargetPos = ezVec3::MakeZero()
 
float m_fRepathCooldown = 0.0f
 
ezAngle m_BankAngle = ezAngle::MakeFromRadian(0.0f)
 
- Protected Attributes inherited from ezComponent
const ezRTTIm_pMessageDispatchType = nullptr
 Messages will be dispatched to this type. Default is what GetDynamicRTTI() returns, can be redirected if necessary.
 

Additional Inherited Members

- Static Public Member Functions inherited from ezNoBase
static const ezRTTIGetStaticRTTI ()
 

Detailed Description

Navigates a game object through 3D space using a voxel grid.

Suitable for flying creatures, underwater movement, or space navigation. Call SetDestination() with a world-space target. The component computes a 3D A* path through free voxels and steers the game object along that path.

Tracks two separate positions. The path position is the ground truth: it always lies exactly on the computed path (which is guaranteed clear - A*'d and string-pulled through free voxels) and advances along it by arc length every frame; it is only ever voxel-validated once, when a path is computed (SetDestination()/SetDestinationDirect()), never at runtime while moving. The steering position is the visual position actually applied to the game object: it free-form steers nose-first towards a look-ahead point on the path (LookAheadDistance) rather than snapping onto waypoints or the path position, and is explicitly not voxel-validated - it may lag or stray from the path, but is pulled back smoothly (CorridorCorrectionRate) once it strays further than MaxPathOffset (a "path corridor").

Because the ground truth can never leave the cleared path, following it can never get stuck: the Failed state is only reachable from SetDestination()/SetDestinationDirect() failing to find a path at all (unreachable target), never from runtime movement.

Turning is rate-limited (MaxAngularSpeed) and speed is reduced while turning sharply and while approaching the end of the path (Speed/Acceleration/Deceleration).

The object generally stays upright (local +Z towards world +Z); while turning it banks/tilts into the curve (BankAmount, clamped by MaxBankAngle), relaxing back to level once it stops turning.

Member Function Documentation

◆ ApplyCorridorClamp()

ezVec3 ezAiVoxelNavigationComponent::ApplyCorridorClamp ( const ezVec3 vCandidate,
float  fTimeDiff 
) const
protected

Pulls vCandidate back towards m_vPathPosition if it is further away than m_fMaxPathOffset, smoothly (rate m_fCorridorCorrectionRate) rather than snapping - the "path corridor" that keeps the free-form visual position from straying arbitrarily far from the path.

◆ CancelNavigation()

void ezAiVoxelNavigationComponent::CancelNavigation ( )

Stops all navigation.

[ scriptable ]

◆ DeserializeComponent()

void ezAiVoxelNavigationComponent::DeserializeComponent ( ezWorldReader inout_stream)
overridevirtual

Override this to load the current state of the component from the given stream.

The active state will be automatically serialized. The 'initialized' state is not serialized, all components will be initialized after creation, even if they were already in an initialized state when they were serialized.

Reimplemented from ezComponent.

◆ FindRandomPointAroundSphere()

bool ezAiVoxelNavigationComponent::FindRandomPointAroundSphere ( const ezVec3 vCenter,
float  fRadius,
ezUInt32  uiMaxAttempts,
ezVec3 out_vPoint 
)

[ scriptable ]

Attempts to find a random navigable point within a sphere around vCenter.

A sampled point counts as navigable if it is a free voxel in its covering grid, or lies outside all grids entirely (space not covered by any grid is treated as free, same convention as pathfinding). Returns false if the voxel grid is not ready or no navigable point was found after uiMaxAttempts random samples.

◆ GetState()

ezEnum< ezAiVoxelNavigationComponentState > ezAiVoxelNavigationComponent::GetState ( ) const
inline

Returns the current navigation state.

[ scriptable ]

◆ GetTurnAngleTowards()

ezAngle ezAiVoxelNavigationComponent::GetTurnAngleTowards ( const ezVec3 vDirection) const

[ scriptable ]

Peek-only companion to TurnTowards(): how much the object would have to turn to face vDirection, without changing anything.

◆ GetValidCellNearby()

bool ezAiVoxelNavigationComponent::GetValidCellNearby ( const ezVec3 vStart,
float  fSearchRadius,
ezVec3 out_vPoint 
) const

[ scriptable ]

Finds a navigable (free) point at or near vStart, preferring points that are physically closer to vStart. If vStart itself is already free (or not covered by any voxel grid at all), returns it unchanged. Otherwise searches for the closest free voxel within fSearchRadius.

Intended for recovering from an occupied start position - e.g. combine with SetDestinationDirect() to move out of a voxel that turned solid - but can also be used to nudge an arbitrary destination onto a valid cell before calling SetDestination().

Returns false if the voxel grid is not ready, or no free voxel was found within fSearchRadius.

◆ IsApproachingDestination()

bool ezAiVoxelNavigationComponent::IsApproachingDestination ( ) const

[ scriptable ]

Returns true if the component is navigating and the remaining path distance has entered the braking distance for Speed (i.e. it would start slowing down this frame if not redirected).

Useful for objects that should keep moving continuously (never actually decelerate to a stop): call SetDestination()/SetNavigationTarget() with a new target once this turns true, instead of waiting for IsNavigating() to become false.

◆ IsNavigating()

bool ezAiVoxelNavigationComponent::IsNavigating ( ) const
inline

Returns true if the component is currently navigating along a path.

[ scriptable ]

◆ OnSimulationStarted()

void ezAiVoxelNavigationComponent::OnSimulationStarted ( )
overrideprotectedvirtual

This method is called once for active components, at the start of the next world update, but only when the world is simulated.

This is the one preferred method to setup typical game logic. In a pure game environment there is no practical difference between OnActivated() and OnSimulationStarted(), as OnSimulationStarted() will be called right after OnActivated().

However, when a scene is open inside the editor, there is an important difference: OnActivated() is called once the component was created. OnSimulationStarted() is only called once the game simulation is started inside the editor. As an example, if a component starts a sound in OnActivated(), that sound will play right after the scene has been loaded into the editor. If instead the sound gets started in OnSimulationStarted(), it will only play once the user starts the game mode inside the editor.

Additionally, OnSimulationStarted() is only executed once, even if the ezWorld pauses and resumes world simulation multiple times. However, note that it will be called again after the component has been deactivated and is activated again.

See also
OnActivated(), OnDeactivated(), Initialize(), Deinitialize(), OnSimulationStarted()

Reimplemented from ezComponent.

◆ SerializeComponent()

void ezAiVoxelNavigationComponent::SerializeComponent ( ezWorldWriter inout_stream) const
overridevirtual

Override this to save the current state of the component to the given stream.

Reimplemented from ezComponent.

◆ SetDestination()

void ezAiVoxelNavigationComponent::SetDestination ( const ezVec3 vGlobalPos)

Sets the target position to navigate towards.

[ scriptable ]

◆ SetDestinationDirect()

void ezAiVoxelNavigationComponent::SetDestinationDirect ( const ezVec3 vGlobalPos)

[ scriptable ]

Sets the target position to fly straight towards, bypassing pathfinding and occlusion checks entirely - it just turns and moves in a straight line, using the same speed/acceleration/ turning behavior as regular path-following.

Useful for emergency recovery (e.g. the object ended up inside an occupied voxel and regular SetDestination() fails with InvalidStartPosition) or any other case where flying straight to a known-clear point is preferable to pathfinding. Combine with GetValidCellNearby() to first find a safe point to recover to.

◆ SteerAndBank()

void ezAiVoxelNavigationComponent::SteerAndBank ( const ezVec3 vDesiredDir,
float  fTimeDiff 
)
protected

Turns m_qSteerRotation towards vDesiredDir (see ezAiSteeringUtils::TurnTowards - this also re-levels any existing roll), then banks/tilts it into the turn by up to MaxBankAngle, smoothed via m_BankAngle so it relaxes back to level once the turn ends.

◆ TurnTowards()

ezAngle ezAiVoxelNavigationComponent::TurnTowards ( const ezVec3 vDirection)

[ scriptable ]

Rotates the object to face vDirection, turning at most by MaxAngularSpeed this frame.

Independent of any active path-following (typically used while Idle, e.g. to face a direction before deciding to call SetDestination()). If a path is currently being followed, this has no lasting effect: the path-following steering runs later in the same frame and will overwrite the rotation again next update.

Returns the remaining angle to face vDirection exactly (zero once fully turned), so script logic can decide e.g. whether it is facing closely enough to start moving now.

Member Data Documentation

◆ m_uiSkipNextFrames

ezUInt8 ezAiVoxelNavigationComponent::m_uiSkipNextFrames = 0
protected

Warm-up counter: Update() early-returns while this is > 0 (set in OnSimulationStarted()). Delays the first few updates after simulation start so the object's initial transform has settled (spawn/prefab instantiation, physics placement) and the voxel grid has become ready before the component starts driving the transform and pathfinding.


The documentation for this class was generated from the following files: