载入中...
搜索中...
未找到
RTSMovementGroups.cpp
浏览该文件的文档.
1// eve-hot-path
2#include "common/Profile.h"
3#include "rts/RTS.h"
6
7#include <algorithm>
8#include <cmath>
9#include <unordered_set>
10
11namespace eve::rts {
12namespace {
13Result<void> groupFailure(const char* message) {
15}
16
17double remainingRoute(Unit& unit, const OrderRecord& order) {
18 auto motion = unit.motion();
19 auto navigation = unit.navigation();
20 WorldPosition previous{motion->x, motion->y};
21 double remaining = 0.0;
22 const auto add = [&](WorldPosition next) {
23 remaining += std::hypot(static_cast<double>(next.x) - previous.x, static_cast<double>(next.y) - previous.y);
24 previous = next;
25 };
26 if (navigation->plannedOrderId == order.id && !navigation->unreachable) {
27 for (std::size_t i = navigation->waypointIndex; i < navigation->waypoints.size(); ++i)
28 add(navigation->waypoints[i]);
29 }
30 add(order.target);
31 return remaining;
32}
33} // namespace
34
36 if (batch.units.size() < 2 || batch.units.size() > 1024 || movementGroups_.size() >= 64 ||
37 (batch.kind != OrderKind::Move && batch.kind != OrderKind::AttackMove) || !std::isfinite(batch.leadDistance) ||
38 batch.leadDistance <= 0.f)
39 return Result<FanOutReceipt>::failure(groupFailure("Movement group requires 2..1024 units, Move/AttackMove, "
40 "available group capacity and positive lead distance")
41 .status());
43 group.state.leadDistance = batch.leadDistance;
44 group.handles.reserve(batch.units.size());
45 group.state.members.reserve(batch.units.size());
46 for (auto subject : batch.units) {
47 auto* unit = findUnit(subject);
48 if (!unit || !unit->durability()->alive || unit->containment()->container.isBound())
50 groupFailure("Movement group member must be a live uncontained owned unit").status());
51 group.handles.push_back(ecs::handle_of(unit));
52 group.epochs.push_back(unit->orders()->values.membershipEpoch_);
53 group.state.members.push_back({subject, {}});
54 }
55 movementGroups_.reserve(movementGroups_.size() + 1);
56 CommandSpec command;
57 command.kind = batch.kind;
58 command.target = batch.target;
59 auto admitted = CommandFanOutSystem::fanOut(group.handles, command, batch.formation);
60 if (!admitted) return admitted;
61 for (std::size_t i = 0; i < group.state.members.size(); ++i)
62 group.state.members[i].orderId = admitted.value().orderIds[i];
63 movementGroups_.push_back(std::move(group));
64 return admitted;
65}
66
67Result<std::size_t> RTS::stepMovementGroups() {
68 EV_PROFILE_MODULE("rts", "RTS::stepMovementGroups");
69 // Derived factors are refreshed even when the last group dissolved. Native
70 // and Crowd motion consume the same projection after navigation/convoy.
71 {
72 auto view = ecs::View<Unit, Unit::Navigation>();
73 for (auto it = view.begin(); it != view.end(); ++it) {
74 auto [navigation] = *it;
75 navigation->formationSpeedFactor = 1.f;
76 navigation->formationTarget.reset();
77 }
78 }
79 std::size_t processed = 0;
80 std::vector<CrowdFlowNavigation::GroupInput> flowGroups;
81 for (auto& group : movementGroups_) {
82 MovementGroup active;
83 active.state.leadDistance = group.state.leadDistance;
84 std::vector<double> distances;
85 std::vector<WorldPosition> targets;
86 double offsetX = 0.0, offsetY = 0.0;
87 bool openTravel = true;
88 double furthest = 0.0;
89 for (std::size_t i = 0; i < group.handles.size(); ++i) {
90 auto* unit = dynamic_cast<Unit*>(ecs::try_get(group.handles[i]));
91 if (!unit || !unit->durability()->alive || unit->containment()->container.isBound() ||
92 unit->orders()->values.membershipEpoch_ != group.epochs[i])
93 continue;
94 auto current = systems_internal::readCurrent(unit->orders()->values);
95 if (!current) return Result<std::size_t>::failure(current.status());
96 if (!current.value() || current.value()->id != group.state.members[i].orderId ||
97 (current.value()->kind != OrderKind::Move && current.value()->kind != OrderKind::AttackMove))
98 continue;
99 auto navigation = unit->navigation();
100 if (pathfinder_ && navigation->plannedOrderId == current.value()->id && !navigation->unreachable &&
101 navigation->waypointIndex + 1 < navigation->waypoints.size()) {
102 const WorldPosition position{unit->motion()->x, unit->motion()->y};
103 const auto waypoint = navigation->waypoints[navigation->waypointIndex];
104 const double tolerance =
105 std::max(static_cast<double>(unit->motion()->arrivalRadius),
106 static_cast<double>(unit->crowd()->radius) + navigationGrid_.cellSize * 0.1);
107 if (std::hypot(static_cast<double>(position.x) - waypoint.x,
108 static_cast<double>(position.y) - waypoint.y) <= tolerance &&
109 systems_internal::isFormationSegmentClear(*pathfinder_, navigationGrid_, position,
110 navigation->waypoints[navigation->waypointIndex + 1],
111 unit->crowd()->radius))
112 ++navigation->waypointIndex;
113 }
114 const double remaining = remainingRoute(*unit, *current.value());
115 if (!std::isfinite(remaining))
117 groupFailure("Movement group route distance must be finite").status());
118 // A traffic loser must not stop the winner from clearing its route.
119 // Keep membership so ordinary pacing resumes after the wait ends.
120 const auto engagedPosition = systems_internal::entityPosition(unit->combat()->target);
121 const bool engaged =
122 current.value()->kind == OrderKind::AttackMove && engagedPosition &&
123 unit->combat()->engagementRange > 0.f &&
124 std::hypot(double(unit->motion()->x) - engagedPosition->x,
125 double(unit->motion()->y) - engagedPosition->y) <= unit->combat()->engagementRange;
126 const bool yielding = engaged || unit->navigation()->trafficWaiting || unit->supply()->convoyWaiting ||
127 (unit->morale()->retreating && unit->tactics()->retreatCovering);
128 if (!yielding) furthest = std::max(furthest, remaining);
129 // Keep the formation compressed until the winning unit has cleared its reserved portal.
130 openTravel = openTravel && !yielding && !navigation->trafficRecoveryTarget;
131 targets.push_back(current.value()->target);
132 offsetX += static_cast<double>(unit->motion()->x) - current.value()->target.x;
133 offsetY += static_cast<double>(unit->motion()->y) - current.value()->target.y;
134 distances.push_back(remaining);
135 active.handles.push_back(group.handles[i]);
136 active.epochs.push_back(group.epochs[i]);
137 active.state.members.push_back(group.state.members[i]);
138 }
139 group = std::move(active);
140 if (group.handles.size() < 2) continue;
141 bool allArrived = true;
142 for (std::size_t i = 0; i < group.handles.size(); ++i) {
143 auto* unit = static_cast<Unit*>(ecs::try_get(group.handles[i]));
144 allArrived = allArrived && unit->motion()->arrived &&
145 std::hypot(double(unit->motion()->x) - targets[i].x,
146 double(unit->motion()->y) - targets[i].y) <= unit->motion()->arrivalRadius;
147 }
148 if (allArrived) {
149 // The moving formation is complete; AttackMove may retain its combat stance.
150 group.handles.clear();
151 group.epochs.clear();
152 group.state.members.clear();
153 continue;
154 }
155 offsetX /= static_cast<double>(group.handles.size());
156 offsetY /= static_cast<double>(group.handles.size());
157 const double offsetLength = std::hypot(offsetX, offsetY);
158 const double residual = offsetLength > 0.0 ? std::max(0.0, 1.0 - group.state.leadDistance / offsetLength) : 0.0;
159 std::vector<WorldPosition> movingTargets;
160 movingTargets.reserve(targets.size());
161 for (std::size_t i = 0; i < targets.size(); ++i) {
162 const WorldPosition target{static_cast<float>(targets[i].x + offsetX * residual),
163 static_cast<float>(targets[i].y + offsetY * residual)};
165 return Result<std::size_t>::failure(groupFailure("Moving formation target must be finite").status());
166 movingTargets.push_back(target);
167 if (pathfinder_ && openTravel) {
168 auto* unit = static_cast<Unit*>(ecs::try_get(group.handles[i]));
169 const WorldPosition from{unit->motion()->x, unit->motion()->y};
170 openTravel = systems_internal::isFormationSegmentClear(*pathfinder_, navigationGrid_, from, targets[i],
171 unit->crowd()->radius) &&
172 systems_internal::isFormationSegmentClear(*pathfinder_, navigationGrid_, from, target,
173 unit->crowd()->radius);
174 }
175 }
176 for (std::size_t i = 0; i < group.handles.size(); ++i) {
177 auto* unit = static_cast<Unit*>(ecs::try_get(group.handles[i]));
178 const double excess =
179 pathfinder_ && !openTravel ? 0.0 : std::max(0.0, furthest - distances[i] - group.state.leadDistance);
180 unit->navigation()->formationSpeedFactor =
181 static_cast<float>(std::clamp(1.0 - excess / group.state.leadDistance, 0.0, 1.0));
182 if (openTravel) {
183 // Translate the assigned destination slots to a shared moving
184 // anchor. The anchor is derived from current positions, so
185 // restore and member removal cannot leave an orphan leader.
186 unit->navigation()->formationTarget = movingTargets[i];
187 // A radius-clear direct route supersedes intermediate grid
188 // waypoints; retaining them would send the unit back afterward.
189 if (pathfinder_) unit->navigation()->waypointIndex = unit->navigation()->waypoints.size();
190 } else if (pathfinder_ && !unit->navigation()->trafficRecoveryTarget &&
191 !unit->navigation()->trafficWaiting &&
192 systems_internal::isFormationSegmentClear(*pathfinder_, navigationGrid_,
193 {unit->motion()->x, unit->motion()->y}, targets[i],
194 unit->crowd()->radius)) {
195 // Other members may still be fighting or crossing. A checked direct final leg
196 // does not need another full-map field and keeps this member's original slot.
197 unit->navigation()->formationTarget = targets[i];
198 unit->navigation()->waypointIndex = unit->navigation()->waypoints.size();
199 }
200 ++processed;
201 }
202 if (crowdFlowNavigation_ && crowdFlowNavigation_->enabled() && !openTravel) {
203 CrowdFlowNavigation::GroupInput projection;
204 projection.targets = targets;
205 for (std::size_t i = 0; i < group.handles.size(); ++i) {
206 auto* unit = static_cast<Unit*>(ecs::try_get(group.handles[i]));
207 if (unit->crowd()->link.isBound())
208 projection.members.push_back({group.handles[i], group.state.members[i].orderId});
209 }
210 if (!projection.members.empty()) flowGroups.push_back(std::move(projection));
211 }
212 }
213 std::erase_if(movementGroups_, [](const auto& group) { return group.handles.size() < 2; });
214 if (crowdFlowNavigation_ && crowdFlowNavigation_->enabled()) {
215 auto published = crowdFlowNavigation_->replaceGroups(*crowd_, std::move(flowGroups));
216 if (!published) return Result<std::size_t>::failure(published.status());
217 }
218 return Result<std::size_t>::success(processed);
219}
220
221Result<std::vector<RTSMovementGroupSnapshot>> RTS::captureMovementGroups() const {
222 std::vector<RTSMovementGroupSnapshot> result;
223 for (const auto& group : movementGroups_) {
224 RTSMovementGroupSnapshot active;
225 active.leadDistance = group.state.leadDistance;
226 for (std::size_t i = 0; i < group.handles.size(); ++i) {
227 auto* unit = dynamic_cast<Unit*>(ecs::try_get(group.handles[i]));
228 if (!unit || !unit->durability()->alive || unit->containment()->container.isBound() ||
229 unit->orders()->values.membershipEpoch_ != group.epochs[i])
230 continue;
231 auto current = systems_internal::readCurrent(unit->orders()->values);
232 if (!current) return Result<std::vector<RTSMovementGroupSnapshot>>::failure(current.status());
233 if (current.value() &&
234 (current.value()->kind == OrderKind::Move || current.value()->kind == OrderKind::AttackMove) &&
235 current.value()->id == group.state.members[i].orderId)
236 active.members.push_back(group.state.members[i]);
237 }
238 if (active.members.size() >= 2) {
239 std::sort(active.members.begin(), active.members.end(), [](const auto& left, const auto& right) {
240 return left.subject.format() < right.subject.format();
241 });
242 result.push_back(std::move(active));
243 }
244 }
245 std::sort(result.begin(), result.end(), [](const auto& left, const auto& right) {
246 return left.members.front().subject.format() < right.members.front().subject.format();
247 });
248 return Result<std::vector<RTSMovementGroupSnapshot>>::success(std::move(result));
249}
250
251Result<std::vector<RTS::MovementGroup>> RTS::prepareMovementGroups(const RTSStateSnapshot& snapshot) const {
252 using Output = Result<std::vector<MovementGroup>>;
253 if (snapshot.version == 1 && !snapshot.movementGroups.empty())
254 return Output::failure(groupFailure("Version 1 RTS snapshots cannot contain movement groups").status());
255 std::vector<MovementGroup> result;
256 std::unordered_set<SubjectRef> claimed;
257 for (const auto& state : snapshot.movementGroups) {
258 if (state.members.size() < 2 || !std::isfinite(state.leadDistance) || state.leadDistance <= 0.f)
259 return Output::failure(groupFailure("Invalid movement-group snapshot geometry").status());
261 group.state = state;
262 for (const auto& member : state.members) {
263 auto* unit = findUnit(member.subject);
264 const auto saved = std::find_if(snapshot.units.begin(), snapshot.units.end(),
265 [&](const auto& candidate) { return candidate.subject == member.subject; });
266 if (!unit || saved == snapshot.units.end() || !claimed.insert(member.subject).second ||
267 !saved->durability.alive || saved->container.isValid())
268 return Output::failure(groupFailure("Invalid or duplicate movement-group member").status());
269 OrderComponent validator;
270 auto restored = validator.restoreState(saved->orders);
271 if (!restored) return Output::failure(restored.status());
272 auto current = validator.current();
273 if (!current || current.value().id != member.orderId ||
274 (current.value().kind != OrderKind::Move && current.value().kind != OrderKind::AttackMove))
275 return Output::failure(
276 groupFailure("Movement-group membership does not match its active order").status());
277 group.handles.push_back(ecs::handle_of(unit));
278 group.epochs.push_back(unit->orders()->values.membershipEpoch_);
279 }
280 result.push_back(std::move(group));
281 }
282 return Output::success(std::move(result));
283}
284} // namespace eve::rts
double y
double x
LogicalId target
bool & active
int subject
Definition AnimSmr.cpp:163
std::vector< FieldTarget > targets
std::string message
wgpu::PopErrorScopeStatus status
HexVec3 left
HexVec3 right
std::array< float, 3 > position
std::string from
Poco::JSON::Object::Ptr result
Snapshot snapshot
double radius
Definition MeleeHit.cpp:42
std::vector< std::int32_t > order
OceanSprayView view
std::shared_ptr< const OceanSprayFrame > previous
#define EV_PROFILE_MODULE(module, name)
Profile the enclosing scope, tagged with a module for grouping.
Definition Profile.h:158
RTS module owner and phase-one composition profile entry point.
double current
AbilityActivationGroup group
TacticalUnit * unit
float offsetX
float offsetY
float(ui::Theme::* member)[4]
std::map< std::string, std::span< const std::uint8_t > > members
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 Result< FanOutReceipt > fanOut(std::span< const ecs::EntityHandle > unitHandles, const CommandSpec &command, const FormationSpec &formation)
Submit one command to every selected live Unit.
Unit * findUnit(SubjectRef subject) const noexcept
Resolve a module-owned unit by persistent subject identity.
Definition RTS.cpp:978
Result< FanOutReceipt > submitMovementGroup(const MovementGroupBatch &batch)
Commit a caller-built immediate Move/AttackMove group with coordinated pacing.
constexpr HexDirection next(HexDirection d) noexcept
The next direction clockwise (NW wraps to NE).
Definition HexMetrics.h:76
ForceVector add(ForceVector a, ForceVector b)
Definition ForceMath.h:13
Result< std::optional< OrderRecord > > readCurrent(OrderComponent &orders)
std::optional< WorldPosition > entityPosition(const ecs::EntityHandle &handle)
bool isFinitePosition(WorldPosition position)
EVENGINE_API_DOMAINS bool isFormationSegmentClear(const map::Pathfinder &pathfinder, const NavigationGrid &grid, WorldPosition from, WorldPosition to, float radius)
One domain-neutral command submitted to a unit's generic order queue.
Definition RTSTypes.h:106
WorldPosition target
Definition RTSTypes.h:108
Caller-built admission batch for an immediate coordinated Move or AttackMove command....
Definition RTSSystems.h:48
float leadDistance
Positive world-space allowance before leaders slow for lagging members.
Definition RTSSystems.h:52
OrderKind kind
Supported coordinated order; other kinds reject before mutation.
Definition RTSSystems.h:53
std::vector< SubjectRef > units
Owned stable identities; no entity pointers are retained.
Definition RTSSystems.h:49