载入中...
搜索中...
未找到
RTS.cpp
浏览该文件的文档.
1#include "rts/RTS.h"
2#include "common/Profile.h"
4#include "crowd/Crowd.h"
6#include "map/Fov.h"
7#include "map/Pathfinder.h"
8#include "rts/RTSAttributes.h"
11#include "rts/RTSMission.h"
15#include "sensing/Sensing.h"
17
18#include "action/Action.h"
19#include "common/Capability.h"
20
21#include <simplesquirrel/simplesquirrel.hpp>
22
23#include <algorithm>
24#include <cmath>
25#include <limits>
26#include <numbers>
27#include <set>
28#include <utility>
29
30namespace eve::rts {
31namespace {
36
37bool validSubject(SubjectRef subject) { return subject.isValid(); }
38
39bool sameHandle(const ecs::EntityHandle& left, const ecs::EntityHandle& right) noexcept {
40 return left.table == right.table && left.type == right.type && left.id == right.id &&
41 left.generation == right.generation;
42}
43
44Result<resource::CostSpec> scaledCost(const resource::CostSpec& source, double factor) {
45 if (!std::isfinite(factor) || factor <= 0.0)
47 DiagnosticCode::InvalidArgument, "RTS refund factor must be finite and positive", "refund.factor"));
48 std::vector<resource::ResourceCost> items;
49 items.reserve(source.items().size());
50 for (const auto& item : source.items()) {
51 const auto amount = static_cast<std::int64_t>(std::llround(static_cast<double>(item.amount.value()) * factor));
52 if (amount <= 0) continue;
53 auto scaled = resource::ResourceCost::create(item.resource.value(), amount);
54 if (!scaled) return Result<resource::CostSpec>::failure(scaled.status());
55 items.push_back(std::move(scaled).takeValue());
56 }
57 return resource::CostSpec::create(std::move(items));
58}
59
60std::uint64_t stableRallyGroup(SubjectRef subject) {
61 std::uint64_t hash = 1469598103934665603ull;
62 for (unsigned char byte : subject.format()) {
63 hash ^= byte;
64 hash *= 1099511628211ull;
65 }
66 return hash == 0 ? 1 : hash;
67}
68
69SubjectRef deterministicSubject(std::string_view seed, std::uint64_t sequence) {
70 const auto hash = [&](std::uint64_t basis) {
71 std::uint64_t value = basis;
72 for (unsigned char byte : seed) {
73 value ^= byte;
74 value *= 1099511628211ull;
75 }
76 for (unsigned shift = 0; shift < 64; shift += 8) {
77 value ^= static_cast<unsigned char>(sequence >> shift);
78 value *= 1099511628211ull;
79 }
80 return value;
81 };
82 const std::uint64_t high = hash(1469598103934665603ull);
83 const std::uint64_t low = hash(1099511628211ull);
85 for (unsigned index = 0; index < 8; ++index) {
86 bytes[index] = static_cast<std::uint8_t>(high >> ((7 - index) * 8));
87 bytes[8 + index] = static_cast<std::uint8_t>(low >> ((7 - index) * 8));
88 }
89 bytes[6] = static_cast<std::uint8_t>((bytes[6] & 0x0f) | 0x70);
90 bytes[8] = static_cast<std::uint8_t>((bytes[8] & 0x3f) | 0x80);
92}
93
94bool controls(const GameplaySession& session, SubjectRef subject) {
96 std::find(session.controlledSubjects.begin(), session.controlledSubjects.end(), subject) !=
97 session.controlledSubjects.end();
98}
99
100LogicalId gameplayId(std::string_view value) { return LogicalId::parse(value).value(); }
101
102Result<double> numericParameter(const Value& parameters, std::string_view name) {
103 const auto* object = parameters.getIf<Value::Object>();
104 if (!object)
106 "RTS gameplay parameters must be an object", "parameters"));
107 const auto found = object->find(std::string(name));
108 if (found == object->end() || !found->second.isNumeric())
110 "RTS gameplay parameter must be numeric",
111 "parameters." + std::string(name)));
112 return Result<double>::success(found->second.isInt64() ? static_cast<double>(found->second.asInt())
113 : found->second.asDouble());
114}
115
116template <typename T>
117T* tryGetCurrent(ecs::EntityHandle handle) {
118 if (handle.table != ecs::current()) return nullptr;
119 return dynamic_cast<T*>(ecs::try_get(handle));
120}
121
122template <typename T>
123void destroyHandles(std::vector<ecs::EntityHandle>& handles) {
124 for (const auto& handle : handles) {
125 if (auto* typed = tryGetCurrent<T>(handle)) typed->release();
126 }
127 handles.clear();
128}
129
130template <typename T>
131std::size_t countLive(const std::vector<ecs::EntityHandle>& handles) {
132 return static_cast<std::size_t>(std::count_if(handles.begin(), handles.end(), [](const ecs::EntityHandle& handle) {
133 return tryGetCurrent<T>(handle) != nullptr;
134 }));
135}
136
137template <typename T>
138bool owns(const std::vector<ecs::EntityHandle>& handles, const T& entity) {
139 const auto live = ecs::handle_of(const_cast<T*>(&entity));
140 return std::any_of(handles.begin(), handles.end(), [&live](const auto& handle) {
141 return handle.table == live.table && handle.type == live.type && handle.id == live.id &&
142 handle.generation == live.generation;
143 });
144}
145
146template <typename T>
147T* findSubject(const std::vector<ecs::EntityHandle>& handles, SubjectRef subject) {
148 for (const auto& handle : handles) {
149 auto* entity = tryGetCurrent<T>(handle);
150 if (entity != nullptr && entity->identity()->subject == subject) return entity;
151 }
152 return nullptr;
153}
154
155Result<LogicalId> parseScriptDefinition(std::string_view text) {
156 if (text.empty()) return Result<LogicalId>::success(LogicalId{});
157 const auto parsed = LogicalId::parse(text);
158 if (!parsed)
160 DiagnosticCode::InvalidArgument, "RTS script definition must be a canonical logical id", "definition"));
161 return Result<LogicalId>::success(*parsed);
162}
163
164
165} // namespace
166
168
169
174
175RTS::RTS() : gameplayRuntime_(std::make_unique<GameplayRuntime>()) {
176 cap::addListener<IGameplayControlProvider>(this);
177 cap::addListener<IGameplayInstanceCatalog>(this);
178}
179
181 cap::removeListener<IGameplayInstanceCatalog>(this);
182 cap::removeListener<IGameplayControlProvider>(this);
183 FogOfWarSystem::clear(fogState_);
184 setCrowdProvider(nullptr);
185 setCombatProviders(nullptr, nullptr);
186 clearOwnedRoots();
187}
188
189void RTS::clearOwnedRoots() noexcept {
190 movementGroups_.clear();
191 destroyHandles<Match>(matches_);
192 destroyHandles<Unit>(units_);
193 destroyHandles<Building>(buildings_);
194 destroyHandles<ResourceNode>(resourceNodes_);
195 destroyHandles<Player>(players_);
196 destroyHandles<Faction>(factions_);
197 destroyHandles<weapon::WeaponEntity>(weapons_);
198}
199
201 FogOfWarSystem::clear(fogState_);
202 fogProvider_ = std::move(provider);
203 for (const auto& handle : factions_)
204 if (auto* faction = tryGetCurrent<Faction>(handle)) faction->intel()->enabled = static_cast<bool>(fogProvider_);
205}
206
208 if (sensing_ != nullptr && (sensing_ != sensing || damage == nullptr)) {
209 for (const auto& id : combatState_.mirroredSubjects)
210 sensing_->remove(id).ignore("best-effort RTS sensing mirror cleanup");
211 combatState_.mirroredSubjects.clear();
212 combatState_.blockedSubjects.clear();
213 }
214 sensing_ = sensing;
215 damage_ = damage;
216}
217
219 if (damage_ == nullptr)
221 Diagnostic::error(DiagnosticCode::NotFound, "RTS combat damage provider is not attached", "damage"));
222 return damage_->configureSettlementRules(rules);
223}
224
225void RTS::setCrowdProvider(crowd::Crowd* crowd) noexcept {
226 if (crowd_ == crowd && (crowd == nullptr || crowdLifetime_.isAlive())) return;
227 if (crowd_ != nullptr && crowdLifetime_.isAlive()) {
228 for (const auto& handle : units_) {
229 auto* unit = tryGetCurrent<Unit>(handle);
230 if (unit != nullptr && unit->crowd()->link.isBound()) crowd_->removeNamedAgent(unit->crowd()->link.key());
231 }
232 }
233
234 crowd_ = crowd;
235 crowdLifetime_ = crowd ? crowd->lifetimeWitness() : LifetimeWitness{};
236 for (const auto& handle : units_) {
237 auto* unit = tryGetCurrent<Unit>(handle);
238 if (!unit) continue;
239 unit->crowd()->runtimeAgent = {};
240 unit->crowd()->runtimeOwner = 0;
241 unit->crowd()->runtimeBindingKey.clear();
242 }
243}
244
245std::string_view RTS::gameplayDomain() const noexcept { return "rts"; }
246
247std::vector<SubjectRef> RTS::gameplayInstances() const {
248 // One RTS instance is one player; the instance identity is that player's
249 // subject, which is also what `observeGameplay` resolves.
250 std::vector<SubjectRef> result;
251 for (const auto& handle : players_) {
252 auto* player = tryGetCurrent<Player>(handle);
253 if (player != nullptr && player->identity()->subject.isValid()) result.push_back(player->identity()->subject);
254 }
255 std::sort(result.begin(), result.end(),
256 [](const SubjectRef& left, const SubjectRef& right) { return left.format() < right.format(); });
257 return result;
258}
259
261 Player* player = resolvePlayer(instance);
262 if (!player)
264 Diagnostic::error(DiagnosticCode::NotFound, "RTS gameplay player was not found", "instance"));
265 if (!controls(session, instance))
267 DiagnosticCode::PreconditionViolation, "session does not control this RTS player", "instance"));
269 for (const auto& handle : player->selection()->units) {
270 auto* unit = tryGetCurrent<Unit>(handle);
271 if (!unit) continue;
272 auto current = unit->orders()->values.current();
273 std::string orderKind;
274 if (current) {
275 orderKind = orderKindName(current.value().kind);
276 } else if (current.code() == StatusCode::NotFound) {
277 current.ignore("idle RTS unit has no active order");
278 } else {
280 }
281 units.emplace_back(Value::Object{{"activeOrder", Value(std::move(orderKind))},
282 {"arrived", Value(unit->motion()->arrived)},
283 {"subject", Value(unit->identity()->subject.format())},
284 {"x", Value(unit->motion()->x)},
285 {"y", Value(unit->motion()->y)}});
286 }
287 GameplayObservation observation;
288 observation.domain = gameplayId("gameplay:rts");
289 observation.instance = instance;
290 observation.tick = player->selection()->tick;
291 observation.revision = player->selection()->revision;
292 observation.state = Value(Value::Object{{"selectedUnits", Value(std::move(units))}});
293 return Result<GameplayObservation>::success(std::move(observation));
294}
295
297 SubjectRef instance,
298 SubjectRef subject) const {
299 Player* player = resolvePlayer(instance);
300 Unit* unit = resolveUnit(subject);
301 if (!player || !unit)
303 Diagnostic::error(DiagnosticCode::NotFound, "RTS gameplay player or unit was not found", "subject"));
304 if (!controls(session, instance))
306 DiagnosticCode::PreconditionViolation, "session does not control this RTS player", "instance"));
307 const auto unitHandle = ecs::handle_of(unit);
308 const bool selected =
309 std::any_of(player->selection()->units.begin(), player->selection()->units.end(), [&](const auto& handle) {
310 return handle.table == unitHandle.table && handle.type == unitHandle.type && handle.id == unitHandle.id &&
311 handle.generation == unitHandle.generation;
312 });
313 if (!selected)
315 DiagnosticCode::PreconditionViolation, "RTS unit is not in the player's selection", "subject"));
316 Value number(Value::Object{{"type", Value("number")}});
317 Value schema(Value::Object{{"x", number}, {"y", number}});
318 std::vector<GameplayActionDescriptor> actions;
319 actions.push_back({gameplayId("rts:move"), schema});
320 actions.push_back({gameplayId("rts:attack"), std::move(schema)});
321 return Result<std::vector<GameplayActionDescriptor>>::success(std::move(actions));
322}
323
325 const GameplayCommand& command) {
326 Player* player = resolvePlayer(instance);
327 if (!player)
329 Diagnostic::error(DiagnosticCode::NotFound, "RTS gameplay player was not found", "instance"));
330 if (!controls(session, instance))
332 DiagnosticCode::PreconditionViolation, "session does not control this RTS player", "instance"));
333 if (command.id.empty())
335 Diagnostic::error(DiagnosticCode::InvalidArgument, "command id must not be empty", "command.id"));
336 if (command.observedTick != player->selection()->tick || command.expectedRevision != player->selection()->revision)
338 DiagnosticCode::Conflict, "RTS command was based on a stale observation", "command.expectedRevision"));
339 auto x = numericParameter(command.parameters, "x");
340 auto y = numericParameter(command.parameters, "y");
341 if (!x) return Result<GameplayCommandReceipt>::failure(x.status());
342 if (!y) return Result<GameplayCommandReceipt>::failure(y.status());
343
344 CommandSpec spec;
345 if (command.action == gameplayId("rts:move")) {
346 spec.kind = OrderKind::Move;
347 spec.definitionId = "rts:move";
348 } else if (command.action == gameplayId("rts:attack")) {
349 spec.kind = OrderKind::Attack;
350 spec.definitionId = "rts:attack";
351 } else {
353 Diagnostic::error(DiagnosticCode::Unsupported, "unsupported RTS gameplay action", "command.action"));
354 }
355 spec.target = {static_cast<float>(x.value()), static_cast<float>(y.value())};
356 FormationSpec formation;
357 auto accepted = fanOut(*player->selection(), spec, formation);
358 if (!accepted) return Result<GameplayCommandReceipt>::failure(accepted.status());
359 auto fanOutReceipt = std::move(accepted).takeValue();
360
362 receipt.commandId = command.id;
363 receipt.executionId = fanOutReceipt.orderIds.empty() ? std::string{} : fanOutReceipt.orderIds.front();
364 receipt.acceptedTick = player->selection()->tick;
365 receipt.resultingRevision = player->selection()->revision;
366 Value::Array orderIds;
367 for (auto& id : fanOutReceipt.orderIds) orderIds.emplace_back(std::move(id));
368 receipt.details = Value(Value::Object{{"accepted", Value(static_cast<std::int64_t>(fanOutReceipt.accepted))},
369 {"orderIds", Value(std::move(orderIds))}});
370 GameplayEvent event;
371 event.sequence = nextGameplayEventSequence_++;
372 event.tick = player->selection()->tick;
373 event.type = "rts.command.accepted";
374 event.subject = command.subject;
375 event.causationCommandId = command.id;
376 event.correlationId = command.id;
377 event.payload =
378 Value(Value::Object{{"action", Value(command.action.format())},
379 {"instance", Value(instance.format())},
380 {"resultingRevision", Value(static_cast<std::int64_t>(player->selection()->revision))}});
381 gameplayEvents_.push_back(std::move(event));
383}
384
386 const SimulationStep& simulationStep) {
387 Player* player = resolvePlayer(instance);
388 if (!player)
390 Diagnostic::error(DiagnosticCode::NotFound, "RTS gameplay player was not found", "instance"));
391 if (!controls(session, instance))
393 DiagnosticCode::PreconditionViolation, "session does not control this RTS player", "instance"));
394 if (simulationStep.tick <= player->selection()->tick)
396 Diagnostic::error(DiagnosticCode::Conflict, "RTS simulation tick must increase", "step.tick"));
397 auto advanced = step(simulationStep, gameplayRuntime_->adapter);
398 if (!advanced) return Result<GameplayObservation>::failure(advanced.status());
399 std::move(advanced).takeValue();
400 player->selection()->tick = simulationStep.tick;
401 ++player->selection()->revision;
402 return observeGameplay(session, instance);
403}
404
406 std::uint64_t afterSequence) const {
407 auto observation = observeGameplay(session, instance);
408 if (!observation) return Result<std::vector<GameplayEvent>>::failure(observation.status());
409 std::move(observation).takeValue();
410 std::vector<GameplayEvent> result;
411 for (const auto& event : gameplayEvents_) {
412 const auto* eventInstance = event.payload.find("instance");
413 if (event.sequence > afterSequence && eventInstance && eventInstance->isString() &&
414 eventInstance->asString() == instance.format())
415 result.push_back(event);
416 }
417 const bool empty = result.empty();
418 return Result<std::vector<GameplayEvent>>::success(std::move(result),
420}
421
423 if (!validSubject(subject))
425 Diagnostic::error(DiagnosticCode::InvalidArgument, "RTS Unit requires a valid SubjectRef", "subject"));
426 if (ownsSubject(subject, scriptRuntime_ && scriptRuntime_->spawningProduction ? SubjectClaimScope::Live
427 : SubjectClaimScope::LiveOrReserved))
429 Diagnostic::error(DiagnosticCode::Conflict, "RTS SubjectRef is already owned by this module", "subject"));
430 Unit* unit = Unit::createUnit(subject, std::move(definition));
431 if (unit == nullptr)
433 Diagnostic::error(DiagnosticCode::Failed, "ECS failed to create an RTS Unit", "unit"));
434 unit->attributes()->values = AttributeComponent{};
435 if (!scriptRuntime_ || !scriptRuntime_->spawningProduction) {
437 if (!attributes) {
438 const auto status = attributes.status();
439 unit->release();
441 }
442 }
443 auto effects = unit->effects()->values.bindSubject(subject);
444 if (!effects) {
445 const auto status = effects.status();
446 unit->release();
448 }
449 units_.push_back(ecs::handle_of(unit));
451}
452
454 if (!validSubject(subject))
456 Diagnostic::error(DiagnosticCode::InvalidArgument, "RTS Building requires a valid SubjectRef", "subject"));
457 if (ownsSubject(subject, SubjectClaimScope::LiveOrReserved))
459 Diagnostic::error(DiagnosticCode::Conflict, "RTS SubjectRef is already owned by this module", "subject"));
460 Building* building = Building::createBuilding(subject, std::move(definition));
461 if (building == nullptr)
463 Diagnostic::error(DiagnosticCode::Failed, "ECS failed to create an RTS Building", "building"));
464 auto effects = building->effects()->values.bindSubject(subject);
465 if (!effects) {
466 const auto status = effects.status();
467 building->release();
469 }
470 buildings_.push_back(ecs::handle_of(building));
472}
473
474Result<ResourceNode*> RTS::newResourceNode(SubjectRef subject, std::string resourceType, float amount,
475 WorldPosition position, std::size_t workerCapacity) {
476 if (!validSubject(subject) || resourceType.empty() || !std::isfinite(amount) || amount < 0.0f ||
477 !std::isfinite(position.x) || !std::isfinite(position.y) || workerCapacity == 0)
479 DiagnosticCode::InvalidArgument, "RTS resource node requires valid identity, stock, position and capacity",
480 "resourceNode"));
481 if (ownsSubject(subject, SubjectClaimScope::LiveOrReserved))
483 Diagnostic::error(DiagnosticCode::Conflict, "RTS SubjectRef is already owned by this module", "subject"));
485 if (node == nullptr)
487 Diagnostic::error(DiagnosticCode::Failed, "ECS failed to create an RTS ResourceNode", "resourceNode"));
488 node->position()->x = position.x;
489 node->position()->y = position.y;
490 node->stock()->resourceType = std::move(resourceType);
491 node->stock()->remaining = amount;
492 node->stock()->maximum = amount;
493 node->harvest()->capacity = workerCapacity;
494 resourceNodes_.push_back(ecs::handle_of(node));
496}
497
499 if (!validSubject(subject))
501 Diagnostic::error(DiagnosticCode::InvalidArgument, "RTS Player requires a valid SubjectRef", "subject"));
502 if (ownsSubject(subject, SubjectClaimScope::LiveOrReserved))
504 Diagnostic::error(DiagnosticCode::Conflict, "RTS SubjectRef is already owned by this module", "subject"));
506 if (player == nullptr)
508 Diagnostic::error(DiagnosticCode::Failed, "ECS failed to create an RTS Player", "player"));
509 players_.push_back(ecs::handle_of(player));
511}
512
514 if (!validSubject(subject))
516 Diagnostic::error(DiagnosticCode::InvalidArgument, "RTS Faction requires a valid SubjectRef", "subject"));
517 if (ownsSubject(subject, SubjectClaimScope::LiveOrReserved))
519 Diagnostic::error(DiagnosticCode::Conflict, "RTS SubjectRef is already owned by this module", "subject"));
521 if (faction == nullptr)
523 Diagnostic::error(DiagnosticCode::Failed, "ECS failed to create an RTS Faction", "faction"));
524 factions_.push_back(ecs::handle_of(faction));
525 faction->intel()->enabled = static_cast<bool>(fogProvider_);
526 if (scriptRuntime_ && scriptRuntime_->configured) {
527 const std::string key = faction->identity()->subject.format();
528 scriptRuntime_->economies.emplace(key, std::make_unique<ScriptRuntime::EconomySlot>());
529 auto factionFov = std::make_unique<map::Fov>(scriptRuntime_->width, scriptRuntime_->height);
530 factionFov->setMode("heightmap");
531 factionFov->setEyeOffset(1.0f);
532 factionFov->setCliffBlock(0.0f);
533 for (int y = 0; y < scriptRuntime_->height; ++y)
534 for (int x = 0; x < scriptRuntime_->width; ++x)
535 if (!scriptRuntime_->terrainElevations.empty())
536 factionFov->setElevation(
537 x, y,
538 scriptRuntime_->terrainElevations[static_cast<std::size_t>(y * scriptRuntime_->width + x)]);
539 scriptRuntime_->fovs.emplace(key, std::move(factionFov));
540 auto economyLink = EconomyLink::bind("rts/script/economy/" + key);
541 if (!economyLink) {
542 const Status status = economyLink.status();
543 scriptRuntime_->economies.erase(key);
544 scriptRuntime_->fovs.erase(key);
545 faction->release();
546 factions_.pop_back();
548 }
549 faction->economy()->link = std::move(economyLink).takeValue();
550 }
552}
553
554Result<void> RTS::materialize(Unit& unit) {
555 if (definitions_ == nullptr || !unit.definition()->id.isValid())
557 const std::size_t weaponCount = weapons_.size();
558 ArchetypeWeaponFactory factory = [this](std::string_view definitionId,
560 auto runtime = weapon::WeaponDefinitionRuntime::create(*definitions_, definitionId, instanceId);
561 if (!runtime) return Result<weapon::WeaponEntity*>::failure(runtime.status());
563 if (entity == nullptr)
565 Diagnostic::error(DiagnosticCode::Failed, "ECS failed to create an RTS weapon instance", "weapon"));
566 auto applied = runtime.value().applyTo(entity);
567 if (!applied) {
568 const Status status = applied.status();
569 entity->release();
571 }
572 weapons_.push_back(ecs::handle_of(entity));
574 };
575 auto applied = RTSArchetypeMaterializer::apply(*definitions_, unit, factory);
576 if (!applied) {
577 while (weapons_.size() > weaponCount) {
578 if (auto* entity = dynamic_cast<weapon::WeaponEntity*>(ecs::try_get(weapons_.back()))) entity->release();
579 weapons_.pop_back();
580 }
581 }
582 return applied;
583}
584
585Result<void> RTS::materialize(Building& building) {
586 if (definitions_ == nullptr || !building.definition()->id.isValid())
588 const std::size_t weaponCount = weapons_.size();
589 ArchetypeWeaponFactory factory = [this](std::string_view definitionId,
590 PersistentId instanceId) -> Result<weapon::WeaponEntity*> {
591 auto runtime = weapon::WeaponDefinitionRuntime::create(*definitions_, definitionId, instanceId);
592 if (!runtime) return Result<weapon::WeaponEntity*>::failure(runtime.status());
594 if (entity == nullptr)
596 Diagnostic::error(DiagnosticCode::Failed, "ECS failed to create an RTS weapon instance", "weapon"));
597 auto applied = runtime.value().applyTo(entity);
598 if (!applied) {
599 const Status status = applied.status();
600 entity->release();
602 }
603 weapons_.push_back(ecs::handle_of(entity));
605 };
606 auto applied = RTSArchetypeMaterializer::apply(*definitions_, building, factory);
607 if (!applied) {
608 while (weapons_.size() > weaponCount) {
609 if (auto* entity = dynamic_cast<weapon::WeaponEntity*>(ecs::try_get(weapons_.back()))) entity->release();
610 weapons_.pop_back();
611 }
612 }
613 return applied;
614}
615
617 if (!owns(factions_, faction))
619 Diagnostic::error(DiagnosticCode::StaleHandle, "RTS Faction does not belong to this facade", "faction"));
620 auto created = newUnit(subject, std::move(definition));
621 if (!created) return created;
622 Unit* unit = std::move(created).takeValue();
623 const std::size_t weaponCount = weapons_.size();
624 const auto rollbackWeapons = [this, weaponCount]() {
625 while (weapons_.size() > weaponCount) {
626 if (auto* weapon = dynamic_cast<weapon::WeaponEntity*>(ecs::try_get(weapons_.back()))) weapon->release();
627 weapons_.pop_back();
628 }
629 };
630 auto archetype = materialize(*unit);
631 if (!archetype) {
632 const Status status = archetype.status();
633 unit->release();
634 units_.pop_back();
635 rollbackWeapons();
637 }
638 auto link = FactionLink::bind(ecs::handle_of(&faction));
639 if (!link) {
640 const Status status = link.status();
641 unit->release();
642 units_.pop_back();
643 rollbackWeapons();
645 }
646 unit->faction()->link = std::move(link).takeValue();
647 faction.members()->units.push_back(ecs::handle_of(unit));
648 if (scriptRuntime_ && scriptRuntime_->configured) {
649 const std::string key = unit->identity()->subject.format();
650 auto crowdLink = CrowdLink::bind(key);
651 auto sensingLink = SensingLink::bind(key);
652 if (!crowdLink || !sensingLink) {
653 const Status status = !crowdLink ? crowdLink.status() : sensingLink.status();
654 faction.members()->units.pop_back();
655 unit->release();
656 units_.pop_back();
657 rollbackWeapons();
659 }
660 unit->crowd()->link = std::move(crowdLink).takeValue();
661 unit->sensing()->link = std::move(sensingLink).takeValue();
662 }
664}
665
667 if (!owns(factions_, faction))
669 Diagnostic::error(DiagnosticCode::StaleHandle, "RTS Faction does not belong to this facade", "faction"));
670 auto created = newBuilding(subject, std::move(definition));
671 if (!created) return created;
672 Building* building = std::move(created).takeValue();
673 const std::size_t weaponCount = weapons_.size();
674 const auto rollbackWeapons = [this, weaponCount]() {
675 while (weapons_.size() > weaponCount) {
676 if (auto* weapon = dynamic_cast<weapon::WeaponEntity*>(ecs::try_get(weapons_.back()))) weapon->release();
677 weapons_.pop_back();
678 }
679 };
680 auto archetype = materialize(*building);
681 if (!archetype) {
682 const Status status = archetype.status();
683 building->release();
684 buildings_.pop_back();
685 rollbackWeapons();
687 }
688 auto link = FactionLink::bind(ecs::handle_of(&faction));
689 if (!link) {
690 const Status status = link.status();
691 building->release();
692 buildings_.pop_back();
693 rollbackWeapons();
695 }
696 building->faction()->link = std::move(link).takeValue();
697 faction.members()->buildings.push_back(ecs::handle_of(building));
699}
700
702 if (!validSubject(subject))
704 Diagnostic::error(DiagnosticCode::InvalidArgument, "RTS Match requires a valid SubjectRef", "subject"));
705 if (ownsSubject(subject, SubjectClaimScope::LiveOrReserved))
707 Diagnostic::error(DiagnosticCode::Conflict, "RTS SubjectRef is already owned by this module", "subject"));
709 if (match == nullptr)
711 Diagnostic::error(DiagnosticCode::Failed, "ECS failed to create an RTS Match", "match"));
712 matches_.push_back(ecs::handle_of(match));
714}
715
716Result<void> RTS::configureMatch(Match& match, VictoryRule rule, std::string archetype, double targetValue) const {
717 if (!owns(matches_, match))
719 "RTS match is not owned by this composition root", "match"));
720 if (match.state()->phase != MatchPhase::Setup)
722 Diagnostic::error(DiagnosticCode::Conflict, "RTS match rules are immutable after start", "match.phase"));
723 if (rule == VictoryRule::DestroyHeadquarters && archetype.empty())
725 "RTS headquarters victory requires an archetype", "archetype"));
726 if (rule == VictoryRule::ResourceTarget && (archetype.empty() || !std::isfinite(targetValue) || targetValue <= 0.0))
728 "RTS resource victory requires a resource and positive target",
729 "targetValue"));
730 if (rule == VictoryRule::ScoreTarget && (!std::isfinite(targetValue) || targetValue <= 0.0))
732 "RTS score victory requires a positive target", "targetValue"));
733 if (match.rules()->suddenDeath && (rule == VictoryRule::ScoreTarget || rule == VictoryRule::ResourceTarget ||
734 rule == VictoryRule::Mission))
737 "RTS sudden death applies only to annihilation or headquarters victory", "rules.suddenDeath"));
738 match.rules()->rule = rule;
739 match.rules()->archetype = std::move(archetype);
740 match.rules()->targetValue = targetValue;
742}
743
744Result<void> RTS::configureMatchTiming(Match& match, Duration timeLimit, bool suddenDeath) const {
745 if (!owns(matches_, match))
747 "RTS match is not owned by this composition root", "match"));
748 if (match.state()->phase != MatchPhase::Setup)
750 Diagnostic::error(DiagnosticCode::Conflict, "RTS match timing is immutable after start", "match.phase"));
751 if (timeLimit.nanoseconds() < 0)
753 "RTS match time limit cannot be negative", "timeLimit"));
754 if (suddenDeath && timeLimit.isZero())
756 DiagnosticCode::InvalidArgument, "RTS sudden death requires a positive time limit", "suddenDeath"));
757 if (suddenDeath && (match.rules()->rule == VictoryRule::ScoreTarget ||
758 match.rules()->rule == VictoryRule::ResourceTarget ||
759 match.rules()->rule == VictoryRule::Mission))
762 "RTS sudden death applies only to annihilation or headquarters victory", "suddenDeath"));
763 match.rules()->timeLimit = timeLimit;
764 match.rules()->suddenDeath = suddenDeath;
766}
767
768Result<void> RTS::addMatchParticipant(Match& match, Faction& faction, int team) const {
769 if (!owns(matches_, match) || findFaction(faction.identity()->subject) != &faction)
771 DiagnosticCode::InvalidArgument, "RTS match and faction must share this composition root", "participant"));
772 return MatchSystem::addParticipant(match, faction, team);
773}
774
776 if (!owns(matches_, match))
778 "RTS match is not owned by this composition root", "match"));
779 return MatchSystem::addObjective(match, std::move(objective));
780}
781
783 if (!owns(matches_, match))
785 "RTS match is not owned by this composition root", "match"));
786 return MissionScriptSystem::addTrigger(match, std::move(trigger));
787}
788
790 if (!owns(matches_, match))
792 "RTS match is not owned by this composition root", "match"));
793 return MissionScriptSystem::addMonitor(match, std::move(monitor));
794}
795
797 if (!owns(matches_, match))
799 "RTS match is not owned by this composition root", "match"));
800 return MissionScriptSystem::addTimer(match, std::move(timer));
801}
802
803Result<void> RTS::setMatchVariable(Match& match, std::string id, double value) const {
804 if (!owns(matches_, match))
806 "RTS match is not owned by this composition root", "match"));
807 return MissionScriptSystem::setVariable(match, std::move(id), value);
808}
809
811 if (!owns(matches_, match))
813 "RTS match is not owned by this composition root", "match"));
814 return MissionScriptSystem::pushEvent(match, std::move(event));
815}
816
818 if (!owns(matches_, match))
820 "RTS match is not owned by this composition root", "match"));
822}
823
825 if (!owns(matches_, match))
827 "RTS match is not owned by this composition root", "match"));
828 return MatchSystem::start(match);
829}
830
832 if (!owns(matches_, match) || findFaction(faction.identity()->subject) != &faction)
834 DiagnosticCode::InvalidArgument, "RTS match and faction must share this composition root", "participant"));
835 return MatchSystem::surrender(match, faction);
836}
837
838Result<void> RTS::creditMatchScore(Match& match, int team, double amount) const {
839 if (!owns(matches_, match))
841 "RTS match is not owned by this composition root", "match"));
842 return MatchSystem::creditScore(match, team, amount);
843}
844
846 if (!owns(matches_, match))
848 "RTS match is not owned by this composition root", "match"));
849 const auto phase = match.state()->phase == MatchPhase::Setup ? "setup"
850 : match.state()->phase == MatchPhase::Running ? "running"
851 : "finished";
852 const char* ruleName = "annihilation";
853 switch (match.rules()->rule) {
854 case VictoryRule::DestroyHeadquarters: ruleName = "headquarters"; break;
855 case VictoryRule::ResourceTarget: ruleName = "resource"; break;
856 case VictoryRule::ScoreTarget: ruleName = "score"; break;
857 case VictoryRule::Mission: ruleName = "mission"; break;
858 case VictoryRule::Annihilation: break;
859 }
860 Value::Array participants;
861 for (auto& entry : match.participants()->entries) {
862 auto* faction = dynamic_cast<Faction*>(entry.faction.resolve());
863 participants.emplace_back(
864 Value::Object{{"faction", faction == nullptr ? std::string{} : faction->identity()->subject.format()},
865 {"team", entry.team},
866 {"eliminated", entry.eliminated},
867 {"surrendered", entry.surrendered},
868 {"reason", entry.reason}});
869 }
870 Value::Array scores;
871 for (const auto& entry : match.scores()->entries)
872 scores.emplace_back(Value::Object{{"team", entry.team}, {"value", entry.value}});
874 for (const auto& objective : match.objectives()->values) {
875 const char* kindName = "eliminate";
876 switch (objective.spec.kind) {
877 case MissionObjectiveKind::DestroyBuilding: kindName = "destroy_building"; break;
878 case MissionObjectiveKind::SurviveDuration: kindName = "survive"; break;
879 case MissionObjectiveKind::ProtectSubjects: kindName = "protect"; break;
880 case MissionObjectiveKind::OccupyBuildings: kindName = "occupy"; break;
881 case MissionObjectiveKind::ReachScore: kindName = "reach_score"; break;
882 case MissionObjectiveKind::ReachResource: kindName = "reach_resource"; break;
883 case MissionObjectiveKind::EliminateFaction: break;
884 }
885 const char* statusName = objective.status == MissionObjectiveStatus::Completed ? "completed"
886 : objective.status == MissionObjectiveStatus::Failed ? "failed"
887 : "pending";
888 Value::Array subjects;
889 for (const auto& subject : objective.spec.requiredSubjects) subjects.emplace_back(subject.format());
890 objectives.emplace_back(Value::Object{
891 {"id", objective.spec.id},
892 {"kind", kindName},
893 {"status", statusName},
894 {"beneficiaryTeam", objective.spec.beneficiaryTeam},
895 {"targetFaction", objective.spec.targetFaction.isValid() ? objective.spec.targetFaction.format()
896 : std::string{}},
897 {"targetSubject", objective.spec.targetSubject.isValid() ? objective.spec.targetSubject.format()
898 : std::string{}},
899 {"archetype", objective.spec.archetype},
900 {"resourceType", objective.spec.resourceType},
901 {"requiredDuration", objective.spec.requiredDuration.seconds()},
902 {"targetValue", objective.spec.targetValue},
903 {"requiredSubjects", Value(std::move(subjects))},
904 {"endsMatch", objective.spec.endsMatch},
905 {"failsMatch", objective.spec.failsMatch}});
906 }
908 for (const auto& event : match.events()->values)
909 events.emplace_back(Value::Object{{"sequence", static_cast<std::int64_t>(event.sequence)},
910 {"kind", event.kind},
911 {"faction", event.faction.isValid() ? event.faction.format() : std::string{}},
912 {"team", event.team},
913 {"reason", event.reason}});
914 Value::Array triggers;
915 for (const auto& trigger : match.campaign()->triggers)
916 triggers.emplace_back(Value::Object{{"id", trigger.id},
917 {"enabled", trigger.enabled},
918 {"once", trigger.once},
919 {"priority", trigger.priority},
920 {"fired", trigger.fired},
921 {"eventCount", static_cast<std::int64_t>(trigger.events.size())},
922 {"actionCount", static_cast<std::int64_t>(trigger.actions.size())}});
923 Value::Array monitors;
924 for (const auto& monitor : match.campaign()->monitors) {
925 Value::Array occupants;
926 for (const auto& subject : monitor.occupants) occupants.emplace_back(subject.format());
927 monitors.emplace_back(Value::Object{{"id", monitor.id},
928 {"enabled", monitor.enabled},
929 {"minX", static_cast<double>(monitor.minX)},
930 {"minY", static_cast<double>(monitor.minY)},
931 {"maxX", static_cast<double>(monitor.maxX)},
932 {"maxY", static_cast<double>(monitor.maxY)},
933 {"occupants", Value(std::move(occupants))}});
934 }
935 Value::Array timers;
936 for (const auto& timer : match.campaign()->timers)
937 timers.emplace_back(Value::Object{{"id", timer.id},
938 {"duration", timer.duration.seconds()},
939 {"elapsed", timer.elapsed.seconds()},
940 {"running", timer.running},
941 {"repeating", timer.repeating}});
943 for (const auto& variable : match.campaign()->variables)
944 variables.emplace_back(Value::Object{{"id", variable.id}, {"value", variable.value}});
945 Value::Array campaignActions;
946 for (const auto& action : match.campaign()->actions)
947 campaignActions.emplace_back(Value::Object{{"sequence", static_cast<std::int64_t>(action.sequence)},
948 {"tick", static_cast<std::int64_t>(action.tick)},
949 {"triggerId", action.triggerId},
950 {"kind", action.kind},
951 {"targetId", action.targetId},
952 {"numeric", action.numeric},
953 {"args", action.args}});
955 Value(Value::Object{{"subject", match.identity()->subject.format()},
956 {"phase", phase},
957 {"winningTeam", match.state()->winningTeam},
958 {"rule", static_cast<std::int64_t>(match.rules()->rule)},
959 {"ruleName", ruleName},
960 {"archetype", match.rules()->archetype},
961 {"target", match.rules()->targetValue},
962 {"timeLimit", match.rules()->timeLimit.seconds()},
963 {"suddenDeath", match.rules()->suddenDeath},
964 {"elapsed", match.state()->elapsed.seconds()},
965 {"suddenDeathActive", match.state()->suddenDeathActive},
966 {"scores", Value(std::move(scores))},
967 {"objectives", Value(std::move(objectives))},
968 {"participants", Value(std::move(participants))},
969 {"events", Value(std::move(events))},
970 {"triggers", Value(std::move(triggers))},
971 {"monitors", Value(std::move(monitors))},
972 {"timers", Value(std::move(timers))},
973 {"variables", Value(std::move(variables))},
974 {"campaignActions", Value(std::move(campaignActions))}}),
976}
977
978Unit* RTS::findUnit(SubjectRef subject) const noexcept { return findSubject<Unit>(units_, subject); }
979
980Building* RTS::findBuilding(SubjectRef subject) const noexcept { return findSubject<Building>(buildings_, subject); }
981
982ResourceNode* RTS::findResourceNode(SubjectRef subject) const noexcept {
983 return findSubject<ResourceNode>(resourceNodes_, subject);
984}
985
986bool RTS::ownsSubject(SubjectRef subject, SubjectClaimScope scope) const noexcept {
987 if (scope == SubjectClaimScope::LiveOrReserved && scriptRuntime_ &&
988 std::any_of(scriptRuntime_->pendingProductionSubjects.begin(), scriptRuntime_->pendingProductionSubjects.end(),
989 [subject](const auto& entry) { return entry.second == subject; }))
990 return true;
991 return findSubject<Unit>(units_, subject) != nullptr || findSubject<Building>(buildings_, subject) != nullptr ||
992 findSubject<ResourceNode>(resourceNodes_, subject) != nullptr ||
993 findSubject<Player>(players_, subject) != nullptr || findSubject<Faction>(factions_, subject) != nullptr ||
994 findSubject<Match>(matches_, subject) != nullptr;
995}
996
997Result<void> RTS::setUnitStance(std::span<const SubjectRef> subjects, CombatStance stance, float leashRange) const {
998 if (stance != CombatStance::Passive && stance != CombatStance::Defensive && stance != CombatStance::Aggressive)
1000 Diagnostic::error(DiagnosticCode::InvalidArgument, "RTS combat stance is invalid", "stance"));
1001 if (!std::isfinite(leashRange) || leashRange < 0.0f)
1003 DiagnosticCode::InvalidArgument, "RTS combat leash range must be finite and non-negative", "leashRange"));
1004 std::vector<Unit*> units;
1005 units.reserve(subjects.size());
1006 for (std::size_t index = 0; index < subjects.size(); ++index) {
1007 auto* unit = findUnit(subjects[index]);
1008 if (unit == nullptr)
1010 "RTS stance unit identity was not found",
1011 "subjects[" + std::to_string(index) + "]"));
1012 units.push_back(unit);
1013 }
1014 for (auto* unit : units) {
1015 auto combat = unit->combat();
1016 combat->stance = stance;
1017 combat->leashRange = leashRange;
1018 combat->guardX = unit->motion()->x;
1019 combat->guardY = unit->motion()->y;
1020 combat->guardSet = true;
1021 if (stance == CombatStance::Passive && unit->orders()->values.orderCount() == 0) combat->target = {};
1022 }
1024}
1025
1026Result<void> RTS::setUnitMovementPriority(std::span<const SubjectRef> subjects, int priority) const {
1027 std::vector<Unit*> units;
1028 units.reserve(subjects.size());
1029 for (std::size_t index = 0; index < subjects.size(); ++index) {
1030 auto* unit = findUnit(subjects[index]);
1031 if (unit == nullptr)
1033 "RTS movement-priority unit identity was not found",
1034 "subjects[" + std::to_string(index) + "]"));
1035 units.push_back(unit);
1036 }
1037 const int clamped = std::clamp(priority, -100, 100);
1038 for (auto* unit : units) unit->navigation()->movementPriority = clamped;
1040}
1041
1042Result<void> RTS::assignWorker(Unit& worker, ResourceNode& node, Building& dropoff) const {
1043 if (!owns(units_, worker) || !owns(resourceNodes_, node) || !owns(buildings_, dropoff))
1045 DiagnosticCode::StaleHandle, "RTS worker assignment requires roots owned by this facade", "assignment"));
1046 if (!worker.durability()->alive || worker.durability()->state.health <= 0.0)
1047 return Result<void>::failure(Diagnostic::error(DiagnosticCode::Conflict, "RTS worker must be alive", "worker"));
1048 if (worker.worker()->capacity <= 0.0f || worker.worker()->gatherRate <= 0.0f ||
1049 worker.worker()->resourceType.empty())
1050 return Result<void>::failure(
1051 Diagnostic::error(DiagnosticCode::Conflict, "RTS unit is not configured as a resource worker", "worker"));
1052 if ((!node.stock()->infinite && node.stock()->remaining <= 0.0f) ||
1053 node.stock()->resourceType != worker.worker()->resourceType)
1055 DiagnosticCode::Conflict, "RTS resource node is depleted or incompatible with the worker", "node"));
1056 if (!dropoff.integrity()->alive || dropoff.construction()->progress < 1.0f ||
1057 worker.faction()->link.resolve() == nullptr ||
1058 worker.faction()->link.resolve() != dropoff.faction()->link.resolve() ||
1059 std::find(dropoff.dropoff()->acceptedResources.begin(), dropoff.dropoff()->acceptedResources.end(),
1060 worker.worker()->resourceType) == dropoff.dropoff()->acceptedResources.end())
1062 DiagnosticCode::Conflict, "RTS dropoff must be completed, friendly, and accept the resource", "dropoff"));
1063
1064 auto& assigned = node.harvest()->workers;
1065 std::erase_if(assigned, [](const ecs::EntityHandle& handle) { return tryGetCurrent<Unit>(handle) == nullptr; });
1066 const auto workerHandle = ecs::handle_of(&worker);
1067 const bool alreadyAssigned = std::any_of(assigned.begin(), assigned.end(),
1068 [&](const auto& handle) { return sameHandle(handle, workerHandle); });
1069 if (!alreadyAssigned && assigned.size() >= node.harvest()->capacity)
1070 return Result<void>::failure(
1071 Diagnostic::error(DiagnosticCode::Conflict, "RTS resource node worker capacity is full", "node"));
1072
1073 auto nodeLink = ResourceNodeLink::bind(ecs::handle_of(&node));
1074 if (!nodeLink) return Result<void>::failure(nodeLink.status());
1075 auto dropoffLink = BuildingLink::bind(ecs::handle_of(&dropoff));
1076 if (!dropoffLink) return Result<void>::failure(dropoffLink.status());
1077 CommandSpec command;
1078 command.kind = OrderKind::Gather;
1079 command.target = {node.position()->x, node.position()->y};
1080 command.targetEntity = ecs::handle_of(&node);
1081 auto ordered = worker.orders()->values.replace(command);
1082 if (!ordered) return Result<void>::failure(ordered.status());
1083 std::move(ordered).takeValue();
1084
1085 if (auto* previous = dynamic_cast<ResourceNode*>(worker.worker()->resourceNode.resolve());
1086 previous != nullptr && previous != &node) {
1087 std::erase_if(previous->harvest()->workers,
1088 [&](const auto& handle) { return sameHandle(handle, workerHandle); });
1089 }
1090 if (!alreadyAssigned) assigned.push_back(workerHandle);
1091 worker.worker()->resourceNode = std::move(nodeLink).takeValue();
1092 worker.worker()->dropoff = std::move(dropoffLink).takeValue();
1094}
1095
1096Result<void> RTS::setWorkerAutoAssignment(std::span<const SubjectRef> subjects, bool enabled) const {
1097 std::vector<Unit*> workers;
1098 workers.reserve(subjects.size());
1099 for (std::size_t index = 0; index < subjects.size(); ++index) {
1100 auto* unit = findUnit(subjects[index]);
1101 if (unit == nullptr)
1103 "RTS auto-assignment unit identity was not found",
1104 "subjects[" + std::to_string(index) + "]"));
1105 if (unit->worker()->capacity <= 0.0f || unit->worker()->gatherRate <= 0.0f ||
1106 unit->worker()->resourceType.empty())
1108 "RTS auto-assignment target is not a resource worker",
1109 "subjects[" + std::to_string(index) + "]"));
1110 workers.push_back(unit);
1111 }
1112 for (auto* worker : workers) worker->worker()->autoAssign = enabled;
1114}
1115
1116Result<void> RTS::configureWorkforce(Faction& faction, bool autoConstruction, int maxBuildersPerSite, bool autoRepair,
1117 int maxRepairersPerBuilding, int reserveWorkers) const {
1118 if (!owns(factions_, faction))
1120 DiagnosticCode::StaleHandle, "RTS workforce faction does not belong to this facade", "faction"));
1121 if (maxBuildersPerSite <= 0 || maxRepairersPerBuilding <= 0 || reserveWorkers < 0)
1122 return Result<void>::failure(
1124 "RTS workforce limits must be positive and reserve workers non-negative", "workforce"));
1125 auto workforce = faction.workforce();
1126 workforce->autoConstruction = autoConstruction;
1127 workforce->autoRepair = autoRepair;
1128 workforce->maxBuildersPerSite = static_cast<std::size_t>(maxBuildersPerSite);
1129 workforce->maxRepairersPerBuilding = static_cast<std::size_t>(maxRepairersPerBuilding);
1130 workforce->reserveWorkers = static_cast<std::size_t>(reserveWorkers);
1132}
1133
1134Result<std::string> RTS::assignBuilder(Unit& worker, Building& building) const {
1135 if (!owns(units_, worker) || !owns(buildings_, building))
1137 DiagnosticCode::StaleHandle, "RTS builder assignment requires roots owned by this facade", "assignment"));
1138 if (!worker.durability()->alive || worker.containment()->container.isBound() || worker.worker()->buildRate <= 0.0f)
1140 DiagnosticCode::Conflict, "RTS builder must be alive, deployed, and construction-capable", "worker"));
1141 if (!building.integrity()->alive || building.construction()->progress >= 1.0f || building.construction()->paused)
1143 DiagnosticCode::Conflict, "RTS construction target must be alive, unfinished, and active", "building"));
1144 if (worker.faction()->link.resolve() == nullptr ||
1145 worker.faction()->link.resolve() != building.faction()->link.resolve())
1147 DiagnosticCode::Conflict, "RTS builder and construction target must share a faction", "assignment"));
1148 CommandSpec command;
1149 command.kind = OrderKind::Build;
1150 command.target = {building.placement()->worldX, building.placement()->worldY};
1151 command.targetEntity = building.identity()->self;
1152 auto ordered = worker.orders()->values.replace(command);
1153 if (!ordered) return Result<std::string>::failure(ordered.status());
1154 return ordered;
1155}
1156
1157Result<int> RTS::addUnitReserveAmmo(Unit& unit, int rounds) const {
1158 if (!owns(units_, unit))
1160 DiagnosticCode::StaleHandle, "RTS reserve-ammunition unit does not belong to this facade", "unit"));
1161 if (!unit.durability()->alive)
1162 return Result<int>::failure(
1163 Diagnostic::error(DiagnosticCode::Conflict, "RTS reserve-ammunition unit must be alive", "unit"));
1164 auto* weaponEntity = dynamic_cast<weapon::WeaponEntity*>(unit.weapon()->link.resolve());
1165 if (weaponEntity == nullptr)
1166 return Result<int>::failure(
1167 Diagnostic::error(DiagnosticCode::NotFound, "RTS unit has no canonical weapon", "unit.weapon"));
1168 auto& resource = weaponEntity->state()->resource;
1169 if (resource.kind != weapon::ResourceKind::Ammo || resource.infinite)
1171 DiagnosticCode::Conflict, "RTS unit weapon has no finite reserve ammunition", "unit.weapon.resource"));
1172 if (auto* pool = weaponEntity->state()->ammoPool) {
1173 if (pool->state()->max < 0)
1175 DiagnosticCode::Conflict, "RTS unit weapon ammunition pool is infinite", "unit.weapon.ammoPool"));
1176 const long long adjusted = static_cast<long long>(pool->state()->count) + rounds;
1177 pool->state()->count = static_cast<int>(std::clamp<long long>(adjusted, 0, pool->state()->max));
1178 return Result<int>::success(pool->state()->count, Status::success(StatusCode::Applied));
1179 }
1180 if (resource.reserve < 0)
1182 "RTS unit weapon reserve ammunition is infinite",
1183 "unit.weapon.resource.reserve"));
1184 const auto* definition = weaponEntity->definition()->def;
1185 const int capacity = std::max(resource.reserve, definition == nullptr ? resource.reserve : definition->reserveSize);
1186 const long long adjusted = static_cast<long long>(resource.reserve) + rounds;
1187 resource.reserve = static_cast<int>(std::clamp<long long>(adjusted, 0, capacity));
1189}
1190
1191Result<float> RTS::addUnitAmmoSupply(Unit& unit, float rounds) const {
1192 if (!owns(units_, unit))
1194 DiagnosticCode::StaleHandle, "RTS ammunition-supply unit does not belong to this facade", "unit"));
1195 if (!unit.durability()->alive)
1197 Diagnostic::error(DiagnosticCode::Conflict, "RTS ammunition-supply unit must be alive", "unit"));
1198 if (!std::isfinite(rounds))
1200 "RTS ammunition supply adjustment must be finite", "rounds"));
1201 auto supply = unit.supply();
1202 supply->stock = std::clamp(supply->stock + rounds, 0.0f, std::max(0.0f, supply->capacity));
1204}
1205
1206Result<float> RTS::addBuildingAmmoSupply(Building& building, float rounds) const {
1207 if (!owns(buildings_, building))
1209 DiagnosticCode::StaleHandle, "RTS ammunition-supply building does not belong to this facade", "building"));
1210 if (!building.integrity()->alive)
1212 Diagnostic::error(DiagnosticCode::Conflict, "RTS ammunition-supply building must be alive", "building"));
1213 if (!std::isfinite(rounds))
1215 "RTS ammunition supply adjustment must be finite", "rounds"));
1216 auto supply = building.supply();
1217 supply->stock = std::clamp(supply->stock + rounds, 0.0f, std::max(0.0f, supply->capacity));
1219}
1220
1221Result<void> RTS::setUnitAutoResupply(Unit& unit, bool enabled) const {
1222 if (!owns(units_, unit))
1224 DiagnosticCode::StaleHandle, "RTS automatic-resupply unit does not belong to this facade", "unit"));
1225 if (!unit.durability()->alive)
1226 return Result<void>::failure(
1227 Diagnostic::error(DiagnosticCode::Conflict, "RTS automatic-resupply unit must be alive", "unit"));
1228 auto supply = unit.supply();
1229 supply->autoDispatch = enabled;
1231 auto current = unit.orders()->values.current();
1232 if (current && (current.value().kind == OrderKind::Resupply || current.value().kind == OrderKind::SupplyRelay)) {
1233 auto cancelled = unit.orders()->values.cancel(current.value().id, "automatic resupply disabled");
1234 if (!cancelled) return cancelled;
1235 supply->assignedTarget = {};
1236 supply->reservedStock = 0.0f;
1237 supply->returning = false;
1238 supply->rendezvousActive = false;
1239 supply->convoyWaiting = false;
1240 supply->convoyLeader = {};
1241 auto navigation = unit.navigation();
1242 navigation->waypoints.clear();
1243 navigation->waypointIndex = 0;
1244 navigation->plannedOrderId.clear();
1245 navigation->unreachable = false;
1246 navigation->unreachableReported = false;
1247 unit.motion()->arrived = true;
1248 }
1250}
1251
1252Result<FanOutReceipt> RTS::suppressArea(std::span<const SubjectRef> subjects, WorldPosition start, WorldPosition end,
1253 float width, int shotsPerUnit) const {
1254 if (!std::isfinite(start.x) || !std::isfinite(start.y) || !std::isfinite(end.x) || !std::isfinite(end.y) ||
1255 !std::isfinite(width) || width <= 0.0f || shotsPerUnit < 0 ||
1256 std::hypot(end.x - start.x, end.y - start.y) <= 1e-3f)
1259 "RTS suppression requires a non-degenerate corridor, positive width, and non-negative shots",
1260 "suppression"));
1261 std::vector<Unit*> units;
1262 units.reserve(subjects.size());
1263 for (std::size_t index = 0; index < subjects.size(); ++index) {
1264 auto* unit = findUnit(subjects[index]);
1265 if (unit == nullptr)
1267 "RTS suppression unit identity was not found",
1268 "subjects[" + std::to_string(index) + "]"));
1269 if (!unit->durability()->alive || unit->containment()->container.isBound() ||
1270 unit->weapon()->link.resolve() == nullptr)
1272 Diagnostic::error(DiagnosticCode::Conflict, "RTS suppression unit must be alive, deployed, and armed",
1273 "subjects[" + std::to_string(index) + "]"));
1274 units.push_back(unit);
1275 }
1276 CommandSpec command;
1277 command.kind = OrderKind::SuppressArea;
1278 command.target = start;
1279 command.secondaryTarget = end;
1280 command.radius = width;
1281 auto issued = commandUnits(subjects, command);
1282 if (!issued) return issued;
1283 for (auto* unit : units) {
1284 unit->artillery()->suppressionShotsRemaining = shotsPerUnit == 0 ? -1 : shotsPerUnit;
1285 unit->artillery()->fireSupportRequester = {};
1286 }
1287 return issued;
1288}
1289
1290Result<FanOutReceipt> RTS::escortUnits(std::span<const SubjectRef> subjects, SubjectRef protectedSubject,
1291 float guardRadius, float spacing) const {
1292 if (!std::isfinite(guardRadius) || !std::isfinite(spacing) || guardRadius <= 0.0f || spacing <= 0.0f)
1295 "RTS escort guard radius and spacing must be finite and positive", "escort"));
1296 ecs::Entity* protectedEntity = findUnit(protectedSubject);
1297 if (protectedEntity == nullptr) protectedEntity = findBuilding(protectedSubject);
1298 ecs::Entity* protectedFaction = nullptr;
1300 float protectedRadius = 0.0f;
1301 if (auto* unit = dynamic_cast<Unit*>(protectedEntity);
1302 unit != nullptr && unit->durability()->alive && !unit->containment()->container.isBound()) {
1303 protectedFaction = unit->faction()->link.resolve();
1304 center = {unit->motion()->x, unit->motion()->y};
1305 protectedRadius = unit->crowd()->radius;
1306 } else if (auto* building = dynamic_cast<Building*>(protectedEntity);
1307 building != nullptr && building->integrity()->alive) {
1308 protectedFaction = building->faction()->link.resolve();
1309 center = {building->placement()->worldX, building->placement()->worldY};
1310 } else {
1312 Diagnostic::error(DiagnosticCode::NotFound, "RTS escort target must be a live deployed unit or building",
1313 "protectedSubject"));
1314 }
1315 if (protectedFaction == nullptr)
1317 DiagnosticCode::Conflict, "RTS escort target must have an owning faction", "protectedSubject"));
1318
1319 std::vector<Unit*> escorts;
1320 escorts.reserve(subjects.size());
1321 for (std::size_t index = 0; index < subjects.size(); ++index) {
1322 auto* unit = findUnit(subjects[index]);
1323 if (unit == nullptr)
1325 "RTS escort unit identity was not found",
1326 "subjects[" + std::to_string(index) + "]"));
1327 if (unit == protectedEntity || !unit->durability()->alive || unit->containment()->container.isBound() ||
1328 !FactionRelationSystem::isAllied(dynamic_cast<Faction*>(unit->faction()->link.resolve()),
1329 dynamic_cast<Faction*>(protectedFaction)))
1332 "RTS escort units must be live, deployed, friendly, and distinct from the target",
1333 "subjects[" + std::to_string(index) + "]"));
1334 escorts.push_back(unit);
1335 }
1336 std::sort(escorts.begin(), escorts.end(), [](Unit* left, Unit* right) {
1337 return left->identity()->subject.format() < right->identity()->subject.format();
1338 });
1339 std::vector<SubjectRef> orderedSubjects;
1340 orderedSubjects.reserve(escorts.size());
1341 for (auto* unit : escorts) orderedSubjects.push_back(unit->identity()->subject);
1342 CommandSpec command;
1343 command.kind = OrderKind::Escort;
1344 command.target = center;
1345 command.targetEntity = ecs::handle_of(protectedEntity);
1346 auto issued = commandUnits(orderedSubjects, command);
1347 if (!issued) return issued;
1348 constexpr float tau = 2.0f * static_cast<float>(std::numbers::pi);
1349 for (std::size_t index = 0; index < escorts.size(); ++index) {
1350 const float angle = tau * static_cast<float>(index) / static_cast<float>(escorts.size());
1351 const float distance = protectedRadius + escorts[index]->crowd()->radius + spacing;
1352 escorts[index]->tactics()->escortOffsetX = std::cos(angle) * distance;
1353 escorts[index]->tactics()->escortOffsetY = std::sin(angle) * distance;
1354 escorts[index]->tactics()->protectionRange = guardRadius;
1355 escorts[index]->combat()->leashRange = guardRadius;
1356 }
1357 return issued;
1358}
1359
1360Value RTS::inspectState() const {
1362 for (const auto& handle : units_) {
1363 auto* unit = tryGetCurrent<Unit>(handle);
1364 if (unit == nullptr) continue;
1365 std::string faction;
1366 if (auto* owner = dynamic_cast<Faction*>(unit->faction()->link.resolve()); owner != nullptr)
1367 faction = owner->identity()->subject.format();
1368 std::string order = "idle";
1369 auto current = unit->orders()->values.current();
1370 if (current) order = orderKindName(std::move(current).takeValue().kind);
1371 auto* resourceNode = dynamic_cast<ResourceNode*>(unit->worker()->resourceNode.resolve());
1372 auto* dropoff = dynamic_cast<Building*>(unit->worker()->dropoff.resolve());
1373 int reserveAmmo = 0;
1374 int reserveAmmoCapacity = 0;
1375 if (auto* weaponEntity = dynamic_cast<weapon::WeaponEntity*>(unit->weapon()->link.resolve())) {
1376 const auto& resource = weaponEntity->state()->resource;
1377 if (resource.kind == weapon::ResourceKind::Ammo && !resource.infinite) {
1378 if (auto* pool = weaponEntity->state()->ammoPool) {
1379 reserveAmmo = pool->state()->count;
1380 reserveAmmoCapacity = pool->state()->max;
1381 } else {
1382 reserveAmmo = resource.reserve;
1383 reserveAmmoCapacity = weaponEntity->definition()->def == nullptr
1384 ? resource.reserve
1385 : weaponEntity->definition()->def->reserveSize;
1386 }
1387 }
1388 }
1389 units.emplace_back(Value::Object{
1390 {"subject", unit->identity()->subject.format()},
1391 {"definition", unit->definition()->id.format()},
1392 {"faction", std::move(faction)},
1393 {"x", unit->motion()->x},
1394 {"y", unit->motion()->y},
1395 {"airborne", unit->motion()->airborne},
1396 {"order", std::move(order)},
1397 {"queuedOrders", static_cast<std::int64_t>(unit->orders()->values.orderCount())},
1398 {"stance", combatStanceName(unit->combat()->stance)},
1399 {"leashRange", unit->combat()->leashRange},
1400 {"movementPriority", unit->navigation()->movementPriority},
1401 {"trafficWaiting", unit->navigation()->trafficWaiting},
1402 {"combatSlotWaiting", unit->navigation()->combatSlotWaiting},
1403 {"combatSlotActive", unit->navigation()->combatSlotTarget.has_value()},
1404 {"cloaked", unit->vision()->cloaked},
1405 {"health", unit->durability()->state.health},
1406 {"maxHealth", unit->durability()->state.maxHealth},
1407 {"shield", unit->shield()->value},
1408 {"maxShield", unit->shield()->capacity},
1409 {"experience", unit->veterancy()->experience},
1410 {"veterancyLevel", static_cast<std::int64_t>(unit->veterancy()->level)},
1411 {"activeEffects", static_cast<std::int64_t>(unit->effects()->values.count())},
1412 {"inCommand", unit->command()->inCommand},
1413 {"garrisoned", unit->containment()->container.resolve() != nullptr},
1414 {"resourceType", unit->worker()->resourceType},
1415 {"cargo", unit->worker()->cargo},
1416 {"cargoCapacity", unit->worker()->capacity},
1417 {"autoAssign", unit->worker()->autoAssign},
1418 {"resourceNode", resourceNode == nullptr ? std::string{} : resourceNode->identity()->subject.format()},
1419 {"dropoff", dropoff == nullptr ? std::string{} : dropoff->identity()->subject.format()},
1420 {"reserveAmmo", static_cast<std::int64_t>(reserveAmmo)},
1421 {"reserveAmmoCapacity", static_cast<std::int64_t>(reserveAmmoCapacity)},
1422 {"supplyStock", unit->supply()->stock},
1423 {"supplyCapacity", unit->supply()->capacity},
1424 {"autoResupply", unit->supply()->autoDispatch},
1425 {"reservedSupply", unit->supply()->reservedStock},
1426 {"supplyReturning", unit->supply()->returning},
1427 });
1428 }
1429
1430 Value::Array buildings;
1431 for (const auto& handle : buildings_) {
1432 auto* building = tryGetCurrent<Building>(handle);
1433 if (building == nullptr) continue;
1434 std::string faction;
1435 if (auto* owner = dynamic_cast<Faction*>(building->faction()->link.resolve()); owner != nullptr)
1436 faction = owner->identity()->subject.format();
1437 buildings.emplace_back(Value::Object{
1438 {"subject", building->identity()->subject.format()},
1439 {"definition", building->definition()->id.format()},
1440 {"faction", std::move(faction)},
1441 {"x", building->placement()->worldX},
1442 {"y", building->placement()->worldY},
1443 {"complete", building->construction()->progress >= 1.0f},
1444 {"progress", building->construction()->progress},
1445 {"powered", building->infrastructure()->powered},
1446 {"productionQueue", static_cast<std::int64_t>(building->production()->values.taskCount())},
1447 {"health", building->integrity()->state.health},
1448 {"maxHealth", building->integrity()->state.maxHealth},
1449 {"shield", building->shield()->value},
1450 {"maxShield", building->shield()->capacity},
1451 {"activeEffects", static_cast<std::int64_t>(building->effects()->values.count())},
1452 {"supplyStock", building->supply()->stock},
1453 {"supplyCapacity", building->supply()->capacity},
1454 });
1455 }
1456
1457 Value::Array resourceNodes;
1458 for (const auto& handle : resourceNodes_) {
1459 auto* node = tryGetCurrent<ResourceNode>(handle);
1460 if (node == nullptr) continue;
1461 resourceNodes.emplace_back(Value::Object{
1462 {"subject", node->identity()->subject.format()},
1463 {"resource", node->stock()->resourceType},
1464 {"remaining", node->stock()->remaining},
1465 {"maximum", node->stock()->maximum},
1466 {"x", node->position()->x},
1467 {"y", node->position()->y},
1468 {"capacity", static_cast<std::int64_t>(node->harvest()->capacity)},
1469 {"workers", static_cast<std::int64_t>(node->harvest()->workers.size())},
1470 });
1471 }
1472
1473 Value::Array factions;
1474 auto* currentTable = ecs::current();
1475 for (const auto& handle : factions_) {
1476 if (handle.table != currentTable) continue;
1477 auto* faction = tryGetCurrent<Faction>(handle);
1478 if (faction == nullptr) continue;
1479 factions.emplace_back(Value::Object{
1480 {"subject", faction->identity()->subject.format()},
1481 {"displayName", faction->identity()->displayName},
1482 {"units", static_cast<std::int64_t>(faction->members()->units.size())},
1483 {"buildings", static_cast<std::int64_t>(faction->members()->buildings.size())},
1484 {"autoConstruction", faction->workforce()->autoConstruction},
1485 {"autoRepair", faction->workforce()->autoRepair},
1486 {"maxBuildersPerSite", static_cast<std::int64_t>(faction->workforce()->maxBuildersPerSite)},
1487 {"maxRepairersPerBuilding", static_cast<std::int64_t>(faction->workforce()->maxRepairersPerBuilding)},
1488 {"reserveWorkers", static_cast<std::int64_t>(faction->workforce()->reserveWorkers)},
1489 });
1490 }
1491
1492 return Value(Value::Object{
1493 {"units", Value(std::move(units))},
1494 {"buildings", Value(std::move(buildings))},
1495 {"resourceNodes", Value(std::move(resourceNodes))},
1496 {"factions", Value(std::move(factions))},
1497 });
1498}
1499
1500Value RTS::inspectFrameEvents() const {
1501 const auto channelName = [](DamageChannel channel) {
1502 switch (channel) {
1503 case DamageChannel::Ability: return "ability";
1504 case DamageChannel::Projectile: return "projectile";
1505 case DamageChannel::Weapon: return "weapon";
1506 }
1507 return "weapon";
1508 };
1509 const auto reactionName = [](combat::HitReaction reaction) {
1510 switch (reaction) {
1511 case combat::HitReaction::None: return "none";
1512 case combat::HitReaction::Flinch: return "flinch";
1513 case combat::HitReaction::Stagger: return "stagger";
1514 case combat::HitReaction::Knockdown: return "knockdown";
1515 case combat::HitReaction::Death: return "death";
1516 }
1517 return "none";
1518 };
1519 std::vector<std::pair<std::uint64_t, Value>> sequenced;
1520 sequenced.reserve(frameDamageEvents_.size() + frameCombatEvents_.size() + frameLifecycleEvents_.size());
1521 for (const auto& event : frameDamageEvents_) {
1522 sequenced.emplace_back(event.sequence, Value(Value::Object{
1523 {"type", "damage"},
1524 {"tick", static_cast<std::int64_t>(event.tick.value())},
1525 {"channel", channelName(event.channel)},
1526 {"source", event.outcome.source.format()},
1527 {"target", event.outcome.target.format()},
1528 {"damageType", event.request.damageType},
1529 {"previousHealth", event.outcome.previousHealth},
1530 {"health", event.outcome.health},
1531 {"appliedHealthDamage", event.outcome.appliedHealthDamage},
1532 {"appliedPoiseDamage", event.outcome.appliedPoiseDamage},
1533 {"reaction", reactionName(event.outcome.reaction)},
1534 {"killed", event.outcome.reaction == combat::HitReaction::Death},
1535 }));
1536 }
1537 const auto fireType = [](CombatFireEventKind kind) {
1538 switch (kind) {
1539 case CombatFireEventKind::WeaponFired: return "weapon_fired";
1540 case CombatFireEventKind::ProjectileFired: return "projectile_fired";
1541 case CombatFireEventKind::ShotMissed: return "shot_missed";
1542 case CombatFireEventKind::ReloadStarted: return "reload_started";
1543 case CombatFireEventKind::ReloadCompleted: return "reload_completed";
1544 case CombatFireEventKind::WeaponDry: return "weapon_dry";
1545 case CombatFireEventKind::FireBlocked: return "fire_blocked";
1546 }
1547 return "weapon_fired";
1548 };
1549 for (const auto& value : frameCombatEvents_)
1550 sequenced.emplace_back(value.sequence, Value(Value::Object{
1551 {"type", fireType(value.event.kind)},
1552 {"tick", static_cast<std::int64_t>(value.tick.value())},
1553 {"source", value.event.source.format()},
1554 {"target", value.event.target.format()},
1555 {"x", value.event.point.x},
1556 {"y", value.event.point.y},
1557 }));
1558 const auto lifecycleType = [](LifecycleEventKind kind) {
1559 switch (kind) {
1560 case LifecycleEventKind::SuppressionRecovered: return "suppression_recovered";
1561 case LifecycleEventKind::ShieldRecharged: return "shield_recharged";
1562 case LifecycleEventKind::ConstructionCompleted: return "construction_completed";
1563 case LifecycleEventKind::ProductionSpawnBlocked: return "production_spawn_blocked";
1564 case LifecycleEventKind::ProductionSpawnCleared: return "production_spawn_cleared";
1565 case LifecycleEventKind::UnitProduced: return "unit_produced";
1566 case LifecycleEventKind::BuildingCaptured: return "building_captured";
1567 case LifecycleEventKind::AbilityCast: return "ability_cast";
1568 case LifecycleEventKind::AbilityChannelStarted: return "ability_channel_started";
1569 case LifecycleEventKind::AbilityChannelTick: return "ability_channel_tick";
1570 case LifecycleEventKind::AbilityChannelCompleted: return "ability_channel_completed";
1571 case LifecycleEventKind::AbilityInterrupted: return "ability_interrupted";
1572 case LifecycleEventKind::AbilityChannelCancelled: return "ability_channel_cancelled";
1573 case LifecycleEventKind::StatusApplied: return "status_applied";
1574 case LifecycleEventKind::StatusExpired: return "status_expired";
1575 case LifecycleEventKind::AmmoProduced: return "ammo_produced";
1576 case LifecycleEventKind::SupplyDispatched: return "supply_dispatched";
1577 case LifecycleEventKind::SupplyRelayDispatched: return "supply_rendezvous_dispatched";
1578 case LifecycleEventKind::AmmoResupplied: return "ammo_resupplied";
1579 case LifecycleEventKind::SupplyRelayTransferred: return "supply_relay_transferred";
1580 case LifecycleEventKind::SupplyReturning: return "supply_returning";
1581 case LifecycleEventKind::SupplyReturned: return "supply_returned";
1582 }
1583 return "lifecycle";
1584 };
1585 for (const auto& value : frameLifecycleEvents_)
1586 sequenced.emplace_back(value.sequence, Value(Value::Object{
1587 {"type", lifecycleType(value.event.kind)},
1588 {"tick", static_cast<std::int64_t>(value.tick.value())},
1589 {"source", value.event.source.format()},
1590 {"target", value.event.target.format()},
1591 {"detail", value.event.detail},
1592 {"value", value.event.value},
1593 }));
1594 std::sort(sequenced.begin(), sequenced.end(),
1595 [](const auto& left, const auto& right) { return left.first < right.first; });
1597 events.reserve(sequenced.size());
1598 for (auto& [sequence, value] : sequenced) {
1599 (void)sequence;
1600 events.push_back(std::move(value));
1601 }
1602 return Value(std::move(events));
1603}
1604
1605void RTS::recordDamageEvent(const combat::DamageRequest& request, const combat::DamageOutcome& outcome,
1607 frameDamageEvents_.push_back({frameEventSequence_++, tick, channel, request, outcome});
1608}
1609
1610void RTS::recordCombatEvent(const CombatFireEvent& event, SimulationTick tick) {
1611 frameCombatEvents_.push_back({frameEventSequence_++, tick, event});
1612}
1613
1614void RTS::recordLifecycleEvent(const LifecycleEvent& event, SimulationTick tick) {
1615 frameLifecycleEvents_.push_back({frameEventSequence_++, tick, event});
1616}
1617
1618Result<double> RTS::readUnitAttribute(Unit& unit, std::string_view attribute) const {
1619 if (!owns(units_, unit))
1621 Diagnostic::error(DiagnosticCode::StaleHandle, "RTS Unit does not belong to this facade", "unit"));
1622 return RTSUnitAttributeAdapter::read(unit, attribute);
1623}
1624
1625Result<void> RTS::setUnitAttribute(Unit& unit, std::string_view attribute, double value) const {
1626 if (!owns(units_, unit))
1627 return Result<void>::failure(
1628 Diagnostic::error(DiagnosticCode::StaleHandle, "RTS Unit does not belong to this facade", "unit"));
1629 return RTSUnitAttributeAdapter::setBase(unit, attribute, value);
1630}
1631
1632Result<effects::EffectHandle> RTS::applyEffect(Unit& unit, const RTSEffectDefinition& definition) const {
1633 if (!owns(units_, unit))
1635 Diagnostic::error(DiagnosticCode::StaleHandle, "RTS Unit does not belong to this facade", "unit"));
1636 return unit.effects()->values.apply(definition);
1637}
1638
1639Result<effects::EffectHandle> RTS::applyEffect(Building& building, const RTSEffectDefinition& definition) const {
1640 if (!owns(buildings_, building))
1642 Diagnostic::error(DiagnosticCode::StaleHandle, "RTS Building does not belong to this facade", "building"));
1643 return building.effects()->values.apply(definition);
1644}
1645
1646Result<double> RTS::heal(SubjectRef source, SubjectRef target, double amount) const {
1647 if (!source.isValid() || !target.isValid() || !std::isfinite(amount) || amount <= 0.0)
1650 "RTS healing requires valid subjects and a finite positive amount", "healing"));
1651 if (!ownsSubject(source))
1653 Diagnostic::error(DiagnosticCode::NotFound, "RTS healing source was not found", "source"));
1654 combat::CombatState* state = nullptr;
1655 bool* alive = nullptr;
1656 if (auto* unit = findUnit(target)) {
1657 state = &unit->durability()->state;
1658 alive = &unit->durability()->alive;
1659 } else if (auto* building = findBuilding(target)) {
1660 state = &building->integrity()->state;
1661 alive = &building->integrity()->alive;
1662 } else {
1664 Diagnostic::error(DiagnosticCode::NotFound, "RTS healing target was not found", "target"));
1665 }
1666 if (!*alive || state->health <= 0.0)
1668 Diagnostic::error(DiagnosticCode::Conflict, "RTS healing target must be alive", "target"));
1669 auto valid = state->validate();
1670 if (!valid) return Result<double>::failure(valid.status());
1671 combat::DamageRuntime defaultSettlement;
1672 auto& settlement = damage_ != nullptr ? *damage_ : defaultSettlement;
1673 auto settled = settlement.heal(*state, source, amount);
1674 if (!settled) return Result<double>::failure(settled.status());
1675 const double applied = settled.value().applied;
1677}
1678
1680 double durationOverride) {
1681 if (definitions_ == nullptr)
1683 DiagnosticCode::Conflict, "RTS status effects require a definition registry", "definitions"));
1684 if (!ownsSubject(source))
1686 Diagnostic::error(DiagnosticCode::NotFound, "RTS status-effect source was not found", "source"));
1687 auto definition = resolveEffectDefinition(*definitions_, effect, source, durationOverride);
1688 if (!definition) return Result<effects::EffectHandle>::failure(definition.status());
1689 if (auto* unit = findUnit(target)) {
1690 if (!unit->durability()->alive)
1692 Diagnostic::error(DiagnosticCode::Conflict, "RTS status-effect target must be alive", "target"));
1693 auto applied = applyEffect(*unit, definition.value());
1694 if (applied)
1695 recordLifecycleEvent(
1696 {LifecycleEventKind::StatusApplied, source, target, effect, definition.value().duration},
1697 SimulationTick(scriptTick()));
1698 return applied;
1699 }
1700 if (auto* building = findBuilding(target)) {
1701 if (!building->integrity()->alive)
1703 Diagnostic::error(DiagnosticCode::Conflict, "RTS status-effect target must be alive", "target"));
1704 auto applied = applyEffect(*building, definition.value());
1705 if (applied)
1706 recordLifecycleEvent(
1707 {LifecycleEventKind::StatusApplied, source, target, effect, definition.value().duration},
1708 SimulationTick(scriptTick()));
1709 return applied;
1710 }
1712 Diagnostic::error(DiagnosticCode::NotFound, "RTS status-effect target was not found", "target"));
1713}
1714
1715Result<void> RTS::setProductionResourceReserve(Faction& faction, std::string resource, std::int64_t amount,
1716 int minimumPriority) {
1717 if (!owns(factions_, faction))
1718 return Result<void>::failure(
1719 Diagnostic::error(DiagnosticCode::StaleHandle, "RTS Faction does not belong to this facade", "faction"));
1720 if (resource.empty() || amount < 0)
1723 "RTS production resource reserve requires a resource and non-negative amount", "reserve"));
1724 if (amount == 0) {
1725 faction.productionPolicy()->resourceReserves.erase(resource);
1727 }
1729 if (!valid) return Result<void>::failure(valid.status());
1730 faction.productionPolicy()->resourceReserves[std::move(resource)] = {amount, minimumPriority};
1732}
1733
1735 std::string productionTaskId, std::string orderId,
1736 resource::CostSpec refund, std::string reason) {
1737 if (!owns(buildings_, building))
1739 Diagnostic::error(DiagnosticCode::StaleHandle, "RTS Building does not belong to this facade", "building"));
1740 return RTSProductionActionAdapter::cancel(building, account, std::move(productionTaskId), std::move(orderId),
1741 std::move(refund), std::move(reason));
1742}
1743
1744Result<std::size_t> RTS::step(const SimulationStep& simulationStep, IRTSActionExecutor& executor) {
1745 auto provider = checkCrowdLifetime();
1746 if (!provider) return Result<std::size_t>::failure(provider.status());
1747 if (crowdFlowNavigation_ && crowdFlowNavigation_->enabled() && !crowd_)
1749 "Shared-flow mode requires a Crowd provider",
1750 "crowdFlowNavigation"));
1751 if (crowd_) {
1752 auto admitted = crowd_->checkAdvanceClock({simulationStep.tick, simulationStep.delta, {}});
1753 if (!admitted) return Result<std::size_t>::failure(admitted.status());
1754 }
1755 auto surface = synchronizeCrowdSurface();
1756 if (!surface) return Result<std::size_t>::failure(surface.status());
1757 if (crowdFlowNavigation_ && crowdFlowNavigation_->enabled() && crowd_->getFieldStatus().surface.surface.isZero())
1760 "Shared-flow mode requires an imported movement projection", "crowdFlowNavigation"));
1761
1762 if (!preserveFrameEventsOnNextStep_) {
1763 frameDamageEvents_.clear();
1764 frameCombatEvents_.clear();
1765 frameLifecycleEvents_.clear();
1766 frameEventSequence_ = 0;
1767 }
1768 preserveFrameEventsOnNextStep_ = false;
1769 const DamageEventSink damageEvents =
1771 DamageChannel channel) { recordDamageEvent(request, outcome, tick, channel); };
1772 const CombatFireEventSink fireEvents = [this](const CombatFireEvent& event, SimulationTick tick) {
1773 recordCombatEvent(event, tick);
1774 };
1775 const LifecycleEventSink lifecycleEvents = [this](const LifecycleEvent& event, SimulationTick tick) {
1776 recordLifecycleEvent(event, tick);
1777 };
1778 auto assignments = WorkerAssignmentSystem::step();
1779 if (!assignments) return Result<std::size_t>::failure(assignments.status());
1780 std::size_t processed = std::move(assignments).takeValue();
1781
1782 auto workforce = WorkforceAssignmentSystem::step();
1783 if (!workforce) return Result<std::size_t>::failure(workforce.status());
1784 processed += std::move(workforce).takeValue();
1785
1786 auto ai = AISystem::step(simulationStep, aiProductionRequest_);
1787 if (!ai) return Result<std::size_t>::failure(ai.status());
1788 processed += std::move(ai).takeValue();
1789
1790 auto tactics = TacticsSystem::step(damage_, simulationStep);
1791 if (!tactics) return Result<std::size_t>::failure(tactics.status());
1792 processed += std::move(tactics).takeValue();
1793
1794 auto command = CommandNetworkSystem::step();
1795 if (!command) return Result<std::size_t>::failure(command.status());
1796 processed += std::move(command).takeValue();
1797
1798 auto commandState = CommandStateSystem::step();
1799 if (!commandState) return Result<std::size_t>::failure(commandState.status());
1800 processed += std::move(commandState).takeValue();
1801
1802 auto patrol = PatrolSystem::step();
1803 if (!patrol) return Result<std::size_t>::failure(patrol.status());
1804 processed += std::move(patrol).takeValue();
1805
1806 if (pathfinder_ != nullptr) {
1807 auto navigation = crowdFlowNavigation_ && crowdFlowNavigation_->enabled()
1808 ? NavigationSystem::stepSharedFlow(*pathfinder_, navigationGrid_, navigationEvent_)
1809 : NavigationSystem::step(*pathfinder_, navigationGrid_, navigationEvent_);
1810 if (!navigation) return Result<std::size_t>::failure(navigation.status());
1811 processed += std::move(navigation).takeValue();
1812 auto traffic = TrafficReservationSystem::step(*pathfinder_, navigationGrid_);
1813 if (!traffic) return Result<std::size_t>::failure(traffic.status());
1814 processed += std::move(traffic).takeValue();
1815 }
1816
1817 auto convoy = SupplyConvoySystem::step();
1818 if (!convoy) return Result<std::size_t>::failure(convoy.status());
1819 processed += std::move(convoy).takeValue();
1820
1821 auto movementGroups = stepMovementGroups();
1822 if (!movementGroups) return Result<std::size_t>::failure(movementGroups.status());
1823 processed += std::move(movementGroups).takeValue();
1824
1825 if (fogProvider_) {
1826 auto fog = FogOfWarSystem::step(simulationStep, navigationGrid_, fogState_, fogProvider_);
1827 if (!fog) return Result<std::size_t>::failure(fog.status());
1828 processed += std::move(fog).takeValue();
1829 }
1830
1831 auto attackSlots = stepAttackSlots();
1832 if (!attackSlots) return Result<std::size_t>::failure(attackSlots.status());
1833 processed += std::move(attackSlots).takeValue();
1834
1835 auto motion = MotionSystem::step(simulationStep);
1836 if (!motion) return Result<std::size_t>::failure(motion.status());
1837 processed += std::move(motion).takeValue();
1838
1839 if (crowd_ != nullptr) {
1840 EV_PROFILE_MODULE("rts", "RTS::crowdAdvancePhase");
1841 auto alive = checkCrowdLifetime();
1842 if (!alive) return Result<std::size_t>::failure(alive.status());
1843 auto crowdMotion = advanceCrowdMotion(simulationStep);
1844 if (!crowdMotion) return Result<std::size_t>::failure(crowdMotion.status());
1845 processed += std::move(crowdMotion).takeValue();
1846 }
1847
1848 auto movementOrders = MovementOrderSystem::step();
1849 if (!movementOrders) return Result<std::size_t>::failure(movementOrders.status());
1850 processed += std::move(movementOrders).takeValue();
1851
1852 auto containment = ContainmentSystem::step();
1853 if (!containment) return Result<std::size_t>::failure(containment.status());
1854 processed += std::move(containment).takeValue();
1855
1856 auto morale = MoraleSystem::step(simulationStep, lifecycleEvents);
1857 if (!morale) return Result<std::size_t>::failure(morale.status());
1858 processed += std::move(morale).takeValue();
1859
1860 auto shields = ShieldSystem::step(simulationStep, lifecycleEvents);
1861 if (!shields) return Result<std::size_t>::failure(shields.status());
1862 processed += std::move(shields).takeValue();
1863
1864 auto supply = SupplySystem::step(
1865 simulationStep, ammoProductionPurchase_, pathfinder_, navigationGrid_,
1866 [this](const LifecycleEvent& event, SimulationTick tick) { recordLifecycleEvent(event, tick); });
1867 if (!supply) return Result<std::size_t>::failure(supply.status());
1868 processed += std::move(supply).takeValue();
1869
1870 auto artillery = ArtillerySystem::step(simulationStep);
1871 if (!artillery) return Result<std::size_t>::failure(artillery.status());
1872 processed += std::move(artillery).takeValue();
1873
1874 auto fireSupport = FireSupportSystem::step(simulationStep);
1875 if (!fireSupport) return Result<std::size_t>::failure(fireSupport.status());
1876 processed += std::move(fireSupport).takeValue();
1877
1878 if (resourceCredit_) {
1879 auto mining = MiningSystem::step(simulationStep, resourceCredit_);
1880 if (!mining) return Result<std::size_t>::failure(mining.status());
1881 processed += std::move(mining).takeValue();
1882 }
1883
1884 auto construction = ConstructionSystem::step(simulationStep, lifecycleEvents);
1885 if (!construction) return Result<std::size_t>::failure(construction.status());
1886 processed += std::move(construction).takeValue();
1887
1888 auto infrastructure = InfrastructureSystem::step(simulationStep, passiveIncomeCredit_);
1889 if (!infrastructure) return Result<std::size_t>::failure(infrastructure.status());
1890 processed += std::move(infrastructure).takeValue();
1891
1892 combat::DamageRuntime defaultHealthSettlement;
1893 auto& healthSettlement = damage_ != nullptr ? *damage_ : defaultHealthSettlement;
1894 if (repairDebit_) {
1895 auto repair = RepairSystem::step(simulationStep, healthSettlement, repairDebit_);
1896 if (!repair) return Result<std::size_t>::failure(repair.status());
1897 processed += std::move(repair).takeValue();
1898 }
1899
1900 auto capture = CaptureSystem::step(simulationStep, lifecycleEvents);
1901 if (!capture) return Result<std::size_t>::failure(capture.status());
1902 processed += std::move(capture).takeValue();
1903
1904 if (damage_ != nullptr) {
1905 auto abilities = AbilitySystem::step(simulationStep, *damage_, damageEvents, lifecycleEvents);
1906 if (!abilities) return Result<std::size_t>::failure(abilities.status());
1907 processed += std::move(abilities).takeValue();
1908 auto projectileImpacts = projectiles_.step(simulationStep, *damage_, projectileCollisionQuery_, damageEvents);
1909 if (!projectileImpacts) return Result<std::size_t>::failure(projectileImpacts.status());
1910 processed += std::move(projectileImpacts).takeValue();
1911 }
1912 if (sensing_ != nullptr && damage_ != nullptr) {
1913 auto combat =
1914 CombatFireSystem::step(simulationStep, combatState_, *sensing_, *damage_, &projectiles_, fireLineQuery_,
1915 pathfinder_, navigationGrid_, combatHeightQuery_, damageEvents, fireEvents);
1916 if (!combat) return Result<std::size_t>::failure(combat.status());
1917 processed += std::move(combat).takeValue();
1918 }
1919
1920 auto actions = OrderActionSystem::step(simulationStep, executor);
1921 if (!actions) return Result<std::size_t>::failure(actions.status());
1922 processed += std::move(actions).takeValue();
1923
1924 auto reinforcementPolicy = ReinforcementProductionPolicySystem::step(simulationStep, reinforcementCancel_);
1925 if (!reinforcementPolicy) return Result<std::size_t>::failure(reinforcementPolicy.status());
1926 processed += std::move(reinforcementPolicy).takeValue();
1927
1928 if (crowd_ != nullptr) {
1929 EV_PROFILE_MODULE("rts", "RTS::crowdReconcilePhase");
1930 // Containment/actions can change footprints after the movement phase.
1931 // Reconcile those projections without advancing simulation time before spawning.
1932 auto alive = checkCrowdLifetime();
1933 if (!alive) return Result<std::size_t>::failure(alive.status());
1934 auto synchronized = advanceCrowdMotion({simulationStep.tick, Duration{}});
1935 if (!synchronized) return Result<std::size_t>::failure(synchronized.status());
1936 processed += std::move(synchronized).takeValue();
1937 }
1938
1939 auto production =
1940 BuildingProductionSystem::step(simulationStep, productionSpawn_, productionSpawnPosition_, lifecycleEvents);
1941 if (!production) return Result<std::size_t>::failure(production.status());
1942 processed += std::move(production).takeValue();
1943 for (const auto& handle : units_) {
1944 auto* unit = tryGetCurrent<Unit>(handle);
1945 if (unit == nullptr || unit->attributes()->values.initialized()) continue;
1946 auto initialized = RTSUnitAttributeAdapter::ensure(*unit);
1947 if (!initialized) return Result<std::size_t>::failure(initialized.status());
1948 }
1949
1950 auto reinforcements = ReinforcementSystem::step();
1951 if (!reinforcements) return Result<std::size_t>::failure(reinforcements.status());
1952 processed += std::move(reinforcements).takeValue();
1953 if (definitions_ != nullptr) {
1954 auto technology = TechnologySystem::step(*definitions_);
1955 if (!technology) return Result<std::size_t>::failure(technology.status());
1956 processed += std::move(technology).takeValue();
1957 }
1958
1959 auto effects = EffectSystem::step(simulationStep, healthSettlement, lifecycleEvents);
1960 if (!effects) return Result<std::size_t>::failure(effects.status());
1961 processed += std::move(effects).takeValue();
1962 for (const auto& handle : matches_) {
1963 auto* match = tryGetCurrent<Match>(handle);
1964 if (match == nullptr) continue;
1965 auto outcome = MatchSystem::step(*match, simulationStep, matchResourceQuery_);
1966 if (!outcome) return Result<std::size_t>::failure(outcome.status());
1967 processed += std::move(outcome).takeValue();
1968 auto campaign = MissionScriptSystem::step(*match, simulationStep);
1969 if (!campaign) return Result<std::size_t>::failure(campaign.status());
1970 processed += std::move(campaign).takeValue();
1971 }
1972 auto cleanup = cleanupDestroyed();
1973 if (!cleanup) return Result<std::size_t>::failure(cleanup.status());
1974 processed += std::move(cleanup).takeValue();
1976}
1977
1978Result<void> RTS::configureScriptCrowdExecution(crowd::CrowdExecution execution,
1979 std::shared_ptr<crowd::CrowdWorkScheduler> scheduler) {
1980 if (!scriptRuntime_ || !scriptRuntime_->configured)
1981 return Result<void>::failure(
1982 Diagnostic::error(DiagnosticCode::NotFound, "RTS script world is not configured", "crowd.scheduler"));
1983 return scriptRuntime_->crowd.setWorkScheduler(execution, std::move(scheduler));
1984}
1985
1986Result<std::size_t> RTS::stepScript(double seconds) {
1987 auto duration = Duration::fromSeconds(seconds);
1988 if (!duration || seconds <= 0.0) {
1989 if (!duration) return Result<std::size_t>::failure(duration.status());
1991 Diagnostic::error(DiagnosticCode::InvalidArgument, "RTS script step duration must be positive", "seconds"));
1992 }
1993 if (!scriptRuntime_) scriptRuntime_ = std::make_unique<ScriptRuntime>();
1994 if (scriptRuntime_->nextTick == std::numeric_limits<std::uint64_t>::max())
1996 Diagnostic::error(DiagnosticCode::Conflict, "RTS script simulation tick overflow", "tick"));
1997 const SimulationTick tick{scriptRuntime_->nextTick++};
1998 frameDamageEvents_.clear();
1999 frameCombatEvents_.clear();
2000 frameLifecycleEvents_.clear();
2001 frameEventSequence_ = 0;
2002 preserveFrameEventsOnNextStep_ = true;
2003 auto commands = scriptRuntime_->commandLog.apply(tick, *this);
2004 if (!commands) {
2005 preserveFrameEventsOnNextStep_ = false;
2006 return Result<std::size_t>::failure(commands.status());
2007 }
2008 const SimulationStep simulationStep{tick, std::move(duration).takeValue()};
2009 auto stepped = step(simulationStep, scriptRuntime_->adapter);
2010 if (!stepped) return stepped;
2011 std::erase_if(scriptRuntime_->paidProduction, [this](const auto& record) {
2012 auto* producer = findBuilding(record.producer);
2013 if (producer == nullptr) return true;
2014 auto task = producer->production()->values.find(record.taskId);
2015 if (!task || task->get().state == production::TaskState::Cancelled ||
2016 task->get().state == production::TaskState::Failed)
2017 return true;
2018 if (task->get().state != production::TaskState::Completed) return false;
2019 // A completed unit task can still be waiting for a free production exit.
2020 const auto& settled = producer->rally()->settledProductionTasks;
2021 return record.kind != "unit" || std::find(settled.begin(), settled.end(), record.taskId) != settled.end();
2022 });
2024}
2025
2026Result<void> RTS::configureScriptWorld(int width, int height, float cellSize, float originX, float originY) {
2027 if (width <= 0 || height <= 0 || !std::isfinite(cellSize) || cellSize <= 0.0f || !std::isfinite(originX) ||
2028 !std::isfinite(originY))
2029 return Result<void>::failure(
2031 "RTS script world requires positive dimensions and finite grid geometry", "grid"));
2032 if (!scriptRuntime_) scriptRuntime_ = std::make_unique<ScriptRuntime>();
2033 scriptRuntime_->pathfinder.setSize(width, height);
2034 scriptRuntime_->crowd.resizeField(width, height, cellSize, originX - cellSize * 0.5f, originY - cellSize * 0.5f);
2035 scriptRuntime_->crowd.setClampToField(false);
2036 // RTS uses navigation-cell world units; legacy flocking defaults use pixel-scale distances.
2037 // Predictive avoidance and contact resolution supply clearance without long-range repulsion.
2038 scriptRuntime_->crowd.setArriveRadius(cellSize);
2039 scriptRuntime_->crowd.setSeparationWeight(0.0f);
2040 crowd::AvoidanceSettings avoidance;
2041 avoidance.enabled = true;
2042 auto configuredAvoidance = scriptRuntime_->crowd.configureAvoidance(avoidance);
2043 if (!configuredAvoidance) return configuredAvoidance;
2044 scriptRuntime_->width = width;
2045 scriptRuntime_->height = height;
2046 scriptRuntime_->cellSize = cellSize;
2047 scriptRuntime_->originX = originX;
2048 scriptRuntime_->originY = originY;
2049 scriptRuntime_->terrainElevations.assign(static_cast<std::size_t>(width * height), 0.0f);
2050 scriptRuntime_->commandLog.clear();
2051 scriptRuntime_->nextTick = 1;
2052 scriptRuntime_->aiProductionSequence = 1;
2053 scriptRuntime_->configured = true;
2054 setDefinitionRegistry(&scriptRuntime_->definitions);
2055 setNavigationProvider(&scriptRuntime_->pathfinder, {cellSize, originX, originY});
2056 setCrowdProvider(&scriptRuntime_->crowd);
2057 // The canonical sensing world owns filtering and ranking; its existing grid only culls candidates.
2058 auto sensingIndex = scriptRuntime_->sensing.setSpatialIndexEnabled(true, cellSize * 8.f);
2059 if (!sensingIndex) return sensingIndex;
2060 setCombatProviders(&scriptRuntime_->sensing, &scriptRuntime_->damage);
2061 const auto firstBlockedPoint = [this](WorldPosition from, WorldPosition to) -> std::optional<WorldPosition> {
2062 if (!scriptRuntime_ || !scriptRuntime_->configured) return std::nullopt;
2063 const float dx = to.x - from.x;
2064 const float dy = to.y - from.y;
2065 const float distance = std::hypot(dx, dy);
2066 const float sampleLength = std::max(scriptRuntime_->cellSize * 0.25f, 0.001f);
2067 const int samples = std::max(1, static_cast<int>(std::ceil(distance / sampleLength)));
2068 int previousX =
2069 static_cast<int>(std::floor((from.x - scriptRuntime_->originX) / scriptRuntime_->cellSize + 0.5f));
2070 int previousY =
2071 static_cast<int>(std::floor((from.y - scriptRuntime_->originY) / scriptRuntime_->cellSize + 0.5f));
2072 for (int sample = 1; sample <= samples; ++sample) {
2073 const float t = static_cast<float>(sample) / static_cast<float>(samples);
2074 const WorldPosition point{from.x + dx * t, from.y + dy * t};
2075 const int cellX =
2076 static_cast<int>(std::floor((point.x - scriptRuntime_->originX) / scriptRuntime_->cellSize + 0.5f));
2077 const int cellY =
2078 static_cast<int>(std::floor((point.y - scriptRuntime_->originY) / scriptRuntime_->cellSize + 0.5f));
2079 if (cellX == previousX && cellY == previousY) continue;
2080 previousX = cellX;
2081 previousY = cellY;
2082 if (cellX < 0 || cellY < 0 || cellX >= scriptRuntime_->width || cellY >= scriptRuntime_->height ||
2083 !scriptRuntime_->pathfinder.isWalkable(cellX, cellY))
2084 return point;
2085 }
2086 return std::nullopt;
2087 };
2088 const auto terrainAt = [this](WorldPosition point) {
2089 if (!scriptRuntime_ || scriptRuntime_->terrainElevations.empty()) return 0.0f;
2090 const int x =
2091 static_cast<int>(std::floor((point.x - scriptRuntime_->originX) / scriptRuntime_->cellSize + 0.5f));
2092 const int y =
2093 static_cast<int>(std::floor((point.y - scriptRuntime_->originY) / scriptRuntime_->cellSize + 0.5f));
2094 if (x < 0 || y < 0 || x >= scriptRuntime_->width || y >= scriptRuntime_->height) return 0.0f;
2095 return scriptRuntime_->terrainElevations[static_cast<std::size_t>(y * scriptRuntime_->width + x)];
2096 };
2097 const auto relativeHeight = [](ecs::EntityHandle handle, bool firing) {
2098 if (auto* unit = tryGetCurrent<Unit>(handle))
2099 return firing ? unit->combat()->firingHeight : unit->combat()->targetHeight;
2100 if (auto* building = tryGetCurrent<Building>(handle))
2101 return firing ? building->combat()->firingHeight : building->combat()->targetHeight;
2102 return firing ? 1.0f : 0.0f;
2103 };
2104 const auto terrainBlocks = [this](WorldPosition from, WorldPosition to, float fromHeight,
2105 float toHeight) -> std::optional<WorldPosition> {
2106 const auto impact = terrain_internal::firstTerrainImpact(
2107 from.x, from.y, fromHeight, to.x, to.y, toHeight, scriptRuntime_->originX, scriptRuntime_->originY,
2108 scriptRuntime_->cellSize, [this](int x, int y) {
2109 if (x < 0 || y < 0 || x >= scriptRuntime_->width || y >= scriptRuntime_->height) return 0.0f;
2110 return scriptRuntime_->terrainElevations[static_cast<std::size_t>(y * scriptRuntime_->width + x)];
2111 });
2112 if (!impact) return std::nullopt;
2113 return WorldPosition{from.x + (to.x - from.x) * *impact, from.y + (to.y - from.y) * *impact};
2114 };
2115 setFireLineQuery([firstBlockedPoint, terrainAt, relativeHeight, terrainBlocks](
2116 WorldPosition from, WorldPosition to, ecs::EntityHandle source, ecs::EntityHandle target,
2118 const float sourceHeight = terrainAt(from) + relativeHeight(source, true);
2119 const float targetHeight = terrainAt(to) + relativeHeight(target, false);
2120 const bool blocked =
2121 firstBlockedPoint(from, to).has_value() || terrainBlocks(from, to, sourceHeight, targetHeight).has_value();
2123 });
2124 setCombatHeightQuery([terrainAt, relativeHeight](WorldPosition from, WorldPosition to, ecs::EntityHandle source,
2125 ecs::EntityHandle target) {
2126 return CombatHeightProfile{terrainAt(from) + relativeHeight(source, true),
2127 terrainAt(to) + relativeHeight(target, false)};
2128 });
2129 setProjectileCollisionQuery([firstBlockedPoint, terrainBlocks](
2130 WorldPosition from, float fromHeight, WorldPosition to, float toHeight, SubjectRef,
2131 ecs::EntityHandle) -> Result<std::optional<ProjectileCollision>> {
2132 const auto blocked = firstBlockedPoint(from, to);
2133 const auto terrainImpact = terrainBlocks(from, to, fromHeight, toHeight);
2134 if (!blocked && !terrainImpact)
2136 const auto distanceSquared = [from](WorldPosition point) {
2137 const float dx = point.x - from.x;
2138 const float dy = point.y - from.y;
2139 return dx * dx + dy * dy;
2140 };
2141 const WorldPosition impact =
2142 blocked && (!terrainImpact || distanceSquared(*blocked) < distanceSquared(*terrainImpact)) ? *blocked
2143 : *terrainImpact;
2146 });
2147 setFogProvider([this](Faction& faction) -> map::Fov* {
2148 if (!scriptRuntime_) return nullptr;
2149 const auto found = scriptRuntime_->fovs.find(faction.identity()->subject.format());
2150 return found == scriptRuntime_->fovs.end() ? nullptr : found->second.get();
2151 });
2152 setProductionSpawn([this](Building& producer, const production::ProductionTask& task,
2154 if (!scriptRuntime_)
2156 Diagnostic::error(DiagnosticCode::Conflict, "RTS script runtime is unavailable", "production"));
2157 const auto pending = scriptRuntime_->pendingProductionSubjects.find(task.id);
2158 if (pending == scriptRuntime_->pendingProductionSubjects.end())
2160 DiagnosticCode::NotFound, "RTS produced unit has no reserved stable subject", "production.task"));
2161 const auto definition = LogicalId::parse("unit:" + task.product);
2162 if (!definition)
2165 "RTS produced unit has an invalid logical definition", "production.product"));
2166 auto* faction = dynamic_cast<Faction*>(producer.faction()->link.resolve());
2167 if (faction == nullptr)
2169 DiagnosticCode::StaleHandle, "RTS producer faction link is stale", "production.faction"));
2170 scriptRuntime_->spawningProduction = true;
2171 auto created = newFactionUnit(*faction, pending->second, *definition);
2172 scriptRuntime_->spawningProduction = false;
2174 Unit* unit = std::move(created).takeValue();
2175 auto placed = placeProducedUnit(*unit, requested);
2176 if (!placed || placed.value().state == ProductionSpawnState::Blocked) {
2177 removeUnitRoot(*unit, UnitRemovalReason::SpawnRollback);
2178 return placed;
2179 }
2180 scriptRuntime_->pendingProductionSubjects.erase(pending);
2181 return placed;
2182 });
2183 setAIProductionRequest([this](Faction& faction, Building& producer, const LogicalId& definition) -> Result<void> {
2184 if (!scriptRuntime_ || !scriptRuntime_->configured)
2186 DiagnosticCode::Conflict, "RTS script AI production requires a configured world", "scriptRuntime"));
2187 if (scriptRuntime_->aiProductionSequence == std::numeric_limits<std::uint64_t>::max())
2189 DiagnosticCode::Conflict, "RTS script AI production identity sequence overflow", "ai.sequence"));
2190 SubjectRef generated;
2191 do {
2192 generated = deterministicSubject(faction.identity()->subject.format() + ":" +
2193 producer.identity()->subject.format() + ":" + definition.format(),
2194 scriptRuntime_->aiProductionSequence++);
2195 } while (ownsSubject(generated, SubjectClaimScope::LiveOrReserved) &&
2196 scriptRuntime_->aiProductionSequence != std::numeric_limits<std::uint64_t>::max());
2197 if (ownsSubject(generated, SubjectClaimScope::LiveOrReserved))
2198 return Result<void>::failure(
2200 "RTS script AI could not allocate a stable production subject", "ai.sequence"));
2201 auto queued = queueScriptUnit(producer, generated, definition);
2202 if (!queued) return Result<void>::failure(queued.status());
2204 });
2205
2206 for (const auto& handle : factions_) {
2207 auto* faction = tryGetCurrent<Faction>(handle);
2208 if (faction == nullptr) continue;
2209 const std::string key = faction->identity()->subject.format();
2210 if (!scriptRuntime_->economies.contains(key))
2211 scriptRuntime_->economies.emplace(key, std::make_unique<ScriptRuntime::EconomySlot>());
2212 auto& fov = scriptRuntime_->fovs[key];
2213 if (!fov)
2214 fov = std::make_unique<map::Fov>(width, height);
2215 else
2216 fov->setSize(width, height);
2217 fov->setMode("heightmap");
2218 fov->setEyeOffset(1.0f);
2219 fov->setCliffBlock(0.0f);
2220 auto link = EconomyLink::bind("rts/script/economy/" + key);
2221 if (!link) return Result<void>::failure(link.status());
2222 faction->economy()->link = std::move(link).takeValue();
2223 }
2224 for (const auto& handle : units_) {
2225 auto* unit = tryGetCurrent<Unit>(handle);
2226 if (unit == nullptr) continue;
2227 const std::string key = unit->identity()->subject.format();
2228 auto crowdLink = CrowdLink::bind(key);
2229 auto sensingLink = SensingLink::bind(key);
2230 if (!crowdLink) return Result<void>::failure(crowdLink.status());
2231 if (!sensingLink) return Result<void>::failure(sensingLink.status());
2232 unit->crowd()->link = std::move(crowdLink).takeValue();
2233 unit->sensing()->link = std::move(sensingLink).takeValue();
2234 }
2235
2236 const auto accountForFaction = [this](Faction* faction) -> resource::IResourceAccount* {
2237 if (faction == nullptr || !scriptRuntime_) return nullptr;
2238 const auto found = scriptRuntime_->economies.find(faction->identity()->subject.format());
2239 return found == scriptRuntime_->economies.end() ? nullptr : &found->second->account;
2240 };
2241 setResourceCredit([accountForFaction](Unit& unit, const resource::CostSpec& cost) -> Result<resource::Receipt> {
2242 auto* account = accountForFaction(dynamic_cast<Faction*>(unit.faction()->link.resolve()));
2243 if (account == nullptr)
2245 DiagnosticCode::NotFound, "RTS script faction economy was not found", "unit.faction"));
2246 return account->credit(cost);
2247 });
2248 setRepairDebit(
2249 [accountForFaction](Unit& unit, Building&, const resource::CostSpec& cost) -> Result<resource::Receipt> {
2250 auto* account = accountForFaction(dynamic_cast<Faction*>(unit.faction()->link.resolve()));
2251 if (account == nullptr)
2253 DiagnosticCode::NotFound, "RTS script faction economy was not found", "unit.faction"));
2254 return account->debit(cost);
2255 });
2256 setPassiveIncomeCredit(
2257 [accountForFaction](Building& building, const resource::CostSpec& cost) -> Result<resource::Receipt> {
2258 auto* account = accountForFaction(dynamic_cast<Faction*>(building.faction()->link.resolve()));
2259 if (account == nullptr)
2261 DiagnosticCode::NotFound, "RTS script faction economy was not found", "building.faction"));
2262 return account->credit(cost);
2263 });
2264 setMatchResourceQuery([this](Faction& faction, std::string_view resource) -> Result<double> {
2265 auto balance = scriptResource(faction, resource);
2266 if (!balance) return Result<double>::failure(balance.status());
2267 return Result<double>::success(static_cast<double>(balance.value()), Status::success(StatusCode::Applied));
2268 });
2270}
2271
2272Result<void> RTS::setScriptNavigationBlocked(int x, int y, bool blocked) {
2273 if (!scriptRuntime_ || !scriptRuntime_->configured)
2274 return Result<void>::failure(
2275 Diagnostic::error(DiagnosticCode::Conflict, "RTS script world is not configured", "grid"));
2276 if (x < 0 || y < 0 || x >= scriptRuntime_->width || y >= scriptRuntime_->height)
2278 "RTS script navigation cell is outside the grid", "cell"));
2279 scriptRuntime_->pathfinder.setBlocked(x, y, blocked);
2280 scriptRuntime_->crowd.setBlocked(x, y, blocked);
2281 for (auto& [key, fov] : scriptRuntime_->fovs) {
2282 (void)key;
2283 if (fov) fov->setOpaque(x, y, blocked);
2284 }
2286}
2287
2288Result<void> RTS::rebindScriptRootProviders() {
2289 if (!scriptRuntime_ || !scriptRuntime_->configured)
2290 return Result<void>::failure(
2291 Diagnostic::error(DiagnosticCode::Conflict, "RTS script world is not configured", "scriptWorld"));
2292 for (const auto& handle : factions_) {
2293 auto* faction = tryGetCurrent<Faction>(handle);
2294 if (faction == nullptr) continue;
2295 const std::string key = faction->identity()->subject.format();
2296 if (!scriptRuntime_->economies.contains(key))
2297 scriptRuntime_->economies.emplace(key, std::make_unique<ScriptRuntime::EconomySlot>());
2298 if (!scriptRuntime_->fovs.contains(key) || !scriptRuntime_->fovs.at(key))
2299 scriptRuntime_->fovs[key] = std::make_unique<map::Fov>(scriptRuntime_->width, scriptRuntime_->height);
2300 scriptRuntime_->fovs[key]->setMode("heightmap");
2301 scriptRuntime_->fovs[key]->setEyeOffset(1.0f);
2302 scriptRuntime_->fovs[key]->setCliffBlock(0.0f);
2303 auto economy = EconomyLink::bind("rts/script/economy/" + key);
2304 if (!economy) return Result<void>::failure(economy.status());
2305 faction->economy()->link = std::move(economy).takeValue();
2306 }
2307 for (const auto& handle : units_) {
2308 auto* unit = tryGetCurrent<Unit>(handle);
2309 if (unit == nullptr) continue;
2310 const std::string key = unit->identity()->subject.format();
2311 auto crowdLink = CrowdLink::bind(key);
2312 auto sensingLink = SensingLink::bind(key);
2313 if (!crowdLink) return Result<void>::failure(crowdLink.status());
2314 if (!sensingLink) return Result<void>::failure(sensingLink.status());
2315 unit->crowd()->link = std::move(crowdLink).takeValue();
2316 unit->sensing()->link = std::move(sensingLink).takeValue();
2317 }
2319}
2320
2321Result<void> RTS::setScriptNavigationCost(int x, int y, float cost) {
2322 if (!scriptRuntime_ || !scriptRuntime_->configured)
2323 return Result<void>::failure(
2324 Diagnostic::error(DiagnosticCode::Conflict, "RTS script world is not configured", "grid"));
2325 if (x < 0 || y < 0 || x >= scriptRuntime_->width || y >= scriptRuntime_->height || !std::isfinite(cost) ||
2326 cost <= 0.0f)
2327 return Result<void>::failure(
2329 "RTS script navigation cost requires an in-grid cell and positive finite cost", "cell"));
2330 scriptRuntime_->pathfinder.setCellCost(x, y, cost);
2331 scriptRuntime_->crowd.setCellCost(x, y, cost);
2333}
2334
2335Result<void> RTS::setScriptTerrainElevation(int x, int y, float elevation) {
2336 if (!scriptRuntime_ || !scriptRuntime_->configured)
2337 return Result<void>::failure(
2338 Diagnostic::error(DiagnosticCode::Conflict, "RTS script world is not configured", "terrain"));
2339 if (x < 0 || y < 0 || x >= scriptRuntime_->width || y >= scriptRuntime_->height || !std::isfinite(elevation))
2340 return Result<void>::failure(
2342 "RTS terrain elevation requires an in-grid cell and finite value", "terrain.cell"));
2343 scriptRuntime_->terrainElevations[static_cast<std::size_t>(y * scriptRuntime_->width + x)] = elevation;
2344 for (auto& [faction, fov] : scriptRuntime_->fovs) {
2345 (void)faction;
2346 if (fov) fov->setElevation(x, y, elevation);
2347 }
2349}
2350
2351Result<float> RTS::scriptTerrainElevation(int x, int y) const {
2352 if (!scriptRuntime_ || !scriptRuntime_->configured)
2354 Diagnostic::error(DiagnosticCode::Conflict, "RTS script world is not configured", "terrain"));
2355 if (x < 0 || y < 0 || x >= scriptRuntime_->width || y >= scriptRuntime_->height)
2357 Diagnostic::error(DiagnosticCode::InvalidArgument, "RTS terrain cell is outside the grid", "terrain.cell"));
2359 scriptRuntime_->terrainElevations[static_cast<std::size_t>(y * scriptRuntime_->width + x)],
2361}
2362
2363Result<void> RTS::addScriptResource(Faction& faction, std::string resource, std::int64_t amount) {
2364 if (!owns(factions_, faction))
2365 return Result<void>::failure(
2366 Diagnostic::error(DiagnosticCode::StaleHandle, "RTS Faction does not belong to this facade", "faction"));
2367 if (!scriptRuntime_ || !scriptRuntime_->configured)
2368 return Result<void>::failure(
2369 Diagnostic::error(DiagnosticCode::Conflict, "RTS script world is not configured", "economy"));
2370 const auto found = scriptRuntime_->economies.find(faction.identity()->subject.format());
2371 if (found == scriptRuntime_->economies.end())
2372 return Result<void>::failure(
2373 Diagnostic::error(DiagnosticCode::NotFound, "RTS script faction economy was not found", "faction"));
2374 auto cost = resource::CostSpec::single(std::move(resource), amount);
2375 if (!cost) return Result<void>::failure(cost.status());
2376 auto credited = found->second->account.credit(std::move(cost).takeValue());
2377 if (!credited) return Result<void>::failure(credited.status());
2378 std::move(credited).takeValue();
2380}
2381
2382Result<std::int64_t> RTS::scriptResource(Faction& faction, std::string_view resource) const {
2383 if (!owns(factions_, faction))
2385 Diagnostic::error(DiagnosticCode::StaleHandle, "RTS Faction does not belong to this facade", "faction"));
2386 if (!scriptRuntime_ || !scriptRuntime_->configured || resource.empty())
2389 "RTS script resource query requires a configured world and resource", "resource"));
2390 const auto found = scriptRuntime_->economies.find(faction.identity()->subject.format());
2391 if (found == scriptRuntime_->economies.end())
2393 Diagnostic::error(DiagnosticCode::NotFound, "RTS script faction economy was not found", "faction"));
2394 return Result<std::int64_t>::success(found->second->ledger.get(std::string(resource)));
2395}
2396
2397Result<void> RTS::configureScriptAI(Faction& faction, LogicalId workerDefinition, LogicalId armyDefinition,
2398 LogicalId targetBuildingDefinition, int desiredWorkers, int attackThreshold,
2399 float thinkInterval, float formationSpacing, bool enabled) {
2400 if (!owns(factions_, faction))
2401 return Result<void>::failure(
2402 Diagnostic::error(DiagnosticCode::StaleHandle, "RTS AI faction does not belong to this facade", "faction"));
2403 if (!scriptRuntime_ || !scriptRuntime_->configured || definitions_ == nullptr)
2405 DiagnosticCode::Conflict, "RTS AI requires a configured script world and content", "scriptRuntime"));
2406 if (!workerDefinition.isValid() || !armyDefinition.isValid() || !targetBuildingDefinition.isValid() ||
2407 desiredWorkers < 0 || attackThreshold <= 0 || !std::isfinite(thinkInterval) || thinkInterval <= 0.0f ||
2408 !std::isfinite(formationSpacing) || formationSpacing <= 0.0f ||
2409 !definitions_->resolve("unit", std::string(workerDefinition.name())) ||
2410 !definitions_->resolve("unit", std::string(armyDefinition.name())) ||
2411 !definitions_->resolve("building", std::string(targetBuildingDefinition.name())))
2414 "RTS AI policy requires known definitions and positive finite policy values", "strategy"));
2415 auto strategy = faction.strategy();
2416 strategy->workerDefinition = std::move(workerDefinition);
2417 strategy->armyDefinition = std::move(armyDefinition);
2418 strategy->targetBuildingDefinition = std::move(targetBuildingDefinition);
2419 strategy->desiredWorkers = desiredWorkers;
2420 strategy->attackThreshold = attackThreshold;
2421 strategy->thinkInterval = thinkInterval;
2422 strategy->thinkAccumulator = 0.0f;
2423 strategy->formationSpacing = formationSpacing;
2424 strategy->enabled = enabled;
2426}
2427
2428Result<ContentImportReceipt> RTS::loadScriptContent(std::string_view json) {
2429 if (!scriptRuntime_) scriptRuntime_ = std::make_unique<ScriptRuntime>();
2430 setDefinitionRegistry(&scriptRuntime_->definitions);
2431 return loadContent(scriptRuntime_->definitions, json);
2432}
2433
2434Result<ReinforcementRequestReceipt> RTS::queueScriptReinforcement(Building& producer, SubjectRef unitSubject,
2435 LogicalId preferredDefinition, int priority) {
2436 if (!owns(buildings_, producer))
2438 DiagnosticCode::StaleHandle, "RTS reinforcement producer does not belong to this facade", "producer"));
2439 if (!unitSubject.isValid() || ownsSubject(unitSubject, SubjectClaimScope::LiveOrReserved) ||
2440 !preferredDefinition.isValid())
2443 "RTS reinforcement requires a new stable subject and preferred unit definition", "reinforcement"));
2444 return ReinforcementProductionPolicySystem::request(
2445 producer, std::string(preferredDefinition.name()),
2446 [&](Building& selectedProducer, std::string_view candidate) -> Result<std::string> {
2447 auto definition = LogicalId::parse(candidate);
2448 if (!definition) definition = LogicalId::parse("unit:" + std::string(candidate));
2449 if (!definition)
2450 return Result<std::string>::failure(Diagnostic::error(
2451 DiagnosticCode::InvalidArgument, "RTS reinforcement fallback is not a valid unit definition",
2452 "reinforcement.fallback"));
2453 auto queued = queueScriptUnit(selectedProducer, unitSubject, *definition, priority);
2454 if (!queued) return Result<std::string>::failure(queued.status());
2455 return Result<std::string>::success(queued.value().productionTaskId, Status::success(StatusCode::Applied));
2456 });
2457}
2458
2459Result<Building*> RTS::startScriptConstruction(Faction& faction, SubjectRef buildingSubject,
2460 LogicalId buildingDefinition, WorldPosition position, Unit& builder) {
2461 if (!owns(factions_, faction) || !owns(units_, builder))
2464 "RTS construction faction or builder does not belong to this facade", "construction"));
2465 if (builder.faction()->link.resolve() != &faction || builder.worker()->buildRate <= 0.0f)
2467 DiagnosticCode::PreconditionViolation, "RTS construction requires a same-faction builder", "builder"));
2468 if (!scriptRuntime_ || !scriptRuntime_->configured || definitions_ == nullptr || !buildingSubject.isValid() ||
2469 ownsSubject(buildingSubject) || !buildingDefinition.isValid() || !std::isfinite(position.x) ||
2470 !std::isfinite(position.y))
2473 "RTS construction request is invalid or the world is not configured", "construction"));
2474 auto resolved = definitions_->resolve("building", std::string(buildingDefinition.name()));
2475 if (!resolved) return Result<Building*>::failure(resolved.status());
2476 auto parsed = Value::fromJson(resolved.value().get().json);
2477 if (!parsed) return Result<Building*>::failure(parsed.status());
2478 const auto* object = parsed.value().getIf<Value::Object>();
2479 if (object == nullptr)
2481 DiagnosticCode::InvalidArgument, "RTS building definition must be an object", "buildingDefinition"));
2482 const auto resourceIt = object->find("costResource");
2483 const auto costIt = object->find("cost");
2484 if (resourceIt == object->end() || costIt == object->end())
2486 "RTS building definition lacks a construction cost",
2487 "buildingDefinition"));
2488 const auto* resourceName = resourceIt->second.getIf<std::string>();
2489 double costNumber = -1.0;
2490 if (const auto* integer = costIt->second.getIf<std::int64_t>())
2491 costNumber = static_cast<double>(*integer);
2492 else if (const auto* real = costIt->second.getIf<double>())
2493 costNumber = *real;
2494 if (resourceName == nullptr || resourceName->empty() || !std::isfinite(costNumber) || costNumber < 0.0 ||
2495 std::floor(costNumber) != costNumber)
2497 DiagnosticCode::InvalidArgument, "RTS building construction cost is invalid", "buildingDefinition"));
2498 const auto economy = scriptRuntime_->economies.find(faction.identity()->subject.format());
2499 if (economy == scriptRuntime_->economies.end())
2501 Diagnostic::error(DiagnosticCode::NotFound, "RTS construction economy was not found", "faction"));
2502 auto cost = resource::CostSpec::single(*resourceName, static_cast<std::int64_t>(costNumber));
2503 if (!cost) return Result<Building*>::failure(cost.status());
2504 auto previousOrders = builder.orders()->values.snapshotState();
2505 if (!previousOrders) return Result<Building*>::failure(previousOrders.status());
2506 auto paid = economy->second->account.debit(cost.value());
2507 if (!paid) return Result<Building*>::failure(paid.status());
2508
2509 const std::size_t weaponCount = weapons_.size();
2510 auto created = newFactionBuilding(faction, buildingSubject, buildingDefinition);
2511 if (!created) {
2512 economy->second->account.credit(cost.value()).ignore("compensate failed construction root creation");
2513 return created;
2514 }
2515 Building* building = created.value();
2516 building->placement()->worldX = position.x;
2517 building->placement()->worldY = position.y;
2518 building->construction()->progress = 0.0f;
2519 building->construction()->builders = {ecs::handle_of(&builder)};
2520 // Build already owns approach movement with the building's interaction
2521 // radius. A preceding Move demands entry into its blocked footprint.
2522 CommandSpec buildCommand;
2523 buildCommand.kind = OrderKind::Build;
2524 buildCommand.target = position;
2525 buildCommand.targetEntity = ecs::handle_of(building);
2526 auto ordered = builder.orders()->values.replace(buildCommand);
2527 if (!ordered) {
2528 const Status status = ordered.status();
2529 builder.orders()->values.restoreState(previousOrders.value()).ignore("restore construction builder orders");
2530 faction.members()->buildings.pop_back();
2531 building->release();
2532 buildings_.pop_back();
2533 while (weapons_.size() > weaponCount) {
2534 if (auto* weapon = dynamic_cast<weapon::WeaponEntity*>(ecs::try_get(weapons_.back()))) weapon->release();
2535 weapons_.pop_back();
2536 }
2537 economy->second->account.credit(cost.value()).ignore("compensate failed construction order");
2539 }
2540 std::move(ordered).takeValue();
2541 scriptRuntime_->paidConstruction.push_back({buildingSubject, faction.identity()->subject, cost.value()});
2543}
2544
2545Result<resource::Receipt> RTS::cancelScriptConstruction(Building& building) {
2546 if (!owns(buildings_, building))
2548 DiagnosticCode::StaleHandle, "RTS construction does not belong to this facade", "building"));
2549 if (!scriptRuntime_ || !scriptRuntime_->configured || !building.integrity()->alive ||
2550 building.construction()->progress >= 1.0f)
2553 "RTS construction cancellation requires a live unfinished script building", "building.construction"));
2554 const auto payment =
2555 std::find_if(scriptRuntime_->paidConstruction.begin(), scriptRuntime_->paidConstruction.end(),
2556 [&](const auto& value) { return value.building == building.identity()->subject; });
2557 if (payment == scriptRuntime_->paidConstruction.end())
2559 DiagnosticCode::NotFound, "RTS construction payment record was not found", "building.construction"));
2560 auto* faction = findFaction(payment->faction);
2561 if (faction == nullptr)
2563 Diagnostic::error(DiagnosticCode::StaleHandle, "RTS construction faction is stale", "building.faction"));
2564 const auto economy = scriptRuntime_->economies.find(payment->faction.format());
2565 if (economy == scriptRuntime_->economies.end())
2567 Diagnostic::error(DiagnosticCode::NotFound, "RTS construction economy was not found", "building.faction"));
2568 auto refund = scaledCost(payment->cost,
2569 1.0 - 0.5 * std::clamp(static_cast<double>(building.construction()->progress), 0.0, 1.0));
2570 if (!refund) return Result<resource::Receipt>::failure(refund.status());
2571 auto credited = economy->second->account.credit(refund.value());
2572 if (!credited) return Result<resource::Receipt>::failure(credited.status());
2573
2574 for (const auto& builderHandle : building.construction()->builders) {
2575 auto* builder = dynamic_cast<Unit*>(ecs::try_get(builderHandle));
2576 if (builder != nullptr) builder->orders()->values.clear();
2577 }
2578 building.construction()->builders.clear();
2579 building.integrity()->alive = false;
2580 building.integrity()->state.health = 0.0;
2581 building.placement()->placed = false;
2582 const auto buildingHandle = ecs::handle_of(&building);
2583 std::erase_if(faction->members()->buildings, [&](const auto& value) { return sameHandle(value, buildingHandle); });
2584 const auto weaponHandle = building.weapon()->link.handle();
2585 if (auto* weapon = dynamic_cast<weapon::WeaponEntity*>(building.weapon()->link.resolve())) weapon->release();
2586 std::erase_if(weapons_, [&](const auto& value) { return sameHandle(value, weaponHandle); });
2587 std::erase_if(buildings_, [&](const auto& value) { return sameHandle(value, buildingHandle); });
2588 scriptRuntime_->paidConstruction.erase(payment);
2589 building.release();
2590 return credited;
2591}
2592
2593Result<resource::Receipt> RTS::sellScriptBuilding(Building& building) {
2594 if (!owns(buildings_, building))
2596 Diagnostic::error(DiagnosticCode::StaleHandle, "RTS building does not belong to this facade", "building"));
2597 if (!scriptRuntime_ || !scriptRuntime_->configured || definitions_ == nullptr || !building.integrity()->alive ||
2598 building.construction()->progress < 1.0f)
2601 "RTS sale requires a live completed script building", "building.construction"));
2602 auto* faction = dynamic_cast<Faction*>(building.faction()->link.resolve());
2603 if (faction == nullptr)
2605 Diagnostic::error(DiagnosticCode::StaleHandle, "RTS building faction link is stale", "building.faction"));
2606 const auto economy = scriptRuntime_->economies.find(faction->identity()->subject.format());
2607 if (economy == scriptRuntime_->economies.end())
2609 Diagnostic::error(DiagnosticCode::NotFound, "RTS building economy was not found", "building.faction"));
2610 auto definition = definitions_->resolve("building", std::string(building.definition()->id.name()));
2611 if (!definition) return Result<resource::Receipt>::failure(definition.status());
2612 auto parsed = Value::fromJson(definition.value().get().json);
2613 if (!parsed) return Result<resource::Receipt>::failure(parsed.status());
2614 const auto* object = parsed.value().getIf<Value::Object>();
2615 if (object == nullptr)
2617 DiagnosticCode::InvalidArgument, "RTS building definition must be an object", "building.definition"));
2618 const auto resourceIt = object->find("costResource");
2619 const auto costIt = object->find("cost");
2620 if (resourceIt == object->end() || costIt == object->end() || resourceIt->second.getIf<std::string>() == nullptr)
2622 DiagnosticCode::InvalidArgument, "RTS building definition lacks a sale cost", "building.definition"));
2623 double costNumber = -1.0;
2624 if (const auto* integer = costIt->second.getIf<std::int64_t>())
2625 costNumber = static_cast<double>(*integer);
2626 else if (const auto* real = costIt->second.getIf<double>())
2627 costNumber = *real;
2628 double ratio = 0.5;
2629 if (const auto ratioIt = object->find("sellRefundRatio"); ratioIt != object->end()) {
2630 if (const auto* integer = ratioIt->second.getIf<std::int64_t>())
2631 ratio = static_cast<double>(*integer);
2632 else if (const auto* real = ratioIt->second.getIf<double>())
2633 ratio = *real;
2634 else
2635 ratio = -1.0;
2636 }
2637 if (!std::isfinite(costNumber) || costNumber <= 0.0 || std::floor(costNumber) != costNumber ||
2638 !std::isfinite(ratio) || ratio <= 0.0 || ratio > 1.0)
2640 DiagnosticCode::InvalidArgument, "RTS building sale values are invalid", "building.definition"));
2641 auto baseCost =
2642 resource::CostSpec::single(*resourceIt->second.getIf<std::string>(), static_cast<std::int64_t>(costNumber));
2643 if (!baseCost) return Result<resource::Receipt>::failure(baseCost.status());
2644 auto saleRefund = scaledCost(baseCost.value(), ratio);
2645 if (!saleRefund) return Result<resource::Receipt>::failure(saleRefund.status());
2646
2647 auto rootBefore = snapshotState();
2648 if (!rootBefore) return Result<resource::Receipt>::failure(rootBefore.status());
2649 const auto ledgerBefore = economy->second->ledger.snapshot();
2650 const auto pendingBefore = scriptRuntime_->pendingProductionSubjects;
2651 const auto paymentsBefore = scriptRuntime_->paidProduction;
2652 const SubjectRef producerSubject = building.identity()->subject;
2653 const auto rollback = [&]() {
2654 economy->second->ledger.restore(ledgerBefore);
2655 scriptRuntime_->pendingProductionSubjects = pendingBefore;
2656 scriptRuntime_->paidProduction = paymentsBefore;
2657 (void)restoreState(rootBefore.value());
2658 };
2659 for (const auto& record : paymentsBefore) {
2660 if (record.producer != producerSubject) continue;
2661 auto task = building.production()->values.find(record.taskId);
2662 if (!task || task->get().state == production::TaskState::Completed ||
2663 task->get().state == production::TaskState::Cancelled || task->get().state == production::TaskState::Failed)
2664 continue;
2665 auto cancelled = cancelProduction(building, economy->second->account, record.taskId, record.orderId,
2666 record.refund, "building sold");
2667 if (!cancelled) {
2668 rollback();
2670 }
2671 scriptRuntime_->pendingProductionSubjects.erase(record.taskId);
2672 std::erase_if(scriptRuntime_->paidProduction, [&](const auto& value) { return value.taskId == record.taskId; });
2673 }
2674 auto credited = economy->second->account.credit(saleRefund.value());
2675 if (!credited) {
2676 rollback();
2677 return Result<resource::Receipt>::failure(credited.status());
2678 }
2679 auto evacuated = evacuateBuilding(building, {building.placement()->worldX + 2.0f, building.placement()->worldY});
2680 if (!evacuated) {
2681 rollback();
2682 return Result<resource::Receipt>::failure(evacuated.status());
2683 }
2684
2685 const auto buildingHandle = ecs::handle_of(&building);
2686 for (const auto& factionHandle : factions_) {
2687 auto* owner = dynamic_cast<Faction*>(ecs::try_get(factionHandle));
2688 if (owner != nullptr)
2689 std::erase_if(owner->members()->buildings,
2690 [&](const auto& value) { return sameHandle(value, buildingHandle); });
2691 }
2692 const auto weaponHandle = building.weapon()->link.handle();
2693 if (auto* weapon = dynamic_cast<weapon::WeaponEntity*>(building.weapon()->link.resolve())) weapon->release();
2694 std::erase_if(weapons_, [&](const auto& value) { return sameHandle(value, weaponHandle); });
2695 std::erase_if(buildings_, [&](const auto& value) { return sameHandle(value, buildingHandle); });
2696 std::erase_if(scriptRuntime_->paidConstruction,
2697 [&](const auto& value) { return value.building == producerSubject; });
2698 building.release();
2699 return credited;
2700}
2701
2702Result<RTSBuildReceipt> RTS::queueScriptResearch(Building& producer, std::string upgrade, int priority) {
2703 if (!owns(buildings_, producer))
2705 DiagnosticCode::StaleHandle, "RTS research producer does not belong to this facade", "producer"));
2706 if (!scriptRuntime_ || !scriptRuntime_->configured || definitions_ == nullptr || upgrade.empty())
2708 DiagnosticCode::InvalidArgument, "RTS research requires a configured world and upgrade", "upgrade"));
2709 auto* faction = dynamic_cast<Faction*>(producer.faction()->link.resolve());
2710 if (faction == nullptr)
2712 DiagnosticCode::StaleHandle, "RTS research producer faction link is stale", "producer.faction"));
2713 if (std::binary_search(faction->technology()->unlocked.begin(), faction->technology()->unlocked.end(), upgrade))
2715 Diagnostic::error(DiagnosticCode::Conflict, "RTS upgrade is already unlocked", "upgrade"));
2716 auto researchBuildings = ecs::View<Building, Building::Faction, Building::Production>();
2717 for (auto it = researchBuildings.begin(); it != researchBuildings.end(); ++it) {
2718 auto [candidateFaction, candidateProduction] = *it;
2719 if (candidateFaction->link.resolve() != faction) continue;
2720 for (int index = 0; index < static_cast<int>(candidateProduction->values.taskCount()); ++index) {
2721 auto task = candidateProduction->values.taskAt(index);
2722 if (task && task->get().kind == "research" && task->get().product == upgrade &&
2723 task->get().state != production::TaskState::Cancelled &&
2724 task->get().state != production::TaskState::Failed &&
2725 task->get().state != production::TaskState::Completed)
2727 DiagnosticCode::Conflict, "RTS upgrade is already queued by this faction", "upgrade"));
2728 }
2729 }
2730 auto resolved = definitions_->resolve("upgrade", upgrade);
2731 if (!resolved) return Result<RTSBuildReceipt>::failure(resolved.status());
2732 auto definitionHandle = definitions_->handle("upgrade", upgrade);
2733 if (!definitionHandle) return Result<RTSBuildReceipt>::failure(definitionHandle.status());
2734 auto parsed = Value::fromJson(resolved.value().get().json);
2735 if (!parsed) return Result<RTSBuildReceipt>::failure(parsed.status());
2736 const auto* object = parsed.value().getIf<Value::Object>();
2737 if (object == nullptr)
2739 Diagnostic::error(DiagnosticCode::InvalidArgument, "RTS upgrade definition must be an object", "upgrade"));
2740 const auto textField = [object](std::string_view name) -> std::string {
2741 const auto found = object->find(std::string(name));
2742 if (found == object->end()) return {};
2743 const auto* value = found->second.getIf<std::string>();
2744 return value == nullptr ? std::string{} : *value;
2745 };
2746 const auto numberField = [object](std::string_view name) -> std::optional<double> {
2747 const auto found = object->find(std::string(name));
2748 if (found == object->end()) return std::nullopt;
2749 if (const auto* integer = found->second.getIf<std::int64_t>()) return static_cast<double>(*integer);
2750 if (const auto* real = found->second.getIf<double>()) return *real;
2751 return std::nullopt;
2752 };
2753 const std::string requiredProducer = textField("producer");
2754 const std::string prerequisite = textField("prerequisiteUpgrade");
2755 const std::string resourceName = textField("costResource");
2756 const auto costNumber = numberField("cost");
2757 const auto researchTime = numberField("researchTime");
2758 if (requiredProducer != producer.definition()->id.name())
2760 Diagnostic::error(DiagnosticCode::Conflict, "RTS building cannot research this upgrade", "producer"));
2761 if (!prerequisite.empty() && !std::binary_search(faction->technology()->unlocked.begin(),
2762 faction->technology()->unlocked.end(), prerequisite))
2764 DiagnosticCode::PreconditionViolation, "RTS research prerequisite is not unlocked", "upgrade"));
2765 if (resourceName.empty() || !costNumber || !researchTime || !std::isfinite(*costNumber) || *costNumber < 0.0 ||
2766 std::floor(*costNumber) != *costNumber || !std::isfinite(*researchTime) || *researchTime <= 0.0)
2768 DiagnosticCode::InvalidArgument, "RTS upgrade cost or research duration is invalid", "upgrade"));
2769 const auto economy = scriptRuntime_->economies.find(faction->identity()->subject.format());
2770 if (economy == scriptRuntime_->economies.end())
2772 Diagnostic::error(DiagnosticCode::NotFound, "RTS research economy was not found", "producer.faction"));
2773 auto cost = resource::CostSpec::single(resourceName, static_cast<std::int64_t>(*costNumber));
2774 auto duration = Duration::fromSeconds(*researchTime);
2775 if (!cost) return Result<RTSBuildReceipt>::failure(cost.status());
2776 if (!duration) return Result<RTSBuildReceipt>::failure(duration.status());
2777 const resource::CostSpec paidCost = cost.value();
2778 const std::string product = upgrade;
2779 auto receipt = build(producer, scriptRuntime_->actions, economy->second->account, std::move(cost).takeValue(),
2780 std::move(upgrade), std::move(duration).takeValue(), "research", priority, {},
2781 std::move(definitionHandle).takeValue());
2782 if (receipt)
2783 scriptRuntime_->paidProduction.push_back({producer.identity()->subject,
2784 {},
2785 "research",
2786 product,
2787 receipt.value().productionTaskId,
2788 receipt.value().orderId,
2789 paidCost});
2790 return receipt;
2791}
2792
2793Result<RTSCancelProductionReceipt> RTS::cancelScriptProduction(Building& producer, int queueIndex) {
2794 if (!owns(buildings_, producer))
2796 Diagnostic::error(DiagnosticCode::StaleHandle, "RTS producer does not belong to this facade", "producer"));
2797 if (!scriptRuntime_ || !scriptRuntime_->configured || queueIndex < -1)
2800 "RTS production cancellation requires a configured world and valid queue index", "queueIndex"));
2801 std::vector<std::string> active;
2802 for (int index = 0; index < static_cast<int>(producer.production()->values.taskCount()); ++index) {
2803 auto task = producer.production()->values.taskAt(index);
2804 if (task && task->get().state != production::TaskState::Completed &&
2805 task->get().state != production::TaskState::Cancelled && task->get().state != production::TaskState::Failed)
2806 active.push_back(task->get().id);
2807 }
2808 if (active.empty())
2810 Diagnostic::error(DiagnosticCode::NotFound, "RTS producer has no cancellable production", "production"));
2811 if (queueIndex < 0) queueIndex = static_cast<int>(active.size()) - 1;
2812 if (queueIndex >= static_cast<int>(active.size()))
2814 Diagnostic::error(DiagnosticCode::NotFound, "RTS production queue index was not found", "queueIndex"));
2815 const auto record = std::find_if(scriptRuntime_->paidProduction.begin(), scriptRuntime_->paidProduction.end(),
2816 [&](const auto& value) {
2817 return value.taskId == active[static_cast<std::size_t>(queueIndex)] &&
2818 value.producer == producer.identity()->subject;
2819 });
2820 if (record == scriptRuntime_->paidProduction.end())
2822 DiagnosticCode::NotFound, "RTS production payment record was not found", "production.task"));
2823 auto* faction = dynamic_cast<Faction*>(producer.faction()->link.resolve());
2824 if (faction == nullptr)
2826 Diagnostic::error(DiagnosticCode::StaleHandle, "RTS producer faction link is stale", "producer.faction"));
2827 const auto economy = scriptRuntime_->economies.find(faction->identity()->subject.format());
2828 if (economy == scriptRuntime_->economies.end())
2830 Diagnostic::error(DiagnosticCode::NotFound, "RTS producer economy was not found", "producer.faction"));
2831 const std::string taskId = record->taskId;
2832 auto cancelled = cancelProduction(producer, economy->second->account, record->taskId, record->orderId,
2833 record->refund, "script production cancelled");
2834 if (!cancelled) return cancelled;
2835 scriptRuntime_->pendingProductionSubjects.erase(taskId);
2836 scriptRuntime_->paidProduction.erase(record);
2837 return cancelled;
2838}
2839
2840Result<void> RTS::setBuildingRally(Building& producer, CommandSpec command, bool groupedReinforcements) const {
2841 if (!owns(buildings_, producer))
2843 DiagnosticCode::StaleHandle, "RTS rally producer does not belong to this facade", "producer"));
2844 auto valid = command.validate();
2845 if (!valid) return valid;
2846 if (command.kind != OrderKind::Move && command.kind != OrderKind::AttackMove)
2848 "RTS rally command must be Move or AttackMove", "command.kind"));
2849 auto& rally = *producer.rally();
2850 rally = {};
2851 rally.enabled = true;
2852 rally.command = std::move(command);
2853 rally.combatGroup = groupedReinforcements ? stableRallyGroup(producer.identity()->subject) : 0;
2855}
2856
2857Result<void> RTS::linkBuildingRally(Building& producer, Building& source) const {
2858 if (!owns(buildings_, producer) || !owns(buildings_, source) || &producer == &source)
2860 DiagnosticCode::StaleHandle, "RTS rally link requires two distinct owned producers", "producer"));
2861 if (producer.faction()->link.resolve() != source.faction()->link.resolve() || !source.rally()->enabled ||
2862 source.rally()->combatGroup == 0)
2864 "RTS rally source must be a grouped friendly rally",
2865 "source.rally"));
2866 auto linked = *source.rally();
2867 linked.transport = {};
2868 linked.minimumTransportLoad = 1;
2869 linked.transportActive = false;
2870 linked.productionSpawnBlocked = false;
2871 linked.blockedProductionTask.clear();
2872 linked.settledProductionTasks.clear();
2873 linked.reinforcements.clear();
2874 linked.reinforcementCapped = false;
2875 linked.reinforcementPolicyPausedTask.clear();
2876 linked.reinforcementCappedSeconds = 0.0f;
2877 *producer.rally() = std::move(linked);
2879}
2880
2881Result<void> RTS::clearBuildingRally(Building& producer) const {
2882 if (!owns(buildings_, producer))
2884 DiagnosticCode::StaleHandle, "RTS rally producer does not belong to this facade", "producer"));
2885 *producer.rally() = {};
2887}
2888
2889Result<void> RTS::setReinforcementLimit(Building& producer, std::size_t maximum) const {
2890 if (!owns(buildings_, producer) || !producer.rally()->enabled || producer.rally()->combatGroup == 0)
2892 "RTS reinforcement limit requires an owned grouped rally",
2893 "producer.rally"));
2894 const auto group = producer.rally()->combatGroup;
2895 auto* faction = producer.faction()->link.resolve();
2896 for (const auto& handle : buildings_) {
2897 auto* building = tryGetCurrent<Building>(handle);
2898 if (building == nullptr || building->faction()->link.resolve() != faction ||
2899 building->rally()->combatGroup != group)
2900 continue;
2901 building->rally()->reinforcementLimit = maximum;
2902 building->rally()->reinforcementCapped = false;
2903 building->rally()->reinforcementCappedSeconds = 0.0f;
2904 }
2906}
2907
2908Result<void> RTS::setReinforcementTypeLimit(Building& producer, std::string unitType, std::size_t maximum) const {
2909 if (!owns(buildings_, producer) || !producer.rally()->enabled || producer.rally()->combatGroup == 0 ||
2910 unitType.empty() || definitions_ == nullptr || !definitions_->resolve("unit", unitType))
2911 return Result<void>::failure(
2913 "RTS reinforcement type limit requires a grouped rally and known unit type", "unitType"));
2914 const auto group = producer.rally()->combatGroup;
2915 auto* faction = producer.faction()->link.resolve();
2916 for (const auto& handle : buildings_) {
2917 auto* building = tryGetCurrent<Building>(handle);
2918 if (building == nullptr || building->faction()->link.resolve() != faction ||
2919 building->rally()->combatGroup != group)
2920 continue;
2921 if (maximum == 0)
2922 building->rally()->reinforcementTypeLimits.erase(unitType);
2923 else
2924 building->rally()->reinforcementTypeLimits[unitType] = maximum;
2925 building->rally()->reinforcementCapped = false;
2926 building->rally()->reinforcementCappedSeconds = 0.0f;
2927 }
2929}
2930
2931Result<void> RTS::setReinforcementTypePriority(Building& producer, std::string unitType, int priority) const {
2932 if (!owns(buildings_, producer) || !producer.rally()->enabled || producer.rally()->combatGroup == 0 ||
2933 unitType.empty() || priority < 0 || definitions_ == nullptr || !definitions_->resolve("unit", unitType))
2936 "RTS reinforcement priority requires a grouped rally, known unit type, and non-negative priority",
2937 "priority"));
2938 const auto group = producer.rally()->combatGroup;
2939 auto* faction = producer.faction()->link.resolve();
2940 for (const auto& handle : buildings_) {
2941 auto* building = tryGetCurrent<Building>(handle);
2942 if (building == nullptr || building->faction()->link.resolve() != faction ||
2943 building->rally()->combatGroup != group)
2944 continue;
2945 if (priority == 0)
2946 building->rally()->reinforcementTypePriorities.erase(unitType);
2947 else
2948 building->rally()->reinforcementTypePriorities[unitType] = priority;
2949 }
2951}
2952
2953Result<void> RTS::setReinforcementFallback(Building& producer, std::string preferred, std::string fallback) const {
2954 if (!owns(buildings_, producer) || !producer.rally()->enabled || producer.rally()->combatGroup == 0 ||
2955 preferred.empty() || preferred == fallback || definitions_ == nullptr ||
2956 !definitions_->resolve("unit", preferred) || (!fallback.empty() && !definitions_->resolve("unit", fallback)))
2959 "RTS reinforcement fallback requires a grouped rally and known distinct unit types", "fallback"));
2960 auto strategy = producer.rally()->reinforcementFallbacks;
2961 if (fallback.empty())
2962 strategy.erase(preferred);
2963 else
2964 strategy[preferred] = fallback;
2965 for (const auto& [start, ignored] : strategy) {
2966 (void)ignored;
2967 std::set<std::string> visited;
2968 std::string current = start;
2969 while (true) {
2970 const auto next = strategy.find(current);
2971 if (next == strategy.end()) break;
2972 if (!visited.insert(current).second)
2974 DiagnosticCode::Conflict, "RTS reinforcement fallback chain contains a cycle", "fallback"));
2975 current = next->second;
2976 }
2977 }
2978 const auto group = producer.rally()->combatGroup;
2979 auto* faction = producer.faction()->link.resolve();
2980 for (const auto& handle : buildings_) {
2981 auto* building = tryGetCurrent<Building>(handle);
2982 if (building != nullptr && building->faction()->link.resolve() == faction &&
2983 building->rally()->combatGroup == group)
2984 building->rally()->reinforcementFallbacks = strategy;
2985 }
2987}
2988
2989Result<void> RTS::setReinforcementAutoCancel(Building& producer, float seconds) const {
2990 if (!owns(buildings_, producer) || !producer.rally()->enabled || producer.rally()->combatGroup == 0 ||
2991 !std::isfinite(seconds) || seconds < 0.0f)
2994 "RTS reinforcement auto-cancel requires a grouped rally and non-negative delay", "seconds"));
2995 const auto group = producer.rally()->combatGroup;
2996 auto* faction = producer.faction()->link.resolve();
2997 for (const auto& handle : buildings_) {
2998 auto* building = tryGetCurrent<Building>(handle);
2999 if (building == nullptr || building->faction()->link.resolve() != faction ||
3000 building->rally()->combatGroup != group)
3001 continue;
3002 building->rally()->reinforcementAutoCancelDelay = seconds;
3003 building->rally()->reinforcementCappedSeconds = 0.0f;
3004 }
3006}
3007
3008Result<void> RTS::setReinforcementTransport(Building& producer, Unit* transport, std::size_t minimumLoad) const {
3009 if (!owns(buildings_, producer))
3011 DiagnosticCode::StaleHandle, "RTS rally producer does not belong to this facade", "producer"));
3012 if (transport == nullptr) {
3013 if (minimumLoad != 0)
3014 return Result<void>::failure(
3016 "RTS clearing a reinforcement transport requires zero minimum load", "minimumLoad"));
3017 producer.rally()->transport = {};
3018 producer.rally()->minimumTransportLoad = 1;
3019 producer.rally()->transportActive = false;
3021 }
3022 if (!owns(units_, *transport) || transport->faction()->link.resolve() != producer.faction()->link.resolve() ||
3023 transport->containment()->capacity == 0 || minimumLoad == 0 ||
3024 minimumLoad > transport->containment()->capacity || transport->containment()->container.isBound())
3027 "RTS reinforcement transport must be an uncontained friendly carrier with a valid minimum load",
3028 "transport"));
3029 const auto handle = ecs::handle_of(transport);
3030 for (const auto& buildingHandle : buildings_) {
3031 auto* building = dynamic_cast<Building*>(ecs::try_get(buildingHandle));
3032 const auto assigned = building == nullptr ? ecs::EntityHandle{} : building->rally()->transport;
3033 const bool sameTransport = assigned.table == handle.table && assigned.type == handle.type &&
3034 assigned.id == handle.id && assigned.generation == handle.generation;
3035 if (building != nullptr && building != &producer && sameTransport)
3036 return Result<void>::failure(
3038 "RTS reinforcement transport is already assigned to another producer", "transport"));
3039 }
3040 producer.rally()->transport = handle;
3041 producer.rally()->minimumTransportLoad = minimumLoad;
3042 producer.rally()->transportActive = false;
3044}
3045
3046Result<void> RTS::cancelScriptAbility(Unit& caster) {
3047 if (!owns(units_, caster))
3049 "RTS ability caster does not belong to this facade", "caster"));
3050 if (!caster.abilities()->channel)
3051 return Result<void>::failure(
3052 Diagnostic::error(DiagnosticCode::NotFound, "RTS unit has no active ability channel", "ability.channel"));
3053 const auto channel = *caster.abilities()->channel;
3054 SubjectRef cancelledTarget;
3055 if (auto* unit = dynamic_cast<Unit*>(ecs::try_get(channel.target)))
3056 cancelledTarget = unit->identity()->subject;
3057 else if (auto* building = dynamic_cast<Building*>(ecs::try_get(channel.target)))
3058 cancelledTarget = building->identity()->subject;
3059 caster.abilities()->channel.reset();
3060 recordLifecycleEvent({LifecycleEventKind::AbilityChannelCancelled, caster.identity()->subject, cancelledTarget,
3061 channel.spec.id, channel.remaining},
3062 SimulationTick(scriptTick()));
3064}
3065
3066Result<std::size_t> RTS::requestFireSupport(Unit& requester, WorldPosition center, float radius, int shotsPerResponder,
3067 std::size_t maxResponders) const {
3068 if (!owns(units_, requester))
3070 DiagnosticCode::StaleHandle, "RTS fire-support requester does not belong to this facade", "requester"));
3071 return FireSupportSystem::request(requester, center, radius, shotsPerResponder, maxResponders);
3072}
3073
3074Result<std::size_t> RTS::cancelFireSupport(Unit& requester) const {
3075 if (!owns(units_, requester))
3077 DiagnosticCode::StaleHandle, "RTS fire-support requester does not belong to this facade", "requester"));
3078 return FireSupportSystem::cancel(requester);
3079}
3080
3081Result<std::size_t> RTS::unloadTransport(Unit& transport, WorldPosition destination) const {
3082 if (!transport.identity()->subject.isValid() || findUnit(transport.identity()->subject) != &transport)
3084 DiagnosticCode::InvalidArgument, "RTS transport is not owned by this composition root", "transport"));
3085 return ContainmentSystem::unload(transport, destination);
3086}
3087
3088Result<std::size_t> RTS::evacuateBuilding(Building& building, WorldPosition destination) const {
3089 if (!building.identity()->subject.isValid() || findBuilding(building.identity()->subject) != &building)
3091 DiagnosticCode::InvalidArgument, "RTS building is not owned by this composition root", "building"));
3092 return ContainmentSystem::evacuate(building, destination);
3093}
3094
3095Result<void> RTS::setUnitCloaked(Unit& unit, bool cloaked) const {
3096 if (!unit.identity()->subject.isValid() || findUnit(unit.identity()->subject) != &unit)
3098 "RTS unit is not owned by this composition root", "unit"));
3099 unit.vision()->cloaked = cloaked;
3101}
3102
3103Result<void> RTS::queueScriptCommand(RTSReplayCommand command) {
3104 if (!scriptRuntime_ || !scriptRuntime_->configured)
3106 DiagnosticCode::Conflict, "RTS script world must be configured before queuing commands", "scriptWorld"));
3107 return scriptRuntime_->commandLog.queue(std::move(command), SimulationTick{scriptRuntime_->nextTick});
3108}
3109
3110Result<std::string> RTS::exportScriptCommandLog() const {
3111 if (!scriptRuntime_)
3113 Diagnostic::error(DiagnosticCode::Conflict, "RTS script runtime is not configured", "scriptWorld"));
3114 return Result<std::string>::success(scriptRuntime_->commandLog.exportText(), Status::success(StatusCode::Applied));
3115}
3116
3117Result<void> RTS::importScriptCommandLog(std::string_view text, bool clearExisting) {
3118 if (!scriptRuntime_ || !scriptRuntime_->configured)
3120 DiagnosticCode::Conflict, "RTS script world must be configured before importing commands", "scriptWorld"));
3121 return scriptRuntime_->commandLog.importText(text, SimulationTick{scriptRuntime_->nextTick}, clearExisting);
3122}
3123
3124std::uint64_t RTS::scriptTick() const noexcept {
3125 return scriptRuntime_ == nullptr || scriptRuntime_->nextTick == 0 ? 0 : scriptRuntime_->nextTick - 1;
3126}
3127
3128Result<void> RTS::captureScriptCheckpoint(std::string name) {
3129 if (!scriptRuntime_ || !scriptRuntime_->configured)
3130 return Result<void>::failure(
3132 "RTS script world must be configured before capturing a checkpoint", "scriptWorld"));
3133 if (name.empty())
3134 return Result<void>::failure(
3135 Diagnostic::error(DiagnosticCode::InvalidArgument, "RTS checkpoint name must not be empty", "name"));
3136 auto roots = snapshotState();
3137 if (!roots) return Result<void>::failure(roots.status());
3138
3139 ScriptRuntime::Checkpoint checkpoint;
3140 auto crowdState = scriptRuntime_->crowd.captureSnapshot();
3141 if (!crowdState) return Result<void>::failure(crowdState.status());
3142 checkpoint.crowdState = std::move(crowdState).takeValue();
3143 checkpoint.roots = std::move(roots).takeValue();
3144 checkpoint.pendingProductionSubjects = scriptRuntime_->pendingProductionSubjects;
3145 checkpoint.paidProduction = scriptRuntime_->paidProduction;
3146 checkpoint.paidConstruction = scriptRuntime_->paidConstruction;
3147 checkpoint.commandLog = scriptRuntime_->commandLog;
3148 checkpoint.nextTick = scriptRuntime_->nextTick;
3149 checkpoint.aiProductionSequence = scriptRuntime_->aiProductionSequence;
3150 for (const auto& [key, slot] : scriptRuntime_->economies)
3151 checkpoint.economies.emplace(key, slot->ledger.snapshot());
3152 for (const auto& [key, fov] : scriptRuntime_->fovs)
3153 if (fov) checkpoint.fovs.emplace(key, fov->snapshot());
3154 checkpoint.navigationCosts.reserve(static_cast<std::size_t>(scriptRuntime_->width * scriptRuntime_->height));
3155 for (int y = 0; y < scriptRuntime_->height; ++y)
3156 for (int x = 0; x < scriptRuntime_->width; ++x)
3157 checkpoint.navigationCosts.push_back(scriptRuntime_->pathfinder.getCellCost(x, y));
3158 checkpoint.terrainElevations = scriptRuntime_->terrainElevations;
3159 scriptRuntime_->checkpoints.insert_or_assign(std::move(name), std::move(checkpoint));
3161}
3162
3163Result<void> RTS::restoreScriptCheckpoint(std::string_view name) {
3164 if (!scriptRuntime_ || !scriptRuntime_->configured)
3165 return Result<void>::failure(
3167 "RTS script world must be configured before restoring a checkpoint", "scriptWorld"));
3168 const auto found = scriptRuntime_->checkpoints.find(std::string(name));
3169 if (found == scriptRuntime_->checkpoints.end())
3170 return Result<void>::failure(
3171 Diagnostic::error(DiagnosticCode::NotFound, "RTS script checkpoint was not found", "name"));
3172 const auto& checkpoint = found->second;
3173 auto crowdRestore = scriptRuntime_->crowd.prepareRestore(checkpoint.crowdState);
3174 if (!crowdRestore) return Result<void>::failure(crowdRestore.status());
3175 const auto expectedCells = static_cast<std::size_t>(scriptRuntime_->width * scriptRuntime_->height);
3176 if (checkpoint.navigationCosts.size() != expectedCells || checkpoint.terrainElevations.size() != expectedCells)
3177 return Result<void>::failure(
3178 Diagnostic::error(DiagnosticCode::Conflict, "RTS checkpoint grid dimensions do not match", "grid"));
3179 for (const auto& [key, snapshot] : checkpoint.fovs) {
3180 const auto current = scriptRuntime_->fovs.find(key);
3181 if (current == scriptRuntime_->fovs.end() || !current->second || snapshot.width != scriptRuntime_->width ||
3182 snapshot.height != scriptRuntime_->height)
3183 return Result<void>::failure(
3184 Diagnostic::error(DiagnosticCode::Conflict, "RTS checkpoint fog topology does not match", "fog"));
3185 }
3186 const auto containsPlayer = [this](SubjectRef subject) {
3187 return std::any_of(players_.begin(), players_.end(), [subject](const ecs::EntityHandle& handle) {
3188 auto* player = tryGetCurrent<Player>(handle);
3189 return player != nullptr && player->identity()->subject == subject;
3190 });
3191 };
3192 const bool exactTopology =
3193 checkpoint.roots.units.size() == unitCount() && checkpoint.roots.buildings.size() == buildingCount() &&
3194 checkpoint.roots.resourceNodes.size() == resourceNodeCount() &&
3195 checkpoint.roots.players.size() == playerCount() && checkpoint.roots.factions.size() == factionCount() &&
3196 checkpoint.roots.matches.size() == matchCount() &&
3197 std::all_of(checkpoint.roots.units.begin(), checkpoint.roots.units.end(),
3198 [this](const auto& value) { return findUnit(value.subject) != nullptr; }) &&
3199 std::all_of(checkpoint.roots.buildings.begin(), checkpoint.roots.buildings.end(),
3200 [this](const auto& value) { return findBuilding(value.subject) != nullptr; }) &&
3201 std::all_of(checkpoint.roots.resourceNodes.begin(), checkpoint.roots.resourceNodes.end(),
3202 [this](const auto& value) { return findResourceNode(value.subject) != nullptr; }) &&
3203 std::all_of(checkpoint.roots.players.begin(), checkpoint.roots.players.end(),
3204 [&](const auto& value) { return containsPlayer(value.subject); }) &&
3205 std::all_of(checkpoint.roots.factions.begin(), checkpoint.roots.factions.end(),
3206 [this](const auto& value) { return findFaction(value.subject) != nullptr; }) &&
3207 std::all_of(checkpoint.roots.matches.begin(), checkpoint.roots.matches.end(),
3208 [this](const auto& value) { return findMatch(value.subject) != nullptr; });
3209
3210 if (exactTopology) {
3211 auto restored = restoreState(checkpoint.roots);
3212 if (!restored) return restored;
3213 } else {
3214 // Validate the complete graph before touching the live roots. The staged
3215 // module also verifies definition-backed weapon materialization.
3216 {
3217 RTS validator;
3218 validator.setDefinitionRegistry(&scriptRuntime_->definitions);
3219 auto valid = validator.rebuildState(checkpoint.roots);
3220 if (!valid) return valid;
3221 }
3222 auto rollbackRoots = snapshotState();
3223 if (!rollbackRoots) return Result<void>::failure(rollbackRoots.status());
3224 setCrowdProvider(nullptr);
3225 setCombatProviders(nullptr, nullptr);
3226 clearOwnedRoots();
3227 auto rebuilt = rebuildState(checkpoint.roots);
3228 if (!rebuilt) {
3229 const Status failureStatus = rebuilt.status();
3230 clearOwnedRoots();
3231 auto rollback = rebuildState(rollbackRoots.value());
3232 setCrowdProvider(&scriptRuntime_->crowd);
3233 setCombatProviders(&scriptRuntime_->sensing, &scriptRuntime_->damage);
3234 auto rebound = rebindScriptRootProviders();
3235 if (!rollback || !rebound)
3236 return Result<void>::failure(
3238 "RTS checkpoint restore and live-state rollback both failed", "checkpoint"));
3239 return Result<void>::failure(failureStatus);
3240 }
3241 setCrowdProvider(&scriptRuntime_->crowd);
3242 setCombatProviders(&scriptRuntime_->sensing, &scriptRuntime_->damage);
3243 auto rebound = rebindScriptRootProviders();
3244 if (!rebound) return rebound;
3245 }
3246
3247 std::size_t cell = 0;
3248 for (int y = 0; y < scriptRuntime_->height; ++y) {
3249 for (int x = 0; x < scriptRuntime_->width; ++x, ++cell) {
3250 const float cost = checkpoint.navigationCosts[cell];
3251 const bool blocked = cost <= 0.0f;
3252 scriptRuntime_->pathfinder.setBlocked(x, y, blocked);
3253 scriptRuntime_->crowd.setBlocked(x, y, blocked);
3254 if (!blocked) {
3255 scriptRuntime_->pathfinder.setCellCost(x, y, cost);
3256 scriptRuntime_->crowd.setCellCost(x, y, cost);
3257 }
3258 for (auto& [faction, fov] : scriptRuntime_->fovs) {
3259 (void)faction;
3260 if (fov) fov->setOpaque(x, y, blocked);
3261 }
3262 }
3263 }
3264 scriptRuntime_->terrainElevations = checkpoint.terrainElevations;
3265 for (auto& [faction, fov] : scriptRuntime_->fovs) {
3266 (void)faction;
3267 if (!fov) continue;
3268 fov->setMode("heightmap");
3269 fov->setEyeOffset(1.0f);
3270 fov->setCliffBlock(0.0f);
3271 for (int y = 0; y < scriptRuntime_->height; ++y)
3272 for (int x = 0; x < scriptRuntime_->width; ++x)
3273 fov->setElevation(
3274 x, y, checkpoint.terrainElevations[static_cast<std::size_t>(y * scriptRuntime_->width + x)]);
3275 }
3276 std::erase_if(scriptRuntime_->economies,
3277 [&](const auto& entry) { return !checkpoint.economies.contains(entry.first); });
3278 std::erase_if(scriptRuntime_->fovs, [&](const auto& entry) { return !checkpoint.fovs.contains(entry.first); });
3279 for (const auto& [key, snapshot] : checkpoint.economies) {
3280 const auto current = scriptRuntime_->economies.find(key);
3281 if (current == scriptRuntime_->economies.end())
3283 DiagnosticCode::Conflict, "RTS checkpoint economy topology does not match", "economy"));
3284 current->second->ledger.restore(snapshot);
3285 }
3286 for (const auto& [key, snapshot] : checkpoint.fovs) {
3287 auto restored = scriptRuntime_->fovs.at(key)->restore(snapshot);
3288 if (!restored) return restored;
3289 }
3290 scriptRuntime_->pendingProductionSubjects = checkpoint.pendingProductionSubjects;
3291 scriptRuntime_->paidProduction = checkpoint.paidProduction;
3292 scriptRuntime_->paidConstruction = checkpoint.paidConstruction;
3293 scriptRuntime_->commandLog = checkpoint.commandLog;
3294 auto crowdCommitted = scriptRuntime_->crowd.commitRestore(std::move(crowdRestore).takeValue());
3295 if (!crowdCommitted) return crowdCommitted;
3296 scriptRuntime_->nextTick = checkpoint.nextTick;
3297 scriptRuntime_->aiProductionSequence = checkpoint.aiProductionSequence;
3298 const SimulationTick restoredTick{checkpoint.nextTick == 0 ? 0 : checkpoint.nextTick - 1};
3299 for (const auto& handle : units_)
3300 if (auto* unit = tryGetCurrent<Unit>(handle)) unit->effects()->values.restoreSchedulerTick(restoredTick);
3301 for (const auto& handle : buildings_)
3302 if (auto* building = tryGetCurrent<Building>(handle))
3303 building->effects()->values.restoreSchedulerTick(restoredTick);
3304 scriptRuntime_->actions.clear();
3305 scriptRuntime_->adapter.clear();
3307}
3308
3309Result<void> RTS::removeScriptCheckpoint(std::string_view name) {
3310 if (!scriptRuntime_ || scriptRuntime_->checkpoints.erase(std::string(name)) == 0)
3311 return Result<void>::failure(
3312 Diagnostic::error(DiagnosticCode::NotFound, "RTS script checkpoint was not found", "name"));
3314}
3315
3316Result<bool> RTS::scriptCellVisible(Faction& faction, int x, int y) const {
3317 if (!scriptRuntime_ || !scriptRuntime_->configured || findFaction(faction.identity()->subject) != &faction)
3318 return Result<bool>::failure(
3320 "RTS fog query requires an owned faction in a configured script world", "faction"));
3321 if (x < 0 || y < 0 || x >= scriptRuntime_->width || y >= scriptRuntime_->height)
3322 return Result<bool>::failure(
3323 Diagnostic::error(DiagnosticCode::InvalidArgument, "RTS fog cell is outside the grid", "cell"));
3324 const auto found = scriptRuntime_->fovs.find(faction.identity()->subject.format());
3325 if (found == scriptRuntime_->fovs.end() || !found->second)
3326 return Result<bool>::failure(
3327 Diagnostic::error(DiagnosticCode::NotFound, "RTS faction fog provider was not found", "faction"));
3328 return Result<bool>::success(found->second->isVisible(x, y), Status::success(StatusCode::Applied));
3329}
3330
3331Result<bool> RTS::scriptCellExplored(Faction& faction, int x, int y) const {
3332 if (!scriptRuntime_ || !scriptRuntime_->configured || findFaction(faction.identity()->subject) != &faction)
3333 return Result<bool>::failure(
3335 "RTS fog query requires an owned faction in a configured script world", "faction"));
3336 if (x < 0 || y < 0 || x >= scriptRuntime_->width || y >= scriptRuntime_->height)
3337 return Result<bool>::failure(
3338 Diagnostic::error(DiagnosticCode::InvalidArgument, "RTS fog cell is outside the grid", "cell"));
3339 const auto found = scriptRuntime_->fovs.find(faction.identity()->subject.format());
3340 if (found == scriptRuntime_->fovs.end() || !found->second)
3341 return Result<bool>::failure(
3342 Diagnostic::error(DiagnosticCode::NotFound, "RTS faction fog provider was not found", "faction"));
3343 return Result<bool>::success(found->second->isExplored(x, y), Status::success(StatusCode::Applied));
3344}
3345
3346Result<Value> RTS::scriptContact(Faction& faction, SubjectRef target) const {
3347 if (findFaction(faction.identity()->subject) != &faction || !target.isValid())
3349 "RTS contact query requires an owned faction and valid target",
3350 "contact"));
3351 const auto* contact = FogOfWarSystem::contact(faction, target);
3352 if (contact == nullptr)
3354 Diagnostic::error(DiagnosticCode::NotFound, "RTS faction contact was not found", "contact"));
3355 return Result<Value>::success(Value(Value::Object{{"subject", contact->subject.format()},
3356 {"kind", contact->kind},
3357 {"x", contact->position.x},
3358 {"y", contact->position.y},
3359 {"age", contact->ageSeconds},
3360 {"visible", contact->visible},
3361 {"detected", contact->detected}}),
3363}
3364
3365void RTS::removeUnitRoot(Unit& unit, UnitRemovalReason reason) {
3366 const auto handle = ecs::handle_of(&unit);
3367 const SubjectRef subject = unit.identity()->subject;
3368 const auto passengers = unit.containment()->occupants;
3369 unit.containment()->occupants.clear();
3370 for (const auto& passengerHandle : passengers) {
3371 auto* passenger = dynamic_cast<Unit*>(ecs::try_get(passengerHandle));
3372 if (passenger != nullptr && passenger != &unit && owns(units_, *passenger)) removeUnitRoot(*passenger);
3373 }
3374
3375 if (reason == UnitRemovalReason::Gameplay && crowd_ != nullptr && crowdLifetime_.isAlive() &&
3376 unit.crowd()->link.isBound())
3377 crowd_->removeNamedAgent(unit.crowd()->link.key());
3378 const std::string subjectKey = subject.format();
3379 if (reason != UnitRemovalReason::SpawnRollback) {
3380 if (sensing_ != nullptr) sensing_->remove(subjectKey).ignore("best-effort RTS sensing cleanup");
3381 combatState_.mirroredSubjects.erase(subjectKey);
3382 combatState_.blockedSubjects.erase(subjectKey);
3383 }
3384
3385 if (reason != UnitRemovalReason::GameplayReferencesPrepared) {
3386 for (const auto& nodeHandle : resourceNodes_) {
3387 if (auto* node = dynamic_cast<ResourceNode*>(ecs::try_get(nodeHandle)))
3388 std::erase_if(node->harvest()->workers, [&](const auto& value) { return sameHandle(value, handle); });
3389 }
3390 for (const auto& buildingHandle : buildings_) {
3391 auto* building = dynamic_cast<Building*>(ecs::try_get(buildingHandle));
3392 if (building == nullptr) continue;
3393 std::erase_if(building->construction()->builders,
3394 [&](const auto& value) { return sameHandle(value, handle); });
3395 std::erase_if(building->garrison()->occupants,
3396 [&](const auto& value) { return sameHandle(value, handle); });
3397 std::erase_if(building->rally()->reinforcements,
3398 [&](const auto& value) { return sameHandle(value, handle); });
3399 if (sameHandle(building->rally()->transport, handle)) {
3400 building->rally()->transport = {};
3401 building->rally()->transportActive = false;
3402 }
3403 building->capture()->blockedByGarrison = !building->garrison()->occupants.empty();
3404 }
3405 for (const auto& otherHandle : units_) {
3406 auto* other = dynamic_cast<Unit*>(ecs::try_get(otherHandle));
3407 if (other == nullptr || other == &unit) continue;
3408 std::erase_if(other->containment()->occupants,
3409 [&](const auto& value) { return sameHandle(value, handle); });
3410 if (other->containment()->container.isBound() &&
3411 sameHandle(other->containment()->container.handle(), handle))
3412 other->containment()->container = {};
3413 if (sameHandle(other->combat()->target, handle)) other->combat()->target = {};
3414 if (sameHandle(other->tactics()->escortTarget, handle)) other->tactics()->escortTarget = {};
3415 if (sameHandle(other->supply()->assignedTarget, handle)) other->supply()->assignedTarget = {};
3416 if (sameHandle(other->supply()->convoyLeader, handle)) other->supply()->convoyLeader = {};
3417 }
3418 for (const auto& factionHandle : factions_) {
3419 if (auto* faction = dynamic_cast<Faction*>(ecs::try_get(factionHandle)))
3420 std::erase_if(faction->members()->units, [&](const auto& value) { return sameHandle(value, handle); });
3421 }
3422 for (const auto& playerHandle : players_) {
3423 if (auto* player = dynamic_cast<Player*>(ecs::try_get(playerHandle)))
3424 std::erase_if(player->selection()->units, [&](const auto& value) { return sameHandle(value, handle); });
3425 }
3426 }
3427 const auto weaponHandle = unit.weapon()->link.handle();
3428 if (auto* weapon = dynamic_cast<weapon::WeaponEntity*>(unit.weapon()->link.resolve())) weapon->release();
3429 if (reason != UnitRemovalReason::GameplayReferencesPrepared) {
3430 std::erase_if(weapons_, [&](const auto& value) { return sameHandle(value, weaponHandle); });
3431 std::erase_if(units_, [&](const auto& value) { return sameHandle(value, handle); });
3432 }
3433 if (scriptRuntime_ && reason != UnitRemovalReason::SpawnRollback)
3434 std::erase_if(scriptRuntime_->paidProduction,
3435 [&](const auto& value) { return value.resultSubject == subject; });
3436 unit.release();
3437}
3438
3439void RTS::removeBuildingRoot(Building& building, bool destroyOccupants) {
3440 const auto handle = ecs::handle_of(&building);
3441 const SubjectRef subject = building.identity()->subject;
3442 const std::string subjectKey = subject.format();
3443 if (sensing_ != nullptr) sensing_->remove(subjectKey).ignore("best-effort RTS sensing cleanup");
3444 combatState_.mirroredSubjects.erase(subjectKey);
3445 combatState_.blockedSubjects.erase(subjectKey);
3446 const auto occupants = building.garrison()->occupants;
3447 building.garrison()->occupants.clear();
3448 building.capture()->blockedByGarrison = false;
3449 for (const auto& occupantHandle : occupants) {
3450 auto* occupant = dynamic_cast<Unit*>(ecs::try_get(occupantHandle));
3451 if (occupant == nullptr || !owns(units_, *occupant)) continue;
3452 occupant->containment()->container = {};
3453 if (destroyOccupants) {
3454 occupant->durability()->alive = false;
3455 occupant->durability()->state.health = 0.0;
3456 removeUnitRoot(*occupant);
3457 } else {
3458 occupant->motion()->x = building.placement()->worldX;
3459 occupant->motion()->y = building.placement()->worldY;
3460 occupant->motion()->arrived = true;
3461 occupant->orders()->values.clear();
3462 }
3463 }
3464 for (const auto& unitHandle : units_) {
3465 auto* unit = dynamic_cast<Unit*>(ecs::try_get(unitHandle));
3466 if (unit == nullptr) continue;
3467 if (unit->containment()->container.isBound() && sameHandle(unit->containment()->container.handle(), handle))
3468 unit->containment()->container = {};
3469 if (sameHandle(unit->combat()->target, handle)) unit->combat()->target = {};
3470 if (sameHandle(unit->tactics()->escortTarget, handle)) unit->tactics()->escortTarget = {};
3471 if (unit->worker()->dropoff.isBound() && sameHandle(unit->worker()->dropoff.handle(), handle))
3472 unit->worker()->dropoff = {};
3473 }
3474 for (const auto& factionHandle : factions_) {
3475 if (auto* faction = dynamic_cast<Faction*>(ecs::try_get(factionHandle)))
3476 std::erase_if(faction->members()->buildings, [&](const auto& value) { return sameHandle(value, handle); });
3477 }
3478 for (const auto& playerHandle : players_) {
3479 if (auto* player = dynamic_cast<Player*>(ecs::try_get(playerHandle)))
3480 std::erase_if(player->selection()->buildings, [&](const auto& value) { return sameHandle(value, handle); });
3481 }
3482 const auto weaponHandle = building.weapon()->link.handle();
3483 if (auto* weapon = dynamic_cast<weapon::WeaponEntity*>(building.weapon()->link.resolve())) weapon->release();
3484 std::erase_if(weapons_, [&](const auto& value) { return sameHandle(value, weaponHandle); });
3485 std::erase_if(buildings_, [&](const auto& value) { return sameHandle(value, handle); });
3486 if (scriptRuntime_) {
3487 std::erase_if(scriptRuntime_->paidConstruction, [&](const auto& value) { return value.building == subject; });
3488 std::erase_if(scriptRuntime_->paidProduction, [&](const auto& value) {
3489 if (value.producer != subject) return false;
3490 scriptRuntime_->pendingProductionSubjects.erase(value.taskId);
3491 return true;
3492 });
3493 }
3494 building.release();
3495}
3496
3497void RTS::removeResourceNodeRoot(ResourceNode& node) {
3498 const auto handle = ecs::handle_of(&node);
3499 for (const auto& workerHandle : node.harvest()->workers) {
3500 auto* worker = dynamic_cast<Unit*>(ecs::try_get(workerHandle));
3501 if (worker != nullptr && worker->worker()->resourceNode.isBound() &&
3502 sameHandle(worker->worker()->resourceNode.handle(), handle)) {
3503 worker->worker()->resourceNode = {};
3504 worker->orders()->values.clear();
3505 }
3506 }
3507 node.harvest()->workers.clear();
3508 std::erase_if(resourceNodes_, [&](const auto& value) { return sameHandle(value, handle); });
3509 node.release();
3510}
3511
3513 if (!subject.isValid())
3515 "RTS removal requires a valid stable identity", "subject"));
3516 if (auto* unit = findUnit(subject)) {
3517 removeUnitRoot(*unit);
3519 }
3520 if (auto* building = findBuilding(subject)) {
3521 removeBuildingRoot(*building, false);
3523 }
3524 if (auto* node = findResourceNode(subject)) {
3525 removeResourceNodeRoot(*node);
3527 }
3528 return Result<void>::failure(
3529 Diagnostic::error(DiagnosticCode::NotFound, "RTS gameplay root identity was not found", "subject"));
3530}
3531
3532Result<std::size_t> RTS::cleanupDestroyed() {
3533 EV_PROFILE_MODULE("rts", "RTS::cleanupDestroyed");
3534 std::vector<ecs::EntityHandle> deadUnits;
3535 std::vector<ecs::EntityHandle> deadBuildings;
3536 for (const auto& handle : units_) {
3537 auto* unit = tryGetCurrent<Unit>(handle);
3538 if (unit != nullptr && (!unit->durability()->alive || unit->durability()->state.health <= 0.0))
3539 deadUnits.push_back(handle);
3540 }
3541 for (const auto& handle : buildings_) {
3542 auto* building = tryGetCurrent<Building>(handle);
3543 if (building != nullptr && (!building->integrity()->alive || building->integrity()->state.health <= 0.0))
3544 deadBuildings.push_back(handle);
3545 }
3546 if (deadUnits.empty() && deadBuildings.empty())
3548 const bool batchReady = deadBuildings.empty() && std::all_of(deadUnits.begin(), deadUnits.end(), [&](auto handle) {
3549 auto* unit = tryGetCurrent<Unit>(handle);
3550 if (!unit || !unit->containment()->occupants.empty()) return false;
3551 if (crowd_ && crowdLifetime_.isAlive() && unit->crowd()->link.isBound()) {
3552 const auto settings = unit->crowd();
3553 if (settings->runtimeBindingKey != settings->link.key() ||
3554 !crowd_->isAgentAlive({settings->runtimeAgent, settings->runtimeOwner}))
3555 return false;
3556 }
3557 return true;
3558 });
3559 if (batchReady) {
3560 auto prepared = prepareUnitRemovalBatch(deadUnits);
3561 if (!prepared) return Result<std::size_t>::failure(prepared.status());
3562 for (auto handle : deadUnits) {
3563 if (auto* unit = tryGetCurrent<Unit>(handle))
3564 removeUnitRoot(*unit, UnitRemovalReason::GameplayReferencesPrepared);
3565 }
3567 }
3568 const auto before = unitCount() + buildingCount();
3569 for (const auto& handle : deadBuildings) {
3570 auto* building = tryGetCurrent<Building>(handle);
3571 if (building == nullptr || !owns(buildings_, *building)) continue;
3572 removeBuildingRoot(*building, true);
3573 }
3574 for (const auto& handle : deadUnits) {
3575 auto* unit = tryGetCurrent<Unit>(handle);
3576 if (unit == nullptr || !owns(units_, *unit)) continue;
3577 removeUnitRoot(*unit);
3578 }
3579 const std::size_t after = unitCount() + buildingCount();
3580 const std::size_t removed = before >= after ? before - after : 0;
3583}
3584
3585std::size_t RTS::unitCount() const noexcept { return countLive<Unit>(units_); }
3586std::size_t RTS::buildingCount() const noexcept { return countLive<Building>(buildings_); }
3587std::size_t RTS::resourceNodeCount() const noexcept { return countLive<ResourceNode>(resourceNodes_); }
3588std::size_t RTS::playerCount() const noexcept { return countLive<Player>(players_); }
3589std::size_t RTS::factionCount() const noexcept { return countLive<Faction>(factions_); }
3590std::size_t RTS::matchCount() const noexcept { return countLive<Match>(matches_); }
3591
3592Faction* RTS::findFaction(SubjectRef subject) const noexcept { return findSubject<Faction>(factions_, subject); }
3593Match* RTS::findMatch(SubjectRef subject) const noexcept { return findSubject<Match>(matches_, subject); }
3594
3595Player* RTS::resolvePlayer(SubjectRef subject) const noexcept {
3596 for (const auto& handle : players_) {
3597 auto* player = tryGetCurrent<Player>(handle);
3598 if (player && player->identity()->subject == subject) return player;
3599 }
3600 return nullptr;
3601}
3602
3603Unit* RTS::resolveUnit(SubjectRef subject) const noexcept {
3604 for (const auto& handle : units_) {
3605 auto* unit = tryGetCurrent<Unit>(handle);
3606 if (unit && unit->identity()->subject == subject) return unit;
3607 }
3608 return nullptr;
3609}
3610
3611void RTS::expose(ssq::Table& table) {
3612 auto cls = table.addClass(name, ssq::Class::Ctor<RTS()>(), true);
3613 expose(cls);
3614}
3615
3616void RTS::expose(ssq::Class& cls) {
3617 cls.addFunc("getName", &RTS::getName);
3618 // simplesquirrel's member-function binder predates noexcept member
3619 // pointers; keep the C++ query APIs noexcept and adapt them at the script
3620 // boundary with the same object-pointer convention used by other modules.
3621 cls.addFunc("unitCount", [](RTS* self) { return self->unitCount(); });
3622 cls.addFunc("buildingCount", [](RTS* self) { return self->buildingCount(); });
3623 cls.addFunc("resourceNodeCount", [](RTS* self) { return self->resourceNodeCount(); });
3624 cls.addFunc("playerCount", [](RTS* self) { return self->playerCount(); });
3625 cls.addFunc("factionCount", [](RTS* self) { return self->factionCount(); });
3626 cls.addFunc("matchCount", [](RTS* self) { return self->matchCount(); });
3627 cls.addFunc("scriptTick", [](RTS* self) { return static_cast<std::int64_t>(self->scriptTick()); });
3628 const auto vm = cls.getHandle();
3629 cls.addFunc("configureSettlementRulesJson", [vm](RTS* self, const std::string& json) -> ssq::Table {
3630 if (self == nullptr)
3633 Diagnostic::error(DiagnosticCode::InvalidArgument, "RTS receiver must not be null", "rts")));
3634 auto rules = settlement::SettlementRuleSet::fromJson(json);
3635 if (!rules) return script::projectStatusResult(vm, rules.status());
3636 return script::projectResult(vm, self->configureSettlementRules(rules.value()));
3637 });
3638 cls.addFunc("removeSubject", [vm](RTS* self, const std::string& subjectText) -> ssq::Table {
3639 auto subject = parseScriptSubject(subjectText, "subject");
3640 if (!subject) return script::projectStatusResult(vm, subject.status());
3641 return script::projectResult(vm, self->remove(std::move(subject).takeValue()));
3642 });
3643 cls.addFunc("newFaction", [vm](RTS* self, const std::string& subjectText) -> ssq::Table {
3644 auto subject = parseScriptSubject(subjectText, "subject");
3645 if (!subject) return script::projectStatusResult(vm, subject.status());
3646 return script::projectResult(vm, self->newFaction(std::move(subject).takeValue()),
3647 [](Faction* faction) { return Value(faction->identity()->subject.format()); });
3648 });
3649 cls.addFunc("newMatch", [vm](RTS* self, const std::string& subjectText) -> ssq::Table {
3650 auto subjectValue = parseScriptSubject(subjectText, "subject");
3651 if (!subjectValue) return script::projectStatusResult(vm, subjectValue.status());
3652 return script::projectResult(vm, self->newMatch(std::move(subjectValue).takeValue()),
3653 [](Match* match) { return Value(match->identity()->subject.format()); });
3654 });
3655 cls.addFunc("configureMatch",
3656 [vm](RTS* self, const std::string& matchText, const std::string& ruleText, const std::string& archetype,
3657 float targetValue) -> ssq::Table {
3658 auto matchSubject = parseScriptSubject(matchText, "match");
3659 if (!matchSubject) return script::projectStatusResult(vm, matchSubject.status());
3660 Match* match = self->findMatch(matchSubject.value());
3661 if (match == nullptr)
3664 "RTS match identity was not found", "match")));
3665 VictoryRule rule;
3666 if (ruleText == "annihilation")
3667 rule = VictoryRule::Annihilation;
3668 else if (ruleText == "headquarters")
3669 rule = VictoryRule::DestroyHeadquarters;
3670 else if (ruleText == "resource")
3671 rule = VictoryRule::ResourceTarget;
3672 else if (ruleText == "score")
3673 rule = VictoryRule::ScoreTarget;
3674 else if (ruleText == "mission")
3675 rule = VictoryRule::Mission;
3676 else
3679 "RTS victory rule is invalid", "rule")));
3680 return script::projectResult(
3681 vm, self->configureMatch(*match, rule, archetype, static_cast<double>(targetValue)));
3682 });
3683 cls.addFunc("configureMatchTiming",
3684 [vm](RTS* self, const std::string& matchText, float timeLimitSeconds, bool suddenDeath) -> ssq::Table {
3685 auto matchSubject = parseScriptSubject(matchText, "match");
3686 if (!matchSubject) return script::projectStatusResult(vm, matchSubject.status());
3687 Match* match = self->findMatch(matchSubject.value());
3688 if (match == nullptr)
3691 "RTS match identity was not found", "match")));
3692 auto duration = Duration::fromSeconds(static_cast<double>(timeLimitSeconds));
3693 if (!duration) return script::projectStatusResult(vm, duration.status());
3694 return script::projectResult(vm, self->configureMatchTiming(
3695 *match, std::move(duration).takeValue(), suddenDeath));
3696 });
3697 cls.addFunc(
3698 "addMatchParticipant",
3699 [vm](RTS* self, const std::string& matchText, const std::string& factionText, int team) -> ssq::Table {
3700 auto matchSubject = parseScriptSubject(matchText, "match");
3701 if (!matchSubject) return script::projectStatusResult(vm, matchSubject.status());
3702 auto factionSubject = parseScriptSubject(factionText, "faction");
3703 if (!factionSubject) return script::projectStatusResult(vm, factionSubject.status());
3704 Match* match = self->findMatch(matchSubject.value());
3705 Faction* faction = self->findFaction(factionSubject.value());
3706 if (match == nullptr || faction == nullptr)
3709 DiagnosticCode::NotFound, "RTS match participant identity was not found", "participant")));
3710 return script::projectResult(vm, self->addMatchParticipant(*match, *faction, team));
3711 });
3712 cls.addFunc("addMatchObjectiveJson", [vm](RTS* self, const std::string& matchText,
3713 const std::string& json) -> ssq::Table {
3714 auto matchSubject = parseScriptSubject(matchText, "match");
3715 if (!matchSubject) return script::projectStatusResult(vm, matchSubject.status());
3716 Match* match = self->findMatch(matchSubject.value());
3717 if (match == nullptr)
3720 Diagnostic::error(DiagnosticCode::NotFound, "RTS match identity was not found", "match")));
3721 auto parsed = Value::fromJson(json);
3722 if (!parsed) return script::projectStatusResult(vm, parsed.status());
3723 const auto* object = parsed.value().getIf<Value::Object>();
3724 if (object == nullptr)
3727 "RTS mission objective JSON must be an object", "objective")));
3728 auto requireString = [&](const char* key) -> Result<std::string> {
3729 const auto found = object->find(key);
3730 if (found == object->end() || found->second.getIf<std::string>() == nullptr)
3732 DiagnosticCode::InvalidArgument, "RTS mission objective field missing", key));
3733 return Result<std::string>::success(*found->second.getIf<std::string>());
3734 };
3735 auto optionalString = [&](const char* key) -> std::string {
3736 const auto found = object->find(key);
3737 if (found == object->end() || found->second.getIf<std::string>() == nullptr) return {};
3738 return *found->second.getIf<std::string>();
3739 };
3740 auto optionalBool = [&](const char* key, bool fallback) {
3741 const auto found = object->find(key);
3742 if (found == object->end() || found->second.getIf<bool>() == nullptr) return fallback;
3743 return *found->second.getIf<bool>();
3744 };
3745 auto optionalNumber = [&](const char* key, double fallback) {
3746 const auto found = object->find(key);
3747 if (found == object->end()) return fallback;
3748 if (const auto* asDouble = found->second.getIf<double>()) return *asDouble;
3749 if (const auto* asInt = found->second.getIf<std::int64_t>()) return static_cast<double>(*asInt);
3750 return fallback;
3751 };
3752 auto id = requireString("id");
3753 if (!id) return script::projectStatusResult(vm, id.status());
3754 auto kindText = requireString("kind");
3755 if (!kindText) return script::projectStatusResult(vm, kindText.status());
3756 MissionObjectiveSpec objective;
3757 objective.id = std::move(id).takeValue();
3758 const auto kind = kindText.value();
3759 if (kind == "eliminate")
3760 objective.kind = MissionObjectiveKind::EliminateFaction;
3761 else if (kind == "destroy_building")
3762 objective.kind = MissionObjectiveKind::DestroyBuilding;
3763 else if (kind == "survive")
3764 objective.kind = MissionObjectiveKind::SurviveDuration;
3765 else if (kind == "protect")
3766 objective.kind = MissionObjectiveKind::ProtectSubjects;
3767 else if (kind == "occupy")
3768 objective.kind = MissionObjectiveKind::OccupyBuildings;
3769 else if (kind == "reach_score")
3770 objective.kind = MissionObjectiveKind::ReachScore;
3771 else if (kind == "reach_resource")
3772 objective.kind = MissionObjectiveKind::ReachResource;
3773 else
3776 "RTS mission objective kind is invalid", "kind")));
3777 objective.beneficiaryTeam = static_cast<int>(optionalNumber("beneficiaryTeam", 0.0));
3778 objective.archetype = optionalString("archetype");
3779 objective.resourceType = optionalString("resourceType");
3780 objective.targetValue = optionalNumber("targetValue", 0.0);
3781 objective.endsMatch = optionalBool("endsMatch", true);
3782 objective.failsMatch = optionalBool("failsMatch", true);
3783 if (const auto targetFaction = optionalString("targetFaction"); !targetFaction.empty()) {
3784 auto subject = parseScriptSubject(targetFaction, "targetFaction");
3785 if (!subject) return script::projectStatusResult(vm, subject.status());
3786 objective.targetFaction = std::move(subject).takeValue();
3787 }
3788 if (const auto targetSubject = optionalString("targetSubject"); !targetSubject.empty()) {
3789 auto subject = parseScriptSubject(targetSubject, "targetSubject");
3790 if (!subject) return script::projectStatusResult(vm, subject.status());
3791 objective.targetSubject = std::move(subject).takeValue();
3792 }
3793 const double durationSeconds = optionalNumber("requiredDuration", 0.0);
3794 if (durationSeconds != 0.0) {
3795 auto duration = Duration::fromSeconds(durationSeconds);
3796 if (!duration) return script::projectStatusResult(vm, duration.status());
3797 objective.requiredDuration = std::move(duration).takeValue();
3798 }
3799 const auto subjectsFound = object->find("requiredSubjects");
3800 if (subjectsFound != object->end()) {
3801 const auto* subjects = subjectsFound->second.getIf<Value::Array>();
3802 if (subjects == nullptr)
3805 "RTS requiredSubjects must be an array",
3806 "requiredSubjects")));
3807 for (const auto& entry : *subjects) {
3808 const auto* text = entry.getIf<std::string>();
3809 if (text == nullptr)
3812 "RTS requiredSubjects entries must be strings",
3813 "requiredSubjects")));
3814 auto subject = parseScriptSubject(*text, "requiredSubjects");
3815 if (!subject) return script::projectStatusResult(vm, subject.status());
3816 objective.requiredSubjects.push_back(std::move(subject).takeValue());
3817 }
3818 }
3819 return script::projectResult(vm, self->addMatchObjective(*match, std::move(objective)));
3820 });
3821 cls.addFunc("addMatchTriggerJson", [vm](RTS* self, const std::string& matchText,
3822 const std::string& json) -> ssq::Table {
3823 auto matchSubject = parseScriptSubject(matchText, "match");
3824 if (!matchSubject) return script::projectStatusResult(vm, matchSubject.status());
3825 Match* match = self->findMatch(matchSubject.value());
3826 if (match == nullptr)
3829 Diagnostic::error(DiagnosticCode::NotFound, "RTS match identity was not found", "match")));
3830 auto trigger = MissionScriptSystem::parseTriggerJson(json);
3831 if (!trigger) return script::projectStatusResult(vm, trigger.status());
3832 return script::projectResult(vm, self->addMatchTrigger(*match, std::move(trigger).takeValue()));
3833 });
3834 cls.addFunc("addMatchMonitorJson", [vm](RTS* self, const std::string& matchText,
3835 const std::string& json) -> ssq::Table {
3836 auto matchSubject = parseScriptSubject(matchText, "match");
3837 if (!matchSubject) return script::projectStatusResult(vm, matchSubject.status());
3838 Match* match = self->findMatch(matchSubject.value());
3839 if (match == nullptr)
3842 Diagnostic::error(DiagnosticCode::NotFound, "RTS match identity was not found", "match")));
3843 auto monitor = MissionScriptSystem::parseMonitorJson(json);
3844 if (!monitor) return script::projectStatusResult(vm, monitor.status());
3845 return script::projectResult(vm, self->addMatchMonitor(*match, std::move(monitor).takeValue()));
3846 });
3847 cls.addFunc("addMatchTimer", [vm](RTS* self, const std::string& matchText, const std::string& id,
3848 float seconds, bool repeating, bool start) -> ssq::Table {
3849 auto matchSubject = parseScriptSubject(matchText, "match");
3850 if (!matchSubject) return script::projectStatusResult(vm, matchSubject.status());
3851 Match* match = self->findMatch(matchSubject.value());
3852 if (match == nullptr)
3855 Diagnostic::error(DiagnosticCode::NotFound, "RTS match identity was not found", "match")));
3856 auto duration = Duration::fromSeconds(static_cast<double>(seconds));
3857 if (!duration) return script::projectStatusResult(vm, duration.status());
3858 MissionTimer timer;
3859 timer.id = id;
3860 timer.duration = std::move(duration).takeValue();
3861 timer.repeating = repeating;
3862 timer.running = start;
3863 return script::projectResult(vm, self->addMatchTimer(*match, std::move(timer)));
3864 });
3865 cls.addFunc("setMatchVariable", [vm](RTS* self, const std::string& matchText, const std::string& id,
3866 float value) -> ssq::Table {
3867 auto matchSubject = parseScriptSubject(matchText, "match");
3868 if (!matchSubject) return script::projectStatusResult(vm, matchSubject.status());
3869 Match* match = self->findMatch(matchSubject.value());
3870 if (match == nullptr)
3873 Diagnostic::error(DiagnosticCode::NotFound, "RTS match identity was not found", "match")));
3874 return script::projectResult(vm, self->setMatchVariable(*match, id, static_cast<double>(value)));
3875 });
3876 cls.addFunc("pushMatchCampaignEvent", [vm](RTS* self, const std::string& matchText, const std::string& kindText,
3877 const std::string& id) -> ssq::Table {
3878 auto matchSubject = parseScriptSubject(matchText, "match");
3879 if (!matchSubject) return script::projectStatusResult(vm, matchSubject.status());
3880 Match* match = self->findMatch(matchSubject.value());
3881 if (match == nullptr)
3884 Diagnostic::error(DiagnosticCode::NotFound, "RTS match identity was not found", "match")));
3885 MissionPendingEvent event;
3886 event.id = id;
3887 if (kindText == "custom")
3888 event.kind = MissionTriggerEventKind::Custom;
3889 else if (kindText == "timer_elapsed")
3890 event.kind = MissionTriggerEventKind::TimerElapsed;
3891 else if (kindText == "region_entered")
3892 event.kind = MissionTriggerEventKind::RegionEntered;
3893 else if (kindText == "region_exited")
3894 event.kind = MissionTriggerEventKind::RegionExited;
3895 else if (kindText == "unit_died")
3896 event.kind = MissionTriggerEventKind::UnitDied;
3897 else if (kindText == "building_destroyed")
3898 event.kind = MissionTriggerEventKind::BuildingDestroyed;
3899 else if (kindText == "objective_completed")
3900 event.kind = MissionTriggerEventKind::ObjectiveCompleted;
3901 else if (kindText == "objective_failed")
3902 event.kind = MissionTriggerEventKind::ObjectiveFailed;
3903 else if (kindText == "match_started")
3904 event.kind = MissionTriggerEventKind::MatchStarted;
3905 else if (kindText == "match_finished")
3906 event.kind = MissionTriggerEventKind::MatchFinished;
3907 else
3910 "RTS campaign event kind is invalid", "kind")));
3911 return script::projectResult(vm, self->pushMatchCampaignEvent(*match, std::move(event)));
3912 });
3913 cls.addFunc("clearMatchCampaignActions", [vm](RTS* self, const std::string& matchText) -> ssq::Table {
3914 auto matchSubject = parseScriptSubject(matchText, "match");
3915 if (!matchSubject) return script::projectStatusResult(vm, matchSubject.status());
3916 Match* match = self->findMatch(matchSubject.value());
3917 if (match == nullptr)
3920 Diagnostic::error(DiagnosticCode::NotFound, "RTS match identity was not found", "match")));
3921 return script::projectResult(vm, self->clearMatchCampaignActions(*match));
3922 });
3923 cls.addFunc("startMatch", [vm](RTS* self, const std::string& matchText) -> ssq::Table {
3924 auto matchSubject = parseScriptSubject(matchText, "match");
3925 if (!matchSubject) return script::projectStatusResult(vm, matchSubject.status());
3926 Match* match = self->findMatch(matchSubject.value());
3927 if (match == nullptr)
3930 Diagnostic::error(DiagnosticCode::NotFound, "RTS match identity was not found", "match")));
3931 return script::projectResult(vm, self->startMatch(*match));
3932 });
3933 cls.addFunc(
3934 "surrenderMatch", [vm](RTS* self, const std::string& matchText, const std::string& factionText) -> ssq::Table {
3935 auto matchSubject = parseScriptSubject(matchText, "match");
3936 if (!matchSubject) return script::projectStatusResult(vm, matchSubject.status());
3937 auto factionSubject = parseScriptSubject(factionText, "faction");
3938 if (!factionSubject) return script::projectStatusResult(vm, factionSubject.status());
3939 Match* match = self->findMatch(matchSubject.value());
3940 Faction* faction = self->findFaction(factionSubject.value());
3941 if (match == nullptr || faction == nullptr)
3944 DiagnosticCode::NotFound, "RTS match participant identity was not found", "participant")));
3945 return script::projectResult(vm, self->surrenderMatch(*match, *faction));
3946 });
3947 cls.addFunc("creditMatchScore",
3948 [vm](RTS* self, const std::string& matchText, int team, float amount) -> ssq::Table {
3949 auto matchSubject = parseScriptSubject(matchText, "match");
3950 if (!matchSubject) return script::projectStatusResult(vm, matchSubject.status());
3951 Match* match = self->findMatch(matchSubject.value());
3952 if (match == nullptr)
3955 "RTS match identity was not found", "match")));
3956 return script::projectResult(vm, self->creditMatchScore(*match, team, static_cast<double>(amount)));
3957 });
3958 cls.addFunc("inspectMatch", [vm](RTS* self, const std::string& matchText) -> ssq::Table {
3959 auto matchSubject = parseScriptSubject(matchText, "match");
3960 if (!matchSubject) return script::projectStatusResult(vm, matchSubject.status());
3961 Match* match = self->findMatch(matchSubject.value());
3962 if (match == nullptr)
3965 Diagnostic::error(DiagnosticCode::NotFound, "RTS match identity was not found", "match")));
3966 return script::projectResult(vm, self->inspectMatch(*match), [](Value value) { return value; });
3967 });
3968 cls.addFunc("newUnit",
3969 [vm](RTS* self, const std::string& subjectText, const std::string& definitionText,
3970 const std::string& factionText, float x, float y) -> ssq::Table {
3971 auto subject = parseScriptSubject(subjectText, "subject");
3972 if (!subject) return script::projectStatusResult(vm, subject.status());
3973 auto definition = parseScriptDefinition(definitionText);
3974 if (!definition) return script::projectStatusResult(vm, definition.status());
3975 auto factionSubject = parseScriptSubject(factionText, "faction");
3976 if (!factionSubject) return script::projectStatusResult(vm, factionSubject.status());
3977 Faction* faction = self->findFaction(std::move(factionSubject).takeValue());
3978 if (faction == nullptr)
3981 "RTS script faction was not found", "faction")));
3982 auto created = self->newFactionUnit(*faction, std::move(subject).takeValue(),
3983 std::move(definition).takeValue());
3984 if (!created) return script::projectStatusResult(vm, created.status());
3985 Unit* unit = std::move(created).takeValue();
3986 unit->motion()->x = x;
3987 unit->motion()->y = y;
3989 Value(unit->identity()->subject.format()));
3990 });
3991 cls.addFunc("newBuilding",
3992 [vm](RTS* self, const std::string& subjectText, const std::string& definitionText,
3993 const std::string& factionText, float x, float y) -> ssq::Table {
3994 auto subject = parseScriptSubject(subjectText, "subject");
3995 if (!subject) return script::projectStatusResult(vm, subject.status());
3996 auto definition = parseScriptDefinition(definitionText);
3997 if (!definition) return script::projectStatusResult(vm, definition.status());
3998 auto factionSubject = parseScriptSubject(factionText, "faction");
3999 if (!factionSubject) return script::projectStatusResult(vm, factionSubject.status());
4000 Faction* faction = self->findFaction(std::move(factionSubject).takeValue());
4001 if (faction == nullptr)
4004 "RTS script faction was not found", "faction")));
4005 auto created = self->newFactionBuilding(*faction, std::move(subject).takeValue(),
4006 std::move(definition).takeValue());
4007 if (!created) return script::projectStatusResult(vm, created.status());
4008 Building* building = std::move(created).takeValue();
4009 building->placement()->worldX = x;
4010 building->placement()->worldY = y;
4012 Value(building->identity()->subject.format()));
4013 });
4014 cls.addFunc(
4015 "newResourceNode",
4016 [vm](RTS* self, const std::string& subjectText, const std::string& resource, float amount, float x, float y,
4017 int capacity) -> ssq::Table {
4018 auto subject = parseScriptSubject(subjectText, "subject");
4019 if (!subject) return script::projectStatusResult(vm, subject.status());
4020 if (capacity <= 0)
4022 vm,
4024 "RTS script resource capacity must be positive", "capacity")));
4026 self->newResourceNode(std::move(subject).takeValue(), resource, amount, {x, y},
4027 static_cast<std::size_t>(capacity)),
4028 [](ResourceNode* node) { return Value(node->identity()->subject.format()); });
4029 });
4030 cls.addFunc("inspectState", [vm](RTS* self) -> ssq::Table {
4031 return script::projectStatusResult(vm, Status::success(), self->inspectState());
4032 });
4033 cls.addFunc("inspectFrameEvents", [vm](RTS* self) -> ssq::Table {
4034 return script::projectStatusResult(vm, Status::success(), self->inspectFrameEvents());
4035 });
4036 cls.addFunc("stepScript", [vm](RTS* self, float seconds) -> ssq::Table {
4037 return script::projectResult(vm, self->stepScript(static_cast<double>(seconds)),
4038 [](std::size_t processed) { return Value(static_cast<std::int64_t>(processed)); });
4039 });
4040 cls.addFunc("configureScriptWorld",
4041 [vm](RTS* self, int width, int height, float cellSize, float originX, float originY) -> ssq::Table {
4043 self->configureScriptWorld(width, height, cellSize, originX, originY));
4044 });
4045 cls.addFunc("captureScriptCheckpoint", [vm](RTS* self, const std::string& name) -> ssq::Table {
4046 return script::projectResult(vm, self->captureScriptCheckpoint(name));
4047 });
4048 cls.addFunc("restoreScriptCheckpoint", [vm](RTS* self, const std::string& name) -> ssq::Table {
4049 return script::projectResult(vm, self->restoreScriptCheckpoint(name));
4050 });
4051 cls.addFunc("removeScriptCheckpoint", [vm](RTS* self, const std::string& name) -> ssq::Table {
4052 return script::projectResult(vm, self->removeScriptCheckpoint(name));
4053 });
4054 cls.addFunc("loadScriptContent", [vm](RTS* self, const std::string& json) -> ssq::Table {
4055 return script::projectResult(vm, self->loadScriptContent(json), [](ContentImportReceipt receipt) {
4056 return Value(Value::Object{{"inserted", static_cast<std::int64_t>(receipt.inserted)},
4057 {"replaced", static_cast<std::int64_t>(receipt.replaced)}});
4058 });
4059 });
4060 cls.addFunc("setScriptNavigationBlocked", [vm](RTS* self, int x, int y, bool blocked) -> ssq::Table {
4061 return script::projectResult(vm, self->setScriptNavigationBlocked(x, y, blocked));
4062 });
4063 cls.addFunc("setScriptNavigationCost", [vm](RTS* self, int x, int y, float cost) -> ssq::Table {
4064 return script::projectResult(vm, self->setScriptNavigationCost(x, y, cost));
4065 });
4066 cls.addFunc("setScriptTerrainElevation", [vm](RTS* self, int x, int y, float elevation) -> ssq::Table {
4067 return script::projectResult(vm, self->setScriptTerrainElevation(x, y, elevation));
4068 });
4069 cls.addFunc("scriptTerrainElevation", [vm](RTS* self, int x, int y) -> ssq::Table {
4070 return script::projectResult(vm, self->scriptTerrainElevation(x, y),
4071 [](float elevation) { return Value(static_cast<double>(elevation)); });
4072 });
4073 cls.addFunc("scriptCellVisible", [vm](RTS* self, const std::string& factionText, int x, int y) -> ssq::Table {
4074 auto subjectValue = parseScriptSubject(factionText, "faction");
4075 if (!subjectValue) return script::projectStatusResult(vm, subjectValue.status());
4076 Faction* faction = self->findFaction(subjectValue.value());
4077 if (faction == nullptr)
4080 "RTS fog faction identity was not found", "faction")));
4081 return script::projectResult(vm, self->scriptCellVisible(*faction, x, y),
4082 [](bool visible) { return Value(visible); });
4083 });
4084 cls.addFunc("scriptCellExplored", [vm](RTS* self, const std::string& factionText, int x, int y) -> ssq::Table {
4085 auto subjectValue = parseScriptSubject(factionText, "faction");
4086 if (!subjectValue) return script::projectStatusResult(vm, subjectValue.status());
4087 Faction* faction = self->findFaction(subjectValue.value());
4088 if (faction == nullptr)
4091 "RTS fog faction identity was not found", "faction")));
4092 return script::projectResult(vm, self->scriptCellExplored(*faction, x, y),
4093 [](bool explored) { return Value(explored); });
4094 });
4095 cls.addFunc("scriptContact",
4096 [vm](RTS* self, const std::string& factionText, const std::string& targetText) -> ssq::Table {
4097 auto factionSubject = parseScriptSubject(factionText, "faction");
4098 if (!factionSubject) return script::projectStatusResult(vm, factionSubject.status());
4099 auto targetSubject = parseScriptSubject(targetText, "target");
4100 if (!targetSubject) return script::projectStatusResult(vm, targetSubject.status());
4101 Faction* faction = self->findFaction(factionSubject.value());
4102 if (faction == nullptr)
4105 DiagnosticCode::NotFound, "RTS fog faction identity was not found", "faction")));
4106 return script::projectResult(vm, self->scriptContact(*faction, targetSubject.value()),
4107 [](Value value) { return value; });
4108 });
4109 cls.addFunc("addScriptResource",
4110 [vm](RTS* self, const std::string& factionText, const std::string& resource,
4111 std::int64_t amount) -> ssq::Table {
4112 auto factionSubject = parseScriptSubject(factionText, "faction");
4113 if (!factionSubject) return script::projectStatusResult(vm, factionSubject.status());
4114 Faction* faction = self->findFaction(std::move(factionSubject).takeValue());
4115 if (faction == nullptr)
4118 "RTS script faction was not found", "faction")));
4119 return script::projectResult(vm, self->addScriptResource(*faction, resource, amount));
4120 });
4121 cls.addFunc("scriptResource",
4122 [vm](RTS* self, const std::string& factionText, const std::string& resource) -> ssq::Table {
4123 auto factionSubject = parseScriptSubject(factionText, "faction");
4124 if (!factionSubject) return script::projectStatusResult(vm, factionSubject.status());
4125 Faction* faction = self->findFaction(std::move(factionSubject).takeValue());
4126 if (faction == nullptr)
4129 "RTS script faction was not found", "faction")));
4130 return script::projectResult(vm, self->scriptResource(*faction, resource),
4131 [](std::int64_t amount) { return Value(amount); });
4132 });
4133 cls.addFunc("configureScriptAI",
4134 [vm](RTS* self, const std::string& factionText, const std::string& workerText,
4135 const std::string& armyText, const std::string& targetBuildingText, int desiredWorkers,
4136 int attackThreshold, float thinkInterval, float formationSpacing, bool enabled) -> ssq::Table {
4137 auto factionSubject = parseScriptSubject(factionText, "faction");
4138 auto worker = parseScriptDefinition(workerText);
4139 auto army = parseScriptDefinition(armyText);
4140 auto target = parseScriptDefinition(targetBuildingText);
4141 if (!factionSubject) return script::projectStatusResult(vm, factionSubject.status());
4142 if (!worker) return script::projectStatusResult(vm, worker.status());
4143 if (!army) return script::projectStatusResult(vm, army.status());
4144 if (!target) return script::projectStatusResult(vm, target.status());
4145 Faction* faction = self->findFaction(factionSubject.value());
4146 if (faction == nullptr)
4149 "RTS script AI faction was not found", "faction")));
4150 return script::projectResult(
4151 vm,
4152 self->configureScriptAI(*faction, worker.value(), army.value(), target.value(), desiredWorkers,
4153 attackThreshold, thinkInterval, formationSpacing, enabled));
4154 });
4155 cls.addFunc("queueScriptUnit",
4156 [vm](RTS* self, const std::string& producerText, const std::string& unitSubjectText,
4157 const std::string& definitionText, int priority) -> ssq::Table {
4158 auto producerSubject = parseScriptSubject(producerText, "producer");
4159 if (!producerSubject) return script::projectStatusResult(vm, producerSubject.status());
4160 Building* producer = self->findBuilding(producerSubject.value());
4161 if (producer == nullptr)
4164 "RTS script producer was not found", "producer")));
4165 auto unitSubject = parseScriptSubject(unitSubjectText, "unitSubject");
4166 if (!unitSubject) return script::projectStatusResult(vm, unitSubject.status());
4167 auto definition = parseScriptDefinition(definitionText);
4168 if (!definition) return script::projectStatusResult(vm, definition.status());
4169 return script::projectResult(
4170 vm, self->queueScriptUnit(*producer, unitSubject.value(), definition.value(), priority),
4171 [](RTSBuildReceipt receipt) {
4172 return Value(Value::Object{{"productionTaskId", std::move(receipt.productionTaskId)},
4173 {"orderId", std::move(receipt.orderId)}});
4174 });
4175 });
4176 cls.addFunc(
4177 "queueScriptReinforcement",
4178 [vm](RTS* self, const std::string& producerText, const std::string& unitSubjectText,
4179 const std::string& definitionText, int priority) -> ssq::Table {
4180 auto producerSubject = parseScriptSubject(producerText, "producer");
4181 auto unitSubject = parseScriptSubject(unitSubjectText, "unitSubject");
4182 auto definition = parseScriptDefinition(definitionText);
4183 if (!producerSubject) return script::projectStatusResult(vm, producerSubject.status());
4184 if (!unitSubject) return script::projectStatusResult(vm, unitSubject.status());
4185 if (!definition) return script::projectStatusResult(vm, definition.status());
4186 Building* producer = self->findBuilding(producerSubject.value());
4187 if (producer == nullptr)
4190 DiagnosticCode::NotFound, "RTS script reinforcement producer was not found", "producer")));
4191 return script::projectResult(
4192 vm, self->queueScriptReinforcement(*producer, unitSubject.value(), definition.value(), priority),
4193 [](ReinforcementRequestReceipt receipt) {
4194 return Value(Value::Object{{"requestedProduct", std::move(receipt.requestedProduct)},
4195 {"queuedProduct", std::move(receipt.queuedProduct)},
4196 {"productionTaskId", std::move(receipt.taskId)}});
4197 });
4198 });
4199 cls.addFunc(
4200 "startScriptConstruction",
4201 [vm](RTS* self, const std::string& factionText, const std::string& buildingSubjectText,
4202 const std::string& definitionText, float x, float y, const std::string& builderText) -> ssq::Table {
4203 auto factionSubject = parseScriptSubject(factionText, "faction");
4204 auto buildingSubject = parseScriptSubject(buildingSubjectText, "buildingSubject");
4205 auto definition = parseScriptDefinition(definitionText);
4206 auto builderSubject = parseScriptSubject(builderText, "builder");
4207 if (!factionSubject) return script::projectStatusResult(vm, factionSubject.status());
4208 if (!buildingSubject) return script::projectStatusResult(vm, buildingSubject.status());
4209 if (!definition) return script::projectStatusResult(vm, definition.status());
4210 if (!builderSubject) return script::projectStatusResult(vm, builderSubject.status());
4211 Faction* faction = self->findFaction(factionSubject.value());
4212 Unit* builder = self->findUnit(builderSubject.value());
4213 if (faction == nullptr || builder == nullptr)
4216 "RTS script construction faction or builder was not found",
4217 "construction")));
4218 return script::projectResult(
4219 vm,
4220 self->startScriptConstruction(*faction, buildingSubject.value(), definition.value(), {x, y}, *builder),
4221 [](Building* building) { return Value(building->identity()->subject.format()); });
4222 });
4223 const auto buildingLifecycle = [vm](RTS* self, const std::string& buildingText, bool sell) -> ssq::Table {
4224 auto subjectValue = parseScriptSubject(buildingText, "building");
4225 if (!subjectValue) return script::projectStatusResult(vm, subjectValue.status());
4226 Building* building = self->findBuilding(subjectValue.value());
4227 if (building == nullptr)
4230 Diagnostic::error(DiagnosticCode::NotFound, "RTS script building was not found", "building")));
4231 auto result = sell ? self->sellScriptBuilding(*building) : self->cancelScriptConstruction(*building);
4232 return script::projectResult(vm, std::move(result), [](resource::Receipt) { return Value(true); });
4233 };
4234 cls.addFunc("cancelScriptConstruction",
4235 [buildingLifecycle](RTS* self, const std::string& buildingText) -> ssq::Table {
4236 return buildingLifecycle(self, buildingText, false);
4237 });
4238 cls.addFunc("sellScriptBuilding", [buildingLifecycle](RTS* self, const std::string& buildingText) -> ssq::Table {
4239 return buildingLifecycle(self, buildingText, true);
4240 });
4241 cls.addFunc(
4242 "queueScriptResearch",
4243 [vm](RTS* self, const std::string& producerText, const std::string& upgrade, int priority) -> ssq::Table {
4244 auto producerSubject = parseScriptSubject(producerText, "producer");
4245 if (!producerSubject) return script::projectStatusResult(vm, producerSubject.status());
4246 Building* producer = self->findBuilding(producerSubject.value());
4247 if (producer == nullptr)
4250 "RTS script research producer was not found", "producer")));
4251 return script::projectResult(
4252 vm, self->queueScriptResearch(*producer, upgrade, priority), [](RTSBuildReceipt receipt) {
4253 return Value(Value::Object{{"productionTaskId", std::move(receipt.productionTaskId)},
4254 {"orderId", std::move(receipt.orderId)}});
4255 });
4256 });
4257 cls.addFunc(
4258 "cancelScriptProduction", [vm](RTS* self, const std::string& producerText, int queueIndex) -> ssq::Table {
4259 auto producerSubject = parseScriptSubject(producerText, "producer");
4260 if (!producerSubject) return script::projectStatusResult(vm, producerSubject.status());
4261 Building* producer = self->findBuilding(producerSubject.value());
4262 if (producer == nullptr)
4264 vm, Status::failure(Diagnostic::error(DiagnosticCode::NotFound, "RTS script producer was not found",
4265 "producer")));
4266 return script::projectResult(
4267 vm, self->cancelScriptProduction(*producer, queueIndex), [](RTSCancelProductionReceipt receipt) {
4268 return Value(Value::Object{{"productionTaskId", std::move(receipt.productionTaskId)},
4269 {"orderId", std::move(receipt.orderId)}});
4270 });
4271 });
4272 cls.addFunc("castScriptAbility",
4273 [vm](RTS* self, const std::string& casterText, const std::string& ability,
4274 const std::string& targetText, float x, float y) -> ssq::Table {
4275 auto casterSubject = parseScriptSubject(casterText, "caster");
4276 if (!casterSubject) return script::projectStatusResult(vm, casterSubject.status());
4277 Unit* caster = self->findUnit(casterSubject.value());
4278 if (caster == nullptr)
4281 DiagnosticCode::NotFound, "RTS script ability caster was not found", "caster")));
4283 if (!targetText.empty()) {
4284 auto parsed = parseScriptSubject(targetText, "target");
4285 if (!parsed) return script::projectStatusResult(vm, parsed.status());
4286 target = parsed.value();
4287 }
4288 return script::projectResult(vm, self->castScriptAbility(*caster, ability, target, {x, y}));
4289 });
4290 cls.addFunc("cancelScriptAbility", [vm](RTS* self, const std::string& casterText) -> ssq::Table {
4291 auto casterSubject = parseScriptSubject(casterText, "caster");
4292 if (!casterSubject) return script::projectStatusResult(vm, casterSubject.status());
4293 Unit* caster = self->findUnit(casterSubject.value());
4294 if (caster == nullptr)
4297 "RTS script ability caster was not found", "caster")));
4298 return script::projectResult(vm, self->cancelScriptAbility(*caster));
4299 });
4300 cls.addFunc("setBuildingRally",
4301 [vm](RTS* self, const std::string& producerText, float x, float y, bool attackMove,
4302 bool groupedReinforcements) -> ssq::Table {
4303 auto producerSubject = parseScriptSubject(producerText, "producer");
4304 if (!producerSubject) return script::projectStatusResult(vm, producerSubject.status());
4305 Building* producer = self->findBuilding(producerSubject.value());
4306 if (producer == nullptr)
4309 "RTS rally producer was not found", "producer")));
4310 CommandSpec command;
4311 command.kind = attackMove ? OrderKind::AttackMove : OrderKind::Move;
4312 command.target = {x, y};
4313 return script::projectResult(vm, self->setBuildingRally(*producer, command, groupedReinforcements));
4314 });
4315 cls.addFunc("linkBuildingRally",
4316 [vm](RTS* self, const std::string& producerText, const std::string& sourceText) -> ssq::Table {
4317 auto producerSubject = parseScriptSubject(producerText, "producer");
4318 auto sourceSubject = parseScriptSubject(sourceText, "source");
4319 if (!producerSubject) return script::projectStatusResult(vm, producerSubject.status());
4320 if (!sourceSubject) return script::projectStatusResult(vm, sourceSubject.status());
4321 Building* producer = self->findBuilding(producerSubject.value());
4322 Building* source = self->findBuilding(sourceSubject.value());
4323 if (producer == nullptr || source == nullptr)
4325 vm,
4327 DiagnosticCode::NotFound, "RTS rally producer or source was not found", "building")));
4328 return script::projectResult(vm, self->linkBuildingRally(*producer, *source));
4329 });
4330 cls.addFunc("clearBuildingRally", [vm](RTS* self, const std::string& producerText) -> ssq::Table {
4331 auto producerSubject = parseScriptSubject(producerText, "producer");
4332 if (!producerSubject) return script::projectStatusResult(vm, producerSubject.status());
4333 Building* producer = self->findBuilding(producerSubject.value());
4334 if (producer == nullptr)
4337 Diagnostic::error(DiagnosticCode::NotFound, "RTS rally producer was not found", "producer")));
4338 return script::projectResult(vm, self->clearBuildingRally(*producer));
4339 });
4340 cls.addFunc(
4341 "setReinforcementLimit", [vm](RTS* self, const std::string& producerText, std::int64_t maximum) -> ssq::Table {
4342 if (maximum < 0)
4345 "RTS reinforcement limit must be non-negative", "maximum")));
4346 auto producerSubject = parseScriptSubject(producerText, "producer");
4347 if (!producerSubject) return script::projectStatusResult(vm, producerSubject.status());
4348 Building* producer = self->findBuilding(producerSubject.value());
4349 if (producer == nullptr)
4352 "RTS reinforcement producer was not found", "producer")));
4353 return script::projectResult(vm, self->setReinforcementLimit(*producer, static_cast<std::size_t>(maximum)));
4354 });
4355 cls.addFunc("setReinforcementTypeLimit",
4356 [vm](RTS* self, const std::string& producerText, const std::string& unitType,
4357 std::int64_t maximum) -> ssq::Table {
4358 if (maximum < 0)
4361 "RTS reinforcement type limit must be non-negative",
4362 "maximum")));
4363 auto producerSubject = parseScriptSubject(producerText, "producer");
4364 if (!producerSubject) return script::projectStatusResult(vm, producerSubject.status());
4365 Building* producer = self->findBuilding(producerSubject.value());
4366 if (producer == nullptr)
4369 DiagnosticCode::NotFound, "RTS reinforcement producer was not found", "producer")));
4370 return script::projectResult(
4371 vm, self->setReinforcementTypeLimit(*producer, unitType, static_cast<std::size_t>(maximum)));
4372 });
4373 cls.addFunc(
4374 "setReinforcementTypePriority",
4375 [vm](RTS* self, const std::string& producerText, const std::string& unitType, int priority) -> ssq::Table {
4376 auto producerSubject = parseScriptSubject(producerText, "producer");
4377 if (!producerSubject) return script::projectStatusResult(vm, producerSubject.status());
4378 Building* producer = self->findBuilding(producerSubject.value());
4379 if (producer == nullptr)
4382 "RTS reinforcement producer was not found", "producer")));
4383 return script::projectResult(vm, self->setReinforcementTypePriority(*producer, unitType, priority));
4384 });
4385 cls.addFunc("setReinforcementFallback",
4386 [vm](RTS* self, const std::string& producerText, const std::string& preferred,
4387 const std::string& fallback) -> ssq::Table {
4388 auto producerSubject = parseScriptSubject(producerText, "producer");
4389 if (!producerSubject) return script::projectStatusResult(vm, producerSubject.status());
4390 Building* producer = self->findBuilding(producerSubject.value());
4391 if (producer == nullptr)
4394 DiagnosticCode::NotFound, "RTS reinforcement producer was not found", "producer")));
4395 return script::projectResult(vm, self->setReinforcementFallback(*producer, preferred, fallback));
4396 });
4397 cls.addFunc("setReinforcementAutoCancel",
4398 [vm](RTS* self, const std::string& producerText, float seconds) -> ssq::Table {
4399 auto producerSubject = parseScriptSubject(producerText, "producer");
4400 if (!producerSubject) return script::projectStatusResult(vm, producerSubject.status());
4401 Building* producer = self->findBuilding(producerSubject.value());
4402 if (producer == nullptr)
4405 DiagnosticCode::NotFound, "RTS reinforcement producer was not found", "producer")));
4406 return script::projectResult(vm, self->setReinforcementAutoCancel(*producer, seconds));
4407 });
4408 cls.addFunc(
4409 "setReinforcementTransport",
4410 [vm](RTS* self, const std::string& producerText, const std::string& transportText,
4411 std::int64_t minimumLoad) -> ssq::Table {
4412 if (minimumLoad < 0)
4415 "RTS reinforcement minimum load must be non-negative",
4416 "minimumLoad")));
4417 auto producerSubject = parseScriptSubject(producerText, "producer");
4418 if (!producerSubject) return script::projectStatusResult(vm, producerSubject.status());
4419 Building* producer = self->findBuilding(producerSubject.value());
4420 if (producer == nullptr)
4423 "RTS reinforcement producer was not found", "producer")));
4424 Unit* transport = nullptr;
4425 if (!transportText.empty()) {
4426 auto transportSubject = parseScriptSubject(transportText, "transport");
4427 if (!transportSubject) return script::projectStatusResult(vm, transportSubject.status());
4428 transport = self->findUnit(transportSubject.value());
4429 if (transport == nullptr)
4432 DiagnosticCode::NotFound, "RTS reinforcement transport was not found", "transport")));
4433 }
4434 return script::projectResult(
4435 vm, self->setReinforcementTransport(*producer, transport, static_cast<std::size_t>(minimumLoad)));
4436 });
4437 cls.addFunc("exportScriptCommandLog", [vm](RTS* self) -> ssq::Table {
4438 return script::projectResult(vm, self->exportScriptCommandLog(),
4439 [](std::string value) { return Value(std::move(value)); });
4440 });
4441 cls.addFunc("importScriptCommandLog", [vm](RTS* self, const std::string& text, bool clearExisting) -> ssq::Table {
4442 return script::projectResult(vm, self->importScriptCommandLog(text, clearExisting));
4443 });
4444 cls.addFunc("queueScriptConstructionCommand",
4445 [vm](RTS* self, std::int64_t tick, const std::string& factionText, const std::string& builderText,
4446 const std::string& buildingSubjectText, const std::string& definitionText, float x,
4447 float y) -> ssq::Table {
4448 if (tick < 0)
4451 "RTS replay tick must be non-negative", "tick")));
4452 auto faction = parseScriptSubject(factionText, "faction");
4453 auto builder = parseScriptSubject(builderText, "builder");
4454 auto result = parseScriptSubject(buildingSubjectText, "buildingSubject");
4455 auto definition = parseScriptDefinition(definitionText);
4456 if (!faction) return script::projectStatusResult(vm, faction.status());
4457 if (!builder) return script::projectStatusResult(vm, builder.status());
4458 if (!result) return script::projectStatusResult(vm, result.status());
4459 if (!definition) return script::projectStatusResult(vm, definition.status());
4460 RTSReplayCommand replay;
4461 replay.tick = SimulationTick{static_cast<std::uint64_t>(tick)};
4462 replay.operation = RTSReplayOperation::Construction;
4463 replay.units = {builder.value()};
4464 replay.faction = faction.value();
4465 replay.resultSubject = result.value();
4466 replay.definition = definition.value();
4467 replay.point = {x, y};
4468 return script::projectResult(vm, self->queueScriptCommand(std::move(replay)));
4469 });
4470 cls.addFunc("queueScriptProductionCommand",
4471 [vm](RTS* self, std::int64_t tick, const std::string& producerText, const std::string& unitSubjectText,
4472 const std::string& definitionText, int priority) -> ssq::Table {
4473 if (tick < 0)
4476 "RTS replay tick must be non-negative", "tick")));
4477 auto producer = parseScriptSubject(producerText, "producer");
4478 auto result = parseScriptSubject(unitSubjectText, "unitSubject");
4479 auto definition = parseScriptDefinition(definitionText);
4480 if (!producer) return script::projectStatusResult(vm, producer.status());
4481 if (!result) return script::projectStatusResult(vm, result.status());
4482 if (!definition) return script::projectStatusResult(vm, definition.status());
4483 RTSReplayCommand replay;
4484 replay.tick = SimulationTick{static_cast<std::uint64_t>(tick)};
4485 replay.operation = RTSReplayOperation::Production;
4486 replay.producer = producer.value();
4487 replay.resultSubject = result.value();
4488 replay.definition = definition.value();
4489 replay.priority = priority;
4490 return script::projectResult(vm, self->queueScriptCommand(std::move(replay)));
4491 });
4492 cls.addFunc("queueScriptReinforcementCommand",
4493 [vm](RTS* self, std::int64_t tick, const std::string& producerText, const std::string& unitSubjectText,
4494 const std::string& definitionText, int priority) -> ssq::Table {
4495 if (tick < 0)
4498 "RTS replay tick must be non-negative", "tick")));
4499 auto producer = parseScriptSubject(producerText, "producer");
4500 auto result = parseScriptSubject(unitSubjectText, "unitSubject");
4501 auto definition = parseScriptDefinition(definitionText);
4502 if (!producer) return script::projectStatusResult(vm, producer.status());
4503 if (!result) return script::projectStatusResult(vm, result.status());
4504 if (!definition) return script::projectStatusResult(vm, definition.status());
4505 RTSReplayCommand replay;
4506 replay.tick = SimulationTick{static_cast<std::uint64_t>(tick)};
4507 replay.operation = RTSReplayOperation::ReinforcementProduction;
4508 replay.producer = producer.value();
4509 replay.resultSubject = result.value();
4510 replay.definition = definition.value();
4511 replay.priority = priority;
4512 return script::projectResult(vm, self->queueScriptCommand(std::move(replay)));
4513 });
4514 cls.addFunc("queueScriptResearchCommand",
4515 [vm](RTS* self, std::int64_t tick, const std::string& producerText, const std::string& upgrade,
4516 int priority) -> ssq::Table {
4517 if (tick < 0)
4520 "RTS replay tick must be non-negative", "tick")));
4521 auto producer = parseScriptSubject(producerText, "producer");
4522 if (!producer) return script::projectStatusResult(vm, producer.status());
4523 RTSReplayCommand replay;
4524 replay.tick = SimulationTick{static_cast<std::uint64_t>(tick)};
4525 replay.operation = RTSReplayOperation::Research;
4526 replay.producer = producer.value();
4527 replay.value = upgrade;
4528 replay.priority = priority;
4529 return script::projectResult(vm, self->queueScriptCommand(std::move(replay)));
4530 });
4531 cls.addFunc("queueScriptAbilityCommand",
4532 [vm](RTS* self, std::int64_t tick, const std::string& casterText, const std::string& ability,
4533 const std::string& targetText, float x, float y) -> ssq::Table {
4534 if (tick < 0)
4537 "RTS replay tick must be non-negative", "tick")));
4538 auto caster = parseScriptSubject(casterText, "caster");
4539 if (!caster) return script::projectStatusResult(vm, caster.status());
4541 if (!targetText.empty()) {
4542 auto parsed = parseScriptSubject(targetText, "target");
4543 if (!parsed) return script::projectStatusResult(vm, parsed.status());
4544 target = parsed.value();
4545 }
4546 RTSReplayCommand replay;
4547 replay.tick = SimulationTick{static_cast<std::uint64_t>(tick)};
4548 replay.operation = RTSReplayOperation::Ability;
4549 replay.units = {caster.value()};
4550 replay.value = ability;
4551 replay.targetEntity = target;
4552 replay.point = {x, y};
4553 return script::projectResult(vm, self->queueScriptCommand(std::move(replay)));
4554 });
4555 cls.addFunc("queueScriptCancelProductionCommand",
4556 [vm](RTS* self, std::int64_t tick, const std::string& producerText, int queueIndex) -> ssq::Table {
4557 if (tick < 0)
4560 "RTS replay tick must be non-negative", "tick")));
4561 auto producer = parseScriptSubject(producerText, "producer");
4562 if (!producer) return script::projectStatusResult(vm, producer.status());
4563 RTSReplayCommand replay;
4564 replay.tick = SimulationTick{static_cast<std::uint64_t>(tick)};
4565 replay.operation = RTSReplayOperation::CancelProduction;
4566 replay.producer = producer.value();
4567 replay.priority = queueIndex;
4568 return script::projectResult(vm, self->queueScriptCommand(std::move(replay)));
4569 });
4570 cls.addFunc("queueScriptCancelAbilityCommand",
4571 [vm](RTS* self, std::int64_t tick, const std::vector<std::string>& subjectTexts) -> ssq::Table {
4572 if (tick < 0)
4575 "RTS replay tick must be non-negative", "tick")));
4576 auto subjects = parseScriptSubjects(subjectTexts);
4577 if (!subjects) return script::projectStatusResult(vm, subjects.status());
4578 RTSReplayCommand replay;
4579 replay.tick = SimulationTick{static_cast<std::uint64_t>(tick)};
4580 replay.operation = RTSReplayOperation::CancelAbility;
4581 replay.units = std::move(subjects).takeValue();
4582 return script::projectResult(vm, self->queueScriptCommand(std::move(replay)));
4583 });
4584 cls.addFunc("queueScriptFireSupportCommand",
4585 [vm](RTS* self, std::int64_t tick, const std::string& requesterText, float x, float y, float radius,
4586 int shotsPerResponder, int maxResponders) -> ssq::Table {
4587 if (tick < 0 || maxResponders < 0)
4591 "RTS fire-support tick and responder limit must be non-negative", "fireSupport")));
4592 auto requester = parseScriptSubject(requesterText, "requester");
4593 if (!requester) return script::projectStatusResult(vm, requester.status());
4594 RTSReplayCommand replay;
4595 replay.tick = SimulationTick{static_cast<std::uint64_t>(tick)};
4596 replay.operation = RTSReplayOperation::RequestFireSupport;
4597 replay.producer = requester.value();
4598 replay.point = {x, y};
4599 replay.command.radius = radius;
4600 replay.priority = shotsPerResponder;
4601 replay.limit = static_cast<std::size_t>(maxResponders);
4602 return script::projectResult(vm, self->queueScriptCommand(std::move(replay)));
4603 });
4604 cls.addFunc("queueScriptCancelFireSupportCommand",
4605 [vm](RTS* self, std::int64_t tick, const std::string& requesterText) -> ssq::Table {
4606 if (tick < 0)
4609 "RTS replay tick must be non-negative", "tick")));
4610 auto requester = parseScriptSubject(requesterText, "requester");
4611 if (!requester) return script::projectStatusResult(vm, requester.status());
4612 RTSReplayCommand replay;
4613 replay.tick = SimulationTick{static_cast<std::uint64_t>(tick)};
4614 replay.operation = RTSReplayOperation::CancelFireSupport;
4615 replay.producer = requester.value();
4616 return script::projectResult(vm, self->queueScriptCommand(std::move(replay)));
4617 });
4618 const auto queueBuildingLifecycle = [vm](RTS* self, std::int64_t tick, const std::string& buildingText,
4619 RTSReplayOperation operation) -> ssq::Table {
4620 if (tick < 0)
4623 "RTS replay tick must be non-negative", "tick")));
4624 auto building = parseScriptSubject(buildingText, "building");
4625 if (!building) return script::projectStatusResult(vm, building.status());
4626 RTSReplayCommand replay;
4627 replay.tick = SimulationTick{static_cast<std::uint64_t>(tick)};
4628 replay.operation = operation;
4629 replay.producer = building.value();
4630 return script::projectResult(vm, self->queueScriptCommand(std::move(replay)));
4631 };
4632 cls.addFunc("queueScriptCancelConstructionCommand",
4633 [queueBuildingLifecycle](RTS* self, std::int64_t tick, const std::string& buildingText) -> ssq::Table {
4634 return queueBuildingLifecycle(self, tick, buildingText, RTSReplayOperation::CancelConstruction);
4635 });
4636 cls.addFunc("queueScriptSellBuildingCommand",
4637 [queueBuildingLifecycle](RTS* self, std::int64_t tick, const std::string& buildingText) -> ssq::Table {
4638 return queueBuildingLifecycle(self, tick, buildingText, RTSReplayOperation::SellBuilding);
4639 });
4640 cls.addFunc("queueScriptMove",
4641 [vm](RTS* self, std::int64_t tick, const std::vector<std::string>& subjectTexts, float x,
4642 float y) -> ssq::Table {
4643 if (tick < 0)
4646 "RTS replay tick must be non-negative", "tick")));
4647 auto subjects = parseScriptSubjects(subjectTexts);
4648 if (!subjects) return script::projectStatusResult(vm, subjects.status());
4649 RTSReplayCommand replay;
4650 replay.tick = SimulationTick{static_cast<std::uint64_t>(tick)};
4651 replay.units = std::move(subjects).takeValue();
4652 replay.command.kind = OrderKind::Move;
4653 replay.command.target = {x, y};
4654 replay.formation.kind = FormationKind::Grid;
4655 replay.formation.spacing = 1.0f;
4656 return script::projectResult(vm, self->queueScriptCommand(std::move(replay)));
4657 });
4658 cls.addFunc("queueScriptAttackMove",
4659 [vm](RTS* self, std::int64_t tick, const std::vector<std::string>& subjectTexts, float x,
4660 float y) -> ssq::Table {
4661 if (tick < 0)
4664 "RTS replay tick must be non-negative", "tick")));
4665 auto subjects = parseScriptSubjects(subjectTexts);
4666 if (!subjects) return script::projectStatusResult(vm, subjects.status());
4667 RTSReplayCommand replay;
4668 replay.tick = SimulationTick{static_cast<std::uint64_t>(tick)};
4669 replay.units = std::move(subjects).takeValue();
4670 replay.command.kind = OrderKind::AttackMove;
4671 replay.command.target = {x, y};
4672 replay.formation.kind = FormationKind::Grid;
4673 replay.formation.spacing = 1.0f;
4674 return script::projectResult(vm, self->queueScriptCommand(std::move(replay)));
4675 });
4676 cls.addFunc("queueScriptAttack",
4677 [vm](RTS* self, std::int64_t tick, const std::vector<std::string>& subjectTexts,
4678 const std::string& targetText) -> ssq::Table {
4679 if (tick < 0)
4682 "RTS replay tick must be non-negative", "tick")));
4683 auto subjects = parseScriptSubjects(subjectTexts);
4684 if (!subjects) return script::projectStatusResult(vm, subjects.status());
4685 auto targetSubject = parseScriptSubject(targetText, "target");
4686 if (!targetSubject) return script::projectStatusResult(vm, targetSubject.status());
4687 ecs::Entity* target = self->findUnit(targetSubject.value());
4688 if (target == nullptr) target = self->findBuilding(targetSubject.value());
4689 if (target == nullptr)
4692 DiagnosticCode::NotFound, "RTS replay target identity was not found", "target")));
4693 RTSReplayCommand replay;
4694 replay.tick = SimulationTick{static_cast<std::uint64_t>(tick)};
4695 replay.units = std::move(subjects).takeValue();
4696 replay.command.kind = OrderKind::Attack;
4697 replay.command.targetEntity = ecs::handle_of(target);
4698 replay.targetEntity = targetSubject.value();
4699 return script::projectResult(vm, self->queueScriptCommand(std::move(replay)));
4700 });
4701 cls.addFunc("queueScriptSuppressAreaCommand",
4702 [vm](RTS* self, std::int64_t tick, const std::vector<std::string>& subjectTexts, float startX,
4703 float startY, float endX, float endY, float width, int shotsPerUnit) -> ssq::Table {
4704 if (tick < 0)
4707 "RTS replay tick must be non-negative", "tick")));
4708 auto subjects = parseScriptSubjects(subjectTexts);
4709 if (!subjects) return script::projectStatusResult(vm, subjects.status());
4710 RTSReplayCommand replay;
4711 replay.tick = SimulationTick{static_cast<std::uint64_t>(tick)};
4712 replay.operation = RTSReplayOperation::SuppressArea;
4713 replay.units = std::move(subjects).takeValue();
4714 replay.command.kind = OrderKind::SuppressArea;
4715 replay.command.target = {startX, startY};
4716 replay.command.secondaryTarget = {endX, endY};
4717 replay.command.radius = width;
4718 replay.priority = shotsPerUnit;
4719 return script::projectResult(vm, self->queueScriptCommand(std::move(replay)));
4720 });
4721 cls.addFunc("queueScriptEscortCommand",
4722 [vm](RTS* self, std::int64_t tick, const std::vector<std::string>& subjectTexts,
4723 const std::string& targetText, float guardRadius, float spacing) -> ssq::Table {
4724 if (tick < 0)
4727 "RTS replay tick must be non-negative", "tick")));
4728 auto subjects = parseScriptSubjects(subjectTexts);
4729 if (!subjects) return script::projectStatusResult(vm, subjects.status());
4730 auto target = parseScriptSubject(targetText, "target");
4731 if (!target) return script::projectStatusResult(vm, target.status());
4732 RTSReplayCommand replay;
4733 replay.tick = SimulationTick{static_cast<std::uint64_t>(tick)};
4734 replay.operation = RTSReplayOperation::Escort;
4735 replay.units = std::move(subjects).takeValue();
4736 replay.targetEntity = target.value();
4737 replay.command.kind = OrderKind::Escort;
4738 replay.command.radius = guardRadius;
4739 replay.formation.spacing = spacing;
4740 return script::projectResult(vm, self->queueScriptCommand(std::move(replay)));
4741 });
4742 const auto queueUnitOrder = [vm](RTS* self, std::int64_t tick, const std::vector<std::string>& subjectTexts,
4743 OrderKind kind, WorldPosition point, SubjectRef target, bool append,
4744 float formationSpacing) -> ssq::Table {
4745 if (tick < 0)
4748 "RTS replay tick must be non-negative", "tick")));
4749 if (formationSpacing == 0.0f || !std::isfinite(formationSpacing))
4752 "RTS replay formation spacing must be positive", "spacing")));
4753 auto subjects = parseScriptSubjects(subjectTexts);
4754 if (!subjects) return script::projectStatusResult(vm, subjects.status());
4755 RTSReplayCommand replay;
4756 replay.tick = SimulationTick{static_cast<std::uint64_t>(tick)};
4757 replay.units = std::move(subjects).takeValue();
4758 replay.command.kind = kind;
4759 replay.command.target = point;
4760 replay.command.append = append;
4761 replay.targetEntity = target;
4762 if (formationSpacing > 0.0f) {
4763 replay.formation.kind = FormationKind::Grid;
4764 replay.formation.spacing = formationSpacing;
4765 }
4766 return script::projectResult(vm, self->queueScriptCommand(std::move(replay)));
4767 };
4768 cls.addFunc("queueScriptStopCommand",
4769 [queueUnitOrder](RTS* self, std::int64_t tick, const std::vector<std::string>& subjects) -> ssq::Table {
4770 return queueUnitOrder(self, tick, subjects, OrderKind::Stop, {}, {}, false, -1.0f);
4771 });
4772 cls.addFunc("queueScriptHoldCommand",
4773 [queueUnitOrder](RTS* self, std::int64_t tick, const std::vector<std::string>& subjects) -> ssq::Table {
4774 return queueUnitOrder(self, tick, subjects, OrderKind::HoldPosition, {}, {}, false, -1.0f);
4775 });
4776 cls.addFunc("queueScriptPatrolCommand",
4777 [queueUnitOrder](RTS* self, std::int64_t tick, const std::vector<std::string>& subjects, float x,
4778 float y) -> ssq::Table {
4779 return queueUnitOrder(self, tick, subjects, OrderKind::Patrol, {x, y}, {}, false, -1.0f);
4780 });
4781 cls.addFunc("queueScriptAttackGroundCommand",
4782 [queueUnitOrder](RTS* self, std::int64_t tick, const std::vector<std::string>& subjects, float x,
4783 float y, bool append) -> ssq::Table {
4784 return queueUnitOrder(self, tick, subjects, OrderKind::AttackGround, {x, y}, {}, append, -1.0f);
4785 });
4786 cls.addFunc(
4787 "queueScriptAppendMoveCommand",
4788 [vm, queueUnitOrder](RTS* self, std::int64_t tick, const std::vector<std::string>& subjects, float x, float y,
4789 float spacing) -> ssq::Table {
4790 if (!std::isfinite(spacing) || spacing <= 0.0f)
4793 "RTS replay formation spacing must be positive", "spacing")));
4794 return queueUnitOrder(self, tick, subjects, OrderKind::Move, {x, y}, {}, true, spacing);
4795 });
4796 cls.addFunc(
4797 "queueScriptAppendAttackMoveCommand",
4798 [vm, queueUnitOrder](RTS* self, std::int64_t tick, const std::vector<std::string>& subjects, float x, float y,
4799 float spacing) -> ssq::Table {
4800 if (!std::isfinite(spacing) || spacing <= 0.0f)
4803 "RTS replay formation spacing must be positive", "spacing")));
4804 return queueUnitOrder(self, tick, subjects, OrderKind::AttackMove, {x, y}, {}, true, spacing);
4805 });
4806 const auto queueEntityOrder = [vm, queueUnitOrder](RTS* self, std::int64_t tick,
4807 const std::vector<std::string>& subjects,
4808 const std::string& targetText, OrderKind kind) -> ssq::Table {
4809 auto target = parseScriptSubject(targetText, "target");
4810 if (!target) return script::projectStatusResult(vm, target.status());
4811 return queueUnitOrder(self, tick, subjects, kind, {}, target.value(), false, -1.0f);
4812 };
4813 cls.addFunc("queueScriptRepairCommand",
4814 [queueEntityOrder](RTS* self, std::int64_t tick, const std::vector<std::string>& subjects,
4815 const std::string& target) -> ssq::Table {
4816 return queueEntityOrder(self, tick, subjects, target, OrderKind::Repair);
4817 });
4818 cls.addFunc("queueScriptCaptureCommand",
4819 [queueEntityOrder](RTS* self, std::int64_t tick, const std::vector<std::string>& subjects,
4820 const std::string& target) -> ssq::Table {
4821 return queueEntityOrder(self, tick, subjects, target, OrderKind::Capture);
4822 });
4823 cls.addFunc("queueScriptGarrisonCommand",
4824 [queueEntityOrder](RTS* self, std::int64_t tick, const std::vector<std::string>& subjects,
4825 const std::string& target) -> ssq::Table {
4826 return queueEntityOrder(self, tick, subjects, target, OrderKind::Garrison);
4827 });
4828 cls.addFunc("queueScriptBoardTransportCommand",
4829 [queueEntityOrder](RTS* self, std::int64_t tick, const std::vector<std::string>& subjects,
4830 const std::string& target) -> ssq::Table {
4831 return queueEntityOrder(self, tick, subjects, target, OrderKind::BoardTransport);
4832 });
4833 script_internal::exposeFormationBindings(cls);
4834 script_internal::exposeCrowdSurfaceBindings(cls);
4835 script_internal::exposeEconomyBindings(cls);
4836 script_internal::exposeStageBindings(cls);
4837 cls.addFunc("attackUnits",
4838 [vm](RTS* self, const std::vector<std::string>& subjectTexts, const std::string& targetText,
4839 bool append) -> ssq::Table {
4840 auto subjects = parseScriptSubjects(subjectTexts);
4841 if (!subjects) return script::projectStatusResult(vm, subjects.status());
4842 auto targetSubject = parseScriptSubject(targetText, "target");
4843 if (!targetSubject) return script::projectStatusResult(vm, targetSubject.status());
4844 ecs::Entity* target = self->findUnit(targetSubject.value());
4845 if (target == nullptr) target = self->findBuilding(targetSubject.value());
4846 if (target == nullptr)
4849 DiagnosticCode::NotFound, "RTS attack target identity was not found", "target")));
4850 CommandSpec command;
4851 command.kind = OrderKind::Attack;
4852 command.targetEntity = ecs::handle_of(target);
4853 command.append = append;
4854 return script::projectResult(vm, self->commandUnits(std::move(subjects).takeValue(), command),
4855 fanOutValue);
4856 });
4857 cls.addFunc(
4858 "attackGroundUnits",
4859 [vm](RTS* self, const std::vector<std::string>& subjectTexts, float x, float y, bool append) -> ssq::Table {
4860 auto subjects = parseScriptSubjects(subjectTexts);
4861 if (!subjects) return script::projectStatusResult(vm, subjects.status());
4862 CommandSpec command;
4863 command.kind = OrderKind::AttackGround;
4864 command.target = {x, y};
4865 command.append = append;
4866 return script::projectResult(vm, self->commandUnits(std::move(subjects).takeValue(), command), fanOutValue);
4867 });
4868 cls.addFunc("suppressAreaUnits",
4869 [vm](RTS* self, const std::vector<std::string>& subjectTexts, float startX, float startY, float endX,
4870 float endY, float width, int shotsPerUnit) -> ssq::Table {
4871 auto subjects = parseScriptSubjects(subjectTexts);
4872 if (!subjects) return script::projectStatusResult(vm, subjects.status());
4874 self->suppressArea(std::move(subjects).takeValue(), {startX, startY},
4875 {endX, endY}, width, shotsPerUnit),
4876 fanOutValue);
4877 });
4878 cls.addFunc("escortUnits",
4879 [vm](RTS* self, const std::vector<std::string>& subjectTexts, const std::string& targetText,
4880 float guardRadius, float spacing) -> ssq::Table {
4881 auto subjects = parseScriptSubjects(subjectTexts);
4882 if (!subjects) return script::projectStatusResult(vm, subjects.status());
4883 auto target = parseScriptSubject(targetText, "target");
4884 if (!target) return script::projectStatusResult(vm, target.status());
4885 return script::projectResult(
4886 vm, self->escortUnits(std::move(subjects).takeValue(), target.value(), guardRadius, spacing),
4887 fanOutValue);
4888 });
4889 cls.addFunc("setUnitMovementPriority",
4890 [vm](RTS* self, const std::vector<std::string>& subjectTexts, int priority) -> ssq::Table {
4891 auto subjects = parseScriptSubjects(subjectTexts);
4892 if (!subjects) return script::projectStatusResult(vm, subjects.status());
4893 return script::projectResult(
4894 vm, self->setUnitMovementPriority(std::move(subjects).takeValue(), priority));
4895 });
4896 cls.addFunc("assignWorker",
4897 [vm](RTS* self, const std::string& workerText, const std::string& nodeText,
4898 const std::string& dropoffText) -> ssq::Table {
4899 auto workerSubject = parseScriptSubject(workerText, "worker");
4900 if (!workerSubject) return script::projectStatusResult(vm, workerSubject.status());
4901 auto nodeSubject = parseScriptSubject(nodeText, "node");
4902 if (!nodeSubject) return script::projectStatusResult(vm, nodeSubject.status());
4903 auto dropoffSubject = parseScriptSubject(dropoffText, "dropoff");
4904 if (!dropoffSubject) return script::projectStatusResult(vm, dropoffSubject.status());
4905 auto* worker = self->findUnit(workerSubject.value());
4906 auto* node = self->findResourceNode(nodeSubject.value());
4907 auto* dropoff = self->findBuilding(dropoffSubject.value());
4908 if (worker == nullptr || node == nullptr || dropoff == nullptr)
4910 vm,
4912 DiagnosticCode::NotFound, "RTS worker assignment root was not found", "assignment")));
4913 return script::projectResult(vm, self->assignWorker(*worker, *node, *dropoff));
4914 });
4915 cls.addFunc("setWorkerAutoAssignment",
4916 [vm](RTS* self, const std::vector<std::string>& subjectTexts, bool enabled) -> ssq::Table {
4917 auto subjects = parseScriptSubjects(subjectTexts);
4918 if (!subjects) return script::projectStatusResult(vm, subjects.status());
4919 return script::projectResult(
4920 vm, self->setWorkerAutoAssignment(std::move(subjects).takeValue(), enabled));
4921 });
4922 cls.addFunc("configureAutoConstruction",
4923 [vm](RTS* self, const std::string& factionText, bool enabled, int maxBuildersPerSite,
4924 int reserveWorkers) -> ssq::Table {
4925 auto subject = parseScriptSubject(factionText, "faction");
4926 if (!subject) return script::projectStatusResult(vm, subject.status());
4927 auto* faction = self->findFaction(subject.value());
4928 if (faction == nullptr)
4931 "RTS workforce faction was not found", "faction")));
4932 const auto workforce = faction->workforce();
4933 return script::projectResult(
4934 vm,
4935 self->configureWorkforce(*faction, enabled, maxBuildersPerSite, workforce->autoRepair,
4936 static_cast<int>(workforce->maxRepairersPerBuilding), reserveWorkers));
4937 });
4938 cls.addFunc("configureAutoRepair",
4939 [vm](RTS* self, const std::string& factionText, bool enabled, int maxRepairersPerBuilding,
4940 int reserveWorkers) -> ssq::Table {
4941 auto subject = parseScriptSubject(factionText, "faction");
4942 if (!subject) return script::projectStatusResult(vm, subject.status());
4943 auto* faction = self->findFaction(subject.value());
4944 if (faction == nullptr)
4947 "RTS workforce faction was not found", "faction")));
4948 const auto workforce = faction->workforce();
4949 return script::projectResult(
4950 vm, self->configureWorkforce(*faction, workforce->autoConstruction,
4951 static_cast<int>(workforce->maxBuildersPerSite), enabled,
4952 maxRepairersPerBuilding, reserveWorkers));
4953 });
4954 cls.addFunc(
4955 "assignBuilder", [vm](RTS* self, const std::string& workerText, const std::string& buildingText) -> ssq::Table {
4956 auto workerSubject = parseScriptSubject(workerText, "worker");
4957 if (!workerSubject) return script::projectStatusResult(vm, workerSubject.status());
4958 auto buildingSubject = parseScriptSubject(buildingText, "building");
4959 if (!buildingSubject) return script::projectStatusResult(vm, buildingSubject.status());
4960 auto* worker = self->findUnit(workerSubject.value());
4961 auto* building = self->findBuilding(buildingSubject.value());
4962 if (worker == nullptr || building == nullptr)
4965 "RTS builder assignment root was not found", "assignment")));
4966 return script::projectResult(vm, self->assignBuilder(*worker, *building),
4967 [](std::string id) { return Value(std::move(id)); });
4968 });
4969 cls.addFunc("addUnitReserveAmmo", [vm](RTS* self, const std::string& subjectText, int rounds) -> ssq::Table {
4970 auto subject = parseScriptSubject(subjectText, "unit");
4971 if (!subject) return script::projectStatusResult(vm, subject.status());
4972 auto* unit = self->findUnit(subject.value());
4973 if (unit == nullptr)
4976 "RTS reserve-ammunition unit was not found", "unit")));
4977 return script::projectResult(vm, self->addUnitReserveAmmo(*unit, rounds),
4978 [](int value) { return Value(static_cast<std::int64_t>(value)); });
4979 });
4980 cls.addFunc("addUnitAmmoSupply", [vm](RTS* self, const std::string& subjectText, float rounds) -> ssq::Table {
4981 auto subject = parseScriptSubject(subjectText, "unit");
4982 if (!subject) return script::projectStatusResult(vm, subject.status());
4983 auto* unit = self->findUnit(subject.value());
4984 if (unit == nullptr)
4987 "RTS ammunition-supply unit was not found", "unit")));
4988 return script::projectResult(vm, self->addUnitAmmoSupply(*unit, rounds),
4989 [](float value) { return Value(static_cast<double>(value)); });
4990 });
4991 cls.addFunc("addBuildingAmmoSupply", [vm](RTS* self, const std::string& subjectText, float rounds) -> ssq::Table {
4992 auto subject = parseScriptSubject(subjectText, "building");
4993 if (!subject) return script::projectStatusResult(vm, subject.status());
4994 auto* building = self->findBuilding(subject.value());
4995 if (building == nullptr)
4998 "RTS ammunition-supply building was not found", "building")));
4999 return script::projectResult(vm, self->addBuildingAmmoSupply(*building, rounds),
5000 [](float value) { return Value(static_cast<double>(value)); });
5001 });
5002 cls.addFunc("setUnitAutoResupply", [vm](RTS* self, const std::string& subjectText, bool enabled) -> ssq::Table {
5003 auto subject = parseScriptSubject(subjectText, "unit");
5004 if (!subject) return script::projectStatusResult(vm, subject.status());
5005 auto* unit = self->findUnit(subject.value());
5006 if (unit == nullptr)
5009 "RTS automatic-resupply unit was not found", "unit")));
5010 return script::projectResult(vm, self->setUnitAutoResupply(*unit, enabled));
5011 });
5012 cls.addFunc(
5013 "heal",
5014 [vm](RTS* self, const std::string& sourceText, const std::string& targetText, float amount) -> ssq::Table {
5015 auto source = parseScriptSubject(sourceText, "source");
5016 if (!source) return script::projectStatusResult(vm, source.status());
5017 auto target = parseScriptSubject(targetText, "target");
5018 if (!target) return script::projectStatusResult(vm, target.status());
5019 return script::projectResult(vm, self->heal(source.value(), target.value(), static_cast<double>(amount)),
5020 [](double applied) { return Value(applied); });
5021 });
5022 cls.addFunc(
5023 "applyStatusEffect",
5024 [vm](RTS* self, const std::string& sourceText, const std::string& targetText, const std::string& effect,
5025 float durationOverride) -> ssq::Table {
5026 auto source = parseScriptSubject(sourceText, "source");
5027 if (!source) return script::projectStatusResult(vm, source.status());
5028 auto target = parseScriptSubject(targetText, "target");
5029 if (!target) return script::projectStatusResult(vm, target.status());
5030 return script::projectResult(
5031 vm,
5032 self->applyStatusEffect(source.value(), target.value(), effect, static_cast<double>(durationOverride)),
5033 [](effects::EffectHandle handle) {
5034 return Value(Value::Object{{"instanceId", std::move(handle.instanceId)},
5035 {"generation", static_cast<std::int64_t>(handle.containerGeneration)}});
5036 });
5037 });
5038 cls.addFunc(
5039 "requestFireSupport",
5040 [vm](RTS* self, const std::string& requesterText, float x, float y, float radius, int shotsPerResponder,
5041 int maxResponders) -> ssq::Table {
5042 if (maxResponders < 0)
5045 "RTS fire-support responder limit must be non-negative",
5046 "maxResponders")));
5047 auto requesterSubject = parseScriptSubject(requesterText, "requester");
5048 if (!requesterSubject) return script::projectStatusResult(vm, requesterSubject.status());
5049 auto* requester = self->findUnit(requesterSubject.value());
5050 if (requester == nullptr)
5053 "RTS fire-support requester was not found", "requester")));
5055 self->requestFireSupport(*requester, {x, y}, radius, shotsPerResponder,
5056 static_cast<std::size_t>(maxResponders)),
5057 [](std::size_t count) { return Value(static_cast<std::int64_t>(count)); });
5058 });
5059 cls.addFunc("cancelFireSupport", [vm](RTS* self, const std::string& requesterText) -> ssq::Table {
5060 auto requesterSubject = parseScriptSubject(requesterText, "requester");
5061 if (!requesterSubject) return script::projectStatusResult(vm, requesterSubject.status());
5062 auto* requester = self->findUnit(requesterSubject.value());
5063 if (requester == nullptr)
5066 "RTS fire-support requester was not found", "requester")));
5067 return script::projectResult(vm, self->cancelFireSupport(*requester),
5068 [](std::size_t count) { return Value(static_cast<std::int64_t>(count)); });
5069 });
5070 cls.addFunc(
5071 "patrolUnits",
5072 [vm](RTS* self, const std::vector<std::string>& subjectTexts, float x, float y, float spacing) -> ssq::Table {
5073 auto subjects = parseScriptSubjects(subjectTexts);
5074 if (!subjects) return script::projectStatusResult(vm, subjects.status());
5075 CommandSpec command;
5076 command.kind = OrderKind::Patrol;
5077 command.target = {x, y};
5078 FormationSpec formation;
5079 formation.kind = FormationKind::Grid;
5080 formation.spacing = spacing;
5081 return script::projectResult(vm, self->commandUnits(std::move(subjects).takeValue(), command, formation),
5082 fanOutValue);
5083 });
5084 cls.addFunc(
5085 "repairUnits",
5086 [vm](RTS* self, const std::vector<std::string>& subjectTexts, const std::string& buildingText,
5087 bool append) -> ssq::Table {
5088 auto subjects = parseScriptSubjects(subjectTexts);
5089 if (!subjects) return script::projectStatusResult(vm, subjects.status());
5090 auto targetSubject = parseScriptSubject(buildingText, "building");
5091 if (!targetSubject) return script::projectStatusResult(vm, targetSubject.status());
5092 Building* building = self->findBuilding(targetSubject.value());
5093 if (building == nullptr)
5096 "RTS repair building identity was not found", "building")));
5097 CommandSpec command;
5098 command.kind = OrderKind::Repair;
5099 command.targetEntity = ecs::handle_of(building);
5100 command.target = {building->placement()->worldX, building->placement()->worldY};
5101 command.append = append;
5102 return script::projectResult(vm, self->commandUnits(std::move(subjects).takeValue(), command), fanOutValue);
5103 });
5104 cls.addFunc(
5105 "captureUnits",
5106 [vm](RTS* self, const std::vector<std::string>& subjectTexts, const std::string& buildingText,
5107 bool append) -> ssq::Table {
5108 auto subjects = parseScriptSubjects(subjectTexts);
5109 if (!subjects) return script::projectStatusResult(vm, subjects.status());
5110 auto targetSubject = parseScriptSubject(buildingText, "building");
5111 if (!targetSubject) return script::projectStatusResult(vm, targetSubject.status());
5112 Building* building = self->findBuilding(targetSubject.value());
5113 if (building == nullptr)
5116 "RTS capture building identity was not found", "building")));
5117 CommandSpec command;
5118 command.kind = OrderKind::Capture;
5119 command.targetEntity = ecs::handle_of(building);
5120 command.target = {building->placement()->worldX, building->placement()->worldY};
5121 command.append = append;
5122 return script::projectResult(vm, self->commandUnits(std::move(subjects).takeValue(), command), fanOutValue);
5123 });
5124 cls.addFunc(
5125 "garrisonUnits",
5126 [vm](RTS* self, const std::vector<std::string>& subjectTexts, const std::string& buildingText,
5127 bool append) -> ssq::Table {
5128 auto subjects = parseScriptSubjects(subjectTexts);
5129 if (!subjects) return script::projectStatusResult(vm, subjects.status());
5130 auto targetSubject = parseScriptSubject(buildingText, "building");
5131 if (!targetSubject) return script::projectStatusResult(vm, targetSubject.status());
5132 Building* building = self->findBuilding(targetSubject.value());
5133 if (building == nullptr)
5136 "RTS garrison building identity was not found", "building")));
5137 CommandSpec command;
5138 command.kind = OrderKind::Garrison;
5139 command.targetEntity = ecs::handle_of(building);
5140 command.target = {building->placement()->worldX, building->placement()->worldY};
5141 command.append = append;
5142 return script::projectResult(vm, self->commandUnits(std::move(subjects).takeValue(), command), fanOutValue);
5143 });
5144 cls.addFunc("boardTransportUnits",
5145 [vm](RTS* self, const std::vector<std::string>& subjectTexts, const std::string& transportText,
5146 bool append) -> ssq::Table {
5147 auto subjects = parseScriptSubjects(subjectTexts);
5148 if (!subjects) return script::projectStatusResult(vm, subjects.status());
5149 auto targetSubject = parseScriptSubject(transportText, "transport");
5150 if (!targetSubject) return script::projectStatusResult(vm, targetSubject.status());
5151 Unit* transport = self->findUnit(targetSubject.value());
5152 if (transport == nullptr)
5155 DiagnosticCode::NotFound, "RTS transport identity was not found", "transport")));
5156 CommandSpec command;
5157 command.kind = OrderKind::BoardTransport;
5158 command.targetEntity = ecs::handle_of(transport);
5159 command.target = {transport->motion()->x, transport->motion()->y};
5160 command.append = append;
5161 return script::projectResult(vm, self->commandUnits(std::move(subjects).takeValue(), command),
5162 fanOutValue);
5163 });
5164 cls.addFunc("unloadTransport", [vm](RTS* self, const std::string& transportText, float x, float y) -> ssq::Table {
5165 auto subjectValue = parseScriptSubject(transportText, "transport");
5166 if (!subjectValue) return script::projectStatusResult(vm, subjectValue.status());
5167 Unit* transport = self->findUnit(subjectValue.value());
5168 if (transport == nullptr)
5170 vm, Status::failure(Diagnostic::error(DiagnosticCode::NotFound, "RTS transport identity was not found",
5171 "transport")));
5172 return script::projectResult(vm, self->unloadTransport(*transport, {x, y}),
5173 [](std::size_t released) { return Value(static_cast<std::int64_t>(released)); });
5174 });
5175 cls.addFunc("evacuateBuilding", [vm](RTS* self, const std::string& buildingText, float x, float y) -> ssq::Table {
5176 auto subjectValue = parseScriptSubject(buildingText, "building");
5177 if (!subjectValue) return script::projectStatusResult(vm, subjectValue.status());
5178 Building* building = self->findBuilding(subjectValue.value());
5179 if (building == nullptr)
5181 vm, Status::failure(Diagnostic::error(DiagnosticCode::NotFound, "RTS building identity was not found",
5182 "building")));
5183 return script::projectResult(vm, self->evacuateBuilding(*building, {x, y}),
5184 [](std::size_t released) { return Value(static_cast<std::int64_t>(released)); });
5185 });
5186 cls.addFunc("setUnitCloaked", [vm](RTS* self, const std::string& unitText, bool cloaked) -> ssq::Table {
5187 auto subjectValue = parseScriptSubject(unitText, "unit");
5188 if (!subjectValue) return script::projectStatusResult(vm, subjectValue.status());
5189 Unit* unit = self->findUnit(subjectValue.value());
5190 if (unit == nullptr)
5193 Diagnostic::error(DiagnosticCode::NotFound, "RTS unit identity was not found", "unit")));
5194 return script::projectResult(vm, self->setUnitCloaked(*unit, cloaked));
5195 });
5196 cls.addFunc("stopUnits", [vm](RTS* self, const std::vector<std::string>& subjectTexts) -> ssq::Table {
5197 auto subjects = parseScriptSubjects(subjectTexts);
5198 if (!subjects) return script::projectStatusResult(vm, subjects.status());
5199 CommandSpec command;
5200 command.kind = OrderKind::Stop;
5201 return script::projectResult(vm, self->commandUnits(std::move(subjects).takeValue(), command), fanOutValue);
5202 });
5203 cls.addFunc("holdUnits", [vm](RTS* self, const std::vector<std::string>& subjectTexts) -> ssq::Table {
5204 auto subjects = parseScriptSubjects(subjectTexts);
5205 if (!subjects) return script::projectStatusResult(vm, subjects.status());
5206 CommandSpec command;
5207 command.kind = OrderKind::HoldPosition;
5208 return script::projectResult(vm, self->commandUnits(std::move(subjects).takeValue(), command), fanOutValue);
5209 });
5210}
5211
5212} // namespace eve::rts
double y
double x
LogicalId target
ActionParameterOperation operation
Duration start
Renderer- and ruleset-neutral gameplay action pipeline.
bool & active
float duration
int subject
Definition AnimSmr.cpp:163
std::string selected
std::vector< QuestEvent > pending
int priority
std::vector< std::unique_ptr< ScriptClimbingEventSink > > live
bool applied
eve::resource::CostSpec cost
eve::resource::IResourceAccount * account
HSQUIRRELVM vm
Definition ECS.cpp:38
HSQOBJECT cls
Definition ECS.cpp:39
SQObjectPtr key
Definition ECS.cpp:155
ScriptComponentRecord record
Definition ECS.cpp:228
std::string name
Definition ECS.cpp:154
Resource-account adapter backed by an EconomyLedger.
int instanceId
float maximum[3]
const GltfImportRequest & request
std::uint32_t alive
std::uint32_t capacity
wgpu::PopErrorScopeStatus status
HexVec3 left
HexVec3 right
float elevation
std::uint32_t height
std::uint32_t width
JobScope scope
float ratio
PhysicsJointLink link
bool ordered
std::array< float, 3 > position
std::string to
std::string from
std::string id
std::shared_ptr< std::atomic< bool > > cancelled
Poco::JSON::Object::Ptr result
Snapshot snapshot
std::uint64_t bytes
bool valid
double radius
Definition MeleeHit.cpp:42
float distance
std::vector< std::int32_t > order
#define Module_IMPL(ModuleName, newExpr)
Definition Module.h:27
std::shared_ptr< OceanGpuSpectrum > owner
glm::dvec2 center
glm::dvec3 dx
std::shared_ptr< const OceanSprayFrame > previous
size_t queued
Definition OnnxGpgpu.cpp:60
std::unique_ptr< gpgpu::Sequence > sequence
Definition OnnxGpgpu.cpp:43
std::vector< particles::ParticleRecordEvent > events
std::unique_ptr< ParticleEffect > effect
std::array< uint32_t, 9 > parameters
std::string action
Definition PlayHost.cpp:118
std::vector< ActionSpec > actions
Definition PlayHost.cpp:127
PrimitiveHandle handle
std::string taskId
#define EV_PROFILE_MODULE(module, name)
Profile the enclosing scope, tagged with a module for grouping.
Definition Profile.h:158
std::set< std::string > values
std::map< std::string, Type > variables
Object::Ptr value
std::string hash
float t
const EntityFact * entity
const QuestGenerationArchetype * archetype
std::map< std::string, double > attributes
std::string build
std::string slot
int rounds
std::string attribute
Selective combat-stat adapter for RTS units.
Match-owned campaign trigger host: events, monitors, timers, variables, actions.
RTS module owner and phase-one composition profile entry point.
RoadNetwork resolved
const RoadNode * node
double number
bool found
int created
int removed
std::string text
std::string_view source
size_t end
std::string kind
double current
std::string resource
std::string string
float dy
Definition Shadow.cpp:151
int count
The single Squirrel projection for common Result, Status and Value.
AbilityActivationGroup group
float phase
Cell cell
TacticalUnit * unit
bool placed
std::vector< UnitCandidate > units
SimulationTick tick
Battle::Objectives objectives
std::optional< InteractionSession > session
Definition Tactics.cpp:39
int spacing
bool visible
Json object
uint32_t seed
Definition TreeMesh.cpp:276
float step
Definition TreeMesh.cpp:451
uint32_t index
std::vector< VegetationPresetCommand > commands
Contact contact
glm::vec3 point
Strongly typed Weapon definition/runtime adapter.
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
Signed, fixed-resolution simulation duration in nanoseconds.
Definition Time.h:43
constexpr std::int64_t nanoseconds() const noexcept
Return the exact signed nanosecond representation.
Definition Time.h:69
static Result< Duration > fromSeconds(double seconds)
Convert finite seconds to the nearest nanosecond.
Definition Time.cpp:17
constexpr bool isZero() const noexcept
Whether this duration is exactly zero.
Definition Time.h:75
Owner-thread lifetime observation; cannot retain or access its owner.
Human-readable, scoped identifier in the form namespace:name.
Definition Identity.h:414
const std::string & format() const noexcept
Returns the canonical namespace:name representation.
Definition Identity.h:439
static std::optional< LogicalId > parse(std::string_view text)
Parses a scoped logical name.
Definition Identity.cpp:37
bool isValid() const noexcept
Returns whether this value contains a valid namespace and name.
Definition Identity.h:436
std::string_view name() const noexcept
Returns the name component as a view into this object.
Definition Identity.cpp:64
void value() const
Mark a successful void operation as checked.
Definition Result.h:560
const Status & status() const noexcept
Inspect the structured operation status.
Definition Result.h:521
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
Structured status and zero or more diagnostics for an operation.
Definition Status.h:70
static Status success(StatusCode code=StatusCode::Ok)
Construct a successful status with an explicit non-error outcome.
Definition Status.cpp:19
static Status failure(StatusCode code, Diagnostic diagnostic)
Construct a failed status with one diagnostic.
Definition Status.cpp:28
Strong, domain-neutral reference to a runtime subject.
Definition SubjectRef.h:26
static SubjectRef fromPersistentId(PersistentId id) noexcept
Wrap a persistent identity without changing its bytes.
Definition SubjectRef.h:32
std::string format() const
Return the canonical lower-case UUID spelling.
Definition SubjectRef.h:44
bool isValid() const noexcept
Return whether this reference is valid and non-nil.
Definition SubjectRef.h:38
The canonical owning dynamic value used by data-facing protocols.
Definition Value.h:31
static Result< Value > fromJson(std::string_view json)
Parse one strict JSON value into an owning Value.
Definition Value.cpp:177
std::map< std::string, Value > Object
Definition Value.h:34
std::vector< Value > Array
Definition Value.h:33
Type type() const noexcept
Return the active value kind.
Definition Value.h:94
Deterministic action lifecycle coordinator.
Definition Action.h:540
Owner-thread deterministic damage coordinator.
Definition Damage.h:130
Result< void > configureSettlementRules(const settlement::SettlementRuleSet &rules)
Replace the optional declarative buff/effect rules used by subsequent damage settlements.
Definition Damage.cpp:300
Result< settlement::SettlementResult > heal(CombatState &target, SubjectRef source, double amount) const
Resolve and atomically commit health restoration through the configured settlement pipeline.
Definition Damage.cpp:283
群体行为模块:连续流场寻路 + 海量单位移动/转向/行动 + Boids 鸟群。
Definition Crowd.h:266
Id128 public API.
Definition Identity.h:111
std::array< std::uint8_t, 16 > Bytes
Definition Identity.h:113
Dynamic field-of-view / fog-of-war facade. Phase A: 2D shadowcast + multi-revealer + explored memory....
Definition Fov.h:27
Immutable canonical multi-resource cost.
static eve::Result< CostSpec > create(std::vector< ResourceCost > items)
Validate and canonicalize resource items.
static eve::Result< CostSpec > single(std::string_view resource, std::int64_t amount)
Build a one-resource cost.
Provider-neutral resource account contract.
virtual eve::Result< Receipt > credit(const CostSpec &cost)=0
Atomically credit all items immediately.
virtual eve::Result< Receipt > debit(const CostSpec &cost)=0
Atomically debit all items immediately.
Adapter that maps RTS orders to the existing action::ActionRuntime.
Definition RTSAction.h:61
Canonical attributes component adapter, backed by attributes::AttributeSet.
Definition RTSTypes.h:328
RTS building domain root with placement and production composition.
Definition RTSTypes.h:852
void release() override
Entity.
Definition RTSTypes.h:858
static Building * createBuilding(SubjectRef subject={}, LogicalId definition={})
Create a building and initialize its self handle and identity.
Definition RTSTypes.cpp:667
Faction domain root; membership is a set of typed runtime handles.
Definition RTSTypes.h:1192
static Faction * createFaction(SubjectRef subject={})
Create a faction and initialize its self handle and identity.
Definition RTSTypes.cpp:695
void release() override
Entity.
Definition RTSTypes.h:1198
static void clear(State &state) noexcept
Remove all revealers previously installed by this state.
Interface isolating RTS orders from the shared action runtime.
Definition RTSAction.h:38
static Result< void > addObjective(Match &match, MissionObjectiveSpec objective)
Register one campaign objective while the match is in setup. @cost Linear in existing objectives for ...
Definition RTSMatch.cpp:510
static Result< void > start(Match &match)
Validate rules/participants/objectives and transition Setup to Running.
Definition RTSMatch.cpp:533
static Result< void > creditScore(Match &match, int team, double amount)
Credit a finite team score while the match is running. @cost Linear in the number of score entries (t...
Definition RTSMatch.cpp:604
static Result< void > addParticipant(Match &match, Faction &faction, int team)
Add one live faction before match start.
Definition RTSMatch.cpp:497
static Result< void > surrender(Match &match, Faction &faction)
Eliminate a participant and all of its live RTS entities.
Definition RTSMatch.cpp:590
Independent match composition root; factions may participate in different matches.
Definition RTSTypes.h:1476
static Match * createMatch(SubjectRef subject={})
Create a match and initialize every composition component. @ownership The active ECS table owns the e...
Definition RTSTypes.cpp:703
static Result< void > addMonitor(Match &match, MissionRegionMonitor monitor)
Register one axis-aligned region monitor. @cost Linear in existing monitor count for duplicate-id che...
static Result< void > addTrigger(Match &match, MissionTrigger trigger)
Register one trigger definition (Setup or Running). @cost Linear in existing trigger count for duplic...
static Result< void > pushEvent(Match &match, MissionPendingEvent event)
Push one custom (or domain) event onto the campaign pending queue. @cost Amortized constant; triggers...
static Result< void > addTimer(Match &match, MissionTimer timer)
Register one countdown timer; optionally start it immediately. @cost Linear in existing timer count f...
static Result< void > setVariable(Match &match, std::string id, double value)
Create or overwrite one named campaign variable.
static Result< void > clearActionLog(Match &match) noexcept
Clear retained Script action log entries after the game layer has consumed them.
Player domain root; selection is RTS-local, authority/economy/social are links.
Definition RTSTypes.h:1133
static Player * createPlayer(SubjectRef subject={})
Create a player and initialize its self handle and identity.
Definition RTSTypes.cpp:687
static Result< void > apply(definitions::DefinitionRegistry &registry, Unit &unit, const ArchetypeWeaponFactory &weaponFactory={})
Apply the Unit root's logical definition atomically.
static eve::Result< void > ensure(Unit &unit)
Bind and seed default optional combat stats exactly once.
Owns RTS root entities and coordinates the phase-one systems.
Definition RTS.h:105
Result< GameplayObservation > observeGameplay(const GameplaySession &session, SubjectRef instance) const override
Observe one provider-owned gameplay instance without mutation.
Definition RTS.cpp:260
Result< Player * > newPlayer(SubjectRef subject)
Create and own one Player root with a valid subject identity.
Definition RTS.cpp:498
Result< GameplayCommandReceipt > submitGameplay(const GameplaySession &session, SubjectRef instance, const GameplayCommand &command) override
Validate authority and atomically submit one domain command.
Definition RTS.cpp:324
Result< std::vector< GameplayEvent > > gameplayEvents(const GameplaySession &session, SubjectRef instance, std::uint64_t afterSequence) const override
Return events strictly newer than an instance-local sequence cursor.
Definition RTS.cpp:405
Result< Building * > newBuilding(SubjectRef subject, LogicalId definition={})
Create and own one Building root.
Definition RTS.cpp:453
Result< Value > inspectMatch(Match &match) const
Return an owning deterministic projection of one match lifecycle.
Definition RTS.cpp:845
~RTS() override
Destroy only live entities created through this module.
Definition RTS.cpp:180
void setCombatProviders(sensing::SensingWorld *sensing, combat::DamageRuntime *damage) noexcept
Attach canonical sensing and damage coordinators used by automatic combat.
Definition RTS.cpp:207
Result< void > addMatchTrigger(Match &match, MissionTrigger trigger) const
Register one campaign trigger on an owned match.
Definition RTS.cpp:782
Result< std::vector< GameplayActionDescriptor > > availableGameplayActions(const GameplaySession &session, SubjectRef instance, SubjectRef subject) const override
Discover currently legal player-semantic actions for one subject.
Definition RTS.cpp:296
Result< Building * > newFactionBuilding(Faction &faction, SubjectRef subject, LogicalId definition={})
Atomically create a Building, bind its owning faction and register canonical membership.
Definition RTS.cpp:666
Result< Match * > newMatch(SubjectRef subject)
Create and own one independent RTS match composition root.
Definition RTS.cpp:701
void setDefinitionRegistry(definitions::DefinitionRegistry *registry) noexcept
Attach the canonical definition registry used to settle completed research.
Definition RTS.h:371
Result< void > addMatchParticipant(Match &match, Faction &faction, int team) const
Add one owned faction to one owned setup-phase match.
Definition RTS.cpp:768
Result< void > configureSettlementRules(const settlement::SettlementRuleSet &rules)
Replace declarative settlement rules on the active canonical damage provider.
Definition RTS.cpp:218
Result< void > surrenderMatch(Match &match, Faction &faction) const
Surrender one owned faction from one owned running match.
Definition RTS.cpp:831
Result< void > addMatchTimer(Match &match, MissionTimer timer) const
Register one campaign timer on an owned match.
Definition RTS.cpp:796
Result< Faction * > newFaction(SubjectRef subject)
Create and own one Faction root with a valid subject identity.
Definition RTS.cpp:513
std::string_view gameplayDomain() const noexcept override
Stable provider domain used for discovery and routing.
Definition RTS.cpp:245
Result< void > addMatchObjective(Match &match, MissionObjectiveSpec objective) const
Register one campaign objective on an owned setup-phase match.
Definition RTS.cpp:775
Result< ResourceNode * > newResourceNode(SubjectRef subject, std::string resourceType, float amount, WorldPosition position, std::size_t workerCapacity=1)
Create and own one harvestable resource node.
Definition RTS.cpp:474
Result< void > configureMatch(Match &match, VictoryRule rule, std::string archetype={}, double targetValue=0.0) const
Configure one owned setup-phase match victory rule.
Definition RTS.cpp:716
Result< void > rebuildState(const RTSStateSnapshot &snapshot)
Materialize a complete snapshot into an empty RTS module.
Result< Unit * > newUnit(SubjectRef subject, LogicalId definition={})
Create and own one Unit root.
Definition RTS.cpp:422
Result< void > pushMatchCampaignEvent(Match &match, MissionPendingEvent event) const
Push one campaign event onto an owned match pending queue.
Definition RTS.cpp:810
Result< void > creditMatchScore(Match &match, int team, double amount) const
Credit a finite score to one active team in a running owned match.
Definition RTS.cpp:838
Result< void > addMatchMonitor(Match &match, MissionRegionMonitor monitor) const
Register one campaign region monitor on an owned match.
Definition RTS.cpp:789
Result< void > configureMatchTiming(Match &match, Duration timeLimit, bool suddenDeath=false) const
Configure the optional match clock before start.
Definition RTS.cpp:744
Result< void > clearMatchCampaignActions(Match &match) const
Clear retained campaign Script action log entries on an owned match.
Definition RTS.cpp:817
std::vector< SubjectRef > gameplayInstances() const override
Instances currently served, in publication order.
Definition RTS.cpp:247
Faction * findFaction(SubjectRef subject) const noexcept
Resolve a module-owned faction by persistent subject identity.
Definition RTS.cpp:3592
RTS()
Construct an empty RTS composition profile.
Definition RTS.cpp:175
Result< void > setMatchVariable(Match &match, std::string id, double value) const
Create or overwrite one campaign variable on an owned match.
Definition RTS.cpp:803
Result< FanOutReceipt > fanOut(Player::Selection &selection, const CommandSpec &command, const FormationSpec &formation) const
Fan one common command out through a player's selected unit handles.
void setFogProvider(FogProvider provider) noexcept
Install the faction-to-canonical-FOV resolver used by fog-of-war projection.
Definition RTS.cpp:200
Result< Unit * > newFactionUnit(Faction &faction, SubjectRef subject, LogicalId definition={})
Atomically create a Unit, bind its owning faction and register canonical membership.
Definition RTS.cpp:616
void setCrowdProvider(crowd::Crowd *crowd) noexcept
Attach the canonical Crowd provider used by Units with a bound Unit::Crowd link. @ownership Borrows p...
Definition RTS.cpp:225
Result< void > startMatch(Match &match) const
Start one owned match after participant/rule validation.
Definition RTS.cpp:824
Result< GameplayObservation > advanceGameplay(const GameplaySession &session, SubjectRef instance, const SimulationStep &step) override
Advance one provider-owned instance using injected deterministic time.
Definition RTS.cpp:385
Harvestable RTS resource node; deposited balances are owned by an external resource account.
Definition RTSTypes.h:1085
static ResourceNode * createResourceNode(SubjectRef subject={})
Create a resource node and initialize all composition components. @ownership The active ECS table own...
Definition RTSTypes.cpp:679
RTS unit domain root.
Definition RTSTypes.h:501
static Unit * createUnit(SubjectRef subject={}, LogicalId definition={})
Create a unit and initialize its self handle and identity.
Definition RTSTypes.cpp:655
Mirrored world positions and query composition; consumers decide gameplay actions from results.
Definition Sensing.h:197
Validated immutable-style rule collection installable into pipelines.
static eve::Result< SettlementRuleSet > fromJson(std::string_view json)
Decode and compile a strict versioned JSON rule document without mutating an existing rule set.
static eve::Result< WeaponDefinitionRuntime > create(eve::definitions::DefinitionRegistry &registry, eve::DefinitionRef definition, eve::PersistentId instanceId, eve::definition::ReloadPolicy policy=eve::definition::ReloadPolicy::RebuildInstance)
Create from a common weapon:<name> definition reference.
武器实体:数据全部在组件里,行为在 WeaponSystem。
static WeaponEntity * createWeapon()
创建并触摸全部组件。
Definition Weapon.cpp:129
Result< void > replay(const Trace &trace, IEnvironment &environment, double tolerance)
Reset and replay actual actions, checking all observations and failure evidence.
Definition Agent.cpp:259
HitReaction
Typed reaction selected after health and poise are resolved.
Definition Damage.h:27
CrowdExecution
Explicit execution selection; serial does not require a provider.
std::variant< std::monostate, std::int64_t, double, std::string, bool > Value
Definition Database.h:27
eve::StatusCode Status
std::unordered_map< std::string, SkillDefinition > & table()
Definition Skill.cpp:73
Value fanOutValue(FanOutReceipt receipt)
Result< std::vector< SubjectRef > > parseScriptSubjects(const std::vector< std::string > &texts)
Parse script UUID strings into stable subjects. @cost Linear in subject count; allocates one output v...
Result< SubjectRef > parseScriptSubject(std::string_view text, std::string_view path)
Result< RTSEffectDefinition > resolveEffectDefinition(definitions::DefinitionRegistry &registry, std::string_view id, SubjectRef source, double durationOverride)
DamageChannel
Authoritative damage route that produced one transient RTS frame event.
Definition RTSSystems.h:68
std::function< map::Fov *(Faction &)> FogProvider
Resolves the canonical FOV instance used by a faction; allies may deliberately share one instance.
Definition RTSSystems.h:332
std::function< void(const LifecycleEvent &, SimulationTick)> LifecycleEventSink
Read-only observer invoked after a non-combat lifecycle transition commits.
Definition RTSSystems.h:128
std::function< void(const CombatFireEvent &, SimulationTick)> CombatFireEventSink
Read-only observer invoked after a weapon consumes one authoritative shot.
Definition RTSSystems.h:92
const char * combatStanceName(CombatStance stance) noexcept
Return the stable lower-case spelling of a combat stance. @ownership Returns a borrowed pointer to im...
Definition RTSTypes.cpp:168
OrderKind
Commands shared by movement, combat, construction and gathering.
Definition RTSTypes.h:69
RTSReplayOperation
Stable operation kinds accepted by the shared deterministic RTS input stream.
Definition RTSReplay.h:20
CombatFireEventKind
Transient weapon lifecycle event emitted after an authoritative firing attempt commits.
Definition RTSSystems.h:75
std::function< Result< weapon::WeaponEntity * >(std::string_view definitionId, PersistentId instanceId)> ArchetypeWeaponFactory
Factory that creates one canonical weapon instance from a registry definition.
LifecycleEventKind
Non-combat RTS state transition exposed to presentation without entering authoritative state.
Definition RTSSystems.h:95
std::function< void(const combat::DamageRequest &request, const combat::DamageOutcome &outcome, SimulationTick tick, DamageChannel channel)> DamageEventSink
Read-only observer invoked after canonical damage has committed.
Definition RTSSystems.h:72
CombatStance
Automatic target-acquisition policy for an RTS unit.
Definition RTSTypes.h:59
const char * orderKindName(OrderKind kind) noexcept
Return the stable lower-case spelling of an RTS order kind.
Definition RTSTypes.cpp:177
VictoryRule
Supported deterministic RTS victory policies.
Definition RTSTypes.h:1307
@ Mission
Campaign/mission mode: Match::Objectives own completion and failure settlement.
ssq::Table projectStatusResult(HSQUIRRELVM vm, const Status &status)
Project a checked native status that carries no payload.
ssq::Table projectResult(HSQUIRRELVM vm, Result< void > &&result)
Consume and project a void native Result using the common schema.
::eve::SubjectRef SubjectRef
Strong reference to a runtime subject.
Definition Targeting.h:68
std::string_view statusName(BattleStatus status) noexcept
Return the stable protocol spelling of a battle status.
StrongUuid< detail::PersistentIdTag > PersistentId
Stable instance identity for persistence, networking and process boundaries.
Definition Identity.h:253
StatusCode
Stable outcome category for an operation.
Definition Status.h:28
detail::StrongUint64< detail::SimulationTickTag > SimulationTick
Deterministic simulation time step; it is not wall-clock time.
Definition Time.h:31
bool enabled
Owning evidence that a gameplay authority accepted one command.
One player-semantic command submitted to a domain authority.
std::uint64_t expectedRevision
SimulationTick observedTick
Owning event projection safe across frames and process boundaries.
std::uint64_t sequence
Immutable owning observation of one authoritative gameplay instance.
Owning authorization context shared by player, script and automation adapters.
One deterministic fixed-step emitted by SimulationClock.
Definition Time.h:158
SimulationTick tick
Tick reached after this step is applied.
Definition Time.h:160
Duration delta
Fixed simulation duration for this step.
Definition Time.h:162
Mutable combat state owned by the gameplay domain for one subject.
Definition Damage.h:38
Complete owning audit result of one committed damage transaction.
Definition Damage.h:103
Owning input for one damage transaction.
Definition Damage.h:50
Optional bounded velocity sampling for RTS local avoidance.
Definition Crowd.h:129
bool enabled
Opt in independently of legacy Boids steering.
Definition Crowd.h:130
A subject-agnostic continuous task retained for audit and save games.
Definition Production.h:158
static eve::Result< ResourceCost > create(std::string_view resourceId, std::int64_t amountValue)
Construct and validate one cost item.
Stable presentation payload for firing, launch, and miss feedback.
Definition RTSSystems.h:85
Absolute muzzle and target heights resolved by the authoritative map/game adapter.
Definition RTSSystems.h:627
One domain-neutral command submitted to a unit's generic order queue.
Definition RTSTypes.h:106
std::string definitionId
Definition RTSTypes.h:109
ecs::EntityHandle targetEntity
Definition RTSTypes.h:112
Result< void > validate() const
Validate coordinates and command metadata without mutating state.
Definition RTSTypes.cpp:201
WorldPosition target
Definition RTSTypes.h:108
WorldPosition secondaryTarget
Definition RTSTypes.h:113
Input to the pure formation planner.
Definition RTSSystems.h:34
Stable payload for one committed RTS lifecycle transition.
Definition RTSSystems.h:120
Persistent mission objective definition using stable subjects and team ids.
Definition RTSTypes.h:1332
Queued campaign event waiting to wake triggers.
Definition RTSTypes.h:1455
Axis-aligned world region that emits enter/exit events for live subjects.
Definition RTSTypes.h:1426
Match-owned countdown that emits TimerElapsed when it reaches zero.
Definition RTSTypes.h:1440
Authorable trigger: OR of events, AND of variable conditions, then actions.
Definition RTSTypes.h:1414
Earliest canonical collision found along one projectile sweep segment.
Definition RTSSystems.h:657
Typed RTS definition projected to the common lifecycle schema.
Definition RTSEffects.h:35
One process-independent command using stable subjects instead of ECS handles.
Definition RTSReplay.h:39
action::ActionRuntime action
Definition RTS.cpp:171
std::vector< PaidConstruction > paidConstruction
std::map< std::string, economy::EconomyLedger::Snapshot > economies
std::map< std::string, SubjectRef > pendingProductionSubjects
std::map< std::string, map::Fov::Snapshot > fovs
Two-dimensional deterministic RTS world position.
Definition RTSTypes.h:53
武器模板(registerWeaponsFromJson 注册,进程级注册表)。