void PhysicsSystem::addObject (const Ptr& ptr)
 {
     std::string mesh = MWWorld::Class::get(ptr).getModel(ptr);
     Ogre::SceneNode* node = ptr.getRefData().getBaseNode();
     handleToMesh[node->getName()] = mesh;
     OEngine::Physic::RigidBody* body = mEngine->createAndAdjustRigidBody(mesh, node->getName(), node->getScale().x, node->getPosition(), node->getOrientation());
     mEngine->addRigidBody(body);
 }
Beispiel #2
0
Monster* MonsterFactory::createInstance(SceneManager* sceneMgr, Maze* maze, MonsterManager* monsterMgr)
{
	Ogre::SceneNode* monsterNode = sceneMgr->getRootSceneNode()->createChildSceneNode();
	Ogre::Entity* entity = sceneMgr->createEntity(mParams["mesh"]);
	//entity->setCastShadows(true);
	monsterNode->attachObject(entity);
	Monster* mon;
	mon = new Monster(monsterNode, entity, maze, monsterMgr);
	if (mParams.find("radius") != mParams.end())
		mon->setRadius((float)atof(mParams["radius"].c_str()));

	if (mParams.find("blood") != mParams.end())
	{
		mon->setBlood((float)atof(mParams["blood"].c_str()));
		mon->setMaxBlood(mon->getBlood());
	}

	if (mParams.find("speed") != mParams.end())
		mon->setSpeed((float)atof(mParams["speed"].c_str()));

	if (mParams.find("spell") != mParams.end())
		mon->setType((mParams["spell"].c_str()));

	if (mParams.find("scale") != mParams.end())
	{
		float scale = (float)atof(mParams["scale"].c_str());
		mon->setScale(scale, scale, scale);
	}

	//mon->setScale(2, 2, 2);

	// 创建怪物头顶血条
	BillboardSet* healthHUD = sceneMgr->createBillboardSet();
	healthHUD->setMaterialName("Glass/Billboard");
	healthHUD->setDefaultWidth(100);
	healthHUD->setDefaultHeight(14);
	SceneNode* hudNode = monsterNode->createChildSceneNode();
	hudNode->attachObject(healthHUD);
	/*Billboard* b2 = healthHUD->createBillboard(0, entity->getBoundingBox().getSize().y, 0);
	b2->setColour(ColourValue::Black);*/
	Billboard* b = healthHUD->createBillboard(0, entity->getBoundingBox().getSize().y, 0);
	//b->setColour(ColourValue(0, 0.75f, 0));
	//b->setDimensions(96, 12);
	mon->setHealthHUD(healthHUD);

	// 测试粒子by kid
    Ogre::ParticleSystem* ps = sceneMgr->createParticleSystem(monsterNode->getName() + "frozen", "Glass/MonsterFrozen");
	monsterNode->attachObject(ps);
	ps->setVisible(false);
    ps = sceneMgr->createParticleSystem(monsterNode->getName() + "burn", "Glass/MonsterBurn");
	monsterNode->attachObject(ps);
	ps->setVisible(false);

	return mon;
}
 void PhysicsSystem::addActor (const Ptr& ptr)
 {
     std::string mesh = MWWorld::Class::get(ptr).getModel(ptr);
     Ogre::SceneNode* node = ptr.getRefData().getBaseNode();
     //TODO:optimize this. Searching the std::map isn't very efficient i think.
     mEngine->addCharacter(node->getName(), mesh, node->getPosition(), node->getScale().x, node->getOrientation());
 }
	//---------------------------------------------------------------------
	bool BillboardSetElement::_createBillboardSet(void)
	{
		Ogre::SceneNode* parent = mBasicNode;

		if (parent)
		{
			mBillboardSet = mSystem->getSceneManager()->createBillboardSet( parent->getName() );
			mBillboardSet->setMaterialName(mBillboardMaterial);

            if ( (mStacks > 1) || (mSlices > 1) )
                mBillboardSet->setTextureStacksAndSlices(mStacks, mSlices);

            mBillboardSet->setCastShadows(false);

            mBillboardSet->setVisible(mVisible);

			parent->attachObject(mBillboardSet);

			for ( int i=0; i<mBillboardCount; ++i )
			{
				Ogre::Billboard *billboard = mBillboardSet->createBillboard(0, i*mBillboardInterval, 0, mBillboardColour * mAlphaValue);
				assert (billboard);
				billboard->setDimensions(mBillboardWidth, mBillboardHeight);
			}

            _resetBillboardStartTexIndex();
            _resetBillboardStartScaleTime();

			return true;
		}

		return false;
	}
void CFakeObjectEntityManager::_DestroyFakeNode(FakeObject& obj)
{
	//销毁摄像机
	CEngineInterface::GetMe()->GetFairySystem()->getSceneManager()->destroyCamera(obj.pCamera);

	//销毁ViewPort
	if(!obj.ptrRenderTexture.isNull() && obj.ptrRenderTexture->getBuffer()->getRenderTarget())
	{
		obj.ptrRenderTexture->getBuffer()->getRenderTarget()->removeAllViewports();
	}

	//销毁RenderTexture
	obj.ptrRenderTexture.setNull();
	Ogre::TextureManager::getSingleton().remove(
		Ogre::String(obj.strName) + "_RenderTexture");

	//销毁Rectangle2D
	if (obj.pRectange)
	{
		Ogre::SceneNode* parentNode = obj.pRectange->getParentSceneNode();

		if (parentNode)
		{
			parentNode->detachObject(obj.pRectange);

			// 摧毁Rectangle2D所挂接的scene node
			if (parentNode->getParentSceneNode())
				parentNode->getParentSceneNode()->removeAndDestroyChild(parentNode->getName());
		}

		delete obj.pRectange;
		obj.pRectange = NULL;
	}
}
Beispiel #6
0
    void Scene::unloadCell (CellStoreCollection::iterator iter)
    {
        std::cout << "Unloading cell\n";
        ListHandles functor;

        (*iter)->forEach<ListHandles>(functor);
        {
            // silence annoying g++ warning
            for (std::vector<Ogre::SceneNode*>::const_iterator iter2 (functor.mHandles.begin());
                iter2!=functor.mHandles.end(); ++iter2){
                 Ogre::SceneNode* node = *iter2;
                mPhysics->removeObject (node->getName());
            }

            if ((*iter)->mCell->isExterior())
            {
                ESM::Land* land =
                    MWBase::Environment::get().getWorld()->getStore().get<ESM::Land>().search(
                        (*iter)->mCell->getGridX(),
                        (*iter)->mCell->getGridY()
                    );
                if (land)
                    mPhysics->removeHeightField( (*iter)->mCell->getGridX(), (*iter)->mCell->getGridY() );
            }
        }

        mRendering.removeCell(*iter);
       //mPhysics->removeObject("Unnamed_43");

        MWBase::Environment::get().getWorld()->getLocalScripts().clearCell (*iter);
        MWBase::Environment::get().getMechanicsManager()->drop (*iter);
        MWBase::Environment::get().getSoundManager()->stopSound (*iter);
        mActiveCells.erase(*iter);
    }
Beispiel #7
0
void Actor::attachActor(Actor* obj)
{
	Ogre::SceneNode* target = obj->getNode();
	gameLog("Actor::attachActor " + target->getName() + " to " + mNode->getName());
	target->getParent()->removeChild(target);
	mNode->addChild(target);
}
Beispiel #8
0
    void Scene::unloadCell (CellStoreCollection::iterator iter)
    {
        std::cout << "Unloading cell\n";
        ListHandles functor;






        (*iter)->forEach<ListHandles>(functor);

        {


            // silence annoying g++ warning
            for (std::vector<Ogre::SceneNode*>::const_iterator iter (functor.mHandles.begin());
                iter!=functor.mHandles.end(); ++iter){
                 Ogre::SceneNode* node = *iter;
                mPhysics->removeObject (node->getName());
            }
        }
		mRendering.removeCell(*iter);
		//mPhysics->removeObject("Unnamed_43");

        mWorld->getLocalScripts().clearCell (*iter);
        mEnvironment.mMechanicsManager->dropActors (*iter);
        mEnvironment.mSoundManager->stopSound (*iter);
		mActiveCells.erase(*iter);
        
        
    }
Beispiel #9
0
void Replicator::update(float value)
{
	//logFile << getFrequentcyRange() << " :\t " << value << "\n";
	Ogre::Vector3 currentScale = getScale();
	this->setThreshold(0.7*this->getThreshold() + 0.4*value);

	float result = value / this->getThreshold();
	int numOfChildrenToGenerate = result > 1.0 ? (result - value) * 2 : 0;
	//logFile  << value / this->getThreashold() << "\t" << (result - value) * 10 << "\t" << numOfChildrenToGenerate << "\n";
	for ( int i = 0; i < numOfChildrenToGenerate; i++ ) {
		createChildren(numOfChildrenToGenerate);
	}

	for(std::vector<Ogre::Entity*>::size_type i = 0; i < children.size(); ) {
		Ogre::SceneNode* childNode = children[i]->getParentSceneNode();
		Ogre::Real res = childNode->getScale().length();
		if ( res < 0.1 ) {
			children[i]->setVisible(false);
			childNode->setVisible(false);
			childNode->detachObject(children[i]->getName());
			_sceneManager->destroyEntity(children[i]->getName());
			// entity is now destroyed, don't try to use the pointer anymore!
			// optionally destroy node
			_sceneManager->destroySceneNode(childNode->getName());
			 children.erase( children.begin() + i );
		} else {
			Ogre::Vector3 currScale = childNode->getScale();
			childNode->setScale(Ogre::Vector3(currScale.x - currScale.x/3, currScale.y - currScale.y/3, currScale.z - currScale.z/3));
			i++;
		}
	}
}
// add a control point
Ogre::String CTrack::mAdd( ControlPoint tCP )
{
	Ogre::Entity *ent;
	char name[16];
	sprintf(name, "ControlPoint%d", mCount++);
	ent = mSm->createEntity(name, "point.mesh");
	ent->setQueryFlags(ObjectControl::CONTROL_POINT);

	Ogre::SceneNode *mCurrentObject = mSm->getRootSceneNode()->createChildSceneNode(std::string(name) + "Node", tCP.pos);
	mCurrentObject->attachObject(ent);
	mCurrentObject->setScale(0.05f, 0.05f, 0.05f);

	tCP.name = mCurrentObject->getName();

	CPs.push_back(tCP);

	return mCurrentObject->getName();
}
Beispiel #11
0
     void PhysicsSystem::insertObjectPhysics(const MWWorld::Ptr& ptr, const std::string model){

           Ogre::SceneNode* node = ptr.getRefData().getBaseNode();

           // unused
		   //Ogre::Vector3 objPos = node->getPosition();

         addObject (node->getName(), model, node->getOrientation(),
            node->getScale().x, node->getPosition());
     }
