Example #1
0
    //
    // LookAtRH
    //
    bool Mat4::LookAtRH( const Vec3<float>& Eye, const Vec3<float>& At, const Vec3<float>& _Up )
    {
    #ifdef _DEBUG
        _Up.Assume();
    #endif

        Vec3<float> Dir = Eye - At; // RHS
        Dir.Normalize();
        Vec3<float> Side = CrossProduct( _Up, Dir );
	    Side.Normalize();
        Vec3<float> Up = CrossProduct( Dir, Side );

	    m[ 0 ][ 0 ] = Side.x;    
        m[ 1 ][ 0 ] = Side.y;    
        m[ 2 ][ 0 ] = Side.z;     
        m[ 3 ][ 0 ] = -DotProduct( Side, Eye );

	    m[ 0 ][ 1 ] = Up.x;    
        m[ 1 ][ 1 ] = Up.y;    
        m[ 2 ][ 1 ] = Up.z;     
        m[ 3 ][ 1 ] = -DotProduct( Up, Eye );

	    m[ 0 ][ 2 ] = Dir.x;  
        m[ 1 ][ 2 ] = Dir.y;   
        m[ 2 ][ 2 ] = Dir.z;    
        m[ 3 ][ 2 ] = -DotProduct( Dir, Eye );

	    m[ 0 ][ 3 ] = 0.0f;   
        m[ 1 ][ 3 ] = 0.0f;   
        m[ 2 ][ 3 ] = 0.0f;
        m[ 3 ][ 3 ] = 1.0f;

        return true;
    }
int TrackBallManipulator::hitSphere(int posX, int posY, Vec3 &intersect)
{
    Vec3 rayPoint;
    Vec3 rayDir;
    getSceneGraph()->getCamera()->get_project_ray(posX,posY,rayPoint,rayDir);
    rayDir.Normalize();
    Vec3 center = getSceneGraph()->getCamera()->center();
    Quat quat;
    quat.convertFromMatrix(getSceneGraph()->getCamera()->get_model_matrix());
    HomoMatrix4 inverseModelMatrix = quat.conjugate().convertToMatrix();
    Vec3 np = inverseModelMatrix * Vec3(0,0,1);
    Vec3 hitPlane;
    if(Vec3::getIntersectionRayToPlane(rayPoint,rayDir,center,np,hitPlane))
    {
        Vec3 v = hitPlane - center;
        Scalar len = v.length();
        bool isNearOne = true;
        v.Normalize();
        int k = len / this->getRadius();

        Scalar residual = len - this->getRadius() * k;
        Vec3 planePoint = hitPlane;
        if(k % 4== 0)
        {
            planePoint = center + v * residual;
        }
        else if(k % 4== 1)
        {
            planePoint = center + v * (this->getRadius() - residual);
            isNearOne = false;
        }
        else if(k % 4== 2)
        {
            planePoint = center - v * residual;
            isNearOne = false;
        }
        else
        {
            planePoint = center - v * (this->getRadius() - residual);
        }
        Vec3 dir = planePoint - rayPoint;
        dir.Normalize();
        if(getIntersectionToSphere(rayPoint,dir,intersect,isNearOne))
        {
            return k % 4;
        }
    }
    intersect = Vec3::getClosestPointFromPointToRay(center,rayPoint,rayDir);
    return -1;
}
    bool CCoherentViewListener::RaycastGeometry( const Vec3& origin, const Vec3& dir, float& outDist, int& outViewX, int& outViewY )
    {
        if ( !m_pView || !m_Geometry )
        {
            return false;
        }

        IEntity* pEntity = gEnv->pEntitySystem->FindEntityByName( m_EngineObjectName.c_str() );

        if ( pEntity )
        {
            const Matrix34& invWorldMatrix = pEntity->GetWorldTM().GetInverted();
            Vec3 originModelSpace = invWorldMatrix.TransformPoint( origin );
            Vec3 dirModelSpace = invWorldMatrix.TransformVector( dir );
            dirModelSpace.Normalize();

            float t, u, v;

            if ( m_Geometry->IntersectWithRay( originModelSpace, dirModelSpace, t, u, v ) )
            {
                outDist = t;
                outViewX = ( int )( m_pView->GetWidth() * u );
                outViewY = ( int )( m_pView->GetHeight() * v );
                return true;
            }
        }

        return false;
    }
Example #4
0
void gkAuxRenderer::AuxRenderSkeleton( const Vec3& from, const Vec3& to, ColorF& color /*= ColorF(1.0,1.0,1.0,1.0)*/, float radius /*= 0.05f*/, bool ignoreZ /*= false */ )
{
	Vec3 dir = to - from;
	Vec3 dirInPlane = Vec3::CreateProjection(Vec3(0,0,1), dir.GetNormalized());
	if (dirInPlane.IsEquivalent(Vec3(0,0,0)))
	{
		dirInPlane = Vec3::CreateProjection(Vec3(1,0,0), dir.GetNormalized());
	}

	float len = dir.GetLength();
	dirInPlane.Normalize();
	dirInPlane *= radius * len;

	Vec3 dirInPlane1 = dirInPlane.GetRotated(dir.GetNormalized(), DEG2RAD(120.0f));
	Vec3 dirInPlane2 = dirInPlane.GetRotated(dir.GetNormalized(), DEG2RAD(-120.0f));

	Vec3 jointPt = from + dir.GetNormalized() * len * 0.8f;

	AuxRender3DLine(from, jointPt + dirInPlane, color, true);
	AuxRender3DLine(from, jointPt + dirInPlane1, color, true);
	AuxRender3DLine(from, jointPt + dirInPlane2, color, true);

	AuxRender3DLine(to, jointPt + dirInPlane, ColorF(1,0,0,1), true);
	AuxRender3DLine(to, jointPt + dirInPlane1, ColorF(1,0,0,1), true);
	AuxRender3DLine(to, jointPt + dirInPlane2, ColorF(1,0,0,1), true);

	AuxRender3DLine(jointPt + dirInPlane, jointPt + dirInPlane2, ColorF(1,0,0,1), true);
	AuxRender3DLine(jointPt + dirInPlane1, jointPt + dirInPlane2, ColorF(1,0,0,1), true);
	AuxRender3DLine(jointPt + dirInPlane, jointPt + dirInPlane1, ColorF(1,0,0,1), true);



}
Example #5
0
float AiCarStandard::GetHorizontalDistanceAlongPatch(const Bezier & patch, Vec3 carposition)
{
	Vec3 leftside = (patch.GetPoint(0,0) + patch.GetPoint(3,0))*0.5;
	Vec3 rightside = (patch.GetPoint(0,3) + patch.GetPoint(3,3))*0.5;
	Vec3 patchwidthvector = rightside - leftside;
	return patchwidthvector.Normalize().dot(carposition-leftside);
}
//------------------------------------------------------------------------
void CTracer::Reset(const Vec3 &pos, const Vec3 &dest)
{
	m_pos.zero();
	m_dest.zero();
	m_startingPos=pos;
	m_age=0.0f;
	m_lifeTime=1.5f;
	m_tracerFlags &= ~kTracerFlag_scaleToDistance;
	m_startFadeOutTime = 0.0f;
	m_slideFrac = 0.f;

	if (IEntity *pEntity=gEnv->pEntitySystem->GetEntity(m_entityId))
	{
		pEntity->FreeSlot(TRACER_GEOM_SLOT);
		pEntity->FreeSlot(TRACER_FX_SLOT);

		Vec3 dir = dest - pos;
		dir.Normalize();

		Matrix34 tm;
		
		tm.SetIdentity();

		if(!dir.IsZero())
		{
			tm = Matrix33::CreateRotationVDir(dir);
		}
		
		tm.AddTranslation(pos);
		pEntity->SetWorldTM(tm);
	}
}
Example #7
0
//------------------------------------------------------------------
void CLam::AdjustLaserFPDirection(CItem* parent, Vec3 &dir, Vec3 &pos)
{
    pos = parent->GetSlotHelperPos(eIGS_FirstPerson,m_laserHelperFP.c_str(),true);
    Quat   lamRot = Quat(parent->GetSlotHelperRotation(eIGS_FirstPerson,m_laserHelperFP.c_str(),true));
    dir = -lamRot.GetColumn0();

    if(!m_lamparams.isLamRifle)
        dir = lamRot.GetColumn1();

    CActor *pActor = parent->GetOwnerActor();
    IMovementController * pMC = pActor ? pActor->GetMovementController() : NULL;
    if (pMC)
    {
        SMovementState info;
        pMC->GetMovementState(info);


        CWeapon* pWep = static_cast<CWeapon*>(parent->GetIWeapon());
        if(pWep && (pWep->IsReloading() || (!pActor->CanFire() && !pWep->IsZoomed())))
            return;

        if(dir.Dot(info.fireDirection)<0.985f)
            return;

        CCamera& camera = gEnv->pSystem->GetViewCamera();
        pos = camera.GetPosition();
        dir = camera.GetMatrix().GetColumn1();
        dir.Normalize();
    }
}
Example #8
0
void CDeflectorShield::ShootDeflectedEnergy(const CDeflectorShield::SDeflectedEnergy& energy)
{
	if (!m_pAmmoClass)
		return;
	CProjectile* pEnergyBlast = g_pGame->GetWeaponSystem()->SpawnAmmo(m_pAmmoClass, false);
	if (!pEnergyBlast)
		return;

	const Matrix34& worldTransform = GetEntity()->GetWorldTM();

	const float positionBias = 0.05f;

	const Vec3 worldReflectPos = worldTransform.TransformPoint(energy.m_localPosition);
	const Vec3 worldReflectDir = worldTransform.TransformVector(energy.m_localDirection);

	const Vec3 worldSpreadU = worldReflectDir.GetOrthogonal();
	const Vec3 worldSpreadV = worldReflectDir.Cross(worldSpreadU);

	const float spreadOffset = cry_random(0.0f, m_spread);
	
	const Vec3 position = worldReflectPos + worldReflectDir * positionBias;
	Vec3 direction = 
		worldReflectDir + 
		(worldSpreadU * cry_random(0.0f, m_spread)) + 
		(worldSpreadV * cry_random(0.0f, m_spread));
	direction.Normalize();

	CProjectile::SProjectileDesc projectileDesc(
		0, 0, 0, energy.m_damage, m_dropMinDistance, m_dropPerMeter, float(m_minDamage), m_hitTypeId,
		0, false);
	pEnergyBlast->SetParams(projectileDesc);
	pEnergyBlast->Launch(position, direction, Vec3(ZERO));
}
Vec3 BVaabb::GetSurfaceFrom(const Vec3& src, Vec3& normal)
{
	Vec3 dir = mCenter - src;
	dir.Normalize();
	Ray3 ray(src, dir);
	Ray3::IResult ret = ray.Intersects(mAABB, normal);
	return dir * ret.second;
}
Ang3 CVehicleSeatActionOrientateBoneToView::GetDesiredViewAngles(const Vec3& lookPos, const Vec3& aimPos) const
{
	Vec3 forwardDir = (aimPos - lookPos).GetNormalized();
	Vec3 upDir = Vec3(0.f, 0.f, 1.f);
	Vec3 sideDir = forwardDir.Cross(upDir);
	sideDir.Normalize();
	upDir = sideDir.Cross(forwardDir);
	upDir.Normalize();

	Matrix34 matrix;
	matrix.SetFromVectors(sideDir, forwardDir, upDir, Vec3(0.f, 0.f, 0.f));

	Ang3 lookAngles;
	lookAngles.SetAnglesXYZ(matrix);

	return lookAngles;
}
Example #11
0
Vec3<float>& Triangle::calculateNormal()
{
	Vec3<float> vec1 = corners[2] - corners[0];
	Vec3<float> vec2 = corners[1] - corners[0];
	Vec3<float> crossP = vec1.crossProduct(vec2);
	crossP.Normalize();
	return crossP;
}
Example #12
0
///=====================================================
/// Code from Squirrel Eiserloh
///=====================================================
Vec3 EngineAndrew::Mesh::ComputeTriangleNormal(const Vec3& ccwPosition0, const Vec3& ccwPosition1, const Vec3& ccwPosition2)
{
	Vec3 edge01 = ccwPosition1 - ccwPosition0;
	Vec3 edge12 = ccwPosition2 - ccwPosition1;
	Vec3 normal = CrossProduct(edge01, edge12);
	normal.Normalize();
	return normal;
}
bool LightMapGenerator::CastSpecularRay( Ray &vRayInOut, Vec3 &worldSpaceNormals )
{
	//calculate reflection ray	
	Vec3 Reflection = (worldSpaceNormals*2) - vRayInOut.m_Direction;
	Reflection.Normalize();
	//simple weight distribution
	int weight = rand()%100;
	//goes to 10,000
	float multiplier = 1.f - ((float)(weight*weight)/10000.f);//most of the time it will be near 1k so near (1-1) = 0

	//add fuzzy
	Reflection.x = Reflection.x*100 + multiplier*(float)(rand()%20) + multiplier*10.f;
	Reflection.y = Reflection.y*100 + multiplier*(float)(rand()%20) + multiplier*10.f;
	Reflection.z = Reflection.z*100 + multiplier*(float)(rand()%20) + multiplier*10.f;
	Reflection.Normalize();
	vRayInOut.m_Direction = Reflection;
	return true;
}
Example #14
0
Vec3 BVSphere::GetSurfaceFrom(const Vec3& src, Vec3& normal)
{
	Vec3 dir = mCenter - src;
	Real dist = dir.Normalize();
	normal = -dir;
	dist -= mRadius;
	dir *= dist;
	return dir;
}
Example #15
0
Vec3 Vec3::Random()
{
	Vec3 temp;
	temp.x = float(rand()%3001)-1500.0f;
	temp.y = float(rand()%3001)-1500.0f;
	temp.z = float(rand()%3001)-1500.0f;
	temp.Normalize();
	return temp;
}
Example #16
0
	//---------------------------------------------------------------------------
	void ConsumeInput(IInputInjectorPtr injector)
	{
		if (mOverridingCamera)
		{
			mOverridingCamera->ConsumeInput(injector);
			return;
		}

		if (!mCurrentCamera)
			return;
		auto target = mTarget.lock();
		if (!mProcessInput || !target)
			return;
		if (injector->IsValid(InputDevice::Mouse) && !injector->IsKeyDown(VK_CONTROL)){
			const Vec3 camPos = GetPosition();
			Vec3 toCam = camPos - target->GetPosition();
			const Real distToTarget = toCam.Normalize();
			long dx, dy;
			injector->GetDeltaXY(dx, dy);

			if (injector->IsLButtonDown())
			{
				Real mouseSens = injector->GetSensitivity();
				if (dx != 0)
				{
					mUserParams.dYaw = dx * mouseSens;
				}

				if (dy != 0)
				{
					mUserParams.dPitch = -dy * mouseSens;
				}

				injector->LockMousePos(true, this);
				injector->Invalidate(InputDevice::Mouse);
			}
			else
			{
				//pMouse->LockMousePos(false, this);
			}

			long wheel = injector->GetWheel();
			if (wheel)
			{
				injector->PopWheel();
				Real shift = 1.0f;
				if (injector->IsKeyDown(VK_SHIFT))
					shift = 0.1f;
				Real wheelSens = injector->GetWheelSensitivity();
				Real numLinesSens = wheelSens * (Real)injector->GetNumLinesWheelScroll();
				numLinesSens *= std::max((Real)1.0f, (Real)(mInternalParams.dist * 0.05f));
				mUserParams.dDist += -wheel * numLinesSens * shift;
				injector->Invalidate(InputDevice::Mouse);
			}
		}
	}
	void CollisionAvoidance::Update(SteeringOutput* output)
	{
		float shortestTime = FLT_MAX;

		//for now
		const float DIAMETER = 2.0f;

		Agent* firstTarget = nullptr;
		float  firstMinSeparation = 0;
		float  firstDistance = 0;
		Vec3   firstRelativePos;
		Vec3   firstRelativeVel;

		//used in for loop
		Vec3 relativePos;
		Vec3 relativeVel;
		float relativeSpeed   = 0.0f;
		float timeToCollision = 0.0f;
		float distance		  = 0.0f;
		float minSeparation   =	0.0f;									  

		AgentMap* map = TheAIManager::Instance() ->GetAgentMap();
		for(auto it = map ->begin(); it != map ->end(); ++it)
		{
			relativePos = it ->second ->GetPos() - m_parent ->GetPos();
			relativeVel = it ->second ->GetVel() - m_parent ->GetVel();
			relativeSpeed = relativeVel.Length();
			timeToCollision = DotProduct(firstRelativePos, relativeVel) / (relativeSpeed * relativeSpeed);

			distance = relativePos.Length();
			minSeparation = distance - relativeSpeed * shortestTime;

			if(minSeparation > DIAMETER) continue;

			if((timeToCollision > 0) && (timeToCollision < shortestTime))
			{
				shortestTime = timeToCollision;
				firstTarget = it ->second;
				firstMinSeparation = minSeparation;
				firstDistance = distance;
				firstRelativePos = relativePos;
				firstRelativeVel = relativeVel;
			}
		}

		if(!firstTarget) return;

		if((firstMinSeparation <= 0) || (distance < DIAMETER))
			relativePos = firstTarget ->GetPos() - m_parent ->GetPos();

		else
			relativePos = firstRelativePos + firstRelativeVel * shortestTime;

		relativePos.Normalize();
		output ->linear = relativePos * m_parent ->GetMaxAcc();
	}
Example #18
0
	//----------------------------------------------------------------------------
	void ProcessInputData()
	{
		if (mOverridingCamera){
			mOverridingCamera->ProcessInputData();
			return;
		}
		auto target = mTarget.lock();
		if (!mProcessInput || !mCurrentCamera || !target)
			return;
		if (mUserParams.Changed() || mPrevTargetPos != target->GetPosition())
		{
			mInternalParams.dist += mUserParams.dDist;
			mInternalParams.dist = std::max((Real)2.0f, (Real)mInternalParams.dist);
			if (mInternalParams.dist > 300.0)
				mInternalParams.dist = 300.0;

			mInternalParams.pitch += mUserParams.dPitch;
			if (mInternalParams.pitch > fb::HALF_PI - fb::Radian(5))
			{
				mInternalParams.pitch = fb::HALF_PI - fb::Radian(5);
			}
			else if (mInternalParams.pitch <  -fb::HALF_PI + fb::Radian(5))
			{
				mInternalParams.pitch = -fb::HALF_PI + fb::Radian(5);
			}

			mInternalParams.yaw += mUserParams.dYaw;
			if (mInternalParams.yaw > fb::TWO_PI)
			{
				mInternalParams.yaw -= fb::TWO_PI;
			}
			else if (mInternalParams.yaw < -fb::TWO_PI)
			{
				mInternalParams.yaw += fb::TWO_PI;
			}

			Vec3 defaultDir = -Vec3::UNIT_Y;
			Quat qPitch(mInternalParams.pitch, Vec3::UNIT_X);
			Quat qYaw(-mInternalParams.yaw, Vec3::UNIT_Z);
			Vec3 toCam = qPitch * defaultDir;
			toCam = qYaw * toCam;
			Vec3 forward = -toCam;
			Vec3 right = forward.Cross(Vec3::UNIT_Z);
			right.Normalize();
			Vec3 up = right.Cross(forward);
			forward = up.Cross(right);

			Mat33 rot(right.x, forward.x, up.x,
				right.y, forward.y, up.y,
				right.z, forward.z, up.z);
			Vec3 pos = target->GetPosition() + toCam * mInternalParams.dist;
			SetTransformation(pos, Quat(rot));
			mUserParams.Clear();
			mPrevTargetPos = target->GetPosition();
		}
	}
