Prepare fixtures

This commit is contained in:
dkanus 2026-07-14 20:27:09 +07:00
commit 9c94356263
6021 changed files with 722805 additions and 22 deletions

View file

@ -0,0 +1,119 @@
/**
* Main and only Acedia mutator. Used for providing access to mutator
* events' calls and detecting server travel.
* Copyright 2020-2023 Anton Tarasenko
* 2023 Shtoyan
*------------------------------------------------------------------------------
* This file is part of Acedia.
*
* Acedia is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3 of the License, or
* (at your option) any later version.
*
* Acedia is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Acedia. If not, see <https://www.gnu.org/licenses/>.
*/
class AcediaLauncherMut extends Mutator;
// Acedia's reference to a `Global` object.
var private Global _;
// Responsible for setting up Acedia's game modes in current voting system
var private VotingHandlerAdapter votingAdapter;
var Mutator_OnMutate_Signal onMutateSignal;
var Mutator_OnModifyLogin_Signal onModifyLoginSignal;
var Mutator_OnCheckReplacement_Signal onCheckReplacementSignal;
simulated function PreBeginPlay()
{
local StartUp startUpActor;
_ = class'Global'.static.GetInstance();
if (level.netMode == NM_DedicatedServer)
{
foreach AllActors(class'StartUp', startUpActor)
{
votingAdapter = startUpActor.GetVotingHandlerAdapter();
startUpActor.Destroy();
break;
}
if (votingAdapter != none) {
votingAdapter.InjectIntoVotingHandler();
}
SetupMutatorSignals();
}
else {
class'ClientLevelCore'.static.CreateLevelCore(self);
}
}
function ServerTraveling(string URL, bool bItems)
{
if (votingAdapter != none)
{
votingAdapter.PrepareForServerTravel();
votingAdapter.RestoreVotingHandlerConfigBackup();
_.memory.Free(votingAdapter);
votingAdapter = none;
}
_.environment.ShutDown();
if (nextMutator != none) {
nextMutator.ServerTraveling(URL, bItems);
}
Destroy();
}
// Fetches and sets up signals that `Mutator` needs to provide
private function SetupMutatorSignals()
{
local ServerUnrealService service;
service = ServerUnrealService(class'ServerUnrealService'.static.Require());
onMutateSignal = Mutator_OnMutate_Signal(
service.GetSignal(class'Mutator_OnMutate_Signal'));
onModifyLoginSignal = Mutator_OnModifyLogin_Signal(
service.GetSignal(class'Mutator_OnModifyLogin_Signal'));
onCheckReplacementSignal = Mutator_OnCheckReplacement_Signal(
service.GetSignal(class'Mutator_OnCheckReplacement_Signal'));
}
function bool CheckReplacement(Actor other, out byte isSuperRelevant)
{
if (onCheckReplacementSignal != none) {
return onCheckReplacementSignal.Emit(other, isSuperRelevant);
}
return true;
}
function Mutate(string command, PlayerController sendingController)
{
if (onMutateSignal != none) {
onMutateSignal.Emit(command, sendingController);
}
super.Mutate(command, sendingController);
}
function ModifyLogin(out string portal, out string options)
{
if (onModifyLoginSignal != none) {
onModifyLoginSignal.Emit(portal, options);
}
super.ModifyLogin(portal, options);
}
defaultproperties
{
remoteRole = ROLE_SimulatedProxy
bAlwaysRelevant = true
// Mutator description
GroupName = "Package loader"
FriendlyName = "Acedia loader"
Description = "Launcher for Acedia packages"
}

View file

