RCS0056 - roslynator_max_line_length = 160

This commit is contained in:
RoosterDragon
2024-07-27 16:09:46 +01:00
committed by Matthias Mailänder
parent 9d5d2ab493
commit 0649f3dc32
129 changed files with 606 additions and 245 deletions

View File

@@ -516,9 +516,13 @@ namespace OpenRA.Mods.Common.Activities
sealed class MoveFirstHalf : MovePart
{
public MoveFirstHalf(Move move, WPos from, WPos to, WAngle fromFacing, WAngle toFacing,
public MoveFirstHalf(
Move move, WPos from, WPos to, WAngle fromFacing, WAngle toFacing,
WRot? fromTerrainOrientation, WRot? toTerrainOrientation, int terrainOrientationMargin, int carryoverProgress, bool shouldArc, bool movingOnGroundLayer)
: base(move, from, to, fromFacing, toFacing, fromTerrainOrientation, toTerrainOrientation, terrainOrientationMargin, carryoverProgress, shouldArc, movingOnGroundLayer) { }
: base(
move, from, to, fromFacing, toFacing,
fromTerrainOrientation, toTerrainOrientation, terrainOrientationMargin, carryoverProgress, shouldArc, movingOnGroundLayer)
{ }
bool IsTurn(Actor self, Mobile mobile, CPos nextCell, Map map)
{
@@ -599,9 +603,13 @@ namespace OpenRA.Mods.Common.Activities
sealed class MoveSecondHalf : MovePart
{
public MoveSecondHalf(Move move, WPos from, WPos to, WAngle fromFacing, WAngle toFacing,
public MoveSecondHalf(
Move move, WPos from, WPos to, WAngle fromFacing, WAngle toFacing,
WRot? fromTerrainOrientation, WRot? toTerrainOrientation, int terrainOrientationMargin, int carryoverProgress, bool shouldArc, bool movingOnGroundLayer)
: base(move, from, to, fromFacing, toFacing, fromTerrainOrientation, toTerrainOrientation, terrainOrientationMargin, carryoverProgress, shouldArc, movingOnGroundLayer) { }
: base(
move, from, to, fromFacing, toFacing,
fromTerrainOrientation, toTerrainOrientation, terrainOrientationMargin, carryoverProgress, shouldArc, movingOnGroundLayer)
{ }
protected override MovePart OnComplete(Actor self, Mobile mobile, Move parent)
{

View File

@@ -253,7 +253,14 @@ namespace OpenRA.Mods.Common.FileFormats
WriteSample(DecodeNibble((short)((bytecode >> 4) & 0x0F), bpred[0], ref chanIdelta[0], ref s1[0], ref s2[0]), data);
// Decode the second nibble, for stereo this will be the right channel
WriteSample(DecodeNibble((short)(bytecode & 0x0F), bpred[channelNumber], ref chanIdelta[channelNumber], ref s1[channelNumber], ref s2[channelNumber]), data);
WriteSample(
DecodeNibble(
(short)(bytecode & 0x0F),
bpred[channelNumber],
ref chanIdelta[channelNumber],
ref s1[channelNumber],
ref s2[channelNumber]),
data);
}
return ++currentBlock >= numBlocks;

View File

@@ -36,7 +36,8 @@ namespace OpenRA.Mods.Common.Graphics
IndexedSheetSize = FieldLoader.GetValue<int>("IndexedSheetSize", yaml.Value);
}
public virtual ISpriteSequence CreateSequence(ModData modData, string tileset, SpriteCache cache, string image, string sequence, MiniYaml data, MiniYaml defaults)
public virtual ISpriteSequence CreateSequence(
ModData modData, string tileset, SpriteCache cache, string image, string sequence, MiniYaml data, MiniYaml defaults)
{
return new DefaultSpriteSequence(cache, this, image, sequence, data, defaults);
}
@@ -44,7 +45,8 @@ namespace OpenRA.Mods.Common.Graphics
int ISpriteSequenceLoader.BgraSheetSize => BgraSheetSize;
int ISpriteSequenceLoader.IndexedSheetSize => IndexedSheetSize;
IReadOnlyDictionary<string, ISpriteSequence> ISpriteSequenceLoader.ParseSequences(ModData modData, string tileset, SpriteCache cache, MiniYamlNode imageNode)
IReadOnlyDictionary<string, ISpriteSequence> ISpriteSequenceLoader.ParseSequences(
ModData modData, string tileset, SpriteCache cache, MiniYamlNode imageNode)
{
var sequences = new Dictionary<string, ISpriteSequence>();
var node = imageNode.Value.NodeWithKeyOrDefault("Defaults");
@@ -135,7 +137,9 @@ namespace OpenRA.Mods.Common.Graphics
[Desc("The number of facings that are provided by sprite frames. Use negative values to rotate counter-clockwise.")]
protected static readonly SpriteSequenceField<int> Facings = new(nameof(Facings), 1);
[Desc("The total number of facings for the sequence. If >Facings, the closest facing sprite will be rotated to match. Use negative values to rotate counter-clockwise.")]
[Desc("The total number of facings for the sequence. " +
"If >Facings, the closest facing sprite will be rotated to match. " +
"Use negative values to rotate counter-clockwise.")]
protected static readonly SpriteSequenceField<int?> InterpolatedFacings = new(nameof(InterpolatedFacings), null);
[Desc("Time (in milliseconds at default game speed) to wait until playing the next frame in the animation.")]
@@ -302,7 +306,8 @@ namespace OpenRA.Mods.Common.Graphics
return Rectangle.FromLTRB(left, top, right, bottom);
}
protected static List<int> CalculateFrameIndices(int start, int? length, int stride, int facings, int[] frames, bool transpose, bool reverseFacings, int shadowStart)
protected static List<int> CalculateFrameIndices(
int start, int? length, int stride, int facings, int[] frames, bool transpose, bool reverseFacings, int shadowStart)
{
// Request all frames
if (length == null)
@@ -411,10 +416,17 @@ namespace OpenRA.Mods.Common.Graphics
// Facings must be an integer factor of 1024 (i.e. 1024 / facings is an integer) to allow the frames to be
// mapped uniformly over the full rotation range. This implies that it is a power of 2.
if (facings == 0 || facings > 1024 || !Exts.IsPowerOf2(facings))
throw new YamlException($"{facingsLocation}: {Facings.Key} must be within the (positive or negative) range of 1 to 1024, and a power of 2.");
throw new YamlException(
$"{facingsLocation}: {Facings.Key} must be within the (positive or negative) range of 1 to 1024, and a power of 2.");
if (interpolatedFacings != null && (interpolatedFacings < 2 || interpolatedFacings <= facings || interpolatedFacings > 1024 || !Exts.IsPowerOf2(interpolatedFacings.Value)))
throw new YamlException($"{interpolatedFacingsLocation}: {InterpolatedFacings.Key} must be greater than {Facings.Key}, within the range of 2 to 1024, and a power of 2.");
if (interpolatedFacings != null &&
(interpolatedFacings < 2 ||
interpolatedFacings <= facings ||
interpolatedFacings > 1024 ||
!Exts.IsPowerOf2(interpolatedFacings.Value)))
throw new YamlException(
$"{interpolatedFacingsLocation}: {InterpolatedFacings.Key} must be greater than {Facings.Key}, " +
"within the range of 2 to 1024, and a power of 2.");
if (length != null && length <= 0)
throw new YamlException($"{lengthLocation}: {Length.Key} must be positive.");

View File

@@ -20,7 +20,8 @@ namespace OpenRA.Mods.Common.Graphics
public TilesetSpecificSpriteSequenceLoader(ModData modData)
: base(modData) { }
public override ISpriteSequence CreateSequence(ModData modData, string tileSet, SpriteCache cache, string image, string sequence, MiniYaml data, MiniYaml defaults)
public override ISpriteSequence CreateSequence(
ModData modData, string tileSet, SpriteCache cache, string image, string sequence, MiniYaml data, MiniYaml defaults)
{
return new TilesetSpecificSpriteSequence(cache, this, image, sequence, data, defaults);
}

View File

@@ -48,8 +48,8 @@ namespace OpenRA.Mods.Common.Installer
InstallFromSourceLogic.CopyingFilename,
Translation.Arguments("filename", displayFilename)));
else
onProgress = b => updateMessage(
TranslationProvider.GetString(InstallFromSourceLogic.CopyingFilenameProgress,
onProgress = b => updateMessage(TranslationProvider.GetString(
InstallFromSourceLogic.CopyingFilenameProgress,
Translation.Arguments("filename", displayFilename, "progress", 100 * b / length)));
InstallerUtils.CopyStream(source, target, length, onProgress);

View File

@@ -23,7 +23,9 @@ namespace OpenRA.Mods.Common.Installer
public void RunActionOnSource(MiniYaml actionYaml, string path, ModData modData, List<string> extracted, Action<string> updateMessage)
{
// Yaml path may be specified relative to a named directory (e.g. ^SupportDir) or the detected source path
var sourcePath = actionYaml.Value.StartsWith('^') ? Platform.ResolvePath(actionYaml.Value) : FS.ResolveCaseInsensitivePath(Path.Combine(path, actionYaml.Value));
var sourcePath = actionYaml.Value.StartsWith('^')
? Platform.ResolvePath(actionYaml.Value)
: FS.ResolveCaseInsensitivePath(Path.Combine(path, actionYaml.Value));
using (var source = File.OpenRead(sourcePath))
{

View File

@@ -23,7 +23,9 @@ namespace OpenRA.Mods.Common.Installer
public void RunActionOnSource(MiniYaml actionYaml, string path, ModData modData, List<string> extracted, Action<string> updateMessage)
{
// Yaml path may be specified relative to a named directory (e.g. ^SupportDir) or the detected source path
var sourcePath = actionYaml.Value.StartsWith('^') ? Platform.ResolvePath(actionYaml.Value) : FS.ResolveCaseInsensitivePath(Path.Combine(path, actionYaml.Value));
var sourcePath = actionYaml.Value.StartsWith('^')
? Platform.ResolvePath(actionYaml.Value)
: FS.ResolveCaseInsensitivePath(Path.Combine(path, actionYaml.Value));
var volumeNode = actionYaml.NodeWithKeyOrDefault("Volumes");
if (volumeNode == null)

View File

@@ -23,7 +23,9 @@ namespace OpenRA.Mods.Common.Installer
public void RunActionOnSource(MiniYaml actionYaml, string path, ModData modData, List<string> extracted, Action<string> updateMessage)
{
// Yaml path may be specified relative to a named directory (e.g. ^SupportDir) or the detected source path
var sourcePath = actionYaml.Value.StartsWith('^') ? Platform.ResolvePath(actionYaml.Value) : FS.ResolveCaseInsensitivePath(Path.Combine(path, actionYaml.Value));
var sourcePath = actionYaml.Value.StartsWith('^')
? Platform.ResolvePath(actionYaml.Value)
: FS.ResolveCaseInsensitivePath(Path.Combine(path, actionYaml.Value));
using (var source = File.OpenRead(sourcePath))
{

View File

@@ -22,7 +22,9 @@ namespace OpenRA.Mods.Common.Installer
public void RunActionOnSource(MiniYaml actionYaml, string path, ModData modData, List<string> extracted, Action<string> updateMessage)
{
// Yaml path may be specified relative to a named directory (e.g. ^SupportDir) or the detected source path
var sourcePath = actionYaml.Value.StartsWith('^') ? Platform.ResolvePath(actionYaml.Value) : FS.ResolveCaseInsensitivePath(Path.Combine(path, actionYaml.Value));
var sourcePath = actionYaml.Value.StartsWith('^')
? Platform.ResolvePath(actionYaml.Value)
: FS.ResolveCaseInsensitivePath(Path.Combine(path, actionYaml.Value));
using (var source = File.OpenRead(sourcePath))
{

View File

@@ -49,7 +49,9 @@ namespace OpenRA.Mods.Common.Installer
using (var targetStream = File.OpenWrite(targetPath))
sourceStream.CopyTo(targetStream);
updateMessage(TranslationProvider.GetString(InstallFromSourceLogic.ExtractingProgress, Translation.Arguments("filename", displayFilename, "progress", 100)));
updateMessage(TranslationProvider.GetString(
InstallFromSourceLogic.ExtractingProgress,
Translation.Arguments("filename", displayFilename, "progress", 100)));
extracted.Add(targetPath);
}

View File

@@ -85,16 +85,29 @@ namespace OpenRA.Mods.Common.Installer
}
case PlatformType.OSX:
candidatePaths.Add(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Library", "Application Support", "Steam"));
candidatePaths.Add(Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
"Library",
"Application Support",
"Steam"));
break;
case PlatformType.Linux:
// Direct distro install
candidatePaths.Add(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".steam", "root"));
candidatePaths.Add(Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
".steam",
"root"));
// Flatpak installed via Flathub
candidatePaths.Add(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".var", "app", "com.valvesoftware.Steam", ".steam", "root"));
candidatePaths.Add(Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
".var",
"app",
"com.valvesoftware.Steam",
".steam",
"root"));
break;
}

View File

@@ -64,8 +64,15 @@ namespace OpenRA.Mods.Common.Lint
}
}
static void CheckInner(ModData modData, string[] namedKeys, (string Widget, string Field)[] checkWidgetFields, Dictionary<string, List<string>> customLintMethods,
IEnumerable<MiniYamlNode> nodes, string filename, MiniYamlNode parent, Action<string> emitError)
static void CheckInner(
ModData modData,
string[] namedKeys,
(string Widget, string Field)[] checkWidgetFields,
Dictionary<string, List<string>> customLintMethods,
IEnumerable<MiniYamlNode> nodes,
string filename,
MiniYamlNode parent,
Action<string> emitError)
{
foreach (var node in nodes)
{

View File

@@ -42,7 +42,9 @@ namespace OpenRA.Mods.Common.Lint
if (count == 0)
emitError($"Actor type `{actorInfo.Key}` does not define a default visibility type.");
else if (count > 1)
emitError($"Actor type `{actorInfo.Key}` defines multiple default visibility types: {string.Join(", ", visibilityTypes.Select(vis => vis.GetType().Name))}.");
emitError(
$"Actor type `{actorInfo.Key}` defines multiple default visibility types: " +
$"{string.Join(", ", visibilityTypes.Select(vis => vis.GetType().Name))}.");
else
{
var vis = actorInfo.Value.TraitInfoOrDefault<HiddenUnderShroudInfo>();
@@ -50,9 +52,13 @@ namespace OpenRA.Mods.Common.Lint
{
var ios = actorInfo.Value.TraitInfoOrDefault<IOccupySpaceInfo>();
if (ios == null)
emitError($"Actor type `{actorInfo.Key}` defines VisibilityType.Footprint in `{vis.GetType().Name}` but has no IOccupySpace traits.");
emitError(
$"Actor type `{actorInfo.Key}` defines VisibilityType.Footprint in `{vis.GetType().Name}` " +
"but has no IOccupySpace traits.");
else if (ios.OccupiedCells(actorInfo.Value, CPos.Zero).Count == 0)
emitError($"Actor type `{actorInfo.Key}` defines VisibilityType.Footprint in `{vis.GetType().Name}` but does not have any footprint cells.");
emitError(
$"Actor type `{actorInfo.Key}` defines VisibilityType.Footprint in `{vis.GetType().Name}` " +
"but does not have any footprint cells.");
}
}
}

View File

@@ -38,7 +38,8 @@ namespace OpenRA.Mods.Common.Lint
Run(emitError, emitWarning, map.Players, map.Visibility, map.WorldActorInfo, map.SpawnPoints);
}
static void Run(Action<string> emitError, Action<string> emitWarning, MapPlayers players, MapVisibility visibility, ActorInfo worldActorInfo, CPos[] spawnPoints)
static void Run(Action<string> emitError, Action<string> emitWarning,
MapPlayers players, MapVisibility visibility, ActorInfo worldActorInfo, CPos[] spawnPoints)
{
if (players.Players.Count > 64)
emitError("Defining more than 64 players is not allowed.");

View File

@@ -97,10 +97,13 @@ namespace OpenRA.Mods.Common.Lint
// TODO: Remove prefixed sequence references and instead use explicit lists of lintable references.
if (!sequences.Sequences(i).Any(s => s.StartsWith(sequence, StringComparison.Ordinal)))
emitWarning(
$"Actor type `{actorInfo.Value.Name}` trait `{traitName}` field `{field.Name}` defines a prefix `{sequence}` that does not match any sequences on image `{i}`.");
$"Actor type `{actorInfo.Value.Name}` trait `{traitName}` field `{field.Name}` " +
$"defines a prefix `{sequence}` that does not match any sequences on image `{i}`.");
}
else if (!sequences.HasSequence(i, sequence))
emitError($"Actor type `{actorInfo.Value.Name}` trait `{traitName}` field `{field.Name}` references an undefined sequence `{sequence}` on image `{i}`.");
emitError(
$"Actor type `{actorInfo.Value.Name}` trait `{traitName}` field `{field.Name}` " +
$"references an undefined sequence `{sequence}` on image `{i}`.");
}
}
}
@@ -145,10 +148,14 @@ namespace OpenRA.Mods.Common.Lint
{
// TODO: Remove prefixed sequence references and instead use explicit lists of lintable references.
if (!sequences.Sequences(image).Any(s => s.StartsWith(sequence, StringComparison.Ordinal)))
emitWarning($"Weapon type `{weaponInfo.Key}` projectile field `{field.Name}` defines a prefix `{sequence}` that does not match any sequences on image `{image}`.");
emitWarning(
$"Weapon type `{weaponInfo.Key}` projectile field `{field.Name}` " +
$"defines a prefix `{sequence}` that does not match any sequences on image `{image}`.");
}
else if (!sequences.HasSequence(image, sequence))
emitError($"Weapon type `{weaponInfo.Key}` projectile field `{field.Name}` references an undefined sequence `{sequence}` on image `{image}`.");
emitError(
$"Weapon type `{weaponInfo.Key}` projectile field `{field.Name}` " +
$"references an undefined sequence `{sequence}` on image `{image}`.");
}
}
}

View File

@@ -209,7 +209,9 @@ namespace OpenRA.Mods.Common.Lint
{
var userInterface = typeof(UserInterfaceGlobal).GetCustomAttribute<ScriptGlobalAttribute>().Name;
const string Translate = nameof(UserInterfaceGlobal.Translate);
emitWarning($"{context} calls {userInterface}.{Translate} with key `{key}` and translate args passed as `{variable}`. Inline the args at the callsite for lint analysis.");
emitWarning(
$"{context} calls {userInterface}.{Translate} with key `{key}` and translate args passed as `{variable}`." +
"Inline the args at the callsite for lint analysis.");
}
}
}

View File

@@ -63,7 +63,9 @@ namespace OpenRA.Mods.Common.Lint
"BooleanExpression", "IntegerExpression"
};
throw new InvalidOperationException($"Bad type for reference on `{ruleInfo.GetType().Name}.{fieldInfo.Name}`. Supported types: {supportedTypes.JoinWith(", ")}.");
throw new InvalidOperationException(
$"Bad type for reference on `{ruleInfo.GetType().Name}.{fieldInfo.Name}`. " +
$"Supported types: {supportedTypes.JoinWith(", ")}.");
}
public static IEnumerable<string> GetPropertyValues(object ruleInfo, PropertyInfo propertyInfo,
@@ -108,7 +110,9 @@ namespace OpenRA.Mods.Common.Lint
"BooleanExpression", "IntegerExpression"
};
throw new InvalidOperationException($"Bad type for reference on `{ruleInfo.GetType().Name}.{propertyInfo.Name}`. Supported types: {supportedTypes.JoinWith(", ")}.");
throw new InvalidOperationException(
$"Bad type for reference on `{ruleInfo.GetType().Name}.{propertyInfo.Name}`." +
$"Supported types: {supportedTypes.JoinWith(", ")}.");
}
}
}

View File

@@ -294,7 +294,12 @@ namespace OpenRA.Mods.Common.Orders
{
var isCloseEnough = buildingInfo.IsCloseEnoughToBase(world, world.LocalPlayer, actorInfo, topLeft);
foreach (var t in buildingInfo.Tiles(topLeft))
footprint.Add(t, MakeCellType(isCloseEnough && world.IsCellBuildable(t, actorInfo, buildingInfo) && (resourceLayer == null || resourceLayer.GetResource(t).Type == null)));
footprint.Add(
t,
MakeCellType(
isCloseEnough &&
world.IsCellBuildable(t, actorInfo, buildingInfo) &&
(resourceLayer == null || resourceLayer.GetResource(t).Type == null)));
}
return preview?.Render(wr, topLeft, footprint) ?? Enumerable.Empty<IRenderable>();

View File

@@ -99,7 +99,10 @@ namespace OpenRA.Mods.Common.Orders
public virtual bool InputOverridesSelection(World world, int2 xy, MouseInput mi)
{
var actor = world.ScreenMap.ActorsAtMouse(xy)
.Where(a => !a.Actor.IsDead && a.Actor.Info.HasTraitInfo<ISelectableInfo>() && (a.Actor.Owner.IsAlliedWith(world.RenderPlayer) || !world.FogObscures(a.Actor)))
.Where(a =>
!a.Actor.IsDead &&
a.Actor.Info.HasTraitInfo<ISelectableInfo>() &&
(a.Actor.Owner.IsAlliedWith(world.RenderPlayer) || !world.FogObscures(a.Actor)))
.WithHighestSelectionPriority(xy, mi.Modifiers);
if (actor == null)

View File

@@ -75,7 +75,8 @@ namespace OpenRA.Mods.Common.Projectiles
target = Target.FromPos(args.PassiveTarget);
// Check for blocking actors
if (info.Blockable && BlocksProjectiles.AnyBlockingActorsBetween(world, args.SourceActor.Owner, args.Source, target.CenterPosition, info.Width, out var blockedPos))
if (info.Blockable && BlocksProjectiles.AnyBlockingActorsBetween(
world, args.SourceActor.Owner, args.Source, target.CenterPosition, info.Width, out var blockedPos))
target = Target.FromPos(blockedPos);
var warheadArgs = new WarheadArgs(args)

View File

@@ -45,7 +45,9 @@ namespace OpenRA.Mods.Common.Scripting.Global
using (kv.Value)
{
if (!kv.Key.TryGetClrValue<string>(out var variable) || !kv.Value.TryGetClrValue<object>(out var value))
throw new LuaException($"Translation arguments requires a table of [\"string\"]=value pairs. Received {kv.Key.WrappedClrType().Name},{kv.Value.WrappedClrType().Name}");
throw new LuaException(
"Translation arguments requires a table of [\"string\"]=value pairs. " +
$"Received {kv.Key.WrappedClrType().Name},{kv.Value.WrappedClrType().Name}");
argumentDictionary.Add(variable, value);
}

View File

@@ -165,33 +165,34 @@ namespace OpenRA.Mods.Common.Server
[TranslationReference]
const string VoteKickDisabled = "notification-vote-kick-disabled";
readonly IDictionary<string, Func<S, Connection, Session.Client, string, bool>> commandHandlers = new Dictionary<string, Func<S, Connection, Session.Client, string, bool>>
{
{ "state", State },
{ "startgame", StartGame },
{ "slot", Slot },
{ "allow_spectators", AllowSpectators },
{ "spectate", Specate },
{ "slot_close", SlotClose },
{ "slot_open", SlotOpen },
{ "slot_bot", SlotBot },
{ "map", Map },
{ "option", Option },
{ "reset_options", ResetOptions },
{ "assignteams", AssignTeams },
{ "kick", Kick },
{ "vote_kick", VoteKick },
{ "make_admin", MakeAdmin },
{ "make_spectator", MakeSpectator },
{ "name", Name },
{ "faction", Faction },
{ "team", Team },
{ "handicap", Handicap },
{ "spawn", Spawn },
{ "clear_spawn", ClearPlayerSpawn },
{ "color", PlayerColor },
{ "sync_lobby", SyncLobby }
};
readonly IDictionary<string, Func<S, Connection, Session.Client, string, bool>> commandHandlers =
new Dictionary<string, Func<S, Connection, Session.Client, string, bool>>
{
{ "state", State },
{ "startgame", StartGame },
{ "slot", Slot },
{ "allow_spectators", AllowSpectators },
{ "spectate", Specate },
{ "slot_close", SlotClose },
{ "slot_open", SlotOpen },
{ "slot_bot", SlotBot },
{ "map", Map },
{ "option", Option },
{ "reset_options", ResetOptions },
{ "assignteams", AssignTeams },
{ "kick", Kick },
{ "vote_kick", VoteKick },
{ "make_admin", MakeAdmin },
{ "make_spectator", MakeSpectator },
{ "name", Name },
{ "faction", Faction },
{ "team", Team },
{ "handicap", Handicap },
{ "spawn", Spawn },
{ "clear_spawn", ClearPlayerSpawn },
{ "color", PlayerColor },
{ "sync_lobby", SyncLobby }
};
static bool ValidateSlotCommand(S server, Connection conn, Session.Client client, string arg, bool requiresHost)
{

View File

@@ -50,7 +50,8 @@ namespace OpenRA.Mods.Common.Terrain
if (key < 0 || key >= tileInfo.Length)
throw new YamlException(
$"Tileset `{terrainInfo.Id}` template `{Id}` references frame {key}, but only [0..{tileInfo.Length - 1}] are valid for a {Size.X}x{Size.Y} Size template.");
$"Tileset `{terrainInfo.Id}` template `{Id}` references frame {key}, " +
$"but only [0..{tileInfo.Length - 1}] are valid for a {Size.X}x{Size.Y} Size template.");
tileInfo[key] = LoadTileInfo(terrainInfo, node.Value);
}

