7-Segment Digital Clock with SDL3 Callbacks, cglm, and OpenGL Семисегментные цифровые часы с SDL3 Callbacks, cglm и OpenGL

A comprehensive guide to building a hardware-style 7-segment digital clock (HH:MM:SS) in modern C++ (C++20) using the official SDL3 Callbacks API, GLAD (OpenGL 3.3 Core Profile), and cglm for orthographic matrix transformations. This tutorial covers procedural 2D polygon segment triangulation, transparent inactive segment ghosting with alpha blending, bitmask digit decoding, native 60 FPS frame pacing via SDL_HINT_MAIN_CALLBACK_RATE, and smooth sinusoidal floating/pulsing cutscene animations via an extensible Action Queue. Подробное руководство по созданию аппаратных 7-сегментных цифровых часов (ЧЧ:ММ:СС) на современном C++ (C++20) с использованием официального SDL3 Callbacks API, GLAD (OpenGL 3.3 Core Profile) и библиотеки cglm для ортографических матричных трансформаций. Руководство охватывает процедурную триангуляцию 2D полигонов сегментов, эффект полупрозрачных неактивных сегментов через альфа-блендинг, декодирование битовых масок цифр, ограничение частоты кадров до 60 FPS через SDL_HINT_MAIN_CALLBACK_RATE и плавную анимацию покачивания и пульсации с помощью расширяемой Action Queue.

Architecture & Rendering Highlights Особенности архитектуры и рендеринга

Each segment is constructed as a procedural 6-sided convex polygon in OpenGL, perfectly mimicking vacuum fluorescent displays (VFD) and classic LCD panels. In addition to displaying accurate real-time clock digits and blinking colons, the clock integrates an Action Queue to smoothly pulse and tilt the display continuously without spaghetti state machines. Каждый сегмент формируется процедурно в виде 6-угольного выпуклого полигона напрямую в OpenGL, точно воссоздавая эффект винтажных вакуумно-люминесцентных и жидкокристаллических дисплеев. Помимо отображения точного времени и мигающих разделителей, часы используют систему Action Queue для непрерывной плавной пульсации и покачивания дисплея без громоздких конечных автоматов.

Why SDL3 Callbacks API & SDL_HINT_MAIN_CALLBACK_RATE? Почему именно SDL3 Callbacks API и SDL_HINT_MAIN_CALLBACK_RATE?

The SDL3 Callbacks API (SDL_AppInit, SDL_AppIterate, SDL_AppEvent, SDL_AppQuit) is the official cross-platform standard in SDL3, eliminating manual while loops. Because some integrated GPUs (such as Intel HD Graphics on desktop CPUs) ignore OpenGL VSync swap intervals, setting SDL_SetHint(SDL_HINT_MAIN_CALLBACK_RATE, "60") tells SDL3's internal event loop to dispatch SDL_AppIterate at a smooth, rock-solid 60 FPS across all systems without manual sleeping. Combined with cglm, we compute an aspect-ratio-preserving orthographic projection (glm_ortho) and view matrix (glm_lookat) into an MVP matrix passed to the shader. SDL3 Callbacks API (SDL_AppInit, SDL_AppIterate, SDL_AppEvent, SDL_AppQuit) — это официальный кроссплатформенный стандарт в SDL3, избавляющий от ручных циклов while. Поскольку некоторые встроенные видеокарты (например, Intel HD Graphics) игнорируют интервалы VSync в OpenGL, указание SDL_SetHint(SDL_HINT_MAIN_CALLBACK_RATE, "60") сообщает внутреннему диспетчеру SDL3 вызывать SDL_AppIterate со стабильной частотой 60 кадров/сек без ручных задержек. В связке с cglm мы рассчитываем сохраняющую пропорции ортографическую проекцию (glm_ortho) и матрицу камеры (glm_lookat) в единую матрицу MVP, передаваемую в шейдер.

Core Architecture: In-Depth Component Breakdown Основная архитектура: подробный разбор компонентов

1. struct Vertex & Alpha Blending