@ -0,0 +1,449 @@
/**
* Base class for a game mode config, contains all the information Acedia's
* game modes must have, including settings
* (`includeFeature`, `includeFeatureAs` and `excludeFeature`)
* for picking used `Feature`s.
*
* Contains three types of methods:
* 1. Getters for its values;
* 2. `UpdateFeatureArray()` method for updating list of `Feature`s to
* be used based on game info's settings;
* 3. `Report...()` methods that perform various validation checks
* (and log them) on config data.
* Copyright 2021-2023 Anton Tarasenko
*------------------------------------------------------------------------------
* This file is part of Acedia.
*
* Acedia is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3 of the License, or
* (at your option) any later version.
*
* Acedia is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Acedia. If not, see <https://www.gnu.org/licenses/>.
*/
class BaseGameMode extends AcediaConfig
dependson(Packages)
abstract;
// Name of the game mode players will see in voting (formatted string)
var protected config string title;
// Preferable game length (plain string)
var protected config string length;
// Preferable difficulty level (plain string)
var protected config string difficulty;
// `Mutator`s to add with this game mode
var protected config array<string> includeMutator;
// `Feature`s to include (with "default" config)
var protected config array<string> includeFeature;
// `Feature`s to exclude from game mode, regardless of other settings
// (this one has highest priority)
var protected config array<string> excludeFeature;
// Lists of maps to include for this game mode
var protected config array<string> includeMaps;
struct FeatureConfigPair
{
var public string feature;
var public string config;
};
// `Feature`s to include (with specified config).
// Higher priority than `includeFeature`, but lower than `excludeFeature`.
var protected config array<FeatureConfigPair> includeFeatureAs;
var private LoggerAPI.Definition warnBadMutatorName, warnBadFeatureName;
protected function HashTable ToData()
{
local int i;
local HashTable result;
local HashTable nextPair;
local ArrayList nextArray;
result = _.collections.EmptyHashTable();
result.SetFormattedString(P("title"), title);
result.SetString(P("length"), length);
result.SetString(P("difficulty"), difficulty);
nextArray = _.collections.EmptyArrayList();
for (i = 0; i < includeFeature.length; i += 1) {
nextArray.AddString(includeFeature[i]);
}
result.SetItem(P("includeFeature"), nextArray);
_.memory.Free(nextArray);
nextArray = _.collections.EmptyArrayList();
for (i = 0; i < excludeFeature.length; i += 1) {
nextArray.AddString(excludeFeature[i]);
}
result.SetItem(P("excludeFeature"), nextArray);
_.memory.Free(nextArray);
nextArray = _.collections.EmptyArrayList();
for (i = 0; i < includeMutator.length; i += 1) {
nextArray.AddString(includeFeature[i]);
}
result.SetItem(P("includeMutator"), nextArray);
_.memory.Free(nextArray);
nextArray = _.collections.EmptyArrayList();
for (i = 0; i < includeMaps.length; i += 1) {
nextArray.AddString(includeMaps[i]);
}
result.SetItem(P("includeMaps"), nextArray);
_.memory.Free(nextArray);
nextArray = _.collections.EmptyArrayList();
for (i = 0; i < includeFeatureAs.length; i += 1)
{
nextPair = _.collections.EmptyHashTable();
nextPair.SetString(P("feature"), includeFeatureAs[i].feature);
nextPair.SetString(P("config"), includeFeatureAs[i].config);
nextArray.AddItem(nextPair);
_.memory.Free(nextPair);
}
result.SetItem(P("includeFeatureAs"), nextArray);
_.memory.Free(nextArray);
return result;
}
protected function FromData(HashTable source)
{
local int i;
local ArrayList nextArray;
local HashTable nextPair;
if (source == none) {
return;
}
title = source.GetFormattedString(P("title"));
length = source.GetString(P("length"));
difficulty = source.GetString(P("difficulty"));
nextArray = source.GetArrayList(P("includeFeature"));
includeFeature = DynamicIntoStringArray(nextArray);
_.memory.Free(nextArray);
nextArray = source.GetArrayList(P("excludeFeature"));
excludeFeature = DynamicIntoStringArray(nextArray);
_.memory.Free(nextArray);
nextArray = source.GetArrayList(P("includeMutator"));
includeMutator = DynamicIntoStringArray(nextArray);
_.memory.Free(nextArray);
nextArray = source.GetArrayList(P("includeMaps"));
includeMaps = DynamicIntoStringArray(nextArray);
_.memory.Free(nextArray);
nextArray = source.GetArrayList(P("includeFeatureAs"));
if (nextArray == none) {
return;
}
includeFeatureAs.length = 0;
for (i = 0; i < nextArray.GetLength(); i += 1)
{
nextPair = nextArray.GetHashTable(i);
includeFeatureAs[i] = HashTableIntoPair(nextPair);
_.memory.Free(nextPair);
}
_.memory.Free(nextArray);
}
private final function FeatureConfigPair HashTableIntoPair(HashTable source)
{
local Text nextText;
local FeatureConfigPair result;
if (source == none) {
return result;
}
nextText = source.GetText(P("feature"));
if (nextText != none) {
result.feature = nextText.ToString();
}
nextText = source.GetText(P("config"));
if (nextText != none) {
result.config = nextText.ToString();
}
return result;
}
private final function array<string> DynamicIntoStringArray(ArrayList source)
{
local int i;
local Text nextText;
local array<string> result;
if (source == none) {
return result;
}
for (i = 0; i < source.GetLength(); i += 1)
{
nextText = source.GetText(i);
if (nextText != none) {
includeFeature[i] = nextText.ToString();
}
}
}
protected function array<Text> StringToTextArray(array<string> input)
{
local int i;
local array<Text> result;
for (i = 0; i < input.length; i += 1) {
result[i] = _.text.FromString(input[i]);
}
return result;
}
/**
* @return Name of the `GameInfo` class to be used with the caller game mode.
*/
public function Text GetGameTypeClass()
{
return none;
}
/**
* @return Human-readable name of the caller game mode.
* Players will see it as the name of the mode in the voting options.
*/
public function Text GetTitle()
{
return _.text.FromFormattedString(title);
}
/**
* @return Specified game length for the game mode.
* Interpretation of this value can depend on each particular game mode.
*/
public function Text GetLength()
{
return _.text.FromString(length);
}
/**
* @return Specified difficulty for the game mode.
* Interpretation of this value can depend on each particular game mode.
*/
public function Text GetDifficulty()
{
return _.text.FromString(difficulty);
}
/**
* Checks `Feature`-related settings (`includeFeature`, `includeFeatureAs` and
* `excludeFeature`) for correctness and reports any issues.
* Currently correctness check simply ensures that all listed `Feature`s
* actually exist.
*/
public function ReportIncorrectSettings(
array<Packages.FeatureConfigPair> featuresToEnable)
{
local int i;
local array<string> featureNames, featuresToReplace;
for (i = 0; i < featuresToEnable.length; i += 1) {
featureNames[i] = string(featuresToEnable[i].featureClass);
}
ValidateFeatureArray(includeFeature, featureNames, "includeFeatures");
ValidateFeatureArray(excludeFeature, featureNames, "excludeFeatures");
for (i = 0; i < includeFeatureAs.length; i += 1) {
featuresToReplace[i] = includeFeatureAs[i].feature;
}
ValidateFeatureArray(featuresToReplace, featureNames, "includeFeatureAs");
}
/**
* Checks `Mutator`-related settings (`includeMutator`) for correctness and
* reports any issues.
* Currently correctness check performs a simple validity check for mutator,
* to make sure it would not define a new option in server's URL.
*
* See `ValidateServerURLName()` for more information.
*/
public function ReportBadMutatorNames()
{
local int i;
for (i = 0; i < includeMutator.length; i += 1)
{
if (!ValidateServerURLName(includeMutator[i]))
{
_.logger.Auto(warnBadMutatorName)
.Arg(_.text.FromString(includeMutator[i]))
.Arg(_.text.FromString(string(name)));
}
}
}
/**
* Makes sure that a word to be used in server URL as a part of an option
* does not contain "," / "?" / "=" or whitespace.
* This is useful to make sure that user-specified mutator entries only add
* one mutator or option's key / values will not specify only one pair,
* avoiding "?opt1=value1?opt2=value2" entries.
*/
protected function bool ValidateServerURLName(string entry)
{
if (InStr(entry, "=") >= 0) return false;
if (InStr(entry, "?") >= 0) return false;
if (InStr(entry, ",") >= 0) return false;
if (InStr(entry, " ") >= 0) return false;
return true;
}
// Is every element `subset` present inside `whole`?
private function ValidateFeatureArray(
array<string> subset,
array<string> whole,
string arrayName)
{
local int i, j;
local bool foundItem;
for (i = 0; i < subset.length; i += 1)
{
foundItem = false;
for (j = 0; j < whole.length; j += 1)
{
if (subset[i] ~= whole[j])
{
foundItem = true;
break;
}
}
if (!foundItem)
{
_.logger.Auto(warnBadFeatureName)
.Arg(_.text.FromString(includeMutator[i]))
.Arg(_.text.FromString(string(name)))
.Arg(_.text.FromString(arrayName));
}
}
}
/**
* Updates passed `Feature` settings according to this game mode's settings.
*
* @param featuresToEnable Settings to update.
* `FeatureConfigPair` is a pair of `Feature` (`featureClass`) and its
* config's name (`configName`).
* If `configName` is set to `none`, then corresponding `Feature`
* should not be enabled.
* Otherwise it should be enabled with a specified config.
*/
public function UpdateFeatureArray(
out array<Packages.FeatureConfigPair> featuresToEnable)
{
local int i;
local HashTable includedFeaturesMap;
local Text nextKey, nextConfig;
local string nextFeatureClassName;
local CollectionIterator iter;
local Packages.FeatureConfigPair newPair;
// Exclude features we're told to exclude
while (i < featuresToEnable.length)
{
nextFeatureClassName = string(featuresToEnable[i].featureClass);
if (IsFeatureExcluded(nextFeatureClassName))
{
_.memory.Free(featuresToEnable[i].configName);
featuresToEnable.Remove(i, 1);
}
else {
i += 1;
}
}
// Rewrite auto-enabled configs if different config was specified
includedFeaturesMap = BuildIncludedFeaturesMap();
for (i = 0; i < featuresToEnable.length; i += 1)
{
nextKey =
_.text.FromString(Locs(string(featuresToEnable[i].featureClass)));
nextConfig = Text(includedFeaturesMap.TakeItem(nextKey));
if (nextConfig != none)
{
_.memory.Free(featuresToEnable[i].configName);
featuresToEnable[i].configName = nextConfig;
}
nextKey.FreeSelf();
}
// Add features that are included, but weren't auto-enabled in
// the first place
for (iter = includedFeaturesMap.Iterate(); !iter.HasFinished(); iter.Next())
{
nextKey = Text(iter.GetKey());
newPair.featureClass = class<Feature>(_.memory.LoadClass(nextKey));
newPair.configName = Text(iter.Get());
nextKey.FreeSelf();
featuresToEnable[featuresToEnable.length] = newPair;
}
includedFeaturesMap.FreeSelf();
}
private function HashTable BuildIncludedFeaturesMap()
{
local int i;
local Text nextKey;
local HashTable result;
result = _.collections.EmptyHashTable();
// First fill `HashTable` with non-specified conmfigs from `includeFeature`
for (i = 0; i < includeFeature.length; i += 1)
{
nextKey = _.text.FromString(Locs(includeFeature[i]));
result.SetItem(nextKey, none);
nextKey.FreeSelf();
}
// Then add/rewrite configs from `includeFeatureAs`
for (i = 0; i < includeFeatureAs.length; i += 1)
{
nextKey = _.text.FromString(Locs(includeFeatureAs[i].feature));
result.SetString(nextKey, Locs(includeFeatureAs[i].config));
nextKey.FreeSelf();
}
return result;
}
private function bool IsFeatureExcluded(string featureClassName)
{
local int i;
for (i = 0; i < excludeFeature.length; i += 1)
{
if (excludeFeature[i] ~= featureClassName) {
return true;
}
}
return false;
}
public function array<Text> GetIncludedMutators()
{
local int i;
local array<string> validatedMutators;
for (i = 0; i < includeMutator.length; i += 1)
{
if (ValidateServerURLName(includeMutator[i])) {
validatedMutators[validatedMutators.length] = includeMutator[i];
}
}
return StringToTextArray(validatedMutators);
}
public function array<Text> GetIncludedMapLists()
{
return StringToTextArray(includeMaps);
}
public function array<string> GetIncludedMapLists_S()
{
return includeMaps;
}
defaultproperties
{
configName = "AcediaGameModes"
warnBadMutatorName = (l=LOG_Warning,m="Mutator \"%1\" specified for game mode \"%2\" contains invalid characters and will be ignored. This is a configuration error, you should fix it.")
warnBadFeatureName = (l=LOG_Warning,m="Feature \"%1\" specified for game mode \"%2\" in array `%3` does not exist in enabled packages and will be ignored. This is a configuration error, you should fix it.")
}

