#include "sdl_helpers.h" #include #include #include #include #include using namespace std; using nlohmann::json; map, TTF_Font*> font_map; bool init_sdl() { if (SDL_Init(SDL_INIT_VIDEO) < 0) { cout << "SDL could not initialize! SDL - " << SDL_GetError() << endl; return false; } if (0 != TTF_Init()) { cout << "Could not init TTF! SDL - " << SDL_GetError() << endl; SDL_Quit(); return false; } int img_flags = IMG_Init(IMG_INIT_JPG | IMG_INIT_PNG | IMG_INIT_TIF); if (img_flags != (IMG_INIT_JPG | IMG_INIT_PNG | IMG_INIT_TIF)) { cout << "Could not init IMG! SDL - " << SDL_GetError() << endl; TTF_Quit(); SDL_Quit(); return false; } return true; } void clean_sdl() { // Clean up all fonts for (auto it = font_map.begin(); it != font_map.end(); ++it) { TTF_CloseFont(it->second); } font_map.clear(); IMG_Quit(); TTF_Quit(); SDL_Quit(); } TTF_Font* get_font(const string& filename, int size) { pair key(filename, size); if (0 != font_map.count(key)) { return font_map[key]; } else { TTF_Font* font = TTF_OpenFont(filename.c_str(), size); if (nullptr != font) { font_map[key] = font; } else { cout << "Could not open font '"<< filename << "' with size " << size << endl; } return font; } } bool read_config_json(json& cfg, const string& filename, ostream* log) { ifstream cfg_file(filename); if (!cfg_file.is_open()) { if (nullptr != log) { *log << "Could not open config.json" << endl; } return false; } // Parse with comments try { cfg = json::parse(cfg_file, nullptr, true, true); } catch (const std::exception &e) { if (nullptr != log) { *log << e.what() << endl; } return false; } return true; } void json_extract(const json& j, const string& key, string& out) { if (j.contains(key) && j[key].is_string()) { out = j[key]; } } void json_extract(const nlohmann::json& j, const string& key, int& out) { if (j.contains(key) && j[key].is_number_integer()) { out = j[key]; } }