Example #1
0
Ogre::Vector3 GetBoneWorldPosition(Ogre::Entity* ent, Ogre::Bone* bone)
{
	Vector3 world_position = bone->_getDerivedPosition();

	//multiply with the parent derived transformation
	Ogre::Node *pParentNode = ent->getParentNode();
	Ogre::SceneNode *pSceneNode = ent->getParentSceneNode();
	while (pParentNode != NULL)
	{
		//process the current i_Node
		if (pParentNode != pSceneNode)
		{
			//this is a tag point (a connection point between 2 entities). which means it has a parent i_Node to be processed
			world_position = pParentNode->_getFullTransform() * world_position;
			pParentNode = pParentNode->getParent();
		}
		else
		{
			//this is the scene i_Node meaning this is the last i_Node to process
			world_position = pParentNode->_getFullTransform() * world_position;
			break;
		}
	}
	return world_position;
}
Example #2
0
//-----------------------------------------------------------------------
const Ogre::Quaternion&
BasicRenderable::getWorldOrientation(void) const
{
    Ogre::Node* n = mParent->getParentNode();
    assert(n);
    return n->_getDerivedOrientation();
}
Example #3
0
Ogre::SceneNode * WheelAnimalSceneObj::getBaseCenter()
{
	if(_sn == NULL)
	{
		_sn =  Orz::OgreGraphicsManager::getSingleton().getSceneManager()->getRootSceneNode()->createChildSceneNode(getCenterPoint());
		//_sn->yaw(Ogre::Radian(Ogre::Math::PI));
		for(int i=0 ; i<(BASE_ALL-BASE_0); ++i)
		{
			Ogre::SceneNode * base = getBase(i);
			Ogre::Node * parent = base->getParent();
			Ogre::Vector3 p = base->getPosition();
			if(parent)
			{
				parent->removeChild(base);
			}
			base->translate(-getCenterPoint());
			_sn->addChild(base);
			Ogre::SceneManager * sm = OgreGraphicsManager::getSingleton().getSceneManager();
			Ogre::Entity * ent = sm->createEntity("ring"+Ogre::StringConverter::toString(i), "zp_dwdzgh.mesh");
			Ogre::SceneNode * node = base->createChildSceneNode("ring"+Ogre::StringConverter::toString(i),Ogre::Vector3(0.f, 10.f, 0.f));
			node->setScale(0.6f,0.6f,0.6f);
			node->attachObject(ent);
			Orz::OgreGraphicsManager::getSingleton().getSceneManager()->getSceneNode("ring"+Ogre::StringConverter::toString(i))->setVisible(false);
		}
	}
	return _sn;
}
Example #4
0
//-----------------------------------------------------------------------
const Ogre::Vector3&
BasicRenderable::getWorldPosition(void) const
{
    Ogre::Node* n = mParent->getParentNode();
    assert(n);
    return n->_getDerivedPosition();
}
Example #5
0
//-----------------------------------------------------------------------
Ogre::Real
BasicRenderable::getSquaredViewDepth(const Ogre::Camera* camera) const
{
    Ogre::Node* n = mParent->getParentNode();
    assert(n);
    return n->getSquaredViewDepth(camera);
}
void PlaneNodeProcessor::createCollision(Ogre::Entity *entity, DOMElement *physicsProxyElem)
{
    bool collisionEnabled = false;
    if (physicsProxyElem == NULL || !hasAttribute(physicsProxyElem, "collision"))
        collisionEnabled = false;
    else if(getAttributeValueAsBool(physicsProxyElem, "collision"))
        collisionEnabled = true;
    if(collisionEnabled)
    {
        std::vector<OgreNewt::CollisionPtr> collisions;
        OgreNewt::CollisionPtr collision = OgreNewt::CollisionPtr();
        OgreNewt::World* world = PhysicsManager::getSingleton()._getNewtonWorld();

        const AxisAlignedBox &aab = entity->getMesh()->getBounds();
        Ogre::Node* parentNode = entity->getParentNode();
        Ogre::Vector3 size = (aab.getMaximum() - aab.getMinimum()) * parentNode->getScale();

        const Quaternion orientation(0,0,0,0);// = parentNode->getOrientation();
        const Ogre::Vector3 pos = aab.getMinimum() * parentNode->getScale() + (size/2.0);

        collision = PhysicsManager::getSingleton().createCollision(entity, GT_BOX, "", Vector3::ZERO, Quaternion::IDENTITY, 0, NULL, NULL, true);

        if ( collision != NULL )
        {
            collisions.push_back(collision);
        }

        // Add to physics of map
        if (collisions.size() > 0)
        {
            PhysicsManager::getSingleton().addLevelGeometry(entity, collisions);
            LOG_WARNING(Logger::RULES, " Plane '"+entity->getName()+"' in levelGeometry geladen");
        }
    }
}
Example #7
0
void CreatureWeaponAnimation::updatePart(NifOgre::ObjectScenePtr& scene, int slot)
{
    MWWorld::InventoryStore& inv = mPtr.getClass().getInventoryStore(mPtr);
    MWWorld::ContainerStoreIterator it = inv.getSlot(slot);

    if (it == inv.end())
    {
        scene.setNull();
        return;
    }
    MWWorld::Ptr item = *it;

    std::string bonename;
    if (slot == MWWorld::InventoryStore::Slot_CarriedRight)
        bonename = "Weapon Bone";
    else
        bonename = "Shield Bone";

    scene = NifOgre::Loader::createObjects(mSkelBase, bonename, mInsert, item.getClass().getModel(item));
    Ogre::Vector3 glowColor = getEnchantmentColor(item);

    setRenderProperties(scene, RV_Actors, RQG_Main, RQG_Alpha, 0,
                        !item.getClass().getEnchantment(item).empty(), &glowColor);

    if(scene->mSkelBase)
    {
        Ogre::SkeletonInstance *skel = scene->mSkelBase->getSkeleton();
        if(scene->mSkelBase->isParentTagPoint())
        {
            Ogre::Node *root = scene->mSkelBase->getParentNode();
            if(skel->hasBone("BoneOffset"))
            {
                Ogre::Bone *offset = skel->getBone("BoneOffset");

                root->translate(offset->getPosition());

                // It appears that the BoneOffset rotation is completely bogus, at least for light models.
                //root->rotate(offset->getOrientation());
                root->pitch(Ogre::Degree(-90.0f));

                root->scale(offset->getScale());
                root->setInitialState();
            }
        }
        updateSkeletonInstance(mSkelBase->getSkeleton(), skel);
    }

    // TODO:
    // type == ESM::PRT_Weapon should get an animation source based on the current offset
    // of the weapon attack animation (from its beginning, or start marker?)
    std::vector<Ogre::Controller<Ogre::Real> >::iterator ctrl(scene->mControllers.begin());
    for(;ctrl != scene->mControllers.end();ctrl++)
    {
        if(ctrl->getSource().isNull())
            ctrl->setSource(Ogre::SharedPtr<NullAnimationTime>(new NullAnimationTime()));
    }
}
	//-----------------------------------------------------------------------
	void EntityRenderer::_destroyAll(void)
	{
		if (!mParentTechnique)
			return;


		// Delete the visual data
		vector<EntityRendererVisualData*>::const_iterator it;
		vector<EntityRendererVisualData*>::const_iterator itEnd = mAllVisualData.end();
		for (it = mAllVisualData.begin(); it != itEnd; ++it)
		{
			PU_DELETE_T(*it, EntityRendererVisualData, MEMCATEGORY_SCENE_OBJECTS);
		}

		mAllVisualData.clear();
		mVisualData.clear();

		// V1.5: Destroy the created ChildSceneNodes (which leads to detaching the Entities)
		if (mParentTechnique->getParentSystem())
		{
			Ogre::SceneNode* parentNode = mParentTechnique->getParentSystem()->getParentSceneNode();
			if (parentNode)
			{
				String sceneNodeName;
				std::stringstream ss; 
				unsigned short numChilds = parentNode->numChildren();
				for (unsigned short i = 0; i < numChilds; ++i)
				{
					Ogre::Node* node = parentNode->getChild(i);
					if (node)
					{
						Ogre::String name = node->getName();
						if (name.find("ParticleUniverse") != Ogre::String::npos)
						{
							parentNode->removeAndDestroyChild(i);
						}
					}
				}
			}
		} // V1.5

		// Destroy the Entities. Do it like this, because it must be assured that the entity still exists
		// and has not already been destroyed.
		Ogre::SceneManager* sceneManager = mParentTechnique->getParentSystem()->getSceneManager();
		for (size_t i = 0; i < mQuota; i++)
		{
			if (sceneManager->hasEntity(mEntityName + StringConverter::toString(i)))
			{
				sceneManager->destroyEntity(mEntityName + StringConverter::toString(i));
			}
		}
		mEntities.clear();

		// Reset the visual data in the pool
		mParentTechnique->initVisualDataInPool();
	}