View file

@ -0,0 +1,266 @@
/**
* The only implementation for `BaseGameMode` suitable for standard
* killing floor game types.
* Copyright 2021-2023 Anton Tarasenko
*------------------------------------------------------------------------------
* This file is part of Acedia.
*
* Acedia is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3 of the License, or
* (at your option) any later version.
*
* Acedia is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Acedia. If not, see <https://www.gnu.org/licenses/>.
*/
class GameMode extends BaseGameMode
perobjectconfig
config(AcediaGameModes);
struct GameOption
{
var public string key;
var public string value;
};
// Allow to specify additional server options for this game mode
var protected config array<GameOption> option;
// Specify `GameInfo`'s class to use, default is "KFMod.KFGameType"
// (plain string)
var protected config string gameTypeClass;
// Short version of the name of the game mode players will see in
// voting handler messages sometimes (plain string)
var protected config string acronym;
// Aliases are an unnecessary overkill for difficulty names, so just define
// them in special `string` arrays.
// We accept not just these exact words, but any of their prefixes.
var private const array<string> beginnerSynonyms;
var private const array<string> normalSynonyms;
var private const array<string> hardSynonyms;
var private const array<string> suicidalSynonyms;
var private const array<string> hoeSynonyms;
var private LoggerAPI.Definition warnBadOption, warnDifficultyOption;
protected function DefaultIt()
{
title = "Acedia game mode";
length = "long";
difficulty = "Hell On Earth";
gameTypeClass = "KFMod.KFGameType";
acronym = "";
includeFeature.length = 0;
excludeFeature.length = 0;
includeMutator.length = 0;
option.length = 0;
}
protected function HashTable ToData()
{
local int i;
local ArrayList nextArray;
local HashTable result, nextPair;
result = super.ToData();
if (result == none) {
return none;
}
result.SetString(P("gameTypeClass"), gameTypeClass);
result.SetString(P("acronym"), acronym);
nextArray = _.collections.EmptyArrayList();
for (i = 0; i < option.length; i += 1)
{
nextPair = _.collections.EmptyHashTable();
nextPair.SetString(P("key"), option[i].key);
nextPair.SetString(P("value"), option[i].value);
nextArray.AddItem(nextPair);
_.memory.Free(nextPair);
}
result.SetItem(P("option"), nextArray);
_.memory.Free(nextArray);
return result;
}
protected function FromData(HashTable source)
{
local int i;
local GameOption nextGameOption;
local ArrayList nextArray;
local HashTable nextPair;
super.FromData(source);
if (source == none) {
return;
}
gameTypeClass = source.GetString(P("gameTypeClass"));
acronym = source.GetString(P("acronym"));
nextArray = source.GetArrayList(P("option"));
if (nextArray == none) {
return;
}
option.length = 0;
for (i = 0; i < nextArray.GetLength(); i += 1)
{
nextPair = HashTable(nextArray.GetItem(i));
if (nextPair == none) {
continue;
}
nextGameOption.key = nextPair.GetString(P("key"));
nextGameOption.value = nextPair.GetString(P("value"));
option[option.length] = nextGameOption;
_.memory.Free(nextPair);
}
_.memory.Free(nextArray);
}
public function Text GetGameTypeClass()
{
if (gameTypeClass == "") {
return P("KFMod.KFGameType").Copy();
}
else {
return _.text.FromString(gameTypeClass);
}
}
public function Text GetAcronym()
{
if (acronym == "") {
return _.text.FromString(string(name));
}
else {
return _.text.FromFormattedString(acronym);
}
}
/**
* Checks option-related settings (`option`) for correctness and reports
* any issues.
* Currently correctness check performs a simple validity check for mutator,
* to make sure it would not define a new option in server's URL.
*
* See `ValidateServerURLName()` in `BaseGameMode` for more information.
*/
public function ReportBadOptions()
{
local int i;
for (i = 0; i < option.length; i += 1)
{
if ( !ValidateServerURLName(option[i].key)
|| !ValidateServerURLName(option[i].value))
{
_.logger.Auto(warnBadOption)
.Arg(_.text.FromString(option[i].key))
.Arg(_.text.FromString(option[i].value))
.Arg(_.text.FromString(string(name)));
}
}
}
/**
* @return Server options as key-value pairs in an `HashTable`.
*/
public function HashTable GetOptions()
{
local int i;
local HashTable result;
local Text nextKey, nextValue;
result = _.collections.EmptyHashTable();
for (i = 0; i < option.length; i += 1)
{
if (!ValidateServerURLName(option[i].key)) continue;
if (!ValidateServerURLName(option[i].value)) continue;
if (option[i].key ~= "difficulty")
{
_.logger.Auto(warnDifficultyOption);
continue;
}
nextKey = _.text.FromString(option[i].key);
nextValue = _.text.FromString(option[i].value);
result.SetItem(nextKey, nextValue);
nextKey.FreeSelf();
nextValue.FreeSelf();
}
// Add difficulty option
nextValue = _.text.FromInt(GetNumericDifficulty());
result.SetItem(P("difficulty"), nextValue);
nextValue.FreeSelf();
return result;
}
// Convert `GameMode`'s difficulty's textual representation into
// KF's numeric one.
private final function int GetNumericDifficulty()
{
local int i;
local string lowerCaseDifficulty;
lowerCaseDifficulty = Locs(_.text.IntoString(GetDifficulty()));
for (i = 0; i < default.beginnerSynonyms.length; i += 1)
{
if (IsPrefixOf(lowerCaseDifficulty, default.beginnerSynonyms[i])) {
return 1;
}
}
for (i = 0; i < default.normalSynonyms.length; i += 1)
{
if (IsPrefixOf(lowerCaseDifficulty, default.normalSynonyms[i])) {
return 2;
}
}
for (i = 0; i < default.hardSynonyms.length; i += 1)
{
if (IsPrefixOf(lowerCaseDifficulty, default.hardSynonyms[i])) {
return 4;
}
}
for (i = 0; i < default.suicidalSynonyms.length; i += 1)
{
if (IsPrefixOf(lowerCaseDifficulty, default.suicidalSynonyms[i])) {
return 5;
}
}
for (i = 0; i < default.hoeSynonyms.length; i += 1)
{
if (IsPrefixOf(lowerCaseDifficulty, default.hoeSynonyms[i])) {
return 7;
}
}
return int(lowerCaseDifficulty);
}
protected final static function bool IsPrefixOf(string prefix, string value)
{
return (InStr(value, prefix) == 0);
}
defaultproperties
{
configName = "AcediaGameModes"
beginnerSynonyms(0) = "easy"
beginnerSynonyms(1) = "beginer"
beginnerSynonyms(2) = "beginner"
beginnerSynonyms(3) = "begginer"
beginnerSynonyms(4) = "begginner"
normalSynonyms(0) = "regular"
normalSynonyms(1) = "default"
normalSynonyms(2) = "normal"
hardSynonyms(0) = "harder" // "hard" is prefix of this, so it will count
hardSynonyms(1) = "difficult"
suicidalSynonyms(0) = "suicidal"
hoeSynonyms(0) = "hellonearth"
hoeSynonyms(1) = "hellon earth"
hoeSynonyms(2) = "hell onearth"
hoeSynonyms(3) = "hoe"
warnBadOption = (l=LOG_Warning,m="Option with key \"%1\" and value \"%2\" specified for game mode \"%3\" contains invalid characters and will be ignored. This is a configuration error, you should fix it.")
warnDifficultyOption = (l=LOG_Warning,m="Option with key \"Difficulty\" is specified. This key reserved and will be ignored. Difficulty value should be set through the game mode's \"Difficulty\" setting in \"AcediaGameModes.ini\" config. This is a configuration error, you should fix it.")
}

