| 1 |
#include "SwDevice.h" |
| 2 |
#include "SwBuffer.h" |
| 3 |
#include "SwRaster.h" |
| 4 |
#include "SwScanlineOps.h" |
| 5 |
#include "SwShaderProgram.h" |
| 6 |
#include "SwRenderTarget.h" |
| 7 |
#include "SwTexture.h" |
| 8 |
|
| 9 |
#include "../../../../Shaders/Generated/ShaderCompilerTypes.h" |
| 10 |
#include "../../../../Shaders/Generated/SwGeneratedShaders.h" |
| 11 |
|
| 12 |
#include <algorithm> |
| 13 |
#include <cmath> |
| 14 |
#include <cstdio> |
| 15 |
#include <cstring> |
| 16 |
#include <string> |
| 17 |
#include <vector> |
| 18 |
|
| 19 |
#include <Containers/StringStl.h> |
| 20 |
|
| 21 |
namespace nCine::RHI::Software |
| 22 |
{ |
| 23 |
namespace |
| 24 |
{ |
| 25 |
// The DefaultSprite / DefaultBatchedSprites instance layout is a hard contract of the shader family |
| 26 |
// (std140 offsets within the InstanceBlock / each batched Instance), so the effect reads members |
| 27 |
// at these fixed byte offsets instead of chasing per-member reflection (the batched reflection only |
| 28 |
// exposes the "instances" array as one symbolic struct member) |
| 29 |
constexpr std::uint32_t kModelMatrixOffset = 0; |
| 30 |
constexpr std::uint32_t kColorOffset = 64; |
| 31 |
constexpr std::uint32_t kTexRectOffset = 80; |
| 32 |
constexpr std::uint32_t kSpriteSizeOffset = 96; |
| 33 |
// The palette shaders park a flat palette index in the std140 tail padding after spriteSize |
| 34 |
constexpr std::uint32_t kPaletteOffsetOffset = 104; |
| 35 |
// The no-texture sprite family (Sprite_NoTexture / Batched_Sprites_NoTexture) drops texRect from the |
| 36 |
// instance block, so spriteSize sits directly after color (offset 80, not 96) and there is no palette tail |
| 37 |
constexpr std::uint32_t kSpriteSizeNoTexOffset = 80; |
| 38 |
|
| 39 |
const float IdentityMatrix[16] = { |
| 40 |
1, 0, 0, 0, |
| 41 |
0, 1, 0, 0, |
| 42 |
0, 0, 1, 0, |
| 43 |
0, 0, 0, 1 |
| 44 |
}; |
| 45 |
|
| 46 |
// Column-major 4x4 multiply: out = a * b (element (col c, row r) is stored at index c*4 + r) |
| 47 |
void Mat4Mul(const float* a, const float* b, float* out) |
| 48 |
{ |
| 49 |
for (int c = 0; c < 4; c++) { |
| 50 |
for (int r = 0; r < 4; r++) { |
| 51 |
float sum = 0.0f; |
| 52 |
for (int k = 0; k < 4; k++) { |
| 53 |
sum += a[k * 4 + r] * b[c * 4 + k]; |
| 54 |
} |
| 55 |
out[c * 4 + r] = sum; |
| 56 |
} |
| 57 |
} |
| 58 |
} |
| 59 |
|
| 60 |
// Column-major 4x4 times a column vector: out = m * v |
| 61 |
void Mat4Vec4(const float* m, const float* v, float* out) |
| 62 |
{ |
| 63 |
for (int r = 0; r < 4; r++) { |
| 64 |
out[r] = m[0 * 4 + r] * v[0] + m[1 * 4 + r] * v[1] + m[2 * 4 + r] * v[2] + m[3 * 4 + r] * v[3]; |
| 65 |
} |
| 66 |
} |
| 67 |
|
| 68 |
// Maps a pipeline-neutral blend factor onto the rasterizer-local mirror the engine specializes. The |
| 69 |
// two enums list the same factors, so this is a plain meaning-preserving translation; factors the CPU |
| 70 |
// blenders never see fall back to One. |
| 71 |
SwBlendFactor MapBlend(nCine::BlendingFactor factor) |
| 72 |
{ |
| 73 |
switch (factor) { |
| 74 |
case nCine::BlendingFactor::Zero: return SwBlendFactor::Zero; |
| 75 |
case nCine::BlendingFactor::One: return SwBlendFactor::One; |
| 76 |
case nCine::BlendingFactor::SrcColor: return SwBlendFactor::SrcColor; |
| 77 |
case nCine::BlendingFactor::OneMinusSrcColor: return SwBlendFactor::OneMinusSrcColor; |
| 78 |
case nCine::BlendingFactor::SrcAlpha: return SwBlendFactor::SrcAlpha; |
| 79 |
case nCine::BlendingFactor::OneMinusSrcAlpha: return SwBlendFactor::OneMinusSrcAlpha; |
| 80 |
case nCine::BlendingFactor::DstAlpha: return SwBlendFactor::DstAlpha; |
| 81 |
case nCine::BlendingFactor::OneMinusDstAlpha: return SwBlendFactor::OneMinusDstAlpha; |
| 82 |
case nCine::BlendingFactor::DstColor: return SwBlendFactor::DstColor; |
| 83 |
case nCine::BlendingFactor::OneMinusDstColor: return SwBlendFactor::OneMinusDstColor; |
| 84 |
default: return SwBlendFactor::One; |
| 85 |
} |
| 86 |
} |
| 87 |
|
| 88 |
} |
| 89 |
|
| 90 |
SwDevice::BlendingState SwDevice::_blending; |
| 91 |
SwDevice::DepthTestState SwDevice::_depthTest; |
| 92 |
SwDevice::CullFaceState SwDevice::_cullFace; |
| 93 |
SwDevice::ScissorState SwDevice::_scissor; |
| 94 |
Recti SwDevice::_viewport(0, 0, 0, 0); |
| 95 |
Colorf SwDevice::_clearColor(0.0f, 0.0f, 0.0f, 0.0f); |
| 96 |
|
| 97 |
SwShaderProgram* SwDevice::_currentProgram = nullptr; |
| 98 |
const SwTexture* SwDevice::_boundTextures[SwDevice::MaxTextureUnits] = {}; |
| 99 |
SwDevice::UniformRange SwDevice::_boundUniformRanges[SwDevice::MaxUniformBindings] = {}; |
| 100 |
SwRenderTarget* SwDevice::_currentRenderTarget = nullptr; |
| 101 |
std::uint8_t* SwDevice::_defaultFbPixels = nullptr; |
| 102 |
std::int32_t SwDevice::_defaultFbWidth = 0; |
| 103 |
std::int32_t SwDevice::_defaultFbHeight = 0; |
| 104 |
std::int32_t SwDevice::_defaultFbStride = 0; |
| 105 |
std::vector<std::uint8_t> SwDevice::_screenPixels; |
| 106 |
std::vector<SwDevice::PendingSoftwareLight> SwDevice::_pendingSoftwareLights; |
| 107 |
|
| 108 |
void SwDevice::SetBlendingEnabled(bool enabled) |
| 109 |
{ |
| 110 |
_blending.Enabled = enabled; |
| 111 |
} |
| 112 |
|
| 113 |
void SwDevice::SetBlendingFactors(nCine::BlendingFactor srcRgb, nCine::BlendingFactor dstRgb, nCine::BlendingFactor srcAlpha, nCine::BlendingFactor dstAlpha) |
| 114 |
{ |
| 115 |
_blending.SrcRgb = srcRgb; |
| 116 |
_blending.DstRgb = dstRgb; |
| 117 |
_blending.SrcAlpha = srcAlpha; |
| 118 |
_blending.DstAlpha = dstAlpha; |
| 119 |
} |
| 120 |
|
| 121 |
SwDevice::BlendingState SwDevice::GetBlendingState() |
| 122 |
{ |
| 123 |
return _blending; |
| 124 |
} |
| 125 |
|
| 126 |
void SwDevice::SetBlendingState(const BlendingState& state) |
| 127 |
{ |
| 128 |
_blending = state; |
| 129 |
} |
| 130 |
|
| 131 |
void SwDevice::SetDepthTestEnabled(bool enabled) |
| 132 |
{ |
| 133 |
_depthTest.TestEnabled = enabled; |
| 134 |
} |
| 135 |
|
| 136 |
void SwDevice::SetDepthMaskEnabled(bool enabled) |
| 137 |
{ |
| 138 |
_depthTest.MaskEnabled = enabled; |
| 139 |
} |
| 140 |
|
| 141 |
SwDevice::DepthTestState SwDevice::GetDepthTestState() |
| 142 |
{ |
| 143 |
return _depthTest; |
| 144 |
} |
| 145 |
|
| 146 |
void SwDevice::SetDepthTestState(const DepthTestState& state) |
| 147 |
{ |
| 148 |
_depthTest = state; |
| 149 |
} |
| 150 |
|
| 151 |
void SwDevice::SetCullFaceEnabled(bool enabled) |
| 152 |
{ |
| 153 |
_cullFace.Enabled = enabled; |
| 154 |
} |
| 155 |
|
| 156 |
SwDevice::CullFaceState SwDevice::GetCullFaceState() |
| 157 |
{ |
| 158 |
return _cullFace; |
| 159 |
} |
| 160 |
|
| 161 |
void SwDevice::SetCullFaceState(const CullFaceState& state) |
| 162 |
{ |
| 163 |
_cullFace = state; |
| 164 |
} |
| 165 |
|
| 166 |
SwDevice::ScissorState SwDevice::GetScissorState() |
| 167 |
{ |
| 168 |
return _scissor; |
| 169 |
} |
| 170 |
|
| 171 |
void SwDevice::SetScissorState(const ScissorState& state) |
| 172 |
{ |
| 173 |
_scissor = state; |
| 174 |
} |
| 175 |
|
| 176 |
void SwDevice::SetScissor(const Recti& rect) |
| 177 |
{ |
| 178 |
_scissor.Enabled = true; |
| 179 |
_scissor.Rect = rect; |
| 180 |
} |
| 181 |
|
| 182 |
void SwDevice::SetScissorTestEnabled(bool enabled) |
| 183 |
{ |
| 184 |
_scissor.Enabled = enabled; |
| 185 |
} |
| 186 |
|
| 187 |
Recti SwDevice::GetViewport() |
| 188 |
{ |
| 189 |
return _viewport; |
| 190 |
} |
| 191 |
|
| 192 |
void SwDevice::SetViewport(const Recti& rect) |
| 193 |
{ |
| 194 |
_viewport = rect; |
| 195 |
} |
| 196 |
|
| 197 |
void SwDevice::InitViewport(std::int32_t x, std::int32_t y, std::int32_t width, std::int32_t height) |
| 198 |
{ |
| 199 |
_viewport = Recti(x, y, width, height); |
| 200 |
} |
| 201 |
|
| 202 |
Colorf SwDevice::GetClearColor() |
| 203 |
{ |
| 204 |
return _clearColor; |
| 205 |
} |
| 206 |
|
| 207 |
void SwDevice::SetClearColor(const Colorf& color) |
| 208 |
{ |
| 209 |
_clearColor = color; |
| 210 |
} |
| 211 |
|
| 212 |
void SwDevice::Clear(ClearFlags flags) |
| 213 |
{ |
| 214 |
// The software backend is 2D, so only the color buffer is meaningful |
| 215 |
if ((flags & ClearFlags::Color) == ClearFlags::None) { |
| 216 |
return; |
| 217 |
} |
| 218 |
Framebuffer fb; |
| 219 |
if (!ResolveFramebuffer(fb)) { |
| 220 |
return; |
| 221 |
} |
| 222 |
// A render target's color texture is stored bottom-up, the screen back-buffer top-down; Clear fills |
| 223 |
// the whole store either way, so the flag only has to match SetColorBuffer's row convention |
| 224 |
SwRaster::SetColorBuffer(fb.pixels, fb.width, fb.height, _currentRenderTarget != nullptr); |
| 225 |
SwRaster::Clear(_clearColor.R, _clearColor.G, _clearColor.B, _clearColor.A); |
| 226 |
} |
| 227 |
|
| 228 |
void SwDevice::DrawArrays(PrimitiveType primitive, std::int32_t firstVertex, std::int32_t numVertices) |
| 229 |
{ |
| 230 |
Dispatch(primitive, firstVertex, numVertices); |
| 231 |
} |
| 232 |
|
| 233 |
void SwDevice::DrawArraysInstanced(PrimitiveType primitive, std::int32_t firstVertex, std::int32_t numVertices, std::int32_t numInstances) |
| 234 |
{ |
| 235 |
static_cast<void>(numInstances); |
| 236 |
// The sprite path batches into one non-instanced draw; hardware instancing is unused here |
| 237 |
Dispatch(primitive, firstVertex, numVertices); |
| 238 |
} |
| 239 |
|
| 240 |
void SwDevice::DrawElements(PrimitiveType primitive, std::uint32_t numIndices, IndexFormat indexFormat, std::uintptr_t indexOffset, std::int32_t baseVertex) |
| 241 |
{ |
| 242 |
static_cast<void>(indexFormat); |
| 243 |
static_cast<void>(indexOffset); |
| 244 |
Dispatch(primitive, baseVertex, std::int32_t(numIndices)); |
| 245 |
} |
| 246 |
|
| 247 |
void SwDevice::DrawElementsInstanced(PrimitiveType primitive, std::uint32_t numIndices, IndexFormat indexFormat, std::uintptr_t indexOffset, std::int32_t numInstances, std::int32_t baseVertex) |
| 248 |
{ |
| 249 |
static_cast<void>(indexFormat); |
| 250 |
static_cast<void>(indexOffset); |
| 251 |
static_cast<void>(numInstances); |
| 252 |
Dispatch(primitive, baseVertex, std::int32_t(numIndices)); |
| 253 |
} |
| 254 |
|
| 255 |
FenceHandle SwDevice::InsertFence() |
| 256 |
{ |
| 257 |
return nullptr; |
| 258 |
} |
| 259 |
|
| 260 |
void SwDevice::DeleteFence(FenceHandle& fence) |
| 261 |
{ |
| 262 |
fence = nullptr; |
| 263 |
} |
| 264 |
|
| 265 |
bool SwDevice::ClientWaitFence(FenceHandle fence, std::uint64_t timeoutNs) |
| 266 |
{ |
| 267 |
static_cast<void>(fence); |
| 268 |
static_cast<void>(timeoutNs); |
| 269 |
return true; |
| 270 |
} |
| 271 |
|
| 272 |
void SwDevice::SetupInitialState() |
| 273 |
{ |
| 274 |
_blending = BlendingState{}; |
| 275 |
_depthTest = DepthTestState{}; |
| 276 |
_cullFace = CullFaceState{}; |
| 277 |
_scissor = ScissorState{}; |
| 278 |
} |
| 279 |
|
| 280 |
void SwDevice::BindProgram(SwShaderProgram* program) |
| 281 |
{ |
| 282 |
_currentProgram = program; |
| 283 |
} |
| 284 |
|
| 285 |
SwShaderProgram* SwDevice::CurrentProgram() |
| 286 |
{ |
| 287 |
return _currentProgram; |
| 288 |
} |
| 289 |
|
| 290 |
void SwDevice::BindTexture(std::uint32_t unit, const SwTexture* texture) |
| 291 |
{ |
| 292 |
if (unit < MaxTextureUnits) { |
| 293 |
_boundTextures[unit] = texture; |
| 294 |
} |
| 295 |
} |
| 296 |
|
| 297 |
void SwDevice::UnbindTexture(const SwTexture* texture) |
| 298 |
{ |
| 299 |
// Called from ~SwTexture so a destroyed texture never lingers as a dangling pointer in _boundTextures (a |
| 300 |
// later deferred draw reads it in Dispatch and would dereference freed memory - the same class of crash the |
| 301 |
// D3D11 backend hit during splitscreen level changes). Clears every unit it may be bound to. |
| 302 |
for (std::uint32_t unit = 0; unit < MaxTextureUnits; unit++) { |
| 303 |
if (_boundTextures[unit] == texture) { |
| 304 |
_boundTextures[unit] = nullptr; |
| 305 |
} |
| 306 |
} |
| 307 |
} |
| 308 |
|
| 309 |
const SwTexture* SwDevice::GetBoundTexture(std::uint32_t unit) |
| 310 |
{ |
| 311 |
return (unit < MaxTextureUnits ? _boundTextures[unit] : nullptr); |
| 312 |
} |
| 313 |
|
| 314 |
void SwDevice::BindUniformRange(std::uint32_t index, const std::uint8_t* data, std::uint32_t size) |
| 315 |
{ |
| 316 |
if (index < MaxUniformBindings) { |
| 317 |
_boundUniformRanges[index].Data = data; |
| 318 |
_boundUniformRanges[index].Size = size; |
| 319 |
} |
| 320 |
} |
| 321 |
|
| 322 |
void SwDevice::SetRenderTarget(SwRenderTarget* renderTarget) |
| 323 |
{ |
| 324 |
_currentRenderTarget = renderTarget; |
| 325 |
} |
| 326 |
|
| 327 |
void SwDevice::UnbindRenderTarget(const SwRenderTarget* renderTarget) |
| 328 |
{ |
| 329 |
// Called from ~SwRenderTarget so a destroyed target can't dangle as _currentRenderTarget (ResolveFramebuffer |
| 330 |
// and Dispatch dereference it). Reverts to the default framebuffer (nullptr); the pipeline binds a fresh |
| 331 |
// target before the next off-screen draw. |
| 332 |
if (_currentRenderTarget == renderTarget) { |
| 333 |
_currentRenderTarget = nullptr; |
| 334 |
} |
| 335 |
} |
| 336 |
|
| 337 |
void SwDevice::SetDefaultFramebuffer(const Framebuffer& framebuffer) |
| 338 |
{ |
| 339 |
_defaultFbPixels = framebuffer.pixels; |
| 340 |
_defaultFbWidth = framebuffer.width; |
| 341 |
_defaultFbHeight = framebuffer.height; |
| 342 |
_defaultFbStride = framebuffer.strideBytes; |
| 343 |
} |
| 344 |
|
| 345 |
void SwDevice::ResizeScreenFramebuffer(std::int32_t width, std::int32_t height) |
| 346 |
{ |
| 347 |
if (width <= 0 || height <= 0) { |
| 348 |
return; |
| 349 |
} |
| 350 |
#if defined(RHI_USE_FB16) |
| 351 |
// 16-bit mode: the screen buffer stores native-endian RGB565 (2 bytes per pixel - half the memory |
| 352 |
// and present bandwidth); render-target textures stay RGBA8 (see SwRaster.h) |
| 353 |
constexpr std::size_t ScreenBpp = 2; |
| 354 |
#else |
| 355 |
constexpr std::size_t ScreenBpp = 4; |
| 356 |
#endif |
| 357 |
const std::size_t required = std::size_t(width) * std::size_t(height) * ScreenBpp; |
| 358 |
if (_screenPixels.size() != required) { |
| 359 |
_screenPixels.assign(required, 0); |
| 360 |
} |
| 361 |
Framebuffer fb; |
| 362 |
fb.pixels = _screenPixels.data(); |
| 363 |
fb.width = width; |
| 364 |
fb.height = height; |
| 365 |
fb.strideBytes = width * std::int32_t(ScreenBpp); |
| 366 |
SetDefaultFramebuffer(fb); |
| 367 |
} |
| 368 |
|
| 369 |
Framebuffer SwDevice::GetScreenFramebuffer() |
| 370 |
{ |
| 371 |
Framebuffer fb; |
| 372 |
fb.pixels = _defaultFbPixels; |
| 373 |
fb.width = _defaultFbWidth; |
| 374 |
fb.height = _defaultFbHeight; |
| 375 |
fb.strideBytes = _defaultFbStride; |
| 376 |
return fb; |
| 377 |
} |
| 378 |
|
| 379 |
void SwDevice::FlushSoftwareRenderer() |
| 380 |
{ |
| 381 |
SwRaster::Flush(); |
| 382 |
} |
| 383 |
|
| 384 |
void SwDevice::EndFrame() |
| 385 |
{ |
| 386 |
if (!_pendingSoftwareLights.empty()) { |
| 387 |
// A queued lightmap was not consumed by a Combine draw this frame (the draw was culled or skipped); |
| 388 |
// drop the leftovers so they cannot desync the FIFO pairing or dangle into the next frame |
| 389 |
static bool warnedLeftoverLights = false; |
| 390 |
if (!warnedLeftoverLights) { |
| 391 |
warnedLeftoverLights = true; |
| 392 |
LOGW("{} software-lighting entr{} left unconsumed at frame end - dropping", _pendingSoftwareLights.size(), _pendingSoftwareLights.size() == 1 ? "y" : "ies"); |
| 393 |
} |
| 394 |
_pendingSoftwareLights.clear(); |
| 395 |
} |
| 396 |
} |
| 397 |
|
| 398 |
void SwDevice::SetPendingSoftwareLighting(const float* lightmap, std::int32_t lmW, std::int32_t lmH, std::int32_t scale, |
| 399 |
std::int32_t vpX, std::int32_t vpY, std::int32_t vpW, std::int32_t vpH, float ambR, float ambG, float ambB, |
| 400 |
bool waterActive, float waterLevelPx, float waterTime, float waterCamY) |
| 401 |
{ |
| 402 |
PendingSoftwareLight entry; |
| 403 |
entry.Lightmap = lightmap; |
| 404 |
entry.LmW = lmW; |
| 405 |
entry.LmH = lmH; |
| 406 |
entry.Scale = (scale > 0 ? scale : 1); |
| 407 |
entry.VpX = vpX; |
| 408 |
entry.VpY = vpY; |
| 409 |
entry.VpW = vpW; |
| 410 |
entry.VpH = vpH; |
| 411 |
entry.AmbR = ambR; |
| 412 |
entry.AmbG = ambG; |
| 413 |
entry.AmbB = ambB; |
| 414 |
entry.WaterActive = waterActive; |
| 415 |
entry.WaterLevelPx = waterLevelPx; |
| 416 |
entry.WaterTime = waterTime; |
| 417 |
entry.WaterCamY = waterCamY; |
| 418 |
// Pushed in Visit/OnDraw order; the matching Combine draws are dispatched in that same order, so the queue |
| 419 |
// is consumed front-to-back (see ApplyPendingSoftwareLighting) |
| 420 |
_pendingSoftwareLights.push_back(entry); |
| 421 |
} |
| 422 |
|
| 423 |
// Shifts one row of RGBA8 pixels horizontally in place with edge clamping: out(x) = in(clamp(x + shift, |
| 424 |
// 0, count - 1)) - the per-row equivalent of the water shader's clamped uv.x displacement. A memmove plus |
| 425 |
// an edge-pixel fill, so it stays cheap even at full viewport width. |
| 426 |
static void ShiftRowHorizontal(std::uint8_t* row, std::int32_t count, std::int32_t shift) |
| 427 |
{ |
| 428 |
if (shift == 0 || count <= 0) { |
| 429 |
return; |
| 430 |
} |
| 431 |
std::uint8_t edge[4]; |
| 432 |
if (shift >= count || shift <= -count) { |
| 433 |
// Degenerate shift: the whole row clamps to one edge pixel |
| 434 |
std::memcpy(edge, row + (shift > 0 ? (std::size_t)(count - 1) * 4 : 0), 4); |
| 435 |
for (std::int32_t x = 0; x < count; x++) { |
| 436 |
std::memcpy(row + (std::size_t)x * 4, edge, 4); |
| 437 |
} |
| 438 |
return; |
| 439 |
} |
| 440 |
if (shift > 0) { |
| 441 |
std::memmove(row, row + (std::size_t)shift * 4, (std::size_t)(count - shift) * 4); |
| 442 |
std::memcpy(edge, row + (std::size_t)(count - shift - 1) * 4, 4); |
| 443 |
for (std::int32_t x = count - shift; x < count; x++) { |
| 444 |
std::memcpy(row + (std::size_t)x * 4, edge, 4); |
| 445 |
} |
| 446 |
} else { |
| 447 |
const std::int32_t s = -shift; |
| 448 |
std::memmove(row + (std::size_t)s * 4, row, (std::size_t)(count - s) * 4); |
| 449 |
std::memcpy(edge, row + (std::size_t)s * 4, 4); |
| 450 |
for (std::int32_t x = 0; x < s; x++) { |
| 451 |
std::memcpy(row + (std::size_t)x * 4, edge, 4); |
| 452 |
} |
| 453 |
} |
| 454 |
} |
| 455 |
|
| 456 |
#if defined(RHI_USE_FB16) |
| 457 |
// RGBA8 staging row for the RGB565 screen framebuffer, used by ApplyPendingSoftwareLighting below (its |
| 458 |
// row kernels operate on 4-byte pixels). Main-thread-only, like the whole Combine intercept. Sized for |
| 459 |
// the widest surface the tile renderer accepts. |
| 460 |
alignas(32) static std::uint8_t g_fb16RowStage[8192 * 4]; |
| 461 |
#endif |
| 462 |
|
| 463 |
void SwDevice::ApplyPendingSoftwareLighting() |
| 464 |
{ |
| 465 |
if (_pendingSoftwareLights.empty()) { |
| 466 |
// No lighting queued for this Combine draw: the scene stays as rasterized (fully lit) |
| 467 |
return; |
| 468 |
} |
| 469 |
const PendingSoftwareLight light = _pendingSoftwareLights.front(); |
| 470 |
_pendingSoftwareLights.erase(_pendingSoftwareLights.begin()); |
| 471 |
|
| 472 |
const bool hasLighting = (light.Lightmap != nullptr && light.LmW > 0 && light.LmH > 0); |
| 473 |
const bool hasWater = light.WaterActive; |
| 474 |
if (!hasLighting && !hasWater) { |
| 475 |
return; |
| 476 |
} |
| 477 |
|
| 478 |
// The scene viewport rasterized straight into the screen back-buffer and deferred its tiles to the tile |
| 479 |
// renderer; drain them so the buffer holds the finished scene before it is read back and modified here. The |
| 480 |
// HUD is dispatched after this Combine draw, so it is not affected (it re-defers and is flushed at present). |
| 481 |
FlushSoftwareRenderer(); |
| 482 |
const Framebuffer fb = GetScreenFramebuffer(); |
| 483 |
if (fb.pixels == nullptr) { |
| 484 |
return; |
| 485 |
} |
| 486 |
|
| 487 |
// Clamp the viewport rectangle to the actual screen buffer (the compositor submits the unclamped rect) |
| 488 |
const std::int32_t vpX = std::max(0, light.VpX); |
| 489 |
const std::int32_t vpY = std::max(0, light.VpY); |
| 490 |
const std::int32_t vpW = std::min(light.VpW, fb.width - vpX); |
| 491 |
const std::int32_t vpH = std::min(light.VpH, fb.height - vpY); |
| 492 |
if (vpW <= 0 || vpH <= 0) { |
| 493 |
return; |
| 494 |
} |
| 495 |
|
| 496 |
const std::int32_t scale = light.Scale; |
| 497 |
const std::int32_t lmW = light.LmW; |
| 498 |
const std::int32_t lmH = light.LmH; |
| 499 |
const float ambR = light.AmbR; |
| 500 |
const float ambG = light.AmbG; |
| 501 |
const float ambB = light.AmbB; |
| 502 |
|
| 503 |
// Water precompute. This is the lightweight CPU replacement of the CombineWithWaterLow shader: a per-row |
| 504 |
// horizontal sine displacement, the constant water tint mix(main, (0.4, 0.6, 0.8), 0.4), a surface glow |
| 505 |
// band (0.2 * topGradient^2 plus 0.2 on the waterline row, approximated as a mix toward white instead of |
| 506 |
// the shader's saturating add) and the shader's extra darkness above deep water (uWaterLevel < 0.4). The |
| 507 |
// High-quality extras (noise displacement, chromatic aberration, light rays, wavy surface shape) are |
| 508 |
// dropped - both quality settings share this effect on the software backend. |
| 509 |
// |
| 510 |
// Rows inside the viewport run bottom-up visually (row = camY - worldY + vpH/2, the same convention the |
| 511 |
// lightmap uses; the present blit flips the buffer), so the underwater part (worldY > waterY) is the row |
| 512 |
// range [0, waterRowLimit) and the waterline sits at row waterRowLimit, counted from the buffer's top. |
| 513 |
const float invVpH = 1.0f / (float)vpH; |
| 514 |
float waterRowLimit = 0.0f; |
| 515 |
std::int32_t belowEndExcl = 0; |
| 516 |
float waveAmplitudePx = 0.0f, wavePhaseBase = 0.0f, wavePhasePerRow = 0.0f; |
| 517 |
std::uint8_t aboveWaterBlend[4] = {}; |
| 518 |
if (hasWater) { |
| 519 |
waterRowLimit = (float)vpH - light.WaterLevelPx; |
| 520 |
belowEndExcl = std::min(vpH, (std::int32_t)std::ceil(waterRowLimit)); |
| 521 |
// Shader: uv.x += 0.008 * sin(uTime * 16 + uvWorld.y * 20), uvWorld.y = (camY + vpH - row) / vpH |
| 522 |
waveAmplitudePx = 0.008f * (float)vpW; |
| 523 |
wavePhaseBase = light.WaterTime * 16.0f + (light.WaterCamY + (float)vpH) * invVpH * 20.0f; |
| 524 |
wavePhasePerRow = -20.0f * invVpH; |
| 525 |
// Shader: when the waterline is in the top 40% of the view, the above-water part is darkened toward |
| 526 |
// the ambient colour by (0.4 - uWaterLevel) - deep water dims the world above it |
| 527 |
const float waterLevelNorm = light.WaterLevelPx * invVpH; |
| 528 |
if (waterLevelNorm < 0.4f) { |
| 529 |
const std::int32_t a = (std::int32_t)((0.4f - waterLevelNorm) * 255.0f + 0.5f); |
| 530 |
aboveWaterBlend[0] = (std::uint8_t)std::clamp((std::int32_t)(ambR * 255.0f + 0.5f), 0, 255); |
| 531 |
aboveWaterBlend[1] = (std::uint8_t)std::clamp((std::int32_t)(ambG * 255.0f + 0.5f), 0, 255); |
| 532 |
aboveWaterBlend[2] = (std::uint8_t)std::clamp((std::int32_t)(ambB * 255.0f + 0.5f), 0, 255); |
| 533 |
aboveWaterBlend[3] = (std::uint8_t)std::clamp(a, 0, 254); |
| 534 |
} |
| 535 |
} |
| 536 |
constexpr float WaterColorR = 0.4f, WaterColorG = 0.6f, WaterColorB = 0.8f; |
| 537 |
|
| 538 |
// In-place combine over the viewport region, matching the core of Combine(WithWater).shader with the |
| 539 |
// (heavy, blur-dependent) grayscale night-vision term dropped: |
| 540 |
// main = water tint/waves (underwater rows only) |
| 541 |
// lit = main * (1 + g) + max(g - 0.7, 0) |
| 542 |
// out = mix(lit, ambientRGB, clamp(1 - r, 0, 1)) (+ above-deep-water darkness) |
| 543 |
// The water colour ops run before the lighting mix, in the same order as the shader. The half-resolution |
| 544 |
// lightmap is sampled point-wise (both channels clamped to [0,1] to match the shader path's RG8 lighting |
| 545 |
// buffer, so a negative Brightness stays a no-op instead of becoming a "black light"), and a fully lit |
| 546 |
// texel leaves the scene pixel as-is. The row cores are the CPU-dispatched SIMD kernels (the lighting one |
| 547 |
// bit-identical to the scalar loop it replaced, see SwScanlineOps.h). |
| 548 |
for (std::int32_t y = 0; y < vpH; y++) { |
| 549 |
std::uint8_t* px; |
| 550 |
#if defined(RHI_USE_FB16) |
| 551 |
// The screen framebuffer is RGB565 in this mode; stage each touched row as RGBA8 so the row |
| 552 |
// kernels below (wave shift, water tint, lighting combine) stay unchanged, then store it back |
| 553 |
std::uint8_t* fbRow16 = fb.pixels + (std::size_t)(vpY + y) * fb.strideBytes + (std::size_t)vpX * 2; |
| 554 |
SwLoadFbSpan565(g_fb16RowStage, fbRow16, vpW); |
| 555 |
px = g_fb16RowStage; |
| 556 |
#else |
| 557 |
px = fb.pixels + (std::size_t)(vpY + y) * fb.strideBytes + (std::size_t)vpX * 4; |
| 558 |
#endif |
| 559 |
|
| 560 |
const bool isUnderwaterRow = (hasWater && y < belowEndExcl); |
| 561 |
if (isUnderwaterRow) { |
| 562 |
// Horizontal wave displacement, constant per row |
| 563 |
const float phase = wavePhaseBase + wavePhasePerRow * (float)y; |
| 564 |
const std::int32_t shift = (std::int32_t)std::lround(waveAmplitudePx * std::sin(phase)); |
| 565 |
ShiftRowHorizontal(px, vpW, shift); |
| 566 |
|
| 567 |
// Water tint + surface glow folded into one constant blend: out = main * 0.6 * (1 - glow) + |
| 568 |
// (waterColor * 0.4 * (1 - glow) + glow). Solving out = mix(main, src, a) for the blend kernel |
| 569 |
// gives a = 0.4 + 0.6 * glow and src = (waterColor * 0.4 * (1 - glow) + glow) / a, with src |
| 570 |
// always inside [0, 1] because it is a convex combination of waterColor and white. |
| 571 |
const float topDist = (waterRowLimit - (float)y) * invVpH; |
| 572 |
const float topGradient = std::max(1.0f - topDist, 0.0f); |
| 573 |
float glow = 0.2f * topGradient * topGradient; |
| 574 |
if (waterRowLimit - (float)y < 1.0f) { |
| 575 |
glow += 0.2f; // The waterline row itself gets an extra highlight |
| 576 |
} |
| 577 |
const float a = 0.4f + 0.6f * glow; |
| 578 |
const float tintScale = 0.4f * (1.0f - glow) / a; |
| 579 |
const float glowTerm = glow / a; |
| 580 |
std::uint8_t tintBlend[4]; |
| 581 |
tintBlend[0] = (std::uint8_t)std::clamp((std::int32_t)((WaterColorR * tintScale + glowTerm) * 255.0f + 0.5f), 0, 255); |
| 582 |
tintBlend[1] = (std::uint8_t)std::clamp((std::int32_t)((WaterColorG * tintScale + glowTerm) * 255.0f + 0.5f), 0, 255); |
| 583 |
tintBlend[2] = (std::uint8_t)std::clamp((std::int32_t)((WaterColorB * tintScale + glowTerm) * 255.0f + 0.5f), 0, 255); |
| 584 |
tintBlend[3] = (std::uint8_t)std::clamp((std::int32_t)(a * 255.0f + 0.5f), 1, 254); |
| 585 |
BlendScanlineConstSrcAlpha(px, vpW, tintBlend); |
| 586 |
} |
| 587 |
|
| 588 |
if (hasLighting) { |
| 589 |
const std::int32_t lmY = std::min(y / scale, lmH - 1); |
| 590 |
const float* texelBase = light.Lightmap + (std::size_t)lmY * lmW * 2; |
| 591 |
CombineLightingScanline(px, vpW, texelBase, lmW, scale, ambR, ambG, ambB); |
| 592 |
} |
| 593 |
|
| 594 |
if (hasWater && !isUnderwaterRow && aboveWaterBlend[3] != 0) { |
| 595 |
BlendScanlineConstSrcAlpha(px, vpW, aboveWaterBlend); |
| 596 |
} |
| 597 |
|
| 598 |
#if defined(RHI_USE_FB16) |
| 599 |
SwStoreFbSpan565(fbRow16, g_fb16RowStage, vpW); |
| 600 |
#endif |
| 601 |
} |
| 602 |
} |
| 603 |
|
| 604 |
bool SwDevice::ResolveFramebuffer(Framebuffer& out) |
| 605 |
{ |
| 606 |
if (_currentRenderTarget != nullptr) { |
| 607 |
SwTexture* texture = _currentRenderTarget->GetColorTexture(0); |
| 608 |
if (texture != nullptr && texture->MutablePixels() != nullptr) { |
| 609 |
out.pixels = texture->MutablePixels(); |
| 610 |
out.width = texture->GetWidth(); |
| 611 |
out.height = texture->GetHeight(); |
| 612 |
out.strideBytes = texture->GetStrideBytes(); |
| 613 |
return true; |
| 614 |
} |
| 615 |
} |
| 616 |
if (_defaultFbPixels != nullptr) { |
| 617 |
out.pixels = _defaultFbPixels; |
| 618 |
out.width = _defaultFbWidth; |
| 619 |
out.height = _defaultFbHeight; |
| 620 |
out.strideBytes = _defaultFbStride; |
| 621 |
return true; |
| 622 |
} |
| 623 |
return false; |
| 624 |
} |
| 625 |
|
| 626 |
namespace |
| 627 |
{ |
| 628 |
/** |
| 629 |
General vertex-fed dispatch of the MeshSprite family (called from SwDevice::Dispatch when the |
| 630 |
bound program declares real vertex attributes). Reads the interleaved vertices of |
| 631 |
[firstVertex, firstVertex + numVertices) from the bound vertex buffer, transforms them on the |
| 632 |
CPU exactly like the DefaultMeshSprite vertex shader (aPosition scaled by the instance's |
| 633 |
spriteSize through modelMatrix and the projection; aTexCoords mapped through texRect) and |
| 634 |
issues one general clip-space [x, y, u, v] draw per instance run (batched draws carry a |
| 635 |
per-vertex aMeshIndex; a run is a maximal span of one index, so each run keeps its own |
| 636 |
instance color / texRect / constant varyings). |
| 637 |
*/ |
| 638 |
void DispatchMeshVerticesImpl(PrimitiveType primitive, std::int32_t firstVertex, std::int32_t numVertices, |
| 639 |
const SwGeneratedShaderInfo& generatedShader, SwShaderProgram* program, const float* pv, |
| 640 |
const std::uint8_t* blockData, std::uint32_t blockDataSize, std::uint32_t instanceStride, |
| 641 |
std::int32_t uTextureUnit, const SwTexture* const* boundTextures, |
| 642 |
bool blendOn, SwBlendFactor bsrc, SwBlendFactor bdst, bool scissorEnabled, const Recti& scissorRect) |
| 643 |
{ |
| 644 |
SwVertexFormat::Attribute* posAttr = program->GetAttribute("aPosition"); |
| 645 |
SwVertexFormat::Attribute* texAttr = program->GetAttribute("aTexCoords"); |
| 646 |
SwVertexFormat::Attribute* idxAttr = program->GetAttribute("aMeshIndex"); |
| 647 |
if (texAttr != nullptr && (!texAttr->IsEnabled() || texAttr->GetVbo() != posAttr->GetVbo())) { |
| 648 |
texAttr = nullptr; |
| 649 |
} |
| 650 |
if (idxAttr != nullptr && (!idxAttr->IsEnabled() || idxAttr->GetVbo() != posAttr->GetVbo())) { |
| 651 |
idxAttr = nullptr; |
| 652 |
} |
| 653 |
|
| 654 |
const SwBuffer* vbo = posAttr->GetVbo(); |
| 655 |
const std::uint8_t* vboData = vbo->HostData(); |
| 656 |
std::int32_t stride = posAttr->GetStride(); |
| 657 |
if (stride <= 0) { |
| 658 |
stride = std::int32_t((2 + (texAttr != nullptr ? 2 : 0) + (idxAttr != nullptr ? 1 : 0)) * sizeof(float)); |
| 659 |
} |
| 660 |
const std::size_t posOff = std::size_t(posAttr->GetBaseOffset()) + reinterpret_cast<std::uintptr_t>(posAttr->GetPointer()); |
| 661 |
const std::size_t texOff = (texAttr != nullptr ? std::size_t(texAttr->GetBaseOffset()) + reinterpret_cast<std::uintptr_t>(texAttr->GetPointer()) : 0); |
| 662 |
const std::size_t idxOff = (idxAttr != nullptr ? std::size_t(idxAttr->GetBaseOffset()) + reinterpret_cast<std::uintptr_t>(idxAttr->GetPointer()) : 0); |
| 663 |
|
| 664 |
// The whole vertex range must be inside the buffer store (the offsets address into each vertex) |
| 665 |
std::size_t maxAttrEnd = posOff + 2 * sizeof(float); |
| 666 |
if (texAttr != nullptr) { |
| 667 |
maxAttrEnd = std::max(maxAttrEnd, texOff + 2 * sizeof(float)); |
| 668 |
} |
| 669 |
if (idxAttr != nullptr) { |
| 670 |
maxAttrEnd = std::max(maxAttrEnd, idxOff + sizeof(std::int32_t)); |
| 671 |
} |
| 672 |
if (vboData == nullptr || firstVertex < 0 || |
| 673 |
(std::size_t(firstVertex) + std::size_t(numVertices) - 1) * std::size_t(stride) + maxAttrEnd > vbo->GetSize()) { |
| 674 |
LOGW("Skipped draw: Vertex range exceeds the bound vertex buffer"); |
| 675 |
return; |
| 676 |
} |
| 677 |
|
| 678 |
// The no-texture mesh variants drop texRect from the instance block, which moves spriteSize up |
| 679 |
const bool hasTexRect = (texAttr != nullptr); |
| 680 |
const std::uint32_t spriteSizeOffset = (hasTexRect ? kSpriteSizeOffset : kSpriteSizeNoTexOffset); |
| 681 |
|
| 682 |
const std::uint32_t uniformsSize = generatedShader.uniformsSize; |
| 683 |
std::uint8_t uniformScratch[MaxFragmentShaderUserDataSize]; |
| 684 |
// Reused per run; safe because both the immediate rasterizer and the tile renderer's submit |
| 685 |
// (which snapshots the vertices into the deferred command) consume it before Draw() returns |
| 686 |
static std::vector<float> vertexScratch; |
| 687 |
|
| 688 |
auto vertexBytes = [&](std::int32_t index) { |
| 689 |
return vboData + (std::size_t(firstVertex) + std::size_t(index)) * std::size_t(stride); |
| 690 |
}; |
| 691 |
auto meshIndexAt = [&](std::int32_t index) -> std::int32_t { |
| 692 |
std::int32_t value; |
| 693 |
std::memcpy(&value, vertexBytes(index) + idxOff, sizeof(value)); |
| 694 |
return (value >= 0 ? value : 0); |
| 695 |
}; |
| 696 |
|
| 697 |
std::int32_t runBegin = 0; |
| 698 |
while (runBegin < numVertices) { |
| 699 |
const std::int32_t meshIndex = (idxAttr != nullptr ? meshIndexAt(runBegin) : 0); |
| 700 |
std::int32_t runEnd = (idxAttr != nullptr ? runBegin + 1 : numVertices); |
| 701 |
while (idxAttr != nullptr && runEnd < numVertices && meshIndexAt(runEnd) == meshIndex) { |
| 702 |
runEnd++; |
| 703 |
} |
| 704 |
const std::int32_t runCount = runEnd - runBegin; |
| 705 |
|
| 706 |
const std::size_t instOffset = std::size_t(meshIndex) * instanceStride; |
| 707 |
if (blockDataSize != 0 && instOffset + spriteSizeOffset + 2 * sizeof(float) > blockDataSize) { |
| 708 |
runBegin = runEnd; |
| 709 |
continue; // Malformed mesh index - skip the run rather than read past the bound block |
| 710 |
} |
| 711 |
const std::uint8_t* inst = blockData + instOffset; |
| 712 |
|
| 713 |
float mvp[16]; |
| 714 |
Mat4Mul(pv, reinterpret_cast<const float*>(inst + kModelMatrixOffset), mvp); |
| 715 |
const float* spriteSize = reinterpret_cast<const float*>(inst + spriteSizeOffset); |
| 716 |
const float* texRect = (hasTexRect ? reinterpret_cast<const float*>(inst + kTexRectOffset) : nullptr); |
| 717 |
|
| 718 |
vertexScratch.resize(std::size_t(runCount) * 4); |
| 719 |
float* out = vertexScratch.data(); |
| 720 |
for (std::int32_t i = runBegin; i < runEnd; i++, out += 4) { |
| 721 |
float pos[2]; |
| 722 |
std::memcpy(pos, vertexBytes(i) + posOff, sizeof(pos)); |
| 723 |
const float wx = pos[0] * spriteSize[0]; |
| 724 |
const float wy = pos[1] * spriteSize[1]; |
| 725 |
float cx = mvp[0] * wx + mvp[4] * wy + mvp[12]; |
| 726 |
float cy = mvp[1] * wx + mvp[5] * wy + mvp[13]; |
| 727 |
const float cw = mvp[3] * wx + mvp[7] * wy + mvp[15]; |
| 728 |
if (cw != 0.0f && cw != 1.0f) { |
| 729 |
// The 2D pipeline's projections keep w == 1; divide only when one does not |
| 730 |
cx /= cw; |
| 731 |
cy /= cw; |
| 732 |
} |
| 733 |
out[0] = cx; |
| 734 |
out[1] = cy; |
| 735 |
if (texRect != nullptr) { |
| 736 |
float tex[2]; |
| 737 |
std::memcpy(tex, vertexBytes(i) + texOff, sizeof(tex)); |
| 738 |
out[2] = tex[0] * texRect[0] + texRect[1]; |
| 739 |
out[3] = tex[1] * texRect[2] + texRect[3]; |
| 740 |
} else { |
| 741 |
out[2] = 0.0f; |
| 742 |
out[3] = 0.0f; |
| 743 |
} |
| 744 |
} |
| 745 |
|
| 746 |
DrawContext ctx; |
| 747 |
for (std::uint32_t u = 0; u < MaxTextureUnits; u++) { |
| 748 |
ctx.textures[u] = boundTextures[u]; |
| 749 |
} |
| 750 |
std::memcpy(ctx.ff.color, inst + kColorOffset, sizeof(ctx.ff.color)); |
| 751 |
ctx.ff.hasTexture = hasTexRect; |
| 752 |
ctx.ff.textureUnit = uTextureUnit; |
| 753 |
|
| 754 |
// Populate the generated fragment's uniforms + this instance's constant varyings, exactly |
| 755 |
// like the procedural-quad generated path |
| 756 |
if (uniformsSize > 0) { |
| 757 |
std::memset(uniformScratch, 0, uniformsSize); |
| 758 |
} |
| 759 |
for (std::uint32_t fi = 0; fi < generatedShader.uniformFieldCount; fi++) { |
| 760 |
const SwGeneratedUniformField& field = generatedShader.uniformFields[fi]; |
| 761 |
const std::uint8_t* v = program->ResolveUniform(field.name); |
| 762 |
if (v != nullptr && field.offset + field.componentCount * sizeof(float) <= uniformsSize) { |
| 763 |
std::memcpy(uniformScratch + field.offset, v, field.componentCount * sizeof(float)); |
| 764 |
} |
| 765 |
} |
| 766 |
if (generatedShader.computeVaryings != nullptr) { |
| 767 |
generatedShader.computeVaryings(uniformScratch, inst); |
| 768 |
} |
| 769 |
ctx.fragmentShader = generatedShader.fragment; |
| 770 |
ctx.fragmentShaderUserData = uniformScratch; |
| 771 |
ctx.fragmentShaderUserDataSize = uniformsSize; |
| 772 |
ctx.blendingEnabled = blendOn; |
| 773 |
ctx.blendSrc = bsrc; |
| 774 |
ctx.blendDst = bdst; |
| 775 |
ctx.scissorEnabled = scissorEnabled; |
| 776 |
ctx.scissorRect = scissorRect; |
| 777 |
ctx.vertexData = vertexScratch.data(); |
| 778 |
ctx.vertexStride = 4 * sizeof(float); |
| 779 |
SwRaster::SetDrawContext(ctx); |
| 780 |
SwRaster::Draw(primitive, 0, runCount); |
| 781 |
|
| 782 |
runBegin = runEnd; |
| 783 |
} |
| 784 |
} |
| 785 |
} |
| 786 |
|
| 787 |
void SwDevice::Dispatch(PrimitiveType primitive, std::int32_t firstVertex, std::int32_t numVertices) |
| 788 |
{ |
| 789 |
if (_currentProgram == nullptr || numVertices <= 0) { |
| 790 |
return; |
| 791 |
} |
| 792 |
|
| 793 |
const SwEffect effect = _currentProgram->GetEffect(); |
| 794 |
|
| 795 |
// The viewport compositor. The software backend renders the scene straight to the screen buffer and has no |
| 796 |
// shader post-processing, so a Combine draw does not run a fragment: it triggers the CPU dynamic-lighting |
| 797 |
// combine the compositor queued for this viewport (SetPendingSoftwareLighting), applied in place over the |
| 798 |
// screen buffer. Combine is only ever the compositor, so every Combine draw is intercepted here. |
| 799 |
if (effect == SwEffect::Combine) { |
| 800 |
ApplyPendingSoftwareLighting(); |
| 801 |
return; |
| 802 |
} |
| 803 |
|
| 804 |
// Resolve the offline-transpiled generated fragment for this program (looked up by object label = the |
| 805 |
// shader name; FindGeneratedShader also resolves the labels that bake a variant into the name, such as |
| 806 |
// the "...Dither" ones). An Unknown-effect program requires one, else the draw is skipped as before. |
| 807 |
// TexturedBackground(+Circle) and PaletteRemap(+Batched) are dispatched entirely through this generated |
| 808 |
// fragment. DefaultSprite / DefaultBatchedSprites keep their dedicated no-fragment fast path and never |
| 809 |
// look one up. |
| 810 |
const bool prefersGenerated = (effect == SwEffect::Unknown || |
| 811 |
effect == SwEffect::TexturedBackground || effect == SwEffect::TexturedBackgroundCircle || |
| 812 |
effect == SwEffect::PaletteRemap || effect == SwEffect::BatchedPaletteRemap); |
| 813 |
const SwGeneratedShaderInfo* generatedShader = nullptr; |
| 814 |
if (prefersGenerated) { |
| 815 |
generatedShader = FindGeneratedShader(_currentProgram->GetObjectLabel()); |
| 816 |
if (generatedShader == nullptr) { |
| 817 |
// The engine registers the nCine default programs under labels without the shader file's |
| 818 |
// "Default" prefix (e.g. "MeshSprite" for DefaultMeshSprite.shader, "BatchedMeshSprites" |
| 819 |
// for DefaultBatchedMeshSprites.shader); retry prefixed so the mesh family resolves its |
| 820 |
// transpiled fragment. Sprite-family labels never get here (they classify to a fast path). |
| 821 |
const char* label = _currentProgram->GetObjectLabel(); |
| 822 |
if (label != nullptr && label[0] != '\0') { |
| 823 |
std::string prefixed = "Default"; |
| 824 |
prefixed += label; |
| 825 |
generatedShader = FindGeneratedShader(prefixed.c_str()); |
| 826 |
} |
| 827 |
} |
| 828 |
if (generatedShader == nullptr && effect == SwEffect::Unknown) { |
| 829 |
// Expected for shaders the offline transpiler declined - their visuals are simply absent on |
| 830 |
// the software backend. Warn once per program, not per draw. |
| 831 |
static std::vector<std::string> warnedLabels; |
| 832 |
const char* label = _currentProgram->GetObjectLabel(); |
| 833 |
const std::string labelStr = (label != nullptr ? label : "<unlabeled>"); |
| 834 |
if (std::find(warnedLabels.begin(), warnedLabels.end(), labelStr) == warnedLabels.end()) { |
| 835 |
warnedLabels.push_back(labelStr); |
| 836 |
LOGW("Skipping draws of program \"{}\": No transpiled C++ fragment", StringView(labelStr)); |
| 837 |
} |
| 838 |
return; |
| 839 |
} |
| 840 |
} |
| 841 |
|
| 842 |
Framebuffer fb; |
| 843 |
if (!ResolveFramebuffer(fb)) { |
| 844 |
LOGW("Skipped draw: No render target bound"); |
| 845 |
return; |
| 846 |
} |
| 847 |
|
| 848 |
// A render target's color texture is stored bottom-up (OpenGL framebuffer convention); the screen |
| 849 |
// back-buffer is top-down. The engine derives every store's orientation - and the matching sample |
| 850 |
// alignment - from this one flag, so the effects never need a manual Y-flip. |
| 851 |
const bool isFboTarget = (_currentRenderTarget != nullptr); |
| 852 |
|
| 853 |
const Recti viewport = (_viewport.W > 0 && _viewport.H > 0) ? _viewport : Recti(0, 0, fb.width, fb.height); |
| 854 |
|
| 855 |
const std::uint8_t* projBytes = _currentProgram->ResolveUniform("uProjectionMatrix"); |
| 856 |
const std::uint8_t* viewBytes = _currentProgram->ResolveUniform("uViewMatrix"); |
| 857 |
const float* projMat = (projBytes != nullptr ? reinterpret_cast<const float*>(projBytes) : IdentityMatrix); |
| 858 |
const float* viewMat = (viewBytes != nullptr ? reinterpret_cast<const float*>(viewBytes) : IdentityMatrix); |
| 859 |
|
| 860 |
const SwUniformBlock* block = _currentProgram->FindBlock("InstanceBlock"); |
| 861 |
if (block == nullptr) { |
| 862 |
block = _currentProgram->FindBlock("InstancesBlock"); |
| 863 |
} |
| 864 |
if (block == nullptr) { |
| 865 |
LOGW("Skipped draw: Program has no instance block"); |
| 866 |
return; |
| 867 |
} |
| 868 |
std::int32_t binding = block->GetBindingIndex(); |
| 869 |
if (binding < 0 || std::uint32_t(binding) >= MaxUniformBindings) { |
| 870 |
binding = 0; |
| 871 |
} |
| 872 |
const std::uint8_t* blockData = _boundUniformRanges[binding].Data; |
| 873 |
if (blockData == nullptr) { |
| 874 |
LOGW("Skipped draw: No uniform block data bound"); |
| 875 |
return; |
| 876 |
} |
| 877 |
|
| 878 |
// Sampler texture units and the batched instance stride come from the offline reflection |
| 879 |
const ShaderCompiler::ProgramVariant* reflection = _currentProgram->GetReflection(); |
| 880 |
auto samplerUnit = [reflection](const char* name, std::int32_t def) -> std::int32_t { |
| 881 |
if (reflection != nullptr) { |
| 882 |
for (std::size_t i = 0; i < reflection->TextureCount; i++) { |
| 883 |
if (std::strcmp(reflection->Textures[i].Name, name) == 0) { |
| 884 |
return (reflection->Textures[i].Unit >= 0 ? reflection->Textures[i].Unit : def); |
| 885 |
} |
| 886 |
} |
| 887 |
} |
| 888 |
return def; |
| 889 |
}; |
| 890 |
std::uint32_t instanceStride = 0; |
| 891 |
if (reflection != nullptr) { |
| 892 |
for (std::size_t i = 0; i < reflection->BlockCount; i++) { |
| 893 |
if (reflection->Blocks[i].InstanceStride > 0) { |
| 894 |
instanceStride = reflection->Blocks[i].InstanceStride; |
| 895 |
break; |
| 896 |
} |
| 897 |
} |
| 898 |
} |
| 899 |
|
| 900 |
// Reads a committed loose uniform (or fills a default when it was never set) |
| 901 |
auto readUniform = [](const char* name, float* dst, int count, float def) { |
| 902 |
const std::uint8_t* p = _currentProgram->ResolveUniform(name); |
| 903 |
if (p != nullptr) { |
| 904 |
const float* f = reinterpret_cast<const float*>(p); |
| 905 |
for (int i = 0; i < count; i++) { dst[i] = f[i]; } |
| 906 |
} else { |
| 907 |
for (int i = 0; i < count; i++) { dst[i] = def; } |
| 908 |
} |
| 909 |
}; |
| 910 |
|
| 911 |
float pv[16]; |
| 912 |
Mat4Mul(projMat, viewMat, pv); |
| 913 |
|
| 914 |
// Persistent rasterizer state for every quad this draw issues |
| 915 |
SwRaster::SetColorBuffer(fb.pixels, fb.width, fb.height, isFboTarget); |
| 916 |
SwRaster::SetViewport(viewport.X, viewport.Y, viewport.W, viewport.H); |
| 917 |
// nCine hands scissor rectangles in bottom-up (OpenGL) window coordinates; the engine flips them |
| 918 |
SwRaster::SetScissor(_scissor.Enabled, _scissor.Rect.X, _scissor.Rect.Y, _scissor.Rect.W, _scissor.Rect.H); |
| 919 |
|
| 920 |
SwBlendFactor bsrc = SwBlendFactor::One, bdst = SwBlendFactor::Zero; |
| 921 |
bool blendOn = _blending.Enabled; |
| 922 |
if (blendOn) { |
| 923 |
bsrc = MapBlend(static_cast<BlendingFactor>(static_cast<std::uint32_t>(_blending.SrcRgb))); |
| 924 |
bdst = MapBlend(static_cast<BlendingFactor>(static_cast<std::uint32_t>(_blending.DstRgb))); |
| 925 |
} |
| 926 |
|
| 927 |
// Fills a draw context from one instance's fixed-function state and hands it to the engine as a |
| 928 |
// procedural sprite quad (vertexData stays null, so FetchVertex synthesizes the four corners from ff). |
| 929 |
// userDataSize is the byte size of the block userData points at, so the tile renderer can snapshot it |
| 930 |
// when the draw is deferred (its storage is caller-stack memory); pass 0 when there is no callback. |
| 931 |
auto drawQuad = [&](const FFState& ff, FragmentShaderFn fragmentShader, void* userData, std::uint32_t userDataSize) { |
| 932 |
DrawContext ctx; |
| 933 |
for (std::uint32_t u = 0; u < MaxTextureUnits; u++) { |
| 934 |
ctx.textures[u] = _boundTextures[u]; |
| 935 |
} |
| 936 |
ctx.ff = ff; |
| 937 |
ctx.fragmentShader = fragmentShader; |
| 938 |
ctx.fragmentShaderUserData = userData; |
| 939 |
ctx.fragmentShaderUserDataSize = userDataSize; |
| 940 |
// PaletteRemap(+Batched) draws qualify for the tile renderer's palette-LUT fast path (the |
| 941 |
// classified effect guarantees the fragment is the transpiled PaletteRemap one, whose parameter |
| 942 |
// block is a single vPaletteOffset float); the remaining constraints are validated at build time |
| 943 |
ctx.paletteRemapHint = ((effect == SwEffect::PaletteRemap || effect == SwEffect::BatchedPaletteRemap) && |
| 944 |
fragmentShader != nullptr && userData != nullptr); |
| 945 |
// The no-texture sprite family's fragment is packColor(vColor) - a per-draw constant - so the |
| 946 |
// tile renderer may evaluate it once and run its constant-color fill/blend scanline path |
| 947 |
ctx.constantColorHint = ((effect == SwEffect::DefaultSpriteNoTexture || effect == SwEffect::DefaultBatchedSpritesNoTexture) && |
| 948 |
fragmentShader != nullptr); |
| 949 |
ctx.blendingEnabled = blendOn; |
| 950 |
ctx.blendSrc = bsrc; |
| 951 |
ctx.blendDst = bdst; |
| 952 |
ctx.scissorEnabled = _scissor.Enabled; |
| 953 |
ctx.scissorRect = _scissor.Rect; |
| 954 |
SwRaster::SetDrawContext(ctx); |
| 955 |
SwRaster::Draw(PrimitiveType::TriangleStrip, 0, 4); |
| 956 |
}; |
| 957 |
|
| 958 |
// A generated shader is batched when its instance block carries a BATCH_SIZE-sized array (instanceStride > 0) |
| 959 |
const bool batched = (effect == SwEffect::DefaultBatchedSprites || effect == SwEffect::DefaultBatchedSpritesNoTexture || |
| 960 |
effect == SwEffect::BatchedPaletteRemap || |
| 961 |
(generatedShader != nullptr && instanceStride > 0)); |
| 962 |
std::int32_t numInstances = 1; |
| 963 |
if (batched) { |
| 964 |
numInstances = numVertices / 6; |
| 965 |
if (numInstances < 1) { |
| 966 |
numInstances = 1; |
| 967 |
} |
| 968 |
} |
| 969 |
|
| 970 |
// Offline-transpiled generated fragment path. Reached for Unknown-effect programs and for the |
| 971 |
// Combine / TexturedBackground(+Circle) / PaletteRemap(+Batched) effects, which are dispatched entirely |
| 972 |
// here (the switch below only keeps the DefaultSprite / DefaultBatchedSprites fast path). Handles |
| 973 |
// batched and non-batched draws and fills any per-instance-constant varyings via the generated |
| 974 |
// computeVaryings hook. |
| 975 |
if (generatedShader != nullptr) { |
| 976 |
const std::uint32_t uniformsSize = generatedShader->uniformsSize; |
| 977 |
if (uniformsSize > MaxFragmentShaderUserDataSize) { |
| 978 |
LOGW("Skipped draw: Generated shader uniform block exceeds the callback storage"); |
| 979 |
SwRaster::ClearDrawContext(); |
| 980 |
return; |
| 981 |
} |
| 982 |
|
| 983 |
// General vertex-fed path (the MeshSprite family). Programs with real vertex attributes read |
| 984 |
// their geometry from the bound vertex buffer instead of synthesizing a procedural quad: each |
| 985 |
// vertex is transformed on the CPU exactly like the DefaultMeshSprite vertex shader (aPosition |
| 986 |
// scaled by the instance's spriteSize through modelMatrix and the projection, aTexCoords mapped |
| 987 |
// through texRect) and handed to the rasterizer as interleaved clip-space [x, y, u, v]. A |
| 988 |
// batched draw (aMeshIndex attribute) is split at instance boundaries so every run keeps its |
| 989 |
// own instance color / texRect / constant varyings; the stitching vertices the batcher |
| 990 |
// duplicates between meshes only ever form degenerate (zero-area) triangles inside a run. |
| 991 |
// In-game consumers: the HUD weapon wheel (LineStrip) and the multiplayer minimap ribbons |
| 992 |
// (TriangleStrip); plain quad sprites never have attributes, so they never take this path. |
| 993 |
SwVertexFormat::Attribute* posAttr = _currentProgram->GetAttribute("aPosition"); |
| 994 |
if (posAttr != nullptr && posAttr->IsEnabled() && posAttr->GetVbo() != nullptr) { |
| 995 |
DispatchMeshVerticesImpl(primitive, firstVertex, numVertices, *generatedShader, |
| 996 |
_currentProgram, pv, blockData, _boundUniformRanges[binding].Size, instanceStride, |
| 997 |
samplerUnit("uTexture", 0), _boundTextures, blendOn, bsrc, bdst, |
| 998 |
_scissor.Enabled, _scissor.Rect); |
| 999 |
SwRaster::ClearDrawContext(); |
| 1000 |
return; |
| 1001 |
} |
| 1002 |
|
| 1003 |
// The generated fragment reads the sprite's instance state (and any constant varying) at the fixed |
| 1004 |
// sprite-family std140 offsets (through kPaletteOffsetOffset). Guard against a program whose instance |
| 1005 |
// block does not follow that layout, so the reads below never run past the bound block. |
| 1006 |
const std::uint32_t blockDataSize = _boundUniformRanges[binding].Size; |
| 1007 |
const std::size_t maxByte = std::size_t(numInstances > 0 ? numInstances - 1 : 0) * instanceStride + |
| 1008 |
(kPaletteOffsetOffset + sizeof(float)); |
| 1009 |
if (blockDataSize != 0 && maxByte > blockDataSize) { |
| 1010 |
LOGW("Skipped draw: Generated shader instance block is not sprite-compatible"); |
| 1011 |
SwRaster::ClearDrawContext(); |
| 1012 |
return; |
| 1013 |
} |
| 1014 |
|
| 1015 |
const std::int32_t uTextureUnit = samplerUnit("uTexture", 0); |
| 1016 |
|
| 1017 |
// The shield fragments' SOFTWARE_RENDERER variant reconstructs the GL path's interpolated |
| 1018 |
// quad-local position from the interpolated texcoord, so those draws are fed an IDENTITY |
| 1019 |
// texRect (u = corner.x, v = corner.y in [0,1]) instead of the instance texRect - for the |
| 1020 |
// shield effects that field carries the animated shift values, not texture coordinates, and |
| 1021 |
// it reaches the fragment separately through the vShieldRect constant varying computed by |
| 1022 |
// computeVaryings from the untouched instance block (see Include/ShieldVs.inc). |
| 1023 |
const bool quadLocalUV = (std::strstr(generatedShader->name, "Shield") != nullptr); |
| 1024 |
|
| 1025 |
std::uint8_t uniformScratch[MaxFragmentShaderUserDataSize]; |
| 1026 |
for (std::int32_t k = 0; k < numInstances; k++) { |
| 1027 |
const std::uint8_t* inst = blockData + std::size_t(k) * instanceStride; |
| 1028 |
FFState ff; |
| 1029 |
Mat4Mul(pv, reinterpret_cast<const float*>(inst + kModelMatrixOffset), ff.mvpMatrix); |
| 1030 |
std::memcpy(ff.color, inst + kColorOffset, sizeof(ff.color)); |
| 1031 |
std::memcpy(ff.texRect, inst + kTexRectOffset, sizeof(ff.texRect)); |
| 1032 |
std::memcpy(ff.spriteSize, inst + kSpriteSizeOffset, sizeof(ff.spriteSize)); |
| 1033 |
if (quadLocalUV) { |
| 1034 |
ff.texRect[0] = 1.0f; |
| 1035 |
ff.texRect[1] = 0.0f; |
| 1036 |
ff.texRect[2] = 1.0f; |
| 1037 |
ff.texRect[3] = 0.0f; |
| 1038 |
} |
| 1039 |
ff.hasTexture = true; |
| 1040 |
ff.textureUnit = uTextureUnit; |
| 1041 |
|
| 1042 |
// Populate the shader's "<Program>_Uniforms" struct generically: zero it, then copy each |
| 1043 |
// committed loose uniform to its offset (a uniform that was never set stays zero). |
| 1044 |
if (uniformsSize > 0) { |
| 1045 |
std::memset(uniformScratch, 0, uniformsSize); |
| 1046 |
} |
| 1047 |
for (std::uint32_t fi = 0; fi < generatedShader->uniformFieldCount; fi++) { |
| 1048 |
const SwGeneratedUniformField& field = generatedShader->uniformFields[fi]; |
| 1049 |
const std::uint8_t* v = _currentProgram->ResolveUniform(field.name); |
| 1050 |
if (v != nullptr && field.offset + field.componentCount * sizeof(float) <= uniformsSize) { |
| 1051 |
std::memcpy(uniformScratch + field.offset, v, field.componentCount * sizeof(float)); |
| 1052 |
} |
| 1053 |
} |
| 1054 |
// Fill any per-instance-constant varyings for THIS instance (after the loose uniforms, which a |
| 1055 |
// varying expression may reference). Reads the same instance block at baked std140 offsets. |
| 1056 |
if (generatedShader->computeVaryings != nullptr) { |
| 1057 |
generatedShader->computeVaryings(uniformScratch, inst); |
| 1058 |
} |
| 1059 |
drawQuad(ff, generatedShader->fragment, uniformScratch, uniformsSize); |
| 1060 |
} |
| 1061 |
SwRaster::ClearDrawContext(); |
| 1062 |
return; |
| 1063 |
} |
| 1064 |
|
| 1065 |
switch (effect) { |
| 1066 |
case SwEffect::DefaultSprite: |
| 1067 |
case SwEffect::DefaultBatchedSprites: { |
| 1068 |
// The rasterizer's gathers expand every stored texel (native R8/RG8 included) to the 4-byte |
| 1069 |
// working form, so the primary sample is always 4 bytes |
| 1070 |
const std::int32_t uTextureUnit = samplerUnit("uTexture", 0); |
| 1071 |
const SwTexture* texture = GetBoundTexture(std::uint32_t(uTextureUnit)); |
| 1072 |
if (texture == nullptr || texture->GetPixels() == nullptr) { |
| 1073 |
LOGW("Skipped draw: No texture bound to the sampler unit"); |
| 1074 |
break; |
| 1075 |
} |
| 1076 |
for (std::int32_t k = 0; k < numInstances; k++) { |
| 1077 |
const std::uint8_t* inst = blockData + std::size_t(k) * instanceStride; |
| 1078 |
FFState ff; |
| 1079 |
Mat4Mul(pv, reinterpret_cast<const float*>(inst + kModelMatrixOffset), ff.mvpMatrix); |
| 1080 |
std::memcpy(ff.color, inst + kColorOffset, sizeof(ff.color)); |
| 1081 |
std::memcpy(ff.texRect, inst + kTexRectOffset, sizeof(ff.texRect)); |
| 1082 |
std::memcpy(ff.spriteSize, inst + kSpriteSizeOffset, sizeof(ff.spriteSize)); |
| 1083 |
ff.hasTexture = true; |
| 1084 |
ff.textureUnit = uTextureUnit; |
| 1085 |
drawQuad(ff, nullptr, nullptr, 0); |
| 1086 |
} |
| 1087 |
break; |
| 1088 |
} |
| 1089 |
|
| 1090 |
case SwEffect::DefaultSpriteNoTexture: |
| 1091 |
case SwEffect::DefaultBatchedSpritesNoTexture: { |
| 1092 |
// Solid-colour sprite: no texture is bound (so there is no fast-blit) and the instance block |
| 1093 |
// omits texRect, which places spriteSize at offset 80 (not 96). Run the transpiled no-texture |
| 1094 |
// fragment (COLOR = vColor); it overwrites the pixel unconditionally, so an unbound sampler unit |
| 1095 |
// is handled safely. hasTexture stays false so the rasterizer never dereferences a null texture. |
| 1096 |
const FragmentShaderFn noTexFragment = (effect == SwEffect::DefaultBatchedSpritesNoTexture) |
| 1097 |
? &DefaultBatchedSpritesNoTexture_Fragment : &DefaultSpriteNoTexture_Fragment; |
| 1098 |
for (std::int32_t k = 0; k < numInstances; k++) { |
| 1099 |
const std::uint8_t* inst = blockData + std::size_t(k) * instanceStride; |
| 1100 |
FFState ff; |
| 1101 |
Mat4Mul(pv, reinterpret_cast<const float*>(inst + kModelMatrixOffset), ff.mvpMatrix); |
| 1102 |
std::memcpy(ff.color, inst + kColorOffset, sizeof(ff.color)); |
| 1103 |
std::memcpy(ff.spriteSize, inst + kSpriteSizeNoTexOffset, sizeof(ff.spriteSize)); |
| 1104 |
ff.hasTexture = false; |
| 1105 |
drawQuad(ff, noTexFragment, nullptr, 0); |
| 1106 |
} |
| 1107 |
break; |
| 1108 |
} |
| 1109 |
|
| 1110 |
default: |
| 1111 |
// Every other effect is dispatched through the generated fragment path above (an Unknown |
| 1112 |
// program that matched none already returned there). Nothing to do here. |
| 1113 |
break; |
| 1114 |
} |
| 1115 |
|
| 1116 |
SwRaster::ClearDrawContext(); |
| 1117 |
} |
| 1118 |
} |