载入中...
搜索中...
未找到
RTSCrowdMotion.cpp
浏览该文件的文档.
1#include "common/Profile.h"
2#include "crowd/Crowd.h"
5
6#include <algorithm>
7#include <cmath>
8#include <new>
9#include <optional>
10#include <vector>
11
12namespace eve::rts {
17
19 return stepInternal(step, crowd, nullptr);
20}
22 CrowdFlowNavigation& navigation) {
23 return stepInternal(step, crowd, &navigation);
24}
25Result<std::size_t> CrowdMotionSystem::stepInternal(const SimulationStep& step, crowd::Crowd& crowd,
26 CrowdFlowNavigation* flowNavigation) {
27 EV_PROFILE_MODULE("rts", "CrowdMotionSystem::step");
28 const crowd::CrowdStep crowdStep{step.tick, step.delta, {}};
29 auto admitted = crowd.checkAdvanceClock(crowdStep);
30 if (!admitted) return Result<std::size_t>::failure(admitted.status());
31 if (step.delta.nanoseconds() < 0)
33 DiagnosticCode::InvalidArgument, "RTS crowd step delta must be non-negative", "step.delta"));
35 if (flowNavigation) {
36 auto begun = flowNavigation->begin(crowd, step);
37 if (!begun) return Result<std::size_t>::failure(begun.status());
38 change = begun.value();
39 }
40 struct LinkedUnit {
41 Unit* unit;
42 Unit::Motion* motion;
43 Unit::Navigation* navigation;
44 Unit::Crowd* settings;
45 Unit::Combat* combat;
46 Unit::Supply* supply;
47 Unit::Morale* morale;
48 Unit::Tactics* tactics;
49 Unit::Command* command;
50 Unit::Effects* effects;
51 OrderComponent* orders;
52 bool sharedFlowReady = true;
53 std::optional<OrderRecord> record{};
54 };
55 std::vector<LinkedUnit> linked;
56 std::vector<Unit::Crowd*> detached;
57 bool needsBinding = false;
58 auto view = ecs::View<Unit, Unit::Identity, Unit::Motion, Unit::Navigation, Unit::Orders, Unit::Crowd, Unit::Combat,
59 Unit::Containment, Unit::Supply, Unit::Morale, Unit::Tactics, Unit::Command, Unit::Effects>();
60 for (auto it = view.begin(); it != view.end(); ++it) {
61 auto [identity, motion, navigation, orders, settings, combat, containment, supply, morale, tactics, command,
62 effects] = *it;
63 auto* unit = identity == nullptr ? nullptr : dynamic_cast<Unit*>(ecs::try_get(identity->self));
64 if (unit == nullptr || &*unit->identity() != identity) continue;
65 if (!settings->link.isBound() || containment->container.isBound()) {
66 detached.push_back(settings);
67 continue;
68 }
69 needsBinding = needsBinding || settings->runtimeBindingKey != settings->link.key() ||
70 !crowd.isAgentAlive({settings->runtimeAgent, settings->runtimeOwner});
71 linked.push_back(
72 {unit, motion, navigation, settings, combat, supply, morale, tactics, command, effects, &orders->values});
73 }
74 // Logical-name admission happens only when a binding changes. Ordinary ticks use numeric references.
75 if (needsBinding) {
76 std::vector<const std::string*> keys;
77 keys.reserve(linked.size());
78 for (const auto& entry : linked) keys.push_back(&entry.settings->link.key());
79 std::sort(keys.begin(), keys.end(), [](const auto* a, const auto* b) { return *a < *b; });
80 if (std::adjacent_find(keys.begin(), keys.end(), [](const auto* a, const auto* b) { return *a == *b; }) !=
81 keys.end())
83 Diagnostic::error(DiagnosticCode::Conflict, "RTS crowd agent keys must be unique", "unit.crowd.link"));
84 }
85 crowd::AgentRemovalBatch removals;
86 for (const auto* settings : detached) {
87 const crowd::AgentRef ref{settings->runtimeAgent, settings->runtimeOwner};
88 if (crowd.isAgentAlive(ref)) removals.agents.push_back(ref);
89 }
90 for (const auto& entry : linked) {
91 const crowd::AgentRef ref{entry.settings->runtimeAgent, entry.settings->runtimeOwner};
92 if (entry.settings->runtimeBindingKey != entry.settings->link.key() && crowd.isAgentAlive(ref))
93 removals.agents.push_back(ref);
94 }
95 if (!removals.agents.empty()) {
96 auto removed = crowd.removeAgents(removals);
97 if (!removed) return Result<std::size_t>::failure(removed.status());
98 }
99 for (auto* settings : detached) {
100 settings->runtimeAgent = {};
101 settings->runtimeOwner = 0;
102 settings->runtimeBindingKey.clear();
103 }
104 if (linked.empty()) {
105 auto advanced = crowd.advance(crowdStep);
106 if (!advanced) return Result<std::size_t>::failure(advanced.status());
108 }
109
110 const auto isWaiting = [](const LinkedUnit& entry) {
111 return (entry.navigation->trafficWaiting && !entry.navigation->trafficRecoveryTarget) ||
112 entry.supply->convoyWaiting || (entry.morale->retreating && entry.tactics->retreatCovering);
113 };
114 struct FlowAssignment {
115 size_t index;
116 CrowdFlowNavigation::Route route;
117 };
118 std::vector<FlowAssignment> flowAssignments;
119 crowd::AgentUpdateBatch updates;
120 std::vector<crowd::AgentRef> references;
121 updates.agents.reserve(linked.size());
122 references.reserve(linked.size());
123 for (auto& entry : linked) {
124 const std::string& key = entry.settings->link.key();
125 crowd::AgentRef reference{entry.settings->runtimeAgent, entry.settings->runtimeOwner};
126 if (entry.settings->runtimeBindingKey != key || !crowd.isAgentAlive(reference)) {
127 auto resolved = crowd.resolveNamedAgent(key);
128 if (!resolved) {
129 // Legacy binding admits existing authoritative ECS geometry, including preexisting overlap.
130 // Production creation goes through the atomic placement batch instead.
131 const int agent = crowd.addNamedAgent(key, entry.motion->x, entry.motion->y, entry.settings->heading,
132 entry.settings->radius);
133 if (agent < 0)
135 DiagnosticCode::Failed, "canonical Crowd rejected an RTS binding", "unit.crowd.link"));
136 resolved = crowd.agentRef(agent);
137 }
138 if (!resolved) return Result<std::size_t>::failure(resolved.status());
139 reference = resolved.value();
140 entry.settings->runtimeAgent = reference.handle;
141 entry.settings->runtimeOwner = reference.owner;
142 entry.settings->runtimeBindingKey = key;
143 }
144 crowd::AgentUpdate update;
145 update.reference = reference;
146 if (flowNavigation) update.flow = crowd::FlowLease{};
147 update.radius = entry.settings->radius;
148 update.avoidancePriority = entry.navigation->movementPriority;
149 const float speedFactor =
150 entry.morale->active ? std::clamp(entry.morale->suppressedSpeedFactor, 0.0f, 1.0f) : 1.0f;
151 const float commandFactor =
152 entry.command->requiresCommand && !entry.command->inCommand ? entry.command->outOfCommandSpeedFactor : 1.0f;
153 const float effectFactor = static_cast<float>(entry.effects->values.multiplier("speedMultiplier"));
154 update.maxSpeed =
155 entry.motion->speed * speedFactor * commandFactor * effectFactor * entry.navigation->formationSpeedFactor;
156 auto current = readCurrent(*entry.orders);
157 if (!current) return Result<std::size_t>::failure(current.status());
158 auto record = std::move(current).takeValue();
159 update.holdPosition = record && record->kind == OrderKind::HoldPosition;
160 bool attackMoveEngaged = false;
161 if (record && record->kind == OrderKind::AttackMove && entry.combat->engagementRange > 0.0f &&
162 !entry.navigation->trafficRecoveryTarget && !entry.navigation->combatSlotTarget) {
163 auto engaged = entityPosition(entry.combat->target);
164 attackMoveEngaged = engaged && distanceSquared(entry.motion->x, entry.motion->y, engaged->x, engaged->y) <=
165 entry.combat->engagementRange * entry.combat->engagementRange;
166 }
167 if (record && isMovementOrder(record->kind) && !isWaiting(entry) && !attackMoveEngaged) {
168 WorldPosition target = systems_internal::movementGoal(*entry.unit, *record);
169 const auto requestedGoal = target;
170 if (entry.navigation->plannedOrderId == record->id && !entry.navigation->unreachable &&
171 entry.navigation->waypointIndex < entry.navigation->waypoints.size())
172 target = entry.navigation->waypoints[entry.navigation->waypointIndex];
173 if (record->kind == OrderKind::Move && entry.navigation->formationTarget)
174 target = *entry.navigation->formationTarget;
175 if (entry.navigation->combatSlotTarget) target = *entry.navigation->combatSlotTarget;
176 if (entry.navigation->trafficRecoveryTarget) target = *entry.navigation->trafficRecoveryTarget;
177 if (flowNavigation && systems_internal::isSharedFlowOrder(*entry.unit, *record)) {
178 auto requested =
179 flowNavigation->requestRoute(crowd, entry.unit->identity()->self, record->id,
180 {entry.motion->x, entry.motion->y}, requestedGoal, step.tick);
181 if (!requested) return Result<std::size_t>::failure(requested.status());
182 flowAssignments.push_back({updates.agents.size(), std::move(requested).takeValue()});
183 }
184 update.intent = {crowd::AgentAction::Seek, true, target.x, target.y};
185 } else {
186 update.intent = {crowd::AgentAction::Idle, false, 0.f, 0.f};
187 }
188 entry.record = std::move(record);
189 updates.agents.push_back(update);
190 references.push_back(reference);
191 }
192 if (flowNavigation) {
194 crowd::AgentUpdateBatch releases;
195 releases.agents.reserve(references.size());
196 for (const auto ref : references) {
197 crowd::AgentUpdate release;
198 release.reference = ref;
199 release.flow = crowd::FlowLease{};
200 releases.agents.push_back(std::move(release));
201 }
202 auto cleared = crowd.updateAgents(releases);
203 if (!cleared) return Result<std::size_t>::failure(cleared.status());
204 }
205 auto pumped = flowNavigation->pump(crowd, step);
206 if (!pumped) return Result<std::size_t>::failure(pumped.status());
207 for (const auto& assignment : flowAssignments) {
208 auto& entry = linked[assignment.index];
209 auto& update = updates.agents[assignment.index];
210 auto before = crowd.readAgent(references[assignment.index]);
211 if (!before) return Result<std::size_t>::failure(before.status());
212 auto steered = flowNavigation->steerRoute(crowd, {before.value().x, before.value().y}, assignment.route,
213 entry.settings->radius, before.value().movement, update);
214 if (!steered) return Result<std::size_t>::failure(steered.status());
215 entry.sharedFlowReady = steered.value() == CrowdFlowNavigation::DriveState::Ready;
216 entry.navigation->unreachable = steered.value() == CrowdFlowNavigation::DriveState::Unreachable ||
218 if (!entry.navigation->unreachable) entry.navigation->unreachableReported = false;
219 if (entry.navigation->unreachable && !entry.navigation->unreachableReported) {
220 if (entry.record) flowNavigation->queueNotice(entry.unit->identity()->self, *entry.record);
221 }
222 }
223 }
224 auto updated = crowd.updateAgents(updates);
225 if (!updated) return Result<std::size_t>::failure(updated.status());
226 crowd::AgentFrame frame;
227 std::vector<std::uint8_t> arrivalSelection;
228 try {
229 frame.agents.reserve(references.size());
230 arrivalSelection.assign(references.size(), 0);
231 } catch (const std::bad_alloc&) {
233 Diagnostic::error(DiagnosticCode::Failed, "Cannot prepare RTS Crowd output frame", "rts.crowd.frame"));
234 }
235 const bool zeroDelta = step.delta.nanoseconds() == 0;
236 std::optional<crowd::Crowd::AgentUpdatePlan> arrivalPlan;
237 if (!zeroDelta) {
238 updates.agents.clear();
239 for (const auto reference : references) {
240 crowd::AgentUpdate arrived;
241 arrived.reference = reference;
242 arrived.intent = {crowd::AgentAction::Idle, false, 0.f, 0.f};
243 updates.agents.push_back(arrived);
244 }
245 auto prepared = crowd.prepareAgentUpdates(updates);
246 if (!prepared) return Result<std::size_t>::failure(prepared.status());
247 arrivalPlan.emplace(std::move(prepared).takeValue());
248 }
249 auto advanced = crowd.advance(crowdStep);
250 if (!advanced) return Result<std::size_t>::failure(advanced.status());
251 auto copied = crowd.copyAgentStates(references, frame);
252 if (!copied) return Result<std::size_t>::failure(copied.status());
253 updates.agents.clear();
254 for (std::size_t index = 0; index < linked.size(); ++index) {
255 const auto& entry = linked[index];
256 const auto& state = frame.agents[index].state;
257 entry.motion->x = state.x;
258 entry.motion->y = state.y;
259 entry.settings->heading = state.heading;
260 }
261 // Publish every pose before evaluating goals that observe another unit's new pose.
262 for (std::size_t index = 0; index < linked.size(); ++index) {
263 const auto& entry = linked[index];
264 const auto& state = frame.agents[index].state;
265 const auto& record = entry.record;
266 if (!record || !isMovementOrder(record->kind)) {
267 entry.motion->arrived = true;
268 continue;
269 }
270 if (!entry.sharedFlowReady || isWaiting(entry) || entry.navigation->trafficRecoveryTarget ||
271 entry.navigation->combatSlotTarget) {
272 entry.motion->arrived = false;
273 continue;
274 }
275 const auto target = systems_internal::movementGoal(*entry.unit, *record);
276 const float remaining = std::sqrt(distanceSquared(state.x, state.y, target.x, target.y));
277 float arrivalRadius = systems_internal::interactionArrivalRadius(*entry.unit, *record);
278 if (record->kind == OrderKind::Attack)
279 arrivalRadius = std::max(arrivalRadius, entry.combat->engagementRange);
280 else if (record->kind == OrderKind::Resupply || record->kind == OrderKind::SupplyRelay)
281 arrivalRadius = std::max(arrivalRadius, entry.supply->range * 0.8f);
282 entry.motion->arrived = remaining <= arrivalRadius;
283 if (entry.motion->arrived) {
284 // Arrival is a gameplay tolerance, not permission to undo collision resolution.
285 arrivalSelection[index] = 1;
286 }
287 }
288 if (zeroDelta) {
289 // The no-time pass cannot move agents. The copied frame already validates every
290 // reference, so only units that reached a goal need an idle-intent update.
291 crowd::AgentUpdateBatch arrived;
292 for (std::size_t index = 0; index < references.size(); ++index) {
293 if (arrivalSelection[index] == 0) continue;
294 crowd::AgentUpdate update;
295 update.reference = references[index];
296 update.intent = {crowd::AgentAction::Idle, false, 0.f, 0.f};
297 arrived.agents.push_back(update);
298 }
299 if (!arrived.agents.empty()) {
300 auto arrivals = crowd.updateAgents(arrived);
301 if (!arrivals) return Result<std::size_t>::failure(arrivals.status());
302 }
303 } else {
304 auto arrivals = crowd.commitAgentUpdates(std::move(*arrivalPlan), arrivalSelection);
305 if (!arrivals) return Result<std::size_t>::failure(arrivals.status());
306 }
308}
309
310} // namespace eve::rts
double x
LogicalId target
AuthorityStoreHandleRef reference
Definition Authority.cpp:24
SQObjectPtr key
Definition ECS.cpp:155
ScriptComponentRecord record
Definition ECS.cpp:228
PhysicsJointLink link
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
OceanWakeSettings settings
ssq::Object frame
OceanSprayView view
std::array< std::uint64_t, kPixelChunkSize *kPixelChunkSize > updated
#define EV_PROFILE_MODULE(module, name)
Profile the enclosing scope, tagged with a module for grouping.
Definition Profile.h:158
RoadNetwork resolved
int removed
double current
TacticalUnit * unit
float step
Definition TreeMesh.cpp:451
uint32_t index
uint64_t identity
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
群体行为模块:连续流场寻路 + 海量单位移动/转向/行动 + Boids 鸟群。
Definition Crowd.h:266
Result< AgentState > readAgent(AgentRef reference) const
Read an owning state snapshot by owner-qualified identity.
Result< StepReport > advance(float dt)
Advance using bounded simultaneous integration and contact projection.
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< void > checkAdvanceClock(const CrowdStep &step) const
Validate external clock admission before a consumer publishes its input batch.
Result< AgentRef > agentRef(int slot) const
Resolve a compatibility dense slot to an owning identity value.
Result< AgentBatchReceipt > updateAgents(const AgentUpdateBatch &batch)
Compatibility-only one-call facade over canonical prepareAgentUpdates/commitAgentUpdates....
Result< AgentUpdatePlan > prepareAgentUpdates(const AgentUpdateBatch &batch) const
Canonically validate and own a batch before a later nonallocating commit. @ownership Copies values; r...
Result< AgentRef > resolveNamedAgent(const std::string &stableId) const
Resolve a logical name once at binding boundaries, without rebuilding any state.
Result< AgentBatchReceipt > commitAgentUpdates(AgentUpdatePlan &&plan, std::span< const std::uint8_t > selection)
Validate all identities then apply selected prepared updates without allocating success-path workspac...
bool isAgentAlive(AgentRef reference) const noexcept
Whether the owner and generation still identify a live agent. @thread Simulation thread only; the cal...
Result< AgentBatchReceipt > removeAgents(const AgentRemovalBatch &batch)
Atomically remove live references; every reference is checked before any removal. @ownership Borrows ...
Result< AgentBatchReceipt > copyAgentStates(std::span< const AgentRef > references, AgentFrame &destination) const
Copy a selected owning frame in request order; stale input preserves the destination....
Owner-thread derived shared static-goal navigation service; retains no ECS pointers.
EVENGINE_API_DOMAINS Result< void > pump(crowd::Crowd &crowd, const SimulationStep &step)
void queueNotice(ecs::EntityHandle unit, const OrderRecord &order)
Append an owning post-commit event; failure leaves this notice unpublished.
EVENGINE_API_DOMAINS Result< InputChange > begin(crowd::Crowd &crowd, const SimulationStep &step)
Reconcile owner/input epochs and retire unused goals; owner thread, no callbacks.
EVENGINE_API_DOMAINS Result< DriveState > steerRoute(crowd::Crowd &crowd, WorldPosition position, const Route &route, float radius, crowd::MovementBinding movement, crowd::AgentUpdate &update)
Steer a previously collected route without repeating target-set conversion. @ownership Borrows route ...
EVENGINE_API_DOMAINS Result< Route > requestRoute(crowd::Crowd &crowd, ecs::EntityHandle unit, std::string_view orderId, WorldPosition position, WorldPosition target, SimulationTick tick)
Collect the applicable group or exact-terminal request for one current order. @ownership Borrows inpu...
static Result< std::size_t > stepSharedFlow(const SimulationStep &step, crowd::Crowd &crowd, CrowdFlowNavigation &navigation)
Consume shared static-goal fields through a known owner-thread flow service.
static Result< std::size_t > step(const SimulationStep &step, crowd::Crowd &crowd)
Push ECS targets into Crowd, advance it once, and project positions back to Unit::Motion.
void keys(const Value &value, std::initializer_list< const char * > names)
WorldPosition movementGoal(Unit &unit, const OrderRecord &order)
Resolve the current canonical movement goal without retaining entity pointers. @ownership Returns a w...
float interactionArrivalRadius(Unit &unit, const OrderRecord &order)
float distanceSquared(float ax, float ay, float bx, float by)
Result< std::optional< OrderRecord > > readCurrent(OrderComponent &orders)
std::optional< WorldPosition > entityPosition(const ecs::EntityHandle &handle)
bool isSharedFlowOrder(Unit &unit, const OrderRecord &order)
Whether motion uses a shared field instead of a radius-clear moving slot.
One deterministic fixed-step emitted by SimulationClock.
Definition Time.h:158
Explicit owner step; positive duration consumes the next contiguous tick. Zero reconciles current tic...
Definition Crowd.h:88
SimulationTick tick
Definition Crowd.h:89