Compare commits

..

1 Commits

Author SHA1 Message Date
zhexu14
ef8eeeb1f1 Update README.md due to changes in URLs 2024-03-05 21:45:23 +11:00
357 changed files with 3795 additions and 13636 deletions

View File

@@ -31,7 +31,7 @@ body:
If the bug was found in a development build, select "Development build"
and provide a link to the build in the field below.
options:
- 14.0.0
- 10.0.0
- Development build
- type: textarea
attributes:

View File

@@ -39,7 +39,7 @@ body:
If the bug was found in a development build, select "Development build"
and provide a link to the build in the field below.
options:
- 14.0.0
- 10.0.0
- Development build
- type: textarea
attributes:

View File

@@ -4,7 +4,7 @@ runs:
using: composite
steps:
- name: Set up Node
uses: actions/setup-node@v4
uses: actions/setup-node@v2
with:
node-version: "16"
cache: npm

View File

@@ -4,9 +4,9 @@ runs:
using: composite
steps:
- name: Set up Python
uses: actions/setup-python@v5
uses: actions/setup-python@v2
with:
python-version: "3.11.4"
python-version: "3.11"
cache: pip
- name: Install environment

View File

@@ -12,7 +12,7 @@ jobs:
build:
runs-on: windows-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v2
with:
submodules: true
@@ -35,7 +35,7 @@ jobs:
Compress-Archive -Path .\dist\dcs_liberation\ -DestinationPath
dist\dcs_liberation.zip
- uses: actions/upload-artifact@v4
- uses: actions/upload-artifact@v2
with:
name: dcs_liberation
path: dist/dcs_liberation.zip

View File

@@ -7,11 +7,11 @@ jobs:
name: Black
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
- uses: actions/checkout@v2
- uses: actions/setup-python@v2
- uses: psf/black@stable
with:
version: ~=24.3.0
version: ~=23.11
src: "."
options: "--check"
@@ -19,7 +19,7 @@ jobs:
name: Type checking
runs-on: windows-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v2
with:
submodules: true

View File

@@ -14,7 +14,7 @@ jobs:
build:
runs-on: windows-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v2
with:
submodules: true
@@ -33,7 +33,7 @@ jobs:
with:
release: true
- uses: actions/upload-artifact@v4
- uses: actions/upload-artifact@v2
with:
name: dcs_liberation
path: dist/
@@ -42,7 +42,7 @@ jobs:
needs: [build]
runs-on: windows-latest
steps:
- uses: actions/download-artifact@v4.1.7
- uses: actions/download-artifact@v2
with:
name: dcs_liberation

View File

@@ -5,7 +5,7 @@ jobs:
name: Python tests
runs-on: windows-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v2
with:
submodules: true
@@ -24,7 +24,7 @@ jobs:
name: Typescript tests
runs-on: windows-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v2
- name: Set up JS environment
uses: ./.github/actions/setup-liberation-js

View File

