载入中...
搜索中...
未找到
CrowdSpawn.cpp
浏览该文件的文档.
2
3#include <unordered_set>
4
5namespace eve::crowd {
6bool isTerrainClear(const CrowdField& field, bool clamp, float x, float y, float radius) {
7 if (!field.valid()) return true;
8 if (clamp && (x - radius < field.getOriginX() || y - radius < field.getOriginY() ||
9 x + radius > field.getOriginX() + float(field.getWidth()) * field.getCellSize() ||
10 y + radius > field.getOriginY() + float(field.getHeight()) * field.getCellSize()))
11 return false;
12 float projectedX = x, projectedY = y;
13 field.resolvePenetration(projectedX, projectedY, radius);
14 return std::hypot(projectedX - x, projectedY - y) <= 0.001f;
15}
16
17namespace {
18constexpr float tolerance = 0.001f;
19
20void projectTerrain(const CrowdField& field, bool clamp, float& x, float& y, float radius) {
21 if (!field.valid()) return;
22 for (int pass = 0; pass < 4; ++pass) {
23 field.resolvePenetration(x, y, radius);
24 if (clamp) {
25 const float width = float(field.getWidth()) * field.getCellSize();
26 const float height = float(field.getHeight()) * field.getCellSize();
27 const float rx = std::min(radius, width * 0.5f), ry = std::min(radius, height * 0.5f);
28 x = std::clamp(x, field.getOriginX() + rx, field.getOriginX() + width - rx);
29 y = std::clamp(y, field.getOriginY() + ry, field.getOriginY() + height - ry);
30 }
31 }
32}
33} // namespace
34
36
38 const auto failure = [](DiagnosticCode code, const char* message) {
40 };
41 if (!std::isfinite(batch.maxDistance) || batch.maxDistance < 0.f || !std::isfinite(batch.searchSpacing) ||
42 batch.searchSpacing <= 0.f || batch.maxPasses < 1 || batch.maxPasses > 256 || batch.maxChecks < 1 ||
43 batch.maxChecks > 10000000 || batch.agents.size() > 1024 ||
46 return failure(DiagnosticCode::InvalidArgument, "Invalid spawn policy or work budget");
47 SpawnReceipt receipt;
48 if (batch.agents.empty())
50 if (impl_->xs.size() + batch.agents.size() > size_t(std::max(impl_->maxAgents, 0)))
51 return failure(DiagnosticCode::PreconditionViolation, "Crowd capacity cannot fit the batch");
52 std::unordered_set<std::string> names;
53 std::unordered_set<std::uint64_t> tieKeys;
54 if (batch.agents.size() > std::numeric_limits<std::uint64_t>::max() - impl_->nextAnonymousTieKey)
55 return failure(DiagnosticCode::Conflict, "Crowd tie identity sequence exhausted");
56 for (size_t i = 0; i < impl_->xs.size(); ++i)
57 if (!std::isfinite(impl_->xs[i]) || !std::isfinite(impl_->ys[i]) || !std::isfinite(impl_->radii[i]) ||
58 impl_->radii[i] < 0.f)
59 return failure(DiagnosticCode::PreconditionViolation, "Existing crowd geometry is invalid");
60 for (const auto& request : batch.agents) {
61 if ((request.movement.movement.value() == 0) != (request.movement.revision == 0))
62 return failure(DiagnosticCode::InvalidArgument, "Incomplete movement class binding");
63 const auto policy = request.policy.value_or(canonicalInteraction(request.interaction));
64 if (request.stableId.empty() || !std::isfinite(request.x) || !std::isfinite(request.y) ||
65 !std::isfinite(request.heading) || !std::isfinite(request.radius) || request.radius <= 0.f ||
66 !validInteraction(policy))
67 return failure(DiagnosticCode::InvalidArgument, "Invalid spawn agent");
68 if (impl_->namedAgents.contains(request.stableId) || !names.insert(request.stableId).second)
69 return failure(DiagnosticCode::Conflict, "Spawn stable identifiers must be unique");
70 const auto tie = namedTieValue(request.stableId);
71 if (impl_->namedTieKeys.contains(tie) || !tieKeys.insert(tie).second)
72 return failure(DiagnosticCode::Conflict, "Spawn numeric identity hash collision");
73 }
74
75 // No callbacks or external mutations occur between the snapshot and swap.
76 Crowd staged;
77 staged.impl_ = std::make_unique<Impl>(*impl_);
78 auto& d = *staged.impl_;
79 const size_t originalCount = d.xs.size();
80 bool exhausted = false;
81 const auto consume = [&]() {
82 if (receipt.checks >= batch.maxChecks) {
83 exhausted = true;
84 return false;
85 }
86 ++receipt.checks;
87 return true;
88 };
89 const auto isClear = [&](const SpawnRequest& request, float x, float y, bool checkAgents) {
90 const auto policy = request.policy.value_or(canonicalInteraction(request.interaction));
91 if (!consume() || !std::isfinite(x) || !std::isfinite(y) ||
92 !isTerrainClear(d.field, d.clampToField, x, y, request.radius))
93 return false;
94 if (!checkAgents) return true;
95 for (size_t i = 0; i < d.xs.size(); ++i) {
96 if (!consume()) return false;
97 if ((policy.contactLayer & d.interactions[i].contactMask) == 0 ||
98 (d.interactions[i].contactLayer & policy.contactMask) == 0)
99 continue;
100 if (std::hypot(double(x) - d.xs[i], double(y) - d.ys[i]) < double(request.radius) + d.radii[i] - tolerance)
101 return false;
102 }
103 return true;
104 };
105 for (const auto& request : batch.agents) {
106 float x = request.x, y = request.y;
107 bool clear = isClear(request, x, y, batch.policy != SpawnPolicy::PushNeighbors);
108 if (!clear && batch.policy == SpawnPolicy::NearestFree) {
109 // Double loop counters avoid integer overflow for tiny spacing/huge radii.
110 const double rings = std::ceil(double(batch.maxDistance) / double(batch.searchSpacing));
111 for (double ring = 1; ring <= rings && !clear && !exhausted; ++ring) {
112 const double radius = std::min(ring * double(batch.searchSpacing), double(batch.maxDistance));
113 const double samples = std::max(8.0, std::ceil(6.283185307179586 * radius / batch.searchSpacing));
114 for (double sample = 0; sample < samples && !exhausted; ++sample) {
115 const double angle = sample / samples * 6.283185307179586;
116 x = request.x + float(std::cos(angle) * radius);
117 y = request.y + float(std::sin(angle) * radius);
118 if (isClear(request, x, y, true)) {
119 clear = true;
120 break;
121 }
122 }
123 }
124 }
125 if (!clear)
126 return failure(
128 exhausted ? "Spawn work budget exhausted" : "No valid spawn placement within search distance");
129 const int slot = staged.addNamedAgent(request.stableId, x, y, request.heading, request.radius);
130 if (slot < 0) return failure(DiagnosticCode::InvariantViolation, "Validated spawn allocation rejected");
131 staged.impl_->movements[size_t(slot)] = request.movement;
132 auto reference = staged.agentRef(slot);
134 auto policy = staged.setInteractionPolicy(reference.value(),
135 request.policy.value_or(canonicalInteraction(request.interaction)));
136 if (!policy) return Result<SpawnReceipt>::failure(policy.status());
137 receipt.created.push_back({request.stableId, x, y, reference.value()});
138 }
139
140 if (batch.policy == SpawnPolicy::PushNeighbors) {
141 const size_t count = d.xs.size();
142 std::vector<uint8_t> active(count, 0);
143 for (size_t i = originalCount; i < count; ++i) active[i] = 1;
144 std::vector<double> correctionsX(count), correctionsY(count);
145 bool solved = false;
146 for (int pass = 0; pass <= batch.maxPasses; ++pass) {
147 std::fill(correctionsX.begin(), correctionsX.end(), 0.f);
148 std::fill(correctionsY.begin(), correctionsY.end(), 0.f);
149 bool overlap = false;
150 for (size_t i = 0; i < count; ++i) {
151 if (!active[i]) continue;
152 for (size_t j = 0; j < count; ++j) {
153 if (j == i || (j < i && active[j])) continue;
154 if (!consume())
155 return failure(DiagnosticCode::PreconditionViolation, "Spawn work budget exhausted");
156 if (!d.canContact(i, j)) continue;
157 double dx = double(d.xs[j]) - d.xs[i], dy = double(d.ys[j]) - d.ys[i];
158 double distance = std::hypot(dx, dy);
159 const double depth = double(d.radii[i]) + d.radii[j] - distance;
160 if (depth <= tolerance) continue;
161 overlap = true;
162 active[j] = 1;
163 const auto mobility = [&](size_t slot) {
164 return slot >= originalCount || d.interactions[slot].holdPosition
165 ? 0.f
166 : d.interactions[slot].pushability;
167 };
168 const float left = mobility(i), right = mobility(j), total = left + right;
169 if (total == 0.f)
170 return failure(DiagnosticCode::Conflict, "Spawn contact is blocked by fixed agents");
171 if (distance < 1e-6f) {
172 // Slot order only selects the tie direction. The operation is repeatable
173 // for identical world and request ordering; no random stream is consumed.
174 dx = i < j ? 1.f : -1.f;
175 dy = 0.f;
176 distance = 1.f;
177 }
178 correctionsX[i] -= dx / distance * depth * left / total;
179 correctionsY[i] -= dy / distance * depth * left / total;
180 correctionsX[j] += dx / distance * depth * right / total;
181 correctionsY[j] += dy / distance * depth * right / total;
182 }
183 }
184 if (!overlap) {
185 solved = true;
186 break;
187 }
188 if (pass == batch.maxPasses) break;
189 for (size_t i = 0; i < originalCount; ++i) {
190 if (!active[i] || d.interactions[i].holdPosition || d.interactions[i].pushability == 0.f) continue;
191 const double length = std::hypot(correctionsX[i], correctionsY[i]);
192 const float limit = d.field.valid() ? std::min(d.radii[i], d.field.getCellSize() * 0.5f) : d.radii[i];
193 const double scale = length > limit && length > 0.f ? limit / length : 1.0;
194 d.xs[i] += float(correctionsX[i] * scale);
195 d.ys[i] += float(correctionsY[i] * scale);
196 if (!std::isfinite(d.xs[i]) || !std::isfinite(d.ys[i]))
197 return failure(DiagnosticCode::PreconditionViolation, "Spawn displacement exceeds numeric range");
198 projectTerrain(d.field, d.clampToField, d.xs[i], d.ys[i], d.radii[i]);
199 if (!isTerrainClear(d.field, d.clampToField, d.xs[i], d.ys[i], d.radii[i]) ||
200 std::hypot(d.xs[i] - impl_->xs[i], d.ys[i] - impl_->ys[i]) > batch.maxDistance + tolerance)
202 "Spawn displacement violates terrain or distance budget");
203 }
204 }
205 if (!solved)
206 return failure(DiagnosticCode::PreconditionViolation, "Spawn relaxation did not converge within budget");
207 for (size_t i = 0; i < originalCount; ++i)
208 if (d.xs[i] != impl_->xs[i] || d.ys[i] != impl_->ys[i]) ++receipt.displacedAgents;
209 }
210 // Cached broadphase refers to pre-transaction positions; rebuild on the next advance.
211 d.spatialIndex.clear();
212 impl_.swap(staged.impl_);
214} catch (const std::bad_alloc&) {
216 Diagnostic::error(DiagnosticCode::Failed, "Cannot allocate agent creation transaction", "spawnBatch"));
217}
218
219} // namespace eve::crowd
double y
double x
bool & active
AuthorityStoreHandleRef reference
Definition Authority.cpp:24
std::string message
DiagnosticCode code
const GltfImportRequest & request
HexVec3 left
HexVec3 right
std::uint32_t height
std::uint32_t width
float length
std::array< float, 3 > scale
double radius
Definition MeleeHit.cpp:42
float distance
glm::dvec3 dx
float d
std::string slot
float dy
Definition Shadow.cpp:151
int count
int limit
Definition TreeMesh.cpp:166
std::uint32_t depth
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
连续流场(flow field)。
Definition CrowdField.h:25
群体行为模块:连续流场寻路 + 海量单位移动/转向/行动 + Boids 鸟群。
Definition Crowd.h:266
Result< void > setInteractionPolicy(AgentRef reference, InteractionPolicy policy)
Atomically replace independent steering/contact rules by owner-qualified identity.
Result< SpawnReceipt > createAgents(const AgentCreateBatch &batch)
Canonical atomic agent creation with placement policies and work budgets. @ownership Borrows the owni...
int addNamedAgent(const std::string &stableId, float x, float y, float heading, float radius)
Add an agent with an editor/game-stable logical identifier.
Definition Crowd.cpp:150
Result< SpawnReceipt > applySpawnBatch(const SpawnBatch &batch)
Apply a caller-built spawn batch atomically, including neighbor displacement.
Result< AgentRef > agentRef(int slot) const
Resolve a compatibility dense slot to an owning identity value.
bool validInteraction(InteractionPolicy policy)
Check finite mobility and nonnegative filter masks without modifying state.
InteractionPolicy canonicalInteraction(AgentInteraction policy)
Normalize a compatibility filter into the canonical two-filter policy.
std::uint64_t namedTieValue(std::string_view identity)
Hash UTF-8 identity bytes once at admission; collisions are rejected by the registry.
bool isTerrainClear(const CrowdField &field, bool clamp, float x, float y, float radius)
Shared exact-placement geometry predicate for creation and relocation transactions.
Definition CrowdSpawn.cpp:6
DiagnosticCode
Stable machine-readable diagnostic codes.
Definition Diagnostic.h:47
Caller-built transaction; positive budgets bound search and relaxation. @cost Linear in requested age...
Definition Crowd.h:223
int maxChecks
Combined candidate/neighbor work budget, at most ten million.
Definition Crowd.h:229
float searchSpacing
NearestFree samples concentric rings at this spacing.
Definition Crowd.h:227
float maxDistance
Maximum relocation from each requested/original position.
Definition Crowd.h:226
std::vector< SpawnRequest > agents
Definition Crowd.h:224
int maxPasses
Contact relaxation limit, at most 256.
Definition Crowd.h:228
SpawnPolicy policy
Definition Crowd.h:225
Observations from a committed spawn transaction. @cost Linear in created placement count; returned by...
Definition Crowd.h:246
std::vector< SpawnPlacement > created
Definition Crowd.h:247
One named agent to create; all fields are owned values.
Definition Crowd.h:210