Beispiel #12
0
    void PhysicsSystem::scaleObject (const Ptr& ptr)
    {
        Ogre::SceneNode* node = ptr.getRefData().getBaseNode();
        std::string handle = node->getName();
        if(handleToMesh.find(handle) != handleToMesh.end())
        {
            removeObject(handle);
            addObject(ptr);
        }

        if (OEngine::Physic::PhysicActor* act = mEngine->getCharacter(handle))
            act->setScale(node->getScale().x);
    }
Beispiel #13
0
//-----------------------------------------------------------------------
void ActorObject::createActor(void)
{
    assert(!mActor);
    assert(mProxy && !mActorName.empty());

    Ogre::SceneNode* parent = getSceneNode();
    assert(parent);
    Ogre::SceneManager* creator = parent->getCreator();
    assert(creator);

    mActor = new Actor(mSystem, parent->getName(), mActorName, parent);
    mActor->setUserObject(mProxy);
}
bool TutorialApplication::mousePressed(
	const OIS::MouseEvent& me, OIS::MouseButtonID id) 
{ 
	Ogre::Vector2 mousePos = 
		Ogre::Vector2(static_cast<Ogre::Real>(me.state.X.abs),static_cast<Ogre::Real>(me.state.Y.abs));

	Ogre::Ray mouseRay =
		mCamera->getCameraToViewportRay(
		mousePos.x / float(me.state.width),
		mousePos.y / float(me.state.height));
	mRayScnQuery = mSceneMgr->createRayQuery(Ogre::Ray());
	mRayScnQuery->setRay(mouseRay);
	mRayScnQuery->setSortByDistance(true);

	Ogre::RaySceneQueryResult& result = mRayScnQuery->execute();
	Ogre::RaySceneQueryResult::iterator it = result.begin();

	Ogre::SceneNode* mCurObject;

	mMovableFound = false;


	for ( ; it != result.end(); it++)
	{
		mMovableFound =
			it->movable &&
			it->movable->getName() != "" &&
			it->movable->getName() != "MainCam" &&
			it->movable->getName() != "Ground" && 
			it->movable->getName() != "ground";

		if (mMovableFound)
		{
			//Ogre::Vector3 intersect = it->worldFragment->singleIntersection;
			mCurObject = it->movable->getParentSceneNode();
			Ogre::LogManager::getSingletonPtr()->logMessage("Moveable object found: "+mCurObject->getName());
			//Ogre::LogManager::getSingletonPtr()->logMessage("Position: "+Ogre::StringConverter::toString(intersect));
			
			break;
		}
	}

	if(mMovableFound)
	{
		// We have selected an entity
		std::cout << "Moveable object found" << std::endl;
		Ogre::LogManager::getSingletonPtr()->logMessage("Moveable object found");
	}

	return true; 
}
Beispiel #15
0
//!
//! Creates a deep copy of the given scene node.
//!
//! \param sceneNode The scene node to copy.
//! \param sceneNodeCopy The scene node to add the copied objects to (will be created if 0).
//! \param namePrefix The prefix to use for names of copied objects.
//! \param sceneManager The scene manager to use for creating the object.
//!
void OgreTools::deepCopySceneNode ( Ogre::SceneNode *sceneNode, Ogre::SceneNode *&sceneNodeCopy, const QString &namePrefix, Ogre::SceneManager *sceneManager /* = 0 */ )
{
    // make sure the given scene node is valid
    if (!sceneNode) {
        Log::error("The given scene node is invalid.", "OgreTools::deepCopySceneNode");
        return;
    }

    // make sure a valid scene manager is available
    if (!sceneManager)
        sceneManager = sceneNode->getCreator();
    if (!sceneManager) {
        Log::error("No valid scene manager available.", "OgreTools::deepCopySceneNode");
        return;
    }

    // create the target scene node if it doesn't exist yet
    if (!sceneNodeCopy) {
        QString sceneNodeCopyName = QString("%1_%2Copy").arg(namePrefix).arg(sceneNode->getName().c_str());
        sceneNodeCopy = copySceneNode(sceneNode, sceneNodeCopyName, sceneManager);
        if (!sceneNodeCopy) {
            Log::error("The scene node could not be copied.", "OgreTools::deepCopySceneNode");
            return;
        }
    }

    // iterate over the list of attached objects
    Ogre::SceneNode::ObjectIterator objectIterator = sceneNode->getAttachedObjectIterator();
    while (objectIterator.hasMoreElements()) {
        Ogre::MovableObject *movableObject = objectIterator.getNext();
        if (movableObject) {
            QString entityCopyName = QString("%1_%2Copy").arg(namePrefix).arg(movableObject->getName().c_str());
            Ogre::MovableObject *movableObjectCopy = cloneMovableObject(movableObject, entityCopyName, sceneManager);
            if (movableObjectCopy)
                sceneNodeCopy->attachObject(movableObjectCopy);
        }
    }

    // iterate over the list of child nodes
    Ogre::SceneNode::ChildNodeIterator childNodeIterator = sceneNode->getChildIterator();
    while (childNodeIterator.hasMoreElements() ) {
        Ogre::SceneNode *childSceneNode = (Ogre::SceneNode *) childNodeIterator.getNext();
        QString childSceneNodeCopyName = QString("%1_%2Copy").arg(namePrefix).arg(childSceneNode->getName().c_str());
        Ogre::SceneNode *childSceneNodeCopy = copySceneNode(childSceneNode, childSceneNodeCopyName, sceneManager);
        if (childSceneNodeCopy) {
            sceneNodeCopy->addChild(childSceneNodeCopy);
            deepCopySceneNode(childSceneNode, childSceneNodeCopy, namePrefix, sceneManager);
        }
    }
}
Beispiel #16
0
void SelectionHandler::destroyBox(const std::pair<CollObjectHandle, uint64_t>& handles)
{
  M_HandleToBox::iterator it = boxes_.find(handles);
  if (it != boxes_.end())
  {
    Ogre::SceneNode* node = it->second.first;
    Ogre::WireBoundingBox* box = it->second.second;

    node->detachAllObjects();
    node->getParentSceneNode()->removeAndDestroyChild(node->getName());

    delete box;

    boxes_.erase(it);
  }
}
Beispiel #17
0
void Cube::save(Ogre::String file)
{
  if (rndCounter == 0)
  {
    std::ofstream output(file.c_str());

    // Write cube size
    output << size << std::endl;

    for (int i = 0; i < size; ++i)
      for (int j = 0; j < size; ++j)
        for (int k = 0; k < size; ++k)
        {
          CubeElement *e = data[i][j][k];
          Ogre::Entity *ent = static_cast<Ogre::Entity*>(e->node->getAttachedObject(0));
          Ogre::SceneNode *node = e->node;
          // Write name, indexes and position
          output << node->getName() << "\n"
                 << "\t" << i << " " << j << " " << k << "\n" // index in data array
                 << "\t" << node->getPosition().x << " " << node->getPosition().y << " " << node->getPosition().z << "\n"; // position
          // Write orientation
          Ogre::Vector3 orient_axis;
          Ogre::Degree orient_angle;
          node->getOrientation().ToAngleAxis(orient_angle, orient_axis);
          output << "\t" << orient_axis.x << " " << orient_axis.y << " " << orient_axis.z << " " // orientation axis
                 << orient_angle.valueDegrees() << "\n"; // orientation angle
          output << "\t" << ent->getSubEntity(0)->getMaterialName() << "\n"
                 << "\t" << ent->getSubEntity(1)->getMaterialName() << "\n"
                 << "\t" << ent->getSubEntity(2)->getMaterialName() << "\n"
                 << "\t" << ent->getSubEntity(3)->getMaterialName() << "\n"
                 << "\t" << ent->getSubEntity(4)->getMaterialName() << "\n"
                 << "\t" << ent->getSubEntity(5)->getMaterialName() << "\n";
          // Write pivot info
          output << "\t" << e->isPivot << "\n";
          if (e->isPivot)
          {
            // pivot indexes
            output << "\t" << e->pivotArrays[0] << " " << e->pivotArrayIndexes[0] << "\n"
                   << "\t" << e->pivotArrays[1] << " " << e->pivotArrayIndexes[1] << "\n";
          }
          // flush
          output << std::endl;
        }

    output.close();
  }
}
Beispiel #18
0
SnapToMovement::SnapToMovement(Eris::Entity& entity, Ogre::Node& node, float snapThreshold, Ogre::SceneManager& sceneManager, bool showDebugOverlay) :
	mEntity(entity), mNode(node), mSnapThreshold(snapThreshold), mSceneManager(sceneManager)
{
	if (showDebugOverlay) {
		for (int i = 0; i < 30; ++i) {
			Ogre::SceneNode* node = mSceneManager.getRootSceneNode()->createChildSceneNode();
			Ogre::Entity* sphereEntity = mSceneManager.createEntity(node->getName() + "_entity", "3d_objects/primitives/models/sphere.mesh");
			//start out with a normal material
			sphereEntity->setMaterialName("/global/authoring/point");
			sphereEntity->setRenderingDistance(300);
			// 		entity.setQueryFlags(MousePicker::CM_UNDEFINED);
			node->setScale(0.25, 0.25, 0.25);
			node->attachObject(sphereEntity);
			node->setVisible(false);
			mDebugNodes.push_back(node);
		}
	}
}
    //-----------------------------------------------------------------------
    void ParticleSystemObject::createParticleSystem(void)
    {
        assert( mParticleSystem == NULL );
        assert(!mParticleSystemName.empty());

        Ogre::SceneNode* parent = getSceneNode();

        if (parent)
        {
            mParticleSystem = parent->getCreator()->createParticleSystem( parent->getName(), mParticleSystemName );
            assert(mParticleSystem);

            // Set render queue for particle system, the particle system should be render after world geometry 2
            mParticleSystem->setRenderQueueGroup(Ogre::RENDER_QUEUE_8);

            parent->attachObject(mParticleSystem);
        }
    }
