Debian Codegraph @

Source/Core/VideoCommon/ShaderGenCommon.h

raw symbols SCIP
1 // Copyright 2012 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #pragma once
5
6 #include <cstring>
7 #include <functional>
8 #include <iterator>
9 #include <string>
10 #include <string_view>
11 #include <type_traits>
12 #include <vector>
13
14 #include <fmt/format.h>
15
16 #include "Common/BitField.h"
17 #include "Common/CommonTypes.h"
18 #include "Common/EnumMap.h"
19 #include "Common/StringUtil.h"
20 #include "Common/TypeUtils.h"
21
22 #include "VideoCommon/AbstractShader.h"
23 #include "VideoCommon/VideoCommon.h"
24
25 /**
26 * Common interface for classes that need to go through the shader generation path
27 * (GenerateVertexShader, GenerateGeometryShader, GeneratePixelShader)
28 * In particular, this includes the shader code generator (ShaderCode).
29 * A different class (ShaderUid) can be used to uniquely identify each ShaderCode object.
30 * More interesting things can be done with this, e.g. ShaderConstantProfile checks what shader
31 * constants are being used. This can be used to optimize buffer management.
32 * If the class does not use one or more of these methods (e.g. Uid class does not need code), the
33 * method will be defined as a no-op by the base class, and the call
34 * should be optimized out. The reason for this implementation is so that shader
35 * selection/generation can be done in two passes, with only a cache lookup being
36 * required if the shader has already been generated.
37 */
38 class ShaderGeneratorInterface
39 {
40 public:
41 /*
42 * Used when the shader generator would write a piece of ShaderCode.
43 * Can be used like printf.
44 * @note In the ShaderCode implementation, this does indeed write the parameter string to an
45 * internal buffer. However, you're free to do whatever you like with the parameter.
46 */
47 void Write(const char*, ...)
48 #ifdef __GNUC__
49 __attribute__((format(printf, 2, 3)))
50 #endif
51 {
52 }
53
54 /*
55 * Tells us that a specific constant range (including last_index) is being used by the shader
56 */
57 void SetConstantsUsed(unsigned int first_index, unsigned int last_index) {}
58 };
59
60 /*
61 * Shader UID class used to uniquely identify the ShaderCode output written in the shader generator.
62 * uid_data can be any struct of parameters that uniquely identify each shader code output.
63 * Unless performance is not an issue, uid_data should be tightly packed to reduce memory footprint.
64 * Shader generators will write to specific uid_data fields; ShaderUid methods will only read raw
65 * u32 values from a union.
66 * NOTE: Because LinearDiskCache reads and writes the storage associated with a ShaderUid instance,
67 * ShaderUid must be trivially copyable.
68 */
69 template <class uid_data>
70 class ShaderUid : public ShaderGeneratorInterface
71 {
72 public:
73 static_assert(std::is_trivially_copyable_v<uid_data>,
74 "uid_data must be a trivially copyable type");
75
76 ShaderUid() { memset(GetUidData(), 0, GetUidDataSize()); }
77
78 bool operator==(const ShaderUid& obj) const
79 {
80 return memcmp(GetUidData(), obj.GetUidData(), GetUidDataSize()) == 0;
81 }
82
83 // determines the storage order inside STL containers
84 bool operator<(const ShaderUid& obj) const
85 {
86 return memcmp(GetUidData(), obj.GetUidData(), GetUidDataSize()) < 0;
87 }
88
89 // Returns a pointer to an internally stored object of the uid_data type.
90 uid_data* GetUidData() { return &data; }
91
92 // Returns a pointer to an internally stored object of the uid_data type.
93 const uid_data* GetUidData() const { return &data; }
94
95 // Returns the raw bytes that make up the shader UID.
96 const u8* GetUidDataRaw() const { return reinterpret_cast<const u8*>(&data); }
97
98 // Returns the size of the underlying UID data structure in bytes.
99 size_t GetUidDataSize() const { return sizeof(data); }
100
101 private:
102 uid_data data{};
103 };
104
105 class ShaderCode : public ShaderGeneratorInterface
106 {
107 public:
108 ShaderCode() { m_buffer.reserve(16384); }
109 const std::string& GetBuffer() const { return m_buffer; }
110
111 // Writes format strings using fmtlib format strings.
112 template <typename... Args>
113 void Write(fmt::format_string<Args...> format, Args&&... args)
114 {
115 fmt::format_to(std::back_inserter(m_buffer), format, std::forward<Args>(args)...);
116 }
117
118 protected:
119 std::string m_buffer;
120 };
121
122 /**
123 * Generates a shader constant profile which can be used to query which constants are used in a
124 * shader
125 */
126 class ShaderConstantProfile : public ShaderGeneratorInterface
127 {
128 public:
129 ShaderConstantProfile(int num_constants) { constant_usage.resize(num_constants); }
130 void SetConstantsUsed(unsigned int first_index, unsigned int last_index)
131 {
132 for (unsigned int i = first_index; i < last_index + 1; ++i)
133 constant_usage[i] = true;
134 }
135
136 bool ConstantIsUsed(unsigned int index) const
137 {
138 // TODO: Not ready for usage yet
139 return true;
140 // return constant_usage[index];
141 }
142
143 private:
144 std::vector<bool> constant_usage; // TODO: Is vector<bool> appropriate here?
145 };
146
147 // Host config contains the settings which can influence generated shaders.
148 union ShaderHostConfig
149 {
150 u32 bits;
151
152 BitField<0, 1, bool, u32> msaa;
153 BitField<1, 1, bool, u32> ssaa;
154 BitField<2, 1, bool, u32> stereo;
155 BitField<3, 1, bool, u32> wireframe;
156 BitField<4, 1, bool, u32> per_pixel_lighting;
157 BitField<5, 1, bool, u32> vertex_rounding;
158 BitField<6, 1, bool, u32> fast_depth_calc;
159 BitField<7, 1, bool, u32> bounding_box;
160 BitField<8, 1, bool, u32> backend_dual_source_blend;
161 BitField<9, 1, bool, u32> backend_geometry_shaders;
162 BitField<10, 1, bool, u32> backend_early_z;
163 BitField<11, 1, bool, u32> backend_bbox;
164 BitField<12, 1, bool, u32> backend_gs_instancing;
165 BitField<13, 1, bool, u32> backend_clip_control;
166 BitField<14, 1, bool, u32> backend_ssaa;
167 BitField<15, 1, bool, u32> backend_atomics;
168 BitField<16, 1, bool, u32> backend_depth_clamp;
169 BitField<17, 1, bool, u32> backend_reversed_depth_range;
170 BitField<18, 1, bool, u32> backend_bitfield;
171 BitField<19, 1, bool, u32> backend_dynamic_sampler_indexing;
172 BitField<20, 1, bool, u32> backend_shader_framebuffer_fetch;
173 BitField<21, 1, bool, u32> backend_logic_op;
174 BitField<22, 1, bool, u32> backend_palette_conversion;
175 BitField<23, 1, bool, u32> enable_validation_layer;
176 BitField<24, 1, bool, u32> manual_texture_sampling;
177 BitField<25, 1, bool, u32> manual_texture_sampling_custom_texture_sizes;
178 BitField<26, 1, bool, u32> backend_sampler_lod_bias;
179 BitField<27, 1, bool, u32> backend_dynamic_vertex_loader;
180 BitField<28, 1, bool, u32> backend_vs_point_line_expand;
181 BitField<29, 1, bool, u32> backend_gl_layer_in_fs;
182
183 static ShaderHostConfig GetCurrent();
184 };
185
186 // Gets the filename of the specified type of cache object (e.g. vertex shader, pipeline).
187 std::string GetDiskShaderCacheFileName(APIType api_type, const char* type, bool include_gameid,
188 bool include_host_config, bool include_api = true);
189
190 void WriteIsNanHeader(ShaderCode& out, APIType api_type);
191 void WriteBitfieldExtractHeader(ShaderCode& out, APIType api_type,
192 const ShaderHostConfig& host_config);
193
194 void GenerateVSOutputMembers(ShaderCode& object, APIType api_type, u32 texgens,
195 const ShaderHostConfig& host_config, std::string_view qualifier,
196 ShaderStage stage);
197
198 void AssignVSOutputMembers(ShaderCode& object, std::string_view a, std::string_view b, u32 texgens,
199 const ShaderHostConfig& host_config);
200
201 void GenerateLineOffset(ShaderCode& object, std::string_view indent0, std::string_view indent1,
202 std::string_view pos_a, std::string_view pos_b, std::string_view sign);
203
204 void GenerateVSLineExpansion(ShaderCode& object, std::string_view indent, u32 texgens);
205
206 void GenerateVSPointExpansion(ShaderCode& object, std::string_view indent, u32 texgens);
207
208 // We use the flag "centroid" to fix some MSAA rendering bugs. With MSAA, the
209 // pixel shader will be executed for each pixel which has at least one passed sample.
210 // So there may be rendered pixels where the center of the pixel isn't in the primitive.
211 // As the pixel shader usually renders at the center of the pixel, this position may be
212 // outside the primitive. This will lead to sampling outside the texture, sign changes, ...
213 // As a workaround, we interpolate at the centroid of the coveraged pixel, which
214 // is always inside the primitive.
215 // Without MSAA, this flag is defined to have no effect.
216 const char* GetInterpolationQualifier(bool msaa, bool ssaa, bool in_glsl_interface_block = false,
217 bool in = false);
218
219 // bitfieldExtract generator for BitField types
220 template <auto ptr_to_bitfield_member>
221 std::string BitfieldExtract(std::string_view source)
222 {
223 using BitFieldT = Common::MemberType<ptr_to_bitfield_member>;
224 return fmt::format("bitfieldExtract({}({}), {}, {})", BitFieldT::IsSigned() ? "int" : "uint",
225 source, static_cast<u32>(BitFieldT::StartBit()),
226 static_cast<u32>(BitFieldT::NumBits()));
227 }
228
229 template <auto last_member>
230 void WriteSwitch(ShaderCode& out, APIType ApiType, std::string_view variable,
231 const Common::EnumMap<std::string_view, last_member>& values, int indent,
232 bool break_)
233 {
234 using enum_type = decltype(last_member);
235
236 // Generate a tree of if statements recursively
237 // std::function must be used because auto won't capture before initialization and thus can't be
238 // used recursively
239 std::function<void(u32, u32, u32)> BuildTree = [&](u32 cur_indent, u32 low, u32 high) {
240 // Each generated statement is for low <= x < high
241 if (high == low + 1)
242 {
243 // Down to 1 case (low <= x < low + 1 means x == low)
244 const enum_type key = static_cast<enum_type>(low);
245 // Note that this indentation behaves poorly for multi-line code
246 out.Write("{:{}}{} // {}\n", "", cur_indent, values[key], key);
247 }
248 else
249 {
250 u32 mid = low + ((high - low) / 2);
251 out.Write("{:{}}if ({} < {}u) {{\n", "", cur_indent, variable, mid);
252 BuildTree(cur_indent + 2, low, mid);
253 out.Write("{:{}}}} else {{\n", "", cur_indent);
254 BuildTree(cur_indent + 2, mid, high);
255 out.Write("{:{}}}}\n", "", cur_indent);
256 }
257 };
258 BuildTree(indent, 0, static_cast<u32>(last_member) + 1);
259 }
260
261 // Constant variable names
262 #define I_COLORS "color"
263 #define I_KCOLORS "k"
264 #define I_ALPHA "alphaRef"
265 #define I_TEXDIMS "texdim"
266 #define I_ZBIAS "czbias"
267 #define I_INDTEXSCALE "cindscale"
268 #define I_INDTEXMTX "cindmtx"
269 #define I_FOGCOLOR "cfogcolor"
270 #define I_FOGI "cfogi"
271 #define I_FOGF "cfogf"
272 #define I_FOGRANGE "cfogrange"
273 #define I_ZSLOPE "czslope"
274 #define I_EFBSCALE "cefbscale"
275
276 #define I_POSNORMALMATRIX "cpnmtx"
277 #define I_PROJECTION "cproj"
278 #define I_MATERIALS "cmtrl"
279 #define I_LIGHTS "clights"
280 #define I_TEXMATRICES "ctexmtx"
281 #define I_TRANSFORMMATRICES "ctrmtx"
282 #define I_NORMALMATRICES "cnmtx"
283 #define I_POSTTRANSFORMMATRICES "cpostmtx"
284 #define I_PIXELCENTERCORRECTION "cpixelcenter"
285 #define I_VIEWPORT_SIZE "cviewport"
286 #define I_CACHED_NORMAL "cnormal"
287 #define I_CACHED_TANGENT "ctangent"
288 #define I_CACHED_BINORMAL "cbinormal"
289
290 #define I_STEREOPARAMS "cstereo"
291 #define I_LINEPTPARAMS "clinept"
292 #define I_TEXOFFSET "ctexoffset"
293
294 static const char s_shader_uniforms[] = "\tuint components;\n"
295 "\tuint xfmem_dualTexInfo;\n"
296 "\tuint xfmem_numColorChans;\n"
297 "\tuint missing_color_hex;\n"
298 "\tfloat4 missing_color_value;\n"
299 "\tfloat4 " I_POSNORMALMATRIX "[6];\n"
300 "\tfloat4 " I_PROJECTION "[4];\n"
301 "\tint4 " I_MATERIALS "[4];\n"
302 "\tLight " I_LIGHTS "[8];\n"
303 "\tfloat4 " I_TEXMATRICES "[24];\n"
304 "\tfloat4 " I_TRANSFORMMATRICES "[64];\n"
305 "\tfloat4 " I_NORMALMATRICES "[32];\n"
306 "\tfloat4 " I_POSTTRANSFORMMATRICES "[64];\n"
307 "\tfloat4 " I_PIXELCENTERCORRECTION ";\n"
308 "\tfloat2 " I_VIEWPORT_SIZE ";\n"
309 "\tuint4 xfmem_pack1[8];\n"
310 "\tfloat4 " I_CACHED_NORMAL ";\n"
311 "\tfloat4 " I_CACHED_TANGENT ";\n"
312 "\tfloat4 " I_CACHED_BINORMAL ";\n"
313 "\tuint vertex_stride;\n"
314 "\tuint vertex_offset_rawnormal;\n"
315 "\tuint vertex_offset_rawtangent;\n"
316 "\tuint vertex_offset_rawbinormal;\n"
317 "\tuint vertex_offset_rawpos;\n"
318 "\tuint vertex_offset_posmtx;\n"
319 "\tuint vertex_offset_rawcolor0;\n"
320 "\tuint vertex_offset_rawcolor1;\n"
321 "\tuint4 vertex_offset_rawtex[2];\n" // std140 is pain
322 "\t#define xfmem_texMtxInfo(i) (xfmem_pack1[(i)].x)\n"
323 "\t#define xfmem_postMtxInfo(i) (xfmem_pack1[(i)].y)\n"
324 "\t#define xfmem_color(i) (xfmem_pack1[(i)].z)\n"
325 "\t#define xfmem_alpha(i) (xfmem_pack1[(i)].w)\n";
326
327 static const char s_geometry_shader_uniforms[] = "\tfloat4 " I_STEREOPARAMS ";\n"
328 "\tfloat4 " I_LINEPTPARAMS ";\n"
329 "\tint4 " I_TEXOFFSET ";\n"
330 "\tuint vs_expand;\n";
331
332 constexpr std::string_view CUSTOM_PIXELSHADER_COLOR_FUNC = "customShaderColor";
333
334 struct CustomPixelShader
335 {
336 std::string custom_shader;
337 std::string material_uniform_block;
338
339 bool operator==(const CustomPixelShader& other) const = default;
340 };
341
342 struct CustomPixelShaderContents
343 {
344 std::vector<CustomPixelShader> shaders;
345
346 bool operator==(const CustomPixelShaderContents& other) const = default;
347 };