Appearance
Chapter 02: Drawing from One Pixel
In Chapter 01: The Project and the Host, you created the project, wrote the thin host and opened a black window. The window draws nothing yet.
In this chapter, you create one white pixel in code and draw the arena outline and the player dot from it. You also meet the first two renderers, which are classes that only draw.
| Figure 02-1: The chapter 02 window. A light grey arena outline with a cyan dot at its top-left corner. This is a drawn illustration, not a screenshot. |
Time: [TODO Simon: time estimate for chapter 02]
In this chapter, you will:
- Create a 1 x 1 white texture in code, with no content pipeline.
- Learn how
SpriteBatch.Begin,DrawandEndbatch work for the graphics card. - Write
PrimitiveDrawingwith three operations: a line, a path segment and a filled circle. - Write the first two renderers, for the arena outline and the player.
- Learn why renderers take what to draw as parameters and own no game state.
Requirements in this chapter
| ID | Short name |
|---|---|
| REN-01 | Every shape from one 1 x 1 texture with point sampling |
| PLT-03 | No content files (second half: the pixel) |
Screen coordinates
MonoGame measures positions from the top-left corner of the window. X grows to the right and Y grows downward. One unit is one pixel of the back buffer, which is the image the game draws into. The window in this course is 1024 pixels wide and 768 high. Figure 02-2 shows the axes and the rectangle the arena will occupy.
| Figure 02-2: Screen coordinates. The origin is at the top-left, Y grows downward, and the arena rectangle sits inside the 1024 x 768 window |
The game draws straight into this space, so a position in the game is also a position on screen. A point higher up the screen has a smaller Y. The cyan dot in the figure is centred only for illustration. In this chapter you place it at the arena's top-left corner, at (50, 122).
One pixel, scaled and rotated
A texture is an image held in graphics memory. The game needs only one texture, a single white pixel. SpriteBatch.Draw can stretch a texture to any size, rotate it, and tint it with a colour. A white pixel tinted cyan is cyan, and the same pixel stretched is a rectangle of any size.
Figure 02-3 shows the three shapes this chapter draws. A rectangle is the pixel stretched to a width and a height. A line is a rectangle as long as the line, rotated to the angle of the line. A circle is a stack of one pixel tall rectangles, one for each row, each as wide as the circle is at that row.
| Figure 02-3: One 1 x 1 white texture becomes a rectangle, a rotated line, and a circle made of horizontal rows |
The pixel is built in code, so the game needs no image file. This is why the content project from Chapter 01 stays empty (PLT-03).
Sprite batching and point sampling
Sending each shape to the graphics card on its own would be slow. A SpriteBatch collects shapes between a call to Begin and a call to End, then sends them together. The game calls Begin once per frame, draws everything, and calls End once.
A sampler decides which colour the card reads from a texture when the texture is stretched. Linear sampling blends the colour of neighbouring texels, which makes a stretched image smooth. Point sampling reads the nearest texel and does not blend. This game wants hard edges, so Begin is given SamplerState.PointClamp. With linear sampling, the edges of a 2 pixel line would blur into the pixels beside them.
What a renderer is
A renderer is a class with a Draw method. The method takes the batch, the pixel and the data to draw, and it draws. It reads state and never changes it. A renderer owns no graphics resources, because the host creates the batch and the pixel and is the one class that knows when to dispose of them.
This is the drawing half of a split that Chapter 05 completes. The rules live in classes that never draw, and the pictures live in classes that never decide anything. Each half can then change without the other.
Setting up
In a terminal, from the LastPerimeter folder, run the following two commands, one at a time. Each creates one folder. They are the same in PowerShell and bash.
text
mkdir Source/Rendering
mkdir Source/EntitiesCreating the pixel
The host creates the batch and the pixel. Both need the graphics device, which does not exist when the constructor runs. They are therefore created in LoadContent, which MonoGame calls once the device is ready, and the fields that hold them cannot be filled in the constructor.
NOTE
The two fields below are nullable for this chapter only. Chapter 05 replaces them with GameServices, which builds everything in one step, so you never need this pattern again. Do not copy it into later code.
Open Source/Game/LastPerimeterApp.cs. At the top, add the following line below the using Microsoft.Xna.Framework; line. It gives you SpriteBatch, Texture2D and SamplerState.
add-using Source/Game/LastPerimeterApp.cs
csharp
using Microsoft.Xna.Framework.Graphics;Add the following fields to the LastPerimeterApp class, below the _launchOptions field. The question mark after a type means the value may be null until LoadContent runs.
add-member Source/Game/LastPerimeterApp.cs after=_launchOptions
csharp
// Nullable for this chapter only, because LoadContent runs after the constructor.
// Chapter 05 replaces both with GameServices, which is built in one step.
private SpriteBatch? _spriteBatch;
private Texture2D? _pixel;Add the following method to the LastPerimeterApp class, above the Update method:
add-member Source/Game/LastPerimeterApp.cs before=Update
csharp
protected override void LoadContent()
{
_spriteBatch = new SpriteBatch(GraphicsDevice);
_pixel = CreatePixel(GraphicsDevice);
}Add the following method to the LastPerimeterApp class, above the ShouldAutoExit method. It makes a 1 x 1 texture and sets its single pixel to white.
add-member Source/Game/LastPerimeterApp.cs before=ShouldAutoExit
csharp
private static Texture2D CreatePixel(GraphicsDevice graphicsDevice)
{
Texture2D pixel = new(graphicsDevice, 1, 1);
pixel.SetData([Color.White]);
return pixel;
}The batch and the pixel hold graphics memory, so the host must release them. New to IDisposable? See the C# primer. Add the following method to the LastPerimeterApp class, above the CreatePixel method. MonoGame calls Dispose(bool) once, when the game ends.
add-member Source/Game/LastPerimeterApp.cs before=CreatePixel
csharp
protected override void Dispose(bool disposing)
{
if (disposing)
{
_pixel?.Dispose();
_spriteBatch?.Dispose();
}
base.Dispose(disposing);
}The key things to note are:
new Texture2D(device, 1, 1)makes a texture one pixel wide and one high.SetData([Color.White])fills it with white.Disposeuses?.(see the C# primer), so it does nothing for a field that is still null. It releases the pixel and the batch only whendisposingis true.- Nothing in the host loads a file. The pixel is the only texture the game ever has.
Building the drawing toolkit
Three operations turn the pixel into shapes. They sit in one static class, PrimitiveDrawing. A static class has no instances, so you call its methods by the class name. It is internal, which means only this project can use it. Each operation takes the batch and the pixel as parameters.
One of the operations draws a wall segment, so you first need the type that describes one. In the Source/Entities folder, create a new file named PlayableWallPath.cs and add the following code. A record struct is a small value type that is compared by its values. New to record structs? See the C# primer. Chapter 06 adds the wall path itself to this file.
new-file Source/Entities/PlayableWallPath.cs
csharp
using Microsoft.Xna.Framework;
namespace LastPerimeter.Entities;
// One straight wall segment. Chapter 06 adds its operations and the PlayableWallPath class.
public readonly record struct PathSegment(Vector2 Start, Vector2 End);In the Source/Entities folder, create a new file named Player.cs and add the following code. The player has only a position and a radius for now. A later chapter adds movement.
new-file Source/Entities/Player.cs
csharp
using Microsoft.Xna.Framework;
namespace LastPerimeter.Entities;
public sealed class Player
{
public Vector2 Position { get; set; }
public float Radius { get; set; } = 6f;
}Here are the cards for the three operations.
PrimitiveDrawing.DrawLine(spriteBatch, pixel, start, end, color, thickness) : void
- Takes: the batch, the pixel, two points, a colour and a thickness that defaults to 2.
- Gives: nothing. It adds one stretched, rotated pixel to the batch.
- Promises: the line is as long as the distance from start to end, and it points from start to end.
- Refuses: nothing. Two equal points still draw a one pixel mark.
- Requirements: REN-01.
PrimitiveDrawing.DrawSegment(spriteBatch, pixel, segment, color, thickness) : voidtakes aPathSegmentand draws a line from itsStartto itsEnd. Requirements: REN-01.
PrimitiveDrawing.DrawFilledCircle(spriteBatch, pixel, center, radius, color) : void
- Takes: the batch, the pixel, a centre, a radius and a colour.
- Gives: nothing. It adds one row of pixels for each line of the circle.
- Promises: the circle is as wide as the circle equation allows at each row.
- Refuses: nothing. The game uses whole number radii, such as the player's 6.
- Requirements: REN-01.
None of these operations has a test, because their result is a picture, and the batch needs a window. The proof is in "Running the game". Chapter 03 shows why the course still prefers tests wherever a rule can be checked with numbers.
In the Source/Rendering folder, create a new file named PrimitiveDrawing.cs and add the following code:
new-file Source/Rendering/PrimitiveDrawing.cs
csharp
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using LastPerimeter.Entities;
namespace LastPerimeter.Rendering;
internal static class PrimitiveDrawing
{
public static void DrawLine(SpriteBatch spriteBatch, Texture2D pixel, Vector2 start, Vector2 end, Color color, float thickness = 2f)
{
Vector2 edge = end - start;
float angle = (float)Math.Atan2(edge.Y, edge.X);
spriteBatch.Draw(pixel, new Rectangle((int)start.X, (int)start.Y, Math.Max(1, (int)edge.Length()), Math.Max(1, (int)thickness)), null, color, angle, Vector2.Zero, SpriteEffects.None, 0f);
}
public static void DrawSegment(SpriteBatch spriteBatch, Texture2D pixel, PathSegment segment, Color color, float thickness = 2f)
{
DrawLine(spriteBatch, pixel, segment.Start, segment.End, color, thickness);
}
public static void DrawFilledCircle(SpriteBatch spriteBatch, Texture2D pixel, Vector2 center, float radius, Color color)
{
int radiusInt = (int)Math.Ceiling(radius);
for (int y = -radiusInt; y <= radiusInt; y++)
{
float width = (float)Math.Sqrt((radius * radius) - (y * y));
spriteBatch.Draw(pixel, new Rectangle((int)(center.X - width), (int)(center.Y + y), Math.Max(1, (int)(width * 2)), 1), color);
}
}
}The key things to note are:
DrawLinefinds the edge asend - start. Its length is the width of the stretched pixel, and its thickness is the height.Math.Atan2(edge.Y, edge.X)gives the angle of the edge in radians.Drawrotates the pixel by that angle around its top-left corner, which sits at the start point.Math.Max(1, ...)stops a very short or thin line from collapsing to zero pixels.DrawSegmentadds nothing new. It unpacks aPathSegmentand callsDrawLine, so the wall path of Chapter 06 draws through the same code.DrawFilledCirclevisits each row from-radiustoradius. At rowy, the half width is the square root ofradius * radius - y * y, which is the circle equation solved for x.- Each row is a rectangle one pixel tall and
width * 2pixels wide, starting atcenter.X - width.
Building the renderers
In the Source/Rendering folder, create a new file named ArenaRenderer.cs and add the following code. It draws the four sides of a rectangle as four lines.
new-file Source/Rendering/ArenaRenderer.cs
csharp
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace LastPerimeter.Rendering;
public sealed class ArenaRenderer
{
// Chapter 06 replaces this outline with the wall path.
public void Draw(SpriteBatch spriteBatch, Texture2D pixel, Rectangle bounds)
{
Vector2 topLeft = new(bounds.Left, bounds.Top);
Vector2 topRight = new(bounds.Right, bounds.Top);
Vector2 bottomLeft = new(bounds.Left, bounds.Bottom);
Vector2 bottomRight = new(bounds.Right, bounds.Bottom);
PrimitiveDrawing.DrawLine(spriteBatch, pixel, topLeft, topRight, Color.LightGray, 2f);
PrimitiveDrawing.DrawLine(spriteBatch, pixel, topRight, bottomRight, Color.LightGray, 2f);
PrimitiveDrawing.DrawLine(spriteBatch, pixel, bottomRight, bottomLeft, Color.LightGray, 2f);
PrimitiveDrawing.DrawLine(spriteBatch, pixel, bottomLeft, topLeft, Color.LightGray, 2f);
}
}In the same folder, create a new file named PlayerRenderer.cs and add the following code. It draws the player as a filled circle in the colour it is given.
new-file Source/Rendering/PlayerRenderer.cs
csharp
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using LastPerimeter.Entities;
namespace LastPerimeter.Rendering;
public sealed class PlayerRenderer
{
public void Draw(SpriteBatch spriteBatch, Texture2D pixel, Player player, Color color)
{
PrimitiveDrawing.DrawFilledCircle(spriteBatch, pixel, player.Position, player.Radius, color);
}
}The key things to note are:
- Both
Drawmethods receive the batch and the pixel. Neither renderer owns a resource. ArenaRenderer.Drawtakes the arena rectangle as a parameter. A comment records that Chapter 06 replaces the outline with the wall path.PlayerRenderer.Drawtakes the colour as a parameter, and does not read it from the player. Colour is presentation, so a theme can change it in Chapter 20 without touching the player.
Wiring it into the game
The host now creates the renderers and a player, and draws them every frame. At the top of Source/Game/LastPerimeterApp.cs, add the following lines below the using Microsoft.Xna.Framework.Graphics; line:
add-using Source/Game/LastPerimeterApp.cs
csharp
using LastPerimeter.Entities;
using LastPerimeter.Rendering;Add the following field to the LastPerimeterApp class, below the _launchOptions field:
add-member Source/Game/LastPerimeterApp.cs after=_launchOptions
csharp
private readonly ArenaRenderer _arenaRenderer = new();Add the following field below the _arenaRenderer field:
add-member Source/Game/LastPerimeterApp.cs after=_arenaRenderer
csharp
private readonly PlayerRenderer _playerRenderer = new();Add the following field below the _playerRenderer field. The player stands still at the arena's top-left corner for this chapter.
add-member Source/Game/LastPerimeterApp.cs after=_playerRenderer
csharp
// A fixed point at the arena's top-left corner. Chapter 04 moves this player.
private readonly Player _player = new() { Position = new Vector2(50, 122) };In Source/Game/LastPerimeterApp.cs, find the Draw method and replace the whole method with the following:
replace-method Source/Game/LastPerimeterApp.cs Draw
csharp
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.Black);
if (_spriteBatch is not null && _pixel is not null)
{
_spriteBatch.Begin(samplerState: SamplerState.PointClamp);
_arenaRenderer.Draw(_spriteBatch, _pixel, new Rectangle(50, 122, 924, 552));
_playerRenderer.Draw(_spriteBatch, _pixel, _player, Color.Cyan);
_spriteBatch.End();
}
base.Draw(gameTime);
}The key changes are:
Drawstill clears to black first.- The
ifskips drawing when the batch or the pixel is null, which is only possible beforeLoadContenthas run. Beginis called once withSamplerState.PointClamp, so every shape has hard edges.- The arena rectangle
new Rectangle(50, 122, 924, 552)is typed here for now. Chapter 03 moves it intoGameConfig. Endsends the whole batch to the graphics card.
Your Source/Game/LastPerimeterApp.cs should now match the following listing. It is for reading, so you can compare your file with it. Do not type it again.
csharp
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using LastPerimeter.Entities;
using LastPerimeter.Rendering;
namespace LastPerimeter.Game;
// The thin MonoGame host. It owns the MonoGame lifetime and nothing else.
public sealed class LastPerimeterApp : Microsoft.Xna.Framework.Game
{
private readonly GraphicsDeviceManager _graphics;
private readonly GameLaunchOptions _launchOptions;
private readonly ArenaRenderer _arenaRenderer = new();
private readonly PlayerRenderer _playerRenderer = new();
// A fixed point at the arena's top-left corner. Chapter 04 moves this player.
private readonly Player _player = new() { Position = new Vector2(50, 122) };
// Nullable for this chapter only, because LoadContent runs after the constructor.
// Chapter 05 replaces both with GameServices, which is built in one step.
private SpriteBatch? _spriteBatch;
private Texture2D? _pixel;
public LastPerimeterApp(GameLaunchOptions? launchOptions = null)
{
_launchOptions = launchOptions ?? new GameLaunchOptions(null);
_graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
IsMouseVisible = true;
_graphics.PreferredBackBufferWidth = 1024;
_graphics.PreferredBackBufferHeight = 768;
}
protected override void LoadContent()
{
_spriteBatch = new SpriteBatch(GraphicsDevice);
_pixel = CreatePixel(GraphicsDevice);
}
protected override void Update(GameTime gameTime)
{
if (ShouldAutoExit(gameTime))
{
return;
}
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.Black);
if (_spriteBatch is not null && _pixel is not null)
{
_spriteBatch.Begin(samplerState: SamplerState.PointClamp);
_arenaRenderer.Draw(_spriteBatch, _pixel, new Rectangle(50, 122, 924, 552));
_playerRenderer.Draw(_spriteBatch, _pixel, _player, Color.Cyan);
_spriteBatch.End();
}
base.Draw(gameTime);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_pixel?.Dispose();
_spriteBatch?.Dispose();
}
base.Dispose(disposing);
}
private static Texture2D CreatePixel(GraphicsDevice graphicsDevice)
{
Texture2D pixel = new(graphicsDevice, 1, 1);
pixel.SetData([Color.White]);
return pixel;
}
private bool ShouldAutoExit(GameTime gameTime)
{
if (_launchOptions.AutoExitAfter is TimeSpan autoExitAfter && gameTime.TotalGameTime >= autoExitAfter)
{
Exit();
return true;
}
return false;
}
}Running the tests
The host has no tests of its own, so the test count does not change. In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 0 and Passed: 3. They are the three tests from Chapter 01.
Running the game
The drawing checks below need a window and a screen, so only you can confirm them. The test count in the previous section is the one check that needs neither.
From the LastPerimeter folder, run dotnet run --project Platforms/DesktopVK. A window opens. It shows a light grey rectangle 50 pixels in from the left and right sides, with space above it for the HUD and a smaller gap below it. A cyan dot sits at the rectangle's top-left corner, as in Figure 02-1. Close the window with its close button.
This proves REN-01. Every shape on the screen came from one pixel, and the edges are hard. PLT-03 is also proved, because the project loads no file. The next section is optional. It replaces your files with the chapter 02 snapshot.
TIP
To see why point sampling matters, open Source/Game/LastPerimeterApp.cs, change SamplerState.PointClamp to SamplerState.LinearClamp, and run the game again. Look closely at the dot. Change the line back before you go on.
If you got lost
This section is optional. Use it only when your project no longer builds or the tests no longer match this chapter. It overwrites your Source and Tests folders with the chapter 02 snapshot, so any change of your own in those folders is lost. <course-repo> is the folder where you cloned the course repository.
WARNING
These commands overwrite your own changes in Source and Tests. Copy your project folder elsewhere first if you want to keep it.
In PowerShell, from the LastPerimeter folder, run the following. Replace <course-repo> with the real path first.
powershell
$snapshot = "<course-repo>/DOCUMENTATION/learning_plan_2/snapshots/02-Drawing-From-One-Pixel"
Remove-Item -Recurse -Force Source, Tests
Copy-Item -Recurse "$snapshot/Source" Source
Copy-Item -Recurse "$snapshot/Tests" TestsIn bash, from the LastPerimeter folder, run the following. Replace <course-repo> with the real path first.
bash
snapshot="<course-repo>/DOCUMENTATION/learning_plan_2/snapshots/02-Drawing-From-One-Pixel"
rm -rf Source Tests
cp -r "$snapshot/Source" Source
cp -r "$snapshot/Tests" TestsThen run dotnet test from the LastPerimeter folder and check for Passed: 3.
Common mistakes
- The window is black and nothing is drawn.
Drawnever reachesBegin, becauseLoadContentwas not added or has the wrong name. Check that the method isprotected override void LoadContent(). - The build says
Texture2DorSpriteBatchwas not found. Theusing Microsoft.Xna.Framework.Graphics;line is missing fromLastPerimeterApp.csor from a renderer. - The build says
PathSegmentwas not found.PlayableWallPath.csis in the wrong folder, or its namespace is wrong. It belongs inSource/Entities. - The outline is soft or blurred.
Beginwas called withoutSamplerState.PointClamp. - The lines look wrong or point the wrong way. Check that
DrawLinepassesangleandVector2.ZerotoDraw, in that order. - The dot is missing.
_playerRenderer.Drawis missing fromDraw, or it is called beforeBegin.
Conclusion
In this chapter, you accomplished the following:
- Created a 1 x 1 white texture in code, with no content pipeline.
- Learned how a
SpriteBatchcollects shapes betweenBeginandEnd. - Wrote
PrimitiveDrawingwith a line, a path segment and a filled circle. - Wrote the first two renderers, for the arena outline and the player.
- Learned why renderers take their data as parameters and own no game state.
The game now proves REN-01 and the second half of PLT-03 by running the game. In the next chapter, Chapter 03: The Service Pattern and the Arena, you build the first real service and write tests before bodies.
Test Your Knowledge
Why does the game build its only texture in code instead of loading it?
Answer
The pixel is one white texel. Building it in code avoids the content pipeline entirely, and tinting it gives every colour.
What would happen to the edges of a 2 pixel line with linear sampling instead of point sampling?
Answer
They would blur into neighbouring pixels. Linear sampling blends texel colours when the texture is stretched or rotated, and a hard edge needs the nearest texel only.
Why does
PlayerRenderer.Drawtake the colour as a parameter instead of reading it from the player?Answer
Colour is presentation. Themes change it in Chapter 20 without touching the player.
Why are
_spriteBatchand_pixelcreated inLoadContentand not in the constructor?Answer
Both need the graphics device, and the device does not exist until MonoGame has created the window.
LoadContentruns after that.
Extensions
- Add a third line to
ArenaRenderer.Drawwith a thickness of 6, and watch where the thick edge falls. Does the thickness grow on both sides of the line, or on one? - Change the player's
Radiusto 20 and run the game. Then try 6.5, and readDrawFilledCircleto work out why a whole number is safer.

