Formatted all files.

Automatically formatted all files via VS. This generally corrects indentation, removes trailing whitespace and corrects misplaced tabs or spaces. Manually tweaked a few files where required.
This commit is contained in:
RoosterDragon
2015-01-04 22:09:32 +00:00
parent 6468c0b6e6
commit a6cda967c2
153 changed files with 740 additions and 698 deletions

View File

@@ -334,8 +334,9 @@ namespace OpenRA.Editor
{ {
var vX = (int)Math.Floor((mousePos.X - Offset.X) / Zoom); var vX = (int)Math.Floor((mousePos.X - Offset.X) / Zoom);
var vY = (int)Math.Floor((mousePos.Y - Offset.Y) / Zoom); var vY = (int)Math.Floor((mousePos.Y - Offset.Y) / Zoom);
return new CPos((vX + TileSetRenderer.TileSize - 1) / TileSetRenderer.TileSize, return new CPos(
(vY + TileSetRenderer.TileSize - 1) / TileSetRenderer.TileSize); (vX + TileSetRenderer.TileSize - 1) / TileSetRenderer.TileSize,
(vY + TileSetRenderer.TileSize - 1) / TileSetRenderer.TileSize);
} }
public void DrawActor(SGraphics g, CPos p, ActorTemplate t, ColorPalette cp) public void DrawActor(SGraphics g, CPos p, ActorTemplate t, ColorPalette cp)

View File

@@ -156,7 +156,7 @@ namespace OpenRA
else if (fieldType == typeof(decimal)) else if (fieldType == typeof(decimal))
{ {
decimal res; decimal res;
if (decimal.TryParse(value.Replace("%", ""), NumberStyles.Float, NumberFormatInfo.InvariantInfo, out res)) if (decimal.TryParse(value.Replace("%", ""), NumberStyles.Float, NumberFormatInfo.InvariantInfo, out res))
return res * (value.Contains('%') ? 0.01m : 1m); return res * (value.Contains('%') ? 0.01m : 1m);
return InvalidValueAction(value, fieldType, fieldName); return InvalidValueAction(value, fieldType, fieldName);
} }
@@ -291,7 +291,7 @@ namespace OpenRA
if (Exts.TryParseIntegerInvariant(value, out rr) if (Exts.TryParseIntegerInvariant(value, out rr)
&& Exts.TryParseIntegerInvariant(value, out rp) && Exts.TryParseIntegerInvariant(value, out rp)
&& Exts.TryParseIntegerInvariant(value, out ry)) && Exts.TryParseIntegerInvariant(value, out ry))
return new WRot(new WAngle(rr), new WAngle(rp), new WAngle(ry)); return new WRot(new WAngle(rr), new WAngle(rp), new WAngle(ry));
} }
return InvalidValueAction(value, fieldType, fieldName); return InvalidValueAction(value, fieldType, fieldName);

View File

@@ -390,7 +390,8 @@ namespace OpenRA.FileFormats
MulBignumWord(esi, globOne, tmp, 2 * len); MulBignumWord(esi, globOne, tmp, 2 * len);
if ((*edi & 0x8000) == 0) if ((*edi & 0x8000) == 0)
{ {
if (0 != SubBigNum((uint*)esi, (uint*)esi, g1, 0, (int)len))(*edi)--; if (0 != SubBigNum((uint*)esi, (uint*)esi, g1, 0, (int)len))
(*edi)--;
} }
} }
} }

View File

@@ -33,17 +33,17 @@ namespace OpenRA.FileFormats
Transforms = new float[16 * FrameCount * LimbCount]; Transforms = new float[16 * FrameCount * LimbCount];
for (var j = 0; j < FrameCount; j++) for (var j = 0; j < FrameCount; j++)
for (var i = 0; i < LimbCount; i++) for (var i = 0; i < LimbCount; i++)
{ {
// Convert to column-major matrices and add the final matrix row // Convert to column-major matrices and add the final matrix row
var c = 16 * (LimbCount * j + i); var c = 16 * (LimbCount * j + i);
Transforms[c + 3] = 0; Transforms[c + 3] = 0;
Transforms[c + 7] = 0; Transforms[c + 7] = 0;
Transforms[c + 11] = 0; Transforms[c + 11] = 0;
Transforms[c + 15] = 1; Transforms[c + 15] = 1;
for (var k = 0; k < 12; k++) for (var k = 0; k < 12; k++)
Transforms[c + ids[k]] = s.ReadFloat(); Transforms[c + ids[k]] = s.ReadFloat();
} }
} }
public static HvaReader Load(string filename) public static HvaReader Load(string filename)

View File

@@ -44,9 +44,9 @@ namespace OpenRA.FileFormats
switch (line[0]) switch (line[0])
{ {
case ';': break; case ';': break;
case '[': currentSection = ProcessSection(line); break; case '[': currentSection = ProcessSection(line); break;
default: ProcessEntry(line, currentSection); break; default: ProcessEntry(line, currentSection); break;
} }
} }
} }

View File

@@ -197,10 +197,10 @@ namespace OpenRA.FileFormats
} }
compressed = type == "SND2"; compressed = type == "SND2";
break; break;
default: default:
stream.ReadBytes((int)length); stream.ReadBytes((int)length);
break; break;
} }
// Chunks are aligned on even bytes; advance by a byte if the next one is null // Chunks are aligned on even bytes; advance by a byte if the next one is null
@@ -283,18 +283,18 @@ namespace OpenRA.FileFormats
{ {
case "VQFR": case "VQFR":
DecodeVQFR(stream); DecodeVQFR(stream);
break; break;
case "\0VQF": case "\0VQF":
stream.ReadByte(); stream.ReadByte();
DecodeVQFR(stream); DecodeVQFR(stream);
break; break;
case "VQFL": case "VQFL":
DecodeVQFR(stream, "VQFL"); DecodeVQFR(stream, "VQFL");
break; break;
default: default:
// Don't parse sound here. // Don't parse sound here.
stream.ReadBytes((int)length); stream.ReadBytes((int)length);
break; break;
} }
// Chunks are aligned on even bytes; advance by a byte if the next one is null // Chunks are aligned on even bytes; advance by a byte if the next one is null
@@ -343,10 +343,10 @@ namespace OpenRA.FileFormats
if (parentType == "VQFL") if (parentType == "VQFL")
return; return;
break; break;
case "CBF0": case "CBF0":
cbf = s.ReadBytes(subchunkLength); cbf = s.ReadBytes(subchunkLength);
break; break;
// frame-modifier chunk // frame-modifier chunk
case "CBP0": case "CBP0":
@@ -366,7 +366,7 @@ namespace OpenRA.FileFormats
bytes.CopyTo(cbp, chunkBufferOffset); bytes.CopyTo(cbp, chunkBufferOffset);
chunkBufferOffset += subchunkLength; chunkBufferOffset += subchunkLength;
currentChunkBuffer++; currentChunkBuffer++;
break; break;
// Palette // Palette
case "CPL0": case "CPL0":
@@ -378,7 +378,7 @@ namespace OpenRA.FileFormats
palette[i] = (uint)((255 << 24) | (r << 16) | (g << 8) | b); palette[i] = (uint)((255 << 24) | (r << 16) | (g << 8) | b);
} }
break; break;
// Frame data // Frame data
case "VPTZ": case "VPTZ":
@@ -434,21 +434,21 @@ namespace OpenRA.FileFormats
{ {
case 0: case 0:
x += para_A; x += para_A;
break; break;
case 1: case 1:
WriteBlock(para_B1, para_B2, ref x, ref y); WriteBlock(para_B1, para_B2, ref x, ref y);
break; break;
case 2: case 2:
WriteBlock(para_B1, 1, ref x, ref y); WriteBlock(para_B1, 1, ref x, ref y);
for (var i = 0; i < para_B2; i++) for (var i = 0; i < para_B2; i++)
WriteBlock(origData[p++], 1, ref x, ref y); WriteBlock(origData[p++], 1, ref x, ref y);
break; break;
case 3: case 3:
WriteBlock(para_A, 1, ref x, ref y); WriteBlock(para_A, 1, ref x, ref y);
break; break;
case 5: case 5:
WriteBlock(para_A, origData[p++], ref x, ref y); WriteBlock(para_A, origData[p++], ref x, ref y);
break; break;
default: default:
throw new NotSupportedException(); throw new NotSupportedException();
} }

View File

@@ -75,8 +75,8 @@ namespace OpenRA.FileSystem
foreach (var file in contents) foreach (var file in contents)
using (var dataStream = File.Create(Path.Combine(path, file.Key))) using (var dataStream = File.Create(Path.Combine(path, file.Key)))
using (var writer = new BinaryWriter(dataStream)) using (var writer = new BinaryWriter(dataStream))
writer.Write(file.Value); writer.Write(file.Value);
} }
} }
} }

View File

@@ -59,41 +59,41 @@ namespace OpenRA.FileSystem
{ {
switch (type) switch (type)
{ {
case PackageHashType.Classic: case PackageHashType.Classic:
{
name = name.ToUpperInvariant();
if (name.Length % 4 != 0)
name = name.PadRight(name.Length + (4 - name.Length % 4), '\0');
var ms = new MemoryStream(Encoding.ASCII.GetBytes(name));
var reader = new BinaryReader(ms);
var len = name.Length >> 2;
uint result = 0;
while (len-- != 0)
result = ((result << 1) | (result >> 31)) + reader.ReadUInt32();
return result;
}
case PackageHashType.CRC32:
{
name = name.ToUpperInvariant();
var l = name.Length;
var a = l >> 2;
if ((l & 3) != 0)
{ {
name += (char)(l - (a << 2)); name = name.ToUpperInvariant();
var i = 3 - (l & 3); if (name.Length % 4 != 0)
while (i-- != 0) name = name.PadRight(name.Length + (4 - name.Length % 4), '\0');
name += name[a << 2];
var ms = new MemoryStream(Encoding.ASCII.GetBytes(name));
var reader = new BinaryReader(ms);
var len = name.Length >> 2;
uint result = 0;
while (len-- != 0)
result = ((result << 1) | (result >> 31)) + reader.ReadUInt32();
return result;
} }
return CRC32.Calculate(Encoding.ASCII.GetBytes(name)); case PackageHashType.CRC32:
} {
name = name.ToUpperInvariant();
var l = name.Length;
var a = l >> 2;
if ((l & 3) != 0)
{
name += (char)(l - (a << 2));
var i = 3 - (l & 3);
while (i-- != 0)
name += name[a << 2];
}
default: throw new NotImplementedException("Unknown hash type `{0}`".F(type)); return CRC32.Calculate(Encoding.ASCII.GetBytes(name));
}
default: throw new NotImplementedException("Unknown hash type `{0}`".F(type));
} }
} }

View File

@@ -92,7 +92,8 @@ namespace OpenRA
if (constructOrderCache != null) if (constructOrderCache != null)
return constructOrderCache; return constructOrderCache;
var source = Traits.WithInterface<ITraitInfo>().Select(i => new { var source = Traits.WithInterface<ITraitInfo>().Select(i => new
{
Trait = i, Trait = i,
Type = i.GetType(), Type = i.GetType(),
Dependencies = PrerequisitesOf(i).ToList() Dependencies = PrerequisitesOf(i).ToList()

View File

@@ -83,7 +83,7 @@ namespace OpenRA.Graphics
var isAlly = actor.Owner.IsAlliedWith(actor.World.LocalPlayer) var isAlly = actor.Owner.IsAlliedWith(actor.World.LocalPlayer)
|| (actor.EffectiveOwner != null && actor.EffectiveOwner.Disguised || (actor.EffectiveOwner != null && actor.EffectiveOwner.Disguised
&& actor.World.LocalPlayer.IsAlliedWith(actor.EffectiveOwner.Owner)); && actor.World.LocalPlayer.IsAlliedWith(actor.EffectiveOwner.Owner));
return isAlly ? Color.LimeGreen : actor.Owner.NonCombatant ? Color.Tan : Color.Red; return isAlly ? Color.LimeGreen : actor.Owner.NonCombatant ? Color.Tan : Color.Red;
} }
else else
return health.DamageState == DamageState.Critical ? Color.Red : return health.DamageState == DamageState.Critical ? Color.Red :

View File

@@ -106,12 +106,12 @@ namespace OpenRA.Graphics
{ {
var mtx = new float[16]; var mtx = new float[16];
for (var i = 0; i < 4; i++) for (var i = 0; i < 4; i++)
for (var j = 0; j < 4; j++) for (var j = 0; j < 4; j++)
{ {
mtx[4 * i + j] = 0; mtx[4 * i + j] = 0;
for (var k = 0; k < 4; k++) for (var k = 0; k < 4; k++)
mtx[4 * i + j] += lhs[4 * k + j] * rhs[4 * i + k]; mtx[4 * i + j] += lhs[4 * k + j] * rhs[4 * i + k];
} }
return mtx; return mtx;
} }
@@ -250,7 +250,7 @@ namespace OpenRA.Graphics
return null; return null;
for (var i = 0; i < 16; i++) for (var i = 0; i < 16; i++)
mtx[i] *= 1 / det; mtx[i] *= 1 / det;
return mtx; return mtx;
} }

