using System; using System.Diagnostics; using System.Runtime.InteropServices; using…
- User
using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Collections.Generic;
namespace ConsoleRaycastMaze { class Program { // Screen dimensions static int screenWidth; static int screenHeight;
static int BaseSeed = Random.Shared.Next(1, 10000000); // Map storage using a dictionary to support an infinite map static Dictionary<(int, int), char> map = new Dictionary<(int, int), char>(); // Player variables static double posX = 0.0, posY = 0.0; // Player position starts at (0,0) static double dirX = 1.0, dirY = 0.0; // Player direction (facing right initially) static double planeX = 0, planeY = 0.66; // Camera plane // Camera rotation angles static double pitch = 0.0; // Not used in rendering but tracked for potential future use static double yaw = 0.0; // Yaw is equivalent to dirX and dirY rotation // Timing static double time = 0; // Time of current frame static double oldTime = 0; // Time of previous frame // ANSI Escape Codes const string resetColor = "\u001b[0m"; // Minimap dimensions (restored to original aspect ratio) const int minimapSize = 10; // Debug information toggle static bool showUI = false; static bool wallTexture = true; // Enable ANSI escape codes on Windows [DllImport("kernel32.dll", SetLastError = true)] static extern IntPtr GetStdHandle(int nStdHandle); [DllImport("kernel32.dll")] static extern bool GetConsoleMode(IntPtr hConsoleHandle, out int lpMode); [DllImport("kernel32.dll")] static extern bool SetConsoleMode(IntPtr hConsoleHandle, int dwMode); const int STD_OUTPUT_HANDLE = -11; const int ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004; static void EnableANSIColors() { IntPtr handle = GetStdHandle(STD_OUTPUT_HANDLE); if (!GetConsoleMode(handle, out int mode)) { return; } mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING; SetConsoleMode(handle, mode); } static void Main(string[] args) { EnableANSIColors(); // Enable ANSI escape codes Console.CursorVisible = false; Console.Clear(); // Set initial window and buffer size //try //{ // Console.SetWindowSize(120, 40); // Console.SetBufferSize(120, 40); //} //catch //{ // // Ignore if setting window size fails due to system limitations //} screenWidth = Console.WindowWidth; screenHeight = Console.WindowHeight; // Initialize player's starting position to ensure adequate open space posX = 0.0; posY = 0.0; bool doneGenerating = false; while (!doneGenerating) { try { InitializePlayerStartingArea(); doneGenerating = true; } catch (Exception) { } } Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); while (true) { // Handle window resizing if (screenWidth != Console.WindowWidth || screenHeight != Console.WindowHeight) { screenWidth = Console.WindowWidth; screenHeight = Console.WindowHeight; try { Console.SetBufferSize(screenWidth, screenHeight); } catch { // Ignore if setting buffer size fails } } // Timing oldTime = time; time = stopwatch.Elapsed.TotalSeconds; double frameTime = time - oldTime; // Input ProcessInput(frameTime); // Render frame RenderFrame(); // Sleep to reduce CPU usage Thread.Sleep(1); } } /// <summary> /// Initializes a larger open area around the player's starting position /// to prevent immediate trapping. /// </summary> static void InitializePlayerStartingArea() { int baseX = (int)Math.Floor(posX); int baseY = (int)Math.Floor(posY); Random random = new Random(); // Define the radius of the open area int openRadius = 500; // Clear the base area for (int x = baseX - openRadius; x <= baseX + openRadius; x++) { for (int y = baseY - openRadius; y <= baseY + openRadius; y++) { map[(x, y)] = ' '; } } // Add random walls for (int x = baseX - openRadius + 1; x < baseX + openRadius; x++) { for (int y = baseY - openRadius + 1; y < baseY + openRadius; y++) { if (random.Next(100) < 30) // 30% chance of placing a wall { map[(x, y)] = '#'; } } } // Add random 3x3 rooms int numRooms = random.Next(3, 6); // 3 to 5 rooms for (int i = 0; i < numRooms; i++) { int roomX = random.Next(baseX - openRadius + 2, baseX + openRadius - 2); int roomY = random.Next(baseY - openRadius + 2, baseY + openRadius - 2); for (int x = roomX - 1; x <= roomX + 1; x++) { for (int y = roomY - 1; y <= roomY + 1; y++) { map[(x, y)] = ' '; // Clear the room area } } } // Ensure the player's starting position is clear map[(baseX, baseY)] = ' '; // Add walls around the perimeter for (int x = baseX - openRadius - 1; x <= baseX + openRadius + 1; x++) { for (int y = baseY - openRadius - 1; y <= baseY + openRadius + 1; y++) { if (Math.Abs(x - baseX) == openRadius + 1 || Math.Abs(y - baseY) == openRadius + 1) { map[(x, y)] = '#'; } } } } static void ProcessInput(double frameTime) { double moveSpeed = frameTime * 5.0; // squares per second double rotSpeed = frameTime * 2.0; // radians per second while (Console.KeyAvailable) { ConsoleKeyInfo ki = Console.ReadKey(true); var key = ki.Key; bool shift = ki.Modifiers == ConsoleModifiers.Shift; var mult = shift ? 0.2 : 1; moveSpeed *= mult; rotSpeed *= mult; if (key == ConsoleKey.W || key == ConsoleKey.UpArrow) { if (IsPositionEmpty(posX + dirX * moveSpeed, posY)) posX += dirX * moveSpeed; if (IsPositionEmpty(posX, posY + dirY * moveSpeed)) posY += dirY * moveSpeed; EnsureMapAroundPlayer(); } if (key == ConsoleKey.S || key == ConsoleKey.DownArrow) { if (IsPositionEmpty(posX - dirX * moveSpeed, posY)) posX -= dirX * moveSpeed; if (IsPositionEmpty(posX, posY - dirY * moveSpeed)) posY -= dirY * moveSpeed; EnsureMapAroundPlayer(); } if (key == ConsoleKey.A) { // Move left (strafe) relative to yaw double perpDirX = Math.Cos(yaw - Math.PI / 2); double perpDirY = Math.Sin(yaw - Math.PI / 2); if (IsPositionEmpty(posX + perpDirX * moveSpeed, posY)) posX += perpDirX * moveSpeed; if (IsPositionEmpty(posX, posY + perpDirY * moveSpeed)) posY += perpDirY * moveSpeed; EnsureMapAroundPlayer(); } if (key == ConsoleKey.D) { // Move right (strafe) relative to yaw double perpDirX = Math.Cos(yaw + Math.PI / 2); double perpDirY = Math.Sin(yaw + Math.PI / 2); if (IsPositionEmpty(posX + perpDirX * moveSpeed, posY)) posX += perpDirX * moveSpeed; if (IsPositionEmpty(posX, posY + perpDirY * moveSpeed)) posY += perpDirY * moveSpeed; EnsureMapAroundPlayer(); } if (key == ConsoleKey.LeftArrow) { // Rotate left (Yaw) Rotate(-rotSpeed); } if (key == ConsoleKey.RightArrow) { // Rotate right (Yaw) Rotate(rotSpeed); } if (key == ConsoleKey.F1) { // Toggle debug information showUI = !showUI; } if (key == ConsoleKey.Escape) { Environment.Exit(0); } if (key == ConsoleKey.R) { BaseSeed = Random.Shared.Next(1, 100000000); } if (key == ConsoleKey.G) { wallTexture = !wallTexture; } } } static bool IsPositionEmpty(double x, double y) { int mapX = (int)Math.Floor(x); int mapY = (int)Math.Floor(y); if (map.ContainsKey((mapX, mapY))) return map[(mapX, mapY)] == ' '; else return false; // Treat unknown areas as walls } static void Rotate(double angle) { double oldDirX = dirX; dirX = dirX * Math.Cos(angle) - dirY * Math.Sin(angle); dirY = oldDirX * Math.Sin(angle) + dirY * Math.Cos(angle); // Update camera plane based on new direction double oldPlaneX = planeX; planeX = planeX * Math.Cos(angle) - planeY * Math.Sin(angle); planeY = oldPlaneX * Math.Sin(angle) + planeY * Math.Cos(angle); yaw += angle; // Keep yaw within 0 to 2*PI yaw %= 2 * Math.PI; if (yaw < 0) yaw += 2 * Math.PI; } static void RenderFrame() { StringBuilder sb = new StringBuilder(); // Initialize a 2D character array for the screen char[,] screenBuffer = new char[screenHeight, screenWidth]; string[,] colorBuffer = new string[screenHeight, screenWidth]; // Fill screen buffer with default characters and colors for (int y = 0; y < screenHeight; y++) for (int x = 0; x < screenWidth; x++) { screenBuffer[y, x] = ' '; colorBuffer[y, x] = "\u001b[0m"; // Reset color } // Raycasting for (int x = 0; x < screenWidth; x++) { // Calculate ray position and direction double cameraX = 2 * x / (double)screenWidth - 1; // x-coordinate in camera space double rayDirX = dirX + planeX * cameraX; double rayDirY = dirY + planeY * cameraX; // Which box of the map we're in int mapX = (int)Math.Floor(posX); int mapY = (int)Math.Floor(posY); // Length of ray from current position to next x or y-side double sideDistX; double sideDistY; // Length of ray from one x or y-side to next x or y-side double deltaDistX = (rayDirX == 0) ? 1e30 : Math.Abs(1 / rayDirX); double deltaDistY = (rayDirY == 0) ? 1e30 : Math.Abs(1 / rayDirY); double perpWallDist; // What direction to step in x or y-direction (either +1 or -1) int stepX, stepY; bool hit = false; // Was a wall hit? int side = 0; // Was the wall vertical or horizontal? // Calculate step and initial sideDist if (rayDirX < 0) { stepX = -1; sideDistX = (posX - mapX) * deltaDistX; } else { stepX = 1; sideDistX = (mapX + 1.0 - posX) * deltaDistX; } if (rayDirY < 0) { stepY = -1; sideDistY = (posY - mapY) * deltaDistY; } else { stepY = 1; sideDistY = (mapY + 1.0 - posY) * deltaDistY; } // Perform DDA while (!hit) { // Jump to next map square, either in x-direction or y-direction if (sideDistX < sideDistY) { sideDistX += deltaDistX; mapX += stepX; side = 0; } else { sideDistY += deltaDistY; mapY += stepY; side = 1; } // Check if ray has hit a wall if (map.ContainsKey((mapX, mapY))) { if (map[(mapX, mapY)] == '#') hit = true; } else { // Generate new map area on-the-fly to simulate infinite map //GenerateMapArea(mapX, mapY); if (map.ContainsKey((mapX, mapY)) && map[(mapX, mapY)] == '#') hit = true; else hit = true; // Treat unknown areas as walls } } // Calculate distance to the point of impact if (side == 0) perpWallDist = (sideDistX - deltaDistX); else perpWallDist = (sideDistY - deltaDistY); // Calculate height of line to draw on screen int lineHeight = (int)(screenHeight / perpWallDist); // Calculate lowest and highest pixel to fill in current stripe int drawStart = Math.Max(-lineHeight / 2 + screenHeight / 2, 0); int drawEnd = Math.Min(lineHeight / 2 + screenHeight / 2, screenHeight - 1); if (wallTexture) { // Base color components for #9e9a56 int baseR = 158; // 0x9e int baseG = 154; // 0x9a int baseB = 86; // 0x56 // Adjust color intensity based on distance float distanceFactor = (float)Math.Clamp(1.0 / (perpWallDist * 1.5), 0.0, 1.0); int colorR = (int)(baseR * distanceFactor); int colorG = (int)(baseG * distanceFactor); int colorB = (int)(baseB * distanceFactor); string baseWallColor = $"\u001b[38;2;{colorR};{colorG};{colorB}m"; string darkWallColor = $"\u001b[38;2;{Math.Max(colorR - 30, 0)};{Math.Max(colorG - 30, 0)};{Math.Max(colorB - 30, 0)}m"; // Darken colors for y-sides to add depth if (side == 1) { colorR = Math.Max(colorR - 30, 0); colorG = Math.Max(colorG - 30, 0); colorB = Math.Max(colorB - 30, 0); baseWallColor = $"\u001b[38;2;{colorR};{colorG};{colorB}m"; darkWallColor = $"\u001b[38;2;{Math.Max(colorR - 20, 0)};{Math.Max(colorG - 20, 0)};{Math.Max(colorB - 20, 0)}m"; } for (int y = drawStart; y <= drawEnd; y++) { if (y >= 0 && y < screenHeight && x >= 0 && x < screenWidth) { // Create a simple pattern bool isAlternateColor = ((y + x) % 2 == 0); // Set wall color and pattern colorBuffer[y, x] = isAlternateColor ? darkWallColor : baseWallColor; screenBuffer[y, x] = isAlternateColor ? '█' : '█'; // Different characters for texture } } } else { // Base color components for #9e9a56 int baseR = 158; // 0x9e int baseG = 154; // 0x9a int baseB = 86; // 0x56 // Adjust color intensity based on distance float distanceFactor = (float)Math.Clamp(1.0 / (perpWallDist * 1.5), 0.0, 1.0); int colorR = (int)(baseR * distanceFactor); int colorG = (int)(baseG * distanceFactor); int colorB = (int)(baseB * distanceFactor); string wallColor = $"\u001b[38;2;{colorR};{colorG};{colorB}m"; // Darken colors for y-sides to add depth if (side == 1) { colorR = Math.Max(colorR - 30, 0); colorG = Math.Max(colorG - 30, 0); colorB = Math.Max(colorB - 30, 0); wallColor = $"\u001b[38;2;{colorR};{colorG};{colorB}m"; } for (int y = drawStart; y <= drawEnd; y++) { if (y >= 0 && y < screenHeight && x >= 0 && x < screenWidth) { // Set wall color colorBuffer[y, x] = wallColor; screenBuffer[y, x] = '\u2588'; // Full block character } } } // Ceiling: Square Tiles Texture (3x3 Grid) for (int y = 0; y < drawStart; y++) { if (y >= 0 && y < screenHeight && x >= 0 && x < screenWidth) { // Determine if the current position is on a grid line bool isVerticalLine = (x % 3 == 0); bool isHorizontalLine = (y % 3 == 0); if (isVerticalLine && isHorizontalLine) { // Intersection of vertical and horizontal lines colorBuffer[y, x] = "\u001b[38;2;70;70;70m"; // Dark Gray for intersections } else if (isVerticalLine || isHorizontalLine) { // Vertical or Horizontal grid lines colorBuffer[y, x] = "\u001b[38;2;100;100;100m"; // Medium Gray for lines } else { // Tile Color colorBuffer[y, x] = "\u001b[38;2;111;99;39m"; // Original Ceiling Color } screenBuffer[y, x] = '\u2588'; // Full block character } } // Floor: Carpet-like Texture (Darker Patches Every 3 Pixels) for (int y = drawEnd + 1; y < screenHeight; y++) { if (y >= 0 && y < screenHeight && x >= 0 && x < screenWidth) { // Determine if the current position should have a darker patch bool isDarkPatch = ((x + y) % 6 < 2); // Adjust the modulus for pattern density if (isDarkPatch) { // Darker Carpet Patch colorBuffer[y, x] = "\u001b[38;2;80;60;20m"; // Darker Brown for patches } else { // Base Floor Color colorBuffer[y, x] = "\u001b[38;2;101;84;30m"; // Original Floor Color } screenBuffer[y, x] = '\u2588'; // Full block character } } } if (showUI) { // Overlay Minimap at bottom-right corner RenderMinimap(screenBuffer, colorBuffer); // Overlay Debug Information at bottom-left corner RenderDebugInfo(screenBuffer, colorBuffer); } // Build the final string with colors for (int y = 0; y < screenHeight; y++) { for (int x = 0; x < screenWidth; x++) { sb.Append($"{colorBuffer[y, x]}{screenBuffer[y, x]}"); } sb.Append(resetColor); // Reset color at end of line if (y != screenHeight - 1) { sb.Append('\n'); } } // Output to console try { Console.SetCursorPosition(0, 0); Console.Write(sb.ToString()); } catch (ArgumentOutOfRangeException) { // Handle potential exceptions when writing outside the buffer } } /// <summary> /// Restores the minimap to its original aspect ratio without horizontal stretching. /// </summary> static void RenderMinimap(char[,] screenBuffer, string[,] colorBuffer) { int minimapWidth = minimapSize; // Original width int minimapHeight = minimapSize; // Calculate top-left corner of minimap at bottom-right int startX = screenWidth - minimapWidth - 2; // 2 characters padding from right int startY = screenHeight - minimapHeight - 1; // 1 line padding from bottom bool playerAdded = false; for (int y = 0; y < minimapHeight; y++) { for (int x = 0; x < minimapWidth; x++) { int mapX = (int)(posX - minimapWidth / 2 + x); int mapY = (int)(posY - minimapHeight / 2 + y); if (mapX == (int)posX && mapY == (int)posY && !playerAdded) { // Player position on minimap: Bright Green 'P' if (IsWithinScreen(startX + x, startY + y)) { colorBuffer[startY + y, startX + x] = "\u001b[38;2;0;255;0m"; // Bright Green screenBuffer[startY + y, startX + x] = 'P'; playerAdded = true; } } else if (map.ContainsKey((mapX, mapY))) { if (map[(mapX, mapY)] == '#') { // Wall on minimap: White '#' if (IsWithinScreen(startX + x, startY + y)) { colorBuffer[startY + y, startX + x] = "\u001b[38;2;255;255;255m"; // White screenBuffer[startY + y, startX + x] = '#'; } } else { // Empty space on minimap: Light Gray '.' if (IsWithinScreen(startX + x, startY + y)) { colorBuffer[startY + y, startX + x] = "\u001b[38;2;200;200;200m"; // Light Gray screenBuffer[startY + y, startX + x] = '.'; } } } else { // Outside map bounds: Render space if (IsWithinScreen(startX + x, startY + y)) { colorBuffer[startY + y, startX + x] = "\u001b[0m"; // Reset color screenBuffer[startY + y, startX + x] = ' '; } } } } } static void RenderDebugInfo(char[,] screenBuffer, string[,] colorBuffer) { string posInfo = $"Pos: X={posX:F2}, Y={posY:F2}"; string rotInfo = $"Yaw: {yaw * (180 / Math.PI):F2}° Pitch: {pitch * (180 / Math.PI):F2}°"; for (int i = 0; i < posInfo.Length && i < screenWidth; i++) { if (IsWithinScreen(i, screenHeight - 2)) { colorBuffer[screenHeight - 2, i] = "\u001b[38;2;255;255;0m"; // Yellow screenBuffer[screenHeight - 2, i] = posInfo[i]; } } for (int i = 0; i < rotInfo.Length && i < screenWidth; i++) { if (IsWithinScreen(i, screenHeight - 1)) { colorBuffer[screenHeight - 1, i] = "\u001b[38;2;255;255;0m"; // Yellow screenBuffer[screenHeight - 1, i] = rotInfo[i]; } } } static bool IsWithinScreen(int x, int y) { return x >= 0 && x < screenWidth && y >= 0 && y < screenHeight; } /// <summary> /// Ensures that the map is generated around the player's current position. /// Expands the map dynamically as the player moves. /// </summary> static void EnsureMapAroundPlayer() { int baseX = (int)Math.Floor(posX); int baseY = (int)Math.Floor(posY); // Define the radius around the player to generate the map int generationRadius = 10; for (int x = baseX - generationRadius; x <= baseX + generationRadius; x++) { for (int y = baseY - generationRadius; y <= baseY + generationRadius; y++) { if (!map.ContainsKey((x, y))) { map[(x, y)] = ' '; // Keep central area open } } } } }}
make the textures of the ceiling and floor move and transform relative to the position and rotation, so the grid on the ceiling and carpet on floor appear as if they were really there and not only static textures. same with the wall texture.
- Assistant
To create a more immersive and dynamic environment in your console-based raycast maze, you can enhance the ceiling, floor, and wall textures to respond to the player's movement and rotation. This involves transforming the textures based on the player's position and viewing direction, making them appear as if they're part of a real, cohesive 3D environment rather than static patterns.
Here's a step-by-step guide to achieve this, including modified code snippets:
1. Understanding the Current Rendering
Currently, your
RenderFramemethod handles rendering the walls, ceiling, and floor with static patterns:- Walls: Rendered with alternating characters and colors to simulate texture.
- Ceiling: Rendered with a static 3x3 grid pattern.
- Floor: Rendered with a static carpet-like pattern.
These textures don't respond to the player's movement or rotation, making them appear static from the player's perspective.
2. Dynamic Texture Mapping
To make textures dynamic:
- Walls: Use the exact hit position from the raycasting to determine the texture pattern.
- Ceiling and Floor: Calculate the world coordinates corresponding to each pixel and use these to vary the texture based on the player's current position and orientation.
3. Implementing Dynamic Wall Textures
Modify the wall rendering section to use the exact hit position for texture variation. This can be done by computing the exact point where the ray hits the wall and using its coordinates to determine the texture.
Modified Wall Rendering:
// After determining mapX and mapY in the DDA loop // Calculate the exact hit position double hitX, hitY; if (side == 0) { hitX = posY + perpWallDist * rayDirY; hitY = posX; } else { hitX = posY; hitY = posX + perpWallDist * rayDirX; } // Calculate texture coordinate int texX = (int)((side == 0 ? hitX % 1.0 : hitY % 1.0) * 3); // Assuming a 3x3 grid // Use texX to vary the wall texture bool isAlternateColor = (texX % 2 == 0); colorBuffer[y, x] = isAlternateColor ? darkWallColor : baseWallColor; screenBuffer[y, x] = '█';4. Implementing Dynamic Ceiling and Floor Textures
To make the ceiling and floor textures dynamic, you need to calculate the world coordinates for each pixel and adjust the texture based on these coordinates relative to the player's position and orientation.
Dynamic Floor and Ceiling Casting:
for (int y = 0; y < screenHeight; y++) { for (int x = 0; x < screenWidth; x++) { if (y < drawStart) // Ceiling { // Calculate the position on the ceiling double p = y / (double)screenHeight; double posZ = 0.5; // Ceiling height double rayDirX0 = dirX - planeX; double rayDirY0 = dirY - planeY; double rayDirX1 = dirX + planeX; double rayDirY1 = dirY + planeY; double floorStepX = rayDirX1 - rayDirX0; double floorStepY = rayDirY1 - rayDirY0; double floorX = posX + p * floorStepX; double floorY = posY + p * floorStepY; int texFloorX = (int)(floorX * 3) % 3; // 3x3 grid int texFloorY = (int)(floorY * 3) % 3; if (texFloorX < 0) texFloorX += 3; if (texFloorY < 0) texFloorY += 3; // Determine texture based on position bool isVerticalLine = (texFloorX == 0 || texFloorX == 2); bool isHorizontalLine = (texFloorY == 0 || texFloorY == 2); if (isVerticalLine && isHorizontalLine) { colorBuffer[y, x] = "\u001b[38;2;70;70;70m"; // Intersection color } else if (isVerticalLine || isHorizontalLine) { colorBuffer[y, x] = "\u001b[38;2;100;100;100m"; // Line color } else { colorBuffer[y, x] = "\u001b[38;2;111;99;39m"; // Tile color } screenBuffer[y, x] = '\u2588'; // Full block character } else if (y > drawEnd) // Floor { // Calculate the position on the floor double p = y / (double)screenHeight; double posZ = 0.5; // Floor height double rayDirX0 = dirX - planeX; double rayDirY0 = dirY - planeY; double rayDirX1 = dirX + planeX; double rayDirY1 = dirY + planeY; double floorStepX = rayDirX1 - rayDirX0; double floorStepY = rayDirY1 - rayDirY0; double floorX = posX + p * floorStepX; double floorY = posY + p * floorStepY; int texFloorX = (int)(floorX * 3) % 3; // 3x3 grid int texFloorY = (int)(floorY * 3) % 3; if (texFloorX < 0) texFloorX += 3; if (texFloorY < 0) texFloorY += 3; // Determine texture based on position bool isDarkPatch = ((texFloorX + texFloorY) % 2 == 0); if (isDarkPatch) { colorBuffer[y, x] = "\u001b[38;2;80;60;20m"; // Darker Floor Patch } else { colorBuffer[y, x] = "\u001b[38;2;101;84;30m"; // Base Floor Color } screenBuffer[y, x] = '\u2588'; // Full block character } } }Explanation:
-
Ceiling Rendering:
- Calculate the position on the ceiling based on the current pixel's vertical position.
- Determine the texture coordinates (
texFloorX,texFloorY) by scaling the world coordinates. - Use these coordinates to decide which part of the texture to render, creating a dynamic grid that moves and rotates with the player.
-
Floor Rendering:
- Similar to the ceiling, calculate the position on the floor.
- Determine if the current position should display a dark patch or the base floor color based on the texture coordinates.
5. Integrating with the Existing RenderFrame
Integrate the above changes into your existing
RenderFramemethod. Here's the modifiedRenderFramewith dynamic ceiling and floor textures:static void RenderFrame() { StringBuilder sb = new StringBuilder(); // Initialize a 2D character array for the screen char[,] screenBuffer = new char[screenHeight, screenWidth]; string[,] colorBuffer = new string[screenHeight, screenWidth]; // Fill screen buffer with default characters and colors for (int y = 0; y < screenHeight; y++) for (int x = 0; x < screenWidth; x++) { screenBuffer[y, x] = ' '; colorBuffer[y, x] = "\u001b[0m"; // Reset color } // Raycasting for (int x = 0; x < screenWidth; x++) { // ... [Existing Raycasting Code] ... // Calculate distance to the point of impact if (side == 0) perpWallDist = (sideDistX - deltaDistX); else perpWallDist = (sideDistY - deltaDistY); // Calculate height of line to draw on screen int lineHeight = (int)(screenHeight / perpWallDist); // Calculate lowest and highest pixel to fill in current stripe int drawStart = Math.Max(-lineHeight / 2 + screenHeight / 2, 0); int drawEnd = Math.Min(lineHeight / 2 + screenHeight / 2, screenHeight - 1); // Dynamic Wall Texture // [Insert Dynamic Wall Texture Code Here] // Dynamic Ceiling and Floor Textures for (int y = 0; y < screenHeight; y++) { if (y < drawStart) // Ceiling { // [Insert Dynamic Ceiling Texture Code Here] } else if (y > drawEnd) // Floor { // [Insert Dynamic Floor Texture Code Here] } } } if (showUI) { // Overlay Minimap and Debug Info RenderMinimap(screenBuffer, colorBuffer); RenderDebugInfo(screenBuffer, colorBuffer); } // Build the final string with colors for (int y = 0; y < screenHeight; y++) { for (int x = 0; x < screenWidth; x++) { sb.Append($"{colorBuffer[y, x]}{screenBuffer[y, x]}"); } sb.Append(resetColor); // Reset color at end of line if (y != screenHeight - 1) { sb.Append('\n'); } } // Output to console try { Console.SetCursorPosition(0, 0); Console.Write(sb.ToString()); } catch (ArgumentOutOfRangeException) { // Handle potential exceptions when writing outside the buffer } }6. Optimizing Texture Calculations
To further optimize the texture calculations:
- Cache Repeated Calculations: Precompute values that don't change within loops.
- Use Bitwise Operations: For patterns, bitwise operations can quickly determine alternate textures.
- Limit Texture Resolution: Keep texture patterns simple to maintain performance in the console.
7. Additional Enhancements
-
Texture Rotation: To make textures rotate with the player's view, apply rotation transformations to the texture coordinates.
double cosYaw = Math.Cos(yaw); double sinYaw = Math.Sin(yaw); // Rotate floor and ceiling coordinates double rotatedFloorX = floorX * cosYaw - floorY * sinYaw; double rotatedFloorY = floorX * sinYaw + floorY * cosYaw; int texFloorX = (int)(rotatedFloorX * 3) % 3; int texFloorY = (int)(rotatedFloorY * 3) % 3; -
Dynamic Wall Shading: Adjust wall colors based on the angle of the wall relative to the player's view to simulate lighting and depth.
-
Textures Based on Direction: Use different textures for walls facing different directions (e.g., north, south, east, west).
8. Final Code Integration
Here's the complete
RenderFramemethod with dynamic textures integrated:static void RenderFrame() { StringBuilder sb = new StringBuilder(); // Initialize a 2D character array for the screen char[,] screenBuffer = new char[screenHeight, screenWidth]; string[,] colorBuffer = new string[screenHeight, screenWidth]; // Fill screen buffer with default characters and colors for (int y = 0; y < screenHeight; y++) for (int x = 0; x < screenWidth; x++) { screenBuffer[y, x] = ' '; colorBuffer[y, x] = "\u001b[0m"; // Reset color } // Raycasting for (int x = 0; x < screenWidth; x++) { // Calculate ray position and direction double cameraX = 2 * x / (double)screenWidth - 1; // x-coordinate in camera space double rayDirX = dirX + planeX * cameraX; double rayDirY = dirY + planeY * cameraX; // Which box of the map we're in int mapX = (int)Math.Floor(posX); int mapY = (int)Math.Floor(posY); // Length of ray from current position to next x or y-side double sideDistX; double sideDistY; // Length of ray from one x or y-side to next x or y-side double deltaDistX = (rayDirX == 0) ? 1e30 : Math.Abs(1 / rayDirX); double deltaDistY = (rayDirY == 0) ? 1e30 : Math.Abs(1 / rayDirY); double perpWallDist; // What direction to step in x or y-direction (either +1 or -1) int stepX, stepY; bool hit = false; // Was a wall hit? int side = 0; // Was the wall vertical or horizontal? // Calculate step and initial sideDist if (rayDirX < 0) { stepX = -1; sideDistX = (posX - mapX) * deltaDistX; } else { stepX = 1; sideDistX = (mapX + 1.0 - posX) * deltaDistX; } if (rayDirY < 0) { stepY = -1; sideDistY = (posY - mapY) * deltaDistY; } else { stepY = 1; sideDistY = (mapY + 1.0 - posY) * deltaDistY; } // Perform DDA while (!hit) { // Jump to next map square, either in x-direction or y-direction if (sideDistX < sideDistY) { sideDistX += deltaDistX; mapX += stepX; side = 0; } else { sideDistY += deltaDistY; mapY += stepY; side = 1; } // Check if ray has hit a wall if (map.ContainsKey((mapX, mapY))) { if (map[(mapX, mapY)] == '#') hit = true; } else { // Treat unknown areas as walls hit = true; } } // Calculate distance to the point of impact if (side == 0) perpWallDist = (sideDistX - deltaDistX); else perpWallDist = (sideDistY - deltaDistY); // Calculate height of line to draw on screen int lineHeight = (int)(screenHeight / perpWallDist); // Calculate lowest and highest pixel to fill in current stripe int drawStart = Math.Max(-lineHeight / 2 + screenHeight / 2, 0); int drawEnd = Math.Min(lineHeight / 2 + screenHeight / 2, screenHeight - 1); // Dynamic Wall Texture // Calculate the exact hit position double hitX, hitY; if (side == 0) { hitX = posY + perpWallDist * rayDirY; hitY = posX; } else { hitX = posY; hitY = posX + perpWallDist * rayDirX; } // Calculate texture coordinate int texX = (int)((side == 0 ? hitX % 1.0 : hitY % 1.0) * 3) % 3; // 3x3 grid if (texX < 0) texX += 3; bool isAlternateColorWall = (texX % 2 == 0); // Base color components for #9e9a56 int baseR = 158; // 0x9e int baseG = 154; // 0x9a int baseB = 86; // 0x56 // Adjust color intensity based on distance float distanceFactor = (float)Math.Clamp(1.0 / (perpWallDist * 1.5), 0.0, 1.0); int colorR = (int)(baseR * distanceFactor); int colorG = (int)(baseG * distanceFactor); int colorB = (int)(baseB * distanceFactor); string baseWallColor = $"\u001b[38;2;{colorR};{colorG};{colorB}m"; string darkWallColor = $"\u001b[38;2;{Math.Max(colorR - 30, 0)};{Math.Max(colorG - 30, 0)};{Math.Max(colorB - 30, 0)}m"; // Darken colors for y-sides to add depth if (side == 1) { colorR = Math.Max(colorR - 30, 0); colorG = Math.Max(colorG - 30, 0); colorB = Math.Max(colorB - 30, 0); baseWallColor = $"\u001b[38;2;{colorR};{colorG};{colorB}m"; darkWallColor = $"\u001b[38;2;{Math.Max(colorR - 20, 0)};{Math.Max(colorG - 20, 0)};{Math.Max(colorB - 20, 0)}m"; } for (int y = drawStart; y <= drawEnd; y++) { if (y >= 0 && y < screenHeight && x >= 0 && x < screenWidth) { // Set wall color and pattern colorBuffer[y, x] = isAlternateColorWall ? darkWallColor : baseWallColor; screenBuffer[y, x] = '█'; } } // Dynamic Ceiling and Floor Textures for (int y = 0; y < screenHeight; y++) { if (y < drawStart) // Ceiling { // Calculate the position on the ceiling double p = y / (double)screenHeight; double posZ = 0.5; // Ceiling height double floorStepX = dirX + planeX * (2 * x / (double)screenWidth - 1); double floorStepY = dirY + planeY * (2 * x / (double)screenWidth - 1); double floorX = posX + perpWallDist * rayDirX; double floorY = posY + perpWallDist * rayDirY; // Rotate floor and ceiling based on yaw double cosYaw = Math.Cos(yaw); double sinYaw = Math.Sin(yaw); double rotatedFloorX = floorX * cosYaw - floorY * sinYaw; double rotatedFloorY = floorX * sinYaw + floorY * cosYaw; int texFloorX = (int)(rotatedFloorX * 3) % 3; // 3x3 grid int texFloorY = (int)(rotatedFloorY * 3) % 3; if (texFloorX < 0) texFloorX += 3; if (texFloorY < 0) texFloorY += 3; // Determine texture based on position bool isVerticalLine = (texFloorX == 0 || texFloorX == 2); bool isHorizontalLine = (texFloorY == 0 || texFloorY == 2); if (isVerticalLine && isHorizontalLine) { colorBuffer[y, x] = "\u001b[38;2;70;70;70m"; // Intersection color } else if (isVerticalLine || isHorizontalLine) { colorBuffer[y, x] = "\u001b[38;2;100;100;100m"; // Line color } else { colorBuffer[y, x] = "\u001b[38;2;111;99;39m"; // Tile color } screenBuffer[y, x] = '\u2588'; // Full block character } else if (y > drawEnd) // Floor { // Calculate the position on the floor double p = y / (double)screenHeight; double posZ = 0.5; // Floor height double floorStepX = dirX + planeX * (2 * x / (double)screenWidth - 1); double floorStepY = dirY + planeY * (2 * x / (double)screenWidth - 1); double floorX = posX + perpWallDist * rayDirX; double floorY = posY + perpWallDist * rayDirY; // Rotate floor and ceiling based on yaw double cosYaw = Math.Cos(yaw); double sinYaw = Math.Sin(yaw); double rotatedFloorX = floorX * cosYaw - floorY * sinYaw; double rotatedFloorY = floorX * sinYaw + floorY * cosYaw; int texFloorX = (int)(rotatedFloorX * 3) % 3; // 3x3 grid int texFloorY = (int)(rotatedFloorY * 3) % 3; if (texFloorX < 0) texFloorX += 3; if (texFloorY < 0) texFloorY += 3; // Determine texture based on position bool isDarkPatch = ((texFloorX + texFloorY) % 2 == 0); if (isDarkPatch) { colorBuffer[y, x] = "\u001b[38;2;80;60;20m"; // Darker Floor Patch } else { colorBuffer[y, x] = "\u001b[38;2;101;84;30m"; // Base Floor Color } screenBuffer[y, x] = '\u2588'; // Full block character } } } if (showUI) { // Overlay Minimap at bottom-right corner RenderMinimap(screenBuffer, colorBuffer); // Overlay Debug Information at bottom-left corner RenderDebugInfo(screenBuffer, colorBuffer); } // Build the final string with colors for (int y = 0; y < screenHeight; y++) { for (int x = 0; x < screenWidth; x++) { sb.Append($"{colorBuffer[y, x]}{screenBuffer[y, x]}"); } sb.Append(resetColor); // Reset color at end of line if (y != screenHeight - 1) { sb.Append('\n'); } } // Output to console try { Console.SetCursorPosition(0, 0); Console.Write(sb.ToString()); } catch (ArgumentOutOfRangeException) { // Handle potential exceptions when writing outside the buffer } }9. Testing and Optimization
After implementing the above changes:
- Test Movement and Rotation: Move and rotate the player to ensure that the ceiling and floor textures update dynamically.
- Adjust Texture Scaling: Modify the scaling factors (e.g., multiplication by
3in texture coordinates) to achieve the desired texture density. - Performance Tuning: If the rendering becomes slow, consider simplifying the texture calculations or reducing the resolution of the textures.
10. Final Thoughts
By following the above steps, you transform static textures into dynamic, responsive patterns that enhance the depth and realism of your console-based raycast maze. This approach leverages the player's position and orientation to adjust textures in real-time, providing a more engaging and believable 3D environment.
Feel free to further customize the textures, experiment with different patterns, and even introduce more complex shading techniques to refine the visual experience. Happy coding!