Do static variables not work the way I think?

  • Posts: 20
2 years 9 months ago - 2 years 9 months ago #1 by Citizenkane
I've spent all day trying to debug one of my shaders, and am completely stuck. I've stripped my shader down to essentially nothing, but I still don't understand why this is happening.

This shader colors the entire screen cyan, until the 'I' key is pressed. When that happens, myInt is set to 1, and the screen turns magenta. But pressing 'I' again turns the screen back to cyan. HOW? Why, or where, is myInt getting set back to 0?
#include "ReShade.fxh"

uniform bool bInventoryKeyToggle <source="key"; keycode=0x49; toggle=true;>; // I (default INVENTORY key)

static int myInt = 0;

float4 MyShader(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target {
    
	if( bInventoryKeyToggle ){		
		myInt = 1;
	}
	
	float3 col;
	if( myInt == 0 ){
		col = float3(0.0,1.0,1.0); //CYAN
	}
	if( myInt == 1){
		col = float3(1.0,0.0,1.0); //MAGENTA
	}
    
    return float4(col, 1.0);
}

technique MyTechnique {
    pass {
        VertexShader = PostProcessVS;
        PixelShader = MyShader;
    }
}

Please Log in or Create an account to join the conversation.

  • Posts: 20
2 years 9 months ago - 2 years 9 months ago #2 by Citizenkane
Alright, so I guess static variables reset each time the shader runs, or at least each frame. I thought that, for static variables, the compiler reserves memory so the variable preserves it's value. Evidently not?

Is there any way at all to capture data from a pixel shader to use again in the same shader during the next pass/next frame?

Please Log in or Create an account to join the conversation.

  • Posts: 3638
2 years 9 months ago #3 by crosire
No. That's not how GPUs work. The only way to store data is to render to a texture and then sample that texture the next frame. Note that you can't read and write to the same texture in the same pass, so that would need to be split into multiple passes as well.
The "static" keyword means that the variable persists between function calls during the execution length of the shader. It does not persists between shader invocations! There is no global memory that you can read or write from/to. Think about it this way: your shader is executed thousands of times at the same time for every pixel on screen. How would all those instances synchronize access to a single memory location? It can't work.
The following user(s) said Thank You: Citizenkane

Please Log in or Create an account to join the conversation.

  • Posts: 20
2 years 9 months ago #4 by Citizenkane
Yeah, I understand now, thank you for your explanation!

Please Log in or Create an account to join the conversation.