Instantly share code, notes, and snippets.

Created October 12, 2018 09:53
Show Gist options
• Save BWibo/2614b89b25827908fcac57efc525cbc5 to your computer and use it in GitHub Desktop.
SFCGAL constraint delaunay triangulation

# Constraint Delaunay Triangulation for PostGIS using SFCGAL

As discussed in this StackExchange question, there is a function available in SFCGAL that performs a Constrained Delaunay Triangulation. Some explanation and examples are available here.

## Setup

There is a secret function available in SFCGAL that just needs to be exposed to use it. Make sure to set the correct PostGIS version in '\$libdir/postgis-2.4.

CREATE OR REPLACE FUNCTION public.st_triangulate2dz(geometry)
RETURNS geometry AS
'\$libdir/postgis-2.4', 'sfcgal_triangulate'
LANGUAGE c IMMUTABLE STRICT
COST 100;

## Usage example

The example code below creates a triangulation for a set of points and a polygon. The edges of the polygon are not cut by the triangulation.

SELECT st_triangulate2dz(ST_GeomFromText(
'GEOMETRYCOLLECTION(
POLYGON Z((5 5 -20, 10 5 -20, 10 10 -20, 5 10 -20, 5 5 -20)),
POINT Z(0 0 0),
POINT Z(1 2 1),
POINT Z(4 5 8),
POINT Z(6 0 3),
POINT Z(6 -5 2),
POINT Z(5 1 3),
POINT Z(10 4 2),
POINT Z(11 0 8),
POINT Z(12 3 8),
POINT Z(12 6 9),
POINT Z(15 7 9),
POINT Z(10 11 9),
POINT Z(12 11 8),
POINT Z(18 0 5),
POINT Z(9 16 3),
POINT Z(6 11 6),
POINT Z(-3 0 3),
POINT Z(-2 8 5),
POINT Z(4 18 9),
POINT Z(18 23 5),
POINT Z(20 12 6)
)'
));

Resulting triangulation in 2D. The polygon is highlighted green.

Resulting triangulation in 3D. The polygon is highlighted purple.