Z buffer working in OpenGL After Z-Buffer Testing does the fragment shader run on the discarded fragments?
Does the Z-Test happen after the fragment shader runs?

Please, tell me the step by step events that occur in the Z-Test.

Also what is early Z-Test and how to achieve it?
When depth testing is enabled, the testing occurs after the fragment shader executes. The procedure is relatively simple (and spelled out pretty well here):


Get depth of fragment
Test against depth buffer
Discard if it fails


Early-z discard is when a rasterizer discards a fragment before a fragment shader runs because it's clear early on that it won't pass the depth test. However, the rasterizer can't safely do this if certain things happen (such as calling discard() or modifying the fragment depth in a fragment shader). This is a hardware optimization and isn't required to occur unless you force it with OpenGL 4.2 or with an extension.

There are things that can prevent early-z discard from occurring. To achieve it:


Don't use discard() in a fragment shader
Don't modify the depth of a fragment in a fragment shader
Don't use alpha testing (deprecated)
Make sure you have depth testing turned on
Make sure you have a depth buffer