collision_library.h 14.9 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
#ifndef COLLISION_LIBRARY_H
#define COLLISION_LIBRARY_H

// collision library interface
#include <collision_interface.h>

#include <typeinfo>
#include <unordered_map>


namespace collision
{

    // "Declaration" of the struct
    struct StateChangeObj;


class MyController : public Controller {
    GM_SCENEOBJECT (MyController)
public:

    explicit MyController () = default;

    void add (DynamicPSphere* const sphere);
    void add (StaticPSphere* const sphere);
    void add (StaticPPlane* const plane);
    void add (StaticPCylinder* const cylinder);
    void add (StaticPBezierSurf* const surf);

    // Change "value" and return type if the sphere should be able to be attached to objects other than planes
    std::unordered_set<StaticPPlane *> getAttachedObjects(DynamicPSphere* sphere);
//    std::vector<StaticPPlane*> getAttachedObjects(DynamicPSphere* sphere);


    void setAttachedObjects( std::unordered_set<StaticPPlane*> plane, DynamicPSphere* sphere );
    void detachObjects(DynamicPSphere* sphere);

    // States
    void
    detectStateChanges(double dt);

    StateChangeObj
    detectStateChange(DynamicPSphere* sphere, double dt);

    void
    handleStates (StateChangeObj& state, double dt);

    void
    testMethod();

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


    // Collisions
    CollisionState detectCollision (const DynamicPSphere& S,
                                    const DynamicPCylinder& C, seconds_type dt);

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

    void computeImpactResponse (DynamicPSphere& S, 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);

    void handleCollision ( collision::CollisionObject& col, double dt);

    Environment                                 _stillEnvironment;
    DefaultEnvironment                          _env;



private:

    template <typename T_s, typename T_o>
    void sphereStaticCollision(T_s* sphere, T_o* object, seconds_type dt);

    template <typename T_s, typename T_o>
    void sphereDynamicCollision(T_s* sphere, T_o* object, seconds_type dt);

    template <class Container>
    void sortAndMakeUniqueStates(Container& c);

    template <typename Container_1, typename Container_2>
    void crossUnique( Container_1 container1, Container_2 container2);

protected:
    void localSimulate (double dt) override;

    std::vector<DynamicPSphere*>                _dynamic_spheres;
    std::vector<DynamicPCylinder*>              _dynamic_cylinders;
    std::vector<StaticPSphere*>                 _static_spheres;
    std::vector<StaticPPlane*>                  _static_planes;
    std::vector<StaticPCylinder*>               _static_cylinders;
    std::vector<StaticPBezierSurf*>             _static_bezier_surf;

    std::vector<collision::CollisionObject>     _collisions;
    std::vector<StateChangeObj>                 _singularities;
    std::vector<StateChangeObj>                 _fakeSingularities;

    std::unordered_map<DynamicPSphere*, std::unordered_set<StaticPPlane*>>     _map;
    std::unordered_set<StaticPPlane*>           fakePlanes;




};

template <>
class DynamicPhysObject<GMlib::PSphere<float>> : public DynamicPhysObject_Base<GMlib::PSphere<float>> {
public:
    using DynamicPhysObject_Base<GMlib::PSphere<float>>::DynamicPhysObject_Base;

    enum class States {
        Free,
        Rolling,
        AtRest,
        NoChange
    };

    MyController*   _sphereController;
    States          _state = States::Free;     // Which state is the sphere in



    GMlib::Vector<double,3>
    adjustedTrajectory (seconds_type dt);

    // "Old" methods
    void            simulateToTInDt( seconds_type t ) override;

    GMlib::Vector<double, 3>
    computeTrajectory (seconds_type dt) const override; // [m]

    GMlib::Vector<double, 3> externalForces () const override; // [m / s^2]


};

// StateChangeObject struct
struct StateChangeObj {
    DynamicPSphere*                             obj;               // Object whos state will change
    std::unordered_set<StaticPPlane*>           attachedPlanes;     // Object that obj1 will change state ACCORDING to
    seconds_type                                time;               // Time of singularity
    DynamicPSphere::States                      state;              // State that obj1 will change to

