Shader pass API

Afterglow uses Phosphor ShaderRegistry metadata, source containment, include resolution, parameter slots and presets. Terminal shaders are a Phosphor shader family, like Phosphor’s animation, pointer and surface families and Phosphor’s overlay shader family. In the rest of this document, an overlay is a program that runs over a pane. See overlay transitions. Afterglow’s PostChain renders them in terminal QRhi composition passes. Afterglow reads its own metadata keys from pack metadata: highDynamicRange, windowBackground, settleSeconds, overviewNavigation and geometryPasses.

The terminal contract

The contract is the set of headers in data/shaders/shared. terminal_uniforms.glsl declares every input and documents each one. Afterglow compiles the copy built into it, so a pack cannot replace these headers. See pack locations for where packs and shared include files go.

HeaderContentsInclude
terminal_uniforms.glslUniform block, uTerminal, uTexture0 to uTexture3 and cursor shape constants.Automatic.
terminal_color.glslsRGB and linear conversions.Automatic.
terminal_lib.glslThe two headers above and helper functions.Automatic.
terminal_multipass.glsliChannel0 to iChannel7 and uDepthBuffer.For buffers.
terminal_audio.glsluAudioSpectrum and the audio helpers.Enables audio capture.
terminal_history.glsluPreviousText.Enables text history.
terminal_scene.glslObject matrices and helpers for mesh passes with objects.For object hierarchies.
terminal_panes.glslThe tab’s pane rectangles, focus, the pane overview’s state and the overlay transition.For window, overview, tab transition, pane effects and overlay transition shaders.

Entry points

Each stage defines one entry function. The final pass can also define a pointer map. Afterglow adds terminal_lib.glsl, the parameter definitions and main().

StageFunction
Final and buffer passesvec4 pTerminal(vec2 uv) returns premultiplied color for uv.
vertexShadervec4 pVertex(vec2 uv) returns the clip position of the canvas quad’s corner at uv.
Mesh vertex shadervec4 pMesh() returns the clip position of the current vertex.
Final pass, optionalvec2 pPointerMap(vec2 uv) returns where the content shown at uv comes from. See pointer maps.

A stage can define main() instead. Afterglow then adds only the parameter definitions. That stage must declare #version 450, its includes and its outputs.

Coordinates

All coordinates are top-down. Y increases downwards in positions, rectangles and texture coordinates. uv covers the canvas from (0, 0) at its top-left corner to (1, 1) at its bottom-right corner. The canvas is the layer, pane, window or buffer that the pass shades. Canvas pixels are device pixels, scaled by bufferScale in a buffer pass. Use terminalPixel(uv) and terminalUv(pixel) to convert. Sample the canvas with terminalTexel(uv).

Inputs

The uniform block starts with Phosphor’s BaseUniforms and continues with the terminal fields.

InputMeaning
iTime, iTimeDelta, iFrameShader time, wrapped every 1,024 seconds, the frame interval and the frame number.
iTimeHiThe seconds that wrapping removed from iTime, a multiple of 1,024. iTimeHi + iTime is the full shader time.
iResolutionCanvas size in canvas pixels.
iMousePointer in canvas pixels (.xy) and normalized (.zw). All components are -1 off the canvas.
uWindowMousePointer in window pixels, for a scene that spans panes. -1 outside the window.
customParams, customColorsParameter values. Use the p_<id> names.
uTerminalRect, uWindowSizeThe shaded region in window pixels and the window size. Buffer scaling does not change them.
uCellSizeOne character cell in canvas pixels.
uCursorRect, uPreviousCursorRectThe cursor and its previous position, in canvas pixels.
uCursorColor, uPreviousCursorColorThe cursor colors as drawn.
uCursorStateShape, previous shape, visibility and pane focus. Shapes are the kCursor constants. An unfocused pane always reports kCursorBlockHollow.
uEventAgesSeconds since the cursor moved and since focus changed. 1e6 means never: a pane seen for the first time reads 1e6 for both. So does every pane on the first frame after frames without shaders. Only a move of the cursor rectangle sets the cursor age. A change of shape or color does not.
uBackgroundColor, uForegroundColorTheme colors. uBackgroundColor.a is the window background opacity.
uThemeCursorColor, uThemeCursorTextColorTheme cursor colors.
uSelectionBackgroundColor, uSelectionForegroundColorTheme selection colors.
uPaletteThe 256-color palette.
uSignal, uScrollback, uAudioLevelsScript signals, history counts and audio levels. See Shaders.
uOverlayTransitionIn every pass of the overlay transition pack, its buffer passes too: .x the progress, .w 1. All zeros in other passes.

