32#include <SDL3_image/SDL_image.h>
34#include <boost/algorithm/string.hpp>
36#if BOOST_VERSION >= 108100
38#include <boost/unordered/unordered_flat_map.hpp>
39template<
typename Key,
typename Value>
40using cache_map = boost::unordered_flat_map<Key, Value>;
44#include <boost/unordered/unordered_map.hpp>
45template<
typename Key,
typename Value>
54#define ERR_IMG LOG_STREAM(err, log_image)
55#define WRN_IMG LOG_STREAM(warn, log_image)
56#define LOG_IMG LOG_STREAM(info, log_image)
57#define DBG_IMG LOG_STREAM(debug, log_image)
60#define ERR_CFG LOG_STREAM(err, log_config)
69 std::size_t hash = std::hash<unsigned>{}(val.
type_);
76 boost::hash_combine(hash, val.
loc_.
x);
77 boost::hash_combine(hash, val.
loc_.
y);
143std::array<surface_cache, NUM_TYPES> surfaces_;
149using texture_cache_map = std::map<image::scale_quality, image::texture_cache>;
151texture_cache_map textures_;
152texture_cache_map textures_hexed_;
153texture_cache_map texture_tod_colored_;
156image::bool_cache in_hex_info_;
159image::bool_cache is_empty_hex_;
162image::lit_surface_cache lit_surfaces_;
163image::lit_texture_cache lit_textures_;
165image::lit_surface_variants surface_lightmaps_;
166image::lit_texture_variants texture_lightmaps_;
169std::array<bool_cache, NUM_TYPES> skipped_cache_;
170int duplicate_loads_ = 0;
175std::map<std::string, bool> image_existence_map;
178std::set<std::string> precached_dirs;
180int red_adjust = 0, green_adjust = 0, blue_adjust = 0;
182const std::string data_uri_prefix =
"data:";
183struct parsed_data_URI{
184 explicit parsed_data_URI(std::string_view data_URI);
191parsed_data_URI::parsed_data_URI(std::string_view data_URI)
193 const std::size_t colon = data_URI.find(
':');
194 const std::string_view after_scheme = data_URI.substr(colon + 1);
196 const std::size_t
comma = after_scheme.find(
',');
197 const std::string_view type_info = after_scheme.substr(0,
comma);
199 const std::size_t
semicolon = type_info.find(
';');
201 scheme = data_URI.substr(0, colon);
213class intermediate_cache
219 entry_map::iterator it =
lookup_.find(key);
224 entry_list::iterator lru_it = it->second;
225 lru_it->second.last_access = std::chrono::steady_clock::now();
227 return lru_it->second.surf;
259 std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now();
260 if(now - last_stale_check_ < prune_interval) {
285 using entry_list = std::list<std::pair<image::locator, entry>>;
289 static constexpr std::size_t
max_size = 200 * 1024 * 1024;
290 static constexpr std::chrono::seconds
ttl{10};
295 const std::pair<image::locator, entry>& lru_item =
lru_list_.back();
296 size_ -= lru_item.second.size_bytes;
301 void prune_oversized(std::size_t space_needed)
303 while(size_ + space_needed > max_size && !
lru_list_.empty()) {
314intermediate_cache intermediate_surfaces_;
320 for(surface_cache&
cache : surfaces_) {
323 lit_surfaces_.flush();
324 lit_textures_.flush();
325 surface_lightmaps_.clear();
326 texture_lightmaps_.clear();
327 in_hex_info_.flush();
328 is_empty_hex_.flush();
330 textures_hexed_.clear();
331 texture_tod_colored_.clear();
332 image_existence_map.clear();
333 precached_dirs.clear();
334 intermediate_surfaces_.clear();
367 if(boost::algorithm::starts_with(
filename_, data_uri_prefix)) {
368 if(parsed_data_URI parsed{
filename_ }; !parsed.good) {
370 std::string_view stripped = view.substr(0, view.find(
","));
371 ERR_IMG <<
"Invalid data URI: " << stripped;
377 if(
const std::size_t markup_field =
filename_.find(
'~'); markup_field != std::string::npos) {
389 , modifications_(modifications)
398 const std::string& modifications)
401 , modifications_(modifications)
403 , center_x_(center_x)
404 , center_y_(center_y)
439 surface ovr_surf = IMG_Load(ovr_file.c_str());
444 rect area {0, 0, ovr_surf->w, ovr_surf->h};
446 sdl_blit(ovr_surf,
nullptr, orig_surf, &area);
452 const std::string& name =
loc.get_filename();
460 if(!location && (boost::algorithm::ends_with(name,
".png") || boost::algorithm::ends_with(name,
".jpg"))) {
461 std::string webp_name = name.substr(0, name.size() - 4) +
".webp";
464 WRN_IMG <<
"Replaced missing '" << name <<
"' with found '"
465 << webp_name <<
"'.";
474 location = loc_location.value();
477 res = IMG_Load(location.value().c_str());
479 ERR_IMG <<
"Failed to load image with reason: " << SDL_GetError();
483 if(res && !loc_location) {
492 if(!res && !name.empty()) {
493 ERR_IMG <<
"could not open image '" << name <<
"' at location '" << location.value_or(
"<location missing>") <<
"'";
512 intermediate_surfaces_.prune_stale();
514 if(!
loc.get_modifications().empty()) {
519 surf = intermediate_surfaces_.find(intermediate_cache_key);
522 if(
surf ==
nullptr) {
524 if(
surf ==
nullptr) {
530 while(!mods.
empty()) {
534 std::ostringstream ss;
538 ss <<
"\t" << mod_name <<
"\n";
541 ERR_CFG <<
"Failed to apply a modification to an image:\n"
542 <<
"Image: " <<
loc.get_filename() <<
"\n"
543 <<
"Modifications: " << ss.str() <<
"\n"
544 <<
"Error: " <<
e.message;
551 intermediate_surfaces_.add(intermediate_cache_key,
surf);
557 if(
surf ==
nullptr) {
564 ((tile_size * 3) / 4) *
loc.get_loc().
x,
565 tile_size *
loc.get_loc().
y + (tile_size / 2) * (
loc.get_loc().
x % 2),
570 if(
loc.get_center_x() >= 0 &&
loc.get_center_y() >= 0) {
571 srcrect.x +=
surf->w / 2 -
loc.get_center_x();
572 srcrect.y +=
surf->h / 2 -
loc.get_center_y();
589 is_empty_hex_.add_to_cache(
loc, is_empty);
599 parsed_data_URI parsed{
loc.get_filename()};
602 std::string_view fn =
loc.get_filename();
603 std::string_view stripped = fn.substr(0, fn.find(
","));
604 ERR_IMG <<
"Invalid data URI: " << stripped;
605 }
else if(parsed.mime.substr(0, 5) !=
"image") {
606 ERR_IMG <<
"Data URI not of image MIME type: " << parsed.mime;
608 const std::vector<uint8_t> image_data =
base64::decode(parsed.data);
610 if(image_data.empty()) {
611 ERR_IMG <<
"Invalid encoding in data URI";
612 }
else if(parsed.mime ==
"image/png") {
613 surf = IMG_LoadTyped_IO(SDL_IOFromConstMem(image_data.data(), image_data.size()),
true,
"PNG");
614 }
else if(parsed.mime ==
"image/jpeg") {
615 surf = IMG_LoadTyped_IO(SDL_IOFromConstMem(image_data.data(), image_data.size()),
true,
"JPG");
616 }
else if(parsed.mime ==
"image/webp") {
617 surf = IMG_LoadTyped_IO(SDL_IOFromConstMem(image_data.data(), image_data.size()),
true,
"WEBP");
619 ERR_IMG <<
"Invalid image MIME type: " << parsed.mime;
627 : l(op), r(),
g(),
b()
629 constexpr int min = std::numeric_limits<int8_t>::min();
630 constexpr int max = std::numeric_limits<int8_t>::max();
633 r = std::clamp(rr / 2, min, max);
634 g = std::clamp(gg / 2, min, max);
635 b = std::clamp(bb / 2, min, max);
638#ifndef __cpp_impl_three_way_comparison
641 return std::tie(
l,
r,
g,
b) == std::tie(o.
l, o.
r, o.
g, o.
b);
650 boost::hash_combine(hash, adj.
l);
651 boost::hash_combine(hash, adj.
r);
652 boost::hash_combine(hash, adj.
g);
653 boost::hash_combine(hash, adj.
b);
664 int m = ls[0].l == -1 ? 2 : 1;
669 const auto get_lightmap = [&ls]
671 const auto iter = surface_lightmaps_.find(ls);
672 if(iter != surface_lightmaps_.end()) {
677 static const std::string
p =
"terrain/light/light";
678 static const std::string lm_img[19] {
680 p +
"-concave-2-tr.png",
p +
"-concave-2-r.png",
p +
"-concave-2-br.png",
681 p +
"-concave-2-bl.png",
p +
"-concave-2-l.png",
p +
"-concave-2-tl.png",
682 p +
"-convex-br-bl.png",
p +
"-convex-bl-l.png",
p +
"-convex-l-tl.png",
683 p +
"-convex-tl-tr.png",
p +
"-convex-tr-r.png",
p +
"-convex-r-br.png",
684 p +
"-convex-l-bl.png",
p +
"-convex-tl-l.png",
p +
"-convex-tr-tl.png",
685 p +
"-convex-r-tr.png",
p +
"-convex-br-r.png",
p +
"-convex-bl-br.png"
697 if(base ==
nullptr) {
701 sdl_blit(lts,
nullptr, base,
nullptr);
706 surface_lightmaps_[ls] = base;
717 switch(
loc.get_type()) {
719 if(
loc.is_data_uri()){
742 if(r != red_adjust ||
g != green_adjust ||
b != blue_adjust) {
747 lit_surfaces_.flush();
748 lit_textures_.flush();
749 texture_tod_colored_.clear();
762 <<
" image to hex mask: " << i_locator;
764 auto fit =
surface(mask->w, mask->h);
767 SDL_FillSurfaceRect(fit,
nullptr, SDL_MapSurfaceRGBA(fit, 0, 0, 0, 0));
773 std::max(0,
surf->w - base->w) / 2,
774 std::max(0,
surf->h - base->h) / 2,
775 std::min(
surf->w, base->w),
776 std::min(
surf->h, base->h),
783 SDL_BlendMode src_blend;
784 SDL_GetSurfaceBlendMode(
image, &src_blend);
785 SDL_SetSurfaceBlendMode(
image, SDL_BLENDMODE_NONE);
792 SDL_SetSurfaceBlendMode(
image, src_blend);
794 image = std::move(fit);
799 is_empty_hex_.add_to_cache(i_locator, is_empty);
814 if(red_adjust == 0 && green_adjust == 0 && blue_adjust == 0) {
844 WRN_IMG <<
"get_surface called with unknown image type";
847 surface_cache& imap = surfaces_[type];
850 if(
const surface* cached_surf = imap.locate_in_cache(i_locator)) {
853 DBG_IMG <<
"surface cache [" << type <<
"] miss: " << i_locator;
869 throw game::error(
"get_surface somehow lost image type?");
872 bool_cache& skip = skipped_cache_[type];
875 if(
const bool* cached_value = skip.locate_in_cache(i_locator)) {
878 DBG_IMG <<
"duplicate load: " << i_locator
879 <<
" [" << type <<
"]"
880 <<
" (" << duplicate_loads_ <<
"/" << total_loads_ <<
" total)";
888 DBG_IMG <<
"surface cache [" << type <<
"] skip: " << i_locator;
889 skip.add_to_cache(i_locator,
true);
891 imap.add_to_cache(i_locator, res);
903 lit_surface_variants& lvar = lit_surfaces_.access_in_cache(i_locator);
906 if(
const auto iter = lvar.find(ls); iter != lvar.end()) {
909 DBG_IMG <<
"lit surface cache miss: " << i_locator;
917 lit_surface_variants& reacquired_lvar = lit_surfaces_.access_in_cache(i_locator);
920 reacquired_lvar[ls] = res;
930 lit_texture_variants& lvar = lit_textures_.access_in_cache(i_locator);
933 if(
const auto iter = lvar.find(ls); iter != lvar.end()) {
936 DBG_IMG <<
"lit texture cache miss: " << i_locator;
964 if(
const bool* cached_value = in_hex_info_.locate_in_cache(i_locator)) {
965 return *cached_value;
968 in_hex_info_.add_to_cache(i_locator, res);
975 if(
const bool* cached_value = is_empty_hex_.locate_in_cache(i_locator)) {
976 return *cached_value;
982 if(
const bool* cached_value = is_empty_hex_.locate_in_cache(i_locator)) {
983 return *cached_value;
989 is_empty_hex_.add_to_cache(i_locator, is_empty);
1003 bool&
cache = iter->second;
1017 const std::string checked_dir = dir +
"/" + subdir;
1018 if(precached_dirs.find(checked_dir) != precached_dirs.end()) {
1022 precached_dirs.insert(checked_dir);
1028 std::vector<std::string> files_found;
1029 std::vector<std::string> dirs_found;
1033 for(
const auto&
f : files_found) {
1034 image_existence_map[subdir +
f] =
true;
1037 for(
const auto&
d : dirs_found) {
1051 const auto b = image_existence_map.find(file);
1052 if(
b != image_existence_map.end()) {
1070 if(boost::algorithm::ends_with(
filename,
".jpeg") || boost::algorithm::ends_with(
filename,
".jpg") || boost::algorithm::ends_with(
filename,
".jpe")) {
1072 const int err = IMG_SaveJPG(
surf,
filename.c_str(), 75);
1076 if(boost::algorithm::ends_with(
filename,
".png")) {
1105 static int prune_counter = 0;
1106 if(++prune_counter >= 20000) {
1108 intermediate_surfaces_.prune_stale();
1121 texture_cache*
cache =
nullptr;
1125 cache = &textures_hexed_[quality];
1128 cache = &texture_tod_colored_[quality];
1131 cache = &textures_[quality];
1137 if(
const texture* cached_texture =
cache->locate_in_cache(i_locator)) {
1138 return *cached_texture;
1140 DBG_IMG <<
"texture cache [" << type <<
"] miss: " << i_locator;
1160 DBG_IMG <<
"texture cache [" << type <<
"] skip: " << i_locator;
1162 cache->add_to_cache(i_locator, res);
bool in_cache(const locator &item) const
T & access_in_cache(const locator &item)
Returns a reference to the cache item associated with the given key.
const T * locate_in_cache(const locator &item) const
Returns a pointer to the cached value, or nullptr if not found.
cache_map< locator, T > content_
void add_to_cache(const locator &item, T data)
Generic locator abstracting the location of an image.
bool is_void() const
Returns true if the locator does not correspond to an actual image.
const std::string & get_filename() const
const map_location & get_loc() const
bool operator<(const locator &a) const
bool operator==(const locator &a) const
locator clone(const std::string &mods) const
Returns a copy of this locator with the given IPF.
std::string modifications_
const std::string & get_modifications() const
A modified priority queue used to order image modifications.
const modification & top() const
Returns a const reference to the top element in the queue.
void pop()
Removes the top element from the queue.
static modification_queue decode(const std::string &)
Decodes modifications from a modification string.
surface clone() const
Creates a new, duplicate surface in memory using the 'neutral' pixel format.
Wrapper class to encapsulate creation and management of an SDL_Texture.
Declarations for File-IO.
Standard logging facilities (interface).
std::vector< uint8_t > decode(std::string_view in)
void clear()
Clear the current render target.
void get_files_in_dir(const std::string &dir, std::vector< std::string > *files, std::vector< std::string > *dirs=nullptr, name_mode mode=name_mode::FILE_NAME_ONLY, filter_mode filter=filter_mode::NO_FILTER, reorder_mode reorder=reorder_mode::DONT_REORDER, file_tree_checksum *checksum=nullptr)
Get a list of all files and/or directories in a given directory.
bool is_directory(const std::string &fname)
Returns true if the given file is a directory.
utils::optional< std::string > get_binary_file_location(const std::string &type, const std::string &filename)
Returns a complete path to the actual file of a given type, if it exists.
utils::optional< std::string > get_localized_path(const std::string &file, const std::string &suff="")
Returns the localized version of the given filename, if it exists.
NOT_DANGLING const std::vector< std::string > & get_binary_paths(const std::string &type)
Returns a vector with all possible paths to a given type of binary, e.g.
Functions to load and save images from/to disk.
static surface load_image_sub_file(const image::locator &loc)
Loads and modifies an image, cutting out a single hex tile from it if the locator specifies a map loc...
bool is_empty_hex(const locator &i_locator)
Checks if an image is empty after hex masking.
static void add_localized_overlay(const std::string &ovr_file, surface &orig_surf)
bool precached_file_exists(const std::string &file)
static TYPE simplify_type(const image::locator &i_locator, TYPE type)
translate type to a simpler one when possible
static surface load_image_data_uri(const image::locator &loc)
static surface get_tod_colored(const locator &i_locator, bool skip_cache=false)
bool exists(const image::locator &i_locator)
Returns true if the given image actually exists, without loading it.
void flush_cache()
Purges all image caches.
static void precache_file_existence_internal(const std::string &dir, const std::string &subdir)
static surface load_from_disk(const locator &loc)
surface get_surface(const image::locator &i_locator, TYPE type, bool skip_cache)
Returns an image surface suitable for software manipulation.
static surface apply_light(surface surf, const std::vector< light_adjust > &ls)
surface get_hexmask()
Retrieves the standard hexagonal tile mask.
std::ostream & operator<<(std::ostream &s, const locator &l)
save_result save_image(const locator &i_locator, const std::string &filename)
void precache_file_existence(const std::string &subdir)
Precache the existence of files in a binary path subdirectory (e.g.
TYPE
Used to specify the rendering format of images.
@ HEXED
Standard hexagonal tile mask applied, removing portions that don't fit.
@ TOD_COLORED
Same as HEXED, but with Time of Day color tint applied.
@ UNSCALED
Unmodified original-size image.
texture get_texture(const image::locator &i_locator, TYPE type, bool skip_cache)
Returns an image texture suitable for hardware-accelerated rendering.
point get_size(const locator &i_locator, bool skip_cache)
Returns the width and height of an image.
static surface get_hexed(const locator &i_locator, bool skip_cache=false)
texture get_lighted_texture(const image::locator &i_locator, const std::vector< light_adjust > &ls)
std::size_t hash_value(const image::locator &val)
Hash function overload for boost::hash.
void set_color_adjustment(int r, int g, int b)
Changes Time of Day color tint for all applicable image types.
surface get_lighted_image(const image::locator &i_locator, const std::vector< light_adjust > &ls)
Caches and returns an image with a lightmap applied to it.
bool is_in_hex(const locator &i_locator)
Checks if an image fits into a single hex.
static surface load_image_file(const image::locator &loc)
std::vector< std::string > parenthetical_split(std::string_view val, const char separator, std::string_view left, std::string_view right, const int flags)
Splits a string based either on a separator, except then the text appears within specified parenthesi...
auto * find(Container &container, const Value &value)
Convenience wrapper for using find on a container without needing to comare to end()
static constexpr std::chrono::seconds prune_interval
static lg::log_domain log_image("image")
boost::unordered_map< Key, Value > cache_map
static constexpr std::size_t max_size
std::chrono::steady_clock::time_point last_stale_check_
std::chrono::steady_clock::time_point last_access
static lg::log_domain log_config("config")
static constexpr std::chrono::seconds ttl
Contains the SDL_Rect helper code.
std::unordered_map< std::string, cache_item > cache
rect dst
Location on the final composed sheet.
rect src
Non-transparent portion of the surface to compose.
std::string filename
Filename.
Base class for all the errors encountered by the engine.
Type used to store color information of central and adjacent hexes.
bool operator==(const light_adjust &o) const
light_adjust(int op, int r, int g, int b)
Exception thrown by the operator() when an error occurs.
Encapsulates the map of the game.
An abstract description of a rectangle with integer coordinates.
static map_location::direction s
surface cut_surface(const surface &surf, const rect &r)
Cuts a rectangle from a surface.
void adjust_surface_color(surface &nsurf, int red, int green, int blue)
void light_surface(surface &nsurf, const surface &lightmap)
Light surf using lightmap.
bool in_mask_surface(const surface &nsurf, const surface &nmask)
Checks if the source surface is entirely covered by the visible area of the mask.
bool mask_surface(surface &nsurf, const surface &nmask, const std::string &filename)
Applies a mask to the source surface by calculating the minimum alpha channel value for every corresp...
void sdl_blit(const surface &src, const SDL_Rect *src_rect, surface &dst, SDL_Rect *dst_rect)