コード例 #1
0
ファイル: PolygonPoint.cpp プロジェクト: nocylah/ember
PolygonPoint::PolygonPoint(Polygon& polygon, const WFMath::Point<2>& localPosition) :
    mPolygon(polygon), mUserObject(*this), mNode(0), mEntity(0)
{
    Ogre::Vector3 nodePosition = Convert::toOgre<Ogre::Vector3>(localPosition);
    if (polygon.getPositionProvider()) {
        nodePosition.y = polygon.getPositionProvider()->getHeightForPosition(localPosition);
    }
    mNode = mPolygon.getBaseNode()->createChildSceneNode(nodePosition);
    mNode->setScale(0.25f, 0.25f, 0.25f);

    std::stringstream ss;
    ss << "PolygonPoint" << sPointCounter++;

    try {
        mEntity = mNode->getCreator()->createEntity(ss.str(), "3d_objects/primitives/models/sphere.mesh");
        //start out with a normal material
        mEntity->setMaterialName("/global/authoring/point");
        mEntity->setRenderingDistance(300);
        mEntity->setQueryFlags(MousePicker::CM_UNDEFINED);

        mEntity->setUserAny(Ogre::Any(&mUserObject));

    } catch (const std::exception& ex) {
        S_LOG_FAILURE("Error when creating polygon point marker entity." << ex);
        return;
    }

    if (!mEntity) {
        S_LOG_FAILURE("Unexpected error when creating polygon point marker entity.");
        return;
    }
    mNode->attachObject(mEntity);
}
コード例 #2
0
ファイル: Widget.cpp プロジェクト: Chimangoo/ember
	CEGUI::Window* Widget::loadMainSheet(const std::string& filename, const std::string& prefix) {
		assert(mWindowManager && "You must call init() before you can call any other methods.");
		mPrefix = prefix;
		std::string finalFileName(mGuiManager->getLayoutDir() + filename);
		try {
			mMainWindow = mWindowManager->loadLayoutFromFile(finalFileName);
		} catch (const std::exception& ex) {
			S_LOG_FAILURE("Error when loading from " << filename << "." << ex);
			throw ex;
		} catch (...) {
			S_LOG_FAILURE("Unknown error when loading from " << filename << ".");
			throw;
		}
		mMainWindow->setName(prefix);
		mOriginalWindowAlpha = mMainWindow->getAlpha();
		getMainSheet()->addChild(mMainWindow);
		BIND_CEGUI_EVENT(mMainWindow, CEGUI::FrameWindow::EventActivated, Widget::MainWindow_Activated);
		BIND_CEGUI_EVENT(mMainWindow, CEGUI::FrameWindow::EventDeactivated, Widget::MainWindow_Deactivated);
		//we want to catch all click events, so we'll listen for the mouse button down event
		BIND_CEGUI_EVENT(mMainWindow, CEGUI::Window::EventMouseButtonDown, Widget::MainWindow_MouseButtonDown);
		if (mMainWindow->isVisible()) {
			onEventFirstTimeShown();
		} else {
			//Set it up to listen for the first time the window is shown.
			BIND_CEGUI_EVENT(mMainWindow, CEGUI::Window::EventShown, Widget::MainWindow_Shown);
		}

		return mMainWindow;
	}