View file

@ -0,0 +1,99 @@
/**
* Config class for storing map lists.
* Copyright 2023 Anton Tarasenko
* 2023 Shtoyan
*------------------------------------------------------------------------------
* This file is part of Acedia.
*
* Acedia is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3 of the License, or
* (at your option) any later version.
*
* Acedia is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Acedia. If not, see <https://www.gnu.org/licenses/>.
*/
class MapList extends AcediaConfig
perObjectConfig
config(AcediaMaps);
var public config array<string> map;
protected function HashTable ToData() {
local int i;
local ArrayList commandArray;
local HashTable result;
result = _.collections.EmptyHashTable();
commandArray = _.collections.EmptyArrayList();
for (i = 0; i < map.length; i += 1) {
commandArray.AddString(map[i]);
}
result.SetItem(P("maps"), commandArray);
_.memory.Free(commandArray);
return result;
}
protected function FromData(HashTable source) {
local int i;
local ArrayList commandArray;
if (source == none) {
return;
}
commandArray = source.GetArrayList(P("maps"));
if (commandArray == none) {
return;
}
map.length = 0;
for (i = 0; i < commandArray.GetLength(); i += 1) {
map[map.length] = commandArray.GetString(i);
}
_.memory.Free(commandArray);
}
protected function DefaultIt() {
map.length = 0;
map[0] = "KF-AbusementPark";
map[1] = "KF-Aperture";
map[2] = "KF-Bedlam";
map[3] = "KF-Biohazard";
map[4] = "KF-BioticsLab";
map[5] = "KF-Clandestine";
map[6] = "KF-Crash";
map[7] = "KF-Departed";
map[8] = "KF-EvilSantasLair";
map[9] = "KF-Farm";
map[10] = "KF-FilthsCross";
map[11] = "KF-Forgotten";
map[12] = "KF-Foundry";
map[13] = "KF-FrightYard";
map[14] = "KF-Hell";
map[15] = "KF-Hellride";
map[16] = "KF-HillbillyHorror";
map[17] = "KF-Hospitalhorrors";
map[18] = "KF-Icebreaker";
map[19] = "KF-IceCave";
map[20] = "KF-Manor";
map[21] = "KF-MoonBase";
map[22] = "KF-MountainPass";
map[23] = "KF-Offices";
map[24] = "KF-SirensBelch";
map[25] = "KF-Steamland";
map[26] = "KF-Stronghold";
map[27] = "KF-Suburbia";
map[28] = "KF-ThrillsChills";
map[29] = "KF-Transit";
map[30] = "KF-Waterworks";
map[31] = "KF-WestLondon";
map[32] = "KF-Wyre";
}
defaultproperties {
configName = "AcediaMaps"
}

View file