Vec3 GetVectorFromYRotation(float angleRadians)
{
	Vec3 lookAt;
	WrapPi(angleRadians);
	lookAt.x = cos(angleRadians);
	lookAt.y = 0;
	lookAt.z = sin(angleRadians);
	lookAt.Normalize();
	return lookAt;
}
Example #20
0
void BVSphere::Merge(const Vec3& pos)
{
	assert(0 && "don't use");
	Vec3 dir = mCenter - pos;
	Real distance = dir.Normalize();
	if (distance > mRadius)
	{
		mRadius = distance;
	}
}
Example #21
0
//------------------------------------------------------------------------
void CVehicleMountedWeapon::CorrectRipperEntityPosition(float timeStep)
{
	IVehicle *pVehicle = gEnv->pGame->GetIGameFramework()->GetIVehicleSystem()->GetVehicle(m_vehicleId);
	if(pVehicle)
	{
		const IEntity* pVehicleEnt = pVehicle->GetEntity();

		Vec3 posDiff(ZERO);
		IActor* pOwner = GetOwnerActor();
		if (pOwner && pOwner->IsPlayer())
		{
			CPlayer* pPlayer	 = static_cast<CPlayer*>(pOwner); 
			const Matrix34& wMat = pVehicleEnt->GetWorldTM(); 
			Vec3 vehiclePos		 = wMat.GetTranslation();
			Vec3 currWSpaceRipUserOffset = wMat.TransformPoint(m_localRipUserOffset);

			posDiff = currWSpaceRipUserOffset - m_previousWSpaceOffsetPosition;

			// Don't want to overwrite anyone else changes with an absolute 'set'
			pOwner->GetEntity()->SetPos(pOwner->GetEntity()->GetWorldPos() + posDiff); 

			m_previousWSpaceOffsetPosition = currWSpaceRipUserOffset;

			//Update view limit direction based on change in vehicle rotation
			if(pPlayer->IsClient())
			{
				SViewLimitParams &viewLimits = pPlayer->GetActorParams().viewLimits;
				if(viewLimits.GetViewLimitRangeH()) //Don't do this unless we are currently horizontally constrained
				{
					Quat vehicleRotation(wMat);
					Quat rotationChange = vehicleRotation * m_previousVehicleRotation.GetInverted();

					Vec3 viewLimitDir = rotationChange * viewLimits.GetViewLimitDir();
					viewLimitDir.z = 0.f;
					viewLimitDir.Normalize();

					viewLimits.SetViewLimit(viewLimitDir, 0.01f, 0.01f, 0.f, 0.f, SViewLimitParams::eVLS_Item);

					m_previousVehicleRotation = vehicleRotation;
				}

				//Reset the pitch/roll view angles over time
				Quat viewDirFinal = pPlayer->GetViewQuatFinal();
				Ang3 viewAngles(viewDirFinal);
				float xAdjustment = (float)__fsel(viewAngles.x, max(-viewAngles.x, -0.5f * timeStep), min(-viewAngles.x, 0.5f * timeStep));
				float yAdjustment = (float)__fsel(viewAngles.y, max(-viewAngles.y, -0.5f * timeStep), min(-viewAngles.y, 0.5f * timeStep));

				if(xAdjustment || yAdjustment)
				{
					pPlayer->AddViewAngles(Ang3(xAdjustment, yAdjustment, 0.f));
				}
			}
		}
	}
}
void CLocalPlayerComponent::StartFreeFallDeath()
{
	m_bIsInFreeFallDeath = true;

	Vec3 currentLook = m_rPlayer.GetEntity()->GetWorldTM().GetColumn1();

	currentLook.z = tan_tpl(DEG2RAD(g_pGameCVars->pl_freeFallDeath_cameraAngle));
	currentLook.Normalize();

	m_freeFallLookTarget = currentLook;
}
Example #23
0
Vec3 BVSphere::GetRandomPosInVolume(const Vec3* nearLocal) const
{
	Vec3 pos = Vec3(Random(0.f, mRadius), Random(0.f, mRadius), Random(0.f, mRadius));
	if (nearLocal)
	{
		pos = Lerp(pos, *nearLocal, Random(0.5f, 1.0f));
	}
	pos.Normalize();
	return mCenter + pos*mRadius;
	
}
Example #24
0
 RUNEMATH_API bool Intersect(const Sphere3<T> &s1, const Sphere3<T> &s2, Vec3<T> &point)
 {
     if (Intersect(s1, s2))
     {
         Vec3<T> dir = s1.pos - s2.pos;
         dir.Normalize();
         point = s2.pos + dir * s2.radius;
         return true;
     }
     return false;
 }
Example #25
0
//----------------------------------------------------------------------------
void BVSphere::Merge(const BoundingVolume* pBV)
{
	Vec3 dir = mCenter - pBV->GetCenter();
	Real distance = dir.Normalize();
	Vec3 myFar = mCenter + dir * mRadius;
	Vec3 otherFar = pBV->GetCenter() + dir * pBV->GetRadius();
	Real mydot = myFar.Dot(dir);
	Real otherdot = otherFar.Dot(dir);
	Vec3 mostFar0 = mydot > otherdot ? myFar : otherFar;

	dir = pBV->GetCenter() - mCenter;
	dir.Normalize();
	myFar = mCenter + dir * mRadius;
	otherFar = pBV->GetCenter() + dir * pBV->GetRadius();
	mydot = myFar.Dot(dir);
	otherdot = otherFar.Dot(dir);
	Vec3 mostFar1 = mydot > otherdot ? myFar : otherFar;

	mCenter = (mostFar0 + mostFar1) * .5f;
	mRadius = (mostFar0 - mostFar1).Length() * .5f;
}
Example #26
0
/*
=============
  TestIntersectWithSquare
  circle + square
=============
*/
bool CollisionElementCircle::TestIntersectWithSquare( CollisionElement &object, Vec3 *outSolver ) {
  bool thisPosXInSquare = this->position->x >= object._rect->leftTop.x && this->position->x <= object._rect->rightBottom.x;
  bool thisPosYInSquare = this->position->y >= object._rect->leftTop.y && this->position->y <= object._rect->rightBottom.y;
  if( thisPosXInSquare || thisPosYInSquare ) {  //круг выталкивается либо вертикально, либо горизонтально
    if( outSolver ) {
      float dy = this->position->y - object.position->y;
      float xDivY = ( fabs( dy ) < 0.01f ? 10.0f : fabs( ( this->position->x - object.position->x ) / dy ) );
      if( xDivY > 1.0f ) {  //горизонтально
        outSolver->Set(
          this->position->x < object.position->x ? object._rect->leftTop.x - this->_rect->rightBottom.x : object._rect->rightBottom.x - this->_rect->leftTop.x,
          0.0f, 0.0f );
      } else {  //вертикально
        outSolver->Set( 0.0f,
          this->position->y < object.position->y ? object._rect->leftTop.y - this->_rect->rightBottom.y : object._rect->rightBottom.y - this->_rect->leftTop.y,
          0.0f );
      }
    }
  } else {  //круг находится по диагонали от квадрата
    Vec3 point( Vec3Null );
    if( this->position->x < object.position->x ) {
      point.x = object._rect->leftTop.x;
    } else {
      point.x = object._rect->rightBottom.x;
    }
    if( this->position->y < object.position->y ) {
      point.y = object._rect->leftTop.y;
    } else {
      point.y = object._rect->rightBottom.y;
    }
    Vec3 dir = *this->position - point;
    float distance = this->diameter * 0.5f - dir.Length();
    if( distance < 0.0f ) {
      return false;
    } else {
      if( outSolver ) {
        dir.Normalize();
        dir *= distance;
        *outSolver = dir;
      }
    }
  }
  /*
  if( outSolver ) {
    outSolver->Set(
      Math::Fabs( max( this->_rect->leftTop.x, object._rect->leftTop.x ) - min( this->_rect->rightBottom.x, object._rect->rightBottom.x ) ),
      Math::Fabs( max( this->_rect->leftTop.y, object._rect->leftTop.y ) - min( this->_rect->rightBottom.y, object._rect->rightBottom.y ) ),
      0.0f
    );
  }
  */
  //__log.PrintInfo( Filelevel_DEBUG, "CollisionElementCircle::TestIntersectWithSquare => thisType[%d]", this->type );
  return true;
}//TestIntersectWithSquare
Example #27
0
///trim the patch's width in-place
void AiCarStandard::TrimPatch(Bezier & patch, float trimleft_front, float trimright_front, float trimleft_back, float trimright_back)
{
	Vec3 frontvector = (patch.GetPoint(0,3) - patch.GetPoint(0,0));
	Vec3 backvector = (patch.GetPoint(3,3) - patch.GetPoint(3,0));
	float frontwidth = frontvector.Magnitude();
	float backwidth = backvector.Magnitude();
	if (trimleft_front + trimright_front > frontwidth)
	{
		float scale = frontwidth/(trimleft_front + trimright_front);
		trimleft_front *= scale;
		trimright_front *= scale;
	}
	if (trimleft_back + trimright_back > backwidth)
	{
		float scale = backwidth/(trimleft_back + trimright_back);
		trimleft_back *= scale;
		trimright_back *= scale;
	}

	Vec3 newfl = patch.GetPoint(0,0);
	Vec3 newfr = patch.GetPoint(0,3);
	Vec3 newbl = patch.GetPoint(3,0);
	Vec3 newbr = patch.GetPoint(3,3);

	if (frontvector.Magnitude() > 0.001)
	{
		Vec3 trimdirection_front = frontvector.Normalize();
		newfl = patch.GetPoint(0,0) + trimdirection_front*trimleft_front;
		newfr = patch.GetPoint(0,3) - trimdirection_front*trimright_front;
	}

	if (backvector.Magnitude() > 0.001)
	{
		Vec3 trimdirection_back = backvector.Normalize();
		newbl = patch.GetPoint(3,0) + trimdirection_back*trimleft_back;
		newbr = patch.GetPoint(3,3) - trimdirection_back*trimright_back;
	}

	patch.SetFromCorners(newfl, newfr, newbl, newbr);
}
Example #28
0
// ************************************************************
// get hit result with a ray.
RTHitResult RTPlane::GetHitResult(RTRay *r) {
    /*
    Ray = r->vStart + t * r->vDir
     and
    vNormal dot (vOrigin - vPointOnPlane) = 0.

    So substitute the ray equation r(t) in for x and solve for t:

      vNormal dot (vOrigin - ray(t)) = 0
      vNormal dot (vOrigin - vStart - vDir*t) = 0
      vNormal dot (vOrigin - vStart) = (vNormal dot vDir) * t
      t = [ vNormal dot (vOrigin - vStart) ] / (vNormal dot vDir)
    */

    Vec3 vDirToOrigin = vPos.Sub(r->vStart);
    vDirToOrigin.Normalize();

    Vec3 vDirNormalized = r->vDir.GetNormalized();


    GLfloat numerator = vec3_dot(&vNormal, &vDirToOrigin);
    GLfloat denominator = vec3_dot(&vNormal, &vDirNormalized);

    GLfloat t = (GLfloat) (numerator / denominator);

    RTHitResult hr;
    hr.Clear();

    // if line wasn't parallel or directly on the plane,
    if(t >= 0) {
        // find point hit
        hr.vPointHit = r->PointAtTValue(t);

        // if point hit was at a reasonable distance
        if(vec3_distance(&r->vStart, &hr.vPointHit) > 30) {
            hr.bHit = false;
            return hr;

        } else {
            // return a hit result containing the point, normal, etc.
            hr.bHit = true;
            hr.t = t;
            hr.vNormalHit = vNormal;
            hr.matHit = mat;

        }

    }

    return hr;

}
Example #29
0
    //
    // OrthoNormalize
    //
    void Mat4::OrthoNormalize()
    {
        Vec3<float> v = m[ 0 ].ToVec3<float>();
        v.Normalize();
        
        m[ 0 ].x = v.x;
        m[ 0 ].y = v.y;
        m[ 0 ].z = v.z;
        
        v = CrossProduct( m[ 0 ], m[ 1 ] );
        v.Normalize();

        m[ 2 ].x = v.x;
        m[ 2 ].y = v.y;
        m[ 2 ].z = v.z;

        v = CrossProduct( m[ 2 ], m[ 0 ] );
        v.Normalize();

        m[ 1 ].x = v.x;
        m[ 1 ].y = v.y;
        m[ 1 ].z = v.z;
    }
	// Since the modelviewmatrix is updated in the update, and flowgraph is updated in the preupdate, we need this postupdate
	virtual void OnPostUpdate(float fDeltaTime)
	{
		int invMouseY = gEnv->pRenderer->GetHeight() - m_mouseY;

		Vec3 vPos0(0,0,0);
		gEnv->pRenderer->UnProjectFromScreen((float)m_mouseX, (float)invMouseY, 0, &vPos0.x, &vPos0.y, &vPos0.z);

		Vec3 vPos1(0,0,0);
		gEnv->pRenderer->UnProjectFromScreen((float)m_mouseX, (float)invMouseY, 1, &vPos1.x, &vPos1.y, &vPos1.z);

		Vec3 vDir = vPos1 - vPos0;
		vDir.Normalize();
		
		ray_hit hit;
		const unsigned int flags = rwi_stop_at_pierceable|rwi_colltype_any;

		IPhysicalEntity** pSkipEnts = NULL;
		int numSkipped = 0;

		int containerId = GetPortInt(&m_actInfo, EIP_EntitiesToIgnore);
		if(containerId != 0)
		{
			IFlowSystemContainerPtr container = gEnv->pFlowSystem->GetContainer(containerId);
			numSkipped = container->GetItemCount();
			pSkipEnts = new IPhysicalEntity*[numSkipped];
			for (int i = 0; i < numSkipped; i++)
			{
				EntityId id;
				container->GetItem(i).GetValueWithConversion(id);
				pSkipEnts[i] = gEnv->pEntitySystem->GetEntity(id)->GetPhysics();
			}
		}

		if (gEnv->pPhysicalWorld && gEnv->pPhysicalWorld->RayWorldIntersection(vPos0, vDir *  gEnv->p3DEngine->GetMaxViewDistance(), m_rayTypeFilter, flags, &hit, 1, pSkipEnts, numSkipped))
		{
			ActivateOutput(&m_actInfo, EOP_HitPos, hit.pt);
			ActivateOutput(&m_actInfo, EOP_HitNormal, hit.n);

			if(hit.pCollider)
			{
				if(IEntity *pEntity = gEnv->pEntitySystem->GetEntityFromPhysics(hit.pCollider))
				{
					ActivateOutput(&m_actInfo, EOP_EntityId, pEntity->GetId());
				}
			}
		}

		if(pSkipEnts)
			delete [] pSkipEnts;
	}