Reader small image

You're reading from  C++ Game Animation Programming - Second Edition

Product typeBook
Published inDec 2023
Reading LevelN/a
PublisherPackt
ISBN-139781803246529
Edition2nd Edition
Languages
Tools
Concepts
Right arrow
Authors (2):
Michael Dunsky
Michael Dunsky
author image
Michael Dunsky

Michael Dunsky is an educated electronics technician, game developer, and console porting programmer with more than 20 years of programming experience. He started at the age of 14 with BASIC, adding on his way Assembly language, C, C++, Java, Python, VHDL, OpenGL, GLSL, and Vulkan to his portfolio. During his career, he also gained extensive knowledge in virtual machines, server operation, infrastructure automation, and other DevOps topics. Michael holds a Master of Science degree in Computer Science from the FernUniversität in Hagen, focused on computer graphics, parallel programming and software systems.
Read more about Michael Dunsky

Gabor Szauer
Gabor Szauer
author image
Gabor Szauer

Gabor Szauer has been making games since 2010. He graduated from Full Sail University in 2010 with a bachelor's degree in game development. Gabor maintains an active Twitter presence, and maintains a programming-oriented game development blog. Gabor's previously published books are Game Physics Programming Cookbook and Lua Quick Start Guide, both published by Packt.
Read more about Gabor Szauer

View More author details
Right arrow

8

Loading Models
in the glTF Format

Welcome to Chapter 8! In the previous two chapters, we explored the mathematical elements and GLM data types of Vector, Matrix, Quaternion, and Spline.

In this chapter, you will learn how to use these four data types to transform the data from the glTF model description in a file into a C++ model class, storing the first parts of the glTF data to display a static, non-animated model on the screen. We will progressively expand the C++ model class in the upcoming chapters, incorporating additional data from the glTF model we utilize.

At the end of the chapter, you will know the basic elements of the glTF format, how to load it into a C++ class using a glTF loader library, and how to display the loaded model on the screen in the OpenGL and Vulkan renderer.

In this chapter, we will cover the following topics:

  • An analysis of the glTF file format
  • Exploring an example glTF file
  • Using a C++ glTF loader to get the model data
  • ...

Technical requirements

For this chapter, you will need the example code from Chapter 6, 02_opengl_movement, or Chapter 7, 02_opengl_quaternion or 03_opengl_relative_rotation, as a basis for the new code.

For a better understanding of the internal data for the models we will use for the remaining part of the book, we will start with a broad overview of the file format.

An analysis of the glTF file format

The glTF file format was created with efficiency in the transmission and loading of 3D scenes
and models in mind. The file format is an open standard, supports external files and embedded, Base64-encoded data, and can be easily extended to adopt new features.

Figure 8.1 shows the general hierarchy of the glTF file format. Even if it contains only a small number of object types, loading and interpreting a file can be a complex task.

Figure 8.1: An overview of the glTF 2.0 file format

Figure 8.1: An overview of the glTF 2.0 file format

We will take a closer look at these objects and their function in the file format. Some of the descriptions may sound abstract, but these will be clarified once we look at an glTF example file in the Exploring an example glTF file section.

The following list describes the main elements of a glTF file:

  • Scene: The top element of every glTF file is the scene. The scene is the anchor for all other elements, creating a hierarchical...

Exploring an example glTF file

The glTF format uses JSON to store data. JSON is a well-known format; readers and writers are available for all kinds of operating systems and programming languages. A second format type, binary glTF, contains the textual description and all referred data in a single file. The binary type avoids the overhead for the Base64 encoding of the file data and the management of several separate files for the model description, texture images, and other buffer data.

We will now walk through the basic glTF file using the official glTF tutorial. The link to this glTF file is available in the Additional resources section.

Understanding the scenes element

The first part of the file defines the scene, or scenes:

{
  "scene": 0,
  "scenes" : [
    {
      "nodes" : [ 0 ]
    }
  ],

The scene field contains the index of the...

Using a C++ glTF loader to get the model data

An uncomplicated way to load a glTF model into a structured data model can be achieved by using a glTF loader library. For this book, we will use the tinygltf library.

The repository for the project is available at GitHub: https://github.com/syoyo/tinygltf.

We need to add a couple of files to our project. Create a new folder called tinygltf, download the following files, and move them into the new folder:

  • tiny_gltf.h
  • tiny_gltf.cc
  • json.hpp

The tiny_gltf.h file contains the glTF loader implementation itself; this is the file we will have to include to the classes loading the model file. The next file on the list, tiny_gltf.cc, has some additional C-style #define directives that are required for the loader. The last file, json.hpp, is required to read and write JSON files.

In addition to these three files, we need to get two other files. Download these two files to the include folder:

  • stb_image.h
  • ...

Adding new glTF shaders

Most of the glTF models contain a normal vector for every vertex, in addition to the color and the position we used for the textured box in the Loading and compiling shaders section of Chapter 2. The normal vector will be used to calculate the angle between every triangle and a light vector in the scene. We will then use a simple lighting model to make the final color brighter or darker, depending on the angle between the normal of the vertex and the light source.

To support the changed format for the vertex data, we must create a new pair of shaders. The first shader is the vertex shader. Create a new file, gltf.vert, in the shaders folder:

#version 460 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec3 aNormal;
layout (location = 2) in vec2 aTexCoord;

The shader uses GLSL 4.6, like the other renderer shaders in the Loading and compiling shaders section of Chapter 2, and the Fitting the Vulkan nuts and bolts together section of...

Organizing the loaded data into a C++ class

As we have now explored the glTF file format and an example glTF file, extending the shader code in preparation to draw a glTF model in previous sections of this chapter, we will use this new-found knowledge to create a new C++ model class. The new class will encapsulate all functionality and code to load a glTF file from the filesystem, drawing the model defined by the file on the screen.

Learning about the design and implementation of the C++ class

Our new model class will have two purposes:

  • Loading a glTF model: To load the model, we need the filename for the model and the texture; plus, we will update the user interface to show the number of triangles that the glTF model is made of
  • To draw a glTF model: Drawing the model needs to be split into the creation of the vertex and index buffer, the upload of the vertex and index data, and the call to draw the model itself

Finally, a cleanup method will be implemented...

Summary

In this chapter, we explored the structure of a glTF model file format by using a simple example. Other glTF model files will be much more complex, so we just focused on the important parts. You can try out the suggestions in the Practical sessions section; they will enable you to load and draw even more complex models.

The theoretical knowledge gained from the analysis of the glTF file format and the exploration of the example file has been used to create a C++ class, containing the vertex data of the model and the vertex indices to draw the model. Our focus here was to encapsulate the model data and create independent objects that can be drawn to the screen using a couple of simple commands in the renderer.

In the following chapter, we will continue with the fundamental parts of a character in a game. You will learn the basic steps to animate a game character, how animation data is stored in the glTF model file, and how to extract and interpret this data.

Practical sessions

Here are some ideas if you want to get a deeper insight into the glTF format:

  • Change the lightPos and lightColor fragment shader variables into uniform variables, and make them adjustable via sliders in the user interface. You could use two SliderFloat3 ImGui elements – one for the color, and the other one for the position.
  • Load a binary glTF model. A link to sample models is included in the Additional resources section. The tinygltf loader has a function to load binary models, called LoadBinaryFromFile(); you should use the filename extension to switch between textual (.gltf) and binary (.glb) model format loading.
  • Try to load the textures of the binary models. The textures are not stored as separate files but included in the binary model file. Compared to the normal file-based method, this should be easier, as you will get the texture data to upload to the GPU as part of one of the glTF buffers – no need to load from files.
  • Add...

Additional resources

lock icon
The rest of the chapter is locked
You have been reading a chapter from
C++ Game Animation Programming - Second Edition
Published in: Dec 2023Publisher: PacktISBN-13: 9781803246529
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at AU $19.99/month. Cancel anytime

Authors (2)

author image
Michael Dunsky

Michael Dunsky is an educated electronics technician, game developer, and console porting programmer with more than 20 years of programming experience. He started at the age of 14 with BASIC, adding on his way Assembly language, C, C++, Java, Python, VHDL, OpenGL, GLSL, and Vulkan to his portfolio. During his career, he also gained extensive knowledge in virtual machines, server operation, infrastructure automation, and other DevOps topics. Michael holds a Master of Science degree in Computer Science from the FernUniversität in Hagen, focused on computer graphics, parallel programming and software systems.
Read more about Michael Dunsky

author image
Gabor Szauer

Gabor Szauer has been making games since 2010. He graduated from Full Sail University in 2010 with a bachelor's degree in game development. Gabor maintains an active Twitter presence, and maintains a programming-oriented game development blog. Gabor's previously published books are Game Physics Programming Cookbook and Lua Quick Start Guide, both published by Packt.
Read more about Gabor Szauer