View File

@@ -77,9 +77,10 @@ namespace OpenRA.Graphics
shader.SetMatrix("View", view); shader.SetMatrix("View", view);
} }
public VoxelRenderProxy RenderAsync(WorldRenderer wr, IEnumerable<VoxelAnimation> voxels, WRot camera, float scale, public VoxelRenderProxy RenderAsync(
float[] groundNormal, WRot lightSource, float[] lightAmbientColor, float[] lightDiffuseColor, WorldRenderer wr, IEnumerable<VoxelAnimation> voxels, WRot camera, float scale,
PaletteReference color, PaletteReference normals, PaletteReference shadowPalette) float[] groundNormal, WRot lightSource, float[] lightAmbientColor, float[] lightDiffuseColor,
PaletteReference color, PaletteReference normals, PaletteReference shadowPalette)
{ {
// Correct for inverted y-axis // Correct for inverted y-axis
var scaleTransform = Util.ScaleMatrix(scale, scale, scale); var scaleTransform = Util.ScaleMatrix(scale, scale, scale);
@@ -202,7 +203,7 @@ namespace OpenRA.Graphics
var lightDirection = ExtractRotationVector(Util.MatrixMultiply(Util.MatrixInverse(t), lightTransform)); var lightDirection = ExtractRotationVector(Util.MatrixMultiply(Util.MatrixInverse(t), lightTransform));
Render(rd, Util.MatrixMultiply(transform, t), lightDirection, Render(rd, Util.MatrixMultiply(transform, t), lightDirection,
lightAmbientColor, lightDiffuseColor, color.Index, normals.Index); lightAmbientColor, lightDiffuseColor, color.Index, normals.Index);
// Disable shadow normals by forcing zero diffuse and identity ambient light // Disable shadow normals by forcing zero diffuse and identity ambient light
Render(rd, Util.MatrixMultiply(shadow, t), lightDirection, Render(rd, Util.MatrixMultiply(shadow, t), lightDirection,
@@ -249,14 +250,16 @@ namespace OpenRA.Graphics
return tVec; return tVec;
} }
void Render(VoxelRenderData renderData, void Render(
float[] t, float[] lightDirection, VoxelRenderData renderData,
float[] ambientLight, float[] diffuseLight, float[] t, float[] lightDirection,
int colorPalette, int normalsPalette) float[] ambientLight, float[] diffuseLight,
int colorPalette, int normalsPalette)
{ {
shader.SetTexture("DiffuseTexture", renderData.Sheet.GetTexture()); shader.SetTexture("DiffuseTexture", renderData.Sheet.GetTexture());
shader.SetVec("PaletteRows", (colorPalette + 0.5f) / HardwarePalette.MaxPalettes, shader.SetVec("PaletteRows",
(normalsPalette + 0.5f) / HardwarePalette.MaxPalettes); (colorPalette + 0.5f) / HardwarePalette.MaxPalettes,
(normalsPalette + 0.5f) / HardwarePalette.MaxPalettes);
shader.SetMatrix("TransformMatrix", t); shader.SetMatrix("TransformMatrix", t);
shader.SetVec("LightDirection", lightDirection, 4); shader.SetVec("LightDirection", lightDirection, 4);
shader.SetVec("AmbientLight", ambientLight, 3); shader.SetVec("AmbientLight", ambientLight, 3);

View File

@@ -270,8 +270,7 @@ namespace OpenRA
} }
} }
if (throwErrors) if (throwErrors && noInherit.ContainsValue(false))
if (noInherit.ContainsValue(false))
throw new YamlException("Bogus yaml removals: {0}".F( throw new YamlException("Bogus yaml removals: {0}".F(
noInherit.Where(x => !x.Value).JoinWith(", "))); noInherit.Where(x => !x.Value).JoinWith(", ")));

View File

@@ -53,10 +53,10 @@ namespace OpenRA.Network
{ {
case "Handshake": case "Handshake":
FieldLoader.Load(handshake, y.Value); FieldLoader.Load(handshake, y.Value);
break; break;
case "Client": case "Client":
FieldLoader.Load(handshake.Client, y.Value); FieldLoader.Load(handshake.Client, y.Value);
break; break;
} }
} }

View File

@@ -52,7 +52,7 @@ namespace OpenRA.Network
} }
case "Message": // Server message case "Message": // Server message
Game.AddChatLine(Color.White, "Server", order.TargetString); Game.AddChatLine(Color.White, "Server", order.TargetString);
break; break;
case "Disconnected": /* reports that the target player disconnected */ case "Disconnected": /* reports that the target player disconnected */

View File

@@ -26,24 +26,24 @@ namespace OpenRA
static PlatformType GetCurrentPlatform() static PlatformType GetCurrentPlatform()
{ {
if (Environment.OSVersion.Platform == PlatformID.Win32NT) if (Environment.OSVersion.Platform == PlatformID.Win32NT)
return PlatformType.Windows; return PlatformType.Windows;
try try
{ {
var psi = new ProcessStartInfo("uname", "-s"); var psi = new ProcessStartInfo("uname", "-s");
psi.UseShellExecute = false; psi.UseShellExecute = false;
psi.RedirectStandardOutput = true; psi.RedirectStandardOutput = true;
var p = Process.Start(psi); var p = Process.Start(psi);
var kernelName = p.StandardOutput.ReadToEnd(); var kernelName = p.StandardOutput.ReadToEnd();
if (kernelName.Contains("Linux") || kernelName.Contains("BSD")) if (kernelName.Contains("Linux") || kernelName.Contains("BSD"))
return PlatformType.Linux; return PlatformType.Linux;
if (kernelName.Contains("Darwin")) if (kernelName.Contains("Darwin"))
return PlatformType.OSX; return PlatformType.OSX;
} }
catch { } catch { }
return PlatformType.Unknown; return PlatformType.Unknown;
} }
public static string RuntimeVersion public static string RuntimeVersion
@@ -75,16 +75,16 @@ namespace OpenRA
switch (CurrentPlatform) switch (CurrentPlatform)
{ {
case PlatformType.Windows: case PlatformType.Windows:
dir += Path.DirectorySeparatorChar + "OpenRA"; dir += Path.DirectorySeparatorChar + "OpenRA";
break; break;
case PlatformType.OSX: case PlatformType.OSX:
dir += "/Library/Application Support/OpenRA"; dir += "/Library/Application Support/OpenRA";
break; break;
case PlatformType.Linux: case PlatformType.Linux:
default: default:
dir += "/.openra"; dir += "/.openra";
break; break;
} }
if (!Directory.Exists(dir)) if (!Directory.Exists(dir))

View File

@@ -347,7 +347,7 @@ namespace OpenRA.Server
LobbyInfo.ClientPings.Add(clientPing); LobbyInfo.ClientPings.Add(clientPing);
Log.Write("server", "Client {0}: Accepted connection from {1}.", Log.Write("server", "Client {0}: Accepted connection from {1}.",
newConn.PlayerIndex, newConn.Socket.RemoteEndPoint); newConn.PlayerIndex, newConn.Socket.RemoteEndPoint);
foreach (var t in serverTraits.WithInterface<IClientJoined>()) foreach (var t in serverTraits.WithInterface<IClientJoined>())
t.ClientJoined(this, newConn); t.ClientJoined(this, newConn);
@@ -451,20 +451,20 @@ namespace OpenRA.Server
switch (so.Name) switch (so.Name)
{ {
case "Command": case "Command":
{
var handled = false;
foreach (var t in serverTraits.WithInterface<IInterpretCommand>())
if (handled = t.InterpretCommand(this, conn, GetClient(conn), so.Data))
break;
if (!handled)
{ {
Log.Write("server", "Unknown server command: {0}", so.Data); var handled = false;
SendOrderTo(conn, "Message", "Unknown server command: {0}".F(so.Data)); foreach (var t in serverTraits.WithInterface<IInterpretCommand>())
} if (handled = t.InterpretCommand(this, conn, GetClient(conn), so.Data))
break;
break; if (!handled)
} {
Log.Write("server", "Unknown server command: {0}", so.Data);
SendOrderTo(conn, "Message", "Unknown server command: {0}".F(so.Data));
}
break;
}
case "HandshakeResponse": case "HandshakeResponse":
ValidateClient(conn, so.Data); ValidateClient(conn, so.Data);
@@ -475,33 +475,33 @@ namespace OpenRA.Server
DispatchOrdersToClients(conn, 0, so.Serialize()); DispatchOrdersToClients(conn, 0, so.Serialize());
break; break;
case "Pong": case "Pong":
{
int pingSent;
if (!OpenRA.Exts.TryParseIntegerInvariant(so.Data, out pingSent))
{ {
Log.Write("server", "Invalid order pong payload: {0}", so.Data); int pingSent;
if (!OpenRA.Exts.TryParseIntegerInvariant(so.Data, out pingSent))
{
Log.Write("server", "Invalid order pong payload: {0}", so.Data);
break;
}
var pingFromClient = LobbyInfo.PingFromClient(GetClient(conn));
if (pingFromClient == null)
return;
var history = pingFromClient.LatencyHistory.ToList();
history.Add(Game.RunTime - pingSent);
// Cap ping history at 5 values (25 seconds)
if (history.Count > 5)
history.RemoveRange(0, history.Count - 5);
pingFromClient.Latency = history.Sum() / history.Count;
pingFromClient.LatencyJitter = (history.Max() - history.Min()) / 2;
pingFromClient.LatencyHistory = history.ToArray();
SyncClientPing();
break; break;
} }
var pingFromClient = LobbyInfo.PingFromClient(GetClient(conn));
if (pingFromClient == null)
return;
var history = pingFromClient.LatencyHistory.ToList();
history.Add(Game.RunTime - pingSent);
// Cap ping history at 5 values (25 seconds)
if (history.Count > 5)
history.RemoveRange(0, history.Count - 5);
pingFromClient.Latency = history.Sum() / history.Count;
pingFromClient.LatencyJitter = (history.Max() - history.Min()) / 2;
pingFromClient.LatencyHistory = history.ToArray();
SyncClientPing();
break;
}
} }
} }

View File

@@ -61,11 +61,11 @@ namespace OpenRA
engine = Game.Settings.Server.Dedicated ? "Null" : engine; engine = Game.Settings.Server.Dedicated ? "Null" : engine;
switch (engine) switch (engine)
{ {
case "AL": return new OpenAlSoundEngine(); case "AL": return new OpenAlSoundEngine();
case "Null": return new NullSoundEngine(); case "Null": return new NullSoundEngine();
default: default:
throw new InvalidOperationException("Unsupported sound engine: {0}".F(engine)); throw new InvalidOperationException("Unsupported sound engine: {0}".F(engine));
} }
} }

View File

@@ -30,7 +30,7 @@ namespace OpenRA
Directory.CreateDirectory(path); Directory.CreateDirectory(path);
for (var i = 0;; i++) for (var i = 0;; i++)
yield return Path.Combine(path, i > 0 ? "{0}.{1}".F(baseFilename, i) : baseFilename); yield return Path.Combine(path, i > 0 ? "{0}.{1}".F(baseFilename, i) : baseFilename);
} }
public static void AddChannel(string channelName, string baseFilename) public static void AddChannel(string channelName, string baseFilename)

View File

