Syntriax.Engine/Engine.Core/HierarchyObjectBase.cs

143 lines
3.6 KiB
C#

using Syntriax.Engine.Core.Abstract;
namespace Syntriax.Engine.Core;
public abstract class HierarchyObjectBase : IHierarchyObject
{
public event IHierarchyObject.OnEnteredHierarchyEventHandler? OnEnteredHierarchy = null;
public event IHierarchyObject.OnExitedHierarchyEventHandler? OnExitedHierarchy = null;
public event IEntity.OnIdChangedEventHandler? OnIdChanged = null;
public event IInitialize.OnInitializedEventHandler? OnInitialized = null;
public event IInitialize.OnFinalizedEventHandler? OnFinalized = null;
public event IAssignableStateEnable.OnStateEnableAssignedEventHandler? OnStateEnableAssigned = null;
public event IAssignable.OnUnassignedEventHandler? OnUnassigned = null;
public event INameable.OnNameChangedEventHandler? OnNameChanged = null;
private string _id = string.Empty;
private string _name = nameof(HierarchyObjectBase);
private bool _initialized = false;
private IStateEnable _stateEnable = null!;
private IGameManager _gameManager = null!;
public IGameManager GameManager => _gameManager;
public bool IsInHierarchy => _gameManager is not null;
public bool IsInitialized
{
get => _initialized;
private set
{
if (value == _initialized)
return;
_initialized = value;
if (value)
OnInitialized?.Invoke(this);
else
OnFinalized?.Invoke(this);
}
}
public virtual IStateEnable StateEnable => _stateEnable;
public string Name
{
get => _name;
set
{
if (value == _name) return;
string previousName = _name;
_name = value;
OnNameChanged?.Invoke(this, previousName);
}
}
public string Id
{
get => _id;
set
{
if (value == _id)
return;
string previousId = _id;
_id = value;
OnIdChanged?.Invoke(this, previousId);
}
}
public bool Assign(IStateEnable stateEnable)
{
if (IsInitialized)
return false;
_stateEnable = stateEnable;
_stateEnable.Assign(this);
OnStateEnableAssigned?.Invoke(this);
return true;
}
protected virtual void UnassignInternal() { }
public bool Unassign()
{
if (IsInitialized)
return false;
UnassignInternal();
OnUnassigned?.Invoke(this);
return true;
}
protected virtual void InitializeInternal() { }
public bool Initialize()
{
if (IsInitialized)
return false;
InitializeInternal();
IsInitialized = true;
return true;
}
protected virtual void FinalizeInternal() { }
public bool Finalize()
{
if (!IsInitialized)
return false;
FinalizeInternal();
IsInitialized = false;
return true;
}
protected virtual void OnEnteringHierarchy(IGameManager gameManager) { }
bool IHierarchyObject.EnterHierarchy(IGameManager gameManager)
{
if (IsInHierarchy)
return false;
_gameManager = gameManager;
OnEnteringHierarchy(gameManager);
OnEnteredHierarchy?.Invoke(this, gameManager);
return true;
}
protected virtual void OnExitingHierarchy(IGameManager gameManager) { }
bool IHierarchyObject.ExitHierarchy()
{
if (!IsInHierarchy || _gameManager is not IGameManager gameManager)
return false;
_gameManager = null!;
OnExitingHierarchy(gameManager);
OnExitedHierarchy?.Invoke(this, gameManager);
return true;
}
}