From 38931cf65e95dfb11437e42990b09d4c226bd679 Mon Sep 17 00:00:00 2001 From: jettis Date: Fri, 6 Dec 2024 12:33:58 +0200 Subject: [PATCH] store States to heap so that State memory adresses stay same --- Animal.cpp | 18 +++++++++++++++--- Animal.h | 11 +++++++++-- 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/Animal.cpp b/Animal.cpp index 636bc66..504cd78 100644 --- a/Animal.cpp +++ b/Animal.cpp @@ -22,6 +22,7 @@ Animal::Animal(string skin) { cur = 0; viime_event = 0; state_changed = false; + animation_i = 0; // set rand seed SDL_srand(0); @@ -31,6 +32,11 @@ Animal::Animal(string skin) { } Animal::~Animal() { + for (unsigned i = 0; i < states.size(); i++) { + if (states[i]) { + delete states[i]; + } + } } SDL_Surface *Animal::readImg(string skin, string state_name, int num) { @@ -79,6 +85,12 @@ void Animal::readSkin(string skin) { State feat; char prev_chr; + for (unsigned i = 0; i < states.size(); i++) { + if (states[i]) { + delete states[i]; + } + } + states.clear(); special_states.clear(); random_states.clear(); @@ -150,11 +162,11 @@ void Animal::readSkinStep(string skin, char chr, string &buf, string &key, State prev_chr = chr; } -void Animal::readSkinFill(string skin, State feat) { - states.push_back(feat); +void Animal::readSkinFill(string skin, State &feat) { + cur_state = new State(feat); + states.push_back(cur_state); // Load images to memory - cur_state = &states.back(); for (int x = 0; x < cur_state->count; x++) { cur_state->imgs.push_back(NULL); cur_state->imgs[x] = readImg(skin, cur_state->img_name, x); diff --git a/Animal.h b/Animal.h index 1671759..54fc3e6 100644 --- a/Animal.h +++ b/Animal.h @@ -30,6 +30,13 @@ class State { vector imgs; SoundData sound_data; + ~State() { + for (unsigned i = 0; i < imgs.size(); i++) { + if (imgs[i]) { + SDL_DestroySurface(imgs[i]); + } + } + } }; class Animal { @@ -40,7 +47,7 @@ class Animal { SDL_Surface *readImg(string skin, string state_name, int num); void readSkin(string file); void readSkinStep(string skin, char chr, string &buf, string &key, State &state, char &prev_chr); - void readSkinFill(string skin, State state); + void readSkinFill(string skin, State &state); void createShape(int num, int w, int h); void move(); void animate(bool reset); @@ -57,7 +64,7 @@ class Animal { SDL_Rect disp_pos; // has display width and height and window posiion on it - vector states; + vector states; vector special_states; State *cur_state; vector random_states;