| 1 |
#include "GxmShaderProgram.h" |
| 2 |
#include "GxmShaderUniforms.h" |
| 3 |
#include "GxmBufferObject.h" |
| 4 |
#include "GxmDevice.h" |
| 5 |
|
| 6 |
#include "../../../../Main.h" |
| 7 |
#include "../../../../Shaders/Generated/ShaderCompilerTypes.h" |
| 8 |
#include "../../../../Shaders/Generated/CgGeneratedShaders.h" |
| 9 |
#include "../../Material.h" |
| 10 |
|
| 11 |
#include <cstdlib> |
| 12 |
#include <cstring> |
| 13 |
|
| 14 |
#include <Containers/StringConcatenable.h> |
| 15 |
|
| 16 |
#include <vitashark.h> |
| 17 |
|
| 18 |
namespace nCine::RHI::GXM |
| 19 |
{ |
| 20 |
namespace |
| 21 |
{ |
| 22 |
/** @brief Maps an engine blending factor onto its sceGxm counterpart */ |
| 23 |
SceGxmBlendFactor TranslateBlendFactor(nCine::BlendingFactor factor) |
| 24 |
{ |
| 25 |
switch (factor) { |
| 26 |
case nCine::BlendingFactor::Zero: return SCE_GXM_BLEND_FACTOR_ZERO; |
| 27 |
case nCine::BlendingFactor::One: return SCE_GXM_BLEND_FACTOR_ONE; |
| 28 |
case nCine::BlendingFactor::SrcColor: return SCE_GXM_BLEND_FACTOR_SRC_COLOR; |
| 29 |
case nCine::BlendingFactor::OneMinusSrcColor: return SCE_GXM_BLEND_FACTOR_ONE_MINUS_SRC_COLOR; |
| 30 |
case nCine::BlendingFactor::SrcAlpha: return SCE_GXM_BLEND_FACTOR_SRC_ALPHA; |
| 31 |
case nCine::BlendingFactor::OneMinusSrcAlpha: return SCE_GXM_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA; |
| 32 |
case nCine::BlendingFactor::DstAlpha: return SCE_GXM_BLEND_FACTOR_DST_ALPHA; |
| 33 |
case nCine::BlendingFactor::OneMinusDstAlpha: return SCE_GXM_BLEND_FACTOR_ONE_MINUS_DST_ALPHA; |
| 34 |
case nCine::BlendingFactor::DstColor: return SCE_GXM_BLEND_FACTOR_DST_COLOR; |
| 35 |
case nCine::BlendingFactor::OneMinusDstColor: return SCE_GXM_BLEND_FACTOR_ONE_MINUS_DST_COLOR; |
| 36 |
case nCine::BlendingFactor::SrcAlphaSaturate: return SCE_GXM_BLEND_FACTOR_SRC_ALPHA_SATURATE; |
| 37 |
default: |
| 38 |
// The constant-colour factors have no sceGxm counterpart (there is no per-context blend |
| 39 |
// colour), and the renderer never selects them |
| 40 |
return SCE_GXM_BLEND_FACTOR_ONE; |
| 41 |
} |
| 42 |
} |
| 43 |
|
| 44 |
/** |
| 45 |
@brief Rewrites the batch size baked into a generated batched Cg source |
| 46 |
|
| 47 |
The emitter bakes the fallback the shader's own `#ifndef BATCH_SIZE` declares (the 64 KB uniform |
| 48 |
block budget divided by the instance stride) into a plain `#define`, because a Cg source is |
| 49 |
compiled as one string with no place to inject a define ahead of it. When the runtime settles on a |
| 50 |
different batch size - a smaller uniform-block budget, a `WITH_FIXED_BATCH_SIZE` build, the retry |
| 51 |
after a failed compile - the number in that line is rewritten here so the shader's instance array |
| 52 |
matches what the pipeline will actually bind. |
| 53 |
*/ |
| 54 |
String PatchBatchSize(const char* source, std::uint32_t batchSize) |
| 55 |
{ |
| 56 |
static const char Marker[] = "#define BATCH_SIZE "; |
| 57 |
const char* found = std::strstr(source, Marker); |
| 58 |
if (found == nullptr) { |
| 59 |
return String{source}; |
| 60 |
} |
| 61 |
|
| 62 |
const char* valueBegin = found + (sizeof(Marker) - 1); |
| 63 |
const char* valueEnd = valueBegin; |
| 64 |
while (*valueEnd != '\0' && *valueEnd != '\n' && *valueEnd != '\r') { |
| 65 |
valueEnd++; |
| 66 |
} |
| 67 |
|
| 68 |
char number[16]; |
| 69 |
const std::int32_t numberLength = std::snprintf(number, sizeof(number), "%u", batchSize); |
| 70 |
return StringView{source, std::size_t(valueBegin - source)} |
| 71 |
+ StringView{number, std::size_t(numberLength > 0 ? numberLength : 0)} |
| 72 |
+ StringView{valueEnd}; |
| 73 |
} |
| 74 |
|
| 75 |
/** @brief Forwards SceShaccCg diagnostics into the engine log */ |
| 76 |
void SharkLogCallback(const char* message, shark_log_level level, int line) |
| 77 |
{ |
| 78 |
if (message == nullptr) { |
| 79 |
return; |
| 80 |
} |
| 81 |
switch (level) { |
| 82 |
case SHARK_LOG_ERROR: LOGE("Cg compiler (line {}): {}", line, message); break; |
| 83 |
case SHARK_LOG_WARNING: LOGW("Cg compiler (line {}): {}", line, message); break; |
| 84 |
default: LOGD("Cg compiler (line {}): {}", line, message); break; |
| 85 |
} |
| 86 |
} |
| 87 |
} |
| 88 |
|
| 89 |
std::uint32_t GxmShaderProgram::_nextHandle = 1; |
| 90 |
|
| 91 |
GxmShaderProgram::GxmShaderProgram() |
| 92 |
: GxmShaderProgram(QueryPhase::Immediate) |
| 93 |
{ |
| 94 |
} |
| 95 |
|
| 96 |
GxmShaderProgram::GxmShaderProgram(QueryPhase queryPhase) |
| 97 |
: _handle(_nextHandle++), _status(Status::NotLinked), _introspection(Introspection::Enabled), _queryPhase(queryPhase), |
| 98 |
_batchSize(std::uint32_t(DefaultBatchSize)), _shouldLogOnErrors(true), _uniformsSize(0), _uniformBlocksSize(0), |
| 99 |
_reflection(nullptr), _programName(nullptr), _variantName(nullptr), |
| 100 |
_boundVbo(nullptr), _boundIbo(nullptr), _vboOffset(0), _usesCornerStream(false), _usesBatchedStream(false), |
| 101 |
_usesGeometryStream(false), _geometryStride(0), |
| 102 |
_vertexStage(nullptr), _fragmentStage(nullptr), _vertexStageId(nullptr), _fragmentStageId(nullptr), |
| 103 |
_vertexUniformBufferSize(0), _fragmentUniformBufferSize(0) |
| 104 |
{ |
| 105 |
} |
| 106 |
|
| 107 |
GxmShaderProgram::GxmShaderProgram(StringView vertexFile, StringView fragmentFile, Introspection introspection, QueryPhase queryPhase) |
| 108 |
: GxmShaderProgram(queryPhase) |
| 109 |
{ |
| 110 |
static_cast<void>(vertexFile); |
| 111 |
static_cast<void>(fragmentFile); |
| 112 |
_introspection = introspection; |
| 113 |
} |
| 114 |
|
| 115 |
GxmShaderProgram::GxmShaderProgram(StringView vertexFile, StringView fragmentFile, Introspection introspection) |
| 116 |
: GxmShaderProgram(vertexFile, fragmentFile, introspection, QueryPhase::Immediate) |
| 117 |
{ |
| 118 |
} |
| 119 |
|
| 120 |
GxmShaderProgram::GxmShaderProgram(StringView vertexFile, StringView fragmentFile) |
| 121 |
: GxmShaderProgram(vertexFile, fragmentFile, Introspection::Enabled, QueryPhase::Immediate) |
| 122 |
{ |
| 123 |
} |
| 124 |
|
| 125 |
GxmShaderProgram::~GxmShaderProgram() |
| 126 |
{ |
| 127 |
GxmDevice::OnProgramDestroyed(this); |
| 128 |
ReleaseGpu(); |
| 129 |
} |
| 130 |
|
| 131 |
void GxmShaderProgram::ReleaseGpu() |
| 132 |
{ |
| 133 |
SceGxmShaderPatcher* patcher = GxmDevice::GetShaderPatcher(); |
| 134 |
if (patcher != nullptr) { |
| 135 |
// A patched program may still be referenced by a scene the GPU has not finished, and releasing it |
| 136 |
// frees its USSE code |
| 137 |
GxmDevice::FinishScene(); |
| 138 |
if (SceGxmContext* context = GxmDevice::GetContext()) { |
| 139 |
sceGxmFinish(context); |
| 140 |
} |
| 141 |
for (CachedVertexProgram& cached : _vertexPrograms) { |
| 142 |
sceGxmShaderPatcherReleaseVertexProgram(patcher, cached.Program); |
| 143 |
} |
| 144 |
for (CachedFragmentProgram& cached : _fragmentPrograms) { |
| 145 |
sceGxmShaderPatcherReleaseFragmentProgram(patcher, cached.Program); |
| 146 |
} |
| 147 |
if (_vertexStageId != nullptr) { |
| 148 |
sceGxmShaderPatcherUnregisterProgram(patcher, _vertexStageId); |
| 149 |
} |
| 150 |
if (_fragmentStageId != nullptr) { |
| 151 |
sceGxmShaderPatcherUnregisterProgram(patcher, _fragmentStageId); |
| 152 |
} |
| 153 |
} |
| 154 |
_vertexPrograms.clear(); |
| 155 |
_fragmentPrograms.clear(); |
| 156 |
_vertexStageId = nullptr; |
| 157 |
_fragmentStageId = nullptr; |
| 158 |
|
| 159 |
// The GXP binaries are our own copies of the compiler's output (see CompileCgStage), and the patcher |
| 160 |
// only borrowed them |
| 161 |
std::free(_vertexStage); |
| 162 |
std::free(_fragmentStage); |
| 163 |
_vertexStage = nullptr; |
| 164 |
_fragmentStage = nullptr; |
| 165 |
} |
| 166 |
|
| 167 |
bool GxmShaderProgram::IsLinked() const |
| 168 |
{ |
| 169 |
return (_status == Status::Linked || _status == Status::LinkedWithDeferredQueries || _status == Status::LinkedWithIntrospection); |
| 170 |
} |
| 171 |
|
| 172 |
bool GxmShaderProgram::AttachShaderFromFile(ShaderStage stage, StringView filename) |
| 173 |
{ |
| 174 |
static_cast<void>(stage); |
| 175 |
static_cast<void>(filename); |
| 176 |
// The stage sources come from the generated Cg table, resolved by SetProgramIdentity() |
| 177 |
return true; |
| 178 |
} |
| 179 |
|
| 180 |
bool GxmShaderProgram::AttachShaderFromString(ShaderStage stage, StringView string) |
| 181 |
{ |
| 182 |
static_cast<void>(stage); |
| 183 |
static_cast<void>(string); |
| 184 |
return true; |
| 185 |
} |
| 186 |
|
| 187 |
bool GxmShaderProgram::AttachShaderFromStrings(ShaderStage stage, ArrayView<const StringView> strings) |
| 188 |
{ |
| 189 |
static_cast<void>(stage); |
| 190 |
static_cast<void>(strings); |
| 191 |
return true; |
| 192 |
} |
| 193 |
|
| 194 |
bool GxmShaderProgram::AttachShaderFromStringsAndFile(ShaderStage stage, ArrayView<const StringView> strings, StringView filename) |
| 195 |
{ |
| 196 |
static_cast<void>(stage); |
| 197 |
static_cast<void>(strings); |
| 198 |
static_cast<void>(filename); |
| 199 |
return true; |
| 200 |
} |
| 201 |
|
| 202 |
bool GxmShaderProgram::CompileStages() |
| 203 |
{ |
| 204 |
SceGxmShaderPatcher* patcher = GxmDevice::GetShaderPatcher(); |
| 205 |
if (patcher == nullptr) { |
| 206 |
LOGE("Cannot compile shaders: the sceGxm shader patcher is not created yet"); |
| 207 |
return false; |
| 208 |
} |
| 209 |
|
| 210 |
const GeneratedCgShader* sources = FindGeneratedCgShader(_programName, _variantName); |
| 211 |
if (sources == nullptr) { |
| 212 |
if (_shouldLogOnErrors) { |
| 213 |
LOGE("No generated Cg source for shader \"{}\" (variant \"{}\"): either its Cg transform was " |
| 214 |
"declined by the emitter, or the shader is compiled at runtime, which this backend cannot do", |
| 215 |
_programName != nullptr ? _programName : "<unnamed>", _variantName != nullptr ? _variantName : ""); |
| 216 |
} |
| 217 |
return false; |
| 218 |
} |
| 219 |
|
| 220 |
// Only a batched program carries the baked define, and only then is there anything to rewrite |
| 221 |
String vertexSource, fragmentSource; |
| 222 |
const char* vertexText = sources->VertexSource; |
| 223 |
const char* fragmentText = sources->FragmentSource; |
| 224 |
if (_batchSize != std::uint32_t(DefaultBatchSize) && _batchSize > 0) { |
| 225 |
vertexSource = PatchBatchSize(vertexText, _batchSize); |
| 226 |
fragmentSource = PatchBatchSize(fragmentText, _batchSize); |
| 227 |
vertexText = vertexSource.data(); |
| 228 |
fragmentText = fragmentSource.data(); |
| 229 |
} |
| 230 |
|
| 231 |
std::uint32_t vertexSize = 0; |
| 232 |
_vertexStage = CompileCgStage(vertexText, true, vertexSize); |
| 233 |
if (_vertexStage == nullptr) { |
| 234 |
LOGE("Failed to compile the vertex stage of shader \"{}\"", _programName != nullptr ? _programName : "<unnamed>"); |
| 235 |
return false; |
| 236 |
} |
| 237 |
|
| 238 |
std::uint32_t fragmentSize = 0; |
| 239 |
_fragmentStage = CompileCgStage(fragmentText, false, fragmentSize); |
| 240 |
if (_fragmentStage == nullptr) { |
| 241 |
LOGE("Failed to compile the fragment stage of shader \"{}\"", _programName != nullptr ? _programName : "<unnamed>"); |
| 242 |
std::free(_vertexStage); |
| 243 |
_vertexStage = nullptr; |
| 244 |
return false; |
| 245 |
} |
| 246 |
|
| 247 |
std::int32_t result = sceGxmShaderPatcherRegisterProgram(patcher, _vertexStage, &_vertexStageId); |
| 248 |
if (result < 0) { |
| 249 |
LOGE("sceGxmShaderPatcherRegisterProgram(vertex) failed with 0x{:.8x}", std::uint32_t(result)); |
| 250 |
return false; |
| 251 |
} |
| 252 |
result = sceGxmShaderPatcherRegisterProgram(patcher, _fragmentStage, &_fragmentStageId); |
| 253 |
if (result < 0) { |
| 254 |
LOGE("sceGxmShaderPatcherRegisterProgram(fragment) failed with 0x{:.8x}", std::uint32_t(result)); |
| 255 |
return false; |
| 256 |
} |
| 257 |
|
| 258 |
_vertexUniformBufferSize = sceGxmProgramGetDefaultUniformBufferSize(_vertexStage); |
| 259 |
_fragmentUniformBufferSize = sceGxmProgramGetDefaultUniformBufferSize(_fragmentStage); |
| 260 |
return true; |
| 261 |
} |
| 262 |
|
| 263 |
void GxmShaderProgram::ReflectStage(const SceGxmProgram* program, SmallVector<GxmUniformSlot, 0>& uniformSlots, |
| 264 |
SmallVector<GxmBlockUpload, 0>& blockUploads, SmallVector<GxmSamplerSlot, 0>& samplerSlots) |
| 265 |
{ |
| 266 |
if (program == nullptr || _reflection == nullptr) { |
| 267 |
return; |
| 268 |
} |
| 269 |
|
| 270 |
// Loose uniforms: the byte size comes from the engine-side reflection rather than the compiled |
| 271 |
// parameter, because that is the layout the uniform cache wrote and the whole value moves as one copy |
| 272 |
for (const GxmUniform& uniform : _uniforms) { |
| 273 |
if (uniform.GetBlockIndex() != -1) { |
| 274 |
continue; |
| 275 |
} |
| 276 |
const SceGxmProgramParameter* parameter = sceGxmProgramFindParameterByName(program, uniform.GetName()); |
| 277 |
if (parameter == nullptr) { |
| 278 |
continue; |
| 279 |
} |
| 280 |
// Samplers are resolved separately below, out of the reflection list that carries their unit |
| 281 |
if (sceGxmProgramParameterGetCategory(parameter) == SCE_GXM_PARAMETER_CATEGORY_UNIFORM) { |
| 282 |
uniformSlots.push_back({uniform.GetName(), sceGxmProgramParameterGetResourceIndex(parameter), |
| 283 |
uniform.GetMemorySize()}); |
| 284 |
} |
| 285 |
} |
| 286 |
|
| 287 |
// Uniform blocks: the Cg emitter hoisted each member to a top-level uniform, so a block is uploaded |
| 288 |
// member by member from the range the pipeline bound. The binding index the pipeline uses is the |
| 289 |
// block's own index (see GxmShaderUniformBlocks::Bind()). |
| 290 |
for (std::size_t blockIndex = 0; blockIndex < _reflection->BlockCount; blockIndex++) { |
| 291 |
const ShaderCompiler::UniformBlock& block = _reflection->Blocks[blockIndex]; |
| 292 |
// A batched instance array has to move as one contiguous run, because the reflection describes one |
| 293 |
// element and the shader's array is addressed by index - there is no per-element parameter to resolve. |
| 294 |
// Every other block is a set of independent uniforms that the Cg emitter hoisted out of it, and each |
| 295 |
// one is written where the *compiler* put it, at its own size (see below). |
| 296 |
const bool blockIsInstanceArray = (block.InstanceStride > 0); |
| 297 |
std::int64_t blockBase = INT64_MIN; |
| 298 |
for (std::size_t memberIndex = 0; memberIndex < block.MemberCount; memberIndex++) { |
| 299 |
const ShaderCompiler::BlockMember& member = block.Members[memberIndex]; |
| 300 |
// A member a stage does not read simply is not there, which is normal - only the vertex stage |
| 301 |
// reads the transform, only the fragment stage reads the palette offset - so an unresolved |
| 302 |
// member is not itself worth reporting. What matters is a *block* that reaches neither stage, |
| 303 |
// which is checked once after both have been reflected. |
| 304 |
GxmBlockUpload::Destination destination = GxmBlockUpload::Destination::DefaultUniformBuffer; |
| 305 |
std::uint32_t index = 0; |
| 306 |
if (!FindUniformBase(program, member.Name, destination, index)) { |
| 307 |
continue; |
| 308 |
} |
| 309 |
std::uint32_t memberBytes; |
| 310 |
std::uint32_t sourceStride = 0; |
| 311 |
std::uint32_t compiledStride = 0; |
| 312 |
if (blockIsInstanceArray) { |
| 313 |
// How far apart the compiler put two elements of the array, which is not necessarily the |
| 314 |
// std140 stride the pipeline writes them at: the widest Instance struct carries a palOffset |
| 315 |
// and the narrowest (BatchedLighting) does not, so the compiler packs a shorter element and |
| 316 |
// only element zero of a single contiguous copy ends up where the shader looks for it |
| 317 |
char elementName[128]; |
| 318 |
std::snprintf(elementName, sizeof(elementName), "%s[1]", member.Name); |
| 319 |
GxmBlockUpload::Destination elementDestination = destination; |
| 320 |
std::uint32_t elementIndex = 0; |
| 321 |
if (FindUniformBase(program, elementName, elementDestination, elementIndex) |
| 322 |
&& elementDestination == destination && elementIndex > index) { |
| 323 |
sourceStride = block.InstanceStride; |
| 324 |
compiledStride = (elementIndex - index) * 4u; |
| 325 |
if (compiledStride != sourceStride) { |
| 326 |
LOGD("Shader \"{}\" packs \"{}\" {} bytes apart, not the {} its std140 stride implies", |
| 327 |
_programName != nullptr ? _programName : "<unnamed>", member.Name, |
| 328 |
compiledStride, sourceStride); |
| 329 |
} |
| 330 |
} |
| 331 |
// The bound range from this member to the end of the block, so a batched draw uploads every |
| 332 |
// instance it filled rather than one - clamping to a single element is exactly the kind of |
| 333 |
// silent truncation that renders "almost right". This does assume the compiled array element |
| 334 |
// is laid out like the engine's std140 one, which it is (verified on the console). |
| 335 |
const std::uint32_t blockBytes = (blockIndex < _uniformBlocks.size() |
| 336 |
? std::uint32_t(_uniformBlocks[blockIndex].GetSize()) : 0u); |
| 337 |
memberBytes = (blockBytes > member.Offset ? blockBytes - member.Offset : 0u); |
| 338 |
} else { |
| 339 |
// Just this member. Copying the rest of the block along with it - which is what the batched |
| 340 |
// case above has to do - would only land correctly if the compiler had placed every following |
| 341 |
// uniform exactly where std140 places it, and nothing says it does: it packs what a stage |
| 342 |
// actually reads, in its own order. Where that differs, the members after the first get each |
| 343 |
// other's bytes, and a `spriteSize` holding some other member's data is a quad of the wrong |
| 344 |
// size - a light covering the whole screen instead of its own small area. |
| 345 |
const std::uint32_t elements = (member.ArraySize > 0 |
| 346 |
&& member.ArraySize != ShaderCompiler::SymbolicArraySize ? std::uint32_t(member.ArraySize) : 1u); |
| 347 |
memberBytes = UniformTypeInfo::ComponentCount(member.Type) * 4u * elements; |
| 348 |
if (memberBytes == 0) { |
| 349 |
// A type with no component count of its own (a struct aggregate); the old bulk copy is |
| 350 |
// the only thing that can move it, so keep doing that rather than nothing |
| 351 |
const std::uint32_t blockBytes = (blockIndex < _uniformBlocks.size() |
| 352 |
? std::uint32_t(_uniformBlocks[blockIndex].GetSize()) : 0u); |
| 353 |
memberBytes = (blockBytes > member.Offset ? blockBytes - member.Offset : 0u); |
| 354 |
} |
| 355 |
|
| 356 |
// Whether that assumption would have held is worth knowing, so the difference between where |
| 357 |
// the compiler put this member and where std140 puts it is compared against the first |
| 358 |
// member's - a block whose members disagree is one the old bulk copy corrupted |
| 359 |
const std::int64_t base = std::int64_t(index) * 4 - std::int64_t(member.Offset); |
| 360 |
if (blockBase == INT64_MIN) { |
| 361 |
blockBase = base; |
| 362 |
} else if (base != blockBase) { |
| 363 |
LOGD("Shader \"{}\" lays out \"{}.{}\" at byte {}, not the {} its std140 offset implies", |
| 364 |
_programName != nullptr ? _programName : "<unnamed>", block.Name, member.Name, |
| 365 |
index * 4u, blockBase + std::int64_t(member.Offset)); |
| 366 |
} |
| 367 |
} |
| 368 |
blockUploads.push_back({destination, std::uint32_t(blockIndex), member.Offset, index, memberBytes, |
| 369 |
member.Name, sourceStride, compiledStride}); |
| 370 |
} |
| 371 |
} |
| 372 |
|
| 373 |
// Samplers: the reflection assigns each one the texture unit the material binds to, while the compiled |
| 374 |
// shader decides which sceGxm texture slot it reads - both are needed to route a bound texture |
| 375 |
for (std::size_t i = 0; i < _reflection->TextureCount; i++) { |
| 376 |
const ShaderCompiler::TextureBinding& texture = _reflection->Textures[i]; |
| 377 |
const SceGxmProgramParameter* parameter = sceGxmProgramFindParameterByName(program, texture.Name); |
| 378 |
if (parameter == nullptr || sceGxmProgramParameterGetCategory(parameter) != SCE_GXM_PARAMETER_CATEGORY_SAMPLER) { |
| 379 |
continue; |
| 380 |
} |
| 381 |
const std::uint32_t engineUnit = (texture.Unit >= 0 ? std::uint32_t(texture.Unit) : std::uint32_t(i)); |
| 382 |
const std::uint32_t textureIndex = sceGxmProgramParameterGetResourceIndex(parameter); |
| 383 |
samplerSlots.push_back({texture.Name, engineUnit, textureIndex}); |
| 384 |
} |
| 385 |
} |
| 386 |
|
| 387 |
bool GxmShaderProgram::Link(Introspection introspection) |
| 388 |
{ |
| 389 |
_introspection = introspection; |
| 390 |
|
| 391 |
if (_reflection == nullptr) { |
| 392 |
if (_shouldLogOnErrors) { |
| 393 |
LOGE("Cannot link a shader program without offline reflection on this backend"); |
| 394 |
} |
| 395 |
_status = Status::CompilationFailed; |
| 396 |
return false; |
| 397 |
} |
| 398 |
|
| 399 |
if (!CompileStages()) { |
| 400 |
_status = Status::CompilationFailed; |
| 401 |
return false; |
| 402 |
} |
| 403 |
|
| 404 |
return FinalizeAfterLinking(introspection); |
| 405 |
} |
| 406 |
|
| 407 |
bool GxmShaderProgram::FinalizeAfterLinking(Introspection introspection) |
| 408 |
{ |
| 409 |
_introspection = introspection; |
| 410 |
_status = Status::Linked; |
| 411 |
PerformIntrospection(); |
| 412 |
return true; |
| 413 |
} |
| 414 |
|
| 415 |
void GxmShaderProgram::PerformIntrospection() |
| 416 |
{ |
| 417 |
if (_introspection == Introspection::Disabled || _reflection == nullptr) { |
| 418 |
return; |
| 419 |
} |
| 420 |
|
| 421 |
_uniforms.clear(); |
| 422 |
_uniformBlocks.clear(); |
| 423 |
_attributes.clear(); |
| 424 |
_uniformsSize = 0; |
| 425 |
_uniformBlocksSize = 0; |
| 426 |
_vertexUniformSlots.clear(); |
| 427 |
_fragmentUniformSlots.clear(); |
| 428 |
_vertexBlockUploads.clear(); |
| 429 |
_fragmentBlockUploads.clear(); |
| 430 |
_vertexSamplerSlots.clear(); |
| 431 |
_fragmentSamplerSlots.clear(); |
| 432 |
_stageAttributes.clear(); |
| 433 |
|
| 434 |
ImportReflection(); |
| 435 |
ReflectStageAttributes(); |
| 436 |
ReflectStage(_vertexStage, _vertexUniformSlots, _vertexBlockUploads, _vertexSamplerSlots); |
| 437 |
ReflectStage(_fragmentStage, _fragmentUniformSlots, _fragmentBlockUploads, _fragmentSamplerSlots); |
| 438 |
|
| 439 |
// A uniform block that resolved in neither stage means every draw of this program reads undefined |
| 440 |
// instance data - the failure mode that looks like garbled sprites rather than like an error |
| 441 |
for (std::size_t blockIndex = 0; blockIndex < _reflection->BlockCount; blockIndex++) { |
| 442 |
bool reached = false; |
| 443 |
for (const GxmBlockUpload& upload : _vertexBlockUploads) { |
| 444 |
reached |= (upload.BindingIndex == blockIndex); |
| 445 |
} |
| 446 |
for (const GxmBlockUpload& upload : _fragmentBlockUploads) { |
| 447 |
reached |= (upload.BindingIndex == blockIndex); |
| 448 |
} |
| 449 |
if (!reached) { |
| 450 |
LOGW("Shader \"{}\" uniform block \"{}\" reaches neither stage; its draws will read undefined uniforms", |
| 451 |
_programName != nullptr ? _programName : "<unnamed>", _reflection->Blocks[blockIndex].Name); |
| 452 |
} |
| 453 |
} |
| 454 |
|
| 455 |
_status = Status::LinkedWithIntrospection; |
| 456 |
} |
| 457 |
|
| 458 |
void GxmShaderProgram::ReflectStageAttributes() |
| 459 |
{ |
| 460 |
if (_vertexStage == nullptr) { |
| 461 |
return; |
| 462 |
} |
| 463 |
|
| 464 |
const std::uint32_t count = sceGxmProgramGetParameterCount(_vertexStage); |
| 465 |
for (std::uint32_t i = 0; i < count; i++) { |
| 466 |
const SceGxmProgramParameter* parameter = sceGxmProgramGetParameter(_vertexStage, i); |
| 467 |
if (parameter == nullptr || sceGxmProgramParameterGetCategory(parameter) != SCE_GXM_PARAMETER_CATEGORY_ATTRIBUTE) { |
| 468 |
continue; |
| 469 |
} |
| 470 |
const char* name = sceGxmProgramParameterGetName(parameter); |
| 471 |
if (name == nullptr) { |
| 472 |
continue; |
| 473 |
} |
| 474 |
// An attribute the entry point receives through an input struct is named "<struct>.<member>"; |
| 475 |
// the engine knows it by the member alone |
| 476 |
if (const char* lastDot = std::strrchr(name, '.')) { |
| 477 |
name = lastDot + 1; |
| 478 |
} |
| 479 |
_stageAttributes.push_back({name, |
| 480 |
std::uint16_t(sceGxmProgramParameterGetResourceIndex(parameter)), |
| 481 |
std::uint8_t(sceGxmProgramParameterGetComponentCount(parameter))}); |
| 482 |
} |
| 483 |
} |
| 484 |
|
| 485 |
void GxmShaderProgram::ImportReflection() |
| 486 |
{ |
| 487 |
const ShaderCompiler::ProgramVariant& reflection = *_reflection; |
| 488 |
std::int32_t nextLocation = 0; |
| 489 |
|
| 490 |
// Loose uniforms - samplers are kept in a separate reflection list but treated as loose uniforms here |
| 491 |
for (std::size_t i = 0; i < reflection.UniformCount; i++) { |
| 492 |
const ShaderCompiler::Uniform& u = reflection.Uniforms[i]; |
| 493 |
_uniforms.emplace_back(this, u.Name, u.Type, std::int32_t(u.ArraySize), nextLocation++); |
| 494 |
_uniformsSize += _uniforms.back().GetMemorySize(); |
| 495 |
} |
| 496 |
for (std::size_t i = 0; i < reflection.TextureCount; i++) { |
| 497 |
const ShaderCompiler::TextureBinding& t = reflection.Textures[i]; |
| 498 |
_uniforms.emplace_back(this, t.Name, ShaderCompiler::UniformType::Sampler2D, 1, nextLocation++); |
| 499 |
_uniformsSize += _uniforms.back().GetMemorySize(); |
| 500 |
} |
| 501 |
|
| 502 |
_uniformBlocks.reserve(reflection.BlockCount); |
| 503 |
for (std::size_t i = 0; i < reflection.BlockCount; i++) { |
| 504 |
const ShaderCompiler::UniformBlock& b = reflection.Blocks[i]; |
| 505 |
|
| 506 |
// A BATCH_SIZE-sized instance array uses the explicitly set batch size, or the same 64 KB-based |
| 507 |
// fallback the in-shader "#ifndef BATCH_SIZE" defaults assume when no size is injected |
| 508 |
std::uint32_t effectiveBatchSize = 0; |
| 509 |
std::uint32_t dataSize = b.BaseSize; |
| 510 |
if (b.InstanceStride > 0) { |
| 511 |
effectiveBatchSize = (_batchSize != std::uint32_t(DefaultBatchSize) && _batchSize > 0) |
| 512 |
? _batchSize : (64u * 1024u) / b.InstanceStride; |
| 513 |
dataSize += b.InstanceStride * effectiveBatchSize; |
| 514 |
} |
| 515 |
|
| 516 |
const std::uint32_t blockIndex = std::uint32_t(_uniformBlocks.size()); |
| 517 |
_uniformBlocks.emplace_back(blockIndex, b.Name, std::int32_t(dataSize)); |
| 518 |
GxmUniformBlock& block = _uniformBlocks.back(); |
| 519 |
_uniformBlocksSize += block.GetSize(); |
| 520 |
|
| 521 |
if (_introspection != Introspection::NoUniformsInBlocks) { |
| 522 |
block._members.reserve(b.MemberCount); |
| 523 |
for (std::size_t j = 0; j < b.MemberCount; j++) { |
| 524 |
const ShaderCompiler::BlockMember& m = b.Members[j]; |
| 525 |
if (m.Type == ShaderCompiler::UniformType::Struct) { |
| 526 |
// Struct aggregates are never read by name; only flat leaf members matter |
| 527 |
continue; |
| 528 |
} |
| 529 |
GxmUniform member; |
| 530 |
member.SetName(m.Name); |
| 531 |
member._type = m.Type; |
| 532 |
member._size = (m.ArraySize == ShaderCompiler::SymbolicArraySize) |
| 533 |
? std::int32_t(effectiveBatchSize) |
| 534 |
: (m.ArraySize > 0 ? std::int32_t(m.ArraySize) : 1); |
| 535 |
member._blockIndex = std::int32_t(blockIndex); |
| 536 |
member._offset = std::int32_t(m.Offset); |
| 537 |
member._owner = this; |
| 538 |
block._members.push_back(member); |
| 539 |
} |
| 540 |
} |
| 541 |
} |
| 542 |
|
| 543 |
for (std::size_t i = 0; i < reflection.AttributeCount; i++) { |
| 544 |
const ShaderCompiler::Attribute& a = reflection.Attributes[i]; |
| 545 |
const std::int32_t location = (a.Location >= 0 ? a.Location : std::int32_t(i)); |
| 546 |
_attributes.emplace_back(a.Name, a.Type, location); |
| 547 |
_vertexFormat[std::uint32_t(location)].Init(std::uint32_t(location), std::int32_t(UniformTypeInfo::ComponentCount(a.Type)), 0); |
| 548 |
} |
| 549 |
} |
| 550 |
|
| 551 |
void GxmShaderProgram::Use() |
| 552 |
{ |
| 553 |
GxmDevice::BindProgram(this); |
| 554 |
} |
| 555 |
|
| 556 |
bool GxmShaderProgram::HasAttribute(const char* name) const |
| 557 |
{ |
| 558 |
for (const GxmAttribute& attribute : _attributes) { |
| 559 |
if (std::strcmp(attribute.GetName(), name) == 0) { |
| 560 |
return true; |
| 561 |
} |
| 562 |
} |
| 563 |
return false; |
| 564 |
} |
| 565 |
|
| 566 |
bool GxmShaderProgram::IsIntegerAttribute(const char* name) const |
| 567 |
{ |
| 568 |
for (const GxmAttribute& attribute : _attributes) { |
| 569 |
if (std::strcmp(attribute.GetName(), name) == 0) { |
| 570 |
const ShaderCompiler::UniformType type = attribute.GetType(); |
| 571 |
return (type == ShaderCompiler::UniformType::Int || type == ShaderCompiler::UniformType::UInt); |
| 572 |
} |
| 573 |
} |
| 574 |
return false; |
| 575 |
} |
| 576 |
|
| 577 |
GxmVertexFormat::Attribute* GxmShaderProgram::GetAttribute(const char* name) |
| 578 |
{ |
| 579 |
for (const GxmAttribute& attribute : _attributes) { |
| 580 |
if (std::strcmp(attribute.GetName(), name) == 0 && attribute.GetLocation() >= 0) { |
| 581 |
return &_vertexFormat[std::uint32_t(attribute.GetLocation())]; |
| 582 |
} |
| 583 |
} |
| 584 |
return nullptr; |
| 585 |
} |
| 586 |
|
| 587 |
void GxmShaderProgram::DefineVertexFormat(const GxmBufferObject* vbo, const GxmBufferObject* ibo, std::uint32_t vboOffset) |
| 588 |
{ |
| 589 |
_boundVbo = vbo; |
| 590 |
_boundIbo = ibo; |
| 591 |
_vboOffset = vboOffset; |
| 592 |
_vertexFormat.SetIbo(ibo); |
| 593 |
|
| 594 |
// The corner and instance-index attributes are fed by the device's static streams, not by the |
| 595 |
// pipeline's geometry buffer - the shaders read them instead of gl_VertexID (see VertexIdRewrite). |
| 596 |
// Everything else comes from the bound vertex buffer, exactly like the OpenGL|ES 2.0 profile. |
| 597 |
// The compiled stage decides which streams exist: a sprite shader's corner and instance index come |
| 598 |
// from the device's static streams and appear in no reflection, while a mesh shader's attributes come |
| 599 |
// out of the pipeline's vertex buffer and do |
| 600 |
_usesCornerStream = false; |
| 601 |
_usesBatchedStream = false; |
| 602 |
_usesGeometryStream = false; |
| 603 |
_geometryStride = 0; |
| 604 |
for (const GxmStageAttribute& stageAttribute : _stageAttributes) { |
| 605 |
const bool isCorner = (std::strcmp(stageAttribute.Name, Material::QuadCornerAttributeName) == 0); |
| 606 |
const bool isInstance = (std::strcmp(stageAttribute.Name, "aInstanceIndex") == 0); |
| 607 |
if (isCorner || isInstance) { |
| 608 |
_usesCornerStream = true; |
| 609 |
_usesBatchedStream |= isInstance; |
| 610 |
continue; |
| 611 |
} |
| 612 |
if (vbo == nullptr) { |
| 613 |
continue; |
| 614 |
} |
| 615 |
if (GxmVertexFormat::Attribute* formatAttribute = GetAttribute(stageAttribute.Name)) { |
| 616 |
formatAttribute->setVbo(vbo); |
| 617 |
formatAttribute->SetBaseOffset(vboOffset); |
| 618 |
_usesGeometryStream = true; |
| 619 |
if (formatAttribute->GetStride() > 0) { |
| 620 |
_geometryStride = std::uint32_t(formatAttribute->GetStride()); |
| 621 |
} |
| 622 |
} |
| 623 |
} |
| 624 |
} |
| 625 |
|
| 626 |
void GxmShaderProgram::Reset() |
| 627 |
{ |
| 628 |
if (_status != Status::NotLinked && _status != Status::CompilationFailed) { |
| 629 |
_uniforms.clear(); |
| 630 |
_uniformBlocks.clear(); |
| 631 |
_attributes.clear(); |
| 632 |
_uniformsSize = 0; |
| 633 |
_uniformBlocksSize = 0; |
| 634 |
_resolvedUniforms.clear(); |
| 635 |
_vertexUniformSlots.clear(); |
| 636 |
_fragmentUniformSlots.clear(); |
| 637 |
_vertexBlockUploads.clear(); |
| 638 |
_fragmentBlockUploads.clear(); |
| 639 |
_vertexSamplerSlots.clear(); |
| 640 |
_fragmentSamplerSlots.clear(); |
| 641 |
_vertexFormat.Reset(); |
| 642 |
ReleaseGpu(); |
| 643 |
} |
| 644 |
_status = Status::NotLinked; |
| 645 |
} |
| 646 |
|
| 647 |
void GxmShaderProgram::SetObjectLabel(StringView label) |
| 648 |
{ |
| 649 |
static_cast<void>(label); |
| 650 |
} |
| 651 |
|
| 652 |
void GxmShaderProgram::SetResolvedUniform(const char* name, const std::uint8_t* data) |
| 653 |
{ |
| 654 |
for (ResolvedUniform& resolved : _resolvedUniforms) { |
| 655 |
if (resolved.Name == name) { |
| 656 |
resolved.Data = data; |
| 657 |
return; |
| 658 |
} |
| 659 |
} |
| 660 |
_resolvedUniforms.push_back({String{name}, data}); |
| 661 |
} |
| 662 |
|
| 663 |
const std::uint8_t* GxmShaderProgram::ResolveUniform(const char* name) const |
| 664 |
{ |
| 665 |
for (const ResolvedUniform& resolved : _resolvedUniforms) { |
| 666 |
if (resolved.Name == name) { |
| 667 |
return resolved.Data; |
| 668 |
} |
| 669 |
} |
| 670 |
return nullptr; |
| 671 |
} |
| 672 |
|
| 673 |
void GxmShaderProgram::InstallCompilerLogCallback() |
| 674 |
{ |
| 675 |
shark_install_log_cb(SharkLogCallback); |
| 676 |
} |
| 677 |
|
| 678 |
SceGxmProgram* GxmShaderProgram::CompileCgStage(const char* source, bool vertexStage, std::uint32_t& sizeInBytes) |
| 679 |
{ |
| 680 |
// The length goes IN (vitaShaRK reads it as the source length), the compiled size comes back OUT |
| 681 |
sizeInBytes = std::uint32_t(std::strlen(source)); |
| 682 |
const SceGxmProgram* compiled = shark_compile_shader(source, &sizeInBytes, |
| 683 |
vertexStage ? SHARK_VERTEX_SHADER : SHARK_FRAGMENT_SHADER); |
| 684 |
|
| 685 |
SceGxmProgram* owned = nullptr; |
| 686 |
if (compiled != nullptr && sizeInBytes > 0) { |
| 687 |
owned = static_cast<SceGxmProgram*>(std::malloc(sizeInBytes)); |
| 688 |
if (owned != nullptr) { |
| 689 |
std::memcpy(owned, compiled, sizeInBytes); |
| 690 |
} else { |
| 691 |
LOGE("Out of memory copying a {} byte GXP binary", sizeInBytes); |
| 692 |
} |
| 693 |
} |
| 694 |
|
| 695 |
// Only now, with our own copy in hand, is the compiler's output released |
| 696 |
shark_clear_output(); |
| 697 |
return owned; |
| 698 |
} |
| 699 |
|
| 700 |
bool GxmShaderProgram::FindUniformBase(const SceGxmProgram* program, const char* name, |
| 701 |
GxmBlockUpload::Destination& destination, std::uint32_t& index) |
| 702 |
{ |
| 703 |
if (program == nullptr || name == nullptr) { |
| 704 |
return false; |
| 705 |
} |
| 706 |
|
| 707 |
// A member is matched by its own name, or - for an array of structs, which the compiler may only name |
| 708 |
// through its leaves - by the lowest-indexed parameter whose name begins with it |
| 709 |
const std::size_t nameLength = std::strlen(name); |
| 710 |
const std::uint32_t count = sceGxmProgramGetParameterCount(program); |
| 711 |
bool found = false; |
| 712 |
bool foundBuffer = false; |
| 713 |
std::uint32_t lowest = 0; |
| 714 |
for (std::uint32_t i = 0; i < count; i++) { |
| 715 |
const SceGxmProgramParameter* candidate = sceGxmProgramGetParameter(program, i); |
| 716 |
if (candidate == nullptr) { |
| 717 |
continue; |
| 718 |
} |
| 719 |
const SceGxmParameterCategory category = sceGxmProgramParameterGetCategory(candidate); |
| 720 |
if (category != SCE_GXM_PARAMETER_CATEGORY_UNIFORM && category != SCE_GXM_PARAMETER_CATEGORY_UNIFORM_BUFFER) { |
| 721 |
continue; |
| 722 |
} |
| 723 |
const char* candidateName = sceGxmProgramParameterGetName(candidate); |
| 724 |
if (candidateName == nullptr || std::strncmp(candidateName, name, nameLength) != 0) { |
| 725 |
continue; |
| 726 |
} |
| 727 |
// Only a whole-name match counts, so "instances" does not swallow "instancesFoo" |
| 728 |
const char separator = candidateName[nameLength]; |
| 729 |
if (separator != '\0' && separator != '[' && separator != '.') { |
| 730 |
continue; |
| 731 |
} |
| 732 |
|
| 733 |
if (category == SCE_GXM_PARAMETER_CATEGORY_UNIFORM_BUFFER) { |
| 734 |
// The container wins outright: a member that lives in one is not in the default buffer at all, |
| 735 |
// and its buffer index is what sceGxmSet{Vertex,Fragment}UniformBuffer() takes |
| 736 |
destination = GxmBlockUpload::Destination::UniformBufferContainer; |
| 737 |
index = sceGxmProgramParameterGetContainerIndex(candidate); |
| 738 |
LOGI("Uniform \"{}\" lives in uniform buffer container {} (resource index {})", |
| 739 |
candidateName, index, sceGxmProgramParameterGetResourceIndex(candidate)); |
| 740 |
foundBuffer = true; |
| 741 |
return true; |
| 742 |
} |
| 743 |
|
| 744 |
const std::uint32_t resourceIndex = sceGxmProgramParameterGetResourceIndex(candidate); |
| 745 |
if (!found || resourceIndex < lowest) { |
| 746 |
lowest = resourceIndex; |
| 747 |
found = true; |
| 748 |
} |
| 749 |
} |
| 750 |
|
| 751 |
if (found && !foundBuffer) { |
| 752 |
destination = GxmBlockUpload::Destination::DefaultUniformBuffer; |
| 753 |
index = lowest; |
| 754 |
} |
| 755 |
return found; |
| 756 |
} |
| 757 |
|
| 758 |
const SceGxmProgramParameter* GxmShaderProgram::FindAttribute(const SceGxmProgram* program, const char* name) |
| 759 |
{ |
| 760 |
if (program == nullptr || name == nullptr) { |
| 761 |
return nullptr; |
| 762 |
} |
| 763 |
|
| 764 |
const std::uint32_t count = sceGxmProgramGetParameterCount(program); |
| 765 |
const SceGxmProgramParameter* parameter = (count > 0 ? sceGxmProgramFindParameterByName(program, name) : nullptr); |
| 766 |
if (parameter != nullptr && sceGxmProgramParameterGetCategory(parameter) == SCE_GXM_PARAMETER_CATEGORY_ATTRIBUTE) { |
| 767 |
return parameter; |
| 768 |
} |
| 769 |
|
| 770 |
// Fall back to the last dot-separated component, which is what a `<struct>.<member>` reflected name |
| 771 |
// reduces to, and report the real names if that fails too |
| 772 |
for (std::uint32_t i = 0; i < count; i++) { |
| 773 |
const SceGxmProgramParameter* candidate = sceGxmProgramGetParameter(program, i); |
| 774 |
if (candidate == nullptr || sceGxmProgramParameterGetCategory(candidate) != SCE_GXM_PARAMETER_CATEGORY_ATTRIBUTE) { |
| 775 |
continue; |
| 776 |
} |
| 777 |
const char* candidateName = sceGxmProgramParameterGetName(candidate); |
| 778 |
if (candidateName == nullptr) { |
| 779 |
continue; |
| 780 |
} |
| 781 |
const char* lastDot = std::strrchr(candidateName, '.'); |
| 782 |
if (std::strcmp(lastDot != nullptr ? lastDot + 1 : candidateName, name) == 0) { |
| 783 |
return candidate; |
| 784 |
} |
| 785 |
} |
| 786 |
|
| 787 |
// Every parameter is listed, not just the attributes: "no parameters at all" and "parameters but no |
| 788 |
// attributes" are different problems with different fixes, and the whole point of getting here is to |
| 789 |
// tell them apart |
| 790 |
LOGW("Vertex attribute \"{}\" was not resolved; the stage reflects {} parameters:", name, count); |
| 791 |
for (std::uint32_t i = 0; i < count; i++) { |
| 792 |
const SceGxmProgramParameter* candidate = sceGxmProgramGetParameter(program, i); |
| 793 |
if (candidate == nullptr) { |
| 794 |
LOGW(" [{}] <null parameter>", i); |
| 795 |
continue; |
| 796 |
} |
| 797 |
const char* candidateName = sceGxmProgramParameterGetName(candidate); |
| 798 |
LOGW(" [{}] \"{}\" category {} type {} components {} array {} resource {}", i, |
| 799 |
candidateName != nullptr ? candidateName : "<unnamed>", |
| 800 |
std::uint32_t(sceGxmProgramParameterGetCategory(candidate)), |
| 801 |
std::uint32_t(sceGxmProgramParameterGetType(candidate)), |
| 802 |
sceGxmProgramParameterGetComponentCount(candidate), |
| 803 |
sceGxmProgramParameterGetArraySize(candidate), |
| 804 |
sceGxmProgramParameterGetResourceIndex(candidate)); |
| 805 |
} |
| 806 |
return nullptr; |
| 807 |
} |
| 808 |
|
| 809 |
std::uint32_t GxmShaderProgram::PackBlendKey(bool enabled, nCine::BlendingFactor srcRgb, nCine::BlendingFactor dstRgb, |
| 810 |
nCine::BlendingFactor srcAlpha, nCine::BlendingFactor dstAlpha) |
| 811 |
{ |
| 812 |
if (!enabled) { |
| 813 |
return 0; |
| 814 |
} |
| 815 |
// The four factors compress to a nibble each through their sceGxm counterparts (12 values), leaving the |
| 816 |
// top bit to mark "blending enabled" so an opaque key stays 0 |
| 817 |
return 0x80000000u |
| 818 |
| (std::uint32_t(TranslateBlendFactor(srcRgb)) << 0) |
| 819 |
| (std::uint32_t(TranslateBlendFactor(dstRgb)) << 4) |
| 820 |
| (std::uint32_t(TranslateBlendFactor(srcAlpha)) << 8) |
| 821 |
| (std::uint32_t(TranslateBlendFactor(dstAlpha)) << 12); |
| 822 |
} |
| 823 |
|
| 824 |
SceGxmVertexProgram* GxmShaderProgram::GetVertexProgram() |
| 825 |
{ |
| 826 |
SceGxmShaderPatcher* patcher = GxmDevice::GetShaderPatcher(); |
| 827 |
if (patcher == nullptr || _vertexStageId == nullptr) { |
| 828 |
return nullptr; |
| 829 |
} |
| 830 |
|
| 831 |
const std::uint64_t fingerprint = _vertexFormat.CalculateFingerprint(); |
| 832 |
for (const CachedVertexProgram& cached : _vertexPrograms) { |
| 833 |
if (cached.Fingerprint == fingerprint) { |
| 834 |
return cached.Program; |
| 835 |
} |
| 836 |
} |
| 837 |
|
| 838 |
// Stream 0 is the pipeline's geometry buffer, stream 1 the device's static corner/instance stream. |
| 839 |
// Their strides are the ones the vertex format recorded, or the fixed layout of the static streams. |
| 840 |
SceGxmVertexAttribute gxmAttributes[SCE_GXM_MAX_VERTEX_ATTRIBUTES] = {}; |
| 841 |
SceGxmVertexStream gxmStreams[2] = {}; |
| 842 |
std::uint32_t attributeCount = 0; |
| 843 |
const std::uint32_t staticStreamIndex = GetStaticStreamIndex(); |
| 844 |
|
| 845 |
// Built from what the compiled stage declares - the reflection does not list a sprite shader's |
| 846 |
// synthesized corner and instance-index inputs at all (see GxmStageAttribute) |
| 847 |
for (const GxmStageAttribute& stageAttribute : _stageAttributes) { |
| 848 |
if (attributeCount >= SCE_GXM_MAX_VERTEX_ATTRIBUTES) { |
| 849 |
break; |
| 850 |
} |
| 851 |
const bool isCorner = (std::strcmp(stageAttribute.Name, Material::QuadCornerAttributeName) == 0); |
| 852 |
const bool isInstance = (std::strcmp(stageAttribute.Name, "aInstanceIndex") == 0); |
| 853 |
|
| 854 |
SceGxmVertexAttribute& out = gxmAttributes[attributeCount]; |
| 855 |
out.regIndex = stageAttribute.RegIndex; |
| 856 |
if (isCorner || isInstance) { |
| 857 |
// The device's static stream: two floats of corner, then the batched instance index |
| 858 |
out.streamIndex = std::uint16_t(staticStreamIndex); |
| 859 |
out.offset = std::uint16_t(isInstance ? 8 : 0); |
| 860 |
out.format = SCE_GXM_ATTRIBUTE_FORMAT_F32; |
| 861 |
out.componentCount = std::uint8_t(isInstance ? 1 : 2); |
| 862 |
attributeCount++; |
| 863 |
continue; |
| 864 |
} |
| 865 |
|
| 866 |
const GxmVertexFormat::Attribute* formatAttribute = GetAttribute(stageAttribute.Name); |
| 867 |
if (formatAttribute == nullptr || !_usesGeometryStream) { |
| 868 |
// A geometry attribute the pipeline never described has no stream to read from; leaving it |
| 869 |
// undeclared is better than pointing it at nothing |
| 870 |
LOGW("Vertex attribute \"{}\" of shader \"{}\" has no vertex buffer bound and was skipped", |
| 871 |
stageAttribute.Name, _programName != nullptr ? _programName : "<unnamed>"); |
| 872 |
continue; |
| 873 |
} |
| 874 |
|
| 875 |
out.streamIndex = 0; |
| 876 |
out.offset = std::uint16_t(reinterpret_cast<std::uintptr_t>(formatAttribute->GetPointer())); |
| 877 |
out.componentCount = std::uint8_t(formatAttribute->GetSize() > 0 ? formatAttribute->GetSize() : 1); |
| 878 |
// A vertex format may override the component type to unsigned byte (the ImGui vertex colour is |
| 879 |
// 4 x u8 read as a float4), which is honoured here like glVertexAttribPointer does |
| 880 |
if (formatAttribute->GetType() == std::uint32_t(VertexAttribType::UnsignedByte)) { |
| 881 |
out.format = (formatAttribute->IsNormalized() ? SCE_GXM_ATTRIBUTE_FORMAT_U8N : SCE_GXM_ATTRIBUTE_FORMAT_U8); |
| 882 |
} else if (IsIntegerAttribute(stageAttribute.Name)) { |
| 883 |
// The batch element index of a batched mesh shader, which the batcher writes as an `int32_t` |
| 884 |
// because that is what an integer attribute takes in OpenGL. sceGxm has no 32-bit integer vertex |
| 885 |
// format (only 8- and 16-bit ones, F16 and F32), so the low half of the value is read as a U16 |
| 886 |
// instead - an integer format, so the shader still receives the index as the number it is, where |
| 887 |
// reading the same bytes as F32 would deliver a denormal and truncate to element 0. Little-endian |
| 888 |
// puts that half first, and no batch comes close to 65535 elements. |
| 889 |
out.format = SCE_GXM_ATTRIBUTE_FORMAT_U16; |
| 890 |
out.componentCount = 1; |
| 891 |
} else { |
| 892 |
out.format = SCE_GXM_ATTRIBUTE_FORMAT_F32; |
| 893 |
} |
| 894 |
attributeCount++; |
| 895 |
} |
| 896 |
|
| 897 |
if (attributeCount == 0) { |
| 898 |
// A shader with no attribute inputs at all still needs a vertex program; sceGxm accepts an empty |
| 899 |
// attribute set as long as no stream is declared either |
| 900 |
SceGxmVertexProgram* program = nullptr; |
| 901 |
const std::int32_t result = sceGxmShaderPatcherCreateVertexProgram(patcher, _vertexStageId, nullptr, 0, nullptr, 0, &program); |
| 902 |
if (result < 0) { |
| 903 |
LOGE("sceGxmShaderPatcherCreateVertexProgram(no attributes) failed with 0x{:.8x}", std::uint32_t(result)); |
| 904 |
return nullptr; |
| 905 |
} |
| 906 |
_vertexPrograms.push_back({fingerprint, program}); |
| 907 |
return program; |
| 908 |
} |
| 909 |
|
| 910 |
// Only the streams the layout actually reads are declared: sceGxm expects an address for every one of |
| 911 |
// them, and a layout with no geometry attributes gives the static stream slot 0 instead |
| 912 |
std::uint32_t streamCount = 0; |
| 913 |
if (_usesGeometryStream) { |
| 914 |
gxmStreams[streamCount].stride = std::uint16_t(_geometryStride); |
| 915 |
gxmStreams[streamCount].indexSource = SCE_GXM_INDEX_SOURCE_INDEX_16BIT; |
| 916 |
streamCount++; |
| 917 |
} |
| 918 |
if (_usesCornerStream) { |
| 919 |
gxmStreams[staticStreamIndex].stride = std::uint16_t(_usesBatchedStream ? 12 : 8); |
| 920 |
gxmStreams[staticStreamIndex].indexSource = SCE_GXM_INDEX_SOURCE_INDEX_16BIT; |
| 921 |
streamCount = staticStreamIndex + 1; |
| 922 |
} |
| 923 |
|
| 924 |
SceGxmVertexProgram* program = nullptr; |
| 925 |
const std::int32_t result = sceGxmShaderPatcherCreateVertexProgram(patcher, _vertexStageId, |
| 926 |
gxmAttributes, attributeCount, gxmStreams, streamCount, &program); |
| 927 |
if (result < 0) { |
| 928 |
LOGE("sceGxmShaderPatcherCreateVertexProgram({} attributes, {} streams) failed with 0x{:.8x}", |
| 929 |
attributeCount, streamCount, std::uint32_t(result)); |
| 930 |
return nullptr; |
| 931 |
} |
| 932 |
|
| 933 |
_vertexPrograms.push_back({fingerprint, program}); |
| 934 |
return program; |
| 935 |
} |
| 936 |
|
| 937 |
SceGxmFragmentProgram* GxmShaderProgram::GetFragmentProgram(std::uint32_t blendKey, const SceGxmBlendInfo* blendInfo) |
| 938 |
{ |
| 939 |
SceGxmShaderPatcher* patcher = GxmDevice::GetShaderPatcher(); |
| 940 |
if (patcher == nullptr || _fragmentStageId == nullptr) { |
| 941 |
return nullptr; |
| 942 |
} |
| 943 |
|
| 944 |
for (const CachedFragmentProgram& cached : _fragmentPrograms) { |
| 945 |
if (cached.BlendKey == blendKey) { |
| 946 |
return cached.Program; |
| 947 |
} |
| 948 |
} |
| 949 |
|
| 950 |
SceGxmFragmentProgram* program = nullptr; |
| 951 |
const std::int32_t result = sceGxmShaderPatcherCreateFragmentProgram(patcher, _fragmentStageId, |
| 952 |
SCE_GXM_OUTPUT_REGISTER_FORMAT_UCHAR4, SCE_GXM_MULTISAMPLE_NONE, blendInfo, _vertexStage, &program); |
| 953 |
if (result < 0) { |
| 954 |
LOGE("sceGxmShaderPatcherCreateFragmentProgram(blend 0x{:.8x}) failed with 0x{:.8x}", blendKey, std::uint32_t(result)); |
| 955 |
return nullptr; |
| 956 |
} |
| 957 |
|
| 958 |
_fragmentPrograms.push_back({blendKey, program}); |
| 959 |
return program; |
| 960 |
} |
| 961 |
} |