Hello 🙂

In this entry, we go back to some basic rasterization shit! How to draw a line from 2 points… Line is at the core of rasterization, so let’s dive into it! What compose a line on a per-pixel approach on rasterization toolkit. Well, let’s focuss on the problem we want to solve, wich is to draw a line in 2D between two coordinates.

Tools:

Math: You do not need math! I mean, if you are from the public highschool standards in Quebec, you are good to go.

Basic structures:

Before starting to discuss the algorithm, let’s define a basic language. We mentionned that we need 2 points with x and y coordinates. In GLSL we would use Vec2. But let’s dive a bit deeper, and explore a bit more those components.

For exevery pixel we run this code!

void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
vec2 uv = fragCoord/iResolution.xy;
vec3 col = 0.5 + 0.5*cos(iTime+uv.xyx+vec3(1.,2,4));
fragColor = vec4(col,1.0);
}

We are the pixel shader levels. Wich is where all the geometries, projections, culling and so on are computed, our task is to compute sexy pixels!

Note the time and res… We simply compute the color out of every pixel of the canvas based on the sourced UV.

Line shit:

Let’s draw a line!

void SetPixel(int x, int y,
inout vec3 col,
vec2 frag,
vec3 pixelColor
)
{
float px = float(x) + .5;
float py = float(y) + .5;

if(px == frag.x && py == frag.y)
{
col = pixelColor;
}
}


Here is our friendly functions! From the pixel approach we want to have a “drawPixel”-ish at x,y coordinates. In the functions we pass those two parameters as the first arguments. We will dive into the code later but for now, let’s just assume you can write a pixel and X,Y using SetPixel(x,y)

Back to our main functions:

To draw a line we need a basic formula to draw linear equations. To draw the slope of the line, we use this: easy highschool math!

Let’s compute that:


float x1 = 50.0f;
float y1 = 50.0f;

float x2 = 100.0f;
float y2 = 120.0f;

float ddx = (x2 - x1);
float ddy = (y2 - y1);

ddx and ddy are what we want to take a look at. Defining the slope and the performing the per-pixel loop to draw the line.

    // y slope line shit
float slope = ydiff / xdiff;
for(float x = xmin; x <= xmax; x += 1.0f)
{
float y = y1 + ((x - x1) * slope);
SetPixel(int(x), int(y), col, fragCoord, vec3(1.0f, 1.0f, 1.0f));
}

We now draw a line! 🙂

Back to our main vertex Buffer:

Now that we have a basic line drawing… How do we define a vertex buffer to do this? Let’s dive into that!