Phosphor
Qt6 / Wayland library suite for window-management tools
Loading...
Searching...
No Matches
PhosphorShaders Namespace Reference

Namespaces

namespace  UboRegions
 UBO region offsets and sizes for partial updates (reduces GPU bandwidth).
namespace  CustomParams
 Canonical key format for the customParams[N].
namespace  CustomColors
 Canonical key format for the customColors[N] slots in BaseUniforms.
namespace  Bindings
 The ONE descriptor-binding layout every Qt-RHI shader family speaks (overlay, animation, surface, pointer) and the daemon's ShaderNodeRhi populates.

Classes

class  BaseUniformProfile
 IUboProfile implementation for the overlay/animation runtime — the legacy 672-byte BaseUniforms layout. More...
struct  BaseUniforms
 GPU uniform buffer layout following std140 rules (base region). More...
struct  UboUploadRegion
 A contiguous byte range inside the UBO to (re)upload via QRhiResourceUpdateBatch::updateDynamicBuffer. More...
class  UboUploadRegionList
 Fixed-capacity list of upload regions. More...
struct  UboDirtyFlags
 Which conceptual blocks of the UBO changed since the last upload. More...
struct  UboFrameState
 Snapshot of every node-side value a UBO profile's fill() may read for a single frame. More...
class  IUboProfile
 Pluggable UBO concern for the shared shader render engine. More...
class  IUniformExtension
 Interface for appending custom uniform data after the base UBO layout. More...
class  IWallpaperProvider
 Abstract wallpaper provider interface. More...
struct  EntryCandidate
 One candidate entry function the author may define, paired with the void main() the harness generates when that function is present and the source defines no main() of its own (T1.4). More...
class  ShaderIncludeResolver
 Resolves #include directives in GLSL shader source. More...
struct  PreambleParam
 One declared shader parameter, in metadata declaration order, as fed to buildParamPreamble. More...
struct  ShaderPreset
 One named parameter tuning for one shader pack. More...
class  ShaderPresetRegistry
 The one place a presetId on an assignment turns into parameters. More...
class  ShaderPresetStore
 One per consumer, holding every shader preset for every family it names. More...
class  ShaderRegistry
 Registry of available shader effects. More...

Typedefs

using PresetValueRange = QPair<QVariant, QVariant>
 A pack's declared numeric range for one parameter: { min, max }, either of which may be an invalid QVariant when the pack declares only one side.
using PresetValueBounds = QHash<QString, PresetValueRange>
 The declared ranges for a pack's parameters, by parameter id.
using PackPresets = QMap<QString, QVariantMap>
 Pack-declared named parameter presets: preset name → { paramId → value }.
using LiveReload = PhosphorFsLoader::LiveReload

Enumerations

enum class  ShaderStage { Vertex , Fragment }
 The pipeline stage a source is compiled for, as stripVaryingLocations needs to tell a varying from a vertex input or a fragment output. More...
enum class  ShaderFamily { Animation , Surface , Pointer , Overlay }
 Which shader family a preset belongs to. More...

Functions

bool isValidWrapToken (const QString &wrap)
 The accepted texture / buffer wrap vocabulary, shared by every validation site across the shader registries (overlay image-param parse, surface metadata parse, per-slot texture parse, and runtime override translation).
bool isValidFilterToken (const QString &filter)
 The accepted buffer filter vocabulary: linear / nearest / mipmap.
PHOSPHORSHADERS_EXPORT std::unique_ptr< IWallpaperProvider > createWallpaperProvider ()
 Create the default wallpaper provider for the current desktop environment.
QLatin1String pixelUnit ()
 The unit a parameter declares when its value is logical pixels of the real surface the shader draws on, which is the screen for a zone/overlay pack.
PHOSPHORSHADERS_EXPORT void scalePixelParams (const QVariantList &parameterInfos, QVariantMap &values, double factor)
 Scale every px-denominated parameter for a host that renders the shader on a surface smaller than the real thing.
PHOSPHORSHADERS_EXPORT bool definesMain (const QString &expandedSource)
 True if expandedSource defines void main() at top level.
PHOSPHORSHADERS_EXPORT bool definesFunction (const QString &expandedSource, const QString &functionName)
 True if expandedSource defines a function named functionName.
PHOSPHORSHADERS_EXPORT QString composeEntryPoint (const QString &expandedSource, const QList< EntryCandidate > &candidates)
 Compose the fragment entry point (T1.4).
PHOSPHORSHADERS_EXPORT QString assembleEntryPoint (const QString &raw, const QString &prologue, const QList< EntryCandidate > &candidates)
 Convenience wrapper for the full assembly: when candidates is empty or raw already defines main(), returns raw unchanged; otherwise returns composeEntryPoint(prologue + raw, candidates).
