Sure! Below is a basic implementation of a 2D text game engine in C++ using SDL3 and OpenGL 3.3. This engine sets up an SDL window with an OpenGL context, uses FreeType to load and render fonts, and includes a simple game loop to handle events and rendering.
Note: This example is a starting point to help you build your own 2D text-based game engine. You'll need to have the following libraries installed and properly linked in your development environment:
- SDL3
- OpenGL 3.3
- FreeType
- GLM (OpenGL Mathematics Library)
Step 1: Setting Up the Project
First, set up your C++ project and ensure all the libraries are correctly linked. Include the necessary headers in your main file.
// main.cpp
#include <iostream>
#include <string>
#include <map>
// SDL and OpenGL headers
#include <SDL3/SDL.h>
#include <SDL3/SDL_opengl.h>
// GLM for matrix transformations
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
// FreeType for font rendering
#include <ft2build.h>
#include FT_FREETYPE_H
Step 2: Shader Code
Create vertex and fragment shaders for rendering text. The shaders will handle positioning and coloring of text glyphs.
Vertex Shader (text.vs):
#version 330 core
layout (location = 0) in vec4 vertex;
// <vec2 pos, vec2 tex>
out vec2 TexCoords;
uniform mat4 projection;
void main()
{
gl_Position = projection * vec4(vertex.xy, 0.0, 1.0);
TexCoords = vertex.zw;
}
Fragment Shader (text.fs):
#version 330 core
in vec2 TexCoords;
out vec4 color;
uniform sampler2D text;
uniform vec3 textColor;
void main()
{
float alpha = texture(text, TexCoords).r;
color = vec4(textColor, alpha);
}
Step 3: Initialize SDL and OpenGL
Set up SDL with an OpenGL context.
bool initSDL(SDL_Window*& window, SDL_GLContext& glContext, const std::string& title, int width, int height)
{
if (SDL_Init(SDL_INIT_VIDEO) != 0)
{
std::cerr << "SDL Init Failed: " << SDL_GetError() << std::endl;
return false;
}
// Set OpenGL attributes
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);
// Create window
window = SDL_CreateWindow(title.c_str(), width, height, SDL_WINDOW_OPENGL);
if (!window)
{
std::cerr << "Window Creation Failed: " << SDL_GetError() << std::endl;
return false;
}
// Create OpenGL context
glContext = SDL_GL_CreateContext(window);
if (!glContext)
{
std::cerr << "OpenGL Context Creation Failed: " << SDL_GetError() << std::endl;
return false;
}
// Initialize OpenGL loader (e.g., GLAD) here if needed
// Enable blending
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
return true;
}
Step 4: Load and Compile Shaders
Write functions to compile shaders and link them into a program.
GLuint compileShader(const char* source, GLenum shaderType)
{
GLuint shader = glCreateShader(shaderType);
glShaderSource(shader, 1, &source, nullptr);
glCompileShader(shader);
// Check for compilation errors
GLint success;
glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
if (!success)
{
// Handle errors
char infoLog[512];
glGetShaderInfoLog(shader, 512, nullptr, infoLog);
std::cerr << "Shader Compilation Failed:\n" << infoLog << std::endl;
}
return shader;
}
GLuint createShaderProgram(const char* vertexSource, const char* fragmentSource)
{
GLuint vertexShader = compileShader(vertexSource, GL_VERTEX_SHADER);
GLuint fragmentShader = compileShader(fragmentSource, GL_FRAGMENT_SHADER);
// Link shaders into a program
GLuint shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
glLinkProgram(shaderProgram);
// Check for linking errors
GLint success;
glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);
if (!success)
{
// Handle errors
char infoLog[512];
glGetProgramInfoLog(shaderProgram, 512, nullptr, infoLog);
std::cerr << "Program Linking Failed:\n" << infoLog << std::endl;
}
// Clean up shaders as they're linked now
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
return shaderProgram;
}
Step 5: Set Up FreeType and Load Fonts
Define a structure to hold character information and load the font using FreeType.
struct Character {
GLuint TextureID; // ID handle of the glyph texture
glm::ivec2 Size; // Size of glyph
glm::ivec2 Bearing; // Offset from baseline to left/top of glyph
GLuint Advance; // Offset to advance to next glyph
};
std::map<GLchar, Character> Characters;
bool loadFont(FT_Library& ft, const std::string& fontPath, GLuint& VAO, GLuint& VBO)
{
// Initialize FreeType
if (FT_Init_FreeType(&ft))
{
std::cerr << "Could not init FreeType Library" << std::endl;
return false;
}
// Load font
FT_Face face;
if (FT_New_Face(ft, fontPath.c_str(), 0, &face))
{
std::cerr << "Failed to load font" << std::endl;
return false;
}
// Set font size
FT_Set_Pixel_Sizes(face, 0, 48);
// Disable byte-alignment restriction
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
// Load first 128 ASCII characters
for (unsigned char c = 0; c < 128; c++)
{
// Load character glyph
if (FT_Load_Char(face, c, FT_LOAD_RENDER))
{
std::cerr << "Failed to load Glyph: " << c << std::endl;
continue;
}
// Generate texture
GLuint texture;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexImage2D(
GL_TEXTURE_2D,
0,
GL_RED,
face->glyph->bitmap.width,
face->glyph->bitmap.rows,
0,
GL_RED,
GL_UNSIGNED_BYTE,
face->glyph->bitmap.buffer
);
// Set texture options
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);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// Store character data
Character character = {
texture,
glm::ivec2(face->glyph->bitmap.width, face->glyph->bitmap.rows),
glm::ivec2(face->glyph->bitmap_left, face->glyph->bitmap_top),
static_cast<GLuint>(face->glyph->advance.x)
};
Characters.insert(std::pair<GLchar, Character>(c, character));
}
// Clean up FreeType
FT_Done_Face(face);
FT_Done_FreeType(ft);
// Configure VAO/VBO for texture quads
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 6 * 4, nullptr, GL_DYNAMIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(float), nullptr);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
return true;
}
Step 6: Render Text Function
Create a function that renders the text using the loaded fonts and OpenGL.
void renderText(GLuint& shaderProgram, const std::string& text, GLfloat x, GLfloat y, GLfloat scale, glm::vec3 color, GLuint VAO, GLuint VBO)
{
// Activate corresponding render state
glUseProgram(shaderProgram);
glUniform3f(glGetUniformLocation(shaderProgram, "textColor"), color.x, color.y, color.z);
glActiveTexture(GL_TEXTURE0);
glBindVertexArray(VAO);
// Iterate over characters
std::string::const_iterator c;
for (c = text.begin(); c != text.end(); c++)
{
Character ch = Characters[*c];
GLfloat xpos = x + ch.Bearing.x * scale;
GLfloat ypos = y - (ch.Size.y - ch.Bearing.y) * scale;
GLfloat w = ch.Size.x * scale;
GLfloat h = ch.Size.y * scale;
// Update VBO for each character
float vertices[6][4] = {
{ xpos, ypos + h, 0.0f, 0.0f },
{ xpos, ypos, 0.0f, 1.0f },
{ xpos + w, ypos, 1.0f, 1.0f },
{ xpos, ypos + h, 0.0f, 0.0f },
{ xpos + w, ypos, 1.0f, 1.0f },
{ xpos + w, ypos + h, 1.0f, 0.0f }
};
// Render glyph texture over quad
glBindTexture(GL_TEXTURE_2D, ch.TextureID);
// Update content of VBO memory
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices);
glBindBuffer(GL_ARRAY_BUFFER, 0);
// Render quad
glDrawArrays(GL_TRIANGLES, 0, 6);
// Advance cursors for next glyph
x += (ch.Advance >> 6) * scale;
}
glBindVertexArray(0);
glBindTexture(GL_TEXTURE_2D, 0);
}
Step 7: Main Function and Game Loop
Bring everything together in the main function and set up a basic game loop.
int main(int argc, char* argv[])
{
// Initialize SDL and OpenGL
SDL_Window* window = nullptr;
SDL_GLContext glContext;
const int screenWidth = 800;
const int screenHeight = 600;
if (!initSDL(window, glContext, "2D Text Game Engine", screenWidth, screenHeight))
{
return -1;
}
// Load shaders
// Load shader source code from files or define strings (as shown earlier)
const char* vertexShaderSource = /* vertex shader code */;
const char* fragmentShaderSource = /* fragment shader code */;
GLuint shaderProgram = createShaderProgram(vertexShaderSource, fragmentShaderSource);
// Configure projection matrix
glm::mat4 projection = glm::ortho(0.0f, static_cast<GLfloat>(screenWidth), 0.0f, static_cast<GLfloat>(screenHeight));
glUseProgram(shaderProgram);
glUniformMatrix4fv(glGetUniformLocation(shaderProgram, "projection"), 1, GL_FALSE, glm::value_ptr(projection));
// Load font and set up text rendering
FT_Library ft;
GLuint VAO, VBO;
if (!loadFont(ft, "path/to/your/font.ttf", VAO, VBO))
{
return -1;
}
// Main loop flag
bool quit = false;
SDL_Event e;
// Game loop
while (!quit)
{
// Event handling
while (SDL_PollEvent(&e))
{
if (e.type == SDL_EVENT_QUIT)
{
quit = true;
}
// Handle other events (keyboard, mouse, etc.)
}
// Clear screen
glClearColor(0.f, 0.f, 0.f, 1.f);
glClear(GL_COLOR_BUFFER_BIT);
// Render text
renderText(shaderProgram, "Hello, World!", 25.0f, screenHeight - 50.0f, 1.0f, glm::vec3(1.0f, 1.0f, 1.0f), VAO, VBO);
// Update window
SDL_GL_SwapWindow(window);
}
// Clean up
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
Additional Notes
- Font Path: Replace
"path/to/your/font.ttf" with the actual path to a TrueType font file on your system.
- Shader Sources: You'll need to provide the actual shader code strings or load them from files where indicated in the code.
- OpenGL Loader: You'll need an OpenGL function loader like GLAD or GLEW for modern OpenGL function pointers. Initialize it after creating the OpenGL context.
- Error Handling: The code includes basic error handling. You may want to expand on this for robustness.
- Event Handling: Extend the event handling to capture keyboard and mouse input as required for your game.
- Rendering Logic: This example renders a static "Hello, World!" text. You can expand the
renderText calls to render game UI, player stats, dialogue, etc.
Building the Project
Ensure all library paths and linker settings are correctly configured in your build system or IDE. If you're using CMake, your CMakeLists.txt might include:
cmake_minimum_required(VERSION 3.10)
project(TextGameEngine)
find_package(SDL3 REQUIRED)
find_package(Freetype REQUIRED)
find_package(GLM REQUIRED)
# Include OpenGL and GLAD as needed
add_executable(TextGameEngine main.cpp)
target_include_directories(TextGameEngine PRIVATE ${SDL3_INCLUDE_DIRS} ${FREETYPE_INCLUDE_DIRS} ${GLM_INCLUDE_DIRS})
target_link_libraries(TextGameEngine PRIVATE ${SDL3_LIBRARIES} ${FREETYPE_LIBRARIES} OpenGL::GL)
Next Steps
- Game Mechanics: Implement game logic, states, and mechanics according to your game's design.
- Text Formatting: Enhance text rendering to support multi-line text, alignment, and styling.
- Resource Management: Implement proper resource loading and management for textures, fonts, and other assets.
- UI Elements: Build additional UI components like buttons, menus, and dialogues.
Feel free to ask if you have any questions or need further assistance with specific parts of the code!