struct Vertex
{
    float x, y;
    float r, g, b, a;
};
  • Position & Color:Позиция и цвет: Each vertex carries 2D coordinate positions (x, y) and 4-component RGBA floating-point color values (r, g, b, a). Каждая вершина хранит 2D координаты (x, y) и четырёхкомпонентный цвет RGBA с плавающей точкой (r, g, b, a).
  • Alpha Blending Configuration:Настройка альфа-блендинга: In SDL_AppInit, alpha blending is activated via glEnable(GL_BLEND) and glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA). Active segments shine in bright emerald green (#00AF70 at ~75% opacity), while inactive segments remain subtly visible at ~12.5% opacity. В функции SDL_AppInit активируется смешивание цветов через glEnable(GL_BLEND) и glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA). Активные сегменты светятся ярким изумрудно-зелёным цветом (#00AF70 при непрозрачности ~75%), а неактивные сегменты остаются слегка заметными при ~12.5% непрозрачности.

2. 7-Segment Bitmask Topology

The 7 segments of each digit correspond to bits 0 through 6: 7 сегментов каждого разряда соответствуют битам с 0 по 6:

     5 (Top)
     ---
 3  | 4 |  1
(UL)|(M)| (UR)
     ---
 2  | 6 |  0
(LL)|(B)| (LR)
     ---
Bit Segment Orientation Offset (X, Y)
0Lower-Right (LR)Vertical(x + 1.0, y = 1.0)
1Upper-Right (UR)Vertical(x + 1.0, y = 0.0)
2Lower-Left (LL)Vertical(x + 0.0, y = 1.0)
3Upper-Left (UL)Vertical(x + 0.0, y = 0.0)
4Middle (M)Horizontal(x + 0.0, y = 1.0)
5Top (T)Horizontal(x + 0.0, y = 0.0)
6Bottom (B)Horizontal(x + 0.0, y = 2.0)
static constexpr uint8_t DIGIT_MASKS[10] = {
    0x6F, 0x03, 0x76, 0x73, 0x1B, 0x79, 0x7D, 0x23, 0x7F, 0x7B
};

By checking (mask >> esi) & 1, the renderer instantly determines whether each segment should be rendered with COLOR_ACTIVE or COLOR_INACTIVE. Проверяя выражение (mask >> esi) & 1, рендерер моментально определяет, каким цветом рисовать сегмент: COLOR_ACTIVE или COLOR_INACTIVE.

3. Procedural Polygon Triangulation

Each horizontal segment is defined by a 6-point beveled hexagon: Каждый горизонтальный сегмент описывается 6-точечным скошенным шестиугольником:

      (0.2, 0.0)               (0.8, 0.0)
          *------------------------*
         /                          \
(0.1,0.1)*                          *(0.9, 0.1)
         \                          /
          *------------------------*
      (0.2, 0.2)               (0.8, 0.2)
  • Convex Polygon Decomposition:Разбиение выпуклого полигона: Triangulated into 4 counter-clockwise triangles, generating 12 vertices per segment. Триангулируется на 4 треугольника против часовой стрелки, порождая 12 вершин на сегмент.
  • Vertical Rotation & Alignment:Поворот и выравнивание вертикальных сегментов: For vertical segments, the transformation worldPts[i][0] = x + 0.2f - pts[i][1] and worldPts[i][1] = y + 0.1f + pts[i][0] rotates the polygon 90° clockwise and aligns the 45° miter ends uniformly with horizontal segments. Для вертикальных сегментов формулы worldPts[i][0] = x + 0.2f - pts[i][1] и worldPts[i][1] = y + 0.1f + pts[i][0] поворачивают полигон на 90° по часовой стрелке и идеально стыкуют скошенные под 45° углы с горизонтальными перекладинами.
  • Colon Dots:Точки двоеточий: Rendered as 12-sided regular polygons at coordinates x = 2.65 and x = 5.65. Their color alternates between active and inactive every 500 ms (SDL_GetTicks() / 500 % 2). Отрисовываются в виде 12-сторонних правильных полигонов по координатам x = 2.65 и x = 5.65. Их цвет переключается между активным и неактивным каждые 500 мс (SDL_GetTicks() / 500 % 2).

4. Action Queue Animation Loop

static void setupCutscene(AppState *state)
{
    // Gentle floating pulse & rotation effect
    state->actionQueue.push(std::make_unique(state, 1.15f, 1.2f));
    state->actionQueue.push(std::make_unique(state, 0.15f, 0.8f));
    state->actionQueue.push(std::make_unique(state, -0.15f, 1.6f));
    state->actionQueue.push(std::make_unique(state, 0.0f, 0.8f));
}

The ActionQueue sequences smooth sinusoidal scale pulsing (via PulseAction) and tilt rotation (via RotateAction), giving the clock an organic floating appearance in 3D/2D space while preserving precise timekeeping. ActionQueue последовательно выполняет плавную синусоидальную пульсацию масштаба (через PulseAction) и наклон (через RotateAction), придавая часам эффект живого парения в пространстве без нарушения точности хода времени.

Step 1: Create Project Directory Structure Шаг 1: Создание структуры директории проекта

Create your workspace directory for the project and a src subdirectory for C++ source files: Создайте рабочую директорию проекта и подпапку src для исходных файлов C++:

Windows (Command Prompt / PowerShell)

mkdir C:\projects\7-segment-digital-clock-sdl3-opengl-desktop
mkdir C:\projects\7-segment-digital-clock-sdl3-opengl-desktop\src
cd C:\projects\7-segment-digital-clock-sdl3-opengl-desktop

Ubuntu / WSL (Terminal)

mkdir -p ~/projects/7-segment-digital-clock-sdl3-opengl-desktop/src
cd ~/projects/7-segment-digital-clock-sdl3-opengl-desktop

Step 2: Create Source Files (src/main.cpp & CMakeLists.txt) Шаг 2: Создание исходных файлов (src/main.cpp и CMakeLists.txt)

Windows (Terminal / Notepad)

notepad src\main.cpp
notepad CMakeLists.txt

Ubuntu (Terminal / Nano)

nano src/main.cpp
nano CMakeLists.txt

1. File Contents for src/main.cpp 1. Содержимое файла src/main.cpp

#define SDL_MAIN_USE_CALLBACKS 1
#include <SDL3/SDL.h>
#include <SDL3/SDL_main.h>
#include <cglm/cglm.h>
#include <glad/glad.h>

#include <algorithm>
#include <cmath>
#include <ctime>
#include <deque>
#include <memory>
#include <vector>

// ============================================================================
// Action / Command Queue System
// ============================================================================

enum class ActionStatus
{
    Running,
    Finished
};

class Action
{
public:
    virtual ~Action() = default;
    virtual void on_start() { }
    virtual ActionStatus update(float dt) = 0;
};

class ActionQueue
{
public:
    void push(std::unique_ptr<Action> action)
    {
        queue.push_back(std::move(action));
    }

    void update(float dt)
    {
        if (queue.empty())
            return;

        if (!started)
        {
            queue.front()->on_start();
            started = true;
        }

        if (queue.front()->update(dt) == ActionStatus::Finished)
        {
            queue.pop_front();
            started = false;
        }
    }

    bool is_empty() const { return queue.empty(); }
    void clear()
    {
        queue.clear();
        started = false;
    }

private:
    std::deque<std::unique_ptr<Action>> queue;
    bool started = false;
};

// ============================================================================
// 7-Segment Digital Clock Renderer
// ============================================================================

struct Vertex
{
    float x, y;
    float r, g, b, a;
};

class DigitalClock
{
public:
    // ARGB: COLOR_ACTIVE = 0xC000AF70, COLOR_INACTIVE = 0x20007F30
    static constexpr float COLOR_ACTIVE[4] = { 0.0f, 175.0f / 255.0f, 112.0f / 255.0f, 192.0f / 255.0f };
    static constexpr float COLOR_INACTIVE[4] = { 0.0f, 127.0f / 255.0f, 48.0f / 255.0f, 32.0f / 255.0f };

    // Segment bitmasks for digits 0-9
    // Bit 0: lower-right | Bit 1: upper-right | Bit 2: lower-left | Bit 3: upper-left
    // Bit 4: middle      | Bit 5: top         | Bit 6: bottom
    static constexpr uint8_t DIGIT_MASKS[10] = {
        0x6F, 0x03, 0x76, 0x73, 0x1B, 0x79, 0x7D, 0x23, 0x7F, 0x7B
    };

    // Positions of the 6 digits: HH : MM : SS
    static constexpr float DIGIT_POSITIONS[6] = {
        0.0f, 1.3f, 3.0f, 4.3f, 6.0f, 7.3f
    };

    void init()
    {
        glGenVertexArrays(1, &vao);
        glGenBuffers(1, &vbo);

        glBindVertexArray(vao);
        glBindBuffer(GL_ARRAY_BUFFER, vbo);

        // Position: 2 floats
        glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void *)offsetof(Vertex, x));
        glEnableVertexAttribArray(0);

        // Color (RGBA): 4 floats
        glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void *)offsetof(Vertex, r));
        glEnableVertexAttribArray(1);

        glBindVertexArray(0);
    }

    void destroy()
    {
        if (vao)
            glDeleteVertexArrays(1, &vao);
        if (vbo)
            glDeleteBuffers(1, &vbo);
        vao = 0;
        vbo = 0;
    }

    void update_and_render()
    {
        std::time_t rawTime = std::time(nullptr);
        std::tm *timeInfo = std::localtime(&rawTime);

        int digits[6] = {
            timeInfo->tm_hour / 10,
            timeInfo->tm_hour % 10,
            timeInfo->tm_min / 10,
            timeInfo->tm_min % 10,
            timeInfo->tm_sec / 10,
            timeInfo->tm_sec % 10
        };

        // Blink colon separators every 500 ms (equivalent to SetTimer 500ms)
        bool blink = (SDL_GetTicks() / 500) % 2 == 1;

        meshVertices.clear();

        // Draw 6 digits
        for (int i = 0; i < 6; ++i)
        {
            draw_digit(digits[i], DIGIT_POSITIONS[i]);
        }

        // Draw colon separator pairs at x = 2.65 and x = 5.65
        const float *dotColor = blink ? COLOR_ACTIVE : COLOR_INACTIVE;
        draw_dot(2.65f, 0.7f, 0.2f, dotColor);
        draw_dot(2.65f, 1.3f, 0.2f, dotColor);
        draw_dot(5.65f, 0.7f, 0.2f, dotColor);
        draw_dot(5.65f, 1.3f, 0.2f, dotColor);

        // Upload dynamic mesh and draw
        glBindVertexArray(vao);
        glBindBuffer(GL_ARRAY_BUFFER, vbo);
        glBufferData(GL_ARRAY_BUFFER, meshVertices.size() * sizeof(Vertex), meshVertices.data(), GL_DYNAMIC_DRAW);

        glDrawArrays(GL_TRIANGLES, 0, static_cast<GLsizei>(meshVertices.size()));
        glBindVertexArray(0);
    }

private:
    GLuint vao = 0;
    GLuint vbo = 0;
    std::vector<Vertex> meshVertices;

    // Center offset to center the clock around (0,0) in OpenGL space
    static constexpr float OFFSET_X = 4.25f;
    static constexpr float OFFSET_Y = 1.10f;

    void add_triangle(float x1, float y1, float x2, float y2, float x3, float y3, const float col[4])
    {
        // Invert Y so that 0 is top and 2 is bottom matching GDI coordinates
        meshVertices.push_back({ (x1 - OFFSET_X), -(y1 - OFFSET_Y), col[0], col[1], col[2], col[3] });
        meshVertices.push_back({ (x2 - OFFSET_X), -(y2 - OFFSET_Y), col[0], col[1], col[2], col[3] });
        meshVertices.push_back({ (x3 - OFFSET_X), -(y3 - OFFSET_Y), col[0], col[1], col[2], col[3] });
    }

    void draw_segment(float x, float y, bool horizontal, const float col[4])
    {
        // Base 6-point hexagon from g_segment_points:
        // (0.1, 0.1), (0.2, 0.0), (0.8, 0.0), (0.9, 0.1), (0.8, 0.2), (0.2, 0.2)
        float pts[6][2] = {
            { 0.1f, 0.1f },
            { 0.2f, 0.0f },
            { 0.8f, 0.0f },
            { 0.9f, 0.1f },
            { 0.8f, 0.2f },
            { 0.2f, 0.2f }
        };

        float worldPts[6][2];
        for (int i = 0; i < 6; ++i)
        {
            if (horizontal)
            {
                worldPts[i][0] = x + 0.1f + pts[i][0];
                worldPts[i][1] = y + pts[i][1];
            }
            else
            {
                // Vertical segment: Rotate 90 degrees clockwise and translate (x + 0.2, y + 0.1)
                worldPts[i][0] = x + 0.2f - pts[i][1];
                worldPts[i][1] = y + 0.1f + pts[i][0];
            }
        }

        // Triangulate 6-sided convex polygon into 4 triangles
        add_triangle(worldPts[0][0], worldPts[0][1], worldPts[1][0], worldPts[1][1], worldPts[2][0], worldPts[2][1], col);
        add_triangle(worldPts[0][0], worldPts[0][1], worldPts[2][0], worldPts[2][1], worldPts[5][0], worldPts[5][1], col);
        add_triangle(worldPts[2][0], worldPts[2][1], worldPts[3][0], worldPts[3][1], worldPts[4][0], worldPts[4][1], col);
        add_triangle(worldPts[2][0], worldPts[2][1], worldPts[4][0], worldPts[4][1], worldPts[5][0], worldPts[5][1], col);
    }

    void draw_digit(int val, float posX)
    {
        val = std::clamp(val, 0, 9);
        uint8_t mask = DIGIT_MASKS[val];

        for (int esi = 0; esi < 7; ++esi)
        {
            bool active = (mask >> esi) & 1;
            const float *col = active ? COLOR_ACTIVE : COLOR_INACTIVE;

            bool isHorizontal = (esi & 4) != 0;
            float x = (esi < 2) ? (posX + 1.0f) : posX;
            float y = (esi == 6) ? 2.0f : ((esi % 2 == 0) ? 1.0f : 0.0f);

            draw_segment(x, y, isHorizontal, col);
        }
    }

    void draw_dot(float x, float y, float size, const float col[4])
    {
        // Approximate circular dot with a 12-sided regular polygon
        constexpr int segments = 12;
        float radius = size * 0.5f;
        float cx = x + radius;
        float cy = y + radius;

        for (int i = 0; i < segments; ++i)
        {
            float a1 = (float)i * (2.0f * 3.14159265f / segments);
            float a2 = (float)(i + 1) * (2.0f * 3.14159265f / segments);

            float x1 = cx + radius * std::cos(a1);
            float y1 = cy + radius * std::sin(a1);
            float x2 = cx + radius * std::cos(a2);
            float y2 = cy + radius * std::sin(a2);

            add_triangle(cx, cy, x1, y1, x2, y2, col);
        }
    }
};