@ -0,0 +1,362 @@
/**
* Author: Anton Tarasenko
* Home repo: https://insultplayers.ru/git/AcediaFramework/AcediaCore/
* License: GPL
* Copyright 2023 Anton Tarasenko
*------------------------------------------------------------------------------
* This file is part of Acedia.
*
* Acedia is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3 of the License, or
* (at your option) any later version.
*
* Acedia is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Acedia. If not, see <https://www.gnu.org/licenses/>.
*/
class MapTool extends AcediaObject;
//! Tool for adapting AcediaLauncher's map lists for [`xVotingHandler`].
//!
//! This class is responsible for making [`xVotingHandler`] use specific maps (defined in
//! AcediaLauncer's configs) for specific game modes.
//! To achieve that it abuses [`xVotingHandler`]'s ability to filter maps by
//! game mode-specific prefix.
//! Normally prefix filtering for [`xVotingHandler`] is of limited use, because most Killing Floor
//! maps start with the same prefix `KF-` (and some objective ones starting with `KFO-`).
//! However we swap that prefix for something unique for each game mode: `MapSet0-`, `MapSet1-`,
//! etc, allowing us to pick the precise map set we want.
//!
//! There's two main challenges:
//!
//! 1. *Altered map names break voting* - since [`xVotingHandler`] expects to be provided real map
//! names and our mangled ones. We deal with it by catching a map change message broadcasted
//! right before actual map change occurs and swap our names with real ones.
//! 2. *Increased amount of maps to replicate* - if we implement this name mangling by using
//! a naive approach, in which we separately add maps for every game mode, then it will lead to
//! drastic increase in replication time of the complete map list to players.
//! Consider, for example, that you have 10 different game modes with exactly the same maps:
//! we will be needlessly replicating the exact same thing 10 times!
//! To solve this issue we specifically track map lists other game modes use, along with
//! prefixes assigned to them, and reuse already added maps in case two game modes are defined
//! to use the exactly same ones.
/// For storing which map sequences have which prefixes. Storage order is important.
struct MapSequenceRecord {
var public array<string> sequence;
var public string prefix;
};
// To avoid doing excesive work when injecting maps for a second time
var private bool injectedMaps;
// Finding voting handler is not cheap, so only do it once and then store it.
var private NativeActorRef votingHandlerReference;
// Resulting full map list with pseudonim (with replaced prefixes) and real names of maps.
var private array<VotingHandler.MapVoteMapList> pseudonimMapList;
var private array<VotingHandler.MapVoteMapList> realMapList;
var private array<KFVotingHandler.FMapRepType> likesData;
// Map sequences used by game modes we've seen so far.
var private array<MapSequenceRecord> usedMapSequences;
// To more easily detect broadcasted message about map change we replace it with our own that is
// both unlikely to occur and is easy to get voted map name from.
var private string backupMessageMapWon;
var private string backupMessageAdminMapChange;
var private const string ACEDIA_ADMIN_MAP_CHANGE_COMMAND;
var private const string ACEDIA_MAP_WON_COMMAND;
var private LoggerAPI.Definition fatVotingHandlerMissing, warnMissingMapList;
protected function Finalizer() {
_server.unreal.broadcasts.OnHandleText(self).Disconnect();
_.memory.Free(votingHandlerReference);
votingHandlerReference = none;
pseudonimMapList.length = 0;
realMapList.length = 0;
usedMapSequences.length = 0;
injectedMaps = false;
}
/// Initializes [`MapTool`] by associating it with an [`XVotingHandler`].
///
/// Initialization fails if [`initVotingHandlerReference`] doesn't provide reference to
/// [`XVotingHandler`] or caller [`MapTool`] already was initialized.
/// Returns `true` iff initialization was successful.
public final function bool Initialize(NativeActorRef initVotingHandlerReference) {
if (initVotingHandlerReference == none) return false;
if (XVotingHandler(initVotingHandlerReference.Get()) == none) return false;
initVotingHandlerReference.NewRef();
votingHandlerReference = initVotingHandlerReference;
return true;
}
/// Adds map information from the new game mode.
///
/// Returns prefix that given game mode must use to display maps configured for it.
public final function string AddGameMode(GameMode gameMode) {
local XVotingHandler votingHandler;
local string gameModePrefix;
votingHandler = GetVotingHandler();
if (votingHandler == none) {
_.logger.Auto(fatVotingHandlerMissing);
return "KF";
}
if (CheckNeedToLoadMaps(gameMode, gameModePrefix)) {
LoadGameModeMaps(gameMode, gameModePrefix, votingHandler);
}
return gameModePrefix;
}
/// Injects final map list into [`XVotingHandler`].
///
/// Call this after all game modes have been added.
/// Shouldn't be called more than once.
public final function Inject() {
local KFVotingHandler kfHandler;
local XVotingHandler votingHandler;
votingHandler = GetVotingHandler();
if (votingHandler == none) {
_.logger.Auto(fatVotingHandlerMissing);
return;
}
votingHandler.mapList = pseudonimMapList;
votingHandler.mapCount = pseudonimMapList.length;
kfHandler = KFVotingHandler(votingHandler);
if (kfHandler != none) {
kfHandler.repArray = likesData;
}
// Replace map change messages with our commands and make sure it is done only once,
// in case we mess up somewhere else and call this method second time
if (!injectedMaps) {
backupMessageMapWon = votingHandler.lmsgMapWon;
backupMessageAdminMapChange = votingHandler.lmsgAdminMapChange;
votingHandler.lmsgMapWon = ACEDIA_MAP_WON_COMMAND $ "::%mapname%";
votingHandler.lmsgAdminMapChange = ACEDIA_ADMIN_MAP_CHANGE_COMMAND $ "::%mapname%";
_server.unreal.broadcasts.OnHandleText(self).connect = HandleMapChange;
}
injectedMaps = true;
}
/// Builds arrays of [`VotingHandler::MapVoteMapList`] (each such item describes a map +
/// its meta data in a way [`XVotingHandler`] understands).
private function string LoadGameModeMaps(
GameMode gameMode,
string gameModePrefix,
XVotingHandler votingHandler
) {
local int i;
local ArrayList gameModeMaps;
local Text mapNameReal, mapNamePseudonim;
local KFVotingHandler kfHandler;
local KFVotingHandler.FMapRepType nextReputation;
local VotingHandler.MapHistoryInfo nextMapInfo;
local VotingHandler.MapVoteMapList nextRecord;
local array<VotingHandler.MapVoteMapList> newMapsPseudonim, newMapReal;
kfHandler = KFVotingHandler(votingHandler);
nextRecord.bEnabled = true;
gameModeMaps = GetAllGameModeMaps(gameMode);
for (i = 0; i < gameModeMaps.GetLength(); i += 1) {
mapNameReal = gameModeMaps.GetText(i);
mapNamePseudonim = MakeMapPseudonim(mapNameReal, gameModePrefix);
if (votingHandler.history != none) {
nextMapInfo = votingHandler.history.GetMapHistory(mapNameReal.ToString());
nextRecord.playCount = nextMapInfo.p;
nextRecord.sequence = nextMapInfo.s;
}
nextRecord.mapName = _.text.IntoString(mapNamePseudonim);
newMapsPseudonim[newMapsPseudonim.length] = nextRecord;
nextRecord.mapName = _.text.IntoString(mapNameReal);
newMapReal[newMapReal.length] = nextRecord;
if (kfHandler != none) {
class'MVMapRepHistory'.static.GetMapHistoryRep(
nextRecord.mapName,
nextReputation.positive,
nextReputation.negative);
likesData[likesData.length] = nextReputation;
}
}
AppendMapsIntoVotingHandler(newMapsPseudonim, newMapReal);
_.memory.Free(gameModeMaps);
return gameModePrefix;
}
private function bool CheckNeedToLoadMaps(GameMode gameMode, out string prefix) {
local int mapSequenceIndex, mapListIndex;
local bool sameMapList, foundMatch;
local array<string> existingMapSequence, newMapSequence;
local MapSequenceRecord newRecord;
// We don't need to load maps for the `gameMode` only when we've already added the exactly same
// map sequence, order being important
newMapSequence = gameMode.GetIncludedMapLists_S();
for (mapSequenceIndex = 0; mapSequenceIndex < usedMapSequences.length; mapSequenceIndex += 1) {
existingMapSequence = usedMapSequences[mapSequenceIndex].sequence;
if (existingMapSequence.length != newMapSequence.length) {
continue;
}
foundMatch = true;
for (mapListIndex = 0; mapListIndex < newMapSequence.length; mapListIndex += 1) {
// Map lists are ASCII config names, so we can compare them with case-ignoring
// built-in `~=` operator works (it can only handle properly ASCII input)
sameMapList = (existingMapSequence[mapListIndex] ~= newMapSequence[mapListIndex]);
if (!sameMapList) {
foundMatch = false;
break;
}
}
if (foundMatch) {
prefix = usedMapSequences[mapSequenceIndex].prefix;
return false;
}
}
newRecord.sequence = newMapSequence;
newRecord.prefix = "MapSet" $ usedMapSequences.length;
usedMapSequences[usedMapSequences.length] = newRecord;
prefix = newRecord.prefix;
return true;
}
// Replaces prefixes like "KF-", "KFO-" or "KFS-" with "{gameModePrefix}-".
private function Text MakeMapPseudonim(Text realName, string gameModePrefix) {
local Parser parser;
local MutableText prefix, nameBody;
local MutableText result;
result = _.text.FromStringM(gameModePrefix);
result.Append(P("-"));
parser = realName.Parse();
parser.MUntil(prefix, _.text.GetCharacter("-"));
parser.Match(P("-"));
if (parser.Ok()) {
nameBody = parser.GetRemainderM();
result.Append(nameBody);
}
else {
result.Append(realName);
}
_.memory.Free(nameBody);
_.memory.Free(prefix);
_.memory.Free(parser);
return result.IntoText();
}
private function ArrayList GetAllGameModeMaps(GameMode gameMode) {
local int i, j;
local HashTable uniqueMapSet;
local ArrayList result;
local array<Text> usedMapLists;
local array<string> nextMapArray;
local Text nextMapName, lowerMapName;
uniqueMapSet = _.collections.EmptyHashTable(); // for testing map name uniqueness
result = _.collections.EmptyArrayList();
usedMapLists = gameMode.GetIncludedMapLists();
for (i = 0; i < usedMapLists.length; i += 1) {
nextMapArray = GetMapNameFromConfig(usedMapLists[i]);
for (j = 0; j < nextMapArray.length; j += 1) {
nextMapName = _.text.FromString(nextMapArray[j]);
// Use lower case version of map name for uniqueness testing to ignore characters' case
lowerMapName = nextMapName.LowerCopy();
if (!uniqueMapSet.HasKey(lowerMapName)) {
uniqueMapSet.SetItem(lowerMapName, none);
result.AddItem(nextMapName);
}
_.memory.Free(lowerMapName);
_.memory.Free(nextMapName);
}
}
_.memory.Free(uniqueMapSet);
_.memory.FreeMany(usedMapLists);
return result;
}
private function array<string> GetMapNameFromConfig(Text configName) {
local MapList mapConfig;
local array<string> result;
mapConfig = MapList(class'MapList'.static.GetConfigInstance(configName));
if (mapConfig == none) {
_.logger.Auto(warnMissingMapList).Arg(configName.Copy());
} else {
result = mapConfig.map;
_.memory.Free(mapConfig);
}
return result;
}
private function AppendMapsIntoVotingHandler(
array<VotingHandler.MapVoteMapList> newMapsPseudonim,
array<VotingHandler.MapVoteMapList> newMapsReal) {
local int i;
local XVotingHandler votingHandler;
votingHandler = GetVotingHandler();
if (votingHandler == none) {
_.logger.Auto(fatVotingHandlerMissing);
return;
}
for (i = 0; i < newMapsPseudonim.length; i += 1) {
pseudonimMapList[pseudonimMapList.length] = newMapsPseudonim[i];
}
for (i = 0; i < newMapsReal.length; i += 1) {
realMapList[realMapList.length] = newMapsReal[i];
}
}
private function bool HandleMapChange(
Actor sender,
out string message,
name type,
bool teamMessage
) {
local Parser parser;
local XVotingHandler votingHandler;
votingHandler = GetVotingHandler();
if (sender == none) return true;
if (votingHandler != sender) return true;
parser = _.text.ParseString(message);
parser.Match(P(ACEDIA_MAP_WON_COMMAND));
parser.Match(P("::"));
if (parser.Ok()) {
message = Repl(backupMessageMapWon, "%mapname%", parser.GetRemainderS());
} else {
parser.Match(P(ACEDIA_ADMIN_MAP_CHANGE_COMMAND));
parser.Match(P("::"));
if (parser.Ok()) {
message = Repl(backupMessageAdminMapChange, "%mapname%", parser.GetRemainderS());
}
}
if (parser.Ok()) {
votingHandler.mapList = realMapList;
votingHandler.mapCount = realMapList.length;
}
_.memory.Free(parser);
return true;
}
private function XVotingHandler GetVotingHandler() {
if (votingHandlerReference != none) {
return XVotingHandler(votingHandlerReference.Get());
}
return none;
}
defaultproperties {
ACEDIA_ADMIN_MAP_CHANGE_COMMAND = "ACEDIA_LAUNCHER:ADMIN_MAP_CHANGE:DEADBEEF"
ACEDIA_MAP_WON_COMMAND = "ACEDIA_LAUNCHER:MAP_WON:DEADBEEF"
fatVotingHandlerMissing = (l=LOG_Fatal,m="No voting `XVotingHandler` available. This is unexpected at this stage. Report this issue.")
warnMissingMapList = (l=LOG_Warning,m="Cannot find map list `%1`.")
}