Example #9
0
void ObjectAnimation::fillBatch(Ogre::StaticGeometry *sg)
{
    std::vector<Ogre::Entity*>::reverse_iterator iter = mObjectRoot->mEntities.rbegin();
    for(;iter != mObjectRoot->mEntities.rend();++iter)
    {
        Ogre::Node *node = (*iter)->getParentNode();
        if ((*iter)->isVisible())
            sg->addEntity(*iter, node->_getDerivedPosition(), node->_getDerivedOrientation(), node->_getDerivedScale());
    }
}
	//-----------------------------------------------------------------------
	void ParticleSystem::_process(ParticleTechnique* technique, Real timeElapsed)
	{
		// Inherited from the Particle class and is only called if the Particle System is emitted.
		// Update node position.
		Particle::_process(technique, timeElapsed);
		Ogre::Node* node = technique->getParentSystem()->getParentNode();
		if (mParentNode && node)
		{
			// position attribute is derived, but the the parentNode position must be set in relation to its parent.
			mParentNode->setPosition(position - node->getPosition());
		}
	}
Example #11
0
    /** See Ogre::ParticleEmitter. */
    void _initParticle(Ogre::Particle *particle)
    {
        Ogre::Vector3 xOff, yOff, zOff;

        // Call superclass
        ParticleEmitter::_initParticle(particle);

        xOff = Ogre::Math::SymmetricRandom() * mXRange;
        yOff = Ogre::Math::SymmetricRandom() * mYRange;
        zOff = Ogre::Math::SymmetricRandom() * mZRange;

#if OGRE_VERSION >= (1 << 16 | 10 << 8 | 0)
        Ogre::Vector3& position = particle->mPosition;
        Ogre::Vector3& direction = particle->mDirection;
        Ogre::ColourValue& colour = particle->mColour;
        Ogre::Real& totalTimeToLive = particle->mTotalTimeToLive;
        Ogre::Real& timeToLive = particle->mTimeToLive;
#else
        Ogre::Vector3& position = particle->position;
        Ogre::Vector3& direction = particle->direction;
        Ogre::ColourValue& colour = particle->colour;
        Ogre::Real& totalTimeToLive = particle->totalTimeToLive;
        Ogre::Real& timeToLive = particle->timeToLive;
#endif

        Ogre::Node* emitterBone = mEmitterBones.at(OEngine::Misc::Rng::rollDice(mEmitterBones.size()));

        position = xOff + yOff + zOff +
                 mParticleBone->_getDerivedOrientation().Inverse() * (emitterBone->_getDerivedPosition()
                - mParticleBone->_getDerivedPosition());

        // Generate complex data by reference
        genEmissionColour(colour);

        // NOTE: We do not use mDirection/mAngle for the initial direction.
        Ogre::Radian hdir = mHorizontalDir + mHorizontalAngle*Ogre::Math::SymmetricRandom();
        Ogre::Radian vdir = mVerticalDir + mVerticalAngle*Ogre::Math::SymmetricRandom();
        direction = (mParticleBone->_getDerivedOrientation().Inverse()
                     * emitterBone->_getDerivedOrientation() *
                                Ogre::Quaternion(hdir, Ogre::Vector3::UNIT_Z) *
                               Ogre::Quaternion(vdir, Ogre::Vector3::UNIT_X)) *
                              Ogre::Vector3::UNIT_Z;

        genEmissionVelocity(direction);

        // Generate simpler data
        timeToLive = totalTimeToLive = genEmissionTTL();
    }
