GPUSurfFeatureDetector::GPUSurfFeatureDetector(Ogre::Cuda::Root* root, int nbOctave, int nbFeatureMax)
: mCudaRoot(root)
{
	mOgreIsAllocated = false;
	mCudaIsAllocated = false;

	mWidth          = 0;
	mHeight         = 0;
	mNbFeatureMax   = nbFeatureMax;
	mNbOctave       = nbOctave;
	mThreshold      = 0.003f;

	mNbFeatureFound = 0;
	mGPGPURoot = new Ogre::GPGPU::Root;

	mWebcamTexture = Ogre::TextureManager::getSingleton().createManual("WebcamVideoTexture", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::TEX_TYPE_2D, 640,  480,  0, Ogre::PF_R8G8B8, Ogre::TU_RENDERTARGET);

	//Create Webcam Material
	Ogre::MaterialPtr material = Ogre::MaterialManager::getSingleton().create("WebcamVideoMaterial", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
	Ogre::Technique *technique = material->createTechnique();
	technique->createPass();
	material->getTechnique(0)->getPass(0)->setLightingEnabled(false);
	material->getTechnique(0)->getPass(0)->setDepthWriteEnabled(false);
	material->getTechnique(0)->getPass(0)->createTextureUnitState("WebcamVideoTexture");
}
	//--------------------------------------------------------------------------------
	void MaterialUtil::updateSelectedVersion(const MaterialPtr& _material)
	{
		String name = _material->getName();
		String selName = getSelectedVersionName(name);
		MaterialPtr material, selectedMaterial;
		if(selName == name)
		{
			name = getUnselectedVersionName(selName);
			selectedMaterial = _material;
			material = MaterialManager::getSingleton().getByName(name);
		}
		else
		{
			material = _material;
			selectedMaterial = MaterialManager::getSingleton().getByName(selName);
		}
		
		if(!material.isNull() && !selectedMaterial.isNull())
		{
			material->copyDetailsTo(selectedMaterial);
			Ogre::Technique* technique = selectedMaterial->getBestTechnique();
			Pass* pass0 = technique->getPass(0);
			Pass* passNew = technique->createPass();
			passNew->setDiffuse(1, 1, 1, 1);
			passNew->setPolygonMode(Ogre::PM_WIREFRAME);

			if(pass0->getNumTextureUnitStates() != 0)
			{
				Ogre::TextureUnitState* tu = pass0->getTextureUnitState(0);
				tu->setColourOperationEx(Ogre::LBX_MODULATE, 
					Ogre::LBS_TEXTURE, Ogre::LBS_MANUAL,
					ColourValue::White, ColourValue(1, 0.6f, 0.6f, 1));
			}
		}
	}
示例#3
0
文件: Simple.cpp 项目: Arsakes/ember
bool Simple::compileMaterial(Ogre::MaterialPtr material)
{
	material->removeAllTechniques();
	Ogre::Technique* technique = material->createTechnique();
	for (SurfaceLayerStore::const_iterator I = mTerrainPageSurfaces.begin(); I != mTerrainPageSurfaces.end(); ++I) {
		const TerrainPageSurfaceLayer* surfaceLayer = I->second;
		if (I == mTerrainPageSurfaces.begin()) {
			Ogre::Pass* pass = technique->createPass();
			pass->setLightingEnabled(false);
			//add the first layer of the terrain, no alpha or anything
			Ogre::TextureUnitState * textureUnitState = pass->createTextureUnitState();
			textureUnitState->setTextureScale(1.0f / surfaceLayer->getScale(), 1.0f / surfaceLayer->getScale());
			textureUnitState->setTextureName(surfaceLayer->getDiffuseTextureName());
			textureUnitState->setTextureCoordSet(0);
		} else {
			if (surfaceLayer->intersects(*mGeometry)) {
				addPassToTechnique(*mGeometry, technique, surfaceLayer);
			}
		}
	}
	if (mTerrainPageShadow) {
		addShadow(technique, mTerrainPageShadow, material);
	}
	material->load();
	if (material->getNumSupportedTechniques() == 0) {
		S_LOG_WARNING("The material '" << material->getName() << "' has no supported techniques. The reason for this is: \n" << material->getUnsupportedTechniquesExplanation());
		return false;
	}
	return true;
}
示例#4
0
bool Simple::compileMaterial(Ogre::MaterialPtr material, std::set<std::string>& managedTextures) const
{
	material->removeAllTechniques();
	Ogre::Technique* technique = material->createTechnique();
	if (!mTerrainPageSurfaces.empty()) {
		//First add a base pass
		auto surfaceLayer = mTerrainPageSurfaces.begin()->second;
		Ogre::Pass* pass = technique->createPass();
		pass->setLightingEnabled(false);
		Ogre::TextureUnitState * textureUnitState = pass->createTextureUnitState();
		textureUnitState->setTextureScale(1.0f / surfaceLayer->getScale(), 1.0f / surfaceLayer->getScale());
		textureUnitState->setTextureName(surfaceLayer->getDiffuseTextureName());
		textureUnitState->setTextureCoordSet(0);

		for (auto& layer : mLayers) {
			addPassToTechnique(*mGeometry, technique, layer, managedTextures);
		}
	}
	if (mTerrainPageShadow) {
		addShadow(technique, mTerrainPageShadow, material, managedTextures);
	}

//	addLightingPass(technique, managedTextures);

	material->load();
	if (material->getNumSupportedTechniques() == 0) {
		S_LOG_WARNING("The material '" << material->getName() << "' has no supported techniques. The reason for this is: \n" << material->getUnsupportedTechniquesExplanation());
		return false;
	}
	return true;
}
示例#5
0
bool OgreARAppLogic::initAR()
{
	//INIT Realidad aumentada
	if ( !userInit(this) ) return false; // user defined function to init AR
	if(mWidth==0 || mHeight==0 || mBuffer==0) {
		std::cout << "Image size or buffer not defined in user-defined init function" << std::endl;
		return false;
	}

	// create background texture
	mPixelBox = Ogre::PixelBox(mWidth, mHeight, 1, Ogre::PF_R8G8B8, mBuffer);
	// Create Texture
	mTexture = Ogre::TextureManager::getSingleton().createManual(
			"CameraTexture",
			Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
			Ogre::TEX_TYPE_2D,
			mWidth,
			mHeight,
			0,
			Ogre::PF_R8G8B8,
			Ogre::TU_DYNAMIC_WRITE_ONLY_DISCARDABLE);	

	//Create Camera Material
	MaterialPtr material = MaterialManager::getSingleton().create("CameraMaterial", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
	Ogre::Technique *technique = material->createTechnique();
	technique->createPass();
	material->getTechnique(0)->getPass(0)->setLightingEnabled(false);
	material->getTechnique(0)->getPass(0)->setDepthWriteEnabled(false);
	material->getTechnique(0)->getPass(0)->createTextureUnitState("CameraTexture");
	return true;
}
//-----------------------------------------------------------------------
Ogre::TextureUnitState* MaterialTab::forceCreateFirstTexture(const Ogre::String textureName)
{
	// Ignore some materials because they result in a crash while unloading
	wxString materialName = mMaterialListBox->GetStringSelection();
	if (materialName == wxT("DefaultSettings"))
		return 0;

	Ogre::Technique* technique = 0;
	Ogre::TextureUnitState* texture = 0;
	Ogre::Pass* pass = getFirstPass();
	if (pass)
	{
		// There is a pass, check for textures or create one
		if (pass->getNumTextureUnitStates() > 0)
		{
			pass->removeAllTextureUnitStates();
		}
		texture = pass->createTextureUnitState(textureName);
	}
	else
	{
		// There is no pass
		wxString materialName = mMaterialListBox->GetStringSelection();
		Ogre::String name = wx2ogre(materialName);
		Ogre::MaterialPtr material = Ogre::MaterialManager::getSingleton().getByName(name);
		if (!material.isNull())
		{
			material->load();
			if (material->getNumTechniques() > 0)
			{
				technique = material->getBestTechnique(); // Get the best technique
				pass = technique->createPass();
				texture = pass->createTextureUnitState(textureName);
			}
			else
			{
				// There is no technique, no pass and no textureunitstate
				technique = material->createTechnique();
				pass = technique->createPass();
				texture = pass->createTextureUnitState(textureName);
			}
		}
	}

	return texture;
}
Ogre::Technique* GBufferSchemeHandler::handleSchemeNotFound(unsigned short schemeIndex, 
		const Ogre::String& schemeName, Ogre::Material* originalMaterial, unsigned short lodIndex, 
		const Ogre::Renderable* rend)
{
	Ogre::MaterialManager& matMgr = Ogre::MaterialManager::getSingleton();
	Ogre::String curSchemeName = matMgr.getActiveScheme();
	matMgr.setActiveScheme(Ogre::MaterialManager::DEFAULT_SCHEME_NAME);
	Ogre::Technique* originalTechnique = originalMaterial->getBestTechnique(lodIndex, rend);
	matMgr.setActiveScheme(curSchemeName);

	Ogre::Technique* gBufferTech = originalMaterial->createTechnique();
	gBufferTech->removeAllPasses();
	gBufferTech->setSchemeName(schemeName);

	Ogre::Technique* noGBufferTech = originalMaterial->createTechnique();
	noGBufferTech->removeAllPasses();
	noGBufferTech->setSchemeName("NoGBuffer");

	for (unsigned short i=0; i<originalTechnique->getNumPasses(); i++)
	{
		Ogre::Pass* originalPass = originalTechnique->getPass(i);
		PassProperties props = inspectPass(originalPass, lodIndex, rend);
		
		if (!props.isDeferred)
		{
			//Just copy the technique so it gets rendered regularly
			Ogre::Pass* clonePass = noGBufferTech->createPass();
			*clonePass = *originalPass;
			continue;
		}

		Ogre::Pass* newPass = gBufferTech->createPass();
		MaterialGenerator::Perm perm = getPermutation(props);

		const Ogre::MaterialPtr& templateMat = mMaterialGenerator.getMaterial(perm);
    	
		//We assume that the GBuffer technique contains only one pass. But its true.
		*newPass = *(templateMat->getTechnique(0)->getPass(0));
		fillPass(newPass, originalPass, props);    
	}
    
	return gBufferTech;
}
示例#8
0
void OgreAppLogic::initTracking(int width, int height)
{
	mWebcamBufferL8 = new unsigned char[width*height];
	mTrackingSystem->init(width, height);

	//Create Webcam Material
	MaterialPtr material = MaterialManager::getSingleton().create("WebcamMaterial", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
	Ogre::Technique *technique = material->createTechnique();
	technique->createPass();
	material->getTechnique(0)->getPass(0)->setLightingEnabled(false);
	material->getTechnique(0)->getPass(0)->setDepthWriteEnabled(false);
	material->getTechnique(0)->getPass(0)->createTextureUnitState(colorTextureName);
}
示例#9
0
void MaterialEditor::OnNewPass(wxCommandEvent &e)
{
	if(mMaterial.isNull())
		return;
	Ogre::Technique* pTechinque = m_MaterialTree->getSelecteTechnique();
	if(pTechinque)
	{
		Ogre::Pass* pPass = pTechinque->createPass();
		m_Frame->GetEffectObjectProperty()->InitMaterialEditor(mMaterial,mMaterialName);
		m_MaterialTree->DeleteAllItems();
		m_MaterialTree->AddMaterialToTree(mMaterial,mMaterialName);
		m_MaterialTree->SelectePassItem(pPass);
	}
}
示例#10
0
void MeshResourceMarker::onNewMessage(const MarkerConstPtr& old_message, const MarkerConstPtr& new_message)
{
  ROS_ASSERT(new_message->type == visualization_msgs::Marker::MESH_RESOURCE);

  // flag indicating if the mesh material color needs to be updated
  bool update_color = false;

  scene_node_->setVisible(false);

  if (!entity_ ||
      old_message->mesh_resource != new_message->mesh_resource ||
      old_message->mesh_use_embedded_materials != new_message->mesh_use_embedded_materials)
  {
    reset();

    if (new_message->mesh_resource.empty())
    {
      return;
    }

    if (loadMeshFromResource(new_message->mesh_resource).isNull())
    {
      std::stringstream ss;
      ss << "Mesh resource marker [" << getStringID() << "] could not load [" << new_message->mesh_resource << "]";
      if (owner_)
      {
        owner_->setMarkerStatus(getID(), StatusProperty::Error, ss.str());
      }
      ROS_DEBUG("%s", ss.str().c_str());
      return;
    }

    static uint32_t count = 0;
    std::stringstream ss;
    ss << "mesh_resource_marker_" << count++;
    std::string id = ss.str();
    entity_ = context_->getSceneManager()->createEntity(id, new_message->mesh_resource);
    scene_node_->attachObject(entity_);

    // create a default material for any sub-entities which don't have their own.
    ss << "Material";
    Ogre::MaterialPtr default_material = Ogre::MaterialManager::getSingleton().create(ss.str(), ROS_PACKAGE_NAME);
    default_material->setReceiveShadows(false);
    default_material->getTechnique(0)->setLightingEnabled(true);
    default_material->getTechnique(0)->setAmbient(0.5, 0.5, 0.5);
    materials_.insert(default_material);

    if (new_message->mesh_use_embedded_materials)
    {
      // make clones of all embedded materials so selection works correctly
      S_MaterialPtr materials = getMaterials();

      S_MaterialPtr::iterator it;
      for (it = materials.begin(); it != materials.end(); it++)
      {
        if ((*it)->getName() != "BaseWhiteNoLighting")
        {
          Ogre::MaterialPtr new_material = (*it)->clone(id + (*it)->getName());
          materials_.insert(new_material);
        }
      }

      // make sub-entities use cloned materials
      for (uint32_t i = 0; i < entity_->getNumSubEntities(); ++i)
      {
        std::string mat_name = entity_->getSubEntity(i)->getMaterialName();
        if (mat_name != "BaseWhiteNoLighting")
        {
          entity_->getSubEntity(i)->setMaterialName(id + mat_name);
        }
        else
        {
          // BaseWhiteNoLighting is the default material Ogre uses
          // when it sees a mesh with no material.  Here we replace
          // that with our default_material which gets colored with
          // new_message->color.
          entity_->getSubEntity(i)->setMaterial(default_material);
        }
      }
    }
    else
    {
      entity_->setMaterial(default_material);
    }

    // add a pass to every material to perform the color tinting
    S_MaterialPtr::iterator material_it;
    for (material_it = materials_.begin(); material_it != materials_.end(); material_it++)
    {
      Ogre::Technique* technique = (*material_it)->getTechnique(0);
      color_tint_passes_.push_back(technique->createPass());
    }

    // always update color on resource change
    update_color = true;

    handler_.reset(new MarkerSelectionHandler(this, MarkerID(new_message->ns, new_message->id), context_));
    handler_->addTrackedObject(entity_);
  }
  else
  {
    // underlying mesh resource has not changed but if the color has
    //  then we need to update the materials color
    if (!old_message
        || old_message->color.r != new_message->color.r
        || old_message->color.g != new_message->color.g
        || old_message->color.b != new_message->color.b
        || old_message->color.a != new_message->color.a)
    {
      update_color = true;
    }
  }

  // update material color
  //  if the mesh_use_embedded_materials is true and color is non-zero
  //  then the color will be used to tint the embedded materials
  if (update_color)
  {
    float r = new_message->color.r;
    float g = new_message->color.g;
    float b = new_message->color.b;
    float a = new_message->color.a;

    Ogre::SceneBlendType blending;
    bool depth_write;

    if (a < 0.9998)
    {
      blending = Ogre::SBT_TRANSPARENT_ALPHA;
      depth_write = false;
    }
    else
    {
      blending = Ogre::SBT_REPLACE;
      depth_write = true;
    }

    for (std::vector<Ogre::Pass*>::iterator it = color_tint_passes_.begin();
         it != color_tint_passes_.end();
         ++it)
    {
      (*it)->setAmbient(0.5 * r, 0.5 * g, 0.5 * b);
      (*it)->setDiffuse(r, g, b, a);
      (*it)->setSceneBlending(blending);
      (*it)->setDepthWriteEnabled(depth_write);
      (*it)->setLightingEnabled(true);
    }
  }

  Ogre::Vector3 pos, scale;
  Ogre::Quaternion orient;
  transform(new_message, pos, orient, scale);

  scene_node_->setVisible(true);
  setPosition(pos);
  setOrientation(orient);

  scene_node_->setScale(scale);
}
示例#11
0
    Ogre::MaterialPtr MaterialGenerator::create(bool renderCompositeMap, bool displayCompositeMap)
    {
        assert(!renderCompositeMap || !displayCompositeMap);

        static int count = 0;
        std::stringstream name;
        name << "terrain/mat" << count++;

        if (!mShaders)
        {
            Ogre::MaterialPtr mat = Ogre::MaterialManager::getSingleton().create(name.str(),
                                                               Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
            Ogre::Technique* technique = mat->getTechnique(0);
            technique->removeAllPasses();

            if (displayCompositeMap)
            {
                Ogre::Pass* pass = technique->createPass();
                pass->setVertexColourTracking(Ogre::TVC_AMBIENT|Ogre::TVC_DIFFUSE);
                pass->createTextureUnitState(mCompositeMap)->setTextureAddressingMode(Ogre::TextureUnitState::TAM_CLAMP);
            }
            else
            {
                assert(mLayerList.size() == mBlendmapList.size()+1);
                std::vector<Ogre::TexturePtr>::iterator blend = mBlendmapList.begin();
                for (std::vector<LayerInfo>::iterator layer = mLayerList.begin(); layer != mLayerList.end(); ++layer)
                {
                    Ogre::Pass* pass = technique->createPass();
                    pass->setLightingEnabled(false);
                    pass->setVertexColourTracking(Ogre::TVC_NONE);
                    // TODO: How to handle fog?
                    pass->setFog(true, Ogre::FOG_NONE);

                    bool first = (layer == mLayerList.begin());

                    Ogre::TextureUnitState* tus;

                    if (!first)
                    {
                        pass->setSceneBlending(Ogre::SBT_TRANSPARENT_ALPHA);
                        pass->setDepthFunction(Ogre::CMPF_EQUAL);

                        tus = pass->createTextureUnitState((*blend)->getName());
                        tus->setAlphaOperation(Ogre::LBX_BLEND_TEXTURE_ALPHA,
                                               Ogre::LBS_TEXTURE,
                                               Ogre::LBS_TEXTURE);
                        tus->setColourOperationEx(Ogre::LBX_BLEND_DIFFUSE_ALPHA,
                                                  Ogre::LBS_TEXTURE,
                                                  Ogre::LBS_TEXTURE);
                        tus->setIsAlpha(true);
                        tus->setTextureAddressingMode(Ogre::TextureUnitState::TAM_CLAMP);

                        float scale = (16/(16.f+1.f));
                        tus->setTextureScale(1.f/scale,1.f/scale);
                    }

                    // Add the actual layer texture on top of the alpha map.
                    tus = pass->createTextureUnitState(layer->mDiffuseMap);
                    if (!first)
                        tus->setColourOperationEx(Ogre::LBX_BLEND_DIFFUSE_ALPHA,
                                                  Ogre::LBS_TEXTURE,
                                                  Ogre::LBS_CURRENT);

                    tus->setTextureScale(1/16.f,1/16.f);

                    if (!first)
                        ++blend;
                }

                if (!renderCompositeMap)
                {
                    Ogre::Pass* lightingPass = technique->createPass();
                    lightingPass->setSceneBlending(Ogre::SBT_MODULATE);
                    lightingPass->setVertexColourTracking(Ogre::TVC_AMBIENT|Ogre::TVC_DIFFUSE);
                    lightingPass->setFog(true, Ogre::FOG_NONE);
                }
            }

            return mat;
        }
#if TERRAIN_USE_SHADER
        else
        {
            sh::MaterialInstance* material = sh::Factory::getInstance().createMaterialInstance (name.str());
            material->setProperty ("allow_fixed_function", sh::makeProperty<sh::BooleanValue>(new sh::BooleanValue(false)));

            if (displayCompositeMap)
            {
                sh::MaterialInstancePass* p = material->createPass ();

                p->setProperty ("vertex_program", sh::makeProperty<sh::StringValue>(new sh::StringValue("terrain_vertex")));
                p->setProperty ("fragment_program", sh::makeProperty<sh::StringValue>(new sh::StringValue("terrain_fragment")));
                p->mShaderProperties.setProperty ("is_first_pass", sh::makeProperty(new sh::BooleanValue(true)));
                p->mShaderProperties.setProperty ("render_composite_map", sh::makeProperty(new sh::BooleanValue(false)));
                p->mShaderProperties.setProperty ("display_composite_map", sh::makeProperty(new sh::BooleanValue(true)));
                p->mShaderProperties.setProperty ("num_layers", sh::makeProperty (new sh::StringValue("0")));
                p->mShaderProperties.setProperty ("num_blendmaps", sh::makeProperty (new sh::StringValue("0")));
                p->mShaderProperties.setProperty ("normal_map_enabled", sh::makeProperty (new sh::BooleanValue(false)));
                p->mShaderProperties.setProperty ("parallax_enabled", sh::makeProperty (new sh::BooleanValue(false)));
                p->mShaderProperties.setProperty ("normal_maps",
                                                  sh::makeProperty (new sh::IntValue(0)));

                sh::MaterialInstanceTextureUnit* tex = p->createTextureUnit ("compositeMap");
                tex->setProperty ("direct_texture", sh::makeProperty (new sh::StringValue(mCompositeMap)));
                tex->setProperty ("tex_address_mode", sh::makeProperty (new sh::StringValue("clamp")));

                // shadow. TODO: repeated, put in function
                if (mShadows)
                {
                    for (int i = 0; i < (mSplitShadows ? 3 : 1); ++i)
                    {
                        sh::MaterialInstanceTextureUnit* shadowTex = p->createTextureUnit ("shadowMap" + Ogre::StringConverter::toString(i));
                        shadowTex->setProperty ("content_type", sh::makeProperty<sh::StringValue> (new sh::StringValue("shadow")));
                    }
                }
                p->mShaderProperties.setProperty ("shadowtexture_offset", sh::makeProperty (new sh::StringValue(
                    Ogre::StringConverter::toString(1))));

                p->mShaderProperties.setProperty ("pass_index", sh::makeProperty(new sh::IntValue(0)));
            }
            else
            {

                bool shadows = mShadows && !renderCompositeMap;

                int layerOffset = 0;
                while (layerOffset < (int)mLayerList.size())
                {
                    int blendmapOffset = (layerOffset == 0) ? 1 : 0; // the first layer of the first pass is the base layer and does not need a blend map

                    // Check how many layers we can fit in this pass
                    int numLayersInThisPass = 0;
                    int numBlendTextures = 0;
                    std::vector<std::string> blendTextures;
                    int remainingTextureUnits = OGRE_MAX_TEXTURE_LAYERS;
                    if (shadows)
                        remainingTextureUnits -= (mSplitShadows ? 3 : 1);
                    while (remainingTextureUnits && layerOffset + numLayersInThisPass < (int)mLayerList.size())
                    {
                        int layerIndex = numLayersInThisPass + layerOffset;

                        int neededTextureUnits=0;
                        int neededBlendTextures=0;

                        if (layerIndex != 0)
                        {
                            std::string blendTextureName = mBlendmapList[getBlendmapIndexForLayer(layerIndex)]->getName();
                            if (std::find(blendTextures.begin(), blendTextures.end(), blendTextureName) == blendTextures.end())
                            {
                                blendTextures.push_back(blendTextureName);
                                ++neededBlendTextures;
                                ++neededTextureUnits; // blend texture
                            }
                        }
                        ++neededTextureUnits; // layer texture

                        // Check if this layer has a normal map
                        if (mNormalMapping && !mLayerList[layerIndex].mNormalMap.empty() && !renderCompositeMap)
                            ++neededTextureUnits; // normal map
                        if (neededTextureUnits <= remainingTextureUnits)
                        {
                            // We can fit another!
                            remainingTextureUnits -= neededTextureUnits;
                            numBlendTextures += neededBlendTextures;
                            ++numLayersInThisPass;
                        }
                        else
                            break; // We're full
                    }


                    sh::MaterialInstancePass* p = material->createPass ();
                    p->setProperty ("vertex_program", sh::makeProperty<sh::StringValue>(new sh::StringValue("terrain_vertex")));
                    p->setProperty ("fragment_program", sh::makeProperty<sh::StringValue>(new sh::StringValue("terrain_fragment")));
                    if (layerOffset != 0)
                    {
                        p->setProperty ("scene_blend", sh::makeProperty(new sh::StringValue("alpha_blend")));
                        // Only write if depth is equal to the depth value written by the previous pass.
                        p->setProperty ("depth_func", sh::makeProperty(new sh::StringValue("equal")));
                    }

                    p->mShaderProperties.setProperty ("render_composite_map", sh::makeProperty(new sh::BooleanValue(renderCompositeMap)));
                    p->mShaderProperties.setProperty ("display_composite_map", sh::makeProperty(new sh::BooleanValue(displayCompositeMap)));

                    p->mShaderProperties.setProperty ("num_layers", sh::makeProperty (new sh::StringValue(Ogre::StringConverter::toString(numLayersInThisPass))));
                    p->mShaderProperties.setProperty ("num_blendmaps", sh::makeProperty (new sh::StringValue(Ogre::StringConverter::toString(numBlendTextures))));
                    p->mShaderProperties.setProperty ("normal_map_enabled",
                                                      sh::makeProperty (new sh::BooleanValue(false)));

                    // blend maps
                    // the index of the first blend map used in this pass
                    int blendmapStart;
                    if (mLayerList.size() == 1) // special case. if there's only one layer, we don't need blend maps at all
                        blendmapStart = 0;
                    else
                        blendmapStart = getBlendmapIndexForLayer(layerOffset+blendmapOffset);
                    for (int i = 0; i < numBlendTextures; ++i)
                    {
                        sh::MaterialInstanceTextureUnit* blendTex = p->createTextureUnit ("blendMap" + Ogre::StringConverter::toString(i));
                        blendTex->setProperty ("direct_texture", sh::makeProperty (new sh::StringValue(mBlendmapList[blendmapStart+i]->getName())));
                        blendTex->setProperty ("tex_address_mode", sh::makeProperty (new sh::StringValue("clamp")));
                    }

                    // layer maps
                    bool anyNormalMaps = false;
                    bool anyParallax = false;
                    size_t normalMaps = 0;
                    for (int i = 0; i < numLayersInThisPass; ++i)
                    {
                        const LayerInfo& layer = mLayerList[layerOffset+i];
                        // diffuse map
                        sh::MaterialInstanceTextureUnit* diffuseTex = p->createTextureUnit ("diffuseMap" + Ogre::StringConverter::toString(i));
                        diffuseTex->setProperty ("direct_texture", sh::makeProperty (new sh::StringValue(layer.mDiffuseMap)));

                        // normal map (optional)
                        bool useNormalMap = mNormalMapping && !mLayerList[layerOffset+i].mNormalMap.empty() && !renderCompositeMap;
                        bool useParallax = useNormalMap && mParallaxMapping && layer.mParallax;
                        bool useSpecular = layer.mSpecular;
                        if (useNormalMap)
                        {
                            anyNormalMaps = true;
                            anyParallax = anyParallax || useParallax;
                            sh::MaterialInstanceTextureUnit* normalTex = p->createTextureUnit ("normalMap" + Ogre::StringConverter::toString(i));
                            normalTex->setProperty ("direct_texture", sh::makeProperty (new sh::StringValue(layer.mNormalMap)));
                        }
                        p->mShaderProperties.setProperty ("use_normal_map_" + Ogre::StringConverter::toString(i),
                                                          sh::makeProperty (new sh::BooleanValue(useNormalMap)));
                        p->mShaderProperties.setProperty ("use_parallax_" + Ogre::StringConverter::toString(i),
                                                          sh::makeProperty (new sh::BooleanValue(useParallax)));
                        p->mShaderProperties.setProperty ("use_specular_" + Ogre::StringConverter::toString(i),
                                                          sh::makeProperty (new sh::BooleanValue(useSpecular)));
                        boost::hash_combine(normalMaps, useNormalMap);
                        boost::hash_combine(normalMaps, useNormalMap && layer.mParallax);
                        boost::hash_combine(normalMaps, useSpecular);

                        if (i+layerOffset > 0)
                        {
                            int blendTextureIndex = getBlendmapIndexForLayer(layerOffset+i);
                            std::string blendTextureComponent = getBlendmapComponentForLayer(layerOffset+i);
                            p->mShaderProperties.setProperty ("blendmap_component_" + Ogre::StringConverter::toString(i),
                                                              sh::makeProperty (new sh::StringValue(Ogre::StringConverter::toString(blendTextureIndex-blendmapStart) + "." + blendTextureComponent)));
                        }
                        else
                        {
                            // just to make it shut up about blendmap_component_0 not existing in the first pass.
                            // it might be retrieved, but will never survive the preprocessing step.
                            p->mShaderProperties.setProperty ("blendmap_component_" + Ogre::StringConverter::toString(i),
                                sh::makeProperty (new sh::StringValue("")));
                        }
                    }
                    p->mShaderProperties.setProperty ("normal_map_enabled",
                                                      sh::makeProperty (new sh::BooleanValue(anyNormalMaps)));
                    p->mShaderProperties.setProperty ("parallax_enabled",
                                                      sh::makeProperty (new sh::BooleanValue(anyParallax)));
                    // Since the permutation handler can't handle dynamic property names,
                    // combine normal map settings for all layers into one value
                    p->mShaderProperties.setProperty ("normal_maps",
                                                      sh::makeProperty (new sh::IntValue(normalMaps)));

                    // shadow
                    if (shadows)
                    {
                        for (int i = 0; i < (mSplitShadows ? 3 : 1); ++i)
                        {
                            sh::MaterialInstanceTextureUnit* shadowTex = p->createTextureUnit ("shadowMap" + Ogre::StringConverter::toString(i));
                            shadowTex->setProperty ("content_type", sh::makeProperty<sh::StringValue> (new sh::StringValue("shadow")));
                        }
                    }
                    p->mShaderProperties.setProperty ("shadowtexture_offset", sh::makeProperty (new sh::StringValue(
                        Ogre::StringConverter::toString(numBlendTextures + numLayersInThisPass))));

                    // Make sure the pass index is fed to the permutation handler, because blendmap components may be different
                    p->mShaderProperties.setProperty ("pass_index", sh::makeProperty(new sh::IntValue(layerOffset)));

                    assert ((int)p->mTexUnits.size() == OGRE_MAX_TEXTURE_LAYERS - remainingTextureUnits);

                    layerOffset += numLayersInThisPass;
                }
            }
        }
#endif
        return Ogre::MaterialManager::getSingleton().getByName(name.str());
    }
示例#12
0
void MaterialGenerator::generate()
{	
	mMaterial = prepareMaterial(mDef->getName());
	
	// reset some attributes
	resetTexUnitCounter();
	
	// choose textures from list (depending on user iTexSize setting)
	chooseTextures();
	
	// -------------------------- Main technique ----------------------------- //
	Ogre::Technique* technique = mMaterial->createTechnique();
	
	// Main pass
	Ogre::Pass* pass = technique->createPass();
	
	pass->setAmbient( mDef->mProps->ambient.x, mDef->mProps->ambient.y, mDef->mProps->ambient.z );
	pass->setDiffuse( mDef->mProps->diffuse.x, mDef->mProps->diffuse.y, mDef->mProps->diffuse.z, 1.0 );
	
	// shader assumes shininess in specular w component
	pass->setSpecular(mDef->mProps->specular.x, mDef->mProps->specular.y, mDef->mProps->specular.z, mDef->mProps->specular.w);
	
	pass->setCullingMode(chooseCullingMode());
	
	pass->setFog(true); // turn off fixed function fog, we use shaders
		
	if (!mDef->mProps->lighting)
		pass->setLightingEnabled(false);
	
	if (mDef->mProps->sceneBlend == SBM_ALPHA_BLEND)
		pass->setSceneBlending(SBT_TRANSPARENT_ALPHA);
	else if (mDef->mProps->sceneBlend == SBM_COLOUR_BLEND)
		pass->setSceneBlending(SBT_TRANSPARENT_COLOUR);
	else if (mDef->mProps->sceneBlend == SBM_ADD)
		pass->setSceneBlending(SBT_ADD);
	else if (mDef->mProps->sceneBlend == SBM_MODULATE)
		pass->setSceneBlending(SBT_MODULATE);
		
	pass->setDepthWriteEnabled( mDef->mProps->depthWrite );
		
	pass->setDepthCheckEnabled( mDef->mProps->depthCheck );
		
	pass->setTransparentSortingEnabled( mDef->mProps->transparentSorting );
	
	pass->setAlphaRejectFunction( mDef->mProps->alphaRejectFunc );
	pass->setAlphaRejectValue( mDef->mProps->alphaRejectValue );
	
	if (mDef->mProps->depthBias != 0.f)
		pass->setDepthBias( mDef->mProps->depthBias );
	
	createTexUnits(pass);
	
	// create shaders		
	if (!mShaderCached)
	{
		try
		{
			mVertexProgram = createVertexProgram();
			mFragmentProgram = createFragmentProgram();
		}
		catch (Ogre::Exception& e) {
			LogO(e.getFullDescription());
		}
		
		//!todo put this code into a function for reusability in other material generators
		if (mFragmentProgram.isNull() || mVertexProgram.isNull() || 
			!mFragmentProgram->isSupported() || !mVertexProgram->isSupported())
		{
			LogO("[MaterialFactory] WARNING: shader for material '" + mDef->getName()
				+ "' is not supported");
				
			LogO("[MaterialFactory] Vertex program source: ");
			StringUtil::StrStreamType vSourceStr;
			generateVertexProgramSource(vSourceStr);
			LogO(vSourceStr.str());
			LogO("[MaterialFactory] Fragment program source: ");
			StringUtil::StrStreamType fSourceStr;
			generateFragmentProgramSource(fSourceStr);
			LogO(fSourceStr.str());
			
			mVertexProgram.setNull(); mFragmentProgram.setNull();
			return;
		}
	}
	
	pass->setVertexProgram(mVertexProgram->getName());
	pass->setFragmentProgram(mFragmentProgram->getName());
	
	//set shadow caster
	technique->setShadowCasterMaterial(chooseShadowCasterMaterial());
	if (mShaderCached)
	{
		// set individual material shader params
		individualVertexProgramParams(pass->getVertexProgramParameters());
		individualFragmentProgramParams(pass->getFragmentProgramParameters());
	}
	// ----------------------------------------------------------------------- //
	
	createSSAOTechnique();
	createOccluderTechnique();
		
	// indicate we need enable/disable wind parameter
	// only needed for trees (wind == 2) because the wind effect has to be disabled before rendering impostors
	if (mShader->wind == 2)
		mParent->windMtrs.push_back( mDef->getName() );
		
	if (mDef->mProps->fog)
		mParent->fogMtrs.push_back( mDef->getName() );
	
	
	/// uncomment to export to .material
	//LogO(mDef->getName());
	/**
	//if (mDef->getName() == "Water_cyan")
	/*{
		MaterialSerializer serializer;
		serializer.exportMaterial(mMaterial, "water.material");
	}
	/**/
	
	/// uncomment to see full shader source code in log
	/**
	LogO(mDef->getName());
	if (StringUtil::startsWith(mDef->getName(), "FluidWater" ))  //"water" //_cyan"
	{
		LogO("[MaterialFactory] Vertex program source: ");
		StringUtil::StrStreamType vSourceStr;
		generateVertexProgramSource(vSourceStr);
		LogO(vSourceStr.str());
		LogO("[MaterialFactory] Fragment program source: ");
		StringUtil::StrStreamType fSourceStr;
		generateFragmentProgramSource(fSourceStr);
		LogO(fSourceStr.str());
	}
	/**/
}
示例#13
0
/****************************************************************************
**
** Copyright (C) 2014
**
** This file is generated by the Magus toolkit
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
****************************************************************************/

// Include
#include "mainwindow.h"
#include "Editor_dockwidget.h"
#include "constants.h"
#include "sme_asset_material.h"
#include "sme_node_material.h"
#include "sme_asset_technique.h"
#include "sme_node_technique.h"
#include "sme_asset_pass.h"
#include "sme_node_pass.h"
#include "sme_asset_texture_unit.h"
#include "sme_node_texture_unit.h"

//****************************************************************************/
EditorDockWidget::EditorDockWidget(QString title, MainWindow* parent, Qt::WindowFlags flags) : 
	QDockWidget (title, parent, flags), 
	mParent(parent)
{
    mInnerMain = new QMainWindow();
    setWidget(mInnerMain);

    // Perform standard functions
    createActions();
    createMenus();
    createToolBars();

    // Create the node editor widget.
    mNodeEditor = new Magus::QtNodeEditor(this);
    mNodeEditor->setMenuSelectionToCompoundEnabled(false); // Enabling this makes it a bit more complicated
    mNodeEditor->setMenuExpandCompoundsEnabled(false); // No compounds are used
    connect(mNodeEditor, SIGNAL(nodeRemoved(QtNode*)), this, SLOT(nodeDeleted()));
    connect(mNodeEditor, SIGNAL(nodeSelected(QtNode*)), this, SLOT(nodeSelected(QtNode*)));
    mInnerMain->setCentralWidget(mNodeEditor);
    mMaterialNode = 0;
}

//****************************************************************************/
EditorDockWidget::~EditorDockWidget(void)
{
}

//****************************************************************************/
void EditorDockWidget::createActions(void)
{
    mMaterialHToolbarAction = new QAction(QIcon(ICON_MATERIAL), QString("Add a material node to the editor"), this);
    connect(mMaterialHToolbarAction, SIGNAL(triggered()), this, SLOT(doMaterialHToolbarAction()));
    mTechniqueHToolbarAction = new QAction(QIcon(ICON_TECHNIQUE), QString("Add a technique node to the editor"), this);
    connect(mTechniqueHToolbarAction, SIGNAL(triggered()), this, SLOT(doTechniqueHToolbarAction()));
    mPassHToolbarAction = new QAction(QIcon(ICON_PASS), QString("Add a pass node to the editor"), this);
    connect(mPassHToolbarAction, SIGNAL(triggered()), this, SLOT(doPassHToolbarAction()));
    mTextureHToolbarAction = new QAction(QIcon(ICON_TEXTURE), QString("Add a texture unit node to the editor"), this);
    connect(mTextureHToolbarAction, SIGNAL(triggered()), this, SLOT(doTextureHToolbarAction()));
    mCogHToolbarAction = new QAction(QIcon(ICON_COG), QString("Generate material"), this);
    connect(mCogHToolbarAction, SIGNAL(triggered()), this, SLOT(doCogHToolbarAction()));
}

//****************************************************************************/
void EditorDockWidget::createMenus(void)
{

}

//****************************************************************************/
void EditorDockWidget::createToolBars(void)
{
    mHToolBar = new QToolBar();
    mInnerMain->addToolBar(Qt::TopToolBarArea, mHToolBar);
    mHToolBar->setMinimumHeight(TB_ICON_AND_SPACING);
    mHToolBar->setMinimumWidth(1200);
    mHToolBar->addAction(mMaterialHToolbarAction);
    mHToolBar->addAction(mTechniqueHToolbarAction);
    mHToolBar->addAction(mPassHToolbarAction);
    mHToolBar->addAction(mTextureHToolbarAction);
    mHToolBar->addAction(mCogHToolbarAction);
}

//****************************************************************************/
void EditorDockWidget::doMaterialHToolbarAction(void)
{
    // Add a material node; only 1 is allowed
    if (!mMaterialNode)
    {
        mMaterialNode = new Magus::QtNodeMaterial(NODE_TITLE_MATERIAL);
        mNodeEditor->addNode(mMaterialNode);
    }
}

//****************************************************************************/
void EditorDockWidget::doTechniqueHToolbarAction(void)
{
    // Add a technique node
    Magus::QtNodeTechnique* techniqueNode = new Magus::QtNodeTechnique(NODE_TITLE_TECHNIQUE);
    mNodeEditor->addNode(techniqueNode);
}

//****************************************************************************/
void EditorDockWidget::doPassHToolbarAction(void)
{
    // Add a pass node
    Magus::QtNodePass* passNode = new Magus::QtNodePass(NODE_TITLE_PASS);
    mNodeEditor->addNode(passNode);
}

//****************************************************************************/
void EditorDockWidget::doTextureHToolbarAction(void)
{
    // Add a texture unit node
    Magus::QtNodeTextureUnit* textureUnitNode = new Magus::QtNodeTextureUnit(NODE_TITLE_TEXTURE_UNIT);
    mNodeEditor->addNode(textureUnitNode);
}

//****************************************************************************/
void EditorDockWidget::doCogHToolbarAction(void)
{
    if (!mMaterialNode)
        return;

    if (mMaterialNode->getMaterialName().isEmpty())
        return;

    // ---------------------------------------- Create a material ----------------------------------------
    Ogre::LogManager* logManager = Ogre::LogManager::getSingletonPtr();
    Ogre::MaterialManager* materialManager = Ogre::MaterialManager::getSingletonPtr();
    Ogre::String materialName = mMaterialNode->getMaterialName().toStdString(); // Convert to std format
    logManager->logMessage("SME: create Ogre material: " + materialName);
    Ogre::MaterialPtr material = materialManager->create(materialName, "General");

    // Remark: Sceneblending is done for each pass individually, although it is defined on material level

    // ---------------------------------------- Add the technique ----------------------------------------
    Magus::QtNode* node = mMaterialNode->getNodeConnectedToPort(PORT_TECHNIQUE_OUT);
    if (!node)
    {
        logManager->logMessage("SME: No technique node available");
        return;
    }

    Magus::QtNodeTechnique* techniqueNode = static_cast<Magus::QtNodeTechnique*>(node);
    material->removeAllTechniques();
    Ogre::Technique* technique = material->createTechnique();
    technique->removeAllPasses();
    logManager->logMessage("SME: Technique created" + Ogre::StringConverter::toString(material->getNumTechniques()));

    // ---------------------------------------- Add the passes ----------------------------------------
    Magus::QtNodePass* passNode;
    Magus::QtNodeTextureUnit* textureUnitNode;
    Ogre::Pass* pass;
    Ogre::TextureUnitState* textureUnit;
    for (unsigned int i = 1; i < 5; ++i)
    {
        node = techniqueNode->getNodeConnectedToPort(PORT_PASS_OUT, i); // node with the same name
        if (node)
        {
            passNode = static_cast<Magus::QtNodePass*>(node);
            pass = technique->createPass();
            pass->removeAllTextureUnitStates();
            logManager->logMessage("SME: Pass on port nr. " + Ogre::StringConverter::toString(i) + " created");
            propagatePassNodeData(passNode, pass);

            // ---------------------------------------- Add the texture units ----------------------------------------
            for (unsigned int j = 1; j < 9; ++j)
            {
                node = passNode->getNodeConnectedToPort(PORT_TEXTURE_OUT, j);
                if (node)
                {
                    logManager->logMessage("SME: Texture unit on port nr. " +
                                           Ogre::StringConverter::toString(j) +
                                           " of Pass port nr. " +
                                           Ogre::StringConverter::toString(i) +
                                           " created");
                    textureUnitNode = static_cast<Magus::QtNodeTextureUnit*>(node);
                    textureUnit = pass->createTextureUnitState();
                    propagateTextureUnitNodeData(textureUnitNode, textureUnit);
                }
            }
        }
    }

    // Assign the material to the ogrehead
    material->compile();
    material->load();
    mParent->getOgreManager()->getOgreWidget(1)->mEntity->setMaterial(material);
}
示例#14
0
void GActiveMarker::markerCallback(const visualization_msgs::Marker& marker)
{
	int frameNo;
	bool found, renew;
	string name;
	GActiveMarker * tAM;
	vector<Gadget *>::iterator gadIt;
	
	switch (marker.action)
	{
		case visualization_msgs::Marker::DELETE:
			{
				// Make an appropriate name based on the namespace and marker ID
				name = marker.ns + boost::lexical_cast<std::string>(marker.id);
				
				found = false;
				for (gadIt = boss->gadgets.begin(); gadIt != boss->gadgets.end(); gadIt++)
				{
					if ((*gadIt)->name == name)
					{
						found = true;
						break;
					}
				}
				
				// No marker, leave without a sound
				if (!found)
				{
					break;
				}
				
				(*gadIt)->killMe = true;
				
				break;
			}
		
		// ROS has ADD and MODIFY have the same value...
		case visualization_msgs::Marker::ADD:
		//case visualization_msgs::Marker::MODIFY:
			
			// Make an appropriate name based on the namespace and marker ID
			name = marker.ns + boost::lexical_cast<std::string>(marker.id);

			// Get the associated frame
			frameNo = Frame::findFrame(marker.header.frame_id);

			// If we can't find the frame, or it is invalid leave
			if (frameNo < 0)
			{
				return;
			}
			if (!availableFrames[frameNo].valid)
			{
				return;
			}

			// Look for an existing Gadget with this name
			found = false;
			for (gadIt = boss->gadgets.begin(); gadIt != boss->gadgets.end(); gadIt++)
			{
				if ((*gadIt)->name == name)
				{
					found = true;
					break;
				}
			}

			if (found)
			{
				// We're modifying an existing marker
				tAM = (GActiveMarker * )*gadIt;
			}
			else // !found
			{
				// Create a new marker
				tAM = new GActiveMarker(name);
				
				// Create the gadget for this marker
				boss->addGadget(tAM);
				
				// Have the active marker create a scene node (graphicNode)
				tAM->show(true);
			}

			// Set the Gadget's frame
			tAM->sourceFrame = frameNo;

			// If the marker's nature changes, free up all its allocated graphic memory
			if (found)
			{
				if (tAM->markerType != marker.type)
				{
					tAM->cleanup();
					
					renew = true;

					tAM->markerType = marker.type;
				}
				else 
				{
					renew = false;
				}
			}
			else 
			{
				renew = true;
				
				tAM->markerType = marker.type;
			}
			
			switch (marker.type)
			{
				case visualization_msgs::Marker::ARROW:
					{
						if (renew)
						{
							Shape * shape;
						
							if (!tAM->subGraphicNode)
							{
								tAM->subGraphicNode = tAM->graphicNode->createChildSceneNode();
							}
						
							shape = new Shape(Shape::Cone, tAM->scene, tAM->subGraphicNode);
							tAM->shapes.push_back(shape);
							
							shape = new Shape(Shape::RoughCylinder, tAM->scene, tAM->subGraphicNode);
							tAM->shapes.push_back(shape);
						}
						
						Ogre::Vector3 startPoint;
						Ogre::Vector3 endPoint;
						
						if (marker.points.size() > 1)
						{
							startPoint[0] = marker.points[0].x;
							startPoint[1] = marker.points[0].y,
							startPoint[2] = marker.points[0].z;
									
							endPoint[0] = marker.points[1].x;
							endPoint[1] = marker.points[1].y;
							endPoint[2]	= marker.points[1].z;
						}
						else
						{
							if (marker.points.size() == 1)
							{
								tAM->publishStatus(Gadget::WARNING, "To few points to specify an arrow direction, 2 needed");
							}
							
							startPoint[0] = 0;
							startPoint[1] = 0,
							startPoint[2] = 0;
									
							endPoint[0] = 1;
							endPoint[1] = 0;
							endPoint[2]	= 0;
						}
							
						tAM->shapes[0]->alignToLineSegment(startPoint + (endPoint - startPoint) * 0.9,
							endPoint,
							1);
						tAM->shapes[0]->setScale(Ogre::Vector3(marker.scale.y, 
							marker.scale.x * 0.2, 
							marker.scale.y));
							
						tAM->shapes[1]->alignToLineSegment(startPoint,
							endPoint,
							1);
						tAM->shapes[1]->setScale(Ogre::Vector3(marker.scale.y * 0.1, 
							marker.scale.x * 0.8, 
							marker.scale.y * 0.1));
						
						// Set shape properties
						
						tAM->shapes[0]->setColor(Ogre::ColourValue(marker.color.r, marker.color.g,
							marker.color.b, marker.color.a));

						tAM->subGraphicNode->setPosition(Ogre::Vector3(marker.pose.position.x, 
							marker.pose.position.y, marker.pose.position.z));
						tAM->subGraphicNode->setOrientation(Ogre::Quaternion(marker.pose.orientation.w, 
							marker.pose.orientation.x, marker.pose.orientation.y,
							marker.pose.orientation.z));
						
						if (renew)
						{
							tAM->publishStatus(Gadget::OKAY, "Successfully added arrow marker");
						}
						
						break;
					}
					
				case visualization_msgs::Marker::CUBE:
				case visualization_msgs::Marker::SPHERE:
				case visualization_msgs::Marker::CYLINDER:
					{
						if (renew)
						{
							Shape * shape;
												
							switch (marker.type)
							{
								case visualization_msgs::Marker::CUBE:
									shape = new Shape(Shape::Cube, tAM->scene, tAM->graphicNode);
									break;
								case visualization_msgs::Marker::SPHERE:
									shape = new Shape(Shape::Sphere, tAM->scene, tAM->graphicNode);
									break;
								case visualization_msgs::Marker::CYLINDER:
									shape = new Shape(Shape::Cylinder, tAM->scene, tAM->graphicNode);
									break;
							}
							
							tAM->shapes.push_back(shape);
						}
						
						// Set shape properties
						tAM->shapes[0]->setPosition(Ogre::Vector3(marker.pose.position.x, 
							marker.pose.position.y, marker.pose.position.z));
						tAM->shapes[0]->setOrientation(Ogre::Quaternion(marker.pose.orientation.w, 
							marker.pose.orientation.x, marker.pose.orientation.y,
							marker.pose.orientation.z));
						tAM->shapes[0]->setScale(Ogre::Vector3(marker.scale.x, marker.scale.y,
							marker.scale.z));
						tAM->shapes[0]->setColor(Ogre::ColourValue(marker.color.r, marker.color.g,
							marker.color.b, marker.color.a));
						
						if (renew)
						{	
							switch (marker.type)
							{
								case visualization_msgs::Marker::CUBE:
									tAM->publishStatus(Gadget::OKAY, "Successfully added cube marker");
									break;
								case visualization_msgs::Marker::SPHERE:
									tAM->publishStatus(Gadget::OKAY, "Successfully added sphere marker");
									break;
								case visualization_msgs::Marker::CYLINDER:
									tAM->publishStatus(Gadget::OKAY, "Successfully added cylinder marker");
									break;
							}
						}
						break;
					}
				
				case visualization_msgs::Marker::LINE_STRIP:
					{
						unsigned int N;
						unsigned int i;
						
						if (!tAM->subGraphicNode)
						{
							tAM->subGraphicNode = tAM->graphicNode->createChildSceneNode();
						}
						
						// Line count
						N = marker.points.size() - 1;
						
						if (N < 1)
						{
							tAM->publishStatus(Gadget::ERROR, "Insufficient data to draw lines");
							return;
						}
						
						// If the number of preallocated shapes is too many, cull a few
						if (!renew && tAM->shapes.size() > N)
						{
							while (tAM->shapes.size() > N)
							{
								delete tAM->shapes[0];
								tAM->shapes.erase(tAM->shapes.begin());
							}
						}
						
						// Otherwise, if we have too few shapes preallocated, add a few
						if (tAM->shapes.size() < N)
						{
							while (tAM->shapes.size() < N)
							{
								Shape * shape = new Shape(Shape::RoughCylinder, tAM->scene, tAM->subGraphicNode);
								tAM->shapes.push_back(shape);
							}
						}
						
						// Set shapes' properties
						for (i = 0; i < N; i++)
						{
							tAM->shapes[i]->alignToLineSegment(Ogre::Vector3(marker.points[i].x, 
									marker.points[i].y,
									marker.points[i].z),
								Ogre::Vector3(marker.points[i + 1].x, 
									marker.points[i + 1].y,
									marker.points[i + 1].z),
								marker.scale.x);
						}
						
						// Set the shapes colors based on whether we're getting a list of colors
						// or just a single color...
						if (marker.colors.size() != marker.points.size())
						{
							for (i = 0; i < tAM->shapes.size(); i++)
							{
								tAM->shapes[i]->setColor(Ogre::ColourValue(marker.color.r, marker.color.g,
									marker.color.b, marker.color.a));
							}
						}
						else
						{
							for (i = 0; i < tAM->shapes.size(); i++)
							{
								tAM->shapes[i]->setColor(Ogre::ColourValue(marker.colors[i].r, 
									marker.colors[i].g,
									marker.colors[i].b, 
									marker.colors[i].a));
							}
						}
						
						tAM->subGraphicNode->setPosition(Ogre::Vector3(marker.pose.position.x, 
							marker.pose.position.y, marker.pose.position.z));
						tAM->subGraphicNode->setOrientation(Ogre::Quaternion(marker.pose.orientation.w, 
							marker.pose.orientation.x, marker.pose.orientation.y,
							marker.pose.orientation.z));
						
						if (renew)
						{
							tAM->publishStatus(Gadget::OKAY, "Successfully added line strip marker");
						}
						
						break;
					}
					
				case visualization_msgs::Marker::LINE_LIST:
					{
						unsigned int N;
						unsigned int i;
						
						if (!tAM->subGraphicNode)
						{
							tAM->subGraphicNode = tAM->graphicNode->createChildSceneNode();
						}
						
						if (marker.points.size() % 2 != 0)
						{
							tAM->publishStatus(Gadget::ERROR, "Need 2xN points to draw N lines");
							return;
						}
						
						// Line count
						N = marker.points.size() / 2;
						
						// If the number of preallocated shapes is too many, cull a few
						if (!renew && tAM->shapes.size() > N)
						{
							while (tAM->shapes.size() > N)
							{
								delete tAM->shapes[0];
								tAM->shapes.erase(tAM->shapes.begin());
							}
						}
						
						// Otherwise, if we have too few shapes preallocated, add a few
						if (tAM->shapes.size() < N)
						{
							while (tAM->shapes.size() < N)
							{
								Shape * shape = new Shape(Shape::RoughCylinder, tAM->scene, tAM->subGraphicNode);
								tAM->shapes.push_back(shape);
							}
						}
						
						
						// Set shapes' properties
						for (i = 0; i < N; i++)
						{
							tAM->shapes[i]->alignToLineSegment(Ogre::Vector3(marker.points[i * 2].x, 
									marker.points[i * 2].y,
									marker.points[i * 2].z),
								Ogre::Vector3(marker.points[i * 2 + 1].x, 
									marker.points[i * 2 + 1].y,
									marker.points[i * 2 + 1].z),
								marker.scale.x);
						}
						
						// Set the shapes colors based on whether we're getting a list of colors
						// or just a single color...
						if (marker.colors.size() != marker.points.size())
						{
							for (i = 0; i < tAM->shapes.size(); i++)
							{
								tAM->shapes[i]->setColor(Ogre::ColourValue(marker.color.r, marker.color.g,
									marker.color.b, marker.color.a));
							}
						}
						else
						{
							for (i = 0; i < tAM->shapes.size(); i++)
							{
								tAM->shapes[i]->setColor(Ogre::ColourValue(marker.colors[i * 2].r, 
									marker.colors[i * 2].g,
									marker.colors[i * 2].b, 
									marker.colors[i * 2].a));
							}
						}
						
						tAM->subGraphicNode->setPosition(Ogre::Vector3(marker.pose.position.x, 
							marker.pose.position.y, marker.pose.position.z));
						tAM->subGraphicNode->setOrientation(Ogre::Quaternion(marker.pose.orientation.w, 
							marker.pose.orientation.x, marker.pose.orientation.y,
							marker.pose.orientation.z));	
	
						if (renew)
						{
							tAM->publishStatus(Gadget::OKAY, "Successfully added line list marker");
						}
						
						break;
					}
				
				case visualization_msgs::Marker::SPHERE_LIST:
				case visualization_msgs::Marker::CUBE_LIST:
					{
						int shapeType;
						unsigned int i;
						
						if (!tAM->subGraphicNode)
						{
							tAM->subGraphicNode = tAM->graphicNode->createChildSceneNode();
						}
						
						switch (marker.type)
						{
							case visualization_msgs::Marker::SPHERE_LIST:
								shapeType = Shape::Sphere;
								break;
								
							case visualization_msgs::Marker::CUBE_LIST:
								shapeType = Shape::Cube;
								break;
						}
						
						// If the number of preallocated shapes is too many, cull a few
						if (!renew && tAM->shapes.size() > marker.points.size())
						{
							while (tAM->shapes.size() > marker.points.size())
							{
								delete tAM->shapes[0];
								tAM->shapes.erase(tAM->shapes.begin());
							}
						}
						
						// Otherwise, if we have too few shapes preallocated, add a few
						if (tAM->shapes.size() < marker.points.size())
						{
							while (tAM->shapes.size() < marker.points.size())
							{
								Shape * shape = new Shape(shapeType, tAM->scene, tAM->subGraphicNode);
								tAM->shapes.push_back(shape);
							}
						}
						
						// Set shapes' properties
						for (i = 0; i < marker.points.size(); i++)
						{
							tAM->shapes[i]->setPosition(Ogre::Vector3(marker.points[i].x, 
								marker.points[i].y, marker.points[i].z));
								
							tAM->shapes[i]->setOrientation(Ogre::Quaternion(marker.pose.orientation.w, 
								marker.pose.orientation.x, marker.pose.orientation.y,
								marker.pose.orientation.z));
							
							tAM->shapes[i]->setScale(Ogre::Vector3(marker.scale.x, marker.scale.y,
								marker.scale.z));
						}
						
						// Set the shapes colors based on whether we're getting a list of colors
						// or just a single color...
						if (marker.colors.size() != marker.points.size())
						{
							for (i = 0; i < tAM->shapes.size(); i++)
							{
								tAM->shapes[i]->setColor(Ogre::ColourValue(marker.color.r, marker.color.g,
									marker.color.b, marker.color.a));
							}
						}
						else
						{
							for (i = 0; i < tAM->shapes.size(); i++)
							{
								tAM->shapes[i]->setColor(Ogre::ColourValue(marker.colors[i].r, marker.colors[i].g,
									marker.colors[i].b, marker.colors[i].a));
							}
						}
						
						tAM->subGraphicNode->setPosition(Ogre::Vector3(marker.pose.position.x, 
							marker.pose.position.y, marker.pose.position.z));
						tAM->subGraphicNode->setOrientation(Ogre::Quaternion(marker.pose.orientation.w, 
							marker.pose.orientation.x, marker.pose.orientation.y,
							marker.pose.orientation.z));
							
						if (renew)
						{
							switch (marker.type)
							{
								case visualization_msgs::Marker::CUBE_LIST:
									tAM->publishStatus(Gadget::OKAY, "Successfully added cube list marker");
									break;
								case visualization_msgs::Marker::SPHERE_LIST:
									tAM->publishStatus(Gadget::OKAY, "Successfully added sphere list marker");
									break;
							}
						}
					}
					
					break;
					
				case visualization_msgs::Marker::POINTS:
					{
						
						unsigned int i;
						unsigned int N;
						
						if (renew)
						{
							tAM->subGraphicNode = tAM->graphicNode->createChildSceneNode();
							
							if (marker.points.size() > 0)
							{
								string materialName = name + "PointMat";

								tAM->material = Ogre::MaterialManager::getSingleton().create(materialName.c_str(), 
									Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
								tAM->material->setPointSize(marker.scale.x);
								Ogre::Technique* pT = tAM->material->getTechnique( 0 );
									if( NULL == pT ) pT = tAM->material->createTechnique();
								Ogre::Pass* pP = pT->getPass( 0 );
								if( NULL == pP ) pP = pT->createPass();

								// set parameters
								pP->setVertexColourTracking(Ogre::TVC_AMBIENT);
								pP->setLightingEnabled(false);
								//pP->setDepthCheckEnabled(true);
								//pP->setDepthWriteEnabled(false);
								//pP->setSceneBlending(Ogre::SBT_TRANSPARENT_ALPHA);
							
								tAM->manual = tAM->scene->createManualObject(tAM->name + "_manual");
								
								tAM->subGraphicNode->attachObject(tAM->manual);
								
								tAM->manual->setDynamic(true);
								tAM->manual->estimateVertexCount(1000);
								tAM->manual->begin(materialName.c_str(), Ogre::RenderOperation::OT_POINT_LIST);
							}
							else
							{
								tAM->publishStatus(Gadget::WARNING, "No data in message");
							}
						}
						else
						{
							if (marker.points.size() > 0)
							{
								tAM->material->setPointSize(marker.scale.x);
								tAM->manual->beginUpdate(0);
							}
							else
							{
								tAM->publishStatus(Gadget::WARNING, "No data in message");
							}
						}
						
						N = marker.points.size();
						
						// Setting each point's color independently or not?
						if (marker.colors.size() == marker.points.size())
						{
							for (i = 0; i < N; i++)
							{
								tAM->manual->position(marker.points[i].x,
									marker.points[i].y,
									marker.points[i].z);
								tAM->manual->colour(Ogre::ColourValue(marker.colors[i].r,
									marker.colors[i].g,
									marker.colors[i].b,
									marker.colors[i].a));
							}
						}
						else
						{
							tAM->manual->colour(Ogre::ColourValue(marker.color.r,
									marker.color.g,
									marker.color.b,
									marker.color.a));
									
							for (i = 0; i < N; i++)
							{
								tAM->manual->position(marker.points[i].x,
									marker.points[i].y,
									marker.points[i].z);
							}
						}
						
						tAM->manual->end();
						
						//tAM->subGraphicNode->setScale(Ogre::Vector3(marker.scale.x, marker.scale.y,
						//	marker.scale.z));
						tAM->subGraphicNode->setOrientation(Ogre::Quaternion(marker.pose.orientation.w, 
							marker.pose.orientation.x, marker.pose.orientation.y,
							marker.pose.orientation.z));
						tAM->subGraphicNode->setPosition(Ogre::Vector3(marker.pose.position.x, 
							marker.pose.position.y, marker.pose.position.z));
					}
					
					if (renew)
					{
						tAM->publishStatus(Gadget::OKAY, "Successfully added points marker");
					}
					
					break;
						
				case visualization_msgs::Marker::TEXT_VIEW_FACING:
					{
						// If we must abandon all of our preallocated data
						if (renew)
						{
							tAM->text = new Ogre::MovableText("TextLabel" + boost::lexical_cast<std::string>(textNameNum),
								marker.text);
							
							// Create host scene nodes
							tAM->subGraphicNode = tAM->graphicNode->createChildSceneNode();
							tAM->subGraphicNode->attachObject(tAM->text);
						}
						
						// Update movable text properties
						tAM->text->setCaption(marker.text);
						tAM->text->setColor(Ogre::ColourValue(marker.color.r, marker.color.g,
									marker.color.b, marker.color.a));
						tAM->subGraphicNode->setPosition(Ogre::Vector3(marker.pose.position.x, 
							marker.pose.position.y, marker.pose.position.z));
						tAM->text->setCharacterHeight(marker.scale.z);
					
						if (renew)
						{
							tAM->publishStatus(Gadget::OKAY, "Successfully added view facing text marker");
						}
					
						break;
					}
				
				case visualization_msgs::Marker::TRIANGLE_LIST:
					{
						unsigned int i;
						
						if (!tAM->subGraphicNode)
						{
							tAM->subGraphicNode = tAM->graphicNode->createChildSceneNode();
						}
						
						// Make sure we 3xN points to make triangles
						if (marker.points.size() % 3 == 0)
						{
							if (marker.points.size() > 0)
							{
								if (renew)
								{			
									tAM->manual = tAM->scene->createManualObject(name + "_manual");
		
									tAM->subGraphicNode->attachObject(tAM->manual);
		
									tAM->manual->setDynamic(true);
									tAM->manual->estimateVertexCount(1000);
									tAM->manual->begin("Surfaces/FlatVertexColour", Ogre::RenderOperation::OT_TRIANGLE_LIST);
								}
								else 
								{
									tAM->manual->beginUpdate(0);
								}
							}
							else 
							{
								tAM->publishStatus(Gadget::WARNING, "No point data");
								return;
							}
						}
						else
						{
							tAM->publishStatus(Gadget::ERROR, "Need 3xN points to draw N triangles");
							return;
						}
	 
						// Handle the cases of colors being populated correctly and not, separately
						if (marker.colors.size() == marker.points.size())
						{
							for (i = 0; i < marker.points.size(); i++)
							{
								tAM->manual->position(marker.points[i].x, 
									marker.points[i].y,
									marker.points[i].z);	
								tAM->manual->colour(Ogre::ColourValue(marker.colors[i].r,
									marker.colors[i].g,
									marker.colors[i].b,
									marker.colors[i].a));
							}
						}
						else
						{
							tAM->manual->colour(Ogre::ColourValue(marker.color.r,
								marker.color.g,
								marker.color.b,
								marker.color.a));
							for (i = 0; i < marker.points.size(); i++)
							{
								tAM->manual->position(marker.points[i].x, 
									marker.points[i].y,
									marker.points[i].z);	
							}
						}
	 
						tAM->manual->end();
						
						tAM->subGraphicNode->setScale(Ogre::Vector3(marker.scale.x, marker.scale.y,
							marker.scale.z));
						tAM->subGraphicNode->setOrientation(Ogre::Quaternion(marker.pose.orientation.w, 
							marker.pose.orientation.x, marker.pose.orientation.y,
							marker.pose.orientation.z));
						tAM->subGraphicNode->setPosition(Ogre::Vector3(marker.pose.position.x, 
							marker.pose.position.y, marker.pose.position.z));
					
						if (renew)
						{
							tAM->publishStatus(Gadget::OKAY, "Successfully added triangle list marker");
						}
					
						break;
					}
				
				case visualization_msgs::Marker::MESH_RESOURCE:
					// If something has changed free up old resources
					
					if (!renew && (tAM->meshResource != marker.mesh_resource))
					{
						if (tAM->entity)
						{
							// TODO!! :  Need to destroy scene nodes
							
							tAM->scene->destroyEntity(tAM->entity);
							tAM->entity = NULL;
						}
						renew = true;
					}
					
					if (renew)
					{	
						// Load the mesh
						int gotMaterial;
						tAM->mesh = loadMesh(marker.mesh_resource, gotMaterial);
										
						if (tAM->mesh.isNull())
						{
							tAM->publishStatus(Gadget::ERROR, "Failed to load mesh " + marker.mesh_resource);
							return;
						}
						
						// Create Ogre entity to encapsulate it
						tAM->entity = tAM->scene->createEntity((name + "_Ent").c_str(), marker.mesh_resource);
						
						if (!gotMaterial)
						{
							Ogre::MaterialPtr templateMat = Ogre::MaterialManager::getSingleton().getByName("Template/WhiteNoBlend");
							tAM->entity->setMaterial(templateMat);
							
							tAM->publishStatus(Gadget::WARNING, "No material associated with mesh " + marker.mesh_resource);
						}
	
						tAM->meshResource = marker.mesh_resource;
						
						if (!tAM->subGraphicNode)
						{
							tAM->subGraphicNode = tAM->graphicNode->createChildSceneNode();
						}
						
						tAM->subGraphicNode->attachObject(tAM->entity);
					}
					
					// Update scale and position of the mesh
					
					tAM->subGraphicNode->setScale(Ogre::Vector3(marker.scale.x, marker.scale.y,
						marker.scale.z));
					tAM->subGraphicNode->setOrientation(Ogre::Quaternion(marker.pose.orientation.w, 
						marker.pose.orientation.x, marker.pose.orientation.y,
						marker.pose.orientation.z));
					tAM->subGraphicNode->setPosition(Ogre::Vector3(marker.pose.position.x, 
						marker.pose.position.y, marker.pose.position.z));
						
					// Update to ensure the graphic is placed at the correct location
					tAM->update();	
						
					if (renew)
					{
						tAM->publishStatus(Gadget::OKAY, "Successfully added mesh marker");
					}
					
					break;
					
			}
			
			if (tAM->boundsVisible)
			{
				tAM->calculateBounds();
				tAM->boundsChanged = true;
			}
			
			break;
	}	
}
示例#15
0
int initOgreAR(aruco::CameraParameters camParams, unsigned char* buffer, std::string resourcePath)
{
	/// INIT OGRE FUNCTIONS
#ifdef _WIN32
  	root = new Ogre::Root(resourcePath + "plugins_win.cfg", resourcePath + "ogre_win.cfg");
#elif __x86_64__ || __ppc64__
	root = new Ogre::Root(resourcePath + "plugins_x64.cfg", resourcePath + "ogre.cfg");
#else
	root = new Ogre::Root(resourcePath + "plugins.cfg", resourcePath + "ogre.cfg");
#endif
  	if (!root->showConfigDialog()) return -1;
	Ogre::SceneManager* smgr = root->createSceneManager(Ogre::ST_GENERIC);


	/// CREATE WINDOW, CAMERA AND VIEWPORT
    Ogre::RenderWindow* window = root->initialise(true);
	Ogre::Camera *camera;
	Ogre::SceneNode* cameraNode;
	camera = smgr->createCamera("camera");
	camera->setNearClipDistance(0.01f);
	camera->setFarClipDistance(10.0f);
	camera->setProjectionType(Ogre::PT_ORTHOGRAPHIC);
	camera->setPosition(0, 0, 0);
	camera->lookAt(0, 0, 1);
	double pMatrix[16];
	camParams.OgreGetProjectionMatrix(camParams.CamSize,camParams.CamSize, pMatrix, 0.05,10, false);
	Ogre::Matrix4 PM(pMatrix[0], pMatrix[1], pMatrix[2] , pMatrix[3],
			pMatrix[4], pMatrix[5], pMatrix[6] , pMatrix[7],
			pMatrix[8], pMatrix[9], pMatrix[10], pMatrix[11],
			pMatrix[12], pMatrix[13], pMatrix[14], pMatrix[15]);
	camera->setCustomProjectionMatrix(true, PM);
	camera->setCustomViewMatrix(true, Ogre::Matrix4::IDENTITY);
	window->addViewport(camera);
	cameraNode = smgr->getRootSceneNode()->createChildSceneNode("cameraNode");
	cameraNode->attachObject(camera);


	/// CREATE BACKGROUND FROM CAMERA IMAGE
	int width = camParams.CamSize.width;
	int height = camParams.CamSize.height;
	// create background camera image
	mPixelBox = Ogre::PixelBox(width, height, 1, Ogre::PF_R8G8B8, buffer);
	// Create Texture
	mTexture = Ogre::TextureManager::getSingleton().createManual("CameraTexture",Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
		      Ogre::TEX_TYPE_2D,width,height,0,Ogre::PF_R8G8B8,Ogre::TU_DYNAMIC_WRITE_ONLY_DISCARDABLE);

	//Create Camera Material
	Ogre::MaterialPtr material = Ogre::MaterialManager::getSingleton().create("CameraMaterial", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
	Ogre::Technique *technique = material->createTechnique();
	technique->createPass();
	material->getTechnique(0)->getPass(0)->setLightingEnabled(false);
	material->getTechnique(0)->getPass(0)->setDepthWriteEnabled(false);
	material->getTechnique(0)->getPass(0)->createTextureUnitState("CameraTexture");

	Ogre::Rectangle2D* rect = new Ogre::Rectangle2D(true);
	rect->setCorners(-1.0, 1.0, 1.0, -1.0);
	rect->setMaterial("CameraMaterial");

	// Render the background before everything else
	rect->setRenderQueueGroup(Ogre::RENDER_QUEUE_BACKGROUND);

	// Hacky, but we need to set the bounding box to something big, use infinite AAB to always stay visible
	Ogre::AxisAlignedBox aabInf;
	aabInf.setInfinite();
	rect->setBoundingBox(aabInf);

	// Attach background to the scene
	Ogre::SceneNode* node = smgr->getRootSceneNode()->createChildSceneNode("Background");
	node->attachObject(rect);


	/// CREATE SIMPLE OGRE SCENE
	// add sinbad.mesh
	Ogre::ResourceGroupManager::getSingleton().addResourceLocation(resourcePath + "Sinbad.zip", "Zip", "Popular");
 	Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
	for(int i=0; i<MAX_MARKERS; i++) {
	  Ogre::String entityName = "Marker_" + Ogre::StringConverter::toString(i);
	  Ogre::Entity* ogreEntity = smgr->createEntity(entityName, "Sinbad.mesh");
	  Ogre::Real offset = ogreEntity->getBoundingBox().getHalfSize().y;
	  ogreNode[i] = smgr->getRootSceneNode()->createChildSceneNode();
	  // add entity to a child node to correct position (this way, entity axis is on feet of sinbad)
	  Ogre::SceneNode *ogreNodeChild = ogreNode[i]->createChildSceneNode();
	  ogreNodeChild->attachObject(ogreEntity);
	  // Sinbad is placed along Y axis, we need to rotate to put it along Z axis so it stands up over the marker
	  // first rotate along X axis, then add offset in Z dir so it is over the marker and not in the middle of it
	  ogreNodeChild->rotate(Ogre::Vector3(1,0,0), Ogre::Radian(Ogre::Degree(90)));
	  ogreNodeChild->translate(0,0,offset,Ogre::Node::TS_PARENT);
	  // mesh is too big, rescale!
	  const float scale = 0.006675f;
	  ogreNode[i]->setScale(scale, scale, scale);

	    // Init animation
	  ogreEntity->getSkeleton()->setBlendMode(Ogre::ANIMBLEND_CUMULATIVE);
	  if(i==0)
	  {
        baseAnim[i] = ogreEntity->getAnimationState("HandsClosed");
        topAnim[i] = ogreEntity->getAnimationState("HandsRelaxed");
	  }
	  else if(i==1)
	  {
        baseAnim[i] = ogreEntity->getAnimationState("Dance");
        topAnim[i] = ogreEntity->getAnimationState("Dance");
	  }
	  else if(i==2)
	  {
        baseAnim[i] = ogreEntity->getAnimationState("RunBase");
        topAnim[i] = ogreEntity->getAnimationState("RunTop");
	  }
	  else
	  {
        baseAnim[i] = ogreEntity->getAnimationState("IdleBase");
        topAnim[i] = ogreEntity->getAnimationState("IdleTop");
	  }
	  baseAnim[i]->setLoop(true);
	  topAnim[i]->setLoop(true);
	  baseAnim[i]->setEnabled(true);
	  topAnim[i]->setEnabled(true);
	}


 	/// KEYBOARD INPUT READING
 	size_t windowHnd = 0;
 	window->getCustomAttribute("WINDOW", &windowHnd);
 	im = OIS::InputManager::createInputSystem(windowHnd);
 	keyboard = static_cast<OIS::Keyboard*>(im->createInputObject(OIS::OISKeyboard, true));

	return 1;
}
示例#16
0
Camera::Camera(Event::Lane& lane,
               GameHandle cameraHandle, 
               Ogre::SceneNode* camNode, 
               Ogre::RenderTarget* renderTarget, 
               u32 width, 
               u32 height,
               const v3& position,
               const qv4& orientation,
               GameHandle parent) :
mSubLane(lane.createSubLane()),
mCameraNode(camNode),
mRenderTarget(renderTarget),
mHandle(cameraHandle),
mNodeCreated(false),
mRenderTargetCreated(false)
{
	Ogre::SceneManager* sceneMgr = Ogre::Root::getSingleton().getSceneManager(BFG_SCENEMANAGER);
	if (mCameraNode == NULL) // Create SceneNode
	{
		if (sceneMgr->hasSceneNode(stringify(mHandle)))
		{
			mCameraNode = sceneMgr->getSceneNode(stringify(mHandle));
		}
		else
		{
			mCameraNode = sceneMgr->getRootSceneNode()->createChildSceneNode(stringify(mHandle));
			mNodeCreated = true;
		}
	}
	mCameraNode->setOrientation(toOgre(orientation));
	mCameraNode->setPosition(toOgre(position));

	v3 target = toBFG(mCameraNode->getOrientation().zAxis());
	norm(target);

	Ogre::Camera* cam;
	cam = sceneMgr->createCamera(stringify(mHandle));

	cam->setFOVy(Ogre::Degree(60.0f));
	cam->setNearClipDistance(0.1f);
	cam->setFarClipDistance(250000.0f);
	cam->lookAt(toOgre(target)*10);
	mCameraNode->attachObject(cam);

	infolog << "Camera: " << stringify(mHandle) << " created.";

	if (mRenderTarget == NULL)
	{
		// Create renderToTexture RenderTarget

		if (width == 0 || height == 0)
		{
			throw std::logic_error("Too few information to create a render target.");
		}

		cam->setAspectRatio((f32)width / (f32)height);

		Ogre::TexturePtr texture = Ogre::TextureManager::getSingleton().createManual
		(
			stringify(mHandle),
			Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
			Ogre::TEX_TYPE_2D,
			width,
			height,
			0,
			Ogre::PF_R8G8B8,
			Ogre::TU_RENDERTARGET
		);

		mRenderTarget = texture->getBuffer()->getRenderTarget();

		prepareRenderTarget();

		mRenderTarget->addViewport(cam);

		mRenderTarget->getViewport(0)->setClearEveryFrame(true);
		mRenderTarget->getViewport(0)->setBackgroundColour(Ogre::ColourValue::Black);
		mRenderTarget->getViewport(0)->setOverlaysEnabled(false);

		Ogre::MaterialPtr mat =
			Ogre::MaterialManager::getSingleton().getByName(stringify(mHandle));
		if (mat.isNull())
		{
			mat = Ogre::MaterialManager::getSingleton().create(
			    stringify(mHandle), 
			    Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
		}
		Ogre::Technique* tech = mat->getTechnique(0);
		if (!tech)
		{
			tech = mat->createTechnique();
		}
		Ogre::Pass* pass = tech->getPass(0);
		if (!pass)
		{
			pass = tech->createPass();
		}
		pass->setLightingEnabled(false);

		if (pass->getNumTextureUnitStates() > 0)
		{
			Ogre::TextureUnitState* txState = NULL;
			txState = pass->getTextureUnitState(0);
			txState->setTextureName(stringify(mHandle));
		}
		else
		{
			pass->createTextureUnitState(stringify(mHandle));
		}

		mRenderTarget->setAutoUpdated(true);

		mRenderTargetCreated = true;

		infolog << "Rendertarget: " << stringify(mHandle) << " created.";
	}
	else
	{
		prepareRenderTarget();
		f32 width = static_cast<f32>(mRenderTarget->getWidth());
		f32 height = static_cast<f32>(mRenderTarget->getHeight());
		cam->setAspectRatio(width / height);
		mRenderTarget->addViewport(cam);
	}
	
// 	mSubLane->connect(ID::VE_UPDATE_POSITION, this, &Camera::updatePosition, mHandle);
// 	mSubLane->connect(ID::VE_UPDATE_ORIENTATION, this, &Camera::updateOrientation, mHandle);
	mSubLane->connect(ID::VE_SET_CAMERA_TARGET, this, &Camera::onSetTarget, mHandle);

	if (parent != NULL_HANDLE)
	{
		onSetTarget(parent);
	}
}
示例#17
0
void ParticleMaterialGenerator::generate()
{
	mMaterial = prepareMaterial(mDef->getName());
	
	// reset some attributes
	resetTexUnitCounter();
	
	// choose textures from list (depending on user iTexSize setting)
	chooseTextures();
	
	// -------------------------- Main technique ----------------------------- //
	Ogre::Technique* technique = mMaterial->createTechnique();

	// particledepth pass
	Ogre::Pass* particleDepthPass = technique->createPass();
	particleDepthPass->setAmbient( mDef->mProps->ambient.x, mDef->mProps->ambient.y, mDef->mProps->ambient.z );
	particleDepthPass->setDiffuse( mDef->mProps->diffuse.x, mDef->mProps->diffuse.y, mDef->mProps->diffuse.z, 1.0 );
	
	particleDepthPass->setSpecular(mDef->mProps->specular.x, mDef->mProps->specular.y, mDef->mProps->specular.z, mDef->mProps->specular.w);
	
	particleDepthPass->setFog(true); // actually this disables fog

	if (!mDef->mProps->lighting)
		particleDepthPass->setLightingEnabled(false);
	
	if (mDef->mProps->sceneBlend == SBM_ALPHA_BLEND)
		particleDepthPass->setSceneBlending(SBT_TRANSPARENT_ALPHA);
	else if (mDef->mProps->sceneBlend == SBM_COLOUR_BLEND)
		particleDepthPass->setSceneBlending(SBT_TRANSPARENT_COLOUR);
	else if (mDef->mProps->sceneBlend == SBM_ADD)
		particleDepthPass->setSceneBlending(SBT_ADD);
	else if (mDef->mProps->sceneBlend == SBM_MODULATE)
		particleDepthPass->setSceneBlending(SBT_MODULATE);
		
	particleDepthPass->setDepthWriteEnabled( mDef->mProps->depthWrite );
		
	particleDepthPass->setDepthCheckEnabled( mDef->mProps->depthCheck );
		
	particleDepthPass->setTransparentSortingEnabled( mDef->mProps->transparentSorting );
	
	particleDepthPass->setAlphaRejectFunction( mDef->mProps->alphaRejectFunc );
	particleDepthPass->setAlphaRejectValue( mDef->mProps->alphaRejectValue );

	Ogre::TextureUnitState* tu = particleDepthPass->createTextureUnitState( mDiffuseMap );
	tu->setName("diffuseMap");
	tu->setTextureAddressingMode(mDef->mProps->textureAddressMode);

	tu = particleDepthPass->createTextureUnitState();
	tu->setName("depthMap");
	tu->setTextureAddressingMode(mDef->mProps->textureAddressMode);
	
	// create shaders
	HighLevelGpuProgramPtr fragmentProg, vertexProg;
	try
	{
		vertexProg = createSoftParticleVertexProgram();
		fragmentProg = createSoftParticleFragmentProgram();
	}
	catch (Ogre::Exception& e) {
		LogO(e.getFullDescription());
	}

	if (fragmentProg.isNull() || vertexProg.isNull() || 
		!fragmentProg->isSupported() || !vertexProg->isSupported())
	{
		LogO("[MaterialFactory] WARNING: ambient shader for material '" + mDef->getName()
			+ "' is not supported.");
	}
	else
	{
		particleDepthPass->setVertexProgram(vertexProg->getName());
		particleDepthPass->setFragmentProgram(fragmentProg->getName());
	}

	createSSAOTechnique();
	createOccluderTechnique();

	// indicate we need depth buffer set every frame
	mParent->softMtrs.push_back(mDef->getName());
	
}
示例#18
0
void WaterMaterialGenerator::generate()
{
	mMaterial = prepareMaterial(mDef->getName());
	
	resetTexUnitCounter();
	
	// we need a lot of uniform constants, disabling shadows reduces them significantly so that it can still run on PS2
	const RenderSystemCapabilities *caps = Root::getSingleton().getRenderSystem()->getCapabilities();
	if(!caps->isShaderProfileSupported("ps_4_0") && !caps->isShaderProfileSupported("fp40"))
		mDef->mProps->receivesShadows = false;

	
	// -------------------------- Main technique ----------------------------- //
	Ogre::Technique* technique = mMaterial->createTechnique();

	//  Main pass -----------------------------------------------------------
	Ogre::Pass* pass = technique->createPass();
	
	pass->setCullingMode(CULL_NONE);
	pass->setDepthWriteEnabled(true);
	
	if (!mParent->getRefract())
		pass->setSceneBlending(SBT_TRANSPARENT_ALPHA);
	
	Ogre::TextureUnitState* tu;
	//  normal map
	mNormalMap = pickTexture(&mDef->mProps->normalMaps);
	tu = pass->createTextureUnitState( mNormalMap );
	tu->setName("normalMap");
	mNormalTexUnit = mTexUnit_i; mTexUnit_i++;

	// global terrain lightmap (static)
	if (needTerrainLightMap())
	{
		tu = pass->createTextureUnitState(""); // texture name set later (in changeShadows)
		tu->setName("terrainLightMap");
		mTerrainLightTexUnit = mTexUnit_i; mTexUnit_i++;
	}

	if (mParent->getRefract())
	{
		tu = pass->createTextureUnitState( "PlaneRefraction" );
		tu->setName("refractionMap");
		tu->setTextureAddressingMode(TextureUnitState::TAM_CLAMP);
		mScreenRefrUnit = mTexUnit_i++;
	}
	if (mParent->getReflect())
	{
		tu = pass->createTextureUnitState( "PlaneReflection" );
		tu->setName("reflectionMap");
		tu->setTextureAddressingMode(TextureUnitState::TAM_CLAMP);
		mScreenReflUnit = mTexUnit_i++;
	}
	//else
	{
		// retrieve sky texture name from scene
		std::string skyTexName;
		if (mParent->pApp->terrain)
		{
			MaterialPtr mtrSky = MaterialManager::getSingleton().getByName(mParent->pApp->sc.skyMtr);
			if(!mtrSky.isNull())
			{
				Pass* passSky = mtrSky->getTechnique(0)->getPass(0);
				TextureUnitState* tusSky = passSky->getTextureUnitState(0);

				skyTexName = tusSky->getTextureName();
			}
		}
		else skyTexName = String("white.png");
		
		tu = pass->createTextureUnitState( skyTexName );
		tu->setName("skyMap");
		tu->setTextureAddressingMode(TextureUnitState::TAM_MIRROR);
		mEnvTexUnit = mTexUnit_i++;
	}
	
	//  waterDepth
	tu = pass->createTextureUnitState( "waterDepth.png" );
	tu->setName("depthMap");
	tu->setTextureAddressingMode(TextureUnitState::TAM_BORDER);
	tu->setTextureBorderColour(ColourValue::White);  // outside tex water always visible
	mWaterDepthUnit = mTexUnit_i;  mTexUnit_i++;
	
	
	// realtime shadow maps
	if (needShadows())
	{
		mShadowTexUnit_start = mTexUnit_i;
		for (int i = 0; i < mParent->getNumShadowTex(); ++i)
		{
			tu = pass->createTextureUnitState();
			tu->setName("shadowMap" + toStr(i));
			tu->setContentType(TextureUnitState::CONTENT_SHADOW);
			tu->setTextureAddressingMode(TextureUnitState::TAM_BORDER);
			tu->setTextureBorderColour(ColourValue::White);
			mTexUnit_i++;
		}
	}
	
	// shader
	if (!mShaderCached)
	{
		mVertexProgram = createVertexProgram();
		mFragmentProgram = createFragmentProgram();
	}
	
	pass->setVertexProgram(mVertexProgram->getName());
	pass->setFragmentProgram(mFragmentProgram->getName());
	
	if (mShaderCached)
	{
		individualFragmentProgramParams(pass->getFragmentProgramParameters());
		individualVertexProgramParams(pass->getFragmentProgramParameters());
	}

	// ----------------------------------------------------------------------- //
	
	createSSAOTechnique();
	createOccluderTechnique();

	// indicate we need 'time' parameter set every frame
	mParent->timeMtrs.push_back(mDef->getName());
	/*
	if (mDef->getName() == "Grease_jelly")
	{
		LogO("[MaterialFactory] Vertex program source: ");
		StringUtil::StrStreamType vSourceStr;
		generateVertexProgramSource(vSourceStr);
		LogO(vSourceStr.str());
		LogO("[MaterialFactory] Fragment program source: ");
		StringUtil::StrStreamType fSourceStr;
		generateFragmentProgramSource(fSourceStr);
		LogO(fSourceStr.str());
	}
	/**/
}
示例#19
0
void Game::setupScene()
{
	// Init stuff for render to texture - Minimap
	// First the texture
	rtt_texture_minimap = Ogre::TextureManager::getSingleton().createManual("RttTex",
			Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::TEX_TYPE_2D,
			OgreFW::getSingletonPtr()->m_pRenderWnd->getWidth(),
			OgreFW::getSingletonPtr()->m_pRenderWnd->getHeight(),
			0, Ogre::PF_R8G8B8, Ogre::TU_RENDERTARGET);
	// Then, get its render target
	renderTextureTarget = rtt_texture_minimap->getBuffer()->getRenderTarget();
	renderTextureTarget->addViewport(OgreFW::getSingletonPtr()->m_pCamera);
	renderTextureTarget->getViewport(0)->setClearEveryFrame(true);
	renderTextureTarget->getViewport(0)->setBackgroundColour(Ogre::ColourValue::Black);
	renderTextureTarget->getViewport(0)->setOverlaysEnabled(false);
	// Set it active!
	renderTextureTarget->setActive(true);
	// Last, the mini rectangle
	mMiniScreen = new Ogre::Rectangle2D(true);
	mMiniScreen->setCorners(0.75f, -0.75f, 1.0f, -1.0f);
	mMiniScreen->setBoundingBox(Ogre::AxisAlignedBox(-100000.0f * Ogre::Vector3::UNIT_SCALE, 100000.0f * Ogre::Vector3::UNIT_SCALE));
	// Scenenode, then add
	mMiniScreenSN = OgreFW::getSingletonPtr()->m_pSceneMgr->getRootSceneNode()->createChildSceneNode("MiniScreenNode");
	mMiniScreenSN->attachObject(mMiniScreen);
	// The texture needs its material
	Ogre::MaterialPtr renderMaterial = Ogre::MaterialManager::getSingleton().create("RttMat", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
	Ogre::Technique* matTechnique = renderMaterial->createTechnique();
	matTechnique->createPass();
	renderMaterial->getTechnique(0)->getPass(0)->setLightingEnabled(false);
	renderMaterial->getTechnique(0)->getPass(0)->createTextureUnitState("RttTex");
	mMiniScreen->setMaterial("RttMat");
	//Register this as a listener
	renderTextureTarget->addListener(this);

	// Init the CollisionHandler
	GameCollisionHandler = new CollisionHandler(OgreFW::getSingletonPtr()->m_pSceneMgr);

	// Init the first level
	myLevel = myLevelFactory->create();
	// Pass the LevelObjects to the collision_handler
	std::vector<LevelBlock*> levobjs = myLevel->getLevelObjects();
	for (std::vector<LevelBlock*>::iterator i = levobjs.begin(); i != levobjs.end(); ++i) {
		GameCollisionHandler->addNewObject(*i);
	}

	// The skybox!
	OgreFW::getSingletonPtr()->m_pSceneMgr->setSkyDome(true, "Examples/CloudySky");

	// Activate shadows
	OgreFW::getSingletonPtr()->m_pSceneMgr->setShadowTechnique(Ogre::SHADOWTYPE_STENCIL_MODULATIVE);

	// Create Lights
	// Set the ambient light
	OgreFW::getSingletonPtr()->m_pSceneMgr->setAmbientLight(Ogre::ColourValue(0.15, 0.15, 0.15));

	// Create a Directional light
	Ogre::Light* lptr = OgreFW::getSingletonPtr()->m_pSceneMgr->createLight("dirLight");
	lptr->setType(Ogre::Light::LT_DIRECTIONAL);
	lptr->setDiffuseColour(Ogre::ColourValue(0.4, 0.4, 0));
	lptr->setSpecularColour(Ogre::ColourValue(0.4, 0.4, 0));
	lptr->setDirection(Ogre::Vector3( 0, -1, 0 ));
	sceneLights.push_back(lptr);

	// Create a Point Light
	Ogre::Light* lptrpoint = OgreFW::getSingletonPtr()->m_pSceneMgr->createLight("pointLight");
	lptrpoint->setType(Ogre::Light::LT_POINT);
	lptrpoint->setPosition(Ogre::Vector3(0, OBJ_SIZE_Y * myLevel->getHeight() * 2, 0));
	lptrpoint->setDiffuseColour(1.0, 0.0, 0.0);
    lptrpoint->setSpecularColour(1.0, 0.0, 0.0);
	sceneLights.push_back(lptrpoint);

	// Camera settings - TODO
	//OgreFW::getSingletonPtr()->moveCameraToPos(Ogre::Vector3( OBJ_SIZE_X, OBJ_SIZE_Y, OBJ_SIZE_Z));
	OgreFW::getSingletonPtr()->moveCameraToPos(Ogre::Vector3( myLevel->getWidth() * OBJ_SIZE_X / 2, OBJ_SIZE_Y * myLevel->getHeight() / 2, OBJ_SIZE_Z * 5));

	//OgreFW::getSingletonPtr()->setCameraLookAt(Ogre::Vector3(OBJ_SIZE_X * myLevel->getWidth() /2, OBJ_SIZE_Y, 0.0f));
	OgreFW::getSingletonPtr()->setCameraLookAt(Ogre::Vector3( myLevel->getWidth() * OBJ_SIZE_X / 2, OBJ_SIZE_Y * (myLevel->getHeight() -1) / 2, 0.0f));

	// Set the camerapos for rendering the minimap
	cameraPosMap = Ogre::Vector3(OBJ_SIZE_X * myLevel->getWidth() / 2, OBJ_SIZE_Y * myLevel->getHeight() / 2, OBJ_SIZE_Z * 10);

	// Request a sunEffect for creating the sun
	EffectsFactory::getSingletonPtr()->createSunEffect(myLevel->getWidth() * myLevel->getObjectSide() / 2 , myLevel->getHeight() * myLevel->getObjectSide() / 2 , -60.0f);

	// We move to the first game state
	currentGameStage = MAIN_MENU_STATE;

	// Load the GUI sheet
	OgreFW::getSingletonPtr()->mGUIRootWindow = CEGUI::WindowManager::getSingleton().loadWindowLayout("myL2.layout");
	//CEGUI::Window *guiRoot = CEGUI::WindowManager::getSingleton().getWindow(
	CEGUI::System::getSingleton().setGUISheet(OgreFW::getSingletonPtr()->mGUIRootWindow);
	CEGUI::Window* eventButton = OgreFW::getSingletonPtr()->mGUIRootWindow->getChild("MainMenuRoot/LocalGame");
	if (eventButton) {
		std::cout << "Yes I got it" << std::endl;
		// Register handler
		eventButton->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::SubscriberSlot(&Game::setupLocalGame, this));
		//std::cout << "Text: " << eventButton->getText() << std::endl;
	}
	eventButton = OgreFW::getSingletonPtr()->mGUIRootWindow->getChild("MainMenuRoot/NetClient");
	if (eventButton) {
		eventButton->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::SubscriberSlot(&Game::setupClientGame, this));
	}
	eventButton = OgreFW::getSingletonPtr()->mGUIRootWindow->getChild("MainMenuRoot/NetServer");
	if (eventButton) {
		eventButton->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::SubscriberSlot(&Game::setupServerGame, this));
	}

}
示例#20
0
	OgrePass::OgrePass (OgreMaterial* parent, const std::string& configuration, unsigned short lodIndex)
		: Pass()
	{
		Ogre::Technique* t = parent->getOgreTechniqueForConfiguration(configuration, lodIndex);
		mPass = t->createPass();
	}
示例#21
0
文件: vpAROgre.cpp 项目: tswang/visp
/*!
  Create a color background to show the real scene.

  \param I : This parameter is here only used to initialize a color background.
*/
void vpAROgre::createBackground(vpImage<vpRGBa> & /* I */)
{
  // Create a rectangle to show the incoming images from the camera
  mBackground = new Ogre::Rectangle2D(true); // true = textured
  mBackground->setCorners(-1.0, 1.0, 1.0, -1.0); // Spread all over the window
  mBackground->setBoundingBox(Ogre::AxisAlignedBox(-100000.0*Ogre::Vector3::UNIT_SCALE, 100000.0*Ogre::Vector3::UNIT_SCALE)); // To be shown everywhere

  // Texture options
  Ogre::MaterialManager::getSingleton().setDefaultTextureFiltering(Ogre::TFO_NONE);
  Ogre::MaterialManager::getSingleton().setDefaultAnisotropy(1);

  // Dynamic texture
  // If we are using opengl we can boost a little bit performances with a dynamic texture
  if(mRoot->getRenderSystem()->getName() == "OpenGL Rendering Subsystem") {
    Ogre::TextureManager::getSingleton().createManual("BackgroundTexture",
						      Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
						      Ogre::TEX_TYPE_2D,
						      mBackgroundWidth,//width
						      mBackgroundHeight,//height
						      0,  // num of mip maps
                  //Ogre::PF_BYTE_RGBA,
                  Ogre::PF_BYTE_BGRA,
                  Ogre::TU_DYNAMIC_WRITE_ONLY_DISCARDABLE);
  }
  else{ // As that texture does not seem to work properly with direct3D we use a default texture
    Ogre::TextureManager::getSingleton().createManual("BackgroundTexture",
						      Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
						      Ogre::TEX_TYPE_2D,
						      mBackgroundWidth,//width
						      mBackgroundHeight,//height
						      0,  // num of mip maps
                  //Ogre::PF_BYTE_RGBA,
                  Ogre::PF_BYTE_BGRA,
						      Ogre::TU_DEFAULT);
  }


  // Pointer to the dynamic texture
  Ogre::TexturePtr dynTexPtr =
    Ogre::TextureManager::getSingleton().getByName("BackgroundTexture");
//#if ( OGRE_VERSION >= (1 << 16 | 9 << 8 | 0) )
//      .dynamicCast<Ogre::Texture>();// Get the pixel buffer
//#else
//      ;
//#endif

  // Get the pixel buffer
  mPixelBuffer = dynTexPtr->getBuffer();

  // Material to apply the texture to the background
  Ogre::MaterialPtr Backgroundmaterial
    = Ogre::MaterialManager::getSingleton().create("BackgroundMaterial",
               Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
//#if ( OGRE_VERSION >= (1 << 16 | 9 << 8 | 0) )
//      .dynamicCast<Ogre::Material>();
//#else
//      ;
//#endif
  Ogre::Technique *Backgroundtechnique = Backgroundmaterial->createTechnique();
  Backgroundtechnique->createPass();
  Backgroundmaterial->getTechnique(0)->getPass(0)->setLightingEnabled(false);
  Backgroundmaterial->getTechnique(0)->getPass(0)->setDepthCheckEnabled(false); // Background
  Backgroundmaterial->getTechnique(0)->getPass(0)->setDepthWriteEnabled(false); // Background
  Backgroundmaterial->getTechnique(0)->getPass(0)->createTextureUnitState("BackgroundTexture");
  mBackground->setMaterial("BackgroundMaterial"); // Attach the material to the rectangle
  mBackground->setRenderQueueGroup(Ogre::RENDER_QUEUE_BACKGROUND); // To be rendered in Background

  // Add the background to the Scene Graph so it will be rendered
  Ogre::SceneNode *BackgroundNode = mSceneMgr->getRootSceneNode()->createChildSceneNode("BackgoundNode");
  BackgroundNode->attachObject(mBackground);
}