@@ -92,7 +92,7 @@ namespace OpenRA.Traits
}; };
foreach (var nd in self.TraitsImplementing<INotifyDamage>() foreach (var nd in self.TraitsImplementing<INotifyDamage>()
.Concat(self.Owner.PlayerActor.TraitsImplementing<INotifyDamage>())) .Concat(self.Owner.PlayerActor.TraitsImplementing<INotifyDamage>()))
nd.Damaged(self, ai); nd.Damaged(self, ai);
foreach (var nd in self.TraitsImplementing<INotifyDamageStateChanged>()) foreach (var nd in self.TraitsImplementing<INotifyDamageStateChanged>())
@@ -100,7 +100,7 @@ namespace OpenRA.Traits
if (Info.NotifyAppliedDamage && repairer != null && repairer.IsInWorld && !repairer.IsDead) if (Info.NotifyAppliedDamage && repairer != null && repairer.IsInWorld && !repairer.IsDead)
foreach (var nd in repairer.TraitsImplementing<INotifyAppliedDamage>() foreach (var nd in repairer.TraitsImplementing<INotifyAppliedDamage>()
.Concat(repairer.Owner.PlayerActor.TraitsImplementing<INotifyAppliedDamage>())) .Concat(repairer.Owner.PlayerActor.TraitsImplementing<INotifyAppliedDamage>()))
nd.AppliedDamage(repairer, self, ai); nd.AppliedDamage(repairer, self, ai);
} }
@@ -144,7 +144,7 @@ namespace OpenRA.Traits
if (Info.NotifyAppliedDamage && attacker != null && attacker.IsInWorld && !attacker.IsDead) if (Info.NotifyAppliedDamage && attacker != null && attacker.IsInWorld && !attacker.IsDead)
foreach (var nd in attacker.TraitsImplementing<INotifyAppliedDamage>() foreach (var nd in attacker.TraitsImplementing<INotifyAppliedDamage>()
.Concat(attacker.Owner.PlayerActor.TraitsImplementing<INotifyAppliedDamage>())) .Concat(attacker.Owner.PlayerActor.TraitsImplementing<INotifyAppliedDamage>()))
nd.AppliedDamage(attacker, self, ai); nd.AppliedDamage(attacker, self, ai);
if (hp == 0) if (hp == 0)
{ {

View File

@@ -101,15 +101,15 @@ namespace OpenRA.Traits
{ {
switch (Type) switch (Type)
{ {
case TargetType.Actor: case TargetType.Actor:
return actor.CenterPosition; return actor.CenterPosition;
case TargetType.FrozenActor: case TargetType.FrozenActor:
return frozen.CenterPosition; return frozen.CenterPosition;
case TargetType.Terrain: case TargetType.Terrain:
return pos; return pos;
default: default:
case TargetType.Invalid: case TargetType.Invalid:
throw new InvalidOperationException("Attempting to query the position of an invalid Target"); throw new InvalidOperationException("Attempting to query the position of an invalid Target");
} }
} }
} }
@@ -122,20 +122,20 @@ namespace OpenRA.Traits
{ {
switch (Type) switch (Type)
{ {
case TargetType.Actor: case TargetType.Actor:
var targetable = actor.TraitOrDefault<ITargetable>(); var targetable = actor.TraitOrDefault<ITargetable>();
if (targetable == null) if (targetable == null)
return new[] { actor.CenterPosition }; return new[] { actor.CenterPosition };
var positions = targetable.TargetablePositions(actor); var positions = targetable.TargetablePositions(actor);
return positions.Any() ? positions : new[] { actor.CenterPosition }; return positions.Any() ? positions : new[] { actor.CenterPosition };
case TargetType.FrozenActor: case TargetType.FrozenActor:
return new[] { frozen.CenterPosition }; return new[] { frozen.CenterPosition };
case TargetType.Terrain: case TargetType.Terrain:
return new[] { pos }; return new[] { pos };
default: default:
case TargetType.Invalid: case TargetType.Invalid:
return NoPositions; return NoPositions;
} }
} }
} }

View File

@@ -63,16 +63,16 @@ namespace OpenRA
switch (components.Length) switch (components.Length)
{ {
case 2: case 2:
if (!Exts.TryParseIntegerInvariant(components[0], out cell) || if (!Exts.TryParseIntegerInvariant(components[0], out cell) ||
!Exts.TryParseIntegerInvariant(components[1], out subcell)) !Exts.TryParseIntegerInvariant(components[1], out subcell))
return false; return false;
break; break;
case 1: case 1:
if (!Exts.TryParseIntegerInvariant(components[0], out subcell)) if (!Exts.TryParseIntegerInvariant(components[0], out subcell))
return false; return false;
break; break;
default: return false; default: return false;
} }
// Propagate sign to fractional part // Propagate sign to fractional part

View File

@@ -28,8 +28,10 @@ namespace OpenRA
public static WRot operator -(WRot a, WRot b) { return new WRot(a.Roll - b.Roll, a.Pitch - b.Pitch, a.Yaw - b.Yaw); } public static WRot operator -(WRot a, WRot b) { return new WRot(a.Roll - b.Roll, a.Pitch - b.Pitch, a.Yaw - b.Yaw); }
public static WRot operator -(WRot a) { return new WRot(-a.Roll, -a.Pitch, -a.Yaw); } public static WRot operator -(WRot a) { return new WRot(-a.Roll, -a.Pitch, -a.Yaw); }
public static bool operator ==(WRot me, WRot other) { return me.Roll == other.Roll && public static bool operator ==(WRot me, WRot other)
me.Pitch == other.Pitch && me.Yaw == other.Yaw; } {
return me.Roll == other.Roll && me.Pitch == other.Pitch && me.Yaw == other.Yaw;
}
public static bool operator !=(WRot me, WRot other) { return !(me == other); } public static bool operator !=(WRot me, WRot other) { return !(me == other); }

View File

@@ -197,8 +197,14 @@ namespace OpenRA.Widgets
tooltipContainer.Value.RemoveTooltip(); tooltipContainer.Value.RemoveTooltip();
} }
public override int2 ChildOrigin { get { return RenderOrigin + public override int2 ChildOrigin
(Depressed ? new int2(VisualHeight, VisualHeight) : new int2(0, 0)); } } {
get
{
return RenderOrigin +
(Depressed ? new int2(VisualHeight, VisualHeight) : new int2(0, 0));
}
}
public override void Draw() public override void Draw()
{ {

View File

@@ -101,8 +101,7 @@ namespace OpenRA.Widgets
public void ShowDropDown<T>(string panelTemplate, int maxHeight, IEnumerable<T> options, Func<T, ScrollItemWidget, ScrollItemWidget> setupItem) public void ShowDropDown<T>(string panelTemplate, int maxHeight, IEnumerable<T> options, Func<T, ScrollItemWidget, ScrollItemWidget> setupItem)
{ {
var substitutions = new Dictionary<string, int>() { { "DROPDOWN_WIDTH", Bounds.Width } }; var substitutions = new Dictionary<string, int>() { { "DROPDOWN_WIDTH", Bounds.Width } };
var panel = (ScrollPanelWidget)Ui.LoadWidget(panelTemplate, null, new WidgetArgs() var panel = (ScrollPanelWidget)Ui.LoadWidget(panelTemplate, null, new WidgetArgs() { { "substitutions", substitutions } });
{ { "substitutions", substitutions } });
var itemTemplate = panel.Get<ScrollItemWidget>("TEMPLATE"); var itemTemplate = panel.Get<ScrollItemWidget>("TEMPLATE");
panel.RemoveChildren(); panel.RemoveChildren();
@@ -124,8 +123,7 @@ namespace OpenRA.Widgets
public void ShowDropDown<T>(string panelTemplate, int height, Dictionary<string, IEnumerable<T>> groups, Func<T, ScrollItemWidget, ScrollItemWidget> setupItem) public void ShowDropDown<T>(string panelTemplate, int height, Dictionary<string, IEnumerable<T>> groups, Func<T, ScrollItemWidget, ScrollItemWidget> setupItem)
{ {
var substitutions = new Dictionary<string, int>() { { "DROPDOWN_WIDTH", Bounds.Width } }; var substitutions = new Dictionary<string, int>() { { "DROPDOWN_WIDTH", Bounds.Width } };
var panel = (ScrollPanelWidget)Ui.LoadWidget(panelTemplate, null, new WidgetArgs() var panel = (ScrollPanelWidget)Ui.LoadWidget(panelTemplate, null, new WidgetArgs() { { "substitutions", substitutions } });
{ { "substitutions", substitutions } });
var headerTemplate = panel.GetOrNull<ScrollItemWidget>("HEADER"); var headerTemplate = panel.GetOrNull<ScrollItemWidget>("HEADER");
var itemTemplate = panel.Get<ScrollItemWidget>("TEMPLATE"); var itemTemplate = panel.Get<ScrollItemWidget>("TEMPLATE");

View File

@@ -61,22 +61,22 @@ namespace OpenRA.Widgets
switch (mi.Event) switch (mi.Event)
{ {
case MouseInputEvent.Up: case MouseInputEvent.Up:
isMoving = false; isMoving = false;
YieldMouseFocus(mi); YieldMouseFocus(mi);
break; break;
case MouseInputEvent.Down: case MouseInputEvent.Down:
isMoving = true; isMoving = true;
/* TODO: handle snapping to ticks properly again */ /* TODO: handle snapping to ticks properly again */
/* TODO: handle nudge via clicking outside the thumb */ /* TODO: handle nudge via clicking outside the thumb */
UpdateValue(ValueFromPx(mi.Location.X - RenderBounds.Left));
break;
case MouseInputEvent.Move:
if (isMoving)
UpdateValue(ValueFromPx(mi.Location.X - RenderBounds.Left)); UpdateValue(ValueFromPx(mi.Location.X - RenderBounds.Left));
break; break;
case MouseInputEvent.Move:
if (isMoving)
UpdateValue(ValueFromPx(mi.Location.X - RenderBounds.Left));
break;
} }
return ThumbRect.Contains(mi.Location); return ThumbRect.Contains(mi.Location);

View File

@@ -268,9 +268,10 @@ namespace OpenRA.Widgets
Bounds.Width - LeftMargin - RightMargin, Bounds.Bottom)); Bounds.Width - LeftMargin - RightMargin, Bounds.Bottom));
} }
var color = disabled ? TextColorDisabled var color =
: IsValid() ? TextColor disabled ? TextColorDisabled
: TextColorInvalid; : IsValid() ? TextColor
: TextColorInvalid;
font.DrawText(apparentText, textPos, color); font.DrawText(apparentText, textPos, color);
if (showCursor && HasKeyboardFocus) if (showCursor && HasKeyboardFocus)

View File

@@ -485,7 +485,7 @@ namespace OpenRA.Widgets
public override string GetCursor(int2 pos) { return null; } public override string GetCursor(int2 pos) { return null; }
public override Widget Clone() { return new ContainerWidget(this); } public override Widget Clone() { return new ContainerWidget(this); }
public Func<KeyInput, bool> OnKeyPress = _ => false; public Func<KeyInput, bool> OnKeyPress = _ => false;
public override bool HandleKeyPress(KeyInput e) { return OnKeyPress(e); } public override bool HandleKeyPress(KeyInput e) { return OnKeyPress(e); }
} }
public class WidgetArgs : Dictionary<string, object> public class WidgetArgs : Dictionary<string, object>

View File

@@ -105,7 +105,7 @@ namespace OpenRA.Widgets
// Background // Background
if (ps.HasFlags(PanelSides.Center) && ss[8] != null) if (ps.HasFlags(PanelSides.Center) && ss[8] != null)
FillRectWithSprite(new Rectangle(bounds.Left + marginLeft, bounds.Top + marginTop, FillRectWithSprite(new Rectangle(bounds.Left + marginLeft, bounds.Top + marginTop,
bounds.Width - marginWidth, bounds.Height - marginHeight), bounds.Width - marginWidth, bounds.Height - marginHeight),
ss[8]); ss[8]);
// Left border // Left border

View File