Helpers in terminal_lib.glsl include cursorVisible(), paneFocused(), cursorCenter(), cursorAge(), focusAge(), signalValue(), signalAge() and paletteColor().

sin(iTime * rate) and fract(iTime / period) jump each time iTime wraps, unless 1,024 seconds holds a whole number of turns or periods. Use the time helpers instead. They read the full shader time and do not jump.

HelperValue
timeAngle(rate)The angle that rate radians per second have turned, for sin() and cos(). Full precision however long the window runs. Use it only through a periodic function.
timeCycle(period)The position in a cycle of period seconds, from 0 to 1.
timeSeconds()iTimeHi + iTime, for a drift that does not repeat, such as a noise offset. Its precision falls as time grows: about 0.5 ms after two hours, 8 ms after a day and 62 ms after a week. Do not use it for a rotation, an orbit or a wave. Use timeAngle().

The window renders continuously while an active shader does one of these:

  • Reads iTime, iTimeDelta, iTimeHi, iFrame or iDate.
  • Calls timeAngle(), timeCycle() or timeSeconds().
  • Includes terminal_history.glsl.
  • Sets bufferFeedback, or spins a scene object.

A name in a comment does not count.

Event ages are a different time source. They are cursorAge(), focusAge(), signalAge(), uEventAges and uSignal. A shader that reads ages, and nothing in the list above, renders continuously only for a short time after an event. The window stops when the youngest age that the shader reads is settleSeconds or more. The next event of that kind starts the frames again.

AgeEvent
cursorAge()The cursor moved.
focusAge()The pane focus changed.
signalAge()A script, afterglow ctl signal or the control socket set a signal.
uEventAgesThe cursor moved, or the pane focus changed.
uSignalA script, afterglow ctl signal or the control socket set a signal.

Set settleSeconds to the time that the effect needs to finish at the largest parameter values. If the value is too short, the effect stops before its end. At the next redraw, it jumps to its current state.

signalValue() alone does not animate the shader. The window redraws when a signal changes. A shader that reads iMouse or uWindowMouse, and nothing in the lists above, redraws when the pointer moves.

Metadata

FieldSupported values
multipasstrue enables multiple passes.
bufferShadersUp to eight buffer shaders. Afterglow uses the first eight and logs a warning.
bufferFeedbackRetain previous buffer values. The pack then renders continuously.
bufferScale0.125–1. A value above 1 uses 1. A value below 0.125 rejects the pack.
halfFloatBuffersRGBA16F by default. false selects clamped RGBA8.
bufferWrap, bufferWrapsclamp, repeat, mirror.
bufferFilter, bufferFilterslinear, nearest.
depthBuffertrue adds an auxiliary color attachment to each buffer pass.
vertexShaderPath to a stage that defines pVertex.
geometryPassesOne mesh object or null per buffer shader.
highDynamicRangetrue keeps values above 1 between passes.
windowBackgroundtrue shares one background across the window’s panes.
settleSecondsAbove 0, at most 600. The default is 2. How long a shader that reads only event ages renders after an event. A value outside the range rejects the pack.
overviewNavigationorder or direction, for an overview pack. The default is order. See panes and the overview. Another value rejects the pack.

Pass order and coordinates

uTerminal contains the current terminal or layer input in every pass. Include terminal_multipass.glsl to read the buffers as iChannel0 through iChannel7. Passes execute in metadata order. Earlier buffers contain the current frame’s result. The current and later buffers contain the previous frame. Without feedback, previous values are cleared each frame. The final image pass receives all current-frame buffers.

Input textures are local to the region, and every texture is top-down. Raw texelFetch addresses local texture pixels.

Buffer passes use scaled buffer pixels for iResolution, cell, cursor and mouse coordinates. The final pass uses full-resolution pixels. uTerminalRect keeps the pane rectangle in window pixels: X, Y, width and height. uWindowSize keeps the window width and height. Buffer scaling does not change these two inputs. Use them for a camera or effect that spans split panes. The window size includes the docked areas of scripts. Afterglow draws the window areas (areas with the window scope) after every chain, so no shader changes them. Under them, a layer input is transparent, and the first pack of the window chain sees the clear color. Later packs and the overview, tab transition and pane effects see what the passes before them drew there. A pane area is part of its pane. It is inside uTerminalRect, in the layers and in the cards. The layer, pane and window chains and the event packs draw over it. Buffer iFrame starts at zero after reset. Final-pass iFrame keeps the window frame counter. iTime is the shared host clock.

