summaryrefslogtreecommitdiffstats
path: root/src/video_core/renderer_opengl/gl_shader_cache.cpp
blob: aea6bf1afeaba7f74087b00634241337aed780ae (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
// Copyright 2018 yuzu Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.

#include <boost/functional/hash.hpp>
#include "common/assert.h"
#include "common/hash.h"
#include "core/core.h"
#include "core/memory.h"
#include "video_core/engines/maxwell_3d.h"
#include "video_core/renderer_opengl/gl_rasterizer.h"
#include "video_core/renderer_opengl/gl_shader_cache.h"
#include "video_core/renderer_opengl/gl_shader_manager.h"
#include "video_core/renderer_opengl/utils.h"

namespace OpenGL {

/// Gets the address for the specified shader stage program
static VAddr GetShaderAddress(Maxwell::ShaderProgram program) {
    const auto& gpu = Core::System::GetInstance().GPU().Maxwell3D();
    const auto& shader_config = gpu.regs.shader_config[static_cast<std::size_t>(program)];
    return *gpu.memory_manager.GpuToCpuAddress(gpu.regs.code_address.CodeAddress() +
                                               shader_config.offset);
}

/// Gets the shader program code from memory for the specified address
static GLShader::ProgramCode GetShaderCode(VAddr addr) {
    GLShader::ProgramCode program_code(GLShader::MAX_PROGRAM_CODE_LENGTH);
    Memory::ReadBlock(addr, program_code.data(), program_code.size() * sizeof(u64));
    return program_code;
}

/// Helper function to set shader uniform block bindings for a single shader stage
static void SetShaderUniformBlockBinding(GLuint shader, const char* name,
                                         Maxwell::ShaderStage binding, std::size_t expected_size) {
    const GLuint ub_index = glGetUniformBlockIndex(shader, name);
    if (ub_index == GL_INVALID_INDEX) {
        return;
    }

    GLint ub_size = 0;
    glGetActiveUniformBlockiv(shader, ub_index, GL_UNIFORM_BLOCK_DATA_SIZE, &ub_size);
    ASSERT_MSG(static_cast<std::size_t>(ub_size) == expected_size,
               "Uniform block size did not match! Got {}, expected {}", ub_size, expected_size);
    glUniformBlockBinding(shader, ub_index, static_cast<GLuint>(binding));
}

/// Sets shader uniform block bindings for an entire shader program
static void SetShaderUniformBlockBindings(GLuint shader) {
    SetShaderUniformBlockBinding(shader, "vs_config", Maxwell::ShaderStage::Vertex,
                                 sizeof(GLShader::MaxwellUniformData));
    SetShaderUniformBlockBinding(shader, "gs_config", Maxwell::ShaderStage::Geometry,
                                 sizeof(GLShader::MaxwellUniformData));
    SetShaderUniformBlockBinding(shader, "fs_config", Maxwell::ShaderStage::Fragment,
                                 sizeof(GLShader::MaxwellUniformData));
}

CachedShader::CachedShader(VAddr addr, Maxwell::ShaderProgram program_type)
    : addr{addr}, program_type{program_type}, setup{GetShaderCode(addr)} {

    GLShader::ProgramResult program_result;
    GLenum gl_type{};

    switch (program_type) {
    case Maxwell::ShaderProgram::VertexA:
        // VertexB is always enabled, so when VertexA is enabled, we have two vertex shaders.
        // Conventional HW does not support this, so we combine VertexA and VertexB into one
        // stage here.
        setup.SetProgramB(GetShaderCode(GetShaderAddress(Maxwell::ShaderProgram::VertexB)));
    case Maxwell::ShaderProgram::VertexB:
        CalculateProperties();
        program_result = GLShader::GenerateVertexShader(setup);
        gl_type = GL_VERTEX_SHADER;
        break;
    case Maxwell::ShaderProgram::Geometry:
        CalculateProperties();
        program_result = GLShader::GenerateGeometryShader(setup);
        gl_type = GL_GEOMETRY_SHADER;
        break;
    case Maxwell::ShaderProgram::Fragment:
        CalculateProperties();
        program_result = GLShader::GenerateFragmentShader(setup);
        gl_type = GL_FRAGMENT_SHADER;
        break;
    default:
        LOG_CRITICAL(HW_GPU, "Unimplemented program_type={}", static_cast<u32>(program_type));
        UNREACHABLE();
        return;
    }

    entries = program_result.second;
    shader_length = entries.shader_length;

    if (program_type != Maxwell::ShaderProgram::Geometry) {
        OGLShader shader;
        shader.Create(program_result.first.c_str(), gl_type);
        program.Create(true, shader.handle);
        SetShaderUniformBlockBindings(program.handle);
        LabelGLObject(GL_PROGRAM, program.handle, addr);
    } else {
        // Store shader's code to lazily build it on draw
        geometry_programs.code = program_result.first;
    }
}

GLuint CachedShader::GetProgramResourceIndex(const GLShader::ConstBufferEntry& buffer) {
    const auto search{resource_cache.find(buffer.GetHash())};
    if (search == resource_cache.end()) {
        const GLuint index{
            glGetProgramResourceIndex(program.handle, GL_UNIFORM_BLOCK, buffer.GetName().c_str())};
        resource_cache[buffer.GetHash()] = index;
        return index;
    }

    return search->second;
}

GLint CachedShader::GetUniformLocation(const GLShader::SamplerEntry& sampler) {
    const auto search{uniform_cache.find(sampler.GetHash())};
    if (search == uniform_cache.end()) {
        const GLint index{glGetUniformLocation(program.handle, sampler.GetName().c_str())};
        uniform_cache[sampler.GetHash()] = index;
        return index;
    }

    return search->second;
}

GLuint CachedShader::LazyGeometryProgram(OGLProgram& target_program,
                                         const std::string& glsl_topology, u32 max_vertices,
                                         const std::string& debug_name) {
    if (target_program.handle != 0) {
        return target_program.handle;
    }
    std::string source = "#version 430 core\n";
    source += "layout (" + glsl_topology + ") in;\n";
    source += "#define MAX_VERTEX_INPUT " + std::to_string(max_vertices) + '\n';
    source += geometry_programs.code;

    OGLShader shader;
    shader.Create(source.c_str(), GL_GEOMETRY_SHADER);
    target_program.Create(true, shader.handle);
    SetShaderUniformBlockBindings(target_program.handle);
    LabelGLObject(GL_PROGRAM, target_program.handle, addr, debug_name);
    return target_program.handle;
};

static bool IsSchedInstruction(std::size_t offset, std::size_t main_offset) {
    // sched instructions appear once every 4 instructions.
    static constexpr std::size_t SchedPeriod = 4;
    const std::size_t absolute_offset = offset - main_offset;
    return (absolute_offset % SchedPeriod) == 0;
}

static std::size_t CalculateProgramSize(const GLShader::ProgramCode& program) {
    constexpr std::size_t start_offset = 10;
    std::size_t offset = start_offset;
    std::size_t size = start_offset * sizeof(u64);
    while (offset < program.size()) {
        const u64 inst = program[offset];
        if (!IsSchedInstruction(offset, start_offset)) {
            if (inst == 0 || (inst >> 52) == 0x50b) {
                break;
            }
        }
        size += sizeof(inst);
        offset++;
    }
    return size;
}

void CachedShader::CalculateProperties() {
    setup.program.real_size = CalculateProgramSize(setup.program.code);
    setup.program.real_size_b = 0;
    setup.program.unique_identifier = Common::CityHash64(
        reinterpret_cast<const char*>(setup.program.code.data()), setup.program.real_size);
    if (program_type == Maxwell::ShaderProgram::VertexA) {
        std::size_t seed = 0;
        boost::hash_combine(seed, setup.program.unique_identifier);
        setup.program.real_size_b = CalculateProgramSize(setup.program.code_b);
        const u64 identifier_b = Common::CityHash64(
            reinterpret_cast<const char*>(setup.program.code_b.data()), setup.program.real_size_b);
        boost::hash_combine(seed, identifier_b);
        setup.program.unique_identifier = static_cast<u64>(seed);
    }
}

ShaderCacheOpenGL::ShaderCacheOpenGL(RasterizerOpenGL& rasterizer) : RasterizerCache{rasterizer} {}

Shader ShaderCacheOpenGL::GetStageProgram(Maxwell::ShaderProgram program) {
    const VAddr program_addr{GetShaderAddress(program)};

    // Look up shader in the cache based on address
    Shader shader{TryGet(program_addr)};

    if (!shader) {
        // No shader found - create a new one
        shader = std::make_shared<CachedShader>(program_addr, program);
        Register(shader);
    }

    return shader;
}

} // namespace OpenGL