载入中...
搜索中...
未找到
ClimbingAnchorGraph.cpp
浏览该文件的文档.
2#include "common/Assert.h"
3#include "common/ValueRead.h"
4
5#include "physics/Body3D.h"
6#include "physics/World3D.h"
7
8#include <algorithm>
9#include <cmath>
10#include <deque>
11#include <limits>
12#include <unordered_set>
13#include <utility>
14
15namespace eve::climbing {
16namespace {
17
18constexpr std::size_t maxGraphNodes = 4096;
19constexpr std::size_t maxGraphEdges = 16384;
20constexpr std::uint32_t maxOccupancySlots = 8;
21constexpr float frameTolerance = 0.02f;
22
23bool finite(float value) { return std::isfinite(value); }
24bool finite(Vec3 value) { return finite(value.x) && finite(value.y) && finite(value.z); }
25float lengthSquared(Vec3 value) { return value.x * value.x + value.y * value.y + value.z * value.z; }
26float dot(Vec3 lhs, Vec3 rhs) { return lhs.x * rhs.x + lhs.y * rhs.y + lhs.z * rhs.z; }
27
28const eve::Value* field(const eve::Value::Object& object, std::string_view name) {
29 const auto found = object.find(std::string(name));
30 return found == object.end() ? nullptr : &found->second;
31}
32
33bool readString(const eve::Value::Object& object, std::string_view name, std::string& output) {
34 auto text = eve::readStringMember(object, name);
35 if (!text) return false;
36 output = std::move(text.value());
37 return true;
38}
39
40bool readInt64(const eve::Value::Object& object, std::string_view name, std::int64_t& output) {
41 const auto* value = field(object, name);
42 if (!value) return false;
43 auto parsed = eve::readInt64Value(*value);
44 if (!parsed) return false;
45 output = parsed.value();
46 return true;
47}
48
49bool readBool(const eve::Value::Object& object, std::string_view name, bool& output) {
50 const auto* value = field(object, name);
51 if (!value) return false;
52 auto parsed = eve::readBoolValue(*value);
53 if (!parsed) return false;
54 output = parsed.value();
55 return true;
56}
57
58bool numericFloat(const eve::Value& value, float& output) {
59 auto parsed = eve::readFiniteFloatValue(value);
60 if (!parsed) return false;
61 output = parsed.value();
62 return true;
63}
64
65bool readVec(const eve::Value::Object& object, std::string_view name, Vec3& output) {
66 const eve::Value* value = field(object, name);
67 const auto* array = value ? value->getIf<eve::Value::Array>() : nullptr;
68 return array && array->size() == 3 && numericFloat((*array)[0], output.x) &&
69 numericFloat((*array)[1], output.y) && numericFloat((*array)[2], output.z);
70}
71
72eve::Value vecValue(Vec3 value) {
74}
75
76std::string_view nodeKindName(ClimbingAnchorKind kind) {
77 switch (kind) {
78 case ClimbingAnchorKind::Ledge: return "ledge";
79 case ClimbingAnchorKind::CornerInner: return "corner_inner";
80 case ClimbingAnchorKind::CornerOuter: return "corner_outer";
81 case ClimbingAnchorKind::LadderRung: return "ladder_rung";
82 case ClimbingAnchorKind::Pole: return "pole";
83 case ClimbingAnchorKind::Beam: return "beam";
84 case ClimbingAnchorKind::Bar: return "bar";
85 }
86 return "unknown";
87}
88
89bool readNodeKind(std::string_view value, ClimbingAnchorKind& output) {
90 if (value == "ledge")
92 else if (value == "corner_inner")
94 else if (value == "corner_outer")
96 else if (value == "ladder_rung")
98 else if (value == "pole")
100 else if (value == "beam")
102 else if (value == "bar")
104 else
105 return false;
106 return true;
107}
108
109std::string_view edgeKindName(ClimbingAnchorEdgeKind kind) {
110 switch (kind) {
111 case ClimbingAnchorEdgeKind::Shimmy: return "shimmy";
112 case ClimbingAnchorEdgeKind::Corner: return "corner";
113 case ClimbingAnchorEdgeKind::Jump: return "jump";
114 case ClimbingAnchorEdgeKind::Drop: return "drop";
115 case ClimbingAnchorEdgeKind::Mount: return "mount";
116 case ClimbingAnchorEdgeKind::Dismount: return "dismount";
117 case ClimbingAnchorEdgeKind::Climb: return "climb";
118 case ClimbingAnchorEdgeKind::Balance: return "balance";
119 case ClimbingAnchorEdgeKind::Swing: return "swing";
120 }
121 return "unknown";
122}
123
124bool readEdgeKind(std::string_view value, ClimbingAnchorEdgeKind& output) {
125 if (value == "shimmy")
127 else if (value == "corner")
129 else if (value == "jump")
131 else if (value == "drop")
133 else if (value == "mount")
135 else if (value == "dismount")
137 else if (value == "climb")
139 else if (value == "balance")
141 else if (value == "swing")
143 else
144 return false;
145 return true;
146}
147
148eve::Value::Array stringArray(const std::vector<std::string>& strings) {
150 values.reserve(strings.size());
151 for (const auto& value : strings) values.emplace_back(value);
152 return values;
153}
154
155bool readStringArray(const eve::Value::Object& object, std::string_view name, std::vector<std::string>& output) {
156 const eve::Value* value = field(object, name);
157 const auto* array = value ? value->getIf<eve::Value::Array>() : nullptr;
158 if (!array) return false;
159 output.reserve(array->size());
160 for (const auto& item : *array) {
161 const auto* text = item.getIf<std::string>();
162 if (!text) return false;
163 output.push_back(*text);
164 }
165 return true;
166}
167
168eve::Value::Object unknownFields(const eve::Value::Object& object,
169 std::initializer_list<std::string_view> knownNames) {
170 std::unordered_set<std::string_view> known(knownNames.begin(), knownNames.end());
172 for (const auto& [name, value] : object)
173 if (!known.contains(name)) result.emplace(name, value);
174 return result;
175}
176
177bool validUniqueStrings(std::vector<std::string> values) {
178 std::sort(values.begin(), values.end());
179 return !std::any_of(values.begin(), values.end(), [](const auto& value) { return value.empty(); }) &&
180 std::adjacent_find(values.begin(), values.end()) == values.end();
181}
182
183void canonicalize(ClimbingAnchorGraphDefinition& graph) {
184 for (auto& node : graph.nodes) std::sort(node.tags.begin(), node.tags.end());
185 for (auto& edge : graph.edges) std::sort(edge.requiredTags.begin(), edge.requiredTags.end());
186 std::sort(graph.nodes.begin(), graph.nodes.end(), [](const auto& lhs, const auto& rhs) { return lhs.id < rhs.id; });
187 std::sort(graph.edges.begin(), graph.edges.end(), [](const auto& lhs, const auto& rhs) {
188 if (lhs.from != rhs.from) return lhs.from < rhs.from;
189 if (lhs.to != rhs.to) return lhs.to < rhs.to;
190 if (lhs.kind != rhs.kind) return lhs.kind < rhs.kind;
191 return lhs.bidirectional < rhs.bidirectional;
192 });
193}
194
195bool sameEdgeIdentity(const ClimbingAnchorEdgeDefinition& lhs, const ClimbingAnchorEdgeDefinition& rhs) {
196 return lhs.from == rhs.from && lhs.to == rhs.to && lhs.kind == rhs.kind;
197}
198
199Vec3 vectorFrom(physics::PhysicsVector3D value) { return {value.x, value.y, value.z}; }
200
201} // namespace
202
204 if (graph.id.empty() || graph.sourceGeometryContentId.empty() || graph.buildSettingsHash.empty())
207 "graph id, source geometry content id, and build settings hash are required",
208 "graph.identity", {}, "climbing.anchor_graph"));
209 if (graph.nodes.empty() || graph.nodes.size() > maxGraphNodes || graph.edges.size() > maxGraphEdges)
211 eve::DiagnosticCode::InvalidArgument, "anchor graph node and edge counts exceed supported bounds",
212 "graph.topology", {}, "climbing.anchor_graph"));
213 std::unordered_set<std::string> nodeIds;
214 for (std::size_t index = 0; index < graph.nodes.size(); ++index) {
215 const auto& node = graph.nodes[index];
216 const std::string path = "nodes." + std::to_string(index);
217 if (node.id.empty() || !nodeIds.emplace(node.id).second)
219 "anchor node ids must be non-empty and unique",
220 path + ".id", {}, "climbing.anchor_graph"));
221 if (!finite(node.localPosition) || !finite(node.localNormal) || !finite(node.localTangent) ||
222 !finite(node.leftHandSocket) || !finite(node.rightHandSocket) || !finite(node.feetSocket))
224 "anchor frame and sockets must be finite", path,
225 {}, "climbing.anchor_graph"));
226 const float normalLength = lengthSquared(node.localNormal);
227 const float tangentLength = lengthSquared(node.localTangent);
228 if (std::fabs(normalLength - 1.f) > frameTolerance || std::fabs(tangentLength - 1.f) > frameTolerance ||
229 std::fabs(dot(node.localNormal, node.localTangent)) > frameTolerance)
231 eve::DiagnosticCode::InvalidArgument, "anchor normal and tangent must form an orthonormal local frame",
232 path + ".frame", {}, "climbing.anchor_graph"));
233 if (node.occupancySlots == 0 || node.occupancySlots > maxOccupancySlots)
235 eve::DiagnosticCode::InvalidArgument, "anchor occupancy slots must be between one and eight",
236 path + ".occupancySlots", {}, "climbing.anchor_graph"));
237 if (!validUniqueStrings(node.tags))
239 "anchor tags must be non-empty and unique",
240 path + ".tags", {}, "climbing.anchor_graph"));
241 }
242 std::vector<ClimbingAnchorEdgeDefinition> edges = graph.edges;
243 std::sort(edges.begin(), edges.end(), [](const auto& lhs, const auto& rhs) {
244 if (lhs.from != rhs.from) return lhs.from < rhs.from;
245 if (lhs.to != rhs.to) return lhs.to < rhs.to;
246 return lhs.kind < rhs.kind;
247 });
248 for (std::size_t index = 0; index < edges.size(); ++index) {
249 const auto& edge = edges[index];
250 const std::string path = "edges." + std::to_string(index);
251 if (edge.from.empty() || edge.to.empty() || edge.from == edge.to || !nodeIds.contains(edge.from) ||
252 !nodeIds.contains(edge.to))
254 eve::DiagnosticCode::InvalidArgument, "anchor edge endpoints must name two distinct existing nodes",
255 path, {}, "climbing.anchor_graph"));
256 if (index != 0 && sameEdgeIdentity(edges[index - 1], edge))
258 "anchor edge identity must be unique", path, {},
259 "climbing.anchor_graph"));
260 if (!validUniqueStrings(edge.requiredTags))
262 eve::DiagnosticCode::InvalidArgument, "edge required tags must be non-empty and unique",
263 path + ".requiredTags", {}, "climbing.anchor_graph"));
264 }
266}
267
270 if (!valid) return eve::Result<eve::Value>::failure(valid.status());
272 canonicalize(canonical);
274 nodes.reserve(canonical.nodes.size());
275 for (const auto& node : canonical.nodes) {
276 eve::Value::Object object = node.extensionMetadata;
277 object["id"] = eve::Value(node.id);
278 object["kind"] = eve::Value(std::string(nodeKindName(node.kind)));
279 object["localPosition"] = vecValue(node.localPosition);
280 object["localNormal"] = vecValue(node.localNormal);
281 object["localTangent"] = vecValue(node.localTangent);
282 object["leftHandSocket"] = vecValue(node.leftHandSocket);
283 object["rightHandSocket"] = vecValue(node.rightHandSocket);
284 object["feetSocket"] = vecValue(node.feetSocket);
285 object["occupancySlots"] = eve::Value(static_cast<std::int64_t>(node.occupancySlots));
286 object["tags"] = eve::Value(stringArray(node.tags));
287 nodes.emplace_back(std::move(object));
288 }
290 edges.reserve(canonical.edges.size());
291 for (const auto& edge : canonical.edges) {
292 eve::Value::Object object = edge.extensionMetadata;
293 object["from"] = eve::Value(edge.from);
294 object["to"] = eve::Value(edge.to);
295 object["kind"] = eve::Value(std::string(edgeKindName(edge.kind)));
296 object["bidirectional"] = eve::Value(edge.bidirectional);
297 object["requiredTags"] = eve::Value(stringArray(edge.requiredTags));
298 edges.emplace_back(std::move(object));
299 }
301 root["schemaId"] = eve::Value(std::string(ClimbingAnchorGraphDefinition::SchemaId));
303 root["id"] = eve::Value(canonical.id);
304 root["sourceGeometryContentId"] = eve::Value(canonical.sourceGeometryContentId);
305 root["buildSettingsHash"] = eve::Value(canonical.buildSettingsHash);
306 root["nodes"] = eve::Value(std::move(nodes));
307 root["edges"] = eve::Value(std::move(edges));
309}
310
312 const auto* root = value.getIf<eve::Value::Object>();
313 if (!root)
315 eve::Diagnostic::error(eve::DiagnosticCode::ParseError, "anchor graph definition must be an object", {}, {},
316 "climbing.anchor_graph"));
318 std::string schemaId;
319 std::int64_t version = -1;
320 const eve::Value* nodesValue = field(*root, "nodes");
321 const auto* nodes = nodesValue ? nodesValue->getIf<eve::Value::Array>() : nullptr;
322 const eve::Value* edgesValue = field(*root, "edges");
323 const auto* edges = edgesValue ? edgesValue->getIf<eve::Value::Array>() : nullptr;
324 if (!readString(*root, "schemaId", schemaId) || schemaId != ClimbingAnchorGraphDefinition::SchemaId ||
325 !readInt64(*root, "schemaVersion", version) ||
327 version != ClimbingAnchorGraphDefinition::SchemaVersion - 1) || !readString(*root, "id", graph.id) ||
328 !readString(*root, "sourceGeometryContentId", graph.sourceGeometryContentId) ||
329 !readString(*root, "buildSettingsHash", graph.buildSettingsHash) || !nodes || !edges) {
332 eve::DiagnosticCode::UnknownVersion, "anchor graph schema version is unsupported", "schemaVersion", {},
333 "climbing.anchor_graph"));
335 eve::DiagnosticCode::ParseError, "anchor graph envelope has missing or invalid known fields", {}, {},
336 "climbing.anchor_graph"));
337 }
338 graph.nodes.reserve(nodes->size());
339 for (std::size_t index = 0; index < nodes->size(); ++index) {
340 const auto* object = (*nodes)[index].getIf<eve::Value::Object>();
342 std::string kind;
343 std::int64_t occupancySlots = 0;
344 if (!object || !readString(*object, "id", node.id) || !readString(*object, "kind", kind) ||
345 !readNodeKind(kind, node.kind) || !readVec(*object, "localPosition", node.localPosition) ||
346 !readVec(*object, "localNormal", node.localNormal) ||
347 !readVec(*object, "localTangent", node.localTangent) ||
348 !readVec(*object, "leftHandSocket", node.leftHandSocket) ||
349 !readVec(*object, "rightHandSocket", node.rightHandSocket) ||
350 !readVec(*object, "feetSocket", node.feetSocket) ||
351 !readInt64(*object, "occupancySlots", occupancySlots) || occupancySlots < 0 ||
352 occupancySlots > std::numeric_limits<std::uint32_t>::max() ||
353 !readStringArray(*object, "tags", node.tags))
355 eve::DiagnosticCode::ParseError, "anchor node has missing or invalid known fields",
356 "nodes." + std::to_string(index), {}, "climbing.anchor_graph"));
357 node.occupancySlots = static_cast<std::uint32_t>(occupancySlots);
358 node.extensionMetadata = unknownFields(*object, {"id", "kind", "localPosition", "localNormal",
359 "localTangent", "leftHandSocket", "rightHandSocket",
360 "feetSocket", "occupancySlots", "tags"});
361 graph.nodes.push_back(std::move(node));
362 }
363 graph.edges.reserve(edges->size());
364 for (std::size_t index = 0; index < edges->size(); ++index) {
365 const auto* object = (*edges)[index].getIf<eve::Value::Object>();
367 std::string kind;
368 if (!object || !readString(*object, "from", edge.from) || !readString(*object, "to", edge.to) ||
369 !readString(*object, "kind", kind) || !readEdgeKind(kind, edge.kind) ||
370 !readBool(*object, "bidirectional", edge.bidirectional) ||
371 !readStringArray(*object, "requiredTags", edge.requiredTags))
373 eve::DiagnosticCode::ParseError, "anchor edge has missing or invalid known fields",
374 "edges." + std::to_string(index), {}, "climbing.anchor_graph"));
375 edge.extensionMetadata = unknownFields(*object, {"from", "to", "kind", "bidirectional", "requiredTags"});
376 graph.edges.push_back(std::move(edge));
377 }
378 graph.extensionMetadata = unknownFields(*root, {"schemaId", "schemaVersion", "id",
379 "sourceGeometryContentId", "buildSettingsHash", "nodes", "edges"});
382 canonicalize(graph);
384}
385
387 physics::World3D& world,
391 if (!body.isValid() || !world.findBody(body))
393 eve::Diagnostic::error(eve::DiagnosticCode::StaleHandle, "anchor graph target body handle is stale", "body",
394 {}, "climbing.anchor_graph"));
395 canonicalize(graph);
397 instance.graph_ = std::move(graph);
398 instance.world_ = world.runtimeHandle();
399 instance.body_ = body;
400 return eve::Result<ClimbingAnchorGraphInstance>::success(std::move(instance));
401}
402
403const ClimbingAnchorNodeDefinition* ClimbingAnchorGraphInstance::findNode(std::string_view nodeId) const noexcept {
404 const auto found = std::lower_bound(graph_.nodes.begin(), graph_.nodes.end(), nodeId,
405 [](const auto& node, std::string_view id) { return node.id < id; });
406 return found != graph_.nodes.end() && found->id == nodeId ? &*found : nullptr;
407}
408
410 if (!findNode(nodeId))
412 eve::DiagnosticCode::NotFound, "anchor node was not found", "nodeId", {}, "climbing.anchor_graph"));
413 return eve::Result<ClimbingAnchorNodeRef>::success({graph_.id, std::string(nodeId), generation_});
414}
415
417 physics::World3D& world, const ClimbingAnchorNodeRef& reference) const {
419 if (!resolved) return resolved;
420 const auto* node = findNode(reference.nodeId);
421 EV_ASSERT(node != nullptr, "kinematics resolution validated the anchor node");
422 resolved.value().tags = node->tags;
423 return resolved;
424}
425
427 physics::World3D& world, const ClimbingAnchorNodeRef& reference) const {
428 if (reference.graphId != graph_.id)
430 eve::Diagnostic::error(eve::DiagnosticCode::Conflict, "anchor node reference belongs to another graph",
431 "reference.graphId", {}, "climbing.anchor_graph"));
432 if (reference.graphGeneration != generation_)
434 eve::DiagnosticCode::StaleHandle, "anchor node reference belongs to a stale graph generation",
435 "reference.graphGeneration", {}, "climbing.anchor_graph"));
436 const auto* node = findNode(reference.nodeId);
437 if (!node)
439 eve::Diagnostic::error(eve::DiagnosticCode::NotFound, "anchor node was not found", "reference.nodeId", {},
440 "climbing.anchor_graph"));
441 if (world.runtimeHandle() != world_)
443 eve::DiagnosticCode::StaleHandle, "anchor graph belongs to another or stale Physics world", "world", {},
444 "climbing.anchor_graph"));
445 physics::Body3D* body = world.findBody(body_);
446 if (!body)
448 eve::Diagnostic::error(eve::DiagnosticCode::StaleHandle, "anchor graph target body handle is stale", "body",
449 {}, "climbing.anchor_graph"));
452 result.kind = node->kind;
453 result.body = body_;
454 auto position = body->localToWorldPointOwned(node->localPosition.x, node->localPosition.y,
455 node->localPosition.z);
457 auto normal = body->localToWorldVectorOwned(node->localNormal.x, node->localNormal.y,
458 node->localNormal.z);
460 auto tangent = body->localToWorldVectorOwned(node->localTangent.x, node->localTangent.y,
461 node->localTangent.z);
462 if (!tangent) return eve::Result<ResolvedClimbingAnchorNode>::failure(tangent.status());
463 auto leftHand = body->localToWorldPointOwned(node->leftHandSocket.x, node->leftHandSocket.y,
464 node->leftHandSocket.z);
465 if (!leftHand) return eve::Result<ResolvedClimbingAnchorNode>::failure(leftHand.status());
466 auto rightHand = body->localToWorldPointOwned(node->rightHandSocket.x, node->rightHandSocket.y,
467 node->rightHandSocket.z);
468 if (!rightHand) return eve::Result<ResolvedClimbingAnchorNode>::failure(rightHand.status());
469 auto feet = body->localToWorldPointOwned(node->feetSocket.x, node->feetSocket.y, node->feetSocket.z);
470 if (!feet) return eve::Result<ResolvedClimbingAnchorNode>::failure(feet.status());
471 auto velocity = body->getLocalPointVelocityOwned(node->localPosition.x, node->localPosition.y,
472 node->localPosition.z);
474 result.position = vectorFrom(position.value());
475 result.normal = vectorFrom(normal.value());
476 result.tangent = vectorFrom(tangent.value());
477 result.leftHandSocket = vectorFrom(leftHand.value());
478 result.rightHandSocket = vectorFrom(rightHand.value());
479 result.feetSocket = vectorFrom(feet.value());
480 result.pointVelocity = vectorFrom(velocity.value());
482}
483
485 const ClimbingAnchorNodeRef& reference) const {
486 if (reference.graphId != graph_.id)
488 eve::Diagnostic::error(eve::DiagnosticCode::Conflict, "anchor node reference belongs to another graph",
489 "reference.graphId", {}, "climbing.anchor_graph"));
490 if (reference.graphGeneration != generation_)
492 eve::DiagnosticCode::StaleHandle, "anchor node reference belongs to a stale graph generation",
493 "reference.graphGeneration", {}, "climbing.anchor_graph"));
494 if (!findNode(reference.nodeId))
496 eve::Diagnostic::error(eve::DiagnosticCode::NotFound, "anchor node was not found", "reference.nodeId", {},
497 "climbing.anchor_graph"));
498 std::vector<ClimbingAnchorEdgeDefinition> result;
499 for (const auto& edge : graph_.edges) {
500 if (edge.from == reference.nodeId)
501 result.push_back(edge);
502 else if (edge.bidirectional && edge.to == reference.nodeId) {
504 std::swap(reverse.from, reverse.to);
505 result.push_back(std::move(reverse));
506 }
507 }
508 std::sort(result.begin(), result.end(), [](const auto& lhs, const auto& rhs) {
509 if (lhs.kind != rhs.kind) return lhs.kind < rhs.kind;
510 return lhs.to < rhs.to;
511 });
513}
514
516 const ClimbingAnchorRouteRequest& request) const {
517 if (request.start.graphId != graph_.id || request.goal.graphId != graph_.id)
519 eve::Diagnostic::error(eve::DiagnosticCode::Conflict, "route endpoints belong to another anchor graph",
520 "request", {}, "climbing.anchor_graph"));
521 if (request.start.graphGeneration != generation_ || request.goal.graphGeneration != generation_)
523 eve::DiagnosticCode::StaleHandle, "route endpoints belong to a stale graph generation", "request", {},
524 "climbing.anchor_graph"));
525 if (!findNode(request.start.nodeId) || !findNode(request.goal.nodeId))
527 eve::DiagnosticCode::NotFound, "route endpoint was not found", "request", {}, "climbing.anchor_graph"));
528 if (request.maxVisitedNodes == 0 || request.maxVisitedNodes > 65536)
530 eve::DiagnosticCode::InvalidArgument, "route maxVisitedNodes must be between one and 65536",
531 "request.maxVisitedNodes", {}, "climbing.anchor_graph"));
532 const bool requesterHasAgent = !request.requester.agentId.isZero();
533 const bool requesterHasExecution = !request.requester.executionId.isZero();
534 if (requesterHasAgent != requesterHasExecution)
536 eve::DiagnosticCode::InvalidArgument, "route requester must provide both agent and execution ids",
537 "request.requester", {}, "climbing.anchor_graph"));
538
539 std::vector<ClimbingAnchorEdgeKind> allowed = request.allowedEdgeKinds;
540 std::sort(allowed.begin(), allowed.end());
541 allowed.erase(std::unique(allowed.begin(), allowed.end()), allowed.end());
542 if (!validUniqueStrings(request.availableTags))
544 eve::DiagnosticCode::InvalidArgument, "route capability tags must be non-empty and unique",
545 "request.availableTags", {}, "climbing.anchor_graph"));
546 std::vector<std::string> availableTags = request.availableTags;
547 std::sort(availableTags.begin(), availableTags.end());
548 const auto permits = [&allowed](ClimbingAnchorEdgeKind kind) {
549 return allowed.empty() || std::binary_search(allowed.begin(), allowed.end(), kind);
550 };
551 const auto isFull = [this, &request](std::string_view nodeId) {
552 if (request.occupancyPolicy == ClimbingRouteOccupancyPolicy::Ignore) return false;
553 const auto* node = findNode(nodeId);
554 if (!node) return true;
555 std::uint32_t occupied = 0;
556 for (const auto& [id, record] : reservations_) {
557 (void)id;
558 if (record.nodeId != nodeId) continue;
559 if (record.occupant == request.requester) return false;
560 ++occupied;
561 }
562 return occupied >= node->occupancySlots;
563 };
564
565 struct Previous {
566 std::string from;
567 ClimbingAnchorEdgeKind kind = ClimbingAnchorEdgeKind::Shimmy;
568 };
569 std::deque<std::string> queue;
570 std::unordered_map<std::string, Previous> previous;
571 previous.emplace(request.start.nodeId, Previous{});
572 queue.push_back(request.start.nodeId);
573 bool found = request.start.nodeId == request.goal.nodeId;
574 while (!queue.empty() && !found) {
575 if (previous.size() > request.maxVisitedNodes)
577 eve::DiagnosticCode::PreconditionViolation, "route planning exceeded maxVisitedNodes",
578 "request.maxVisitedNodes", {}, "climbing.anchor_graph"));
579 const std::string current = std::move(queue.front());
580 queue.pop_front();
581 auto reference = nodeRef(current);
583 auto outgoing = edgesFrom(reference.value());
584 if (!outgoing) return eve::Result<ClimbingAnchorRoute>::failure(outgoing.status());
585 for (const auto& edge : outgoing.value()) {
586 const bool hasRequiredTags = std::all_of(
587 edge.requiredTags.begin(), edge.requiredTags.end(), [&availableTags](const std::string& tag) {
588 return std::binary_search(availableTags.begin(), availableTags.end(), tag);
589 });
590 if (!permits(edge.kind) || !hasRequiredTags || previous.contains(edge.to) || isFull(edge.to))
591 continue;
592 if (previous.size() >= request.maxVisitedNodes)
594 eve::DiagnosticCode::PreconditionViolation, "route planning exceeded maxVisitedNodes",
595 "request.maxVisitedNodes", {}, "climbing.anchor_graph"));
596 previous.emplace(edge.to, Previous{current, edge.kind});
597 if (edge.to == request.goal.nodeId) {
598 found = true;
599 break;
600 }
601 queue.push_back(edge.to);
602 }
603 }
604 if (!found)
606 eve::Diagnostic::error(eve::DiagnosticCode::NotFound, "no permitted anchor route reaches the goal",
607 "request.goal", {}, "climbing.anchor_graph"));
608
609 std::vector<std::string> reversedNodes;
610 std::vector<ClimbingAnchorEdgeKind> reversedKinds;
611 for (std::string cursor = request.goal.nodeId;;) {
612 reversedNodes.push_back(cursor);
613 if (cursor == request.start.nodeId) break;
614 const auto foundPrevious = previous.find(cursor);
615 if (foundPrevious == previous.end())
617 eve::Diagnostic::error(eve::DiagnosticCode::InvariantViolation, "route predecessor chain is incomplete",
618 "route", {}, "climbing.anchor_graph"));
619 reversedKinds.push_back(foundPrevious->second.kind);
620 cursor = foundPrevious->second.from;
621 }
622 std::reverse(reversedNodes.begin(), reversedNodes.end());
623 std::reverse(reversedKinds.begin(), reversedKinds.end());
624
625 ClimbingAnchorRoute route;
626 route.graphId = graph_.id;
627 route.graphGeneration = generation_;
628 route.nodes.reserve(reversedNodes.size());
629 for (const auto& nodeId : reversedNodes) route.nodes.push_back({graph_.id, nodeId, generation_});
630 route.steps.reserve(reversedKinds.size());
631 for (std::size_t index = 0; index < reversedKinds.size(); ++index)
632 route.steps.push_back({route.nodes[index], route.nodes[index + 1], reversedKinds[index]});
633 return eve::Result<ClimbingAnchorRoute>::success(std::move(route));
634}
635
636eve::Result<ClimbingAnchorReservation> ClimbingAnchorGraphInstance::reserve(
638 if (reference.graphId != graph_.id)
640 eve::Diagnostic::error(eve::DiagnosticCode::Conflict, "anchor node reference belongs to another graph",
641 "reference.graphId", {}, "climbing.anchor_graph"));
642 if (reference.graphGeneration != generation_)
644 eve::DiagnosticCode::StaleHandle, "anchor node reference belongs to a stale graph generation",
645 "reference.graphGeneration", {}, "climbing.anchor_graph"));
646 const auto* node = findNode(reference.nodeId);
647 if (!node)
649 eve::Diagnostic::error(eve::DiagnosticCode::NotFound, "anchor node was not found", "reference.nodeId", {},
650 "climbing.anchor_graph"));
651 if (occupant.agentId.isZero() || occupant.executionId.isZero())
653 eve::DiagnosticCode::InvalidArgument, "anchor reservation requires non-zero agent and execution ids",
654 "occupant", {}, "climbing.anchor_graph"));
655 std::vector<bool> occupied(node->occupancySlots, false);
656 for (const auto& [id, record] : reservations_) {
657 (void)id;
658 if (record.nodeId != node->id) continue;
659 if (record.occupant == occupant)
661 eve::Diagnostic::error(eve::DiagnosticCode::Conflict, "occupant already owns a slot on this anchor",
662 "occupant", {}, "climbing.anchor_graph"));
663 if (record.slot < occupied.size()) occupied[record.slot] = true;
664 }
665 const auto free = std::find(occupied.begin(), occupied.end(), false);
666 if (free == occupied.end())
668 eve::Diagnostic::error(eve::DiagnosticCode::Conflict, "all anchor occupancy slots are reserved",
669 "reference.nodeId", {}, "climbing.anchor_graph"));
670 const auto next = nextReservationId_.incremented();
671 if (!next)
673 eve::DiagnosticCode::PreconditionViolation, "anchor reservation identity is exhausted", "reservationId", {},
674 "climbing.anchor_graph"));
675 const ClimbingAnchorReservationId id = nextReservationId_;
676 const std::uint32_t slot = static_cast<std::uint32_t>(std::distance(occupied.begin(), free));
677 reservations_.emplace(id, ReservationRecord{node->id, slot, occupant, 1});
678 nextReservationId_ = *next;
680 {id, generation_, 1, node->id, slot, occupant}, eve::Status::success(eve::StatusCode::Applied));
681}
682
683eve::Result<void> ClimbingAnchorGraphInstance::release(const ClimbingAnchorReservation& reservation) {
684 auto valid = validateReservation(reservation);
685 if (!valid) return valid;
686 reservations_.erase(reservation.id);
688}
689
690eve::Result<void> ClimbingAnchorGraphInstance::validateReservation(
691 const ClimbingAnchorReservation& reservation) const {
692 if (reservation.graphGeneration != generation_)
694 eve::DiagnosticCode::StaleHandle, "anchor reservation belongs to a stale graph generation",
695 "reservation.graphGeneration", {}, "climbing.anchor_graph"));
696 const auto found = reservations_.find(reservation.id);
697 if (found == reservations_.end())
699 "anchor reservation is not live", "reservation.id", {},
700 "climbing.anchor_graph"));
701 const auto& record = found->second;
702 if (record.nodeId != reservation.nodeId || record.slot != reservation.slot ||
703 record.occupant != reservation.occupant || record.claimGeneration != reservation.claimGeneration)
705 eve::DiagnosticCode::Conflict, "anchor reservation credential does not match the live record",
706 "reservation", {}, "climbing.anchor_graph"));
708}
709
710eve::Result<ClimbingAnchorReservation> ClimbingAnchorGraphInstance::transferReservation(
711 const ClimbingAnchorReservation& reservation) {
712 auto valid = validateReservation(reservation);
714 auto found = reservations_.find(reservation.id);
715 if (found->second.claimGeneration == std::numeric_limits<std::uint64_t>::max())
717 eve::DiagnosticCode::PreconditionViolation, "anchor reservation claim generation is exhausted",
718 "reservation.claimGeneration", {}, "climbing.anchor_graph"));
719 ++found->second.claimGeneration;
720 ClimbingAnchorReservation transferred = reservation;
721 transferred.claimGeneration = found->second.claimGeneration;
723 std::move(transferred), eve::Status::success(eve::StatusCode::Applied));
724}
725
726eve::Result<ClimbingAnchorReservation> ClimbingAnchorGraphInstance::restoreReservation(
727 const ClimbingAnchorReservation& reservation) {
728 if (reservation.graphGeneration != generation_)
730 eve::DiagnosticCode::StaleHandle, "snapshot reservation belongs to a stale graph generation",
731 "reservation.graphGeneration", {}, "climbing.anchor_graph"));
732 const auto* node = findNode(reservation.nodeId);
733 if (!node)
735 eve::Diagnostic::error(eve::DiagnosticCode::NotFound, "snapshot reservation node was not found",
736 "reservation.nodeId", {}, "climbing.anchor_graph"));
737 if (reservation.id.isZero() || reservation.claimGeneration == 0 || reservation.occupant.agentId.isZero() ||
738 reservation.occupant.executionId.isZero() || reservation.slot >= node->occupancySlots)
740 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "snapshot reservation credential is invalid",
741 "reservation", {}, "climbing.anchor_graph"));
742 if (const auto live = reservations_.find(reservation.id); live != reservations_.end()) {
743 auto valid = validateReservation(reservation);
745 return transferReservation(reservation);
746 }
747 for (const auto& [id, record] : reservations_) {
748 (void)id;
749 if (record.nodeId == reservation.nodeId &&
750 (record.slot == reservation.slot || record.occupant == reservation.occupant))
752 eve::DiagnosticCode::Conflict, "snapshot anchor slot or occupant is already reserved",
753 "reservation.slot", {}, "climbing.anchor_graph"));
754 }
755 const auto next = nextReservationId_.incremented();
756 if (!next)
758 eve::DiagnosticCode::PreconditionViolation, "anchor reservation identity is exhausted", "reservationId", {},
759 "climbing.anchor_graph"));
760 const ClimbingAnchorReservationId id = nextReservationId_;
761 reservations_.emplace(id, ReservationRecord{reservation.nodeId, reservation.slot,
762 reservation.occupant, 1});
763 nextReservationId_ = *next;
764 ClimbingAnchorReservation restored{id, generation_, 1, reservation.nodeId, reservation.slot,
765 reservation.occupant};
767 std::move(restored), eve::Status::success(eve::StatusCode::Applied));
768}
769
770eve::Result<std::uint32_t> ClimbingAnchorGraphInstance::releaseOccupant(ClimbingAnchorOccupant occupant) {
771 if (occupant.agentId.isZero() || occupant.executionId.isZero())
773 eve::DiagnosticCode::InvalidArgument, "release requires non-zero agent and execution ids", "occupant", {},
774 "climbing.anchor_graph"));
775 std::uint32_t count = 0;
776 for (auto iterator = reservations_.begin(); iterator != reservations_.end();) {
777 if (iterator->second.occupant == occupant) {
778 iterator = reservations_.erase(iterator);
779 ++count;
780 } else {
781 ++iterator;
782 }
783 }
786}
787
791 if (generation_ == std::numeric_limits<std::uint64_t>::max())
793 eve::Diagnostic::error(eve::DiagnosticCode::PreconditionViolation, "anchor graph generation is exhausted",
794 "generation", {}, "climbing.anchor_graph"));
795 canonicalize(graph);
797 result.oldGeneration = generation_;
798 result.newGeneration = generation_ + 1;
799 result.invalidatedOccupants.reserve(reservations_.size());
800 for (const auto& [id, record] : reservations_) {
801 (void)id;
802 result.invalidatedOccupants.push_back(record.occupant);
803 }
804 std::sort(result.invalidatedOccupants.begin(), result.invalidatedOccupants.end());
805 result.invalidatedOccupants.erase(
806 std::unique(result.invalidatedOccupants.begin(), result.invalidatedOccupants.end()),
807 result.invalidatedOccupants.end());
808 graph_ = std::move(graph);
809 generation_ = result.newGeneration;
810 reservations_.clear();
813}
814
815} // namespace eve::climbing
int root
Definition AnimSmr.cpp:119
EVEngine assertion entry point, backed by zeroerr.
#define EV_ASSERT(cond,...)
Assert an internal engine invariant (state that must always hold).
Definition Assert.h:37
std::string output
AuthorityStoreHandleRef reference
Definition Authority.cpp:24
std::size_t cursor
Versioned body-local climbing topology, dynamic resolution, and deterministic occupancy.
std::vector< std::unique_ptr< ScriptClimbingEventSink > > live
std::string nodeId
ScriptComponentRecord record
Definition ECS.cpp:228
std::string name
Definition ECS.cpp:154
DiagnosticCode code
const GltfImportRequest & request
std::array< float, 3 > position
std::vector< Edge > edges
std::map< std::string, Node > nodes
std::string from
std::string id
Poco::JSON::Object::Ptr result
bool valid
std::unordered_set< std::string > tags
Texture * normal
const std::string * tag
glm::dvec3 velocity
std::shared_ptr< const OceanSprayFrame > previous
bool finite
std::map< std::string, std::vector< std::string > > graph
Definition Package.cpp:173
std::string path
Definition PlayHost.cpp:111
std::set< std::string > values
std::string body
Object::Ptr value
std::string slot
RoadNetwork resolved
const RoadNode * node
bool found
std::string text
size_t begin
size_t end
std::string kind
double current
bool occupied
Definition Shadow.cpp:155
int count
Json object
uint32_t index
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
constexpr bool isValid() const noexcept
Returns whether both coordinates are usable handle values.
static Status success(StatusCode code=StatusCode::Ok)
Construct a successful status with an explicit non-error outcome.
Definition Status.cpp:19
The canonical owning dynamic value used by data-facing protocols.
Definition Value.h:31
std::map< std::string, Value > Object
Definition Value.h:34
std::vector< Value > Array
Definition Value.h:33
static Value array(Array value)
Compatibility factory for an array value.
Definition Value.cpp:128
const T * getIf() const noexcept
Return a typed pointer, or nullptr when the kind differs.
Definition Value.h:209
Runtime instance binding one immutable graph generation to one Physics body.
eve::Result< std::vector< ClimbingAnchorEdgeDefinition > > edgesFrom(const ClimbingAnchorNodeRef &reference) const
Returns deterministic outgoing edges for a current-generation node reference.
eve::Result< ClimbingAnchorNodeRef > nodeRef(std::string_view nodeId) const
Returns a current-generation reference for a stable node id.
physics::PhysicsBodyHandle body() const noexcept
Target Physics body handle; stale detection occurs during resolve.
static eve::Result< ClimbingAnchorGraphInstance > bind(ClimbingAnchorGraphDefinition graph, physics::World3D &world, physics::PhysicsBodyHandle body)
Validates and binds a graph snapshot to an existing Physics body.
eve::Result< ResolvedClimbingAnchorNode > resolveNodeKinematics(physics::World3D &world, const ClimbingAnchorNodeRef &reference) const
Resolves per-tick anchor transforms without copying cold tag metadata.
eve::Result< ResolvedClimbingAnchorNode > resolveNode(physics::World3D &world, const ClimbingAnchorNodeRef &reference) const
Resolves a current node from body-local to world space after validating world/body generation.
eve::Result< ClimbingAnchorRoute > planRoute(const ClimbingAnchorRouteRequest &request) const
Finds the shortest occupancy-aware route using stable edge-kind/node-id tie breaking.
constexpr bool isZero() const noexcept
Returns whether this value is zero.
Backend-neutral 3D rigid body in meter-space coordinates (+Y up by convention). Owned by a World3D; c...
Definition Body3D.h:31
Box3D rigid-body world. Script coordinates are meters (Box3D native), unlike 2D World which uses pixe...
Definition World3D.h:47
const char * nodeKindName(NodeKind kind) noexcept
Stable wire name for a node kind. @ownership Non-owning pointer to a static string literal; do not fr...
const Value * field(const Value &value, const char *key)
Borrow an optional object field.
Value stringArray(const std::vector< std::string > &values)
float lengthSquared(Vec3 value)
Length squared.
ClimbingAnchorEdgeKind
Allowed authored transition between two explicit anchors.
eve::Result< ClimbingAnchorGraphDefinition > decodeClimbingAnchorGraphDefinition(const eve::Value &value)
Decodes and validates a complete owning graph candidate transactionally.
ClimbingAnchorKind
Authored semantic of one explicit climbing anchor.
eve::Result< void > validateClimbingAnchorGraphDefinition(const ClimbingAnchorGraphDefinition &graph)
Validates all graph identities, frames, slots, tags, and edge endpoints.
eve::Result< eve::Value > encodeClimbingAnchorGraphDefinition(const ClimbingAnchorGraphDefinition &graph)
Encodes a validated graph to its canonical owning Value representation.
bool readString(const eve::Value::Object &object, const char *name, std::string &output)
double dot(ForceVector a, ForceVector b)
Definition ForceMath.h:14
Result< std::int64_t > readInt64(const Value::Object &object, std::string_view name)
Reads a required signed decimal integer string.
Result< bool > readBool(const Value::Object &object, std::string_view name)
Reads a required boolean.
StatusCode
Stable outcome category for an operation.
Definition Status.h:28
Result< float > readFiniteFloatValue(const Value &value)
Convert an Integer or Double to a finite Float after validating its source range.
Definition Value.cpp:81
Result< bool > readBoolValue(const Value &value)
Read a Bool without coercing integers, strings or other kinds.
Definition Value.cpp:50
Result< std::string > readStringMember(const Value::Object &object, std::string_view name)
Read a required string field, including an empty string, as an owning value.
Definition Value.cpp:25
Result< std::int64_t > readInt64Value(const Value &value)
Read an Int64 without narrowing or numeric coercion.
Definition Value.cpp:57
Directed authored transition in a climbing anchor graph.
Versioned graph asset; topology is authoritative while collision remains owned by Physics.
eve::Value::Object extensionMetadata
Unknown schema fields retained across decode and encode.
std::vector< ClimbingAnchorNodeDefinition > nodes
std::vector< ClimbingAnchorEdgeDefinition > edges
static constexpr std::string_view SchemaId
Canonical schema id.
static constexpr std::int64_t SchemaVersion
Current schema version.
Atomic graph-reload outcome and owners whose old-generation reservations were invalidated.
One body-local anchor node with deterministic occupancy slots.
Generation-qualified reference to an authored anchor node.
Compound occupancy owner; execution ids are only unique inside one agent/runtime.
Owning reservation credential; release validates every field.
Read-only route request over one current anchor-graph generation.
World-space projection of a body-local anchor at one synchronous resolve point.