Set "windowBackground": true on a background pack to share one set of buffers across the window. The buffer passes run once per frame. The image pass uses window coordinates and is clipped to visible panes. Split changes do not resize these buffers or reset their history. Window resize, shader reload, and changes to source colors, cell size or opacity still reset history. The focused pane supplies the palette, cursor, signals and parameter overrides. If no pane has focus, the first visible pane supplies these values. This option has no effect in text, cursor, pane or window chains. Use it for scene backgrounds and their lens passes, including effects that sample across split boundaries.

Auxiliary depth

With depth enabled, write depthBuffer = vec4(...) in pTerminal. uDepthBuffer samples the preceding pass’s auxiliary output. The first buffer samples its own previous depth. The image pass samples the final buffer’s depth. Initial depth values are zero. This color attachment stores arbitrary shader data. Mesh passes use a separate hardware depth attachment for visibility tests. The two attachments have different purposes.

Vertex stage

A vertex file defines:

vec4 pVertex(vec2 uv)

It returns the clip position of the canvas quad’s corner at uv, from -1 to 1. uv starts at the top-left and ranges from 0 to 1. terminalQuadPosition(uv) is the undeformed position. The stage can use terminal inputs, parameters and samplers. Afterward, the host maps the position into the current pane. Scissoring still isolates panes. Buffer passes use fullscreen geometry unless geometryPasses selects a mesh. The vertex stage applies only to the final pass. The final pass computes uv from the pixel position, not from the quad. A deformed quad changes which pixels run. It does not move the content. The pass does not run for pixels that a smaller quad leaves out. In a pane chain, those pixels show the undeformed pane, because pane passes draw over a copy of their input. The overlay transition also draws over a copy of its input, so those pixels show the overlay. In window, overview, tab transition and pane effects passes, they show the window’s clear color.

Pointer maps

A pack that moves the content, such as a bend or a lens, makes a click land on the wrong cell. The click is at the cell that the layout has there, not at the cell that the pack draws there. To prevent this, define the pointer map in the final pass, beside pTerminal:

vec2 pPointerMap(vec2 uv)

It returns the position of the content that the pack shows at uv, in the same coordinates as pTerminal. Usually it returns the coordinate that pTerminal gives to terminalTexel. Afterglow moves the pointer through it before it finds the pane and the cell. This applies to clicks, selections, links and drops. It also applies to mouse reports to programs, the docks of panes, popups, dividers and the shape of the pointer.

ItemRule
ChainsThe pane chain and the window chain. Layer chains and event packs do not use the map.
OrderLast pack first: the window chain, then the pane chain of the pane that the result is in.
InputsOnly uv, the canvas size iResolution and the pack’s parameters. Time, events, the pointer, the other uniforms and samplers do not apply.
ParametersThe values that the last frames drew with: the pane’s for a pane chain, the window region’s for the window chain.
WhereIn the final pass’s own file, as pTerminal. A map in an include file is not found.
main()A final pass that defines its own main() has no pointer map.
discardDo not discard. At a position that the map discards, the pointer does not move.
Positions outside the canvasThe map carries on in a line past the edge. A pane chain’s result outside the pane goes to the nearest cell at the edge. A window chain’s result outside the window goes to the pane at that edge. Between panes, a click reaches no pane.

Afterglow evaluates the map on the GPU into a grid with a point every 8 pixels of the canvas. Each side of the grid has 8 to 256 points. Between grid points the map is bilinear, so a map must be smooth. Afterglow evaluates the map in the first frame that draws the pack. It evaluates it again in a frame with a new canvas size or new parameter values. The map takes effect a few frames later, when its result arrives. Until then, the previous map stays. A result that is not a finite number leaves the pointer where it is.

The map moves only the pointer. These stay where the layout has them:

  • iMouse and uWindowMouse, which other packs read.
  • The chrome: the tab bar, the menus and the scroll bar, which are drawn over the chains.
  • The docks of the window, which are drawn over the chains.
  • The labels of URL hints, the input method’s cursor and what accessibility tools read.

CRT Curve bends the canvas and moves the pointer the same way. Tilt turns the canvas in perspective. Its map casts the same ray as its picture.

Mesh passes

