A simple ray tracing engine implemented in C# using Windows Forms for visualization. This project demonstrates fundamental concepts of ray tracing including ray generation, camera systems, lighting, reflections, and basic geometry intersection.
The engine is written in C# using the .NET framework. Otherwise, everything is written from scratch!
- Create a new scene
- Create a new camera
- Create a mesh
- Add verticies to the mesh
- Add the mesh to the scene
- Run the tracing algorithm and handle your results
// Create a new Scene
scene = new Scene();
// Create a new camera facing the positive Z direction
Camera camera = new Camera(new Vector3(0,0,-10), Vector3.UnitZ, Vector3.UnitY, 60.0f);
// A basic square shape, but two opposing corners are 1 unit closer to the screen
Mesh mesh1 = new Mesh();
mesh1.AddVertex(2, 2, 3);
mesh1.AddVertex(-2, 2, 4);
Face.CurrentColor = PixelColor.FromRGB(255, 0, 0);
mesh1.AddVertex(2, -2, 4);
Face.CurrentColor = PixelColor.FromRGB(0, 0, 255);
mesh1.AddVertex(-2, -2, 3);
// Add the mesh to the scene
scene.AddMesh(mesh1);
// Create a new RayGenerator and specify the camera, height, and width in pixels
rayGenerator = new RayGenerator(camera, 640, 480);
// Generate rays for the scene
Ray[,] rays = rayGenerator.GenerateRays();
// Loop through pixels and store collisions
collisionBuffer = new Collision[HEIGHT, WIDTH];
for (int y = 0; y < HEIGHT; y++)
{
for (int x = 0; x < WIDTH; x++)
{
collisionBuffer[y, x] = Tracer.Intersect(scene, rays[y, x]);
}
}
See the demo viewer for more about drawing to a window
The engine supports loading a .obj file into the scene. If the obj support vertex normals, those will be loaded as well. The function can return null in the case of the file failing to load.
Mesh? mesh = Import.fromObjectFile("../../../assets/obj/pawn.obj");
if (mesh != null)
{
scene.AddMesh(mesh);
}
Loading in an OBJ file with vertex normals.
Drawing some basic shapes using verticies (No lighting)
Testing out using distance based fog, we can see a line strip being rendered from 1 mesh with 4 vertices. the 2 opposing corners of the square are closer to the camera; creating the gradient effect we see. The white represents areas closer to the camera.