Replace terniary null checks with coalescing.

This commit is contained in:
Paul Chote
2021-03-07 21:22:00 +00:00
committed by teinarss
parent 2473b8763b
commit d52ba83f96
43 changed files with 72 additions and 73 deletions

View File

@@ -65,7 +65,7 @@ namespace OpenRA
public CPos Location => OccupiesSpace.TopLeft; public CPos Location => OccupiesSpace.TopLeft;
public WPos CenterPosition => OccupiesSpace.CenterPosition; public WPos CenterPosition => OccupiesSpace.CenterPosition;
public WRot Orientation => facing != null ? facing.Orientation : WRot.None; public WRot Orientation => facing?.Orientation ?? WRot.None;
/// <summary>Value used to represent an invalid token.</summary> /// <summary>Value used to represent an invalid token.</summary>
public static readonly int InvalidConditionToken = -1; public static readonly int InvalidConditionToken = -1;

View File

@@ -206,7 +206,7 @@ namespace OpenRA
public static void RestartGame() public static void RestartGame()
{ {
var replay = OrderManager.Connection as ReplayConnection; var replay = OrderManager.Connection as ReplayConnection;
var replayName = replay != null ? replay.Filename : null; var replayName = replay?.Filename;
var lobbyInfo = OrderManager.LobbyInfo; var lobbyInfo = OrderManager.LobbyInfo;
// Reseed the RNG so this isn't an exact repeat of the last game // Reseed the RNG so this isn't an exact repeat of the last game

View File

@@ -112,7 +112,7 @@ namespace OpenRA.Graphics
int CurrentSequenceTickOrDefault() int CurrentSequenceTickOrDefault()
{ {
const int DefaultTick = 40; // 25 fps == 40 ms const int DefaultTick = 40; // 25 fps == 40 ms
return CurrentSequence != null ? CurrentSequence.Tick : DefaultTick; return CurrentSequence?.Tick ?? DefaultTick;
} }
void PlaySequence(string sequenceName) void PlaySequence(string sequenceName)

View File

@@ -38,16 +38,16 @@ namespace OpenRA.Graphics
public IRenderable[] Render(Actor self, WorldRenderer wr, PaletteReference pal) public IRenderable[] Render(Actor self, WorldRenderer wr, PaletteReference pal)
{ {
var center = self.CenterPosition; var center = self.CenterPosition;
var offset = OffsetFunc != null ? OffsetFunc() : WVec.Zero; var offset = OffsetFunc?.Invoke() ?? WVec.Zero;
var z = (ZOffset != null) ? ZOffset(center + offset) : 0; var z = ZOffset?.Invoke(center + offset) ?? 0;
return Animation.Render(center, offset, z, pal); return Animation.Render(center, offset, z, pal);
} }
public Rectangle ScreenBounds(Actor self, WorldRenderer wr) public Rectangle ScreenBounds(Actor self, WorldRenderer wr)
{ {
var center = self.CenterPosition; var center = self.CenterPosition;
var offset = OffsetFunc != null ? OffsetFunc() : WVec.Zero; var offset = OffsetFunc?.Invoke() ?? WVec.Zero;
return Animation.ScreenBounds(wr, center, offset); return Animation.ScreenBounds(wr, center, offset);
} }

View File

@@ -86,7 +86,7 @@ namespace OpenRA
public MapVisibility Visibility; public MapVisibility Visibility;
Lazy<Ruleset> rules; Lazy<Ruleset> rules;
public Ruleset Rules => rules != null ? rules.Value : null; public Ruleset Rules => rules?.Value;
public bool InvalidCustomRules { get; private set; } public bool InvalidCustomRules { get; private set; }
public bool DefinesUnsafeCustomRules { get; private set; } public bool DefinesUnsafeCustomRules { get; private set; }
public bool RulesLoaded { get; private set; } public bool RulesLoaded { get; private set; }

View File

@@ -452,7 +452,7 @@ namespace OpenRA
existingDict.TryGetValue(key, out var existingNode); existingDict.TryGetValue(key, out var existingNode);
overrideDict.TryGetValue(key, out var overrideNode); overrideDict.TryGetValue(key, out var overrideNode);
var loc = overrideNode == null ? default(MiniYamlNode.SourceLocation) : overrideNode.Location; var loc = overrideNode?.Location ?? default;
var comment = (overrideNode ?? existingNode).Comment; var comment = (overrideNode ?? existingNode).Comment;
var merged = (existingNode == null || overrideNode == null) ? overrideNode ?? existingNode : var merged = (existingNode == null || overrideNode == null) ? overrideNode ?? existingNode :
new MiniYamlNode(key, MergePartial(existingNode.Value, overrideNode.Value), comment, loc); new MiniYamlNode(key, MergePartial(existingNode.Value, overrideNode.Value), comment, loc);

View File

@@ -103,9 +103,9 @@ namespace OpenRA
return new PlayerBadge( return new PlayerBadge(
labelNode.Value.Value, labelNode.Value.Value,
icon24Node != null ? icon24Node.Value.Value : null, icon24Node?.Value.Value,
icon48Node != null ? icon48Node.Value.Value : null, icon48Node?.Value.Value,
icon72Node != null ? icon72Node.Value.Value : null); icon72Node?.Value.Value);
} }
public Sprite GetIcon(PlayerBadge badge) public Sprite GetIcon(PlayerBadge badge)

View File

@@ -323,9 +323,9 @@ namespace OpenRA
} }
} }
public float MusicSeekPosition => music != null ? music.SeekPosition : 0; public float MusicSeekPosition => music?.SeekPosition ?? 0;
public float VideoSeekPosition => video != null ? video.SeekPosition : 0; public float VideoSeekPosition => video?.SeekPosition ?? 0;
// Returns true if played successfully // Returns true if played successfully
public bool PlayPredefined(SoundType soundType, Ruleset ruleset, Player p, Actor voicedActor, string type, string definition, string variant, public bool PlayPredefined(SoundType soundType, Ruleset ruleset, Player p, Actor voicedActor, string type, string definition, string variant,
@@ -340,11 +340,11 @@ namespace OpenRA
if (ruleset.Voices == null || ruleset.Notifications == null) if (ruleset.Voices == null || ruleset.Notifications == null)
return false; return false;
var rules = (voicedActor != null) ? ruleset.Voices[type] : ruleset.Notifications[type]; var rules = voicedActor != null ? ruleset.Voices[type] : ruleset.Notifications[type];
if (rules == null) if (rules == null)
return false; return false;
var id = voicedActor != null ? voicedActor.ActorID : 0; var id = voicedActor?.ActorID ?? 0;
SoundPool pool; SoundPool pool;
var suffix = rules.DefaultVariant; var suffix = rules.DefaultVariant;

View File

@@ -592,7 +592,7 @@ namespace OpenRA.Support
Token lastToken = null; Token lastToken = null;
for (var i = 0; ;) for (var i = 0; ;)
{ {
var token = Token.GetNext(Expression, ref i, lastToken != null ? lastToken.Type : TokenType.Invalid); var token = Token.GetNext(Expression, ref i, lastToken?.Type ?? TokenType.Invalid);
if (token == null) if (token == null)
{ {
// Sanity check parsed tree // Sanity check parsed tree

View File

@@ -67,7 +67,7 @@ namespace OpenRA
LoadWidget(args, widget, c); LoadWidget(args, widget, c);
var logicNode = node.Value.Nodes.FirstOrDefault(n => n.Key == "Logic"); var logicNode = node.Value.Nodes.FirstOrDefault(n => n.Key == "Logic");
var logic = logicNode == null ? null : logicNode.Value.ToDictionary(); var logic = logicNode?.Value.ToDictionary();
args.Add("logicArgs", logic); args.Add("logicArgs", logic);
widget.PostInit(args); widget.PostInit(args);

View File

@@ -282,13 +282,13 @@ namespace OpenRA.Mods.Common.Orders
footprint.Add(t, MakeCellType(isCloseEnough && world.IsCellBuildable(t, actorInfo, buildingInfo) && (resourceLayer == null || resourceLayer.GetResourceType(t) == null))); footprint.Add(t, MakeCellType(isCloseEnough && world.IsCellBuildable(t, actorInfo, buildingInfo) && (resourceLayer == null || resourceLayer.GetResourceType(t) == null)));
} }
return preview != null ? preview.Render(wr, topLeft, footprint) : Enumerable.Empty<IRenderable>(); return preview?.Render(wr, topLeft, footprint) ?? Enumerable.Empty<IRenderable>();
} }
IEnumerable<IRenderable> IOrderGenerator.RenderAnnotations(WorldRenderer wr, World world) IEnumerable<IRenderable> IOrderGenerator.RenderAnnotations(WorldRenderer wr, World world)
{ {
var preview = variants[variant].Preview; var preview = variants[variant].Preview;
return preview != null ? preview.RenderAnnotations(wr, TopLeft) : Enumerable.Empty<IRenderable>(); return preview?.RenderAnnotations(wr, TopLeft) ?? Enumerable.Empty<IRenderable>();
} }
string IOrderGenerator.GetCursor(World world, CPos cell, int2 worldPixel, MouseInput mi) string IOrderGenerator.GetCursor(World world, CPos cell, int2 worldPixel, MouseInput mi)

View File

@@ -48,7 +48,7 @@ namespace OpenRA.Mods.Common.Scripting
[Desc("Return or set the time limit (in ticks). When setting, the time limit will count from now. Setting the time limit to 0 will disable it.")] [Desc("Return or set the time limit (in ticks). When setting, the time limit will count from now. Setting the time limit to 0 will disable it.")]
public int TimeLimit public int TimeLimit
{ {
get => tlm != null ? tlm.TimeLimit : 0; get => tlm?.TimeLimit ?? 0;
set set
{ {
@@ -62,7 +62,7 @@ namespace OpenRA.Mods.Common.Scripting
[Desc("The notification string used for custom time limit warnings. See the TimeLimitManager trait documentation for details.")] [Desc("The notification string used for custom time limit warnings. See the TimeLimitManager trait documentation for details.")]
public string TimeLimitNotification public string TimeLimitNotification
{ {
get => tlm != null ? tlm.Notification : null; get => tlm?.Notification;
set set
{ {

View File

@@ -393,7 +393,7 @@ namespace OpenRA.Mods.Common.Traits
protected virtual WRot CalculateMuzzleOrientation(Actor self, Barrel b) protected virtual WRot CalculateMuzzleOrientation(Actor self, Barrel b)
{ {
return WRot.FromYaw(b.Yaw).Rotate(turret != null ? turret.WorldOrientation : self.Orientation); return WRot.FromYaw(b.Yaw).Rotate(turret?.WorldOrientation ?? self.Orientation);
} }
public Actor Actor => self; public Actor Actor => self;

View File

@@ -119,7 +119,7 @@ namespace OpenRA.Mods.Common.Traits
actor => actor =>
{ {
var init = actor.GetInitOrDefault<StanceInit>(this); var init = actor.GetInitOrDefault<StanceInit>(this);
var stance = init != null ? init.Value : InitialStance; var stance = init?.Value ?? InitialStance;
return stances[(int)stance]; return stances[(int)stance];
}, },
(actor, value) => actor.ReplaceInit(new StanceInit(this, (UnitStance)stances.IndexOf(value)))); (actor, value) => actor.ReplaceInit(new StanceInit(this, (UnitStance)stances.IndexOf(value))));

View File

@@ -141,7 +141,7 @@ namespace OpenRA.Mods.Common.Traits
Info.ConstructionYardTypes.Contains(a.Info.Name)) Info.ConstructionYardTypes.Contains(a.Info.Name))
.RandomOrDefault(world.LocalRandom); .RandomOrDefault(world.LocalRandom);
return randomConstructionYard != null ? randomConstructionYard.Location : initialBaseCenter; return randomConstructionYard?.Location ?? initialBaseCenter;
} }
public CPos DefenseCenter => defenseCenter; public CPos DefenseCenter => defenseCenter;

View File

@@ -55,7 +55,7 @@ namespace OpenRA.Mods.Common.Traits
Info.ConstructionYardTypes.Contains(a.Info.Name)) Info.ConstructionYardTypes.Contains(a.Info.Name))
.RandomOrDefault(world.LocalRandom); .RandomOrDefault(world.LocalRandom);
return randomConstructionYard != null ? randomConstructionYard.Location : initialBaseCenter; return randomConstructionYard?.Location ?? initialBaseCenter;
} }
readonly World world; readonly World world;

