载入中...
搜索中...
未找到
ActionEncounter.cpp
浏览该文件的文档.
2#include <cmath>
3#include "common/Capability.h"
6#include "rpg/RPGActor.h"
7
8namespace eve::rpg {
11 std::optional<RPGActionDamageReceipt> pending;
12 int lastTick = -1;
13 bool bound = false;
14 RPGActionDamageSink sink{[this](ecs::EntityHandle handle) -> std::optional<RPGDamageTarget> {
15 auto same = [&](const RPGDamageTarget& value) {
16 return handle.table == value.actor.table && handle.type == value.actor.type &&
17 handle.id == value.actor.id && handle.generation == value.actor.generation;
18 };
19 if (same(player)) return player;
20 if (same(enemy)) return enemy;
21 return std::nullopt;
22 }};
23};
24ActionEncounter::ActionEncounter() : impl_(std::make_unique<Impl>()) {}
26void ActionEncounter::close() noexcept { impl_.reset(); }
27Result<void> ActionEncounter::bind(RPGActor& player, RPGActor& enemy, std::string_view playerId,
28 std::string_view enemyId) {
29 const auto source = PersistentId::parse(playerId);
30 const auto target = PersistentId::parse(enemyId);
31 if (!source || !target || !SubjectRef::fromPersistentId(*source).isValid() ||
32 !SubjectRef::fromPersistentId(*target).isValid() || *source == *target || &player == &enemy)
34 Diagnostic::error(DiagnosticCode::InvalidArgument, "Distinct actors and life UUIDs required"));
35 if (!impl_) impl_ = std::make_unique<Impl>();
36 if (impl_->pending)
38 Diagnostic::error(DiagnosticCode::Conflict, "Claim pending reward before rebinding"));
39 impl_->player = {ecs::handle_of(&player), SubjectRef::fromPersistentId(*source)};
40 impl_->enemy = {ecs::handle_of(&enemy), SubjectRef::fromPersistentId(*target)};
41 impl_->lastTick = -1;
42 impl_->bound = true;
43 return Result<void>::success();
44}
45Result<double> ActionEncounter::hit(bool playerAttacks, double amount, int tick) {
46 if (!impl_)
48 if (tick < 0 || tick < impl_->lastTick || !std::isfinite(amount) || amount <= 0.0)
50 Diagnostic::error(DiagnosticCode::InvalidArgument, "Positive finite damage and monotonic tick required"));
51 if (impl_->pending)
52 return Result<double>::failure(Diagnostic::error(DiagnosticCode::Conflict, "Reward delivery is pending"));
53 const auto source = playerAttacks ? impl_->player : impl_->enemy;
54 const auto target = playerAttacks ? impl_->enemy : impl_->player;
55 auto* attacker = dynamic_cast<RPGActor*>(ecs::try_get(source.actor));
56 auto* defender = dynamic_cast<RPGActor*>(ecs::try_get(target.actor));
57 if (!attacker || !defender)
59 Diagnostic::error(DiagnosticCode::StaleHandle, "Encounter participant was destroyed"));
60 if (attacker->getCurrent("hp") <= 0 || defender->getCurrent("hp") <= 0)
62 Diagnostic::error(DiagnosticCode::PreconditionViolation, "Both participants must be alive"));
63 // The registry chooses its first accepting provider. Reject ambiguous ownership
64 // before any provider can commit damage or enqueue a receipt for another encounter.
65 std::size_t accepting = 0;
66 bool ownsTarget = false;
67 cap::forEach<action::IActionDamageSink>([&](action::IActionDamageSink* sink) {
68 if (!sink->supports(target.actor)) return;
69 ++accepting;
70 ownsTarget = ownsTarget || sink == &impl_->sink;
71 });
72 if (accepting != 1 || !ownsTarget)
74 DiagnosticCode::Conflict, "Encounter target must have exactly one owning damage provider"));
76 if (!registry) return Result<double>::failure(registry.status());
78 event.type = *LogicalId::parse("combat:damage");
79 event.payload = {{"damageType", "Damage.Physical"}, {"amount", amount}};
81 context.source = source.actor;
82 context.targets = {target.actor};
83 context.tick = SimulationTick(static_cast<unsigned long long>(tick));
84 auto dispatched = registry.value().dispatch(event, context);
85 if (!dispatched) return Result<double>::failure(dispatched.status());
86 auto receipts = impl_->sink.takeReceipts();
87 if (receipts.size() != 1)
89 Diagnostic::error(DiagnosticCode::InvariantViolation, "Encounter requires sole damage provider ownership"));
90 impl_->lastTick = tick;
91 if (playerAttacks && receipts.front().killed) impl_->pending = receipts.front();
92 return Result<double>::success(receipts.front().applied);
93}
94Result<void> ActionEncounter::claim(GameState& state, Tracker& tracker, std::string_view encounterId) {
95 if (!impl_ || !impl_->pending) return Result<void>::success(Status::success(StatusCode::NoOp));
96 auto result = ActionKillReward::settle(impl_->player, state, tracker, *impl_->pending, encounterId);
97 if (!result) return Result<void>::failure(result.status());
98 impl_->pending.reset();
99 return Result<void>::success(result.status());
100}
101bool ActionEncounter::hasPendingReward() const { return impl_ && impl_->pending.has_value(); }
102bool ActionEncounter::isClosed() const { return !impl_; }
103bool ActionEncounter::isBound() const { return impl_ && impl_->bound; }
104int ActionEncounter::lastTick() const { return impl_ ? impl_->lastTick : -1; }
105} // namespace eve::rpg
LogicalId target
Poco::JSON::Object::Ptr result
PrimitiveHandle handle
const eve::script::BindingContractRegistry & registry
Object::Ptr value
std::string_view source
SimulationTick tick
const VegetationPresetContext & context
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
static std::optional< LogicalId > parse(std::string_view text)
Parses a scoped logical name.
Definition Identity.cpp:37
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
static Status success(StatusCode code=StatusCode::Ok)
Construct a successful status with an explicit non-error outcome.
Definition Status.cpp:19
static SubjectRef fromPersistentId(PersistentId id) noexcept
Wrap a persistent identity without changing its bytes.
Definition SubjectRef.h:32
bool isValid() const noexcept
Return whether this reference is valid and non-nil.
Definition SubjectRef.h:38
static Result< ActionNotifyRegistry > withBuiltins()
Build a registry containing the engine's standard semantic notify types.
Optional target-domain adapter for timeline damage.
virtual bool supports(ecs::EntityHandle target) const =0
Whether this sink can resolve the supplied target handle now.
static std::optional< Id128 > parse(std::string_view text) noexcept
Parses canonical UUID text.
Definition Identity.h:150
bool isClosed() const
True after close() or before the first construction of the provider.
int lastTick() const
Last injected tick that successfully committed a hit, or -1 when none. @cost Cheap read of host-facin...
Result< void > claim(GameState &state, Tracker &tracker, std::string_view encounterId)
Deliver the pending player kill to the canonical reward transaction.
bool isBound() const
True after a successful bind while the encounter remains open.
bool hasPendingReward() const
True while a committed death still needs reward delivery; saving is unsafe then.
void close() noexcept
Abandon this transient encounter and unregister immediately before restart/load.
~ActionEncounter()
Unregister the provider before destroying its link mapping.
Result< double > hit(bool playerAttacks, double amount, int tick)
Dispatch a physical hit through the action registry and authoritative RPG Vitals.
Result< void > bind(RPGActor &player, RPGActor &enemy, std::string_view playerId, std::string_view enemyId)
Bind borrowed actors to stable per-life UUID strings.
ActionEncounter()
Create an unbound encounter and scoped action damage provider.
static Result< BattleVictoryReceipt > settle(const RPGDamageTarget &recipient, GameState &gameState, Tracker &tracker, const RPGActionDamageReceipt &death, std::string_view encounterId)
Grant XP, class skills, gold and quest progress once for a committed death.
一份游戏状态(开关/变量/独立变量)。
Definition GameState.h:26
Scoped action damage provider using RPG Vitals as the sole health authority. @ownership Host owns thi...
属性 / 状态 / 技能三表合一的 ECS 实体。
Definition RPGActor.h:34
一份任务进度 + 本实例事件队列。
Definition Tracker.h:26
RPG 模块的基础实体:把属性 / 状态 / 技能三张表挂到一个 ECS 实体上。
detail::StrongUint64< detail::SimulationTickTag > SimulationTick
Deterministic simulation time step; it is not wall-clock time.
Definition Time.h:31
Context linking a routed event to its action execution.
std::optional< ecs::EntityHandle > source
Optional source entity; resolved by consumers at call time.
Owning event projection returned by the runtime sampler.
std::optional< RPGActionDamageReceipt > pending
Owning identity projection; the host owns the mapping, ECS owns the actor.