Window space to NDC is:

x_{NDC} = 2*(x_{win} - viewport.x)/viewport.width - 1

y_{NDC} = 2*(y_{win} - viewport.y)/viewport.height - 1

z_{NDC} = 2*depth - (gl_DepthRange.near + gl_DepthRange.far) / gl_DepthRange.diff

You can’t recover clip coordinates from NDC because projective division loses information; clip space has 4 components, NDC only has 3.

If you’re trying to re-create the texture-mapping calculation, you can recover barycentric coordinates given the clip-space x, y and w coordinates for the three vertices of a triangle plus the window-space (or NDC) x and y coordinates of a point within a triangle. From there, you can recover the clip-space z coordinate or any other attribute value obtained by interpolation.

If (α,β,γ) are barycentric coordinates subject to α+β+γ=1, and (x1,y1,z1,w1), (x2,y2,z2,w2) and (x3,y3,z3,w3) are the vertices of a triangle, then

\begin{pmatrix}x_{clip} \\ y_{clip} \\ w_{clip} \end{pmatrix} =
\begin{pmatrix}x1 & x2 & x3 \\ y1 & y2 & y3 \\ w1 & w2 & w3 \end{pmatrix}
\begin{pmatrix}\alpha \\ \beta \\ \gamma \end{pmatrix}

(note that we don’t care about Z here). Given clip-space x,y,w, we can recover barycentric coordinates using the inverse of the above 3×3 matrix:

\begin{pmatrix}\alpha \\ \beta \\ \gamma \end{pmatrix} =
\begin{pmatrix}x1 & x2 & x3 \\ y1 & y2 & y3 \\ w1 & w2 & w3 \end{pmatrix}^{-1}
\begin{pmatrix}x_{clip} \\ y_{clip} \\ w_{clip} \end{pmatrix}

The transformation from clip-space to NDC is just

x_{NDC} = x_{clip} / w_{clip}

y_{NDC} = y_{clip} / w_{clip}

Note that we can’t recover clip coordinates from NDC because the transformation loses information. However, we can say that

x_{clip} = w_{clip} x_{NDC}

y_{clip} = w_{clip} y_{NDC}

without actually knowing the value of w_{clip}. And from that:

\begin{aligned}
\begin{pmatrix}\alpha \\ \beta \\ \gamma \end{pmatrix} & =
\begin{pmatrix}x1 & x2 & x3 \\ y1 & y2 & y3 \\ w1 & w2 & w3 \end{pmatrix}^{-1}
\begin{pmatrix}w_{clip} \, x_{NDC} \\ w_{clip} \, y_{NDC} \\ w_{clip} \end{pmatrix}
\\
& = w_{clip} \begin{pmatrix}x1 & x2 & x3 \\ y1 & y2 & y3 \\ w1 & w2 & w3 \end{pmatrix}^{-1}
\begin{pmatrix}x_{NDC} \\ y_{NDC} \\ 1 \end{pmatrix}
\\
& = w_{clip}
\begin{pmatrix}\alpha' \\ \beta' \\ \gamma' \end{pmatrix}
\\
\text{where}
\\
\begin{pmatrix}\alpha' \\ \beta' \\ \gamma' \end{pmatrix} & =
\begin{pmatrix}x1 & x2 & x3 \\ y1 & y2 & y3 \\ w1 & w2 & w3 \end{pmatrix}^{-1}
\begin{pmatrix}x_{NDC} \\ y_{NDC} \\ 1 \end{pmatrix}
\end{aligned}

And w_{clip} can be found from the fact that α+β+γ=1

=> w_{clip} = 1/(α’+β’+γ’).