Example #12
0
    void Player::setRot(float x, float y, float z)
    {
            Ogre::SceneNode *sceneNode = mNode;
            Ogre::Node* yawNode = sceneNode->getChildIterator().getNext();
            Ogre::Node* pitchNode = yawNode->getChildIterator().getNext();

            // we are only interested in X and Y rotation

            // Rotate around X axis
            Ogre::Quaternion xr(Ogre::Radian(x), Ogre::Vector3::UNIT_X);

            // Rotate around Y axis
            Ogre::Quaternion yr(Ogre::Radian(-z), Ogre::Vector3::UNIT_Y);

            pitchNode->setOrientation(xr);
            yawNode->setOrientation(yr);
    }
Example #13
0
void InputListener::updateGravity(const Ogre::FrameEvent& evt)
{
  for (std::list<PhysBody>::iterator it = this->_PhysicList->begin(); it != this->_PhysicList->end(); it++)
  {
    Ogre::Node *node = this->_SceneMgr->getRootSceneNode()->getChild(it->getName());
    Worms *worm;
    worm = this->_Game->findWormByName(it->getName());

    if (!this->_CollisionMgr->isCollidedToStatic(it->getName(), CollisionManager::DOWN) && node->getPosition().y > 0 && !this->_Game->getTeleportActivated())
      {
        if (!this->_CollisionMgr->isCollidedToStatic(it->getName(), CollisionManager::DOWN))
          node->translate(0, -1 * it->getWeight() * evt.timeSinceLastFrame, 0);
        worm->fall(1);
      }
    else
      worm->fall(0);
  }
}
Example #14
0
bool FaSoundEditor::unLoad()
{
    if(!mLoaded->get())
        return true;

    destroyBoundingBox();

    if(mHandle)
    {
        Ogre::Node *parent = mHandle->getParent();
        parent->removeChild(mHandle);
        mOgitorsRoot->GetSceneManager()->destroySceneNode(mHandle);
        mOgitorsRoot->GetSceneManager()->destroyEntity(mEntity);
        mHandle = 0;
        mEntity = 0;
    }
    
    mLoaded->set(false);
    return true;
}
Example #15
0
void scaleAndTestMount(TestModel& model, Model::ModelMount& mount, const Ogre::Node& node)
{
	WFMath::AxisBox<3> axisBox(WFMath::Point<3>(0, 0, 0), WFMath::Point<3>(10, 10, 10));

	model.bbox = Ogre::AxisAlignedBox(Ogre::Vector3(0, 0, 0), Ogre::Vector3(5, 5, 5));
	mount.rescale(&axisBox);
	CPPUNIT_ASSERT(node.getScale() == Ogre::Vector3(2, 2, 2));

	model.bbox = Ogre::AxisAlignedBox(Ogre::Vector3(0, 0, 0), Ogre::Vector3(20, 20, 20));
	mount.rescale(&axisBox);
	CPPUNIT_ASSERT(node.getScale() == Ogre::Vector3(0.5, 0.5, 0.5));

	model.bbox = Ogre::AxisAlignedBox(Ogre::Vector3(10, 10, 10), Ogre::Vector3(20, 20, 20));
	mount.rescale(&axisBox);
	CPPUNIT_ASSERT(node.getScale() == Ogre::Vector3(1, 1, 1));

	model.bbox = Ogre::AxisAlignedBox(Ogre::Vector3(0, 10, 15), Ogre::Vector3(20, 20, 20));
	mount.rescale(&axisBox);
	CPPUNIT_ASSERT(node.getScale() == Ogre::Vector3(2, 1, 0.5));

}
Example #16
0
void EmberEntityLoader::loadPage(::Forests::PageInfo & page)
{
	static Ogre::ColourValue colour(1, 1, 1, 1);

#if EMBERENTITYLOADER_USEBATCH
	const int batchX = static_cast<int>(Ogre::Math::Floor(page.bounds.left/ mBatchSize));
	const int batchY = static_cast<int>(Ogre::Math::Floor(page.bounds.top / mBatchSize));
	EntityMap& entities(mEntities[batchX][batchY]);
#else
	EntityMap& entities(mEntities);
#endif

	for (EntityMap::iterator I = entities.begin(); I != entities.end(); ++I) {
		ModelRepresentationInstance& instance(I->second);
		Model::ModelRepresentation* modelRepresentation(instance.modelRepresentation);
		EmberEntity& emberEntity = modelRepresentation->getEntity();
		if (emberEntity.isVisible()) {
			WFMath::Point<3> viewPos = emberEntity.getViewPosition();
			if (viewPos.isValid()) {
				Ogre::Vector3 pos(Convert::toOgre(viewPos));
				Model::Model& model(modelRepresentation->getModel());
				Ogre::Node* node = model.getParentNode();
				if (node) {
					const Ogre::Vector3& pos = node->_getDerivedPosition();
					if (pos.x > page.bounds.left && pos.x < page.bounds.right && pos.z > page.bounds.top && pos.z < page.bounds.bottom) {
						for (Model::Model::SubModelSet::const_iterator J = model.getSubmodels().begin(); J != model.getSubmodels().end(); ++J) {
							// 				if (!(*J)->getEntity()->getParentSceneNode()) {
							// 					model->getParentSceneNode()->attachObject((*J)->getEntity());
							// 				}
							//  				if ((*J)->getEntity()->isVisible()) {
							addEntity((*J)->getEntity(), pos, node->_getDerivedOrientation(), modelRepresentation->getScale(), colour);
							// 					(*J)->getEntity()->setVisible(false);
							//  				}
						}
					}
				}
			}
		}
	}
}
	//-----------------------------------------------------------------------------------------
	void CollisionCameraController::update(float timeSinceLast) {
		Ogre::Camera* camera     = mGraphicsSystem->getCamera();
		Ogre::Node*   cameraNode = camera->getParentNode();

		{
			btTransform  transform = mGhostObject->getWorldTransform();
			btQuaternion q         = transform.getRotation();
			q *= btQuaternion(btVector3(0, 1, 0), mCameraYaw);
			mGhostObject->getWorldTransform().setRotation(q);
		}

		camera->pitch(Ogre::Radian(mCameraPitch));

		mCameraYaw   = 0.0f;
		mCameraPitch = 0.0f;

		int camMovementZ = mKeymapState[Backward].second - mKeymapState[Forward].second;
		int camMovementX = mKeymapState[Rightward].second - mKeymapState[Leftward].second;
		int slideUpDown  = mKeymapState[Up].second - mKeymapState[Down].second;

		Ogre::Vector3 camMovementDir(camMovementX, slideUpDown, camMovementZ);
		camMovementDir.normalise();
		camMovementDir *= timeSinceLast * mCameraBaseSpeed * (1 + mSpeedModifier * mCameraSpeedBoost);
		if (camMovementDir.y > 0) {
			mCharacter->jump();
			camMovementDir.y = 0;
		}
		mCharacter->setWalkDirection(Collision::Converter::to(Collision::Converter::to(mGhostObject->getWorldTransform().getRotation()) * camMovementDir));

		{
			Ogre::Node*      cameraNode = camera->getParentNode();
			Ogre::Quaternion q;
			q = q * (Collision::Converter::to(mGhostObject->getWorldTransform().getRotation()));
			q = q * Ogre::Quaternion(cameraNode->getOrientation().getPitch(), Ogre::Vector3(1, 0, 0));

			cameraNode->setOrientation(q);
			cameraNode->setPosition(Collision::Converter::to(mGhostObject->getWorldTransform().getOrigin() /* + btVector3(0,1.8,0)*/));
		}
	}