View file

@ -0,0 +1,41 @@
/**
* Object for storing launcher's core settings and defining types that will be
* used everywhere in this package.
* Copyright 2022 Anton Tarasenko
*------------------------------------------------------------------------------
* This file is part of Acedia.
*
* Acedia is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3 of the License, or
* (at your option) any later version.
*
* Acedia is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Acedia. If not, see <https://www.gnu.org/licenses/>.
*/
class Packages extends Object
config(AcediaLauncher);
// Load Acedia on the client as well? DO NOT TOUCH THIS
var public config bool clientside;
// Array of predefined services that must be started along with Acedia mutator.
var public config array<string> package;
// Set to `true` to activate Acedia's game modes system
var public config bool useGameModes;
struct FeatureConfigPair
{
var public class<Feature> featureClass;
var public Text configName;
};
defaultproperties
{
clientside = false
useGameModes = false
}

View file

@ -0,0 +1,194 @@
/**
* This actor's role is to perform Acedia's server startup.
* Copyright 2019-2023 Anton Tarasenko
* 2023 Shtoyan
*------------------------------------------------------------------------------
* This file is part of Acedia.
*
* Acedia is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3 of the License, or
* (at your option) any later version.
*
* Acedia is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Acedia. If not, see <https://www.gnu.org/licenses/>.
*/
class StartUp extends Actor
dependson(Packages);
// Acedia's reference to a `Global` object.
var private Global _;
var private ServerGlobal _server;
// Responsible for setting up Acedia's game modes in current voting system
var private VotingHandlerAdapter votingAdapter;
var private LoggerAPI.Definition infoFeatureEnabled;
var private LoggerAPI.Definition errorCannotRunTests;
function PreBeginPlay()
{
super.PreBeginPlay();
InitializeServer();
if (level != none && level.game != none) {
level.game.AddMutator(string(class'AcediaLauncherMut'));
}
}
public function VotingHandlerAdapter GetVotingHandlerAdapter()
{
if (votingAdapter != none) {
votingAdapter.NewRef();
}
return votingAdapter;
}
private function InitializeServer()
{
local int i;
local GameMode currentGameMode;
local array<Packages.FeatureConfigPair> availableFeatures;
if (class'Packages'.default.clientside) {
AddToPackageMap("AcediaLauncher");
}
CheckForGarbage();
// Launch and setup core Acedia
_ = class'Global'.static.GetInstance();
_server = class'ServerGlobal'.static.GetInstance();
class'ServerLevelCore'.static.CreateLevelCore(self);
class'MapList'.static.Initialize();
for (i = 0; i < class'Packages'.default.package.length; i += 1) {
_.environment.RegisterPackage_S(class'Packages'.default.package[i]);
}
if (class'TestingService'.default.runTestsOnStartUp) {
RunStartUpTests();
}
// Determine required features and launch them
availableFeatures = GetAutoConfigurationInfo();
if (class'Packages'.default.useGameModes)
{
class'GameMode'.static.Initialize();
votingAdapter = VotingHandlerAdapter(
_.memory.Allocate(class'VotingHandlerAdapter'));
currentGameMode = votingAdapter.SetupGameModeAfterTravel();
if (currentGameMode != none) {
currentGameMode.UpdateFeatureArray(availableFeatures);
}
}
EnableFeatures(availableFeatures);
}
// Checks whether Acedia has left garbage after the previous map.
// This can lead to serious problems, so such diagnostic check is warranted.
private function CheckForGarbage()
{
local int leftoverObjectAmount;
local int leftoverActorAmount;
local int leftoverDBRAmount;
local AcediaObject nextObject;
local AcediaActor nextActor;
local DBRecord nextRecord;
foreach AllObjects(class'AcediaObject', nextObject) {
leftoverObjectAmount += 1;
}
foreach AllActors(class'AcediaActor', nextActor) {
leftoverActorAmount += 1;
}
foreach AllObjects(class'DBRecord', nextRecord) {
leftoverDBRAmount += 1;
}
if ( leftoverObjectAmount == 0 && leftoverActorAmount == 0
&& leftoverDBRAmount == 0)
{
Log("Acedia garbage check: nothing was found.");
}
else
{
Log("Acedia garbage check: garbage was found." @
"This can cause problems, report it.");
Log("Leftover object:" @ leftoverObjectAmount);
Log("Leftover actors:" @ leftoverActorAmount);
Log("Leftover database records:" @ leftoverDBRAmount);
}
}
public function array<Packages.FeatureConfigPair> GetAutoConfigurationInfo()
{
local int i;
local Text autoConfig;
local array< class<Feature> > availableFeatures;
local Packages.FeatureConfigPair nextPair;
local array<Packages.FeatureConfigPair> result;
availableFeatures = _.environment.GetAvailableFeatures();
for (i = 0; i < availableFeatures.length; i += 1)
{
autoConfig = availableFeatures[i].static.GetAutoEnabledConfig();
if (autoConfig != none)
{
nextPair.featureClass = availableFeatures[i];
nextPair.configName = autoConfig;
result[result.length] = nextPair;
}
}
return result;
}
private function EnableFeatures(array<Packages.FeatureConfigPair> features)
{
local int i;
local Text defaultConfigName;
local Text nextConfigName;
defaultConfigName = _.text.FromString("default");
for (i = 0; i < features.length; i += 1)
{
if (features[i].featureClass == none) {
continue;
}
// `configName` being `none` here means that config name was not
// specified through config and we should fallback to "default"
if (features[i].configName == none) {
nextConfigName = defaultConfigName.Copy();
}
else {
nextConfigName = features[i].configName.Copy();
}
features[i].featureClass.static.EnableMe(nextConfigName);
_.logger.Auto(infoFeatureEnabled)
.Arg(_.text.FromString(string(features[i].featureClass)))
.Arg(nextConfigName); // consumes `nextConfigName`
}
defaultConfigName.FreeSelf();
}
private final function RunStartUpTests()
{
local TestingService testService;
testService = TestingService(class'TestingService'.static.Require());
testService.PrepareTests();
if (testService.filterTestsByName) {
testService.FilterByName(testService.requiredName);
}
if (testService.filterTestsByGroup) {
testService.FilterByGroup(testService.requiredGroup);
}
if (!testService.Run()) {
_.logger.Auto(errorCannotRunTests);
}
}
defaultproperties
{
// This is a server-only actor
remoteRole = ROLE_None
infoFeatureEnabled = (l=LOG_Info,m="Feature `%1` enabled with config \"%2\".")
errorCannotRunTests = (l=LOG_Error,m="Could not perform Acedia's tests.")
}

