Making masks with shading nodes that accounts camera ray I have a problem that I want to solve if possible.
I have 2 objects (Boxes), Obj2 is above Obj1 (almost touching each other on Obj1's Z+ face). I want to draw Obj2 only in where Obj1 is visible to camera ray. So if I can see Obj1 through X-Ray the Obj2 is drawn.
I know that OpenGL has stencils, this is what I want, but I didn't find it in Blender.

Example:

Viewport is what I have in Blender.
Mask Passed is what I will have in the render (after shading).
Mask Failed is what will not be drawn (This is what failed the comparison inside the stencil, like a inverse mask)

I think Booleans won't work here because it has nothing to intersect with.
So my question is: Is this possible without hardcoding them both in Eevee and Cycles? If I change the Loc/Rot/Scale of the camera the stencil must be calculated automatically.
Thanks
Solution

The mask effect can be achieved with rendering objects in different scenes and combining them in compositor after.

Compositing with Eevee:



Compositing with Cycles: