collision_library.cpp 38.2 KB
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
#include "collision_library.h"

#include <chrono>
using namespace std::chrono_literals;


namespace collision
{


    CollisionState
    detectCollision (const DynamicPhysObject<GMlib::PSphere<float>>& S0,
                     const DynamicPhysObject<GMlib::PSphere<float>>& S1,
                     seconds_type                                    dt)
    {
        const auto dt_max = dt;
        const auto dt_min = std::max(S0.curr_t_in_dt, S1.curr_t_in_dt);
        const auto new_dt = dt_max - dt_min;

        const auto S0_position = S0.getMatrixToScene() * S0.getPos();
        const auto S1_position = S1.getMatrixToScene() * S1.getPos();

        const auto S0_radius = S0.getRadius();
        const auto S1_radius = S1.getRadius();
        const auto radius_sum = S0_radius + S1_radius;

        const auto Q = (S1_position - S0_position);
        const auto r1 = S1.computeTrajectory(new_dt);
        const auto r2 = S0.computeTrajectory(new_dt);
        const auto R = r1 - r2;

        const auto _QR = Q * R;
        const auto _QRQR = std::pow( _QR, 2);

        const auto _RR = R * R;
        const auto _QQ = Q * Q;

        const auto _rr = std::pow( radius_sum, 2);
        const auto _square = std::sqrt(_QRQR - (_RR * (_QQ - _rr)));

        const auto epsilon = 0.00001;

        if ( _square < 0 )
        {
            return CollisionState(seconds_type(0.0), CollisionStateFlag::SingularityNoCollision);
        }
        else if ( (_QQ - _rr) < epsilon )
        {
            return CollisionState(seconds_type(0.0), CollisionStateFlag::SingularityParallelAndTouching);
        }
        else if ( _RR < epsilon )
        {
            return CollisionState( seconds_type(0.0), CollisionStateFlag::SingularityParallel);
        }

        const auto x = (-_QR - _square) / _RR;

        return CollisionState(((x * new_dt) + dt_min), CollisionStateFlag::Collision);


    }

    void
    computeImpactResponse (DynamicPhysObject<GMlib::PSphere<float>>& S0,
                           DynamicPhysObject<GMlib::PSphere<float>>& S1,
                           seconds_type                              dt)
    {
        const auto S0_old_vel = S0.velocity;    // 2.1
        const auto S1_old_vel = S1.velocity;    // -2.1

        const auto S0_pos = S0.getPos().toType<double>();
        const auto S1_pos = S1.getPos().toType<double>();

        const auto S0_mass = S0.mass;
        const auto S1_mass = S1.mass;

        const auto distance_vector_d = GMlib::Vector<double,3>(S1_pos - S0_pos);
        const auto normal_d = distance_vector_d.getNormalized();
        const auto n = (GMlib::Vector<double,3>(distance_vector_d).getLinIndVec()).getNormalized();

        const auto v0_d = (S0_old_vel * normal_d);
        const auto v1_d = (S1_old_vel * normal_d);
        const auto v0_n = (S0_old_vel * n);
        const auto v1_n = (S1_old_vel * n);

        const auto new_v0_d = (((S0_mass - S1_mass) / (S0_mass + S1_mass) ) * v0_d ) + (((2 * S1_mass) / (S0_mass + S1_mass) ) * v1_d );
        const auto new_v1_d = (((S1_mass - S0_mass) / (S0_mass + S1_mass) ) * v1_d ) + (((2 * S0_mass) / (S0_mass + S1_mass) ) * v0_d );

        const auto S0_new_vel = (v0_n * n) + (new_v0_d * normal_d);  // -2.1
        const auto S1_new_vel = v1_n * n + new_v1_d * normal_d;     // 2.1

        S0.velocity = S0_new_vel;
        S1.velocity = S1_new_vel;
    }

    CollisionState
    detectCollision (const DynamicPhysObject<GMlib::PSphere<float>>& S,
                     const StaticPhysObject<GMlib::PPlane<float>>&   P,
                     seconds_type                                    dt)
    {
        const auto dt_max = dt;
        const auto dt_min = S.curr_t_in_dt;
        const auto new_dt = dt_max - dt_min;

        const auto s_position = S.getMatrixToScene() * S.getPos();
        const auto s_radius = S.getRadius();

        auto &plane = const_cast<StaticPhysObject<GMlib::PPlane<float>>&>(P);
        const auto p = plane.evaluateParent(0.5f, 0.5f, 1, 1);                      // plane.getMatrixToScene * plane.evaluateParent(0.5f, 0.5f, 1, 1)
        const auto plane_pos = p(0)(0);
        const auto u = p(1)(0);
        const auto v = p(0)(1);


        const auto n = u ^ v;
        const auto n_normal = GMlib::Vector<float,3>(n).getNormalized();

        const auto d = (plane_pos + s_radius * n_normal) - s_position;

        auto ds = S.computeTrajectory(new_dt);

        // If the sphere's state is Rolling, it should use an adjusted DS
        if( S._state == DynamicPSphere::States::Rolling ) {
            auto unconst_S = const_cast<DynamicPhysObject<GMlib::PSphere<float>>&>(S);
            ds = unconst_S.adjustedTrajectory(new_dt);
        }

        const auto Q = (d * n_normal);
        const auto R = ( ds * n_normal );    // S.computeTrajectory(dt)

        const auto epsilon = 0.00001;

        if( std::abs(Q) < epsilon )
        {
            // The sphere is "touching" the surface
            return CollisionState( seconds_type(0.0), CollisionStateFlag::SingularityParallelAndTouching);
        }
        else if( std::abs(R) < epsilon)
        {
            return CollisionState( seconds_type(0.0), CollisionStateFlag::SingularityParallel);
        }

        const auto x = Q / R;

        return CollisionState( (x * new_dt) + dt_min);
    }

    void
    computeImpactResponse (DynamicPhysObject<GMlib::PSphere<float>>&      S,
                           const StaticPhysObject<GMlib::PPlane<float>>&  P,
                           seconds_type                                   dt) {

        auto &plane = const_cast<StaticPhysObject<GMlib::PPlane<float>>&>(P);
        const auto p = plane.evaluateParent(0.5f, 0.5f, 1, 1);
        const auto u = p(1)(0);
        const auto v = p(0)(1);

        const auto n = u ^ v;
        const auto n_normal = GMlib::Vector<float,3>(n).getNormalized();

        auto new_vel = S.velocity -  (2*(S.velocity * n_normal) * n_normal) * 0.95;

        S.velocity = new_vel;

    }

    CollisionState detectCollision (const DynamicPSphere&  S,
                                    const StaticPBezierSurf& B, seconds_type dt) {

        const auto dt_max = dt;
        const auto dt_min = S.curr_t_in_dt;
        const auto new_dt = dt_max - dt_min;

        const auto p0 = S.getPos();
        const auto r = S.getRadius();


        float u, v, t;
        u = 0.5;
        v = 0.5;
        t = 0.0;
        const auto epsilon = 1e-5;

        for ( int i = 0; i < 50; i++) {

            auto ds = S.computeTrajectory( new_dt );
            auto &Surf = const_cast<StaticPBezierSurf&>(B);
            const auto surf = Surf.evaluate(u, v, 1, 1);
            const auto p = p0 + ds*t;
            const auto q = surf(0)(0);
            const auto Su = surf(1)(0);
            const auto Sv = surf(0)(1);
            const auto Sn = GMlib::Vector<float,3>(Su ^ Sv).getNormalized();



            GMlib::SqMatrix<float,3> A;
            A.setCol(Su, 0);
            A.setCol(Sv, 1);
            A.setCol(-ds, 2);
            auto A_inv = A;

            A_inv.invert();

            const auto b = GMlib::Vector<float,3> {p-q-Sn*r};

            const auto x = A_inv * b;

            const auto deltaU = x(0);
            const auto deltaV = x(1);
            const auto deltaT = x(2);

            u += deltaU;
            v += deltaV;
            t += deltaT;

            if( (std::abs(deltaU) < epsilon) and (std::abs(deltaV) < epsilon) and (std::abs(deltaT) < epsilon) ) {

                return CollisionState(seconds_type(deltaT), CollisionStateFlag::Collision);

            }
        }

        return CollisionState(seconds_type(dt_min), CollisionStateFlag::SingularityNoCollision);


    }

    GMlib::Point<float,2>
    closestPoint(DynamicPSphere& S, StaticPPlane& P) {

    }

    void
    computeImpactResponse (DynamicPSphere& S, const StaticPBezierSurf& B,
                                seconds_type dt) {

    }

    CollisionState detectCollision (const DynamicPSphere& S0,
                                    const StaticPSphere& S1, seconds_type dt) {

    }

    void
    computeImpactResponse (DynamicPSphere& S0, const StaticPSphere& S1,
                                seconds_type dt) {

    }

    CollisionState
    detectCollision(const DynamicPSphere &S, const DynamicPCylinder &C, seconds_type dt) {

    }

    void
    computeImpactResponse (DynamicPSphere& S, DynamicPCylinder& C,
                                seconds_type dt) {

    }

    CollisionState
    detectCollision (const DynamicPSphere&  S, const StaticPCylinder& C, seconds_type dt) {

    }

    void
    computeImpactResponse (DynamicPSphere& S, const StaticPCylinder& C,
                                seconds_type dt);

