The Battle for Wesnoth 1.21.0-dev
 
Loading...
Searching...
No Matches
picture.cpp
Go to the documentation of this file.
1/*
2 Copyright (C) 2003 - 2025
3 by David White <dave@whitevine.net>
4 Part of the Battle for Wesnoth Project https://www.wesnoth.org/
5
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY.
12
13 See the COPYING file for more details.
14*/
15
16/**
17 * @file
18 * Routines for images: load, scale, re-color, etc.
19 */
20
21#include "picture.hpp"
22
23#include "filesystem.hpp"
24#include "game_config.hpp"
26#include "log.hpp"
29#include "sdl/rect.hpp"
30#include "sdl/texture.hpp"
31
32#include <SDL3_image/SDL_image.h>
33
34#include <boost/algorithm/string.hpp>
35
36#if BOOST_VERSION >= 108100
37
38#include <boost/unordered/unordered_flat_map.hpp>
39template<typename Key, typename Value>
40using cache_map = boost::unordered_flat_map<Key, Value>;
41
42#else
43
44#include <boost/unordered/unordered_map.hpp>
45template<typename Key, typename Value>
46using cache_map = boost::unordered_map<Key, Value>;
47
48#endif
49
50#include <array>
51#include <set>
52
53static lg::log_domain log_image("image");
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)
58
59static lg::log_domain log_config("config");
60#define ERR_CFG LOG_STREAM(err, log_config)
61
63
64namespace image
65{
66/** Hash function overload for boost::hash. Must be in the image namespace to satisfy ADL. */
67std::size_t hash_value(const image::locator& val)
68{
69 std::size_t hash = std::hash<unsigned>{}(val.type_);
70
72 boost::hash_combine(hash, val.filename_);
73 }
74
76 boost::hash_combine(hash, val.loc_.x);
77 boost::hash_combine(hash, val.loc_.y);
78 boost::hash_combine(hash, val.center_x_);
79 boost::hash_combine(hash, val.center_y_);
80 boost::hash_combine(hash, val.modifications_);
81 }
82
83 return hash;
84}
85
86template<typename T>
88{
89public:
90 bool in_cache(const locator& item) const
91 {
92 return content_.find(item) != content_.end(); // TODO C++20: use content_.contains()
93 }
94
95 /** Returns a pointer to the cached value, or nullptr if not found. */
96 const T* locate_in_cache(const locator& item) const
97 {
98 if(auto iter = content_.find(item); iter != content_.end()) {
99 return &iter->second;
100 } else {
101 return nullptr;
102 }
103 }
104
105 /**
106 * Returns a reference to the cache item associated with the given key.
107 * If no corresponding value is found, a default instance will be created.
108 */
109 T& access_in_cache(const locator& item)
110 {
111 return content_[item];
112 }
113
114 void add_to_cache(const locator& item, T data)
115 {
116 content_.insert_or_assign(item, std::move(data));
117 }
118
119 void flush()
120 {
121 content_.clear();
122 }
123
124private:
126};
127
128namespace
129{
130using surface_cache = cache_type<surface>;
131using texture_cache = cache_type<texture>;
132using bool_cache = cache_type<bool>;
133
134/** Type used to pair light possibilities with the corresponding lit surface. */
135using lit_surface_variants = cache_map<std::vector<light_adjust>, surface>;
136using lit_texture_variants = cache_map<std::vector<light_adjust>, texture>;
137
138/** Lit variants for each locator. */
139using lit_surface_cache = cache_type<lit_surface_variants>;
140using lit_texture_cache = cache_type<lit_texture_variants>;
141
142/** Definition of all image maps */
143std::array<surface_cache, NUM_TYPES> surfaces_;
144
145/**
146 * Texture caches.
147 * Note that the latter two are temporary and should be removed once we have OGL and shader support.
148 */
149using texture_cache_map = std::map<image::scale_quality, image::texture_cache>;
150
151texture_cache_map textures_;
152texture_cache_map textures_hexed_;
153texture_cache_map texture_tod_colored_;
154
155// cache storing if each image fit in a hex
156image::bool_cache in_hex_info_;
157
158// cache storing if this is an empty hex
159image::bool_cache is_empty_hex_;
160
161// caches storing the different lighted cases for each image
162image::lit_surface_cache lit_surfaces_;
163image::lit_texture_cache lit_textures_;
164// caches storing each lightmap generated
165image::lit_surface_variants surface_lightmaps_;
166image::lit_texture_variants texture_lightmaps_;
167
168// diagnostics for tracking skipped cache impact
169std::array<bool_cache, NUM_TYPES> skipped_cache_;
170int duplicate_loads_ = 0;
171int total_loads_ = 0;
172
173// const int cache_version_ = 0;
174
175std::map<std::string, bool> image_existence_map;
176
177// directories where we already cached file existence
178std::set<std::string> precached_dirs;
179
180int red_adjust = 0, green_adjust = 0, blue_adjust = 0;
181
182const std::string data_uri_prefix = "data:";
183struct parsed_data_URI{
184 explicit parsed_data_URI(std::string_view data_URI);
185 std::string_view scheme;
186 std::string_view mime;
187 std::string_view base64;
188 std::string_view data;
189 bool good;
190};
191parsed_data_URI::parsed_data_URI(std::string_view data_URI)
192{
193 const std::size_t colon = data_URI.find(':');
194 const std::string_view after_scheme = data_URI.substr(colon + 1);
195
196 const std::size_t comma = after_scheme.find(',');
197 const std::string_view type_info = after_scheme.substr(0, comma);
198
199 const std::size_t semicolon = type_info.find(';');
200
201 scheme = data_URI.substr(0, colon);
202 base64 = type_info.substr(semicolon + 1);
203 mime = type_info.substr(0, semicolon);
204 data = after_scheme.substr(comma + 1);
205 good = (scheme == "data" && base64 == "base64" && mime.length() > 0 && data.length() > 0);
206}
207
208/**
209 * Cache for intermediate images that are not the final result but get reused a lot,
210 * mostly modified images that are later cut into several tiles, such as water tiles.
211 * Entries are purged based on time since last access and remaining space (TTL + LRU).
212 */
213class intermediate_cache
214{
215public:
216 /** Finds a surface, refreshing the entry's TTL and LRU position on a hit. Returns null on a miss. */
217 surface find(const image::locator& key)
218 {
219 entry_map::iterator it = lookup_.find(key);
220 if(it == lookup_.end()) {
221 return nullptr;
222 }
223
224 entry_list::iterator lru_it = it->second;
225 lru_it->second.last_access = std::chrono::steady_clock::now();
226 lru_list_.splice(lru_list_.begin(), lru_list_, lru_it);
227 return lru_it->second.surf;
228 }
229
230 /** Adds a surface, evicting least recently used entries to stay within the size limit. */
231 void add(const image::locator& key, const surface& surf)
232 {
233 if(!surf) {
234 return;
235 }
236
237 std::size_t size_bytes = static_cast<std::size_t>(surf->h) * surf->pitch;
238 if(size_bytes > max_size) {
239 return;
240 }
241
242 if(lookup_.find(key) != lookup_.end()) {
243 return;
244 }
245
246 prune_oversized(size_bytes);
247 lru_list_.emplace_front(key, entry{surf, size_bytes, std::chrono::steady_clock::now()});
248 lookup_[key] = lru_list_.begin();
249 size_ += size_bytes;
250 }
251
252 /**
253 * Evicts entries not accessed within the TTL.
254 * Intermediate images tend to be reused in bursts and then never again, since
255 * the final images are cached elsewhere, so they don't need to stay around long.
256 */
257 void prune_stale()
258 {
259 std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now();
260 if(now - last_stale_check_ < prune_interval) {
261 return;
262 }
263 last_stale_check_ = now;
264
265 while(!lru_list_.empty() && now - lru_list_.back().second.last_access > ttl) {
266 evict_oldest();
267 }
268 }
269
270 void clear()
271 {
272 lookup_.clear();
273 lru_list_.clear();
274 size_ = 0;
275 }
276
277private:
278 struct entry
279 {
281 std::size_t size_bytes;
282 std::chrono::steady_clock::time_point last_access;
283 };
284
285 using entry_list = std::list<std::pair<image::locator, entry>>;
287
288 // Arbitrary limit; from testing, a 2.5 MB png file took up 14 MB in cache.
289 static constexpr std::size_t max_size = 200 * 1024 * 1024;
290 static constexpr std::chrono::seconds ttl{10};
291 static constexpr std::chrono::seconds prune_interval = ttl + std::chrono::seconds(1);
292
293 void evict_oldest()
294 {
295 const std::pair<image::locator, entry>& lru_item = lru_list_.back();
296 size_ -= lru_item.second.size_bytes;
297 lookup_.erase(lru_item.first);
298 lru_list_.pop_back();
299 }
300
301 void prune_oversized(std::size_t space_needed)
302 {
303 while(size_ + space_needed > max_size && !lru_list_.empty()) {
304 evict_oldest();
305 }
306 }
307
308 entry_list lru_list_;
309 entry_map lookup_;
310 std::size_t size_ = 0;
311 std::chrono::steady_clock::time_point last_stale_check_ = std::chrono::steady_clock::now();
312};
313
314intermediate_cache intermediate_surfaces_;
315
316} // end anon namespace
317
319{
320 for(surface_cache& cache : surfaces_) {
321 cache.flush();
322 }
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();
329 textures_.clear();
330 textures_hexed_.clear();
331 texture_tod_colored_.clear();
332 image_existence_map.clear();
333 precached_dirs.clear();
334 intermediate_surfaces_.clear();
335}
336
337locator locator::clone(const std::string& mods) const
338{
339 locator res = *this;
340 if(!mods.empty()) {
341 res.modifications_ += mods;
342 res.type_ = SUB_FILE;
343 }
344
345 return res;
346}
347
348std::ostream& operator<<(std::ostream& s, const locator& l)
349{
350 s << l.get_filename();
351 if(!l.get_modifications().empty()) {
352 if(l.get_modifications()[0] != '~') {
353 s << '~';
354 }
355 s << l.get_modifications();
356 }
357 return s;
358}
359
360locator::locator(const std::string& fn)
361 : filename_(fn)
362{
363 if(filename_.empty()) {
364 return;
365 }
366
367 if(boost::algorithm::starts_with(filename_, data_uri_prefix)) {
368 if(parsed_data_URI parsed{ filename_ }; !parsed.good) {
369 std::string_view view{ filename_ };
370 std::string_view stripped = view.substr(0, view.find(","));
371 ERR_IMG << "Invalid data URI: " << stripped;
372 }
373
374 is_data_uri_ = true;
375 }
376
377 if(const std::size_t markup_field = filename_.find('~'); markup_field != std::string::npos) {
378 type_ = SUB_FILE;
379 modifications_ = filename_.substr(markup_field, filename_.size() - markup_field);
380 filename_ = filename_.substr(0, markup_field);
381 } else {
382 type_ = FILE;
383 }
384}
385
386locator::locator(const std::string& filename, const std::string& modifications)
387 : type_(SUB_FILE)
389 , modifications_(modifications)
390{
391}
392
394 const std::string& filename,
395 const map_location& loc,
396 int center_x,
397 int center_y,
398 const std::string& modifications)
399 : type_(SUB_FILE)
401 , modifications_(modifications)
402 , loc_(loc)
403 , center_x_(center_x)
404 , center_y_(center_y)
405{
406}
407
408bool locator::operator==(const locator& a) const
409{
410 if(a.type_ != type_) {
411 return false;
412 } else if(type_ == FILE) {
413 return filename_ == a.filename_;
414 } else if(type_ == SUB_FILE) {
415 return std::tie(filename_, loc_, modifications_, center_x_, center_y_) ==
416 std::tie(a.filename_, a.loc_, a.modifications_, a.center_x_, a.center_y_);
417 }
418
419 return false;
420}
421
422bool locator::operator<(const locator& a) const
423{
424 if(type_ != a.type_) {
425 return type_ < a.type_;
426 } else if(type_ == FILE) {
427 return filename_ < a.filename_;
428 } else if(type_ == SUB_FILE) {
429 return std::tie(filename_, loc_, modifications_, center_x_, center_y_) <
430 std::tie(a.filename_, a.loc_, a.modifications_, a.center_x_, a.center_y_);
431 }
432
433 return false;
434}
435
436// Load overlay image and compose it with the original surface.
437static void add_localized_overlay(const std::string& ovr_file, surface& orig_surf)
438{
439 surface ovr_surf = IMG_Load(ovr_file.c_str());
440 if(!ovr_surf) {
441 return;
442 }
443
444 rect area {0, 0, ovr_surf->w, ovr_surf->h};
445
446 sdl_blit(ovr_surf, nullptr, orig_surf, &area);
447}
448
450{
451 surface res;
452 const std::string& name = loc.get_filename();
453
454 auto location = filesystem::get_binary_file_location("images", name);
455
456 // Many images have been converted from PNG to WEBP format,
457 // but the old filename may still be saved in savegame files etc.
458 // If the file does not exist in ".png" format, also try ".webp".
459 // Similarly for ".jpg", which conveniently has the same number of letters as ".png".
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";
462 location = filesystem::get_binary_file_location("images", webp_name);
463 if(location) {
464 WRN_IMG << "Replaced missing '" << name << "' with found '"
465 << webp_name << "'.";
466 }
467 }
468
469 {
470 if(location) {
471 // Check if there is a localized image.
472 const auto loc_location = filesystem::get_localized_path(location.value());
473 if(loc_location) {
474 location = loc_location.value();
475 }
476
477 res = IMG_Load(location.value().c_str());
478 if(!res) {
479 ERR_IMG << "Failed to load image with reason: " << SDL_GetError();
480 }
481
482 // If there was no standalone localized image, check if there is an overlay.
483 if(res && !loc_location) {
484 const auto ovr_location = filesystem::get_localized_path(location.value(), "--overlay");
485 if(ovr_location) {
486 add_localized_overlay(ovr_location.value(), res);
487 }
488 }
489 }
490 }
491
492 if(!res && !name.empty()) {
493 ERR_IMG << "could not open image '" << name << "' at location '" << location.value_or("<location missing>") << "'";
498 }
499
500 return res;
501}
502
503/**
504 * Loads and modifies an image, cutting out a single hex tile from it if the
505 * locator specifies a map location. Modified images that are cut into multiple
506 * tiles stay briefly in the intermediate cache, so the modifications only run
507 * once per source image rather than once per tile.
508 */
510{
511 surface surf = nullptr;
512 intermediate_surfaces_.prune_stale();
513
514 if(!loc.get_modifications().empty()) {
515 // For a cutout of a larger image, the uncut modified image may already be cached.
516 image::locator intermediate_cache_key;
517 if(loc.get_loc().valid()) {
518 intermediate_cache_key = image::locator(loc.get_filename(), loc.get_modifications());
519 surf = intermediate_surfaces_.find(intermediate_cache_key);
520 }
521
522 if(surf == nullptr) {
523 surf = get_surface(loc.get_filename(), UNSCALED).clone();
524 if(surf == nullptr) {
525 return nullptr;
526 }
527
528 modification_queue mods = modification::decode(loc.get_modifications());
529
530 while(!mods.empty()) {
531 try {
532 std::invoke(mods.top(), surf);
533 } catch(const image::modification::imod_exception& e) {
534 std::ostringstream ss;
535 ss << "\n";
536
537 for(const std::string& mod_name : utils::parenthetical_split(loc.get_modifications(), '~')) {
538 ss << "\t" << mod_name << "\n";
539 }
540
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;
545 }
546
547 mods.pop();
548 }
549
550 if(loc.get_loc().valid()) {
551 intermediate_surfaces_.add(intermediate_cache_key, surf);
552 }
553 }
554 } else {
555 // No modifications, so the cached base surface can be used directly.
556 surf = get_surface(loc.get_filename(), UNSCALED);
557 if(surf == nullptr) {
558 return nullptr;
559 }
560 }
561
562 if(loc.get_loc().valid()) {
563 rect srcrect(
564 ((tile_size * 3) / 4) * loc.get_loc().x,
565 tile_size * loc.get_loc().y + (tile_size / 2) * (loc.get_loc().x % 2),
566 tile_size,
567 tile_size
568 );
569
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();
573 }
574
575 // cut and hex mask, but also check and cache if empty result
576 surface cut = cut_surface(surf, srcrect);
577 bool is_empty = mask_surface(cut, get_hexmask());
578
579 // discard empty images to free memory
580 if(is_empty) {
581 // Safe because those images are only used by terrain rendering
582 // and it filters them out.
583 // A safer and more general way would be to keep only one copy of it
584 surf = nullptr;
585 } else {
586 surf = cut;
587 }
588
589 is_empty_hex_.add_to_cache(loc, is_empty);
590 }
591
592 return surf;
593}
594
596{
598
599 parsed_data_URI parsed{loc.get_filename()};
600
601 if(!parsed.good) {
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;
607 } else {
608 const std::vector<uint8_t> image_data = base64::decode(parsed.data);
609
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");
618 } else {
619 ERR_IMG << "Invalid image MIME type: " << parsed.mime;
620 }
621 }
622
623 return surf;
624}
625
626light_adjust::light_adjust(int op, int rr, int gg, int bb)
627 : l(op), r(), g(), b()
628{
629 constexpr int min = std::numeric_limits<int8_t>::min();
630 constexpr int max = std::numeric_limits<int8_t>::max();
631
632 // Clamp in a wider type (int) to avoid truncating the input value prematurely
633 r = std::clamp(rr / 2, min, max);
634 g = std::clamp(gg / 2, min, max);
635 b = std::clamp(bb / 2, min, max);
636}
637
638#ifndef __cpp_impl_three_way_comparison
640{
641 return std::tie(l, r, g, b) == std::tie(o.l, o.r, o.g, o.b);
642}
643#endif
644
645/** Hash function overload for boost::hash. Must be in the image namespace to satisfy ADL. */
646static std::size_t hash_value(const light_adjust& adj)
647{
648 std::size_t hash{0};
649
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);
654
655 return hash;
656}
657
658static surface apply_light(surface surf, const std::vector<light_adjust>& ls)
659{
660 // atomic lightmap operation are handled directly (important to end recursion)
661 if(ls.size() == 1) {
662 // if no lightmap (first char = -1) then we need the initial value
663 //(before the halving done for lightmap)
664 int m = ls[0].l == -1 ? 2 : 1;
665 adjust_surface_color(surf, ls[0].r * m, ls[0].g * m, ls[0].b * m);
666 return surf;
667 }
668
669 const auto get_lightmap = [&ls]
670 {
671 const auto iter = surface_lightmaps_.find(ls);
672 if(iter != surface_lightmaps_.end()) {
673 return iter->second;
674 }
675
676 // build all the paths for lightmap sources
677 static const std::string p = "terrain/light/light";
678 static const std::string lm_img[19] {
679 p + ".png",
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"
686 };
687
688 // first image will be the base onto which we blit the others
689 surface base;
690
691 for(const light_adjust& adj : ls) {
692 // get the corresponding image and apply the lightmap operation to it
693 // This allows to also cache lightmap parts.
694 // note that we avoid infinite recursion by using only atomic operation
695 surface lts = image::get_lighted_image(lm_img[adj.l], std::vector{adj});
696
697 if(base == nullptr) {
698 // copy the cached image to avoid modifying the cache
699 base = lts.clone();
700 } else {
701 sdl_blit(lts, nullptr, base, nullptr);
702 }
703 }
704
705 // cache the result
706 surface_lightmaps_[ls] = base;
707 return base;
708 };
709
710 // apply the final lightmap
711 light_surface(surf, get_lightmap());
712 return surf;
713}
714
716{
717 switch(loc.get_type()) {
718 case locator::FILE:
719 if(loc.is_data_uri()){
720 return load_image_data_uri(loc);
721 } else {
722 return load_image_file(loc);
723 }
725 return load_image_sub_file(loc);
726 default:
727 return surface(nullptr);
728 }
729}
730
734
739
740void set_color_adjustment(int r, int g, int b)
741{
742 if(r != red_adjust || g != green_adjust || b != blue_adjust) {
743 red_adjust = r;
744 green_adjust = g;
745 blue_adjust = b;
746 surfaces_[TOD_COLORED].flush();
747 lit_surfaces_.flush();
748 lit_textures_.flush();
749 texture_tod_colored_.clear();
750 }
751}
752
753static surface get_hexed(const locator& i_locator, bool skip_cache = false)
754{
755 surface image = get_surface(i_locator, UNSCALED, skip_cache).clone();
756 surface mask = get_hexmask();
757
758 // Ensure the image is the correct size by cropping and/or centering.
759 // TODO: this should probably be a function of sdl/utils
760 if(image && (image->w != mask->w || image->h != mask->h)) {
761 DBG_IMG << "adjusting [" << image->w << ',' << image->h << ']'
762 << " image to hex mask: " << i_locator;
763
764 auto fit = surface(mask->w, mask->h);
765
766 // Fill the crop surface with transparency
767 SDL_FillSurfaceRect(fit, nullptr, SDL_MapSurfaceRGBA(fit, 0, 0, 0, 0));
768
769 // Returns an area rectangle clamped at the max size of the base surface.
770 // If surf is smaller than base, the result is centered relative to base.
771 const auto centered_intersection = [](const surface& surf, const surface& base) -> rect {
772 return {
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),
777 };
778 };
779
780 rect src = centered_intersection(image, mask);
781 rect dst = centered_intersection(mask, image);
782
783 SDL_BlendMode src_blend;
784 SDL_GetSurfaceBlendMode(image, &src_blend);
785 SDL_SetSurfaceBlendMode(image, SDL_BLENDMODE_NONE);
786 // Take the center area of the source image, up to the size of the hex mask,
787 // and copy it, likewise centered, to the temporary surface. If the image is
788 // larger than the hex mask, its center portion will be retained. If instead
789 // it's *smaller* than the hex mask, it will be copied wholesale to the temp
790 // surface and render centered in any hex to which it is drawn.
791 sdl_blit(image, &src, fit, &dst);
792 SDL_SetSurfaceBlendMode(image, src_blend);
793
794 image = std::move(fit);
795 }
796
797 // hex cut tiles, also check and cache if empty result
798 bool is_empty = mask_surface(image, mask, i_locator.get_filename());
799 is_empty_hex_.add_to_cache(i_locator, is_empty);
800 return image;
801}
802
803static surface get_tod_colored(const locator& i_locator, bool skip_cache = false)
804{
805 surface img = get_surface(i_locator, HEXED, skip_cache).clone();
806 adjust_surface_color(img, red_adjust, green_adjust, blue_adjust);
807 return img;
808}
809
810/** translate type to a simpler one when possible */
811static TYPE simplify_type(const image::locator& i_locator, TYPE type)
812{
813 if(type == TOD_COLORED) {
814 if(red_adjust == 0 && green_adjust == 0 && blue_adjust == 0) {
815 type = HEXED;
816 }
817 }
818
819 if(type == HEXED) {
820 // check if the image is already hex-cut by the location system
821 if(i_locator.get_loc().valid()) {
822 type = UNSCALED;
823 }
824 }
825
826 return type;
827}
828
830 const image::locator& i_locator,
831 TYPE type,
832 bool skip_cache)
833{
834 surface res;
835
836 if(i_locator.is_void()) {
837 return res;
838 }
839
840 type = simplify_type(i_locator, type);
841
842 // select associated cache
843 if(type >= NUM_TYPES) {
844 WRN_IMG << "get_surface called with unknown image type";
845 return res;
846 }
847 surface_cache& imap = surfaces_[type];
848
849 // return the image if already cached
850 if(const surface* cached_surf = imap.locate_in_cache(i_locator)) {
851 return *cached_surf;
852 } else {
853 DBG_IMG << "surface cache [" << type << "] miss: " << i_locator;
854 }
855
856 // not cached, generate it
857 switch(type) {
858 case UNSCALED:
859 // If type is unscaled, directly load the image from the disk.
860 res = load_from_disk(i_locator);
861 break;
862 case TOD_COLORED:
863 res = get_tod_colored(i_locator, skip_cache);
864 break;
865 case HEXED:
866 res = get_hexed(i_locator, skip_cache);
867 break;
868 default:
869 throw game::error("get_surface somehow lost image type?");
870 }
871
872 bool_cache& skip = skipped_cache_[type];
873
874 // In cache...
875 if(const bool* cached_value = skip.locate_in_cache(i_locator)) {
876 // ... and cached as true
877 if(*cached_value) {
878 DBG_IMG << "duplicate load: " << i_locator
879 << " [" << type << "]"
880 << " (" << duplicate_loads_ << "/" << total_loads_ << " total)";
881 ++duplicate_loads_;
882 }
883 }
884
885 ++total_loads_;
886
887 if(skip_cache) {
888 DBG_IMG << "surface cache [" << type << "] skip: " << i_locator;
889 skip.add_to_cache(i_locator, true);
890 } else {
891 imap.add_to_cache(i_locator, res);
892 }
893
894 return res;
895}
896
897surface get_lighted_image(const image::locator& i_locator, const std::vector<light_adjust>& ls)
898{
899 if(i_locator.is_void()) {
900 return {};
901 }
902
903 lit_surface_variants& lvar = lit_surfaces_.access_in_cache(i_locator);
904
905 // Check the matching list_string variants for this locator
906 if(const auto iter = lvar.find(ls); iter != lvar.end()) {
907 return iter->second;
908 } else {
909 DBG_IMG << "lit surface cache miss: " << i_locator;
910 }
911
912 // not cached yet, generate it
913 surface res = apply_light(get_surface(i_locator, HEXED).clone(), ls);
914
915 // lvar may no longer be valid as apply_light can reenter this function
916 // and mutate lit_surfaces_; get a new reference before updating
917 lit_surface_variants& reacquired_lvar = lit_surfaces_.access_in_cache(i_locator);
918
919 // record the lighted surface in the corresponding variants cache
920 reacquired_lvar[ls] = res;
921 return res;
922}
923
924texture get_lighted_texture(const image::locator& i_locator, const std::vector<light_adjust>& ls)
925{
926 if(i_locator.is_void()) {
927 return texture();
928 }
929
930 lit_texture_variants& lvar = lit_textures_.access_in_cache(i_locator);
931
932 // Check the matching list_string variants for this locator
933 if(const auto iter = lvar.find(ls); iter != lvar.end()) {
934 return iter->second;
935 } else {
936 DBG_IMG << "lit texture cache miss: " << i_locator;
937 }
938
939 // not cached yet, generate it
940 texture tex(get_lighted_image(i_locator, ls));
941
942 // record the lighted texture in the corresponding variants cache
943 lvar[ls] = tex;
944 return tex;
945}
946
948{
949 static const image::locator terrain_mask(game_config::images::terrain_mask);
950 return get_surface(terrain_mask, UNSCALED);
951}
952
953point get_size(const locator& i_locator, bool skip_cache)
954{
955 if(const surface s = get_surface(i_locator, UNSCALED, skip_cache)) {
956 return {s->w, s->h};
957 } else {
958 return {0, 0};
959 }
960}
961
962bool is_in_hex(const locator& i_locator)
963{
964 if(const bool* cached_value = in_hex_info_.locate_in_cache(i_locator)) {
965 return *cached_value;
966 } else {
967 bool res = in_mask_surface(get_surface(i_locator, UNSCALED), get_hexmask());
968 in_hex_info_.add_to_cache(i_locator, res);
969 return res;
970 }
971}
972
973bool is_empty_hex(const locator& i_locator)
974{
975 if(const bool* cached_value = is_empty_hex_.locate_in_cache(i_locator)) {
976 return *cached_value;
977 }
978
979 surface surf = get_surface(i_locator, HEXED);
980
981 // Empty state should be cached during surface fetch. Let's check again
982 if(const bool* cached_value = is_empty_hex_.locate_in_cache(i_locator)) {
983 return *cached_value;
984 }
985
986 // Should never reach this point, but let's manually do it anyway.
987 surf = surf.clone();
988 bool is_empty = mask_surface(surf, get_hexmask());
989 is_empty_hex_.add_to_cache(i_locator, is_empty);
990 return is_empty;
991}
992
993bool exists(const image::locator& i_locator)
994{
995 if(i_locator.is_void()) {
996 return false;
997 }
998
999 // The insertion will fail if there is already an element in the cache
1000 // and this will point to the existing element.
1001 auto [iter, success] = image_existence_map.emplace(i_locator.get_filename(), false);
1002
1003 bool& cache = iter->second;
1004 if(success) {
1005 if(i_locator.is_data_uri()) {
1006 cache = parsed_data_URI{i_locator.get_filename()}.good;
1007 } else {
1008 cache = filesystem::get_binary_file_location("images", i_locator.get_filename()).has_value();
1009 }
1010 }
1011
1012 return cache;
1013}
1014
1015static void precache_file_existence_internal(const std::string& dir, const std::string& subdir)
1016{
1017 const std::string checked_dir = dir + "/" + subdir;
1018 if(precached_dirs.find(checked_dir) != precached_dirs.end()) {
1019 return;
1020 }
1021
1022 precached_dirs.insert(checked_dir);
1023
1024 if(!filesystem::is_directory(checked_dir)) {
1025 return;
1026 }
1027
1028 std::vector<std::string> files_found;
1029 std::vector<std::string> dirs_found;
1030 filesystem::get_files_in_dir(checked_dir, &files_found, &dirs_found, filesystem::name_mode::FILE_NAME_ONLY,
1032
1033 for(const auto& f : files_found) {
1034 image_existence_map[subdir + f] = true;
1035 }
1036
1037 for(const auto& d : dirs_found) {
1038 precache_file_existence_internal(dir, subdir + d + "/");
1039 }
1040}
1041
1042void precache_file_existence(const std::string& subdir)
1043{
1044 for(const auto& p : filesystem::get_binary_paths("images")) {
1046 }
1047}
1048
1049bool precached_file_exists(const std::string& file)
1050{
1051 const auto b = image_existence_map.find(file);
1052 if(b != image_existence_map.end()) {
1053 return b->second;
1054 }
1055
1056 return false;
1057}
1058
1059save_result save_image(const locator& i_locator, const std::string& filename)
1060{
1061 return save_image(get_surface(i_locator), filename);
1062}
1063
1064save_result save_image(const surface& surf, const std::string& filename)
1065{
1066 if(!surf) {
1067 return save_result::no_image;
1068 }
1069
1070 if(boost::algorithm::ends_with(filename, ".jpeg") || boost::algorithm::ends_with(filename, ".jpg") || boost::algorithm::ends_with(filename, ".jpe")) {
1071 LOG_IMG << "Writing a JPG image to " << filename;
1072 const int err = IMG_SaveJPG(surf, filename.c_str(), 75);
1074 }
1075
1076 if(boost::algorithm::ends_with(filename, ".png")) {
1077 LOG_IMG << "Writing a PNG image to " << filename;
1078 const int err = IMG_SavePNG(surf, filename.c_str());
1080 }
1081
1083}
1084
1085/*
1086 * TEXTURE INTERFACE ======================================================================
1087 *
1088 * The only important difference here is that textures must have their
1089 * scale quality set before creation. All other handling is done by
1090 * get_surface.
1091 */
1092
1093texture get_texture(const image::locator& i_locator, TYPE type, bool skip_cache)
1094{
1095 return get_texture(i_locator, scale_quality::nearest, type, skip_cache);
1096}
1097
1098/** Returns a texture for the corresponding image. */
1099texture get_texture(const image::locator& i_locator, scale_quality quality, TYPE type, bool skip_cache)
1100{
1101 texture res;
1102
1103 // Occasionally reclaim stale intermediate surfaces even when no further sub-file
1104 // loads happen. Counter-gated so this render-path call stays cheap.
1105 static int prune_counter = 0;
1106 if(++prune_counter >= 20000) {
1107 prune_counter = 0;
1108 intermediate_surfaces_.prune_stale();
1109 }
1110
1111 if(i_locator.is_void()) {
1112 return res;
1113 }
1114
1115 type = simplify_type(i_locator, type);
1116
1117 //
1118 // Select the appropriate cache. We don't need caches for every single image types,
1119 // since some types can be handled by render-time operations.
1120 //
1121 texture_cache* cache = nullptr;
1122
1123 switch(type) {
1124 case HEXED:
1125 cache = &textures_hexed_[quality];
1126 break;
1127 case TOD_COLORED:
1128 cache = &texture_tod_colored_[quality];
1129 break;
1130 default:
1131 cache = &textures_[quality];
1132 }
1133
1134 //
1135 // Now attempt to find a cached texture. If found, return it.
1136 //
1137 if(const texture* cached_texture = cache->locate_in_cache(i_locator)) {
1138 return *cached_texture;
1139 } else {
1140 DBG_IMG << "texture cache [" << type << "] miss: " << i_locator;
1141 }
1142
1143 //
1144 // No texture was cached. In that case, create a new one. The explicit cases require special
1145 // handling with surfaces in order to generate the desired effect. This shouldn't be the case
1146 // once we get OGL and shader support.
1147 //
1148
1149 // Get it from the surface cache, also setting the desired scale quality.
1150 const bool linear_scaling = quality == scale_quality::linear ? true : false;
1151 if(i_locator.get_modifications().empty()) {
1152 // skip cache if we're loading plain files with no modifications
1153 res = texture(get_surface(i_locator, type, true), linear_scaling);
1154 } else {
1155 res = texture(get_surface(i_locator, type, skip_cache), linear_scaling);
1156 }
1157
1158 // Cache the texture.
1159 if(skip_cache) {
1160 DBG_IMG << "texture cache [" << type << "] skip: " << i_locator;
1161 } else {
1162 cache->add_to_cache(i_locator, res);
1163 }
1164
1165 return res;
1166}
1167
1168} // end namespace image
std::string filename_
map_location loc
Definition move.cpp:172
#define ERR_CFG
Definition manager.cpp:30
bool in_cache(const locator &item) const
Definition picture.cpp:90
T & access_in_cache(const locator &item)
Returns a reference to the cache item associated with the given key.
Definition picture.cpp:109
const T * locate_in_cache(const locator &item) const
Returns a pointer to the cached value, or nullptr if not found.
Definition picture.cpp:96
cache_map< locator, T > content_
Definition picture.cpp:125
void add_to_cache(const locator &item, T data)
Definition picture.cpp:114
Generic locator abstracting the location of an image.
Definition picture.hpp:59
bool is_void() const
Returns true if the locator does not correspond to an actual image.
Definition picture.hpp:93
map_location loc_
Definition picture.hpp:100
std::string filename_
Definition picture.hpp:98
const std::string & get_filename() const
Definition picture.hpp:82
bool is_data_uri() const
Definition picture.hpp:83
bool is_data_uri_
Definition picture.hpp:97
const map_location & get_loc() const
Definition picture.hpp:84
locator::type type_
Definition picture.hpp:96
locator()=default
bool operator<(const locator &a) const
Definition picture.cpp:422
bool operator==(const locator &a) const
Definition picture.cpp:408
locator clone(const std::string &mods) const
Returns a copy of this locator with the given IPF.
Definition picture.cpp:337
std::string modifications_
Definition picture.hpp:99
const std::string & get_modifications() const
Definition picture.hpp:87
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.
Definition surface.cpp:97
Wrapper class to encapsulate creation and management of an SDL_Texture.
Definition texture.hpp:33
Declarations for File-IO.
Standard logging facilities (interface).
std::vector< uint8_t > decode(std::string_view in)
Definition base64.cpp:219
void clear()
Clear the current render target.
Definition draw.cpp:121
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.
std::string terrain_mask
const bool & debug
unsigned int tile_size
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...
Definition picture.cpp:509
bool is_empty_hex(const locator &i_locator)
Checks if an image is empty after hex masking.
Definition picture.cpp:973
static void add_localized_overlay(const std::string &ovr_file, surface &orig_surf)
Definition picture.cpp:437
bool precached_file_exists(const std::string &file)
Definition picture.cpp:1049
save_result
Definition picture.hpp:271
static TYPE simplify_type(const image::locator &i_locator, TYPE type)
translate type to a simpler one when possible
Definition picture.cpp:811
static surface load_image_data_uri(const image::locator &loc)
Definition picture.cpp:595
static surface get_tod_colored(const locator &i_locator, bool skip_cache=false)
Definition picture.cpp:803
bool exists(const image::locator &i_locator)
Returns true if the given image actually exists, without loading it.
Definition picture.cpp:993
void flush_cache()
Purges all image caches.
Definition picture.cpp:318
static void precache_file_existence_internal(const std::string &dir, const std::string &subdir)
Definition picture.cpp:1015
static surface load_from_disk(const locator &loc)
Definition picture.cpp:715
surface get_surface(const image::locator &i_locator, TYPE type, bool skip_cache)
Returns an image surface suitable for software manipulation.
Definition picture.cpp:829
static surface apply_light(surface surf, const std::vector< light_adjust > &ls)
Definition picture.cpp:658
surface get_hexmask()
Retrieves the standard hexagonal tile mask.
Definition picture.cpp:947
std::ostream & operator<<(std::ostream &s, const locator &l)
Definition picture.cpp:348
save_result save_image(const locator &i_locator, const std::string &filename)
Definition picture.cpp:1059
void precache_file_existence(const std::string &subdir)
Precache the existence of files in a binary path subdirectory (e.g.
Definition picture.cpp:1042
TYPE
Used to specify the rendering format of images.
Definition picture.hpp:171
@ HEXED
Standard hexagonal tile mask applied, removing portions that don't fit.
Definition picture.hpp:175
@ NUM_TYPES
Definition picture.hpp:178
@ TOD_COLORED
Same as HEXED, but with Time of Day color tint applied.
Definition picture.hpp:177
@ UNSCALED
Unmodified original-size image.
Definition picture.hpp:173
texture get_texture(const image::locator &i_locator, TYPE type, bool skip_cache)
Returns an image texture suitable for hardware-accelerated rendering.
Definition picture.cpp:1093
point get_size(const locator &i_locator, bool skip_cache)
Returns the width and height of an image.
Definition picture.cpp:953
static surface get_hexed(const locator &i_locator, bool skip_cache=false)
Definition picture.cpp:753
texture get_lighted_texture(const image::locator &i_locator, const std::vector< light_adjust > &ls)
Definition picture.cpp:924
std::size_t hash_value(const image::locator &val)
Hash function overload for boost::hash.
Definition picture.cpp:67
void set_color_adjustment(int r, int g, int b)
Changes Time of Day color tint for all applicable image types.
Definition picture.cpp:740
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.
Definition picture.cpp:897
bool is_in_hex(const locator &i_locator)
Checks if an image fits into a single hex.
Definition picture.cpp:962
scale_quality
Definition picture.hpp:181
static surface load_image_file(const image::locator &loc)
Definition picture.cpp:449
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()
Definition general.hpp:142
static constexpr std::chrono::seconds prune_interval
Definition picture.cpp:291
#define DBG_IMG
Definition picture.cpp:57
static lg::log_domain log_image("image")
std::string_view scheme
Definition picture.cpp:185
entry_map lookup_
Definition picture.cpp:309
surface surf
Definition picture.cpp:280
boost::unordered_map< Key, Value > cache_map
Definition picture.cpp:46
std::size_t size_bytes
Definition picture.cpp:281
std::string_view mime
Definition picture.cpp:186
bool good
Definition picture.cpp:189
static constexpr std::size_t max_size
Definition picture.cpp:289
#define WRN_IMG
Definition picture.cpp:55
entry_list lru_list_
Definition picture.cpp:308
std::chrono::steady_clock::time_point last_stale_check_
Definition picture.cpp:311
#define LOG_IMG
Definition picture.cpp:56
#define ERR_IMG
Definition picture.cpp:54
std::string_view data
Definition picture.cpp:188
std::size_t size_
Definition picture.cpp:310
std::chrono::steady_clock::time_point last_access
Definition picture.cpp:282
static lg::log_domain log_config("config")
static constexpr std::chrono::seconds ttl
Definition picture.cpp:290
Contains the SDL_Rect helper code.
std::unordered_map< std::string, cache_item > cache
Definition sound.cpp:146
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.
Definition picture.hpp:124
bool operator==(const light_adjust &o) const
Definition picture.cpp:639
light_adjust(int op, int r, int g, int b)
Definition picture.cpp:626
Exception thrown by the operator() when an error occurs.
Encapsulates the map of the game.
Definition location.hpp:46
bool valid() const
Definition location.hpp:111
Holds a 2D point.
Definition point.hpp:25
An abstract description of a rectangle with integer coordinates.
Definition rect.hpp:49
mock_party p
static map_location::direction s
surface cut_surface(const surface &surf, const rect &r)
Cuts a rectangle from a surface.
Definition utils.cpp:1092
void adjust_surface_color(surface &nsurf, int red, int green, int blue)
Definition utils.cpp:405
void light_surface(surface &nsurf, const surface &lightmap)
Light surf using lightmap.
Definition utils.cpp:790
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.
Definition utils.cpp:756
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...
Definition utils.cpp:708
void sdl_blit(const surface &src, const SDL_Rect *src_rect, surface &dst, SDL_Rect *dst_rect)
Definition utils.hpp:43
#define g
#define d
#define e
#define f
#define b