// ============================================================================
// Application & Render State
// ============================================================================

struct AppState
{
    SDL_Window *window = nullptr;
    SDL_GLContext glContext = nullptr;

    GLuint shaderProgram = 0;
    GLint uMVPLoc = -1;

    float rotationAngle = 0.0f;
    float scale = 1.0f;
    float clearColor[3] = { 0.05f, 0.05f, 0.07f }; // Dark background for LED glow

    uint64_t lastTicks = 0;
    ActionQueue actionQueue;
    DigitalClock clock;
};

// ============================================================================
// Concrete Cutscene Actions
// ============================================================================

class RotateAction : public Action
{
public:
    RotateAction(AppState *state, float targetAngleRad, float duration)
        : state(state)
        , target(targetAngleRad)
        , duration(duration)
    {
    }

    void on_start() override
    {
        startAngle = state->rotationAngle;
        elapsed = 0.0f;
    }

    ActionStatus update(float dt) override
    {
        elapsed += dt;
        float t = (duration > 0.0f) ? std::min(1.0f, elapsed / duration) : 1.0f;
        state->rotationAngle = startAngle + (target - startAngle) * t;
        return (t >= 1.0f) ? ActionStatus::Finished : ActionStatus::Running;
    }

private:
    AppState *state;
    float startAngle = 0.0f;
    float target;
    float duration;
    float elapsed = 0.0f;
};

class PulseAction : public Action
{
public:
    PulseAction(AppState *state, float maxScale, float duration)
        : state(state)
        , maxScale(maxScale)
        , duration(duration)
    {
    }

    ActionStatus update(float dt) override
    {
        elapsed += dt;
        float t = std::min(1.0f, elapsed / duration);
        state->scale = 1.0f + (maxScale - 1.0f) * std::sin(t * 3.14159265f);
        return (t >= 1.0f) ? ActionStatus::Finished : ActionStatus::Running;
    }

private:
    AppState *state;
    float maxScale;
    float duration;
    float elapsed = 0.0f;
};

static void setupCutscene(AppState *state)
{
    // Gentle floating pulse & rotation effect
    state->actionQueue.push(std::make_unique<PulseAction>(state, 1.15f, 1.2f));
    state->actionQueue.push(std::make_unique<RotateAction>(state, 0.15f, 0.8f));
    state->actionQueue.push(std::make_unique<RotateAction>(state, -0.15f, 1.6f));
    state->actionQueue.push(std::make_unique<RotateAction>(state, 0.0f, 0.8f));
}

// ============================================================================
// Shaders with Alpha Channel Support
// ============================================================================

const char *vertexShaderSource =
    "#version 330 core\n"
    "layout (location = 0) in vec2 aPos;\n"
    "layout (location = 1) in vec4 aColor;\n"
    "uniform mat4 uMVP;\n"
    "out vec4 vColor;\n"
    "void main() {\n"
    "    gl_Position = uMVP * vec4(aPos, 0.0, 1.0);\n"
    "    vColor = aColor;\n"
    "}\0";

