raylib-cpp

repository·master·Indexed 21 days ago

https://github.com/robloach/raylib-cpp

A header-only C++ object-oriented wrapper for the raylib graphics library (version 6.0.3). It transforms raylib's C-style procedural API into an idiomatic C++ interface featuring automatic resource management (RAII), method chaining, operator overloading, and support for C++20 modules. The library provides a RaylibException for asset loading errors and supports multiple build systems including CMake, Make, and VSCode, with targets for both Desktop and Web via Emscripten.

Tokens
2.1K
Snippets
8
Records
13
Agent score
65%

What's inside raylib-cpp

  1. Handling asset loading errors with RaylibException

    master

    Unlike standard raylib which only logs a warning when an asset fails to load, raylib-cpp throws a raylib::RaylibException (a subclass of std::runtime_error). This allows you to use standard C++ try-catch blocks to handle failed loads safely.

    try {
        raylib::Texture texture("FileNotFound.png");
    }
    catch (raylib::RaylibException& error) {
        TraceLog(LOG_ERROR, "Texture failed to load!");
    }
  2. How raylib-cpp object-oriented features work

    master

    raylib-cpp introduces several C++ paradigms to the raylib API:

    • Constructors: Object constructors handle loading resources (e.g., raylib::Texture2D texture("file.png"); instead of LoadTexture).
    • Object Methods: Methods that take an object as an argument can be called directly on that object (e.g., position.DrawPixel(color) instead of DrawPixelV(position, color)).
    • Method Naming: Redundant object names are removed from method names (e.g., texture.Draw() instead of DrawTexture(texture, ...)).
    • Optional Parameters: Many methods include sane defaults (e.g., texture.Draw(x, y) uses a default white tint).
    • Destructors: Objects automatically unload their raylib resources (textures, sounds, windows, etc.) when they go out of scope, removing the need for manual Unload or Close calls.
    • Property Get/Set: Properties can be accessed via SetX()/GetX() methods or directly via public members.
    • Function Overloading: Instead of using suffixes like V (for Vector), raylib-cpp uses standard C++ overloading to allow the same method name to accept different argument types.
    • Method Chaining: Methods that don't return a value typically return *this, allowing for fluent interfaces (e.g., image.Crop(...).FlipHorizontal().Resize(...)).
    • Operator Overloading: Mathematical operations can be performed directly on objects (e.g., position += speed).
    • Vector-Based Returns: Functions that return pointer-arrays in C are wrapped to return std::vector<T> in raylib-cpp.
    • String Support: Many functions are overloaded to accept std::string directly, avoiding the need for .c_str().
  3. Quickstart with raylib-cpp

    master

    raylib-cpp is a header-only C++ wrapper for raylib. It provides object-oriented wrappers around raylib's struct interfaces, making the API more idiomatic for C++ developers. To use it, you must link your project to raylib and include the header.

    Installation Steps

    1. Set up a raylib project following their build and installation instructions.
    2. Ensure your .cpp files are compiled with a C++ compiler.
    3. Download raylib-cpp.
    4. Include the header in your source code:
    #include "path/to/raylib-cpp.hpp"
    #include "raylib-cpp.hpp"
    
    int main() {
        int screenWidth = 800;
        int screenHeight = 450;
    
        raylib::Window window(screenWidth, screenHeight, "raylib-cpp - basic window");
        raylib::Texture logo("raylib_logo.png");
    
        SetTargetFPS(60);
    
        while (!window.ShouldClose())
        {
            BeginDrawing();
    
            window.ClearBackground(raylib::Color::RayWhite());
    
            DrawText("Congrats! You created your first window!", 190, 200, 20, raylib::Color::LightGray());
    
            // Object methods.
            logo.Draw(
                screenWidth / 2 - logo.GetWidth() / 2,
                screenHeight / 2 - logo.GetHeight() / 2);
    
            EndDrawing();
        }
    
        return 0;
    }
  4. Using raylib-cpp as a C++20 Module

    master

    If you are using C++20 or later, you can use raylib-cpp as a module. To do this, enable the BUILD_RAYLIB_CPP_MODULES define and link against the raylib_cpp_modules target instead of raylib_cpp.

    import raylib;
    
    using raylib::Color;
    using raylib::Window;
    
    int main() {
        Window window(800, 450, "raylib-cpp - basic window");
        // ...
        return 0;
    }
  5. Build a raylib-cpp project for Web using Emscripten

    master

    To target the Web platform, use the Emscripten toolchain. Use emcmake cmake with the -DPLATFORM=Web flag to configure the project for Web and -DCMAKE_BUILD_TYPE=Release for an optimized build. Compile the project using emmake make.

    mkdir build
    cd build
    emcmake cmake .. -DPLATFORM=Web -DCMAKE_BUILD_TYPE=Release
    emmake make
  6. Include raylib-cpp.hpp in multiple files

    master
    To use raylib-cpp across a project with multiple source files, include the header raylib-cpp.hpp in every .cpp file where you intend to use its classes and methods. This allows you to distribute your game logic, rendering code, and input handling across different modules while maintaining access to the raylib-cpp API.
  7. Build the raylib-cpp Make Example Project

    master

    To build the Raylib C++ Starter Kit using make, first clone the repository. The build process requires a setup step to prepare the environment before running the standard make command.

    Linux & macOS

    Use the standard make command:

    1. make setup
    2. make

    Windows

    Use mingw32-make (typically provided with MinGW/MSYS2):

    1. mingw32-make setup
    2. mingw32-make
    # Linux & macOS
    make setup
    make
    
    # Windows
    mingw32-make setup
    mingw32-make
  8. Build the raylib-cpp Doxygen documentation

    master

    To generate the API documentation for raylib-cpp, you must first ensure that all necessary submodules are initialized, then run the Doxygen build command using the provided Doxyfile. This process uses the doxygen-awesome-css theme for styling.

    git submodule update --init
    doxygen projects/Doxygen/Doxyfile
  9. Set up the raylib-cpp VSCode Example Project

    master

    To run the provided VSCode example project, follow these steps:

    1. Install Raylib: Ensure that the raylib library is already installed on your system.
    2. Prepare Headers: Download the include folder from the raylib-cpp repository and place it directly inside your VSCode project folder.
    3. Initialize Workspace:
      • Open FirstPerson.cpp in VSCode.
      • Open the Debug tab.
      • Click on "open a folder" and select the root directory of the project.
    4. Build and Run:
      • VSCode will restart at the welcome page.
      • Re-open FirstPerson.cpp.
      • Open the Debug tab again. You should now see two options: "Run" and "Debug".
      • Selecting either option will build the project and generate a .exe file.
  10. Choose a project template for raylib-cpp

    master

    When starting a new project with raylib-cpp, you can choose from several base templates depending on your preferred build system and IDE:

    • CMake: Best if you want to use cmake to generate build files and manage dependencies.
    • Make: A standard template that uses make to compile the project.
    • VSCode: A template optimized for Visual Studio Code that uses make combined with pre-configured VSCode settings for a smoother development experience.