Пример #1
0
void NPCCharacter::_behaviorIdle()
{
	stop();
	//still want to point the character in the direction last traveled.
	Ogre::Vector3 vel = getVelocity();
	float speed = vel.length();
	Ogre::Vector3 src = _node->getOrientation() * Ogre::Vector3::NEGATIVE_UNIT_Z;
	src.y = 0;

	vel.y = 0;
	vel.normalise();
	_node->rotate(src.getRotationTo(vel));

	_isBhvFinished = true;

	//transition to idle animation
	_animHandler.blend("Idle",AnimationBlender::BlendWhileAnimating,.2f,true);
}
Пример #2
0
Ogre::Vector3 SteeringBehaviors::Pursuit(Character* evader)
{
	Ogre::Vector3 ToEvader = evader->GetSceneNode()->getPosition() - mCharacter->GetSceneNode()->getPosition();
	double RelativeHeading = mCharacter->GetHeading().dotProduct(evader->GetHeading());

	//if evader is in front and moving forward
	if((ToEvader.dotProduct(mCharacter->GetHeading())) > 0 && (RelativeHeading < -0.95))
		return Seek(evader->GetSceneNode()->getPosition());

	//not ahead so look forward
	double LookAheadTime = ToEvader.length() / (mCharacter->GetMaxSpeed() + evader->GetMaxSpeed());
	Ogre::Vector3 currentVelocity = evader->GetVelocity();
	Ogre::Real currentSpeed = currentVelocity.normalise();
	Ogre::Vector3 desiredVelocity =  Seek(evader->GetSceneNode()->getPosition() + evader->GetHeading() * currentSpeed * LookAheadTime);
	desiredVelocity.y = 0;
	return desiredVelocity;

}
Пример #3
0
MapCameraLightning::MapCameraLightning(Ogre::SceneManager& sceneManager)
: mSceneManager(sceneManager)
{
	mLight = sceneManager.createLight("MapFixedSunLight");
	mLight->setType(Ogre::Light::LT_DIRECTIONAL);

	mLight->setPosition(Ogre::Vector3(-500,300,-350));
	Ogre::Vector3 dir = -mLight->getPosition();
	dir.normalise();
	mLight->setDirection(dir);

	mLight->setDiffuseColour(Ogre::ColourValue(0.8, 0.8, 0.6)); //yellow
	//mSun->setSpecularColour(1, 1, 0.7); //yellow
	mLight->setCastShadows(false);
	mLight->setAttenuation(1000000, 1, 0, 0);

	mLight->setVisible(false);
}
Пример #4
0
void RoomSurface::init(Ogre::Vector3 normal, Ogre::Real x_size, Ogre::Real z_size,
                       CreateVisualActor create_visual_actor) {
  create_visual_actor_ = create_visual_actor == CREATE_VISUAL_ACTOR;

  init();

  normal.normalise();
  normal_ = normal;

  // ***Important***
  // The surface is constructed from a "flat" rectangle sitting in the xz-plane, hence
  // we define its size by the x- and z- sizes. Once the surface has been rotated to have the
  // passed-in normal the x_size and z_size will not actually correspond to the surfaces'
  // x and z dimensions in world space.
  StaticBox::set_size(Ogre::Vector3(x_size, kSurfaceThickness, z_size));

  // Rotate the box to correspond to the passed-in normal
  set_orientation(surfaceOrientationForNormal(normal));
}
Пример #5
0
void CharacterMovement::rotateTo( QVector3D directionLook )
{
	qDebug() << "[CharacterMovement::rotateTo]" << directionLook;
	Ogre::Vector3 newDirection = UtilFunctions::qVector3dToOgreVector3( directionLook ) - _node->getPosition();
	newDirection.y = 0;
	newDirection.normalise();
	// Check if it is necessary to rotate
//	Ogre::Vector3 auxDirection = UtilFunctions::qVector3dToOgreVector3( _direction );

//	auxDirection.normalise();

//	qDebug() << "[CharacterMovement::rotateTo]" << directionLook << newDirection.dotProduct( auxDirection );

//	if( newDirection.dotProduct( auxDirection ) != 1 )
	{
		_direction = UtilFunctions::ogreVector3ToQVector3d( newDirection );
		_rotationValue = -4.0f;	// TODO: find another was to stop the rotation (it wasn't stopping)
		_rotating = true;
	}
}
Пример #6
0
// ----------------------------------------------------------
void OgreTestWidget::OnInit()
{
	Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();

	mSceneMgr = Ogre::Root::getSingleton().createSceneManager(Ogre::ST_GENERIC,"principal");
	// create camera
	mCamera = mSceneMgr->createCamera("PlayerCam_EntityPanel" + mName);
	mCamera->setPosition(Ogre::Vector3(0, 0, -40));
	mCamera->lookAt(Ogre::Vector3(0,0,0));
	mCamera->setAutoAspectRatio(true);
	mCamera->setNearClipDistance(0.1);
	// create viewport
	mViewport = mRenderWindow->addViewport(mCamera);
	mViewport->setBackgroundColour(Ogre::ColourValue(0.1, 0.1, 0.1, 1));
	mCamera->setAspectRatio((mViewport->getActualWidth()) /
		(mViewport->getActualHeight()));

	mViewport->_updateDimensions();

	mSceneMgr->setAmbientLight(Ogre::ColourValue(0.1,0.1,0.1));

	Ogre::Light* luz = mSceneMgr->createLight("Light0");
	luz->setType(Ogre::Light::LT_SPOTLIGHT);
	luz->setPosition(0,100,-100);
	luz->setSpotlightRange(Ogre::Degree(10), Ogre::Degree(90));
	Ogre::Vector3 direccion = -luz->getPosition();
	direccion.normalise();
	luz->setDirection(direccion);
	luz->setDiffuseColour(1,1,1);
	luz->setSpecularColour(0.25, 0.25, 0.25);


	mFocusNodo = mSceneMgr->getRootSceneNode()->createChildSceneNode(Ogre::Vector3::ZERO);
	mFocusNodo->attachObject(mCamera);

	/*
	mNodoEscena = mSceneMgr->getRootSceneNode()->createChildSceneNode();
	Ogre::Entity* entity = mSceneMgr->createEntity("pelota1", "flechaShape.mesh");
	mNodoEscena->attachObject(entity);
	*/
}
Пример #7
0
/* Return vector for a normalized (radius 1.0) sphere */
Ogre::Vector3 Grid::projectToSphere(unsigned int x, unsigned int y)
{
	Ogre::Vector3 pos;
	float mSizeFloat, xFloat, yFloat, halfStep;

	mSizeFloat = static_cast<float>(gridSize);
	xFloat = static_cast<float>(x)/mSizeFloat;
	yFloat = static_cast<float>(y)/mSizeFloat;
	halfStep = 1.0f/(mSizeFloat*2.0f);

	// For convenience treat xy-heightmap as a xz-plane in sphere-coordinates
	pos.x = 1.0f-halfStep - xFloat*2.0f;
	pos.z = -1.0f+halfStep + yFloat*2.0f;
	pos.y = 1.0f;
	// Simple re-orientation
	pos = orientation*pos;
	// project heightMap to sphere
	pos.normalise();

	return pos;
}
void PhysicsRagDoll::_joinBones(PhysicsRagDoll::JointType type, RagBone* parent, RagBone* child, Ogre::Vector3 pos, Ogre::Vector3 pin, Ogre::Real limit1, Ogre::Real limit2, OgreNewt::World* world)
{
	pin.normalise();
	OgreNewt::Joint* joint = NULL;

	switch (type)
	{
	case PhysicsRagDoll::JT_BALLSOCKET:
		joint = new OgreNewt::BasicJoints::BallAndSocket(world, child->getBody(), parent->getBody(), pos);
		((OgreNewt::BasicJoints::BallAndSocket*)joint)->setLimits(pin, Ogre::Degree(limit1), Ogre::Degree(limit2));
		break;

	case PhysicsRagDoll::JT_HINGE:
		joint = new OgreNewt::BasicJoints::Hinge(world, child->getBody(), parent->getBody(), pos, pin);
		((OgreNewt::BasicJoints::Hinge*)joint)->setCallback(RagBone::_hingeCallback);
		joint->setUserData(Ogre::Any(child));
		child->setLimits(limit1, limit2);
		break;
	}

}
Пример #9
0
bool CollisionTools::collidesWithEntity(const Ogre::Vector3& fromPoint, const Ogre::Vector3& toPoint, const float collisionRadius, const float rayHeightLevel, const Ogre::uint32 queryMask)
{
	Ogre::Vector3 fromPointAdj(fromPoint.x, fromPoint.y + rayHeightLevel, fromPoint.z);
	Ogre::Vector3 toPointAdj(toPoint.x, toPoint.y + rayHeightLevel, toPoint.z);
	Ogre::Vector3 normal = toPointAdj - fromPointAdj;
	float distToDest = normal.normalise();

	Ogre::Vector3 myResult(0, 0, 0);
	Ogre::MovableObject* myObject = NULL;
	float distToColl = 0.0f;

	if (raycastFromPoint(fromPointAdj, normal, myResult, myObject, distToColl, queryMask))
	{
		distToColl -= collisionRadius;
		return (distToColl <= distToDest);
	}
	else
	{
		return false;
	}
}
Пример #10
0
//Moves the Character
Ogre::Vector3 PlayerCharacter::updateMovement(unsigned long timeSinceLastFrame, Vector3 inputMoveDir, Ogre::Radian* moveDirRotAngle)
{
	//static const float maxUpdateDelay = 0.1f;
	//Ogre::Vector3 moveVector  = Quaternion(*moveDirRotAngle, Vector3::UNIT_Y) * inputMoveDir;

	Ogre::Vector3 moveVector  = this->node->getOrientation() * inputMoveDir;
	moveVector.normalise();

	// Acceleration
	if( inputMoveDir.isZeroLength() )
	{
		curMoveSpeed -= 0.001f * timeSinceLastFrame;
		curMoveSpeed = (curMoveSpeed < 0.001f) ? 0.f : curMoveSpeed;
	}
	else
	{
		curMoveSpeed += 0.001f * timeSinceLastFrame;
		curMoveSpeed = (curMoveSpeed > maxMoveSpeed) ? maxMoveSpeed : curMoveSpeed;
	}

	// Standing or running?
	if( curMoveSpeed == 0.f )
	{
		this->animation->setNextAction("stop");

		return node->getPosition();
	}
	else
	{
		this->animation->setNextAction("run");
		
		Ogre::Vector3 newPos = node->getPosition() + moveVector * curMoveSpeed * (Ogre::Real)timeSinceLastFrame;
		this->node->setPosition(newPos);

		// Pass actual character speed on to animation system
		this->animation->setFlagValue( "character_speed", curMoveSpeed );

		return newPos;
	}
}
Пример #11
0
void SingleplayerGame::onHUDPhysicalSelect(Player* attacker, Player* target) {
    mAttackRunning = true;
    bool attackSuccessful = attacker->attemptPhysicalAttack();

    attacker->lookAt(target);
    AnimationCallback cb = [this, attacker, target, attackSuccessful](void)-> void{
        if (attackSuccessful) {
            attacker->lookAt(target);
            attacker->physicalAttack(*target);
            if (!target->isDead()) {
                time_t physicalStartTime = time(nullptr);
                ParticleEndCheckCallback endCheck = [physicalStartTime](void) -> bool {
                    return difftime(time(nullptr), physicalStartTime) >= 1;
                };
                ParticleCallback onEnd = [](void) -> void {};
                target->mParticleController->runParticleSystem(PT_Physical, endCheck, onEnd);
            }
        }
        else {
            attacker->missAttack(*target);
        }
        mAttackRunning = false;
        attacker->mAnimationController->runIdleAnimation();
    };

    attacker->mAnimationController->runAnimation(AnimationType::Physical, cb);
    if (attackSuccessful) {
        mSoundBank->play("physical_woosh_fx");
        mSoundBank->play("physical_impact_fx");
    }
    else {
        mSoundBank->play("physical_miss_fx");
    }
    Ogre::Vector3 camPos = (attacker->sceneNode->_getDerivedPosition() + Ogre::Vector3(0, 200, 0)) - (target->sceneNode->_getDerivedPosition() + Ogre::Vector3(0, 100, 0));
    camPos.normalise();
    camPos *= 300;
    camPos += (attacker->sceneNode->_getDerivedPosition() + Ogre::Vector3(0, 200, 0));
    mRenderer->mCamera->setPosition(camPos);
    mRenderer->mCamera->lookAt(target->sceneNode->_getDerivedPosition() + Ogre::Vector3(0, 100, 0));
}
Пример #12
0
void SlideCollisionResponse::Response(PhysObjDescriptor* object, CollisionModel3D *CollisionModel, bool ismodelowner)
{
	// при коллизии определяется треугольник и объект движется параллельно плоскости тругольника
	
	float t1[9], t2[9], p[3], *t;

	CollisionModel->getCollisionPoint(p,false);
	Ogre::Vector3 normal, IntersectionPoint(p[0],p[1],p[2]);

	CollisionModel->getCollidingTriangles(t1, t2, false);

	if (ismodelowner)
		t=t1;
	else
		t=t2;
	
	Ogre::Plane collidplane(Ogre::Vector3(t[0],t[1],t[2]), 
		Ogre::Vector3(t[3],t[4],t[5]),
		Ogre::Vector3(t[6],t[7],t[8]));

	Ogre::Vector3 proj = collidplane.projectVector(object->LinVelocity);
	proj.normalise();	
	Ogre::Vector3 Normal = collidplane.normal;

	Ogre::Vector3 linvel = object->LinVelocity;	

	Ogre::Vector3 throttle = object->Throttle;

	Ogre::Vector3 dir=proj+Normal/2;
	dir.normalise();    
    object->Object->SetForces(Ogre::Vector3::ZERO);

	object->VelocityVector = dir*(linvel.length()+1);
	object->LinVelocity = dir*(linvel.length()+1);

	object->Object->SetReplacingDirection(dir*(linvel.length()+1));

	object->Object->AddForce(IntersectionPoint, dir*(linvel.length()+1)*Owner->GetMass()/object->Object->GetMass());
}
Пример #13
0
bool CCameraController::mouseMoved( const OIS::MouseEvent &arg )
{
	Ogre::Vector3 vtPlayerPos = m_pBindObject->GetPosition();
	if( arg.state.buttonDown( OIS::MB_Right ) )
	{
		Rotate(arg.state.X.rel, arg.state.Y.rel);

		Ogre::Vector3 vtCamera = m_pCamera->getPosition();

		Ogre::Vector3 vtDir = vtCamera-vtPlayerPos;

		vtDir.normalise();
		vtDir.y = 0;
		m_pBindObject->SetDirection(vtDir);
	}

	if( arg.state.buttonDown( OIS::MB_Left ) )
	{
		Rotate(arg.state.X.rel, arg.state.Y.rel);
	}
	return true;
}
Пример #14
0
VOID CCameraController::Rotate( float x, float y )
{
	float angle = -x * 0.01f;
	float xt = m_vecUnitDir.x * cos(angle) + m_vecUnitDir.z * sin(angle);
	float zt = m_vecUnitDir.z * cos(angle) - m_vecUnitDir.x * sin(angle);
	m_vecUnitDir.x = xt;
	m_vecUnitDir.z = zt;


	//¼ÆËãXZÐýתÖá
	Ogre::Vector3 axis;
	axis.x = -m_vecUnitDir.z;
	axis.z = m_vecUnitDir.x;
	axis.y = 0;
	axis.normalise();

	//ÑØÖáÐýת
	{
		float angle = y * 0.01f;
		float x = 
			m_vecUnitDir.x * (axis.x * axis.x * (1 - cos(angle)) + cos(angle)) + 
			m_vecUnitDir.y * (axis.x * axis.y * (1 - cos(angle)) - axis.z * sin(angle)) +
			m_vecUnitDir.z * (axis.x * axis.z * (1 - cos(angle)) + axis.y * sin(angle));
		float y = 
			m_vecUnitDir.x * (axis.x * axis.y * (1 - cos(angle)) + axis.z * sin(angle)) + 
			m_vecUnitDir.y * (axis.y * axis.y * (1 - cos(angle)) + cos(angle)) + 
			m_vecUnitDir.z * (axis.y * axis.z * (1 - cos(angle)) - axis.x * sin(angle));
		float z = 
			m_vecUnitDir.x * (axis.x * axis.z * (1 - cos(angle)) - axis.y * sin(angle)) +
			m_vecUnitDir.y * (axis.y * axis.z * (1 - cos(angle)) + axis.x * sin(angle)) +
			m_vecUnitDir.z * (axis.z * axis.z * (1 - cos(angle)) + cos(angle));
		m_vecUnitDir.x = x;
		m_vecUnitDir.y = y;
		m_vecUnitDir.z = z;
	}

	m_bPositionUpate = TRUE;
	
}
Пример #15
0
bool DeferredLight::isCameraInsideLight(Ogre::Camera* camera)
{
	switch (mParentLight->getType())
	{
	case Ogre::Light::LT_DIRECTIONAL:
		return false;

	case Ogre::Light::LT_POINT:
		{
			Ogre::Real distanceFromLight = camera->getDerivedPosition().distance(mParentLight->getDerivedPosition());
			return distanceFromLight <= mRadius + camera->getNearClipDistance() + 0.1;
		}

	case Ogre::Light::LT_SPOTLIGHT:
		{
			Ogre::Vector3 lightPos = mParentLight->getDerivedPosition();
			Ogre::Vector3 lightDir = mParentLight->getDerivedDirection();
			Ogre::Radian attAngle = mParentLight->getSpotlightOuterAngle();
		
			//Extend the analytic cone's radius by the near clip range by moving its tip accordingly.
			//Some trigonometry needed here.
			Ogre::Vector3 clipRangeFix = -lightDir * (camera->getNearClipDistance() / Ogre::Math::Tan(attAngle/2));
			lightPos = lightPos + clipRangeFix;
    
			Ogre::Vector3 lightToCamDir = camera->getDerivedPosition() - lightPos;
			Ogre::Real distanceFromLight = lightToCamDir.normalise();

			Ogre::Real cosAngle = lightToCamDir.dotProduct(lightDir);
			Ogre::Radian angle = Ogre::Math::ACos(cosAngle);
			//Check whether we will see the cone from our current POV.
			return (distanceFromLight <= (mParentLight->getAttenuationRange() + clipRangeFix.length()))
				&& (angle <= attAngle);
		}

	default:
		//Please the compiler
		return false;
	}
}
Пример #16
0
void CameraMan::frameRendered(const Ogre::FrameEvent &evt)
{
    if (mStyle == CS_FREELOOK)
    {
        // build our acceleration vector based on keyboard input composite
        Ogre::Vector3 accel = Ogre::Vector3::ZERO;
        Ogre::Matrix3 axes = mCamera->getLocalAxes();
        if (mGoingForward) accel -= axes.GetColumn(2);
        if (mGoingBack) accel += axes.GetColumn(2);
        if (mGoingRight) accel += axes.GetColumn(0);
        if (mGoingLeft) accel -= axes.GetColumn(0);
        if (mGoingUp) accel += axes.GetColumn(1);
        if (mGoingDown) accel -= axes.GetColumn(1);

        // if accelerating, try to reach top speed in a certain time
        Ogre::Real topSpeed = mFastMove ? mTopSpeed * 20 : mTopSpeed;
        if (accel.squaredLength() != 0)
        {
            accel.normalise();
            mVelocity += accel * topSpeed * evt.timeSinceLastFrame * 10;
        }
        // if not accelerating, try to stop in a certain time
        else mVelocity -= mVelocity * evt.timeSinceLastFrame * 10;

        Ogre::Real tooSmall = std::numeric_limits<Ogre::Real>::epsilon();

        // keep camera velocity below top speed and above epsilon
        if (mVelocity.squaredLength() > topSpeed * topSpeed)
        {
            mVelocity.normalise();
            mVelocity *= topSpeed;
        }
        else if (mVelocity.squaredLength() < tooSmall * tooSmall)
            mVelocity = Ogre::Vector3::ZERO;

        if (mVelocity != Ogre::Vector3::ZERO) mCamera->translate(mVelocity * evt.timeSinceLastFrame);
    }
}
Пример #17
0
// Returns volume for the right ear.
// If the sound is directly to the right, that channel gets 254 of intensity.
// If the sound is directly in front of us, each channel gets 254/2 of intensity.
int SoundManager::calcPanning(Ogre::Camera* mCamera, Ogre::Vector3 soundPosition) {
    Ogre::Vector3 camDirection = mCamera->getOrientation() * Ogre::Vector3::NEGATIVE_UNIT_Z;
    Ogre::Vector3 soundDir = soundPosition - mCamera->getPosition();
    soundDir.normalise();
    // Retrieve the angle made between the sound position and the camera's direction,
    // which should be pointing forwards.
    Ogre::Quaternion q = camDirection.getRotationTo(soundDir);
    Ogre::Radian radians = q.getYaw();

    // anything left of the camera returns positive degrees
    float degrees = radians.valueDegrees();

    int leftIntensity;
    int rightIntensity;

    // from 0 to -179 it's the right ear.
    if(degrees <= 0) {
      //std::cout << "degrees " << degrees << std::endl;
      degrees *= -1;
      if(degrees > 90)
          degrees = 90 - (degrees - 90); // if 91, we subtract 1 and go back to 89
      // Intensity can never be 255 because then the effect cancels out.
      int intensity = (degrees / 90.0) * 254/2 + 254/2;
      //std::cout << "intensity " << intensity << std::endl;
      rightIntensity = intensity;
      leftIntensity = 255 - (rightIntensity);
    }
    // from 0 to 179 it's the left ear.
    else {
      if(degrees > 90)
          degrees = 90 - (degrees - 90); 
      int intensity = (degrees / 90) * 254/2 + 254/2;
      //std::cout << "intensity " << intensity << std::endl;
      leftIntensity = intensity;
      rightIntensity = 254 - (leftIntensity);
    }
    return rightIntensity;
}
Пример #18
0
void Jinx::update(const Ogre::Real time)
{
    if (mDead) {
        mTimeSinceDead += time;
        return;
    }
    if (mTarget) {
        mDestination = mTarget->getPosition();
    }
    Ogre::Vector3 direction = mDestination - mNode->getPosition();
    Ogre::Real distance = direction.normalise();

    Ogre::Vector3 move = direction * time * mSpeed;
    mNode->translate(move);

    if (distance < 1.0f) {
        if (mTarget) {
            mTarget->takeDamage(mPower);
        }
        mSystem->setEmitting(false);
        mDead = true;
    }
}
Пример #19
0
void AIRayPathFinderStrategy::GoTo(Vector3 point)
{
	Ogre::Vector3 Position = Parent->GetPosition();
	Ogre::Vector3 vr;
	//vr=Position-point;

	Parent->GetScenable()->GetOrientation();

	vr=Parent->GetScenable()->GetOrientation()*Ogre::Vector3::UNIT_Z;


	Vector3 AccelerationOn(Vector3::ZERO); // = Parent->GetAccelerationOn();
    	IPhysical *phys = Parent->GetPhysical();
    	assert(phys);

	
	vr.normalise();
	phys->SetForwardDirection(vr);		
	AccelerationOn.z=-1;
	//phys->SetVelocityVector(vr);
	
	phys->SetAcceleration(AccelerationOn);
}
Пример #20
0
void Application::handleAi() {

	// For now AI just mirrors the player's paddle
	Ogre::Vector3 pos = _thePaddle->getNode()->getPosition();
	Ogre::Quaternion qt = _thePaddle->getNode()->getOrientation();

	Ogre::Vector3 ballPos = _theBall->getNode()->getPosition();

	// The ball is on the opponent's side of the net
	_otherPaddle->movePaddle(_oisManager, height, width, (float)ballPos.x, (float)ballPos.z + 500);

	Ogre::Vector3 ballNormal = _theBall->getNode()->getPosition() - _otherPaddle->getNode()->getPosition();

	if(ballNormal.length() <= 200) {
		ballNormal.normalise();
		ballNormal += Ogre::Vector3(0,0,0.5);
		int power = 3000;

		btVector3 impulse = btVector3(ballNormal.x*power, ballNormal.y*power, ballNormal.z*power);
		btVector3 rel_pos = btVector3(0,0,0);
		_theBall->applyImpulse(impulse, rel_pos);
	}
}
void TutorialApplication::evilShot(ShipProject::GameObject* enemy, double speed) {
    Ogre::Entity* ball = mSceneMgr->createEntity("projectile");
	ball->setMaterialName("Projectile/Red");

	Ogre::SceneNode* node = mSceneMgr->getRootSceneNode()->createChildSceneNode();
	Ogre::Vector3 dir = player->entity()->getParentSceneNode()->getPosition() - enemy->entity()->getParentSceneNode()->getPosition();
	dir.normalise();
    Ogre::Quaternion orient = Ogre::Vector3::NEGATIVE_UNIT_Z.getRotationTo(dir);
    node->setPosition(enemy->entity()->getParentSceneNode()->getPosition() );
	node->setOrientation(orient);
	node->translate( orient * (Ogre::Vector3::UNIT_Z * -0.5) );
	node->attachObject(ball);

    ShipProject::GameObject* oBall = new ShipProject::GameObject(ball, 0.25);
    oBall->SetupCollision(new btSphereShape(PROJECTILE_RADIUS), CollisionGroup::PROJECTILES_BALLS, CollisionGroup::PLAYER | CollisionGroup::WALLS);
    objects_.push_back( oBall );

    // orientatation * (original model forward vector) = direction vector
    oBall->body()->setLinearVelocity( BtOgre::Convert::toBullet(node->getOrientation() * Ogre::Vector3::NEGATIVE_UNIT_Z * speed));
    oBall->body()->setRestitution(1.0);
    oBall->body()->activate(true);

    projectiles_[oBall->entity_name()] = Projectile(oBall, 3.0);
}
  Ogre::Vector3
  CharacterController::_collideWithWorld(int recursionDepth,
      const Ogre::Vector3& pos, const Ogre::Vector3& vel,
      CollisionPacket& colData, bool gravityStep,
      const Ogre::Degree& slopeSlideThresold)
  {
    // do we need to worry?
    if (recursionDepth > 5)
      return pos;

    // Ok, we need to worry:
    colData.velocity = vel;
    colData.normalizedVelocity = vel;
    colData.normalizedVelocity.normalise();
    colData.basePoint = pos;
    colData.foundCollision = false;

    // ----------------------------
    // OgreOpcode part begin
    _doOgreOpcodeCollision(colData, mVeryCloseDistance);
    // OgreOpcode part end
    // ----------------------------

    // If no collision we just move along the velocity
    if (colData.foundCollision == false)
      {
        return pos + vel;
      }

    // *** Collision occured ***
    // The original destination point
    Ogre::Vector3 destinationPoint = pos + vel;
    Ogre::Vector3 newBasePoint = pos;

    // only update if we are not already very close
    // and if so we only move very close to intersection..not
    // to the exact spot.
    if (colData.nearestDistance >= mVeryCloseDistance)
      {
        Ogre::Vector3 V = vel;
        V.normalise();
        V = V * (colData.nearestDistance - mVeryCloseDistance);
        newBasePoint = colData.basePoint + V;
        // Adjust polygon intersection point (so sliding
        // plane will be unaffected by the fact that we
        // move slightly less than collision tells us)
        V.normalise();
        colData.intersectionPoint -= mVeryCloseDistance * V;
      }

    // Determine the sliding plane
    Ogre::Vector3 slidePlaneOrigin = colData.intersectionPoint;
    Ogre::Vector3 slidePlaneNormal = newBasePoint - colData.intersectionPoint;
    slidePlaneNormal.normalise();
    Ogre::Plane slidingPlane(slidePlaneNormal, slidePlaneOrigin);

    Ogre::Vector3 newDestinationPoint = destinationPoint
        - slidingPlane.getDistance(destinationPoint) * slidePlaneNormal;

    // Generate the slide vector, which will become our new
    // velocity vector for the next iteration
    Ogre::Vector3 newVelocityVector = newDestinationPoint
        - colData.intersectionPoint;

    // Recurse:
    // dont recurse if the new velocity is very small
    if (newVelocityVector.length() < mVeryCloseDistance)
      {
        return newBasePoint;
      }

    // simulate "friction"
    if (gravityStep)
      {
        // apply gravity only if slope is steep enough
        const Ogre::Radian tolerance = Ogre::Radian(slopeSlideThresold);
        Ogre::Vector3 gravity = vel;
        gravity.normalise();
        if (slidePlaneNormal.directionEquals(-gravity, tolerance))
          {
            return newBasePoint;
          }
      }

    return _collideWithWorld(recursionDepth++, newBasePoint, newVelocityVector,
        colData, gravityStep, slopeSlideThresold);
  }