View File

@@ -95,7 +95,7 @@ namespace OpenRA.Mods.Common.Traits
Info.ConstructionYardTypes.Contains(a.Info.Name)) Info.ConstructionYardTypes.Contains(a.Info.Name))
.RandomOrDefault(World.LocalRandom); .RandomOrDefault(World.LocalRandom);
return randomConstructionYard != null ? randomConstructionYard.Location : initialBaseCenter; return randomConstructionYard?.Location ?? initialBaseCenter;
} }
public readonly World World; public readonly World World;

View File

@@ -59,8 +59,7 @@ namespace OpenRA.Mods.Common.Traits
public static string GetInitialFaction(ActorInfo ai, string defaultFaction) public static string GetInitialFaction(ActorInfo ai, string defaultFaction)
{ {
var bi = ai.TraitInfoOrDefault<BuildableInfo>(); return ai.TraitInfoOrDefault<BuildableInfo>()?.ForceFaction ?? defaultFaction;
return bi != null ? bi.ForceFaction ?? defaultFaction : defaultFaction;
} }
} }

View File

@@ -65,14 +65,14 @@ namespace OpenRA.Mods.Common.Traits
protected static object LoadFootprint(MiniYaml yaml) protected static object LoadFootprint(MiniYaml yaml)
{ {
var footprintYaml = yaml.Nodes.FirstOrDefault(n => n.Key == "Footprint"); var footprintYaml = yaml.Nodes.FirstOrDefault(n => n.Key == "Footprint");
var footprintChars = footprintYaml != null ? footprintYaml.Value.Value.Where(x => !char.IsWhiteSpace(x)).ToArray() : new[] { 'x' }; var footprintChars = footprintYaml?.Value.Value.Where(x => !char.IsWhiteSpace(x)).ToArray() ?? new[] { 'x' };
var dimensionsYaml = yaml.Nodes.FirstOrDefault(n => n.Key == "Dimensions"); var dimensionsYaml = yaml.Nodes.FirstOrDefault(n => n.Key == "Dimensions");
var dim = dimensionsYaml != null ? FieldLoader.GetValue<CVec>("Dimensions", dimensionsYaml.Value.Value) : new CVec(1, 1); var dim = dimensionsYaml != null ? FieldLoader.GetValue<CVec>("Dimensions", dimensionsYaml.Value.Value) : new CVec(1, 1);
if (footprintChars.Length != dim.X * dim.Y) if (footprintChars.Length != dim.X * dim.Y)
{ {
var fp = footprintYaml.Value.Value.ToString(); var fp = footprintYaml.Value.Value;
var dims = dim.X + "x" + dim.Y; var dims = dim.X + "x" + dim.Y;
throw new YamlException("Invalid footprint: {0} does not match dimensions {1}".F(fp, dims)); throw new YamlException("Invalid footprint: {0} does not match dimensions {1}".F(fp, dims));
} }

View File

@@ -104,7 +104,7 @@ namespace OpenRA.Mods.Common.Traits
if (Info.SourceCap > 0) if (Info.SourceCap > 0)
{ {
var timedCount = timedTokens.Count(t => t.Source == source); var timedCount = timedTokens.Count(t => t.Source == source);
if ((permanent != null ? permanent.Count + timedCount : timedCount) >= Info.SourceCap) if ((permanent?.Count ?? 0) + timedCount >= Info.SourceCap)
{ {
// Get timed token from the same source with closest expiration. // Get timed token from the same source with closest expiration.
var expireIndex = timedTokens.FindIndex(t => t.Source == source); var expireIndex = timedTokens.FindIndex(t => t.Source == source);

View File

@@ -43,7 +43,7 @@ namespace OpenRA.Mods.Common.Traits
actor => actor =>
{ {
var init = actor.GetInitOrDefault<HealthInit>(); var init = actor.GetInitOrDefault<HealthInit>();
return init != null ? init.Value : 100; return init?.Value ?? 100;
}, },
(actor, value) => actor.ReplaceInit(new HealthInit((int)value))); (actor, value) => actor.ReplaceInit(new HealthInit((int)value)));
} }

View File

@@ -139,7 +139,7 @@ namespace OpenRA.Mods.Common.Traits
actor => actor =>
{ {
var init = actor.GetInitOrDefault<FacingInit>(this); var init = actor.GetInitOrDefault<FacingInit>(this);
return (init != null ? init.Value : InitialFacing).Angle; return (init?.Value ?? InitialFacing).Angle;
}, },
(actor, value) => actor.ReplaceInit(new FacingInit(new WAngle((int)value)))); (actor, value) => actor.ReplaceInit(new FacingInit(new WAngle((int)value))));
} }