コード例 #3
0
ファイル: TerrainParser.cpp プロジェクト: Arsakes/ember
TerrainDefPointStore TerrainParser::parseTerrain(const Atlas::Message::Element& terrain, const WFMath::Point<3>& offset) const
{
	//_fpreset();
	if (!terrain.isMap()) {
		S_LOG_FAILURE("Terrain is not a map");
	}
	const Atlas::Message::MapType & tmap = terrain.asMap();
	Atlas::Message::MapType::const_iterator I = tmap.find("points");
	if (I == tmap.end()) {
		S_LOG_FAILURE("No terrain points");
	}

	Terrain::TerrainDefPointStore pointStore;
	if (I->second.isList()) {
		// Legacy support for old list format.
		const Atlas::Message::ListType& plist = I->second.asList();
		Atlas::Message::ListType::const_iterator J = plist.begin();
		for (; J != plist.end(); ++J) {
			if (!J->isList()) {
				S_LOG_INFO("Non list in points");
				continue;
			}
			const Atlas::Message::ListType & point = J->asList();
			if (point.size() != 3) {
				S_LOG_INFO("Point without 3 nums.");
				continue;
			}

			Terrain::TerrainDefPoint defPoint(static_cast<int> (point[0].asNum() + offset.x()), static_cast<int> (point[1].asNum() + offset.y()), static_cast<float> (point[3].asNum() + offset.z()));
			pointStore.push_back(defPoint);
		}
	} else if (I->second.isMap()) {
		const Atlas::Message::MapType& plist = I->second.asMap();
		Atlas::Message::MapType::const_iterator J = plist.begin();
		for (; J != plist.end(); ++J) {
			if (!J->second.isList()) {
				S_LOG_INFO("Non list in points.");
				continue;
			}
			const Atlas::Message::ListType & point = J->second.asList();
			if (point.size() != 3) {
				S_LOG_INFO("Point without 3 nums.");
				continue;
			}
			int x = static_cast<int> (point[0].asNum());
			int y = static_cast<int> (point[1].asNum());
			float z = point[2].asNum();
			Terrain::TerrainDefPoint defPoint(x  + offset.x(), y + offset.y(), z + offset.z());
			pointStore.push_back(defPoint);
		}
	} else {
		S_LOG_FAILURE("Terrain is the wrong type");
	}
	return pointStore;

}
コード例 #4
0
ファイル: GUIManager.cpp プロジェクト: Chimangoo/ember
CEGUI::Window* GUIManager::createWindow(const std::string& windowType, const std::string& windowName)
{
	try {
		CEGUI::Window* window = mWindowManager->createWindow(windowType, windowName);
		return window;
	} catch (const CEGUI::Exception& ex) {
		S_LOG_FAILURE("Error when creating new window of type " << windowType << " with name " << windowName << ".\n" << ex.getMessage().c_str());
		return 0;
	} catch (const std::exception& ex) {
		S_LOG_FAILURE("Error when creating new window of type " << windowType << " with name " << windowName << "." << ex);
		return 0;
	}
}
コード例 #5
0
ファイル: FoliageLoader.cpp プロジェクト: Arsakes/ember
void FoliageLoader::plantQueryExecuted(const Terrain::PlantAreaQueryResult& queryResult)
{
	mLatestPlantsResult = &queryResult;
	//Be sure to catch errors so that we always reset the mLatestPlantsResult field when done.
	try {
		mPagedGeometry.reloadGeometryPage(Ogre::Vector3(queryResult.getQuery().getCenter().x, 0, queryResult.getQuery().getCenter().y), true);
	} catch (const std::exception& ex) {
		S_LOG_FAILURE("Error when reloading geometry." << ex);
	} catch (...) {
		S_LOG_FAILURE("Unknown error when reloading geometry.");
	}
	mLatestPlantsResult = 0;

}
コード例 #6
0
	bool SoundGeneral::checkAlError(const std::string& description)
	{
		ALenum error = alGetError();
		if (error == AL_NO_ERROR) {
			return true;
		} else {
			if (description == "") {
				S_LOG_FAILURE("OpenAl error: " << alutGetErrorString(error));
			} else {
				S_LOG_FAILURE("OpenAl error: " << alutGetErrorString(error)
					      << "\nDescription: " << description);
			}
			return false;
		}
	}
