mirror of
https://github.com/MaSzyna-EU07/maszyna.git
synced 2026-10-17 16:49:21 +02:00
* refactor(sonar): use override instead of redundant virtual (cpp:S3471) * refactor(sonar): remove empty statements, one declaration per statement (cpp:S1116, cpp:S1659) * refactor(sonar): drop redundant lambda return types (cpp:S3574) * refactor(sonar): prefer using over typedef (cpp:S5416) * refactor(sonar): use =default for trivial special members (cpp:S3490) * refactor(sonar): use nullptr literal (cpp:S4962) * refactor(sonar): remove redundant access specifiers (cpp:S3539) * refactor(sonar): remove redundant casts (cpp:S1905) * refactor(sonar): use std::scoped_lock instead of std::lock_guard (cpp:S5997) * refactor(sonar): construct elements in place with emplace_back (cpp:S6003) * refactor(sonar): make narrowing conversions explicit (cpp:S5276) * refactor(sonar): mark unused parameters (cpp:S1172) Unused names are commented out; parameters used only on some platforms are marked [[maybe_unused]]. * refactor(sonar): declare non-mutating member functions const (cpp:S5817) Virtual functions are left untouched so overrides keep matching. * refactor(sonar): merge collapsible nested if statements (cpp:S1066) Comments that preceded the inner if are kept above the merged statement. * refactor(sonar): scope single-use variables in if init-statements (cpp:S6004) * fix(sonar): give polymorphic base classes virtual destructors (cpp:S1235) * refactor(sonar): use try_emplace for map insertion (cpp:S6030) * refactor(sonar): use auto where the type is spelled out on the right (cpp:S5827) * refactor(sonar): remove redundant parentheses (cpp:S1110) * refactor(sonar): document intentionally empty functions (cpp:S1186) * refactor(sonar): remove dead stores (cpp:S1854) Side effects (e.g. LISTLINE++) are kept. * refactor(sonar): remove unused variables, captures and private fields (cpp:S1481, cpp:S1068) * refactor(sonar): use structured bindings for pair access (cpp:S6005) * refactor(sonar): use range-based loops and ranges algorithms (cpp:S5566) * refactor(sonar): split chained assignments (cpp:S1121) * refactor(sonar): add default cases to switch statements (cpp:S3562) * refactor(sonar): use std::size for array lengths (cpp:S7127) * refactor(sonar): use std::ranges algorithms and std::erase(_if) (cpp:S6197) * refactor(sonar): access static members through the class (cpp:S2209) * refactor(sonar): add braces around nested if-else (cpp:S5261) * refactor(sonar): avoid side effects inside typeid operands (cpp:S5279) * refactor(sonar): drop top-level const from by-value return types (cpp:S5951) * refactor(sonar): declare variables separately from their type definitions (cpp:S3646) * refactor(sonar): declare loop counters in the for statement (cpp:S5955) * refactor(sonar): rely on class template argument deduction (cpp:S6012) * refactor(sonar): inherit base constructors instead of forwarding them (cpp:S5952) * refactor(sonar): rename locals that shadow outer declarations (cpp:S1117) Only local variables and definition parameters are renamed; shadowing struct fields and enumerators in headers are left for a separate change. * refactor(sonar): reduce enum qualification with using enum (cpp:S6177) Applied only where no unqualified name in the block could be captured by the introduced enumerators. * refactor(sonar): mark converting constructors explicit (cpp:S1709) sound_source and the gl::object conversion operators stay implicit; they are relied upon by copy-list-initialisation and GL calls. * refactor(sonar): initialise members in initialiser lists or declarations (cpp:S3230) * refactor(sonar): make read-only local references and pointers const (cpp:S5350) * refactor(sonar): take read-only pointer and reference parameters as const (cpp:S995) TTrain command handlers keep their signature, it is fixed by the handler table. * refactor(sonar): pass expensive-to-copy parameters by const reference (cpp:S1238) Signatures declared in files touched by PR 206 (Driver.h, EU07.cpp) and virtual overrides are left unchanged. * refactor(sonar): use transparent comparators for string-keyed maps (cpp:S6045) std::unordered_map instances and map types exposed in headers used by other modules are left as they are. * fix(sonar): do not use UI text as a printf format string (cpp:S5281) Text lines containing '%' would otherwise be interpreted as format specifiers by ImGui::TextColored. * refactor(sonar): use std::bind_front for callbacks (cpp:S5995) * refactor(sonar): drop const_cast on string literals passed to the Python C API (cpp:S859) * refactor(sonar): take read-only string parameters as std::string_view (cpp:S6009) The Windows messaging helpers keep std::string, they need c_str(). * refactor(sonar): make read-only global tables const (cpp:S5421) Mutable global state (flags, timers, singletons) is left as is. * refactor(sonar): replace single-case switch statements with if (cpp:S1301) * refactor(sonar): format UUIDs and log timestamps with std::format (cpp:S6494, cpp:S5945) * refactor(sonar): use std::array for local fixed-size arrays (cpp:S5945) Arrays that are class members or part of headers are left unchanged. * fix(sonar): test the bearing damage bit, not bit 0 (cpp:S872) 'DamageFlag & dtrain_bearing > 0' parsed as 'DamageFlag & (dtrain_bearing > 0)', i.e. DamageFlag & 1, so bearing friction reacted to the wrong damage flag. * refactor(sonar): assorted small fixes - empty() instead of size() comparisons (cpp:S1155) - member initialisers in declaration order (cpp:S3229) - no redundant c_str() when a std::string is accepted (cpp:S7121) - contains() on associative containers (cpp:S6171) - const reference instead of a copying range-for (cpp:S6032) - starts_with() for prefix checks (cpp:S6178) - no std::move on temporaries (cpp:S5274) - has_value() on std::optional (cpp:S7172) - bool literals for bool members (cpp:S5820) - inline only on the definition (cpp:S3548) - explicit base access specifier (cpp:S5965) - explicit element access instead of dereferencing an array (cpp:S7116) - rely on the C++20 rewritten operator!= (cpp:S6186) * refactor(sonar): more small fixes - std::format instead of iostream manipulators in to_string/to_hex_str (cpp:S6495); output verified identical, negative hex values keep the unsigned form - remove an empty compound statement (cpp:S108) - drop an always-false unsigned < 0 branch (cpp:S1768) - explicit lambda capture (cpp:S3608) - std::make_unique (cpp:S5950) * chore: strip stray carriage returns left in TTrain constructor comments * fix: keep quantize() in its own value type The S5276 change cast the result of the generic quantize<Type_>() to unsigned int, which truncated float/double callers (shadow angle slider, editor rotation snapping, AI speed control steps) and broke negative values. * fix(sonar): use integer loop counters in segment sampling (cpp:S2193) * refactor(sonar): clean up issues reported on PR 209 - remove locals left unused after the dead-store cleanup (cpp:S1481, cpp:S1854) - unnamed unused parameter (cpp:S1172) - single-use declarations moved into if init-statements (cpp:S6004) - auto for casted initialisers (cpp:S5827) - const references and pointers where nothing is modified (cpp:S5350) - rename structured bindings shadowed by inner declarations (cpp:S1117)
412 lines
13 KiB
C++
412 lines
13 KiB
C++
#include "stdafx.h"
|
|
|
|
#include <fstream>
|
|
#include <sstream>
|
|
#include <cstring>
|
|
#include "shader.h"
|
|
#include "glsl_common.h"
|
|
#include "utilities/Logs.h"
|
|
|
|
inline bool strcend(std::string_view value, std::string_view ending)
|
|
{
|
|
if (ending.size() > value.size())
|
|
return false;
|
|
return std::equal(ending.rbegin(), ending.rend(), value.rbegin());
|
|
}
|
|
|
|
namespace {
|
|
|
|
// The project's glad config only generates GLAD_GL_ARB_texture_filter_anisotropic
|
|
// among the ARB/EXT extension flags -- GL_ARB_texture_gather (desktop) and
|
|
// GL_EXT_gpu_shader5 (GLES 3.1) aren't compiled in, so we can't gate the
|
|
// shadow textureGather() optimisation on a GLAD constant. Query the live
|
|
// extension string instead. The first call walks the extension list once
|
|
// (no extension count in the dozens is large enough to matter here) and
|
|
// the result is cached in the static bool inside has_gl_extension(), so
|
|
// every subsequent shader compile is a plain bool read.
|
|
//
|
|
// SHADERVALIDATOR_STANDALONE gates out the GL queries because the offline
|
|
// shader validator tool links glad.c but never calls gladLoadGL(); the
|
|
// function pointers stay null and a real call would crash. Returning
|
|
// false there means the standalone validator simply compiles the original
|
|
// 16-tap PCF fallback path in light_common.glsl, which is what we want.
|
|
bool has_gl_extension(char const *name) {
|
|
#ifdef SHADERVALIDATOR_STANDALONE
|
|
(void)name;
|
|
return false;
|
|
#else
|
|
if (!glGetIntegerv || !glGetStringi) {
|
|
return false;
|
|
}
|
|
GLint count = 0;
|
|
glGetIntegerv(GL_NUM_EXTENSIONS, &count);
|
|
for (GLint i = 0; i < count; ++i) {
|
|
auto ext = reinterpret_cast<char const *>(glGetStringi(GL_EXTENSIONS, i));
|
|
if (ext != nullptr && std::strcmp(ext, name) == 0) {
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
#endif
|
|
}
|
|
|
|
} // anonymous namespace
|
|
|
|
std::string gl::shader::read_file(const std::string &filename) const
|
|
{
|
|
std::stringstream stream;
|
|
std::ifstream f;
|
|
|
|
f.open(filename);
|
|
stream << f.rdbuf();
|
|
f.close();
|
|
|
|
std::string str = stream.str();
|
|
if (str.empty())
|
|
throw shader_exception("cannot read shader: " + filename);
|
|
|
|
return str;
|
|
}
|
|
|
|
void gl::shader::expand_includes(std::string &str, const std::string &basedir)
|
|
{
|
|
size_t start_pos = 0;
|
|
|
|
std::string magic = "#include";
|
|
while ((start_pos = str.find(magic, start_pos)) != std::string::npos)
|
|
{
|
|
size_t fp = str.find('<', start_pos);
|
|
size_t fe = str.find('>', start_pos);
|
|
if (fp == std::string::npos || fe == std::string::npos)
|
|
return;
|
|
|
|
std::string filename = str.substr(fp + 1, fe - fp - 1);
|
|
std::string content;
|
|
if (filename != "common")
|
|
content = read_file(basedir + filename);
|
|
else
|
|
content = glsl_common;
|
|
|
|
str.replace(start_pos, fe - start_pos + 1, content);
|
|
}
|
|
}
|
|
|
|
std::unordered_map<std::string, gl::shader::components_e> gl::shader::components_mapping =
|
|
{
|
|
{ "R", components_e::R },
|
|
{ "RG", components_e::RG },
|
|
{ "RGB", components_e::RGB },
|
|
{ "RGBA", components_e::RGBA },
|
|
{ "sRGB", components_e::sRGB },
|
|
{ "sRGB_A", components_e::sRGB_A }
|
|
};
|
|
|
|
std::unordered_map<std::string, gl::shader::defaultparam_e> gl::shader::defaultparams_mapping =
|
|
{
|
|
{ "required", defaultparam_e::required },
|
|
{ "nan", defaultparam_e::nan },
|
|
{ "zero", defaultparam_e::zero },
|
|
{ "one", defaultparam_e::one },
|
|
{ "ambient", defaultparam_e::ambient },
|
|
{ "diffuse", defaultparam_e::diffuse },
|
|
{ "specular", defaultparam_e::specular },
|
|
{ "glossiness", defaultparam_e::glossiness }
|
|
};
|
|
|
|
std::pair<GLuint, std::string> gl::shader::process_source(const std::string &filename, const std::string &basedir)
|
|
{
|
|
std::string str;
|
|
|
|
GLuint type;
|
|
if (strcend(filename, ".vert"))
|
|
type = GL_VERTEX_SHADER;
|
|
else if (strcend(filename, ".frag"))
|
|
type = GL_FRAGMENT_SHADER;
|
|
else if (strcend(filename, ".geom"))
|
|
type = GL_GEOMETRY_SHADER;
|
|
else
|
|
throw shader_exception("unknown shader " + filename);
|
|
|
|
if (!Global.gfx_usegles)
|
|
{
|
|
str += "#version 330 core\n";
|
|
// textureGather() on sampler2DArrayShadow is core in GLSL 4.0. On 3.30
|
|
// desktop it requires GL_ARB_gpu_shader5 -- the older
|
|
// GL_ARB_texture_gather (2010) only adds the non-shadow and the plain
|
|
// sampler2DShadow overloads, NOT the sampler2DArrayShadow one we need
|
|
// for cascaded shadow PCF. Some drivers advertise texture_gather but
|
|
// reject the shadow-array overload because the spec for it lives in
|
|
// gpu_shader5; so emit only when gpu_shader5 is advertised. When the
|
|
// extension is missing, calc_shadow() in light_common.glsl falls back
|
|
// to the original 16-tap hardware-PCF loop via #ifndef.
|
|
// (Project's glad config doesn't generate GLAD_GL_ARB_gpu_shader5,
|
|
// so we query the live extension list -- see has_gl_extension above.)
|
|
static bool const have_gpu_shader5 = has_gl_extension("GL_ARB_gpu_shader5");
|
|
if (have_gpu_shader5)
|
|
str += "#extension GL_ARB_gpu_shader5 : enable\n";
|
|
}
|
|
else
|
|
{
|
|
if (GLAD_GL_ES_VERSION_3_1) {
|
|
str += "#version 310 es\n";
|
|
// GLES 3.1 lacks textureGather on shadow samplers in core; the
|
|
// EXT_gpu_shader5 extension adds it. Only emit the directive when
|
|
// the driver advertises support (see desktop comment above).
|
|
// (Glad config doesn't generate GLAD_GL_EXT_gpu_shader5 -- query
|
|
// the live extension string the same way.)
|
|
if (static bool const have_gpu_shader5 = has_gl_extension("GL_EXT_gpu_shader5"); have_gpu_shader5)
|
|
str += "#extension GL_EXT_gpu_shader5 : enable\n";
|
|
if (type == GL_GEOMETRY_SHADER)
|
|
str += "#extension GL_EXT_geometry_shader : require\n";
|
|
} else {
|
|
str += "#version 300 es\n";
|
|
}
|
|
str += "precision highp float;\n";
|
|
str += "precision highp int;\n";
|
|
str += "precision highp sampler2DShadow;\n";
|
|
str += "precision highp sampler2DArrayShadow;\n";
|
|
}
|
|
// expose the shader stage to glsl_common so vertex-only built-ins
|
|
// (gl_InstanceID, effective_modelview, etc.) can be guarded out of
|
|
// fragment/geometry compilations.
|
|
if (type == GL_VERTEX_SHADER) str += "#define STAGE_VERTEX 1\n";
|
|
else if (type == GL_FRAGMENT_SHADER) str += "#define STAGE_FRAGMENT 1\n";
|
|
else if (type == GL_GEOMETRY_SHADER) str += "#define STAGE_GEOMETRY 1\n";
|
|
str += "vec4 FBOUT(vec4 x) { return " + (Global.gfx_shadergamma ? std::string("vec4(pow(x.rgb, vec3(1.0 / 2.2)), x.a)") : std::string("x")) + "; }\n";
|
|
|
|
str += read_file(basedir + filename);
|
|
|
|
expand_includes(str, basedir);
|
|
parse_texture_entries(str);
|
|
parse_param_entries(str);
|
|
|
|
return std::make_pair(type, str);
|
|
}
|
|
|
|
void gl::shader::parse_texture_entries(std::string &str)
|
|
{
|
|
size_t start_pos = 0;
|
|
|
|
std::string magic = "#texture";
|
|
while ((start_pos = str.find(magic, start_pos)) != std::string::npos)
|
|
{
|
|
size_t fp = str.find('(', start_pos);
|
|
size_t fe = str.find(')', start_pos);
|
|
if (fp == std::string::npos || fe == std::string::npos)
|
|
return;
|
|
|
|
std::istringstream ss(str.substr(fp + 1, fe - fp - 1));
|
|
std::string token;
|
|
|
|
std::string uniformname;
|
|
texture_entry conf;
|
|
|
|
size_t arg = 0;
|
|
while (std::getline(ss, token, ','))
|
|
{
|
|
std::istringstream token_ss(token);
|
|
if (arg == 0)
|
|
token_ss >> uniformname;
|
|
else if (arg == 1)
|
|
token_ss >> conf.id;
|
|
else if (arg == 2)
|
|
{
|
|
std::string comp;
|
|
token_ss >> comp;
|
|
if (!components_mapping.contains(comp))
|
|
log_error("unknown components: " + comp);
|
|
else
|
|
conf.components = components_mapping[comp];
|
|
}
|
|
arg++;
|
|
}
|
|
|
|
if (arg == 3)
|
|
{
|
|
if (uniformname.empty())
|
|
log_error("empty name");
|
|
else if (conf.id >= gl::MAX_TEXTURES)
|
|
log_error("invalid texture binding: " + std::to_string(conf.id));
|
|
else
|
|
texture_conf.try_emplace(uniformname, conf);
|
|
}
|
|
else
|
|
log_error("invalid argument count to #texture");
|
|
|
|
str.erase(start_pos, fe - start_pos + 1);
|
|
}
|
|
}
|
|
|
|
void gl::shader::parse_param_entries(std::string &str)
|
|
{
|
|
size_t start_pos = 0;
|
|
|
|
std::string magic = "#param";
|
|
while ((start_pos = str.find(magic, start_pos)) != std::string::npos)
|
|
{
|
|
size_t fp = str.find('(', start_pos);
|
|
size_t fe = str.find(')', start_pos);
|
|
if (fp == std::string::npos || fe == std::string::npos)
|
|
return;
|
|
|
|
std::istringstream ss(str.substr(fp + 1, fe - fp - 1));
|
|
std::string token;
|
|
|
|
std::string uniformname;
|
|
param_entry conf;
|
|
|
|
size_t arg = 0;
|
|
while (std::getline(ss, token, ','))
|
|
{
|
|
std::istringstream token_ss(token);
|
|
if (arg == 0)
|
|
token_ss >> uniformname;
|
|
else if (arg == 1)
|
|
token_ss >> conf.location;
|
|
else if (arg == 2)
|
|
token_ss >> conf.offset;
|
|
else if (arg == 3)
|
|
token_ss >> conf.size;
|
|
else if (arg == 4)
|
|
{
|
|
std::string tok;
|
|
token_ss >> tok;
|
|
if (!defaultparams_mapping.contains(tok))
|
|
log_error("unknown param default: " + tok);
|
|
conf.defaultparam = defaultparams_mapping[tok];
|
|
}
|
|
arg++;
|
|
}
|
|
|
|
if (arg == 5)
|
|
{
|
|
if (uniformname.empty())
|
|
log_error("empty name");
|
|
else if (conf.location >= gl::MAX_PARAMS)
|
|
log_error("invalid param binding: " + std::to_string(conf.location));
|
|
else if (conf.offset > 3)
|
|
log_error("invalid offset: " + std::to_string(conf.offset));
|
|
else if (conf.offset + conf.size > 4)
|
|
log_error("invalid size: " + std::to_string(conf.size));
|
|
else
|
|
param_conf.try_emplace(uniformname, conf);
|
|
}
|
|
else
|
|
log_error("invalid argument count to #param");
|
|
|
|
str.erase(start_pos, fe - start_pos + 1);
|
|
}
|
|
}
|
|
|
|
void gl::shader::log_error(const std::string &str) const
|
|
{
|
|
ErrorLog("bad shader: " + name + ": " + str, logtype::shader);
|
|
}
|
|
|
|
gl::shader::shader(const std::string &filename) : name(filename)
|
|
{
|
|
|
|
auto [shadertype, shadersource] = process_source(filename, "shaders/");
|
|
|
|
const GLchar *cstr = shadersource.c_str();
|
|
|
|
**this = glCreateShader(shadertype);
|
|
glShaderSource(*this, 1, &cstr, nullptr);
|
|
glCompileShader(*this);
|
|
|
|
GLint status;
|
|
glGetShaderiv(*this, GL_COMPILE_STATUS, &status);
|
|
if (!status)
|
|
{
|
|
std::array<GLchar, 512> info{};
|
|
glGetShaderInfoLog(*this, static_cast<GLsizei>(info.size()), nullptr, info.data());
|
|
log_error(std::string(info.data()));
|
|
|
|
throw shader_exception("failed to compile " + filename + ": " + std::string(info.data()));
|
|
}
|
|
}
|
|
|
|
gl::shader::~shader()
|
|
{
|
|
#ifndef SHADERVALIDATOR_STANDALONE
|
|
glDeleteShader(*this);
|
|
#endif
|
|
}
|
|
|
|
void gl::program::init()
|
|
{
|
|
bind();
|
|
|
|
for (auto const &[texturename, textureentry] : texture_conf)
|
|
{
|
|
shader::texture_entry const &e = textureentry;
|
|
GLuint loc = glGetUniformLocation(*this, texturename.c_str());
|
|
glUniform1i(loc, static_cast<GLint>(e.id));
|
|
}
|
|
|
|
glUniform1i(glGetUniformLocation(*this, "shadowmap"), gl::SHADOW_TEX);
|
|
glUniform1i(glGetUniformLocation(*this, "envmap"), gl::ENV_TEX);
|
|
glUniform1i(glGetUniformLocation(*this, "headlightmap"), gl::HEADLIGHT_TEX);
|
|
|
|
GLuint index;
|
|
|
|
if ((index = glGetUniformBlockIndex(*this, "scene_ubo")) != GL_INVALID_INDEX)
|
|
glUniformBlockBinding(*this, index, 0);
|
|
|
|
if ((index = glGetUniformBlockIndex(*this, "model_ubo")) != GL_INVALID_INDEX)
|
|
glUniformBlockBinding(*this, index, 1);
|
|
|
|
if ((index = glGetUniformBlockIndex(*this, "light_ubo")) != GL_INVALID_INDEX)
|
|
glUniformBlockBinding(*this, index, 2);
|
|
|
|
if ((index = glGetUniformBlockIndex(*this, "instance_ubo")) != GL_INVALID_INDEX)
|
|
glUniformBlockBinding(*this, index, 3);
|
|
}
|
|
|
|
gl::program::program()
|
|
{
|
|
**this = glCreateProgram();
|
|
}
|
|
|
|
gl::program::program(std::vector<std::reference_wrapper<const gl::shader>> const &shaders) : program()
|
|
{
|
|
for (const gl::shader &s : shaders)
|
|
attach(s);
|
|
link();
|
|
}
|
|
|
|
void gl::program::attach(const gl::shader &s)
|
|
{
|
|
for (auto [texturename, textureentry] : s.texture_conf)
|
|
texture_conf.try_emplace(texturename, std::move(textureentry));
|
|
for (auto [paramname, paramentry] : s.param_conf)
|
|
param_conf.try_emplace(paramname, std::move(paramentry));
|
|
glAttachShader(*this, *s);
|
|
}
|
|
|
|
void gl::program::link()
|
|
{
|
|
glLinkProgram(*this);
|
|
|
|
GLint status;
|
|
glGetProgramiv(*this, GL_LINK_STATUS, &status);
|
|
if (!status)
|
|
{
|
|
std::array<GLchar, 512> info{};
|
|
glGetProgramInfoLog(*this, static_cast<GLsizei>(info.size()), nullptr, info.data());
|
|
throw shader_exception("failed to link program: " + std::string(info.data()));
|
|
}
|
|
|
|
init();
|
|
}
|
|
|
|
gl::program::~program()
|
|
{
|
|
glDeleteProgram(*this);
|
|
}
|
|
|
|
void gl::program::bind(GLuint i)
|
|
{
|
|
glUseProgram(i);
|
|
}
|