载入中...
搜索中...
未找到
RTSNavigation.cpp
浏览该文件的文档.
1#include "common/Profile.h"
2#include <algorithm>
3#include <memory>
4#include "map/Path.h"
5#include "map/Pathfinder.h"
10 const auto visible = [&](SubjectRef subject) {
11 if (!viewer.intel()->enabled) return true;
12 const auto found = std::find_if(viewer.intel()->contacts.begin(), viewer.intel()->contacts.end(),
13 [&](const auto& contact) { return contact.subject == subject; });
14 return found != viewer.intel()->contacts.end() && found->visible && found->detected;
15 };
16 const auto contribution = [&](const weapon::WeaponDefinition& definition, WorldPosition source) {
17 if (definition.range <= 0.0f) return 0.0f;
18 const float distance = std::hypot(source.x - point.x, source.y - point.y);
19 if (distance > definition.range) return 0.0f;
20 return std::max(0.0f, definition.damage) / std::max(0.05f, definition.cooldown) *
21 (0.1f + 1.0f - distance / definition.range);
22 };
23 float threat = 0.0f;
26 for (auto it = units.begin(); it != units.end(); ++it) {
27 auto [identity, motion, faction, weaponLink, durability, containment] = *it;
28 if (!durability->alive || containment->container.isBound() ||
29 FactionRelationSystem::isAllied(dynamic_cast<Faction*>(faction->link.resolve()), &viewer) ||
30 !visible(identity->subject))
31 continue;
32 auto* weaponEntity = dynamic_cast<weapon::WeaponEntity*>(weaponLink->link.resolve());
33 const auto* definition = weaponEntity == nullptr ? nullptr : weaponEntity->definition()->def;
34 if (definition != nullptr) threat += contribution(*definition, {motion->x, motion->y});
35 }
38 for (auto it = buildings.begin(); it != buildings.end(); ++it) {
39 auto [identity, placement, faction, weaponLink, integrity, construction] = *it;
40 if (!integrity->alive || construction->progress < 1.0f ||
41 FactionRelationSystem::isAllied(dynamic_cast<Faction*>(faction->link.resolve()), &viewer) ||
42 !visible(identity->subject))
43 continue;
44 auto* weaponEntity = dynamic_cast<weapon::WeaponEntity*>(weaponLink->link.resolve());
45 const auto* definition = weaponEntity == nullptr ? nullptr : weaponEntity->definition()->def;
46 if (definition != nullptr) threat += contribution(*definition, {placement->worldX, placement->worldY});
47 }
48 return threat;
49}
50
51} // namespace eve::rts::systems_internal
52namespace eve::rts {
59 const NavigationEvent& unreachable) {
60 return stepInternal(pathfinder, grid, unreachable, false);
61}
63 const NavigationEvent& unreachable) {
64 return stepInternal(pathfinder, grid, unreachable, true);
65}
66Result<std::size_t> NavigationSystem::stepInternal(map::Pathfinder& pathfinder, const NavigationGrid& grid,
67 const NavigationEvent& unreachable, bool sharedFlows) {
68 EV_PROFILE_MODULE("rts", "NavigationSystem::step");
69 if (!std::isfinite(grid.cellSize) || grid.cellSize <= 0.0f || !std::isfinite(grid.originX) ||
70 !std::isfinite(grid.originY))
73 "RTS navigation grid requires finite origin and positive cell size", "navigation.grid"));
74 const auto worldToCell = [&](float value, float origin) {
75 return static_cast<int>(std::lround((value - origin) / grid.cellSize));
76 };
77 const auto cellToWorld = [&](int value, float origin) {
78 return origin + static_cast<float>(value) * grid.cellSize;
79 };
80 std::size_t processed = 0;
81 auto view = ecs::View<Unit, Unit::Identity, Unit::Motion, Unit::Navigation, Unit::Orders, Unit::Containment,
82 Unit::Tactics, Unit::Supply, Unit::Faction>();
83 for (auto it = view.begin(); it != view.end(); ++it) {
84 auto [identity, motion, navigation, orders, containment, tactics, supply, faction] = *it;
85 auto* unit = identity == nullptr ? nullptr : dynamic_cast<Unit*>(ecs::try_get(identity->self));
86 if (unit == nullptr || &*unit->identity() != identity) continue;
87 if (containment->container.isBound()) continue;
88 auto current = readCurrent(orders->values);
89 if (!current) return Result<std::size_t>::failure(current.status());
90 auto record = std::move(current).takeValue();
91 if (!record || !isMovementOrder(record->kind)) {
92 navigation->waypoints.clear();
93 navigation->waypointIndex = 0;
94 navigation->plannedOrderId.clear();
95 navigation->unreachable = false;
96 navigation->unreachableReported = false;
97 navigation->trafficWaiting = false;
98 navigation->patrolInitialized = false;
99 navigation->patrolTowardTarget = true;
100 supply->routeThreat = 0.0f;
101 supply->routeAvoidedThreat = false;
102 continue;
103 }
104 const auto goal = systems_internal::movementGoal(*unit, *record);
106 if (navigation->plannedOrderId != record->id) {
107 navigation->unreachable = false;
108 navigation->unreachableReported = false;
109 }
110 navigation->waypoints.clear();
111 navigation->waypointIndex = 0;
112 navigation->plannedOrderId = record->id;
113 navigation->plannedGoal = goal;
114 ++processed;
115 continue;
116 }
117 const bool supplyMission = record->kind == OrderKind::Resupply || record->kind == OrderKind::SupplyRelay;
118 auto* viewer = dynamic_cast<Faction*>(faction->link.resolve());
119 float currentRouteThreat = 0.0f;
120 if (supplyMission && viewer != nullptr) {
121 WorldPosition previous{motion->x, motion->y};
122 for (std::size_t index = navigation->waypointIndex; index < navigation->waypoints.size(); ++index) {
123 const WorldPosition point = navigation->waypoints[index];
124 currentRouteThreat +=
125 visibleHostileThreatAt(*viewer, point) * std::hypot(point.x - previous.x, point.y - previous.y);
126 previous = point;
127 }
128 }
129 const bool threatChanged = supplyMission && navigation->plannedOrderId == record->id &&
130 currentRouteThreat > supply->routeThreat + 1e-4f;
131 const bool changed = navigation->plannedOrderId != record->id || threatChanged ||
132 distanceSquared(goal.x, goal.y, navigation->plannedGoal.x, navigation->plannedGoal.y) >
133 grid.cellSize * grid.cellSize * 0.25f;
134 if (changed) {
135 navigation->waypoints.clear();
136 navigation->waypointIndex = 0;
137 navigation->plannedOrderId = record->id;
138 navigation->plannedGoal = goal;
139 navigation->unreachable = false;
140 navigation->unreachableReported = false;
141 const int startX = worldToCell(motion->x, grid.originX);
142 const int startY = worldToCell(motion->y, grid.originY);
143 const int goalX = worldToCell(goal.x, grid.originX);
144 const int goalY = worldToCell(goal.y, grid.originY);
145 std::unique_ptr<map::Path> baseline;
146 std::unique_ptr<map::Path> path;
147 if (supplyMission) {
148 baseline.reset(pathfinder.findPath(startX, startY, goalX, goalY));
149 path.reset(pathfinder.findPath(startX, startY, goalX, goalY, [&](int x, int y) {
150 if (viewer == nullptr) return 0.0f;
151 const WorldPosition point{cellToWorld(x, grid.originX), cellToWorld(y, grid.originY)};
152 return visibleHostileThreatAt(*viewer, point) * 0.5f;
153 }));
154 const auto exposure = [&](const map::Path* candidate) {
155 if (candidate == nullptr || candidate->empty() || viewer == nullptr) return 0.0f;
156 float total = 0.0f;
157 WorldPosition previous{motion->x, motion->y};
158 for (int index = 1; index < candidate->getLength(); ++index) {
159 const WorldPosition point{cellToWorld(candidate->getX(index), grid.originX),
160 cellToWorld(candidate->getY(index), grid.originY)};
161 total += visibleHostileThreatAt(*viewer, point) *
162 std::hypot(point.x - previous.x, point.y - previous.y);
163 previous = point;
164 }
165 return total;
166 };
167 supply->routeThreat = exposure(path.get());
168 supply->routeAvoidedThreat =
169 baseline != nullptr && !baseline->empty() && supply->routeThreat + 1e-4f < exposure(baseline.get());
170 } else {
171 path.reset(pathfinder.findPath(startX, startY, goalX, goalY));
172 supply->routeThreat = 0.0f;
173 supply->routeAvoidedThreat = false;
174 }
175 if (path == nullptr || path->empty()) {
176 navigation->unreachable = true;
177 } else {
178 navigation->waypoints.reserve(static_cast<std::size_t>(path->getLength()));
179 for (int index = 1; index < path->getLength(); ++index)
180 navigation->waypoints.push_back(
181 {cellToWorld(path->getX(index), grid.originX), cellToWorld(path->getY(index), grid.originY)});
182 }
183 } else if (supplyMission) {
184 supply->routeThreat = currentRouteThreat;
185 }
186 while (navigation->waypointIndex < navigation->waypoints.size()) {
187 const auto waypoint = navigation->waypoints[navigation->waypointIndex];
188 const float radius = std::max(motion->arrivalRadius, grid.cellSize * 0.1f);
189 if (distanceSquared(motion->x, motion->y, waypoint.x, waypoint.y) > radius * radius) break;
190 ++navigation->waypointIndex;
191 }
192 if (navigation->unreachable && !navigation->unreachableReported) {
193 navigation->unreachableReported = true;
194 if (unreachable) unreachable(*unit, *record);
195 }
196 ++processed;
197 }
198 return Result<std::size_t>::success(processed,
200}
201
202} // namespace eve::rts
double y
double x
int subject
Definition AnimSmr.cpp:163
bool changed
ScriptComponentRecord record
Definition ECS.cpp:228
double radius
Definition MeleeHit.cpp:42
float distance
glm::dvec3 origin
Placement placement
OceanSprayView view
std::shared_ptr< const OceanSprayFrame > previous
std::string path
Definition PlayHost.cpp:111
#define EV_PROFILE_MODULE(module, name)
Profile the enclosing scope, tagged with a module for grouping.
Definition Profile.h:158
Object::Ptr value
bool found
std::string_view source
double current
TacticalUnit * unit
std::vector< UnitCandidate > units
bool visible
uint32_t index
Contact contact
glm::vec3 point
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
Strong, domain-neutral reference to a runtime subject.
Definition SubjectRef.h:26
Pathfinding facade. Single-agent: A*. Group (same goal): Flow Field + follow. Grid/topology internals...
Definition Pathfinder.h:62
Path * findPath(int sx, int sy, int gx, int gy)
A* from (sx,sy) to (gx,gy). Returns owned Path* (may be empty if unreachable). Never returns nullptr ...
RTS building domain root with placement and production composition.
Definition RTSTypes.h:852
static bool isAllied(Faction *left, Faction *right) noexcept
Return true when both live factions are identical or share a team in a common Match.
Faction domain root; membership is a set of typed runtime handles.
Definition RTSTypes.h:1192
static Result< std::size_t > stepSharedFlow(map::Pathfinder &pathfinder, const NavigationGrid &grid, const NavigationEvent &unreachable)
Plan native routes while shared-flow eligible Crowd orders use the injected flow service.
static Result< std::size_t > step(map::Pathfinder &pathfinder, const NavigationGrid &grid, const NavigationEvent &unreachable={})
Replan changed movement orders and advance reached waypoints.
RTS unit domain root.
Definition RTSTypes.h:501
武器实体:数据全部在组件里,行为在 WeaponSystem。
void worldToCell(const GridConfig &cfg, float px, float py, int &cx, int &cy, int mapW, int mapH)
Maps planar coordinates to the nearest cell. Staggered/hex layouts use a bounded nearest-neighbor sea...
void cellToWorld(const GridConfig &cfg, int cx, int cy, float &px, float &py)
Maps a cell to planar coordinates (px, py). On XY plane these are world (x, y); on XZ plane they are ...
WorldPosition movementGoal(Unit &unit, const OrderRecord &order)
Resolve the current canonical movement goal without retaining entity pointers. @ownership Returns a w...
float visibleHostileThreatAt(Faction &viewer, WorldPosition point)
Observe visible hostile weapon threat at a world point using canonical faction intelligence.
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 isSharedFlowNavigationOrder(Unit &unit, const OrderRecord &order)
Whether planning uses the shared policy, before the current group projection exists.
std::function< void(Unit &, const OrderRecord &)> NavigationEvent
Notification emitted once when a newly planned order has no canonical map route.
Definition RTSSystems.h:282
WidgetDesc grid(int columns, std::vector< WidgetDesc > children, std::string id)
Fixed-column grid; children are placed in source order.
Definition Widget.cpp:878
StatusCode
Stable outcome category for an operation.
Definition Status.h:28
Construction progress and generation-checked assigned builders.
Definition RTSTypes.h:909
Owning faction link.
Definition RTSTypes.h:905
Runtime identity.
Definition RTSTypes.h:861
Building health and repair economy configuration.
Definition RTSTypes.h:916
Placement world key and authoritative cell state.
Definition RTSTypes.h:871
Canonical weapon entity used by an armed building.
Definition RTSTypes.h:968
World/grid conversion used when an RTS composition consumes a canonical map Pathfinder.
Definition RTSSystems.h:265
Unit containment state for transports and building garrisons.
Definition RTSTypes.h:705
Canonical combat durability state consumed by combat::DamageRuntime.
Definition RTSTypes.h:643
Owning faction link.
Definition RTSTypes.h:565
Runtime identity and logical unit definition.
Definition RTSTypes.h:510
Authoritative kinematic state used by the phase-one move slice.
Definition RTSTypes.h:569
Weapon entity link.
Definition RTSTypes.h:553
Two-dimensional deterministic RTS world position.
Definition RTSTypes.h:53
std::string id
Definition Widget.h:17
武器模板(registerWeaponsFromJson 注册,进程级注册表)。