Search Unity

Anyone had any success with a shader to only render what is inside another mesh (a box)

Discussion in 'Shaders' started by Reddevildragg, Aug 19, 2020.

  1. Reddevildragg

    Reddevildragg

    Joined:
    May 19, 2014
    Posts:
    50
    Has anyone had any success with creating a shader(s) that will set objects to only render when they are within 1 of X number of bounds in a 3d space. If a mesh partially enters the bounds then it should only render the polygons that are within the bounds.

    I have looked into doing this with a stencil buffer and had some success with it working. However when looking though the shape at a different angle you were able to see objects in the distance as the stencil was working from the screen position not the world position.

    I believe i need 2 shades for this (1 for the mask and 1 for the object) as if an object is not marked as a "hideable" object then i want it to render as normal.
     
  2. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,348
    As you noticed, stencils are a purely 2D effect. They work on the 2D position of the screen pixels, not the 3D position of the objects being rendered. You can kind of use depth only passes to mask the depth position as well, but you can only really prevent objects from rendering further from some invisible mesh, not confine it to a 3D volume. The depth buffer is also 2D and can only record a single depth per pixel.

    The only real solution is to have the shader on the objects you want clipped to be aware of a 3D volume and do the clipping in the shader itself. A box is fairly straight forward, especially one that's axis aligned. You just need to give the shader the center and range of the box and clip if the fragment position is further away from the position than the box's range. If it's not axis aligned, it's just a matter of passing to the shader the transform matrix of the box via c# and transforming the world position of the fragment to the "box space" position and clipping there.