Playing Chicken Dance Animation for Y-Bot using ozz-animation, Qt 6 (QOpenGLWindow), cgltf, cglm, and OpenGL 3.3 Воспроизведение анимации танец цыпленка для Y-Bot с использованием ozz-animation, Qt 6 (QOpenGLWindow), cgltf, cglm и OpenGL 3.3
A step-by-step guide to configuring and integrating ozz-animation, cgltf, cglm, GLAD, SDL3_image, and Qt 6 static libraries to render an animated Y-Bot model via QOpenGLWindow on Windows and Ubuntu. Пошаговое руководство по настройке и интеграции статических библиотек ozz-animation, cgltf, cglm, GLAD, SDL3_image и Qt 6 для рендеринга анимированной модели Y-Bot через QOpenGLWindow под Windows и Ubuntu.
General (OpenGL Loader, Math & glTF Libraries): Общее (Загрузчик OpenGL, математическая библиотека и загрузчик glTF):
- Installing GLAD OpenGL Loader Library on Windows & Ubuntu (OpenGL 3.3) Установка библиотеки-загрузчика OpenGL GLAD под Windows и Ubuntu (OpenGL 3.3)
- Installing cglm Library Установка библиотеки cglm
- Installing cgltf C glTF Loading Library Установка C-библиотеки загрузки glTF cgltf
Windows (MinGW GCC 16.2): Windows (MinGW GCC 16.2):
- Building Static Qt 6 for Desktop OpenGL with MinGW GCC 16.2 Статическая сборка Qt 6 для Desktop OpenGL с MinGW GCC 16.2
- Building SDL3 Static Library for Windows Сборка статической библиотеки SDL3 для Windows
- Building SDL3_image Static Library with WebP Support for Windows (MinGW & CMake) Сборка статической библиотеки SDL3_image с поддержкой WebP для Windows (MinGW и CMake)
Ubuntu & Ubuntu WSL: Ubuntu и Ubuntu WSL:
- Building Static Qt 6 for Desktop OpenGL on Ubuntu & Ubuntu WSL Статическая сборка Qt 6 для Desktop OpenGL в Ubuntu и Ubuntu WSL
- Building SDL3 Static Library for Ubuntu Сборка статической библиотеки SDL3 для Ubuntu
- Building SDL3_image Static Library with WebP Support for Ubuntu (GCC, CMake & Ninja) Сборка статической библиотеки SDL3_image с поддержкой WebP для Ubuntu (GCC, CMake и Ninja)
Create Project Directory Создание директории проекта
Create a workspace folder and a new directory for your Qt 6 ozz-animation project: Создайте рабочую папку для проектов и новую директорию для вашего проекта Qt 6 ozz-animation:
Windows (Command Prompt / PowerShell)
mkdir C:\projects\y-bot-ozz-animation-cglm-opengl-qt6-cpp-desktop
mkdir C:\projects\y-bot-ozz-animation-cglm-opengl-qt6-cpp-desktop\src
mkdir C:\projects\y-bot-ozz-animation-cglm-opengl-qt6-cpp-desktop\assets\models\y-bot
cd C:\projects\y-bot-ozz-animation-cglm-opengl-qt6-cpp-desktop
Ubuntu (Terminal)
mkdir -p ~/projects/y-bot-ozz-animation-cglm-opengl-qt6-cpp-desktop/src
mkdir -p ~/projects/y-bot-ozz-animation-cglm-opengl-qt6-cpp-desktop/assets/models/y-bot
cd ~/projects/y-bot-ozz-animation-cglm-opengl-qt6-cpp-desktop
Download & Place Model, Texture, Skeleton & Animation Assets Скачивание и размещение файлов модели, текстуры, скелета и анимации
Download the Y-Bot 3D binary glTF model file, its WebP texture, skeleton data, and chicken dance animation files: Скачайте бинарный файл 3D-модели glTF Y-Bot, её текстуру WebP, данные скелета и файлы анимации танца цыпленка:
Download y-bot.glb Скачать y-bot.glb Download y-bot.webp Скачать y-bot.webp Download skeleton.ozz Скачать skeleton.ozz Download animation.ozz Скачать animation.ozz
Place y-bot.glb, y-bot.webp, skeleton.ozz, and animation.ozz into your project's assets/models/y-bot/ directory.
Поместите файлы y-bot.glb, y-bot.webp, skeleton.ozz и animation.ozz в папку вашего проекта assets/models/y-bot/.
Windows Path
C:\projects\y-bot-ozz-animation-cglm-opengl-qt6-cpp-desktop\assets\models\y-bot\y-bot.glb
C:\projects\y-bot-ozz-animation-cglm-opengl-qt6-cpp-desktop\assets\models\y-bot\y-bot.webp
C:\projects\y-bot-ozz-animation-cglm-opengl-qt6-cpp-desktop\assets\models\y-bot\skeleton.ozz
C:\projects\y-bot-ozz-animation-cglm-opengl-qt6-cpp-desktop\assets\models\y-bot\animation.ozz
Ubuntu / WSL Command (Copying from Windows to WSL)
If you downloaded and placed the assets inside your Windows project directory, copy them directly to your WSL Linux directory using the Windows mount path (/mnt/c/):
Если вы скачали и поместили ассеты в Windows-папку проекта, скопируйте их напрямую в Linux-папку WSL через монтированный путь Windows (/mnt/c/):
cp /mnt/c/projects/y-bot-ozz-animation-cglm-opengl-qt6-cpp-desktop/assets/models/y-bot/* \
~/projects/y-bot-ozz-animation-cglm-opengl-qt6-cpp-desktop/assets/models/y-bot/
Source Files (src/main.cpp, src/mainwindow.h, src/mainwindow.cpp & CMakeLists.txt) Исходные файлы (src/main.cpp, src/mainwindow.h, src/mainwindow.cpp и CMakeLists.txt)
You can create these files using Notepad / Sublime Text on Windows, or nano in Ubuntu terminal:
Вы можете создать эти файлы через Блокнот / Sublime Text в Windows или с помощью nano в терминале Ubuntu:
Windows (Terminal / Notepad)
notepad src\main.cpp
notepad src\mainwindow.h
notepad src\mainwindow.cpp
notepad CMakeLists.txt
Ubuntu (Terminal / Nano)
nano src/main.cpp
nano src/mainwindow.h
nano src/mainwindow.cpp
nano CMakeLists.txt
File Contents for src/main.cpp Содержимое файла src/main.cpp
#if defined(__linux__)
#include <QtPlugin>
Q_IMPORT_PLUGIN(QWaylandIntegrationPlugin)
#endif
#include "mainwindow.h"
#include <QGuiApplication>
#include <QSurfaceFormat>
#include <SDL3/SDL.h>
int main(int argc, char *argv[])
{
SDL_Init(0);
QSurfaceFormat format;
format.setVersion(3, 3);
format.setProfile(QSurfaceFormat::CoreProfile);
format.setDepthBufferSize(24);
format.setSwapInterval(1);
QSurfaceFormat::setDefaultFormat(format);
// QGuiApplication instead of QApplication (no widget engine overhead)
QGuiApplication a(argc, argv);
MainWindow w;
w.show();
int exitCode = a.exec();
SDL_Quit();
return exitCode;
}
File Contents for src/mainwindow.h Содержимое файла src/mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <glad/glad.h>
#include <cglm/cglm.h>
#include <cglm/affine.h>
#include <cglm/cam.h>
#include <cglm/mat4.h>
// Ozz-animation headers (math headers must precede containers using ozz types)
#include <ozz/base/maths/simd_math.h>
#include <ozz/base/maths/soa_transform.h>
#include <ozz/animation/runtime/animation.h>
#include <ozz/animation/runtime/sampling_job.h>
#include <ozz/animation/runtime/skeleton.h>
#include <ozz/base/containers/vector.h>
#include <QOpenGLWindow>
#include <QOpenGLContext>
#include <QTimer>
#include <QElapsedTimer>
#include <vector>
struct InverseBindMatrix {
mat4 m;
};
class MainWindow : public QOpenGLWindow
{
Q_OBJECT
public:
MainWindow();
~MainWindow() override;
protected:
void initializeGL() override;
void resizeGL(int w, int h) override;
void paintGL() override;
private:
bool loadModelGLB(const char *path);
GLuint createTextureWithSDL3(const char *path);
GLuint m_shaderProgram = 0;
GLuint m_vao = 0;
GLuint m_posVbo = 0;
GLuint m_uvVbo = 0;
GLuint m_jointsVbo = 0;
GLuint m_weightsVbo = 0;
GLuint m_ebo = 0;
GLuint m_texture = 0;
GLsizei m_indexCount = 0;
GLenum m_indexType = GL_UNSIGNED_SHORT;
GLint m_mvpLoc = -1;
GLint m_texLoc = -1;
GLint m_jointMatricesLoc = -1;
// Ozz-animation variables
ozz::animation::Skeleton m_ozzSkeleton;
ozz::animation::Animation m_ozzAnimation;
ozz::animation::SamplingJob::Context m_ozzSamplingContext;
float m_ozzAnimationTime = 0.0f;
ozz::vector<ozz::math::Float4x4> m_ozzModelMatrices;
std::vector<InverseBindMatrix> m_ybotInverseBindMatrices;
QTimer *m_timer = nullptr;
QElapsedTimer m_elapsedTimer;
qint64 m_lastNsecs = 0;
};
#endif // MAINWINDOW_H
File Contents for src/mainwindow.cpp (Pure QOpenGLWindow with cglm) Содержимое файла src/mainwindow.cpp (QOpenGLWindow с cglm)
#include "mainwindow.h"
#define CGLTF_IMPLEMENTATION
#include <cgltf.h>
#include <SDL3/SDL.h>
#include <SDL3_image/SDL_image.h>
#include <ozz/animation/runtime/local_to_model_job.h>
#include <ozz/base/io/archive.h>
#include <ozz/base/io/stream.h>
#include <QDebug>
#include <cmath>
#include <cstring>
#include <utility>
// Custom SDL3 stream wrapper for ozz-animation archives
class OzzSDLStream : public ozz::io::Stream
{
public:
OzzSDLStream(SDL_IOStream *io)
: io_(io)
, opened_(io != nullptr)
{
if (io_)
SDL_SeekIO(io_, 0, SDL_IO_SEEK_SET);
}
~OzzSDLStream()
{
if (io_)
SDL_CloseIO(io_);
}
bool opened() const override { return opened_; }
size_t Read(void *buffer, size_t size) override
{
size_t total = 0;
while (total < size)
{
size_t read = SDL_ReadIO(io_, (uint8_t *)buffer + total, size - total);
if (read == 0)
break;
total += read;
}
return total;
}
size_t Write(const void *, size_t) override { return 0; }
int Seek(int offset, Origin origin) override
{
SDL_IOWhence whence = SDL_IO_SEEK_SET;
if (origin == kCurrent)
whence = SDL_IO_SEEK_CUR;
else if (origin == kEnd)
whence = SDL_IO_SEEK_END;
Sint64 pos = SDL_SeekIO(io_, offset, whence);
return pos >= 0 ? 0 : -1;
}
int Tell() const override
{
Sint64 pos = SDL_TellIO(io_);
return pos >= 0 ? (int)pos : -1;
}
size_t Size() const override
{
Sint64 size = SDL_GetIOSize(io_);
return size >= 0 ? (size_t)size : 0;
}
private:
SDL_IOStream *io_;
bool opened_;
};
// -----------------------------------------------------------------------------
// Shaders: Skinning Matrix Palette, MVP Matrix & WebP Texture Mapping
// -----------------------------------------------------------------------------
static const char *skinningVertexShaderSource = R"(#version 330 core
layout (location = 0) in vec3 aPosition;
layout (location = 1) in vec2 aTexCoord;
layout (location = 2) in vec4 aJoints; // Up to 4 influencing joints per vertex
layout (location = 3) in vec4 aWeights; // Weights corresponding to each joint
out vec2 vTexCoord;
uniform mat4 uMvpMatrix;
const int MAX_JOINTS = 100;
uniform mat4 uJointMatrices[MAX_JOINTS];
void main()
{
mat4 skinMatrix =
aWeights.x * uJointMatrices[int(aJoints.x)]
+ aWeights.y * uJointMatrices[int(aJoints.y)]
+ aWeights.z * uJointMatrices[int(aJoints.z)]
+ aWeights.w * uJointMatrices[int(aJoints.w)];
vec4 skinnedPos = skinMatrix * vec4(aPosition, 1.0);
vTexCoord = aTexCoord;
gl_Position = uMvpMatrix * skinnedPos;
}
)";
static const char *skinningFragmentShaderSource = R"(#version 330 core
in vec2 vTexCoord;
uniform sampler2D ourTexture;
out vec4 fragColor;
void main()
{
fragColor = texture(ourTexture, vTexCoord);
}
)";
// ==========================================
// MainWindow Implementation (Pure QOpenGLWindow)
// ==========================================
MainWindow::MainWindow()
: QOpenGLWindow(QOpenGLWindow::NoPartialUpdate)
{
setTitle("Qt 6 ozz-animation Y-Bot Model (cglm)");
resize(800, 450);
}
MainWindow::~MainWindow()
{
makeCurrent();
if (m_texture) glDeleteTextures(1, &m_texture);
if (m_vao) glDeleteVertexArrays(1, &m_vao);
if (m_posVbo) glDeleteBuffers(1, &m_posVbo);
if (m_uvVbo) glDeleteBuffers(1, &m_uvVbo);
if (m_jointsVbo) glDeleteBuffers(1, &m_jointsVbo);
if (m_weightsVbo) glDeleteBuffers(1, &m_weightsVbo);
if (m_ebo) glDeleteBuffers(1, &m_ebo);
if (m_shaderProgram) glDeleteProgram(m_shaderProgram);
doneCurrent();
}
GLuint MainWindow::createTextureWithSDL3(const char *path)
{
SDL_IOStream *io = SDL_IOFromFile(path, "rb");
if (!io) {
qWarning() << "Failed to open file stream for" << path << SDL_GetError();
return 0;
}
SDL_Surface *surface = IMG_Load_IO(io, 1);
if (!surface) {
qWarning() << "Image loading failed:" << SDL_GetError();
return 0;
}
SDL_Surface *optSurface = SDL_ConvertSurface(surface, SDL_PIXELFORMAT_ABGR8888);
SDL_DestroySurface(surface);
if (!optSurface) {
qWarning() << "Surface conversion failed:" << SDL_GetError();
return 0;
}
GLuint textureID = 0;
glGenTextures(1, &textureID);
glBindTexture(GL_TEXTURE_2D, textureID);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, optSurface->w, optSurface->h,
0, GL_RGBA, GL_UNSIGNED_BYTE, optSurface->pixels);
glGenerateMipmap(GL_TEXTURE_2D);
SDL_DestroySurface(optSurface);
return textureID;
}
bool MainWindow::loadModelGLB(const char *path)
{
size_t glbSize = 0;
void *glbData = SDL_LoadFile(path, &glbSize);
if (!glbData) {
qWarning() << "Failed to load Y-Bot model file into memory:" << SDL_GetError();
return false;
}
cgltf_options options = {};
cgltf_data *data = nullptr;
if (cgltf_parse(&options, glbData, glbSize, &data) != cgltf_result_success)
{
qWarning() << "Failed to parse Y-Bot GLB model:" << path;
SDL_free(glbData);
return false;
}
cgltf_load_buffers(&options, data, path);
if (data->meshes_count == 0 || data->meshes[0].primitives_count == 0)
{
cgltf_free(data);
SDL_free(glbData);
return false;
}
cgltf_primitive &prim = data->meshes[0].primitives[0];
cgltf_accessor *posAccessor = nullptr;
cgltf_accessor *uvAccessor = nullptr;
cgltf_accessor *jointsAccessor = nullptr;
cgltf_accessor *weightsAccessor = nullptr;
cgltf_accessor *indexAccessor = prim.indices;
for (cgltf_size i = 0; i < prim.attributes_count; ++i)
{
if (prim.attributes[i].type == cgltf_attribute_type_position)
posAccessor = prim.attributes[i].data;
else if (prim.attributes[i].type == cgltf_attribute_type_texcoord)
uvAccessor = prim.attributes[i].data;
else if (prim.attributes[i].type == cgltf_attribute_type_joints)
jointsAccessor = prim.attributes[i].data;
else if (prim.attributes[i].type == cgltf_attribute_type_weights)
weightsAccessor = prim.attributes[i].data;
}
glGenVertexArrays(1, &m_vao);
glBindVertexArray(m_vao);
// Positions (Location = 0)
if (posAccessor && posAccessor->buffer_view && posAccessor->buffer_view->buffer)
{
const uint8_t *base = static_cast<const uint8_t *>(posAccessor->buffer_view->buffer->data);
const void *positions = base + posAccessor->buffer_view->offset + posAccessor->offset;
size_t posSize = posAccessor->count * 3 * sizeof(float);
glGenBuffers(1, &m_posVbo);
glBindBuffer(GL_ARRAY_BUFFER, m_posVbo);
glBufferData(GL_ARRAY_BUFFER, posSize, positions, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void *)0);
}
// Texture UVs (Location = 1)
if (uvAccessor && uvAccessor->buffer_view && uvAccessor->buffer_view->buffer)
{
const uint8_t *base = static_cast<const uint8_t *>(uvAccessor->buffer_view->buffer->data);
const void *uvs = base + uvAccessor->buffer_view->offset + uvAccessor->offset;
size_t uvSize = uvAccessor->count * 2 * sizeof(float);
glGenBuffers(1, &m_uvVbo);
glBindBuffer(GL_ARRAY_BUFFER, m_uvVbo);
glBufferData(GL_ARRAY_BUFFER, uvSize, uvs, GL_STATIC_DRAW);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), (void *)0);
}
// Joint Indices (Location = 2)
if (jointsAccessor && jointsAccessor->buffer_view && jointsAccessor->buffer_view->buffer)
{
const uint8_t *base = static_cast<const uint8_t *>(jointsAccessor->buffer_view->buffer->data);
const void *jointsData = base + jointsAccessor->buffer_view->offset + jointsAccessor->offset;
size_t jointsSize = jointsAccessor->count * jointsAccessor->stride;
glGenBuffers(1, &m_jointsVbo);
glBindBuffer(GL_ARRAY_BUFFER, m_jointsVbo);
glBufferData(GL_ARRAY_BUFFER, jointsSize, jointsData, GL_STATIC_DRAW);
GLenum jointGlType = GL_UNSIGNED_SHORT;
size_t componentSize = sizeof(unsigned short);
if (jointsAccessor->component_type == cgltf_component_type_r_8u) {
jointGlType = GL_UNSIGNED_BYTE;
componentSize = sizeof(unsigned char);
}
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 4, jointGlType, GL_FALSE, 4 * componentSize, (void *)0);
}
// Joint Weights (Location = 3)
if (weightsAccessor && weightsAccessor->buffer_view && weightsAccessor->buffer_view->buffer)
{
const uint8_t *base = static_cast<const uint8_t *>(weightsAccessor->buffer_view->buffer->data);
const void *weightsData = base + weightsAccessor->buffer_view->offset + weightsAccessor->offset;
size_t weightsSize = weightsAccessor->count * 4 * sizeof(float);
glGenBuffers(1, &m_weightsVbo);
glBindBuffer(GL_ARRAY_BUFFER, m_weightsVbo);
glBufferData(GL_ARRAY_BUFFER, weightsSize, weightsData, GL_STATIC_DRAW);
glEnableVertexAttribArray(3);
glVertexAttribPointer(3, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void *)0);
}
// Element Indices (EBO)
if (indexAccessor && indexAccessor->buffer_view && indexAccessor->buffer_view->buffer)
{
const uint8_t *base = static_cast<const uint8_t *>(indexAccessor->buffer_view->buffer->data);
const void *indices = base + indexAccessor->buffer_view->offset + indexAccessor->offset;
size_t indexSize = indexAccessor->count * indexAccessor->stride;
glGenBuffers(1, &m_ebo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ebo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexSize, indices, GL_STATIC_DRAW);
if (indexAccessor->component_type == cgltf_component_type_r_32u)
m_indexType = GL_UNSIGNED_INT;
else if (indexAccessor->component_type == cgltf_component_type_r_16u)
m_indexType = GL_UNSIGNED_SHORT;
else if (indexAccessor->component_type == cgltf_component_type_r_8u)
m_indexType = GL_UNSIGNED_BYTE;
m_indexCount = static_cast<GLsizei>(indexAccessor->count);
}
glBindVertexArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
// Inverse Bind Matrices
if (data->skins_count > 0)
{
cgltf_skin &skin = data->skins[0];
if (skin.inverse_bind_matrices)
{
cgltf_accessor *ibmAccessor = skin.inverse_bind_matrices;
size_t numJointsInSkin = skin.joints_count;
m_ybotInverseBindMatrices.resize(numJointsInSkin);
const float *ibmData = reinterpret_cast<const float *>(
static_cast<const uint8_t *>(ibmAccessor->buffer_view->buffer->data) +
ibmAccessor->buffer_view->offset +
ibmAccessor->offset);
for (size_t i = 0; i < numJointsInSkin; ++i) {
memcpy(m_ybotInverseBindMatrices[i].m, &ibmData[i * 16], 16 * sizeof(float));
}
}
}
cgltf_free(data);
SDL_free(glbData);
return true;
}
void MainWindow::initializeGL()
{
gladLoadGLLoader([](const char *name) -> void * {
return reinterpret_cast<void *>(QOpenGLContext::currentContext()->getProcAddress(name));
});
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
GLuint vs = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vs, 1, &skinningVertexShaderSource, nullptr);
glCompileShader(vs);
GLint success;
char infoLog[512];
glGetShaderiv(vs, GL_COMPILE_STATUS, &success);
if (!success) {
glGetShaderInfoLog(vs, 512, nullptr, infoLog);
qWarning() << "Vertex Shader Compilation Failed:" << infoLog;
}
GLuint fs = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fs, 1, &skinningFragmentShaderSource, nullptr);
glCompileShader(fs);
glGetShaderiv(fs, GL_COMPILE_STATUS, &success);
if (!success) {
glGetShaderInfoLog(fs, 512, nullptr, infoLog);
qWarning() << "Fragment Shader Compilation Failed:" << infoLog;
}
m_shaderProgram = glCreateProgram();
glAttachShader(m_shaderProgram, vs);
glAttachShader(m_shaderProgram, fs);
glLinkProgram(m_shaderProgram);
glGetProgramiv(m_shaderProgram, GL_LINK_STATUS, &success);
if (!success) {
glGetProgramInfoLog(m_shaderProgram, 512, nullptr, infoLog);
qWarning() << "Shader Program Link Failed:" << infoLog;
}
glDeleteShader(vs);
glDeleteShader(fs);
m_mvpLoc = glGetUniformLocation(m_shaderProgram, "uMvpMatrix");
m_texLoc = glGetUniformLocation(m_shaderProgram, "ourTexture");
m_jointMatricesLoc = glGetUniformLocation(m_shaderProgram, "uJointMatrices");
// Load Ozz Skeleton
const char *skeletonPath = "assets/models/y-bot/skeleton.ozz";
SDL_IOStream *skeletonIo = SDL_IOFromFile(skeletonPath, "rb");
if (skeletonIo) {
OzzSDLStream stream(skeletonIo);
ozz::io::IArchive archive(&stream);
if (archive.TestTag<ozz::animation::Skeleton>()) {
ozz::animation::Skeleton tempSkeleton;
archive >> tempSkeleton;
m_ozzSkeleton = std::move(tempSkeleton);
} else {
qWarning() << "CRITICAL: Archive tag mismatch for Skeleton!";
}
} else {
qWarning() << "Failed to open ozz skeleton:" << skeletonPath;
}
// Load Ozz Animation
const char *animationPath = "assets/models/y-bot/animation.ozz";
SDL_IOStream *animIo = SDL_IOFromFile(animationPath, "rb");
if (animIo) {
OzzSDLStream stream(animIo);
ozz::io::IArchive archive(&stream);
archive >> m_ozzAnimation;
} else {
qWarning() << "Failed to open ozz animation:" << animationPath;
}
m_ozzSamplingContext.Resize(m_ozzSkeleton.num_joints());
m_ozzAnimationTime = 0.0f;
m_ozzModelMatrices.resize(m_ozzSkeleton.num_joints());
loadModelGLB("assets/models/y-bot/y-bot.glb");
m_texture = createTextureWithSDL3("assets/models/y-bot/y-bot.webp");
// -------------------------------------------------------------------------
// Exact equivalent of SDL_HINT_MAIN_CALLBACK_RATE = "60"
// Timer fires once every 16ms and sleeps the rest of the time.
// -------------------------------------------------------------------------
m_elapsedTimer.start();
m_lastNsecs = 0;
m_timer = new QTimer(this);
m_timer->setTimerType(Qt::PreciseTimer);
connect(m_timer, &QTimer::timeout, this, QOverload<>::of(&QOpenGLWindow::update));
m_timer->start(16); // 60 FPS
}
void MainWindow::resizeGL(int w, int h)
{
glViewport(0, 0, w, h);
}
void MainWindow::paintGL()
{
qint64 currentNsecs = m_elapsedTimer.nsecsElapsed();
float deltaTime = static_cast<float>(currentNsecs - m_lastNsecs) / 1e9f;
m_lastNsecs = currentNsecs;
if (m_ozzAnimation.duration() > 0.0f) {
m_ozzAnimationTime += deltaTime;
if (m_ozzAnimationTime > m_ozzAnimation.duration()) {
m_ozzAnimationTime = std::fmod(m_ozzAnimationTime, m_ozzAnimation.duration());
}
ozz::animation::SamplingJob sampling_job;
sampling_job.animation = &m_ozzAnimation;
sampling_job.ratio = m_ozzAnimationTime / m_ozzAnimation.duration();
sampling_job.context = &m_ozzSamplingContext;
ozz::vector<ozz::math::SoaTransform> locals;
locals.resize(m_ozzSkeleton.num_soa_joints());
sampling_job.output = make_span(locals);
if (sampling_job.Run()) {
ozz::animation::LocalToModelJob conv_job;
conv_job.skeleton = &m_ozzSkeleton;
conv_job.input = make_span(locals);
conv_job.output = make_span(m_ozzModelMatrices);
conv_job.Run();
}
}
glClearColor(0.2f, 0.2f, 0.2f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
if (m_texture && m_indexCount > 0 && !m_ozzModelMatrices.empty())
{
glUseProgram(m_shaderProgram);
// Model Matrix
mat4 model;
glm_mat4_identity(model);
// View Matrix (Frame Y-Bot)
mat4 view;
vec3 eye = {0.0f, 1.2f, 3.0f};
vec3 center = {0.0f, 0.9f, 0.0f};
vec3 up = {0.0f, 1.0f, 0.0f};
glm_lookat(eye, center, up, view);
// Perspective Projection Matrix
mat4 projection;
float aspect = (height() > 0) ? (float)width() / (float)height() : 1.0f;
glm_perspective(glm_rad(45.0f), aspect, 0.1f, 100.0f, projection);
mat4 view_model;
glm_mat4_mul(view, model, view_model);
mat4 mvp;
glm_mat4_mul(projection, view_model, mvp);
glUniformMatrix4fv(m_mvpLoc, 1, GL_FALSE, (const GLfloat *)mvp);
const int activeJointIndices[] = {
2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21,
22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39,
40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57,
58, 59, 60, 61, 62, 63, 64, 65, 66
};
const int numActiveJoints = 65;
std::vector<float> jointMatricesData(numActiveJoints * 16);
for (int idx = 0; idx < numActiveJoints; ++idx) {
int i = activeJointIndices[idx];
const ozz::math::Float4x4 &m = m_ozzModelMatrices[i];
mat4 ozzMat;
memcpy(ozzMat, &m.cols[0], 16 * sizeof(float));
mat4 finalJointMat;
if (idx < (int)m_ybotInverseBindMatrices.size()) {
glm_mat4_mul(ozzMat, m_ybotInverseBindMatrices[idx].m, finalJointMat);
} else {
glm_mat4_copy(ozzMat, finalJointMat);
}
memcpy(&jointMatricesData[idx * 16], finalJointMat, 16 * sizeof(float));
}
glUniformMatrix4fv(m_jointMatricesLoc, numActiveJoints, GL_FALSE, jointMatricesData.data());
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, m_texture);
glUniform1i(m_texLoc, 0);
glBindVertexArray(m_vao);
glDrawElements(GL_TRIANGLES, m_indexCount, m_indexType, 0);
glBindVertexArray(0);
}
// DO NOT call requestUpdate() here. The QTimer handles the 60 FPS tick rate.
}
This implementation uses QGuiApplication and QOpenGLWindow (with QOpenGLWindow::NoPartialUpdate) to eliminate widget engine overhead, combined with a precise 16ms QTimer matching the 60 FPS callback rate of SDL3. On Linux, Q_IMPORT_PLUGIN(QWaylandIntegrationPlugin) ensures static Wayland support.
Эта реализация использует QGuiApplication и QOpenGLWindow (с QOpenGLWindow::NoPartialUpdate), чтобы избежать накладных расходов подсистемы виджетов, в паре с точным 16-миллисекундным QTimer, эквивалентным частоте 60 FPS коллбэков SDL3. В Linux макрос Q_IMPORT_PLUGIN(QWaylandIntegrationPlugin) обеспечивает статическую поддержку Wayland.
File Contents for CMakeLists.txt Содержимое файла CMakeLists.txt
cmake_minimum_required(VERSION 3.21)
if(NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE "Debug")
endif()
project(y-bot-ozz-animation-cglm-opengl-qt6-cpp-desktop CXX C)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
set(CMAKE_AUTOUIC ON)
# -----------------------------------------------------------------------------
# Paths
# -----------------------------------------------------------------------------
if(WIN32)
set(GLAD_DIR "C:/libs/glad-0.1.36/opengl-3.3")
set(CGLTF_INCLUDE_DIR "C:/libs/cgltf-1.15")
set(CGLM_DIR "C:/libs/cglm-0.9.6")
set(SDL3_DIR "C:/libs/sdl3-3.4.18-mingw/lib/cmake/SDL3")
set(SDL3_image_DIR "C:/libs/sdl3_image-3.4.8-webp-mingw/lib/cmake/SDL3_image")
set(webp_ROOT "C:/libs/webp-1.6.0-mingw")
set(webp_INCLUDE_DIR "C:/libs/webp-1.6.0-mingw/include")
set(webp_LIBRARY "C:/libs/webp-1.6.0-mingw/lib/libwebp.a")
set(OZZ_DIR "C:/libs/ozz-animation-0.17.0-mingw")
else()
set(GLAD_DIR "$ENV{HOME}/libs/glad-0.1.36/opengl-3.3")
set(CGLTF_INCLUDE_DIR "$ENV{HOME}/libs/cgltf-1.15")
set(CGLM_DIR "$ENV{HOME}/libs/cglm-0.9.6")
set(SDL3_DIR "$ENV{HOME}/libs/sdl3-3.4.18-ubuntu/lib/cmake/SDL3")
set(SDL3_image_DIR "$ENV{HOME}/libs/sdl3_image-3.4.8-webp-ubuntu/lib/cmake/SDL3_image")
set(webp_ROOT "$ENV{HOME}/libs/webp-1.6.0-ubuntu")
set(webp_INCLUDE_DIR "$ENV{HOME}/libs/webp-1.6.0-ubuntu/include")
set(webp_LIBRARY "$ENV{HOME}/libs/webp-1.6.0-ubuntu/lib/libwebp.a")
set(OZZ_DIR "$ENV{HOME}/libs/ozz-animation-0.17.0-ubuntu")
endif()
# -----------------------------------------------------------------------------
# Locate Packages
# -----------------------------------------------------------------------------
find_package(Qt6 REQUIRED COMPONENTS Widgets OpenGLWidgets)
# Wayland is only present and required on Linux (Ubuntu / WSL)
if(UNIX AND NOT APPLE)
find_package(Qt6 REQUIRED COMPONENTS WaylandClient)
endif()
find_package(SDL3 REQUIRED CONFIG)
find_package(SDL3_image REQUIRED CONFIG)
# -----------------------------------------------------------------------------
# Fix Ninja issue: Clear bogus relative link paths from SDL3_image static target
# -----------------------------------------------------------------------------
if(TARGET SDL3_image::SDL3_image-static)
set_target_properties(SDL3_image::SDL3_image-static PROPERTIES INTERFACE_LINK_LIBRARIES "")
endif()
# -----------------------------------------------------------------------------
# Executable Target (qt_add_executable for static plugin support)
# -----------------------------------------------------------------------------
qt_add_executable(app
src/main.cpp
src/mainwindow.h
src/mainwindow.cpp
${GLAD_DIR}/src/glad.c
)
# -----------------------------------------------------------------------------
# Include Directories & Definitions
# -----------------------------------------------------------------------------
target_include_directories(app PRIVATE
${GLAD_DIR}/include
${CGLTF_INCLUDE_DIR}
${CGLM_DIR}/include
${webp_INCLUDE_DIR}
${OZZ_DIR}/include
)
# -----------------------------------------------------------------------------
# Copy Assets to Build Directory
# -----------------------------------------------------------------------------
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/assets")
add_custom_command(TARGET app POST_BUILD
COMMAND ${CMAKE_COMMAND} -E remove_directory "$<TARGET_FILE_DIR:app>/assets"
COMMAND ${CMAKE_COMMAND} -E copy_directory
"${CMAKE_CURRENT_SOURCE_DIR}/assets"
"$<TARGET_FILE_DIR:app>/assets"
COMMENT "Copying assets directory"
)
endif()
# -----------------------------------------------------------------------------
# Link Flags & Stripping (Applied to BOTH Windows & Ubuntu)
# -----------------------------------------------------------------------------
target_link_options(app PRIVATE -static-libgcc -static-libstdc++)
if(NOT CMAKE_BUILD_TYPE STREQUAL "Debug")
target_link_options(app PRIVATE -s)
endif()
if(WIN32)
target_link_libraries(app PRIVATE
Qt6::Widgets
Qt6::OpenGLWidgets
SDL3_image::SDL3_image-static
SDL3::SDL3-static
opengl32
C:/libs/webp-1.6.0-mingw/lib/libwebpdemux.a
C:/libs/webp-1.6.0-mingw/lib/libwebpmux.a
C:/libs/webp-1.6.0-mingw/lib/libwebp.a
C:/libs/webp-1.6.0-mingw/lib/libsharpyuv.a
${OZZ_DIR}/lib/libozz_animation_offline_r.a
${OZZ_DIR}/lib/libozz_animation_r.a
${OZZ_DIR}/lib/libozz_geometry_r.a
${OZZ_DIR}/lib/libozz_options_r.a
${OZZ_DIR}/lib/libozz_base_r.a
)
# Full static linking and subsystem selection only on Windows
target_link_options(app PRIVATE -static)
if(CMAKE_BUILD_TYPE STREQUAL "Debug")
target_link_options(app PRIVATE -mconsole)
else()
target_compile_options(app PRIVATE -Os)
target_link_options(app PRIVATE -mwindows)
endif()
else()
target_link_libraries(app PRIVATE
$ENV{HOME}/libs/qt-6.12.0-static-gcc/plugins/platforms/libqwayland.a
Qt6::Widgets
Qt6::OpenGLWidgets
Qt6::WaylandClient
SDL3_image::SDL3_image-static
SDL3::SDL3-static
GL
$ENV{HOME}/libs/webp-1.6.0-ubuntu/lib/libwebpdemux.a
$ENV{HOME}/libs/webp-1.6.0-ubuntu/lib/libwebpmux.a
$ENV{HOME}/libs/webp-1.6.0-ubuntu/lib/libwebp.a
$ENV{HOME}/libs/webp-1.6.0-ubuntu/lib/libsharpyuv.a
${OZZ_DIR}/lib/libozz_animation_offline_r.a
${OZZ_DIR}/lib/libozz_animation_r.a
${OZZ_DIR}/lib/libozz_geometry_r.a
${OZZ_DIR}/lib/libozz_options_r.a
${OZZ_DIR}/lib/libozz_base_r.a
)
endif()
Build & Execution Scripts Скрипты сборки и запуска
Windows (MinGW / Batch Scripts)
config-win.bat
@echo off
cmake -G Ninja -S . -B dist/win ^
-DCMAKE_PREFIX_PATH="C:/Qt/6.12.0_static_mingw162" ^
-DCMAKE_BUILD_TYPE=Release
build-win.bat
@echo off
cmake --build dist/win
run-win.bat
@echo off
.\dist\win\app.exe
Run the scripts 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 \
-DCMAKE_PREFIX_PATH="$HOME/libs/qt-6.12.0-static-gcc" \
-DCMAKE_BUILD_TYPE=Release
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 execute permissions on Ubuntu before running: Предоставьте права на выполнение в Ubuntu перед запуском:
chmod +x config-linux.sh build-linux.sh run-linux.sh
./config-linux.sh
./build-linux.sh
./run-linux.sh
Expected Output Ожидаемый результат
After running the build and execution scripts, a Qt window should appear displaying the animated Y-Bot character performing the chicken dance: После запуска скриптов сборки и выполнения появится окно Qt с отображением анимированного персонажа Y-Bot, исполняющего танец цыпленка:
Qt 6 ozz-animation Y-Bot Model (cglm)
Understanding the OzzSDLStream Adapter Class Разбор класса-адаптера OzzSDLStream
The ozz-animation runtime uses an abstract stream interface (ozz::io::Stream) to read and deserialize skeletons and animations via its archive system (ozz::io::IArchive). By wrapping SDL3's modern SDL_IOStream, we enable loading .ozz assets across any platform supported by SDL without depending on standard C file streams:
Библиотека ozz-animation использует абстрактный интерфейс потоков (ozz::io::Stream) для чтения и десериализации скелетов и анимаций через систему архивов (ozz::io::IArchive). Оборачивая современный SDL_IOStream из SDL3, мы обеспечиваем загрузку ассетов .ozz на любой платформе, поддерживаемой SDL, без привязки к стандартным файловым потокам C:
// Custom SDL3 stream wrapper for ozz-animation archives
class OzzSDLStream : public ozz::io::Stream
{
public:
OzzSDLStream(SDL_IOStream *io)
: io_(io)
, opened_(io != nullptr)
{
if (io_)
SDL_SeekIO(io_, 0, SDL_IO_SEEK_SET);
}
~OzzSDLStream()
{
if (io_)
SDL_CloseIO(io_);
}
bool opened() const override { return opened_; }
size_t Read(void *buffer, size_t size) override
{
size_t total = 0;
while (total < size)
{
size_t read = SDL_ReadIO(io_, (uint8_t *)buffer + total, size - total);
if (read == 0)
break;
total += read;
}
return total;
}
size_t Write(const void *, size_t) override { return 0; }
int Seek(int offset, Origin origin) override
{
SDL_IOWhence whence = SDL_IO_SEEK_SET;
if (origin == kCurrent)
whence = SDL_IO_SEEK_CUR;
else if (origin == kEnd)
whence = SDL_IO_SEEK_END;
Sint64 pos = SDL_SeekIO(io_, offset, whence);
return pos >= 0 ? 0 : -1;
}
int Tell() const override
{
Sint64 pos = SDL_TellIO(io_);
return pos >= 0 ? (int)pos : -1;
}
size_t Size() const override
{
Sint64 size = SDL_GetIOSize(io_);
return size >= 0 ? (size_t)size : 0;
}
private:
SDL_IOStream *io_;
bool opened_;
};
Class Methods Breakdown Разбор методов класса
-
Takes ownership of the openedOzzSDLStream(SDL_IOStream *io)&~OzzSDLStream()SDL_IOStream*, rewinds the stream position to the beginning (SDL_SeekIO(io_, 0, SDL_IO_SEEK_SET)), and safely closes it withSDL_CloseIO(io_)when the stream object goes out of scope (RAII pattern). Принимает владение открытымSDL_IOStream*, сбрасывает позицию чтения в начало файла (SDL_SeekIO(io_, 0, SDL_IO_SEEK_SET)) и гарантированно закрывает поток с помощьюSDL_CloseIO(io_)при выходе из области видимости по паттерну RAII. -
Reports whether the underlying stream handle was successfully opened and is valid for read operations. Сообщает, был ли исходный дескриптор потока успешно открыт и готов ли он к операциям чтения.bool opened() const override -
Readssize_t Read(void *buffer, size_t size) overridesizebytes intobuffer. Uses awhileloop with pointer arithmetic ((uint8_t *)buffer + total) to handle short/partial reads from disk until either all requested bytes are gathered or End-Of-File / error occurs. Считываетsizeбайт в буферbuffer. Использует циклwhileс адресной арифметикой ((uint8_t *)buffer + total) для корректной обработки неполных (частичных) чтений, пока не будет получен весь блок данных или не встретится EOF/ошибка. -
Returnssize_t Write(const void *, size_t) override0because this stream is strictly read-only for loading pre-baked skeleton and animation data. Возвращает0, так как данный поток предназначен исключительно для чтения готовых файлов скелета и анимации. -
Maps Ozz's seek origin enum (int Seek(int offset, Origin origin) overridekCurrent,kEnd, and default beginning) to SDL3'sSDL_IOWhenceconstants (SDL_IO_SEEK_CUR,SDL_IO_SEEK_END,SDL_IO_SEEK_SET). Returns0on success and-1on error. Сопоставляет перечисление точки отсчета Ozz (kCurrent,kEndи начало по умолчанию) с константами SDL3SDL_IOWhence(SDL_IO_SEEK_CUR,SDL_IO_SEEK_END,SDL_IO_SEEK_SET). Возвращает0при успехе и-1при ошибке. -
Queries the current byte offset within the stream viaint Tell() const overrideSDL_TellIO(io_). Запрашивает текущее смещение в байтах внутри потока черезSDL_TellIO(io_). -
Returns the total byte size of the file using SDL3'ssize_t Size() const overrideSDL_GetIOSize(io_). Возвращает общий размер файла в байтах с помощью встроенной функции SDL3SDL_GetIOSize(io_).
Deep Dive: OzzSDLStream::Read Method Подробный разбор метода OzzSDLStream::Read
This function implements the virtual ozz::io::Stream::Read() method using SDL3's SDL_ReadIO() API. It acts as an adapter bridging ozz-animation archives (ozz::io::IArchive) and SDL3 file streams (SDL_IOStream):
Эта функция реализует виртуальный метод ozz::io::Stream::Read() с использованием API SDL3 SDL_ReadIO(). Она служит адаптером между архивами ozz-animation (ozz::io::IArchive) и потоками данных SDL3 (SDL_IOStream):
size_t Read(void *buffer, size_t size) override
{
size_t total = 0;
while (total < size)
{
size_t read = SDL_ReadIO(io_, (uint8_t *)buffer + total, size - total);
if (read == 0)
break;
total += read;
}
return total;
}
Line-by-Line Breakdown Построчный разбор
-
size_t Read(void *buffer, size_t size) override
Overrides the pure virtual read method fromozz::io::Stream. It accepts a destination memory pointerbufferand the number of bytessizerequested by the ozz deserializer. Переопределяет виртуальный метод чтения изozz::io::Stream. Принимает указатель на целевой буфер памятиbufferи количество байтsize, запрошенных десериализатором ozz. -
size_t total = 0; while (total < size)
Initializes a byte counter to track progress and runs a loop until all requested bytes are gathered. Инициализирует счётчик байт и выполняет цикл до тех пор, пока не будет прочитан весь запрошенный объём данных. -
(uint8_t *)buffer + total
In C++, pointer arithmetic cannot be performed directly onvoid*. Casting touint8_t*allows byte-level offsetting so each consecutive read appends immediately after the previously read bytes. В C++ нельзя выполнять адресную арифметику надvoid*. Приведение кuint8_t*позволяет выполнять побайтовое смещение, благодаря чему каждая следующая порция данных записывается строго вслед за предыдущей. -
size_t read = SDL_ReadIO(io_, (uint8_t *)buffer + total, size - total);
Invokes SDL3's stream read operation, requesting only the remaining bytes (size - total). Returns the actual number of bytes read in this pass. Вызывает операцию чтения SDL3, запрашивая только недостающие байты (size - total). Возвращает фактическое число прочитанных байт за данный вызов. -
if (read == 0) break;
In SDL3,SDL_ReadIOreturns 0 on End-of-File (EOF) or unrecoverable error. The loop breaks immediately to avoid an infinite loop. В SDL3SDL_ReadIOвозвращает 0 при достижении конца файла (EOF) или возникновении ошибки. Цикл сразу прерывается для предотвращения бесконечного зацикливания. -
total += read;
Accumulates the number of bytes read in the current iteration. Прибавляет число прочитанных в текущей итерации байт к общей сумме. -
return total;
Returns the total number of bytes successfully read (equalssizeon complete success, or less if EOF was reached early). Возвращает общее количество успешно прочитанных байт (равноsizeпри полном успехе либо меньше, если конец файла наступил раньше).
Why the Loop is Necessary (Handling Partial Reads) Зачем нужен цикл (обработка частичного чтения)
Low-level I/O operations are not guaranteed to deliver the entire requested chunk in a single call (often referred to as a "short read"). The while loop guarantees that the stream continuously accumulates data until the entire expected data structure (skeleton, animation curves, or joint matrices) is fully loaded without memory corruption.
Низкоуровневые операции ввода-вывода не гарантируют передачу всего запрошенного блока данных за один вызов («короткое чтение»). Цикл while гарантирует непрерывный добор данных, пока вся структура (скелет, анимационные кривые или матрицы суставов) не будет загружена целиком без повреждения памяти.
Complete source code for this project is available on GitHub: Полный исходный код проекта доступен на GitHub:
View on GitHub Смотреть на GitHubSupport My Work Поддержать проект
If these tutorials helped you, consider buying me a coffee! Если эти туториалы вам помогли, вы можете поддержать автора.
Sberbank (Russia only) Сбербанк (только для РФ)
Direct transfer via phone number (Russia only) Перевод по номеру телефона (только для РФ)
USDT TRC20
Support via Cryptocurrency Поддержка криптовалютой