A buffer pass can draw triangle meshes with hardware depth testing and depth writes. The final pass samples the result through iChannel0 to iChannel7. It can combine mesh output with terminal content and other effects. Existing ray-marched shaders continue to work.

Add geometryPasses to pack metadata. Supply one entry per bufferShaders entry. Use null for a fullscreen pass.

{
"fragmentShader": "effect.frag",
"multipass": true,
"bufferShaders": ["surface.frag", "blur.frag"],
"geometryPasses": [
{"vertexShader": "mesh.vert", "mesh": "model.obj", "instances": 4},
null
]
}

A mesh vertex shader defines vec4 pMesh(), which returns the clip position. Imported meshes provide meshPosition (vec3), meshNormal (vec3) and meshUV (vec2). Positions are in model coordinates. The shader applies model, camera and projection transforms. The output uses Vulkan clip coordinates: X and Y from -W to W, and Z from 0 to W. Positive Y points down. Smaller depth values are closer to the camera. The rasterizer clips triangles and interpolates attributes with perspective correction.

Declare matching layout(location=N) out and in values in vertex and fragment shaders. The fragment shader defines pTerminal as usual. It must output premultiplied color. Face culling and alpha blending are off. Use discard for cutout materials. Transparent surfaces require a separate composition method.

Replace mesh with vertexCount to generate vertices in the shader. Use gl_VertexIndex to select a vertex and gl_InstanceIndex to select an object. vertexCount must be a multiple of three. Both modes support instances, which defaults to one. Set samples to 1, 2, 4 or 8 to select multisample antialiasing. The default is 1. Other values reject the pack. A count that the GPU does not support uses 1. The renderer resolves multisample color before another pass samples it. Multisampling increases buffer memory use. Use bufferScale to reduce the target size when necessary. Afterglow does not import OBJ materials.

Both shader stages can read terminal uniforms, audio, images and script-controlled parameters. Reads of time, audio, scrollback and previous text have the same behavior as fullscreen shaders. Parameters update without recompiling or uploading the mesh again.

Each mesh pass has its own depth attachment, cleared to 1 once per pass. All instances and objects in that pass share depth. Separate passes do not share visibility tests. Depth comparison uses strict less. Surfaces at equal depth keep the first fragment. Feedback retains color and auxiliary data, but does not retain hardware depth. To pass visible depth to another shader, enable depthBuffer and write depthBuffer = vec4(gl_FragCoord.z) in the mesh fragment shader.

OBJ files must contain triangles. Export triangulated faces from the modeling application. The loader accepts positions, UVs, normals and negative face indices. A position record has 3, 4 or 6 values, a normal record 3, and a UV record 1 to 3. The loader uses the first three or two. Other counts reject the pack. Each OBJ line permits up to 4,096 bytes. Coordinate components must be finite and no greater than 1,000,000 in magnitude. It generates face normals when normals are absent. Missing UVs are zero. Object names, group names, smoothing groups and material references do not change rendering. The loader does not open material files. Supply materials in the shader and image parameters.

Geometry assets must be regular files inside the pack, including symlink targets. Each asset has a 32 MiB file limit. A pack can contain up to 96 MiB of decoded vertices. A pass permits 3,145,728 vertices, 4,096 instances and 12,582,912 total vertex invocations. Geometry and hardware depth count toward the shared 256 MiB buffer budget. A pass that exceeds that budget renders at a smaller size that fits, and logs a warning. It grows back when the budget has room again. Resize and shader replacement release obsolete GPU resources.

Mesh Reactor demonstrates instanced geometry, parent and child rotations in a shader, a perspective camera, lighting and audio response.

Object hierarchies

Replace mesh, vertexCount and instances with objects to describe a scene graph. Afterglow computes each object’s world transform on every frame and draws each object that has a mesh.

{
"geometryPasses": [{
"vertexShader": "scene.vert",
"objects": [
{"id": "sun", "mesh": "sphere.obj", "spin": [0, 8, 0]},
{"id": "orbit", "spin": [0, "$orbitSpeed", 0]},
{"id": "planet", "parent": "orbit", "mesh": "sphere.obj", "translate": [4, 0, 0], "scale": 0.5}
]
}]
}
KeyValue
idA unique name.
parentThe id of an earlier object. The object moves with its parent.
meshAn OBJ file in the pack. An object without a mesh is a pivot: it draws nothing and moves its children.
translateThree components. Default: 0, 0, 0.
rotateThree angles in degrees, applied about X, then Y, then Z. Default: 0, 0, 0.
scaleThree components, or one value for all axes. Default: 1.
spinThree rates in degrees per second, added to rotate. Default: 0, 0, 0.