const char *fragmentShaderSource =
    "#version 330 core\n"
    "in vec4 vColor;\n"
    "out vec4 FragColor;\n"
    "void main() {\n"
    "    FragColor = vColor;\n"
    "}\0";

static GLuint compileShader(GLenum type, const char *source)
{
    GLuint shader = glCreateShader(type);
    glShaderSource(shader, 1, &source, nullptr);
    glCompileShader(shader);
    return shader;
}

// ============================================================================
// SDL3 Callbacks
// ============================================================================

SDL_AppResult SDL_AppInit(void **appstate, int argc, char *argv[])
{
    // Configure SDL3 to invoke SDL_AppIterate at 60 FPS
    if (!SDL_SetHint(SDL_HINT_MAIN_CALLBACK_RATE, "60"))
    {
        SDL_Log("Warning: Failed to set callback rate hint: %s", SDL_GetError());
    }

    if (!SDL_Init(SDL_INIT_VIDEO))
    {
        SDL_Log("Unable to initialize SDL: %s", SDL_GetError());
        return SDL_APP_FAILURE;
    }

    auto *state = new AppState();
    *appstate = state;

    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

    state->window = SDL_CreateWindow(
        "Digital Clock (SDL3 Callbacks + OpenGL + cglm)",
        900, 360,
        SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);

    if (!state->window)
    {
        SDL_Log("Failed to create window: %s", SDL_GetError());
        return SDL_APP_FAILURE;
    }

    state->glContext = SDL_GL_CreateContext(state->window);
    if (!state->glContext)
    {
        SDL_Log("Failed to create OpenGL context: %s", SDL_GetError());
        return SDL_APP_FAILURE;
    }

    SDL_GL_MakeCurrent(state->window, state->glContext);

    if (!gladLoadGLLoader((GLADloadproc)SDL_GL_GetProcAddress))
    {
        SDL_Log("Failed to initialize GLAD");
        return SDL_APP_FAILURE;
    }

    // Enable Alpha Blending for the inactive segment transparency
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    GLuint vs = compileShader(GL_VERTEX_SHADER, vertexShaderSource);
    GLuint fs = compileShader(GL_FRAGMENT_SHADER, fragmentShaderSource);

    state->shaderProgram = glCreateProgram();
    glAttachShader(state->shaderProgram, vs);
    glAttachShader(state->shaderProgram, fs);
    glLinkProgram(state->shaderProgram);

    glDeleteShader(vs);
    glDeleteShader(fs);

    state->uMVPLoc = glGetUniformLocation(state->shaderProgram, "uMVP");

    // Initialize clock buffers
    state->clock.init();

    state->lastTicks = SDL_GetTicksNS();
    setupCutscene(state);

    return SDL_APP_CONTINUE;
}

