-
Notifications
You must be signed in to change notification settings - Fork 0
/
psimpl.h
1890 lines (1614 loc) · 84 KB
/
psimpl.h
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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is
* 'psimpl - generic n-dimensional polyline simplification'.
*
* The Initial Developer of the Original Code is
* Elmar de Koning.
* Portions created by the Initial Developer are Copyright (C) 2010-2011
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** */
/*
psimpl - generic n-dimensional polyline simplification
Copyright (C) 2010-2011 Elmar de Koning, [email protected]
This file is part of psimpl, and is hosted at SourceForge:
http://sourceforge.net/projects/psimpl/
*/
/*!
\mainpage psimpl - generic n-dimensional polyline simplification
<pre>
Author - Elmar de Koning
Support - [email protected]
Website - http://psimpl.sf.net
Article - http://www.codeproject.com/KB/recipes/PolylineSimplification.aspx
License - MPL 1.1
</pre><br>
\section sec_psimpl psimpl
<pre>
'psimpl' is a c++ polyline simplification library that is generic, easy to use, and supports
the following algorithms:
Simplification
+ Nth point - A naive algorithm that keeps only each nth point
+ Distance between points - Removes successive points that are clustered together
+ Perpendicular distance - Removes points based on their distance to the line segment defined
by their left and right neighbors
+ Reumann-Witkam - Shifts a strip along the polyline and removes points that fall outside
+ Opheim - A constrained version of Reumann-Witkam
+ Lang - Similar to the Perpendicular distance routine, but instead of looking only at direct
neighbors, an entire search region is processed
+ Douglas-Peucker - A classic simplification algorithm that provides an excellent approximation
of the original line
+ A variation on the Douglas-Peucker algorithm - Slower, but yields better results at lower resolutions
Errors
+ positional error - Distance of each polyline point to its simplification
All the algorithms have been implemented in a single standalone C++ header using an STL-style
interface that operates on input and output iterators. Polylines can be of any dimension, and
defined using floating point or signed integer data types.
</pre><br>
\section sec_changelog changelog
<pre>
28-09-2010 - Initial version
23-10-2010 - Changed license from CPOL to MPL
26-10-2010 - Clarified input (type) requirements, and changed the behavior of the algorithms
under invalid input
01-12-2010 - Added the nth point, perpendicular distance and Reumann-Witkam routines; moved all
functions related to distance calculations to the math namespace
10-12-2010 - Fixed a bug in the perpendicular distance routine
27-02-2011 - Added Opheim simplification, and functions for computing positional errors due to
simplification; renamed simplify_douglas_peucker_alt to simplify_douglas_peucker_n
18-06-2011 - Added Lang simplification; fixed divide by zero bug when using integers; fixed a
bug where incorrect output iterators were returned under invalid input; fixed a bug
in douglas_peucker_n where an incorrect number of points could be returned; fixed a
bug in compute_positional_errors2 that required the output and input iterator types
to be the same; fixed a bug in compute_positional_error_statistics where invalid
statistics could be returned under questionable input; documented input iterator
requirements for each algorithm; miscellaneous refactoring of most algorithms.
</pre>
*/
#ifndef PSIMPL_GENERIC
#define PSIMPL_GENERIC
#include <queue>
#include <stack>
#include <numeric>
#include <algorithm>
#include <cmath>
/*!
\brief Root namespace of the polyline simplification library.
*/
namespace psimpl
{
/*!
\brief Contains utility functions and classes.
*/
namespace util
{
/*!
\brief A smart pointer for holding a dynamically allocated array.
Similar to boost::scoped_array.
*/
template <typename T>
class scoped_array
{
public:
scoped_array (unsigned n) {
array = new T [n];
}
~scoped_array () {
delete [] array;
}
T& operator [] (int offset) {
return array [offset];
}
const T& operator [] (int offset) const {
return array [offset];
}
T* get () const {
return array;
}
void swap (scoped_array& b) {
T* tmp = b.array;
b.array = array;
array = tmp;
}
private:
scoped_array (const scoped_array&);
scoped_array& operator= (const scoped_array&);
private:
T* array;
};
template <typename T> inline void swap (scoped_array <T>& a, scoped_array <T>& b) {
a.swap (b);
}
}
/*!
\brief Contains functions for calculating statistics and distances between various geometric entities.
*/
namespace math
{
/*!
\brief POD structure for storing several statistical values
*/
struct Statistics
{
Statistics () :
max (0),
sum (0),
mean (0),
std (0)
{}
double max;
double sum;
double mean;
double std; //! standard deviation
};
/*!
\brief Determines if two points have the exact same coordinates.
\param[in] p1 the first coordinate of the first point
\param[in] p2 the first coordinate of the second point
\return true when the points are equal; false otherwise
*/
template <unsigned DIM, class InputIterator>
inline bool equal (
InputIterator p1,
InputIterator p2)
{
for (unsigned d = 0; d < DIM; ++d) {
if (*p1 != *p2) {
return false;
}
++p1;
++p2;
}
return true;
}
/*!
\brief Creates a vector from two points.
\param[in] p1 the first coordinate of the first point
\param[in] p2 the first coordinate of the second point
\param[in] result the resulting vector (p2-p1)
\return one beyond the last coordinate of the resulting vector
*/
template <unsigned DIM, class InputIterator, class OutputIterator>
inline OutputIterator make_vector (
InputIterator p1,
InputIterator p2,
OutputIterator result)
{
for (unsigned d = 0; d < DIM; ++d) {
*result = *p2 - *p1;
++result;
++p1;
++p2;
}
return result;
}
/*!
\brief Computes the dot product of two vectors.
\param[in] v1 the first coordinate of the first vector
\param[in] v2 the first coordinate of the second vector
\return the dot product (v1 * v2)
*/
template <unsigned DIM, class InputIterator>
inline typename std::iterator_traits <InputIterator>::value_type dot (
InputIterator v1,
InputIterator v2)
{
typename std::iterator_traits <InputIterator>::value_type result = 0;
for (unsigned d = 0; d < DIM; ++d) {
result += (*v1) * (*v2);
++v1;
++v2;
}
return result;
}
/*!
\brief Peforms linear interpolation between two points.
\param[in] p1 the first coordinate of the first point
\param[in] p2 the first coordinate of the second point
\param[in] fraction the fraction used during interpolation
\param[in] result the interpolation result (p1 + fraction * (p2 - p1))
\return one beyond the last coordinate of the interpolated point
*/
template <unsigned DIM, class InputIterator, class OutputIterator>
inline OutputIterator interpolate (
InputIterator p1,
InputIterator p2,
float fraction,
OutputIterator result)
{
typedef typename std::iterator_traits <InputIterator>::value_type value_type;
for (unsigned d = 0; d < DIM; ++d) {
*result = *p1 + static_cast <value_type> (fraction * (*p2 - *p1));
++result;
++p1;
++p2;
}
return result;
}
/*!
\brief Computes the squared distance of two points
\param[in] p1 the first coordinate of the first point
\param[in] p2 the first coordinate of the second point
\return the squared distance
*/
template <unsigned DIM, class InputIterator1, class InputIterator2>
inline typename std::iterator_traits <InputIterator1>::value_type point_distance2 (
InputIterator1 p1,
InputIterator2 p2)
{
typename std::iterator_traits <InputIterator1>::value_type result = 0;
for (unsigned d = 0; d < DIM; ++d) {
result += (*p1 - *p2) * (*p1 - *p2);
++p1;
++p2;
}
return result;
}
/*!
\brief Computes the squared distance between an infinite line (l1, l2) and a point p
\param[in] l1 the first coordinate of the first point on the line
\param[in] l2 the first coordinate of the second point on the line
\param[in] p the first coordinate of the test point
\return the squared distance
*/
template <unsigned DIM, class InputIterator>
inline typename std::iterator_traits <InputIterator>::value_type line_distance2 (
InputIterator l1,
InputIterator l2,
InputIterator p)
{
typedef typename std::iterator_traits <InputIterator>::value_type value_type;
value_type v [DIM]; // vector l1 --> l2
value_type w [DIM]; // vector l1 --> p
make_vector <DIM> (l1, l2, v);
make_vector <DIM> (l1, p, w);
value_type cv = dot <DIM> (v, v); // squared length of v
value_type cw = dot <DIM> (w, v); // project w onto v
// avoid problems with divisions when value_type is an integer type
float fraction = cv == 0 ? 0 : static_cast <float> (cw) / static_cast <float> (cv);
value_type proj [DIM]; // p projected onto line (l1, l2)
interpolate <DIM> (l1, l2, fraction, proj);
return point_distance2 <DIM> (p, proj);
}
/*!
\brief Computes the squared distance between a line segment (s1, s2) and a point p
\param[in] s1 the first coordinate of the start point of the segment
\param[in] s2 the first coordinate of the end point of the segment
\param[in] p the first coordinate of the test point
\return the squared distance
*/
template <unsigned DIM, class InputIterator>
inline typename std::iterator_traits <InputIterator>::value_type segment_distance2 (
InputIterator s1,
InputIterator s2,
InputIterator p)
{
typedef typename std::iterator_traits <InputIterator>::value_type value_type;
value_type v [DIM]; // vector s1 --> s2
value_type w [DIM]; // vector s1 --> p
make_vector <DIM> (s1, s2, v);
make_vector <DIM> (s1, p, w);
value_type cw = dot <DIM> (w, v); // project w onto v
if (cw <= 0) {
// projection of w lies to the left of s1
return point_distance2 <DIM> (p, s1);
}
value_type cv = dot <DIM> (v, v); // squared length of v
if (cv <= cw) {
// projection of w lies to the right of s2
return point_distance2 <DIM> (p, s2);
}
// avoid problems with divisions when value_type is an integer type
float fraction = cv == 0 ? 0 : static_cast <float> (cw) / static_cast <float> (cv);
value_type proj [DIM]; // p projected onto segement (s1, s2)
interpolate <DIM> (s1, s2, fraction, proj);
return point_distance2 <DIM> (p, proj);
}
/*!
\brief Computes the squared distance between a ray (r1, r2) and a point p
\param[in] r1 the first coordinate of the start point of the ray
\param[in] r2 the first coordinate of a point on the ray
\param[in] p the first coordinate of the test point
\return the squared distance
*/
template <unsigned DIM, class InputIterator>
inline typename std::iterator_traits <InputIterator>::value_type ray_distance2 (
InputIterator r1,
InputIterator r2,
InputIterator p)
{
typedef typename std::iterator_traits <InputIterator>::value_type value_type;
value_type v [DIM]; // vector r1 --> r2
value_type w [DIM]; // vector r1 --> p
make_vector <DIM> (r1, r2, v);
make_vector <DIM> (r1, p, w);
value_type cv = dot <DIM> (v, v); // squared length of v
value_type cw = dot <DIM> (w, v); // project w onto v
if (cw <= 0) {
// projection of w lies to the left of r1 (not on the ray)
return point_distance2 <DIM> (p, r1);
}
// avoid problems with divisions when value_type is an integer type
float fraction = cv == 0 ? 0 : static_cast <float> (cw) / static_cast <float> (cv);
value_type proj [DIM]; // p projected onto ray (r1, r2)
interpolate <DIM> (r1, r2, fraction, proj);
return point_distance2 <DIM> (p, proj);
}
/*!
\brief Computes various statistics for the range [first, last)
\param[in] first the first value
\param[in] last one beyond the last value
\return the calculated statistics
*/
template <class InputIterator>
inline Statistics compute_statistics (
InputIterator first,
InputIterator last)
{
typedef typename std::iterator_traits <InputIterator>::value_type value_type;
typedef typename std::iterator_traits <InputIterator>::difference_type diff_type;
Statistics stats;
diff_type count = std::distance (first, last);
if (count == 0) {
return stats;
}
value_type init = 0;
stats.max = static_cast <double> (*std::max_element (first, last));
stats.sum = static_cast <double> (std::accumulate (first, last, init));
stats.mean = stats.sum / count;
std::transform (first, last, first, std::bind2nd (std::minus <value_type> (), stats.mean));
stats.std = std::sqrt (static_cast <double> (std::inner_product (first, last, first, init)) / count);
return stats;
}
}
/*!
\brief Provides various simplification algorithms for n-dimensional simple polylines.
A polyline is simple when it is non-closed and non-selfintersecting. All algorithms
operate on input iterators and output iterators. Note that unisgned integer types are
NOT supported.
*/
template <unsigned DIM, class InputIterator, class OutputIterator>
class PolylineSimplification
{
typedef typename std::iterator_traits <InputIterator>::difference_type diff_type;
typedef typename std::iterator_traits <InputIterator>::value_type value_type;
typedef typename std::iterator_traits <const value_type*>::difference_type ptr_diff_type;
public:
/*!
\brief Performs the nth point routine (NP).
NP is an O(n) algorithm for polyline simplification. It keeps only the first, last and
each nth point. As an example, consider any random line of 8 points. Using n = 3 will
always yield a simplification consisting of points: 1, 4, 7, 8
\image html psimpl_np.png
NP is applied to the range [first, last). The resulting simplified polyline is copied
to the output range [result, result + m*DIM), where m is the number of vertices of the
simplified polyline. The return value is the end of the output range: result + m*DIM.
Input (Type) requirements:
1- DIM is not 0, where DIM represents the dimension of the polyline
2- The InputIterator type models the concept of a forward iterator
3- The input iterator value type is convertible to a value type of the OutputIterator
4- The range [first, last) contains only vertex coordinates in multiples of DIM, f.e.:
x, y, z, x, y, z, x, y, z when DIM = 3
5- The range [first, last) contains at least 2 vertices
6- n is not 0
In case these requirements are not met, the entire input range [first, last) is copied
to the output range [result, result + (last - first)) OR compile errors may occur.
\param[in] first the first coordinate of the first polyline point
\param[in] last one beyond the last coordinate of the last polyline point
\param[in] n specifies 'each nth point'
\param[in] result destination of the simplified polyline
\return one beyond the last coordinate of the simplified polyline
*/
OutputIterator NthPoint (
InputIterator first,
InputIterator last,
unsigned n,
OutputIterator result)
{
diff_type coordCount = std::distance (first, last);
diff_type pointCount = DIM // protect against zero DIM
? coordCount / DIM
: 0;
// validate input and check if simplification required
if (coordCount % DIM || pointCount < 3 || n < 2) {
return std::copy (first, last, result);
}
unsigned remaining = pointCount - 1; // the number of points remaining after key
InputIterator key = first; // indicates the current key
// the first point is always part of the simplification
CopyKey (key, result);
// copy each nth point
while (Forward (key, n, remaining)) {
CopyKey (key, result);
}
return result;
}
/*!
\brief Performs the (radial) distance between points routine (RD).
RD is a brute-force O(n) algorithm for polyline simplification. It reduces successive
vertices that are clustered too closely to a single vertex, called a key. The resulting
keys form the simplified polyline.
\image html psimpl_rd.png
RD is applied to the range [first, last) using the specified tolerance tol. The
resulting simplified polyline is copied to the output range [result, result + m*DIM),
where m is the number of vertices of the simplified polyline. The return value is the
end of the output range: result + m*DIM.
Input (Type) requirements:
1- DIM is not 0, where DIM represents the dimension of the polyline
2- The InputIterator type models the concept of a forward iterator
3- The input iterator value type is convertible to a value type of the output iterator
4- The range [first, last) contains only vertex coordinates in multiples of DIM, f.e.:
x, y, z, x, y, z, x, y, z when DIM = 3
5- The range [first, last) contains at least 2 vertices
6- tol is not 0
In case these requirements are not met, the entire input range [first, last) is copied
to the output range [result, result + (last - first)) OR compile errors may occur.
\param[in] first the first coordinate of the first polyline point
\param[in] last one beyond the last coordinate of the last polyline point
\param[in] tol radial (point-to-point) distance tolerance
\param[in] result destination of the simplified polyline
\return one beyond the last coordinate of the simplified polyline
*/
OutputIterator RadialDistance (
InputIterator first,
InputIterator last,
value_type tol,
OutputIterator result)
{
diff_type coordCount = std::distance (first, last);
diff_type pointCount = DIM // protect against zero DIM
? coordCount / DIM
: 0;
value_type tol2 = tol * tol; // squared distance tolerance
// validate input and check if simplification required
if (coordCount % DIM || pointCount < 3 || tol2 == 0) {
return std::copy (first, last, result);
}
InputIterator current = first; // indicates the current key
InputIterator next = first; // used to find the next key
// the first point is always part of the simplification
CopyKeyAdvance (next, result);
// Skip first and last point, because they are always part of the simplification
for (diff_type index = 1; index < pointCount - 1; ++index) {
if (math::point_distance2 <DIM> (current, next) < tol2) {
Advance (next);
continue;
}
current = next;
CopyKeyAdvance (next, result);
}
// the last point is always part of the simplification
CopyKeyAdvance (next, result);
return result;
}
/*!
\brief Repeatedly performs the perpendicular distance routine (PD).
The algorithm stops after calling the PD routine 'repeat' times OR when the
simplification does not improve. Note that this algorithm will need to store
up to two intermediate simplification results.
\sa PerpendicularDistance(InputIterator, InputIterator, value_type, OutputIterator)
\param[in] first the first coordinate of the first polyline point
\param[in] last one beyond the last coordinate of the last polyline point
\param[in] tol perpendicular (segment-to-point) distance tolerance
\param[in] repeat the number of times to successively apply the PD routine
\param[in] result destination of the simplified polyline
\return one beyond the last coordinate of the simplified polyline
*/
OutputIterator PerpendicularDistance (
InputIterator first,
InputIterator last,
value_type tol,
unsigned repeat,
OutputIterator result)
{
if (repeat == 1) {
// single pass
return PerpendicularDistance (first, last, tol, result);
}
// only validate repeat; other input is validated by simplify_perpendicular_distance
if (repeat < 1) {
return std::copy (first, last, result);
}
diff_type coordCount = std::distance (first, last);
// first pass: [first, last) --> temporary array 'tempPoly'
util::scoped_array <value_type> tempPoly (coordCount);
PolylineSimplification <DIM, InputIterator, value_type*> psimpl_to_array;
diff_type tempCoordCount = std::distance (tempPoly.get (),
psimpl_to_array.PerpendicularDistance (first, last, tol, tempPoly.get ()));
// check if simplification did not improved
if (coordCount == tempCoordCount) {
return std::copy (tempPoly.get (), tempPoly.get () + coordCount, result);
}
std::swap (coordCount, tempCoordCount);
--repeat;
// intermediate passes: temporary array 'tempPoly' --> temporary array 'tempResult'
if (1 < repeat) {
util::scoped_array <value_type> tempResult (coordCount);
PolylineSimplification <DIM, value_type*, value_type*> psimpl_arrays;
while (--repeat) {
tempCoordCount = std::distance (tempResult.get (),
psimpl_arrays.PerpendicularDistance (
tempPoly.get (), tempPoly.get () + coordCount, tol, tempResult.get ()));
// check if simplification did not improved
if (coordCount == tempCoordCount) {
return std::copy (tempPoly.get (), tempPoly.get () + coordCount, result);
}
util::swap (tempPoly, tempResult);
std::swap (coordCount, tempCoordCount);
}
}
// final pass: temporary array 'tempPoly' --> result
PolylineSimplification <DIM, value_type*, OutputIterator> psimpl_from_array;
return psimpl_from_array.PerpendicularDistance (
tempPoly.get (), tempPoly.get () + coordCount, tol, result);
}
/*!
\brief Performs the perpendicular distance routine (PD).
PD is an O(n) algorithm for polyline simplification. It computes the perpendicular
distance of each point pi to the line segment S(pi-1, pi+1). Only when this distance is
larger than the given tolerance will pi be part of the simpification. Note that the
original polyline can only be reduced by a maximum of 50%. Multiple passes are required
to achieve higher points reductions.
\image html psimpl_pd.png
PD is applied to the range [first, last) using the specified tolerance tol. The
resulting simplified polyline is copied to the output range [result, result + m*DIM),
where m is the number of vertices of the simplified polyline. The return value is the
end of the output range: result + m*DIM.
Input (Type) requirements:
1- DIM is not 0, where DIM represents the dimension of the polyline
2- The InputIterator type models the concept of a forward iterator
3- The input iterator value type is convertible to a value type of the output iterator
4- The range [first, last) contains only vertex coordinates in multiples of DIM, f.e.:
x, y, z, x, y, z, x, y, z when DIM = 3
5- The range [first, last) contains at least 2 vertices
6- tol is not 0
In case these requirements are not met, the entire input range [first, last) is copied
to the output range [result, result + (last - first)) OR compile errors may occur.
\param[in] first the first coordinate of the first polyline point
\param[in] last one beyond the last coordinate of the last polyline point
\param[in] tol perpendicular (segment-to-point) distance tolerance
\param[in] result destination of the simplified polyline
\return one beyond the last coordinate of the simplified polyline
*/
OutputIterator PerpendicularDistance (
InputIterator first,
InputIterator last,
value_type tol,
OutputIterator result)
{
diff_type coordCount = std::distance (first, last);
diff_type pointCount = DIM // protect against zero DIM
? coordCount / DIM
: 0;
value_type tol2 = tol * tol; // squared distance tolerance
// validate input and check if simplification required
if (coordCount % DIM || pointCount < 3 || tol2 == 0) {
return std::copy (first, last, result);
}
InputIterator p0 = first;
InputIterator p1 = AdvanceCopy(p0);
InputIterator p2 = AdvanceCopy(p1);
// the first point is always part of the simplification
CopyKey (p0, result);
while (p2 != last) {
// test p1 against line segment S(p0, p2)
if (math::segment_distance2 <DIM> (p0, p2, p1) < tol2) {
CopyKey (p2, result);
// move up by two points
p0 = p2;
Advance (p1, 2);
if (p1 == last) {
// protect against advancing p2 beyond last
break;
}
Advance (p2, 2);
}
else {
CopyKey (p1, result);
// move up by one point
p0 = p1;
p1 = p2;
Advance (p2);
}
}
// make sure the last point is part of the simplification
if (p1 != last) {
CopyKey (p1, result);
}
return result;
}
/*!
\brief Performs Reumann-Witkam approximation (RW).
The O(n) RW routine uses a point-to-line (perpendicular) distance tolerance. It defines
a line through the first two vertices of the original polyline. For each successive
vertex vi its perpendicular distance to this line is calculated. A new key is found at
vi-1, when this distance exceeds the specified tolerance. The vertices vi and vi+1 are
then used to define a new line, and the process repeats itself.
\image html psimpl_rw.png
RW routine is applied to the range [first, last) using the specified perpendicular
distance tolerance tol. The resulting simplified polyline is copied to the output range
[result, result + m*DIM), where m is the number of vertices of the simplified polyline.
The return value is the end of the output range: result + m*DIM.
Input (Type) Requirements:
1- DIM is not 0, where DIM represents the dimension of the polyline
2- The InputIterator type models the concept of a forward iterator
3- The input iterator value type is convertible to a value type of the output iterator
4- The range [first, last) contains vertex coordinates in multiples of DIM,
f.e.: x, y, z, x, y, z, x, y, z when DIM = 3
5- The range [first, last) contains at least 2 vertices
6- tol is not 0
In case these requirements are not met, the entire input range [first, last) is copied
to the output range [result, result + (last - first)) OR compile errors may occur.
\param[in] first the first coordinate of the first polyline point
\param[in] last one beyond the last coordinate of the last polyline point
\param[in] tol perpendicular (point-to-line) distance tolerance
\param[in] result destination of the simplified polyline
\return one beyond the last coordinate of the simplified polyline
*/
OutputIterator ReumannWitkam (
InputIterator first,
InputIterator last,
value_type tol,
OutputIterator result)
{
diff_type coordCount = std::distance (first, last);
diff_type pointCount = DIM // protect against zero DIM
? coordCount / DIM
: 0;
value_type tol2 = tol * tol; // squared distance tolerance
// validate input and check if simplification required
if (coordCount % DIM || pointCount < 3 || tol2 == 0) {
return std::copy (first, last, result);
}
// define the line L(p0, p1)
InputIterator p0 = first; // indicates the current key
InputIterator p1 = AdvanceCopy (first); // indicates the next point after p0
// keep track of two test points
InputIterator pi = p1; // the previous test point
InputIterator pj = p1; // the current test point (pi+1)
// the first point is always part of the simplification
CopyKey (p0, result);
// check each point pj against L(p0, p1)
for (diff_type j = 2; j < pointCount; ++j) {
pi = pj;
Advance (pj);
if (math::line_distance2 <DIM> (p0, p1, pj) < tol2) {
continue;
}
// found the next key at pi
CopyKey (pi, result);
// define new line L(pi, pj)
p0 = pi;
p1 = pj;
}
// the last point is always part of the simplification
CopyKey (pj, result);
return result;
}
/*!
\brief Performs Opheim approximation (OP).
The O(n) OP routine is very similar to the Reumann-Witkam (RW) routine, and can be seen
as a constrained version of that RW routine. OP uses both a minimum and a maximum
distance tolerance to constrain the search area. For each successive vertex vi, its
radial distance to the current key vkey (initially v0) is calculated. The last point
within the minimum distance tolerance is used to define a ray R (vkey, vi). If no
such vi exists, the ray is defined as R(vkey, vkey+1). For each successive vertex vj
beyond vi its perpendicular distance to the ray R is calculated. A new key is found at
vj-1, when this distance exceeds the minimum tolerance Or when the radial distance
between vj and the vkey exceeds the maximum tolerance. After a new key is found, the
process repeats itself.
\image html psimpl_op.png
OP routine is applied to the range [first, last) using the specified distance tolerances
min_tol and max_tol. The resulting simplified polyline is copied to the output range
[result, result + m*DIM), where m is the number of vertices of the simplified polyline.
The return value is the end of the output range: result + m*DIM.
Input (Type) Requirements:
1- DIM is not 0, where DIM represents the dimension of the polyline
2- The InputIterator type models the concept of a forward iterator
3- The input iterator value type is convertible to a value type of the output iterator
4- The range [first, last) contains vertex coordinates in multiples of DIM,
f.e.: x, y, z, x, y, z, x, y, z when DIM = 3
5- The range [first, last) contains at least 2 vertices
6- min_tol is not 0
7- max_tol is not 0
In case these requirements are not met, the entire input range [first, last) is copied
to the output range [result, result + (last - first)) OR compile errors may occur.
\param[in] first the first coordinate of the first polyline point
\param[in] last one beyond the last coordinate of the last polyline point
\param[in] min_tol radial and perpendicular (point-to-ray) distance tolerance
\param[in] max_tol radial distance tolerance
\param[in] result destination of the simplified polyline
\return one beyond the last coordinate of the simplified polyline
*/
OutputIterator Opheim (
InputIterator first,
InputIterator last,
value_type min_tol,
value_type max_tol,
OutputIterator result)
{
diff_type coordCount = std::distance (first, last);
diff_type pointCount = DIM // protect against zero DIM
? coordCount / DIM
: 0;
value_type min_tol2 = min_tol * min_tol; // squared minimum distance tolerance
value_type max_tol2 = max_tol * max_tol; // squared maximum distance tolerance
// validate input and check if simplification required
if (coordCount % DIM || pointCount < 3 || min_tol2 == 0 || max_tol2 == 0) {
return std::copy (first, last, result);
}
// define the ray R(r0, r1)
InputIterator r0 = first; // indicates the current key and start of the ray
InputIterator r1 = first; // indicates a point on the ray
bool rayDefined = false;
// keep track of two test points
InputIterator pi = r0; // the previous test point
InputIterator pj = // the current test point (pi+1)
AdvanceCopy (pi);
// the first point is always part of the simplification
CopyKey (r0, result);
for (diff_type j = 2; j < pointCount; ++j) {
pi = pj;
Advance (pj);
if (!rayDefined) {
// discard each point within minimum tolerance
if (math::point_distance2 <DIM> (r0, pj) < min_tol2) {
continue;
}
// the last point within minimum tolerance pi defines the ray R(r0, r1)
r1 = pi;
rayDefined = true;
}
// check each point pj against R(r0, r1)
if (math::point_distance2 <DIM> (r0, pj) < max_tol2 &&
math::ray_distance2 <DIM> (r0, r1, pj) < min_tol2)
{
continue;
}
// found the next key at pi
CopyKey (pi, result);
// define new ray R(pi, pj)
r0 = pi;
rayDefined = false;
}
// the last point is always part of the simplification
CopyKey (pj, result);
return result;
}
/*!
\brief Performs Lang approximation (LA).
The LA routine defines a fixed size search-region. The first and last points of that
search region form a segment. This segment is used to calculate the perpendicular
distance to each intermediate point. If any calculated distance is larger than the
specified tolerance, the search region will be shrunk by excluding its last point. This
process will continue untill all calculated distances fall below the specified tolerance
, or there are no more intermediate points. At this point all intermediate points are
removed and a new search region is defined starting at the last point from old search
region.
Note that the size of the search region (look_ahead parameter) controls the maximum
amount of simplification, e.g.: a size of 20 will always result in a simplification that
contains at least 5% of the original points.
\image html psimpl_la.png
LA routine is applied to the range [first, last) using the specified tolerance and
look ahead values. The resulting simplified polyline is copied to the output range
[result, result + m*DIM), where m is the number of vertices of the simplified polyline.
The return value is the end of the output range: result + m*DIM.
Input (Type) Requirements:
1- DIM is not 0, where DIM represents the dimension of the polyline
2- The InputIterator type models the concept of a bidirectional iterator
3- The InputIterator value type is convertible to a value type of the output iterator
4- The range [first, last) contains vertex coordinates in multiples of DIM,
f.e.: x, y, z, x, y, z, x, y, z when DIM = 3
5- The range [first, last) contains at least 2 vertices
6- tol is not 0
7- look_ahead is not zero
In case these requirements are not met, the entire input range [first, last) is copied
to the output range [result, result + (last - first)) OR compile errors may occur.
\param[in] first the first coordinate of the first polyline point
\param[in] last one beyond the last coordinate of the last polyline point
\param[in] tol perpendicular (point-to-segment) distance tolerance
\param[in] look_ahead defines the size of the search region
\param[in] result destination of the simplified polyline
\return one beyond the last coordinate of the simplified polyline
*/
OutputIterator Lang (
InputIterator first,
InputIterator last,
value_type tol,
unsigned look_ahead,
OutputIterator result)
{
diff_type coordCount = std::distance (first, last);
diff_type pointCount = DIM // protect against zero DIM
? coordCount / DIM
: 0;
value_type tol2 = tol * tol; // squared minimum distance tolerance
// validate input and check if simplification required
if (coordCount % DIM || pointCount < 3 || look_ahead < 2 || tol2 == 0) {
return std::copy (first, last, result);
}
InputIterator current = first; // indicates the current key
InputIterator next = first; // used to find the next key
unsigned remaining = pointCount - 1; // the number of points remaining after current
unsigned moved = Forward (next, look_ahead, remaining);