Ejemplo n.º 1
0
//---------------------------------------------------------------------
int MilkshapePlugin::Execute (msModel* pModel)
{
    // Do nothing if no model selected
    if (!pModel)
        return -1;

	Ogre::LogManager logMgr;
	logMgr.createLog("msOgreExporter.log", true);
	logMgr.logMessage("OGRE Milkshape Exporter Log");
	logMgr.logMessage("---------------------------");
	Ogre::ResourceGroupManager resGrpMgr;

	//
    // check, if we have something to export
    //
    if (msModel_GetMeshCount (pModel) == 0)
    {
        ::MessageBox (NULL, "The model is empty!  Nothing exported!", "OGRE Export", MB_OK | MB_ICONWARNING);
        return 0;
    }

    if (!showOptions()) return 0;

    if (exportMesh)
    {
        doExportMesh(pModel);
    }

    return 0;

}
Ejemplo n.º 2
0
void SoundFX::loadImpl() {
  Ogre::LogManager* pLogManager = Ogre::LogManager::getSingletonPtr();

  // Ruta al archivo.
  Ogre::FileInfoListPtr info;
  info = Ogre::ResourceGroupManager::getSingleton().findResourceFileInfo(mGroup, mName);
  for (Ogre::FileInfoList::iterator i = info->begin(); i != info->end(); ++i) {
    _path = i->archive->getName() + "/" + i->filename;
  }
  
  // Archivo no encontrado...
  if (_path == "") {
    pLogManager->logMessage("SoundFX::loadImpl() Imposible encontrar el recurso.");
    throw (Ogre::Exception(Ogre::Exception::ERR_FILE_NOT_FOUND,
			   "Imposible encontrar el recurso", "SoundFX::loadImpl()"));
  }
  
  // Cargar el efecto de sonido.
  if ((_pSound = Mix_LoadWAV(_path.c_str())) == NULL) {
    pLogManager->logMessage("SoundFX::loadImpl() Imposible cargar el efecto.");
    throw (Ogre::Exception(Ogre::Exception::ERR_INTERNAL_ERROR,
			   "Imposible cargar el efecto", "SoundFX::loadImpl()"));
  }
  
  // Cálculo del tamaño del recurso de sonido.
  std::ifstream stream;
  char byteBuffer;
  stream.open(_path.c_str(), std::ios_base::binary);
  
  while (stream >> byteBuffer) {
    ++_size;
  }
  
  stream.close();
}
Ejemplo n.º 3
0
//-------------------------------------------------------------------------------------
bool BaseApplication::setup(void)
{
    Ogre::LogManager * lm = new Ogre::LogManager();
    lm->createLog("Ogre.log", true, false, false);
    mRoot = new Ogre::Root(mPluginsCfg);

    setupResources();

    bool carryOn = configure();
    if (!carryOn) return false;

    chooseSceneManager();
    createCamera();
    createViewports();

    // Set default mipmap level (NB some APIs ignore this)
    Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5);

    // Create any resource listeners (for loading screens)
    createResourceListener();
    // Load resources
    loadResources();

    // Create the scene
    createScene();

    createFrameListener();

    return true;
};
Ejemplo n.º 4
0
void wxOgre::cameraTrackNode(Ogre::SceneNode* target)
{
	static const wxString camCalcPosCaption(wxT("CalcCamPos:X:%08.4f, Y:%08.4f, Z:%08.4f"));
	static const wxString camRealPosCaption(wxT("CalcCamPos:X:%08.4f, Y:%08.4f, Z:%08.4f"));

	// TODO: Position camera somwehere sensible relative to object
	if (target)
	{
		Ogre::LogManager* logMgr = Ogre::LogManager::getSingletonPtr();
		Ogre::Log* log(logMgr->getDefaultLog());
		mTarget = target;
		Ogre::Vector3 size( target->getAttachedObject(0)->getBoundingBox().getSize() );
		Ogre::Vector3 camPos(target->getPosition() + size * 1.2f); 
		setZoomScale(size.length() / 30.0f);
		mCameraNode->setPosition(camPos);
		mCamera->lookAt(target->getPosition());
		mDebugPanelOverlay->show();
		wxString msg(wxString::Format(camCalcPosCaption, camPos.x, camPos.y, camPos.x));
		log->logMessage(Ogre::String(msg.mb_str(wxConvUTF8)));
		Ogre::Vector3 camRealPos(mCamera->getRealPosition());
		msg = wxString(wxString::Format(camCalcPosCaption, camRealPos.x, camRealPos.y, camRealPos.x));
		log->logMessage(Ogre::String(msg.mb_str(wxConvUTF8)));
	} else {
		mTarget = NULL;
	}

}
Ejemplo n.º 5
0
// Fachada de MixFadeOutMusic()
void Track::fadeOut (int ms) {
  Ogre::LogManager* pLogManager = Ogre::LogManager::getSingletonPtr();

  if (Mix_FadeOutMusic(ms) == -1) {
    pLogManager->logMessage("Track::fadeIn() Error al aplicar efecto de sonido.");
    throw (Ogre::Exception(Ogre::Exception::ERR_INTERNAL_ERROR,
			   "Imposible aplicar suavizado de sonido", "Track::fadeIn()"));
    }
}
Ejemplo n.º 6
0
	/********************************************************************************************************
	*                           Method to write data to OGRE format                                         *
	********************************************************************************************************/
	MStatus OgreExporter::writeOgreData()
	{
		// Create singletons
		Ogre::LogManager logMgr;
		Ogre::ResourceGroupManager rgm;
		Ogre::MeshManager meshMgr;
		Ogre::SkeletonManager skelMgr;
		Ogre::MaterialManager matMgr;
		Ogre::DefaultHardwareBufferManager hardwareBufMgr;

		// Create a log
		logMgr.createLog("ogreMayaExporter.log", true);

		// Write mesh binary
		if (m_params.exportMesh)
		{
			std::cout << "Writing mesh binary...\n";
			std::cout.flush();
			stat = m_pMesh->writeOgreBinary(m_params);
			if (stat != MS::kSuccess)
			{
				std::cout << "Error writing mesh binary file\n";
				std::cout.flush();
			}
		}

		// Write skeleton binary
		if (m_params.exportSkeleton)
		{
			if (m_pMesh->getSkeleton())
			{
				std::cout << "Writing skeleton binary...\n";
				std::cout.flush();
				stat = m_pMesh->getSkeleton()->writeOgreBinary(m_params);
				if (stat != MS::kSuccess)
				{
					std::cout << "Error writing mesh binary file\n";
					std::cout.flush();
				}
			}
		}
		
		// Write materials data
		if (m_params.exportMaterial)
		{
			std::cout << "Writing materials data...\n";
			std::cout.flush();
			stat  = m_pMaterialSet->writeOgreScript(m_params);
			if (stat != MS::kSuccess)
			{
				std::cout << "Error writing materials file\n";
				std::cout.flush();
			}
		}

		return MS::kSuccess;
	}
Ejemplo n.º 7
0
ClientLog::ClientLog () : ::Log ("screamers.log"), Ogre::LogListener ()
{
	Ogre::LogManager *manager;
	if (Ogre::LogManager::getSingletonPtr () == NULL)
		manager = new Ogre::LogManager ();
	else
		manager = Ogre::LogManager::getSingletonPtr ();
	manager->addListener (this);
	manager->setLogDetail (Ogre::LL_BOREME);
}
Ejemplo n.º 8
0
/** Setup a minimal ogre renderer
  *
  * \param custom_log Should we create a custom log
  * \param base_dir   The path to the config and data files 
  *                   (plugins.cfg and ogre.cfg
  *
  * \warning Incorrect base_dir could lead to a 'memory access violation' when
  *          launched.
  *
  * \note The \c custom_log parameter is used to avoid an Ogre3D assertion
  *       that occurs when creating our custom log. 
  *
  */
void 
OgreMinimalSetup::setupOgre(const Ogre::String& base_dir, bool custom_log)
{
  Ogre::Root *root; // The Ogre root singleton

  mListener = new SilentLogListener();

  string dir= base_dir + "config/";
  if (!dirExists(dir)){
    throw "config directory '" + dir + "' does not exist.";
  }

  try{
    if (custom_log == true)
      {
	Ogre::LogManager* logger = new Ogre::LogManager();
	assert(logger && "Failed to create an Ogre Logger");
	logger->createLog("log.log", true, false, true);
	Ogre::LogManager::getSingleton().getDefaultLog()
	  ->addListener(mListener);
      }

  }
  catch(Ogre::Exception e){
    cout << "setupOgre failed to initialize LogManager: "<< e.what() << endl;
    exit(1);
  }

  try
    {
      root = new Ogre::Root(dir + "plugins-unittests.cfg", 
			    dir + "ogre.cfg", dir + "ogre.log");
    }
  catch(Ogre::Exception e){
    cout << "setupOgre failed to initialize Ogre::Root : "<< e.what() << endl;
    exit(1);
  }

  assert(root && "Cannot initialize Ogre::Root");
  assert(Ogre::Root::getSingletonPtr() && "Cannot initialize Ogre::Root");

  // Select rendersystem
  Ogre::RenderSystemList list=Ogre::Root::getSingleton().getAvailableRenderers();
  this->debugRenderList( list );
  Ogre::Root::getSingleton().setRenderSystem(list[0]);
  Ogre::Root::getSingleton().initialise(false, "RainbruRPG blah");
  Ogre::Root::getSingleton().addResourceLocation(base_dir + "data/", "FileSystem");
  Ogre::Root::getSingleton().addResourceLocation(base_dir + "data/gui/fonts", "FileSystem");
  mRenderWindow = Ogre::Root::getSingleton().getRenderSystem()
    ->_createRenderWindow(RW_NAME, 20, 20, false);
  Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5);
 
}
Ejemplo n.º 9
0
int SoundFX::play(int loop) {
  int channel;
  Ogre::LogManager* pLogManager = Ogre::LogManager::getSingletonPtr();

  // Si el primer parámetro es un -1, maneja nuevos canales para efectos simultáneos
  if ((channel = Mix_PlayChannel(1, _pSound, loop)) == -1) {
    pLogManager->logMessage("SoundFX::play() Imposible reproducir el efecto de sonido.");
    throw (Ogre::Exception(Ogre::Exception::ERR_INTERNAL_ERROR,
			   "Imposible reproducir el efecto de sonido", "SoundFX::play()"));
  }

  return channel;
}
Ejemplo n.º 10
0
bool OgreApplication::initStart(void)
{

    mPluginsCfg = "../configs/plugins.cfg";
    mResourcesCfg = "../configs/resources.cfg";

    Ogre::LogManager * lm = new Ogre::LogManager();
    lm->createLog("OgreLogfile.log", true, false, false);

    // construct Ogre::Root
    mRoot = new Ogre::Root(mPluginsCfg, "", "");

    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();
        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);
        }
    }

    Ogre::ResourceGroupManager::getSingleton().addResourceLocation("../assets/", "FileSystem");

    Ogre::ResourceGroupManager::getSingleton().addResourceLocation("../assets/particles", "FileSystem");

    // Do not add this to the application
    Ogre::RenderSystem *rs = mRoot->getRenderSystemByName("OpenGL Rendering Subsystem");
    mRoot->setRenderSystem(rs);
    rs->setConfigOption("Full Screen", "No");
    rs->setConfigOption("Video Mode", "800 x 600 @ 32-bit colour");
    rs->setStencilCheckEnabled(true);

    mRoot->initialise(false);

    running = true;
    return true;
}
Ejemplo n.º 11
0
void Track::play(int loop) {
  Ogre::LogManager* pLogManager = Ogre::LogManager::getSingletonPtr();

  // Estaba pausada?
  if(Mix_PausedMusic()) {
    Mix_ResumeMusic();  // Reanudación.
  }

  // Si no, se reproduce desde el principio.
  else { 
    if (Mix_PlayMusic(_pTrack, loop) == -1) {
      pLogManager->logMessage("Track::play() Error al reproducir el recurso de sonido.");
      throw (Ogre::Exception(Ogre::Exception::ERR_FILE_NOT_FOUND,
			     "Imposible reproducir el recurso de sonido", "Track::play()"));
        }
    }
}
Ejemplo n.º 12
0
void Client::StartupOgre() {
	Ogre::LogManager* logMgr = OGRE_NEW Ogre::LogManager;
	logMgr->createLog("DefaultLog", true, false, false);

	mOgreRoot = new Ogre::Root("../data/config/plugins.cfg");

	// setup resources
	// Load resource paths from config file
	Ogre::ConfigFile cf;
	cf.load("../data/config/resources.cfg");

	// 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;
			Ogre::ResourceGroupManager::getSingleton().addResourceLocation(
				archName, typeName, secName);
		}
	}

	// configure
	// Show the configuration dialog and initialise the system
	if(!(mOgreRoot->restoreConfig() || mOgreRoot->showConfigDialog())) {
		exit(0);
	}
	mWindow = mOgreRoot->initialise(true, "Client Window");


	// Set default mipmap level (NB some APIs ignore this)
	Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5);
	// initialise all resource groups
	// Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();

	Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("Basics");
	Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("GUI");

	InitializeWindow();
	// ogre loaded
}
Ejemplo n.º 13
0
    void Entresol::SetupLogging(const String& LogFileName)
    {
        /// @todo Allow the FrameScheduler Log target to be inspected and changed here
        Ogre::LogManager* OgreLogs = Ogre::LogManager::getSingletonPtr();
        if( NULL == OgreLogs )
            { OgreLogs = new Ogre::LogManager(); }

        if(!LogFileName.empty())
        {
            OgreLogs->createLog(String("Graphics")+LogFileName,true,true);
        }
        else
        {
            OgreLogs->createLog("GraphicsMezzanine.log",true,true);
        }
        this->Aggregator = new Threading::LogAggregator();
        Aggregator->SetAggregationTarget(&WorkScheduler);
        this->WorkScheduler.AddWorkUnitMain(Aggregator, "LogAggregator");
    }