SDL_AppResult SDL_AppEvent(void *appstate, SDL_Event *event)
{
    if (event->type == SDL_EVENT_QUIT)
    {
        return SDL_APP_SUCCESS;
    }
    return SDL_APP_CONTINUE;
}

SDL_AppResult SDL_AppIterate(void *appstate)
{
    auto *state = static_cast<AppState *>(appstate);

    uint64_t currentTicks = SDL_GetTicksNS();
    float dt = static_cast<float>(currentTicks - state->lastTicks) / 1e9f;
    state->lastTicks = currentTicks;

    // Advance Cutscene / Actions
    state->actionQueue.update(dt);
    if (state->actionQueue.is_empty())
    {
        setupCutscene(state);
    }

    // Render Frame
    int w, h;
    SDL_GetWindowSizeInPixels(state->window, &w, &h);
    glViewport(0, 0, w, h);

    glClearColor(state->clearColor[0], state->clearColor[1], state->clearColor[2], 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);

    glUseProgram(state->shaderProgram);

    // Matrix Math using cglm
    float aspect = (h > 0) ? static_cast<float>(w) / static_cast<float>(h) : 1.0f;

    mat4 proj, view, model, vp, mvp;

    // View boundaries: the clock is ~9 units wide and ~2.5 units tall
    float orthoHalfHeight = 2.2f;
    float orthoHalfWidth = orthoHalfHeight * aspect;
    glm_ortho(-orthoHalfWidth, orthoHalfWidth, -orthoHalfHeight, orthoHalfHeight, -1.0f, 1.0f, proj);

    vec3 eye = { 0.0f, 0.0f, 1.0f };
    vec3 center = { 0.0f, 0.0f, 0.0f };
    vec3 up = { 0.0f, 1.0f, 0.0f };
    glm_lookat(eye, center, up, view);

    glm_mat4_identity(model);
    vec3 axisZ = { 0.0f, 0.0f, 1.0f };
    glm_rotate(model, state->rotationAngle, axisZ);
    glm_scale_uni(model, state->scale);

    glm_mat4_mul(proj, view, vp);
    glm_mat4_mul(vp, model, mvp);

    glUniformMatrix4fv(state->uMVPLoc, 1, GL_FALSE, (const GLfloat *)mvp);

    // Render the 7-segment digital clock
    state->clock.update_and_render();

    SDL_GL_SwapWindow(state->window);
    return SDL_APP_CONTINUE;
}

void SDL_AppQuit(void *appstate, SDL_AppResult result)
{
    if (appstate)
    {
        auto *state = static_cast<AppState *>(appstate);
        state->clock.destroy();
        if (state->shaderProgram)
            glDeleteProgram(state->shaderProgram);
        if (state->glContext)
            SDL_GL_DestroyContext(state->glContext);
        if (state->window)
            SDL_DestroyWindow(state->window);
        delete state;
    }
    SDL_Quit();
}

2. File Contents for CMakeLists.txt 2. Содержимое файла CMakeLists.txt

cmake_minimum_required(VERSION 3.21)

if(NOT CMAKE_BUILD_TYPE)
    set(CMAKE_BUILD_TYPE "Debug")
endif()

project(7-segment-digital-clock-sdl3-opengl-desktop CXX C)

set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

find_package(OpenGL REQUIRED)

if(WIN32)
    set(SDL3_DIR "C:/libs/sdl3-3.4.20-mingw/lib/cmake/SDL3")
    set(CGLM_INCLUDE_DIR "C:/libs/cglm-0.9.6/include")
    set(GLAD_INCLUDE_DIR "C:/libs/glad-0.1.36/opengl-3.3/include")
    set(GLAD_SOURCE "C:/libs/glad-0.1.36/opengl-3.3/src/glad.c")
else()
    set(SDL3_DIR "$ENV{HOME}/libs/sdl3-3.4.20-ubuntu/lib/cmake/SDL3")
    set(CGLM_INCLUDE_DIR "$ENV{HOME}/libs/cglm-0.9.6/include")
    set(GLAD_INCLUDE_DIR "$ENV{HOME}/libs/glad-0.1.36/opengl-3.3/include")
    set(GLAD_SOURCE "$ENV{HOME}/libs/glad-0.1.36/opengl-3.3/src/glad.c")