@@ -53,7 +53,8 @@ namespace OpenRA.Mods.Cnc.Activities
state = State.Dock; state = State.Dock;
return Util.SequenceActivities(new Drag(self, startDock, endDock, 12), this); return Util.SequenceActivities(new Drag(self, startDock, endDock, 12), this);
case State.Dock: case State.Dock:
ru.PlayCustomAnimation(self, "dock", () => { ru.PlayCustomAnimation(self, "dock", () =>
{
ru.PlayCustomAnimRepeating(self, "dock-loop"); ru.PlayCustomAnimRepeating(self, "dock-loop");
if (proc.IsInWorld && !proc.IsDead) if (proc.IsInWorld && !proc.IsDead)
foreach (var nd in proc.TraitsImplementing<INotifyDocking>()) foreach (var nd in proc.TraitsImplementing<INotifyDocking>())

View File

@@ -255,7 +255,7 @@ namespace OpenRA.Mods.Common.Activities
// Check target validity if not exiting or done // Check target validity if not exiting or done
if (nextState != State.Done && (target.Type != TargetType.Actor || !target.IsValidFor(self))) if (nextState != State.Done && (target.Type != TargetType.Actor || !target.IsValidFor(self)))
AbortOrExit(self); AbortOrExit(self);
// If no current activity, tick next activity // If no current activity, tick next activity
if (inner == null && FindAndTransitionToNextState(self) == State.Done) if (inner == null && FindAndTransitionToNextState(self) == State.Done)

View File

@@ -41,7 +41,9 @@ namespace OpenRA.Mods.Common.Commands
{ {
case "pause": case "pause":
world.IssueOrder(new Order("PauseGame", null, false) world.IssueOrder(new Order("PauseGame", null, false)
{ TargetString = world.Paused ? "UnPause" : "Pause" }); {
TargetString = world.Paused ? "UnPause" : "Pause"
});
break; break;
case "surrender": case "surrender":
world.IssueOrder(new Order("Surrender", world.LocalPlayer.PlayerActor, false)); world.IssueOrder(new Order("Surrender", world.LocalPlayer.PlayerActor, false));

View File

@@ -32,9 +32,10 @@ namespace OpenRA.Mods.Common.Graphics
// Generated at render-time // Generated at render-time
VoxelRenderProxy renderProxy; VoxelRenderProxy renderProxy;
public VoxelRenderable(IEnumerable<VoxelAnimation> voxels, WPos pos, int zOffset, WRot camera, float scale, public VoxelRenderable(
WRot lightSource, float[] lightAmbientColor, float[] lightDiffuseColor, IEnumerable<VoxelAnimation> voxels, WPos pos, int zOffset, WRot camera, float scale,
PaletteReference color, PaletteReference normals, PaletteReference shadow) WRot lightSource, float[] lightAmbientColor, float[] lightDiffuseColor,
PaletteReference color, PaletteReference normals, PaletteReference shadow)
{ {
this.voxels = voxels; this.voxels = voxels;
this.pos = pos; this.pos = pos;
@@ -58,30 +59,34 @@ namespace OpenRA.Mods.Common.Graphics
public IRenderable WithScale(float newScale) public IRenderable WithScale(float newScale)
{ {
return new VoxelRenderable(voxels, pos, zOffset, camera, newScale, return new VoxelRenderable(
lightSource, lightAmbientColor, lightDiffuseColor, voxels, pos, zOffset, camera, newScale,
palette, normalsPalette, shadowPalette); lightSource, lightAmbientColor, lightDiffuseColor,
palette, normalsPalette, shadowPalette);
} }
public IRenderable WithPalette(PaletteReference newPalette) public IRenderable WithPalette(PaletteReference newPalette)
{ {
return new VoxelRenderable(voxels, pos, zOffset, camera, scale, return new VoxelRenderable(
lightSource, lightAmbientColor, lightDiffuseColor, voxels, pos, zOffset, camera, scale,
newPalette, normalsPalette, shadowPalette); lightSource, lightAmbientColor, lightDiffuseColor,
newPalette, normalsPalette, shadowPalette);
} }
public IRenderable WithZOffset(int newOffset) public IRenderable WithZOffset(int newOffset)
{ {
return new VoxelRenderable(voxels, pos, newOffset, camera, scale, return new VoxelRenderable(
lightSource, lightAmbientColor, lightDiffuseColor, voxels, pos, newOffset, camera, scale,
palette, normalsPalette, shadowPalette); lightSource, lightAmbientColor, lightDiffuseColor,
palette, normalsPalette, shadowPalette);
} }
public IRenderable OffsetBy(WVec vec) public IRenderable OffsetBy(WVec vec)
{ {
return new VoxelRenderable(voxels, pos + vec, zOffset, camera, scale, return new VoxelRenderable(
lightSource, lightAmbientColor, lightDiffuseColor, voxels, pos + vec, zOffset, camera, scale,
palette, normalsPalette, shadowPalette); lightSource, lightAmbientColor, lightDiffuseColor,
palette, normalsPalette, shadowPalette);
} }
public IRenderable AsDecoration() { return this; } public IRenderable AsDecoration() { return this; }

View File

@@ -20,7 +20,8 @@ namespace OpenRA.Mods.Common.Scripting
public class MapGlobal : ScriptGlobal public class MapGlobal : ScriptGlobal
{ {
SpawnMapActors sma; SpawnMapActors sma;
public MapGlobal(ScriptContext context) : base(context) public MapGlobal(ScriptContext context)
: base(context)
{ {
sma = context.World.WorldActor.Trait<SpawnMapActors>(); sma = context.World.WorldActor.Trait<SpawnMapActors>();

View File

@@ -19,7 +19,8 @@ namespace OpenRA.Mods.Common.Scripting
public class MediaGlobal : ScriptGlobal public class MediaGlobal : ScriptGlobal
{ {
World world; World world;
public MediaGlobal(ScriptContext context) : base(context) public MediaGlobal(ScriptContext context)
: base(context)
{ {
world = context.World; world = context.World;
} }

View File

@@ -413,7 +413,7 @@ namespace OpenRA.Mods.Common.Scripting
GetScriptTriggers(a).ClearAll(); GetScriptTriggers(a).ClearAll();
} }
[Desc("Removes the specified trigger from this actor." + [Desc("Removes the specified trigger from this actor." +
"Note that the removal will only take effect at the end of a tick, " + "Note that the removal will only take effect at the end of a tick, " +
"so you must not add new triggers at the same time that you are calling this function.")] "so you must not add new triggers at the same time that you are calling this function.")]
public void Clear(Actor a, string triggerName) public void Clear(Actor a, string triggerName)

View File

@@ -18,8 +18,11 @@ using OpenRA.Traits;
namespace OpenRA.Mods.Common.Scripting namespace OpenRA.Mods.Common.Scripting
{ {
public enum Trigger { OnIdle, OnDamaged, OnKilled, OnProduction, OnOtherProduction, OnPlayerWon, OnPlayerLost, public enum Trigger
OnObjectiveAdded, OnObjectiveCompleted, OnObjectiveFailed, OnCapture, OnInfiltrated, OnAddedToWorld, OnRemovedFromWorld } {
OnIdle, OnDamaged, OnKilled, OnProduction, OnOtherProduction, OnPlayerWon, OnPlayerLost,
OnObjectiveAdded, OnObjectiveCompleted, OnObjectiveFailed, OnCapture, OnInfiltrated, OnAddedToWorld, OnRemovedFromWorld
}
[Desc("Allows map scripts to attach triggers to this actor via the Triggers global.")] [Desc("Allows map scripts to attach triggers to this actor via the Triggers global.")]
public class ScriptTriggersInfo : ITraitInfo public class ScriptTriggersInfo : ITraitInfo

View File

@@ -20,8 +20,8 @@ namespace OpenRA.Mods.Common.Server
{ {
public class MasterServerPinger : ServerTrait, ITick, INotifySyncLobbyInfo, IStartGame, IEndGame public class MasterServerPinger : ServerTrait, ITick, INotifySyncLobbyInfo, IStartGame, IEndGame
{ {
const int MasterPingInterval = 60 * 3; // 3 minutes. server has a 5 minute TTL for games, so give ourselves a bit // 3 minutes. Server has a 5 minute TTL for games, so give ourselves a bit of leeway.
// of leeway. const int MasterPingInterval = 60 * 3;
public int TickTimeout { get { return MasterPingInterval * 10000; } } public int TickTimeout { get { return MasterPingInterval * 10000; } }
public void Tick(S server) public void Tick(S server)

View File

@@ -168,26 +168,26 @@ namespace OpenRA.Mods.Common.SpriteLoaders
{ {
case Format.Format20: case Format.Format20:
case Format.Format40: case Format.Format40:
{
if (h.RefImage.Data == null)
{ {
++recurseDepth; if (h.RefImage.Data == null)
Decompress(h.RefImage); {
--recurseDepth; ++recurseDepth;
Decompress(h.RefImage);
--recurseDepth;
}
h.Data = CopyImageData(h.RefImage.Data);
Format40.DecodeInto(shpBytes, h.Data, (int)(h.FileOffset - shpBytesFileOffset));
break;
} }
h.Data = CopyImageData(h.RefImage.Data);
Format40.DecodeInto(shpBytes, h.Data, (int)(h.FileOffset - shpBytesFileOffset));
break;
}
case Format.Format80: case Format.Format80:
{ {
var imageBytes = new byte[Size.Width * Size.Height]; var imageBytes = new byte[Size.Width * Size.Height];
Format80.DecodeInto(shpBytes, imageBytes, (int)(h.FileOffset - shpBytesFileOffset)); Format80.DecodeInto(shpBytes, imageBytes, (int)(h.FileOffset - shpBytesFileOffset));
h.Data = imageBytes; h.Data = imageBytes;
break; break;
} }
default: default:
throw new InvalidDataException(); throw new InvalidDataException();

View File

@@ -288,12 +288,12 @@ namespace OpenRA.Mods.Common.Traits
{ {
switch (order.OrderString) switch (order.OrderString)
{ {
case "Move": case "Move":
case "Enter": case "Enter":
case "ReturnToBase": case "ReturnToBase":
case "Stop": case "Stop":
return "Move"; return "Move";
default: return null; default: return null;
} }
} }
} }

View File

@@ -135,7 +135,7 @@ namespace OpenRA.Mods.Common.Traits
public Activity MoveIntoWorld(Actor self, CPos cell, SubCell subCell = SubCell.Any) { return new Fly(self, Target.FromCell(self.World, cell)); } public Activity MoveIntoWorld(Actor self, CPos cell, SubCell subCell = SubCell.Any) { return new Fly(self, Target.FromCell(self.World, cell)); }
public Activity VisualMove(Actor self, WPos fromPos, WPos toPos) { return Util.SequenceActivities(new CallFunc(() => SetVisualPosition(self, fromPos)), new Fly(self, Target.FromPos(toPos))); } public Activity VisualMove(Actor self, WPos fromPos, WPos toPos) { return Util.SequenceActivities(new CallFunc(() => SetVisualPosition(self, fromPos)), new Fly(self, Target.FromPos(toPos))); }
public Activity MoveToTarget(Actor self, Target target) { return new Fly(self, target, WRange.FromCells(3), WRange.FromCells(5)); } public Activity MoveToTarget(Actor self, Target target) { return new Fly(self, target, WRange.FromCells(3), WRange.FromCells(5)); }
public Activity MoveIntoTarget(Actor self, Target target) { return new Land(target); } public Activity MoveIntoTarget(Actor self, Target target) { return new Land(target); }
} }
} }

View File

@@ -33,8 +33,11 @@ namespace OpenRA.Mods.Common.Traits
public override string[] TargetTypes public override string[] TargetTypes
{ {
get { return (self.CenterPosition.Z > 0) ? info.TargetTypes get
: info.GroundedTargetTypes; } {
return (self.CenterPosition.Z > 0) ? info.TargetTypes
: info.GroundedTargetTypes;
}
} }
} }
} }

View File

@@ -113,12 +113,12 @@ namespace OpenRA.Mods.Common.Traits
{ {
switch (target.Type) switch (target.Type)
{ {
case TargetType.Actor: case TargetType.Actor:
return new Order("Attack", self, queued) { TargetActor = target.Actor }; return new Order("Attack", self, queued) { TargetActor = target.Actor };
case TargetType.FrozenActor: case TargetType.FrozenActor:
return new Order("Attack", self, queued) { ExtraData = target.FrozenActor.ID }; return new Order("Attack", self, queued) { ExtraData = target.FrozenActor.ID };
case TargetType.Terrain: case TargetType.Terrain:
return new Order("Attack", self, queued) { TargetLocation = self.World.Map.CellContaining(target.CenterPosition) }; return new Order("Attack", self, queued) { TargetLocation = self.World.Map.CellContaining(target.CenterPosition) };
} }
} }
@@ -255,13 +255,13 @@ namespace OpenRA.Mods.Common.Traits
{ {
switch (target.Type) switch (target.Type)
{ {
case TargetType.Actor: case TargetType.Actor:
case TargetType.FrozenActor: case TargetType.FrozenActor:
return CanTargetActor(self, target, modifiers, ref cursor); return CanTargetActor(self, target, modifiers, ref cursor);
case TargetType.Terrain: case TargetType.Terrain:
return CanTargetLocation(self, self.World.Map.CellContaining(target.CenterPosition), othersAtTarget, modifiers, ref cursor); return CanTargetLocation(self, self.World.Map.CellContaining(target.CenterPosition), othersAtTarget, modifiers, ref cursor);
default: default:
return false; return false;
} }
} }

View File

@@ -40,10 +40,13 @@ namespace OpenRA.Mods.Common.Traits
// the one we're playing in. // the one we're playing in.
return new DisposableAction( return new DisposableAction(
() => { reservedFor = null; reservedForAircraft = null; }, () => { reservedFor = null; reservedForAircraft = null; },
() => Game.RunAfterTick( () => Game.RunAfterTick(() =>
() => { if (Game.IsCurrentWorld(self.World)) throw new InvalidOperationException( {
"Attempted to finalize an undisposed DisposableAction. {0} ({1}) reserved {2} ({3})" if (Game.IsCurrentWorld(self.World))
.F(forActor.Info.Name, forActor.ActorID, self.Info.Name, self.ActorID)); })); throw new InvalidOperationException(
"Attempted to finalize an undisposed DisposableAction. {0} ({1}) reserved {2} ({3})".F(
forActor.Info.Name, forActor.ActorID, self.Info.Name, self.ActorID));
}));
} }
public static bool IsReserved(Actor a) public static bool IsReserved(Actor a)

View File

@@ -44,7 +44,7 @@ namespace OpenRA.Mods.Common.Traits
{ {
var info = self.Info.Traits.Get<GivesBountyInfo>(); var info = self.Info.Traits.Get<GivesBountyInfo>();
if (e.Attacker == null || e.Attacker.Destroyed) return; if (e.Attacker == null || e.Attacker.Destroyed) return;
if (!info.Stances.Contains(e.Attacker.Owner.Stances[self.Owner])) return; if (!info.Stances.Contains(e.Attacker.Owner.Stances[self.Owner])) return;

View File

@@ -12,7 +12,7 @@ using OpenRA.Traits;
namespace OpenRA.Mods.Common.Traits namespace OpenRA.Mods.Common.Traits
{ {
[Desc("This actor can be targeted by the Hunt activity.")] [Desc("This actor can be targeted by the Hunt activity.")]
public class HuntableInfo : TraitInfo<Huntable> { } public class HuntableInfo : TraitInfo<Huntable> { }
public class Huntable { } public class Huntable { }
} }

View File

@@ -12,8 +12,8 @@ using OpenRA.Traits;
namespace OpenRA.Mods.Common.Traits namespace OpenRA.Mods.Common.Traits
{ {
[Desc("Allows automatic targeting of disguised actors.")] [Desc("Allows automatic targeting of disguised actors.")]
class IgnoresDisguiseInfo : TraitInfo<IgnoresDisguise> { } class IgnoresDisguiseInfo : TraitInfo<IgnoresDisguise> { }
class IgnoresDisguise { } class IgnoresDisguise { }
} }

View File

@@ -36,13 +36,13 @@ namespace OpenRA.Mods.Common.Traits
public class MissionObjectivesInfo : ITraitInfo public class MissionObjectivesInfo : ITraitInfo
{ {
[Desc("Set this to true if multiple cooperative players have a distinct set of " + [Desc("Set this to true if multiple cooperative players have a distinct set of " +
"objectives that each of them has to complete to win the game. This is mainly " + "objectives that each of them has to complete to win the game. This is mainly " +
"useful for multiplayer coop missions. Do not use this for skirmish team games.")] "useful for multiplayer coop missions. Do not use this for skirmish team games.")]
public readonly bool Cooperative = false; public readonly bool Cooperative = false;
[Desc("If set to true, this setting causes the game to end immediately once the first " + [Desc("If set to true, this setting causes the game to end immediately once the first " +
"player (or team of cooperative players) fails or completes his objectives. If " + "player (or team of cooperative players) fails or completes his objectives. If " +
"set to false, players that fail their objectives will stick around and become observers.")] "set to false, players that fail their objectives will stick around and become observers.")]
public readonly bool EarlyGameOver = false; public readonly bool EarlyGameOver = false;
[Desc("Delay between the game over condition being met, and the game actually ending, in milliseconds.")] [Desc("Delay between the game over condition being met, and the game actually ending, in milliseconds.")]
@@ -245,8 +245,8 @@ namespace OpenRA.Mods.Common.Traits
} }
[Desc("Provides game mode progress information for players.", [Desc("Provides game mode progress information for players.",
"Goes on WorldActor - observers don't have a player it can live on.", "Goes on WorldActor - observers don't have a player it can live on.",
"Current options for PanelName are 'SKIRMISH_STATS' and 'MISSION_OBJECTIVES'.")] "Current options for PanelName are 'SKIRMISH_STATS' and 'MISSION_OBJECTIVES'.")]
public class ObjectivesPanelInfo : ITraitInfo public class ObjectivesPanelInfo : ITraitInfo
{ {
public string PanelName = null; public string PanelName = null;

View File

@@ -38,9 +38,10 @@ namespace OpenRA.Mods.Common.Traits
anim = new Animation(self.World, rs.GetImage(self)); anim = new Animation(self.World, rs.GetImage(self));
anim.PlayFetchIndex(info.Sequence, anim.PlayFetchIndex(info.Sequence,
() => playerResources.ResourceCapacity != 0 () =>
? ((10 * anim.CurrentSequence.Length - 1) * playerResources.Resources) / (10 * playerResources.ResourceCapacity) playerResources.ResourceCapacity != 0 ?
: 0); ((10 * anim.CurrentSequence.Length - 1) * playerResources.Resources) / (10 * playerResources.ResourceCapacity) :
0);
rs.Add("resources_{0}".F(info.Sequence), new AnimationWithOffset( rs.Add("resources_{0}".F(info.Sequence), new AnimationWithOffset(
anim, null, () => !buildComplete, 1024)); anim, null, () => !buildComplete, 1024));

View File

@@ -99,8 +99,8 @@ namespace OpenRA.Mods.Common.Traits
// Select only the tiles that are within range from the requested SubCell // Select only the tiles that are within range from the requested SubCell
// This assumes that the SubCell does not change during the path traversal // This assumes that the SubCell does not change during the path traversal
var tilesInRange = world.Map.FindTilesInCircle(targetCell, range.Range / 1024 + 1) var tilesInRange = world.Map.FindTilesInCircle(targetCell, range.Range / 1024 + 1)
.Where(t => (world.Map.CenterOfCell(t) - target).LengthSquared <= rangeSquared .Where(t => (world.Map.CenterOfCell(t) - target).LengthSquared <= rangeSquared &&
&& mi.CanEnterCell(self.World, self, t)); mi.CanEnterCell(self.World, self, t));
// See if there is any cell within range that does not involve a cross-domain request // See if there is any cell within range that does not involve a cross-domain request
// Really, we only need to check the circle perimeter, but it's not clear that would be a performance win // Really, we only need to check the circle perimeter, but it's not clear that would be a performance win

View File

@@ -24,7 +24,7 @@ namespace OpenRA.Mods.Common.Traits
public readonly string FogPalette = "fog"; public readonly string FogPalette = "fog";
[Desc("Bitfield of shroud directions for each frame. Lower four bits are", [Desc("Bitfield of shroud directions for each frame. Lower four bits are",
"corners clockwise from TL; upper four are edges clockwise from top")] "corners clockwise from TL; upper four are edges clockwise from top")]
public readonly int[] Index = new[] { 12, 9, 8, 3, 1, 6, 4, 2, 13, 11, 7, 14 }; public readonly int[] Index = new[] { 12, 9, 8, 3, 1, 6, 4, 2, 13, 11, 7, 14 };
[Desc("Use the upper four bits when calculating frame")] [Desc("Use the upper four bits when calculating frame")]

View File

@@ -1,12 +1,12 @@
#region Copyright & License Information #region Copyright & License Information
/* /*
* Copyright 2007-2014 The OpenRA Developers (see AUTHORS) * Copyright 2007-2014 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made * This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License * available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information, * as published by the Free Software Foundation. For more information,
* see COPYING. * see COPYING.
*/ */
#endregion #endregion
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;

View File

@@ -732,13 +732,13 @@ namespace OpenRA.Mods.Common.UtilityCommands
ConvertAngle(ref node.Value.Value); ConvertAngle(ref node.Value.Value);
break; break;
case "Speed": case "Speed":
{ {
if (parent.Value.Value == "Missile") if (parent.Value.Value == "Missile")
ConvertPxToRange(ref node.Value.Value, 1, 5); ConvertPxToRange(ref node.Value.Value, 1, 5);
if (parent.Value.Value == "Bullet") if (parent.Value.Value == "Bullet")
ConvertPxToRange(ref node.Value.Value, 2, 5); ConvertPxToRange(ref node.Value.Value, 2, 5);
break; break;
} }
default: default:
break; break;

View File

@@ -171,25 +171,25 @@ namespace OpenRA.Mods.Common.Widgets
switch (mi.Event) switch (mi.Event)
{ {
case MouseInputEvent.Up: case MouseInputEvent.Up:
isMoving = false; isMoving = false;
YieldMouseFocus(mi); YieldMouseFocus(mi);
break; break;
case MouseInputEvent.Down: case MouseInputEvent.Down:
isMoving = true; isMoving = true;
SetValueFromPx(mi.Location - RenderOrigin);
OnChange();
break;
case MouseInputEvent.Move:
if (isMoving)
{
SetValueFromPx(mi.Location - RenderOrigin); SetValueFromPx(mi.Location - RenderOrigin);
OnChange(); OnChange();
} break;
break; case MouseInputEvent.Move:
if (isMoving)
{
SetValueFromPx(mi.Location - RenderOrigin);
OnChange();
}
break;
} }
return true; return true;

View File

@@ -325,8 +325,8 @@ namespace OpenRA.Mods.Common.Widgets.Logic
Func<IFolder, ScrollItemWidget, ScrollItemWidget> setupItem = (source, itemTemplate) => Func<IFolder, ScrollItemWidget, ScrollItemWidget> setupItem = (source, itemTemplate) =>
{ {
var item = ScrollItemWidget.Setup(itemTemplate, var item = ScrollItemWidget.Setup(itemTemplate,
() => assetSource == source, () => assetSource == source,
() => { assetSource = source; PopulateAssetList(); }); () => { assetSource = source; PopulateAssetList(); });
item.Get<LabelWidget>("LABEL").GetText = () => source != null ? Platform.UnresolvePath(source.Name) : "All Packages"; item.Get<LabelWidget>("LABEL").GetText = () => source != null ? Platform.UnresolvePath(source.Name) : "All Packages";
return item; return item;
}; };

View File

@@ -126,7 +126,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
var textBox = key.Get<HotkeyEntryWidget>("HOTKEY"); var textBox = key.Get<HotkeyEntryWidget>("HOTKEY");
textBox.Key = (Hotkey)field.GetValue(ks); textBox.Key = (Hotkey)field.GetValue(ks);
textBox.OnLoseFocus = () => field.SetValue(ks, textBox.Key); textBox.OnLoseFocus = () => field.SetValue(ks, textBox.Key);
parent.AddChild(key); parent.AddChild(key);
} }
@@ -536,8 +536,8 @@ namespace OpenRA.Mods.Common.Widgets.Logic
Func<string, ScrollItemWidget, ScrollItemWidget> setupItem = (o, itemTemplate) => Func<string, ScrollItemWidget, ScrollItemWidget> setupItem = (o, itemTemplate) =>
{ {
var item = ScrollItemWidget.Setup(itemTemplate, var item = ScrollItemWidget.Setup(itemTemplate,
() => s.MouseScroll == options[o], () => s.MouseScroll == options[o],
() => s.MouseScroll = options[o]); () => s.MouseScroll = options[o]);
item.Get<LabelWidget>("LABEL").GetText = () => o; item.Get<LabelWidget>("LABEL").GetText = () => o;
return item; return item;
}; };

View File

@@ -96,8 +96,9 @@ namespace OpenRA.Mods.Common.Widgets
} }
} }
else else
Game.Renderer.LineRenderer.FillRect(new Rectangle(b.X, (int)float2.Lerp(b.Bottom, b.Top, providedFrac), Game.Renderer.LineRenderer.FillRect(new Rectangle(
b.Width, (int)(providedFrac * b.Height)), color); b.X, (int)float2.Lerp(b.Bottom, b.Top, providedFrac),
b.Width, (int)(providedFrac * b.Height)), color);
var x = (b.Left + b.Right - indicator.Size.X) / 2; var x = (b.Left + b.Right - indicator.Size.X) / 2;
var y = float2.Lerp(b.Bottom, b.Top, usedFrac) - indicator.Size.Y / 2; var y = float2.Lerp(b.Bottom, b.Top, usedFrac) - indicator.Size.Y / 2;

View File

@@ -177,7 +177,7 @@ namespace OpenRA.Mods.D2k.Activities
c.Dropped(); c.Dropped();
state = State.Done; state = State.Done;
return Util.SequenceActivities(new Wait(10), this); return Util.SequenceActivities(new Wait(10), this);
case State.Done: case State.Done:

View File

@@ -293,10 +293,10 @@ namespace OpenRA.Mods.D2k.Widgets
var size = font.Measure(tb.Second); var size = font.Measure(tb.Second);
if (ReadyTextStyle == ReadyTextStyleOptions.Solid || orderManager.LocalFrameNumber / 9 % 2 == 0 || tb.Second != ReadyText) if (ReadyTextStyle == ReadyTextStyleOptions.Solid || orderManager.LocalFrameNumber / 9 % 2 == 0 || tb.Second != ReadyText)
font.DrawTextWithContrast(tb.Second, tb.First - new float2(size.X / 2, 0), font.DrawTextWithContrast(tb.Second, tb.First - new float2(size.X / 2, 0),
Color.White, Color.Black, 1); Color.White, Color.Black, 1);
else if (ReadyTextStyle == ReadyTextStyleOptions.AlternatingColor) else if (ReadyTextStyle == ReadyTextStyleOptions.AlternatingColor)
font.DrawTextWithContrast(tb.Second, tb.First - new float2(size.X / 2, 0), font.DrawTextWithContrast(tb.Second, tb.First - new float2(size.X / 2, 0),
ReadyTextAltColor, Color.Black, 1); ReadyTextAltColor, Color.Black, 1);
} }
// Tooltip // Tooltip

View File

@@ -914,8 +914,7 @@ namespace OpenRA.Mods.RA.AI
{ {
BotDebug("Bot noticed damage {0} {1}->{2}, repairing.", BotDebug("Bot noticed damage {0} {1}->{2}, repairing.",
self, e.PreviousDamageState, e.DamageState); self, e.PreviousDamageState, e.DamageState);
World.IssueOrder(new Order("RepairBuilding", self.Owner.PlayerActor, false) World.IssueOrder(new Order("RepairBuilding", self.Owner.PlayerActor, false) { TargetActor = self });
{ TargetActor = self });
} }
} }

View File

@@ -47,7 +47,8 @@ namespace OpenRA.Mods.RA
state = State.Dock; state = State.Dock;
return Util.SequenceActivities(new Turn(self, angle), this); return Util.SequenceActivities(new Turn(self, angle), this);
case State.Dock: case State.Dock:
ru.PlayCustomAnimation(self, "dock", () => { ru.PlayCustomAnimation(self, "dock", () =>
{
ru.PlayCustomAnimRepeating(self, "dock-loop"); ru.PlayCustomAnimRepeating(self, "dock-loop");
if (proc.IsInWorld && !proc.IsDead) if (proc.IsInWorld && !proc.IsDead)
foreach (var nd in proc.TraitsImplementing<INotifyDocking>()) foreach (var nd in proc.TraitsImplementing<INotifyDocking>())

View File

@@ -1,12 +1,12 @@
#region Copyright & License Information #region Copyright & License Information
/* /*
* Copyright 2007-2014 The OpenRA Developers (see AUTHORS) * Copyright 2007-2014 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made * This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License * available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information, * as published by the Free Software Foundation. For more information,
* see COPYING. * see COPYING.
*/ */
#endregion #endregion
using System; using System;
using OpenRA.Traits; using OpenRA.Traits;

View File

@@ -20,9 +20,9 @@ namespace OpenRA.Mods.RA
{ {
if (map.Bounds.Left == 0 || map.Bounds.Top == 0 if (map.Bounds.Left == 0 || map.Bounds.Top == 0
|| map.Bounds.Right == map.MapSize.X || map.Bounds.Bottom == map.MapSize.Y) || map.Bounds.Right == map.MapSize.X || map.Bounds.Bottom == map.MapSize.Y)
emitError("This map does not define a valid cordon.\n" emitError("This map does not define a valid cordon.\n"
+ "A one cell (or greater) border is required on all four sides " + "A one cell (or greater) border is required on all four sides "
+ "between the playable bounds and the map edges"); + "between the playable bounds and the map edges");
} }
} }
} }

View File

@@ -12,7 +12,6 @@ using OpenRA.Mods.Common;
using OpenRA.Traits; using OpenRA.Traits;
namespace OpenRA.Mods.RA.Traits namespace OpenRA.Mods.RA.Traits
{ {
[Desc("Attach this to the player actor to allow building repair by team mates.")] [Desc("Attach this to the player actor to allow building repair by team mates.")]
class AllyRepairInfo : TraitInfo<AllyRepair> { } class AllyRepairInfo : TraitInfo<AllyRepair> { }

View File

@@ -254,70 +254,70 @@ namespace OpenRA.Mods.RA
switch (order.OrderString) switch (order.OrderString)
{ {
case "StartProduction": case "StartProduction":
{
var unit = self.World.Map.Rules.Actors[order.TargetString];
var bi = unit.Traits.Get<BuildableInfo>();
if (!bi.Queue.Contains(Info.Type))
return; /* Not built by this queue */
var cost = unit.Traits.Contains<ValuedInfo>() ? unit.Traits.Get<ValuedInfo>().Cost : 0;
var time = GetBuildTime(order.TargetString);
if (BuildableItems().All(b => b.Name != order.TargetString))
return; /* you can't build that!! */
// Check if the player is trying to build more units that they are allowed
var fromLimit = int.MaxValue;
if (bi.BuildLimit > 0)
{ {
var inQueue = queue.Count(pi => pi.Item == order.TargetString); var unit = self.World.Map.Rules.Actors[order.TargetString];
var owned = self.Owner.World.ActorsWithTrait<Buildable>().Count(a => a.Actor.Info.Name == order.TargetString && a.Actor.Owner == self.Owner); var bi = unit.Traits.Get<BuildableInfo>();
fromLimit = bi.BuildLimit - (inQueue + owned); if (!bi.Queue.Contains(Info.Type))
return; /* Not built by this queue */
if (fromLimit <= 0) var cost = unit.Traits.Contains<ValuedInfo>() ? unit.Traits.Get<ValuedInfo>().Cost : 0;
return; var time = GetBuildTime(order.TargetString);
}
var amountToBuild = Math.Min(fromLimit, order.ExtraData); if (BuildableItems().All(b => b.Name != order.TargetString))
for (var n = 0; n < amountToBuild; n++) return; /* you can't build that!! */
{
var hasPlayedSound = false; // Check if the player is trying to build more units that they are allowed
BeginProduction(new ProductionItem(this, order.TargetString, cost, playerPower, () => self.World.AddFrameEndTask(_ => var fromLimit = int.MaxValue;
if (bi.BuildLimit > 0)
{ {
var isBuilding = unit.Traits.Contains<BuildingInfo>(); var inQueue = queue.Count(pi => pi.Item == order.TargetString);
if (isBuilding && !hasPlayedSound) var owned = self.Owner.World.ActorsWithTrait<Buildable>().Count(a => a.Actor.Info.Name == order.TargetString && a.Actor.Owner == self.Owner);
fromLimit = bi.BuildLimit - (inQueue + owned);
if (fromLimit <= 0)
return;
}
var amountToBuild = Math.Min(fromLimit, order.ExtraData);
for (var n = 0; n < amountToBuild; n++)
{
var hasPlayedSound = false;
BeginProduction(new ProductionItem(this, order.TargetString, cost, playerPower, () => self.World.AddFrameEndTask(_ =>
{ {
hasPlayedSound = Sound.PlayNotification(self.World.Map.Rules, self.Owner, "Speech", Info.ReadyAudio, self.Owner.Country.Race); var isBuilding = unit.Traits.Contains<BuildingInfo>();
} if (isBuilding && !hasPlayedSound)
else if (!isBuilding)
{
if (BuildUnit(order.TargetString))
Sound.PlayNotification(self.World.Map.Rules, self.Owner, "Speech", Info.ReadyAudio, self.Owner.Country.Race);
else if (!hasPlayedSound && time > 0)
{ {
hasPlayedSound = Sound.PlayNotification(self.World.Map.Rules, self.Owner, "Speech", Info.BlockedAudio, self.Owner.Country.Race); hasPlayedSound = Sound.PlayNotification(self.World.Map.Rules, self.Owner, "Speech", Info.ReadyAudio, self.Owner.Country.Race);
} }
} else if (!isBuilding)
}))); {
if (BuildUnit(order.TargetString))
Sound.PlayNotification(self.World.Map.Rules, self.Owner, "Speech", Info.ReadyAudio, self.Owner.Country.Race);
else if (!hasPlayedSound && time > 0)
{
hasPlayedSound = Sound.PlayNotification(self.World.Map.Rules, self.Owner, "Speech", Info.BlockedAudio, self.Owner.Country.Race);
}
}
})));
}
break;
} }
break; case "PauseProduction":
} {
if (queue.Count > 0 && queue[0].Item == order.TargetString)
queue[0].Pause(order.ExtraData != 0);
case "PauseProduction": break;
{ }
if (queue.Count > 0 && queue[0].Item == order.TargetString)
queue[0].Pause(order.ExtraData != 0);
break; case "CancelProduction":
} {
CancelProduction(order.TargetString, order.ExtraData);
case "CancelProduction": break;
{ }
CancelProduction(order.TargetString, order.ExtraData);
break;
}
} }
} }

View File

@@ -47,7 +47,7 @@ namespace OpenRA.Mods.RA
// Queue-per-actor // Queue-per-actor
var queue = world.Selection.Actors var queue = world.Selection.Actors
.Where(a => a.IsInWorld && a.World.LocalPlayer == a.Owner) .Where(a => a.IsInWorld && a.World.LocalPlayer == a.Owner)
.SelectMany(a => a.TraitsImplementing<ProductionQueue>()) .SelectMany(a => a.TraitsImplementing<ProductionQueue>())
.FirstOrDefault(q => q.Enabled); .FirstOrDefault(q => q.Enabled);

View File

@@ -40,8 +40,11 @@ namespace OpenRA.Mods.RA.Traits
public IEnumerable<IOrderTargeter> Orders public IEnumerable<IOrderTargeter> Orders
{ {
get { yield return new EnterAlliedActorTargeter<Building>("Repair", 5, get
target => CanRepairAt(target), _ => CanRepair()); } {
yield return new EnterAlliedActorTargeter<Building>("Repair", 5,
target => CanRepairAt(target), _ => CanRepair());
}
} }
public Order IssueOrder(Actor self, IOrderTargeter order, Target target, bool queued) public Order IssueOrder(Actor self, IOrderTargeter order, Target target, bool queued)

View File

@@ -87,7 +87,7 @@ namespace OpenRA.Mods.RA.Scripting
if (af != null) if (af != null)
{ {
actor.QueueActivity(new CallFunc(() => actor.QueueActivity(new CallFunc(() =>
{ {
af.Call(actor.ToLuaValue(Context)); af.Call(actor.ToLuaValue(Context));
af.Dispose(); af.Dispose();

View File

@@ -21,7 +21,7 @@ namespace OpenRA.Mods.RA.Scripting
public class PlayerProperties : ScriptPlayerProperties public class PlayerProperties : ScriptPlayerProperties
{ {
public PlayerProperties(ScriptContext context, Player player) public PlayerProperties(ScriptContext context, Player player)
: base(context, player) { } : base(context, player) { }
[Desc("The player's name.")] [Desc("The player's name.")]
public string Name { get { return Player.PlayerName; } } public string Name { get { return Player.PlayerName; } }

View File

@@ -1,12 +1,12 @@
#region Copyright & License Information #region Copyright & License Information
/* /*
* Copyright 2007-2014 The OpenRA Developers (see AUTHORS) * Copyright 2007-2014 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made * This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License * available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information, * as published by the Free Software Foundation. For more information,
* see COPYING. * see COPYING.
*/ */
#endregion #endregion
using System; using System;
using System.Linq; using System.Linq;

View File

@@ -18,6 +18,6 @@ namespace OpenRA.Mods.RA.Traits
class Fake : ITags class Fake : ITags
{ {
public IEnumerable<TagType> GetTags() { yield return TagType.Fake; } public IEnumerable<TagType> GetTags() { yield return TagType.Fake; }
} }
} }

View File

@@ -74,7 +74,8 @@ namespace OpenRA.Mods.RA.Traits
{ {
s.First.Activate(crusher); s.First.Activate(crusher);
return; return;
} else }
else
n -= s.Second; n -= s.Second;
} }
} }

View File

@@ -75,17 +75,17 @@ namespace OpenRA.Mods.RA.Traits
using (var se = sourceTiles.GetEnumerator()) using (var se = sourceTiles.GetEnumerator())
using (var de = destTiles.GetEnumerator()) using (var de = destTiles.GetEnumerator())
while (se.MoveNext() && de.MoveNext()) while (se.MoveNext() && de.MoveNext())
{ {
var a = se.Current; var a = se.Current;
var b = de.Current; var b = de.Current;
if (!Self.Owner.Shroud.IsExplored(a) || !Self.Owner.Shroud.IsExplored(b)) if (!Self.Owner.Shroud.IsExplored(a) || !Self.Owner.Shroud.IsExplored(b))
return false; return false;
if (Self.World.Map.GetTerrainIndex(a) != Self.World.Map.GetTerrainIndex(b)) if (Self.World.Map.GetTerrainIndex(a) != Self.World.Map.GetTerrainIndex(b))
return false; return false;
} }
return true; return true;
} }
@@ -242,7 +242,7 @@ namespace OpenRA.Mods.RA.Traits
{ {
var targetCell = unit.Location + (xy - sourceLocation); var targetCell = unit.Location + (xy - sourceLocation);
var canEnter = manager.Self.Owner.Shroud.IsExplored(targetCell) && var canEnter = manager.Self.Owner.Shroud.IsExplored(targetCell) &&
unit.Trait<Chronoshiftable>().CanChronoshiftTo(unit, targetCell); unit.Trait<Chronoshiftable>().CanChronoshiftTo(unit, targetCell);
var tile = canEnter ? validTile : invalidTile; var tile = canEnter ? validTile : invalidTile;
yield return new SpriteRenderable(tile, wr.World.Map.CenterOfCell(targetCell), WVec.Zero, -511, pal, 1f, true); yield return new SpriteRenderable(tile, wr.World.Map.CenterOfCell(targetCell), WVec.Zero, -511, pal, 1f, true);
} }

View File

@@ -92,7 +92,8 @@ namespace OpenRA.Mods.RA.Traits
{ {
GpsWatcher owner; GpsWatcher owner;
public GpsPower(Actor self, GpsPowerInfo info) : base(self, info) public GpsPower(Actor self, GpsPowerInfo info)
: base(self, info)
{ {
owner = self.Owner.PlayerActor.Trait<GpsWatcher>(); owner = self.Owner.PlayerActor.Trait<GpsWatcher>();
owner.GpsAdd(self); owner.GpsAdd(self);

View File

@@ -32,8 +32,10 @@ namespace OpenRA.Mods.RA.Traits
public override string[] TargetTypes public override string[] TargetTypes
{ {
get { return cloak.Cloaked ? info.CloakedTargetTypes get
: info.TargetTypes; } {
return cloak.Cloaked ? info.CloakedTargetTypes : info.TargetTypes;
}
} }
} }
} }

View File

@@ -18,7 +18,7 @@ namespace OpenRA.Mods.RA.Widgets.Logic
public class CreditsLogic public class CreditsLogic
{ {
[ObjectCreator.UseCtor] [ObjectCreator.UseCtor]
public CreditsLogic(Widget widget, Action onExit) public CreditsLogic(Widget widget, Action onExit)
{ {
var panel = widget.Get("CREDITS_PANEL"); var panel = widget.Get("CREDITS_PANEL");

View File

@@ -322,7 +322,7 @@ namespace OpenRA.Mods.RA.Widgets.Logic
{ {
allowCheats.IsChecked = () => orderManager.LobbyInfo.GlobalSettings.AllowCheats; allowCheats.IsChecked = () => orderManager.LobbyInfo.GlobalSettings.AllowCheats;
allowCheats.IsDisabled = () => Map.Status != MapStatus.Available || Map.Map.Options.Cheats.HasValue || configurationDisabled(); allowCheats.IsDisabled = () => Map.Status != MapStatus.Available || Map.Map.Options.Cheats.HasValue || configurationDisabled();
allowCheats.OnClick = () => orderManager.IssueOrder(Order.Command( allowCheats.OnClick = () => orderManager.IssueOrder(Order.Command(
"allowcheats {0}".F(!orderManager.LobbyInfo.GlobalSettings.AllowCheats))); "allowcheats {0}".F(!orderManager.LobbyInfo.GlobalSettings.AllowCheats)));
} }

View File

@@ -217,14 +217,14 @@ namespace OpenRA.Mods.RA.Widgets.Logic
if (title != null) if (title != null)
{ {
title.GetText = () => game.Name; title.GetText = () => game.Name;
title.GetColor = () => !compatible ? Color.DarkGray : !canJoin ? Color.LightGray : title.TextColor; title.GetColor = () => !compatible ? Color.DarkGray : !canJoin ? Color.LightGray : title.TextColor;
} }
var maptitle = item.GetOrNull<LabelWidget>("MAP"); var maptitle = item.GetOrNull<LabelWidget>("MAP");
if (title != null) if (title != null)
{ {
maptitle.GetText = () => map.Title; maptitle.GetText = () => map.Title;
maptitle.GetColor = () => !compatible ? Color.DarkGray : !canJoin ? Color.LightGray : maptitle.TextColor; maptitle.GetColor = () => !compatible ? Color.DarkGray : !canJoin ? Color.LightGray : maptitle.TextColor;
} }
var players = item.GetOrNull<LabelWidget>("PLAYERS"); var players = item.GetOrNull<LabelWidget>("PLAYERS");
@@ -232,7 +232,7 @@ namespace OpenRA.Mods.RA.Widgets.Logic
{ {
players.GetText = () => "{0} / {1}".F(game.Players, game.MaxPlayers) players.GetText = () => "{0} / {1}".F(game.Players, game.MaxPlayers)
+ (game.Spectators > 0 ? " ({0} Spectator{1})".F(game.Spectators, game.Spectators > 1 ? "s" : "") : ""); + (game.Spectators > 0 ? " ({0} Spectator{1})".F(game.Spectators, game.Spectators > 1 ? "s" : "") : "");
players.GetColor = () => !compatible ? Color.DarkGray : !canJoin ? Color.LightGray : players.TextColor; players.GetColor = () => !compatible ? Color.DarkGray : !canJoin ? Color.LightGray : players.TextColor;
} }
var state = item.GetOrNull<LabelWidget>("STATE"); var state = item.GetOrNull<LabelWidget>("STATE");
@@ -254,7 +254,7 @@ namespace OpenRA.Mods.RA.Widgets.Logic
{ {
var cachedServerLocation = LobbyUtils.LookupCountry(game.Address.Split(':')[0]); var cachedServerLocation = LobbyUtils.LookupCountry(game.Address.Split(':')[0]);
location.GetText = () => cachedServerLocation; location.GetText = () => cachedServerLocation;
location.GetColor = () => !compatible ? Color.DarkGray : !canJoin ? Color.LightGray : location.TextColor; location.GetColor = () => !compatible ? Color.DarkGray : !canJoin ? Color.LightGray : location.TextColor;
} }
rows.Add(item); rows.Add(item);

View File

@@ -51,24 +51,24 @@ namespace OpenRA.Mods.RA.Widgets.Logic
labelText = "Unexplored Terrain"; labelText = "Unexplored Terrain";
break; break;
case WorldTooltipType.Actor: case WorldTooltipType.Actor:
{ {
o = viewport.ActorTooltip.Owner; o = viewport.ActorTooltip.Owner;
showOwner = !o.NonCombatant && viewport.ActorTooltip.TooltipInfo.IsOwnerRowVisible; showOwner = !o.NonCombatant && viewport.ActorTooltip.TooltipInfo.IsOwnerRowVisible;
var stance = o == null || world.RenderPlayer == null ? Stance.None : o.Stances[world.RenderPlayer]; var stance = o == null || world.RenderPlayer == null ? Stance.None : o.Stances[world.RenderPlayer];
labelText = viewport.ActorTooltip.TooltipInfo.TooltipForPlayerStance(stance); labelText = viewport.ActorTooltip.TooltipInfo.TooltipForPlayerStance(stance);
break; break;
} }
case WorldTooltipType.FrozenActor: case WorldTooltipType.FrozenActor:
{ {
o = viewport.FrozenActorTooltip.TooltipOwner; o = viewport.FrozenActorTooltip.TooltipOwner;
showOwner = !o.NonCombatant && viewport.FrozenActorTooltip.TooltipInfo.IsOwnerRowVisible; showOwner = !o.NonCombatant && viewport.FrozenActorTooltip.TooltipInfo.IsOwnerRowVisible;
var stance = o == null || world.RenderPlayer == null ? Stance.None : o.Stances[world.RenderPlayer]; var stance = o == null || world.RenderPlayer == null ? Stance.None : o.Stances[world.RenderPlayer];
labelText = viewport.FrozenActorTooltip.TooltipInfo.TooltipForPlayerStance(stance); labelText = viewport.FrozenActorTooltip.TooltipInfo.TooltipForPlayerStance(stance);
break; break;
} }
} }
var textWidth = font.Measure(labelText).X; var textWidth = font.Measure(labelText).X;

View File

@@ -295,7 +295,7 @@ namespace OpenRA.Mods.RA.Widgets
if (ReadyTextStyle == ReadyTextStyleOptions.Solid || orderManager.LocalFrameNumber / 9 % 2 == 0) if (ReadyTextStyle == ReadyTextStyleOptions.Solid || orderManager.LocalFrameNumber / 9 % 2 == 0)
overlayFont.DrawTextWithContrast(ReadyText, icon.Pos + readyOffset, Color.White, Color.Black, 1); overlayFont.DrawTextWithContrast(ReadyText, icon.Pos + readyOffset, Color.White, Color.Black, 1);
else if (ReadyTextStyle == ReadyTextStyleOptions.AlternatingColor) else if (ReadyTextStyle == ReadyTextStyleOptions.AlternatingColor)
overlayFont.DrawTextWithContrast(ReadyText, icon.Pos + readyOffset, ReadyTextAltColor, Color.Black, 1); overlayFont.DrawTextWithContrast(ReadyText, icon.Pos + readyOffset, ReadyTextAltColor, Color.Black, 1);
} }
else if (first.Paused) else if (first.Paused)
overlayFont.DrawTextWithContrast(HoldText, overlayFont.DrawTextWithContrast(HoldText,

View File

@@ -94,9 +94,10 @@ namespace OpenRA.Mods.TS.Traits
initializePalettes = false; initializePalettes = false;
} }
yield return new VoxelRenderable(components, self.CenterPosition, 0, camera, info.Scale, yield return new VoxelRenderable(
lightSource, info.LightAmbientColor, info.LightDiffuseColor, components, self.CenterPosition, 0, camera, info.Scale,
colorPalette, normalsPalette, shadowPalette); lightSource, info.LightAmbientColor, info.LightDiffuseColor,
colorPalette, normalsPalette, shadowPalette);
} }
public string Image { get { return info.Image ?? self.Info.Name; } } public string Image { get { return info.Image ?? self.Info.Name; } }

View File

@@ -65,8 +65,8 @@ namespace OpenRA.Mods.TS.Traits
var rv = self.Trait<RenderVoxels>(); var rv = self.Trait<RenderVoxels>();
rv.Add(new VoxelAnimation(VoxelProvider.GetVoxel(rv.Image, info.Sequence), rv.Add(new VoxelAnimation(VoxelProvider.GetVoxel(rv.Image, info.Sequence),
() => BarrelOffset(), () => BarrelRotation(), () => BarrelOffset(), () => BarrelRotation(),
() => false, () => 0)); () => false, () => 0));
} }
WVec BarrelOffset() WVec BarrelOffset()

View File

@@ -48,8 +48,8 @@ namespace OpenRA.Mods.TS.Traits
var voxel = VoxelProvider.GetVoxel(rv.Image, info.Sequence); var voxel = VoxelProvider.GetVoxel(rv.Image, info.Sequence);
rv.Add(new VoxelAnimation(voxel, () => WVec.Zero, rv.Add(new VoxelAnimation(voxel, () => WVec.Zero,
() => new[] { body.QuantizeOrientation(self, self.Orientation) }, () => new[] { body.QuantizeOrientation(self, self.Orientation) },
() => false, () => 0)); () => false, () => 0));
// Selection size // Selection size
var rvi = self.Info.Traits.Get<RenderVoxelsInfo>(); var rvi = self.Info.Traits.Get<RenderVoxelsInfo>();

View File

@@ -57,8 +57,8 @@ namespace OpenRA.Mods.TS.Traits
var rv = self.Trait<RenderVoxels>(); var rv = self.Trait<RenderVoxels>();
rv.Add(new VoxelAnimation(VoxelProvider.GetVoxel(rv.Image, info.Sequence), rv.Add(new VoxelAnimation(VoxelProvider.GetVoxel(rv.Image, info.Sequence),
() => turreted.Position(self), () => TurretRotation(), () => turreted.Position(self), () => TurretRotation(),
() => false, () => 0)); () => false, () => 0));
} }
IEnumerable<WRot> TurretRotation() IEnumerable<WRot> TurretRotation()