Пример #23
0
/// @brief  Loads the lighting system for the supplied arena.
/// @param  aid The ArenaID of the arena to load.
void SceneSetup::loadArenaLighting (ArenaID aid)
{
    Ogre::Degree sunRotation; // rotation horizontally (yaw) from +x axis
    Ogre::Degree sunPitch;      // rotation downwards (pitch) from horizontal
    float sunBrightness[4];   // RGBA
    float   sunSpecular[4];   // RGBA
    float   sunAmbience[4];   // RGBA
    std::string skyBoxMap;
    float sf; // scaling factor

    // Set lighting constants
    if (aid == COLOSSEUM_ARENA)
    {
        sunRotation = -170;
        sunPitch = 60;
        sunBrightness[0] = 233;
        sunBrightness[1] = 225;
        sunBrightness[2] = 201;
        sunBrightness[3] = 700;
        sunSpecular[0] = 233;
        sunSpecular[1] = 225;
        sunSpecular[2] = 201;
        sunSpecular[3] = 400;
        sunAmbience[0] = 241;
        sunAmbience[1] = 228;
        sunAmbience[2] = 190;
        sunAmbience[3] = 500;
        skyBoxMap = "arena1_skybox";
    }
    else if (aid == FOREST_ARENA)
    {
        sunRotation = 43;
        sunPitch = 45;
        sunBrightness[0] = 255;
        sunBrightness[1] = 232;
        sunBrightness[2] = 208;
        sunBrightness[3] = 650;
        sunSpecular[0] = 255;
        sunSpecular[1] = 232;
        sunSpecular[2] = 208;
        sunSpecular[3] = 300;
        sunAmbience[0] = 183;
        sunAmbience[1] = 201;
        sunAmbience[2] = 206;
        sunAmbience[3] = 400;
        skyBoxMap = "arena2_skybox";
    }
    else // Quarry
    {
        sunRotation = -55;
        sunPitch = 35;
        sunBrightness[0] = 255;
        sunBrightness[1] = 255;
        sunBrightness[2] = 249;
        sunBrightness[3] = 550;
        sunSpecular[0] = 255;
        sunSpecular[1] = 255;
        sunSpecular[2] = 255;
        sunSpecular[3] = 250;
        sunAmbience[0] = 172;
        sunAmbience[1] = 196;
        sunAmbience[2] = 204;
        sunAmbience[3] = 200;
        skyBoxMap = "arena3_skybox";
    }
    
    // Setup the lighting colours
    sf = (1.0f / 255.0f) * (sunAmbience[3] / 1000.0f);
    Ogre::ColourValue sunAmbienceColour   = Ogre::ColourValue(sunAmbience[0]   * sf, sunAmbience[1]   * sf, sunAmbience[2]   * sf);
    sf = (1.0f / 255.0f) * (sunBrightness[3] / 1000.0f);
    Ogre::ColourValue sunBrightnessColour = Ogre::ColourValue(sunBrightness[0] * sf, sunBrightness[1] * sf, sunBrightness[2] * sf);
    sf = (1.0f / 255.0f) * (sunSpecular[3] / 1000.0f);
    Ogre::ColourValue sunSpecularColour   = Ogre::ColourValue(sunSpecular[0]   * sf, sunSpecular[1]   * sf, sunSpecular[2]   * sf);

    // Calculate the sun direction (using rotation matrices).
    Ogre::Real cos_pitch = Ogre::Math::Cos(sunPitch);
    Ogre::Real sin_pitch = Ogre::Math::Sin(sunPitch);
    Ogre::Real cos_yaw   = Ogre::Math::Cos(sunRotation);
    Ogre::Real sin_yaw   = Ogre::Math::Sin(sunRotation);
    Ogre::Matrix3 Rz(cos_pitch, -sin_pitch,       0, 
                     sin_pitch,  cos_pitch,       0, 
                             0,          0,       1);
    Ogre::Matrix3 Ry(  cos_yaw,          0, sin_yaw, 
                             0,          1,       0, 
                      -sin_yaw,          0, cos_yaw);
    Ogre::Vector3 sunDirection = Ry * Rz * Ogre::Vector3(-1, 0, 0);
    sunDirection.normalise();
    
    // Set the ambient light.
    GameCore::mSceneMgr->setAmbientLight(sunAmbienceColour);
    
    // Add a directional light (for the sun).
    mWorldSun->setDiffuseColour(sunBrightnessColour);
    mWorldSun->setSpecularColour(sunSpecularColour);
    mWorldSun->setDirection(sunDirection);
    mWorldSun->setCastShadows(true);
    
    // Create the skybox
    GameCore::mSceneMgr->setSkyBox(true, skyBoxMap, 1000);
}
Пример #24
0
void TFDisplay::updateFrame(FrameInfo* frame)
{
  tf::Stamped<tf::Pose> pose( btTransform( btQuaternion( 0, 0, 0 ), btVector3( 0, 0, 0 ) ), ros::Time(), frame->name_ );

  if (tf_->canTransform(fixed_frame_, frame->name_, ros::Time()))
  {
    try
    {
      tf_->transformPose( fixed_frame_, pose, pose );
    }
    catch(tf::TransformException& e)
    {
      ROS_ERROR( "Error transforming frame '%s' to frame '%s'\n", frame->name_.c_str(), fixed_frame_.c_str() );
    }
  }

  frame->position_ = Ogre::Vector3( pose.getOrigin().x(), pose.getOrigin().y(), pose.getOrigin().z() );
  frame->robot_space_position_ = frame->position_;
  robotToOgre( frame->position_ );

  btQuaternion quat;
  pose.getBasis().getRotation( quat );
  frame->orientation_ = Ogre::Quaternion( quat.w(), quat.x(), quat.y(), quat.z() );
  frame->robot_space_orientation_ = frame->orientation_;
  robotToOgre( frame->orientation_ );

  frame->axes_->setPosition( frame->position_ );
  frame->axes_->setOrientation( frame->orientation_ );

  frame->name_node_->setPosition( frame->position_ );

  frame->position_property_->changed();
  frame->orientation_property_->changed();

  std::string old_parent = frame->parent_;
  frame->parent_.clear();
  bool has_parent = tf_->getParent( frame->name_, ros::Time(), frame->parent_ );
  if ( has_parent )
  {
    if ( !frame->tree_property_ || old_parent != frame->parent_ )
    {
      M_FrameInfo::iterator parent_it = frames_.find( frame->parent_ );

      if ( parent_it != frames_.end() )
      {
        FrameInfo* parent = parent_it->second;

        if ( parent->tree_property_ )
        {
          property_manager_->deleteProperty( frame->tree_property_ );
          frame->tree_property_ = property_manager_->createCategory( frame->name_, property_prefix_ + frame->name_ + "Tree", parent->tree_property_, this );
        }
      }
    }

    if ( show_arrows_ )
    {
      tf::Stamped<tf::Pose> parent_pose( btTransform( btQuaternion( 0, 0, 0 ), btVector3( 0, 0, 0 ) ), ros::Time(), frame->parent_ );

      if (tf_->canTransform(fixed_frame_, frame->parent_, ros::Time()))
      {
        try
        {
          tf_->transformPose( fixed_frame_, parent_pose, parent_pose );
        }
        catch(tf::TransformException& e)
        {
          ROS_ERROR( "Error transforming frame '%s' to frame '%s'\n", frame->parent_.c_str(), fixed_frame_.c_str() );
        }
      }

      Ogre::Vector3 parent_position = Ogre::Vector3( parent_pose.getOrigin().x(), parent_pose.getOrigin().y(), parent_pose.getOrigin().z() );
      robotToOgre( parent_position );

      Ogre::Vector3 direction = parent_position - frame->position_;
      float distance = direction.length();
      direction.normalise();

      Ogre::Quaternion orient = Ogre::Vector3::NEGATIVE_UNIT_Z.getRotationTo( direction );

      Ogre::Vector3 old_pos = frame->parent_arrow_->getPosition();

      // The set() operation on the arrow is rather expensive (has to clear/regenerate geometry), so
      // avoid doing it if possible
      bool distance_changed = abs(distance - frame->distance_to_parent_) > 0.0001f;
      if ( distance_changed )
      {
        frame->distance_to_parent_ = distance;
        float head_length = ( distance < 0.1 ) ? (0.1*distance) : 0.1;
        float shaft_length = distance - head_length;
        frame->parent_arrow_->set( shaft_length, 0.01, head_length, 0.08 );
        frame->parent_arrow_->setShaftColor( 0.8f, 0.8f, 0.3f, 1.0f );
        frame->parent_arrow_->setHeadColor( 1.0f, 0.1f, 0.6f, 1.0f );
        frame->parent_arrow_->setUserData( Ogre::Any( (void*)this ) );
      }

      if ( distance > 0.001f )
      {
        frame->parent_arrow_->getSceneNode()->setVisible( show_arrows_ );
      }
      else
      {
        frame->parent_arrow_->getSceneNode()->setVisible( false );
      }

      frame->parent_arrow_->setPosition( frame->position_ );
      frame->parent_arrow_->setOrientation( orient );
    }
    else
    {
      frame->parent_arrow_->getSceneNode()->setVisible( false );
    }
  }
  else
  {
    if ( !frame->tree_property_ || old_parent != frame->parent_ )
    {
      property_manager_->deleteProperty( frame->tree_property_ );
      frame->tree_property_ = property_manager_->createCategory( frame->name_, property_prefix_ + frame->name_ + "Tree", tree_category_, this );
    }

    frame->parent_arrow_->getSceneNode()->setVisible( false );
  }

  frame->parent_property_->changed();
}
void MumbleIntegration::update(Ogre::Vector3 cameraPos, Ogre::Vector3 cameraDir, Ogre::Vector3 cameraUp, Ogre::Vector3 avatarPos, Ogre::Vector3 avatarDir, Ogre::Vector3 avatarUp)
{
	if (! lm) return;

	if (lm->uiVersion != 2)
	{
		wcsncpy(lm->name, L"Rigs of Rods", 256);
		wcsncpy(lm->description, L"This plugin links Rigs of Rods with Mumble", 2048);
		lm->uiVersion = 2;
	}
	lm->uiTick++;

	// Left handed coordinate system ( http://wiki.mumble.info/index.php?title=Link#Coordinate_system )
	// X positive towards "right".
	// Y positive towards "up".
	// Z positive towards "front".
	//
	// 1 unit = 1 meter

	// OGRE uses right-handed coordinate system ( http://www.ogre3d.org/tikiwiki/tiki-index.php?page=Basic+Tutorial+1&structure=Tutorials )
	// X positive towards "right".
	// Y positive towards "up".
	// Z positive towards "back". => conversion necessary!
	//
	// 1 unit = 1 meter (in RoR)

	// We need unit vectors
	avatarDir.normalise();
	avatarUp.normalise();
	cameraDir.normalise();
	cameraUp.normalise();

	// Position of the avatar
	lm->fAvatarPosition[0] = avatarPos.x;
	lm->fAvatarPosition[1] = avatarPos.y;
	lm->fAvatarPosition[2] = -avatarPos.z;

	// Unit vector pointing out of the avatars eyes
	lm->fAvatarFront[0] = avatarDir.x;
	lm->fAvatarFront[1] = avatarDir.y;
	lm->fAvatarFront[2] = -avatarDir.z;

	// Unit vector pointing out of the top of the avatars head
	lm->fAvatarTop[0] = avatarUp.x;
	lm->fAvatarTop[1] = avatarUp.y;
	lm->fAvatarTop[2] = -avatarUp.z;

	// Same as avatar but for the camera.
	lm->fCameraPosition[0] = cameraPos.x;
	lm->fCameraPosition[1] = cameraPos.y;
	lm->fCameraPosition[2] = -cameraPos.z;

	lm->fCameraFront[0] = cameraDir.x;
	lm->fCameraFront[1] = cameraDir.y;
	lm->fCameraFront[2] = -cameraDir.z;

	lm->fCameraTop[0] = cameraUp.x;
	lm->fCameraTop[1] = cameraUp.y;
	lm->fCameraTop[2] = -cameraUp.z;

	// Identifier which uniquely identifies a certain player in a context (e.g. the ingame Name).
	std::string playername = SSETTING("Nickname", "Anonymous").c_str();
	std::wstring wplayername;
	wplayername.assign(playername.begin(), playername.end());
	wcsncpy(lm->identity, wplayername.c_str(), 256);

	// Context should be equal for players which should be able to hear each other _positional_ and
	// differ for those who shouldn't (e.g. it could contain the server+port and team)
	// This ensures that Mumble users in the same channel playing on different servers
	// don't hear each other positional since the positional information would be wrong

	// TODO: Right now we only create contexts based on server identification but
	// some servers allow players to play on different maps independently
	// so we should take that into account as well

	int teamID = 0; // RoR currently doesn't have any kind of team-based gameplay
	sprintf((char *)lm->context, "%s:%s|%d", SSETTING("Server name", "-").c_str(), SSETTING("Server port", "1337").c_str(), teamID);
	lm->context_len = (int)strnlen((char *)lm->context, 256);
}
Пример #26
0
	void Lightning::create()
	{
		remove();

		Ogre::Vector3 end = mOrigin + mDirection*mLength;
		Ogre::Vector3 current, last = mOrigin;

		// Create ray segments
		for(Ogre::uint32 k = 1; k < mDivisions+1; k++)
		{
			Ogre::Vector3 current = mOrigin + mDirection*mLength*(static_cast<Ogre::Real>(k)/mDivisions);

			current += (mLength/(mDivisions*3))*Ogre::Vector3(
				Ogre::Math::RangeRandom(-1, 1), Ogre::Math::RangeRandom(-1, 1), Ogre::Math::RangeRandom(-1, 1));

			mSegments.push_back(Segment(last, current));

			mRealLength += (current-last).length();

			last = current;
		}

		// Create the associated billboard set
		mBillboardSet = mSceneManager->createBillboardSet();
		mBillboardSet->setMaterialName("SkyX_Lightning");
		mBillboardSet->setBillboardType(Ogre::BBT_ORIENTED_SELF);

		Ogre::Real width = mWidthMultiplier*3*(static_cast<Ogre::Real>(mRecursivity)/4+1)*Ogre::Math::RangeRandom(0.5f, 2.5f-mRecursivity/3);

		// Create the associated billboard for each segment
		Ogre::Real delta;
		Ogre::Vector2 bounds;
		Ogre::Billboard* bb;
		for(Ogre::uint32 k = 0; k < mSegments.size(); k++)
		{
			delta = 1.0f / mSegments.size();
			bounds = Ogre::Vector2(k*delta,(k+1)*delta);

			bounds = Ogre::Vector2(mBounds.x, mBounds.x) + bounds*(mBounds.y-mBounds.x);

			bb = mBillboardSet->createBillboard((mSegments.at(k).a+mSegments.at(k).b)/2);
			bb->setDimensions(width, (mSegments.at(k).a-mSegments.at(k).b).length());
			bb->setColour(Ogre::ColourValue(0,bounds.x,bounds.y));
			bb->mDirection = (mSegments.at(k).a-mSegments.at(k).b).normalisedCopy();

			bb = mBillboardSet->createBillboard(mSegments.at(k).a + (mSegments.at(k).a-mSegments.at(k).b).normalisedCopy()*width/2);
			bb->setDimensions(width, width);
			bb->setColour(Ogre::ColourValue(1,bounds.x,bounds.x));
			bb->mDirection = (mSegments.at(k).a-mSegments.at(k).b).normalisedCopy();
			
			bb = mBillboardSet->createBillboard(mSegments.at(k).b - (mSegments.at(k).a-mSegments.at(k).b).normalisedCopy()*width/2);
			bb->setDimensions(width, width);
			bb->setColour(Ogre::ColourValue(1,bounds.y,bounds.y));
			bb->mDirection = -(mSegments.at(k).a-mSegments.at(k).b).normalisedCopy();
		
			width *= 1-(1.0f/(mRecursivity*mRecursivity))*(1.0f/mSegments.size());
		}

		mBillboardSet->_updateBounds();

		mSceneNode->attachObject(mBillboardSet);

		mBillboardSet->setCustomParameter(0, Ogre::Vector4(1,0,0,0));

		// Ramifications
		if (mRecursivity > 0)
		{
			Ogre::Real angle;
			Ogre::Vector3 dir;
			Ogre::Real lengthMult;
			for (Ogre::uint32 k = 0; k < mDivisions-1; k++)
			{
				angle = (mSegments.at(k).b-mSegments.at(k).a).normalisedCopy().dotProduct(
					((mSegments.at(k+1).b-mSegments.at(k+1).a).normalisedCopy()));

				if (angle < Ogre::Math::RangeRandom(mAngleRange.x, mAngleRange.y))
				{
					dir = (mSegments.at(k).b-mSegments.at(k).a).normalisedCopy();
					dir.x *= Ogre::Math::RangeRandom(0.8f, 1.2f);
					dir.y *= Ogre::Math::RangeRandom(0.8f, 1.2f);
					dir.z *= Ogre::Math::RangeRandom(0.8f, 1.2f);
					dir.normalise();

					delta = 1.0f / mSegments.size();
					bounds = Ogre::Vector2(mBounds.x+(mBounds.y-mBounds.x)*(k+1)*delta,1);

					lengthMult = Ogre::Math::RangeRandom(0.1f, 0.7f);

					Lightning* lightning = new Lightning(mSceneManager, mSceneNode, mSegments.at(k).b, dir, lengthMult*mLength, 2+mDivisions*lengthMult, mRecursivity-1, mTimeMultiplier, mWidthMultiplier, bounds);
					lightning->create();
					
					mChildren.push_back(lightning);
				}
			}
		}

		mCreated = true;
	}
Пример #27
0
BOOL CCameraController::UpdateCameraControl()
{
	if (m_bLocked)
	{
		return TRUE;
	}

	Vector3 vtNewPos = m_pBindObject->GetPosition();
	if((m_vtBindObjPos == vtNewPos)&&(!m_bPositionUpate)&&!m_bMoveCameraFar&&!m_bMoveCameraNear)
	{
		return TRUE;
	}

	if(m_bMoveCameraNear)
	{
		m_fDistance -= 0.05;
	}

	if(m_bMoveCameraFar)
	{
		m_fDistance += 0.05;
	}

	m_vtBindObjPos = vtNewPos;

	m_vecDstPos = m_vecUnitDir * m_fDistance + m_vtBindObjPos;

	

	Ogre::Vector3 RayDir = m_vecDstPos-vtNewPos;
	RayDir.normalise();

	Ogre::Ray SearchRay;
	SearchRay.setOrigin(vtNewPos);
	SearchRay.setDirection(RayDir);

	g_Debuginfo.PrintfInfo("m_vecDstPos x:%.2f-y:%.2f-z:%.2f!||", m_vecDstPos.x,m_vecDstPos.y,m_vecDstPos.z);

	
	Ogre::TerrainGroup::RayResult rayResult = CGameApp::GetGameApp()->m_World.m_pTerrainGroup->rayIntersects(SearchRay);
	if(rayResult.hit)
	{
		if((rayResult.position-vtNewPos).length()<m_fDistance)
		{
			m_vecDstPos = rayResult.position;
			m_vecDstPos .y += 1;
			g_Debuginfo.PrintfInfo("hit -- rayResult x:%.2f--y:%.2f--z:%.2f!\n", rayResult.position.x,rayResult.position.y,rayResult.position.z);
		}
		else
		{
			g_Debuginfo.PrintfInfo("hit --rayResult x:1--y:1--z:1!\n");
		}
		
	}
	else
	{
		g_Debuginfo.PrintfInfo("unhit --rayResult x:0--y:0--z:0!\n");
	}

	m_pCamera->lookAt(vtNewPos+Vector3(0,1.5,0));

	m_pCamera->setPosition(m_vecDstPos);

	m_bPositionUpate = FALSE;

	return TRUE;
}
Пример #28
0
//michael wander code
//code taken and adapted from http://gamedevelopment.tutsplus.com/tutorials/understanding-steering-behaviors-wander--gamedev-1624
//written by Michael Kong
void Tank::wander(const float& deltaTime){
	float circleDistance = 200.f;
	Ogre::Vector3 circleCenter;
	float radius = 20.f;

	std::random_device rd;
	std::mt19937 random(rd());

	Ogre::Quaternion tankOrientation = mTankBodyNode->getOrientation();
	Ogre::Vector3 currentDirection = tankOrientation * Ogre::Vector3::NEGATIVE_UNIT_X; 
	currentDirection.normalise();
	circleCenter = currentDirection * circleDistance;

	Ogre::Vector3 displacement = Ogre::Vector3::UNIT_Z * radius;

	float length = displacement.length();
	displacement.x = cos(wanderAngle) * length;
   	displacement.z = sin(wanderAngle) * length;
	displacement.y = 13;

   	std::uniform_real_distribution<double> randomGen;

   	wanderAngle += randomGen(random) * ANGLE_CHANGE - ANGLE_CHANGE * 0.5f;

   	Ogre::Vector3 steering = circleCenter + displacement;
	steering.normalise();
	steering *= ms;
	
	circleCenter.y = 13.f;

	mTankBodyNode->lookAt(displacement, Ogre::Node::TransformSpace::TS_WORLD);

	mTankBodyNode->translate(steering * deltaTime);

	/*
	Ogre::Vector3 rayDest;

	rayDest = mTankBodyNode->getOrientation() * Ogre::Vector3(1,0,0);

	bool check = false;
	

			Ogre::Ray shootToCheckWall = Ogre::Ray(mTankBodyNode->getPosition(), rayDest);

			Ogre::RaySceneQuery* mRaySceneQuery = mSceneMgr->createRayQuery(shootToCheckWall, Ogre::SceneManager::ENTITY_TYPE_MASK);
			mRaySceneQuery->setSortByDistance(true);

			// Ray-cast and get first hit
			Ogre::RaySceneQueryResult &result = mRaySceneQuery->execute();
			Ogre::RaySceneQueryResult::iterator itr = result.begin();

			bool hit = false;
			for (itr = result.begin(); itr != result.end(); itr++) 
			{
					
				std::string x = itr->movable->getName();
				printf("Check %s \n", x.c_str());

				if (x[0] == 'C' && itr->distance < 10)
				{
					printf("Too close to %s: %f \n", x.c_str(), (float)itr->distance);
					hit = true;
				}
			}

			if(hit == true)
			{
				mTankBodyNode->yaw(Ogre::Degree(180));
				mTankBodyNode->translate((mTankBodyNode->getPosition() * Ogre::Vector3(-1,0,0)) * deltaTime );
			}
			else if (hit == false)
			{
				
				check = true;
			}
	
	
	*/

			


}
Пример #29
0
void AIInConeAttackStrategy::Step(unsigned timeMs)
{        
    IScenable *scen = Parent->GetScenable();
	
	if (TargetID<0)
	{		
		return;
	}
	if (TargetID==0)
	{
		if (Owner)
		{
			TargetID = Owner->SelectTargetID();			
		}
		if (TargetID<=0)
		{
			TargetID=-1;
			IEquipped *eq = Parent->GetEquipped();
			eq->SetTargetPosition(Ogre::Vector3::ZERO);
			eq->SetShooting(false);
			return;
		}
	}
		
	IAAObject *obj = CommonDeclarations::GetIDObject(TargetID);
	if (NULL==obj)
	{		
		TargetID=0;
		return;
	}
		
	IScenable* Target;	
	Target = obj->GetScenable();
	if (NULL==Target/* || phys->IsCollided()*/)
		return;
	
	if(RotationUnit.mRotating)
	{
		RotationUnit.Step();
		if(RotationUnit.mRotating)                                // Process timed rotation
		{				
			Ogre::Quaternion delta = RotationUnit.Slerp();	
			scen->SetOrientation(delta);
		}
	}// else
	{	
		int actual_rotation_speed = RotationSpeed;
		IPhysical *phys = Parent->GetPhysical();
        AICommander *commander = Owner->GetCommander();
        Ogre::Vector3 src = Ogre::Vector3::ZERO;
        if (commander)
        {
            IAAObject *obj = commander->GetParent();
            if (obj)
            {
                IScenable *scen = obj->GetScenable();
                if (scen)
                {
                    src = scen->GetOrientation()*Ogre::Vector3::NEGATIVE_UNIT_Z;
                }
            }
        } else
        {
            src = -phys->GetForwardDirection(); //OurOrientation * Ogre::Vector3::NEGATIVE_UNIT_Z;
        }
		
		Ogre::Vector3 direction = Target->GetPosition()-scen->GetPosition();
        direction.normalise();

        Ogre::Real cs = src.dotProduct(direction);
        if (src.isZeroLength() || cs>=AngleCosinusModule)
        {
			actual_rotation_speed = actual_rotation_speed/2;
			/*char log[100];
			sprintf(log,"in cone %f %f %f\n",direction.x, direction.y, direction.z);
			Debugging::Log("icas",log);*/			
        } else
		{			
			direction = src;
			/*char log[100];
			sprintf(log,"not in cone %f %f %f\n",direction.x, direction.y, direction.z);
			Debugging::Log("icas",log);*/
		}

        Ogre::Vector3 up =CommonDeclarations::GetUpVector();

		Ogre::Quaternion OurOrientation = scen->GetOrientation();
		Vector3 xVec = up.crossProduct(direction);
		xVec.normalise();
		Vector3 yVec = direction.crossProduct(xVec);
		yVec.normalise();
		Quaternion unitZToTarget = Quaternion(xVec, yVec, direction);

		Quaternion targetOrientation = Quaternion(-unitZToTarget.y, -unitZToTarget.z, unitZToTarget.w, unitZToTarget.x);

		RotationUnit.StartRotation(OurOrientation, targetOrientation, actual_rotation_speed);
	}

	std::pair<bool, Ogre::Real> intersection_res;
		
	IEquipped *eq = Parent->GetEquipped();
	Ogre::Ray pl_ray = eq->GetSightRay();

	intersection_res = pl_ray.intersects(Target->GetBoundingBox(true));
	if (intersection_res.first)
	{
        eq->SetTargetPosition(Target->GetPosition(), intersection_res.second);
		eq->SetShooting(true);
	} else
    {
        eq->SetTargetPosition(Ogre::Vector3::ZERO);
        eq->SetShooting(false);
    }
		
}
Пример #30
0
bit GameVisualScene::init( Game* game )
{
	game->visualSystem.lockThread();

	game->visualSystem.loadResources("InGame");
	Ogre::Viewport* vp = game->visualSystem.getPrimaryRenderWindow()->getViewport(0);
	Ogre::CompositorManager* compositorMgr = Ogre::CompositorManager::getSingletonPtr();
	Ogre::CompositorInstance* compositor = compositorMgr->addCompositor(vp,"LuminanceBloom");
	compositorMgr->setCompositorEnabled(vp,"LuminanceBloom",true);

	VisualScene::init(game);

	Ogre::Light* light = game->visualSystem.getSceneMgr()->createLight("MainLight");
	light->setType(Ogre::Light::LT_DIRECTIONAL);
	light->setPosition(800,900,-550);
	Ogre::Vector3 dir = -light->getPosition();
	dir.normalise();
	light->setDirection(dir);
	light->setSpecularColour(1.0f,1.0f,1.0f);
	light->setDiffuseColour(0.8f,0.8f,0.8f);
	//light->setSpotlightRange(Ogre::Degree(50), Ogre::Degree(75));
	light->setPowerScale(1.0f);
	light->setCastShadows(true);	

	//Ogre::LiSPSMShadowCameraSetup* cameraSetup = new Ogre::LiSPSMShadowCameraSetup;
	//game->visualSystem.getSceneMgr()->setShadowCameraSetup(Ogre::ShadowCameraSetupPtr(cameraSetup));

	game->visualSystem.getSceneMgr()->getRootSceneNode()->attachObject(light);

	game->visualSystem.getSceneMgr()->setAmbientLight(Ogre::ColourValue(0.1,0.90,0.75));
	//game->visualSystem.getSceneMgr()->setShadowTechnique(Ogre::SHADOWTYPE_TEXTURE_ADDITIVE);
	game->visualSystem.getSceneMgr()->setShadowTextureSize(1024);
	//game->visualSystem.getSceneMgr()->setShadowTextureSettings(1024,2);
	game->visualSystem.getSceneMgr()->setShadowFarDistance(24);
	game->visualSystem.getSceneMgr()->setShadowDirLightTextureOffset(0.05);
	game->visualSystem.getSceneMgr()->setShadowTextureSelfShadow(false);
	game->visualSystem.getSceneMgr()->setShadowColour( Ogre::ColourValue(0.75f, 0.75f, 0.75f) );
	game->visualSystem.getSceneMgr()->setSkyBox(true,"skybox",1000);	
	game->visualSystem.getSceneMgr()->setShadowTextureCasterMaterial("depthShadowMapCasterMaterial");
	//game->visualSystem.getSceneMgr()->setShadowTextureCasterMaterial("VarianceShadowMapping/ShadowCaster");
	game->visualSystem.getSceneMgr()->setShadowTexturePixelFormat(PF_FLOAT32_R);
	game->visualSystem.getSceneMgr()->setShadowCasterRenderBackFaces(true);
	game->visualSystem.getSceneMgr()->setShadowTechnique(SHADOWTYPE_TEXTURE_ADDITIVE_INTEGRATED);
	
	Bridge* bridge = new Bridge(game);
	bridge->init("bridge");

	RoadBarrier* barrier[20];

	for(u32 i=0 ; i<20 ; i++)
	{		
		barrier[i] = new RoadBarrier(game);
		barrier[i]->init("barrier"+IntToStr(i));		
	}
	hkQuaternion q;
	q.setAxisAngle(hkVector4(0,1,0),Deg2Rad(90));
	barrier[0]->getPhysicsEntity()->setPositionAndRotation(hkVector4(-5.5,0.51f,-50.0),q);
	barrier[1]->getPhysicsEntity()->setPositionAndRotation(hkVector4(4.5,0.51f,-40.0),q);
	barrier[2]->getPhysicsEntity()->setPositionAndRotation(hkVector4(-5.5,0.51f,-30.0),q);
	barrier[3]->getPhysicsEntity()->setPositionAndRotation(hkVector4(1.5,0.51f,-20.0),q);
	barrier[4]->getPhysicsEntity()->setPositionAndRotation(hkVector4(-5.5,0.51f,-10.0),q);
	barrier[5]->getPhysicsEntity()->setPositionAndRotation(hkVector4(2.5,0.51f,-70.0),q);
	barrier[6]->getPhysicsEntity()->setPositionAndRotation(hkVector4(-5.5,0.51f,-90.0),q);
	barrier[7]->getPhysicsEntity()->setPositionAndRotation(hkVector4(0.5,0.51f,100.0),q);
	barrier[8]->getPhysicsEntity()->setPositionAndRotation(hkVector4(-5.5,0.51f,110.0),q);
	barrier[9]->getPhysicsEntity()->setPositionAndRotation(hkVector4(5.5,0.51f,40.0),q);
	barrier[10]->getPhysicsEntity()->setPositionAndRotation(hkVector4(1.5,0.51f,50.0),q);
	barrier[11]->getPhysicsEntity()->setPositionAndRotation(hkVector4(-5.5,0.51f,60.0),q);
	barrier[12]->getPhysicsEntity()->setPositionAndRotation(hkVector4(5.5,0.51f,70.0),q);
	barrier[13]->getPhysicsEntity()->setPositionAndRotation(hkVector4(-5.5,0.51f,80.0),q);
	barrier[14]->getPhysicsEntity()->setPositionAndRotation(hkVector4(3.5,0.51f,90.0),q);
	barrier[15]->getPhysicsEntity()->setPositionAndRotation(hkVector4(-5.5,0.51f,100.0),q);
	barrier[16]->getPhysicsEntity()->setPositionAndRotation(hkVector4(-2.5,0.51f,110.0),q);
	barrier[17]->getPhysicsEntity()->setPositionAndRotation(hkVector4(-0.5,0.51f,120.0),q);
	barrier[18]->getPhysicsEntity()->setPositionAndRotation(hkVector4(2.5,0.51f,130.0),q);
	barrier[19]->getPhysicsEntity()->setPositionAndRotation(hkVector4(5.5,0.51f,140.0),q);

	Crate* crate[32];
	for(u32 i=0 ; i<32 ; i++)
	{
		crate[i] = new Crate(game);
		crate[i]->init("crate"+IntToStr(i));		
	}
	crate[0]->getPhysicsEntity()->setPosition(hkVector4(-1.25,0.0f,20.75));
	crate[1]->getPhysicsEntity()->setPosition(hkVector4(-2   ,0.0f,20.75));
	crate[2]->getPhysicsEntity()->setPosition(hkVector4(-2,0.0f,20.75));
	crate[3]->getPhysicsEntity()->setPosition(hkVector4(-1,25,0.0f,20.0));
	crate[4]->getPhysicsEntity()->setPosition(hkVector4(-2   ,0.0f,20.0));
	crate[5]->getPhysicsEntity()->setPosition(hkVector4(-2.75,0.0f,20.0));
	crate[6]->getPhysicsEntity()->setPosition(hkVector4(-1,25,0.0f,20.75));
	crate[7]->getPhysicsEntity()->setPosition(hkVector4(-2   ,0.0f,20.75));
	crate[8]->getPhysicsEntity()->setPosition(hkVector4(-2.75,0.0f,20.75));

	crate[9]->getPhysicsEntity()->setPosition(hkVector4(-1.25,0.5f,20.75));
	crate[10]->getPhysicsEntity()->setPosition(hkVector4(-2   ,0.5f,20.75));
	crate[11]->getPhysicsEntity()->setPosition(hkVector4(-2.75,0.5f,20.75));
	crate[12]->getPhysicsEntity()->setPosition(hkVector4(-1,25,0.5f,20.0));
	crate[13]->getPhysicsEntity()->setPosition(hkVector4(-2   ,0.5f,20.0));
	crate[14]->getPhysicsEntity()->setPosition(hkVector4(-2.75,0.5f,20.0));
	crate[15]->getPhysicsEntity()->setPosition(hkVector4(-1,25,0.5f,20.750));
	crate[16]->getPhysicsEntity()->setPosition(hkVector4(-2   ,0.5f,20.750));
	crate[17]->getPhysicsEntity()->setPosition(hkVector4(-2.75,0.5f,20.750));

	crate[18]->getPhysicsEntity()->setPosition(hkVector4(-1.25,1.0f,20.75));
	crate[19]->getPhysicsEntity()->setPosition(hkVector4(-2   ,1.0f,20.75));
	crate[20]->getPhysicsEntity()->setPosition(hkVector4(-2.75,1.0f,20.75));
	crate[21]->getPhysicsEntity()->setPosition(hkVector4(-1,25,1.0f,20.0));
	crate[22]->getPhysicsEntity()->setPosition(hkVector4(-2   ,1.0f,20.0));
	crate[23]->getPhysicsEntity()->setPosition(hkVector4(-2.75,1.0f,20.0));
	crate[24]->getPhysicsEntity()->setPosition(hkVector4(-1,25,1.0f,20.75));
	crate[25]->getPhysicsEntity()->setPosition(hkVector4(-2   ,1.0f,20.75));
	crate[26]->getPhysicsEntity()->setPosition(hkVector4(-2.75,1.0f,20.75));

	crate[27]->getPhysicsEntity()->setPosition(hkVector4(-1.25,1.5f,-20.75));
	crate[28]->getPhysicsEntity()->setPosition(hkVector4(-20   ,1.5f,-20.75));
	crate[29]->getPhysicsEntity()->setPosition(hkVector4(-2.75,1.5f,-20.75));
	crate[30]->getPhysicsEntity()->setPosition(hkVector4(-1,25,1.5f,-20.0));
	crate[31]->getPhysicsEntity()->setPosition(hkVector4(-2   ,1.5f,-20.0));


	//RoadBarrier* barrier = new RoadBarrier(game);
	//barrier->init("barrier");
	//barrier->getPhysicsEntity()->setPosition(hkVector4(-5.5,0.25f,0.0f));

	Ogre::OverlayManager* overlayManager = Ogre::OverlayManager::getSingletonPtr();
	Ogre::Overlay* overlay = overlayManager->getByName("debugText");
	overlay->show();
	debugTextOverlay  = (Ogre::TextAreaOverlayElement*)overlayManager->getOverlayElement("debugTextArea");
	debugTextOverlay->show();

	updateCamera();

	game->visualSystem.unlockThread();

	return true;
}