コード例 #7
0
ファイル: SimpleWater.cpp プロジェクト: junrw/ember-gsoc2012
bool SimpleWater::initialize()
{
  try {
    Ogre::Plane waterPlane(Ogre::Vector3::UNIT_Y, 0);

    // create a water plane/scene node
    Ogre::MeshManager::getSingleton().createPlane("SimpleWaterPlane", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, waterPlane, 10000, 10000, 5, 5, true, 1, 1000, 1000, Ogre::Vector3::UNIT_Z);

    mWaterNode = mSceneMgr.getRootSceneNode()->createChildSceneNode("water");

    mWaterEntity = mSceneMgr.createEntity("water", "SimpleWaterPlane");
    mWaterEntity->setMaterialName("/global/environment/water/ocean");
    //Render the water very late on, so that any transparent entity which is half submerged is already rendered.
    mWaterEntity->setRenderQueueGroup(Ogre::RENDER_QUEUE_8);
    mWaterEntity->setCastShadows(false);
    mWaterEntity->setQueryFlags(MousePicker::CM_NATURE);

    mWaterNode->attachObject(mWaterEntity);
    return true;
  } catch (const std::exception& ex) {
    S_LOG_FAILURE("Error when creating simple water." << ex);
    return false;
  }

}
コード例 #8
0
ShaderManager::GraphicsLevel ShaderManager::setGraphicsLevel(ShaderManager::GraphicsLevel newLevel)
{
  if (newLevel > mBestGraphicsLevel) {
    S_LOG_FAILURE("Cannot set graphics level " << mGraphicSchemes[newLevel]);
    return mGraphicsLevel;
  }

  S_LOG_INFO("Using graphics level " << mGraphicSchemes[newLevel]);
  Ogre::MaterialManager::getSingleton().setActiveScheme(mGraphicSchemes[newLevel]);

  Ogre::RenderWindow* window = EmberOgre::getSingleton().getRenderWindow();
  for (int i = 0; i < window->getNumViewports(); ++i) {
    window->getViewport(i)->setMaterialScheme(mGraphicSchemes[newLevel]);
  }

  switch (newLevel) {
  case LEVEL_EXPERIMENTAL:
  case LEVEL_HIGH:
    setPSSMShadows();
    break;

  case LEVEL_MEDIUM:
  case LEVEL_LOW:
  case LEVEL_DEFAULT:
    setNoShadows();
    break;
  }
  mGraphicsLevel = newLevel;

  EventLevelChanged.emit();

  return mGraphicsLevel;
}
コード例 #9
0
void MainCamera::enableCompositor(const std::string& compositorName, bool enable)
{
	if (enable) {
		S_LOG_INFO("Enabling compositor '" << compositorName<< "'.");
	} else {
		S_LOG_INFO("Disabling compositor '" << compositorName<< "'.");
	}
	if (std::find(mLoadedCompositors.begin(), mLoadedCompositors.end(), compositorName) == mLoadedCompositors.end()) {
		Ogre::CompositorInstance* compositor = Ogre::CompositorManager::getSingleton().addCompositor(mWindow.getViewport(0), compositorName);
		if (compositor) {
			bool hasErrors = false;
			//There's a bug in Ogre which will causes a segfault during rendering if a compositor has an invalid shader.
			//We therefore need to check for this here, and disable the shader if so is the case.
			compositor->getCompositor()->load();
			hasErrors = !validateCompositionTargetPass(*compositor->getTechnique()->getOutputTargetPass());
			if (!hasErrors) {
				Ogre::CompositionTechnique::TargetPassIterator targetPassIter = compositor->getTechnique()->getTargetPassIterator();
				while (targetPassIter.hasMoreElements() && !hasErrors) {
					hasErrors = !validateCompositionTargetPass(*targetPassIter.getNext());
				}
			}
			if (hasErrors) {
				S_LOG_FAILURE("Compositor "<< compositorName <<" has errors and will be disabled.");
				Ogre::CompositorManager::getSingleton().removeCompositor(mWindow.getViewport(0), compositorName);
			} else {
				compositor->setEnabled(true);
				mLoadedCompositors.push_back(compositorName);
			}
		}
	} else {
		Ogre::CompositorManager::getSingleton().setCompositorEnabled(mWindow.getViewport(0), compositorName, enable);
	}
}
コード例 #10
0
ファイル: ConfigService.cpp プロジェクト: LawrenceWeng/ember
	bool ConfigService::loadSavedConfig ( const std::string& filename, const StringConfigMap& commandLineSettings )
	{
		S_LOG_INFO ( "Loading shared config file from " << getSharedConfigDirectory() + "/"+ filename << "." );
		bool success = mGlobalConfig->readFromFile ( getSharedConfigDirectory() + "/"+ filename, varconf::GLOBAL );
		std::string userConfigPath ( getHomeDirectory() + "/" + filename );
		std::ifstream file ( userConfigPath.c_str() );
		if ( !file.fail() )
		{
			S_LOG_INFO ( "Loading user config file from "<< getHomeDirectory() + "/" + filename <<"." );
			try
			{
				mUserConfig->parseStream ( file, varconf::USER );
			}
			catch ( varconf::ParseError& p )
			{
				S_LOG_FAILURE ( "Error loading user config file: " << p );
				success = false;
			}
		}
		else
		{
			S_LOG_INFO ( "Could not find any user config file." );
		}

		//after loading the config from file, override with command time settings
		for (StringConfigMap::const_iterator I = commandLineSettings.begin(); I != commandLineSettings.end(); ++I) {
			for (std::map<std::string, std::string>::const_iterator J = I->second.begin(); J != I->second.end(); ++J) {
				S_LOG_INFO("Setting command line config option " << I->first << ":" << J->first << " to " << J->second);
				mCommandLineConfig->setItem(I->first, J->first, J->second);
				EventChangedConfigItem(I->first, J->first);
			}
		}
		return success;
	}