View File

@@ -60,7 +60,7 @@ namespace OpenRA.Mods.Common.Traits
var exploredMap = init.World.LobbyInfo.GlobalSettings.OptionOrDefault("explored", shroudInfo.ExploredMapCheckboxEnabled); var exploredMap = init.World.LobbyInfo.GlobalSettings.OptionOrDefault("explored", shroudInfo.ExploredMapCheckboxEnabled);
startsRevealed = exploredMap && init.Contains<SpawnedByMapInit>() && !init.Contains<HiddenUnderFogInit>(); startsRevealed = exploredMap && init.Contains<SpawnedByMapInit>() && !init.Contains<HiddenUnderFogInit>();
var buildingInfo = init.Self.Info.TraitInfoOrDefault<BuildingInfo>(); var buildingInfo = init.Self.Info.TraitInfoOrDefault<BuildingInfo>();
var footprintCells = buildingInfo != null ? buildingInfo.FrozenUnderFogTiles(init.Self.Location).ToList() : new List<CPos>() { init.Self.Location }; var footprintCells = buildingInfo?.FrozenUnderFogTiles(init.Self.Location).ToList() ?? new List<CPos>() { init.Self.Location };
footprint = footprintCells.SelectMany(c => map.ProjectedCellsCovering(c.ToMPos(map))).ToArray(); footprint = footprintCells.SelectMany(c => map.ProjectedCellsCovering(c.ToMPos(map))).ToArray();
} }

View File

@@ -78,9 +78,9 @@ namespace OpenRA.Mods.Common.Traits
var myTeam = self.World.LobbyInfo.ClientWithIndex(self.Owner.ClientIndex).Team; var myTeam = self.World.LobbyInfo.ClientWithIndex(self.Owner.ClientIndex).Team;
var teams = self.World.Players.Where(p => !p.NonCombatant && p.Playable) var teams = self.World.Players.Where(p => !p.NonCombatant && p.Playable)
.Select(p => (Player: p, PlayerStatistics: p.PlayerActor.TraitOrDefault<PlayerStatistics>())) .Select(p => (Player: p, PlayerStatistics: p.PlayerActor.TraitOrDefault<PlayerStatistics>()))
.OrderByDescending(p => p.PlayerStatistics != null ? p.PlayerStatistics.Experience : 0) .OrderByDescending(p => p.PlayerStatistics?.Experience ?? 0)
.GroupBy(p => (self.World.LobbyInfo.ClientWithIndex(p.Player.ClientIndex) ?? new Session.Client()).Team) .GroupBy(p => (self.World.LobbyInfo.ClientWithIndex(p.Player.ClientIndex) ?? new Session.Client()).Team)
.OrderByDescending(g => g.Sum(gg => gg.PlayerStatistics != null ? gg.PlayerStatistics.Experience : 0)); .OrderByDescending(g => g.Sum(gg => gg.PlayerStatistics?.Experience ?? 0));
if (teams.First().Key == myTeam && (myTeam != 0 || teams.First().First().Player == self.Owner)) if (teams.First().Key == myTeam && (myTeam != 0 || teams.First().First().Player == self.Owner))
{ {

View File

@@ -91,7 +91,7 @@ namespace OpenRA.Mods.Common.Traits
} }
var producer = queue.MostLikelyProducer(); var producer = queue.MostLikelyProducer();
var faction = producer.Trait != null ? producer.Trait.Faction : self.Owner.Faction.InternalName; var faction = producer.Trait?.Faction ?? self.Owner.Faction.InternalName;
var buildingInfo = actorInfo.TraitInfo<BuildingInfo>(); var buildingInfo = actorInfo.TraitInfo<BuildingInfo>();
var buildableInfo = actorInfo.TraitInfoOrDefault<BuildableInfo>(); var buildableInfo = actorInfo.TraitInfoOrDefault<BuildableInfo>();

