void LaunchPadListener::contactPointAddedCallback(hkpContactPointAddedEvent& event)
{
	// Grab the body to launch
	hkpRigidBody* collidedRb = hkGetRigidBody( event.m_bodyA->getRootCollidable() );

	// If m_forceMagnitude is zero then launch toward a target
	if( m_forceMagnitude == 0.0f )
	{
		collidedRb->setMaxLinearVelocity( 300.0f );

		hkVector4 impulse;
		impulse.setSub4( m_targetPosition, collidedRb->getPosition() );
		impulse.mul4( 225.0f );

		PlanetGravityDemo::applyScaledLinearImpulse( collidedRb, impulse );
	}
	// Just apply an impulse along the contact normal
	else
	{
		hkVector4 impulse( event.m_contactPoint->getNormal() );
		impulse.mul4( m_forceMagnitude * 225.0f );
		collidedRb->setMaxLinearVelocity( 300.0f );

		PlanetGravityDemo::applyScaledLinearImpulse( collidedRb, impulse );
	}

	event.m_status = HK_CONTACT_POINT_REJECT;
}
Exemple #2
0
void Forest::applyRadialImpulse( const Point3F &origin, F32 radius, F32 magnitude )
{   
   if ( isServerObject() )
      return;   

   // Find all the trees in the radius
   // then get their accumulators and 
   // push our impulse into them.
   VectorF impulse( 0, 0, 0 );
   ForestWindAccumulator *accumulator = NULL;

   Vector<TreePlacementInfo> trees;
   getLocalWindTrees( origin, radius, &trees );
   for ( U32 i = 0; i < trees.size(); i++ )
   {
      const TreePlacementInfo &treeInfo = trees[i];
      accumulator = WINDMGR->getLocalWind( treeInfo.itemKey );
      if ( !accumulator )
         continue;

      impulse = treeInfo.pos - origin;
      impulse.normalize();
      impulse *= magnitude;

      accumulator->applyImpulse( impulse );
   }
}
Exemple #3
0
void
warp64(uvlong entry)
{
	u64intptr kzero64;
	extern void _warp64(ulong);

//	kzero64 = KZERO64;
//	if(entry != 0xFFFFFFFF80110000ULL){
//		print("bad entry address %#llux\n", entry);
//		return;
//	}
kzero64 = entry & ~0x000000000fffffffull;
	print("warp64(%#llux) %#llux %d\n", entry, kzero64, nmmap);
	if(vflag)
		print("mkmultiboot\n");
	mkmultiboot();
	if(vflag)
		print("mkmach0pt\n");
	mkmach0pt(kzero64);
	if(vflag)
		print("impulse\n");

	/*
	 * No output after impulse().
	 */
	if(vflag)
		print("_warp64\n");
	impulse();
	_warp64(Pml4);
}
void CalculatePickForceAndTorque (const NewtonBody* const body, const dVector& pointOnBodyInGlobalSpace, const dVector& targetPositionInGlobalSpace, dFloat timestep)
{
	dFloat mass;
	dFloat Ixx;
	dFloat Iyy;
	dFloat Izz;
	const dFloat stiffness = 0.33f;
	const dFloat damping = -0.05f;

	NewtonBodyGetMass(body, &mass, &Ixx, &Iyy, &Izz);

	// calculate the desired impulse
	dVector posit(targetPositionInGlobalSpace - pointOnBodyInGlobalSpace);
	dVector impulse(posit.Scale(stiffness * mass));

	// apply linear impulse
	NewtonBodyApplyImpulseArray(body, 1, sizeof (dVector), &impulse[0], &pointOnBodyInGlobalSpace[0], timestep);

	// apply linear and angular damping
	dMatrix inertia;
	dVector linearMomentum(0.0f);
	dVector angularMomentum(0.0f);

	NewtonBodyGetOmega(body, &angularMomentum[0]);
	NewtonBodyGetVelocity(body, &linearMomentum[0]);


	NewtonBodyGetInertiaMatrix(body, &inertia[0][0]);

	angularMomentum = inertia.RotateVector(angularMomentum);
	angularMomentum = angularMomentum.Scale(damping);
	linearMomentum = linearMomentum.Scale(mass * damping);

	NewtonBodyApplyImpulsePair(body, &linearMomentum[0], &angularMomentum[0], timestep);
}
Exemple #5
0
void
warp86(char* s, uint32_t)
{
	if(s == nil)
		s = "Warp86\n";
	print(s);
	spllo();

	impulse();

	i8042reset();

	/*
	 * Often the BIOS hangs during restart if a conventional 8042
	 * warm-boot sequence is tried. The following is Intel specific and
	 * seems to perform a cold-boot, but at least it comes back.
	 * And sometimes there is no keyboard...
	 *
	 * The reset register (0xcf9) is usually in one of the bridge
	 * chips. The actual location and sequence could be extracted from
	 * ACPI but why bother, this is the end of the line anyway.
	 */
	print("Takes a licking and keeps on ticking...\n");
	*(uint16_t*)KADDR(0x472) = 0x1234;	/* BIOS warm-boot flag */
	outb(0xcf9, 0x02);
	outb(0xcf9, 0x06);

	for(;;)
		idle();
}
Exemple #6
0
void dgBody::ApplyImpulsesAtPoint (dgInt32 count, dgInt32 strideInBytes, const dgFloat32* const impulseArray, const dgFloat32* const pointArray)
{
	dgInt32 stride = strideInBytes / sizeof (dgFloat32);

	dgMatrix inertia (CalculateInertiaMatrix());

	dgVector impulse (m_veloc.Scale3 (m_mass.m_w));
	dgVector angularImpulse (inertia.RotateVector (m_omega));

	dgVector com (m_globalCentreOfMass);
	for (dgInt32 i = 0; i < count; i ++) {
		dgInt32 index = i * stride;
		dgVector r (pointArray[index], pointArray[index + 1], pointArray[index + 2], dgFloat32 (0.0f));
		dgVector L (impulseArray[index], impulseArray[index + 1], impulseArray[index + 2], dgFloat32 (0.0f));
		dgVector Q ((r - com) * L);

		impulse += L;
		angularImpulse += Q;
	}

	dgMatrix invInertia (CalculateInvInertiaMatrix());
	m_veloc = impulse.Scale3(m_invMass.m_w);
	m_omega = invInertia.RotateVector(angularImpulse);

	m_sleeping	= false;
	m_equilibrium = false;
	Unfreeze ();
}
Exemple #7
0
//--------------------------------------------------------------
void testApp::update(){
	mouseParticle->set(mouseX, mouseY);
	if(newParticle){
		newParticle->setRadius((sin(newParticleIncrement)*100) + 5);
		newParticleIncrement+= 0.01f;
		newParticle->moveTo(mouseX, mouseY);
	}
	if(bCreateParticles){
		if(ofGetFrameNum() % 5 == 0){
			float radius = ofRandom(10, 50);
			float mass = radius * 0.5f;
			ofxParticle* p = new ofxParticle(mouseX, mouseY, radius, mass);
			float randomStep = 5;
			ofxVec2f impulse(ofRandom(-randomStep, randomStep), ofRandom(-randomStep, randomStep));
			p->applyImpulse(impulse);
			particles.push_back(p);
			physics->add(p);
		}
	}
	for(int i=0; i<particles.size(); i++){
		if(particles[i]->y > ofGetHeight() + particles[i]->getRadius()){
			while(physics->getConstraintWithParticle(particles[i]) != NULL){
				physics->deleteConstraintsWithParticle(particles[i]);
			}
			physics->deleteParticle(particles[i]);
			particles.erase(particles.begin()+i);
		}
	}
	physics->update();
}
        /**
         * Compute and return the velocity impulsion
         * given the contact point (in global frame)
         * and collision normal direction
         */
        inline Vector2D computeImpulsion
            (const Vector2D& point, const Vector2D& dir) const
        {
            if (dir.norm() < 0.999 || dir.norm() > 1.001) {
                throw std::logic_error(
                    "UnaryConstraint not normalized dir");
            }

            //Compute velocity of collisioning point
            Vector2D centerPos = _system->evalPosition(*_body);
            Vector2D centerVel = _system->evalPositionVel(*_body);
            scalar centerAngleVel = _system->evalAngleVel(*_body);
            Vector2D vel = centerVel
                + centerAngleVel*Vector2D::normal(point - centerPos);

                //FIXME: between moving bodies?


            //Build impulse
            Vector2D impulse(0.0, 0.0);

            //Declare normal and tangent unit vector
            Vector2D n = dir;
            Vector2D t = Vector2D::normal(dir);
            //Tangent (friction) component
            if (Constraint::isFriction()) {
                impulse += -Vector2D::dot(vel, t)*t;
            }
            //Normal (response) component
            scalar e = Constraint::getRestitutionCoef();
            impulse += -(e+1.0)*Vector2D::dot(vel, n)*n;

            return impulse;
        }
Exemple #9
0
void
warp64(uvlong entry)
{
	u64intptr kzero64 = 0xfffffffff0000000ull;
	extern void _warp64(ulong);

	print("warp64(%#llux) %#llux %d\n", entry, entry & ~kzero64, nmmap);
	if(!havelongmode()) {
		print("can't run 64-bit kernel on 32-bit cpu\n");
		delay(5000);
		exit(0);
	}
	if(v_flag)
		print("mkmultiboot\n");
	mkmultiboot();
	if(v_flag)
		print("impulse\n");
	/*
	 * No output after impulse().
	 */
	if(v_flag)
		print("_warp64\n");
	impulse();
	_warp64(entry & ~kzero64);
}
Exemple #10
0
hkVector4 RPG_Explosion::GetImpulse( hkVector4 const& positionHk )
{
  hkvVec3 impulse(0.0f, 0.0f, 0.0f);

  hkvVec3 position;
  vHavokConversionUtils::PhysVecToVisVecLocal(positionHk, position);

  switch(m_type)
  {
  case ET_Sphere:
    {
      impulse = GetSphereImpulse(position);
    }
    break;

  case ET_HerringBone:
    {
      impulse = GetHerringBoneImpulse(position);
    }
    break;

  case ET_None:
  case ET_Count:
  default:
    {
      VASSERT_MSG(false, "Please specify a valid RPG_ExplosionType_e.")
    }
    break;
  }

  hkVector4 impulseHk;
  vHavokConversionUtils::VisVecToPhysVecLocal(impulse, impulseHk);
  return impulseHk;
}
Exemple #11
0
hkvVec3 RPG_Explosion::GetHerringBoneImpulse( hkvVec3 const& position )
{
  hkvVec3 impulse(0.0f, 0.0f, 0.0f);

  hkvVec3 attackLine = m_direction;
  attackLine.z = 0.0f;
  attackLine.normalize();
  float const lineProjection = hkvMath::Max(0.0f, position.dot(attackLine) - m_center.dot(attackLine));
  hkvVec3 const& closestPointOnAttackLine = m_center + lineProjection * attackLine;
  impulse = (position - closestPointOnAttackLine);
  impulse.z = 0.0f;
  float distanceLineToImpact = impulse.getLengthAndNormalize();
  if(hkvMath::isFloatEqual(0.0f, distanceLineToImpact))
  {
    if(Vision::Game.GetFloatRand() > 0.5)
    {
      impulse.x = attackLine.y;
      impulse.y = -attackLine.x;
    }
    else
    {
      impulse.x = -attackLine.y;
      impulse.y = -attackLine.x;
    }
  }
  impulse += attackLine;
  impulse.normalize();
  
  float const strengthScale = hkvMath::Max(0.0f, (m_length - lineProjection) / m_length) *
    hkvMath::Max(0.0f, (m_radius - distanceLineToImpact) / m_radius);

  impulse.z = 0.1f;
  return impulse * strengthScale * m_impulseStrength;
}
const btVector3 Weapon::bulletLinearVelocity() const {
    double bulletVelocity = impulse()/m_bullet_mass;
    btVector3 result(0, 0, bulletVelocity);
    result = result.rotate(m_body->getWorldTransform().getRotation().getAxis(),
                           m_body->getWorldTransform().getRotation().getAngle())
             + m_body->getLinearVelocity();
    return result;
}
Exemple #13
0
void verify_rdft2(bench_problem *p, int rounds, double tol, errors *e)
{
     C *inA, *inB, *inC, *outA, *outB, *outC, *tmp;
     int n, vecn, N;
     dofft_rdft2_closure k;

     BENCH_ASSERT(p->kind == PROBLEM_REAL);

     if (!FINITE_RNK(p->sz->rnk) || !FINITE_RNK(p->vecsz->rnk))
	  return;      /* give up */

     k.k.apply = rdft2_apply;
     k.k.recopy_input = 0;
     k.p = p;

     if (rounds == 0)
	  rounds = 20;  /* default value */

     n = tensor_sz(p->sz);
     vecn = tensor_sz(p->vecsz);
     N = n * vecn;

     inA = (C *) bench_malloc(N * sizeof(C));
     inB = (C *) bench_malloc(N * sizeof(C));
     inC = (C *) bench_malloc(N * sizeof(C));
     outA = (C *) bench_malloc(N * sizeof(C));
     outB = (C *) bench_malloc(N * sizeof(C));
     outC = (C *) bench_malloc(N * sizeof(C));
     tmp = (C *) bench_malloc(N * sizeof(C));

     e->i = impulse(&k.k, n, vecn, inA, inB, inC, outA, outB, outC, 
		    tmp, rounds, tol);
     e->l = linear(&k.k, 1, N, inA, inB, inC, outA, outB, outC,
		   tmp, rounds, tol);

     e->s = 0.0;
     if (p->sign < 0)
	  e->s = dmax(e->s, tf_shift(&k.k, 1, p->sz, n, vecn, p->sign,
				     inA, inB, outA, outB, 
				     tmp, rounds, tol, TIME_SHIFT));
     else
	  e->s = dmax(e->s, tf_shift(&k.k, 1, p->sz, n, vecn, p->sign,
				     inA, inB, outA, outB, 
				     tmp, rounds, tol, FREQ_SHIFT));
     
     if (!p->in_place && !p->destroy_input)
	  preserves_input(&k.k, p->sign < 0 ? mkreal : mkhermitian1,
			  N, inA, inB, outB, rounds);

     bench_free(tmp);
     bench_free(outC);
     bench_free(outB);
     bench_free(outA);
     bench_free(inC);
     bench_free(inB);
     bench_free(inA);
}
Exemple #14
0
static void
set_sep_scale (Mtx sep_scale, sync_info *sync)
{
  if (sync->bar >= 73 && sync->bar <= 75)
    {
      float beat = 4.0 * (sync->bar_pos - 0.25);
      float bar_pos_adj = sync->bar_pos + (float) sync->bar - 73.0;
      float size, bar_impulse;
      beat = beat - floorf (beat);
      if (bar_pos_adj >= 0)
        bar_impulse = impulse (4, bar_pos_adj);
      else
        bar_impulse = 0.0;
      size = 10.0 + 10.0 * impulse (4, beat) * bar_impulse;
      guMtxScale (sep_scale, size, size, size);
    }
  else
    guMtxScale (sep_scale, 10.0, 10.0, 10.0);
}
Exemple #15
0
void Player::jump() {
    if(m_ability < JUMP) return;

    float strength = 7.f * m_springPower;
    btVector3 impulse(0, -1, 0);
    impulse = impulse.rotate(btVector3(0, 0, 1), thor::Pi + m_rotation);
    impulse *= strength;
    m_physicsBody->applyCentralImpulse(impulse);

    m_springPower = 0;
}
void verify_dft(bench_problem *p, int rounds, double tol, errors *e)
{
     C *inA, *inB, *inC, *outA, *outB, *outC, *tmp;
     int n, vecn, N;
     dofft_dft_closure k;

     BENCH_ASSERT(p->kind == PROBLEM_COMPLEX);

     k.k.apply = dft_apply;
     k.k.recopy_input = 0;
     k.p = p;

     if (rounds == 0)
	  rounds = 20;  /* default value */

     n = tensor_sz(p->sz);
     vecn = tensor_sz(p->vecsz);
     N = n * vecn;

     inA = (C *) bench_malloc(N * sizeof(C));
     inB = (C *) bench_malloc(N * sizeof(C));
     inC = (C *) bench_malloc(N * sizeof(C));
     outA = (C *) bench_malloc(N * sizeof(C));
     outB = (C *) bench_malloc(N * sizeof(C));
     outC = (C *) bench_malloc(N * sizeof(C));
     tmp = (C *) bench_malloc(N * sizeof(C));

     e->i = impulse(&k.k, n, vecn, inA, inB, inC, outA, outB, outC, 
		    tmp, rounds, tol);
     e->l = linear(&k.k, 0, N, inA, inB, inC, outA, outB, outC,
		   tmp, rounds, tol);

     e->s = 0.0;
     e->s = dmax(e->s, tf_shift(&k.k, 0, p->sz, n, vecn, p->sign,
				inA, inB, outA, outB, 
				tmp, rounds, tol, TIME_SHIFT));
     e->s = dmax(e->s, tf_shift(&k.k, 0, p->sz, n, vecn, p->sign,
				inA, inB, outA, outB, 
				tmp, rounds, tol, FREQ_SHIFT));

     if (!p->in_place && !p->destroy_input)
	  preserves_input(&k.k, 0, N, inA, inB, outB, rounds);

     bench_free(tmp);
     bench_free(outC);
     bench_free(outB);
     bench_free(outA);
     bench_free(inC);
     bench_free(inB);
     bench_free(inA);
}
	void DynamicEntity::jump(b2Vec2 gravity)
	{
		
		//float maxJumpForce = body_->GetMass() * getJumpPower() * (-gravity.y) / 1.2; //happy constant
		//animationManager_.setAnimation("Jump", false);
		//float oldVelocity = body_->GetLinearVelocity().y;
		float jumpForce = body_->GetMass() * getJumpPower() * (-gravity.y) / 1.2;
		/*if (oldVelocity > 0)
		{
			jumpForce -= oldVelocity;
		}*/

		b2Vec2 impulse(0, jumpForce);
		body_->ApplyLinearImpulse(impulse, body_->GetWorldCenter(), true);
	}
