video_core: Refactor GPU interface (#7272)

* video_core: Refactor GPU interface

* citra_qt: Better debug widget lifetime
This commit is contained in:
GPUCode 2023-12-28 12:46:57 +02:00 committed by GitHub
parent 602f4f60d8
commit 2bb7f89c30
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
167 changed files with 4172 additions and 4866 deletions

View file

@ -1,8 +1,6 @@
add_subdirectory(host_shaders)
add_library(video_core STATIC
command_processor.cpp
command_processor.h
custom_textures/custom_format.cpp
custom_textures/custom_format.h
custom_textures/custom_tex_manager.cpp
@ -11,29 +9,41 @@ add_library(video_core STATIC
custom_textures/material.h
debug_utils/debug_utils.cpp
debug_utils/debug_utils.h
geometry_pipeline.cpp
geometry_pipeline.h
gpu.cpp
gpu.h
gpu_debugger.h
pica.cpp
pica.h
pica_state.h
pica_types.h
precompiled_headers.h
primitive_assembly.cpp
primitive_assembly.h
rasterizer_accelerated.cpp
rasterizer_accelerated.h
rasterizer_interface.h
regs.cpp
regs.h
regs_framebuffer.h
regs_lighting.h
regs_pipeline.h
regs_rasterizer.h
regs_shader.h
regs_texturing.h
renderer_base.cpp
renderer_base.h
pica/geometry_pipeline.cpp
pica/geometry_pipeline.h
pica/pica_core.cpp
pica/pica_core.h
pica/output_vertex.cpp
pica/output_vertex.h
pica/primitive_assembly.cpp
pica/primitive_assembly.h
pica/regs_external.h
pica/regs_framebuffer.h
pica/regs_internal.cpp
pica/regs_internal.h
pica/regs_lcd.h
pica/regs_lighting.h
pica/regs_pipeline.h
pica/regs_rasterizer.h
pica/regs_shader.h
pica/regs_texturing.h
pica/shader_setup.cpp
pica/shader_setup.h
pica/shader_unit.cpp
pica/shader_unit.h
pica/packed_attribute.h
pica/vertex_loader.cpp
pica/vertex_loader.h
rasterizer_cache/framebuffer_base.h
rasterizer_cache/pixel_format.cpp
rasterizer_cache/pixel_format.h
@ -84,6 +94,8 @@ add_library(video_core STATIC
renderer_opengl/renderer_opengl.h
renderer_software/renderer_software.cpp
renderer_software/renderer_software.h
renderer_software/sw_blitter.cpp
renderer_software/sw_blitter.h
renderer_software/sw_clipper.cpp
renderer_software/sw_clipper.h
renderer_software/sw_framebuffer.cpp
@ -167,8 +179,6 @@ add_library(video_core STATIC
texture/texture_decode.cpp
texture/texture_decode.h
utils.h
vertex_loader.cpp
vertex_loader.h
video_core.cpp
video_core.h
)

View file

@ -1,677 +0,0 @@
// Copyright 2014 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#include <array>
#include <cstddef>
#include <cstring>
#include <memory>
#include <utility>
#include "common/assert.h"
#include "common/logging/log.h"
#include "common/microprofile.h"
#include "common/vector_math.h"
#include "core/hle/service/gsp/gsp.h"
#include "core/hw/gpu.h"
#include "core/memory.h"
#include "core/tracer/recorder.h"
#include "video_core/command_processor.h"
#include "video_core/debug_utils/debug_utils.h"
#include "video_core/pica_state.h"
#include "video_core/pica_types.h"
#include "video_core/primitive_assembly.h"
#include "video_core/rasterizer_interface.h"
#include "video_core/regs.h"
#include "video_core/regs_pipeline.h"
#include "video_core/regs_texturing.h"
#include "video_core/renderer_base.h"
#include "video_core/shader/shader.h"
#include "video_core/vertex_loader.h"
#include "video_core/video_core.h"
namespace Pica::CommandProcessor {
// Expand a 4-bit mask to 4-byte mask, e.g. 0b0101 -> 0x00FF00FF
constexpr std::array<u32, 16> expand_bits_to_bytes{
0x00000000, 0x000000ff, 0x0000ff00, 0x0000ffff, 0x00ff0000, 0x00ff00ff, 0x00ffff00, 0x00ffffff,
0xff000000, 0xff0000ff, 0xff00ff00, 0xff00ffff, 0xffff0000, 0xffff00ff, 0xffffff00, 0xffffffff,
};
MICROPROFILE_DEFINE(GPU_Drawing, "GPU", "Drawing", MP_RGB(50, 50, 240));
static const char* GetShaderSetupTypeName(Shader::ShaderSetup& setup) {
if (&setup == &g_state.vs) {
return "vertex shader";
}
if (&setup == &g_state.gs) {
return "geometry shader";
}
return "unknown shader";
}
static void WriteUniformBoolReg(Shader::ShaderSetup& setup, u32 value) {
for (unsigned i = 0; i < setup.uniforms.b.size(); ++i)
setup.uniforms.b[i] = (value & (1 << i)) != 0;
}
static void WriteUniformIntReg(Shader::ShaderSetup& setup, unsigned index,
const Common::Vec4<u8>& values) {
ASSERT(index < setup.uniforms.i.size());
setup.uniforms.i[index] = values;
LOG_TRACE(HW_GPU, "Set {} integer uniform {} to {:02x} {:02x} {:02x} {:02x}",
GetShaderSetupTypeName(setup), index, values.x, values.y, values.z, values.w);
}
static void WriteUniformFloatReg(ShaderRegs& config, Shader::ShaderSetup& setup,
int& float_regs_counter, std::array<u32, 4>& uniform_write_buffer,
u32 value) {
auto& uniform_setup = config.uniform_setup;
// TODO: Does actual hardware indeed keep an intermediate buffer or does
// it directly write the values?
uniform_write_buffer[float_regs_counter++] = value;
// Uniforms are written in a packed format such that four float24 values are encoded in
// three 32-bit numbers. We write to internal memory once a full such vector is
// written.
if ((float_regs_counter >= 4 && uniform_setup.IsFloat32()) ||
(float_regs_counter >= 3 && !uniform_setup.IsFloat32())) {
float_regs_counter = 0;
if (uniform_setup.index >= setup.uniforms.f.size()) {
LOG_ERROR(HW_GPU, "Invalid {} float uniform index {}", GetShaderSetupTypeName(setup),
(int)uniform_setup.index);
} else {
auto& uniform = setup.uniforms.f[uniform_setup.index];
// NOTE: The destination component order indeed is "backwards"
if (uniform_setup.IsFloat32()) {
for (auto i : {0, 1, 2, 3}) {
float buffer_value;
std::memcpy(&buffer_value, &uniform_write_buffer[i], sizeof(float));
uniform[3 - i] = f24::FromFloat32(buffer_value);
}
} else {
// TODO: Untested
uniform.w = f24::FromRaw(uniform_write_buffer[0] >> 8);
uniform.z = f24::FromRaw(((uniform_write_buffer[0] & 0xFF) << 16) |
((uniform_write_buffer[1] >> 16) & 0xFFFF));
uniform.y = f24::FromRaw(((uniform_write_buffer[1] & 0xFFFF) << 8) |
((uniform_write_buffer[2] >> 24) & 0xFF));
uniform.x = f24::FromRaw(uniform_write_buffer[2] & 0xFFFFFF);
}
LOG_TRACE(HW_GPU, "Set {} float uniform {:x} to ({} {} {} {})",
GetShaderSetupTypeName(setup), (int)uniform_setup.index,
uniform.x.ToFloat32(), uniform.y.ToFloat32(), uniform.z.ToFloat32(),
uniform.w.ToFloat32());
// TODO: Verify that this actually modifies the register!
uniform_setup.index.Assign(uniform_setup.index + 1);
}
}
}
static void WritePicaReg(u32 id, u32 value, u32 mask) {
auto& regs = g_state.regs;
if (id >= Regs::NUM_REGS) {
LOG_ERROR(
HW_GPU,
"Commandlist tried to write to invalid register 0x{:03X} (value: {:08X}, mask: {:X})",
id, value, mask);
return;
}
// TODO: Figure out how register masking acts on e.g. vs.uniform_setup.set_value
u32 old_value = regs.reg_array[id];
const u32 write_mask = expand_bits_to_bytes[mask];
regs.reg_array[id] = (old_value & ~write_mask) | (value & write_mask);
// Double check for is_pica_tracing to avoid call overhead
if (DebugUtils::IsPicaTracing()) {
DebugUtils::OnPicaRegWrite({(u16)id, (u16)mask, regs.reg_array[id]});
}
if (g_debug_context)
g_debug_context->OnEvent(DebugContext::Event::PicaCommandLoaded,
reinterpret_cast<void*>(&id));
switch (id) {
// Trigger IRQ
case PICA_REG_INDEX(trigger_irq):
Service::GSP::SignalInterrupt(Service::GSP::InterruptId::P3D);
break;
case PICA_REG_INDEX(pipeline.triangle_topology):
g_state.primitive_assembler.Reconfigure(regs.pipeline.triangle_topology);
break;
case PICA_REG_INDEX(pipeline.restart_primitive):
g_state.primitive_assembler.Reset();
break;
case PICA_REG_INDEX(pipeline.vs_default_attributes_setup.index):
g_state.immediate.current_attribute = 0;
g_state.immediate.reset_geometry_pipeline = true;
g_state.default_attr_counter = 0;
break;
// Load default vertex input attributes
case PICA_REG_INDEX(pipeline.vs_default_attributes_setup.set_value[0]):
case PICA_REG_INDEX(pipeline.vs_default_attributes_setup.set_value[1]):
case PICA_REG_INDEX(pipeline.vs_default_attributes_setup.set_value[2]): {
// TODO: Does actual hardware indeed keep an intermediate buffer or does
// it directly write the values?
g_state.default_attr_write_buffer[g_state.default_attr_counter++] = value;
// Default attributes are written in a packed format such that four float24 values are
// encoded in
// three 32-bit numbers. We write to internal memory once a full such vector is
// written.
if (g_state.default_attr_counter >= 3) {
g_state.default_attr_counter = 0;
auto& setup = regs.pipeline.vs_default_attributes_setup;
if (setup.index >= 16) {
LOG_ERROR(HW_GPU, "Invalid VS default attribute index {}", (int)setup.index);
break;
}
Common::Vec4<f24> attribute;
// NOTE: The destination component order indeed is "backwards"
attribute.w = f24::FromRaw(g_state.default_attr_write_buffer[0] >> 8);
attribute.z = f24::FromRaw(((g_state.default_attr_write_buffer[0] & 0xFF) << 16) |
((g_state.default_attr_write_buffer[1] >> 16) & 0xFFFF));
attribute.y = f24::FromRaw(((g_state.default_attr_write_buffer[1] & 0xFFFF) << 8) |
((g_state.default_attr_write_buffer[2] >> 24) & 0xFF));
attribute.x = f24::FromRaw(g_state.default_attr_write_buffer[2] & 0xFFFFFF);
LOG_TRACE(HW_GPU, "Set default VS attribute {:x} to ({} {} {} {})", (int)setup.index,
attribute.x.ToFloat32(), attribute.y.ToFloat32(), attribute.z.ToFloat32(),
attribute.w.ToFloat32());
// TODO: Verify that this actually modifies the register!
if (setup.index < 15) {
g_state.input_default_attributes.attr[setup.index] = attribute;
setup.index++;
} else {
// Put each attribute into an immediate input buffer. When all specified immediate
// attributes are present, the Vertex Shader is invoked and everything is sent to
// the primitive assembler.
auto& immediate_input = g_state.immediate.input_vertex;
auto& immediate_attribute_id = g_state.immediate.current_attribute;
immediate_input.attr[immediate_attribute_id] = attribute;
if (immediate_attribute_id < regs.pipeline.max_input_attrib_index) {
immediate_attribute_id += 1;
} else {
MICROPROFILE_SCOPE(GPU_Drawing);
immediate_attribute_id = 0;
Shader::OutputVertex::ValidateSemantics(regs.rasterizer);
auto* shader_engine = Shader::GetEngine();
shader_engine->SetupBatch(g_state.vs, regs.vs.main_offset);
// Send to vertex shader
if (g_debug_context)
g_debug_context->OnEvent(DebugContext::Event::VertexShaderInvocation,
static_cast<void*>(&immediate_input));
Shader::UnitState shader_unit;
Shader::AttributeBuffer output{};
shader_unit.LoadInput(regs.vs, immediate_input);
shader_engine->Run(g_state.vs, shader_unit);
shader_unit.WriteOutput(regs.vs, output);
// Send to geometry pipeline
if (g_state.immediate.reset_geometry_pipeline) {
g_state.geometry_pipeline.Reconfigure();
g_state.immediate.reset_geometry_pipeline = false;
}
ASSERT(!g_state.geometry_pipeline.NeedIndexInput());
g_state.geometry_pipeline.Setup(shader_engine);
g_state.geometry_pipeline.SubmitVertex(output);
// TODO: If drawing after every immediate mode triangle kills performance,
// change it to flush triangles whenever a drawing config register changes
// See: https://github.com/citra-emu/citra/pull/2866#issuecomment-327011550
VideoCore::g_renderer->Rasterizer()->DrawTriangles();
if (g_debug_context) {
g_debug_context->OnEvent(DebugContext::Event::FinishedPrimitiveBatch,
nullptr);
}
}
}
}
break;
}
case PICA_REG_INDEX(pipeline.gpu_mode):
// This register likely just enables vertex processing and doesn't need any special handling
break;
case PICA_REG_INDEX(pipeline.command_buffer.trigger[0]):
case PICA_REG_INDEX(pipeline.command_buffer.trigger[1]): {
unsigned index =
static_cast<unsigned>(id - PICA_REG_INDEX(pipeline.command_buffer.trigger[0]));
u32* head_ptr = (u32*)VideoCore::g_memory->GetPhysicalPointer(
regs.pipeline.command_buffer.GetPhysicalAddress(index));
g_state.cmd_list.head_ptr = g_state.cmd_list.current_ptr = head_ptr;
g_state.cmd_list.length = regs.pipeline.command_buffer.GetSize(index) / sizeof(u32);
break;
}
// It seems like these trigger vertex rendering
case PICA_REG_INDEX(pipeline.trigger_draw):
case PICA_REG_INDEX(pipeline.trigger_draw_indexed): {
MICROPROFILE_SCOPE(GPU_Drawing);
#if PICA_LOG_TEV
DebugUtils::DumpTevStageConfig(regs.GetTevStages());
#endif
if (g_debug_context)
g_debug_context->OnEvent(DebugContext::Event::IncomingPrimitiveBatch, nullptr);
PrimitiveAssembler<Shader::OutputVertex>& primitive_assembler = g_state.primitive_assembler;
bool accelerate_draw = VideoCore::g_hw_shader_enabled && primitive_assembler.IsEmpty();
if (regs.pipeline.use_gs == PipelineRegs::UseGS::No) {
auto topology = primitive_assembler.GetTopology();
if (topology == PipelineRegs::TriangleTopology::Shader ||
topology == PipelineRegs::TriangleTopology::List) {
accelerate_draw = accelerate_draw && (regs.pipeline.num_vertices % 3) == 0;
}
// TODO (wwylele): for Strip/Fan topology, if the primitive assember is not restarted
// after this draw call, the buffered vertex from this draw should "leak" to the next
// draw, in which case we should buffer the vertex into the software primitive assember,
// or disable accelerate draw completely. However, there is not game found yet that does
// this, so this is left unimplemented for now. Revisit this when an issue is found in
// games.
} else {
accelerate_draw = false;
}
bool is_indexed = (id == PICA_REG_INDEX(pipeline.trigger_draw_indexed));
if (accelerate_draw &&
VideoCore::g_renderer->Rasterizer()->AccelerateDrawBatch(is_indexed)) {
if (g_debug_context) {
g_debug_context->OnEvent(DebugContext::Event::FinishedPrimitiveBatch, nullptr);
}
break;
}
// Processes information about internal vertex attributes to figure out how a vertex is
// loaded.
// Later, these can be compiled and cached.
const u32 base_address = regs.pipeline.vertex_attributes.GetPhysicalBaseAddress();
VertexLoader loader(regs.pipeline);
Shader::OutputVertex::ValidateSemantics(regs.rasterizer);
// Load vertices
const auto& index_info = regs.pipeline.index_array;
const u8* index_address_8 =
VideoCore::g_memory->GetPhysicalPointer(base_address + index_info.offset);
const u16* index_address_16 = reinterpret_cast<const u16*>(index_address_8);
bool index_u16 = index_info.format != 0;
if (g_debug_context && g_debug_context->recorder) {
for (int i = 0; i < 3; ++i) {
const auto texture = regs.texturing.GetTextures()[i];
if (!texture.enabled)
continue;
u8* texture_data =
VideoCore::g_memory->GetPhysicalPointer(texture.config.GetPhysicalAddress());
g_debug_context->recorder->MemoryAccessed(
texture_data,
Pica::TexturingRegs::NibblesPerPixel(texture.format) * texture.config.width /
2 * texture.config.height,
texture.config.GetPhysicalAddress());
}
}
DebugUtils::MemoryAccessTracker memory_accesses;
// Simple circular-replacement vertex cache
// The size has been tuned for optimal balance between hit-rate and the cost of lookup
const std::size_t VERTEX_CACHE_SIZE = 32;
std::array<bool, VERTEX_CACHE_SIZE> vertex_cache_valid{};
std::array<u16, VERTEX_CACHE_SIZE> vertex_cache_ids;
std::array<Shader::AttributeBuffer, VERTEX_CACHE_SIZE> vertex_cache;
Shader::AttributeBuffer vs_output;
unsigned int vertex_cache_pos = 0;
auto* shader_engine = Shader::GetEngine();
Shader::UnitState shader_unit;
shader_engine->SetupBatch(g_state.vs, regs.vs.main_offset);
g_state.geometry_pipeline.Reconfigure();
g_state.geometry_pipeline.Setup(shader_engine);
if (g_state.geometry_pipeline.NeedIndexInput())
ASSERT(is_indexed);
for (unsigned int index = 0; index < regs.pipeline.num_vertices; ++index) {
// Indexed rendering doesn't use the start offset
unsigned int vertex =
is_indexed ? (index_u16 ? index_address_16[index] : index_address_8[index])
: (index + regs.pipeline.vertex_offset);
bool vertex_cache_hit = false;
if (is_indexed) {
if (g_state.geometry_pipeline.NeedIndexInput()) {
g_state.geometry_pipeline.SubmitIndex(vertex);
continue;
}
if (g_debug_context && Pica::g_debug_context->recorder) {
int size = index_u16 ? 2 : 1;
memory_accesses.AddAccess(base_address + index_info.offset + size * index,
size);
}
for (unsigned int i = 0; i < VERTEX_CACHE_SIZE; ++i) {
if (vertex_cache_valid[i] && vertex == vertex_cache_ids[i]) {
vs_output = vertex_cache[i];
vertex_cache_hit = true;
break;
}
}
}
if (!vertex_cache_hit) {
// Initialize data for the current vertex
Shader::AttributeBuffer input;
loader.LoadVertex(base_address, index, vertex, input, memory_accesses);
// Send to vertex shader
if (g_debug_context)
g_debug_context->OnEvent(DebugContext::Event::VertexShaderInvocation,
(void*)&input);
shader_unit.LoadInput(regs.vs, input);
shader_engine->Run(g_state.vs, shader_unit);
shader_unit.WriteOutput(regs.vs, vs_output);
if (is_indexed) {
vertex_cache[vertex_cache_pos] = vs_output;
vertex_cache_valid[vertex_cache_pos] = true;
vertex_cache_ids[vertex_cache_pos] = vertex;
vertex_cache_pos = (vertex_cache_pos + 1) % VERTEX_CACHE_SIZE;
}
}
// Send to geometry pipeline
g_state.geometry_pipeline.SubmitVertex(vs_output);
}
for (auto& range : memory_accesses.ranges) {
g_debug_context->recorder->MemoryAccessed(
VideoCore::g_memory->GetPhysicalPointer(range.first), range.second, range.first);
}
VideoCore::g_renderer->Rasterizer()->DrawTriangles();
if (g_debug_context) {
g_debug_context->OnEvent(DebugContext::Event::FinishedPrimitiveBatch, nullptr);
}
break;
}
case PICA_REG_INDEX(gs.bool_uniforms):
WriteUniformBoolReg(g_state.gs, g_state.regs.gs.bool_uniforms.Value());
break;
case PICA_REG_INDEX(gs.int_uniforms[0]):
case PICA_REG_INDEX(gs.int_uniforms[1]):
case PICA_REG_INDEX(gs.int_uniforms[2]):
case PICA_REG_INDEX(gs.int_uniforms[3]): {
unsigned index = (id - PICA_REG_INDEX(gs.int_uniforms[0]));
auto values = regs.gs.int_uniforms[index];
WriteUniformIntReg(g_state.gs, index,
Common::Vec4<u8>(values.x, values.y, values.z, values.w));
break;
}
case PICA_REG_INDEX(gs.uniform_setup.set_value[0]):
case PICA_REG_INDEX(gs.uniform_setup.set_value[1]):
case PICA_REG_INDEX(gs.uniform_setup.set_value[2]):
case PICA_REG_INDEX(gs.uniform_setup.set_value[3]):
case PICA_REG_INDEX(gs.uniform_setup.set_value[4]):
case PICA_REG_INDEX(gs.uniform_setup.set_value[5]):
case PICA_REG_INDEX(gs.uniform_setup.set_value[6]):
case PICA_REG_INDEX(gs.uniform_setup.set_value[7]): {
WriteUniformFloatReg(g_state.regs.gs, g_state.gs, g_state.gs_float_regs_counter,
g_state.gs_uniform_write_buffer, value);
break;
}
case PICA_REG_INDEX(gs.program.set_word[0]):
case PICA_REG_INDEX(gs.program.set_word[1]):
case PICA_REG_INDEX(gs.program.set_word[2]):
case PICA_REG_INDEX(gs.program.set_word[3]):
case PICA_REG_INDEX(gs.program.set_word[4]):
case PICA_REG_INDEX(gs.program.set_word[5]):
case PICA_REG_INDEX(gs.program.set_word[6]):
case PICA_REG_INDEX(gs.program.set_word[7]): {
u32& offset = g_state.regs.gs.program.offset;
if (offset >= 4096) {
LOG_ERROR(HW_GPU, "Invalid GS program offset {}", offset);
} else {
g_state.gs.program_code[offset] = value;
g_state.gs.MarkProgramCodeDirty();
offset++;
}
break;
}
case PICA_REG_INDEX(gs.swizzle_patterns.set_word[0]):
case PICA_REG_INDEX(gs.swizzle_patterns.set_word[1]):
case PICA_REG_INDEX(gs.swizzle_patterns.set_word[2]):
case PICA_REG_INDEX(gs.swizzle_patterns.set_word[3]):
case PICA_REG_INDEX(gs.swizzle_patterns.set_word[4]):
case PICA_REG_INDEX(gs.swizzle_patterns.set_word[5]):
case PICA_REG_INDEX(gs.swizzle_patterns.set_word[6]):
case PICA_REG_INDEX(gs.swizzle_patterns.set_word[7]): {
u32& offset = g_state.regs.gs.swizzle_patterns.offset;
if (offset >= g_state.gs.swizzle_data.size()) {
LOG_ERROR(HW_GPU, "Invalid GS swizzle pattern offset {}", offset);
} else {
g_state.gs.swizzle_data[offset] = value;
g_state.gs.MarkSwizzleDataDirty();
offset++;
}
break;
}
case PICA_REG_INDEX(vs.bool_uniforms):
// TODO (wwylele): does regs.pipeline.gs_unit_exclusive_configuration affect this?
WriteUniformBoolReg(g_state.vs, g_state.regs.vs.bool_uniforms.Value());
break;
case PICA_REG_INDEX(vs.int_uniforms[0]):
case PICA_REG_INDEX(vs.int_uniforms[1]):
case PICA_REG_INDEX(vs.int_uniforms[2]):
case PICA_REG_INDEX(vs.int_uniforms[3]): {
// TODO (wwylele): does regs.pipeline.gs_unit_exclusive_configuration affect this?
unsigned index = (id - PICA_REG_INDEX(vs.int_uniforms[0]));
auto values = regs.vs.int_uniforms[index];
WriteUniformIntReg(g_state.vs, index,
Common::Vec4<u8>(values.x, values.y, values.z, values.w));
break;
}
case PICA_REG_INDEX(vs.uniform_setup.set_value[0]):
case PICA_REG_INDEX(vs.uniform_setup.set_value[1]):
case PICA_REG_INDEX(vs.uniform_setup.set_value[2]):
case PICA_REG_INDEX(vs.uniform_setup.set_value[3]):
case PICA_REG_INDEX(vs.uniform_setup.set_value[4]):
case PICA_REG_INDEX(vs.uniform_setup.set_value[5]):
case PICA_REG_INDEX(vs.uniform_setup.set_value[6]):
case PICA_REG_INDEX(vs.uniform_setup.set_value[7]): {
// TODO (wwylele): does regs.pipeline.gs_unit_exclusive_configuration affect this?
WriteUniformFloatReg(g_state.regs.vs, g_state.vs, g_state.vs_float_regs_counter,
g_state.vs_uniform_write_buffer, value);
break;
}
case PICA_REG_INDEX(vs.program.set_word[0]):
case PICA_REG_INDEX(vs.program.set_word[1]):
case PICA_REG_INDEX(vs.program.set_word[2]):
case PICA_REG_INDEX(vs.program.set_word[3]):
case PICA_REG_INDEX(vs.program.set_word[4]):
case PICA_REG_INDEX(vs.program.set_word[5]):
case PICA_REG_INDEX(vs.program.set_word[6]):
case PICA_REG_INDEX(vs.program.set_word[7]): {
u32& offset = g_state.regs.vs.program.offset;
if (offset >= 512) {
LOG_ERROR(HW_GPU, "Invalid VS program offset {}", offset);
} else {
g_state.vs.program_code[offset] = value;
g_state.vs.MarkProgramCodeDirty();
if (!g_state.regs.pipeline.gs_unit_exclusive_configuration) {
g_state.gs.program_code[offset] = value;
g_state.gs.MarkProgramCodeDirty();
}
offset++;
}
break;
}
case PICA_REG_INDEX(vs.swizzle_patterns.set_word[0]):
case PICA_REG_INDEX(vs.swizzle_patterns.set_word[1]):
case PICA_REG_INDEX(vs.swizzle_patterns.set_word[2]):
case PICA_REG_INDEX(vs.swizzle_patterns.set_word[3]):
case PICA_REG_INDEX(vs.swizzle_patterns.set_word[4]):
case PICA_REG_INDEX(vs.swizzle_patterns.set_word[5]):
case PICA_REG_INDEX(vs.swizzle_patterns.set_word[6]):
case PICA_REG_INDEX(vs.swizzle_patterns.set_word[7]): {
u32& offset = g_state.regs.vs.swizzle_patterns.offset;
if (offset >= g_state.vs.swizzle_data.size()) {
LOG_ERROR(HW_GPU, "Invalid VS swizzle pattern offset {}", offset);
} else {
g_state.vs.swizzle_data[offset] = value;
g_state.vs.MarkSwizzleDataDirty();
if (!g_state.regs.pipeline.gs_unit_exclusive_configuration) {
g_state.gs.swizzle_data[offset] = value;
g_state.gs.MarkSwizzleDataDirty();
}
offset++;
}
break;
}
case PICA_REG_INDEX(lighting.lut_data[0]):
case PICA_REG_INDEX(lighting.lut_data[1]):
case PICA_REG_INDEX(lighting.lut_data[2]):
case PICA_REG_INDEX(lighting.lut_data[3]):
case PICA_REG_INDEX(lighting.lut_data[4]):
case PICA_REG_INDEX(lighting.lut_data[5]):
case PICA_REG_INDEX(lighting.lut_data[6]):
case PICA_REG_INDEX(lighting.lut_data[7]): {
auto& lut_config = regs.lighting.lut_config;
ASSERT_MSG(lut_config.index < 256, "lut_config.index exceeded maximum value of 255!");
g_state.lighting.luts[lut_config.type][lut_config.index].raw = value;
lut_config.index.Assign(lut_config.index + 1);
break;
}
case PICA_REG_INDEX(texturing.fog_lut_data[0]):
case PICA_REG_INDEX(texturing.fog_lut_data[1]):
case PICA_REG_INDEX(texturing.fog_lut_data[2]):
case PICA_REG_INDEX(texturing.fog_lut_data[3]):
case PICA_REG_INDEX(texturing.fog_lut_data[4]):
case PICA_REG_INDEX(texturing.fog_lut_data[5]):
case PICA_REG_INDEX(texturing.fog_lut_data[6]):
case PICA_REG_INDEX(texturing.fog_lut_data[7]): {
g_state.fog.lut[regs.texturing.fog_lut_offset % 128].raw = value;
regs.texturing.fog_lut_offset.Assign(regs.texturing.fog_lut_offset + 1);
break;
}
case PICA_REG_INDEX(texturing.proctex_lut_data[0]):
case PICA_REG_INDEX(texturing.proctex_lut_data[1]):
case PICA_REG_INDEX(texturing.proctex_lut_data[2]):
case PICA_REG_INDEX(texturing.proctex_lut_data[3]):
case PICA_REG_INDEX(texturing.proctex_lut_data[4]):
case PICA_REG_INDEX(texturing.proctex_lut_data[5]):
case PICA_REG_INDEX(texturing.proctex_lut_data[6]):
case PICA_REG_INDEX(texturing.proctex_lut_data[7]): {
auto& index = regs.texturing.proctex_lut_config.index;
auto& pt = g_state.proctex;
switch (regs.texturing.proctex_lut_config.ref_table.Value()) {
case TexturingRegs::ProcTexLutTable::Noise:
pt.noise_table[index % pt.noise_table.size()].raw = value;
break;
case TexturingRegs::ProcTexLutTable::ColorMap:
pt.color_map_table[index % pt.color_map_table.size()].raw = value;
break;
case TexturingRegs::ProcTexLutTable::AlphaMap:
pt.alpha_map_table[index % pt.alpha_map_table.size()].raw = value;
break;
case TexturingRegs::ProcTexLutTable::Color:
pt.color_table[index % pt.color_table.size()].raw = value;
break;
case TexturingRegs::ProcTexLutTable::ColorDiff:
pt.color_diff_table[index % pt.color_diff_table.size()].raw = value;
break;
}
index.Assign(index + 1);
break;
}
default:
break;
}
VideoCore::g_renderer->Rasterizer()->NotifyPicaRegisterChanged(id);
if (g_debug_context)
g_debug_context->OnEvent(DebugContext::Event::PicaCommandProcessed,
reinterpret_cast<void*>(&id));
}
void ProcessCommandList(PAddr list, u32 size) {
u32* buffer = (u32*)VideoCore::g_memory->GetPhysicalPointer(list);
if (Pica::g_debug_context && Pica::g_debug_context->recorder) {
Pica::g_debug_context->recorder->MemoryAccessed((u8*)buffer, size, list);
}
g_state.cmd_list.addr = list;
g_state.cmd_list.head_ptr = g_state.cmd_list.current_ptr = buffer;
g_state.cmd_list.length = size / sizeof(u32);
while (g_state.cmd_list.current_ptr < g_state.cmd_list.head_ptr + g_state.cmd_list.length) {
// Align read pointer to 8 bytes
if ((g_state.cmd_list.head_ptr - g_state.cmd_list.current_ptr) % 2 != 0)
++g_state.cmd_list.current_ptr;
u32 value = *g_state.cmd_list.current_ptr++;
const CommandHeader header = {*g_state.cmd_list.current_ptr++};
WritePicaReg(header.cmd_id, value, header.parameter_mask);
for (unsigned i = 0; i < header.extra_data_length; ++i) {
u32 cmd = header.cmd_id + (header.group_commands ? i + 1 : 0);
WritePicaReg(cmd, *g_state.cmd_list.current_ptr++, header.parameter_mask);
}
}
}
} // namespace Pica::CommandProcessor

View file

@ -1,37 +0,0 @@
// Copyright 2014 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#pragma once
#include <type_traits>
#include "common/bit_field.h"
#include "common/common_types.h"
namespace Pica::CommandProcessor {
union CommandHeader {
u32 hex;
BitField<0, 16, u32> cmd_id;
// parameter_mask:
// Mask applied to the input value to make it possible to update
// parts of a register without overwriting its other fields.
// first bit: 0x000000FF
// second bit: 0x0000FF00
// third bit: 0x00FF0000
// fourth bit: 0xFF000000
BitField<16, 4, u32> parameter_mask;
BitField<20, 11, u32> extra_data_length;
BitField<31, 1, u32> group_commands;
};
static_assert(std::is_standard_layout<CommandHeader>::value == true,
"CommandHeader does not use standard layout");
static_assert(sizeof(CommandHeader) == sizeof(u32), "CommandHeader has incorrect size!");
void ProcessCommandList(PAddr list, u32 size);
} // namespace Pica::CommandProcessor

View file

@ -2,38 +2,22 @@
// Licensed under GPLv2
// Refer to the license.txt file included.
#include <algorithm>
#include <condition_variable>
#include <cstdint>
#include <cstring>
#include <fstream>
#include <map>
#include <mutex>
#include <stdexcept>
#include <string>
#include <nihstro/bit_field.h>
#include <nihstro/float24.h>
#include <nihstro/shader_binary.h>
#include "common/assert.h"
#include "common/bit_field.h"
#include "common/color.h"
#include "common/common_types.h"
#include "common/logging/log.h"
#include "common/math_util.h"
#include "common/vector_math.h"
#include "core/core.h"
#include "video_core/debug_utils/debug_utils.h"
#include "video_core/pica_state.h"
#include "video_core/pica_types.h"
#include "video_core/rasterizer_interface.h"
#include "video_core/regs_rasterizer.h"
#include "video_core/regs_shader.h"
#include "video_core/regs_texturing.h"
#include "video_core/gpu.h"
#include "video_core/pica/regs_shader.h"
#include "video_core/pica/shader_setup.h"
#include "video_core/renderer_base.h"
#include "video_core/shader/shader.h"
#include "video_core/texture/texture_decode.h"
#include "video_core/utils.h"
#include "video_core/video_core.h"
using nihstro::DVLBHeader;
using nihstro::DVLEHeader;
@ -41,13 +25,13 @@ using nihstro::DVLPHeader;
namespace Pica {
void DebugContext::DoOnEvent(Event event, void* data) {
void DebugContext::DoOnEvent(Event event, const void* data) {
{
std::unique_lock lock{breakpoint_mutex};
// Commit the rasterizer's caches so framebuffers, render targets, etc. will show on debug
// widgets
VideoCore::g_renderer->Rasterizer()->FlushAll();
Core::System::GetInstance().GPU().Renderer().Rasterizer()->FlushAll();
// TODO: Should stop the CPU thread here once we multithread emulation.
@ -84,8 +68,7 @@ std::shared_ptr<DebugContext> g_debug_context; // TODO: Get rid of this global
namespace DebugUtils {
void DumpShader(const std::string& filename, const ShaderRegs& config,
const Shader::ShaderSetup& setup,
void DumpShader(const std::string& filename, const ShaderRegs& config, const ShaderSetup& setup,
const RasterizerRegs::VSOutputAttributes* output_attributes) {
struct StuffToWrite {
const u8* pointer;
@ -288,13 +271,13 @@ void StartPicaTracing() {
g_is_pica_tracing = true;
}
void OnPicaRegWrite(PicaTrace::Write write) {
void OnPicaRegWrite(u16 cmd_id, u16 mask, u32 value) {
std::lock_guard lock(pica_trace_mutex);
if (!g_is_pica_tracing)
return;
pica_trace->writes.push_back(write);
pica_trace->writes.push_back(PicaTrace::Write{cmd_id, mask, value});
}
std::unique_ptr<PicaTrace> FinishPicaTracing() {
@ -313,153 +296,6 @@ std::unique_ptr<PicaTrace> FinishPicaTracing() {
return ret;
}
static std::string ReplacePattern(const std::string& input, const std::string& pattern,
const std::string& replacement) {
std::size_t start = input.find(pattern);
if (start == std::string::npos)
return input;
std::string ret = input;
ret.replace(start, pattern.length(), replacement);
return ret;
}
static std::string GetTevStageConfigSourceString(
const TexturingRegs::TevStageConfig::Source& source) {
using Source = TexturingRegs::TevStageConfig::Source;
static const std::map<Source, std::string> source_map = {
{Source::PrimaryColor, "PrimaryColor"},
{Source::PrimaryFragmentColor, "PrimaryFragmentColor"},
{Source::SecondaryFragmentColor, "SecondaryFragmentColor"},
{Source::Texture0, "Texture0"},
{Source::Texture1, "Texture1"},
{Source::Texture2, "Texture2"},
{Source::Texture3, "Texture3"},
{Source::PreviousBuffer, "PreviousBuffer"},
{Source::Constant, "Constant"},
{Source::Previous, "Previous"},
};
const auto src_it = source_map.find(source);
if (src_it == source_map.end())
return "Unknown";
return src_it->second;
}
static std::string GetTevStageConfigColorSourceString(
const TexturingRegs::TevStageConfig::Source& source,
const TexturingRegs::TevStageConfig::ColorModifier modifier) {
using ColorModifier = TexturingRegs::TevStageConfig::ColorModifier;
static const std::map<ColorModifier, std::string> color_modifier_map = {
{ColorModifier::SourceColor, "%source.rgb"},
{ColorModifier::OneMinusSourceColor, "(1.0 - %source.rgb)"},
{ColorModifier::SourceAlpha, "%source.aaa"},
{ColorModifier::OneMinusSourceAlpha, "(1.0 - %source.aaa)"},
{ColorModifier::SourceRed, "%source.rrr"},
{ColorModifier::OneMinusSourceRed, "(1.0 - %source.rrr)"},
{ColorModifier::SourceGreen, "%source.ggg"},
{ColorModifier::OneMinusSourceGreen, "(1.0 - %source.ggg)"},
{ColorModifier::SourceBlue, "%source.bbb"},
{ColorModifier::OneMinusSourceBlue, "(1.0 - %source.bbb)"},
};
auto src_str = GetTevStageConfigSourceString(source);
auto modifier_it = color_modifier_map.find(modifier);
std::string modifier_str = "%source.????";
if (modifier_it != color_modifier_map.end())
modifier_str = modifier_it->second;
return ReplacePattern(modifier_str, "%source", src_str);
}
static std::string GetTevStageConfigAlphaSourceString(
const TexturingRegs::TevStageConfig::Source& source,
const TexturingRegs::TevStageConfig::AlphaModifier modifier) {
using AlphaModifier = TexturingRegs::TevStageConfig::AlphaModifier;
static const std::map<AlphaModifier, std::string> alpha_modifier_map = {
{AlphaModifier::SourceAlpha, "%source.a"},
{AlphaModifier::OneMinusSourceAlpha, "(1.0 - %source.a)"},
{AlphaModifier::SourceRed, "%source.r"},
{AlphaModifier::OneMinusSourceRed, "(1.0 - %source.r)"},
{AlphaModifier::SourceGreen, "%source.g"},
{AlphaModifier::OneMinusSourceGreen, "(1.0 - %source.g)"},
{AlphaModifier::SourceBlue, "%source.b"},
{AlphaModifier::OneMinusSourceBlue, "(1.0 - %source.b)"},
};
auto src_str = GetTevStageConfigSourceString(source);
auto modifier_it = alpha_modifier_map.find(modifier);
std::string modifier_str = "%source.????";
if (modifier_it != alpha_modifier_map.end())
modifier_str = modifier_it->second;
return ReplacePattern(modifier_str, "%source", src_str);
}
static std::string GetTevStageConfigOperationString(
const TexturingRegs::TevStageConfig::Operation& operation) {
using Operation = TexturingRegs::TevStageConfig::Operation;
static const std::map<Operation, std::string> combiner_map = {
{Operation::Replace, "%source1"},
{Operation::Modulate, "(%source1 * %source2)"},
{Operation::Add, "(%source1 + %source2)"},
{Operation::AddSigned, "(%source1 + %source2) - 0.5"},
{Operation::Lerp, "lerp(%source1, %source2, %source3)"},
{Operation::Subtract, "(%source1 - %source2)"},
{Operation::Dot3_RGB, "dot(%source1, %source2)"},
{Operation::MultiplyThenAdd, "((%source1 * %source2) + %source3)"},
{Operation::AddThenMultiply, "((%source1 + %source2) * %source3)"},
};
const auto op_it = combiner_map.find(operation);
if (op_it == combiner_map.end())
return "Unknown op (%source1, %source2, %source3)";
return op_it->second;
}
std::string GetTevStageConfigColorCombinerString(const TexturingRegs::TevStageConfig& tev_stage) {
auto op_str = GetTevStageConfigOperationString(tev_stage.color_op);
op_str = ReplacePattern(
op_str, "%source1",
GetTevStageConfigColorSourceString(tev_stage.color_source1, tev_stage.color_modifier1));
op_str = ReplacePattern(
op_str, "%source2",
GetTevStageConfigColorSourceString(tev_stage.color_source2, tev_stage.color_modifier2));
return ReplacePattern(
op_str, "%source3",
GetTevStageConfigColorSourceString(tev_stage.color_source3, tev_stage.color_modifier3));
}
std::string GetTevStageConfigAlphaCombinerString(const TexturingRegs::TevStageConfig& tev_stage) {
auto op_str = GetTevStageConfigOperationString(tev_stage.alpha_op);
op_str = ReplacePattern(
op_str, "%source1",
GetTevStageConfigAlphaSourceString(tev_stage.alpha_source1, tev_stage.alpha_modifier1));
op_str = ReplacePattern(
op_str, "%source2",
GetTevStageConfigAlphaSourceString(tev_stage.alpha_source2, tev_stage.alpha_modifier2));
return ReplacePattern(
op_str, "%source3",
GetTevStageConfigAlphaSourceString(tev_stage.alpha_source3, tev_stage.alpha_modifier3));
}
void DumpTevStageConfig(const std::array<TexturingRegs::TevStageConfig, 6>& stages) {
std::string stage_info = "Tev setup:\n";
for (std::size_t index = 0; index < stages.size(); ++index) {
const auto& tev_stage = stages[index];
stage_info += "Stage " + std::to_string(index) + ": " +
GetTevStageConfigColorCombinerString(tev_stage) + " " +
GetTevStageConfigAlphaCombinerString(tev_stage) + "\n";
}
LOG_TRACE(HW_GPU, "{}", stage_info);
}
} // namespace DebugUtils
} // namespace Pica

View file

@ -4,22 +4,16 @@
#pragma once
#include <algorithm>
#include <array>
#include <condition_variable>
#include <iterator>
#include <list>
#include <map>
#include <memory>
#include <mutex>
#include <string>
#include <utility>
#include <vector>
#include "common/common_types.h"
#include "common/vector_math.h"
#include "video_core/regs_rasterizer.h"
#include "video_core/regs_shader.h"
#include "video_core/regs_texturing.h"
#include "video_core/pica/regs_rasterizer.h"
namespace CiTrace {
class Recorder;
@ -27,9 +21,8 @@ class Recorder;
namespace Pica {
namespace Shader {
struct ShaderRegs;
struct ShaderSetup;
}
class DebugContext {
public:
@ -87,7 +80,7 @@ public:
* @param data Optional data pointer (if unused, this is a nullptr)
* @note This function will perform nothing unless it is overridden in the child class.
*/
virtual void OnPicaBreakPointHit(Event event, void* data) {}
virtual void OnPicaBreakPointHit(Event event, const void* data) {}
/**
* Action to perform when emulation is resumed from a breakpoint.
@ -126,7 +119,7 @@ public:
* @param data Optional data pointer (pass nullptr if unused). Needs to remain valid until
* Resume() is called.
*/
void OnEvent(Event event, void* data) {
void OnEvent(Event event, const void* data) {
// This check is left in the header to allow the compiler to inline it.
if (!breakpoints[(int)event].enabled)
return;
@ -134,7 +127,7 @@ public:
DoOnEvent(event, data);
}
void DoOnEvent(Event event, void* data);
void DoOnEvent(Event event, const void* data);
/**
* Resume from the current breakpoint.
@ -181,10 +174,7 @@ extern std::shared_ptr<DebugContext> g_debug_context; // TODO: Get rid of this g
namespace DebugUtils {
#define PICA_LOG_TEV 0
void DumpShader(const std::string& filename, const ShaderRegs& config,
const Shader::ShaderSetup& setup,
void DumpShader(const std::string& filename, const ShaderRegs& config, const ShaderSetup& setup,
const RasterizerRegs::VSOutputAttributes* output_attributes);
// Utility class to log Pica commands.
@ -203,46 +193,9 @@ void StartPicaTracing();
inline bool IsPicaTracing() {
return g_is_pica_tracing;
}
void OnPicaRegWrite(PicaTrace::Write write);
void OnPicaRegWrite(u16 cmd_id, u16 mask, u32 value);
std::unique_ptr<PicaTrace> FinishPicaTracing();
std::string GetTevStageConfigColorCombinerString(const TexturingRegs::TevStageConfig& tev_stage);
std::string GetTevStageConfigAlphaCombinerString(const TexturingRegs::TevStageConfig& tev_stage);
/// Dumps the Tev stage config to log at trace level
void DumpTevStageConfig(const std::array<TexturingRegs::TevStageConfig, 6>& stages);
/**
* Used in the vertex loader to merge access records. TODO: Investigate if actually useful.
*/
class MemoryAccessTracker {
/// Combine overlapping and close ranges
void SimplifyRanges() {
for (auto it = ranges.begin(); it != ranges.end(); ++it) {
// NOTE: We add 32 to the range end address to make sure "close" ranges are combined,
// too
auto it2 = std::next(it);
while (it2 != ranges.end() && it->first + it->second + 32 >= it2->first) {
it->second = std::max(it->second, it2->first + it2->second - it->first);
it2 = ranges.erase(it2);
}
}
}
public:
/// Record a particular memory access in the list
void AddAccess(u32 paddr, u32 size) {
// Create new range or extend existing one
ranges[paddr] = std::max(ranges[paddr], size);
// Simplify ranges...
SimplifyRanges();
}
/// Map of accessed ranges (mapping start address to range size)
std::map<u32, u32> ranges;
};
} // namespace DebugUtils
} // namespace Pica

419
src/video_core/gpu.cpp Normal file
View file

@ -0,0 +1,419 @@
// Copyright 2023 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#include "common/archives.h"
#include "common/microprofile.h"
#include "core/core.h"
#include "core/core_timing.h"
#include "core/hle/service/gsp/gsp_gpu.h"
#include "core/hle/service/plgldr/plgldr.h"
#include "video_core/debug_utils/debug_utils.h"
#include "video_core/gpu.h"
#include "video_core/gpu_debugger.h"
#include "video_core/pica/pica_core.h"
#include "video_core/pica/regs_lcd.h"
#include "video_core/renderer_base.h"
#include "video_core/renderer_software/sw_blitter.h"
#include "video_core/video_core.h"
namespace VideoCore {
constexpr VAddr VADDR_LCD = 0x1ED02000;
constexpr VAddr VADDR_GPU = 0x1EF00000;
static PAddr VirtualToPhysicalAddress(VAddr addr) {
if (addr == 0) {
return 0;
}
if (addr >= Memory::VRAM_VADDR && addr <= Memory::VRAM_VADDR_END) {
return addr - Memory::VRAM_VADDR + Memory::VRAM_PADDR;
}
if (addr >= Memory::LINEAR_HEAP_VADDR && addr <= Memory::LINEAR_HEAP_VADDR_END) {
return addr - Memory::LINEAR_HEAP_VADDR + Memory::FCRAM_PADDR;
}
if (addr >= Memory::NEW_LINEAR_HEAP_VADDR && addr <= Memory::NEW_LINEAR_HEAP_VADDR_END) {
return addr - Memory::NEW_LINEAR_HEAP_VADDR + Memory::FCRAM_PADDR;
}
if (addr >= Memory::PLUGIN_3GX_FB_VADDR && addr <= Memory::PLUGIN_3GX_FB_VADDR_END) {
return addr - Memory::PLUGIN_3GX_FB_VADDR + Service::PLGLDR::PLG_LDR::GetPluginFBAddr();
}
LOG_ERROR(HW_Memory, "Unknown virtual address @ 0x{:08X}", addr);
return addr;
}
MICROPROFILE_DEFINE(GPU_DisplayTransfer, "GPU", "DisplayTransfer", MP_RGB(100, 100, 255));
MICROPROFILE_DEFINE(GPU_CmdlistProcessing, "GPU", "Cmdlist Processing", MP_RGB(100, 255, 100));
struct GPU::Impl {
Core::Timing& timing;
Core::System& system;
Memory::MemorySystem& memory;
Pica::DebugContext& debug_context;
Pica::PicaCore pica;
GraphicsDebugger gpu_debugger;
std::unique_ptr<RendererBase> renderer;
RasterizerInterface* rasterizer;
std::unique_ptr<SwRenderer::SwBlitter> sw_blitter;
Core::TimingEventType* vblank_event;
Service::GSP::InterruptHandler signal_interrupt;
explicit Impl(Core::System& system, Frontend::EmuWindow& emu_window,
Frontend::EmuWindow* secondary_window)
: timing{system.CoreTiming()}, system{system}, memory{system.Memory()},
debug_context{*Pica::g_debug_context}, pica{memory, debug_context},
renderer{VideoCore::CreateRenderer(emu_window, secondary_window, pica, system)},
rasterizer{renderer->Rasterizer()}, sw_blitter{std::make_unique<SwRenderer::SwBlitter>(
memory, rasterizer)} {}
~Impl() = default;
};
GPU::GPU(Core::System& system, Frontend::EmuWindow& emu_window,
Frontend::EmuWindow* secondary_window)
: impl{std::make_unique<Impl>(system, emu_window, secondary_window)} {
impl->vblank_event = impl->timing.RegisterEvent(
"GPU::VBlankCallback",
[this](uintptr_t user_data, s64 cycles_late) { VBlankCallback(user_data, cycles_late); });
impl->timing.ScheduleEvent(FRAME_TICKS, impl->vblank_event);
// Bind the rasterizer to the PICA GPU
impl->pica.BindRasterizer(impl->rasterizer);
}
GPU::~GPU() = default;
void GPU::SetInterruptHandler(Service::GSP::InterruptHandler handler) {
impl->signal_interrupt = handler;
impl->pica.SetInterruptHandler(handler);
}
void GPU::FlushRegion(PAddr addr, u32 size) {
impl->rasterizer->FlushRegion(addr, size);
}
void GPU::InvalidateRegion(PAddr addr, u32 size) {
impl->rasterizer->InvalidateRegion(addr, size);
}
void GPU::ClearAll(bool flush) {
impl->rasterizer->ClearAll(flush);
}
void GPU::Execute(const Service::GSP::Command& command) {
using Service::GSP::CommandId;
auto& regs = impl->pica.regs;
switch (command.id) {
case CommandId::RequestDma: {
Memory::RasterizerFlushVirtualRegion(command.dma_request.source_address,
command.dma_request.size, Memory::FlushMode::Flush);
Memory::RasterizerFlushVirtualRegion(command.dma_request.dest_address,
command.dma_request.size,
Memory::FlushMode::Invalidate);
// TODO(Subv): These memory accesses should not go through the application's memory mapping.
// They should go through the GSP module's memory mapping.
const auto process = impl->system.Kernel().GetCurrentProcess();
impl->memory.CopyBlock(*process, command.dma_request.dest_address,
command.dma_request.source_address, command.dma_request.size);
impl->signal_interrupt(Service::GSP::InterruptId::DMA);
break;
}
case CommandId::SubmitCmdList: {
auto& params = command.submit_gpu_cmdlist;
auto& cmdbuffer = regs.internal.pipeline.command_buffer;
// Write to the command buffer GPU registers
cmdbuffer.addr[0].Assign(VirtualToPhysicalAddress(params.address) >> 3);
cmdbuffer.size[0].Assign(params.size >> 3);
cmdbuffer.trigger[0] = 1;
// Trigger processing of the command list
SubmitCmdList(0);
break;
}
case CommandId::MemoryFill: {
auto& params = command.memory_fill;
auto& memfill = regs.memory_fill_config;
// Write to the memory fill GPU registers.
if (params.start1 != 0) {
memfill[0].address_start = VirtualToPhysicalAddress(params.start1) >> 3;
memfill[0].address_end = VirtualToPhysicalAddress(params.end1) >> 3;
memfill[0].value_32bit = params.value1;
memfill[0].control = params.control1;
MemoryFill(0);
}
if (params.start2 != 0) {
memfill[1].address_start = VirtualToPhysicalAddress(params.start2) >> 3;
memfill[1].address_end = VirtualToPhysicalAddress(params.end2) >> 3;
memfill[1].value_32bit = params.value2;
memfill[1].control = params.control2;
MemoryFill(1);
}
break;
}
case CommandId::DisplayTransfer: {
auto& params = command.display_transfer;
auto& display_transfer = regs.display_transfer_config;
// Write to the transfer engine GPU registers.
display_transfer.input_address = VirtualToPhysicalAddress(params.in_buffer_address) >> 3;
display_transfer.output_address = VirtualToPhysicalAddress(params.out_buffer_address) >> 3;
display_transfer.input_size = params.in_buffer_size;
display_transfer.output_size = params.out_buffer_size;
display_transfer.flags = params.flags;
display_transfer.trigger.Assign(1);
// Trigger the display transfer.
MemoryTransfer();
break;
}
case CommandId::TextureCopy: {
auto& params = command.texture_copy;
auto& texture_copy = regs.display_transfer_config;
// Write to the transfer engine GPU registers.
texture_copy.input_address = VirtualToPhysicalAddress(params.in_buffer_address) >> 3;
texture_copy.output_address = VirtualToPhysicalAddress(params.out_buffer_address) >> 3;
texture_copy.texture_copy.size = params.size;
texture_copy.texture_copy.input_size = params.in_width_gap;
texture_copy.texture_copy.output_size = params.out_width_gap;
texture_copy.flags = params.flags;
texture_copy.trigger.Assign(1);
// Trigger the texture copy.
MemoryTransfer();
break;
}
case CommandId::CacheFlush: {
// Rasterizer flushing handled elsewhere in CPU read/write and other GPU handlers
// Use command.cache_flush.regions to implement this handler
break;
}
default:
LOG_ERROR(HW_GPU, "Unknown command {:#08X}", command.id.Value());
}
// Notify debugger that a GSP command was processed.
impl->debug_context.OnEvent(Pica::DebugContext::Event::GSPCommandProcessed, &command);
}
void GPU::SetBufferSwap(u32 screen_id, const Service::GSP::FrameBufferInfo& info) {
const PAddr phys_address_left = VirtualToPhysicalAddress(info.address_left);
const PAddr phys_address_right = VirtualToPhysicalAddress(info.address_right);
// Update framebuffer properties.
auto& framebuffer = impl->pica.regs.framebuffer_config[screen_id];
if (info.active_fb == 0) {
framebuffer.address_left1 = phys_address_left;
framebuffer.address_right1 = phys_address_right;
} else {
framebuffer.address_left2 = phys_address_left;
framebuffer.address_right2 = phys_address_right;
}
framebuffer.stride = info.stride;
framebuffer.format = info.format;
framebuffer.active_fb = info.shown_fb;
// Notify debugger about the buffer swap.
impl->debug_context.OnEvent(Pica::DebugContext::Event::BufferSwapped, nullptr);
if (screen_id == 0) {
MicroProfileFlip();
impl->system.perf_stats->EndGameFrame();
}
}
void GPU::SetColorFill(const Pica::ColorFill& fill) {
impl->pica.regs_lcd.color_fill_top = fill;
impl->pica.regs_lcd.color_fill_bottom = fill;
}
u32 GPU::ReadReg(VAddr addr) {
switch (addr & 0xFFFFF000) {
case VADDR_LCD: {
const u32 offset = addr - VADDR_LCD;
const u32 index = offset / sizeof(u32);
ASSERT(addr % sizeof(u32) == 0);
ASSERT(index < Pica::RegsLcd::NumIds());
return impl->pica.regs_lcd[index];
}
case VADDR_GPU:
case VADDR_GPU + 0x1000: {
const u32 offset = addr - VADDR_GPU;
const u32 index = offset / sizeof(u32);
ASSERT(addr % sizeof(u32) == 0);
ASSERT(index < Pica::PicaCore::Regs::NUM_REGS);
return impl->pica.regs.reg_array[index];
}
default:
UNREACHABLE_MSG("Read from unknown GPU address {:#08X}", addr);
}
}
void GPU::WriteReg(VAddr addr, u32 data) {
switch (addr & 0xFFFFF000) {
case VADDR_LCD: {
const u32 offset = addr - VADDR_LCD;
const u32 index = offset / sizeof(u32);
ASSERT(addr % sizeof(u32) == 0);
ASSERT(index < Pica::RegsLcd::NumIds());
impl->pica.regs_lcd[index] = data;
break;
}
case VADDR_GPU:
case VADDR_GPU + 0x1000: {
const u32 offset = addr - VADDR_GPU;
const u32 index = offset / sizeof(u32);
ASSERT(addr % sizeof(u32) == 0);
ASSERT(index < Pica::PicaCore::Regs::NUM_REGS);
impl->pica.regs.reg_array[index] = data;
// Handle registers that trigger GPU actions
switch (index) {
case GPU_REG_INDEX(memory_fill_config[0].trigger):
MemoryFill(0);
break;
case GPU_REG_INDEX(memory_fill_config[1].trigger):
MemoryFill(1);
break;
case GPU_REG_INDEX(display_transfer_config.trigger):
MemoryTransfer();
break;
case GPU_REG_INDEX(internal.pipeline.command_buffer.trigger[0]):
SubmitCmdList(0);
break;
case GPU_REG_INDEX(internal.pipeline.command_buffer.trigger[1]):
SubmitCmdList(1);
break;
default:
break;
}
break;
}
default:
UNREACHABLE_MSG("Write to unknown GPU address {:#08X}", addr);
}
}
void GPU::Sync() {
impl->renderer->Sync();
}
VideoCore::RendererBase& GPU::Renderer() {
return *impl->renderer;
}
Pica::PicaCore& GPU::PicaCore() {
return impl->pica;
}
const Pica::PicaCore& GPU::PicaCore() const {
return impl->pica;
}
Pica::DebugContext& GPU::DebugContext() {
return *Pica::g_debug_context;
}
GraphicsDebugger& GPU::Debugger() {
return impl->gpu_debugger;
}
void GPU::SubmitCmdList(u32 index) {
// Check if a command list was triggered.
auto& config = impl->pica.regs.internal.pipeline.command_buffer;
if (!config.trigger[index]) {
return;
}
MICROPROFILE_SCOPE(GPU_CmdlistProcessing);
// Forward command list processing to the PICA core.
const PAddr addr = config.GetPhysicalAddress(index);
const u32 size = config.GetSize(index);
impl->pica.ProcessCmdList(addr, size);
config.trigger[index] = 0;
}
void GPU::MemoryFill(u32 index) {
// Check if a memory fill was triggered.
auto& config = impl->pica.regs.memory_fill_config[index];
if (!config.trigger) {
return;
}
// Perform memory fill.
if (!impl->rasterizer->AccelerateFill(config)) {
impl->sw_blitter->MemoryFill(config);
}
// It seems that it won't signal interrupt if "address_start" is zero.
// TODO: hwtest this
if (config.GetStartAddress() != 0) {
if (!index) {
impl->signal_interrupt(Service::GSP::InterruptId::PSC0);
} else {
impl->signal_interrupt(Service::GSP::InterruptId::PSC1);
}
}
// Reset "trigger" flag and set the "finish" flag
// This was confirmed to happen on hardware even if "address_start" is zero.
config.trigger.Assign(0);
config.finished.Assign(1);
}
void GPU::MemoryTransfer() {
// Check if a transfer was triggered.
auto& config = impl->pica.regs.display_transfer_config;
if (!config.trigger.Value()) {
return;
}
MICROPROFILE_SCOPE(GPU_DisplayTransfer);
// Notify debugger about the display transfer.
impl->debug_context.OnEvent(Pica::DebugContext::Event::IncomingDisplayTransfer, nullptr);
// Perform memory transfer
if (config.is_texture_copy) {
if (!impl->rasterizer->AccelerateTextureCopy(config)) {
impl->sw_blitter->TextureCopy(config);
}
} else {
if (!impl->rasterizer->AccelerateDisplayTransfer(config)) {
impl->sw_blitter->DisplayTransfer(config);
}
}
// Complete transfer.
config.trigger.Assign(0);
impl->signal_interrupt(Service::GSP::InterruptId::PPF);
}
void GPU::VBlankCallback(std::uintptr_t user_data, s64 cycles_late) {
// Present renderered frame.
impl->renderer->SwapBuffers();
// Signal to GSP that GPU interrupt has occurred
impl->signal_interrupt(Service::GSP::InterruptId::PDC0);
impl->signal_interrupt(Service::GSP::InterruptId::PDC1);
// Reschedule recurrent event
impl->timing.ScheduleEvent(FRAME_TICKS - cycles_late, impl->vblank_event);
}
template <class Archive>
void GPU::serialize(Archive& ar, const u32 file_version) {
ar & impl->pica;
}
SERIALIZE_IMPL(GPU)
} // namespace VideoCore

113
src/video_core/gpu.h Normal file
View file

@ -0,0 +1,113 @@
// Copyright 2023 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#pragma once
#include <functional>
#include <memory>
#include <boost/serialization/access.hpp>
#include "core/hle/service/gsp/gsp_interrupt.h"
namespace Service::GSP {
struct Command;
struct FrameBufferInfo;
} // namespace Service::GSP
namespace Core {
class System;
}
namespace Pica {
class DebugContext;
class PicaCore;
struct RegsLcd;
union ColorFill;
} // namespace Pica
namespace Frontend {
class EmuWindow;
}
namespace VideoCore {
/// Measured on hardware to be 2240568 timer cycles or 4481136 ARM11 cycles
constexpr u64 FRAME_TICKS = 4481136ull;
class GraphicsDebugger;
class RendererBase;
/**
* The GPU class is the high level interface to the video_core for core services.
*/
class GPU {
public:
explicit GPU(Core::System& system, Frontend::EmuWindow& emu_window,
Frontend::EmuWindow* secondary_window);
~GPU();
/// Sets the function to call for signalling GSP interrupts.
void SetInterruptHandler(Service::GSP::InterruptHandler handler);
/// Notify rasterizer that any caches of the specified region should be flushed to Switch memory
void FlushRegion(PAddr addr, u32 size);
/// Notify rasterizer that any caches of the specified region should be invalidated
void InvalidateRegion(PAddr addr, u32 size);
/// Flushes and invalidates all memory in the rasterizer cache and removes any leftover state.
void ClearAll(bool flush);
/// Executes the provided GSP command.
void Execute(const Service::GSP::Command& command);
/// Updates GPU display framebuffer configuration using the specified parameters.
void SetBufferSwap(u32 screen_id, const Service::GSP::FrameBufferInfo& info);
/// Sets the LCD color fill configuration for the top and bottom screens.
void SetColorFill(const Pica::ColorFill& fill);
/// Reads a word from the GPU virtual address.
u32 ReadReg(VAddr addr);
/// Writes the provided value to the GPU virtual address.
void WriteReg(VAddr addr, u32 data);
/// Synchronizes fixed function renderer state with PICA registers.
void Sync();
/// Returns a mutable reference to the renderer.
[[nodiscard]] VideoCore::RendererBase& Renderer();
/// Returns a mutable reference to the PICA GPU.
[[nodiscard]] Pica::PicaCore& PicaCore();
/// Returns an immutable reference to the PICA GPU.
[[nodiscard]] const Pica::PicaCore& PicaCore() const;
/// Returns a mutable reference to the pica debugging context.
[[nodiscard]] Pica::DebugContext& DebugContext();
/// Returns a mutable reference to the GSP command debugger.
[[nodiscard]] GraphicsDebugger& Debugger();
private:
void SubmitCmdList(u32 index);
void MemoryFill(u32 index);
void MemoryTransfer();
void VBlankCallback(uintptr_t user_data, s64 cycles_late);
friend class boost::serialization::access;
template <class Archive>
void serialize(Archive& ar, const u32 file_version);
private:
struct Impl;
std::unique_ptr<Impl> impl;
};
} // namespace VideoCore

View file

@ -7,18 +7,22 @@
#include <algorithm>
#include <functional>
#include <vector>
#include "core/hle/service/gsp/gsp.h"
#include "core/hle/service/gsp/gsp_command.h"
namespace VideoCore {
class GraphicsDebugger {
public:
// Base class for all objects which need to be notified about GPU events
class DebuggerObserver {
public:
DebuggerObserver() : observed(nullptr) {}
friend class GraphicsDebugger;
public:
DebuggerObserver() = default;
virtual ~DebuggerObserver() {
if (observed)
if (observed) {
observed->UnregisterObserver(this);
}
}
/**
@ -39,20 +43,15 @@ public:
}
private:
GraphicsDebugger* observed;
friend class GraphicsDebugger;
GraphicsDebugger* observed{};
};
void GXCommandProcessed(u8* command_data) {
if (observers.empty())
void GXCommandProcessed(Service::GSP::Command& command_data) {
if (observers.empty()) {
return;
}
gx_command_history.emplace_back();
Service::GSP::Command& cmd = gx_command_history.back();
std::memcpy(&cmd, command_data, sizeof(Service::GSP::Command));
gx_command_history.emplace_back(command_data);
ForEachObserver([this](DebuggerObserver* observer) {
observer->GXCommandProcessed(static_cast<int>(this->gx_command_history.size()));
});
@ -80,6 +79,7 @@ private:
}
std::vector<DebuggerObserver*> observers;
std::vector<Service::GSP::Command> gx_command_history;
};
} // namespace VideoCore

View file

@ -1,70 +0,0 @@
// Copyright 2015 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#include <cstring>
#include <type_traits>
#include "core/global.h"
#include "video_core/geometry_pipeline.h"
#include "video_core/pica.h"
#include "video_core/pica_state.h"
#include "video_core/renderer_base.h"
#include "video_core/video_core.h"
namespace Core {
template <>
Pica::State& Global() {
return Pica::g_state;
}
} // namespace Core
namespace Pica {
State g_state;
void Init() {
g_state.Reset();
}
void Shutdown() {
Shader::Shutdown();
}
template <typename T>
void Zero(T& o) {
static_assert(std::is_trivial_v<T>, "It's undefined behavior to memset a non-trivial type");
std::memset(&o, 0, sizeof(o));
}
State::State() : geometry_pipeline(*this) {
auto SubmitVertex = [this](const Shader::AttributeBuffer& vertex) {
using Pica::Shader::OutputVertex;
auto AddTriangle = [](const OutputVertex& v0, const OutputVertex& v1,
const OutputVertex& v2) {
VideoCore::g_renderer->Rasterizer()->AddTriangle(v0, v1, v2);
};
primitive_assembler.SubmitVertex(
Shader::OutputVertex::FromAttributeBuffer(regs.rasterizer, vertex), AddTriangle);
};
auto SetWinding = [this]() { primitive_assembler.SetWinding(); };
g_state.gs_unit.SetVertexHandler(SubmitVertex, SetWinding);
g_state.geometry_pipeline.SetVertexHandler(SubmitVertex);
}
void State::Reset() {
Zero(regs);
vs = {};
gs = {};
Zero(cmd_list);
immediate = {};
primitive_assembler.Reconfigure(PipelineRegs::TriangleTopology::List);
vs_float_regs_counter = 0;
vs_uniform_write_buffer.fill(0);
gs_float_regs_counter = 0;
gs_uniform_write_buffer.fill(0);
default_attr_counter = 0;
default_attr_write_buffer.fill(0);
}
} // namespace Pica

View file

@ -1,16 +0,0 @@
// Copyright 2014 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#pragma once
#include "video_core/regs_texturing.h"
namespace Pica {
/// Initialize Pica state
void Init();
/// Shutdown Pica state
void Shutdown();
} // namespace Pica

View file

@ -6,11 +6,13 @@
#include <boost/serialization/export.hpp>
#include <boost/serialization/unique_ptr.hpp>
#include "common/archives.h"
#include "video_core/geometry_pipeline.h"
#include "video_core/pica_state.h"
#include "video_core/regs.h"
#include "video_core/renderer_base.h"
#include "video_core/video_core.h"
#include "core/core.h"
#include "video_core/gpu.h"
#include "video_core/pica/geometry_pipeline.h"
#include "video_core/pica/pica_core.h"
#include "video_core/pica/shader_setup.h"
#include "video_core/pica/shader_unit.h"
#include "video_core/shader/shader.h"
namespace Pica {
@ -33,7 +35,7 @@ public:
* @param input attributes of a vertex output from vertex shader
* @return if the buffer is full and the geometry shader should be invoked
*/
virtual bool SubmitVertex(const Shader::AttributeBuffer& input) = 0;
virtual bool SubmitVertex(const AttributeBuffer& input) = 0;
private:
template <class Archive>
@ -49,32 +51,33 @@ private:
// TODO: what happens when the input size is not divisible by the output size?
class GeometryPipeline_Point : public GeometryPipelineBackend {
public:
GeometryPipeline_Point(const Regs& regs, Shader::GSUnitState& unit) : regs(regs), unit(unit) {
GeometryPipeline_Point(const RegsInternal& regs, GeometryShaderUnit& unit)
: regs(regs), unit(unit) {
ASSERT(regs.pipeline.variable_primitive == 0);
ASSERT(regs.gs.input_to_uniform == 0);
vs_output_num = regs.pipeline.vs_outmap_total_minus_1_a + 1;
std::size_t gs_input_num = regs.gs.max_input_attribute_index + 1;
ASSERT(gs_input_num % vs_output_num == 0);
buffer_cur = attribute_buffer.attr;
buffer_end = attribute_buffer.attr + gs_input_num;
buffer_cur = attribute_buffer.data();
buffer_end = attribute_buffer.data() + gs_input_num;
}
bool IsEmpty() const override {
return buffer_cur == attribute_buffer.attr;
return buffer_cur == attribute_buffer.data();
}
bool NeedIndexInput() const override {
return false;
}
void SubmitIndex(unsigned int val) override {
void SubmitIndex(u32 val) override {
UNREACHABLE();
}
bool SubmitVertex(const Shader::AttributeBuffer& input) override {
buffer_cur = std::copy(input.attr, input.attr + vs_output_num, buffer_cur);
bool SubmitVertex(const AttributeBuffer& input) override {
buffer_cur = std::copy(input.data(), input.data() + vs_output_num, buffer_cur);
if (buffer_cur == buffer_end) {
buffer_cur = attribute_buffer.attr;
buffer_cur = attribute_buffer.data();
unit.LoadInput(regs.gs, attribute_buffer);
return true;
}
@ -82,14 +85,17 @@ public:
}
private:
const Regs& regs;
Shader::GSUnitState& unit;
Shader::AttributeBuffer attribute_buffer;
const RegsInternal& regs;
GeometryShaderUnit& unit;
AttributeBuffer attribute_buffer;
Common::Vec4<f24>* buffer_cur;
Common::Vec4<f24>* buffer_end;
unsigned int vs_output_num;
u32 vs_output_num;
GeometryPipeline_Point() : regs(g_state.regs), unit(g_state.gs_unit) {}
// TODO: REMOVE THIS
GeometryPipeline_Point()
: regs(Core::System::GetInstance().GPU().PicaCore().regs.internal),
unit(Core::System::GetInstance().GPU().PicaCore().gs_unit) {}
template <typename Class, class Archive>
static void serialize_common(Class* self, Archive& ar, const unsigned int version) {
@ -101,8 +107,8 @@ private:
template <class Archive>
void save(Archive& ar, const unsigned int version) const {
serialize_common(this, ar, version);
auto buffer_idx = static_cast<u32>(buffer_cur - attribute_buffer.attr);
auto buffer_size = static_cast<u32>(buffer_end - attribute_buffer.attr);
auto buffer_idx = static_cast<u32>(buffer_cur - attribute_buffer.data());
auto buffer_size = static_cast<u32>(buffer_end - attribute_buffer.data());
ar << buffer_idx;
ar << buffer_size;
}
@ -113,8 +119,8 @@ private:
u32 buffer_idx, buffer_size;
ar >> buffer_idx;
ar >> buffer_size;
buffer_cur = attribute_buffer.attr + buffer_idx;
buffer_end = attribute_buffer.attr + buffer_size;
buffer_cur = attribute_buffer.data() + buffer_idx;
buffer_end = attribute_buffer.data() + buffer_size;
}
BOOST_SERIALIZATION_SPLIT_MEMBER()
@ -127,7 +133,7 @@ private:
// value in the batch. This mode is usually used for subdivision.
class GeometryPipeline_VariablePrimitive : public GeometryPipelineBackend {
public:
GeometryPipeline_VariablePrimitive(const Regs& regs, Shader::ShaderSetup& setup)
GeometryPipeline_VariablePrimitive(const RegsInternal& regs, ShaderSetup& setup)
: regs(regs), setup(setup) {
ASSERT(regs.pipeline.variable_primitive == 1);
ASSERT(regs.gs.input_to_uniform == 1);
@ -142,7 +148,7 @@ public:
return need_index;
}
void SubmitIndex(unsigned int val) override {
void SubmitIndex(u32 val) override {
DEBUG_ASSERT(need_index);
// The number of vertex input is put to the uniform register
@ -157,15 +163,15 @@ public:
need_index = false;
}
bool SubmitVertex(const Shader::AttributeBuffer& input) override {
bool SubmitVertex(const AttributeBuffer& input) override {
DEBUG_ASSERT(!need_index);
if (main_vertex_num != 0) {
// For main vertices, receive all attributes
buffer_cur = std::copy(input.attr, input.attr + vs_output_num, buffer_cur);
buffer_cur = std::copy(input.data(), input.data() + vs_output_num, buffer_cur);
--main_vertex_num;
} else {
// For other vertices, only receive the first attribute (usually the position)
*(buffer_cur++) = input.attr[0];
*(buffer_cur++) = input[0];
}
--total_vertex_num;
@ -179,14 +185,17 @@ public:
private:
bool need_index = true;
const Regs& regs;
Shader::ShaderSetup& setup;
unsigned int main_vertex_num;
unsigned int total_vertex_num;
const RegsInternal& regs;
ShaderSetup& setup;
u32 main_vertex_num;
u32 total_vertex_num;
Common::Vec4<f24>* buffer_cur;
unsigned int vs_output_num;
u32 vs_output_num;
GeometryPipeline_VariablePrimitive() : regs(g_state.regs), setup(g_state.gs) {}
// TODO: REMOVE THIS
GeometryPipeline_VariablePrimitive()
: regs(Core::System::GetInstance().GPU().PicaCore().regs.internal),
setup(Core::System::GetInstance().GPU().PicaCore().gs_setup) {}
template <typename Class, class Archive>
static void serialize_common(Class* self, Archive& ar, const unsigned int version) {
@ -222,8 +231,7 @@ private:
// particle system.
class GeometryPipeline_FixedPrimitive : public GeometryPipelineBackend {
public:
GeometryPipeline_FixedPrimitive(const Regs& regs, Shader::ShaderSetup& setup)
: regs(regs), setup(setup) {
GeometryPipeline_FixedPrimitive(const RegsInternal& regs, ShaderSetup& setup) : setup(setup) {
ASSERT(regs.pipeline.variable_primitive == 0);
ASSERT(regs.gs.input_to_uniform == 1);
vs_output_num = regs.pipeline.vs_outmap_total_minus_1_a + 1;
@ -241,12 +249,12 @@ public:
return false;
}
void SubmitIndex(unsigned int val) override {
void SubmitIndex(u32 val) override {
UNREACHABLE();
}
bool SubmitVertex(const Shader::AttributeBuffer& input) override {
buffer_cur = std::copy(input.attr, input.attr + vs_output_num, buffer_cur);
bool SubmitVertex(const AttributeBuffer& input) override {
buffer_cur = std::copy(input.data(), input.data() + vs_output_num, buffer_cur);
if (buffer_cur == buffer_end) {
buffer_cur = buffer_begin;
return true;
@ -255,14 +263,15 @@ public:
}
private:
[[maybe_unused]] const Regs& regs;
Shader::ShaderSetup& setup;
ShaderSetup& setup;
Common::Vec4<f24>* buffer_begin;
Common::Vec4<f24>* buffer_cur;
Common::Vec4<f24>* buffer_end;
unsigned int vs_output_num;
u32 vs_output_num;
GeometryPipeline_FixedPrimitive() : regs(g_state.regs), setup(g_state.gs) {}
// TODO: REMOVE THIS
GeometryPipeline_FixedPrimitive()
: setup(Core::System::GetInstance().GPU().PicaCore().gs_setup) {}
template <typename Class, class Archive>
static void serialize_common(Class* self, Archive& ar, const unsigned int version) {
@ -298,52 +307,53 @@ private:
friend class boost::serialization::access;
};
GeometryPipeline::GeometryPipeline(State& state) : state(state) {}
GeometryPipeline::GeometryPipeline(RegsInternal& regs_, GeometryShaderUnit& gs_unit_,
ShaderSetup& gs_)
: regs(regs_), gs_unit(gs_unit_), gs(gs_) {}
GeometryPipeline::~GeometryPipeline() = default;
void GeometryPipeline::SetVertexHandler(Shader::VertexHandler vertex_handler) {
void GeometryPipeline::SetVertexHandler(VertexHandler vertex_handler) {
this->vertex_handler = std::move(vertex_handler);
}
void GeometryPipeline::Setup(Shader::ShaderEngine* shader_engine) {
if (!backend)
void GeometryPipeline::Setup(ShaderEngine* shader_engine) {
if (!backend) {
return;
}
this->shader_engine = shader_engine;
shader_engine->SetupBatch(state.gs, state.regs.gs.main_offset);
shader_engine->SetupBatch(gs, regs.gs.main_offset);
}
void GeometryPipeline::Reconfigure() {
ASSERT(!backend || backend->IsEmpty());
if (state.regs.pipeline.use_gs == PipelineRegs::UseGS::No) {
if (regs.pipeline.use_gs == PipelineRegs::UseGS::No) {
backend = nullptr;
return;
}
ASSERT(state.regs.pipeline.use_gs == PipelineRegs::UseGS::Yes);
// The following assumes that when geometry shader is in use, the shader unit 3 is configured as
// a geometry shader unit.
// TODO: what happens if this is not true?
ASSERT(state.regs.pipeline.gs_unit_exclusive_configuration == 1);
ASSERT(state.regs.gs.shader_mode == ShaderRegs::ShaderMode::GS);
ASSERT(regs.pipeline.gs_unit_exclusive_configuration == 1);
ASSERT(regs.gs.shader_mode == ShaderRegs::ShaderMode::GS);
ASSERT(regs.pipeline.use_gs == PipelineRegs::UseGS::Yes);
state.gs_unit.ConfigOutput(state.regs.gs);
gs_unit.ConfigOutput(regs.gs);
ASSERT(state.regs.pipeline.vs_outmap_total_minus_1_a ==
state.regs.pipeline.vs_outmap_total_minus_1_b);
ASSERT(regs.pipeline.vs_outmap_total_minus_1_a == regs.pipeline.vs_outmap_total_minus_1_b);
switch (state.regs.pipeline.gs_config.mode) {
switch (regs.pipeline.gs_config.mode) {
case PipelineRegs::GSMode::Point:
backend = std::make_unique<GeometryPipeline_Point>(state.regs, state.gs_unit);
backend = std::make_unique<GeometryPipeline_Point>(regs, gs_unit);
break;
case PipelineRegs::GSMode::VariablePrimitive:
backend = std::make_unique<GeometryPipeline_VariablePrimitive>(state.regs, state.gs);
backend = std::make_unique<GeometryPipeline_VariablePrimitive>(regs, gs);
break;
case PipelineRegs::GSMode::FixedPrimitive:
backend = std::make_unique<GeometryPipeline_FixedPrimitive>(state.regs, state.gs);
backend = std::make_unique<GeometryPipeline_FixedPrimitive>(regs, gs);
break;
default:
UNREACHABLE();
@ -351,8 +361,9 @@ void GeometryPipeline::Reconfigure() {
}
bool GeometryPipeline::NeedIndexInput() const {
if (!backend)
if (!backend) {
return false;
}
return backend->NeedIndexInput();
}
@ -360,19 +371,19 @@ void GeometryPipeline::SubmitIndex(unsigned int val) {
backend->SubmitIndex(val);
}
void GeometryPipeline::SubmitVertex(const Shader::AttributeBuffer& input) {
void GeometryPipeline::SubmitVertex(const AttributeBuffer& input) {
if (!backend) {
// No backend means the geometry shader is disabled, so we send the vertex shader output
// directly to the primitive assembler.
vertex_handler(input);
} else {
if (backend->SubmitVertex(input)) {
shader_engine->Run(state.gs, state.gs_unit);
shader_engine->Run(gs, gs_unit);
// The uniform b15 is set to true after every geometry shader invocation. This is useful
// for the shader to know if this is the first invocation in a batch, if the program set
// b15 to false first.
state.gs.uniforms.b[15] = true;
gs.uniforms.b[15] = true;
}
}
}

View file

@ -6,11 +6,14 @@
#include <memory>
#include <boost/serialization/export.hpp>
#include "video_core/shader/shader.h"
#include "video_core/pica/shader_unit.h"
namespace Pica {
struct State;
struct RegsInternal;
struct GeometryShaderUnit;
struct ShaderSetup;
class ShaderEngine;
class GeometryPipelineBackend;
class GeometryPipeline_Point;
@ -20,17 +23,14 @@ class GeometryPipeline_FixedPrimitive;
/// A pipeline receiving from vertex shader and sending to geometry shader and primitive assembler
class GeometryPipeline {
public:
explicit GeometryPipeline(State& state);
explicit GeometryPipeline(RegsInternal& regs, GeometryShaderUnit& gs_unit, ShaderSetup& gs);
~GeometryPipeline();
/// Sets the handler for receiving vertex outputs from vertex shader
void SetVertexHandler(Shader::VertexHandler vertex_handler);
void SetVertexHandler(VertexHandler vertex_handler);
/**
* Setup the geometry shader unit if it is in use
* @param shader_engine the shader engine for the geometry shader to run
*/
void Setup(Shader::ShaderEngine* shader_engine);
/// Setup the geometry shader unit if it is in use
void Setup(ShaderEngine* shader_engine);
/// Reconfigures the pipeline according to current register settings
void Reconfigure();
@ -42,13 +42,15 @@ public:
void SubmitIndex(unsigned int val);
/// Submits vertex attributes output from vertex shader
void SubmitVertex(const Shader::AttributeBuffer& input);
void SubmitVertex(const AttributeBuffer& input);
private:
Shader::VertexHandler vertex_handler;
Shader::ShaderEngine* shader_engine;
VertexHandler vertex_handler;
ShaderEngine* shader_engine;
std::unique_ptr<GeometryPipelineBackend> backend;
State& state;
RegsInternal& regs;
GeometryShaderUnit& gs_unit;
ShaderSetup& gs;
template <class Archive>
void serialize(Archive& ar, const unsigned int version);

View file

@ -0,0 +1,50 @@
// Copyright 2023 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#include "video_core/pica/output_vertex.h"
#include "video_core/pica/regs_rasterizer.h"
namespace Pica {
OutputVertex::OutputVertex(const RasterizerRegs& regs, const AttributeBuffer& output) {
// Attributes can be used without being set in GPUREG_SH_OUTMAP_Oi
// Hardware tests have shown that they are initialized to 1 in this case.
std::array<f24, 32> vertex_slots_overflow;
vertex_slots_overflow.fill(f24::One());
const u32 num_attributes = regs.vs_output_total & 7;
for (std::size_t attrib = 0; attrib < num_attributes; ++attrib) {
const auto output_register_map = regs.vs_output_attributes[attrib];
vertex_slots_overflow[output_register_map.map_x] = output[attrib][0];
vertex_slots_overflow[output_register_map.map_y] = output[attrib][1];
vertex_slots_overflow[output_register_map.map_z] = output[attrib][2];
vertex_slots_overflow[output_register_map.map_w] = output[attrib][3];
}
// Copy to result
std::memcpy(this, vertex_slots_overflow.data(), sizeof(OutputVertex));
// The hardware takes the absolute and saturates vertex colors, *before* doing interpolation
for (u32 i = 0; i < 4; ++i) {
const f32 c = std::fabs(color[i].ToFloat32());
color[i] = f24::FromFloat32(c < 1.0f ? c : 1.0f);
}
}
#define ASSERT_POS(var, pos) \
static_assert(offsetof(OutputVertex, var) == pos * sizeof(f24), "Semantic at wrong " \
"offset.")
ASSERT_POS(pos, RasterizerRegs::VSOutputAttributes::POSITION_X);
ASSERT_POS(quat, RasterizerRegs::VSOutputAttributes::QUATERNION_X);
ASSERT_POS(color, RasterizerRegs::VSOutputAttributes::COLOR_R);
ASSERT_POS(tc0, RasterizerRegs::VSOutputAttributes::TEXCOORD0_U);
ASSERT_POS(tc1, RasterizerRegs::VSOutputAttributes::TEXCOORD1_U);
ASSERT_POS(tc0_w, RasterizerRegs::VSOutputAttributes::TEXCOORD0_W);
ASSERT_POS(view, RasterizerRegs::VSOutputAttributes::VIEW_X);
ASSERT_POS(tc2, RasterizerRegs::VSOutputAttributes::TEXCOORD2_U);
#undef ASSERT_POS
} // namespace Pica

View file

@ -0,0 +1,48 @@
// Copyright 2023 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#pragma once
#include "common/vector_math.h"
#include "video_core/pica_types.h"
namespace Pica {
struct RasterizerRegs;
using AttributeBuffer = std::array<Common::Vec4<f24>, 16>;
struct OutputVertex {
OutputVertex() = default;
explicit OutputVertex(const RasterizerRegs& regs, const AttributeBuffer& output);
Common::Vec4<f24> pos;
Common::Vec4<f24> quat;
Common::Vec4<f24> color;
Common::Vec2<f24> tc0;
Common::Vec2<f24> tc1;
f24 tc0_w;
INSERT_PADDING_WORDS(1);
Common::Vec3<f24> view;
INSERT_PADDING_WORDS(1);
Common::Vec2<f24> tc2;
private:
template <class Archive>
void serialize(Archive& ar, const u32) {
ar& pos;
ar& quat;
ar& color;
ar& tc0;
ar& tc1;
ar& tc0_w;
ar& view;
ar& tc2;
}
friend class boost::serialization::access;
};
static_assert(std::is_trivial_v<OutputVertex>, "Structure is not POD");
static_assert(sizeof(OutputVertex) == 24 * sizeof(f32), "OutputVertex has invalid size");
} // namespace Pica

View file

@ -0,0 +1,74 @@
// Copyright 2023 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#pragma once
#include <boost/serialization/binary_object.hpp>
#include "common/vector_math.h"
#include "video_core/pica_types.h"
namespace Pica {
/**
* Uniforms and fixed attributes are written in a packed format such that four float24 values are
* encoded in three 32-bit numbers. Uniforms can also encode four float32 values in four 32-bit
* numbers. We write to internal memory once a full vector is written.
*/
struct PackedAttribute {
std::array<u32, 4> buffer{};
u32 index{};
/// Places a word to the queue and returns true if the queue becomes full.
constexpr bool Push(u32 word, bool is_float32 = false) {
buffer[index++] = word;
return (index >= 4 && is_float32) || (index >= 3 && !is_float32);
}
/// Resets the queue discarding previous entries.
constexpr void Reset() {
index = 0;
}
/// Returns the queue contents with either float24 or float32 interpretation.
constexpr Common::Vec4<f24> Get(bool is_float32 = false) {
Reset();
if (is_float32) {
return AsFloat32();
} else {
return AsFloat24();
}
}
private:
/// Decodes the queue contents with float24 transfer mode.
constexpr Common::Vec4<f24> AsFloat24() const {
const u32 x = buffer[2] & 0xFFFFFF;
const u32 y = ((buffer[1] & 0xFFFF) << 8) | ((buffer[2] >> 24) & 0xFF);
const u32 z = ((buffer[0] & 0xFF) << 16) | ((buffer[1] >> 16) & 0xFFFF);
const u32 w = buffer[0] >> 8;
return Common::Vec4<f24>{f24::FromRaw(x), f24::FromRaw(y), f24::FromRaw(z),
f24::FromRaw(w)};
}
/// Decodes the queue contents with float32 transfer mode.
constexpr Common::Vec4<f24> AsFloat32() const {
Common::Vec4<f24> uniform;
for (u32 i = 0; i < 4; i++) {
const f32 buffer_value = std::bit_cast<f32>(buffer[i]);
uniform[3 - i] = f24::FromFloat32(buffer_value);
}
return uniform;
}
private:
template <class Archive>
void serialize(Archive& ar, const u32) {
ar& buffer;
ar& index;
}
friend class boost::serialization::access;
};
} // namespace Pica

View file

@ -0,0 +1,592 @@
// Copyright 2023 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#include "common/arch.h"
#include "common/archives.h"
#include "common/microprofile.h"
#include "common/scope_exit.h"
#include "common/settings.h"
#include "core/core.h"
#include "core/memory.h"
#include "video_core/debug_utils/debug_utils.h"
#include "video_core/pica/pica_core.h"
#include "video_core/pica/vertex_loader.h"
#include "video_core/rasterizer_interface.h"
#include "video_core/shader/shader.h"
namespace Pica {
MICROPROFILE_DEFINE(GPU_Drawing, "GPU", "Drawing", MP_RGB(50, 50, 240));
using namespace DebugUtils;
union CommandHeader {
u32 hex;
BitField<0, 16, u32> cmd_id;
BitField<16, 4, u32> parameter_mask;
BitField<20, 8, u32> extra_data_length;
BitField<31, 1, u32> group_commands;
};
static_assert(sizeof(CommandHeader) == sizeof(u32), "CommandHeader has incorrect size!");
PicaCore::PicaCore(Memory::MemorySystem& memory_, DebugContext& debug_context_)
: memory{memory_}, debug_context{debug_context_}, geometry_pipeline{regs.internal, gs_unit,
gs_setup},
shader_engine{CreateEngine(Settings::values.use_shader_jit.GetValue())} {
SetFramebufferDefaults();
const auto submit_vertex = [this](const AttributeBuffer& buffer) {
const auto add_triangle = [this](const OutputVertex& v0, const OutputVertex& v1,
const OutputVertex& v2) {
rasterizer->AddTriangle(v0, v1, v2);
};
const auto vertex = OutputVertex(regs.internal.rasterizer, buffer);
primitive_assembler.SubmitVertex(vertex, add_triangle);
};
gs_unit.SetVertexHandlers(submit_vertex, [this]() { primitive_assembler.SetWinding(); });
geometry_pipeline.SetVertexHandler(submit_vertex);
primitive_assembler.Reconfigure(PipelineRegs::TriangleTopology::List);
}
PicaCore::~PicaCore() = default;
void PicaCore::SetFramebufferDefaults() {
auto& framebuffer_top = regs.framebuffer_config[0];
auto& framebuffer_sub = regs.framebuffer_config[1];
// Set framebuffer defaults from nn::gx::Initialize
framebuffer_top.address_left1 = 0x181E6000;
framebuffer_top.address_left2 = 0x1822C800;
framebuffer_top.address_right1 = 0x18273000;
framebuffer_top.address_right2 = 0x182B9800;
framebuffer_sub.address_left1 = 0x1848F000;
framebuffer_sub.address_left2 = 0x184C7800;
framebuffer_top.width.Assign(240);
framebuffer_top.height.Assign(400);
framebuffer_top.stride = 3 * 240;
framebuffer_top.color_format.Assign(PixelFormat::RGB8);
framebuffer_top.active_fb = 0;
framebuffer_sub.width.Assign(240);
framebuffer_sub.height.Assign(320);
framebuffer_sub.stride = 3 * 240;
framebuffer_sub.color_format.Assign(PixelFormat::RGB8);
framebuffer_sub.active_fb = 0;
}
void PicaCore::BindRasterizer(VideoCore::RasterizerInterface* rasterizer) {
this->rasterizer = rasterizer;
}
void PicaCore::SetInterruptHandler(Service::GSP::InterruptHandler& signal_interrupt) {
this->signal_interrupt = signal_interrupt;
}
void PicaCore::ProcessCmdList(PAddr list, u32 size) {
// Initialize command list tracking.
const u8* head = memory.GetPhysicalPointer(list);
cmd_list.Reset(list, head, size);
while (cmd_list.current_index < cmd_list.length) {
// Align read pointer to 8 bytes
if (cmd_list.current_index % 2 != 0) {
cmd_list.current_index++;
}
// Read the header and the value to write.
const u32 value = cmd_list.head[cmd_list.current_index++];
const CommandHeader header{cmd_list.head[cmd_list.current_index++]};
// Write to the requested PICA register.
WriteInternalReg(header.cmd_id, value, header.parameter_mask);
// Write any extra paramters as well.
for (u32 i = 0; i < header.extra_data_length; ++i) {
const u32 cmd = header.cmd_id + (header.group_commands ? i + 1 : 0);
const u32 extra_value = cmd_list.head[cmd_list.current_index++];
WriteInternalReg(cmd, extra_value, header.parameter_mask);
}
}
}
void PicaCore::WriteInternalReg(u32 id, u32 value, u32 mask) {
if (id >= RegsInternal::NUM_REGS) {
LOG_ERROR(
HW_GPU,
"Commandlist tried to write to invalid register 0x{:03X} (value: {:08X}, mask: {:X})",
id, value, mask);
return;
}
// Expand a 4-bit mask to 4-byte mask, e.g. 0b0101 -> 0x00FF00FF
constexpr std::array<u32, 16> ExpandBitsToBytes = {
0x00000000, 0x000000ff, 0x0000ff00, 0x0000ffff, 0x00ff0000, 0x00ff00ff,
0x00ffff00, 0x00ffffff, 0xff000000, 0xff0000ff, 0xff00ff00, 0xff00ffff,
0xffff0000, 0xffff00ff, 0xffffff00, 0xffffffff,
};
// TODO: Figure out how register masking acts on e.g. vs.uniform_setup.set_value
const u32 old_value = regs.internal.reg_array[id];
const u32 write_mask = ExpandBitsToBytes[mask];
regs.internal.reg_array[id] = (old_value & ~write_mask) | (value & write_mask);
// Track register write.
DebugUtils::OnPicaRegWrite(id, mask, regs.internal.reg_array[id]);
// Track events.
debug_context.OnEvent(DebugContext::Event::PicaCommandLoaded, &id);
SCOPE_EXIT({ debug_context.OnEvent(DebugContext::Event::PicaCommandProcessed, &id); });
switch (id) {
// Trigger IRQ
case PICA_REG_INDEX(trigger_irq):
signal_interrupt(Service::GSP::InterruptId::P3D);
break;
case PICA_REG_INDEX(pipeline.triangle_topology):
primitive_assembler.Reconfigure(regs.internal.pipeline.triangle_topology);
break;
case PICA_REG_INDEX(pipeline.restart_primitive):
primitive_assembler.Reset();
break;
case PICA_REG_INDEX(pipeline.vs_default_attributes_setup.index):
immediate.Reset();
break;
// Load default vertex input attributes
case PICA_REG_INDEX(pipeline.vs_default_attributes_setup.set_value[0]):
case PICA_REG_INDEX(pipeline.vs_default_attributes_setup.set_value[1]):
case PICA_REG_INDEX(pipeline.vs_default_attributes_setup.set_value[2]):
SubmitImmediate(value);
break;
case PICA_REG_INDEX(pipeline.gpu_mode):
// This register likely just enables vertex processing and doesn't need any special handling
break;
case PICA_REG_INDEX(pipeline.command_buffer.trigger[0]):
case PICA_REG_INDEX(pipeline.command_buffer.trigger[1]): {
const u32 index = static_cast<u32>(id - PICA_REG_INDEX(pipeline.command_buffer.trigger[0]));
const PAddr addr = regs.internal.pipeline.command_buffer.GetPhysicalAddress(index);
const u32 size = regs.internal.pipeline.command_buffer.GetSize(index);
const u8* head = memory.GetPhysicalPointer(addr);
cmd_list.Reset(addr, head, size);
break;
}
// It seems like these trigger vertex rendering
case PICA_REG_INDEX(pipeline.trigger_draw):
case PICA_REG_INDEX(pipeline.trigger_draw_indexed): {
const bool is_indexed = (id == PICA_REG_INDEX(pipeline.trigger_draw_indexed));
DrawArrays(is_indexed);
break;
}
case PICA_REG_INDEX(gs.bool_uniforms):
gs_setup.WriteUniformBoolReg(regs.internal.gs.bool_uniforms.Value());
break;
case PICA_REG_INDEX(gs.int_uniforms[0]):
case PICA_REG_INDEX(gs.int_uniforms[1]):
case PICA_REG_INDEX(gs.int_uniforms[2]):
case PICA_REG_INDEX(gs.int_uniforms[3]): {
const u32 index = (id - PICA_REG_INDEX(gs.int_uniforms[0]));
gs_setup.WriteUniformIntReg(index, regs.internal.gs.GetIntUniform(index));
break;
}
case PICA_REG_INDEX(gs.uniform_setup.set_value[0]):
case PICA_REG_INDEX(gs.uniform_setup.set_value[1]):
case PICA_REG_INDEX(gs.uniform_setup.set_value[2]):
case PICA_REG_INDEX(gs.uniform_setup.set_value[3]):
case PICA_REG_INDEX(gs.uniform_setup.set_value[4]):
case PICA_REG_INDEX(gs.uniform_setup.set_value[5]):
case PICA_REG_INDEX(gs.uniform_setup.set_value[6]):
case PICA_REG_INDEX(gs.uniform_setup.set_value[7]): {
gs_setup.WriteUniformFloatReg(regs.internal.gs, value);
break;
}
case PICA_REG_INDEX(gs.program.set_word[0]):
case PICA_REG_INDEX(gs.program.set_word[1]):
case PICA_REG_INDEX(gs.program.set_word[2]):
case PICA_REG_INDEX(gs.program.set_word[3]):
case PICA_REG_INDEX(gs.program.set_word[4]):
case PICA_REG_INDEX(gs.program.set_word[5]):
case PICA_REG_INDEX(gs.program.set_word[6]):
case PICA_REG_INDEX(gs.program.set_word[7]): {
u32& offset = regs.internal.gs.program.offset;
if (offset >= 4096) {
LOG_ERROR(HW_GPU, "Invalid GS program offset {}", offset);
} else {
gs_setup.program_code[offset] = value;
gs_setup.MarkProgramCodeDirty();
offset++;
}
break;
}
case PICA_REG_INDEX(gs.swizzle_patterns.set_word[0]):
case PICA_REG_INDEX(gs.swizzle_patterns.set_word[1]):
case PICA_REG_INDEX(gs.swizzle_patterns.set_word[2]):
case PICA_REG_INDEX(gs.swizzle_patterns.set_word[3]):
case PICA_REG_INDEX(gs.swizzle_patterns.set_word[4]):
case PICA_REG_INDEX(gs.swizzle_patterns.set_word[5]):
case PICA_REG_INDEX(gs.swizzle_patterns.set_word[6]):
case PICA_REG_INDEX(gs.swizzle_patterns.set_word[7]): {
u32& offset = regs.internal.gs.swizzle_patterns.offset;
if (offset >= gs_setup.swizzle_data.size()) {
LOG_ERROR(HW_GPU, "Invalid GS swizzle pattern offset {}", offset);
} else {
gs_setup.swizzle_data[offset] = value;
gs_setup.MarkSwizzleDataDirty();
offset++;
}
break;
}
case PICA_REG_INDEX(vs.bool_uniforms):
vs_setup.WriteUniformBoolReg(regs.internal.vs.bool_uniforms.Value());
break;
case PICA_REG_INDEX(vs.int_uniforms[0]):
case PICA_REG_INDEX(vs.int_uniforms[1]):
case PICA_REG_INDEX(vs.int_uniforms[2]):
case PICA_REG_INDEX(vs.int_uniforms[3]): {
const u32 index = (id - PICA_REG_INDEX(vs.int_uniforms[0]));
vs_setup.WriteUniformIntReg(index, regs.internal.vs.GetIntUniform(index));
break;
}
case PICA_REG_INDEX(vs.uniform_setup.set_value[0]):
case PICA_REG_INDEX(vs.uniform_setup.set_value[1]):
case PICA_REG_INDEX(vs.uniform_setup.set_value[2]):
case PICA_REG_INDEX(vs.uniform_setup.set_value[3]):
case PICA_REG_INDEX(vs.uniform_setup.set_value[4]):
case PICA_REG_INDEX(vs.uniform_setup.set_value[5]):
case PICA_REG_INDEX(vs.uniform_setup.set_value[6]):
case PICA_REG_INDEX(vs.uniform_setup.set_value[7]): {
vs_setup.WriteUniformFloatReg(regs.internal.vs, value);
break;
}
case PICA_REG_INDEX(vs.program.set_word[0]):
case PICA_REG_INDEX(vs.program.set_word[1]):
case PICA_REG_INDEX(vs.program.set_word[2]):
case PICA_REG_INDEX(vs.program.set_word[3]):
case PICA_REG_INDEX(vs.program.set_word[4]):
case PICA_REG_INDEX(vs.program.set_word[5]):
case PICA_REG_INDEX(vs.program.set_word[6]):
case PICA_REG_INDEX(vs.program.set_word[7]): {
u32& offset = regs.internal.vs.program.offset;
if (offset >= 512) {
LOG_ERROR(HW_GPU, "Invalid VS program offset {}", offset);
} else {
vs_setup.program_code[offset] = value;
vs_setup.MarkProgramCodeDirty();
if (!regs.internal.pipeline.gs_unit_exclusive_configuration) {
gs_setup.program_code[offset] = value;
gs_setup.MarkProgramCodeDirty();
}
offset++;
}
break;
}
case PICA_REG_INDEX(vs.swizzle_patterns.set_word[0]):
case PICA_REG_INDEX(vs.swizzle_patterns.set_word[1]):
case PICA_REG_INDEX(vs.swizzle_patterns.set_word[2]):
case PICA_REG_INDEX(vs.swizzle_patterns.set_word[3]):
case PICA_REG_INDEX(vs.swizzle_patterns.set_word[4]):
case PICA_REG_INDEX(vs.swizzle_patterns.set_word[5]):
case PICA_REG_INDEX(vs.swizzle_patterns.set_word[6]):
case PICA_REG_INDEX(vs.swizzle_patterns.set_word[7]): {
u32& offset = regs.internal.vs.swizzle_patterns.offset;
if (offset >= vs_setup.swizzle_data.size()) {
LOG_ERROR(HW_GPU, "Invalid VS swizzle pattern offset {}", offset);
} else {
vs_setup.swizzle_data[offset] = value;
vs_setup.MarkSwizzleDataDirty();
if (!regs.internal.pipeline.gs_unit_exclusive_configuration) {
gs_setup.swizzle_data[offset] = value;
gs_setup.MarkSwizzleDataDirty();
}
offset++;
}
break;
}
case PICA_REG_INDEX(lighting.lut_data[0]):
case PICA_REG_INDEX(lighting.lut_data[1]):
case PICA_REG_INDEX(lighting.lut_data[2]):
case PICA_REG_INDEX(lighting.lut_data[3]):
case PICA_REG_INDEX(lighting.lut_data[4]):
case PICA_REG_INDEX(lighting.lut_data[5]):
case PICA_REG_INDEX(lighting.lut_data[6]):
case PICA_REG_INDEX(lighting.lut_data[7]): {
auto& lut_config = regs.internal.lighting.lut_config;
ASSERT_MSG(lut_config.index < 256, "lut_config.index exceeded maximum value of 255!");
lighting.luts[lut_config.type][lut_config.index].raw = value;
lut_config.index.Assign(lut_config.index + 1);
break;
}
case PICA_REG_INDEX(texturing.fog_lut_data[0]):
case PICA_REG_INDEX(texturing.fog_lut_data[1]):
case PICA_REG_INDEX(texturing.fog_lut_data[2]):
case PICA_REG_INDEX(texturing.fog_lut_data[3]):
case PICA_REG_INDEX(texturing.fog_lut_data[4]):
case PICA_REG_INDEX(texturing.fog_lut_data[5]):
case PICA_REG_INDEX(texturing.fog_lut_data[6]):
case PICA_REG_INDEX(texturing.fog_lut_data[7]): {
fog.lut[regs.internal.texturing.fog_lut_offset % 128].raw = value;
regs.internal.texturing.fog_lut_offset.Assign(regs.internal.texturing.fog_lut_offset + 1);
break;
}
case PICA_REG_INDEX(texturing.proctex_lut_data[0]):
case PICA_REG_INDEX(texturing.proctex_lut_data[1]):
case PICA_REG_INDEX(texturing.proctex_lut_data[2]):
case PICA_REG_INDEX(texturing.proctex_lut_data[3]):
case PICA_REG_INDEX(texturing.proctex_lut_data[4]):
case PICA_REG_INDEX(texturing.proctex_lut_data[5]):
case PICA_REG_INDEX(texturing.proctex_lut_data[6]):
case PICA_REG_INDEX(texturing.proctex_lut_data[7]): {
auto& index = regs.internal.texturing.proctex_lut_config.index;
switch (regs.internal.texturing.proctex_lut_config.ref_table.Value()) {
case TexturingRegs::ProcTexLutTable::Noise:
proctex.noise_table[index % proctex.noise_table.size()].raw = value;
break;
case TexturingRegs::ProcTexLutTable::ColorMap:
proctex.color_map_table[index % proctex.color_map_table.size()].raw = value;
break;
case TexturingRegs::ProcTexLutTable::AlphaMap:
proctex.alpha_map_table[index % proctex.alpha_map_table.size()].raw = value;
break;
case TexturingRegs::ProcTexLutTable::Color:
proctex.color_table[index % proctex.color_table.size()].raw = value;
break;
case TexturingRegs::ProcTexLutTable::ColorDiff:
proctex.color_diff_table[index % proctex.color_diff_table.size()].raw = value;
break;
}
index.Assign(index + 1);
break;
}
default:
break;
}
// Notify the rasterizer an internal register was updated.
rasterizer->NotifyPicaRegisterChanged(id);
}
void PicaCore::SubmitImmediate(u32 value) {
// Push to word to the queue. This returns true when a full attribute is formed.
if (!immediate.queue.Push(value)) {
return;
}
constexpr size_t IMMEDIATE_MODE_INDEX = 0xF;
auto& setup = regs.internal.pipeline.vs_default_attributes_setup;
if (setup.index > IMMEDIATE_MODE_INDEX) {
LOG_ERROR(HW_GPU, "Invalid VS default attribute index {}", setup.index);
return;
}
// Retrieve the attribute and place it in the default attribute buffer.
const auto attribute = immediate.queue.Get();
if (setup.index < IMMEDIATE_MODE_INDEX) {
input_default_attributes[setup.index] = attribute;
setup.index++;
return;
}
// When index is 0xF the attribute is used for immediate mode drawing.
immediate.input_vertex[immediate.current_attribute] = attribute;
if (immediate.current_attribute < regs.internal.pipeline.max_input_attrib_index) {
immediate.current_attribute++;
return;
}
// We formed a vertex, flush.
DrawImmediate();
}
void PicaCore::DrawImmediate() {
// Compile the vertex shader.
shader_engine->SetupBatch(vs_setup, regs.internal.vs.main_offset);
// Track vertex in the debug recorder.
debug_context.OnEvent(DebugContext::Event::VertexShaderInvocation,
std::addressof(immediate.input_vertex));
SCOPE_EXIT({ debug_context.OnEvent(DebugContext::Event::FinishedPrimitiveBatch, nullptr); });
ShaderUnit shader_unit;
AttributeBuffer output{};
// Invoke the vertex shader for the vertex.
shader_unit.LoadInput(regs.internal.vs, immediate.input_vertex);
shader_engine->Run(vs_setup, shader_unit);
shader_unit.WriteOutput(regs.internal.vs, output);
// Reconfigure geometry pipeline if needed.
if (immediate.reset_geometry_pipeline) {
geometry_pipeline.Reconfigure();
immediate.reset_geometry_pipeline = false;
}
// Send to geometry pipeline.
ASSERT(!geometry_pipeline.NeedIndexInput());
geometry_pipeline.Setup(shader_engine.get());
geometry_pipeline.SubmitVertex(output);
// Flush the immediate triangle.
rasterizer->DrawTriangles();
immediate.current_attribute = 0;
}
void PicaCore::DrawArrays(bool is_indexed) {
MICROPROFILE_SCOPE(GPU_Drawing);
// Track vertex in the debug recorder.
debug_context.OnEvent(DebugContext::Event::IncomingPrimitiveBatch, nullptr);
SCOPE_EXIT({ debug_context.OnEvent(DebugContext::Event::FinishedPrimitiveBatch, nullptr); });
const bool accelerate_draw = [this] {
// Geometry shaders cannot be accelerated due to register preservation.
if (regs.internal.pipeline.use_gs == PipelineRegs::UseGS::Yes) {
return false;
}
// TODO (wwylele): for Strip/Fan topology, if the primitive assember is not restarted
// after this draw call, the buffered vertex from this draw should "leak" to the next
// draw, in which case we should buffer the vertex into the software primitive assember,
// or disable accelerate draw completely. However, there is not game found yet that does
// this, so this is left unimplemented for now. Revisit this when an issue is found in
// games.
bool accelerate_draw = Settings::values.use_hw_shader && primitive_assembler.IsEmpty();
const auto topology = primitive_assembler.GetTopology();
if (topology == PipelineRegs::TriangleTopology::Shader ||
topology == PipelineRegs::TriangleTopology::List) {
accelerate_draw = accelerate_draw && (regs.internal.pipeline.num_vertices % 3) == 0;
}
return accelerate_draw;
}();
// Attempt to use hardware vertex shaders if possible.
if (accelerate_draw && rasterizer->AccelerateDrawBatch(is_indexed)) {
return;
}
// We cannot accelerate the draw, so load and execute the vertex shader for each vertex.
LoadVertices(is_indexed);
// Draw emitted triangles.
rasterizer->DrawTriangles();
}
void PicaCore::LoadVertices(bool is_indexed) {
// Read and validate vertex information from the loaders
const auto& pipeline = regs.internal.pipeline;
const PAddr base_address = pipeline.vertex_attributes.GetPhysicalBaseAddress();
const auto loader = VertexLoader(memory, pipeline);
regs.internal.rasterizer.ValidateSemantics();
// Locate index buffer.
const auto& index_info = pipeline.index_array;
const u8* index_address_8 = memory.GetPhysicalPointer(base_address + index_info.offset);
const u16* index_address_16 = reinterpret_cast<const u16*>(index_address_8);
const bool index_u16 = index_info.format != 0;
// Simple circular-replacement vertex cache
const std::size_t VERTEX_CACHE_SIZE = 64;
std::array<bool, VERTEX_CACHE_SIZE> vertex_cache_valid{};
std::array<u16, VERTEX_CACHE_SIZE> vertex_cache_ids;
std::array<AttributeBuffer, VERTEX_CACHE_SIZE> vertex_cache;
u32 vertex_cache_pos = 0;
// Compile the vertex shader for this batch.
ShaderUnit shader_unit;
AttributeBuffer vs_output;
shader_engine->SetupBatch(vs_setup, regs.internal.vs.main_offset);
// Setup geometry pipeline in case we are using a geometry shader.
geometry_pipeline.Reconfigure();
geometry_pipeline.Setup(shader_engine.get());
ASSERT(!geometry_pipeline.NeedIndexInput() || is_indexed);
for (u32 index = 0; index < pipeline.num_vertices; ++index) {
// Indexed rendering doesn't use the start offset
const u32 vertex = is_indexed
? (index_u16 ? index_address_16[index] : index_address_8[index])
: (index + pipeline.vertex_offset);
bool vertex_cache_hit = false;
if (is_indexed) {
if (geometry_pipeline.NeedIndexInput()) {
geometry_pipeline.SubmitIndex(vertex);
continue;
}
for (u32 i = 0; i < VERTEX_CACHE_SIZE; ++i) {
if (vertex_cache_valid[i] && vertex == vertex_cache_ids[i]) {
vs_output = vertex_cache[i];
vertex_cache_hit = true;
break;
}
}
}
if (!vertex_cache_hit) {
// Initialize data for the current vertex
AttributeBuffer input;
loader.LoadVertex(base_address, index, vertex, input, input_default_attributes);
// Record vertex processing to the debugger.
debug_context.OnEvent(DebugContext::Event::VertexShaderInvocation,
std::addressof(input));
// Invoke the vertex shader for this vertex.
shader_unit.LoadInput(regs.internal.vs, input);
shader_engine->Run(vs_setup, shader_unit);
shader_unit.WriteOutput(regs.internal.vs, vs_output);
// Cache the vertex when doing indexed rendering.
if (is_indexed) {
vertex_cache[vertex_cache_pos] = vs_output;
vertex_cache_valid[vertex_cache_pos] = true;
vertex_cache_ids[vertex_cache_pos] = vertex;
vertex_cache_pos = (vertex_cache_pos + 1) % VERTEX_CACHE_SIZE;
}
}
// Send to geometry pipeline
geometry_pipeline.SubmitVertex(vs_output);
}
}
template <class Archive>
void PicaCore::CommandList::serialize(Archive& ar, const u32 file_version) {
ar& addr;
ar& length;
ar& current_index;
if (Archive::is_loading::value) {
const u8* ptr = Core::System::GetInstance().Memory().GetPhysicalPointer(addr);
head = reinterpret_cast<const u32*>(ptr);
}
}
SERIALIZE_IMPL(PicaCore::CommandList)
} // namespace Pica

View file

@ -0,0 +1,287 @@
// Copyright 2023 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#pragma once
#include "core/hle/service/gsp/gsp_interrupt.h"
#include "video_core/pica/geometry_pipeline.h"
#include "video_core/pica/packed_attribute.h"
#include "video_core/pica/primitive_assembly.h"
#include "video_core/pica/regs_external.h"
#include "video_core/pica/regs_internal.h"
#include "video_core/pica/regs_lcd.h"
#include "video_core/pica/shader_setup.h"
#include "video_core/pica/shader_unit.h"
namespace Memory {
class MemorySystem;
}
namespace VideoCore {
class RasterizerInterface;
}
namespace Pica {
class DebugContext;
class ShaderEngine;
class PicaCore {
public:
explicit PicaCore(Memory::MemorySystem& memory, DebugContext& debug_context_);
~PicaCore();
void BindRasterizer(VideoCore::RasterizerInterface* rasterizer);
void SetInterruptHandler(Service::GSP::InterruptHandler& signal_interrupt);
void ProcessCmdList(PAddr list, u32 size);
private:
void SetFramebufferDefaults();
void WriteInternalReg(u32 id, u32 value, u32 mask);
void SubmitImmediate(u32 data);
void DrawImmediate();
void DrawArrays(bool is_indexed);
void LoadVertices(bool is_indexed);
public:
union Regs {
static constexpr size_t NUM_REGS = 0x732;
struct {
u32 hardware_id;
INSERT_PADDING_WORDS(0x3);
MemoryFillConfig memory_fill_config[2];
u32 vram_bank_control;
u32 gpu_busy;
INSERT_PADDING_WORDS(0x22);
u32 backlight_control;
INSERT_PADDING_WORDS(0xCF);
FramebufferConfig framebuffer_config[2];
INSERT_PADDING_WORDS(0x180);
DisplayTransferConfig display_transfer_config;
INSERT_PADDING_WORDS(0xF5);
RegsInternal internal;
};
std::array<u32, NUM_REGS> reg_array;
};
static_assert(sizeof(Regs) == Regs::NUM_REGS * sizeof(u32));
struct CommandList {
PAddr addr;
const u32* head;
u32 current_index;
u32 length;
void Reset(PAddr addr, const u8* head, u32 size) {
this->addr = addr;
this->head = reinterpret_cast<const u32*>(head);
this->length = size / sizeof(u32);
current_index = 0;
}
private:
friend class boost::serialization::access;
template <class Archive>
void serialize(Archive& ar, const u32 file_version);
};
struct ImmediateModeState {
AttributeBuffer input_vertex{};
u32 current_attribute{};
bool reset_geometry_pipeline{true};
PackedAttribute queue;
void Reset() {
current_attribute = 0;
reset_geometry_pipeline = true;
queue.Reset();
}
private:
friend class boost::serialization::access;
template <class Archive>
void serialize(Archive& ar, const u32 file_version) {
ar& input_vertex;
ar& current_attribute;
ar& reset_geometry_pipeline;
ar& queue;
}
};
struct ProcTex {
union ValueEntry {
u32 raw;
// LUT value, encoded as 12-bit fixed point, with 12 fraction bits
BitField<0, 12, u32> value; // 0.0.12 fixed point
// Difference between two entry values. Used for efficient interpolation.
// 0.0.12 fixed point with two's complement. The range is [-0.5, 0.5).
// Note: the type of this is different from the one of lighting LUT
BitField<12, 12, s32> difference;
f32 ToFloat() const {
return static_cast<f32>(value) / 4095.f;
}
f32 DiffToFloat() const {
return static_cast<f32>(difference) / 4095.f;
}
};
union ColorEntry {
u32 raw;
BitField<0, 8, u32> r;
BitField<8, 8, u32> g;
BitField<16, 8, u32> b;
BitField<24, 8, u32> a;
Common::Vec4<u8> ToVector() const {
return {static_cast<u8>(r), static_cast<u8>(g), static_cast<u8>(b),
static_cast<u8>(a)};
}
};
union ColorDifferenceEntry {
u32 raw;
BitField<0, 8, s32> r; // half of the difference between two ColorEntry
BitField<8, 8, s32> g;
BitField<16, 8, s32> b;
BitField<24, 8, s32> a;
Common::Vec4<s32> ToVector() const {
return Common::Vec4<s32>{r, g, b, a} * 2;
}
};
std::array<ValueEntry, 128> noise_table;
std::array<ValueEntry, 128> color_map_table;
std::array<ValueEntry, 128> alpha_map_table;
std::array<ColorEntry, 256> color_table;
std::array<ColorDifferenceEntry, 256> color_diff_table;
private:
friend class boost::serialization::access;
template <class Archive>
void serialize(Archive& ar, const u32 file_version) {
ar& boost::serialization::make_binary_object(this, sizeof(ProcTex));
}
};
struct Lighting {
union LutEntry {
// Used for raw access
u32 raw;
// LUT value, encoded as 12-bit fixed point, with 12 fraction bits
BitField<0, 12, u32> value; // 0.0.12 fixed point
// Used for efficient interpolation.
BitField<12, 11, u32> difference; // 0.0.11 fixed point
BitField<23, 1, u32> neg_difference;
f32 ToFloat() const {
return static_cast<f32>(value) / 4095.f;
}
f32 DiffToFloat() const {
const f32 diff = static_cast<f32>(difference) / 2047.f;
return neg_difference ? -diff : diff;
}
template <class Archive>
void serialize(Archive& ar, const u32 file_version) {
ar& raw;
}
};
std::array<std::array<LutEntry, 256>, 24> luts;
private:
friend class boost::serialization::access;
template <class Archive>
void serialize(Archive& ar, const u32 file_version) {
ar& boost::serialization::make_binary_object(this, sizeof(Lighting));
}
};
struct Fog {
union LutEntry {
// Used for raw access
u32 raw;
BitField<0, 13, s32> difference; // 1.1.11 fixed point
BitField<13, 11, u32> value; // 0.0.11 fixed point
f32 ToFloat() const {
return static_cast<f32>(value) / 2047.0f;
}
f32 DiffToFloat() const {
return static_cast<f32>(difference) / 2047.0f;
}
};
std::array<LutEntry, 128> lut;
private:
friend class boost::serialization::access;
template <class Archive>
void serialize(Archive& ar, const u32 file_version) {
ar& boost::serialization::make_binary_object(this, sizeof(Fog));
}
};
RegsLcd regs_lcd{};
Regs regs{};
// TODO: Move these to a separate shader scheduler class
GeometryShaderUnit gs_unit;
ShaderSetup vs_setup;
ShaderSetup gs_setup;
ProcTex proctex{};
Lighting lighting{};
Fog fog{};
AttributeBuffer input_default_attributes{};
ImmediateModeState immediate{};
private:
friend class boost::serialization::access;
template <class Archive>
void serialize(Archive& ar, const u32 file_version) {
ar& regs_lcd;
ar& regs.reg_array;
ar& gs_unit;
ar& vs_setup;
ar& gs_setup;
ar& proctex;
ar& lighting;
ar& fog;
ar& input_default_attributes;
ar& immediate;
ar& geometry_pipeline;
ar& primitive_assembler;
ar& cmd_list;
}
private:
Memory::MemorySystem& memory;
VideoCore::RasterizerInterface* rasterizer;
DebugContext& debug_context;
Service::GSP::InterruptHandler signal_interrupt;
GeometryPipeline geometry_pipeline;
PrimitiveAssembler primitive_assembler;
CommandList cmd_list;
std::unique_ptr<ShaderEngine> shader_engine;
};
#define GPU_REG_INDEX(field_name) (offsetof(Pica::PicaCore::Regs, field_name) / sizeof(u32))
} // namespace Pica

View file

@ -0,0 +1,53 @@
// Copyright 2014 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#include "common/logging/log.h"
#include "video_core/pica/primitive_assembly.h"
namespace Pica {
PrimitiveAssembler::PrimitiveAssembler(PipelineRegs::TriangleTopology topology)
: topology(topology) {}
void PrimitiveAssembler::SubmitVertex(const OutputVertex& vtx,
const TriangleHandler& triangle_handler) {
switch (topology) {
case PipelineRegs::TriangleTopology::List:
case PipelineRegs::TriangleTopology::Shader:
if (buffer_index < 2) {
buffer[buffer_index++] = vtx;
} else {
buffer_index = 0;
if (topology == PipelineRegs::TriangleTopology::Shader && winding) {
triangle_handler(buffer[1], buffer[0], vtx);
winding = false;
} else {
triangle_handler(buffer[0], buffer[1], vtx);
}
}
break;
case PipelineRegs::TriangleTopology::Strip:
case PipelineRegs::TriangleTopology::Fan:
if (strip_ready) {
triangle_handler(buffer[0], buffer[1], vtx);
}
buffer[buffer_index] = vtx;
strip_ready |= (buffer_index == 1);
if (topology == PipelineRegs::TriangleTopology::Strip) {
buffer_index = !buffer_index;
} else if (topology == PipelineRegs::TriangleTopology::Fan) {
buffer_index = 1;
}
break;
default:
LOG_ERROR(HW_GPU, "Unknown triangle topology {:x}:", (int)topology);
break;
}
}
} // namespace Pica

View file

@ -8,61 +8,73 @@
#include <functional>
#include <boost/serialization/access.hpp>
#include <boost/serialization/array.hpp>
#include "video_core/regs_pipeline.h"
#include "video_core/pica/output_vertex.h"
#include "video_core/pica/regs_pipeline.h"
namespace Pica {
/*
/**
* Utility class to build triangles from a series of vertices,
* according to a given triangle topology.
*/
template <typename VertexType>
struct PrimitiveAssembler {
using TriangleHandler =
std::function<void(const VertexType& v0, const VertexType& v1, const VertexType& v2)>;
std::function<void(const OutputVertex&, const OutputVertex&, const OutputVertex&)>;
explicit PrimitiveAssembler(
PipelineRegs::TriangleTopology topology = PipelineRegs::TriangleTopology::List);
/*
/**
* Queues a vertex, builds primitives from the vertex queue according to the given
* triangle topology, and calls triangle_handler for each generated primitive.
* NOTE: We could specify the triangle handler in the constructor, but this way we can
* keep event and handler code next to each other.
*/
void SubmitVertex(const VertexType& vtx, const TriangleHandler& triangle_handler);
void SubmitVertex(const OutputVertex& vtx, const TriangleHandler& triangle_handler);
/**
* Invert the vertex order of the next triangle. Called by geometry shader emitter.
* This only takes effect for TriangleTopology::Shader.
*/
void SetWinding();
void SetWinding() noexcept {
winding = true;
}
/**
* Resets the internal state of the PrimitiveAssembler.
*/
void Reset();
void Reset() {
buffer_index = 0;
strip_ready = false;
winding = false;
}
/**
* Reconfigures the PrimitiveAssembler to use a different triangle topology.
*/
void Reconfigure(PipelineRegs::TriangleTopology topology);
void Reconfigure(PipelineRegs::TriangleTopology topology) {
Reset();
this->topology = topology;
}
/**
* Returns whether the PrimitiveAssembler has an empty internal buffer.
*/
bool IsEmpty() const;
bool IsEmpty() const {
return buffer_index == 0 && !strip_ready;
}
/**
* Returns the current topology.
*/
PipelineRegs::TriangleTopology GetTopology() const;
PipelineRegs::TriangleTopology GetTopology() const {
return topology;
}
private:
PipelineRegs::TriangleTopology topology;
int buffer_index = 0;
std::array<VertexType, 2> buffer;
std::array<OutputVertex, 2> buffer;
bool strip_ready = false;
bool winding = false;
@ -70,7 +82,7 @@ private:
void serialize(Archive& ar, const unsigned int version) {
ar& topology;
ar& buffer_index;
ar& boost::serialization::make_array(buffer.data(), buffer.size());
ar& buffer;
ar& strip_ready;
ar& winding;
}

View file

@ -0,0 +1,217 @@
// Copyright 2023 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#pragma once
#include "common/bit_field.h"
namespace Pica {
/**
* Most physical addresses which GPU registers refer to are 8-byte aligned.
* This function should be used to get the address from a raw register value.
*/
constexpr u32 DecodeAddressRegister(u32 register_value) {
return register_value * 8;
}
/// Components are laid out in reverse byte order, most significant bits first.
enum class PixelFormat : u32 {
RGBA8 = 0,
RGB8 = 1,
RGB565 = 2,
RGB5A1 = 3,
RGBA4 = 4,
};
constexpr u32 BytesPerPixel(Pica::PixelFormat format) {
switch (format) {
case Pica::PixelFormat::RGBA8:
return 4;
case Pica::PixelFormat::RGB8:
return 3;
case Pica::PixelFormat::RGB565:
case Pica::PixelFormat::RGB5A1:
case Pica::PixelFormat::RGBA4:
return 2;
default:
UNREACHABLE();
}
return 0;
}
struct MemoryFillConfig {
u32 address_start;
u32 address_end;
union {
u32 value_32bit;
BitField<0, 16, u32> value_16bit;
// TODO: Verify component order
BitField<0, 8, u32> value_24bit_r;
BitField<8, 8, u32> value_24bit_g;
BitField<16, 8, u32> value_24bit_b;
};
union {
u32 control;
// Setting this field to 1 triggers the memory fill.
// This field also acts as a status flag, and gets reset to 0 upon completion.
BitField<0, 1, u32> trigger;
// Set to 1 upon completion.
BitField<1, 1, u32> finished;
// If both of these bits are unset, then it will fill the memory with a 16 bit value
// 1: fill with 24-bit wide values
BitField<8, 1, u32> fill_24bit;
// 1: fill with 32-bit wide values
BitField<9, 1, u32> fill_32bit;
};
inline u32 GetStartAddress() const {
return DecodeAddressRegister(address_start);
}
inline u32 GetEndAddress() const {
return DecodeAddressRegister(address_end);
}
inline std::string DebugName() const {
return fmt::format("from {:#X} to {:#X} with {}-bit value {:#X}", GetStartAddress(),
GetEndAddress(), fill_32bit ? "32" : (fill_24bit ? "24" : "16"),
value_32bit);
}
};
static_assert(sizeof(MemoryFillConfig) == 0x10);
struct FramebufferConfig {
INSERT_PADDING_WORDS(0x17);
union {
u32 size;
BitField<0, 16, u32> width;
BitField<16, 16, u32> height;
};
INSERT_PADDING_WORDS(0x2);
u32 address_left1;
u32 address_left2;
union {
u32 format;
BitField<0, 3, PixelFormat> color_format;
};
INSERT_PADDING_WORDS(0x1);
union {
u32 active_fb;
// 0: Use parameters ending with "1"
// 1: Use parameters ending with "2"
BitField<0, 1, u32> second_fb_active;
};
INSERT_PADDING_WORDS(0x5);
// Distance between two pixel rows, in bytes
u32 stride;
u32 address_right1;
u32 address_right2;
INSERT_PADDING_WORDS(0x19);
};
static_assert(sizeof(FramebufferConfig) == 0x100);
struct DisplayTransferConfig {
u32 input_address;
u32 output_address;
inline u32 GetPhysicalInputAddress() const {
return DecodeAddressRegister(input_address);
}
inline u32 GetPhysicalOutputAddress() const {
return DecodeAddressRegister(output_address);
}
inline std::string DebugName() const noexcept {
return fmt::format("from {:#x} to {:#x} with {} scaling and stride {}, width {}",
GetPhysicalInputAddress(), GetPhysicalOutputAddress(),
scaling == NoScale ? "no" : (scaling == ScaleX ? "X" : "XY"),
input_width.Value(), output_width.Value());
}
union {
u32 output_size;
BitField<0, 16, u32> output_width;
BitField<16, 16, u32> output_height;
};
union {
u32 input_size;
BitField<0, 16, u32> input_width;
BitField<16, 16, u32> input_height;
};
enum ScalingMode : u32 {
NoScale = 0, // Doesn't scale the image
ScaleX = 1, // Downscales the image in half in the X axis and applies a box filter
ScaleXY =
2, // Downscales the image in half in both the X and Y axes and applies a box filter
};
union {
u32 flags;
BitField<0, 1, u32> flip_vertically; // flips input data vertically
BitField<1, 1, u32> input_linear; // Converts from linear to tiled format
BitField<2, 1, u32> crop_input_lines;
BitField<3, 1, u32> is_texture_copy; // Copies the data without performing any
// processing and respecting texture copy fields
BitField<5, 1, u32> dont_swizzle;
BitField<8, 3, PixelFormat> input_format;
BitField<12, 3, PixelFormat> output_format;
/// Uses some kind of 32x32 block swizzling mode, instead of the usual 8x8 one.
BitField<16, 1, u32> block_32; // TODO(yuriks): unimplemented
BitField<24, 2, ScalingMode> scaling; // Determines the scaling mode of the transfer
};
INSERT_PADDING_WORDS(0x1);
// it seems that writing to this field triggers the display transfer
BitField<0, 1, u32> trigger;
INSERT_PADDING_WORDS(0x1);
struct {
u32 size; // The lower 4 bits are ignored
union {
u32 input_size;
BitField<0, 16, u32> input_width;
BitField<16, 16, u32> input_gap;
};
union {
u32 output_size;
BitField<0, 16, u32> output_width;
BitField<16, 16, u32> output_gap;
};
} texture_copy;
};
static_assert(sizeof(DisplayTransferConfig) == 0x2c);
} // namespace Pica

View file

@ -7,11 +7,11 @@
#include <utility>
#include "common/common_types.h"
#include "video_core/regs.h"
#include "video_core/pica/regs_internal.h"
namespace Pica {
static const std::pair<u16, const char*> register_names[] = {
static constexpr std::pair<u16, const char*> register_names[] = {
{0x010, "GPUREG_FINALIZE"},
{0x040, "GPUREG_FACECULLING_CONFIG"},
@ -474,15 +474,15 @@ static const std::pair<u16, const char*> register_names[] = {
{0x2DD, "GPUREG_VSH_OPDESCS_DATA7"},
};
const char* Regs::GetRegisterName(u16 index) {
auto found = std::lower_bound(std::begin(register_names), std::end(register_names), index,
[](auto p, auto i) { return p.first < i; });
if (found->first == index) {
return found->second;
} else {
// Return empty string if no match is found
return "";
const char* RegsInternal::GetRegisterName(u16 index) {
const auto it = std::lower_bound(std::begin(register_names), std::end(register_names), index,
[](auto p, auto i) { return p.first < i; });
if (it->first == index) {
return it->second;
}
// Return empty string if no match is found
return "";
}
} // namespace Pica

View file

@ -3,18 +3,19 @@
// Refer to the license.txt file included.
#pragma once
#include "video_core/regs_framebuffer.h"
#include "video_core/regs_lighting.h"
#include "video_core/regs_pipeline.h"
#include "video_core/regs_rasterizer.h"
#include "video_core/regs_shader.h"
#include "video_core/regs_texturing.h"
#include "video_core/pica/regs_framebuffer.h"
#include "video_core/pica/regs_lighting.h"
#include "video_core/pica/regs_pipeline.h"
#include "video_core/pica/regs_rasterizer.h"
#include "video_core/pica/regs_shader.h"
#include "video_core/pica/regs_texturing.h"
namespace Pica {
#define PICA_REG_INDEX(field_name) (offsetof(Pica::Regs, field_name) / sizeof(u32))
#define PICA_REG_INDEX(field_name) (offsetof(Pica::RegsInternal, field_name) / sizeof(u32))
struct Regs {
struct RegsInternal {
static constexpr std::size_t NUM_REGS = 0x300;
union {
@ -38,10 +39,11 @@ struct Regs {
static const char* GetRegisterName(u16 index);
};
static_assert(sizeof(Regs) == Regs::NUM_REGS * sizeof(u32), "Regs struct has wrong size");
static_assert(sizeof(RegsInternal) == RegsInternal::NUM_REGS * sizeof(u32),
"Regs struct has wrong size");
#define ASSERT_REG_POSITION(field_name, position) \
static_assert(offsetof(Regs, field_name) == position * 4, \
static_assert(offsetof(RegsInternal, field_name) == position * 4, \
"Field " #field_name " has invalid position")
ASSERT_REG_POSITION(trigger_irq, 0x10);
@ -110,4 +112,5 @@ ASSERT_REG_POSITION(gs, 0x280);
ASSERT_REG_POSITION(vs, 0x2b0);
#undef ASSERT_REG_POSITION
} // namespace Pica

View file

@ -0,0 +1,78 @@
// Copyright 2023 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#pragma once
#include <boost/serialization/access.hpp>
#include "common/bit_field.h"
#include "common/common_funcs.h"
#include "common/common_types.h"
#include "common/vector_math.h"
#define LCD_REG_INDEX(field_name) (offsetof(Pica::RegsLcd, field_name) / sizeof(u32))
namespace Pica {
union ColorFill {
u32 raw;
BitField<0, 8, u32> color_r;
BitField<8, 8, u32> color_g;
BitField<16, 8, u32> color_b;
BitField<24, 1, u32> is_enabled;
Common::Vec3<u8> AsVector() const noexcept {
return Common::MakeVec<u8>(color_r, color_g, color_b);
}
};
struct RegsLcd {
INSERT_PADDING_WORDS(0x81);
ColorFill color_fill_top;
INSERT_PADDING_WORDS(0xE);
u32 backlight_top;
INSERT_PADDING_WORDS(0x1F0);
ColorFill color_fill_bottom;
INSERT_PADDING_WORDS(0xE);
u32 backlight_bottom;
INSERT_PADDING_WORDS(0x16F);
static constexpr std::size_t NumIds() {
return sizeof(RegsLcd) / sizeof(u32);
}
const u32& operator[](int index) const {
const u32* content = reinterpret_cast<const u32*>(this);
return content[index];
}
u32& operator[](int index) {
u32* content = reinterpret_cast<u32*>(this);
return content[index];
}
private:
template <class Archive>
void serialize(Archive& ar, const unsigned int) {
ar& color_fill_top.raw;
ar& backlight_top;
ar& color_fill_bottom.raw;
ar& backlight_bottom;
}
friend class boost::serialization::access;
};
static_assert(std::is_standard_layout_v<RegsLcd>, "Structure does not use standard layout");
#define ASSERT_REG_POSITION(field_name, position) \
static_assert(offsetof(RegsLcd, field_name) == position * 4, \
"Field " #field_name " has invalid position")
ASSERT_REG_POSITION(color_fill_top, 0x81);
ASSERT_REG_POSITION(backlight_top, 0x90);
ASSERT_REG_POSITION(color_fill_bottom, 0x281);
ASSERT_REG_POSITION(backlight_bottom, 0x290);
#undef ASSERT_REG_POSITION
} // namespace Pica

View file

@ -26,16 +26,16 @@ struct LightingRegs {
DistanceAttenuation = 16,
};
static constexpr unsigned NumLightingSampler = 24;
static constexpr u32 NumLightingSampler = 24;
static LightingSampler SpotlightAttenuationSampler(unsigned index) {
static LightingSampler SpotlightAttenuationSampler(u32 index) {
return static_cast<LightingSampler>(
static_cast<unsigned>(LightingSampler::SpotlightAttenuation) + index);
static_cast<u32>(LightingSampler::SpotlightAttenuation) + index);
}
static LightingSampler DistanceAttenuationSampler(unsigned index) {
return static_cast<LightingSampler>(
static_cast<unsigned>(LightingSampler::DistanceAttenuation) + index);
static LightingSampler DistanceAttenuationSampler(u32 index) {
return static_cast<LightingSampler>(static_cast<u32>(LightingSampler::DistanceAttenuation) +
index);
}
/**

View file

@ -20,6 +20,20 @@ struct PipelineRegs {
FLOAT = 3,
};
static u32 GetFormatBytes(VertexAttributeFormat format) {
switch (format) {
case VertexAttributeFormat::FLOAT:
return 4;
case VertexAttributeFormat::SHORT:
return 2;
case VertexAttributeFormat::BYTE:
case VertexAttributeFormat::UBYTE:
return 1;
default:
UNREACHABLE();
}
}
struct {
BitField<1, 28, u32> base_address;
@ -194,14 +208,14 @@ struct PipelineRegs {
BitField<0, 28, u32> addr[2]; ///< Physical address / 8 of each channel's command buffer
u32 trigger[2]; ///< Triggers execution of the channel's command buffer when written to
unsigned GetSize(unsigned index) const {
u32 GetSize(u32 index) const {
ASSERT(index < 2);
return 8 * size[index];
}
PAddr GetPhysicalAddress(unsigned index) const {
PAddr GetPhysicalAddress(u32 index) const {
ASSERT(index < 2);
return (PAddr)(8 * addr[index]);
return 8 * addr[index];
}
} command_buffer;

View file

@ -104,6 +104,17 @@ struct RasterizerRegs {
u32 raw;
} vs_output_attributes[7];
void ValidateSemantics() {
for (std::size_t attrib = 0; attrib < vs_output_total; ++attrib) {
const u32 output_register_map = vs_output_attributes[attrib].raw;
for (std::size_t comp = 0; comp < 4; ++comp) {
const u32 semantic = (output_register_map >> (8 * comp)) & 0x1F;
ASSERT_MSG(semantic < 24 || semantic == VSOutputAttributes::INVALID,
"Invalid/unknown semantic id: {}", semantic);
}
}
}
INSERT_PADDING_WORDS(0xe);
enum class ScissorMode : u32 {

View file

@ -4,11 +4,10 @@
#pragma once
#include <array>
#include "common/bit_field.h"
#include "common/common_funcs.h"
#include "common/common_types.h"
#include "common/vector_math.h"
namespace Pica {
@ -22,6 +21,11 @@ struct ShaderRegs {
BitField<24, 8, u32> w;
} int_uniforms[4];
Common::Vec4<u8> GetIntUniform(u32 index) const {
const auto& values = int_uniforms[index];
return Common::MakeVec<u8>(values.x, values.y, values.z, values.w);
}
INSERT_PADDING_WORDS(0x4);
enum ShaderMode {
@ -55,13 +59,13 @@ struct ShaderRegs {
INSERT_PADDING_WORDS(0x2);
struct {
enum Format : u32 {
FLOAT24 = 0,
FLOAT32 = 1,
enum class Format : u32 {
Float24 = 0,
Float32 = 1,
};
bool IsFloat32() const {
return format == FLOAT32;
return format == Format::Float32;
}
union {
@ -70,7 +74,6 @@ struct ShaderRegs {
// indices
// TODO: Maybe the uppermost index is for the geometry shader? Investigate!
BitField<0, 7, u32> index;
BitField<31, 1, Format> format;
};

View file

@ -0,0 +1,61 @@
// Copyright 2023 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#include "common/bit_set.h"
#include "common/hash.h"
#include "video_core/pica/regs_shader.h"
#include "video_core/pica/shader_setup.h"
namespace Pica {
ShaderSetup::ShaderSetup() = default;
ShaderSetup::~ShaderSetup() = default;
void ShaderSetup::WriteUniformBoolReg(u32 value) {
const auto bits = BitSet32(value);
for (u32 i = 0; i < uniforms.b.size(); ++i) {
uniforms.b[i] = bits[i];
}
}
void ShaderSetup::WriteUniformIntReg(u32 index, const Common::Vec4<u8> values) {
ASSERT(index < uniforms.i.size());
uniforms.i[index] = values;
}
void ShaderSetup::WriteUniformFloatReg(ShaderRegs& config, u32 value) {
auto& uniform_setup = config.uniform_setup;
const bool is_float32 = uniform_setup.IsFloat32();
if (!uniform_queue.Push(value, is_float32)) {
return;
}
const auto uniform = uniform_queue.Get(is_float32);
if (uniform_setup.index >= uniforms.f.size()) {
LOG_ERROR(HW_GPU, "Invalid float uniform index {}", uniform_setup.index.Value());
return;
}
uniforms.f[uniform_setup.index] = uniform;
uniform_setup.index.Assign(uniform_setup.index + 1);
}
u64 ShaderSetup::GetProgramCodeHash() {
if (program_code_hash_dirty) {
program_code_hash = Common::ComputeHash64(&program_code, sizeof(program_code));
program_code_hash_dirty = false;
}
return program_code_hash;
}
u64 ShaderSetup::GetSwizzleDataHash() {
if (swizzle_data_hash_dirty) {
swizzle_data_hash = Common::ComputeHash64(&swizzle_data, sizeof(swizzle_data));
swizzle_data_hash_dirty = false;
}
return swizzle_data_hash;
}
} // namespace Pica

View file

@ -0,0 +1,103 @@
// Copyright 2023 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#pragma once
#include "common/vector_math.h"
#include "video_core/pica/packed_attribute.h"
#include "video_core/pica_types.h"
namespace Pica {
constexpr u32 MAX_PROGRAM_CODE_LENGTH = 4096;
constexpr u32 MAX_SWIZZLE_DATA_LENGTH = 4096;
using ProgramCode = std::array<u32, MAX_PROGRAM_CODE_LENGTH>;
using SwizzleData = std::array<u32, MAX_SWIZZLE_DATA_LENGTH>;
struct Uniforms {
alignas(16) std::array<Common::Vec4<f24>, 96> f;
std::array<bool, 16> b;
std::array<Common::Vec4<u8>, 4> i;
static size_t GetFloatUniformOffset(u32 index) {
return offsetof(Uniforms, f) + index * sizeof(Common::Vec4<f24>);
}
static size_t GetBoolUniformOffset(u32 index) {
return offsetof(Uniforms, b) + index * sizeof(bool);
}
static size_t GetIntUniformOffset(u32 index) {
return offsetof(Uniforms, i) + index * sizeof(Common::Vec4<u8>);
}
private:
friend class boost::serialization::access;
template <class Archive>
void serialize(Archive& ar, const u32 file_version) {
ar& f;
ar& b;
ar& i;
}
};
struct ShaderRegs;
/**
* This structure contains the state information common for all shader units such as uniforms.
* The geometry shaders has a unique configuration so when enabled it has its own setup.
*/
struct ShaderSetup {
public:
explicit ShaderSetup();
~ShaderSetup();
void WriteUniformBoolReg(u32 value);
void WriteUniformIntReg(u32 index, const Common::Vec4<u8> values);
void WriteUniformFloatReg(ShaderRegs& config, u32 value);
u64 GetProgramCodeHash();
u64 GetSwizzleDataHash();
void MarkProgramCodeDirty() {
program_code_hash_dirty = true;
}
void MarkSwizzleDataDirty() {
swizzle_data_hash_dirty = true;
}
public:
Uniforms uniforms;
PackedAttribute uniform_queue;
ProgramCode program_code;
SwizzleData swizzle_data;
u32 entry_point;
const void* cached_shader{};
private:
bool program_code_hash_dirty{true};
bool swizzle_data_hash_dirty{true};
u64 program_code_hash{0xDEADC0DE};
u64 swizzle_data_hash{0xDEADC0DE};
friend class boost::serialization::access;
template <class Archive>
void serialize(Archive& ar, const u32 file_version) {
ar& uniforms;
ar& uniform_queue;
ar& program_code;
ar& swizzle_data;
ar& program_code_hash_dirty;
ar& swizzle_data_hash_dirty;
ar& program_code_hash;
ar& swizzle_data_hash;
}
};
} // namespace Pica

View file

@ -0,0 +1,63 @@
// Copyright 2023 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#include "common/bit_set.h"
#include "video_core/pica/regs_shader.h"
#include "video_core/pica/shader_unit.h"
namespace Pica {
ShaderUnit::ShaderUnit(GeometryEmitter* emitter) : emitter_ptr{emitter} {}
ShaderUnit::~ShaderUnit() = default;
void ShaderUnit::LoadInput(const ShaderRegs& config, const AttributeBuffer& buffer) {
const u32 max_attribute = config.max_input_attribute_index;
for (u32 attr = 0; attr <= max_attribute; ++attr) {
const u32 reg = config.GetRegisterForAttribute(attr);
input[reg] = buffer[attr];
}
}
void ShaderUnit::WriteOutput(const ShaderRegs& config, AttributeBuffer& buffer) {
u32 output_index{};
for (u32 reg : Common::BitSet<u32>(config.output_mask)) {
buffer[output_index++] = output[reg];
}
}
void GeometryEmitter::Emit(std::span<Common::Vec4<f24>, 16> output_regs) {
ASSERT(vertex_id < 3);
u32 output_index{};
for (u32 reg : Common::BitSet<u32>(output_mask)) {
buffer[vertex_id][output_index++] = output_regs[reg];
}
if (prim_emit) {
if (winding) {
handlers->winding_setter();
}
for (std::size_t i = 0; i < buffer.size(); ++i) {
handlers->vertex_handler(buffer[i]);
}
}
}
GeometryShaderUnit::GeometryShaderUnit() : ShaderUnit{&emitter} {}
GeometryShaderUnit::~GeometryShaderUnit() = default;
void GeometryShaderUnit::SetVertexHandlers(VertexHandler vertex_handler,
WindingSetter winding_setter) {
emitter.handlers = new Handlers;
emitter.handlers->vertex_handler = vertex_handler;
emitter.handlers->winding_setter = winding_setter;
}
void GeometryShaderUnit::ConfigOutput(const ShaderRegs& config) {
emitter.output_mask = config.output_mask;
}
} // namespace Pica

View file

@ -0,0 +1,120 @@
// Copyright 2023 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#pragma once
#include <functional>
#include <span>
#include <boost/serialization/base_object.hpp>
#include "video_core/pica/output_vertex.h"
namespace Pica {
/// Handler type for receiving vertex outputs from vertex shader or geometry shader
using VertexHandler = std::function<void(const AttributeBuffer&)>;
/// Handler type for signaling to invert the vertex order of the next triangle
using WindingSetter = std::function<void()>;
struct ShaderRegs;
struct GeometryEmitter;
/**
* This structure contains the state information that needs to be unique for a shader unit. The 3DS
* has four shader units that process shaders in parallel.
*/
struct ShaderUnit {
explicit ShaderUnit(GeometryEmitter* emitter = nullptr);
~ShaderUnit();
void LoadInput(const ShaderRegs& config, const AttributeBuffer& input);
void WriteOutput(const ShaderRegs& config, AttributeBuffer& output);
static constexpr size_t InputOffset(s32 register_index) {
return offsetof(ShaderUnit, input) + register_index * sizeof(Common::Vec4<f24>);
}
static constexpr size_t OutputOffset(s32 register_index) {
return offsetof(ShaderUnit, output) + register_index * sizeof(Common::Vec4<f24>);
}
static constexpr size_t TemporaryOffset(s32 register_index) {
return offsetof(ShaderUnit, temporary) + register_index * sizeof(Common::Vec4<f24>);
}
public:
s32 address_registers[3];
bool conditional_code[2];
alignas(16) std::array<Common::Vec4<f24>, 16> input;
alignas(16) std::array<Common::Vec4<f24>, 16> temporary;
alignas(16) std::array<Common::Vec4<f24>, 16> output;
GeometryEmitter* emitter_ptr;
private:
friend class boost::serialization::access;
template <class Archive>
void serialize(Archive& ar, const u32 file_version) {
ar& input;
ar& temporary;
ar& output;
ar& conditional_code;
ar& address_registers;
}
};
struct Handlers {
VertexHandler vertex_handler;
WindingSetter winding_setter;
};
/// This structure contains state information for primitive emitting in geometry shader.
struct GeometryEmitter {
void Emit(std::span<Common::Vec4<f24>, 16> output_regs);
public:
std::array<AttributeBuffer, 3> buffer;
u8 vertex_id;
bool prim_emit;
bool winding;
u32 output_mask;
Handlers* handlers;
private:
friend class boost::serialization::access;
template <class Archive>
void serialize(Archive& ar, const u32 file_version) {
ar& buffer;
ar& vertex_id;
ar& prim_emit;
ar& winding;
ar& output_mask;
}
};
/**
* This is an extended shader unit state that represents the special unit that can run both vertex
* shader and geometry shader. It contains an additional primitive emitter and utilities for
* geometry shader.
*/
struct GeometryShaderUnit : public ShaderUnit {
GeometryShaderUnit();
~GeometryShaderUnit();
void SetVertexHandlers(VertexHandler vertex_handler, WindingSetter winding_setter);
void ConfigOutput(const ShaderRegs& config);
GeometryEmitter emitter;
private:
friend class boost::serialization::access;
template <class Archive>
void serialize(Archive& ar, const u32 file_version) {
ar& boost::serialization::base_object<ShaderUnit>(*this);
ar& emitter;
}
};
} // namespace Pica

View file

@ -0,0 +1,109 @@
// Copyright 2023 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#include "common/alignment.h"
#include "common/logging/log.h"
#include "video_core/pica/vertex_loader.h"
namespace Pica {
VertexLoader::VertexLoader(Memory::MemorySystem& memory_, const PipelineRegs& regs)
: memory{memory_} {
const auto& attribute_config = regs.vertex_attributes;
num_total_attributes = attribute_config.GetNumTotalAttributes();
vertex_attribute_sources.fill(0xdeadbeef);
for (u32 i = 0; i < 16; i++) {
vertex_attribute_is_default[i] = attribute_config.IsDefaultAttribute(i);
}
// Setup attribute data from loaders
for (u32 loader = 0; loader < 12; ++loader) {
const auto& loader_config = attribute_config.attribute_loaders[loader];
u32 offset = 0;
// TODO: What happens if a loader overwrites a previous one's data?
for (u32 component = 0; component < loader_config.component_count; ++component) {
if (component >= 12) {
LOG_ERROR(HW_GPU,
"Overflow in the vertex attribute loader {} trying to load component {}",
loader, component);
continue;
}
u32 attribute_index = loader_config.GetComponent(component);
if (attribute_index < 12) {
offset = Common::AlignUp(offset,
attribute_config.GetElementSizeInBytes(attribute_index));
vertex_attribute_sources[attribute_index] = loader_config.data_offset + offset;
vertex_attribute_strides[attribute_index] =
static_cast<u32>(loader_config.byte_count);
vertex_attribute_formats[attribute_index] =
attribute_config.GetFormat(attribute_index);
vertex_attribute_elements[attribute_index] =
attribute_config.GetNumElements(attribute_index);
offset += attribute_config.GetStride(attribute_index);
} else if (attribute_index < 16) {
// Attribute ids 12, 13, 14 and 15 signify 4, 8, 12 and 16-byte paddings,
// respectively
offset = Common::AlignUp(offset, 4);
offset += (attribute_index - 11) * 4;
} else {
UNREACHABLE(); // This is truly unreachable due to the number of bits for each
// component
}
}
}
}
VertexLoader::~VertexLoader() = default;
void VertexLoader::LoadVertex(PAddr base_address, u32 index, u32 vertex, AttributeBuffer& input,
AttributeBuffer& input_default_attributes) const {
for (s32 i = 0; i < num_total_attributes; ++i) {
// Load the default attribute if we're configured to do so
if (vertex_attribute_is_default[i]) {
input[i] = input_default_attributes[i];
continue;
}
// TODO(yuriks): In this case, no data gets loaded and the vertex
// remains with the last value it had. This isn't currently maintained
// as global state, however, and so won't work in Citra yet.
if (vertex_attribute_elements[i] == 0) {
LOG_ERROR(HW_GPU, "Vertex retension unimplemented");
continue;
}
// Load per-vertex data from the loader arrays
const PAddr source_addr =
base_address + vertex_attribute_sources[i] + vertex_attribute_strides[i] * vertex;
switch (vertex_attribute_formats[i]) {
case PipelineRegs::VertexAttributeFormat::BYTE:
LoadAttribute<s8>(source_addr, i, input);
break;
case PipelineRegs::VertexAttributeFormat::UBYTE:
LoadAttribute<u8>(source_addr, i, input);
break;
case PipelineRegs::VertexAttributeFormat::SHORT:
LoadAttribute<s16>(source_addr, i, input);
break;
case PipelineRegs::VertexAttributeFormat::FLOAT:
LoadAttribute<f32>(source_addr, i, input);
break;
}
// Default attribute values set if array elements have < 4 components. This
// is *not* carried over from the default attribute settings even if they're
// enabled for this attribute.
for (u32 comp = vertex_attribute_elements[i]; comp < 4; comp++) {
input[i][comp] = comp == 3 ? f24::One() : f24::Zero();
}
}
}
} // namespace Pica

View file

@ -0,0 +1,47 @@
// Copyright 2023 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#pragma once
#include "core/memory.h"
#include "video_core/pica/output_vertex.h"
#include "video_core/pica/regs_pipeline.h"
namespace Memory {
class MemorySystem;
}
namespace Pica {
class VertexLoader {
public:
explicit VertexLoader(Memory::MemorySystem& memory_, const PipelineRegs& regs);
~VertexLoader();
void LoadVertex(PAddr base_address, u32 index, u32 vertex, AttributeBuffer& input,
AttributeBuffer& input_default_attributes) const;
template <typename T>
void LoadAttribute(PAddr source_addr, u32 attrib, AttributeBuffer& out) const {
const T* data = reinterpret_cast<const T*>(memory.GetPhysicalPointer(source_addr));
for (u32 comp = 0; comp < vertex_attribute_elements[attrib]; ++comp) {
out[attrib][comp] = f24::FromFloat32(data[comp]);
}
}
int GetNumTotalAttributes() const {
return num_total_attributes;
}
private:
Memory::MemorySystem& memory;
std::array<u32, 16> vertex_attribute_sources;
std::array<u32, 16> vertex_attribute_strides{};
std::array<PipelineRegs::VertexAttributeFormat, 16> vertex_attribute_formats;
std::array<u32, 16> vertex_attribute_elements{};
std::array<bool, 16> vertex_attribute_is_default;
int num_total_attributes = 0;
};
} // namespace Pica

View file

@ -1,255 +0,0 @@
// Copyright 2016 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#pragma once
#include <array>
#include <boost/serialization/array.hpp>
#include <boost/serialization/split_member.hpp>
#include "common/bit_field.h"
#include "common/common_types.h"
#include "common/vector_math.h"
#include "core/memory.h"
#include "video_core/geometry_pipeline.h"
#include "video_core/primitive_assembly.h"
#include "video_core/regs.h"
#include "video_core/shader/shader.h"
#include "video_core/video_core.h"
// Boost::serialization doesn't like union types for some reason,
// so we need to mark arrays of union values with a special serialization method
template <typename Value, size_t Size>
struct UnionArray : public std::array<Value, Size> {
private:
template <class Archive>
void serialize(Archive& ar, const unsigned int) {
static_assert(sizeof(Value) == sizeof(u32));
ar&* static_cast<u32(*)[Size]>(static_cast<void*>(this->data()));
}
friend class boost::serialization::access;
};
namespace Pica {
/// Struct used to describe current Pica state
struct State {
State();
void Reset();
/// Pica registers
Regs regs;
Shader::ShaderSetup vs;
Shader::ShaderSetup gs;
Shader::AttributeBuffer input_default_attributes;
struct ProcTex {
union ValueEntry {
u32 raw;
// LUT value, encoded as 12-bit fixed point, with 12 fraction bits
BitField<0, 12, u32> value; // 0.0.12 fixed point
// Difference between two entry values. Used for efficient interpolation.
// 0.0.12 fixed point with two's complement. The range is [-0.5, 0.5).
// Note: the type of this is different from the one of lighting LUT
BitField<12, 12, s32> difference;
float ToFloat() const {
return static_cast<float>(value) / 4095.f;
}
float DiffToFloat() const {
return static_cast<float>(difference) / 4095.f;
}
};
union ColorEntry {
u32 raw;
BitField<0, 8, u32> r;
BitField<8, 8, u32> g;
BitField<16, 8, u32> b;
BitField<24, 8, u32> a;
Common::Vec4<u8> ToVector() const {
return {static_cast<u8>(r), static_cast<u8>(g), static_cast<u8>(b),
static_cast<u8>(a)};
}
};
union ColorDifferenceEntry {
u32 raw;
BitField<0, 8, s32> r; // half of the difference between two ColorEntry
BitField<8, 8, s32> g;
BitField<16, 8, s32> b;
BitField<24, 8, s32> a;
Common::Vec4<s32> ToVector() const {
return Common::Vec4<s32>{r, g, b, a} * 2;
}
};
UnionArray<ValueEntry, 128> noise_table;
UnionArray<ValueEntry, 128> color_map_table;
UnionArray<ValueEntry, 128> alpha_map_table;
UnionArray<ColorEntry, 256> color_table;
UnionArray<ColorDifferenceEntry, 256> color_diff_table;
private:
friend class boost::serialization::access;
template <class Archive>
void serialize(Archive& ar, const unsigned int file_version) {
ar& noise_table;
ar& color_map_table;
ar& alpha_map_table;
ar& color_table;
ar& color_diff_table;
}
} proctex;
struct Lighting {
union LutEntry {
// Used for raw access
u32 raw;
// LUT value, encoded as 12-bit fixed point, with 12 fraction bits
BitField<0, 12, u32> value; // 0.0.12 fixed point
// Used for efficient interpolation.
BitField<12, 11, u32> difference; // 0.0.11 fixed point
BitField<23, 1, u32> neg_difference;
float ToFloat() const {
return static_cast<float>(value) / 4095.f;
}
float DiffToFloat() const {
float diff = static_cast<float>(difference) / 2047.f;
return neg_difference ? -diff : diff;
}
template <class Archive>
void serialize(Archive& ar, const unsigned int file_version) {
ar& raw;
}
};
std::array<UnionArray<LutEntry, 256>, 24> luts;
} lighting;
struct {
union LutEntry {
// Used for raw access
u32 raw;
BitField<0, 13, s32> difference; // 1.1.11 fixed point
BitField<13, 11, u32> value; // 0.0.11 fixed point
float ToFloat() const {
return static_cast<float>(value) / 2047.0f;
}
float DiffToFloat() const {
return static_cast<float>(difference) / 2047.0f;
}
};
UnionArray<LutEntry, 128> lut;
} fog;
/// Current Pica command list
struct {
PAddr addr; // This exists only for serialization
const u32* head_ptr;
const u32* current_ptr;
u32 length;
} cmd_list;
/// Struct used to describe immediate mode rendering state
struct ImmediateModeState {
// Used to buffer partial vertices for immediate-mode rendering.
Shader::AttributeBuffer input_vertex;
// Index of the next attribute to be loaded into `input_vertex`.
u32 current_attribute = 0;
// Indicates the immediate mode just started and the geometry pipeline needs to reconfigure
bool reset_geometry_pipeline = true;
private:
friend class boost::serialization::access;
template <class Archive>
void serialize(Archive& ar, const unsigned int file_version) {
ar& input_vertex;
ar& current_attribute;
ar& reset_geometry_pipeline;
}
} immediate;
// the geometry shader needs to be kept in the global state because some shaders relie on
// preserved register value across shader invocation.
// TODO: also bring the three vertex shader units here and implement the shader scheduler.
Shader::GSUnitState gs_unit;
GeometryPipeline geometry_pipeline;
// This is constructed with a dummy triangle topology
PrimitiveAssembler<Shader::OutputVertex> primitive_assembler;
int vs_float_regs_counter = 0;
std::array<u32, 4> vs_uniform_write_buffer{};
int gs_float_regs_counter = 0;
std::array<u32, 4> gs_uniform_write_buffer{};
int default_attr_counter = 0;
std::array<u32, 3> default_attr_write_buffer{};
private:
friend class boost::serialization::access;
template <class Archive>
void serialize(Archive& ar, const unsigned int file_version) {
ar& regs.reg_array;
ar& vs;
ar& gs;
ar& input_default_attributes;
ar& proctex;
ar& lighting.luts;
ar& fog.lut;
ar& cmd_list.addr;
ar& cmd_list.length;
ar& immediate;
ar& gs_unit;
ar& geometry_pipeline;
ar& primitive_assembler;
ar& vs_float_regs_counter;
ar& boost::serialization::make_array(vs_uniform_write_buffer.data(),
vs_uniform_write_buffer.size());
ar& gs_float_regs_counter;
ar& boost::serialization::make_array(gs_uniform_write_buffer.data(),
gs_uniform_write_buffer.size());
ar& default_attr_counter;
ar& boost::serialization::make_array(default_attr_write_buffer.data(),
default_attr_write_buffer.size());
boost::serialization::split_member(ar, *this, file_version);
}
template <class Archive>
void save(Archive& ar, const unsigned int file_version) const {
ar << static_cast<u32>(cmd_list.current_ptr - cmd_list.head_ptr);
}
template <class Archive>
void load(Archive& ar, const unsigned int file_version) {
u32 offset{};
ar >> offset;
cmd_list.head_ptr =
reinterpret_cast<u32*>(VideoCore::g_memory->GetPhysicalPointer(cmd_list.addr));
cmd_list.current_ptr = cmd_list.head_ptr + offset;
}
};
extern State g_state; ///< Current Pica state
} // namespace Pica

View file

@ -1,87 +0,0 @@
// Copyright 2014 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#include "common/logging/log.h"
#include "video_core/primitive_assembly.h"
#include "video_core/regs_pipeline.h"
#include "video_core/shader/shader.h"
namespace Pica {
template <typename VertexType>
PrimitiveAssembler<VertexType>::PrimitiveAssembler(PipelineRegs::TriangleTopology topology)
: topology(topology) {}
template <typename VertexType>
void PrimitiveAssembler<VertexType>::SubmitVertex(const VertexType& vtx,
const TriangleHandler& triangle_handler) {
switch (topology) {
case PipelineRegs::TriangleTopology::List:
case PipelineRegs::TriangleTopology::Shader:
if (buffer_index < 2) {
buffer[buffer_index++] = vtx;
} else {
buffer_index = 0;
if (topology == PipelineRegs::TriangleTopology::Shader && winding) {
triangle_handler(buffer[1], buffer[0], vtx);
winding = false;
} else {
triangle_handler(buffer[0], buffer[1], vtx);
}
}
break;
case PipelineRegs::TriangleTopology::Strip:
case PipelineRegs::TriangleTopology::Fan:
if (strip_ready)
triangle_handler(buffer[0], buffer[1], vtx);
buffer[buffer_index] = vtx;
strip_ready |= (buffer_index == 1);
if (topology == PipelineRegs::TriangleTopology::Strip)
buffer_index = !buffer_index;
else if (topology == PipelineRegs::TriangleTopology::Fan)
buffer_index = 1;
break;
default:
LOG_ERROR(HW_GPU, "Unknown triangle topology {:x}:", (int)topology);
break;
}
}
template <typename VertexType>
void PrimitiveAssembler<VertexType>::SetWinding() {
winding = true;
}
template <typename VertexType>
void PrimitiveAssembler<VertexType>::Reset() {
buffer_index = 0;
strip_ready = false;
winding = false;
}
template <typename VertexType>
void PrimitiveAssembler<VertexType>::Reconfigure(PipelineRegs::TriangleTopology topology) {
Reset();
this->topology = topology;
}
template <typename VertexType>
bool PrimitiveAssembler<VertexType>::IsEmpty() const {
return buffer_index == 0 && strip_ready == false;
}
template <typename VertexType>
PipelineRegs::TriangleTopology PrimitiveAssembler<VertexType>::GetTopology() const {
return topology;
}
// explicitly instantiate use cases
template struct PrimitiveAssembler<Shader::OutputVertex>;
} // namespace Pica

View file

@ -2,10 +2,9 @@
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#include <limits>
#include "common/alignment.h"
#include "core/memory.h"
#include "video_core/pica_state.h"
#include "video_core/pica/pica_core.h"
#include "video_core/rasterizer_accelerated.h"
namespace VideoCore {
@ -22,7 +21,7 @@ static Common::Vec3f LightColor(const Pica::LightingRegs::LightColor& color) {
return Common::Vec3u{color.r, color.g, color.b} / 255.0f;
}
RasterizerAccelerated::HardwareVertex::HardwareVertex(const Pica::Shader::OutputVertex& v,
RasterizerAccelerated::HardwareVertex::HardwareVertex(const Pica::OutputVertex& v,
bool flip_quaternion) {
position[0] = v.pos.x.ToFloat32();
position[1] = v.pos.y.ToFloat32();
@ -52,8 +51,8 @@ RasterizerAccelerated::HardwareVertex::HardwareVertex(const Pica::Shader::Output
}
}
RasterizerAccelerated::RasterizerAccelerated(Memory::MemorySystem& memory_)
: memory{memory_}, regs{Pica::g_state.regs} {
RasterizerAccelerated::RasterizerAccelerated(Memory::MemorySystem& memory_, Pica::PicaCore& pica_)
: memory{memory_}, pica{pica_}, regs{pica.regs.internal} {
fs_uniform_block_data.lighting_lut_dirty.fill(true);
}
@ -82,9 +81,8 @@ static bool AreQuaternionsOpposite(Common::Vec4<f24> qa, Common::Vec4<f24> qb) {
return (Common::Dot(a, b) < 0.f);
}
void RasterizerAccelerated::AddTriangle(const Pica::Shader::OutputVertex& v0,
const Pica::Shader::OutputVertex& v1,
const Pica::Shader::OutputVertex& v2) {
void RasterizerAccelerated::AddTriangle(const Pica::OutputVertex& v0, const Pica::OutputVertex& v1,
const Pica::OutputVertex& v2) {
vertex_batch.emplace_back(v0, false);
vertex_batch.emplace_back(v1, AreQuaternionsOpposite(v0.quat, v1.quat));
vertex_batch.emplace_back(v2, AreQuaternionsOpposite(v0.quat, v2.quat));
@ -146,7 +144,7 @@ void RasterizerAccelerated::SyncEntireState() {
}
SyncGlobalAmbient();
for (unsigned light_index = 0; light_index < 8; light_index++) {
for (u32 light_index = 0; light_index < 8; light_index++) {
SyncLightSpecular0(light_index);
SyncLightSpecular1(light_index);
SyncLightDiffuse(light_index);
@ -162,7 +160,7 @@ void RasterizerAccelerated::SyncEntireState() {
SyncShadowBias();
SyncShadowTextureBias();
for (unsigned tex_index = 0; tex_index < 3; tex_index++) {
for (u32 tex_index = 0; tex_index < 3; tex_index++) {
SyncTextureLodBias(tex_index);
}
}

View file

@ -6,7 +6,6 @@
#include "common/vector_math.h"
#include "video_core/rasterizer_interface.h"
#include "video_core/regs_texturing.h"
#include "video_core/shader/generator/pica_fs_config.h"
#include "video_core/shader/generator/shader_uniforms.h"
@ -15,19 +14,21 @@ class MemorySystem;
}
namespace Pica {
struct Regs;
class PicaCore;
}
namespace VideoCore {
class RasterizerAccelerated : public RasterizerInterface {
public:
RasterizerAccelerated(Memory::MemorySystem& memory);
explicit RasterizerAccelerated(Memory::MemorySystem& memory, Pica::PicaCore& pica);
virtual ~RasterizerAccelerated() = default;
void AddTriangle(const Pica::Shader::OutputVertex& v0, const Pica::Shader::OutputVertex& v1,
const Pica::Shader::OutputVertex& v2) override;
void AddTriangle(const Pica::OutputVertex& v0, const Pica::OutputVertex& v1,
const Pica::OutputVertex& v2) override;
void NotifyPicaRegisterChanged(u32 id) override;
void SyncEntireState() override;
protected:
@ -128,7 +129,7 @@ protected:
/// Structure that the hardware rendered vertices are composed of
struct HardwareVertex {
HardwareVertex() = default;
HardwareVertex(const Pica::Shader::OutputVertex& v, bool flip_quaternion);
HardwareVertex(const Pica::OutputVertex& v, bool flip_quaternion);
Common::Vec4f position;
Common::Vec4f color;
@ -151,7 +152,8 @@ protected:
protected:
Memory::MemorySystem& memory;
Pica::Regs& regs;
Pica::PicaCore& pica;
Pica::RegsInternal& regs;
std::vector<HardwareVertex> vertex_batch;
Pica::Shader::UserConfig user_config{};
@ -159,8 +161,8 @@ protected:
VSUniformBlockData vs_uniform_block_data{};
FSUniformBlockData fs_uniform_block_data{};
std::array<std::array<Common::Vec2f, 256>, Pica::LightingRegs::NumLightingSampler>
lighting_lut_data{};
using LightLUT = std::array<Common::Vec2f, 256>;
std::array<LightLUT, Pica::LightingRegs::NumLightingSampler> lighting_lut_data{};
std::array<Common::Vec2f, 128> fog_lut_data{};
std::array<Common::Vec2f, 128> proctex_noise_lut_data{};
std::array<Common::Vec2f, 128> proctex_color_map_data{};

View file

@ -6,9 +6,9 @@
#include "common/hash.h"
#include "common/math_util.h"
#include "video_core/pica/regs_rasterizer.h"
#include "video_core/rasterizer_cache/slot_id.h"
#include "video_core/rasterizer_cache/surface_params.h"
#include "video_core/regs_rasterizer.h"
namespace VideoCore {

View file

@ -2,6 +2,7 @@
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#include "video_core/pica/regs_external.h"
#include "video_core/rasterizer_cache/pixel_format.h"
namespace VideoCore {
@ -134,17 +135,17 @@ PixelFormat PixelFormatFromDepthFormat(Pica::FramebufferRegs::DepthFormat format
}
}
PixelFormat PixelFormatFromGPUPixelFormat(GPU::Regs::PixelFormat format) {
PixelFormat PixelFormatFromGPUPixelFormat(Pica::PixelFormat format) {
switch (format) {
case GPU::Regs::PixelFormat::RGBA8:
case Pica::PixelFormat::RGBA8:
return PixelFormat::RGBA8;
case GPU::Regs::PixelFormat::RGB8:
case Pica::PixelFormat::RGB8:
return PixelFormat::RGB8;
case GPU::Regs::PixelFormat::RGB565:
case Pica::PixelFormat::RGB565:
return PixelFormat::RGB565;
case GPU::Regs::PixelFormat::RGB5A1:
case Pica::PixelFormat::RGB5A1:
return PixelFormat::RGB5A1;
case GPU::Regs::PixelFormat::RGBA4:
case Pica::PixelFormat::RGBA4:
return PixelFormat::RGBA4;
default:
return PixelFormat::Invalid;

View file

@ -6,9 +6,12 @@
#include <limits>
#include <string_view>
#include "core/hw/gpu.h"
#include "video_core/regs_framebuffer.h"
#include "video_core/regs_texturing.h"
#include "video_core/pica/regs_framebuffer.h"
#include "video_core/pica/regs_texturing.h"
namespace Pica {
enum class PixelFormat : u32;
}
namespace VideoCore {
@ -109,6 +112,6 @@ PixelFormat PixelFormatFromColorFormat(Pica::FramebufferRegs::ColorFormat format
PixelFormat PixelFormatFromDepthFormat(Pica::FramebufferRegs::DepthFormat format);
PixelFormat PixelFormatFromGPUPixelFormat(GPU::Regs::PixelFormat format);
PixelFormat PixelFormatFromGPUPixelFormat(Pica::PixelFormat format);
} // namespace VideoCore

View file

@ -14,9 +14,10 @@
#include "common/settings.h"
#include "core/memory.h"
#include "video_core/custom_textures/custom_tex_manager.h"
#include "video_core/pica/regs_external.h"
#include "video_core/pica/regs_internal.h"
#include "video_core/rasterizer_cache/rasterizer_cache_base.h"
#include "video_core/rasterizer_cache/surface_base.h"
#include "video_core/regs.h"
#include "video_core/renderer_base.h"
#include "video_core/texture/texture_decode.h"
@ -34,7 +35,7 @@ constexpr auto RangeFromInterval(const auto& map, const auto& interval) {
template <class T>
RasterizerCache<T>::RasterizerCache(Memory::MemorySystem& memory_,
CustomTexManager& custom_tex_manager_, Runtime& runtime_,
Pica::Regs& regs_, RendererBase& renderer_)
Pica::RegsInternal& regs_, RendererBase& renderer_)
: memory{memory_}, custom_tex_manager{custom_tex_manager_}, runtime{runtime_}, regs{regs_},
renderer{renderer_}, resolution_scale_factor{renderer.GetResolutionScaleFactor()},
filter{Settings::values.texture_filter.GetValue()},
@ -151,7 +152,7 @@ void RasterizerCache<T>::RemoveTextureCubeFace(SurfaceId surface_id) {
}
template <class T>
bool RasterizerCache<T>::AccelerateTextureCopy(const GPU::Regs::DisplayTransferConfig& config) {
bool RasterizerCache<T>::AccelerateTextureCopy(const Pica::DisplayTransferConfig& config) {
const DebugScope scope{runtime, Common::Vec4f{0.f, 0.f, 1.f, 1.f},
"RasterizerCache::AccelerateTextureCopy ({})", config.DebugName()};
@ -249,7 +250,7 @@ bool RasterizerCache<T>::AccelerateTextureCopy(const GPU::Regs::DisplayTransferC
}
template <class T>
bool RasterizerCache<T>::AccelerateDisplayTransfer(const GPU::Regs::DisplayTransferConfig& config) {
bool RasterizerCache<T>::AccelerateDisplayTransfer(const Pica::DisplayTransferConfig& config) {
const DebugScope scope{runtime, Common::Vec4f{0.f, 0.f, 1.f, 1.f},
"RasterizerCache::AccelerateDisplayTransfer ({})", config.DebugName()};
@ -274,10 +275,9 @@ bool RasterizerCache<T>::AccelerateDisplayTransfer(const GPU::Regs::DisplayTrans
// Using flip_vertically alongside crop_input_lines produces skewed output on hardware.
// We have to emulate this because some games rely on this behaviour to render correctly.
if (config.flip_vertically && config.crop_input_lines &&
config.input_width > config.output_width) {
if (config.flip_vertically && config.crop_input_lines) {
dst_params.addr += (config.input_width - config.output_width) * (config.output_height - 1) *
GPU::Regs::BytesPerPixel(config.output_format);
Pica::BytesPerPixel(config.output_format);
}
auto [src_surface_id, src_rect] = GetSurfaceSubRect(src_params, ScaleMatch::Ignore, true);
@ -320,7 +320,7 @@ bool RasterizerCache<T>::AccelerateDisplayTransfer(const GPU::Regs::DisplayTrans
}
template <class T>
bool RasterizerCache<T>::AccelerateFill(const GPU::Regs::MemoryFillConfig& config) {
bool RasterizerCache<T>::AccelerateFill(const Pica::MemoryFillConfig& config) {
const DebugScope scope{runtime, Common::Vec4f{1.f, 0.f, 1.f, 1.f},
"RasterizerCache::AccelerateFill ({})", config.DebugName()};

View file

@ -12,6 +12,7 @@
#include <vector>
#include <boost/icl/interval_map.hpp>
#include <tsl/robin_map.h>
#include "video_core/rasterizer_cache/framebuffer_base.h"
#include "video_core/rasterizer_cache/sampler_params.h"
#include "video_core/rasterizer_cache/surface_params.h"
@ -22,8 +23,10 @@ class MemorySystem;
}
namespace Pica {
struct Regs;
}
struct RegsInternal;
struct DisplayTransferConfig;
struct MemoryFillConfig;
} // namespace Pica
namespace Pica::Texture {
struct TextureInfo;
@ -74,20 +77,20 @@ class RasterizerCache {
public:
explicit RasterizerCache(Memory::MemorySystem& memory, CustomTexManager& custom_tex_manager,
Runtime& runtime, Pica::Regs& regs, RendererBase& renderer);
Runtime& runtime, Pica::RegsInternal& regs, RendererBase& renderer);
~RasterizerCache();
/// Notify the cache that a new frame has been queued
void TickFrame();
/// Perform hardware accelerated texture copy according to the provided configuration
bool AccelerateTextureCopy(const GPU::Regs::DisplayTransferConfig& config);
bool AccelerateTextureCopy(const Pica::DisplayTransferConfig& config);
/// Perform hardware accelerated display transfer according to the provided configuration
bool AccelerateDisplayTransfer(const GPU::Regs::DisplayTransferConfig& config);
bool AccelerateDisplayTransfer(const Pica::DisplayTransferConfig& config);
/// Perform hardware accelerated memory fill according to the provided configuration
bool AccelerateFill(const GPU::Regs::MemoryFillConfig& config);
bool AccelerateFill(const Pica::MemoryFillConfig& config);
/// Returns a reference to the surface object assigned to surface_id
Surface& GetSurface(SurfaceId surface_id);
@ -212,7 +215,7 @@ private:
Memory::MemorySystem& memory;
CustomTexManager& custom_tex_manager;
Runtime& runtime;
Pica::Regs& regs;
Pica::RegsInternal& regs;
RendererBase& renderer;
std::unordered_map<TextureCubeConfig, TextureCube> texture_cube_cache;
tsl::robin_pg_map<u64, std::vector<SurfaceId>, Common::IdentityHash<u64>> page_table;

View file

@ -6,7 +6,7 @@
#include <compare>
#include "common/hash.h"
#include "video_core/regs_texturing.h"
#include "video_core/pica/regs_texturing.h"
namespace VideoCore {

View file

@ -5,8 +5,8 @@
#pragma once
#include "common/hash.h"
#include "video_core/pica/regs_texturing.h"
#include "video_core/rasterizer_cache/slot_id.h"
#include "video_core/regs_texturing.h"
namespace VideoCore {

View file

@ -7,11 +7,15 @@
#include <atomic>
#include <functional>
#include "common/common_types.h"
#include "core/hw/gpu.h"
namespace Pica::Shader {
namespace Pica {
struct OutputVertex;
} // namespace Pica::Shader
}
namespace Pica {
struct DisplayTransferConfig;
struct MemoryFillConfig;
} // namespace Pica
namespace VideoCore {
@ -29,9 +33,8 @@ public:
virtual ~RasterizerInterface() = default;
/// Queues the primitive formed by the given vertices for rendering
virtual void AddTriangle(const Pica::Shader::OutputVertex& v0,
const Pica::Shader::OutputVertex& v1,
const Pica::Shader::OutputVertex& v2) = 0;
virtual void AddTriangle(const Pica::OutputVertex& v0, const Pica::OutputVertex& v1,
const Pica::OutputVertex& v2) = 0;
/// Draw the current batch of triangles
virtual void DrawTriangles() = 0;
@ -56,19 +59,17 @@ public:
virtual void ClearAll(bool flush) = 0;
/// Attempt to use a faster method to perform a display transfer with is_texture_copy = 0
virtual bool AccelerateDisplayTransfer(
[[maybe_unused]] const GPU::Regs::DisplayTransferConfig& config) {
virtual bool AccelerateDisplayTransfer(const Pica::DisplayTransferConfig&) {
return false;
}
/// Attempt to use a faster method to perform a display transfer with is_texture_copy = 1
virtual bool AccelerateTextureCopy(
[[maybe_unused]] const GPU::Regs::DisplayTransferConfig& config) {
virtual bool AccelerateTextureCopy(const Pica::DisplayTransferConfig&) {
return false;
}
/// Attempt to use a faster method to fill a region
virtual bool AccelerateFill([[maybe_unused]] const GPU::Regs::MemoryFillConfig& config) {
virtual bool AccelerateFill(const Pica::MemoryFillConfig&) {
return false;
}

View file

@ -49,10 +49,6 @@ void RendererBase::EndFrame() {
system.frame_limiter.DoFrameLimiting(system.CoreTiming().GetGlobalTimeUs());
system.perf_stats->BeginSystemFrame();
if (Pica::g_debug_context && Pica::g_debug_context->recorder) {
Pica::g_debug_context->recorder->FrameFinished();
}
}
bool RendererBase::IsScreenshotPending() const {

View file

@ -8,15 +8,12 @@
#include "common/logging/log.h"
#include "common/math_util.h"
#include "common/microprofile.h"
#include "video_core/pica_state.h"
#include "video_core/regs_framebuffer.h"
#include "video_core/regs_rasterizer.h"
#include "video_core/pica/pica_core.h"
#include "video_core/renderer_opengl/gl_rasterizer.h"
#include "video_core/renderer_opengl/pica_to_gl.h"
#include "video_core/renderer_opengl/renderer_opengl.h"
#include "video_core/shader/generator/shader_gen.h"
#include "video_core/texture/texture_decode.h"
#include "video_core/video_core.h"
namespace OpenGL {
@ -76,10 +73,10 @@ GLenum MakeAttributeType(Pica::PipelineRegs::VertexAttributeFormat format) {
} // Anonymous namespace
RasterizerOpenGL::RasterizerOpenGL(Memory::MemorySystem& memory,
RasterizerOpenGL::RasterizerOpenGL(Memory::MemorySystem& memory, Pica::PicaCore& pica,
VideoCore::CustomTexManager& custom_tex_manager,
VideoCore::RendererBase& renderer, Driver& driver_)
: VideoCore::RasterizerAccelerated{memory}, driver{driver_},
: VideoCore::RasterizerAccelerated{memory, pica}, driver{driver_},
shader_manager{renderer.GetRenderWindow(), driver, !driver.IsOpenGLES()},
runtime{driver, renderer}, res_cache{memory, custom_tex_manager, runtime, regs, renderer},
texture_buffer_size{TextureBufferSize()}, vertex_buffer{driver, GL_ARRAY_BUFFER,
@ -259,7 +256,7 @@ void RasterizerOpenGL::SetupVertexArray(u8* array_ptr, GLintptr buffer_offset,
if (vertex_attributes.IsDefaultAttribute(i)) {
const u32 reg = regs.vs.GetRegisterForAttribute(i);
if (!enable_attributes[reg]) {
const auto& attr = Pica::g_state.input_default_attributes.attr[i];
const auto& attr = pica.input_default_attributes[i];
glVertexAttrib4f(reg, attr.x.ToFloat32(), attr.y.ToFloat32(), attr.z.ToFloat32(),
attr.w.ToFloat32());
}
@ -269,7 +266,7 @@ void RasterizerOpenGL::SetupVertexArray(u8* array_ptr, GLintptr buffer_offset,
bool RasterizerOpenGL::SetupVertexShader() {
MICROPROFILE_SCOPE(OpenGL_VS);
return shader_manager.UseProgrammableVertexShader(regs, Pica::g_state.vs);
return shader_manager.UseProgrammableVertexShader(regs, pica.vs_setup);
}
bool RasterizerOpenGL::SetupGeometryShader() {
@ -710,19 +707,19 @@ void RasterizerOpenGL::ClearAll(bool flush) {
res_cache.ClearAll(flush);
}
bool RasterizerOpenGL::AccelerateDisplayTransfer(const GPU::Regs::DisplayTransferConfig& config) {
bool RasterizerOpenGL::AccelerateDisplayTransfer(const Pica::DisplayTransferConfig& config) {
return res_cache.AccelerateDisplayTransfer(config);
}
bool RasterizerOpenGL::AccelerateTextureCopy(const GPU::Regs::DisplayTransferConfig& config) {
bool RasterizerOpenGL::AccelerateTextureCopy(const Pica::DisplayTransferConfig& config) {
return res_cache.AccelerateTextureCopy(config);
}
bool RasterizerOpenGL::AccelerateFill(const GPU::Regs::MemoryFillConfig& config) {
bool RasterizerOpenGL::AccelerateFill(const Pica::MemoryFillConfig& config) {
return res_cache.AccelerateFill(config);
}
bool RasterizerOpenGL::AccelerateDisplay(const GPU::Regs::FramebufferConfig& config,
bool RasterizerOpenGL::AccelerateDisplay(const Pica::FramebufferConfig& config,
PAddr framebuffer_addr, u32 pixel_stride,
ScreenInfo& screen_info) {
if (framebuffer_addr == 0) {
@ -943,7 +940,7 @@ void RasterizerOpenGL::SyncAndUploadLUTsLF() {
for (unsigned index = 0; index < fs_uniform_block_data.lighting_lut_dirty.size(); index++) {
if (fs_uniform_block_data.lighting_lut_dirty[index] || invalidate) {
std::array<Common::Vec2f, 256> new_data;
const auto& source_lut = Pica::g_state.lighting.luts[index];
const auto& source_lut = pica.lighting.luts[index];
std::transform(source_lut.begin(), source_lut.end(), new_data.begin(),
[](const auto& entry) {
return Common::Vec2f{entry.ToFloat(), entry.DiffToFloat()};
@ -968,7 +965,7 @@ void RasterizerOpenGL::SyncAndUploadLUTsLF() {
if (fs_uniform_block_data.fog_lut_dirty || invalidate) {
std::array<Common::Vec2f, 128> new_data;
std::transform(Pica::g_state.fog.lut.begin(), Pica::g_state.fog.lut.end(), new_data.begin(),
std::transform(pica.fog.lut.begin(), pica.fog.lut.end(), new_data.begin(),
[](const auto& entry) {
return Common::Vec2f{entry.ToFloat(), entry.DiffToFloat()};
});
@ -1007,9 +1004,8 @@ void RasterizerOpenGL::SyncAndUploadLUTs() {
// helper function for SyncProcTexNoiseLUT/ColorMap/AlphaMap
const auto sync_proc_tex_value_lut =
[this, buffer = buffer, offset = offset, invalidate = invalidate,
&bytes_used](const std::array<Pica::State::ProcTex::ValueEntry, 128>& lut,
std::array<Common::Vec2f, 128>& lut_data, GLint& lut_offset) {
[this, buffer = buffer, offset = offset, invalidate = invalidate, &bytes_used](
const auto& lut, std::array<Common::Vec2f, 128>& lut_data, GLint& lut_offset) {
std::array<Common::Vec2f, 128> new_data;
std::transform(lut.begin(), lut.end(), new_data.begin(), [](const auto& entry) {
return Common::Vec2f{entry.ToFloat(), entry.DiffToFloat()};
@ -1027,21 +1023,21 @@ void RasterizerOpenGL::SyncAndUploadLUTs() {
// Sync the proctex noise lut
if (fs_uniform_block_data.proctex_noise_lut_dirty || invalidate) {
sync_proc_tex_value_lut(Pica::g_state.proctex.noise_table, proctex_noise_lut_data,
sync_proc_tex_value_lut(pica.proctex.noise_table, proctex_noise_lut_data,
fs_uniform_block_data.data.proctex_noise_lut_offset);
fs_uniform_block_data.proctex_noise_lut_dirty = false;
}
// Sync the proctex color map
if (fs_uniform_block_data.proctex_color_map_dirty || invalidate) {
sync_proc_tex_value_lut(Pica::g_state.proctex.color_map_table, proctex_color_map_data,
sync_proc_tex_value_lut(pica.proctex.color_map_table, proctex_color_map_data,
fs_uniform_block_data.data.proctex_color_map_offset);
fs_uniform_block_data.proctex_color_map_dirty = false;
}
// Sync the proctex alpha map
if (fs_uniform_block_data.proctex_alpha_map_dirty || invalidate) {
sync_proc_tex_value_lut(Pica::g_state.proctex.alpha_map_table, proctex_alpha_map_data,
sync_proc_tex_value_lut(pica.proctex.alpha_map_table, proctex_alpha_map_data,
fs_uniform_block_data.data.proctex_alpha_map_offset);
fs_uniform_block_data.proctex_alpha_map_dirty = false;
}
@ -1050,9 +1046,8 @@ void RasterizerOpenGL::SyncAndUploadLUTs() {
if (fs_uniform_block_data.proctex_lut_dirty || invalidate) {
std::array<Common::Vec4f, 256> new_data;
std::transform(Pica::g_state.proctex.color_table.begin(),
Pica::g_state.proctex.color_table.end(), new_data.begin(),
[](const auto& entry) {
std::transform(pica.proctex.color_table.begin(), pica.proctex.color_table.end(),
new_data.begin(), [](const auto& entry) {
auto rgba = entry.ToVector() / 255.0f;
return Common::Vec4f{rgba.r(), rgba.g(), rgba.b(), rgba.a()};
});
@ -1073,9 +1068,8 @@ void RasterizerOpenGL::SyncAndUploadLUTs() {
if (fs_uniform_block_data.proctex_diff_lut_dirty || invalidate) {
std::array<Common::Vec4f, 256> new_data;
std::transform(Pica::g_state.proctex.color_diff_table.begin(),
Pica::g_state.proctex.color_diff_table.end(), new_data.begin(),
[](const auto& entry) {
std::transform(pica.proctex.color_diff_table.begin(), pica.proctex.color_diff_table.end(),
new_data.begin(), [](const auto& entry) {
auto rgba = entry.ToVector() / 255.0f;
return Common::Vec4f{rgba.r(), rgba.g(), rgba.b(), rgba.a()};
});
@ -1134,7 +1128,7 @@ void RasterizerOpenGL::UploadUniforms(bool accelerate_draw) {
if (sync_vs_pica) {
VSPicaUniformData vs_uniforms;
vs_uniforms.uniforms.SetFromRegs(regs.vs, Pica::g_state.vs);
vs_uniforms.uniforms.SetFromRegs(regs.vs, pica.vs_setup);
std::memcpy(uniforms + used_bytes, &vs_uniforms, sizeof(vs_uniforms));
glBindBufferRange(GL_UNIFORM_BUFFER, UniformBindings::VSPicaData,
uniform_buffer.GetHandle(), offset + used_bytes, sizeof(vs_uniforms));

View file

@ -4,10 +4,8 @@
#pragma once
#include "core/hw/gpu.h"
#include "video_core/rasterizer_accelerated.h"
#include "video_core/rasterizer_interface.h"
#include "video_core/regs_texturing.h"
#include "video_core/renderer_opengl/gl_shader_manager.h"
#include "video_core/renderer_opengl/gl_state.h"
#include "video_core/renderer_opengl/gl_stream_buffer.h"
@ -21,6 +19,12 @@ namespace VideoCore {
class CustomTexManager;
}
namespace Pica {
struct DisplayTransferConfig;
struct MemoryFillConfig;
struct FramebufferConfig;
} // namespace Pica
namespace OpenGL {
struct ScreenInfo;
@ -30,7 +34,7 @@ class ShaderProgramManager;
class RasterizerOpenGL : public VideoCore::RasterizerAccelerated {
public:
explicit RasterizerOpenGL(Memory::MemorySystem& memory,
explicit RasterizerOpenGL(Memory::MemorySystem& memory, Pica::PicaCore& pica,
VideoCore::CustomTexManager& custom_tex_manager,
VideoCore::RendererBase& renderer, Driver& driver);
~RasterizerOpenGL() override;
@ -45,10 +49,10 @@ public:
void InvalidateRegion(PAddr addr, u32 size) override;
void FlushAndInvalidateRegion(PAddr addr, u32 size) override;
void ClearAll(bool flush) override;
bool AccelerateDisplayTransfer(const GPU::Regs::DisplayTransferConfig& config) override;
bool AccelerateTextureCopy(const GPU::Regs::DisplayTransferConfig& config) override;
bool AccelerateFill(const GPU::Regs::MemoryFillConfig& config) override;
bool AccelerateDisplay(const GPU::Regs::FramebufferConfig& config, PAddr framebuffer_addr,
bool AccelerateDisplayTransfer(const Pica::DisplayTransferConfig& config) override;
bool AccelerateTextureCopy(const Pica::DisplayTransferConfig& config) override;
bool AccelerateFill(const Pica::MemoryFillConfig& config) override;
bool AccelerateDisplay(const Pica::FramebufferConfig& config, PAddr framebuffer_addr,
u32 pixel_stride, ScreenInfo& screen_info);
bool AccelerateDrawBatch(bool is_indexed) override;

View file

@ -83,7 +83,7 @@ bool ShaderDiskCacheRaw::Save(FileUtil::IOFile& file) const {
}
// Just for future proofing, save the sizes of the array to the file
const std::size_t reg_array_len = Pica::Regs::NUM_REGS;
const std::size_t reg_array_len = Pica::RegsInternal::NUM_REGS;
if (file.WriteObject(static_cast<u64>(reg_array_len)) != 1) {
return false;
}

View file

@ -4,23 +4,16 @@
#pragma once
#include <algorithm>
#include <array>
#include <bitset>
#include <optional>
#include <string>
#include <tuple>
#include <unordered_map>
#include <utility>
#include <vector>
#include <glad/glad.h>
#include "common/assert.h"
#include "common/common_types.h"
#include "common/file_util.h"
#include "video_core/regs.h"
#include "video_core/shader/generator/glsl_shader_gen.h"
#include "video_core/pica/regs_internal.h"
#include "video_core/shader/generator/shader_gen.h"
namespace Core {
class System;
@ -35,7 +28,7 @@ namespace OpenGL {
struct ShaderDiskCacheDecompiled;
struct ShaderDiskCacheDump;
using RawShaderConfig = Pica::Regs;
using RawShaderConfig = Pica::RegsInternal;
using ProgramCode = std::vector<u32>;
using ProgramType = Pica::Shader::Generator::ProgramType;
using ShaderDecompiledMap = std::unordered_map<u64, ShaderDiskCacheDecompiled>;

View file

@ -3,29 +3,33 @@
// Refer to the license.txt file included.
#include <algorithm>
#include <mutex>
#include <set>
#include <span>
#include <thread>
#include <unordered_map>
#include <variant>
#include "common/settings.h"
#include "core/frontend/emu_window.h"
#include "video_core/pica/shader_setup.h"
#include "video_core/renderer_opengl/gl_driver.h"
#include "video_core/renderer_opengl/gl_resource_manager.h"
#include "video_core/renderer_opengl/gl_shader_disk_cache.h"
#include "video_core/renderer_opengl/gl_shader_manager.h"
#include "video_core/renderer_opengl/gl_state.h"
#include "video_core/shader/generator/glsl_fs_shader_gen.h"
#include "video_core/shader/generator/glsl_shader_gen.h"
#include "video_core/shader/generator/profile.h"
#include "video_core/video_core.h"
using namespace Pica::Shader::Generator;
using Pica::Shader::FSConfig;
namespace OpenGL {
static u64 GetUniqueIdentifier(const Pica::Regs& regs, const ProgramCode& code) {
static u64 GetUniqueIdentifier(const Pica::RegsInternal& regs, const ProgramCode& code) {
std::size_t hash = 0;
u64 regs_uid = Common::ComputeHash64(regs.reg_array.data(), Pica::Regs::NUM_REGS * sizeof(u32));
u64 regs_uid =
Common::ComputeHash64(regs.reg_array.data(), Pica::RegsInternal::NUM_REGS * sizeof(u32));
hash = Common::HashCombine(hash, regs_uid);
if (code.size() > 0) {
@ -77,15 +81,14 @@ static std::set<GLenum> GetSupportedFormats() {
return supported_formats;
}
static std::tuple<PicaVSConfig, Pica::Shader::ShaderSetup> BuildVSConfigFromRaw(
static std::tuple<PicaVSConfig, Pica::ShaderSetup> BuildVSConfigFromRaw(
const ShaderDiskCacheRaw& raw, const Driver& driver) {
Pica::Shader::ProgramCode program_code{};
Pica::Shader::SwizzleData swizzle_data{};
std::copy_n(raw.GetProgramCode().begin(), Pica::Shader::MAX_PROGRAM_CODE_LENGTH,
program_code.begin());
std::copy_n(raw.GetProgramCode().begin() + Pica::Shader::MAX_PROGRAM_CODE_LENGTH,
Pica::Shader::MAX_SWIZZLE_DATA_LENGTH, swizzle_data.begin());
Pica::Shader::ShaderSetup setup;
Pica::ProgramCode program_code{};
Pica::SwizzleData swizzle_data{};
std::copy_n(raw.GetProgramCode().begin(), Pica::MAX_PROGRAM_CODE_LENGTH, program_code.begin());
std::copy_n(raw.GetProgramCode().begin() + Pica::MAX_PROGRAM_CODE_LENGTH,
Pica::MAX_SWIZZLE_DATA_LENGTH, swizzle_data.begin());
Pica::ShaderSetup setup;
setup.program_code = program_code;
setup.swizzle_data = swizzle_data;
@ -193,14 +196,13 @@ private:
// program buffer from the previous shader, which is hashed into the config, resulting several
// different config values from the same shader program.
template <typename KeyConfigType,
std::string (*CodeGenerator)(const Pica::Shader::ShaderSetup&, const KeyConfigType&,
bool),
std::string (*CodeGenerator)(const Pica::ShaderSetup&, const KeyConfigType&, bool),
GLenum ShaderType>
class ShaderDoubleCache {
public:
explicit ShaderDoubleCache(bool separable) : separable(separable) {}
std::tuple<GLuint, std::optional<std::string>> Get(const KeyConfigType& key,
const Pica::Shader::ShaderSetup& setup) {
const Pica::ShaderSetup& setup) {
std::optional<std::string> result{};
auto map_it = shader_map.find(key);
if (map_it == shader_map.end()) {
@ -334,8 +336,8 @@ ShaderProgramManager::ShaderProgramManager(Frontend::EmuWindow& emu_window_, con
ShaderProgramManager::~ShaderProgramManager() = default;
bool ShaderProgramManager::UseProgrammableVertexShader(const Pica::Regs& regs,
Pica::Shader::ShaderSetup& setup) {
bool ShaderProgramManager::UseProgrammableVertexShader(const Pica::RegsInternal& regs,
Pica::ShaderSetup& setup) {
// Enable the geometry-shader only if we are actually doing per-fragment lighting
// and care about proper quaternions. Otherwise just use standard vertex+fragment shaders
const bool use_geometry_shader = !regs.lighting.disable;
@ -356,8 +358,9 @@ bool ShaderProgramManager::UseProgrammableVertexShader(const Pica::Regs& regs,
const u64 unique_identifier = GetUniqueIdentifier(regs, program_code);
const ShaderDiskCacheRaw raw{unique_identifier, ProgramType::VS, regs,
std::move(program_code)};
const bool sanitize_mul = Settings::values.shaders_accurate_mul.GetValue();
disk_cache.SaveRaw(raw);
disk_cache.SaveDecompiled(unique_identifier, *result, VideoCore::g_hw_shader_accurate_mul);
disk_cache.SaveDecompiled(unique_identifier, *result, sanitize_mul);
}
return true;
}
@ -367,7 +370,7 @@ void ShaderProgramManager::UseTrivialVertexShader() {
impl->current.vs_hash = 0;
}
void ShaderProgramManager::UseFixedGeometryShader(const Pica::Regs& regs) {
void ShaderProgramManager::UseFixedGeometryShader(const Pica::RegsInternal& regs) {
PicaFixedGSConfig gs_config(regs, driver.HasClipCullDistance());
auto [handle, _] = impl->fixed_geometry_shaders.Get(gs_config, impl->separable);
impl->current.gs = handle;
@ -379,7 +382,7 @@ void ShaderProgramManager::UseTrivialGeometryShader() {
impl->current.gs_hash = 0;
}
void ShaderProgramManager::UseFragmentShader(const Pica::Regs& regs,
void ShaderProgramManager::UseFragmentShader(const Pica::RegsInternal& regs,
const Pica::Shader::UserConfig& user) {
const FSConfig fs_config{regs, user, impl->profile};
auto [handle, result] = impl->fragment_shaders.Get(fs_config, impl->profile);
@ -415,8 +418,8 @@ void ShaderProgramManager::ApplyTo(OpenGLState& state) {
cached_program.Create(false,
std::array{impl->current.vs, impl->current.gs, impl->current.fs});
auto& disk_cache = impl->disk_cache;
disk_cache.SaveDumpToFile(unique_identifier, cached_program.handle,
VideoCore::g_hw_shader_accurate_mul);
const bool sanitize_mul = Settings::values.shaders_accurate_mul.GetValue();
disk_cache.SaveDumpToFile(unique_identifier, cached_program.handle, sanitize_mul);
}
state.draw.shader_program = cached_program.handle;
}
@ -481,8 +484,9 @@ void ShaderProgramManager::LoadDiskCache(const std::atomic_bool& stop_loading,
if (dump != dump_map.end() && decomp != decompiled_map.end()) {
// Only load the vertex shader if its sanitize_mul setting matches
const bool sanitize_mul = Settings::values.shaders_accurate_mul.GetValue();
if (raw.GetProgramType() == ProgramType::VS &&
decomp->second.sanitize_mul != VideoCore::g_hw_shader_accurate_mul) {
decomp->second.sanitize_mul != sanitize_mul) {
continue;
}
@ -537,7 +541,8 @@ void ShaderProgramManager::LoadDiskCache(const std::atomic_bool& stop_loading,
const auto decomp{decompiled_map.find(unique_identifier)};
// Only load the program if its sanitize_mul setting matches
if (decomp->second.sanitize_mul != VideoCore::g_hw_shader_accurate_mul) {
const bool sanitize_mul = Settings::values.shaders_accurate_mul.GetValue();
if (decomp->second.sanitize_mul != sanitize_mul) {
continue;
}

View file

@ -12,13 +12,13 @@ class EmuWindow;
}
namespace Pica {
struct Regs;
}
struct RegsInternal;
struct ShaderSetup;
} // namespace Pica
namespace Pica::Shader {
struct ShaderSetup;
union UserConfig;
} // namespace Pica::Shader
}
namespace OpenGL {
@ -40,15 +40,15 @@ public:
void LoadDiskCache(const std::atomic_bool& stop_loading,
const VideoCore::DiskResourceLoadCallback& callback);
bool UseProgrammableVertexShader(const Pica::Regs& config, Pica::Shader::ShaderSetup& setup);
bool UseProgrammableVertexShader(const Pica::RegsInternal& config, Pica::ShaderSetup& setup);
void UseTrivialVertexShader();
void UseFixedGeometryShader(const Pica::Regs& regs);
void UseFixedGeometryShader(const Pica::RegsInternal& regs);
void UseTrivialGeometryShader();
void UseFragmentShader(const Pica::Regs& config, const Pica::Shader::UserConfig& user);
void UseFragmentShader(const Pica::RegsInternal& config, const Pica::Shader::UserConfig& user);
void ApplyTo(OpenGLState& state);

View file

@ -10,9 +10,9 @@
#include "common/logging/log.h"
#include "core/core.h"
#include "core/telemetry_session.h"
#include "video_core/regs_framebuffer.h"
#include "video_core/regs_lighting.h"
#include "video_core/regs_texturing.h"
#include "video_core/pica/regs_framebuffer.h"
#include "video_core/pica/regs_lighting.h"
#include "video_core/pica/regs_texturing.h"
namespace PicaToGL {

View file

@ -8,15 +8,13 @@
#include "core/core.h"
#include "core/frontend/emu_window.h"
#include "core/frontend/framebuffer_layout.h"
#include "core/hw/hw.h"
#include "core/hw/lcd.h"
#include "core/memory.h"
#include "video_core/pica/pica_core.h"
#include "video_core/renderer_opengl/gl_state.h"
#include "video_core/renderer_opengl/gl_texture_mailbox.h"
#include "video_core/renderer_opengl/post_processing_opengl.h"
#include "video_core/renderer_opengl/renderer_opengl.h"
#include "video_core/shader/generator/glsl_shader_gen.h"
#include "video_core/video_core.h"
#include "video_core/host_shaders/opengl_present_anaglyph_frag.h"
#include "video_core/host_shaders/opengl_present_frag.h"
@ -74,11 +72,12 @@ static std::array<GLfloat, 3 * 2> MakeOrthographicMatrix(const float width, cons
return matrix;
}
RendererOpenGL::RendererOpenGL(Core::System& system, Frontend::EmuWindow& window,
Frontend::EmuWindow* secondary_window)
: VideoCore::RendererBase{system, window, secondary_window}, driver{system.TelemetrySession()},
rasterizer{system.Memory(), system.CustomTexManager(), *this, driver}, frame_dumper{system,
window} {
RendererOpenGL::RendererOpenGL(Core::System& system, Pica::PicaCore& pica_,
Frontend::EmuWindow& window, Frontend::EmuWindow* secondary_window)
: VideoCore::RendererBase{system, window, secondary_window}, pica{pica_},
driver{system.TelemetrySession()}, rasterizer{system.Memory(), pica,
system.CustomTexManager(), *this, driver},
frame_dumper{system, window} {
const bool has_debug_tool = driver.HasDebugTool();
window.mailbox = std::make_unique<OGLTextureMailbox>(has_debug_tool);
if (secondary_window) {
@ -156,39 +155,24 @@ void RendererOpenGL::RenderScreenshot() {
}
void RendererOpenGL::PrepareRendertarget() {
for (int i : {0, 1, 2}) {
int fb_id = i == 2 ? 1 : 0;
const auto& framebuffer = GPU::g_regs.framebuffer_config[fb_id];
// Main LCD (0): 0x1ED02204, Sub LCD (1): 0x1ED02A04
u32 lcd_color_addr =
(fb_id == 0) ? LCD_REG_INDEX(color_fill_top) : LCD_REG_INDEX(color_fill_bottom);
lcd_color_addr = HW::VADDR_LCD + 4 * lcd_color_addr;
LCD::Regs::ColorFill color_fill = {0};
LCD::Read(color_fill.raw, lcd_color_addr);
const auto& framebuffer_config = pica.regs.framebuffer_config;
const auto& regs_lcd = pica.regs_lcd;
for (u32 i = 0; i < 3; i++) {
const u32 fb_id = i == 2 ? 1 : 0;
const auto& framebuffer = framebuffer_config[fb_id];
auto& texture = screen_infos[i].texture;
const auto color_fill = fb_id == 0 ? regs_lcd.color_fill_top : regs_lcd.color_fill_bottom;
if (color_fill.is_enabled) {
LoadColorToActiveGLTexture(color_fill.color_r, color_fill.color_g, color_fill.color_b,
screen_infos[i].texture);
// Resize the texture in case the framebuffer size has changed
screen_infos[i].texture.width = 1;
screen_infos[i].texture.height = 1;
} else {
if (screen_infos[i].texture.width != (GLsizei)framebuffer.width ||
screen_infos[i].texture.height != (GLsizei)framebuffer.height ||
screen_infos[i].texture.format != framebuffer.color_format) {
// Reallocate texture if the framebuffer size has changed.
// This is expected to not happen very often and hence should not be a
// performance problem.
ConfigureFramebufferTexture(screen_infos[i].texture, framebuffer);
}
LoadFBToScreenInfo(framebuffer, screen_infos[i], i == 1);
// Resize the texture in case the framebuffer size has changed
screen_infos[i].texture.width = framebuffer.width;
screen_infos[i].texture.height = framebuffer.height;
FillScreen(color_fill.AsVector(), texture);
continue;
}
if (texture.width != framebuffer.width || texture.height != framebuffer.height ||
texture.format != framebuffer.color_format) {
ConfigureFramebufferTexture(texture, framebuffer);
}
LoadFBToScreenInfo(framebuffer, screen_infos[i], i == 1);
}
}
@ -245,7 +229,7 @@ void RendererOpenGL::RenderToMailbox(const Layout::FramebufferLayout& layout,
/**
* Loads framebuffer from emulated memory into the active OpenGL texture.
*/
void RendererOpenGL::LoadFBToScreenInfo(const GPU::Regs::FramebufferConfig& framebuffer,
void RendererOpenGL::LoadFBToScreenInfo(const Pica::FramebufferConfig& framebuffer,
ScreenInfo& screen_info, bool right_eye) {
if (framebuffer.address_right1 == 0 || framebuffer.address_right2 == 0)
@ -260,7 +244,7 @@ void RendererOpenGL::LoadFBToScreenInfo(const GPU::Regs::FramebufferConfig& fram
framebuffer.stride * framebuffer.height, framebuffer_addr, framebuffer.width.Value(),
framebuffer.height.Value(), framebuffer.format);
int bpp = GPU::Regs::BytesPerPixel(framebuffer.color_format);
int bpp = Pica::BytesPerPixel(framebuffer.color_format);
std::size_t pixel_stride = framebuffer.stride / bpp;
// OpenGL only supports specifying a stride in units of pixels, not bytes, unfortunately
@ -274,11 +258,11 @@ void RendererOpenGL::LoadFBToScreenInfo(const GPU::Regs::FramebufferConfig& fram
screen_info)) {
// Reset the screen info's display texture to its own permanent texture
screen_info.display_texture = screen_info.texture.resource.handle;
screen_info.display_texcoords = Common::Rectangle<float>(0.f, 0.f, 1.f, 1.f);
screen_info.display_texcoords = Common::Rectangle<f32>(0.f, 0.f, 1.f, 1.f);
Memory::RasterizerFlushRegion(framebuffer_addr, framebuffer.stride * framebuffer.height);
rasterizer.FlushRegion(framebuffer_addr, framebuffer.stride * framebuffer.height);
const u8* framebuffer_data = VideoCore::g_memory->GetPhysicalPointer(framebuffer_addr);
const u8* framebuffer_data = system.Memory().GetPhysicalPointer(framebuffer_addr);
state.texture_units[0].texture_2d = screen_info.texture.resource.handle;
state.Apply();
@ -302,23 +286,21 @@ void RendererOpenGL::LoadFBToScreenInfo(const GPU::Regs::FramebufferConfig& fram
}
}
/**
* Fills active OpenGL texture with the given RGB color. Since the color is solid, the texture can
* be 1x1 but will stretch across whatever it's rendered on.
*/
void RendererOpenGL::LoadColorToActiveGLTexture(u8 color_r, u8 color_g, u8 color_b,
const TextureInfo& texture) {
void RendererOpenGL::FillScreen(Common::Vec3<u8> color, TextureInfo& texture) {
state.texture_units[0].texture_2d = texture.resource.handle;
state.Apply();
glActiveTexture(GL_TEXTURE0);
u8 framebuffer_data[3] = {color_r, color_g, color_b};
// Update existing texture
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 1, 1, 0, GL_RGB, GL_UNSIGNED_BYTE, framebuffer_data);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 1, 1, 0, GL_RGB, GL_UNSIGNED_BYTE, color.AsArray());
state.texture_units[0].texture_2d = 0;
state.Apply();
// Resize the texture in case the framebuffer size has changed
texture.width = 1;
texture.height = 1;
}
/**
@ -446,8 +428,8 @@ void RendererOpenGL::ReloadShader() {
}
void RendererOpenGL::ConfigureFramebufferTexture(TextureInfo& texture,
const GPU::Regs::FramebufferConfig& framebuffer) {
GPU::Regs::PixelFormat format = framebuffer.color_format;
const Pica::FramebufferConfig& framebuffer) {
Pica::PixelFormat format = framebuffer.color_format;
GLint internal_format{};
texture.format = format;
@ -455,13 +437,13 @@ void RendererOpenGL::ConfigureFramebufferTexture(TextureInfo& texture,
texture.height = framebuffer.height;
switch (format) {
case GPU::Regs::PixelFormat::RGBA8:
case Pica::PixelFormat::RGBA8:
internal_format = GL_RGBA;
texture.gl_format = GL_RGBA;
texture.gl_type = driver.IsOpenGLES() ? GL_UNSIGNED_BYTE : GL_UNSIGNED_INT_8_8_8_8;
break;
case GPU::Regs::PixelFormat::RGB8:
case Pica::PixelFormat::RGB8:
// This pixel format uses BGR since GL_UNSIGNED_BYTE specifies byte-order, unlike every
// specific OpenGL type used in this function using native-endian (that is, little-endian
// mostly everywhere) for words or half-words.
@ -473,19 +455,19 @@ void RendererOpenGL::ConfigureFramebufferTexture(TextureInfo& texture,
texture.gl_type = GL_UNSIGNED_BYTE;
break;
case GPU::Regs::PixelFormat::RGB565:
case Pica::PixelFormat::RGB565:
internal_format = GL_RGB;
texture.gl_format = GL_RGB;
texture.gl_type = GL_UNSIGNED_SHORT_5_6_5;
break;
case GPU::Regs::PixelFormat::RGB5A1:
case Pica::PixelFormat::RGB5A1:
internal_format = GL_RGBA;
texture.gl_format = GL_RGBA;
texture.gl_type = GL_UNSIGNED_SHORT_5_5_5_1;
break;
case GPU::Regs::PixelFormat::RGBA4:
case Pica::PixelFormat::RGBA4:
internal_format = GL_RGBA;
texture.gl_format = GL_RGBA;
texture.gl_type = GL_UNSIGNED_SHORT_4_4_4_4;

View file

@ -5,7 +5,6 @@
#pragma once
#include <array>
#include "core/hw/gpu.h"
#include "video_core/renderer_base.h"
#include "video_core/renderer_opengl/frame_dumper_opengl.h"
#include "video_core/renderer_opengl/gl_driver.h"
@ -26,9 +25,9 @@ namespace OpenGL {
/// Structure used for storing information about the textures for each 3DS screen
struct TextureInfo {
OGLTexture resource;
GLsizei width;
GLsizei height;
GPU::Regs::PixelFormat format;
u32 width;
u32 height;
Pica::PixelFormat format;
GLenum gl_format;
GLenum gl_type;
};
@ -42,7 +41,7 @@ struct ScreenInfo {
class RendererOpenGL : public VideoCore::RendererBase {
public:
explicit RendererOpenGL(Core::System& system, Frontend::EmuWindow& window,
explicit RendererOpenGL(Core::System& system, Pica::PicaCore& pica, Frontend::EmuWindow& window,
Frontend::EmuWindow* secondary_window);
~RendererOpenGL() override;
@ -64,7 +63,7 @@ private:
void RenderToMailbox(const Layout::FramebufferLayout& layout,
std::unique_ptr<Frontend::TextureMailbox>& mailbox, bool flipped);
void ConfigureFramebufferTexture(TextureInfo& texture,
const GPU::Regs::FramebufferConfig& framebuffer);
const Pica::FramebufferConfig& framebuffer);
void DrawScreens(const Layout::FramebufferLayout& layout, bool flipped);
void ApplySecondLayerOpacity();
void ResetSecondLayerOpacity();
@ -79,12 +78,12 @@ private:
Layout::DisplayOrientation orientation);
// Loads framebuffer from emulated memory into the display information structure
void LoadFBToScreenInfo(const GPU::Regs::FramebufferConfig& framebuffer,
ScreenInfo& screen_info, bool right_eye);
// Fills active OpenGL texture with the given RGB color.
void LoadColorToActiveGLTexture(u8 color_r, u8 color_g, u8 color_b, const TextureInfo& texture);
void LoadFBToScreenInfo(const Pica::FramebufferConfig& framebuffer, ScreenInfo& screen_info,
bool right_eye);
void FillScreen(Common::Vec3<u8> color, TextureInfo& texture);
private:
Pica::PicaCore& pica;
Driver driver;
RasterizerOpenGL rasterizer;
OpenGLState state;

View file

@ -4,16 +4,16 @@
#include "common/color.h"
#include "core/core.h"
#include "core/hw/gpu.h"
#include "core/hw/hw.h"
#include "core/hw/lcd.h"
#include "video_core/gpu.h"
#include "video_core/pica/pica_core.h"
#include "video_core/renderer_software/renderer_software.h"
namespace SwRenderer {
RendererSoftware::RendererSoftware(Core::System& system, Frontend::EmuWindow& window)
: VideoCore::RendererBase{system, window, nullptr}, memory{system.Memory()},
rasterizer{system.Memory()} {}
RendererSoftware::RendererSoftware(Core::System& system, Pica::PicaCore& pica_,
Frontend::EmuWindow& window)
: VideoCore::RendererBase{system, window, nullptr}, memory{system.Memory()}, pica{pica_},
rasterizer{memory, pica} {}
RendererSoftware::~RendererSoftware() = default;
@ -23,15 +23,11 @@ void RendererSoftware::SwapBuffers() {
}
void RendererSoftware::PrepareRenderTarget() {
const auto& regs_lcd = pica.regs_lcd;
for (u32 i = 0; i < 3; i++) {
const int fb_id = i == 2 ? 1 : 0;
u32 lcd_color_addr =
(fb_id == 0) ? LCD_REG_INDEX(color_fill_top) : LCD_REG_INDEX(color_fill_bottom);
lcd_color_addr = HW::VADDR_LCD + 4 * lcd_color_addr;
LCD::Regs::ColorFill color_fill = {0};
LCD::Read(color_fill.raw, lcd_color_addr);
const u32 fb_id = i == 2 ? 1 : 0;
const auto color_fill = fb_id == 0 ? regs_lcd.color_fill_top : regs_lcd.color_fill_bottom;
if (!color_fill.is_enabled) {
LoadFBToScreenInfo(i);
}
@ -40,12 +36,12 @@ void RendererSoftware::PrepareRenderTarget() {
void RendererSoftware::LoadFBToScreenInfo(int i) {
const u32 fb_id = i == 2 ? 1 : 0;
const auto& framebuffer = GPU::g_regs.framebuffer_config[fb_id];
const auto& framebuffer = pica.regs.framebuffer_config[fb_id];
auto& info = screen_infos[i];
const PAddr framebuffer_addr =
framebuffer.active_fb == 0 ? framebuffer.address_left1 : framebuffer.address_left2;
const s32 bpp = GPU::Regs::BytesPerPixel(framebuffer.color_format);
const s32 bpp = Pica::BytesPerPixel(framebuffer.color_format);
const u8* framebuffer_data = memory.GetPhysicalPointer(framebuffer_addr);
const s32 pixel_stride = framebuffer.stride / bpp;
@ -58,15 +54,15 @@ void RendererSoftware::LoadFBToScreenInfo(int i) {
const u8* pixel = framebuffer_data + (y * pixel_stride + pixel_stride - x) * bpp;
const Common::Vec4 color = [&] {
switch (framebuffer.color_format) {
case GPU::Regs::PixelFormat::RGBA8:
case Pica::PixelFormat::RGBA8:
return Common::Color::DecodeRGBA8(pixel);
case GPU::Regs::PixelFormat::RGB8:
case Pica::PixelFormat::RGB8:
return Common::Color::DecodeRGB8(pixel);
case GPU::Regs::PixelFormat::RGB565:
case Pica::PixelFormat::RGB565:
return Common::Color::DecodeRGB565(pixel);
case GPU::Regs::PixelFormat::RGB5A1:
case Pica::PixelFormat::RGB5A1:
return Common::Color::DecodeRGB5A1(pixel);
case GPU::Regs::PixelFormat::RGBA4:
case Pica::PixelFormat::RGBA4:
return Common::Color::DecodeRGBA4(pixel);
}
UNREACHABLE();

View file

@ -21,7 +21,8 @@ struct ScreenInfo {
class RendererSoftware : public VideoCore::RendererBase {
public:
explicit RendererSoftware(Core::System& system, Frontend::EmuWindow& window);
explicit RendererSoftware(Core::System& system, Pica::PicaCore& pica,
Frontend::EmuWindow& window);
~RendererSoftware() override;
[[nodiscard]] VideoCore::RasterizerInterface* Rasterizer() override {
@ -42,6 +43,7 @@ private:
private:
Memory::MemorySystem& memory;
Pica::PicaCore& pica;
RasterizerSoftware rasterizer;
std::array<ScreenInfo, 3> screen_infos{};
};

View file

@ -0,0 +1,346 @@
// Copyright 2023 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#include "common/alignment.h"
#include "common/color.h"
#include "common/vector_math.h"
#include "core/memory.h"
#include "video_core/pica/regs_external.h"
#include "video_core/rasterizer_interface.h"
#include "video_core/renderer_software/sw_blitter.h"
#include "video_core/utils.h"
namespace SwRenderer {
static Common::Vec4<u8> DecodePixel(Pica::PixelFormat input_format, const u8* src_pixel) {
switch (input_format) {
case Pica::PixelFormat::RGBA8:
return Common::Color::DecodeRGBA8(src_pixel);
case Pica::PixelFormat::RGB8:
return Common::Color::DecodeRGB8(src_pixel);
case Pica::PixelFormat::RGB565:
return Common::Color::DecodeRGB565(src_pixel);
case Pica::PixelFormat::RGB5A1:
return Common::Color::DecodeRGB5A1(src_pixel);
case Pica::PixelFormat::RGBA4:
return Common::Color::DecodeRGBA4(src_pixel);
default:
LOG_ERROR(HW_GPU, "Unknown source framebuffer format {:x}", input_format);
return {0, 0, 0, 0};
}
}
SwBlitter::SwBlitter(Memory::MemorySystem& memory_, VideoCore::RasterizerInterface* rasterizer_)
: memory{memory_}, rasterizer{rasterizer_} {}
SwBlitter::~SwBlitter() = default;
void SwBlitter::TextureCopy(const Pica::DisplayTransferConfig& config) {
const PAddr src_addr = config.GetPhysicalInputAddress();
const PAddr dst_addr = config.GetPhysicalOutputAddress();
// TODO: do hwtest with invalid addresses
if (!memory.IsValidPhysicalAddress(src_addr)) {
LOG_CRITICAL(HW_GPU, "invalid input address {:#010X}", src_addr);
return;
}
if (!memory.IsValidPhysicalAddress(dst_addr)) {
LOG_CRITICAL(HW_GPU, "invalid output address {:#010X}", dst_addr);
return;
}
u8* src_pointer = memory.GetPhysicalPointer(src_addr);
u8* dst_pointer = memory.GetPhysicalPointer(dst_addr);
u32 remaining_size = Common::AlignDown(config.texture_copy.size, 16);
if (remaining_size == 0) {
LOG_CRITICAL(HW_GPU, "zero size. Real hardware freezes on this.");
return;
}
u32 input_gap = config.texture_copy.input_gap * 16;
u32 output_gap = config.texture_copy.output_gap * 16;
// Zero gap means contiguous input/output even if width = 0. To avoid infinite loop below, width
// is assigned with the total size if gap = 0.
u32 input_width = input_gap == 0 ? remaining_size : config.texture_copy.input_width * 16;
u32 output_width = output_gap == 0 ? remaining_size : config.texture_copy.output_width * 16;
if (input_width == 0) {
LOG_CRITICAL(HW_GPU, "zero input width. Real hardware freezes on this.");
return;
}
if (output_width == 0) {
LOG_CRITICAL(HW_GPU, "zero output width. Real hardware freezes on this.");
return;
}
const size_t contiguous_input_size =
config.texture_copy.size / input_width * (input_width + input_gap);
rasterizer->FlushRegion(config.GetPhysicalInputAddress(),
static_cast<u32>(contiguous_input_size));
const size_t contiguous_output_size =
config.texture_copy.size / output_width * (output_width + output_gap);
// Only need to flush output if it has a gap
if (output_gap != 0) {
rasterizer->FlushAndInvalidateRegion(dst_addr, static_cast<u32>(contiguous_output_size));
} else {
rasterizer->InvalidateRegion(dst_addr, static_cast<u32>(contiguous_output_size));
}
u32 remaining_input = input_width;
u32 remaining_output = output_width;
while (remaining_size > 0) {
u32 copy_size = std::min({remaining_input, remaining_output, remaining_size});
std::memcpy(dst_pointer, src_pointer, copy_size);
src_pointer += copy_size;
dst_pointer += copy_size;
remaining_input -= copy_size;
remaining_output -= copy_size;
remaining_size -= copy_size;
if (remaining_input == 0) {
remaining_input = input_width;
src_pointer += input_gap;
}
if (remaining_output == 0) {
remaining_output = output_width;
dst_pointer += output_gap;
}
}
}
void SwBlitter::DisplayTransfer(const Pica::DisplayTransferConfig& config) {
const PAddr src_addr = config.GetPhysicalInputAddress();
PAddr dst_addr = config.GetPhysicalOutputAddress();
// TODO: do hwtest with these cases
if (!memory.IsValidPhysicalAddress(src_addr)) {
LOG_CRITICAL(HW_GPU, "invalid input address {:#010X}", src_addr);
return;
}
if (!memory.IsValidPhysicalAddress(dst_addr)) {
LOG_CRITICAL(HW_GPU, "invalid output address {:#010X}", dst_addr);
return;
}
if (config.input_width == 0) {
LOG_CRITICAL(HW_GPU, "zero input width");
return;
}
if (config.input_height == 0) {
LOG_CRITICAL(HW_GPU, "zero input height");
return;
}
if (config.output_width == 0) {
LOG_CRITICAL(HW_GPU, "zero output width");
return;
}
if (config.output_height == 0) {
LOG_CRITICAL(HW_GPU, "zero output height");
return;
}
// Using flip_vertically alongside crop_input_lines produces skewed output on hardware.
// We have to emulate this because some games rely on this behaviour to render correctly.
if (config.flip_vertically && config.crop_input_lines) {
dst_addr += (config.input_width - config.output_width) * (config.output_height - 1) *
BytesPerPixel(config.output_format);
}
u8* src_pointer = memory.GetPhysicalPointer(src_addr);
u8* dst_pointer = memory.GetPhysicalPointer(dst_addr);
if (config.scaling > config.ScaleXY) {
LOG_CRITICAL(HW_GPU, "Unimplemented display transfer scaling mode {}",
config.scaling.Value());
UNIMPLEMENTED();
return;
}
if (config.input_linear && config.scaling != config.NoScale) {
LOG_CRITICAL(HW_GPU, "Scaling is only implemented on tiled input");
UNIMPLEMENTED();
return;
}
const u32 horizontal_scale = config.scaling != config.NoScale ? 1 : 0;
const u32 vertical_scale = config.scaling == config.ScaleXY ? 1 : 0;
const u32 output_width = config.output_width >> horizontal_scale;
const u32 output_height = config.output_height >> vertical_scale;
const u32 input_size =
config.input_width * config.input_height * BytesPerPixel(config.input_format);
const u32 output_size = output_width * output_height * BytesPerPixel(config.output_format);
rasterizer->FlushRegion(config.GetPhysicalInputAddress(), input_size);
rasterizer->InvalidateRegion(config.GetPhysicalOutputAddress(), output_size);
for (u32 y = 0; y < output_height; ++y) {
for (u32 x = 0; x < output_width; ++x) {
Common::Vec4<u8> src_color;
// Calculate the [x,y] position of the input image
// based on the current output position and the scale
const u32 input_x = x << horizontal_scale;
const u32 input_y = y << vertical_scale;
u32 output_y;
if (config.flip_vertically) {
// Flip the y value of the output data,
// we do this after calculating the [x,y] position of the input image
// to account for the scaling options.
output_y = output_height - y - 1;
} else {
output_y = y;
}
const u32 dst_bytes_per_pixel = BytesPerPixel(config.output_format);
const u32 src_bytes_per_pixel = BytesPerPixel(config.input_format);
u32 src_offset;
u32 dst_offset;
if (config.input_linear) {
if (!config.dont_swizzle) {
// Interpret the input as linear and the output as tiled
u32 coarse_y = output_y & ~7;
u32 stride = output_width * dst_bytes_per_pixel;
src_offset = (input_x + input_y * config.input_width) * src_bytes_per_pixel;
dst_offset = VideoCore::GetMortonOffset(x, output_y, dst_bytes_per_pixel) +
coarse_y * stride;
} else {
// Both input and output are linear
src_offset = (input_x + input_y * config.input_width) * src_bytes_per_pixel;
dst_offset = (x + output_y * output_width) * dst_bytes_per_pixel;
}
} else {
if (!config.dont_swizzle) {
// Interpret the input as tiled and the output as linear
const u32 coarse_y = input_y & ~7;
const u32 stride = config.input_width * src_bytes_per_pixel;
src_offset = VideoCore::GetMortonOffset(input_x, input_y, src_bytes_per_pixel) +
coarse_y * stride;
dst_offset = (x + output_y * output_width) * dst_bytes_per_pixel;
} else {
// Both input and output are tiled
const u32 out_coarse_y = output_y & ~7;
const u32 out_stride = output_width * dst_bytes_per_pixel;
const u32 in_coarse_y = input_y & ~7;
const u32 in_stride = config.input_width * src_bytes_per_pixel;
src_offset = VideoCore::GetMortonOffset(input_x, input_y, src_bytes_per_pixel) +
in_coarse_y * in_stride;
dst_offset = VideoCore::GetMortonOffset(x, output_y, dst_bytes_per_pixel) +
out_coarse_y * out_stride;
}
}
const u8* src_pixel = src_pointer + src_offset;
src_color = DecodePixel(config.input_format, src_pixel);
if (config.scaling == config.ScaleX) {
const auto pixel =
DecodePixel(config.input_format, src_pixel + src_bytes_per_pixel);
src_color = ((src_color + pixel) / 2).Cast<u8>();
} else if (config.scaling == config.ScaleXY) {
const auto pixel1 =
DecodePixel(config.input_format, src_pixel + 1 * src_bytes_per_pixel);
const auto pixel2 =
DecodePixel(config.input_format, src_pixel + 2 * src_bytes_per_pixel);
const auto pixel3 =
DecodePixel(config.input_format, src_pixel + 3 * src_bytes_per_pixel);
src_color = (((src_color + pixel1) + (pixel2 + pixel3)) / 4).Cast<u8>();
}
u8* dst_pixel = dst_pointer + dst_offset;
switch (config.output_format) {
case Pica::PixelFormat::RGBA8:
Common::Color::EncodeRGBA8(src_color, dst_pixel);
break;
case Pica::PixelFormat::RGB8:
Common::Color::EncodeRGB8(src_color, dst_pixel);
break;
case Pica::PixelFormat::RGB565:
Common::Color::EncodeRGB565(src_color, dst_pixel);
break;
case Pica::PixelFormat::RGB5A1:
Common::Color::EncodeRGB5A1(src_color, dst_pixel);
break;
case Pica::PixelFormat::RGBA4:
Common::Color::EncodeRGBA4(src_color, dst_pixel);
break;
default:
LOG_ERROR(HW_GPU, "Unknown destination framebuffer format {:x}",
static_cast<u32>(config.output_format.Value()));
break;
}
}
}
}
void SwBlitter::MemoryFill(const Pica::MemoryFillConfig& config) {
const PAddr start_addr = config.GetStartAddress();
const PAddr end_addr = config.GetEndAddress();
// TODO: do hwtest with these cases
if (!memory.IsValidPhysicalAddress(start_addr)) {
LOG_CRITICAL(HW_GPU, "invalid start address {:#010X}", start_addr);
return;
}
if (!memory.IsValidPhysicalAddress(end_addr)) {
LOG_CRITICAL(HW_GPU, "invalid end address {:#010X}", end_addr);
return;
}
if (end_addr <= start_addr) {
LOG_CRITICAL(HW_GPU, "invalid memory range from {:#010X} to {:#010X}", start_addr,
end_addr);
return;
}
u8* start = memory.GetPhysicalPointer(start_addr);
u8* end = memory.GetPhysicalPointer(end_addr);
rasterizer->InvalidateRegion(start_addr, end_addr - start_addr);
if (config.fill_24bit) {
// Fill with 24-bit values
for (u8* ptr = start; ptr < end; ptr += 3) {
ptr[0] = config.value_24bit_r;
ptr[1] = config.value_24bit_g;
ptr[2] = config.value_24bit_b;
}
} else if (config.fill_32bit) {
// Fill with 32-bit values
if (end > start) {
const u32 value = config.value_32bit;
const size_t len = (end - start) / sizeof(u32);
for (std::size_t i = 0; i < len; ++i) {
std::memcpy(&start[i * sizeof(u32)], &value, sizeof(u32));
}
}
} else {
// Fill with 16-bit values
const u16 value_16bit = config.value_16bit.Value();
for (u8* ptr = start; ptr < end; ptr += sizeof(u16)) {
std::memcpy(ptr, &value_16bit, sizeof(u16));
}
}
}
} // namespace SwRenderer

View file

@ -0,0 +1,38 @@
// Copyright 2023 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#pragma once
namespace Pica {
struct DisplayTransferConfig;
struct MemoryFillConfig;
} // namespace Pica
namespace Memory {
class MemorySystem;
}
namespace VideoCore {
class RasterizerInterface;
}
namespace SwRenderer {
class SwBlitter {
public:
explicit SwBlitter(Memory::MemorySystem& memory, VideoCore::RasterizerInterface* rasterizer);
~SwBlitter();
void TextureCopy(const Pica::DisplayTransferConfig& config);
void DisplayTransfer(const Pica::DisplayTransferConfig& config);
void MemoryFill(const Pica::MemoryFillConfig& config);
private:
Memory::MemorySystem& memory;
VideoCore::RasterizerInterface* rasterizer;
};
} // namespace SwRenderer

View file

@ -4,7 +4,7 @@
#include <array>
#include <cstddef>
#include "video_core/regs_texturing.h"
#include "video_core/pica/regs_texturing.h"
#include "video_core/renderer_software/sw_clipper.h"
namespace SwRenderer {

View file

@ -5,10 +5,10 @@
#include <algorithm>
#include "common/color.h"
#include "common/logging/log.h"
#include "core/hw/gpu.h"
#include "core/memory.h"
#include "video_core/pica/regs_external.h"
#include "video_core/pica/regs_framebuffer.h"
#include "video_core/pica_types.h"
#include "video_core/regs_framebuffer.h"
#include "video_core/renderer_software/sw_framebuffer.h"
#include "video_core/utils.h"
@ -63,7 +63,7 @@ void Framebuffer::DrawPixel(u32 x, u32 y, const Common::Vec4<u8>& color) const {
const u32 coarse_y = y & ~7;
const u32 bytes_per_pixel =
GPU::Regs::BytesPerPixel(GPU::Regs::PixelFormat(framebuffer.color_format.Value()));
Pica::BytesPerPixel(Pica::PixelFormat(framebuffer.color_format.Value()));
const u32 dst_offset = VideoCore::GetMortonOffset(x, y, bytes_per_pixel) +
coarse_y * framebuffer.width * bytes_per_pixel;
u8* dst_pixel = color_buffer + dst_offset;
@ -97,7 +97,7 @@ const Common::Vec4<u8> Framebuffer::GetPixel(u32 x, u32 y) const {
const u32 coarse_y = y & ~7;
const u32 bytes_per_pixel =
GPU::Regs::BytesPerPixel(GPU::Regs::PixelFormat(framebuffer.color_format.Value()));
Pica::BytesPerPixel(Pica::PixelFormat(framebuffer.color_format.Value()));
const u32 src_offset = VideoCore::GetMortonOffset(x, y, bytes_per_pixel) +
coarse_y * framebuffer.width * bytes_per_pixel;
const u8* src_pixel = color_buffer + src_offset;

View file

@ -6,7 +6,7 @@
#include "common/common_types.h"
#include "common/vector_math.h"
#include "video_core/regs_framebuffer.h"
#include "video_core/pica/regs_framebuffer.h"
namespace Memory {
class MemorySystem;

View file

@ -10,7 +10,7 @@ namespace SwRenderer {
using Pica::f16;
using Pica::LightingRegs;
static float LookupLightingLut(const Pica::State::Lighting& lighting, std::size_t lut_index,
static float LookupLightingLut(const Pica::PicaCore::Lighting& lighting, std::size_t lut_index,
u8 index, float delta) {
ASSERT_MSG(lut_index < lighting.luts.size(), "Out of range lut");
ASSERT_MSG(index < lighting.luts[lut_index].size(), "Out of range index");
@ -24,7 +24,7 @@ static float LookupLightingLut(const Pica::State::Lighting& lighting, std::size_
}
std::pair<Common::Vec4<u8>, Common::Vec4<u8>> ComputeFragmentsColors(
const Pica::LightingRegs& lighting, const Pica::State::Lighting& lighting_state,
const Pica::LightingRegs& lighting, const Pica::PicaCore::Lighting& lighting_state,
const Common::Quaternion<f32>& normquat, const Common::Vec3f& view,
std::span<const Common::Vec4<u8>, 4> texture_color) {

View file

@ -9,12 +9,12 @@
#include "common/quaternion.h"
#include "common/vector_math.h"
#include "video_core/pica_state.h"
#include "video_core/pica/pica_core.h"
namespace SwRenderer {
std::pair<Common::Vec4<u8>, Common::Vec4<u8>> ComputeFragmentsColors(
const Pica::LightingRegs& lighting, const Pica::State::Lighting& lighting_state,
const Pica::LightingRegs& lighting, const Pica::PicaCore::Lighting& lighting_state,
const Common::Quaternion<f32>& normquat, const Common::Vec3f& view,
std::span<const Common::Vec4<u8>, 4> texture_color);

View file

@ -15,7 +15,7 @@ using ProcTexCombiner = Pica::TexturingRegs::ProcTexCombiner;
using ProcTexFilter = Pica::TexturingRegs::ProcTexFilter;
using Pica::f16;
float LookupLUT(const std::array<Pica::State::ProcTex::ValueEntry, 128>& lut, float coord) {
float LookupLUT(const std::array<Pica::PicaCore::ProcTex::ValueEntry, 128>& lut, float coord) {
// For NoiseLUT/ColorMap/AlphaMap, coord=0.0 is lut[0], coord=127.0/128.0 is lut[127] and
// coord=1.0 is lut[127]+lut_diff[127]. For other indices, the result is interpolated using
// value entries and difference entries.
@ -47,7 +47,7 @@ float NoiseRand2D(unsigned int x, unsigned int y) {
}
float NoiseCoef(float u, float v, const Pica::TexturingRegs& regs,
const Pica::State::ProcTex& state) {
const Pica::PicaCore::ProcTex& state) {
const float freq_u = f16::FromRaw(regs.proctex_noise_frequency.u).ToFloat32();
const float freq_v = f16::FromRaw(regs.proctex_noise_frequency.v).ToFloat32();
const float phase_u = f16::FromRaw(regs.proctex_noise_u.phase).ToFloat32();
@ -115,7 +115,7 @@ void ClampCoord(float& coord, ProcTexClamp mode) {
}
float CombineAndMap(float u, float v, ProcTexCombiner combiner,
const std::array<Pica::State::ProcTex::ValueEntry, 128>& map_table) {
const std::array<Pica::PicaCore::ProcTex::ValueEntry, 128>& map_table) {
float f;
switch (combiner) {
case ProcTexCombiner::U:
@ -158,7 +158,7 @@ float CombineAndMap(float u, float v, ProcTexCombiner combiner,
} // Anonymous namespace
Common::Vec4<u8> ProcTex(float u, float v, const Pica::TexturingRegs& regs,
const Pica::State::ProcTex& state) {
const Pica::PicaCore::ProcTex& state) {
u = std::abs(u);
v = std::abs(v);

View file

@ -6,12 +6,12 @@
#include "common/common_types.h"
#include "common/vector_math.h"
#include "video_core/pica_state.h"
#include "video_core/pica/pica_core.h"
namespace SwRenderer {
/// Generates procedural texture color for the given coordinates
Common::Vec4<u8> ProcTex(float u, float v, const Pica::TexturingRegs& regs,
const Pica::State::ProcTex& state);
const Pica::PicaCore::ProcTex& state);
} // namespace SwRenderer

View file

@ -8,14 +8,13 @@
#include "common/quaternion.h"
#include "common/vector_math.h"
#include "core/memory.h"
#include "video_core/pica_state.h"
#include "video_core/pica_types.h"
#include "video_core/pica/output_vertex.h"
#include "video_core/pica/pica_core.h"
#include "video_core/renderer_software/sw_framebuffer.h"
#include "video_core/renderer_software/sw_lighting.h"
#include "video_core/renderer_software/sw_proctex.h"
#include "video_core/renderer_software/sw_rasterizer.h"
#include "video_core/renderer_software/sw_texturing.h"
#include "video_core/shader/shader.h"
#include "video_core/texture/texture_decode.h"
namespace SwRenderer {
@ -33,7 +32,7 @@ using Pica::Texture::TextureInfo;
// we can use a very small epsilon value for clip plane comparison.
constexpr f32 EPSILON_Z = 0.00000001f;
struct Vertex : Pica::Shader::OutputVertex {
struct Vertex : Pica::OutputVertex {
Vertex(const OutputVertex& v) : OutputVertex(v) {}
/// Attributes used to store intermediate results position after perspective divide.
@ -101,14 +100,13 @@ private:
} // Anonymous namespace
RasterizerSoftware::RasterizerSoftware(Memory::MemorySystem& memory_)
: memory{memory_}, state{Pica::g_state}, regs{state.regs},
RasterizerSoftware::RasterizerSoftware(Memory::MemorySystem& memory_, Pica::PicaCore& pica_)
: memory{memory_}, pica{pica_}, regs{pica.regs.internal},
num_sw_threads{std::max(std::thread::hardware_concurrency(), 2U)},
sw_workers{num_sw_threads, "SwRenderer workers"}, fb{memory, regs.framebuffer} {}
void RasterizerSoftware::AddTriangle(const Pica::Shader::OutputVertex& v0,
const Pica::Shader::OutputVertex& v1,
const Pica::Shader::OutputVertex& v2) {
void RasterizerSoftware::AddTriangle(const Pica::OutputVertex& v0, const Pica::OutputVertex& v1,
const Pica::OutputVertex& v2) {
/**
* Clipping a planar n-gon against a plane will remove at least 1 vertex and introduces 2 at
* the new edge (or less in degenerate cases). As such, we can say that each clipping plane
@ -170,8 +168,8 @@ void RasterizerSoftware::AddTriangle(const Pica::Shader::OutputVertex& v0,
}
}
if (state.regs.rasterizer.clip_enable) {
const ClippingEdge custom_edge{state.regs.rasterizer.GetClipCoef()};
if (regs.rasterizer.clip_enable) {
const ClippingEdge custom_edge{regs.rasterizer.GetClipCoef()};
clip(custom_edge);
if (output_list->size() < 3) {
return;
@ -434,7 +432,7 @@ void RasterizerSoftware::ProcessTriangle(const Vertex& v0, const Vertex& v1, con
get_interpolated_attribute(v0.view.z, v1.view.z, v2.view.z).ToFloat32(),
};
std::tie(primary_fragment_color, secondary_fragment_color) =
ComputeFragmentsColors(regs.lighting, state.lighting, normquat, view,
ComputeFragmentsColors(regs.lighting, pica.lighting, normquat, view,
texture_color);
}
@ -587,7 +585,7 @@ std::array<Common::Vec4<u8>, 4> RasterizerSoftware::TextureColor(
if (regs.texturing.main_config.texture3_enable) {
const auto& proctex_uv = uv[regs.texturing.main_config.texture3_coordinates];
texture_color[3] = ProcTex(proctex_uv.u().ToFloat32(), proctex_uv.v().ToFloat32(),
regs.texturing, state.proctex);
regs.texturing, pica.proctex);
}
return texture_color;
@ -813,7 +811,7 @@ void RasterizerSoftware::WriteFog(float depth, Common::Vec4<u8>& combiner_output
// Generate clamped fog factor from LUT for given fog index
const f32 fog_i = std::clamp(floorf(fog_index), 0.0f, 127.0f);
const f32 fog_f = fog_index - fog_i;
const auto& fog_lut_entry = state.fog.lut[static_cast<u32>(fog_i)];
const auto& fog_lut_entry = pica.fog.lut[static_cast<u32>(fog_i)];
f32 fog_factor = fog_lut_entry.ToFloat() + fog_lut_entry.DiffToFloat() * fog_f;
fog_factor = std::clamp(fog_factor, 0.0f, 1.0f);
for (u32 i = 0; i < 3; i++) {

View file

@ -6,18 +6,14 @@
#include <span>
#include "common/thread_worker.h"
#include "video_core/pica/regs_texturing.h"
#include "video_core/rasterizer_interface.h"
#include "video_core/regs_texturing.h"
#include "video_core/renderer_software/sw_clipper.h"
#include "video_core/renderer_software/sw_framebuffer.h"
namespace Pica::Shader {
struct OutputVertex;
}
namespace Pica {
struct State;
struct Regs;
struct RegsInternal;
class PicaCore;
} // namespace Pica
namespace SwRenderer {
@ -26,10 +22,10 @@ struct Vertex;
class RasterizerSoftware : public VideoCore::RasterizerInterface {
public:
explicit RasterizerSoftware(Memory::MemorySystem& memory);
explicit RasterizerSoftware(Memory::MemorySystem& memory, Pica::PicaCore& pica);
void AddTriangle(const Pica::Shader::OutputVertex& v0, const Pica::Shader::OutputVertex& v1,
const Pica::Shader::OutputVertex& v2) override;
void AddTriangle(const Pica::OutputVertex& v0, const Pica::OutputVertex& v1,
const Pica::OutputVertex& v2) override;
void DrawTriangles() override {}
void NotifyPicaRegisterChanged(u32 id) override {}
void FlushAll() override {}
@ -72,8 +68,8 @@ private:
private:
Memory::MemorySystem& memory;
Pica::State& state;
const Pica::Regs& regs;
Pica::PicaCore& pica;
Pica::RegsInternal& regs;
size_t num_sw_threads;
Common::ThreadWorker sw_workers;
Framebuffer fb;

View file

@ -6,7 +6,7 @@
#include "common/assert.h"
#include "common/common_types.h"
#include "common/vector_math.h"
#include "video_core/regs_texturing.h"
#include "video_core/pica/regs_texturing.h"
#include "video_core/renderer_software/sw_texturing.h"
namespace SwRenderer {

View file

@ -8,7 +8,7 @@
#include "common/common_types.h"
#include "common/vector_math.h"
#include "video_core/regs_texturing.h"
#include "video_core/pica/regs_texturing.h"
namespace SwRenderer {

View file

@ -4,10 +4,8 @@
#pragma once
#include "common/logging/log.h"
#include "core/core.h"
#include "core/telemetry_session.h"
#include "video_core/regs.h"
#include "common/assert.h"
#include "video_core/pica/regs_internal.h"
#include "video_core/renderer_vulkan/vk_common.h"
namespace PicaToVK {
@ -56,14 +54,6 @@ inline vk::SamplerAddressMode WrapMode(Pica::TexturingRegs::TextureConfig::WrapM
const auto index = static_cast<std::size_t>(mode);
ASSERT_MSG(index < wrap_mode_table.size(), "Unknown texture wrap mode {}", index);
if (index > 3) {
Core::System::GetInstance().TelemetrySession().AddField(
Common::Telemetry::FieldType::Session, "VideoCore_Pica_UnsupportedTextureWrapMode",
static_cast<u32>(index));
LOG_WARNING(Render_Vulkan, "Using texture wrap mode {}", index);
}
return wrap_mode_table[index];
}

View file

@ -9,9 +9,8 @@
#include "common/settings.h"
#include "core/core.h"
#include "core/frontend/emu_window.h"
#include "core/hw/gpu.h"
#include "core/hw/hw.h"
#include "core/hw/lcd.h"
#include "video_core/gpu.h"
#include "video_core/pica/pica_core.h"
#include "video_core/renderer_vulkan/renderer_vulkan.h"
#include "video_core/renderer_vulkan/vk_memory_util.h"
#include "video_core/renderer_vulkan/vk_shader_util.h"
@ -51,15 +50,16 @@ constexpr static std::array<vk::DescriptorSetLayoutBinding, 1> PRESENT_BINDINGS
{0, vk::DescriptorType::eCombinedImageSampler, 3, vk::ShaderStageFlagBits::eFragment},
}};
RendererVulkan::RendererVulkan(Core::System& system, Frontend::EmuWindow& window,
Frontend::EmuWindow* secondary_window)
: RendererBase{system, window, secondary_window}, memory{system.Memory()},
RendererVulkan::RendererVulkan(Core::System& system, Pica::PicaCore& pica_,
Frontend::EmuWindow& window, Frontend::EmuWindow* secondary_window)
: RendererBase{system, window, secondary_window}, memory{system.Memory()}, pica{pica_},
instance{system.TelemetrySession(), window, Settings::values.physical_device.GetValue()},
scheduler{instance}, renderpass_cache{instance, scheduler}, pool{instance},
main_window{window, instance, scheduler},
vertex_buffer{instance, scheduler, vk::BufferUsageFlagBits::eVertexBuffer,
VERTEX_BUFFER_SIZE},
rasterizer{memory,
pica,
system.CustomTexManager(),
*this,
render_window,
@ -103,37 +103,25 @@ void RendererVulkan::Sync() {
}
void RendererVulkan::PrepareRendertarget() {
const auto& framebuffer_config = pica.regs.framebuffer_config;
const auto& regs_lcd = pica.regs_lcd;
for (u32 i = 0; i < 3; i++) {
const u32 fb_id = i == 2 ? 1 : 0;
const auto& framebuffer = GPU::g_regs.framebuffer_config[fb_id];
// Main LCD (0): 0x1ED02204, Sub LCD (1): 0x1ED02A04
u32 lcd_color_addr =
(fb_id == 0) ? LCD_REG_INDEX(color_fill_top) : LCD_REG_INDEX(color_fill_bottom);
lcd_color_addr = HW::VADDR_LCD + 4 * lcd_color_addr;
LCD::Regs::ColorFill color_fill{0};
LCD::Read(color_fill.raw, lcd_color_addr);
const auto& framebuffer = framebuffer_config[fb_id];
auto& texture = screen_infos[i].texture;
const auto color_fill = fb_id == 0 ? regs_lcd.color_fill_top : regs_lcd.color_fill_bottom;
if (color_fill.is_enabled) {
LoadColorToActiveVkTexture(color_fill.color_r, color_fill.color_g, color_fill.color_b,
screen_infos[i].texture);
} else {
TextureInfo& texture = screen_infos[i].texture;
if (texture.width != framebuffer.width || texture.height != framebuffer.height ||
texture.format != framebuffer.color_format) {
// Reallocate texture if the framebuffer size has changed.
// This is expected to not happen very often and hence should not be a
// performance problem.
ConfigureFramebufferTexture(texture, framebuffer);
}
LoadFBToScreenInfo(framebuffer, screen_infos[i], i == 1);
// Resize the texture in case the framebuffer size has changed
texture.width = framebuffer.width;
texture.height = framebuffer.height;
FillScreen(color_fill.AsVector(), texture);
continue;
}
if (texture.width != framebuffer.width || texture.height != framebuffer.height ||
texture.format != framebuffer.color_format) {
ConfigureFramebufferTexture(texture, framebuffer);
}
LoadFBToScreenInfo(framebuffer, screen_infos[i], i == 1);
}
}
@ -203,7 +191,7 @@ void RendererVulkan::RenderToWindow(PresentWindow& window, const Layout::Framebu
window.Present(frame);
}
void RendererVulkan::LoadFBToScreenInfo(const GPU::Regs::FramebufferConfig& framebuffer,
void RendererVulkan::LoadFBToScreenInfo(const Pica::FramebufferConfig& framebuffer,
ScreenInfo& screen_info, bool right_eye) {
if (framebuffer.address_right1 == 0 || framebuffer.address_right2 == 0) {
@ -219,7 +207,7 @@ void RendererVulkan::LoadFBToScreenInfo(const GPU::Regs::FramebufferConfig& fram
framebuffer.stride * framebuffer.height, framebuffer_addr, framebuffer.width.Value(),
framebuffer.height.Value(), framebuffer.format);
const int bpp = GPU::Regs::BytesPerPixel(framebuffer.color_format);
const u32 bpp = Pica::BytesPerPixel(framebuffer.color_format);
const std::size_t pixel_stride = framebuffer.stride / bpp;
ASSERT(pixel_stride * bpp == framebuffer.stride);
@ -405,7 +393,7 @@ void RendererVulkan::BuildPipelines() {
}
void RendererVulkan::ConfigureFramebufferTexture(TextureInfo& texture,
const GPU::Regs::FramebufferConfig& framebuffer) {
const Pica::FramebufferConfig& framebuffer) {
vk::Device device = instance.GetDevice();
if (texture.image_view) {
device.destroyImageView(texture.image_view);
@ -466,14 +454,14 @@ void RendererVulkan::ConfigureFramebufferTexture(TextureInfo& texture,
texture.format = framebuffer.color_format;
}
void RendererVulkan::LoadColorToActiveVkTexture(u8 color_r, u8 color_g, u8 color_b,
const TextureInfo& texture) {
void RendererVulkan::FillScreen(Common::Vec3<u8> color, const TextureInfo& texture) {
return;
const vk::ClearColorValue clear_color = {
.float32 =
std::array{
color_r / 255.0f,
color_g / 255.0f,
color_b / 255.0f,
color.r() / 255.0f,
color.g() / 255.0f,
color.b() / 255.0f,
1.0f,
},
};

View file

@ -4,12 +4,8 @@
#pragma once
#include <array>
#include <condition_variable>
#include <mutex>
#include "common/common_types.h"
#include "common/math_util.h"
#include "core/hw/gpu.h"
#include "video_core/renderer_base.h"
#include "video_core/renderer_vulkan/vk_descriptor_pool.h"
#include "video_core/renderer_vulkan/vk_instance.h"
@ -17,7 +13,6 @@
#include "video_core/renderer_vulkan/vk_rasterizer.h"
#include "video_core/renderer_vulkan/vk_renderpass_cache.h"
#include "video_core/renderer_vulkan/vk_scheduler.h"
#include "video_core/renderer_vulkan/vk_swapchain.h"
namespace Core {
class System;
@ -27,16 +22,24 @@ namespace Memory {
class MemorySystem;
}
namespace Pica {
class PicaCore;
}
namespace Layout {
struct FramebufferLayout;
}
namespace VideoCore {
class GPU;
}
namespace Vulkan {
struct TextureInfo {
u32 width;
u32 height;
GPU::Regs::PixelFormat format;
Pica::PixelFormat format;
vk::Image image;
vk::ImageView image_view;
VmaAllocation allocation;
@ -64,7 +67,7 @@ class RendererVulkan : public VideoCore::RendererBase {
static constexpr std::size_t PRESENT_PIPELINES = 3;
public:
explicit RendererVulkan(Core::System& system, Frontend::EmuWindow& window,
explicit RendererVulkan(Core::System& system, Pica::PicaCore& pica, Frontend::EmuWindow& window,
Frontend::EmuWindow* secondary_window);
~RendererVulkan() override;
@ -86,7 +89,7 @@ private:
void BuildLayouts();
void BuildPipelines();
void ConfigureFramebufferTexture(TextureInfo& texture,
const GPU::Regs::FramebufferConfig& framebuffer);
const Pica::FramebufferConfig& framebuffer);
void ConfigureRenderPipeline();
void PrepareRendertarget();
void RenderScreenshot();
@ -105,12 +108,13 @@ private:
Layout::DisplayOrientation orientation);
void DrawSingleScreenStereo(u32 screen_id_l, u32 screen_id_r, float x, float y, float w,
float h, Layout::DisplayOrientation orientation);
void LoadFBToScreenInfo(const GPU::Regs::FramebufferConfig& framebuffer,
ScreenInfo& screen_info, bool right_eye);
void LoadColorToActiveVkTexture(u8 color_r, u8 color_g, u8 color_b, const TextureInfo& texture);
void LoadFBToScreenInfo(const Pica::FramebufferConfig& framebuffer, ScreenInfo& screen_info,
bool right_eye);
void FillScreen(Common::Vec3<u8> color, const TextureInfo& texture);
private:
Memory::MemorySystem& memory;
Pica::PicaCore& pica;
Instance instance;
Scheduler scheduler;

View file

@ -3,9 +3,9 @@
// Refer to the license.txt file included.
#include "common/thread_worker.h"
#include "video_core/pica/regs_pipeline.h"
#include "video_core/pica/regs_rasterizer.h"
#include "video_core/rasterizer_cache/pixel_format.h"
#include "video_core/regs_pipeline.h"
#include "video_core/regs_rasterizer.h"
#include "video_core/renderer_vulkan/vk_common.h"
namespace Common {

View file

@ -6,8 +6,8 @@
#include <span>
#include "video_core/pica/regs_pipeline.h"
#include "video_core/rasterizer_cache/pixel_format.h"
#include "video_core/regs_pipeline.h"
#include "video_core/renderer_vulkan/vk_platform.h"
namespace Core {

View file

@ -2,6 +2,7 @@
// SPDX-License-Identifier: GPL-2.0-or-later
#include <limits>
#include <mutex>
#include "video_core/renderer_vulkan/vk_instance.h"
#include "video_core/renderer_vulkan/vk_master_semaphore.h"
#include "video_core/renderer_vulkan/vk_scheduler.h"

View file

@ -377,8 +377,8 @@ bool PipelineCache::BindPipeline(const PipelineInfo& info, bool wait_built) {
return true;
}
bool PipelineCache::UseProgrammableVertexShader(const Pica::Regs& regs,
Pica::Shader::ShaderSetup& setup,
bool PipelineCache::UseProgrammableVertexShader(const Pica::RegsInternal& regs,
Pica::ShaderSetup& setup,
const VertexLayout& layout) {
// Enable the geometry-shader only if we are actually doing per-fragment lighting
// and care about proper quaternions. Otherwise just use standard vertex+fragment shaders.
@ -443,7 +443,7 @@ void PipelineCache::UseTrivialVertexShader() {
shader_hashes[ProgramType::VS] = 0;
}
bool PipelineCache::UseFixedGeometryShader(const Pica::Regs& regs) {
bool PipelineCache::UseFixedGeometryShader(const Pica::RegsInternal& regs) {
if (!instance.UseGeometryShaders()) {
UseTrivialGeometryShader();
return true;
@ -472,7 +472,7 @@ void PipelineCache::UseTrivialGeometryShader() {
shader_hashes[ProgramType::GS] = 0;
}
void PipelineCache::UseFragmentShader(const Pica::Regs& regs,
void PipelineCache::UseFragmentShader(const Pica::RegsInternal& regs,
const Pica::Shader::UserConfig& user) {
const FSConfig fs_config{regs, user, profile};
const auto [it, new_shader] = fragment_shaders.try_emplace(fs_config, instance);

View file

@ -14,12 +14,9 @@
#include "video_core/shader/generator/shader_gen.h"
namespace Pica {
struct Regs;
}
namespace Pica::Shader {
struct RegsInternal;
struct ShaderSetup;
}
} // namespace Pica
namespace Vulkan {
@ -54,20 +51,20 @@ public:
bool BindPipeline(const PipelineInfo& info, bool wait_built = false);
/// Binds a PICA decompiled vertex shader
bool UseProgrammableVertexShader(const Pica::Regs& regs, Pica::Shader::ShaderSetup& setup,
bool UseProgrammableVertexShader(const Pica::RegsInternal& regs, Pica::ShaderSetup& setup,
const VertexLayout& layout);
/// Binds a passthrough vertex shader
void UseTrivialVertexShader();
/// Binds a PICA decompiled geometry shader
bool UseFixedGeometryShader(const Pica::Regs& regs);
bool UseFixedGeometryShader(const Pica::RegsInternal& regs);
/// Binds a passthrough geometry shader
void UseTrivialGeometryShader();
/// Binds a fragment shader generated from PICA state
void UseFragmentShader(const Pica::Regs& regs, const Pica::Shader::UserConfig& user);
void UseFragmentShader(const Pica::RegsInternal& regs, const Pica::Shader::UserConfig& user);
/// Binds a texture to the specified binding
void BindTexture(u32 binding, vk::ImageView image_view, vk::Sampler sampler);

View file

@ -8,10 +8,8 @@
#include "common/math_util.h"
#include "common/microprofile.h"
#include "common/settings.h"
#include "video_core/pica_state.h"
#include "video_core/regs_framebuffer.h"
#include "video_core/regs_pipeline.h"
#include "video_core/regs_rasterizer.h"
#include "core/memory.h"
#include "video_core/pica/pica_core.h"
#include "video_core/renderer_vulkan/renderer_vulkan.h"
#include "video_core/renderer_vulkan/vk_instance.h"
#include "video_core/renderer_vulkan/vk_rasterizer.h"
@ -56,13 +54,13 @@ struct DrawParams {
} // Anonymous namespace
RasterizerVulkan::RasterizerVulkan(Memory::MemorySystem& memory,
RasterizerVulkan::RasterizerVulkan(Memory::MemorySystem& memory, Pica::PicaCore& pica,
VideoCore::CustomTexManager& custom_tex_manager,
VideoCore::RendererBase& renderer,
Frontend::EmuWindow& emu_window, const Instance& instance,
Scheduler& scheduler, DescriptorPool& pool,
RenderpassCache& renderpass_cache, u32 image_count)
: RasterizerAccelerated{memory}, instance{instance}, scheduler{scheduler},
: RasterizerAccelerated{memory, pica}, instance{instance}, scheduler{scheduler},
renderpass_cache{renderpass_cache}, pipeline_cache{instance, scheduler, renderpass_cache,
pool},
runtime{instance, scheduler, renderpass_cache, pool, pipeline_cache.TextureProvider(),
@ -278,7 +276,7 @@ void RasterizerVulkan::SetupFixedAttribs() {
if (vertex_attributes.IsDefaultAttribute(i)) {
const u32 reg = regs.vs.GetRegisterForAttribute(i);
if (!enable_attributes[reg]) {
const auto& attr = Pica::g_state.input_default_attributes.attr[i];
const auto& attr = pica.input_default_attributes[i];
const std::array data = {attr.x.ToFloat32(), attr.y.ToFloat32(), attr.z.ToFloat32(),
attr.w.ToFloat32()};
@ -323,7 +321,7 @@ void RasterizerVulkan::SetupFixedAttribs() {
bool RasterizerVulkan::SetupVertexShader() {
MICROPROFILE_SCOPE(Vulkan_VS);
return pipeline_cache.UseProgrammableVertexShader(regs, Pica::g_state.vs,
return pipeline_cache.UseProgrammableVertexShader(regs, pica.vs_setup,
pipeline_info.vertex_layout);
}
@ -741,19 +739,19 @@ void RasterizerVulkan::ClearAll(bool flush) {
res_cache.ClearAll(flush);
}
bool RasterizerVulkan::AccelerateDisplayTransfer(const GPU::Regs::DisplayTransferConfig& config) {
bool RasterizerVulkan::AccelerateDisplayTransfer(const Pica::DisplayTransferConfig& config) {
return res_cache.AccelerateDisplayTransfer(config);
}
bool RasterizerVulkan::AccelerateTextureCopy(const GPU::Regs::DisplayTransferConfig& config) {
bool RasterizerVulkan::AccelerateTextureCopy(const Pica::DisplayTransferConfig& config) {
return res_cache.AccelerateTextureCopy(config);
}
bool RasterizerVulkan::AccelerateFill(const GPU::Regs::MemoryFillConfig& config) {
bool RasterizerVulkan::AccelerateFill(const Pica::MemoryFillConfig& config) {
return res_cache.AccelerateFill(config);
}
bool RasterizerVulkan::AccelerateDisplay(const GPU::Regs::FramebufferConfig& config,
bool RasterizerVulkan::AccelerateDisplay(const Pica::FramebufferConfig& config,
PAddr framebuffer_addr, u32 pixel_stride,
ScreenInfo& screen_info) {
if (framebuffer_addr == 0) [[unlikely]] {
@ -935,7 +933,7 @@ void RasterizerVulkan::SyncAndUploadLUTsLF() {
for (unsigned index = 0; index < fs_uniform_block_data.lighting_lut_dirty.size(); index++) {
if (fs_uniform_block_data.lighting_lut_dirty[index] || invalidate) {
std::array<Common::Vec2f, 256> new_data;
const auto& source_lut = Pica::g_state.lighting.luts[index];
const auto& source_lut = pica.lighting.luts[index];
std::transform(source_lut.begin(), source_lut.end(), new_data.begin(),
[](const auto& entry) {
return Common::Vec2f{entry.ToFloat(), entry.DiffToFloat()};
@ -960,7 +958,7 @@ void RasterizerVulkan::SyncAndUploadLUTsLF() {
if (fs_uniform_block_data.fog_lut_dirty || invalidate) {
std::array<Common::Vec2f, 128> new_data;
std::transform(Pica::g_state.fog.lut.begin(), Pica::g_state.fog.lut.end(), new_data.begin(),
std::transform(pica.fog.lut.begin(), pica.fog.lut.end(), new_data.begin(),
[](const auto& entry) {
return Common::Vec2f{entry.ToFloat(), entry.DiffToFloat()};
});
@ -981,7 +979,7 @@ void RasterizerVulkan::SyncAndUploadLUTsLF() {
}
void RasterizerVulkan::SyncAndUploadLUTs() {
const auto& proctex = Pica::g_state.proctex;
const auto& proctex = pica.proctex;
constexpr std::size_t max_size =
sizeof(Common::Vec2f) * 128 * 3 + // proctex: noise + color + alpha
sizeof(Common::Vec4f) * 256 + // proctex
@ -1000,7 +998,7 @@ void RasterizerVulkan::SyncAndUploadLUTs() {
// helper function for SyncProcTexNoiseLUT/ColorMap/AlphaMap
auto sync_proctex_value_lut =
[this, buffer = buffer, offset = offset, invalidate = invalidate,
&bytes_used](const std::array<Pica::State::ProcTex::ValueEntry, 128>& lut,
&bytes_used](const std::array<Pica::PicaCore::ProcTex::ValueEntry, 128>& lut,
std::array<Common::Vec2f, 128>& lut_data, int& lut_offset) {
std::array<Common::Vec2f, 128> new_data;
std::transform(lut.begin(), lut.end(), new_data.begin(), [](const auto& entry) {
@ -1120,7 +1118,7 @@ void RasterizerVulkan::UploadUniforms(bool accelerate_draw) {
if (sync_vs_pica) {
VSPicaUniformData vs_uniforms;
vs_uniforms.uniforms.SetFromRegs(regs.vs, Pica::g_state.vs);
vs_uniforms.uniforms.SetFromRegs(regs.vs, pica.vs_setup);
std::memcpy(uniforms + used_bytes, &vs_uniforms, sizeof(vs_uniforms));
pipeline_cache.SetBufferOffset(0, offset + used_bytes);

View file

@ -4,7 +4,6 @@
#pragma once
#include "core/hw/gpu.h"
#include "video_core/rasterizer_accelerated.h"
#include "video_core/renderer_vulkan/vk_pipeline_cache.h"
#include "video_core/renderer_vulkan/vk_renderpass_cache.h"
@ -20,6 +19,12 @@ class CustomTexManager;
class RendererBase;
} // namespace VideoCore
namespace Pica {
struct DisplayTransferConfig;
struct MemoryFillConfig;
struct FramebufferConfig;
} // namespace Pica
namespace Vulkan {
struct ScreenInfo;
@ -31,7 +36,7 @@ class DescriptorPool;
class RasterizerVulkan : public VideoCore::RasterizerAccelerated {
public:
explicit RasterizerVulkan(Memory::MemorySystem& memory,
explicit RasterizerVulkan(Memory::MemorySystem& memory, Pica::PicaCore& pica,
VideoCore::CustomTexManager& custom_tex_manager,
VideoCore::RendererBase& renderer, Frontend::EmuWindow& emu_window,
const Instance& instance, Scheduler& scheduler, DescriptorPool& pool,
@ -48,10 +53,10 @@ public:
void InvalidateRegion(PAddr addr, u32 size) override;
void FlushAndInvalidateRegion(PAddr addr, u32 size) override;
void ClearAll(bool flush) override;
bool AccelerateDisplayTransfer(const GPU::Regs::DisplayTransferConfig& config) override;
bool AccelerateTextureCopy(const GPU::Regs::DisplayTransferConfig& config) override;
bool AccelerateFill(const GPU::Regs::MemoryFillConfig& config) override;
bool AccelerateDisplay(const GPU::Regs::FramebufferConfig& config, PAddr framebuffer_addr,
bool AccelerateDisplayTransfer(const Pica::DisplayTransferConfig& config) override;
bool AccelerateTextureCopy(const Pica::DisplayTransferConfig& config) override;
bool AccelerateFill(const Pica::MemoryFillConfig& config) override;
bool AccelerateDisplay(const Pica::FramebufferConfig& config, PAddr framebuffer_addr,
u32 pixel_stride, ScreenInfo& screen_info);
bool AccelerateDrawBatch(bool is_indexed) override;

View file

@ -914,7 +914,7 @@ void FragmentModule::WriteLogicOp() {
}
void FragmentModule::WriteBlending() {
if (!config.EmulateBlend()) [[likely]] {
if (!config.EmulateBlend() || profile.is_vulkan) [[likely]] {
return;
}
@ -1258,7 +1258,7 @@ void FragmentModule::DefineExtensions() {
use_fragment_shader_barycentric = false;
}
}
if (config.EmulateBlend()) {
if (config.EmulateBlend() && !profile.is_vulkan) {
if (profile.has_gl_ext_framebuffer_fetch) {
out += "#extension GL_EXT_shader_framebuffer_fetch : enable\n";
out += "#define destFactor color\n";

View file

@ -23,7 +23,7 @@ using nihstro::RegisterType;
using nihstro::SourceRegister;
using nihstro::SwizzlePattern;
constexpr u32 PROGRAM_END = Pica::Shader::MAX_PROGRAM_CODE_LENGTH;
constexpr u32 PROGRAM_END = MAX_PROGRAM_CODE_LENGTH;
class DecompileFail : public std::runtime_error {
public:
@ -58,7 +58,7 @@ struct Subroutine {
/// Analyzes shader code and produces a set of subroutines.
class ControlFlowAnalyzer {
public:
ControlFlowAnalyzer(const Pica::Shader::ProgramCode& program_code, u32 main_offset)
ControlFlowAnalyzer(const ProgramCode& program_code, u32 main_offset)
: program_code(program_code) {
// Recursively finds all subroutines.
@ -72,7 +72,7 @@ public:
}
private:
const Pica::Shader::ProgramCode& program_code;
const ProgramCode& program_code;
std::set<Subroutine> subroutines;
std::map<std::pair<u32, u32>, ExitMethod> exit_method_map;
@ -265,9 +265,8 @@ constexpr auto GetSelectorSrc3 = GetSelectorSrc<&SwizzlePattern::GetSelectorSrc3
class GLSLGenerator {
public:
GLSLGenerator(const std::set<Subroutine>& subroutines,
const Pica::Shader::ProgramCode& program_code,
const Pica::Shader::SwizzleData& swizzle_data, u32 main_offset,
GLSLGenerator(const std::set<Subroutine>& subroutines, const ProgramCode& program_code,
const SwizzleData& swizzle_data, u32 main_offset,
const RegGetter& inputreg_getter, const RegGetter& outputreg_getter,
bool sanitize_mul)
: subroutines(subroutines), program_code(program_code), swizzle_data(swizzle_data),
@ -921,8 +920,8 @@ private:
private:
const std::set<Subroutine>& subroutines;
const Pica::Shader::ProgramCode& program_code;
const Pica::Shader::SwizzleData& swizzle_data;
const ProgramCode& program_code;
const SwizzleData& swizzle_data;
const u32 main_offset;
const RegGetter& inputreg_getter;
const RegGetter& outputreg_getter;
@ -931,10 +930,9 @@ private:
ShaderWriter shader;
};
std::string DecompileProgram(const Pica::Shader::ProgramCode& program_code,
const Pica::Shader::SwizzleData& swizzle_data, u32 main_offset,
const RegGetter& inputreg_getter, const RegGetter& outputreg_getter,
bool sanitize_mul) {
std::string DecompileProgram(const ProgramCode& program_code, const SwizzleData& swizzle_data,
u32 main_offset, const RegGetter& inputreg_getter,
const RegGetter& outputreg_getter, bool sanitize_mul) {
try {
auto subroutines = ControlFlowAnalyzer(program_code, main_offset).MoveSubroutines();

View file

@ -6,15 +6,14 @@
#include <functional>
#include <string>
#include "common/common_types.h"
#include "video_core/shader/shader.h"
#include "video_core/pica/shader_setup.h"
namespace Pica::Shader::Generator::GLSL {
using RegGetter = std::function<std::string(u32)>;
std::string DecompileProgram(const Pica::Shader::ProgramCode& program_code,
const Pica::Shader::SwizzleData& swizzle_data, u32 main_offset,
std::string DecompileProgram(const Pica::ProgramCode& program_code,
const Pica::SwizzleData& swizzle_data, u32 main_offset,
const RegGetter& inputreg_getter, const RegGetter& outputreg_getter,
bool sanitize_mul);

View file

@ -5,9 +5,10 @@
#include <string_view>
#include <fmt/format.h>
#include "common/logging/log.h"
#include "video_core/pica/regs_rasterizer.h"
#include "video_core/shader/generator/glsl_shader_decompiler.h"
#include "video_core/shader/generator/glsl_shader_gen.h"
#include "video_core/shader/generator/shader_gen.h"
using VSOutputAttributes = Pica::RasterizerRegs::VSOutputAttributes;
@ -141,7 +142,7 @@ std::string_view MakeLoadPrefix(AttribLoadFlags flag) {
return "";
}
std::string GenerateVertexShader(const Pica::Shader::ShaderSetup& setup, const PicaVSConfig& config,
std::string GenerateVertexShader(const ShaderSetup& setup, const PicaVSConfig& config,
bool separable_shader) {
std::string out;
if (separable_shader) {

View file

@ -4,9 +4,6 @@
#pragma once
#include "video_core/shader/generator/shader_gen.h"
#include "video_core/shader/shader.h"
// High precision may or may not be supported in GLES3. If it isn't, use medium precision instead.
static constexpr char fragment_shader_precision_OES[] = R"(
#if GL_ES
@ -24,6 +21,15 @@ precision mediump uimage2D;
#endif
)";
namespace Pica {
struct ShaderSetup;
}
namespace Pica::Shader::Generator {
struct PicaVSConfig;
struct PicaFixedGSConfig;
} // namespace Pica::Shader::Generator
namespace Pica::Shader::Generator::GLSL {
/**
@ -37,7 +43,7 @@ std::string GenerateTrivialVertexShader(bool use_clip_planes, bool separable_sha
* Generates the GLSL vertex shader program source code for the given VS program
* @returns String of the shader source code; empty on failure
*/
std::string GenerateVertexShader(const Pica::Shader::ShaderSetup& setup, const PicaVSConfig& config,
std::string GenerateVertexShader(const Pica::ShaderSetup& setup, const PicaVSConfig& config,
bool separable_shader);
/**

View file

@ -6,7 +6,7 @@
namespace Pica::Shader {
FramebufferConfig::FramebufferConfig(const Pica::Regs& regs, const Profile& profile) {
FramebufferConfig::FramebufferConfig(const Pica::RegsInternal& regs, const Profile& profile) {
const auto& output_merger = regs.framebuffer.output_merger;
scissor_test_mode.Assign(regs.rasterizer.scissor_test.mode);
depthmap_enable.Assign(regs.rasterizer.depthmap_enable);
@ -186,7 +186,7 @@ ProcTexConfig::ProcTexConfig(const Pica::TexturingRegs& regs) {
lut_filter.Assign(regs.proctex_lut.filter);
}
FSConfig::FSConfig(const Pica::Regs& regs, const UserConfig& user_, const Profile& profile)
FSConfig::FSConfig(const Pica::RegsInternal& regs, const UserConfig& user_, const Profile& profile)
: framebuffer{regs, profile}, texture{regs.texturing, profile}, lighting{regs.lighting},
proctex{regs.texturing}, user{user_} {}

View file

@ -5,7 +5,7 @@
#pragma once
#include "common/hash.h"
#include "video_core/regs.h"
#include "video_core/pica/regs_internal.h"
#include "video_core/shader/generator/profile.h"
namespace Pica::Shader {
@ -17,7 +17,7 @@ struct BlendConfig {
};
struct FramebufferConfig {
explicit FramebufferConfig(const Pica::Regs& regs, const Profile& profile);
explicit FramebufferConfig(const Pica::RegsInternal& regs, const Profile& profile);
union {
u32 raw{};
@ -158,7 +158,8 @@ union UserConfig {
static_assert(std::has_unique_object_representations_v<UserConfig>);
struct FSConfig {
explicit FSConfig(const Pica::Regs& regs, const UserConfig& user, const Profile& profile);
explicit FSConfig(const Pica::RegsInternal& regs, const UserConfig& user,
const Profile& profile);
[[nodiscard]] bool TevStageUpdatesCombinerBufferColor(u32 stage_index) const {
return (stage_index < 4) && (texture.combiner_buffer_input & (1 << stage_index));

View file

@ -4,12 +4,14 @@
#include "common/bit_set.h"
#include "common/logging/log.h"
#include "common/settings.h"
#include "video_core/pica/regs_internal.h"
#include "video_core/pica/shader_setup.h"
#include "video_core/shader/generator/shader_gen.h"
#include "video_core/video_core.h"
namespace Pica::Shader::Generator {
void PicaGSConfigState::Init(const Pica::Regs& regs, bool use_clip_planes_) {
void PicaGSConfigState::Init(const Pica::RegsInternal& regs, bool use_clip_planes_) {
use_clip_planes = use_clip_planes_;
vs_output_attributes = Common::BitSet<u32>(regs.vs.output_mask).Count();
@ -34,7 +36,7 @@ void PicaGSConfigState::Init(const Pica::Regs& regs, bool use_clip_planes_) {
}
}
void PicaVSConfigState::Init(const Pica::Regs& regs, Pica::Shader::ShaderSetup& setup,
void PicaVSConfigState::Init(const Pica::RegsInternal& regs, Pica::ShaderSetup& setup,
bool use_clip_planes_, bool use_geometry_shader_) {
use_clip_planes = use_clip_planes_;
use_geometry_shader = use_geometry_shader_;
@ -42,13 +44,13 @@ void PicaVSConfigState::Init(const Pica::Regs& regs, Pica::Shader::ShaderSetup&
program_hash = setup.GetProgramCodeHash();
swizzle_hash = setup.GetSwizzleDataHash();
main_offset = regs.vs.main_offset;
sanitize_mul = VideoCore::g_hw_shader_accurate_mul;
sanitize_mul = Settings::values.shaders_accurate_mul.GetValue();
num_outputs = 0;
load_flags.fill(AttribLoadFlags::Float);
output_map.fill(16);
for (int reg : Common::BitSet<u32>(regs.vs.output_mask)) {
for (u32 reg : Common::BitSet<u32>(regs.vs.output_mask)) {
output_map[reg] = num_outputs++;
}
@ -57,12 +59,12 @@ void PicaVSConfigState::Init(const Pica::Regs& regs, Pica::Shader::ShaderSetup&
}
}
PicaVSConfig::PicaVSConfig(const Pica::Regs& regs, Pica::Shader::ShaderSetup& setup,
PicaVSConfig::PicaVSConfig(const Pica::RegsInternal& regs, Pica::ShaderSetup& setup,
bool use_clip_planes_, bool use_geometry_shader_) {
state.Init(regs, setup, use_clip_planes_, use_geometry_shader_);
}
PicaFixedGSConfig::PicaFixedGSConfig(const Pica::Regs& regs, bool use_clip_planes_) {
PicaFixedGSConfig::PicaFixedGSConfig(const Pica::RegsInternal& regs, bool use_clip_planes_) {
state.Init(regs, use_clip_planes_);
}

View file

@ -5,8 +5,11 @@
#pragma once
#include "common/hash.h"
#include "video_core/regs.h"
#include "video_core/shader/shader.h"
namespace Pica {
struct RegsInternal;
struct ShaderSetup;
} // namespace Pica
namespace Pica::Shader::Generator {
@ -41,7 +44,7 @@ DECLARE_ENUM_FLAG_OPERATORS(AttribLoadFlags)
* PICA geometry shader.
*/
struct PicaGSConfigState {
void Init(const Pica::Regs& regs, bool use_clip_planes_);
void Init(const Pica::RegsInternal& regs, bool use_clip_planes_);
bool use_clip_planes;
@ -62,7 +65,7 @@ struct PicaGSConfigState {
* PICA vertex shader.
*/
struct PicaVSConfigState {
void Init(const Pica::Regs& regs, Pica::Shader::ShaderSetup& setup, bool use_clip_planes_,
void Init(const Pica::RegsInternal& regs, Pica::ShaderSetup& setup, bool use_clip_planes_,
bool use_geometry_shader_);
bool use_clip_planes;
@ -88,7 +91,7 @@ struct PicaVSConfigState {
* shader.
*/
struct PicaVSConfig : Common::HashableStruct<PicaVSConfigState> {
explicit PicaVSConfig(const Pica::Regs& regs, Pica::Shader::ShaderSetup& setup,
explicit PicaVSConfig(const Pica::RegsInternal& regs, Pica::ShaderSetup& setup,
bool use_clip_planes_, bool use_geometry_shader_);
};
@ -97,7 +100,7 @@ struct PicaVSConfig : Common::HashableStruct<PicaVSConfigState> {
* shader pipeline
*/
struct PicaFixedGSConfig : Common::HashableStruct<PicaGSConfigState> {
explicit PicaFixedGSConfig(const Pica::Regs& regs, bool use_clip_planes_);
explicit PicaFixedGSConfig(const Pica::RegsInternal& regs, bool use_clip_planes_);
};
} // namespace Pica::Shader::Generator

View file

@ -3,13 +3,13 @@
// Refer to the license.txt file included.
#include <algorithm>
#include "video_core/pica/regs_shader.h"
#include "video_core/pica/shader_setup.h"
#include "video_core/shader/generator/shader_uniforms.h"
#include "video_core/shader/shader.h"
namespace Pica::Shader::Generator {
void PicaUniformsData::SetFromRegs(const Pica::ShaderRegs& regs,
const Pica::Shader::ShaderSetup& setup) {
void PicaUniformsData::SetFromRegs(const Pica::ShaderRegs& regs, const Pica::ShaderSetup& setup) {
std::transform(std::begin(setup.uniforms.b), std::end(setup.uniforms.b), std::begin(bools),
[](bool value) -> BoolAligned { return {value ? 1 : 0}; });
std::transform(std::begin(regs.int_uniforms), std::end(regs.int_uniforms), std::begin(i),

View file

@ -5,15 +5,12 @@
#pragma once
#include "common/vector_math.h"
#include "video_core/regs_lighting.h"
#include "video_core/pica/regs_lighting.h"
namespace Pica {
struct ShaderRegs;
}
namespace Pica::Shader {
struct ShaderSetup;
}
} // namespace Pica
namespace Pica::Shader::Generator {
@ -24,8 +21,8 @@ struct LightSrc {
alignas(16) Common::Vec3f ambient;
alignas(16) Common::Vec3f position;
alignas(16) Common::Vec3f spot_direction; // negated
float dist_atten_bias;
float dist_atten_scale;
f32 dist_atten_bias;
f32 dist_atten_scale;
};
/**

View file

@ -3,6 +3,7 @@
// Refer to the license.txt file included.
#include <boost/container/small_vector.hpp>
#include "video_core/shader/generator/pica_fs_config.h"
#include "video_core/shader/generator/spv_fs_shader_gen.h"
namespace Pica::Shader::Generator::SPIRV {

View file

@ -7,7 +7,13 @@
#include <array>
#include <sirit/sirit.h>
#include "video_core/shader/generator/pica_fs_config.h"
#include "video_core/pica/regs_framebuffer.h"
#include "video_core/pica/regs_texturing.h"
namespace Pica::Shader {
struct FSConfig;
struct Profile;
} // namespace Pica::Shader
namespace Pica::Shader::Generator::SPIRV {

View file

@ -2,166 +2,23 @@
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#include <cmath>
#include <cstring>
#include "common/arch.h"
#include "common/assert.h"
#include "common/bit_set.h"
#include "common/logging/log.h"
#include "common/microprofile.h"
#include "video_core/regs_rasterizer.h"
#include "video_core/regs_shader.h"
#include "video_core/shader/shader.h"
#include "video_core/shader/shader_interpreter.h"
#if CITRA_ARCH(x86_64) || CITRA_ARCH(arm64)
#include "video_core/shader/shader_jit.h"
#endif // CITRA_ARCH(x86_64) || CITRA_ARCH(arm64)
#include "video_core/video_core.h"
#endif
#include "video_core/shader/shader.h"
namespace Pica::Shader {
void OutputVertex::ValidateSemantics(const RasterizerRegs& regs) {
u32 num_attributes = regs.vs_output_total;
ASSERT(num_attributes <= 7);
for (std::size_t attrib = 0; attrib < num_attributes; ++attrib) {
u32 output_register_map = regs.vs_output_attributes[attrib].raw;
for (std::size_t comp = 0; comp < 4; ++comp) {
u32 semantic = (output_register_map >> (8 * comp)) & 0x1F;
ASSERT_MSG(semantic < 24 || semantic == RasterizerRegs::VSOutputAttributes::INVALID,
"Invalid/unknown semantic id: {}", semantic);
}
}
}
OutputVertex OutputVertex::FromAttributeBuffer(const RasterizerRegs& regs,
const AttributeBuffer& input) {
// Setup output data
union {
OutputVertex ret{};
// Allow us to overflow OutputVertex to avoid branches, since
// RasterizerRegs::VSOutputAttributes::INVALID would write to slot 31, which
// would be out of bounds otherwise.
std::array<f24, 32> vertex_slots_overflow;
};
// Some games use attributes without setting them in GPUREG_SH_OUTMAP_Oi
// Hardware tests have shown that they are initialized to 1.f in this case.
vertex_slots_overflow.fill(f24::One());
// Assert that OutputVertex has enough space for 24 semantic registers
static_assert(sizeof(std::array<f24, 24>) == sizeof(ret),
"Struct and array have different sizes.");
u32 num_attributes = regs.vs_output_total & 7;
for (std::size_t attrib = 0; attrib < num_attributes; ++attrib) {
const auto output_register_map = regs.vs_output_attributes[attrib];
vertex_slots_overflow[output_register_map.map_x] = input.attr[attrib][0];
vertex_slots_overflow[output_register_map.map_y] = input.attr[attrib][1];
vertex_slots_overflow[output_register_map.map_z] = input.attr[attrib][2];
vertex_slots_overflow[output_register_map.map_w] = input.attr[attrib][3];
}
// The hardware takes the absolute and saturates vertex colors like this, *before* doing
// interpolation
for (u32 i = 0; i < 4; ++i) {
float c = std::fabs(ret.color[i].ToFloat32());
ret.color[i] = f24::FromFloat32(c < 1.0f ? c : 1.0f);
}
LOG_TRACE(HW_GPU,
"Output vertex: pos({:.2}, {:.2}, {:.2}, {:.2}), quat({:.2}, {:.2}, {:.2}, {:.2}), "
"col({:.2}, {:.2}, {:.2}, {:.2}), tc0({:.2}, {:.2}), view({:.2}, {:.2}, {:.2})",
ret.pos.x.ToFloat32(), ret.pos.y.ToFloat32(), ret.pos.z.ToFloat32(),
ret.pos.w.ToFloat32(), ret.quat.x.ToFloat32(), ret.quat.y.ToFloat32(),
ret.quat.z.ToFloat32(), ret.quat.w.ToFloat32(), ret.color.x.ToFloat32(),
ret.color.y.ToFloat32(), ret.color.z.ToFloat32(), ret.color.w.ToFloat32(),
ret.tc0.u().ToFloat32(), ret.tc0.v().ToFloat32(), ret.view.x.ToFloat32(),
ret.view.y.ToFloat32(), ret.view.z.ToFloat32());
return ret;
}
void UnitState::LoadInput(const ShaderRegs& config, const AttributeBuffer& input) {
const u32 max_attribute = config.max_input_attribute_index;
for (u32 attr = 0; attr <= max_attribute; ++attr) {
u32 reg = config.GetRegisterForAttribute(attr);
registers.input[reg] = input.attr[attr];
}
}
static void CopyRegistersToOutput(std::span<Common::Vec4<f24>, 16> regs, u32 mask,
AttributeBuffer& buffer) {
int output_i = 0;
for (int reg : Common::BitSet<u32>(mask)) {
buffer.attr[output_i++] = regs[reg];
}
}
void UnitState::WriteOutput(const ShaderRegs& config, AttributeBuffer& output) {
CopyRegistersToOutput(registers.output, config.output_mask, output);
}
UnitState::UnitState(GSEmitter* emitter) : emitter_ptr(emitter) {}
GSEmitter::GSEmitter() {
handlers = new Handlers;
}
GSEmitter::~GSEmitter() {
delete handlers;
}
void GSEmitter::Emit(std::span<Common::Vec4<f24>, 16> output_regs) {
ASSERT(vertex_id < 3);
// TODO: This should be merged with UnitState::WriteOutput somehow
CopyRegistersToOutput(output_regs, output_mask, buffer[vertex_id]);
if (prim_emit) {
if (winding)
handlers->winding_setter();
for (std::size_t i = 0; i < buffer.size(); ++i) {
handlers->vertex_handler(buffer[i]);
}
}
}
GSUnitState::GSUnitState() : UnitState(&emitter) {}
void GSUnitState::SetVertexHandler(VertexHandler vertex_handler, WindingSetter winding_setter) {
emitter.handlers->vertex_handler = std::move(vertex_handler);
emitter.handlers->winding_setter = std::move(winding_setter);
}
void GSUnitState::ConfigOutput(const ShaderRegs& config) {
emitter.output_mask = config.output_mask;
}
MICROPROFILE_DEFINE(GPU_Shader, "GPU", "Shader", MP_RGB(50, 50, 240));
namespace Pica {
std::unique_ptr<ShaderEngine> CreateEngine(bool use_jit) {
#if CITRA_ARCH(x86_64) || CITRA_ARCH(arm64)
static std::unique_ptr<JitEngine> jit_engine;
#endif // CITRA_ARCH(x86_64) || CITRA_ARCH(arm64)
static InterpreterEngine interpreter_engine;
ShaderEngine* GetEngine() {
#if CITRA_ARCH(x86_64) || CITRA_ARCH(arm64)
// TODO(yuriks): Re-initialize on each change rather than being persistent
if (VideoCore::g_shader_jit_enabled) {
if (jit_engine == nullptr) {
jit_engine = std::make_unique<JitEngine>();
}
return jit_engine.get();
if (use_jit) {
return std::make_unique<Shader::JitEngine>();
}
#endif // CITRA_ARCH(x86_64) || CITRA_ARCH(arm64)
#endif
return &interpreter_engine;
return std::make_unique<Shader::InterpreterEngine>();
}
void Shutdown() {
#if CITRA_ARCH(x86_64) || CITRA_ARCH(arm64)
jit_engine.reset();
#endif // CITRA_ARCH(x86_64) || CITRA_ARCH(arm64)
}
} // namespace Pica::Shader
} // namespace Pica

View file

@ -4,301 +4,12 @@
#pragma once
#include <array>
#include <cstddef>
#include <functional>
#include <span>
#include <type_traits>
#include <boost/serialization/access.hpp>
#include <boost/serialization/array.hpp>
#include <boost/serialization/base_object.hpp>
#include "common/common_funcs.h"
#include "common/common_types.h"
#include "common/hash.h"
#include "common/vector_math.h"
#include "video_core/pica_types.h"
#include "video_core/regs_rasterizer.h"
#include "video_core/regs_shader.h"
namespace Pica::Shader {
namespace Pica {
constexpr u32 MAX_PROGRAM_CODE_LENGTH = 4096;
constexpr u32 MAX_SWIZZLE_DATA_LENGTH = 4096;
using ProgramCode = std::array<u32, MAX_PROGRAM_CODE_LENGTH>;
using SwizzleData = std::array<u32, MAX_SWIZZLE_DATA_LENGTH>;
struct AttributeBuffer {
alignas(16) Common::Vec4<f24> attr[16];
private:
friend class boost::serialization::access;
template <class Archive>
void serialize(Archive& ar, const u32 file_version) {
ar& attr;
}
};
/// Handler type for receiving vertex outputs from vertex shader or geometry shader
using VertexHandler = std::function<void(const AttributeBuffer&)>;
/// Handler type for signaling to invert the vertex order of the next triangle
using WindingSetter = std::function<void()>;
struct OutputVertex {
Common::Vec4<f24> pos;
Common::Vec4<f24> quat;
Common::Vec4<f24> color;
Common::Vec2<f24> tc0;
Common::Vec2<f24> tc1;
f24 tc0_w;
INSERT_PADDING_WORDS(1);
Common::Vec3<f24> view;
INSERT_PADDING_WORDS(1);
Common::Vec2<f24> tc2;
static void ValidateSemantics(const RasterizerRegs& regs);
static OutputVertex FromAttributeBuffer(const RasterizerRegs& regs,
const AttributeBuffer& output);
private:
template <class Archive>
void serialize(Archive& ar, const u32) {
ar& pos;
ar& quat;
ar& color;
ar& tc0;
ar& tc1;
ar& tc0_w;
ar& view;
ar& tc2;
}
friend class boost::serialization::access;
};
#define ASSERT_POS(var, pos) \
static_assert(offsetof(OutputVertex, var) == pos * sizeof(f24), "Semantic at wrong " \
"offset.")
ASSERT_POS(pos, RasterizerRegs::VSOutputAttributes::POSITION_X);
ASSERT_POS(quat, RasterizerRegs::VSOutputAttributes::QUATERNION_X);
ASSERT_POS(color, RasterizerRegs::VSOutputAttributes::COLOR_R);
ASSERT_POS(tc0, RasterizerRegs::VSOutputAttributes::TEXCOORD0_U);
ASSERT_POS(tc1, RasterizerRegs::VSOutputAttributes::TEXCOORD1_U);
ASSERT_POS(tc0_w, RasterizerRegs::VSOutputAttributes::TEXCOORD0_W);
ASSERT_POS(view, RasterizerRegs::VSOutputAttributes::VIEW_X);
ASSERT_POS(tc2, RasterizerRegs::VSOutputAttributes::TEXCOORD2_U);
#undef ASSERT_POS
static_assert(std::is_trivial_v<OutputVertex>, "Structure is not POD");
static_assert(sizeof(OutputVertex) == 24 * sizeof(float), "OutputVertex has invalid size");
/**
* This structure contains state information for primitive emitting in geometry shader.
*/
struct GSEmitter {
std::array<AttributeBuffer, 3> buffer;
u8 vertex_id;
bool prim_emit;
bool winding;
u32 output_mask;
// Function objects are hidden behind a raw pointer to make the structure standard layout type,
// for JIT to use offsetof to access other members.
struct Handlers {
VertexHandler vertex_handler;
WindingSetter winding_setter;
}* handlers;
GSEmitter();
~GSEmitter();
void Emit(std::span<Common::Vec4<f24>, 16> output_regs);
private:
friend class boost::serialization::access;
template <class Archive>
void serialize(Archive& ar, const u32 file_version) {
ar& buffer;
ar& vertex_id;
ar& prim_emit;
ar& winding;
ar& output_mask;
// Handlers are ignored because they're constant
}
};
static_assert(std::is_standard_layout<GSEmitter>::value, "GSEmitter is not standard layout type");
/**
* This structure contains the state information that needs to be unique for a shader unit. The 3DS
* has four shader units that process shaders in parallel. At the present, Citra only implements a
* single shader unit that processes all shaders serially. Putting the state information in a struct
* here will make it easier for us to parallelize the shader processing later.
*/
struct UnitState {
explicit UnitState(GSEmitter* emitter = nullptr);
// Two Address registers and one loop counter
// TODO: How many bits do these actually have?
s32 address_registers[3];
bool conditional_code[2];
struct Registers {
// The registers are accessed by the shader JIT using SSE instructions, and are therefore
// required to be 16-byte aligned.
alignas(16) std::array<Common::Vec4<f24>, 16> input;
alignas(16) std::array<Common::Vec4<f24>, 16> temporary;
alignas(16) std::array<Common::Vec4<f24>, 16> output;
private:
friend class boost::serialization::access;
template <class Archive>
void serialize(Archive& ar, const u32 file_version) {
ar& input;
ar& temporary;
ar& output;
}
} registers;
static_assert(std::is_trivial_v<Registers>, "Structure is not POD");
GSEmitter* emitter_ptr;
static std::size_t InputOffset(s32 register_index) {
return offsetof(UnitState, registers.input) + register_index * sizeof(Common::Vec4<f24>);
}
static std::size_t OutputOffset(s32 register_index) {
return offsetof(UnitState, registers.output) + register_index * sizeof(Common::Vec4<f24>);
}
static std::size_t TemporaryOffset(s32 register_index) {
return offsetof(UnitState, registers.temporary) +
register_index * sizeof(Common::Vec4<f24>);
}
/**
* Loads the unit state with an input vertex.
*
* @param config Shader configuration registers corresponding to the unit.
* @param input Attribute buffer to load into the input registers.
*/
void LoadInput(const ShaderRegs& config, const AttributeBuffer& input);
void WriteOutput(const ShaderRegs& config, AttributeBuffer& output);
private:
friend class boost::serialization::access;
template <class Archive>
void serialize(Archive& ar, const u32 file_version) {
ar& registers;
ar& conditional_code;
ar& address_registers;
// emitter_ptr is only set by GSUnitState and is serialized there
}
};
/**
* This is an extended shader unit state that represents the special unit that can run both vertex
* shader and geometry shader. It contains an additional primitive emitter and utilities for
* geometry shader.
*/
struct GSUnitState : public UnitState {
GSUnitState();
void SetVertexHandler(VertexHandler vertex_handler, WindingSetter winding_setter);
void ConfigOutput(const ShaderRegs& config);
GSEmitter emitter;
private:
friend class boost::serialization::access;
template <class Archive>
void serialize(Archive& ar, const u32 file_version) {
ar& boost::serialization::base_object<UnitState>(*this);
ar& emitter;
}
};
struct Uniforms {
// The float uniforms are accessed by the shader JIT using SSE instructions, and are
// therefore required to be 16-byte aligned.
alignas(16) std::array<Common::Vec4<f24>, 96> f;
std::array<bool, 16> b;
std::array<Common::Vec4<u8>, 4> i;
static std::size_t GetFloatUniformOffset(u32 index) {
return offsetof(Uniforms, f) + index * sizeof(Common::Vec4<f24>);
}
static std::size_t GetBoolUniformOffset(u32 index) {
return offsetof(Uniforms, b) + index * sizeof(bool);
}
static std::size_t GetIntUniformOffset(u32 index) {
return offsetof(Uniforms, i) + index * sizeof(Common::Vec4<u8>);
}
private:
friend class boost::serialization::access;
template <class Archive>
void serialize(Archive& ar, const u32 file_version) {
ar& f;
ar& b;
ar& i;
}
};
struct ShaderSetup {
Uniforms uniforms;
ProgramCode program_code;
SwizzleData swizzle_data;
/// Data private to ShaderEngines
struct EngineData {
u32 entry_point;
/// Used by the JIT, points to a compiled shader object.
const void* cached_shader = nullptr;
} engine_data;
void MarkProgramCodeDirty() {
program_code_hash_dirty = true;
}
void MarkSwizzleDataDirty() {
swizzle_data_hash_dirty = true;
}
u64 GetProgramCodeHash() {
if (program_code_hash_dirty) {
program_code_hash = Common::ComputeHash64(&program_code, sizeof(program_code));
program_code_hash_dirty = false;
}
return program_code_hash;
}
u64 GetSwizzleDataHash() {
if (swizzle_data_hash_dirty) {
swizzle_data_hash = Common::ComputeHash64(&swizzle_data, sizeof(swizzle_data));
swizzle_data_hash_dirty = false;
}
return swizzle_data_hash;
}
private:
bool program_code_hash_dirty = true;
bool swizzle_data_hash_dirty = true;
u64 program_code_hash = 0xDEADC0DE;
u64 swizzle_data_hash = 0xDEADC0DE;
friend class boost::serialization::access;
template <class Archive>
void serialize(Archive& ar, const u32 file_version) {
ar& uniforms;
ar& program_code;
ar& swizzle_data;
ar& program_code_hash_dirty;
ar& swizzle_data_hash_dirty;
ar& program_code_hash;
ar& swizzle_data_hash;
}
};
struct ShaderSetup;
struct ShaderUnit;
class ShaderEngine {
public:
@ -316,11 +27,9 @@ public:
* @param setup Shader engine state, must be setup with SetupBatch on each shader change.
* @param state Shader unit state, must be setup with input data before each shader invocation.
*/
virtual void Run(const ShaderSetup& setup, UnitState& state) const = 0;
virtual void Run(const ShaderSetup& setup, ShaderUnit& state) const = 0;
};
// TODO(yuriks): Remove and make it non-global state somewhere
ShaderEngine* GetEngine();
void Shutdown();
std::unique_ptr<ShaderEngine> CreateEngine(bool use_jit);
} // namespace Pica::Shader
} // namespace Pica

View file

@ -3,7 +3,6 @@
// Refer to the license.txt file included.
#include <algorithm>
#include <array>
#include <cmath>
#include <numeric>
#include <boost/circular_buffer.hpp>
@ -14,9 +13,9 @@
#include "common/logging/log.h"
#include "common/microprofile.h"
#include "common/vector_math.h"
#include "video_core/pica_state.h"
#include "video_core/pica/shader_setup.h"
#include "video_core/pica/shader_unit.h"
#include "video_core/pica_types.h"
#include "video_core/shader/shader.h"
#include "video_core/shader/shader_interpreter.h"
using nihstro::Instruction;
@ -46,8 +45,8 @@ struct LoopStackElement {
};
template <bool Debug>
static void RunInterpreter(const ShaderSetup& setup, UnitState& state, DebugData<Debug>& debug_data,
unsigned entry_point) {
static void RunInterpreter(const ShaderSetup& setup, ShaderUnit& state,
DebugData<Debug>& debug_data, unsigned entry_point) {
boost::circular_buffer<IfStackElement> if_stack(8);
boost::circular_buffer<CallStackElement> call_stack(4);
boost::circular_buffer<LoopStackElement> loop_stack(4);
@ -136,10 +135,10 @@ static void RunInterpreter(const ShaderSetup& setup, UnitState& state, DebugData
int index = source_reg.GetIndex();
switch (source_reg.GetRegisterType()) {
case RegisterType::Input:
return &state.registers.input[index].x;
return &state.input[index].x;
case RegisterType::Temporary:
return &state.registers.temporary[index].x;
return &state.temporary[index].x;
case RegisterType::FloatUniform:
if (address_register_index != 0) {
@ -202,9 +201,9 @@ static void RunInterpreter(const ShaderSetup& setup, UnitState& state, DebugData
}
f24* dest = (instr.common.dest.Value() < 0x10)
? &state.registers.output[instr.common.dest.Value().GetIndex()][0]
? &state.output[instr.common.dest.Value().GetIndex()][0]
: (instr.common.dest.Value() < 0x20)
? &state.registers.temporary[instr.common.dest.Value().GetIndex()][0]
? &state.temporary[instr.common.dest.Value().GetIndex()][0]
: dummy_vec4_float24_zeros;
debug_data.max_opdesc_id =
@ -537,9 +536,9 @@ static void RunInterpreter(const ShaderSetup& setup, UnitState& state, DebugData
}
f24* dest = (instr.mad.dest.Value() < 0x10)
? &state.registers.output[instr.mad.dest.Value().GetIndex()][0]
? &state.output[instr.mad.dest.Value().GetIndex()][0]
: (instr.mad.dest.Value() < 0x20)
? &state.registers.temporary[instr.mad.dest.Value().GetIndex()][0]
? &state.temporary[instr.mad.dest.Value().GetIndex()][0]
: dummy_vec4_float24_zeros;
Record<DebugDataRecord::SRC1>(debug_data, iteration, src1);
@ -652,14 +651,14 @@ static void RunInterpreter(const ShaderSetup& setup, UnitState& state, DebugData
}
case OpCode::Id::EMIT: {
GSEmitter* emitter = state.emitter_ptr;
auto* emitter = state.emitter_ptr;
ASSERT_MSG(emitter, "Execute EMIT on VS");
emitter->Emit(state.registers.output);
emitter->Emit(state.output);
break;
}
case OpCode::Id::SETEMIT: {
GSEmitter* emitter = state.emitter_ptr;
auto* emitter = state.emitter_ptr;
ASSERT_MSG(emitter, "Execute SETEMIT on VS");
emitter->vertex_id = instr.setemit.vertex_id;
emitter->prim_emit = instr.setemit.prim_emit != 0;
@ -726,29 +725,29 @@ static void RunInterpreter(const ShaderSetup& setup, UnitState& state, DebugData
void InterpreterEngine::SetupBatch(ShaderSetup& setup, unsigned int entry_point) {
ASSERT(entry_point < MAX_PROGRAM_CODE_LENGTH);
setup.engine_data.entry_point = entry_point;
setup.entry_point = entry_point;
}
MICROPROFILE_DECLARE(GPU_Shader);
MICROPROFILE_DEFINE(GPU_Shader, "GPU", "Shader", MP_RGB(50, 50, 240));
void InterpreterEngine::Run(const ShaderSetup& setup, UnitState& state) const {
void InterpreterEngine::Run(const ShaderSetup& setup, ShaderUnit& state) const {
MICROPROFILE_SCOPE(GPU_Shader);
DebugData<false> dummy_debug_data;
RunInterpreter(setup, state, dummy_debug_data, setup.engine_data.entry_point);
RunInterpreter(setup, state, dummy_debug_data, setup.entry_point);
}
DebugData<true> InterpreterEngine::ProduceDebugInfo(const ShaderSetup& setup,
const AttributeBuffer& input,
const ShaderRegs& config) const {
UnitState state;
ShaderUnit state;
DebugData<true> debug_data;
// Setup input register table
state.registers.input.fill(Common::Vec4<f24>::AssignToAll(f24::Zero()));
state.input.fill(Common::Vec4<f24>::AssignToAll(f24::Zero()));
state.LoadInput(config, input);
RunInterpreter(setup, state, debug_data, setup.engine_data.entry_point);
RunInterpreter(setup, state, debug_data, setup.entry_point);
return debug_data;
}

View file

@ -4,15 +4,20 @@
#pragma once
#include "video_core/pica/output_vertex.h"
#include "video_core/shader/debug_data.h"
#include "video_core/shader/shader.h"
namespace Pica {
struct ShaderRegs;
}
namespace Pica::Shader {
class InterpreterEngine final : public ShaderEngine {
public:
void SetupBatch(ShaderSetup& setup, unsigned int entry_point) override;
void Run(const ShaderSetup& setup, UnitState& state) const override;
void SetupBatch(ShaderSetup& setup, u32 entry_point) override;
void Run(const ShaderSetup& setup, ShaderUnit& state) const override;
/**
* Produce debug information based on the given shader and input vertex

View file

@ -6,6 +6,7 @@
#if CITRA_ARCH(x86_64) || CITRA_ARCH(arm64)
#include "common/assert.h"
#include "common/hash.h"
#include "common/microprofile.h"
#include "video_core/shader/shader.h"
#include "video_core/shader/shader_jit.h"
@ -23,7 +24,7 @@ JitEngine::~JitEngine() = default;
void JitEngine::SetupBatch(ShaderSetup& setup, u32 entry_point) {
ASSERT(entry_point < MAX_PROGRAM_CODE_LENGTH);
setup.engine_data.entry_point = entry_point;
setup.entry_point = entry_point;
const u64 code_hash = setup.GetProgramCodeHash();
const u64 swizzle_hash = setup.GetSwizzleDataHash();
@ -31,24 +32,24 @@ void JitEngine::SetupBatch(ShaderSetup& setup, u32 entry_point) {
const u64 cache_key = Common::HashCombine(code_hash, swizzle_hash);
auto iter = cache.find(cache_key);
if (iter != cache.end()) {
setup.engine_data.cached_shader = iter->second.get();
setup.cached_shader = iter->second.get();
} else {
auto shader = std::make_unique<JitShader>();
shader->Compile(&setup.program_code, &setup.swizzle_data);
setup.engine_data.cached_shader = shader.get();
setup.cached_shader = shader.get();
cache.emplace_hint(iter, cache_key, std::move(shader));
}
}
MICROPROFILE_DECLARE(GPU_Shader);
void JitEngine::Run(const ShaderSetup& setup, UnitState& state) const {
ASSERT(setup.engine_data.cached_shader != nullptr);
void JitEngine::Run(const ShaderSetup& setup, ShaderUnit& state) const {
ASSERT(setup.cached_shader != nullptr);
MICROPROFILE_SCOPE(GPU_Shader);
const JitShader* shader = static_cast<const JitShader*>(setup.engine_data.cached_shader);
shader->Run(setup, state, setup.engine_data.entry_point);
const JitShader* shader = static_cast<const JitShader*>(setup.cached_shader);
shader->Run(setup, state, setup.entry_point);
}
} // namespace Pica::Shader

Some files were not shown because too many files have changed in this diff Show more