View File

@@ -41,8 +41,8 @@ namespace OpenRA.Mods.TS.Traits
var voxel = VoxelProvider.GetVoxel(rv.Image, "idle"); var voxel = VoxelProvider.GetVoxel(rv.Image, "idle");
frames = voxel.Frames; frames = voxel.Frames;
rv.Add(new VoxelAnimation(voxel, () => WVec.Zero, rv.Add(new VoxelAnimation(voxel, () => WVec.Zero,
() => new[] { body.QuantizeOrientation(self, self.Orientation) }, () => new[] { body.QuantizeOrientation(self, self.Orientation) },
() => false, () => frame)); () => false, () => frame));
// Selection size // Selection size
var rvi = self.Info.Traits.Get<RenderVoxelsInfo>(); var rvi = self.Info.Traits.Get<RenderVoxelsInfo>();

View File

@@ -53,7 +53,7 @@ namespace OpenRA.Renderer.Sdl2
Log.Write("graphics", message); Log.Write("graphics", message);
Log.Write("graphics", ""); Log.Write("graphics", "");
Log.Write("graphics", "OpenGL Information:"); Log.Write("graphics", "OpenGL Information:");
Log.Write("graphics", "Vendor: {0}", GL.GetString(StringName.Vendor)); Log.Write("graphics", "Vendor: {0}", GL.GetString(StringName.Vendor));
if (GL.GetString(StringName.Vendor).Contains("Microsoft")) if (GL.GetString(StringName.Vendor).Contains("Microsoft"))
{ {
var msg = ""; var msg = "";
@@ -62,9 +62,9 @@ namespace OpenRA.Renderer.Sdl2
Log.Write("graphics", msg); Log.Write("graphics", msg);
} }
Log.Write("graphics", "Renderer: {0}", GL.GetString(StringName.Renderer)); Log.Write("graphics", "Renderer: {0}", GL.GetString(StringName.Renderer));
Log.Write("graphics", "GL Version: {0}", GL.GetString(StringName.Version)); Log.Write("graphics", "GL Version: {0}", GL.GetString(StringName.Version));
Log.Write("graphics", "Shader Version: {0}", GL.GetString(StringName.ShadingLanguageVersion)); Log.Write("graphics", "Shader Version: {0}", GL.GetString(StringName.ShadingLanguageVersion));
Log.Write("graphics", "Available extensions:"); Log.Write("graphics", "Available extensions:");
Log.Write("graphics", GL.GetString(StringName.Extensions)); Log.Write("graphics", GL.GetString(StringName.Extensions));
} }

