Reproducing Terrain.SampleHeight() for custom mesh terrains

Hi folks! I’m trying to write a method which mimics GetHeights() or SampleHeight(), but which works on my own generated mesh terrains. They’re functionally similar, just subdivided planes. Each vertex’s y position is set by a float[,] heightmap, just like built-in terrains.

I’m finding that similar issues are a common rite-of-passage thing, but I get the feeling I’m missing some simple algorithm that would be lightning fast given that this is a very specific case. It’d be so easy to sample these points using raycasting, but I’m hoping for a less expensive solution based on some mesh-level math wizardry. Am I wrong in assuming this is wise?

For bonus points, could my solution to this also provide a foundation for reproducing GetSteepness() or GetInterpolatedNormal()? Will post again if I have any success on my own. Thanks for any ideas / insight!

I can easily find and reference the nearest vertex because the data structure I use allows this to be really cheap. Since the necessary projections are all XZ parallel, based on which direction I rounded to arrive at the nearest vertex, I can discover the quad the target position is in pretty darn quick and cheap.

Doing some “fancy collegiate arithmetic” picks the correct three points describing the tri and does a weighted interpolation for a height value.

This approach applies to a float[,] heightmap data set, but would also be useful - if slightly more expensive - when working with mesh.vertices in similar cases.