Clamp Sampling to Inside Source Rectangle

In my 2D game, I have a glitch effect shader that samples a texture 3 times per pixel, and each time I sample with a different UV offset. I would then combine the samples into a glitchy look. I’m also using a texture atlas (i.e., all my textures are on one big texture, and I use source rectangles to choose which “subtexture” to render).

This unfortunately means that my pixel shader might sample pixels from outside of the source rectangle, which causes the shader to sample pixels on the atlas texture that belongs to other “subtextures”.

Is there a way to prevent the pixel shader from sampling outside of the source rectangle passed to SpriteBatch?

I thought of using effect parameters to store the source rectangle and clamp the offseted UV in my pixel shader, but I would need to begin a new sprite batch for each subtexture that uses this glitch effect, as each “subtexture” would have a different source rectangle.

I also thought of passing the source rectangle information into the vertex data. Then I could use a custom vertex shader like the one in this post I created. This is the best way I can think of, but I’m wondering if there is a better way to achieve this.