9#include <unordered_set>
13Result<void> groupFailure(
const char*
message) {
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) {
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]);
36 if (batch.
units.size() < 2 || batch.
units.size() > 1024 || movementGroups_.size() >= 64 ||
40 "available group capacity and positive lead distance")
45 group.state.members.reserve(batch.
units.size());
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_);
55 movementGroups_.reserve(movementGroups_.size() + 1);
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));
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();
79 std::size_t processed = 0;
80 std::vector<CrowdFlowNavigation::GroupInput> flowGroups;
81 for (
auto&
group : movementGroups_) {
83 active.state.leadDistance =
group.state.leadDistance;
84 std::vector<double> distances;
85 std::vector<WorldPosition>
targets;
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])
99 auto navigation =
unit->navigation();
100 if (pathfinder_ && navigation->plannedOrderId ==
current.value()->id && !navigation->unreachable &&
101 navigation->waypointIndex + 1 < navigation->waypoints.size()) {
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 &&
110 navigation->waypoints[navigation->waypointIndex + 1],
111 unit->crowd()->radius))
112 ++navigation->waypointIndex;
114 const double remaining = remainingRoute(*
unit, *
current.value());
115 if (!std::isfinite(remaining))
117 groupFailure(
"Movement group route distance must be finite").
status());
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);
130 openTravel = openTravel && !yielding && !navigation->trafficRecoveryTarget;
134 distances.push_back(remaining);
137 active.state.members.push_back(
group.state.members[i]);
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;
150 group.handles.clear();
151 group.epochs.clear();
152 group.state.members.clear();
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) {
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};
171 unit->crowd()->radius) &&
173 unit->crowd()->radius);
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));
186 unit->navigation()->formationTarget = movingTargets[i];
189 if (pathfinder_)
unit->navigation()->waypointIndex =
unit->navigation()->waypoints.size();
190 }
else if (pathfinder_ && !
unit->navigation()->trafficRecoveryTarget &&
191 !
unit->navigation()->trafficWaiting &&
198 unit->navigation()->waypointIndex =
unit->navigation()->waypoints.size();
202 if (crowdFlowNavigation_ && crowdFlowNavigation_->enabled() && !openTravel) {
203 CrowdFlowNavigation::GroupInput projection;
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});
210 if (!projection.members.empty()) flowGroups.push_back(std::move(projection));
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));
221Result<std::vector<RTSMovementGroupSnapshot>> RTS::captureMovementGroups()
const {
222 std::vector<RTSMovementGroupSnapshot>
result;
223 for (
const auto&
group : movementGroups_) {
224 RTSMovementGroupSnapshot
active;
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])
231 auto current = systems_internal::readCurrent(
unit->orders()->values);
232 if (!
current)
return Result<std::vector<RTSMovementGroupSnapshot>>::failure(
current.status());
234 (
current.value()->kind == OrderKind::Move ||
current.value()->kind == OrderKind::AttackMove) &&
238 if (
active.members.size() >= 2) {
240 return left.subject.format() < right.subject.format();
246 return left.members.front().subject.format() < right.members.front().subject.format();
248 return Result<std::vector<RTSMovementGroupSnapshot>>::success(std::move(
result));
251Result<std::vector<RTS::MovementGroup>> RTS::prepareMovementGroups(
const RTSStateSnapshot& snapshot)
const {
252 using Output = Result<std::vector<MovementGroup>>;
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());
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();
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_);
282 return Output::success(std::move(
result));
std::vector< FieldTarget > targets
wgpu::PopErrorScopeStatus status
std::array< float, 3 > position
std::shared_ptr< const OceanSprayFrame > previous
#define EV_PROFILE_MODULE(module, name)
Profile the enclosing scope, tagged with a module for grouping.
RTS module owner and phase-one composition profile entry point.
AbilityActivationGroup group
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.
static Result success(T value)
Construct a successful result owning value.
static Result failure(Status status)
Construct a failed result from a structured status.
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.
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).
ForceVector add(ForceVector a, ForceVector b)
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.
Caller-built admission batch for an immediate coordinated Move or AttackMove command....
float leadDistance
Positive world-space allowance before leaders slow for lagging members.
OrderKind kind
Supported coordinated order; other kinds reject before mutation.
std::vector< SubjectRef > units
Owned stable identities; no entity pointers are retained.