move a bunch of stuff into subfolders

This commit is contained in:
Vinzenz Schroeter 2024-04-07 11:19:14 +02:00
commit 151cad4cee
13 changed files with 44 additions and 27 deletions

View file

@ -1,6 +1,8 @@
using System.Net.WebSockets;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using TanksServer.Helpers;
using TanksServer.Services;
namespace TanksServer;

View file

@ -1,6 +1,7 @@
using System.Net.WebSockets;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using TanksServer.Helpers;
namespace TanksServer;
@ -55,22 +56,19 @@ internal sealed class ControlsServer(ILogger<ControlsServer> logger, ILoggerFact
protected override Task ReceiveAsync(ArraySegment<byte> buffer)
{
logger.LogDebug("player input {} {}", buffer[0], buffer[1]);
var type = (MessageType)buffer[0];
var control = (InputType)buffer[1];
logger.LogTrace("player input {} {} {}", player.Id, type, control);
bool isEnable;
switch ((MessageType)buffer[0])
var isEnable = type switch
{
case MessageType.Enable:
isEnable = true;
break;
case MessageType.Disable:
isEnable = false;
break;
default:
return CloseAsync(WebSocketCloseStatus.InvalidPayloadData, "invalid state");
}
MessageType.Enable => true,
MessageType.Disable => false,
_ => throw new ArgumentException("invalid message type")
};
switch ((InputType)buffer[1])
switch (control)
{
case InputType.Forward:
player.Controls.Forward = isEnable;
@ -88,7 +86,7 @@ internal sealed class ControlsServer(ILogger<ControlsServer> logger, ILoggerFact
player.Controls.Shoot = isEnable;
break;
default:
return CloseAsync(WebSocketCloseStatus.InvalidPayloadData, "invalid control");
throw new ArgumentException("invalid control type");
}
return Task.CompletedTask;

View file

@ -0,0 +1,6 @@
using System.Text.Json.Serialization;
namespace TanksServer;
[JsonSerializable(typeof(Player))]
internal partial class AppSerializerContext: JsonSerializerContext;

View file

@ -0,0 +1,57 @@
using TanksServer.Helpers;
namespace TanksServer;
internal sealed class DisplayPixelBuffer(byte[] data)
{
public byte[] Data => data;
public byte Magic1
{
get => data[0];
set => data[0] = value;
}
public byte Magic2
{
get => data[1];
set => data[1] = value;
}
public ushort X
{
get => GetTwoBytes(2);
set => SetTwoBytes(2, value);
}
public ushort Y
{
get => GetTwoBytes(4);
set => SetTwoBytes(4, value);
}
public ushort WidthInTiles
{
get => GetTwoBytes(6);
set => SetTwoBytes(6, value);
}
public ushort HeightInPixels
{
get => GetTwoBytes(8);
set => SetTwoBytes(8, value);
}
public FixedSizeBitFieldView Pixels { get; } = new(data.AsMemory(10));
private ushort GetTwoBytes(int index)
{
return (ushort)(data[index] * byte.MaxValue + data[index + 1]);
}
private void SetTwoBytes(int index, ushort value)
{
data[index] = (byte)(value / byte.MaxValue);
data[index + 1] = (byte)(value % byte.MaxValue);
}
}

View file

@ -0,0 +1,74 @@
using System.Net.WebSockets;
using Microsoft.Extensions.Logging;
namespace TanksServer.Helpers;
/// <summary>
/// Hacky class for easier semantics
/// </summary>
internal abstract class EasyWebSocket
{
private readonly TaskCompletionSource _completionSource = new();
private readonly ILogger _logger;
private readonly WebSocket _socket;
private readonly Task _readLoop;
private readonly ArraySegment<byte> _buffer;
private int _closed;
protected EasyWebSocket(WebSocket socket, ILogger logger, ArraySegment<byte> buffer)
{
_socket = socket;
_logger = logger;
_buffer = buffer;
_readLoop = ReadLoopAsync();
}
public Task Done => _completionSource.Task;
private async Task ReadLoopAsync()
{
do
{
var response = await _socket.ReceiveAsync(_buffer, CancellationToken.None);
if (response.CloseStatus.HasValue)
break;
await ReceiveAsync(_buffer[..response.Count]);
} while (_socket.State == WebSocketState.Open);
}
protected abstract Task ReceiveAsync(ArraySegment<byte> buffer);
protected abstract Task ClosingAsync();
protected async Task TrySendAsync(byte[] data)
{
if (_socket.State != WebSocketState.Open)
await CloseAsync();
_logger.LogTrace("sending {} bytes of data", _buffer.Count);
try
{
await _socket.SendAsync(data, WebSocketMessageType.Binary, true, CancellationToken.None);
}
catch (WebSocketException wsEx)
{
_logger.LogDebug(wsEx, "send failed");
}
}
public async Task CloseAsync(
WebSocketCloseStatus status = WebSocketCloseStatus.NormalClosure,
string? description = null
)
{
if (Interlocked.Exchange(ref _closed, 1) == 1)
return;
_logger.LogDebug("closing socket");
await _socket.CloseAsync(status, description, CancellationToken.None);
await _readLoop;
await ClosingAsync();
_completionSource.SetResult();
}
}

View file

@ -0,0 +1,74 @@
using System.Collections;
namespace TanksServer.Helpers;
internal sealed class FixedSizeBitFieldView(Memory<byte> data) : IList<bool>
{
public int Count => data.Length * 8;
public bool IsReadOnly => false;
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public IEnumerator<bool> GetEnumerator()
{
return Enumerable().GetEnumerator();
IEnumerable<bool> Enumerable()
{
for (var i = 0; i < Count; i++)
yield return this[i];
}
}
public void Clear()
{
var span = data.Span;
for (var i = 0; i < data.Length; i++)
span[i] = 0;
}
public void CopyTo(bool[] array, int arrayIndex)
{
for (var i = 0; i < Count && i + arrayIndex < array.Length; i++)
array[i + arrayIndex] = this[i];
}
private static (int byteIndex, int bitInByteIndex) GetIndexes(int bitIndex)
{
var byteIndex = bitIndex / 8;
var bitInByteIndex = 7 - bitIndex % 8;
return (byteIndex, bitInByteIndex);
}
public bool this[int bitIndex]
{
get
{
var (byteIndex, bitInByteIndex) = GetIndexes(bitIndex);
var bitInByteMask = (byte)(1 << bitInByteIndex);
return (data.Span[byteIndex] & bitInByteMask) != 0;
}
set
{
var (byteIndex, bitInByteIndex) = GetIndexes(bitIndex);
var bitInByteMask = (byte)(1 << bitInByteIndex);
if (value)
{
data.Span[byteIndex] |= bitInByteMask;
}
else
{
var withoutBitMask = (byte)(ushort.MaxValue ^ bitInByteMask);
data.Span[byteIndex] &= withoutBitMask;
}
}
}
public void Add(bool item) => throw new NotSupportedException();
public bool Contains(bool item) => throw new NotSupportedException();
public bool Remove(bool item) => throw new NotSupportedException();
public int IndexOf(bool item) => throw new NotSupportedException();
public void Insert(int index, bool item) => throw new NotSupportedException();
public void RemoveAt(int index) => throw new NotSupportedException();
}

View file

@ -0,0 +1,49 @@
using System.Collections.Concurrent;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Extensions.Logging;
namespace TanksServer;
internal sealed class PlayerServer(ILogger<PlayerServer> logger)
{
private readonly ConcurrentDictionary<string, Player> _players = new();
public Player GetOrAdd(string name)
{
var player = _players.GetOrAdd(name, _ => new Player(name));
logger.LogInformation("player {} (re)joined", player.Id);
return player;
}
public bool TryGet(Guid? playerId, [MaybeNullWhen(false)] out Player foundPlayer)
{
foreach (var player in _players.Values)
{
if (player.Id != playerId)
continue;
foundPlayer = player;
return true;
}
foundPlayer = null;
return false;
}
}
internal sealed class Player(string name)
{
public string Name => name;
public Guid Id { get; } = Guid.NewGuid();
public PlayerControls Controls { get; } = new();
}
internal sealed class PlayerControls
{
public bool Forward { get; set; }
public bool Backward { get; set; }
public bool TurnLeft { get; set; }
public bool TurnRight { get; set; }
public bool Shoot { get; set; }
}

View file

@ -4,6 +4,7 @@ using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using TanksServer.Services;
namespace TanksServer;
@ -17,7 +18,7 @@ internal static class Program
app.UseWebSockets();
var clientScreenServer = app.Services.GetRequiredService<ClientScreenServer>();
var playerService = app.Services.GetRequiredService<PlayerService>();
var playerService = app.Services.GetRequiredService<PlayerServer>();
var controlsServer = app.Services.GetRequiredService<ControlsServer>();
var clientFileProvider = new PhysicalFileProvider(Path.Combine(app.Environment.ContentRootPath, "client"));
@ -84,7 +85,7 @@ internal static class Program
builder.Services.AddHostedService<GameTickService>();
builder.Services.AddSingleton<PlayerService>();
builder.Services.AddSingleton<PlayerServer>();
return builder.Build();
}

View file

@ -0,0 +1,37 @@
using Microsoft.Extensions.Hosting;
namespace TanksServer.Services;
internal sealed class GameTickService(IEnumerable<ITickStep> steps) : IHostedService
{
private readonly CancellationTokenSource _cancellation = new();
private readonly List<ITickStep> _steps = steps.ToList();
private Task? _run;
public Task StartAsync(CancellationToken cancellationToken)
{
_run = RunAsync();
return Task.CompletedTask;
}
private async Task RunAsync()
{
while (!_cancellation.IsCancellationRequested)
{
foreach (var step in _steps)
await step.TickAsync();
await Task.Delay(1000);
}
}
public async Task StopAsync(CancellationToken cancellationToken)
{
await _cancellation.CancelAsync();
if (_run != null) await _run;
}
}
public interface ITickStep
{
Task TickAsync();
}

View file

@ -0,0 +1,56 @@
namespace TanksServer.Services;
internal class MapDrawer(MapService map):ITickStep
{
private const uint GameFieldPixelCount = MapService.PixelsPerRow * MapService.PixelsPerColumn;
private void DrawInto(DisplayPixelBuffer buf)
{
for (var tileY = 0; tileY < MapService.TilesPerColumn; tileY++)
for (var tileX = 0; tileX < MapService.TilesPerRow; tileX++)
{
if (!map.IsCurrentlyWall(tileX, tileY))
continue;
var absoluteTilePixelY = tileY * MapService.TileSize;
for (var pixelInTileY = 0; pixelInTileY < MapService.TileSize; pixelInTileY++)
{
var absoluteRowStartPixelIndex = (absoluteTilePixelY + pixelInTileY) * MapService.PixelsPerRow
+ tileX * MapService.TileSize;
for (var pixelInTileX = 0; pixelInTileX < MapService.TileSize; pixelInTileX++)
buf.Pixels[absoluteRowStartPixelIndex + pixelInTileX] = pixelInTileX % 2 == pixelInTileY % 2;
}
}
}
private DisplayPixelBuffer CreateGameFieldPixelBuffer()
{
var data = new byte[10 + GameFieldPixelCount / 8];
var result = new DisplayPixelBuffer(data)
{
Magic1 = 0,
Magic2 = 19,
X = 0,
Y = 0,
WidthInTiles = MapService.TilesPerRow,
HeightInPixels = MapService.PixelsPerColumn
};
return result;
}
private DisplayPixelBuffer? _lastFrame;
public DisplayPixelBuffer LastFrame
{
get => _lastFrame ?? throw new InvalidOperationException("first frame not yet drawn");
private set => _lastFrame = value;
}
public Task TickAsync()
{
var buffer = CreateGameFieldPixelBuffer();
DrawInto(buffer);
LastFrame = buffer;
return Task.CompletedTask;
}
}

View file

@ -0,0 +1,42 @@
namespace TanksServer.Services;
internal class MapService
{
public const int TilesPerRow = 44;
public const int TilesPerColumn = 20;
public const int TileSize = 8;
public const int PixelsPerRow = TilesPerRow * TileSize;
public const int PixelsPerColumn = TilesPerColumn * TileSize;
private readonly string _map =
"""
############################################
#...................##.....................#
#...................##.....................#
#.....####......................####.......#
#..........................................#
#............###...........###.............#
#............#...............#.............#
#...##.......#...............#......##.....#
#....#..............................#......#
#....#..##......................##..#......#
#....#..##......................##..#......#
#....#..............................#......#
#...##.......#...............#......##.....#
#............#...............#.............#
#............###...........###.............#
#..........................................#
#.....####......................####.......#
#...................##.....................#
#...................##.....................#
############################################
"""
.ReplaceLineEndings(string.Empty);
private char this[int tileX, int tileY] => _map[tileX + tileY * TilesPerRow];
public bool IsCurrentlyWall(int tileX, int tileY)
{
return this[tileX, tileY] == '#';
}
}

View file

@ -0,0 +1,20 @@
using System.Net.Sockets;
using Microsoft.Extensions.Options;
namespace TanksServer.Services;
internal sealed class ServicePointDisplay(IOptions<ServicePointDisplayConfiguration> options)
{
private readonly UdpClient _udpClient = new(options.Value.Hostname, options.Value.Port);
public ValueTask<int> Send(DisplayPixelBuffer buffer)
{
return _udpClient.SendAsync(buffer.Data);
}
}
internal sealed class ServicePointDisplayConfiguration
{
public string Hostname { get; set; } = string.Empty;
public int Port { get; set; }
}

View file

@ -14,5 +14,11 @@
<Link>.dockerignore</Link>
</Content>
</ItemGroup>
<PropertyGroup>
<AnalysisMode>Recommended</AnalysisMode>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<NoWarn>CA1805,CA1848</NoWarn>
</PropertyGroup>
</Project>