# Greiner-Hormann

Efficient polygon clipping algorithm

View the Project on GitHub w8r/GreinerHormann

## Greiner-Hormann clipping algorithm

The algorithm is a rough implementation of Gunther Greiner a Kai Hormann "Efficient Clipping of Arbitrary Polygons". You can use it in browser or node.

• Does AND, OR, XOR (intersection, union, difference, if you're human)
• Plays nicely with Leaflet, comes with an adaptor for it
• Handles non-convex polygons and multiple clipping areas
• ~3kb compressed, no dependencies

## Examples

### XOR (diff)

There are 3 bundles in the dist dir:

• greiner-hormann(.min).js - algorithm, requires Array.isArray polyfill, you can find it in libs
• greiner-hormann.leaflet(.min).js - algorithm + adapter for Leaflet.

All minified versions are compiled with Google Closure Compiler in ADVANCED mode.

## Usage

### npm

\$ npm install greiner-hormann
<script src="dist/greiner-hormann.leaflet.min.js"></script>
<script>
...
var intersection = greinerHormann.intersection(source, clip);
var union        = greinerHormann.union(source, clip);
var diff         = greinerHormann.diff(source, clip);

...

if(intersection){
if(typeof intersection[0][0] === 'number'){ // single linear ring
intersection = [intersection];
}
for(var i = 0, len = intersection.length; i < len; i++){
}
}
</script>

## Results

The output of the binary operation could be one or several linear rings, or null, you have to check.

## Code

Although being adapted for use with leaflet, algorithm uses it's own polygon and vertex abstraction, mainly for the better understanding of the algorithm and flexibility. Maybe I'll provide a plain L.PolyUtils. ... implementation for that in the future.

## Development

It's an early version, some implications may occur when trying to make operation with polygons that are crossing the date change line, for that we'll have to dissect the polygons and treat the parts separately. Also some adaptation is needed to handle holes(entry/exit points analysis).

Following will re-bundle and re-compile the code in the dist folder. Be careful, Google Closure compiler won't output any errors or warnings with current settings.

\$ make

## Authors and Contributors

Alexander Milevski @w8r

Thanks to @helderco