Debian Codegraph @

Source/Core/VideoCommon/VertexLoaderManager.cpp

raw symbols SCIP
1 // Copyright 2008 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #include "VideoCommon/VertexLoaderManager.h"
5
6 #include <algorithm>
7 #include <iterator>
8 #include <memory>
9 #include <mutex>
10 #include <string>
11 #include <type_traits>
12 #include <unordered_map>
13 #include <utility>
14 #include <vector>
15
16 #include "Common/CommonTypes.h"
17 #include "Common/EnumMap.h"
18 #include "Common/Logging/Log.h"
19
20 #include "Core/DolphinAnalytics.h"
21 #include "Core/HW/Memmap.h"
22 #include "Core/System.h"
23
24 #include "VideoCommon/AbstractGfx.h"
25 #include "VideoCommon/BPMemory.h"
26 #include "VideoCommon/CPMemory.h"
27 #include "VideoCommon/DataReader.h"
28 #include "VideoCommon/NativeVertexFormat.h"
29 #include "VideoCommon/Statistics.h"
30 #include "VideoCommon/VertexLoaderBase.h"
31 #include "VideoCommon/VertexManagerBase.h"
32 #include "VideoCommon/VertexShaderManager.h"
33 #include "VideoCommon/VideoConfig.h"
34 #include "VideoCommon/XFMemory.h"
35
36 namespace VertexLoaderManager
37 {
38 // Used by zfreeze
39 std::array<u32, 3> position_matrix_index_cache;
40 // 3 vertices, 4 floats each to allow SIMD overwrite
41 alignas(sizeof(std::array<float, 4>)) std::array<std::array<float, 4>, 3> position_cache;
42 alignas(sizeof(std::array<float, 4>)) std::array<float, 4> normal_cache;
43 alignas(sizeof(std::array<float, 4>)) std::array<float, 4> tangent_cache;
44 alignas(sizeof(std::array<float, 4>)) std::array<float, 4> binormal_cache;
45
46 static NativeVertexFormatMap s_native_vertex_map;
47 static NativeVertexFormat* s_current_vtx_fmt;
48 u32 g_current_components;
49
50 typedef std::unordered_map<VertexLoaderUID, std::unique_ptr<VertexLoaderBase>> VertexLoaderMap;
51 static std::mutex s_vertex_loader_map_lock;
52 static VertexLoaderMap s_vertex_loader_map;
53 // TODO - change into array of pointers. Keep a map of all seen so far.
54
55 Common::EnumMap<u8*, CPArray::TexCoord7> cached_arraybases;
56
57 BitSet8 g_main_vat_dirty;
58 BitSet8 g_preprocess_vat_dirty;
59 bool g_bases_dirty; // Main only
60 std::array<VertexLoaderBase*, CP_NUM_VAT_REG> g_main_vertex_loaders;
61 std::array<VertexLoaderBase*, CP_NUM_VAT_REG> g_preprocess_vertex_loaders;
62 bool g_needs_cp_xf_consistency_check;
63
64 void Init()
65 {
66 MarkAllDirty();
67 g_main_vertex_loaders.fill(nullptr);
68 g_preprocess_vertex_loaders.fill(nullptr);
69 SETSTAT(g_stats.num_vertex_loaders, 0);
70 }
71
72 void Clear()
73 {
74 std::lock_guard<std::mutex> lk(s_vertex_loader_map_lock);
75 s_vertex_loader_map.clear();
76 s_native_vertex_map.clear();
77 }
78
79 void UpdateVertexArrayPointers()
80 {
81 // Anything to update?
82 if (!g_bases_dirty) [[likely]]
83 return;
84
85 auto& system = Core::System::GetInstance();
86 auto& memory = system.GetMemory();
87
88 // Some games such as Burnout 2 can put invalid addresses into
89 // the array base registers. (see issue 8591)
90 // But the vertex arrays with invalid addresses aren't actually enabled.
91 // Note: Only array bases 0 through 11 are used by the Vertex loaders.
92 // 12 through 15 are used for loading data into xfmem.
93 // We also only update the array base if the vertex description states we are going to use it.
94 if (IsIndexed(g_main_cp_state.vtx_desc.low.Position))
95 {
96 u8* const base_pointer =
97 memory.GetPointerForRange(g_main_cp_state.array_bases[CPArray::Position], sizeof(u32));
98 if (base_pointer != nullptr)
99 cached_arraybases[CPArray::Position] = base_pointer;
100 }
101
102 if (IsIndexed(g_main_cp_state.vtx_desc.low.Normal))
103 {
104 u8* const base_pointer =
105 memory.GetPointerForRange(g_main_cp_state.array_bases[CPArray::Normal], sizeof(u32));
106 if (base_pointer != nullptr)
107 cached_arraybases[CPArray::Normal] = base_pointer;
108 }
109
110 for (u8 i = 0; i < g_main_cp_state.vtx_desc.low.Color.Size(); i++)
111 {
112 if (IsIndexed(g_main_cp_state.vtx_desc.low.Color[i]))
113 {
114 u8* const base_pointer =
115 memory.GetPointerForRange(g_main_cp_state.array_bases[CPArray::Color0 + i], sizeof(u32));
116 if (base_pointer != nullptr)
117 cached_arraybases[CPArray::Color0 + i] = base_pointer;
118 }
119 }
120
121 for (u8 i = 0; i < g_main_cp_state.vtx_desc.high.TexCoord.Size(); i++)
122 {
123 if (IsIndexed(g_main_cp_state.vtx_desc.high.TexCoord[i]))
124 {
125 u8* const base_pointer = memory.GetPointerForRange(
126 g_main_cp_state.array_bases[CPArray::TexCoord0 + i], sizeof(u32));
127 if (base_pointer != nullptr)
128 cached_arraybases[CPArray::TexCoord0 + i] = base_pointer;
129 }
130 }
131
132 g_bases_dirty = false;
133 }
134
135 void MarkAllDirty()
136 {
137 g_bases_dirty = true;
138 g_main_vat_dirty = BitSet8::AllTrue(8);
139 g_preprocess_vat_dirty = BitSet8::AllTrue(8);
140 g_needs_cp_xf_consistency_check = true;
141 }
142
143 NativeVertexFormat* GetOrCreateMatchingFormat(const PortableVertexDeclaration& decl)
144 {
145 auto iter = s_native_vertex_map.find(decl);
146 if (iter == s_native_vertex_map.end())
147 {
148 std::unique_ptr<NativeVertexFormat> fmt = g_gfx->CreateNativeVertexFormat(decl);
149 auto ipair = s_native_vertex_map.emplace(decl, std::move(fmt));
150 iter = ipair.first;
151 }
152
153 return iter->second.get();
154 }
155
156 NativeVertexFormat* GetUberVertexFormat(const PortableVertexDeclaration& decl)
157 {
158 // The padding in the structs can cause the memcmp() in the map to create duplicates.
159 // Avoid this by initializing the padding to zero.
160 PortableVertexDeclaration new_decl;
161 static_assert(std::is_trivially_copyable_v<PortableVertexDeclaration>);
162 std::memset(static_cast<void*>(&new_decl), 0, sizeof(new_decl));
163 new_decl.stride = decl.stride;
164
165 auto MakeDummyAttribute = [](AttributeFormat& attr, ComponentFormat type, int components,
166 bool integer) {
167 attr.type = type;
168 attr.components = components;
169 attr.offset = 0;
170 attr.enable = true;
171 attr.integer = integer;
172 };
173 auto CopyAttribute = [](AttributeFormat& attr, const AttributeFormat& src) {
174 attr.type = src.type;
175 attr.components = src.components;
176 attr.offset = src.offset;
177 attr.enable = src.enable;
178 attr.integer = src.integer;
179 };
180
181 if (decl.position.enable)
182 CopyAttribute(new_decl.position, decl.position);
183 else
184 MakeDummyAttribute(new_decl.position, ComponentFormat::Float, 1, false);
185 for (size_t i = 0; i < std::size(new_decl.normals); i++)
186 {
187 if (decl.normals[i].enable)
188 CopyAttribute(new_decl.normals[i], decl.normals[i]);
189 else
190 MakeDummyAttribute(new_decl.normals[i], ComponentFormat::Float, 1, false);
191 }
192 for (size_t i = 0; i < std::size(new_decl.colors); i++)
193 {
194 if (decl.colors[i].enable)
195 CopyAttribute(new_decl.colors[i], decl.colors[i]);
196 else
197 MakeDummyAttribute(new_decl.colors[i], ComponentFormat::UByte, 4, false);
198 }
199 for (size_t i = 0; i < std::size(new_decl.texcoords); i++)
200 {
201 if (decl.texcoords[i].enable)
202 CopyAttribute(new_decl.texcoords[i], decl.texcoords[i]);
203 else
204 MakeDummyAttribute(new_decl.texcoords[i], ComponentFormat::Float, 1, false);
205 }
206 if (decl.posmtx.enable)
207 CopyAttribute(new_decl.posmtx, decl.posmtx);
208 else
209 MakeDummyAttribute(new_decl.posmtx, ComponentFormat::UByte, 1, true);
210
211 return GetOrCreateMatchingFormat(new_decl);
212 }
213
214 namespace detail
215 {
216 template <bool IsPreprocess>
217 VertexLoaderBase* GetOrCreateLoader(int vtx_attr_group)
218 {
219 constexpr CPState* state = IsPreprocess ? &g_preprocess_cp_state : &g_main_cp_state;
220 constexpr BitSet8& attr_dirty = IsPreprocess ? g_preprocess_vat_dirty : g_main_vat_dirty;
221 constexpr auto& vertex_loaders =
222 IsPreprocess ? g_preprocess_vertex_loaders : g_main_vertex_loaders;
223
224 VertexLoaderBase* loader;
225
226 // We are not allowed to create a native vertex format on preprocessing as this is on the wrong
227 // thread
228 bool check_for_native_format = !IsPreprocess;
229
230 VertexLoaderUID uid(state->vtx_desc, state->vtx_attr[vtx_attr_group]);
231 std::lock_guard<std::mutex> lk(s_vertex_loader_map_lock);
232 VertexLoaderMap::iterator iter = s_vertex_loader_map.find(uid);
233 if (iter != s_vertex_loader_map.end())
234 {
235 loader = iter->second.get();
236 check_for_native_format &= !loader->m_native_vertex_format;
237 }
238 else
239 {
240 auto [it, added] = s_vertex_loader_map.try_emplace(
241 uid,
242 VertexLoaderBase::CreateVertexLoader(state->vtx_desc, state->vtx_attr[vtx_attr_group]));
243 loader = it->second.get();
244 INCSTAT(g_stats.num_vertex_loaders);
245 }
246 if (check_for_native_format)
247 {
248 // search for a cached native vertex format
249 loader->m_native_vertex_format = GetOrCreateMatchingFormat(loader->m_native_vtx_decl);
250 }
251 vertex_loaders[vtx_attr_group] = loader;
252 attr_dirty[vtx_attr_group] = false;
253 return loader;
254 }
255
256 } // namespace detail
257
258 static void CheckCPConfiguration(int vtx_attr_group)
259 {
260 // Validate that the XF input configuration matches the CP configuration
261 u32 num_cp_colors = std::count_if(
262 g_main_cp_state.vtx_desc.low.Color.begin(), g_main_cp_state.vtx_desc.low.Color.end(),
263 [](auto format) { return format != VertexComponentFormat::NotPresent; });
264 u32 num_cp_tex_coords = std::count_if(
265 g_main_cp_state.vtx_desc.high.TexCoord.begin(), g_main_cp_state.vtx_desc.high.TexCoord.end(),
266 [](auto format) { return format != VertexComponentFormat::NotPresent; });
267
268 u32 num_cp_normals;
269 if (g_main_cp_state.vtx_desc.low.Normal == VertexComponentFormat::NotPresent)
270 num_cp_normals = 0;
271 else if (g_main_cp_state.vtx_attr[vtx_attr_group].g0.NormalElements == NormalComponentCount::NTB)
272 num_cp_normals = 3;
273 else
274 num_cp_normals = 1;
275
276 std::optional<u32> num_xf_normals;
277 switch (xfmem.invtxspec.numnormals)
278 {
279 case NormalCount::None:
280 num_xf_normals = 0;
281 break;
282 case NormalCount::Normal:
283 num_xf_normals = 1;
284 break;
285 case NormalCount::NormalTangentBinormal:
286 case NormalCount::Invalid: // see https://bugs.dolphin-emu.org/issues/13070
287 num_xf_normals = 3;
288 break;
289 }
290
291 if (num_cp_colors != xfmem.invtxspec.numcolors || num_cp_normals != num_xf_normals ||
292 num_cp_tex_coords != xfmem.invtxspec.numtextures) [[unlikely]]
293 {
294 PanicAlertFmt("Mismatched configuration between CP and XF stages - {}/{} colors, {}/{} "
295 "normals, {}/{} texture coordinates. Please report on the issue tracker.\n\n"
296 "VCD: {:08x} {:08x}\nVAT {}: {:08x} {:08x} {:08x}\nXF vertex spec: {:08x}",
297 num_cp_colors, xfmem.invtxspec.numcolors, num_cp_normals,
298 num_xf_normals.has_value() ? fmt::to_string(num_xf_normals.value()) : "invalid",
299 num_cp_tex_coords, xfmem.invtxspec.numtextures, g_main_cp_state.vtx_desc.low.Hex,
300 g_main_cp_state.vtx_desc.high.Hex, vtx_attr_group,
301 g_main_cp_state.vtx_attr[vtx_attr_group].g0.Hex,
302 g_main_cp_state.vtx_attr[vtx_attr_group].g1.Hex,
303 g_main_cp_state.vtx_attr[vtx_attr_group].g2.Hex, xfmem.invtxspec.hex);
304
305 // Analytics reporting so we can discover which games have this problem, that way when we
306 // eventually simulate the behavior we have test cases for it.
307 if (num_cp_colors != xfmem.invtxspec.numcolors) [[unlikely]]
308 {
309 DolphinAnalytics::Instance().ReportGameQuirk(GameQuirk::MismatchedGPUColorsBetweenCPAndXF);
310 }
311 if (num_cp_normals != num_xf_normals) [[unlikely]]
312 {
313 DolphinAnalytics::Instance().ReportGameQuirk(GameQuirk::MismatchedGPUNormalsBetweenCPAndXF);
314 }
315 if (num_cp_tex_coords != xfmem.invtxspec.numtextures) [[unlikely]]
316 {
317 DolphinAnalytics::Instance().ReportGameQuirk(GameQuirk::MismatchedGPUTexCoordsBetweenCPAndXF);
318 }
319
320 // Don't bail out, though; we can still render something successfully
321 // (real hardware seems to hang in this case, though)
322 }
323
324 if (g_main_cp_state.matrix_index_a.Hex != xfmem.MatrixIndexA.Hex ||
325 g_main_cp_state.matrix_index_b.Hex != xfmem.MatrixIndexB.Hex) [[unlikely]]
326 {
327 WARN_LOG_FMT(VIDEO,
328 "Mismatched matrix index configuration between CP and XF stages - "
329 "index A: {:08x}/{:08x}, index B {:08x}/{:08x}.",
330 g_main_cp_state.matrix_index_a.Hex, xfmem.MatrixIndexA.Hex,
331 g_main_cp_state.matrix_index_b.Hex, xfmem.MatrixIndexB.Hex);
332 DolphinAnalytics::Instance().ReportGameQuirk(
333 GameQuirk::MismatchedGPUMatrixIndicesBetweenCPAndXF);
334 }
335
336 if (g_main_cp_state.vtx_attr[vtx_attr_group].g0.PosFormat >= ComponentFormat::InvalidFloat5)
337 {
338 WARN_LOG_FMT(VIDEO, "Invalid position format {} for VAT {} - {:08x} {:08x} {:08x}",
339 g_main_cp_state.vtx_attr[vtx_attr_group].g0.PosFormat, vtx_attr_group,
340 g_main_cp_state.vtx_attr[vtx_attr_group].g0.Hex,
341 g_main_cp_state.vtx_attr[vtx_attr_group].g1.Hex,
342 g_main_cp_state.vtx_attr[vtx_attr_group].g2.Hex);
343 DolphinAnalytics::Instance().ReportGameQuirk(GameQuirk::InvalidPositionComponentFormat);
344 }
345 if (g_main_cp_state.vtx_attr[vtx_attr_group].g0.NormalFormat >= ComponentFormat::InvalidFloat5)
346 {
347 WARN_LOG_FMT(VIDEO, "Invalid normal format {} for VAT {} - {:08x} {:08x} {:08x}",
348 g_main_cp_state.vtx_attr[vtx_attr_group].g0.NormalFormat, vtx_attr_group,
349 g_main_cp_state.vtx_attr[vtx_attr_group].g0.Hex,
350 g_main_cp_state.vtx_attr[vtx_attr_group].g1.Hex,
351 g_main_cp_state.vtx_attr[vtx_attr_group].g2.Hex);
352 DolphinAnalytics::Instance().ReportGameQuirk(GameQuirk::InvalidNormalComponentFormat);
353 }
354 for (size_t i = 0; i < 8; i++)
355 {
356 if (g_main_cp_state.vtx_attr[vtx_attr_group].GetTexFormat(i) >= ComponentFormat::InvalidFloat5)
357 {
358 WARN_LOG_FMT(VIDEO,
359 "Invalid texture coordinate {} format {} for VAT {} - {:08x} {:08x} {:08x}", i,
360 g_main_cp_state.vtx_attr[vtx_attr_group].GetTexFormat(i), vtx_attr_group,
361 g_main_cp_state.vtx_attr[vtx_attr_group].g0.Hex,
362 g_main_cp_state.vtx_attr[vtx_attr_group].g1.Hex,
363 g_main_cp_state.vtx_attr[vtx_attr_group].g2.Hex);
364 DolphinAnalytics::Instance().ReportGameQuirk(
365 GameQuirk::InvalidTextureCoordinateComponentFormat);
366 }
367 }
368 for (size_t i = 0; i < 2; i++)
369 {
370 if (g_main_cp_state.vtx_attr[vtx_attr_group].GetColorFormat(i) > ColorFormat::RGBA8888)
371 {
372 WARN_LOG_FMT(VIDEO, "Invalid color {} format {} for VAT {} - {:08x} {:08x} {:08x}", i,
373 g_main_cp_state.vtx_attr[vtx_attr_group].GetColorFormat(i), vtx_attr_group,
374 g_main_cp_state.vtx_attr[vtx_attr_group].g0.Hex,
375 g_main_cp_state.vtx_attr[vtx_attr_group].g1.Hex,
376 g_main_cp_state.vtx_attr[vtx_attr_group].g2.Hex);
377 DolphinAnalytics::Instance().ReportGameQuirk(GameQuirk::InvalidColorComponentFormat);
378 }
379 }
380 }
381
382 static bool CanSplit(OpcodeDecoder::Primitive primitive)
383 {
384 // Splitting is currently only implemented for the easy cases (individual lines/points/triangles)
385 switch (primitive)
386 {
387 case OpcodeDecoder::Primitive::GX_DRAW_QUADS:
388 case OpcodeDecoder::Primitive::GX_DRAW_QUADS_2:
389 case OpcodeDecoder::Primitive::GX_DRAW_TRIANGLES:
390 case OpcodeDecoder::Primitive::GX_DRAW_LINES:
391 case OpcodeDecoder::Primitive::GX_DRAW_POINTS:
392 return true;
393 default:
394 return false;
395 }
396 }
397
398 template <bool IsPreprocess>
399 int RunVertices(int vtx_attr_group, OpcodeDecoder::Primitive primitive, int count, const u8* src)
400 {
401 if (count == 0) [[unlikely]]
402 return 0;
403 ASSERT(count > 0);
404
405 VertexLoaderBase* loader = RefreshLoader<IsPreprocess>(vtx_attr_group);
406
407 int size = count * loader->m_vertex_size;
408
409 if constexpr (!IsPreprocess)
410 {
411 // Doing early return for the opposite case would be cleaner
412 // but triggers a false unreachable code warning in MSVC debug builds.
413
414 if (g_needs_cp_xf_consistency_check) [[unlikely]]
415 {
416 CheckCPConfiguration(vtx_attr_group);
417 g_needs_cp_xf_consistency_check = false;
418 }
419
420 // If the native vertex format changed, force a flush.
421 if (loader->m_native_vertex_format != s_current_vtx_fmt ||
422 loader->m_native_components != g_current_components) [[unlikely]]
423 {
424 g_vertex_manager->Flush();
425
426 s_current_vtx_fmt = loader->m_native_vertex_format;
427 g_current_components = loader->m_native_components;
428 auto& system = Core::System::GetInstance();
429 auto& vertex_shader_manager = system.GetVertexShaderManager();
430 vertex_shader_manager.SetVertexFormat(loader->m_native_components,
431 loader->m_native_vertex_format->GetVertexDeclaration());
432 }
433
434 // CPUCull's performance increase comes from encoding fewer GPU commands, not sending less data
435 // Therefore it's only useful to check if culling could remove a flush
436 bool can_cpu_cull = g_ActiveConfig.bCPUCull &&
437 primitive < OpcodeDecoder::Primitive::GX_DRAW_LINES &&
438 !g_vertex_manager->HasSendableVertices();
439
440 // if cull mode is CULL_ALL, tell VertexManager to skip triangles and quads.
441 // They still need to go through vertex loading, because we need to calculate a zfreeze
442 // reference slope.
443 const bool cullall = (bpmem.genMode.cull_mode == CullMode::All &&
444 primitive < OpcodeDecoder::Primitive::GX_DRAW_LINES);
445
446 const int stride = loader->m_native_vtx_decl.stride;
447 do
448 {
449 const int max_vertices = 16380; // Max is 16383, but 16380 is divisible by both 4 and 3
450 const int run = CanSplit(primitive) && count > max_vertices ? max_vertices : count;
451 count -= run;
452 DataReader dst = g_vertex_manager->PrepareForAdditionalData(primitive, run, stride,
453 cullall || can_cpu_cull);
454
455 const int num_loaded = loader->RunVertices(src, dst.GetPointer(), run);
456 src += loader->m_vertex_size * max_vertices;
457
458 if (can_cpu_cull && !cullall)
459 {
460 const bool all_culled =
461 g_vertex_manager->AreAllVerticesCulled(loader, primitive, dst.GetPointer(), num_loaded);
462 if (!all_culled)
463 {
464 DataReader new_dst = g_vertex_manager->DisableCullAll(stride);
465 memmove(new_dst.GetPointer(), dst.GetPointer(), num_loaded * stride);
466 can_cpu_cull = false;
467 }
468 }
469
470 g_vertex_manager->AddIndices(primitive, num_loaded);
471 g_vertex_manager->FlushData(num_loaded, stride);
472
473 ADDSTAT(g_stats.this_frame.num_prims, num_loaded);
474 } while (count);
475
476 INCSTAT(g_stats.this_frame.num_primitive_joins);
477 }
478 return size;
479 }
480
481 template int RunVertices<false>(int vtx_attr_group, OpcodeDecoder::Primitive primitive, int count,
482 const u8* src);
483 template int RunVertices<true>(int vtx_attr_group, OpcodeDecoder::Primitive primitive, int count,
484 const u8* src);
485
486 NativeVertexFormat* GetCurrentVertexFormat()
487 {
488 return s_current_vtx_fmt;
489 }
490
491 } // namespace VertexLoaderManager