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
36 changes: 29 additions & 7 deletions src/RetroRaycaster.Core/GridMap.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,14 @@ public enum WallSide { Vertical, Horizontal }
/// <summary>A grid of unit cells. X increases rightward and Y downward.</summary>
public sealed class GridMap
{
private readonly bool[,] solid;
public int Width => solid.GetLength(1);
public int Height => solid.GetLength(0);
private readonly int[,] materials;
private readonly WallTexture[] textures = [];
public int Width => materials.GetLength(1);
public int Height => materials.GetLength(0);

internal bool IsSolid(int x, int y) => solid[y, x];
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];

/// <param name="solidCells">Rows indexed by [y, x]. True denotes a wall.</param>
public GridMap(bool[,] solidCells)
Expand All @@ -23,7 +26,26 @@ public GridMap(bool[,] solidCells)
if (solidCells.GetLength(0) == 0 || solidCells.GetLength(1) == 0)
throw new ArgumentException("The grid must contain at least one row and column.", nameof(solidCells));

solid = (bool[,])solidCells.Clone();
materials = new int[solidCells.GetLength(0), solidCells.GetLength(1)];
for (int y = 0; y < Height; y++)
for (int x = 0; x < Width; x++)
materials[y, x] = solidCells[y, x] ? 1 : 0;
}

/// <summary>Zero denotes empty space. Positive IDs select textures starting at one.</summary>
public GridMap(int[,] materialIds, WallTexture[] textures)
{
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.textures = (WallTexture[])textures.Clone();
foreach (var texture in this.textures)
ArgumentNullException.ThrowIfNull(texture);
foreach (int id in materials)
if (id < 0 || id > textures.Length)
throw new ArgumentOutOfRangeException(nameof(materialIds), "Unknown material ID.");
}

/// <summary>
Expand All @@ -44,7 +66,7 @@ public GridMap(bool[,] solidCells)

int x = (int)originX;
int y = (int)originY;
if (solid[y, x])
if (IsSolid(x, y))
throw new ArgumentException("A moving ray must start in an empty cell.");

int stepX = Math.Sign(directionX);
Expand All @@ -62,7 +84,7 @@ public GridMap(bool[,] solidCells)
if (crossY) y += stepY;
if (x < 0 || x >= Width || y < 0 || y >= Height)
return null;
if (solid[y, x])
if (IsSolid(x, y))
return new RayHit(x, y, crossX ? WallSide.Vertical : WallSide.Horizontal, t);

// Compute from the original ray to avoid accumulating rounding at corners.
Expand Down
32 changes: 28 additions & 4 deletions src/RetroRaycaster.Core/SoftwareRenderer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,9 @@ public static void Render(GridMap map, double cameraX, double cameraY, double an
{
double offset = 2 * (x + 0.5) / width - 1;
// The forward component stays one, so T measures perpendicular depth.
var hit = map.CastRay(cameraX, cameraY, forwardX + offset * planeX,
forwardY + offset * planeY);
double rayX = forwardX + offset * planeX;
double rayY = forwardY + offset * planeY;
var hit = map.CastRay(cameraX, cameraY, rayX, rayY);
if (hit is not RayHit wall)
continue;

Expand All @@ -54,9 +55,32 @@ public static void Render(GridMap map, double cameraX, double cameraY, double an
// Include row centers in the half-open interval [top, bottom).
int top = (int)Math.Ceiling(horizon - halfWall - 0.5);
int bottom = (int)Math.Ceiling(horizon + halfWall - 0.5);
uint color = wall.Side == WallSide.Vertical ? VerticalWallColor : HorizontalWallColor;
bool vertical = wall.Side == WallSide.Vertical;
var texture = map.TextureAtWall(wall.CellX, wall.CellY);
if (texture is null)
{
uint color = vertical ? VerticalWallColor : HorizontalWallColor;
for (int y = top; y < bottom; y++)
pixels[y * width + x] = color;
continue;
}

double along = vertical ? cameraY + rayY * wall.T : cameraX + rayX * wall.T;
int u = Math.Min(texture.Width - 1, (int)((along - Math.Floor(along)) * texture.Width));
// U increases to the viewer's right when facing each wall head-on.
if (vertical ? rayX < 0 : rayY > 0)
u = texture.Width - 1 - u;

// T / focalLength is the inverse *unclipped* projected wall height.
// At T = 0 the visible strip samples the middle of the texture.
double inverseHeight = wall.T / focalLength;
for (int y = top; y < bottom; y++)
pixels[y * width + x] = color;
{
double v = 0.5 + (y + 0.5 - horizon) * inverseHeight;
int row = Math.Clamp((int)(v * texture.Height), 0, texture.Height - 1);
uint color = texture[row, u];
pixels[y * width + x] = vertical ? color : (color & 0xFF000000u) | ((color & 0x00FEFEFEu) >> 1);
}
}
}
}
20 changes: 20 additions & 0 deletions src/RetroRaycaster.Core/WallTexture.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
using System;

namespace RetroRaycaster.Core;

