Flat Shading


Flat shading is one of the shading techquie. It relate on the faces.

So the implement step is just like face culling before.

First we need to define a light, we can use global light for simplify.

typedef struct {
    vec3_t direction;
} light_t;


light_t light = {
    .direction = { 0, 0, 1 }
};

This simple global light is directly through z-axis.

Next, we need to calc the factor of faces color values based on light direction.

In other word, the flat shading techquie actually calc the color percentage, based on the face different position (Normalization).(Cuz we don't really have light on our pc😂).

So the magic is the face more close to the light, then the face will get more bright.

uint32_t flat_light(uint32_t original_color, float percentage_factor) {
    if (percentage_factor < 0) percentage_factor = 0;
    if (percentage_factor > 1) percentage_factor = 1;

    uint32_t a = (original_color & 0xFF000000);
    uint32_t r = (original_color & 0x00FF0000) * percentage_factor;
    uint32_t g = (original_color & 0x0000FF00) * percentage_factor;
    uint32_t b = (original_color & 0x000000FF) * percentage_factor;

    uint32_t new_color = a | (r & 0x00FF0000) | (g & 0x0000FF00) | (b & 0x000000FF);

    return new_color;
}

We use dot product to make the triangle face normalized value and get the light direction.

float percentage_factor = vec3_dot(face_n, light.direction);

That we can know the face is near the light or not.

Result:

Date: 2024-01-06 Sat 00:00

Author: Terry Fung

Created: 2024-11-10 Sun 14:09

Emacs 29.4 (Org mode 9.6.15)

Validate