    CollisionState
    detectCollision (const DynamicPCylinder& C0, const DynamicPCylinder& C, seconds_type dt);

    void computeImpactResponse (DynamicPCylinder& C0, DynamicPCylinder& C1,
                                seconds_type dt) {

    }

    void computeImpactResponse (DynamicPCylinder& C, const StaticPSphere& S,
                                seconds_type dt){

    }

    void computeImpactResponse (DynamicPCylinder& C, const StaticPBezierSurf& B,
                                seconds_type dt){

    }

    void computeImpactResponse (DynamicPCylinder& C, const StaticPPlane& P,
                                seconds_type dt){

    }


    std::unique_ptr<Controller>
    unittestCollisionControllerFactory() {

        return std::make_unique<MyController> ();
    }

    void
    DynamicPhysObject<GMlib::PSphere<float> >::simulateToTInDt(seconds_type t){

        if( this->_state == DynamicPSphere::States::AtRest
                    or (this->_state == DynamicPSphere::States::Rolling and std::abs(this->velocity(2) <= 1e-2))) {

            this->curr_t_in_dt = t;
            this->velocity = {0.0f, 0.0f, 0.0f};
            this->environment = &this->_sphereController->_stillEnvironment;

        }
        else {

            auto dt = t - this->curr_t_in_dt;
            auto MI = this->getMatrixToSceneInverse();
            GMlib::Vector<double,3> ds {0.0f, 0.0f, 0.0f};

            if( this->_state == DynamicPSphere::States::Rolling ) {

                ds = adjustedTrajectory(dt);
            }
            if( this->_state == DynamicPSphere::States::Free ) {

                ds = this->computeTrajectory(dt);
            }

            // Move
            this->translateParent( MI * ds);
            this->curr_t_in_dt = t;

            // Update physics
            auto F = this->externalForces();
            auto c = dt.count();
            auto a = F*c;
            this->velocity += a;

            this->environment = &this->_sphereController->_env;
        }

    }


    GMlib::Vector<double,3>
    DynamicPhysObject<GMlib::PSphere<float> >::computeTrajectory(seconds_type dt) const {

        auto vel = this->velocity;
        auto dtCount = dt.count();  // 0
        auto xF = this->externalForces();
        auto ds = vel * dtCount + 0.5 * xF * std::pow(dtCount, 2);

        return ds;

    }



    GMlib::Vector<double,3>
    DynamicPhysObject<GMlib::PSphere<float> >::adjustedTrajectory(seconds_type dt) {

        // Update ds to modified DS'
        auto ds = this->computeTrajectory(seconds_type(dt));
        auto r = this->getRadius();
        auto s = this->getMatrixToScene() * this->getPos();
        auto p = ds + s;

        auto planes = this->_sphereController->getAttachedObjects(this);
        GMlib::Vector<float,3> n {0.0f, 0.0f, 0.0f};

        for( auto& plane : planes ) {

            const auto M = plane->evaluateParent(0.5f, 0.5f, 1, 1);
            const auto q = M(0)(0);
            const auto u = M(1)(0);
            const auto v = M(0)(1);
            auto normal = GMlib::Vector<float,3> (u ^ v);
            n += normal;
        }

        n = GMlib::Vector<float,3> (n / planes.size()).getNormalized();

//        auto adjusted_ds = ds + (r + (p * s) )* n;

        auto adjusted_ds = ds - (ds * n * n);

        return adjusted_ds;

    }

    GMlib::Vector<double,3>
    DynamicPhysObject<GMlib::PSphere<float> >::externalForces() const {

        assert(environment != nullptr);

        return this->environment->externalForces().toType<double>();
    }

