Exemplo n.º 1
0
	bool Noise::loadCfg(Ogre::ConfigFile &CfgFile)
	{
		if (CfgFile.getSetting("Noise") == mName)
		{
			return true;
		}

		return false;
	}
Exemplo n.º 2
0
void loadMaterialControlsFile(MaterialControlsContainer& controlsContainer, const Ogre::String& filename)
{
    // Load material controls from config file
    Ogre::ConfigFile cf;

    try
    {

        cf.load(filename, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, "\t;=", true);

        // Go through all sections & controls in the file
        Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator();

        Ogre::String secName, typeName, materialName, dataString;

        while (seci.hasMoreElements())
        {
            secName = seci.peekNextKey();
            Ogre::ConfigFile::SettingsMultiMap* settings = seci.getNext();
            if (!secName.empty() && settings)
            {
                materialName = cf.getSetting("material", secName);
				
				Ogre::MaterialPtr curMat = Ogre::MaterialManager::getSingleton().getByName(materialName);
				curMat->load();
				Ogre::Technique * curTec = curMat->getBestTechnique();
				if (!curTec || !curTec->isSupported())
				{
					continue;
				}

                MaterialControls newMaaterialControls(secName, materialName);
                controlsContainer.push_back(newMaaterialControls);

                size_t idx = controlsContainer.size() - 1;

                Ogre::ConfigFile::SettingsMultiMap::iterator i;

                for (i = settings->begin(); i != settings->end(); ++i)
                {
                    typeName = i->first;
                    dataString = i->second;
                    if (typeName == "control")
                        controlsContainer[idx].addControl(dataString);
                }
            }
        }

	    Ogre::LogManager::getSingleton().logMessage( "Material Controls setup" );
    }
    catch (Ogre::Exception e)
    {
        // Guess the file didn't exist
    }
}
Exemplo n.º 3
0
	bool Noise::loadCfg(Ogre::ConfigFile &CfgFile)
	{
		if (CfgFile.getSetting("Noise") == mName)
		{
		    HydraxLOG(mName + " options entry found.");
			return true;
		}

        HydraxLOG("Error (Noise::loadCfg):\t" + mName + " options entry can not be found.");
		return false;
	}
Exemplo n.º 4
0
void LoginState::createGUIWindow()
{
  assert(pGui);

    // Load the previous login settings from login.cfg, if one exists
  std::string ipAddress(""), playerName("nameless newbie");
  float colorSelection = 0.0f;
  Ogre::ConfigFile loginConfig;
  try {
      loginConfig.load(bundlePath() + "login.cfg");
      ipAddress = loginConfig.getSetting("IPaddress");
      playerName = loginConfig.getSetting("PlayerName");
      if (!from_string<float>(colorSelection, loginConfig.getSetting("PlayerColor"), std::dec))
        colorSelection = 0.0f;
  } catch (Ogre::FileNotFoundException e) {}

  pGui->setupLoginWindow(ipAddress, playerName, colorSelection);
  pGui->setLoginReceiver(this);

  mViewport = new MenuStateViewport(pSceneManager);
}
Exemplo n.º 5
0
    StereoManager::StereoMode StereoManager::loadConfig(const Ogre::String &filename)
    {
        Ogre::ConfigFile cf;
        cf.load(filename.c_str());

        StereoMode mode = SM_NONE;

        const Ogre::String &modeName = cf.getSetting("Stereo mode","Stereoscopy");
        const StereoModeList::const_iterator end = available_nodes_.end();
        StereoModeList::iterator it;
        for(it = available_nodes_.begin(); it != end; ++it)
        {
            if(it->second.name_ == modeName)
            {
                mode = it->first;
                break;
            }
        }
        if(it == available_nodes_.end())
            mode = SM_NONE;

        fixFocalPlanePos(Ogre::StringConverter::parseBool(cf.getSetting("Fixed screen","Stereoscopy")));

        if(cf.getSetting("Focal length","Stereoscopy") == "inf")
            infinite_focal_length_ = true;
        else
            setFocalLength(Ogre::StringConverter::parseReal(cf.getSetting("Focal length","Stereoscopy")));

        setEyesSpacing(Ogre::StringConverter::parseReal(cf.getSetting("Eyes spacing","Stereoscopy")));
        setScreenWidth(Ogre::StringConverter::parseReal(cf.getSetting("Screen width","Stereoscopy")));
        inverseStereo(Ogre::StringConverter::parseBool(cf.getSetting("Inverse stereo","Stereoscopy")));

        return mode;
    }
