location based opacity: using output of mask to sample a texture at same location?

I need to carve portals / entrances thru arbitrary geometry at runtime. For that I used the location based opacity tutorial as a starting point: A new, community-hosted Unreal Engine Wiki - Announcements - Epic Developer Community Forums

In my case, instead of a spheremask I use a box2d mask.
That is, I have the following material function:

Which I then use in the material that I apply to the surface being carved like this:

Finally, I have a static mesh actor subclass which updates the center and bounds parameters whenever it moves or changes size. And this works as expected: If I make a rectangular box and make it intersect any static mesh with the above material, the box “carves” into the mesh.

What I’d like to do though, is to not just have a square mask for the cutout. Instead, I have a texture of an irregular shape (made of 1s and 0s for use as an opacity mask) and I want to use the output of the box mask function to sample into this texture, but at the same location as the mask and with the whole texture contained within the bounds of the mask.

The main issue is that I can’t figure out how to come up with the right uv coordinates for the mask sampling. Basically I need to be able to sample only for the pixels within the box2d mask (meaning where the box2d outputs 1).

Ok I got it.

The basic idea is that from the mask area as given by the center and bounds parameters I can figure out how to map to the UV range [0,1]:

  1. the lower bound is center - bounds / 2.
  2. for each world space pixel p, I create p’ by subtracting the lower bound to p.
  3. then I divide each p’ by the range which is bounds.
  4. At this point p’ will be either within range [0,1] or outside the range.
  5. I also subtract this from 1 cause I had the coordinate origin flipped :p.

With the above I can sample a texture at the area given by the center and bounds parameters. I then used that along with the standard box mask function output to use the texture as a means to shape the opacity mask.

My final material function is like this:

And I use it in my material like so: