import random
import math


def random_triangle_sample(tm, index):
    """Randomly sample a point inside of a triangle without geometric bias
    
    Parameters
    ----------
    tm : geomproc.mesh
        Triangle mesh
    index : float
        Index of the triangle in the mesh to be sampled

    Returns
    -------
    point : array_like
        A random 3D point on the surface of the triangle and inside its
        boundaries
    """

    # Reference: Osada et al., "Shape distributions", TOG 2002, page 814.

    # Get two random numbers
    r1 = random.random()
    r2 = random.random()

    # Get three vertices of the selected face
    v0 = tm.vertex[tm.face[index, 0], :]
    v1 = tm.vertex[tm.face[index, 1], :]
    v2 = tm.vertex[tm.face[index, 2], :]

    # Get random point without bias
    point = (1 - math.sqrt(r1))*v0 + math.sqrt(r1)*(1 - r2)*v1 + math.sqrt(r1)*r2*v2
    return point