Example #18
0
void InputListener::updateCam(const Ogre::FrameEvent& evt, Worms *_current)
{
  Ogre::Vector3 deplacement = Ogre::Vector3::ZERO;
  if (this->_fixedCam)
  {
    if (this->_Keyboard->isKeyDown(OIS::KC_W))
    {
      this->_CamSupposedPosition = Ogre::Vector3(600, 250.0, 950);
    }
    else
    {
      this->_CamSupposedPosition = _current->getNode()->getPosition() - Ogre::Vector3(0, 0, -300);
    }
  }
  if (!this->_fixedCam)
  {
    Ogre::Vector3 mov = this->_Mouvement;

    if (this->_currentScene->getCamera()->getPosition().x < 100)
      mov.x = 1;
    if (this->_currentScene->getCamera()->getPosition().x > 1200)
      mov.x = -1;
    if (this->_currentScene->getCamera()->getPosition().y < 50)
      mov.y = 1;
    if (this->_currentScene->getCamera()->getPosition().y > 510)
      mov.y = -1;
    if (this->_currentScene->getCamera()->getPosition().z < 50)
      mov.z = 1;
    if (this->_currentScene->getCamera()->getPosition().z > 510)
      mov.z = -1;
    deplacement = mov * this->_Vitesse * evt.timeSinceLastFrame;
    this->_currentScene->getCamera()->moveRelative(deplacement);
  }
  else
    this->_currentScene->getCamera()->setPosition(this->_currentScene->getCamera()->getPosition() + ((this->_CamSupposedPosition - this->_currentScene->getCamera()->getPosition()) * 0.05f));
  Ogre::Node *node = this->_WormsApp->getSceneManager()->getScene("PlayScene")->getScene()->getRootSceneNode()->getChild("CrossHair");
  node->setPosition(_current->getNode()->getPosition().x + 40 * cos(_current->getAngle()), _current->getNode()->getPosition().y + 40 * sin(_current->getAngle()), 30);
}
Example #19
0
    void PhysicsSystem::doPhysics(float dt, const std::vector<std::pair<std::string, Ogre::Vector3> >& actors)
    {
        //set the DebugRenderingMode. To disable it,set it to 0
        //eng->setDebugRenderingMode(1);

        //set the walkdirection to 0 (no movement) for every actor)
        for(std::map<std::string,OEngine::Physic::PhysicActor*>::iterator it = mEngine->PhysicActorMap.begin(); it != mEngine->PhysicActorMap.end();it++)
        {
            OEngine::Physic::PhysicActor* act = it->second;
            act->setWalkDirection(btVector3(0,0,0));
        }
		playerMove::playercmd& pm_ref = playerphysics->cmd;

        pm_ref.rightmove = 0;
        pm_ref.forwardmove = 0;
        pm_ref.upmove = 0;

		//playerphysics->ps.move_type = PM_NOCLIP;
        for (std::vector<std::pair<std::string, Ogre::Vector3> >::const_iterator iter (actors.begin());
            iter!=actors.end(); ++iter)
        {
            //dirty stuff to get the camera orientation. Must be changed!

            Ogre::SceneNode *sceneNode = mRender.getScene()->getSceneNode (iter->first);
            Ogre::Vector3 dir;
            Ogre::Node* yawNode = sceneNode->getChildIterator().getNext();
            Ogre::Node* pitchNode = yawNode->getChildIterator().getNext();
			Ogre::Quaternion yawQuat = yawNode->getOrientation();
            Ogre::Quaternion pitchQuat = pitchNode->getOrientation();



            playerphysics->ps.viewangles.x = pitchQuat.getPitch().valueDegrees();

			playerphysics->ps.viewangles.y = yawQuat.getYaw().valueDegrees() *-1 + 90;


                Ogre::Quaternion quat = yawNode->getOrientation();
                Ogre::Vector3 dir1(iter->second.x,iter->second.z,-iter->second.y);

				pm_ref.rightmove = -iter->second.x;
				pm_ref.forwardmove = -iter->second.y;
				pm_ref.upmove = iter->second.z;



            }





        mEngine->stepSimulation(dt);
    }
Example #20
0
    //-----------------------------------------------------------------------------------
    void CameraController::update( float timeSinceLast )
    {
        Ogre::Camera *camera = mGraphicsSystem->getCamera();

        if( mCameraYaw || mCameraPitch )
        {
            if( mUseSceneNode )
            {
                Ogre::Node *cameraNode = camera->getParentNode();

                // Update now as yaw needs the derived orientation.
                cameraNode->_getFullTransformUpdated();
                cameraNode->yaw( Ogre::Radian( mCameraYaw ), Ogre::Node::TS_WORLD );
                cameraNode->pitch( Ogre::Radian( mCameraPitch ) );
            }
            else
            {
                camera->yaw( Ogre::Radian( mCameraYaw ) );
                camera->pitch( Ogre::Radian( mCameraPitch ) );
            }

            mCameraYaw   = 0.0f;
            mCameraPitch = 0.0f;
        }

        int camMovementZ = mWASD[2] - mWASD[0];
        int camMovementX = mWASD[3] - mWASD[1];
        int slideUpDown = mSlideUpDown[0] - mSlideUpDown[1];

        if( camMovementZ || camMovementX || slideUpDown )
        {
            Ogre::Vector3 camMovementDir( camMovementX, slideUpDown, camMovementZ );
            camMovementDir.normalise();
            camMovementDir *= timeSinceLast * 10.0f * (1 + mSpeedMofifier * 5);

            if( mUseSceneNode )
            {
                Ogre::Node *cameraNode = camera->getParentNode();
                cameraNode->translate( camMovementDir, Ogre::Node::TS_LOCAL );
            }
            else
            {
                camera->moveRelative( camMovementDir );
            }
        }
    }
Example #21
0
void EC_Mesh::OnAttributeUpdated(IAttribute *attribute)
{
    if (attribute == &drawDistance)
    {
        if(entity_)
            entity_->setRenderingDistance(drawDistance.Get());
    }
    else if (attribute == &castShadows)
    {
        if(entity_)
        {
            if (entity_)
                entity_->setCastShadows(castShadows.Get());
            //! \todo might want to disable shadows for some attachments
            for (uint i = 0; i < attachment_entities_.size(); ++i)
            {
                if (attachment_entities_[i])
                    attachment_entities_[i]->setCastShadows(castShadows.Get());
            }
        }
    }
    else if (attribute == &nodeTransformation)
    {
        Ogre::Node* adjustmentTarget = adjustment_node_;
        if (bone_tagpoint_)
            adjustmentTarget = bone_tagpoint_;
        
        if (adjustmentTarget)
        {
            Transform newTransform = nodeTransformation.Get();
            adjustmentTarget->setPosition(newTransform.position.x, newTransform.position.y, newTransform.position.z);
            Quaternion adjust(DEGTORAD * newTransform.rotation.x,
                              DEGTORAD * newTransform.rotation.y,
                              DEGTORAD * newTransform.rotation.z);
            // Let's not assume the needed haxor adjustment here, but let user specify it as necessary
            //adjust = Quaternion(PI/2, 0, PI) * adjust;
            adjustmentTarget->setOrientation(Ogre::Quaternion(adjust.w, adjust.x, adjust.y, adjust.z));
            
            // Prevent Ogre exception from zero scale
            if (newTransform.scale.x < 0.0000001f)
                newTransform.scale.x = 0.0000001f;
            if (newTransform.scale.y < 0.0000001f)
                newTransform.scale.y = 0.0000001f;
            if (newTransform.scale.z < 0.0000001f)
                newTransform.scale.z = 0.0000001f;
            
            adjustmentTarget->setScale(newTransform.scale.x, newTransform.scale.y, newTransform.scale.z);
        }
    }
    else if (attribute == &meshRef)
    {
        if (!ViewEnabled())
            return;
            
        //Ensure that mesh is requested only when it's has actually changed.
//        if(entity_)
 //           if(QString::fromStdString(entity_->getMesh()->getName()) == meshRef.Get().ref/*meshResourceId.Get()*/)
  //              return;
/*
        AssetTransferPtr transfer = GetFramework()->Asset()->RequestAsset(meshRef.Get());
        if (transfer)
        {
            connect(transfer.get(), SIGNAL(Loaded(AssetPtr)), SLOT(OnMeshAssetLoaded()), Qt::UniqueConnection);
        }
        else
        {
            RemoveMesh();
        }
        */
        if (meshRef.Get().ref.trimmed().isEmpty())
            LogDebug("Warning: Mesh \"" + this->parent_entity_->GetName().toStdString() + "\" mesh ref was set to an empty reference!");
        meshAsset->HandleAssetRefChange(&meshRef);
    }
    else if (attribute == &meshMaterial)
    {
        if (!ViewEnabled())
            return;
        
        // We won't request materials until we are sure that mesh has been loaded and it's safe to apply materials into it.
        // This logic shouldn't be necessary anymore. -jj.
//        if(!HasMaterialsChanged())
//            return;

        AssetReferenceList materials = meshMaterial.Get();

        // Reallocate the number of material asset reflisteners.
        while(materialAssets.size() > materials.Size())
            materialAssets.pop_back();
        while(materialAssets.size() < materials.Size())
            materialAssets.push_back(boost::shared_ptr<AssetRefListener>(new AssetRefListener));

        for(int i = 0; i < materials.Size(); ++i)
        {
            connect(materialAssets[i].get(), SIGNAL(Loaded(AssetPtr)), this, SLOT(OnMaterialAssetLoaded(AssetPtr)), Qt::UniqueConnection);
            materialAssets[i]->HandleAssetRefChange(framework_->Asset(), materials[i].ref);
        }
    }
    else if((attribute == &skeletonRef) && (!skeletonRef.Get().ref.isEmpty()))
    {
        if (!ViewEnabled())
            return;
        
        // If same name skeleton already set no point to do it again.
//        if (entity_ && entity_->getSkeleton() && entity_->getSkeleton()->getName() == skeletonRef.Get().ref/*skeletonId.Get()*/.toStdString())
 //           return;

  //      AssetTransferPtr transfer = GetFramework()->Asset()->RequestAsset(skeletonRef.Get().ref);
   //     if (transfer)
    //        connect(transfer.get(), SIGNAL(Loaded(AssetPtr)), SLOT(OnSkeletonAssetLoaded(AssetPtr)), Qt::UniqueConnection);
        skeletonAsset->HandleAssetRefChange(&skeletonRef);
    }
}
Example #22
0
Ogre::Real Canvas::getSquaredViewDepth(const Ogre::Camera* cam) const
{
	Ogre::Node* node = this->getParentNode();
	assert(node);
	return node->getSquaredViewDepth(cam);
}
Example #23
0
void VLogicModel::setVisible(VBOOL visible)
{
    if (mModelMainNode != VNULL)
    {
        mModelMainNode->setVisible(visible);

        Ogre::Node *parentNode = mModelMainNode->getParent();

        if (visible)
        {
            if (parentNode == VNULL)
            {
                mParentNode->addChild(mModelMainNode);
            }
            else
            {
                if (mParentNode != parentNode)
                {

                }
            }
        }
        else
        {
            if (parentNode != VNULL)
            {
                if (mParentNode != parentNode)
                {

                }

                parentNode->removeChild(mModelMainNode);
            }
            else
            {
                if (mVisible != visible)
                {

                }
            }
        }

        mVisible = visible;

        // 特效也需要设置可见性

        // locator上挂接的model也需要设置可见性
        for (VLocatorMap::iterator itr = mLocators.begin(); itr != mLocators.end(); ++itr)
        {
            VLocatorValue &locator = itr->second;

            for (VSlotMap::iterator i = locator.mSlots.begin(); i != locator.mSlots.end(); ++i)
            {
                VSlotValue &slot = i->second;
                if (slot.mModel != VNULL)
                {
                    slot.mModel->setVisible(visible);
                }
            }
        }

        // 设置技能特效可见性
        if (!visible)
        {

        }
    }
}
Example #24
0
    void BtOgreSoftBody::updateOgreMesh()
    {
        Ogre::Node *ogreNode = mEntity->getParentNode();

        //printf("updateOgreMesh %d %s %s\n", internalId, mEntity->getName().c_str(), ogreNode->getName().c_str());

        MeshPtr mesh = mEntity->getMesh();
        Mesh::SubMeshIterator subMeshI = mesh->getSubMeshIterator();
        SubMesh* subMesh = NULL;

        VertexData* vData = NULL;
        VertexDeclaration* vDeclaration = NULL;
        const VertexElement* vPosElement = NULL;

        bool isSharedVerticesAdded = false;
        unsigned short bufferIndex = 0;
        HardwareVertexBufferSharedPtr vBuffer;

        // Can not do arithmetic operations on void*
        unsigned char* lockedMem = NULL;
        float* vPosition;

        btSoftBody::tNodeArray& btNodes = mSoftBody->m_nodes;
        //printf("Bullet nodes size %d\n", btNodes.size());

        int ogreVertexIdx = 0;
        btVector3 btPosOffset;

        while (subMeshI.hasMoreElements())
        {
            subMesh = subMeshI.getNext();

            if (subMesh->useSharedVertices)
            {

                if (isSharedVerticesAdded)
                {
                    continue;
                }

                vData = mesh->sharedVertexData;

                // We need to add shared vertices only once
                isSharedVerticesAdded = true;

            }
            else
            {
                vData = subMesh->vertexData;
            }

            vDeclaration = vData->vertexDeclaration;
            vPosElement = vDeclaration->findElementBySemantic(VES_POSITION);

            bufferIndex = vPosElement->getSource();
            vBuffer = vData->vertexBufferBinding->getBuffer(bufferIndex);

            // Lock the buffer before reading from it
            lockedMem = static_cast<unsigned char*>(vBuffer->lock(HardwareBuffer::HBL_DISCARD));

            // Read each vertex
            for (unsigned int i = 0; i < vData->vertexCount; ++i)
            {
                vPosElement->baseVertexPointerToElement(lockedMem, &vPosition);

                int idx = getBulletIndex(ogreVertexIdx);
                const btVector3 &btPos = btNodes[idx].m_x;

                if (ogreVertexIdx == 0)
                {
                    btPosOffset = btPos;
                }

                *vPosition++ = btPos.x() - btPosOffset.x();
                *vPosition++ = btPos.y() - btPosOffset.y();
                *vPosition = btPos.z() - btPosOffset.z();

                // Point to the next vertex
                lockedMem += vBuffer->getVertexSize();

                ogreVertexIdx++;
            }

            vBuffer->unlock();
        }

        ogreNode->setPosition(btPosOffset.x(), btPosOffset.y(), btPosOffset.z());

    }
