Skip to content

Commit

Permalink
Merge pull request #151 from csiro-coasts/optimise-triangulation
Browse files Browse the repository at this point in the history
Generate a fan triangulation for convex polygons
  • Loading branch information
mx-moth authored Sep 4, 2024
2 parents 2d2248c + c8b9fcb commit 4abcb69
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
2 changes: 2 additions & 0 deletions docs/releases/development.rst
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,5 @@ Next release (in development)

* Fix invalid geometry being generated for 'river' cells
in CFGrid2D datasets with no cell bounds (:pr:`154`).
* Improved speed of triangulation for convex polygons
(:pr:`151`).
14 changes: 14 additions & 0 deletions src/emsarray/operations/triangulate.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"""
from typing import cast

import numpy
import xarray
from shapely.geometry import LineString, MultiPoint, Polygon

Expand Down Expand Up @@ -149,6 +150,19 @@ def _triangulate_polygon(polygon: Polygon) -> list[tuple[Vertex, Vertex, Vertex]
if not polygon.is_simple:
raise ValueError("_triangulate_polygon only supports simple polygons")

# The 'ear clipping' method used below is correct for all polygons, but not
# performant. If the polygon is convex we can use a shortcut method.
if polygon.equals(polygon.convex_hull):
# Make a fan triangulation. For a polygon with n vertices the triangles
# will have vertices:
# (1, 2, 3), (1, 3, 4), (1, 4, 5), ... (1, n-1, n)
exterior_vertices = numpy.array(polygon.exterior.coords)[:-1]
num_triangles = len(exterior_vertices) - 2
v0 = numpy.broadcast_to(exterior_vertices[0], (num_triangles, 2))
v1 = exterior_vertices[1:-1]
v2 = exterior_vertices[2:]
return list(zip(map(tuple, v0), map(tuple, v1), map(tuple, v2)))

# This is the 'ear clipping' method of polygon triangulation.
# In any simple polygon, there is guaranteed to be at least two 'ears'
# - three neighbouring vertices whos diagonal is inside the polygon.
Expand Down

0 comments on commit 4abcb69

Please sign in to comment.