Beispiel #20
0
 void PhysicsSystem::rotateObject (const Ptr& ptr)
 {
     Ogre::SceneNode* node = ptr.getRefData().getBaseNode();
     std::string handle = node->getName();
     Ogre::Quaternion rotation = node->getOrientation();
     if (OEngine::Physic::PhysicActor* act = mEngine->getCharacter(handle))
     {
         //Needs to be changed
         act->setRotation(rotation);
     }
     if (OEngine::Physic::RigidBody* body = mEngine->getRigidBody(handle))
     {
         if(dynamic_cast<btBoxShape*>(body->getCollisionShape()) == NULL)
             body->getWorldTransform().setRotation(btQuaternion(rotation.x, rotation.y, rotation.z, rotation.w));
         else
             mEngine->boxAdjustExternal(handleToMesh[handle], body, node->getScale().x, node->getPosition(), rotation);
     }
 }
Beispiel #21
0
//!
//! Remove and destroy this scene children.
//! \param The scenenode to be destroyed
//!
void Model2SceneNode::destroyAllChildren( Ogre::SceneNode* i_pSceneNode )
{
	if ( !i_pSceneNode || i_pSceneNode->numChildren() == 0 )
      return;

   // Destroy all the attached objects
   Ogre::SceneNode::ObjectIterator itObject = i_pSceneNode->getAttachedObjectIterator();

   // Recurse to child SceneNodes
   Ogre::SceneNode::ChildNodeIterator itChild = i_pSceneNode->getChildIterator();

   while ( itChild.hasMoreElements() )
   {
      Ogre::SceneNode* pChildNode = static_cast<Ogre::SceneNode*>(itChild.getNext());
      destroyAllAttachedMovableObjects( pChildNode );
	  // obtain the OGRE scene manager
	  Ogre::SceneManager *sceneManager = OgreManager::getSceneManager();
	  if (pChildNode != m_sceneNode)
		  sceneManager->destroySceneNode( pChildNode->getName() );
   }
}
Beispiel #22
0
    Ogre::SceneNode*
    JunctionPoints::allocNode(void)
    {
        Ogre::SceneNode* node;
        if (mFreeNodes.empty())
        {
            node = getIndicatorRootSceneNode()->createChildSceneNode();
            Ogre::Entity* entity = getSceneManager()->createEntity(node->getName(), mBaseMesh->getName());
            entity->setQueryFlags(0);
			//david-<<
            //entity->setNormaliseNormals(true);
			//david->>
            node->attachObject(entity);
        }
        else
        {
            node = mFreeNodes.back();
            mFreeNodes.pop_back();
            getIndicatorRootSceneNode()->addChild(node);
        }

        node->setScale(mScale, mScale, mScale);
        return node;
    }
