Math::Polygon(3pm)
β¨ NAME β¨
Math::Polygon β Class for maintaining polygon data. This is the Math::Polygon(3pm) page from User Contributed Perl Documentation, bestie. It's literally giving "polygon data maintenance" and I'm obsessed.
π SYNOPSIS π
okay so here's the vibe check, copied exactly so you can run it:
my $poly = Math::Polygon->new( [1,2], [2,4], [5,7], [1,2] );
print $poly->nrPoints;
my @p = $poly->points;
my ($xmin, $ymin, $xmax, $ymax) = $poly->bbox;
my $area = $poly->area;
my $l = $poly->perimeter;
if($poly->isClockwise) { ... };
my $rot = $poly->startMinXY;
my $center = $poly->centroid;
if($poly->contains($point)) { ... };
my $boxed = $poly->lineClip($xmin, $xmax, $ymin, $ymax);
# [2.00] Stack-trace for errors, add this to your script
# to see where your math goes wrong:
use Log::Report mode => "DEBUG";
π DESCRIPTION π
This class provides an Object Oriented interface around Math::Polygon::Calc, Math::Polygon::Clip, and other. Together, these modules provide basic transformations on 2D polygons in pure perl. It's giving "math but make it OO" and honestly, slay.
WARNING: These computations may show platform dependent rounding differences. These may also originate from compilation options of the Perl version you installed. Not me being dramatic, it's just facts.
TIP: When you need better accuracy, you may use Math::BigFloat to represent coordinate values. Of course, this has a considerable price in performance. Highkey worth it when you need it, lowkey expensive though.
π METHODS π
π Constructors π
$any->new(%options, [@points], %options)
You may add %options before and/or after the @points. You may also use the "points" option to set the points. Each point in @points is (a references) to an ARRAY with two elements: an X and a Y coordinate. Bestie, it's literally giving coordinate cuteness.
When new() is called as instance method, it is believed that the new polygon is derived from the callee, and therefore some facts (like clockwise or anti-clockwise direction) will get copied unless overruled. Main character energy tbh.
The option defaults are:
bboxβ default:undef.clockwiseβ default:undef.pointsβ default:undef.
Here's the full tea on each option:
bbox=>[$xmin,$ymin, $xmax,$ymax]β default:undef. Usually computed from the shape automatically, but can also be overruled (for instance because it is already known). Seebbox().clockwise=> BOOLEAN β default:undef. Is not specified, it will be computed by theisClockwise()method on demand.points=>\@pointsβ default:undef. Seepoints()andnrPoints().
example: creation of new polygon
my $p = Math::Polygon->new([1,0],[1,1],[0,1],[0,0],[1,0]);
my @p = ([1,0],[1,1],[0,1],[0,0],[1,0]);
my $p = Math::Polygon->new(points => \@p);
π¦ Attributes π¦
$obj->nrPoints()
Returns the number of points, periodt.
$obj->order()
Returns the number of (unique?) points: one less than nrPoints() because we (usually) have a closed polygon. It's giving "almost the same but not quite" and that's valid.
$obj->point( $index, [$index,...] )
Returns the point with the specified $index or INDEXES. In SCALAR context, only the first $index is used. No cap.
example:
my $point = $poly->point(2);
my ($first, $last) = $poly->point(0, -1);
$obj->points( [FORMAT] )
In LIST context, the points are returned as list, otherwise as reference to an ARRAY of points.
[1.09] When a "FORMAT" is given, each coordinate will get processed. This may be useful to hide platform specific rounding errors. "FORMAT" may be a CODE reference or a printf() alike string. See Math::Polygon::Calc::polygon_format().
example:
my @points = $poly->points;
my $first = $points[0];
my $x0 = $points[0][0]; # == $first->[0] --> X
my $y0 = $points[0][1]; # == $first->[1] --> Y
my @points = $poly->points("%.2f");
πΈ Geometry πΈ
$obj->area()
Returns the area enclosed by the polygon. The last point of the list must be the same as the first to produce a correct result. The computed result is cached. Function Math::Polygon::Calc::polygon_area(). It's giving "area girl" and honestly same.
example:
my $area = $poly->area;
print "$area $poly_units ^2\n";
$obj->bbox()
Returns a list with four elements: (xmin, ymin, xmax, ymax), which describe the bounding box of the polygon (all points of the polygon are inside that area). The computation is expensive, and therefore, the results are cached. Function Math::Polygon::Calc::polygon_bbox(). Expensive but worth it, iykyk.
example:
my ($xmin, $ymin, $xmax, $ymax) = $poly->bbox;
$obj->beautify(%options)
Returns a new, beautified version of this polygon. Function Math::Polygon::Calc::polygon_beautify().
Polygons, certainly after some computations, can have a lot of horrible artifacts: points which are double, spikes, etc. Not the vibe. So this cleans them up.
The option defaults are:
remove_spikesβ default:false.remove_spikes=> BOOLEAN β no extra deets in the original, bestie. It is what it is.
$obj->centroid(%options)
Returns the centroid location of the polygon. The last point of the list must be the same as the first to produce a correct result. The computed result is cached. Function Math::Polygon::Calc::polygon_centroid().
Be aware that this algorithm does not like very flat polygons. It's giving "I can't with flat polygons" and honestly same.
The option defaults are:
is_largeβ default:false.is_large=> BOOLEAN β [2.00] When the polygon is large with respect to its distance to the origin, we do not need to be afraid for rounding errors. When set, the calculation will be a bit faster.
example:
my $center = $poly->centroid;
my ($cx, $cy) = @$center;
$obj->clockwise()
Make sure the points are in clockwise order. Clockwise queen.
example:
$poly->clockwise;
$obj->contains($point)
Returns a truth value indicating whether the point is inside the polygon or not. On the edge is inside. Edge case? More like edge is in, periodt.
$obj->counterClockwise()
Make sure the points are in counter-clockwise order. The other direction, but make it iconic.
example:
$poly->counterClockwise
$obj->distance($point)
[1.05] Returns the distance of the point to the closest point on the border of the polygon, zero if the point is on an edge. Literally the closest-distance vibe check.
$obj->equal(($other|\@points, [$tolerance]) | @points)
Compare two polygons on the level of @points. When the polygons are the same but rotated or mirrored, this returns "false". See same() for the more thorrow (and expensive) comparison. Function Math::Polygon::Calc::polygon_equal().
example:
if($poly->equal($other_poly, 0.1)) ...
if($poly->equal(\@points, 0.1)) ...
if($poly->equal(@points)) ...
$obj->isClockwise()
The points are (in majority) orded in the direction of the hands of the clock. This calculation is quite expensive (same effort as calculating the area of the polygon), and the result is therefore cached. Expensive but cached, so it's fine.
example:
if($poly->isClockwise) ...
$obj->isClosed()
Returns "true" if the first point of the poly definition is the same as the last point. Closed for business, but in a polygon way.
$obj->perimeter()
The length of the line of the polygon. This can also be used to compute the length of any line: of the last point is not equal to the first, then a line is presumed; for a polygon they must match. Function Math::Polygon::Calc::polygon_perimeter(). It's giving "fence length" and I'm here for it.
example:
my $fence = $poly->perimeter;
print "fence length: $fence $poly_units\n"
$obj->same(($other|\@points, [$tolerance]) | @points)
[1.12] Compare two polygons, where the polygons may be rotated or mirrored wrt each other. This is (much) slower than equal(), but some algorithms will cause un unpredictable rotation in the result. Function Math::Polygon::Calc::polygon_same(). Slow but thorough, highkey worth it.
example:
if($poly->same($other_poly, 0.1)) ...
if($poly->same(\@points, 0.1)) ...
if($poly->same(@points)) ...
$obj->startMinXY()
Returns a new polygon object, where the points are rotated in such a way that the point which is closest to the left-bottom point of the bounding box has become the first. Function Math::Polygon::Calc::polygon_start_minxy(). Starting from the bottom-left, main character energy.
β¨ Transformations β¨
Implemented in Math::Polygon::Transform: changes on the structure of the polygon except clipping. All functions return a new polygon object or "undef". No in-place drama here, bestie.
$obj->grid(%options)
Returns a polygon object with the points snapped to grid points. See Math::Polygon::Transform::polygon_grid().
The option defaults are:
rasterβ default:1.0.raster=> FLOAT β The raster size, which determines the points to round to. The origin"[0,0]"is always on a grid-point. When the raster value is zero, no transformation will take place.
$obj->mirror(%options)
Mirror the polygon in a line. Only one of the options can be provided. Some programs call this "flip" or "flop". Not me calling it flop though.
The option defaults are:
bβ default:0.lineβ default:<C<undef>>.rcβ default:undef.xβ default:undef.yβ default:undef.b=> FLOAT β Only used in combination with option"rc"to describe a line.line=>[POINT, POINT]β Alternative way to specify the mirror line. The"rc"and"b"are computed from the two points of the line.rc=> FLOAT β Description of the line which is used to mirror in. The line is"y= rc*x+b". The"rc"equals"-dy/dx", the firing angle. If"undef"is explicitly specified then"b"is used as constant x: it's a vertical mirror.x=> FLOAT β Mirror in the line"x=value", which means that"y"stays unchanged.y=> FLOAT β Mirror in the line"y=value", which means that"x"stays unchanged.
$obj->move(%options)
Returns a moved polygon object: all point are moved over the indicated distance. See Math::Polygon::Transform::polygon_move().
The option defaults are:
dxβ default:0.dyβ default:0.dx=> FLOAT β Displacement in the horizontal direction.dy=> FLOAT β Displacement in the vertical direction.
$obj->resize(%options)
Returns a resized polygon object. See Math::Polygon::Transform::polygon_resize().
The option defaults are:
centerβ default:[0,0].scaleβ default:1.0.xscaleβ default:<scale>.yscaleβ default:<scale>.center=>$pointβ no extra deets in the original, bestie.scale=> FLOAT β Resize the polygon with the indicated factor. When the factor is larger than 1, the resulting polygon with grow, when small it will be reduced in size. The scale will be respective from the center.xscale=> FLOAT β Specific scaling factor in the horizontal direction.yscale=> FLOAT β Specific scaling factor in the vertical direction.
$obj->rotate(%options)
Returns a rotated polygon object: all point are moved over the indicated distance. See Math::Polygon::Transform::polygon_rotate().
okay bestie we're back π not me sliding straight back in mid-thought. These are the options that rotate chews on, defaults first because we respect the classics:
-Option --Default
center [0,0]
degrees 0
radians 0
center=> POINT β this is the point you're spinning around, and by default it's[0,0], the origin, the main character. β¨degrees=> FLOAT β default is0. You're specifying the rotation angle in degrees, and it's gotta be between-180and360.radians=> FLOAT β default is0. Same vibe, but the angle is in rads and it's gotta be between-piand2*pi.
πΈ $obj->simplify(%options) πΈ
Returns a polygon object where points are removed. Like, it's the glow-down for polygons. See Math::Polygon::Transform::polygon_simplify() if you wanna go straight to the source. π«Ά
-Option --Default
max_points undef
same 0.0001
slope undef
max_points=> INTEGER β first,sameandslopedo their little thing and shrink the point count. then, if there are still more points left than you asked for, the points with the widest angles get yeeted one by one until we hit that maximum number. periodt. πsame=> FLOAT β default0.0001. This is the distance between two points for them to be considered "the same" point. The value gets used as the radius of the circle. πslope=> FLOAT β so picture three pointsX(n),X(n+1),X(n+2). The pointX(n+1)gets removed if the length of the path over all three points is less thanslopelonger than the direct path betweenX(n)andX(n+2). iykyk. π₯
lowkey important: the slope will not be removed around the starting point of the polygon. also, removing points will change the area of the polygon β it's giving irreversible haircut, bestie, so be sure. π
π Clipping π
π
$obj->fillClip1($box) π
Clipping a polygon into rectangles can be done in various ways, and this is one of those ways. With this algorithm, the parts of the polygon that are outside the $box get mapped onto the borders. The polygon stays in one piece, but it may end up with vertices that are followed in two directions β icon behaviour honestly, it's just built different. π¦
What you get back is one polygon, cleaned from double points, spikes and superfluous intermediate points, or undef when no polygon is outside the $box. Function: Math::Polygon::Clip::polygon_fill_clip1().
β¨ $obj->lineClip($box) β¨
What you get back is a LIST of ARRAYS-of-points containing line pieces from the input polygon. Function: Math::Polygon::Clip::polygon_line_clip().
π Display π
π $obj->string( [FORMAT] ) π
Print the polygon. that's it, that's the function. π
[1.09] When a FORMAT is specified, all coordinates get formatted first. Heads up though: this may hide platform dependent rounding differences, so like, don't come for the rounding, it's not the vibe. π
π SEE ALSO π
This module is part of Math-Polygon version 2.00, built on September 04, 2025. Website: http://perl.overmeer.net/CPAN/
πΈ LICENSE πΈ
For contributors see file ChangeLog.
This software is copyright (c) 2004-2025 by Mark Overmeer.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. slay, honestly. π«Ά
and that's a wrap, bestie!! this page came from Math::Polygon(3pm) β perl v5.40.1, dated 2025-10-04 β so if you're quoting me, quote the source, mwah π bye babes β¨ππ¦
π¦ where this page comes from
- ubuntu resolute: libmath-polygon-perl 2.00-1 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu stonking: libmath-polygon-perl 2.00-1 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms