File: Calc.pm

package info (click to toggle)
libmath-polygon-perl 2.00-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 256 kB
  • sloc: perl: 1,618; makefile: 2
file content (422 lines) | stat: -rw-r--r-- 9,264 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
# This code is part of Perl distribution Math-Polygon version 2.00.
# The POD got stripped from this file by OODoc version 3.03.
# 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.
# SPDX-License-Identifier: Artistic-1.0-Perl OR GPL-1.0-or-later

#oodist: *** DO NOT USE THIS VERSION FOR PRODUCTION ***
#oodist: This file contains OODoc-style documentation which will get stripped
#oodist: during its release in the distribution.  You can use this file for
#oodist: testing, however the code of this development version may be broken!

package Math::Polygon::Calc;{
our $VERSION = '2.00';
}

use parent 'Exporter';

use strict;
use warnings;

use Log::Report   'math-polygon';
use List::Util    qw/min max/;
use Scalar::Util  qw/blessed/;

our @EXPORT = qw/
	polygon_area
	polygon_bbox
	polygon_beautify
	polygon_centroid
	polygon_clockwise
	polygon_contains_point
	polygon_counter_clockwise
	polygon_distance
	polygon_equal
	polygon_is_clockwise
	polygon_is_closed
	polygon_perimeter
	polygon_same
	polygon_start_minxy
	polygon_string
	polygon_format
/;

sub polygon_is_closed(@);

#--------------------

sub polygon_string(@) { join ', ', map "[$_->[0],$_->[1]]", @_ }


sub polygon_bbox(@)
{
	(	min( map $_->[0], @_ ),
		min( map $_->[1], @_ ),
		max( map $_->[0], @_ ),
		max( map $_->[1], @_ )
	);
}


sub polygon_area(@)
{	my $area    = 0;
	while(@_ >= 2)
	{	$area += $_[0][0]*$_[1][1] - $_[0][1]*$_[1][0];
		shift;
	}

	abs($area)/2;
}


sub polygon_is_clockwise(@)
{	my $area  = 0;

	polygon_is_closed(@_)
		or error __"polygon must be closed: begin==end";

	while(@_ >= 2)
	{	$area += $_[0][0]*$_[1][1] - $_[0][1]*$_[1][0];
		shift;
	}

	$area < 0;
}


sub polygon_clockwise(@)
{	polygon_is_clockwise(@_) ? @_ : reverse @_;
}


sub polygon_counter_clockwise(@)
{	polygon_is_clockwise(@_) ? reverse(@_) : @_;
}



sub polygon_perimeter(@)
{	my $l    = 0;

	while(@_ >= 2)
	{	$l += sqrt(($_[0][0]-$_[1][0])**2 + ($_[0][1]-$_[1][1])**2);
		shift;
	}

	$l;
}


