How it works...

The first line of the main function within the fragment shader expands the texture coordinates to a 3D (homogeneous) value with a z coordinate of zero (s, t, 0, 1), and then transforms the value via the Slice matrix. This matrix can scale, translate, and/or rotate the texture coordinates to define the 2D region of the virtual log.

One way to visualize this is to think of the slice as a 2D unit square embedded in the log with its lower-left corner at the origin. The matrix is then used to transform that square within the log to define a slice through the log. For example, I might just translate the square by (-0.5, -0.5, -0.5) and scale by 20 in x and y to get a slice through the middle of the log.

Next, the distance from the y axis is determined by using the built-in length function (length(cyl.xz)). This will be used to determine how close we are to a growth ring. The color will be a light wood color if we are between growth rings, and a dark color when we are close to a growth ring. However, before determining the color, we perturb the distance slightly using a value from our noise texture by using the following line of code:

dist += noise.b; 

The next step is just a bit of numerical trickery to determine the color based on how close we are to a whole number. We start by taking the fractional part of the distance (fract(dist)), multiplying by two, subtracting one, and taking the absolute value. As fract(dist) is a value between zero and one, multiplying by two, subtracting one, and taking the absolute value will result in a value that is also between zero and one. However, the value will range from 1.0 when dist is 0.0, to 0.0 when dist is 0.5, and back to 1.0 when dist is 1.0 (a v shape).

We then invert the v by subtracting from one, and storing the result in t. Next, we use the smoothstep function to create a somewhat sharp transition between the light and dark colors. In other words, we want a dark color when t is less than 0.2, a light color when it is greater than 0.5, and a smooth transition in between. The result is used to mix the light and dark colors via the GLSL mix function.

The smoothstep( a, b, x ) function works in the following way. It returns 0.0 when x <= a, 1.0 when x >= b, and uses Hermite interpolation between 0 and 1 when x is between a and b.

The result of all of this is a narrow band of the dark color around integer distances, and a light color in-between, with a rapid but smooth transition. Finally, we simply apply the final color to the fragment.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.254.231