layers/evaluation_cache.h
| Line | Branch | Exec | Source |
|---|---|---|---|
| 1 | /// @file | ||
| 2 | /// @brief `EvaluationCache`, values one evaluation's batches of points share. | ||
| 3 | #pragma once | ||
| 4 | |||
| 5 | #include "terraingen/util/lru_cache.h" | ||
| 6 | |||
| 7 | #include <bit> | ||
| 8 | #include <cstddef> | ||
| 9 | #include <cstdint> | ||
| 10 | #include <functional> | ||
| 11 | #include <memory> | ||
| 12 | |||
| 13 | namespace terraingen { | ||
| 14 | |||
| 15 | /// Values that depend only on the terrain beneath a layer, such as crater datums, computed once | ||
| 16 | /// per evaluation of points and shared by its batches; thread-safe. | ||
| 17 | /// | ||
| 18 | /// An evaluation makes one and drops it at its end, so a value never outlives the terrain it was | ||
| 19 | /// computed for. Keys name the layer that owns the value (`owner`), a feature ID and the sample | ||
| 20 | /// spacing. | ||
| 21 | class EvaluationCache { | ||
| 22 | public: | ||
| 23 | /// An empty cache holding at most `capacity` values. | ||
| 24 | 75 | explicit EvaluationCache(std::size_t capacity = 1 << 20) | |
| 25 | 16858 | : values_(capacity, [](const Holder&) { return std::size_t{1}; }) {} | |
| 26 | |||
| 27 | /// The value of `owner` for feature `id` at `spacing`, computed by `compute` when not held. | ||
| 28 | template <typename T> | ||
| 29 | 132231 | std::shared_ptr<const T> Get(const void* owner, std::uint64_t id, double spacing, | |
| 30 | const std::function<T()>& compute) { | ||
| 31 | 264462 | const Key key{reinterpret_cast<std::uintptr_t>(owner), id, | |
| 32 | 132231 | std::bit_cast<std::uint64_t>(spacing)}; | |
| 33 | 132231 | const std::shared_ptr<const Holder> held = | |
| 34 | 149014 | values_.Get(key, [&] { return Holder{std::make_shared<const T>(compute())}; }); | |
| 35 | 264462 | return std::static_pointer_cast<const T>(held->value); | |
| 36 | 132231 | } | |
| 37 | |||
| 38 | private: | ||
| 39 | struct Key { | ||
| 40 | 115720 | std::uintptr_t owner = 0; | |
| 41 | 115720 | std::uint64_t id = 0; | |
| 42 | 115720 | std::uint64_t spacing = 0; | |
| 43 | |||
| 44 | 115720 | bool operator==(const Key&) const = default; | |
| 45 | }; | ||
| 46 | struct KeyHash { | ||
| 47 | 297396 | std::size_t operator()(const Key& key) const { | |
| 48 | 297396 | return std::hash<std::uint64_t>{}(key.id * 0x9E3779B97F4A7C15ull ^ key.owner ^ | |
| 49 | 297396 | (key.spacing << 1)); | |
| 50 | } | ||
| 51 | }; | ||
| 52 | struct Holder { | ||
| 53 | std::shared_ptr<const void> value; | ||
| 54 | }; | ||
| 55 | |||
| 56 | LruCache<Key, Holder, KeyHash> values_; | ||
| 57 | }; | ||
| 58 | |||
| 59 | } // namespace terraingen | ||
| 60 |