PHOSPHORSHADERS_EXPORT QString stripGlslComments (const QString &source)
 Strip GLSL line (//…) and block (/* … */) comments from source, preserving newlines inside block comments so line numbers are unchanged.
PHOSPHORSHADERS_EXPORT QString resolveWithinPack (const QDir &packDir, const QString &declaredName, PhosphorFsLoader::AbsolutePathPolicy policy, const QLoggingCategory &log)
 Resolve a pack-declared relative path against packDir, refusing anything that escapes the pack.
PHOSPHORSHADERS_EXPORT QString buildParamPreamble (const QList< PreambleParam > &params)
 Build the generated #define p_<id> <glsl-accessor> preamble for a shader's declared parameters.
PHOSPHORSHADERS_EXPORT bool isValidParamId (const QString &id)
 True if id is a valid GLSL identifier body ([A-Za-z0-9_], non-empty) — the p_ prefix supplies the leading character, so a leading digit is fine.
PHOSPHORSHADERS_EXPORT bool isReservedAnimationParamId (const QString &id)
 True if p_<id> would COLLIDE with a #define p_... a shared family header already owns.
PHOSPHORSHADERS_EXPORT QString spliceAfterVersion (const QString &source, const QString &block)
 Splice block into source immediately after its #version line, then emit a lineDirective re-anchoring source string 0 so the author's subsequent lines keep their original numbers despite the inserted block.
PHOSPHORSHADERS_EXPORT int versionDirectiveEnd (const QString &source)
 Locate the first REAL #version directive of source: the first line whose first non-whitespace token is #version outside any // or /* … */ comment, with a leading UTF-8 BOM (U+FEFF) skipped.
PHOSPHORSHADERS_EXPORT QString kwinDefineBlock (const QString &eol=QStringLiteral("\n"))
 The preprocessor block that selects the COMPOSITOR branch of a pack's source, newline-terminated with eol and ready for spliceAfterVersion.
PHOSPHORSHADERS_EXPORT QString stripVaryingLocations (const QString &source, ShaderStage stage)
 Remove the layout(location = N) qualifier from every varying of source: the out declarations of a vertex stage and the in declarations of a fragment stage.
PHOSPHORSHADERS_EXPORT QString kwinGlesDialect (const QString &source)
 source as KWin 6.8 hands it to the driver: every line that starts with #version blanked (its newline kept, so line numbers do not move), and KWin's GLSL ES 300 prologue (the version line, the GL_OES_EGL_image_external require and its default precision declarations) prepended.
PHOSPHORSHADERS_EXPORT QString kwinDesktopDialect (const QString &source)
 source as KWin 6.7 hands it to the driver on a desktop GL context: every line that starts with #version blanked (newline kept) and #version 140 prepended, with no precision or extension lines.
PHOSPHORSHADERS_EXPORT QString kwinTopDownTexcoordsDefine (const QString &eol=QStringLiteral("\n"))
 The #define KWin 6.8's per-window animation path and the decoration present shader splice beside kwinDefineBlock, telling a shader that the offscreen texture KWin hands an effect is top-down.
PHOSPHORSHADERS_EXPORT QString kwinCompositorSource (const QString &source, ShaderStage stage, const QString &extraDefines={}, bool *synthesizedVersion=nullptr)
 The compositor branch of source exactly as the effect hands it to KWin: kwinDefineBlock and extraDefines spliced after #version, then the varying locations of stage stripped.
PHOSPHORSHADERS_EXPORT QString lineDirective (int line, int sourceString, const QString &eol=QStringLiteral("\n"))
 A #line re-anchor that numbers the NEXT line line of source string sourceString under every GLSL dialect a shader here compiles in, terminated with eol.
PHOSPHORSHADERS_EXPORT QLatin1StringView shaderFamilyToken (ShaderFamily family)
 Wire token for family: "animation" / "surface" / "pointer" / "overlay".
template<typename ParameterList>
PresetValueBounds presetBoundsFrom (const ParameterList &parameters)
 Collect PresetValueBounds from any family's declared parameter list.
PHOSPHORSHADERS_EXPORT QVariantMap overlayPresetDeltas (const QVariantMap &base, const QVariantMap &deltas)
 Overlay deltas onto base and return the result — the one definition of how a preset and an assignment's own parameter edits combine.
PHOSPHORSHADERS_EXPORT PackPresets parsePackPresets (const QDir &packDir, const QSet< QString > &imageParamIds, const QJsonObject &root, const QLoggingCategory &log)
 Parse the presets object of a pack metadata root.
template<typename EffectList>
void seedPackPresets (ShaderPresetRegistry &registry, ShaderFamily family, const EffectList &effects)
 Seed registry with every pack-declared preset in effects, for family.
PHOSPHORSHADERS_EXPORT QString standardUserPresetRoot (const QString &subdirectory)
 The standard root for user-saved shader presets: <XDG_DATA_HOME>/<subdirectory>, where subdirectory is the app's preset directory relative to the user data dir, no leading slash (PlasmaZones passes plasmazones/shader-presets).
PHOSPHORSHADERS_EXPORT QString userPresetDirectory (const QString &root, ShaderFamily family)
 The directory holding family's user presets under root.
PHOSPHORSHADERS_EXPORT int migrateLegacyOverlayPresets (const QString &root)
 Import pre-existing overlay preset files into the family layout.

Variables

constexpr double kShaderTimeWrap = 1024.0
 Time wrap period for float32 precision preservation.
constexpr double kMinBufferScale = 0.0078125
 Lower / upper bounds on a multipass bufferScale (FBO downscale factor).
constexpr double kMaxBufferScale = 1.0
constexpr int kMaxBufferPasses = 8
 Maximum number of multipass buffer passes a pack may declare.
constexpr int kMaxImageSlots = 4
 Image-pool budget: overlay/zone image params bind to uTexture0..3.
constexpr std::size_t ShaderFamilyCount = 4
 How many families there are, for the one-slot-per-family arrays that index by static_cast<std::size_t>(family).

Typedef Documentation

◆ LiveReload

◆ PackPresets

using PhosphorShaders::PackPresets = QMap<QString, QVariantMap>

Pack-declared named parameter presets: preset name → { paramId → value }.

The same shape for every shader family. A preset names a subset of the pack's declared parameters; ids the pack does not declare are inert at resolve time, so parsing does not reject them (the offline pack validator is where an author hears about a typo).

◆ PresetValueBounds

The declared ranges for a pack's parameters, by parameter id.

Preset values are clamped to these before they reach a consumer. A pack's declared min/max used to be enforced only by the settings slider, so a hand-written preset file could put any number into a uniform — and at least six bundled overlay packs derive a GLSL loop bound from one (int octaves = int(p_octaves ...) feeding for (i < octaves)), which makes an out-of-range value a GPU stall rather than a cosmetic mistake.

◆ PresetValueRange

using PhosphorShaders::PresetValueRange = QPair<QVariant, QVariant>

A pack's declared numeric range for one parameter: { min, max }, either of which may be an invalid QVariant when the pack declares only one side.

Enumeration Type Documentation

◆ ShaderFamily

enum class PhosphorShaders::ShaderFamily
strong

Which shader family a preset belongs to.

The four families keep separate pack-id namespaces, so a preset is only ever offered for the family it was written against. The wire token doubles as the subdirectory name under the user preset root, which is what tells the loader which family a preset file belongs to — the file itself carries only its pack id, so moving one between family directories re-homes it.

Enumerator
Animation 
Surface 
Pointer 
Overlay 

◆ ShaderStage

enum class PhosphorShaders::ShaderStage
strong

The pipeline stage a source is compiled for, as stripVaryingLocations needs to tell a varying from a vertex input or a fragment output.

Enumerator
Vertex 
Fragment 

Function Documentation

◆ assembleEntryPoint()

PHOSPHORSHADERS_EXPORT QString PhosphorShaders::assembleEntryPoint ( const QString & raw,
const QString & prologue,
const QList< EntryCandidate > & candidates )

Convenience wrapper for the full assembly: when candidates is empty or raw already defines main(), returns raw unchanged; otherwise returns composeEntryPoint(prologue + raw, candidates).

When prologue carries the #version line, a lineDirective goes between the two, so a diagnostic names the author's own line rather than one counted from the top of the prologue. This is the single assembly entry point shared by the daemon bake layer and the kwin-effect path so both produce the identical pre-expansion source for an entry-only pack. Apply it to RAW (pre-expansion) source so the prologue's #include is then resolved. Entry-function detection therefore sees only the author's inline body — by convention the entry function (pZone/pImage/pTransition, or a hand-written main()) is authored directly, never pulled from an #include — which is why this wraps RAW rather than the expanded source composeEntryPoint expects.

◆ buildParamPreamble()

PHOSPHORSHADERS_EXPORT QString PhosphorShaders::buildParamPreamble ( const QList< PreambleParam > & params)

Build the generated #define p_<id> <glsl-accessor> preamble for a shader's declared parameters.

Auto-numbers each pool independently in declaration order for params whose explicitSlot < 0. Returns an empty string for an empty list. A param whose id isn't a valid GLSL identifier body, or whose resolved slot is out of range, is emitted as a // p: skipped ... comment rather than a broken #define, so the block always compiles.

The returned block is newline-terminated and contains no #version or #line directive — the caller splices it after the shader's #version line and is responsible for any #line fixup that restores author line numbers (see the include resolver's #line contract).

◆ composeEntryPoint()

PHOSPHORSHADERS_EXPORT QString PhosphorShaders::composeEntryPoint ( const QString & expandedSource,
const QList< EntryCandidate > & candidates )

Compose the fragment entry point (T1.4).

• If expandedSource already defines void main(), it is returned unchanged — the author keeps full control (the escape hatch every existing pack uses today). • Otherwise the first candidate whose functionName is defined has its generatedMain appended (separated by a newline) and the result returned. • If no main() and no candidate matches, expandedSource is returned unchanged; the compiler then surfaces the missing-main() error, which the offline validator (T1.2) maps back to the author's file via the resolver's #line legend.

Splice the T1.1 param preamble (spliceAfterVersion) AFTER this, or before — they don't overlap (the preamble sits just after #version; the wrapper is appended at the end), but compose on the include-expanded source so definesMain / definesFunction see any entry point arriving from an include.

◆ createWallpaperProvider()

PHOSPHORSHADERS_EXPORT std::unique_ptr< IWallpaperProvider > PhosphorShaders::createWallpaperProvider ( )

Create the default wallpaper provider for the current desktop environment.

Detects KDE, Hyprland, Sway, GNOME and returns the appropriate implementation. Returns a fallback provider (empty path) if no supported DE is detected.

◆ definesFunction()

PHOSPHORSHADERS_EXPORT bool PhosphorShaders::definesFunction ( const QString & expandedSource,
const QString & functionName )

True if expandedSource defines a function named functionName.

Matches a definition — <name> ( <params> ) { — not a call: the trailing { distinguishes vec4 pZone(ZoneCtx z) { … } from return pZone(z);. Comments are stripped first. functionName is matched as a whole word. Parameter lists spanning multiple lines are handled.

◆ definesMain()

PHOSPHORSHADERS_EXPORT bool PhosphorShaders::definesMain ( const QString & expandedSource)

True if expandedSource defines void main() at top level.

Comments are stripped first so a main inside a // or block comment never false-matches, and the match requires the (…) signature followed by { so a stray main identifier or a forward reference can't trip it. Run on the include-expanded source: a main() can legitimately arrive from an include, and the harness must treat that exactly like an inline one.

◆ isReservedAnimationParamId()

PHOSPHORSHADERS_EXPORT bool PhosphorShaders::isReservedAnimationParamId ( const QString & id)

True if p_<id> would COLLIDE with a #define p_... a shared family header already owns.

isValidParamId checks only the character set, so an id like reversed is a perfectly legal identifier that buildParamPreamble will happily turn into #define p_reversed <slot> — while plasmazones/data/animations/shared/animation_uniforms.glsl already carries #define p_reversed (iIsReversed == 1). Redefining a macro with a different replacement list is an error in GLSL, so such a pack fails to compile with the diagnostic pointing at the SHARED HEADER rather than at the pack's own metadata, which is the wrong place to send an author.

The reservation is per family, because a header only reserves a name for the packs that include it. Only the animation family reserves anything today; the list lives here, beside the generator that creates the clash, so a family that adds a #define p_... has one place to declare it.

◆ isValidFilterToken()

bool PhosphorShaders::isValidFilterToken ( const QString & filter)
inline

The accepted buffer filter vocabulary: linear / nearest / mipmap.

Same membership and empty-string contract as isValidWrapToken, and the same forwarders, each on its own contract header (SurfaceShaderContract, AnimationShaderContract, PointerShaderContract).

◆ isValidParamId()

PHOSPHORSHADERS_EXPORT bool PhosphorShaders::isValidParamId ( const QString & id)

True if id is a valid GLSL identifier body ([A-Za-z0-9_], non-empty) — the p_ prefix supplies the leading character, so a leading digit is fine.

Shared so the metadata parser's auto-slot assignment skips exactly the same params buildParamPreamble skips, keeping the two lane-numberings identical.

◆ isValidWrapToken()

bool PhosphorShaders::isValidWrapToken ( const QString & wrap)
inline

The accepted texture / buffer wrap vocabulary, shared by every validation site across the shader registries (overlay image-param parse, surface metadata parse, per-slot texture parse, and runtime override translation).

Returns true only for the three canonical tokens clamp / repeat / mirror. An empty string is NOT a member — callers treat empty as "use the runtime default" and handle it explicitly before consulting this predicate. Lives here (the lowest shader library) so the four families' validation cannot drift apart. All three of the other families forward to it, each from its own contract header: PhosphorSurfaceShaders::SurfaceShaderContract::isValidWrapToken, PhosphorAnimationShaders::AnimationShaderContract::isValidWrapToken and PhosphorPointerShaders::PointerShaderContract::isValidWrapToken. The overlay family and the pack validator call this one directly. Vocabulary matches the runtime normaliser (ShaderNodeRhi::normalizeWrapMode).

◆ kwinCompositorSource()

PHOSPHORSHADERS_EXPORT QString PhosphorShaders::kwinCompositorSource ( const QString & source,
ShaderStage stage,
const QString & extraDefines = {},
bool * synthesizedVersion = nullptr )

The compositor branch of source exactly as the effect hands it to KWin: kwinDefineBlock and extraDefines spliced after #version, then the varying locations of stage stripped.

A leading BOM is dropped. A source with no #version gets #version 450 synthesized in front of the block, with the author's first line re-anchored to line 1, and synthesizedVersion (when given) reports that so the caller can warn. extraDefines is re-terminated to the source's line-ending convention.

ONE function for every place that builds this source: the compositor's ShaderInternal::injectKwinDefineAfterVersion, the offline validator's compositor bake and the GPU bake tests. Each of them used to splice and strip by hand, which is how a gate ends up compiling something the compositor never runs.

◆ kwinDefineBlock()

PHOSPHORSHADERS_EXPORT QString PhosphorShaders::kwinDefineBlock ( const QString & eol = QStringLiteral("\n"))

The preprocessor block that selects the COMPOSITOR branch of a pack's source, newline-terminated with eol and ready for spliceAfterVersion.

#define PLASMAZONES_KWIN is the ABI switch itself: the shared uniform headers key their default-block-uniform branch off it.

KWin picks the dialect from the GL context, not from its own version. On a desktop GL context KWin 6.7 recompiles custom shaders as desktop GLSL 140, where the layout(location = N) qualifiers left on vertex inputs and fragment outputs need GL_ARB_explicit_attrib_location (NVIDIA error C7548). GL_ARB_separate_shader_objects stays enabled there as well. The qualifiers on varyings are gone by then (see stripVaryingLocations), so it only backs up a varying declaration the strip does not recognise, which 6.7 accepted before the strip existed. On a GLES 3 context, which is every context on KWin 6.8, KWin compiles GLSL ES 300, where the remaining qualifiers are built in and KWin's precision declarations come before this block. The desktop extensions are guarded with #ifndef GL_ES, because an #extension after those precision declarations is rejected by Mesa ("#extension directive is not allowed in the middle of a shader") and by NVIDIA (error C7621).

Shared because the compositor's injector (through kwinCompositorSource), the offline validator's compositor bake and the GPU bake tests must agree on it exactly, and they are in different link units. A private copy in any of them turns the checkers into gates that pass source the compositor would reject, or reject source it accepts — the exact failure a reproduce-the-runtime gate exists to rule out.

◆ kwinDesktopDialect()

PHOSPHORSHADERS_EXPORT QString PhosphorShaders::kwinDesktopDialect ( const QString & source)

source as KWin 6.7 hands it to the driver on a desktop GL context: every line that starts with #version blanked (newline kept) and #version 140 prepended, with no precision or extension lines.

The desktop counterpart of kwinGlesDialect, for the validator's desktop compositor arm. The runtime never calls it.

◆ kwinGlesDialect()

PHOSPHORSHADERS_EXPORT QString PhosphorShaders::kwinGlesDialect ( const QString & source)

source as KWin 6.8 hands it to the driver: every line that starts with #version blanked (its newline kept, so line numbers do not move), and KWin's GLSL ES 300 prologue (the version line, the GL_OES_EGL_image_external require and its default precision declarations) prepended.

A copy of what KWin::GLShader::preprocess does at the top level on a GLES 3 context, for the gates that compile the compositor branch offline: the validator's GLES arm and the GPU bake tests. The runtime never calls it, since KWin applies the real rewrite itself.

◆ kwinTopDownTexcoordsDefine()

PHOSPHORSHADERS_EXPORT QString PhosphorShaders::kwinTopDownTexcoordsDefine ( const QString & eol = QStringLiteral("\n"))

The #define KWin 6.8's per-window animation path and the decoration present shader splice beside kwinDefineBlock, telling a shader that the offscreen texture KWin hands an effect is top-down.

KWin 6.8 changed that orientation, so the runtime adds it exactly when the effect is built against 6.8. Shared so the effect, the validator's GLES arm (which models 6.8) and the GPU bake tests spell it once. Newline-terminated with eol.

◆ lineDirective()

PHOSPHORSHADERS_EXPORT QString PhosphorShaders::lineDirective ( int line,
int sourceString,
const QString & eol = QStringLiteral("\n") )

A #line re-anchor that numbers the NEXT line line of source string sourceString under every GLSL dialect a shader here compiles in, terminated with eol.

GLSL changed the directive's meaning: before desktop GLSL 330, #line N numbered the line after it N+1, and from 330 on it numbers it N. Every GLSL ES version numbers it N, 1.00 included, which is how glslang and Mesa read the ES specs. KWin 6.7 compiles the compositor branch as desktop GLSL 140, so a plain #line N put every compile-log line there one past the real fault. The directive therefore takes its number from a macro defined per dialect under __VERSION__. A macro and not an expression, because Mesa's preprocessor accepts only an integer after #line once macros are expanded. The macro name carries both numbers, so two re-anchors to the same place define it identically, which GLSL allows.

Used by spliceAfterVersion, by assembleEntryPoint after a family prologue, and by the include resolver, which also honours a re-anchor of this shape that its input already carries.

◆ migrateLegacyOverlayPresets()

PHOSPHORSHADERS_EXPORT int PhosphorShaders::migrateLegacyOverlayPresets ( const QString & root)

Import pre-existing overlay preset files into the family layout.

Before presets became assignable, the zone shader browser saved them through a different path. This moves any it finds at root into <root>/overlay/<id>.json, deriving each id from the old filename so two processes racing the migration agree on the result rather than importing twice. Idempotent: a file it has already moved is not seen again, and each import clears the reference it applied.

Returns
the number of files imported.

◆ overlayPresetDeltas()

PHOSPHORSHADERS_EXPORT QVariantMap PhosphorShaders::overlayPresetDeltas ( const QVariantMap & base,
const QVariantMap & deltas )

Overlay deltas onto base and return the result — the one definition of how a preset and an assignment's own parameter edits combine.

Every consumer resolves through this, so "the preset supplies the value unless this assignment overrode it" means the same thing in the daemon, the compositor and the settings preview. A key present in deltas wins even when its value equals the preset's; sameness is not a reason to drop an explicit override, because the preset may change later and the user's choice must not silently start following it.

◆ parsePackPresets()

PHOSPHORSHADERS_EXPORT PackPresets PhosphorShaders::parsePackPresets ( const QDir & packDir,
const QSet< QString > & imageParamIds,
const QJsonObject & root,
const QLoggingCategory & log )

Parse the presets object of a pack metadata root.

imageParamIds names the pack's image-typed parameters, whose preset values are pack-declared PATHS rather than plain values. Only the overlay family has a SUPPORTED image parameter type, and the other three carry textures in a separate top-level list — but none of them passes a statically empty set here. All four derive this set from their declared parameter types, and type is read raw from a hand-editable metadata.json with no enum validation, so a pack writing "type": "image" under any family turns the path branch below on. That is why the branch is not a no-op anywhere and why the empty-pack-directory refusal in the implementation is a fail-closed guard rather than a formality.

Image-typed preset values must be containment-checked at PARSE time with the Reject policy, exactly like an image param's default. They cannot be trusted at translate time: a preset reaches translateParamsToUniforms through storedParams (the user picked the preset), so the provenance heuristic there (storedParams.contains(id) → Trust) would wave a pack-manufactured "tex": "/home/user/.ssh/id_rsa" straight through — the very escape the default path already closes. Gate it here, where the value's true (pack) provenance is known.

A refused image value is DROPPED from the preset, so that parameter falls back to its declared default rather than binding an arbitrary file.

An author-declared empty preset ("Default": {}) is KEPT: it legitimately means "this preset is the pack's declared defaults", and dropping it also hid it from the offline validator, which lints the parsed map. A preset left empty only because every one of its values was refused IS omitted, because it cannot do what it says. The implementation states that rule beside the test that distinguishes the two.

If a non-overlay family ever SUPPORTS an image parameter, read this first

Two things are correct today ONLY because no non-overlay family binds a preset image: the overlay family is the one whose loader honours the type, and the other three either refuse it (pointer) or reach this function with a pack directory the fail-closed guard rejects.

  • AnimationShaderEffect::toJson writes its preset map out verbatim, while fromJson re-parses every path under AbsolutePathPolicy::Reject. The values here are ABSOLUTE once resolved, so the round trip would silently drop them and fromJson(toJson(x)) != x.
  • PointerShaderRegistry::effectContentSignature does catch a preset being RETUNED, because a pack's presets live inside its metadata.json and the signature hashes that file. What it cannot catch is an edit to the image FILE a preset names: only DECLARED texture paths reach effectWatchPaths, so repainting a preset-declared texture neither re-registers nor reloads the pack.

Neither is reachable now, and neither is cheap to notice later: the first is a silent value loss and the second a stale pack. Handle both in the same change that widens the set, not afterwards.

◆ pixelUnit()

QLatin1String PhosphorShaders::pixelUnit ( )
inline

The unit a parameter declares when its value is logical pixels of the real surface the shader draws on, which is the screen for a zone/overlay pack.

Only zone/overlay pack metadata declares this: the surface schema has no unit field and nothing under libs/phosphor-surface reads one.

Every other parameter is unitless as far as the runtime is concerned: a strength, an angle, a count, a colour. Only px values have to be re-read when the surface is not its real size.

◆ presetBoundsFrom()

template<typename ParameterList>
PresetValueBounds PhosphorShaders::presetBoundsFrom ( const ParameterList & parameters)

Collect PresetValueBounds from any family's declared parameter list.

A template because the four families each have their own ParameterInfo type in their own library; all four carry id, minValue and maxValue, which is all this needs. Lets a caller seeding presets pass the bounds in the same breath without this library depending on four pack registries.

◆ resolveWithinPack()

PHOSPHORSHADERS_EXPORT QString PhosphorShaders::resolveWithinPack ( const QDir & packDir,
const QString & declaredName,
PhosphorFsLoader::AbsolutePathPolicy policy,
const QLoggingCategory & log )

Resolve a pack-declared relative path against packDir, refusing anything that escapes the pack.

This is the path-traversal guard for every file a shader pack names, not a preset concern. The whole registry routes through it: the fragment shader, the vertex shader, the implicit zone.vert fallback, every buffer-shader entry, every image parameter's default, and every image-typed preset value. It lived in ShaderPresetParse.h for a while, which put all pack path security behind a preset-shaped include where nobody would look for it, and put a future change to preset parsing in the same header as the check that keeps arbitrary files off the GPU. Its own header, so both are findable as what they are.

Delegates to PhosphorFsLoader::resolveWithinDirectory rather than hand-rolling a lexical check: a lexical-only check misses a symlink inside the pack pointing out of it, and mixing canonical with lexical fails open. Subdirectories INSIDE the pack stay legal ("shaders/effect.frag"), because containment is checked on the resolved canonical path rather than by refusing separators. A name that does not exist yet resolves lexically, so a pack referencing a file it does not ship is rejected later by the existence checks rather than here.

policy is REQUIRED here, deliberately — there is no default on this declaration, so every family has to state its own. Reject is right for everything a PACK FILE declares: a pack ships its own assets, so an absolute path can only be a mistake or an escape. Only a value the USER supplied at runtime (a file picker, D-Bus) may pass Trust.

Returns an empty string when the path is refused, and when declaredName is itself empty — an empty declared name is ABSENT, not an escape, and warning about it points the pack author at the wrong problem.

◆ scalePixelParams()

PHOSPHORSHADERS_EXPORT void PhosphorShaders::scalePixelParams ( const QVariantList & parameterInfos,
QVariantMap & values,
double factor )

Scale every px-denominated parameter for a host that renders the shader on a surface smaller than the real thing.

A shader's px parameters are absolute against the surface it draws on: a 24px blur radius over a 1000px window is a light frost, and the SAME 24px over a 240px preview card covers a tenth of it and swallows everything underneath. So a preview that shrinks the surface has to shrink the pixel values with it, or it shows a different effect than the one that will run — and, when the same shader is previewed at two sizes, two different effects.

factor is the linear reduction (preview extent / real extent). 1.0, and anything non-finite or non-positive, leaves values untouched.

ONE factor, taken from a single axis (width, at every current call site), is applied to every px parameter. That is exact only while the preview preserves the screen's aspect ratio, which the current preview hosts do NOT — they scale their rects anisotropically, so a px parameter denominating a VERTICAL length is still scaled by the horizontal ratio and comes out slightly off. A second, per-axis factor is not the fix: nothing in the pack metadata says which axis a parameter denominates, so there is no way to pick the right one. The limitation is documented rather than papered over.

A px parameter the caller left out of values is INSERTED at its scaled default rather than skipped: an absent parameter falls back to the pack's declared default further down the pipeline, which is the unscaled value this function exists to avoid. Parameters with any other unit are passed through, values that are not numbers are passed through, and the map keeps every entry the caller put in it. image parameters are skipped outright, even if one declares px: their values are paths, and inserting a default for one would manufacture the "the user set this" provenance that ShaderRegistry::translateParamsToUniforms derives from key presence to pick its absolute-path Trust-vs-Reject policy.

◆ seedPackPresets()

template<typename EffectList>
void PhosphorShaders::seedPackPresets ( ShaderPresetRegistry & registry,
ShaderFamily family,
const EffectList & effects )

Seed registry with every pack-declared preset in effects, for family.

The projection every consumer of this library performed by hand. Three processes each wrote the same loop — build {packId -> presets} and {packId -> bounds} from a pack registry's effect list, then whole-family replace — and the daemon wrote it three more times, once per family, so a fourth family meant a fourth copy. A fix to the projection had to land in every one of them.

A template because the four families each keep their own effect type in their own library; all four carry id, presets and parameters, which is all this reads. That is also why it lives here rather than on the STORE: the store deliberately knows nothing about the four pack registries, and this knows nothing about them either — only about the three fields their effects share.

Whole-family replace, not a per-pack loop, and that is the point: a loop over the packs that still exist cannot name one that has GONE, so an uninstalled pack's presets would survive for the process lifetime. The declared parameter ranges ride along, because resolveParams clamps to them, which is what keeps a hand-written preset value out of a pack's GLSL loop bound unchecked.

◆ shaderFamilyToken()

PHOSPHORSHADERS_EXPORT QLatin1StringView PhosphorShaders::shaderFamilyToken ( ShaderFamily family)

Wire token for family: "animation" / "surface" / "pointer" / "overlay".

◆ spliceAfterVersion()

PHOSPHORSHADERS_EXPORT QString PhosphorShaders::spliceAfterVersion ( const QString & source,
const QString & block )

Splice block into source immediately after its #version line, then emit a lineDirective re-anchoring source string 0 so the author's subsequent lines keep their original numbers despite the inserted block.

source is expected to be already include-expanded. A block may carry an #include only the compositor can resolve (kwinFinalizeColorBlock includes a KWin resource), which the phosphor resolver would fail on, so splicing before expansion is not an option for every caller. After expansion it composes cleanly: the fixup re-anchors source string 0 and the resolver's #line directives are untouched. block must be newline-terminated (as buildParamPreamble returns). An empty block returns source unchanged. If source has no #version line the block is prepended best-effort (such source is not valid GLSL anyway).

The #version line is located by versionDirectiveEnd, so a #version inside a comment is never taken for the directive. A leading BOM is stripped once whether or not block is empty, so the returned source never carries it. The newline and directive this function emits follow the source's own convention (CRLF when it contains any). block itself is spliced verbatim, so a CRLF source given an LF block comes back mixed, which every GLSL compiler accepts.

◆ standardUserPresetRoot()

PHOSPHORSHADERS_EXPORT QString PhosphorShaders::standardUserPresetRoot ( const QString & subdirectory)

The standard root for user-saved shader presets: <XDG_DATA_HOME>/<subdirectory>, where subdirectory is the app's preset directory relative to the user data dir, no leading slash (PlasmaZones passes plasmazones/shader-presets).

One subdirectory per family, named by shaderFamilyToken. Empty subdirectory answers an empty string, which ShaderPresetStore::load() refuses, so an app that names no directory loads and saves no presets rather than writing into the data dir's root.

Does NOT create the directory. WatchedDirectorySet promotes its watch to the parent when the target does not exist yet, so a preset saved into a fresh install is picked up without a restart and without every reader having to mkdir a directory it only wants to read.

◆ stripGlslComments()

PHOSPHORSHADERS_EXPORT QString PhosphorShaders::stripGlslComments ( const QString & source)

Strip GLSL line (//…) and block (/* … */) comments from source, preserving newlines inside block comments so line numbers are unchanged.

Exposed for the detection helpers and for tests; GLSL has no string literals so there is no quoting context to preserve.

◆ stripVaryingLocations()

PHOSPHORSHADERS_EXPORT QString PhosphorShaders::stripVaryingLocations ( const QString & source,
ShaderStage stage )

Remove the layout(location = N) qualifier from every varying of source: the out declarations of a vertex stage and the in declarations of a fragment stage.

Vertex inputs and fragment outputs keep theirs.

The compositor branch of a pack must not carry them. On a GLES 3 context, which is every context on KWin 6.8, KWin compiles custom shaders as GLSL ES 300, which allows a location only on vertex inputs and fragment outputs. A location on a varying needs ES 310 or GL_EXT_separate_shader_objects, and that extension cannot be enabled because KWin's precision declarations precede anything a shader splices in. Mesa's GLSL compiler, which every Mesa driver shares, rejects the source outright ("shader output explicit location requires GL_EXT_separate_shader_objects extension or GLSL ES 3.10"), while the proprietary NVIDIA driver accepts it. The qualifier is redundant there anyway: KWin links both stages into one program, which matches varyings by name. That makes name matching the contract on every KWin version, so a pack's vertex outputs and fragment inputs must share names and types.

The daemon branch keeps the qualifiers, because qsb's SPIR-V target requires them, so the pack files declare them and this runs only on the compositor path: kwinCompositorSource (the compositor's injector, the offline validator's compositor bake and the GPU bake tests all go through it). Run it on include-expanded source. Each qualifier is removed within its own line, so line numbers are unchanged.

Recognised: layout(location = <digits>), whitespace anywhere inside the parentheses but on one line, followed by any mix of flat, smooth, noperspective, centroid, sample, invariant and precise (possibly across newlines) and then the stage's in or out. Left in place: a layout list with a second member (location = 0, component = 1), a location spelled as a macro or expression, a newline inside the parentheses, and a comment or preprocessor line between the qualifier and the storage keyword. Those fail the validator's GLES arm, as they fail live.

◆ userPresetDirectory()

PHOSPHORSHADERS_EXPORT QString PhosphorShaders::userPresetDirectory ( const QString & root,
ShaderFamily family )

The directory holding family's user presets under root.

◆ versionDirectiveEnd()

PHOSPHORSHADERS_EXPORT int PhosphorShaders::versionDirectiveEnd ( const QString & source)

Locate the first REAL #version directive of source: the first line whose first non-whitespace token is #version outside any // or /* … */ comment, with a leading UTF-8 BOM (U+FEFF) skipped.

Returns the index of the newline that terminates that line, source.size() when the directive is the last line and has no trailing newline, or -1 when there is no directive at all.

The #version finder every SPLICE shares: spliceAfterVersion above (the daemon's preview bake, the validator and the compositor's preamble splices) and kwinCompositorSource, which the compositor's own ShaderInternal::injectKwinDefineAfterVersion wraps. Two finders that disagreed on a comment or a BOM put the preamble and the ABI define on different sides of the directive, which is a compile failure on the compositor only.

It is more permissive than KWin's own finder, which kwinGlesDialect and kwinDesktopDialect reproduce on purpose: KWin drops only a line that STARTS with #version, untrimmed and with no comment awareness. So an indented #version, or one after a same-line comment, is found here and survives KWin's rewrite, where it then fails as a second directive. The validator's compositor arms compile through those dialects and report it.

Unsupported shapes, all rejected rather than guessed at: • # version (whitespace after the #) is not recognised, and KWin would not drop it either. • A file whose lines end in a bare CR is one line here. • A #version line that opens a block comment it does not close returns -1. Splicing after it would land the block inside the comment, where the ABI define and every p_<id> silently vanish, so the caller's no-directive path runs instead and the compile fails loudly.

Variable Documentation

◆ kMaxBufferPasses

int PhosphorShaders::kMaxBufferPasses = 8
inlineconstexpr

Maximum number of multipass buffer passes a pack may declare.

Canonical home shared by the overlay parser, the pack validator and the daemon's ShaderNodeRhi binding budget (the surface tree forwards SurfaceShaderEffect::kMaxBufferPasses to it, as does the animation tree's AnimationShaderContract::kMaxBufferPasses). The figure comes from the SURFACE family: a dual Kawase pyramid needs seven passes, four down and three up, to reach a 256 px blur from a quarter-resolution base, and the eighth is headroom so the deepest bundled chain is not sitting exactly on the cap. Every buffer pass costs a texture at its declared scale, so the cap bounds GPU memory.

THE OTHER THREE FAMILIES INHERIT THAT NUMBER RATHER THAN NEEDING IT, and that is deliberate rather than an oversight. The overlay and animation parsers take this constant directly, so an installable pack in either family may now declare eight full-canvas buffer draws where four was the documented ceiling, on a path that is GPU-bound. The grant is accepted because both are opt-in per pack and both already pay per pass at the declared scale, so the cap bounds the worst case rather than describing a typical one. The POINTER family is the exception and keeps its own cap of two, stated in its contract, because a pointer chain runs on every output frame while the pointer is live. A family that acquires that shape should take its own cap the same way instead of inheriting this one.

The shared GLSL headers do NOT all declare this many iChannel samplers. Overlay (multipass.glsl) and surface (surface_multipass.glsl) declare iChannel0..7 and match; pointer declares iChannel0..3, above its own cap of two; and the animation family declares none at all, which is why a multipass animation pack has no declaration to sample its buffers through. See ShaderBindings.h for the binding numbers the first two use.

◆ kMaxBufferScale

double PhosphorShaders::kMaxBufferScale = 1.0
inlineconstexpr

◆ kMaxImageSlots

int PhosphorShaders::kMaxImageSlots = 4
inlineconstexpr

Image-pool budget: overlay/zone image params bind to uTexture0..3.

Animation packs never use the Image pool (their textures are a separate top-level list bound to uTexture1..3), so this cap only governs the zone path. Public so the metadata parser can warn on over-budget slots with the same figure the preamble generator skips at.

◆ kMinBufferScale

double PhosphorShaders::kMinBufferScale = 0.0078125
inlineconstexpr

Lower / upper bounds on a multipass bufferScale (FBO downscale factor).

1/128 means a 1/128 downscale on each axis, and 1.0 means full-resolution FBOs. Canonical home for every clamp site, so the bounds cannot drift per-runtime: all four families' metadata parsers, the kMin/MaxBufferScale forwarders that surface, animation and pointer each re-export from here, the four rendering setters (ShaderEffect's scalar and per-pass scale setters and their two ShaderNodeRhi counterparts), the four pack-validator range lints, and the compositor's own clamps for the surface backdrop and the pointer pass.

WHY THE FLOOR SITS FOUR STEPS BELOW THE DEEPEST LEVEL ANY PACK DECLARES. The deepest level of the bundled Kawase pyramids is 1/32, which is as deep as a pyramid starting at quarter resolution can go and still have texels to average. But the compositor multiplies every declared scale by the user's decoration blur-scale multiplier BEFORE clamping (PlasmaZonesEffect::clampedBufferScale), and that multiplier bottoms out at 1/4 (DecorationDefaults::BlurScaleMultiplierMin). A floor equal to the deepest declared level therefore clamped the bottom of the pyramid straight back up at any multiplier below 1. At the minimum, five of the seven levels all landed on 1/32 and the pyramid stopped halving at all, so turning the quality down stopped reducing work and started destroying the blur instead. 1/32 * 1/4 = 1/128 gives the multiplier its full range to scale the whole pyramid without collapsing it. Nothing degenerates at the floor: both hosts size targets with qMax(1, qRound(extent * scale)).

◆ kShaderTimeWrap

double PhosphorShaders::kShaderTimeWrap = 1024.0
constexpr

Time wrap period for float32 precision preservation.

◆ ShaderFamilyCount

std::size_t PhosphorShaders::ShaderFamilyCount = 4
constexpr

How many families there are, for the one-slot-per-family arrays that index by static_cast<std::size_t>(family).

Declared beside the enum, and static_asserted against it, so adding a family cannot leave a four-element array behind: the array grows with the constant instead of silently indexing past its end. The assert is what makes the coupling a compile error rather than a convention.