Example #25
0
bool OgreSmartBody::frameRenderingQueued(const Ogre::FrameEvent& evt)
{
    if(mWindow->isClosed())
        return false;
 
    //Need to capture/update each device
    mKeyboard->capture();
    mMouse->capture();
 
    if(mKeyboard->isKeyDown(OIS::KC_ESCAPE))
        return false;

	// smartbody
	if (!m_pScene)
		return true;

	SmartBody::SBSimulationManager* sim = m_pScene->getSimulationManager();
	sim->setTime((Ogre::Root::getSingleton().getTimer()->getMilliseconds() / 1000.0f) - mStartTime);
	m_pScene->update();

	int numCharacters = m_pScene->getNumCharacters();
	if (numCharacters == 0)
		return true;

	const std::vector<std::string>& characterNames = m_pScene->getCharacterNames();

	for (size_t n = 0; n < characterNames.size(); n++)
	{
		SmartBody::SBCharacter* character = m_pScene->getCharacter(characterNames[n]);
		if (!this->getSceneManager()->hasEntity(characterNames[n]))
			continue;

		Ogre::Entity* entity = this->getSceneManager()->getEntity(characterNames[n]);
		Ogre::Skeleton* meshSkel = entity->getSkeleton();
		Ogre::Node* node = entity->getParentNode();

		SrVec pos = character->getPosition();
		SrQuat ori = character->getOrientation();
		//std::cout << ori.w << ori.x << " " << ori.y << " " << ori.z << std::endl;
		node->setPosition(pos.x, pos.y, pos.z);
		node->setOrientation(ori.w, ori.x, ori.y, ori.z);
	
		// Update joints
		SmartBody::SBSkeleton* sbSkel = character->getSkeleton();
			
		int numJoints = sbSkel->getNumJoints();
		for (int j = 0; j < numJoints; j++)
		{
			SmartBody::SBJoint* joint = sbSkel->getJoint(j);
	
			try
			{
				SrQuat orientation = joint->quat()->value();
	
				Ogre::Vector3 posDelta(joint->getPosition().x, joint->getPosition().y, joint->getPosition().z);
				Ogre::Quaternion quatDelta(orientation.w, orientation.x, orientation.y, orientation.z);
				Ogre::Bone* bone = meshSkel->getBone(joint->getName());
				if (!bone)
					continue;
				bone->setPosition(bone->getInitialPosition() + posDelta);
				bone->setOrientation(quatDelta);
			}
			catch (Ogre::ItemIdentityException& ex)
			{
				// Should not happen as we filtered using m_mValidBones
			}
		}
	}
	

 
    return true;
}
Example #26
0
    void PhysicsSystem::doPhysics(float dt, const std::vector<std::pair<std::string, Ogre::Vector3> >& actors)
    {
        //set the DebugRenderingMode. To disable it,set it to 0
        //eng->setDebugRenderingMode(1);

        //set the walkdirection to 0 (no movement) for every actor)
        for(std::map<std::string,OEngine::Physic::PhysicActor*>::iterator it = mEngine->PhysicActorMap.begin(); it != mEngine->PhysicActorMap.end();it++)
        {
            OEngine::Physic::PhysicActor* act = it->second;
            act->setWalkDirection(btVector3(0,0,0));
        }
		playerMove::playercmd& pm_ref = playerphysics->cmd;

        pm_ref.rightmove = 0;
        pm_ref.forwardmove = 0;
        pm_ref.upmove = 0;

		//playerphysics->ps.move_type = PM_NOCLIP;
        for (std::vector<std::pair<std::string, Ogre::Vector3> >::const_iterator iter (actors.begin());
            iter!=actors.end(); ++iter)
        {
            OEngine::Physic::PhysicActor* act = mEngine->getCharacter(iter->first);
			//if(iter->first == "player")
			//	std::cout << "This is player\n";
            //dirty stuff to get the camera orientation. Must be changed!

            Ogre::SceneNode *sceneNode = mRender.getScene()->getSceneNode (iter->first);
            Ogre::Vector3 dir;
            Ogre::Node* yawNode = sceneNode->getChildIterator().getNext();
            Ogre::Node* pitchNode = yawNode->getChildIterator().getNext();
			Ogre::Quaternion yawQuat = yawNode->getOrientation();
            Ogre::Quaternion pitchQuat = pitchNode->getOrientation();

            // unused
            //Ogre::Quaternion both = yawQuat * pitchQuat;

            playerphysics->ps.viewangles.x = pitchQuat.getPitch().valueDegrees();
            playerphysics->ps.viewangles.z = 0;
			playerphysics->ps.viewangles.y = yawQuat.getYaw().valueDegrees() *-1 + 90;

            if(mFreeFly)
            {
                Ogre::Vector3 dir1(iter->second.x,iter->second.z,-iter->second.y);

				pm_ref.rightmove = -dir1.x;
				pm_ref.forwardmove = dir1.z;
				pm_ref.upmove = dir1.y;


				//std::cout << "Current angle" << yawQuat.getYaw().valueDegrees() - 90<< "\n";
				//playerphysics->ps.viewangles.x = pitchQuat.getPitch().valueDegrees();
				//std::cout << "Pitch: " << yawQuat.getPitch() << "Yaw:" << yawQuat.getYaw() << "Roll: " << yawQuat.getRoll() << "\n";
                dir = 0.07*(yawQuat*pitchQuat*dir1);
            }
            else
            {

                Ogre::Quaternion quat = yawNode->getOrientation();
                Ogre::Vector3 dir1(iter->second.x,iter->second.z,-iter->second.y);

				pm_ref.rightmove = -dir1.x;
				pm_ref.forwardmove = dir1.z;
				pm_ref.upmove = dir1.y;



                dir = 0.025*(quat*dir1);
            }


            //set the walk direction
            act->setWalkDirection(btVector3(dir.x,-dir.z,dir.y));
        }
        mEngine->stepSimulation(dt);
    }
