Toast Engine
Loading...
Searching...
No Matches
shader_cache.hpp
Go to the documentation of this file.
1
6
7#pragma once
8
10
11#include <cstddef>
12#include <future>
13#include <memory>
14#include <mutex>
15#include <optional>
16#include <string>
19#include <toast/events/event.hpp>
20#include <toast/events/listener.hpp>
21#include <toast/uid.hpp>
22#include <unordered_map>
23#include <unordered_set>
24#include <vector>
25
26namespace event {
27
28struct ShaderRecompiled : public Event<ShaderRecompiled> {
29 toast::UID uid;
30
31 explicit ShaderRecompiled(toast::UID uid) : uid(uid) { }
32};
33
34}
35
36namespace renderer {
37
38class TOAST_API ShaderCache {
39public:
40 struct Entry {
41 std::vector<std::byte> spirv;
42 ShaderReflection reflection;
43 uint64_t hash = 0;
44 std::string source_uri;
45 std::vector<std::string> dependencies;
46 };
47
48 static auto get() -> ShaderCache&;
49
50 void compileAllAtStartup();
51
53 auto acquire(toast::UID uid) -> std::shared_ptr<const Entry>;
54
55 auto ensureCompiled(toast::UID uid) -> bool;
56
57 auto onShaderSourceReloaded(toast::UID uid) -> bool;
58
59 static auto fnv1a(const void* data, size_t size) -> uint64_t;
60
61private:
62 using EntryPtr = std::shared_ptr<const Entry>;
63
64 ShaderCache();
65
67 auto loadOrCompile(toast::UID uid) -> EntryPtr;
68 auto compile(toast::UID uid, const std::string& source) -> EntryPtr;
69 static auto loadFromDisk(toast::UID uid) -> EntryPtr;
70 auto isDiskCacheFresh(toast::UID uid, uint64_t source_hash) -> bool;
72 auto sourceOf(toast::UID uid) -> std::optional<std::string>;
73
74 void loadHashIndexLocked();
75 void saveHashIndexLocked();
76 auto sourceHandleLocked(toast::UID uid) -> assets::Handle<assets::Shader>&;
77
79 std::mutex m_mutex;
80 std::unordered_map<uint64_t, EntryPtr> m_entries;
81 std::unordered_map<uint64_t, std::shared_future<EntryPtr>> m_in_flight;
82 std::unordered_map<uint64_t, assets::Handle<assets::Shader>> m_sources;
83 std::unordered_map<uint64_t, std::unordered_set<uint64_t>> m_reverse_deps;
84 nlohmann::json m_hash_index;
85 bool m_hash_index_loaded = false;
86
87 event::Listener m_listener;
88};
89
90}
Type-safe smart pointer for assets.
Definition core_types.hpp:149
manages the lifetime, subscription, and unsubscription of callbacks
Definition listener.hpp:39
auto acquire(toast::UID uid) -> std::shared_ptr< const Entry >
Thread safe and concurrent calls for one shader share a compile.
Definition shader_cache.cpp:283
Base types for the asset system.
Slang shader source asset, compiled to SPIR-V by the renderer's ShaderCache.
Definition shader_cache.hpp:40
Definition shader_reflection.hpp:87
Definition uid.hpp:20
Unique identifier for everything that exists in our engine.