sub polygon_start_minxy(@)
{	return @_ if @_ <= 1;
	my $ring  = $_[0][0]==$_[-1][0] && $_[0][1]==$_[-1][1];
	pop @_ if $ring;

	my ($xmin, $ymin) = polygon_bbox @_;

	my $rot   = 0;
	my $dmin_sq = ($_[0][0]-$xmin)**2 + ($_[0][1]-$ymin)**2;

	for(my $i=1; $i<@_; $i++)
	{	next if $_[$i][0] - $xmin > $dmin_sq;

		my $d_sq = ($_[$i][0]-$xmin)**2 + ($_[$i][1]-$ymin)**2;
		if($d_sq < $dmin_sq)
		{	$dmin_sq = $d_sq;
			$rot     = $i;
		}
	}

	$rot==0 ? (@_, ($ring ? $_[0] : ())) : (@_[$rot..$#_], @_[0..$rot-1], ($ring ? $_[$rot] : ()));
}


sub polygon_beautify(@)
{	my %opts     = ref $_[0] eq 'HASH' ? %{ (shift) } : ();
	@_ or return ();

	my $despike  = exists $opts{remove_spikes} ? $opts{remove_spikes}  : 0;

	my @res      = @_;
	return () if @res < 4;  # closed triangle = 4 points
	pop @res;               # cyclic: last is first
	my $unchanged= 0;

	while($unchanged < 2*@res)
	{	return () if @res < 3;  # closed triangle = 4 points

		my $this = shift @res;
		push @res, $this;         # recycle
		$unchanged++;

		# remove doubles
		my ($x, $y) = @$this;
		while(@res && $res[0][0]==$x && $res[0][1]==$y)
		{	$unchanged = 0;
			shift @res;
		}

		# remove spike
		if($despike && @res >= 2)
		{	# any spike
			if($res[1][0]==$x && $res[1][1]==$y)
			{	$unchanged = 0;
				shift @res;
			}

			# x-spike
			if($y==$res[0][1] && $y==$res[1][1]
				&& (($res[0][0] < $x && $x < $res[1][0]) || ($res[0][0] > $x && $x > $res[1][0])))
			{	$unchanged = 0;
				shift @res;
			}

			# y-spike
			if(   $x==$res[0][0] && $x==$res[1][0]
				&& (($res[0][1] < $y && $y < $res[1][1]) || ($res[0][1] > $y && $y > $res[1][1])))
			{	$unchanged = 0;
				shift @res;
			}
		}

		# remove intermediate
		if(   @res >= 2
			&& $res[0][0]==$x && $res[1][0]==$x
			&& (($y < $res[0][1] && $res[0][1] < $res[1][1]) || ($y > $res[0][1] && $res[0][1] > $res[1][1])))
		{	$unchanged = 0;
			shift @res;
		}

		if(   @res >= 2
			&& $res[0][1]==$y && $res[1][1]==$y
			&& (($x < $res[0][0] && $res[0][0] < $res[1][0]) || ($x > $res[0][0] && $res[0][0] > $res[1][0])))
		{	$unchanged = 0;
			shift @res;
		}

		# remove 2 out-of order between two which stay
		if(@res >= 3
			&& $x==$res[0][0] && $x==$res[1][0] && $x==$res[2][0]
			&& ($y < $res[0][1] && $y < $res[1][1] && $res[0][1] < $res[2][1] && $res[1][1] < $res[2][1]))
		{	$unchanged = 0;
			splice @res, 0, 2;
		}

		if(@res >= 3
			&& $y==$res[0][1] && $y==$res[1][1] && $y==$res[2][1]
			&& ($x < $res[0][0] && $x < $res[1][0] && $res[0][0] < $res[2][0] && $res[1][0] < $res[2][0]))
		{	$unchanged = 0;
			splice @res, 0, 2;
		}
	}

	@res ? (@res, $res[0]) : ();
}


sub polygon_equal($$;$)
{	my  ($f,$s, $tolerance) = @_;
	return 0 if @$f != @$s;

	my @f = @$f;
	my @s = @$s;

	if(defined $tolerance)
	{	while(@f)
		{	return 0 if abs($f[0][0]-$s[0][0]) > $tolerance || abs($f[0][1]-$s[0][1]) > $tolerance;
			shift @f; shift @s;
		}
		return 1;
	}

	while(@f)
	{	return 0 if $f[0][0] != $s[0][0] || $f[0][1] != $s[0][1];
		shift @f; shift @s;
	}

	1;
}


sub polygon_same($$;$)
{	return 0 if @{$_[0]} != @{$_[1]};
	my @f = polygon_start_minxy polygon_clockwise @{ (shift) };
	my @s = polygon_start_minxy polygon_clockwise @{ (shift) };
	polygon_equal \@f, \@s, $_[0];
}


# Algorithms can be found at
# http://www.eecs.umich.edu/courses/eecs380/HANDOUTS/PROJ2/InsidePoly.html
# p1 = polygon[0];
# for (i=1;i<=N;i++) {
#   p2 = polygon[i % N];
#   if (p.y > MIN(p1.y,p2.y)) {
#     if (p.y <= MAX(p1.y,p2.y)) {
#       if (p.x <= MAX(p1.x,p2.x)) {
#         if (p1.y != p2.y) {
#           xinters = (p.y-p1.y)*(p2.x-p1.x)/(p2.y-p1.y)+p1.x;
#           if (p1.x == p2.x || p.x <= xinters)
#             counter++;
#         }
#       }
#     }
#   }
#   p1 = p2;
# }
# inside = counter % 2;

sub polygon_contains_point($@)
{	my $point = shift;
	return 0 if @_ < 3;

	my ($x, $y) = @$point;
	my $inside  = 0;

	polygon_is_closed(@_)
		or error __"polygon must be closed: begin==end";

	my ($px, $py) = @{ (shift) };

	while(@_)
	{	my ($nx, $ny) = @{ (shift) };

		# Extra check for exactly on the edge when the axes are
		# horizontal or vertical.
		return 1 if $y==$py && $py==$ny
				&& ($x >= $px || $x >= $nx)
				&& ($x <= $px || $x <= $nx);

		return 1 if $x==$px && $px==$nx
				&& ($y >= $py || $y >= $ny)
				&& ($y <= $py || $y <= $ny);

		if(   $py == $ny
			|| ($y <= $py && $y <= $ny)
			|| ($y >  $py && $y >  $ny)
			|| ($x >  $px && $x >  $nx)
		)
		{
			($px, $py) = ($nx, $ny);
			next;
		}

		# side wrt diagonal
		my $xinters = ($y-$py)*($nx-$px)/($ny-$py)+$px;
		$inside = !$inside
			if $px==$nx || $x <= $xinters;

		($px, $py) = ($nx, $ny);
	}

	$inside;
}


sub polygon_centroid(@)
{	my $args;
	if(ref $_[0] eq 'HASH') { $args = shift }
	else
	{	while(@_ && !ref $_[0])
		{	my $key       = shift;
			$args->{$key} = shift;
		}
	}

	polygon_is_closed @_
		or error __"polygon must be closed: begin==end";

	return [ ($_[0][0] + $_[1][0])/2, ($_[0][1] + $_[1][1])/2 ]
		if @_==3;  # line

	my $correct   = exists $args->{is_large} ? $args->{is_large} : blessed($_[0][0]);
	my ($mx, $my) = $correct ? (0, 0) : @{$_[0]};
	my $do_move   = $mx != 0 || $my != 0;

	@_ = map [ $_->[0] - $mx, $_->[1] - $my ], @_
		if $do_move;

	my ($cx, $cy, $a) = (0, 0, 0);
	foreach my $i (0..@_-2)
	{	my $ap =   $_[$i][0] * $_[$i+1][1] - $_[$i+1][0] * $_[$i][1];
		$cx   += ( $_[$i][0] + $_[$i+1][0] ) * $ap;
		$cy   += ( $_[$i][1] + $_[$i+1][1] ) * $ap;
		$a    += $ap;
	}

	$a != 0
		or error __"polygon points on a line, so no centroid";

	my $c = 3*$a; # 6*$a/2;
	$do_move ? [ $cx/$c + $mx, $cy/$c + $my ] : [ $cx/$c, $cy/$c ];
}


sub polygon_is_closed(@)
{	@_ or error __"empty polygon is neither closed nor open";

	my ($first, $last) = @_[0,-1];
	$first->[0]==$last->[0] && $first->[1]==$last->[1];
}


# Contributed by Andreas Koenig for 1.05
# http://stackoverflow.com/questions/10983872/distance-from-a-point-to-a-polygon#10984080
# with correction from
# http://stackoverflow.com/questions/849211/shortest-distance-between-a-point-and-a-line-segment
sub polygon_distance($%)
{	my $p = shift;

	my ($x, $y) = @$p;
	my $minDist;

	@_ or return undef;

	my ($x1, $y1) = @{ (shift) };
	unless(@_)
	{	my ($dx, $dy) = ($x1 - $x, $y1 - $y);
		return sqrt($dx * $dx + $dy * $dy);
	}

	while(@_)
	{	my ($x2, $y2) = @{ (shift) };   # closed poly!
		my $A =  $x - $x1;
		my $B =  $y - $y1;
		my $C = $x2 - $x1;
		my $D = $y2 - $y1;

		# closest point to the line segment
		my $dot    = $A * $C + $B * $D;
		my $len_sq = $C * $C + $D * $D;
		my $angle  = $len_sq==0 ? -1 : $dot / $len_sq;

		my ($xx, $yy)
		= $angle < 0 ? ($x1, $y1)   # perpendicular line crosses off segment
		: $angle > 1 ? ($x2, $y2)
		:              ($x1 + $angle * $C, $y1 + $angle * $D);

		my $dx = $x - $xx;
		my $dy = $y - $yy;
		my $dist = sqrt($dx * $dx + $dy * $dy);
		$minDist = $dist unless defined $minDist;
		$minDist = $dist if $dist < $minDist;

		($x1, $y1) = ($x2, $y2);
	}

	$minDist;
}


sub polygon_format($@)
{	my $format = shift;
	my $call   = ref $format eq 'CODE' ? $format : sub { sprintf $format, $_[0] };

	map +[ $call->($_->[0]), $call->($_->[1]) ], @_;
}

1;