Example #27
0
void EditorFrameHandler::Init()
{
	Ogre::SceneManager *scene_manager = CommonDeclarations::GetSceneManager();
	EditorCamera = scene_manager->createCamera("EditorCamera");
	EditorCamera->setNearClipDistance(5);		
	EditorCamera->setFarClipDistance(0);

	EditorCamera->setPosition(CommonDeclarations::GetCamera()->GetOgreCamera()->getWorldPosition());

	CommonDeclarations::GetApplication()->SetCurrentCamera(EditorCamera);

	/*CommonDeclarations::ObjectsPool *objects = CommonDeclarations::GetEditableObjects();
	for (CommonDeclarations::ObjectsPool::ListNode *pos = objects->GetBegin();pos!=NULL;pos=pos->Next)
	{		
		SEditableObject obj;
		obj.Object = pos->Value;
		IScenable *scen = pos->Value->GetScenable();
		if (scen)
		{
			obj.EditNode = NULL;
			obj.EditEntity = NULL;
			ICollidable *collid = pos->Value->GetCollidable();
			if (collid)
			{
				obj.CollisionModel = collid->GetCollisionModel();
			} else
			{				
				const char *modelname = scen->GetModelName();
				if (NULL == modelname)
					modelname = AAUtilities::StringCopy("cube.mesh");
				obj.CollisionModel = GetCollisionModel(modelname);
			}				
		} else
		{
			obj.EditNode = scene_manager->getRootSceneNode()->createChildSceneNode();	
			char *buffer = CommonDeclarations::GenGUID();			
			obj.EditEntity = scene_manager->createEntity(buffer, "cube.mesh");					
			delete [] buffer;

			obj.EditNode->attachObject(obj.EditEntity);

			obj.CollisionModel = GetCollisionModel("cube.mesh");
		}
		EditableObjects.PushBack(obj);		
	}
	delete objects;*/

	//
	CommonDeclarations::ObjectsPool *objects = CommonDeclarations::GetEditableObjects();
	const char *str;
	TiXmlElement *node = 0, *nodes, *env;
	env = SceneRootElement->FirstChildElement("environment");	
	if (env)
	{
		node = env->FirstChildElement("skyBox");	
		if (node)
		{			
			SEditableDescription descr;
				
			descr.EditNode = NULL;
			descr.EditElement = node;
			EditorNodes.insert(std::make_pair("SkyBox", descr));
		}
	}
	
	nodes = SceneRootElement->FirstChildElement("nodes");	
	if (nodes)
	{
		node = nodes->FirstChildElement("node");	
		
		Ogre::Node::ChildNodeIterator iFirst = scene_manager->getRootSceneNode()->getChildIterator(), iPos = iFirst;
		
		while (node)
		{
			str = node->Attribute("name");
			SEditableDescription descr;
			Ogre::Node *t = NULL;
			iPos = iFirst;
			while (iPos.hasMoreElements()) 
			{
				t = iPos.getNext();
				if (t->getName()==str)
				{
					descr.EditNode = t;
					break;
				}
			}
			
			descr.EditElement = node;
			EditorNodes.insert(std::make_pair(str, descr));
			
			node = node->NextSiblingElement("node");
		}
	}
	delete objects;
	//

	MyGUI::Gui *gui = GUISystem::GetInstance()->GetGui();
	OIS::Mouse *mouse = EditorFrameListener::GetInstance()->GetMouse();

	InitGUI();

	const OIS::MouseState &ms = mouse->getMouseState();
	int x=ms.width/2,
		y=ms.height/2;
	mouse->setMousePosition(x,y);
    gui->setPointerPosition(x, y);	
	gui->showPointer();
}
Example #28
0
void Objects::insertMesh (const MWWorld::Ptr& ptr, const std::string& mesh, bool light)
{
    Ogre::SceneNode* insert = ptr.getRefData().getBaseNode();
    assert(insert);

    Ogre::AxisAlignedBox bounds = Ogre::AxisAlignedBox::BOX_NULL;
    NifOgre::ObjectList objects = NifOgre::Loader::createObjects(insert, mesh);
    for(size_t i = 0;i < objects.mEntities.size();i++)
        bounds.merge(objects.mEntities[i]->getWorldBoundingBox(true));

    Ogre::Vector3 extents = bounds.getSize();
    extents *= insert->getScale();
    float size = std::max(std::max(extents.x, extents.y), extents.z);

    bool small = (size < Settings::Manager::getInt("small object size", "Viewing distance")) && Settings::Manager::getBool("limit small object distance", "Viewing distance");

    // do not fade out doors. that will cause holes and look stupid
    if (ptr.getTypeName().find("Door") != std::string::npos)
        small = false;

    if (mBounds.find(ptr.getCell()) == mBounds.end())
        mBounds[ptr.getCell()] = Ogre::AxisAlignedBox::BOX_NULL;
    mBounds[ptr.getCell()].merge(bounds);

    bool anyTransparency = false;
    for(size_t i = 0;!anyTransparency && i < objects.mEntities.size();i++)
    {
        Ogre::Entity *ent = objects.mEntities[i];
        for(unsigned int i=0;!anyTransparency && i < ent->getNumSubEntities(); ++i)
        {
            anyTransparency = ent->getSubEntity(i)->getMaterial()->isTransparent();
        }
    }

    if(!mIsStatic || !Settings::Manager::getBool("use static geometry", "Objects") ||
       anyTransparency || objects.mParticles.size() > 0)
    {
        for(size_t i = 0;i < objects.mEntities.size();i++)
        {
            Ogre::Entity *ent = objects.mEntities[i];
            for(unsigned int i=0; i < ent->getNumSubEntities(); ++i)
            {
                Ogre::SubEntity* subEnt = ent->getSubEntity(i);
                subEnt->setRenderQueueGroup(subEnt->getMaterial()->isTransparent() ? RQG_Alpha : RQG_Main);
            }
            ent->setRenderingDistance(small ? Settings::Manager::getInt("small object distance", "Viewing distance") : 0);
            ent->setVisibilityFlags(mIsStatic ? (small ? RV_StaticsSmall : RV_Statics) : RV_Misc);
        }
        for(size_t i = 0;i < objects.mParticles.size();i++)
        {
            Ogre::ParticleSystem *part = objects.mParticles[i];
            // TODO: Check the particle system's material for actual transparency
            part->setRenderQueueGroup(RQG_Alpha);
            part->setRenderingDistance(small ? Settings::Manager::getInt("small object distance", "Viewing distance") : 0);
            part->setVisibilityFlags(mIsStatic ? (small ? RV_StaticsSmall : RV_Statics) : RV_Misc);
        }
    }
    else
    {
        Ogre::StaticGeometry* sg = 0;

        if (small)
        {
            if( mStaticGeometrySmall.find(ptr.getCell()) == mStaticGeometrySmall.end())
            {
                uniqueID = uniqueID +1;
                sg = mRenderer.getScene()->createStaticGeometry( "sg" + Ogre::StringConverter::toString(uniqueID));
                mStaticGeometrySmall[ptr.getCell()] = sg;

                sg->setRenderingDistance(Settings::Manager::getInt("small object distance", "Viewing distance"));
            }
            else
                sg = mStaticGeometrySmall[ptr.getCell()];
        }
        else
        {
            if( mStaticGeometry.find(ptr.getCell()) == mStaticGeometry.end())
            {

                uniqueID = uniqueID +1;
                sg = mRenderer.getScene()->createStaticGeometry( "sg" + Ogre::StringConverter::toString(uniqueID));
                mStaticGeometry[ptr.getCell()] = sg;
            }
            else
                sg = mStaticGeometry[ptr.getCell()];
        }

        // This specifies the size of a single batch region.
        // If it is set too high:
        //  - there will be problems choosing the correct lights
        //  - the culling will be more inefficient
        // If it is set too low:
        //  - there will be too many batches.
        sg->setRegionDimensions(Ogre::Vector3(2500,2500,2500));

        sg->setVisibilityFlags(small ? RV_StaticsSmall : RV_Statics);

        sg->setCastShadows(true);

        sg->setRenderQueueGroup(RQG_Main);

        std::vector<Ogre::Entity*>::reverse_iterator iter = objects.mEntities.rbegin();
        while(iter != objects.mEntities.rend())
        {
            Ogre::Node *node = (*iter)->getParentNode();
            sg->addEntity(*iter, node->_getDerivedPosition(), node->_getDerivedOrientation(), node->_getDerivedScale());

            (*iter)->detachFromParent();
            mRenderer.getScene()->destroyEntity(*iter);
            iter++;
        }
    }

    if (light)
    {
        insertLight(ptr, objects.mSkelBase, bounds.getCenter() - insert->_getDerivedPosition());
    }
}