View File

@@ -190,12 +190,14 @@ namespace OpenRA.Mods.Common.Traits
yield return new FacingInit(PreviewFacing);
}
public IReadOnlyDictionary<CPos, SubCell> OccupiedCells(ActorInfo info, CPos location, SubCell subCell = SubCell.Any) { return new Dictionary<CPos, SubCell>(); }
public IReadOnlyDictionary<CPos, SubCell> OccupiedCells(ActorInfo info, CPos location, SubCell subCell = SubCell.Any) =>
new Dictionary<CPos, SubCell>();
bool IOccupySpaceInfo.SharesCell => false;
// Used to determine if an aircraft can spawn landed
public bool CanEnterCell(World world, Actor self, CPos cell, SubCell subCell = SubCell.FullCell, Actor ignoreActor = null, BlockedByActor check = BlockedByActor.All)
public bool CanEnterCell(World world, Actor self, CPos cell,
SubCell subCell = SubCell.FullCell, Actor ignoreActor = null, BlockedByActor check = BlockedByActor.All)
{
if (!world.Map.Contains(cell))
return false;

View File

@@ -27,7 +27,9 @@ namespace OpenRA.Mods.Common.Traits
"Strafe: Perform a fixed-length attack run on the target.")]
public readonly AirAttackType AttackType = AirAttackType.Default;
[Desc("Distance the strafing aircraft makes to a target before turning for another pass. When set to WDist.Zero this defaults to the maximum armament range.")]
[Desc(
"Distance the strafing aircraft makes to a target before turning for another pass. " +
"When set to WDist.Zero this defaults to the maximum armament range.")]
public readonly WDist StrafeRunLength = WDist.Zero;
public override object Create(ActorInitializer init) { return new AttackAircraft(init.Self, this); }
@@ -45,7 +47,8 @@ namespace OpenRA.Mods.Common.Traits
aircraftInfo = self.Info.TraitInfo<AircraftInfo>();
}
public override Activity GetAttackActivity(Actor self, AttackSource source, in Target newTarget, bool allowMove, bool forceAttack, Color? targetLineColor = null)
public override Activity GetAttackActivity(
Actor self, AttackSource source, in Target newTarget, bool allowMove, bool forceAttack, Color? targetLineColor = null)
{
return new FlyAttack(self, source, newTarget, forceAttack, targetLineColor);
}

View File

@@ -380,7 +380,10 @@ namespace OpenRA.Mods.Common.Traits
Burst = Weapon.Burst;
if (Weapon.AfterFireSound != null && Weapon.AfterFireSound.Length > 0)
ScheduleDelayedAction(Weapon.AfterFireSoundDelay, Burst, (burst) => Game.Sound.Play(SoundType.World, Weapon.AfterFireSound, self.World, self.CenterPosition));
ScheduleDelayedAction(
Weapon.AfterFireSoundDelay,
Burst,
burst => Game.Sound.Play(SoundType.World, Weapon.AfterFireSound, self.World, self.CenterPosition));
foreach (var nbc in notifyBurstComplete)
nbc.FiredBurst(self, target, this);

View File

@@ -226,7 +226,8 @@ namespace OpenRA.Mods.Common.Traits
return order.OrderString == attackOrderName || order.OrderString == forceAttackOrderName ? Info.Voice : null;
}
public abstract Activity GetAttackActivity(Actor self, AttackSource source, in Target newTarget, bool allowMove, bool forceAttack, Color? targetLineColor = null);
public abstract Activity GetAttackActivity(
Actor self, AttackSource source, in Target newTarget, bool allowMove, bool forceAttack, Color? targetLineColor = null);
public bool HasAnyValidWeapons(in Target t, bool checkForCenterTargetingWeapons = false, bool reloadingIsInvalid = false)
{

View File

@@ -159,7 +159,8 @@ namespace OpenRA.Mods.Common.Traits
base.Tick(self);
}
public override Activity GetAttackActivity(Actor self, AttackSource source, in Target newTarget, bool allowMove, bool forceAttack, Color? targetLineColor = null)
public override Activity GetAttackActivity(
Actor self, AttackSource source, in Target newTarget, bool allowMove, bool forceAttack, Color? targetLineColor = null)
{
// HACK: Manually set force attacking if we persisted an opportunity target that required force attacking
if (opportunityTargetIsPersistentTarget && opportunityForceAttack && newTarget == OpportunityTarget)

View File

@@ -39,7 +39,8 @@ namespace OpenRA.Mods.Common.Traits
return TargetInFiringArc(self, target, Info.FacingTolerance);
}
public override Activity GetAttackActivity(Actor self, AttackSource source, in Target newTarget, bool allowMove, bool forceAttack, Color? targetLineColor = null)
public override Activity GetAttackActivity(
Actor self, AttackSource source, in Target newTarget, bool allowMove, bool forceAttack, Color? targetLineColor = null)
{
return new Activities.Attack(self, newTarget, allowMove, forceAttack, targetLineColor);
}

View File

@@ -26,7 +26,8 @@ namespace OpenRA.Mods.Common.Traits
public AttackOmni(Actor self, AttackOmniInfo info)
: base(self, info) { }
public override Activity GetAttackActivity(Actor self, AttackSource source, in Target newTarget, bool allowMove, bool forceAttack, Color? targetLineColor = null)
public override Activity GetAttackActivity(
Actor self, AttackSource source, in Target newTarget, bool allowMove, bool forceAttack, Color? targetLineColor = null)
{
return new SetTarget(this, newTarget, allowMove, forceAttack, targetLineColor);
}

View File

@@ -100,8 +100,12 @@ namespace OpenRA.Mods.Common.Traits
return;
playerBuildings = world.ActorsHavingTrait<Building>().Where(a => a.Owner == player).ToArray();
var excessPowerBonus = baseBuilder.Info.ExcessPowerIncrement * (playerBuildings.Length / baseBuilder.Info.ExcessPowerIncreaseThreshold.Clamp(1, int.MaxValue));
minimumExcessPower = (baseBuilder.Info.MinimumExcessPower + excessPowerBonus).Clamp(baseBuilder.Info.MinimumExcessPower, baseBuilder.Info.MaximumExcessPower);
var excessPowerBonus =
baseBuilder.Info.ExcessPowerIncrement *
(playerBuildings.Length / baseBuilder.Info.ExcessPowerIncreaseThreshold.Clamp(1, int.MaxValue));
minimumExcessPower =
(baseBuilder.Info.MinimumExcessPower + excessPowerBonus)
.Clamp(baseBuilder.Info.MinimumExcessPower, baseBuilder.Info.MaximumExcessPower);
// PERF: Queue only one actor at a time per category
itemQueuedThisTick = false;
@@ -344,7 +348,9 @@ namespace OpenRA.Mods.Common.Traits
var buildingVariantInfo = actorInfo.TraitInfoOrDefault<PlaceBuildingVariantsInfo>();
var variants = buildingVariantInfo?.Actors ?? Array.Empty<string>();
var count = playerBuildings.Count(a => a.Info.Name == name || variants.Contains(a.Info.Name)) + (baseBuilder.BuildingsBeingProduced.TryGetValue(name, out var num) ? num : 0);
var count = playerBuildings.Count(a =>
a.Info.Name == name || variants.Contains(a.Info.Name)) +
(baseBuilder.BuildingsBeingProduced.TryGetValue(name, out var num) ? num : 0);
// Do we want to build this structure?
if (count * 100 > frac.Value * playerBuildings.Length)

View File

@@ -148,7 +148,8 @@ namespace OpenRA.Mods.Common.Traits
foreach (var minelayer in minelayers)
{
var cells = pathFinder.FindPathToTargetCell(minelayer.Actor, new[] { minelayer.Actor.Location }, enemy.Location, BlockedByActor.Immovable, laneBias: false);
var cells = pathFinder.FindPathToTargetCell(
minelayer.Actor, new[] { minelayer.Actor.Location }, enemy.Location, BlockedByActor.Immovable, laneBias: false);
if (cells != null && cells.Count != 0)
{
AIUtils.BotDebug($"{player}: try find a location to lay mine.");
@@ -192,7 +193,8 @@ namespace OpenRA.Mods.Common.Traits
foreach (var minelayer in minelayers)
{
var cells = pathFinder.FindPathToTargetCell(minelayer.Actor, new[] { minelayer.Actor.Location }, minelayingPosition, BlockedByActor.Immovable, laneBias: false);
var cells = pathFinder.FindPathToTargetCell(
minelayer.Actor, new[] { minelayer.Actor.Location }, minelayingPosition, BlockedByActor.Immovable, laneBias: false);
if (cells != null && cells.Count != 0)
{
orderedActors.Add(minelayer.Actor);

View File

@@ -24,10 +24,16 @@ namespace OpenRA.Mods.Common.Traits
[Desc("What support power does this decision apply to?")]
public readonly string OrderName = "AirstrikePowerInfoOrder";
[Desc("What is the coarse scan radius of this power?", "For finding the general target area, before doing a detail scan", "Should be 10 or more to avoid lag")]
[Desc(
"What is the coarse scan radius of this power?",
"For finding the general target area, before doing a detail scan",
"Should be 10 or more to avoid lag")]
public readonly int CoarseScanRadius = 20;
[Desc("What is the fine scan radius of this power?", "For doing a detailed scan in the general target area.", "Minimum is 1")]
[Desc(
"What is the fine scan radius of this power?",
"For doing a detailed scan in the general target area.",
"Minimum is 1")]
public readonly int FineScanRadius = 2;
[FieldLoader.LoadUsing(nameof(LoadConsiderations))]

View File

@@ -111,7 +111,9 @@ namespace OpenRA.Mods.Common.Traits
waitingPowers[sp] += 10;
// Note: SelectDirectionalTarget uses uint.MaxValue in ExtraData to indicate that the player did not pick a direction.
bot.QueueOrder(new Order(sp.Key, supportPowerManager.Self, Target.FromCell(world, attackLocation.Value), false) { SuppressVisualFeedback = true, ExtraData = uint.MaxValue });
bot.QueueOrder(
new Order(sp.Key, supportPowerManager.Self, Target.FromCell(world, attackLocation.Value), false)
{ SuppressVisualFeedback = true, ExtraData = uint.MaxValue });
}
}

View File

@@ -23,7 +23,8 @@ namespace OpenRA.Mods.Common.Traits
// Reason: If this is less than SquadSize, the bot might get stuck between not producing more units due to this,
// but also not creating squads since there aren't enough idle units.
[Desc("If > 0, only produce units as long as there are less than this amount of units idling inside the base.",
"Beware: if it is less than squad size, e.g. the `SquadSize` from `SquadManagerBotModule`, the bot might get stuck as there aren't enough idle units to create squad.")]
"Beware: if it is less than squad size, e.g. the `SquadSize` from `SquadManagerBotModule`, " +
"the bot might get stuck as there aren't enough idle units to create squad.")]
public readonly int IdleBaseUnitsMaximum = -1;
[Desc("Production queues AI uses for producing units.")]

View File

@@ -140,7 +140,8 @@ namespace OpenRA.Mods.Common.Traits
if (Info.RequiresForceMove && !forceEnter)
return false;
return !IsTraitDisabled && target.TraitsImplementing<DockHost>().Any(host => dockClients.Any(client => client.IsDockingPossible(host.GetDockType)));
return !IsTraitDisabled && target.TraitsImplementing<DockHost>().Any(
host => dockClients.Any(client => client.IsDockingPossible(host.GetDockType)));
}
/// <summary>Clone of <see cref="DockClientManager.DockingPossible(Actor, TargetModifiers)"/>.</summary>
@@ -150,7 +151,8 @@ namespace OpenRA.Mods.Common.Traits
if (Info.RequiresForceMove && !forceEnter)
return false;
return !IsTraitDisabled && target.TraitsImplementing<DockHost>().Any(host => dockClients.Any(client => client.IsDockingPossible(host.GetDockType, forceEnter)));
return !IsTraitDisabled && target.TraitsImplementing<DockHost>().Any(
host => dockClients.Any(client => client.IsDockingPossible(host.GetDockType, forceEnter)));
}
/// <summary>Clone of <see cref="DockClientManager.CanDockAt(Actor, bool, bool)"/>.</summary>
@@ -159,7 +161,8 @@ namespace OpenRA.Mods.Common.Traits
if (!(self.CurrentActivity is Transform || transforms.Any(t => !t.IsTraitDisabled && !t.IsTraitPaused)))
return false;
return !IsTraitDisabled && target.TraitsImplementing<DockHost>().Any(host => dockClients.Any(client => client.CanDockAt(target, host, forceEnter, true)));
return !IsTraitDisabled && target.TraitsImplementing<DockHost>().Any(
host => dockClients.Any(client => client.CanDockAt(target, host, forceEnter, true)));
}
}
}

View File

@@ -411,7 +411,9 @@ namespace OpenRA.Mods.Common.Traits
void INotifyKilled.Killed(Actor self, AttackInfo e)
{
// IsAtGroundLevel contains Map.Contains(self.Location) check.
if (Info.EjectOnDeath && self.IsAtGroundLevel() && (!checkTerrainType || Info.UnloadTerrainTypes.Contains(self.World.Map.GetTerrainInfo(self.Location).Type)))
if (Info.EjectOnDeath &&
self.IsAtGroundLevel() &&
(!checkTerrainType || Info.UnloadTerrainTypes.Contains(self.World.Map.GetTerrainInfo(self.Location).Type)))
{
while (!IsEmpty())
{

View File

@@ -50,7 +50,9 @@ namespace OpenRA.Mods.Common.Traits
[Desc("Measured in game ticks.")]
public readonly int CloakDelay = 30;
[Desc("Events leading to the actor getting uncloaked. Possible values are: Attack, Move, Unload, Infiltrate, Demolish, Dock, Damage, Heal, SelfHeal and SupportPower.",
[Desc(
"Events leading to the actor getting uncloaked. " +
"Possible values are: Attack, Move, Unload, Infiltrate, Demolish, Dock, Damage, Heal, SelfHeal and SupportPower.",
"'Dock' is triggered when docking to a refinery or resupplying.",
"'SupportPower' is triggered when using a support power.")]
public readonly UncloakType UncloakOn = UncloakType.Attack
@@ -108,7 +110,8 @@ namespace OpenRA.Mods.Common.Traits
public override object Create(ActorInitializer init) { return new Cloak(this); }
}
public class Cloak : PausableConditionalTrait<CloakInfo>, IRenderModifier, INotifyDamage, INotifyUnloadCargo, INotifyLoadCargo, INotifyDemolition, INotifyInfiltration,
public class Cloak : PausableConditionalTrait<CloakInfo>,
IRenderModifier, INotifyDamage, INotifyUnloadCargo, INotifyLoadCargo, INotifyDemolition, INotifyInfiltration,
INotifyAttack, ITick, IVisibilityModifier, IRadarColorModifier, INotifyDockClient, INotifySupportPower
{
readonly float3 cloakedColor;

View File

@@ -39,7 +39,8 @@ namespace OpenRA.Mods.Common.Traits
bool IOccupySpaceInfo.SharesCell => false;
public bool CanEnterCell(World world, Actor self, CPos cell, SubCell subCell = SubCell.FullCell, Actor ignoreActor = null, BlockedByActor check = BlockedByActor.All)
public bool CanEnterCell(World world, Actor self, CPos cell,
SubCell subCell = SubCell.FullCell, Actor ignoreActor = null, BlockedByActor check = BlockedByActor.All)
{
// Since crates don't share cells and GetAvailableSubCell only returns SubCell.Full or SubCell.Invalid, we ignore the subCell parameter
return GetAvailableSubCell(world, cell, ignoreActor, check) != SubCell.Invalid;

View File

@@ -45,7 +45,9 @@ namespace OpenRA.Mods.Common.Traits
this.self = self;
this.info = info;
if (info.Units.Length == 0)
throw new YamlException("A GiveUnitCrateAction does not specify any units to give. This might be because the yaml is referring to 'Unit' rather than 'Units'.");
throw new YamlException(
"A GiveUnitCrateAction does not specify any units to give. " +
"This might be because the yaml is referring to 'Unit' rather than 'Units'.");
}
public bool CanGiveTo(Actor collector)

View File

@@ -17,7 +17,8 @@ using OpenRA.Traits;
namespace OpenRA.Mods.Common.Traits
{
[Desc("This actor can grant experience levels equal to it's own current level via entering to other actors with the `" + nameof(AcceptsDeliveredExperience) + "` trait.")]
[Desc("This actor can grant experience levels equal to it's own current level " +
"via entering to other actors with the `" + nameof(AcceptsDeliveredExperience) + "` trait.")]
sealed class DeliversExperienceInfo : TraitInfo, Requires<GainsExperienceInfo>
{
[Desc("The amount of experience the donating player receives.")]

View File

@@ -42,7 +42,9 @@ namespace OpenRA.Mods.Common.Traits
public virtual bool CanDockAt(Actor hostActor, IDockHost host, bool forceEnter = false, bool ignoreOccupancy = false)
{
return (forceEnter || self.Owner.IsAlliedWith(hostActor.Owner)) && IsDockingPossible(host.GetDockType, forceEnter) && host.IsDockingPossible(self, this, ignoreOccupancy);
return (forceEnter || self.Owner.IsAlliedWith(hostActor.Owner)) &&
IsDockingPossible(host.GetDockType, forceEnter) &&
host.IsDockingPossible(self, this, ignoreOccupancy);
}
public virtual void OnDockStarted(Actor self, Actor hostActor, IDockHost host) { }

View File

@@ -240,26 +240,30 @@ namespace OpenRA.Mods.Common.Traits
/// <summary>Does this <paramref name="target"/> contain at least one enabled <see cref="IDockHost"/> with maching <see cref="DockType"/>.</summary>
public bool DockingPossible(Actor target)
{
return !IsTraitDisabled && target.TraitsImplementing<IDockHost>().Any(host => dockClients.Any(client => client.IsDockingPossible(host.GetDockType)));
return !IsTraitDisabled && target.TraitsImplementing<IDockHost>().Any(
host => dockClients.Any(client => client.IsDockingPossible(host.GetDockType)));
}
/// <summary>Does this <paramref name="target"/> contain at least one enabled <see cref="IDockHost"/> with maching <see cref="DockType"/>.</summary>
public bool DockingPossible(Actor target, TargetModifiers modifiers)
{
var forceEnter = modifiers.HasModifier(TargetModifiers.ForceMove);
return !IsTraitDisabled && target.TraitsImplementing<IDockHost>().Any(host => dockClients.Any(client => client.IsDockingPossible(host.GetDockType, forceEnter)));
return !IsTraitDisabled && target.TraitsImplementing<IDockHost>().Any(
host => dockClients.Any(client => client.IsDockingPossible(host.GetDockType, forceEnter)));
}
/// <summary>Can we dock to this <paramref name="host"/>.</summary>
public bool CanDockAt(Actor hostActor, IDockHost host, bool forceEnter = false, bool ignoreOccupancy = false)
{
return !IsTraitDisabled && dockClients.Any(client => client.CanDockAt(hostActor, host, forceEnter, ignoreOccupancy));
return !IsTraitDisabled && dockClients.Any(
client => client.CanDockAt(hostActor, host, forceEnter, ignoreOccupancy));
}
/// <summary>Can we dock to this <paramref name="target"/>.</summary>
public bool CanDockAt(Actor target, bool forceEnter = false, bool ignoreOccupancy = false)
{
return !IsTraitDisabled && target.TraitsImplementing<IDockHost>().Any(host => dockClients.Any(client => client.CanDockAt(target, host, forceEnter, ignoreOccupancy)));
return !IsTraitDisabled && target.TraitsImplementing<IDockHost>().Any(
host => dockClients.Any(client => client.CanDockAt(target, host, forceEnter, ignoreOccupancy)));
}
/// <summary>Find the closest viable <see cref="IDockHost"/>.</summary>
@@ -268,7 +272,9 @@ namespace OpenRA.Mods.Common.Traits
{
var clients = type.IsEmpty ? dockClients : AvailableDockClients(type);
return self.World.ActorsWithTrait<IDockHost>()
.Where(host => host.Trait != ignore && clients.Any(client => client.CanDockAt(host.Actor, host.Trait, forceEnter, ignoreOccupancy)))
.Where(host =>
host.Trait != ignore &&
clients.Any(client => client.CanDockAt(host.Actor, host.Trait, forceEnter, ignoreOccupancy)))
.ClosestDock(self, this);
}

View File

@@ -133,7 +133,8 @@ namespace OpenRA.Mods.Common.Traits
OnDockCompleted(self, dockedClientActor, dockedClient);
}
public virtual bool QueueMoveActivity(Activity moveToDockActivity, Actor self, Actor clientActor, DockClientManager client, MoveCooldownHelper moveCooldownHelper)
public virtual bool QueueMoveActivity(
Activity moveToDockActivity, Actor self, Actor clientActor, DockClientManager client, MoveCooldownHelper moveCooldownHelper)
{
var move = clientActor.Trait<IMove>();

View File

@@ -72,7 +72,8 @@ namespace OpenRA.Mods.Common.Traits
var displayedBounty = GetDisplayedBountyValue(self);
if (Info.ShowBounty && self.IsInWorld && displayedBounty != 0 && e.Attacker.Owner.IsAlliedWith(self.World.RenderPlayer))
e.Attacker.World.AddFrameEndTask(w => w.Add(new FloatingText(self.CenterPosition, e.Attacker.OwnerColor(), FloatingText.FormatCashTick(displayedBounty), 30)));
e.Attacker.World.AddFrameEndTask(
w => w.Add(new FloatingText(self.CenterPosition, e.Attacker.OwnerColor(), FloatingText.FormatCashTick(displayedBounty), 30)));
e.Attacker.Owner.PlayerActor.Trait<PlayerResources>().ChangeCash(GetBountyValue(self));
}

View File

@@ -47,7 +47,8 @@ namespace OpenRA.Mods.Common.Traits
bool IOccupySpaceInfo.SharesCell => false;
public bool CanEnterCell(World world, Actor self, CPos cell, SubCell subCell = SubCell.FullCell, Actor ignoreActor = null, BlockedByActor check = BlockedByActor.All)
public bool CanEnterCell(World world, Actor self, CPos cell,
SubCell subCell = SubCell.FullCell, Actor ignoreActor = null, BlockedByActor check = BlockedByActor.All)
{
// IPositionable*Info*.CanEnterCell is only ever used for things like exiting production facilities,
// all places relevant for husks check IPositionable.CanEnterCell instead, so we can safely set this to true.

View File

@@ -127,7 +127,8 @@ namespace OpenRA.Mods.Common.Traits
/// <summary>
/// Note: If the target <paramref name="cell"/> has any free subcell, the value of <paramref name="subCell"/> is ignored.
/// </summary>
public bool CanEnterCell(World world, Actor self, CPos cell, SubCell subCell = SubCell.FullCell, Actor ignoreActor = null, BlockedByActor check = BlockedByActor.All)
public bool CanEnterCell(World world, Actor self, CPos cell,
SubCell subCell = SubCell.FullCell, Actor ignoreActor = null, BlockedByActor check = BlockedByActor.All)
{
// PERF: Avoid repeated trait queries on the hot path
locomotor ??= world.WorldActor.TraitsImplementing<Locomotor>()

View File

@@ -26,7 +26,8 @@ namespace OpenRA.Mods.Common.Traits
public override object Create(ActorInitializer init) { return new FrozenUnderFog(init, this); }
}
public class FrozenUnderFog : ICreatesFrozenActors, IRenderModifier, IDefaultVisibility, ITickRender, ISync, INotifyCreated, INotifyOwnerChanged, INotifyActorDisposing
public class FrozenUnderFog : ICreatesFrozenActors, IRenderModifier, IDefaultVisibility,
ITickRender, ISync, INotifyCreated, INotifyOwnerChanged, INotifyActorDisposing
{
[Sync]
public int VisibilityHash;

View File

@@ -63,7 +63,9 @@ namespace OpenRA.Mods.Common.Traits
ImmutablePalette pal;
if (info.PlayerIndex.TryGetValue(playerName, out var remap))
pal = new ImmutablePalette(basePalette, new IndexedColorRemap(basePalette, info.RemapIndex.Length == 0 ? Enumerable.Range(0, 256).ToArray() : info.RemapIndex, remap));
pal = new ImmutablePalette(
basePalette,
new IndexedColorRemap(basePalette, info.RemapIndex.Length == 0 ? Enumerable.Range(0, 256).ToArray() : info.RemapIndex, remap));
else
pal = new ImmutablePalette(basePalette);

View File

@@ -61,7 +61,8 @@ namespace OpenRA.Mods.Common.Traits
public override object Create(ActorInitializer init) { return new Passenger(this); }
}
public class Passenger : IIssueOrder, IResolveOrder, IOrderVoice, INotifyRemovedFromWorld, INotifyEnteredCargo, INotifyExitedCargo, INotifyKilled, IObservesVariables
public class Passenger : IIssueOrder, IResolveOrder, IOrderVoice,
INotifyRemovedFromWorld, INotifyEnteredCargo, INotifyExitedCargo, INotifyKilled, IObservesVariables
{
public readonly PassengerInfo Info;
public Actor Transport;

View File

@@ -66,7 +66,8 @@ namespace OpenRA.Mods.Common.Traits
IEnumerable<LobbyOption> ILobbyOptions.LobbyOptions(MapPreview map)
{
yield return new LobbyBooleanOption(map, "cheats", CheckboxLabel, CheckboxDescription, CheckboxVisible, CheckboxDisplayOrder, CheckboxEnabled, CheckboxLocked);
yield return new LobbyBooleanOption(map, "cheats",
CheckboxLabel, CheckboxDescription, CheckboxVisible, CheckboxDisplayOrder, CheckboxEnabled, CheckboxLocked);
}
public override object Create(ActorInitializer init) { return new DeveloperMode(this); }

View File

@@ -28,7 +28,8 @@ namespace OpenRA.Mods.Common.Traits
[Desc("Human-readable name this bot uses.")]
public readonly string Name = "Unnamed Bot";
[Desc("Minimum portion of pending orders to issue each tick (e.g. 5 issues at least 1/5th of all pending orders). Excess orders remain queued for subsequent ticks.")]
[Desc("Minimum portion of pending orders to issue each tick (e.g. 5 issues at least 1/5th of all pending orders). " +
"Excess orders remain queued for subsequent ticks.")]
public readonly int MinOrderQuotientPerTick = 5;
string IBotInfo.Type => Type;

View File

@@ -66,7 +66,8 @@ namespace OpenRA.Mods.Common.Traits
var startingCash = SelectableCash.ToDictionary(c => c.ToStringInvariant(), c => "$" + c.ToString(NumberFormatInfo.CurrentInfo));
if (startingCash.Count > 0)
yield return new LobbyOption(map, "startingcash", DefaultCashDropdownLabel, DefaultCashDropdownDescription, DefaultCashDropdownVisible, DefaultCashDropdownDisplayOrder,
yield return new LobbyOption(map, "startingcash",
DefaultCashDropdownLabel, DefaultCashDropdownDescription, DefaultCashDropdownVisible, DefaultCashDropdownDisplayOrder,
startingCash, DefaultCash.ToStringInvariant(), DefaultCashDropdownLocked);
}

View File

@@ -41,7 +41,8 @@ namespace OpenRA.Mods.Common.Traits
{
var pci = rules.Actors[SystemActors.Player].TraitInfoOrDefault<ProximityCaptorInfo>();
if (pci == null)
throw new YamlException(nameof(ProximityCapturableBase) + " requires the `" + nameof(Player) + "` actor to have the " + nameof(ProximityCaptor) + " trait.");
throw new YamlException(
nameof(ProximityCapturableBase) + " requires the `" + nameof(Player) + "` actor to have the " + nameof(ProximityCaptor) + " trait.");
}
public abstract override object Create(ActorInitializer init);

View File

@@ -182,7 +182,10 @@ namespace OpenRA.Mods.Common.Traits.Render
var palette = wr.Palette(info.Palette);
var alpha = shadow.CurrentSequence.GetAlpha(shadow.CurrentFrame);
var tintModifiers = shadow.CurrentSequence.IgnoreWorldTint ? TintModifiers.ReplaceColor | TintModifiers.IgnoreWorldTint : TintModifiers.ReplaceColor;
return new IRenderable[] { new SpriteRenderable(shadow.Image, pos, info.ShadowOffset, info.ShadowZOffset, palette, 1, shadowAlpha * alpha, shadowColor, tintModifiers, true) };
return new IRenderable[]
{
new SpriteRenderable(shadow.Image, pos, info.ShadowOffset, info.ShadowZOffset, palette, 1, shadowAlpha * alpha, shadowColor, tintModifiers, true)
};
}
IEnumerable<Rectangle> IRender.ScreenBounds(Actor self, WorldRenderer wr)

View File

@@ -18,7 +18,8 @@ using OpenRA.Traits;
namespace OpenRA.Mods.Common.Traits.Render
{
[Desc("Renders a decorative animation on units and buildings. Overlay switching controlled by " + nameof(PauseOnCondition) + ".")]
public class WithSwitchableOverlayInfo : PausableConditionalTraitInfo, IRenderActorPreviewSpritesInfo, Requires<RenderSpritesInfo>, Requires<BodyOrientationInfo>
public class WithSwitchableOverlayInfo : PausableConditionalTraitInfo,
IRenderActorPreviewSpritesInfo, Requires<RenderSpritesInfo>, Requires<BodyOrientationInfo>
{
[Desc("Image used for this decoration. Defaults to the actor's type.")]
public readonly string Image = null;
@@ -123,7 +124,11 @@ namespace OpenRA.Mods.Common.Traits.Render
var facing = self.TraitOrDefault<IFacing>();
var image = info.Image ?? rs.GetImage(self);
overlay = new Animation(self.World, image, facing == null ? () => WAngle.Zero : (body == null ? () => facing.Facing : () => body.QuantizeFacing(facing.Facing)), () => false)
overlay = new Animation(
self.World,
image,
facing == null ? () => WAngle.Zero : (body == null ? () => facing.Facing : () => body.QuantizeFacing(facing.Facing)),
() => false)
{
IsDecoration = info.IsDecoration
};

View File

@@ -111,7 +111,9 @@ namespace OpenRA.Mods.Common.Traits
else
return;
self.QueueActivity(order.Queued, new RepairBridge(self, order.Target, info.EnterBehaviour, info.RepairNotification, info.RepairTextNotification, info.TargetLineColor));
self.QueueActivity(
order.Queued,
new RepairBridge(self, order.Target, info.EnterBehaviour, info.RepairNotification, info.RepairTextNotification, info.TargetLineColor));
self.ShowTargetLines();
}
}

View File

@@ -81,7 +81,8 @@ namespace OpenRA.Mods.Common.Traits
IEnumerable<LobbyOption> ILobbyOptions.LobbyOptions(MapPreview map)
{
yield return new LobbyBooleanOption(map, "crates", CheckboxLabel, CheckboxDescription, CheckboxVisible, CheckboxDisplayOrder, CheckboxEnabled, CheckboxLocked);
yield return new LobbyBooleanOption(map, "crates",
CheckboxLabel, CheckboxDescription, CheckboxVisible, CheckboxDisplayOrder, CheckboxEnabled, CheckboxLocked);
}
public override object Create(ActorInitializer init) { return new CrateSpawner(init.Self, this); }

View File

@@ -206,7 +206,8 @@ namespace OpenRA.Mods.Common.Traits
return terrainInfos[index].Speed;
}
public short MovementCostToEnterCell(Actor actor, CPos destNode, BlockedByActor check, Actor ignoreActor, bool ignoreSelf = false, SubCell subCell = SubCell.FullCell)
public short MovementCostToEnterCell(
Actor actor, CPos destNode, BlockedByActor check, Actor ignoreActor, bool ignoreSelf = false, SubCell subCell = SubCell.FullCell)
{
var cellCost = MovementCostForCell(destNode);
@@ -217,7 +218,8 @@ namespace OpenRA.Mods.Common.Traits
return cellCost;
}
public short MovementCostToEnterCell(Actor actor, CPos srcNode, CPos destNode, BlockedByActor check, Actor ignoreActor, bool ignoreSelf = false)
public short MovementCostToEnterCell(
Actor actor, CPos srcNode, CPos destNode, BlockedByActor check, Actor ignoreActor, bool ignoreSelf = false)
{
var cellCost = MovementCostForCell(destNode, srcNode);

View File

@@ -40,7 +40,8 @@ namespace OpenRA.Mods.Common.Traits
IEnumerable<LobbyOption> ILobbyOptions.LobbyOptions(MapPreview map)
{
yield return new LobbyBooleanOption(map, "creeps", CheckboxLabel, CheckboxDescription, CheckboxVisible, CheckboxDisplayOrder, CheckboxEnabled, CheckboxLocked);
yield return new LobbyBooleanOption(map, "creeps",
CheckboxLabel, CheckboxDescription, CheckboxVisible, CheckboxDisplayOrder, CheckboxEnabled, CheckboxLocked);
}
public override object Create(ActorInitializer init) { return new MapCreeps(this); }

View File

@@ -81,14 +81,16 @@ namespace OpenRA.Mods.Common.Traits
IEnumerable<LobbyOption> ILobbyOptions.LobbyOptions(MapPreview map)
{
yield return new LobbyBooleanOption(map, "shortgame", ShortGameCheckboxLabel, ShortGameCheckboxDescription,
yield return new LobbyBooleanOption(map, "shortgame",
ShortGameCheckboxLabel, ShortGameCheckboxDescription,
ShortGameCheckboxVisible, ShortGameCheckboxDisplayOrder, ShortGameCheckboxEnabled, ShortGameCheckboxLocked);
var techLevels = map.PlayerActorInfo.TraitInfos<ProvidesTechPrerequisiteInfo>()
.ToDictionary(t => t.Id, t => map.GetLocalisedString(t.Name));
if (techLevels.Count > 0)
yield return new LobbyOption(map, "techlevel", TechLevelDropdownLabel, TechLevelDropdownDescription, TechLevelDropdownVisible, TechLevelDropdownDisplayOrder,
yield return new LobbyOption(map, "techlevel",
TechLevelDropdownLabel, TechLevelDropdownDescription, TechLevelDropdownVisible, TechLevelDropdownDisplayOrder,
techLevels, TechLevel, TechLevelDropdownLocked);
var gameSpeeds = Game.ModData.Manifest.Get<GameSpeeds>();

View File

@@ -95,7 +95,8 @@ namespace OpenRA.Mods.Common.Traits
case TargetType.Terrain:
{
world.AddFrameEndTask(w => w.Add(new SpriteAnnotation(target.CenterPosition, world, info.TerrainFlashImage, info.TerrainFlashSequence, info.TerrainFlashPalette)));
world.AddFrameEndTask(w => w.Add(new SpriteAnnotation(
target.CenterPosition, world, info.TerrainFlashImage, info.TerrainFlashSequence, info.TerrainFlashPalette)));
return true;
}

View File

@@ -19,7 +19,8 @@ using OpenRA.Traits;
namespace OpenRA.Mods.Common.Traits
{
[TraitLocation(SystemActors.World)]
[Desc("Spawn base actor at the spawnpoint and support units in an annulus around the base actor. Both are defined at MPStartUnits. Attach this to the world actor.")]
[Desc("Spawn base actor at the spawnpoint and support units in an annulus around the base actor. " +
"Both are defined at MPStartUnits. Attach this to the world actor.")]
public class SpawnStartingUnitsInfo : TraitInfo, Requires<StartingUnitsInfo>, NotBefore<LocomotorInfo>, ILobbyOptions
{
public readonly string StartingUnitsClass = "none";

View File

@@ -377,7 +377,8 @@ namespace OpenRA.Mods.Common.Traits
Color[] PresetColors { get; }
Color RandomPresetColor(MersenneTwister random, IReadOnlyCollection<Color> terrainColors, IReadOnlyCollection<Color> playerColors);
Color RandomValidColor(MersenneTwister random, IReadOnlyCollection<Color> terrainColors, IReadOnlyCollection<Color> playerColors);
Color MakeValid(Color color, MersenneTwister random, IReadOnlyCollection<Color> terrainColors, IReadOnlyCollection<Color> playerColors, Action<string> onError = null);
Color MakeValid(
Color color, MersenneTwister random, IReadOnlyCollection<Color> terrainColors, IReadOnlyCollection<Color> playerColors, Action<string> onError = null);
void ShowColorDropDown(DropDownButtonWidget dropdownButton, Color initialColor, string initialFaction, WorldRenderer worldRenderer, Action<Color> onExit);
}
@@ -876,7 +877,8 @@ namespace OpenRA.Mods.Common.Traits
public interface IPositionableInfo : IOccupySpaceInfo
{
bool CanEnterCell(World world, Actor self, CPos cell, SubCell subCell = SubCell.FullCell, Actor ignoreActor = null, BlockedByActor check = BlockedByActor.All);
bool CanEnterCell(World world, Actor self, CPos cell,
SubCell subCell = SubCell.FullCell, Actor ignoreActor = null, BlockedByActor check = BlockedByActor.All);
}
public interface IPositionable : IOccupySpace
@@ -885,7 +887,8 @@ namespace OpenRA.Mods.Common.Traits
bool IsLeavingCell(CPos location, SubCell subCell = SubCell.Any);
bool CanEnterCell(CPos location, Actor ignoreActor = null, BlockedByActor check = BlockedByActor.All);
SubCell GetValidSubCell(SubCell preferred = SubCell.Any);
SubCell GetAvailableSubCell(CPos location, SubCell preferredSubCell = SubCell.Any, Actor ignoreActor = null, BlockedByActor check = BlockedByActor.All);
SubCell GetAvailableSubCell(CPos location,
SubCell preferredSubCell = SubCell.Any, Actor ignoreActor = null, BlockedByActor check = BlockedByActor.All);
void SetPosition(Actor self, CPos cell, SubCell subCell = SubCell.Any);
void SetPosition(Actor self, WPos pos);
void SetCenterPosition(Actor self, WPos pos);

View File

@@ -17,7 +17,9 @@ namespace OpenRA.Mods.Common.UpdateRules.Rules
{
public override string Name => "Adds the old default value for AttackFrontal's FacingTolerance.";
public override string Description => "The tolerance for the attack angle was defined twice on AttackFrontal. This override has to be defined in the rules now.";
public override string Description =>
"The tolerance for the attack angle was defined twice on AttackFrontal. " +
"This override has to be defined in the rules now.";
public override IEnumerable<string> UpdateActorNode(ModData modData, MiniYamlNodeBuilder actorNode)
{

View File

@@ -17,7 +17,9 @@ namespace OpenRA.Mods.Common.UpdateRules.Rules
{
public override string Name => "HarvesterResourceMultiplier and RefineryResourceMultiplier replaced with ResourceValueMultiplier.";
public override string Description => "The HarvesterResourceMultiplier trait has been removed, and the RefineryResourceMultiplier trait renamed to ResourceValueMultiplier.";
public override string Description =>
"The HarvesterResourceMultiplier trait has been removed, " +
"and the RefineryResourceMultiplier trait renamed to ResourceValueMultiplier.";
bool notified;
public override IEnumerable<string> UpdateActorNode(ModData modData, MiniYamlNodeBuilder actorNode)

View File

@@ -17,7 +17,9 @@ namespace OpenRA.Mods.Common.UpdateRules.Rules
{
public override string Name => "Removes PlayerExperience property from Infiltrates.";
public override string Description => "Infiltrates property PlayerExperience was removed, it was replaced by adding PlayerExperience to all InfiltrateFor* Traits.";
public override string Description =>
"Infiltrates property PlayerExperience was removed, " +
"it was replaced by adding PlayerExperience to all InfiltrateFor* Traits.";
readonly List<string> locations = new();

View File

@@ -35,7 +35,12 @@ namespace OpenRA.Mods.Common.UpdateRules
continue;
}
yaml.Add(((IReadWritePackage)package, name, MiniYaml.FromStream(package.GetStream(name), $"{package.Name}:{name}", false).ConvertAll(n => new MiniYamlNodeBuilder(n))));
yaml.Add(
((IReadWritePackage)package,
name,
MiniYaml
.FromStream(package.GetStream(name), $"{package.Name}:{name}", false)
.ConvertAll(n => new MiniYamlNodeBuilder(n))));
}
return yaml;
@@ -68,7 +73,12 @@ namespace OpenRA.Mods.Common.UpdateRules
{
// Ignore any files that aren't in the map bundle
if (!filename.Contains('|') && mapPackage.Contains(filename))
fileSet.Add((mapPackage, filename, MiniYaml.FromStream(mapPackage.GetStream(filename), $"{mapPackage.Name}:{filename}", false).ConvertAll(n => new MiniYamlNodeBuilder(n))));
fileSet.Add((
mapPackage,
filename,
MiniYaml
.FromStream(mapPackage.GetStream(filename), $"{mapPackage.Name}:{filename}", false)
.ConvertAll(n => new MiniYamlNodeBuilder(n))));
else if (modData.ModFiles.Exists(filename))
externalFilenames.Add(filename);
}
@@ -159,7 +169,8 @@ namespace OpenRA.Mods.Common.UpdateRules
return manualSteps;
}
public static List<MiniYamlNodeBuilder> LoadMapYaml(IReadOnlyFileSystem fileSystem, IReadOnlyPackage mapPackage, IEnumerable<string> files, MiniYamlBuilder mapNode)
public static List<MiniYamlNodeBuilder> LoadMapYaml(
IReadOnlyFileSystem fileSystem, IReadOnlyPackage mapPackage, IEnumerable<string> files, MiniYamlBuilder mapNode)
{
var yaml = files.Select(s => MiniYaml.FromStream(fileSystem.Open(s), s)).ToList();
@@ -357,7 +368,8 @@ namespace OpenRA.Mods.Common.UpdateRules
}
/// <summary>Renames a yaml key preserving any @suffix.</summary>
public static void RenameKey(this MiniYamlNodeBuilder node, string newKey, bool preserveSuffix = true, bool includeRemovals = true)
public static void RenameKey(
this MiniYamlNodeBuilder node, string newKey, bool preserveSuffix = true, bool includeRemovals = true)
{
var prefix = includeRemovals && node.IsRemoval() ? "-" : "";
var split = node.Key.IndexOf('@');
@@ -398,7 +410,8 @@ namespace OpenRA.Mods.Common.UpdateRules
fromNode.Value.Nodes.Remove(node);
}
public static void MoveAndRenameNode(this MiniYamlNodeBuilder node,
public static void MoveAndRenameNode(
this MiniYamlNodeBuilder node,
MiniYamlNodeBuilder fromNode, MiniYamlNodeBuilder toNode, string newKey, bool preserveSuffix = true, bool includeRemovals = true)
{
node.RenameKey(newKey, preserveSuffix, includeRemovals);
@@ -406,13 +419,15 @@ namespace OpenRA.Mods.Common.UpdateRules
}
/// <summary>Removes children with keys equal to [match] or [match]@[arbitrary suffix].</summary>
public static int RemoveNodes(this MiniYamlNodeBuilder node, string match, bool ignoreSuffix = true, bool includeRemovals = true)
public static int RemoveNodes(
this MiniYamlNodeBuilder node, string match, bool ignoreSuffix = true, bool includeRemovals = true)
{
return node.Value.Nodes.RemoveAll(n => n.KeyMatches(match, ignoreSuffix, includeRemovals));
}
/// <summary>Returns true if the node is of the form [match] or [match]@[arbitrary suffix].</summary>
public static bool KeyMatches(this MiniYamlNodeBuilder node, string match, bool ignoreSuffix = true, bool includeRemovals = true)
public static bool KeyMatches(
this MiniYamlNodeBuilder node, string match, bool ignoreSuffix = true, bool includeRemovals = true)
{
if (node.Key == null)
return false;
@@ -430,7 +445,8 @@ namespace OpenRA.Mods.Common.UpdateRules
}
/// <summary>Returns true if the node is of the form [match], [match]@[arbitrary suffix] or [arbitrary suffix]@[match].</summary>
public static bool KeyContains(this MiniYamlNodeBuilder node, string match, bool ignoreSuffix = true, bool includeRemovals = true)
public static bool KeyContains(
this MiniYamlNodeBuilder node, string match, bool ignoreSuffix = true, bool includeRemovals = true)
{
if (node.Key == null)
return false;
@@ -445,23 +461,27 @@ namespace OpenRA.Mods.Common.UpdateRules
}
/// <summary>Returns children with keys equal to [match] or [match]@[arbitrary suffix].</summary>
public static IEnumerable<MiniYamlNodeBuilder> ChildrenMatching(this MiniYamlNodeBuilder node, string match, bool ignoreSuffix = true, bool includeRemovals = true)
public static IEnumerable<MiniYamlNodeBuilder> ChildrenMatching(
this MiniYamlNodeBuilder node, string match, bool ignoreSuffix = true, bool includeRemovals = true)
{
return node.Value.Nodes.Where(n => n.KeyMatches(match, ignoreSuffix, includeRemovals));
}
/// <summary>Returns children whose keys contain 'match' (optionally in the suffix).</summary>
public static IEnumerable<MiniYamlNodeBuilder> ChildrenContaining(this MiniYamlNodeBuilder node, string match, bool ignoreSuffix = true, bool includeRemovals = true)
public static IEnumerable<MiniYamlNodeBuilder> ChildrenContaining(
this MiniYamlNodeBuilder node, string match, bool ignoreSuffix = true, bool includeRemovals = true)
{
return node.Value.Nodes.Where(n => n.KeyContains(match, ignoreSuffix, includeRemovals));
}
public static MiniYamlNodeBuilder LastChildMatching(this MiniYamlNodeBuilder node, string match, bool includeRemovals = true)
public static MiniYamlNodeBuilder LastChildMatching(
this MiniYamlNodeBuilder node, string match, bool includeRemovals = true)
{
return node.ChildrenMatching(match, includeRemovals: includeRemovals).LastOrDefault();
}
public static void RenameChildrenMatching(this MiniYamlNodeBuilder node, string match, string newKey, bool preserveSuffix = true, bool includeRemovals = true)
public static void RenameChildrenMatching(
this MiniYamlNodeBuilder node, string match, string newKey, bool preserveSuffix = true, bool includeRemovals = true)
{
var matching = node.ChildrenMatching(match);
foreach (var m in matching)

View File

@@ -74,7 +74,10 @@ namespace OpenRA.Mods.Common.UtilityCommands
}
}
var output = HtmlTemplate.JoinWith("\n").FormatInvariant(zoom, Convert.ToBase64String(modData.ModFiles.Open(image).ReadAllBytes()), "[" + regions.JoinWith(",") + "]");
var output = HtmlTemplate.JoinWith("\n").FormatInvariant(
zoom,
Convert.ToBase64String(modData.ModFiles.Open(image).ReadAllBytes()),
"[" + regions.JoinWith(",") + "]");
var outputPath = Path.ChangeExtension(image, ".html");
File.WriteAllLines(outputPath, new[] { output });
Console.WriteLine("Saved {0}", outputPath);

View File

@@ -244,7 +244,8 @@ namespace OpenRA.Mods.Common.UtilityCommands
.ToLowerInvariant();
}
static void FromChromeLayout(MiniYamlNodeBuilder node, Dictionary<string, string[]> translatables, string container, ref List<TranslationCandidate> translations)
static void FromChromeLayout(
MiniYamlNodeBuilder node, Dictionary<string, string[]> translatables, string container, ref List<TranslationCandidate> translations)
{
var nodeSplit = node.Key.Split('@');
var nodeType = nodeSplit[0];

View File

@@ -68,7 +68,9 @@ namespace OpenRA.Mods.Common.UtilityCommands
static void WriteDiagnosticsDisabling()
{
Console.WriteLine("--- This file only lists function \"signatures\", causing Lua Diagnostics errors: \"Annotations specify that a return value is required here.\"");
Console.WriteLine(
"--- This file only lists function \"signatures\", causing Lua Diagnostics errors: " +
"\"Annotations specify that a return value is required here.\"");
Console.WriteLine("--- and Lua Diagnostics warnings \"Unused local\" for the functions' parameters.");
Console.WriteLine("--- Disable those specific errors for the entire file.");
Console.WriteLine("---@diagnostic disable: missing-return");
@@ -341,7 +343,8 @@ namespace OpenRA.Mods.Common.UtilityCommands
if (requiredTraits.Length != 0)
Console.WriteLine(
$"{new string(' ', indentation * 4)}--- **Requires {(requiredTraits.Length == 1 ? "Trait" : "Traits")}:** {requiredTraits.Select(GetDocumentationUrl).JoinWith(", ")}");
$"{new string(' ', indentation * 4)}--- **Requires {(requiredTraits.Length == 1 ? "Trait" : "Traits")}:** " +
$"{requiredTraits.Select(GetDocumentationUrl).JoinWith(", ")}");
}
}

View File

@@ -38,7 +38,10 @@ namespace OpenRA.Mods.Common.Warheads
[Desc("Can this warhead affect the actor that fired it.")]
public readonly bool AffectsParent = false;
[Desc("If impact is above this altitude, warheads that would affect terrain ignore terrain target types (and either do nothing or perform their own checks).")]
[Desc(
"If impact is above this altitude, " +
"warheads that would affect terrain ignore terrain target types " +
"(and either do nothing or perform their own checks).")]
public readonly WDist AirThreshold = new(128);
[Desc("Delay in ticks before applying the warhead effect.", "0 = instant (old model).")]

View File

@@ -78,7 +78,11 @@ namespace OpenRA.Mods.Common.Widgets
var checkmarkImage = getCheckmarkImageCache
.Update((GetCheckmark(), IsChecked()))
.Update((disabled, Depressed, hover, false, IsHighlighted()));
WidgetUtils.DrawSprite(checkmarkImage, new float2(rect.Right - (int)((rect.Height + checkmarkImage.Size.X) / 2), rect.Top + (int)((rect.Height - checkmarkImage.Size.Y) / 2)));
WidgetUtils.DrawSprite(
checkmarkImage,
new float2(
rect.Right - (int)((rect.Height + checkmarkImage.Size.X) / 2),
rect.Top + (int)((rect.Height - checkmarkImage.Size.Y) / 2)));
}
public override Widget Clone() { return new CheckboxWidget(this); }

View File

@@ -58,13 +58,20 @@ namespace OpenRA.Mods.Common.Widgets
getMarkerImage ??= WidgetUtils.GetCachedStatefulImage(Decorations, DecorationMarker);
var arrowImage = getMarkerImage.Update((isDisabled, Depressed, isHover, false, IsHighlighted()));
WidgetUtils.DrawSprite(arrowImage, stateOffset + new float2(rb.Right - (int)((rb.Height + arrowImage.Size.X) / 2), rb.Top + (int)((rb.Height - arrowImage.Size.Y) / 2)));
WidgetUtils.DrawSprite(
arrowImage,
stateOffset + new float2(
rb.Right - (int)((rb.Height + arrowImage.Size.X) / 2),
rb.Top + (int)((rb.Height - arrowImage.Size.Y) / 2)));
getSeparatorImage ??= WidgetUtils.GetCachedStatefulImage(Separators, SeparatorImage);
var separatorImage = getSeparatorImage.Update((isDisabled, Depressed, isHover, false, IsHighlighted()));
if (separatorImage != null)
WidgetUtils.DrawSprite(separatorImage, stateOffset + new float2(-3, 0) + new float2(rb.Right - rb.Height + 4, rb.Top + (int)((rb.Height - separatorImage.Size.Y) / 2)));
WidgetUtils.DrawSprite(
separatorImage,
stateOffset + new float2(-3, 0) + new float2(rb.Right - rb.Height + 4,
rb.Top + (int)((rb.Height - separatorImage.Size.Y) / 2)));
}
public override Widget Clone() { return new DropDownButtonWidget(this); }
@@ -138,7 +145,8 @@ namespace OpenRA.Mods.Common.Widgets
(panel as ScrollPanelWidget)?.ScrollToSelectedItem();
}
public void ShowDropDown<T>(string panelTemplate, int maxHeight, IEnumerable<T> options, Func<T, ScrollItemWidget, ScrollItemWidget> setupItem)
public void ShowDropDown<T>(
string panelTemplate, int maxHeight, IEnumerable<T> options, Func<T, ScrollItemWidget, ScrollItemWidget> setupItem)
{
var substitutions = new Dictionary<string, int>() { { "DROPDOWN_WIDTH", Bounds.Width } };
var panel = (ScrollPanelWidget)Ui.LoadWidget(panelTemplate, null, new WidgetArgs() { { "substitutions", substitutions } });
@@ -160,7 +168,8 @@ namespace OpenRA.Mods.Common.Widgets
AttachPanel(panel);
}
public void ShowDropDown<T>(string panelTemplate, int height, Dictionary<string, IEnumerable<T>> groups, Func<T, ScrollItemWidget, ScrollItemWidget> setupItem)
public void ShowDropDown<T>(
string panelTemplate, int height, Dictionary<string, IEnumerable<T>> groups, Func<T, ScrollItemWidget, ScrollItemWidget> setupItem)
{
var substitutions = new Dictionary<string, int>() { { "DROPDOWN_WIDTH", Bounds.Width } };
var panel = (ScrollPanelWidget)Ui.LoadWidget(panelTemplate, null, new WidgetArgs() { { "substitutions", substitutions } });

View File

@@ -471,11 +471,17 @@ namespace OpenRA.Mods.Common.Widgets.Logic
item.IsVisible = () =>
{
var allowed = (assetTypesToDisplay.HasFlag(AssetType.Sprite) && allowedSpriteExtensions.Any(ext => filepath.EndsWith(ext, true, CultureInfo.InvariantCulture)))
|| (assetTypesToDisplay.HasFlag(AssetType.Model) && allowedModelExtensions.Any(ext => filepath.EndsWith(ext, true, CultureInfo.InvariantCulture)))
|| (assetTypesToDisplay.HasFlag(AssetType.Audio) && allowedAudioExtensions.Any(ext => filepath.EndsWith(ext, true, CultureInfo.InvariantCulture)))
|| (assetTypesToDisplay.HasFlag(AssetType.Video) && allowedVideoExtensions.Any(ext => filepath.EndsWith(ext, true, CultureInfo.InvariantCulture)))
|| (assetTypesToDisplay.HasFlag(AssetType.Unknown) && !allowedExtensions.Any(ext => filepath.EndsWith(ext, true, CultureInfo.InvariantCulture)));
var allowed =
(assetTypesToDisplay.HasFlag(AssetType.Sprite)
&& allowedSpriteExtensions.Any(ext => filepath.EndsWith(ext, true, CultureInfo.InvariantCulture)))
|| (assetTypesToDisplay.HasFlag(AssetType.Model)
&& allowedModelExtensions.Any(ext => filepath.EndsWith(ext, true, CultureInfo.InvariantCulture)))
|| (assetTypesToDisplay.HasFlag(AssetType.Audio)
&& allowedAudioExtensions.Any(ext => filepath.EndsWith(ext, true, CultureInfo.InvariantCulture)))
|| (assetTypesToDisplay.HasFlag(AssetType.Video)
&& allowedVideoExtensions.Any(ext => filepath.EndsWith(ext, true, CultureInfo.InvariantCulture)))
|| (assetTypesToDisplay.HasFlag(AssetType.Unknown)
&& !allowedExtensions.Any(ext => filepath.EndsWith(ext, true, CultureInfo.InvariantCulture)));
if (assetVisByName.TryGetValue(filepath, out var visible))
return visible && allowed;

View File

@@ -87,7 +87,8 @@ namespace OpenRA.Mods.Common.Widgets.Logic
const string VoteKickVoteCancel = "dialog-vote-kick.vote-cancel";
[ObjectCreator.UseCtor]
public GameInfoStatsLogic(Widget widget, ModData modData, World world, OrderManager orderManager, WorldRenderer worldRenderer, Action<bool> hideMenu, Action closeMenu)
public GameInfoStatsLogic(Widget widget, ModData modData, World world,
OrderManager orderManager, WorldRenderer worldRenderer, Action<bool> hideMenu, Action closeMenu)
{
var player = world.LocalPlayer;
var playerPanel = widget.Get<ScrollPanelWidget>("PLAYER_LIST");

View File

@@ -135,7 +135,10 @@ namespace OpenRA.Mods.Common.Widgets.Logic
var timeText = formatBuildTime.Update(buildTime * timeModifier / 100);
timeLabel.GetText = () => timeText;
timeLabel.TextColor = (pm != null && pm.PowerState != PowerState.Normal && tooltipIcon.ProductionQueue.Info.LowPowerModifier > 100) ? Color.Red : Color.White;
timeLabel.TextColor =
(pm != null && pm.PowerState != PowerState.Normal && tooltipIcon.ProductionQueue.Info.LowPowerModifier > 100)
? Color.Red
: Color.White;
var timeSize = font.Measure(timeText);
var costText = cost.ToString(NumberFormatInfo.CurrentInfo);

View File

@@ -19,7 +19,8 @@ namespace OpenRA.Mods.Common.Widgets.Logic
public class SupportPowerTooltipLogic : ChromeLogic
{
[ObjectCreator.UseCtor]
public SupportPowerTooltipLogic(Widget widget, TooltipContainerWidget tooltipContainer, Func<SupportPowersWidget.SupportPowerIcon> getTooltipIcon, World world)
public SupportPowerTooltipLogic(Widget widget, TooltipContainerWidget tooltipContainer,
Func<SupportPowersWidget.SupportPowerIcon> getTooltipIcon, World world)
{
widget.IsVisible = () => getTooltipIcon() != null && getTooltipIcon().Power.Info != null;
var nameLabel = widget.Get<LabelWidget>("NAME");

View File

@@ -40,7 +40,10 @@ namespace OpenRA.Mods.Common.Widgets.Logic
var panel = widget.Get("CONTENT_PROMPT_PANEL");
var headerTemplate = panel.Get<LabelWidget>("HEADER_TEMPLATE");
var headerLines = !string.IsNullOrEmpty(content.InstallPromptMessage) ? content.InstallPromptMessage.Replace("\\n", "\n").Split('\n') : Array.Empty<string>();
var headerLines =
!string.IsNullOrEmpty(content.InstallPromptMessage)
? content.InstallPromptMessage.Replace("\\n", "\n").Split('\n')
: Array.Empty<string>();
var headerHeight = 0;
foreach (var l in headerLines)
{

View File

@@ -592,7 +592,9 @@ namespace OpenRA.Mods.Common.Widgets.Logic
panel = PanelType.Players;
var chatWasEnabled = chatEnabled;
chatEnabled = worldRenderer.World.IsReplay || (Game.RunTime >= TextNotificationsManager.ChatDisabledUntil && TextNotificationsManager.ChatDisabledUntil != uint.MaxValue);
chatEnabled =
worldRenderer.World.IsReplay ||
(Game.RunTime >= TextNotificationsManager.ChatDisabledUntil && TextNotificationsManager.ChatDisabledUntil != uint.MaxValue);
if (chatEnabled && !chatWasEnabled)
{

View File

@@ -284,7 +284,9 @@ namespace OpenRA.Mods.Common.Widgets.Logic
static void SetSpawnPoint(OrderManager orderManager, Session.Client playerToMove, int selectedSpawnPoint)
{
var owned = orderManager.LobbyInfo.Clients.Any(c => c.SpawnPoint == selectedSpawnPoint) || orderManager.LobbyInfo.DisabledSpawnPoints.Contains(selectedSpawnPoint);
var owned =
orderManager.LobbyInfo.Clients.Any(c => c.SpawnPoint == selectedSpawnPoint) ||
orderManager.LobbyInfo.DisabledSpawnPoints.Contains(selectedSpawnPoint);
if (selectedSpawnPoint == 0 || !owned)
orderManager.IssueOrder(Order.Command($"spawn {(playerToMove ?? orderManager.LocalClient).Index} {selectedSpawnPoint}"));
}

View File

@@ -205,17 +205,28 @@ namespace OpenRA.Mods.Common.Widgets.Logic
var previewSmall = SetupMapPreview(widget.Get("MAP_SMALL"));
// Widgets to be made visible.
previewWidgets[PreviewStatus.Unknown] = new Widget[] { previewLarge };
previewWidgets[PreviewStatus.Playable] = new Widget[] { previewLarge, SetupAuthorAndMapType(widget.Get("MAP_AVAILABLE")) };
previewWidgets[PreviewStatus.Incompatible] = new Widget[] { previewLarge, widget.Get("MAP_INCOMPATIBLE") };
previewWidgets[PreviewStatus.Validating] = new Widget[] { previewSmall, widget.Get("MAP_VALIDATING") };
previewWidgets[PreviewStatus.UpdateAvailable] = new Widget[] { previewSmall, widget.Get("MAP_UPDATE_AVAILABLE"), updateButton };
previewWidgets[PreviewStatus.DownloadAvailable] = new Widget[] { previewSmall, SetUpInstallButton(SetupAuthorAndMapType(widget.Get("MAP_DOWNLOAD_AVAILABLE"))) };
previewWidgets[PreviewStatus.UpdateDownloadAvailable] = new Widget[] { previewSmall, SetUpInstallButton(widget.Get("MAP_UPDATE_DOWNLOAD_AVAILABLE")), updateButton };
previewWidgets[PreviewStatus.Searching] = new Widget[] { previewSmall, widget.Get("MAP_SEARCHING") };
previewWidgets[PreviewStatus.Downloading] = new Widget[] { previewSmall, SetUpDownloadProgress(widget.Get("MAP_DOWNLOADING")) };
previewWidgets[PreviewStatus.Unavailable] = new Widget[] { previewSmall, widget.Get("MAP_UNAVAILABLE"), retryButton };
previewWidgets[PreviewStatus.DownloadError] = new Widget[] { previewSmall, widget.Get("MAP_ERROR"), retryButton };
previewWidgets[PreviewStatus.Unknown] =
new Widget[] { previewLarge };
previewWidgets[PreviewStatus.Playable] =
new Widget[] { previewLarge, SetupAuthorAndMapType(widget.Get("MAP_AVAILABLE")) };
previewWidgets[PreviewStatus.Incompatible] =
new Widget[] { previewLarge, widget.Get("MAP_INCOMPATIBLE") };
previewWidgets[PreviewStatus.Validating] =
new Widget[] { previewSmall, widget.Get("MAP_VALIDATING") };
previewWidgets[PreviewStatus.UpdateAvailable] =
new Widget[] { previewSmall, widget.Get("MAP_UPDATE_AVAILABLE"), updateButton };
previewWidgets[PreviewStatus.DownloadAvailable] =
new Widget[] { previewSmall, SetUpInstallButton(SetupAuthorAndMapType(widget.Get("MAP_DOWNLOAD_AVAILABLE"))) };
previewWidgets[PreviewStatus.UpdateDownloadAvailable] =
new Widget[] { previewSmall, SetUpInstallButton(widget.Get("MAP_UPDATE_DOWNLOAD_AVAILABLE")), updateButton };
previewWidgets[PreviewStatus.Searching] =
new Widget[] { previewSmall, widget.Get("MAP_SEARCHING") };
previewWidgets[PreviewStatus.Downloading] =
new Widget[] { previewSmall, SetUpDownloadProgress(widget.Get("MAP_DOWNLOADING")) };
previewWidgets[PreviewStatus.Unavailable] =
new Widget[] { previewSmall, widget.Get("MAP_UNAVAILABLE"), retryButton };
previewWidgets[PreviewStatus.DownloadError] =
new Widget[] { previewSmall, widget.Get("MAP_ERROR"), retryButton };
// Hide all widgets.
foreach (var preview in previewWidgets)

View File

@@ -29,7 +29,8 @@ namespace OpenRA.Mods.Common.Widgets.Logic
readonly CachedTransform<int, string> teamMessage;
[ObjectCreator.UseCtor]
public SpawnSelectorTooltipLogic(Widget widget, ModData modData, TooltipContainerWidget tooltipContainer, MapPreviewWidget preview, bool showUnoccupiedSpawnpoints)
public SpawnSelectorTooltipLogic(Widget widget, ModData modData,
TooltipContainerWidget tooltipContainer, MapPreviewWidget preview, bool showUnoccupiedSpawnpoints)
{
var showTooltip = true;
widget.IsVisible = () => preview.TooltipSpawnIndex != -1 && showTooltip;

View File

@@ -72,7 +72,8 @@ namespace OpenRA.Mods.Common.Widgets.Logic
static bool IncompatibleReplayDialog(string text, Dictionary<string, object> textArguments, ModData modData, Action onCancel)
{
ConfirmationDialogs.ButtonPrompt(modData, IncompatibleReplayTitle, text, textArguments: textArguments, onCancel: onCancel, cancelText: IncompatibleReplayAccept);
ConfirmationDialogs.ButtonPrompt(
modData, IncompatibleReplayTitle, text, textArguments: textArguments, onCancel: onCancel, cancelText: IncompatibleReplayAccept);
return false;
}
}

View File

@@ -70,7 +70,10 @@ namespace OpenRA.Mods.Common.Widgets.Logic
var settings = Game.Settings;
map = modData.MapCache[modData.MapCache.ChooseInitialMap(modData.MapCache.PickLastModifiedMap(MapVisibility.Lobby) ?? Game.Settings.Server.Map, Game.CosmeticRandom)];
map = modData.MapCache[
modData.MapCache.ChooseInitialMap(
modData.MapCache.PickLastModifiedMap(MapVisibility.Lobby) ?? Game.Settings.Server.Map,
Game.CosmeticRandom)];
Ui.LoadWidget("MAP_PREVIEW", panel.Get("MAP_PREVIEW_ROOT"), new WidgetArgs
{

View File

@@ -32,7 +32,11 @@ namespace OpenRA.Mods.Common.Widgets.Logic
}
[ObjectCreator.UseCtor]
public AudioSettingsLogic(Action<string, string, Func<Widget, Func<bool>>, Func<Widget, Action>> registerPanel, string panelID, string label, WorldRenderer worldRenderer)
public AudioSettingsLogic(
Action<string, string, Func<Widget, Func<bool>>, Func<Widget, Action>> registerPanel,
string panelID,
string label,
WorldRenderer worldRenderer)
{
this.worldRenderer = worldRenderer;

View File

@@ -276,7 +276,9 @@ namespace OpenRA.Mods.Common.Widgets.Logic
duplicateHotkeyDefinition = modData.Hotkeys.GetFirstDuplicate(selectedHotkeyDefinition, hotkeyEntryWidget.Key);
isHotkeyValid = duplicateHotkeyDefinition == null || selectedHotkeyDefinition.Readonly;
isHotkeyDefault = hotkeyEntryWidget.Key == selectedHotkeyDefinition.Default || (!hotkeyEntryWidget.Key.IsValid() && !selectedHotkeyDefinition.Default.IsValid());
isHotkeyDefault =
hotkeyEntryWidget.Key == selectedHotkeyDefinition.Default ||
(!hotkeyEntryWidget.Key.IsValid() && !selectedHotkeyDefinition.Default.IsValid());
if (isHotkeyValid)
{

View File

@@ -212,7 +212,13 @@ namespace OpenRA.Mods.Common.Widgets
}
if (occupied)
WidgetUtils.FillEllipseWithColor(new Rectangle(pos.X - offset.X + 1, pos.Y - offset.Y + 1, (int)sprite.Size.X - 2, (int)sprite.Size.Y - 2), occupant.Color);
WidgetUtils.FillEllipseWithColor(
new Rectangle(
pos.X - offset.X + 1,
pos.Y - offset.Y + 1,
(int)sprite.Size.X - 2,
(int)sprite.Size.Y - 2),
occupant.Color);
WidgetUtils.DrawSprite(sprite, pos - offset);

View File

@@ -269,7 +269,9 @@ namespace OpenRA.Mods.Common.Widgets
lastIconIdx = i;
TooltipIcon = productionIcons[i];
currentTooltipToken = tooltipContainer.Value.SetTooltip(TooltipTemplate, new WidgetArgs { { "player", GetPlayer() }, { "getTooltipIcon", GetTooltipIcon } });
currentTooltipToken = tooltipContainer.Value.SetTooltip(
TooltipTemplate,
new WidgetArgs { { "player", GetPlayer() }, { "getTooltipIcon", GetTooltipIcon } });
return;
}

View File

@@ -336,7 +336,8 @@ namespace OpenRA.Mods.Common.Widgets
if (buildable != null)
{
if (CurrentQueue.Info.PayUpFront && currentQueue.GetProductionCost(buildable) > CurrentQueue.Actor.Owner.PlayerActor.Trait<PlayerResources>().GetCashAndResources())
if (CurrentQueue.Info.PayUpFront &&
currentQueue.GetProductionCost(buildable) > CurrentQueue.Actor.Owner.PlayerActor.Trait<PlayerResources>().GetCashAndResources())
return false;
Game.Sound.PlayNotification(World.Map.Rules, World.LocalPlayer, "Sounds", ClickSound, null);

View File

@@ -20,18 +20,21 @@ namespace OpenRA.Mods.Common.Widgets
{
public static class SelectionUtils
{
public static IEnumerable<Actor> SelectActorsOnScreen(World world, WorldRenderer wr, IEnumerable<string> selectionClasses, IEnumerable<Player> players)
public static IEnumerable<Actor> SelectActorsOnScreen(
World world, WorldRenderer wr, IEnumerable<string> selectionClasses, IEnumerable<Player> players)
{
var actors = world.ScreenMap.ActorsInMouseBox(wr.Viewport.TopLeft, wr.Viewport.BottomRight).Select(a => a.Actor);
return SelectActorsByOwnerAndSelectionClass(actors, players, selectionClasses);
}
public static IEnumerable<Actor> SelectActorsInWorld(World world, IEnumerable<string> selectionClasses, IEnumerable<Player> players)
public static IEnumerable<Actor> SelectActorsInWorld(
World world, IEnumerable<string> selectionClasses, IEnumerable<Player> players)
{
return SelectActorsByOwnerAndSelectionClass(world.Actors.Where(a => a.IsInWorld), players, selectionClasses);
}
public static IEnumerable<Actor> SelectActorsByOwnerAndSelectionClass(IEnumerable<Actor> actors, IEnumerable<Player> owners, IEnumerable<string> selectionClasses)
public static IEnumerable<Actor> SelectActorsByOwnerAndSelectionClass(
IEnumerable<Actor> actors, IEnumerable<Player> owners, IEnumerable<string> selectionClasses)
{
return actors.Where(a =>
{

View File

@@ -20,7 +20,8 @@ namespace OpenRA.Mods.Common.Widgets
{
public static class WidgetUtils
{
public static string GetStatefulImageName(string baseName, bool disabled = false, bool pressed = false, bool hover = false, bool focused = false)
public static string GetStatefulImageName(
string baseName, bool disabled = false, bool pressed = false, bool hover = false, bool focused = false)
{
var suffix = disabled ? "-disabled" :
focused ? "-focused" :
@@ -31,7 +32,8 @@ namespace OpenRA.Mods.Common.Widgets
return baseName + suffix;
}
public static CachedTransform<(bool Disabled, bool Pressed, bool Hover, bool Focused, bool Highlighted), Sprite> GetCachedStatefulImage(string collection, string imageName)
public static CachedTransform<(bool Disabled, bool Pressed, bool Hover, bool Focused, bool Highlighted), Sprite>
GetCachedStatefulImage(string collection, string imageName)
{
return new CachedTransform<(bool, bool, bool, bool, bool), Sprite>(
((bool Disabled, bool Pressed, bool Hover, bool Focused, bool Highlighted) args) =>
@@ -43,7 +45,8 @@ namespace OpenRA.Mods.Common.Widgets
}
// TODO: refactor buttons and related UI to use this function
public static CachedTransform<(bool Disabled, bool Pressed, bool Hover, bool Focused, bool Highlighted), Sprite[]> GetCachedStatefulPanelImages(string collection)
public static CachedTransform<(bool Disabled, bool Pressed, bool Hover, bool Focused, bool Highlighted), Sprite[]>
GetCachedStatefulPanelImages(string collection)
{
return new CachedTransform<(bool, bool, bool, bool, bool), Sprite[]>(
((bool Disabled, bool Pressed, bool Hover, bool Focused, bool Highlighted) args) =>

View File

@@ -25,7 +25,8 @@ namespace OpenRA.Mods.Common
/// <paramref name="targetOffsets"/> is used to define locations around each actor in <paramref name="actors"/>
/// of which one must be reachable.
/// </summary>
public static IEnumerable<(Actor Actor, WVec[] ReachableOffsets)> WithPathFrom(this IEnumerable<Actor> actors, Actor sourceActor, Func<Actor, WVec[]> targetOffsets)
public static IEnumerable<(Actor Actor, WVec[] ReachableOffsets)> WithPathFrom(
this IEnumerable<Actor> actors, Actor sourceActor, Func<Actor, WVec[]> targetOffsets)
{
if (sourceActor.Info.HasTraitInfo<AircraftInfo>())
return actors.Select<Actor, (Actor Actor, WVec[] ReachableOffsets)>(a => (a, targetOffsets(a)));
@@ -66,7 +67,8 @@ namespace OpenRA.Mods.Common
/// <paramref name="targetOffsets"/> is used to define locations around each actor in <paramref name="actors"/>
/// of which one must be reachable.
/// </summary>
public static Actor ClosestToWithPathFrom(this IEnumerable<Actor> actors, Actor sourceActor, Func<Actor, WVec[]> targetOffsets = null)
public static Actor ClosestToWithPathFrom(
this IEnumerable<Actor> actors, Actor sourceActor, Func<Actor, WVec[]> targetOffsets = null)
{
return actors
.WithPathFrom(sourceActor, targetOffsets ?? (_ => new[] { WVec.Zero }))
@@ -178,7 +180,8 @@ namespace OpenRA.Mods.Common
/// target of a path from the actor, returns the nearest by comparing the <see cref="Actor.CenterPosition"/>.
/// Only terrain is taken into account, i.e. as if <see cref="BlockedByActor.None"/> was given.
/// </summary>
public static Actor ClosestToWithPathToAny(this IEnumerable<Actor> actors, World world, Func<Actor, WPos[]> targetPositions)
public static Actor ClosestToWithPathToAny(
this IEnumerable<Actor> actors, World world, Func<Actor, WPos[]> targetPositions)
{
return actors
.WithPathToAny(world, targetPositions)
@@ -206,7 +209,8 @@ namespace OpenRA.Mods.Common
/// <param name="onlyBlockers">If set, only considers the size of actors that have an <see cref="IBlocksProjectiles"/>
/// trait which may improve search performance. However does NOT filter the returned actors on this trait.</param>
/// <returns>A list of all the actors intersected by the line.</returns>
public static IEnumerable<Actor> FindActorsOnLine(this World world, WPos lineStart, WPos lineEnd, WDist lineWidth, bool onlyBlockers = false)
public static IEnumerable<Actor> FindActorsOnLine(
this World world, WPos lineStart, WPos lineEnd, WDist lineWidth, bool onlyBlockers = false)
{
// This line intersection check is done by first just finding all actors within a square that starts at the source, and ends at the target.
// Then we iterate over this list, and find all actors for which their health radius is at least within lineWidth of the line.