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
8 changes: 6 additions & 2 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,16 @@ Open ``RetroRaycaster.sln`` in Visual Studio 2022 with the .NET 8 desktop
development workload. In Solution Explorer, right-click
``RetroRaycaster.Desktop``, choose **Set as Startup Project**, and press F5.
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.
arrow keys to turn, and Esc to close the demo. From the starting position,
press E to open the wooden door straight ahead. Walk through with W, clear
the threshold, turn around and press E again to close it.

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
``.`` is empty, ``B`` is brick, ``M`` is metal and ``D`` is an initially
closed door. E toggles the first door in sight within 1.5 grid units.
An occupied doorway stays open. 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.

Expand Down
35 changes: 31 additions & 4 deletions src/RetroRaycaster.Core/GridMap.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,12 @@ public sealed class GridMap
{
private readonly int[,] materials;
private readonly WallTexture[] textures = [];
// Door cells retain their material ID. A negative ID denotes an open door.
private readonly int doorMaterial;
public int Width => materials.GetLength(1);
public int Height => materials.GetLength(0);

internal bool IsSolid(int x, int y) => materials[y, x] != 0;
internal bool IsSolid(int x, int y) => materials[y, x] > 0;
internal WallTexture? TextureAtWall(int x, int y) =>
textures.Length == 0 ? null : textures[materials[y, x] - 1];

Expand All @@ -33,13 +35,16 @@ public GridMap(bool[,] solidCells)
}

/// <summary>Zero denotes empty space. Positive IDs select textures starting at one.</summary>
public GridMap(int[,] materialIds, WallTexture[] textures)
public GridMap(int[,] materialIds, WallTexture[] textures) : this(materialIds, textures, 0) { }

internal GridMap(int[,] materialIds, WallTexture[] textures, int doorMaterial)
{
ArgumentNullException.ThrowIfNull(materialIds);
ArgumentNullException.ThrowIfNull(textures);
if (materialIds.Length == 0)
throw new ArgumentException("The grid must contain at least one cell.", nameof(materialIds));
materials = (int[,])materialIds.Clone();
this.doorMaterial = doorMaterial;
this.textures = (WallTexture[])textures.Clone();
foreach (var texture in this.textures)
ArgumentNullException.ThrowIfNull(texture);
Expand All @@ -54,7 +59,26 @@ public GridMap(int[,] materialIds, WallTexture[] textures)
/// The origin belongs to cell (floor(x), floor(y)) and must be empty if inside.
/// At a corner the ray enters only the diagonal cell and reports its vertical side.
/// </summary>
public RayHit? CastRay(double originX, double originY, double directionX, double directionY)
public RayHit? CastRay(double originX, double originY, double directionX, double directionY) =>
Trace(originX, originY, directionX, directionY, double.PositiveInfinity, includeOpenDoors: false);

/// <summary>Toggles the first visible door within 1.5 grid units of the player.</summary>
public bool TryToggleDoor(PlayerState player)
{
if (doorMaterial == 0) return false;
var (dy, dx) = Math.SinCos(player.Angle);
var hit = Trace(player.X, player.Y, dx, dy, 1.5, includeOpenDoors: true);
if (hit is not RayHit cell) return false;
int id = materials[cell.CellY, cell.CellX];
if (Math.Abs(id) != doorMaterial) return false;
if (id < 0 && PlayerMovement.OverlapsCell(player.X, player.Y, cell.CellX, cell.CellY))
return false;
materials[cell.CellY, cell.CellX] = -id;
return true;
}

private RayHit? Trace(double originX, double originY, double directionX, double directionY,
double maxDistance, bool includeOpenDoors)
{
if (!double.IsFinite(originX) || !double.IsFinite(originY) ||
!double.IsFinite(directionX) || !double.IsFinite(directionY))
Expand All @@ -68,6 +92,8 @@ public GridMap(int[,] materialIds, WallTexture[] textures)
int y = (int)originY;
if (IsSolid(x, y))
throw new ArgumentException("A moving ray must start in an empty cell.");
// The occupied doorway is the first door and cannot be closed.
if (includeOpenDoors && materials[y, x] < 0) return null;

int stepX = Math.Sign(directionX);
int stepY = Math.Sign(directionY);
Expand All @@ -79,12 +105,13 @@ public GridMap(int[,] materialIds, WallTexture[] textures)
bool crossX = stepX != 0 && (stepY == 0 || nextX <= nextY);
bool crossY = stepY != 0 && (stepX == 0 || nextY <= nextX);
double t = crossX ? nextX : nextY;
if (t > maxDistance) return null;

if (crossX) x += stepX;
if (crossY) y += stepY;
if (x < 0 || x >= Width || y < 0 || y >= Height)
return null;
if (IsSolid(x, y))
if (IsSolid(x, y) || (includeOpenDoors && materials[y, x] < 0))
return new RayHit(x, y, crossX ? WallSide.Vertical : WallSide.Horizontal, t);

// Compute from the original ray to avoid accumulating rounding at corners.
Expand Down
26 changes: 25 additions & 1 deletion src/RetroRaycaster.Core/LevelLoader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,14 +43,38 @@ public static (GridMap Map, PlayerState Spawn) Load(Stream stream, WallTexture b
'.' => 0,
'B' => 1,
'M' => 2,
'D' => DoorMaterial,
var symbol => throw new JsonException($"Unknown symbol '{symbol}' at row {y + 1}, column {x + 1}.")
};

var map = new GridMap(cells, [brick, metal]);
var map = new GridMap(cells, [brick, metal, DoorTexture], DoorMaterial);
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)));
}