コード例 #11
0
ファイル: AvatarLogger.cpp プロジェクト: Laefy/ember
AvatarLogger::AvatarLogger(EmberEntity& avatarEntity)
: mChatLogger(nullptr)
{
	assert(&avatarEntity);

	//Put log files in a "logs" subdirectory of the home directory.
	const std::string dir = EmberServices::getSingleton().getConfigService().getHomeDirectory() + "/logs/";
	try {
		//make sure the directory exists

		oslink::directory osdir(dir);

		if (!osdir.isExisting()) {
			oslink::directory::mkdir(dir.c_str());
		}
		//perform setup of the stream
		std::stringstream logFileSS;
		logFileSS << dir << "/" << avatarEntity.getName() << "_chatlog.log";
		mChatLogger = std::unique_ptr<std::ofstream>(new std::ofstream(logFileSS.str().c_str(), std::ios::app));
		S_LOG_VERBOSE("Chat Logging set to write in [ " << logFileSS.str() << " ]");

		*mChatLogger << "-------------------------------------------------------" << std::endl;
		*mChatLogger << "Chat Logging Initialized at " <<  Time::getLocalTimeStr() << std::endl;
		*mChatLogger << "-------------------------------------------------------" << std::endl;

		//wait with connecting until everything has been properly set up
		GUIManager::getSingleton().AppendIGChatLine.connect(sigc::mem_fun(*this, &AvatarLogger::GUIManager_AppendIGChatLine));

	} catch (const std::exception& ex) {
		S_LOG_FAILURE("Error when creating directory for logs." << ex);
	}
}
コード例 #12
0
ファイル: Connectors.cpp プロジェクト: evilprince/ember
void ConnectorBase::callFunction(lua_State* state, int numberOfArguments)
{

	//push our error handling method before calling the code
	int error_index = lua_gettop(state) - numberOfArguments;
#if LUA51
	lua_pushcfunction(state, LuaHelper::luaErrorHandler);
#else
	lua_pushliteral(state, "_TRACEBACK");
	lua_rawget(state, LUA_GLOBALSINDEX); /* get traceback function */
#endif
	lua_insert(state, error_index);/* put it under chunk and args */

	luaPop pop(state, 1); // pops error handler on exit

	// call it
	int error = 0;

	try {
		error = lua_pcall(state, numberOfArguments, LUA_MULTRET, error_index);
	} catch (const std::exception& ex) {
		const std::string& msg = lua_tostring(state,-1);
		throw Exception(msg);
	}

	// handle errors
	if (error) {
		const std::string& msg = lua_tostring(state,-1);
		S_LOG_FAILURE("(LuaScriptModule) Lua error: " << msg);
		return;
	}
}
コード例 #13
0
bool OgreResourceLoader::addResourceDirectory(const std::string& path, const std::string& type, const std::string& section, bool recursive, bool reportFailure, bool throwOnFailure)
{
	if (isExistingDir(path)) {
		S_LOG_VERBOSE("Adding dir " << path);
		try {
			Ogre::ResourceGroupManager::getSingleton().addResourceLocation(path, type, section, recursive);
			return true;
		} catch (const std::exception&) {
			if (throwOnFailure) {
				throw Ember::Exception(std::string("Could not load from required directory '") + path + "'. This is fatal and Ember will shut down. The probable cause for this error is that you haven't properly installed all required media.");
			}
			if (reportFailure) {
				S_LOG_FAILURE("Couldn't load " << path << ". Continuing as if nothing happened.");
			}
		}
	} else {
		if (throwOnFailure) {
			throw Ember::Exception(std::string("Could not find required directory '") + path + "'. This is fatal and Ember will shut down. The probable cause for this error is that you haven't properly installed all required media.");
		}
		if (reportFailure) {
			S_LOG_VERBOSE("Couldn't find resource directory " << path);
		}
	}
	return false;
}
コード例 #14
0
SimpleEntityVisualization::SimpleEntityVisualization(EmberEntity& entity, Ogre::SceneNode* sceneNode) :
		mEntity(entity),
		mSceneNode(sceneNode),
		mErisEntityBoundingBox(OGRE_NEW Ogre::OOBBWireBoundingBox()),
		mBboxConnection(entity.observe("bbox", sigc::mem_fun(*this, &SimpleEntityVisualization::entity_BboxChanged))),
		mScaleConnection(entity.observe("scale", sigc::mem_fun(*this, &SimpleEntityVisualization::entity_BboxChanged)))
{

	mVelocityArrowEntity = sceneNode->getCreator()->createEntity("common/primitives/model/arrow.mesh");
	mVelocitySceneNode = sceneNode->getParentSceneNode()->createChildSceneNode();
	mVelocitySceneNode->attachObject(mVelocityArrowEntity);
	mVelocitySceneNode->setScale(0.5, 0.5, 0.5);

	try {
		auto materialPtr = Ogre::MaterialManager::getSingleton().getByName(BboxMaterialName, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
		if (materialPtr) {
			mErisEntityBoundingBox->setMaterial(materialPtr);
		}
	} catch (const std::exception& ex) {
		S_LOG_FAILURE("Error when setting Ogre material for bounding box.");
		OGRE_DELETE mErisEntityBoundingBox;
		mErisEntityBoundingBox = nullptr;
		throw Exception("Error when setting Ogre material for bounding box.");
	}
	mSceneNode->attachObject(mErisEntityBoundingBox);
	mErisEntityBoundingBox->setVisible(true);
	updateBbox();
	updatePositionAndOrientation();
	mEntity.Moved.connect(sigc::mem_fun(*this, &SimpleEntityVisualization::entity_Moved));
}
コード例 #15
0
void EmberEntityModelAction::activate(EntityMapping::ChangeContext& context)
{
	Model::Model* model = Model::ModelRepresentationManager::getSingleton().getModelForEntity(mEntity);
	if (!model || model->getDefinition()->getName() != mModelName) {
		mEntity.setGraphicalRepresentation(0);
		model = Model::Model::createModel(mScene.getSceneManager(), mModelName, mEntity.getId());
		model->setVisible(mEntity.isVisible());

		//if the model definition isn't valid, use a placeholder
		if (!model->getDefinition()->isValid()) {
			S_LOG_FAILURE( "Could not find " << mModelName << ", using placeholder.");
			//add a placeholder model
			Model::ModelDefinitionPtr modelDef = model->getDefinition();
			modelDef->createSubModelDefinition("3d_objects/primitives/models/box.mesh")->createPartDefinition("main")->setShow(true);
			modelDef->setValid(true);
			modelDef->reloadAllInstances();
		}

		Model::ModelRepresentation* representation = new Model::ModelRepresentation(mEntity, *model, mScene, mMapping);
		mEntity.setGraphicalRepresentation(representation);
		representation->initFromModel();


	}
}
コード例 #16
0
SoundGroupDefinition* SoundDefinitionManager::createSoundGroupDefinition(const std::string& name)
{
	SoundGroupDefinition* newModel = getSoundGroupDefinition(name);
	if (!newModel)
	{
		newModel = new SoundGroupDefinition();
		if (newModel)
		{
			#ifdef THREAD_SAFE
			pthread_mutex_lock(&mGroupModelsMutex);
			#endif

			mSoundGroupDefinitions[name] = newModel;

			#ifdef THREAD_SAFE
			pthread_mutex_unlock(&mGroupModelsMutex);
			#endif

			return newModel;
		}
		else
		{
			S_LOG_FAILURE("Failed to allocate sound group model " << name);
			return NULL;
		}
	}
	else
	{
		S_LOG_INFO("Sound Group definition " << name << " already exists.");
		return NULL;
	}
}
コード例 #17
0
ファイル: EmberTerrainGroup.cpp プロジェクト: Chimangoo/ember
void EmberTerrainGroup::handleResponse(const WorkQueue::Response* res, const WorkQueue* srcQ)
{
	--sLoadingTaskNum;

	LoadRequest lreq = any_cast<LoadRequest>(res->getRequest()->getData());

	if (res->succeeded()) {
		TerrainSlot* slot = lreq.slot;
		Ogre::Terrain* terrain = slot->instance;
		if (terrain) {
			terrain->setPosition(getTerrainSlotPosition(slot->x, slot->y));

			if (mAutoUpdateLod) {
				terrain->load(-1, false);
			} else {
				terrain->load(0, true);
			}

			for (int i = -1; i <= 1; ++i) {
				for (int j = -1; j <= 1; ++j) {
					if (i != 0 || j != 0) {
						connectNeighbour(slot, i, j);
					}
				}

			}
		}
	} else {
		S_LOG_FAILURE("Failed to prepare terrain at " << lreq.slot->x << ", " << lreq.slot->y << ". Error: " << res->getMessages());
		lreq.slot->freeInstance();
	}
}
コード例 #18
0
ファイル: XMLHelper.cpp プロジェクト: Arsakes/ember
bool XMLHelper::Load(TiXmlDocument& xmlDoc, Ogre::DataStreamPtr stream)
{
	size_t length(stream->size());

	if ( length )
	{
		// If we have a file, assume it is all one big XML file, and read it in.
		// The document parser may decide the document ends sooner than the entire file, however.
		std::string data(stream->getAsString());

		xmlDoc.Parse( data.c_str());

		if (xmlDoc.Error() ) {
			std::string errorDesc = xmlDoc.ErrorDesc();
			int errorLine =  xmlDoc.ErrorRow();
			int errorColumn =  xmlDoc.ErrorCol();
			std::stringstream ss;
			ss << "Failed to load xml file '" << stream->getName() << "'! Error at column: " << errorColumn << " line: " << errorLine << ". Error message: " << errorDesc;
			S_LOG_FAILURE(ss.str());
			return false;
		} else {
            return true;
		}
	}
	return false;
}
コード例 #19
0
void ModelPreviewWorker::setModel(const std::string& modelName)
{
	if (mModel) {
		if (mModel->getDefinition()->getName() == modelName) {
			return;
		} else {
			//Reset the model mount to start with.
			delete mModelMount;
			mModelMount = 0;
			mWorld.getSceneManager().destroyMovableObject(mModel);
		}
	}
	mModel = Model::Model::createModel(mWorld.getSceneManager(), modelName);
	mModel->Reloaded.connect(sigc::mem_fun(*this, &ModelPreviewWorker::model_Reloaded));

	//if the model definition isn't valid, use a placeholder
	if (!mModel->getDefinition()->isValid()) {
		S_LOG_FAILURE( "Could not find " << modelName << ", using placeholder.");
		//add a placeholder model
		Model::ModelDefnPtr modelDef = mModel->getDefinition();
		modelDef->createSubModelDefinition("3d_objects/primitives/models/box.mesh")->createPartDefinition("main")->setShow(true);
		modelDef->setValid(true);
		modelDef->reloadAllInstances();
	}

	mModelMount = new Model::ModelMount(*mModel, new SceneNodeProvider(*mEntityNode, mModel));

	initFromModel();

	// Setting inital position and orientation
	if (mPos.isValid()) {
		mEntityNode->setPosition(Convert::toOgre(mPos));
	}
	mEntityNode->setOrientation(Convert::toOgre(mOrientation));
}
コード例 #20
0
ファイル: TaskQueue.cpp プロジェクト: junrw/ember-gsoc2012
void TaskQueue::pollProcessedTasks(long long maxAllowedTimeMilliseconds)
{
  long long startTime = Time::currentTimeMillis();
  TaskUnitQueue processedCopy;
  {
    boost::mutex::scoped_lock l(mProcessedQueueMutex);
    processedCopy = mProcessedTaskUnits;
    if (mProcessedTaskUnits.size()) {
      mProcessedTaskUnits = TaskUnitQueue();
    }
  }
  while (processedCopy.size()) {

    TaskUnit* taskUnit = processedCopy.front();
    processedCopy.pop();
    try {
      taskUnit->executeInMainThread();
    } catch (const std::exception& ex) {
      S_LOG_FAILURE("Error when executing task in main thread." << ex);
    } catch (...) {
      S_LOG_FAILURE("Unknown error when executing task in main thread.");
    }
    try {
      delete taskUnit;
    } catch (const std::exception& ex) {
      S_LOG_FAILURE("Error when deleting task in main thread." << ex);
    } catch (...) {
      S_LOG_FAILURE("Unknown error when deleting task in main thread.");
    }
    //Try to keep the time spent here each frame down, to keep the framerate up.
    if (maxAllowedTimeMilliseconds > 0 && Time::currentTimeMillis() - startTime > maxAllowedTimeMilliseconds) {
      break;
    }
  }
  //If there are any unprocessed tasks, put them back at the front of the queue.
  if (processedCopy.size()) {
    boost::mutex::scoped_lock l(mProcessedQueueMutex);
    TaskUnitQueue queueCopy(mProcessedTaskUnits);
    mProcessedTaskUnits = processedCopy;
    while (queueCopy.size()) {
      mProcessedTaskUnits.push(queueCopy.front());
      queueCopy.pop();
    }
  }
}
コード例 #21
0
void CaelumEnvironment::createFirmament()
{
	try {
		setupCaelum(mSceneMgr, mWindow, mCamera);
	} catch (const std::exception& ex) {
		S_LOG_FAILURE("Could not load Caelum." << ex);
		throw;
	}
}
コード例 #22
0
ファイル: TimeImpl.cpp プロジェクト: jekin-worldforge/ember
void TimeImpl::createCalendar(Eris::Avatar* avatar)
{
	try {
		mCalendar = std::auto_ptr<Eris::Calendar>(new Eris::Calendar(avatar));
	} catch (const std::exception& ex) {
		S_LOG_FAILURE("Error when creating calendar object." << ex);
		mCalendar.release();
	}
}
コード例 #23
0
ファイル: TerrainArea.cpp プロジェクト: Arsakes/ember
bool TerrainArea::parseArea()
{
	if (!mEntity.hasAttr("area")) {
		S_LOG_FAILURE("TerrainArea created for entity with no area attribute");
		return false;
	}

	const Atlas::Message::Element areaElem(mEntity.valueOfAttr("area"));

	if (!areaElem.isMap()) {
		S_LOG_FAILURE("TerrainArea element ('area') must be of map type.");
		return false;
	}

	const Atlas::Message::MapType& areaData(areaElem.asMap());

	int layer = 0;
	WFMath::Polygon<2> poly;
	TerrainAreaParser parser;
	if (parser.parseArea(areaData, poly, layer)) {
		if (!mArea) {
			mArea = new Mercator::Area(layer, false);
		} else {
			//A bit of an ugly hack here since the Mercator system doesn't support changing the layer. We need to swap the old area for a new one if the layer has changed.
			if (mArea->getLayer() != layer) {
				mOldArea = mArea;
				mArea = new Mercator::Area(layer, false);
			}
		}
		// transform polygon into terrain coords
		WFMath::Vector<3> xVec = WFMath::Vector<3>(1.0, 0.0, 0.0).rotate(mEntity.getOrientation());
		double theta = atan2(xVec.y(), xVec.x()); // rotation about Z

		WFMath::RotMatrix<2> rm;
		poly.rotatePoint(rm.rotation(theta), WFMath::Point<2>(0, 0));
		poly.shift(WFMath::Vector<2>(mEntity.getPosition().x(), mEntity.getPosition().y()));

		mArea->setShape(poly);

		return true;
	} else {
		return false;
	}
}
コード例 #24
0
ファイル: TaskQueue.cpp プロジェクト: angkorcn/ember
void TaskQueue::pollProcessedTasks(TimeFrame timeFrame)
{
	TaskUnitQueue processedCopy;
	{
		std::unique_lock<std::mutex> l(mProcessedQueueMutex);
		processedCopy = mProcessedTaskUnits;
		if (!mProcessedTaskUnits.empty()) {
			mProcessedTaskUnits = TaskUnitQueue();
		}
	}
	while (!processedCopy.empty()) {

		TaskUnit* taskUnit = processedCopy.front();
		processedCopy.pop();
		try {
			taskUnit->executeInMainThread();
		} catch (const std::exception& ex) {
			S_LOG_FAILURE("Error when executing task in main thread." << ex);
		} catch (...) {
			S_LOG_FAILURE("Unknown error when executing task in main thread.");
		}
		try {
			delete taskUnit;
		} catch (const std::exception& ex) {
			S_LOG_FAILURE("Error when deleting task in main thread." << ex);
		} catch (...) {
			S_LOG_FAILURE("Unknown error when deleting task in main thread.");
		}
		//Try to keep the time spent here each frame down, to keep the framerate up.
		if (!timeFrame.isTimeLeft()) {
			break;
		}
	}
	//If there are any unprocessed tasks, put them back at the front of the queue.
	if (!processedCopy.empty()) {
		std::unique_lock<std::mutex> l(mProcessedQueueMutex);
		TaskUnitQueue queueCopy(mProcessedTaskUnits);
		mProcessedTaskUnits = processedCopy;
		while (!queueCopy.empty()) {
			mProcessedTaskUnits.push(queueCopy.front());
			queueCopy.pop();
		}
	}
}
コード例 #25
0
ファイル: SimpleRenderContext.cpp プロジェクト: bregma/ember
void SimpleRenderContextResourceLoader::loadResource(Ogre::Resource *resource)
{
    if (resource->getLoadingState() == Ogre::Resource::LOADSTATE_UNLOADED) {
        try {
            mRenderContext.getRenderTexture()->update();
        } catch (const std::exception& ex) {
            S_LOG_FAILURE("Error when updating render for SimpleRenderContext, after the resource has been reloaded." << ex);
        }
    }
}
コード例 #26
0
void MovableObjectRenderer::updateRender()
{
	try {
		if (mTexture->getRenderContext()->getRenderTexture()) {
			mTexture->getRenderContext()->getRenderTexture()->update();
		}
	} catch (const std::exception& ex) {
		S_LOG_FAILURE("Error when updating render for MovableObjectRenderer." << ex);
	}
}
コード例 #27
0
ファイル: Application.cpp プロジェクト: LawrenceWeng/ember
void Application::startScripting()
{
	//this should be defined in some kind of text file, which should be different depending on what game you're playing (like deeds)
	try {
		//load the bootstrap script which will load all other scripts
		mServices->getScriptingService().loadScript("lua/Bootstrap.lua");
	} catch (const std::exception& e) {
		S_LOG_FAILURE("Error when loading bootstrap script." << e);
	}

	//load any user defined scripts
	const std::string userScriptDirectoryPath = mServices->getConfigService().getHomeDirectory() + "/scripts";
	oslink::directory scriptDir(userScriptDirectoryPath);
	if (scriptDir.isExisting()) {
		static const std::string luaSuffix = ".lua";
		std::list<std::string> luaFiles;
		while (scriptDir) {
			std::string fileName = scriptDir.next();
			if (fileName != "." && fileName != "..") {
				std::string lowerCaseFileName = fileName;
				std::transform(lowerCaseFileName.begin(), lowerCaseFileName.end(), lowerCaseFileName.begin(), ::tolower);

				if (lowerCaseFileName.compare(lowerCaseFileName.length() - luaSuffix.length(), luaSuffix.length(), luaSuffix) == 0) {
					luaFiles.push_back(fileName);
				}

			}
		}

		//Sorting, because we want to load the scripts in a deterministic order.
		luaFiles.sort();
		for (auto& fileName : luaFiles) {
			std::ifstream stream(userScriptDirectoryPath + "/" + fileName, std::ios::in);
			if (stream) {
				std::stringstream ss;
				ss << stream.rdbuf();
				stream.close();
				//It's important that we inform the user that we're loading a script (in case it provides any confusing behaviour).
				ConsoleBackend::getSingleton().pushMessage("Loading user Lua script from '" + fileName + "'.", "info");
				mServices->getScriptingService().executeCode(ss.str(), "LuaScriptingProvider");
			}
		}
	} else {
		try {
			//Create the script user script directory
			oslink::directory::mkdir(userScriptDirectoryPath.c_str());
			std::ofstream readme(userScriptDirectoryPath + "/README", std::ios::out);
			readme << "Any script files placed here will be executed as long as they have a supported file suffix.\nScripts are executed in alphabetical order.\nEmber currently supports lua scripts (ending with '.lua').";
			readme.close();
			S_LOG_INFO("Created user user scripting directory (" + userScriptDirectoryPath + ").");
		} catch (const std::exception& e) {
			S_LOG_INFO("Could not create user scripting directory.");
		}
	}
}
コード例 #28
0
ファイル: PolygonAdapter.cpp プロジェクト: Laefy/ember
void PolygonAdapter::toggleDisplayOfPolygon()
{
	if (!mPolygon) {
		if (!mEntity) {
			S_LOG_WARNING("There's no entity attached to the PolygonAdapter, and the polygon can't thus be shown.");
		} else {
			//It's important that we do the call to getChangedElement before we create and set mPolygon, since if that's set, the values from there will be used instead of the original atlas values.
			::Atlas::Message::Element areaElem(getChangedElement());

			Ogre::SceneNode* entitySceneNode = getEntitySceneNode();
			if (entitySceneNode) {
				if (areaElem.isMap()) {
					try {
						WFMath::Polygon<2> poly(areaElem);
						createNewPolygon(&poly);
					} catch (const WFMath::_AtlasBadParse& ex) {
						createNewPolygon(0);
					}
				} else {
					createNewPolygon(0);
				}

			}
		}
	} else {
		if (mPickListener) {
			EmberOgre::getSingleton().getWorld()->getMainCamera().removeWorldPickListener(mPickListener);
			try {
				delete mPickListener;
			} catch (const std::exception& ex) {
				S_LOG_FAILURE("Error when deleting polygon point pick listener.");
			}
			mPickListener = 0;
		}
		try {
			delete mPolygon;
		} catch (const std::exception& ex) {
			S_LOG_FAILURE("Error when deleting polygon.");
		}
		mPolygon = 0;
	}
}
コード例 #29
0
void ShadowCameraSetup::Config_ShadowFarDistance(const std::string& section, const std::string& key, varconf::Variable& variable)
{
	try {
		if (variable.is_double()) {
			S_LOG_VERBOSE("Setting shadow far distance: " << static_cast<double>(variable));
			mSceneMgr.setShadowFarDistance(static_cast<double>(variable));
		}
	} catch (const std::exception& ex) {
		S_LOG_FAILURE("Error when setting shadow far distance." << ex);
	}
}
コード例 #30
0
void ShadowCameraSetup::Config_ShadowTextureSize(const std::string& section, const std::string& key, varconf::Variable& variable)
{
	try {
		if (variable.is_int()) {
			S_LOG_VERBOSE("Setting shadow texture size: " << static_cast<int>(variable));
			mSceneMgr.setShadowTextureSize(static_cast<int>(variable));
		}
	} catch (const std::exception& ex) {
		S_LOG_FAILURE("Error when setting shadow texture size." << ex);
	}
}