File: buffer2.c

package info (click to toggle)
grass 8.4.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 277,040 kB
  • sloc: ansic: 460,798; python: 227,732; cpp: 42,026; sh: 11,262; makefile: 7,007; xml: 3,637; sql: 968; lex: 520; javascript: 484; yacc: 450; asm: 387; perl: 157; sed: 25; objc: 6; ruby: 4
file content (1208 lines) | stat: -rw-r--r-- 38,569 bytes parent folder | download | duplicates (2)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
/*!
   \file lib/vector/Vlib/buffer2.c

   \brief Vector library - nearest, adjust, parallel lines

   Higher level functions for reading/writing/manipulating vectors.

   (C) 2001-2009 by the GRASS Development Team

   This program is free software under the
   GNU General Public License (>=v2).
   Read the file COPYING that comes with GRASS
   for details.

   \author Original author Radim Blazek (see buffer.c)
   \author Rewritten by Rosen Matev (Google Summer of Code 2008)
 */

#include <stdlib.h>
#include <math.h>
#include <grass/gis.h>
#include <grass/vector.h>
#include <grass/glocale.h>

#include "dgraph.h"

#define LENGTH(DX, DY)  (sqrt((DX * DX) + (DY * DY)))
#define PI              M_PI
#define RIGHT_SIDE      1
#define LEFT_SIDE       -1
#define LOOPED_LINE     1
#define NON_LOOPED_LINE 0

/* norm_vector() calculates normalized vector form two points */
static void norm_vector(double x1, double y1, double x2, double y2, double *x,
                        double *y)
{
    double dx, dy, l;

    dx = x2 - x1;
    dy = y2 - y1;
    if ((dx == 0) && (dy == 0)) {
        /* assume that dx == dy == 0, which should give (NaN,NaN) */
        /* without this, very small dx or dy could result in Infinity */
        *x = 0;
        *y = 0;
        return;
    }
    l = LENGTH(dx, dy);
    *x = dx / l;
    *y = dy / l;

    return;
}

static void rotate_vector(double x, double y, double cosa, double sina,
                          double *nx, double *ny)
{
    *nx = x * cosa - y * sina;
    *ny = x * sina + y * cosa;

    return;
}

/*
 * (x,y) should be normalized vector for common transforms; This func transforms
 * (x,y) to a vector corresponding to da, db, dalpha params dalpha is in radians
 */
static void elliptic_transform(double x, double y, double da, double db,
                               double dalpha, double *nx, double *ny)
{
    double cosa = cos(dalpha);
    double sina = sin(dalpha);

    /*    double cc = cosa*cosa;
       double ss = sina*sina;
       double t = (da-db)*sina*cosa;

       *nx = (da*cc + db*ss)*x + t*y;
       *ny = (da*ss + db*cc)*y + t*x;
       return; */

    double va, vb;

    va = (x * cosa + y * sina) * da;
    vb = (x * (-sina) + y * cosa) * db;
    *nx = va * cosa + vb * (-sina);
    *ny = va * sina + vb * cosa;

    return;
}

/*
 * vect(x,y) must be normalized
 * gives the tangent point of the tangent to ellpise(da,db,dalpha) parallel to
 * vect(x,y) dalpha is in radians ellipse center is in (0,0)
 */
static void elliptic_tangent(double x, double y, double da, double db,
                             double dalpha, double *px, double *py)
{
    double cosa = cos(dalpha);
    double sina = sin(dalpha);
    double u, v, len;

    /* rotate (x,y) -dalpha radians */
    rotate_vector(x, y, cosa, -sina, &x, &y);
    /*u = (x + da*y/db)/2;
       v = (y - db*x/da)/2; */
    u = da * da * y;
    v = -db * db * x;
    len = da * db / sqrt(da * da * v * v + db * db * u * u);
    u *= len;
    v *= len;
    rotate_vector(u, v, cosa, sina, px, py);

    return;
}

/*
 * !!! This is not line in GRASS' sense. See
 * https://en.wikipedia.org/wiki/Line_%28mathematics%29
 */
static void line_coefficients(double x1, double y1, double x2, double y2,
                              double *a, double *b, double *c)
{
    *a = y2 - y1;
    *b = x1 - x2;
    *c = x2 * y1 - x1 * y2;

    return;
}

/*
 * Finds intersection of two straight lines. Returns 0 if the lines are
 * parallel, 1 if they cross, 2 if they are the same line.
 * !!!!!!!!!!!!!!!! FIX THIS TOLERANCE CONSTANTS BAD (and UGLY) CODE !!!!!!!!!
 */
static int line_intersection(double a1, double b1, double c1, double a2,
                             double b2, double c2, double *x, double *y)
{
    double d;

    if (fabs(a2 * b1 - a1 * b2) == 0) {
        if (fabs(a2 * c1 - a1 * c2) == 0)
            return 2;
        else
            return 0;
    }
    else {
        d = a1 * b2 - a2 * b1;
        *x = (b1 * c2 - b2 * c1) / d;
        *y = (c1 * a2 - c2 * a1) / d;
        return 1;
    }
}

static double angular_tolerance(double tol, double da, double db)
{
    double a = MAX(da, db);

    if (tol > a)
        tol = a;

    return 2 * acos(1 - tol / a);
}

/*
 * This function generates parallel line (with loops, but not like the old
 * ones). It is not to be used directly for creating buffers.
 * + added elliptical buffers/par.lines support
 *
 * dalpha - direction of elliptical buffer major axis in degrees
 * da - distance along major axis
 * db: distance along minor (perp.) axis
 * side: side >= 0 - right side, side < 0 - left side
 * when (da == db) we have plain distances (old case)
 * round - 1 for round corners, 0 for sharp corners. (tol is used only if round
 * == 1)
 */
static void parallel_line(struct line_pnts *Points, double da, double db,
                          double dalpha, int side, int round, int caps,
                          int looped, double tol, struct line_pnts *nPoints)
{
    int i, j, res, np;
    double *x, *y;
    double tx, ty, vx, vy, wx, wy, nx, ny, mx, my, rx, ry;
    double vx1, vy1, wx1, wy1;
    double a0, b0, c0, a1, b1, c1;
    double phi1, phi2, delta_phi;
    double nsegments, angular_tol, angular_step;
    int inner_corner, turns360;

    G_debug(3, "parallel_line()");

    if (looped && 0) {
        /* start point != end point */
        return;
    }

    Vect_reset_line(nPoints);

    if (looped) {
        Vect_append_point(Points, Points->x[1], Points->y[1], Points->z[1]);
    }
    np = Points->n_points;
    x = Points->x;
    y = Points->y;

    if ((np == 0) || (np == 1))
        return;

    if ((da == 0) || (db == 0)) {
        Vect_copy_xyz_to_pnts(nPoints, x, y, NULL, np);
        return;
    }

    side = (side >= 0) ? (1) : (-1); /* normalize variable */
    dalpha *= PI / 180; /* convert dalpha from degrees to radians */
    angular_tol = angular_tolerance(tol, da, db);

    for (i = 0; i < np - 1; i++) {
        /* save the old values */
        a0 = a1;
        b0 = b1;
        c0 = c1;
        wx = vx;
        wy = vy;

        norm_vector(x[i], y[i], x[i + 1], y[i + 1], &tx, &ty);
        if ((tx == 0) && (ty == 0))
            continue;

        elliptic_tangent(side * tx, side * ty, da, db, dalpha, &vx, &vy);

        nx = x[i] + vx;
        ny = y[i] + vy;

        mx = x[i + 1] + vx;
        my = y[i + 1] + vy;

        line_coefficients(nx, ny, mx, my, &a1, &b1, &c1);

        if (i == 0) {
            if (!looped)
                Vect_append_point(nPoints, nx, ny, 0);
            continue;
        }

        delta_phi = atan2(ty, tx) - atan2(y[i] - y[i - 1], x[i] - x[i - 1]);
        if (delta_phi > PI)
            delta_phi -= 2 * PI;
        else if (delta_phi <= -PI)
            delta_phi += 2 * PI;
        /* now delta_phi is in [-pi;pi] */
        turns360 = (fabs(fabs(delta_phi) - PI) < 1e-15);
        inner_corner = (side * delta_phi <= 0) && (!turns360);

        if ((turns360) && (!(caps && round))) {
            if (caps) {
                norm_vector(0, 0, vx, vy, &tx, &ty);
                elliptic_tangent(side * tx, side * ty, da, db, dalpha, &tx,
                                 &ty);
            }
            else {
                tx = 0;
                ty = 0;
            }
            Vect_append_point(nPoints, x[i] + wx + tx, y[i] + wy + ty, 0);
            Vect_append_point(nPoints, nx + tx, ny + ty,
                              0); /* nx == x[i] + vx, ny == y[i] + vy */
        }
        else if ((!round) || inner_corner) {
            res = line_intersection(a0, b0, c0, a1, b1, c1, &rx, &ry);
            /*                if (res == 0) {
               G_debug(4, "a0=%.18f, b0=%.18f, c0=%.18f, a1=%.18f, b1=%.18f,
               c1=%.18f", a0, b0, c0, a1, b1, c1); G_fatal_error("Two
               consecutive line segments are parallel, but not on one straight
               line! This should never happen."); return;
               }  */
            if (res == 1) {
                if (!round)
                    Vect_append_point(nPoints, rx, ry, 0);
                else {
                    /*                    d = dig_distance2_point_to_line(rx,
                       ry, 0, x[i-1], y[i-1], 0, x[i], y[i], 0, 0, NULL, NULL,
                       NULL, NULL, NULL); if ( */
                    Vect_append_point(nPoints, rx, ry, 0);
                }
            }
        }
        else {
            /* we should draw elliptical arc for outside corner */

            /* inverse transforms */
            elliptic_transform(wx, wy, 1 / da, 1 / db, dalpha, &wx1, &wy1);
            elliptic_transform(vx, vy, 1 / da, 1 / db, dalpha, &vx1, &vy1);

            phi1 = atan2(wy1, wx1);
            phi2 = atan2(vy1, vx1);
            delta_phi = side * (phi2 - phi1);

            /* make delta_phi in [0, 2pi] */
            if (delta_phi < 0)
                delta_phi += 2 * PI;

            nsegments = (int)(delta_phi / angular_tol) + 1;
            angular_step = side * (delta_phi / nsegments);

            for (j = 0; j <= nsegments; j++) {
                elliptic_transform(cos(phi1), sin(phi1), da, db, dalpha, &tx,
                                   &ty);
                Vect_append_point(nPoints, x[i] + tx, y[i] + ty, 0);
                phi1 += angular_step;
            }
        }

        if ((!looped) && (i == np - 2)) {
            Vect_append_point(nPoints, mx, my, 0);
        }
    }

    if (looped) {
        Vect_append_point(nPoints, nPoints->x[0], nPoints->y[0], nPoints->z[0]);
    }

    Vect_line_prune(nPoints);

    if (looped) {
        Vect_line_delete_point(Points, Points->n_points - 1);
    }
}

/* input line must be looped */
static void convolution_line(struct line_pnts *Points, double da, double db,
                             double dalpha, int side, int round, int caps,
                             double tol, struct line_pnts *nPoints)
{
    int i, j, res, np;
    double *x, *y;
    double tx, ty, vx, vy, wx, wy, nx, ny, mx, my, rx, ry;
    double vx1, vy1, wx1, wy1;
    double a0, b0, c0, a1, b1, c1;
    double phi1, phi2, delta_phi;
    double nsegments, angular_tol, angular_step;
    double angle0, angle1;
    int inner_corner, turns360;

    G_debug(3, "convolution_line() side = %d", side);

    np = Points->n_points;
    x = Points->x;
    y = Points->y;
    if ((np == 0) || (np == 1))
        return;
    if ((x[0] != x[np - 1]) || (y[0] != y[np - 1])) {
        G_fatal_error(_("Line is not looped"));
        return;
    }

    Vect_reset_line(nPoints);

    if ((da == 0) || (db == 0)) {
        Vect_copy_xyz_to_pnts(nPoints, x, y, NULL, np);
        return;
    }

    side = (side >= 0) ? (1) : (-1); /* normalize variable */
    dalpha *= PI / 180; /* convert dalpha from degrees to radians */
    angular_tol = angular_tolerance(tol, da, db);

    i = np - 2;
    norm_vector(x[i], y[i], x[i + 1], y[i + 1], &tx, &ty);
    elliptic_tangent(side * tx, side * ty, da, db, dalpha, &vx, &vy);
    angle1 = atan2(ty, tx);
    nx = x[i] + vx;
    ny = y[i] + vy;
    mx = x[i + 1] + vx;
    my = y[i + 1] + vy;
    if (!round)
        line_coefficients(nx, ny, mx, my, &a1, &b1, &c1);

    for (i = 0; i <= np - 2; i++) {
        G_debug(4, "point %d, segment %d-%d", i, i, i + 1);
        /* save the old values */
        if (!round) {
            a0 = a1;
            b0 = b1;
            c0 = c1;
        }
        wx = vx;
        wy = vy;
        angle0 = angle1;

        norm_vector(x[i], y[i], x[i + 1], y[i + 1], &tx, &ty);
        if ((tx == 0) && (ty == 0))
            continue;
        elliptic_tangent(side * tx, side * ty, da, db, dalpha, &vx, &vy);
        angle1 = atan2(ty, tx);
        nx = x[i] + vx;
        ny = y[i] + vy;
        mx = x[i + 1] + vx;
        my = y[i + 1] + vy;
        if (!round)
            line_coefficients(nx, ny, mx, my, &a1, &b1, &c1);

        delta_phi = angle1 - angle0;
        if (delta_phi > PI)
            delta_phi -= 2 * PI;
        else if (delta_phi <= -PI)
            delta_phi += 2 * PI;
        /* now delta_phi is in [-pi;pi] */
        turns360 = (fabs(fabs(delta_phi) - PI) < 1e-15);
        inner_corner = (side * delta_phi <= 0) && (!turns360);

        /* if <line turns 360> and (<caps> and <not round>) */
        if (turns360 && caps && (!round)) {
            norm_vector(0, 0, vx, vy, &tx, &ty);
            elliptic_tangent(side * tx, side * ty, da, db, dalpha, &tx, &ty);
            Vect_append_point(nPoints, x[i] + wx + tx, y[i] + wy + ty, 0);
            G_debug(4, " append point (c) x=%.16f y=%.16f", x[i] + wx + tx,
                    y[i] + wy + ty);
            Vect_append_point(nPoints, nx + tx, ny + ty,
                              0); /* nx == x[i] + vx, ny == y[i] + vy */
            G_debug(4, " append point (c) x=%.16f y=%.16f", nx + tx, ny + ty);
        }

        if ((!turns360) && (!round) && (!inner_corner)) {
            res = line_intersection(a0, b0, c0, a1, b1, c1, &rx, &ry);
            if (res == 1) {
                Vect_append_point(nPoints, rx, ry, 0);
                G_debug(4, " append point (o) x=%.16f y=%.16f", rx, ry);
            }
            else if (res == 2) {
                /* no need to append point in this case */
            }
            else
                G_fatal_error(
                    _("Unexpected result of line_intersection() res = %d"),
                    res);
        }

        if (round && (!inner_corner) && (!turns360 || caps)) {
            /* we should draw elliptical arc for outside corner */

            /* inverse transforms */
            elliptic_transform(wx, wy, 1 / da, 1 / db, dalpha, &wx1, &wy1);
            elliptic_transform(vx, vy, 1 / da, 1 / db, dalpha, &vx1, &vy1);

            phi1 = atan2(wy1, wx1);
            phi2 = atan2(vy1, vx1);
            delta_phi = side * (phi2 - phi1);

            /* make delta_phi in [0, 2pi] */
            if (delta_phi < 0)
                delta_phi += 2 * PI;

            nsegments = (int)(delta_phi / angular_tol) + 1;
            angular_step = side * (delta_phi / nsegments);

            phi1 += angular_step;
            for (j = 1; j <= nsegments - 1; j++) {
                elliptic_transform(cos(phi1), sin(phi1), da, db, dalpha, &tx,
                                   &ty);
                Vect_append_point(nPoints, x[i] + tx, y[i] + ty, 0);
                G_debug(4, " append point (r) x=%.16f y=%.16f", x[i] + tx,
                        y[i] + ty);
                phi1 += angular_step;
            }
        }

        Vect_append_point(nPoints, nx, ny, 0);
        G_debug(4, " append point (s) x=%.16f y=%.16f", nx, ny);
        Vect_append_point(nPoints, mx, my, 0);
        G_debug(4, " append point (s) x=%.16f y=%.16f", mx, my);
    }

    /* close the output line */
    Vect_append_point(nPoints, nPoints->x[0], nPoints->y[0], nPoints->z[0]);
    Vect_line_prune(nPoints);
}

/*
 * side: side >= 0 - extracts contour on right side of edge, side < 0 - extracts
 * contour on left side of edge if the extracted contour is the outer contour,
 * it is returned in ccw order else if it is inner contour, it is returned in cw
 * order
 */
static void extract_contour(struct planar_graph *pg, struct pg_edge *first,
                            int side, int winding, int stop_at_line_end,
                            struct line_pnts *nPoints)
{
    int j;
    int v; /* current vertex number */
    int v0;
    int eside;     /* side of the current edge */
    double eangle; /* current edge angle with Ox (according to the current
                      direction) */
    struct pg_vertex *vert;  /* current vertex */
    struct pg_vertex *vert0; /* last vertex */
    struct pg_edge *edge;    /* current edge; must be edge of vert */

    /*    int cs; */ /* on which side are we turning along the contour */
    /* we will always turn right and don't need that one */
    double opt_angle, tangle;
    int opt_j, opt_side, opt_flag;

    G_debug(3, "extract_contour(): v1=%d, v2=%d, side=%d, stop_at_line_end=%d",
            first->v1, first->v2, side, stop_at_line_end);

    Vect_reset_line(nPoints);

    edge = first;
    if (side >= 0) {
        eside = 1;
        v0 = edge->v1;
        v = edge->v2;
    }
    else {
        eside = -1;
        v0 = edge->v2;
        v = edge->v1;
    }
    vert0 = &(pg->v[v0]);
    vert = &(pg->v[v]);
    eangle = atan2(vert->y - vert0->y, vert->x - vert0->x);