View File

@@ -55,116 +55,116 @@ namespace OpenRA.Renderer.Sdl2
break; break;
case SDL.SDL_EventType.SDL_WINDOWEVENT: case SDL.SDL_EventType.SDL_WINDOWEVENT:
{
switch (e.window.windowEvent)
{ {
case SDL.SDL_WindowEventID.SDL_WINDOWEVENT_FOCUS_LOST: switch (e.window.windowEvent)
Game.HasInputFocus = false; {
break; case SDL.SDL_WindowEventID.SDL_WINDOWEVENT_FOCUS_LOST:
Game.HasInputFocus = false;
break;
case SDL.SDL_WindowEventID.SDL_WINDOWEVENT_FOCUS_GAINED: case SDL.SDL_WindowEventID.SDL_WINDOWEVENT_FOCUS_GAINED:
Game.HasInputFocus = true; Game.HasInputFocus = true;
break; break;
}
break;
} }
break;
}
case SDL.SDL_EventType.SDL_MOUSEBUTTONDOWN: case SDL.SDL_EventType.SDL_MOUSEBUTTONDOWN:
{
if (pendingMotion != null)
{ {
inputHandler.OnMouseInput(pendingMotion.Value); if (pendingMotion != null)
pendingMotion = null; {
inputHandler.OnMouseInput(pendingMotion.Value);
pendingMotion = null;
}
var button = MakeButton(e.button.button);
lastButtonBits |= button;
var pos = new int2(e.button.x, e.button.y);
inputHandler.OnMouseInput(new MouseInput(
MouseInputEvent.Down, button, scrollDelta, pos, mods,
MultiTapDetection.DetectFromMouse(e.button.button, pos)));
break;
} }
var button = MakeButton(e.button.button);
lastButtonBits |= button;
var pos = new int2(e.button.x, e.button.y);
inputHandler.OnMouseInput(new MouseInput(
MouseInputEvent.Down, button, scrollDelta, pos, mods,
MultiTapDetection.DetectFromMouse(e.button.button, pos)));
break;
}
case SDL.SDL_EventType.SDL_MOUSEBUTTONUP: case SDL.SDL_EventType.SDL_MOUSEBUTTONUP:
{
if (pendingMotion != null)
{ {
inputHandler.OnMouseInput(pendingMotion.Value); if (pendingMotion != null)
pendingMotion = null; {
inputHandler.OnMouseInput(pendingMotion.Value);
pendingMotion = null;
}
var button = MakeButton(e.button.button);
lastButtonBits &= ~button;
var pos = new int2(e.button.x, e.button.y);
inputHandler.OnMouseInput(new MouseInput(
MouseInputEvent.Up, button, scrollDelta, pos, mods,
MultiTapDetection.InfoFromMouse(e.button.button)));
break;
} }
var button = MakeButton(e.button.button);
lastButtonBits &= ~button;
var pos = new int2(e.button.x, e.button.y);
inputHandler.OnMouseInput(new MouseInput(
MouseInputEvent.Up, button, scrollDelta, pos, mods,
MultiTapDetection.InfoFromMouse(e.button.button)));
break;
}
case SDL.SDL_EventType.SDL_MOUSEMOTION: case SDL.SDL_EventType.SDL_MOUSEMOTION:
{ {
pendingMotion = new MouseInput( pendingMotion = new MouseInput(
MouseInputEvent.Move, lastButtonBits, scrollDelta, MouseInputEvent.Move, lastButtonBits, scrollDelta,
new int2(e.motion.x, e.motion.y), mods, 0); new int2(e.motion.x, e.motion.y), mods, 0);
break; break;
} }
case SDL.SDL_EventType.SDL_MOUSEWHEEL: case SDL.SDL_EventType.SDL_MOUSEWHEEL:
{ {
int x, y; int x, y;
SDL.SDL_GetMouseState(out x, out y); SDL.SDL_GetMouseState(out x, out y);
scrollDelta = e.wheel.y; scrollDelta = e.wheel.y;
inputHandler.OnMouseInput(new MouseInput(MouseInputEvent.Scroll, MouseButton.None, scrollDelta, new int2(x, y), Modifiers.None, 0)); inputHandler.OnMouseInput(new MouseInput(MouseInputEvent.Scroll, MouseButton.None, scrollDelta, new int2(x, y), Modifiers.None, 0));
break; break;
} }
case SDL.SDL_EventType.SDL_TEXTINPUT: case SDL.SDL_EventType.SDL_TEXTINPUT:
{ {
var rawBytes = new byte[SDL.SDL_TEXTINPUTEVENT_TEXT_SIZE]; var rawBytes = new byte[SDL.SDL_TEXTINPUTEVENT_TEXT_SIZE];
unsafe { Marshal.Copy((IntPtr)e.text.text, rawBytes, 0, SDL.SDL_TEXTINPUTEVENT_TEXT_SIZE); } unsafe { Marshal.Copy((IntPtr)e.text.text, rawBytes, 0, SDL.SDL_TEXTINPUTEVENT_TEXT_SIZE); }
inputHandler.OnTextInput(Encoding.UTF8.GetString(rawBytes, 0, Array.IndexOf(rawBytes, (byte)0))); inputHandler.OnTextInput(Encoding.UTF8.GetString(rawBytes, 0, Array.IndexOf(rawBytes, (byte)0)));
break; break;
} }
case SDL.SDL_EventType.SDL_KEYDOWN: case SDL.SDL_EventType.SDL_KEYDOWN:
case SDL.SDL_EventType.SDL_KEYUP: case SDL.SDL_EventType.SDL_KEYUP:
{
var keyCode = (Keycode)e.key.keysym.sym;
var type = e.type == SDL.SDL_EventType.SDL_KEYDOWN ?
KeyInputEvent.Down : KeyInputEvent.Up;
var tapCount = e.type == SDL.SDL_EventType.SDL_KEYDOWN ?
MultiTapDetection.DetectFromKeyboard(keyCode) :
MultiTapDetection.InfoFromKeyboard(keyCode);
var keyEvent = new KeyInput
{ {
Event = type, var keyCode = (Keycode)e.key.keysym.sym;
Key = keyCode, var type = e.type == SDL.SDL_EventType.SDL_KEYDOWN ?
Modifiers = mods, KeyInputEvent.Down : KeyInputEvent.Up;
UnicodeChar = (char)e.key.keysym.sym,
MultiTapCount = tapCount
};
// Special case workaround for windows users var tapCount = e.type == SDL.SDL_EventType.SDL_KEYDOWN ?
if (e.key.keysym.sym == SDL.SDL_Keycode.SDLK_F4 && mods.HasModifier(Modifiers.Alt) && MultiTapDetection.DetectFromKeyboard(keyCode) :
Platform.CurrentPlatform == PlatformType.Windows) MultiTapDetection.InfoFromKeyboard(keyCode);
Game.Exit();
else
inputHandler.OnKeyInput(keyEvent);
break; var keyEvent = new KeyInput
} {
Event = type,
Key = keyCode,
Modifiers = mods,
UnicodeChar = (char)e.key.keysym.sym,
MultiTapCount = tapCount
};
// Special case workaround for windows users
if (e.key.keysym.sym == SDL.SDL_Keycode.SDLK_F4 && mods.HasModifier(Modifiers.Alt) &&
Platform.CurrentPlatform == PlatformType.Windows)
Game.Exit();
else
inputHandler.OnKeyInput(keyEvent);
break;
}
} }
} }

View File

@@ -22,14 +22,16 @@ namespace OpenRA.Test
[SetUp] [SetUp]
public void SetUp() public void SetUp()
{ {
order = new Order("TestOrder", null, false) { order = new Order("TestOrder", null, false)
{
TargetString = "TestTarget", TargetString = "TestTarget",
TargetLocation = new CPos(1234, 5678), TargetLocation = new CPos(1234, 5678),
ExtraData = 1234, ExtraData = 1234,
ExtraLocation = new CPos(555, 555) ExtraLocation = new CPos(555, 555)
}; };
immediateOrder = new Order("TestOrderImmediate", null, false) { immediateOrder = new Order("TestOrderImmediate", null, false)
{
IsImmediate = true, IsImmediate = true,
TargetString = "TestTarget" TargetString = "TestTarget"
}; };