Files
2026-02-16 11:27:01 +09:00

127 lines
3.0 KiB
C++

#pragma once
#include <stdint.h>
#include "flecs.h"
#include "Tick.hpp"
#include "Inventory.hpp"
struct ResourceInfo
{
uint16_t ResourceID;
};
struct ResourceHealth
{
uint16_t MaxHealth{};
uint16_t Health{};
};
struct ResourceTick : public TickAccumulator
{};
struct Renewing
{};
struct RenewingTick : public TickAccumulator
{};
struct FullyGrown
{};
inline void Flecs_Resource(flecs::world& world)
{
world.component<ResourceInfo>()
.member<uint16_t>("ResourceID");
world.component<ResourceHealth>()
.member<uint16_t>("MaxHealth")
.member<uint16_t>("Health");
world.component<ResourceTick>()
.is_a<TickAccumulator>();
world.component<RenewingTick>()
.is_a<TickAccumulator>();
world.component<Renewing>()
.add<Freezes, ResourceTick>();
// harvesting resource to inventory
world.system<const ResourceInfo, const ResourceTick, WorldInventory, Inventory*>()
.kind(flecs::OnUpdate)
.without<Renewing>()
.each([](ResourceInfo info, ResourceTick tick, WorldInventory& worldInventory, Inventory* optionalInventory) {
if (tick.Finished())
{
bool pushToLocalInventory = optionalInventory && !optionalInventory->IsFull(info.ResourceID);
if (pushToLocalInventory) optionalInventory->AddItems(info.ResourceID, 1);
else worldInventory.AddItems(info.ResourceID, 1);
}
});
// decrease health if ResourceHealth component
world.system<ResourceHealth, const ResourceTick>()
.kind(flecs::OnUpdate)
.without<Renewing>()
.each([](ResourceHealth& health, ResourceTick tick){
health.Health -= tick.Finished();
});
// checking if we have to renew the resource
world.system<const ResourceHealth>()
.kind(flecs::OnUpdate)
.with<RenewingTick>()
.without<Renewing>()
.each([](flecs::entity entity, ResourceHealth health) {
if (health.Health == 0) {
entity.remove<FullyGrown>();
entity.add<Renewing>();
entity.ensure<RenewingTick>().AccumulatedTick = 0;
}
});
// finish renewing
world.system<ResourceHealth, RenewingTick>("Finish Renewing")
.kind(flecs::OnUpdate)
.with<Renewing>()
.each([](flecs::entity entity, ResourceHealth& health, RenewingTick& tick) {
if (tick.Finished()) {
health.Health = health.MaxHealth;
entity.remove<Renewing>();
entity.add<FullyGrown>();
entity.ensure<ResourceTick>().AccumulatedTick = 0;
}
});
}
inline void Resource_Ore_Helper(const flecs::entity& entity, uint16_t resourceID, uint16_t gatherTicks)
{
ResourceInfo info{};
info.ResourceID = resourceID;
ResourceTick tick{};
tick.MaxTick = gatherTicks;
entity.set<ResourceInfo>(info);
entity.set<ResourceTick>(tick);
}
inline void Resource_Tree_Helper(const flecs::entity& entity, uint16_t resourceID,
uint16_t gatherTicks, uint16_t maxHealth, uint16_t renewalTicks)
{
Resource_Ore_Helper(entity, resourceID, gatherTicks);
ResourceHealth health{};
health.MaxHealth = maxHealth;
health.Health = maxHealth;
RenewingTick tick{};
tick.MaxTick = renewalTicks;
entity.set<ResourceHealth>(health);
entity.set<RenewingTick>(tick);
entity.add<FullyGrown>();
}