载入中...
搜索中...
未找到
SensingQueryCodec.cpp
浏览该文件的文档.
2#include <cmath>
3#include <stdexcept>
4#include "common/Json.h"
5
6namespace eve::sensing {
7namespace {
8struct DecodeError : std::runtime_error {
9 using std::runtime_error::runtime_error;
10};
11using Node = json::Value;
12void require(bool ok, const std::string& field) {
13 if (!ok) throw DecodeError(field);
14}
15std::string text(Node n, const char* key, std::string fallback = {}) {
16 if (!n.has(key)) return fallback;
17 require(n.get(key).isString(), key);
18 return n.getString(key);
19}
20double number(Node n, const char* key, double fallback = 0) {
21 if (!n.has(key)) return fallback;
22 require(n.get(key).isNumber() && std::isfinite(n.getDouble(key)), key);
23 return n.getDouble(key);
24}
25float scalar(Node n, const char* key) {
26 require(n.has(key), key);
27 const auto value = number(n, key);
28 require(std::abs(value) <= std::numeric_limits<float>::max(), key);
29 return static_cast<float>(value);
30}
31std::uint32_t count(Node n, const char* key, std::uint32_t fallback) {
32 if (!n.has(key)) return fallback;
33 require(n.get(key).isInt64() && n.get(key).asInt64() >= 0 &&
34 n.get(key).asInt64() <= std::numeric_limits<std::uint32_t>::max(),
35 key);
36 return static_cast<std::uint32_t>(n.get(key).asInt64());
37}
38bool flag(Node n, const char* key, bool fallback) {
39 if (!n.has(key)) return fallback;
40 require(n.get(key).isBool(), key);
41 return n.getBool(key);
42}
43template <class E>
44E choice(Node n, const char* key, E fallback, std::initializer_list<std::pair<std::string_view, E>> names) {
45 if (!n.has(key)) return fallback;
46 const auto name = text(n, key);
47 for (const auto& [label, value] : names)
48 if (label == name) return value;
49 throw DecodeError(key);
50}
51std::vector<std::string> strings(Node n, const char* key) {
52 if (!n.has(key)) return {};
53 auto a = n.get(key);
54 require(a.isArray(), key);
55 std::vector<std::string> result;
56 for (std::size_t i = 0; i < a.size(); ++i) {
57 require(a.at(i).isString(), key);
58 result.push_back(a.at(i).asString());
59 }
60 return result;
61}
62CoordinateSpace space(Node n) {
63 require(n.has("space"), "space");
64 return choice<CoordinateSpace>(n, "space", CoordinateSpace::World2D,
65 {{"world2d", CoordinateSpace::World2D},
66 {"world3d", CoordinateSpace::World3D},
67 {"grid2d", CoordinateSpace::Grid2D},
68 {"grid3d", CoordinateSpace::Grid3D}});
69}
70TargetLocation location(Node n) {
71 require(n.isObject(), "location");
72 const auto tag = space(n);
74 auto p = tag == CoordinateSpace::World2D ? WorldPoint::world2D(scalar(n, "x"), scalar(n, "y"))
75 : WorldPoint::world3D(scalar(n, "x"), scalar(n, "y"), scalar(n, "z"));
76 require(p.ok(), "location");
77 return p.value();
78 }
79 const auto integer = [&](const char* key) {
80 require(n.get(key).isInt64() && n.get(key).asInt64() >= std::numeric_limits<int>::min() &&
81 n.get(key).asInt64() <= std::numeric_limits<int>::max(),
82 key);
83 return static_cast<int>(n.get(key).asInt64());
84 };
86 return GridPoint::grid3D(integer("x"), integer("y"), integer("z"));
87}
88template <class T, class F>
89Result<T> decode(std::string_view bytes, std::string_view schema, F parse) {
90 std::string error;
91 auto document = json::Document::parse(std::string(bytes), &error);
92 if (!document.valid())
94 try {
95 auto root = document.root();
96 require(root.isObject() && text(root, "schema") == schema && root.get("version").isInt64() &&
97 root.get("version").asInt64() == 1,
98 "schema/version");
100 } catch (const DecodeError& error) {
101 return Result<T>::failure(Diagnostic::error(DiagnosticCode::InvalidArgument, "invalid sensing request field",
102 error.what(), {}, "sensing.codec"));
103 }
104}
105} // namespace
107 return decode<SensingQueryRequest>(bytes, "eve.sensing.query", [](Node n) {
109 auto p = location(n.get("origin"));
110 const auto* world = std::get_if<WorldPoint>(&p);
111 require(world != nullptr, "origin.space");
112 r.origin = {world->x(), world->y(), std::nullopt, world->z(), world->space()};
113 if (n.has("subjectId")) r.origin.subjectId = text(n, "subjectId");
114 r.spec.axes = choice<QueryAxes>(
115 n, "axes", world->space() == CoordinateSpace::World3D ? QueryAxes::XYZ : QueryAxes::XY,
116 {{"xy", QueryAxes::XY}, {"xz", QueryAxes::XZ}, {"yz", QueryAxes::YZ}, {"xyz", QueryAxes::XYZ}});
117 r.spec.minRange = static_cast<float>(number(n, "minRange", 0));
118 r.spec.maxRange = static_cast<float>(number(n, "maxRange", std::numeric_limits<float>::infinity()));
119 require(!n.has("maxRange") || std::isfinite(r.spec.maxRange), "maxRange");
120 r.spec.minCount = count(n, "minCount", 0);
121 r.spec.maxCount = count(n, "maxCount", std::numeric_limits<std::uint32_t>::max());
122 r.spec.requiredTags = strings(n, "requiredTags");
123 r.spec.excludedTags = strings(n, "excludedTags");
124 r.spec.includeFactions = strings(n, "includeFactions");
125 r.spec.excludeFactions = strings(n, "excludeFactions");
126 if (n.has("visibleTo")) r.spec.visibleTo = text(n, "visibleTo");
127 r.spec.requireLineOfSight = flag(n, "lineOfSight", false);
128 r.spec.countPolicy =
129 choice<CountPolicy>(n, "countPolicy", CountPolicy::TruncateToMax,
131 r.spec.sortKey = choice<SortKey>(
133 {{"distance", SortKey::DistanceAscending},
134 {"closest", SortKey::DistanceAscending},
135 {"furthest", SortKey::DistanceDescending},
138 {"strongest", SortKey::StrengthDescending},
139 {"weakest", SortKey::StrengthAscending},
140 {"none", SortKey::None}});
141 if (n.has("shape")) {
142 auto shape = n.get("shape");
143 require(shape.isObject(), "shape");
144 const auto kind = text(shape, "kind");
145 if (kind == "sphere")
146 r.spec.shape =
147 QuerySphere{scalar(shape, "x"), scalar(shape, "y"), scalar(shape, "z"), scalar(shape, "radius")};
148 else if (kind == "circle")
149 r.spec.shape = QueryCircle{scalar(shape, "x"), scalar(shape, "y"), scalar(shape, "radius")};
150 else if (kind == "box")
151 r.spec.shape = QueryBox{scalar(shape, "minX"), scalar(shape, "minY"), scalar(shape, "maxX"),
152 scalar(shape, "maxY")};
153 else if (kind == "cone")
154 r.spec.shape = QueryCone{scalar(shape, "x"), scalar(shape, "y"), scalar(shape, "dirX"),
155 scalar(shape, "dirY"), scalar(shape, "halfAngle"), scalar(shape, "range")};
156 else
157 throw DecodeError("shape.kind");
158 }
159 auto valid = r.spec.validate();
160 require(valid.ok(), "query");
161 return r;
162 });
163}
165 return decode<EnvironmentRequest>(bytes, "eve.sensing.environmentRequest", [](Node n) {
167 auto contexts = n.get("contexts");
168 require(contexts.isArray(), "contexts");
169 for (std::size_t i = 0; i < contexts.size(); ++i) {
170 auto context = contexts.at(i);
172 c.name = text(context, "name");
173 auto points = context.get("locations");
174 require(points.isArray(), "contexts.locations");
175 for (std::size_t j = 0; j < points.size(); ++j) c.locations.push_back(location(points.at(j)));
176 r.contexts.push_back(std::move(c));
177 }
178 if (n.has("input")) {
179 auto items = n.get("input");
180 require(items.isArray(), "input");
181 for (std::size_t i = 0; i < items.size(); ++i) {
182 auto item = items.at(i);
183 require(item.get("id").isInt64() && item.get("id").asInt64() >= 0, "input.id");
184 EnvironmentItem value{static_cast<std::uint64_t>(item.get("id").asInt64()),
185 location(item.get("location")), std::nullopt};
186 if (item.has("subjectKey")) value.subjectKey = text(item, "subjectKey");
187 r.input.push_back(std::move(value));
188 }
189 }
190 return r;
191 });
192}
194 return decode<EnvironmentQueryDefinition>(bytes, "eve.sensing.environmentDefinition", [](Node n) {
196 d.id = text(n, "id");
197 d.space = space(n);
198 d.contexts = strings(n, "contexts");
199 d.revision = count(n, "revision", 1);
200 d.maxResults = count(n, "maxResults", 8);
201 d.optimize = flag(n, "optimize", true);
202 d.maxTraceItems = count(n, "maxTraceItems", 256);
203 d.mode = choice<EnvironmentRunMode>(n, "mode", EnvironmentRunMode::All,
205 d.trace = choice<EnvironmentTraceLevel>(n, "trace", EnvironmentTraceLevel::Summary,
208 {"detailed", EnvironmentTraceLevel::Detailed}});
209 auto options = n.get("options");
210 require(options.isArray(), "options");
211 for (std::size_t i = 0; i < options.size(); ++i) {
212 auto o = options.at(i);
213 require(o.isObject(), "options");
214 EnvironmentOption option;
215 option.id = text(o, "id");
216 if (o.has("generator")) {
217 auto g = o.get("generator");
218 require(g.isObject(), "generator");
219 option.generator.kind = choice<EnvironmentGeneratorKind>(g, "kind", EnvironmentGeneratorKind::Input,
223 option.generator.context = text(g, "context");
224 option.generator.radius = number(g, "radius", 10);
225 option.generator.spacing = number(g, "spacing", 2);
226 option.generator.samples = count(g, "samples", 16);
227 option.generator.maxItems = count(g, "maxItems", 4096);
228 }
229 auto tests = o.get("tests");
230 require(tests.isArray(), "tests");
231 for (std::size_t j = 0; j < tests.size(); ++j) {
232 auto t = tests.at(j);
233 require(t.isObject(), "tests");
234 EnvironmentTest test;
235 test.id = text(t, "id");
236 test.context = text(t, "context");
237 test.metric = choice<EnvironmentMetricKind>(
240 test.purpose = choice<EnvironmentPurpose>(t, "purpose", EnvironmentPurpose::FilterAndScore,
241 {{"filter", EnvironmentPurpose::Filter},
242 {"score", EnvironmentPurpose::Score},
243 {"filterAndScore", EnvironmentPurpose::FilterAndScore}});
244 test.filterOp =
245 choice<EnvironmentFilterOp>(t, "filterOp", EnvironmentFilterOp::All,
247 test.aggregate = choice<EnvironmentAggregate>(t, "aggregate", EnvironmentAggregate::Average,
248 {{"average", EnvironmentAggregate::Average},
250 {"maximum", EnvironmentAggregate::Maximum}});
251 test.normalization =
252 choice<EnvironmentNormalization>(t, "normalization", EnvironmentNormalization::FixedRange,
255 test.curve = choice<EnvironmentCurve>(t, "curve", EnvironmentCurve::Linear,
256 {{"linear", EnvironmentCurve::Linear},
257 {"square", EnvironmentCurve::Square},
259 test.preference = choice<EnvironmentPreference>(t, "preference", EnvironmentPreference::Lower,
262 {"reference", EnvironmentPreference::Reference}});
263 test.minimum = number(t, "minimum", 0);
264 test.maximum = number(t, "maximum", std::numeric_limits<double>::max());
265 test.scoreMinimum = number(t, "scoreMinimum", 0);
266 test.scoreMaximum = number(t, "scoreMaximum", 100);
267 test.referenceValue = number(t, "referenceValue", 0);
268 test.weight = number(t, "weight", 1);
269 option.tests.push_back(std::move(test));
270 }
271 d.options.push_back(std::move(option));
272 }
273 return d;
274 });
275}
276} // namespace eve::sensing
int root
Definition AnimSmr.cpp:119
glm::vec4 p[6]
SQObjectPtr key
Definition ECS.cpp:155
std::string name
Definition ECS.cpp:154
std::vector< CompiledTest > tests
tensor::Graph g
Definition GpuGraph.cpp:7
ShaderImageInput shape
glm::vec3 n
Definition Grass.cpp:63
double r
std::int32_t c
std::string label
Poco::JSON::Object::Ptr result
std::uint64_t bytes
bool valid
MeleePoint3 a
Definition MeleeHit.cpp:40
const std::string * tag
std::string error
Definition Package.cpp:174
std::shared_ptr< const std::vector< glm::vec2 > > points
Object::Ptr value
float d
float t
double number
std::string text
std::string kind
const SquirrelValueOptions & options
int count
const VegetationPresetContext & context
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
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 Document parse(const std::string &text, std::string *error=nullptr)
Parse.
Definition Json.cpp:623
static GridPoint grid3D(std::int32_t x, std::int32_t y, std::int32_t z) noexcept
Creates a 3D integer grid point.
static GridPoint grid2D(std::int32_t x, std::int32_t y) noexcept
Creates a 2D integer grid point.
static Result< WorldPoint > world2D(float x, float y)
Creates a finite 2D world point.
char * decode(std::string format, const char *src, size_t srclen, size_t &dstlen)
Decodes a text buffer (hex / base64) back into raw bytes.
std::variant< WorldPoint, GridPoint > TargetLocation
Either a world point or a grid point, with the tag retained.
Definition Targeting.h:190
CoordinateSpace
Coordinate spaces are not interchangeable, even when dimensions match.
Result< SensingQueryRequest > decodeSensingQuery(std::string_view bytes)
Decodes eve.sensing.query v1; rejects malformed known fields, ignores unknown fields....
Result< EnvironmentQueryDefinition > decodeEnvironmentDefinition(std::string_view bytes)
Decodes eve.sensing.environmentDefinition v1 into an owning definition. @cost Linear in input bytes p...
Result< EnvironmentRequest > decodeEnvironmentRequest(std::string_view bytes)
Decodes eve.sensing.environmentRequest v1; locations retain explicit coordinate tags....
@ TruncateToMax
Keep the best maxCount candidates after sorting (legacy circle/box limit).
@ FailIfOutOfRange
Fail the query when the filtered set is outside [minCount, maxCount].
int64_t integer(const RuntimeTensor &v, size_t i=0)
Integer.
ModelData parse(std::span< const uint8_t > bytes)
Parse.
Owning context snapshot, resolved once at instance creation.
A query-local identity and typed location; subjectKey names a mirrored fact, not a UUID.
std::optional< std::string > subjectKey
Ordered alternative: advance only when this option has no valid items.
std::vector< EnvironmentTest > tests
Authoring value; compile validates and owns a copy. Not a persistent wire format.
Per-execution values. No world pointers or callbacks are retained.
One metric with independent filtering and scoring parameters.
EnvironmentPreference preference
EnvironmentNormalization normalization
Inclusive axis-aligned box shape for QuerySpec (World2D).
Definition Sensing.h:86
Circle shape for QuerySpec (World2D).
Definition Sensing.h:79
2D cone/sector shape for QuerySpec (World2D).
Definition Sensing.h:99
Sphere in actual XYZ world coordinates.
Definition Sensing.h:109
Owning request decoded at a script or tooling boundary.