Exemple #18
0
// This function actually applies the specified noise to the given image
// in the given amounts
IplImage* GenerateNoise(IplImage* img, int noiseType, float amount=255)
{
	CvSize imgSize = cvGetSize(img);
	IplImage* imgTemp = cvCloneImage(img);	// This will hold the noisy image

	// Go through each pixel
	for(int y=0;y<imgSize.height;y++)
	{
		for(int x=0;x<imgSize.width;x++)
		{
			int randomValue=0;				// Our noise is additive.. this holds
			switch(noiseType)				// the amount to add/subtract
			{
			case NOISE_UNIFORM:				// I chose UNIFORM, so give me a uniform random number
				randomValue = (char)(uniform()*amount);
				break;

			case NOISE_EXPONENTIAL:			// I chose EXPONENTIAL... so exp random number please
				randomValue = (int)(exponential()*amount);
				break;

			case NOISE_GAUSSIAN:			// same here
				randomValue = (int)(gaussian()*amount);
				break;

			case NOISE_RAYLEIGH:			// ... guess!!
				randomValue = (int)(rayleigh()*amount);
				break;

			case NOISE_GAMMA:				// I chose gamma... give me a gamma random number
				randomValue = (int)(gamma()*amount);
				break;

			case NOISE_IMPULSE:				// I need salt and pepper.. pass the shakers please
				randomValue = (int)(impulse((float)amount/256)*amount);
			}
			
			// Here we "apply" the noise to the current pixel
			int pixelValue = cvGetReal2D(imgTemp, y, x)+randomValue;

			// And set this value in our noisy image
			cvSetReal2D(imgTemp, y, x, pixelValue);
		}
	}

	// return
	return imgTemp;
}
Exemple #19
0
		// hkpPhantom interface implementation
		virtual void phantomLeaveEvent( const hkpCollidable* collidableA, const hkpCollidable* collidableB )
		{
			// the color can only be changed once the entity has been added to the world
			hkpRigidBody* owner = hkGetRigidBody(collidableB);

			// the "Collidables" here are "faked" so it's necessary to get the owner first in order
			// to get the "real" collidable!
			HK_SET_OBJECT_COLOR((hkUlong)owner->getCollidable(), hkColor::rgbFromChars(0, 255, 0));

			// If moving out AND falling down, apply impulse to fire it towards "wall"
			if(owner->getLinearVelocity()(1) < 0.0f)
			{
				hkVector4 impulse(-50.0f, 220.0f, 0.0f);
				owner->applyLinearImpulseAsCriticalOperation(impulse);
			}
		}
Exemple #20
0
// This function actually applies the specified noise to the given
// in the given amounts
IplImage* GenerateNoise(IplImage* img, int noiseType, float amount=255)
{
    CvSize imgSize = cvGetSize(img);
    IplImage* imgTemp = cvCloneImage(img); // This will hold the n

    // Go through each pixel
    for(int y=0; y<imgSize.height; y++)
    {
        for(int x=0; x<imgSize.width; x++)
        {
            int randomValue=0; // our noise is additivwe
            switch(noiseType) // the amount to add/substract
            {
            case NOISE_UNIFORM:
                randomValue = (char)(uniform()*amount);
                break;

            case NOISE_EXPONENTIAL:
                randomValue = (int)(exponential()*amount);
                break;

            case NOISE_GAUSSIAN:
                randomValue = (int)(gaussian()*amount);
                break;

            case NOISE_RAYLEIGH:
                randomValue = (int)(rayleigh()*amount);
                break;

            case NOISE_GAMMA:
                break;

            case NOISE_IMPULSE:
                randomValue = (int)(impulse((float)amount/256)*amount);
            }

            int pixelValue = cvGetReal2D(imgTemp, y, x)+randomValue;

            // And set this value in our noisy image
            cvSetReal2D(imgTemp, y, x, pixelValue);
        }
    }

    // return
    return imgTemp;
}
	void PIG2D_Bungee::updateImpulse(Particle2D* particle, float dt)
	{
		glm::vec2 impulse(particle->position);
		impulse -= otherParticle->position;

		float magnitude = glm::length(impulse);

		if(magnitude <= restLength) return;

		magnitude -= restLength;
		magnitude = (magnitude < 0) ? -magnitude : magnitude;
		
		magnitude *= springConstant;

		impulse = glm::normalize(impulse);
		impulse *= -magnitude;
		particle->addImpulse(impulse);
	}
