Mesh.cpp 43.4 KB
Newer Older
1 2 3 4 5 6 7 8
#include "Mesh.hpp"

Mesh::Mesh(Sketch &sketch) {
    Boundary = sketch.boundary();

    for (size_t i = 0; i != sketch.size_curves(); ++i) {
        auto c = sketch.curve(i);
        if (!(c->for_construction())) {
9
            BoundaryConstraints.push_back(std::make_shared<BoundaryConstraint>(c));
10 11
        }
    }
12
    sort_constraints();
13 14 15 16 17

    for (size_t i = 0; i != sketch.size_contours(); ++i) {
        Contours.push_back(sketch.contour(i));
    }

18
    new_dart_constraint(0.0, 1.0, std::make_shared<BoundaryConstraint>(nullptr));
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
}

bool Mesh::are_intersecting(size_t ei, size_t ej) const {
    // TODO, Make more detailed return type enumeration
    if (is_constrained(ei) && constraint_curve(ei) == constraint_curve(ej)) {
        return false;
    }

    Point const v00 = base(ei);
    Point const v01 = tip(ei);
    Point const v10 = base(ej);
    Point const v11 = tip(ej);

    double xs0 = (v00.X + v01.X) / 2.0;
    double ys0 = (v00.Y + v01.Y) / 2.0;
    double xs1 = (v10.X + v11.X) / 2.0;
    double ys1 = (v10.Y + v11.Y) / 2.0;

    double xd0 = (v00.X - v01.X) / 2.0;
    double yd0 = (v00.Y - v01.Y) / 2.0;
    double xd1 = (v10.X - v11.X) / 2.0;
    double yd1 = (v10.Y - v11.Y) / 2.0;

    double d0 = xd0 * xd0 + yd0 * yd0;
    double d1 = xd1 * xd1 + yd1 * yd1;
    double cross = abs(xd0 * yd1 - xd1 * yd0);
    double tol = (d0 * d1) * FLT_EPSILON;

    if (cross < tol) {
        // Lines are nearly parallel
        // There are four possible minimum distance points between the lines

        double s, dx, dy, dmin = DBL_MAX;

        s = ((xd0 - xd1) * (xs0 - xs1) + (yd0 - yd1) * (ys0 - ys1)) /
            ((xd0 - xd1) * (xd0 - xd1) + (yd0 - yd1) * (yd0 - yd1));
        if (abs(s) < 1.0 - FLT_EPSILON) {
            dx = xs0 + xd0 * s - xs1 - xd1 * s;
            dy = ys0 + yd0 * s - ys1 - yd1 * s;
            dmin = std::fmin(dmin, dx * dx + dy * dy);

            dx = xs0 - xd0 * s - xs1 + xd1 * s;
            dy = ys0 - yd0 * s - ys1 + yd1 * s;
            dmin = std::fmin(dmin, dx * dx + dy * dy);
        }

        s = ((xd0 + xd1) * (xs0 - xs1) + (yd0 + yd1) * (ys0 - ys1)) /
            ((xd0 + xd1) * (xd0 + xd1) + (yd0 + yd1) * (yd0 + yd1));
        if (abs(s) < 1.0 - FLT_EPSILON) {
            dx = xs0 + xd0 * s - xs1 + xd1 * s;
            dy = ys0 + yd0 * s - ys1 + yd1 * s;
            dmin = std::fmin(dmin, dx * dx + dy * dy);

            dx = xs0 - xd0 * s - xs1 - xd1 * s;
            dy = ys0 - yd0 * s - ys1 - yd1 * s;
            dmin = std::fmin(dmin, dx * dx + dy * dy);
        }

        tol = (d0 + d1) * FLT_EPSILON;
        return (dmin < tol);
    } else { // Lines are not parallel
        double s0 = abs(xd1 * (ys0 - ys1) - yd1 * (xs0 - xs1));
        double s1 = abs(xd0 * (ys0 - ys1) - yd0 * (xs0 - xs1));
        tol = cross * (1.0 - FLT_EPSILON);

        return (s0 < tol && s1 < tol);
    }
}

bool Mesh::edges_are_valid() const {
    bool result = true;

    for (size_t e = 0; e != Edges.size(); ++e) {
        if (e != prev(next(e))) {
            result = false;
            break;
        }
        if (e != next(prev(e))) {
            result = false;
            break;
        }
        if (e != twin(twin(e))) {
            result = false;
            break;
        }

        if ((e != twin(e))) {
            if (node(e) != node(next(twin(e)))) {
                result = false;
                break;
            }
            if (constraint_curve(e) != constraint_curve(twin(e))) {
                result = false;
                break;
            }
            if (is_constrained(e)) {
                if (orientation(e) == orientation(twin(e))) {
                    result = false;
                    break;
                }
            }

            if (node(e) == node(twin(e))) {
                result = false;
                break;
            }
        }

        if (is_constrained(e)) {
128
            DartConstraint dc = DartConstraints[Edges[e].Constraint];
129 130 131
            double tol = length(e) * FLT_EPSILON;
            if (orientation(e)) {
                Point p0 = base(e);
132
                Point p1 = dc.curve()->point(dc.S0);
133 134 135 136 137 138
                if (dist(p0,p1) > tol) {
                    result = false;
                    break;
                }

                p0 = tip(e);
139
                p1 = dc.curve()->point(dc.S1);
140 141 142 143 144 145
                if (dist(p0,p1) > tol) {
                    result = false;
                    break;
                }
            } else {
                Point p0 = base(e);
146
                Point p1 = dc.curve()->point(dc.S1);
147 148 149 150 151 152
                if (dist(p0,p1) > tol) {
                    result = false;
                    break;
                }

                p0 = tip(e);
153
                p1 = dc.curve()->point(dc.S0);
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
                if (dist(p0,p1) > tol) {
                    result = false;
                    break;
                }
            }
        }
    }

    return result;
}

bool Mesh::find_attached(Point const p, size_t &e_out) {
    double tol = length(e_out) * FLT_EPSILON;

    if (dist(tip(e_out),p) < tol) {
        return true;
    }

    size_t e_in = e_out;

    if (e_out != twin(e_out)) {
        e_out = next(twin(e_out));
        while (e_out != e_in) {
            if (dist(tip(e_out),p) < tol) {
                return true;
            } else if (e_out != twin(e_out)) {
                e_out = next(twin(e_out));
            } else {
                break;
            }
        }
    }

    if (e_out == twin(e_out)) {
        e_out = prev(e_in);
        while (e_out != twin(e_out)) {
            if (dist(base(e_out),p) < tol) {
                e_out = twin(e_out);
                return true;
            } else {
                e_out = prev(twin(e_out));
            }
        }
    }

    return false;
}

bool Mesh::refine() {
    std::vector<double> radii;
    std::vector<double> quality;
    std::vector<size_t> index;

    // TODO: Loop until quality is satisfied
    // TODO: Iteratively decrease the min and max element size until quality is satisfied
    // TODO: plan() bounds on maximum element quality
    // TODO: First: refine until maximum element size criteria is satisfied
    // TODO:        plan() out iterative maximum element size refinement
    // TODO: Then: refine until element quality cirteria is satisfied
    // TODO:        ?somehow iterate?
    // TODO: SMOOTHING!

    element_quality(radii, quality);
    //sort_permutation_ascending(quality, index);
    sort_permutation_descending(radii, index);
    size_t N = Triangles.size();

    refine_once(index, radii, quality);
    size_t M = Triangles.size();

    while (M > N) {
        N = M;
        element_quality(radii, quality);
        //sort_permutation_ascending(quality, index);
        sort_permutation_descending(radii, index);
        refine_once(index, radii, quality);
        M = Triangles.size();
    }

    return edges_are_valid(); // TODO: Instrument in tests
}

bool Mesh::refine_once() {
    std::vector<double> radii;
    std::vector<double> quality;
    std::vector<size_t> index;

    element_quality(radii, quality);
    //sort_permutation_ascending(quality, index);
    sort_permutation_descending(radii, index);
    refine_once(index, radii, quality);

    return edges_are_valid(); // TODO: Instrument in tests
}

bool Mesh::in_triangle(Point const p, size_t ei) const {
    double xp = p.X;
    double yp = p.Y;

    Point const p0 = base(ei);
    Point const p1 = base(next(ei));
    Point const p2 = base(prev(ei));

    double dx0p = p0.X - xp;
    double dy0p = p0.Y - yp;

    double dx1p = p1.X - xp;
    double dy1p = p1.Y - yp;

    double dx2p = p2.X - xp;
    double dy2p = p2.Y - yp;

    double dx01 = p0.X - p1.X;
    double dy01 = p0.Y - p1.Y;

    double dx12 = p1.X - p2.X;
    double dy12 = p1.Y - p2.Y;

    double dx20 = p2.X - p0.X;
    double dy20 = p2.Y - p0.Y;

    double area012 = dx01 * dy12 - dy01 * dx12;

    double tol = FLT_EPSILON * area012;

    double area01p = dx0p * dy1p - dx1p * dy0p;
    double area12p = dx1p * dy2p - dx2p * dy1p;
    double area20p = dx2p * dy0p - dx0p * dy2p;

    return (area01p > -tol && area12p > -tol && area20p > -tol);
}

bool Mesh::is_encroached(Point const p, size_t ei) const {
    /*
        A constrained edge is encroached if a triangle and it's circumcenter lie on opposite sides of the edge.
        This is equivalent to a node being in the diameteral ball of the edge?
        This only occurs if one of the triangles attached to the edge encroaches the edge?
        This only occurs if the angle of the triangles attached to the edge has an angle opposite the edge of greater than 90 degrees.
        Using the dot product, this requires that the normalized dot product < cos(90) = 0
    */

    if (!is_constrained(ei)) {
        return false;
    } else {
        Point const p0 = base(ei);
        Point const p1 = tip(ei);

        double dx0 = p0.X - p.X;
        double dy0 = p0.Y - p.Y;

        double dx1 = p1.X - p.X;
        double dy1 = p1.Y - p.Y;

        double dot = dx0 * dx1 + dy0 * dy1;
        double tol = std::sqrt(dx0 * dx0 + dy0 * dy0) * std::sqrt(dx1 * dx1 + dy1 * dy1) * FLT_EPSILON;

        return (dot < tol);
    }
}

bool Mesh::is_locally_optimal(size_t ei) const {
    /*
        See Chapter 3.7 of "Triangulations and Applications" by Øyvind Hjelle and Morten Dæhlen
    */

    if (is_constrained(ei)) {
        return true;
    } else {
        Point const p3 = base(ei);
        Point const p2 = base(prev(ei));
        Point const p1 = base(twin(ei));
        Point const p4 = base(prev(twin(ei)));

        double v1x = p3.X - p2.X;
        double v1y = p3.Y - p2.Y;
        double v2x = p1.X - p2.X;
        double v2y = p1.Y - p2.Y;
        double v3x = p1.X - p4.X;
        double v3y = p1.Y - p4.Y;
        double v4x = p3.X - p4.X;
        double v4y = p3.Y - p4.Y;

        double d1 = std::sqrt(v1x * v1x + v1y * v1y);
        double d2 = std::sqrt(v2x * v2x + v2y * v2y);
        double d3 = std::sqrt(v3x * v3x + v3y * v3y);
        double d4 = std::sqrt(v4x * v4x + v4y * v4y);
340
        double tol = -std::sqrt(d1 * d2 * d3 * d4) * FLT_EPSILON;
341 342 343 344 345 346 347

        double sina = v1x * v2y - v1y * v2x;
        double sinb = v3x * v4y - v3y * v4x;
        double cosa = v1x * v2x + v1y * v2y;
        double cosb = v3x * v4x + v3y * v4y;
        double cct = sina * cosb + cosa * sinb;

348
        return cct >= tol; // TODO: Optional tol for testing purposes
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
    }
}

bool Mesh::is_protruding(size_t ei) const {
    //
    //    See Chapter 1.4 of "Triangulations and Applications" by Øyvind Hjelle and Morten Dæhlen
    //

    Point const p0 = base(prev(ei));
    Point const p1 = base(ei);
    Point const p2 = base(next(ei));

    double v1x = p2.X - p1.X;
    double v1y = p2.Y - p1.Y;

    double v0x = p0.X - p1.X;
    double v0y = p0.Y - p1.Y;

    double area = v1x * v0y - v1y * v0x;

    if (area > 0.0) {
        // Make sure no boundary points interior to triangle
        // Calculate barrycentric coordinates of p

        size_t nxt = next(next(ei));
        while (nxt != prev(ei)) {
            Point const p4 = base(nxt);

            double v2x = p2.X - p4.X;
            double v2y = p2.Y - p4.Y;

            v1x = p1.X - p4.X;
            v1y = p1.Y - p4.Y;

            v0x = p0.X - p4.X;
            v0y = p0.Y - p4.Y;

            double b0 = (v0x * v1y - v0y * v1x);
            double b1 = (v1x * v2y - v1y * v2x);
            double b2 = (v2x * v0y - v2y * v0x);

            if (b0 >= 0.0 && b0 <= area && b1 >= 0.0 && b1 <= area && b2 >= 0.0 && b2 <= area) {
                return false;    // Point is interior to triangle
            } else {
                nxt = next(nxt);
            }
        }
        return true;
    } else {
        return false;
    }
}

bool Mesh::is_valid(size_t ei) const {
    bool value = true;

    value = value && (ei == prev(next(ei)));
    value = value && (ei == next(prev(ei)));
    value = value && (ei == twin(twin(ei)));

    return value;
}

bool Mesh::recursive_swap(size_t ei) {
    // TODO, May need to have two different recursive swap methods, one for midpoint insertion and one for circumcenter insertion
    if (!is_locally_optimal(ei) && swap(ei)) {
        size_t enext = next(ei);
        size_t eprev = prev(ei);
        size_t tnext = next(twin(ei));
        size_t tprev = prev(twin(ei));

        recursive_swap(enext);
        recursive_swap(eprev);
        recursive_swap(tnext);
        recursive_swap(tprev);

        return true;
    } else {
        return false;
    }
}

bool Mesh::swap(size_t ei) {
    if (!is_constrained(ei)) {
        Edge &e0 = Edges[ei];
        Edge &e1 = Edges[e0.Next];
        Edge &e2 = Edges[e0.Prev];
        Edge &e5 = Edges[e0.Twin];
        Edge &e3 = Edges[e5.Next];
        Edge &e4 = Edges[e5.Prev];

        e0.Node = e2.Node;
        e0.Next = e4.Self;
        e0.Prev = e1.Self;
        e0.Mark = false;

        e5.Node = e4.Node;
        e5.Next = e2.Self;
        e5.Prev = e3.Self;
        e5.Mark = false;

        e1.Next = e0.Self;
        e1.Prev = e4.Self;
        e1.Mark = false;

        e2.Next = e3.Self;
        e2.Prev = e0.Twin;
        e2.Mark = false;

        e3.Next = e0.Twin;
        e3.Prev = e2.Self;
        e3.Mark = false;

        e4.Next = e1.Self;
        e4.Prev = e0.Self;
        e4.Mark = false;

        return true;
    } else {
        Edges[ei].Mark = false;
        return false;
    }
}

double Mesh::circumradius(size_t ei) const {
    Point const slf = base(ei);
    Point const prv = base(prev(ei));
    Point const nxt = base(next(ei));

    double xa = slf.X;
    double ya = slf.Y;
    double xb = prv.X - xa;
    double yb = prv.Y - ya;
    double xc = nxt.X - xa;
    double yc = nxt.Y - ya;
    xa = xb - xc;
    ya = yb - yc;

    double den = 2.0 * abs(xb * yc - yb * xc);
    double num = std::sqrt(xa * xa + ya * ya) * std::sqrt(xb * xb + yb * yb) * std::sqrt(xc * xc + yc * yc);

    return num / den;
}

double Mesh::length(size_t ei) const {
    Point const p0 = base(ei);
    Point const p1 = tip(ei);

    double dx = p0.X - p1.X;
    double dy = p0.Y - p1.Y;

    return std::sqrt(dx * dx + dy * dy);
}

double Mesh::shortest_edge_length(size_t ei) const { // TODO: Rename Edge class to Dart
    Point const slf = base(ei);
    Point const prv = base(prev(ei));
    Point const nxt = base(next(ei));

    double x0 = slf.X;
    double y0 = slf.Y;
    double x1 = nxt.X;
    double y1 = nxt.Y;
    double x2 = prv.X;
    double y2 = prv.Y;

    double dx = x0 - x1;
    double dy = y0 - y1;
    double dl = dx * dx + dy * dy;

    dx = x1 - x2;
    dy = y1 - y2;
    dl = std::fmin(dl, dx * dx + dy * dy);

    dx = x2 - x0;
    dy = y2 - y0;
    dl = std::fmin(dl, dx * dx + dy * dy);

    return std::sqrt(dl);
}

size_t Mesh::num_edges() const {
    size_t count = 0;
    for (size_t e = 0; e != Edges.size(); ++e) {
        count += (e == twin(e) ? 2 : 1);
    }
    count /= 2;

    return count;
}

void Mesh::create() {
    create_boundary_polygon();
    triangulate_boundary_polygon();

    insert_internal_boundaries();
    get_triangles();
}

void Mesh::create_boundary_polygon() {
    // Create input edges
    Edges.reserve(Boundary->size());
    Points.reserve(Boundary->size());
    for (size_t i = 0; i != Boundary->size(); ++i) {
        std::shared_ptr<Curve const> cc = Boundary->curve(i);
        bool dir = Boundary->orientation(i);
555
        Edge &e = new_edge(Points.size(), DartConstraints.size(), dir); // TODO: change to new_edge(Edge)
556 557
        e.Twin = e.Self;

558
        DartConstraint &dc = new_dart_constraint(0.0, 1.0, boundary_constraint(cc));
559 560 561 562 563 564

        if (dir) {
            dc.forward_dart(e.self());
        } else {
            dc.reverse_dart(e.self());
        }
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
        Points.push_back(Point(dir ? cc->start() : cc->end()));
    }

    // Set Next/Prev edges from Boundary
    size_t Ne = 0;
    for (size_t i = 0; i != Edges.size(); ++i) {
        size_t j = (i + 1) % Edges.size();
        Edges[i].Next = Edges[j].Self;
        Edges[j].Prev = Edges[i].Self;
    }

    // Some edges may intersect due to discretization error
    // If two edges intersect, split the longest edge
    bool any_split = true;
    while (any_split) {
        any_split = false;
        for (size_t i = 0; i != Edges.size() - 1; ++i) {
            for (size_t j = i + 1; j != Edges.size(); ++j) {
                if (are_intersecting(i, j)) {
                    any_split = true;
                    if (length(i) > length(j)) {
                        split_edge(i);
                    } else {
                        split_edge(j);
                    }
                }
            }
        }
    }
}

void Mesh::element_quality(std::vector<double> &radii, std::vector<double> &quality) {
    radii.resize(0);
    quality.resize(0);

    radii.reserve(Triangles.size());
    quality.reserve(Triangles.size());
    for (size_t i = 0; i != Triangles.size(); ++i) {
604 605
        double r = circumradius(Triangles[i].Edge);
        double l = shortest_edge_length(Triangles[i].Edge);
606 607 608 609 610 611 612 613 614 615 616

        radii.push_back(r);
        quality.push_back(l / r / sqrt(3.0)); // sqrt(3.0) = (shortest edges length) / radius of equilateral triangle
    }
}

void Mesh::get_triangles() {
    Triangles.resize(0);
    Triangles.reserve(2 * num_points());

    for (auto &e : Edges) {
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
        e.Mark = true;
    }

    std::vector<size_t> edge_queue;
    std::vector<size_t> contours;
    edge_queue.reserve(2 * num_points());
    contours.reserve(2 * num_points());
    for (size_t contour_index = 0; contour_index != Contours.size(); ++contour_index) {
        edge_queue.resize(0);

        std::shared_ptr<Contour const> &contour = Contours[contour_index];
        std::shared_ptr<Curve const> c = contour->curve(0);
        std::shared_ptr<BoundaryConstraint> bc = boundary_constraint(c);
        DartConstraint const dc = dart_constraint(bc->dart(0));

        edge_queue.push_back(contour->orientation(0) ? dc.forward_dart() : dc.reverse_dart());
        while(edge_queue.size() > 0) {
            Edge &et = Edges[edge_queue.back()];
            Edge &en = Edges[et.next()];
            Edge &ep = Edges[et.prev()];

            edge_queue.pop_back();

            if (et.Mark) {
                Triangles.emplace_back(et.self(), contour_index);

                if(!en.is_constrained() && en.Mark) {
                    edge_queue.push_back(en.twin());
                    en.Mark = false;
                }

                if(!ep.is_constrained() && ep.Mark) {
                    edge_queue.push_back(ep.twin());
                    ep.Mark = false;
                }
            }
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
        }
    }
}

void Mesh::insert_internal_boundaries() {
    /*
        For each constraint curve :
            Add constraint curve to queue
            Insert endpoints if they do not exist.
                Will have to keep attempting insertion until no existing edge is encroached

            While the queue is not empty :
                Orbit the start point of the last curve in the queue :
                    If the end point is attached to the start point by some edge :
                        Set Edge->ConstraintCurve and->Orientation properties
                        Pop last curve from queue
                    Else
                        Split the last curve and add a new curve to the end of the queue

            Repeat until no edge is split :
                Orbit each edge, checking for encroachment by attached verticies
                If encroached, split edge
    */

    // Find interior curves
678 679 680
    std::vector<size_t> interior_index;
    for (size_t i = 0; i!= BoundaryConstraints.size(); ++i) {
        auto const & bc = BoundaryConstraints[i];
681 682
        bool on_exterior = false;
        for (size_t i = 0; i != Boundary->size(); ++i) {
683
            if (bc->curve() == Boundary->curve(i)) {
684 685 686 687 688 689
                on_exterior = true;
                break;
            }
        }

        if (!on_exterior) {
690
            interior_index.push_back(i);
691 692 693 694
        }
    }

    // Insert interior curve end points
695
    for (size_t i : interior_index) {
696
        // Insert start point
697
        Point p = BoundaryConstraints[i]->curve()->start();
698 699
        LocateTriangleResult result = locate_triangle(p);
        if (result == LocateTriangleResult::Interior) {
700 701 702 703
            while (add_point_to_queue(p) == AddToQueueResult::Midpoint) {
                insert_from_queue();
            }
            insert_from_queue();
704 705 706
        }

        // Insert end point
707
        p = BoundaryConstraints[i]->curve()->end();
708 709
        result = locate_triangle(p);
        if (result == LocateTriangleResult::Interior) {
710 711 712 713
            while (add_point_to_queue(p) == AddToQueueResult::Midpoint) {
                insert_from_queue();
            }
            insert_from_queue();
714 715 716
        }
    }

717 718
    // Attach edges to constraints by inserting interior curve midpoints until constraints are naturally satisfied
    std::vector<size_t> queue;
719
    for (size_t i : interior_index) {
720
        queue.push_back(DartConstraints.size());
721
        new_dart_constraint(0.0, 1.0, BoundaryConstraints[i]);
722
        while (queue.size() != 0) {
723
            DartConstraint &dc = DartConstraints[queue.back()];
724 725
            Point p0 = dc.curve()->point(dc.S0); // TODO: write Point Curve::point(double) and differentiate from Vertex Curve::vertex(double)
            Point p1 = dc.curve()->point(dc.S1);
726 727 728 729 730 731 732 733 734 735

            size_t ei = Edges.size() - 1;
            LocateTriangleResult result = locate_triangle(p0, ei);

            if (result != LocateTriangleResult::Point) {
                throw std::exception();
            }

            if (find_attached(p1, ei)) {
                Edge &e = Edges[ei];
736
                e.Constraint = dc.Self;
737
                e.Orientation = true;
738 739
                dc.forward_dart(e.self());

740
                Edge &et = Edges[e.Twin];
741
                et.Constraint = dc.Self;
742
                et.Orientation = false;
743
                dc.reverse_dart(et.self());
744 745 746 747 748 749

                queue.pop_back();
            } else {
                double s0 = dc.S0;
                double s1 = dc.S1;
                double sn = (s0 + s1) / 2.0;
750 751

                Point const p = dc.curve()->point(sn);
752 753 754

                dc.S1 = sn;

755 756 757 758 759 760 761
                queue.push_back(DartConstraints.size());
                new_dart_constraint(sn, s1, dc.boundary_constraint());

                while (add_point_to_queue(p) == AddToQueueResult::Midpoint) {
                    insert_from_queue();
                }
                insert_from_queue();
762 763 764 765
            }
        }
    }

766
    for (auto bc : BoundaryConstraints) { // Length based refinement
767
        bc->refine(*this, 0.01);
768 769
    }

770
    split_encroached_edges();
771

772 773 774 775 776 777
    for (auto bc: BoundaryConstraints) {
        if (bc->uniform_discretizaiton()) {
            bc->make_uniform(*this);
        }
    }

778
    // TODO: Enforce BoundaryConstraint conditions (e.g. uniform discretization, boundary maps)
779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796
}

void Mesh::mark_triangles() {
    for (size_t i = 0; i != Edges.size(); ++i) {
        Edges[i].Mark = true;
    }

    for (size_t i = 0; i != Edges.size(); ++i) {
        if (Edges[i].Mark && Edges[next(i)].Mark && Edges[prev(i)].Mark) {
            Edges[next(i)].Mark = false;
            Edges[prev(i)].Mark = false;
        }
    }
}

void Mesh::refine_once(std::vector<size_t> index, std::vector<double> radii, std::vector<double> quality) {
    for (size_t i = 0; i != Triangles.size(); ++i) {
        size_t j = index[i];
797
        if ((edge_from_triangle_index(j).Mark) && ((radii[j] > MaximumElementSize) || (radii[j] > MinimumElementSize && quality[j] < MinimumElementQuality))) {
798
            add_circumcenter_to_queue(Triangles[j].Edge);
799
            insert_from_queue();
800 801 802 803 804
        }
    }
    get_triangles();
}

805 806 807 808 809 810 811
void Mesh::insert_from_queue() {
    while (!Queue.empty()) {
        Queue.back()->insert(*this);
        Queue.pop_back();
    }
}

812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833
void Mesh::save_as(std::string path, std::string file_name) const {
    /*
        This is a stub for visualization
    */

    if (!boost::filesystem::exists(path)) {
        boost::filesystem::create_directories(path);
    }

    std::fstream fs;
    fs.open(path + file_name + ".oeme", std::fstream::out);

    for (size_t e = 0; e != Edges.size(); ++e) {
        Point const v0 = base(e);
        Point const v1 = base(next(e));
        Point const v2 = base(next(next(e)));
        fs << v0.X << ',' << v1.X << ',' << v2.X << ',' << v0.Y << ',' << v1.Y << ',' << v2.Y << '\n';
    }

    fs.close();
}

834 835 836 837 838 839 840 841
void Mesh::sort_constraints() {
    std::sort(BoundaryConstraints.begin(), BoundaryConstraints.end(),
              [](std::shared_ptr<BoundaryConstraint> const &x, std::shared_ptr<BoundaryConstraint> const &y) {
                  return (size_t)(x->curve().get()) < (size_t)(y->curve().get());
              }
    );
}

842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859
void Mesh::sort_permutation_ascending(std::vector<double> &values, std::vector<size_t> &index) const {
    index.resize(values.size());
    std::iota(index.begin(), index.end(), 0);
    std::sort(index.begin(), index.end(), [&](size_t i, size_t j) { return (values[i] < values[j]); });
}

void Mesh::sort_permutation_descending(std::vector<double> &values, std::vector<size_t> &index) const {
    index.resize(values.size());
    std::iota(index.begin(), index.end(), 0);
    std::sort(index.begin(), index.end(), [&](size_t i, size_t j) { return (values[i] > values[j]); });
}

void Mesh::split_edge(size_t ei) {
    /*
        Splits edge into two edges at the midpoint without creating any new triangles.
        Used for initial polygon refinement.
    */

860
    // TODO: Rename to split_boundary_edge
861

862 863 864
    if (!(is_constrained(ei) && ei == twin(ei))) { // TODO: write bool Edge::is_boundary()
        std::cerr << "Mesh::split_edge(size_t ei) should only be called on boundary edges" << std::endl;
        return;
865 866
    }

867 868 869
    DartConstraint &dci = DartConstraints[Edges[ei].Constraint];
    double s0 = dci.S0;
    double s1 = dci.S1;
870
    std::shared_ptr<Curve const> cc = dci.curve();
871

872 873
    double sn = (s0 + s1) / 2.0;
    dci.S1 = sn;
874

875
    size_t c{DartConstraints.size()};
876 877
    new_dart_constraint(sn, s1, dci.boundary_constraint());
    Points.push_back(cc->point(sn));
878

879 880 881 882 883
    size_t itr = new_edges(1);
    Edge &newe = Edges[--itr];
    Edge &e = Edges[ei];
    Edge &nxt = Edges[e.Next];

884 885 886
    DartConstraint &dcc = DartConstraints[c];
    DartConstraint &dce = DartConstraints[e.Constraint];

887 888 889 890
    // Constraint Curve
    newe.Orientation = e.Orientation;
    if (e.Orientation) {
        newe.Constraint = c;
891 892

        dcc.forward_dart(newe.self());
893
    } else {
894 895
        newe.Constraint = e.Constraint;
        e.Constraint = c;
896 897 898

        dce.reverse_dart(newe.self());
        dcc.reverse_dart(e.self());
899
    }
900 901 902 903 904 905 906 907 908 909 910 911 912

    // Connectivity
    newe.Node = Points.size() - 1;
    newe.Next = e.Next;
    newe.Prev = e.Self;
    newe.Twin = newe.Self;
    newe.Mark = false;

    nxt.Prev = newe.Self;
    nxt.Mark = false;

    e.Next = newe.Self;
    e.Mark = false;
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
}

void Mesh::split_encroached_edges() {
    bool any_split = true;
    while (any_split) {
        any_split = false;
        for (size_t i = 0; i != Edges.size(); ++i) {
            if (is_constrained(i)) {
                if (is_encroached(base(prev(i)), i)) {
                    any_split = true;
                    insert_midpoint(i);
                }
            }
        }
    }
}

void Mesh::triangulate_boundary_polygon() {
    Edges.reserve(3 * num_points());

    size_t i = 0;
    while (i != next(next(next(i)))) {
        if (is_protruding(i)) {
            size_t itr = new_edges(2);
            Edge &e1 = Edges[--itr];
            Edge &e0 = Edges[--itr];

            Edge &ei = Edges[i];
            Edge &nxt = Edges[ei.Next];
            Edge &prv = Edges[ei.Prev];

            Edge &prvprv = Edges[prv.Prev];

            // Edge of new triangle
            e0.Node = nxt.Node;
            e0.Prev = ei.Self;
            e0.Next = ei.Prev;
            e0.Twin = e1.Self;

            // Twin edge, part of new polygonal boundary
            e1.Node = prv.Node;
            e1.Next = ei.Next;
            e1.Prev = prv.Prev;
            e1.Twin = e0.Self;

            // Update polygonal boundary
            nxt.Prev = e1.Self;
            ei.Next = e0.Self;
            prvprv.Next = e1.Self;
            prv.Prev = e0.Self;

            // Next edge
            i = next(e1.Self);
        } else {
            i = next(i);
        }
    }

    // Edge swap to make triangulation Delaunay
    for (size_t i = 0; i != Edges.size(); ++i) {
        recursive_swap(i);
    }

    split_encroached_edges();
977 978 979 980 981 982 983 984 985

    for (size_t i = 0; i != Boundary->size(); ++i) { // Length based-refinement of boundary curves
        std::shared_ptr<Curve const> cc = Boundary->curve(i);
        std::shared_ptr<BoundaryConstraint> bc = boundary_constraint(cc);
        bc->refine(*this, 0.01);
        if (bc->uniform_discretizaiton()) {
            bc->make_uniform(*this);
        }
    }
986 987 988
}

LocateTriangleResult Mesh::locate_triangle(Point const p, size_t &ei) const {
989
    // TODO: Check for visibility of vertex? That someone contradicts the purpose of this method as a general point location function (as opposed to purely for mesh refinement)
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
    double xp = p.X;
    double yp = p.Y;

    Point p0 = base(ei);
    Point p1 = base(next(ei));
    Point p2 = base(prev(ei));

    double dx0p = p0.X - xp;
    double dy0p = p0.Y - yp;

    double dx1p = p1.X - xp;
    double dy1p = p1.Y - yp;

    double dx2p = p2.X - xp;
    double dy2p = p2.Y - yp;

    double dx01 = p0.X - p1.X;
    double dy01 = p0.Y - p1.Y;

    double dx12 = p1.X - p2.X;
    double dy12 = p1.Y - p2.Y;

    double dx20 = p2.X - p0.X;
    double dy20 = p2.Y - p0.Y;

    double tol_a = FLT_EPSILON * (dx20 * dy01 - dy20 * dx01);
    double tol_l = FLT_EPSILON * sqrt(dx20 * dy01 - dy20 * dx01);

    double dist0 = sqrt(dx0p * dx0p + dy0p * dy0p);
    double dist1 = sqrt(dx1p * dx1p + dy1p * dy1p);
    double dist2 = sqrt(dx2p * dx2p + dy2p * dy2p);

    double area01 = dx0p * dy1p - dx1p * dy0p;
    double area12 = dx1p * dy2p - dx2p * dy1p;
    double area20 = dx2p * dy0p - dx0p * dy2p;

    if (dist0 < tol_l) {
        return LocateTriangleResult::Point;
    } else if (dist1 < tol_l) {
        ei = next(ei);
        return LocateTriangleResult::Point;
    } else if (dist2 < tol_l) {
        ei = prev(ei);
        return LocateTriangleResult::Point;
    } else  if (area01 > tol_a && area12 > tol_a && area20 > tol_a) {
        return LocateTriangleResult::Interior;
    } else if (area01 < -tol_a && ei != twin(ei)) {
        ei = twin(ei);
        p2 = p1;
        p1 = p0;
        p0 = p2;

        dx2p = dx1p;
        dx1p = dx0p;
        dx0p = dx2p;

        dy2p = dy1p;
        dy1p = dy0p;
        dy0p = dy2p;

        dx01 = -dx01;
        dy01 = -dy01;
    } else if (area12 < -tol_a && next(ei) != twin(next(ei))) {
        ei = twin(next(ei));
        p0 = p2;

        dx0p = dx2p;
        dy0p = dy2p;

        dx01 = -dx12;
        dy01 = -dy12;
    } else if (area20 < -tol_a && prev(ei) != twin(prev(ei))) {
        ei = twin(prev(ei));
        p1 = p2;

        dx1p = dx2p;
        dy1p = dy2p;

        dx01 = -dx20;
        dy01 = -dy20;
    } else if (area01 > -tol_a && area12 > tol_a && area20 > tol_a) {
        ei = twin(ei);
        return LocateTriangleResult::Interior;
    } else if (area01 > tol_a && area12 > -tol_a && area20 > tol_a) {
        ei = twin(next(ei));
        return LocateTriangleResult::Interior;
    } else if (area01 > tol_a && area12 > tol_a && area20 > -tol_a) {
        ei = twin(prev(ei));
        return LocateTriangleResult::Interior;
    } else if (area01 < -tol_a) {
        return LocateTriangleResult::Exterior;
    } else if (area12 < -tol_a) {
        ei = next(ei);
        return LocateTriangleResult::Exterior;
    } else if (area20 < -tol_a) {
        ei = prev(ei);
        return LocateTriangleResult::Exterior;
    } else {
        throw std::exception();
    }

    while (true) { // After first iteration, area01 > 0
        p2 = base(prev(ei));

        dx2p = p2.X - xp;
        dy2p = p2.Y - yp;

        dx12 = p1.X - p2.X;
        dy12 = p1.Y - p2.Y;

        dx20 = p2.X - p0.X;
        dy20 = p2.Y - p0.Y;

        tol_a = FLT_EPSILON * (dx20 * dy01 - dy20 * dx01);
        tol_l = FLT_EPSILON * sqrt(dx20 * dy01 - dy20 * dx01);

        dist2 = sqrt(dx2p * dx2p + dy2p * dy2p);

        area12 = dx1p * dy2p - dx2p * dy1p;
        area20 = dx2p * dy0p - dx0p * dy2p;

        if (dist2 < tol_l) {
            ei = prev(ei);
            return LocateTriangleResult::Point;
        } else if (area12 > tol_a && area20 > tol_a) {
            return LocateTriangleResult::Interior;
        } else if (area12 < -tol_a && next(ei) != twin(next(ei))) {
            ei = twin(next(ei));
            p0 = p2;

            dx0p = dx2p;
            dy0p = dy2p;

            dx01 = -dx12;
            dy01 = -dy12;
            continue;
        } else if (area20 < -tol_a && prev(ei) != twin(prev(ei))) {
            ei = twin(prev(ei));
            p1 = p2;

            dx1p = dx2p;
            dy1p = dy2p;

            dx01 = -dx20;
            dy01 = -dy20;
            continue;
        } else if (area12 > -tol_a && area20 > tol_a) {
            ei = twin(next(ei));
            return LocateTriangleResult::Interior;
        } else if (area12 > tol_a && area20 > -tol_a) {
            ei = twin(prev(ei));
            return LocateTriangleResult::Interior;
        } else if (area12 < -tol_a) {
            ei = next(ei);
            return LocateTriangleResult::Exterior;
        } else if (area20 < -tol_a) {
            ei = prev(ei);
            return LocateTriangleResult::Exterior;
        } else {
            throw std::exception();
        }
    }
}

1154 1155
AddToQueueResult Mesh::add_circumcenter_to_queue(size_t dart) {
    return add_point_to_queue(circumcenter(dart), dart);
1156 1157 1158 1159 1160 1161 1162 1163 1164
}

InsertPointResult Mesh::insert_midpoint(size_t ei) {
    /*
        Splits edge into two edges and creates two new triangles.
    */

    size_t c{0};
    if (is_constrained(ei)) { // Constrained Edge
1165
        c = DartConstraints.size();
1166

1167
        DartConstraint &dc = DartConstraints[Edges[ei].Constraint];
1168 1169
        double s0 = dc.S0;
        double s1 = dc.S1;
1170
        std::shared_ptr<Curve const> cc = dc.curve();
1171 1172 1173 1174

        double sn = (s0 + s1) / 2.0;
        dc.S1 = sn;

1175
        new_dart_constraint(sn, s1, dc.boundary_constraint());
1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192
        Points.push_back(cc->point(sn));
    } else { // Unconstrained Edge
        Point const p0 = base(ei);
        Point const p1 = tip(ei);
        Points.push_back(Point((p0.X + p1.X) / 2.0, (p0.Y + p1.Y) / 2.0));
    }

    if (ei == twin(ei)) { // Boundary Edge
        size_t itr = new_edges(3);
        Edge &e2 = Edges[--itr];
        Edge &e1 = Edges[--itr];
        Edge &e0 = Edges[--itr];

        Edge &e = Edges[ei];
        Edge &nxt = Edges[e.Next];
        Edge &prv = Edges[e.Prev];

1193 1194 1195
        DartConstraint &dcc = DartConstraints[c];
        DartConstraint &dce = DartConstraints[e.Constraint];

1196 1197 1198 1199
        // Handle constraint curves
        e2.Orientation = e.Orientation;
        if (e.Orientation) {
            e2.Constraint = c;
1200 1201

            dcc.forward_dart(e2.self());
1202 1203 1204
        } else {
            e2.Constraint = e.Constraint;
            e.Constraint = c;
1205 1206 1207

            dcc.reverse_dart(e.self());
            dce.reverse_dart(e2.self());
1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258
        }

        // Construct edges
        e0.Node = prv.Node;
        e0.Next = e2.Self;
        e0.Prev = e.Next;
        e0.Twin = e1.Self;
        e0.Mark = false;

        e1.Node = Points.size() - 1; // TODO: write new_point(Point) method
        e1.Next = e.Prev;
        e1.Prev = e.Self;
        e1.Twin = e0.Self;
        e1.Mark = false;

        e2.Node = Points.size() - 1;
        e2.Next = e.Next;
        e2.Prev = e0.Self;
        e2.Twin = e2.Self;
        e2.Mark = false;

        nxt.Next = e0.Self;
        nxt.Prev = e2.Self;
        nxt.Mark = false;

        prv.Prev = e1.Self;
        prv.Mark = false;

        e.Next = e1.Self;
        e.Mark = false;

        // Recursive swap
        recursive_swap(e0.Self);
        recursive_swap(nxt.Self);
        recursive_swap(prv.Self);
    } else { // Interior Edge
        size_t itr = new_edges(6);
        Edge &e5 = Edges[--itr];
        Edge &e4 = Edges[--itr];
        Edge &e3 = Edges[--itr];
        Edge &e2 = Edges[--itr];
        Edge &e1 = Edges[--itr];
        Edge &e0 = Edges[--itr];

        Edge &e = Edges[ei];
        Edge &nxt = Edges[e.Next];
        Edge &prv = Edges[e.Prev];
        Edge &twn = Edges[e.Twin];
        Edge &tnxt = Edges[twn.Next];
        Edge &tprv = Edges[twn.Prev];

1259 1260 1261
        DartConstraint &dcc = DartConstraints[c];
        DartConstraint &dce = DartConstraints[e.Constraint];

1262 1263 1264 1265 1266 1267
        // Handle constraint curves
        e1.Orientation = e.Orientation;
        e4.Orientation = !e.Orientation;
        twn.Orientation = !e.Orientation;
        if (e.Orientation) {
            e1.Constraint = c;
1268 1269 1270 1271 1272 1273 1274
            dcc.forward_dart(e1.self());

            twn.Constraint = e1.Constraint;
            e4.Constraint = e.Constraint;

            dce.reverse_dart(e4.self());
            dcc.reverse_dart(twn.self());
1275 1276 1277
        } else {
            e1.Constraint = e.Constraint;
            e.Constraint = c;
1278 1279 1280 1281 1282 1283 1284 1285 1286

            dcc.reverse_dart(e.self());
            dce.reverse_dart(e1.self());

            twn.Constraint = e1.Constraint;
            e4.Constraint = e.Constraint;

            dcc.forward_dart(e4.self());
            dce.forward_dart(twn.self());
1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359
        }

        // Construct Edges
        e0.Node = Points.size() - 1;
        e0.Next = e.Prev;
        e0.Prev = e.Self;
        e0.Twin = e2.Self;
        e0.Mark = false;

        e1.Node = Points.size() - 1;
        e1.Next = e.Next;
        e1.Prev = e2.Self;
        e1.Twin = e.Twin;
        e1.Mark = false;

        e2.Node = prv.Node;
        e2.Next = e1.Self;
        e2.Prev = e.Next;
        e2.Twin = e0.Self;
        e2.Mark = false;

        e3.Node = Points.size() - 1;
        e3.Next = twn.Prev;
        e3.Prev = e.Twin;
        e3.Twin = e5.Self;
        e3.Mark = false;

        e4.Node = Points.size() - 1;
        e4.Next = twn.Next;
        e4.Prev = e5.Self;
        e4.Twin = e.Self;
        e4.Mark = false;

        e5.Node = tprv.Node;
        e5.Next = e4.Self;
        e5.Prev = twn.Next;
        e5.Twin = e3.Self;
        e5.Mark = false;

        tnxt.Next = e5.Self;
        tnxt.Prev = e4.Self;
        tnxt.Mark = false;

        tprv.Prev = e3.Self;
        tprv.Mark = false;

        twn.Next = e3.Self;
        twn.Twin = e1.Self;
        twn.Mark = false;

        nxt.Next = e2.Self;
        nxt.Prev = e1.Self;
        nxt.Mark = false;

        prv.Prev = e0.Self;
        prv.Mark = false;

        e.Next = e0.Self;
        e.Twin = e4.Self;
        e.Mark = false;

        // Recursive swap
        recursive_swap(e0.Self);
        recursive_swap(e3.Self);
        recursive_swap(nxt.Self);
        recursive_swap(prv.Self);
        recursive_swap(tnxt.Self);
        recursive_swap(tprv.Self);
    }

    return InsertPointResult::Midpoint;
}

1360
AddToQueueResult Mesh::add_point_to_queue(Point vc, size_t ei) {
1361 1362 1363 1364
    // Find triangle containing point
    LocateTriangleResult result = locate_triangle(vc, ei);

    if (result == LocateTriangleResult::Point) {
1365 1366 1367 1368 1369 1370 1371 1372 1373
        return AddToQueueResult::Duplicate; // Do not insert point if it is duplicate
    }

    if (result == LocateTriangleResult::Exterior) {
        if (is_constrained(ei)) { // Move attempted insertion point to the midpoint of the located edge to force encroachement
            vc = midpoint(ei);
        } else {
            throw std::exception(); // TODO: No triangle found containing circumcenter, boundary edge was encroached by circumcenter, and the located edge was not a constrained edge
        }
1374 1375 1376 1377
    }

    // Test edges in current and adjacent triangles for encroachment
    // These are the only possible edges that are encroached due to empty circumcircle property
1378 1379
    std::vector<size_t> encroached_edges = get_encroached_edges(vc, ei);
    bool any_encroached{encroached_edges.size() > 0};
1380

1381 1382
    if (any_encroached) {
        for (size_t e : encroached_edges) {
1383
            Edges[e].add_to_queue(*this);
1384
        }
1385
        return AddToQueueResult::Midpoint;
1386 1387

    } else if (result == LocateTriangleResult::Interior) {
1388 1389
        Queue.push_back(std::make_unique<CircumcenterQueuer>(vc, ei));
        return AddToQueueResult::Circumcenter;
1390

1391 1392 1393 1394
    } else {
        throw std::exception(); // TODO: No triangle could be found containing circumcenter and no boundary edge was encroached by circumcenter
    }
}
1395

1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471
InsertPointResult Mesh::insert_point(Point const vc, size_t ei) {
    // TODO: Give Queuers function pointers and references to the mesh, then make these private
    // ei should be the triangle containing the point vc

    size_t itr = new_edges(6);
    Edge &e5 = Edges[--itr];
    Edge &e4 = Edges[--itr];
    Edge &e3 = Edges[--itr];
    Edge &e2 = Edges[--itr];
    Edge &e1 = Edges[--itr];
    Edge &e0 = Edges[--itr];

    Edge &tri = Edges[ei];
    Edge &nxt = Edges[tri.Next];
    Edge &prv = Edges[tri.Prev];

    size_t vt = node(tri);
    size_t vn = node(nxt);
    size_t vp = node(prv);

    Points.push_back(vc);

    e0.Node = Points.size() - 1;
    e0.Next = tri.Self;
    e0.Prev = e1.Self;
    e0.Twin = e5.Self;
    e0.Mark = false;

    e1.Node = vn;
    e1.Next = e0.Self;
    e1.Prev = tri.Self;
    e1.Twin = e2.Self;
    e1.Mark = false;

    e2.Node = Points.size() - 1;
    e2.Next = nxt.Self;
    e2.Prev = e3.Self;
    e2.Twin = e1.Self;
    e2.Mark = false;

    e3.Node = vp;
    e3.Next = e2.Self;
    e3.Prev = nxt.Self;
    e3.Twin = e4.Self;
    e3.Mark = false;

    e4.Node = Points.size() - 1;
    e4.Next = prv.Self;
    e4.Prev = e5.Self;
    e4.Twin = e3.Self;
    e4.Mark = false;

    e5.Node = vt;
    e5.Next = e4.Self;
    e5.Prev = prv.Self;
    e5.Twin = e0.Self;
    e5.Mark = false;

    nxt.Next = e3.Self;
    nxt.Prev = e2.Self;
    nxt.Mark = false;

    prv.Next = e5.Self;
    prv.Prev = e4.Self;
    prv.Mark = false;

    tri.Next = e1.Self;
    tri.Prev = e0.Self;
    tri.Mark = false;

    recursive_swap(tri.Self);
    recursive_swap(nxt.Self);
    recursive_swap(prv.Self);

    return InsertPointResult::Success;
}
1472

1473 1474 1475 1476 1477 1478 1479 1480
std::vector<size_t> Mesh::get_encroached_edges(Point const p, size_t edge) {
    std::vector<size_t> encroached_edges;
    encroached_edges.reserve(9);
    size_t e_self = edge;
    for (size_t i = 0; i != 3; ++i) {
        if (is_encroached(p, e_self)) {
            encroached_edges.push_back(e_self);
        }
1481

1482 1483 1484 1485 1486 1487
        size_t e_twin = twin(e_self);
        if (e_self != e_twin) { // if not boundary edge, check adjacent triangle
            size_t e_next = next(e_twin);
            if (is_encroached(p, e_next)) {
                encroached_edges.push_back(e_next);
            }
1488

1489 1490 1491 1492 1493
            size_t e_prev = prev(e_twin);
            if (is_encroached(p, e_prev)) {
                encroached_edges.push_back(e_prev);
            }
        }
1494

1495
        e_self = next(e_self);
1496
    }