载入中...
搜索中...
未找到
DialogueState.cpp
浏览该文件的文档.
2
3#include "common/Capability.h"
5
6#include <algorithm>
7#include <string>
8#include <utility>
9#include <vector>
10
11namespace eve::dialogue {
12namespace {
13
14template <class T, class Query>
15std::optional<T> queryProviders(const std::string& subject, eve::IStateQuery* explicitProvider, Query&& query) {
16 if (explicitProvider) {
17 if (auto result = query(explicitProvider, subject); result.has_value()) return result;
18 }
19
20 eve::IStateQuery* service = eve::cap::query<eve::IStateQuery>();
21 if (service && service != explicitProvider) {
22 if (auto result = query(service, subject); result.has_value()) return result;
23 }
24
25 std::optional<T> result;
26 eve::cap::forEach<eve::IStateQuery>([&](eve::IStateQuery* provider) {
27 if (result.has_value() || provider == explicitProvider || provider == service) return;
29 });
30 return result;
31}
32
33eve::Result<eve::condition::Condition> conditionError(std::string message, std::string path = {}) {
36}
37
38bool readString(const eve::Value& object, std::string_view key, std::string& out) {
39 const eve::Value* value = object.find(std::string(key));
40 if (!value || !value->isString()) return false;
41 out = value->asString();
42 return true;
43}
44
45bool readOperator(std::string_view spelling, eve::condition::CompareOperator& out) {
46 if (spelling == "eq" || spelling == "equal" || spelling == "==") {
48 return true;
49 }
50 if (spelling == "ne" || spelling == "notEqual" || spelling == "!=") {
52 return true;
53 }
54 if (spelling == "lt" || spelling == "<") {
56 return true;
57 }
58 if (spelling == "le" || spelling == "<=") {
60 return true;
61 }
62 if (spelling == "gt" || spelling == ">") {
64 return true;
65 }
66 if (spelling == "ge" || spelling == "gte" || spelling == ">=") {
68 return true;
69 }
70 if (spelling == "lte") {
72 return true;
73 }
74 return false;
75}
76
77eve::Result<eve::condition::Condition> compileCondition(const eve::Value& specification) {
78 if (specification.isArray()) {
79 std::vector<eve::condition::Condition> children;
80 children.reserve(specification.arraySize());
81 for (std::size_t i = 0; i < specification.arraySize(); ++i) {
82 auto child = compileCondition(specification.at(i));
83 if (!child) return eve::Result<eve::condition::Condition>::failure(child.status());
84 children.push_back(std::move(child).takeValue());
85 }
87 }
88 if (!specification.isObject()) return conditionError("dialogue condition must be an object or array");
89
90 if (const eve::Value* all = specification.find("all")) {
91 if (!all->isArray()) return conditionError("condition 'all' must be an array", "all");
92 std::vector<eve::condition::Condition> children;
93 children.reserve(all->arraySize());
94 for (std::size_t i = 0; i < all->arraySize(); ++i) {
95 auto child = compileCondition(all->at(i));
96 if (!child) return eve::Result<eve::condition::Condition>::failure(child.status());
97 children.push_back(std::move(child).takeValue());
98 }
100 }
101 if (const eve::Value* any = specification.find("any")) {
102 if (!any->isArray()) return conditionError("condition 'any' must be an array", "any");
103 std::vector<eve::condition::Condition> children;
104 children.reserve(any->arraySize());
105 for (std::size_t i = 0; i < any->arraySize(); ++i) {
106 auto child = compileCondition(any->at(i));
107 if (!child) return eve::Result<eve::condition::Condition>::failure(child.status());
108 children.push_back(std::move(child).takeValue());
109 }
111 }
112 if (const eve::Value* negated = specification.find("not")) {
113 auto child = compileCondition(*negated);
114 if (!child) return eve::Result<eve::condition::Condition>::failure(child.status());
116 eve::condition::Condition::not_(std::move(child).takeValue()));
117 }
118
119 const eve::Value* tag = specification.find("tag");
120 if (!tag) tag = specification.find("hasTag");
121 if (tag) {
122 if (!tag->isString()) return conditionError("tag condition requires a string tag", "tag");
124 }
125
126 const eve::Value* authority = specification.find("authority");
127 if (authority) {
128 if (!authority->isString()) return conditionError("authority condition requires a string scope", "authority");
130 }
131
132 const eve::Value* policy = specification.find("policy");
133 if (!policy) policy = specification.find("script");
134 if (policy) {
135 if (!policy->isString()) return conditionError("policy condition requires a string name", "policy");
136 eve::Value arguments = eve::Value::Object{};
137 if (const eve::Value* supplied = specification.find("arguments")) arguments = *supplied;
139 eve::condition::Condition::policyCall(policy->asString(), std::move(arguments)));
140 }
141
142 const eve::Value* state = specification.find("state");
143 if (state && state->isString()) {
144 const eve::Value* expected = specification.find("equals");
145 if (!expected) expected = specification.find("value");
146 if (!expected)
149 eve::condition::stateEquals(state->asString(), *expected));
150 }
151
152 const eve::Value* attribute = specification.find("attribute");
153 const eve::Value* nameValue = specification.find("key");
154 if (!nameValue) nameValue = specification.find("var");
155 if (attribute && attribute->isString()) nameValue = attribute;
156
157 const eve::Value* operation = specification.find("op");
158 if (nameValue && operation) {
159 if (!nameValue->isString() || !operation->isString())
160 return conditionError("comparison condition requires string key and op");
161 const std::string key = nameValue->asString();
162 const std::string op = operation->asString();
164 if (op == "missing")
168 if (!readOperator(op, parsed)) return conditionError("unknown condition operator: " + op, "op");
169 const eve::Value* expected = specification.find("value");
170 if (!expected) return conditionError("comparison condition is missing value", "value");
172 attribute && attribute->isString() ? eve::condition::attrKey(key) : key, parsed, *expected));
173 }
174
175 if (attribute && attribute->isString())
177
178 if (state && state->isObject()) {
179 std::string key;
180 if (!readString(*state, "key", key)) return conditionError("state condition is missing key", "state.key");
181 const eve::Value* expected = state->find("equals");
182 if (!expected) expected = state->find("value");
183 if (!expected) return conditionError("state condition is missing value", "state.value");
185 }
186
187 if (const eve::Value* compare = specification.find("compare")) {
188 if (!compare->isObject()) return conditionError("compare condition must be an object", "compare");
189 return compileCondition(*compare);
190 }
191
192 return conditionError("unrecognized dialogue condition");
193}
194
195eve::Result<eve::MutationReceipt> mutationUnavailable() {
197 eve::DiagnosticCode::Unsupported, "dialogue world mutation requires an IStateMutation capability",
198 "dialogue.state.mutation"));
199}
200
201} // namespace
202
204 switch (value.kind()) {
212 result.reserve(value.arraySize());
213 for (std::size_t i = 0; i < value.arraySize(); ++i) result.push_back(toCanonicalValue(value.at(i)));
214 return eve::Value::array(std::move(result));
215 }
218 for (const auto& key : value.keys()) result.emplace(key, toCanonicalValue(*value.find(key)));
219 return eve::Value::object(std::move(result));
220 }
221 }
222 return eve::Value::null();
223}
224
226
229
230void StateEvaluationContext::setSubject(std::string subject) { subject_ = std::move(subject); }
231
232std::optional<eve::Value> StateEvaluationContext::value(std::string_view key) const {
234 auto result = queryProviders<bool>(
235 subject_, provider_,
236 [&](eve::IStateQuery* provider, const std::string& subject) { return provider->hasTag(subject, *tag); });
237 return result.has_value() ? std::optional<eve::Value>(eve::Value(*result)) : std::nullopt;
238 }
240 auto result = queryProviders<eve::Value>(subject_, provider_,
241 [&](eve::IStateQuery* provider, const std::string& subject) {
242 return provider->attribute(subject, *attr);
243 });
244 if (result.has_value()) return result;
245 return queryProviders<eve::Value>(
246 subject_, provider_,
247 [&](eve::IStateQuery* provider, const std::string& subject) { return provider->value(subject, *attr); });
248 }
250 return queryProviders<eve::Value>(subject_, provider_,
251 [&](eve::IStateQuery* provider, const std::string& subject) {
253 });
254 }
256 auto result = queryProviders<eve::Value>(
257 subject_, provider_,
258 [&](eve::IStateQuery* provider, const std::string& subject) { return provider->state(subject, *state); });
259 if (result.has_value()) return result;
260 return queryProviders<eve::Value>(
261 subject_, provider_,
262 [&](eve::IStateQuery* provider, const std::string& subject) { return provider->value(subject, *state); });
263 }
264 return queryProviders<eve::Value>(subject_, provider_, [&](eve::IStateQuery* provider, const std::string& subject) {
265 return provider->value(subject, key);
266 });
267}
268
269std::optional<eve::condition::ConditionResult> StateEvaluationContext::policy(std::string_view name,
270 const eve::Value& arguments) const {
271 if (auto authority = eve::condition::resolveAuthorityAllow(name, arguments, [this](std::string_view scope) {
272 return queryProviders<bool>(subject_, provider_,
273 [&](eve::IStateQuery* provider, const std::string& subject) {
275 });
276 })) {
277 return authority;
278 }
279 if (!policyEvaluator_) return std::nullopt;
280 return policyEvaluator_(name, arguments);
281}
282
284
285void DialogueStateContext::setSubject(std::string subject) { subject_ = std::move(subject); }
286
287StateEvaluationContext DialogueStateContext::evaluationContext() const {
288 StateEvaluationContext context(subject_, queryProvider_);
289 context.setPolicyEvaluator(policyEvaluator_);
290 return context;
291}
292
293std::optional<eve::Value> DialogueStateContext::value(std::string_view key) const {
294 auto context = evaluationContext();
295 return context.value(key);
296}
297
298std::optional<bool> DialogueStateContext::hasTag(std::string_view tag) const {
299 auto result = evaluationContext().value(eve::condition::tagKey(tag));
300 if (!result || !result->isBool()) return std::nullopt;
301 return result->asBool();
302}
303
304std::optional<eve::Value> DialogueStateContext::attribute(std::string_view key) const {
305 auto context = evaluationContext();
306 if (auto prefixed = context.value(eve::condition::attrKey(key))) return prefixed;
307 return context.value(key);
308}
309
310std::optional<eve::Value> DialogueStateContext::resource(std::string_view key) const {
311 return evaluationContext().value(eve::condition::resourceKey(key));
312}
313
314std::optional<eve::Value> DialogueStateContext::state(std::string_view key) const {
315 auto context = evaluationContext();
316 if (auto prefixed = context.value(eve::condition::stateKey(key))) return prefixed;
317 return context.value(key);
318}
319
321 return ::eve::dialogue::compileCondition(specification);
322}
323
325 auto context = evaluationContext();
326 return condition.evaluate(context);
327}
328
330 auto compiled = compileCondition(specification);
331 if (!compiled) {
332 const eve::Diagnostic* diagnostic = compiled.error();
333 const std::string message = diagnostic ? diagnostic->message() : "invalid dialogue condition";
335 eve::Value(),
337 }
338 eve::condition::Condition condition = std::move(compiled).takeValue();
339 return evaluate(condition);
340}
341
342eve::Result<eve::MutationReceipt> DialogueStateContext::apply(std::span<const eve::StateMutation> mutations,
343 const eve::MutationContext& context) const {
344 eve::IStateMutation* provider = mutationProvider_;
345 if (!provider) provider = eve::cap::query<eve::IStateMutation>();
346 if (!provider) return mutationUnavailable();
347 return provider->apply(mutations, context);
348}
349
350} // namespace eve::dialogue
ActionParameterOperation operation
int subject
Definition AnimSmr.cpp:163
void * service
Canonical Compare key prefixes and PolicyCall names for thin conditions.
Dialogue's state boundary, condition adapter, and command request protocol.
eve::Value condition
SQObjectPtr key
Definition ECS.cpp:155
std::string name
Definition ECS.cpp:154
std::string message
JobScope scope
Poco::JSON::Object::Ptr result
bool all
const std::string * tag
std::string path
Definition PlayHost.cpp:111
Object::Ptr value
std::string attribute
ScriptStructure out
std::string resource
int children
Definition TreeMesh.cpp:432
const VegetationPresetContext & context
A structured explanation of a failed, degraded, or noteworthy result.
Definition Diagnostic.h:94
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
const std::string & message() const noexcept
Human-readable explanation.
Definition Diagnostic.h:147
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
JSON-compatible state value tree used by state hot reload.
Definition StateValue.h:30
The canonical owning dynamic value used by data-facing protocols.
Definition Value.h:31
const std::string & asString() const
Return the string payload; the caller must have checked the kind.
Definition Value.cpp:207
static Value null()
Compatibility factory for a null value.
Definition Value.h:113
std::map< std::string, Value > Object
Definition Value.h:34
bool isArray() const noexcept
Return true when this value is an array.
Definition Value.h:108
static Value number(double value)
Compatibility factory for a Double value.
Definition Value.h:117
bool isString() const noexcept
Return true when this value is a string.
Definition Value.h:106
static Value string(std::string value)
Compatibility factory for a string value.
Definition Value.h:121
std::vector< Value > Array
Definition Value.h:33
static Value array(Array value)
Compatibility factory for an array value.
Definition Value.cpp:128
static Value integer(std::int64_t value)
Compatibility factory for an Int64 value.
Definition Value.h:115
std::size_t arraySize() const
Return the number of array elements.
Definition Value.cpp:220
static Value boolean(bool value)
Compatibility factory for a boolean value.
Definition Value.h:119
bool isObject() const noexcept
Return true when this value is an object.
Definition Value.h:110
Value & at(std::size_t index)
Return a bounds-checked array element.
Definition Value.cpp:226
static Value object(Object value)
Compatibility factory for an object value.
Definition Value.cpp:129
Value * find(const std::string &key) noexcept
Return an object member, or nullptr when absent.
Definition Value.cpp:244
Explain one condition evaluation in a UI- and log-friendly form.
Definition Condition.h:137
static ConditionResult failed(ConditionReasonCode reason, Value evidence={}, Value details=Value::Object{})
Construct a rejected result with a stable reason and explanation.
Immutable condition AST node.
Definition Condition.h:199
static Condition compare(std::string key, CompareOperator op, Value expected={})
Compare a context value against an expected scalar value.
static Condition any(std::vector< Condition > children)
Construct a disjunction of child conditions.
static Condition all(std::vector< Condition > children)
Construct a conjunction of child conditions.
static Condition not_(Condition child)
Construct a logical negation of one child condition.
static Condition policyCall(std::string name, Value arguments=Value::Object{}, std::optional< ScriptConditionDeclaration > scriptDeclaration=std::nullopt)
Call a named read-only policy and use its ConditionResult.
std::optional< eve::Value > value(std::string_view key) const
Query a canonical world value without creating a local copy in Dialogue.
eve::Result< eve::condition::Condition > compileCondition(const eve::Value &specification) const
Compile a canonical condition specification to condition::Condition.
DialogueStateContext(std::string subject={})
Construct a context for one stable world subject.
eve::Result< eve::MutationReceipt > apply(std::span< const eve::StateMutation > mutations, const eve::MutationContext &context) const
Apply a complete mutation set through one authoritative provider.
eve::condition::ConditionResult evaluate(const eve::condition::Condition &condition) const
Evaluate an already compiled shared condition with explanation.
std::optional< eve::Value > state(std::string_view key) const
Query one persistent state value.
std::optional< eve::Value > resource(std::string_view key) const
Query one resource value.
std::optional< bool > hasTag(std::string_view tag) const
Query exact world tag membership.
std::optional< eve::Value > attribute(std::string_view key) const
Query one attribute or reputation value.
void setSubject(std::string subject)
Set the subject used for all future condition queries.
const std::string & subject() const noexcept
Return the currently selected subject id.
Decision EvaluationContext backed by one dialogue subject.
std::optional< eve::Value > value(std::string_view key) const override
Query a named scalar or structured value for Compare nodes.
void setSubject(std::string subject)
Change the subject used by subsequent synchronous queries.
std::optional< eve::condition::ConditionResult > policy(std::string_view name, const eve::Value &arguments) const override
Evaluate a named read-only policy with owned arguments.
StateEvaluationContext(std::string subject={}, eve::IStateQuery *provider=nullptr)
Construct a context for a stable subject id and optional provider.
All-or-nothing mutation boundary owned by the consumer.
Read-only world-state boundary owned by consumers such as Dialogue.
Definition StateAccess.h:79
virtual std::optional< eve::Value > state(std::string_view subject, std::string_view key) const =0
Query a persistent/world state value.
virtual std::optional< bool > hasTag(std::string_view subject, std::string_view tag) const =0
Query exact tag membership.
virtual std::optional< eve::Value > resource(std::string_view subject, std::string_view key) const =0
Query a resource value or marker.
virtual std::optional< bool > authority(std::string_view subject, std::string_view scope) const =0
Query read-only authority for a scope.
virtual std::optional< eve::Value > value(std::string_view subject, std::string_view key) const =0
Query a generic world value.
virtual std::optional< eve::Value > attribute(std::string_view subject, std::string_view key) const =0
Query a numeric or structured attribute.
I * query()
Queries .
Definition Capability.h:88
Condition stateEquals(std::string name, Value expected)
Compare that a state key equals an expected value.
std::string resourceKey(std::string_view name)
Build a resource:<name> Compare key.
Condition attributeExists(std::string name)
Compare that an attribute key exists (attr:<name> Exists).
constexpr std::string_view kResourcePrefix
Prefix for resource values (resource:<name>).
constexpr std::string_view kStatePrefix
Prefix for state values (state:<name>).
constexpr std::string_view kTagPrefix
Prefix for tag membership booleans (tag:<name>).
std::optional< ConditionResult > resolveAuthorityAllow(std::string_view name, const Value &arguments, AuthorityQuery &&authorityQuery)
Resolve the built-in authority.allow policy when name matches.
Condition tagPresent(std::string tag)
Compare that a tag key is present (tag:<name> == true).
std::string stateKey(std::string_view name)
Build a state:<name> Compare key.
std::optional< std::string_view > stripPrefix(std::string_view key, std::string_view prefix)
Strip a known domain prefix from a key.
constexpr std::string_view kAttrPrefix
Prefix for attribute values (attr:<name>).
std::string attrKey(std::string_view name)
Build an attr:<name> Compare key.
CompareOperator
Scalar comparison used by a Compare node.
Definition Condition.h:35
Condition authorityAllow(std::string scope)
PolicyCall for read-only authority (authority.allow).
std::string tagKey(std::string_view tag)
Build a tag:<name> Compare key.
eve::Value toCanonicalValue(const eve::StateValue &value)
Convert the legacy reload value into the canonical common value.
eve::StateValue toDialogueStateValue(const eve::Value &value)
Convert a canonical value to the legacy reload representation.
bool readString(const eve::Value::Object &object, const char *name, std::string &output)
ShapeState * child(const JPH::Body &body, const JPH::SubShapeID &id)
Resolves a native child record for a synchronous callback or query. @ownership Borrowed from the worl...
StateValue toLegacyStateValue(const Value &value)
Project a canonical value into the legacy reload snapshot format.
Correlation metadata shared by a mutation transaction.
Definition StateAccess.h:57