载入中...
搜索中...
未找到
RTS.cpp
浏览该文件的文档.
47 DiagnosticCode::InvalidArgument, "RTS refund factor must be finite and positive", "refund.factor"));
51 const auto amount = static_cast<std::int64_t>(std::llround(static_cast<double>(item.amount.value()) * factor));
112 return Result<double>::success(found->second.isInt64() ? static_cast<double>(found->second.asInt())
132 return static_cast<std::size_t>(std::count_if(handles.begin(), handles.end(), [](const ecs::EntityHandle& handle) {
160 DiagnosticCode::InvalidArgument, "RTS script definition must be a canonical logical id", "definition"));
204 if (auto* faction = tryGetCurrent<Faction>(handle)) faction->intel()->enabled = static_cast<bool>(fogProvider_);
207void RTS::setCombatProviders(sensing::SensingWorld* sensing, combat::DamageRuntime* damage) noexcept {
221 Diagnostic::error(DiagnosticCode::NotFound, "RTS combat damage provider is not attached", "damage"));
253 if (player != nullptr && player->identity()->subject.isValid()) result.push_back(player->identity()->subject);
256 [](const SubjectRef& left, const SubjectRef& right) { return left.format() < right.format(); });
260Result<GameplayObservation> RTS::observeGameplay(const GameplaySession& session, SubjectRef instance) const {
267 DiagnosticCode::PreconditionViolation, "session does not control this RTS player", "instance"));
296Result<std::vector<GameplayActionDescriptor>> RTS::availableGameplayActions(const GameplaySession& session,
303 Diagnostic::error(DiagnosticCode::NotFound, "RTS gameplay player or unit was not found", "subject"));
306 DiagnosticCode::PreconditionViolation, "session does not control this RTS player", "instance"));
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 &&
315 DiagnosticCode::PreconditionViolation, "RTS unit is not in the player's selection", "subject"));
324Result<GameplayCommandReceipt> RTS::submitGameplay(const GameplaySession& session, SubjectRef instance,
332 DiagnosticCode::PreconditionViolation, "session does not control this RTS player", "instance"));
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"));
353 Diagnostic::error(DiagnosticCode::Unsupported, "unsupported RTS gameplay action", "command.action"));
363 receipt.executionId = fanOutReceipt.orderIds.empty() ? std::string{} : fanOutReceipt.orderIds.front();
368 receipt.details = Value(Value::Object{{"accepted", Value(static_cast<std::int64_t>(fanOutReceipt.accepted))},
382 return Result<GameplayCommandReceipt>::success(std::move(receipt), Status::success(StatusCode::Applied));
385Result<GameplayObservation> RTS::advanceGameplay(const GameplaySession& session, SubjectRef instance,
393 DiagnosticCode::PreconditionViolation, "session does not control this RTS player", "instance"));
405Result<std::vector<GameplayEvent>> RTS::gameplayEvents(const GameplaySession& session, SubjectRef instance,
425 Diagnostic::error(DiagnosticCode::InvalidArgument, "RTS Unit requires a valid SubjectRef", "subject"));
426 if (ownsSubject(subject, scriptRuntime_ && scriptRuntime_->spawningProduction ? SubjectClaimScope::Live
429 Diagnostic::error(DiagnosticCode::Conflict, "RTS SubjectRef is already owned by this module", "subject"));
456 Diagnostic::error(DiagnosticCode::InvalidArgument, "RTS Building requires a valid SubjectRef", "subject"));
459 Diagnostic::error(DiagnosticCode::Conflict, "RTS SubjectRef is already owned by this module", "subject"));
474Result<ResourceNode*> RTS::newResourceNode(SubjectRef subject, std::string resourceType, float amount,
476 if (!validSubject(subject) || resourceType.empty() || !std::isfinite(amount) || amount < 0.0f ||
479 DiagnosticCode::InvalidArgument, "RTS resource node requires valid identity, stock, position and capacity",
483 Diagnostic::error(DiagnosticCode::Conflict, "RTS SubjectRef is already owned by this module", "subject"));
487 Diagnostic::error(DiagnosticCode::Failed, "ECS failed to create an RTS ResourceNode", "resourceNode"));
501 Diagnostic::error(DiagnosticCode::InvalidArgument, "RTS Player requires a valid SubjectRef", "subject"));
504 Diagnostic::error(DiagnosticCode::Conflict, "RTS SubjectRef is already owned by this module", "subject"));
516 Diagnostic::error(DiagnosticCode::InvalidArgument, "RTS Faction requires a valid SubjectRef", "subject"));
519 Diagnostic::error(DiagnosticCode::Conflict, "RTS SubjectRef is already owned by this module", "subject"));
560 auto runtime = weapon::WeaponDefinitionRuntime::create(*definitions_, definitionId, instanceId);
565 Diagnostic::error(DiagnosticCode::Failed, "ECS failed to create an RTS weapon instance", "weapon"));
578 if (auto* entity = dynamic_cast<weapon::WeaponEntity*>(ecs::try_get(weapons_.back()))) entity->release();
591 auto runtime = weapon::WeaponDefinitionRuntime::create(*definitions_, definitionId, instanceId);
596 Diagnostic::error(DiagnosticCode::Failed, "ECS failed to create an RTS weapon instance", "weapon"));
609 if (auto* entity = dynamic_cast<weapon::WeaponEntity*>(ecs::try_get(weapons_.back()))) entity->release();
619 Diagnostic::error(DiagnosticCode::StaleHandle, "RTS Faction does not belong to this facade", "faction"));
626 if (auto* weapon = dynamic_cast<weapon::WeaponEntity*>(ecs::try_get(weapons_.back()))) weapon->release();
666Result<Building*> RTS::newFactionBuilding(Faction& faction, SubjectRef subject, LogicalId definition) {
669 Diagnostic::error(DiagnosticCode::StaleHandle, "RTS Faction does not belong to this facade", "faction"));
676 if (auto* weapon = dynamic_cast<weapon::WeaponEntity*>(ecs::try_get(weapons_.back()))) weapon->release();
704 Diagnostic::error(DiagnosticCode::InvalidArgument, "RTS Match requires a valid SubjectRef", "subject"));
707 Diagnostic::error(DiagnosticCode::Conflict, "RTS SubjectRef is already owned by this module", "subject"));
716Result<void> RTS::configureMatch(Match& match, VictoryRule rule, std::string archetype, double targetValue) const {
722 Diagnostic::error(DiagnosticCode::Conflict, "RTS match rules are immutable after start", "match.phase"));
726 if (rule == VictoryRule::ResourceTarget && (archetype.empty() || !std::isfinite(targetValue) || targetValue <= 0.0))
733 if (match.rules()->suddenDeath && (rule == VictoryRule::ScoreTarget || rule == VictoryRule::ResourceTarget ||
744Result<void> RTS::configureMatchTiming(Match& match, Duration timeLimit, bool suddenDeath) const {
750 Diagnostic::error(DiagnosticCode::Conflict, "RTS match timing is immutable after start", "match.phase"));
756 DiagnosticCode::InvalidArgument, "RTS sudden death requires a positive time limit", "suddenDeath"));
771 DiagnosticCode::InvalidArgument, "RTS match and faction must share this composition root", "participant"));
834 DiagnosticCode::InvalidArgument, "RTS match and faction must share this composition root", "participant"));
864 Value::Object{{"faction", faction == nullptr ? std::string{} : faction->identity()->subject.format()},
889 for (const auto& subject : objective.spec.requiredSubjects) subjects.emplace_back(subject.format());
895 {"targetFaction", objective.spec.targetFaction.isValid() ? objective.spec.targetFaction.format()
897 {"targetSubject", objective.spec.targetSubject.isValid() ? objective.spec.targetSubject.format()
978Unit* RTS::findUnit(SubjectRef subject) const noexcept { return findSubject<Unit>(units_, subject); }
980Building* RTS::findBuilding(SubjectRef subject) const noexcept { return findSubject<Building>(buildings_, subject); }
988 std::any_of(scriptRuntime_->pendingProductionSubjects.begin(), scriptRuntime_->pendingProductionSubjects.end(),
991 return findSubject<Unit>(units_, subject) != nullptr || findSubject<Building>(buildings_, subject) != nullptr ||
993 findSubject<Player>(players_, subject) != nullptr || findSubject<Faction>(factions_, subject) != nullptr ||
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)
1003 DiagnosticCode::InvalidArgument, "RTS combat leash range must be finite and non-negative", "leashRange"));
1021 if (stance == CombatStance::Passive && unit->orders()->values.orderCount() == 0) combat->target = {};
1026Result<void> RTS::setUnitMovementPriority(std::span<const SubjectRef> subjects, int priority) const {
1045 DiagnosticCode::StaleHandle, "RTS worker assignment requires roots owned by this facade", "assignment"));
1047 return Result<void>::failure(Diagnostic::error(DiagnosticCode::Conflict, "RTS worker must be alive", "worker"));
1051 Diagnostic::error(DiagnosticCode::Conflict, "RTS unit is not configured as a resource worker", "worker"));
1055 DiagnosticCode::Conflict, "RTS resource node is depleted or incompatible with the worker", "node"));
1059 std::find(dropoff.dropoff()->acceptedResources.begin(), dropoff.dropoff()->acceptedResources.end(),
1062 DiagnosticCode::Conflict, "RTS dropoff must be completed, friendly, and accept the resource", "dropoff"));
1065 std::erase_if(assigned, [](const ecs::EntityHandle& handle) { return tryGetCurrent<Unit>(handle) == nullptr; });
1071 Diagnostic::error(DiagnosticCode::Conflict, "RTS resource node worker capacity is full", "node"));
1096Result<void> RTS::setWorkerAutoAssignment(std::span<const SubjectRef> subjects, bool enabled) const {
1116Result<void> RTS::configureWorkforce(Faction& faction, bool autoConstruction, int maxBuildersPerSite, bool autoRepair,
1120 DiagnosticCode::StaleHandle, "RTS workforce faction does not belong to this facade", "faction"));
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"));
1147 DiagnosticCode::Conflict, "RTS builder and construction target must share a faction", "assignment"));
1160 DiagnosticCode::StaleHandle, "RTS reserve-ammunition unit does not belong to this facade", "unit"));
1163 Diagnostic::error(DiagnosticCode::Conflict, "RTS reserve-ammunition unit must be alive", "unit"));
1167 Diagnostic::error(DiagnosticCode::NotFound, "RTS unit has no canonical weapon", "unit.weapon"));
1171 DiagnosticCode::Conflict, "RTS unit weapon has no finite reserve ammunition", "unit.weapon.resource"));
1175 DiagnosticCode::Conflict, "RTS unit weapon ammunition pool is infinite", "unit.weapon.ammoPool"));
1177 pool->state()->count = static_cast<int>(std::clamp<long long>(adjusted, 0, pool->state()->max));
1194 DiagnosticCode::StaleHandle, "RTS ammunition-supply unit does not belong to this facade", "unit"));
1197 Diagnostic::error(DiagnosticCode::Conflict, "RTS ammunition-supply unit must be alive", "unit"));
1209 DiagnosticCode::StaleHandle, "RTS ammunition-supply building does not belong to this facade", "building"));
1212 Diagnostic::error(DiagnosticCode::Conflict, "RTS ammunition-supply building must be alive", "building"));
1224 DiagnosticCode::StaleHandle, "RTS automatic-resupply unit does not belong to this facade", "unit"));
1227 Diagnostic::error(DiagnosticCode::Conflict, "RTS automatic-resupply unit must be alive", "unit"));
1232 if (current && (current.value().kind == OrderKind::Resupply || current.value().kind == OrderKind::SupplyRelay)) {
1252Result<FanOutReceipt> RTS::suppressArea(std::span<const SubjectRef> subjects, WorldPosition start, WorldPosition end,
1254 if (!std::isfinite(start.x) || !std::isfinite(start.y) || !std::isfinite(end.x) || !std::isfinite(end.y) ||
1272 Diagnostic::error(DiagnosticCode::Conflict, "RTS suppression unit must be alive, deployed, and armed",
1290Result<FanOutReceipt> RTS::escortUnits(std::span<const SubjectRef> subjects, SubjectRef protectedSubject,
1292 if (!std::isfinite(guardRadius) || !std::isfinite(spacing) || guardRadius <= 0.0f || spacing <= 0.0f)
1312 Diagnostic::error(DiagnosticCode::NotFound, "RTS escort target must be a live deployed unit or building",
1317 DiagnosticCode::Conflict, "RTS escort target must have an owning faction", "protectedSubject"));
1375 if (auto* weaponEntity = dynamic_cast<weapon::WeaponEntity*>(unit->weapon()->link.resolve())) {
1418 {"resourceNode", resourceNode == nullptr ? std::string{} : resourceNode->identity()->subject.format()},
1435 if (auto* owner = dynamic_cast<Faction*>(building->faction()->link.resolve()); owner != nullptr)
1605void RTS::recordDamageEvent(const combat::DamageRequest& request, const combat::DamageOutcome& outcome,
1621 Diagnostic::error(DiagnosticCode::StaleHandle, "RTS Unit does not belong to this facade", "unit"));
1625Result<void> RTS::setUnitAttribute(Unit& unit, std::string_view attribute, double value) const {
1628 Diagnostic::error(DiagnosticCode::StaleHandle, "RTS Unit does not belong to this facade", "unit"));
1632Result<effects::EffectHandle> RTS::applyEffect(Unit& unit, const RTSEffectDefinition& definition) const {
1635 Diagnostic::error(DiagnosticCode::StaleHandle, "RTS Unit does not belong to this facade", "unit"));
1639Result<effects::EffectHandle> RTS::applyEffect(Building& building, const RTSEffectDefinition& definition) const {
1642 Diagnostic::error(DiagnosticCode::StaleHandle, "RTS Building does not belong to this facade", "building"));
1676 return Result<double>::success(applied, Status::success(applied == 0.0 ? StatusCode::NoOp : StatusCode::Applied));
1679Result<effects::EffectHandle> RTS::applyStatusEffect(SubjectRef source, SubjectRef target, std::string effect,
1686 Diagnostic::error(DiagnosticCode::NotFound, "RTS status-effect source was not found", "source"));
1692 Diagnostic::error(DiagnosticCode::Conflict, "RTS status-effect target must be alive", "target"));
1703 Diagnostic::error(DiagnosticCode::Conflict, "RTS status-effect target must be alive", "target"));
1712 Diagnostic::error(DiagnosticCode::NotFound, "RTS status-effect target was not found", "target"));
1715Result<void> RTS::setProductionResourceReserve(Faction& faction, std::string resource, std::int64_t amount,
1719 Diagnostic::error(DiagnosticCode::StaleHandle, "RTS Faction does not belong to this facade", "faction"));
1734Result<RTSCancelProductionReceipt> RTS::cancelProduction(Building& building, resource::IResourceAccount& account,
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),
1744Result<std::size_t> RTS::step(const SimulationStep& simulationStep, IRTSActionExecutor& executor) {
1757 if (crowdFlowNavigation_ && crowdFlowNavigation_->enabled() && crowd_->getFieldStatus().surface.surface.isZero())
1770 [this](const combat::DamageRequest& request, const combat::DamageOutcome& outcome, SimulationTick tick,
1772 const CombatFireEventSink fireEvents = [this](const CombatFireEvent& event, SimulationTick tick) {
1775 const LifecycleEventSink lifecycleEvents = [this](const LifecycleEvent& event, SimulationTick tick) {
1866 [this](const LifecycleEvent& event, SimulationTick tick) { recordLifecycleEvent(event, tick); });
1908 auto projectileImpacts = projectiles_.step(simulationStep, *damage_, projectileCollisionQuery_, damageEvents);
1914 CombatFireSystem::step(simulationStep, combatState_, *sensing_, *damage_, &projectiles_, fireLineQuery_,
1924 auto reinforcementPolicy = ReinforcementProductionPolicySystem::step(simulationStep, reinforcementCancel_);
1982 Diagnostic::error(DiagnosticCode::NotFound, "RTS script world is not configured", "crowd.scheduler"));
1991 Diagnostic::error(DiagnosticCode::InvalidArgument, "RTS script step duration must be positive", "seconds"));
2021 return record.kind != "unit" || std::find(settled.begin(), settled.end(), record.taskId) != settled.end();
2023 return Result<std::size_t>::success(commands.value() + stepped.value(), Status::success(StatusCode::Applied));
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) ||
2034 scriptRuntime_->crowd.resizeField(width, height, cellSize, originX - cellSize * 0.5f, originY - cellSize * 0.5f);
2057 // The canonical sensing world owns filtering and ranking; its existing grid only culls candidates.
2061 const auto firstBlockedPoint = [this](WorldPosition from, WorldPosition to) -> std::optional<WorldPosition> {
2069 static_cast<int>(std::floor((from.x - scriptRuntime_->originX) / scriptRuntime_->cellSize + 0.5f));
2071 static_cast<int>(std::floor((from.y - scriptRuntime_->originY) / scriptRuntime_->cellSize + 0.5f));
2076 static_cast<int>(std::floor((point.x - scriptRuntime_->originX) / scriptRuntime_->cellSize + 0.5f));
2078 static_cast<int>(std::floor((point.y - scriptRuntime_->originY) / scriptRuntime_->cellSize + 0.5f));
2082 if (cellX < 0 || cellY < 0 || cellX >= scriptRuntime_->width || cellY >= scriptRuntime_->height ||
2091 static_cast<int>(std::floor((point.x - scriptRuntime_->originX) / scriptRuntime_->cellSize + 0.5f));
2093 static_cast<int>(std::floor((point.y - scriptRuntime_->originY) / scriptRuntime_->cellSize + 0.5f));
2095 return scriptRuntime_->terrainElevations[static_cast<std::size_t>(y * scriptRuntime_->width + x)];
2107 from.x, from.y, fromHeight, to.x, to.y, toHeight, scriptRuntime_->originX, scriptRuntime_->originY,
2110 return scriptRuntime_->terrainElevations[static_cast<std::size_t>(y * scriptRuntime_->width + x)];
2121 firstBlockedPoint(from, to).has_value() || terrainBlocks(from, to, sourceHeight, targetHeight).has_value();
2124 setCombatHeightQuery([terrainAt, relativeHeight](WorldPosition from, WorldPosition to, ecs::EntityHandle source,
2135 return Result<std::optional<ProjectileCollision>>::success(std::nullopt, Status::success(StatusCode::NoOp));
2142 blocked && (!terrainImpact || distanceSquared(*blocked) < distanceSquared(*terrainImpact)) ? *blocked
2156 Diagnostic::error(DiagnosticCode::Conflict, "RTS script runtime is unavailable", "production"));
2160 DiagnosticCode::NotFound, "RTS produced unit has no reserved stable subject", "production.task"));
2183 setAIProductionRequest([this](Faction& faction, Building& producer, const LogicalId& definition) -> Result<void> {
2186 DiagnosticCode::Conflict, "RTS script AI production requires a configured world", "scriptRuntime"));
2189 DiagnosticCode::Conflict, "RTS script AI production identity sequence overflow", "ai.sequence"));
2241 setResourceCredit([accountForFaction](Unit& unit, const resource::CostSpec& cost) -> Result<resource::Receipt> {
2249 [accountForFaction](Unit& unit, Building&, const resource::CostSpec& cost) -> Result<resource::Receipt> {
2257 [accountForFaction](Building& building, const resource::CostSpec& cost) -> Result<resource::Receipt> {
2267 return Result<double>::success(static_cast<double>(balance.value()), Status::success(StatusCode::Applied));
2291 Diagnostic::error(DiagnosticCode::Conflict, "RTS script world is not configured", "scriptWorld"));
2299 scriptRuntime_->fovs[key] = std::make_unique<map::Fov>(scriptRuntime_->width, scriptRuntime_->height);
2339 if (x < 0 || y < 0 || x >= scriptRuntime_->width || y >= scriptRuntime_->height || !std::isfinite(elevation))
2357 Diagnostic::error(DiagnosticCode::InvalidArgument, "RTS terrain cell is outside the grid", "terrain.cell"));
2363Result<void> RTS::addScriptResource(Faction& faction, std::string resource, std::int64_t amount) {
2366 Diagnostic::error(DiagnosticCode::StaleHandle, "RTS Faction does not belong to this facade", "faction"));
2373 Diagnostic::error(DiagnosticCode::NotFound, "RTS script faction economy was not found", "faction"));
2385 Diagnostic::error(DiagnosticCode::StaleHandle, "RTS Faction does not belong to this facade", "faction"));
2393 Diagnostic::error(DiagnosticCode::NotFound, "RTS script faction economy was not found", "faction"));
2397Result<void> RTS::configureScriptAI(Faction& faction, LogicalId workerDefinition, LogicalId armyDefinition,
2402 Diagnostic::error(DiagnosticCode::StaleHandle, "RTS AI faction does not belong to this facade", "faction"));
2405 DiagnosticCode::Conflict, "RTS AI requires a configured script world and content", "scriptRuntime"));
2406 if (!workerDefinition.isValid() || !armyDefinition.isValid() || !targetBuildingDefinition.isValid() ||
2434Result<ReinforcementRequestReceipt> RTS::queueScriptReinforcement(Building& producer, SubjectRef unitSubject,
2438 DiagnosticCode::StaleHandle, "RTS reinforcement producer does not belong to this facade", "producer"));
2443 "RTS reinforcement requires a new stable subject and preferred unit definition", "reinforcement"));
2467 DiagnosticCode::PreconditionViolation, "RTS construction requires a same-faction builder", "builder"));
2468 if (!scriptRuntime_ || !scriptRuntime_->configured || definitions_ == nullptr || !buildingSubject.isValid() ||
2481 DiagnosticCode::InvalidArgument, "RTS building definition must be an object", "buildingDefinition"));
2494 if (resourceName == nullptr || resourceName->empty() || !std::isfinite(costNumber) || costNumber < 0.0 ||
2497 DiagnosticCode::InvalidArgument, "RTS building construction cost is invalid", "buildingDefinition"));
2501 Diagnostic::error(DiagnosticCode::NotFound, "RTS construction economy was not found", "faction"));
2512 economy->second->account.credit(cost.value()).ignore("compensate failed construction root creation");
2529 builder.orders()->values.restoreState(previousOrders.value()).ignore("restore construction builder orders");
2534 if (auto* weapon = dynamic_cast<weapon::WeaponEntity*>(ecs::try_get(weapons_.back()))) weapon->release();
2553 "RTS construction cancellation requires a live unfinished script building", "building.construction"));
2559 DiagnosticCode::NotFound, "RTS construction payment record was not found", "building.construction"));
2563 Diagnostic::error(DiagnosticCode::StaleHandle, "RTS construction faction is stale", "building.faction"));
2567 Diagnostic::error(DiagnosticCode::NotFound, "RTS construction economy was not found", "building.faction"));
2583 std::erase_if(faction->members()->buildings, [&](const auto& value) { return sameHandle(value, buildingHandle); });
2585 if (auto* weapon = dynamic_cast<weapon::WeaponEntity*>(building.weapon()->link.resolve())) weapon->release();
2596 Diagnostic::error(DiagnosticCode::StaleHandle, "RTS building does not belong to this facade", "building"));
2597 if (!scriptRuntime_ || !scriptRuntime_->configured || definitions_ == nullptr || !building.integrity()->alive ||
2605 Diagnostic::error(DiagnosticCode::StaleHandle, "RTS building faction link is stale", "building.faction"));
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()));
2617 DiagnosticCode::InvalidArgument, "RTS building definition must be an object", "building.definition"));
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"));
2640 DiagnosticCode::InvalidArgument, "RTS building sale values are invalid", "building.definition"));
2642 resource::CostSpec::single(*resourceIt->second.getIf<std::string>(), static_cast<std::int64_t>(costNumber));
2663 task->get().state == production::TaskState::Cancelled || task->get().state == production::TaskState::Failed)
2665 auto cancelled = cancelProduction(building, economy->second->account, record.taskId, record.orderId,
2672 std::erase_if(scriptRuntime_->paidProduction, [&](const auto& value) { return value.taskId == record.taskId; });
2679 auto evacuated = evacuateBuilding(building, {building.placement()->worldX + 2.0f, building.placement()->worldY});
2693 if (auto* weapon = dynamic_cast<weapon::WeaponEntity*>(building.weapon()->link.resolve())) weapon->release();
2702Result<RTSBuildReceipt> RTS::queueScriptResearch(Building& producer, std::string upgrade, int priority) {
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"));
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))
2720 for (int index = 0; index < static_cast<int>(candidateProduction->values.taskCount()); ++index) {
2739 Diagnostic::error(DiagnosticCode::InvalidArgument, "RTS upgrade definition must be an object", "upgrade"));
2749 if (const auto* integer = found->second.getIf<std::int64_t>()) return static_cast<double>(*integer);
2760 Diagnostic::error(DiagnosticCode::Conflict, "RTS building cannot research this upgrade", "producer"));
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"));
2772 Diagnostic::error(DiagnosticCode::NotFound, "RTS research economy was not found", "producer.faction"));
2793Result<RTSCancelProductionReceipt> RTS::cancelScriptProduction(Building& producer, int queueIndex) {
2796 Diagnostic::error(DiagnosticCode::StaleHandle, "RTS producer does not belong to this facade", "producer"));
2800 "RTS production cancellation requires a configured world and valid queue index", "queueIndex"));
2802 for (int index = 0; index < static_cast<int>(producer.production()->values.taskCount()); ++index) {
2805 task->get().state != production::TaskState::Cancelled && task->get().state != production::TaskState::Failed)
2810 Diagnostic::error(DiagnosticCode::NotFound, "RTS producer has no cancellable production", "production"));
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(),
2826 Diagnostic::error(DiagnosticCode::StaleHandle, "RTS producer faction link is stale", "producer.faction"));
2830 Diagnostic::error(DiagnosticCode::NotFound, "RTS producer economy was not found", "producer.faction"));
2840Result<void> RTS::setBuildingRally(Building& producer, CommandSpec command, bool groupedReinforcements) const {
2843 DiagnosticCode::StaleHandle, "RTS rally producer does not belong to this facade", "producer"));
2860 DiagnosticCode::StaleHandle, "RTS rally link requires two distinct owned producers", "producer"));
2884 DiagnosticCode::StaleHandle, "RTS rally producer does not belong to this facade", "producer"));
2908Result<void> RTS::setReinforcementTypeLimit(Building& producer, std::string unitType, std::size_t maximum) const {
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))
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 ||
2956 !definitions_->resolve("unit", preferred) || (!fallback.empty() && !definitions_->resolve("unit", fallback)))
3008Result<void> RTS::setReinforcementTransport(Building& producer, Unit* transport, std::size_t minimumLoad) const {
3011 DiagnosticCode::StaleHandle, "RTS rally producer does not belong to this facade", "producer"));
3022 if (!owns(units_, *transport) || transport->faction()->link.resolve() != producer.faction()->link.resolve() ||
3024 minimumLoad > transport->containment()->capacity || transport->containment()->container.isBound())
3027 "RTS reinforcement transport must be an uncontained friendly carrier with a valid minimum load",
3052 Diagnostic::error(DiagnosticCode::NotFound, "RTS unit has no active ability channel", "ability.channel"));
3060 recordLifecycleEvent({LifecycleEventKind::AbilityChannelCancelled, caster.identity()->subject, cancelledTarget,
3066Result<std::size_t> RTS::requestFireSupport(Unit& requester, WorldPosition center, float radius, int shotsPerResponder,
3070 DiagnosticCode::StaleHandle, "RTS fire-support requester does not belong to this facade", "requester"));
3077 DiagnosticCode::StaleHandle, "RTS fire-support requester does not belong to this facade", "requester"));
3082 if (!transport.identity()->subject.isValid() || findUnit(transport.identity()->subject) != &transport)
3084 DiagnosticCode::InvalidArgument, "RTS transport is not owned by this composition root", "transport"));
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"));
3106 DiagnosticCode::Conflict, "RTS script world must be configured before queuing commands", "scriptWorld"));
3107 return scriptRuntime_->commandLog.queue(std::move(command), SimulationTick{scriptRuntime_->nextTick});
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));
3120 DiagnosticCode::Conflict, "RTS script world must be configured before importing commands", "scriptWorld"));
3121 return scriptRuntime_->commandLog.importText(text, SimulationTick{scriptRuntime_->nextTick}, clearExisting);
3124std::uint64_t RTS::scriptTick() const noexcept {
3135 Diagnostic::error(DiagnosticCode::InvalidArgument, "RTS checkpoint name must not be empty", "name"));
3154 checkpoint.navigationCosts.reserve(static_cast<std::size_t>(scriptRuntime_->width * scriptRuntime_->height));
3175 const auto expectedCells = static_cast<std::size_t>(scriptRuntime_->width * scriptRuntime_->height);
3176 if (checkpoint.navigationCosts.size() != expectedCells || checkpoint.terrainElevations.size() != expectedCells)
3178 Diagnostic::error(DiagnosticCode::Conflict, "RTS checkpoint grid dimensions do not match", "grid"));
3181 if (current == scriptRuntime_->fovs.end() || !current->second || snapshot.width != scriptRuntime_->width ||
3184 Diagnostic::error(DiagnosticCode::Conflict, "RTS checkpoint fog topology does not match", "fog"));
3187 return std::any_of(players_.begin(), players_.end(), [subject](const ecs::EntityHandle& handle) {
3193 checkpoint.roots.units.size() == unitCount() && checkpoint.roots.buildings.size() == buildingCount() &&
3195 checkpoint.roots.players.size() == playerCount() && checkpoint.roots.factions.size() == factionCount() &&
3278 std::erase_if(scriptRuntime_->fovs, [&](const auto& entry) { return !checkpoint.fovs.contains(entry.first); });
3294 auto crowdCommitted = scriptRuntime_->crowd.commitRestore(std::move(crowdRestore).takeValue());
3317 if (!scriptRuntime_ || !scriptRuntime_->configured || findFaction(faction.identity()->subject) != &faction)
3323 Diagnostic::error(DiagnosticCode::InvalidArgument, "RTS fog cell is outside the grid", "cell"));
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));
3332 if (!scriptRuntime_ || !scriptRuntime_->configured || findFaction(faction.identity()->subject) != &faction)
3338 Diagnostic::error(DiagnosticCode::InvalidArgument, "RTS fog cell is outside the grid", "cell"));
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));
3372 if (passenger != nullptr && passenger != &unit && owns(units_, *passenger)) removeUnitRoot(*passenger);
3380 if (sensing_ != nullptr) sensing_->remove(subjectKey).ignore("best-effort RTS sensing cleanup");
3388 std::erase_if(node->harvest()->workers, [&](const auto& value) { return sameHandle(value, handle); });
3420 std::erase_if(faction->members()->units, [&](const auto& value) { return sameHandle(value, handle); });
3424 std::erase_if(player->selection()->units, [&](const auto& value) { return sameHandle(value, handle); });
3428 if (auto* weapon = dynamic_cast<weapon::WeaponEntity*>(unit.weapon()->link.resolve())) weapon->release();
3443 if (sensing_ != nullptr) sensing_->remove(subjectKey).ignore("best-effort RTS sensing cleanup");
3467 if (unit->containment()->container.isBound() && sameHandle(unit->containment()->container.handle(), handle))
3476 std::erase_if(faction->members()->buildings, [&](const auto& value) { return sameHandle(value, handle); });
3480 std::erase_if(player->selection()->buildings, [&](const auto& value) { return sameHandle(value, handle); });
3483 if (auto* weapon = dynamic_cast<weapon::WeaponEntity*>(building.weapon()->link.resolve())) weapon->release();
3487 std::erase_if(scriptRuntime_->paidConstruction, [&](const auto& value) { return value.building == subject; });
3529 Diagnostic::error(DiagnosticCode::NotFound, "RTS gameplay root identity was not found", "subject"));
3538 if (unit != nullptr && (!unit->durability()->alive || unit->durability()->state.health <= 0.0))
3543 if (building != nullptr && (!building->integrity()->alive || building->integrity()->state.health <= 0.0))
3548 const bool batchReady = deadBuildings.empty() && std::all_of(deadUnits.begin(), deadUnits.end(), [&](auto handle) {
3587std::size_t RTS::resourceNodeCount() const noexcept { return countLive<ResourceNode>(resourceNodes_); }
3592Faction* RTS::findFaction(SubjectRef subject) const noexcept { return findSubject<Faction>(factions_, subject); }
3593Match* RTS::findMatch(SubjectRef subject) const noexcept { return findSubject<Match>(matches_, subject); }
3627 cls.addFunc("scriptTick", [](RTS* self) { return static_cast<std::int64_t>(self->scriptTick()); });
3629 cls.addFunc("configureSettlementRulesJson", [vm](RTS* self, const std::string& json) -> ssq::Table {
3656 [vm](RTS* self, const std::string& matchText, const std::string& ruleText, const std::string& archetype,
3684 [vm](RTS* self, const std::string& matchText, float timeLimitSeconds, bool suddenDeath) -> ssq::Table {
3699 [vm](RTS* self, const std::string& matchText, const std::string& factionText, int team) -> ssq::Table {
3749 if (const auto* asInt = found->second.getIf<std::int64_t>()) return static_cast<double>(*asInt);
3832 return script::projectResult(vm, self->addMatchTrigger(*match, std::move(trigger).takeValue()));
3845 return script::projectResult(vm, self->addMatchMonitor(*match, std::move(monitor).takeValue()));
3847 cls.addFunc("addMatchTimer", [vm](RTS* self, const std::string& matchText, const std::string& id,
3865 cls.addFunc("setMatchVariable", [vm](RTS* self, const std::string& matchText, const std::string& id,
3874 return script::projectResult(vm, self->setMatchVariable(*match, id, static_cast<double>(value)));
3876 cls.addFunc("pushMatchCampaignEvent", [vm](RTS* self, const std::string& matchText, const std::string& kindText,
3913 cls.addFunc("clearMatchCampaignActions", [vm](RTS* self, const std::string& matchText) -> ssq::Table {
3934 "surrenderMatch", [vm](RTS* self, const std::string& matchText, const std::string& factionText) -> ssq::Table {
3956 return script::projectResult(vm, self->creditMatchScore(*match, team, static_cast<double>(amount)));
3966 return script::projectResult(vm, self->inspectMatch(*match), [](Value value) { return value; });
4016 [vm](RTS* self, const std::string& subjectText, const std::string& resource, float amount, float x, float y,
4041 [vm](RTS* self, int width, int height, float cellSize, float originX, float originY) -> ssq::Table {
4045 cls.addFunc("captureScriptCheckpoint", [vm](RTS* self, const std::string& name) -> ssq::Table {
4048 cls.addFunc("restoreScriptCheckpoint", [vm](RTS* self, const std::string& name) -> ssq::Table {
4055 return script::projectResult(vm, self->loadScriptContent(json), [](ContentImportReceipt receipt) {
4060 cls.addFunc("setScriptNavigationBlocked", [vm](RTS* self, int x, int y, bool blocked) -> ssq::Table {
4063 cls.addFunc("setScriptNavigationCost", [vm](RTS* self, int x, int y, float cost) -> ssq::Table {
4066 cls.addFunc("setScriptTerrainElevation", [vm](RTS* self, int x, int y, float elevation) -> ssq::Table {
4073 cls.addFunc("scriptCellVisible", [vm](RTS* self, const std::string& factionText, int x, int y) -> ssq::Table {
4084 cls.addFunc("scriptCellExplored", [vm](RTS* self, const std::string& factionText, int x, int y) -> ssq::Table {
4136 int attackThreshold, float thinkInterval, float formationSpacing, bool enabled) -> ssq::Table {
4152 self->configureScriptAI(*faction, worker.value(), army.value(), target.value(), desiredWorkers,
4192 vm, self->queueScriptReinforcement(*producer, unitSubject.value(), definition.value(), priority),
4202 const std::string& definitionText, float x, float y, const std::string& builderText) -> ssq::Table {
4220 self->startScriptConstruction(*faction, buildingSubject.value(), definition.value(), {x, y}, *builder),
4223 const auto buildingLifecycle = [vm](RTS* self, const std::string& buildingText, bool sell) -> ssq::Table {
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); });
4238 cls.addFunc("sellScriptBuilding", [buildingLifecycle](RTS* self, const std::string& buildingText) -> ssq::Table {
4243 [vm](RTS* self, const std::string& producerText, const std::string& upgrade, int priority) -> ssq::Table {
4258 "cancelScriptProduction", [vm](RTS* self, const std::string& producerText, int queueIndex) -> ssq::Table {
4264 vm, Status::failure(Diagnostic::error(DiagnosticCode::NotFound, "RTS script producer was not found",
4267 vm, self->cancelScriptProduction(*producer, queueIndex), [](RTSCancelProductionReceipt receipt) {
4290 cls.addFunc("cancelScriptAbility", [vm](RTS* self, const std::string& casterText) -> ssq::Table {
4313 return script::projectResult(vm, self->setBuildingRally(*producer, command, groupedReinforcements));
4316 [vm](RTS* self, const std::string& producerText, const std::string& sourceText) -> ssq::Table {
4330 cls.addFunc("clearBuildingRally", [vm](RTS* self, const std::string& producerText) -> ssq::Table {
4341 "setReinforcementLimit", [vm](RTS* self, const std::string& producerText, std::int64_t maximum) -> ssq::Table {
4353 return script::projectResult(vm, self->setReinforcementLimit(*producer, static_cast<std::size_t>(maximum)));
4375 [vm](RTS* self, const std::string& producerText, const std::string& unitType, int priority) -> ssq::Table {
4383 return script::projectResult(vm, self->setReinforcementTypePriority(*producer, unitType, priority));
4395 return script::projectResult(vm, self->setReinforcementFallback(*producer, preferred, fallback));
4435 vm, self->setReinforcementTransport(*producer, transport, static_cast<std::size_t>(minimumLoad)));
4441 cls.addFunc("importScriptCommandLog", [vm](RTS* self, const std::string& text, bool clearExisting) -> ssq::Table {
4445 [vm](RTS* self, std::int64_t tick, const std::string& factionText, const std::string& builderText,
4471 [vm](RTS* self, std::int64_t tick, const std::string& producerText, const std::string& unitSubjectText,
4493 [vm](RTS* self, std::int64_t tick, const std::string& producerText, const std::string& unitSubjectText,
4515 [vm](RTS* self, std::int64_t tick, const std::string& producerText, const std::string& upgrade,
4556 [vm](RTS* self, std::int64_t tick, const std::string& producerText, int queueIndex) -> ssq::Table {
4571 [vm](RTS* self, std::int64_t tick, const std::vector<std::string>& subjectTexts) -> ssq::Table {
4585 [vm](RTS* self, std::int64_t tick, const std::string& requesterText, float x, float y, float radius,
4618 const auto queueBuildingLifecycle = [vm](RTS* self, std::int64_t tick, const std::string& buildingText,
4633 [queueBuildingLifecycle](RTS* self, std::int64_t tick, const std::string& buildingText) -> ssq::Table {
4634 return queueBuildingLifecycle(self, tick, buildingText, RTSReplayOperation::CancelConstruction);
4637 [queueBuildingLifecycle](RTS* self, std::int64_t tick, const std::string& buildingText) -> ssq::Table {
4742 const auto queueUnitOrder = [vm](RTS* self, std::int64_t tick, const std::vector<std::string>& subjectTexts,
4769 [queueUnitOrder](RTS* self, std::int64_t tick, const std::vector<std::string>& subjects) -> ssq::Table {
4773 [queueUnitOrder](RTS* self, std::int64_t tick, const std::vector<std::string>& subjects) -> ssq::Table {
4777 [queueUnitOrder](RTS* self, std::int64_t tick, const std::vector<std::string>& subjects, float x,
4782 [queueUnitOrder](RTS* self, std::int64_t tick, const std::vector<std::string>& subjects, float x,
4784 return queueUnitOrder(self, tick, subjects, OrderKind::AttackGround, {x, y}, {}, append, -1.0f);
4788 [vm, queueUnitOrder](RTS* self, std::int64_t tick, const std::vector<std::string>& subjects, float x, float y,
4798 [vm, queueUnitOrder](RTS* self, std::int64_t tick, const std::vector<std::string>& subjects, float x, float y,
4859 [vm](RTS* self, const std::vector<std::string>& subjectTexts, float x, float y, bool append) -> ssq::Table {
4866 return script::projectResult(vm, self->commandUnits(std::move(subjects).takeValue(), command), fanOutValue);
4869 [vm](RTS* self, const std::vector<std::string>& subjectTexts, float startX, float startY, float endX,
4955 "assignBuilder", [vm](RTS* self, const std::string& workerText, const std::string& buildingText) -> ssq::Table {
4969 cls.addFunc("addUnitReserveAmmo", [vm](RTS* self, const std::string& subjectText, int rounds) -> ssq::Table {
4980 cls.addFunc("addUnitAmmoSupply", [vm](RTS* self, const std::string& subjectText, float rounds) -> ssq::Table {
4991 cls.addFunc("addBuildingAmmoSupply", [vm](RTS* self, const std::string& subjectText, float rounds) -> ssq::Table {
5002 cls.addFunc("setUnitAutoResupply", [vm](RTS* self, const std::string& subjectText, bool enabled) -> ssq::Table {
5014 [vm](RTS* self, const std::string& sourceText, const std::string& targetText, float amount) -> ssq::Table {
5019 return script::projectResult(vm, self->heal(source.value(), target.value(), static_cast<double>(amount)),
5024 [vm](RTS* self, const std::string& sourceText, const std::string& targetText, const std::string& effect,
5032 self->applyStatusEffect(source.value(), target.value(), effect, static_cast<double>(durationOverride)),
5040 [vm](RTS* self, const std::string& requesterText, float x, float y, float radius, int shotsPerResponder,
5059 cls.addFunc("cancelFireSupport", [vm](RTS* self, const std::string& requesterText) -> ssq::Table {
5072 [vm](RTS* self, const std::vector<std::string>& subjectTexts, float x, float y, float spacing) -> ssq::Table {
5081 return script::projectResult(vm, self->commandUnits(std::move(subjects).takeValue(), command, formation),
5102 return script::projectResult(vm, self->commandUnits(std::move(subjects).takeValue(), command), fanOutValue);
5122 return script::projectResult(vm, self->commandUnits(std::move(subjects).takeValue(), command), fanOutValue);
5142 return script::projectResult(vm, self->commandUnits(std::move(subjects).takeValue(), command), fanOutValue);
5145 [vm](RTS* self, const std::vector<std::string>& subjectTexts, const std::string& transportText,
5164 cls.addFunc("unloadTransport", [vm](RTS* self, const std::string& transportText, float x, float y) -> ssq::Table {
5170 vm, Status::failure(Diagnostic::error(DiagnosticCode::NotFound, "RTS transport identity was not found",
5175 cls.addFunc("evacuateBuilding", [vm](RTS* self, const std::string& buildingText, float x, float y) -> ssq::Table {
5181 vm, Status::failure(Diagnostic::error(DiagnosticCode::NotFound, "RTS building identity was not found",
5186 cls.addFunc("setUnitCloaked", [vm](RTS* self, const std::string& unitText, bool cloaked) -> ssq::Table {
5196 cls.addFunc("stopUnits", [vm](RTS* self, const std::vector<std::string>& subjectTexts) -> ssq::Table {
5201 return script::projectResult(vm, self->commandUnits(std::move(subjects).takeValue(), command), fanOutValue);
5203 cls.addFunc("holdUnits", [vm](RTS* self, const std::vector<std::string>& subjectTexts) -> ssq::Table {
5208 return script::projectResult(vm, self->commandUnits(std::move(subjects).takeValue(), command), fanOutValue);
Renderer- and ruleset-neutral gameplay action pipeline.
std::vector< std::unique_ptr< ScriptClimbingEventSink > > live
Definition ClimbingServices.cpp:187
Resource-account adapter backed by an EconomyLedger.
#define EV_PROFILE_MODULE(module, name)
Profile the enclosing scope, tagged with a module for grouping.
Definition Profile.h:158
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.
The single Squirrel projection for common Result, Status and Value.
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.
Definition Diagnostic.cpp:21
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
Owner-thread lifetime observation; cannot retain or access its owner.
Definition LifetimeWitness.h:6
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
const Status & status() const noexcept
Inspect the structured operation status.
Definition Result.h:521
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
static Status success(StatusCode code=StatusCode::Ok)
Construct a successful status with an explicit non-error outcome.
Definition Status.cpp:19
static Status failure(StatusCode code, Diagnostic diagnostic)
Construct a failed status with one diagnostic.
Definition Status.cpp:28
static SubjectRef fromPersistentId(PersistentId id) noexcept
Wrap a persistent identity without changing its bytes.
Definition SubjectRef.h:32
bool isValid() const noexcept
Return whether this reference is valid and non-nil.
Definition SubjectRef.h:38
static Result< Value > fromJson(std::string_view json)
Parse one strict JSON value into an owning Value.
Definition Value.cpp:177
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
Dynamic field-of-view / fog-of-war facade. Phase A: 2D shadowcast + multi-revealer + explored memory....
Definition Fov.h:27
static eve::Result< CostSpec > create(std::vector< ResourceCost > items)
Validate and canonicalize resource items.
Definition ResourceAccount.cpp:74
static eve::Result< CostSpec > single(std::string_view resource, std::int64_t amount)
Build a one-resource cost.
Definition ResourceAccount.cpp:117
Provider-neutral resource account contract.
Definition ResourceAccount.h:316
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
static Building * createBuilding(SubjectRef subject={}, LogicalId definition={})
Create a building and initialize its self handle and identity.
Definition RTSTypes.cpp:667
static Result< EntityLink > bind(ecs::EntityHandle handle)
Bind a live ECS handle, rejecting a null or stale handle.
Definition RTSTypes.h:189
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
static void clear(State &state) noexcept
Remove all revealers previously installed by this state.
Definition RTSSystems.cpp:1130
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...
Definition RTSMission.cpp:479
static Result< void > addTrigger(Match &match, MissionTrigger trigger)
Register one trigger definition (Setup or Running). @cost Linear in existing trigger count for duplic...
Definition RTSMission.cpp:464
static Result< void > pushEvent(Match &match, MissionPendingEvent event)
Push one custom (or domain) event onto the campaign pending queue. @cost Amortized constant; triggers...
Definition RTSMission.cpp:568
static Result< void > addTimer(Match &match, MissionTimer timer)
Register one countdown timer; optionally start it immediately. @cost Linear in existing timer count f...
Definition RTSMission.cpp:499
static Result< void > setVariable(Match &match, std::string id, double value)
Create or overwrite one named campaign variable.
Definition RTSMission.cpp:515
static Result< void > clearActionLog(Match &match) noexcept
Clear retained Script action log entries after the game layer has consumed them.
Definition RTSMission.cpp:594
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 ®istry, Unit &unit, const ArchetypeWeaponFactory &weaponFactory={})
Apply the Unit root's logical definition atomically.
Definition RTSAction.cpp:241
static eve::Result< void > ensure(Unit &unit)
Bind and seed default optional combat stats exactly once.
Definition RTSAttributes.cpp:24
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
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.
Definition RTSSnapshot.cpp:1291
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
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.
Definition RTSCommands.cpp:4
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
static Result< ServiceLink > bind(std::string_view key)
Bind a non-empty provider key.
Definition RTSTypes.h:248
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.
Definition SettlementRules.h:77
static eve::Result< SettlementRuleSet > fromJson(std::string_view json)
Decode and compile a strict versioned JSON rule document without mutating an existing rule set.
Definition SettlementRuleJson.cpp:165
static eve::Result< WeaponDefinitionRuntime > create(eve::definitions::DefinitionRegistry ®istry, eve::DefinitionRef definition, eve::PersistentId instanceId, eve::definition::ReloadPolicy policy=eve::definition::ReloadPolicy::RebuildInstance)
Create from a common weapon:<name> definition reference.
Definition WeaponDefinitionRuntime.cpp:423
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
@ Building
@ Flinch
@ Stagger
@ Knockdown
CrowdExecution
Explicit execution selection; serial does not require a provider.
Definition CrowdWorkScheduler.h:7
std::variant< std::monostate, std::int64_t, double, std::string, bool > Value
Definition Database.h:27
@ Completed
@ Cancelled
Value fanOutValue(FanOutReceipt receipt)
Definition RTSScriptInternal.h:35
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...
Definition RTSScriptInternal.h:24
Result< SubjectRef > parseScriptSubject(std::string_view text, std::string_view path)
Definition RTSScriptInternal.h:12
Result< RTSEffectDefinition > resolveEffectDefinition(definitions::DefinitionRegistry ®istry, std::string_view id, SubjectRef source, double durationOverride)
Definition RTSScriptActions.cpp:8
Definition RTS.cpp:30
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
@ Attack
RTSReplayOperation
Stable operation kinds accepted by the shared deterministic RTS input stream.
Definition RTSReplay.h:20
@ Running
@ Setup
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.
Definition RTSArchetype.h:18
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
const char * orderKindName(OrderKind kind) noexcept
Return the stable lower-case spelling of an RTS order kind.
Definition RTSTypes.cpp:177
@ ScoreTarget
@ Mission
Campaign/mission mode: Match::Objectives own completion and failure settlement.
@ Annihilation
@ DestroyHeadquarters
@ ResourceTarget
ssq::Table projectStatusResult(HSQUIRRELVM vm, const Status &status)
Project a checked native status that carries no payload.
Definition SquirrelBinding.cpp:524
ssq::Table projectResult(HSQUIRRELVM vm, Result< void > &&result)
Consume and project a void native Result using the common schema.
Definition SquirrelBinding.cpp:540
std::string_view statusName(BattleStatus status) noexcept
Return the stable protocol spelling of a battle status.
Definition TacticsTypes.cpp:216
@ InvalidArgument
@ NotFound
@ PreconditionViolation
@ Unsupported
@ Failed
@ StaleHandle
@ Conflict
StrongUuid< detail::PersistentIdTag > PersistentId
Stable instance identity for persistence, networking and process boundaries.
Definition Identity.h:253
@ NotFound
@ NoOp
@ Applied
@ Object
@ PlayerEquivalent
detail::StrongUint64< detail::SimulationTickTag > SimulationTick
Deterministic simulation time step; it is not wall-clock time.
Definition Time.h:31
Definition Container.h:602
Owning evidence that a gameplay authority accepted one command.
Definition GameplayControl.h:62
std::uint64_t resultingRevision
Definition GameplayControl.h:66
One player-semantic command submitted to a domain authority.
Definition GameplayControl.h:52
Owning event projection safe across frames and process boundaries.
Definition GameplayControl.h:71
Immutable owning observation of one authoritative gameplay instance.
Definition GameplayControl.h:43
Owning authorization context shared by player, script and automation adapters.
Definition GameplayControl.h:30
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
Optional bounded velocity sampling for RTS local avoidance.
Definition Crowd.h:129
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.
Definition ResourceAccount.cpp:63
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
Result< void > validate() const
Validate coordinates and command metadata without mutating state.
Definition RTSTypes.cpp:201
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
Definition RTS.cpp:170
std::vector< PaidConstruction > paidConstruction
Definition RTSScriptRuntimeInternal.h:41
std::vector< float > terrainElevations
Definition RTSScriptRuntimeInternal.h:44
std::map< std::string, economy::EconomyLedger::Snapshot > economies
Definition RTSScriptRuntimeInternal.h:37
std::map< std::string, SubjectRef > pendingProductionSubjects
Definition RTSScriptRuntimeInternal.h:39
RTSStateSnapshot roots
Definition RTSScriptRuntimeInternal.h:36
std::uint64_t aiProductionSequence
Definition RTSScriptRuntimeInternal.h:46
std::vector< PaidProduction > paidProduction
Definition RTSScriptRuntimeInternal.h:40
RTSCommandLog commandLog
Definition RTSScriptRuntimeInternal.h:42
std::map< std::string, map::Fov::Snapshot > fovs
Definition RTSScriptRuntimeInternal.h:38
crowd::Crowd::Snapshot crowdState
Definition RTSScriptRuntimeInternal.h:35
std::vector< float > navigationCosts
Definition RTSScriptRuntimeInternal.h:43
std::uint64_t nextTick
Definition RTSScriptRuntimeInternal.h:45