Esempio n. 1
0
void ContactGenerator::sphere_halfspace(const CollisionShape &a, const RigidBody &rbA, const CollisionShape &b, const RigidBody &rbB, ContactManifold &contactManifold)
{
	// Make sure we have contacts left and Check if they're the right shapes.
	if ( a.getShapeType() != SHAPE_SPHERE || b.getShapeType() != SHAPE_HALFSPACE ) { return; }

	// then typecast their appropriate shapes
	const ShapeSphere& sphere = (const ShapeSphere&)a;
	const ShapeHalfspace& halfspace = (const ShapeHalfspace&)b;

	// Get the positions and halfspace normal
	Vec3 posSphere = a.getOffset().getPosition() + rbA.getTransform().getPosition();
	Vec3 posHalfspace = a.getOffset().getPosition() + rbB.getTransform().getPosition();;
	Vec3 normHalfspace = rbB.getTransform() * b.getOffset() * Vec3(0.f, 1.f, 0.f, 0.f);

	// Find the distance from the plane to the sphere
	Scalar distance = normHalfspace.dot(posSphere) - sphere.getRadius() - (posHalfspace).y;

	// Check collision
	if(distance < 0)
	{
		// Create contact data
		ContactPoint newContact;

		newContact.normal = normHalfspace;
		newContact.position = posSphere + -newContact.normal*(sphere.getRadius() - newContact.penetration/2);
		newContact.penetration = -distance;

		contactManifold.addContactPoint(newContact);
	}

	return;
}
// Integrate all of the rigid bodies in the scene
void Physics::integrateRigidBodies(real duration)
{
	// Integrate all of the particles
	for (unsigned int particleIndex = 0; particleIndex < particles.size(); particleIndex++)
	{
		particles[particleIndex]->integrate(duration);
	}

	// Integrate all of the cubes
	if (rectangleObjects.size() > 0)
	{
		// Integrate all of the rigid bodies and add them to the bounding sphere heirarchy
		for (unsigned int rigidBodyIndex = 0; rigidBodyIndex < rectangleObjects.size(); rigidBodyIndex++)
		{
			RigidBody *body = rectangleObjects[rigidBodyIndex]->body;
			body->integrate(duration);
		}
	}

	// Integrate all of the spheres
	if (sphereObjects.size() > 0)
	{
		for (unsigned int rigidBodyIndex = 0; rigidBodyIndex < sphereObjects.size(); rigidBodyIndex++)
		{
			sphereObjects[rigidBodyIndex]->body->integrate(duration);
		}
	}

	// Integrate all the cylinders
	for (unsigned int rigidBodyIndex = 0; rigidBodyIndex < capsuleObjects.size(); rigidBodyIndex++)
	{
		capsuleObjects[rigidBodyIndex]->body->integrate(duration);
	}
}
Esempio n. 3
0
/**
 * Copy constructor.
 * @return A deep copy of this object.
 */
Object* RigidBody::clone() {
	RigidBody* rb = new RigidBody(*this);
	//rb.setShape(new rb
	rb->body_ = NULL;
	rb->processBody_();
	return rb;
} 
Esempio n. 4
0
Node* buildDrop()
{
  // A simple free falling mass.
  SharedPtr<Group> group = new Group("Group");

  MobileRootJoint* mobileRootJoint = new MobileRootJoint("Root Joint");
  mobileRootJoint->setInitialPosition(Vector3(0, 0, -10000));
  mobileRootJoint->setInitialAngularVelocity(Vector3(1, 1, 1));
  group->addChild(mobileRootJoint);

  RigidBody* rigidBody = new RigidBody("Rigid Body");
  rigidBody->addLink("externalInteractLink");
  group->addChild(rigidBody);

  Mass* mass = new Mass("Mass", 1, InertiaMatrix(1, 0, 0, 1, 0, 1));
  group->addChild(mass);

  ExternalInteract* externalInteract = new ExternalInteract("ExternalInteract");
  externalInteract->setPosition(mass->getPosition());
  externalInteract->setEnableAllOutputs(true);
  group->addChild(externalInteract);

  group->connect(mobileRootJoint->getPort("link"),
                 rigidBody->getPort("link0"));
  group->connect(rigidBody->getPort("link1"),
                 mass->getPort("link"));
  group->connect(rigidBody->getPort("externalInteractLink"),
                 externalInteract->getPort("link"));

  return group.release();
}
Esempio n. 5
0
RigidBody* PhysicsManager::createRigidBody(Ogre::SceneNode* node, Ogre::Entity* ent, RigidBodyInfo* rbInfo) {
    RigidBody* rigBod = new RigidBody();
    rigBod->setConstructionInfo(rbInfo);
    rigBod->setNode(node);
    rigBod->setEntity(ent);
    return rigBod;
}
Esempio n. 6
0
void MyGame::Update(float elapsedTime)
{
    static float spawnTimer = 0;

    spawnTimer += elapsedTime;

    if(spawnTimer >= 0.15f)
    {
        Cube* c = new Cube(Vector3f(1.f, 1.f, 1.f));
        c->SetTexture(Texture::Get("!debug.png"));
        GetScene().GetRoot()->AddChild(c);
        RigidBody* rb = c->AddToPhysic(1, Vector3f(0, 25, 7.5));
        rb->ApplyForce(Vector3f(0, -10.f, 0));
        spawnTimer = 0;

        m_cubeCount++;
    }

    std::ostringstream fps;
    fps << "FPS: " << GetFps();
    m_txtFps->SetText(fps.str());

    std::ostringstream CubeCount;
    CubeCount << "Cube count: " << m_cubeCount;
    m_txtCubeCount->SetText(CubeCount.str());
}
Esempio n. 7
0
void SceneReplication::CreateScene()
{
    scene_ = new Scene(context_);

    // Create scene content on the server only
    ResourceCache* cache = GetSubsystem<ResourceCache>();

    // Create octree and physics world with default settings. Create them as local so that they are not needlessly replicated
    // when a client connects
    scene_->CreateComponent<Octree>(LOCAL);
    scene_->CreateComponent<PhysicsWorld>(LOCAL);

    // All static scene content and the camera are also created as local, so that they are unaffected by scene replication and are
    // not removed from the client upon connection. Create a Zone component first for ambient lighting & fog control.
    Node* zoneNode = scene_->CreateChild("Zone", LOCAL);
    Zone* zone = zoneNode->CreateComponent<Zone>();
    zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.0f));
    zone->SetAmbientColor(Color(0.1f, 0.1f, 0.1f));
    zone->SetFogStart(100.0f);
    zone->SetFogEnd(300.0f);

    // Create a directional light without shadows
    Node* lightNode = scene_->CreateChild("DirectionalLight", LOCAL);
    lightNode->SetDirection(Vector3(0.5f, -1.0f, 0.5f));
    Light* light = lightNode->CreateComponent<Light>();
    light->SetLightType(LIGHT_DIRECTIONAL);
    light->SetColor(Color(0.2f, 0.2f, 0.2f));
    light->SetSpecularIntensity(1.0f);

    // Create a "floor" consisting of several tiles. Make the tiles physical but leave small cracks between them
    for (int y = -20; y <= 20; ++y)
    {
        for (int x = -20; x <= 20; ++x)
        {
            Node* floorNode = scene_->CreateChild("FloorTile", LOCAL);
            floorNode->SetPosition(Vector3(x * 20.2f, -0.5f, y * 20.2f));
            floorNode->SetScale(Vector3(20.0f, 1.0f, 20.0f));
            StaticModel* floorObject = floorNode->CreateComponent<StaticModel>();
            floorObject->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
            floorObject->SetMaterial(cache->GetResource<Material>("Materials/Stone.xml"));

            RigidBody* body = floorNode->CreateComponent<RigidBody>();
            body->SetFriction(1.0f);
            CollisionShape* shape = floorNode->CreateComponent<CollisionShape>();
            shape->SetBox(Vector3::ONE);
        }
    }

    // Create the camera. Limit far clip distance to match the fog
    // The camera needs to be created into a local node so that each client can retain its own camera, that is unaffected by
    // network messages. Furthermore, because the client removes all replicated scene nodes when connecting to a server scene,
    // the screen would become blank if the camera node was replicated (as only the locally created camera is assigned to a
    // viewport in SetupViewports() below)
    cameraNode_ = scene_->CreateChild("Camera", LOCAL);
    Camera* camera = cameraNode_->CreateComponent<Camera>();
    camera->SetFarClip(300.0f);

    // Set an initial position for the camera scene node above the plane
    cameraNode_->SetPosition(Vector3(0.0f, 5.0f, 0.0f));
}
Esempio n. 8
0
RigidBody* RigidBody::clone() {
    RigidBody* obj = new RigidBody();
    obj->setPosition(this->position);
    for (std::vector<Object*>::iterator it = this->childs.begin(); it != this->childs.end(); ++it) {
        obj->addChild(*it);
    }
    this->bindVBO();

    obj->setRotation(this->rotation);
    obj->setVAO(this->vao);
    obj->setShader(this->shader);
    obj->setVertexCounter(this->vertexCounter);

    obj->setVertices(this->g_vp);
    obj->setVPVBO(this->vp_vbo);
    obj->setBoundingBox(this->vbo_vertices_bounding_box,
                        this->ibo_elements,
                        this->sizeBoundingBox,
                        this->centerBoundingBox,
                        this->minBoundingBox,
                        this->maxBoundingBox);

    return obj;

}
Esempio n. 9
0
void Grid::ResolveCollisions(Entity* ent)
{
	RigidBody* rigid = ent->GetComponent<RigidBody>();

	if (rigid)
	{
		rigid->ResolveCollisions();

		BoxCollider* box = ent->GetComponent<BoxCollider>();

		if (box)
		{
			Vector3& max = box->GetMaxCoord();
			Vector3& min = box->GetMinCoord();

			if (min.x < 0 || min.y < 0 || max.x > GridWidth || max.y > GridHeight)
				ent->OnCollisionEnter(Collision());
		}
	}

	for (auto &child : ent->GetChildren())
	{
		ResolveCollisions(child);
	}
}
Esempio n. 10
0
void StateCharacterTurning::Update(float timeStep)
{
	StateCharacterGrounded::Update();
	
	RigidBody* body = pawn_->GetBody();
	AnimationController* animCtrl = static_cast<PawnAnimated*>(pawn_)->GetAnimationController();

	//apply a force to slow it down further, since we are changing direction
	body->ApplyImpulse(moveDir_ * pawn_->GetMoveForce() *0.25);//0.25 to dampen it

    //get the speed that we are travelling, that will determine when we turn around
    if(!flipped_)
    {
        //before we are flipped around, we drive the turning animation
        //float spd = pawn_->GetPlaneVelocity().Length();
        //float turnTime = Fit(spd,0.0f,speed_,1.0f,0.0f);
        
        animCtrl->PlayExclusive("Models/Man/MAN_TurnSkidGunning.ani", 0,false, 0.1f);
        //animCtrl->SetTime("Models/Man/MAN_TurnSkidGunning.ani",turnTime);

        if(animCtrl->IsAtEnd("Models/Man/MAN_TurnSkidGunning.ani"))
        {
            Turn();
            animCtrl->Play("Models/Man/MAN_TurnSkidGunningFlipped.ani", false, 0.0f);
            flipped_=true;
        }
    }
    else
    {
        animCtrl->Play("Models/Man/MAN_TurnSkidGunningFlipped.ani", false, 0.0f);
        //now that we are flipped we can set it to the next state too
        pawn_->SetState( new StateCharacterRunning(context_) );
    }
}
Esempio n. 11
0
bool RigidBody::CollidesWith(const RigidBody& other) const {
  bool ignored =
      this == &other || adjacentTo(other) ||
      (collision_filter_group_ & other.getCollisionFilterIgnores()).any() ||
      (other.getCollisionFilterGroup() & collision_filter_ignores_).any();
  return !ignored;
}
Esempio n. 12
0
void Gravity::ForceUpdate(RigidBody & body, REAL dt)
{
	if (body.HasInfiniteMass())
		return;

	body.AddForce(gravity*body.GetMass());
}
Esempio n. 13
0
File: Area.cpp Progetto: dcbishop/tx
/**
 * Adds an Object to the area.
 * @param object The Object's pointer.
 * @see removeObject()
 */
void Area::addObject(Object* object) {
    //object->setArea(this);
    DEBUG_M("Entering function...");
    GameManager* gm = getGameManager();
    if(object->getGameManager() != gm) {
        DEBUG_A("Different GameMangers...");
        object->setGameManager(gm);
        if(gm) {
            DEBUG_A("Registering  object with gamemanager...");
            gm->registerObject(object);
        }
    }

    RigidBody* rb = dynamic_cast<RigidBody*>(object);
    if(rb) {
        rb->addBody(getPhysics());
    }

    Light* pl = dynamic_cast<Light*>(object);
    if(pl) {
        lights_.push_back(pl);
    }

    addChild(object);
}
Esempio n. 14
0
void ContactGenerator::box_halfspace(const CollisionShape &a, const RigidBody &rbA, const CollisionShape &b, const RigidBody &rbB, ContactManifold &contactManifold)
{
	// Make sure we have contacts left and Check if they're the right shapes.
	if (a.getShapeType() != SHAPE_BOX || b.getShapeType() != SHAPE_HALFSPACE ) { return; }

	// then typecast their appropriate shapes
	const ShapeBox& box = (const ShapeBox&)a;
	const ShapeHalfspace& halfspace = (const ShapeHalfspace&)b;

	const Vec3& boxHalfExtents = box.getHalfExtents();

	// generate a array of all of the box's vertices
	Vec3 boxVertex[8] = 
	{
		Vec3(-boxHalfExtents.x, -boxHalfExtents.y, -boxHalfExtents.z),
		Vec3(-boxHalfExtents.x, -boxHalfExtents.y, +boxHalfExtents.z),
		Vec3(-boxHalfExtents.x, +boxHalfExtents.y, -boxHalfExtents.z),
		Vec3(-boxHalfExtents.x, +boxHalfExtents.y, +boxHalfExtents.z),
		Vec3(+boxHalfExtents.x, -boxHalfExtents.y, -boxHalfExtents.z),
		Vec3(+boxHalfExtents.x, -boxHalfExtents.y, +boxHalfExtents.z),
		Vec3(+boxHalfExtents.x, +boxHalfExtents.y, -boxHalfExtents.z),
		Vec3(+boxHalfExtents.x, +boxHalfExtents.y, +boxHalfExtents.z),
	};

	const Transform& boxTransform = rbA.getTransform();

	// Apply collision object offset
	for (int i = 0; i < 8; i++)
	{
		boxVertex[i] = boxTransform * a.getOffset() * boxVertex[i];
	}

	// Calculate halfspace's position and normal
	Vec3 posHalfspace = b.getOffset().getPosition() + rbB.getPosition();
	Vec3 normHalfspace = rbB.getTransform() * b.getOffset() * Vec3(0.f, 1.f, 0.f, 0.f);

	// Check each vertice for intersection with the halfspace
	Scalar vertexDistance;

	unsigned int numContacts = 0;

	for (int i = 0; i < 8; i++)
	{
		vertexDistance = boxVertex[i].dot(normHalfspace) - posHalfspace.y;

		if(vertexDistance <= 0)
		{
			// Create contact data
			ContactPoint newContact;

			newContact.normal = normHalfspace;
			newContact.penetration = -vertexDistance;
			newContact.position = boxVertex[i] + newContact.normal*(newContact.penetration*0.5f);

			contactManifold.addContactPoint(newContact);
		}
	}

	return;
}
Esempio n. 15
0
void	WheelInfo::UpdateWheel(const RigidBody& chassis,RaycastInfo& raycastInfo)
{

	
	if (m_raycastInfo.m_isInContact)

	{
		SimdScalar	project= m_raycastInfo.m_contactNormalWS.dot( m_raycastInfo.m_wheelDirectionWS );
		SimdVector3	 chassis_velocity_at_contactPoint;
		SimdVector3 relpos = m_raycastInfo.m_contactPointWS - chassis.getCenterOfMassPosition();
		chassis_velocity_at_contactPoint = chassis.getVelocityInLocalPoint( relpos );
		SimdScalar projVel = m_raycastInfo.m_contactNormalWS.dot( chassis_velocity_at_contactPoint );
		if ( project >= -0.1f)
		{
			m_suspensionRelativeVelocity = 0.0f;
			m_clippedInvContactDotSuspension = 1.0f / 0.1f;
		}
		else
		{
			SimdScalar inv = -1.f / project;
			m_suspensionRelativeVelocity = projVel * inv;
			m_clippedInvContactDotSuspension = inv;
		}
		
	}

	else	// Not in contact : position wheel in a nice (rest length) position
	{
		m_raycastInfo.m_suspensionLength = this->GetSuspensionRestLength();
		m_suspensionRelativeVelocity = 0.0f;
		m_raycastInfo.m_contactNormalWS = -m_raycastInfo.m_wheelDirectionWS;
		m_clippedInvContactDotSuspension = 1.0f;
	}
}
// -------------------------------------------------------------------------
RigidBody *OgreBulletListener::addSphere(const Ogre::String instanceName,
                                         const Ogre::Vector3 &pos, const Ogre::Quaternion &q, const Ogre::Real radius,
                                         const Ogre::Real bodyRestitution, const Ogre::Real bodyFriction, 
                                         const Ogre::Real bodyMass)
{
    Entity *entity = mSceneMgr->createEntity(
        instanceName + StringConverter::toString(mNumEntitiesInstanced),
        "ellipsoid.mesh");

    entity->setQueryFlags (GEOMETRY_QUERY_MASK);
#if (OGRE_VERSION < ((1 << 16) | (5 << 8) | 0)) // only applicable before shoggoth (1.5.0)
    entity->setNormaliseNormals(true);
#endif
	entity->setCastShadows(true);

    entity->setMaterialName("Bullet/box");

    SphereCollisionShape *sceneCubeShape = new SphereCollisionShape(radius);

    RigidBody *defaultBody = new RigidBody(
        "defaultSphereRigid" + StringConverter::toString(mNumEntitiesInstanced),
        mWorld);

    SceneNode *node = mSceneMgr->getRootSceneNode ()->createChildSceneNode ();
    node->attachObject (entity);

    defaultBody->setShape (node,  sceneCubeShape, bodyRestitution, bodyFriction, bodyMass, pos, q);

    mEntities.push_back(entity);
    mShapes.push_back(sceneCubeShape);
    mBodies.push_back(defaultBody);
    mNumEntitiesInstanced++;

    return defaultBody;
}
Esempio n. 17
0
bool CaptureWorld::setObjectRigidBody(int oid, int rid, bool offset)
{
	ClientHandler* client = AppData::getInstance()->getClient();
	if (!client) return false;

	RigidBody* rb;
	// detach object
	if (rid < 0)
	{
		rb = NULL;
	}
	else 
	{
		// check if has ownership of rigid body transformation
		rb = client->getRigidBody(rid);
		if (!rb || 
			rb->getWorldID() >=0 && rb->getWorldID() != this->id) 
			return false;

		rb->setWorldID(this->id);
	}

	CaptureObject* object = getObject(oid);
	object->setRigidBody(rb, offset);
	updateObjectsNode();
	MainFormController::getInstance()->objectUpdateGridView(oid);
	return true;
}
// -------------------------------------------------------------------------
RigidBody *OgreBulletListener::addStaticTrimesh(const Ogre::String &instanceName,
                                                const Ogre::String &meshName,
                                                const Ogre::Vector3 &pos, 
                                                const Ogre::Quaternion &q, 
                                                const Ogre::Real bodyRestitution, 
                                                const Ogre::Real bodyFriction,
                                                bool castShadow)
{
    Entity *sceneEntity = mSceneMgr->createEntity(instanceName + StringConverter::toString(mNumEntitiesInstanced), meshName);
    sceneEntity->setCastShadows (castShadow);

    StaticMeshToShapeConverter *trimeshConverter = new StaticMeshToShapeConverter(sceneEntity);
    TriangleMeshCollisionShape *sceneTriMeshShape = trimeshConverter->createTrimesh();
    delete trimeshConverter;
    RigidBody *sceneRigid = new RigidBody(
        instanceName + "Rigid" + StringConverter::toString(mNumEntitiesInstanced),
        mWorld);

    SceneNode *node = mSceneMgr->getRootSceneNode ()->createChildSceneNode ();
    node->attachObject (sceneEntity);

    sceneRigid->setStaticShape(node, sceneTriMeshShape, bodyRestitution, bodyFriction, pos);

    mEntities.push_back(sceneEntity);
    mBodies.push_back(sceneRigid);
    mNumEntitiesInstanced++;

    return sceneRigid;
}
Esempio n. 19
0
vector<pair<RigidBody *, RigidBody *>> &NSquared::ComputePairs()
{
	ColliderPairList.clear();

	//Outer Loop
	for(vector<RigidBody *>::iterator i = ColliderList.begin(); i != ColliderList.end(); ++i)
	{
		vector<RigidBody *>::iterator jStart = i;
		for(vector<RigidBody *>::iterator j = ++jStart; j != ColliderList.end(); ++j)
		{
			RigidBody *rBodyA = *i;
			RigidBody *rBodyB = *j;
			AABB *aabbA = rBodyA->GetBoundingBox();
			AABB *aabbB = rBodyB->GetBoundingBox();

			if(aabbA->checkCollision(*aabbB))
			{
				ColliderPairList.push_back(make_pair(rBodyA, rBodyB));
			}
			
		}
	}

	return ColliderPairList;
}
/**
 *	This method is used when a mouse event gets generated. This method returns true if the message gets processed, false otherwise.
 */