    StateChangeObj
    (DynamicPSphere* o1, std::unordered_set<StaticPPlane*> planes, seconds_type t, DynamicPSphere::States s) :
        obj{o1}, attachedPlanes{planes}, time{t} ,state{s} {}
};

template <class PSurf_T, typename... Arguments>
std::unique_ptr<DynamicPhysObject<PSurf_T>> unittestDynamicPhysObjectFactory(Arguments... parameters) {

    return std::make_unique<DynamicPhysObject<PSurf_T>> (parameters...);

}

template <class PSurf_T, typename... Arguments>
std::unique_ptr<StaticPhysObject<PSurf_T>> unittestStaticPhysObjectFactory(Arguments... parameters) {

    return std::make_unique<StaticPhysObject<PSurf_T>> (parameters...);
}

// Make collisions and states crosswise unique
template <typename Container_1, typename Container_2>
void MyController::crossUnique(Container_1 container1, Container_2 container2) {

    auto objPred =  [](const auto &a, const auto &b) {

        if( a.obj1 == b.obj or a.obj2 == b.obj ) return true;

        return false;
    };

    auto timePred =  [](const auto &a, const auto &b) {

        if( a.t_in_dt < b.time ) return true;

        return false;
    };

    auto inCollisionsAlreadyPred = [](Container_1 a, const auto &b) {

        for( auto& c : a) {

            // Check if any of the collisions objects are in the collection already
            if( c.obj1 == b.obj1 ) return true;
            if( c.obj1 == b.obj2 ) return true;
            if( c.obj2 == b.obj1 ) return true;
            if( c.obj2 == b.obj2 ) return true;

            return false;
        }
    };

    auto inSingularitiesAlreadyPred = [](Container_2 a, const auto &b) {

        for( auto& c : a) {

            // Check if any of the state objects are in the collection already
            if( c.obj == b.obj ) return true;

            return false;
        }
    };

    std::vector<collision::CollisionObject>     _realCollisions;
    std::vector<StateChangeObj>                 _realSingularities;

    auto start = std::end(container2);

    // Check if any object that is in CONTAINER1 is also in CONTAINER2 and compares time values to remove one
    for( auto first_iter = std::end(container1) - 1; first_iter != std::begin(container1) -1; --first_iter) {
        for( auto second_iter = start - 1; second_iter != std::begin(container2) -1; --second_iter ) {


            if(( objPred( *first_iter, *second_iter ) )) {

                if( timePred( *first_iter, *second_iter )) {

                    // Keep collision
                    if( inCollisionsAlreadyPred(_realCollisions, *first_iter) == false) {

                        _realCollisions.push_back(*first_iter);
                    }
                }
                else {

                    // Keep state
                    if( inSingularitiesAlreadyPred(_realSingularities, *second_iter) == false ) {

                        _realSingularities.push_back(*second_iter);
                    }
                }
            }
//            else {
//                break;
//            }
        }
    }

    _collisions = _realCollisions;
    _singularities = _realSingularities;
}

// Sort and make Unique for states
template <class Container>
void MyController::sortAndMakeUniqueStates(Container& c) {

    // Sorting
    std::sort( std::begin(c), std::end(c), [] (const auto& a, const auto&b) {
       return a.time < b.time;
    });

    // Make unique

    auto pred =  [](const auto &a, const auto &b) {

        if( a.obj == b.obj ) return true;

        return false;
    };

    typename Container::iterator NE = std::end(c);
    for( auto first_iter = std::begin(c); first_iter != NE; ++first_iter) {

        for( auto r_iterator = NE - 1; r_iterator != first_iter; --r_iterator) {

                if( (pred(*first_iter, *r_iterator))) {
                        std::swap( *r_iterator, *(NE-1) );
                        NE--;

                    }
            }
        }

        c.erase( NE, std::end( c ) );
}

template <class Container_T >
void sortAndMakeUnique( Container_T& container) {

    // Sort

    std::sort( std::begin(container), std::end(container), [](const auto& a, const auto& b) {
        return a.t_in_dt < b.t_in_dt;
    });

    // Make unique

    auto pred =  [](const auto &a, const auto &b) {

        auto is_d_pred = []( const auto* obj ) {
          if(dynamic_cast<const DynamicPSphere*>(obj)) return true;



          return false;
        };

        if( a.obj1 == b.obj1 ) return true;
        if( a.obj1 == b.obj2 ) return true;
        if( a.obj2 == b.obj1 ) return true;
        if( ( is_d_pred(a.obj2) or is_d_pred(b.obj2) )
                and a.obj2 == b.obj2 ) return true;

        return false;
    };

    typename Container_T::iterator NE = std::end(container);
    for( auto first_iter = std::begin(container); first_iter != NE; ++first_iter) {

        for( auto r_iterator = NE - 1; r_iterator != first_iter; --r_iterator) {

                if( (pred(*first_iter, *r_iterator))) {
                        std::swap( *r_iterator, *(NE-1) );
                        NE--;

                    }
            }
        }

        container.erase( NE, std::end( container ) );

    } // EOF


template <typename T_s, typename T_o>
inline
void MyController::sphereDynamicCollision(T_s* sphere, T_o* object, seconds_type dt) {

    bool movingObject = false;

    for( auto& s : _dynamic_spheres ) {
        if( s->_state != DynamicPSphere::States::AtRest ) {
            movingObject = true;
            break;
        }
    }

    if( movingObject ) {

        auto cylinder = dynamic_cast<DynamicPCylinder*>(object);
    //    auto plane = dynamic_cast<DynamicPPlane*>(object);

        if( cylinder ) {

            // Sphere vs. Dynamic Cylinder
        }
    //    else if( plane ) {

            // Sphere vs. Dynamic Plane
    //    }
        else {

            // Sphere vs. Dynamic Sphere
            for( auto iter = std::begin(_dynamic_spheres); iter != std::end(_dynamic_spheres); ++iter) {

                if( (*iter == sphere) or (*iter == object) or (sphere->_state == DynamicPSphere::States::AtRest)) {
                    break;
                }
                else {

                    // Check only for collisions for the first dynamic sphere
                    auto col = collision::detectCollision(*sphere, **iter, dt);

                    // The check for if the second object is a dynamic sphere is done in the main algorithm
                    // and the method is called again only with the 1'st and 2'nd sphere swapped

                    if( col.CollisionState::flag == CollisionStateFlag::Collision ) {

                        auto& first_sphere = sphere;
                        auto& second_sphere = *iter;

                        auto new_t = std::max(first_sphere->curr_t_in_dt, second_sphere->curr_t_in_dt);

                        if( col.time > seconds_type(new_t) and col.time < dt) {
                            auto col_obj = CollisionObject(first_sphere, second_sphere, col.time);
                            _collisions.push_back(col_obj);

                            // Simulate the objects to T in dt?

                        }
                    }
                }
            }
        }

    }


}

template <typename T_s, typename T_o>
inline
void MyController::sphereStaticCollision(T_s* sphere, T_o* object, seconds_type dt)
{

    bool movingObject = false;

    for( auto& s : _dynamic_spheres ) {
        if( s->_state != DynamicPSphere::States::AtRest ) {
            movingObject = true;
            break;
        }
    }

    if( movingObject ) {


        // The game will mainly have two types of static objects that can be collided with, planes and bezier surfaces
        // Checks to see which one the sphere has collided with
        auto plane = dynamic_cast<const StaticPPlane*>(object);
        auto bezier_s = dynamic_cast<const StaticPBezierSurf*>(object);


        // Sphere vs. Static Plane
        if( plane ) {

            auto attachedPlanes = getAttachedObjects(sphere);

            for( auto iter = std::begin(_static_planes); iter != std::end(_static_planes); ++iter) {

                // The sphere cannot collide with the same plane it just collided with
    //            if( *iter == plane ) {
    //                break;
    //            }

                // If sphere is attached to the plane, it should NOT check for collisions with it
                if( !attachedPlanes.empty() ) {
                    for( auto comperator = attachedPlanes.begin(); comperator != attachedPlanes.end(); ++comperator) {

                        if( *iter == *comperator) break;
                        else {

                            // Else look for collision
                            auto col = collision::detectCollision(*sphere, **iter, dt);

                            if( col.CollisionState::flag == CollisionStateFlag::Collision ) {

                                auto& static_object = *iter;

                                auto new_t = sphere->curr_t_in_dt;

                                if( col.time > seconds_type(new_t) and col.time < dt)
                                {
                                    auto col_obj = CollisionObject(sphere, static_object, col.time);
                                    _collisions.push_back(col_obj);

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

                    auto col = collision::detectCollision(*sphere, **iter, dt);

                    if( col.CollisionState::flag == CollisionStateFlag::Collision ) {

                        auto& static_object = *iter;

                        auto new_t = sphere->curr_t_in_dt;

                        if( col.time > seconds_type(new_t) and col.time < dt)
                        {
                            auto col_obj = CollisionObject(sphere, static_object, col.time);
                            _collisions.push_back(col_obj);

                        }
                    }
                }
            }
        }

        // Same as above, only for bezier surfaces
        else if( bezier_s) {

        }
    }


}


} // END namespace collision



#endif