/// <summary>Immutable ARGB texels indexed by row and column, starting at the top left.</summary>
public sealed class WallTexture
{
private readonly uint[,] pixels;
public int Width => pixels.GetLength(1);
public int Height => pixels.GetLength(0);
public uint this[int y, int x] => pixels[y, x];

public WallTexture(uint[,] pixels)
{
ArgumentNullException.ThrowIfNull(pixels);
if (pixels.Length == 0)
throw new ArgumentException("The texture must contain at least one texel.", nameof(pixels));
this.pixels = (uint[,])pixels.Clone();
}
}
10 changes: 5 additions & 5 deletions src/RetroRaycaster.Desktop/DemoForm.cs
Original file line number Diff line number Diff line change
Expand Up @@ -103,18 +103,18 @@ private static GridMap CreateMap()
[
"###############",
"#.............#",
"#.....##......#",
"#.....##......#",
"#.....MM......#",
"#.....MM......#",
"#.........###.#",
"###########.#.#",
"#...........#.#",
"#.............#",
"###############"
];
var walls = new bool[rows.Length, rows[0].Length];
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] == '#';
return new GridMap(walls);
walls[y, x] = rows[y][x] switch { '#' => 1, 'M' => 2, _ => 0 };
return new GridMap(walls, [DemoTextures.Brick, DemoTextures.Metal]);
}
}
41 changes: 41 additions & 0 deletions src/RetroRaycaster.Desktop/DemoTextures.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
using RetroRaycaster.Core;

namespace RetroRaycaster.Desktop;

internal static class DemoTextures
{
public static readonly WallTexture Brick = CreateBrick();
public static readonly WallTexture Metal = CreateMetal();

private static WallTexture CreateBrick()
{
var pixels = new uint[32, 32];
for (int y = 0; y < 32; y++)
{
int course = y / 8;
for (int x = 0; x < 32; x++)
{
int offsetX = x + 8 * (course % 2);
int joint = offsetX % 16;
uint clay = (course + offsetX / 16) % 2 == 0 ? 0xFFAD5842u : 0xFF99503Cu;
pixels[y, x] = y % 8 == 0 || joint == 0 ? 0xFF635851u :
y % 8 == 1 || joint == 1 ? 0xFFC47557u : clay;
}
}
return new WallTexture(pixels);
}

private static WallTexture CreateMetal()
{
var pixels = new uint[32, 32];
for (int y = 0; y < 32; y++)
for (int x = 0; x < 32; x++)
{
bool rivet = x is 3 or 28 && y is 3 or 28;
pixels[y, x] = x == 0 || y == 0 ? 0xFF344551u :
x == 1 || y == 1 || rivet ? 0xFFB5CAD1u :
y % 4 == 2 ? 0xFF708795u : 0xFF788D99u;
}
return new WallTexture(pixels);
}
}
59 changes: 59 additions & 0 deletions tests/RetroRaycaster.Core.Tests/TexturedWallTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
using System;
using Xunit;

namespace RetroRaycaster.Core.Tests;

public class TexturedWallTests
{
private static readonly WallTexture Pattern = new(new uint[,]
{
{ 0xFF100000, 0xFF200000, 0xFF300000, 0xFF400000 },
{ 0xFF001000, 0xFF002000, 0xFF003000, 0xFF004000 },
{ 0xFF122434, 0xFF244668, 0xFF36689A, 0xFF488ACE },
{ 0xFF000010, 0xFF000020, 0xFF000030, 0xFF000040 }
});

[Theory]
[InlineData(0, 0xFF36689Au)] // East: impact Y = 1.61, column 2.
[InlineData(2, 0xFF488ACEu)] // West: impact Y = 1.21, mirrored column 3.
[InlineData(1, 0xFF244567u)] // South: impact X = 1.09, mirrored column 3, shaded.
[InlineData(3, 0xFF122334u)] // North: impact X = 1.49, column 1, shaded.
public void ObliqueRaySamplesOrientedFace(int quarterTurns, uint expected)
{
var map = new GridMap(new int[,] { { 1, 1, 1 }, { 1, 0, 1 }, { 1, 1, 1 } }, [Pattern]);
var pixels = new uint[5 * 3];
SoftwareRenderer.Render(map, 1.35, 1.35, quarterTurns * Math.PI / 2, Math.PI / 2, 5, 3, pixels);
Assert.Equal(expected, pixels[1 * 5 + 3]);
}

[Fact]
public void AdjacentCellsSelectDifferentMaterialsInOneFrame()
{
var second = new WallTexture(new uint[,] { { 0xFFABCDEF } });
var map = new GridMap(new int[,] { { 0, 1 }, { 0, 2 } }, [Pattern, second]);
var pixels = new uint[3];
SoftwareRenderer.Render(map, 0.5, 1, 0, Math.PI / 2, 3, 1, pixels);
Assert.Equal(new uint[] { 0xFF36689A, 0xFFABCDEF, 0xFFABCDEF }, pixels);
}

[Fact]
public void CloseWallShowsOnlyMiddleTexels()
{
var map = new GridMap(new int[,] { { 0, 1 } }, [Pattern]);
var pixels = new uint[5 * 4];
// The wall projects to ten rows. Only the four central rows fit on screen.
SoftwareRenderer.Render(map, 0.75, 0.4, 0, Math.PI / 2, 5, 4, pixels);
Assert.Equal(new uint[] { 0xFF002000, 0xFF002000, 0xFF244668, 0xFF244668 },
new[] { pixels[2], pixels[7], pixels[12], pixels[17] });
}

[Theory]
[InlineData(1)]
[InlineData(2)]
public void EitherMaterialStopsMovement(int material)
{
var map = new GridMap(new int[,] { { 0, material, 0 } }, [Pattern, Pattern]);
var player = PlayerMovement.Update(map, new PlayerState(0.5, 0.5, 0), new MovementInput(1, 0, 0), 1);
Assert.Equal(1 - PlayerMovement.Radius, player.X, 10);
}
}
Loading