载入中...
搜索中...
未找到
WorldInteraction.cpp
浏览该文件的文档.
2
3#include <cmath>
4#include <optional>
5#include <string>
6#include <utility>
8#include "rpg/GameState.h"
9#include "rpg/Tracker.h"
10#include "rpg/WorldState.h"
11
12// WorldInteraction.cpp
13namespace eve::rpg {
14namespace {
15
16eve::Result<int> interactionFailure(eve::DiagnosticCode code, std::string message, std::string path,
17 const WorldLootRequest &request) {
19 {{"mapId", request.mapId}, {"objectId", request.objectId}},
20 "rpg.world-loot"));
21}
22
23struct TrackerRollback {
24 std::unordered_map<std::string, QuestRuntime> entries;
25 std::vector<std::string> order;
26 std::vector<QuestEvent> pending;
27 std::vector<QuestEvent> polled;
28};
29
30void restoreTracker(Tracker &tracker, TrackerRollback rollback) {
31 tracker.entries = std::move(rollback.entries);
32 tracker.order = std::move(rollback.order);
33 tracker.pending = std::move(rollback.pending);
34 tracker.polled = std::move(rollback.polled);
35}
36
37} // namespace
38
41 const bool hasItem = !request.itemId.empty() || request.itemQuantity != 0;
42 const bool hasAttribute = !request.attributeId.empty() || request.attributeAmount != 0.0;
43 const bool hasNotification =
44 !request.notifyTopic.empty() || !request.notifyTarget.empty() || request.notifyAmount != 0;
45 if (!hasItem && !hasAttribute && !hasNotification)
46 return interactionFailure(eve::DiagnosticCode::InvalidArgument, "world loot must contain at least one effect",
47 "request", request);
48 if (hasItem && (request.itemId.empty() || request.itemQuantity <= 0))
49 return interactionFailure(eve::DiagnosticCode::InvalidArgument,
50 "item loot requires an id and positive quantity", "item", request);
51 if (hasAttribute &&
52 (request.attributeId.empty() || !std::isfinite(request.attributeAmount) || request.attributeAmount <= 0.0))
53 return interactionFailure(eve::DiagnosticCode::InvalidArgument,
54 "attribute loot requires an id and finite positive amount", "attribute", request);
55 if (hasAttribute && !std::isfinite(gameState.getVariable(request.attributeId) + request.attributeAmount))
56 return interactionFailure(eve::DiagnosticCode::InvalidArgument,
57 "attribute loot would produce a non-finite value", "attribute.amount", request);
58 if (hasNotification && (request.notifyTopic.empty() || request.notifyTarget.empty() || request.notifyAmount <= 0))
59 return interactionFailure(eve::DiagnosticCode::InvalidArgument,
60 "quest notification requires topic, target, and positive amount", "notification",
61 request);
62 if (!request.requiredQuestId.empty() && tracker.getState(request.requiredQuestId) != "active")
63 return interactionFailure(eve::DiagnosticCode::PreconditionViolation,
64 "required quest must be active before collecting world loot", "requiredQuestId",
65 request);
66
67 auto gameStateBefore = gameState.snapshotJson();
68 if (!gameStateBefore.ok()) return eve::Result<int>::failure(gameStateBefore.status());
69 std::string gameStateSnapshot = std::move(gameStateBefore).takeValue();
70 GameState candidateState;
71 auto candidateRestore = candidateState.restoreSnapshotJson(gameStateSnapshot);
72 if (!candidateRestore.ok()) return eve::Result<int>::failure(candidateRestore.status());
73 WorldState candidateWorld(candidateState);
74 if (candidateWorld.isObjectConsumed(request.mapId, request.objectId))
75 return interactionFailure(eve::DiagnosticCode::Conflict, "world loot object was already consumed", "objectId",
76 request);
77 auto candidateConsume = candidateWorld.consumeObject(request.mapId, request.objectId);
78 if (!candidateConsume.ok()) return eve::Result<int>::failure(candidateConsume.status());
79
80 std::optional<inventory::PreparedInventoryAdd> preparedInventory;
81 if (hasItem) {
82 auto prepared = inventory::InventorySystem::prepareAddBatch(&bag, {{request.itemId, request.itemQuantity}});
83 if (!prepared.ok()) return eve::Result<int>::failure(prepared.status());
84 preparedInventory.emplace(std::move(prepared).takeValue());
85 }
86
87 TrackerRollback trackerBefore{tracker.entries, tracker.order, tracker.pending, tracker.polled};
88 if (hasAttribute) gameState.addVariable(request.attributeId, request.attributeAmount);
89 if (hasNotification) tracker.notify(request.notifyTopic, request.notifyTarget, request.notifyAmount);
90 WorldState world(gameState);
91 auto consumed = world.consumeObject(request.mapId, request.objectId);
92 if (!consumed.ok() || consumed.code() != eve::StatusCode::Applied) {
93 auto restored = gameState.restoreSnapshotJson(gameStateSnapshot);
94 const bool restoredOk = restored.ok();
95 restoreTracker(tracker, std::move(trackerBefore));
96 if (!restoredOk)
97 return interactionFailure(eve::DiagnosticCode::InvariantViolation,
98 "world loot rollback could not restore GameState", "rollback", request);
99 return interactionFailure(eve::DiagnosticCode::Conflict, "world loot object changed before commit", "objectId",
100 request);
101 }
102
103 if (preparedInventory) {
104 auto committed = inventory::InventorySystem::commitAddBatch(std::move(*preparedInventory));
105 if (!committed.ok()) {
106 auto restored = gameState.restoreSnapshotJson(gameStateSnapshot);
107 const bool restoredOk = restored.ok();
108 restoreTracker(tracker, std::move(trackerBefore));
109 if (!restoredOk)
110 return interactionFailure(eve::DiagnosticCode::InvariantViolation,
111 "world loot rollback could not restore GameState", "rollback", request);
112 return eve::Result<int>::failure(committed.status());
113 }
114 }
115
117 static_cast<int>(hasItem) + static_cast<int>(hasAttribute) + static_cast<int>(hasNotification) + 1,
119}
120
121} // namespace eve::rpg
122
123// WorldState.cpp
124namespace eve::rpg {
125namespace {
126
127constexpr std::size_t maxIdBytes = 256;
128
129bool validId(std::string_view id) {
130 if (id.empty() || id.size() > maxIdBytes) return false;
131 for (unsigned char character : id)
132 if (character < 0x20 || character == 0x7f) return false;
133 return true;
134}
135
136std::string scope(std::string_view mapId) { return "world.object:" + std::string(mapId); }
137
138} // namespace
139
140bool WorldState::isObjectConsumed(std::string_view mapId, std::string_view objectId) const {
141 if (!gameState_ || !validId(mapId) || !validId(objectId)) return false;
142 const std::string owningScope = scope(mapId);
143 const std::string owningObjectId(objectId);
144 return gameState_->hasSelfVariable(owningScope, owningObjectId) &&
145 gameState_->getSelfVariable(owningScope, owningObjectId) != 0.0;
146}
147
148eve::Result<void> WorldState::consumeObject(std::string_view mapId, std::string_view objectId) {
149 if (!validId(mapId))
151 eve::DiagnosticCode::InvalidArgument, "world-state IDs must be non-empty, bounded, and control-free",
152 "mapId", {}, "rpg.world-state"));
153 if (!validId(objectId))
155 eve::DiagnosticCode::InvalidArgument, "world-state IDs must be non-empty, bounded, and control-free",
156 "objectId", {}, "rpg.world-state"));
157 if (isObjectConsumed(mapId, objectId))
159 gameState_->setSelfVariable(scope(mapId), std::string(objectId), 1.0);
161}
162
163eve::Result<void> WorldState::resetObject(std::string_view mapId, std::string_view objectId) {
164 if (!validId(mapId))
166 eve::DiagnosticCode::InvalidArgument, "world-state IDs must be non-empty, bounded, and control-free",
167 "mapId", {}, "rpg.world-state"));
168 if (!validId(objectId))
170 eve::DiagnosticCode::InvalidArgument, "world-state IDs must be non-empty, bounded, and control-free",
171 "objectId", {}, "rpg.world-state"));
172 if (!isObjectConsumed(mapId, objectId))
174 gameState_->setSelfVariable(scope(mapId), std::string(objectId), 0.0);
176}
177
178} // namespace eve::rpg
std::vector< QuestEvent > pending
std::unordered_map< std::string, QuestRuntime > entries
std::vector< QuestEvent > polled
bool committed
全局游戏状态:开关(bool)、变量(数字)、独立变量(按作用域)。
std::string message
DiagnosticCode code
const GltfImportRequest & request
JobScope scope
std::string id
std::vector< std::int32_t > order
std::string path
Definition PlayHost.cpp:111
目标追踪器运行时实例(玩家日志 / 成就 / 教程可各建一份)。
float size
Definition TreeMesh.cpp:158
Atomic settlement of persistent world loot interactions.
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
bool ok() const noexcept
Whether this result represents a non-failure outcome.
Definition Result.h:514
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
格子型物品容器(脚本可直接操作)。
Definition Bag.h:22
static eve::Result< int > commitAddBatch(PreparedInventoryAdd prepared)
Commit one prepared addition and then publish its change events.
static eve::Result< PreparedInventoryAdd > prepareAddBatch(Bag *bag, const std::vector< InventoryItemGrant > &grants)
Validate a multi-item addition against a private candidate Bag.
一份游戏状态(开关/变量/独立变量)。
Definition GameState.h:26
double getVariable(const std::string &name) const
Returns the variable.
Definition GameState.cpp:65
void addVariable(const std::string &name, double delta)
Adds variable.
Definition GameState.cpp:70
eve::Result< void > restoreSnapshotJson(std::string_view json)
Validate and atomically restore a canonical RPG game-state JSON document.
eve::Result< std::string > snapshotJson() const
Serialize this state as the canonical versioned RPG game-state JSON document.
double getSelfVariable(const std::string &scope, const std::string &name) const
Returns the self variable.
Definition GameState.cpp:78
bool hasSelfVariable(const std::string &scope, const std::string &name) const
True when self variable.
Definition GameState.cpp:85
void setSelfVariable(const std::string &scope, const std::string &name, double value)
独立变量:scope(如 "map:1:event:3")下按名字存数字。
Definition GameState.cpp:74
一份任务进度 + 本实例事件队列。
Definition Tracker.h:26
std::unordered_map< std::string, QuestRuntime > entries
运行时条目(QuestSystem 读写;公开以便测试与脚本查询)。
Definition Tracker.h:148
std::vector< std::string > order
Definition Tracker.h:149
std::vector< QuestEvent > pending
Definition Tracker.h:150
void notify(const std::string &topic, const std::string &target, int amount)
Notify.
Definition Tracker.cpp:26
std::string getState(const std::string &id) const
Returns the state.
Definition Tracker.cpp:202
std::vector< QuestEvent > polled
Definition Tracker.h:151
static eve::Result< int > collectLoot(GameState &gameState, Tracker &tracker, inventory::Bag &bag, const WorldLootRequest &request)
Atomically grant loot, notify quest progress, and consume one world object.
Non-owning typed adapter for persistent per-map object lifecycle state.
Definition WorldState.h:19
eve::Result< void > resetObject(std::string_view mapId, std::string_view objectId)
Idempotently clear the consumed fact for one stable map object.
bool isObjectConsumed(std::string_view mapId, std::string_view objectId) const
Query whether a stable object has been consumed in one map.
eve::Result< void > consumeObject(std::string_view mapId, std::string_view objectId)
Idempotently publish the consumed fact for one stable map object.
RPG 模块的基础实体:把属性 / 状态 / 技能三张表挂到一个 ECS 实体上。
DiagnosticCode
Stable machine-readable diagnostic codes.
Definition Diagnostic.h:47
Complete data needed to settle one persistent loot object.
bool consumed
Definition Graphics.cpp:201