载入中...
搜索中...
未找到
CrowdAvoidance.cpp
浏览该文件的文档.
1// eve-hot-path
2#include "common/Profile.h"
4
5#include <array>
6#include <exception>
7#include <limits>
8
9namespace eve::crowd {
10namespace {
11constexpr int32_t seekAction = 2;
12constexpr float predictionAngles[] = {0.f, -0.2617994f, 0.2617994f, -0.5235988f, 0.5235988f,
13 -0.7853982f, 0.7853982f, -1.0471976f, 1.0471976f, -1.5707963f,
14 1.5707963f, -2.3561945f, 2.3561945f, 3.1415927f};
15constexpr float predictionFractions[] = {1.f, 0.5f, 0.25f};
16constexpr std::int64_t scoresPerNeighbor = 3 + std::size(predictionAngles) * std::size(predictionFractions);
17} // namespace
18
19
21 if (!std::isfinite(settings.horizon) || settings.horizon <= 0.f || settings.horizon > 10.f ||
22 !std::isfinite(settings.margin) || settings.margin < 0.f || settings.maxNeighbors < 1 ||
23 settings.maxNeighbors > 128)
25 Diagnostic::error(DiagnosticCode::InvalidArgument, "Invalid predictive avoidance settings", "avoidance"));
26 impl_->avoidance = settings;
28}
29
30AvoidanceSettings Crowd::getAvoidanceSettings() const { return impl_->avoidance; }
31
33 EV_PROFILE_MODULE("crowd", "Crowd::prepareAvoidanceNeighbors");
34 // Arrival/settled tests depend only on a neighbour's own state, not the querying agent.
35 std::vector<std::uint8_t> settled(actions.size(), 0);
36 for (size_t j = 0; j < actions.size(); ++j) {
37 if (interactions[j].holdPosition || interactions[j].pushability <= 0.f) continue;
38 settled[j] = actions[j] == 0 || (actions[j] == seekAction && hasTargets[j] &&
39 std::hypot(targetXs[j] - xs[j], targetYs[j] - ys[j]) <= arriveRadius &&
40 std::hypot(vxs[j], vys[j]) <= maxSpeeds[j] * 0.05f);
41 }
42 predictionNeighbors.resize(actions.size());
43 const auto prepareRange = [&](size_t first, size_t last, StepReport* partitionReport, std::int64_t& checks,
44 int& truncations) {
45 for (size_t i = first; i < last; ++i) {
46 using Neighbor = AvoidanceNeighbor;
47 auto& neighbors = predictionNeighbors[i];
48 neighbors.clear();
49 if (maxSpeeds[i] <= 0.f || interactions[i].holdPosition) continue;
50 neighbors.reserve(size_t(avoidance.maxNeighbors) + 1);
51 const double query = double(radii[i]) + avoidanceMaxRadius + avoidance.margin +
52 double(avoidance.horizon) * (double(maxSpeeds[i]) + avoidanceMaxSpeed);
53 const bool arriving = resolveOverlaps && actions[i] == seekAction && hasTargets[i];
54 int encountered = 0;
55 const auto nearer = [&](const Neighbor& a, const Neighbor& b) {
56 if (a.distance2 != b.distance2) return a.distance2 < b.distance2;
57 return tieKeys[a.slot] < tieKeys[b.slot];
58 };
59 const double queryRadius = float(std::min(query, double(std::numeric_limits<float>::max())));
61 xs[i], ys[i], float(queryRadius),
62 [&](int slot) {
63 const size_t j = size_t(slot);
64 if (i == j || !canAvoid(i, j)) return;
65 // Settled, pushable neighbours yield through the contact solver during final arrival.
66 // Held bodies and pairs without physical contact still require predictive avoidance.
67 if (arriving && (settled[j] || maxSpeeds[j] <= maxSpeeds[i] * 0.05f) &&
68 !interactions[j].holdPosition && interactions[j].pushability > 0.f && canContact(i, j))
69 return;
70 ++encountered;
71 const double dx = double(xs[j]) - xs[i], dy = double(ys[j]) - ys[i];
72 Neighbor neighbor{j, dx * dx + dy * dy};
73 if (neighbors.size() == size_t(avoidance.maxNeighbors) && !nearer(neighbor, neighbors.back()))
74 return;
75 const auto position = std::lower_bound(neighbors.begin(), neighbors.end(), neighbor, nearer);
76 if (position != neighbors.end() || neighbors.size() < size_t(avoidance.maxNeighbors)) {
77 neighbors.insert(position, neighbor);
78 if (neighbors.size() > size_t(avoidance.maxNeighbors)) neighbors.pop_back();
79 }
80 },
81 partitionReport);
82 if (encountered > avoidance.maxNeighbors) ++truncations;
83 checks += static_cast<std::int64_t>(neighbors.size()) * scoresPerNeighbor;
84 }
85 };
86 std::int64_t checks = 0;
88 prepareRange(0, actions.size(), nullptr, checks, avoidanceTruncations);
89 } else {
90 constexpr size_t grain = 256;
91 struct Partition {
92 StepReport report;
93 std::int64_t checks = 0;
94 int truncations = 0;
95 std::exception_ptr error;
96 };
97 std::vector<Partition> partitions((actions.size() + grain - 1) / grain);
98 dispatchWork(actions.size(), [&](size_t first, size_t last) {
99 auto& partition = partitions[first / grain];
100 try {
101 prepareRange(first, last, &partition.report, partition.checks, partition.truncations);
102 } catch (...) {
103 partition.error = std::current_exception();
104 }
105 });
106 for (const auto& partition : partitions) {
107 if (partition.error) std::rethrow_exception(partition.error);
108 if (budgetActive &&
109 partition.report.spatialVisits > activeBudget.maxSpatialVisits - workReport.spatialVisits)
110 throw WorkLimit{"Crowd spatial lookup budget exhausted"};
111 workReport.spatialVisits += partition.report.spatialVisits;
112 workReport.cellsVisited += partition.report.cellsVisited;
113 if (budgetActive &&
114 partition.report.candidatesVisited > activeBudget.maxNeighborVisits - workReport.candidatesVisited)
115 throw WorkLimit{"Crowd neighbor visit budget exhausted"};
116 workReport.candidatesVisited += partition.report.candidatesVisited;
117 avoidanceTruncations += partition.truncations;
118 checks += partition.checks;
119 }
120 }
121 if (budgetActive && checks > activeBudget.maxPredictionChecks - avoidanceChecks)
122 throw WorkLimit{"Crowd prediction check budget exhausted"};
123 avoidanceChecks += checks;
124}
125
126void Crowd::Impl::selectAvoidanceVelocity(size_t i, float dt, float& vx, float& vy) {
127 const auto& neighbors = predictionNeighbors[i];
128 if (neighbors.empty()) return;
129
130
131 const float speed = maxSpeeds[i];
132 const float preferredX = preferredVxs[i], preferredY = preferredVys[i];
133 const float preferredLength = std::hypot(preferredX, preferredY);
134 const float acceleration = maxAccels[i] * dt;
135 const auto reachable = [&](float& x, float& y) {
136 const float changeX = x - vxs[i], changeY = y - vys[i];
137 const float change = std::hypot(changeX, changeY);
138 if (change > acceleration && change > 0.f) {
139 x = vxs[i] + changeX * acceleration / change;
140 y = vys[i] + changeY * acceleration / change;
141 }
142 const float length = std::hypot(x, y);
143 if (length > speed) {
144 x *= speed / length;
145 y *= speed / length;
146 }
147 };
148 const auto score = [&](float x, float y, double cutoff) {
149 double cost =
150 std::hypot(x - preferredX, y - preferredY) / speed + 0.15 * std::hypot(x - vxs[i], y - vys[i]) / speed;
151 // A small, persistent right-hand preference breaks mirror symmetry.
152 if (preferredLength > 1e-5f)
153 cost += 0.05 * std::max(0.f, preferredX * y - preferredY * x) / (preferredLength * speed);
154 // Remaining terms can only add cost. A candidate already above the winner cannot improve it.
155 if (cost >= cutoff) return cost;
156 for (const auto& neighbor : neighbors) {
157 const size_t j = neighbor.slot;
158 const double px = double(xs[j]) - xs[i], py = double(ys[j]) - ys[i];
159 const double dx = double(x) - vxs[j], dy = double(y) - vys[j];
160 const double radius = double(radii[i]) + radii[j] + avoidance.margin;
161 const double c = neighbor.distance2 - radius * radius;
162 const double a = dx * dx + dy * dy, b = px * dx + py * dy;
163 double collision = double(avoidance.horizon) + 1.0;
164 if (c < 0.0) {
165 // Prefer opening an existing contact, rather than freezing all candidates.
166 collision = 0.0;
167 cost += 2.0 * std::max(0.0, b) / (std::max(radius, 1e-6) * speed);
168 } else if (a > 1e-10 && b > 0.0) {
169 const double discriminant = b * b - a * c;
170 if (discriminant >= 0.0) collision = (b - std::sqrt(discriminant)) / a;
171 }
172 if (collision >= 0.0 && collision < avoidance.horizon) {
173 const double urgency = 1.0 - collision / avoidance.horizon;
174 // Priority adjusts yielding preference; it never removes collision cost.
175 const double priority =
176 std::clamp(double(avoidancePriorities[j]) - avoidancePriorities[i], -100.0, 100.0);
177 cost += (20.0 + 0.1 * priority) * urgency * urgency;
178 }
179 if (cost >= cutoff) return cost;
180 }
181 if (field.valid()) {
182 float px = xs[i] + x * dt, py = ys[i] + y * dt;
183 float projectedX = px, projectedY = py;
184 field.resolvePenetration(projectedX, projectedY, radii[i]);
185 if (std::hypot(projectedX - px, projectedY - py) > 1e-4f) cost += 100.0;
186 if (clampToField && (px - radii[i] < field.getOriginX() || py - radii[i] < field.getOriginY() ||
187 px + radii[i] > field.getOriginX() + float(field.getWidth()) * field.getCellSize() ||
188 py + radii[i] > field.getOriginY() + float(field.getHeight()) * field.getCellSize()))
189 cost += 100.0;
190 }
191 return cost;
192 };
193 double best = score(vx, vy, std::numeric_limits<double>::infinity());
194 // Every score term is non-negative; a zero-cost current choice cannot be improved.
195 if (best <= 1e-9) return;
196 const auto consider = [&](float x, float y) {
197 reachable(x, y);
198 const double value = score(x, y, best - 1e-9);
199 if (value < best - 1e-9) {
200 best = value;
201 vx = x;
202 vy = y;
203 }
204 };
205 consider(0.f, 0.f);
206 consider(vxs[i], vys[i]);
207 const float samplingSpeed = std::max(preferredLength, speed * 0.25f);
208 // Fractions reuse the same directions. Preserve the original trig arguments,
209 // multiplication order and candidate order, but evaluate each direction only once.
210 const float baseAngle = preferredLength > 1e-5f ? std::atan2(preferredY, preferredX) : headings[i];
211 std::array<float, std::size(predictionAngles)> sampleXs, sampleYs;
212 for (size_t angle = 0; angle < std::size(predictionAngles); ++angle) {
213 sampleXs[angle] = std::cos(baseAngle + predictionAngles[angle]) * samplingSpeed;
214 sampleYs[angle] = std::sin(baseAngle + predictionAngles[angle]) * samplingSpeed;
215 }
216 for (float fraction : predictionFractions)
217 for (size_t angle = 0; angle < std::size(predictionAngles); ++angle)
218 consider(sampleXs[angle] * fraction, sampleYs[angle] * fraction);
219}
220
221} // namespace eve::crowd
double y
double x
double score
Definition Agent.cpp:51
int priority
eve::resource::CostSpec cost
float grain
ScriptForceVector acceleration
std::int32_t c
std::int32_t first
std::vector< Colorf > px
float length
std::array< float, 3 > position
MeleePoint3 b
Definition MeleeHit.cpp:41
double radius
Definition MeleeHit.cpp:42
MeleePoint3 a
Definition MeleeHit.cpp:40
OceanWakeSettings settings
glm::dvec3 dx
double dt
std::string error
Definition Package.cpp:174
#define EV_PROFILE_MODULE(module, name)
Profile the enclosing scope, tagged with a module for grouping.
Definition Profile.h:158
Object::Ptr value
double urgency
std::string slot
float dy
Definition Shadow.cpp:151
std::map< Cell, int > best
float fraction
int neighbor
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 Status success(StatusCode code=StatusCode::Ok)
Construct a successful status with an explicit non-error outcome.
Definition Status.cpp:19
float getOriginX() const
Returns the origin x.
Definition CrowdField.h:62
int getWidth() const
网格尺寸访问器。
Definition CrowdField.h:56
float getOriginY() const
Returns the origin y.
Definition CrowdField.h:64
bool resolvePenetration(float &wx, float &wy, float radius) const
圆 vs 阻挡格碰撞消解:把圆心从覆盖到的阻挡格中推出来。
int getHeight() const
Returns the height.
Definition CrowdField.h:58
float getCellSize() const
Returns the cell size.
Definition CrowdField.h:60
bool valid() const
是否配置了有效网格。
Definition CrowdField.h:53
Result< void > configureAvoidance(AvoidanceSettings settings)
Configure predictive velocity sampling; invalid input leaves settings unchanged.
AvoidanceSettings getAvoidanceSettings() const
Return an owning settings snapshot. @thread Simulation thread only.
std::int64_t maxSpatialVisits
Query row/cell/binary-search work.
Definition Crowd.h:78
std::int64_t maxNeighborVisits
Definition Crowd.h:75
Optional bounded velocity sampling for RTS local avoidance.
Definition Crowd.h:129
float horizon
Positive prediction seconds, at most ten.
Definition Crowd.h:131
float margin
Non-negative extra pair clearance in world units.
Definition Crowd.h:132
int maxNeighbors
Nearest interacting neighbors considered, in [1,128].
Definition Crowd.h:133
std::vector< float > xs
SOA agent storage, indexed by compact slot id. @cost Linear in agent count; mutation keeps all owned ...
std::vector< float > preferredVys
CrowdExecution execution
std::vector< float > headings
std::vector< float > maxSpeeds
std::vector< float > vys
std::vector< float > ys
std::vector< float > preferredVxs
bool canContact(size_t a, size_t b) const
std::vector< float > targetYs
bool canAvoid(size_t a, size_t b) const
void dispatchWork(std::size_t items, const std::function< void(std::size_t, std::size_t)> &body)
std::vector< float > maxAccels
std::vector< TieKey > tieKeys
void forEachNeighbor(float qx, float qy, float radius, Fn &&fn, StepReport *partitionReport=nullptr) const
AvoidanceSettings avoidance
std::vector< InteractionPolicy > interactions
std::vector< float > vxs
std::vector< int32_t > avoidancePriorities
std::vector< std::vector< AvoidanceNeighbor > > predictionNeighbors
Per-step avoidance neighbor scratch space. @cost Linear in checked neighbors and bounded by avoidance...
void selectAvoidanceVelocity(size_t index, float dt, float &vx, float &vy)
std::vector< int32_t > actions
std::vector< uint8_t > hasTargets
std::vector< float > radii
std::vector< float > targetXs
Owning observations of one completed advance; simulation-thread only.
Definition Crowd.h:94
std::int64_t cellsVisited
Occupied cells enumerated by all neighborhood queries.
Definition Crowd.h:105
std::int64_t spatialVisits
Query row/cell enumeration and binary-search comparisons.
Definition Crowd.h:108
std::int64_t candidatesVisited
Bucket entries inspected before radius or interaction filtering.
Definition Crowd.h:111
Non-allocating internal unwind signal, translated at the checked simulation boundary.