/****** spritesheets Contained are all functions related to creating, loading, and freeing Spritesheet structs. ******/ #include "interface.h" #include "spritesheets.h" /**** malloc()s a new Spritesheet, sets default options, then returns the pointer to the new Spritesheet. ****/ struct Spritesheet *newSpritesheet() { struct Spritesheet *sheet = malloc(sizeof(struct Spritesheet)); sheet->width = 0; sheet->height = 0; sheet->s_width = 0; sheet->s_height = 0; sheet->columns = 0; sheet->scale_x = 1.0f; sheet->scale_y = 1.0f; sheet->surface = NULL; sheet->s_surface = NULL; sheet->texture = 0; return sheet; } /**** Takes a Spritesheet struct and attempts to load the given file_name. Sets spritesheet's width, height, and columns properties to the passed values. Also sets up scale to the default of 1.0f and copies spritesheet->surface to spritesheet->s_surface, populating s_width and s_height. ****/ int loadSpritesheetFromFile(struct Spritesheet *spritesheet, char *file_name, int width, int height, int columns) { spritesheet->width = width; spritesheet->height = height; spritesheet->columns = columns; // huehue char temp[strlen(file_name)+5]; sprintf(temp, "%s.png", file_name); spritesheet->surface = IMG_Load(temp); if (spritesheet->surface == NULL) { printf("couldn't load\n"); // TODO: Add error output return -1; } setSpritesheetScale(spritesheet, 1.0f, 1.0f); return 0; } int loadSpritesheetFromMemory(struct Spritesheet *spritesheet, unsigned char *memory, unsigned int length, int width, int height, int columns) { if (length <= 0) return -1; spritesheet->width = width; spritesheet->height = height; spritesheet->columns = columns; spritesheet->surface = IMG_Load_RW(SDL_RWFromMem(memory, length), 1); if (spritesheet->surface == NULL) { // TODO: Add error output return -2; } setSpritesheetScale(spritesheet, 1.0f, 1.0f); return 0; } void setSpritesheetScale(struct Spritesheet *spritesheet, float scale_x, float scale_y) { spritesheet->scale_x = scale_x; spritesheet->scale_y = scale_y; spritesheet->s_width = spritesheet->width * scale_x; spritesheet->s_height = spritesheet->height * scale_y; if (spritesheet->s_surface != NULL) SDL_FreeSurface(spritesheet->s_surface); spritesheet->s_surface = SDL_ScaleSurface(spritesheet->surface, scale_x, scale_y); } /**** Frees the spritesheet and its surfaces if they are not NULL. ****/ void freeSpritesheet(struct Spritesheet *sheet) { if (sheet->surface != NULL) SDL_FreeSurface(sheet->surface); if (sheet->s_surface != NULL) SDL_FreeSurface(sheet->s_surface); free(sheet); }