Fix IDE0090

This commit is contained in:
RoosterDragon
2023-04-05 19:34:12 +01:00
committed by Pavel Penev
parent 164abfdae1
commit 8a285f9b19
385 changed files with 790 additions and 794 deletions

View File

@@ -169,7 +169,7 @@ dotnet_diagnostic.IDE0082.severity = warning
# IDE0090 Simplify 'new' expression # IDE0090 Simplify 'new' expression
#csharp_style_implicit_object_creation_when_type_is_apparent = true #csharp_style_implicit_object_creation_when_type_is_apparent = true
dotnet_diagnostic.IDE0090.severity = silent # Requires C# 9 - TODO Consider enabling dotnet_diagnostic.IDE0090.severity = warning
# IDE0180 Use tuple to swap values # IDE0180 Use tuple to swap values
#csharp_style_prefer_tuple_swap = true #csharp_style_prefer_tuple_swap = true

View File

@@ -84,21 +84,21 @@ namespace OpenRA
class ConditionState class ConditionState
{ {
/// <summary>Delegates that have registered to be notified when this condition changes.</summary> /// <summary>Delegates that have registered to be notified when this condition changes.</summary>
public readonly List<VariableObserverNotifier> Notifiers = new List<VariableObserverNotifier>(); public readonly List<VariableObserverNotifier> Notifiers = new();
/// <summary>Unique integers identifying granted instances of the condition.</summary> /// <summary>Unique integers identifying granted instances of the condition.</summary>
public readonly HashSet<int> Tokens = new HashSet<int>(); public readonly HashSet<int> Tokens = new();
} }
readonly Dictionary<string, ConditionState> conditionStates = new Dictionary<string, ConditionState>(); readonly Dictionary<string, ConditionState> conditionStates = new();
/// <summary>Each granted condition receives a unique token that is used when revoking.</summary> /// <summary>Each granted condition receives a unique token that is used when revoking.</summary>
readonly Dictionary<int, string> conditionTokens = new Dictionary<int, string>(); readonly Dictionary<int, string> conditionTokens = new();
int nextConditionToken = 1; int nextConditionToken = 1;
/// <summary>Cache of condition -> enabled state for quick evaluation of token counter conditions.</summary> /// <summary>Cache of condition -> enabled state for quick evaluation of token counter conditions.</summary>
readonly Dictionary<string, int> conditionCache = new Dictionary<string, int>(); readonly Dictionary<string, int> conditionCache = new();
/// <summary>Read-only version of conditionCache that is passed to IConditionConsumers.</summary> /// <summary>Read-only version of conditionCache that is passed to IConditionConsumers.</summary>
readonly IReadOnlyDictionary<string, int> readOnlyConditionCache; readonly IReadOnlyDictionary<string, int> readOnlyConditionCache;

View File

@@ -41,7 +41,7 @@ namespace OpenRA
Bits = (x & 0xFFF) << 20 | (y & 0xFFF) << 8 | layer; Bits = (x & 0xFFF) << 20 | (y & 0xFFF) << 8 | layer;
} }
public static readonly CPos Zero = new CPos(0, 0, 0); public static readonly CPos Zero = new(0, 0, 0);
public static explicit operator CPos(int2 a) { return new CPos(a.X, a.Y); } public static explicit operator CPos(int2 a) { return new CPos(a.X, a.Y); }

View File

@@ -22,7 +22,7 @@ namespace OpenRA
public readonly int X, Y; public readonly int X, Y;
public CVec(int x, int y) { X = x; Y = y; } public CVec(int x, int y) { X = x; Y = y; }
public static readonly CVec Zero = new CVec(0, 0); public static readonly CVec Zero = new(0, 0);
public static CVec operator +(CVec a, CVec b) { return new CVec(a.X + b.X, a.Y + b.Y); } public static CVec operator +(CVec a, CVec b) { return new CVec(a.X + b.X, a.Y + b.Y); }
public static CVec operator -(CVec a, CVec b) { return new CVec(a.X - b.X, a.Y - b.Y); } public static CVec operator -(CVec a, CVec b) { return new CVec(a.X - b.X, a.Y - b.Y); }

View File

@@ -41,7 +41,7 @@ namespace OpenRA
public class ExternalMods : IReadOnlyDictionary<string, ExternalMod> public class ExternalMods : IReadOnlyDictionary<string, ExternalMod>
{ {
readonly Dictionary<string, ExternalMod> mods = new Dictionary<string, ExternalMod>(); readonly Dictionary<string, ExternalMod> mods = new();
readonly SheetBuilder sheetBuilder; readonly SheetBuilder sheetBuilder;
Sheet CreateSheet() Sheet CreateSheet()

View File

@@ -62,14 +62,14 @@ namespace OpenRA
throw new NotImplementedException($"FieldLoader: Missing field `{s}` on `{f.Name}`"); throw new NotImplementedException($"FieldLoader: Missing field `{s}` on `{f.Name}`");
static readonly ConcurrentCache<Type, FieldLoadInfo[]> TypeLoadInfo = static readonly ConcurrentCache<Type, FieldLoadInfo[]> TypeLoadInfo =
new ConcurrentCache<Type, FieldLoadInfo[]>(BuildTypeLoadInfo); new(BuildTypeLoadInfo);
static readonly ConcurrentCache<string, BooleanExpression> BooleanExpressionCache = static readonly ConcurrentCache<string, BooleanExpression> BooleanExpressionCache =
new ConcurrentCache<string, BooleanExpression>(expression => new BooleanExpression(expression)); new(expression => new BooleanExpression(expression));
static readonly ConcurrentCache<string, IntegerExpression> IntegerExpressionCache = static readonly ConcurrentCache<string, IntegerExpression> IntegerExpressionCache =
new ConcurrentCache<string, IntegerExpression>(expression => new IntegerExpression(expression)); new(expression => new IntegerExpression(expression));
static readonly Dictionary<Type, Func<string, Type, string, MemberInfo, object>> TypeParsers = static readonly Dictionary<Type, Func<string, Type, string, MemberInfo, object>> TypeParsers =
new Dictionary<Type, Func<string, Type, string, MemberInfo, object>>() new()
{ {
{ typeof(int), ParseInt }, { typeof(int), ParseInt },
{ typeof(ushort), ParseUShort }, { typeof(ushort), ParseUShort },
@@ -103,7 +103,7 @@ namespace OpenRA
}; };
static readonly Dictionary<Type, Func<string, Type, string, MiniYaml, MemberInfo, object>> GenericTypeParsers = static readonly Dictionary<Type, Func<string, Type, string, MiniYaml, MemberInfo, object>> GenericTypeParsers =
new Dictionary<Type, Func<string, Type, string, MiniYaml, MemberInfo, object>>() new()
{ {
{ typeof(HashSet<>), ParseHashSetOrList }, { typeof(HashSet<>), ParseHashSetOrList },
{ typeof(List<>), ParseHashSetOrList }, { typeof(List<>), ParseHashSetOrList },
@@ -749,7 +749,7 @@ namespace OpenRA
[AttributeUsage(AttributeTargets.Field)] [AttributeUsage(AttributeTargets.Field)]
public class SerializeAttribute : Attribute public class SerializeAttribute : Attribute
{ {
public static readonly SerializeAttribute Default = new SerializeAttribute(true); public static readonly SerializeAttribute Default = new(true);
public bool IsDefault => this == Default; public bool IsDefault => this == Default;

View File

@@ -31,7 +31,7 @@ namespace OpenRA.FileFormats
public Color[] Palette { get; } public Color[] Palette { get; }
public byte[] Data { get; } public byte[] Data { get; }
public SpriteFrameType Type { get; } public SpriteFrameType Type { get; }
public Dictionary<string, string> EmbeddedData = new Dictionary<string, string>(); public Dictionary<string, string> EmbeddedData = new();
public int PixelStride => Type == SpriteFrameType.Indexed8 ? 1 : Type == SpriteFrameType.Rgb24 ? 3 : 4; public int PixelStride => Type == SpriteFrameType.Indexed8 ? 1 : Type == SpriteFrameType.Rgb24 ? 3 : 4;

View File

@@ -29,16 +29,16 @@ namespace OpenRA.FileSystem
public class FileSystem : IReadOnlyFileSystem public class FileSystem : IReadOnlyFileSystem
{ {
public IEnumerable<IReadOnlyPackage> MountedPackages => mountedPackages.Keys; public IEnumerable<IReadOnlyPackage> MountedPackages => mountedPackages.Keys;
readonly Dictionary<IReadOnlyPackage, int> mountedPackages = new Dictionary<IReadOnlyPackage, int>(); readonly Dictionary<IReadOnlyPackage, int> mountedPackages = new();
readonly Dictionary<string, IReadOnlyPackage> explicitMounts = new Dictionary<string, IReadOnlyPackage>(); readonly Dictionary<string, IReadOnlyPackage> explicitMounts = new();
readonly string modID; readonly string modID;
// Mod packages that should not be disposed // Mod packages that should not be disposed
readonly List<IReadOnlyPackage> modPackages = new List<IReadOnlyPackage>(); readonly List<IReadOnlyPackage> modPackages = new();
readonly IReadOnlyDictionary<string, Manifest> installedMods; readonly IReadOnlyDictionary<string, Manifest> installedMods;
readonly IPackageLoader[] packageLoaders; readonly IPackageLoader[] packageLoaders;
Cache<string, List<IReadOnlyPackage>> fileIndex = new Cache<string, List<IReadOnlyPackage>>(_ => new List<IReadOnlyPackage>()); Cache<string, List<IReadOnlyPackage>> fileIndex = new(_ => new List<IReadOnlyPackage>());
public FileSystem(string modID, IReadOnlyDictionary<string, Manifest> installedMods, IPackageLoader[] packageLoaders) public FileSystem(string modID, IReadOnlyDictionary<string, Manifest> installedMods, IPackageLoader[] packageLoaders)
{ {

View File

@@ -95,7 +95,7 @@ namespace OpenRA.FileSystem
sealed class ReadWriteZipFile : ReadOnlyZipFile, IReadWritePackage sealed class ReadWriteZipFile : ReadOnlyZipFile, IReadWritePackage
{ {
readonly MemoryStream pkgStream = new MemoryStream(); readonly MemoryStream pkgStream = new();
public ReadWriteZipFile(string filename, bool create = false) public ReadWriteZipFile(string filename, bool create = false)
{ {

View File

@@ -48,7 +48,7 @@ namespace OpenRA
internal static OrderManager OrderManager; internal static OrderManager OrderManager;
static Server.Server server; static Server.Server server;
public static MersenneTwister CosmeticRandom = new MersenneTwister(); // not synced public static MersenneTwister CosmeticRandom = new(); // not synced
public static Renderer Renderer; public static Renderer Renderer;
public static Sound Sound; public static Sound Sound;
@@ -563,7 +563,7 @@ namespace OpenRA
// Note: These delayed actions should only be used by widgets or disposing objects // Note: These delayed actions should only be used by widgets or disposing objects
// - things that depend on a particular world should be queuing them on the world actor. // - things that depend on a particular world should be queuing them on the world actor.
static volatile ActionQueue delayedActions = new ActionQueue(); static volatile ActionQueue delayedActions = new();
public static void RunAfterTick(Action a) { delayedActions.Add(a, RunTime); } public static void RunAfterTick(Action a) { delayedActions.Add(a, RunTime); }
public static void RunAfterDelay(int delayMilliseconds, Action a) { delayedActions.Add(a, RunTime + delayMilliseconds); } public static void RunAfterDelay(int delayMilliseconds, Action a) { delayedActions.Add(a, RunTime + delayMilliseconds); }

View File

@@ -36,7 +36,7 @@ namespace OpenRA
public TimeSpan Duration => EndTimeUtc > StartTimeUtc ? EndTimeUtc - StartTimeUtc : TimeSpan.Zero; public TimeSpan Duration => EndTimeUtc > StartTimeUtc ? EndTimeUtc - StartTimeUtc : TimeSpan.Zero;
public IList<Player> Players { get; } public IList<Player> Players { get; }
public HashSet<int> DisabledSpawnPoints = new HashSet<int>(); public HashSet<int> DisabledSpawnPoints = new();
public MapPreview MapPreview => Game.ModData.MapCache[MapUid]; public MapPreview MapPreview => Game.ModData.MapCache[MapUid];
public IEnumerable<Player> HumanPlayers { get { return Players.Where(p => p.IsHuman); } } public IEnumerable<Player> HumanPlayers { get { return Players.Where(p => p.IsHuman); } }
public bool IsSinglePlayer => HumanPlayers.Count() == 1; public bool IsSinglePlayer => HumanPlayers.Count() == 1;

View File

@@ -32,7 +32,7 @@ namespace OpenRA
/// You can remove inherited traits by adding a - in front of them as in -TraitName: to inherit everything, but this trait. /// You can remove inherited traits by adding a - in front of them as in -TraitName: to inherit everything, but this trait.
/// </summary> /// </summary>
public readonly string Name; public readonly string Name;
readonly TypeDictionary traits = new TypeDictionary(); readonly TypeDictionary traits = new();
List<TraitInfo> constructOrderCache = null; List<TraitInfo> constructOrderCache = null;
public ActorInfo(ObjectCreator creator, string name, MiniYaml node) public ActorInfo(ObjectCreator creator, string name, MiniYaml node)

View File

@@ -17,14 +17,14 @@ namespace OpenRA.GameRules
{ {
public class SoundInfo public class SoundInfo
{ {
public readonly Dictionary<string, string[]> Variants = new Dictionary<string, string[]>(); public readonly Dictionary<string, string[]> Variants = new();
public readonly Dictionary<string, string[]> Prefixes = new Dictionary<string, string[]>(); public readonly Dictionary<string, string[]> Prefixes = new();
public readonly Dictionary<string, string[]> Voices = new Dictionary<string, string[]>(); public readonly Dictionary<string, string[]> Voices = new();
public readonly Dictionary<string, string[]> Notifications = new Dictionary<string, string[]>(); public readonly Dictionary<string, string[]> Notifications = new();
public readonly string DefaultVariant = ".aud"; public readonly string DefaultVariant = ".aud";
public readonly string DefaultPrefix = ""; public readonly string DefaultPrefix = "";
public readonly HashSet<string> DisableVariants = new HashSet<string>(); public readonly HashSet<string> DisableVariants = new();
public readonly HashSet<string> DisablePrefixes = new HashSet<string>(); public readonly HashSet<string> DisablePrefixes = new();
public readonly Lazy<Dictionary<string, SoundPool>> VoicePools; public readonly Lazy<Dictionary<string, SoundPool>> VoicePools;
public readonly Lazy<Dictionary<string, SoundPool>> NotificationsPools; public readonly Lazy<Dictionary<string, SoundPool>> NotificationsPools;
@@ -69,7 +69,7 @@ namespace OpenRA.GameRules
public readonly float VolumeModifier; public readonly float VolumeModifier;
public readonly InterruptType Type; public readonly InterruptType Type;
readonly string[] clips; readonly string[] clips;
readonly List<string> liveclips = new List<string>(); readonly List<string> liveclips = new();
public SoundPool(float volumeModifier, InterruptType interruptType, params string[] clips) public SoundPool(float volumeModifier, InterruptType interruptType, params string[] clips)
{ {

View File

@@ -103,16 +103,16 @@ namespace OpenRA.GameRules
public readonly bool CanTargetSelf = false; public readonly bool CanTargetSelf = false;
[Desc("What types of targets are affected.")] [Desc("What types of targets are affected.")]
public readonly BitSet<TargetableType> ValidTargets = new BitSet<TargetableType>("Ground", "Water"); public readonly BitSet<TargetableType> ValidTargets = new("Ground", "Water");
[Desc("What types of targets are unaffected.", "Overrules ValidTargets.")] [Desc("What types of targets are unaffected.", "Overrules ValidTargets.")]
public readonly BitSet<TargetableType> InvalidTargets; public readonly BitSet<TargetableType> InvalidTargets;
static readonly BitSet<TargetableType> TargetTypeAir = new BitSet<TargetableType>("Air"); static readonly BitSet<TargetableType> TargetTypeAir = new("Air");
[Desc("If weapon is not directly targeting an actor and targeted position is above this altitude,", [Desc("If weapon is not directly targeting an actor and targeted position is above this altitude,",
"the weapon will ignore terrain target types and only check TargetTypeAir for validity.")] "the weapon will ignore terrain target types and only check TargetTypeAir for validity.")]
public readonly WDist AirThreshold = new WDist(128); public readonly WDist AirThreshold = new(128);
[Desc("Delay in ticks between firing shots from the same ammo magazine. If one entry, it will be used for all bursts.", [Desc("Delay in ticks between firing shots from the same ammo magazine. If one entry, it will be used for all bursts.",
"If multiple entries, their number needs to match Burst - 1.")] "If multiple entries, their number needs to match Burst - 1.")]
@@ -128,7 +128,7 @@ namespace OpenRA.GameRules
public readonly IProjectileInfo Projectile; public readonly IProjectileInfo Projectile;
[FieldLoader.LoadUsing(nameof(LoadWarheads))] [FieldLoader.LoadUsing(nameof(LoadWarheads))]
public readonly List<IWarhead> Warheads = new List<IWarhead>(); public readonly List<IWarhead> Warheads = new();
/// <summary> /// <summary>
/// This constructor is used solely for documentation generation. /// This constructor is used solely for documentation generation.

View File

@@ -49,7 +49,7 @@ namespace OpenRA.Graphics
public readonly int[] PanelRegion = null; public readonly int[] PanelRegion = null;
public readonly PanelSides PanelSides = PanelSides.All; public readonly PanelSides PanelSides = PanelSides.All;
public readonly Dictionary<string, Rectangle> Regions = new Dictionary<string, Rectangle>(); public readonly Dictionary<string, Rectangle> Regions = new();
} }
public static IReadOnlyDictionary<string, Collection> Collections => collections; public static IReadOnlyDictionary<string, Collection> Collections => collections;

View File

@@ -28,7 +28,7 @@ namespace OpenRA.Graphics
public IHardwareCursor[] Cursors; public IHardwareCursor[] Cursors;
} }
readonly Dictionary<string, Cursor> cursors = new Dictionary<string, Cursor>(); readonly Dictionary<string, Cursor> cursors = new();
readonly SheetBuilder sheetBuilder; readonly SheetBuilder sheetBuilder;
readonly GraphicSettings graphicSettings; readonly GraphicSettings graphicSettings;

View File

@@ -21,9 +21,9 @@ namespace OpenRA.Graphics
public ITexture ColorShifts { get; } public ITexture ColorShifts { get; }
public int Height { get; private set; } public int Height { get; private set; }
readonly Dictionary<string, ImmutablePalette> palettes = new Dictionary<string, ImmutablePalette>(); readonly Dictionary<string, ImmutablePalette> palettes = new();
readonly Dictionary<string, MutablePalette> mutablePalettes = new Dictionary<string, MutablePalette>(); readonly Dictionary<string, MutablePalette> mutablePalettes = new();
readonly Dictionary<string, int> indices = new Dictionary<string, int>(); readonly Dictionary<string, int> indices = new();
byte[] buffer = Array.Empty<byte>(); byte[] buffer = Array.Empty<byte>();
float[] colorShiftBuffer = Array.Empty<float>(); float[] colorShiftBuffer = Array.Empty<float>();

View File

@@ -37,7 +37,7 @@ namespace OpenRA.Graphics
// Static constants // Static constants
static readonly float[] ShadowDiffuse = new float[] { 0, 0, 0 }; static readonly float[] ShadowDiffuse = new float[] { 0, 0, 0 };
static readonly float[] ShadowAmbient = new float[] { 1, 1, 1 }; static readonly float[] ShadowAmbient = new float[] { 1, 1, 1 };
static readonly float2 SpritePadding = new float2(2, 2); static readonly float2 SpritePadding = new(2, 2);
static readonly float[] ZeroVector = new float[] { 0, 0, 0, 1 }; static readonly float[] ZeroVector = new float[] { 0, 0, 0, 1 };
static readonly float[] ZVector = new float[] { 0, 0, 1, 1 }; static readonly float[] ZVector = new float[] { 0, 0, 1, 1 };
static readonly float[] FlipMtx = Util.ScaleMatrix(1, -1, 1); static readonly float[] FlipMtx = Util.ScaleMatrix(1, -1, 1);
@@ -47,9 +47,9 @@ namespace OpenRA.Graphics
readonly Renderer renderer; readonly Renderer renderer;
readonly IShader shader; readonly IShader shader;
readonly Dictionary<Sheet, IFrameBuffer> mappedBuffers = new Dictionary<Sheet, IFrameBuffer>(); readonly Dictionary<Sheet, IFrameBuffer> mappedBuffers = new();
readonly Stack<KeyValuePair<Sheet, IFrameBuffer>> unmappedBuffers = new Stack<KeyValuePair<Sheet, IFrameBuffer>>(); readonly Stack<KeyValuePair<Sheet, IFrameBuffer>> unmappedBuffers = new();
readonly List<(Sheet Sheet, Action Func)> doRender = new List<(Sheet, Action)>(); readonly List<(Sheet Sheet, Action Func)> doRender = new();
SheetBuilder sheetBuilderForFrame; SheetBuilder sheetBuilderForFrame;
bool isInFrame; bool isInFrame;

View File

@@ -18,7 +18,7 @@ namespace OpenRA.Graphics
{ {
public class RgbaColorRenderer public class RgbaColorRenderer
{ {
static readonly float3 Offset = new float3(0.5f, 0.5f, 0f); static readonly float3 Offset = new(0.5f, 0.5f, 0f);
readonly SpriteRenderer parent; readonly SpriteRenderer parent;
readonly Vertex[] vertices = new Vertex[6]; readonly Vertex[] vertices = new Vertex[6];

View File

@@ -34,7 +34,7 @@ namespace OpenRA.Graphics
public sealed class SheetBuilder : IDisposable public sealed class SheetBuilder : IDisposable
{ {
public readonly SheetType Type; public readonly SheetType Type;
readonly List<Sheet> sheets = new List<Sheet>(); readonly List<Sheet> sheets = new();
readonly Func<Sheet> allocateSheet; readonly Func<Sheet> allocateSheet;
readonly int margin; readonly int margin;
int rowHeight = 0; int rowHeight = 0;

View File

@@ -24,14 +24,14 @@ namespace OpenRA.Graphics
readonly ISpriteLoader[] loaders; readonly ISpriteLoader[] loaders;
readonly IReadOnlyFileSystem fileSystem; readonly IReadOnlyFileSystem fileSystem;
readonly Dictionary<int, (int[] Frames, MiniYamlNode.SourceLocation Location)> spriteReservations = new Dictionary<int, (int[], MiniYamlNode.SourceLocation)>(); readonly Dictionary<int, (int[] Frames, MiniYamlNode.SourceLocation Location)> spriteReservations = new();
readonly Dictionary<int, (int[] Frames, MiniYamlNode.SourceLocation Location)> frameReservations = new Dictionary<int, (int[], MiniYamlNode.SourceLocation)>(); readonly Dictionary<int, (int[] Frames, MiniYamlNode.SourceLocation Location)> frameReservations = new();
readonly Dictionary<string, List<int>> reservationsByFilename = new Dictionary<string, List<int>>(); readonly Dictionary<string, List<int>> reservationsByFilename = new();
readonly Dictionary<int, ISpriteFrame[]> resolvedFrames = new Dictionary<int, ISpriteFrame[]>(); readonly Dictionary<int, ISpriteFrame[]> resolvedFrames = new();
readonly Dictionary<int, Sprite[]> resolvedSprites = new Dictionary<int, Sprite[]>(); readonly Dictionary<int, Sprite[]> resolvedSprites = new();
readonly Dictionary<int, (string Filename, MiniYamlNode.SourceLocation Location)> missingFiles = new Dictionary<int, (string, MiniYamlNode.SourceLocation)>(); readonly Dictionary<int, (string Filename, MiniYamlNode.SourceLocation Location)> missingFiles = new();
int nextReservationToken = 1; int nextReservationToken = 1;

View File

@@ -27,7 +27,7 @@ namespace OpenRA.Graphics
readonly IVertexBuffer<Vertex> vertexBuffer; readonly IVertexBuffer<Vertex> vertexBuffer;
readonly Vertex[] vertices; readonly Vertex[] vertices;
readonly bool[] ignoreTint; readonly bool[] ignoreTint;
readonly HashSet<int> dirtyRows = new HashSet<int>(); readonly HashSet<int> dirtyRows = new();
readonly int rowStride; readonly int rowStride;
readonly bool restrictToBounds; readonly bool restrictToBounds;

View File

@@ -53,7 +53,7 @@ namespace OpenRA.Graphics
public WPos CenterPosition => worldRenderer.ProjectedPosition(CenterLocation); public WPos CenterPosition => worldRenderer.ProjectedPosition(CenterLocation);
public Rectangle Rectangle => new Rectangle(TopLeft, new Size(viewportSize.X, viewportSize.Y)); public Rectangle Rectangle => new(TopLeft, new Size(viewportSize.X, viewportSize.Y));
public int2 TopLeft => CenterLocation - viewportSize / 2; public int2 TopLeft => CenterLocation - viewportSize / 2;
public int2 BottomRight => CenterLocation + viewportSize / 2; public int2 BottomRight => CenterLocation + viewportSize / 2;
int2 viewportSize; int2 viewportSize;

View File

@@ -31,19 +31,19 @@ namespace OpenRA.Graphics
public event Action PaletteInvalidated = null; public event Action PaletteInvalidated = null;
readonly HashSet<Actor> onScreenActors = new HashSet<Actor>(); readonly HashSet<Actor> onScreenActors = new();
readonly HardwarePalette palette = new HardwarePalette(); readonly HardwarePalette palette = new();
readonly Dictionary<string, PaletteReference> palettes = new Dictionary<string, PaletteReference>(); readonly Dictionary<string, PaletteReference> palettes = new();
readonly IRenderTerrain terrainRenderer; readonly IRenderTerrain terrainRenderer;
readonly Lazy<DebugVisualizations> debugVis; readonly Lazy<DebugVisualizations> debugVis;
readonly Func<string, PaletteReference> createPaletteReference; readonly Func<string, PaletteReference> createPaletteReference;
readonly bool enableDepthBuffer; readonly bool enableDepthBuffer;
readonly List<IFinalizedRenderable> preparedRenderables = new List<IFinalizedRenderable>(); readonly List<IFinalizedRenderable> preparedRenderables = new();
readonly List<IFinalizedRenderable> preparedOverlayRenderables = new List<IFinalizedRenderable>(); readonly List<IFinalizedRenderable> preparedOverlayRenderables = new();
readonly List<IFinalizedRenderable> preparedAnnotationRenderables = new List<IFinalizedRenderable>(); readonly List<IFinalizedRenderable> preparedAnnotationRenderables = new();
readonly List<IRenderable> renderablesBuffer = new List<IRenderable>(); readonly List<IRenderable> renderablesBuffer = new();
internal WorldRenderer(ModData modData, World world) internal WorldRenderer(ModData modData, World world)
{ {

View File

@@ -19,8 +19,8 @@ namespace OpenRA
public readonly string Name; public readonly string Name;
public readonly Hotkey Default = Hotkey.Invalid; public readonly Hotkey Default = Hotkey.Invalid;
public readonly string Description = ""; public readonly string Description = "";
public readonly HashSet<string> Types = new HashSet<string>(); public readonly HashSet<string> Types = new();
public readonly HashSet<string> Contexts = new HashSet<string>(); public readonly HashSet<string> Contexts = new();
public readonly bool Readonly = false; public readonly bool Readonly = false;
public bool HasDuplicates { get; internal set; } public bool HasDuplicates { get; internal set; }

View File

@@ -18,8 +18,8 @@ namespace OpenRA
public sealed class HotkeyManager public sealed class HotkeyManager
{ {
readonly Dictionary<string, Hotkey> settings; readonly Dictionary<string, Hotkey> settings;
readonly Dictionary<string, HotkeyDefinition> definitions = new Dictionary<string, HotkeyDefinition>(); readonly Dictionary<string, HotkeyDefinition> definitions = new();
readonly Dictionary<string, Hotkey> keys = new Dictionary<string, Hotkey>(); readonly Dictionary<string, Hotkey> keys = new();
public HotkeyManager(IReadOnlyFileSystem fileSystem, Dictionary<string, Hotkey> settings, Manifest manifest) public HotkeyManager(IReadOnlyFileSystem fileSystem, Dictionary<string, Hotkey> settings, Manifest manifest)
{ {
@@ -102,7 +102,7 @@ namespace OpenRA
return null; return null;
} }
public HotkeyReference this[string name] => new HotkeyReference(GetHotkeyReference(name)); public HotkeyReference this[string name] => new(GetHotkeyReference(name));
public IEnumerable<HotkeyDefinition> Definitions => definitions.Values; public IEnumerable<HotkeyDefinition> Definitions => definitions.Values;
} }

View File

@@ -19,15 +19,13 @@ namespace OpenRA
public class Utility public class Utility
{ {
static readonly ConcurrentCache<Type, FieldInfo[]> TypeFields = static readonly ConcurrentCache<Type, FieldInfo[]> TypeFields =
new ConcurrentCache<Type, FieldInfo[]>(type => type.GetFields()); new(type => type.GetFields());
static readonly ConcurrentCache<(MemberInfo Member, Type AttributeType), bool> MemberHasAttribute = static readonly ConcurrentCache<(MemberInfo Member, Type AttributeType), bool> MemberHasAttribute =
new ConcurrentCache<(MemberInfo Member, Type AttributeType), bool>( new(x => Attribute.IsDefined(x.Member, x.AttributeType));
x => Attribute.IsDefined(x.Member, x.AttributeType));
static readonly ConcurrentCache<(MemberInfo Member, Type AttributeType, bool Inherit), object[]> MemberCustomAttributes = static readonly ConcurrentCache<(MemberInfo Member, Type AttributeType, bool Inherit), object[]> MemberCustomAttributes =
new ConcurrentCache<(MemberInfo Member, Type AttributeType, bool Inherit), object[]>( new(x => x.Member.GetCustomAttributes(x.AttributeType, x.Inherit));
x => x.Member.GetCustomAttributes(x.AttributeType, x.Inherit));
public static FieldInfo[] GetFields(Type type) public static FieldInfo[] GetFields(Type type)
{ {

View File

@@ -15,7 +15,7 @@ namespace OpenRA
{ {
public readonly struct Hotkey : IEquatable<Hotkey> public readonly struct Hotkey : IEquatable<Hotkey>
{ {
public static Hotkey Invalid = new Hotkey(Keycode.UNKNOWN, Modifiers.None); public static Hotkey Invalid = new(Keycode.UNKNOWN, Modifiers.None);
public bool IsValid() public bool IsValid()
{ {
return Key != Keycode.UNKNOWN; return Key != Keycode.UNKNOWN;

View File

@@ -256,7 +256,7 @@ namespace OpenRA
public static class KeycodeExts public static class KeycodeExts
{ {
static readonly Dictionary<Keycode, string> KeyNames = new Dictionary<Keycode, string> static readonly Dictionary<Keycode, string> KeyNames = new()
{ {
{ Keycode.UNKNOWN, "Undefined" }, { Keycode.UNKNOWN, "Undefined" },
{ Keycode.RETURN, "Return" }, { Keycode.RETURN, "Return" },

View File

@@ -19,7 +19,7 @@ namespace OpenRA
public readonly int U, V; public readonly int U, V;
public MPos(int u, int v) { U = u; V = v; } public MPos(int u, int v) { U = u; V = v; }
public static readonly MPos Zero = new MPos(0, 0); public static readonly MPos Zero = new(0, 0);
public static bool operator ==(MPos me, MPos other) { return me.U == other.U && me.V == other.V; } public static bool operator ==(MPos me, MPos other) { return me.U == other.U && me.V == other.V; }
public static bool operator !=(MPos me, MPos other) { return !(me == other); } public static bool operator !=(MPos me, MPos other) { return !(me == other); }
@@ -71,7 +71,7 @@ namespace OpenRA
public readonly int U, V; public readonly int U, V;
public PPos(int u, int v) { U = u; V = v; } public PPos(int u, int v) { U = u; V = v; }
public static readonly PPos Zero = new PPos(0, 0); public static readonly PPos Zero = new(0, 0);
public static bool operator ==(PPos me, PPos other) { return me.U == other.U && me.V == other.V; } public static bool operator ==(PPos me, PPos other) { return me.U == other.U && me.V == other.V; }
public static bool operator !=(PPos me, PPos other) { return !(me == other); } public static bool operator !=(PPos me, PPos other) { return !(me == other); }

View File

@@ -95,7 +95,7 @@ namespace OpenRA
"RequiresMods", "PackageFormats" "RequiresMods", "PackageFormats"
}; };
readonly TypeDictionary modules = new TypeDictionary(); readonly TypeDictionary modules = new();
readonly Dictionary<string, MiniYaml> yaml; readonly Dictionary<string, MiniYaml> yaml;
bool customDataLoaded; bool customDataLoaded;

View File

@@ -102,7 +102,7 @@ namespace OpenRA
return uv.U >= mapTopLeft.U && uv.U <= mapBottomRight.U && uv.V >= mapTopLeft.V && uv.V <= mapBottomRight.V; return uv.U >= mapTopLeft.U && uv.U <= mapBottomRight.U && uv.V >= mapTopLeft.V && uv.V <= mapBottomRight.V;
} }
public MapCoordsRegion MapCoords => new MapCoordsRegion(mapTopLeft, mapBottomRight); public MapCoordsRegion MapCoords => new(mapTopLeft, mapBottomRight);
public CellRegionEnumerator GetEnumerator() public CellRegionEnumerator GetEnumerator()
{ {

View File

@@ -198,8 +198,8 @@ namespace OpenRA
public int2 MapSize { get; private set; } public int2 MapSize { get; private set; }
// Player and actor yaml. Public for access by the map importers and lint checks. // Player and actor yaml. Public for access by the map importers and lint checks.
public List<MiniYamlNode> PlayerDefinitions = new List<MiniYamlNode>(); public List<MiniYamlNode> PlayerDefinitions = new();
public List<MiniYamlNode> ActorDefinitions = new List<MiniYamlNode>(); public List<MiniYamlNode> ActorDefinitions = new();
// Custom map yaml. Public for access by the map importers and lint checks // Custom map yaml. Public for access by the map importers and lint checks
public readonly MiniYaml RuleDefinitions; public readonly MiniYaml RuleDefinitions;
@@ -210,7 +210,7 @@ namespace OpenRA
public readonly MiniYaml MusicDefinitions; public readonly MiniYaml MusicDefinitions;
public readonly MiniYaml NotificationDefinitions; public readonly MiniYaml NotificationDefinitions;
public readonly Dictionary<CPos, TerrainTile> ReplacedInvalidTerrainTiles = new Dictionary<CPos, TerrainTile>(); public readonly Dictionary<CPos, TerrainTile> ReplacedInvalidTerrainTiles = new();
// Generated data // Generated data
public readonly MapGrid Grid; public readonly MapGrid Grid;
@@ -997,7 +997,7 @@ namespace OpenRA
/// </summary> /// </summary>
/// RectangularIsometric defines 1024 units along the diagonal axis, /// RectangularIsometric defines 1024 units along the diagonal axis,
/// giving a half-tile height step of sqrt(2) * 512 /// giving a half-tile height step of sqrt(2) * 512
public WDist CellHeightStep => new WDist(Grid.Type == MapGridType.RectangularIsometric ? 724 : 512); public WDist CellHeightStep => new(Grid.Type == MapGridType.RectangularIsometric ? 724 : 512);
public CPos CellContaining(WPos pos) public CPos CellContaining(WPos pos)
{ {

View File

@@ -25,9 +25,9 @@ namespace OpenRA
{ {
public sealed class MapCache : IEnumerable<MapPreview>, IDisposable public sealed class MapCache : IEnumerable<MapPreview>, IDisposable
{ {
public static readonly MapPreview UnknownMap = new MapPreview(null, null, MapGridType.Rectangular, null); public static readonly MapPreview UnknownMap = new(null, null, MapGridType.Rectangular, null);
public IReadOnlyDictionary<IReadOnlyPackage, MapClassification> MapLocations => mapLocations; public IReadOnlyDictionary<IReadOnlyPackage, MapClassification> MapLocations => mapLocations;
readonly Dictionary<IReadOnlyPackage, MapClassification> mapLocations = new Dictionary<IReadOnlyPackage, MapClassification>(); readonly Dictionary<IReadOnlyPackage, MapClassification> mapLocations = new();
public bool LoadPreviewImages = true; public bool LoadPreviewImages = true;
readonly Cache<string, MapPreview> previews; readonly Cache<string, MapPreview> previews;
@@ -35,18 +35,18 @@ namespace OpenRA
readonly SheetBuilder sheetBuilder; readonly SheetBuilder sheetBuilder;
Thread previewLoaderThread; Thread previewLoaderThread;
bool previewLoaderThreadShutDown = true; bool previewLoaderThreadShutDown = true;
readonly object syncRoot = new object(); readonly object syncRoot = new();
readonly Queue<MapPreview> generateMinimap = new Queue<MapPreview>(); readonly Queue<MapPreview> generateMinimap = new();
public Dictionary<string, string> StringPool { get; } = new Dictionary<string, string>(); public Dictionary<string, string> StringPool { get; } = new Dictionary<string, string>();
readonly List<MapDirectoryTracker> mapDirectoryTrackers = new List<MapDirectoryTracker>(); readonly List<MapDirectoryTracker> mapDirectoryTrackers = new();
/// <summary> /// <summary>
/// The most recently modified or loaded map at runtime. /// The most recently modified or loaded map at runtime.
/// </summary> /// </summary>
public string LastModifiedMap { get; private set; } = null; public string LastModifiedMap { get; private set; } = null;
readonly Dictionary<string, string> mapUpdates = new Dictionary<string, string>(); readonly Dictionary<string, string> mapUpdates = new();
string lastLoadedLastModifiedMap; string lastLoadedLastModifiedMap;

View File

@@ -25,7 +25,7 @@ namespace OpenRA
readonly MapClassification classification; readonly MapClassification classification;
enum MapAction { Add, Delete, Update } enum MapAction { Add, Delete, Update }
readonly Dictionary<string, MapAction> mapActionQueue = new Dictionary<string, MapAction>(); readonly Dictionary<string, MapAction> mapActionQueue = new();
bool dirty = false; bool dirty = false;

View File

@@ -106,7 +106,7 @@ namespace OpenRA
public class MapGrid : IGlobalModData public class MapGrid : IGlobalModData
{ {
public readonly MapGridType Type = MapGridType.Rectangular; public readonly MapGridType Type = MapGridType.Rectangular;
public readonly Size TileSize = new Size(24, 24); public readonly Size TileSize = new(24, 24);
public readonly byte MaximumTerrainHeight = 0; public readonly byte MaximumTerrainHeight = 0;
public readonly SubCell DefaultSubCell = (SubCell)byte.MaxValue; public readonly SubCell DefaultSubCell = (SubCell)byte.MaxValue;

View File

@@ -59,7 +59,7 @@ namespace OpenRA
/// this does not validate whether individual map cells are actually /// this does not validate whether individual map cells are actually
/// projected inside the region. /// projected inside the region.
/// </summary> /// </summary>
public MapCoordsRegion CandidateMapCoords => new MapCoordsRegion(mapTopLeft, mapBottomRight); public MapCoordsRegion CandidateMapCoords => new(mapTopLeft, mapBottomRight);
public ProjectedCellRegionEnumerator GetEnumerator() public ProjectedCellRegionEnumerator GetEnumerator()
{ {

View File

@@ -60,7 +60,7 @@ namespace OpenRA
{ {
public readonly string Type; public readonly string Type;
public readonly BitSet<TargetableType> TargetTypes; public readonly BitSet<TargetableType> TargetTypes;
public readonly HashSet<string> AcceptsSmudgeType = new HashSet<string>(); public readonly HashSet<string> AcceptsSmudgeType = new();
public readonly Color Color; public readonly Color Color;
public readonly bool RestrictPlayerColor = false; public readonly bool RestrictPlayerColor = false;

View File

@@ -42,9 +42,9 @@ namespace OpenRA.Network
public sealed class EchoConnection : IConnection public sealed class EchoConnection : IConnection
{ {
const int LocalClientId = 1; const int LocalClientId = 1;
readonly Queue<(int Frame, int SyncHash, ulong DefeatState)> sync = new Queue<(int, int, ulong)>(); readonly Queue<(int Frame, int SyncHash, ulong DefeatState)> sync = new();
readonly Queue<(int Frame, OrderPacket Orders)> orders = new Queue<(int, OrderPacket)>(); readonly Queue<(int Frame, OrderPacket Orders)> orders = new();
readonly Queue<OrderPacket> immediateOrders = new Queue<OrderPacket>(); readonly Queue<OrderPacket> immediateOrders = new();
bool disposed; bool disposed;
int IConnection.LocalClientId => LocalClientId; int IConnection.LocalClientId => LocalClientId;
@@ -100,12 +100,12 @@ namespace OpenRA.Network
{ {
public readonly ConnectionTarget Target; public readonly ConnectionTarget Target;
internal ReplayRecorder Recorder { get; private set; } internal ReplayRecorder Recorder { get; private set; }
readonly Queue<(int Frame, int SyncHash, ulong DefeatState)> sentSync = new Queue<(int, int, ulong)>(); readonly Queue<(int Frame, int SyncHash, ulong DefeatState)> sentSync = new();
readonly Queue<(int Frame, int SyncHash, ulong DefeatState)> queuedSyncPackets = new Queue<(int, int, ulong)>(); readonly Queue<(int Frame, int SyncHash, ulong DefeatState)> queuedSyncPackets = new();
readonly Queue<(int Frame, OrderPacket Orders)> sentOrders = new Queue<(int, OrderPacket)>(); readonly Queue<(int Frame, OrderPacket Orders)> sentOrders = new();
readonly Queue<OrderPacket> sentImmediateOrders = new Queue<OrderPacket>(); readonly Queue<OrderPacket> sentImmediateOrders = new();
readonly ConcurrentQueue<(int FromClient, byte[] Data)> receivedPackets = new ConcurrentQueue<(int, byte[])>(); readonly ConcurrentQueue<(int FromClient, byte[] Data)> receivedPackets = new();
TcpClient tcp; TcpClient tcp;
volatile ConnectionState connectionState = ConnectionState.Connecting; volatile ConnectionState connectionState = ConnectionState.Connecting;
volatile int clientId; volatile int clientId;

View File

@@ -81,7 +81,7 @@ namespace OpenRA.Network
public const int MetadataMarker = -1; public const int MetadataMarker = -1;
public const int TraitDataMarker = -3; public const int TraitDataMarker = -3;
readonly MemoryStream ordersStream = new MemoryStream(); readonly MemoryStream ordersStream = new();
// Loaded from file and updated during gameplay // Loaded from file and updated during gameplay
public int LastOrdersFrame { get; private set; } public int LastOrdersFrame { get; private set; }
@@ -92,7 +92,7 @@ namespace OpenRA.Network
public Session.Global GlobalSettings { get; private set; } public Session.Global GlobalSettings { get; private set; }
public Dictionary<string, Session.Slot> Slots { get; private set; } public Dictionary<string, Session.Slot> Slots { get; private set; }
public Dictionary<string, SlotClient> SlotClients { get; private set; } public Dictionary<string, SlotClient> SlotClients { get; private set; }
public Dictionary<int, MiniYaml> TraitData = new Dictionary<int, MiniYaml>(); public Dictionary<int, MiniYaml> TraitData = new();
// Set on game start // Set on game start
int[] clientsBySlotIndex = Array.Empty<int>(); int[] clientsBySlotIndex = Array.Empty<int>();

View File

@@ -39,7 +39,7 @@ namespace OpenRA.Network
initialized = true; initialized = true;
} }
static readonly SemaphoreSlim Locker = new SemaphoreSlim(1, 1); static readonly SemaphoreSlim Locker = new(1, 1);
static async void DeviceFound(object sender, DeviceEventArgs args) static async void DeviceFound(object sender, DeviceEventArgs args)
{ {

View File

@@ -78,7 +78,7 @@ namespace OpenRA.Network
public static class OrderIO public static class OrderIO
{ {
static readonly OrderPacket NoOrders = new OrderPacket(Array.Empty<Order>()); static readonly OrderPacket NoOrders = new(Array.Empty<Order>());
public static byte[] SerializeSync((int Frame, int SyncHash, ulong DefeatState) data) public static byte[] SerializeSync((int Frame, int SyncHash, ulong DefeatState) data)
{ {

View File

@@ -23,10 +23,10 @@ namespace OpenRA.Network
const OrderPacket ClientDisconnected = null; const OrderPacket ClientDisconnected = null;
readonly SyncReport syncReport; readonly SyncReport syncReport;
readonly Dictionary<int, Queue<(int Frame, OrderPacket Orders)>> pendingOrders = new Dictionary<int, Queue<(int, OrderPacket)>>(); readonly Dictionary<int, Queue<(int Frame, OrderPacket Orders)>> pendingOrders = new();
readonly Dictionary<int, (int SyncHash, ulong DefeatState)> syncForFrame = new Dictionary<int, (int, ulong)>(); readonly Dictionary<int, (int SyncHash, ulong DefeatState)> syncForFrame = new();
public Session LobbyInfo = new Session(); public Session LobbyInfo = new();
/// <summary>Null when watching a replay.</summary> /// <summary>Null when watching a replay.</summary>
public Session.Client LocalClient => LobbyInfo.ClientWithIndex(Connection.LocalClientId); public Session.Client LocalClient => LobbyInfo.ClientWithIndex(Connection.LocalClientId);
@@ -47,11 +47,11 @@ namespace OpenRA.Network
internal int GameSaveLastFrame = -1; internal int GameSaveLastFrame = -1;
internal int GameSaveLastSyncFrame = -1; internal int GameSaveLastSyncFrame = -1;
readonly List<Order> localOrders = new List<Order>(); readonly List<Order> localOrders = new();
readonly List<Order> localImmediateOrders = new List<Order>(); readonly List<Order> localImmediateOrders = new();
readonly List<ClientOrder> processClientOrders = new List<ClientOrder>(); readonly List<ClientOrder> processClientOrders = new();
readonly List<int> processClientsToRemove = new List<int>(); readonly List<int> processClientsToRemove = new();
bool disposed; bool disposed;
bool generateSyncReport = false; bool generateSyncReport = false;

View File

@@ -24,8 +24,8 @@ namespace OpenRA.Network
public (int ClientId, byte[] Packet)[] Packets; public (int ClientId, byte[] Packet)[] Packets;
} }
readonly Queue<Chunk> chunks = new Queue<Chunk>(); readonly Queue<Chunk> chunks = new();
readonly Queue<(int Frame, int SyncHash, ulong DefeatState)> sync = new Queue<(int, int, ulong)>(); readonly Queue<(int Frame, int SyncHash, ulong DefeatState)> sync = new();
readonly int orderLatency; readonly int orderLatency;
public readonly int TickCount; public readonly int TickCount;

View File

@@ -24,7 +24,7 @@ namespace OpenRA.Network
public ReplayMetadata Metadata; public ReplayMetadata Metadata;
BinaryWriter writer; BinaryWriter writer;
readonly Func<string> chooseFilename; readonly Func<string> chooseFilename;
MemoryStream preStartBuffer = new MemoryStream(); MemoryStream preStartBuffer = new();
static bool IsGameStart(byte[] data) static bool IsGameStart(byte[] data)
{ {

View File

@@ -20,14 +20,14 @@ namespace OpenRA.Network
{ {
public class Session public class Session
{ {
public List<Client> Clients = new List<Client>(); public List<Client> Clients = new();
// Keyed by the PlayerReference id that the slot corresponds to // Keyed by the PlayerReference id that the slot corresponds to
public Dictionary<string, Slot> Slots = new Dictionary<string, Slot>(); public Dictionary<string, Slot> Slots = new();
public HashSet<int> DisabledSpawnPoints = new HashSet<int>(); public HashSet<int> DisabledSpawnPoints = new();
public Global GlobalSettings = new Global(); public Global GlobalSettings = new();
public static string AnonymizeIP(IPAddress ip) public static string AnonymizeIP(IPAddress ip)
{ {
@@ -221,7 +221,7 @@ namespace OpenRA.Network
public int NetFrameInterval = 3; public int NetFrameInterval = 3;
[FieldLoader.Ignore] [FieldLoader.Ignore]
public Dictionary<string, LobbyOptionState> LobbyOptions = new Dictionary<string, LobbyOptionState>(); public Dictionary<string, LobbyOptionState> LobbyOptions = new();
public static Global Deserialize(MiniYaml data) public static Global Deserialize(MiniYaml data)
{ {

View File

@@ -22,7 +22,7 @@ namespace OpenRA.Network
class SyncReport class SyncReport
{ {
const int NumSyncReports = 7; const int NumSyncReports = 7;
static readonly Cache<Type, TypeInfo> TypeInfoCache = new Cache<Type, TypeInfo>(t => new TypeInfo(t)); static readonly Cache<Type, TypeInfo> TypeInfoCache = new(t => new TypeInfo(t));
readonly OrderManager orderManager; readonly OrderManager orderManager;
@@ -166,9 +166,9 @@ namespace OpenRA.Network
public int Frame; public int Frame;
public int SyncedRandom; public int SyncedRandom;
public int TotalCount; public int TotalCount;
public readonly List<TraitReport> Traits = new List<TraitReport>(); public readonly List<TraitReport> Traits = new();
public readonly List<EffectReport> Effects = new List<EffectReport>(); public readonly List<EffectReport> Effects = new();
public readonly List<OrderManager.ClientOrder> Orders = new List<OrderManager.ClientOrder>(); public readonly List<OrderManager.ClientOrder> Orders = new();
} }
struct TraitReport struct TraitReport
@@ -278,7 +278,7 @@ namespace OpenRA.Network
/// </summary> /// </summary>
struct Values struct Values
{ {
static readonly object Sentinel = new object(); static readonly object Sentinel = new();
object item1OrArray; object item1OrArray;
object item2OrSentinel; object item2OrSentinel;

View File

@@ -22,7 +22,7 @@ namespace OpenRA
{ {
// .NET does not support unloading assemblies, so mod libraries will leak across mod changes. // .NET does not support unloading assemblies, so mod libraries will leak across mod changes.
// This tracks the assemblies that have been loaded since game start so that we don't load multiple copies // This tracks the assemblies that have been loaded since game start so that we don't load multiple copies
static readonly Dictionary<string, Assembly> ResolvedAssemblies = new Dictionary<string, Assembly>(); static readonly Dictionary<string, Assembly> ResolvedAssemblies = new();
readonly Cache<string, Type> typeCache; readonly Cache<string, Type> typeCache;
readonly Cache<Type, ConstructorInfo> ctorCache; readonly Cache<Type, ConstructorInfo> ctorCache;

View File

@@ -19,7 +19,7 @@ namespace OpenRA.Primitives
/// </summary> /// </summary>
public class ActionQueue public class ActionQueue
{ {
readonly List<DelayedAction> actions = new List<DelayedAction>(); readonly List<DelayedAction> actions = new();
public void Add(Action a, long desiredTime) public void Add(Action a, long desiredTime)
{ {

View File

@@ -18,7 +18,7 @@ namespace OpenRA.Primitives
{ {
static class BitSetAllocator<T> where T : class static class BitSetAllocator<T> where T : class
{ {
static readonly Cache<string, BitSetIndex> Bits = new Cache<string, BitSetIndex>(Allocate); static readonly Cache<string, BitSetIndex> Bits = new(Allocate);
static BitSetIndex nextBits = 1; static BitSetIndex nextBits = 1;
static BitSetIndex Allocate(string value) static BitSetIndex Allocate(string value)

View File

@@ -17,7 +17,7 @@ namespace OpenRA.Primitives
{ {
static class LongBitSetAllocator<T> where T : class static class LongBitSetAllocator<T> where T : class
{ {
static readonly Cache<string, long> Bits = new Cache<string, long>(Allocate); static readonly Cache<string, long> Bits = new(Allocate);
static long nextBits = 1; static long nextBits = 1;
static long Allocate(string value) static long Allocate(string value)

View File

@@ -16,7 +16,7 @@ namespace OpenRA.Primitives
{ {
public readonly struct Polygon public readonly struct Polygon
{ {
public static readonly Polygon Empty = new Polygon(Rectangle.Empty); public static readonly Polygon Empty = new(Rectangle.Empty);
public readonly Rectangle BoundingRect; public readonly Rectangle BoundingRect;
public readonly int2[] Vertices; public readonly int2[] Vertices;

View File

@@ -21,7 +21,7 @@ namespace OpenRA.Primitives
/// </summary> /// </summary>
public abstract class ReadOnlyAdapterStream : Stream public abstract class ReadOnlyAdapterStream : Stream
{ {
readonly Queue<byte> data = new Queue<byte>(1024); readonly Queue<byte> data = new(1024);
readonly Stream baseStream; readonly Stream baseStream;
bool baseStreamEmpty; bool baseStreamEmpty;

View File

@@ -63,13 +63,13 @@ namespace OpenRA.Primitives
public int Top => Y; public int Top => Y;
public int Bottom => Y + Height; public int Bottom => Y + Height;
public bool IsEmpty => X == 0 && Y == 0 && Width == 0 && Height == 0; public bool IsEmpty => X == 0 && Y == 0 && Width == 0 && Height == 0;
public int2 Location => new int2(X, Y); public int2 Location => new(X, Y);
public Size Size => new Size(Width, Height); public Size Size => new(Width, Height);
public int2 TopLeft => Location; public int2 TopLeft => Location;
public int2 TopRight => new int2(X + Width, Y); public int2 TopRight => new(X + Width, Y);
public int2 BottomLeft => new int2(X, Y + Height); public int2 BottomLeft => new(X, Y + Height);
public int2 BottomRight => new int2(X + Width, Y + Height); public int2 BottomRight => new(X + Width, Y + Height);
public bool Contains(int x, int y) public bool Contains(int x, int y)
{ {

View File

@@ -18,7 +18,7 @@ namespace OpenRA.Primitives
{ {
readonly int rows, cols, binSize; readonly int rows, cols, binSize;
readonly Dictionary<T, Rectangle>[] itemBoundsBins; readonly Dictionary<T, Rectangle>[] itemBoundsBins;
readonly Dictionary<T, Rectangle> itemBounds = new Dictionary<T, Rectangle>(); readonly Dictionary<T, Rectangle> itemBounds = new();
readonly Action<Dictionary<T, Rectangle>, T, Rectangle> addItem = (bin, actor, bounds) => bin.Add(actor, bounds); readonly Action<Dictionary<T, Rectangle>, T, Rectangle> addItem = (bin, actor, bounds) => bin.Add(actor, bounds);
readonly Action<Dictionary<T, Rectangle>, T, Rectangle> removeItem = (bin, actor, bounds) => bin.Remove(actor); readonly Action<Dictionary<T, Rectangle>, T, Rectangle> removeItem = (bin, actor, bounds) => bin.Remove(actor);

View File

@@ -19,7 +19,7 @@ namespace OpenRA.Primitives
public class TypeDictionary : IEnumerable public class TypeDictionary : IEnumerable
{ {
static readonly Func<Type, List<object>> CreateList = type => new List<object>(); static readonly Func<Type, List<object>> CreateList = type => new List<object>();
readonly Dictionary<Type, List<object>> data = new Dictionary<Type, List<object>>(); readonly Dictionary<Type, List<object>> data = new();
public void Add(object val) public void Add(object val)
{ {

View File

@@ -76,7 +76,7 @@ namespace OpenRA
public override string ToString() { return X + "," + Y; } public override string ToString() { return X + "," + Y; }
public static readonly float2 Zero = new float2(0, 0); public static readonly float2 Zero = new(0, 0);
public static bool WithinEpsilon(float2 a, float2 b, float e) public static bool WithinEpsilon(float2 a, float2 b, float e)
{ {

View File

@@ -20,7 +20,7 @@ namespace OpenRA
public readonly struct float3 : IEquatable<float3> public readonly struct float3 : IEquatable<float3>
{ {
public readonly float X, Y, Z; public readonly float X, Y, Z;
public float2 XY => new float2(X, Y); public float2 XY => new(X, Y);
public float3(float x, float y, float z) { X = x; Y = y; Z = z; } public float3(float x, float y, float z) { X = x; Y = y; Z = z; }
public float3(float2 xy, float z) { X = xy.X; Y = xy.Y; Z = z; } public float3(float2 xy, float z) { X = xy.X; Y = xy.Y; Z = z; }
@@ -60,7 +60,7 @@ namespace OpenRA
public override string ToString() { return $"{X},{Y},{Z}"; } public override string ToString() { return $"{X},{Y},{Z}"; }
public static readonly float3 Zero = new float3(0, 0, 0); public static readonly float3 Zero = new(0, 0, 0);
public static readonly float3 Ones = new float3(1, 1, 1); public static readonly float3 Ones = new(1, 1, 1);
} }
} }

View File

@@ -59,7 +59,7 @@ namespace OpenRA
public static int2 Max(int2 a, int2 b) { return new int2(Math.Max(a.X, b.X), Math.Max(a.Y, b.Y)); } public static int2 Max(int2 a, int2 b) { return new int2(Math.Max(a.X, b.X), Math.Max(a.Y, b.Y)); }
public static int2 Min(int2 a, int2 b) { return new int2(Math.Min(a.X, b.X), Math.Min(a.Y, b.Y)); } public static int2 Min(int2 a, int2 b) { return new int2(Math.Min(a.X, b.X), Math.Min(a.Y, b.Y)); }
public static readonly int2 Zero = new int2(0, 0); public static readonly int2 Zero = new(0, 0);
public float2 ToFloat2() { return new float2(X, Y); } public float2 ToFloat2() { return new float2(X, Y); }
// Change endianness of a uint32 // Change endianness of a uint32

View File

@@ -44,7 +44,7 @@ namespace OpenRA
internal int TempBufferSize { get; } internal int TempBufferSize { get; }
readonly IVertexBuffer<Vertex> tempBuffer; readonly IVertexBuffer<Vertex> tempBuffer;
readonly Stack<Rectangle> scissorState = new Stack<Rectangle>(); readonly Stack<Rectangle> scissorState = new();
IFrameBuffer screenBuffer; IFrameBuffer screenBuffer;
Sprite screenSprite; Sprite screenSprite;
@@ -63,7 +63,7 @@ namespace OpenRA
float depthMargin; float depthMargin;
Size lastBufferSize = new Size(-1, -1); Size lastBufferSize = new(-1, -1);
Rectangle lastWorldViewport = Rectangle.Empty; Rectangle lastWorldViewport = Rectangle.Empty;
ITexture currentPaletteTexture; ITexture currentPaletteTexture;

View File

@@ -18,7 +18,7 @@ namespace OpenRA.Scripting
{ {
public static class ScriptMemberExts public static class ScriptMemberExts
{ {
static readonly Dictionary<string, string> LuaTypeNameReplacements = new Dictionary<string, string>() static readonly Dictionary<string, string> LuaTypeNameReplacements = new()
{ {
{ "Void", "void" }, { "Void", "void" },
{ "Int32", "int" }, { "Int32", "int" },

View File

@@ -22,7 +22,7 @@ namespace OpenRA.Scripting
protected abstract string MemberNotFoundError(string memberName); protected abstract string MemberNotFoundError(string memberName);
protected readonly ScriptContext Context; protected readonly ScriptContext Context;
readonly Dictionary<string, ScriptMemberWrapper> members = new Dictionary<string, ScriptMemberWrapper>(); readonly Dictionary<string, ScriptMemberWrapper> members = new();
#if !NET5_0_OR_GREATER #if !NET5_0_OR_GREATER
readonly List<string> membersToRemove = new List<string>(); readonly List<string> membersToRemove = new List<string>();

View File

@@ -41,8 +41,8 @@ namespace OpenRA.Server
long lastReceivedTime = 0; long lastReceivedTime = 0;
readonly BlockingCollection<byte[]> sendQueue = new BlockingCollection<byte[]>(); readonly BlockingCollection<byte[]> sendQueue = new();
readonly Queue<int> pingHistory = new Queue<int>(); readonly Queue<int> pingHistory = new();
public Connection(Server server, Socket socket, string authToken) public Connection(Server server, Socket socket, string authToken)
{ {

View File

@@ -20,7 +20,7 @@ namespace OpenRA.Server
public class MapStatusCache public class MapStatusCache
{ {
readonly Dictionary<MapPreview, Session.MapStatus> cache = new Dictionary<MapPreview, Session.MapStatus>(); readonly Dictionary<MapPreview, Session.MapStatus> cache = new();
readonly Action<string, Session.MapStatus> onStatusChanged; readonly Action<string, Session.MapStatus> onStatusChanged;
readonly bool enableRemoteLinting; readonly bool enableRemoteLinting;
readonly ModData modData; readonly ModData modData;

View File

@@ -31,8 +31,8 @@ namespace OpenRA.Server
Stopwatch gameTimer; Stopwatch gameTimer;
long nextUpdate = 0; long nextUpdate = 0;
readonly ConcurrentDictionary<int, long> timestamps = new ConcurrentDictionary<int, long>(); readonly ConcurrentDictionary<int, long> timestamps = new();
readonly ConcurrentDictionary<int, Queue<long>> deltas = new ConcurrentDictionary<int, Queue<long>>(); readonly ConcurrentDictionary<int, Queue<long>> deltas = new();
int timestep; int timestep;
int ticksPerInterval; int ticksPerInterval;

View File

@@ -19,7 +19,7 @@ namespace OpenRA.Server
[TranslationReference("remaining")] [TranslationReference("remaining")]
const string ChatTemporaryDisabled = "notification-chat-temp-disabled"; const string ChatTemporaryDisabled = "notification-chat-temp-disabled";
readonly Dictionary<int, List<long>> messageTracker = new Dictionary<int, List<long>>(); readonly Dictionary<int, List<long>> messageTracker = new();
readonly Server server; readonly Server server;
readonly Action<Connection, int, int, byte[]> dispatchOrdersToClient; readonly Action<Connection, int, int, byte[]> dispatchOrdersToClient;
readonly Action<Connection, string, Dictionary<string, object>> sendLocalizedMessageTo; readonly Action<Connection, string, Dictionary<string, object>> sendLocalizedMessageTo;

View File

@@ -115,15 +115,15 @@ namespace OpenRA.Server
[TranslationReference] [TranslationReference]
const string GameStarted = "notification-game-started"; const string GameStarted = "notification-game-started";
public readonly MersenneTwister Random = new MersenneTwister(); public readonly MersenneTwister Random = new();
public readonly ServerType Type; public readonly ServerType Type;
public readonly List<Connection> Conns = new List<Connection>(); public readonly List<Connection> Conns = new();
public Session LobbyInfo; public Session LobbyInfo;
public ServerSettings Settings; public ServerSettings Settings;
public ModData ModData; public ModData ModData;
public List<string> TempBans = new List<string>(); public List<string> TempBans = new();
// Managed by LobbyCommands // Managed by LobbyCommands
public MapPreview Map; public MapPreview Map;
@@ -134,19 +134,19 @@ namespace OpenRA.Server
public int OrderLatency = 1; public int OrderLatency = 1;
readonly int randomSeed; readonly int randomSeed;
readonly List<TcpListener> listeners = new List<TcpListener>(); readonly List<TcpListener> listeners = new();
readonly TypeDictionary serverTraits = new TypeDictionary(); readonly TypeDictionary serverTraits = new();
readonly PlayerDatabase playerDatabase; readonly PlayerDatabase playerDatabase;
OrderBuffer orderBuffer; OrderBuffer orderBuffer;
volatile ServerState internalState = ServerState.WaitingPlayers; volatile ServerState internalState = ServerState.WaitingPlayers;
readonly BlockingCollection<IServerEvent> events = new BlockingCollection<IServerEvent>(); readonly BlockingCollection<IServerEvent> events = new();
ReplayRecorder recorder; ReplayRecorder recorder;
GameInformation gameInfo; GameInformation gameInfo;
readonly List<GameInformation.Player> worldPlayers = new List<GameInformation.Player>(); readonly List<GameInformation.Player> worldPlayers = new();
readonly Stopwatch pingUpdated = Stopwatch.StartNew(); readonly Stopwatch pingUpdated = Stopwatch.StartNew();
readonly PlayerMessageTracker playerMessageTracker; readonly PlayerMessageTracker playerMessageTracker;
@@ -802,7 +802,7 @@ namespace OpenRA.Server
recorder = null; recorder = null;
} }
readonly Dictionary<int, byte[]> syncForFrame = new Dictionary<int, byte[]>(); readonly Dictionary<int, byte[]> syncForFrame = new();
int lastDefeatStateFrame; int lastDefeatStateFrame;
ulong lastDefeatState; ulong lastDefeatState;

View File

@@ -177,10 +177,10 @@ namespace OpenRA
public bool VSync = true; public bool VSync = true;
[Desc("Screen resolution in fullscreen mode.")] [Desc("Screen resolution in fullscreen mode.")]
public int2 FullscreenSize = new int2(0, 0); public int2 FullscreenSize = new(0, 0);
[Desc("Screen resolution in windowed mode.")] [Desc("Screen resolution in windowed mode.")]
public int2 WindowedSize = new int2(1024, 768); public int2 WindowedSize = new(1024, 768);
public bool CursorDouble = false; public bool CursorDouble = false;
public WorldViewport ViewportDistance = WorldViewport.Medium; public WorldViewport ViewportDistance = WorldViewport.Medium;
@@ -253,7 +253,7 @@ namespace OpenRA
public bool LockMouseWindow = false; public bool LockMouseWindow = false;
public MouseScrollType MouseScroll = MouseScrollType.Joystick; public MouseScrollType MouseScroll = MouseScrollType.Joystick;
public MouseButtonPreference MouseButtonPreference = new MouseButtonPreference(); public MouseButtonPreference MouseButtonPreference = new();
public float ViewportEdgeScrollStep = 30f; public float ViewportEdgeScrollStep = 30f;
public float UIScrollSpeed = 50f; public float UIScrollSpeed = 50f;
public float ZoomSpeed = 0.04f; public float ZoomSpeed = 0.04f;
@@ -295,20 +295,20 @@ namespace OpenRA
{ {
readonly string settingsFile; readonly string settingsFile;
public readonly PlayerSettings Player = new PlayerSettings(); public readonly PlayerSettings Player = new();
public readonly GameSettings Game = new GameSettings(); public readonly GameSettings Game = new();
public readonly SoundSettings Sound = new SoundSettings(); public readonly SoundSettings Sound = new();
public readonly GraphicSettings Graphics = new GraphicSettings(); public readonly GraphicSettings Graphics = new();
public readonly ServerSettings Server = new ServerSettings(); public readonly ServerSettings Server = new();
public readonly DebugSettings Debug = new DebugSettings(); public readonly DebugSettings Debug = new();
internal Dictionary<string, Hotkey> Keys = new Dictionary<string, Hotkey>(); internal Dictionary<string, Hotkey> Keys = new();
public readonly Dictionary<string, object> Sections; public readonly Dictionary<string, object> Sections;
// A direct clone of the file loaded from disk. // A direct clone of the file loaded from disk.
// Any changed settings will be merged over this on save, // Any changed settings will be merged over this on save,
// allowing us to persist any unknown configuration keys // allowing us to persist any unknown configuration keys
readonly List<MiniYamlNode> yamlCache = new List<MiniYamlNode>(); readonly List<MiniYamlNode> yamlCache = new();
public Settings(string file, Arguments args) public Settings(string file, Arguments args)
{ {

View File

@@ -43,8 +43,8 @@ namespace OpenRA
ISoundSource videoSource; ISoundSource videoSource;
ISound music; ISound music;
ISound video; ISound video;
readonly Dictionary<uint, ISound> currentSounds = new Dictionary<uint, ISound>(); readonly Dictionary<uint, ISound> currentSounds = new();
readonly Dictionary<string, ISound> currentNotifications = new Dictionary<string, ISound>(); readonly Dictionary<string, ISound> currentNotifications = new();
public bool DummyEngine { get; } public bool DummyEngine { get; }
public Sound(IPlatform platform, SoundSettings soundSettings) public Sound(IPlatform platform, SoundSettings soundSettings)

View File

@@ -16,9 +16,9 @@ namespace OpenRA
{ {
public class Arguments public class Arguments
{ {
readonly Dictionary<string, string> args = new Dictionary<string, string>(); readonly Dictionary<string, string> args = new();
public static Arguments Empty => new Arguments(); public static Arguments Empty => new();
public Arguments(params string[] src) public Arguments(params string[] src)
{ {

View File

@@ -53,8 +53,8 @@ namespace OpenRA.Support
public class AssemblyLoadContextBuilder public class AssemblyLoadContextBuilder
{ {
readonly Dictionary<string, ManagedLibrary> managedLibraries = new Dictionary<string, ManagedLibrary>(StringComparer.Ordinal); readonly Dictionary<string, ManagedLibrary> managedLibraries = new(StringComparer.Ordinal);
readonly Dictionary<string, NativeLibrary> nativeLibraries = new Dictionary<string, NativeLibrary>(StringComparer.Ordinal); readonly Dictionary<string, NativeLibrary> nativeLibraries = new(StringComparer.Ordinal);
string basePath; string basePath;
public AssemblyLoadContext Build() public AssemblyLoadContext Build()

View File

@@ -16,7 +16,7 @@ namespace OpenRA.Support
class Benchmark class Benchmark
{ {
readonly string prefix; readonly string prefix;
readonly Dictionary<string, List<BenchmarkPoint>> samples = new Dictionary<string, List<BenchmarkPoint>>(); readonly Dictionary<string, List<BenchmarkPoint>> samples = new();
public Benchmark(string prefix) public Benchmark(string prefix)
{ {

View File

@@ -80,7 +80,7 @@ namespace OpenRA.Support
} }
static readonly Dictionary<string, int> Prec static readonly Dictionary<string, int> Prec
= new Dictionary<string, int> { { "+", 0 }, { "-", 0 }, { "*", 1 }, { "/", 1 }, { "(", -1 } }; = new() { { "+", 0 }, { "-", 0 }, { "*", 1 }, { "/", 1 }, { "(", -1 } };
static IEnumerable<string> Tokens(string expr, string ops) static IEnumerable<string> Tokens(string expr, string ops)
{ {

View File

@@ -21,7 +21,7 @@ namespace OpenRA.Support
static readonly TimeSpan ConnectionLifeTime = TimeSpan.FromMinutes(1); static readonly TimeSpan ConnectionLifeTime = TimeSpan.FromMinutes(1);
#endif #endif
static readonly Lazy<HttpMessageHandler> Handler = new Lazy<HttpMessageHandler>(GetHandler); static readonly Lazy<HttpMessageHandler> Handler = new(GetHandler);
public static HttpClient Create() public static HttpClient Create()
{ {

View File

@@ -19,7 +19,7 @@ namespace OpenRA.Support
public class HttpQueryBuilder : IEnumerable public class HttpQueryBuilder : IEnumerable
{ {
readonly string url; readonly string url;
readonly List<Parameter> parameters = new List<Parameter>(); readonly List<Parameter> parameters = new();
public HttpQueryBuilder(string url) public HttpQueryBuilder(string url)
{ {

View File

@@ -41,10 +41,10 @@ namespace OpenRA
{ {
const int CreateLogFileMaxRetryCount = 128; const int CreateLogFileMaxRetryCount = 128;
static readonly ConcurrentDictionary<string, ChannelInfo> Channels = new ConcurrentDictionary<string, ChannelInfo>(); static readonly ConcurrentDictionary<string, ChannelInfo> Channels = new();
static readonly Channel<ChannelData> Channel; static readonly Channel<ChannelData> Channel;
static readonly ChannelWriter<ChannelData> ChannelWriter; static readonly ChannelWriter<ChannelData> ChannelWriter;
static readonly CancellationTokenSource CancellationToken = new CancellationTokenSource(); static readonly CancellationTokenSource CancellationToken = new();
static readonly TimeSpan FlushInterval = TimeSpan.FromSeconds(5); static readonly TimeSpan FlushInterval = TimeSpan.FromSeconds(5);
static readonly Timer Timer; static readonly Timer Timer;

View File

@@ -28,7 +28,7 @@ namespace OpenRA.Support
static int nextColor; static int nextColor;
public static Cache<string, PerfItem> Items = new Cache<string, PerfItem>( public static Cache<string, PerfItem> Items = new(
s => s =>
{ {
var x = new PerfItem(s, Colors[nextColor++]); var x = new PerfItem(s, Colors[nextColor++]);

View File

@@ -31,7 +31,7 @@ namespace OpenRA.Support
List<PerfTimer> children; List<PerfTimer> children;
long ticks; long ticks;
static readonly ThreadLocal<PerfTimer> ParentThreadLocal = new ThreadLocal<PerfTimer>(); static readonly ThreadLocal<PerfTimer> ParentThreadLocal = new();
public PerfTimer(string name, float thresholdMs = 0) public PerfTimer(string name, float thresholdMs = 0)
{ {

View File

@@ -24,7 +24,7 @@ namespace OpenRA.Support
public static readonly IReadOnlyDictionary<string, int> NoVariables = new ReadOnlyDictionary<string, int>(new Dictionary<string, int>()); public static readonly IReadOnlyDictionary<string, int> NoVariables = new ReadOnlyDictionary<string, int>(new Dictionary<string, int>());
public readonly string Expression; public readonly string Expression;
readonly HashSet<string> variables = new HashSet<string>(); readonly HashSet<string> variables = new();
public IEnumerable<string> Variables => variables; public IEnumerable<string> Variables => variables;
enum CharClass { Whitespace, Operator, Mixed, Id, Digit } enum CharClass { Whitespace, Operator, Mixed, Id, Digit }
@@ -716,8 +716,8 @@ namespace OpenRA.Support
class AstStack class AstStack
{ {
readonly List<Expression> expressions = new List<Expression>(); readonly List<Expression> expressions = new();
readonly List<ExpressionType> types = new List<ExpressionType>(); readonly List<ExpressionType> types = new();
public ExpressionType PeekType() { return types[^1]; } public ExpressionType PeekType() { return types[^1]; }
@@ -774,7 +774,7 @@ namespace OpenRA.Support
class Compiler class Compiler
{ {
readonly AstStack ast = new AstStack(); readonly AstStack ast = new();
public Expression Build(Token[] postfix, ExpressionType resultType) public Expression Build(Token[] postfix, ExpressionType resultType)
{ {

View File

@@ -28,7 +28,7 @@ namespace OpenRA
public static class Sync public static class Sync
{ {
static readonly ConcurrentCache<Type, Func<object, int>> HashFunctions = static readonly ConcurrentCache<Type, Func<object, int>> HashFunctions =
new ConcurrentCache<Type, Func<object, int>>(GenerateHashFunc); new(GenerateHashFunc);
internal static Func<object, int> GetHashFunction(ISync sync) internal static Func<object, int> GetHashFunction(ISync sync)
{ {
@@ -40,7 +40,7 @@ namespace OpenRA
return GetHashFunction(sync)(sync); return GetHashFunction(sync)(sync);
} }
static readonly Dictionary<Type, MethodInfo> CustomHashFunctions = new Dictionary<Type, MethodInfo>() static readonly Dictionary<Type, MethodInfo> CustomHashFunctions = new()
{ {
{ typeof(int2), ((Func<int2, int>)HashInt2).Method }, { typeof(int2), ((Func<int2, int>)HashInt2).Method },
{ typeof(CPos), ((Func<CPos, int>)HashCPos).Method }, { typeof(CPos), ((Func<CPos, int>)HashCPos).Method },

View File

@@ -21,9 +21,9 @@ namespace OpenRA
static readonly string SystemMessageLabel; static readonly string SystemMessageLabel;
public static long ChatDisabledUntil { get; internal set; } public static long ChatDisabledUntil { get; internal set; }
public static readonly Dictionary<int, bool> MutedPlayers = new Dictionary<int, bool>(); public static readonly Dictionary<int, bool> MutedPlayers = new();
static readonly List<TextNotification> NotificationsCache = new List<TextNotification>(); static readonly List<TextNotification> NotificationsCache = new();
public static IReadOnlyList<TextNotification> Notifications => NotificationsCache; public static IReadOnlyList<TextNotification> Notifications => NotificationsCache;
static TextNotificationsManager() static TextNotificationsManager()

View File

@@ -44,7 +44,7 @@ namespace OpenRA
static readonly Func<Type, ITraitContainer> CreateTraitContainer = t => static readonly Func<Type, ITraitContainer> CreateTraitContainer = t =>
(ITraitContainer)typeof(TraitContainer<>).MakeGenericType(t).GetConstructor(Type.EmptyTypes).Invoke(null); (ITraitContainer)typeof(TraitContainer<>).MakeGenericType(t).GetConstructor(Type.EmptyTypes).Invoke(null);
readonly Dictionary<Type, ITraitContainer> traits = new Dictionary<Type, ITraitContainer>(); readonly Dictionary<Type, ITraitContainer> traits = new();
ITraitContainer InnerGet(Type t) ITraitContainer InnerGet(Type t)
{ {
@@ -143,9 +143,9 @@ namespace OpenRA
class TraitContainer<T> : ITraitContainer class TraitContainer<T> : ITraitContainer
{ {
readonly List<Actor> actors = new List<Actor>(); readonly List<Actor> actors = new();
readonly List<T> traits = new List<T>(); readonly List<T> traits = new();
readonly PerfTickLogger perfLogger = new PerfTickLogger(); readonly PerfTickLogger perfLogger = new();
public int Queries { get; private set; } public int Queries { get; private set; }
@@ -277,7 +277,7 @@ namespace OpenRA
public void Reset() { index = -1; } public void Reset() { index = -1; }
public bool MoveNext() { return ++index < actors.Count; } public bool MoveNext() { return ++index < actors.Count; }
public TraitPair<T> Current => new TraitPair<T>(actors[index], traits[index]); public TraitPair<T> Current => new(actors[index], traits[index]);
object System.Collections.IEnumerator.Current => Current; object System.Collections.IEnumerator.Current => Current;
public void Dispose() { } public void Dispose() { }
} }

View File

@@ -39,7 +39,7 @@ namespace OpenRA.Traits
readonly Actor actor; readonly Actor actor;
readonly ICreatesFrozenActors frozenTrait; readonly ICreatesFrozenActors frozenTrait;
readonly Shroud shroud; readonly Shroud shroud;
readonly List<WPos> targetablePositions = new List<WPos>(); readonly List<WPos> targetablePositions = new();
public Player Viewer { get; } public Player Viewer { get; }
public Player Owner { get; private set; } public Player Owner { get; private set; }
@@ -253,7 +253,7 @@ namespace OpenRA.Traits
readonly Player owner; readonly Player owner;
readonly Dictionary<uint, FrozenActor> frozenActorsById; readonly Dictionary<uint, FrozenActor> frozenActorsById;
readonly SpatiallyPartitioned<uint> partitionedFrozenActorIds; readonly SpatiallyPartitioned<uint> partitionedFrozenActorIds;
readonly HashSet<uint> dirtyFrozenActorIds = new HashSet<uint>(); readonly HashSet<uint> dirtyFrozenActorIds = new();
public FrozenActorLayer(Actor self, FrozenActorLayerInfo info) public FrozenActorLayer(Actor self, FrozenActorLayerInfo info)
{ {

View File

@@ -98,7 +98,7 @@ namespace OpenRA.Traits
readonly Map map; readonly Map map;
// Individual shroud modifier sources (type and area) // Individual shroud modifier sources (type and area)
readonly Dictionary<object, ShroudSource> sources = new Dictionary<object, ShroudSource>(); readonly Dictionary<object, ShroudSource> sources = new();
// Per-cell count of each source type, used to resolve the final cell type // Per-cell count of each source type, used to resolve the final cell type
readonly ProjectedCellLayer<short> passiveVisibleCount; readonly ProjectedCellLayer<short> passiveVisibleCount;

View File

@@ -563,7 +563,7 @@ namespace OpenRA.Traits
public class LobbyBooleanOption : LobbyOption public class LobbyBooleanOption : LobbyOption
{ {
static readonly Dictionary<string, string> BoolValues = new Dictionary<string, string>() static readonly Dictionary<string, string> BoolValues = new()
{ {
{ true.ToString(), "Enabled" }, { true.ToString(), "Enabled" },
{ false.ToString(), "Disabled" } { false.ToString(), "Disabled" }

View File

@@ -24,7 +24,7 @@ namespace OpenRA.Traits
public readonly string InternalName = null; public readonly string InternalName = null;
[Desc("Pick a random faction as the player's faction out of this list.")] [Desc("Pick a random faction as the player's faction out of this list.")]
public readonly HashSet<string> RandomFactionMembers = new HashSet<string>(); public readonly HashSet<string> RandomFactionMembers = new();
[Desc("The side that the faction belongs to. For example, England belongs to the 'Allies' side.")] [Desc("The side that the faction belongs to. For example, England belongs to the 'Allies' side.")]
public readonly string Side = null; public readonly string Side = null;

View File

@@ -47,15 +47,15 @@ namespace OpenRA.Traits
readonly Func<Actor, ActorBoundsPair> selectActorAndBounds; readonly Func<Actor, ActorBoundsPair> selectActorAndBounds;
readonly Cache<Player, SpatiallyPartitioned<FrozenActor>> partitionedMouseFrozenActors; readonly Cache<Player, SpatiallyPartitioned<FrozenActor>> partitionedMouseFrozenActors;
readonly SpatiallyPartitioned<Actor> partitionedMouseActors; readonly SpatiallyPartitioned<Actor> partitionedMouseActors;
readonly Dictionary<Actor, ActorBoundsPair> partitionedMouseActorBounds = new Dictionary<Actor, ActorBoundsPair>(); readonly Dictionary<Actor, ActorBoundsPair> partitionedMouseActorBounds = new();
readonly Cache<Player, SpatiallyPartitioned<FrozenActor>> partitionedRenderableFrozenActors; readonly Cache<Player, SpatiallyPartitioned<FrozenActor>> partitionedRenderableFrozenActors;
readonly SpatiallyPartitioned<Actor> partitionedRenderableActors; readonly SpatiallyPartitioned<Actor> partitionedRenderableActors;
readonly SpatiallyPartitioned<IEffect> partitionedRenderableEffects; readonly SpatiallyPartitioned<IEffect> partitionedRenderableEffects;
// Updates are done in one pass to ensure all bound changes have been applied // Updates are done in one pass to ensure all bound changes have been applied
readonly HashSet<Actor> addOrUpdateActors = new HashSet<Actor>(); readonly HashSet<Actor> addOrUpdateActors = new();
readonly HashSet<Actor> removeActors = new HashSet<Actor>(); readonly HashSet<Actor> removeActors = new();
readonly Cache<Player, HashSet<FrozenActor>> addOrUpdateFrozenActors; readonly Cache<Player, HashSet<FrozenActor>> addOrUpdateFrozenActors;
readonly Cache<Player, HashSet<FrozenActor>> removeFrozenActors; readonly Cache<Player, HashSet<FrozenActor>> removeFrozenActors;

View File

@@ -19,8 +19,8 @@ namespace OpenRA.Traits
[TraitLocation(SystemActors.World)] [TraitLocation(SystemActors.World)]
public class ScreenShakerInfo : TraitInfo public class ScreenShakerInfo : TraitInfo
{ {
public readonly float2 MinMultiplier = new float2(-3, -3); public readonly float2 MinMultiplier = new(-3, -3);
public readonly float2 MaxMultiplier = new float2(3, 3); public readonly float2 MaxMultiplier = new(3, 3);
public override object Create(ActorInitializer init) { return new ScreenShaker(this); } public override object Create(ActorInitializer init) { return new ScreenShaker(this); }
} }
@@ -29,7 +29,7 @@ namespace OpenRA.Traits
{ {
readonly ScreenShakerInfo info; readonly ScreenShakerInfo info;
WorldRenderer worldRenderer; WorldRenderer worldRenderer;
readonly List<ShakeEffect> shakeEffects = new List<ShakeEffect>(); readonly List<ShakeEffect> shakeEffects = new();
int ticks = 0; int ticks = 0;
public ScreenShaker(ScreenShakerInfo info) public ScreenShaker(ScreenShakerInfo info)

View File

@@ -31,7 +31,7 @@ namespace OpenRA
Angle += 1024; Angle += 1024;
} }
public static readonly WAngle Zero = new WAngle(0); public static readonly WAngle Zero = new(0);
public static WAngle FromFacing(int facing) { return new WAngle(facing * 4); } public static WAngle FromFacing(int facing) { return new WAngle(facing * 4); }
public static WAngle FromDegrees(int degrees) { return new WAngle(degrees * 1024 / 360); } public static WAngle FromDegrees(int degrees) { return new WAngle(degrees * 1024 / 360); }
public static WAngle operator +(WAngle a, WAngle b) { return new WAngle(a.Angle + b.Angle); } public static WAngle operator +(WAngle a, WAngle b) { return new WAngle(a.Angle + b.Angle); }

View File

@@ -27,8 +27,8 @@ namespace OpenRA
public long LengthSquared => (long)Length * Length; public long LengthSquared => (long)Length * Length;
public WDist(int r) { Length = r; } public WDist(int r) { Length = r; }
public static readonly WDist Zero = new WDist(0); public static readonly WDist Zero = new(0);
public static readonly WDist MaxValue = new WDist(int.MaxValue); public static readonly WDist MaxValue = new(int.MaxValue);
public static WDist FromCells(int cells) { return new WDist(1024 * cells); } public static WDist FromCells(int cells) { return new WDist(1024 * cells); }
public static WDist operator +(WDist a, WDist b) { return new WDist(a.Length + b.Length); } public static WDist operator +(WDist a, WDist b) { return new WDist(a.Length + b.Length); }

View File

@@ -25,7 +25,7 @@ namespace OpenRA
public WPos(int x, int y, int z) { X = x; Y = y; Z = z; } public WPos(int x, int y, int z) { X = x; Y = y; Z = z; }
public WPos(WDist x, WDist y, WDist z) { X = x.Length; Y = y.Length; Z = z.Length; } public WPos(WDist x, WDist y, WDist z) { X = x.Length; Y = y.Length; Z = z.Length; }
public static readonly WPos Zero = new WPos(0, 0, 0); public static readonly WPos Zero = new(0, 0, 0);
public static explicit operator WVec(in WPos a) { return new WVec(a.X, a.Y, a.Z); } public static explicit operator WVec(in WPos a) { return new WVec(a.X, a.Y, a.Z); }

View File

@@ -105,7 +105,7 @@ namespace OpenRA
Yaw = yaw; Yaw = yaw;
} }
public static readonly WRot None = new WRot(WAngle.Zero, WAngle.Zero, WAngle.Zero); public static readonly WRot None = new(WAngle.Zero, WAngle.Zero, WAngle.Zero);
public static WRot FromFacing(int facing) { return new WRot(WAngle.Zero, WAngle.Zero, WAngle.FromFacing(facing)); } public static WRot FromFacing(int facing) { return new WRot(WAngle.Zero, WAngle.Zero, WAngle.FromFacing(facing)); }
public static WRot FromYaw(WAngle yaw) { return new WRot(WAngle.Zero, WAngle.Zero, yaw); } public static WRot FromYaw(WAngle yaw) { return new WRot(WAngle.Zero, WAngle.Zero, yaw); }

View File

@@ -24,7 +24,7 @@ namespace OpenRA
public WVec(int x, int y, int z) { X = x; Y = y; Z = z; } public WVec(int x, int y, int z) { X = x; Y = y; Z = z; }
public WVec(WDist x, WDist y, WDist z) { X = x.Length; Y = y.Length; Z = z.Length; } public WVec(WDist x, WDist y, WDist z) { X = x.Length; Y = y.Length; Z = z.Length; }
public static readonly WVec Zero = new WVec(0, 0, 0); public static readonly WVec Zero = new(0, 0, 0);
public static WVec operator +(in WVec a, in WVec b) { return new WVec(a.X + b.X, a.Y + b.Y, a.Z + b.Z); } public static WVec operator +(in WVec a, in WVec b) { return new WVec(a.X + b.X, a.Y + b.Y, a.Z + b.Z); }
public static WVec operator -(in WVec a, in WVec b) { return new WVec(a.X - b.X, a.Y - b.Y, a.Z - b.Z); } public static WVec operator -(in WVec a, in WVec b) { return new WVec(a.X - b.X, a.Y - b.Y, a.Z - b.Z); }

View File

@@ -16,7 +16,7 @@ namespace OpenRA.Widgets
{ {
public static class ChromeMetrics public static class ChromeMetrics
{ {
static Dictionary<string, string> data = new Dictionary<string, string>(); static Dictionary<string, string> data = new();
public static void Initialize(ModData modData) public static void Initialize(ModData modData)
{ {

View File

@@ -25,15 +25,15 @@ namespace OpenRA.Widgets
public static Widget Root = new ContainerWidget(); public static Widget Root = new ContainerWidget();
public static TickTime LastTickTime = new TickTime(() => Timestep, Game.RunTime); public static TickTime LastTickTime = new(() => Timestep, Game.RunTime);
static readonly Stack<Widget> WindowList = new Stack<Widget>(); static readonly Stack<Widget> WindowList = new();
public static Widget MouseFocusWidget; public static Widget MouseFocusWidget;
public static Widget KeyboardFocusWidget; public static Widget KeyboardFocusWidget;
public static Widget MouseOverWidget; public static Widget MouseOverWidget;
static readonly Mediator Mediator = new Mediator(); static readonly Mediator Mediator = new();
public static void CloseWindow() public static void CloseWindow()
{ {
@@ -185,7 +185,7 @@ namespace OpenRA.Widgets
{ {
string defaultCursor = null; string defaultCursor = null;
public readonly List<Widget> Children = new List<Widget>(); public readonly List<Widget> Children = new();
// Info defined in YAML // Info defined in YAML
public string Id = null; public string Id = null;
@@ -644,7 +644,7 @@ namespace OpenRA.Widgets
public sealed class Mediator public sealed class Mediator
{ {
readonly TypeDictionary types = new TypeDictionary(); readonly TypeDictionary types = new();
public void Subscribe<T>(T instance) public void Subscribe<T>(T instance)
{ {

View File

@@ -18,7 +18,7 @@ namespace OpenRA
{ {
public class WidgetLoader public class WidgetLoader
{ {
readonly Dictionary<string, MiniYamlNode> widgets = new Dictionary<string, MiniYamlNode>(); readonly Dictionary<string, MiniYamlNode> widgets = new();
readonly ModData modData; readonly ModData modData;
public WidgetLoader(ModData modData) public WidgetLoader(ModData modData)

View File

@@ -28,15 +28,15 @@ namespace OpenRA
public sealed class World : IDisposable public sealed class World : IDisposable
{ {
internal readonly TraitDictionary TraitDict = new TraitDictionary(); internal readonly TraitDictionary TraitDict = new();
readonly SortedDictionary<uint, Actor> actors = new SortedDictionary<uint, Actor>(); readonly SortedDictionary<uint, Actor> actors = new();
readonly List<IEffect> effects = new List<IEffect>(); readonly List<IEffect> effects = new();
readonly List<IEffect> unpartitionedEffects = new List<IEffect>(); readonly List<IEffect> unpartitionedEffects = new();
readonly List<ISync> syncedEffects = new List<ISync>(); readonly List<ISync> syncedEffects = new();
readonly GameSettings gameSettings; readonly GameSettings gameSettings;
readonly ModData modData; readonly ModData modData;
readonly Queue<Action<World>> frameEndActions = new Queue<Action<World>>(); readonly Queue<Action<World>> frameEndActions = new();
public readonly GameSpeed GameSpeed; public readonly GameSpeed GameSpeed;
@@ -390,7 +390,7 @@ namespace OpenRA
public int WorldTick { get; private set; } public int WorldTick { get; private set; }
readonly Dictionary<int, MiniYaml> gameSaveTraitData = new Dictionary<int, MiniYaml>(); readonly Dictionary<int, MiniYaml> gameSaveTraitData = new();
internal void AddGameSaveTraitData(int traitIndex, MiniYaml yaml) internal void AddGameSaveTraitData(int traitIndex, MiniYaml yaml)
{ {
gameSaveTraitData[traitIndex] = yaml; gameSaveTraitData[traitIndex] = yaml;

View File

@@ -15,16 +15,16 @@ namespace OpenRA
{ {
public class WorldViewportSizes : IGlobalModData public class WorldViewportSizes : IGlobalModData
{ {
public readonly int2 CloseWindowHeights = new int2(480, 600); public readonly int2 CloseWindowHeights = new(480, 600);
public readonly int2 MediumWindowHeights = new int2(600, 900); public readonly int2 MediumWindowHeights = new(600, 900);
public readonly int2 FarWindowHeights = new int2(900, 1300); public readonly int2 FarWindowHeights = new(900, 1300);
public readonly float DefaultScale = 1.0f; public readonly float DefaultScale = 1.0f;
public readonly float MaxZoomScale = 2.0f; public readonly float MaxZoomScale = 2.0f;
public readonly int MaxZoomWindowHeight = 240; public readonly int MaxZoomWindowHeight = 240;
public readonly bool AllowNativeZoom = true; public readonly bool AllowNativeZoom = true;
public readonly Size MinEffectiveResolution = new Size(1024, 720); public readonly Size MinEffectiveResolution = new(1024, 720);
public int2 GetSizeRange(WorldViewport distance) public int2 GetSizeRange(WorldViewport distance)
{ {

View File

@@ -27,7 +27,7 @@ namespace OpenRA.Mods.Cnc.FileFormats
public uint Len; public uint Len;
} }
readonly PublicKey pubkey = new PublicKey(); readonly PublicKey pubkey = new();
readonly uint[] globOne = new uint[64]; readonly uint[] globOne = new uint[64];
uint globOneBitLen, globOneLenXTwo; uint globOneBitLen, globOneLenXTwo;

View File

@@ -25,7 +25,7 @@ namespace OpenRA.Mods.Cnc.FileSystem
public string Name { get; } public string Name { get; }
public IEnumerable<string> Contents => index.Keys; public IEnumerable<string> Contents => index.Keys;
readonly Dictionary<string, Entry> index = new Dictionary<string, Entry>(); readonly Dictionary<string, Entry> index = new();
readonly Stream s; readonly Stream s;
public BigFile(Stream s, string filename) public BigFile(Stream s, string filename)

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