@@ -2,6 +2,8 @@
(Github Readme Banner and Splash screen Artwork by Andriy Dankovych, CC BY-SA 4.0)
[![Patreon](https://img.shields.io/badge/patreon-become%20a%20patron-orange?logo=patreon)](https://patreon.com/dcsliberation)
[![Download](https://img.shields.io/github/downloads/dcs-liberation/dcs_liberation/total?label=Download)](https://github.com/dcs-liberation/dcs_liberation/releases)
[![Discord](https://img.shields.io/discord/595702951800995872?label=Discord&logo=discord)](https://discord.gg/bKrtrkJ)
@@ -15,6 +17,11 @@
DCS Liberation is a [DCS World](https://www.digitalcombatsimulator.com/en/products/world/) turn based single-player or co-op dynamic campaign.
It is an external program that generates full and complex DCS missions and manage a persistent combat environment.
**Note that DCS Liberation does not support the stable release of DCS. We can
only guarantee compatibility with either the open beta or the stable release,
and more people play the open beta. DCS stable _might_ work sometimes, but it's
untested, and we will be unable to fix any bugs unique to stable DCS.**
![Screenshot](https://user-images.githubusercontent.com/315852/120939254-0b4a9f80-c6cc-11eb-82f5-ce3f8d714bfe.png)
## Downloads

View File

@@ -1,99 +1,13 @@
# 14.0.0
Saves from 13.x are not compatible with 14.0.0.
## Features/Improvements
* **[Engine]** Support for DCS 2.9.21.
* **[Engine]** Support for MiG-29 Fulcrum (full fidelity version).
* **[Engine]** Support for F-14A-135-GR Early.
* **[Mods]** A4EC mod version updated to 2.3.
* **[UI]** Allow saving after fast forwarding manually with sim speed controls (--show-sim-speed-controls option).
* **[UI]** Add new option to fast forward until player is at the IP.
## Fixes
* **[Campaign]** Units are restored to full health when repaired.
* **[UI]** Air Wing and Transfers buttons disabled when no game is loaded as pressing them without a game loaded resulted in a crash.
* **[UI]** A package is cancelled (deleted) when the last flight in the package is cancelled instead of showing "No mission".
# 13.0.0
Saves from 12.x are not compatible with 13.0.0.
## Features/Improvements
* **[Engine]** Support for DCS 2.9.12.5536.
* **[Data]** Support for CH-47 Chinook.
## Fixes
* **[Data]** Added/updated CBU weapons data.
* **[Data]** Added Strike mission type for KA-50 (all playable variants).
* **[Mission Generation]** Fixed crash when using factions that have Eastern callsign conventions.
* **[Mission Generation]** Fixed issues when spawning on carriers and FARPs in multiplayer sessions.
# 12.0.0
Saves from 11.x are not compatible with 12.0.0.
## Features/Improvements
* **[Engine]** Support for DCS 2.9.9.2280.
* **[Campaign]** Flights are assigned different callsigns appropriate to the faction.
* **[Campaign]** Removed deprecated settings for generating persistent and invulnerable AWACs and tankers.
* **[Data]** Added ability to restrict weapons usage for a faction to a different year from the nominal weapon introduction year. Updated faction data to restrict more advanced missiles from Soviet client states during the cold war. Updated Egypt 2000 faction to restrict AIM-120 usage.
* **[Mission Generation]** Added option to skip combat when fast forwarding, which progresses fast forward as if the combat did not occur. Simplified fast forward settings by consolidating "Fast forward mission to first contact" and "Player missions interrupt fast forward" into a single setting and expanding options for "Auto-resolve combat during fast-forward (WIP)".
* **[Mods]** F/A-18 E/F/G Super Hornet mod version updated to 2.3.
## Fixes
* **[Data]** Added/updated weapons data for F4E weapons such as AIM-7, AIM-9, AGM-12, AGM-45 and AGM-65.
* **[Campaign]** Do not allow aircraft from a captured control point to retreat if the captured control point has a damaged runway.
* **[Campaign]** Do not allow ground units to be transferred to LHAs, CVNs or off map spawns.
* **[Mission Generation]** Fixed aircraft not spawning correctly on CVNs, LHAs and FARPs.
# 11.1.1
Saves from 11.0.0 are compatible with 11.1.1. See Known Issues section for exceptions.
## Features/Improvements
* **[Engine]** Support for DCS 2.9.5.55918 including Heatblur F-4E and Polychop OH-58D Kiowa Warrior support.
## Fixes
* **[Campaign]** Fixed double counting of parked aircraft kills when DCS reports multiple kill events.
* **[Campaign]** Fixed error where frontline units are not re-deployed when multiple control points were captured in one turn or when control points are captured "out of order" using air-assault missions.
* **[Cheat Menu]** Re-deploy frontline units when using cheats to capture control points, so that cheats behave the same way as capturing a control point in-mission.
* **[Data]** Added FuSe-65 Early Warning Radar.
* **[Data]** Updated Peru 1995 and Germany 1944 factions.
* **[Flight Planning]** Theater refuelling flight plans (those not tied to a particular package) will remain on station for a longer period, specifically the desired mission duration + 30 minutes. By default, this increases the on-station time from 1 hour to 1.5 hours.
* **[Mission Generation]** Patched bug where Liberation crashed when aborting a turn when Fighter Sweep missions were planned.
* **[Radios]** Added radio setup for F-5E, F-86, Mi-8 and Mi-24.
* **[UI]** Naval control points (carriers, LHAs) can no longer be moved onto land.
## Known Issues
* When loading saves from 11.0, loadouts with AGM-45B (Imp), typically on A-4E-C mod, will have the AGM-45B replaced with an empty pylon due to changes in DCS for this weapon. The AGM-45A is not affected by this issue.
# 11.0.0
Saves from 10.x are not compatible with 11.0.0.
## Features/Improvements
* **[Engine]** Support for DCS 2.9.3.51704.
* **[Campaign]** Improved tracking of parked aircraft deaths. Parked aircraft are now considered dead once sufficient damage is done, meaning guns, rockets and AGMs are viable weapons for OCA/Aircraft missions. Previously Liberation relied on DCS death tracking which required parked aircraft to be hit with more powerful weapons e.g. 2000lb bombs as they were uncontrolled.
* **[Campaign]** Track damage to theater ground objects across turns. Damage can accumulate across turns leading to death of the unit. This behavior only applies to SAMs, ships and other units that appear on the Liberation map. Frontline units and buildings are not tracked (yet).
* **[Mods]** F/A-18 E/F/G Super Hornet mod (v2.2.5) support added.
* **[Engine]** Support for DCS 2.9.3.51704 Open Beta.
## Fixes
* **[Mission Generation]** When planning anti-ship missions against carriers or LHAs, target escorts (if present) if the carrier/LHA is sunk.
* **[UI]** Identify that a carrier or LHA is sunk instead of "damaged".
# 10.0.0
Saves from 9.x are not compatible with 10.0.0.

2298
client/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -15,7 +15,7 @@
"@types/react": "^18.0.21",
"@types/react-dom": "^18.0.6",
"@types/react-redux": "^7.1.24",
"axios": "^1.12.1",
"axios": "^1.6.0",
"electron-window-state": "^5.0.3",
"esri-leaflet": "^3.0.8",
"leaflet": "^1.9.2",
@@ -66,7 +66,7 @@
"@types/leaflet": "^1.8.0",
"@types/redux-logger": "^3.0.9",
"@types/websocket": "^1.0.5",
"electron": "^35.7.5",
"electron": "^22.3.25",
"electron-is-dev": "^2.0.0",
"generate-license-file": "^2.0.0",
"jest-transform-stub": "^2.0.0",
@@ -74,7 +74,7 @@
"msw": "^1.2.2",
"react-scripts": "5.0.1",
"ts-node": "^10.9.1",
"wait-on": "^8.0.0"
"wait-on": "^6.0.1"
},
"jest": {
"transformIgnorePatterns": [

View File

@@ -7,9 +7,9 @@
# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information
project = "DCS Liberation"
copyright = "2025, DCS Liberation Team"
copyright = "2023, DCS Liberation Team"
author = "DCS Liberation Team"
release = "14.0.0"
release = "11.0.0"
# -- General configuration ---------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration

View File

@@ -1,5 +1,4 @@
"""Objective adjacency lists."""
from __future__ import annotations
from typing import Dict, Iterator, List, Optional, TYPE_CHECKING

View File

@@ -12,7 +12,6 @@ from .flightmembers import FlightMembers
from .flightroster import FlightRoster
from .flightstate import FlightState, Navigating, Uninitialized
from .flightstate.killed import Killed
from .flighttype import FlightType
from ..sidc import (
Entity,
SidcDescribable,
@@ -22,7 +21,6 @@ from ..sidc import (
)
if TYPE_CHECKING:
from game.callsigns.callsigngenerator import Callsign
from game.dcs.aircrafttype import AircraftType
from game.sim.gameupdateevents import GameUpdateEvents
from game.sim.simulationresults import SimulationResults
@@ -32,6 +30,7 @@ if TYPE_CHECKING:
from game.data.weapons import WeaponType
from .flightmember import FlightMember
from .flightplans.flightplan import FlightPlan
from .flighttype import FlightType
from .flightwaypoint import FlightWaypoint
from .package import Package
from .starttype import StartType
@@ -50,7 +49,6 @@ class Flight(SidcDescribable):
custom_name: Optional[str] = None,
cargo: Optional[TransferOrder] = None,
roster: Optional[FlightRoster] = None,
callsign: Optional[Callsign] = None,
) -> None:
self.id = uuid.uuid4()
self.package = package
@@ -58,8 +56,7 @@ class Flight(SidcDescribable):
self.coalition = squadron.coalition
self.squadron = squadron
self.flight_type = flight_type
if flight_type != FlightType.IDLE:
self.squadron.claim_inventory(count)
self.squadron.claim_inventory(count)
if roster is None:
self.roster = FlightMembers(self, initial_size=count)
else:
@@ -72,8 +69,6 @@ class Flight(SidcDescribable):
# Only used by transport missions.
self.cargo = cargo
self.callsign = callsign
# Flight properties that can be set in the mission editor. This is used for
# things like HMD selection, ripple quantity, etc. Any values set here will take
# the place of the defaults defined by DCS.
@@ -110,6 +105,19 @@ class Flight(SidcDescribable):
waypoint.actions.clear()
waypoint.options.clear()
def __getstate__(self) -> dict[str, Any]:
state = self.__dict__.copy()
# Avoid persisting the flight state since that's not (currently) used outside
# mission generation. This is a bit of a hack for the moment and in the future
# we will need to persist the flight state, but for now keep it out of save
# compat (it also contains a generator that cannot be pickled).
del state["state"]
return state
def __setstate__(self, state: dict[str, Any]) -> None:
state["state"] = Uninitialized(self, state["squadron"].settings)
self.__dict__.update(state)
@property
def blue(self) -> bool:
return self.squadron.player

View File

@@ -69,15 +69,6 @@ class FlightMembers(IFlightRoster):
self.flight.squadron.return_pilot(current_pilot)
self.members[index].pilot = pilot
def remove_pilot(self, pilot: Pilot) -> None:
for i, member in enumerate(self.members):
if member.pilot is not None and member.pilot.name == pilot.name:
self.members.pop(i)
if (code := member.tgp_laser_code) is not None:
code.release()
return
raise ValueError(f"Pilot {pilot.name} not a member")
def clear(self) -> None:
self.flight.squadron.return_pilots(
[p for p in self.iter_pilots() if p is not None]

View File

@@ -12,7 +12,7 @@ from game.utils import Distance, Heading, Speed, feet, knots, meters, nautical_m
class AewcFlightPlan(PatrollingFlightPlan[PatrollingLayout]):
@property
def patrol_duration(self) -> timedelta:
return self.flight.coalition.doctrine.aewc.duration
return timedelta(hours=4)
@property
def patrol_speed(self) -> Speed:

View File

@@ -5,7 +5,6 @@ MissionPlanner. Those only plan basic information like the objective, aircraft
type, and the size of the flight. The FlightPlanBuilder is responsible for
generating the waypoints for the mission.
"""
from __future__ import annotations
import math

View File

@@ -64,7 +64,6 @@ class FlightPlanBuilderTypes:
FlightType.TRANSPORT: AirliftFlightPlan.builder_type(),
FlightType.FERRY: FerryFlightPlan.builder_type(),
FlightType.AIR_ASSAULT: AirAssaultFlightPlan.builder_type(),
FlightType.IDLE: BarCapFlightPlan.builder_type(),
}
try:
return builder_dict[flight.flight_type]

View File

@@ -30,7 +30,8 @@ LayoutT = TypeVar("LayoutT", bound=FormationLayout)
class FormationFlightPlan(LoiterFlightPlan[LayoutT], ABC):
@property
@abstractmethod
def package_speed_waypoints(self) -> set[FlightWaypoint]: ...
def package_speed_waypoints(self) -> set[FlightWaypoint]:
...
@property
def combat_speed_waypoints(self) -> set[FlightWaypoint]:
@@ -68,11 +69,13 @@ class FormationFlightPlan(LoiterFlightPlan[LayoutT], ABC):
@property
@abstractmethod
def join_time(self) -> datetime: ...
def join_time(self) -> datetime:
...
@property
@abstractmethod
def split_time(self) -> datetime: ...
def split_time(self) -> datetime:
...
def tot_for_waypoint(self, waypoint: FlightWaypoint) -> datetime | None:
if waypoint == self.layout.join:

View File

@@ -60,7 +60,8 @@ class IBuilder(ABC, Generic[FlightPlanT, LayoutT]):
return self.flight.departure.theater
@abstractmethod
def build(self, dump_debug_info: bool = False) -> FlightPlanT: ...
def build(self, dump_debug_info: bool = False) -> FlightPlanT:
...
@property
def package(self) -> Package:

View File

@@ -30,7 +30,8 @@ class LoiterFlightPlan(StandardFlightPlan[LayoutT], ABC):
@property
@abstractmethod
def push_time(self) -> datetime: ...
def push_time(self) -> datetime:
...
def depart_time_for_waypoint(self, waypoint: FlightWaypoint) -> datetime | None:
if waypoint == self.layout.hold:

View File

@@ -17,13 +17,7 @@ class TheaterRefuelingFlightPlan(RefuelingFlightPlan):
@property
def patrol_duration(self) -> timedelta:
# Add 30 minutes to desired_player_mission_duration as TOTs for flights
# can sit up to this time. This extension means the tanker remains on
# station for the flights' return.
return (
self.flight.coalition.game.settings.desired_player_mission_duration
+ timedelta(minutes=30)
)
return timedelta(hours=1)
class Builder(IBuilder[TheaterRefuelingFlightPlan, PatrollingLayout]):

View File

@@ -14,4 +14,5 @@ class UiZone:
class UiZoneDisplay(abc.ABC):
@abc.abstractmethod
def ui_zone(self) -> UiZone: ...
def ui_zone(self) -> UiZone:
...

View File

@@ -21,14 +21,8 @@ class FlightState(ABC):
self.settings = settings
self.avoid_further_combat = False
def initialize(self, now: datetime) -> None:
from game.ato.flightstate import Uninitialized, WaitingForStart
# Flight objects are created with Uninitialized state. However when the simulation runs
# the flight state changes and may be serialized. We only want to initialize the state
# for newly created flights and not ones deserialized from a save file.
if type(self.flight.state) != Uninitialized:
return
def reinitialize(self, now: datetime) -> None:
from game.ato.flightstate import WaitingForStart
if self.flight.flight_plan.startup_time() <= now:
self._set_active_flight_state(now)
@@ -63,12 +57,14 @@ class FlightState(ABC):
@property
@abstractmethod
def cancelable(self) -> bool: ...
def cancelable(self) -> bool:
...
@abstractmethod
def on_game_tick(
self, events: GameUpdateEvents, time: datetime, duration: timedelta
) -> None: ...
) -> None:
...
@property
def in_flight(self) -> bool:
@@ -99,14 +95,17 @@ class FlightState(ABC):
@property
@abstractmethod
def is_waiting_for_start(self) -> bool: ...
def is_waiting_for_start(self) -> bool:
...
@abstractmethod
def estimate_position(self) -> Point: ...
def estimate_position(self) -> Point:
...
@property
@abstractmethod
def spawn_type(self) -> StartType: ...
def spawn_type(self) -> StartType:
...
def a2a_commit_region(self) -> Optional[ThreatPoly]:
return None

View File

@@ -3,7 +3,6 @@ from __future__ import annotations
from abc import ABC, abstractmethod
from collections import deque
from datetime import datetime, timedelta
import logging
from typing import TYPE_CHECKING
from dcs import Point
@@ -14,7 +13,6 @@ from game.ato.flightstate.flightstate import FlightState
from game.ato.flightwaypoint import FlightWaypoint
from game.ato.flightwaypointtype import FlightWaypointType
from game.ato.starttype import StartType
from game.settings.settings import FastForwardStopCondition
from game.utils import Distance, LBS_TO_KG, Speed, pairwise
if TYPE_CHECKING:
@@ -69,13 +67,16 @@ class InFlight(FlightState, ABC):
)
@abstractmethod
def estimate_position(self) -> Point: ...
def estimate_position(self) -> Point:
...
@abstractmethod
def estimate_altitude(self) -> tuple[Distance, str]: ...
def estimate_altitude(self) -> tuple[Distance, str]:
...
@abstractmethod
def estimate_speed(self) -> Speed: ...
def estimate_speed(self) -> Speed:
...
def estimate_fuel_at_current_waypoint(self) -> float:
initial_fuel = super().estimate_fuel()
@@ -166,17 +167,3 @@ class InFlight(FlightState, ABC):
@property
def spawn_type(self) -> StartType:
return StartType.IN_FLIGHT
def should_halt_sim(self) -> bool:
if (
self.flight.client_count > 0
and self.settings.fast_forward_stop_condition
== FastForwardStopCondition.PLAYER_AT_IP
and self.is_at_ip
):
logging.info(
f"Interrupting simulation because {self.flight} has players and has "
"reached IP"
)
return True
return False

View File

@@ -8,9 +8,6 @@ from .atdeparture import AtDeparture
from .taxi import Taxi
from ..starttype import StartType
from game.settings.settings import FastForwardStopCondition
if TYPE_CHECKING:
from game.ato.flight import Flight
from game.settings import Settings
@@ -40,8 +37,7 @@ class StartUp(AtDeparture):
def should_halt_sim(self) -> bool:
if (
self.flight.client_count > 0
and self.settings.fast_forward_stop_condition
== FastForwardStopCondition.PLAYER_STARTUP
and self.settings.player_mission_interrupts_sim_at is StartType.COLD
):
logging.info(
f"Interrupting simulation because {self.flight} has players and has "

View File

@@ -9,8 +9,6 @@ from .navigating import Navigating
from ..starttype import StartType
from ...utils import LBS_TO_KG
from game.settings.settings import FastForwardStopCondition
if TYPE_CHECKING:
from game.ato.flight import Flight
from game.settings import Settings
@@ -47,8 +45,7 @@ class Takeoff(AtDeparture):
def should_halt_sim(self) -> bool:
if (
self.flight.client_count > 0
and self.settings.fast_forward_stop_condition
== FastForwardStopCondition.PLAYER_TAKEOFF
and self.settings.player_mission_interrupts_sim_at is StartType.RUNWAY
):
logging.info(
f"Interrupting simulation because {self.flight} has players and has "

View File

@@ -8,8 +8,6 @@ from .atdeparture import AtDeparture
from .takeoff import Takeoff
from ..starttype import StartType
from game.settings.settings import FastForwardStopCondition
if TYPE_CHECKING:
from game.ato.flight import Flight
from game.settings import Settings
@@ -39,8 +37,7 @@ class Taxi(AtDeparture):
def should_halt_sim(self) -> bool:
if (
self.flight.client_count > 0
and self.settings.fast_forward_stop_condition
== FastForwardStopCondition.PLAYER_TAXI
and self.settings.player_mission_interrupts_sim_at is StartType.WARM
):
logging.info(
f"Interrupting simulation because {self.flight} has players and has "

View File

@@ -20,7 +20,7 @@ class Uninitialized(FlightState):
def on_game_tick(
self, events: GameUpdateEvents, time: datetime, duration: timedelta
) -> None:
self.initialize(time)
self.reinitialize(time)
self.flight.state.on_game_tick(events, time, duration)
@property

View File

@@ -57,7 +57,6 @@ class FlightType(Enum):
REFUELING = "Refueling"
FERRY = "Ferry"
AIR_ASSAULT = "Air Assault"
IDLE = "Idle"
def __str__(self) -> str:
return self.value

View File

@@ -9,20 +9,26 @@ if TYPE_CHECKING:
class IFlightRoster(ABC):
@abstractmethod
def iter_pilots(self) -> Iterator[Pilot | None]: ...
def iter_pilots(self) -> Iterator[Pilot | None]:
...
@abstractmethod
def pilot_at(self, idx: int) -> Pilot | None: ...
def pilot_at(self, idx: int) -> Pilot | None:
...
@property
@abstractmethod
def max_size(self) -> int: ...
def max_size(self) -> int:
...
@abstractmethod
def resize(self, new_size: int) -> None: ...
def resize(self, new_size: int) -> None:
...
@abstractmethod
def set_pilot(self, index: int, pilot: Optional[Pilot]) -> None: ...
def set_pilot(self, index: int, pilot: Optional[Pilot]) -> None:
...
@abstractmethod
def clear(self) -> None: ...
def clear(self) -> None:
...

View File

@@ -10,8 +10,6 @@ from dcs.unittype import FlyingType
from game.data.weapons import Pylon, Weapon, WeaponType
from game.dcs.aircrafttype import AircraftType
from game.factions.faction import Faction
from .flighttype import FlightType
if TYPE_CHECKING:
@@ -54,7 +52,6 @@ class Loadout:
weapon: Weapon,
pylon: Pylon,
date: datetime.date,
faction: Faction,
skip_types: Optional[Iterable[WeaponType]] = None,
) -> Optional[Weapon]:
if skip_types is None:
@@ -62,16 +59,14 @@ class Loadout:
for fallback in weapon.fallbacks:
if not pylon.can_equip(fallback):
continue
if not fallback.available_on(date, faction):
if not fallback.available_on(date):
continue
if fallback.weapon_group.type in skip_types:
continue
return fallback
return None
def degrade_for_date(
self, unit_type: AircraftType, date: datetime.date, faction: Faction
) -> Loadout:
def degrade_for_date(self, unit_type: AircraftType, date: datetime.date) -> Loadout:
if self.date is not None and self.date <= date:
return Loadout(self.name, self.pylons, self.date, self.is_custom)
@@ -80,9 +75,9 @@ class Loadout:
if weapon is None:
del new_pylons[pylon_number]
continue
if not weapon.available_on(date, faction):
if not weapon.available_on(date):
pylon = Pylon.for_aircraft(unit_type, pylon_number)
fallback = self._fallback_for(weapon, pylon, date, faction)
fallback = self._fallback_for(weapon, pylon, date)
if fallback is None:
del new_pylons[pylon_number]
else:
@@ -94,11 +89,11 @@ class Loadout:
# If the loadout was chosen explicitly by the user, assume they know what
# they're doing. They may be coordinating buddy-lase.
if not loadout.is_custom:
loadout.replace_lgbs_if_no_tgp(unit_type, date, faction)
loadout.replace_lgbs_if_no_tgp(unit_type, date)
return loadout
def replace_lgbs_if_no_tgp(
self, unit_type: AircraftType, date: datetime.date, faction: Faction
self, unit_type: AircraftType, date: datetime.date
) -> None:
if self.has_weapon_of_type(WeaponType.TGP):
return
@@ -111,7 +106,7 @@ class Loadout:
if weapon is not None and weapon.weapon_group.type is WeaponType.LGB:
pylon = Pylon.for_aircraft(unit_type, pylon_number)
fallback = self._fallback_for(
weapon, pylon, date, faction, skip_types={WeaponType.LGB}
weapon, pylon, date, skip_types={WeaponType.LGB}
)
if fallback is None:
del new_pylons[pylon_number]

View File

@@ -1,5 +1,4 @@
"""Support for working with DCS group callsigns."""
import logging
import re
from typing import Any

View File

@@ -1,253 +0,0 @@
from __future__ import annotations
from abc import ABC
from dataclasses import dataclass
from enum import StrEnum
from collections import deque
from typing import Any, List, Optional
from dcs.country import Country
from dcs.countries import countries_by_name
from game.ato.flight import Flight
from game.ato.flighttype import FlightType
MAX_GROUP_ID = 99
class CallsignCategory(StrEnum):
AIR = "Air"
TANKERS = "Tankers"
AWACS = "AWACS"
GROUND_UNITS = "GroundUnits"
HELIPADS = "Helipad"
GRASS_AIRFIELDS = "GrassAirfield"
@dataclass(frozen=True)
class Callsign:
name: Optional[
str
] # Callsign name e.g. "Enfield" for western callsigns. None for eastern callsigns.
group_id: int # ID of the group e.g. 2 in Enfield-2-3 for western callsigns. First two digits of eastern callsigns.
unit_id: int # ID of the unit e.g. 3 in Enfield-2-3 for western callsigns. Last digit of eastern callsigns.
def __post_init__(self) -> None:
if self.group_id < 1 or self.group_id > MAX_GROUP_ID:
raise ValueError(
f"Invalid group ID {self.group_id}. Group IDs have to be between 1 and {MAX_GROUP_ID}."
)
if self.unit_id < 1 or self.unit_id > 9:
raise ValueError(
f"Invalid unit ID {self.unit_id}. Unit IDs have to be between 1 and 9."
)
def __str__(self) -> str:
if self.name is not None:
return f"{self.name}{self.group_id}{self.unit_id}"
else:
return str(self.group_id * 10 + self.unit_id)
def lead_callsign(self) -> Callsign:
return Callsign(self.name, self.group_id, 1)
def unit_callsign(self, unit_id: int) -> Callsign:
return Callsign(self.name, self.group_id, unit_id)
def group_name(self) -> str:
if self.name is not None:
return f"{self.name}-{self.group_id}"
else:
return str(self.lead_callsign())
def pydcs_dict(self, country: str) -> dict[Any, Any]:
country_obj = countries_by_name[country]()
for category in CallsignCategory:
if category in country_obj.callsign:
for index, name in enumerate(country_obj.callsign[category]):
if name == self.name:
return {
"name": str(self),
1: index + 1,
2: self.group_id,
3: self.unit_id,
}
raise ValueError(f"Could not find callsign {name} in {country}.")
class WesternGroupIdRegistry:
def __init__(self, country: Country, max_group_id: int = MAX_GROUP_ID):
self._names: dict[str, deque[int]] = {}
for category in CallsignCategory:
if category in country.callsign:
for name in country.callsign[category]:
self._names[name] = deque()
self._max_group_id = max_group_id
self.reset()
def reset(self) -> None:
for name in self._names:
self._names[name] = deque()
for i in range(
self._max_group_id, 0, -1
): # Put group IDs on FIFO queue so 1 gets popped first
self._names[name].appendleft(i)
def alloc_group_id(self, name: str) -> int:
return self._names[name].popleft()
def release_group_id(self, callsign: Callsign) -> None:
if callsign.name is None:
raise ValueError("Releasing eastern callsign")
self._names[callsign.name].appendleft(callsign.group_id)
class EasternGroupIdRegistry:
def __init__(self, max_group_id: int = MAX_GROUP_ID):
self._max_group_id = max_group_id
self._queue: deque[int] = deque()
self.reset()
def reset(self) -> None:
self._queue = deque()
for i in range(
self._max_group_id, 0, -1
): # Put group IDs on FIFO queue so 1 gets popped first
self._queue.appendleft(i)
def alloc_group_id(self) -> int:
return self._queue.popleft()
def release_group_id(self, callsign: Callsign) -> None:
self._queue.appendleft(callsign.group_id)
class RoundRobinNameAllocator:
def __init__(self, names: List[str]):
self.names = names
self._index = 0
def allocate(self) -> str:
this_index = self._index
if this_index == len(self.names) - 1:
self._index = 0
else:
self._index += 1
return self.names[this_index]
class FlightTypeNameAllocator:
def __init__(self, names: List[str]):
self.names = names
def allocate(self, flight: Flight) -> str:
index = self.FLIGHT_TYPE_LOOKUP.get(flight.flight_type, 0)
return self.names[index]
FLIGHT_TYPE_LOOKUP: dict[FlightType, int] = {
FlightType.TARCAP: 1,
FlightType.BARCAP: 1,
FlightType.INTERCEPTION: 1,
FlightType.SWEEP: 1,
FlightType.CAS: 2,
FlightType.ANTISHIP: 2,
FlightType.BAI: 2,
FlightType.STRIKE: 3,
FlightType.OCA_RUNWAY: 3,
FlightType.OCA_AIRCRAFT: 3,
FlightType.SEAD: 4,
FlightType.DEAD: 4,
FlightType.ESCORT: 5,
FlightType.AIR_ASSAULT: 6,
FlightType.TRANSPORT: 7,
FlightType.FERRY: 7,
}
class WesternFlightCallsignGenerator:
"""Generate western callsign for lead unit in a group"""
def __init__(self, country: str) -> None:
self._country = countries_by_name[country]()
self._group_id_registry = WesternGroupIdRegistry(self._country)
self._awacs_name_allocator = None
self._tankers_name_allocator = None
if CallsignCategory.AWACS in self._country.callsign:
self._awacs_name_allocator = RoundRobinNameAllocator(
self._country.callsign[CallsignCategory.AWACS]
)
if CallsignCategory.TANKERS in self._country.callsign:
self._tankers_name_allocator = RoundRobinNameAllocator(
self._country.callsign[CallsignCategory.TANKERS]
)
self._air_name_allocator = FlightTypeNameAllocator(
self._country.callsign[CallsignCategory.AIR]
)
def reset(self) -> None:
self._group_id_registry.reset()
def alloc_callsign(self, flight: Flight) -> Callsign:
if flight.flight_type == FlightType.AEWC:
if self._awacs_name_allocator is None:
raise ValueError(f"{self._country.name} does not have AWACs callsigns")
name = self._awacs_name_allocator.allocate()
elif flight.flight_type == FlightType.REFUELING:
if self._tankers_name_allocator is None:
raise ValueError(f"{self._country.name} does not have tanker callsigns")
name = self._tankers_name_allocator.allocate()
else:
name = self._air_name_allocator.allocate(flight)
group_id = self._group_id_registry.alloc_group_id(name)
return Callsign(name, group_id, 1)
def release_callsign(self, callsign: Callsign) -> None:
self._group_id_registry.release_group_id(callsign)
class EasternFlightCallsignGenerator:
"""Generate eastern callsign for lead unit in a group"""
def __init__(self) -> None:
self._group_id_registry = EasternGroupIdRegistry()
def reset(self) -> None:
self._group_id_registry.reset()
def alloc_callsign(self, flight: Flight) -> Callsign:
group_id = self._group_id_registry.alloc_group_id()
return Callsign(None, group_id, 1)
def release_callsign(self, callsign: Callsign) -> None:
self._group_id_registry.release_group_id(callsign)
class FlightCallsignGenerator:
def __init__(self, country: str):
self._use_western_callsigns = countries_by_name[country]().use_western_callsigns
self._generators: dict[
bool, WesternFlightCallsignGenerator | EasternFlightCallsignGenerator
] = {}
if self._use_western_callsigns:
self._generators[self._use_western_callsigns] = (
WesternFlightCallsignGenerator(country)
)
else:
self._generators[self._use_western_callsigns] = (
EasternFlightCallsignGenerator()
)
def reset(self) -> None:
self._generators[self._use_western_callsigns].reset()
def alloc_callsign(self, flight: Flight) -> Callsign:
return self._generators[self._use_western_callsigns].alloc_callsign(flight)
def release_callsign(self, callsign: Callsign) -> None:
self._generators[self._use_western_callsigns].release_callsign(callsign)

View File

@@ -14,10 +14,12 @@ class FactionRecommendation(ABC):
self.name = name
@abstractmethod
def register_campaign_specific_faction(self, factions: Factions) -> None: ...
def register_campaign_specific_faction(self, factions: Factions) -> None:
...
@abstractmethod
def get_faction(self, factions: Factions) -> Faction: ...
def get_faction(self, factions: Factions) -> Faction:
...
@staticmethod
def from_field(

View File

@@ -61,8 +61,6 @@ class MizCampaignLoader:
AirDefence.Hawk_ln.id,
AirDefence.S_75M_Volhov.id,
AirDefence.X_5p73_s_125_ln.id,
AirDefence.NASAMS_LN_B.id,
AirDefence.NASAMS_LN_C.id,
}
SHORT_RANGE_SAM_UNIT_TYPES = {

View File

@@ -7,7 +7,6 @@ from faker import Faker
from game.armedforces.armedforces import ArmedForces
from game.ato.airtaaskingorder import AirTaskingOrder
from game.callsigns.callsigngenerator import FlightCallsignGenerator
from game.campaignloader.defaultsquadronassigner import DefaultSquadronAssigner
from game.commander import TheaterCommander
from game.commander.missionscheduler import MissionScheduler
@@ -47,7 +46,6 @@ class Coalition:
self.air_wing = AirWing(player, game, self.faction)
self.armed_forces = ArmedForces(self.faction)
self.transfers = PendingTransfers(game, player)
self.callsign_generator = FlightCallsignGenerator(faction.country)
# Late initialized because the two coalitions in the game are mutually
# dependent, so must be both constructed before this property can be set.
@@ -165,8 +163,6 @@ class Coalition:
# is handled correctly.
self.transfers.perform_transfers()
self.callsign_generator.reset()
def preinit_turn_0(self) -> None:
"""Runs final Coalition initialization.

View File

@@ -47,17 +47,6 @@ class MissionScheduler:
margin=5 * 60,
)
for package in self.coalition.ato.packages:
if package.time_over_target > datetime.min:
if package.primary_task in dca_types:
if (
package.mission_departure_time is not None
and package.mission_departure_time
> previous_cap_end_time[package.target]
):
previous_cap_end_time[package.target] = (
package.mission_departure_time
)
continue # If package already has TOT, leave it.
tot = TotEstimator(package).earliest_tot(now)
if package.primary_task in dca_types:
previous_end_time = previous_cap_end_time[package.target]

View File

@@ -2,7 +2,6 @@ from __future__ import annotations
from typing import Optional, TYPE_CHECKING
from game.callsigns.callsigngenerator import FlightCallsignGenerator
from game.theater import ControlPoint, MissionTarget, OffMapSpawn
from game.utils import nautical_miles
from ..ato.flight import Flight
@@ -27,7 +26,6 @@ class PackageBuilder:
closest_airfields: ClosestAirfields,
air_wing: AirWing,
laser_code_registry: LaserCodeRegistry,
callsign_generator: FlightCallsignGenerator,
flight_db: Database[Flight],
is_player: bool,
package_country: str,
@@ -40,7 +38,6 @@ class PackageBuilder:
self.package = Package(location, flight_db, auto_asap=asap)
self.air_wing = air_wing
self.laser_code_registry = laser_code_registry
self.callsign_generator = callsign_generator
self.start_type = start_type
def plan_flight(self, plan: ProposedFlight) -> bool:
@@ -74,7 +71,6 @@ class PackageBuilder:
member.assign_tgp_laser_code(
self.laser_code_registry.alloc_laser_code()
)
flight.callsign = self.callsign_generator.alloc_callsign(flight)
self.package.add_flight(flight)
return True
@@ -104,6 +100,4 @@ class PackageBuilder:
"""Returns any planned flights to the inventory."""
flights = list(self.package.flights)
for flight in flights:
if flight.callsign is not None:
self.callsign_generator.release_callsign(flight.callsign)
self.package.remove_flight(flight)

View File

@@ -142,7 +142,6 @@ class PackageFulfiller:
ObjectiveDistanceCache.get_closest_airfields(mission.location),
self.air_wing,
self.coalition.laser_code_registry,
self.coalition.callsign_generator,
self.flight_db,
self.is_player,
self.coalition.country_name,

View File

@@ -21,7 +21,8 @@ class FrontLineStanceTask(TheaterCommanderTask, ABC):
@property
@abstractmethod
def stance(self) -> CombatStance: ...
def stance(self) -> CombatStance:
...
@staticmethod
def management_allowed(state: TheaterState) -> bool:
@@ -48,7 +49,8 @@ class FrontLineStanceTask(TheaterCommanderTask, ABC):
@property
@abstractmethod
def have_sufficient_front_line_advantage(self) -> bool: ...
def have_sufficient_front_line_advantage(self) -> bool:
...
@property
def ground_force_balance(self) -> float:

View File

@@ -54,7 +54,8 @@ class PackagePlanningTask(TheaterCommanderTask, Generic[MissionTargetT]):
coalition.ato.add_package(self.package)
@abstractmethod
def propose_flights(self) -> None: ...
def propose_flights(self) -> None:
...
def propose_flight(
self,
@@ -117,9 +118,9 @@ class PackagePlanningTask(TheaterCommanderTask, Generic[MissionTargetT]):
target_ranges: list[
tuple[Union[IadsGroundObject, NavalGroundObject], Distance]
] = []
all_iads: Iterator[Union[IadsGroundObject, NavalGroundObject]] = (
itertools.chain(state.enemy_air_defenses, state.enemy_ships)
)
all_iads: Iterator[
Union[IadsGroundObject, NavalGroundObject]
] = itertools.chain(state.enemy_air_defenses, state.enemy_ships)
for target in all_iads:
distance = meters(target.distance_to(self.target))
if range_type is RangeType.Detection:

View File

@@ -12,4 +12,5 @@ if TYPE_CHECKING:
class TheaterCommanderTask(PrimitiveTask[TheaterState]):
@abstractmethod
def execute(self, coalition: Coalition) -> None: ...
def execute(self, coalition: Coalition) -> None:
...

View File

@@ -52,7 +52,6 @@ even though it is a primitive task used by many other tasks.
https://en.wikipedia.org/wiki/Hierarchical_task_network
"""
from __future__ import annotations
from datetime import datetime

View File

@@ -24,7 +24,6 @@ from game.theater.theatergroundobject import (
VehicleGroupGroundObject,
)
from game.threatzones import ThreatZones
from game.ato.flighttype import FlightType
if TYPE_CHECKING:
from game import Game
@@ -78,8 +77,7 @@ class TheaterState(WorldState["TheaterState"]):
self.threatening_air_defenses.remove(target)
if target in self.detecting_air_defenses:
self.detecting_air_defenses.remove(target)
if target in self.enemy_air_defenses:
self.enemy_air_defenses.remove(target)
self.enemy_air_defenses.remove(target)
self._rebuild_threat_zones()
def eliminate_ship(self, target: NavalGroundObject) -> None:
@@ -87,8 +85,7 @@ class TheaterState(WorldState["TheaterState"]):
self.threatening_air_defenses.remove(target)
if target in self.detecting_air_defenses:
self.detecting_air_defenses.remove(target)
if target in self.enemy_ships:
self.enemy_ships.remove(target)
self.enemy_ships.remove(target)
self._rebuild_threat_zones()
def has_battle_position(self, target: VehicleGroupGroundObject) -> bool:
@@ -158,16 +155,21 @@ class TheaterState(WorldState["TheaterState"]):
tracer,
)
# Plan enough rounds of CAP that the target has coverage over the expected
# mission duration.
mission_duration = game.settings.desired_player_mission_duration.total_seconds()
barcap_duration = coalition.doctrine.cap.duration.total_seconds()
barcap_rounds = math.ceil(mission_duration / barcap_duration)
refueling_targets: list[MissionTarget] = []
theater_refuling_point = finder.preferred_theater_refueling_control_point()
if theater_refuling_point is not None:
refueling_targets.append(theater_refuling_point)
theater_state = TheaterState(
return TheaterState(
context=context,
barcaps_needed={
cp: cls._barcap_rounds(game, player, now, cp)
for cp in finder.vulnerable_control_points()
cp: barcap_rounds for cp in finder.vulnerable_control_points()
},
active_front_lines=list(finder.front_lines()),
front_line_stances={f: None for f in finder.front_lines()},
@@ -189,62 +191,3 @@ class TheaterState(WorldState["TheaterState"]):
enemy_barcaps=list(game.theater.control_points_for(not player)),
threat_zones=game.threat_zone_for(not player),
)
# Look through packages already planned in the ATO and eliminate from the
# list of targets.
for package in coalition.ato.packages:
if isinstance(package.target, NavalGroundObject):
theater_state.eliminate_ship(package.target)
if package.primary_task == FlightType.BAI and isinstance(
package.target, VehicleGroupGroundObject
):
theater_state.eliminate_battle_position(package.target)
if isinstance(package.target, IadsGroundObject):
theater_state.eliminate_air_defense(package.target)
if (
package.primary_task == FlightType.STRIKE
and isinstance(package.target, TheaterGroundObject)
and package.target in theater_state.strike_targets
):
theater_state.strike_targets.remove(package.target)
if package.primary_task == FlightType.AEWC:
# If a planned AEWC mission covers the target beyond the planned mission duration, it can safely be removed
if (
package.time_over_target + coalition.doctrine.aewc.duration
> now + game.settings.desired_player_mission_duration
) and package.target in theater_state.aewc_targets:
theater_state.aewc_targets.remove(package.target)
if (
package.primary_task
in (
FlightType.OCA_AIRCRAFT,
FlightType.OCA_RUNWAY,
)
and isinstance(package.target, ControlPoint)
and package.target in theater_state.oca_targets
):
theater_state.oca_targets.remove(package.target)
return theater_state
@classmethod
def _barcap_rounds(
cls, game: Game, player: bool, now: datetime, control_point: ControlPoint
) -> int:
"""Calculate number of additional rounds of CAP required to cover mission duration."""
coalition = game.coalition_for(player)
# Look through ATO for any existing planned CAP missions and calculate last planned CAP end
planned_cap_coverage_end_time = now
for package in coalition.ato.packages:
if package.target == control_point:
cap_end_time = (
package.time_over_target + coalition.doctrine.cap.duration
)
if cap_end_time > planned_cap_coverage_end_time:
planned_cap_coverage_end_time = cap_end_time
# When mission is expected to finish
mission_end_time = now + game.settings.desired_player_mission_duration
return math.ceil(
(mission_end_time - planned_cap_coverage_end_time).total_seconds()
/ coalition.doctrine.cap.duration.total_seconds()
)

View File

@@ -2,11 +2,11 @@ from __future__ import annotations
from pathlib import Path
import yaml
from typing import Any, ClassVar, Optional
from typing import Any, ClassVar
from dataclasses import dataclass
from datetime import timedelta
from dcs.task import OptAAMissileAttackRange
from game.data.units import UnitClass
from game.utils import Distance, feet, nautical_miles
@@ -52,16 +52,6 @@ class Helicopter:
)
@dataclass
class Aewc:
#: The duration that AEWC flights will remain on-station
duration: timedelta
@staticmethod
def from_dict(data: dict[str, Any]) -> Aewc:
return Aewc(duration=timedelta(minutes=data["duration_minutes"]))
@dataclass
class Cas:
#: The duration that CAP flights will remain on-station.
@@ -125,25 +115,6 @@ class Cap:
)
@dataclass(frozen=True)
class Tactics:
#: Air-to-air missile attack range options
air_to_air_missile_attack_range: Optional[OptAAMissileAttackRange.Values]
#: Air defence units evade ARMs
air_defence_evades_anti_radiation_missiles: bool
@staticmethod
def from_dict(data: dict[str, Any]) -> Tactics:
return Tactics(
air_to_air_missile_attack_range=None,
air_defence_evades_anti_radiation_missiles=data.get(
"air_defence_evades_anti_radiation_missiles", False
),
)
@dataclass(frozen=True)
class Doctrine:
#: Name of the doctrine, used to assign a doctrine in a faction.
@@ -179,9 +150,6 @@ class Doctrine:
#: Helicopter specific doctrines.
helicopter: Helicopter
#: Doctrine for AEWC missions.
aewc: Aewc
#: Doctrine for CAS missions.
cas: Cas
@@ -191,9 +159,6 @@ class Doctrine:
#: Doctrine for Fighter Sweep missions.
sweep: Sweep
#: Tactics options
tactics: Tactics
_by_name: ClassVar[dict[str, Doctrine]] = {}
_loaded: ClassVar[bool] = False
@@ -251,11 +216,9 @@ class Doctrine:
data["ground_unit_procurement_ratios"]
),
helicopter=Helicopter.from_dict(data["helicopter"]),
aewc=Aewc.from_dict(data["aewc"]),
cas=Cas.from_dict(data["cas"]),
cap=Cap.from_dict(data["cap"]),
sweep=Sweep.from_dict(data["sweep"]),
tactics=Tactics.from_dict(data.get("tactics", {})),
)
)
cls._loaded = True

View File

@@ -14,8 +14,6 @@ from dcs.flyingunit import FlyingUnit
from dcs.weapons_data import weapon_ids
from game.dcs.aircrafttype import AircraftType
from game.factions.faction import Faction
PydcsWeapon = Any
PydcsWeaponAssignment = tuple[int, PydcsWeapon]
@@ -79,12 +77,8 @@ class Weapon:
WeaponGroup.load_all()
cls._loaded = True
def available_on(self, date: datetime.date, faction: Faction) -> bool:
def available_on(self, date: datetime.date) -> bool:
introduction_year = self.weapon_group.introduction_year
if self.weapon_group.name in faction.weapons_introduction_year_overrides:
introduction_year = faction.weapons_introduction_year_overrides[
self.weapon_group.name
]
if introduction_year is None:
return True
return date >= datetime.date(introduction_year, 1, 1)
@@ -249,9 +243,9 @@ class Pylon:
def make_pydcs_assignment(self, weapon: Weapon) -> PydcsWeaponAssignment:
return self.number, weapon.pydcs_data
def available_on(self, date: datetime.date, faction: Faction) -> Iterator[Weapon]:
def available_on(self, date: datetime.date) -> Iterator[Weapon]:
for weapon in self.allowed:
if weapon.available_on(date, faction):
if weapon.available_on(date):
yield weapon
@classmethod

View File

@@ -34,11 +34,6 @@ from game.radio.channels import (
ViggenRadioChannelAllocator,
ViperChannelNamer,
WarthogChannelNamer,
PhantomChannelNamer,
HindChannelNamer,
HipChannelNamer,
KiowaChannelNamer,
FulcrumChannelNamer,
)
from game.utils import (
Distance,
@@ -115,11 +110,6 @@ class RadioConfig:
"apache": ApacheChannelNamer,
"a10c-legacy": LegacyWarthogChannelNamer,
"a10c-ii": WarthogChannelNamer,
"phantom": PhantomChannelNamer,
"hind": HindChannelNamer,
"hip": HipChannelNamer,
"kiowa": KiowaChannelNamer,
"fulcrum": FulcrumChannelNamer,
}[config.get("namer", "default")]
@@ -508,11 +498,9 @@ class AircraftType(UnitType[Type[FlyingType]]):
patrol_altitude=patrol_config.altitude,
patrol_speed=patrol_config.speed,
max_mission_range=mission_range,
cruise_speed=(
knots(data["cruise_speed_kt_indicated"])
if "cruise_speed_kt_indicated" in data
else None
),
cruise_speed=knots(data["cruise_speed_kt_indicated"])
if "cruise_speed_kt_indicated" in data
else None,
fuel_consumption=fuel_consumption,
default_livery=data.get("default_livery"),
intra_flight_radio=radio_config.intra_flight,

View File

@@ -60,9 +60,9 @@ class GroundUnitType(UnitType[Type[VehicleType]]):
reversed_heading: bool = False
_by_name: ClassVar[dict[str, GroundUnitType]] = {}
_by_unit_type: ClassVar[dict[type[VehicleType], list[GroundUnitType]]] = (
defaultdict(list)
)
_by_unit_type: ClassVar[
dict[type[VehicleType], list[GroundUnitType]]
] = defaultdict(list)
def __setstate__(self, state: dict[str, Any]) -> None:
# Update any existing models with new data on load.

View File

@@ -17,10 +17,12 @@ class LaserCodeConfig(ABC):
)
@abstractmethod
def iter_prop_ids(self) -> Iterator[str]: ...
def iter_prop_ids(self) -> Iterator[str]:
...
@abstractmethod
def property_dict_for_code(self, code: int) -> dict[str, int]: ...
def property_dict_for_code(self, code: int) -> dict[str, int]:
...
class SinglePropertyLaserCodeConfig(LaserCodeConfig):

View File

@@ -1,5 +1,5 @@
from __future__ import annotations
from abc import ABC
import itertools
import logging
from collections import defaultdict
@@ -9,9 +9,7 @@ from typing import (
Dict,
Iterator,
List,
Optional,
TYPE_CHECKING,
TypeVar,
Union,
)
from uuid import UUID
@@ -23,10 +21,8 @@ from game.theater import Airfield, ControlPoint
if TYPE_CHECKING:
from game import Game
from game.ato.flight import Flight
from game.dcs.unittype import UnitType
from game.sim.simulationresults import SimulationResults
from game.transfers import CargoShip
from game.theater import TheaterUnit
from game.unitmap import (
AirliftUnits,
ConvoyUnit,
@@ -94,111 +90,11 @@ class BaseCaptureEvent:
captured_by_player: bool
@dataclass
class UnitHitpointUpdate(ABC):
unit: Any
hit_points: int
@classmethod
def from_json(
cls, data: dict[str, Any], unit_map: UnitMap
) -> Optional[UnitHitpointUpdate]:
raise NotImplementedError()
def is_dead(self) -> bool:
# Use hit_points > 1 to indicate unit is alive, rather than >=1 (DCS logic) to account for uncontrolled units which often have a
# health floor of 1
if self.hit_points > 1:
return False
return True
def is_friendly(self, to_player: bool) -> bool:
raise NotImplementedError()
@dataclass
class FlyingUnitHitPointUpdate(UnitHitpointUpdate):
unit: FlyingUnit
@classmethod
def from_json(
cls, data: dict[str, Any], unit_map: UnitMap
) -> Optional[FlyingUnitHitPointUpdate]:
unit = unit_map.flight(data["name"])
if unit is None:
return None
return cls(unit, int(float(data["hit_points"])))
def is_friendly(self, to_player: bool) -> bool:
if to_player:
return self.unit.flight.departure.captured
return not self.unit.flight.departure.captured
@dataclass
class TheaterUnitHitPointUpdate(UnitHitpointUpdate):
unit: TheaterUnitMapping
@classmethod
def from_json(
cls, data: dict[str, Any], unit_map: UnitMap
) -> Optional[TheaterUnitHitPointUpdate]:
unit = unit_map.theater_units(data["name"])
if unit is None:
return None
if unit.theater_unit.unit_type is None:
logging.debug(
f"Ground unit {data['name']} does not have a valid unit type."
)
return None
if unit.theater_unit.hit_points is None:
logging.debug(f"Ground unit {data['name']} does not have hit_points set.")
return None
sim_hit_points = int(
float(data["hit_points"])
) # Hit points out of the sim i.e. new unit hit points - damage in this turn
previous_turn_hit_points = (
unit.theater_unit.hit_points
) # Hit points at the end of the previous turn
full_health_hit_points = (
unit.theater_unit.unit_type.hit_points
) # Hit points of a new unit
# Hit points left after damage this turn is subtracted from hit points at the end of the previous turn
new_hit_points = previous_turn_hit_points - (
full_health_hit_points - sim_hit_points
)
return cls(unit, new_hit_points)
def is_dead(self) -> bool:
# Some TheaterUnits can start with low health of around 1, make sure we don't always kill them off.
if (
self.unit.theater_unit.unit_type is not None
and self.unit.theater_unit.unit_type.hit_points is not None
and self.unit.theater_unit.unit_type.hit_points <= 1
):
return False
return super().is_dead()
def is_friendly(self, to_player: bool) -> bool:
return self.unit.theater_unit.ground_object.is_friendly(to_player)
def commit(self) -> None:
self.unit.theater_unit.hit_points = self.hit_points
@dataclass(frozen=True)
class StateData:
#: True if the mission ended. If False, the mission exited abnormally.
mission_ended: bool
#: Simulation time since mission start in seconds
simulation_time_seconds: float
#: Names of aircraft units that were killed during the mission.
killed_aircraft: List[str]
@@ -212,10 +108,6 @@ class StateData:
#: Mangled names of bases that were captured during the mission.
base_capture_events: List[str]
# List of descriptions of damage done to units. Each list element is a dict like the following
# {"name": "<damaged unit name>", "hit_points": <hit points as float>}
unit_hit_point_updates: List[dict[str, Any]]
@classmethod
def from_json(cls, data: Dict[str, Any], unit_map: UnitMap) -> StateData:
def clean_unit_list(unit_list: List[Any]) -> List[str]:
@@ -251,12 +143,10 @@ class StateData:
return cls(
mission_ended=data["mission_ended"],
simulation_time_seconds=data["simulation_time_seconds"],
killed_aircraft=killed_aircraft,
killed_ground_units=killed_ground_units,
destroyed_statics=data["destroyed_objects_positions"],
base_capture_events=data["base_capture_events"],
unit_hit_point_updates=data["unit_hit_point_updates"],
)
@@ -394,25 +284,6 @@ class Debriefing:
player_losses.append(aircraft)
else:
enemy_losses.append(aircraft)
# Keep track of damaged units that are counted as killed so we don't double count
# when DCS reports damage multiple times.
units_killed_by_damage = set()
for unit_data in self.state_data.unit_hit_point_updates:
damaged_unit = FlyingUnitHitPointUpdate.from_json(unit_data, self.unit_map)
if damaged_unit is None:
continue
if damaged_unit.is_dead():
# If unit already killed, nothing to do.
if unit_data["name"] in self.state_data.killed_aircraft:
continue
if unit_data["name"] in units_killed_by_damage:
continue
units_killed_by_damage.add(unit_data["name"])
if damaged_unit.is_friendly(to_player=True):
player_losses.append(damaged_unit.unit)
else:
enemy_losses.append(damaged_unit.unit)
return AirLosses(player_losses, enemy_losses)
def dead_ground_units(self) -> GroundLosses:
@@ -485,29 +356,8 @@ class Debriefing:
losses.enemy_airlifts.append(airlift_unit)
continue
for unit_data in self.state_data.unit_hit_point_updates:
damaged_unit = TheaterUnitHitPointUpdate.from_json(unit_data, self.unit_map)
if damaged_unit is None:
continue
if damaged_unit.is_dead():
if unit_data["name"] in self.state_data.killed_ground_units:
continue
if damaged_unit.is_friendly(to_player=True):
losses.player_ground_objects.append(damaged_unit.unit)
else:
losses.enemy_ground_objects.append(damaged_unit.unit)
return losses
def unit_hit_point_update_events(self) -> List[TheaterUnitHitPointUpdate]:
damaged_units = []
for unit_data in self.state_data.unit_hit_point_updates:
unit = TheaterUnitHitPointUpdate.from_json(unit_data, self.unit_map)
if unit is None:
continue
damaged_units.append(unit)
return damaged_units
def base_capture_events(self) -> List[BaseCaptureEvent]:
"""Keeps only the last instance of a base capture event for each base ID."""
blue_coalition_id = 2

View File

@@ -3,7 +3,6 @@ from __future__ import annotations
import itertools
import logging
from dataclasses import dataclass, field
import datetime
from functools import cached_property
from typing import Any, Dict, Iterator, List, Optional, TYPE_CHECKING, Type
@@ -119,13 +118,6 @@ class Faction:
#: both will use it.
unrestricted_satnav: bool = False
#: Overrides default weapons introduction years for faction. Maps names of
#: weapons groups to their introduction years.
weapons_introduction_year_overrides: Dict[str, int] = field(default_factory=dict)
#: Set to True if the faction has access to countermeasures (chaff and flares).
countermeasures_available: bool = True
def has_access_to_dcs_type(self, unit_type: Type[DcsUnitType]) -> bool:
# Vehicle and Ship Units
if any(unit_type == u.dcs_unit_type for u in self.accessible_units):
@@ -270,12 +262,6 @@ class Faction:
faction.unrestricted_satnav = json.get("unrestricted_satnav", False)
faction.weapons_introduction_year_overrides = json.get(
"weapons_introduction_year_overrides", {}
)
faction.countermeasures_available = json.get("countermeasures_available", True)
return faction
@property
@@ -314,11 +300,8 @@ class Faction:
self.remove_aircraft("Su-57")
if not mod_settings.ov10a_bronco:
self.remove_aircraft("Bronco-OV-10A")
if not mod_settings.fa18efg:
self.remove_aircraft("FA_18E")
self.remove_aircraft("FA_18F")
self.remove_aircraft("EA_18G")
if not mod_settings.superhornet:
self.remove_aircraft("Super-Hornet")
# frenchpack
if not mod_settings.frenchpack:
self.remove_vehicle("AMX10RCR")

View File

@@ -15,12 +15,15 @@ if TYPE_CHECKING:
class WaypointAction(ABC):
@abstractmethod
def describe(self) -> str: ...
def describe(self) -> str:
...
@abstractmethod
def update_state(
self, state: ActionState, time: datetime, duration: timedelta
) -> timedelta: ...
) -> timedelta:
...
@abstractmethod
def iter_tasks(self, ctx: TaskContext) -> Iterator[Task]: ...
def iter_tasks(self, ctx: TaskContext) -> Iterator[Task]:
...

View File

@@ -28,12 +28,14 @@ def point_at_heading(p: Point, heading: Heading, distance: Distance) -> Point:
class Prerequisite(ABC):
@abstractmethod
def is_satisfied(self) -> bool: ...
def is_satisfied(self) -> bool:
...
@abstractmethod
def describe_debug_info(
self, to_geojson: Callable[[BaseGeometry], dict[str, Any]]
) -> dict[str, Any]: ...
) -> dict[str, Any]:
...
class DistancePrerequisite(Prerequisite):

View File

@@ -125,11 +125,7 @@ class Game:
self.time_of_day_offset_for_start_time = list(TimeOfDay).index(
self.theater.daytime_map.best_guess_time_of_day_at(start_time)
)
# self.conditions.start_time is the time at the start of a turn and does not change within a turn.
# self.simulation_time tracks time progression within a turn and is synchronized with the
# MissionSimulation object.
self.conditions = self.generate_conditions(forced_time=start_time)
self.simulation_time = self.conditions.start_time
self.sanitize_sides(player_faction, enemy_faction)
self.blue = Coalition(self, player_faction, player_budget, player=True)
@@ -295,7 +291,6 @@ class Game:
# turn 1.
if self.turn > 1:
self.conditions = self.generate_conditions()
self.simulation_time = self.conditions.start_time
def begin_turn_0(self) -> None:
"""Initialization for the first turn of the game."""

View File

@@ -11,7 +11,8 @@ WorldStateT = TypeVar("WorldStateT", bound="WorldState[Any]")
class WorldState(ABC, Generic[WorldStateT]):
@abstractmethod
def clone(self) -> WorldStateT: ...
def clone(self) -> WorldStateT:
...
class Task(Generic[WorldStateT]):
@@ -23,17 +24,18 @@ Method = Sequence[Task[WorldStateT]]
class PrimitiveTask(Task[WorldStateT], Generic[WorldStateT], ABC):
@abstractmethod
def preconditions_met(self, state: WorldStateT) -> bool: ...
def preconditions_met(self, state: WorldStateT) -> bool:
...
@abstractmethod
def apply_effects(self, state: WorldStateT) -> None: ...
def apply_effects(self, state: WorldStateT) -> None:
...
class CompoundTask(Task[WorldStateT], Generic[WorldStateT], ABC):
@abstractmethod
def each_valid_method(
self, state: WorldStateT
) -> Iterator[Method[WorldStateT]]: ...
def each_valid_method(self, state: WorldStateT) -> Iterator[Method[WorldStateT]]:
...
PrimitiveTaskT = TypeVar("PrimitiveTaskT", bound=PrimitiveTask[Any])

View File

@@ -10,11 +10,9 @@ class Information:
def __str__(self) -> str:
return "[{}][{}] {} {}".format(
(
self.timestamp.strftime("%Y-%m-%d %H:%M:%S")
if self.timestamp is not None
else ""
),
self.timestamp.strftime("%Y-%m-%d %H:%M:%S")
if self.timestamp is not None
else "",
self.turn,
self.title,
self.text,

View File

@@ -9,7 +9,9 @@ if TYPE_CHECKING:
class ILaserCodeRegistry(ABC):
@abstractmethod
def alloc_laser_code(self) -> LaserCode: ...
def alloc_laser_code(self) -> LaserCode:
...
@abstractmethod
def release_code(self, code: LaserCode) -> None: ...
def release_code(self, code: LaserCode) -> None:
...

View File

@@ -1,5 +1,4 @@
"""Logging APIs."""
import logging
import logging.config
import os

View File

@@ -148,7 +148,7 @@ class AircraftGenerator:
faction.country,
squadron,
1,
FlightType.IDLE,
FlightType.BARCAP,
StartType.COLD,
divert=None,
)

View File

@@ -6,7 +6,7 @@ from typing import Optional, TYPE_CHECKING
from dcs.flyingunit import FlyingUnit
from game.callsigns.callsign import create_group_callsign_from_unit
from game.callsigns import create_group_callsign_from_unit
if TYPE_CHECKING:
from game.ato import FlightType, FlightWaypoint, Package

View File

@@ -10,8 +10,7 @@ from dcs.unit import Skill
from dcs.unitgroup import FlyingGroup
from game.ato import Flight, FlightType
from game.callsigns.callsign import callsign_for_support_unit
from game.callsigns.callsigngenerator import Callsign, FlightCallsignGenerator
from game.callsigns import callsign_for_support_unit
from game.data.weapons import Pylon
from game.missiongenerator.logisticsgenerator import LogisticsGenerator
from game.missiongenerator.missiondata import AwacsInfo, MissionData, TankerInfo
@@ -116,8 +115,6 @@ class FlightGroupConfigurator:
self.flight.flight_plan.waypoints,
)
self.set_callsigns()
return FlightData(
package=self.flight.package,
aircraft_type=self.flight.unit_type,
@@ -245,11 +242,7 @@ class FlightGroupConfigurator:
loadout = member.loadout
if self.game.settings.restrict_weapons_by_date:
loadout = loadout.degrade_for_date(
self.flight.unit_type,
self.game.date,
self.flight.squadron.coalition.faction,
)
loadout = loadout.degrade_for_date(self.flight.unit_type, self.game.date)
for pylon_number, weapon in loadout.pylons.items():
if weapon is None:
@@ -276,17 +269,3 @@ class FlightGroupConfigurator:
# our own tracking, so undo that.
# https://github.com/pydcs/dcs/commit/303a81a8e0c778599fe136dd22cb2ae8123639a6
unit.fuel = self.flight.unit_type.dcs_unit_type.fuel_max
def set_callsigns(self) -> None:
if self.flight.callsign is None:
return
for unit_index, unit in enumerate(self.group.units):
unit_callsign = self.flight.callsign.unit_callsign(unit_index + 1)
if (
unit_callsign.name is None
): # pydcs needs unit.callsign to be set for eastern callsigns
unit.callsign = str(unit_callsign)
else: # Use western callsign
unit.callsign_dict = unit_callsign.pydcs_dict(
country=self.flight.country
)

View File

@@ -243,7 +243,11 @@ class FlightGroupSpawner:
for i in range(self.flight.count):
group.units[i].position = hpad.position
group.units[i].heading = hpad.heading
group.units[i].parking_id = str(i + 1)
# pydcs has just `parking_id = None`, so mypy thinks str is invalid. Ought
# to fix pydcs, but that's not the kind of change we want to pull into the
# 6.1 branch, and frankly we should probably just improve pydcs's handling
# of FARPs instead.
group.units[i].parking_id = str(i + 1) # type: ignore
return group
def dcs_start_type(self) -> DcsStartType:

View File

@@ -20,14 +20,8 @@ class AntiShipIngressBuilder(PydcsWaypointBuilder):
group_names.append(target.name)
elif isinstance(target, NavalControlPoint):
carrier_name = target.get_carrier_group_name()
if carrier_name and self.mission.find_group(
carrier_name
): # Found a carrier, target it.
if carrier_name:
group_names.append(carrier_name)
else: # Could not find carrier/LHA, indicating it was sunk. Target other groups if present e.g. escorts.
for ground_object in target.ground_objects:
for group in ground_object.groups:
group_names.append(group.group_name)
else:
logging.error(
"Unexpected target type for anti-ship mission: %s",

View File

@@ -4,7 +4,7 @@ from datetime import datetime
from typing import Any, Iterable, Union
from dcs import Mission
from dcs.planes import AJS37, F_14A_135_GR, F_14A_135_GR_Early, F_14B, JF_17
from dcs.planes import AJS37, F_14B, JF_17
from dcs.point import MovingPoint, PointAction
from dcs.unitgroup import FlyingGroup
@@ -127,9 +127,5 @@ class PydcsWaypointBuilder:
for i, t in enumerate(targets):
if self.group.units[0].unit_type == JF_17 and i < 4:
self.group.add_nav_target_point(t.position, "PP" + str(i + 1))
if (
self.group.units[0].unit_type
in [F_14A_135_GR, F_14A_135_GR_Early, F_14B]
and i == 0
):
if self.group.units[0].unit_type == F_14B and i == 0:
self.group.add_nav_target_point(t.position, "ST")

View File

@@ -0,0 +1,210 @@
from __future__ import annotations
import logging
from typing import List, TYPE_CHECKING, Tuple, Type
from dcs.mission import Mission, StartType
from dcs.planes import IL_78M, KC130, KC135MPRS, KC_135, PlaneType
from dcs.task import (
AWACS,
ActivateBeaconCommand,
MainTask,
Refueling,
SetImmortalCommand,
SetInvisibleCommand,
)
from dcs.unittype import UnitType
from game.ato import FlightType
from game.callsigns import callsign_for_support_unit
from game.naming import namegen
from game.radio.radios import RadioRegistry
from game.radio.tacan import TacanBand, TacanRegistry, TacanUsage
from game.utils import Heading
from .airconflictdescription import AirConflictDescription
from .missiondata import AwacsInfo, MissionData, TankerInfo
if TYPE_CHECKING:
from game import Game
TANKER_DISTANCE = 15000
TANKER_ALT = 4572
TANKER_HEADING_OFFSET = 45
AWACS_DISTANCE = 150000
AWACS_ALT = 13000
class AirSupportGenerator:
def __init__(
self,
mission: Mission,
conflict: AirConflictDescription,
game: Game,
radio_registry: RadioRegistry,
tacan_registry: TacanRegistry,
mission_data: MissionData,
) -> None:
self.mission = mission
self.conflict = conflict
self.game = game
self.radio_registry = radio_registry
self.tacan_registry = tacan_registry
self.mission_data = mission_data
@classmethod
def support_tasks(cls) -> List[Type[MainTask]]:
return [Refueling, AWACS]
@staticmethod
def _get_tanker_params(unit_type: Type[UnitType]) -> Tuple[int, int]:
if unit_type is KC130:
return TANKER_ALT - 500, 596
elif unit_type is KC_135:
return TANKER_ALT, 770
elif unit_type is KC135MPRS:
return TANKER_ALT + 500, 596
return TANKER_ALT, 574
def generate(self) -> None:
player_cp = (
self.conflict.blue_cp
if self.conflict.blue_cp.captured
else self.conflict.red_cp
)
country = self.mission.country(self.game.blue.country_name)
if not self.game.settings.disable_legacy_tanker:
fallback_tanker_number = 0
for i, tanker_unit_type in enumerate(
self.game.faction_for(player=True).tankers
):
unit_type = tanker_unit_type.dcs_unit_type
if not issubclass(unit_type, PlaneType):
logging.warning(f"Refueling aircraft {unit_type} must be a plane")
continue
# TODO: Make loiter altitude a property of the unit type.
alt, airspeed = self._get_tanker_params(tanker_unit_type.dcs_unit_type)
freq = self.radio_registry.alloc_uhf()
tacan = self.tacan_registry.alloc_for_band(
TacanBand.Y, TacanUsage.AirToAir
)
tanker_heading = Heading.from_degrees(
self.conflict.red_cp.position.heading_between_point(
self.conflict.blue_cp.position
)
+ TANKER_HEADING_OFFSET * i
)
tanker_position = player_cp.position.point_from_heading(
tanker_heading.degrees, TANKER_DISTANCE
)
tanker_group = self.mission.refuel_flight(
country=country,
name=namegen.next_tanker_name(country, tanker_unit_type),
airport=None,
plane_type=unit_type,
position=tanker_position,
altitude=alt,
race_distance=58000,
frequency=freq.mhz,
start_type=StartType.Warm,
speed=airspeed,
tacanchannel=str(tacan),
)
tanker_group.set_frequency(freq.mhz)
callsign = callsign_for_support_unit(tanker_group)
tacan_callsign = {
"Texaco": "TEX",
"Arco": "ARC",
"Shell": "SHL",
}.get(callsign)
if tacan_callsign is None:
# The dict above is all the callsigns currently in the game, but
# non-Western countries don't use the callsigns and instead just
# use numbers. It's possible that none of those nations have
# TACAN compatible refueling aircraft, but fallback just in
# case.
tacan_callsign = f"TK{fallback_tanker_number}"
fallback_tanker_number += 1
if tanker_unit_type != IL_78M:
# Override PyDCS tacan channel.
tanker_group.points[0].tasks.pop()
tanker_group.points[0].tasks.append(
ActivateBeaconCommand(
tacan.number,
tacan.band.value,
tacan_callsign,
True,
tanker_group.units[0].id,
True,
)
)
tanker_group.points[0].tasks.append(SetInvisibleCommand(True))
tanker_group.points[0].tasks.append(SetImmortalCommand(True))
self.mission_data.tankers.append(
TankerInfo(
group_name=str(tanker_group.name),
callsign=callsign,
variant=tanker_unit_type.display_name,
freq=freq,
tacan=tacan,
start_time=None,
end_time=None,
blue=True,
)
)
if not self.game.settings.disable_legacy_aewc:
possible_awacs = [
a
for a in self.game.faction_for(player=True).aircrafts
if a.capable_of(FlightType.AEWC)
]
if not possible_awacs:
logging.warning("No AWACS for faction")
return
awacs_unit = possible_awacs[0]
freq = self.radio_registry.alloc_uhf()
unit_type = awacs_unit.dcs_unit_type
if not issubclass(unit_type, PlaneType):
logging.warning(f"AWACS aircraft {unit_type} must be a plane")
return
awacs_flight = self.mission.awacs_flight(
country=country,
name=namegen.next_awacs_name(country),
plane_type=unit_type,
altitude=AWACS_ALT,
airport=None,
position=self.conflict.center.random_point_within(
AWACS_DISTANCE, AWACS_DISTANCE
),
frequency=freq.mhz,
start_type=StartType.Warm,
)
awacs_flight.set_frequency(freq.mhz)
awacs_flight.points[0].tasks.append(SetInvisibleCommand(True))
awacs_flight.points[0].tasks.append(SetImmortalCommand(True))
self.mission_data.awacs.append(
AwacsInfo(
group_name=str(awacs_flight.name),
callsign=callsign_for_support_unit(awacs_flight),
freq=freq,
depature_location=None,
start_time=None,
end_time=None,
blue=True,
)
)

View File

@@ -1,7 +1,6 @@
"""
Briefing generation logic
"""
from __future__ import annotations
import os
@@ -17,7 +16,7 @@ from game.radio.radios import RadioFrequency
from game.runways import RunwayData
from game.theater import ControlPoint, FrontLine
from .aircraft.flightdata import FlightData
from .missiondata import AwacsInfo, TankerInfo
from .airsupportgenerator import AwacsInfo, TankerInfo
from .flotgenerator import JtacInfo
if TYPE_CHECKING:

View File

@@ -27,7 +27,7 @@ from dcs.triggers import Event, TriggerOnce
from dcs.unit import Skill, Vehicle
from dcs.unitgroup import VehicleGroup
from game.callsigns.callsign import callsign_for_support_unit
from game.callsigns import callsign_for_support_unit
from game.data.units import UnitClass
from game.dcs.aircrafttype import AircraftType
from game.dcs.groundunittype import GroundUnitType

View File

@@ -22,7 +22,6 @@ https://forums.eagle.ru/showthread.php?t=206360 claims that kneeboard pages can
only be added per airframe, so PvP missions where each side have the same
aircraft will be able to see the enemy's kneeboard for the same airframe.
"""
import datetime
import math
import textwrap
@@ -47,7 +46,7 @@ from game.theater.bullseye import Bullseye
from game.utils import Distance, UnitSystem, meters, mps, pounds
from game.weather.weather import Weather
from .aircraft.flightdata import FlightData
from .missiondata import AwacsInfo, TankerInfo
from .airsupportgenerator import AwacsInfo, TankerInfo
from .briefinggenerator import CommInfo, JtacInfo, MissionInfoGenerator
from ..ato import Package

View File

@@ -24,6 +24,7 @@ from game.theater import Airfield
from game.theater.bullseye import Bullseye
from game.unitmap import UnitMap
from .airconflictdescription import AirConflictDescription
from .airsupportgenerator import AirSupportGenerator
from .briefinggenerator import BriefingGenerator, MissionInfoGenerator
from .cargoshipgenerator import CargoShipGenerator
from .convoygenerator import ConvoyGenerator
@@ -239,6 +240,17 @@ class MissionGenerator:
def generate_air_units(self, tgo_generator: TgoGenerator) -> None:
"""Generate the air units for the Operation"""
# Air Support (Tanker & Awacs)
air_support_generator = AirSupportGenerator(
self.mission,
AirConflictDescription.for_theater(self.game.theater),
self.game,
self.radio_registry,
self.tacan_registry,
self.mission_data,
)
air_support_generator.generate()
# Generate Aircraft Activity on the map
aircraft_generator = AircraftGenerator(
self.mission,
@@ -248,7 +260,7 @@ class MissionGenerator:
self.radio_registry,
self.tacan_registry,
self.unit_map,
mission_data=self.mission_data,
mission_data=air_support_generator.mission_data,
helipads=tgo_generator.helipads,
)
@@ -274,7 +286,7 @@ class MissionGenerator:
if not flight.client_units:
continue
flight.aircraft_type.assign_channels_for_flight(
flight, self.mission_data
flight, air_support_generator.mission_data
)
self.mission_data.briefing_data = aircraft_generator.briefing_data

View File

@@ -5,7 +5,6 @@ groups, statics, missile sites, and AA sites for the mission. Each of these
objectives is defined in the Theater by a TheaterGroundObject. These classes
create the pydcs groups and statics for those areas and add them to the mission.
"""
from __future__ import annotations
import logging

View File

@@ -48,10 +48,12 @@ class PurchaseAdapter(Generic[ItemType]):
return self.pending_delivery_quantity(item) < 0
@abstractmethod
def current_quantity_of(self, item: ItemType) -> int: ...
def current_quantity_of(self, item: ItemType) -> int:
...
@abstractmethod
def pending_delivery_quantity(self, item: ItemType) -> int: ...
def pending_delivery_quantity(self, item: ItemType) -> int:
...
def expected_quantity_next_turn(self, item: ItemType) -> int:
return self.current_quantity_of(item) + self.pending_delivery_quantity(item)
@@ -63,28 +65,36 @@ class PurchaseAdapter(Generic[ItemType]):
return self.can_sell(item) or self.has_pending_orders(item)
@abstractmethod
def can_sell(self, item: ItemType) -> bool: ...
def can_sell(self, item: ItemType) -> bool:
...
@abstractmethod
def do_purchase(self, item: ItemType) -> None: ...
def do_purchase(self, item: ItemType) -> None:
...
@abstractmethod
def do_cancel_purchase(self, item: ItemType) -> None: ...
def do_cancel_purchase(self, item: ItemType) -> None:
...
@abstractmethod
def do_sale(self, item: ItemType) -> None: ...
def do_sale(self, item: ItemType) -> None:
...
@abstractmethod
def do_cancel_sale(self, item: ItemType) -> None: ...
def do_cancel_sale(self, item: ItemType) -> None:
...
@abstractmethod
def price_of(self, item: ItemType) -> int: ...
def price_of(self, item: ItemType) -> int:
...
@abstractmethod
def name_of(self, item: ItemType, multiline: bool = False) -> str: ...
def name_of(self, item: ItemType, multiline: bool = False) -> str:
...
@abstractmethod
def unit_type_of(self, item: ItemType) -> UnitType[Any]: ...
def unit_type_of(self, item: ItemType) -> UnitType[Any]:
...
class AircraftPurchaseAdapter(PurchaseAdapter[Squadron]):

View File

@@ -389,76 +389,3 @@ class WarthogChannelNamer(ChannelNamer):
@classmethod
def name(cls) -> str:
return "a10c-ii"
class PhantomChannelNamer(ChannelNamer):
"""Channel namer for the F4-E."""
@staticmethod
def channel_name(radio_id: int, channel_id: int) -> str:
radio_name = [
"COMM", # AN/ARC-164 COMM
"AUX", # AN/ARC-164 AUX
][radio_id - 1]
return f"{radio_name} Ch {channel_id}"
@classmethod
def name(cls) -> str:
return "phantom"
class HindChannelNamer(ChannelNamer):
"""Channel namer for Mi-24 Hind"""
@staticmethod
def channel_name(radio_id: int, channel_id: int) -> str:
radio_name = [
"R863",
"R828",
][radio_id - 1]
return f"{radio_name} Ch {channel_id-1}"
@classmethod
def name(cls) -> str:
return "hind"
class HipChannelNamer(ChannelNamer):
"""Channel namer for Mi-8 Hip"""
@staticmethod
def channel_name(radio_id: int, channel_id: int) -> str:
radio_name = [
"R863",
"R828",
][radio_id - 1]
return f"{radio_name} Ch {channel_id}"
@classmethod
def name(cls) -> str:
return "hip"
class KiowaChannelNamer(ChannelNamer):
"""Channel namer for OH58D Kiowa Warrior"""
@staticmethod
def channel_name(radio_id: int, channel_id: int) -> str:
radio_name = ["UHF AM", "VHF AM", "VHF FM1", "VHF FM2"][radio_id - 1]
return f"{radio_name} Ch {channel_id}"
@classmethod
def name(cls) -> str:
return "kiowa"
class FulcrumChannelNamer(ChannelNamer):
"""Channel namer for MiG-29A Fulcrum"""
@staticmethod
def channel_name(radio_id: int, channel_id: int) -> str:
return f"R862 Ch {channel_id}"
@classmethod
def name(cls) -> str:
return "fulcrum"

View File

@@ -1,5 +1,4 @@
"""Radio frequency types and allocators."""
from __future__ import annotations
import itertools
@@ -160,7 +159,6 @@ RADIOS: List[Radio] = [
Radio("AN/ARC-164", (RadioRange(MHz(225), MHz(400), MHz(1), Modulation.AM),)),
Radio("AN/ARC-186(V) AM", (RadioRange(MHz(116), MHz(152), MHz(1), Modulation.AM),)),
Radio("AN/ARC-186(V) FM", (RadioRange(MHz(30), MHz(76), MHz(1), Modulation.FM),)),
Radio("AN/ARC-201", (RadioRange(MHz(30), MHz(88), kHz(25), Modulation.FM),)),
Radio(
"AN/ARC-210",
(
@@ -187,7 +185,6 @@ RADIOS: List[Radio] = [
),
),
Radio("AN/ARC-222", (RadioRange(MHz(116), MHz(152), MHz(1), Modulation.AM),)),
Radio("AN/ARC-27", (RadioRange(MHz(225), MHz(400), kHz(100), Modulation.AM),)),
Radio("SCR-522", (RadioRange(MHz(100), MHz(156), MHz(1), Modulation.AM),)),
Radio("A.R.I. 1063", (RadioRange(MHz(100), MHz(156), MHz(1), Modulation.AM),)),
Radio("BC-1206", (RadioRange(kHz(200), kHz(400), kHz(10), Modulation.AM),)),
@@ -234,6 +231,7 @@ RADIOS: List[Radio] = [
# Ka-50
# Note: Also capable of 100MHz-150MHz, but we can't model gaps.
Radio("R-800L1", (RadioRange(MHz(220), MHz(400), kHz(25), Modulation.AM),)),
Radio("R-828", (RadioRange(MHz(20), MHz(60), kHz(25), Modulation.FM),)),
# UH-1H
Radio("AN/ARC-51BX", (RadioRange(MHz(225), MHz(400), kHz(50), Modulation.AM),)),
Radio("AN/ARC-131", (RadioRange(MHz(30), MHz(76), kHz(50), Modulation.FM),)),
@@ -294,19 +292,6 @@ RADIOS: List[Radio] = [
),
),
),
# Mi-8/Mi-24
Radio("R863", (RadioRange(MHz(220), MHz(400), kHz(25), Modulation.AM),)),
Radio("R828", (RadioRange(MHz(20), MHz(60), kHz(25), Modulation.FM),)),
# MiG-29A
Radio(
"R862",
(
RadioRange(MHz(220), MHz(400), kHz(25), Modulation.AM),
RadioRange(MHz(100), MHz(150), kHz(25), Modulation.AM),
RadioRange(MHz(220), MHz(400), kHz(25), Modulation.FM),
RadioRange(MHz(100), MHz(150), kHz(25), Modulation.FM),
),
),
]

View File

@@ -1,5 +1,4 @@
"""TACAN channel handling."""
from __future__ import annotations
import re

View File

@@ -1,5 +1,4 @@
"""Runway information and selection."""
from __future__ import annotations
import logging

View File

@@ -1,5 +1,4 @@
"""Tools for aiding in save compat removal after compatibility breaks."""
from collections.abc import Callable
from typing import TypeVar

View File

@@ -89,11 +89,6 @@ def set_destination(
detail=f"Cannot move {cp} more than "
f"{cp.max_move_distance.nautical_miles}nm.",
)
if cp.is_fleet and not game.theater.is_in_sea(point):
raise HTTPException(
status.HTTP_400_BAD_REQUEST,
detail=f"Cannot move naval control point {cp} onto land.",
)
cp.target_position = point
from .. import EventStream

View File

@@ -28,24 +28,6 @@ class AutoAtoBehavior(Enum):
Prefer = "Prefer player pilots"
@unique
class FastForwardStopCondition(Enum):
DISABLED = "Fast forward disabled"
FIRST_CONTACT = "First contact"
PLAYER_TAKEOFF = "Player takeoff time"
PLAYER_TAXI = "Player taxi time"
PLAYER_STARTUP = "Player startup time"
PLAYER_AT_IP = "Player at IP"
MANUAL = "Manual fast forward control"
@unique
class CombatResolutionMethod(Enum):
PAUSE = "Pause simulation"
RESOLVE = "Resolve combat"
SKIP = "Skip combat"
DIFFICULTY_PAGE = "Difficulty"
AI_DIFFICULTY_SECTION = "AI Difficulty"
@@ -191,6 +173,30 @@ class Settings:
"extremely incomplete so does not affect all weapons."
),
)
disable_legacy_aewc: bool = boolean_option(
"Spawn invulnerable, always-available AEW&C aircraft (deprecated)",
page=CAMPAIGN_MANAGEMENT_PAGE,
section=GENERAL_SECTION,
default=True,
invert=True,
detail=(
"If checked, an invulnerable friendly AEW&C aircraft that begins the "
"mission on station will be be spawned. This behavior will be removed in a "
"future release."
),
)
disable_legacy_tanker: bool = boolean_option(
"Spawn invulnerable, always-available tanker aircraft (deprecated)",
page=CAMPAIGN_MANAGEMENT_PAGE,
section=GENERAL_SECTION,
default=True,
invert=True,
detail=(
"If checked, an invulnerable friendly tanker aircraft that begins the "
"mission on station will be be spawned. This behavior will be removed in a "
"future release."
),
)
# Pilots and Squadrons
ai_pilot_levelling: bool = boolean_option(
"Allow AI pilot leveling",
@@ -311,7 +317,7 @@ class Settings:
"Tactical commander",
page=MISSION_GENERATOR_PAGE,
section=COMMANDERS_SECTION,
default=0,
default=1,
min=0,
max=100,
)
@@ -327,7 +333,7 @@ class Settings:
"Observer",
page=MISSION_GENERATOR_PAGE,
section=COMMANDERS_SECTION,
default=0,
default=1,
min=0,
max=100,
)
@@ -345,6 +351,19 @@ class Settings:
"run out of fuel when players would not."
),
)
fast_forward_to_first_contact: bool = boolean_option(
"Fast forward mission to first contact (WIP)",
page=MISSION_GENERATOR_PAGE,
section=GAMEPLAY_SECTION,
default=False,
detail=(
"If enabled, the mission will be generated at the point of first contact. "
"If you enable this option, you will not be able to create new flights "
'after pressing "TAKE OFF". Doing so will create an error the next time '
'you press "TAKE OFF". Save your game first if you want to make '
"modifications."
),
)
reload_pre_sim_checkpoint_on_abort: bool = boolean_option(
"Reset mission to pre-take off conditions on abort",
page=MISSION_GENERATOR_PAGE,
@@ -356,55 +375,37 @@ class Settings:
"your game after aborting take off."
),
)
turnless_mode: bool = boolean_option(
"Enable turnless mode (WIP)",
player_mission_interrupts_sim_at: Optional[StartType] = choices_option(
"Player missions interrupt fast forward",
page=MISSION_GENERATOR_PAGE,
section=GAMEPLAY_SECTION,
default=None,
choices={
"Never": None,
"At startup time": StartType.COLD,
"At taxi time": StartType.WARM,
"At takeoff time": StartType.RUNWAY,
},
detail=(
"Determines what player mission states will interrupt fast-forwarding to "
"first contact, if enabled. If never is selected player missions will not "
"impact simulation and player missions may be generated mid-flight. The "
"other options will cause the mission to be generated as soon as a player "
"mission reaches the set state or at first contact, whichever comes first."
),
)
auto_resolve_combat: bool = boolean_option(
"Auto-resolve combat during fast-forward (WIP)",
page=MISSION_GENERATOR_PAGE,
section=GAMEPLAY_SECTION,
default=False,
detail=(
"If enabled, turns do not end after mission completion. A new mission "
"can be started picking up from where the previous mission ended."
),
)
fast_forward_stop_condition: FastForwardStopCondition = choices_option(
"Fast forward until",
page=MISSION_GENERATOR_PAGE,
section=GAMEPLAY_SECTION,
default=FastForwardStopCondition.DISABLED,
choices={
"No fast forward": FastForwardStopCondition.DISABLED,
"Player startup time": FastForwardStopCondition.PLAYER_STARTUP,
"Player taxi time": FastForwardStopCondition.PLAYER_TAXI,
"Player takeoff time": FastForwardStopCondition.PLAYER_TAKEOFF,
"Player at IP": FastForwardStopCondition.PLAYER_AT_IP,
"First contact": FastForwardStopCondition.FIRST_CONTACT,
"Manual": FastForwardStopCondition.MANUAL,
},
detail=(
"Determines when fast forwarding stops: "
"No fast forward: disables fast forward. "
"Player startup time: fast forward until player startup time. "
"Player taxi time: fast forward until player taxi time. "
"Player takeoff time: fast forward until player takeoff time. "
"First contact: fast forward until first contact between blue and red units. "
"Manual: manually control fast forward. Show manual controls with --show-sim-speed-controls."
),
)
combat_resolution_method: CombatResolutionMethod = choices_option(
"Resolve combat when fast forwarding by",
page=MISSION_GENERATOR_PAGE,
section=GAMEPLAY_SECTION,
default=CombatResolutionMethod.PAUSE,
choices={
"Pause": CombatResolutionMethod.PAUSE,
"Resolving combat (WIP)": CombatResolutionMethod.RESOLVE,
"Skipping combat": CombatResolutionMethod.SKIP,
},
detail=(
"Determines what happens when combat occurs when fast forwarding. "
"Pause: pause fast forward and generate mission. Fast forwarding may stop before the condition specified in the above setting. "
"Resolving combat (WIP): auto resolve combat. This method is very rudimentary and will result in large losses. "
"Skipping combat: skip combat as if it did not occur."
'Requires a "Player missions interrupt fast forward" setting other than '
'"Never" If enabled, aircraft entering combat during fast forward will have'
"their combat auto-resolved after a period of time. This allows the "
"simulation to advance further into the mission before requiring mission "
"generation, but simulation is currently very rudimentary so may result in "
"huge losses."
),
)
supercarrier: bool = boolean_option(
@@ -466,12 +467,6 @@ class Settings:
default=timedelta(minutes=60),
min=30,
max=150,
detail=(
"Period of time after the start of a turn where "
"there is coverage by one or more CAP flight(s), "
"refuelling flights not tied to a specific package are on station, "
"and other flights have their TOTs."
),
)
# Performance

View File

@@ -10,7 +10,6 @@ from the output.
https://nso.nato.int/nso/nsdd/main/standards/ap-details/1912/EN
https://www.spatialillusions.com/milsymbol/docs/milsymbol-APP6d.html
"""
from __future__ import annotations
from abc import ABC, abstractmethod
@@ -331,15 +330,18 @@ class SymbolIdentificationCode:
class SidcDescribable(ABC):
@property
@abstractmethod
def standard_identity(self) -> StandardIdentity: ...
def standard_identity(self) -> StandardIdentity:
...
@property
@abstractmethod
def sidc_status(self) -> Status: ...
def sidc_status(self) -> Status:
...
@property
@abstractmethod
def symbol_set_and_entity(self) -> tuple[SymbolSet, Entity]: ...
def symbol_set_and_entity(self) -> tuple[SymbolSet, Entity]:
...
def sidc(self) -> SymbolIdentificationCode:
symbol_set, entity = self.symbol_set_and_entity

View File

@@ -7,8 +7,9 @@ from datetime import datetime, timedelta
from typing_extensions import TYPE_CHECKING
from game.ato.flightstate import Uninitialized, Completed, InCombat
from game.settings.settings import FastForwardStopCondition, CombatResolutionMethod
from game.ato.flightstate import (
Uninitialized,
)
from .combat import CombatInitiator, FrozenCombat
from .gameupdateevents import GameUpdateEvents
from .simulationresults import SimulationResults
@@ -25,20 +26,13 @@ class AircraftSimulation:
self.results = SimulationResults()
def begin_simulation(self) -> None:
self.reset()
self.set_initial_flight_states()
def on_game_tick(
self,
events: GameUpdateEvents,
time: datetime,
duration: timedelta,
combat_resolution_method: CombatResolutionMethod,
force_continue: bool,
self, events: GameUpdateEvents, time: datetime, duration: timedelta
) -> None:
if (
not self._auto_resolve_combat(combat_resolution_method, force_continue)
and self.combats
):
if not self.game.settings.auto_resolve_combat and self.combats:
logging.error(
"Cannot resume simulation because aircraft are in combat and "
"auto-resolve is disabled"
@@ -48,13 +42,7 @@ class AircraftSimulation:
still_active = []
for combat in self.combats:
if combat.on_game_tick(
time,
duration,
self.results,
events,
combat_resolution_method,
):
if combat.on_game_tick(time, duration, self.results, events):
events.end_combat(combat)
else:
still_active.append(combat)
@@ -69,38 +57,22 @@ class AircraftSimulation:
# After updating all combat states, check for halts.
for flight in self.iter_flights():
if flight.should_halt_sim() and not force_continue:
if flight.should_halt_sim():
events.complete_simulation()
return
# Find completed flights, removing them from the ATO and returning aircraft
# and pilots back to the squadron.
for flight in self.iter_flights():
if type(flight.state) == Completed:
flight.package.remove_flight(flight)
if len(flight.package.flights) == 0:
flight.squadron.coalition.ato.remove_package(flight.package)
if (
not self._auto_resolve_combat(combat_resolution_method, force_continue)
and self.combats
):
if not self.game.settings.auto_resolve_combat and self.combats:
events.complete_simulation()
def set_initial_flight_states(self) -> None:
# Initialize flights in Uninitialized state
now = self.game.simulation_time
now = self.game.conditions.start_time
for flight in self.iter_flights():
flight.state.initialize(now)
flight.state.reinitialize(now)
# Recover combat instances from flight states. Flight state information is serialized
# when saving a game but the aircraft simulation state is not. Combat instances are
# de-duplicated as multiple flights can be involved in a single combat instance.
combats = set()
def reset(self) -> None:
for flight in self.iter_flights():
if type(flight.state) == InCombat:
combats.add(flight.state.combat)
self.combats = list(combats)
flight.set_state(Uninitialized(flight, self.game.settings))
self.combats = []
def iter_flights(self) -> Iterator[Flight]:
packages = itertools.chain(
@@ -108,10 +80,3 @@ class AircraftSimulation:
)
for package in packages:
yield from package.flights
def _auto_resolve_combat(
self, combat_resolution_method: CombatResolutionMethod, force_continue: bool
) -> bool:
if force_continue:
return True
return combat_resolution_method != CombatResolutionMethod.PAUSE

View File

@@ -8,7 +8,6 @@ from typing import TYPE_CHECKING
from shapely.ops import unary_union
from game.ato.flightstate import InCombat, InFlight
from game.settings.settings import CombatResolutionMethod
from game.utils import dcs_to_shapely_point
from .joinablecombat import JoinableCombat
from .. import GameUpdateEvents
@@ -68,15 +67,7 @@ class AirCombat(JoinableCombat):
events: GameUpdateEvents,
time: datetime,
elapsed_time: timedelta,
resolution_method: CombatResolutionMethod,
) -> None:
if resolution_method is CombatResolutionMethod.SKIP:
for flight in self.flights:
assert isinstance(flight.state, InCombat)
flight.state.exit_combat(events, time, elapsed_time)
return
blue = []
red = []
for flight in self.flights:

View File

@@ -8,7 +8,6 @@ from typing import TYPE_CHECKING
from .frozencombat import FrozenCombat
from .. import GameUpdateEvents
from ...ato.flightstate import InCombat
from game.settings.settings import CombatResolutionMethod
if TYPE_CHECKING:
from game.ato import Flight
@@ -35,7 +34,6 @@ class AtIp(FrozenCombat):
events: GameUpdateEvents,
time: datetime,
elapsed_time: timedelta,
resolution_method: CombatResolutionMethod,
) -> None:
logging.debug(
f"{self.flight} attack on {self.flight.package.target} auto-resolved with "

View File

@@ -7,7 +7,6 @@ from datetime import datetime, timedelta
from typing import TYPE_CHECKING
from game.ato.flightstate import InCombat
from game.settings.settings import CombatResolutionMethod
from .frozencombat import FrozenCombat
from .. import GameUpdateEvents
@@ -44,14 +43,8 @@ class DefendingSam(FrozenCombat):
events: GameUpdateEvents,
time: datetime,
elapsed_time: timedelta,
resolution_method: CombatResolutionMethod,
) -> None:
assert isinstance(self.flight.state, InCombat)
if resolution_method is CombatResolutionMethod.SKIP:
self.flight.state.exit_combat(events, time, elapsed_time)
return
if random.random() >= 0.5:
logging.debug(f"Air defense combat auto-resolved with {self.flight} lost")
self.flight.kill(results, events)

View File

@@ -7,7 +7,6 @@ from datetime import datetime, timedelta
from typing import TYPE_CHECKING
from game.ato.flightstate import InCombat, InFlight
from game.settings.settings import CombatResolutionMethod
from .. import GameUpdateEvents
if TYPE_CHECKING:
@@ -27,11 +26,10 @@ class FrozenCombat(ABC):
duration: timedelta,
results: SimulationResults,
events: GameUpdateEvents,
resolution_method: CombatResolutionMethod,
) -> bool:
self.elapsed_time += duration
if self.elapsed_time >= self.freeze_duration:
self.resolve(results, events, time, self.elapsed_time, resolution_method)
self.resolve(results, events, time, self.elapsed_time)
return True
return False
@@ -42,17 +40,20 @@ class FrozenCombat(ABC):
events: GameUpdateEvents,
time: datetime,
elapsed_time: timedelta,
resolution_method: CombatResolutionMethod,
) -> None: ...
) -> None:
...
@abstractmethod
def because(self) -> str: ...
def because(self) -> str:
...
@abstractmethod
def describe(self) -> str: ...
def describe(self) -> str:
...
@abstractmethod
def iter_flights(self) -> Iterator[Flight]: ...
def iter_flights(self) -> Iterator[Flight]:
...
def update_flight_states(self) -> None:
for flight in self.iter_flights():

View File

@@ -18,7 +18,8 @@ class JoinableCombat(FrozenCombat, ABC):
self.flights = flights
@abstractmethod
def joinable_by(self, flight: Flight) -> bool: ...
def joinable_by(self, flight: Flight) -> bool:
...
def join(self, flight: Flight) -> None:
assert isinstance(flight.state, InFlight)

View File

@@ -65,7 +65,7 @@ class GameLoop:
self.start()
logging.info("Running sim to first contact")
while not self.completed:
self.tick(suppress_events=False)
self.tick(suppress_events=True)
def pause_and_generate_miz(self, output: Path) -> None:
self.pause()
@@ -100,11 +100,7 @@ class GameLoop:
if not self.started:
raise RuntimeError("Attempted to tick game loop before initialization")
try:
self.sim.tick(
self.events,
self.game.settings.combat_resolution_method,
force_continue=False,
)
self.sim.tick(self.events)
self.completed = self.events.simulation_complete
if not suppress_events:
self.send_update(rate_limit=True)

View File

@@ -8,7 +8,6 @@ from game.ground_forces.combat_stance import CombatStance
from game.theater import ControlPoint
from .gameupdateevents import GameUpdateEvents
from ..ato.airtaaskingorder import AirTaskingOrder
from ..ato.flightstate.atdeparture import AtDeparture
if TYPE_CHECKING:
from ..game import Game
@@ -35,7 +34,6 @@ class MissionResultsProcessor:
self.commit_damaged_runways(debriefing)
self.commit_captures(debriefing, events)
self.commit_front_line_battle_impact(debriefing, events)
self.commit_unit_damage(debriefing)
self.record_carcasses(debriefing)
def commit_air_losses(self, debriefing: Debriefing) -> None:
@@ -58,25 +56,6 @@ class MissionResultsProcessor:
logging.info(f"{aircraft} destroyed from {squadron}")
squadron.owned_aircraft -= 1
# Remove air losses from the flight. Remove the flight if all aircraft are lost.
# Remove the package if the flight is the last flight in the package.
# This logic is redundant if we are going to a new turn, since the whole ATO is
# regenerated. However if we want to keep the ATO to continue a turn, this update
# is necessary to make sure lost aircraft are removed from the ATO.
if loss.pilot is not None:
loss.flight.roster.remove_pilot(loss.pilot)
if loss.flight.count == 0: # Last aircraft in the flight, remove the flight
# If no flights in package, generally indicates that the loss is an aircraft
# that is not assigned to a mission and is parked on the ground. There is no need
# to remove the aircraft from the ATO as it was never in the ATO in the first place.
if len(loss.flight.package.flights) == 0:
continue
loss.flight.package.remove_flight(loss.flight)
if len(loss.flight.package.flights) == 0:
loss.flight.squadron.coalition.ato.remove_package(
loss.flight.package
)
@staticmethod
def _commit_pilot_experience(ato: AirTaskingOrder) -> None:
for package in ato.packages:
@@ -168,21 +147,10 @@ class MissionResultsProcessor:
iads_network.update_network(events)
return
def commit_damaged_runways(self, debriefing: Debriefing) -> None:
@staticmethod
def commit_damaged_runways(debriefing: Debriefing) -> None:
for damaged_runway in debriefing.damaged_runways:
damaged_runway.damage_runway()
# Remove any flight in ATO scheduled to take off from the damaged runway.
for coalition in self.game.coalitions:
for package in coalition.ato.packages:
for flight in package.flights:
if flight.departure.name == damaged_runway.name and isinstance(
flight.state, AtDeparture
):
flight.package.remove_flight(flight)
if len(flight.package.flights) == 0:
flight.squadron.coalition.ato.remove_package(
flight.package
)
def commit_captures(self, debriefing: Debriefing, events: GameUpdateEvents) -> None:
for captured in debriefing.base_captures:
@@ -339,52 +307,42 @@ class MissionResultsProcessor:
f"{enemy_cp.name}. {status_msg}",
)
@staticmethod
def commit_unit_damage(debriefing: Debriefing) -> None:
for damaged_unit in debriefing.unit_hit_point_update_events():
logging.info(
f"{damaged_unit.unit.theater_unit.name} damaged, setting hit points to {damaged_unit.hit_points}"
)
damaged_unit.commit()
def redeploy_units(self, cp: ControlPoint) -> None:
""" "
Auto redeploy units to newly captured base
"""
# Find the set of friendly CPs that can either contribute or receive frontline units
all_ally_connected_cps = cp.transitive_connected_friendly_points() + [cp]
# Split into frontline CPs that are connected to enemy CPs and should receive units
# vs. non-frontline CPs that are not connected to enemy CPs and should send units.
frontline_cps = []
non_frontline_cps = []
for cp in all_ally_connected_cps:
is_frontline = False
for ocp in cp.connected_points:
if not ocp.captured:
is_frontline = True
break
if is_frontline:
frontline_cps.append(cp)
else:
non_frontline_cps.append(cp)
ally_connected_cps = [
ocp for ocp in cp.connected_points if cp.captured == ocp.captured
]
enemy_connected_cps = [
ocp for ocp in cp.connected_points if cp.captured != ocp.captured
]
# If there are no frontline CPs, then nothing to do.
if len(frontline_cps) == 0:
# If the newly captured cp does not have enemy connected cp,
# then it is not necessary to redeploy frontline units there.
if len(enemy_connected_cps) == 0:
return
# Equally split between all frontline CPs
move_factor = 1.0 / len(frontline_cps)
for non_frontline_cp in non_frontline_cps:
for frontline_cp in frontline_cps:
self.redeploy_between(frontline_cp, non_frontline_cp, move_factor)
# From each ally cp, send reinforcements
for ally_cp in ally_connected_cps:
self.redeploy_between(cp, ally_cp)
def redeploy_between(
self, destination: ControlPoint, source: ControlPoint, move_factor: float
) -> None:
def redeploy_between(self, destination: ControlPoint, source: ControlPoint) -> None:
total_units_redeployed = 0
moved_units = {}
if source.has_active_frontline or not destination.captured:
# If there are still active front lines to defend at the
# transferring CP we should not transfer all units.
#
# Opfor also does not transfer all of their units.
# TODO: Balance the CPs rather than moving half from everywhere.
move_factor = 0.5
else:
# Otherwise we can move everything.
move_factor = 1
for frontline_unit, count in source.base.armor.items():
moved_units[frontline_unit] = int(count * move_factor)
total_units_redeployed = total_units_redeployed + int(count * move_factor)

View File

@@ -1,5 +1,5 @@
from __future__ import annotations
import copy
import json
from datetime import timedelta
from pathlib import Path
@@ -7,7 +7,6 @@ from typing import Optional, TYPE_CHECKING
from game.debriefing import Debriefing
from game.missiongenerator import MissionGenerator
from game.settings.settings import FastForwardStopCondition, CombatResolutionMethod
from game.unitmap import UnitMap
from .aircraftsimulation import AircraftSimulation
from .missionresultsprocessor import MissionResultsProcessor
@@ -32,31 +31,17 @@ class MissionSimulation:
self.unit_map: Optional[UnitMap] = None
self.aircraft_simulation = AircraftSimulation(self.game)
self.completed = False
self.time = self.game.simulation_time
self.time = self.game.conditions.start_time
def begin_simulation(self) -> None:
self.time = self.game.simulation_time
self.time = self.game.conditions.start_time
self.aircraft_simulation.begin_simulation()
def tick(
self,
events: GameUpdateEvents,
combat_resolution_method: CombatResolutionMethod,
force_continue: bool,
) -> GameUpdateEvents:
def tick(self, events: GameUpdateEvents) -> GameUpdateEvents:
self.time += TICK
self.game.simulation_time = self.time
if self.completed:
raise RuntimeError("Simulation already completed")
if (
self.game.settings.fast_forward_stop_condition
== FastForwardStopCondition.DISABLED
):
events.complete_simulation()
return events
self.aircraft_simulation.on_game_tick(
events, self.time, TICK, combat_resolution_method, force_continue
)
self.aircraft_simulation.on_game_tick(events, self.time, TICK)
self.completed = events.simulation_complete
return events
@@ -90,24 +75,6 @@ class MissionSimulation:
self.game.save_last_turn_state()
MissionResultsProcessor(self.game).commit(debriefing, events)
if self.game.settings.turnless_mode:
# Set completed to False to clear completion of any previous simulation tick.
self.completed = False
# If running in turnless mode, run sim to calculate planned positions of flights
# for the duration of time the DCS mission ran.
start_time = copy.deepcopy(self.time)
while self.time < start_time + timedelta(
seconds=int(debriefing.state_data.simulation_time_seconds)
):
# Always skip combat as we are processing results from DCS. Any combat has already
# been resolved in-game
self.tick(events, CombatResolutionMethod.SKIP, force_continue=True)
self.game.blue.plan_missions(self.game.simulation_time)
self.game.red.plan_missions(self.game.simulation_time)
self.game.game_stats.update(self.game)
# Generate begin_new_turn event which triggers a refresh of the React map screen to
# show newly planned missions.
events.begin_new_turn()
def finish(self) -> None:
self.unit_map = None

View File

@@ -472,7 +472,8 @@ class ControlPoint(MissionTarget, SidcDescribable, ABC):
@property
@abstractmethod
def heading(self) -> Heading: ...
def heading(self) -> Heading:
...
def __str__(self) -> str:
return self.name
@@ -593,7 +594,8 @@ class ControlPoint(MissionTarget, SidcDescribable, ABC):
@property
@abstractmethod
def can_deploy_ground_units(self) -> bool: ...
def can_deploy_ground_units(self) -> bool:
...
@property
@abstractmethod
@@ -762,9 +764,6 @@ class ControlPoint(MissionTarget, SidcDescribable, ABC):
def aircraft_retreat_destination(
self, squadron: Squadron
) -> Optional[ControlPoint]:
if not self.runway_is_operational():
return None
closest = ObjectiveDistanceCache.get_closest_airfields(self)
max_retreat_distance = squadron.aircraft.max_mission_range
# Skip the first airbase because that's the airbase we're retreating
@@ -878,7 +877,8 @@ class ControlPoint(MissionTarget, SidcDescribable, ABC):
return None
@abstractmethod
def can_operate(self, aircraft: AircraftType) -> bool: ...
def can_operate(self, aircraft: AircraftType) -> bool:
...
def unclaimed_parking(self) -> int:
return self.total_aircraft_parking - self.allocated_aircraft().total
@@ -889,7 +889,8 @@ class ControlPoint(MissionTarget, SidcDescribable, ABC):
theater: ConflictTheater,
conditions: Conditions,
dynamic_runways: Dict[str, RunwayData],
) -> RunwayData: ...
) -> RunwayData:
...
def stub_runway_data(self) -> RunwayData:
return RunwayData(
@@ -906,11 +907,13 @@ class ControlPoint(MissionTarget, SidcDescribable, ABC):
@property
@abstractmethod
def runway_is_destroyable(self) -> bool: ...
def runway_is_destroyable(self) -> bool:
...
@property
@abstractmethod
def runway_status(self) -> RunwayStatus: ...
def runway_status(self) -> RunwayStatus:
...
@abstractmethod
def describe_runway_status(self) -> str | None:
@@ -1068,11 +1071,13 @@ class ControlPoint(MissionTarget, SidcDescribable, ABC):
@property
@abstractmethod
def category(self) -> str: ...
def category(self) -> str:
...
@property
@abstractmethod
def status(self) -> ControlPointStatus: ...
def status(self) -> ControlPointStatus:
...
class Airfield(ControlPoint):
@@ -1278,10 +1283,7 @@ class NavalControlPoint(ControlPoint, ABC):
return RunwayStatus(damaged=not self.runway_is_operational())
def describe_runway_status(self) -> str:
if self.runway_is_operational():
return f"Flight deck {self.runway_status.describe()}"
# Special handling for not operational carriers/LHAs
return f"Sunk"
return f"Flight deck {self.runway_status.describe()}"
@property
def runway_can_be_repaired(self) -> bool:

View File

@@ -107,7 +107,7 @@ class FrontLine(MissionTarget):
yield from [
FlightType.CAS,
FlightType.AEWC,
FlightType.REFUELING,
FlightType.REFUELING
# TODO: FlightType.TROOP_TRANSPORT
# TODO: FlightType.EVAC
]

View File

@@ -66,7 +66,7 @@ class ModSettings:
frenchpack: bool = False
high_digit_sams: bool = False
ov10a_bronco: bool = False
fa18efg: bool = False
superhornet: bool = False
def save_player_settings(self) -> None:
"""Saves the player's global settings to the user directory."""

View File

@@ -35,8 +35,6 @@ class TheaterUnit:
position: PointWithHeading
# The parent ground object
ground_object: TheaterGroundObject
# Number of hit points the unit has
hit_points: Optional[int] = None
# State of the unit, dead or alive
alive: bool = True
@@ -44,17 +42,13 @@ class TheaterUnit:
def from_template(
id: int, dcs_type: Type[DcsUnitType], t: LayoutUnit, go: TheaterGroundObject
) -> TheaterUnit:
unit = TheaterUnit(
return TheaterUnit(
id,
t.name,
dcs_type,
PointWithHeading.from_point(t.position, Heading.from_degrees(t.heading)),
go,
)
# if the TheaterUnit represents a GroundUnitType or ShipUnitType, initialize health to full hit points
if unit.unit_type is not None:
unit.hit_points = unit.unit_type.hit_points
return unit
@property
def unit_type(self) -> Optional[UnitType[Any]]:
@@ -76,12 +70,14 @@ class TheaterUnit:
@property
def display_name(self) -> str:
dead_label = " [DEAD]" if not self.alive else ""
unit_label = self.unit_type or self.type.name or self.name
return f"{str(self.id).zfill(4)} | {unit_label}{self._status_label()}"
return f"{str(self.id).zfill(4)} | {unit_label}{dead_label}"
@property
def short_name(self) -> str:
return f"<b>{self.type.id[0:18]}</b> {self._status_label()}"
dead_label = " [DEAD]" if not self.alive else ""
return f"<b>{self.type.id[0:18]}</b> {dead_label}"
@property
def is_static(self) -> bool:
@@ -121,18 +117,6 @@ class TheaterUnit:
unit_range = getattr(self.type, "threat_range", None)
return meters(unit_range if unit_range is not None and self.alive else 0)
def _status_label(self) -> str:
if not self.alive:
return " [DEAD]"
if self.unit_type is None:
return ""
if self.hit_points is None:
return ""
if self.unit_type.hit_points == self.hit_points:
return ""
damage_percentage = 100 - int(100 * self.hit_points / self.unit_type.hit_points)
return f" [DAMAGED {damage_percentage}%]"
class SceneryUnit(TheaterUnit):
"""Special TheaterUnit for handling scenery ground objects"""

View File

@@ -8,7 +8,7 @@ from enum import Enum, auto
from typing import Dict, Iterator, List, Optional, Set, Tuple
from .conflicttheater import ConflictTheater
from .controlpoint import ControlPoint, ControlPointType
from .controlpoint import ControlPoint
class NoPathError(RuntimeError):
@@ -47,9 +47,9 @@ class TransitConnection(Enum):
class TransitNetwork:
def __init__(self) -> None:
self.nodes: Dict[ControlPoint, Dict[ControlPoint, TransitConnection]] = (
defaultdict(dict)
)
self.nodes: Dict[
ControlPoint, Dict[ControlPoint, TransitConnection]
] = defaultdict(dict)
def has_destinations(self, control_point: ControlPoint) -> bool:
return bool(self.nodes[control_point])
@@ -160,14 +160,7 @@ class TransitNetworkBuilder:
self.airports: Set[ControlPoint] = {
cp
for cp in self.control_points
if cp.is_friendly(for_player)
and cp.runway_is_operational()
and cp.cptype
not in [
ControlPointType.LHA_GROUP,
ControlPointType.AIRCRAFT_CARRIER_GROUP,
ControlPointType.OFF_MAP,
] # TransitNetwork is for ground units, so do not consider LHAs, CVNs or off map spawns.
if cp.is_friendly(for_player) and cp.runway_is_operational()
}
def build(self) -> TransitNetwork:

View File

@@ -29,7 +29,6 @@ transports and processing the turn's transit actions.
Routing is handled by TransitNetwork.
"""
from __future__ import annotations
import logging
@@ -495,9 +494,9 @@ TransportType = TypeVar("TransportType", bound=MultiGroupTransport)
class TransportMap(Generic[TransportType]):
def __init__(self) -> None:
# Dict of origin -> destination -> transport.
self.transports: dict[ControlPoint, dict[ControlPoint, TransportType]] = (
defaultdict(dict)
)
self.transports: dict[
ControlPoint, dict[ControlPoint, TransportType]
] = defaultdict(dict)
def create_transport(
self, origin: ControlPoint, destination: ControlPoint

View File

@@ -1,5 +1,4 @@
"""Maps generated units back to their Liberation types."""
from __future__ import annotations
import itertools

View File

@@ -1,7 +1,7 @@
from pathlib import Path
MAJOR_VERSION = 14
MAJOR_VERSION = 11
MINOR_VERSION = 0
MICRO_VERSION = 0
VERSION_NUMBER = ".".join(str(v) for v in (MAJOR_VERSION, MINOR_VERSION, MICRO_VERSION))

View File

@@ -101,7 +101,8 @@ class Weather(ABC):
@property
@abstractmethod
def archetype(self) -> WeatherArchetype: ...
def archetype(self) -> WeatherArchetype:
...
@property
def pressure_adjustment(self) -> float:

View File

@@ -25,7 +25,8 @@ class WeibullWindSpeedParameters:
class WindSpeedGenerator(ABC):
@abstractmethod
def random_wind(self) -> WindConditions: ...
def random_wind(self) -> WindConditions:
...
@staticmethod
def from_data(data: dict[str, Any]) -> WindSpeedGenerator:

Some files were not shown because too many files have changed in this diff Show More