accurate getGroundHeight algorithm for GeoMipTerrain

i remember when i tested Panda1.72 using getElevation to limit my camera from droping below ground, when i moved the camera (i use custom code to drive the cam, not Panda built-in driver) along the terrain, the camera suddenly moved up at some point, leaving the ground. i also remember other users mentioned about “stair-case” like movement if they use getElevation instead of collision traverser.
that was because getElevation uses surrounding vertices (i don’t remember how many vertices) and linearly interpolate to get the height value. but the actual geometry is formed by triangles which are defined by 3 point. to get accurate height on a triangle, we should use the triangle which a vertical line (defined by XY pos) intersect with.
the algorithm i posted does find the actual triangle then use the 3 points and linearly interpolate. the result is the actual Z pos in the triangle given a certain XY pos. using this can make the camera always stick to the rendered ground, so can it make the roaming ralph stick to the ground, and other uses.
because GeomipTerrain divides the quads in different directions (into triangles) at different pos of a block, the algorithm takes several lines of code to decide which 3 points form the target triangle. hence the “split, upper” variables in the function posted.