diff --git a/OpenRA.Game/Actor.cs b/OpenRA.Game/Actor.cs index 919cc93ac8..cf2467f28c 100644 --- a/OpenRA.Game/Actor.cs +++ b/OpenRA.Game/Actor.cs @@ -24,12 +24,13 @@ namespace OpenRA { public class Actor : IScriptBindable, IScriptNotifyBind, ILuaTableBinding, ILuaEqualityBinding, ILuaToStringBinding, IEquatable { - [Sync] public Player Owner; - public readonly ActorInfo Info; public readonly World World; public readonly uint ActorID; + [Sync] + public Player Owner; + public bool IsInWorld { get; internal set; } public bool Destroyed { get; private set; } diff --git a/OpenRA.Game/CPos.cs b/OpenRA.Game/CPos.cs index 5b585baf2f..2a01fae2d2 100644 --- a/OpenRA.Game/CPos.cs +++ b/OpenRA.Game/CPos.cs @@ -31,7 +31,7 @@ namespace OpenRA public static CVec operator -(CPos a, CPos b) { return new CVec(a.X - b.X, a.Y - b.Y); } - public static bool operator ==(CPos me, CPos other) { return (me.X == other.X && me.Y == other.Y); } + public static bool operator ==(CPos me, CPos other) { return me.X == other.X && me.Y == other.Y; } public static bool operator !=(CPos me, CPos other) { return !(me == other); } public static CPos Max(CPos a, CPos b) { return new CPos(Math.Max(a.X, b.X), Math.Max(a.Y, b.Y)); } diff --git a/OpenRA.Game/CVec.cs b/OpenRA.Game/CVec.cs index 873d3a4836..0203110af4 100644 --- a/OpenRA.Game/CVec.cs +++ b/OpenRA.Game/CVec.cs @@ -31,7 +31,7 @@ namespace OpenRA public static CVec operator -(CVec a) { return new CVec(-a.X, -a.Y); } - public static bool operator ==(CVec me, CVec other) { return (me.X == other.X && me.Y == other.Y); } + public static bool operator ==(CVec me, CVec other) { return me.X == other.X && me.Y == other.Y; } public static bool operator !=(CVec me, CVec other) { return !(me == other); } public static CVec Max(CVec a, CVec b) { return new CVec(Math.Max(a.X, b.X), Math.Max(a.Y, b.Y)); } @@ -48,8 +48,7 @@ namespace OpenRA { return new CVec( Math.Min(r.Right, Math.Max(X, r.Left)), - Math.Min(r.Bottom, Math.Max(Y, r.Top)) - ); + Math.Min(r.Bottom, Math.Max(Y, r.Top))); } public override int GetHashCode() { return X.GetHashCode() ^ Y.GetHashCode(); } diff --git a/OpenRA.Game/Exts.cs b/OpenRA.Game/Exts.cs index 17b7b4da62..e636824a79 100644 --- a/OpenRA.Game/Exts.cs +++ b/OpenRA.Game/Exts.cs @@ -91,8 +91,7 @@ namespace OpenRA { return (k & mod) == mod; } - - + public static V GetOrAdd(this Dictionary d, K k) where V : new() { @@ -184,6 +183,7 @@ namespace OpenRA u = nextU; } } + return t; } } @@ -242,7 +242,6 @@ namespace OpenRA // Adjust for other rounding modes if (round == ISqrtRoundMode.Nearest && remainder > root) root += 1; - else if (round == ISqrtRoundMode.Ceiling && root * root < number) root += 1; @@ -284,7 +283,6 @@ namespace OpenRA // Adjust for other rounding modes if (round == ISqrtRoundMode.Nearest && remainder > root) root += 1; - else if (round == ISqrtRoundMode.Ceiling && root * root < number) root += 1; diff --git a/OpenRA.Game/FieldLoader.cs b/OpenRA.Game/FieldLoader.cs index 616bc1af34..9ec3847d44 100644 --- a/OpenRA.Game/FieldLoader.cs +++ b/OpenRA.Game/FieldLoader.cs @@ -131,7 +131,6 @@ namespace OpenRA return res; return InvalidValueAction(value, fieldType, fieldName); } - else if (fieldType == typeof(ushort)) { ushort res; @@ -147,7 +146,6 @@ namespace OpenRA return res; return InvalidValueAction(value, fieldType, fieldName); } - else if (fieldType == typeof(float)) { float res; @@ -155,7 +153,6 @@ namespace OpenRA return res * (value.Contains('%') ? 0.01f : 1f); return InvalidValueAction(value, fieldType, fieldName); } - else if (fieldType == typeof(decimal)) { decimal res; @@ -163,14 +160,12 @@ namespace OpenRA return res * (value.Contains('%') ? 0.01m : 1m); return InvalidValueAction(value, fieldType, fieldName); } - else if (fieldType == typeof(string)) { if (field != null && field.HasAttribute()) return Regex.Replace(value, "@[^@]+@", m => Translate(m.Value.Substring(1, m.Value.Length - 2)), RegexOptions.Compiled); return value; } - else if (fieldType == typeof(Color)) { var parts = value.Split(','); @@ -187,7 +182,6 @@ namespace OpenRA Exts.ParseIntegerInvariant(parts[3]).Clamp(0, 255)); return InvalidValueAction(value, fieldType, fieldName); } - else if (fieldType == typeof(Color[])) { var parts = value.Split(','); @@ -208,7 +202,6 @@ namespace OpenRA return colors; } - else if (fieldType == typeof(HSLColor)) { var parts = value.Split(','); @@ -222,7 +215,6 @@ namespace OpenRA return InvalidValueAction(value, fieldType, fieldName); } - else if (fieldType == typeof(Hotkey)) { Hotkey res; @@ -231,7 +223,6 @@ namespace OpenRA return InvalidValueAction(value, fieldType, fieldName); } - else if (fieldType == typeof(WRange)) { WRange res; @@ -240,7 +231,6 @@ namespace OpenRA return InvalidValueAction(value, fieldType, fieldName); } - else if (fieldType == typeof(WVec)) { var parts = value.Split(','); @@ -253,7 +243,6 @@ namespace OpenRA return InvalidValueAction(value, fieldType, fieldName); } - else if (fieldType == typeof(WVec[])) { var parts = value.Split(','); @@ -274,7 +263,6 @@ namespace OpenRA return vecs; } - else if (fieldType == typeof(WPos)) { var parts = value.Split(','); @@ -287,7 +275,6 @@ namespace OpenRA return InvalidValueAction(value, fieldType, fieldName); } - else if (fieldType == typeof(WAngle)) { int res; @@ -295,7 +282,6 @@ namespace OpenRA return new WAngle(res); return InvalidValueAction(value, fieldType, fieldName); } - else if (fieldType == typeof(WRot)) { var parts = value.Split(','); @@ -310,7 +296,6 @@ namespace OpenRA return InvalidValueAction(value, fieldType, fieldName); } - else if (fieldType == typeof(CPos)) { var parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); @@ -318,7 +303,6 @@ namespace OpenRA Exts.ParseIntegerInvariant(parts[0]), Exts.ParseIntegerInvariant(parts[1])); } - else if (fieldType == typeof(CVec)) { var parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); @@ -326,7 +310,6 @@ namespace OpenRA Exts.ParseIntegerInvariant(parts[0]), Exts.ParseIntegerInvariant(parts[1])); } - else if (fieldType.IsEnum) { try @@ -338,10 +321,8 @@ namespace OpenRA return InvalidValueAction(value, fieldType, fieldName); } } - else if (fieldType == typeof(bool)) return ParseYesNo(value, fieldType, fieldName); - else if (fieldType.IsArray) { if (value == null) @@ -354,7 +335,6 @@ namespace OpenRA ret.SetValue(GetValue(fieldName, fieldType.GetElementType(), parts[i].Trim(), field), i); return ret; } - else if (fieldType == typeof(Size)) { var parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); @@ -362,7 +342,6 @@ namespace OpenRA Exts.ParseIntegerInvariant(parts[0]), Exts.ParseIntegerInvariant(parts[1])); } - else if (fieldType == typeof(int2)) { var parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); @@ -370,7 +349,6 @@ namespace OpenRA Exts.ParseIntegerInvariant(parts[0]), Exts.ParseIntegerInvariant(parts[1])); } - else if (fieldType == typeof(float2)) { var parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); @@ -383,7 +361,6 @@ namespace OpenRA yy = res * (parts[1].Contains('%') ? 0.01f : 1f); return new float2(xx, yy); } - else if (fieldType == typeof(Rectangle)) { var parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); @@ -393,7 +370,6 @@ namespace OpenRA Exts.ParseIntegerInvariant(parts[2]), Exts.ParseIntegerInvariant(parts[3])); } - else if (fieldType.IsGenericType && fieldType.GetGenericTypeDefinition() == typeof(Bits<>)) { var parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); @@ -401,14 +377,12 @@ namespace OpenRA var argValues = new object[] { parts }; return fieldType.GetConstructor(argTypes).Invoke(argValues); } - else if (fieldType.IsGenericType && fieldType.GetGenericTypeDefinition() == typeof(Nullable<>)) { var innerType = fieldType.GetGenericArguments().First(); var innerValue = GetValue("Nullable", innerType, value, field); return fieldType.GetConstructor(new[] { innerType }).Invoke(new[] { innerValue }); } - else if (fieldType == typeof(DateTime)) { DateTime dt; @@ -416,7 +390,6 @@ namespace OpenRA return dt; return InvalidValueAction(value, fieldType, fieldName); } - else { var conv = TypeDescriptor.GetConverter(fieldType); diff --git a/OpenRA.Game/FieldSaver.cs b/OpenRA.Game/FieldSaver.cs index e14c179624..940dcf82ca 100644 --- a/OpenRA.Game/FieldSaver.cs +++ b/OpenRA.Game/FieldSaver.cs @@ -46,8 +46,7 @@ namespace OpenRA return new MiniYaml( null, - fields.Select(info => new MiniYamlNode(info.YamlName, FormatValue(o, info.Field))).ToList() - ); + fields.Select(info => new MiniYamlNode(info.YamlName, FormatValue(o, info.Field))).ToList()); } public static MiniYamlNode SaveField(object o, string field) diff --git a/OpenRA.Game/FileFormats/Blast.cs b/OpenRA.Game/FileFormats/Blast.cs index 48c6413af4..31c9d628a5 100644 --- a/OpenRA.Game/FileFormats/Blast.cs +++ b/OpenRA.Game/FileFormats/Blast.cs @@ -142,9 +142,9 @@ namespace OpenRA.FileFormats } } while (len != 0); } - // literal value else { + // literal value var symbol = EncodedLiterals ? Decode(litcode, br) : br.ReadBits(8); outBuffer[next++] = (byte)symbol; if (next == MAXWIN) diff --git a/OpenRA.Game/FileFormats/Blowfish.cs b/OpenRA.Game/FileFormats/Blowfish.cs index e841f205c2..6501f932c3 100644 --- a/OpenRA.Game/FileFormats/Blowfish.cs +++ b/OpenRA.Game/FileFormats/Blowfish.cs @@ -26,7 +26,7 @@ namespace OpenRA.FileFormats uint l = 0, r = 0; - for (var i = 0; i < 18; ) + for (var i = 0; i < 18;) { Encrypt(ref l, ref r); m_p[i++] = l; @@ -34,7 +34,7 @@ namespace OpenRA.FileFormats } for (var i = 0; i < 4; ++i) - for (var j = 0; j < 256; ) + for (var j = 0; j < 256;) { Encrypt(ref l, ref r); m_s[i, j++] = l; @@ -45,7 +45,7 @@ namespace OpenRA.FileFormats public uint[] Encrypt(uint[] data) { return RunCipher(data, Encrypt); } public uint[] Decrypt(uint[] data) { return RunCipher(data, Decrypt); } - delegate void CipherFunc( ref uint a, ref uint b ); + delegate void CipherFunc(ref uint a, ref uint b); static uint[] RunCipher(uint[] data, CipherFunc f) { @@ -56,7 +56,7 @@ namespace OpenRA.FileFormats while (size-- > 0) { var a = SwapBytes(data[i]); - var b = SwapBytes(data[i+1]); + var b = SwapBytes(data[i + 1]); f(ref a, ref b); @@ -73,13 +73,14 @@ namespace OpenRA.FileFormats _a ^= m_p[0]; var x = false; - for( var i = 1; i <= 16; i++, x ^= true) + for (var i = 1; i <= 16; i++, x ^= true) { if (x) Round(ref _a, _b, i); else Round(ref _b, _a, i); } + _b ^= m_p[17]; a = _b; @@ -99,6 +100,7 @@ namespace OpenRA.FileFormats else Round(ref _b, _a, i); } + _b ^= m_p[0]; a = _b; @@ -400,7 +402,6 @@ namespace OpenRA.FileFormats 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6 } - }; } } diff --git a/OpenRA.Game/FileFormats/BlowfishKeyProvider.cs b/OpenRA.Game/FileFormats/BlowfishKeyProvider.cs index 3e9b007cf1..6a185f586a 100644 --- a/OpenRA.Game/FileFormats/BlowfishKeyProvider.cs +++ b/OpenRA.Game/FileFormats/BlowfishKeyProvider.cs @@ -25,6 +25,7 @@ namespace OpenRA.FileFormats public uint[] key2 = new uint[64]; public uint len; } + PublicKey pubkey = new PublicKey(); uint[] glob1 = new uint[64]; @@ -81,6 +82,7 @@ namespace OpenRA.FileFormats keylen = key[j]; j++; } + if (keylen <= len * 4) move_key_to_big(n, key.Skip(j).ToArray(), keylen, len); } @@ -105,6 +107,7 @@ namespace OpenRA.FileFormats mask >>= 1; bitlen--; } + return bitlen; } @@ -124,13 +127,13 @@ namespace OpenRA.FileFormats static int cmp_bignum(uint[] n1, uint[] n2, uint len) { - while (len > 0) { --len; if (n1[len] < n2[len]) return -1; if (n1[len] > n2[len]) return 1; } + return 0; } @@ -149,6 +152,7 @@ namespace OpenRA.FileFormats for (; i < len; i++) n[i] = 0; bits = bits % 32; } + if (bits == 0) return; for (i = 0; i < len - 1; i++) n[i] = (n[i] >> bits) | (n[i + 1] << (32 - bits)); @@ -166,6 +170,7 @@ namespace OpenRA.FileFormats for (; i > 0; i--) n[i] = 0; bits = bits % 32; } + if (bits == 0) return; for (i = len - 1; i > 0; i--) n[i] = (n[i] << bits) | (n[i - 1] >> (32 - bits)); @@ -196,6 +201,7 @@ namespace OpenRA.FileFormats } } } + return carry; } @@ -215,8 +221,8 @@ namespace OpenRA.FileFormats i2 = *ps2++; *pd++ = (ushort)(i1 - i2 - carry); if (((i1 - i2 - carry) & 0x10000) != 0) carry = 1; else carry = 0; - } + return carry; } @@ -245,6 +251,7 @@ namespace OpenRA.FileFormats sub_bignum(n_tmp, n_tmp, n2, 0, (int)len); n1[j] |= bit; } + bit >>= 1; if (bit == 0) { @@ -252,6 +259,7 @@ namespace OpenRA.FileFormats bit = 0x80000000; } } + init_bignum(n_tmp, 0, len); } @@ -278,6 +286,7 @@ namespace OpenRA.FileFormats shr_bignum(glob1_hi_inv, 1, 2); glob1_hi_bitlen--; } + glob1_hi_inv_lo = (ushort)glob1_hi_inv[0]; glob1_hi_inv_hi = (ushort)(glob1_hi_inv[0] >> 16); } @@ -311,8 +320,8 @@ namespace OpenRA.FileFormats unsafe { - fixed( uint * _psrc2 = &src2[0] ) - fixed(uint* _pdest = &dest[0]) + fixed (uint* _psrc2 = &src2[0]) + fixed (uint* _pdest = &dest[0]) { var psrc2 = (ushort*)_psrc2; var pdest = (ushort*)_pdest; @@ -360,7 +369,7 @@ namespace OpenRA.FileFormats uint g2_len_x2, len_diff; unsafe { - fixed( uint* g1 = &glob1[0]) + fixed (uint* g1 = &glob1[0]) fixed (uint* g2 = &glob2[0]) { mul_bignum(glob2, n2, n3, len); @@ -383,13 +392,15 @@ namespace OpenRA.FileFormats mul_bignum_word(esi, glob1, tmp, 2 * len); if ((*edi & 0x8000) == 0) { - if (0 != sub_bignum((uint*)esi, (uint*)esi, g1, 0, (int)len)) (*edi)--; + if (0 != sub_bignum((uint*)esi, (uint*)esi, g1, 0, (int)len))(*edi)--; } } } + neg_bignum(glob2, len); dec_bignum(glob2, len); } + mov_bignum(n1, glob2, len); } } @@ -437,6 +448,7 @@ namespace OpenRA.FileFormats bit_mask = 0x80000000; pn3--; } + calc_a_bignum(n_tmp, n1, n1, n4_len); if ((*pn3 & bit_mask) != 0) calc_a_bignum(n1, n_tmp, n2, n4_len); @@ -444,6 +456,7 @@ namespace OpenRA.FileFormats mov_bignum(n1, n_tmp, n4_len); bit_mask >>= 1; } + init_bignum(n_tmp, 0, n4_len); clear_tmp_vars(len); } @@ -455,7 +468,7 @@ namespace OpenRA.FileFormats while (len-- != 0) *dest++ = *src++; } - unsafe void process_predata(byte* pre, uint pre_len, byte *buf) + unsafe void process_predata(byte* pre, uint pre_len, byte* buf) { var n2 = new uint[64]; var n3 = new uint[64]; @@ -464,12 +477,12 @@ namespace OpenRA.FileFormats while (a + 1 <= pre_len) { init_bignum(n2, 0, 64); - fixed( uint * pn2 = &n2[0] ) - memcpy((byte *)pn2, pre, (int)a + 1); + fixed (uint* pn2 = &n2[0]) + memcpy((byte*)pn2, pre, (int)a + 1); calc_a_key(n3, n2, pubkey.key2, pubkey.key1, 64); - fixed( uint * pn3 = &n3[0] ) - memcpy(buf, (byte *)pn3, (int)a); + fixed (uint* pn3 = &n3[0]) + memcpy(buf, (byte*)pn3, (int)a); pre_len -= a + 1; pre += a + 1; @@ -488,6 +501,7 @@ namespace OpenRA.FileFormats fixed (byte* psrc = &src[0]) process_predata(psrc, len_predata(), pdest); } + return dest.Take(56).ToArray(); } } diff --git a/OpenRA.Game/FileFormats/CRC32.cs b/OpenRA.Game/FileFormats/CRC32.cs index 21cf13c01a..bdc1bb994d 100644 --- a/OpenRA.Game/FileFormats/CRC32.cs +++ b/OpenRA.Game/FileFormats/CRC32.cs @@ -10,7 +10,6 @@ namespace OpenRA.FileFormats { - /// /// Static class that uses a lookup table to calculates CRC32 /// checksums of input strings. @@ -104,6 +103,7 @@ namespace OpenRA.FileFormats crc ^= polynomial; return crc; } + public static uint Calculate(byte[] data) { return Calculate(data, 0xFFFFFFFF); @@ -125,6 +125,7 @@ namespace OpenRA.FileFormats crc ^= polynomial; return crc; } + public static unsafe uint Calculate(byte* data, uint len) { return Calculate(data, len, 0xFFFFFFFF); diff --git a/OpenRA.Game/FileFormats/Format40.cs b/OpenRA.Game/FileFormats/Format40.cs index ed250e88e7..5aeeb219af 100644 --- a/OpenRA.Game/FileFormats/Format40.cs +++ b/OpenRA.Game/FileFormats/Format40.cs @@ -50,7 +50,7 @@ namespace OpenRA.FileFormats if ((count & 0x8000) == 0) { // case 2 - destIndex += (count & 0x7FFF); + destIndex += count & 0x7FFF; } else if ((count & 0x4000) == 0) { diff --git a/OpenRA.Game/FileFormats/HvaReader.cs b/OpenRA.Game/FileFormats/HvaReader.cs index b2724a9b5c..4779bd8e99 100644 --- a/OpenRA.Game/FileFormats/HvaReader.cs +++ b/OpenRA.Game/FileFormats/HvaReader.cs @@ -22,20 +22,20 @@ namespace OpenRA.FileFormats public HvaReader(Stream s) { // Index swaps for transposing a matrix - var ids = new byte[]{0,4,8,12,1,5,9,13,2,6,10,14}; + var ids = new byte[] { 0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14 }; s.Seek(16, SeekOrigin.Begin); FrameCount = s.ReadUInt32(); LimbCount = s.ReadUInt32(); // Skip limb names - s.Seek(16*LimbCount, SeekOrigin.Current); - Transforms = new float[16*FrameCount*LimbCount]; + s.Seek(16 * LimbCount, SeekOrigin.Current); + Transforms = new float[16 * FrameCount * LimbCount]; for (var j = 0; j < FrameCount; j++) for (var i = 0; i < LimbCount; i++) { // 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 + 7] = 0; Transforms[c + 11] = 0; diff --git a/OpenRA.Game/FileFormats/PngLoader.cs b/OpenRA.Game/FileFormats/PngLoader.cs index 261a7fd641..c9a07c704a 100644 --- a/OpenRA.Game/FileFormats/PngLoader.cs +++ b/OpenRA.Game/FileFormats/PngLoader.cs @@ -41,7 +41,7 @@ namespace OpenRA.FileFormats Color[] palette = null; var data = new List(); - for (; ; ) + for (;;) { var length = IPAddress.NetworkToHostOrder(br.ReadInt32()); var type = Encoding.UTF8.GetString(br.ReadBytes(4)); @@ -54,7 +54,6 @@ namespace OpenRA.FileFormats { case "IHDR": { - var width = IPAddress.NetworkToHostOrder(cr.ReadInt32()); var height = IPAddress.NetworkToHostOrder(cr.ReadInt32()); var bitDepth = cr.ReadByte(); @@ -67,8 +66,8 @@ namespace OpenRA.FileFormats if (interlace != 0) throw new InvalidDataException("Interlacing not supported"); bitmap = new Bitmap(width, height, MakePixelFormat(bitDepth, colorType)); - } + break; case "PLTE": @@ -80,6 +79,7 @@ namespace OpenRA.FileFormats palette[i] = Color.FromArgb(r, g, b); } } + break; case "tRNS": @@ -87,12 +87,14 @@ namespace OpenRA.FileFormats for (var i = 0; i < length; i++) palette[i] = Color.FromArgb(cr.ReadByte(), palette[i]); } + break; case "IDAT": { data.AddRange(content); } + break; case "IEND": @@ -168,8 +170,8 @@ namespace OpenRA.FileFormats } [Flags] - enum PngColorType { Indexed = 1, Color = 2, Alpha = 4 }; - enum PngFilter { None, Sub, Up, Average, Paeth }; + enum PngColorType { Indexed = 1, Color = 2, Alpha = 4 } + enum PngFilter { None, Sub, Up, Average, Paeth } static PixelFormat MakePixelFormat(byte bitDepth, PngColorType colorType) { diff --git a/OpenRA.Game/FileFormats/VxlReader.cs b/OpenRA.Game/FileFormats/VxlReader.cs index 01b9adf51d..08e7075436 100644 --- a/OpenRA.Game/FileFormats/VxlReader.cs +++ b/OpenRA.Game/FileFormats/VxlReader.cs @@ -42,11 +42,11 @@ namespace OpenRA.FileFormats static void ReadVoxelData(Stream s, VxlLimb l) { - var baseSize = l.Size[0]*l.Size[1]; + var baseSize = l.Size[0] * l.Size[1]; var colStart = new int[baseSize]; for (var i = 0; i < baseSize; i++) colStart[i] = s.ReadInt32(); - s.Seek(4*baseSize, SeekOrigin.Current); + s.Seek(4 * baseSize, SeekOrigin.Current); var dataStart = s.Position; // Count the voxels in this limb @@ -65,12 +65,12 @@ namespace OpenRA.FileFormats var count = s.ReadUInt8(); z += count; l.VoxelCount += count; - s.Seek(2*count + 1, SeekOrigin.Current); + s.Seek(2 * count + 1, SeekOrigin.Current); } while (z < l.Size[2]); } // Read the data - l.VoxelMap = new Dictionary[l.Size[0],l.Size[1]]; + l.VoxelMap = new Dictionary[l.Size[0], l.Size[1]]; for (var i = 0; i < baseSize; i++) { // Empty column @@ -82,7 +82,7 @@ namespace OpenRA.FileFormats var x = (byte)(i % l.Size[0]); var y = (byte)(i / l.Size[0]); byte z = 0; - l.VoxelMap[x,y] = new Dictionary(); + l.VoxelMap[x, y] = new Dictionary(); do { z += s.ReadUInt8(); @@ -93,9 +93,10 @@ namespace OpenRA.FileFormats v.Color = s.ReadUInt8(); v.Normal = s.ReadUInt8(); - l.VoxelMap[x,y].Add(z, v); + l.VoxelMap[x, y].Add(z, v); z++; } + // Skip duplicate count s.ReadUInt8(); } while (z < l.Size[2]); @@ -104,7 +105,6 @@ namespace OpenRA.FileFormats public VxlReader(Stream s) { - if (!s.ReadASCII(16).StartsWith("Voxel Animation")) throw new InvalidDataException("Invalid vxl header"); @@ -124,7 +124,7 @@ namespace OpenRA.FileFormats } // Skip to the Limb footers - s.Seek(802 + 28*LimbCount + BodySize, SeekOrigin.Begin); + s.Seek(802 + 28 * LimbCount + BodySize, SeekOrigin.Begin); var LimbDataOffset = new uint[LimbCount]; for (var i = 0; i < LimbCount; i++) @@ -143,7 +143,7 @@ namespace OpenRA.FileFormats for (var i = 0; i < LimbCount; i++) { - s.Seek(802 + 28*LimbCount + LimbDataOffset[i], SeekOrigin.Begin); + s.Seek(802 + 28 * LimbCount + LimbDataOffset[i], SeekOrigin.Begin); ReadVoxelData(s, Limbs[i]); } } diff --git a/OpenRA.Game/FileFormats/WavLoader.cs b/OpenRA.Game/FileFormats/WavLoader.cs index f718f42bc8..36cfeb373a 100644 --- a/OpenRA.Game/FileFormats/WavLoader.cs +++ b/OpenRA.Game/FileFormats/WavLoader.cs @@ -30,7 +30,7 @@ namespace OpenRA.FileFormats public readonly int DataSize; public readonly byte[] RawOutput; - public enum WaveType { Pcm = 0x1, ImaAdpcm = 0x11 }; + public enum WaveType { Pcm = 0x1, ImaAdpcm = 0x11 } public static WaveType Type { get; private set; } public WavLoader(Stream s) @@ -69,6 +69,7 @@ namespace OpenRA.FileFormats UncompressedSize = s.ReadInt32(); s.ReadBytes(chunkSize - 4); } + break; case "data": DataSize = s.ReadInt32(); @@ -80,6 +81,7 @@ namespace OpenRA.FileFormats var chunkSize = s.ReadInt32(); s.ReadBytes(chunkSize); } + break; } } diff --git a/OpenRA.Game/FileFormats/XccGlobalDatabase.cs b/OpenRA.Game/FileFormats/XccGlobalDatabase.cs index fdc028cc42..9e764d232e 100644 --- a/OpenRA.Game/FileFormats/XccGlobalDatabase.cs +++ b/OpenRA.Game/FileFormats/XccGlobalDatabase.cs @@ -34,7 +34,7 @@ namespace OpenRA.FileFormats entries.Add(new string(chars.ToArray())); // Skip comment - while ((c = reader.ReadChar()) != 0); + while ((c = reader.ReadChar()) != 0) { } } } diff --git a/OpenRA.Game/FileFormats/XccLocalDatabase.cs b/OpenRA.Game/FileFormats/XccLocalDatabase.cs index 3c4570b07b..63ed87759d 100644 --- a/OpenRA.Game/FileFormats/XccLocalDatabase.cs +++ b/OpenRA.Game/FileFormats/XccLocalDatabase.cs @@ -47,9 +47,9 @@ namespace OpenRA.FileFormats using (var writer = new BinaryWriter(data)) { writer.Write(Encoding.ASCII.GetBytes("XCC by Olaf van der Spek")); - writer.Write(new byte[] {0x1A,0x04,0x17,0x27,0x10,0x19,0x80,0x00}); + writer.Write(new byte[] { 0x1A, 0x04, 0x17, 0x27, 0x10, 0x19, 0x80, 0x00 }); - writer.Write((int)(Entries.Aggregate(Entries.Length, (a,b) => a + b.Length) + 52)); // Size + writer.Write((int)(Entries.Aggregate(Entries.Length, (a, b) => a + b.Length) + 52)); // Size writer.Write((int)0); // Type writer.Write((int)0); // Version writer.Write((int)0); // Game/Format (0 == TD) @@ -64,4 +64,4 @@ namespace OpenRA.FileFormats return data.ToArray(); } } -} \ No newline at end of file +} diff --git a/OpenRA.Game/FileSystem/D2kSoundResources.cs b/OpenRA.Game/FileSystem/D2kSoundResources.cs index 6dbafc593e..92c8edb92c 100644 --- a/OpenRA.Game/FileSystem/D2kSoundResources.cs +++ b/OpenRA.Game/FileSystem/D2kSoundResources.cs @@ -76,7 +76,7 @@ namespace OpenRA.FileSystem public string Name { get { return filename; } } - public int Priority { get { return 1000 + priority; }} + public int Priority { get { return 1000 + priority; } } public IEnumerable ClassicHashes() { diff --git a/OpenRA.Game/FileSystem/Folder.cs b/OpenRA.Game/FileSystem/Folder.cs index 061d5101fb..d6f5337fe1 100644 --- a/OpenRA.Game/FileSystem/Folder.cs +++ b/OpenRA.Game/FileSystem/Folder.cs @@ -39,7 +39,7 @@ namespace OpenRA.FileSystem public Stream GetContent(string filename) { - try { return File.OpenRead( Path.Combine( path, filename ) ); } + try { return File.OpenRead(Path.Combine(path, filename)); } catch { return null; } } diff --git a/OpenRA.Game/FileSystem/GlobalFileSystem.cs b/OpenRA.Game/FileSystem/GlobalFileSystem.cs index 937fec71cc..137902d583 100644 --- a/OpenRA.Game/FileSystem/GlobalFileSystem.cs +++ b/OpenRA.Game/FileSystem/GlobalFileSystem.cs @@ -88,6 +88,7 @@ namespace OpenRA.FileSystem return new MixFile(filename, type, order); } + if (filename.EndsWith(".zip", StringComparison.InvariantCultureIgnoreCase)) return new ZipFile(filename, order); if (filename.EndsWith(".oramap", StringComparison.InvariantCultureIgnoreCase)) diff --git a/OpenRA.Game/FileSystem/InstallShieldPackage.cs b/OpenRA.Game/FileSystem/InstallShieldPackage.cs index 35e0271f29..e15f8cdf02 100644 --- a/OpenRA.Game/FileSystem/InstallShieldPackage.cs +++ b/OpenRA.Game/FileSystem/InstallShieldPackage.cs @@ -51,6 +51,7 @@ namespace OpenRA.FileSystem var TOCreader = new BinaryReader(s); var fileCountInDirs = new List(); + // Parse directories for (var i = 0; i < DirCount; i++) fileCountInDirs.Add(ParseDirectory(TOCreader)); @@ -59,7 +60,6 @@ namespace OpenRA.FileSystem foreach (var fileCount in fileCountInDirs) for (var i = 0; i < fileCount; i++) ParseFile(reader); - } static uint ParseDirectory(BinaryReader reader) @@ -68,7 +68,7 @@ namespace OpenRA.FileSystem var FileCount = reader.ReadUInt16(); var ChunkSize = reader.ReadUInt16(); var NameLength = reader.ReadUInt16(); - reader.ReadChars(NameLength); //var DirName = new String(reader.ReadChars(NameLength)); + reader.ReadChars(NameLength); // var DirName = new String(reader.ReadChars(NameLength)); // Skip to the end of the chunk reader.ReadBytes(ChunkSize - NameLength - 6); @@ -84,11 +84,11 @@ namespace OpenRA.FileSystem var ChunkSize = reader.ReadUInt16(); reader.ReadBytes(4); var NameLength = reader.ReadByte(); - var FileName = new String(reader.ReadChars(NameLength)); + var FileName = new string(reader.ReadChars(NameLength)); var hash = PackageEntry.HashFilename(FileName, PackageHashType.Classic); if (!index.ContainsKey(hash)) - index.Add(hash, new PackageEntry(hash,AccumulatedData, CompressedSize)); + index.Add(hash, new PackageEntry(hash, AccumulatedData, CompressedSize)); filenames.Add(FileName); AccumulatedData += CompressedSize; @@ -133,7 +133,7 @@ namespace OpenRA.FileSystem return index.ContainsKey(PackageEntry.HashFilename(filename, PackageHashType.Classic)); } - public int Priority { get { return 2000 + priority; }} + public int Priority { get { return 2000 + priority; } } public string Name { get { return filename; } } public void Write(Dictionary contents) diff --git a/OpenRA.Game/FileSystem/MixFile.cs b/OpenRA.Game/FileSystem/MixFile.cs index 484d309d4a..1872ee3297 100644 --- a/OpenRA.Game/FileSystem/MixFile.cs +++ b/OpenRA.Game/FileSystem/MixFile.cs @@ -68,9 +68,8 @@ namespace OpenRA.FileSystem entries = ParseHeader(s, isCncMix ? 0 : 4, out dataStart); index = entries.ToDictionaryWithConflictLog(x => x.Hash, - "{0} ({1} format, Encrypted: {2}, DataStart: {3})".F(filename, (isCncMix ? "C&C" : "RA/TS/RA2"), isEncrypted, dataStart), - null, x => "(offs={0}, len={1})".F(x.Offset, x.Length) - ); + "{0} ({1} format, Encrypted: {2}, DataStart: {3})".F(filename, isCncMix ? "C&C" : "RA/TS/RA2", isEncrypted, dataStart), + null, x => "(offs={0}, len={1})".F(x.Offset, x.Length)); } static List ParseHeader(Stream s, long offset, out long headerEnd) @@ -83,7 +82,7 @@ namespace OpenRA.FileSystem for (var i = 0; i < numFiles; i++) items.Add(new PackageEntry(s)); - headerEnd = offset + 6 + numFiles*PackageEntry.Size; + headerEnd = offset + 6 + numFiles * PackageEntry.Size; return items; } @@ -101,8 +100,8 @@ namespace OpenRA.FileSystem var numFiles = ms.ReadUInt16(); // Decrypt the full header - round bytes up to a full block - var blockCount = (13 + numFiles*PackageEntry.Size)/8; - headerEnd = offset + 80 + blockCount*8; + var blockCount = (13 + numFiles * PackageEntry.Size) / 8; + headerEnd = offset + 80 + blockCount * 8; return Decrypt(ReadBlocks(s, offset + 80, blockCount), fish); } @@ -113,7 +112,7 @@ namespace OpenRA.FileSystem var ms = new MemoryStream(); var writer = new BinaryWriter(ms); - foreach(var t in decrypted) + foreach (var t in decrypted) writer.Write(t); writer.Flush(); @@ -126,7 +125,7 @@ namespace OpenRA.FileSystem s.Seek(offset, SeekOrigin.Begin); // A block is a single encryption unit (represented as two 32-bit integers) - var ret = new uint[2*count]; + var ret = new uint[2 * count]; for (var i = 0; i < ret.Length; i++) ret[i] = s.ReadUInt32(); @@ -167,7 +166,7 @@ namespace OpenRA.FileSystem return hash.HasValue ? GetContent(hash.Value) : null; } - static readonly uint[] Nothing = {}; + static readonly uint[] Nothing = { }; public IEnumerable ClassicHashes() { if (type == PackageHashType.Classic) diff --git a/OpenRA.Game/FileSystem/PackageEntry.cs b/OpenRA.Game/FileSystem/PackageEntry.cs index 0c9f7180c8..737abe50ee 100644 --- a/OpenRA.Game/FileSystem/PackageEntry.cs +++ b/OpenRA.Game/FileSystem/PackageEntry.cs @@ -20,6 +20,7 @@ namespace OpenRA.FileSystem public class PackageEntry { + public const int Size = 12; public readonly uint Hash; public readonly uint Offset; public readonly uint Length; @@ -56,7 +57,7 @@ namespace OpenRA.FileSystem public static uint HashFilename(string name, PackageHashType type) { - switch(type) + switch (type) { case PackageHashType.Classic: { @@ -88,6 +89,7 @@ namespace OpenRA.FileSystem while (i-- != 0) name += name[a << 2]; } + return CRC32.Calculate(Encoding.ASCII.GetBytes(name)); } @@ -95,7 +97,7 @@ namespace OpenRA.FileSystem } } - static Dictionary Names = new Dictionary(); + static Dictionary Names = new Dictionary(); public static void AddStandardName(string s) { @@ -104,7 +106,5 @@ namespace OpenRA.FileSystem var crcHash = HashFilename(s, PackageHashType.CRC32); // TS Names.Add(crcHash, s); } - - public const int Size = 12; } } diff --git a/OpenRA.Game/Game.cs b/OpenRA.Game/Game.cs index 9c955565a2..83c0cdb333 100644 --- a/OpenRA.Game/Game.cs +++ b/OpenRA.Game/Game.cs @@ -27,6 +27,10 @@ namespace OpenRA { public static class Game { + public const int NetTickScale = 3; // 120 ms net tick for 40 ms local tick + public const int Timestep = 40; + public const int TimestepJankThreshold = 250; // Don't catch up for delays larger than 250ms + public static ModData modData; public static Settings Settings; public static ICursor Cursor; @@ -83,9 +87,6 @@ namespace OpenRA public static int RenderFrame = 0; public static int NetFrameNumber { get { return orderManager.NetFrameNumber; } } public static int LocalTick { get { return orderManager.LocalFrameNumber; } } - public const int NetTickScale = 3; // 120 ms net tick for 40 ms local tick - public const int Timestep = 40; - public const int TimestepJankThreshold = 250; // Don't catch up for delays larger than 250ms public static event Action OnRemoteDirectConnect = (a, b) => { }; public static event Action ConnectionStateChanged = _ => { }; @@ -148,6 +149,7 @@ namespace OpenRA orderManager.World = new World(map, orderManager, isShellmap); orderManager.World.Timestep = Timestep; } + if (worldRenderer != null) worldRenderer.Dispose(); worldRenderer = new WorldRenderer(orderManager.World); @@ -417,7 +419,7 @@ namespace OpenRA } var worldTimestep = world == null ? Timestep : world.Timestep; - var worldTickDelta = (tick - orderManager.LastTickTime); + var worldTickDelta = tick - orderManager.LastTickTime; if (worldTimestep != 0 && worldTickDelta >= worldTimestep) { using (new PerfSample("tick_time")) @@ -426,7 +428,6 @@ namespace OpenRA // If dt < TickJankThreshold then we should try and catch up by repeatedly ticking // If dt >= TickJankThreshold then we should accept the jank and progress at the normal rate // dt is rounded down to an integer tick count in order to preserve fractional tick components. - var integralTickTimestep = (worldTickDelta / worldTimestep) * worldTimestep; orderManager.LastTickTime += integralTickTimestep >= TimestepJankThreshold ? integralTickTimestep : worldTimestep; diff --git a/OpenRA.Game/GameInformation.cs b/OpenRA.Game/GameInformation.cs index 9776fd688b..08b40c3b30 100644 --- a/OpenRA.Game/GameInformation.cs +++ b/OpenRA.Game/GameInformation.cs @@ -21,6 +21,7 @@ namespace OpenRA public string MapUid; public string MapTitle; public DateTime StartTimeUtc; + // Game end timestamp (when the recoding stopped). public DateTime EndTimeUtc; @@ -78,7 +79,7 @@ namespace OpenRA nodes.Add(new MiniYamlNode("Root", FieldSaver.Save(this))); - for (var i=0; i public bool IsRandomSpawnPoint; - // // Information gathered at a later stage - // // The game outcome for this player public WinState Outcome; + // The time when this player won or lost the game public DateTime OutcomeTimestampUtc; } diff --git a/OpenRA.Game/GameRules/ActorInfo.cs b/OpenRA.Game/GameRules/ActorInfo.cs index 191877b85f..593c279031 100644 --- a/OpenRA.Game/GameRules/ActorInfo.cs +++ b/OpenRA.Game/GameRules/ActorInfo.cs @@ -16,7 +16,7 @@ using OpenRA.Traits; namespace OpenRA { - //TODO: This is not exported into the documentation yet. + // TODO: This is not exported into the documentation yet. [Desc("A unit/building inside the game. Every rules starts with one and adds trait to it.", "Special actors like world or player are usually defined in system.yaml and affect everything.")] public class ActorInfo @@ -29,7 +29,7 @@ namespace OpenRA public readonly TypeDictionary Traits = new TypeDictionary(); List constructOrderCache = null; - public ActorInfo( string name, MiniYaml node, Dictionary allUnits ) + public ActorInfo(string name, MiniYaml node, Dictionary allUnits) { try { @@ -46,15 +46,15 @@ namespace OpenRA } } - static MiniYaml GetParent( MiniYaml node, Dictionary allUnits ) + static MiniYaml GetParent(MiniYaml node, Dictionary allUnits) { MiniYaml inherits; - node.ToDictionary().TryGetValue( "Inherits", out inherits ); - if( inherits == null || string.IsNullOrEmpty( inherits.Value ) ) + node.ToDictionary().TryGetValue("Inherits", out inherits); + if (inherits == null || string.IsNullOrEmpty(inherits.Value)) return null; MiniYaml parent; - allUnits.TryGetValue( inherits.Value, out parent ); + allUnits.TryGetValue(inherits.Value, out parent); if (parent == null) throw new InvalidOperationException( "Bogus inheritance -- actor type {0} does not exist".F(inherits.Value)); @@ -62,9 +62,9 @@ namespace OpenRA return parent; } - static MiniYaml MergeWithParent( MiniYaml node, Dictionary allUnits ) + static MiniYaml MergeWithParent(MiniYaml node, Dictionary allUnits) { - var parent = GetParent( node, allUnits ); + var parent = GetParent(node, allUnits); if (parent != null) { var result = MiniYaml.MergeStrict(node, MergeWithParent(parent, allUnits)); @@ -73,6 +73,7 @@ namespace OpenRA result.Nodes.RemoveAll(a => a.Key.StartsWith("-")); return result; } + return node; } @@ -101,7 +102,7 @@ namespace OpenRA var unresolved = source.Except(resolved); var testResolve = new Func((a, b) => a == b || a.IsAssignableFrom(b)); - var more = unresolved.Where(u => u.Dependencies.All( d => resolved.Exists(r => testResolve(d, r.Type)) )); + var more = unresolved.Where(u => u.Dependencies.All(d => resolved.Exists(r => testResolve(d, r.Type)))); // Re-evaluate the vars above until sorted while (more.Any()) @@ -146,11 +147,11 @@ namespace OpenRA .Where(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(UsesInit<>)) .Select(i => i.GetGenericArguments()[0])).ToList(); - inits.Add( typeof(OwnerInit) ); /* not exposed by a trait; this is used by the Actor itself */ + inits.Add(typeof(OwnerInit)); /* not exposed by a trait; this is used by the Actor itself */ return inits.Select( i => Pair.New( - i.Name.Replace( "Init", "" ), i )); + i.Name.Replace("Init", ""), i)); } } } diff --git a/OpenRA.Game/GameRules/MusicInfo.cs b/OpenRA.Game/GameRules/MusicInfo.cs index 3d5d0e70b1..4419d94c6e 100644 --- a/OpenRA.Game/GameRules/MusicInfo.cs +++ b/OpenRA.Game/GameRules/MusicInfo.cs @@ -20,13 +20,13 @@ namespace OpenRA.GameRules public int Length { get; private set; } // seconds public bool Exists { get; private set; } - public MusicInfo( string key, MiniYaml value ) + public MusicInfo(string key, MiniYaml value) { Title = value.Value; var nd = value.ToDictionary(); var ext = nd.ContainsKey("Extension") ? nd["Extension"].Value : "aud"; - Filename = (nd.ContainsKey("Filename") ? nd["Filename"].Value : key)+"."+ext; + Filename = (nd.ContainsKey("Filename") ? nd["Filename"].Value : key) + "." + ext; if (!GlobalFileSystem.Exists(Filename)) return; diff --git a/OpenRA.Game/GameRules/SoundInfo.cs b/OpenRA.Game/GameRules/SoundInfo.cs index 4f51833201..68d42ca369 100644 --- a/OpenRA.Game/GameRules/SoundInfo.cs +++ b/OpenRA.Game/GameRules/SoundInfo.cs @@ -16,12 +16,12 @@ namespace OpenRA.GameRules { public class SoundInfo { - [FieldLoader.Ignore] public readonly Dictionary Variants; - [FieldLoader.Ignore] public readonly Dictionary Prefixes; - [FieldLoader.Ignore] public readonly Dictionary Voices; - [FieldLoader.Ignore] public readonly Dictionary Notifications; - public readonly string DefaultVariant = ".aud" ; - public readonly string DefaultPrefix = "" ; + [FieldLoader.Ignore] public readonly Dictionary Variants; + [FieldLoader.Ignore] public readonly Dictionary Prefixes; + [FieldLoader.Ignore] public readonly Dictionary Voices; + [FieldLoader.Ignore] public readonly Dictionary Notifications; + public readonly string DefaultVariant = ".aud"; + public readonly string DefaultPrefix = ""; public readonly string[] DisableVariants = { }; public readonly string[] DisablePrefixes = { }; @@ -36,16 +36,16 @@ namespace OpenRA.GameRules public readonly Lazy> VoicePools; public readonly Lazy> NotificationsPools; - public SoundInfo( MiniYaml y ) + public SoundInfo(MiniYaml y) { - FieldLoader.Load( this, y ); + FieldLoader.Load(this, y); Variants = Load(y, "Variants"); Prefixes = Load(y, "Prefixes"); Voices = Load(y, "Voices"); Notifications = Load(y, "Notifications"); VoicePools = Exts.Lazy(() => Voices.ToDictionary(a => a.Key, a => new SoundPool(a.Value))); - NotificationsPools = Exts.Lazy(() => Notifications.ToDictionary( a => a.Key, a => new SoundPool(a.Value) )); + NotificationsPools = Exts.Lazy(() => Notifications.ToDictionary(a => a.Key, a => new SoundPool(a.Value))); } } diff --git a/OpenRA.Game/GameRules/Warhead.cs b/OpenRA.Game/GameRules/Warhead.cs index 95316875ea..84a0ed9c34 100644 --- a/OpenRA.Game/GameRules/Warhead.cs +++ b/OpenRA.Game/GameRules/Warhead.cs @@ -30,13 +30,13 @@ namespace OpenRA.GameRules [Desc("Can this warhead affect the actor that fired it.")] public readonly bool AffectsParent = false; - [Desc("Delay in ticks before applying the warhead effect.","0 = instant (old model).")] + [Desc("Delay in ticks before applying the warhead effect.", "0 = instant (old model).")] public readonly int Delay = 0; - ///Applies the warhead's effect against the target. + /// Applies the warhead's effect against the target. public abstract void DoImpact(Target target, Actor firedBy, IEnumerable damageModifiers); - ///Checks if the warhead is valid against (can do something to) the target. + /// Checks if the warhead is valid against (can do something to) the target. public bool IsValidAgainst(Target target, World world, Actor firedBy) { if (target.Type == TargetType.Actor) @@ -66,7 +66,7 @@ namespace OpenRA.GameRules // assumption has been removed from the yaml definitions public virtual bool CanTargetActor(ActorInfo victim, Actor firedBy) { return false; } - ///Checks if the warhead is valid against (can do something to) the actor. + /// Checks if the warhead is valid against (can do something to) the actor. public bool IsValidAgainst(Actor victim, Actor firedBy) { if (!CanTargetActor(victim.Info, firedBy)) @@ -88,7 +88,7 @@ namespace OpenRA.GameRules return true; } - ///Checks if the warhead is valid against (can do something to) the frozen actor. + /// Checks if the warhead is valid against (can do something to) the frozen actor. public bool IsValidAgainst(FrozenActor victim, Actor firedBy) { if (!CanTargetActor(victim.Info, firedBy)) diff --git a/OpenRA.Game/Graphics/Animation.cs b/OpenRA.Game/Graphics/Animation.cs index 25b97440eb..2811a211f1 100644 --- a/OpenRA.Game/Graphics/Animation.cs +++ b/OpenRA.Game/Graphics/Animation.cs @@ -15,6 +15,7 @@ namespace OpenRA.Graphics { public class Animation { + readonly int defaultTick = 40; // 25 fps == 40 ms public Sequence CurrentSequence { get; private set; } public bool IsDecoration = false; public Func Paused; @@ -26,7 +27,6 @@ namespace OpenRA.Graphics string name; - readonly int defaultTick = 40; // 25 fps == 40 ms bool tickAlways; public string Name { get { return name; } } @@ -43,7 +43,7 @@ namespace OpenRA.Graphics { this.sequenceProvider = sequenceProvider; this.name = name.ToLowerInvariant(); - this.tickFunc = () => {}; + this.tickFunc = () => { }; this.facingFunc = facingFunc; } diff --git a/OpenRA.Game/Graphics/AnimationWithOffset.cs b/OpenRA.Game/Graphics/AnimationWithOffset.cs index 79582fb69e..7f818b79ac 100644 --- a/OpenRA.Game/Graphics/AnimationWithOffset.cs +++ b/OpenRA.Game/Graphics/AnimationWithOffset.cs @@ -50,5 +50,4 @@ namespace OpenRA.Graphics return new AnimationWithOffset(a, null, null, null, null); } } -} - +} \ No newline at end of file diff --git a/OpenRA.Game/Graphics/LineRenderer.cs b/OpenRA.Game/Graphics/LineRenderer.cs index f7c3ff79ec..8b8b2dd98c 100644 --- a/OpenRA.Game/Graphics/LineRenderer.cs +++ b/OpenRA.Game/Graphics/LineRenderer.cs @@ -38,6 +38,7 @@ namespace OpenRA.Graphics { return lineWidth; } + set { if (LineWidth != value) diff --git a/OpenRA.Game/Graphics/MappedImage.cs b/OpenRA.Game/Graphics/MappedImage.cs index 840ccf85b9..46114bde51 100644 --- a/OpenRA.Game/Graphics/MappedImage.cs +++ b/OpenRA.Game/Graphics/MappedImage.cs @@ -37,7 +37,7 @@ namespace OpenRA.Graphics if (defaultSrc != src) root.Add(new MiniYamlNode("src", src)); - return new MiniYaml(FieldSaver.FormatValue( this, this.GetType().GetField("rect") ), root); + return new MiniYaml(FieldSaver.FormatValue(this, this.GetType().GetField("rect")), root); } } } diff --git a/OpenRA.Game/Graphics/Palette.cs b/OpenRA.Game/Graphics/Palette.cs index 61bf3c0257..6cb21d17fd 100644 --- a/OpenRA.Game/Graphics/Palette.cs +++ b/OpenRA.Game/Graphics/Palette.cs @@ -23,6 +23,7 @@ namespace OpenRA.Graphics uint this[int index] { get; } void CopyToArray(Array destination, int destinationOffset); } + public interface IPaletteRemap { Color GetRemappedColor(Color original, int index); } public static class Palette diff --git a/OpenRA.Game/Graphics/Renderable.cs b/OpenRA.Game/Graphics/Renderable.cs index 2ac4f9cb70..6143a90637 100644 --- a/OpenRA.Game/Graphics/Renderable.cs +++ b/OpenRA.Game/Graphics/Renderable.cs @@ -87,13 +87,13 @@ namespace OpenRA.Graphics float2 ScreenPosition(WorldRenderer wr) { - return wr.ScreenPxPosition(pos) + wr.ScreenPxOffset(offset) - (0.5f*scale*sprite.size).ToInt2(); + return wr.ScreenPxPosition(pos) + wr.ScreenPxOffset(offset) - (0.5f * scale * sprite.size).ToInt2(); } - public void BeforeRender(WorldRenderer wr) {} + public void BeforeRender(WorldRenderer wr) { } public void Render(WorldRenderer wr) { - Game.Renderer.WorldSpriteRenderer.DrawSprite(sprite, ScreenPosition(wr), palette, sprite.size*scale); + Game.Renderer.WorldSpriteRenderer.DrawSprite(sprite, ScreenPosition(wr), palette, sprite.size * scale); } public void RenderDebugGeometry(WorldRenderer wr) diff --git a/OpenRA.Game/Graphics/Renderer.cs b/OpenRA.Game/Graphics/Renderer.cs index c99cd38d94..b90574a7b1 100644 --- a/OpenRA.Game/Graphics/Renderer.cs +++ b/OpenRA.Game/Graphics/Renderer.cs @@ -177,6 +177,7 @@ namespace OpenRA.Graphics { return currentBatchRenderer; } + set { if (currentBatchRenderer == value) diff --git a/OpenRA.Game/Graphics/SelectionBarsRenderable.cs b/OpenRA.Game/Graphics/SelectionBarsRenderable.cs index 647a9815ca..ed447cbfa5 100644 --- a/OpenRA.Game/Graphics/SelectionBarsRenderable.cs +++ b/OpenRA.Game/Graphics/SelectionBarsRenderable.cs @@ -135,7 +135,7 @@ namespace OpenRA.Graphics } } - public void BeforeRender(WorldRenderer wr) {} + public void BeforeRender(WorldRenderer wr) { } public void Render(WorldRenderer wr) { if (!actor.IsInWorld || actor.IsDead) @@ -154,6 +154,6 @@ namespace OpenRA.Graphics DrawExtraBars(wr, xy, Xy); } - public void RenderDebugGeometry(WorldRenderer wr) {} + public void RenderDebugGeometry(WorldRenderer wr) { } } } diff --git a/OpenRA.Game/Graphics/SelectionBoxRenderable.cs b/OpenRA.Game/Graphics/SelectionBoxRenderable.cs index 9cf4f63cf1..6cbe2528c3 100644 --- a/OpenRA.Game/Graphics/SelectionBoxRenderable.cs +++ b/OpenRA.Game/Graphics/SelectionBoxRenderable.cs @@ -45,7 +45,7 @@ namespace OpenRA.Graphics public IRenderable OffsetBy(WVec vec) { return new SelectionBoxRenderable(pos + vec, bounds, scale, color); } public IRenderable AsDecoration() { return this; } - public void BeforeRender(WorldRenderer wr) {} + public void BeforeRender(WorldRenderer wr) { } public void Render(WorldRenderer wr) { var screenPos = wr.ScreenPxPosition(pos); @@ -68,6 +68,6 @@ namespace OpenRA.Graphics wlr.DrawLine(br, br - v, color, color); } - public void RenderDebugGeometry(WorldRenderer wr) {} + public void RenderDebugGeometry(WorldRenderer wr) { } } } diff --git a/OpenRA.Game/Graphics/Sheet.cs b/OpenRA.Game/Graphics/Sheet.cs index a04db289c7..163af2a5cc 100644 --- a/OpenRA.Game/Graphics/Sheet.cs +++ b/OpenRA.Game/Graphics/Sheet.cs @@ -30,6 +30,7 @@ namespace OpenRA.Graphics CreateBuffer(); return data; } + public bool Buffered { get { return data != null || texture == null; } } public Sheet(Size size) @@ -83,7 +84,6 @@ namespace OpenRA.Graphics if (data != null) { - if (dirty) { texture.SetData(data, Size.Width, Size.Height); diff --git a/OpenRA.Game/Graphics/SoftwareCursor.cs b/OpenRA.Game/Graphics/SoftwareCursor.cs index cbff0c227f..ef022f5fce 100644 --- a/OpenRA.Game/Graphics/SoftwareCursor.cs +++ b/OpenRA.Game/Graphics/SoftwareCursor.cs @@ -99,4 +99,3 @@ namespace OpenRA.Graphics } } } - diff --git a/OpenRA.Game/Graphics/Sprite.cs b/OpenRA.Game/Graphics/Sprite.cs index a022ea4ea2..4cb04745d2 100644 --- a/OpenRA.Game/Graphics/Sprite.cs +++ b/OpenRA.Game/Graphics/Sprite.cs @@ -24,10 +24,10 @@ namespace OpenRA.Graphics public readonly float top, left, bottom, right; public Sprite(Sheet sheet, Rectangle bounds, TextureChannel channel) - : this(sheet, bounds, float2.Zero, channel, BlendMode.Alpha) {} + : this(sheet, bounds, float2.Zero, channel, BlendMode.Alpha) { } public Sprite(Sheet sheet, Rectangle bounds, TextureChannel channel, BlendMode blendMode) - : this(sheet, bounds, float2.Zero, channel, blendMode) {} + : this(sheet, bounds, float2.Zero, channel, blendMode) { } public Sprite(Sheet sheet, Rectangle bounds, float2 offset, TextureChannel channel, BlendMode blendMode) { @@ -40,10 +40,10 @@ namespace OpenRA.Graphics this.fractionalOffset = offset / this.size; - left = (float)(bounds.Left) / sheet.Size.Width; - top = (float)(bounds.Top) / sheet.Size.Height; - right = (float)(bounds.Right) / sheet.Size.Width; - bottom = (float)(bounds.Bottom) / sheet.Size.Height; + left = (float)bounds.Left / sheet.Size.Width; + top = (float)bounds.Top / sheet.Size.Height; + right = (float)bounds.Right / sheet.Size.Width; + bottom = (float)bounds.Bottom / sheet.Size.Height; } } diff --git a/OpenRA.Game/Graphics/SpriteFont.cs b/OpenRA.Game/Graphics/SpriteFont.cs index cf477d66a3..df34fe72a1 100644 --- a/OpenRA.Game/Graphics/SpriteFont.cs +++ b/OpenRA.Game/Graphics/SpriteFont.cs @@ -136,7 +136,6 @@ namespace OpenRA.Graphics } } - s.sheet.CommitData(); return g; diff --git a/OpenRA.Game/Graphics/SpriteLoader.cs b/OpenRA.Game/Graphics/SpriteLoader.cs index ca0aecb36c..85339c2de5 100644 --- a/OpenRA.Game/Graphics/SpriteLoader.cs +++ b/OpenRA.Game/Graphics/SpriteLoader.cs @@ -38,6 +38,7 @@ namespace OpenRA.Graphics public SpriteCache(ISpriteLoader[] loaders, string[] exts, SheetBuilder sheetBuilder) { SheetBuilder = sheetBuilder; + // Include extension-less version exts = exts.Append("").ToArray(); sprites = new Cache(filename => SpriteLoader.GetSprites(filename, exts, loaders, sheetBuilder)); diff --git a/OpenRA.Game/Graphics/TargetLineRenderable.cs b/OpenRA.Game/Graphics/TargetLineRenderable.cs index c00d0221b2..45ecb768e9 100644 --- a/OpenRA.Game/Graphics/TargetLineRenderable.cs +++ b/OpenRA.Game/Graphics/TargetLineRenderable.cs @@ -39,7 +39,7 @@ namespace OpenRA.Graphics public IRenderable OffsetBy(WVec vec) { return new TargetLineRenderable(waypoints.Select(w => w + vec), color); } public IRenderable AsDecoration() { return this; } - public void BeforeRender(WorldRenderer wr) {} + public void BeforeRender(WorldRenderer wr) { } public void Render(WorldRenderer wr) { if (!waypoints.Any()) @@ -57,6 +57,6 @@ namespace OpenRA.Graphics wr.DrawTargetMarker(color, first); } - public void RenderDebugGeometry(WorldRenderer wr) {} + public void RenderDebugGeometry(WorldRenderer wr) { } } } diff --git a/OpenRA.Game/Graphics/UISpriteRenderable.cs b/OpenRA.Game/Graphics/UISpriteRenderable.cs index 5ff496b023..0b43b81a4d 100644 --- a/OpenRA.Game/Graphics/UISpriteRenderable.cs +++ b/OpenRA.Game/Graphics/UISpriteRenderable.cs @@ -46,7 +46,7 @@ namespace OpenRA.Graphics public IRenderable OffsetBy(WVec vec) { return this; } public IRenderable AsDecoration() { return this; } - public void BeforeRender(WorldRenderer wr) {} + public void BeforeRender(WorldRenderer wr) { } public void Render(WorldRenderer wr) { Game.Renderer.SpriteRenderer.DrawSprite(sprite, screenPos, palette, sprite.size * scale); diff --git a/OpenRA.Game/Graphics/Util.cs b/OpenRA.Game/Graphics/Util.cs index 7dcf6cfc73..0671b9c778 100644 --- a/OpenRA.Game/Graphics/Util.cs +++ b/OpenRA.Game/Graphics/Util.cs @@ -17,6 +17,8 @@ namespace OpenRA.Graphics { public static class Util { + // yes, our channel order is nuts. + static readonly int[] channelMasks = { 2, 1, 0, 3 }; static float[] channelSelect = { 0.75f, 0.25f, -0.25f, -0.75f }; public static void FastCreateQuad(Vertex[] vertices, float2 o, Sprite r, int palette, int nv, float2 size) @@ -38,8 +40,6 @@ namespace OpenRA.Graphics vertices[nv + 3] = new Vertex(d, r.left, r.bottom, attribP, attribC); } - static readonly int[] channelMasks = { 2, 1, 0, 3 }; // yes, our channel order is nuts. - public static void FastCopyIntoChannel(Sprite dest, byte[] src) { FastCopyIntoChannel(dest, 0, src); } public static void FastCopyIntoChannel(Sprite dest, int channelOffset, byte[] src) { @@ -58,6 +58,7 @@ namespace OpenRA.Graphics data[destOffset] = src[srcOffset]; destOffset += 4; } + destOffset += destSkip; } } @@ -107,9 +108,9 @@ namespace OpenRA.Graphics for (var i = 0; i < 4; i++) for (var j = 0; j < 4; j++) { - mtx[4*i + j] = 0; + mtx[4 * i + j] = 0; 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; @@ -122,7 +123,7 @@ namespace OpenRA.Graphics { ret[j] = 0; for (var k = 0; k < 4; k++) - ret[j] += mtx[4*k + j]*vec[k]; + ret[j] += mtx[4 * k + j] * vec[k]; } return ret; @@ -132,124 +133,124 @@ namespace OpenRA.Graphics { var mtx = new float[16]; - mtx[0] = m[5]*m[10]*m[15] - - m[5]*m[11]*m[14] - - m[9]*m[6]*m[15] + - m[9]*m[7]*m[14] + - m[13]*m[6]*m[11] - - m[13]*m[7]*m[10]; + mtx[0] = m[5] * m[10] * m[15] - + m[5] * m[11] * m[14] - + m[9] * m[6] * m[15] + + m[9] * m[7] * m[14] + + m[13] * m[6] * m[11] - + m[13] * m[7] * m[10]; - mtx[4] = -m[4]*m[10]*m[15] + - m[4]*m[11]*m[14] + - m[8]*m[6]*m[15] - - m[8]*m[7]*m[14] - - m[12]*m[6]*m[11] + - m[12]*m[7]*m[10]; + mtx[4] = -m[4] * m[10] * m[15] + + m[4] * m[11] * m[14] + + m[8] * m[6] * m[15] - + m[8] * m[7] * m[14] - + m[12] * m[6] * m[11] + + m[12] * m[7] * m[10]; - mtx[8] = m[4]*m[9]*m[15] - - m[4]*m[11]*m[13] - - m[8]*m[5]*m[15] + - m[8]*m[7]*m[13] + - m[12]*m[5]*m[11] - - m[12]*m[7]*m[9]; + mtx[8] = m[4] * m[9] * m[15] - + m[4] * m[11] * m[13] - + m[8] * m[5] * m[15] + + m[8] * m[7] * m[13] + + m[12] * m[5] * m[11] - + m[12] * m[7] * m[9]; - mtx[12] = -m[4]*m[9]*m[14] + - m[4]*m[10]*m[13] + - m[8]*m[5]*m[14] - - m[8]*m[6]*m[13] - - m[12]*m[5]*m[10] + - m[12]*m[6]*m[9]; + mtx[12] = -m[4] * m[9] * m[14] + + m[4] * m[10] * m[13] + + m[8] * m[5] * m[14] - + m[8] * m[6] * m[13] - + m[12] * m[5] * m[10] + + m[12] * m[6] * m[9]; - mtx[1] = -m[1]*m[10]*m[15] + - m[1]*m[11]*m[14] + - m[9]*m[2]*m[15] - - m[9]*m[3]*m[14] - - m[13]*m[2]*m[11] + - m[13]*m[3]*m[10]; + mtx[1] = -m[1] * m[10] * m[15] + + m[1] * m[11] * m[14] + + m[9] * m[2] * m[15] - + m[9] * m[3] * m[14] - + m[13] * m[2] * m[11] + + m[13] * m[3] * m[10]; - mtx[5] = m[0]*m[10]*m[15] - - m[0]*m[11]*m[14] - - m[8]*m[2]*m[15] + - m[8]*m[3]*m[14] + - m[12]*m[2]*m[11] - - m[12]*m[3]*m[10]; + mtx[5] = m[0] * m[10] * m[15] - + m[0] * m[11] * m[14] - + m[8] * m[2] * m[15] + + m[8] * m[3] * m[14] + + m[12] * m[2] * m[11] - + m[12] * m[3] * m[10]; - mtx[9] = -m[0]*m[9]*m[15] + - m[0]*m[11]*m[13] + - m[8]*m[1]*m[15] - - m[8]*m[3]*m[13] - - m[12]*m[1]*m[11] + - m[12]*m[3]*m[9]; + mtx[9] = -m[0] * m[9] * m[15] + + m[0] * m[11] * m[13] + + m[8] * m[1] * m[15] - + m[8] * m[3] * m[13] - + m[12] * m[1] * m[11] + + m[12] * m[3] * m[9]; - mtx[13] = m[0]*m[9]*m[14] - - m[0]*m[10]*m[13] - - m[8]*m[1]*m[14] + - m[8]*m[2]*m[13] + - m[12]*m[1]*m[10] - - m[12]*m[2]*m[9]; + mtx[13] = m[0] * m[9] * m[14] - + m[0] * m[10] * m[13] - + m[8] * m[1] * m[14] + + m[8] * m[2] * m[13] + + m[12] * m[1] * m[10] - + m[12] * m[2] * m[9]; - mtx[2] = m[1]*m[6]*m[15] - - m[1]*m[7]*m[14] - - m[5]*m[2]*m[15] + - m[5]*m[3]*m[14] + - m[13]*m[2]*m[7] - - m[13]*m[3]*m[6]; + mtx[2] = m[1] * m[6] * m[15] - + m[1] * m[7] * m[14] - + m[5] * m[2] * m[15] + + m[5] * m[3] * m[14] + + m[13] * m[2] * m[7] - + m[13] * m[3] * m[6]; - mtx[6] = -m[0]*m[6]*m[15] + - m[0]*m[7]*m[14] + - m[4]*m[2]*m[15] - - m[4]*m[3]*m[14] - - m[12]*m[2]*m[7] + - m[12]*m[3]*m[6]; + mtx[6] = -m[0] * m[6] * m[15] + + m[0] * m[7] * m[14] + + m[4] * m[2] * m[15] - + m[4] * m[3] * m[14] - + m[12] * m[2] * m[7] + + m[12] * m[3] * m[6]; - mtx[10] = m[0]*m[5]*m[15] - - m[0]*m[7]*m[13] - - m[4]*m[1]*m[15] + - m[4]*m[3]*m[13] + - m[12]*m[1]*m[7] - - m[12]*m[3]*m[5]; + mtx[10] = m[0] * m[5] * m[15] - + m[0] * m[7] * m[13] - + m[4] * m[1] * m[15] + + m[4] * m[3] * m[13] + + m[12] * m[1] * m[7] - + m[12] * m[3] * m[5]; - mtx[14] = -m[0]*m[5]*m[14] + - m[0]*m[6]*m[13] + - m[4]*m[1]*m[14] - - m[4]*m[2]*m[13] - - m[12]*m[1]*m[6] + - m[12]*m[2]*m[5]; + mtx[14] = -m[0] * m[5] * m[14] + + m[0] * m[6] * m[13] + + m[4] * m[1] * m[14] - + m[4] * m[2] * m[13] - + m[12] * m[1] * m[6] + + m[12] * m[2] * m[5]; - mtx[3] = -m[1]*m[6]*m[11] + - m[1]*m[7]*m[10] + - m[5]*m[2]*m[11] - - m[5]*m[3]*m[10] - - m[9]*m[2]*m[7] + - m[9]*m[3]*m[6]; + mtx[3] = -m[1] * m[6] * m[11] + + m[1] * m[7] * m[10] + + m[5] * m[2] * m[11] - + m[5] * m[3] * m[10] - + m[9] * m[2] * m[7] + + m[9] * m[3] * m[6]; - mtx[7] = m[0]*m[6]*m[11] - - m[0]*m[7]*m[10] - - m[4]*m[2]*m[11] + - m[4]*m[3]*m[10] + - m[8]*m[2]*m[7] - - m[8]*m[3]*m[6]; + mtx[7] = m[0] * m[6] * m[11] - + m[0] * m[7] * m[10] - + m[4] * m[2] * m[11] + + m[4] * m[3] * m[10] + + m[8] * m[2] * m[7] - + m[8] * m[3] * m[6]; - mtx[11] = -m[0]*m[5]*m[11] + - m[0]*m[7]*m[9] + - m[4]*m[1]*m[11] - - m[4]*m[3]*m[9] - - m[8]*m[1]*m[7] + - m[8]*m[3]*m[5]; + mtx[11] = -m[0] * m[5] * m[11] + + m[0] * m[7] * m[9] + + m[4] * m[1] * m[11] - + m[4] * m[3] * m[9] - + m[8] * m[1] * m[7] + + m[8] * m[3] * m[5]; - mtx[15] = m[0]*m[5]*m[10] - - m[0]*m[6]*m[9] - - m[4]*m[1]*m[10] + - m[4]*m[2]*m[9] + - m[8]*m[1]*m[6] - - m[8]*m[2]*m[5]; + mtx[15] = m[0] * m[5] * m[10] - + m[0] * m[6] * m[9] - + m[4] * m[1] * m[10] + + m[4] * m[2] * m[9] + + m[8] * m[1] * m[6] - + m[8] * m[2] * m[5]; - var det = m[0]*mtx[0] + m[1]*mtx[4] + m[2]*mtx[8] + m[3]*mtx[12]; + var det = m[0] * mtx[0] + m[1] * mtx[4] + m[2] * mtx[8] + m[3] * mtx[12]; if (det == 0) return null; for (var i = 0; i < 16; i++) - mtx[i] *= 1/det; + mtx[i] *= 1 / det; return mtx; } @@ -258,33 +259,33 @@ namespace OpenRA.Graphics { var fmtx = new float[16]; for (var i = 0; i < 16; i++) - fmtx[i] = imtx[i]*1f / imtx[15]; + fmtx[i] = imtx[i] * 1f / imtx[15]; return fmtx; } public static float[] MatrixAABBMultiply(float[] mtx, float[] bounds) { // Corner offsets - var ix = new uint[] {0,0,0,0,3,3,3,3}; - var iy = new uint[] {1,1,4,4,1,1,4,4}; - var iz = new uint[] {2,5,2,5,2,5,2,5}; + var ix = new uint[] { 0, 0, 0, 0, 3, 3, 3, 3 }; + var iy = new uint[] { 1, 1, 4, 4, 1, 1, 4, 4 }; + var iz = new uint[] { 2, 5, 2, 5, 2, 5, 2, 5 }; // Vectors to opposing corner - var ret = new float[] {float.MaxValue, float.MaxValue, float.MaxValue, - float.MinValue, float.MinValue, float.MinValue}; + var ret = new float[] { float.MaxValue, float.MaxValue, float.MaxValue, + float.MinValue, float.MinValue, float.MinValue }; // Transform vectors and find new bounding box for (var i = 0; i < 8; i++) { - var vec = new float[] {bounds[ix[i]], bounds[iy[i]], bounds[iz[i]], 1}; + var vec = new float[] { bounds[ix[i]], bounds[iy[i]], bounds[iz[i]], 1 }; var tvec = MatrixVectorMultiply(mtx, vec); - ret[0] = Math.Min(ret[0], tvec[0]/tvec[3]); - ret[1] = Math.Min(ret[1], tvec[1]/tvec[3]); - ret[2] = Math.Min(ret[2], tvec[2]/tvec[3]); - ret[3] = Math.Max(ret[3], tvec[0]/tvec[3]); - ret[4] = Math.Max(ret[4], tvec[1]/tvec[3]); - ret[5] = Math.Max(ret[5], tvec[2]/tvec[3]); + ret[0] = Math.Min(ret[0], tvec[0] / tvec[3]); + ret[1] = Math.Min(ret[1], tvec[1] / tvec[3]); + ret[2] = Math.Min(ret[2], tvec[2] / tvec[3]); + ret[3] = Math.Max(ret[3], tvec[0] / tvec[3]); + ret[4] = Math.Max(ret[4], tvec[1] / tvec[3]); + ret[5] = Math.Max(ret[5], tvec[2] / tvec[3]); } return ret; diff --git a/OpenRA.Game/Graphics/Voxel.cs b/OpenRA.Game/Graphics/Voxel.cs index 56b16946fa..a67904af42 100644 --- a/OpenRA.Game/Graphics/Voxel.cs +++ b/OpenRA.Game/Graphics/Voxel.cs @@ -61,12 +61,12 @@ namespace OpenRA.Graphics var l = limbData[limb]; var t = new float[16]; - Array.Copy(transforms, 16*(Limbs*frame + limb), t, 0, 16); + Array.Copy(transforms, 16 * (Limbs * frame + limb), t, 0, 16); // Fix limb position - t[12] *= l.Scale*(l.Bounds[3] - l.Bounds[0]) / l.Size[0]; - t[13] *= l.Scale*(l.Bounds[4] - l.Bounds[1]) / l.Size[1]; - t[14] *= l.Scale*(l.Bounds[5] - l.Bounds[2]) / l.Size[2]; + t[12] *= l.Scale * (l.Bounds[3] - l.Bounds[0]) / l.Size[0]; + t[13] *= l.Scale * (l.Bounds[4] - l.Bounds[1]) / l.Size[1]; + t[14] *= l.Scale * (l.Bounds[5] - l.Bounds[2]) / l.Size[2]; // Center, flip and scale t = Util.MatrixMultiply(t, Util.TranslationMatrix(l.Bounds[0], l.Bounds[1], l.Bounds[2])); @@ -84,8 +84,8 @@ namespace OpenRA.Graphics { get { - return limbData.Select(a => a.Size.Select(b => a.Scale*b).ToArray()) - .Aggregate((a,b) => new float[] + return limbData.Select(a => a.Size.Select(b => a.Scale * b).ToArray()) + .Aggregate((a, b) => new float[] { Math.Max(a[0], b[0]), Math.Max(a[1], b[1]), @@ -96,8 +96,8 @@ namespace OpenRA.Graphics public float[] Bounds(uint frame) { - var ret = new float[] {float.MaxValue,float.MaxValue,float.MaxValue, - float.MinValue,float.MinValue,float.MinValue}; + var ret = new float[] { float.MaxValue, float.MaxValue, float.MaxValue, + float.MinValue, float.MinValue, float.MinValue }; for (uint j = 0; j < Limbs; j++) { @@ -115,7 +115,7 @@ namespace OpenRA.Graphics for (var i = 0; i < 3; i++) { ret[i] = Math.Min(ret[i], bb[i]); - ret[i+3] = Math.Max(ret[i+3], bb[i+3]); + ret[i + 3] = Math.Max(ret[i + 3], bb[i + 3]); } } diff --git a/OpenRA.Game/Graphics/VoxelAnimation.cs b/OpenRA.Game/Graphics/VoxelAnimation.cs index 93f10a2ce4..448c823ce1 100644 --- a/OpenRA.Game/Graphics/VoxelAnimation.cs +++ b/OpenRA.Game/Graphics/VoxelAnimation.cs @@ -30,5 +30,4 @@ namespace OpenRA.Graphics FrameFunc = frame; } } -} - +} \ No newline at end of file diff --git a/OpenRA.Game/Graphics/VoxelLoader.cs b/OpenRA.Game/Graphics/VoxelLoader.cs index 506a5070da..41b259832a 100644 --- a/OpenRA.Game/Graphics/VoxelLoader.cs +++ b/OpenRA.Game/Graphics/VoxelLoader.cs @@ -93,7 +93,7 @@ namespace OpenRA.Graphics return new Vertex[4] { new Vertex(coord(0, 0), s.left, s.top, channelP, channelC), - new Vertex(coord(su, 0),s.right, s.top, channelP, channelC), + new Vertex(coord(su, 0), s.right, s.top, channelP, channelC), new Vertex(coord(su, sv), s.right, s.bottom, channelP, channelC), new Vertex(coord(0, sv), s.left, s.bottom, channelP, channelC) }; diff --git a/OpenRA.Game/Graphics/VoxelProvider.cs b/OpenRA.Game/Graphics/VoxelProvider.cs index 80123d141b..669a56d550 100644 --- a/OpenRA.Game/Graphics/VoxelProvider.cs +++ b/OpenRA.Game/Graphics/VoxelProvider.cs @@ -39,7 +39,7 @@ namespace OpenRA.Graphics var hva = unit; if (info.Value != null) { - var fields = info.Value.Split(new char[] {','}, StringSplitOptions.RemoveEmptyEntries); + var fields = info.Value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); if (fields.Length >= 1) vxl = hva = fields[0].Trim(); @@ -58,7 +58,7 @@ namespace OpenRA.Graphics var seq = sequences.ToDictionary(my => LoadVoxel(unit, my)); units.Add(unit, seq); } - catch (FileNotFoundException) {} // Do nothing; we can crash later if we actually wanted art + catch (FileNotFoundException) { } // Do nothing; we can crash later if we actually wanted art } public static Voxel GetVoxel(string unitName, string voxelName) diff --git a/OpenRA.Game/Graphics/WorldRenderer.cs b/OpenRA.Game/Graphics/WorldRenderer.cs index 89140b8406..c721172370 100644 --- a/OpenRA.Game/Graphics/WorldRenderer.cs +++ b/OpenRA.Game/Graphics/WorldRenderer.cs @@ -92,7 +92,7 @@ namespace OpenRA.Graphics if (world.OrderGenerator != null) effectRenderables = effectRenderables.Concat(world.OrderGenerator.RenderAfterWorld(this, world)); - // Iterating via foreach() copies the structs, so enumerate by index + // Iterating via foreach copies the structs, so enumerate by index var renderables = worldRenderables.Concat(effectRenderables).ToList(); Game.Renderer.WorldVoxelRenderer.BeginFrame(); diff --git a/OpenRA.Game/InstallUtils.cs b/OpenRA.Game/InstallUtils.cs index 95f89b0127..5406ea1025 100644 --- a/OpenRA.Game/InstallUtils.cs +++ b/OpenRA.Game/InstallUtils.cs @@ -23,11 +23,11 @@ namespace OpenRA public readonly string MenuWidget = null; public readonly string MusicMenuWidget = null; public readonly string BackgroundWidget = null; - public readonly string[] TestFiles = {}; - public readonly string[] DiskTestFiles = {}; + public readonly string[] TestFiles = { }; + public readonly string[] DiskTestFiles = { }; public readonly string PackageToExtractFromCD = null; - public readonly string[] ExtractFilesFromCD = {}; - public readonly string[] CopyFilesFromCD = {}; + public readonly string[] ExtractFilesFromCD = { }; + public readonly string[] CopyFilesFromCD = { }; public readonly string PackageMirrorList = null; @@ -153,4 +153,4 @@ namespace OpenRA z.Close(); } } -} \ No newline at end of file +} diff --git a/OpenRA.Game/Map/ActorReference.cs b/OpenRA.Game/Map/ActorReference.cs index eb6a38d00f..aa2ee3e578 100755 --- a/OpenRA.Game/Map/ActorReference.cs +++ b/OpenRA.Game/Map/ActorReference.cs @@ -22,9 +22,10 @@ namespace OpenRA { get { return initDict.Value; } } + Lazy initDict; - public ActorReference( string type ) : this(type, new Dictionary()) { } + public ActorReference(string type) : this(type, new Dictionary()) { } public ActorReference(string type, Dictionary inits) { @@ -53,6 +54,7 @@ namespace OpenRA var initName = init.GetType().Name; ret.Nodes.Add(new MiniYamlNode(initName.Substring(0, initName.Length - 4), FieldSaver.Save(init))); } + return ret; } diff --git a/OpenRA.Game/Map/Map.cs b/OpenRA.Game/Map/Map.cs index 70b3461117..32e5050f1b 100644 --- a/OpenRA.Game/Map/Map.cs +++ b/OpenRA.Game/Map/Map.cs @@ -113,6 +113,12 @@ namespace OpenRA public class Map { + public const int MaxTilesInCircleRange = 50; + public readonly TileShape TileShape; + [FieldLoader.Ignore] + public readonly WVec[] SubCellOffsets; + public readonly SubCell DefaultSubCell; + public readonly SubCell LastSubCell; [FieldLoader.Ignore] public IFolder Container; public string Path { get; private set; } @@ -131,12 +137,6 @@ namespace OpenRA public Bitmap CustomPreview; public bool InvalidCustomRules { get; private set; } - public readonly TileShape TileShape; - [FieldLoader.Ignore] - public readonly WVec[] SubCellOffsets; - public readonly SubCell DefaultSubCell; - public readonly SubCell LastSubCell; - public WVec OffsetOfSubCell(SubCell subCell) { return SubCellOffsets[(int)subCell]; } [FieldLoader.LoadUsing("LoadOptions")] @@ -207,14 +207,14 @@ namespace OpenRA var tileShape = Game.modData.Manifest.TileShape; var tileRef = new TerrainTile(tileset.Templates.First().Key, (byte)0); - var makeMapTiles = Exts.Lazy(() => + var makeMapTiles = Exts.Lazy(() => { var ret = new CellLayer(tileShape, size); ret.Clear(tileRef); return ret; }); - var makeMapHeight = Exts.Lazy(() => + var makeMapHeight = Exts.Lazy(() => { var ret = new CellLayer(tileShape, size); ret.Clear(0); @@ -421,12 +421,10 @@ namespace OpenRA root.Add(new MiniYamlNode("Options", FieldSaver.SaveDifferences(Options, new MapOptions()))); root.Add(new MiniYamlNode("Players", null, - Players.Select(p => new MiniYamlNode("PlayerReference@{0}".F(p.Key), FieldSaver.SaveDifferences(p.Value, new PlayerReference()))).ToList()) - ); + Players.Select(p => new MiniYamlNode("PlayerReference@{0}".F(p.Key), FieldSaver.SaveDifferences(p.Value, new PlayerReference()))).ToList())); root.Add(new MiniYamlNode("Actors", null, - Actors.Value.Select(x => new MiniYamlNode(x.Key, x.Value.Save())).ToList()) - ); + Actors.Value.Select(x => new MiniYamlNode(x.Key, x.Value.Save())).ToList())); root.Add(new MiniYamlNode("Smudges", MiniYaml.FromList(Smudges.Value))); root.Add(new MiniYamlNode("Rules", null, RuleDefinitions)); @@ -623,7 +621,6 @@ namespace OpenRA // (b) Therefore: // - ax + by adds (a - b) * 512 + 512 to u // - ax + by adds (a + b) * 512 + 512 to v - var z = Contains(cell) ? 512 * MapHeight.Value[cell] : 0; return new WPos(512 * (cell.X - cell.Y + 1), 512 * (cell.X + cell.Y + 1), z); } @@ -721,7 +718,6 @@ namespace OpenRA string ComputeHash() { // UID is calculated by taking an SHA1 of the yaml and binary data - using (var ms = new MemoryStream()) { // Read the relevant data into the buffer @@ -837,7 +833,7 @@ namespace OpenRA var edge = rand.Next(2) == 0; var x = isX ? rand.Next(Bounds.Left, Bounds.Right) : (edge ? Bounds.Left : Bounds.Right); - var y = !isX ? rand.Next(Bounds.Top, Bounds.Bottom) : (edge ? Bounds.Top : Bounds.Bottom); + var y = !isX ? rand.Next(Bounds.Top, Bounds.Bottom) : (edge ? Bounds.Top : Bounds.Bottom); return MapToCell(TileShape, new CPos(x, y)); } @@ -851,14 +847,13 @@ namespace OpenRA return new WRange(Math.Min(x, y) * dir.Length); } - public const int MaxTilesInCircleRange = 50; static CVec[][] TilesByDistance = InitTilesByDistance(MaxTilesInCircleRange); static CVec[][] InitTilesByDistance(int max) { var ts = new List[max + 1]; for (var i = 0; i < max + 1; i++) - ts [i] = new List(); + ts[i] = new List(); for (var j = -max; j <= max; j++) for (var i = -max; i <= max; i++) diff --git a/OpenRA.Game/Map/MapCache.cs b/OpenRA.Game/Map/MapCache.cs index b02adcdf8b..2330152b68 100644 --- a/OpenRA.Game/Map/MapCache.cs +++ b/OpenRA.Game/Map/MapCache.cs @@ -132,6 +132,7 @@ namespace OpenRA // Milliseconds to wait on one loop when nothing to do var emptyDelay = 50; + // Keep the thread alive for at least 5 seconds after the last minimap generation var maxKeepAlive = 5000 / emptyDelay; var keepAlive = maxKeepAlive; @@ -151,6 +152,7 @@ namespace OpenRA break; } } + if (todo.Count == 0) { Thread.Sleep(emptyDelay); @@ -170,6 +172,7 @@ namespace OpenRA createdPreview = true; bitmap = Minimap.RenderMapPreview(modData.DefaultRules.TileSets[p.Map.Tileset], p.Map, modData.DefaultRules, true); } + // Note: this is not generally thread-safe, but it works here because: // (a) This worker is the only thread writing to this sheet // (b) The main thread is the only thread reading this sheet @@ -192,7 +195,9 @@ namespace OpenRA Thread.Sleep(Environment.ProcessorCount == 1 ? 25 : 5); } } + sheetBuilder.Current.ReleaseBuffer(); + // The buffer is not fully reclaimed until changes are written out to the texture. // We will access the texture in order to force changes to be written out, allowing the buffer to be freed. Game.RunAfterTick(() => sheetBuilder.Current.GetTexture()); diff --git a/OpenRA.Game/Map/MapPreview.cs b/OpenRA.Game/Map/MapPreview.cs index 975b5efb09..b14b5ce111 100755 --- a/OpenRA.Game/Map/MapPreview.cs +++ b/OpenRA.Game/Map/MapPreview.cs @@ -36,7 +36,7 @@ namespace OpenRA public readonly string map_type; public readonly int players; public readonly Rectangle bounds; - public readonly int[] spawnpoints = {}; + public readonly int[] spawnpoints = { }; public readonly string minimap; public readonly bool downloading; } @@ -142,12 +142,12 @@ namespace OpenRA var spawns = new List(); for (var j = 0; j < r.spawnpoints.Length; j += 2) - spawns.Add(new CPos(r.spawnpoints[j], r.spawnpoints[j+1])); + spawns.Add(new CPos(r.spawnpoints[j], r.spawnpoints[j + 1])); SpawnPoints = spawns; CustomPreview = new Bitmap(new MemoryStream(Convert.FromBase64String(r.minimap))); } - catch (Exception) {} + catch (Exception) { } if (CustomPreview != null) cache.CacheMinimap(this); @@ -177,7 +177,6 @@ namespace OpenRA var mapUrl = Game.Settings.Game.MapRepository + Uid; try { - var request = WebRequest.Create(mapUrl); request.Method = "HEAD"; var res = request.GetResponse(); diff --git a/OpenRA.Game/MiniYaml.cs b/OpenRA.Game/MiniYaml.cs index 933af18c93..41493704a8 100755 --- a/OpenRA.Game/MiniYaml.cs +++ b/OpenRA.Game/MiniYaml.cs @@ -115,6 +115,7 @@ namespace OpenRA throw new InvalidDataException("Duplicate key '{0}' in {1}".F(y.Key, y.Location), ex); } } + return ret; } diff --git a/OpenRA.Game/ModData.cs b/OpenRA.Game/ModData.cs index 55ab4b1e12..eb457838e4 100644 --- a/OpenRA.Game/ModData.cs +++ b/OpenRA.Game/ModData.cs @@ -44,6 +44,7 @@ namespace OpenRA LoadScreen.Init(Manifest, Manifest.LoadScreen.ToDictionary(my => my.Value)); LoadScreen.Display(); } + WidgetLoader = new WidgetLoader(this); RulesetCache = new RulesetCache(this); RulesetCache.LoadingProgress += HandleLoadingProgress; diff --git a/OpenRA.Game/Network/SyncReport.cs b/OpenRA.Game/Network/SyncReport.cs index 20d244e265..732438fb18 100644 --- a/OpenRA.Game/Network/SyncReport.cs +++ b/OpenRA.Game/Network/SyncReport.cs @@ -198,6 +198,7 @@ namespace OpenRA.Network var boxedCopy = Expression.Convert(getMember, typeof(object)); return Expression.Lambda>(boxedCopy, name, new[] { syncParam }).Compile(); } + return MemberToString(getMember, memberType, name); } diff --git a/OpenRA.Game/Platform.cs b/OpenRA.Game/Platform.cs index 94ebf84b13..ec2904775a 100644 --- a/OpenRA.Game/Platform.cs +++ b/OpenRA.Game/Platform.cs @@ -126,6 +126,5 @@ namespace OpenRA return path; } - } } diff --git a/OpenRA.Game/Player.cs b/OpenRA.Game/Player.cs index db69894c3f..26cafa1e98 100644 --- a/OpenRA.Game/Player.cs +++ b/OpenRA.Game/Player.cs @@ -21,14 +21,12 @@ using OpenRA.Traits; namespace OpenRA { - public enum PowerState { Normal, Low, Critical }; - public enum WinState { Undefined, Won, Lost }; + public enum PowerState { Normal, Low, Critical } + public enum WinState { Undefined, Won, Lost } - public class Player : IScriptBindable, IScriptNotifyBind, ILuaTableBinding, ILuaEqualityBinding, ILuaToStringBinding + public class Player : IScriptBindable, IScriptNotifyBind, ILuaTableBinding, ILuaEqualityBinding, ILuaToStringBinding { - public Actor PlayerActor; - public WinState WinState = WinState.Undefined; - + public readonly Actor PlayerActor; public readonly HSLColor Color; public readonly string PlayerName; @@ -39,6 +37,8 @@ namespace OpenRA public readonly bool Playable = true; public readonly int ClientIndex; public readonly PlayerReference PlayerReference; + + public WinState WinState = WinState.Undefined; public bool IsBot; public int SpawnPoint; public bool HasObjectives = false; @@ -84,6 +84,7 @@ namespace OpenRA botType = pr.Bot; Country = ChooseCountry(world, pr.Race); } + PlayerActor = world.CreateActor("Player", new TypeDictionary { new OwnerInit(this) }); Shroud = PlayerActor.Trait(); @@ -138,7 +139,7 @@ namespace OpenRA set { luaInterface.Value[runtime, keyValue] = value; } } - public LuaValue Equals (LuaRuntime runtime, LuaValue left, LuaValue right) + public LuaValue Equals(LuaRuntime runtime, LuaValue left, LuaValue right) { Player a, b; if (!left.TryGetClrValue(out a) || !right.TryGetClrValue(out b)) diff --git a/OpenRA.Game/Primitives/ActionQueue.cs b/OpenRA.Game/Primitives/ActionQueue.cs index ef0899847b..293a65687d 100644 --- a/OpenRA.Game/Primitives/ActionQueue.cs +++ b/OpenRA.Game/Primitives/ActionQueue.cs @@ -29,7 +29,7 @@ namespace OpenRA.Primitives public void PerformActions() { - Action a = () => {}; + Action a = () => { }; lock (syncRoot) { var t = Game.RunTime; @@ -39,6 +39,7 @@ namespace OpenRA.Primitives a = da.Action + a; } } + a(); } } diff --git a/OpenRA.Game/Primitives/Bits.cs b/OpenRA.Game/Primitives/Bits.cs index 78f3848703..f1acd85668 100644 --- a/OpenRA.Game/Primitives/Bits.cs +++ b/OpenRA.Game/Primitives/Bits.cs @@ -32,16 +32,16 @@ namespace OpenRA.Primitives public static int GetValue(string[] val) { - return val.Select( a => bits[a] ).Aggregate( 0, (a,b) => a | b ); + return val.Select(a => bits[a]).Aggregate(0, (a, b) => a | b); } public static IEnumerable GetStrings(int val) { - for( var i = 0; i < 32; i++ ) + for (var i = 0; i < 32; i++) { var x = 1 << i; if ((val & x) != 0) - yield return bits.Single( a => a.Value == x ).Key; + yield return bits.Single(a => a.Value == x).Key; } } } @@ -58,7 +58,7 @@ namespace OpenRA.Primitives return BitAllocator.GetStrings(Value).JoinWith(","); } - public static bool operator ==(Bits me, Bits other) { return (me.Value == other.Value); } + public static bool operator ==(Bits me, Bits other) { return me.Value == other.Value; } public static bool operator !=(Bits me, Bits other) { return !(me == other); } public bool Equals(Bits other) { return other == this; } diff --git a/OpenRA.Game/Primitives/Cache.cs b/OpenRA.Game/Primitives/Cache.cs index 7191880127..df2615002f 100644 --- a/OpenRA.Game/Primitives/Cache.cs +++ b/OpenRA.Game/Primitives/Cache.cs @@ -40,6 +40,7 @@ namespace OpenRA.Primitives return result; } } + public bool ContainsKey(T key) { return cache.ContainsKey(key); } public bool TryGetValue(T key, out U value) { return cache.TryGetValue(key, out value); } public int Count { get { return cache.Count; } } diff --git a/OpenRA.Game/Primitives/ObservableCollection.cs b/OpenRA.Game/Primitives/ObservableCollection.cs index 3618b5f59f..6d533f3d3e 100644 --- a/OpenRA.Game/Primitives/ObservableCollection.cs +++ b/OpenRA.Game/Primitives/ObservableCollection.cs @@ -18,6 +18,7 @@ namespace OpenRA.Primitives public class ObservableCollection : Collection, IObservableCollection { public event Action OnAdd = k => { }; + // TODO Workaround for https://github.com/OpenRA/OpenRA/issues/6101 #pragma warning disable 67 public event Action OnRemove = k => { }; diff --git a/OpenRA.Game/Primitives/ObservableDictionary.cs b/OpenRA.Game/Primitives/ObservableDictionary.cs index 43ea498af7..0554e5c61f 100644 --- a/OpenRA.Game/Primitives/ObservableDictionary.cs +++ b/OpenRA.Game/Primitives/ObservableDictionary.cs @@ -34,6 +34,7 @@ namespace OpenRA.Primitives public event Action OnAdd = k => { }; public event Action OnRemove = k => { }; + // TODO Workaround for https://github.com/OpenRA/OpenRA/issues/6101 #pragma warning disable 67 public event Action OnRemoveAt = i => { }; diff --git a/OpenRA.Game/Primitives/Pair.cs b/OpenRA.Game/Primitives/Pair.cs index 529a5c43a2..0df1117e9e 100644 --- a/OpenRA.Game/Primitives/Pair.cs +++ b/OpenRA.Game/Primitives/Pair.cs @@ -74,7 +74,7 @@ namespace OpenRA.Primitives static Pair() { - Pair.uc = new ColorEqualityComparer(); + Pair.uc = new ColorEqualityComparer(); } // avoid the default crappy one diff --git a/OpenRA.Game/Primitives/PriorityQueue.cs b/OpenRA.Game/Primitives/PriorityQueue.cs index a163f8a376..3010c0ed42 100644 --- a/OpenRA.Game/Primitives/PriorityQueue.cs +++ b/OpenRA.Game/Primitives/PriorityQueue.cs @@ -46,7 +46,7 @@ namespace OpenRA.Primitives } } - public bool Empty { get { return (level == 0); } } + public bool Empty { get { return level == 0; } } T At(int level, int index) { return items[level][index]; } T Above(int level, int index) { return items[level - 1][index >> 1]; } @@ -62,7 +62,7 @@ namespace OpenRA.Primitives return At(lastLevel, lastIndex); } - public T Peek() { return At(0,0); } + public T Peek() { return At(0, 0); } public T Pop() { if (level == 0 && index == 0) diff --git a/OpenRA.Game/Primitives/TypeDictionary.cs b/OpenRA.Game/Primitives/TypeDictionary.cs index 622843581c..fc3d56ff86 100644 --- a/OpenRA.Game/Primitives/TypeDictionary.cs +++ b/OpenRA.Game/Primitives/TypeDictionary.cs @@ -20,30 +20,30 @@ namespace OpenRA.Primitives Dictionary dataSingular = new Dictionary(); Dictionary> dataMultiple = new Dictionary>(); - public void Add( object val ) + public void Add(object val) { var t = val.GetType(); - foreach( var i in t.GetInterfaces() ) - InnerAdd( i, val ); - foreach( var tt in t.BaseTypes() ) - InnerAdd( tt, val ); + foreach (var i in t.GetInterfaces()) + InnerAdd(i, val); + foreach (var tt in t.BaseTypes()) + InnerAdd(tt, val); } - void InnerAdd( Type t, object val ) + void InnerAdd(Type t, object val) { List objs; object obj; - if( dataMultiple.TryGetValue( t, out objs ) ) - objs.Add( val ); - else if( dataSingular.TryGetValue( t, out obj ) ) + if (dataMultiple.TryGetValue(t, out objs)) + objs.Add(val); + else if (dataSingular.TryGetValue(t, out obj)) { - dataSingular.Remove( t ); - dataMultiple.Add( t, new List { obj, val } ); + dataSingular.Remove(t); + dataMultiple.Add(t, new List { obj, val }); } else - dataSingular.Add( t, val ); + dataSingular.Add(t, val); } public bool Contains() @@ -83,12 +83,12 @@ namespace OpenRA.Primitives List objs; object obj; - if( dataMultiple.TryGetValue( typeof( T ), out objs ) ) + if (dataMultiple.TryGetValue(typeof(T), out objs)) return objs.Cast(); - else if( dataSingular.TryGetValue( typeof( T ), out obj ) ) + else if (dataSingular.TryGetValue(typeof(T), out obj)) return new T[] { (T)obj }; else - return new T[ 0 ]; + return new T[0]; } public IEnumerator GetEnumerator() @@ -99,9 +99,9 @@ namespace OpenRA.Primitives public static class TypeExts { - public static IEnumerable BaseTypes( this Type t ) + public static IEnumerable BaseTypes(this Type t) { - while( t != null ) + while (t != null) { yield return t; t = t.BaseType; diff --git a/OpenRA.Game/Primitives/float2.cs b/OpenRA.Game/Primitives/float2.cs index f035739cea..6f36768725 100644 --- a/OpenRA.Game/Primitives/float2.cs +++ b/OpenRA.Game/Primitives/float2.cs @@ -64,11 +64,11 @@ namespace OpenRA public static float2 operator *(float a, float2 b) { return new float2(a * b.X, a * b.Y); } public static float2 operator *(float2 b, float a) { return new float2(a * b.X, a * b.Y); } - public static float2 operator *( float2 a, float2 b ) { return new float2( a.X * b.X, a.Y * b.Y ); } - public static float2 operator /( float2 a, float2 b ) { return new float2( a.X / b.X, a.Y / b.Y ); } + public static float2 operator *(float2 a, float2 b) { return new float2(a.X * b.X, a.Y * b.Y); } + public static float2 operator /(float2 a, float2 b) { return new float2(a.X / b.X, a.Y / b.Y); } public static float2 operator /(float2 a, float b) { return new float2(a.X / b, a.Y / b); } - public static bool operator ==(float2 me, float2 other) { return (me.X == other.X && me.Y == other.Y); } + public static bool operator ==(float2 me, float2 other) { return me.X == other.X && me.Y == other.Y; } public static bool operator !=(float2 me, float2 other) { return !(me == other); } public override int GetHashCode() { return X.GetHashCode() ^ Y.GetHashCode(); } diff --git a/OpenRA.Game/Scripting/ScriptContext.cs b/OpenRA.Game/Scripting/ScriptContext.cs index 7bd03817b9..83ae4246d6 100644 --- a/OpenRA.Game/Scripting/ScriptContext.cs +++ b/OpenRA.Game/Scripting/ScriptContext.cs @@ -10,8 +10,8 @@ using System; using System.Collections.Generic; -using System.Drawing; using System.Diagnostics; +using System.Drawing; using System.IO; using System.Linq; using System.Reflection; diff --git a/OpenRA.Game/Scripting/ScriptMemberWrapper.cs b/OpenRA.Game/Scripting/ScriptMemberWrapper.cs index 09ca15a19f..a9a6891ab3 100644 --- a/OpenRA.Game/Scripting/ScriptMemberWrapper.cs +++ b/OpenRA.Game/Scripting/ScriptMemberWrapper.cs @@ -67,7 +67,7 @@ namespace OpenRA.Scripting throw new LuaException("Unable to convert parameter {0} to {1}".F(i, pi[i].ParameterType.Name)); } - var ret = (mi.Invoke(Target, clrArgs)); + var ret = mi.Invoke(Target, clrArgs); return ret.ToLuaValue(context); } diff --git a/OpenRA.Game/Scripting/ScriptTypes.cs b/OpenRA.Game/Scripting/ScriptTypes.cs index f388140e26..db4142998c 100644 --- a/OpenRA.Game/Scripting/ScriptTypes.cs +++ b/OpenRA.Game/Scripting/ScriptTypes.cs @@ -69,7 +69,7 @@ namespace OpenRA.Scripting // TODO: Lua 5.3 will introduce an integer type, so this will be able to go away if (value is LuaNumber && t.IsAssignableFrom(typeof(int))) { - clrObject = (int)(value.ToNumber().Value); + clrObject = (int)value.ToNumber().Value; return true; } diff --git a/OpenRA.Game/Selection.cs b/OpenRA.Game/Selection.cs index 135b04b4c3..2081047f78 100644 --- a/OpenRA.Game/Selection.cs +++ b/OpenRA.Game/Selection.cs @@ -64,8 +64,10 @@ namespace OpenRA actors.RemoveAll(a => !a.IsInWorld || (!a.Owner.IsAlliedWith(world.RenderPlayer) && world.FogObscures(a))); foreach (var cg in controlGroups.Values) + { // note: NOT `!a.IsInWorld`, since that would remove things that are in transports. cg.RemoveAll(a => a.Destroyed || a.Owner != world.LocalPlayer); + } } Cache> controlGroups = new Cache>(_ => new List()); diff --git a/OpenRA.Game/Server/Connection.cs b/OpenRA.Game/Server/Connection.cs index 79e4248380..4f56df5999 100644 --- a/OpenRA.Game/Server/Connection.cs +++ b/OpenRA.Game/Server/Connection.cs @@ -17,13 +17,13 @@ namespace OpenRA.Server { public class Connection { + public const int MaxOrderLength = 131072; public Socket socket; public List data = new List(); public ReceiveState State = ReceiveState.Header; public int ExpectLength = 8; public int Frame = 0; public int MostRecentFrame = 0; - public const int MaxOrderLength = 131072; public int TimeSinceLastResponse { get { return Game.RunTime - lastReceivedTime; } } public bool TimeoutMessageShown = false; @@ -44,7 +44,7 @@ namespace OpenRA.Server var rx = new byte[1024]; var len = 0; - for (; ; ) + for (;;) { try { @@ -107,12 +107,11 @@ namespace OpenRA.Server MostRecentFrame = Frame; ExpectLength = 8; State = ReceiveState.Header; - } break; } } } } - public enum ReceiveState { Header, Data }; + public enum ReceiveState { Header, Data } } diff --git a/OpenRA.Game/Support/Log.cs b/OpenRA.Game/Support/Log.cs index f68aa4aa4f..8a84dba0d1 100755 --- a/OpenRA.Game/Support/Log.cs +++ b/OpenRA.Game/Support/Log.cs @@ -29,7 +29,7 @@ namespace OpenRA var path = Platform.SupportDir + "Logs"; 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); } diff --git a/OpenRA.Game/Support/MersenneTwister.cs b/OpenRA.Game/Support/MersenneTwister.cs index 130ffd87e9..2f380d9263 100644 --- a/OpenRA.Game/Support/MersenneTwister.cs +++ b/OpenRA.Game/Support/MersenneTwister.cs @@ -35,9 +35,9 @@ namespace OpenRA.Support if (index == 0) Generate(); var y = mt[index]; - y ^= (y >> 11); - y ^= ((y << 7) & 2636928640); - y ^= ((y << 15) & 4022730752); + y ^= y >> 11; + y ^= (y << 7) & 2636928640; + y ^= (y << 15) & 4022730752; y ^= y >> 18; index = (index + 1) % 624; @@ -77,7 +77,7 @@ namespace OpenRA.Support var y = (mt[i] & 0x80000000) | (mt[(i + 1) % 624] & 0x7fffffff); mt[i] = mt[(i + 397u) % 624u] ^ (y >> 1); if ((y & 1) == 1) - mt[i] = (mt[i] ^ 2567483615); + mt[i] = mt[i] ^ 2567483615; } } } diff --git a/OpenRA.Game/Support/PerfHistory.cs b/OpenRA.Game/Support/PerfHistory.cs index fbdfb5d611..e7e89b4449 100644 --- a/OpenRA.Game/Support/PerfHistory.cs +++ b/OpenRA.Game/Support/PerfHistory.cs @@ -33,7 +33,7 @@ namespace OpenRA.Support return x; }); - public static void Increment( string item, double x ) + public static void Increment(string item, double x) { items[item].val += x; } @@ -91,6 +91,7 @@ namespace OpenRA.Support sum += samples[n]; i++; } + return sum / i; } diff --git a/OpenRA.Game/Support/PerfTimer.cs b/OpenRA.Game/Support/PerfTimer.cs index 1492c436d8..534721050d 100755 --- a/OpenRA.Game/Support/PerfTimer.cs +++ b/OpenRA.Game/Support/PerfTimer.cs @@ -18,6 +18,11 @@ namespace OpenRA.Support { public sealed class PerfTimer : IDisposable { + // Tree settings + const int Digits = 6; + const string IndentationString = "| "; + const string FormatSeperation = " ms "; + static readonly string FormatString = "{0," + Digits + ":0}" + FormatSeperation + "{1}"; readonly string name; readonly float thresholdMs; readonly byte depth; @@ -27,12 +32,6 @@ namespace OpenRA.Support static ThreadLocal Parent = new ThreadLocal(); - // Tree settings - const int Digits = 6; - const string IndentationString = "| "; - const string FormatSeperation = " ms "; - static readonly string FormatString = "{0," + Digits + ":0}" + FormatSeperation + "{1}"; - public PerfTimer(string name, float thresholdMs = 0) { this.name = name; diff --git a/OpenRA.Game/Support/Program.cs b/OpenRA.Game/Support/Program.cs index 542cf2cbb5..3105fc558d 100644 --- a/OpenRA.Game/Support/Program.cs +++ b/OpenRA.Game/Support/Program.cs @@ -86,8 +86,9 @@ namespace OpenRA Indent(sb, d); sb.AppendFormat("TypeName=`{0}`", tle.TypeName); } - else // TODO: more exception types + else { + // TODO: more exception types } if (e.InnerException != null) diff --git a/OpenRA.Game/Sync.cs b/OpenRA.Game/Sync.cs index 8188e49928..70679d7a39 100755 --- a/OpenRA.Game/Sync.cs +++ b/OpenRA.Game/Sync.cs @@ -33,18 +33,18 @@ namespace OpenRA static Dictionary hashFunctions = new Dictionary() { - {typeof(int2), ((Func)hash_int2).Method}, - {typeof(CPos), ((Func)hash_CPos).Method}, - {typeof(CVec), ((Func)hash_CVec).Method}, - {typeof(WRange), ((Func)hash).Method}, - {typeof(WPos), ((Func)hash).Method}, - {typeof(WVec), ((Func)hash).Method}, - {typeof(WAngle), ((Func)hash).Method}, - {typeof(WRot), ((Func)hash).Method}, - {typeof(TypeDictionary), ((Func)hash_tdict).Method}, - {typeof(Actor), ((Func)hash_actor).Method}, - {typeof(Player), ((Func)hash_player).Method}, - {typeof(Target), ((Func)hash_target).Method}, + { typeof(int2), ((Func)hash_int2).Method }, + { typeof(CPos), ((Func)hash_CPos).Method }, + { typeof(CVec), ((Func)hash_CVec).Method }, + { typeof(WRange), ((Func)hash).Method }, + { typeof(WPos), ((Func)hash).Method }, + { typeof(WVec), ((Func)hash).Method }, + { typeof(WAngle), ((Func)hash).Method }, + { typeof(WRot), ((Func)hash).Method }, + { typeof(TypeDictionary), ((Func)hash_tdict).Method }, + { typeof(Actor), ((Func)hash_actor).Method }, + { typeof(Player), ((Func)hash_player).Method }, + { typeof(Target), ((Func)hash_target).Method }, }; static void EmitSyncOpcodes(Type type, ILGenerator il) diff --git a/OpenRA.Game/TraitDictionary.cs b/OpenRA.Game/TraitDictionary.cs index eb055959c7..c6a7f270df 100755 --- a/OpenRA.Game/TraitDictionary.cs +++ b/OpenRA.Game/TraitDictionary.cs @@ -29,6 +29,7 @@ namespace OpenRA else end = mid; } + return start; } } @@ -187,6 +188,7 @@ namespace OpenRA this.actor = actor; Reset(); } + public void Reset() { index = actors.BinarySearchMany(actor) - 1; } public bool MoveNext() { return ++index < actors.Count && actors[index].ActorID == actor; } public T Current { get { return traits[index]; } } @@ -219,6 +221,7 @@ namespace OpenRA traits = container.traits; Reset(); } + public void Reset() { index = -1; } public bool MoveNext() { return ++index < actors.Count; } public TraitPair Current { get { return new TraitPair { Actor = actors[index], Trait = traits[index] }; } } diff --git a/OpenRA.Game/Traits/Armor.cs b/OpenRA.Game/Traits/Armor.cs index 3db6a0ab2f..5450565b50 100644 --- a/OpenRA.Game/Traits/Armor.cs +++ b/OpenRA.Game/Traits/Armor.cs @@ -16,6 +16,5 @@ namespace OpenRA.Traits public readonly string Type = null; } - public class Armor {} -} - + public class Armor { } +} \ No newline at end of file diff --git a/OpenRA.Game/Traits/DrawLineToTarget.cs b/OpenRA.Game/Traits/DrawLineToTarget.cs index 6f2bcf1717..3612b519ce 100644 --- a/OpenRA.Game/Traits/DrawLineToTarget.cs +++ b/OpenRA.Game/Traits/DrawLineToTarget.cs @@ -72,7 +72,7 @@ namespace OpenRA.Traits if (target.Type == TargetType.Invalid) continue; - yield return new TargetLineRenderable(new [] { self.CenterPosition, target.CenterPosition }, c); + yield return new TargetLineRenderable(new[] { self.CenterPosition, target.CenterPosition }, c); } } @@ -131,5 +131,4 @@ namespace OpenRA.Traits }); } } -} - +} \ No newline at end of file diff --git a/OpenRA.Game/Traits/Health.cs b/OpenRA.Game/Traits/Health.cs index 613544d431..f3bf03e9f1 100755 --- a/OpenRA.Game/Traits/Health.cs +++ b/OpenRA.Game/Traits/Health.cs @@ -27,7 +27,7 @@ namespace OpenRA.Traits public virtual object Create(ActorInitializer init) { return new Health(init, this); } } - public enum DamageState { Undamaged, Light, Medium, Heavy, Critical, Dead }; + public enum DamageState { Undamaged, Light, Medium, Heavy, Critical, Dead } public class Health : ISync, ITick { @@ -173,8 +173,8 @@ namespace OpenRA.Traits { [FieldFromYamlKey] public readonly float value = 1f; public HealthInit() { } - public HealthInit( float init ) { value = init; } - public float Value( World world ) { return value; } + public HealthInit(float init) { value = init; } + public float Value(World world) { return value; } } public static class HealthExts diff --git a/OpenRA.Game/Traits/Player/DeveloperMode.cs b/OpenRA.Game/Traits/Player/DeveloperMode.cs index af18664c41..22fbd0a348 100644 --- a/OpenRA.Game/Traits/Player/DeveloperMode.cs +++ b/OpenRA.Game/Traits/Player/DeveloperMode.cs @@ -63,7 +63,7 @@ namespace OpenRA.Traits if (!self.World.AllowDevCommands) return; - switch(order.OrderString) + switch (order.OrderString) { case "DevEnableTech": { @@ -97,6 +97,7 @@ namespace OpenRA.Traits for (var i = 0; i < Info.ResourceGrowth; i++) a.Trait.Seed(a.Actor); } + break; } diff --git a/OpenRA.Game/Traits/Player/PlayerResources.cs b/OpenRA.Game/Traits/Player/PlayerResources.cs index 26f70b2ea8..066011c47c 100644 --- a/OpenRA.Game/Traits/Player/PlayerResources.cs +++ b/OpenRA.Game/Traits/Player/PlayerResources.cs @@ -24,6 +24,8 @@ namespace OpenRA.Traits public class PlayerResources : ITick, ISync { + const float displayCashFracPerFrame = .07f; + const int displayCashDeltaPerFrame = 37; readonly Player Owner; int AdviceInterval; @@ -97,8 +99,6 @@ namespace OpenRA.Traits return true; } - const float displayCashFracPerFrame = .07f; - const int displayCashDeltaPerFrame = 37; int nextSiloAdviceTime = 0; int nextCashTickTime = 0; @@ -130,8 +130,7 @@ namespace OpenRA.Traits var diff = Math.Abs(Cash - DisplayCash); var move = Math.Min(Math.Max((int)(diff * displayCashFracPerFrame), displayCashDeltaPerFrame), diff); - - + if (DisplayCash < Cash) { DisplayCash += move; @@ -159,7 +158,6 @@ namespace OpenRA.Traits } } - public void playCashTickUp(Actor self) { if (Game.Settings.Sound.CashTicks) diff --git a/OpenRA.Game/Traits/SelectionDecorations.cs b/OpenRA.Game/Traits/SelectionDecorations.cs index 3f29190ddf..d75cf9634f 100644 --- a/OpenRA.Game/Traits/SelectionDecorations.cs +++ b/OpenRA.Game/Traits/SelectionDecorations.cs @@ -82,7 +82,7 @@ namespace OpenRA.Traits pipImages.PlayRepeating(pipStrings[0]); var pipSize = pipImages.Image.size.ToInt2(); - var pipxyBase = basePosition + new int2(1 - pipSize.X / 2, - (3 + pipSize.Y / 2)); + var pipxyBase = basePosition + new int2(1 - pipSize.X / 2, -(3 + pipSize.Y / 2)); var pipxyOffset = new int2(0, 0); var pal = wr.Palette(Info.Palette); var width = self.Bounds.Width; @@ -135,7 +135,5 @@ namespace OpenRA.Traits } } } - } -} - +} \ No newline at end of file diff --git a/OpenRA.Game/Traits/Target.cs b/OpenRA.Game/Traits/Target.cs index 39b9fe0a34..52e3a8bd0e 100644 --- a/OpenRA.Game/Traits/Target.cs +++ b/OpenRA.Game/Traits/Target.cs @@ -17,7 +17,7 @@ namespace OpenRA.Traits public enum TargetType { Invalid, Actor, Terrain, FrozenActor } public struct Target { - public static readonly Target[] None = {}; + public static readonly Target[] None = { }; public static readonly Target Invalid = new Target { type = TargetType.Invalid }; TargetType type; @@ -54,7 +54,7 @@ namespace OpenRA.Traits }; } - public static Target FromFrozenActor(FrozenActor a) { return new Target { frozen = a, type = TargetType.FrozenActor }; } + public static Target FromFrozenActor(FrozenActor a) { return new Target { frozen = a, type = TargetType.FrozenActor }; } public Actor Actor { get { return actor; } } public FrozenActor FrozenActor { get { return frozen; } } @@ -115,7 +115,7 @@ namespace OpenRA.Traits } // Positions available to target for range checks - static readonly WPos[] NoPositions = {}; + static readonly WPos[] NoPositions = { }; public IEnumerable Positions { get @@ -125,14 +125,14 @@ namespace OpenRA.Traits case TargetType.Actor: var targetable = actor.TraitOrDefault(); if (targetable == null) - return new [] { actor.CenterPosition }; + return new[] { actor.CenterPosition }; var positions = targetable.TargetablePositions(actor); - return positions.Any() ? positions : new [] { actor.CenterPosition }; + return positions.Any() ? positions : new[] { actor.CenterPosition }; case TargetType.FrozenActor: - return new [] { frozen.CenterPosition }; + return new[] { frozen.CenterPosition }; case TargetType.Terrain: - return new [] { pos }; + return new[] { pos }; default: case TargetType.Invalid: return NoPositions; @@ -146,7 +146,7 @@ namespace OpenRA.Traits return false; // Target ranges are calculated in 2D, so ignore height differences - var rangeSquared = range.Range*range.Range; + var rangeSquared = range.Range * range.Range; return Positions.Any(t => (t - origin).HorizontalLengthSquared <= rangeSquared); } @@ -168,6 +168,5 @@ namespace OpenRA.Traits return "Invalid"; } } - } } diff --git a/OpenRA.Game/Traits/TraitsInterfaces.cs b/OpenRA.Game/Traits/TraitsInterfaces.cs index 8a30198c00..c7b2953209 100644 --- a/OpenRA.Game/Traits/TraitsInterfaces.cs +++ b/OpenRA.Game/Traits/TraitsInterfaces.cs @@ -21,8 +21,8 @@ using OpenRA.Primitives; namespace OpenRA.Traits { // depends on the order of pips in WorldRenderer.cs! - public enum PipType { Transparent, Green, Yellow, Red, Gray, Blue, Ammo, AmmoEmpty }; - public enum TagType { None, Fake, Primary }; + public enum PipType { Transparent, Green, Yellow, Red, Gray, Blue, Ammo, AmmoEmpty } + public enum TagType { None, Fake, Primary } [Flags] public enum Stance @@ -65,7 +65,7 @@ namespace OpenRA.Traits Order IssueOrder(Actor self, IOrderTargeter order, Target target, bool queued); } - [Flags] public enum TargetModifiers { None = 0, ForceAttack = 1, ForceQueue = 2, ForceMove = 4 }; + [Flags] public enum TargetModifiers { None = 0, ForceAttack = 1, ForceQueue = 2, ForceMove = 4 } public static class TargetModifiersExts { @@ -173,6 +173,7 @@ namespace OpenRA.Traits nearestDistance = dist; } } + return nearest; } } diff --git a/OpenRA.Game/Traits/Util.cs b/OpenRA.Game/Traits/Util.cs index 3171384d36..7cca787f2c 100644 --- a/OpenRA.Game/Traits/Util.cs +++ b/OpenRA.Game/Traits/Util.cs @@ -91,9 +91,11 @@ namespace OpenRA.Traits { start = current; } + if (prev == act) break; } + return act; } diff --git a/OpenRA.Game/Traits/World/ActorMap.cs b/OpenRA.Game/Traits/World/ActorMap.cs index c259eb4b5f..4df7cf2d48 100644 --- a/OpenRA.Game/Traits/World/ActorMap.cs +++ b/OpenRA.Game/Traits/World/ActorMap.cs @@ -476,7 +476,6 @@ namespace OpenRA.Traits yield return bins[j * cols + i]; } - public IEnumerable ActorsInBox(WPos a, WPos b) { var left = Math.Min(a.X, b.X); diff --git a/OpenRA.Game/Traits/World/ScreenMap.cs b/OpenRA.Game/Traits/World/ScreenMap.cs index 96f239a6c5..1e6b27f3c9 100755 --- a/OpenRA.Game/Traits/World/ScreenMap.cs +++ b/OpenRA.Game/Traits/World/ScreenMap.cs @@ -72,7 +72,7 @@ namespace OpenRA.Traits for (var j = top; j <= bottom; j++) for (var i = left; i <= right; i++) - frozen[viewer][j*cols + i].Add(fa, bounds); + frozen[viewer][j * cols + i].Add(fa, bounds); } public void Remove(Player viewer, FrozenActor fa) @@ -117,7 +117,7 @@ namespace OpenRA.Traits var i = (worldPx.X / info.BinSize).Clamp(0, cols - 1); var j = (worldPx.Y / info.BinSize).Clamp(0, rows - 1); - return frozen[viewer][j*cols + i] + return frozen[viewer][j * cols + i] .Where(kv => kv.Key.IsValid && kv.Value.Contains(worldPx)) .Select(kv => kv.Key); } diff --git a/OpenRA.Game/WAngle.cs b/OpenRA.Game/WAngle.cs index 503ff0ff4d..0c9dd91c05 100644 --- a/OpenRA.Game/WAngle.cs +++ b/OpenRA.Game/WAngle.cs @@ -25,14 +25,15 @@ namespace OpenRA if (Angle < 0) Angle += 1024; } + public static readonly WAngle Zero = new WAngle(0); - public static WAngle FromFacing(int facing) { return new WAngle(facing*4); } - public static WAngle FromDegrees(int degrees) { return new WAngle(degrees*1024/360); } + public static WAngle FromFacing(int facing) { return new WAngle(facing * 4); } + public static WAngle FromDegrees(int degrees) { return new WAngle(degrees * 1024 / 360); } public static WAngle operator +(WAngle a, WAngle b) { return new WAngle(a.Angle + b.Angle); } public static WAngle operator -(WAngle a, WAngle b) { return new WAngle(a.Angle - b.Angle); } public static WAngle operator -(WAngle a) { return new WAngle(-a.Angle); } - public static bool operator ==(WAngle me, WAngle other) { return (me.Angle == other.Angle); } + public static bool operator ==(WAngle me, WAngle other) { return me.Angle == other.Angle; } public static bool operator !=(WAngle me, WAngle other) { return !(me == other); } public override int GetHashCode() { return Angle.GetHashCode(); } @@ -67,7 +68,7 @@ namespace OpenRA return new WAngle(x >= 0 ? 0 : 512); if (x == 0) - return new WAngle(Math.Sign(y)*256); + return new WAngle(Math.Sign(y) * 256); var ay = Math.Abs(y); var ax = Math.Abs(x); @@ -75,9 +76,9 @@ namespace OpenRA // Find the closest angle that satisfies y = x*tan(theta) var bestVal = int.MaxValue; var bestAngle = 0; - for (var i = 0; i < 256; i+= stride) + for (var i = 0; i < 256; i += stride) { - var val = Math.Abs(1024*ay - ax*TanTable[i]); + var val = Math.Abs(1024 * ay - ax * TanTable[i]); if (val < bestVal) { bestVal = val; diff --git a/OpenRA.Game/WPos.cs b/OpenRA.Game/WPos.cs index dfa3337bf0..9980352dcc 100644 --- a/OpenRA.Game/WPos.cs +++ b/OpenRA.Game/WPos.cs @@ -32,7 +32,7 @@ namespace OpenRA public static WPos operator -(WPos a, WVec b) { return new WPos(a.X - b.X, a.Y - b.Y, a.Z - b.Z); } public static WVec operator -(WPos a, WPos b) { return new WVec(a.X - b.X, a.Y - b.Y, a.Z - b.Z); } - public static bool operator ==(WPos me, WPos other) { return (me.X == other.X && me.Y == other.Y && me.Z == other.Z); } + public static bool operator ==(WPos me, WPos other) { return me.X == other.X && me.Y == other.Y && me.Z == other.Z; } public static bool operator !=(WPos me, WPos other) { return !(me == other); } public static WPos Lerp(WPos a, WPos b, int mul, int div) { return a + (b - a) * mul / div; } diff --git a/OpenRA.Game/WRange.cs b/OpenRA.Game/WRange.cs index 1e6038c405..8259b7e43c 100644 --- a/OpenRA.Game/WRange.cs +++ b/OpenRA.Game/WRange.cs @@ -26,7 +26,7 @@ namespace OpenRA public WRange(int r) { Range = r; } public static readonly WRange Zero = new WRange(0); - public static WRange FromCells(int cells) { return new WRange(1024*cells); } + public static WRange FromCells(int cells) { return new WRange(1024 * cells); } public static WRange operator +(WRange a, WRange b) { return new WRange(a.Range + b.Range); } public static WRange operator -(WRange a, WRange b) { return new WRange(a.Range - b.Range); } @@ -39,7 +39,7 @@ namespace OpenRA public static bool operator <=(WRange a, WRange b) { return a.Range <= b.Range; } public static bool operator >=(WRange a, WRange b) { return a.Range >= b.Range; } - public static bool operator ==(WRange me, WRange other) { return (me.Range == other.Range); } + public static bool operator ==(WRange me, WRange other) { return me.Range == other.Range; } public static bool operator !=(WRange me, WRange other) { return !(me == other); } // Sampled a N-sample probability density function in the range [-1024..1024] @@ -79,7 +79,7 @@ namespace OpenRA if (cell < 0) subcell = -subcell; - result = new WRange(1024*cell + subcell); + result = new WRange(1024 * cell + subcell); return true; } @@ -94,6 +94,7 @@ namespace OpenRA return 1; return Range.CompareTo(((WRange)obj).Range); } + public int CompareTo(WRange other) { return Range.CompareTo(other.Range); } public override string ToString() { return Range.ToString(); } @@ -139,6 +140,7 @@ namespace OpenRA default: throw new LuaException("WPos does not define a member '{0}'".F(key)); } } + set { throw new LuaException("WRange is read-only. Use WRange.New to create a new value"); diff --git a/OpenRA.Game/WRot.cs b/OpenRA.Game/WRot.cs index ca5cd3cc82..b9d5fee88a 100644 --- a/OpenRA.Game/WRot.cs +++ b/OpenRA.Game/WRot.cs @@ -28,8 +28,9 @@ 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) { return new WRot(-a.Roll, -a.Pitch, -a.Yaw); } - public static bool operator ==(WRot me, WRot other) { return (me.Roll == other.Roll && - me.Pitch == other.Pitch && me.Yaw == other.Yaw); } + public static bool operator ==(WRot me, WRot other) { 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 WRot WithYaw(WAngle yaw) @@ -53,10 +54,10 @@ namespace OpenRA // Normalized to 1024 == 1.0 return new int[4] { - (int)((sr*cp*cy - cr*sp*sy) / 1048576), // x - (int)((cr*sp*cy + sr*cp*sy) / 1048576), // y - (int)((cr*cp*sy - sr*sp*cy) / 1048576), // z - (int)((cr*cp*cy + sr*sp*sy) / 1048576) // w + (int)((sr * cp * cy - cr * sp * sy) / 1048576), // x + (int)((cr * sp * cy + sr * cp * sy) / 1048576), // y + (int)((cr * cp * sy - sr * sp * cy) / 1048576), // z + (int)((cr * cp * cy + sr * sp * sy) / 1048576) // w }; } @@ -64,24 +65,24 @@ namespace OpenRA { var q = AsQuarternion(); - // Theoretically 1024**2, but may differ slightly due to rounding - var lsq = q[0]*q[0] + q[1]*q[1] + q[2]*q[2] + q[3]*q[3]; + // Theoretically 1024 * * 2, but may differ slightly due to rounding + var lsq = q[0] * q[0] + q[1] * q[1] + q[2] * q[2] + q[3] * q[3]; // Quarternion components use 10 bits, so there's no risk of overflow var mtx = new int[16]; - mtx[0] = lsq - 2*(q[1]*q[1] + q[2]*q[2]); - mtx[1] = 2*(q[0]*q[1] + q[2]*q[3]); - mtx[2] = 2*(q[0]*q[2] - q[1]*q[3]); + mtx[0] = lsq - 2 * (q[1] * q[1] + q[2] * q[2]); + mtx[1] = 2 * (q[0] * q[1] + q[2] * q[3]); + mtx[2] = 2 * (q[0] * q[2] - q[1] * q[3]); mtx[3] = 0; - mtx[4] = 2*(q[0]*q[1] - q[2]*q[3]); - mtx[5] = lsq - 2*(q[0]*q[0] + q[2]*q[2]); - mtx[6] = 2*(q[1]*q[2] + q[0]*q[3]); + mtx[4] = 2 * (q[0] * q[1] - q[2] * q[3]); + mtx[5] = lsq - 2 * (q[0] * q[0] + q[2] * q[2]); + mtx[6] = 2 * (q[1] * q[2] + q[0] * q[3]); mtx[7] = 0; - mtx[8] = 2*(q[0]*q[2] + q[1]*q[3]); - mtx[9] = 2*(q[1]*q[2] - q[0]*q[3]); - mtx[10] = lsq - 2*(q[0]*q[0] + q[1]*q[1]); + mtx[8] = 2 * (q[0] * q[2] + q[1] * q[3]); + mtx[9] = 2 * (q[1] * q[2] - q[0] * q[3]); + mtx[10] = lsq - 2 * (q[0] * q[0] + q[1] * q[1]); mtx[11] = 0; mtx[12] = 0; diff --git a/OpenRA.Game/WVec.cs b/OpenRA.Game/WVec.cs index 53077558bc..9f42ecf8e8 100644 --- a/OpenRA.Game/WVec.cs +++ b/OpenRA.Game/WVec.cs @@ -30,9 +30,9 @@ namespace OpenRA public static WVec operator -(WVec a) { return new WVec(-a.X, -a.Y, -a.Z); } public static WVec operator /(WVec a, int b) { return new WVec(a.X / b, a.Y / b, a.Z / b); } public static WVec operator *(int a, WVec b) { return new WVec(a * b.X, a * b.Y, a * b.Z); } - public static WVec operator *(WVec a, int b) { return b*a; } + public static WVec operator *(WVec a, int b) { return b * a; } - public static bool operator ==(WVec me, WVec other) { return (me.X == other.X && me.Y == other.Y && me.Z == other.Z); } + public static bool operator ==(WVec me, WVec other) { return me.X == other.X && me.Y == other.Y && me.Z == other.Z; } public static bool operator !=(WVec me, WVec other) { return !(me == other); } public static int Dot(WVec a, WVec b) { return a.X * b.X + a.Y * b.Y + a.Z * b.Z; } @@ -48,9 +48,9 @@ namespace OpenRA var ly = (long)Y; var lz = (long)Z; return new WVec( - (int)((lx * mtx[0] + ly*mtx[4] + lz*mtx[8]) / mtx[15]), - (int)((lx * mtx[1] + ly*mtx[5] + lz*mtx[9]) / mtx[15]), - (int)((lx * mtx[2] + ly*mtx[6] + lz*mtx[10]) / mtx[15])); + (int)((lx * mtx[0] + ly * mtx[4] + lz * mtx[8]) / mtx[15]), + (int)((lx * mtx[1] + ly * mtx[5] + lz * mtx[9]) / mtx[15]), + (int)((lx * mtx[2] + ly * mtx[6] + lz * mtx[10]) / mtx[15])); } public static WVec Lerp(WVec a, WVec b, int mul, int div) { return a + (b - a) * mul / div; } @@ -65,7 +65,7 @@ namespace OpenRA // Add an additional quadratic variation to height // Uses fp to avoid integer overflow - var offset = (int)((float)((float)(b - a).Length*pitch.Tan()*mul*(div - mul)) / (float)(1024*div*div)); + var offset = (int)((float)((float)(b - a).Length * pitch.Tan() * mul * (div - mul)) / (float)(1024 * div * div)); return new WVec(ret.X, ret.Y, ret.Z + offset); } diff --git a/OpenRA.Game/Widgets/BackgroundWidget.cs b/OpenRA.Game/Widgets/BackgroundWidget.cs index e2481a4093..0b1bc1af3f 100644 --- a/OpenRA.Game/Widgets/BackgroundWidget.cs +++ b/OpenRA.Game/Widgets/BackgroundWidget.cs @@ -33,7 +33,7 @@ namespace OpenRA.Widgets if (ClickThrough || !RenderBounds.Contains(mi.Location)) return false; - if (!Draggable || moving && (!TakeMouseFocus(mi) || mi.Button != MouseButton.Left)) + if (!Draggable || (moving && (!TakeMouseFocus(mi) || mi.Button != MouseButton.Left))) return true; if (prevMouseLocation == null) diff --git a/OpenRA.Game/Widgets/ButtonWidget.cs b/OpenRA.Game/Widgets/ButtonWidget.cs index b6e564ed58..c84ad9a90a 100644 --- a/OpenRA.Game/Widgets/ButtonWidget.cs +++ b/OpenRA.Game/Widgets/ButtonWidget.cs @@ -15,7 +15,10 @@ namespace OpenRA.Widgets { public class ButtonWidget : Widget { + public readonly string TooltipContainer; + public readonly string TooltipTemplate = "BUTTON_TOOLTIP"; public Func GetKey = _ => Hotkey.Invalid; + public Hotkey Key { get { return GetKey(this); } @@ -40,19 +43,17 @@ namespace OpenRA.Widgets public Func GetContrastColor; public Func IsDisabled; public Func IsHighlighted; - public Action OnMouseDown = _ => {}; - public Action OnMouseUp = _ => {}; + public Action OnMouseDown = _ => { }; + public Action OnMouseUp = _ => { }; Lazy tooltipContainer; - public readonly string TooltipContainer; - public readonly string TooltipTemplate = "BUTTON_TOOLTIP"; [Translate] public string TooltipText; public Func GetTooltipText; // Equivalent to OnMouseUp, but without an input arg - public Action OnClick = () => {}; - public Action OnDoubleClick = () => {}; - public Action OnKeyPress = _ => {}; + public Action OnClick = () => { }; + public Action OnDoubleClick = () => { }; + public Action OnKeyPress = _ => { }; protected readonly Ruleset ModRules; @@ -149,14 +150,15 @@ namespace OpenRA.Widgets return YieldMouseFocus(mi); } } - // Only fire the onMouseUp event if we successfully lost focus, and were pressed else if (HasMouseFocus && mi.Event == MouseInputEvent.Up) { + // Only fire the onMouseUp event if we successfully lost focus, and were pressed if (Depressed && !disabled) OnMouseUp(mi); return YieldMouseFocus(mi); } + if (mi.Event == MouseInputEvent.Down) { // OnMouseDown returns false if the button shouldn't be pressed @@ -210,7 +212,7 @@ namespace OpenRA.Widgets var colordisabled = GetColorDisabled(); var contrast = GetContrastColor(); var s = font.Measure(text); - var stateOffset = (Depressed) ? new int2(VisualHeight, VisualHeight) : new int2(0, 0); + var stateOffset = Depressed ? new int2(VisualHeight, VisualHeight) : new int2(0, 0); var position = new int2(rb.X + (UsableWidth - s.X) / 2, rb.Y - BaseLine + (Bounds.Height - s.Y) / 2); DrawBackground(rb, disabled, Depressed, Ui.MouseOverWidget == this, highlighted); diff --git a/OpenRA.Game/Widgets/CheckboxWidget.cs b/OpenRA.Game/Widgets/CheckboxWidget.cs index 52b71c6c2d..2bc06207e3 100644 --- a/OpenRA.Game/Widgets/CheckboxWidget.cs +++ b/OpenRA.Game/Widgets/CheckboxWidget.cs @@ -58,7 +58,7 @@ namespace OpenRA.Widgets "checkbox"; WidgetUtils.DrawPanel(state, check); - var position = new float2(rect.Left + rect.Height * 1.5f, RenderOrigin.Y - BaseLine + (Bounds.Height - textSize.Y)/2); + var position = new float2(rect.Left + rect.Height * 1.5f, RenderOrigin.Y - BaseLine + (Bounds.Height - textSize.Y) / 2); if (Contrast) font.DrawTextWithContrast(text, position, diff --git a/OpenRA.Game/Widgets/ChromeMetrics.cs b/OpenRA.Game/Widgets/ChromeMetrics.cs index dd91767285..581be0f0ab 100644 --- a/OpenRA.Game/Widgets/ChromeMetrics.cs +++ b/OpenRA.Game/Widgets/ChromeMetrics.cs @@ -8,7 +8,6 @@ */ #endregion - using System.Collections.Generic; using System.Linq; @@ -42,6 +41,7 @@ namespace OpenRA.Widgets result = default(T); return false; } + result = FieldLoader.GetValue(key, s); return true; } diff --git a/OpenRA.Game/Widgets/ClientTooltipRegionWidget.cs b/OpenRA.Game/Widgets/ClientTooltipRegionWidget.cs index b3665c451b..5e81128ef4 100644 --- a/OpenRA.Game/Widgets/ClientTooltipRegionWidget.cs +++ b/OpenRA.Game/Widgets/ClientTooltipRegionWidget.cs @@ -48,7 +48,7 @@ namespace OpenRA.Widgets { if (TooltipContainer == null) return; - tooltipContainer.Value.SetTooltip(Template, new WidgetArgs() {{"orderManager", orderManager}, {"clientIndex", clientIndex}}); + tooltipContainer.Value.SetTooltip(Template, new WidgetArgs() { { "orderManager", orderManager }, { "clientIndex", clientIndex } }); } public override void MouseExited() diff --git a/OpenRA.Game/Widgets/DropDownButtonWidget.cs b/OpenRA.Game/Widgets/DropDownButtonWidget.cs index 103ad10d8a..735d78130f 100644 --- a/OpenRA.Game/Widgets/DropDownButtonWidget.cs +++ b/OpenRA.Game/Widgets/DropDownButtonWidget.cs @@ -36,16 +36,14 @@ namespace OpenRA.Widgets public override void Draw() { base.Draw(); - var stateOffset = (Depressed) ? new int2(VisualHeight, VisualHeight) : new int2(0, 0); + var stateOffset = Depressed ? new int2(VisualHeight, VisualHeight) : new int2(0, 0); var image = ChromeProvider.GetImage("scrollbar", IsDisabled() ? "down_pressed" : "down_arrow"); var rb = RenderBounds; var color = GetColor(); var colorDisabled = GetColorDisabled(); - WidgetUtils.DrawRGBA( image, - stateOffset + new float2( rb.Right - rb.Height + 4, - rb.Top + (rb.Height - image.bounds.Height) / 2 )); + WidgetUtils.DrawRGBA(image, stateOffset + new float2(rb.Right - rb.Height + 4, rb.Top + (rb.Height - image.bounds.Height) / 2)); WidgetUtils.FillRectWithColor(new Rectangle(stateOffset.X + rb.Right - rb.Height, stateOffset.Y + rb.Top + 3, 1, rb.Height - 6), @@ -102,9 +100,9 @@ namespace OpenRA.Widgets public void ShowDropDown(string panelTemplate, int maxHeight, IEnumerable options, Func setupItem) { - var substitutions = new Dictionary() {{ "DROPDOWN_WIDTH", Bounds.Width }}; + var substitutions = new Dictionary() { { "DROPDOWN_WIDTH", Bounds.Width } }; var panel = (ScrollPanelWidget)Ui.LoadWidget(panelTemplate, null, new WidgetArgs() - {{ "substitutions", substitutions }}); + { { "substitutions", substitutions } }); var itemTemplate = panel.Get("TEMPLATE"); panel.RemoveChildren(); @@ -125,9 +123,9 @@ namespace OpenRA.Widgets public void ShowDropDown(string panelTemplate, int height, Dictionary> groups, Func setupItem) { - var substitutions = new Dictionary() {{ "DROPDOWN_WIDTH", Bounds.Width }}; + var substitutions = new Dictionary() { { "DROPDOWN_WIDTH", Bounds.Width } }; var panel = (ScrollPanelWidget)Ui.LoadWidget(panelTemplate, null, new WidgetArgs() - {{ "substitutions", substitutions }}); + { { "substitutions", substitutions } }); var headerTemplate = panel.GetOrNull("HEADER"); var itemTemplate = panel.Get("TEMPLATE"); @@ -138,7 +136,7 @@ namespace OpenRA.Widgets var group = kv.Key; if (group.Length > 0 && headerTemplate != null) { - var header = ScrollItemWidget.Setup(headerTemplate, () => true, () => {}); + var header = ScrollItemWidget.Setup(headerTemplate, () => true, () => { }); header.Get("LABEL").GetText = () => group; panel.AddChild(header); } @@ -154,6 +152,7 @@ namespace OpenRA.Widgets panel.AddChild(item); } } + panel.Bounds.Height = Math.Min(height, panel.ContentHeight); AttachPanel(panel); } @@ -161,7 +160,7 @@ namespace OpenRA.Widgets public class MaskWidget : Widget { - public event Action OnMouseDown = _ => {}; + public event Action OnMouseDown = _ => { }; public MaskWidget() { } public MaskWidget(MaskWidget other) : base(other) @@ -183,4 +182,4 @@ namespace OpenRA.Widgets public override string GetCursor(int2 pos) { return null; } public override Widget Clone() { return new MaskWidget(this); } } -} \ No newline at end of file +} diff --git a/OpenRA.Game/Widgets/GridLayout.cs b/OpenRA.Game/Widgets/GridLayout.cs index 688b1afc51..d9a35aa56e 100644 --- a/OpenRA.Game/Widgets/GridLayout.cs +++ b/OpenRA.Game/Widgets/GridLayout.cs @@ -44,8 +44,6 @@ namespace OpenRA.Widgets public void AdjustChildren() { - } } -} - +} \ No newline at end of file diff --git a/OpenRA.Game/Widgets/HotkeyEntryWidget.cs b/OpenRA.Game/Widgets/HotkeyEntryWidget.cs index f5d651d23c..d2cf3f60d1 100644 --- a/OpenRA.Game/Widgets/HotkeyEntryWidget.cs +++ b/OpenRA.Game/Widgets/HotkeyEntryWidget.cs @@ -29,7 +29,7 @@ namespace OpenRA.Widgets public Color TextColor = ChromeMetrics.Get("HotkeyColor"); public Color TextColorDisabled = ChromeMetrics.Get("HotkeyColorDisabled"); - public HotkeyEntryWidget() {} + public HotkeyEntryWidget() { } protected HotkeyEntryWidget(HotkeyEntryWidget widget) : base(widget) { @@ -135,4 +135,4 @@ namespace OpenRA.Widgets public override Widget Clone() { return new HotkeyEntryWidget(this); } } -} \ No newline at end of file +} diff --git a/OpenRA.Game/Widgets/LabelWidget.cs b/OpenRA.Game/Widgets/LabelWidget.cs index b6fff7ecbc..921b88871e 100644 --- a/OpenRA.Game/Widgets/LabelWidget.cs +++ b/OpenRA.Game/Widgets/LabelWidget.cs @@ -67,16 +67,16 @@ namespace OpenRA.Widgets var position = RenderOrigin; if (VAlign == TextVAlign.Middle) - position += new int2(0, (Bounds.Height - textSize.Y)/2); + position += new int2(0, (Bounds.Height - textSize.Y) / 2); if (VAlign == TextVAlign.Bottom) position += new int2(0, Bounds.Height - textSize.Y); if (Align == TextAlign.Center) - position += new int2((Bounds.Width - textSize.X)/2, 0); + position += new int2((Bounds.Width - textSize.X) / 2, 0); if (Align == TextAlign.Right) - position += new int2(Bounds.Width - textSize.X,0); + position += new int2(Bounds.Width - textSize.X, 0); if (WordWrap) text = WidgetUtils.WrapText(text, Bounds.Width, font); @@ -91,4 +91,4 @@ namespace OpenRA.Widgets public override Widget Clone() { return new LabelWidget(this); } } -} \ No newline at end of file +} diff --git a/OpenRA.Game/Widgets/LineGraphWidget.cs b/OpenRA.Game/Widgets/LineGraphWidget.cs index b7feb73203..aed1a59669 100644 --- a/OpenRA.Game/Widgets/LineGraphWidget.cs +++ b/OpenRA.Game/Widgets/LineGraphWidget.cs @@ -87,6 +87,7 @@ namespace OpenRA.Widgets { return; } + var rect = RenderBounds; var origin = new float2(rect.Left, rect.Bottom); @@ -141,20 +142,22 @@ namespace OpenRA.Widgets keyOffset++; } - //TODO: make this stuff not draw outside of the RenderBounds + // TODO: make this stuff not draw outside of the RenderBounds for (int n = pointStart, x = 0; n <= pointEnd; n++, x += xStep) { Game.Renderer.LineRenderer.DrawLine(origin + new float2(x, 0), origin + new float2(x, -5), Color.White, Color.White); tiny.DrawText(GetXAxisValueFormat().F(n), origin + new float2(x, 2), Color.White); } + bold.DrawText(GetXAxisLabel(), origin + new float2(width / 2, 20), Color.White); - for (var y = (GetDisplayFirstYAxisValue() ? 0 : yStep); y <= height; y += yStep) + for (var y = GetDisplayFirstYAxisValue() ? 0 : yStep; y <= height; y += yStep) { var yValue = y / scale; Game.Renderer.LineRenderer.DrawLine(origin + new float2(width - 5, -y), origin + new float2(width, -y), Color.White, Color.White); tiny.DrawText(GetYAxisValueFormat().F(yValue), origin + new float2(width + 2, -y), Color.White); } + bold.DrawText(GetYAxisLabel(), origin + new float2(width + 40, -(height / 2)), Color.White); Game.Renderer.LineRenderer.DrawLine(origin, origin + new float2(width, 0), Color.White, Color.White); diff --git a/OpenRA.Game/Widgets/ProgressBarWidget.cs b/OpenRA.Game/Widgets/ProgressBarWidget.cs index 34cf30a280..b13dfe7b52 100644 --- a/OpenRA.Game/Widgets/ProgressBarWidget.cs +++ b/OpenRA.Game/Widgets/ProgressBarWidget.cs @@ -46,7 +46,7 @@ namespace OpenRA.Widgets WidgetUtils.DrawPanel("progressbar-bg", rb); var barRect = wasIndeterminate ? - new Rectangle(rb.X + 2 + (int)(0.75*offset*(rb.Width - 4)), rb.Y + 2, (rb.Width - 4) / 4, rb.Height - 4) : + new Rectangle(rb.X + 2 + (int)(0.75 * offset * (rb.Width - 4)), rb.Y + 2, (rb.Width - 4) / 4, rb.Height - 4) : new Rectangle(rb.X + 2, rb.Y + 2, percentage * (rb.Width - 4) / 100, rb.Height - 4); if (barRect.Width > 0) @@ -73,4 +73,4 @@ namespace OpenRA.Widgets public override Widget Clone() { return new ProgressBarWidget(this); } } -} \ No newline at end of file +} diff --git a/OpenRA.Game/Widgets/ScrollItemWidget.cs b/OpenRA.Game/Widgets/ScrollItemWidget.cs index a35596e10a..e4bae06991 100644 --- a/OpenRA.Game/Widgets/ScrollItemWidget.cs +++ b/OpenRA.Game/Widgets/ScrollItemWidget.cs @@ -40,8 +40,8 @@ namespace OpenRA.Widgets public override void Draw() { - var state = IsSelected() ? BaseName+"-selected" : - Ui.MouseOverWidget == this ? BaseName+"-hover" : + var state = IsSelected() ? BaseName + "-selected" : + Ui.MouseOverWidget == this ? BaseName + "-hover" : null; if (state != null) @@ -74,4 +74,4 @@ namespace OpenRA.Widgets return w; } } -} \ No newline at end of file +} diff --git a/OpenRA.Game/Widgets/ScrollPanelWidget.cs b/OpenRA.Game/Widgets/ScrollPanelWidget.cs index 423d0ab8d5..d5eb6d4cde 100644 --- a/OpenRA.Game/Widgets/ScrollPanelWidget.cs +++ b/OpenRA.Game/Widgets/ScrollPanelWidget.cs @@ -30,6 +30,7 @@ namespace OpenRA.Widgets public class ScrollPanelWidget : Widget { + readonly Ruleset modRules; public int ScrollbarWidth = 24; public int ItemSpacing = 2; public int ButtonDepth = ChromeMetrics.Get("ButtonDepth"); @@ -59,8 +60,6 @@ namespace OpenRA.Widgets // The current value is the actual list offset at the moment float currentListOffset; - readonly Ruleset modRules; - // Setting "smooth" to true will only update the target list offset. // Setting "smooth" to false will also set the current list offset, // i.e. it will scroll immediately. diff --git a/OpenRA.Game/Widgets/SliderWidget.cs b/OpenRA.Game/Widgets/SliderWidget.cs index c8e793d50b..44442c2acc 100755 --- a/OpenRA.Game/Widgets/SliderWidget.cs +++ b/OpenRA.Game/Widgets/SliderWidget.cs @@ -17,7 +17,7 @@ namespace OpenRA.Widgets public class SliderWidget : Widget { public Func IsDisabled = () => false; - public event Action OnChange = _ => {}; + public event Action OnChange = _ => { }; public int Ticks = 0; public int TrackHeight = 5; public string Thumb = "slider-thumb"; @@ -59,7 +59,7 @@ namespace OpenRA.Widgets if (mi.Event == MouseInputEvent.Down && !TakeMouseFocus(mi)) return false; if (!HasMouseFocus) return false; - switch(mi.Event) + switch (mi.Event) { case MouseInputEvent.Up: isMoving = false; @@ -95,7 +95,7 @@ namespace OpenRA.Widgets var rb = RenderBounds; var width = rb.Height; var height = rb.Height; - var origin = (int)(rb.X + thumbPos - width/2f); + var origin = (int)(rb.X + thumbPos - width / 2f); return new Rectangle(origin, rb.Y, width, height); } } @@ -132,5 +132,4 @@ namespace OpenRA.Widgets ButtonWidget.DrawBackground(Thumb, tr, IsDisabled(), isMoving, thumbHover, false); } } -} - +} \ No newline at end of file diff --git a/OpenRA.Game/Widgets/TooltipContainerWidget.cs b/OpenRA.Game/Widgets/TooltipContainerWidget.cs index c3c75cea00..285b4546f1 100644 --- a/OpenRA.Game/Widgets/TooltipContainerWidget.cs +++ b/OpenRA.Game/Widgets/TooltipContainerWidget.cs @@ -16,7 +16,7 @@ namespace OpenRA.Widgets { public class TooltipContainerWidget : Widget { - static readonly Action Nothing = () => {}; + static readonly Action Nothing = () => { }; public int2 CursorOffset = new int2(0, 20); public Action BeforeRender = Nothing; public int TooltipDelay = 5; @@ -30,7 +30,7 @@ namespace OpenRA.Widgets public void SetTooltip(string id, WidgetArgs args) { RemoveTooltip(); - tooltip = Ui.LoadWidget(id, this, new WidgetArgs(args) {{ "tooltipContainer", this }}); + tooltip = Ui.LoadWidget(id, this, new WidgetArgs(args) { { "tooltipContainer", this } }); } public void RemoveTooltip() diff --git a/OpenRA.Game/Widgets/ViewportControllerWidget.cs b/OpenRA.Game/Widgets/ViewportControllerWidget.cs index 4e5b17488f..903b31b9f0 100644 --- a/OpenRA.Game/Widgets/ViewportControllerWidget.cs +++ b/OpenRA.Game/Widgets/ViewportControllerWidget.cs @@ -72,7 +72,7 @@ namespace OpenRA.Widgets return; tooltipContainer.Value.SetTooltip(TooltipTemplate, - new WidgetArgs() {{ "world", world }, { "viewport", this }}); + new WidgetArgs() { { "world", world }, { "viewport", this } }); } public override void MouseExited() diff --git a/OpenRA.Game/Widgets/Widget.cs b/OpenRA.Game/Widgets/Widget.cs index 461718a85b..1874f3db98 100644 --- a/OpenRA.Game/Widgets/Widget.cs +++ b/OpenRA.Game/Widgets/Widget.cs @@ -133,6 +133,8 @@ namespace OpenRA.Widgets public abstract class Widget { + public readonly List Children = new List(); + // Info defined in YAML public string Id = null; public string X = "0"; @@ -150,7 +152,6 @@ namespace OpenRA.Widgets public Widget Parent = null; public Func IsVisible; public Widget() { IsVisible = () => Visible; } - public readonly List Children = new List(); public Widget(Widget widget) { @@ -324,8 +325,8 @@ namespace OpenRA.Widgets return EventBounds.Contains(pos) ? GetCursor(pos) : null; } - public virtual void MouseEntered() {} - public virtual void MouseExited() {} + public virtual void MouseEntered() { } + public virtual void MouseExited() { } public virtual bool HandleMouseInput(MouseInput mi) { return false; } public bool HandleMouseInputOuter(MouseInput mi) @@ -335,6 +336,7 @@ namespace OpenRA.Widgets return false; var oldMouseOver = Ui.MouseOverWidget; + // Send the event to the deepest children first and bubble up if unhandled foreach (var child in Children.OfType().Reverse()) if (child.HandleMouseInputOuter(mi)) @@ -385,7 +387,7 @@ namespace OpenRA.Widgets return handled; } - public virtual void Draw() {} + public virtual void Draw() { } public virtual void DrawOuter() { @@ -397,7 +399,7 @@ namespace OpenRA.Widgets } } - public virtual void Tick() {} + public virtual void Tick() { } public virtual void TickOuter() { @@ -427,7 +429,7 @@ namespace OpenRA.Widgets public virtual void RemoveChildren() { while (Children.Count > 0) - RemoveChild(Children[Children.Count-1]); + RemoveChild(Children[Children.Count - 1]); } public virtual void Removed() @@ -452,12 +454,13 @@ namespace OpenRA.Widgets if (w != null) return w; } + return null; } public T GetOrNull(string id) where T : Widget { - return (T) GetOrNull(id); + return (T)GetOrNull(id); } public T Get(string id) where T : Widget diff --git a/OpenRA.Game/Widgets/WidgetLoader.cs b/OpenRA.Game/Widgets/WidgetLoader.cs index 2b5680db15..123cfb2780 100644 --- a/OpenRA.Game/Widgets/WidgetLoader.cs +++ b/OpenRA.Game/Widgets/WidgetLoader.cs @@ -25,9 +25,9 @@ namespace OpenRA this.modData = modData; foreach (var file in modData.Manifest.ChromeLayout.Select(a => MiniYaml.FromFile(a))) - foreach( var w in file ) + foreach (var w in file) { - var key = w.Key.Substring( w.Key.IndexOf('@') + 1); + var key = w.Key.Substring(w.Key.IndexOf('@') + 1); if (widgets.ContainsKey(key)) throw new InvalidDataException("Widget has duplicate Key `{0}` at {1}".F(w.Key, w.Location)); widgets.Add(key, w); @@ -40,7 +40,7 @@ namespace OpenRA if (!widgets.TryGetValue(w, out ret)) throw new InvalidDataException("Cannot find widget with Id `{0}`".F(w)); - return LoadWidget( args, parent, ret ); + return LoadWidget(args, parent, ret); } public Widget LoadWidget(WidgetArgs args, Widget parent, MiniYamlNode node) @@ -51,7 +51,7 @@ namespace OpenRA var widget = NewWidget(node.Key, args); if (parent != null) - parent.AddChild( widget ); + parent.AddChild(widget); if (node.Key.Contains("@")) FieldLoader.LoadField(widget, "Id", node.Key.Split('@')[1]); @@ -65,7 +65,7 @@ namespace OpenRA foreach (var child in node.Value.Nodes) if (child.Key == "Children") foreach (var c in child.Value.Nodes) - LoadWidget( args, widget, c); + LoadWidget(args, widget, c); widget.PostInit(args); return widget; diff --git a/OpenRA.Game/Widgets/WidgetUtils.cs b/OpenRA.Game/Widgets/WidgetUtils.cs index ed58dc6c8b..f3c13e790b 100644 --- a/OpenRA.Game/Widgets/WidgetUtils.cs +++ b/OpenRA.Game/Widgets/WidgetUtils.cs @@ -24,7 +24,7 @@ namespace OpenRA.Widgets public static void DrawRGBA(Sprite s, float2 pos) { - Game.Renderer.RgbaSpriteRenderer.DrawSprite(s,pos); + Game.Renderer.RgbaSpriteRenderer.DrawSprite(s, pos); } public static void DrawSHPCentered(Sprite s, float2 pos, WorldRenderer wr) @@ -53,10 +53,11 @@ namespace OpenRA.Widgets { var rr = new Rectangle(s.bounds.Left, s.bounds.Top, - Math.Min(left.X,(int)s.size.X), - Math.Min(left.Y,(int)s.size.Y)); - ss = new Sprite(s.sheet,rr,s.channel); + Math.Min(left.X, (int)s.size.X), + Math.Min(left.Y, (int)s.size.Y)); + ss = new Sprite(s.sheet, rr, s.channel); } + DrawRGBA(ss, new float2(x, y)); } } @@ -175,7 +176,7 @@ namespace OpenRA.Widgets { var lines = text.Split('\n').ToList(); - for (var i=0; i { if (a != null) { a(); a = null; } }; } + public static Action Once(Action a) { return () => { if (a != null) { a(); a = null; } }; } public static string ChooseInitialMap(string initialUid) { diff --git a/OpenRA.Game/World.cs b/OpenRA.Game/World.cs index 439fe8d582..510d131dba 100644 --- a/OpenRA.Game/World.cs +++ b/OpenRA.Game/World.cs @@ -116,7 +116,11 @@ namespace OpenRA IOrderGenerator orderGenerator_; public IOrderGenerator OrderGenerator { - get { return orderGenerator_; } + get + { + return orderGenerator_; + } + set { Sync.AssertUnsynced("The current order generator may not be changed from synced code"); @@ -296,7 +300,7 @@ namespace OpenRA public int SyncHash() { - //using (new PerfSample("synchash")) + // using (new PerfSample("synchash")) { var n = 0; var ret = 0; diff --git a/OpenRA.Game/WorldUtils.cs b/OpenRA.Game/WorldUtils.cs index daf103f579..e7ac4994ad 100644 --- a/OpenRA.Game/WorldUtils.cs +++ b/OpenRA.Game/WorldUtils.cs @@ -36,7 +36,7 @@ namespace OpenRA { // Target ranges are calculated in 2D, so ignore height differences var vec = new WVec(r, r, WRange.Zero); - var rSq = r.Range*r.Range; + var rSq = r.Range * r.Range; return world.ActorMap.ActorsInBox(origin - vec, origin + vec).Where( a => (a.CenterPosition - origin).HorizontalLengthSquared <= rSq); } @@ -104,7 +104,7 @@ namespace OpenRA } } - public static bool AreMutualAllies( Player a, Player b ) + public static bool AreMutualAllies(Player a, Player b) { return a.Stances[b] == Stance.Ally && b.Stances[a] == Stance.Ally;