Create Mods.Common

Create a small base for Mods.Common and update solution and makefile to use it
This commit is contained in:
steelphase
2014-09-19 20:16:29 -04:00
parent 83dd4db909
commit 3a72153a3d
12 changed files with 88 additions and 10 deletions

View File

@@ -0,0 +1,57 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{FE6C8CC0-2F07-442A-B29F-17617B3B7FC6}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>OpenRA.Mods.Common</RootNamespace>
<AssemblyName>OpenRA.Mods.Common</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<PlatformTarget>x86</PlatformTarget>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Drawing" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\OpenRA.Game\OpenRA.Game.csproj">
<Project>{0dfb103f-2962-400f-8c6d-e2c28ccba633}</Project>
<Name>OpenRA.Game</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<Compile Include="ServerTraits\ColorValidator.cs" />
<Compile Include="ServerTraits\MasterServerPinger.cs" />
<Compile Include="ServerTraits\PlayerPinger.cs" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<PropertyGroup>
<PostBuildEvent>mkdir "$(SolutionDir)mods/common/"
copy "$(TargetPath)" "$(SolutionDir)mods/common/"
cd "$(SolutionDir)thirdparty/"
copy "FuzzyLogicLibrary.dll" "$(SolutionDir)"
cd "$(SolutionDir)"</PostBuildEvent>
</PropertyGroup>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@@ -0,0 +1,208 @@
#region Copyright & License Information
/*
* Copyright 2007-2014 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see COPYING.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using OpenRA.Graphics;
using OpenRA.Network;
using OpenRA.Server;
using S = OpenRA.Server.Server;
namespace OpenRA.Mods.Common.Server
{
public class ColorValidator : ServerTrait, IClientJoined
{
// The bigger the color threshold, the less permitive is the algorithm
const int ColorThreshold = 0x40;
const byte ColorLowerBound = 0x33;
const byte ColorHigherBound = 0xFF;
public static bool ValidateColorAgainstOtherPlayers(Color askedColor, int playerIndex, IEnumerable<Session.Client> lobbyClients, out Color forbiddenColor)
{
// Get lobby players colors, except from the actual target player
var playerColors = lobbyClients
.Where(lobbyClient => lobbyClient.Index != playerIndex)
.Select(lobbyClient => lobbyClient.Color.RGB);
// Calculate the difference between each player's color and target color and get the closest forbidden color (if invalid)
return ValidateColorAgainstForbidden(askedColor, playerColors, out forbiddenColor);
}
public static bool ValidateColorAgainstTileset(Color askedColor, TileSet tileSet, out Color forbiddenColor)
{
// Get colors from the current map terrain info
var forbiddenColors = tileSet.TerrainInfo.Select(terrainInfo => terrainInfo.Color);
// Calculate the difference between each forbidden color and target color and get the closest forbidden color (if invalid)
return ValidateColorAgainstForbidden(askedColor, forbiddenColors, out forbiddenColor);
}
private static bool ValidateColorAgainstForbidden(Color askedColor, IEnumerable<Color> forbiddenColors, out Color forbiddenColor)
{
var blockingColors =
forbiddenColors
.Where(playerColor => GetColorDelta(askedColor, playerColor) < ColorThreshold)
.Select(playerColor => new { Delta = GetColorDelta(askedColor, playerColor), Color = playerColor });
// Return the player that holds with the lowest difference
if (blockingColors.Any())
{
forbiddenColor = blockingColors.MinBy(aa => aa.Delta).Color;
return false;
}
forbiddenColor = default(Color);
return true;
}
public static Color? GetColorAlternative(Color askedColor, Color forbiddenColor)
{
Color? color = null;
// Vector between the 2 colors
var vector = new double[]
{
askedColor.R - forbiddenColor.R,
askedColor.G - forbiddenColor.G,
askedColor.B - forbiddenColor.B
};
// Reduce vector by it's biggest value (more calculations, but more accuracy too)
var vectorMax = vector.Max(vv => Math.Abs(vv));
if (vectorMax == 0)
vectorMax = 1; // Avoid divison by 0
vector[0] /= vectorMax;
vector[1] /= vectorMax;
vector[2] /= vectorMax;
// Color weights
var rmean = (double)(askedColor.R + forbiddenColor.R) / 2;
var weightVector = new[]
{
2.0 + rmean / 256,
4.0,
2.0 + (255 - rmean) / 256,
};
var ii = 1;
var alternativeColor = new int[3];
do
{
// If we reached the limit (The ii >= 255 prevents too much calculations)
if ((alternativeColor[0] == ColorLowerBound && alternativeColor[1] == ColorLowerBound && alternativeColor[2] == ColorLowerBound)
|| (alternativeColor[0] == ColorHigherBound && alternativeColor[1] == ColorHigherBound && alternativeColor[2] == ColorHigherBound)
|| ii >= 255)
{
color = null;
break;
}
// Apply vector to forbidden color
alternativeColor[0] = forbiddenColor.R + (int)(vector[0] * weightVector[0] * ii);
alternativeColor[1] = forbiddenColor.G + (int)(vector[1] * weightVector[1] * ii);
alternativeColor[2] = forbiddenColor.B + (int)(vector[2] * weightVector[2] * ii);
// Be sure it doesnt go out of bounds (0x33 is the lower limit for HSL picker)
alternativeColor[0] = alternativeColor[0].Clamp(ColorLowerBound, ColorHigherBound);
alternativeColor[1] = alternativeColor[1].Clamp(ColorLowerBound, ColorHigherBound);
alternativeColor[2] = alternativeColor[2].Clamp(ColorLowerBound, ColorHigherBound);
// Get the alternative color attempt
color = Color.FromArgb(alternativeColor[0], alternativeColor[1], alternativeColor[2]);
++ii;
} while (GetColorDelta(color.Value, forbiddenColor) < ColorThreshold);
return color;
}
public static double GetColorDelta(Color colorA, Color colorB)
{
var rmean = (colorA.R + colorB.R) / 2.0;
var r = colorA.R - colorB.R;
var g = colorA.G - colorB.G;
var b = colorA.B - colorB.B;
var weightR = 2.0 + rmean / 256;
var weightG = 4.0;
var weightB = 2.0 + (255 - rmean) / 256;
return Math.Sqrt(weightR * r * r + weightG * g * g + weightB * b * b);
}
public static HSLColor ValidatePlayerColorAndGetAlternative(S server, HSLColor askedColor, int playerIndex, Connection connectionToEcho = null)
{
var askColor = askedColor;
Color invalidColor;
if (!ValidatePlayerNewColor(server, askColor.RGB, playerIndex, out invalidColor, connectionToEcho))
{
var altColor = GetColorAlternative(askColor.RGB, invalidColor);
if (altColor == null || !ValidatePlayerNewColor(server, altColor.Value, playerIndex))
{
// Pick a random color
do
{
var hue = (byte)server.Random.Next(255);
var sat = (byte)server.Random.Next(255);
var lum = (byte)server.Random.Next(51, 255);
askColor = new HSLColor(hue, sat, lum);
} while (!ValidatePlayerNewColor(server, askColor.RGB, playerIndex));
}
else
askColor = HSLColor.FromRGB(altColor.Value.R, altColor.Value.G, altColor.Value.B);
}
return askColor;
}
public static bool ValidatePlayerNewColor(S server, Color askedColor, int playerIndex, out Color forbiddenColor, Connection connectionToEcho = null)
{
// Validate color against the current map tileset
if (!ValidateColorAgainstTileset(askedColor, Game.modData.DefaultRules.TileSets[server.Map.Tileset], out forbiddenColor))
{
if (connectionToEcho != null)
server.SendOrderTo(connectionToEcho, "Message", "Requested color was too similar to the map terrain, and has been adjusted.");
return false;
}
// Validate color against the other players colors
if (!ValidateColorAgainstOtherPlayers(askedColor, playerIndex, server.LobbyInfo.Clients, out forbiddenColor))
{
if (connectionToEcho != null)
server.SendOrderTo(connectionToEcho, "Message", "Requested color was too similar to another player, and has been adjusted.");
return false;
}
// Else is valid!
forbiddenColor = default(Color);
return true;
}
public static bool ValidatePlayerNewColor(S server, Color askedColor, int playerIndex, Connection connectionToEcho = null)
{
Color forbiddenColor;
return ValidatePlayerNewColor(server, askedColor, playerIndex, out forbiddenColor, connectionToEcho);
}
#region IClientJoined
public void ClientJoined(S server, Connection conn)
{
var client = server.GetClient(conn);
// Validate if color is allowed and get an alternative if it isn't
client.Color = ColorValidator.ValidatePlayerColorAndGetAlternative(server, client.Color, client.Index);
}
#endregion
}
}

View File

@@ -0,0 +1,108 @@
#region Copyright & License Information
/*
* Copyright 2007-2014 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see COPYING.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using OpenRA.Server;
using S = OpenRA.Server.Server;
namespace OpenRA.Mods.Common.Server
{
public class MasterServerPinger : ServerTrait, ITick, INotifySyncLobbyInfo, IStartGame, IEndGame
{
const int MasterPingInterval = 60 * 3; // 3 minutes. server has a 5 minute TTL for games, so give ourselves a bit
// of leeway.
public int TickTimeout { get { return MasterPingInterval * 10000; } }
public void Tick(S server)
{
if ((Game.RunTime - lastPing > MasterPingInterval * 1000) || isInitialPing)
PingMasterServer(server);
else
lock (masterServerMessages)
while (masterServerMessages.Count > 0)
server.SendMessage(masterServerMessages.Dequeue());
}
public void LobbyInfoSynced(S server) { PingMasterServer(server); }
public void GameStarted(S server) { PingMasterServer(server); }
public void GameEnded(S server) { PingMasterServer(server); }
int lastPing = 0;
bool isInitialPing = true;
volatile bool isBusy;
Queue<string> masterServerMessages = new Queue<string>();
public void PingMasterServer(S server)
{
if (isBusy || !server.Settings.AdvertiseOnline) return;
lastPing = Game.RunTime;
isBusy = true;
var mod = server.ModData.Manifest.Mod;
// important to grab these on the main server thread, not in the worker we're about to spawn -- they may be modified
// by the main thread as clients join and leave.
var numPlayers = server.LobbyInfo.Clients.Where(c1 => c1.Bot == null && c1.Slot != null).Count();
var numBots = server.LobbyInfo.Clients.Where(c1 => c1.Bot != null).Count();
var numSpectators = server.LobbyInfo.Clients.Where(c1 => c1.Bot == null && c1.Slot == null).Count();
var passwordProtected = string.IsNullOrEmpty(server.Settings.Password) ? 0 : 1;
var clients = server.LobbyInfo.Clients.Where(c1 => c1.Bot == null).Select(c => Convert.ToBase64String(Encoding.UTF8.GetBytes(c.Name))).ToArray();
Action a = () =>
{
try
{
var url = "ping?port={0}&name={1}&state={2}&players={3}&bots={4}&mods={5}&map={6}&maxplayers={7}&spectators={8}&protected={9}&clients={10}";
if (isInitialPing) url += "&new=1";
using (var wc = new WebClient())
{
wc.Proxy = null;
wc.DownloadData(
server.Settings.MasterServer + url.F(
server.Settings.ExternalPort, Uri.EscapeUriString(server.Settings.Name),
(int)server.State,
numPlayers,
numBots,
"{0}@{1}".F(mod.Id, mod.Version),
server.LobbyInfo.GlobalSettings.Map,
server.Map.PlayerCount,
numSpectators,
passwordProtected,
string.Join(",", clients)));
if (isInitialPing)
{
isInitialPing = false;
lock (masterServerMessages)
masterServerMessages.Enqueue("Master server communication established.");
}
}
}
catch (Exception ex)
{
Log.Write("server", ex.ToString());
lock (masterServerMessages)
masterServerMessages.Enqueue("Master server communication failed.");
}
isBusy = false;
};
a.BeginInvoke(null, null);
}
}
}

View File

@@ -0,0 +1,37 @@
#region Copyright & License Information
/*
* Copyright 2007-2014 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see COPYING.
*/
#endregion
using System;
using OpenRA.Server;
using S = OpenRA.Server.Server;
namespace OpenRA.Mods.Common.Server
{
public class PlayerPinger : ServerTrait, ITick
{
int PingInterval = 5000; // Ping every 5 seconds
// TickTimeout is in microseconds
public int TickTimeout { get { return PingInterval * 100; } }
int lastPing = 0;
bool isInitialPing = true;
public void Tick(S server)
{
if ((Game.RunTime - lastPing > PingInterval) || isInitialPing)
{
isInitialPing = false;
lastPing = Game.RunTime;
foreach (var p in server.Conns)
server.SendOrderTo(p, "Ping", Game.RunTime.ToString());
}
}
}
}