Ejemplo n.º 14
0
bool initOgreRoot(){
	try{
		// Create logs that funnel to android logs
		Ogre::LogManager *lm = OGRE_NEW Ogre::LogManager();
		Ogre::Log *l = lm->createLog("AndroidLog", true, true, true);
		g_ll = OGRE_NEW AndroidLogListener();
		l->addListener(g_ll);
		
		// Create a root object
		g_root = OGRE_NEW Ogre::Root("", "", "");
		
		// Register the ES2 plugin
		g_gles2Plugin = OGRE_NEW Ogre::GLES2Plugin();
		Ogre::Root::getSingleton().installPlugin(g_gles2Plugin);
		
		// Register particle plugin
		g_pfxPlugin = OGRE_NEW Ogre::ParticleFXPlugin();
		Ogre::Root::getSingleton().installPlugin(g_pfxPlugin);
		
		// Grab the available render systems
		const Ogre::RenderSystemList &renderSystemList = g_root->getAvailableRenderers();
		if(renderSystemList.empty())
		{
			return false;
		}
		
		// Set the render system and init
		Ogre::RenderSystem *system = renderSystemList.front();
		g_root->setRenderSystem(system);
		g_root->initialise(false);
		
		g_lastTime = g_timer.getMilliseconds();
		
		return true;
	}catch(Ogre::Exception &e){
	}
	return false;
}
Ejemplo n.º 15
0
// Carga del recurso.
void Track::loadImpl() {
  Ogre::LogManager* pLogManager = Ogre::LogManager::getSingletonPtr();

  // Ruta al archivo.
  Ogre::FileInfoListPtr info;
  info = Ogre::ResourceGroupManager::getSingleton().findResourceFileInfo(mGroup, mName);

  for (Ogre::FileInfoList::const_iterator i = info->begin(); i != info->end(); ++i) {
    _path = i->archive->getName() + "/" + i->filename;
  }
 
  // Archivo no encontrado...
  if (_path == "") {
    pLogManager->logMessage("Track::loadImpl() Imposible cargar el recurso de sonido.");
    throw (Ogre::Exception(Ogre::Exception::ERR_FILE_NOT_FOUND,
			   "Archivo no encontrado", "Track::loadImpl()"));
  }
    cout << "\n\nPath: " << _path << "\n\n" << endl;
    // Cargar el recurso de sonido.
    if ((_pTrack = Mix_LoadMUS(_path.c_str())) == NULL) {
      pLogManager->logMessage("Track::loadI() Imposible cargar el recurso de sonido.");
      throw (Ogre::Exception(Ogre::Exception::ERR_FILE_NOT_FOUND,
			     "Archivo no encontrado", "Track::loadI()"));
    }
    
    // Cálculo del tamaño del recurso de sonido.
    std::ifstream stream;
    char byteBuffer;
    stream.open(_path.c_str(), std::ios_base::binary);
 
    while (stream >> byteBuffer) {
      _size++;
    }
    
    stream.close();
}
Ejemplo n.º 16
0
void OgreExporter_c::ExportLevel(const WadLevel_c &level, const WadFile_c &file)
{	
	this->ExportLevelMaterials(level, file);

	Ogre::DefaultHardwareBufferManager hardwareBufferManager;
	Ogre::ManualObject manualMesh(level.GetName());	

	const LineDef_s *lineDefs = level.GetLineDefs();
	const size_t numLineDefs = level.GetNumLineDefs();

	const SideDef_s *sideDefs = level.GetSideDefs();
	const Sector_s *sectors = level.GetSectors();

	const Vertex_s *vertices = level.GetVertices();
	for(size_t i = 0;i < numLineDefs; ++i)
	{
		if(lineDefs[i].iLeftSideDef >= 0)
		{
			const SideDef_s &leftSide = sideDefs[lineDefs[i].iLeftSideDef];
			const Sector_s &leftSideSector = sectors[leftSide.iSector];

			const SideDef_s &rightSide = sideDefs[lineDefs[i].iRightSideDef];
			const Sector_s &rightSideSector = sectors[rightSide.iSector];


			if(leftSide.uMiddleTexture.uName != '-')
			{
				this->ExportWallMesh(manualMesh, leftSideSector.iFloorHeight, leftSideSector.iCeilHeight, leftSide.uMiddleTexture, leftSide.iOffsetX, leftSide.iOffsety, vertices, lineDefs[i], file);				
			}

			if(leftSide.uLowerTexture.uName != '-')
			{
				this->ExportWallMesh(manualMesh, leftSideSector.iFloorHeight, leftSideSector.iFloorHeight, leftSide.uLowerTexture, leftSide.iOffsetX, leftSide.iOffsety, vertices, lineDefs[i], file);				
			}

			if(leftSide.uUpperTexture.uName != '-')
			{
				this->ExportWallMesh(manualMesh, rightSideSector.iCeilHeight, leftSideSector.iCeilHeight, leftSide.uUpperTexture, leftSide.iOffsetX, leftSide.iOffsety, vertices, lineDefs[i], file);				
			}
		}
		
		if(lineDefs[i].iRightSideDef >= 0)
		{			
			const SideDef_s &rightSide = sideDefs[lineDefs[i].iRightSideDef];
			const Sector_s &rightSideSector = sectors[rightSide.iSector];

			if(rightSide.uLowerTexture.uName != '-')
			{
				const SideDef_s &leftSide = sideDefs[lineDefs[i].iLeftSideDef];
				const Sector_s &leftSideSector = sectors[leftSide.iSector];

				this->ExportWallMesh(manualMesh, rightSideSector.iFloorHeight, leftSideSector.iFloorHeight, rightSide.uLowerTexture, rightSide.iOffsetX, rightSide.iOffsety, vertices, lineDefs[i], file);				
			}	

			if(rightSide.uMiddleTexture.uName != '-')
			{
				this->ExportWallMesh(manualMesh, rightSideSector.iFloorHeight, rightSideSector.iCeilHeight, rightSide.uMiddleTexture, rightSide.iOffsetX, rightSide.iOffsety, vertices, lineDefs[i], file);				
			}		

			if(rightSide.uUpperTexture.uName != '-')
			{
				const SideDef_s &leftSide = sideDefs[lineDefs[i].iLeftSideDef];
				const Sector_s &leftSideSector = sectors[leftSide.iSector];

				this->ExportWallMesh(manualMesh, leftSideSector.iCeilHeight, rightSideSector.iCeilHeight, rightSide.uUpperTexture, rightSide.iOffsetX, rightSide.iOffsety, vertices, lineDefs[i], file);				
			}	
		}
	}

	namespace fs = boost::filesystem;

	fs::path path(strLevelDirectory);

	std::string levelName = level.GetName();
	levelName += ".mesh";

	path /= levelName;	

	Ogre::LogManager logManager;
	logManager.createLog("ogre.log", true, true, false);

	Ogre::ResourceGroupManager resourceGroupManager;
	Ogre::MeshManager meshManager;
	Ogre::LodStrategyManager logStrategyManager;
	Ogre::MeshPtr mesh = manualMesh.convertToMesh(level.GetName());

	Ogre::MeshSerializer serializer;
	serializer.exportMesh(mesh.get(), path.string());

	mesh.setNull();

	resourceGroupManager.shutdownAll();	

	this->CreateResourcesCfg();
}
Ejemplo n.º 17
0
void wxOgre::OnMouseMotion(wxMouseEvent& event)
{
	static float speed = 0.0f;
	static bool dragStart = true;
	static const wxString posInfo(wxT("Pos:X:%03d, Y:%03d Change X:%03d Y:%03d"));
	static Ogre::Quaternion startRot(Ogre::Quaternion::IDENTITY);

	Ogre::LogManager* logMgr = Ogre::LogManager::getSingletonPtr();
	Ogre::Log* log(logMgr->getDefaultLog());
	int left, top, width, height;	
	mCamera->getViewport()->getActualDimensions(left, top, width, height);

	wxPoint pos = event.GetPosition();
	wxPoint change = pos - mPrevPos;

	Ogre::Vector2 changeNorm((Ogre::Real) change.x / (Ogre::Real) width,
							 (Ogre::Real) -change.y / (Ogre::Real) height);
	
	if ((!dragStart) && ((!event.Dragging()) || (!event.LeftIsDown()))) {
 			wxString msg(wxT("Drag End"));
			log->logMessage(Ogre::String(msg.mb_str(wxConvUTF8)));
			dragStart = true;
	}

	if(event.Dragging())
	{
		if (event.LeftIsDown())
		{
			if (mTarget) {
				Ogre::Vector3 objectCentre(mTarget == NULL ? Ogre::Vector3::ZERO : mTarget->getPosition());
				if (dragStart) {
					Ogre::Vector3 cam2Object(mCameraNode->getPosition() - objectCentre);
					mDirection =  cam2Object.normalisedCopy();
					mRadius = cam2Object.length();
					mChangePos = Ogre::Vector2::ZERO;
					dragStart = false;					
					wxString msg(wxT("Drag Start"));
					log->logMessage(Ogre::String(msg.mb_str(wxConvUTF8)));
				}  else {
					Ogre::Vector3 across;
					Ogre::Vector3 up;
					Ogre::Vector3 forward;
					mCamera->getRealOrientation().ToAxes(across, up, forward);
					mChangePos += changeNorm;
					Ogre::Quaternion roty(Ogre::Radian(mChangePos.y * Ogre::Math::PI / 12.0f), across);
					Ogre::Quaternion rotx(Ogre::Radian(mChangePos.x * Ogre::Math::PI / 12.0f), up);					
					Ogre::Quaternion rot(roty * rotx);
					rot.normalise();
					mCameraNode->setPosition(objectCentre + ((rot * mDirection) * mRadius));
 					mCamera->lookAt(objectCentre);
				}
			} 
		}
		else if(event.MiddleIsDown())
		{
			int left, top, width, height;
			mCamera->getViewport()->getActualDimensions(left, top, width, height);

			float speed = 1.0f;
			if (event.ShiftDown())
				speed = 0.1f;
			if (event.ControlDown())
				speed = 10.0f;
			float moveX = ((float)-change.x / (float)width) * mZoomScale * speed;
			float moveY = ((float)change.y / (float)height) * mZoomScale * speed;

			Ogre::Vector3 delta(mCamera->getRealOrientation().xAxis() * moveX);
			delta += mCamera->getRealOrientation().yAxis() * moveY;
			mCamera->setPosition(mCamera->getRealPosition() + delta);
		}
	}
	mPrevPos = pos;
}
Ejemplo n.º 18
0
/** Callback event when clicking the export menu option. Adds an instance of the
    options dialog as a property, then uses the InspectObj XSI command to pop it up
    in a modal dialog. If it wasn't cancelled, performs an export.
*/
XSI::CStatus OnOgreMeshExportMenu( XSI::CRef& in_ref )
{	
	Ogre::LogManager logMgr;
	logMgr.createLog("OgreXSIExporter.log", true);
	CString msg(L"OGRE Exporter Version ");
	msg += OGRE_XSI_EXPORTER_VERSION;
	LogOgreAndXSI(msg);

	Application app;
	CStatus st(CStatus::OK);
	Property prop = app.GetActiveSceneRoot().GetProperties().GetItem(exportPropertyDialogName);
	if (prop.IsValid())
	{
		// Check version number
		CString currVersion(prop.GetParameterValue(L"version"));
		if (!currVersion.IsEqualNoCase(OGRE_XSI_EXPORTER_VERSION))
		{
			DeleteObj(exportPropertyDialogName);
			prop.ResetObject();
		}
	}
	if (!prop.IsValid())
	{
		prop = app.GetActiveSceneRoot().AddProperty(exportPropertyDialogName);
		prop.PutParameterValue(L"version", CString(OGRE_XSI_EXPORTER_VERSION));
	}
	
	try
	{
		// Popup Returns true if the command was cancelled otherwise it returns false. 
		CStatus ret = Popup(exportPropertyDialogName,CValue(),L"OGRE Mesh / Skeleton Export",((LONG)siModal),true);
		if (ret == CStatus::OK)
		{
			Ogre::XsiMeshExporter meshExporter;
			Ogre::XsiSkeletonExporter skelExporter;

			// retrieve the parameters
			Parameter param = prop.GetParameters().GetItem(L"objectName");
			CString objectName = param.GetValue();
			param = prop.GetParameters().GetItem( L"targetMeshFileName" );
			Ogre::String meshFileName = XSItoOgre(XSI::CString(param.GetValue()));
			if (meshFileName.empty())
			{
				OGRE_EXCEPT(Ogre::Exception::ERR_INVALIDPARAMS, 
					"You must supply a mesh file name", 
					"OGRE Exporter");
			}
			// fix any omission of '.mesh'
			if (!Ogre::StringUtil::endsWith(meshFileName, ".mesh"))
			{
				meshFileName += ".mesh";
			}
			param = prop.GetParameters().GetItem( L"mergeSubmeshes" );
			bool mergeSubmeshes = param.GetValue();
			param = prop.GetParameters().GetItem( L"exportChildren" );
			bool exportChildren = param.GetValue();
			param = prop.GetParameters().GetItem( L"calculateEdgeLists" );
			bool edgeLists = param.GetValue();
			param = prop.GetParameters().GetItem( L"calculateTangents" );
			bool tangents = param.GetValue();
			param = prop.GetParameters().GetItem( L"tangentSemantic" );
			CString tangentSemStr = param.GetValue();
			Ogre::VertexElementSemantic tangentSemantic = (tangentSemStr == L"t")?
				Ogre::VES_TANGENT : Ogre::VES_TEXTURE_COORDINATES;
			param = prop.GetParameters().GetItem( L"tangentsSplitMirrored" );
			bool tangentsSplitMirrored = param.GetValue();
			param = prop.GetParameters().GetItem( L"tangentsSplitRotated" );
			bool tangentsSplitRotated = param.GetValue();
			param = prop.GetParameters().GetItem( L"tangentsUseParity" );
			bool tangentsUseParity = param.GetValue();
			param = prop.GetParameters().GetItem( L"numLodLevels" );
			long numlods = (LONG)param.GetValue();
			Ogre::XsiMeshExporter::LodData* lodData = 0;
			if (numlods > 0)
			{
				param = prop.GetParameters().GetItem( L"lodDistanceIncrement" );
				float distanceInc = param.GetValue();

				param = prop.GetParameters().GetItem(L"lodQuota");
				CString quota = param.GetValue();

				param = prop.GetParameters().GetItem(L"lodReduction");
				float reduction = param.GetValue();

				lodData = new Ogre::XsiMeshExporter::LodData;
				float currentInc = distanceInc;
				for (int l = 0; l < numlods; ++l)
				{
					lodData->distances.push_back(currentInc);
					currentInc += distanceInc;
				}
				lodData->quota = (quota == L"p") ?
					Ogre::ProgressiveMesh::VRQ_PROPORTIONAL : Ogre::ProgressiveMesh::VRQ_CONSTANT;
				if (lodData->quota == Ogre::ProgressiveMesh::VRQ_PROPORTIONAL)
					lodData->reductionValue = reduction * 0.01;
				else
					lodData->reductionValue = reduction;

			}

			param = prop.GetParameters().GetItem( L"exportSkeleton" );
			bool exportSkeleton = param.GetValue();
			param = prop.GetParameters().GetItem( L"exportVertexAnimation" );
			bool exportVertexAnimation = param.GetValue();
			param = prop.GetParameters().GetItem( L"exportMaterials" );
			bool exportMaterials = param.GetValue();
			param = prop.GetParameters().GetItem( L"copyTextures" );
			bool copyTextures = param.GetValue();

			// create singletons
			Ogre::ResourceGroupManager rgm;
			Ogre::MeshManager meshMgr;
			Ogre::SkeletonManager skelMgr;
			Ogre::MaterialManager matMgr;
			Ogre::DefaultHardwareBufferManager hardwareBufMgr;

			
			// determine number of exportsteps
			size_t numSteps = 3 + OGRE_XSI_NUM_MESH_STEPS;
			if (numlods > 0)
				numSteps++;
			if (edgeLists)
				numSteps++;
			if (tangents)
				numSteps++;
			if (exportSkeleton)
				numSteps += 3;

			Ogre::ProgressManager progressMgr(numSteps);
			
			// Any material prefix? We need that for mesh linking too
			param = prop.GetParameters().GetItem( L"materialPrefix" );
			Ogre::String materialPrefix = XSItoOgre(XSI::CString(param.GetValue()));

			param = prop.GetParameters().GetItem( L"fps" );
			float fps = param.GetValue();
			if (fps == 0.0f)
			{
				OGRE_EXCEPT(Ogre::Exception::ERR_INVALIDPARAMS, 
					"You must supply a valid value for 'FPS'", 
					"OGRE Export");
			}

			Ogre::AnimationList selAnimList;
			if (exportSkeleton || exportVertexAnimation)
			{

				param = prop.GetParameters().GetItem( L"animationList" );
				GridData gd(param.GetValue());
				for (int a = 0; a < gd.GetRowCount(); ++a)
				{
					if (gd.GetCell(ANIMATION_LIST_EXPORT_COL, a) == true)
					{
						Ogre::AnimationEntry ae;
						ae.animationName = XSItoOgre(XSI::CString(gd.GetCell(ANIMATION_LIST_NAME_COL, a)));
						ae.ikSampleInterval = gd.GetCell(ANIMATION_LIST_IKFREQ_COL, a);
						ae.startFrame = (LONG)gd.GetCell(ANIMATION_LIST_START_COL, a);
						ae.endFrame = (LONG)gd.GetCell(ANIMATION_LIST_END_COL, a);
						selAnimList.push_back(ae);
					}
				}
			}

			if (exportSkeleton)
			{
				param = prop.GetParameters().GetItem( L"targetSkeletonFileName" );
				Ogre::String skeletonFileName = XSItoOgre(XSI::CString(param.GetValue()));
				if (skeletonFileName.empty())
				{
					OGRE_EXCEPT(Ogre::Exception::ERR_INVALIDPARAMS, 
						"You must supply a skeleton file name", 
						"OGRE Exporter");
				}

				// fix any omission of '.skeleton'
				if (!Ogre::StringUtil::endsWith(skeletonFileName, ".skeleton"))
				{
					skeletonFileName += ".skeleton";
				}

				// Truncate the skeleton filename to just the name (no path)
				Ogre::String skelName = skeletonFileName;
				int pos = skeletonFileName.find_last_of("\\");
				if (pos == Ogre::String::npos)
				{
					pos = skeletonFileName.find_last_of("/");
				}
				if (pos != Ogre::String::npos)
				{
					skelName = skelName.substr(pos+1, skelName.size() - pos - 1);
				}


				// Do the mesh
				Ogre::DeformerMap& deformers = 
					meshExporter.buildMeshForExport(mergeSubmeshes, 
						exportChildren, edgeLists, tangents, tangentSemantic, 
						tangentsSplitMirrored, tangentsSplitRotated, tangentsUseParity,
						exportVertexAnimation, selAnimList, fps, materialPrefix,
						lodData, skelName);
				// do the skeleton
				const Ogre::AxisAlignedBox& skelAABB = 
					skelExporter.exportSkeleton(skeletonFileName, deformers, fps, selAnimList);

				// Do final mesh export
				meshExporter.exportMesh(meshFileName, skelAABB);
			}
			else
			{
				Ogre::AxisAlignedBox nullbb;
				// No skeleton
				meshExporter.buildMeshForExport(mergeSubmeshes, 
					exportChildren, edgeLists, tangents, tangentSemantic, 
					tangentsSplitMirrored, tangentsSplitRotated, tangentsUseParity,
					exportVertexAnimation, selAnimList, fps, materialPrefix, lodData);
				meshExporter.exportMesh(meshFileName, nullbb);
			}

			
			delete lodData;

			// Do we want to export materials too?
			if (exportMaterials)
			{
				param = prop.GetParameters().GetItem( L"targetMaterialFileName" );
				Ogre::String materialFileName = XSItoOgre(XSI::CString(param.GetValue()));
				// fix any omission of '.material'
				if (!Ogre::StringUtil::endsWith(materialFileName, ".material"))
				{
					materialFileName += ".material";
				}
				
				Ogre::XsiMaterialExporter matExporter;
				try 
				{
					matExporter.exportMaterials(meshExporter.getMaterials(), 
						meshExporter.getTextureProjectionMap(), 
						materialFileName, copyTextures);
				}
				catch (Ogre::Exception& e)
				{
					// ignore, non-fatal and will be in log
				}
			}

		}

	}
	catch (Ogre::Exception& e)
	{
		// Will already have been logged to the Ogre log manager
		// Tell XSI
		app.LogMessage(OgretoXSI(e.getDescription()), XSI::siFatalMsg);
		app.LogMessage(OgretoXSI(e.getFullDescription()), XSI::siInfoMsg);
	}

	//DeleteObj( L"OgreMeshExportOptions" );
	return st;	
}
Ejemplo n.º 19
0
// This function will set up everything required by Ogre
// and it will ask the user for display settings
// At the end of this function Ogre is ready to render.
// This function is mostly taken from tutorials and sample programs.
int CUIMain::SetupOgre(void)
{
	//=================
	//Ogre defaultly logs to console
	// To prevent this the LogManager has to be created
	// before the Root object.
	//=================
	Ogre::LogManager* logMgr = OGRE_NEW Ogre::LogManager;
	logMgr->createLog("Ogre.log", true, false, false);

	//=================
	//Create the Ogre root object
	// It's possible to specify as parameters the paths to the:
	// plugin file (what render systems it has to load), config file (screen resolution etc) and log file
	//=================
	if( !mRoot ) mRoot = OGRE_NEW Ogre::Root();

	//=================
	// Tell Ogre where all the needed resources are (rendersystems and so on)
	//=================
	Ogre::ConfigFile cf;
	cf.load("resources.cfg");
	
	Ogre::String secName, typeName, archName;
	Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator();
	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;
			Ogre::ResourceGroupManager::getSingleton().addResourceLocation(archName, typeName, secName);
		}
	}

	//=================
	// Set up the render system.
	// Ogre will ask the user for display settings
	//=================
	if( !mRoot->showConfigDialog() )
		return 0; //The user probably clicked cancel

	mWindow = mRoot->initialise(true, "NNYv3");

	//=================
	// Load all the resources. For now, just load all resources at once. The following is from a tutorial:
	// In a very large game or application, we may have hundreds or even thousands of resources
	// that our game uses - everything from meshes to textures to scripts. At any given time though,
	// we probably will only be using a small subset of these resources. To keep down memory requirements,
	// we can load only the resources that our application is using. We do this by dividing the resources
	// into sections and only initializing them as we go. 
	//=================
	Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5);
	Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();

	//=================
	// Preparing the scene
	//=================
	mSceneMgr = mRoot->createSceneManager(Ogre::ST_EXTERIOR_CLOSE); //ST_EXTERIOR_CLOSE allows rendering terrain

	mCamera.Initialize(mSceneMgr);

	Ogre::Viewport* vp = mWindow->addViewport(mCamera.GetCamera());
	vp->setBackgroundColour(Ogre::ColourValue(0.9,0.9,0.9));
	//Fog will not work with sky ;)
	//mSceneMgr->setFog(Ogre::FOG_LINEAR, Ogre::ColourValue(0.9,0.9,0.9), 0.0, 50, 500);

	mCamera.GetCamera()->setAspectRatio(Ogre::Real(vp->getActualWidth()) / Ogre::Real(vp->getActualHeight()));
	
	//Set a moving cloud texture as background
	mSceneMgr->setSkyDome(true, "CloudySky", 5, 8);

	//Get a RaySceneQuery object. A SceneQuery object is a class that can query all
	//objects in a region or scene. RaySceneQuery has it as a base class. RaySceneQuery
	//can get all objects that intersect a ray.
	mQueryMouseMovement = mSceneMgr->createRayQuery(Ogre::Ray(), QUERY_MASK_MOUSE_MOVEMENT);
	mQueryMouseSelection = mSceneMgr->createRayQuery(Ogre::Ray(), QUERY_MASK_MOUSE_SELECTING);

	LoadWorld();

	//=================
	// Set up the CEGUI system
	//=================
	mGUIHandler = new CGUIHandler(mWindow, mSceneMgr);

	//=================
	// Create the input handler
	//=================
	mInputHandler = new CInputHandler(mWorld, mCamera, mWindow, mSceneMgr);
	mRoot->addFrameListener(mInputHandler);
	mRoot->addFrameListener(this);

	//=================
	// Create the console overlay
	//=================
	mConsoleOverlay = new ConsoleOverlay();

	return 1;
}
Ejemplo n.º 20
0
//does all the initial setup of the window, camera, etc.
void OgreDisplay::initialize()
{
	//This code is used to stop ogre from spamming it's log to the command line.
	//It works by creating a dummy loglistener that doesn't output anything
	Ogre::LogManager* logger = new Ogre::LogManager();
	QuietLog qlog;
	logger->createLog("ogre/ogre.log", true, false, true);
	if (!verbose)
	{
		Ogre::LogManager::getSingleton().getDefaultLog()->addListener(&qlog);	
	}
		
	//use the files given 
	root = new Root("ogre/plugins.cfg", "ogre/ogre.cfg", "ogre/ogre.log");

	//this code chooses the renderer to use. without plugins.cfg, this won't work
	RenderSystemList* renderers = root->getAvailableRenderers();
	assert( !renderers->empty() );
	RenderSystem* renderSystems = renderers->at(0);
	root->setRenderSystem(renderSystems);

	//set up some options for our window
	root->getRenderSystem()->setConfigOption( "Full Screen", "No" );
	root->getRenderSystem()->setConfigOption( "Video Mode", "1920x1000" );
	root->getRenderSystem()->setConfigOption( "VSync", "Yes" );
	root->saveConfig();

	//FIXME: how can I get it to read this from resources.cfg instead of manually specifying it here?
	root->addResourceLocation("./content/", "FileSystem");
	
	//if (root->showConfigDialog())
	//FIXME: make it a command line thing to not show this?
	{
		renderWindow = root->initialise(true);
	}

	//choose scene manager, make camera and do clear colour
	sceneMgr = root->createSceneManager( ST_GENERIC, "PrototypeSceneManager");
	camera = sceneMgr->createCamera("ViewCamera");
	camera->setNearClipDistance(0.1);
	camera->setFarClipDistance(1000.0);
	
	viewport = renderWindow->addViewport(camera);
	viewport->setBackgroundColour(ColourValue(1, 1, 1));
	
	camera->setAspectRatio( Real(viewport->getActualWidth()) / Real(viewport->getActualHeight()) );

	//make a texture manager and resource groups
	TextureManager::getSingleton().setDefaultNumMipmaps(5);
	
	//ResourceGroupManager::getSingleton().createResourceGroup("procgen");
	//root->addResourceLocation("../content", "FileSystem", "procgen", true);
	ResourceGroupManager::getSingleton().initialiseAllResourceGroups();

	//some ambient light
	sceneMgr->setAmbientLight(ColourValue(0.0, 0.0, 0.0));
	//set the shadow type we'll be using - commented out because it was causing a crash
	//sceneMgr->setShadowTechnique(Ogre::SHADOWTYPE_STENCIL_ADDITIVE);

	//put the camera looking at the origins
	camera->setPosition(0,0,0);
	camera->lookAt(Vector3(64,64,64));

	//create a static geometry group for doing the voxels
	sceneMgr->createStaticGeometry("voxel_grid");

	//make a billboard group.
	sceneMgr->createBillboardSet("voxel_grid");
	sceneMgr->getRootSceneNode()->attachObject(sceneMgr->getBillboardSet("voxel_grid"));
	sceneMgr->getBillboardSet("voxel_grid")->setDefaultDimensions(1.0, 1.0);
	//enable this to rendering the voxels as points
	sceneMgr->getBillboardSet("voxel_grid")->setPointRenderingEnabled(true);
	sceneMgr->getBillboardSet("voxel_grid")->setMaterialName("basic/cube_default");

	//do mesh setup stuff
	cubeCount = 0;
	cylinderCount = 0;
	this->createCubeMesh(); //use default arguments to make the default cube
	this->createCylinderMesh(); //use default arguments to make the default cylinder
}
Ejemplo n.º 21
0
bool
    GraphicsController::onInit(Ogre::SceneManager* scnMgr, Ogre::Viewport* viewport, Ogre::Camera* camera,
    		Ogre::int32 windowWidth, Ogre::int32 windowHeight)
{

    _cam = camera;
    _scnMgr = scnMgr;
    _vp = viewport;
    //_dynLightsManager = packet->workspaceCtrl->getZWorkspace()->getWorldController()->getDynamicLightManager();
    //generate random textures
    
    for(size_t i = 0; i < NUM_OF_BANDS * 4; i++)
    {
        _SHC_R[i] = 0.0f;
        _SHC_G[i] = 0.0f;
        _SHC_B[i] = 0.0f;
    }

    Ogre::LogManager* lm = Ogre::LogManager::getSingletonPtr();
    lm->logMessage(Ogre::LML_TRIVIAL, "In GraphicsController::onInit()");
    lm->logMessage(Ogre::LML_NORMAL, "Adding compositor bloom");

    //First build the lights.
    _lightDir.normalise();

	Vector3 lightdir(0.0, -0.5, 0.1);
		lightdir.normalise();
    lightdir *= -1;
    _scnMgr->setAmbientLight(Ogre::ColourValue(0.5f, 0.5f, 0.5f));
    light = _scnMgr->createLight("terrainLight");
	light->setType(Light::LT_DIRECTIONAL);
	light->setCastShadows(true);
	light->setShadowFarClipDistance(256);
    
	Ogre::ColourValue fadeColour(1.0, 1.0, 1.0);
    _scnMgr->setFog(Ogre::FOG_NONE);

    _initBackgroundHdr();
    _vp->setBackgroundColour(fadeColour);


    Ogre::CompositorManager& compMgr = Ogre::CompositorManager::getSingleton();
	_hdrLogic = new HDRLogic();
    compMgr.registerCompositorLogic("HDR", _hdrLogic);
    _ogreHdr = CompositorManager::getSingleton().addCompositor(_vp, "HDR", 0);
    Ogre::CompositorManager::getSingleton().setCompositorEnabled(_vp, "HDR", true);

    /*
	//setup the HDR options.
	auto sharedParams = Ogre::GpuProgramManager::getSingleton().getSharedParameters("HdrSharedParams");

	ZGame::Graphics::GraphicsOptions gfxOptions;

	sharedParams->setNamedConstant("MIDDLE_GREY", gfxOptions.hdr_middle_grey);
	sharedParams->setNamedConstant("BRIGHT_LIMITER", gfxOptions.hdr_bright_limiter);
	sharedParams->setNamedConstant("FUDGE", gfxOptions.hdr_fudge_factor);
	*/

    _deferredGfx->initialize(_cam, windowWidth, windowHeight);
    
    //addTextureDebugOverlay(_deferredGfx->getLightBufferTex()->getName(), 1);

    //Ogre::OverlayManager::getSingleton().getByName("PRJZ/DebugOverlay")->show();
	    
    //addTextureDebugOverlay(_deferredGfx->getGBuffer1Tex()->getName(), 0);
	//addTextureDebugOverlay(_rtLum4->getName(), 0);
	//addTextureDebugOverlay(_deferredGfx->getNormalDepthTex()->getName(), 0);
    //Overlay* debugOverlay = OverlayManager::getSingleton().getByName("PRJZ/DebugOverlay");
    //debugOverlay->show();
    //addTextureDebugOverlay(_deferredGfx->getLightBufferTex()->getName(), 0);
    //addTextureDebugOverlay(_ssaoBlurY->getName(), 0);
    //addTextureDebugOverlay(_ssaoTarget->getName(), 0);
    //addTextureDebugOverlay(_hfaoTarget->getName(), 0);
	//addTextureDebugOverlay(_hfaoBlurY->getName(), 0);
    //addTextureDebugOverlay(_wendlandFilter->getName(), 0);
    //addTextureDebugOverlay(_ssaoTarget->getName(), 0);
    //addTextureDebugOverlay(_bitwiseLookupTex->getName(), 0);
    //addTextureDebugOverlay(_hfaoBlurY, 0);

    //setup the texture data textures.

	 //setup lighting direction quad
    /*
    _directionLightQuad = new Ogre::Rectangle2D(true);
    _directionLightQuad->setCorners(-1, 1, 1, -1);
    _directionLightQuad->setBoundingBox(Ogre::AxisAlignedBox::BOX_INFINITE);
    //was 0xf0
    _directionLightQuad->setVisibilityFlags(0xf0); //F**K: for mask see DynamicLightManager. We need to define these globally.
    _directionLightQuad->setCastShadows(false);
	_directionLightQuad->setRenderQueueGroup(Ogre::RENDER_QUEUE_6);
    _directionLightQuad->setVisible(true);
    _directionLightQuad->setMaterial("PRJZ/DirectionLightBuffer");

    _scnMgr->getRootSceneNode()->attachObject(_directionLightQuad);
	*/
    return true;
}
Ejemplo n.º 22
0
int main(int argc, char **argv)
#endif
{
    int ret = 0;
    Ogre::Log * log = NULL;
    Ogre::Root * root = NULL;
    GameManager* game = NULL;
    Ogre::LogManager * logMgr = NULL;
    bool configCreated = false;
    std::string ogreLogPath, ogreCfgPath;
    
    srand(time(NULL));
    
    using namespace boost::filesystem;
    // Creates the Lost Marbles directory to write to
    path lostMarblesDir(utils::getLostMarblesWriteDir());
    
    try {
        if(! exists(lostMarblesDir))
            create_directories(lostMarblesDir);
    } catch(const filesystem_error& ex) {
        #if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
        MessageBoxA(NULL, ex.what(), "An exception has occurred!", MB_OK | MB_ICONERROR | MB_TASKMODAL);
        #else
        std::cerr << "An exception has occured: " << ex.what() << std::endl;
        #endif
        ret = 1;
        goto gracefulexit;
    }
    

    ogreLogPath = (lostMarblesDir / "Ogre.log").string();
    logMgr = new Ogre::LogManager();
    log = logMgr->createLog(ogreLogPath, true, true, false);
    
    ogreCfgPath = (lostMarblesDir / "Ogre.cfg").string();
    root = new Ogre::Root("Plugins.cfg",ogreCfgPath);

    log->logMessage("Main Lost Marbles write directory " + lostMarblesDir.string());
    log->logMessage("Log Path: " + ogreLogPath);
    log->logMessage("Config Path: " + ogreCfgPath);

    if(!root->restoreConfig()) {
        configCreated = root->showConfigDialog();
        root->saveConfig();
    } else
        configCreated = true;

    if(configCreated) {
        game = new GameManager();

        try {
            // initialize the game and switch to the first state
            game->start(LogoState::getInstance());
        } catch (Ogre::Exception& e) {
            #if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
            MessageBoxA(NULL, e.getFullDescription().c_str(), "An exception has occurred!", MB_OK | MB_ICONERROR | MB_TASKMODAL);
            #else
            std::cerr << "An exception has occured: " << e.getFullDescription() << std::endl;
            #endif
            ret = 1;
            goto gracefulexit;
        } 
    }

gracefulexit:
    if(game) delete game;
    if(root) delete root;
    if(logMgr) delete logMgr;
    return ret;
}
void NativeEnginePrivate::initOgre()
{
#if !defined(NDEBUG)
    Ogre::String pluginsCfg = "plugins_d.cfg";
#else
    Ogre::String pluginsCfg = "plugins.cfg";
#endif

    Ogre::LogManager * lm = new Ogre::LogManager();
    Ogre::Log *log = lm->createLog("", true, false, false);
    log->addListener(this);

    /* Initialize Ogre */
    ogreRoot = new Ogre::Root(pluginsCfg);

    /* Set OpenGL render system on Ogre */
    Ogre::RenderSystem *renderSystem = ogreRoot->getRenderSystemByName("OpenGL Rendering Subsystem");
    if (!renderSystem)
        throw std::exception("Unable to find OpenGL Render System!");
    renderSystem->setConfigOption("Colour Depth", "32");
    renderSystem->setConfigOption("Fixed Pipeline Enabled", "Yes");
    renderSystem->setConfigOption("VSync", "No");
    ogreRoot->setRenderSystem(renderSystem);

    ogreRoot->initialise(false);

    /* Initialize the render window to use the GLWidget internally */
    Ogre::NameValuePairList params;
    params["externalGLControl"] = "true";
    params["externalGLContext"] = QString::number((uint)wglGetCurrentContext()).toStdString(); // TODO: Platform dependent
    params["externalWindowHandle"] = QString::number((uint)glWidget->winId()).toStdString();
    ogreWindow = ogreRoot->createRenderWindow("", glWidget->width(), glWidget->height(), false, &params);

    /* We don't use mip maps since our camera distance from all objects is fixed */
    Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(0);

    /* here we could load "builtin" resources, but all other resources should be controlled by c# */
    /*Ogre::ResourceGroupManager &resourceManager = Ogre::ResourceGroupManager::getSingleton();
    resourceManager.addResourceLocation("C:/Users/Sebastian/AppData/Local/EvilTemple/data.zip", "Zip", "General", true);
    resourceManager.initialiseAllResourceGroups();*/

    /* Create the actual scene manager */
    ogreRoot->addSceneManagerFactory(new SceneFactory);
    ogreRoot->addMovableObjectFactory(new GroundDiscFactory);
    sceneManager = static_cast<Scene*>(ogreRoot->createSceneManager("Scene"));
    sceneManager->resizeWindow(glWidget->width(), glWidget->height());

    /* Create and initialize the main camera */
    camera = sceneManager->getMainCamera();

    /* Create the viewport */
    viewport = ogreWindow->addViewport(camera);
    viewport->setBackgroundColour(Ogre::ColourValue(0.5, 0.5, 0.5));

    sceneManager->setAmbientLight(Ogre::ColourValue(0, 0, 0));

    /* TEST */
    /*Ogre::Entity* model = sceneManager->createEntity("meshes/pcs/pc_human_male/pc_human_male.mesh");

    Ogre::SceneNode* headNode = sceneManager->getRootSceneNode()->createChildSceneNode();
    headNode->setPosition(0, 0, 0);
    headNode->attachObject(model);

    Ogre::AnimationState *animState = model->getAnimationState("unarmed_unarmed_idle");
    animState->setEnabled(true);
    animState->setLoop(true);
    animState->setWeight(1.0f);

    sceneManager->setAmbientLight(Ogre::ColourValue(0, 0, 0));

    // Create a light
    Ogre::Light* l = sceneManager->createLight("MainLight");
    l->setType(Ogre::Light::LT_DIRECTIONAL);
    l->setDirection(-0.6324093645670703858428703903848,
                    -0.77463436252716949786709498111783,
                    0);*/

    /* /TEST */
}
Ejemplo n.º 24
0
 void
 setupLog() {
     static Ogre::LogManager logManager;
     logManager.createLog("default", true, false, false);
 }
Ejemplo n.º 25
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);
}