bool InteractiveWorld::onMouseEvent(int eventType, int button, int mouseX, int mouseY){
	//need to figure out if the mouse is in the push interface window (and if we care)...
	if (Globals::drawPushInterface == 1 && button == MOUSE_LBUTTON && eventType != MOUSE_UP){
		Vector3d input;
		Point3d p;
		if (bInterface == false){
			tprintf("Warning: No interaction interface was created!\n");
			return false;
		}

		if (world == NULL){
			tprintf("Warning: There is no valid reference to a world!\n");
			return false;
		}

		RigidBody* dBall = world->getRBByName("dodgeBall");
		if (dBall == NULL){
			tprintf("Warning: No dodgeBall loaded!\n");
			return false;
		}

		bool eventHandled = bInterface->handleMouseEvent(mouseX, mouseY, &input);
		if (eventHandled ){
			if (input.length() > 0){
				//get the object that we will be throwing...
				getDodgeBallPosAndVel(-input.x, input.y, input.length(), &p, &input);
				dBall->setCMPosition(p);
				dBall->setCMVelocity(input);
//				dBall->updateToWorldTransformation();
			}
			return true;
		}
	}
	return false;
}
Esempio n. 21
0
Node* SceneReplication::CreateControllableObject()
{
    ResourceCache* cache = GetSubsystem<ResourceCache>();
    
    // Create the scene node & visual representation. This will be a replicated object
    Node* ballNode = scene_->CreateChild("Ball");
    ballNode->SetPosition(Vector3(Random(40.0f) - 20.0f, 5.0f, Random(40.0f) - 20.0f));
    ballNode->SetScale(0.5f);
    StaticModel* ballObject = ballNode->CreateComponent<StaticModel>();
    ballObject->SetModel(cache->GetResource<Model>("Models/Sphere.mdl"));
    ballObject->SetMaterial(cache->GetResource<Material>("Materials/StoneSmall.xml"));
    
    // Create the physics components
    RigidBody* body = ballNode->CreateComponent<RigidBody>();
    body->SetMass(1.0f);
    body->SetFriction(1.0f);
    // In addition to friction, use motion damping so that the ball can not accelerate limitlessly
    body->SetLinearDamping(0.5f);
    body->SetAngularDamping(0.5f);
    CollisionShape* shape = ballNode->CreateComponent<CollisionShape>();
    shape->SetSphere(1.0f);
    
    // Create a random colored point light at the ball so that can see better where is going
    Light* light = ballNode->CreateComponent<Light>();
    light->SetRange(3.0f);
    light->SetColor(Color(0.5f + (Rand() & 1) * 0.5f, 0.5f + (Rand() & 1) * 0.5f, 0.5f + (Rand() & 1) * 0.5f));
    
    return ballNode;
}
void AiController::OnTick(const natU64 _dt)
{
	if(!m_lifeController->IsAlive())
	{
		// called spawner first
		//m_spawner->OnKilled(GetEntity());

		Spawned* spawned = GetEntity()->GetComponent<Spawned>();
		assert(spawned);
		spawned->Kill();
	}
	else
	{
		// move toward player
		Entity* player = m_playersManager->GetLocalPlayer();
		Transform* transform_player = player->GetComponent<Transform>();
		Transform* transform = GetEntity()->GetComponent<Transform>();
		RigidBody* rigidbody = GetEntity()->GetComponent<RigidBody>();

		glm::vec3 direction = transform_player->GetPos() - transform->GetPos();

		if(direction != glm::vec3(0.f))
		{
			direction = glm::normalize(direction);
			//transform->m_pos += static_cast<natF32>(_dt) * direction * m_speed;
			direction = static_cast<natF32>(_dt) * direction;
			rigidbody->ApplyLinearImpulse(direction);

		}
	}
}
Esempio n. 23
0
void PhysicsWorld::ConvexCast(PhysicsRaycastResult& result, CollisionShape* shape, const Vector3& startPos, const Quaternion& startRot, const Vector3& endPos, const Quaternion& endRot, unsigned collisionMask)
{
    if (!shape || !shape->GetCollisionShape())
    {
        LOGERROR("Null collision shape for convex cast");
        result.body_ = 0;
        result.position_ = Vector3::ZERO;
        result.normal_ = Vector3::ZERO;
        result.distance_ = M_INFINITY;
        return;
    }

    // If shape is attached in a rigidbody, set its collision group temporarily to 0 to make sure it is not returned in the sweep result
    RigidBody* bodyComp = shape->GetComponent<RigidBody>();
    btRigidBody* body = bodyComp ? bodyComp->GetBody() : (btRigidBody*)0;
    btBroadphaseProxy* proxy = body ? body->getBroadphaseProxy() : (btBroadphaseProxy*)0;
    short group = 0;
    if (proxy)
    {
        group = proxy->m_collisionFilterGroup;
        proxy->m_collisionFilterGroup = 0;
    }

    ConvexCast(result, shape->GetCollisionShape(), startPos, startRot, endPos, endRot, collisionMask);

    // Restore the collision group
    if (proxy)
        proxy->m_collisionFilterGroup = group;
}
Esempio n. 24
0
//------------------------------------------------------------------------------
void SoccerBall::frameMove(float dt)
{
    RigidBody::frameMove(dt);

    return;
    
    if (!proxy_object_) return;

    RigidBody * body = (RigidBody*)game_state_->getGameObject(rel_object_id_);
    if (body)
    {
        Vector new_pos = body->getTransform().transformPoint(rel_pos_);

         setPosition(new_pos);
//         setGlobalLinearVel(body->getGlobalLinearVel());

//        getTarget()->setPosition(new_pos);
//        getTarget()->setGlobalLinearVel(body->getGlobalLinearVel());
//         handleProxyInterpolation();
//         handleProxyInterpolation();


//        proxy_object_->setPosition(proxy_object_->getPosition() + dt*body->getGlobalLinearVel());
        
    }
}
Esempio n. 25
0
void Ragdolls::SpawnObject()
{
    ResourceCache* cache = GetContext()->m_ResourceCache.get();

    Node* boxNode = scene_->CreateChild("Sphere");
    boxNode->SetPosition(cameraNode_->GetPosition());
    boxNode->SetRotation(cameraNode_->GetRotation());
    boxNode->SetScale(0.25f);
    StaticModel* boxObject = boxNode->CreateComponent<StaticModel>();
    boxObject->SetModel(cache->GetResource<Model>("Models/Sphere.mdl"));
    boxObject->SetMaterial(cache->GetResource<Material>("Materials/StoneSmall.xml"));
    boxObject->SetCastShadows(true);

    RigidBody* body = boxNode->CreateComponent<RigidBody>();
    body->SetMass(1.0f);
    body->SetRollingFriction(0.15f);
    CollisionShape* shape = boxNode->CreateComponent<CollisionShape>();
    shape->SetSphere(1.0f);

    const float OBJECT_VELOCITY = 10.0f;

    // Set initial velocity for the RigidBody based on camera forward vector. Add also a slight up component
    // to overcome gravity better
    body->SetLinearVelocity(cameraNode_->GetRotation() * Vector3(0.0f, 0.25f, 1.0f) * OBJECT_VELOCITY);
}
bool testBodyTreeModel1(unsigned numLevels, unsigned numBodies)
{
  SharedPtr<Group> group = new Group("Group");

  MobileRootJoint* mechanicRootJoint = new MobileRootJoint("RootJoint");
  group->addChild(mechanicRootJoint);

  RigidBody* rigidBody = new RigidBody("RigidBody");
  group->addChild(rigidBody);
  group->connect(mechanicRootJoint->getPort("link"),
                 rigidBody->addLink("rootLink"));
  
  Mass* mass = new Mass("Mass", 1, InertiaMatrix(1, 0, 0, 1, 0, 1));
  group->addChild(mass);
  group->connect(mass->getPort("link"), rigidBody->addLink("massLink"));

  addBodiesRecursive(numLevels, numBodies, rigidBody, group);

  SharedPtr<System> system = new System("Closed kinematic Loop 1");
  system->setNode(group);

  if (!system->init()) {
    std::cerr << "Initialization of single body model failed!" << std::endl;
    return false;
  }
  return true;
}
Esempio n. 27
0
double ExcludedVolumeRestraint::unprotected_evaluate(DerivativeAccumulator *da)
    const {
  IMP_OBJECT_LOG;
  if (!initialized_) {
    initialize();
  } else {
    IMP_IF_CHECK(USAGE) {
      Model *m = get_model();
      IMP_CONTAINER_FOREACH(SingletonContainer, sc_, {
        if (RigidMember::get_is_setup(m, _1)) {
          RigidBody rb = RigidMember(m, _1).get_rigid_body();
          using IMP::operator<<;
          IMP_USAGE_CHECK(
              std::find(rbs_.begin(), rbs_.end(),
                        rb.get_particle()->get_index()) != rbs_.end(),
              "You cannot change the contents of the singleton container "
                  << "passed to ExcludedVolume after the first evaluate."
                  << " Found unexpected rigid body " << rb->get_name()
                  << " not in " << rbs_);
        } else {
          IMP_USAGE_CHECK(
              std::find(xyzrs_.begin(), xyzrs_.end(), _1) != xyzrs_.end(),
              "You cannot change the contents of the singleton container "
                  << "passed to ExcludedVolume after the first evaluate."
                  << " Found unexpected particle " << m->get_particle_name(_1));
        }
      });
    }
  }
bool testClosedKinematicLoop2()
{
  SharedPtr<Group> group = new Group("Group");

  MobileRootJoint* mechanicRootJoint = new MobileRootJoint("RootJoint");
  group->addChild(mechanicRootJoint);

  RigidBody* rigidBody = new RigidBody("RigidBody");
  group->addChild(rigidBody);
  group->connect(mechanicRootJoint->getPort("link"),
                 rigidBody->addLink("rootLink"));

  PrismaticJoint* prismaticJoint = new PrismaticJoint("PrismaticJoint");
  group->addChild(prismaticJoint);
  group->connect(rigidBody->addLink("jointLink0"),
                 prismaticJoint->getPort("link0"));
  group->connect(rigidBody->addLink("jointLink1"),
                 prismaticJoint->getPort("link1"));

  SharedPtr<System> system = new System("Closed kinematic Loop 1");
  system->setNode(group);

  if (system->init()) {
    std::cerr << "Detection of klosed kinematic loop failed!" << std::endl;
    return false;
  }
  return true;
}
Esempio n. 29
0
void PhysicsStressTest::SpawnObject()
{
    ResourceCache* cache = GetSubsystem<ResourceCache>();
    
    // Create a smaller box at camera position
    Node* boxNode = scene_->CreateChild("SmallBox");
    boxNode->SetPosition(cameraNode_->GetPosition());
    boxNode->SetRotation(cameraNode_->GetRotation());
    boxNode->SetScale(0.25f);
    StaticModel* boxObject = boxNode->CreateComponent<StaticModel>();
    boxObject->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
    boxObject->SetMaterial(cache->GetResource<Material>("Materials/StoneSmall.xml"));
    boxObject->SetCastShadows(true);
    
    // Create physics components, use a smaller mass also
    RigidBody* body = boxNode->CreateComponent<RigidBody>();
    body->SetMass(0.25f);
    body->SetFriction(0.75f);
    CollisionShape* shape = boxNode->CreateComponent<CollisionShape>();
    shape->SetBox(Vector3::ONE);
    
    const float OBJECT_VELOCITY = 10.0f;
    
    // Set initial velocity for the RigidBody based on camera forward vector. Add also a slight up component
    // to overcome gravity better
    body->SetLinearVelocity(cameraNode_->GetRotation() * Vector3(0.0f, 0.25f, 1.0f) * OBJECT_VELOCITY);
}
Esempio n. 30
0
void ContactGenerator::sphere_sphere(const CollisionShape &a, const RigidBody &rbA, const CollisionShape &b, const RigidBody &rbB, ContactManifold &contactManifold)
{
	// Make sure we have contacts left and Check if they're spheres.
	if ( a.getShapeType() != SHAPE_SPHERE || b.getShapeType() != SHAPE_SPHERE ) { return; }
	
	//  then typecast their shape to a sphere
	const ShapeSphere& shapeA = (const ShapeSphere&)a;
	const ShapeSphere& shapeB = (const ShapeSphere&)b;

	// Get the sphere positions
	Vec3 posA = a.getOffset().getPosition() + rbA.getPosition();
	Vec3 posB = b.getOffset().getPosition() + rbB.getPosition();

	// Find the vector between the two object
	Vec3 midLine = posA - posB;
	Scalar distance = midLine.length();

	// Check for collision
	if (distance <= 0.0f || distance >= shapeA.getRadius() + shapeB.getRadius())
	{
		return;
	}

	// Create contact data
	ContactPoint newContact;

	newContact.normal = midLine * ( ((Scalar)1.0) / distance );
	newContact.position = posA + (midLine * (Scalar)-0.5);
	newContact.penetration = (shapeA.getRadius() + shapeA.getRadius() - distance);

	contactManifold.addContactPoint(newContact);
}