Skip to content

Instantly share code, notes, and snippets.

@jkulhanek
Created August 3, 2022 17:02
Show Gist options
  • Save jkulhanek/2d07aae5937371b26ecfe391139cc780 to your computer and use it in GitHub Desktop.
Save jkulhanek/2d07aae5937371b26ecfe391139cc780 to your computer and use it in GitHub Desktop.
Numpy computing 2D SDF function of a polygon
import numpy as np
def compute_sdf_polygon(vertices, points):
vertices = vertices[:, None, ...]
points = points[None, :, ...]
d = np.sum((points[0] - vertices[0]) * (points[0] - vertices[0]), -1)
vert_offset = np.concatenate([vertices[-1:], vertices[:-1]], 0)
e = vert_offset - vertices
w = points - vertices
b = w - e * np.clip(np.sum(w * e, -1) / np.sum(e * e, -1), 0., 1.)[..., None]
b_dot = np.sum(b * b, -1)
d = np.minimum(d, np.min(b_dot, 0))
c = np.stack([
points[..., 1] > vertices[..., 1],
points[..., 1] <= vert_offset[..., 1],
e[..., 0] * w[..., 1] > e[...,1] * w[...,0]], -1)
s = np.where(np.logical_or(np.all(c, -1), np.all(np.logical_not(c), -1)), -1, 1)
s = np.prod(s, 0)
return s * np.sqrt(d)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment