Examples

Distance to simplex

using StaticArrays
using DistanceQueries

a = rand(SVector{2})                        # line segment in n-d
b = rand(SVector{2})

x = rand(SVector{2})

d, t = distancetolinesegment(x, (a, b))

p = (1 - t) * a + t * b                     # projection point
@assert norm(p - x) ≈ d                     # distance

d, λ = distancetosimplex(x, (a, b))
p = λ[1] * a + λ[2] * b                     # projection point
@assert norm(p - x) == 0                    # distance

@assert sum(λ) == 1                         # barycentric coordinates
@assert λ[2] == t
using StaticArrays
using DistanceQueries

a = rand(SVector{3})                        # triangle in 2d or 3d
b = rand(SVector{3})
c = rand(SVector{3})

x = rand(SVector{3})

d, t = distancetotriangle(x, (a, b, c))
d, λ = distancetosimplex(x, (a, b, c))      # synonym

p = λ[1] * a + λ[2] * b + λ[3] * c          # projection point
@assert norm(p - x) == d                    # distance

@assert sum(λ) == 1                         # barycentric coordinates
Note

distancetosimplex provides a common interface.

Distance to sets of simplices

Points

using DistanceQueries

x = rand(2, 100)
tree = kdtree(Val(2), x)                    # fix dimension to 2d

y = rand(2)

d, j = nearest(tree, y)                     # distance and index

@assert d == norm(y - x[:, j])

Line segments

using DistanceQueries
using BaseUtilities

x = rand(2, 100)                                        # vertices
sidx = Int[...; ...]                                    # segment indices in cols

tree = kdtree(scmatrix(Val(2), x), scmatrix(Val(2), sidx))

y = rand(2)
d, j, λ = nearest(tree, y)

p = λ[1] * x[:, sidx[1, j]] + λ[2] * x[:, sidx[2, j]]   # projection point
@assert d == norm(y - p)                                # distance

Triangles

using DistanceQueries
using BaseUtilities

x = rand(3, 100)                                        # vertices in 3d
t = Int[...; ...; ...]                                  # triangle indices in cols

tree = kdtree(scmatrix(Val(3), x), scmatrix(Val(3), t))

y = rand(3)
d, j, λ = nearest(tree, y)

p = sum(λ[i] * x[:, t[i, j]] for i in 1:3)              # projection point
@assert d == norm(y - p)                                # distance

Point location

using DistanceQueries
using BaseUtilities

x = rand(2, 100)                                        # vertices in 2d
t = Int[...; ...; ...]                                  # triangle indices

tree = kdtree(scmatrix(Val(2), x), scmatrix(Val(3), t))

y = rand(2)
d, j, λ = nearest(tree, y)

(d == 0) || error("out of triangulated domain")

# triangle j, barycentyric coordinates λ

p = sum(λ[i] * x[:, t[i, j]] for j in 1:3)              # projection point
@assert p == y