Exemple #22
0
/*
	Detects a collision with a plane and applies physical impulse response
*/
bool RigidBody::collision_detect(Plane &p)
{
	for( int i = 0;	i < 8; i++)
	{
		// make center origin
		vec3 point = center + aabb[i];

		//rotate around origin
		point = orientation * point;

		// rotate center around about true origin
		vec3 offset = orientation * center;

		// translate back to local coordinate origin
		point = point - offset;

		// translate to world coordinates
		point = point + position;

		float d = point * p.normal + p.d;

		if ( d < -0.25f )
		{
			// Simulated too far
			return true;
		}
		else if ( d < 0.0f )
		{
			// Colliding

			// convert rotated point back to local coordinates
			point = point - position;

			// convert point back to radius from center
			point = point + offset;

			// apply impulse to plane and radius vector
			impulse(p, point);
			position = old_position;
			orientation = old_orientation;
		}
	}
	return false;
}
btTransform Weapon::fire() {
    if (m_can_firing) {
        btTransform result(m_body->getWorldTransform().getRotation());
        result.setOrigin(m_bullet_spawn.rotate(m_body->getWorldTransform().getRotation().getAxis(),
                                               m_body->getWorldTransform().getRotation().getAngle())
                         + m_body->getWorldTransform().getOrigin());

        btVector3 returnImpulse = btVector3(0, 0, -impulse());
        returnImpulse = returnImpulse.rotate(m_body->getWorldTransform().getRotation().getAxis(),
                                             m_body->getWorldTransform().getRotation().getAngle());
        m_body->applyCentralImpulse(returnImpulse);

        m_firerate_timer = fireRate();
        --m_package_capacity_current;

        return result;
    } else {
        return btTransform(btQuaternion::getIdentity(), btVector3(NAN, NAN, NAN));
    }
}
Exemple #24
0
b2Vec2 simulator::car_caculate_impulse(double deltime)
{
	float speed_precent;
	float force_precent;

	b2Vec2 impulse(0, 0);
	b2Vec2 ground_normal = get_ground_normal();

	/* Get Wheel Speed  */
	float wheel_speed = car_wheel_speed();

	/*the theoretical speed indicatied by pwm*/
	float pwm_speed = MAX_SPEED * PWM / 255.0;

	/* Caculate the Force at given speed  */
	if (PWM != 0)
	{
		speed_precent = (pwm_speed - wheel_speed) / pwm_speed;

		if (speed_precent >= 1)
			speed_precent = 1;
		else if (speed_precent < 0)
			return impulse;

		force_precent = speed_precent; //*speed_precent;

		float Impulse = force_precent * m_max_force * PWM / 255.0 * deltime;

		// should set the force vector according to the ground vector

#if 0
		impulse.Set(-Impulse * cos(car->GetAngle()),
				Impulse * sin(car->GetAngle()));
#else
		impulse.Set(-Impulse, 0);
#endif
	}
	return impulse;
}
void OssiaImpulse::setNode(QString node)
{
    if(!publisher_singleton)
        return;

    if (m_node == node)
        return;

    m_node = node;

    if(m_ossia_node)
    {
        auto par = m_ossia_node->getParent();
        auto& cld = par->children();
        auto it = std::find(cld.begin(), cld.end(), m_ossia_node);
        if(it != cld.end())
            par->erase(it);
    }

    m_ossia_node = getOrCreateNode(
                publisher_singleton->_localDevice,
                node.split('/'));

    if(auto addr = m_ossia_node->getAddress())
    {
        m_address = addr;
    }
    else
    {
        m_address = m_ossia_node->createAddress(OSSIA::Value::Type::IMPULSE);
        m_address->addCallback([=] (const OSSIA::Value* val) {
            emit impulse();
        });
    }

    emit nodeChanged(node);
}
Exemple #26
0
void CMeleeWeapon::MeleeCollision( idEntity *other, idVec3 dir, trace_t *tr, int location )
{
	const char *DamageDefName;
	const idDict *DmgDef;
	float push(0.0f), DmgScale(1.0f);
	idVec3 impulse(vec3_zero);
	idStr hitSound, sndName, surfType;

	DamageDefName = spawnArgs.GetString( va("def_damage_%s", m_ActionName.c_str()) );
	DmgDef = gameLocal.FindEntityDefDict( DamageDefName, false );

	if( !DmgDef )
	{
		DM_LOG(LC_WEAPON,LT_DEBUG)LOGSTRING("MeleeWeapon: Did not find damage def %s\r", DamageDefName);
		return;
	}

	// Apply physical impulse
	push = DmgDef->GetFloat( "push" );
	impulse = -push * tr->c.normal;
	// DM_LOG(LC_WEAPON,LT_DEBUG)LOGSTRING("MeleeCollision: Applying impulse\r");
	other->ApplyImpulse( this, tr->c.id, tr->c.point, impulse );
	// uncomment for physics debugging
	// gameRenderWorld->DebugArrow( colorBlue, tr->c.point, tr->c.point + impulse, 3, 1000 );

	// get type of material hit (armor, etc)
	int type;
	if( tr->c.material != NULL )
	{
		type = tr->c.material->GetSurfaceType();
	}
	else
	{
		type = SURFTYPE_NONE;
	}

	if ( type == SURFTYPE_NONE )
	{
		// use a default surface type if we are unable to detect one
		surfType = DmgDef->GetString("default_surface_inanimate");
	}
	else
		g_Global.GetSurfName( tr->c.material, surfType );

	// scale the damage by owner's ability and surface type hit
	DmgScale *= m_Owner.GetEntity()->m_MeleeDamageMult;
	DmgScale *= DmgDef->GetFloat( va("damage_mult_%s",surfType.c_str()), "1.0" );

	// Damage
	// Check for reroute entity (can happen with attachments to AI)
	if( other->IsType(idAFEntity_Base::Type) )
	{
		idAFEntity_Base *otherAF = static_cast<idAFEntity_Base *>(other);
		int bodID = otherAF->BodyForClipModelId( tr->c.id );
		idAFBody* StruckBody = otherAF->GetAFPhysics()->GetBody( bodID );

		if( StruckBody != NULL )
		{
			idEntity* reroute = StruckBody->GetRerouteEnt();
			if (reroute != NULL) 
			{
				// joint and clipmodel id's become invalid if we reroute, but that's okay
				other = reroute;
			}
		}
	}

	idActor *otherAct = NULL;
	if( other->IsType(idActor::Type) )
	{
		otherAct = static_cast<idActor *>(other);
	}
	else if( other->IsType(idAFAttachment::Type) )
	{
		otherAct = (idActor *) static_cast<idAFAttachment *>(other)->GetBody();
	}
	// actor-specific stuff
	if( otherAct != NULL )
	{
		// update melee status
		CMeleeStatus *pOthMeleeStatus = &otherAct->m_MeleeStatus;
		pOthMeleeStatus->m_LastHitByType = m_MeleeType;

		// switch the default surface type to that for actors
		if ( type == SURFTYPE_NONE )
		{
			// use a default surface type if we are unable to detect one
			surfType = DmgDef->GetString("default_surface_actor");
		}
	}

	if ( other->fl.takedamage )
	{
		DM_LOG(LC_WEAPON,LT_DEBUG)LOGSTRING("MeleeWeapon: Applying damage at clipmodel id %d, joint handle %d\r", tr->c.id, location );
		// TODO: Damage scaling - on the weapon * melee proficiency on the actor
		other->Damage
		(
			this, m_Owner.GetEntity(), 
			dir, DamageDefName,
			DmgScale, location, tr 
		);
	}

	// apply a LARGE tactile alert to AI (this must be done AFTER damage, otherwise sneak attacks are broken)
	if( other->IsType(idAI::Type) )
	{
		idAI *otherAI = static_cast<idAI *>(other);
		otherAI->TactileAlert( GetOwner(), 100 );

		// being hit always causes flat-footedness
		if( otherAI->m_bCanBeFlatFooted )
		{
			otherAI->m_bFlatFooted = true;
			otherAI->m_FlatFootedTimer = gameLocal.time;
		}
	}

	// Moved impact_damage_effect to DmgDef instead of weapon ent spawnargs
	// DM_LOG(LC_WEAPON,LT_DEBUG)LOGSTRING("MeleeCollision: Applying impact damage FX\r");
	if ( DmgDef->GetBool( "impact_damage_effect" ) ) 
	{
		// ishtvan: Rewrote this to get rid of old D3 code
		// that played the sounds in AddDamageEffect for bleeders, that doesn't make sense
		if ( other->spawnArgs.GetBool( "bleed" ) ) 
		{
			// stuff that bleeds handle smoke and decal in AddDamageEffect
			other->AddDamageEffect( *tr, impulse, DmgDef->GetString( "classname" ) );
		}

		// Handle smoke (particles), and decals
		// NOTE: AddDamageEffect above will handle all wound particles and decals (smoke_wound_*, mtr_wound_*)
		// So we only have to worry armour and other non-wounding strikes here (smoke_strike_* and mtr_strike_*)

		// Uncomment for surface type debugging
		// DM_LOG(LC_WEAPON,LT_DEBUG)LOGSTRING("MeleeCollision: Surface hit was %s\r", tr->c.material->GetName() );
		// DM_LOG(LC_WEAPON,LT_DEBUG)LOGSTRING("MeleeCollision: Material type name was %s\r", surfType.c_str() );

		// start impact sound based on material type
		// DM_LOG(LC_WEAPON,LT_DEBUG)LOGSTRING("MeleeCollision: Playing hit sound\r");
		sndName = va( "snd_%s", surfType.c_str() );
		hitSound = DmgDef->GetString( sndName );

		if ( hitSound.IsEmpty() ) 
		{
			// snd_hit is the default sound
			sndName = "snd_hit";
			hitSound = DmgDef->GetString( sndName );
		}

		// project decal 
		// ishtvan: got rid of min time between decals, let it be up to anim
		// DM_LOG(LC_WEAPON,LT_DEBUG)LOGSTRING("MeleeCollision: Displaying decal\r");
		// TODO: Make this read the surface type like smoke_strike_* ?
		const char *decal;
		decal = DmgDef->GetString( "mtr_strike" );
		if ( decal && *decal ) 
		{
			gameLocal.ProjectDecal( tr->c.point, -tr->c.normal, 8.0f, true, 6.0, decal, 0.0f, other, true );
		}

		// DM_LOG(LC_WEAPON,LT_DEBUG)LOGSTRING("MeleeCollision: Launching smoke\r");
		// Strike particle FX (sparks.. blood is handled in AddDamageEffect)
		const char *smokeName = DmgDef->GetString( va("smoke_strike_%s", surfType.c_str()) );

		if ( m_ParticlesMade < cv_melee_max_particles.GetInteger() && 
				smokeName && *smokeName != '\0' )
		{
			const idDeclParticle *smoke = static_cast<const idDeclParticle *>( declManager->FindType( DECL_PARTICLE, smokeName ) );
			float chance = DmgDef->GetFloat( va("smoke_chance_%s", surfType.c_str()), "1.0" );
			if( gameLocal.random.RandomFloat() > chance )
				smoke = NULL;

			if( smoke )
			{
				gameLocal.smokeParticles->EmitSmoke
					( 
						smoke, gameLocal.time, 
						gameLocal.random.RandomFloat(), 
						tr->c.point, -tr->endAxis
					);
				m_ParticlesMade++;
			}
		}
	}

	// DM_LOG(LC_WEAPON,LT_DEBUG)LOGSTRING("MeleeCollision: Sound playback\r");
	if ( !hitSound.IsEmpty() ) 
	{
		const idSoundShader *snd = declManager->FindSound( hitSound.c_str() );
		StartSoundShader( snd, SND_CHANNEL_BODY2, 0, true, NULL );
			
		// Propagate the sound to AI, must find global sound first because it's on a different dict
		sndName.StripLeading("snd_");
		sndName = DmgDef->GetString( va("sprS_%s", sndName.c_str()) );
		if( !sndName.IsEmpty() )
		{
			// DM_LOG(LC_WEAPON,LT_DEBUG)LOGSTRING("MeleeCollision: Propagating AI sound %s\r", sndName.c_str());
			PropSoundDirect( sndName.c_str(), false, false, 0.0f, 0 ); // grayman #3355
		}
	}
	// DM_LOG(LC_WEAPON,LT_DEBUG)LOGSTRING("MeleeCollision: Done!\r");

	return;
}
Exemple #27
0
SEXP msbsvar_irf(SEXP gibbs, SEXP msbsvar, SEXP nsteps)
{
  int i, k, n, N2, h, m, p, n0max, ns=INTEGER(nsteps)[0];
  int *db, *dF, *dxi, *dQ, N210pct, pctct=0;
  SEXP bR, FR, xiR, QR, Ui, IRFlist, IRFtmp;

//   Rprintf("ns = %d\n",ns); 
  
  // Get b, F, xi, Q, SS, dims from gibbs object
  PROTECT(bR = VECTOR_ELT(gibbs,0)); db=getdims(bR);
//   Rprintf("b(%d,%d)\n",db[0],db[1]); 
  PROTECT(FR = VECTOR_ELT(gibbs,1)); dF=getdims(FR);
//   Rprintf("F(%d,%d)\n",dF[0],dF[1]); 
  PROTECT(xiR= VECTOR_ELT(gibbs,2)); dxi=getdims(xiR);
//   Rprintf("xi(%d,%d)\n",dxi[0],dxi[1]); 
  PROTECT(QR = VECTOR_ELT(gibbs,3)); dQ=getdims(QR); UNPROTECT(1); 
//   Rprintf("Q(%d,%d)\n",dQ[0],dQ[1]); 
  
//   Rprintf("Gibbs Objects and Dimensions Assigned\n"); 
  
  // Reconstruct constants
  N2=db[0]; h=(int)sqrt((double)dQ[1]); n0max=db[1]/h; m=dxi[1]/h; p=((dF[1]/(h*m))-1)/m;
  N210pct=N2/10; 

//   Rprintf("N2=%d\nh=%d\nm=%d\np=%d\nn0max=%d\n",N2,h,m,p,n0max); 

  // Get Ui from msbsvar
  PROTECT(Ui=VECTOR_ELT(msbsvar,7));
 
  Matrix bsample=R2Cmat(bR,N2,n0max*h);
  Matrix Fsample=R2Cmat(FR,N2,m*(m*p+1)*h); 
  Matrix xisample=R2Cmat(xiR,N2,m*h);

  ColumnVector bk(n0max), Fk(m*(m*p+1)), bvec(m*m*p); bk=0.0; Fk=0.0; bvec=0.0; 
  DiagonalMatrix xik(m), sqrtxik(m); xik=0.0; sqrtxik=0.0; 
  Matrix Q(h,h), A0(m,m), A0i(m,m), fmat(m,m*p+1), sqrtwish, impulse(N2,m*m*ns); 
  double *pFk; int IRFdims[]={N2,ns,m*m};   

  PROTECT(IRFlist=allocVector(VECSXP,h)); 
  // Loop over regimes 
  for(k=1;k<=h;k++){
    
//     Rprintf("\n==========\nRegime %d\n==========\n",k);
    pctct=0;
    // Compute impulse responses for every draw of regime k
    for(n=1;n<=N2;n++){
//        Rprintf("\nDraw %d:\n",n); 

      // Get values for draw 'n', regime 'k' 
      bk=bsample.SubMatrix(n,n,(k-1)*n0max+1,k*n0max).t();
//       Rprintf("--bk(%d): ",bk.Storage()); //printCVector(bk); 
      Fk=Fsample.SubMatrix(n,n,(k-1)*m*(m*p+1)+1,k*m*(m*p+1)).t(); pFk=Fk.Store(); 
//       Rprintf("--Fk(%d): ",Fk.Storage()); //printCVector(Fk); 

      for(i=1;i<=m;i++) xik(i)=sqrt(xisample(n,(k-1)*m+i)); 
//       Rprintf("--xik(%d)/sqrtxik(%d) defined\n",m,m); 

      // Compute A0/A0^-1/sqrtwish for regime k
      A0=b2a(bk,Ui); 
      //Rprintf("--A0(%d,%d):",m,m); //printMatrix(A0); 
      A0i=A0.i(); 
      //Rprintf("--A0^-1(%d,%d):",m,m); //printMatrix(A0i); 
      sqrtwish=(A0*xik).i(); 
      //Rprintf("--sqrtwish(%d,%d):",m,m); //printMatrix(sqrtwish); 

      // Compute beta vector 
      fmat.ReSize(m,m*p+1); fmat<<pFk; fmat=fmat.t(); 
      fmat=(fmat.Rows(1,m*p)*A0i).t(); bvec=fmat.AsColumn(); 
//       Rprintf("--fmat(%d,%d):",m,m*p+1); printMatrix(fmat); 
//       Rprintf("bvec_%d:", n); printCVector(bvec);
      
      // Compute IRF 
      impulse.Row(n)=irf_var_from_beta(sqrtwish.t(), bvec, ns).t(); 
      if (!(n%N210pct))
	Rprintf("Regime %d: Monte Carlo IRF %d percent complete (Iteration %d)\n",k,++pctct*10,n);
    }

    // Create and class Robj for impulses, load into IRFlist
    PROTECT(IRFtmp=C2R3D(impulse,IRFdims)); 
    setclass(IRFtmp,"mc.irf.BSVAR"); SET_VECTOR_ELT(IRFlist, k-1, IRFtmp); 
    UNPROTECT(1); 
  }
  UNPROTECT(5); 
  return IRFlist;
}
Exemple #28
0
bool RigidBody::collision_detect(RigidBody &body)
{
	Plane plane[6];
	vec3 point;

	// Bounding box planes
	plane[0] = vec4(0.0f, 1.0f, 0.0f, -0.5f); // up
	plane[1] = vec4(0.0f, -1.0f, 0.0f, 0.5f); // down
	plane[2] = vec4(1.0f, 0.0f, 0.0f, -0.5f); // right
	plane[3] = vec4(-1.0f, 0.0f, 0.0f, 0.5f); // left
	plane[4] = vec4(0.0f, 0.0f, 1.0f, -0.5f); // far
	plane[5] = vec4(0.0f, 0.0f, -1.0f, 0.5f); // near


	// Rotate and translate planes to world space
	for(int i = 0; i < 6; i++)
	{
		point = plane[i].normal * 0.5f;						// point on plane
		point = orientation * point + position;				// rotate point
		plane[i].normal = orientation * plane[i].normal;	// rotate normal
		plane[i].normal.normalize();
		plane[i].d = -(plane[i].normal * point);			// recalculate D
	}

	// Check if point of body is inside our bounding box
	for(int i = 0; i < 8; i++)
	{
		const float padding = 0.0125f;
		float depth = 1000.0f;
		int count = 0;
		int closest = 0;

		// oriented body point in world space
		point = body.orientation * body.aabb[i] + body.position;

		for(int j = 0; j < 6; j++)
		{
			float distance = plane[j].normal * point + plane[j].d;
			if ( distance < padding)
			{
				if (depth > abs32(distance))
				{
					depth = abs32(distance);
					closest = j;
				}
				count++;
			}
		}

		// We had a point inside all 6 planes
		if (count == 6)
		{
			// Too deep, divide time step
			if (depth > 0.125f)
				return true;

//			printf("body body impact\n");
			impulse(body, point, plane[closest]);
			position = old_position;
			orientation = old_orientation;
		}
	}
	return false;
}
Exemple #29
0
void Player::PlayerJump()
{

	impulse(sf::Vector2f(0, -500.0f));
	
}
Exemple #30
0
/** Handles the special case of two karts colliding with each other, which
 *  means that bombs must be passed on. If both karts have a bomb, they'll
 *  explode immediately. This function is called from physics::update() on the
 *  server and if no networking is used, and from race_state on the client to
 *  replay what happened on the server.
 *  \param kart_a First kart involved in the collision.
 *  \param contact_point_a Location of collision at first kart (in kart
 *         coordinates).
 *  \param kart_b Second kart involved in the collision.
 *  \param contact_point_b Location of collision at second kart (in kart
 *         coordinates).
 */
