
local _Material		= Material( "pp/sunbeams" )
local tex_MotionBlur	= render.GetMoBlurTex0()

/*---------------------------------------------------------
   Register the convars that will control this effect
---------------------------------------------------------*/   
CreateClientConVar( "pp_sunbeams", 				"0", 		true, false )
CreateClientConVar( "pp_sunbeams_darken", 		"0.95", 	false, false )
CreateClientConVar( "pp_sunbeams_multiply", 	"1.0", 		false, false )
CreateClientConVar( "pp_sunbeams_sunsize", 		"0.075", 	false, false )


function DrawSunbeams( darken, multiply, sunsize, sunx, suny )

	if ( !render.SupportsPixelShaders_2_0() ) then return end
	
	render.UpdateScreenEffectTexture()

	_Material:SetMaterialFloat( "$darken", darken )
	_Material:SetMaterialFloat( "$multiply", multiply )
	_Material:SetMaterialFloat( "$sunx", sunx )
	_Material:SetMaterialFloat( "$suny", suny )
	_Material:SetMaterialFloat( "$sunsize", sunsize )
	
	render.SetMaterial( _Material )
	render.DrawScreenQuad()
	
end

local function DrawInternal()

	if ( GetConVarNumber( "pp_sunbeams" ) == 0 ) then return end
	if ( !GAMEMODE:PostProcessPermitted( "sunbeams" ) ) then return end
	if ( !render.SupportsPixelShaders_2_0() ) then return end
	
	local sun = util.GetSunInfo()
	
	if (!sun) then return end
	if (sun.obstruction == 0) then return end
	
	local sunpos = EyePos() + sun.direction * 4096
	local scrpos = sunpos:ToScreen()
	
	local dot = (sun.direction:Dot( EyeVector() ) - 0.8) * 5
	if (dot <= 0) then return end
	
	DrawSunbeams( GetConVarNumber( "pp_sunbeams_darken" ),
				  GetConVarNumber( "pp_sunbeams_multiply" ) * dot * sun.obstruction,
				  GetConVarNumber( "pp_sunbeams_sunsize" ), 
				  scrpos.x / ScrW(), 
				  scrpos.y / ScrH()
				  );

end

hook.Add( "RenderScreenspaceEffects", "RenderSunbeams", DrawInternal )