### InitPostShaderlib Source: https://github.com/akabenko/gshader-library/blob/main/_autodocs/api-reference/README.md Extension hook fired during initialization after InitPostReconstruction. It is used by depthbuffer.lua to subscribe for post-shaderlib setup. ```APIDOC ## InitPostShaderlib ### Description Extension hook fired during initialization after InitPostReconstruction. It is used by depthbuffer.lua to subscribe for post-shaderlib setup. ### Hook `InitPostShaderlib` ### Fired From `!!shaderlib.lua:803` ### Payload None ``` -------------------------------- ### Custom PP shader example (HLSL) Source: https://github.com/akabenko/gshader-library/blob/main/_autodocs/api-reference/shader-materials.md Example of authoring a custom post-processing shader over the library render targets. It includes common headers for pixel shader and encoding functions, samples the NormalTangents render target, decodes the normal and tangent, and outputs a color. Compile with the same -shaders/-sdr pipeline and bind via a .vmt with the specified keys. ```hlsl #include "common_ps_fxc.h" #include "common_octahedron_encoding.h" #include "common_diamond_encoding.h" sampler WPDepthBuffer : register(s0); sampler NormalTangents : register(s1); float2 TexBaseSize : register(c4); struct PS_INPUT { float2 P : VPOS; float2 uv : TEXCOORD0; }; float4 main(PS_INPUT i) : COLOR0 { float2 uv = (i.P + 0.5) * TexBaseSize; float4 nt = tex2Dlod(NormalTangents, float4(uv, 0, 0)); float3 n = Decode(nt.xy); float3 t = decode_tangent(n, nt.z); return float4(n * 0.5 + 0.5, 1); } ``` -------------------------------- ### Usage example for enabling 3D skybox Source: https://github.com/akabenko/gshader-library/blob/main/_autodocs/api-reference/depth-buffer.md Shows how to enable the 3D skybox from a convar or addon logic, and how to read the sky depth target in a shader. ```lua -- enable from a convar or addon logic: shaderlib.Enable3DSkyBox() -- depth pass consumers read the sky depth target: -- float2 uv = ...; -- float depth = tex2Dlod(SkyDepthBuffer, float4(uv, 0, 0)).r; ``` -------------------------------- ### InitReconstruction Source: https://github.com/akabenko/gshader-library/blob/main/_autodocs/api-reference/README.md Extension hook fired during initialization to allow addons to subscribe for reconstruction setup. It is fired after the core setup and before InitPostReconstruction. ```APIDOC ## InitReconstruction ### Description Extension hook fired during initialization to allow addons to subscribe for reconstruction setup. It is fired after the core setup and before InitPostReconstruction. ### Hook `InitReconstruction` ### Fired From `!!shaderlib.lua:801` ### Payload None ``` -------------------------------- ### Usage example for ProjectedTexture wrapper Source: https://github.com/akabenko/gshader-library/blob/main/_autodocs/api-reference/projected-texture-wrapper.md Demonstrates creating a projected texture, checking its ID, looking it up by ID, and removing it. Shows that a second Remove() call is safe and does not affect bookkeeping. ```lua local proj = ProjectedTexture() print(proj:GetID()) -- 1 (first texture this session) print(#ENV_PROJTEXS) -- 1 local found = GetProjectedTextureByID(1) if found == proj then print("cache hit") end proj:Remove() print(#ENV_PROJTEXS) -- 0 proj:Remove() -- safe: double-remove no-op on bookkeeping ``` -------------------------------- ### Usage example for render.GetDynamicLights and render.GetDynamicLight Source: https://github.com/akabenko/gshader-library/blob/main/_autodocs/api-reference/dynamic-light-wrapper.md Shows creating a dynamic light, retrieving it by index, and using render.GetDynamicLights to dim all ELights. Also demonstrates render.GetDynamicLight to modify a stored light. Invalid engine indices return nil, and member writes outside the known list are delegated to the engine's original __newindex. ```lua local light = DynamicLight(42) light:SetColor(Color(255, 0, 0, 255)) light:SetLightWorld(true) print(light) -- dlight_t [42] print(light:GetIndex()) -- 42 local spot = DynamicLight(7, true) -- ELight for _, e in ipairs(render.GetDynamicLights(true)) do e:SetBrightness(e:GetBrightness() * 0.5) end local stored = render.GetDynamicLight(42) if stored then stored:SetColorUnpacked(0, 255, 0) end ``` -------------------------------- ### shaderlib.DrawScreenQuad() example with render target Source: https://github.com/akabenko/gshader-library/blob/main/_autodocs/api-reference/shaderlib-core.md Example usage of DrawScreenQuad with a render target and material. Draws the quad into the render target. ```lua render.PushRenderTarget(shaderlib.rt_WPDepth) render.SetMaterial(wp_reconst_mat) shaderlib.DrawScreenQuad() render.PopRenderTarget() ``` -------------------------------- ### shaderlib.DrawVertexScreenQuad example Source: https://github.com/akabenko/gshader-library/blob/main/_autodocs/api-reference/shaderlib-core.md Example usage of DrawVertexScreenQuad with a decode matrix and white color, specifying texture coordinates. ```lua shaderlib.DrawVertexScreenQuad(decode_mat, color_white, nil, {x = 0, y = 0}, {x = 1, y = 0}, {x = 1, y = 1}, {x = 0, y = 1}) ``` -------------------------------- ### GetHeadlightEffect usage example Source: https://github.com/akabenko/gshader-library/blob/main/_autodocs/api-reference/shaderlib-core.md Shows how to call shaderlib.GetHeadlightEffect() and feed the returned state to a flashlight pixel shader. The comment suggests building the ViewProj for the flashlight texture with shaderlib.BuildPerspectiveWorldToFlashlightMatrix. ```lua local state = shaderlib.GetHeadlightEffect() -- feed state to your flashlight pixel shader; e.g. build the ViewProj for the -- flashlight texture with shaderlib.BuildPerspectiveWorldToFlashlightMatrix ``` -------------------------------- ### InitPostReconstruction Source: https://github.com/akabenko/gshader-library/blob/main/_autodocs/api-reference/README.md Extension hook fired during initialization after InitReconstruction. It is used by postprocess/shader_lib.lua to subscribe for post-reconstruction setup. ```APIDOC ## InitPostReconstruction ### Description Extension hook fired during initialization after InitReconstruction. It is used by postprocess/shader_lib.lua to subscribe for post-reconstruction setup. ### Hook `InitPostReconstruction` ### Fired From `!!shaderlib.lua:802` ### Payload None ``` -------------------------------- ### Generate LUT with random colors Source: https://github.com/akabenko/gshader-library/blob/main/_autodocs/api-reference/lut-writing.md Example data generation loop that creates an 8x16 LUT and fills it with random colors using WritePixel. Demonstrates passing a Color object directly. ```lua local lut = shaderlib.CreateLUT("_rt_LUT_custom", 8, 16) for x = 0, lut:Width() do for y = 0, lut:Height() do local color = Color(math.Rand(0, 0.31), math.Rand(0, 0.33), math.Rand(0, 0.43), math.Rand(0, 0.23)) shaderlib.WritePixel(lut, x, y, color) end end ``` -------------------------------- ### DynamicLight wrapper factory (lua/autorun/!!dynamic_light_wrapper.lua) Source: https://github.com/akabenko/gshader-library/blob/main/_autodocs/api-reference/dynamic-light-wrapper.md Replaces the global DynamicLight factory to wrap every created light. Caches lights by index (ELights get +0.1), reuses or creates a metatable, resets mutable members on each acquisition, and returns the wrapped light or nil when the engine returns nil. ```lua local C_DynamicLight = DynamicLight function DynamicLight(index, isELight) local light = C_DynamicLight(index, isELight) if not light then return end index = math_floor(index) local cacheIndex = get_cache_index(index, isELight) local meta = lightCache[cacheIndex] and debug_getmetatable(lightCache[cacheIndex]) meta = meta or create_light_metatable(index, isELight) -- We have to reset the table's values every time to -- preserve 1:1 behavior reset_member_values(meta.__index) debug_setmetatable(light, meta) lightCache[cacheIndex] = light return light end ``` -------------------------------- ### PostDrawReconstructionLighting Source: https://github.com/akabenko/gshader-library/blob/main/_autodocs/api-reference/README.md Extension hook fired after reconstruction drawing and lighting, providing the view setup table as payload. ```APIDOC ## PostDrawReconstructionLighting ### Description Extension hook fired after reconstruction drawing and lighting, providing the view setup table as payload. ### Hook `PostDrawReconstructionLighting` ### Fired From `worldpos.lua:265` ### Payload `viewSetup` ``` -------------------------------- ### Write gamma curve to LUT Source: https://github.com/akabenko/gshader-library/blob/main/_autodocs/api-reference/lut-writing.md Example that creates a 256x1 single-channel LUT and writes a gamma curve (power 2.2) using unpacked channel values. ```lua local lut = shaderlib.CreateLUT("_rt_LUT_gamma", 256, 1, IMAGE_FORMAT_R32F) for x = 0, 255 do local v = math.pow(x / 255, 2.2) shaderlib.WritePixel(lut, x, 0, v, v, v, 255) end ``` -------------------------------- ### Example — full consumption of the encoded data Source: https://github.com/akabenko/gshader-library/blob/main/_autodocs/api-reference/shader-encoding-headers.md Shows how to decode the shader output: unpack world normals, tangents, and binormals to build a TBN matrix. Uses the Decode and decode_tangent functions. ```hlsl float4 normals_tangets = tex2D(NormalTangentBuffer, uv); float flipSign = normals_tangets.a; float3 worldNormal = Decode(normals_tangets.xy); float3 tangents = decode_tangent(worldNormal, normals_tangets.z); float3 binormals = normalize(cross(worldNormal, tangents)) * flipSign; float3x3 TBN = float3x3(tangents, binormals, worldNormal); ``` -------------------------------- ### HLSL shader usage example for reading lightmap pages Source: https://github.com/akabenko/gshader-library/blob/main/_autodocs/api-reference/lightmaps-building.md Shows how to sample the lightmap render target (_rt_Lightmaps) in a shader using the LightmapsBuffer sampler. The sample returns the linear lightmap page color. ```hlsl half4 page = tex2Dlod(LightmapsBuffer, float4(uv, 0, 0)); half3 lightmapColor = page.rgb; -- linear lightmap page sample ``` -------------------------------- ### Usage example: toggling debug from a custom script Source: https://github.com/akabenko/gshader-library/blob/main/_autodocs/api-reference/postprocess-shader-lib.md Checks the r_shaderlib_debug and r_shaderlib convars before calling shaderlib.EnableDebugMode(). Activation is idempotent; convar callbacks toggle hooks by name. ```lua if GetConVar("r_shaderlib_debug"):GetBool() and GetConVar("r_shaderlib"):GetBool() then shaderlib.EnableDebugMode() end ``` -------------------------------- ### Color API methods Source: https://github.com/akabenko/gshader-library/blob/main/_autodocs/api-reference/dynamic-light-wrapper.md Provides methods to get and set colors, both as Color objects and unpacked RGB values. Also includes SetLightModels and SetLightWorld to toggle model/world rendering. ```lua function DLight:GetColor() local tbl = self._Table return Color(tbl.r, tbl.g, tbl.b, 255) end function DLight:GetColorUnpacked() local tbl = self._Table return tbl.r, tbl.g, tbl.b end function DLight:SetColor(color) self.r = color.r self.g = color.g self.b = color.b end function DLight:SetColorUnpacked(r, g, b) self.r = r self.g = g self.b = b end function DLight:SetLightModels(lightModels) self.nomodel = not lightModels end function DLight:SetLightWorld(lightWorld) self.noworld = not lightWorld end ``` -------------------------------- ### Create and fill a LUT texture with random colors Source: https://github.com/akabenko/gshader-library/wiki/shaderlib Creates a LUT texture of size 8x16 and writes random float colors to each pixel using shaderlib.WritePixel. The example uses the default format IMAGE_FORMAT_RGBA32323232F and demonstrates storing light data. ```lua local lut = shaderlib.CreateLUT("_rt_LUT_custom", 8, 16) for x = 0,lut:Width() do for y = 0,lut:Height() do local color = Color(math.Rand(0, 0.3123), math.Rand(0, 0.333), math.Rand(0, 434.3123), math.Rand(0, 0.231) shaderlib.WritePixel(lut, x, y, color) end end ``` -------------------------------- ### Activate GShader bumps from another addon Source: https://github.com/akabenko/gshader-library/blob/main/_autodocs/api-reference/bumps-building.md Usage example to activate the bump shader from another addon. Checks the convar r_shaderlib_bumps and runs the ActivateGShaderBumps hook. After PreDrawEffects, the bump meshes and materials are ready, and the PostBumpDraw hook is fired after the bump render target is drawn. ```lua if GetConVar("r_shaderlib_bumps"):GetBool() then hook.Run("ActivateGShaderBumps") end --- then, in your PreDrawEffects handler or after PreDrawEffects: -- shaderlib.bump_MESHES / shaderlib.bump_MATS are ready; -- hook.Run("PostBumpDraw") is fired after _rt_Bump is drawn. ``` -------------------------------- ### Shader-side usage example (HLSL) Source: https://github.com/akabenko/gshader-library/blob/main/_autodocs/api-reference/reconstruction.md Nominal consumption of the shader output: samples the normal/tangent buffer, decodes world normal and tangents, computes binormals, and builds the TBN matrix. Use this in a pixel shader to reconstruct the tangent frame. ```hlsl float4 normals_tangents = tex2D(NormalTangentBuffer, uv); float flipSign = normals_tangents.a; float3 worldNormal = Decode(normals_tangents.xy); float3 tangents = decode_tangent(worldNormal, normals_tangents.z); float3 binormals = normalize(cross(worldNormal, tangents)) * flipSign; float3x3 TBN = float3x3(tangents, binormals, worldNormal); ``` -------------------------------- ### shaderlib.GetViewSpaceMatrix(pos, ang) Source: https://github.com/akabenko/gshader-library/blob/main/_autodocs/api-reference/shaderlib-core.md Builds a view matrix using U = -ang:Up(); result is used to get view-space normals (float3 N_view = normalize(mul(worldNormals, ViewMatrix));). ```lua function shaderlib.GetViewSpaceMatrix(pos, ang) ``` -------------------------------- ### shaderlib.BuildPerspectiveWorldToFlashlightMatrix(viewSetup) Source: https://github.com/akabenko/gshader-library/blob/main/_autodocs/api-reference/shaderlib-core.md Builds the ViewProj matrix for flashlight texture projection, using BuildWorldToShadowMatrix(viewSetup.origin, viewSetup.angles) times a perspective projection with fov = math.cot(math.rad(viewSetup.fov * 0.5)), range = (viewSetup.znear - viewSetup.zfar), aspect = viewSetup.aspect or 1. ```lua function shaderlib.BuildPerspectiveWorldToFlashlightMatrix(viewSetup) -- ViewProj for Flashlight g_FlashlightWorldToTexture ``` -------------------------------- ### shaderlib.BuildPerspectiveWorldToFlashlightMatrix(viewSetup) Source: https://github.com/akabenko/gshader-library/blob/main/_autodocs/api-reference/shaderlib-core.md Builds a ViewProj matrix for flashlight texture projection using a perspective projection and the world-to-shadow matrix. ```APIDOC ## BuildPerspectiveWorldToFlashlightMatrix ### Description `ViewProj` matrix for flashlight texture projection, built from `BuildWorldToShadowMatrix(viewSetup.origin, viewSetup.angles)` times a perspective projection whose `fov = math.cot(math.rad(viewSetup.fov * 0.5))`, `range = (viewSetup.znear - viewSetup.zfar)`, `aspect = viewSetup.aspect or 1`. ### Method FUNCTION ### Endpoint shaderlib.BuildPerspectiveWorldToFlashlightMatrix(viewSetup) ### Parameters #### Parameters - **viewSetup** (table) - Required - Table from `render.GetViewSetup()`. ### Returns - **Matrix** - The perspective world-to-flashlight matrix. ``` -------------------------------- ### shaderlib.GetViewProjZ( table viewSetup ) Source: https://github.com/akabenko/gshader-library/wiki/shaderlib Returns a table with view-projection Z values. ```APIDOC ## shaderlib.GetViewProjZ( table viewSetup ) ### Description Returns a table with keys x, y, z, w representing the view-projection Z values. ### Parameters - **viewSetup** (table) - Required - The view setup table from render.GetViewSetup. ### Returns - **table** - A table with keys x, y, z, w. ``` -------------------------------- ### PostDrawReconstructionEffects Source: https://github.com/akabenko/gshader-library/blob/main/_autodocs/api-reference/README.md Extension hook fired after reconstruction drawing and effects, providing the view setup table as payload. ```APIDOC ## PostDrawReconstructionEffects ### Description Extension hook fired after reconstruction drawing and effects, providing the view setup table as payload. ### Hook `PostDrawReconstructionEffects` ### Fired From `worldpos.lua:266` ### Payload `viewSetup` ``` -------------------------------- ### shaderlib.GetViewProjMatrix(viewSetup) Source: https://github.com/akabenko/gshader-library/blob/main/_autodocs/api-reference/shaderlib-core.md Returns GetProjMatrix(viewSetup):Mul(GetViewMatrix(pos, ang)). ```lua function shaderlib.GetViewProjMatrix(viewSetup) ``` -------------------------------- ### PostDrawReconstructionPreEffects Source: https://github.com/akabenko/gshader-library/blob/main/_autodocs/api-reference/README.md Extension hook fired after reconstruction drawing but before effects, providing the view setup table as payload. ```APIDOC ## PostDrawReconstructionPreEffects ### Description Extension hook fired after reconstruction drawing but before effects, providing the view setup table as payload. ### Hook `PostDrawReconstructionPreEffects` ### Fired From `worldpos.lua:264` ### Payload `viewSetup` ``` -------------------------------- ### shaderlib.GetViewProjOrthoMatrix(viewSetup) Source: https://github.com/akabenko/gshader-library/blob/main/_autodocs/api-reference/shaderlib-core.md Builds a view matrix times orthogonal projection using viewSetup.ortho.left/right/bottom/top (GetProjOrthoMartix). ```lua function shaderlib.GetViewProjOrthoMatrix(viewSetup) ``` -------------------------------- ### PostDrawReconstruction Source: https://github.com/akabenko/gshader-library/blob/main/_autodocs/api-reference/README.md Extension hook fired after reconstruction drawing, providing the view setup table as payload. It is used for post-processing effects. ```APIDOC ## PostDrawReconstruction ### Description Extension hook fired after reconstruction drawing, providing the view setup table as payload. It is used for post-processing effects. ### Hook `PostDrawReconstruction` ### Fired From `worldpos.lua:263` ### Payload `viewSetup` ``` -------------------------------- ### shaderlib.GetProjMatrix(viewSetup) Source: https://github.com/akabenko/gshader-library/blob/main/_autodocs/api-reference/shaderlib-core.md Builds a perspective projection matrix only (no view rotation): { fov, 0, 0, 0 }, { 0, fov*aspect, 0, 0 }, { 0, 0, 1, 1 }, { 0, 0, -1, 0 } with fov = math.cot(math.rad(viewSetup.fov * 0.5)). ```lua function shaderlib.GetProjMatrix(viewSetup) --Perspective projection matrix ``` -------------------------------- ### Configure lightmap building knobs Source: https://github.com/akabenko/gshader-library/blob/main/_autodocs/api-reference/lightmaps-building.md Module-local configuration knobs. `MATORDER` selects which BSP lump determines material draw order during packing; `FACELUMP` selects the face lump: `MODE_LUMP_LDR` → lump 7, `MODE_LUMP_HDR` → lump 58 when non-empty else 7, `MODE_LUMP_AUTO` → depends on `hdr`. ```lua local MATORDER = MODE_SESSION -- 0 SESSION / 1 TEXINFO / 2 TEXDATA local FACELUMP = MODE_LUMP_AUTO -- 0 AUTO / 1 LDR / 2 HDR ``` -------------------------------- ### Lightmaps lifecycle hooks and initialization Source: https://github.com/akabenko/gshader-library/blob/main/_autodocs/api-reference/lightmaps-building.md Sets up the lifecycle for lightmaps: clears on shutdown, initializes after entities, and handles map changes. It also calls InitLightmaps if already initialized or if the local player is valid. ```lua hook.Add("ShutDown", shaderName, ClearLightmaps) hook.Add("InitPostEntity", shaderName, function() shaderlib.LM_initialized = true if shaderlib.LM_map and shaderlib.LM_map ~= game.GetMap() then ClearLightmaps() end InitLightmaps() end) if shaderlib.LM_initialized or IsValid(LocalPlayer()) then InitLightmaps() end ``` -------------------------------- ### Fire extension hooks in initialization order Source: https://github.com/akabenko/gshader-library/blob/main/_autodocs/api-reference/README.md The core's "Initialize" hook runs this sequence to trigger extension hooks in order: InitReconstruction, InitPostReconstruction, InitPostShaderlib. Subscribers use these to hook into the initialization process. ```lua hook.Run("InitReconstruction") -- worldpos.lua subscribes here hook.Run("InitPostReconstruction") -- postprocess/shader_lib.lua subscribes here hook.Run("InitPostShaderlib") -- depthbuffer.lua subscribes here ``` -------------------------------- ### Register shaderlib initialization hook Source: https://github.com/akabenko/gshader-library/blob/main/_autodocs/api-reference/shaderlib-core.md Registers the InitShaderLib function on the 'Initialize' hook. libName is set to 'shaderlib'. ```lua hook.Add("Initialize", libName, InitShaderLib) -- libName = "shaderlib" ``` -------------------------------- ### shaderlib.GetViewProjZ(viewData) Source: https://github.com/akabenko/gshader-library/blob/main/_autodocs/api-reference/shaderlib-core.md Accepts a viewSetup table or a pre-built matrix; returns the third matrix row as a Vector4 table (the Z row). ```lua function shaderlib.GetViewProjZ(viewData) if !ismatrix(viewData) then viewData = shaderlib.GetViewProjMatrix(viewData) end return Vector4( viewData:GetField( 3,1 ), viewData:GetField( 3,2 ), viewData:GetField( 3,3 ), viewData:GetField( 3,4 ) ) end ``` -------------------------------- ### GetHeadlightEffect PrintTable result Source: https://github.com/akabenko/gshader-library/wiki/shaderlib Example output of PrintTable on the table returned by shaderlib.GetHeadlightEffect(). Shows the flashlight data structure of the LocalPlayer, including color, attenuation, shadow settings, and spotlight texture. ```cpp ["m_Color"]: ["a"] = 0 ["b"] = 255 ["g"] = 255 ["r"] = 255 ["m_FarZ"] = 750 ["m_NearZ"] = 4.8 ["m_bEnableShadows"] = true ["m_fConstantAtten"] = 0 ["m_fHorizontalFOVDegrees"] = 45 ["m_fLinearAtten"] = 100 ["m_fQuadraticAtten"] = 0 ["m_fVerticalFOVDegrees"] = 30 ["m_flShadowAtten"] = 0.34999999403954 ["m_flShadowDepthBias"] = 0.0010000000474975 ["m_flShadowMapResolution"] = 4446 ["m_flShadowSlopeScaleDepthBias"] = 2 ["m_nSpotlightTextureFrame"] = 0 ["m_pSpotlightTexture"] = Texture [effects/flashlight001] ["m_quatOrientation"] = 8.471 -149.509 0.000 ["m_vecLightOrigin"] = -2715.422607 -1528.729980 -99.547180 ``` -------------------------------- ### DLight __tostring meta method Source: https://github.com/akabenko/gshader-library/blob/main/_autodocs/api-reference/dynamic-light-wrapper.md Defines the __tostring metamethod to return a string representation of the light, including its key. ```lua function DLight:__tostring() return 'dlight_t [' .. self.key .. ']' end ``` -------------------------------- ### render.GetDynamicLights, render.GetDynamicLight, render.DynamicLightPairs Source: https://github.com/akabenko/gshader-library/blob/main/_autodocs/api-reference/dynamic-light-wrapper.md Documentation for the global getter functions in the render namespace for accessing cached dynamic lights. ```APIDOC ## render.GetDynamicLights(elight) ### Description Returns an array of cached dynamic lights, optionally filtered by light type (all, ELight-only, or DLight-only). ### Method Function ### Endpoint render.GetDynamicLights(elight) ### Parameters - **elight** (nil/true/false) - Optional - Filter: nil returns all lights, true returns only ELights, false returns only DLights. ### Returns - **array** - Array of cached lights (all, ELight-only, or DLight-only). ### Example ```lua for _, e in ipairs(render.GetDynamicLights(true)) do e:SetBrightness(e:GetBrightness() * 0.5) end ``` ## render.GetDynamicLight(index, isELight) ### Description Returns a single cached dynamic light by its index and type, or nil if not found. ### Method Function ### Endpoint render.GetDynamicLight(index, isELight) ### Parameters - **index** (number) - Required - The light index. - **isELight** (boolean) - Required - Whether the light is an ELight (true) or DLight (false). ### Returns - **light** (light object) - The cached light, or nil if not found. ### Example ```lua local stored = render.GetDynamicLight(42) if stored then stored:SetColorUnpacked(0, 255, 0) end ``` ## render.DynamicLightPairs() ### Description Returns an iterator pair for iterating over the weak-valued light cache. ### Method Function ### Endpoint render.DynamicLightPairs() ### Parameters None. ### Returns - **next** (function) - The next iterator function. - **lightCache** (table) - The weak-valued cache table. ### Example ```lua for k, v in render.DynamicLightPairs() do -- iterate over cached lights end ``` ``` -------------------------------- ### GetViewSpaceMatrix HLSL usage Source: https://github.com/akabenko/gshader-library/wiki/shaderlib HLSL example showing how to use the view matrix returned by shaderlib.GetViewSpaceMatrix to transform world normals into view space. The matrix is bound to register c11 and used to compute screen-space normals. ```cpp float3x3 ViewMatrix : register(c11); // main func: float3 N_view = normalize(mul(worldNormals, ViewMatrix)); ``` -------------------------------- ### Activation hooks for Bumps Building (bumps_building.lua:452-499) Source: https://github.com/akabenko/gshader-library/blob/main/_autodocs/api-reference/bumps-building.md Sets up hooks to build meshes on InitPostEntity and ActivateGShaderBumps. The InitPostEntity hook waits 1 second and checks the r_shaderlib_bumps convar before building. The ActivateGShaderBumps hook builds meshes if not already built and adds a PreDrawEffects hook. ```lua hook.Add("InitPostEntity", shaderName, function() timer.Simple(1, function() if !GetConVar("r_shaderlib_bumps"):GetBool() then return end shaderlib.bump_MESHES, shaderlib.bump_MATS = BuildMeshes(includeDisplacment) end) end) hook.Add("ActivateGShaderBumps", shaderName, function() if !shaderlib.bump_MESHES then shaderlib.bump_MESHES, shaderlib.bump_MATS = BuildMeshes(includeDisplacment) end hook.Add("PreDrawEffects", shaderName, function() ... end) end) ``` -------------------------------- ### Build() - Generate lightmap meshes Source: https://github.com/akabenko/gshader-library/blob/main/_autodocs/api-reference/lightmaps-building.md Builds lightmap meshes for the current map. Re-runs only when the map changed; ClearLightmaps() destroys all meshes and nils LM_meshes / L_MATS / LM_map. Outputs shaderlib.L_MATS (materials) and shaderlib.LM_meshes (meshes), index-aligned, with shaderlib.LM_map set to the current map name. ```lua local function Build() local map = game.GetMap() if shaderlib.LM_meshes and shaderlib.LM_map == map then return end ClearLightmaps() shaderlib.LM_meshes = {} shaderlib.LM_map = map if not ParseBSP() then return end ... ``` -------------------------------- ### Global state initialization for ProjectedTexture wrapper Source: https://github.com/akabenko/gshader-library/blob/main/_autodocs/api-reference/projected-texture-wrapper.md Initializes global tables and variables used by the wrapper. ENV_PROJTEXS stores alive textures in creation order, ENV_PROJTEXS_I maps IDs to list indices, ptCache is a weak-keyed map from textures to IDs, nextID is a monotonic counter, and C_ProjectedTexture holds the original constructor. ```lua ENV_PROJTEXS = ENV_PROJTEXS or {} ENV_PROJTEXS_I = ENV_PROJTEXS_I or {} C_ProjectedTexture = C_ProjectedTexture or ProjectedTexture ptCache = ptCache or setmetatable({}, {__mode = "k"}) nextID = nextID or 0 ``` -------------------------------- ### DLight object (DynamicLight wrapper) Source: https://github.com/akabenko/gshader-library/blob/main/_autodocs/types.md Documentation for the DLight object returned by DynamicLight(). ```APIDOC ## DLight object (DynamicLight wrapper) ### Description Wrapped object shape (`!!dynamic_light_wrapper.lua`). `key`, `_Table`, `_IsELight` are set by `create_light_metatable`; the numeric members are reset to 0 and vector members to nil on every `DynamicLight()` call. ### Method GET ### Endpoint `DynamicLight()` ### Parameters None ### Response #### Success Response (200) - **key** (number) - original (floored) index - **_Table** (table) - self-reference - **_IsELight** (boolean) - default `false` - **brightness, decay, dietime, innerangle, outerangle, minlight, size, style** (number) - 0 after reset - **r, g, b** (number) - 0 after reset - **noworld, nomodel** (boolean) - `false` after reset - **pos, dir** (Vector/nil) - nil until first `GetPos()`/`GetDirection()` (lazy `Vector(0,0,0)`) #### Response Example ```json { "key": "number", "_Table": "table", "_IsELight": "boolean", "brightness": "number", "decay": "number", "dietime": "number", "innerangle": "number", "outerangle": "number", "minlight": "number", "size": "number", "style": "number", "r": "number", "g": "number", "b": "number", "noworld": "boolean", "nomodel": "boolean", "pos": "Vector/nil", "dir": "Vector/nil" } ``` ``` -------------------------------- ### EnableLightmaps render hook for PreDrawEffects Source: https://github.com/akabenko/gshader-library/blob/main/_autodocs/api-reference/lightmaps-building.md Defines the EnableLightmaps function that hooks PreDrawEffects to render lightmaps into a render target. It adjusts the view setup, pushes the lightmap render target, draws all lightmap meshes, and runs the PostDrawLightmaps hook. The pass is skipped if shaderlib.CanDrawEffects returns false. ```lua local function EnableLightmaps() hook.Add("PreDrawEffects", shaderName, function() local viewSetup = render.GetViewSetup() if shaderlib.CanDrawEffects and not shaderlib.CanDrawEffects(viewSetup) then return end viewSetup.znear = viewSetup.znear + 0.01 viewSetup.zfar = viewSetup.zfar + 10 cam.Start(viewSetup) render.PushRenderTarget(shaderlib.rt_Lightmaps) render.Clear(0,0,0,0) render.OverrideDepthEnable(true, true) for i = 1, #shaderlib.LM_meshes do render.SetMaterial(shaderlib.L_MATS[i]) shaderlib.LM_meshes[i]:Draw() end render.OverrideDepthEnable(false, false) render.PopRenderTarget() cam.End() hook.Run("PostDrawLightmaps") end) end ``` -------------------------------- ### LPREVIEW_PS_OUT struct in common_ps_fxc.h Source: https://github.com/akabenko/gshader-library/blob/main/_autodocs/types.md Defines the output structure for the preview pixel shader. ```hlsl struct LPREVIEW_PS_OUT { float4 color : COLOR0; float4 normal : COLOR1; float4 position : COLOR2; float4 flags : COLOR3; }; ``` -------------------------------- ### shaderlib.mat_wpndepth material initialization Source: https://github.com/akabenko/gshader-library/blob/main/_autodocs/api-reference/reconstruction.md Initializes the normals-reconstruction material `shaderlib.mat_wpndepth` to `pp/wpn_reconstruction_improved` if not already set. This material is overridden by `postprocess/shader_lib.lua` (`getCurrentMethodMat`) based on `r_shaderlib_wn_reconsruction`. The five selectable pixel shaders are `pp/wpn_reconstruction_simple`, `pp/wpn_reconstruction_3tap`, `pp/wpn_reconstruction_4tap`, `pp/wpn_reconstruction_improved`, and `pp/wpn_reconstruction_accurate`. ```lua shaderlib.mat_wpndepth = shaderlib.mat_wpndepth or Material("pp/wpn_reconstruction_improved") ``` -------------------------------- ### shaderlib.EnableDebugMode() implementation Source: https://github.com/akabenko/gshader-library/blob/main/_autodocs/api-reference/postprocess-shader-lib.md Draws an on-screen grid of debug render targets. Uses r_shaderlib_dbg_scale to scale the grid, creates a debug material, and initializes test render targets via InitTestRT(). The function is idempotent; re-adding the same HUDPaint hook name replaces it. ```lua function shaderlib.EnableDebugMode() local s = r_shaderlib_dbg_scale:GetFloat() local decode_mat = Material("debug/decode_normals_tangents") InitTestRT() ... end ``` -------------------------------- ### shaderlib.BuildWorldToShadowMatrix(translation, ang) Source: https://github.com/akabenko/gshader-library/blob/main/_autodocs/api-reference/shaderlib-core.md Builds the world→shadow-space basis from ang (forward→up, right→up, up→forward), transposes it, and applies -translation. Returns the matrix. ```lua function shaderlib.BuildWorldToShadowMatrix(translation, ang) -- View Flashlight ``` -------------------------------- ### shaderlib.GetProjMatrix(viewSetup) Source: https://github.com/akabenko/gshader-library/blob/main/_autodocs/api-reference/shaderlib-core.md Builds a perspective projection matrix (no view rotation). ```APIDOC ## GetProjMatrix ### Description Perspective projection only (no view rotation): `{ fov, 0, 0, 0 }, { 0, fov*aspect, 0, 0 }, { 0, 0, 1, 1 }, { 0, 0, -1, 0 }` with `fov = math.cot(math.rad(viewSetup.fov * 0.5))`. ### Method FUNCTION ### Endpoint shaderlib.GetProjMatrix(viewSetup) ### Parameters #### Parameters - **viewSetup** (table) - Required - Table from `render.GetViewSetup()`. ### Returns - **Matrix** - The perspective projection matrix. ``` -------------------------------- ### Render pass for _rt_Bump (bumps_building.lua:464-492) Source: https://github.com/akabenko/gshader-library/blob/main/_autodocs/api-reference/bumps-building.md Draws all material/mesh pairs into shaderlib.rt_Bump. Takes viewSetup from render.GetViewSetup(), early-outs unless shaderlib.CanDrawEffects(viewSetup), adjusts znear and zfar, then renders meshes with STUDIO_RENDER and STUDIO_NOSHADOWS. Finally runs the PostBumpDraw hook. ```lua render.PushRenderTarget(shaderlib.rt_Bump) render.Clear(0,0,0,0) render.OverrideDepthEnable(true,true) for i = 1, #shaderlib.bump_MESHES do render.SetMaterial(shaderlib.bump_MATS[i]) local _mesh = shaderlib.bump_MESHES[i] _mesh:Draw(STUDIO_RENDER + STUDIO_NOSHADOWS) end if IsValid(_WATER_MESH) then render.SetMaterial(mat_water) _WATER_MESH:Draw(STUDIO_RENDER + STUDIO_NOSHADOWS) end render.OverrideDepthEnable(false,false) render.PopRenderTarget() cam.End() hook.Run("PostBumpDraw") ``` -------------------------------- ### shaderlib.BuildWorldToShadowMatrix(translation, ang) Source: https://github.com/akabenko/gshader-library/blob/main/_autodocs/api-reference/shaderlib-core.md Builds the world-to-shadow-space basis matrix from a translation and angle, transposes it, and applies the translation. Returns the resulting matrix. ```APIDOC ## BuildWorldToShadowMatrix ### Description Builds the world→shadow-space basis from `ang` (forward→up, right→up, up→forward), transposes it, and applies `-translation`. Returns the matrix. ### Method FUNCTION ### Endpoint shaderlib.BuildWorldToShadowMatrix(translation, ang) ### Parameters #### Parameters - **translation** (table) - Required - Translation vector. - **ang** (Angle) - Required - Angle used to construct the basis. ### Returns - **Matrix** - The world-to-shadow matrix. ``` -------------------------------- ### Register PostProcess panel entry Source: https://github.com/akabenko/gshader-library/blob/main/_autodocs/api-reference/postprocess-shader-lib.md Registers the library in the settings Post Process list. The cpanel function is elided in the source; the panel includes presets, comboboxes, sliders, checkboxes, and a system info text panel. ```lua list.Set( "PostProcess", "#r_shaderlib", { ["icon"] = "gui/postprocess/shaderlib.jpg", ["convar"] = r_shaderlib:GetName(), ["category"] = "#shaders_pp", ["cpanel"] = function( panel ) ... end } ) ``` -------------------------------- ### PostDrawReconstructionLighting(table viewSetup) Source: https://github.com/akabenko/gshader-library/wiki/hooks Hook for drawing CSM and custom lighting. ```APIDOC ## PostDrawReconstructionLighting(table viewSetup) ### Description Use this hook to draw CSM, custom lighting. ### Method Hook ### Endpoint PostDrawReconstructionLighting ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **viewSetup** (table) - Required - The view setup table from render.GetViewSetup. ### Request Example N/A ### Response #### Success Response No return value. #### Response Example N/A ``` -------------------------------- ### PS_INPUT and PS_OUTPUT structs in wpn_out.h Source: https://github.com/akabenko/gshader-library/blob/main/_autodocs/types.md Defines the input and output structures for the reconstruction pixel shader. ```hlsl struct PS_INPUT { float2 P : VPOS; float2 uv : TEXCOORD0; float3 fogParams : TEXCOORD1; }; struct PS_OUTPUT { float4 color0 : COLOR0; // .xy worldNormals, .b tangent, .a sign half4 color1 : COLOR1; // .xyz bumps, .a fog //float4 color2 : COLOR2; // .ra velocity buffer }; ``` -------------------------------- ### Create render targets for world position, depth, and normals/tangents Source: https://github.com/akabenko/gshader-library/blob/main/_autodocs/api-reference/reconstruction.md Creates the render targets used by the reconstruction pipeline: _rt_WPDepth for world position and depth, _rt_softwaredepth_half and _rt_softwaredepth_quad for depth copies, and _rt_NormalsTangents for normals and tangents. The flags include pointsample (1) for reading normals in downsampled render targets. ```lua shaderlib.rt_WPDepth = GetRenderTargetEx("_rt_WPDepth", ScrW(), ScrH(), RT_SIZE_FULL_FRAME_BUFFER, MATERIAL_RT_DEPTH_NONE, bit.bor(1, 4, 8, 256, 512, 32768, 8388608), -- need pointsample flag 1 for reading normals in downsampled rt 0, IMAGE_FORMAT_RGBA32323232F ) ``` ```lua shaderlib.rt_DepthHalf = GetRenderTargetEx("_rt_softwaredepth_half", ScrW() * 0.5, ScrH() * 0.5, RT_SIZE_LITERAL, MATERIAL_RT_DEPTH_NONE, bit.bor(16, 4, 8, 256, 512, 32768, 8388608), 0, IMAGE_FORMAT_R32F ) ``` ```lua shaderlib.rt_DepthQuad = GetRenderTargetEx("_rt_softwaredepth_quad", ScrW(), ScrH(), RT_SIZE_HDR, MATERIAL_RT_DEPTH_NONE, bit.bor(16, 4, 8, 256, 512, 32768, 8388608), 0, IMAGE_FORMAT_R32F ) ``` ```lua shaderlib.rt_NormalsTangents = GetRenderTargetEx("_rt_NormalsTangents", ScrW(), ScrH(), RT_SIZE_FULL_FRAME_BUFFER, MATERIAL_RT_DEPTH_NONE, bit.bor(1, 4, 8, 256, 512, 32768, 8388608), -- need pointsample flag 1 for reading normals in downsampled rt 0, shaderlib.GetWorldNormalsImageFormat() ) ``` -------------------------------- ### system.GetVendor() Source: https://github.com/akabenko/gshader-library/blob/main/_autodocs/api-reference/shaderlib-core.md Returns the GPU vendor name as a string. ```APIDOC ## system.GetVendor() ### Description Returns the GPU vendor name as a string. ### Method function ### Signature `function system.GetVendor()` ### Returns - **string** - `"NVIDIA"` / `"AMD"` / `"INTEL"` / `"UNKNOWN"` ``` -------------------------------- ### render.GetDynamicLights, render.GetDynamicLight, render.DynamicLightPairs implementation Source: https://github.com/akabenko/gshader-library/blob/main/_autodocs/api-reference/dynamic-light-wrapper.md Implementation of the three global getter functions. render.GetDynamicLights returns an array of cached lights, optionally filtered by ELight status. render.GetDynamicLight returns a single light by index and ELight flag, or nil if not found. render.DynamicLightPairs returns an iterator pair for the weak-valued light cache. ```lua function render.GetDynamicLights(elight) local list = {} local n = 0 for _, light in next, lightCache do local addToList = elight == nil or (elight == true and light:IsELight()) or (elight == false and not light:IsELight()) if addToList then n = n + 1 list[n] = light end end return list end function render.GetDynamicLight(index, isELight) return lightCache[get_cache_index(index, isELight)] end function render.DynamicLightPairs() return next, lightCache end ``` -------------------------------- ### shaderlib.GetProjMatrix( table viewSetup ) Source: https://github.com/akabenko/gshader-library/wiki/shaderlib Returns the projection matrix. ```APIDOC ## shaderlib.GetProjMatrix( table viewSetup ) ### Description Returns the projection matrix based on the given view setup. ### Parameters - **viewSetup** (table) - Required - The view setup table from render.GetViewSetup. ### Returns - **Matrix** - The projection matrix. ``` -------------------------------- ### shaderlib.GetViewProjMatrix( table viewSetup ) Source: https://github.com/akabenko/gshader-library/wiki/shaderlib Returns the view-projection matrix. ```APIDOC ## shaderlib.GetViewProjMatrix( table viewSetup ) ### Description Returns the view-projection matrix based on the given view setup. ### Parameters - **viewSetup** (table) - Required - The view setup table from render.GetViewSetup. ### Returns - **Matrix** - The view-projection matrix. ``` -------------------------------- ### Create shadow map render target with GetRenderTargetEx Source: https://github.com/akabenko/gshader-library/wiki/Shader-examples Creates a 4096x4096 render target for the shadow map. Uses IMAGE_FORMAT_R32F and MATERIAL_RT_DEPTH_ONLY because hardware shadow maps are not supported (see #3067). The bit.bor flags configure the render target format. ```lua local shadowmap_size = 4096 IMAGE_FORMAT_R32F = 27 local rt_shadowmap = GetRenderTargetEx( "_rt_MyShadowMap", shadowmap_size, shadowmap_size, RT_SIZE_LITERAL, MATERIAL_RT_DEPTH_ONLY, bit.bor(4, 8, 256, 512), 0, IMAGE_FORMAT_R32F ) ``` -------------------------------- ### Render shadow map with render.RenderView and PreRender hook Source: https://github.com/akabenko/gshader-library/wiki/Shader-examples Renders the shadow map from the sun's direction using an ortho projection. Sets up a viewSetup with ortho parameters, disables shadowcontroller shadows, and overrides all materials with the Z-buffer material. Uses render.RenderView inside a PreRender hook. Requires the my_z_buffer material and the render target from step 1. ```lua local mat_zbuffer = Material("my_z_buffer") local cam_dist = 10500 local scale = 0.5 -- config local ortho_scale = shadowmap_size * scale local viewSetup = { znear = 0.01; zfar = 32768; ortho = { left = -ortho_scale; right = ortho_scale; bottom = ortho_scale; top = -ortho_scale; }; origin = vector_origin; angles = angle_zero; bloomtone = false; dopostprocess = false; viewid = 6; drawviewer = true; drawviewmodel = false; x = 0; y = 0; w = shadowmap_size, h = shadowmap_size; } render.SetShadowsDisabled( true ) -- disable shadowcontroller shadows hook.Add("PreRender", "MyShadowMapping", function() local sun_info = util.GetSunInfo() if !sun_info then return end local L = sun_info.direction local eyepos = EyePos() local sun_angle = L:Angle() local shadows_pitch = sun_angle.pitch local shadows_yaw = sun_angle.yaw local shadows_roll = sun_angle.roll local LookAt = Angle(shadows_pitch,shadows_yaw,shadows_roll) local ang = ( (eyepos - LookAt:Forward()) - eyepos):Angle() local sun_dir = ang:Forward() local pos = eyepos + (-sun_dir * cam_dist) viewSetup.origin = eyepos + (-sun_dir * cam_dist) viewSetup.angles = ang local ViewProj = shaderlib.GetViewProjOrthoMatrix( viewSetup ) hook.Run( "PreDrawMyShadowMap", ViewProj, L ) render.MaterialOverride( mat_zbuffer ) render.BrushMaterialOverride( mat_zbuffer ) render.ModelMaterialOverride( mat_zbuffer ) render.WorldMaterialOverride( mat_zbuffer ) render.PushRenderTarget(rt_shadowmap) render.Clear(255,0,0,0) render.ClearDepth() render.OverrideDepthEnable( true, true ) -- fix writing depth of screenspace_general render.RenderView( viewSetup ) render.OverrideDepthEnable( false, false ) render.PopRenderTarget() render.MaterialOverride() render.BrushMaterialOverride() render.ModelMaterialOverride() render.WorldMaterialOverride() end) ``` -------------------------------- ### shaderlib.GetViewMatrix(pos, ang) Source: https://github.com/akabenko/gshader-library/blob/main/_autodocs/api-reference/shaderlib-core.md Builds a view matrix with D = -ang:Forward(). Default view matrix for use on ViewProj. ```lua function shaderlib.GetViewMatrix(pos, ang) ```