载入中...
搜索中...
未找到
CrowdFlowCache.cpp
浏览该文件的文档.
1#include <array>
2#include <limits>
3#include <tuple>
4#include <type_traits>
6namespace eve::crowd {
7namespace {
8template <class T>
9Result<T> cacheFailure(DiagnosticCode code, const char* text) {
10 return Result<T>::failure(Diagnostic::error(code, text, "flowCache"));
11}
12} // namespace
13Result<std::vector<int>> canonicalFlowCoordinates(std::span<const FlowGoal> goals, const CrowdField& field) {
14 if (!field.valid() || goals.empty() || goals.size() > 1024)
15 return cacheFailure<std::vector<int>>(DiagnosticCode::InvalidArgument,
16 "Expected 1..1024 goals and a configured field");
17 for (auto goal : goals)
18 if (goal.x < 0 || goal.y < 0 || goal.x >= field.getWidth() || goal.y >= field.getHeight())
19 return cacheFailure<std::vector<int>>(DiagnosticCode::InvalidArgument, "Goal outside grid");
20 std::vector<FlowGoal> sorted(goals.begin(), goals.end());
21 std::sort(sorted.begin(), sorted.end());
22 sorted.erase(std::unique(sorted.begin(), sorted.end()), sorted.end());
23 std::vector<int> result;
24 result.reserve(sorted.size() * 2);
25 for (auto goal : sorted) {
26 result.push_back(goal.x);
27 result.push_back(goal.y);
28 }
29 return Result<std::vector<int>>::success(std::move(result));
30}
31bool isFlowPointReachable(const CrowdField& field, float x, float y) noexcept {
32 if (!field.valid() || !field.isBuilt() || !std::isfinite(x) || !std::isfinite(y)) return false;
33 const double cx = std::floor((double(x) - field.getOriginX()) / field.getCellSize());
34 const double cy = std::floor((double(y) - field.getOriginY()) / field.getCellSize());
35 return cx >= 0 && cy >= 0 && cx < field.getWidth() && cy < field.getHeight() &&
36 field.isReachable(static_cast<int>(cx), static_cast<int>(cy));
37}
39 return sizeof(CrowdField) + sizeof(FlowCacheEntry) +
40 sizeof(float) * (value.cost_.capacity() + value.navigationCost_.capacity() + value.integ_.capacity() +
41 value.flowX_.capacity() + value.flowY_.capacity()) +
42 sizeof(int) * value.goals_.capacity() + sizeof(std::pair<float, int>) * value.buildHeap_.capacity();
43}
45 const auto prefix = [](const auto& entry) {
46 const auto& s = entry.surface;
47 return std::tuple{entry.input, s.surface.value(), s.surfaceRevision, s.movement.value(),
48 s.movementRevision, s.costModelRevision, s.clearanceRadius, entry.algorithm};
49 };
50 if (prefix(a) != prefix(b)) return prefix(a) < prefix(b);
51 return a.field->goals_ < b.field->goals_;
52}
54 std::uint64_t addedBytes,
55 size_t addedCount) const {
56 if (addedBytes > budget)
57 return cacheFailure<std::vector<FlowCacheEntry>>(DiagnosticCode::PreconditionViolation,
58 "Field exceeds cache storage budget");
59 std::vector<bool> evicted(flowCache.size(), false);
60 size_t count = flowCache.size();
61 std::uint64_t bytes = 0;
62 for (const auto& entry : flowCache) bytes += entry.bytes;
63 while (bytes > budget - addedBytes || count + addedCount > 10000) {
64 size_t victim = flowCache.size();
65 for (size_t i = 0; i < flowCache.size(); ++i) {
66 if (evicted[i] || !flowCache[i].pins.expired()) continue;
67 if (victim == flowCache.size() || flowCache[i].access < flowCache[victim].access ||
68 (flowCache[i].access == flowCache[victim].access && isFlowKeyBefore(flowCache[i], flowCache[victim])))
69 victim = i;
70 }
71 if (victim == flowCache.size())
72 return cacheFailure<std::vector<FlowCacheEntry>>(DiagnosticCode::PreconditionViolation,
73 "Cache pressure: all remaining fields are pinned");
74 evicted[victim] = true;
75 bytes -= flowCache[victim].bytes;
76 --count;
77 }
78 std::vector<FlowCacheEntry> staged;
79 staged.reserve(count + addedCount);
80 for (size_t i = 0; i < flowCache.size(); ++i)
81 if (!evicted[i]) staged.push_back(flowCache[i]);
82 return Result<std::vector<FlowCacheEntry>>::success(std::move(staged));
83}
85 auto pin = entry.pins.lock();
86 if (!pin) pin = std::make_shared<const unsigned char>(0);
87 entry.pins = pin;
88 entry.access = tick;
90 result.field_ = entry.field;
91 result.pin_ = std::move(pin);
92 result.owner_ = owner;
93 result.input_ = entry.input;
94 result.generation_ = entry.generation;
95 result.algorithm_ = entry.algorithm;
96 return result;
97}
98Result<FlowLease> Crowd::acquireFlowField(std::span<const FlowGoal> goals) try {
99 auto coordinates = canonicalFlowCoordinates(goals, impl_->field);
100 if (!coordinates) return Result<FlowLease>::failure(coordinates.status());
101 const auto surface = getFieldStatus().surface;
102 for (auto& entry : impl_->flowCache)
103 if (entry.input == impl_->field.inputRevision() && entry.surface == surface &&
104 entry.algorithm == flowBuildAlgorithmVersion && entry.field->goals_ == coordinates.value())
105 return Result<FlowLease>::success(impl_->leaseFor(entry));
106 return cacheFailure<FlowLease>(DiagnosticCode::NotFound, "No ready field for complete navigation key");
107} catch (const std::exception& error) {
108 return cacheFailure<FlowLease>(DiagnosticCode::Failed, error.what());
109}
111 if (!plan.field_ || plan.owner_ != impl_->owner || plan.revision_ != impl_->field.inputRevision() ||
112 (plan.state_ != FlowBuildState::Ready && plan.state_ != FlowBuildState::Unreachable))
113 return cacheFailure<FlowLease>(DiagnosticCode::Conflict, "Incomplete, stale or foreign field publication");
114 const auto surface = getFieldStatus().surface;
115 for (auto& entry : impl_->flowCache) {
116 if (entry.input == plan.revision_ && entry.surface == surface && entry.algorithm == flowBuildAlgorithmVersion &&
117 entry.field->goals_ == plan.field_->goals_) {
118 auto lease = impl_->leaseFor(entry);
119 plan.field_.reset();
120 plan.state_ = FlowBuildState::Committed;
121 return Result<FlowLease>::success(std::move(lease));
122 }
123 }
124 if (impl_->nextFlowGeneration == std::numeric_limits<std::uint64_t>::max())
125 return cacheFailure<FlowLease>(DiagnosticCode::Conflict, "Flow generation exhausted");
126 const auto bytes = Impl::retainedFlowBytes(*plan.field_);
127 auto staged = impl_->stageFlowCache(impl_->flowCacheBudget, bytes, 1);
128 if (!staged) return Result<FlowLease>::failure(staged.status());
129 auto entries = std::move(staged).takeValue();
130 static_assert(std::is_nothrow_move_constructible_v<CrowdField>);
131 static_assert(std::is_nothrow_move_constructible_v<Impl::FlowCacheEntry>);
132 // All metadata allocation and eviction validation precede the no-throw storage move.
133 auto pin = std::make_shared<const unsigned char>(0);
134 auto data = std::make_shared<const CrowdField>(std::move(*plan.field_));
135 entries.push_back({std::move(data), pin, surface, plan.revision_, impl_->nextFlowGeneration, bytes, impl_->tick,
137 auto lease = impl_->leaseFor(entries.back());
138 impl_->flowCache.swap(entries);
139 ++impl_->nextFlowGeneration;
140 plan.field_.reset();
141 plan.state_ = FlowBuildState::Committed;
142 return Result<FlowLease>::success(std::move(lease));
143} catch (const std::exception& error) {
144 return cacheFailure<FlowLease>(DiagnosticCode::Failed, error.what());
145}
146Result<void> Crowd::configureFlowCache(std::uint64_t budgetBytes) try {
147 if (budgetBytes > 8ULL * 1024 * 1024 * 1024)
148 return cacheFailure<void>(DiagnosticCode::InvalidArgument, "Cache budget exceeds eight GiB");
149 auto staged = impl_->stageFlowCache(budgetBytes, 0, 0);
150 if (!staged) return Result<void>::failure(staged.status());
151 impl_->flowCache = std::move(staged).takeValue();
152 impl_->flowCacheBudget = budgetBytes;
153 return Result<void>::success();
154} catch (const std::exception& error) {
155 return cacheFailure<void>(DiagnosticCode::Failed, error.what());
156}
159 result.entries = impl_->flowCache.size();
160 result.budgetBytes = impl_->flowCacheBudget;
161 for (const auto& entry : impl_->flowCache) result.residentBytes += entry.bytes;
162 return result;
163}
165 if (!std::isfinite(x) || !std::isfinite(y))
166 return cacheFailure<FlowSample>(DiagnosticCode::InvalidArgument, "Nonfinite sample position");
167 if (!impl_->isFlowLeaseCurrent(lease))
168 return cacheFailure<FlowSample>(DiagnosticCode::Conflict, "Stale or foreign flow lease");
170 if (isFlowPointReachable(*lease.field_, x, y)) {
172 lease.field_->flowAtWorld(x, y, result.direction.x, result.direction.y);
173 }
175}
176} // namespace eve::crowd
double y
double x
const std::string & s
std::unordered_map< std::string, QuestRuntime > entries
float cx
Definition CardTypes.cpp:36
float cy
Definition CardTypes.cpp:37
DiagnosticCode code
Poco::JSON::Object::Ptr result
std::uint64_t bytes
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
std::shared_ptr< OceanGpuSpectrum > owner
std::string error
Definition Package.cpp:174
PrefabLease lease
Object::Ptr value
std::string text
int count
SimulationTick tick
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
连续流场(flow field)。
Definition CrowdField.h:25
Move-only navigation workstate; contains no borrowed provider pointers.
Definition Crowd.h:309
FieldObservation getFieldStatus() const noexcept
Observe current field readiness and owner-local revision without rebuilding.
Definition Crowd.cpp:62
Result< FlowLease > acquireFlowField(std::span< const FlowGoal > goals)
Acquire an existing field for a canonical goal set without graph work.
Result< void > configureFlowCache(std::uint64_t budgetBytes)
Set retained-storage budget, evicting only unleased fields with atomic pressure failure.
FlowCacheObservation getFlowCacheStatus() const noexcept
Read retained-storage accounting without copying fields; owner thread only.
Result< FlowSample > sampleFlowField(const FlowLease &lease, float x, float y) const
Sample a current lease; stale/foreign leases fail, unreachable locations return zero....
Owning immutable field lease; copies pin storage, never the Crowd provider. @thread Copy/release/quer...
Definition CrowdTypes.h:48
size_t size() const
Returns the size of .
Definition Json.cpp:352
constexpr std::uint32_t flowBuildAlgorithmVersion
Increment when the navigation construction algorithm changes its observable output.
Definition CrowdTypes.h:41
Result< std::vector< int > > canonicalFlowCoordinates(std::span< const FlowGoal > goals, const CrowdField &field)
Copy validated goals into their unique canonical coordinates.
bool isFlowPointReachable(const CrowdField &field, float x, float y) noexcept
Observe exact containing-cell reachability, independent of interpolation across blocked cells....
DiagnosticCode
Stable machine-readable diagnostic codes.
Definition Diagnostic.h:47
std::shared_ptr< const CrowdField > field
std::weak_ptr< const void > pins
FlowLease leaseFor(FlowCacheEntry &entry)
Result< std::vector< FlowCacheEntry > > stageFlowCache(std::uint64_t budget, std::uint64_t bytes, size_t count) const
Stage cache metadata and deterministic unleased evictions without live mutation. @ownership Returns o...
static bool isFlowKeyBefore(const FlowCacheEntry &a, const FlowCacheEntry &b)
static std::uint64_t retainedFlowBytes(const CrowdField &value)
NavigationSurfaceStamp surface
Definition Crowd.h:57
Retained navigation-storage accounting; excludes allocator bookkeeping and pending builds.
Definition CrowdTypes.h:62
Owning lease sample with explicit reachability.
Definition Crowd.h:50
FlowSampleState state
Definition Crowd.h:51