how to access Math::Planar::GPC function and features?

137 views Asked by At

I want print out the intersection of two polygons. but when there is no intersection of two polygons, how can I get to know to avoid print it? Because if no intersection, I can't call $pgons[0]->polygons, it gives me an error.
(no holes in all polygons)
Thanks!

for my $x(0..$#polygon){
    for my $y(0..$#polygon){
        if ($x != $y){
            my $it = GpcClip('INTERSECTION', $polygon[0]->convert2gpc, $polygon[1]->convert2gpc);
            print FO "$x  ==  $y \n";
            my @pgons = Gpc2Polygons($it);  
            #since here we don't have holes, only the first one is a valid polygon 
            if(@pgons){
                print FO Dumper($pgons[0]->polygons->[0]);
                print "\n";
            }    
        }
    }
}
1

There are 1 answers

1
Håkon Hægland On BEST ANSWER

It seems like Gpc2Polygons returns an empty array when no intersection was found. So to determine if the intersection is nonempty you could check if the length of the returned array is greater than zero. For example:

use feature qw(say);
use strict;
use warnings;

use Math::Geometry::Planar;

my $p1 = Math::Geometry::Planar->new;
my $p2 = Math::Geometry::Planar->new;

$p1->points([[0, 0], [0, 2], [2, 2], [2, 0]]);
for my $pos (1, 1.5, 2) {
    say "pos = $pos";
    $p2->points([[$pos, 0], [$pos, 2], [$pos + 2, 2], [$pos + 2, 0]]);
    my $intersect = GpcClip( 'INTERSECTION', $p1->convert2gpc, $p2->convert2gpc );
    my @pgons = Gpc2Polygons( $intersect );  
    if ( @pgons > 0 ) {
        say "  Found intersection";
    }
    else {
        say "  No intersection";
    }
}

The output is:

pos = 1
  Found intersection
pos = 1.5
  Found intersection
pos = 2
  No intersection