# Raymarching explained interactively

## Introduction

Raymarching is a 3D rendering technique popular in the demoscene and in websites like Shadertoy.
What's impressive about demos is that there is no 3D geometry whatsoever. All the objects that make up the scene are generated in real time using mathematical functions.

In this interactive tutorial, we will see how the raymarching algorithm works from the ground up and make our own raymarcher with shaders.

## Signed distance function

The raymarching algorithm is based on the notion of distances, we will see how later.

You may be familiar with the formula for the distance between two points, it is known as the Euclidean distance and is calculated using the Pythagorean theorem:

 EuclideanDistance(P1,P2) = (P1.x-P2.x)2+(P1.y-P2.y)2 =

Now imagine we want to calculate the distance between a point and a circle. To do that we first calculate the euclidean distance between the point and the center of the circle, then substract the radius of the circle:

 DistanceToCircle(P,C,R) = EuclideanDistance(P,C)-R =

Notice that when the point is inside the circle, the distance is negative—hence "signed" distance function. This fact will become useful later on.

The SDF of an object is a function that, given a point in space as input, outputs the distance from that point to the closest point of the object.

The SDF of rectangle is a little bit more complicated

 DistanceToRect(P,C,Size) = ||max(|P-C|-(Size/2),0)|| =

If we have multiple shapes and we want to find the closets point to P, we calculate the minimum of all the SDFs of the shapes:

## The Raymarching algorithm

Why distances have anything to do with rendering 3D shapes?

Near plane:
Field of view:
Number of rays:
Iterations:

## Going 3D

Until now we only saw how raymarching works in two dimensions, to do 3D rendering we are going to use a fragment shader