
class CSSFlashBlinding extends Mutator;

var Texture BlindTexture;
var Color BlindColor;
var CSSFlashBlindEffect BlindEffect;
var float curLength, curStrength;
var bool bPendingHUDRegistration;
var PlayerPawn PlayerOwner;
var HUD MyHUD;
var ChallengeHUD MyChallengeHUD;

simulated function PostRender(Canvas C)
{
	Super.PostRender(C);
	if (PlayerOwner == None)
		return;
	
	if (BlindEffect == None || BlindEffect.bDeleteMe || !BlindEffect.IsStrongestBlinding())
		BlindEffect = FindStrongestBlinding(PlayerOwner);
	
	if (BlindEffect != None) 
	{
		curLength = BlindEffect.BlindLength - BlindEffect.curLength;
		curStrength = BlindEffect.curStrength;
	}
	if (BlindEffect == None || curLength <= 0)
		return;
	
	C.Style = ERenderStyle.STY_Translucent;
	C.SetPos(0, 0);
	C.DrawColor = BlindColor * FClamp(curStrength, 0, 1);
	C.DrawRect(BlindTexture, C.SizeX, C.SizeY);
}

simulated function Tick(float DeltaTime)
{
	if (Level.NetMode == NM_Client && curLength > 0) 
	{
		curStrength = curStrength * FMax(0, curLength - DeltaTime) / curLength;
		curLength -= DeltaTime;
	}

	if (Level.NetMode != NM_DedicatedServer && !bHUDMutator && bPendingHUDRegistration)
		RegisterHUDMutator();
}

simulated function RegisterHUDMutator()
{
	local PlayerPawn P;
	local Mutator M;
	
	bPendingHUDRegistration = False;
	
	if (PlayerPawn(Owner) != None) 
	{
		P = PlayerPawn(Owner);
		if (P.MyHUD != None) 
		{
			For (M = P.MyHUD.HUDMutator; M != None; M = M.NextHUDMutator)
				if (M.Class == Class)
					break;
			if (M == None || M.Class != Class) 
			{
				NextHUDMutator = P.MyHUD.HUDMutator;
				MyHUD = P.MyHUD;
				MyChallengeHUD = ChallengeHUD(MyHud);
				P.MyHUD.HUDMutator = Self;
				PlayerOwner = P;
				bHUDMutator = True;
			}
		}
	}
	else ForEach AllActors(class'Engine.PlayerPawn', P)
		if (P.MyHUD != None) 
		{
			For (M = P.MyHUD.HUDMutator; M != None; M = M.NextHUDMutator)
				if (M.Class == Class)
					break;
			if (M != None && M.Class == Class)
				continue;	// already registered, check next PlayerPawn
			NextHUDMutator = P.MyHUD.HUDMutator;
			MyHUD = P.MyHUD;
			MyChallengeHUD = ChallengeHUD(MyHud);
			P.MyHUD.HUDMutator = Self;
			PlayerOwner = P;
			bHUDMutator = True;
		}
	
	if (!bHUDMutator) 
	{
		bPendingHUDRegistration = True;
		Enable('Tick');
	}
}

simulated function CSSFlashBlindEffect FindStrongestBlinding(Pawn Other)
{
	local Inventory Inv;
	local CSSFlashBlindEffect Best;
	
	For (Inv = Other.Inventory; Inv != None; Inv = Inv.Inventory)
		if (Inv.IsA('CSSFlashBlindEffect') && CSSFlashBlindEffect(Inv).bBlinding && !Inv.bDeleteMe
				&& (Best == None || Best.curStrength < CSSFlashBlindEffect(Inv).curStrength))
			Best = CSSFlashBlindEffect(Inv);
	return Best;
}

defaultproperties
{
   BlindTexture=Texture'UWindow.WhiteTexture'
   BlindColor=(R=255,G=255,B=255,A=0),
   bPendingHUDRegistration=True
   bAlwaysRelevant=True
   bNetTemporary=True
   RemoteRole=ROLE_SimulatedProxy
}