endif()

find_package(SDL3 REQUIRED CONFIG)

add_executable(app
    src/main.cpp
    ${GLAD_SOURCE}
)

target_include_directories(app PRIVATE
    ${CGLM_INCLUDE_DIR}
    ${GLAD_INCLUDE_DIR}
)

if(WIN32)
    target_compile_options(app PRIVATE -Os)
    target_link_options(app PRIVATE -static -s -static-libgcc)

    if(CMAKE_BUILD_TYPE STREQUAL "Debug")
        target_link_options(app PRIVATE -mconsole)
    else()
        target_link_options(app PRIVATE -mwindows)
    endif()

    target_link_libraries(app PRIVATE
        SDL3::SDL3-static
        OpenGL::GL
    )
else()
    target_link_libraries(app PRIVATE
        SDL3::SDL3-static
        OpenGL::GL
    )
endif()

Step 3: Create Build & Execution Scripts Шаг 3: Создание скриптов сборки и запуска

Windows (MinGW / Batch Scripts)

config-win.bat

cmake -G Ninja -S . -B dist/win

build-win.bat

cmake --build dist/win

run-win.bat

@echo off
.\dist\win\app.exe

Run sequentially in Command Prompt or PowerShell: Последовательно запустите в командной строке или PowerShell:

config-win.bat
build-win.bat
run-win.bat

Ubuntu (Bash Scripts)

config-linux.sh

#!/usr/bin/env bash
set -e
cmake -G Ninja -S . -B dist/linux

build-linux.sh

#!/usr/bin/env bash
set -e
cmake --build dist/linux

run-linux.sh

#!/usr/bin/env bash
set -e
./dist/linux/app

Grant execution permissions and execute on Ubuntu: Предоставьте права на запуск и выполните под Ubuntu:

chmod +x config-linux.sh build-linux.sh run-linux.sh
./config-linux.sh
./build-linux.sh
./run-linux.sh

Step 4: Expected Output Шаг 4: Ожидаемый результат

Upon execution, a resizable window opens displaying a full 6-digit real-time clock (HH:MM:SS) with continuous animation effects: После запуска приложения откроется масштабируемое окно с полнофункциональными 6-значными часами реального времени (ЧЧ:ММ:СС) и непрерывными эффектами анимации:

  1. Luminous Active Segments: Currently active segments illuminate in vivid phosphor green (#00AF70).Активные сегменты светятся ярким изумрудно-зеленым цветом (#00AF70).
  2. Translucent Ghost Segments: Inactive segments remain softly visible with ~12.5% alpha transparency, perfectly recreating the look of classic hardware digital displays.Неактивные сегменты остаются мягко различимыми с прозрачностью ~12.5%, создавая характерный эффект аппаратных дисплеев.
  3. Synchronized Blinking Separators: The colon dots between hours/minutes and minutes/seconds blink smoothly every half-second (500 ms).Точки двоеточий между часами/минутами и минутами/секундами синхронно мигают каждые полсекунды (500 мс).
  4. Floating & Pulsing Cutscenes: The display gently scales up to 1.15x and tilts smoothly from -0.15 to +0.15 radians in a looped sequence driven by the Action Queue.Дисплей плавно увеличивается до 1.15x и мягко наклоняется в диапазоне от -0.15 до +0.15 радиан в зацикленной последовательности под управлением Action Queue.
  5. Frame-Paced 60 FPS: Driven consistently at 60 FPS across all GPUs via SDL_HINT_MAIN_CALLBACK_RATE.Стабильная работа с частотой 60 кадров/сек на любых видеокартах благодаря SDL_HINT_MAIN_CALLBACK_RATE.
  6. Aspect Ratio Resilience: Resizing the window dynamically updates the orthographic projection via cglm, preventing distortion or stretching.При изменении размера окна ортографическая проекция cglm динамически пересчитывается, предотвращая искажение пропорций цифр.

Complete unified source code and scripts are available on GitHub: Полный исходный код и скрипты сборки доступны на GitHub:

View on GitHub Смотреть на GitHub