private const int DoorMaterial = 3;
private static readonly WallTexture DoorTexture = CreateDoorTexture();

private static WallTexture CreateDoorTexture()
{
var pixels = new uint[32, 32];
for (int y = 0; y < 32; y++)
for (int x = 0; x < 32; x++)
{
// A timber door with a dark frame, cross braces and a brass latch.
pixels[y, x] = (x, y) switch
{
(< 2 or >= 30, _) or (_, < 2 or >= 30) => 0xFF41352D,
(>= 23 and <= 27, >= 15 and <= 17) => 0xFFFFCC52,
(_, 6 or 7 or 24 or 25) => 0xFF564337,
_ when x % 6 == 2 => 0xFF774827,
_ when (x / 6) % 2 == 0 => 0xFFC28345,
_ => 0xFFAD703D
};
}
return new WallTexture(pixels);
}
}
11 changes: 8 additions & 3 deletions src/RetroRaycaster.Core/PlayerMovement.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,15 +59,20 @@ internal static bool CanStandAt(GridMap map, double x, double y)

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)
if (map.IsSolid(col, row) && OverlapsCell(x, y, col, row))
return false;
}
return true;
}

internal static bool OverlapsCell(double x, double y, int col, int row)
{
if (y <= row - Radius || y >= row + 1 + Radius) return false;
double reach = ReachAtRow(y, row);
return x > col - reach && x < col + 1 + reach;
}