Beispiel #23
0
 void PhysicsSystem::moveObject (const Ptr& ptr)
 {
     Ogre::SceneNode* node = ptr.getRefData().getBaseNode();
     std::string handle = node->getName();
     Ogre::Vector3 position = node->getPosition();
     if (OEngine::Physic::RigidBody* body = mEngine->getRigidBody(handle))
     {
         // TODO very dirty hack to avoid crash during setup -> needs cleaning up to allow
         // start positions others than 0, 0, 0
         
         
         if(dynamic_cast<btBoxShape*>(body->getCollisionShape()) == NULL){
             btTransform tr = body->getWorldTransform();
             tr.setOrigin(btVector3(position.x,position.y,position.z));
             body->setWorldTransform(tr);
         }
         else{
             //For objects that contain a box shape.  
             //Do any such objects exist?  Perhaps animated objects?
             mEngine->boxAdjustExternal(handleToMesh[handle], body, node->getScale().x, position, node->getOrientation());
         }
     }
     if (OEngine::Physic::PhysicActor* act = mEngine->getCharacter(handle))
     {
         // TODO very dirty hack to avoid crash during setup -> needs cleaning up to allow
         // start positions others than 0, 0, 0
         if (handle == "player")
         {
             playerphysics->ps.origin = position;
         }
         else
         {
             act->setPosition(position);
         }
     }
 }
void CsCameraManager::Load (Ogre::SceneNode* ogreScene) {
	UnLoad();
	SetupDefaultCamera();

	if (ogreScene == NULL) return;

	Ogre::Node::ChildNodeIterator it = ogreScene->getChildIterator();
	
	Ogre::SceneNode *tempNode;

	while (it.hasMoreElements()) {
		tempNode = static_cast <Ogre::SceneNode*> (it.getNext());
		assert(tempNode);

		if ((tempNode->getName().find("Camera")) != std::string::npos) {
			ogreScene->removeChild(tempNode);

			if (tempNode->getName().find("Free") != std::string::npos)
				AddCamera((Ogre::Camera*)tempNode->getAttachedObject(0), Chaos::FREE_CAMERA);
			else if (tempNode->getName().find("Track") != std::string::npos)
				AddCamera((Ogre::Camera*)tempNode->getAttachedObject(0), Chaos::TRACK_CAMERA);
			else if (tempNode->getName().find("Chase") != std::string::npos) {
				AddCamera((Ogre::Camera*)tempNode->getAttachedObject(0), Chaos::CHASE_CAMERA);
				if (tempNode->getName().find("001") != std::string::npos) {
					mCurrentCamera = mCameraList.size() - 1;
					ApplyCamera();
				}
			}
			else if (tempNode->getName().find("Cockpit") != std::string::npos)
				AddCamera((Ogre::Camera*)tempNode->getAttachedObject(0), Chaos::COCKPIT_CAMERA);
		}
	}

	mCurrentCamera = 0;
	ApplyCamera();
}
Beispiel #25
0
 void PhysicsSystem::insertActorPhysics(const MWWorld::Ptr& ptr, const std::string model){
       Ogre::SceneNode* node = ptr.getRefData().getBaseNode();
        // std::cout << "Adding node with name" << node->getName();
     addActor (node->getName(), model, node->getPosition());
 }
