Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,13 @@ development workload. In Solution Explorer, right-click
Use W/S to move forward and backward, A/D to strafe, the left and right
arrow keys to turn, and Esc to close the demo.

Edit ``src/RetroRaycaster.Desktop/Levels/demo.json`` to change the level.
Build and publish copy it to ``Levels/demo.json`` beside the executable.
The ``rows`` array lists equal-length strings from top to bottom:
``.`` is empty, ``B`` is brick, and ``M`` is metal. The ``spawn`` object
sets ``x`` and ``y`` in grid units (right and down) and ``angleDegrees``
clockwise from east. The player's circle must fit in free space.

Original source release
-----------------------

Expand Down
56 changes: 56 additions & 0 deletions src/RetroRaycaster.Core/LevelLoader.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
using System;
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace RetroRaycaster.Core;

public static class LevelLoader
{
private sealed class LevelData
{
[JsonPropertyName("rows")] public required string?[]? Rows { get; init; }
[JsonPropertyName("spawn")] public required SpawnData? Spawn { get; init; }
}

private sealed class SpawnData
{
[JsonPropertyName("x")] public required double X { get; init; }
[JsonPropertyName("y")] public required double Y { get; init; }
[JsonPropertyName("angleDegrees")] public required double AngleDegrees { get; init; }
}

public static (GridMap Map, PlayerState Spawn) Load(Stream stream, WallTexture brick, WallTexture metal)
{
var level = JsonSerializer.Deserialize<LevelData>(stream);
if (level?.Rows is not { Length: > 0 } rows)
throw new JsonException("Expected a non-empty rows array.");
var spawn = level.Spawn ?? throw new JsonException("Expected a spawn object.");
int width = rows[0]?.Length ?? 0;
for (int y = 0; y < rows.Length; y++)
{
if (string.IsNullOrEmpty(rows[y]))
throw new JsonException($"Row {y + 1} must be a non-empty string.");
if (rows[y]!.Length != width)
throw new JsonException($"Row {y + 1} must contain {width} cells.");
}

var cells = new int[rows.Length, width];
for (int y = 0; y < rows.Length; y++)
for (int x = 0; x < width; x++)
cells[y, x] = rows[y]![x] switch
{
'.' => 0,
'B' => 1,
'M' => 2,
var symbol => throw new JsonException($"Unknown symbol '{symbol}' at row {y + 1}, column {x + 1}.")
};

var map = new GridMap(cells, [brick, metal]);
if (!PlayerMovement.CanStandAt(map, spawn.X, spawn.Y))
throw new JsonException("The spawn circle must fit inside the map without overlapping a wall.");
if (!double.IsFinite(spawn.AngleDegrees))
throw new JsonException("spawn.angleDegrees must be finite.");
return (map, new PlayerState(spawn.X, spawn.Y, spawn.AngleDegrees * (Math.PI / 180)));
}
}
28 changes: 25 additions & 3 deletions src/RetroRaycaster.Core/PlayerMovement.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,30 @@ public static PlayerState Update(GridMap map, PlayerState player, MovementInput

private static bool ValidAxis(double value) => value is >= -1 and <= 1;

internal static bool CanStandAt(GridMap map, double x, double y)
{
if (!double.IsFinite(x) || !double.IsFinite(y) ||
x < Radius || x > map.Width - Radius || y < Radius || y > map.Height - Radius)
return false;

for (int row = (int)(y - Radius); row <= Math.Min(map.Height - 1, (int)(y + Radius)); row++)
{
if (y <= row - Radius || y >= row + 1 + Radius) continue;
double reach = ReachAtRow(y, row);
for (int col = (int)(x - Radius); col <= Math.Min(map.Width - 1, (int)(x + Radius)); col++)
if (map.IsSolid(col, row) && x > col - reach && x < col + 1 + reach)
return false;
}
return true;
}

// At a corner only this cross-section of the circle reaches the wall.
private static double ReachAtRow(double across, int row)
{
double gap = Math.Max(0, Math.Max(row - across, across - (row + 1)));
return Math.Sqrt(Math.Max(0, Radius * Radius - gap * gap));
}

private static double MoveAxis(GridMap map, double position, double across, double delta, bool horizontal)
{
if (delta == 0) return position;
Expand All @@ -64,9 +88,7 @@ private static double MoveAxis(GridMap map, double position, double across, doub
for (int row = firstRow; row <= lastRow; row++)
{
if (across <= row - Radius || across >= row + 1 + Radius) continue;
double gap = Math.Max(0, Math.Max(row - across, across - (row + 1)));
// At a corner only this cross-section of the circle reaches the wall.
double reach = Math.Sqrt(Math.Max(0, Radius * Radius - gap * gap));
double reach = ReachAtRow(across, row);
for (int cell = first; cell <= last; cell++)
{
if (!(horizontal ? map.IsSolid(cell, row) : map.IsSolid(row, cell))) continue;
Expand Down
29 changes: 5 additions & 24 deletions src/RetroRaycaster.Desktop/DemoForm.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ internal sealed class DemoForm : Form
private const int FrameWidth = 320;
private const int FrameHeight = 200;
private const double HorizontalFov = 70 * Math.PI / 180;
private readonly GridMap map = CreateMap();
private PlayerState player = new(2.5, 3.5, 0);
private readonly GridMap map;
private PlayerState player;
private readonly HashSet<Keys> pressed = new();
private readonly Timer timer = new() { Interval = 16 };
private readonly Stopwatch clock = new();
Expand All @@ -25,8 +25,10 @@ internal sealed class DemoForm : Form
private readonly uint[] pixels = GC.AllocateArray<uint>(FrameWidth * FrameHeight, pinned: true);
private readonly Bitmap frame;

public DemoForm()
public DemoForm(GridMap map, PlayerState spawn)
{
this.map = map;
player = spawn;
frame = new Bitmap(FrameWidth, FrameHeight, FrameWidth * sizeof(uint),
PixelFormat.Format32bppArgb, Marshal.UnsafeAddrOfPinnedArrayElement(pixels, 0));
Text = "RetroRaycaster";
Expand Down Expand Up @@ -96,25 +98,4 @@ protected override void Dispose(bool disposing)
}
base.Dispose(disposing);
}

private static GridMap CreateMap()
{
string[] rows =
[
"###############",
"#.............#",
"#.....MM......#",
"#.....MM......#",
"#.........###.#",
"###########.#.#",
"#...........#.#",
"#.............#",
"###############"
];
var walls = new int[rows.Length, rows[0].Length];
for (int y = 0; y < rows.Length; y++)
for (int x = 0; x < rows[y].Length; x++)
walls[y, x] = rows[y][x] switch { '#' => 1, 'M' => 2, _ => 0 };
return new GridMap(walls, [DemoTextures.Brick, DemoTextures.Metal]);
}
}
14 changes: 14 additions & 0 deletions src/RetroRaycaster.Desktop/Levels/demo.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"rows": [
"BBBBBBBBBBBBBBB",
"B.............B",
"B.....MM......B",
"B.....MM......B",
"B.........BBB.B",
"BBBBBBBBBBB.B.B",
"B...........B.B",
"B.............B",
"BBBBBBBBBBBBBBB"
],
"spawn": { "x": 2.5, "y": 3.5, "angleDegrees": 0 }
}
18 changes: 17 additions & 1 deletion src/RetroRaycaster.Desktop/Program.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
using System;
using System.IO;
using System.Text.Json;
using System.Windows.Forms;
using RetroRaycaster.Core;

namespace RetroRaycaster.Desktop;

Expand All @@ -9,6 +12,19 @@ internal static class Program
private static void Main()
{
ApplicationConfiguration.Initialize();
Application.Run(new DemoForm());
string path = Path.Combine(AppContext.BaseDirectory, "Levels", "demo.json");
(GridMap Map, PlayerState Spawn) level;
try
{
using var file = File.OpenRead(path);
level = LevelLoader.Load(file, DemoTextures.Brick, DemoTextures.Metal);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException)
{
MessageBox.Show($"Could not load the level from {path}\n\n{ex.Message}",
"RetroRaycaster", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
Application.Run(new DemoForm(level.Map, level.Spawn));
}
}
1 change: 1 addition & 0 deletions src/RetroRaycaster.Desktop/RetroRaycaster.Desktop.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<None Update="Levels/demo.json" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
<ProjectReference Include="../RetroRaycaster.Core/RetroRaycaster.Core.csproj" />
</ItemGroup>
</Project>
79 changes: 79 additions & 0 deletions tests/RetroRaycaster.Core.Tests/LevelLoaderTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
using System;
using System.IO;
using System.Text;
using System.Text.Json;
using Xunit;

namespace RetroRaycaster.Core.Tests;

public class LevelLoaderTests
{
private const uint Brick = 0xFFCC4422, Metal = 0xFF667788;
private const string Spawn = """{"x":0.5,"y":0.5,"angleDegrees":0}""";

private static (GridMap Map, PlayerState Spawn) Load(string json)
{
using var stream = new MemoryStream(Encoding.UTF8.GetBytes(json));
return LevelLoader.Load(stream, new WallTexture(new uint[,] { { Brick } }),
new WallTexture(new uint[,] { { Metal } }));
}

[Fact]
public void LoadsRectangularMapWithBothTexturesAndConvertsHeading()
{
var (map, spawn) = Load("""{"rows":["..B","..M"],"spawn":{"x":1.5,"y":0.5,"angleDegrees":90}}""");
Assert.Equal((3, 2), (map.Width, map.Height));
Assert.Equal(new PlayerState(1.5, 0.5, Math.PI / 2), spawn);
var pixels = new uint[1];
for (int row = 0; row < 2; row++)
{
SoftwareRenderer.Render(map, spawn.X, row + 0.5, 0, Math.PI / 2, 1, 1, pixels);
Assert.Equal(row == 0 ? Brick : Metal, pixels[0]);
}
}

[Theory]
[InlineData("[]", "rows")]
[InlineData("""[""]""", "Row 1")]
[InlineData("""[".",null]""", "Row 2")]
[InlineData("""["..","."]""", "Row 2")]
[InlineData("""["..",".?"]""", "'?' at row 2, column 2")]
public void ReportsInvalidRows(string rows, string reason)
{
var error = Assert.Throws<JsonException>(() => Load($$"""{"rows":{{rows}},"spawn":{{Spawn}}}"""));
Assert.Contains(reason, error.Message);
}

[Theory]
[InlineData("""{"rows":["."]}""", "spawn")]
[InlineData("""{"spawn":{}}""", "x")]
[InlineData("""{"spawn":{"x":0,"y":0,"angleDegrees":0}}""", "rows")]
[InlineData("""{"rows":["."],"spawn":{"x":0.5,"angleDegrees":0}}""", "y")]
[InlineData("""{"rows":["."],"spawn":{"x":0.5,"y":0.5}}""", "angleDegrees")]
[InlineData("""{"rows":["."],"spawn":{"x":0.5,"y":0.5,"angleDegrees":1e999}}""", "angleDegrees")]
public void ReportsMissingOrInvalidField(string json, string field)
{
Assert.Contains(field, Assert.Throws<JsonException>(() => Load(json)).Message);
}

[Theory]
[InlineData(0.1, 0.5)] // Circle crosses the outer boundary.
[InlineData(1.5, 1.5)] // Center in the wall.
[InlineData(0.9, 1.5)] // Center in free space, overlap at a face.
[InlineData(0.9, 0.9)] // Only the corner intersects the circle.
public void RejectsSpawnOverlaps(double x, double y)
{
Assert.Throws<JsonException>(() => Load(CornerLevel(x, y)));
}

[Theory]
[InlineData(0.85, 0.85)] // Bounding box overlaps the wall, but the circle clears it.
[InlineData(0.8, 1.5)] // Touching the wall is valid.
public void AcceptsSpawnClearOfWall(double x, double y)
{
Assert.Equal(new PlayerState(x, y, 0), Load(CornerLevel(x, y)).Spawn);
}

private static string CornerLevel(double x, double y) =>
JsonSerializer.Serialize(new { rows = new[] { "..", ".M" }, spawn = new { x, y, angleDegrees = 0 } });
}
Loading