I am making a c++ SDL game engine, currently doing the Renderer class which will be a…
- User
I am making a c++ SDL game engine, currently doing the Renderer class which will be a drop-in repleacement to original SDL_renderer, or at least the most used cases for game making. I need to give me ideas on how to complete it better, currently I have this:
class Renderer { public: Renderer(Window window, bool vsync); virtual ~Renderer(); void SetVsync(bool vsync); void Clear(); void Present(); void SetDrawColor(Uint8 r, Uint8 g, Uint8 b, Uint8 a); void Render(); void Update(const SDL_Event& e);
private: SDL_Renderer* renderer;};
- Assistant
Creating a custom Renderer class as a replacement or a wrapper for SDL_Renderer is a viable route for creating an engine. This allows you to abstract the rendering layer and provides the flexibility to implement custom rendering features, optimizations, or even support a different rendering backend in the future.
Here are some ideas and suggestions to consider as you continue developing your Renderer class:
-
Renderer Initialization: Consider extending the constructor or adding a method to handle SDL_RendererFlags, which allows for more control over the renderer’s behavior. Also, manage the creation and destruction of the
SDL_Windowwithin the renderer or in a separate Window class.Renderer(Window& window, bool vsync, Uint32 rendererFlags = SDL_RENDERER_ACCELERATED); -
Error Handling: Ensure that your class handles any potential errors gracefully. This could be during renderer initialization, setting the draw color, or presenting the renderer.
-
Texture Management: Introduce methods for loading, creating, and managing SDL_Textures. The class can manage a cache of textures for efficient reuse.
SDL_Texture* CreateTextureFromSurface(SDL_Surface* surface); SDL_Texture* LoadTexture(const std::string& filepath); void RenderTexture(SDL_Texture* texture, const SDL_Rect* srcrect, const SDL_Rect* dstrect); -
Rendering Primitives: Implement methods for drawing primitives like points, lines, rectangles, and filled shapes.
void DrawPoint(int x, int y); void DrawLine(int x1, int y1, int x2, int y2); void DrawRect(const SDL_Rect& rect); void FillRect(const SDL_Rect& rect); void DrawCircle(int x, int y, int radius); // You'll have to write this algorithm -
Rendering Text: Integrate SDL_ttf or another font library to support rendering text.
void RenderText(const std::string& text, TTF_Font* font, const SDL_Color& color, int x, int y); -
Transformations: Allow for the transformation of rendered items, like translation, rotation, and scaling.
void SetScale(float scaleX, float scaleY); void SetRotation(double angle, int x, int y); -
Layering and Depth: Incorporate support for layers or order-based rendering to manage which objects appear on top of others.
-
Viewport Management: Add support for manipulating the viewport for rendering scissor tests or window splits (e.g., split-screen multiplayer).
void SetViewport(const SDL_Rect& rect); void ResetViewport(); -
Blend Modes: Expose SDL’s blend modes for more advanced rendering effects.
void SetBlendMode(SDL_BlendMode blendMode); -
Batch Rendering: To improve performance, integrate a batching system that minimizes the number of draw calls by grouping together objects using the same textures and parameters.
-
Design Patterns: Implement design patterns such as the Component pattern for rendering-related components (e.g., Sprite, Animation) that can be added to your game objects.
-
Event Handling: Reconsider if the Renderer should be responsible for updating through SDL_Event, as this might be better suited for a separate Input or Event Manager class, separating concerns.
In summary, focus on building a Renderer class that is flexible, easy to use, and optimized for common game development scenarios. Think in terms of abstracting SDL specifics where it makes sense and providing a clear, higher-level interface for game-specific rendering tasks. Remember to adhere to good software engineering principles, such as single responsibility, low coupling, and high cohesion, to build a robust and maintainable engine.
-
- User
OK, few things. I don't want to expose the SDL library, as I want to do everything in my own library which will have SDL within but not exposing any SDL internal classes or logic. So far, I created the Renderer, the Window, the ScreenManager, ResourceManager, InputManager, GameScreen classes. and I am doing it iteratively to improve it by smaller increments at a time. Now having this in mind, write the previous again.
- Assistant
Apologies for the misunderstanding. Since you're looking to abstract away the SDL specifics and expose only your own classes and interfaces, here's an approach tailored to that goal:
-
Encapsulate Renderer Creation: Your Renderer should encapsulate the details of creating an SDL_Renderer. The Window reference held by the Renderer constructor should not expose SDL_Window.
// In your Renderer.h class Window; // Forward declaration to your own Window class class Renderer { public: Renderer(Window& window, bool vsync); // ... }; -
Separate Resource Handling: Let the ResourceManager handle loading and storing of resources, including textures and fonts. The Renderer can call upon the ResourceManager to fetch these without knowing the underlying SDL mechanisms.
-
Color and Blend Modes: Define your own color class or structure to prevent leaking SDL_Color details and create an abstraction for blend modes as an enum in your renderer header.
struct Color { Uint8 r, g, b, a; }; enum class BlendMode { None, Blend, Add, Mod // Map these to SDL's blend modes internally }; void SetDrawColor(const Color& color); void SetBlendMode(BlendMode blendMode); -
Texture Abstraction: Create a Texture class that wraps SDL_Texture usage, so that internally it uses SDL but externally you only interact with your engine's Texture class.
class Texture { public: // Provide a way to get dimensions or other properties without exposing SDL specifics private: SDL_Texture* sdlTexture; // This is private and thus not exposed // ... }; -
Rendering Shapes and Textures: Implement a collection of methods to render shapes and Texture objects, which will be used in place of calling SDL functions directly.
void DrawRect(const Rect& rect); void FillRect(const Rect& rect); // Add similar methods for points, lines, circles, etc. void RenderTexture(Texture& texture, const Rect& srcRect, const Rect& dstRect); -
Font and Text Rendering: Like Textures, create a Font class that encapsulates font handling and a method in the Renderer for rendering text without exposing SDL_ttf.
class Font { // ... }; void RenderText(const std::string& text, Font& font, const Color& color, const Point& position); -
Transformation and Layering: Implement transformation and layering methods without revealing SDL notions like render targets or SDL_RendererFlip.
-
Viewport and Camera: Instead of directly manipulating SDL's viewport, introduce a Camera class that controls what is rendered on the screen.
-
Batching and Performance: Design your Renderer to support efficient rendering by batching draw calls together where possible.
-
Input and Event Management: The Renderer shouldn't handle events. Rely on the InputManager to process input and an EventManager for broader communication across the system.
-
Design Patterns and Component System: Use design patterns to define components for sprites, animations, etc., without needing to know about SDL under the hood.
-
Documentation and Consistency: In addition to coding, ensure that you have documented your classes and methods clearly and keep a consistent interface design across your engine.
In your incremental approach, each iteration can tackle one area of rendering abstraction. Start with basic rendering, such as drawing colored rectangles, and work toward more advanced features, constantly ensuring the SDL details are hidden from the engine user.
-
- User
OK two things, Why do I need Color (SDL_Color) when renderer can manage rgba separately? if I want to do an incremental approach, which things I have to add first to what I already have?
- Assistant
If you prefer to manage RGBA color components separately in your Renderer rather than creating a Color struct, that's completely fine. The advantage of having a Color struct or class is for convenience and better code readability, as it allows you to pass around and manage colors as a single entity.
For instance, here is a comparison:
Without a
Colorstruct/class (current approach):void SetDrawColor(Uint8 r, Uint8 g, Uint8 b, Uint8 a);With a
Colorstruct/class:struct Color { Uint8 r, g, b, a; // You can add convenience methods or overloads here. }; void SetDrawColor(const Color& color); // This makes the function easier to read and use.The
Colorstruct would only serve as a simple data container, and using it could potentially make your API cleaner and more expressive. But whether or not to use it is a design choice that depends on your preferences and the goals of your engine.For the incremental approach to developing your Renderer class, let's define a rough order of features that you might implement, starting from the basics:
-
Initialization:
- Ensure Renderer can create an SDL renderer from a window, enable VSync if requested.
-
Color Management and Clearing:
- Methods for setting the draw color and clearing the screen. Even if you don't use a Color struct, managing RGBA separately is necessary.
-
Presenting Rendered Content:
- The
Present()method to show rendered content on the screen.
- The
-
Textures and Rendering:
- Basic Texture management (loading, creating textures).
- Rendering textures to the screen. Overload functions for different use cases (full texture, parts of textures).
-
Rendering Primitives:
- Methods to draw basic shapes (lines, rectangles, points).
- Optionally, methods to draw circles and other primitives if needed for your games.
-
Viewport and Camera:
- Camera implementation to control what part of the game world is visible on the screen.
- Viewport management to handle screen portions for rendering.
-
Transformation and Layering:
- Ability to apply transformations such as rotation and scaling to rendered objects.
- Support for layering or z-index to manage the rendering order of objects.
-
Text Rendering:
- Integrate font handling and render text to the screen.
-
Blend Modes and Effects:
- Implement blend modes and allow setting different render modes for various effects.
-
Performance Optimizations:
- Batch rendering optimizations to reduce draw calls.
-
Advanced Features (Optional):
- More complex rendering techniques like shaders, render-to-texture (framebuffer objects), particle systems, etc.
As you implement these features, test and refine each one before moving on to the next. Each feature should be fully functional and blend seamlessly with the existing implementation. By building up functionality in small increments, you can ensure stability and a solid foundation for later features.
-
- User
OK I am at step 4. Textures and Rendering, In my ResourceManager singleton static class, I have this method:
SDL_Surface* ResourceManager::GetSurface(std::string filepath) { if (surfaces.find(filepath) == surfaces.end()) { SDL_Surface* loadedImage = IMG_Load(filepath.c_str()); if (loadedImage != NULL) { surfaces.insert({ filepath, loadedImage }); } }
return surfaces[filepath];}
Can I use it to write the loading and creating of textures in the Renderer?
- Assistant
Yes, you can use your
ResourceManager::GetSurfacemethod to help with loading and creating textures within the Renderer class. The idea is that you can fetch the SDL_Surface using your ResourceManager and then use that surface to create an SDL_Texture that can be used for rendering.Here's a rough outline of the process to load and create a Texture in your Renderer class:
First, let's assume you have a Texture wrapper class:
class Texture final { public: ~Texture() { if (sdlTexture) { SDL_DestroyTexture(sdlTexture); } } // Other necessary functions for texture management private: SDL_Texture* sdlTexture = nullptr; // Other necessary properties such as width, height, etc. // Make Renderer a friend class so it can access the private sdlTexture friend class Renderer; };In your Renderer class, you would have methods such as the following:
class Renderer { public: // ... Texture LoadTexture(const std::string& filepath) { SDL_Surface* surface = ResourceManager::GetInstance().GetSurface(filepath); if (!surface) { // Surface loading failed, handle it appropriately // Maybe throw an exception or return a "null" Texture } SDL_Texture* sdlTexture = SDL_CreateTextureFromSurface(renderer, surface); if (!sdlTexture) { // Texture creation failed, handle it appropriately SDL_FreeSurface(surface); // Maybe throw an exception or return a "null" Texture } // Assuming that we don't need the surface after creating the texture SDL_FreeSurface(surface); Texture texture; texture.sdlTexture = sdlTexture; // Set the SDL_Texture inside the Texture wrapper // Set additional properties such as width and height based on the surface or texture. return texture; } // Methods for rendering the Texture should also be here, like: void RenderTexture(const Texture& texture, const SDL_Rect& srcRect, const SDL_Rect& dstRect) { // Do the rendering logic here using 'texture.sdlTexture' } // ... private: SDL_Renderer* renderer; };Remember to:
- Add error checking after calling SDL functions (such as
SDL_CreateTextureFromSurface) and handle any failures appropriately. - Ensure that you properly manage resource lifetimes. Since you're using raw pointers, be careful with resource deallocation to avoid memory leaks.
- Avoid directly returning or storing SDL pointers in your game engine’s public API to maintain abstraction over SDL.
Using a ResourceManager to centralize the loading and caching of surfaces is a good practice. It decouples resource loading from rendering and can make your code more modular and easier to maintain. Just make sure that your ResourceManager also handles the cleanup of the cached surfaces properly when they are no longer needed.
- Add error checking after calling SDL functions (such as
- User
I get the idea now, I also should change the SDL_Surface I was using to a wrapper, help me with that
- Assistant
Sure! Creating a wrapper class around
SDL_Surfaceis a good idea for keeping the SDL details hidden from the rest of your engine. A wrapper class can enhance the portability of your game engine and make it easier to extend or replace the underlying implementation in the future.Here's a simple example of what such a Surface wrapper class might look like, accompanied with basic usage inside the ResourceManager:
class Surface { public: Surface(const std::string& filepath) : surface_(IMG_Load(filepath.c_str())) { if (surface_ == nullptr) { throw std::runtime_error("Failed to load image: " + filepath); } } ~Surface() { if (surface_ != nullptr) { SDL_FreeSurface(surface_); } } Surface(const Surface&) = delete; // Non-copyable Surface& operator=(const Surface&) = delete; Surface(Surface&& other) noexcept : surface_(other.surface_) { other.surface_ = nullptr; } Surface& operator=(Surface&& other) noexcept { if (this != &other) { if (surface_ != nullptr) { SDL_FreeSurface(surface_); } surface_ = other.surface_; other.surface_ = nullptr; } return *this; } SDL_Surface* GetSDL_Surface() const { return surface_; } private: SDL_Surface* surface_; };In the ResourceManager, you would have a map holding your Surface objects. For example:
class ResourceManager { public: // ... Surface& GetSurface(const std::string& filepath) { auto it = surfaces.find(filepath); if (it == surfaces.end()) { // Construct a Surface and insert it into the map. auto result = surfaces.emplace(std::make_pair(filepath, Surface(filepath))); it = result.first; } return it->second; } // ... private: std::map<std::string, Surface> surfaces; // A cache of surfaces keyed by file paths. };Then in the Renderer class, when you wish to convert a Surface to an SDL_Texture, you can use the
GetSDL_Surface()method:class Renderer { // ... Texture LoadTexture(const std::string& filepath) { Surface& surface = ResourceManager::GetInstance().GetSurface(filepath); SDL_Surface* sdlSurface = surface.GetSDL_Surface(); SDL_Texture* sdlTexture = SDL_CreateTextureFromSurface(renderer, sdlSurface); if (!sdlTexture) { // Handle texture creation failure } Texture texture; texture.sdlTexture = sdlTexture; // Set additional texture properties return texture; } // ... };Remember:
- Manage the SDL_Surface memory within the Surface class to ensure there are no leaks.
- Implement move semantics to eliminate unnecessary copying, especially since SDL_Surface ownership is now tied to the Surface object.
- Provide a method to get the underlying
SDL_Surfacefor when you need to interface directly with SDL functions, but try to limit such usage to maintain abstraction. - Since the ResourceManager now includes wrapper objects rather than raw
SDL_Surfacepointers, there's no need to callSDL_FreeSurfacewithin the ResourceManager. The cleanup will be handled by their respective destructors.
By following this approach, your ResourceManager's
GetSurfacemethod will now return a reference to your Surface class, keeping the SDL implementation away from the user of your ResourceManager. - User
My ResourceManager now it giving me errors because previously I did the free surface in here, but now the new Surface is in charge of freeing the surface, how can I fix this?:
//class ResourceManager std::unordered_map<std::string, Surface> surfaces;
ResourceManager::~ResourceManager() { for (auto it = surfaces.begin(); it != surfaces.end(); ++it) { SDL_FreeSurface(it->second); //ERROR HERE }
surfaces.clear();}
- Assistant
You're right—the error occurs because you're trying to free the internal SDL_Surface of the Surface wrapper using
SDL_FreeSurfacedirectly. After wrapping theSDL_Surfacein your Surface class, the responsibility for managing the memory of the surface now resides entirely within the Surface class, specifically in its destructor.Since Surface objects are now in charge of cleaning up their own SDL_Surface, you no longer need to (and should not) free the surfaces in the ResourceManager's destructor.
Just remove the freeing code from the ResourceManager's destructor, and leave the
surfaces.clear()call to destroy all Surface objects, which will in turn call their destructors and free the SDL_Surface resources:// class ResourceManager std::unordered_map<std::string, Surface> surfaces; ResourceManager::~ResourceManager() { // No need to manually free the surfaces, as the Surface destructors will handle it. surfaces.clear(); // This will destroy all Surface instances. }As a side note,
surfaces.clear()is not necessary in the destructor because theunordered_mapwill automatically clear its contents on destruction. However, includingclear()in the destructor is not wrong and can sometimes be done for clarity or to ensure a specific order of operations during destruction.In sum, since your Resource Manager is now using the Surface wrapper class, you can rely on the automatic memory management provided by the C++ destructor mechanism. When the Resource Manager is destroyed, it will destroy all contained Surface objects, and their destructors will take care of releasing the
SDL_Surfaceresources. This is a great example of RAII (Resource Acquisition Is Initialization), a core concept in C++ resource management. - User
I had to delete some funtions in Surface, and now my ResourceManager::GetSurface code is throwing me errors how can I fix it? error: use of deleted function 'Surface::Surface(const Surface&)
Surface(const Surface&) = delete; Surface& operator=(const Surface&) = delete; Surface(Surface&& other) noexcept; Surface& operator=(Surface&& other) noexcept; SDL_Surface* GetSurface() const;Surface ResourceManager::GetSurface(const std::string& filePath) { auto it = surfaces.find(filePath); if (it == surfaces.end()) { auto result = surfaces.emplace(std::make_pair(filePath, Surface(filePath))); it = result.first; }
return it->second; //ERROR HERE}
- Assistant
The error you are encountering is due to trying to return a copy of Surface object by value, but you have explicitly deleted the copy constructor with
Surface(const Surface&) = delete;. Since copying is not allowed for Surface objects, you need to return a reference or a pointer to the Surface object.To fix the error, you should modify the return type of
ResourceManager::GetSurfaceto return a reference to the Surface object. Here's how you can do that:Surface& ResourceManager::GetSurface(const std::string& filePath) { auto it = surfaces.find(filePath); if (it == surfaces.end()) { // Use emplace to construct the Surface object in-place auto result = surfaces.emplace(filePath, Surface(filePath)); it = result.first; } return it->second; }By returning a reference (
Surface&), you avoid invoking the copy constructor, and you still give access to the Surface object instance stored in the map. Since you are returning a reference to an object stored inside yoursurfacesmap, you also ensure that the object's lifetime is managed by theResourceManager.Now when you call
GetSurface, you will be working with the actual surface object managed byResourceManager, and you won't be making any copies, which would otherwise be trying to invoke the deleted copy constructor.One key thing to remember is that returning a reference means the caller must ensure they don't hold onto the reference after the ResourceManager or the underlying map could potentially destroy the object, which would usually be on ResourceManager's destruction. As long as the ResourceManager lives, and the filepath isn't removed from the map, the reference is safe to use.
- User
Why do I have to pass a reference if I am storing it as std::unordered_map<std::string, Surface> surfaces;, I want to be able to pass the object Surface instead of a reference, or because copy is deleted I can't do it that way? I had to delete it since inside Surface there is a pointer: SDL_surface*
- Assistant
You're right; because you deleted the copy constructor (and copy assignment operator) in the
Surfaceclass, you cannot copySurfaceobjects. This design choice prevents accidental copies of resources, particularly ones that manage pointers or other non-trivial resources likeSDL_Surface, which could lead to double-free errors or other resource management issues if copied improperly.When managing resources like
SDL_Surfacethat require careful memory management, it's common to delete the copy constructor to enforce a single owner of the resource. This follows the rule of three/five/zero in C++, which states that if you provide a destructor or one of the copy operations, you should provide all three (destructor, copy constructor, and copy assignment operator) or disable them (by deleting them) and implement move semantics instead, ensuring resources are safely transferred without duplication.By deleting the copy constructor, you indicate that
Surfaceobjects should not be copied because they manage a unique resource. Instead, they should be moved if you want to transfer ownership, or you should work with references or pointers to the existing object without ownership transfer.Here's why you need to use a reference or pointer:
-
Preventing Copies: By having a deleted copy constructor, you avoid the possibility of implicit copies of the
Surfaceobject, which could otherwise result in multiple attempts to free the sameSDL_Surface. -
Maintaining Resource Ownership: The
ResourceManagerowns theSurfaceobjects. When you obtain aSurfacefromResourceManager, you don't want a new instance; you're typically interested in working with the same instance that theResourceManagerowns. -
Efficiency: Using references or pointers is more efficient because you avoid the overhead of copying potentially large objects. This is especially significant for resources like
SDL_Surfacethat could represent image data and might be large in memory.
Given these considerations, if you want to return an object from your
ResourceManager::GetSurfacemethod without copying, your options are limited to either returning a reference or a pointer.Returning a reference is usually clean and straightforward, as shown in the previous answer:
Surface& ResourceManager::GetSurface(const std::string& filePath) {Returning a pointer would work similarly, but often signals that nullability is possible (which you may want to avoid by ensuring resources are always available):
Surface* ResourceManager::GetSurface(const std::string& filePath) { // ... same logic ... return &it->second; }When returning a reference or pointer, just be mindful of the object's lifetime and who owns the resource to avoid dangling references/pointers.
-
- User
OK I understand now, the efficiency part sold me. Now you picked reference instead of a pointer, why was that?
- Assistant
The preference for returning a reference over a pointer in this scenario is primarily about semantics and what they communicate to the user of your
ResourceManager.When to use references:
-
Existence Guarantee: Returning a reference indicates that the object being referred to must exist. In other words, references in C++ cannot be null (under normal, defined behavior). This communicates to the caller that
GetSurfacewill always return a validSurface, and there's no need to check for null before using it. -
Simplicity: Using a reference is often simpler and cleaner in calling code, as you don't need to work with pointers (dereferencing, null-checks, etc.). This can make the calling code slightly more readable and intuitive.
-
Ownership and Lifetime: Returning a reference helps signify that the caller doesn't own the resource; it's just borrowing it. With references, the issue of memory ownership is less ambiguous — the
ResourceManagerowns theSurfaceand the caller should not attempt to manage its lifetime.
When to use pointers:
-
Optional Objects: If a function may sometimes return a "none" value (indicating the absence of an object), use pointers because they can be null. A null pointer can signify a failed object retrieval or the absence of an object.
-
Dynamic Allocation: If you create or manage objects on the heap and the lifetime isn't tied to a scope (e.g., it isn't automatically destroyed when a function returns), pointers are typically used.
-
Polymorphism: When dealing with objects that should be treated polymorphically (i.e., using subclasses through a pointer to a base class), pointers are the go-to, because C++ does not allow polymorphic behavior via object references (it requires pointers or smart pointers).
In the context of your
ResourceManagerclass, you expectGetSurfaceto always succeed and return a validSurfaceobject that theResourceManagerowns (assuming the filepath is correct and the file is accessible). You also expect that the lifetime of the returnedSurfaceis managed by theResourceManagerand not by the caller. Therefore, using a reference is more appropriate as it conveys these semantics clearly.If there was a scenario where
GetSurfacecould fail and not return a valid object (for example, if the file didn't exist), you'd want to return a pointer instead, and the function could returnnullptrto signal the failure. However, in your design, it seems you expect all resources to be available and failure either to not be a possibility or to be handled via other means (like exceptions or error codes).When designing your API, consistency is also important. If you're already using references in similar situations elsewhere in your codebase, it's good to keep that pattern unless there's a compelling reason to do otherwise.
-
- User
My Surface code doesn't actually deal with failures, because as it works with pointers internally, the element will be NULL if it fails. What can I do about it?
Surface::Surface(const std::string& filePath) { surface = IMG_Load(filePath.c_str());
if (surface == NULL) { SDL_LogError(SDL_LOG_CATEGORY_ERROR, "ERROR: Surface '%s' could not be created: %s\n", filePath.c_str(), SDL_GetError()); }}
- Assistant
In your current
Surfaceconstructor, whenIMG_Loadfails, it logs an error message but does not prevent the rest of the code from continuing with aNULLsurfacepointer, which can lead to undefined behavior later on when the surface is used.A common best practice to handle this kind of failure is to use exceptions. This way, if the
Surfaceinstantiation fails due to an inability to load the image, an exception can signal this exceptional condition to the calling code, giving it the opportunity to handle the error appropriately.Here is an example modification of your
Surfaceconstructor to incorporate exception handling:#include <stdexcept> // For std::runtime_error class Surface { public: Surface(const std::string& filePath) { surface = IMG_Load(filePath.c_str()); if (surface == nullptr) { std::string errorMsg = "ERROR: Surface '" + filePath + "' could not be created: " + SDL_GetError(); SDL_LogError(SDL_LOG_CATEGORY_ERROR, "%s\n", errorMsg.c_str()); throw std::runtime_error(errorMsg); } } // Rest of the implementation ... private: SDL_Surface* surface; };With this modification, when a
Surfaceobject is created andIMG_Loadfails, anstd::runtime_errorexception is thrown with an error message. This will immediately stop the construction process and propagate the error up the call stack, allowing it to be caught and handled where appropriate.Now, when you use
GetSurfacefrom yourResourceManager, you'll need to consider the possibility of an exception being thrown, like this:Surface& ResourceManager::GetSurface(const std::string& filePath) { auto it = surfaces.find(filePath); if (it == surfaces.end()) { try { // Try to create the Surface; this may throw an exception. auto result = surfaces.emplace(filePath, Surface(filePath)); it = result.first; } catch (const std::runtime_error& e) { // Handle the error, e.g., log it and/or take additional action. // Consider how you signal the caller of GetSurface about failure. SDL_LogError(SDL_LOG_CATEGORY_ERROR, "Failed to load surface: %s\n", e.what()); // Alternatively, rethrow the exception or throw a new one. throw; } } return it->second; }By throwing and catching exceptions, you handle potential failures without passing
NULLor invalidsurfacepointers around in your code. It enforces the idea that onceSurfaceis constructed, it always represents a valid, loaded surface. Additionally, you preserve the guarantee to the caller thatGetSurfaceeither succeeds and returns a valid reference or throws an exception.Remember, exception handling can add complexity and performance overhead if not used judiciously, so make sure it fits with the rest of your application's error-handling strategy. Ensure that any code that might throw exceptions is wrapped in a try-catch block where it makes sense, and that resources are handled correctly to avoid leaks (which can be assisted by using smart pointers or RAII containers).
- User
Should I rethrow the exception in this case or with a log is enough? Since it is a reference it has to rethrow right?
- Assistant
Whether to rethrow the exception or just log the error depends on the design and error-handling strategy of your game engine. However, because you're returning a reference, if you fail to load the surface and do not throw an exception, you would have no valid object to return. This could lead to undefined behavior because the caller would receive a reference to an object that doesn’t exist.
The key consideration is what the calling code is expected to do if loading the surface fails. If the surface is critical for the game's operation and there's no sensible way for the game to continue without it, rethrowing the exception would be appropriate so that the calling code has an opportunity to handle the error (e.g., by displaying an error message to the user, trying an alternative resource, or gracefully shutting down the game).
On the other hand, if it would be acceptable for the game to continue without the surface (perhaps using a placeholder texture), you could handle the error without rethrowing. In that case, you might log the error and return a reference to a default surface or a dummy object that represents a "missing texture."
However, based on the way your
Surfaceconstructor is currently written, there’s an expectation that a valid surface will be loaded, or an exception will be thrown if it fails. In yourResourceManager::GetSurfacemethod, you should either:-
Rethrow the exception to allow the caller to handle the situation as they see fit.
catch (const std::runtime_error& e) { SDL_LogError(SDL_LOG_CATEGORY_ERROR, "Failed to load surface: %s\n", e.what()); throw; // Re-propagates the current exception. } -
Return a known good default/dummy
Surfaceobject:catch (const std::runtime_error& e) { SDL_LogError(SDL_LOG_CATEGORY_ERROR, "Failed to load surface: %s, using dummy surface instead.\n", e.what()); return dummySurface; // Make sure you have a fallback dummySurface available. }
Since option 2 involves silently substituting the resource, it's often less preferred because it can make it more difficult to diagnose resource loading issues during development. Developers tend to appreciate knowing when something has gone wrong rather than having the problem masked with silent fallbacks.
In most cases, if a resource cannot be loaded, you should indeed rethrow the exception after logging the error. This way, your ResourceManager does not return a reference to an invalid or non-existent surface, and the calling code has the opportunity to handle the exception at a higher level, where there may be more context available to decide on the appropriate course of action.
Remember that if your game engine or application codebase doesn't use exceptions elsewhere, introducing them in just one place can lead to inconsistency and potentially mishandled errors. Make sure to integrate exception handling thoughtfully and consistently if you choose to use it.
-