Exemplo n.º 6
0
float ArtifexLoader::getMeshYAdjust(Ogre::String meshfile)
{
	Ogre::ConfigFile cfgfile;
	float realY = 0;
	try {
		cfgfile.load("y_correction_tables.cfg");
		realY = Ogre::StringConverter::parseReal(cfgfile.getSetting(meshfile));
	} catch (...){
		cout << "Troubles loading the y_correction_tables.cfg.\n";
		return 0;
	};
	return realY;
};
Exemplo n.º 7
0
void PhysicsMaterialFactory::readMaterialsFromFiles()
{
	// since we can run this whenever (like when we're tweaking files), we want to clear this first
	materials.clear();

	// get all of the filenames of the files in media/physicsmaterials
	std::string path = "media/physicsmaterials/";
	vector<string> files = direntSearch(path, ".physmat");

	for (string filename : files)
	{
		// rev up those files
		Ogre::ConfigFile cfile;
		cfile.load(filename, "=", true);

		auto sectionIterator = cfile.getSectionIterator();
		while (sectionIterator.hasMoreElements())
		{
			string matname = sectionIterator.peekNextKey();
			sectionIterator.moveNext();
			//if (matname.empty()) continue;
			
			ostringstream ssF,ssB,ssAD,ssLD;
			ssF << PhysicsMaterial::DEFAULT_FRICTION;
			ssB << PhysicsMaterial::DEFAULT_BOUNCINESS;
			ssAD << PhysicsMaterial::DEFAULT_ANGULAR_DAMPING;
			ssLD << PhysicsMaterial::DEFAULT_LINEAR_DAMPING;

			PhysicsMaterial *mat = new PhysicsMaterial(
				(float)atof(cfile.getSetting("Friction", matname, ssF.str()).c_str()),
				(float)atof(cfile.getSetting("Bounciness", matname, ssB.str()).c_str()),
				(float)atof(cfile.getSetting("AngularDamping", matname, ssAD.str()).c_str()),
				(float)atof(cfile.getSetting("LinearDamping", matname, ssLD.str()).c_str())
			);

			materials[matname] = mat;
		}
	}
}
Exemplo n.º 8
0
INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, int) {
	char  **argv;
    int    argc;

    // obtain command-line arguments in argv[] style array
    argv = GetArgvCommandLine(&argc);
#else
int main( int argc, char **argv ) {
#endif

    std::string cmdvar;
    int cmd = 0;

    Ogre::ConfigFile lconfig;
    lconfig.load("server.cfg");

    Ogre::String address = lconfig.getSetting("LocalAddress", "Network");
    unsigned int port = Ogre::StringConverter::parseInt(lconfig.getSetting("DefaultPort", "Network"));

    Server::ServerMain server = Server::ServerMain(lconfig);
    return 0;
}
Exemplo n.º 9
0
bool OgreSubsystem::LoadOgrePlugins(Ogre::String const & pluginsfile)
{
	Ogre::StringVector pluginList;
	Ogre::String pluginDir;
	Ogre::ConfigFile cfg;

	try
	{
		cfg.load( pluginsfile );
	}
	catch (Ogre::Exception)
	{
		Ogre::LogManager::getSingleton().logMessage(pluginsfile + " not found, automatic plugin loading disabled.");
		return false;
	}

	pluginDir = cfg.getSetting("PluginFolder"); // Ignored on Mac OS X, uses Resources/ directory
	pluginList = cfg.getMultiSetting("Plugin");

#if OGRE_PLATFORM != OGRE_PLATFORM_APPLE && OGRE_PLATFORM != OGRE_PLATFORM_IPHONE
	if (pluginDir.empty())
	{
		// User didn't specify plugins folder, try current one
		pluginDir = ".";
	}
#endif

	char last_char = pluginDir[pluginDir.length()-1];
	if (last_char != '/' && last_char != '\\')
	{
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
		pluginDir += "\\";
#elif OGRE_PLATFORM == OGRE_PLATFORM_LINUX
		pluginDir += "/";
#endif
	}

	for ( Ogre::StringVector::iterator it = pluginList.begin(); it != pluginList.end(); ++it )
	{
		Ogre::String pluginFilename = pluginDir + (*it);
		try
		{
			m_ogre_root->loadPlugin(pluginFilename);
		} 
		catch(Ogre::Exception &e)
		{
			LOG("failed to load plugin: " + pluginFilename + ": " + e.getFullDescription());
		}
	}
	return true;
}
Exemplo n.º 10
0
void loadRecord()
{
    Ogre::ConfigFile cfg;

    try
    {
        cfg.loadDirect(RECORD_FILE);
    }
    catch (Ogre::FileNotFoundException &)
    {
        std::ofstream out(RECORD_FILE);
        out << std::endl;
        out.close();

        cfg.loadDirect(RECORD_FILE);
    }

    GlbVar.records.firstTime = Ogre::StringConverter::parseBool(cfg.getSetting("firstTime", Ogre::StringUtil::BLANK, "yes"));

    Ogre::String highestLevelStr = cfg.getSetting("highestLevelIndex", Ogre::StringUtil::BLANK, "n");
    if (highestLevelStr != "n")
    {
        GlbVar.records.highestLevelIndex = Ogre::StringConverter::parseInt(highestLevelStr);
        if (GlbVar.records.highestLevelIndex >= GlbVar.woMgr->getNumWorlds())
            GlbVar.records.highestLevelIndex = GlbVar.firstLevel;
    }
    else
        GlbVar.records.highestLevelIndex = GlbVar.firstLevel;

    //Deserialise recordMap from string.
    Ogre::String recordMapStr = cfg.getSetting("records", Ogre::StringUtil::BLANK, "n");
    if (recordMapStr != "n")
    {
        std::stringstream recordMapStream(std::stringstream::in | std::stringstream::out);
        recordMapStream << recordMapStr;
        boost::archive::text_iarchive ia(recordMapStream);
        ia >> GlbVar.records.recordMap;
    }
Exemplo n.º 11
0
Render::Render(wxWindow* parent) : wxPanel(parent,
	wxID_ANY, wxPoint(), wxSize(100, 100)),
	mMapView(NULL), mWindow(NULL), mViewport(NULL), mActive(true)
{
	// Create Ogre render window.
	Ogre::NameValuePairList params;

	params["externalWindowHandle"] =
		Ogre::StringConverter::toString((size_t)GetHandle());

	Ogre::ConfigFile config;
	config.load("Ogre.cfg");

	if (config.getSetting("Render System") == "Direct3D9 Rendering Subsystem")
	{
		std::string aa = config.getSetting("Anti aliasing", "Direct3D9 Rendering Subsystem");
		std::string vs = config.getSetting("VSync", "Direct3D9 Rendering Subsystem");

		if (aa == "None") params["FSAA"] = "0";
		else if (aa == "Level 2") params["FSAA"] = "2";
		else if (aa == "Level 4") params["FSAA"] = "4";

		if (vs == "Yes") params["vsync"] = "1";
		else params["vsync"] = "0";
	}
	else if (config.getSetting("Render System") == "OpenGL Rendering Subsystem")
	{
		params["FSAA"] = config.getSetting("FSAA", "OpenGL Rendering Subsystem", "0");
		std::string vs = config.getSetting("VSync", "OpenGL Rendering Subsystem");

		if (vs == "Yes") params["vsync"] = "1";
		else params["vsync"] = "0";
	}

	// Create render window (Ogre).
	mWindow = Ogre::Root::getSingleton().createRenderWindow("3d-city", 1600, 1200, false, &params);
	mWindow->setActive(false);

	Ogre::Root::getSingleton().addFrameListener(this);

	// Connect events to wxWidgets window.
	Connect(wxEVT_ENTER_WINDOW, wxMouseEventHandler(Render::onEnterWindow), NULL, this);
	Connect(wxEVT_LEFT_DOWN, wxMouseEventHandler(Render::onLeftDown), NULL, this);
	Connect(wxEVT_LEFT_UP, wxMouseEventHandler(Render::onLeftUp), NULL, this);
	Connect(wxEVT_MOTION, wxMouseEventHandler(Render::onMotion), NULL, this);
	Connect(wxEVT_RIGHT_DOWN, wxMouseEventHandler(Render::onRightDown), NULL, this);
	Connect(wxEVT_RIGHT_UP, wxMouseEventHandler(Render::onRightUp), NULL, this);
	Connect(wxEVT_SIZE, wxSizeEventHandler(Render::onSize), NULL, this);
	Connect(wxEVT_MOUSEWHEEL, wxMouseEventHandler(Render::onWheel), NULL, this);

	// Set background colour to black.
	SetBackgroundColour(wxColour(0, 0, 0));

	// Start rendering.
	start();
}
Exemplo n.º 12
0
		virtual void setupResources(void)
		{
			GraphicsSystem::setupResources();

			Ogre::ConfigFile cf;
			cf.load(mResourcePath + "resources2.cfg");

			Ogre::String dataFolder = cf.getSetting("DoNotUseAsResource", "Hlms", "");

			if (dataFolder.empty())
				dataFolder = "./";
			else if (*(dataFolder.end() - 1) != '/')
				dataFolder += "/";

			dataFolder += "2.0/scripts/materials/PbsMaterials";

			addResourceLocation(dataFolder, "FileSystem", "General");
		}
Exemplo n.º 13
0
bool OgreSubsystem::LoadOgrePlugins(Ogre::String const & pluginsfile)
{
    Ogre::ConfigFile cfg;

    try
    {
        cfg.load( pluginsfile );
    }
    catch (Ogre::Exception e)
    {
        Ogre::LogManager::getSingleton().logMessage(pluginsfile + " not found, automatic plugin loading disabled. Message: " + e.getFullDescription());
        return false;
    }

    Ogre::String pluginDir = cfg.getSetting("PluginFolder");
    Ogre::StringVector pluginList = cfg.getMultiSetting("Plugin");

    if (pluginDir.empty())
    {
        pluginDir = RoR::App::sys_process_dir.GetActive();
    }

    for ( Ogre::StringVector::iterator it = pluginList.begin(); it != pluginList.end(); ++it )
    {
        Ogre::String pluginFilename = pluginDir + PATH_SLASH + (*it);
        try
        {
            m_ogre_root->loadPlugin(pluginFilename);
        }
        catch (Ogre::Exception &e)
        {
            LOG("failed to load plugin: " + pluginFilename + ": " + e.getFullDescription());
        }
    }
    return true;
}
Exemplo n.º 14
0
void CLASS::UpdateControls()
{

	int valuecounter = 0; // Going to be usefull for selections

	//Lang (Still not done)
	if (!IsLoaded)
	{
		m_lang->addItem("English (U.S.)");
	}
	m_lang->setIndexSelected(0); //TODO

	if (!IsLoaded)
	{
		m_gearbox_mode->addItem("Automatic shift");
		m_gearbox_mode->addItem("Manual shift - Auto clutch");
		m_gearbox_mode->addItem("Fully Manual: sequential shift");
		m_gearbox_mode->addItem("Fully Manual: stick shift");
		m_gearbox_mode->addItem("Fully Manual: stick shift with ranges");
	}

	//Gearbox
	Ogre::String gearbox_mode = GameSettingsMap["GearboxMode"];
	if (gearbox_mode == "Manual shift - Auto clutch")
		m_gearbox_mode->setIndexSelected(1);
	else if (gearbox_mode == "Fully Manual: sequential shift")
		m_gearbox_mode->setIndexSelected(2);
	else if (gearbox_mode == "Fully Manual: stick shift")
		m_gearbox_mode->setIndexSelected(3);
	else if (gearbox_mode == "Fully Manual: stick shift with ranges")
		m_gearbox_mode->setIndexSelected(4);
	else
		m_gearbox_mode->setIndexSelected(0);


	Ogre::RenderSystem* rs = Ogre::Root::getSingleton().getRenderSystem();
	// add all rendersystems to the list
	if (m_render_sys->getItemCount() == 0)
	{
		const Ogre::RenderSystemList list = Application::GetOgreSubsystem()->GetOgreRoot()->getAvailableRenderers();
		int selection = 0;
		for (Ogre::RenderSystemList::const_iterator it = list.begin(); it != list.end(); it++, valuecounter++)
		{
			if (rs && rs->getName() == (*it)->getName())
			{
				ExOgreSettingsMap["Render System"] = rs->getName();
				selection = valuecounter;
			}
			else if (!rs) {
				LOG("Error: No Ogre Render System found");
			}
			if (!IsLoaded)
			{
				m_render_sys->addItem(Ogre::String((*it)->getName()));
			}
		}
		m_render_sys->setIndexSelected(selection);
	}

	Ogre::ConfigFile cfg;
	cfg.load(SSETTING("ogre.cfg", "ogre.cfg"));

	//Few GameSettingsMap
	Ogre::String bFullScreen = cfg.getSetting("Full Screen", rs->getName());
	if (bFullScreen == "Yes")
	{
		ExOgreSettingsMap["Full Screen"] = "Yes";
		m_fullscreen->setStateCheck(true);
	}
	else
	{
		ExOgreSettingsMap["Full Screen"] = "No";
		m_fullscreen->setStateCheck(false);
	}

	Ogre::String bVsync = cfg.getSetting("VSync", rs->getName());
	if (bVsync == "Yes")
	{
		ExOgreSettingsMap["VSync"] = "Yes";
		m_vsync->setStateCheck(true);
	}
	else
	{
		ExOgreSettingsMap["VSync"] = "No";
		m_vsync->setStateCheck(false);
	}
		
	// store available rendering devices and available resolutions
	Ogre::ConfigOptionMap& CurrentRendererOptions = rs->getConfigOptions();
	Ogre::ConfigOptionMap::iterator configItr = CurrentRendererOptions.begin();
	Ogre::StringVector mFoundResolutions;
	Ogre::StringVector mFoundFSAA;
	while (configItr != CurrentRendererOptions.end())
	{
		if ((configItr)->first == "Video Mode")
		{
			// Store Available Resolutions
			mFoundResolutions = ((configItr)->second.possibleValues);
		}
		if ((configItr)->first == "FSAA")
		{
			// Store Available Resolutions
			mFoundFSAA = ((configItr)->second.possibleValues);
		}
		configItr++;
	}

	//Loop thru the vector for the resolutions
	valuecounter = 0; //Back to default
	Ogre::StringVector::iterator iterRes = mFoundResolutions.begin();
	for (; iterRes != mFoundResolutions.end(); iterRes++)
	{
		if (!IsLoaded)
		{
			m_resolution->addItem(Ogre::String((iterRes)->c_str()));
		}
		if ((iterRes)->c_str() == cfg.getSetting("Video Mode", rs->getName()))
		{
			ExOgreSettingsMap["Video Mode"] = (iterRes)->c_str();
			m_resolution->setIndexSelected(valuecounter);
		}
		valuecounter++;
	}

	//Loop thru the vector for the FSAAs
	valuecounter = 0; //Back to default
	Ogre::StringVector::iterator iterFSAA = mFoundFSAA.begin();
	for (; iterFSAA != mFoundFSAA.end(); iterFSAA++)
	{
		if (!IsLoaded)
		{
			m_fsaa->addItem(Ogre::String((iterFSAA)->c_str()));
		}
		if ((iterFSAA)->c_str() == cfg.getSetting("FSAA", rs->getName()))
		{
			ExOgreSettingsMap["FSAA"] = (iterFSAA)->c_str();
			m_fsaa->setIndexSelected(valuecounter);
		}
		
		valuecounter++;
	}

	//Few GameSettingsMap
	if (GameSettingsMap["ArcadeControls"] == "Yes")
		m_arc_mode->setStateCheck(true);
	else
		m_arc_mode->setStateCheck(false);

	if (GameSettingsMap["External Camera Mode"] == "Static")
		m_d_cam_pitch->setStateCheck(true);
	else
		m_d_cam_pitch->setStateCheck(false);

	if (GameSettingsMap["Creak Sound"] == "No")
		m_d_creak_sound->setStateCheck(true);
	else
		m_d_creak_sound->setStateCheck(false);

	//Fov
	m_fovexternal->setCaption(GameSettingsMap["FOV External"]);
	m_fovinternal->setCaption(GameSettingsMap["FOV Internal"]);

	
	//Texture Filtering
	Ogre::String texfilter = GameSettingsMap["Texture Filtering"];
	if (texfilter == "Bilinear")
		m_tex_filter->setIndexSelected(1);
	else if (texfilter == "Trilinear")
		m_tex_filter->setIndexSelected(2);
	else if (texfilter == "Anisotropic (best looking)")
		m_tex_filter->setIndexSelected(3);
	else
		m_tex_filter->setIndexSelected(0);

	if (!IsLoaded)
	{
		m_water_type->addItem("Hydrax"); //It's working good enough to be here now. 
	}

	if (BSETTING("DevMode", false) && !IsLoaded)
	{
		//Things that aren't ready to be used yet.
		m_sky_type->addItem("SkyX (best looking, slower)");
		m_shadow_type->addItem("Parallel-split Shadow Maps");
	}

	//Sky effects
	Ogre::String skytype = GameSettingsMap["Sky effects"];
	if (skytype == "Caelum (best looking, slower)")
		m_sky_type->setIndexSelected(1);
	else if (skytype == "SkyX (best looking, slower)" && BSETTING("DevMode", false))
		m_sky_type->setIndexSelected(2);
	else
		m_sky_type->setIndexSelected(0);

	//Shadow technique
	Ogre::String shadowtype = GameSettingsMap["Shadow technique"];
	if (shadowtype == "Texture shadows")
		m_shadow_type->setIndexSelected(1);
	else if (shadowtype == "Stencil shadows (best looking)")
		m_shadow_type->setIndexSelected(2);
	else if (shadowtype == "Parallel-split Shadow Maps" && BSETTING("DevMode", false))
		m_shadow_type->setIndexSelected(3);
	else
		m_shadow_type->setIndexSelected(0);

	//Water effects
	Ogre::String watertype = GameSettingsMap["Water effects"];
	if (watertype == "Reflection")
		m_water_type->setIndexSelected(1);
	else if (watertype == "Reflection + refraction (speed optimized)")
		m_water_type->setIndexSelected(2);
	else if (watertype == "Reflection + refraction (quality optimized)")
		m_water_type->setIndexSelected(3);
	else if (watertype == "Hydrax")
		m_water_type->setIndexSelected(4);
	else
		m_water_type->setIndexSelected(0);
		
	//Vegetation
	Ogre::String vegetationtype = GameSettingsMap["Vegetation"];
	if (vegetationtype == "20%")
		m_vegetation->setIndexSelected(1);
	else if (vegetationtype == "50%")
		m_vegetation->setIndexSelected(2);
	else if (vegetationtype == "Full (best looking, slower)")
		m_vegetation->setIndexSelected(3);
	else
		m_vegetation->setIndexSelected(0);

	//Light source effects
	Ogre::String lightstype = GameSettingsMap["Lights"];
	if (lightstype == "Only current vehicle, main lights")
		m_light_source_effects->setIndexSelected(1);
	else if (lightstype == "All vehicles, main lights")
		m_light_source_effects->setIndexSelected(2);
	else if (lightstype == "All vehicles, all lights")
		m_light_source_effects->setIndexSelected(3);
	else
		m_light_source_effects->setIndexSelected(0);
	
	//Speed until selection
	Ogre::String speedunit = GameSettingsMap["SpeedUnit"];
	if (speedunit == "Metric")
		m_speed_unit->setIndexSelected(1);
	else
		m_speed_unit->setIndexSelected(0);

	//Other configs
	if (GameSettingsMap["DigitalSpeedo"] == "Yes")
		m_digital_speedo->setStateCheck(true);
	else
		m_digital_speedo->setStateCheck(false);

	if (GameSettingsMap["Particles"] == "Yes")
		m_psystem->setStateCheck(true);
	else
		m_psystem->setStateCheck(false);

	if (GameSettingsMap["HeatHaze"] == "Yes")
		m_heathaze->setStateCheck(true);
	else
		m_heathaze->setStateCheck(false);

	if (GameSettingsMap["Mirrors"] == "Yes")
		m_mirrors->setStateCheck(true);
	else
		m_mirrors->setStateCheck(false);

	if (GameSettingsMap["Sunburn"] == "Yes")
		m_sunburn->setStateCheck(true);
	else
		m_sunburn->setStateCheck(false);

	if (GameSettingsMap["HDR"] == "Yes")
		m_hdr->setStateCheck(true);
	else
		m_hdr->setStateCheck(false);

	if (GameSettingsMap["Motion blur"] == "Yes")
		m_mblur->setStateCheck(true);
	else
		m_mblur->setStateCheck(false);

	if (GameSettingsMap["Skidmarks"] == "Yes")
		m_skidmarks->setStateCheck(true);
	else
		m_skidmarks->setStateCheck(false);

	if (GameSettingsMap["Envmap"] == "Yes")
		m_hq_ref->setStateCheck(true);
	else
		m_hq_ref->setStateCheck(false);

	if (GameSettingsMap["Glow"] == "Yes")
		m_glow->setStateCheck(true);
	else
		m_glow->setStateCheck(false);

	if (GameSettingsMap["DOF"] == "Yes")
		m_dof->setStateCheck(true);
	else
		m_dof->setStateCheck(false);

	if (GameSettingsMap["Waves"] == "Yes")
		m_e_waves->setStateCheck(true);
	else
		m_e_waves->setStateCheck(false);

	if (GameSettingsMap["Shadow optimizations"] == "Yes")
		m_sh_pf_opti->setStateCheck(true);
	else
		m_sh_pf_opti->setStateCheck(false);

	if (GameSettingsMap["AsynchronousPhysics"] == "Yes")
		m_enable_async_physics->setStateCheck(true);
	else
		m_enable_async_physics->setStateCheck(false);

	if (GameSettingsMap["DisableCollisions"] == "Yes")
		m_disable_inter_collsion->setStateCheck(true);
	else
		m_disable_inter_collsion->setStateCheck(false);

	if (GameSettingsMap["DisableSelfCollisions"] == "Yes")
		m_disable_intra_collision->setStateCheck(true);
	else
		m_disable_intra_collision->setStateCheck(false);

	if (GameSettingsMap["Multi-threading"] == "No")
		m_disable_multithreading->setStateCheck(true);
	else
		m_disable_multithreading->setStateCheck(false);

	//Volume slider
	long sound_volume = Ogre::StringConverter::parseLong(GameSettingsMap["Sound Volume"], 100);
	m_volume_slider->setScrollRange(101);
	m_volume_slider->setScrollPosition(sound_volume -1);
	if (m_volume_slider->getScrollPosition() >= 100)
		m_volume_indicator->setCaption("100%");
	else
		m_volume_indicator->setCaption(Ogre::StringConverter::toString(sound_volume) + "%");

	//Audio Devices
	valuecounter = 0; //Back to default
	char *devices = (char *)alcGetString(NULL, ALC_ALL_DEVICES_SPECIFIER);
	while (devices && *devices != 0)
	{
		if (!IsLoaded)
		{
			m_audio_dev->addItem(Ogre::String(devices));
		}
		if (Ogre::String(devices) == GameSettingsMap["AudioDevice"])
			m_audio_dev->setIndexSelected(valuecounter);

		devices += strlen(devices) + 1; //next device
		valuecounter++;
	}

	//FPS Limiter slider
	long fps_limit = Ogre::StringConverter::parseLong(GameSettingsMap["FPS-Limiter"], 60);
	m_fps_limiter_slider->setScrollRange(200);
	m_fps_limiter_slider->setScrollPosition(fps_limit -1);


	if (fps_limit >= 199)
		m_fps_limiter_indicator->setCaption("Unlimited");
	else
		m_fps_limiter_indicator->setCaption(Ogre::StringConverter::toString(fps_limit) + " FPS");

	//SightRange slider
	long sight_range = Ogre::StringConverter::parseLong(GameSettingsMap["SightRange"], 5000);
	m_sightrange->setScrollRange(5000);
	m_sightrange->setScrollPosition(sight_range -1);
	if (sight_range >= 4999)
		m_sightrange_indicator->setCaption("Unlimited");
	else
		m_sightrange_indicator->setCaption(Ogre::StringConverter::toString(sight_range) + " m");		

	if (GameSettingsMap["Replay mode"] == "Yes")
		m_enable_replay->setStateCheck(true);
	else
		m_enable_replay->setStateCheck(false);

	if (GameSettingsMap["Screenshot Format"] == "png (bigger, no quality loss)")
		m_hq_screenshots->setStateCheck(true);
	else
		m_hq_screenshots->setStateCheck(false);

	if (GameSettingsMap["ChatAutoHide"] == "Yes")
		m_autohide_chatbox->setStateCheck(true);
	else
		m_autohide_chatbox->setStateCheck(false);
}
Exemplo n.º 15
0
Water::Water(const Ogre::ConfigFile &mTerrainConfig) :
	maxampl(0),
	free_wavetrain(0),
	visible(true),
	haswaves(BSETTING("Waves", false)),
	mScale(1.0f),
	vRtt1(0),
	vRtt2(0), 
	mRenderCamera(gEnv->mainCamera),
	pWaterNode(0),
	framecounter(0),
	rttTex1(0),
	rttTex2(0),
	mReflectCam(0),
	mRefractCam(0)
{
	//Ugh.. Why so ugly and hard to read
	mapSize = gEnv->terrainManager->getMaxTerrainSize();
	fade = gEnv->sceneManager->getFogColour();
	waterSceneMgr = gEnv->sceneManager;

	wHeight = PARSEREAL(mTerrainConfig.getSetting("WaterLine", "General"));
	wbHeight = PARSEREAL(mTerrainConfig.getSetting("WaterBottomLine", "General"));

	if (mapSize.x < 1500 && mapSize.z < 1500)
		mScale = 1.5f;

	// disable waves in multiplayer
	if (gEnv->multiplayer)
		haswaves = false;

	// and the type
	String waterSettingsString = SSETTING("Water effects", "Reflection + refraction (speed optimized)");
	if (waterSettingsString == "Basic (fastest)")
		mType = WATER_BASIC;
	if (waterSettingsString == "Reflection")
		mType = WATER_REFLECT;
	else if (waterSettingsString == "Reflection + refraction (speed optimized)")
		mType = WATER_FULL_SPEED;
	else if (waterSettingsString == "Reflection + refraction (quality optimized)")
		mType = WATER_FULL_QUALITY;

	if (haswaves)
	{
		char line[1024] = {};
		FILE *fd = fopen((SSETTING("Config Root", "")+"wavefield.cfg").c_str(), "r");
		if (fd)
		{
			while (!feof(fd))
			{
				int res = fscanf(fd," %[^\n\r]",line);
				if (line[0] == ';') continue;
				float wl,amp,mx,dir;
				res = sscanf(line,"%f, %f, %f, %f",&wl,&amp,&mx,&dir);
				if (res < 4) continue;
				wavetrains[free_wavetrain].wavelength=wl;
				wavetrains[free_wavetrain].amplitude=amp;
				wavetrains[free_wavetrain].maxheight=mx;
				wavetrains[free_wavetrain].direction=dir/57.0;
				wavetrains[free_wavetrain].dir_sin=sin(wavetrains[free_wavetrain].direction);
				wavetrains[free_wavetrain].dir_cos=cos(wavetrains[free_wavetrain].direction);
				free_wavetrain++;
			}
			fclose(fd);
		}
		for (int i=0; i<free_wavetrain; i++)
		{
			wavetrains[i].wavespeed=1.25*sqrt(wavetrains[i].wavelength);
			maxampl+=wavetrains[i].maxheight;
		}
	}

	processWater(mType);
}
Exemplo n.º 16
0
// -------------------------------------------------------------------------
void Terrain_Demo::init(Ogre::Root *root, Ogre::RenderWindow *win, OgreBulletApplication *application)
{
    mCameraMove = 1;

    mHelpKeys.clear();
    mHelpKeys.push_back(BASIC_HELP_INFO0);
    mHelpKeys.push_back(BASIC_HELP_INFO1);
    mHelpKeys.push_back(BASIC_HELP_INFO2);
    mHelpKeys.push_back(BASIC_HELP_INFO3);
    mHelpKeys.push_back(BASIC_HELP_INFO4);
    mHelpKeys.push_back(BASIC_HELP_INFO5);
    mHelpKeys.push_back(BASIC_HELP_INFO6);
    mHelpKeys.push_back("Use Arrow Key to move Car.");

// reset
    for (int i = 0; i < 4; i++)
    {
        mWheelsEngine[i] = 0;
        mWheelsSteerable[i] = 0;
    }
    mWheelsEngineCount = 2;
    mWheelsEngine[0] = 0;
    mWheelsEngine[1] = 1;
    mWheelsEngine[2] = 2;
    mWheelsEngine[3] = 3;

    mWheelsSteerableCount = 2;
    mWheelsSteerable[0] = 0;
    mWheelsSteerable[1] = 1;
    //mWheelsSteerable[2] = 2;
    //mWheelsSteerable[3] = 3;

    mWheelEngineStyle = 0;
    mWheelSteeringStyle = 0;

    mSteeringLeft = false;
    mSteeringRight = false;

    mEngineForce = 0;
    mSteering = 0;

    // ------------------------
    // Start OgreScene
    mSceneMgr = root->createSceneManager("TerrainSceneManager", "BulletTerrain");

    mCamera = mSceneMgr->createCamera("Cam");
    //mCamera->setFOVy(Degree(90));
    mCamera->setNearClipDistance(0.1);
    mCamera->setFarClipDistance(1000);
    Viewport *vp = win->addViewport(mCamera);
    vp->setBackgroundColour(ColourValue(0,0,0));
    // Alter the camera aspect ratio to match the viewport
    mCamera->setAspectRatio(
        Real(vp->getActualWidth()) / Real(vp->getActualHeight()));
    mCamera->setPosition(CameraStart + terrain_Shift);
    mCamera->lookAt(CarPosition + terrain_Shift);


    // Create a terrain
    std::string terrain_cfg("terrain.cfg");
    mSceneMgr->setWorldGeometry(terrain_cfg);

    OgreBulletListener::init(root, win, application);

    // ------------------------
    // add lights
    setBasicLight();

    // ------------------------
    // Add the Gui
    setPhysicGUI();
    // ------------------------
    // Start Bullet
    initWorld();

    // ------------------------
    // Add the ground

    // 0.1, 0.8
    //addStaticPlane(0.3, 0.8);

    {
        Ogre::ConfigFile config;

        config.loadFromResourceSystem(terrain_cfg, ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME, "=", true);

        unsigned page_size = Ogre::StringConverter::parseUnsignedInt(config.getSetting("PageSize"));

        Ogre::Vector3 terrainScale(Ogre::StringConverter::parseReal(config.getSetting("PageWorldX")) / (page_size - 1),
                                   Ogre::StringConverter::parseReal(config.getSetting("MaxHeight")),
                                   Ogre::StringConverter::parseReal(config.getSetting("PageWorldZ")) / (page_size - 1));

        Ogre::String terrainfileName = config.getSetting("Heightmap.image");

        float *heights = new float[page_size*page_size];

        Ogre::Image terrainHeightMap;
        terrainHeightMap.load(terrainfileName, Ogre::ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME);

        for (unsigned y = 0; y < page_size; ++y)
        {
            for (unsigned x = 0; x < page_size; ++x)
            {
                Ogre::ColourValue color = terrainHeightMap.getColourAt(x, y, 0);
                heights[x + y * page_size] = color.r;
            }
        }

        mTerrainShape = new HeightmapCollisionShape(page_size,
                page_size,
                terrainScale,
                heights,
                true);

        RigidBody *defaultTerrainBody = new RigidBody("Terrain",
                mWorld);

        const float terrainBodyRestitution = 0.1f;
        const float terrainBodyFriction    = 0.8f;

        Ogre::Vector3 terrainShiftPos( (terrainScale.x * (page_size - 1) / 2), \
                                       0,
                                       (terrainScale.z * (page_size - 1) / 2));

        terrainShiftPos.y = terrainScale.y / 2 * terrainScale.y;

        Ogre::SceneNode* pTerrainNode = mSceneMgr->getRootSceneNode()->createChildSceneNode();
        defaultTerrainBody->setStaticShape (pTerrainNode, mTerrainShape, terrainBodyRestitution, terrainBodyFriction, terrainShiftPos);

        mBodies.push_back(defaultTerrainBody);
        mShapes.push_back(mTerrainShape);
    }




    // create obstacle in front of car
    addCube("obstacle", Ogre::Vector3(13,  -5.25, -5) + terrain_Shift ,  Quaternion(Radian(Degree(22.5)), Ogre::Vector3::UNIT_X), Ogre::Vector3(1, 1, 1), 0.3, 0.8, 0);
    addCube("obstacle", Ogre::Vector3(15,  -5.25, -5) + terrain_Shift ,  Quaternion(Radian(Degree(22.5)), Ogre::Vector3::UNIT_X), Ogre::Vector3(1, 1, 1), 0.3, 0.8, 0);
    addCube("obstacle", Ogre::Vector3(17,  -5.25, -5) + terrain_Shift ,  Quaternion(Radian(Degree(22.5)), Ogre::Vector3::UNIT_X), Ogre::Vector3(1, 1, 1), 0.3, 0.8, 0);

    addCube("obstacle", Ogre::Vector3(13,  -5.25, -10) + terrain_Shift , Quaternion(Radian(Degree(-22.5)), Ogre::Vector3::UNIT_X), Ogre::Vector3(1, 1, 1), 0.3, 0.8, 0);
    addCube("obstacle", Ogre::Vector3(15,  -5.25, -10) + terrain_Shift , Quaternion(Radian(Degree(-22.5)), Ogre::Vector3::UNIT_X), Ogre::Vector3(1, 1, 1), 0.3, 0.8, 0);
    addCube("obstacle", Ogre::Vector3(17,  -5.25, -10) + terrain_Shift , Quaternion(Radian(Degree(-22.5)), Ogre::Vector3::UNIT_X), Ogre::Vector3(1, 1, 1), 0.3, 0.8, 0);

    // create obstacle a bit aside
    addCube("obstacle", Ogre::Vector3(-2,  0, -5) + terrain_Shift ,  Quaternion(Radian(Degree(45.0)), Ogre::Vector3::UNIT_X), Ogre::Vector3(1, 1, 1), 0.3, 0.8, 0);
    addCube("obstacle", Ogre::Vector3(0,  0, -5) + terrain_Shift ,   Quaternion(Radian(Degree(45.0)), Ogre::Vector3::UNIT_X), Ogre::Vector3(1, 1, 1), 0.3, 0.8, 0);
    addCube("obstacle", Ogre::Vector3(2,  0, -5) + terrain_Shift ,   Quaternion(Radian(Degree(45.0)), Ogre::Vector3::UNIT_X), Ogre::Vector3(1, 1, 1), 0.3, 0.8, 0);

    addCube("obstacle", Ogre::Vector3(-2,  0, -10) + terrain_Shift , Quaternion(Radian(Degree(-45.0)), Ogre::Vector3::UNIT_X), Ogre::Vector3(1, 1, 1), 0.3, 0.8, 0);
    addCube("obstacle", Ogre::Vector3(0,  0, -10) + terrain_Shift ,  Quaternion(Radian(Degree(-45.0)), Ogre::Vector3::UNIT_X), Ogre::Vector3(1, 1, 1), 0.3, 0.8, 0);
    addCube("obstacle", Ogre::Vector3(2,  0, -10) + terrain_Shift ,  Quaternion(Radian(Degree(-45.0)), Ogre::Vector3::UNIT_X), Ogre::Vector3(1, 1, 1), 0.3, 0.8, 0);

    // create obstacle just for fun
    addCube("obstacle", Ogre::Vector3(25, -10, -25) + terrain_Shift , Quaternion(Radian(Degree(45.0)), Ogre::Vector3::UNIT_Z), Ogre::Vector3(1, 1, 1), 0.3, 0.8, 0);
    addCube("obstacle", Ogre::Vector3(25, -10, -27) + terrain_Shift , Quaternion(Radian(Degree(45.0)), Ogre::Vector3::UNIT_Z), Ogre::Vector3(1, 1, 1), 0.3, 0.8, 0);
    addCube("obstacle", Ogre::Vector3(25, -10, -29) + terrain_Shift , Quaternion(Radian(Degree(45.0)), Ogre::Vector3::UNIT_Z), Ogre::Vector3(1, 1, 1), 0.3, 0.8, 0);




    /// create vehicle
    {
        const Ogre::Vector3 chassisShift(0, 1.0, 0);
        float connectionHeight = 0.7f;

        mChassis = mSceneMgr->createEntity(
                       "chassis" + StringConverter::toString(mNumEntitiesInstanced++),
                       "chassis.mesh");

        SceneNode *node = mSceneMgr->getRootSceneNode ()->createChildSceneNode ();

        SceneNode *chassisnode = node->createChildSceneNode ();
        chassisnode->attachObject (mChassis);
        chassisnode->setPosition (chassisShift);


        mChassis->setQueryFlags (GEOMETRY_QUERY_MASK);
#if (OGRE_VERSION < ((1 << 16) | (5 << 8) | 0)) // only applicable before shoggoth (1.5.0)
        mChassis->setNormaliseNormals(true);
#endif
        mChassis->setCastShadows(true);



        CompoundCollisionShape* compound = new CompoundCollisionShape();

        BoxCollisionShape* chassisShape = new BoxCollisionShape(Ogre::Vector3(1.f,0.75f,2.1f));
        compound->addChildShape(chassisShape, chassisShift);

        mCarChassis = new WheeledRigidBody("carChassis", mWorld);

        mCarChassis->setShape(node,
                              compound,
                              0.6, //restitution
                              0.6, //friction
                              800, //bodyMass
                              CarPosition + terrain_Shift,
                              Quaternion::IDENTITY);

        mCarChassis->setDamping(0.2, 0.2);

        mCarChassis->disableDeactivation();
        mTuning = new VehicleTuning(gSuspensionStiffness,
                                    gSuspensionCompression,
                                    gSuspensionDamping,
                                    gMaxSuspensionTravelCm,
                                    gMaxSuspensionForce,
                                    gFrictionSlip);

        mVehicleRayCaster = new VehicleRayCaster(mWorld);
        mVehicle = new RaycastVehicle(mCarChassis, mTuning, mVehicleRayCaster);

        {
            int rightIndex = 0;
            int upIndex = 1;
            int forwardIndex = 2;

            mVehicle->setCoordinateSystem(rightIndex, upIndex, forwardIndex);

            Ogre::Vector3 wheelDirectionCS0(0,-1,0);
            Ogre::Vector3 wheelAxleCS(-1,0,0);

            for (size_t i = 0; i < 4; i++)
            {
                mWheels[i] = mSceneMgr->createEntity(
                                 "wheel" + StringConverter::toString(mNumEntitiesInstanced++),
                                 "wheel.mesh");

                mWheels[i]->setQueryFlags (GEOMETRY_QUERY_MASK);
#if (OGRE_VERSION < ((1 << 16) | (5 << 8) | 0)) // only applicable before shoggoth (1.5.0)
                mWheels[i]->setNormaliseNormals(true);
#endif
                mWheels[i]->setCastShadows(true);

                mWheelNodes[i] = mSceneMgr->getRootSceneNode ()->createChildSceneNode ();
                mWheelNodes[i]->attachObject (mWheels[i]);

            }

            {
                bool isFrontWheel = true;

                Ogre::Vector3 connectionPointCS0 (
                    CUBE_HALF_EXTENTS-(0.3*gWheelWidth),
                    connectionHeight,
                    2*CUBE_HALF_EXTENTS-gWheelRadius);


                mVehicle->addWheel(
                    mWheelNodes[0],
                    connectionPointCS0,
                    wheelDirectionCS0,
                    wheelAxleCS,
                    gSuspensionRestLength,
                    gWheelRadius,
                    isFrontWheel, gWheelFriction, gRollInfluence);

                connectionPointCS0 = Ogre::Vector3(
                                         -CUBE_HALF_EXTENTS+(0.3*gWheelWidth),
                                         connectionHeight,
                                         2*CUBE_HALF_EXTENTS-gWheelRadius);


                mVehicle->addWheel(
                    mWheelNodes[1],
                    connectionPointCS0,
                    wheelDirectionCS0,
                    wheelAxleCS,
                    gSuspensionRestLength,
                    gWheelRadius,
                    isFrontWheel, gWheelFriction, gRollInfluence);


                connectionPointCS0 = Ogre::Vector3(
                                         -CUBE_HALF_EXTENTS+(0.3*gWheelWidth),
                                         connectionHeight,
                                         -2*CUBE_HALF_EXTENTS+gWheelRadius);

                isFrontWheel = false;
                mVehicle->addWheel(
                    mWheelNodes[2],
                    connectionPointCS0,
                    wheelDirectionCS0,
                    wheelAxleCS,
                    gSuspensionRestLength,
                    gWheelRadius,
                    isFrontWheel, gWheelFriction, gRollInfluence);

                connectionPointCS0 = Ogre::Vector3(
                                         CUBE_HALF_EXTENTS-(0.3*gWheelWidth),
                                         connectionHeight,
                                         -2*CUBE_HALF_EXTENTS+gWheelRadius);

                mVehicle->addWheel(
                    mWheelNodes[3],
                    connectionPointCS0,
                    wheelDirectionCS0,
                    wheelAxleCS,
                    gSuspensionRestLength,
                    gWheelRadius,
                    isFrontWheel, gWheelFriction, gRollInfluence);

                //mVehicle->setWheelsAttached();

            }

        }
    }

}
Exemplo n.º 17
0
CEngine::CEngine(void)
	: m_Root(NULL)
{
	TCHAR szPath[MAX_PATH];

	CString ApplicationName = "SceneEditor.exe";

	GetModuleFileName(NULL, szPath, MAX_PATH);
    Ogre::ConfigFile OgreConfigFile;
	CString ApplicationPath(szPath);

	ApplicationPath = ApplicationPath.Left(ApplicationPath.GetLength() - ApplicationName.GetLength());

	m_Root = new Ogre::Root("", "", Ogre::String(ApplicationPath + "SceneEditor.log")); 

	OgreConfigFile.load(Ogre::String(ApplicationPath + "ogre.cfg"), "\t:=", false);

	Ogre::String RenderSystemName;
	RenderSystemName = OgreConfigFile.getSetting("Render System");

		if (RenderSystemName == "Direct3D9 Rendering Subsystem")
		{
#ifdef _DEBUG
			m_Root->loadPlugin("RenderSystem_Direct3D9_d");
#else
		    m_Root->loadPlugin("RenderSystem_Direct3D9");
#endif
		}
		else			
		if(RenderSystemName == "OpenGL Rendering Subsystem")
		{
#ifdef _DEBUG
			m_Root->loadPlugin("RenderSystem_GL_d");
#else
		    m_Root->loadPlugin("RenderSystem_GL");
#endif
		}
		else
		{
#ifdef _DEBUG		 
			m_Root->loadPlugin("RenderSystem_Direct3D9_d");
#else
			m_Root->loadPlugin("RenderSystem_Direct3D9");
#endif
		}

#ifdef _DEBUG
		m_Root->loadPlugin("Plugin_ParticleFX_d");
#else
        m_Root->loadPlugin("Plugin_ParticleFX");
#endif

		Ogre::RenderSystemList RendersList = m_Root->getAvailableRenderers();
		m_Root->setRenderSystem(RendersList[0]);

    //
    // Initialize the system, but don't create a render window.
    //

		// Load resource paths from config file
        Ogre::ConfigFile cf;
		Ogre::String ResourcePath = ApplicationPath + "resources_d.cfg";
        cf.load(ResourcePath);

        // Go through all sections & settings in the file
        Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator();

        Ogre::String secName, typeName, archName;

		while (seci.hasMoreElements())
        {
            secName = seci.peekNextKey();
            Ogre::ConfigFile::SettingsMultiMap *settings = seci.getNext();
            Ogre::ConfigFile::SettingsMultiMap::iterator i;

			for (i = settings->begin(); i != settings->end(); ++i)
            {
                typeName = i->first;
                archName = i->second;
				archName = Ogre::String(ApplicationPath) + archName;
                Ogre::ResourceGroupManager::getSingleton().addResourceLocation(archName, typeName, secName);
            }
        }

    m_Root->initialise(false);
}
Exemplo n.º 18
0
void loadSettings()
{
    Ogre::ConfigFile cfg;

    if (Util::pathExists(SETTINGS_FILE))
        cfg.loadDirect(SETTINGS_FILE);
    else
        cfg.loadDirect(DEFAULT_SETTINGS_FILE);

    //--- Ogre -------------------------------------------------------------------------
    
    GlbVar.settings.ogre.pluginDirectory = cfg.getSetting("pluginDirectory", "ogre", ".");
    GlbVar.settings.ogre.plugins = Ogre::StringConverter::parseStringVector(
            cfg.getSetting("plugins", "ogre", "Plugin_CgProgramManager Plugin_ParticleFX Plugin_OctreeSceneManager")
            );

    GlbVar.settings.ogre.renderer = cfg.getSetting("renderer", "ogre", "OpenGL") == "Direct3D"
        ? Globals::Settings::OgreSettings::DIRECT3D
        : Globals::Settings::OgreSettings::OPENGL;

    GlbVar.settings.ogre.winWidth = Ogre::StringConverter::parseReal(cfg.getSetting("width", "ogre", "1024"));
    GlbVar.settings.ogre.winHeight = Ogre::StringConverter::parseReal(cfg.getSetting("height", "ogre", "768"));
    GlbVar.settings.ogre.winFullscreen = Ogre::StringConverter::parseBool(cfg.getSetting("fullscreen", "ogre", "no"));
    GlbVar.settings.ogre.FSAA = cfg.getSetting("FSAA", "ogre", "0");
    GlbVar.settings.ogre.vsync = cfg.getSetting("vsync", "ogre", "no");

    //--- Graphics ---------------------------------------------------------------------

    GlbVar.settings.graphics.lighting = Ogre::StringConverter::parseBool(cfg.getSetting("lighting", "graphics", "yes"));
    GlbVar.settings.graphics.shadows = Ogre::StringConverter::parseBool(cfg.getSetting("shadows", "graphics", "yes"));
    GlbVar.settings.graphics.normalMapping = Ogre::StringConverter::parseBool(cfg.getSetting("normalMapping", "graphics", "yes"));
    GlbVar.settings.graphics.parallaxMapping = Ogre::StringConverter::parseBool(cfg.getSetting("parallaxMapping", "graphics", "yes"));

    //--- Controls ---------------------------------------------------------------------

    GlbVar.settings.controls.turningSensitivity = Ogre::StringConverter::parseReal(cfg.getSetting("turningSensitivity", "controls", "0.2"));
    GlbVar.settings.controls.upDownSensitivity = Ogre::StringConverter::parseReal(cfg.getSetting("upDownSensitivity", "controls", "1"));
    GlbVar.settings.controls.invertMouse = Ogre::StringConverter::parseBool(cfg.getSetting("invertMouse", "controls", "1"));

    GlbVar.settings.controls.keys["forward"] = GlbVar.keyMap->stringToKey(cfg.getSetting("forward", "controls", "W"), OIS::KC_W);
    GlbVar.settings.controls.keys["backward"] = GlbVar.keyMap->stringToKey(cfg.getSetting("backward", "controls", "S"), OIS::KC_W);
    GlbVar.settings.controls.keys["left"] = GlbVar.keyMap->stringToKey(cfg.getSetting("left", "controls", "A"), OIS::KC_W);
    GlbVar.settings.controls.keys["right"] = GlbVar.keyMap->stringToKey(cfg.getSetting("right", "controls", "D"), OIS::KC_W);

    GlbVar.settings.controls.keys["dimensionSwitch"] = GlbVar.keyMap->stringToKey(cfg.getSetting("dimensionSwitch", "controls", "SPACE"), OIS::KC_W);
    GlbVar.settings.controls.keys["gravitySwitch"] = GlbVar.keyMap->stringToKey(cfg.getSetting("gravitySwitch", "controls", "G"), OIS::KC_W);
    GlbVar.settings.controls.keys["selfDestruct"] = GlbVar.keyMap->stringToKey(cfg.getSetting("selfDestruct", "controls", "Z"), OIS::KC_W);

    GlbVar.settings.controls.keys["peepLeft"] = GlbVar.keyMap->stringToKey(cfg.getSetting("peepLeft", "controls", "Q"), OIS::KC_W);
    GlbVar.settings.controls.keys["peepRight"] = GlbVar.keyMap->stringToKey(cfg.getSetting("peepRight", "controls", "E"), OIS::KC_W);

    //--- Misc. ------------------------------------------------------------------------

    GlbVar.settings.misc.fixCameraObstruction = Ogre::StringConverter::parseBool(cfg.getSetting("fixCameraObstruction", "misc", "yes"));

    //----------------------------------------------------------------------------------
}
Exemplo n.º 19
0
/****************************************************************************
**
** Copyright (C) 2016 - 2017
**
** 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 go (ODS 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 "ogre3_renderman.h"
#include "OgreConfigFile.h"
#include "OgreArchiveManager.h"
#include "OgreHlms.h"
#include "OgreHlmsUnlit.h"
#include "OgreHlmsPbs.h"
#include "OgreHlmsManager.h"
#include "OgreHlmsCommon.h"
#include "OgreLogManager.h"
#include "OgreFrameStats.h"

namespace Magus
{
    //****************************************************************************/
    OgreManager::OgreManager(void)
    {
        mGlContext = 0;
        mCompositorPassProvider = 0;
        mPause = true;

        #if _DEBUG || DEBUG
            mResourcesCfg = "resources_d.cfg";
            mPluginsCfg = "plugins_d.cfg";
        #else
            mResourcesCfg = "resources.cfg";
            mPluginsCfg = "plugins.cfg";
        #endif

        // Create Ogre tt and initialize
        mRoot = new Ogre::Root(mPluginsCfg);

        // Setup renderer
        mCurrentRenderSystem = 0;
        const Ogre::RenderSystemList& rsList = mRoot->getAvailableRenderers();
        Ogre::RenderSystem* renderSystem = rsList[0];
        std::vector<Ogre::String> renderOrder;
        #if defined(Q_OS_WIN)
            renderOrder.push_back("Direct3D11");
        #endif
            renderOrder.push_back("OpenGL 3+");
        for (std::vector<Ogre::String>::iterator iter = renderOrder.begin(); iter != renderOrder.end(); iter++)
        {
            for (Ogre::RenderSystemList::const_iterator it = rsList.begin(); it != rsList.end(); it++)
            {
                if ((*it)->getName().find(*iter) != Ogre::String::npos)
                {
                    renderSystem = *it;
                    break;
                }
            }
            if (renderSystem != 0) break;
        }

        if (renderSystem == 0)
        {
            if (!mRoot->restoreConfig())
            {
                if (!mRoot->showConfigDialog())
                    OGRE_EXCEPT(Ogre::Exception::ERR_INVALIDPARAMS, "Abort render system configuration", "OgreManager::OgreManager");
            }
        }

        renderSystem->setConfigOption("Full Screen", "No");
        renderSystem->setConfigOption("VSync", "Yes");
        mRoot->setRenderSystem(renderSystem);
        mCurrentRenderSystem = renderSystem;

        // Uncomment next line to show dialog
        //if(mRoot->restoreConfig() || mRoot->showConfigDialog())
        //{
            mRoot->initialise(false);
        //}


        // Initialize resources
        setupResources();

        // Start timer
        mTimer = new Ogre::Timer();
        mTimer->reset();
    }

    //****************************************************************************/
    OgreManager::~OgreManager(void)
    {
        // Added removeAllWorkspaces after Ogre 2.1 upgrade (commit 2783a361c0b8)
        // In debug mode, the application crashed in deleting mRoot
        Ogre::CompositorManager2* compositorManager = mRoot->getCompositorManager2();
        compositorManager->removeAllWorkspaces();

        // Delete the dummy CompositorPassProvider
        compositorManager->setCompositorPassProvider(0);
        OGRE_DELETE mCompositorPassProvider;

        // Destroy render textures
        // This is a piece of custom code specific for the HLMS Editor (assume that the OgreWidget is still available)
        QMap<int, QOgreWidget*>::iterator i;
        QOgreWidget* item = 0;
        for (i = mQOgreWidgetMap.begin(); i != mQOgreWidgetMap.end(); ++i)
        {
            item = i.value();
            item->cleanup();
        }

        // Delete Ogre root
        delete mRoot;
    }

    //-------------------------------------------------------------------------------------
    void OgreManager::initialize(void)
    {
        // Create dummy CompositorPassProvider (see http://www.ogre3d.org/forums/viewtopic.php?f=11&t=84816&p=525752&hilit=CompositorPassProvider#p525752)
        // If one of the resource locations contains a compositor with a custom pass, the editor doesn't work anymore. This is to prevent it
        Ogre::MyCompositorPassProvider* mCompositorPassProvider = OGRE_NEW Ogre::MyCompositorPassProvider;
        Ogre::CompositorManager2* compositorManager = mRoot->getCompositorManager2();
        compositorManager->setCompositorPassProvider(mCompositorPassProvider);

        // After resources have been setup and renderwindows created (in ogre widget), the Hlms managers are registered
        registerHlms();

        // Initialise, parse scripts etc
        try
        {
            Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups(false);
        }
        catch (Ogre::Exception e){}
        mPause = false;
        try
        {
            mRoot->renderOneFrame(); // Render first
        }
        catch (Ogre::Exception e) {}
    }

    //-------------------------------------------------------------------------------------
    void OgreManager::setupResources(void)
    {
        // Load resource paths from config file
        Ogre::ConfigFile cf;
        cf.load(mResourcesCfg);

        // Go through all sections & settings in the file
        Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator();

        Ogre::String secName, typeName, archName;
        while( seci.hasMoreElements() )
        {
            secName = seci.peekNextKey();
            Ogre::ConfigFile::SettingsMultiMap *settings = seci.getNext();

            if( secName != "Hlms" )
            {
                Ogre::ConfigFile::SettingsMultiMap::iterator i;
                for (i = settings->begin(); i != settings->end(); ++i)
                {
                    typeName = i->first;
                    archName = i->second;
                    Ogre::ResourceGroupManager::getSingleton().addResourceLocation( archName, typeName, secName );
                }
            }
        }
    }

    //****************************************************************************/
    bool OgreManager::isRenderSystemGL(void)
    {
        if (mCurrentRenderSystem)
            return (mCurrentRenderSystem->getName() == OGRE_RENDERSYSTEM_OPENGL3PLUS);

        return false;
    }

    //****************************************************************************/
    GL_CONTEXT OgreManager::getGlContext(void) const
    {
        return mGlContext;
    }

    //****************************************************************************/
    void OgreManager::setGlContext(GL_CONTEXT glContext)
    {
        mGlContext = glContext;
    }

    //****************************************************************************/
    void OgreManager::registerHlms(void)
    {
        Ogre::ConfigFile cf;
        cf.load(mResourcesCfg);

        Ogre::String dataFolder = cf.getSetting( "DoNotUseAsResource", "Hlms", "" );

        if( dataFolder.empty() )
            dataFolder = "./";
        else if( *(dataFolder.end() - 1) != '/' )
            dataFolder += "/";

        Ogre::RenderSystem* renderSystem = mRoot->getRenderSystem();
        Ogre::String shaderSyntax = "GLSL";
        if( renderSystem->getName() == OGRE_RENDERSYSTEM_DIRECTX11 )
            shaderSyntax = "HLSL";
        else if( renderSystem->getName() == OGRE_RENDERSYSTEM_METAL )
            shaderSyntax = "Metal";

        Ogre::Archive* archiveLibrary = Ogre::ArchiveManager::getSingletonPtr()->load(
                        dataFolder + "Hlms/Common/" + shaderSyntax,
                        "FileSystem", true );
        Ogre::Archive* archiveLibraryAny = Ogre::ArchiveManager::getSingletonPtr()->load(
                        dataFolder + "Hlms/Common/Any",
                        "FileSystem", true );
        Ogre::Archive* archivePbsLibraryAny = Ogre::ArchiveManager::getSingletonPtr()->load(
                        dataFolder + "Hlms/Pbs/Any",
                        "FileSystem", true );
        Ogre::Archive* archiveUnlitLibraryAny = Ogre::ArchiveManager::getSingletonPtr()->load(
                        dataFolder + "Hlms/Unlit/Any",
                        "FileSystem", true );

        Ogre::ArchiveVec library;
        library.push_back( archiveLibrary );
        library.push_back( archiveLibraryAny );

        Ogre::Archive* archiveUnlit = Ogre::ArchiveManager::getSingletonPtr()->load(
                        dataFolder + "Hlms/Unlit/" + shaderSyntax,
                        "FileSystem", true );

        library.push_back( archiveUnlitLibraryAny );
        Ogre::HlmsUnlit* hlmsUnlit = OGRE_NEW Ogre::HlmsUnlit( archiveUnlit, &library );
        mRoot->getHlmsManager()->registerHlms( hlmsUnlit );
        library.pop_back();

        Ogre::Archive* archivePbs = Ogre::ArchiveManager::getSingletonPtr()->load(
                        dataFolder + "Hlms/Pbs/" + shaderSyntax,
                        "FileSystem", true );

        library.push_back( archivePbsLibraryAny );
        Ogre::HlmsPbs* hlmsPbs = OGRE_NEW Ogre::HlmsPbs( archivePbs, &library );
        mRoot->getHlmsManager()->registerHlms( hlmsPbs );
        library.pop_back();

        if( renderSystem->getName() == "Direct3D11 Rendering Subsystem" )
        {
            //Set lower limits 512kb instead of the default 4MB per Hlms in D3D 11.0
            //and below to avoid saturating AMD's discard limit (8MB) or
            //saturate the PCIE bus in some low end machines.
            bool supportsNoOverwriteOnTextureBuffers;
            renderSystem->getCustomAttribute( "MapNoOverwriteOnDynamicBufferSRV",
                                              &supportsNoOverwriteOnTextureBuffers );

            if( !supportsNoOverwriteOnTextureBuffers )
            {
                hlmsPbs->setTextureBufferDefaultSize( 512 * 1024 );
                hlmsUnlit->setTextureBufferDefaultSize( 512 * 1024 );
            }
        }
    }
Exemplo n.º 20
0
    //-----------------------------------------------------------------------
    void TerrainTypeInfos::parseTerrainTypeConfigFile(const Ogre::String& filename)
    {
        mTextureNameTerrainTypeMap.clear();
        mTerrainTypeEffectMap.clear();

        Ogre::ConfigFile cf;
        cf.load(filename);

        // Go through all sections & settings in the file
        Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator();

       Ogre::String secName, texNames, effectNames;
        while (seci.hasMoreElements())
        {
            secName = seci.peekNextKey();

            seci.getNext();

            if (secName.empty())
                continue;

            TerrainTypeMap::const_iterator terrainTypeIterator =
                mTerrainTypeMap.find(secName);

            if (terrainTypeIterator == mTerrainTypeMap.end())
            {
                Ogre::LogManager::getSingleton().logMessage("can't find the terrain type! TerrainTypeInfos::parseTerrainTypeConfigFile");
                continue;
            }
            
            TerrainType terrainType = terrainTypeIterator->second;

            texNames = cf.getSetting("texture", secName);
            effectNames = cf.getSetting("effect", secName);

            //if (texNames.empty())
            //{
            //    Ogre::LogManager::getSingleton().logMessage("texture names is empty! TerrainTypeInfos::parseTerrainTypeConfigFile");
            ////    continue;
            //}
            //else
            // 如果有纹理名称,就解析(像liquid这种是不需要定义纹理名称的)
            if (false == texNames.empty())
            {
                Ogre::StringVector texNameArray = Ogre::StringUtil::split(texNames);

                for (size_t texNameIndex = 0; texNameIndex < texNameArray.size(); ++texNameIndex)
                {
                    mTextureNameTerrainTypeMap.insert( 
                        TextureNameTerrainTypeMap::value_type(texNameArray[texNameIndex], terrainType) );                
                }
            }
            
            // 解析特效描述
            if (effectNames.empty())
            {
                Ogre::LogManager::getSingleton().logMessage("effect names is empty! TerrainTypeInfos::parseTerrainTypeConfigFile");
                continue;
            }

            EffectTemplateList effectTemplateList;

            Ogre::StringVector effectNameArray = Ogre::StringUtil::split(effectNames);

            for (size_t effectNameIndex = 0; effectNameIndex < effectNameArray.size(); ++effectNameIndex)
            {
                Ogre::String str = effectNameArray[effectNameIndex];
                Ogre::StringVector effectDefine = 
                    Ogre::StringUtil::split(str,":");

                if (effectDefine.size() != 2)
                {
                    Ogre::LogManager::getSingleton().logMessage("the effect define line is wrong! TerrainTypeInfos::parseTerrainTypeConfigFile");
                    continue;
                }

                EffectTemplate effectTemplate;
                effectTemplate.mEffectName = effectDefine[0];
                effectTemplate.mTemplateName = effectDefine[1];

                effectTemplateList.push_back(effectTemplate);
            }

            // 插入这种地形所对应的特效名称
            mTerrainTypeEffectMap.insert( TerrainTypeEffectMap::value_type(terrainType, effectTemplateList) );
        }
    }
Exemplo n.º 21
0
int _tmain(int argc, _TCHAR* argv[])
{
	// ------------------------- Check for command line argument -------------------------------------------

	if (! argv[1])
	{
		printf("\n");
		printf("Missing argument.\nExample: \"Converter.exe job1.cfg\"");		
		return 0;	
	}

	// ------------------------- Basic Ogre Engine initialization -------------------------------------------

	Ogre::Root* root = new Ogre::Root;	
	Ogre::RenderSystem* rendersys = root->getRenderSystemByName("Direct3D9 Rendering Subsystem");
	
	rendersys->setConfigOption("Full Screen", "No");
	rendersys->setConfigOption("Video Mode", "800 x 600 @ 32-bit colour");
	
	root->setRenderSystem(rendersys);		
	
	Ogre::ResourceGroupManager::getSingleton().addResourceLocation("resource", "FileSystem", "General");
	Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();

	root->initialise(false);

	Ogre::RenderWindow* window = root->createRenderWindow("RAW2OGT", 800, 600, false);		
	Ogre::SceneManager* scenemgr = root->createSceneManager(Ogre::SceneType::ST_GENERIC);
	Ogre::Camera* camera = scenemgr->createCamera("camera");
	Ogre::Viewport* viewport = window->addViewport(camera);
	/*Ogre::Vector3 lightdir(0, -0.3, 0.75);
	lightdir.normalise();

	Ogre::Light* l = scenemgr->createLight("tstLight");
	l->setType(Ogre::Light::LT_DIRECTIONAL);
	l->setDirection(lightdir);
	l->setDiffuseColour(Ogre::ColourValue(1.0, 1.0, 1.0));
	l->setSpecularColour(Ogre::ColourValue(0.4, 0.4, 0.4));*/

	scenemgr->setAmbientLight(Ogre::ColourValue(0.7, 0.7, 0.7));
	
	// --------------------------------- Start convert ----------------------------------------------------

	// Load job config
	Ogre::ConfigFile* terrainconfig = OGRE_NEW Ogre::ConfigFile();
	terrainconfig->loadDirect(argv[1]);
		
	// Load info from [general] block
	Ogre::String heightmapfile = terrainconfig->getSetting("heightmap", "general");
	Ogre::Real heightmapscale = Ogre::StringConverter::parseReal(terrainconfig->getSetting("heightmapscale", "general"));
	Ogre::Real heightmapoffset = Ogre::StringConverter::parseReal(terrainconfig->getSetting("heightmapoffset", "general"));
	Ogre::uint16 terrainsize = Ogre::StringConverter::parseUnsignedInt(terrainconfig->getSetting("terrainsize", "general"));
	Ogre::Real worldsize = Ogre::StringConverter::parseReal(terrainconfig->getSetting("worldsize", "general"));
	Ogre::uint16 layercount = Ogre::StringConverter::parseUnsignedInt(terrainconfig->getSetting("layercount", "general"));

	// initialise stream to heightmapfile
	Ogre::DataStreamPtr stream = Ogre::ResourceGroupManager::getSingleton().openResource(heightmapfile, "General");
	size_t size = stream.get()->size();
		
	// verify size
	if(size != terrainsize * terrainsize * 4)
		OGRE_EXCEPT( Ogre::Exception::ERR_INTERNAL_ERROR, "Size of stream does not match terrainsize!", "TerrainPage" );
					
	// load to buffer
	float* buffer = OGRE_ALLOC_T(float, size, Ogre::MEMCATEGORY_GENERAL);
	stream->read(buffer, size);

	// apply scale and offset 
	for(int i=0;i<terrainsize*terrainsize;i++)
	{
		buffer[i]  = (buffer[i] + heightmapoffset) * heightmapscale;
	}

	// Terrain initialization
	Ogre::TerrainGlobalOptions* terrainglobals = OGRE_NEW Ogre::TerrainGlobalOptions();
	terrainglobals->setMaxPixelError(1);
	//terrainglobals->setCompositeMapDistance(30000);
	//terrainglobals->setLightMapDirection(lightdir);
    //terrainglobals->setCompositeMapAmbient(scenemgr->getAmbientLight());
    //terrainglobals->setCompositeMapDiffuse(l->getDiffuseColour());
	
	Ogre::TerrainMaterialGeneratorA::SM2Profile* pMatProfile = 
      static_cast<Ogre::TerrainMaterialGeneratorA::SM2Profile*>(terrainglobals->getDefaultMaterialGenerator()->getActiveProfile());
	
	pMatProfile->setLightmapEnabled(false);
	pMatProfile->setCompositeMapEnabled(false);
	
	Ogre::TerrainGroup* terraingroup = OGRE_NEW Ogre::TerrainGroup(scenemgr, Ogre::Terrain::ALIGN_X_Z, terrainsize, worldsize);
    terraingroup->setFilenameConvention(Ogre::String("terrain"), Ogre::String("ogt"));
    terraingroup->setOrigin(Ogre::Vector3::ZERO);
		
	Ogre::Terrain* terrain = OGRE_NEW Ogre::Terrain(scenemgr);

	// terrainsettings							
	Ogre::Terrain::ImportData& imp = terraingroup->getDefaultImportSettings();	
	imp.terrainSize = terrainsize;
	imp.worldSize = worldsize;
	imp.minBatchSize = 33;
	imp.maxBatchSize = 65;

	// use float RAW heightmap as input
	imp.inputFloat = buffer;
	
	// process texture layers
	imp.layerList.resize(layercount);
	Ogre::StringVector blendmaps(layercount);
	for(int i=0;i<layercount;i++)
	{
		// load layer info
		Ogre::String sectionStr = Ogre::StringConverter::toString(i);
		Ogre::Real layerworldsize = Ogre::StringConverter::parseReal(terrainconfig->getSetting("worldsize", sectionStr));
		
		if (i==0)
		{			
			// no blendmap at layer 0 (baselayer)
			Ogre::String specular = terrainconfig->getSetting("specular", sectionStr);
			Ogre::String normal = terrainconfig->getSetting("normal", sectionStr);

			// add layer		
			imp.layerList[i].textureNames.push_back(specular);
			imp.layerList[i].textureNames.push_back(normal);
			imp.layerList[i].worldSize = layerworldsize;			
		}
		else
		{
			Ogre::String specular = terrainconfig->getSetting("specular", sectionStr);
			Ogre::String normal = terrainconfig->getSetting("normal", sectionStr);
			Ogre::String blend = terrainconfig->getSetting("blend", sectionStr);
		
			// add layer		
			imp.layerList[i].textureNames.push_back(specular);
			imp.layerList[i].textureNames.push_back(normal);	
			imp.layerList[i].worldSize = layerworldsize;

			blendmaps[i] = blend; 
		}
	}

	// load the terrain
	terrain->prepare(imp);
	terrain->load();	
	
	// load those blendmaps into the layers
	for(int j = 1;j < terrain->getLayerCount();j++)
	{
		Ogre::TerrainLayerBlendMap *blendmap = terrain->getLayerBlendMap(j);
		Ogre::Image img;
		img.load(blendmaps[j],"General");
		int blendmapsize = terrain->getLayerBlendMapSize();
		if(img.getWidth() != blendmapsize)
			img.resize(blendmapsize, blendmapsize);

		float *ptr = blendmap->getBlendPointer();
		Ogre::uint8 *data = static_cast<Ogre::uint8*>(img.getPixelBox().data);

		for(int bp = 0;bp < blendmapsize * blendmapsize;bp++)
			ptr[bp] = static_cast<float>(data[bp]) / 255.0f;

		blendmap->dirty();
		blendmap->update();
	}

	// create filename for writing
	int pos = heightmapfile.find_last_of('.');
	if (pos < 0)	
		heightmapfile = heightmapfile + ".ogt";
	else	
		heightmapfile = heightmapfile.substr(0, pos) + ".ogt";
			
	// save as Ogre .OGT
	terrain->save(heightmapfile);	
	Ogre::LogManager::getSingletonPtr()->logMessage(Ogre::LogMessageLevel::LML_NORMAL, heightmapfile + " successfully written.");
	
	// debug viewing (exit with CTRL+C)
	camera->setPosition(-terrainsize, 7000, -terrainsize);
	camera->lookAt(terrainsize/2,0,terrainsize/2);	
	root->startRendering();

	return 0;
}
Exemplo n.º 22
0
void TestContext::setup()
{
    // standard setup
    mWindow = createWindow();
    mWindow->setDeactivateOnFocusChange(false);
    setupInput(false);// grab input, since moving the window seemed to change the results (in Linux anyways)
    locateResources();
    loadResources();
    Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5);
    mRoot->addFrameListener(this);

#if OGRE_PLATFORM != OGRE_PLATFORM_ANDROID
    Ogre::WindowEventUtilities::addWindowEventListener(mWindow, this);
#endif

    // get the path and list of test plugins from the config file
    Ogre::ConfigFile testConfig;
    testConfig.load(mFSLayer->getConfigFilePath("tests.cfg"));
    mPluginDirectory = testConfig.getSetting("TestFolder");

    Ogre::ConfigFile::SectionIterator sections = testConfig.getSectionIterator();

    // parse for the test sets and plugins that they're made up of
    for (; sections.hasMoreElements(); sections.moveNext())
    {
        Ogre::String setName = sections.peekNextKey();
        if (setName != "")
        {
            mTestSets[setName] = Ogre::StringVector();
            Ogre::ConfigFile::SettingsMultiMap::iterator it = sections.peekNextValue()->begin();
            for (; it != sections.peekNextValue()->end(); ++it)
                mTestSets[setName].push_back(it->second);
        }
    }

    // timestamp for the filename
    char temp[25];
    time_t raw = time(0);
    strftime(temp, 19, "%Y_%m_%d_%H%M_%S", gmtime(&raw));
    Ogre::String filestamp = Ogre::String(temp);
    // name for this batch (used for naming the directory, and uniquely identifying this batch)
    Ogre::String batchName = mTestSetName + "_" + filestamp;
    
    // a nicer formatted version for display
    strftime(temp, 20, "%Y-%m-%d %H:%M:%S", gmtime(&raw));
    Ogre::String timestamp = Ogre::String(temp);
 
    if (mReferenceSet)
        batchName = "Reference";
    else if (mBatchName != "AUTO")
        batchName = mBatchName;

    // set up output directories
    setupDirectories(batchName);

    // an object storing info about this set
    mBatch = new TestBatch(batchName, mTestSetName, timestamp, 
        mWindow->getWidth(), mWindow->getHeight(), mOutputDir + batchName + "/");
    mBatch->comment = mComment;

    OgreBites::Sample* firstTest = loadTests(mTestSetName);
    runSample(firstTest);
}
Exemplo n.º 23
0
Water::Water(const Ogre::ConfigFile &mTerrainConfig)
{
	Vector3 mapsize = gEnv->terrainManager->getMaxTerrainSize();
	mRenderCamera = gEnv->mainCamera;
	vRtt1 = vRtt2 = 0;
	mScale = 1.0f;
	if (mapsize.x < 1500 && mapsize.z < 1500)
		mScale = 1.5f;
	//reading wavefield
	visible=true;
	free_wavetrain=0;
	maxampl=0;

	haswaves = BSETTING("Waves", false);

	// disable waves in multiplayer
	if(gEnv->network)
		haswaves = false;

	// parse height
	float wheight = PARSEREAL(mTerrainConfig.getSetting("WaterLine", "General"));
	float wbheight = PARSEREAL(mTerrainConfig.getSetting("WaterBottomLine", "General"));

	// and the type
	String waterSettingsString = SSETTING("Water effects", "Reflection + refraction (speed optimized)");
	if (waterSettingsString == "Basic (fastest)")
		mType = WATER_BASIC;
	if (waterSettingsString == "Reflection")
		mType = WATER_REFLECT;
	else if (waterSettingsString == "Reflection + refraction (speed optimized)")
		mType = WATER_FULL_SPEED;
	else if (waterSettingsString == "Reflection + refraction (quality optimized)")
		mType = WATER_FULL_QUALITY;


	if (haswaves)
	{
		char line[1024] = {};
		FILE *fd = fopen((SSETTING("Config Root", "")+"wavefield.cfg").c_str(), "r");
		if (fd)
		{
			while (!feof(fd))
			{
				int res = fscanf(fd," %[^\n\r]",line);
				if (line[0] == ';') continue;
				float wl,amp,mx,dir;
				res = sscanf(line,"%f, %f, %f, %f",&wl,&amp,&mx,&dir);
				if (res < 4) continue;
				wavetrains[free_wavetrain].wavelength=wl;
				wavetrains[free_wavetrain].amplitude=amp;
				wavetrains[free_wavetrain].maxheight=mx;
				wavetrains[free_wavetrain].direction=dir/57.0;
				free_wavetrain++;
			}
			fclose(fd);
		}
		for (int i=0; i<free_wavetrain; i++)
		{
			wavetrains[i].wavespeed=1.25*sqrt(wavetrains[i].wavelength);
			maxampl+=wavetrains[i].maxheight;
		}
	}
	//theCam=camera;
	pTestNode=0;
	waterSceneMgr=gEnv->sceneManager;
	framecounter=0;
	height=wheight;
	orgheight=wheight;
	rttTex1=0;
	rttTex2=0;
	MeshPtr mprt;
	mReflectCam=0;
	mRefractCam=0;
	mapsize = gEnv->terrainManager->getMaxTerrainSize();
	//wbuf=0;
	//ColourValue fade=camera->getViewport()->getBackgroundColour();
	ColourValue fade=gEnv->sceneManager->getFogColour();

	if (mType == WATER_FULL_QUALITY || mType == WATER_FULL_SPEED || mType == WATER_REFLECT)
	{
		// Check prerequisites first
		const RenderSystemCapabilities* caps = Root::getSingleton().getRenderSystem()->getCapabilities();
		if (!caps->hasCapability(RSC_VERTEX_PROGRAM) || !(caps->hasCapability(RSC_FRAGMENT_PROGRAM)))
		{
			OGRE_EXCEPT(1, "Your card does not support vertex and fragment programs, so cannot "
				"run Water effects. Sorry!",
				"Water effects");
		}
		else
		{
			if (!GpuProgramManager::getSingleton().isSyntaxSupported("arbfp1") &&
				!GpuProgramManager::getSingleton().isSyntaxSupported("ps_2_0") &&
				!GpuProgramManager::getSingleton().isSyntaxSupported("ps_1_4")
				)
			{
				OGRE_EXCEPT(1, "Your card does not support advanced fragment programs, "
					"so cannot run Water effects. Sorry!",
					"Water effects");
			}
		}
		// Ok
		// Define a floor plane mesh
		reflectionPlane.normal = Vector3::UNIT_Y;
		reflectionPlane.d = -wheight+0.15;
		refractionPlane.normal = -Vector3::UNIT_Y;
		refractionPlane.d = wheight+0.15;
		waterPlane.normal = Vector3::UNIT_Y;
		waterPlane.d = -wheight;

		if (mType == WATER_FULL_QUALITY || mType == WATER_FULL_SPEED)
		{
			TexturePtr rttTex1Ptr = TextureManager::getSingleton().createManual("Refraction", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, TEX_TYPE_2D, 512, 512, 0, PF_R8G8B8, TU_RENDERTARGET, new ResourceBuffer());
			rttTex1 = rttTex1Ptr->getBuffer()->getRenderTarget();
			{
				mRefractCam = gEnv->sceneManager->createCamera("RefractCam");
				mRefractCam->setNearClipDistance(mRenderCamera->getNearClipDistance());
				mRefractCam->setFarClipDistance(mRenderCamera->getFarClipDistance());
				mRefractCam->setAspectRatio(
					(Real)gEnv->renderWindow->getViewport(0)->getActualWidth() /
					(Real)gEnv->renderWindow->getViewport(0)->getActualHeight());

				vRtt1 = rttTex1->addViewport( mRefractCam );
				vRtt1->setClearEveryFrame( true );
				vRtt1->setBackgroundColour( fade );
				//            v->setBackgroundColour( ColourValue::Black );


				MaterialPtr mat = MaterialManager::getSingleton().getByName("Examples/FresnelReflectionRefraction");
				mat->getTechnique(0)->getPass(0)->getTextureUnitState(2)->setTextureName("Refraction");

				mat = MaterialManager::getSingleton().getByName("Examples/FresnelReflectionRefractioninverted");
				mat->getTechnique(0)->getPass(0)->getTextureUnitState(2)->setTextureName("Refraction");

				vRtt1->setOverlaysEnabled(false);

				rttTex1->addListener(&mRefractionListener);

				//optimisation
				rttTex1->setAutoUpdated(false);

				// Also clip
				mRefractCam->enableCustomNearClipPlane(refractionPlane);
			}
		}

		TexturePtr rttTex2Ptr = TextureManager::getSingleton().createManual("Reflection", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, TEX_TYPE_2D, 512, 512, 0, PF_R8G8B8, TU_RENDERTARGET, new ResourceBuffer());
		rttTex2 = rttTex2Ptr->getBuffer()->getRenderTarget();
		{
			mReflectCam = gEnv->sceneManager->createCamera("ReflectCam");
			mReflectCam->setNearClipDistance(mRenderCamera->getNearClipDistance());
			mReflectCam->setFarClipDistance(mRenderCamera->getFarClipDistance());
			mReflectCam->setAspectRatio(
				(Real)gEnv->renderWindow->getViewport(0)->getActualWidth() /
				(Real)gEnv->renderWindow->getViewport(0)->getActualHeight());

			vRtt2 = rttTex2->addViewport( mReflectCam );
			vRtt2->setClearEveryFrame( true );
			vRtt2->setBackgroundColour( fade );
			//            v->setBackgroundColour( ColourValue::Black );


			MaterialPtr mat ;
			if (mType==WATER_FULL_QUALITY || mType==WATER_FULL_SPEED)
			{
				mat = MaterialManager::getSingleton().getByName("Examples/FresnelReflectionRefraction");
				mat->getTechnique(0)->getPass(0)->getTextureUnitState(1)->setTextureName("Reflection");

				mat = MaterialManager::getSingleton().getByName("Examples/FresnelReflectionRefractioninverted");
				mat->getTechnique(0)->getPass(0)->getTextureUnitState(1)->setTextureName("Reflection");
			} else
			{
				mat = MaterialManager::getSingleton().getByName("Examples/FresnelReflection");
				mat->getTechnique(0)->getPass(0)->getTextureUnitState(1)->setTextureName("Reflection");
			}


			vRtt2->setOverlaysEnabled(false);

			rttTex2->addListener(&mReflectionListener);

			//optimisation
			rttTex2->setAutoUpdated(false);

			// set up linked reflection
			mReflectCam->enableReflection(waterPlane);
			// Also clip
			mReflectCam->enableCustomNearClipPlane(reflectionPlane);
		}

		mprt=MeshManager::getSingleton().createPlane("ReflectPlane",
			ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
			waterPlane,
			mapsize.x * mScale,mapsize.z * mScale,WAVEREZ,WAVEREZ,true,1,50,50,Vector3::UNIT_Z, HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY_DISCARDABLE);
		pPlaneEnt = gEnv->sceneManager->createEntity( "plane", "ReflectPlane" );
		if (mType==WATER_FULL_QUALITY || mType==WATER_FULL_SPEED)
			pPlaneEnt->setMaterialName("Examples/FresnelReflectionRefraction");
		else
			pPlaneEnt->setMaterialName("Examples/FresnelReflection");
		//        gEnv->ogreSceneManager->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt);
		//position
		pTestNode = gEnv->sceneManager->getRootSceneNode()->createChildSceneNode("WaterPlane");
		pTestNode->attachObject(pPlaneEnt);
		pTestNode->setPosition( Vector3((mapsize.x * mScale)/2,0,(mapsize.z * mScale)/2) );
	}
	else
	{
		//basic Water
		waterPlane.normal = Vector3::UNIT_Y;
		waterPlane.d = -wheight;
		mprt=MeshManager::getSingleton().createPlane("WaterPlane",
			ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
			waterPlane,
			mapsize.x * mScale,mapsize.z * mScale,WAVEREZ,WAVEREZ,true,1,50,50,Vector3::UNIT_Z, HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY_DISCARDABLE);
		pPlaneEnt = gEnv->sceneManager->createEntity( "plane", "WaterPlane" );
		pPlaneEnt->setMaterialName("tracks/basicwater");
		//position
		pTestNode = gEnv->sceneManager->getRootSceneNode()->createChildSceneNode("WaterPlane");
		pTestNode->attachObject(pPlaneEnt);
		pTestNode->setPosition( Vector3((mapsize.x * mScale)/2,0,(mapsize.z * mScale)/2) );
	}
	//bottom
	bottomPlane.normal = Vector3::UNIT_Y;
	bottomPlane.d = -wbheight; //30m below waterline
	MeshManager::getSingleton().createPlane("BottomPlane",
		ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
		bottomPlane,
		mapsize.x * mScale,mapsize.z * mScale,1,1,true,1,1,1,Vector3::UNIT_Z);
	Entity *pE = gEnv->sceneManager->createEntity( "bplane", "BottomPlane" );
	pE->setMaterialName("tracks/seabottom");
	//position
	pBottomNode = gEnv->sceneManager->getRootSceneNode()->createChildSceneNode("BottomWaterPlane");
	pBottomNode->attachObject(pE);
	pBottomNode->setPosition( Vector3((mapsize.x * mScale)/2,0,(mapsize.z * mScale)/2) );
	//setup for waves
	wbuf=mprt->sharedVertexData->vertexBufferBinding->getBuffer(0);
	if (wbuf->getSizeInBytes()==(WAVEREZ+1)*(WAVEREZ+1)*32)
	{
		wbuffer=(float*)malloc(wbuf->getSizeInBytes());
		wbuf->readData(0, wbuf->getSizeInBytes(), wbuffer);
	} else wbuffer=0;
}