Each component is a number, or "$id" for the value of a float or int parameter. Parameter references let shader_parameters and its transitions move objects without a recompile. A world transform is the parent’s world transform, then translate, rotate and scale. A pass permits 64 objects. A scene needs at least one object with a mesh. Spin makes the pack animated.

Include terminal_scene.glsl in the mesh vertex shader:

FunctionResult
objectIndex()The object’s position in objects. It is also gl_InstanceIndex.
objectPosition(vec3)A model position in world coordinates.
objectNormal(vec3)A model normal in world coordinates.

uObjectMatrix and uObjectNormalMatrix hold the matrices for all objects. The pack still applies its own camera and projection. Send objectIndex() to the fragment stage in a flat output when that stage needs it. Orrery demonstrates a sun, an orbiting planet and its moon.

Panes and the overview

A window shader sees the whole window but, without terminal_panes.glsl, not where its panes are. Include terminal_panes.glsl in any pass to read the panes and the pane overview. The block lists panes as cards, in tab order and then in layout order within each tab. While the overview is closed, the cards are the current tab’s panes. While it shows, the cards are the panes of every tab, up to 32. Panes after the 32nd, in tab order, do not appear in the overview.

FunctionValue
paneCount()The number of cards.
paneRect(i)Card i’s pane in window pixels: x, y, width and height, in its own tab’s layout.
paneTab(i), currentTab()The card’s tab index and the current tab’s index.
paneInCurrentTab(i)True for a pane of the current tab.
paneTexel(i, uv)The card’s pixels at uv, from (0, 0) at its top-left corner to (1, 1).
focusedPane()The focused card, or -1.
highlightedPane()The card the overview highlights, or -1. While the overview closes, the card it closes onto.
overviewOpen()True while the overview is open. False while it closes.
overviewAmount()0 for the flat window, 1 when the overview is open. A spring can pass 1 briefly.
highlightPosition()The highlight’s position in cards. It is fractional while the highlight moves. It counts on past the last card when the highlight wraps around, so motion continues. Take it modulo paneCount().
highlightOrigin()The card that the highlight last left, or -1 when it has not moved since the overview opened.
tabTransitionActive(), tabTransitionProgress(), tabTransitionDirection()The tab switch, while it runs.
previousTabTexel(uv)The tab being left, at a window uv, during a tab switch.
overlayTransitionActive(), overlayTransitionProgress(), overlayHostTexel(uv)An overlay that fades in or out: see overlay transitions.
paneOpening(i), paneOpenEdge(i)How far a new pane has opened, and the edge it opened from.
paneContext(i), paneContextChange(i)Where the pane’s shell runs, and how far its last change has run.
panePreviousContext(i)Where the pane’s shell ran before its last change.
panePulse(i), panePulseEffect(i), panePulseColor(i)A script’s pulse: how far it has run, its effect and its palette color.
closingPaneActive(), closingPaneProgress(), closingPaneRect(), closingPaneTexel(uv)A closed pane, while it closes.

paneTexel() reads the current tab’s panes from the pass input. It reads other tabs from images that Afterglow renders while the overview shows. The highlighted card’s tab is at full resolution. Other tabs share one window-sized atlas, so they are smaller. These images do not include layer, pane or window shaders. previousTabTexel() and closingPaneTexel() read the same kind of image. Use paneTexel() in window, overview, tab transition and pane effects passes. In layer, pane and overlay transition passes, the input is one pane and not the window, so paneTexel() reads the wrong place. uOverview.z and uOverview.w hold the seconds since the overview opened or closed and since the highlight moved.

Shaders.overview names the pack that draws the pane overview. Afterglow runs that pack after the window chain and the pane effects, only while the overview shows. It costs nothing while the overview is closed. Afterglow eases overviewAmount() and highlightPosition() with Animation.overviewCurve, so a shader reads positions and never times motion itself. Draw the flat window when overviewAmount() is 0. Opening and closing then start and end on the window. While the overview closes, highlightedPane() is the card it closes onto. Draw the highlight on that card, and use focusedPane() only when highlightedPane() is -1. A choice in another tab switches tabs when the close ends. Until then, currentTab() and focusedPane() stay in the old tab. The overview chain receives the window after the window chain. The tab bar, the window areas and other controls stay above it.

Shaders.tabTransition names the pack that animates a tab switch. Afterglow runs it after the window chain and the pane effects while the switch runs, over the new tab. previousTabTexel(uv) reads the tab being left at a window uv. That tab keeps running. tabTransitionProgress() runs from 0, the tab being left, to 1, the new tab. Animation.tabCurve eases it, and a spring can pass 1. tabTransitionDirection() is 1 toward a tab on the right and -1 toward one on the left. Draw the tab being left at progress 0 and the new tab at 1. The switch then starts and ends without a jump. The tab being left has no layer, pane or window shaders, because its image does not include them. With window shaders, the first frame of a switch can differ from the frame before it. The overview takes precedence: a switch that the overview makes does not run the transition. The flat tab transition of Phosphor Tabs and Plain Tabs slides the new tab in flat. The example pack Tab Switch shows a cube, a page flip, a shatter and a slide.

Shaders.paneEffects names the pack that animates panes as they split open and close. Afterglow runs it after the window chain while a pane opens or closes, a pulse runs or a pane is away. It also runs while the overview or a tab switch shows. It then runs before the overview or tab transition pack, so those start and end on what the window showed. paneOpening(i) runs from 0, just split, to 1, open. paneOpenEdge(i) is the edge the pane opened from: 0 none, 1 left, 2 top, 3 right or 4 bottom. closingPaneActive() is true while a closed pane shows. closingPaneRect() is where it was. closingPaneTexel(uv) reads its last frame at a window uv, from uTabImage. closingPaneProgress() runs from 0, just closed, to 1, gone. Both progress values are linear over Animation.paneEffectDuration. The pack eases them. At progress 1, draw the input unchanged. paneContext(i) is where the pane’s shell runs: 0 here, 1 remote, 2 elevated or 3 a container. paneContextChange(i) runs from 0, just changed, to 1, settled. It follows OSC 3008 contexts, such as those afterglow ssh reports. paneContextChange(i) runs linearly over Animation.contextDuration. panePreviousContext(i) is the context before that change, with the same numbers. Blend from it while the change runs. A pane that returns here can then fade its mark out in the color it had. Scripts play pulses with afterglow.pulse. panePulse(i) runs from 0 to 1, linearly over the script’s duration. It is 1 when no pulse runs. panePulseEffect(i) is 0 for none, 1 for a portal, 2 for a flash or 3 for a shake. A pack can define its own numbers from 4 to 255. panePulseColor(i) is the palette color the script chose. While any pane is away from here, the pack also runs on each frame Afterglow draws. Those frames come only from changes, so a static mark costs no extra frames. The flat pane effects of Phosphor Panes and Plain Panes fade panes in and out, and mark a pane that is away with a line at its edge. The example pack Pane Effects shows a hinge and a picture tube, and a ring and a vortex for the context change.

The arrow keys of the overview follow the layout that the pack draws. The pack names it with overviewNavigation in its metadata. With order, the default, Left and Right step through the cards in order and wrap round. Up and Down go to the first pane of the previous or next tab. This fits cards in a row or round a ring, where highlightPosition() moves over each card on its way. With direction, an arrow key goes to the pane in that direction, and stays when no pane is there. A pack with direction must draw each tab as a picture of its layout, with each pane at its paneRect() in the tab. It must draw the tabs in a grid in tab order, with as many columns as the smallest whole number whose square holds the tabs, and the last row centered. flat_overview.glsl draws this layout. In a tab, the key goes where the focus_left action and its like go. At the edge of a tab, it goes on to the nearest pane of another tab in that direction. The highlight then can go to a card that is not next in the count. highlightPosition() still counts the short way through the cards between them. Such a pack fades its highlight from highlightOrigin() to highlightedPane() and lights no card between them. Tab and Shift+Tab step through the cards in order with both values.

Input does not reach the panes while the overview is open. The highlighted pane is the one the user chooses, so a pack needs no hit testing. While the overview shows, other tabs use two more window-sized textures. Afterglow releases them when it closes. The flat overview of Phosphor Overview and Plain Overview lays the panes out flat, each tab as a picture of its layout. The example pack Pane Deck traces the panes as live cards on a carousel in one pass.

Overlay transitions