//-------------------------------------------------------------------------------------
void RollerCoaster::mouseMoveEvent( QMouseEvent *event )
{
	lastPos=event->pos();
	//bLMouseDown = true;



	float RatioX = float (lastPos.x())/mCamera->getViewport()->getActualWidth();
	float RatioY = float (lastPos.y())/mCamera->getViewport()->getActualWidth();
	if(bLMouseDown){
	using namespace Ogre;
	Ray mouseRay=mCamera->getCameraToViewportRay(RatioX,RatioY);
	std::pair<bool, Real>point =mouseRay.intersects(mPlane);
	if(point.first)
	{
		Vector3 pos= mouseRay.getPoint(point.second);
		SceneNode *tempSn = mSceneMgr->getRootSceneNode()->createChildSceneNode();
		Entity *tempEn = mSceneMgr->createEntity("ogrehead.mesh");
		tempSn->attachObject(tempEn);
		tempSn->setPosition(pos);
		tempSn->setScale(0.1,0.1,0.1);
	}


	}
	if( bLMouseDown )
	{
		mCurrentObjName = objControl->mouseDragged(
			lastPos,
			event->pos(),
			mCamera->getViewport()->getActualWidth(), 
			mCamera->getViewport()->getActualHeight()
		);

		if( !mCurrentObjName.empty() )
		{
			Ogre::SceneNode *currObj = mSceneMgr->getSceneNode(mCurrentObjName);
			if (currObj)
			{
				bReplan = true;

				mTrack->mMove(currObj->getName(), currObj->getPosition());
				mTrack->mRotate(currObj->getName(), currObj->getOrientation().yAxis());
			}
		}
	}
	//==== 當按下滑鼠右鍵 ====//
	if( event->buttons().testFlag(Qt::RightButton) && lastPos != invalidMousePoint )
	{
		if( currCamType != eWorld ) return;

		mCamWorldNode = mCamera->getParentSceneNode();

		Ogre::Degree rotX(0);
		Ogre::Degree rotY(0);
		int dx = event->pos().x()-lastPos.x();
		int dy = event->pos().y()-lastPos.y();
		rotX += Ogre::Degree(-dx * 0.0025f * ROT_SCALE);		// Rotate camera horizontaly
		rotY += Ogre::Degree(-dy * 0.0025f * ROT_SCALE);		// Rotate camera vertical

		mCamWorldNode->yaw	( rotX, Ogre::Node::TS_WORLD );
		mCamWorldNode->pitch( rotY, Ogre::Node::TS_LOCAL );

		objControl->update();
	}

	lastPos = event->pos();
}
Beispiel #27
0
void PhysicsWorld::move(int paddleTranslate[], int paddleRotate[], btScalar frameTime)
{
    dynamicsWorld->stepSimulation(frameTime);

    detectCollisions();

    //std::cout << collisionShapes.size() << std::endl;
    for(int i = 0; i < collisionShapes.size(); ++i)
    {
        btCollisionObject* obj = dynamicsWorld->getCollisionObjectArray()[i];

        btRigidBody* body = btRigidBody::upcast(obj);

        if(body && body->getMotionState())
        {
            btTransform transform;
            body->getMotionState()->getWorldTransform(transform);

            void* userPointer = body->getUserPointer();
            if(userPointer)
            {

                Ogre::SceneNode* sn = static_cast<Ogre::SceneNode*>(userPointer);

                btVector3    origin = transform.getOrigin();
                btQuaternion orientation = transform.getRotation();

                bool paddle1 = (sn->getName() == "paddle");
                bool paddle2 = (sn->getName() == "paddle2");

                if( ( multiplayer && ((server && paddle1) || (!server && paddle2)) ) 
                    || (!multiplayer && (paddle1 || paddle2)))
                {
                    int paddleMult = 0;
                    if(sn->getName() == "paddle2")
                        paddleMult = 1;

                    float paddleMoveSpeed = 0.06f;
                    btScalar rotationSpeed = .005f;

                    btTransform newTrans = transform;

                    //TRANSLATION
                    // up
                    if(paddleTranslate[0]) {
                        if(newTrans.getOrigin().getY() < (100.0f - 30.0f/2.0f + paddleMult*200.0f)) {
                            newTrans.getOrigin() += (btVector3(0, paddleMoveSpeed * (1000.0f * frameTime), 0));
                        }
                    }

                    // left
                    if(paddleTranslate[1]) {
                        if(newTrans.getOrigin().getX() < (100.0f - 40.0f/2.0f)) {
                            newTrans.getOrigin() += (btVector3(paddleMoveSpeed * (1000.0f * frameTime), 0, 0));
                        }
                    }

                    // down
                    if(paddleTranslate[2]) {
                        if(newTrans.getOrigin().getY() > (-100.0f + 30.0f/2.0f + paddleMult*200.0f)) {
                            newTrans.getOrigin() += (btVector3(0, -paddleMoveSpeed * (1000.0f * frameTime), 0));
                        }
                    }

                    //right
                    if(paddleTranslate[3]) {
                        if(newTrans.getOrigin().getX() > (-100.0f + 40.0f/2.0f)) {
                            newTrans.getOrigin() += (btVector3(-paddleMoveSpeed * (1000.0f * frameTime), 0, 0));
                        }
                    }

                    btScalar roll, pitch, yaw;
                    btQuaternion rotation = newTrans.getRotation();
                    btMatrix3x3(rotation).getEulerYPR(yaw,pitch,roll);

                    // ROTATION
                    // up
                    if(paddleRotate[0] && roll < 1) {
                        roll  += rotationSpeed * (1000.0f * frameTime);
                    }
                    // left
                    if(paddleRotate[1] && pitch > -1) {
                        pitch -= rotationSpeed * (1000.0f * frameTime);
                    }

                    // down
                    if(paddleRotate[2] && roll > -1) {
                        roll  -= rotationSpeed * (1000.0f * frameTime);
                    }

                    //right
                    if(paddleRotate[3] && pitch < 1){
                        pitch += rotationSpeed * (1000.0f * frameTime);
                    }

                    //reset
                    if(paddleRotate[4])
                    {
                        pitch = 0;
                        roll  = 0;
                        yaw   = 0;
                    }
                    
                    btQuaternion tmp;
                    tmp.setEulerZYX(yaw,pitch,roll);
                    newTrans.setRotation(tmp);

                    body->getMotionState()->setWorldTransform(newTrans);
                    body->translate(newTrans.getOrigin() - body->getCenterOfMassPosition());
                    body->setCenterOfMassTransform(newTrans);

                    if(server) {
                        paddle1Pitch = pitch;
                        paddle1Yaw = yaw;
                        paddle1Roll = roll;
                    } else {
                        paddle2Pitch = pitch;
                        paddle2Yaw = yaw;
                        paddle2Roll = roll;
                    }
                    
                    //std::cout << "Moving paddle transform to (" << tempOrigin.getX() << ", " << tempOrigin.getY() << ", " << tempOrigin.getZ() << ")\n";
                    //std::cout << "Paddle rigid body is now at (" << body->getCenterOfMassPosition().getX() << ", " << body->getCenterOfMassPosition().getY() << ", " << body->getCenterOfMassPosition().getZ() << ")\n";
                    
                }


                
                Ogre::Vector3 pos(origin.getX(), origin.getY(), origin.getZ());
                Ogre::Quaternion quat(orientation.getW(), orientation.getX(), orientation.getY(), orientation.getZ());

                if(multiplayer)
                {

                    if(server)
                    {
                        if(paddle1)
                        {
                            //set the values for paddle1
                            paddle1Position = Ogre::Vector3(origin.getX(), origin.getY(), origin.getZ());

                        } 
                        else if (paddle2)
                        {
                            //get the values for paddle2
                            btTransform newTrans = transform;
                            newTrans.setOrigin(btVector3(paddle2Position.x, paddle2Position.y, paddle2Position.z));
                            
                            btQuaternion tmp;
                            tmp.setEulerZYX(paddle2Yaw, paddle2Pitch, paddle2Roll);
                            newTrans.setRotation(tmp);

                            //newTrans.setRotation(btQuaternion(paddle2Quaternion.w, paddle2Quaternion.x, paddle2Quaternion.y, paddle2Quaternion.z));

                            body->getMotionState()->setWorldTransform(newTrans);
                            body->translate(newTrans.getOrigin() - body->getCenterOfMassPosition());
                            body->setCenterOfMassTransform(newTrans);

                            pos = paddle2Position;
                            // quat.x = (float)tmp.x;
                            // quat.y = (float)tmp.y;
                            // quat.z = (float)tmp.z;
                            // quat.w = (float)tmp.w;
                        }
                    }
                    else
                    {
                        if(paddle2)
                        {
                            //set the values for paddle2
                            paddle2Position = Ogre::Vector3(origin.getX(), origin.getY(), origin.getZ());
                            pos = paddle2Position;
                        }
                        else if (paddle1)
                        {
                            //get the values for paddle1
                            btTransform newTrans = transform;
                            newTrans.setOrigin(btVector3(paddle1Position.x, paddle1Position.y, paddle1Position.z));
                            
                            btQuaternion tmp;
                            tmp.setEulerZYX(paddle1Yaw, paddle1Pitch, paddle1Roll);
                            newTrans.setRotation(tmp);

                            //newTrans.setRotation(btQuaternion(paddle1Quaternion.w, paddle1Quaternion.x, paddle1Quaternion.y, paddle1Quaternion.z));
                            
                            body->getMotionState()->setWorldTransform(newTrans);
                            body->translate(newTrans.getOrigin() - body->getCenterOfMassPosition());
                            body->setCenterOfMassTransform(newTrans);

                            pos = paddle1Position;
                            // quat.x = (float)tmp.x;
                            // quat.y = (float)tmp.y;
                            // quat.z = (float)tmp.z;
                            // quat.w = (float)tmp.w;
                        }
                    }

                }
                    
                sn->setPosition(pos);
                sn->setOrientation(quat);


                // sn->setPosition(paddle1Position);
                // paddle1Quaternion = Ogre::Quaternion(
                //     orientation.getW(), orientation.getX(), 
                //     orientation.getY(), orientation.getZ());
                // sn->setOrientation(paddle1Quaternion);

            }
        }
    }
}
Beispiel #28
0
void PhysicsWorld::detectCollisions(void) 
{
    int numManifolds = dynamicsWorld->getDispatcher()->getNumManifolds();

    int ballContacts = 0;


    for(int i = 0; i < numManifolds; ++i) 
    {
        btPersistentManifold* contactManifold = dynamicsWorld->getDispatcher()->getManifoldByIndexInternal(i);
        btCollisionObject* objectA = const_cast<btCollisionObject*>
          ((btCollisionObject*)contactManifold->getBody0());
        btCollisionObject* objectB = const_cast<btCollisionObject*>
          ((btCollisionObject*)contactManifold->getBody1());

        void* userPointerA = objectA->getUserPointer();
        void* userPointerB = objectB->getUserPointer();

        Ogre::SceneNode* snA;
        Ogre::SceneNode* snB;

        if(userPointerA) snA = static_cast<Ogre::SceneNode*>(userPointerA);
        if(userPointerB) snB = static_cast<Ogre::SceneNode*>(userPointerB);
        
        int numContacts = contactManifold->getNumContacts();

        if(snA && snA->getName() == "ball") {
            ballContacts += numContacts;
        }

        for(int j = 0; j < numContacts; ++j) 
        {
            btManifoldPoint& pt = contactManifold->getContactPoint(j);

            //std::cout << pt.getDistance() << "\n";
            if(pt.getDistance() <= 1.0f) 
            {
                const btVector3& ptA = pt.getPositionWorldOnA();
                const btVector3& ptB = pt.getPositionWorldOnB();
                const btVector3& normalOnB = pt.m_normalWorldOnB;

                //std::cout << collisionIgnoreTimer << std::endl;
                //std::cout << "collision detected!" << std::endl;    

                if(!collisionIgnore) 
                {   
                    if(userPointerA)
                    {
                        if(snA->getName() == "ball") {
                            collisionIgnore = true;
                        }
                        //std::cout << "A is " << snA->getName() << std::endl;
                        if(userPointerB)
                        {
                            //std::cout << "B is " << snB->getName() << std::endl;
                            
                            if (snA->getName() == "floor" ||
                                snB->getName() == "floor" )
                            {
                                // Floor collision
                                physSound->playSound(2);

                                if(!multiplayer) 
                                {
                                    physScore->resetScore();
                                }
                                else 
                                {
                                    if(snA->getName() == "ball") {
                                        if(snA->getPosition().y > 100.0f) 
                                        {
                                            std::cout << "Player 1 gets a point!\n";
                                            physScore->addScore(1,1);
                                        } 
                                        else 
                                        {
                                            std::cout << "Player 2 gets a point!\n";
                                            physScore->addScore(1,2);
                                        }
                                    } 
                                    else 
                                    {
                                        if(snA->getPosition().y > 100.0f) 
                                        {
                                            std::cout << "Player 1 gets a point!\n";
                                            physScore->addScore(1,1);
                                        } 
                                        else 
                                        {
                                            std::cout << "Player 2 gets a point!\n";
                                            physScore->addScore(1,2);
                                        }
                                    }
                                }
                            }
                            else if (
                                snA->getName() == "paddle" ||
                                snB->getName() == "paddle" )
                            {
                                // Paddle collision
                                physSound->playSound(1);
                                
                                if(!multiplayer) 
                                    physScore->addScore(1);  

                                lastPaddleHit = 1;  
                            }      
                            else if (
                                snA->getName() == "paddle2" ||
                                snB->getName() == "paddle2" )
                            {
                                // Paddle collision
                                physSound->playSound(1);
                                
                                lastPaddleHit = 2;
                            } 
                        }
                        else 
                        {
                            // Wall collision
                            physSound->playSound(0);
                            
                            if(!multiplayer) 
                                physScore->addScore(3);
                        }
                    }
                    //std::cout << "Player 1: " << physScore->getScore(1) << std::endl;
                    //std::cout << "Player 2: " << physScore->getScore(2)  << std::endl;
                }
            }
        }
    }

    if(ballContacts == 0) {
        collisionIgnore = false;
    }
}
Beispiel #29
0
void DotSceneLoader::processNode(rapidxml::xml_node<>* XMLNode,
		Ogre::SceneNode *pParent) {
	// Construct the node's name
	Ogre::String name = m_sPrependNode + getAttrib(XMLNode, "name");

	// Create the scene node
	Ogre::SceneNode *pNode;
	if (name.empty()) {
		// Let Ogre choose the name
		if (pParent)
			pNode = pParent->createChildSceneNode();
		else
			pNode = mAttachNode->createChildSceneNode();
	} else {
		// Provide the name
		if (pParent)
			pNode = pParent->createChildSceneNode(name);
		else
			pNode = mAttachNode->createChildSceneNode(name);
	}

	std::cout << pNode->getName();

	// Process other attributes
	Ogre::String id = getAttrib(XMLNode, "id");
//  bool isTarget = getAttribBool(XMLNode, "isTarget");

	rapidxml::xml_node<>* pElement;

	// Process position (?)
	pElement = XMLNode->first_node("position");
	if (pElement) {
		pNode->setPosition(parseVector3(pElement));
		pNode->setInitialState();
	}

	// Process rotation (?)
	pElement = XMLNode->first_node("rotation");
	if (pElement) {
		pNode->setOrientation(parseQuaternion(pElement));
		pNode->setInitialState();
	}

	// Process scale (?)
	pElement = XMLNode->first_node("scale");
	if (pElement) {
		pNode->setScale(parseVector3(pElement));
		pNode->setInitialState();
	}

	// Process lookTarget (?)
	pElement = XMLNode->first_node("lookTarget");
	if (pElement)
		processLookTarget(pElement, pNode);

	// Process trackTarget (?)
	pElement = XMLNode->first_node("trackTarget");
	if (pElement)
		processTrackTarget(pElement, pNode);

	// Process node (*)
	pElement = XMLNode->first_node("node");
	while (pElement) {
		processNode(pElement, pNode);
		pElement = pElement->next_sibling("node");
	}

	// Process entity (*)
	pElement = XMLNode->first_node("entity");
	while (pElement) {
		processEntity(pElement, pNode);
		pElement = pElement->next_sibling("entity");
	}

	// Process light (*)
	pElement = XMLNode->first_node("light");
	while (pElement) {
	    processLight(pElement, pNode);
	    pElement = pElement->next_sibling("light");
	}

	// Process camera (*)
	pElement = XMLNode->first_node("camera");
	while (pElement) {
		processCamera(pElement, pNode);
		pElement = pElement->next_sibling("camera");
	}

	// Process particleSystem (*)
	pElement = XMLNode->first_node("particleSystem");
	while (pElement) {
		processParticleSystem(pElement, pNode);
		pElement = pElement->next_sibling("particleSystem");
	}

	// Process plane (*)
	pElement = XMLNode->first_node("plane");
	while (pElement) {
		processPlane(pElement, pNode);
		pElement = pElement->next_sibling("plane");
	}

	// Process userDataReference (?)
	pElement = XMLNode->first_node("userDataReference");

	// Process entity (*)
	pElement = XMLNode->first_node("pagedgeometry");
	while (pElement) {
		processPagedGeometry(pElement);
		pElement = pElement->next_sibling("pagedgeometry");
	}
}
Beispiel #30
0
 std::string getHandle() const { return mNode->getName(); }