载入中...
搜索中...
未找到
ClimbingServices.cpp
浏览该文件的文档.
1// eve-hot-path
3
5
6#include "common/Capability.h"
7#include "common/CrashLog.h"
9#include "common/Value.h"
10#include "physics/World3D.h"
11
12#include <algorithm>
13#include <cstdint>
14#include <memory>
15#include <span>
16#include <utility>
17#include <vector>
18
19namespace eve::climbing {
20namespace {
21
22bool commandMatches(ClimbingCommandRequirement requirement, ClimbingCommand command) {
23 if (requirement == ClimbingCommandRequirement::Any) return true;
24 return (requirement == ClimbingCommandRequirement::Jump && command == ClimbingCommand::Jump) ||
25 (requirement == ClimbingCommandRequirement::Climb && command == ClimbingCommand::Climb) ||
26 (requirement == ClimbingCommandRequirement::Drop && command == ClimbingCommand::Drop) ||
27 (requirement == ClimbingCommandRequirement::Sprint && command == ClimbingCommand::Sprint) ||
29}
30
31} // namespace
32
34 ClimbingRuntime& runtime, physics::World3D& world, const ClimbingPose& pose, ClimbingIntent& intent,
37 if (subject.isZero())
39 "service subject must be non-zero",
40 "subject", {}, "climbing.services"));
41 if (!ClimbingInputSystem::peek(intent, command, tick))
43 eve::DiagnosticCode::NotFound, "climbing.input.no_match", "intent.commands", {}, "climbing.services"));
44
45 ClimbingPose effectivePose = pose;
46 if (!effectivePose.grounded && command != ClimbingCommand::Drop &&
47 ClimbingInputSystem::coyoteWindowState(tick, lastGroundedTick, runtime.profile_.coyoteTicks) ==
49 effectivePose.grounded = true;
50 auto prepared = runtime.prepareBegin(world, effectivePose, tick);
51 if (!prepared) return eve::Result<ClimbingServiceStart>::failure(prepared.status());
52 if (!commandMatches(prepared.value().action.requiredCommand, command))
54 eve::DiagnosticCode::NotFound, "selected action does not accept the buffered command",
55 "action.requiredCommand", {}, "climbing.services"));
56
57 if (!prepared.value().action.requiredConditionTags.empty()) {
58 IClimbingConditionAuthority* conditions = eve::cap::query<IClimbingConditionAuthority>();
59 if (!conditions)
61 eve::DiagnosticCode::Unsupported, "required climbing condition provider is absent", "conditions", {},
62 "climbing.services"));
63 auto decision = conditions->evaluate(subject, prepared.value().action.requiredConditionTags, tick);
64 if (!decision) return eve::Result<ClimbingServiceStart>::failure(decision.status());
65 if (decision.value() != ClimbingConditionDecision::Allowed)
67 eve::DiagnosticCode::PreconditionViolation, "climbing action conditions were denied", "conditions", {},
68 "climbing.services"));
69 prepared.value().conditionsSatisfied = true;
70 }
71
72 IClimbingStaminaAuthority* stamina = nullptr;
75 if (prepared.value().action.staminaCost > 0.f &&
76 runtime.profile_.staminaPolicy != ClimbingStaminaPolicy::Disabled) {
77 stamina = eve::cap::query<IClimbingStaminaAuthority>();
78 if (!stamina && runtime.profile_.staminaPolicy == ClimbingStaminaPolicy::RequireProvider)
80 eve::Diagnostic::error(eve::DiagnosticCode::Unsupported, "required climbing stamina provider is absent",
81 "stamina", {}, "climbing.services"));
82 if (!stamina) {
84 } else {
85 if (!runtime.profile_.staminaAdapter.empty() &&
86 stamina->adapterId() != runtime.profile_.staminaAdapter)
88 eve::DiagnosticCode::Unsupported, "configured climbing stamina adapter is not available",
89 "staminaAdapter", {}, "climbing.services"));
90 auto reserved = stamina->prepare(subject, prepared.value().action.staminaCost, tick);
91 if (!reserved) return eve::Result<ClimbingServiceStart>::failure(reserved.status());
92 reservation = reserved.value();
93 if (reservation.isZero())
95 eve::DiagnosticCode::InvariantViolation, "stamina provider returned a zero reservation", "stamina",
96 {}, "climbing.services"));
98 }
99 }
100
101 const ClimbingIntent originalIntent = intent;
102 auto consumed = ClimbingInputSystem::consume(intent, command, tick, prepared.value().executionId);
103 if (!consumed || !consumed.value()) {
104 intent = originalIntent;
105 if (stamina) stamina->cancelPrepared(reservation);
108 eve::Diagnostic::error(eve::DiagnosticCode::Conflict, "eligible climbing input changed before commit",
109 "intent.commands", {}, "climbing.services"));
110 }
111 auto committed = runtime.commitBegin(std::move(prepared).takeValue());
112 if (!committed) {
113 intent = originalIntent;
114 if (stamina) stamina->cancelPrepared(reservation);
116 }
117 if (stamina) stamina->commitPrepared(reservation, committed.value().executionId);
118 return eve::Result<ClimbingServiceStart>::success({std::move(committed).takeValue(), staminaState},
120}
121
137
153
154// ---------------------------------------------------------------------------
155// 脚本提供方接缝:IClimbingEventSink
156// ---------------------------------------------------------------------------
157
158namespace {
159
167class ScriptClimbingEventSink final : public IClimbingEventSink {
168public:
169 explicit ScriptClimbingEventSink(eve::ScriptProviderHandle handle) : handle_(std::move(handle)) {}
170
172 [[nodiscard]] const eve::ScriptProviderHandle& handle() const noexcept { return handle_; }
173
174 eve::Result<void> publish(ClimbingServiceSubject subject, std::span<const ClimbingEvent> events) override {
175 const eve::ScriptArg args[] = {
176 eve::ScriptArg::fromTable({{"subject", eve::Value::integer(static_cast<std::int64_t>(subject.value()))},
177 {"events", climbingEventArrayValue(events)}})};
178 return eve::ScriptProviderRegistry::instance().call(handle_, "publishClimbingEvents", args);
179 }
180
181private:
183};
184
186struct ScriptClimbingEventProviders {
187 std::vector<std::unique_ptr<ScriptClimbingEventSink>> live;
188 std::vector<std::unique_ptr<ScriptClimbingEventSink>> retired;
189};
190
191ScriptClimbingEventProviders& scriptClimbingEventProviders() {
192 static ScriptClimbingEventProviders state;
193 return state;
194}
195
196} // namespace
197
199 ScriptClimbingEventProviders& owned = scriptClimbingEventProviders();
203 // 单实现槽位:`provide` 会顶掉当前实现,顶掉必须可见(否则原生 sink 会"悄悄失效",
204 // 而症状只是事件不再被派发)。
205 if (eve::cap::query<IClimbingEventSink>() != nullptr) {
206 eve::recordLogEvent("warn", "script climbing event provider '" + handle.name +
207 "' replaced the provider that owned IClimbingEventSink");
208 }
209 auto adapter = std::make_unique<ScriptClimbingEventSink>(handle);
210 ScriptClimbingEventSink* raw = adapter.get();
211 eve::cap::provide<IClimbingEventSink>(raw);
212 owned.live.push_back(std::move(adapter));
214 },
216 const auto match = std::find_if(owned.live.begin(), owned.live.end(),
217 [&handle](const std::unique_ptr<ScriptClimbingEventSink>& adapter) {
218 return adapter->handle() == handle;
219 });
220 if (match == owned.live.end()) {
221 // 幂等:后置条件是"这一代没有适配器",模块退出时可能已经撤过了。
223 }
224 eve::cap::revoke<IClimbingEventSink>(match->get());
225 owned.retired.push_back(std::move(*match));
226 owned.live.erase(match);
228 });
229}
230
232 ScriptClimbingEventProviders& owned = scriptClimbingEventProviders();
233 for (auto& adapter : owned.live) {
234 eve::cap::revoke<IClimbingEventSink>(adapter.get());
235 owned.retired.push_back(std::move(adapter));
236 }
237 owned.live.clear();
240 .ignore("module teardown may already have dropped this seam");
241}
242
244
246
247} // namespace eve::climbing
int subject
Definition AnimSmr.cpp:163
ActiveSource owned
eve::EntitySpatialPose pose
攀爬事件 ↔ eve::Value 的**唯一**映射。
std::vector< std::unique_ptr< ScriptClimbingEventSink > > live
std::vector< std::unique_ptr< ScriptClimbingEventSink > > retired
Consumer-owned contracts for optional stamina, event, and pose integrations.
bool committed
bool applied
Persistent, thread-safe record of engine crash and problem events.
double raw
#define EVENGINE_API_DOMAINS
Definition Export.h:110
std::vector< particles::ParticleRecordEvent > events
PrimitiveHandle handle
std::string_view adapter
SimulationTick tick
Owning, renderer-independent dynamic values.
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
void ignore(std::string_view reason={}) const noexcept
Explicitly discard this result after documenting the reason.
Definition Result.h:571
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
Result< void > removeCapability(std::string_view capability)
Withdraw a declared seam when its owning module goes away.
static ScriptProviderRegistry & instance()
Process-lifetime registry; clearAll is the only reset.
void declareCapability(std::string capability, ScriptCapabilityBinder binder, ScriptCapabilityUnbinder unbinder)
Declare that one native capability may be served by a script provider.
Result< void > call(const ScriptProviderHandle &handle, std::string_view method) const
Call method() on a published provider.
static Status success(StatusCode code=StatusCode::Ok)
Construct a successful status with an explicit non-error outcome.
Definition Status.cpp:19
static Value integer(std::int64_t value)
Compatibility factory for an Int64 value.
Definition Value.h:115
static ClimbingCoyoteState coyoteWindowState(eve::SimulationTick currentTick, eve::SimulationTick lastGroundedTick, std::uint64_t coyoteTicks) noexcept
Evaluate a grounded grace window without reading wall clock.
static eve::Result< std::optional< BufferedClimbingCommand > > consume(ClimbingIntent &intent, ClimbingCommand command, eve::SimulationTick currentTick, ClimbingExecutionId executionId)
Atomically mark the oldest eligible command consumed by one committed execution.
static std::optional< BufferedClimbingCommand > peek(const ClimbingIntent &intent, ClimbingCommand command, eve::SimulationTick currentTick) noexcept
Observe the oldest eligible command without consuming or pruning intent.
Owner-thread climbing planner and executor for one character.
Definition Climbing.h:659
static eve::Result< ClimbingServiceStart > tryStart(ClimbingRuntime &runtime, physics::World3D &world, const ClimbingPose &pose, ClimbingIntent &intent, ClimbingCommand command, eve::SimulationTick tick, eve::SimulationTick lastGroundedTick, ClimbingServiceSubject subject)
Start one action and publish any configured stamina debit exactly once.
Climbing()
构造时声明脚本接缝(IClimbingEventSink 可由脚本提供)。
~Climbing() override
析构时撤回接缝与仍在位的脚本适配器。
Consumer-owned authority for project-specific condition tags.
virtual eve::Result< ClimbingConditionDecision > evaluate(ClimbingServiceSubject subject, std::span< const std::string > requiredTags, eve::SimulationTick tick)=0
Evaluate every required tag for one subject at the injected simulation tick.
Optional post-simulation event adapter; it does not own the runtime event queue.
virtual eve::Result< void > publish(ClimbingServiceSubject subject, std::span< const ClimbingEvent > events)=0
Consume an owning event view after all ECS simulation views have closed.
static constexpr const char * capabilityName
Optional post-physics Animation/IK adapter consuming derived pose constraints only.
Consumer-owned stamina reservation contract.
virtual std::string_view adapterId() const noexcept=0
Stable adapter identity matched against ClimbingProfileDefinition::staminaAdapter.
virtual eve::Result< ClimbingStaminaReservation > prepare(ClimbingServiceSubject subject, float cost, eve::SimulationTick tick)=0
Reserve an exact non-negative cost without publishing the debit.
virtual void cancelPrepared(ClimbingStaminaReservation reservation) noexcept=0
Release an uncommitted reservation; guaranteed infallible and idempotent.
virtual void commitPrepared(ClimbingStaminaReservation reservation, ClimbingExecutionId executionId) noexcept=0
Publish a successfully prepared debit; guaranteed infallible by the provider contract.
constexpr std::uint64_t value() const noexcept
Returns the underlying value at an explicit protocol boundary.
static constexpr StrongUint64 zero() noexcept
Returns the zero value for this strong type.
constexpr bool isZero() const noexcept
Returns whether this value is zero.
Box3D rigid-body world. Script coordinates are meters (Box3D native), unlike 2D World which uses pixe...
Definition World3D.h:47
EVENGINE_API_DOMAINS void declareScriptClimbingEventSeam()
声明"`IClimbingEventSink` 可以由脚本提供"这条接缝。
ClimbingOptionalServiceState
Observable outcome of one optional-service interaction.
Value climbingEventArrayValue(std::span< const ClimbingEvent > events)
一批事件 → Value 数组,顺序与传入一致。
ClimbingCommandRequirement
Input edge required by an action definition; Any keeps legacy automatic selection.
Definition Climbing.h:79
ClimbingCommand
Edge and held commands understood by the climbing input phase.
eve::detail::StrongUint64< detail::ClimbingServiceSubjectTag > ClimbingServiceSubject
Stable gameplay-owned subject identity passed to optional adapters.
eve::Result< ClimbingPoseResult > applyClimbingPose(animation::AnimSkeleton &skeleton, animation::AnimPose &pose, const ClimbingAdvance &advance, const ClimbingPoseBinding &binding)
Applies contact anchors to an already evaluated animation pose.
EVENGINE_API_DOMAINS eve::Result< ClimbingOptionalServiceState > dispatchClimbingEvents(ClimbingServiceSubject subject, std::span< const ClimbingEvent > events)
Dispatch to the optional event sink, returning ProviderAbsent instead of silently dropping.
EVENGINE_API_DOMAINS void withdrawScriptClimbingEventSeam()
撤回接缝与仍然在位的脚本适配器(由 Climbing 模块析构时调用)。
Result< int > publish(Heightmap &target, std::vector< float > candidate)
Publish.
void recordLogEvent(const std::string &level, const std::string &message)
Appends a timestamped event line to the crash/error log.
Definition CrashLog.cpp:70
One argument passed to a script provider method.
static ScriptArg fromTable(Value::Object fields)
One object argument (a table on the script side). @cost One Value tree copy.
Generation-qualified identity of one published script provider.
Owning output of one execution tick.
Definition Climbing.h:553
Hot authoritative intent component; contains no device or callback pointers.
Input pose used for one deterministic candidate probe.
Definition Climbing.h:275
bool consumed
Definition Graphics.cpp:201