An overlay runs a program over a pane, in the pane’s place or as a popup over a part of it. Shaders.overlayTransition names the pack that blends the pane and the overlay while the overlay opens and closes. Afterglow runs it while the fade runs, over that pane alone, after the pane chain and before the window chain. The pass’s input is the pane with the overlay. overlayHostTexel(uv) reads the pane under the overlay at the pass’s canvas uv. For a popup, the input is the whole pane as it shows with the popup. That is the pane around the popup, darkened by Colors.popupDim, then the popup’s border if it has one, then the popup. overlayHostTexel() stays half a pixel inside the pane, so it never reads a divider or another pane. Both images have the pane’s layer and pane shaders. The window shaders then run over the result. The pane under the overlay keeps running. While the overlay fades in, its program also runs. While the overlay fades out, its program has ended, and the overlay shows the program’s last frame. The pane under the overlay keeps a text history of its own. Its uPreviousText holds its own text from the last frame, never the overlay’s. A fade that starts keeps the text history that the pane had. When a fade out starts after the overlay has shown whole, the pane under the overlay has no text history yet. Its uPreviousText is transparent in that frame. When a popup’s fade out starts after the popup has shown whole, the pane under it also has no text history yet. The history of the pane with its popup is not the history of the pane under it. When a popup opens or closes without a fade, the text history of every pane starts again, as when a full-pane overlay opens or closes. A pane’s own buffers step once a frame, also while a popup over it fades. The pane under the popup steps them, and the pane with the popup reads that step. When the overlay has faded out, the pane’s text history goes on from what it drew under the overlay. If a fade on another pane runs in that frame, this history starts again. When a fade on another pane starts or ends, the text history of each pane whose fade goes on starts again. A windowBackground pack’s buffers step once a frame, for the panes that show. The pane under the overlay reads those buffers as the last frame left them. When the buffers do not exist yet, the pane under the overlay makes them. They then step once in that frame. uScrollback counts the history of the pane under the overlay, also in the overlay’s passes. The overlay’s own history does not count. The window shaders take the focused pane’s inputs, such as its cursor and palette, from the pane under the overlay until the fade is halfway. After that, they take them from the overlay. While a popup runs, the cursor inputs of its pane (uCursorRect, uPreviousCursorRect, the cursor color, style and visibility) are the popup’s cursor, in canvas pixels. The palette, the default colors, the theme’s cursor colors and the text history stay the pane’s. While a popup fades out, its program has ended: the cursor inputs are the pane’s again. overlayTransitionProgress() runs from 0, the pane under the overlay, to 1, the overlay. It stays between 0 and 1. The fade stops the first time that it reaches its target. A curve that overshoots, such as a spring, does not bounce back. Animation.overlayCurve and Animation.overlayDuration time it. The fade out runs the same pack back to 0, from where the fade is. Draw the pane at progress 0 and the overlay at 1. The fade then starts and ends without a jump. overlayTransitionActive() is true in every pass of this pack and false in every other pass. The pack’s buffer passes can use all three helpers. A full-pane overlay hides the pane under it: that pane is drawn only while a fade runs. It goes into the window-sized tab image. Its text history lives until the frame after the last fade. A popup does not hide its pane: the pane and the popup are drawn in every frame. While a popup fades, the pane as it shows without the popup also goes into the tab image. The overview, a tab switch and a closing pane also use that image. An overlay opens and closes without a fade while one of them shows. It also does so while the pane is not on screen or the window is hidden. A fade can already run when one of them starts. If the overview, the tab switch or the closing pane takes the tab image, the fade switches at its halfway point. An overview of one tab does not take the tab image, so a fade that runs in it still blends. A fade whose pane stops showing, for example behind a zoomed pane or in another tab, switches at once. Without Shaders.overlayTransition, or when its pack does not load, an overlay also opens and closes without a fade. Overlay Fade blends the two images.

Images

Up to four image or texture parameters use uTexture0 through uTexture3. Use their p_<id> names. iTextureResolution holds their sizes. Defaults, live updates, presets and reset use the same path checks. An empty path is transparent. Relative paths, including symlink targets, must stay inside the pack. Trusted local scripts can use absolute paths and ~/ paths.

Each image is limited to 16 MiB encoded, 4096 pixels per side and four megapixels. Image transitions change at completion. Numeric and color transitions interpolate.

Color and alpha

RGBA16F stores arbitrary buffer data. RGBA8 clamps buffer data. Neither format enables display HDR. Terminal input and final output use encoded sRGB with premultiplied alpha. The host does not convert transfer functions automatically.