View File

@@ -116,9 +116,9 @@ namespace OpenRA.Mods.Common.Traits
var myTeam = self.World.LobbyInfo.ClientWithIndex(self.Owner.ClientIndex).Team; var myTeam = self.World.LobbyInfo.ClientWithIndex(self.Owner.ClientIndex).Team;
var teams = self.World.Players.Where(p => !p.NonCombatant && p.Playable) var teams = self.World.Players.Where(p => !p.NonCombatant && p.Playable)
.Select(p => (Player: p, PlayerStatistics: p.PlayerActor.TraitOrDefault<PlayerStatistics>())) .Select(p => (Player: p, PlayerStatistics: p.PlayerActor.TraitOrDefault<PlayerStatistics>()))
.OrderByDescending(p => p.PlayerStatistics != null ? p.PlayerStatistics.Experience : 0) .OrderByDescending(p => p.PlayerStatistics?.Experience ?? 0)
.GroupBy(p => (self.World.LobbyInfo.ClientWithIndex(p.Player.ClientIndex) ?? new Session.Client()).Team) .GroupBy(p => (self.World.LobbyInfo.ClientWithIndex(p.Player.ClientIndex) ?? new Session.Client()).Team)
.OrderByDescending(g => g.Sum(gg => gg.PlayerStatistics != null ? gg.PlayerStatistics.Experience : 0)); .OrderByDescending(g => g.Sum(gg => gg.PlayerStatistics?.Experience ?? 0));
if (teams.First().Key == myTeam && (myTeam != 0 || teams.First().First().Player == self.Owner)) if (teams.First().Key == myTeam && (myTeam != 0 || teams.First().First().Player == self.Owner))
{ {

View File

@@ -63,7 +63,7 @@ namespace OpenRA.Mods.Common.Traits
actor => actor =>
{ {
var init = actor.GetInitOrDefault<PlugInit>(this); var init = actor.GetInitOrDefault<PlugInit>(this);
return init != null ? init.Value : ""; return init?.Value ?? "";
}, },
(actor, value) => (actor, value) =>
{ {

View File

@@ -82,7 +82,7 @@ namespace OpenRA.Mods.Common.Traits.Render
{ {
body = self.Trait<BodyOrientation>(); body = self.Trait<BodyOrientation>();
facing = self.TraitOrDefault<IFacing>(); facing = self.TraitOrDefault<IFacing>();
cachedFacing = facing != null ? facing.Facing : WAngle.Zero; cachedFacing = facing?.Facing ?? WAngle.Zero;
cachedPosition = self.CenterPosition; cachedPosition = self.CenterPosition;
base.Created(self); base.Created(self);
@@ -126,14 +126,14 @@ namespace OpenRA.Mods.Common.Traits.Render
var pos = Info.Type == TrailType.CenterPosition ? spawnPosition + body.LocalToWorld(offsetRotation) : var pos = Info.Type == TrailType.CenterPosition ? spawnPosition + body.LocalToWorld(offsetRotation) :
self.World.Map.CenterOfCell(spawnCell); self.World.Map.CenterOfCell(spawnCell);
var spawnFacing = Info.SpawnAtLastPosition ? cachedFacing : (facing != null ? facing.Facing : WAngle.Zero); var spawnFacing = Info.SpawnAtLastPosition ? cachedFacing : facing?.Facing ?? WAngle.Zero;
if ((Info.TerrainTypes.Count == 0 || Info.TerrainTypes.Contains(type)) && !string.IsNullOrEmpty(Info.Image)) if ((Info.TerrainTypes.Count == 0 || Info.TerrainTypes.Contains(type)) && !string.IsNullOrEmpty(Info.Image))
self.World.AddFrameEndTask(w => w.Add(new SpriteEffect(pos, spawnFacing, self.World, Info.Image, self.World.AddFrameEndTask(w => w.Add(new SpriteEffect(pos, spawnFacing, self.World, Info.Image,
Info.Sequences.Random(Game.CosmeticRandom), Info.Palette, Info.VisibleThroughFog))); Info.Sequences.Random(Game.CosmeticRandom), Info.Palette, Info.VisibleThroughFog)));
cachedPosition = self.CenterPosition; cachedPosition = self.CenterPosition;
cachedFacing = facing != null ? facing.Facing : WAngle.Zero; cachedFacing = facing?.Facing ?? WAngle.Zero;
ticks = 0; ticks = 0;
cachedInterval = isMoving ? Info.MovingInterval : Info.StationaryInterval; cachedInterval = isMoving ? Info.MovingInterval : Info.StationaryInterval;

View File

@@ -40,7 +40,7 @@ namespace OpenRA.Mods.Common.Traits.Render
public RenderDebugState(Actor self, RenderDebugStateInfo info) public RenderDebugState(Actor self, RenderDebugStateInfo info)
{ {
var buildingInfo = self.Info.TraitInfoOrDefault<BuildingInfo>(); var buildingInfo = self.Info.TraitInfoOrDefault<BuildingInfo>();
var yOffset = buildingInfo == null ? 1 : buildingInfo.Dimensions.Y; var yOffset = buildingInfo?.Dimensions.Y ?? 1;
offset = new WVec(0, 512 * yOffset, 0); offset = new WVec(0, 512 * yOffset, 0);
this.self = self; this.self = self;

View File

@@ -60,7 +60,7 @@ namespace OpenRA.Mods.Common.Traits.Render
if (facings == -1) if (facings == -1)
{ {
var qbo = init.Actor.TraitInfoOrDefault<IQuantizeBodyOrientationInfo>(); var qbo = init.Actor.TraitInfoOrDefault<IQuantizeBodyOrientationInfo>();
facings = qbo != null ? qbo.QuantizedBodyFacings(init.Actor, sequenceProvider, faction) : 1; facings = qbo?.QuantizedBodyFacings(init.Actor, sequenceProvider, faction) ?? 1;
} }
} }
@@ -127,7 +127,7 @@ namespace OpenRA.Mods.Common.Traits.Render
// Return to the caller whether the renderable position or size has changed // Return to the caller whether the renderable position or size has changed
var visible = IsVisible; var visible = IsVisible;
var offset = Animation.OffsetFunc != null ? Animation.OffsetFunc() : WVec.Zero; var offset = Animation.OffsetFunc?.Invoke() ?? WVec.Zero;
var sequence = Animation.Animation.CurrentSequence; var sequence = Animation.Animation.CurrentSequence;
var updated = visible != cachedVisible || offset != cachedOffset || sequence != cachedSequence; var updated = visible != cachedVisible || offset != cachedOffset || sequence != cachedSequence;

View File

@@ -93,7 +93,7 @@ namespace OpenRA.Mods.Common.Traits.Render
{ {
// Return to the caller whether the renderable position or size has changed // Return to the caller whether the renderable position or size has changed
var visible = model.IsVisible; var visible = model.IsVisible;
var offset = model.OffsetFunc != null ? model.OffsetFunc() : WVec.Zero; var offset = model.OffsetFunc?.Invoke() ?? WVec.Zero;
var updated = visible != cachedVisible || offset != cachedOffset; var updated = visible != cachedVisible || offset != cachedOffset;
cachedVisible = visible; cachedVisible = visible;

View File

@@ -52,9 +52,13 @@ namespace OpenRA.Mods.Common.Traits
if (IsTraitDisabled || !correctFaction) if (IsTraitDisabled || !correctFaction)
return; return;
var buildingInfo = self.Info.TraitInfoOrDefault<BuildingInfo>();
if (buildingInfo == null)
return;
var csv = self.Info.TraitInfoOrDefault<CustomSellValueInfo>(); var csv = self.Info.TraitInfoOrDefault<CustomSellValueInfo>();
var valued = self.Info.TraitInfoOrDefault<ValuedInfo>(); var valued = self.Info.TraitInfoOrDefault<ValuedInfo>();
var cost = csv != null ? csv.Value : (valued != null ? valued.Cost : 0); var cost = csv?.Value ?? valued?.Cost ?? 0;
var health = self.TraitOrDefault<IHealth>(); var health = self.TraitOrDefault<IHealth>();
var dudesValue = Info.ValuePercent * cost / 100; var dudesValue = Info.ValuePercent * cost / 100;
@@ -67,16 +71,14 @@ namespace OpenRA.Mods.Common.Traits
dudesValue = 0; dudesValue = 0;
} }
var buildingInfo = self.Info.TraitInfoOrDefault<BuildingInfo>(); var eligibleLocations = buildingInfo.Tiles(self.Location).ToList();
var eligibleLocations = buildingInfo != null ? buildingInfo.Tiles(self.Location).ToList() : new List<CPos>();
var actorTypes = Info.ActorTypes.Select(a => var actorTypes = Info.ActorTypes.Select(a =>
{ {
var av = self.World.Map.Rules.Actors[a].TraitInfoOrDefault<ValuedInfo>(); var av = self.World.Map.Rules.Actors[a].TraitInfoOrDefault<ValuedInfo>();
return new return new
{ {
Name = a, Name = a,
Cost = av != null ? av.Cost : 0 Cost = av?.Cost ?? 0
}; };
}).ToList(); }).ToList();

View File

@@ -153,7 +153,7 @@ namespace OpenRA.Mods.Common.Traits
{ {
var ios = actor.TraitInfoOrDefault<IOccupySpaceInfo>(); var ios = actor.TraitInfoOrDefault<IOccupySpaceInfo>();
var buildingInfo = ios as BuildingInfo; var buildingInfo = ios as BuildingInfo;
actorCenterOffset = buildingInfo != null ? buildingInfo.CenterOffset(world) : WVec.Zero; actorCenterOffset = buildingInfo?.CenterOffset(world) ?? WVec.Zero;
actorSharesCell = ios != null && ios.SharesCell; actorSharesCell = ios != null && ios.SharesCell;
actorSubCell = SubCell.Invalid; actorSubCell = SubCell.Invalid;

View File

@@ -239,7 +239,7 @@ namespace OpenRA.Mods.Common.Traits
void WorldOnRenderPlayerChanged(Player player) void WorldOnRenderPlayerChanged(Player player)
{ {
var newShroud = player != null ? player.Shroud : null; var newShroud = player?.Shroud;
if (shroud != newShroud) if (shroud != newShroud)
{ {

View File

@@ -60,7 +60,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
var variant = resource.Sequences.FirstOrDefault(); var variant = resource.Sequences.FirstOrDefault();
var sequence = rules.Sequences.GetSequence("resources", variant); var sequence = rules.Sequences.GetSequence("resources", variant);
var frame = sequence.Frames != null ? sequence.Frames.Last() : resource.MaxDensity - 1; var frame = sequence.Frames?.Last() ?? resource.MaxDensity - 1;
layerPreview.GetSprite = () => sequence.GetSprite(frame); layerPreview.GetSprite = () => sequence.GetSprite(frame);
layerPreview.Bounds.Width = tileSize.Width; layerPreview.Bounds.Width = tileSize.Width;

View File

@@ -118,7 +118,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
if (selectedDirectory == null) if (selectedDirectory == null)
selectedDirectory = writableDirectories.OrderByDescending(kv => kv.Classification).First(); selectedDirectory = writableDirectories.OrderByDescending(kv => kv.Classification).First();
directoryDropdown.GetText = () => selectedDirectory == null ? "" : selectedDirectory.DisplayName; directoryDropdown.GetText = () => selectedDirectory?.DisplayName ?? "";
directoryDropdown.OnClick = () => directoryDropdown.OnClick = () =>
directoryDropdown.ShowDropDown("LABEL_DROPDOWN_TEMPLATE", 210, writableDirectories, setupItem); directoryDropdown.ShowDropDown("LABEL_DROPDOWN_TEMPLATE", 210, writableDirectories, setupItem);
} }

View File

@@ -38,7 +38,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
return; return;
var tooltip = armyUnit.TooltipInfo; var tooltip = armyUnit.TooltipInfo;
var name = tooltip != null ? tooltip.Name : armyUnit.ActorInfo.Name; var name = tooltip?.Name ?? armyUnit.ActorInfo.Name;
var buildable = armyUnit.BuildableInfo; var buildable = armyUnit.BuildableInfo;
nameLabel.Text = name; nameLabel.Text = name;

View File

@@ -67,9 +67,9 @@ namespace OpenRA.Mods.Common.Widgets.Logic
var teams = world.Players.Where(p => !p.NonCombatant && p.Playable) var teams = world.Players.Where(p => !p.NonCombatant && p.Playable)
.Select(p => (Player: p, PlayerStatistics: p.PlayerActor.TraitOrDefault<PlayerStatistics>())) .Select(p => (Player: p, PlayerStatistics: p.PlayerActor.TraitOrDefault<PlayerStatistics>()))
.OrderByDescending(p => p.PlayerStatistics != null ? p.PlayerStatistics.Experience : 0) .OrderByDescending(p => p.PlayerStatistics?.Experience ?? 0)
.GroupBy(p => (world.LobbyInfo.ClientWithIndex(p.Player.ClientIndex) ?? new Session.Client()).Team) .GroupBy(p => (world.LobbyInfo.ClientWithIndex(p.Player.ClientIndex) ?? new Session.Client()).Team)
.OrderByDescending(g => g.Sum(gg => gg.PlayerStatistics != null ? gg.PlayerStatistics.Experience : 0)); .OrderByDescending(g => g.Sum(gg => gg.PlayerStatistics?.Experience ?? 0));
foreach (var t in teams) foreach (var t in teams)
{ {
@@ -111,7 +111,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
} }
var scoreCache = new CachedTransform<int, string>(s => s.ToString()); var scoreCache = new CachedTransform<int, string>(s => s.ToString());
item.Get<LabelWidget>("SCORE").GetText = () => scoreCache.Update(p.PlayerStatistics != null ? p.PlayerStatistics.Experience : 0); item.Get<LabelWidget>("SCORE").GetText = () => scoreCache.Update(p.PlayerStatistics?.Experience ?? 0);
playerPanel.AddChild(item); playerPanel.AddChild(item);
} }

View File

@@ -52,7 +52,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
if (status == null && shouldShowStatus()) if (status == null && shouldShowStatus())
return statusText(); return statusText();
var timeLimit = tlm != null ? tlm.TimeLimit : 0; var timeLimit = tlm?.TimeLimit ?? 0;
var displayTick = timeLimit > 0 ? timeLimit - world.WorldTick : world.WorldTick; var displayTick = timeLimit > 0 ? timeLimit - world.WorldTick : world.WorldTick;
return WidgetUtils.FormatTime(Math.Max(0, displayTick), timestep); return WidgetUtils.FormatTime(Math.Max(0, displayTick), timestep);
}; };

View File

@@ -119,7 +119,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
var moi = world.Map.Rules.Actors["player"].TraitInfoOrDefault<MissionObjectivesInfo>(); var moi = world.Map.Rules.Actors["player"].TraitInfoOrDefault<MissionObjectivesInfo>();
if (moi != null) if (moi != null)
{ {
var faction = world.LocalPlayer == null ? null : world.LocalPlayer.Faction.InternalName; var faction = world.LocalPlayer?.Faction.InternalName;
Game.Sound.PlayNotification(world.Map.Rules, null, "Speech", moi.LeaveNotification, faction); Game.Sound.PlayNotification(world.Map.Rules, null, "Speech", moi.LeaveNotification, faction);
} }
} }
@@ -127,7 +127,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
leaving = true; leaving = true;
var iop = world.WorldActor.TraitsImplementing<IObjectivesPanel>().FirstOrDefault(); var iop = world.WorldActor.TraitsImplementing<IObjectivesPanel>().FirstOrDefault();
var exitDelay = iop != null ? iop.ExitDelay : 0; var exitDelay = iop?.ExitDelay ?? 0;
if (mpe != null) if (mpe != null)
{ {
Game.RunAfterDelay(exitDelay, () => Game.RunAfterDelay(exitDelay, () =>
@@ -208,7 +208,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
return; return;
var iop = world.WorldActor.TraitsImplementing<IObjectivesPanel>().FirstOrDefault(); var iop = world.WorldActor.TraitsImplementing<IObjectivesPanel>().FirstOrDefault();
var exitDelay = iop != null ? iop.ExitDelay : 0; var exitDelay = iop?.ExitDelay ?? 0;
Action onRestart = () => Action onRestart = () =>
{ {

View File

@@ -41,7 +41,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
if (world.LocalPlayer.WinState != WinState.Undefined && !loadingObserverWidgets) if (world.LocalPlayer.WinState != WinState.Undefined && !loadingObserverWidgets)
{ {
loadingObserverWidgets = true; loadingObserverWidgets = true;
Game.RunAfterDelay(objectives != null ? objectives.GameOverDelay : 0, () => Game.RunAfterDelay(objectives?.GameOverDelay ?? 0, () =>
{ {
if (!Game.IsCurrentWorld(world)) if (!Game.IsCurrentWorld(world))
return; return;

View File

@@ -49,26 +49,24 @@ namespace OpenRA.Mods.Common.Widgets.Logic
ActorInfo lastActor = null; ActorInfo lastActor = null;
Hotkey lastHotkey = Hotkey.Invalid; Hotkey lastHotkey = Hotkey.Invalid;
var lastPowerState = pm == null ? PowerState.Normal : pm.PowerState; var lastPowerState = pm?.PowerState ?? PowerState.Normal;
var descLabelY = descLabel.Bounds.Y; var descLabelY = descLabel.Bounds.Y;
var descLabelPadding = descLabel.Bounds.Height; var descLabelPadding = descLabel.Bounds.Height;
tooltipContainer.BeforeRender = () => tooltipContainer.BeforeRender = () =>
{ {
var tooltipIcon = getTooltipIcon(); var tooltipIcon = getTooltipIcon();
if (tooltipIcon == null)
return;
var actor = tooltipIcon.Actor; var actor = tooltipIcon?.Actor;
if (actor == null) if (actor == null)
return; return;
var hotkey = tooltipIcon.Hotkey != null ? tooltipIcon.Hotkey.GetValue() : Hotkey.Invalid; var hotkey = tooltipIcon.Hotkey?.GetValue() ?? Hotkey.Invalid;
if (actor == lastActor && hotkey == lastHotkey && (pm == null || pm.PowerState == lastPowerState)) if (actor == lastActor && hotkey == lastHotkey && (pm == null || pm.PowerState == lastPowerState))
return; return;
var tooltip = actor.TraitInfos<TooltipInfo>().FirstOrDefault(info => info.EnabledByDefault); var tooltip = actor.TraitInfos<TooltipInfo>().FirstOrDefault(info => info.EnabledByDefault);
var name = tooltip != null ? tooltip.Name : actor.Name; var name = tooltip?.Name ?? actor.Name;
var buildable = actor.TraitInfo<BuildableInfo>(); var buildable = actor.TraitInfo<BuildableInfo>();
var cost = 0; var cost = 0;
@@ -125,7 +123,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
powerSize = font.Measure(powerLabel.Text); powerSize = font.Measure(powerLabel.Text);
} }
var buildTime = tooltipIcon.ProductionQueue == null ? 0 : tooltipIcon.ProductionQueue.GetBuildTime(actor, buildable); var buildTime = tooltipIcon.ProductionQueue?.GetBuildTime(actor, buildable) ?? 0;
var timeModifier = pm != null && pm.PowerState != PowerState.Normal ? tooltipIcon.ProductionQueue.Info.LowPowerModifier : 100; var timeModifier = pm != null && pm.PowerState != PowerState.Normal ? tooltipIcon.ProductionQueue.Info.LowPowerModifier : 100;
timeLabel.Text = formatBuildTime.Update((buildTime * timeModifier) / 100); timeLabel.Text = formatBuildTime.Update((buildTime * timeModifier) / 100);

View File

@@ -49,7 +49,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
// to efficiently work when the label is going to change, requiring a panel relayout // to efficiently work when the label is going to change, requiring a panel relayout
var remainingSeconds = (int)Math.Ceiling(sp.RemainingTicks * world.Timestep / 1000f); var remainingSeconds = (int)Math.Ceiling(sp.RemainingTicks * world.Timestep / 1000f);
var hotkey = icon.Hotkey != null ? icon.Hotkey.GetValue() : Hotkey.Invalid; var hotkey = icon.Hotkey?.GetValue() ?? Hotkey.Invalid;
if (sp == lastPower && hotkey == lastHotkey && lastRemainingSeconds == remainingSeconds) if (sp == lastPower && hotkey == lastHotkey && lastRemainingSeconds == remainingSeconds)
return; return;