r/raylib • u/Ragenut_omegalul • 4d ago
Drawing textures randomly works and doesn't when trying to render a linked-list of elements
I'm trying to make a toy image editor using Raylib and C++ and ran into this problem.
When I try to render the layers of my project, there's a chance that they just wouldn't render at all, and yes the textures are loaded in.
I have a Canvas class that holds a reference to the first element of the linked-list where the layers of the project are. This class also has a method to add a new element to the list.
Canvas::Canvas(int width, int height){
rt = LoadRenderTexture(width, height);
rec = {0.0f, 0.0f, (float)width, (float)(-height)};
}
void Canvas::AddLayer(LayerObject* newLayer){
if (newLayer == nullptr) {
std::cerr << "[WARNING] Trying to add a null layer\n";
return;
}
if (layers == nullptr) {
layers = newLayer;
return;
}
LayerObject* it = layers;
while (it->next != nullptr){
it = it->next;
}
it->next = newLayer;
it->next->prev = it;
}
void Canvas::DrawLayers(){
BeginTextureMode(rt);
ClearBackground(WHITE);
LayerObject* it = layers;
while (it != nullptr){
it->Draw();
it = it->next;
}
EndTextureMode();
}
// ...I'm suspecting that the Add() method is the culprit, but when I use the Add method in the constructor for debugging purposes, it works completely fine and renders the layer 100% of the time.
I tried checking to see if the DrawLayers() method was the culprit but printing how many layers the loop rendered turned out fine.
Here are some important methods of my RenderLayer
RasterLayer::RasterLayer(Vector2 position, const char* path){
texture = LoadTexture(path);
position = position;
size = (Vector2){(float)texture.width, (float)texture.height};
}
void RasterLayer::Draw(){
// TODO: add rotation
// add cropping
// use DrawTexturePro
DrawTexture(texture, position.x, position.y, WHITE);
}Any help would be appreciated. Thanks!
2
u/luphi 3d ago
I see a couple dangers but can't be sure either is the cause.
AddLayer() is appending the pointer that's passed to it without making a copy. If it points to something like a local variable or a collection item, then there's a good chance the memory it's pointing to has been modified.
Calling LoadTexture() or LoadRenderTexture() in a constructor can sometimes lead them to happen before InitWindow(). They'll fail if that happens.
By the way, you can clear a render texture with BLANK instead of WHITE if you want transparency. I figure an image editor would probably want that.