    void
    MyController::localSimulate(double dt) {

        // Testing
//        testMethod();

        // Reset time variable for all objects
        for( auto sphere : _dynamic_spheres) {

            sphere->curr_t_in_dt = seconds_type{0.0};
        }

        // Detect state changes and fill up our state container
        detectStateChanges(dt);
        sortAndMakeUniqueStates(_singularities);

        // Collision detection algorithm
        for( auto& sphere : _dynamic_spheres) {

            // Sending in sphere twice in the initial call because the function will require a second object in future calls
            sphereDynamicCollision(sphere, sphere, seconds_type(dt));

            for( auto& plane : _static_planes ) {

                sphereStaticCollision(sphere, plane, seconds_type(dt));
            }
        }
        // Make Collision unique
        sortAndMakeUnique(_collisions);

        // Make both collisions and states unique in relation to each other
        if( !_collisions.empty() and !_singularities.empty() ) {

            crossUnique(_collisions, _singularities);
        }
        else {
            // Make sure that the newest event is at the front of the vector
            std::reverse(_singularities.begin(), _singularities.end() );
            std::reverse(_collisions.begin(), _collisions.end());
        }

        while( !_collisions.empty() or !_singularities.empty() ) {

            // IF BOTH NOT EMPTY
            if( !_collisions.empty() and !_singularities.empty() ) {

                const auto col_time = _collisions.back().t_in_dt;
                const auto sing_time = _singularities.back().time;

                // Resolve Collision
                if( col_time < sing_time ) {

                    auto c = _collisions.back();
                    _collisions.pop_back();;

                    handleCollision(c, dt);     // Also detects more collisions

                    detectStateChanges(dt);

                    sortAndMakeUnique(_collisions);
                    sortAndMakeUniqueStates(_singularities);

                    if( !_collisions.empty() and !_singularities.empty() ) {

                        crossUnique(_collisions, _singularities);
                    }
                    else {
                        // Make sure that the newest event is at the front of the vector
                        std::reverse(_singularities.begin(), _singularities.end() );
                        std::reverse(_collisions.begin(), _collisions.end());
                    }
                }

                // Resolve Singularity
                else {

                    auto s = _singularities.back();
                    _singularities.pop_back();

                    handleStates(s, dt);

                    // Collision detection algorithm
                    for( auto& sphere : _dynamic_spheres) {

                        // Sending in sphere twice in the initial call because the function will require a second object in future calls
                        sphereDynamicCollision(sphere, sphere, seconds_type(dt));

                        for( auto& plane : _static_planes ) {

                            sphereStaticCollision(sphere, plane, seconds_type(dt));
                        }
                    }

                    detectStateChanges(dt);

                    sortAndMakeUnique(_collisions);
                    sortAndMakeUniqueStates(_singularities);

                    if( !_collisions.empty() and !_singularities.empty() ) {

                        crossUnique(_collisions, _singularities);
                    }
                    else {
                        // Make sure that the newest event is at the front of the vector
                        std::reverse(_singularities.begin(), _singularities.end() );
                        std::reverse(_collisions.begin(), _collisions.end());
                    }
                }
            }

            // IF COLLISIONS NOT EMPTY
            else if( !_collisions.empty() and _singularities.empty() ) {

                auto c = _collisions.back();
                _collisions.pop_back();;

                handleCollision(c, dt);     // Also detects more collisions

                detectStateChanges(dt);

                sortAndMakeUnique(_collisions);
                sortAndMakeUniqueStates(_singularities);

                if( !_collisions.empty() and !_singularities.empty() ) {

                    crossUnique(_collisions, _singularities);
                }
                else {
                    // Make sure that the newest event is at the front of the vector
                    std::reverse(_singularities.begin(), _singularities.end() );
                    std::reverse(_collisions.begin(), _collisions.end());
                }

            }

            // IF SINGULARITIES NOT EMPTY
            else if( _collisions.empty() and !_singularities.empty() ) {

                auto s = _singularities.back();
                _singularities.pop_back();

                handleStates(s, dt);

                // Collision detection algorithm
                for( auto& sphere : _dynamic_spheres) {

                    // Sending in sphere twice in the initial call because the function will require a second object in future calls
                    sphereDynamicCollision(sphere, sphere, seconds_type(dt));

                    for( auto& plane : _static_planes ) {

                        sphereStaticCollision(sphere, plane, seconds_type(dt));
                    }
                }

                detectStateChanges(dt);

                sortAndMakeUnique(_collisions);
                sortAndMakeUniqueStates(_singularities);

                if( !_collisions.empty() and !_singularities.empty() ) {

                    crossUnique(_collisions, _singularities);
                }
                else {
                    // Make sure that the newest event is at the front of the vector
                    std::reverse(_singularities.begin(), _singularities.end() );
                    std::reverse(_collisions.begin(), _collisions.end());
                }
            }
        }


//         Start simulation for all objects
        for( auto sphere : _dynamic_spheres) {

                sphere->simulateToTInDt(seconds_type(dt));
        }

    }

    // Singularity handeling
    void
    MyController::handleStates(StateChangeObj &state, double dt) {

        auto sphere = state.obj;
        auto newState = state.state;
        auto time = state.time;
        auto planes = state.attachedPlanes;

        if( newState == DynamicPSphere::States::Free ) {

            detachObjects(sphere);
            sphere->_state = newState;
        }
        else {

            setAttachedObjects(planes, sphere);
            sphere->_state = newState;

            if( newState == DynamicPSphere::States::AtRest ) {

                sphere->environment = &_stillEnvironment;
                sphere->velocity = GMlib::Vector<double,3> (0.0f, 0.0f, 0.0f);
            }
        }

        sphere->simulateToTInDt(time);
    }

    // Collision handeling
    void
    MyController::handleCollision(CollisionObject &c, double dt) {

//        c.obj1->simulateToTInDt(c.t_in_dt);
//        c.obj2->simulateToTInDt(c.t_in_dt);

        // Add more objects here if you end up using more
        auto d_sphere_1     = dynamic_cast<DynamicPSphere*>(c.obj1);
        auto d_sphere_2     = dynamic_cast<DynamicPSphere*>(c.obj2);
        auto s_sphere_2     = dynamic_cast<StaticPSphere*>(c.obj2);
        auto d_cylinder_1   = dynamic_cast<DynamicPCylinder*>(c.obj1);
        auto d_cylinder_2   = dynamic_cast<DynamicPCylinder*>(c.obj2);
        auto s_cylinder_2   = dynamic_cast<StaticPCylinder*>(c.obj2);
        auto s_plane_2      = dynamic_cast<StaticPPlane*>(c.obj2);
        auto s_bezier_2     = dynamic_cast<StaticPBezierSurf*>(c.obj2);



        // Impact response
        // If the first object is a sphere
        if(d_sphere_1) {


            if (d_sphere_2)
                collision::computeImpactResponse( *d_sphere_1, *d_sphere_2, c.t_in_dt);    // D_Sphere vs. D_Sphere
            else if (d_sphere_1 && s_sphere_2)
                collision::computeImpactResponse( *d_sphere_1, *s_sphere_2, c.t_in_dt);    // D_Sphere vs. S_Sphere
            else if (d_sphere_1 && d_cylinder_2)
                collision::computeImpactResponse( *d_sphere_1, *d_cylinder_2, c.t_in_dt);  // D_Sphere vs. D_Cylinder
            else if (d_sphere_1 && s_cylinder_2)
                collision::computeImpactResponse( *d_sphere_1, *d_cylinder_2, c.t_in_dt);  // D_Sphere vs. S_Cylinder
            else if (d_sphere_1 && s_plane_2) {

                if(d_sphere_1->_state != DynamicPSphere::States::AtRest)
                    d_sphere_1->simulateToTInDt(c.t_in_dt);
                    collision::computeImpactResponse( *d_sphere_1, *s_plane_2, c.t_in_dt);     // D_Sphere vs. S_Plane

            }
            else if (d_sphere_1 && s_bezier_2)
                collision::computeImpactResponse( *d_sphere_1, *s_bezier_2, c.t_in_dt);    // D_Sphere vs. S_Bezier

        }

        // First object is cylinder
        if(d_cylinder_1) {

            if (d_cylinder_2)
                collision::computeImpactResponse( *d_cylinder_1, *d_cylinder_2, c.t_in_dt);    // D_Cylinder vs. D_Cylinder
            else if (d_cylinder_1 && s_cylinder_2)
                collision::computeImpactResponse( *d_sphere_1, *d_cylinder_2, c.t_in_dt);      // D_Cylinder vs. S_Cylinder
            else if (d_cylinder_1 && d_sphere_2)
                collision::computeImpactResponse( *d_sphere_2, *d_cylinder_1, c.t_in_dt);      // D_Cylinder vs. D_Sphere
            else if (d_cylinder_1 && s_sphere_2)
                collision::computeImpactResponse( *d_cylinder_1, *s_sphere_2, c.t_in_dt);      // D_Cylinder vs. S_Sphere
            else if (d_cylinder_1 && s_bezier_2)
                collision::computeImpactResponse( *d_cylinder_1, *s_bezier_2, c.t_in_dt);      // D_Cylinder vs. S_Bezier
            else if (d_cylinder_1 && s_plane_2)
                collision::computeImpactResponse( *d_cylinder_1, *s_plane_2, c.t_in_dt);      // D_Cylinder vs. S_Plane

        }

        // Additional collisions for the dynamic objects in the collision_object
        // Not allowed: Same collision twice, cannot collide with itself

       // If the dynamic object (obj1) is a sphere
        if( d_sphere_1) {

            sphereDynamicCollision(d_sphere_1, c.obj2, seconds_type(dt));   // Does it collide with any dynamic objects? Can't with same obj as last time
            sphereStaticCollision(d_sphere_1, c.obj2, seconds_type(dt));    // Does it collide with any static objects?  Can't with same obj as last time

            // If sphere 1 collided with a dynamic sphere, check for that sphere's future collisions
            if(d_sphere_2) {

                sphereDynamicCollision(d_sphere_2, d_sphere_1, seconds_type(dt));   // Does it collide with any dynamic objects? Can't with sphere 1
                sphereStaticCollision(d_sphere_2, c.obj2, seconds_type(dt));        // Does it collide with any static objects? Placeholder variable for "Last object"
            }

            // Same if object 2 is a dynamic cylinder
            if(d_cylinder_2) {

                //cylinderDynamicCollision(d_cylinder_2, d_sphere_1, seconds_type(dt));
                //cylinderStaticCollision(d_cylinder_2, c.obj2, seconds_type(dt));
            }
        }

//             If the dynamic object (obj1) is a cylinder
        if(d_cylinder_1) {

            //cylinderDynamicCollision(d_cylinder_1, c.obj2, seconds_type(dt));
            //cylinderStaticCollision(d_cylinder_1, c.obj2, seconds_type(dt));

            if(d_cylinder_2) {

                //cylinderDynamicCollision(d_cylinder_2, d_cylinder_1, seconds_type(dt));
                //cylinderStaticCollision(d_cylinder_2, c.obj2, seconds_type(dt));
            }

            if(d_sphere_2) {

                sphereDynamicCollision(d_sphere_2, d_sphere_1, seconds_type(dt));
                sphereStaticCollision(d_sphere_2, c.obj2, seconds_type(dt));
            }
        }
    }

    void
    MyController::detectStateChanges(double dt) {

        for( auto& sphere : _dynamic_spheres) {

            auto singularity = detectStateChange(sphere, dt);

            if (singularity.state != sphere->_state) {

                _singularities.push_back(singularity);
            }
        }

    }

    //**** Code developed with help from Ghada Bouzidi and Fatemeh Heidari *****

    StateChangeObj
    MyController::detectStateChange(DynamicPSphere *sphere, double dt) {

        std::unordered_set<StaticPPlane*> planeContainer;       // Used for returning planes that the sphere is (not) attached to
        DynamicPSphere::States state;                           // Holder variable for the state the sphere will enter

        const auto epsilon = 1e-5;

        // Sphere variables
        const auto r = sphere->getRadius();
        const auto pos = sphere->getMatrixToScene() * sphere->getPos();

        // Time variables
        const auto sphereTime = sphere->curr_t_in_dt;
        const auto maxDt = seconds_type(dt);
        const auto newDt = maxDt - sphereTime;
        seconds_type returnTime = sphereTime;
//        auto still = 0;                                   // Needed to print out the still value further down

        const auto ds = sphere->computeTrajectory(newDt);   // Calculating "original ds"
//        std::cout << "The DS is: " << ds << std::endl;

        // Plane variables.
        auto planes = getAttachedObjects(sphere);
        GMlib::APoint<float,3> q;
        GMlib::Vector<float,3> n {0.0f, 0.0f, 0.0f};

        if( planes.empty() ) {  // Sphere NOT attached

            for (auto& plane : _static_planes){
                auto M = plane->evaluateParent(0.5f,0.5f,1,1);
                auto q = M(0)(0);
                auto u = M(1)(0);
                auto v = M(0)(1);
                auto n = GMlib::Vector<float,3>(u ^ v).getNormalized();
                auto d = (q + r * n) - pos;

                auto bla        = std::abs(((-n*r) * ds) -(ds*ds));
                auto dsn        = ds * n;
                auto dn         = d*n;
                const auto x    = dn / dsn;
                returnTime      = (x * newDt) + sphereTime;

                if( bla < epsilon ) {

                    planeContainer.insert(plane);
                    state = DynamicPSphere::States::AtRest;
                    std::cout << "detectStateChange says the state will become AtRest from Free" << std::endl;
                }
                else if( std::abs(dn) < epsilon and dsn < 0 ) {

                    planeContainer.insert(plane);
                    state = DynamicPSphere::States::Rolling;
                    std::cout << "detectStateChange says the state will become Rolling from Free" << std::endl;
                }
                else state = DynamicPSphere::States::Free;
            }

            return StateChangeObj(sphere, planeContainer, returnTime, state);
        }
        else {      // Sphere ATTACHED

            for (auto &it :planes){
                auto M = it->evaluateParent(0.5f,0.5f,1,1);
                auto pos= M(0)(0);
                auto u = M(1)(0);
                auto v = M(0)(1);
                auto normal = GMlib::Vector<float,3>(u ^ v);
                n+=normal;
                q=pos;
           }
           n= GMlib::Vector <float,3>(n/planes.size()).getNormalized();

           auto d       = (q + r * n) - pos;
           auto bla     = std::abs(((-n*r) * ds) -(ds*ds));
           auto dsn     = ds * n;
           auto dn      = d * n;
           const auto x = dn / dsn;
           returnTime   = (x * newDt) + sphereTime;


           if( sphere->_state == DynamicPSphere::States::Rolling ) {

               if( dsn > 0) {

                   std::cout << "detectStateChange says the state will become Free from Rolling" << std::endl;
                   state = DynamicPSphere::States::Free;
                   return StateChangeObj(sphere, planes, returnTime, state);
               }
               else if( bla < epsilon ) {

                   std::cout << "detectStateChange says the state will become AtRest from Rolling" << std::endl;
                   state = DynamicPSphere::States::AtRest;
                   return StateChangeObj(sphere, planes, returnTime, state);
               }
               else return StateChangeObj(sphere, planes, returnTime, DynamicPSphere::States::Rolling);
           }

           else if( sphere->_state == DynamicPSphere::States::AtRest ) {

               if( bla > epsilon ) {

                   std::cout << "detectStateChange says the state will become Rolling from AtRest" << std::endl;
                   state = DynamicPSphere::States::Rolling;
                   return StateChangeObj(sphere, planes, returnTime, DynamicPSphere::States::Rolling);
               }
               else if( dsn > 0) {
                   std::cout << "detectStateChange says the state will become Free from AtRest" << std::endl;
                   state = DynamicPSphere::States::Free;
                   return StateChangeObj(sphere, planes, returnTime, DynamicPSphere::States::Rolling);
               }
               else return StateChangeObj(sphere, planes, returnTime, DynamicPSphere::States::AtRest);
           }
        }

        /*
        // If the sphere is NOT ATTACHED to any planes, we check if it BECOMES attached in this timestep
        if( planes.empty() ) {

            // Go through each plane in the game and calculate whether or not the sphere is attached to any of them
            for( auto& plane : _static_planes ) {

                const auto M = plane->evaluateParent(0.5f, 0.5f, 1, 1);
                const auto q = M(0)(0);
                const auto u = M(1)(0);
                const auto v = M(0)(1);
                const auto n = GMlib::Vector<float,3> (u ^ v).getNormalized();
                const auto d = (q + r * n) - pos;

                // Debug variables / criteria for states
                const auto still = std::abs(((-n * r) * ds) - (ds * ds));       // Sphere is Resting on surface
                const auto dsn = ds * n;                                        // Sphere is Rolling on surface. (Cannot be still AND rolling)
                const auto dn = d * n;                                          // Sphere is Flying

//                std::cout << "The still is: " << still << std::endl;          // Useful for seeing if the sphere should be still or not

                // Return time, used same method as for collision time between sphere and plane (Might need to be done in a different way!!!!)
                // sphereTime = dt_min
                const auto x = dn / dsn;
                returnTime = (x * newDt) + sphereTime;

                // Check to see if the sphere has actually even touched the plane yet
                if( std::abs(dn) < epsilon ) {

                    /// If a sphere is attached to a surface, it can only be Still (AtRest) or Rolling, not both.
                    /// If either are true, we store the current plane, as the application is object centric and if a sphere is still or rolling
                    /// in relation to ONE plane, then it that is it's STATE in the game, and store the state the sphere should TRANSITION into.
                    if( still < epsilon ) {

                        std::cout << "State will become AtRest" << std::endl;
                        planeContainer.insert( plane );
                        state = DynamicPSphere::States::AtRest;
                    }
                    else if( still > epsilon ) {

                        std::cout << "State will become Rolling" << std::endl;
                        planeContainer.insert( plane );
                        state = DynamicPSphere::States::Rolling;
                    }
                }
                // The sphere did NOT ATTACH to any surface
                else state = DynamicPSphere::States::Free;
            }

            return StateChangeObj( sphere, planeContainer, returnTime, state );
        }
        // Else the sphere IS ATTACHED and we need to calculate if it will change state / detach
        else {

            // Go through the planes that the sphere is attached to in order to get a common normal for use in computation
            // The sphere won't always be attached to multiple planes
            for( auto& plane : planes ) {

                const auto M = plane->evaluateParent(0.5f, 0.5f, 1, 1);
                const auto q = M(0)(0);
                const auto u = M(1)(0);
                const auto v = M(0)(1);
                auto normal = GMlib::Vector<float,3> (u ^ v);
                n += normal;
            }

            n = GMlib::Vector<float,3> (n / planes.size()).getNormalized();

            // Debug variables / criteria for states
            const auto d = (q + r * n) - pos;
            const auto still = std::abs(((-n * r) * ds) - (ds * ds));       // Sphere is Resting on surface
            const auto dsn = ds * n;                                        // Sphere is Rolling on surface. (Cannot be still AND rolling)
            const auto dn = d * n;                                          // Sphere is Flying

            // Return time, used same method as for collision time between sphere and plane (Might need to be done in a different way!!!!)
            // sphereTime = dt_min
            returnTime = ((dn / dsn) * newDt) + sphereTime;

            if( std::abs(dn) > epsilon ) {

            /// Check the sphere's current state, and if it needs to be changed.
            if( sphere->_state == DynamicPSphere::States::Rolling) {

                // Detatchment is seen as a state change, and will be processed further in the algorithm
                if( dsn > 0 ) {
                    std::cout << "State changing from Rolling to Free" << std::endl;
                    state = DynamicPSphere::States::Free;
                    return StateChangeObj( sphere, planes, returnTime, state );
                }
                else if( still < epsilon ) {
                    std::cout << "State changing from Rolling to AtRest" << std::endl;
                    state = DynamicPSphere::States::AtRest;
                    return StateChangeObj( sphere, planes, returnTime, state );
                }
                // Else the sphere will keep being in a Rolling state
                else return StateChangeObj( sphere, planes, returnTime, DynamicPSphere::States::Rolling );
            }

            if( sphere->_state == DynamicPSphere::States::AtRest ) {

                if( dsn > 0 ) {
                    std::cout << "State changing from AtRest to Free" << std::endl;
                    state = DynamicPSphere::States::Free;
                    return StateChangeObj( sphere, planes, returnTime, state );
                }
                else if( still > epsilon ) {
                    std::cout << "State changing from AtRest to Rolling" << std::endl;
                    state = DynamicPSphere::States::Rolling;
                    return StateChangeObj( sphere, planes, returnTime, state );
                }
                else return StateChangeObj( sphere, planes, returnTime, DynamicPSphere::States::Free );
            }
        }
        */

    }

    void
    MyController::testMethod()
    {


//        auto sphere1 = _dynamic_spheres[0];
//        auto sphere2 = _dynamic_spheres[1];
//        auto sphere3 = _dynamic_spheres[2];
//        StaticPPlane* plane;

//        auto fake_sin1 = StateChangeObj(sphere1, fakePlanes, seconds_type(0.2), DynamicPSphere::States::NoChange);
//        auto fake_sin2 = StateChangeObj(sphere2, fakePlanes, seconds_type(0.4), DynamicPSphere::States::NoChange);
//        auto fake_sin3 = StateChangeObj(sphere3, fakePlanes, seconds_type(0.7), DynamicPSphere::States::NoChange);

//        auto fake_col1 = CollisionObject( sphere3, sphere2, seconds_type(0.3));
////        auto fake_col2 = CollisionObject( sphere2, sphere1, seconds_type(0.4));
////        auto fake_col3 = CollisionObject( sphere3, sphere2, seconds_type(0.5));

//        _singularities.push_back(fake_sin1);
//        _singularities.push_back(fake_sin2);
//        _singularities.push_back(fake_sin3);

//        _collisions.push_back( fake_col1 );
////        _collisions.push_back( fake_col2 );
////        _collisions.push_back( fake_col3 );

//        crossUnique(_collisions, _singularities);

    }



    /// vector; Get, Set and Remove objects to / from Sphere
    /*
    // Get objects attached to sphere
//    std::vector<StaticPPlane *>
//    MyController::getAttachedObjects(DynamicPSphere* sphere)
//    {
//        return (_map[sphere]);
//    }

//    // Set objects attached to sphere
//    void
//    MyController::setAttachedObjects(StaticPPlane* plane, DynamicPSphere* sphere)
//    {
//        _map[sphere].push_back(plane);
//    }

//    // Remove objects from the set In the map
//    void
//    MyController::detachObjects(StaticPPlane *plane, DynamicPSphere *sphere){

////        _map[sphere].erase(plane);
//    }
*/

    /// unordered_set; Get, Set and Remove objects to / from Sphere
    // Get objects attached to sphere
    std::unordered_set<StaticPPlane *>
    MyController::getAttachedObjects(DynamicPSphere* sphere)
    {
        static std::unordered_set<StaticPPlane*> empty {};
        auto iter = _map.find(sphere);

        if( iter != _map.end() ) {

            return iter->second;
        }
        else return empty;
    }

    // Set objects attached to sphere
    void
    MyController::setAttachedObjects(std::unordered_set<StaticPPlane *> plane, DynamicPSphere* sphere)
    {
        for( auto& p : plane) {
            _map[sphere].emplace(p);
        }
    }

    // Remove objects from the set In the map
    void
    MyController::detachObjects(DynamicPSphere *sphere){

        _map.erase(sphere);

    }

    // Adding objects to vector

    void
    MyController::add(DynamicPSphere * const sphere) {

        sphere->environment = &_env;
        _dynamic_spheres.push_back(sphere);
        _map[sphere];

    }
    void
    MyController::add(StaticPSphere * const sphere) {

        _static_spheres.push_back(sphere);
    }
    void
    MyController::add(StaticPPlane * const plane) {

        _static_planes.push_back(plane);
    }
    void
    MyController::add(StaticPCylinder * const cylinder) {

        _static_cylinders.push_back(cylinder);
    }
    void
    MyController::add(StaticPBezierSurf * const surf) {

        _static_bezier_surf.push_back(surf);
    }


} // END namespace collision