View file

@ -0,0 +1,380 @@
/**
* Acedia currently lacks its own means to provide a map/mode voting
* (and new voting mod with proper GUI would not be whitelisted anyway).
* This is why this class was made - to inject existing voting handlers with
* data from Acedia's game modes.
* Requires `GameInfo`'s voting handler to be derived from
* `XVotingHandler`, which is satisfied by pretty much every used handler.
* Copyright 2021-2023 Anton Tarasenko
* 2023 Shtoyan
*------------------------------------------------------------------------------
* This file is part of Acedia.
*
* Acedia is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3 of the License, or
* (at your option) any later version.
*
* Acedia is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Acedia. If not, see <https://www.gnu.org/licenses/>.
*/
class VotingHandlerAdapter extends AcediaObject
dependson(VotingHandler)
config(AcediaLauncherData);
/**
* All usage of this object should start with `InjectIntoVotingHandler()`
* method that will read all the `GameMode` configs and fill voting handler's
* config with their data, while making a backup of all values.
* Backup can be restored with `RestoreVotingHandlerConfigBackup()` method.
* How that affects the clients depends on whether restoration was done before,
* during or after the replication. It is intended to be done after
* server travel has started.
* the process of injection is to create an ordered list of game modes
* (`availableGameModes`) and generate appropriate voting handler's configs
* with `BuildVotingHandlerConfig()`, saving them in the same order inside
* the voting handler. Picked game mode is then determined by index of
* the picked voting handler's option.
*
* Additionally this class has a static internal state that allows it to
* transfer data along the server travel - it is used mainly to remember picked
* game mode and enforce game's difficulty by altering and restoring
* `GameInfo`'s variable.
* To make such transfer happen one must call `PrepareForServerTravel()` before
* server travel to set the internal static state and
* then `SetupGameModeAfterTravel()` after travel (when the new map is loading)
* to read (and forget) from internal state.
*/
// All available game modes for Acedia, loaded during initialization.
// This array is directly produces replacement for `XVotingHandler`'s
// `gameConfig` array and records of `availableGameModes` relate to those of
// `gameConfig` with the same index.
// So if we know that a voting option with a certain index was chosen -
// it means that user picked game mode from `availableGameModes` with
// the same index.
var private array<Text> availableGameModes;
// Finding voting handler is not cheap, so only do it once and then store it.
var private NativeActorRef votingHandlerReference;
// Save `VotingHandler`'s config to restore it before server travel - otherwise Acedia will alter
// its config
var private array<VotingHandler.MapVoteGameConfig> backupVotingHandlerConfig;
// Map list management logic
var private MapTool mapTool;
// Setting value of this flag to `true` indicates that map switching just
// occurred and we need to recover some information from the previous map.
var private config bool isServerTraveling;
// We should not rely on "VotingHandler" to inform us from which game mode its
// selected config option originated after server travel, so we need to
// remember it in this config variable before switching maps.
var private config string targetGameMode;
// Acedia's game modes intend on supporting difficulty switching, but
// `KFGameType` does not support appropriate flags, so we enforce default
// difficulty by overwriting default value of its `gameDifficulty` variable.
// But to not affect game's configs we must restore old value after new map is
// loaded. Store it in config variable for that.
var private config int storedGameLength;
// Aliases are an unnecessary overkill for difficulty names, so just define
// them in special `string` arrays.
// We accept not just these exact words, but any of their prefixes.
var private const array<string> shortSynonyms;
var private const array<string> normalSynonyms;
var private const array<string> longSynonyms;
var private LoggerAPI.Definition fatNoXVotingHandler, fatBadGameConfigIndexVH;
var private LoggerAPI.Definition fatBadGameConfigIndexAdapter, warnMissingMapList;
protected function Constructor() {
mapTool = MapTool(_.memory.Allocate(class'MapTool'));
}
protected function Finalizer() {
_.memory.Free(mapTool);
_.memory.Free(votingHandlerReference);
_.memory.FreeMany(availableGameModes);
mapTool = none;
votingHandlerReference = none;
availableGameModes.length = 0;
}
/**
* Replaces `XVotingHandler`'s configs with Acedia's game modes.
* Backup of replaced configs is made internally, so that they can be restored
* on map change.
*/
public final function InjectIntoVotingHandler()
{
local int i;
local string nextGameModePrefix;
local GameMode nextGameMode;
local XVotingHandler votingHandler;
local array<VotingHandler.MapVoteGameConfig> newVotingHandlerConfig;
// `votingHandlerReference != none` means that we've already injected into voting handler
if (votingHandlerReference != none) {
return;
}
votingHandler = XVotingHandler(_server.unreal.FindActorInstance(
_server.unreal.GetGameType().votingHandlerClass));
if (votingHandler == none) {
_.logger.Auto(fatNoXVotingHandler);
return;
}
votingHandlerReference = _server.unreal.ActorRef(votingHandler);
// This cannot actuall fail at this point - we have valid `votingHandler` reference and
// `mapTool` is only initialized here (which can be executed only once)
mapTool.Initialize(votingHandlerReference);
availableGameModes = class'GameMode'.static.AvailableConfigs();
for (i = 0; i < availableGameModes.length; i += 1) {
nextGameMode = GameMode(class'GameMode'.static.GetConfigInstance(availableGameModes[i]));
nextGameModePrefix = mapTool.AddGameMode(nextGameMode);
newVotingHandlerConfig[i] = BuildVotingHandlerConfig(nextGameMode, nextGameModePrefix);
// Setup proper game mode index
if (availableGameModes[i].ToString() == targetGameMode) {
votingHandler.currentGameConfig = i;
}
// Report omitted mutators / server options
nextGameMode.ReportBadMutatorNames();
nextGameMode.ReportBadOptions();
_.memory.Free(nextGameMode);
}
backupVotingHandlerConfig = votingHandler.gameConfig;
votingHandler.gameConfig = newVotingHandlerConfig;
mapTool.Inject();
}
private function VotingHandler.MapVoteGameConfig BuildVotingHandlerConfig(
GameMode gameMode,
string gameModePrefix)
{
local MutableText nextColoredName;
local VotingHandler.MapVoteGameConfig result;
result.gameClass = _.text.IntoString(gameMode.GetGameTypeClass());
result.prefix = gameModePrefix $ "-";
nextColoredName = gameMode
.GetTitle()
.IntoMutableText()
.ChangeDefaultColor(_.color.white);
result.gameName = _.text.IntoColoredString(nextColoredName)
$ _.color.GetColorTag(_.color.White);
nextColoredName = gameMode
.GetAcronym()
.IntoMutableText()
.ChangeDefaultColor(_.color.white);
result.acronym = _.text.IntoColoredString(nextColoredName)
$ _.color.GetColorTag(_.color.White);
result.mutators = BuildMutatorString(gameMode);
result.options = BuildOptionsString(gameMode);
return result;
}
private function string BuildMutatorString(GameMode gameMode)
{
local int i;
local string result;
local array<Text> usedMutators;
usedMutators = gameMode.GetIncludedMutators();
for (i = 0; i < usedMutators.length; i += 1)
{
if (i > 0) {
result $= ",";
}
result $= _.text.IntoString(usedMutators[i]);
}
return result;
}
private function string BuildOptionsString(GameMode gameMode)
{
local bool optionWasAdded;
local string result;
local string nextKey, nextValue;
local CollectionIterator iter;
local HashTable options;
options = gameMode.GetOptions();
for (iter = options.Iterate(); !iter.HasFinished(); iter.Next())
{
nextKey = _.text.IntoString(Text(iter.GetKey()));
nextValue = _.text.IntoString(Text(iter.Get()));
if (optionWasAdded) {
result $= "?";
}
result $= (nextKey $ "=" $ nextValue);
optionWasAdded = true;
}
options.FreeSelf();
iter.FreeSelf();
return result;
}
/**
* Makes necessary preparations for the server travel.
*/
public final function PrepareForServerTravel()
{
local int pickedVHConfig;
local GameMode nextGameMode;
local string nextGameClassName;
local class<GameInfo> nextGameClass;
local class<KFGameType> nextKFGameType;
local XVotingHandler votingHandler;
if (votingHandlerReference == none) return;
votingHandler = XVotingHandler(votingHandlerReference.Get());
if (votingHandler == none) return;
// Server travel caused by something else than `XVotingHandler`
if (!votingHandler.bLevelSwitchPending) return;
pickedVHConfig = votingHandler.currentGameConfig;
if (pickedVHConfig < 0 || pickedVHConfig >= votingHandler.gameConfig.length)
{
_.logger.Auto(fatBadGameConfigIndexVH)
.ArgInt(pickedVHConfig)
.ArgInt(votingHandler.gameConfig.length);
return;
}
if (pickedVHConfig >= availableGameModes.length)
{
_.logger.Auto(fatBadGameConfigIndexAdapter)
.ArgInt(pickedVHConfig)
.ArgInt(availableGameModes.length);
return;
}
nextGameClassName = votingHandler.gameConfig[pickedVHConfig].gameClass;
if (string(_server.unreal.GetGameType().class) ~= nextGameClassName) {
nextGameClass = _server.unreal.GetGameType().class;
}
else
{
nextGameClass =
class<GameInfo>(_.memory.LoadClass_S(nextGameClassName));
}
isServerTraveling = true;
targetGameMode = availableGameModes[pickedVHConfig].ToString();
nextGameMode = GetConfigFromString(targetGameMode);
nextKFGameType = class<KFGameType>(nextGameClass);
if (nextKFGameType != none)
{
storedGameLength = nextKFGameType.default.kfGameLength;
nextKFGameType.default.kfGameLength =
GetNumericGameLength(nextGameMode);
}
nextGameClass.static.StaticSaveConfig();
SaveConfig();
}
/**
* Restore `GameInfo`'s settings after the server travel and
* apply selected `GameMode`.
*
* @return `GameMode` picked before server travel
* (the one that must be running now).
*/
public final function GameMode SetupGameModeAfterTravel()
{
local KFGameType kfGameType;
if (!isServerTraveling) {
return none;
}
kfGameType = _server.unreal.GetKFGameType();
if (kfGameType != none) {
kfGameType.default.kfGameLength = storedGameLength;
}
isServerTraveling = false;
_server.unreal.GetGameType().StaticSaveConfig();
SaveConfig();
return GetConfigFromString(targetGameMode);
}
/**
* Restores `XVotingHandler`'s config to the values that were overridden by
* `VHAdapter`'s `InjectIntoVotingHandler()` method.
*/
public final function RestoreVotingHandlerConfigBackup()
{
local XVotingHandler votingHandler;
if (votingHandlerReference == none) return;
votingHandler = XVotingHandler(votingHandlerReference.Get());
if (votingHandler == none) return;
votingHandler.gameConfig = backupVotingHandlerConfig;
votingHandler.default.gameConfig = backupVotingHandlerConfig;
votingHandler.currentGameConfig = 0;
votingHandler.SaveConfig();
}
// `GameMode`'s name as a `string` -> `GameMode` instance
private function GameMode GetConfigFromString(string configName)
{
local GameMode result;
local Text nextConfigName;
nextConfigName = _.text.FromString(configName);
result = GameMode(class'GameMode'.static.GetConfigInstance(nextConfigName));
_.memory.Free(nextConfigName);
return result;
}
// Convert `GameMode`'s difficulty's textual representation into
// KF's numeric one.
private final function int GetNumericGameLength(BaseGameMode gameMode)
{
local int i;
local string length;
length = Locs(_.text.IntoString(gameMode.GetLength()));
// Custom game is a bad guess for empty game length setting, since it can
// lead to behavior unexpecte by users
if (length == "") {
return 2;
}
for (i = 0; i < default.shortSynonyms.length; i += 1)
{
if (IsPrefixOf(length, default.shortSynonyms[i])) {
return 0;
}
}
for (i = 0; i < default.normalSynonyms.length; i += 1)
{
if (IsPrefixOf(length, default.normalSynonyms[i])) {
return 1;
}
}
for (i = 0; i < default.longSynonyms.length; i += 1)
{
if (IsPrefixOf(length, default.longSynonyms[i])) {
return 2;
}
}
return 3;
}
protected final static function bool IsPrefixOf(string prefix, string value)
{
return (InStr(value, prefix) == 0);
}
defaultproperties
{
shortSynonyms(0) = "short"
normalSynonyms(0) = "normal"
normalSynonyms(1) = "medium"
normalSynonyms(2) = "regular"
longSynonyms(0) = "long"
fatNoXVotingHandler = (l=LOG_Fatal,m="`XVotingHandler` class is missing. Make sure your server setup supports Acedia's game modes (by used voting handler derived from `XVotingHandler`).")
fatBadGameConfigIndexVH = (l=LOG_Fatal,m="`XVotingHandler`'s `currentGameConfig` variable value of %1 is out-of-bounds for `XVotingHandler.gameConfig` of length %2. Report this issue.")
fatBadGameConfigIndexAdapter = (l=LOG_Fatal,m="`XVotingHandler`'s `currentGameConfig` variable value of %1 is out-of-bounds for `VHAdapter` of length %2. Report this issue.")
}

View file

@ -0,0 +1,14 @@
<html>
<head><title>Index of /kf_sources/AcediaLauncher/Classes/</title></head>
<body>
<h1>Index of /kf_sources/AcediaLauncher/Classes/</h1><hr><pre><a href="../">../</a>
<a href="AcediaLauncherMut.uc">AcediaLauncherMut.uc</a> 26-Jan-2025 11:21 3958
<a href="BaseGameMode.uc">BaseGameMode.uc</a> 21-Aug-2023 20:14 15187
<a href="GameMode.uc">GameMode.uc</a> 21-Aug-2023 20:14 8802
<a href="MapList.uc">MapList.uc</a> 21-Aug-2023 20:14 2992
<a href="MapTool.uc">MapTool.uc</a> 23-Aug-2023 20:04 14837
<a href="Packages.uc">Packages.uc</a> 12-Sep-2022 19:27 1526
<a href="StartUp.uc">StartUp.uc</a> 21-Aug-2023 20:14 6835
<a href="VotingHandlerAdapter.uc">VotingHandlerAdapter.uc</a> 23-Aug-2023 19:20 15174
</pre><hr></body>
</html>