    while (1) {
        Vect_append_point(nPoints, vert0->x, vert0->y, 0);
        G_debug(4, "ec: v0=%d, v=%d, eside=%d, edge->v1=%d, edge->v2=%d", v0, v,
                eside, edge->v1, edge->v2);
        G_debug(4, "ec: append point x=%.18f y=%.18f", vert0->x, vert0->y);

        /* mark current edge as visited on the appropriate side */
        if (eside == 1) {
            edge->visited_right = 1;
            edge->winding_right = winding;
        }
        else {
            edge->visited_left = 1;
            edge->winding_left = winding;
        }

        opt_flag = 1;
        for (j = 0; j < vert->ecount; j++) {
            /* exclude current edge */
            if (vert->edges[j] != edge) {
                tangle = vert->angles[j] - eangle;
                if (tangle < -PI)
                    tangle += 2 * PI;
                else if (tangle > PI)
                    tangle -= 2 * PI;
                /* now tangle is in (-PI, PI) */

                if (opt_flag || (tangle < opt_angle)) {
                    opt_j = j;
                    opt_side = (vert->edges[j]->v1 == v) ? (1) : (-1);
                    opt_angle = tangle;
                    opt_flag = 0;
                }
            }
        }

        /*
           G_debug(4, "ec: opt: side=%d opt_flag=%d opt_angle=%.18f opt_j=%d
           opt_step=%d", side, opt_flag, opt_angle, opt_j, opt_step);
         */

        /* if line end is reached (no other edges at curr vertex) */
        if (opt_flag) {
            if (stop_at_line_end) {
                G_debug(3, "    end has been reached, will stop here");
                break;
            }
            else {
                opt_j = 0; /* the only edge of vert is vert->edges[0] */
                opt_side =
                    -eside; /* go to the other side of the current edge */
                G_debug(3, "    end has been reached, turning around");
            }
        }

        /* break condition */
        if ((vert->edges[opt_j] == first) && (opt_side == side))
            break;
        if (opt_side == 1) {
            if (vert->edges[opt_j]->visited_right) {
                G_warning(_("Next edge was visited (right) but it is not the "
                            "first one !!! breaking loop"));
                G_debug(4,
                        "ec: v0=%d, v=%d, eside=%d, edge->v1=%d, edge->v2=%d",
                        v, (edge->v1 == v) ? (edge->v2) : (edge->v1), opt_side,
                        vert->edges[opt_j]->v1, vert->edges[opt_j]->v2);
                break;
            }
        }
        else {
            if (vert->edges[opt_j]->visited_left) {
                G_warning(_("Next edge was visited (left) but it is not the "
                            "first one !!! breaking loop"));
                G_debug(4,
                        "ec: v0=%d, v=%d, eside=%d, edge->v1=%d, edge->v2=%d",
                        v, (edge->v1 == v) ? (edge->v2) : (edge->v1), opt_side,
                        vert->edges[opt_j]->v1, vert->edges[opt_j]->v2);
                break;
            }
        }

        edge = vert->edges[opt_j];
        eside = opt_side;
        v0 = v;
        v = (edge->v1 == v) ? (edge->v2) : (edge->v1);
        vert0 = vert;
        vert = &(pg->v[v]);
        eangle = vert0->angles[opt_j];
    }
    Vect_append_point(nPoints, vert->x, vert->y, 0);
    Vect_line_prune(nPoints);
    G_debug(4, "ec: append point x=%.18f y=%.18f", vert->x, vert->y);

    return;
}

/*
 * This function extracts the outer contour of a (self crossing) line.
 * It can generate left/right contour if none of the line ends are in a loop.
 * If one or both of them is in a loop, then there's only one contour
 *
 * side: side > 0 - right contour, side < 0 - left contour, side = 0 - outer
 * contour if side != 0 and there's only one contour, the function returns it
 *
 * TODO: Implement side != 0 feature;
 */
static void extract_outer_contour(struct planar_graph *pg, int side,
                                  struct line_pnts *nPoints)
{
    int i;
    int flag;
    int v;
    struct pg_vertex *vert;
    struct pg_edge *edge;
    double min_x, min_angle;

    G_debug(3, "extract_outer_contour()");

    if (side != 0) {
        G_fatal_error(_("side != 0 feature not implemented"));
        return;
    }

    /* find a line segment which is on the outer contour */
    flag = 1;
    for (i = 0; i < pg->vcount; i++) {
        if (flag || (pg->v[i].x < min_x)) {
            v = i;
            min_x = pg->v[i].x;
            flag = 0;
        }
    }
    vert = &(pg->v[v]);

    flag = 1;
    for (i = 0; i < vert->ecount; i++) {
        if (flag || (vert->angles[i] < min_angle)) {
            edge = vert->edges[i];
            min_angle = vert->angles[i];
            flag = 0;
        }
    }

    /* the winding on the outer contour is 0 */
    extract_contour(pg, edge, (edge->v1 == v) ? RIGHT_SIDE : LEFT_SIDE, 0, 0,
                    nPoints);

    return;
}

/*
 * Extracts contours which are not visited.
 * IMPORTANT: the outer contour must be visited (you should call
 * extract_outer_contour() to do that), so that extract_inner_contour() doesn't
 * return it
 *
 * returns: 0 when there are no more inner contours; otherwise, 1
 */
static int extract_inner_contour(struct planar_graph *pg, int *winding,
                                 struct line_pnts *nPoints)
{
    int i, w;
    struct pg_edge *edge;

    G_debug(3, "extract_inner_contour()");

    for (i = 0; i < pg->ecount; i++) {
        edge = &(pg->e[i]);
        if (edge->visited_left) {
            if (!(pg->e[i].visited_right)) {
                w = edge->winding_left - 1;
                extract_contour(pg, &(pg->e[i]), RIGHT_SIDE, w, 0, nPoints);
                *winding = w;
                return 1;
            }
        }
        else {
            if (pg->e[i].visited_right) {
                w = edge->winding_right + 1;
                extract_contour(pg, &(pg->e[i]), LEFT_SIDE, w, 0, nPoints);
                *winding = w;
                return 1;
            }
        }
    }

    return 0;
}

/* point_in_buf - test if point px,py is in d buffer of Points
 ** dalpha is in degrees
 ** returns:  1 in buffer
 **           0 not in buffer
 */
static int point_in_buf(struct line_pnts *Points, double px, double py,
                        double da, double db, double dalpha)
{
    int i, np;
    double cx, cy;
    double delta, delta_k, k;
    double vx, vy, wx, wy, mx, my, nx, ny;
    double len, tx, ty, d, da2;

    G_debug(3, "point_in_buf()");

    dalpha *= PI / 180; /* convert dalpha from degrees to radians */

    np = Points->n_points;
    da2 = da * da;
    for (i = 0; i < np - 1; i++) {
        vx = Points->x[i];
        vy = Points->y[i];
        wx = Points->x[i + 1];
        wy = Points->y[i + 1];

        if (da != db) {
            mx = wx - vx;
            my = wy - vy;
            len = LENGTH(mx, my);
            elliptic_tangent(mx / len, my / len, da, db, dalpha, &cx, &cy);

            delta = mx * cy - my * cx;
            delta_k = (px - vx) * cy - (py - vy) * cx;
            k = delta_k / delta;
            /*            G_debug(4, "k = %g, k1 = %g", k, (mx * (px - vx) + my
             * * (py - vy)) / (mx * mx + my * my)); */
            if (k <= 0) {
                nx = vx;
                ny = vy;
            }
            else if (k >= 1) {
                nx = wx;
                ny = wy;
            }
            else {
                nx = vx + k * mx;
                ny = vy + k * my;
            }

            /* inverse transform */
            elliptic_transform(px - nx, py - ny, 1 / da, 1 / db, dalpha, &tx,
                               &ty);

            d = dig_distance2_point_to_line(nx + tx, ny + ty, 0, vx, vy, 0, wx,
                                            wy, 0, 0, NULL, NULL, NULL, NULL,
                                            NULL);

            /*            G_debug(4, "sqrt(d)*da = %g, len' = %g, olen = %g",
             * sqrt(d)*da, da*LENGTH(tx,ty), LENGTH((px-nx),(py-ny))); */
            if (d <= 1) {
                /* G_debug(1, "d=%g", d); */
                return 1;
            }
        }
        else {
            d = dig_distance2_point_to_line(px, py, 0, vx, vy, 0, wx, wy, 0, 0,
                                            NULL, NULL, NULL, NULL, NULL);
            /*            G_debug(4, "sqrt(d)     = %g", sqrt(d)); */
            if (d <= da2) {
                return 1;
            }
        }
    }

    return 0;
}

/* returns 0 for ccw, non-zero for cw
 */
static int get_polygon_orientation(const double *x, const double *y, int n)
{
    double x1, y1, x2, y2;
    double area;

    x2 = x[n - 1];
    y2 = y[n - 1];

    area = 0;
    while (--n >= 0) {
        x1 = x2;
        y1 = y2;

        x2 = *x++;
        y2 = *y++;

        area += (y2 + y1) * (x2 - x1);
    }

    return (area > 0);
}

/* internal */
static void add_line_to_array(struct line_pnts *Points,
                              struct line_pnts ***arrPoints, int *count,
                              int *allocated, int more)
{
    if (*allocated == *count) {
        *allocated += more;
        *arrPoints =
            G_realloc(*arrPoints, (*allocated) * sizeof(struct line_pnts *));
    }
    (*arrPoints)[*count] = Points;
    (*count)++;

    return;
}

static void destroy_lines_array(struct line_pnts **arr, int count)
{
    int i;

    for (i = 0; i < count; i++)
        Vect_destroy_line_struct(arr[i]);
    G_free(arr);
}

/* area_outer and area_isles[i] must be closed non self-intersecting lines
   side: 0 - auto, 1 - right, -1 left
 */
static void buffer_lines(struct line_pnts *area_outer,
                         struct line_pnts **area_isles, int isles_count,
                         int side, double da, double db, double dalpha,
                         int round, int caps, double tol,
                         struct line_pnts **oPoints,
                         struct line_pnts ***iPoints, int *inner_count)
{
    struct planar_graph *pg2;
    struct line_pnts *sPoints, *cPoints;
    struct line_pnts **arrPoints;
    int i, count = 0;
    int res, winding;
    int auto_side;
    int more = 8;
    int allocated = 0;
    double px, py;

    G_debug(3, "buffer_lines()");

    auto_side = (side == 0);

    /* initializations */
    sPoints = Vect_new_line_struct();
    cPoints = Vect_new_line_struct();
    arrPoints = NULL;

    /* outer contour */
    G_debug(3, "    processing outer contour");
    *oPoints = Vect_new_line_struct();
    if (auto_side)
        side = get_polygon_orientation(area_outer->x, area_outer->y,
                                       area_outer->n_points - 1)
                   ? LEFT_SIDE
                   : RIGHT_SIDE;
    convolution_line(area_outer, da, db, dalpha, side, round, caps, tol,
                     sPoints);
    pg2 = pg_create(sPoints);
    extract_outer_contour(pg2, 0, *oPoints);
    res = extract_inner_contour(pg2, &winding, cPoints);
    while (res != 0) {
        if (winding == 0) {
            int check_poly = 1;
            double area_size;

            dig_find_area_poly(cPoints, &area_size);
            if (area_size == 0) {
                G_warning(_("zero area size"));
                check_poly = 0;
            }
            if (cPoints->x[0] != cPoints->x[cPoints->n_points - 1] ||
                cPoints->y[0] != cPoints->y[cPoints->n_points - 1]) {

                G_warning(_("Line was not closed"));
                check_poly = 0;
            }

            if (check_poly &&
                !Vect_point_in_poly(cPoints->x[0], cPoints->y[0], area_outer)) {
                if (Vect_get_point_in_poly(cPoints, &px, &py) == 0) {
                    if (!point_in_buf(area_outer, px, py, da, db, dalpha)) {
                        add_line_to_array(cPoints, &arrPoints, &count,
                                          &allocated, more);
                        cPoints = Vect_new_line_struct();
                    }
                }
                else {
                    G_warning(_("Vect_get_point_in_poly() failed"));
                }
            }
        }
        res = extract_inner_contour(pg2, &winding, cPoints);
    }
    pg_destroy_struct(pg2);

    /* inner contours */
    G_debug(3, "    processing inner contours");
    for (i = 0; i < isles_count; i++) {
        if (auto_side)
            side = get_polygon_orientation(area_isles[i]->x, area_isles[i]->y,
                                           area_isles[i]->n_points - 1)
                       ? RIGHT_SIDE
                       : LEFT_SIDE;
        convolution_line(area_isles[i], da, db, dalpha, side, round, caps, tol,
                         sPoints);
        pg2 = pg_create(sPoints);
        extract_outer_contour(pg2, 0, cPoints);
        res = extract_inner_contour(pg2, &winding, cPoints);
        while (res != 0) {
            if (winding == -1) {
                int check_poly = 1;
                double area_size;

                dig_find_area_poly(cPoints, &area_size);
                if (area_size == 0) {
                    G_warning(_("zero area size"));
                    check_poly = 0;
                }
                if (cPoints->x[0] != cPoints->x[cPoints->n_points - 1] ||
                    cPoints->y[0] != cPoints->y[cPoints->n_points - 1]) {

                    G_warning(_("Line was not closed"));
                    check_poly = 0;
                }

                /* we need to check if the area is in the buffer.
                   I've simplfied convolution_line(), so that it runs faster,
                   however that leads to occasional problems */
                if (check_poly &&
                    Vect_point_in_poly(cPoints->x[0], cPoints->y[0],
                                       area_isles[i])) {
                    if (Vect_get_point_in_poly(cPoints, &px, &py) == 0) {
                        if (!point_in_buf(area_isles[i], px, py, da, db,
                                          dalpha)) {
                            add_line_to_array(cPoints, &arrPoints, &count,
                                              &allocated, more);
                            cPoints = Vect_new_line_struct();
                        }
                    }
                    else {
                        G_warning(_("Vect_get_point_in_poly() failed"));
                    }
                }
            }
            res = extract_inner_contour(pg2, &winding, cPoints);
        }
        pg_destroy_struct(pg2);
    }

    arrPoints = G_realloc(arrPoints, count * sizeof(struct line_pnts *));
    *inner_count = count;
    *iPoints = arrPoints;

    Vect_destroy_line_struct(sPoints);
    Vect_destroy_line_struct(cPoints);

    G_debug(3, "buffer_lines() ... done");

    return;
}

/*!
   \brief Creates buffer around line.

   See also Vect_line_buffer().

   Shape of buffer endings is managed by two parameters - round and cap.
   Setting round=1, cap=1 gives "classical" buffer, while
   round=0, cap=1 gives square end, but cap=0 – butt.
   See v.buffer manual or SVG stroke-linecap for examples.

   To get "classical" buffer, set db equal to da, and dalpha to 0.

   \param Points input line geometry
   \param da distance along major axis
   \param db distance along minor axis
   \param dalpha angle between 0x and major axis
   \param round make corners round (0 - square, not 0 - round)
   \param caps add caps at line ends (0 - butt, not 0 - caps)
   \param tol maximum distance between theoretical arc and output segments
   \param[out] oPoints output polygon outer border (ccw order)
   \param[out] iPoints array of output polygon's holes (cw order)
   \param[out] inner_count number of holes
 */
void Vect_line_buffer2(const struct line_pnts *Points, double da, double db,
                       double dalpha, int round, int caps, double tol,
                       struct line_pnts **oPoints, struct line_pnts ***iPoints,
                       int *inner_count)
{
    struct planar_graph *pg;
    struct line_pnts *tPoints, *outer;
    struct line_pnts **isles;
    int isles_count = 0;
    int res, winding;
    int more = 8;
    int isles_allocated = 0;

    G_debug(2, "Vect_line_buffer()");

    Vect_line_prune((struct line_pnts *)Points);

    if (Points->n_points == 1) {
        Vect_point_buffer2(Points->x[0], Points->y[0], da, db, dalpha, round,
                           tol, oPoints);
        return;
    }

    /* initializations */
    tPoints = Vect_new_line_struct();
    isles = NULL;
    pg = pg_create(Points);

    /* outer contour */
    outer = Vect_new_line_struct();
    extract_outer_contour(pg, 0, outer);

    /* inner contours */
    res = extract_inner_contour(pg, &winding, tPoints);
    while (res != 0) {
        add_line_to_array(tPoints, &isles, &isles_count, &isles_allocated,
                          more);
        tPoints = Vect_new_line_struct();
        res = extract_inner_contour(pg, &winding, tPoints);
    }

    buffer_lines(outer, isles, isles_count, RIGHT_SIDE, da, db, dalpha, round,
                 caps, tol, oPoints, iPoints, inner_count);

    Vect_destroy_line_struct(tPoints);
    Vect_destroy_line_struct(outer);
    destroy_lines_array(isles, isles_count);
    pg_destroy_struct(pg);
}

/*!
   \brief Creates buffer around area.

   \param Map vector map
   \param area area id
   \param da distance along major axis
   \param db distance along minor axis
   \param dalpha angle between 0x and major axis
   \param round make corners round
   \param caps add caps at line ends
   \param tol maximum distance between theoretical arc and output segments
   \param[out] oPoints output polygon outer border (ccw order)
   \param[out] inner_count number of holes
   \param[out] iPoints array of output polygon's holes (cw order)
 */
void Vect_area_buffer2(struct Map_info *Map, int area, double da, double db,
                       double dalpha, int round, int caps, double tol,
                       struct line_pnts **oPoints, struct line_pnts ***iPoints,
                       int *inner_count)
{
    struct line_pnts *tPoints, *outer;
    struct line_pnts **isles;
    int isles_count = 0, n_isles;
    int i, isle;
    int more = 8;
    int isles_allocated = 0;

    G_debug(2, "Vect_area_buffer()");

    /* initializations */
    tPoints = Vect_new_line_struct();
    n_isles = Vect_get_area_num_isles(Map, area);
    isles_allocated = n_isles;
    isles = G_malloc(isles_allocated * sizeof(struct line_pnts *));

    /* outer contour */
    outer = Vect_new_line_struct();
    Vect_get_area_points(Map, area, outer);
    /* does not work with zero length line segments */
    Vect_line_prune(outer);

    /* inner contours */
    for (i = 0; i < n_isles; i++) {
        isle = Vect_get_area_isle(Map, area, i);
        Vect_get_isle_points(Map, isle, tPoints);

        /* Check if the isle is big enough */
        /*
           if (Vect_line_length(tPoints) < 2*PI*max)
           continue;
         */
        /* does not work with zero length line segments */
        Vect_line_prune(tPoints);
        add_line_to_array(tPoints, &isles, &isles_count, &isles_allocated,
                          more);
        tPoints = Vect_new_line_struct();
    }

    buffer_lines(outer, isles, isles_count, 0, da, db, dalpha, round, caps, tol,
                 oPoints, iPoints, inner_count);

    Vect_destroy_line_struct(tPoints);
    Vect_destroy_line_struct(outer);
    destroy_lines_array(isles, isles_count);

    return;
}

/*!
   \brief Creates buffer around the point (px, py).

   \param px input point x-coordinate
   \param py input point y-coordinate
   \param da distance along major axis
   \param db distance along minor axis
   \param dalpha angle between 0x and major axis
   \param round make corners round
   \param tol maximum distance between theoretical arc and output segments
   \param[out] oPoints output polygon outer border (ccw order)

   \note Currently only handles buffers with rounded corners (round = 1)
 */
void Vect_point_buffer2(double px, double py, double da, double db,
                        double dalpha, int round, double tol,
                        struct line_pnts **oPoints)
{
    double tx, ty;
    double angular_tol, angular_step, phi1;
    int j, nsegments;

    G_debug(2, "%s()", __func__);

    *oPoints = Vect_new_line_struct();

    dalpha *= PI / 180; /* convert dalpha from degrees to radians */

    if (round) {
        angular_tol = angular_tolerance(tol, da, db);

        nsegments = (int)(2 * PI / angular_tol) + 1;
        angular_step = 2 * PI / nsegments;

        phi1 = 0;
        for (j = 0; j < nsegments; j++) {
            elliptic_transform(cos(phi1), sin(phi1), da, db, dalpha, &tx, &ty);
            Vect_append_point(*oPoints, px + tx, py + ty, 0);
            phi1 += angular_step;
        }
    }
    else {
    }

    /* close the output line */
    Vect_append_point(*oPoints, (*oPoints)->x[0], (*oPoints)->y[0],
                      (*oPoints)->z[0]);

    return;
}

/*
   \brief Create parallel line

   See also Vect_line_parallel().

   \param InPoints input line geometry
   \param da distance along major axis
   \param da distance along minor axis
   \param dalpha angle between 0x and major axis
   \param round make corners round
   \param tol maximum distance between theoretical arc and output segments
   \param[out] OutPoints output line
 */
void Vect_line_parallel2(struct line_pnts *InPoints, double da, double db,
                         double dalpha, int side, int round, double tol,
                         struct line_pnts *OutPoints)
{
    G_debug(2,
            "Vect_line_parallel(): npoints = %d, da = %f, "
            "db = %f, dalpha = %f, side = %d, round_corners = %d, tol = %f",
            InPoints->n_points, da, db, dalpha, side, round, tol);

    parallel_line(InPoints, da, db, dalpha, side, round, 1, NON_LOOPED_LINE,
                  tol, OutPoints);

    /*    if (!loops)
       clean_parallel(OutPoints, InPoints, distance, rm_end);
     */

    return;
}