If you haven't read the previous post, I recommend to do so as well. However, I will repeat some things: In a shader you can't ask the graphics engine to draw lines or triangles to the screen because the shader is executed already during that process.
Instead it has access to a variety of data that is passed to the shader. This data includes texture coordinates, normals, position in space and so on.
When rendering a pixel we need to determine whether we shall color the pixel because it is close to a line or whether we want to output the background color. So much for the theory. The simplest thing that we can do is to draw a straight line, let's say along the x-axis:
We can determine how far the pixel is away from it and apply a smoothstep function to generate a clamped transition value that fades from 0 to 1 within that range. This allows us to set the line width using a shader parameter:
I will let you figure out how that shader would look, it's really trivial. So next I want to extend the line drawing so that I am able to draw lines in any arbitrary angle. To define a line, we need 2 points, pt_a and pt_b.
There are plenty of explanations for calculating the distance between a point and a line, check out this link on Wolfram Mathworld, for example.
Using the function that calculates the distance of a point to the line, we can now draw lines with arbitrary slopes:
Check out the source code for the shader here
Rendering a wire/solid square in a MetaSL shader
Since we already covered how to calculate the distance from a line/circle, we are finally missing the squares and rectangles. Without further ado, the formula for the distance of a point from a rectangle is:
distance = max(abs(rect_center.x - coord.x) - rect_size.x,
abs(rect_center.y - coord.y) - rect_size.y);
float2 rect_center - The center position of the rectangle
float2 coord - The coordinate to test against
float2 rect_size - The size of the rectangle
No comments:
Post a Comment