// At a corner only this cross-section of the circle reaches the wall.
private static double ReachAtRow(double across, int row)
{
Expand Down
3 changes: 2 additions & 1 deletion src/RetroRaycaster.Desktop/DemoForm.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@ public DemoForm(GridMap map, PlayerState spawn)
KeyDown += (_, e) =>
{
if (e.KeyCode == Keys.Escape) Close();
else pressed.Add(e.KeyCode);
else if (pressed.Add(e.KeyCode) && e.KeyCode == Keys.E)
map.TryToggleDoor(player);
};
KeyUp += (_, e) => pressed.Remove(e.KeyCode);
Deactivate += (_, _) => pressed.Clear();
Expand Down
2 changes: 1 addition & 1 deletion src/RetroRaycaster.Desktop/Levels/demo.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"BBBBBBBBBBBBBBB",
"B.............B",
"B.....MM......B",
"B.....MM......B",
"B...D.MM......B",
"B.........BBB.B",
"BBBBBBBBBBB.B.B",
"B...........B.B",
Expand Down
77 changes: 77 additions & 0 deletions tests/RetroRaycaster.Core.Tests/DoorTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
using System;
using System.IO;
using System.Text.Json;
using Xunit;

namespace RetroRaycaster.Core.Tests;

public class DoorTests
{
private static readonly WallTexture Wall = new(new uint[,] { { 0xFF808080 } });
private static readonly MovementInput Forward = new(1, 0, 0);

private static (GridMap Map, PlayerState Spawn) Load(params string[] rows)
{
var json = JsonSerializer.SerializeToUtf8Bytes(new { rows, spawn = new { x = 0.5, y = 0.5, angleDegrees = 0 } });
using var stream = new MemoryStream(json);
return LevelLoader.Load(stream, Wall, Wall);
}

[Fact]
public void DoorBlocksUntilOpenedAndCanBeClosedFromOtherSide()
{
var (map, spawn) = Load("..D..B");
Assert.Equal(2, map.CastRay(spawn.X, spawn.Y, 1, 0)?.CellX);
var blocked = PlayerMovement.Update(map, spawn, Forward, 1);
Assert.Equal(2 - PlayerMovement.Radius, blocked.X, 10);

Assert.True(map.TryToggleDoor(spawn)); // Exactly 1.5 units to the near face.
Assert.Equal(5, map.CastRay(spawn.X, spawn.Y, 1, 0)?.CellX);
var across = PlayerMovement.Update(map, spawn, Forward, 1) with { Angle = Math.PI };
Assert.Equal(3.5, across.X, 10);

Assert.True(map.TryToggleDoor(across));
Assert.Equal(2, map.CastRay(across.X, across.Y, -1, 0)?.CellX);
Assert.Equal(3 + PlayerMovement.Radius, PlayerMovement.Update(map, across, Forward, 1).X, 10);
}

[Theory]
[InlineData("...D.")] // Beyond reach.
[InlineData(".BD.")] // A brick wall hides a door within reach.
public void UnreachableDoorRemainsClosed(string row)
{
var (map, spawn) = Load(row);
Assert.False(map.TryToggleDoor(spawn));
Assert.Equal(row.IndexOf('D'), map.CastRay(row.Length - 0.5, 0.5, -1, 0)?.CellX);
}

[Fact]
public void RangeIsMeasuredAlongTheViewRay()
{
var (map, spawn) = Load("....", "..D.");
Assert.False(map.TryToggleDoor(spawn with { Angle = Math.PI / 6 }));
Assert.Equal(2, map.CastRay(spawn.X, spawn.Y, Math.Cos(Math.PI / 6), 0.5)?.CellX);
}

[Theory]
[InlineData(1.5, 1.5, 0)] // Center in the doorway.
[InlineData(0.9, 1.5, 0)] // Circle straddles the near face.
[InlineData(0.9, 0.9, 45)] // Circle overlaps only a corner.
public void OccupiedDoorCannotClose(double x, double y, double degrees)
{
var (map, _) = Load("...", ".D.");
Assert.True(map.TryToggleDoor(new PlayerState(0.5, 1.5, 0)));
Assert.False(map.TryToggleDoor(new PlayerState(x, y, degrees * Math.PI / 180)));
Assert.Null(map.CastRay(0.5, 1.5, 1, 0));
}

[Fact]
public void OpenDoorTakesPrecedenceOverClosedDoorBehindIt()
{
var (map, spawn) = Load(".DD.");
Assert.True(map.TryToggleDoor(spawn));
Assert.Equal(2, map.CastRay(spawn.X, spawn.Y, 1, 0)?.CellX);
Assert.True(map.TryToggleDoor(spawn));
Assert.Equal(1, map.CastRay(spawn.X, spawn.Y, 1, 0)?.CellX);
}
}
Loading