Use srgbToLinear and linearToSrgb for straight RGB. Use toLinearPremultiplied and toSrgbPremultiplied for colors with alpha. Transparent colors convert to zero to prevent division by zero. The feedback-glow example stores linear premultiplied light and converts back during composition.

The Phosphor spectrum and the rim

Include phosphor_spectrum.glsl to draw with the gradient of the bundled Phosphor packs. The file is in the shared/ directory of the bundled packs, so the include search finds it. A pack that includes it must declare the parameters followTheme (bool) and stop0 to stop3 (color).

FunctionValue
spectrum(t)The gradient at t, 0 to 1, as encoded sRGB: cyan, blue, purple and rose by default.
spectrumStop(i)Color i of the gradient, 0 to 3. With followTheme, a bright color of the terminal palette.
spectrumContext(context)The color for a paneContext() value: cyan remote, rose elevated, purple a container.

rim.glsl draws a line at the edge of a rectangle, with a halo inside it. It needs no parameter, and phosphor_spectrum.glsl includes it.

FunctionValue
rimDistance(pixel, rect)How far inside a rectangle a pixel is, in pixels. Negative outside.
drawRim(color, tint, inside, width, line, reach, halo)A line at the edge of a rectangle, with a halo inside it, over a premultiplied color.
addLight(color, light)A premultiplied color with light added. Alpha rises to cover the light.
coverWith(color, paint, amount)A premultiplied color blended toward an opaque color.

The flat event packs

The bundled overview, tab transition and pane effects packs come in two looks, Phosphor and plain, with one motion. The motion is in three files in the same shared/ directory. A pack declares the parameters that the file names, defines macros for its look, and then includes the file. Its pTerminal returns the function of the file. Afterglow looks for pTerminal in the pack’s own file, so an include file cannot define it.

FileFunctionMacrosPacks
flat_overview.glslflatOverview(uv)OVERVIEW_TINT(t), and optionally OVERVIEW_GLOW and OVERVIEW_REACHphosphor-overview, plain-overview
flat_tabs.glslflatTabs(uv)Optionally TAB_SEAM_TINT(t)phosphor-tabs, plain-tabs
flat_panes.glslflatPanes(uv)PANE_CONTEXT_TINT(context), and optionally PANE_EDGE_TINT(pixel, r), PANE_RIM, PANE_GLOW, PANE_REACH, PANE_HALO and PANE_SETTLEDphosphor-panes, plain-panes

The comment at the top of each file gives its parameters and what each macro does. Plain Panes is a complete pack in one macro, one include and one call. A pack of your own can do the same to change only the colors.

Ownership and reset

Each effect occurrence, scope and pane owns two alternating textures per buffer. Depth adds two auxiliary textures. No texture is sampled while it is being written.

These changes reset history:

  • Layout or active-tab identity.
  • Framebuffer size.
  • Cell size or DPI.
  • Theme foreground or background.
  • Opacity.
  • Shader reload.
  • Clock rewind.

Live parameter updates retain history. Focus changes can reset window-scoped buffers because their terminal context changes. Chain removal, window destruction or GPU resource release destroys the buffers. Afterglow also destroys the buffers when no chain runs after a frame in which one ran. This happens, for example, when the last overview, tab transition or pane effect ends and no other chain is set.

Memory limits

StorageLimit and behavior
Persistent buffers256 MiB per window and 32 effect occurrences. A buffer that does not fit renders smaller and logs a warning. A buffer that would shrink below 16 pixels on a side, or past the 32nd occurrence, is transparent.
Region input copies and uploaded imagesA separate 256 MiB GPU cache. Excess inputs become transparent and log a warning.
Decoded live images256 MiB per window, including transition endpoints. Excess updates are rejected atomically. Shared images count once.

A blocked buffer recovers when a size of at least 16 pixels on a side fits the limit. A smaller buffer grows when its full size fits, or when a size at least one eighth larger on each side fits. Unused GPU cache entries expire after one idle frame. These limits count resident pixels. Driver allocations, frames in flight, render targets, terminal textures, uniforms and pipelines require additional memory.

Each buffer uses:

2 × rounded(width × scale) × rounded(height × scale) × bytesPerPixel

Auxiliary depth doubles this amount. Add the amounts for all panes and passes. The feedback-glow half-resolution RGBA16F pair uses approximately 31.6 MiB at 4K or 7.9 MiB at 1080p.

Examples

The example packs are in the source repository. Afterglow does not install them.

Mirrored from docs/SHADER-API.md in the Afterglow repository.