ifsnop / martinez-rueda-php
Robust and tested library for boolean operations on polygons (union, intersection, difference, xor)
Requires
None
Requires (Dev)
- phpstan/phpstan: ^2.1
- phpunit/phpunit: ^10.0
- shipmonk/dead-code-detector: ^0.14.0
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
Robust and tested library for boolean operations on polygons (union, intersection, difference, xor) in PHP.
Some improvements over other libraries: This one is tested (see end-to-end directory) and optimized to use polygons with large amount of vertex (ie, binary search when doing intersections between segments).
This library can use arrays with polygons, geojson strings or geojson files directly.
Release notes: CHANGELOG.md.
Índice
- Arquitectura general
- Clases principales
- Flujo de procesamiento
- API pública
- Ejemplos de uso
- Optimizaciones implementadas
- Suggested improvements
- Profilig
- Testing A. Tutorials and Notes
Arquitectura general
La librería implementa un pipeline de tres fases para las operaciones booleanas:
Polígono(s) de entrada
│
▼
[FASE 1] segments()
Convierte cada polígono en segmentos con información de relleno (Fill).
Usa RegionIntersecter (self-intersection) para resolver solapamientos
internos y asignar el flag inside/outside a cada lado del segmento.
│
▼
[FASE 2] combine() / combineSelect()
Combina los segmentos de ambos polígonos mediante SegmentIntersecter,
calculando intersecciones entre los dos conjuntos y propagando el Fill
cruzado (otherFill). Luego aplica la lógica booleana (union/intersect/
difference/xor) para filtrar qué segmentos forman parte del resultado.
│
▼
[FASE 3] polygon()
Encadena los segmentos resultantes en anillos cerrados (segmentChainer),
divide anillos con auto-intersecciones, y construye el Polygon final.
Clases principales
Algorithm (final)
Clase estática central. Contiene toda la lógica de alto nivel y las operaciones públicas.
| Constante / Método | Descripción |
|---|---|
TOLERANCE = 1e-12 |
Tolerancia de longitud para comparaciones geométricas (en grados, 1e-12 ≈ 0,1 µm). |
TOLERANCE_SQRT = 1e-6 |
Tolerancia adimensional (fracción de la longitud del segmento) con la que el barrido ajusta un cruce a un extremo. Ver ISSUES.md #2. |
segments(Polygon) |
Fase 1: convierte un polígono a PolySegments. |
combine(PolySegments, PolySegments) |
Fase 2: combina dos conjuntos de segmentos. |
polygon(PolySegments) |
Fase 3: reconstruye un Polygon desde segmentos. |
union / intersect / difference / xor |
Operaciones de alto nivel sobre dos Polygon. |
unionMany(array) |
Unión de N polígonos mediante reducción balanceada. |
$precision (todas las operaciones) |
Normalización de entradas redondeadas; ver Precisión de los datos. |
findOverlappingParts(array $parts) |
Reports which parts of a multi-part geometry overlap (they would cancel under the even-odd rule); see Validating input. |
segmentChainer(array) |
Ensambla segmentos sueltos en anillos cerrados. |
splitSelfTouchingRegions(array) |
Divide anillos que se auto-tocan en ciclos simples. |
Polygon (final)
Representa un polígono como una lista de regiones (anillos), donde cada región es un array de objetos Point.
$poly->regions // array de array de Point $poly->isInverted // true = el interior lógico es el exterior geométrico $poly->numPoints // total de puntos $poly->getArray() // convierte a array [[x,y], ...] $poly->getArrayClosed() // igual pero cierra cada anillo
PolySegments (final)
Contenedor intermedio entre fases. Almacena segmentos, flag isInverted y el bounding box precalculado (bounds).
Segment (final)
Un segmento orientado entre dos Point. Contiene:
myFill: relleno respecto al polígono propio (Fill->above,Fill->below).otherFill: relleno respecto al otro polígono (solo en fase combinada).minX/maxX/minY/maxY/len2: bounding box y longitud² cacheados para rechazo temprano en intersecciones.
Point (final)
Coordenada 2D con métodos estáticos de geometría:
| Método | Descripción |
|---|---|
compare(p1, p2) |
Orden lexicográfico con tolerancia epsilon. |
collinear(p1, p2, p3) |
Test de colinealidad por área del triángulo. |
linesIntersect(a0, a1, b0, b1) |
Intersección de dos líneas; devuelve IntersectionPoint con flags alongA/alongB (-2,-1,0,1,2). |
between(p, a, b) |
¿Está p estrictamente entre a y b en el segmento? |
pointAboveOrOnLine(p, left, right) |
Test de semiplano con tolerancia. |
Fill (final)
Par de booleanos (above, below) que indica si el espacio a cada lado de un segmento está dentro del polígono.
EventList / StatusList (final)
Estructuras de datos basadas en Skip List (trait SkipListCore). EventList mantiene la cola de eventos de barrido ordenada; StatusList mantiene el estado activo de segmentos durante el barrido.
GJTools (final)
Utilidades para importar y normalizar GeoJSON:
| Método | Descripción |
|---|---|
geojsonToArray($source) |
Acepta string JSON, ruta de archivo, array o stdClass. Devuelve array de polígonos en formato [[[x,y],...],...]. |
compareCoordinates($a, $b, &$diff) |
Compara dos arrays de coordenadas punto a punto con tolerancia. |
canonicalizePolygons($polys, $precision) |
Normaliza polígonos (rotación al mínimo lexicográfico, redondeo). |
classifyRings($rings) |
Detecta relaciones interior/exterior entre anillos. |
buildPolygons($nodes, $enforceOrientation) |
Construye la estructura final respetando orientación CCW/CW. |
Flujo de procesamiento
Operación binaria típica
Algorithm::union($polyA, $polyB)
├─► normalizeInputs([$polyA, $polyB]) → Polygon[] (InputNormalizer, ver "Precisión de los datos")
├─► segments($polyA) → PolySegments $a
├─► segments($polyB) → PolySegments $b
├─► unionSegments($a, $b)
│ ├─► (bounding boxes disjuntas) concatenar segmentos de frontera
│ └─► combine($a, $b) → Segment[] (con otherFill)
│ └─► selectUnion(...) → PolySegments (segmentos filtrados)
└─► polygon(...) → Polygon resultado
Barrido de línea (Intersecter)
El núcleo del algoritmo es un barrido de línea (sweep line) de izquierda a derecha:
- Se crean eventos START y END para cada extremo de segmento.
- Los eventos se procesan en orden lexicográfico (x, luego y) desde
EventList. - Al procesar un START: se buscan vecinos en
StatusListy se calculan intersecciones con el segmento de arriba y de abajo. Si hay intersección, se divide el segmento afectado. - Al procesar un END: se eliminan de
StatusListy se emite el segmento con su Fill calculado.
Ensamblado de anillos (segmentChainer)
Usa un índice hash head → id y tail → id para encadenar segmentos en O(1) por inserción. Incluye simplificación colineal en los puntos de empalme para eliminar vértices redundantes.
API pública
Operaciones binarias
// Todos aceptan dos Polygon y devuelven un Polygon Algorithm::union(Polygon $a, Polygon $b, ?float $precision = null): Polygon Algorithm::intersect(Polygon $a, Polygon $b, ?float $precision = null): Polygon Algorithm::difference(Polygon $a, Polygon $b, ?float $precision = null): Polygon // A \ B Algorithm::xoring(Polygon $a, Polygon $b, ?float $precision = null): Polygon
Operaciones n-arias
// Al menos un polígono; con uno solo se devuelve limpio (igual que union(P, vacío)) Algorithm::unionMany(array $polygons, ?float $precision = null): Polygon Algorithm::intersectMany(array $polygons, ?float $precision = null): Polygon Algorithm::xorMany(array $polygons, ?float $precision = null): Polygon Algorithm::differenceMany(array $polygons, ?float $precision = null): Polygon // P0 \ P1 \ P2 ...
Precisión de los datos ($precision)
Cuando las coordenadas vienen redondeadas (lo normal en GeoJSON, que suele traer
7 decimales: ~1 cm), dos polígonos que comparten un borde, o un vértice que estaba
exactamente sobre la arista vecina, quedan separados por unos milímetros. Esas aristas
casi coincidentes hacen que el barrido tome decisiones contradictorias y se pierdan o
añadan regiones enteras. Para evitarlo, antes de operar se normalizan las entradas
(InputNormalizer): los vértices a menos de la tolerancia entre sí se unifican, y las
aristas que pasan a menos de la tolerancia de un vértice se parten en ese vértice.
Ninguna coordenada se mueve más que la tolerancia.
Siempre se normaliza al menos con la tolerancia aritmética de la librería
(Algorithm::TOLERANCE, 1e-12): los puntos que la librería considera iguales pasan a
ser idénticos. Esto no depende de los datos, y evita que resultados encadenados (como
las capas de cobertura doble, triple... de un cálculo de coberturas, cuyos vértices
salen de operaciones distintas y difieren en unos pocos ulps) produzcan resultados
erróneos. Ver ISSUES.md #11. Encima se aplica la precisión de los datos:
$precision |
Comportamiento |
|---|---|
null (por defecto) |
Tolerancia aritmética y, si todas las coordenadas tienen como mucho entre 5 y 9 decimales, ese cuanto (1e-7 con 7 decimales). Con enteros o con precisión completa (resultados de otras operaciones) solo la aritmética. |
> 0 |
Tolerancia explícita en unidades de las coordenadas (p.ej. 1e-7), nunca menor que la aritmética. Útil con datos de precisión mezclada o en coordenadas no geográficas. |
0.0 |
Sin ninguna normalización (comportamiento anterior a ISSUES.md #2 y #11). |
No sirve fijar una tolerancia más fina que la precisión de los datos (p.ej. 1 mm con datos de 7 decimales): el redondeo desplaza los vértices hasta ~8 mm y no se corregiría. Redondear las entradas a una rejilla tampoco: es precisamente lo que crea el problema. La normalización cuesta entre un 2 % y un 9 % del tiempo. Ver ISSUES.md #2 y #11.
The library is designed for lon/lat coordinates. For projected coordinates in metres (UTM, Web Mercator) see Coordinate systems.
La API de bajo nivel (segments(), combine(), polygon()...) no normaliza.
Coordinate systems: lon/lat and projected coordinates
The library is designed for lon/lat coordinates in degrees (or any coordinates of
similar magnitude, up to a few hundred units). Its length tolerance,
Algorithm::TOLERANCE = 1e-12, is absolute. For lon/lat that is about 0.1 µm, well above
what a double can resolve at 180° (~3e-14).
Projected coordinates in metres (UTM, Web Mercator) are not supported as they are. At 4.5e6 m a double only resolves steps of ~9e-10 m, so a 1e-12 tolerance is effectively an exact comparison. Points that should coincide stay one or two ulps apart, and operations on near-coincident edges (adjacent parcels, shared borders) can lose or add whole regions. Single polygons and tiles without near-coincident edges are fine. Measured on rotated parcel grids, 240 operations each (ISSUES.md #8):
| Data | Wrong results, metres as they are | With the workaround below |
|---|---|---|
| UTM north (~4.5e6 m), 1 km parcels | 27 | 0 |
| UTM north, rounded to cm | 11 | 0 |
| UTM south (~9.5e6 m) | 28 | 0 |
| Web Mercator (~2e7 m) | 30 | 0 |
Workaround: work in local units that look like degrees.
- Subtract a round origin near the data.
- Divide by 2^17 (131072, about 131 km per unit).
- Operate, then transform the result back.
Both steps are exact in floating point: subtracting a nearby value is exact (Sterbenz),
and so is dividing or multiplying by a power of two. So the input vertices come back
bit-for-bit, and only the computed crossings carry rounding. If the data is rounded (for
example to cm), pass that resolution, converted to local units, as $precision, because
automatic detection can't recognise the decimals after the division.
$origin = [440000.0, 4490000.0]; // a round point near the data, in metres $scale = 131072.0; // 2^17: power of two, so scaling is exact $toLocal = fn(array $rings) => array_map(fn($r) => array_map( fn($p) => [($p[0] - $origin[0]) / $scale, ($p[1] - $origin[1]) / $scale], $r), $rings); $fromLocal = fn(array $rings) => array_map(fn($r) => array_map( fn($p) => [$p[0] * $scale + $origin[0], $p[1] * $scale + $origin[1]], $r), $rings); $precision = 0.01 / $scale; // data rounded to cm; use null if it isn't rounded $result = $fromLocal(Algorithm::union( Polygon::create()->fillFromArray($toLocal($utmA)), Polygon::create()->fillFromArray($toLocal($utmB)), $precision )->getArray());
Other measured options don't work as well:
- A local origin alone doesn't help (27 → 29 wrong): local metres still exceed what 1e-12 can absorb.
- Kilometres help only partly: Web Mercator still fails 15 times out of 240, because the data's own rounding (~4e-9 m) is still above 1e-12 km.
Reprojecting the data to lon/lat is the other good option. ISSUES.md #8 has a tested plan to support projected coordinates directly (a tolerance floor based on coordinate magnitude), not applied because the library's main use is lon/lat.
Regla de relleno: par-impar
Un Polygon es una lista de anillos, y un punto está dentro si lo rodea un número
impar de esos anillos (regla par-impar o even-odd, la misma que el polybooljs
original, martinez o Clipper con EvenOdd). Se aplica igual en todas las operaciones y
tiene estas consecuencias:
- Las partes solapadas de un mismo operando se cancelan: la zona común queda fuera. Lo mismo con un anillo repetido. Con tres partes solapadas, la zona cubierta por las tres vuelve a estar dentro.
- La orientación de los anillos se ignora: un anillo dentro de otro es un agujero por estar anidado, gire en el sentido que gire.
- Un anillo que se cruza consigo mismo sigue la misma regla (en una estrella de cinco puntas trazada con un solo anillo, el pentágono central queda fuera).
Un MultiPolygon con partes solapadas no es válido según OGC Simple Features, así que
otras librerías hacen cosas distintas con él: polygon-clipping y ST_MakeValid(..., 'method=structure') de PostGIS unen las partes, y JTS/GEOS lo rechazan como inválido.
Para unir partes solapadas (por ejemplo, coberturas que se superponen) hay que pasar
un polígono por parte a unionMany() o union():
// MAL si se quiere "cubierto por alguna": como un solo polígono, el solape se cancela $p = Polygon::create()->fillFromArray([$coberturaA, $coberturaB]); // BIEN: un polígono por cobertura $cubierto = Algorithm::unionMany([ Polygon::create()->fillFromArray([$coberturaA]), Polygon::create()->fillFromArray([$coberturaB]), ]);
Este comportamiento está fijado en tests/FillRuleTest.php (ver ISSUES.md #3).
To check input data for overlapping parts before operating, see
findOverlappingParts() below.
Validating input: findOverlappingParts()
Algorithm::findOverlappingParts(array $parts, ?float $precision = null, float $relativeTolerance = 1e-12): array
Because of the even-odd rule, overlapping parts of a single operand cancel each other.
That is rarely what the data means: typically several coverages, parcels or
administrative areas were stored as the parts of one MultiPolygon. findOverlappingParts()
tells you which parts overlap and by how much, so you can decide what to do. It doesn't
change any operation.
- Input: one entry per part. Each entry is a
Polygonor a coordinates array ([exterior, hole, ...], or a single ring). Keys are kept in the result. Pass the parts separately: once they're merged into a singlePolygon, there's no way to tell which ring belongs to which part. For GeoJSON, that's the original MultiPolygoncoordinatesarray, one element per part. Don't useGJTools::geojsonToArray()here, because it regroups rings by geometry. - Output: a list of
['parts' => [$keyA, $keyB], 'area' => float], one per overlapping pair. It's empty when no parts overlap. Parts that only touch (a shared edge or vertex) don't overlap, and an island inside another part's hole doesn't either. $precisionnormalizes the parts as the boolean operations do (see "Precisión de los datos"). Overlaps smaller than$relativeTolerance× the total area of the parts are treated as rounding noise. The default 1e-12 detects about 1 m² in an area of ~1 million km².- Cost: when no parts overlap, about one or two ordinary operations, because the sum of the parts' areas is compared with the area of all of them together. Only if that shows an overlap does it intersect every pair of parts whose bounding boxes overlap. For 8 radar coverages of 720 vertices that overlap heavily (22 pairs), this takes ~2 s.
- Not covered: a ring that crosses itself inside a single part, which is a different
validity problem. Inverted parts are rejected with an
InvalidArgumentException.
$geojson = json_decode(file_get_contents('coverages.geojson'), true); $parts = $geojson['features'][0]['geometry']['coordinates']; // a MultiPolygon $overlaps = Algorithm::findOverlappingParts($parts); foreach ($overlaps as $o) { printf("parts %s and %s overlap (%.6f square units)\n", $o['parts'][0], $o['parts'][1], $o['area']); } // Union the parts instead of letting the overlaps cancel: if ($overlaps) { $merged = Algorithm::unionMany(array_map(fn($p) => Polygon::create()->fillFromArray($p), $parts)); }
API de bajo nivel (para pipelines manuales)
$segs1 = Algorithm::segments($polygon1); // Fase 1 $segs2 = Algorithm::segments($polygon2); $combined = Algorithm::combine($segs1, $segs2); // Fase 2: Segment[] $selected = Algorithm::selectUnion($combined, $segs1->isInverted, $segs2->isInverted); // Selección lógica $result = Algorithm::polygon($selected); // Fase 3
La API de bajo nivel no normaliza las entradas (ver "Precisión de los datos"). Los
ejemplos de esta sección y del ejemplo 5 se ejecutan en tests/ReadmeExamplesTest.php.
Importación GeoJSON
$polygons = GJTools::geojsonToArray('/ruta/a/archivo.geojson'); // o pasando JSON directamente: $polygons = GJTools::geojsonToArray('{"type":"FeatureCollection", ...}');
Construcción manual de polígonos
$poly = Polygon::create()->fillFromArray([ [[0,0], [10,0], [10,10], [0,10]], // exterior [[2,2], [8,2], [8,8], [2,8]], // agujero ]);
Ejemplos de uso
Ejemplo 1: Unión de dos rectángulos
$rectA = Polygon::create()->fillFromArray([ [[0,0], [10,0], [10,10], [0,10]] ]); $rectB = Polygon::create()->fillFromArray([ [[5,5], [15,5], [15,15], [5,15]] ]); $resultado = Algorithm::union($rectA, $rectB); // Obtener coordenadas $coords = $resultado->getArray(); // $coords[0] → array de [x,y] del anillo exterior del resultado
Ejemplo 2: Diferencia (recorte)
$base = Polygon::create()->fillFromArray([ [[0,0], [20,0], [20,20], [0,20]] ]); $hueco = Polygon::create()->fillFromArray([ [[5,5], [15,5], [15,15], [5,15]] ]); // Base con un agujero cuadrado en el centro $resultado = Algorithm::difference($base, $hueco);
Ejemplo 3: Unión de múltiples polígonos
$polígonos = array_map(function($ring) { return Polygon::create()->fillFromArray([$ring]); }, $arrayDeAnillos); $unido = Algorithm::unionMany($polígonos);
Ejemplo 4: Desde GeoJSON
$rings = GJTools::geojsonToArray('archivo.geojson'); // Convertir a objetos Polygon $polygons = array_map(function($ringSet) { return Polygon::create()->fillFromArray($ringSet); }, $rings); $resultado = Algorithm::unionMany($polygons); $geojsonCoords = $resultado->getArrayClosed();
Ejemplo 5: Pipeline manual (máximo control)
// Procesar polígonos por separado y reutilizar segmentos $segsA = Algorithm::segments($polyA); $segsB = Algorithm::segments($polyB); // Probar varias operaciones sin re-procesar los polígonos originales $combined = Algorithm::combine($segsA, $segsB); $union = Algorithm::polygon(Algorithm::selectUnion($combined, $segsA->isInverted, $segsB->isInverted)); $inter = Algorithm::polygon(Algorithm::selectIntersect($combined, $segsA->isInverted, $segsB->isInverted));
Optimizaciones implementadas
1. Skip List para EventList y StatusList
En lugar de listas enlazadas simples (O(n) por búsqueda), se usa una Skip List con altura aleatoria hasta 32 niveles. Esto reduce búsquedas e inserciones a O(log n) amortizado, crítico en el barrido de línea donde estas operaciones son el cuello de botella.
2. Índices hash para segmentChainer
El ensamblado de anillos usa tablas hash ($headIndex, $tailIndex) indexadas por clave de punto cuantizada. El coste de buscar si un punto ya existe en alguna cadena es O(1) en lugar de O(n).
3. Bounding box cacheada en Segment
Cada Segment precalcula y almacena minX, maxX, minY, maxY y len2 al crearse (y al recalcularse tras división). El rechazo temprano por AABB en checkIntersection evita calcular la intersección algebraica entre la gran mayoría de pares de segmentos no solapantes.
4. Bounds de PolySegments y cortocircuito geométrico
PolySegments almacena el bounding box del conjunto de segmentos. Las operaciones unionSegments, intersectSegments, xorSegments y differenceSegments comprueban primero si los bounds se solapan:
- Union/XOR sin solape: concatena segmentos directamente sin intersección.
- Intersection sin solape: devuelve vacío inmediatamente.
- Difference sin solape: devuelve el operando izquierdo directamente.
5. Reducción balanceada para unionMany
reduceBalanced combina los polígonos en un árbol binario en lugar de linealmente, reduciendo el número de operaciones de O(n) a O(log n) niveles de combinación, con mejor comportamiento de memoria.
6. Ordenación por posición antes de la reducción
Antes de la reducción, los segmentos se ordenan por la coordenada X mínima de su bounding box. Esto tiende a emparejar polígonos espacialmente cercanos primero, maximizando los cortocircuitos geométricos del punto 4.
7. Simplificación colineal en el ensamblado
Al encadenar segmentos, appendChainIdx y el caso de extensión en segmentChainer eliminan vértices intermedios cuando tres puntos consecutivos son colineales. Esto reduce el número de vértices del resultado sin pérdida de precisión.
8. Cuantización de puntos para las claves hash
pointKey() cuantiza las coordenadas multiplicando por 1/TOLERANCE y redondeando. Así, dos puntos dentro de la tolerancia producen la misma clave, evitando cadenas huérfanas por errores de punto flotante.
9. Back-pointer snode en Node
Cada Node de evento guarda una referencia directa al SkipNode que lo contiene. El borrado de un evento es O(altura del nodo) sin necesidad de buscar, evitando cierres (closures) por nodo y reduciendo presión sobre el GC.
10. Splitting de anillos auto-tocados
splitSelfTouchingRegions detecta y divide anillos que se auto-intersectan en un punto (figura en "8"), garantizando que el polígono final solo contenga ciclos simples válidos.
Since 3.0.1 this takes linear time per ring (a single pass with a hash of the points);
before, it compared every pair of vertices of every result ring, which dominated
operations producing large rings (ISSUES.md #13).
Suggested improvements
Findings, fixes and proposals are tracked in ISSUES.md, with one
progress check per item (vendor/bin/phpunit --testsuite issues --testdox --colors=never).
Still open:
| Item | Topic | Status |
|---|---|---|
| ISSUES.md #7 | GJTools rejects the whole input when one ring is degenerate |
Decision needed |
| ISSUES.md #8 | Projected coordinates | Documented limitation with a workaround (see Coordinate systems); fix plan tested |
| ISSUES.md #12 | Robust core (snap rounding) | Long term |
The improvements this section used to list are all done: point-key caching, the
$precision argument of ringKey/polygonKey, the collinear-point tolerance in
GJTools (ISSUES.md F4), the return type of combine(), the removal of __operate and
CombinedPolySegments, the intersectMany/differenceMany/xorMany functions, and
array input in buildGeometryFromCoordinates, and the quadratic
__splitRegionAtDuplicates, which was measured and made linear in 3.0.1 (ISSUES.md #13).
Profiling
- check that xdebug module is available and loaded: php -m | grep xdebug
- launch php with xdebug enabled:
php
-dxdebug.mode=profile
-dxdebug.start_with_request=yes
-dxdebug.output_dir=xdebug-profiler/
tests.php
Testing
Some tests inside tests.php, extended coverage with PHPUnit:
- php tests.php
- ./vendor/bin/phpunit
- ./vendor/bin/phpstan analyse --error-format=raw
Requirements: PHP >= 8.1 and, for PHPUnit, the PHP extensions dom, mbstring
and xmlwriter (plus json, libxml and tokenizer, usually built in). The
library itself doesn't need them. On Debian/Ubuntu:
sudo apt install php-xml php-mbstring
Without them composer install refuses to install PHPUnit, and PHPUnit stops with
"PHPUnit requires the "dom", ... extensions".
Known issues and their status are tracked in ISSUES.md. To see
which ones are already fixed:
- ./vendor/bin/phpunit --testsuite issues --testdox --colors=never
Stress suite: 32 radar-coverage scenarios (8 and 9 radars within 300 km, 720-vertex
irregular coverages, exact coverage layers 0..N computed two independent ways and
checked without using the library). It takes ~1-3 minutes per scenario, so it is not
part of the default suite; CI runs it on every merge to main
(.github/workflows/stress.yml, 8 parallel shards on PHP 8.3 and 8.5), and it can be
run by hand from the Actions tab on any branch. Locally:
- ./vendor/bin/phpunit --testsuite stress
- STRESS_SHARDS=4 STRESS_SHARD=0 ./vendor/bin/phpunit --testsuite stress (shard 1 of 4)
Tutorials and notes
- Interactive tutorial Polygon Clipping (Part 1)
- Interactive tutorial Polygon Clipping (Part 2)
- Notes on the Martinez-Rueda Polygon Clipping algorithm
- Let's build! Boolean operations of polygonsPart 1 - IntroductionPart 2 - Intersections
Resources
- To understand the algorithm, you can go here
- Based somewhat on the F. Martinez (2008) algorithm:
- Website
- A new algorithm for computing Boolean operations on polygons 2009 Research GateScience Direct
- A simple algorithm for Boolean operations on polygons 2013
History
- This library is a port for PHP of pypolybool
- Previoulsy, was a port for JS of polybooljs
- Help from a .NET port