void Physics::KartKartCollision(AbstractKart *kart_a,
                                const Vec3 &contact_point_a,
                                AbstractKart *kart_b,
                                const Vec3 &contact_point_b)
{
    // Only one kart needs to handle the attachments, it will
    // fix the attachments for the other kart.
    kart_a->crashed(kart_b, /*handle_attachments*/true);
    kart_b->crashed(kart_a, /*handle_attachments*/false);

    AbstractKart *left_kart, *right_kart;

    // Determine which kart is pushed to the left, and which one to the
    // right. Ideally the sign of the X coordinate of the local conact point
    // could decide the direction (negative X --> was hit on left side, gets
    // push to right), but that can lead to both karts being pushed in the
    // same direction (front left of kart hits rear left).
    // So we just use a simple test (which does the right thing in ideal
    // crashes, but avoids pushing both karts in corner cases
    // - pun intended ;) ).
    if(contact_point_a.getX() < contact_point_b.getX())
    {
        left_kart  = kart_b;
        right_kart = kart_a;
    }
    else
    {
        left_kart  = kart_a;
        right_kart = kart_b;
    }

    // Add a scaling factor depending on the mass (avoid div by zero).
    // The value of f_right is applied to the right kart, and f_left
    // to the left kart. f_left = 1 / f_right
    float f_right =  right_kart->getKartProperties()->getMass() > 0
                     ? left_kart->getKartProperties()->getMass()
                       / right_kart->getKartProperties()->getMass()
                     : 1.5f;
    // Add a scaling factor depending on speed (avoid div by 0)
    f_right *= right_kart->getSpeed() > 0
               ? left_kart->getSpeed()
                  / right_kart->getSpeed()
               : 1.5f;
    // Cap f_right to [0.8,1.25], which results in f_left being
    // capped in the same interval
    if(f_right > 1.25f)
        f_right = 1.25f;
    else if(f_right< 0.8f)
        f_right = 0.8f;
    float f_left = 1/f_right;

    // Check if a kart is more 'actively' trying to push another kart
    // by checking its local sidewards velocity
    float vel_left  = left_kart->getVelocityLC().getX();
    float vel_right = right_kart->getVelocityLC().getX();

    // Use the difference in speed to determine which kart gets a
    // ramming bonus. Normally vel_right and vel_left will have
    // a different sign: right kart will be driving to the left,
    // and left kart to the right (both pushing at each other).
    // By using the sum we get the intended effect: if both karts
    // are pushing with the same speed, vel_diff is 0, if the right
    // kart is driving faster vel_diff will be < 0. If both velocities
    // have the same sign, one kart is trying to steer away from the
    // other, in which case it gets an even bigger push.
    float vel_diff = vel_right + vel_left;

    // More driving towards left --> left kart gets bigger impulse
    if(vel_diff<0)
    {
        // Avoid too large impulse for karts that are driving
        // slow (and division by zero)
        if(fabsf(vel_left)>2.0f)
            f_left *= 1.0f - vel_diff/fabsf(vel_left);
        if(f_left > 2.0f)
            f_left = 2.0f;
    }
    else
    {
        // Avoid too large impulse for karts that are driving
        // slow (and division by zero)
        if(fabsf(vel_right)>2.0f)
            f_right *= 1.0f + vel_diff/fabsf(vel_right);
        if(f_right > 2.0f)
            f_right = 2.0f;
    }

    // Increase the effect somewhat by squaring the factors
    f_left  = f_left  * f_left;
    f_right = f_right * f_right;

    // First push one kart to the left (if there is not already
    // an impulse happening - one collision might cause more
    // than one impulse otherwise)
    if(right_kart->getVehicle()->getCentralImpulseTime()<=0)
    {
        const KartProperties *kp = left_kart->getKartProperties();
        Vec3 impulse(kp->getCollisionImpulse()*f_right, 0, 0);
        impulse = right_kart->getTrans().getBasis() * impulse;
        right_kart->getVehicle()
                 ->setTimedCentralImpulse(kp->getCollisionImpulseTime(),
                                          impulse);
        right_kart ->getBody()->setAngularVelocity(btVector3(0,0,0));
    }

    // Then push the other kart to the right (if there is no
    // impulse happening atm).
    if(left_kart->getVehicle()->getCentralImpulseTime()<=0)
    {
        const KartProperties *kp = right_kart->getKartProperties();
        Vec3 impulse = Vec3(-kp->getCollisionImpulse()*f_left, 0, 0);
        impulse = left_kart->getTrans().getBasis() * impulse;
        left_kart->getVehicle()
                  ->setTimedCentralImpulse(kp->getCollisionImpulseTime(),
                                           impulse);
        left_kart->getBody()->setAngularVelocity(btVector3(0,0,0));
    }

}   // KartKartCollision