text
stringlengths
54
60.6k
<commit_before>// ------------------------------------------------------------------------- // @FileName : NFCTileModule.cpp // @Author : LvSheng.Huang // @Date : 2017-02-25 // @Module : NFCTileModule // // ------------------------------------------------------------------------- #include "NFCTileModule.h" #include "NFComm/NFMessageDefine/NFProtocolDefine.hpp" bool NFCTileModule::Init() { m_pNetModule = pPluginManager->FindModule<NFINetModule>(); m_pBigMapRedisModule = pPluginManager->FindModule<NFIBigMapRedisModule>(); m_pKernelModule = pPluginManager->FindModule<NFIKernelModule>(); m_pLogicClassModule = pPluginManager->FindModule<NFIClassModule>(); m_pElementModule = pPluginManager->FindModule<NFIElementModule>(); m_pGuildRedisModule = pPluginManager->FindModule<NFIGuildRedisModule>(); m_pGameServerNet_ServerModule = pPluginManager->FindModule<NFIGameServerNet_ServerModule>(); m_pPlayerRedisModule = pPluginManager->FindModule<NFIPlayerRedisModule>(); return true; } bool NFCTileModule::Shut() { return true; } bool NFCTileModule::Execute() { return true; } bool NFCTileModule::AfterInit() { m_pKernelModule->AddClassCallBack(NFrame::Player::ThisName(), this, &NFCTileModule::OnObjectClassEvent); if (!m_pNetModule->AddReceiveCallBack(NFMsg::EGameMsgID::EGEC_REQ_MINING_TITLE, this, &NFCTileModule::ReqMineTile)) { return false; } return true; } bool NFCTileModule::GetOnlinePlayerTileData(const NFGUID& self, std::string& strData) { NF_SHARE_PTR<TileData> xTileData = mxTileData.GetElement(self); if (!xTileData) { return false; } NFMsg::AckMiningTitle xData; NF_SHARE_PTR<NFMapEx<int, TileState>> xStateDataMap = xTileData->mxTileState.First(); for (; xStateDataMap; xStateDataMap = xTileData->mxTileState.Next()) { NF_SHARE_PTR<TileState> xStateData = xStateDataMap->First(); for (; xStateData; xStateData = xStateDataMap->Next()) { //pb //xStateData NFMsg::TileState* pTile = xData.add_tile(); if (pTile) { pTile->set_x(xStateData->x); pTile->set_y(xStateData->y); pTile->set_opr(xStateData->state); } } } if (xData.SerializeToString(&strData)) { return true; } return false; } void NFCTileModule::ReqMineTile(const int nSockIndex, const int nMsgID, const char * msg, const uint32_t nLen) { CLIENT_MSG_PROCESS(nSockIndex, nMsgID, msg, nLen, NFMsg::ReqMiningTitle); int nX = xMsg.x(); int nY = xMsg.y(); int nOpr = xMsg.opr(); if (1 == nOpr)//add { ////consume diamond AddTile(nPlayerID, nX, nY, nOpr); } else if (0 == nOpr)//rem { //get money AddTile(nPlayerID, nX, nY, nOpr); } NFMsg::AckMiningTitle xData; NFMsg::TileState* pTile = xData.add_tile(); if (pTile) { pTile->set_x(nX); pTile->set_y(nY); pTile->set_opr(nOpr); } SaveTileData(nPlayerID); m_pGameServerNet_ServerModule->SendMsgPBToGate(NFMsg::EGEC_ACK_MINING_TITLE, xData, nPlayerID); } bool NFCTileModule::AddTile(const NFGUID & self, const int nX, const int nY, const int nOpr) { NF_SHARE_PTR<TileData> xTileData = mxTileData.GetElement(self); if (!xTileData) { xTileData = NF_SHARE_PTR<TileData>(NF_NEW TileData()); mxTileData.AddElement(self, xTileData); } NF_SHARE_PTR<NFMapEx<int, TileState>> xStateDataMap = xTileData->mxTileState.GetElement(nX); if (!xStateDataMap) { xStateDataMap = NF_SHARE_PTR<NFMapEx<int, TileState>>(NF_NEW NFMapEx<int, TileState>()); xTileData->mxTileState.AddElement(nX, xStateDataMap); } NF_SHARE_PTR<TileState> xTileState = xStateDataMap->GetElement(nY); if (!xTileState) { xTileState = NF_SHARE_PTR<TileState>(NF_NEW TileState()); xStateDataMap->AddElement(nY, xTileState); } else { if (nOpr == xTileState->state) { //has be deleted return false; } } xTileState->x = nX; xTileState->y = nY; xTileState->state = nOpr; //save //SaveTileData(self); return true; } bool NFCTileModule::RemoveTile(const NFGUID & self, const int nX, const int nY) { NF_SHARE_PTR<TileData> xTileData = mxTileData.GetElement(self); if (!xTileData) { return false; } NF_SHARE_PTR<NFMapEx<int, TileState>> xStateDataMap = xTileData->mxTileState.GetElement(nX); if (!xStateDataMap) { return false; } if (xStateDataMap->ExistElement(nY)) { xStateDataMap->RemoveElement(nY); //save SaveTileData(self); return true; } return false; } bool NFCTileModule::SaveTileData(const NFGUID & self) { NF_SHARE_PTR<TileData> xTileData = mxTileData.GetElement(self); if (!xTileData) { return false; } NFMsg::AckMiningTitle xData; NF_SHARE_PTR<NFMapEx<int, TileState>> xStateDataMap = xTileData->mxTileState.First(); for (; xStateDataMap; xStateDataMap = xTileData->mxTileState.Next()) { NF_SHARE_PTR<TileState> xStateData = xStateDataMap->First(); for (; xStateData; xStateData = xStateDataMap->Next()) { //pb //xStateData NFMsg::TileState* pTile = xData.add_tile(); if (pTile) { pTile->set_x(xStateData->x); pTile->set_y(xStateData->y); pTile->set_opr(xStateData->state); } } } const int nSceneID = m_pKernelModule->GetPropertyInt(self, NFrame::Player::HomeSceneID()); std::string strData; if (xData.SerializeToString(&strData)) { return m_pPlayerRedisModule->SavePlayerTile(nSceneID, self, strData); } return false; } bool NFCTileModule::LoadTileData(const NFGUID & self) { const int nSceneID = m_pKernelModule->GetPropertyInt(self, NFrame::Player::HomeSceneID()); LoadTileData(self, nSceneID); return false; } bool NFCTileModule::LoadTileData(const NFGUID & self, const int nSceneID) { mxTileData.RemoveElement(self); std::string strData; if (m_pPlayerRedisModule->LoadPlayerTile(nSceneID, self, strData)) { NFMsg::AckMiningTitle xData; if (xData.ParseFromString(strData)) { int nCount = xData.tile_size(); for (int i = 0; i < nCount; ++i) { const NFMsg::TileState& xTile = xData.tile(i); AddTile(self, xTile.x(), xTile.y(), xTile.opr()); } return true; } } return false; } bool NFCTileModule::SendTileData(const NFGUID & self) { NF_SHARE_PTR<TileData> xTileData = mxTileData.GetElement(self); if (!xTileData) { return false; } bool bNeedSend = false; NFMsg::AckMiningTitle xData; NF_SHARE_PTR<NFMapEx<int, TileState>> xStateDataMap = xTileData->mxTileState.First(); for (; xStateDataMap; xStateDataMap = xTileData->mxTileState.Next()) { NF_SHARE_PTR<TileState> xStateData = xStateDataMap->First(); for (; xStateData; xStateData = xStateDataMap->Next()) { //pb //xStateData NFMsg::TileState* pTile = xData.add_tile(); if (pTile) { bNeedSend = true; pTile->set_x(xStateData->x); pTile->set_y(xStateData->y); pTile->set_opr(xStateData->state); } } } if (bNeedSend) { m_pGameServerNet_ServerModule->SendMsgPBToGate(NFMsg::EGEC_ACK_MINING_TITLE, xData, self); } } int NFCTileModule::OnObjectClassEvent(const NFGUID & self, const std::string & strClassName, const CLASS_OBJECT_EVENT eClassEvent, const NFDataList & var) { if (CLASS_OBJECT_EVENT::COE_DESTROY == eClassEvent) { //cannot save tile here, because player maybe offline in other people scene } else if (CLASS_OBJECT_EVENT::COE_CREATE_BEFORE_EFFECT == eClassEvent) { //preload at first, then attach LoadTileData(self); } else if (CLASS_OBJECT_EVENT::COE_CREATE_CLIENT_FINISH == eClassEvent) { //load SendTileData(self); } return 0; } <commit_msg>cannot delete a tile when you in a map which belong to the other people<commit_after>// ------------------------------------------------------------------------- // @FileName : NFCTileModule.cpp // @Author : LvSheng.Huang // @Date : 2017-02-25 // @Module : NFCTileModule // // ------------------------------------------------------------------------- #include "NFCTileModule.h" #include "NFComm/NFMessageDefine/NFProtocolDefine.hpp" bool NFCTileModule::Init() { m_pNetModule = pPluginManager->FindModule<NFINetModule>(); m_pBigMapRedisModule = pPluginManager->FindModule<NFIBigMapRedisModule>(); m_pKernelModule = pPluginManager->FindModule<NFIKernelModule>(); m_pLogicClassModule = pPluginManager->FindModule<NFIClassModule>(); m_pElementModule = pPluginManager->FindModule<NFIElementModule>(); m_pGuildRedisModule = pPluginManager->FindModule<NFIGuildRedisModule>(); m_pGameServerNet_ServerModule = pPluginManager->FindModule<NFIGameServerNet_ServerModule>(); m_pPlayerRedisModule = pPluginManager->FindModule<NFIPlayerRedisModule>(); return true; } bool NFCTileModule::Shut() { return true; } bool NFCTileModule::Execute() { return true; } bool NFCTileModule::AfterInit() { m_pKernelModule->AddClassCallBack(NFrame::Player::ThisName(), this, &NFCTileModule::OnObjectClassEvent); if (!m_pNetModule->AddReceiveCallBack(NFMsg::EGameMsgID::EGEC_REQ_MINING_TITLE, this, &NFCTileModule::ReqMineTile)) { return false; } return true; } bool NFCTileModule::GetOnlinePlayerTileData(const NFGUID& self, std::string& strData) { NF_SHARE_PTR<TileData> xTileData = mxTileData.GetElement(self); if (!xTileData) { return false; } NFMsg::AckMiningTitle xData; NF_SHARE_PTR<NFMapEx<int, TileState>> xStateDataMap = xTileData->mxTileState.First(); for (; xStateDataMap; xStateDataMap = xTileData->mxTileState.Next()) { NF_SHARE_PTR<TileState> xStateData = xStateDataMap->First(); for (; xStateData; xStateData = xStateDataMap->Next()) { //pb //xStateData NFMsg::TileState* pTile = xData.add_tile(); if (pTile) { pTile->set_x(xStateData->x); pTile->set_y(xStateData->y); pTile->set_opr(xStateData->state); } } } if (xData.SerializeToString(&strData)) { return true; } return false; } void NFCTileModule::ReqMineTile(const int nSockIndex, const int nMsgID, const char * msg, const uint32_t nLen) { CLIENT_MSG_PROCESS(nSockIndex, nMsgID, msg, nLen, NFMsg::ReqMiningTitle); NFGUID xViewOppnentID = m_pKernelModule->GetPropertyObject(nPlayerID, NFrame::Player::ViewOppnent()); NFGUID xFightOppnentID = m_pKernelModule->GetPropertyObject(nPlayerID, NFrame::Player::FightOppnent()); if (!xViewOppnentID.IsNull() || !xFightOppnentID.IsNull()) { return; } int nX = xMsg.x(); int nY = xMsg.y(); int nOpr = xMsg.opr(); if (1 == nOpr)//add { ////consume diamond AddTile(nPlayerID, nX, nY, nOpr); } else if (0 == nOpr)//rem { //get money AddTile(nPlayerID, nX, nY, nOpr); } NFMsg::AckMiningTitle xData; NFMsg::TileState* pTile = xData.add_tile(); if (pTile) { pTile->set_x(nX); pTile->set_y(nY); pTile->set_opr(nOpr); } SaveTileData(nPlayerID); m_pGameServerNet_ServerModule->SendMsgPBToGate(NFMsg::EGEC_ACK_MINING_TITLE, xData, nPlayerID); } bool NFCTileModule::AddTile(const NFGUID & self, const int nX, const int nY, const int nOpr) { NF_SHARE_PTR<TileData> xTileData = mxTileData.GetElement(self); if (!xTileData) { xTileData = NF_SHARE_PTR<TileData>(NF_NEW TileData()); mxTileData.AddElement(self, xTileData); } NF_SHARE_PTR<NFMapEx<int, TileState>> xStateDataMap = xTileData->mxTileState.GetElement(nX); if (!xStateDataMap) { xStateDataMap = NF_SHARE_PTR<NFMapEx<int, TileState>>(NF_NEW NFMapEx<int, TileState>()); xTileData->mxTileState.AddElement(nX, xStateDataMap); } NF_SHARE_PTR<TileState> xTileState = xStateDataMap->GetElement(nY); if (!xTileState) { xTileState = NF_SHARE_PTR<TileState>(NF_NEW TileState()); xStateDataMap->AddElement(nY, xTileState); } else { if (nOpr == xTileState->state) { //has be deleted return false; } } xTileState->x = nX; xTileState->y = nY; xTileState->state = nOpr; //save //SaveTileData(self); return true; } bool NFCTileModule::RemoveTile(const NFGUID & self, const int nX, const int nY) { NF_SHARE_PTR<TileData> xTileData = mxTileData.GetElement(self); if (!xTileData) { return false; } NF_SHARE_PTR<NFMapEx<int, TileState>> xStateDataMap = xTileData->mxTileState.GetElement(nX); if (!xStateDataMap) { return false; } if (xStateDataMap->ExistElement(nY)) { xStateDataMap->RemoveElement(nY); //save SaveTileData(self); return true; } return false; } bool NFCTileModule::SaveTileData(const NFGUID & self) { NF_SHARE_PTR<TileData> xTileData = mxTileData.GetElement(self); if (!xTileData) { return false; } NFMsg::AckMiningTitle xData; NF_SHARE_PTR<NFMapEx<int, TileState>> xStateDataMap = xTileData->mxTileState.First(); for (; xStateDataMap; xStateDataMap = xTileData->mxTileState.Next()) { NF_SHARE_PTR<TileState> xStateData = xStateDataMap->First(); for (; xStateData; xStateData = xStateDataMap->Next()) { //pb //xStateData NFMsg::TileState* pTile = xData.add_tile(); if (pTile) { pTile->set_x(xStateData->x); pTile->set_y(xStateData->y); pTile->set_opr(xStateData->state); } } } const int nSceneID = m_pKernelModule->GetPropertyInt(self, NFrame::Player::HomeSceneID()); std::string strData; if (xData.SerializeToString(&strData)) { return m_pPlayerRedisModule->SavePlayerTile(nSceneID, self, strData); } return false; } bool NFCTileModule::LoadTileData(const NFGUID & self) { const int nSceneID = m_pKernelModule->GetPropertyInt(self, NFrame::Player::HomeSceneID()); LoadTileData(self, nSceneID); return false; } bool NFCTileModule::LoadTileData(const NFGUID & self, const int nSceneID) { mxTileData.RemoveElement(self); std::string strData; if (m_pPlayerRedisModule->LoadPlayerTile(nSceneID, self, strData)) { NFMsg::AckMiningTitle xData; if (xData.ParseFromString(strData)) { int nCount = xData.tile_size(); for (int i = 0; i < nCount; ++i) { const NFMsg::TileState& xTile = xData.tile(i); AddTile(self, xTile.x(), xTile.y(), xTile.opr()); } return true; } } return false; } bool NFCTileModule::SendTileData(const NFGUID & self) { NF_SHARE_PTR<TileData> xTileData = mxTileData.GetElement(self); if (!xTileData) { return false; } bool bNeedSend = false; NFMsg::AckMiningTitle xData; NF_SHARE_PTR<NFMapEx<int, TileState>> xStateDataMap = xTileData->mxTileState.First(); for (; xStateDataMap; xStateDataMap = xTileData->mxTileState.Next()) { NF_SHARE_PTR<TileState> xStateData = xStateDataMap->First(); for (; xStateData; xStateData = xStateDataMap->Next()) { //pb //xStateData NFMsg::TileState* pTile = xData.add_tile(); if (pTile) { bNeedSend = true; pTile->set_x(xStateData->x); pTile->set_y(xStateData->y); pTile->set_opr(xStateData->state); } } } if (bNeedSend) { m_pGameServerNet_ServerModule->SendMsgPBToGate(NFMsg::EGEC_ACK_MINING_TITLE, xData, self); } } int NFCTileModule::OnObjectClassEvent(const NFGUID & self, const std::string & strClassName, const CLASS_OBJECT_EVENT eClassEvent, const NFDataList & var) { if (CLASS_OBJECT_EVENT::COE_DESTROY == eClassEvent) { //cannot save tile here, because player maybe offline in other people scene } else if (CLASS_OBJECT_EVENT::COE_CREATE_BEFORE_EFFECT == eClassEvent) { //preload at first, then attach LoadTileData(self); } else if (CLASS_OBJECT_EVENT::COE_CREATE_CLIENT_FINISH == eClassEvent) { //load SendTileData(self); } return 0; } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////// // DESCRIPTION: // // Produces the MEL command "scanDag". // // This plug-in demonstrates walking the DAG using the DAG iterator class. // // To use it: // (1) Create a number of objects anywhere in the scene. // (2) Execute the command "scanDag". This will traverse the DAG printing // information about each node it finds to the window from which you // started Maya. // // The command accepts several flags: // // -b/-breadthFirst : Perform breadth first search // -d/-depthFirst : Perform depth first search // //////////////////////////////////////////////////////////////////////// #include <maya/MFnDagNode.h> #include <maya/MItDag.h> #include <maya/MObject.h> #include <maya/MDagPath.h> #include <maya/MPxCommand.h> #include <maya/MStatus.h> #include <maya/MString.h> #include <maya/MFnPlugin.h> #include <maya/MFnMesh.h> #include <maya/MArgList.h> #include <maya/MFnCamera.h> #include <maya/MPoint.h> #include <maya/MVector.h> #include <maya/MMatrix.h> #include <maya/MTransformationMatrix.h> #include <maya/MFnLight.h> #include <maya/MColor.h> #include <maya/MFnNurbsSurface.h> #include <maya/MIOStream.h> #include <maya/MPlugArray.h> class scanDag : public MPxCommand { public: scanDag() {}; virtual ~scanDag(); static void* creator(); virtual MStatus doIt(const MArgList&); private: MStatus parseArgs(const MArgList& args, MItDag::TraversalType& traversalType); MStatus doScan(const MItDag::TraversalType traversalType); void findHistory(MString& string, MFnDependencyNode& node); }; scanDag::~scanDag() {} void* scanDag::creator() { return new scanDag; } MStatus scanDag::doIt(const MArgList& args) { MItDag::TraversalType traversalType = MItDag::kDepthFirst; MFn::Type filter = MFn::kInvalid; MStatus status; status = parseArgs(args, traversalType); if (!status) return status; return doScan(traversalType); }; void scanDag::findHistory( MString& string, MFnDependencyNode& node) { // If the inpuPolymesh is connected, we have history MPlug inMeshPlug = node.findPlug("inputPolymesh"); if (inMeshPlug.isConnected()) { MPlugArray tempPlugArray; inMeshPlug.connectedTo(tempPlugArray, true, false); // Only one connection should exist on meshNodeShape.inMesh! MPlug upstreamNodeSrcPlug = tempPlugArray[0]; MFnDependencyNode upstreamNode(upstreamNodeSrcPlug.node()); // testing strings string += "\n"; string += upstreamNode.typeName(); string += " | "; string += upstreamNode.name(); findHistory(string, upstreamNode); } } MStatus scanDag::parseArgs(const MArgList& args, MItDag::TraversalType& traversalType) { MStatus stat; MString arg; const MString breadthFlag("-b"); const MString breadthFlagLong("-breadthFirst"); const MString depthFlag("-d"); const MString depthFlagLong("-depthFirst"); // Parse the arguments. for (unsigned int i = 0; i < args.length(); i++) { arg = args.asString(i, &stat); if (!stat) continue; if (arg == breadthFlag || arg == breadthFlagLong) traversalType = MItDag::kBreadthFirst; else if (arg == depthFlag || arg == depthFlagLong) traversalType = MItDag::kDepthFirst; else { arg += ": unknown argument"; displayError(arg); return MS::kFailure; } } return stat; } MStatus scanDag::doScan(const MItDag::TraversalType traversalType) { MStatus status; MItDag dagIterator(traversalType, MFn::kMesh, &status); if (!status) { status.perror("MItDag constructor"); return status; } MString resultString; for (; !dagIterator.isDone(); dagIterator.next()) { MDagPath dagPath; status = dagIterator.getPath(dagPath); if (!status) { status.perror("MItDag::getPath"); continue; } MFnDagNode dagNode(dagPath, &status); if (!status) { status.perror("MFnDagNode constructor"); continue; } bool fHasTweaks = false; dagPath.extendToShape(); MObject meshNodeShape = dagPath.node(); MFnDependencyNode depNodeFn(meshNodeShape); // If the inMesh is connected, we have history MString historyString; MPlug inMeshPlug = depNodeFn.findPlug("inMesh"); if (inMeshPlug.isConnected()) { MPlugArray tempPlugArray; inMeshPlug.connectedTo(tempPlugArray, true, false); MPlug upstreamNodeSrcPlug = tempPlugArray[0]; MFnDependencyNode upstreamNode(upstreamNodeSrcPlug.node()); historyString += "\n"; historyString += upstreamNode.typeName(); historyString += " | "; historyString += upstreamNode.name(); findHistory(historyString, upstreamNode); } // Tweaks exist only if the multi "pnts" attribute contains // plugs that contain non-zero tweak values. Use false, // until proven true search pattern. MPlug tweakPlug = depNodeFn.findPlug("pnts"); if (!tweakPlug.isNull()) { // ASSERT : tweakPlug should be an array plug //MAssert(tweakPlug.isArray(), "tweakPlug.isArray()"); MPlug tweak; MFloatVector tweakData; int i; int numElements = tweakPlug.numElements(); for (i = 0; i < numElements; i++) { tweak = tweakPlug.elementByPhysicalIndex(i, &status); if (status == MS::kSuccess && !tweak.isNull()) { fHasTweaks = true; break; } } } MFnMesh mesh(meshNodeShape); if (!status) { status.perror("MFnMesh:constructor"); continue; } resultString += ("\n Shape: " + mesh.name()); resultString += "\n history: "; resultString += historyString; if(fHasTweaks) resultString += ("\n tweaks: true"); else resultString += ("\n tweaks: false"); } setResult(resultString); return MS::kSuccess; } MStatus initializePlugin(MObject obj) { MStatus status; MFnPlugin plugin(obj, PLUGIN_COMPANY, "3.0", "Any"); status = plugin.registerCommand("scanDag", scanDag::creator); if (!status) status.perror("registerCommand"); return status; } MStatus uninitializePlugin(MObject obj) { MStatus status; MFnPlugin plugin(obj); status = plugin.deregisterCommand("scanDag"); if (!status) status.perror("deregisterCommand"); return status; } <commit_msg>added a status that was needed<commit_after>//////////////////////////////////////////////////////////////////////// // DESCRIPTION: // // Produces the MEL command "scanDag". // // This plug-in demonstrates walking the DAG using the DAG iterator class. // // To use it: // (1) Create a number of objects anywhere in the scene. // (2) Execute the command "scanDag". This will traverse the DAG printing // information about each node it finds to the window from which you // started Maya. // // The command accepts several flags: // // -b/-breadthFirst : Perform breadth first search // -d/-depthFirst : Perform depth first search // //////////////////////////////////////////////////////////////////////// #include <maya/MFnDagNode.h> #include <maya/MItDag.h> #include <maya/MObject.h> #include <maya/MDagPath.h> #include <maya/MPxCommand.h> #include <maya/MStatus.h> #include <maya/MString.h> #include <maya/MFnPlugin.h> #include <maya/MFnMesh.h> #include <maya/MArgList.h> #include <maya/MFnCamera.h> #include <maya/MPoint.h> #include <maya/MVector.h> #include <maya/MMatrix.h> #include <maya/MTransformationMatrix.h> #include <maya/MFnLight.h> #include <maya/MColor.h> #include <maya/MFnNurbsSurface.h> #include <maya/MIOStream.h> #include <maya/MPlugArray.h> class scanDag : public MPxCommand { public: scanDag() {}; virtual ~scanDag(); static void* creator(); virtual MStatus doIt(const MArgList&); private: MStatus parseArgs(const MArgList& args, MItDag::TraversalType& traversalType); MStatus doScan(const MItDag::TraversalType traversalType); void findHistory(MString& string, MFnDependencyNode& node); }; scanDag::~scanDag() {} void* scanDag::creator() { return new scanDag; } MStatus scanDag::doIt(const MArgList& args) { MItDag::TraversalType traversalType = MItDag::kDepthFirst; MFn::Type filter = MFn::kInvalid; MStatus status; status = parseArgs(args, traversalType); if (!status) return status; return doScan(traversalType); }; void scanDag::findHistory( MString& string, MFnDependencyNode& node) { // If the inpuPolymesh is connected, we have history MPlug inMeshPlug = node.findPlug("inputPolymesh"); if (inMeshPlug.isConnected()) { MPlugArray tempPlugArray; inMeshPlug.connectedTo(tempPlugArray, true, false); // Only one connection should exist on meshNodeShape.inMesh! MPlug upstreamNodeSrcPlug = tempPlugArray[0]; MFnDependencyNode upstreamNode(upstreamNodeSrcPlug.node()); // testing strings string += "\n"; string += upstreamNode.typeName(); string += " | "; string += upstreamNode.name(); findHistory(string, upstreamNode); } } MStatus scanDag::parseArgs(const MArgList& args, MItDag::TraversalType& traversalType) { MStatus stat; MString arg; const MString breadthFlag("-b"); const MString breadthFlagLong("-breadthFirst"); const MString depthFlag("-d"); const MString depthFlagLong("-depthFirst"); // Parse the arguments. for (unsigned int i = 0; i < args.length(); i++) { arg = args.asString(i, &stat); if (!stat) continue; if (arg == breadthFlag || arg == breadthFlagLong) traversalType = MItDag::kBreadthFirst; else if (arg == depthFlag || arg == depthFlagLong) traversalType = MItDag::kDepthFirst; else { arg += ": unknown argument"; displayError(arg); return MS::kFailure; } } return stat; } MStatus scanDag::doScan(const MItDag::TraversalType traversalType) { MStatus status; MItDag dagIterator(traversalType, MFn::kMesh, &status); if (!status) { status.perror("MItDag constructor"); return status; } MString resultString; for (; !dagIterator.isDone(); dagIterator.next()) { MDagPath dagPath; status = dagIterator.getPath(dagPath); if (!status) { status.perror("MItDag::getPath"); continue; } MFnDagNode dagNode(dagPath, &status); if (!status) { status.perror("MFnDagNode constructor"); continue; } bool fHasTweaks = false; dagPath.extendToShape(); MObject meshNodeShape = dagPath.node(); MFnDependencyNode depNodeFn(meshNodeShape); // If the inMesh is connected, we have history MString historyString; MPlug inMeshPlug = depNodeFn.findPlug("inMesh"); if (inMeshPlug.isConnected()) { MPlugArray tempPlugArray; inMeshPlug.connectedTo(tempPlugArray, true, false); MPlug upstreamNodeSrcPlug = tempPlugArray[0]; MFnDependencyNode upstreamNode(upstreamNodeSrcPlug.node()); historyString += "\n"; historyString += upstreamNode.typeName(); historyString += " | "; historyString += upstreamNode.name(); findHistory(historyString, upstreamNode); } // Tweaks exist only if the multi "pnts" attribute contains // plugs that contain non-zero tweak values. Use false, // until proven true search pattern. MPlug tweakPlug = depNodeFn.findPlug("pnts"); if (!tweakPlug.isNull()) { // ASSERT : tweakPlug should be an array plug //MAssert(tweakPlug.isArray(), "tweakPlug.isArray()"); MPlug tweak; MFloatVector tweakData; int i; int numElements = tweakPlug.numElements(); for (i = 0; i < numElements; i++) { tweak = tweakPlug.elementByPhysicalIndex(i, &status); if (status == MS::kSuccess && !tweak.isNull()) { fHasTweaks = true; break; } } } MFnMesh mesh(meshNodeShape, &status); if (!status) { status.perror("MFnMesh:constructor"); continue; } resultString += ("\n Shape: " + mesh.name()); resultString += "\n history: "; resultString += historyString; if(fHasTweaks) resultString += ("\n tweaks: true"); else resultString += ("\n tweaks: false"); } setResult(resultString); return MS::kSuccess; } MStatus initializePlugin(MObject obj) { MStatus status; MFnPlugin plugin(obj, PLUGIN_COMPANY, "3.0", "Any"); status = plugin.registerCommand("scanDag", scanDag::creator); if (!status) status.perror("registerCommand"); return status; } MStatus uninitializePlugin(MObject obj) { MStatus status; MFnPlugin plugin(obj); status = plugin.deregisterCommand("scanDag"); if (!status) status.perror("deregisterCommand"); return status; } <|endoftext|>
<commit_before>#include "queueloader.h" #include <cerrno> #include <cstdlib> #include <cstdio> #include <cstring> #include <fstream> #include <iostream> #include <libgen.h> #include <unistd.h> #include "config.h" #include "configcontainer.h" #include "logger.h" #include "stflpp.h" #include "strprintf.h" #include "utils.h" using namespace newsboat; namespace podboat { QueueLoader::QueueLoader(const std::string& filepath, const ConfigContainer& cfg_, std::function<void()> cb_require_view_update_) : queuefile(filepath) , cfg(cfg_) , cb_require_view_update(cb_require_view_update_) { } void QueueLoader::reload(std::vector<Download>& downloads, bool also_remove_finished) const { CategorizedDownloads categorized_downloads; const auto res = categorize_downloads(downloads, also_remove_finished); if (!res.has_value()) { return; } categorized_downloads = res.value(); update_from_queue_file(categorized_downloads); write_queue_file(categorized_downloads); delete_played_files(categorized_downloads); downloads = std::move(categorized_downloads.to_keep); } nonstd::optional<QueueLoader::CategorizedDownloads> QueueLoader::categorize_downloads( const std::vector<Download>& downloads, bool also_remove_finished) { CategorizedDownloads result; for (const auto& dl : downloads) { // we are not allowed to reload if a download is in progress! if (dl.status() == DlStatus::DOWNLOADING) { LOG(Level::INFO, "QueueLoader::reload: aborting reload due to " "DlStatus::DOWNLOADING status"); return nonstd::nullopt; } bool keep_entry = false; switch (dl.status()) { case DlStatus::QUEUED: case DlStatus::CANCELLED: case DlStatus::FAILED: case DlStatus::ALREADY_DOWNLOADED: case DlStatus::READY: case DlStatus::PLAYED: LOG(Level::DEBUG, "QueueLoader::reload: storing %s to new vector", dl.url()); keep_entry = true; break; case DlStatus::FINISHED: if (!also_remove_finished) { LOG(Level::DEBUG, "QueueLoader::reload: storing %s to new vector", dl.url()); keep_entry = true; } break; case DlStatus::DELETED: keep_entry = false; break; case DlStatus::DOWNLOADING: assert(!"Can't be reached because of the `if` above"); break; } if (keep_entry) { result.to_keep.push_back(dl); } else { result.to_delete.push_back(dl); } } return result; } void QueueLoader::update_from_queue_file(CategorizedDownloads& downloads) const { std::fstream f(queuefile, std::fstream::in); if (!f.is_open()) { return; } bool comments_ignored = false; for (std::string line; std::getline(f, line); ) { if (line.empty()) { continue; } LOG(Level::DEBUG, "QueueLoader::reload: loaded `%s' from queue file", line); const std::vector<std::string> fields = utils::tokenize_quoted(line); bool url_found = false; if (fields.empty()) { if (!comments_ignored) { std::cout << strprintf::fmt( _("WARNING: Comment found " "in %s. The queue file is regenerated " "when podboat exits and comments will " "be deleted. Press Enter to continue or " "Ctrl+C to abort"), queuefile) << std::endl; std::cin.ignore(); comments_ignored = true; } continue; } for (const auto& dl : downloads.to_keep) { if (fields[0] == dl.url()) { LOG(Level::INFO, "QueueLoader::reload: found `%s' in old vector", fields[0]); url_found = true; break; } } for (const auto& dl : downloads.to_delete) { if (fields[0] == dl.url()) { LOG(Level::INFO, "QueueLoader::reload: found `%s' in scheduled for deletion vector", fields[0]); url_found = true; break; } } if (url_found) { continue; } LOG(Level::INFO, "QueueLoader::reload: found `%s' nowhere -> storing to new vector", line); Download d(cb_require_view_update); std::string fn; if (fields.size() == 1) { fn = get_filename(fields[0]); } else { fn = fields[1]; } d.set_filename(fn); if (access(fn.c_str(), F_OK) == 0) { LOG(Level::INFO, "QueueLoader::reload: found `%s' on file system -> mark as already downloaded", fn); if (fields.size() >= 3) { if (fields[2] == "downloaded") { d.set_status(DlStatus::READY); } if (fields[2] == "played") { d.set_status(DlStatus::PLAYED); } if (fields[2] == "finished") { d.set_status(DlStatus::FINISHED); } } else { // TODO: scrap DlStatus::ALREADY_DOWNLOADED state d.set_status(DlStatus::ALREADY_DOWNLOADED); } } else if (access((fn + ConfigContainer::PARTIAL_FILE_SUFFIX).c_str(), F_OK) == 0) { LOG(Level::INFO, "QueueLoader::reload: found `%s' on file system -> mark as partially downloaded", fn + ConfigContainer::PARTIAL_FILE_SUFFIX); d.set_status(DlStatus::ALREADY_DOWNLOADED); } d.set_url(fields[0]); downloads.to_keep.push_back(d); } } void QueueLoader::write_queue_file(const CategorizedDownloads& downloads) const { std::fstream f(queuefile, std::fstream::out); if (!f.is_open()) { return; } for (const auto& dl : downloads.to_keep) { f << dl.url() << " " << utils::quote(dl.filename()); switch (dl.status()) { case DlStatus::READY: f << " downloaded"; break; case DlStatus::PLAYED: f << " played"; break; case DlStatus::FINISHED: f << " finished"; break; // The following statuses have no marks in the queue file. case DlStatus::QUEUED: case DlStatus::DOWNLOADING: case DlStatus::CANCELLED: case DlStatus::DELETED: case DlStatus::FAILED: case DlStatus::ALREADY_DOWNLOADED: break; } f << std::endl; } } void QueueLoader::delete_played_files(const CategorizedDownloads& downloads) const { if (!cfg.get_configvalue_as_bool("delete-played-files")) { return; } for (const auto& dl : downloads.to_delete) { const std::string filename = dl.filename(); LOG(Level::INFO, "Deleting file %s", filename); if (std::remove(filename.c_str()) != 0) { if (errno != ENOENT) { LOG(Level::ERROR, "Failed to delete file %s, error code: %d (%s)", filename, errno, strerror(errno)); } } } } std::string QueueLoader::get_filename(const std::string& str) const { std::string fn = cfg.get_configvalue("download-path"); if (fn[fn.length() - 1] != NEWSBEUTER_PATH_SEP) { fn.push_back(NEWSBEUTER_PATH_SEP); } char buf[1024]; snprintf(buf, sizeof(buf), "%s", str.c_str()); char* base = basename(buf); if (!base || strlen(base) == 0) { time_t t = time(nullptr); fn.append(utils::mt_strf_localtime("%Y-%b-%d-%H%M%S.unknown", t)); } else { fn.append(utils::replace_all(base, "'", "%27")); } return fn; } } // namespace podboat <commit_msg>Shuffle code around for slightly better readability<commit_after>#include "queueloader.h" #include <cerrno> #include <cstdlib> #include <cstdio> #include <cstring> #include <fstream> #include <iostream> #include <libgen.h> #include <unistd.h> #include "config.h" #include "configcontainer.h" #include "logger.h" #include "stflpp.h" #include "strprintf.h" #include "utils.h" using namespace newsboat; namespace podboat { QueueLoader::QueueLoader(const std::string& filepath, const ConfigContainer& cfg_, std::function<void()> cb_require_view_update_) : queuefile(filepath) , cfg(cfg_) , cb_require_view_update(cb_require_view_update_) { } void QueueLoader::reload(std::vector<Download>& downloads, bool also_remove_finished) const { CategorizedDownloads categorized_downloads; const auto res = categorize_downloads(downloads, also_remove_finished); if (!res.has_value()) { return; } categorized_downloads = res.value(); update_from_queue_file(categorized_downloads); write_queue_file(categorized_downloads); if (cfg.get_configvalue_as_bool("delete-played-files")) { delete_played_files(categorized_downloads); } downloads = std::move(categorized_downloads.to_keep); } nonstd::optional<QueueLoader::CategorizedDownloads> QueueLoader::categorize_downloads( const std::vector<Download>& downloads, bool also_remove_finished) { CategorizedDownloads result; for (const auto& dl : downloads) { // we are not allowed to reload if a download is in progress! if (dl.status() == DlStatus::DOWNLOADING) { LOG(Level::INFO, "QueueLoader::reload: aborting reload due to " "DlStatus::DOWNLOADING status"); return nonstd::nullopt; } bool keep_entry = false; switch (dl.status()) { case DlStatus::QUEUED: case DlStatus::CANCELLED: case DlStatus::FAILED: case DlStatus::ALREADY_DOWNLOADED: case DlStatus::READY: case DlStatus::PLAYED: LOG(Level::DEBUG, "QueueLoader::reload: storing %s to new vector", dl.url()); keep_entry = true; break; case DlStatus::FINISHED: if (!also_remove_finished) { LOG(Level::DEBUG, "QueueLoader::reload: storing %s to new vector", dl.url()); keep_entry = true; } break; case DlStatus::DELETED: keep_entry = false; break; case DlStatus::DOWNLOADING: assert(!"Can't be reached because of the `if` above"); break; } if (keep_entry) { result.to_keep.push_back(dl); } else { result.to_delete.push_back(dl); } } return result; } void QueueLoader::update_from_queue_file(CategorizedDownloads& downloads) const { std::fstream f(queuefile, std::fstream::in); if (!f.is_open()) { return; } bool comments_ignored = false; for (std::string line; std::getline(f, line); ) { if (line.empty()) { continue; } LOG(Level::DEBUG, "QueueLoader::reload: loaded `%s' from queue file", line); const std::vector<std::string> fields = utils::tokenize_quoted(line); bool url_found = false; if (fields.empty()) { if (!comments_ignored) { std::cout << strprintf::fmt( _("WARNING: Comment found " "in %s. The queue file is regenerated " "when podboat exits and comments will " "be deleted. Press Enter to continue or " "Ctrl+C to abort"), queuefile) << std::endl; std::cin.ignore(); comments_ignored = true; } continue; } for (const auto& dl : downloads.to_keep) { if (fields[0] == dl.url()) { LOG(Level::INFO, "QueueLoader::reload: found `%s' in old vector", fields[0]); url_found = true; break; } } for (const auto& dl : downloads.to_delete) { if (fields[0] == dl.url()) { LOG(Level::INFO, "QueueLoader::reload: found `%s' in scheduled for deletion vector", fields[0]); url_found = true; break; } } if (url_found) { continue; } LOG(Level::INFO, "QueueLoader::reload: found `%s' nowhere -> storing to new vector", line); Download d(cb_require_view_update); std::string fn; if (fields.size() == 1) { fn = get_filename(fields[0]); } else { fn = fields[1]; } d.set_filename(fn); if (access(fn.c_str(), F_OK) == 0) { LOG(Level::INFO, "QueueLoader::reload: found `%s' on file system -> mark as already downloaded", fn); if (fields.size() >= 3) { if (fields[2] == "downloaded") { d.set_status(DlStatus::READY); } if (fields[2] == "played") { d.set_status(DlStatus::PLAYED); } if (fields[2] == "finished") { d.set_status(DlStatus::FINISHED); } } else { // TODO: scrap DlStatus::ALREADY_DOWNLOADED state d.set_status(DlStatus::ALREADY_DOWNLOADED); } } else if (access((fn + ConfigContainer::PARTIAL_FILE_SUFFIX).c_str(), F_OK) == 0) { LOG(Level::INFO, "QueueLoader::reload: found `%s' on file system -> mark as partially downloaded", fn + ConfigContainer::PARTIAL_FILE_SUFFIX); d.set_status(DlStatus::ALREADY_DOWNLOADED); } d.set_url(fields[0]); downloads.to_keep.push_back(d); } } void QueueLoader::write_queue_file(const CategorizedDownloads& downloads) const { std::fstream f(queuefile, std::fstream::out); if (!f.is_open()) { return; } for (const auto& dl : downloads.to_keep) { f << dl.url() << " " << utils::quote(dl.filename()); switch (dl.status()) { case DlStatus::READY: f << " downloaded"; break; case DlStatus::PLAYED: f << " played"; break; case DlStatus::FINISHED: f << " finished"; break; // The following statuses have no marks in the queue file. case DlStatus::QUEUED: case DlStatus::DOWNLOADING: case DlStatus::CANCELLED: case DlStatus::DELETED: case DlStatus::FAILED: case DlStatus::ALREADY_DOWNLOADED: break; } f << std::endl; } } void QueueLoader::delete_played_files(const CategorizedDownloads& downloads) const { for (const auto& dl : downloads.to_delete) { const std::string filename = dl.filename(); LOG(Level::INFO, "Deleting file %s", filename); if (std::remove(filename.c_str()) != 0) { if (errno != ENOENT) { LOG(Level::ERROR, "Failed to delete file %s, error code: %d (%s)", filename, errno, strerror(errno)); } } } } std::string QueueLoader::get_filename(const std::string& str) const { std::string fn = cfg.get_configvalue("download-path"); if (fn[fn.length() - 1] != NEWSBEUTER_PATH_SEP) { fn.push_back(NEWSBEUTER_PATH_SEP); } char buf[1024]; snprintf(buf, sizeof(buf), "%s", str.c_str()); char* base = basename(buf); if (!base || strlen(base) == 0) { time_t t = time(nullptr); fn.append(utils::mt_strf_localtime("%Y-%b-%d-%H%M%S.unknown", t)); } else { fn.append(utils::replace_all(base, "'", "%27")); } return fn; } } // namespace podboat <|endoftext|>
<commit_before>/* * Copyright (c) 2014 liblcf authors * This file is released under the MIT License * http://opensource.org/licenses/MIT */ #include "reader_options.h" #ifdef LCF_SUPPORT_ICU # include "unicode/ucsdet.h" # include "unicode/ucnv.h" #else # ifdef _WIN32 # include <cstdio> # define WIN32_LEAN_AND_MEAN # ifndef NOMINMAX # define NOMINMAX # endif # include <windows.h> # endif #endif #ifndef _WIN32 # include <locale> #endif #include <cstdlib> #include <sstream> #include <vector> #include "inireader.h" #include "reader_util.h" namespace ReaderUtil { } std::string ReaderUtil::CodepageToEncoding(int codepage) { if (codepage == 0) return std::string(); #ifdef _WIN32 if (codepage > 0) { // Looks like a valid codepage return std::string(codepage); } #else if (codepage == 932) { # ifdef LCF_SUPPORT_ICU return "cp943"; # else return "SHIFT_JIS"; # endif } else { std::ostringstream out; # ifdef LCF_SUPPORT_ICU out << "windows-" << codepage; # else out << "CP" << codepage; # endif // Check at first if the ini value is a codepage if (!out.str().empty()) { // Looks like a valid codepage return out.str(); } return std::string(); } #endif } std::string ReaderUtil::DetectEncoding(const std::string& text) { const char* encoding = ""; #ifdef LCF_SUPPORT_ICU UErrorCode status = U_ZERO_ERROR; UCharsetDetector* detector = ucsdet_open(&status); ucsdet_setText(detector, text.data(), text.length(), &status); const UCharsetMatch* match = ucsdet_detect(detector, &status); if (match != NULL) { encoding = ucsdet_getName(match, &status); } ucsdet_close(detector); #endif return std::string(encoding); } std::string ReaderUtil::GetEncoding(const std::string& ini_file) { INIReader ini(ini_file); if (ini.ParseError() != -1) { std::string encoding = ini.Get("EasyRPG", "Encoding", std::string()); if (!encoding.empty()) { return CodepageToEncoding(atoi(encoding.c_str())); } } return std::string(); } std::string ReaderUtil::GetLocaleEncoding() { #ifdef _WIN32 // On Windows, empty string encoding means current system locale. std::string encoding = ""; #else std::string encoding = "1252"; std::locale loc = std::locale(""); // Gets the language and culture part only std::string loc_full = loc.name().substr(0, loc.name().find_first_of("@.")); // Gets the language part only std::string loc_lang = loc.name().substr(0, loc.name().find_first_of("_")); if (loc_lang == "th") encoding = "874"; else if (loc_lang == "ja") encoding = "932"; else if (loc_full == "zh_CN" || loc_full == "zh_SG") encoding = "936"; else if (loc_lang == "ko") encoding = "949"; else if (loc_full == "zh_TW" || loc_full == "zh_HK") encoding = "950"; else if (loc_lang == "cs" || loc_lang == "hu" || loc_lang == "pl" || loc_lang == "ro" || loc_lang == "hr" || loc_lang == "sk" || loc_lang == "sl") encoding = "1250"; else if (loc_lang == "ru") encoding = "1251"; else if (loc_lang == "ca" || loc_lang == "da" || loc_lang == "de" || loc_lang == "en" || loc_lang == "es" || loc_lang == "fi" || loc_lang == "fr" || loc_lang == "it" || loc_lang == "nl" || loc_lang == "nb" || loc_lang == "pt" || loc_lang == "sv" || loc_lang == "eu") encoding = "1252"; else if (loc_lang == "el") encoding = "1253"; else if (loc_lang == "tr") encoding = "1254"; else if (loc_lang == "he") encoding = "1255"; else if (loc_lang == "ar") encoding = "1256"; else if (loc_lang == "et" || loc_lang == "lt" || loc_lang == "lv") encoding = "1257"; else if (loc_lang == "vi") encoding = "1258"; #endif return encoding; } std::string ReaderUtil::Recode(const std::string& str_to_encode, const std::string& source_encoding) { #ifdef _WIN32 return ReaderUtil::Recode(str_to_encode, source_encoding, "65001"); #else return ReaderUtil::Recode(str_to_encode, source_encoding, "UTF-8"); #endif } std::string ReaderUtil::Recode(const std::string& str_to_encode, const std::string& src_enc, const std::string& dst_enc) { std::string encoding_str = src_enc; if (src_enc.empty()) { return str_to_encode; } if (atoi(src_enc.c_str()) > 0) { encoding_str = ReaderUtil::CodepageToEncoding(atoi(src_enc.c_str())); } #ifdef LCF_SUPPORT_ICU UErrorCode status = U_ZERO_ERROR; int size = str_to_encode.size() * 4; UChar unicode_str[size]; UConverter *conv; int length; conv = ucnv_open(encoding_str.c_str(), &status); length = ucnv_toUChars(conv, unicode_str, size, str_to_encode.c_str(), -1, &status); ucnv_close(conv); char result[length]; conv = ucnv_open(dst_enc.c_str(), &status); ucnv_fromUChars(conv, result, length * 4, unicode_str, -1, &status); ucnv_close(conv); if (status != 0) return std::string(); return std::string(&result[0]); #else # ifdef _WIN32 size_t strsize = str_to_encode.size(); wchar_t* widechar = new wchar_t[strsize * 5 + 1]; // To UTF-16 // Default codepage is 0, so we dont need a check here int res = MultiByteToWideChar(atoi(encoding_str.c_str()), 0, str_to_encode.c_str(), strsize, widechar, strsize * 5 + 1); if (res == 0) { // Invalid codepage delete [] widechar; return str_to_encode; } widechar[res] = '\0'; // Back to UTF-8... char* utf8char = new char[strsize * 5 + 1]; res = WideCharToMultiByte(atoi(dst_enc.c_str()), 0, widechar, res, utf8char, strsize * 5 + 1, NULL, NULL); utf8char[res] = '\0'; // Result in str std::string str = std::string(utf8char, res); delete [] widechar; delete [] utf8char; return str; # else iconv_t cd = iconv_open(dst_enc.c_str(), encoding_str.c_str()); if (cd == (iconv_t)-1) return str_to_encode; char *src = const_cast<char *>(str_to_encode.c_str()); size_t src_left = str_to_encode.size(); size_t dst_size = str_to_encode.size() * 5 + 10; char *dst = new char[dst_size]; size_t dst_left = dst_size; # ifdef ICONV_CONST char ICONV_CONST *p = src; # else char *p = src; # endif char *q = dst; size_t status = iconv(cd, &p, &src_left, &q, &dst_left); iconv_close(cd); if (status == (size_t) -1 || src_left > 0) { delete[] dst; return std::string(); } *q++ = '\0'; std::string result(dst); delete[] dst; return result; # endif #endif } <commit_msg>Return encoding instead of codepage when getting encoding from locale<commit_after>/* * Copyright (c) 2014 liblcf authors * This file is released under the MIT License * http://opensource.org/licenses/MIT */ #include "reader_options.h" #ifdef LCF_SUPPORT_ICU # include "unicode/ucsdet.h" # include "unicode/ucnv.h" #else # ifdef _WIN32 # include <cstdio> # define WIN32_LEAN_AND_MEAN # ifndef NOMINMAX # define NOMINMAX # endif # include <windows.h> # endif #endif #ifndef _WIN32 # include <locale> #endif #include <cstdlib> #include <sstream> #include <vector> #include "inireader.h" #include "reader_util.h" namespace ReaderUtil { } std::string ReaderUtil::CodepageToEncoding(int codepage) { if (codepage == 0) return std::string(); #ifdef _WIN32 if (codepage > 0) { // Looks like a valid codepage return std::string(codepage); } #else if (codepage == 932) { # ifdef LCF_SUPPORT_ICU return "cp943"; # else return "SHIFT_JIS"; # endif } else { std::ostringstream out; # ifdef LCF_SUPPORT_ICU out << "windows-" << codepage; # else out << "CP" << codepage; # endif // Check at first if the ini value is a codepage if (!out.str().empty()) { // Looks like a valid codepage return out.str(); } return std::string(); } #endif } std::string ReaderUtil::DetectEncoding(const std::string& text) { const char* encoding = ""; #ifdef LCF_SUPPORT_ICU UErrorCode status = U_ZERO_ERROR; UCharsetDetector* detector = ucsdet_open(&status); ucsdet_setText(detector, text.data(), text.length(), &status); const UCharsetMatch* match = ucsdet_detect(detector, &status); if (match != NULL) { encoding = ucsdet_getName(match, &status); } ucsdet_close(detector); #endif return std::string(encoding); } std::string ReaderUtil::GetEncoding(const std::string& ini_file) { INIReader ini(ini_file); if (ini.ParseError() != -1) { std::string encoding = ini.Get("EasyRPG", "Encoding", std::string()); if (!encoding.empty()) { return ReaderUtil::CodepageToEncoding(atoi(encoding.c_str())); } } return std::string(); } std::string ReaderUtil::GetLocaleEncoding() { #ifdef _WIN32 // On Windows means current system locale. int codepage = 0; #else int codepage = 1252; std::locale loc = std::locale(""); // Gets the language and culture part only std::string loc_full = loc.name().substr(0, loc.name().find_first_of("@.")); // Gets the language part only std::string loc_lang = loc.name().substr(0, loc.name().find_first_of("_")); if (loc_lang == "th") codepage = 874; else if (loc_lang == "ja") codepage = 932; else if (loc_full == "zh_CN" || loc_full == "zh_SG") codepage = 936; else if (loc_lang == "ko") codepage = 949; else if (loc_full == "zh_TW" || loc_full == "zh_HK") codepage = 950; else if (loc_lang == "cs" || loc_lang == "hu" || loc_lang == "pl" || loc_lang == "ro" || loc_lang == "hr" || loc_lang == "sk" || loc_lang == "sl") codepage = 1250; else if (loc_lang == "ru") codepage = 1251; else if (loc_lang == "ca" || loc_lang == "da" || loc_lang == "de" || loc_lang == "en" || loc_lang == "es" || loc_lang == "fi" || loc_lang == "fr" || loc_lang == "it" || loc_lang == "nl" || loc_lang == "nb" || loc_lang == "pt" || loc_lang == "sv" || loc_lang == "eu") codepage = 1252; else if (loc_lang == "el") codepage = 1253; else if (loc_lang == "tr") codepage = 1254; else if (loc_lang == "he") codepage = 1255; else if (loc_lang == "ar") codepage = 1256; else if (loc_lang == "et" || loc_lang == "lt" || loc_lang == "lv") codepage = 1257; else if (loc_lang == "vi") codepage = 1258; #endif return CodepageToEncoding(codepage); } std::string ReaderUtil::Recode(const std::string& str_to_encode, const std::string& source_encoding) { #ifdef _WIN32 return ReaderUtil::Recode(str_to_encode, source_encoding, "65001"); #else return ReaderUtil::Recode(str_to_encode, source_encoding, "UTF-8"); #endif } std::string ReaderUtil::Recode(const std::string& str_to_encode, const std::string& src_enc, const std::string& dst_enc) { std::string encoding_str = src_enc; if (src_enc.empty()) { return str_to_encode; } if (atoi(src_enc.c_str()) > 0) { encoding_str = ReaderUtil::CodepageToEncoding(atoi(src_enc.c_str())); } #ifdef LCF_SUPPORT_ICU UErrorCode status = U_ZERO_ERROR; int size = str_to_encode.size() * 4; UChar unicode_str[size]; // FIXME UConverter *conv; int length; conv = ucnv_open(encoding_str.c_str(), &status); length = ucnv_toUChars(conv, unicode_str, size, str_to_encode.c_str(), -1, &status); ucnv_close(conv); char result[length]; // FIXME conv = ucnv_open(dst_enc.c_str(), &status); ucnv_fromUChars(conv, result, length * 4, unicode_str, -1, &status); ucnv_close(conv); if (status != 0) return std::string(); return std::string(&result[0]); #else # ifdef _WIN32 size_t strsize = str_to_encode.size(); wchar_t* widechar = new wchar_t[strsize * 5 + 1]; // To UTF-16 // Default codepage is 0, so we dont need a check here int res = MultiByteToWideChar(atoi(encoding_str.c_str()), 0, str_to_encode.c_str(), strsize, widechar, strsize * 5 + 1); if (res == 0) { // Invalid codepage delete [] widechar; return str_to_encode; } widechar[res] = '\0'; // Back to UTF-8... char* utf8char = new char[strsize * 5 + 1]; res = WideCharToMultiByte(atoi(dst_enc.c_str()), 0, widechar, res, utf8char, strsize * 5 + 1, NULL, NULL); utf8char[res] = '\0'; // Result in str std::string str = std::string(utf8char, res); delete [] widechar; delete [] utf8char; return str; # else iconv_t cd = iconv_open(dst_enc.c_str(), encoding_str.c_str()); if (cd == (iconv_t)-1) return str_to_encode; char *src = const_cast<char *>(str_to_encode.c_str()); size_t src_left = str_to_encode.size(); size_t dst_size = str_to_encode.size() * 5 + 10; char *dst = new char[dst_size]; size_t dst_left = dst_size; # ifdef ICONV_CONST char ICONV_CONST *p = src; # else char *p = src; # endif char *q = dst; size_t status = iconv(cd, &p, &src_left, &q, &dst_left); iconv_close(cd); if (status == (size_t) -1 || src_left > 0) { delete[] dst; return std::string(); } *q++ = '\0'; std::string result(dst); delete[] dst; return result; # endif #endif } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: CRowSetDataColumn.hxx,v $ * * $Revision: 1.16 $ * * last change: $Author: hr $ $Date: 2006-06-20 02:34:16 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef DBACCESS_CORE_API_CROWSETDATACOLUMN_HXX #define DBACCESS_CORE_API_CROWSETDATACOLUMN_HXX #ifndef _DBACORE_DATACOLUMN_HXX_ #include "datacolumn.hxx" #endif #ifndef DBACCESS_CORE_API_ROWSETROW_HXX #include "RowSetRow.hxx" #endif #ifndef _CONNECTIVITY_COMMONTOOLS_HXX_ #include <connectivity/CommonTools.hxx> #endif #ifndef _COMPHELPER_PROPERTY_ARRAY_HELPER_HXX_ #include <comphelper/proparrhlp.hxx> #endif #ifndef DBACCESS_ROWSETCACHEITERATOR_HXX #include "RowSetCacheIterator.hxx" #endif namespace dbaccess { class ORowSetDataColumn; typedef ::comphelper::OPropertyArrayUsageHelper<ORowSetDataColumn> ORowSetDataColumn_PROP; class ORowSetDataColumn : public ODataColumn, public OColumnSettings, public ORowSetDataColumn_PROP { protected: ORowSetCacheIterator m_aColumnValue; ::com::sun::star::uno::Any m_aOldValue; ::rtl::OUString m_aDescription; // description ORowSetBase* m_pRowSet; virtual ~ORowSetDataColumn(); public: ORowSetDataColumn(const ::com::sun::star::uno::Reference < ::com::sun::star::sdbc::XResultSetMetaData >& _xMetaData, const ::com::sun::star::uno::Reference < ::com::sun::star::sdbc::XRow >& _xRow, const ::com::sun::star::uno::Reference < ::com::sun::star::sdbc::XRowUpdate >& _xRowUpdate, sal_Int32 _nPos, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData >& _rxDBMeta, const ::rtl::OUString& _rDescription, const ORowSetCacheIterator& _rColumnValue); // com::sun::star::lang::XTypeProvider virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() throw (::com::sun::star::uno::RuntimeException); // comphelper::OPropertyArrayUsageHelper virtual ::cppu::IPropertyArrayHelper* createArrayHelper( ) const; // cppu::OPropertySetHelper virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper(); virtual sal_Bool SAL_CALL convertFastPropertyValue( ::com::sun::star::uno::Any & rConvertedValue, ::com::sun::star::uno::Any & rOldValue, sal_Int32 nHandle, const ::com::sun::star::uno::Any& rValue ) throw (::com::sun::star::lang::IllegalArgumentException); virtual void SAL_CALL getFastPropertyValue( ::com::sun::star::uno::Any& rValue, sal_Int32 nHandle ) const; virtual void SAL_CALL setFastPropertyValue_NoBroadcast(sal_Int32 nHandle,const ::com::sun::star::uno::Any& rValue )throw (::com::sun::star::uno::Exception); virtual void fireValueChange(const ::connectivity::ORowSetValue& _rOldValue); protected: using ODataColumn::getFastPropertyValue; }; // ------------------------------------------------------------------------- // typedef connectivity::ORefVector< ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> > // ORowSetDataColumns_COLLECTION; typedef connectivity::sdbcx::OCollection ORowSetDataColumns_BASE; class ORowSetDataColumns : public ORowSetDataColumns_BASE { ::vos::ORef< ::connectivity::OSQLColumns> m_aColumns; protected: virtual connectivity::sdbcx::ObjectType createObject(const ::rtl::OUString& _rName); virtual void impl_refresh() throw(::com::sun::star::uno::RuntimeException); public: ORowSetDataColumns( sal_Bool _bCase, const ::vos::ORef< ::connectivity::OSQLColumns>& _rColumns, ::cppu::OWeakObject& _rParent, ::osl::Mutex& _rMutex, const ::std::vector< ::rtl::OUString> &_rVector ); virtual ~ORowSetDataColumns(); // only the name is identical to ::cppu::OComponentHelper virtual void SAL_CALL disposing(void); void assign(const ::vos::ORef< ::connectivity::OSQLColumns>& _rColumns,const ::std::vector< ::rtl::OUString> &_rVector); }; } #endif <commit_msg>INTEGRATION: CWS changefileheader (1.16.308); FILE MERGED 2008/03/31 13:26:42 rt 1.16.308.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: CRowSetDataColumn.hxx,v $ * $Revision: 1.17 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef DBACCESS_CORE_API_CROWSETDATACOLUMN_HXX #define DBACCESS_CORE_API_CROWSETDATACOLUMN_HXX #ifndef _DBACORE_DATACOLUMN_HXX_ #include "datacolumn.hxx" #endif #ifndef DBACCESS_CORE_API_ROWSETROW_HXX #include "RowSetRow.hxx" #endif #ifndef _CONNECTIVITY_COMMONTOOLS_HXX_ #include <connectivity/CommonTools.hxx> #endif #ifndef _COMPHELPER_PROPERTY_ARRAY_HELPER_HXX_ #include <comphelper/proparrhlp.hxx> #endif #ifndef DBACCESS_ROWSETCACHEITERATOR_HXX #include "RowSetCacheIterator.hxx" #endif namespace dbaccess { class ORowSetDataColumn; typedef ::comphelper::OPropertyArrayUsageHelper<ORowSetDataColumn> ORowSetDataColumn_PROP; class ORowSetDataColumn : public ODataColumn, public OColumnSettings, public ORowSetDataColumn_PROP { protected: ORowSetCacheIterator m_aColumnValue; ::com::sun::star::uno::Any m_aOldValue; ::rtl::OUString m_aDescription; // description ORowSetBase* m_pRowSet; virtual ~ORowSetDataColumn(); public: ORowSetDataColumn(const ::com::sun::star::uno::Reference < ::com::sun::star::sdbc::XResultSetMetaData >& _xMetaData, const ::com::sun::star::uno::Reference < ::com::sun::star::sdbc::XRow >& _xRow, const ::com::sun::star::uno::Reference < ::com::sun::star::sdbc::XRowUpdate >& _xRowUpdate, sal_Int32 _nPos, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData >& _rxDBMeta, const ::rtl::OUString& _rDescription, const ORowSetCacheIterator& _rColumnValue); // com::sun::star::lang::XTypeProvider virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() throw (::com::sun::star::uno::RuntimeException); // comphelper::OPropertyArrayUsageHelper virtual ::cppu::IPropertyArrayHelper* createArrayHelper( ) const; // cppu::OPropertySetHelper virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper(); virtual sal_Bool SAL_CALL convertFastPropertyValue( ::com::sun::star::uno::Any & rConvertedValue, ::com::sun::star::uno::Any & rOldValue, sal_Int32 nHandle, const ::com::sun::star::uno::Any& rValue ) throw (::com::sun::star::lang::IllegalArgumentException); virtual void SAL_CALL getFastPropertyValue( ::com::sun::star::uno::Any& rValue, sal_Int32 nHandle ) const; virtual void SAL_CALL setFastPropertyValue_NoBroadcast(sal_Int32 nHandle,const ::com::sun::star::uno::Any& rValue )throw (::com::sun::star::uno::Exception); virtual void fireValueChange(const ::connectivity::ORowSetValue& _rOldValue); protected: using ODataColumn::getFastPropertyValue; }; // ------------------------------------------------------------------------- // typedef connectivity::ORefVector< ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> > // ORowSetDataColumns_COLLECTION; typedef connectivity::sdbcx::OCollection ORowSetDataColumns_BASE; class ORowSetDataColumns : public ORowSetDataColumns_BASE { ::vos::ORef< ::connectivity::OSQLColumns> m_aColumns; protected: virtual connectivity::sdbcx::ObjectType createObject(const ::rtl::OUString& _rName); virtual void impl_refresh() throw(::com::sun::star::uno::RuntimeException); public: ORowSetDataColumns( sal_Bool _bCase, const ::vos::ORef< ::connectivity::OSQLColumns>& _rColumns, ::cppu::OWeakObject& _rParent, ::osl::Mutex& _rMutex, const ::std::vector< ::rtl::OUString> &_rVector ); virtual ~ORowSetDataColumns(); // only the name is identical to ::cppu::OComponentHelper virtual void SAL_CALL disposing(void); void assign(const ::vos::ORef< ::connectivity::OSQLColumns>& _rColumns,const ::std::vector< ::rtl::OUString> &_rVector); }; } #endif <|endoftext|>
<commit_before>#include "UNIFAQLibrary.h" namespace UNIFAQLibrary{ void UNIFAQParameterLibrary::jsonize(std::string &s, rapidjson::Document &d) { d.Parse<0>(s.c_str()); if (d.HasParseError()) { throw -1; } else { return; } } void UNIFAQParameterLibrary::populate(rapidjson::Value &group_data, rapidjson::Value &interaction_data, rapidjson::Value &comp_data) { // Schema should have been used to validate the data already, so by this point we are can safely consume the data without checking ... for (rapidjson::Value::ValueIterator itr = group_data.Begin(); itr != group_data.End(); ++itr) { Group g; g.sgi = (*itr)["sgi"].GetInt(); g.mgi = (*itr)["mgi"].GetInt(); g.R_k = (*itr)["R_k"].GetDouble(); g.Q_k = (*itr)["Q_k"].GetDouble(); groups.push_back(g); } for (rapidjson::Value::ValueIterator itr = interaction_data.Begin(); itr != interaction_data.End(); ++itr) { InteractionParameters ip; ip.mgi1 = (*itr)["mgi1"].GetInt(); ip.mgi2 = (*itr)["mgi2"].GetInt(); ip.a_ij = (*itr)["a_ij"].GetDouble(); ip.a_ji = (*itr)["a_ji"].GetDouble(); ip.b_ij = (*itr)["b_ij"].GetDouble(); ip.b_ji = (*itr)["b_ji"].GetDouble(); ip.c_ij = (*itr)["c_ij"].GetDouble(); ip.c_ji = (*itr)["c_ji"].GetDouble(); interaction_parameters.push_back(ip); } for (rapidjson::Value::ValueIterator itr = comp_data.Begin(); itr != comp_data.End(); ++itr) { Component c; c.inchikey = (*itr)["inchikey"].GetString(); c.registry_number = (*itr)["registry_number"].GetString(); c.name = (*itr)["name"].GetString(); c.Tc = (*itr)["Tc"].GetDouble(); c.pc = (*itr)["pc"].GetDouble(); c.acentric = (*itr)["acentric"].GetDouble(); c.molemass = (*itr)["molemass"].GetDouble(); // userid is an optional user identifier if ((*itr).HasMember("userid")){ c.userid = (*itr)["userid"].GetString(); } // If provided, store information about the alpha function in use if ((*itr).HasMember("alpha") && (*itr)["alpha"].IsObject()){ rapidjson::Value &alpha = (*itr)["alpha"]; c.alpha_type = cpjson::get_string(alpha, "type"); c.alpha_coeffs = cpjson::get_double_array(alpha, "c"); } else{ c.alpha_type = "default"; } rapidjson::Value &groups = (*itr)["groups"]; for (rapidjson::Value::ValueIterator itrg = groups.Begin(); itrg != groups.End(); ++itrg) { int count = (*itrg)["count"].GetInt(); int sgi = (*itrg)["sgi"].GetInt(); if (has_group(sgi)){ ComponentGroup cg(count, get_group(sgi)); c.groups.push_back(cg); } } components.push_back(c); } } void UNIFAQParameterLibrary::populate(std::string &group_data, std::string &interaction_data, std::string &decomp_data) { rapidjson::Document group_JSON; jsonize(group_data, group_JSON); rapidjson::Document interaction_JSON; jsonize(interaction_data, interaction_JSON); rapidjson::Document decomp_JSON; jsonize(decomp_data, decomp_JSON); populate(group_JSON, interaction_JSON, decomp_JSON); } Group UNIFAQParameterLibrary::get_group(int sgi) const { for (std::vector<Group>::const_iterator it = groups.begin(); it != groups.end(); ++it) { if (it->sgi == sgi) { return *it; } } throw CoolProp::ValueError("Could not find group"); } bool UNIFAQParameterLibrary::has_group(int sgi) const { for (std::vector<Group>::const_iterator it = groups.begin(); it != groups.end(); ++it) { if (it->sgi == sgi) { return true; } } return false; } InteractionParameters UNIFAQParameterLibrary::get_interaction_parameters(int mgi1, int mgi2) const { // If both mgi are the same, yield all zeros for the interaction parameters if (mgi1 == mgi2){ InteractionParameters ip; ip.mgi1 = mgi1; ip.mgi2 = mgi2; ip.zero_out(); return ip; } for (std::vector<InteractionParameters>::const_iterator it = interaction_parameters.begin(); it != interaction_parameters.end(); ++it) { if (it->mgi1 == mgi1 && it->mgi2 == mgi2) { // Correct order, return it return *it; } if (it->mgi2 == mgi1 && it->mgi1 == mgi2) { // Backwards, swap the parameters InteractionParameters ip = *it; ip.swap(); return ip; } } throw CoolProp::ValueError(format("Could not find interaction between pair mgi[%d]-mgi[%d]", static_cast<int>(mgi1), static_cast<int>(mgi2))); } Component UNIFAQParameterLibrary::get_component(const std::string &identifier, const std::string &value) const { if (identifier == "name"){ for (std::vector<Component>::const_iterator it = components.begin(); it != components.end(); ++it ){ if (it->name == value ){ return *it; } } } throw CoolProp::ValueError(format("Could not find component: %s with identifier: %s", value.c_str(), identifier.c_str())); } }; /* namespace UNIFAQLibrary */ #if defined(ENABLE_CATCH) #include "catch.hpp" #include "UNIFAQ.h" TEST_CASE("Check Poling example for UNIFAQ", "[UNIFAQ]") { std::string acetone_pentane_groups = "[{ \"Tc\": 508.1, \"acentric\": 0.3071, \"groups\": [ { \"count\": 1, \"sgi\": 1 }, {\"count\": 1, \"sgi\": 18 } ], \"inchikey\": \"?????????????\", \"name\": \"Acetone\", \"pc\": 4700000.0, \"registry_number\": \"67-64-1\", \"userid\": \"\" }, { \"Tc\": 469.7000000000001, \"acentric\": 0.251, \"groups\": [ { \"count\": 2, \"sgi\": 1 }, { \"count\": 3, \"sgi\": 2 } ], \"inchikey\": \"?????????????\", \"name\": \"n-Pentane\", \"pc\": 3370000.0, \"registry_number\": \"109-66-0\", \"userid\": \"\" } ]"; std::string groups = "[{\"Q_k\": 0.848, \"R_k\": 0.9011, \"maingroup_name\": \"CH2\", \"mgi\": 1, \"sgi\": 1, \"subgroup_name\": \"CH3\"}," "{\"Q_k\": 0.540, \"R_k\": 0.6744, \"maingroup_name\": \"CH2\", \"mgi\": 1, \"sgi\": 2, \"subgroup_name\": \"CH2\"}," "{\"Q_k\": 1.488, \"R_k\": 1.6724, \"maingroup_name\": \"CH2CO\", \"mgi\": 9, \"sgi\": 18, \"subgroup_name\": \"CH3CO\"}]"; std::string interactions = "[{\"a_ij\": 476.4, \"a_ji\": 26.76, \"b_ij\": 0.0, \"b_ji\": 0.0, \"c_ij\": 0.0, \"c_ji\": 0.0, \"mgi1\": 1, \"mgi2\": 9}]"; SECTION("Validate AC for acetone + n-pentane") { UNIFAQLibrary::UNIFAQParameterLibrary lib; CHECK_NOTHROW(lib.populate(groups, interactions, acetone_pentane_groups);); UNIFAQ::UNIFAQMixture mix(lib,1.0); std::vector<std::string> names; names.push_back("Acetone"); names.push_back("n-Pentane"); mix.set_components("name",names); mix.set_interaction_parameters(); std::vector<double> z(2,0.047); z[1] = 1-z[0]; mix.set_mole_fractions(z); CHECK_NOTHROW(mix.set_temperature(307);); double lngammaR0 = mix.ln_gamma_R(1.0/307,0,0); double lngammaR1 = mix.ln_gamma_R(1.0/307,1,0); CAPTURE(lngammaR0); CAPTURE(lngammaR1); CHECK(std::abs(lngammaR0 - 1.66) < 1e-2); CHECK(std::abs(lngammaR1 - 5.68e-3) < 1e-3); std::vector<double> gamma(2); mix.activity_coefficients(1.0/307,z,gamma); CAPTURE(gamma[0]); CAPTURE(gamma[1]); CHECK(std::abs(gamma[0] - 4.99) < 1e-2); CHECK(std::abs(gamma[1] - 1.005) < 1e-3); }; }; #endif <commit_msg>Fix UNIFAQ test for acetone + pentane<commit_after>#include "UNIFAQLibrary.h" namespace UNIFAQLibrary{ void UNIFAQParameterLibrary::jsonize(std::string &s, rapidjson::Document &d) { d.Parse<0>(s.c_str()); if (d.HasParseError()) { throw -1; } else { return; } } void UNIFAQParameterLibrary::populate(rapidjson::Value &group_data, rapidjson::Value &interaction_data, rapidjson::Value &comp_data) { // Schema should have been used to validate the data already, so by this point we are can safely consume the data without checking ... for (rapidjson::Value::ValueIterator itr = group_data.Begin(); itr != group_data.End(); ++itr) { Group g; g.sgi = (*itr)["sgi"].GetInt(); g.mgi = (*itr)["mgi"].GetInt(); g.R_k = (*itr)["R_k"].GetDouble(); g.Q_k = (*itr)["Q_k"].GetDouble(); groups.push_back(g); } for (rapidjson::Value::ValueIterator itr = interaction_data.Begin(); itr != interaction_data.End(); ++itr) { InteractionParameters ip; ip.mgi1 = (*itr)["mgi1"].GetInt(); ip.mgi2 = (*itr)["mgi2"].GetInt(); ip.a_ij = (*itr)["a_ij"].GetDouble(); ip.a_ji = (*itr)["a_ji"].GetDouble(); ip.b_ij = (*itr)["b_ij"].GetDouble(); ip.b_ji = (*itr)["b_ji"].GetDouble(); ip.c_ij = (*itr)["c_ij"].GetDouble(); ip.c_ji = (*itr)["c_ji"].GetDouble(); interaction_parameters.push_back(ip); } for (rapidjson::Value::ValueIterator itr = comp_data.Begin(); itr != comp_data.End(); ++itr) { Component c; c.inchikey = (*itr)["inchikey"].GetString(); c.registry_number = (*itr)["registry_number"].GetString(); c.name = (*itr)["name"].GetString(); c.Tc = (*itr)["Tc"].GetDouble(); c.pc = (*itr)["pc"].GetDouble(); c.acentric = (*itr)["acentric"].GetDouble(); c.molemass = (*itr)["molemass"].GetDouble(); // userid is an optional user identifier if ((*itr).HasMember("userid")){ c.userid = (*itr)["userid"].GetString(); } // If provided, store information about the alpha function in use if ((*itr).HasMember("alpha") && (*itr)["alpha"].IsObject()){ rapidjson::Value &alpha = (*itr)["alpha"]; c.alpha_type = cpjson::get_string(alpha, "type"); c.alpha_coeffs = cpjson::get_double_array(alpha, "c"); } else{ c.alpha_type = "default"; } rapidjson::Value &groups = (*itr)["groups"]; for (rapidjson::Value::ValueIterator itrg = groups.Begin(); itrg != groups.End(); ++itrg) { int count = (*itrg)["count"].GetInt(); int sgi = (*itrg)["sgi"].GetInt(); if (has_group(sgi)){ ComponentGroup cg(count, get_group(sgi)); c.groups.push_back(cg); } } components.push_back(c); } } void UNIFAQParameterLibrary::populate(std::string &group_data, std::string &interaction_data, std::string &decomp_data) { rapidjson::Document group_JSON; jsonize(group_data, group_JSON); rapidjson::Document interaction_JSON; jsonize(interaction_data, interaction_JSON); rapidjson::Document decomp_JSON; jsonize(decomp_data, decomp_JSON); populate(group_JSON, interaction_JSON, decomp_JSON); } Group UNIFAQParameterLibrary::get_group(int sgi) const { for (std::vector<Group>::const_iterator it = groups.begin(); it != groups.end(); ++it) { if (it->sgi == sgi) { return *it; } } throw CoolProp::ValueError("Could not find group"); } bool UNIFAQParameterLibrary::has_group(int sgi) const { for (std::vector<Group>::const_iterator it = groups.begin(); it != groups.end(); ++it) { if (it->sgi == sgi) { return true; } } return false; } InteractionParameters UNIFAQParameterLibrary::get_interaction_parameters(int mgi1, int mgi2) const { // If both mgi are the same, yield all zeros for the interaction parameters if (mgi1 == mgi2){ InteractionParameters ip; ip.mgi1 = mgi1; ip.mgi2 = mgi2; ip.zero_out(); return ip; } for (std::vector<InteractionParameters>::const_iterator it = interaction_parameters.begin(); it != interaction_parameters.end(); ++it) { if (it->mgi1 == mgi1 && it->mgi2 == mgi2) { // Correct order, return it return *it; } if (it->mgi2 == mgi1 && it->mgi1 == mgi2) { // Backwards, swap the parameters InteractionParameters ip = *it; ip.swap(); return ip; } } throw CoolProp::ValueError(format("Could not find interaction between pair mgi[%d]-mgi[%d]", static_cast<int>(mgi1), static_cast<int>(mgi2))); } Component UNIFAQParameterLibrary::get_component(const std::string &identifier, const std::string &value) const { if (identifier == "name"){ for (std::vector<Component>::const_iterator it = components.begin(); it != components.end(); ++it ){ if (it->name == value ){ return *it; } } } throw CoolProp::ValueError(format("Could not find component: %s with identifier: %s", value.c_str(), identifier.c_str())); } }; /* namespace UNIFAQLibrary */ #if defined(ENABLE_CATCH) #include "catch.hpp" #include "UNIFAQ.h" TEST_CASE("Check Poling example for UNIFAQ", "[UNIFAQ]") { std::string acetone_pentane_groups = "[{ \"Tc\": 508.1, \"acentric\": 0.3071, \"groups\": [ { \"count\": 1, \"sgi\": 1 }, {\"count\": 1, \"sgi\": 18 } ], \"molemass\": 0.44, \"inchikey\": \"?????????????\", \"name\": \"Acetone\", \"pc\": 4700000.0, \"registry_number\": \"67-64-1\", \"userid\": \"\" }, { \"Tc\": 469.7000000000001, \"acentric\": 0.251, \"molemass\": 0.44, \"groups\": [ { \"count\": 2, \"sgi\": 1 }, { \"count\": 3, \"sgi\": 2 } ], \"inchikey\": \"?????????????\", \"name\": \"n-Pentane\", \"pc\": 3370000.0, \"registry_number\": \"109-66-0\", \"userid\": \"\" } ]"; std::string groups = "[{\"Q_k\": 0.848, \"R_k\": 0.9011, \"maingroup_name\": \"CH2\", \"mgi\": 1, \"sgi\": 1, \"subgroup_name\": \"CH3\"}," "{\"Q_k\": 0.540, \"R_k\": 0.6744, \"maingroup_name\": \"CH2\", \"mgi\": 1, \"sgi\": 2, \"subgroup_name\": \"CH2\"}," "{\"Q_k\": 1.488, \"R_k\": 1.6724, \"maingroup_name\": \"CH2CO\", \"mgi\": 9, \"sgi\": 18, \"subgroup_name\": \"CH3CO\"}]"; std::string interactions = "[{\"a_ij\": 476.4, \"a_ji\": 26.76, \"b_ij\": 0.0, \"b_ji\": 0.0, \"c_ij\": 0.0, \"c_ji\": 0.0, \"mgi1\": 1, \"mgi2\": 9}]"; SECTION("Validate AC for acetone + n-pentane") { UNIFAQLibrary::UNIFAQParameterLibrary lib; CHECK_NOTHROW(lib.populate(groups, interactions, acetone_pentane_groups);); UNIFAQ::UNIFAQMixture mix(lib,1.0); std::vector<std::string> names; names.push_back("Acetone"); names.push_back("n-Pentane"); mix.set_components("name",names); mix.set_interaction_parameters(); std::vector<double> z(2,0.047); z[1] = 1-z[0]; mix.set_mole_fractions(z); CHECK_NOTHROW(mix.set_temperature(307);); double lngammaR0 = mix.ln_gamma_R(1.0/307,0,0); double lngammaR1 = mix.ln_gamma_R(1.0/307,1,0); CAPTURE(lngammaR0); CAPTURE(lngammaR1); CHECK(std::abs(lngammaR0 - 1.66) < 1e-2); CHECK(std::abs(lngammaR1 - 5.68e-3) < 1e-3); std::vector<double> gamma(2); mix.activity_coefficients(1.0/307,z,gamma); CAPTURE(gamma[0]); CAPTURE(gamma[1]); CHECK(std::abs(gamma[0] - 4.99) < 1e-2); CHECK(std::abs(gamma[1] - 1.005) < 1e-3); }; }; #endif <|endoftext|>
<commit_before>// Copyright eeGeo Ltd (2012-2015), All Rights Reserved #include "CompassModel.h" #include "EnvironmentFlatteningService.h" #include "IAppCameraController.h" #include "CameraHelpers.h" #include "RenderCamera.h" #include "VectorMath.h" #include "NavigationService.h" #include "ILocationService.h" #include "LatLongAltitude.h" #include "IAppModeModel.h" #include "IAlertBoxFactory.h" #include "InteriorsExplorerModel.h" #include "InteriorNavigationHelpers.h" #include "InteriorsCameraController.h" namespace ExampleApp { namespace Compass { namespace SdkModel { CompassModel::CompassModel(Eegeo::Location::NavigationService& navigationService, Eegeo::Resources::Interiors::InteriorInteractionModel& interiorInteractionModel, Eegeo::Location::ILocationService& locationService, ExampleApp::AppCamera::SdkModel::IAppCameraController& cameraController, Metrics::IMetricsService& metricsService, InteriorsExplorer::SdkModel::InteriorsExplorerModel& interiorExplorerModel, AppModes::SdkModel::IAppModeModel& appModeModel, Eegeo::UI::NativeAlerts::IAlertBoxFactory& alertBoxFactory, bool isInKioskMode) : m_navigationService(navigationService) , m_interiorInteractionModel(interiorInteractionModel) , m_locationService(locationService) , m_cameraController(cameraController) , m_metricsService(metricsService) , m_interiorExplorerModel(interiorExplorerModel) , m_appModeModel(appModeModel) , m_appModeChangedCallback(this, &CompassModel::OnAppModeChanged) , m_alertBoxFactory(alertBoxFactory) , m_failAlertHandler(this, &CompassModel::OnFailedToGetLocation) , m_interiorFloorChangedCallback(this, &CompassModel::OnInteriorFloorChanged) , m_exitInteriorTriggered(false) , m_isInKioskMode(isInKioskMode) { m_compassGpsModeToNavigationGpsMode[Eegeo::Location::NavigationService::GpsModeOff] = GpsMode::GpsDisabled; m_compassGpsModeToNavigationGpsMode[Eegeo::Location::NavigationService::GpsModeFollow] = GpsMode::GpsFollow; m_compassGpsModeToNavigationGpsMode[Eegeo::Location::NavigationService::GpsModeCompass] = GpsMode::GpsCompassMode; m_navigationGpsModeToCompassGpsMode[GpsMode::GpsDisabled] = Eegeo::Location::NavigationService::GpsModeOff; m_navigationGpsModeToCompassGpsMode[GpsMode::GpsFollow] = Eegeo::Location::NavigationService::GpsModeFollow; m_navigationGpsModeToCompassGpsMode[GpsMode::GpsCompassMode] = Eegeo::Location::NavigationService::GpsModeCompass; m_gpsModeToString[GpsMode::GpsDisabled] = "GpsDisabled"; m_gpsModeToString[GpsMode::GpsFollow] = "GpsFollow"; m_gpsModeToString[GpsMode::GpsCompassMode] = "GpsCompassMode"; m_appModeModel.RegisterAppModeChangedCallback(m_appModeChangedCallback); m_interiorExplorerModel.InsertInteriorExplorerFloorSelectionDraggedCallback(m_interiorFloorChangedCallback); } CompassModel::~CompassModel() { m_interiorExplorerModel.RemoveInteriorExplorerFloorSelectionDraggedCallback(m_interiorFloorChangedCallback); m_appModeModel.UnregisterAppModeChangedCallback(m_appModeChangedCallback); } bool CompassModel::GetGpsModeActive() const { return GetGpsMode() != GpsMode::GpsDisabled; } GpsMode::Values CompassModel::GetGpsMode() const { return m_gpsMode; } void CompassModel::CycleToNextGpsMode() { if(!m_locationService.GetIsAuthorized()) { DisableGpsMode(); m_gpsModeUnauthorizedCallbacks.ExecuteCallbacks(); return; } Eegeo::Space::LatLong latlong = Eegeo::Space::LatLong::FromDegrees(0.0, 0.0); if(!m_locationService.GetLocation(latlong)) { m_alertBoxFactory.CreateSingleOptionAlertBox("Failed to obtain location", "Could not get the device location. Please ensure you have GPS enabled", m_failAlertHandler); DisableGpsMode(); return; } int gpsMode = static_cast<int>(m_gpsMode); gpsMode = (gpsMode + 1) % static_cast<int>(GpsMode::GpsMode_Max); GpsMode::Values newGpsMode = static_cast<GpsMode::Values>(gpsMode); if(GetGpsModeActive() && newGpsMode == GpsMode::GpsDisabled) { m_gpsMode = newGpsMode; CycleToNextGpsMode(); } else { SetGpsMode(newGpsMode); } } bool CompassModel::NeedsToExitInterior(GpsMode::Values gpsMode) { const AppModes::SdkModel::AppMode appMode = m_appModeModel.GetAppMode(); return ((appMode != AppModes::SdkModel::WorldMode) && !m_exitInteriorTriggered && (gpsMode != GpsMode::GpsDisabled) && !Helpers::InteriorNavigationHelpers::IsPositionInInterior(m_interiorInteractionModel, m_locationService)) && !m_locationService.IsIndoors(); } void CompassModel::TryUpdateToNavigationServiceGpsMode(Eegeo::Location::NavigationService::GpsMode value) { if(!m_locationService.GetIsAuthorized()) { DisableGpsMode(); return; } GpsMode::Values gpsModeValueFromNavigationService = m_compassGpsModeToNavigationGpsMode[value]; // override value if we know we are using navigation service if(m_exitInteriorTriggered) { gpsModeValueFromNavigationService = m_compassGpsModeToNavigationGpsMode[m_navigationService.GetGpsMode()]; } bool forceSetGpsMode = false; const AppModes::SdkModel::AppMode appMode = m_appModeModel.GetAppMode(); if (NeedsToExitInterior(gpsModeValueFromNavigationService)) { m_interiorExplorerModel.Exit(); m_exitInteriorTriggered = true; forceSetGpsMode = true; } else if (appMode == AppModes::SdkModel::WorldMode) { m_exitInteriorTriggered = false; } if(forceSetGpsMode || gpsModeValueFromNavigationService != GetGpsMode()) { SetGpsMode(gpsModeValueFromNavigationService); } } void CompassModel::DisableGpsMode() { if (GetGpsMode() != GpsMode::GpsDisabled) { SetGpsMode(GpsMode::GpsDisabled); } } void CompassModel::SetGpsMode(GpsMode::Values gpsMode) { m_gpsMode = gpsMode; m_navigationService.SetGpsMode(m_navigationGpsModeToCompassGpsMode[m_gpsMode]); m_metricsService.SetEvent("SetGpsMode", "GpsMode", m_gpsModeToString[m_gpsMode]); m_gpsModeChangedCallbacks.ExecuteCallbacks(); } float CompassModel::GetHeadingRadians() const { const Eegeo::Camera::RenderCamera renderCamera = m_cameraController.GetRenderCamera(); const Eegeo::m44& cameraModelMatrix = renderCamera.GetModelMatrix(); const Eegeo::v3& viewDirection = cameraModelMatrix.GetRow(2); Eegeo::v3 ecefUp = renderCamera.GetEcefLocation().ToSingle().Norm(); const float epsilon = 0.001f; Eegeo::v3 heading; if (Eegeo::Math::Abs(Eegeo::v3::Dot(viewDirection, ecefUp)) > (1.f - epsilon)) { const Eegeo::v3& viewUp = cameraModelMatrix.GetRow(1); heading = viewUp; } else { heading = viewDirection; } return Eegeo::Camera::CameraHelpers::GetAbsoluteBearingRadians(renderCamera.GetEcefLocation(), heading); } float CompassModel::GetHeadingDegrees() const { float headingRadians = GetHeadingRadians(); return Eegeo::Math::Rad2Deg(headingRadians); } void CompassModel::InsertGpsModeChangedCallback(Eegeo::Helpers::ICallback0& callback) { m_gpsModeChangedCallbacks.AddCallback(callback); } void CompassModel::RemoveGpsModeChangedCallback(Eegeo::Helpers::ICallback0& callback) { m_gpsModeChangedCallbacks.RemoveCallback(callback); } void CompassModel::InsertGpsModeUnauthorizedCallback(Eegeo::Helpers::ICallback0 &callback) { m_gpsModeUnauthorizedCallbacks.AddCallback(callback); } void CompassModel::RemoveGpsModeUnauthorizedCallback(Eegeo::Helpers::ICallback0 &callback) { m_gpsModeUnauthorizedCallbacks.RemoveCallback(callback); } void CompassModel::OnAppModeChanged() { const AppModes::SdkModel::AppMode appMode = m_appModeModel.GetAppMode(); if (appMode != AppModes::SdkModel::WorldMode && !m_isInKioskMode) { DisableGpsMode(); return; } } void CompassModel::OnInteriorFloorChanged() { DisableGpsMode(); } void CompassModel::OnFailedToGetLocation() { Eegeo_TTY("Failed to get compass location"); } float CompassModel::GetIndoorsHeadingRadians() const { double heading; return m_isInKioskMode && m_locationService.GetHeadingDegrees(heading) ? Eegeo::Math::Deg2Rad(heading) : GetHeadingRadians(); } } } } <commit_msg>Attemp to fix MPLY-8357: check current indoor id when deciding if the compass should exit the current interior. Buddy: Malcolm.<commit_after>// Copyright eeGeo Ltd (2012-2015), All Rights Reserved #include "CompassModel.h" #include "EnvironmentFlatteningService.h" #include "IAppCameraController.h" #include "CameraHelpers.h" #include "RenderCamera.h" #include "VectorMath.h" #include "NavigationService.h" #include "ILocationService.h" #include "LatLongAltitude.h" #include "IAppModeModel.h" #include "IAlertBoxFactory.h" #include "InteriorsExplorerModel.h" #include "InteriorNavigationHelpers.h" #include "InteriorsCameraController.h" #include "InteriorsModel.h" namespace ExampleApp { namespace Compass { namespace SdkModel { CompassModel::CompassModel(Eegeo::Location::NavigationService& navigationService, Eegeo::Resources::Interiors::InteriorInteractionModel& interiorInteractionModel, Eegeo::Location::ILocationService& locationService, ExampleApp::AppCamera::SdkModel::IAppCameraController& cameraController, Metrics::IMetricsService& metricsService, InteriorsExplorer::SdkModel::InteriorsExplorerModel& interiorExplorerModel, AppModes::SdkModel::IAppModeModel& appModeModel, Eegeo::UI::NativeAlerts::IAlertBoxFactory& alertBoxFactory, bool isInKioskMode) : m_navigationService(navigationService) , m_interiorInteractionModel(interiorInteractionModel) , m_locationService(locationService) , m_cameraController(cameraController) , m_metricsService(metricsService) , m_interiorExplorerModel(interiorExplorerModel) , m_appModeModel(appModeModel) , m_appModeChangedCallback(this, &CompassModel::OnAppModeChanged) , m_alertBoxFactory(alertBoxFactory) , m_failAlertHandler(this, &CompassModel::OnFailedToGetLocation) , m_interiorFloorChangedCallback(this, &CompassModel::OnInteriorFloorChanged) , m_exitInteriorTriggered(false) , m_isInKioskMode(isInKioskMode) { m_compassGpsModeToNavigationGpsMode[Eegeo::Location::NavigationService::GpsModeOff] = GpsMode::GpsDisabled; m_compassGpsModeToNavigationGpsMode[Eegeo::Location::NavigationService::GpsModeFollow] = GpsMode::GpsFollow; m_compassGpsModeToNavigationGpsMode[Eegeo::Location::NavigationService::GpsModeCompass] = GpsMode::GpsCompassMode; m_navigationGpsModeToCompassGpsMode[GpsMode::GpsDisabled] = Eegeo::Location::NavigationService::GpsModeOff; m_navigationGpsModeToCompassGpsMode[GpsMode::GpsFollow] = Eegeo::Location::NavigationService::GpsModeFollow; m_navigationGpsModeToCompassGpsMode[GpsMode::GpsCompassMode] = Eegeo::Location::NavigationService::GpsModeCompass; m_gpsModeToString[GpsMode::GpsDisabled] = "GpsDisabled"; m_gpsModeToString[GpsMode::GpsFollow] = "GpsFollow"; m_gpsModeToString[GpsMode::GpsCompassMode] = "GpsCompassMode"; m_appModeModel.RegisterAppModeChangedCallback(m_appModeChangedCallback); m_interiorExplorerModel.InsertInteriorExplorerFloorSelectionDraggedCallback(m_interiorFloorChangedCallback); } CompassModel::~CompassModel() { m_interiorExplorerModel.RemoveInteriorExplorerFloorSelectionDraggedCallback(m_interiorFloorChangedCallback); m_appModeModel.UnregisterAppModeChangedCallback(m_appModeChangedCallback); } bool CompassModel::GetGpsModeActive() const { return GetGpsMode() != GpsMode::GpsDisabled; } GpsMode::Values CompassModel::GetGpsMode() const { return m_gpsMode; } void CompassModel::CycleToNextGpsMode() { if(!m_locationService.GetIsAuthorized()) { DisableGpsMode(); m_gpsModeUnauthorizedCallbacks.ExecuteCallbacks(); return; } Eegeo::Space::LatLong latlong = Eegeo::Space::LatLong::FromDegrees(0.0, 0.0); if(!m_locationService.GetLocation(latlong)) { m_alertBoxFactory.CreateSingleOptionAlertBox("Failed to obtain location", "Could not get the device location. Please ensure you have GPS enabled", m_failAlertHandler); DisableGpsMode(); return; } int gpsMode = static_cast<int>(m_gpsMode); gpsMode = (gpsMode + 1) % static_cast<int>(GpsMode::GpsMode_Max); GpsMode::Values newGpsMode = static_cast<GpsMode::Values>(gpsMode); if(GetGpsModeActive() && newGpsMode == GpsMode::GpsDisabled) { m_gpsMode = newGpsMode; CycleToNextGpsMode(); } else { SetGpsMode(newGpsMode); } } bool CompassModel::NeedsToExitInterior(GpsMode::Values gpsMode) { const AppModes::SdkModel::AppMode appMode = m_appModeModel.GetAppMode(); const bool gpsIsEnabled = gpsMode != GpsMode::GpsDisabled; const bool notCurrentlyExitingToWorldMode = appMode != AppModes::SdkModel::WorldMode && !m_exitInteriorTriggered; const Eegeo::Resources::Interiors::InteriorsModel* selectedInteriorModel = m_interiorInteractionModel.GetInteriorModel(); const bool notInCurrentInterior = !(m_locationService.IsIndoors() && selectedInteriorModel != nullptr && m_locationService.GetInteriorId() == selectedInteriorModel->GetId() && Helpers::InteriorNavigationHelpers::IsPositionInInterior(m_interiorInteractionModel, m_locationService)); return gpsIsEnabled && notCurrentlyExitingToWorldMode && notInCurrentInterior; } void CompassModel::TryUpdateToNavigationServiceGpsMode(Eegeo::Location::NavigationService::GpsMode value) { if(!m_locationService.GetIsAuthorized()) { DisableGpsMode(); return; } GpsMode::Values gpsModeValueFromNavigationService = m_compassGpsModeToNavigationGpsMode[value]; // override value if we know we are using navigation service if(m_exitInteriorTriggered) { gpsModeValueFromNavigationService = m_compassGpsModeToNavigationGpsMode[m_navigationService.GetGpsMode()]; } bool forceSetGpsMode = false; const AppModes::SdkModel::AppMode appMode = m_appModeModel.GetAppMode(); if (NeedsToExitInterior(gpsModeValueFromNavigationService)) { m_interiorExplorerModel.Exit(); m_exitInteriorTriggered = true; forceSetGpsMode = true; } else if (appMode == AppModes::SdkModel::WorldMode) { m_exitInteriorTriggered = false; } if(forceSetGpsMode || gpsModeValueFromNavigationService != GetGpsMode()) { SetGpsMode(gpsModeValueFromNavigationService); } } void CompassModel::DisableGpsMode() { if (GetGpsMode() != GpsMode::GpsDisabled) { SetGpsMode(GpsMode::GpsDisabled); } } void CompassModel::SetGpsMode(GpsMode::Values gpsMode) { m_gpsMode = gpsMode; m_navigationService.SetGpsMode(m_navigationGpsModeToCompassGpsMode[m_gpsMode]); m_metricsService.SetEvent("SetGpsMode", "GpsMode", m_gpsModeToString[m_gpsMode]); m_gpsModeChangedCallbacks.ExecuteCallbacks(); } float CompassModel::GetHeadingRadians() const { const Eegeo::Camera::RenderCamera renderCamera = m_cameraController.GetRenderCamera(); const Eegeo::m44& cameraModelMatrix = renderCamera.GetModelMatrix(); const Eegeo::v3& viewDirection = cameraModelMatrix.GetRow(2); Eegeo::v3 ecefUp = renderCamera.GetEcefLocation().ToSingle().Norm(); const float epsilon = 0.001f; Eegeo::v3 heading; if (Eegeo::Math::Abs(Eegeo::v3::Dot(viewDirection, ecefUp)) > (1.f - epsilon)) { const Eegeo::v3& viewUp = cameraModelMatrix.GetRow(1); heading = viewUp; } else { heading = viewDirection; } return Eegeo::Camera::CameraHelpers::GetAbsoluteBearingRadians(renderCamera.GetEcefLocation(), heading); } float CompassModel::GetHeadingDegrees() const { float headingRadians = GetHeadingRadians(); return Eegeo::Math::Rad2Deg(headingRadians); } void CompassModel::InsertGpsModeChangedCallback(Eegeo::Helpers::ICallback0& callback) { m_gpsModeChangedCallbacks.AddCallback(callback); } void CompassModel::RemoveGpsModeChangedCallback(Eegeo::Helpers::ICallback0& callback) { m_gpsModeChangedCallbacks.RemoveCallback(callback); } void CompassModel::InsertGpsModeUnauthorizedCallback(Eegeo::Helpers::ICallback0 &callback) { m_gpsModeUnauthorizedCallbacks.AddCallback(callback); } void CompassModel::RemoveGpsModeUnauthorizedCallback(Eegeo::Helpers::ICallback0 &callback) { m_gpsModeUnauthorizedCallbacks.RemoveCallback(callback); } void CompassModel::OnAppModeChanged() { const AppModes::SdkModel::AppMode appMode = m_appModeModel.GetAppMode(); if (appMode != AppModes::SdkModel::WorldMode && !m_isInKioskMode) { DisableGpsMode(); return; } } void CompassModel::OnInteriorFloorChanged() { DisableGpsMode(); } void CompassModel::OnFailedToGetLocation() { Eegeo_TTY("Failed to get compass location"); } float CompassModel::GetIndoorsHeadingRadians() const { double heading; return m_isInKioskMode && m_locationService.GetHeadingDegrees(heading) ? Eegeo::Math::Deg2Rad(heading) : GetHeadingRadians(); } } } } <|endoftext|>
<commit_before>/************************************************ Scanner This file which operate scanning represents one node of the entire demonstrator ************************************************/ // Standard headers #include <string> #include <iostream> // ROS headers #include <ros/ros.h> #include <ros/service.h> #include <tf/transform_listener.h> #include <tf_conversions/tf_eigen.h> #include <eigen_conversions/eigen_msg.h> #include <std_msgs/String.h> #include <yaml-cpp/exceptions.h> #include <yaml-cpp/mark.h> #include <scanning/ScanningService.h> // Description of the Service we will use #include <execute_joint_state/ExecuteJointStateService.h> // We will call this service #include <publish_meshfile/PublishMeshfileService.h> #include "yaml_utils.h" // PCL headers #include <pcl/point_cloud.h> #include <pcl/common/colors.h> #include <pcl/common/transforms.h> #include <pcl/io/davidsdk_grabber.h> #include <pcl/io/ply_io.h> #include <pcl/filters/voxel_grid.h> // PCL davidSDK object pointer pcl::DavidSDKGrabber::Ptr davidsdk_ptr; typedef pcl::PointXYZ PointXYZ; typedef pcl::PointCloud<PointXYZ> PointCloudXYZ; boost::shared_ptr<ros::NodeHandle> node; /** Status publisher */ boost::shared_ptr<ros::Publisher> status_pub; /** * This is the service function that is called whenever a request is received * @param req[int] * @param res[out] * @return Always true */ bool moveRobotScan(scanning::ScanningService::Request &req, scanning::ScanningService::Response &res) { std_msgs::String status; status.data = "Parsing YAML trajectory file"; status_pub->publish(status); // Parse YAML File const std::string filename= req.YamlFileName; std::string reference_frame; std::string tool_reference; std::vector<double> joint; std::vector<std::vector<double> > joint_list; try { YAML::Node yamlFile; yaml_parser::yamlNodeFromFileName(filename, yamlFile); // Parse "reference" node in YAML file // Just say no node if no node -->exception const YAML::Node & reference_node = yaml_parser::parseNode(yamlFile, "reference"); if(!yamlFile["reference"]) { YAML::Mark mark; YAML::Exception yaml_exception(mark, "Cannot parse 'reference' node"); throw yaml_exception; } // Parse "reference_frame" tag in "reference" node in YAML file yaml_parser::parseString(reference_node, "reference_frame", reference_frame); // Parse "tool" node in YAML file const YAML::Node & tool_node = yaml_parser::parseNode(yamlFile, "tool"); if(!yamlFile["tool"]) { YAML::Mark mark; YAML::Exception yaml_exception(mark,"Cannot parse 'tool' node"); throw yaml_exception; } // Parse "tool_reference" tag in "tool" node in YAML file yaml_parser::parseString(tool_node, "tool_reference", tool_reference); // Parse "joint_values" node in YAML file const YAML::Node & joint_node = yaml_parser::parseNode(yamlFile, "joint_values"); if(!yamlFile["joint_values"]) { YAML::Mark mark; YAML::Exception yaml_exception(mark,"Cannot parse 'joint_values' node"); throw yaml_exception; } // Parse all "joint" tag in "joint_values" node in YAML file for(unsigned j = 0; j < joint_node.size(); ++ j) { yaml_parser::parseVectorD(joint_node[j], "joint", joint); joint_list.push_back(joint); } } catch(const YAML::Exception &e) { res.ReturnStatus = false; res.ReturnMessage = "Problem occurred during parsing yaml file for joint values, problem is: " + e.msg; return true; } // Parse YAML file in order to obtain sls_2_calibration matrix status.data = "Parsing YAML calibration file"; status_pub->publish(status); const std::string filenameCalibration= req.YamlCalibrationFileName; std::vector<double> n_vector; std::vector<double> o_vector; std::vector<double> a_vector; std::vector<double> p_vector; try { YAML::Node yamlFileCalibration; yaml_parser::yamlNodeFromFileName(filenameCalibration, yamlFileCalibration); // Parse all tags in "sls_2_calibration_values" node in YAML file const YAML::Node& sls_2_node = yaml_parser::parseNode(yamlFileCalibration, "sls_2_calibration_values"); if(!yamlFileCalibration["sls_2_calibration_values"]) { YAML::Mark mark; YAML::Exception yaml_exception(mark,"Cannot parse 'sls_2_calibration_values'"); throw yaml_exception; } yaml_parser::parseVectorD(sls_2_node[0], "n", n_vector); yaml_parser::parseVectorD(sls_2_node[1], "o", o_vector); yaml_parser::parseVectorD(sls_2_node[2], "a", a_vector); yaml_parser::parseVectorD(sls_2_node[3], "p", p_vector); } catch (const YAML::Exception &e) { res.ReturnStatus = false; res.ReturnMessage = "Problem parsing YAML calibration file, error:\n" + e.msg; return true; } // We fill the calibration_sls2 transformation matrix with values contained in the YAML file Eigen::Affine3d calib_sls_2; calib_sls_2.matrix() << n_vector[0], o_vector[0], a_vector[0], p_vector[0], n_vector[1], o_vector[1], a_vector[1], p_vector[1], n_vector[2], o_vector[2], a_vector[2], p_vector[2], n_vector[3], o_vector[3], a_vector[3], p_vector[3]; // We have to invert this matrix in order to give point cloud in a correct frame calib_sls_2 = calib_sls_2.inverse(); // Declaration of ROS listener tf::TransformListener listener; // Grab transformation between /sls_2_frame and tool0 tf::StampedTransform transform_sls_2_tool0; Eigen::Affine3d calibration; listener.waitForTransform("/base", "/sls_2_frame", ros::Time(0), ros::Duration(1.5)); listener.lookupTransform("/tool0", "/sls_2_frame", ros::Time(0), transform_sls_2_tool0); tf::transformTFToEigen(transform_sls_2_tool0, calibration); // Connect SLS-2 Camera status.data = "Connecting to SLS-2 server..."; status_pub->publish(status); std::string davidSDK_ip = req.SLS2IpAddress; std::string davidSDK_server_name = req.SLS2ServerName; // Connect to the SLS_2 davidsdk_ptr.reset(new pcl::DavidSDKGrabber); ROS_INFO_STREAM("Trying to connect to DavidSDK IP \"" << davidSDK_ip << "\" and server name \"" << davidSDK_server_name << "\""); davidsdk_ptr->connect(davidSDK_ip); if (!davidsdk_ptr->isConnected()) { ROS_ERROR_STREAM("Cannot connect to the David SLS-2 scanner (IP: " << davidSDK_ip << ")"); ROS_ERROR_STREAM("Server name: " << davidSDK_server_name); res.ReturnStatus = false; res.ReturnMessage = "Cannot connect to the David SLS-2 scanner"; return true; } davidsdk_ptr->setLocalAndRemotePaths("/var/tmp/davidsdk/", "\\\\" + davidSDK_server_name + "\\davidsdk\\"); davidsdk_ptr->setFileFormatToSTL(); // Best performance status.data = "SLS-2 connected"; status_pub->publish(status); // Create entire point cloud PointCloudXYZ::Ptr stacked_point_cloud (new PointCloudXYZ()); // For each joint state, we call a service which execute this joint state execute_joint_state::ExecuteJointStateService srv_execute_joint_state; ros::ServiceClient execute_joint_state_service = node->serviceClient<execute_joint_state::ExecuteJointStateService>("execute_joint_state_service"); for(unsigned k = 0; k < joint_list.size(); ++k) { // Add the joint state into the request for(unsigned j = 0; j < joint.size(); ++j) srv_execute_joint_state.request.JointState[j]=joint_list[k][j]; execute_joint_state_service.call(srv_execute_joint_state); if(srv_execute_joint_state.response.ReturnStatus == false) { res.ReturnStatus = false; res.ReturnMessage = "Problem occurred during scanning.\n" + srv_execute_joint_state.response.ReturnMessage; return true; } else { // Grab robot transform tf::StampedTransform transform; sleep(1); listener.waitForTransform("/base", "/sls_2_frame", ros::Time::now(), ros::Duration(1.5)); listener.lookupTransform("/base_link", "/tool0", ros::Time(0), transform); Eigen::Affine3d matrix_transform; tf::transformTFToEigen(transform, matrix_transform); // Grab point cloud PointCloudXYZ::Ptr point_cloud (new PointCloudXYZ()); if (!davidsdk_ptr->grabSingleCloud(*point_cloud)) { res.ReturnStatus = false; res.ReturnMessage = "Could not capture point cloud"; return true; } status.data = "Point cloud " + boost::lexical_cast<std::string>(k + 1) + "/" + boost::lexical_cast<std::string>(joint_list.size()) + " captured"; status_pub->publish(status); // Transform point cloud in order into the robot frame Eigen::Affine3d transformation_pc(Eigen::Affine3d::Identity()); transformation_pc = matrix_transform * calibration * calib_sls_2; transformation_pc *= 0.001; // Transform millimeters to meters pcl::transformPointCloud(*point_cloud, *point_cloud, transformation_pc); // Store it into global point cloud *stacked_point_cloud += *point_cloud; } } // Apply a voxel grid to make entire point cloud homogeneous status.data = "Applying voxel grid on point clouds"; status_pub->publish(status); pcl::VoxelGrid<PointXYZ> sor; sor.setLeafSize (req.VoxelGridLeafSize, req.VoxelGridLeafSize, req.VoxelGridLeafSize); sor.setInputCloud (stacked_point_cloud); sor.filter (*stacked_point_cloud); if(stacked_point_cloud->size() == 0) { res.ReturnStatus = false; res.ReturnMessage = "Filtered point cloud is empty"; return true; } // Save the point cloud with CAD meshname and a suffix res.NumerizedMeshName = req.CADName.substr(0, req.CADName.size() - 4) + "_defect.ply"; pcl::io::savePLYFileBinary(res.NumerizedMeshName, *stacked_point_cloud); // Call publish_meshfile service publish_meshfile::PublishMeshfileService srv_publish_meshfile; ros::ServiceClient publish_meshfile_service = node->serviceClient<publish_meshfile::PublishMeshfileService>("publish_meshfile_service"); // Publish final point cloud status.data = "Publishing final point cloud"; status_pub->publish(status); srv_publish_meshfile.request.MeshName = res.NumerizedMeshName; srv_publish_meshfile.request.MarkerName = req.MarkerName; srv_publish_meshfile.request.PosX = srv_publish_meshfile.request.PosY = srv_publish_meshfile.request.PosZ = srv_publish_meshfile.request.RotX = srv_publish_meshfile.request.RotY = srv_publish_meshfile.request.RotZ = 0.0; srv_publish_meshfile.request.RotW = 1.0; publish_meshfile_service.call(srv_publish_meshfile); res.ReturnStatus = true; boost::filesystem::path p(res.NumerizedMeshName); res.ReturnMessage = "Scan succeeded, file:\n" + p.filename().string(); return true; } int main(int argc, char **argv) { ros::init(argc, argv, "scanning"); node.reset(new ros::NodeHandle); status_pub.reset(new ros::Publisher); *status_pub = node->advertise<std_msgs::String>("scanning_status", 1); // Create service server and wait for incoming requests ros::ServiceServer service = node->advertiseService("scanning_service", moveRobotScan); ros::AsyncSpinner spinner(1); spinner.start(); while (node->ok()) { } return 0; } <commit_msg>Fix bug with tranformation matrix<commit_after>/************************************************ Scanner This file which operate scanning represents one node of the entire demonstrator ************************************************/ // Standard headers #include <string> #include <iostream> // ROS headers #include <ros/ros.h> #include <ros/service.h> #include <tf/transform_listener.h> #include <tf_conversions/tf_eigen.h> #include <eigen_conversions/eigen_msg.h> #include <std_msgs/String.h> #include <yaml-cpp/exceptions.h> #include <yaml-cpp/mark.h> #include <scanning/ScanningService.h> // Description of the Service we will use #include <execute_joint_state/ExecuteJointStateService.h> // We will call this service #include <publish_meshfile/PublishMeshfileService.h> #include "yaml_utils.h" // PCL headers #include <pcl/point_cloud.h> #include <pcl/common/colors.h> #include <pcl/common/transforms.h> #include <pcl/io/davidsdk_grabber.h> #include <pcl/io/ply_io.h> #include <pcl/filters/voxel_grid.h> // PCL davidSDK object pointer pcl::DavidSDKGrabber::Ptr davidsdk_ptr; typedef pcl::PointXYZ PointXYZ; typedef pcl::PointCloud<PointXYZ> PointCloudXYZ; boost::shared_ptr<ros::NodeHandle> node; /** Status publisher */ boost::shared_ptr<ros::Publisher> status_pub; /** * This is the service function that is called whenever a request is received * @param req[int] * @param res[out] * @return Always true */ bool moveRobotScan(scanning::ScanningService::Request &req, scanning::ScanningService::Response &res) { std_msgs::String status; status.data = "Parsing YAML trajectory file"; status_pub->publish(status); // Parse YAML File const std::string filename= req.YamlFileName; std::string reference_frame; std::string tool_reference; std::vector<double> joint; std::vector<std::vector<double> > joint_list; try { YAML::Node yamlFile; yaml_parser::yamlNodeFromFileName(filename, yamlFile); // Parse "reference" node in YAML file // Just say no node if no node -->exception const YAML::Node & reference_node = yaml_parser::parseNode(yamlFile, "reference"); if(!yamlFile["reference"]) { YAML::Mark mark; YAML::Exception yaml_exception(mark, "Cannot parse 'reference' node"); throw yaml_exception; } // Parse "reference_frame" tag in "reference" node in YAML file yaml_parser::parseString(reference_node, "reference_frame", reference_frame); // Parse "tool" node in YAML file const YAML::Node & tool_node = yaml_parser::parseNode(yamlFile, "tool"); if(!yamlFile["tool"]) { YAML::Mark mark; YAML::Exception yaml_exception(mark,"Cannot parse 'tool' node"); throw yaml_exception; } // Parse "tool_reference" tag in "tool" node in YAML file yaml_parser::parseString(tool_node, "tool_reference", tool_reference); // Parse "joint_values" node in YAML file const YAML::Node & joint_node = yaml_parser::parseNode(yamlFile, "joint_values"); if(!yamlFile["joint_values"]) { YAML::Mark mark; YAML::Exception yaml_exception(mark,"Cannot parse 'joint_values' node"); throw yaml_exception; } // Parse all "joint" tag in "joint_values" node in YAML file for(unsigned j = 0; j < joint_node.size(); ++ j) { yaml_parser::parseVectorD(joint_node[j], "joint", joint); joint_list.push_back(joint); } } catch(const YAML::Exception &e) { res.ReturnStatus = false; res.ReturnMessage = "Problem occurred during parsing yaml file for joint values, problem is: " + e.msg; return true; } // Parse YAML file in order to obtain sls_2_calibration matrix status.data = "Parsing YAML calibration file"; status_pub->publish(status); const std::string filenameCalibration= req.YamlCalibrationFileName; std::vector<double> n_vector; std::vector<double> o_vector; std::vector<double> a_vector; std::vector<double> p_vector; try { YAML::Node yamlFileCalibration; yaml_parser::yamlNodeFromFileName(filenameCalibration, yamlFileCalibration); // Parse all tags in "sls_2_calibration_values" node in YAML file const YAML::Node& sls_2_node = yaml_parser::parseNode(yamlFileCalibration, "sls_2_calibration_values"); if(!yamlFileCalibration["sls_2_calibration_values"]) { YAML::Mark mark; YAML::Exception yaml_exception(mark,"Cannot parse 'sls_2_calibration_values'"); throw yaml_exception; } yaml_parser::parseVectorD(sls_2_node[0], "n", n_vector); yaml_parser::parseVectorD(sls_2_node[1], "o", o_vector); yaml_parser::parseVectorD(sls_2_node[2], "a", a_vector); yaml_parser::parseVectorD(sls_2_node[3], "p", p_vector); } catch (const YAML::Exception &e) { res.ReturnStatus = false; res.ReturnMessage = "Problem parsing YAML calibration file, error:\n" + e.msg; return true; } // We fill the calibration_sls2 transformation matrix with values contained in the YAML file Eigen::Affine3d calib_sls_2; calib_sls_2.matrix() << n_vector[0], o_vector[0], a_vector[0], p_vector[0], n_vector[1], o_vector[1], a_vector[1], p_vector[1], n_vector[2], o_vector[2], a_vector[2], p_vector[2], n_vector[3], o_vector[3], a_vector[3], p_vector[3]; // We have to invert this matrix in order to give point cloud in a correct frame calib_sls_2 = calib_sls_2.inverse(); // Declaration of ROS listener tf::TransformListener listener; // Grab transformation between /sls_2_frame and tool0 tf::StampedTransform transform_sls_2_tool0; Eigen::Affine3d calibration; listener.waitForTransform("/base", "/sls_2_frame", ros::Time(0), ros::Duration(1.5)); listener.lookupTransform("/tool0", "/sls_2_frame", ros::Time(0), transform_sls_2_tool0); tf::transformTFToEigen(transform_sls_2_tool0, calibration); // Connect SLS-2 Camera status.data = "Connecting to SLS-2 server..."; status_pub->publish(status); std::string davidSDK_ip = req.SLS2IpAddress; std::string davidSDK_server_name = req.SLS2ServerName; // Connect to the SLS_2 davidsdk_ptr.reset(new pcl::DavidSDKGrabber); ROS_INFO_STREAM("Trying to connect to DavidSDK IP \"" << davidSDK_ip << "\" and server name \"" << davidSDK_server_name << "\""); davidsdk_ptr->connect(davidSDK_ip); if (!davidsdk_ptr->isConnected()) { ROS_ERROR_STREAM("Cannot connect to the David SLS-2 scanner (IP: " << davidSDK_ip << ")"); ROS_ERROR_STREAM("Server name: " << davidSDK_server_name); res.ReturnStatus = false; res.ReturnMessage = "Cannot connect to the David SLS-2 scanner"; return true; } davidsdk_ptr->setLocalAndRemotePaths("/var/tmp/davidsdk/", "\\\\" + davidSDK_server_name + "\\davidsdk\\"); davidsdk_ptr->setFileFormatToSTL(); // Best performance status.data = "SLS-2 connected"; status_pub->publish(status); // Create entire point cloud PointCloudXYZ::Ptr stacked_point_cloud (new PointCloudXYZ()); // For each joint state, we call a service which execute this joint state execute_joint_state::ExecuteJointStateService srv_execute_joint_state; ros::ServiceClient execute_joint_state_service = node->serviceClient<execute_joint_state::ExecuteJointStateService>("execute_joint_state_service"); for(unsigned k = 0; k < joint_list.size(); ++k) { // Add the joint state into the request for(unsigned j = 0; j < joint.size(); ++j) srv_execute_joint_state.request.JointState[j]=joint_list[k][j]; execute_joint_state_service.call(srv_execute_joint_state); if(srv_execute_joint_state.response.ReturnStatus == false) { res.ReturnStatus = false; res.ReturnMessage = "Problem occurred during scanning.\n" + srv_execute_joint_state.response.ReturnMessage; return true; } else { // Grab robot transform tf::StampedTransform transform; sleep(1); listener.waitForTransform("/base", "/sls_2_frame", ros::Time::now(), ros::Duration(1.5)); listener.lookupTransform("/base_link", "/tool0", ros::Time(0), transform); Eigen::Affine3d matrix_transform; tf::transformTFToEigen(transform, matrix_transform); // Grab point cloud PointCloudXYZ::Ptr point_cloud (new PointCloudXYZ()); if (!davidsdk_ptr->grabSingleCloud(*point_cloud)) { res.ReturnStatus = false; res.ReturnMessage = "Could not capture point cloud"; return true; } status.data = "Point cloud " + boost::lexical_cast<std::string>(k + 1) + "/" + boost::lexical_cast<std::string>(joint_list.size()) + " captured"; status_pub->publish(status); // Resize point cloud in meters Eigen::Affine3d resize_pc_meters(Eigen::Affine3d::Identity()); resize_pc_meters.matrix() *= 0.001; // Transform point cloud in order into the robot frame Eigen::Affine3d transformation_pc(Eigen::Affine3d::Identity()); transformation_pc = matrix_transform * calibration * calib_sls_2 * resize_pc_meters; pcl::transformPointCloud(*point_cloud, *point_cloud, transformation_pc); // Store it into global point cloud *stacked_point_cloud += *point_cloud; } } // Apply a voxel grid to make entire point cloud homogeneous status.data = "Applying voxel grid on point clouds"; status_pub->publish(status); pcl::VoxelGrid<PointXYZ> sor; sor.setLeafSize (req.VoxelGridLeafSize, req.VoxelGridLeafSize, req.VoxelGridLeafSize); sor.setInputCloud (stacked_point_cloud); sor.filter (*stacked_point_cloud); if(stacked_point_cloud->size() == 0) { res.ReturnStatus = false; res.ReturnMessage = "Filtered point cloud is empty"; return true; } // Save the point cloud with CAD meshname and a suffix res.NumerizedMeshName = req.CADName.substr(0, req.CADName.size() - 4) + "_defect.ply"; pcl::io::savePLYFileBinary(res.NumerizedMeshName, *stacked_point_cloud); // Call publish_meshfile service publish_meshfile::PublishMeshfileService srv_publish_meshfile; ros::ServiceClient publish_meshfile_service = node->serviceClient<publish_meshfile::PublishMeshfileService>("publish_meshfile_service"); // Publish final point cloud status.data = "Publishing final point cloud"; status_pub->publish(status); srv_publish_meshfile.request.MeshName = res.NumerizedMeshName; srv_publish_meshfile.request.MarkerName = req.MarkerName; srv_publish_meshfile.request.PosX = srv_publish_meshfile.request.PosY = srv_publish_meshfile.request.PosZ = srv_publish_meshfile.request.RotX = srv_publish_meshfile.request.RotY = srv_publish_meshfile.request.RotZ = 0.0; srv_publish_meshfile.request.RotW = 1.0; publish_meshfile_service.call(srv_publish_meshfile); res.ReturnStatus = true; boost::filesystem::path p(res.NumerizedMeshName); res.ReturnMessage = "Scan succeeded, file:\n" + p.filename().string(); return true; } int main(int argc, char **argv) { ros::init(argc, argv, "scanning"); node.reset(new ros::NodeHandle); status_pub.reset(new ros::Publisher); *status_pub = node->advertise<std_msgs::String>("scanning_status", 1); // Create service server and wait for incoming requests ros::ServiceServer service = node->advertiseService("scanning_service", moveRobotScan); ros::AsyncSpinner spinner(1); spinner.start(); while (node->ok()) { } return 0; } <|endoftext|>
<commit_before>#include "Messaging/RpcHandler.hpp" #include "Transports/AddressFactory.hpp" #include "Connection.hpp" #include "ConnectionManager.hpp" using Dissent::Transports::AddressFactory; namespace Dissent { namespace Connections { ConnectionManager::ConnectionManager(const Id &local_id, RpcHandler &rpc) : _inquire(this, &ConnectionManager::Inquire), _inquired(this, &ConnectionManager::Inquired), _close(this, &ConnectionManager::Close), _connect(this, &ConnectionManager::Connect), _disconnect(this, &ConnectionManager::Disconnect), _con_tab(local_id), _local_id(local_id), _rpc(rpc), _closed(false) { _rpc.Register(&_inquire, "CM::Inquire"); _rpc.Register(&_close, "CM::Close"); _rpc.Register(&_connect, "CM::Connect"); _rpc.Register(&_disconnect, "CM::Disconnect"); Connection *con = _con_tab.GetConnection(_local_id); con->SetSink(&_rpc); QObject::connect(con->GetEdge().data(), SIGNAL(Closed(const QString &)), this, SLOT(HandleEdgeClose(const QString &))); QObject::connect(con, SIGNAL(CalledDisconnect()), this, SLOT(HandleDisconnect())); QObject::connect(con, SIGNAL(Disconnected(const QString &)), this, SLOT(HandleDisconnected(const QString &))); } ConnectionManager::~ConnectionManager() { _rpc.Unregister("CM::Inquire"); _rpc.Unregister("CM::Close"); _rpc.Unregister("CM::Connect"); _rpc.Unregister("CM::Disconnect"); } void ConnectionManager::AddEdgeListener(QSharedPointer<EdgeListener> el) { if(_closed) { qWarning() << "Attempting to add an EdgeListener after calling Disconnect."; return; } _edge_factory.AddEdgeListener(el); QObject::connect(el.data(), SIGNAL(NewEdge(QSharedPointer<Edge>)), this, SLOT(HandleNewEdge(QSharedPointer<Edge>))); QObject::connect(el.data(), SIGNAL(EdgeCreationFailure(const Address &, const QString &)), this, SLOT(HandleEdgeCreationFailure(const Address &, const QString&))); } void ConnectionManager::ConnectTo(const Address &addr) { if(_closed) { qWarning() << "Attempting to Connect to a remote node after calling Disconnect."; return; } if(_outstanding_con_attempts.contains(addr)) { qDebug() << "Attempting to connect multiple times to the same address:" << addr.ToString(); return; } _outstanding_con_attempts[addr] = true; if(!_edge_factory.CreateEdgeTo(addr)) { _outstanding_con_attempts.remove(addr); emit ConnectionAttemptFailure(addr, "No EdgeListener to handle request"); } } void ConnectionManager::Disconnect() { if(_closed) { qWarning() << "Called Disconnect twice on ConnectionManager."; return; } _closed = true; bool emit_dis = (_con_tab.GetEdges().count() == 0); foreach(Connection *con, _con_tab.GetConnections()) { con->Disconnect(); } foreach(QSharedPointer<Edge> edge, _con_tab.GetEdges()) { if(!edge->IsClosed()) { edge->Close("Disconnecting"); } } _edge_factory.Stop(); if(emit_dis) { emit Disconnected(); } } void ConnectionManager::HandleNewEdge(QSharedPointer<Edge> edge) { _con_tab.AddEdge(edge); edge->SetSink(&_rpc); QObject::connect(edge.data(), SIGNAL(Closed(const QString &)), this, SLOT(HandleEdgeClose(const QString &))); if(!edge->Outbound()) { return; } if(_outstanding_con_attempts.remove(edge->GetRemoteAddress()) == 0) { qDebug() << "No record of attempting connection to" << edge->GetRemoteAddress().ToString(); } QVariantMap request; request["method"] = "CM::Inquire"; request["peer_id"] = _local_id.GetByteArray(); QString type = edge->GetLocalAddress().GetType(); QSharedPointer<EdgeListener> el = _edge_factory.GetEdgeListener(type); qWarning() << el->GetAddress().ToString(); request["persistent"] = el->GetAddress().ToString(); _rpc.SendRequest(request, edge.data(), &_inquired); } void ConnectionManager::HandleEdgeCreationFailure(const Address &to, const QString &reason) { emit ConnectionAttemptFailure(to, reason); } void ConnectionManager::Inquire(RpcRequest &request) { Dissent::Messaging::ISender *from = request.GetFrom(); Edge *edge = dynamic_cast<Edge *>(from); if(edge == 0) { qWarning() << "Received an inquired from a non-Edge: " << from->ToString(); return; } else if(edge->Outbound()) { qWarning() << "We should never receive an inquire call on an outbound edge: " << from->ToString(); return; } QByteArray brem_id = request.GetMessage()["peer_id"].toByteArray(); if(brem_id.isEmpty()) { qWarning() << "Invalid Inqiure, no id"; return; } Id rem_id(brem_id); QVariantMap response; response["peer_id"] = _local_id.GetByteArray(); request.Respond(response); QString saddr = request.GetMessage()["persistent"].toString(); Address addr = AddressFactory::GetInstance().CreateAddress(saddr); edge->SetRemotePersistentAddress(addr); if(_local_id < rem_id) { BindEdge(edge, rem_id); } else if(_local_id == rem_id) { edge->Close("Attempting to connect to ourself"); } } void ConnectionManager::Inquired(RpcRequest &response) { Dissent::Messaging::ISender *from = response.GetFrom(); Edge *edge = dynamic_cast<Edge *>(from); if(edge == 0) { qWarning() << "Received an inquired from a non-Edge: " << from->ToString(); return; } else if(!edge->Outbound()) { qWarning() << "We would never make an inquire call on an incoming edge: " << from->ToString(); return; } QByteArray brem_id = response.GetMessage()["peer_id"].toByteArray(); if(brem_id.isEmpty()) { qWarning() << "Invalid ConnectionEstablished, no id"; return; } Id rem_id(brem_id); if(_local_id < rem_id) { BindEdge(edge, rem_id); } else if(rem_id == _local_id) { qDebug() << "Attempting to connect to ourself"; edge->Close("Attempting to connect to ourself"); emit ConnectionAttemptFailure(edge->GetRemoteAddress(), "Attempting to connect to ourself"); return; } } void ConnectionManager::BindEdge(Edge *edge, const Id &rem_id) { /// @TODO add an extra variable to the connection message such as a session ///token so that quick reconnects can be enabled. if(_con_tab.GetConnection(rem_id) != 0) { qWarning() << "Already have a connection to: " << rem_id.ToString() << " closing Edge: " << edge->ToString(); QVariantMap notification; notification["method"] = "CM::Close"; _rpc.SendNotification(notification, edge); edge->Close("Duplicate connection"); emit ConnectionAttemptFailure(edge->GetRemoteAddress(), "Duplicate connection"); return; } QSharedPointer<Edge> pedge = _con_tab.GetEdge(edge); if(pedge.isNull()) { qCritical() << "An edge attempted to create a connection, but there " "is no record of it" << edge->ToString(); return; } QVariantMap notification; notification["method"] = "CM::Connect"; notification["peer_id"] = _local_id.GetByteArray(); _rpc.SendNotification(notification, edge); CreateConnection(pedge, rem_id); } void ConnectionManager::Connect(RpcRequest &notification) { Edge *edge = dynamic_cast<Edge *>(notification.GetFrom()); if(edge == 0) { qWarning() << "Connection attempt not from an Edge: " << notification.GetFrom()->ToString(); return; } QByteArray brem_id = notification.GetMessage()["peer_id"].toByteArray(); if(brem_id.isEmpty()) { qWarning() << "Invalid ConnectionEstablished, no id"; return; } Id rem_id(brem_id); if(_local_id < rem_id) { qWarning() << "We should be sending CM::Connect, not the remote side."; return; } Connection *old_con = _con_tab.GetConnection(rem_id); // XXX if there is an old connection and the node doesn't want it, we need // to close it if(old_con != 0) { qDebug() << "Disconnecting old connection"; old_con->Disconnect(); } QSharedPointer<Edge> pedge = _con_tab.GetEdge(edge); if(pedge.isNull()) { qCritical() << "An edge attempted to create a connection, but there " "is no record of it" << edge->ToString(); return; } CreateConnection(pedge, rem_id); } void ConnectionManager::CreateConnection(QSharedPointer<Edge> pedge, const Id &rem_id) { Connection *con = new Connection(pedge, _local_id, rem_id); _con_tab.AddConnection(con); qDebug() << _local_id.ToString() << ": Handle new connection from " << rem_id.ToString(); QObject::connect(con, SIGNAL(CalledDisconnect()), this, SLOT(HandleDisconnect())); QObject::connect(con, SIGNAL(Disconnected(const QString &)), this, SLOT(HandleDisconnected(const QString &))); emit NewConnection(con); } void ConnectionManager::Close(RpcRequest &notification) { Edge *edge = dynamic_cast<Edge *>(notification.GetFrom()); if(edge == 0) { qWarning() << "Connection attempt Edge close not from an Edge: " << notification.GetFrom()->ToString(); return; } edge->Close("Closed from remote peer"); } void ConnectionManager::HandleDisconnect() { Connection *con = qobject_cast<Connection *>(sender()); if(con == 0) { return; } qDebug() << "Handle disconnect on: " << con->ToString(); _con_tab.Disconnect(con); if(!con->GetEdge()->IsClosed()) { if(con->GetLocalId() != con->GetRemoteId()) { QVariantMap notification; notification["method"] = "CM::Disconnect"; _rpc.SendNotification(notification, con); } con->GetEdge()->Close("Local disconnect request"); } } void ConnectionManager::HandleDisconnected(const QString &reason) { Connection *con = qobject_cast<Connection *>(sender()); qDebug() << "Edge disconnected now removing Connection: " << con->ToString() << ", because: " << reason; _con_tab.RemoveConnection(con); } void ConnectionManager::Disconnect(RpcRequest &notification) { Connection *con = dynamic_cast<Connection *>(notification.GetFrom()); if(con == 0) { qWarning() << "Received DisconnectResponse from a non-connection: " << notification.GetFrom()->ToString(); return; } qDebug() << "Received disconnect for: " << con->ToString(); _con_tab.Disconnect(con); con->GetEdge()->Close("Remote disconnect"); } void ConnectionManager::HandleEdgeClose(const QString &) { Edge *edge = qobject_cast<Edge *>(sender()); qDebug() << "Edge closed: " << edge->ToString(); if(!_con_tab.RemoveEdge(edge)) { qWarning() << "Edge closed but no Edge found in CT:" << edge->ToString(); } Connection *con = _con_tab.GetConnection(edge); if(con != 0) { con = _con_tab.GetConnection(con->GetRemoteId()); if(con != 0) { con->Disconnect(); } } if(!_closed) { return; } if(_con_tab.GetEdges().count() == 0) { emit Disconnected(); } } } } <commit_msg>[Connections] Was accessing a potentially deleted object<commit_after>#include "Messaging/RpcHandler.hpp" #include "Transports/AddressFactory.hpp" #include "Connection.hpp" #include "ConnectionManager.hpp" using Dissent::Transports::AddressFactory; namespace Dissent { namespace Connections { ConnectionManager::ConnectionManager(const Id &local_id, RpcHandler &rpc) : _inquire(this, &ConnectionManager::Inquire), _inquired(this, &ConnectionManager::Inquired), _close(this, &ConnectionManager::Close), _connect(this, &ConnectionManager::Connect), _disconnect(this, &ConnectionManager::Disconnect), _con_tab(local_id), _local_id(local_id), _rpc(rpc), _closed(false) { _rpc.Register(&_inquire, "CM::Inquire"); _rpc.Register(&_close, "CM::Close"); _rpc.Register(&_connect, "CM::Connect"); _rpc.Register(&_disconnect, "CM::Disconnect"); Connection *con = _con_tab.GetConnection(_local_id); con->SetSink(&_rpc); QObject::connect(con->GetEdge().data(), SIGNAL(Closed(const QString &)), this, SLOT(HandleEdgeClose(const QString &))); QObject::connect(con, SIGNAL(CalledDisconnect()), this, SLOT(HandleDisconnect())); QObject::connect(con, SIGNAL(Disconnected(const QString &)), this, SLOT(HandleDisconnected(const QString &))); } ConnectionManager::~ConnectionManager() { _rpc.Unregister("CM::Inquire"); _rpc.Unregister("CM::Close"); _rpc.Unregister("CM::Connect"); _rpc.Unregister("CM::Disconnect"); } void ConnectionManager::AddEdgeListener(QSharedPointer<EdgeListener> el) { if(_closed) { qWarning() << "Attempting to add an EdgeListener after calling Disconnect."; return; } _edge_factory.AddEdgeListener(el); QObject::connect(el.data(), SIGNAL(NewEdge(QSharedPointer<Edge>)), this, SLOT(HandleNewEdge(QSharedPointer<Edge>))); QObject::connect(el.data(), SIGNAL(EdgeCreationFailure(const Address &, const QString &)), this, SLOT(HandleEdgeCreationFailure(const Address &, const QString&))); } void ConnectionManager::ConnectTo(const Address &addr) { if(_closed) { qWarning() << "Attempting to Connect to a remote node after calling Disconnect."; return; } if(_outstanding_con_attempts.contains(addr)) { qDebug() << "Attempting to connect multiple times to the same address:" << addr.ToString(); return; } _outstanding_con_attempts[addr] = true; if(!_edge_factory.CreateEdgeTo(addr)) { _outstanding_con_attempts.remove(addr); emit ConnectionAttemptFailure(addr, "No EdgeListener to handle request"); } } void ConnectionManager::Disconnect() { if(_closed) { qWarning() << "Called Disconnect twice on ConnectionManager."; return; } _closed = true; bool emit_dis = (_con_tab.GetEdges().count() == 0); foreach(Connection *con, _con_tab.GetConnections()) { con->Disconnect(); } foreach(QSharedPointer<Edge> edge, _con_tab.GetEdges()) { if(!edge->IsClosed()) { edge->Close("Disconnecting"); } } _edge_factory.Stop(); if(emit_dis) { emit Disconnected(); } } void ConnectionManager::HandleNewEdge(QSharedPointer<Edge> edge) { _con_tab.AddEdge(edge); edge->SetSink(&_rpc); QObject::connect(edge.data(), SIGNAL(Closed(const QString &)), this, SLOT(HandleEdgeClose(const QString &))); if(!edge->Outbound()) { return; } if(_outstanding_con_attempts.remove(edge->GetRemoteAddress()) == 0) { qDebug() << "No record of attempting connection to" << edge->GetRemoteAddress().ToString(); } QVariantMap request; request["method"] = "CM::Inquire"; request["peer_id"] = _local_id.GetByteArray(); QString type = edge->GetLocalAddress().GetType(); QSharedPointer<EdgeListener> el = _edge_factory.GetEdgeListener(type); request["persistent"] = el->GetAddress().ToString(); _rpc.SendRequest(request, edge.data(), &_inquired); } void ConnectionManager::HandleEdgeCreationFailure(const Address &to, const QString &reason) { emit ConnectionAttemptFailure(to, reason); } void ConnectionManager::Inquire(RpcRequest &request) { Dissent::Messaging::ISender *from = request.GetFrom(); Edge *edge = dynamic_cast<Edge *>(from); if(edge == 0) { qWarning() << "Received an inquired from a non-Edge: " << from->ToString(); return; } else if(edge->Outbound()) { qWarning() << "We should never receive an inquire call on an outbound edge: " << from->ToString(); return; } QByteArray brem_id = request.GetMessage()["peer_id"].toByteArray(); if(brem_id.isEmpty()) { qWarning() << "Invalid Inqiure, no id"; return; } Id rem_id(brem_id); QVariantMap response; response["peer_id"] = _local_id.GetByteArray(); request.Respond(response); QString saddr = request.GetMessage()["persistent"].toString(); Address addr = AddressFactory::GetInstance().CreateAddress(saddr); edge->SetRemotePersistentAddress(addr); if(_local_id < rem_id) { BindEdge(edge, rem_id); } else if(_local_id == rem_id) { edge->Close("Attempting to connect to ourself"); } } void ConnectionManager::Inquired(RpcRequest &response) { Dissent::Messaging::ISender *from = response.GetFrom(); Edge *edge = dynamic_cast<Edge *>(from); if(edge == 0) { qWarning() << "Received an inquired from a non-Edge: " << from->ToString(); return; } else if(!edge->Outbound()) { qWarning() << "We would never make an inquire call on an incoming edge: " << from->ToString(); return; } QByteArray brem_id = response.GetMessage()["peer_id"].toByteArray(); if(brem_id.isEmpty()) { qWarning() << "Invalid ConnectionEstablished, no id"; return; } Id rem_id(brem_id); if(_local_id < rem_id) { BindEdge(edge, rem_id); } else if(rem_id == _local_id) { Address addr = edge->GetRemoteAddress(); qDebug() << "Attempting to connect to ourself"; edge->Close("Attempting to connect to ourself"); emit ConnectionAttemptFailure(addr, "Attempting to connect to ourself"); return; } } void ConnectionManager::BindEdge(Edge *edge, const Id &rem_id) { /// @TODO add an extra variable to the connection message such as a session ///token so that quick reconnects can be enabled. if(_con_tab.GetConnection(rem_id) != 0) { qWarning() << "Already have a connection to: " << rem_id.ToString() << " closing Edge: " << edge->ToString(); QVariantMap notification; notification["method"] = "CM::Close"; _rpc.SendNotification(notification, edge); Address addr = edge->GetRemoteAddress(); edge->Close("Duplicate connection"); emit ConnectionAttemptFailure(addr, "Duplicate connection"); return; } QSharedPointer<Edge> pedge = _con_tab.GetEdge(edge); if(pedge.isNull()) { qCritical() << "An edge attempted to create a connection, but there " "is no record of it" << edge->ToString(); return; } QVariantMap notification; notification["method"] = "CM::Connect"; notification["peer_id"] = _local_id.GetByteArray(); _rpc.SendNotification(notification, edge); CreateConnection(pedge, rem_id); } void ConnectionManager::Connect(RpcRequest &notification) { Edge *edge = dynamic_cast<Edge *>(notification.GetFrom()); if(edge == 0) { qWarning() << "Connection attempt not from an Edge: " << notification.GetFrom()->ToString(); return; } QByteArray brem_id = notification.GetMessage()["peer_id"].toByteArray(); if(brem_id.isEmpty()) { qWarning() << "Invalid ConnectionEstablished, no id"; return; } Id rem_id(brem_id); if(_local_id < rem_id) { qWarning() << "We should be sending CM::Connect, not the remote side."; return; } Connection *old_con = _con_tab.GetConnection(rem_id); // XXX if there is an old connection and the node doesn't want it, we need // to close it if(old_con != 0) { qDebug() << "Disconnecting old connection"; old_con->Disconnect(); } QSharedPointer<Edge> pedge = _con_tab.GetEdge(edge); if(pedge.isNull()) { qCritical() << "An edge attempted to create a connection, but there " "is no record of it" << edge->ToString(); return; } CreateConnection(pedge, rem_id); } void ConnectionManager::CreateConnection(QSharedPointer<Edge> pedge, const Id &rem_id) { Connection *con = new Connection(pedge, _local_id, rem_id); _con_tab.AddConnection(con); qDebug() << _local_id.ToString() << ": Handle new connection from " << rem_id.ToString(); QObject::connect(con, SIGNAL(CalledDisconnect()), this, SLOT(HandleDisconnect())); QObject::connect(con, SIGNAL(Disconnected(const QString &)), this, SLOT(HandleDisconnected(const QString &))); emit NewConnection(con); } void ConnectionManager::Close(RpcRequest &notification) { Edge *edge = dynamic_cast<Edge *>(notification.GetFrom()); if(edge == 0) { qWarning() << "Connection attempt Edge close not from an Edge: " << notification.GetFrom()->ToString(); return; } edge->Close("Closed from remote peer"); } void ConnectionManager::HandleDisconnect() { Connection *con = qobject_cast<Connection *>(sender()); if(con == 0) { return; } qDebug() << "Handle disconnect on: " << con->ToString(); _con_tab.Disconnect(con); if(!con->GetEdge()->IsClosed()) { if(con->GetLocalId() != con->GetRemoteId()) { QVariantMap notification; notification["method"] = "CM::Disconnect"; _rpc.SendNotification(notification, con); } con->GetEdge()->Close("Local disconnect request"); } } void ConnectionManager::HandleDisconnected(const QString &reason) { Connection *con = qobject_cast<Connection *>(sender()); qDebug() << "Edge disconnected now removing Connection: " << con->ToString() << ", because: " << reason; _con_tab.RemoveConnection(con); } void ConnectionManager::Disconnect(RpcRequest &notification) { Connection *con = dynamic_cast<Connection *>(notification.GetFrom()); if(con == 0) { qWarning() << "Received DisconnectResponse from a non-connection: " << notification.GetFrom()->ToString(); return; } qDebug() << "Received disconnect for: " << con->ToString(); _con_tab.Disconnect(con); con->GetEdge()->Close("Remote disconnect"); } void ConnectionManager::HandleEdgeClose(const QString &) { Edge *edge = qobject_cast<Edge *>(sender()); qDebug() << "Edge closed: " << edge->ToString(); if(!_con_tab.RemoveEdge(edge)) { qWarning() << "Edge closed but no Edge found in CT:" << edge->ToString(); } Connection *con = _con_tab.GetConnection(edge); if(con != 0) { con = _con_tab.GetConnection(con->GetRemoteId()); if(con != 0) { con->Disconnect(); } } if(!_closed) { return; } if(_con_tab.GetEdges().count() == 0) { emit Disconnected(); } } } } <|endoftext|>
<commit_before>#ifndef ALGORITHM #define ALGORITHM #include<algorithm> //move #include<cstddef> #include<functional> #include<iterator> #include<type_traits> //make_unsigned #include<utility> //move #include"../thread/CSmartThread.hpp" namespace nAlgorithm { template<class T,class UnaryPred> bool all_of_val(T begin,const T end,const UnaryPred pred) { while(begin!=end) { if(!pred(begin)) return false; ++begin; } return true; } template<class T,class UnaryPred> T find_if_val(T begin,const T end,const UnaryPred pred) { while(begin!=end) { if(pred(begin)) return begin; ++begin; } return end; } template<class T,class UnaryPred> inline bool any_of_val(const T begin,const T end,UnaryPred pred) { return find_if_val(begin,end,pred)!=end; } template<class T,class UnaryPred> std::ptrdiff_t count_if_val(T begin,const T end,const UnaryPred pred) { std::ptrdiff_t accu{0}; while(begin!=end) { if(pred(begin)) ++accu; ++begin; } return accu; } template<class InIter,class T,class BinaryPred> InIter find_if(InIter begin,const InIter end,const T &val,const BinaryPred pred) { while(begin!=end) { if(pred(*begin,val)) return begin; ++begin; } return begin; } template<class T,class UnaryFunc> UnaryFunc for_each_val(T begin,const T end,const UnaryFunc func) { while(begin!=end) { func(begin); ++begin; } return func; } template<class InIter,class UnaryPred,class UnaryFunc> void loop_until_none_of(const InIter begin,const InIter end,const UnaryPred pred,const UnaryFunc func) { for(InIter iter;(iter=find_if(begin,end,pred))!=end;) func(*iter); } template<class InIter,class OutIter,class BinaryOp> void multiply(InIter lbegin,const InIter lend,const InIter rbegin,const InIter rend,OutIter des,const BinaryOp op) { while(lbegin!=lend) { for(auto begin{rbegin};begin!=rend;++begin,++des) *des=op(*lbegin,*begin); ++lbegin; } } template<class FwdIter,class T,class BinaryPred> FwdIter remove_if(FwdIter begin,const FwdIter end,const T &val,const BinaryPred pred) { begin=find_if(begin,end,val,pred); if(begin!=end) for(auto temp{begin};++temp!=end;) if(!pred(*temp,val)) *begin++=std::move(*temp); return begin; } template<class FwdIter,class BinaryPred=std::equal_to<typename std::iterator_traits<FwdIter>::value_type>> FwdIter unique_without_sort(FwdIter begin,FwdIter end,const BinaryPred pred=BinaryPred()) { while(begin!=end) { end=remove_if(std::next(begin),end,*begin,pred); ++begin; } return end; } template<class FwdIter,class BinaryPred=std::equal_to<typename std::iterator_traits<FwdIter>::value_type>> FwdIter unique_without_sort_thr(const FwdIter begin,const FwdIter end,const std::size_t N,const BinaryPred pred=BinaryPred()) { using namespace std; function<void(FwdIter,FwdIter,FwdIter &)> unique_without_sort_thr_{[&,N,pred](const FwdIter begin,const FwdIter end,FwdIter &divide){ const size_t size{make_unsigned<ptrdiff_t>::type(distance(begin,end))}; if(N&&N<size) { divide=end; FwdIter lhs_end,rhs_end; const auto mid{next(begin,size/2)}; { nThread::CSmartThread lhs{unique_without_sort_thr_,begin,mid,ref(lhs_end)}, rhs{unique_without_sort_thr_,mid,end,ref(rhs_end)}; } for_each(begin,lhs_end,[&,pred,mid](const typename iterator_traits<FwdIter>::value_type &val){ rhs_end=remove_if(mid,rhs_end,val,pred); }); divide=std::move(mid,rhs_end,lhs_end); } else divide=unique_without_sort(begin,end,pred); }}; FwdIter retVal; unique_without_sort_thr_(begin,end,retVal); return retVal; } template<class FwdIter,class BinaryPred=std::equal_to<typename std::iterator_traits<FwdIter>::value_type>> inline FwdIter unique_without_sort_thr(FwdIter begin,FwdIter end,BinaryPred pred=BinaryPred()) { return unique_without_sort_thr(begin,end,std::distance(begin,end)/2,pred); } //Both of unique_without_sort and unique_without_sort_thr will reorder the input permutation. } #endif<commit_msg>use bind and placeholders to reduce function<commit_after>#ifndef ALGORITHM #define ALGORITHM #include<algorithm> //move #include<cstddef> #include<functional> //bind, placeholders #include<iterator> #include<type_traits> //make_unsigned #include<utility> //move #include"../thread/CSmartThread.hpp" namespace nAlgorithm { template<class T,class UnaryPred> bool all_of_val(T begin,const T end,const UnaryPred pred) { while(begin!=end) { if(!pred(begin)) return false; ++begin; } return true; } template<class T,class UnaryPred> T find_if_val(T begin,const T end,const UnaryPred pred) { while(begin!=end) { if(pred(begin)) return begin; ++begin; } return end; } template<class T,class UnaryPred> inline bool any_of_val(const T begin,const T end,UnaryPred pred) { return find_if_val(begin,end,pred)!=end; } template<class T,class UnaryPred> std::ptrdiff_t count_if_val(T begin,const T end,const UnaryPred pred) { std::ptrdiff_t accu{0}; while(begin!=end) { if(pred(begin)) ++accu; ++begin; } return accu; } template<class T,class UnaryFunc> UnaryFunc for_each_val(T begin,const T end,const UnaryFunc func) { while(begin!=end) { func(begin); ++begin; } return func; } template<class InIter,class UnaryPred,class UnaryFunc> void loop_until_none_of(const InIter begin,const InIter end,const UnaryPred pred,const UnaryFunc func) { for(InIter iter;(iter=find_if(begin,end,pred))!=end;) func(*iter); } template<class InIter,class OutIter,class BinaryOp> void multiply(InIter lbegin,const InIter lend,const InIter rbegin,const InIter rend,OutIter des,const BinaryOp op) { while(lbegin!=lend) { for(auto begin{rbegin};begin!=rend;++begin,++des) *des=op(*lbegin,*begin); ++lbegin; } } template<class FwdIter,class BinaryPred=std::equal_to<typename std::iterator_traits<FwdIter>::value_type>> FwdIter unique_without_sort(FwdIter begin,FwdIter end,const BinaryPred pred=BinaryPred()) { while(begin!=end) { end=std::remove_if(std::next(begin),end,std::bind(pred,*begin,std::placeholders::_1)); ++begin; } return end; } template<class FwdIter,class BinaryPred=std::equal_to<typename std::iterator_traits<FwdIter>::value_type>> FwdIter unique_without_sort_thr(const FwdIter begin,const FwdIter end,const std::size_t N,const BinaryPred pred=BinaryPred()) { using namespace std; function<void(FwdIter,FwdIter,FwdIter &)> unique_without_sort_thr_{[&,N,pred](const FwdIter begin,const FwdIter end,FwdIter &divide){ const size_t size{make_unsigned<ptrdiff_t>::type(distance(begin,end))}; if(N&&N<size) { divide=end; FwdIter lhs_end,rhs_end; const auto mid{next(begin,size/2)}; { nThread::CSmartThread lhs{unique_without_sort_thr_,begin,mid,ref(lhs_end)}, rhs{unique_without_sort_thr_,mid,end,ref(rhs_end)}; } for_each(begin,lhs_end,[&,pred,mid](const typename iterator_traits<FwdIter>::value_type &val){ rhs_end=std::remove_if(mid,rhs_end,std::bind(pred,val,placeholders::_1)); }); divide=std::move(mid,rhs_end,lhs_end); } else divide=unique_without_sort(begin,end,pred); }}; FwdIter retVal; unique_without_sort_thr_(begin,end,retVal); return retVal; } template<class FwdIter,class BinaryPred=std::equal_to<typename std::iterator_traits<FwdIter>::value_type>> inline FwdIter unique_without_sort_thr(FwdIter begin,FwdIter end,BinaryPred pred=BinaryPred()) { return unique_without_sort_thr(begin,end,std::distance(begin,end)/2,pred); } //Both of unique_without_sort and unique_without_sort_thr will reorder the input permutation. } #endif<|endoftext|>
<commit_before>#include "QuantityDefinitionsTest.h" #include "QuantityTestMain.h" #include "odr_test/QDummyTranslationUnit1.h" #include "odr_test/QDummyTranslationUnit2.h" #include <src/quantity/Quantity.h> #include <src/quantity/quantityDefinitionsSI.h> #include <src/quantity/quantityMath.h> #include <src/quantity/quantityOperators.h> #include <src/quantity/quantityPrinting.h> #include <src/quantity/quantityReading.h> #include <complex> #include <cassert> #include <iostream> namespace tests { using namespace unit; namespace u { using newton = Unit<1,1,-2,0>; using unitless = Unit<0,0,0,0>; } using newton = Quantity<u::newton, double>; using unitless = Quantity<u::unitless, double>; constexpr newton operator"" _newton ( long double v ) {return newton {static_cast<double>(v)};} constexpr unitless operator"" _unitless ( long double v ) {return unitless {static_cast<double>(v)};} } namespace unit { template<> inline void print_unit< tests::u::newton>(std::ostream& s){ s<<"N"; } } namespace tests { using u_newton_sqr = product_unit<u::newton,u::newton>; using u_newton_cub = product_unit<u_newton_sqr,u::newton>; void quantity_test() { static_assert(Quantity<u::newton,int>(4).magnitude()==4,""); static_assert(Quantity<u::newton,int>(Quantity<u::newton,int>{4}).magnitude()==4,""); { Quantity<u::newton,int> x(4); x=Quantity<u::newton,int>{5}; assert(x.magnitude()==5); } { Quantity<u::newton,int> x(4); x.setMagnitude(Quantity<u::newton,int> (5)); assert(x.magnitude()==5); } { Quantity<u::newton,int> x(4); x+=Quantity<u::newton,int>{5}; assert(x.magnitude()==9); } { Quantity<u::newton,int> x(4); x-=Quantity<u::newton,int>{5}; assert(x.magnitude()==-1); } { Quantity<u::newton,int> x(4); x*=Quantity<u::newton,int>{5}; assert(x.magnitude()==20); } { Quantity<u::newton,int> x(4); x/=Quantity<u::newton,int>{5}; assert(x.magnitude()==0); } { Quantity<u::newton,double> x(4); x = Quantity<u::newton,int>{5}; assert(x.magnitude()==5); } } void complex_math_test() //complex functions are not constexpr, therefore non-static tests { using T = double; using TComplex = std::complex<T>; using cnewton = Quantity<u::newton, TComplex> ; using ncnewton = Quantity<u::newton, T> ; using cnewton_sqr = Quantity<u_newton_sqr, TComplex> ; using cnewton_cub = Quantity<u_newton_cub, TComplex> ; assert(math::abs(cnewton{-7})==ncnewton{7}); assert(math::abs(cnewton{TComplex{3,4}})==ncnewton{5}); { const bool b = math::square(cnewton{TComplex{3,4}})==cnewton_sqr{TComplex{-7,24}}; assert(b); } { const bool b = math::cube(cnewton{TComplex{3,4}})==cnewton_cub{TComplex{-117,44}}; assert(b); } { const bool b = math::sqrt(cnewton_sqr{TComplex{-7,24}})==cnewton{TComplex{3,4}}; assert(b); } { using e = std::ratio<3,2>; using u_src = u_newton_sqr; using u_dst = raised_unit<u_src,e>; using src = Quantity<u_src, TComplex> ; using dst = Quantity<u_dst, TComplex> ; const auto expected = dst{TComplex{2,11}}; const auto actual = math::pow<e>(src{TComplex{3,4}}); const auto d = math::abs(expected-actual); //rounding error assert(d.magnitude()<1.0e-14); } } static_assert(math::abs(-7.0_newton)==7.0_newton,""); static_assert(math::square(-7.5_newton)== Quantity<product_unit<u::newton,u::newton>>{56.25},""); static_assert(math::cube(-7.5_newton)== Quantity<product_unit<u::newton,product_unit<u::newton,u::newton>>>{-421.875},""); static_assert(math::sqrt(Quantity<product_unit<u::newton,u::newton>>{56.25})==7.5_newton,""); //static_assert(math::sqrt(Quantity<u::newton>{56.25})==7.5_newton,""); //mustnt compile static_assert(math::pow<std::ratio<1,2>>(math::square(-7.5_newton))==7.5_newton,""); static_assert(math::pow<std::ratio<1>>(-7.5_newton)==-7.5_newton,""); static_assert(math::pow<std::ratio<2>>(-7.5_newton)==math::square(-7.5_newton),""); static_assert(math::pow<std::ratio<0>>(-7.5_newton)==1.0_unitless,""); static_assert( 4.3_newton == 4.3_newton,""); static_assert( 4.3_newton >= 4.3_newton,""); static_assert( 4.3_newton <= 4.3_newton,""); static_assert((4.3_newton != 4.3_newton) == false,""); static_assert((4.3_newton < 4.3_newton) == false,""); static_assert((4.3_newton > 4.3_newton) == false,""); static_assert( 4.2_newton < 4.3_newton,""); static_assert( 4.3_newton > 4.2_newton,""); static_assert(4.0_newton + 5.0_newton == 9.0_newton,""); static_assert(4.0_newton - 5.0_newton == -1.0_newton,""); static_assert(-4.0_newton * 5.0_newton == Quantity<product_unit<u::newton,u::newton>>{-20.0},""); static_assert(-4.0_newton / 5.0_newton == -0.8_unitless,""); static_assert(static_unit_cast<double>(Quantity<u::newton,int>{-4})==-4.0_newton,""); static_assert(Quantity<u::newton>{-4}==-4.0_newton,""); void print_derived_unit_test_v() { { std::ostringstream s; s << -4.5_newton; if (s.str()!="-4.5N") assert(false); } } void read_unit_test_v() { { std::istringstream s{"-4.5N"}; Quantity<u::newton> n{1}; s >> n; assert(n==-4.5_newton); } { std::istringstream s{"-4.5Hz"}; Quantity<u::newton> n{1}; s >> n; assert(!s); assert(n==1.0_newton); } } QuantityTestMain::QuantityTestMain() { q::QDummyTranslationUnit1{}; q::QDummyTranslationUnit2{}; QuantityDefinitionsTest{}; read_unit_test_v(); print_derived_unit_test_v(); complex_math_test(); quantity_test(); } } <commit_msg>added tests for std::array<commit_after>#include "QuantityDefinitionsTest.h" #include "QuantityTestMain.h" #include "odr_test/QDummyTranslationUnit1.h" #include "odr_test/QDummyTranslationUnit2.h" #include <src/quantity/Quantity.h> #include <src/quantity/quantityDefinitionsSI.h> #include <src/quantity/quantityMath.h> #include <src/quantity/quantityOperators.h> #include <src/quantity/quantityPrinting.h> #include <src/quantity/quantityReading.h> #include <complex> #include <cassert> #include <iostream> #include <type_traits> // array comparisons #include <array> namespace tests { using namespace unit; namespace u { using newton = Unit<1,1,-2,0>; using unitless = Unit<0,0,0,0>; } using newton = Quantity<u::newton, double>; using unitless = Quantity<u::unitless, double>; constexpr newton operator"" _newton ( long double v ) {return newton {static_cast<double>(v)};} constexpr unitless operator"" _unitless ( long double v ) {return unitless {static_cast<double>(v)};} } namespace unit { template<> inline void print_unit< tests::u::newton>(std::ostream& s){ s<<"N"; } } namespace tests { using u_newton_sqr = product_unit<u::newton,u::newton>; using u_newton_cub = product_unit<u_newton_sqr,u::newton>; void quantity_test() { static_assert(Quantity<u::newton,int>(4).magnitude()==4,""); static_assert(Quantity<u::newton,int>(Quantity<u::newton,int>{4}).magnitude()==4,""); { Quantity<u::newton,int> x(4); x=Quantity<u::newton,int>{5}; assert(x.magnitude()==5); } { Quantity<u::newton,int> x(4); x.setMagnitude(Quantity<u::newton,int> (5)); assert(x.magnitude()==5); } { Quantity<u::newton,int> x(4); x+=Quantity<u::newton,int>{5}; assert(x.magnitude()==9); } { Quantity<u::newton,int> x(4); x-=Quantity<u::newton,int>{5}; assert(x.magnitude()==-1); } { Quantity<u::newton,int> x(4); x*=Quantity<u::newton,int>{5}; assert(x.magnitude()==20); } { Quantity<u::newton,int> x(4); x/=Quantity<u::newton,int>{5}; assert(x.magnitude()==0); } { Quantity<u::newton,double> x(4); x = Quantity<u::newton,int>{5}; assert(x.magnitude()==5); } } void complex_math_test() //complex functions are not constexpr, therefore non-static tests { using T = double; using TComplex = std::complex<T>; using cnewton = Quantity<u::newton, TComplex> ; using ncnewton = Quantity<u::newton, T> ; using cnewton_sqr = Quantity<u_newton_sqr, TComplex> ; using cnewton_cub = Quantity<u_newton_cub, TComplex> ; assert(math::abs(cnewton{-7})==ncnewton{7}); assert(math::abs(cnewton{TComplex{3,4}})==ncnewton{5}); { const bool b = math::square(cnewton{TComplex{3,4}})==cnewton_sqr{TComplex{-7,24}}; assert(b); } { const bool b = math::cube(cnewton{TComplex{3,4}})==cnewton_cub{TComplex{-117,44}}; assert(b); } { const bool b = math::sqrt(cnewton_sqr{TComplex{-7,24}})==cnewton{TComplex{3,4}}; assert(b); } { using e = std::ratio<3,2>; using u_src = u_newton_sqr; using u_dst = raised_unit<u_src,e>; using src = Quantity<u_src, TComplex> ; using dst = Quantity<u_dst, TComplex> ; const auto expected = dst{TComplex{2,11}}; const auto actual = math::pow<e>(src{TComplex{3,4}}); const auto d = math::abs(expected-actual); //rounding error assert(d.magnitude()<1.0e-14); } } static_assert(math::abs(-7.0_newton)==7.0_newton,""); static_assert(math::square(-7.5_newton)== Quantity<product_unit<u::newton,u::newton>>{56.25},""); static_assert(math::cube(-7.5_newton)== Quantity<product_unit<u::newton,product_unit<u::newton,u::newton>>>{-421.875},""); static_assert(math::sqrt(Quantity<product_unit<u::newton,u::newton>>{56.25})==7.5_newton,""); //static_assert(math::sqrt(Quantity<u::newton>{56.25})==7.5_newton,""); //mustnt compile static_assert(math::pow<std::ratio<1,2>>(math::square(-7.5_newton))==7.5_newton,""); static_assert(math::pow<std::ratio<1>>(-7.5_newton)==-7.5_newton,""); static_assert(math::pow<std::ratio<2>>(-7.5_newton)==math::square(-7.5_newton),""); static_assert(math::pow<std::ratio<0>>(-7.5_newton)==1.0_unitless,""); static_assert( 4.3_newton == 4.3_newton,""); static_assert( 4.3_newton >= 4.3_newton,""); static_assert( 4.3_newton <= 4.3_newton,""); static_assert((4.3_newton != 4.3_newton) == false,""); static_assert((4.3_newton < 4.3_newton) == false,""); static_assert((4.3_newton > 4.3_newton) == false,""); static_assert( 4.2_newton < 4.3_newton,""); static_assert( 4.3_newton > 4.2_newton,""); static_assert(4.0_newton + 5.0_newton == 9.0_newton,""); static_assert(4.0_newton - 5.0_newton == -1.0_newton,""); static_assert(-4.0_newton * 5.0_newton == Quantity<product_unit<u::newton,u::newton>>{-20.0},""); static_assert(-4.0_newton / 5.0_newton == -0.8_unitless,""); static_assert(static_unit_cast<double>(Quantity<u::newton,int>{-4})==-4.0_newton,""); static_assert(Quantity<u::newton>{-4}==-4.0_newton,""); void print_derived_unit_test_v() { { std::ostringstream s; s << -4.5_newton; if (s.str()!="-4.5N") assert(false); } } void read_unit_test_v() { { std::istringstream s{"-4.5N"}; Quantity<u::newton> n{1}; s >> n; assert(n==-4.5_newton); } { std::istringstream s{"-4.5Hz"}; Quantity<u::newton> n{1}; s >> n; assert(!s); assert(n==1.0_newton); } } static_assert(-4.0_newton / 5.0_newton == -0.8_unitless,""); void array_test () { using T = std::array<int,5>; using anewton = Quantity<u::newton, T> ; constexpr anewton a{T{10, 20, 30, 40, 50}}; constexpr anewton b{T{0, 0, 0, 0, 0}}; if (a!=a) assert(false); if (a<a) assert(false); if (a>a) assert(false); if (!(a==a)) assert(false); if (!(a>=a)) assert(false); if (!(a<=a)) assert(false); if (a==b) assert(false); if (a<=b) assert(false); } QuantityTestMain::QuantityTestMain() { q::QDummyTranslationUnit1{}; q::QDummyTranslationUnit2{}; QuantityDefinitionsTest{}; read_unit_test_v(); print_derived_unit_test_v(); complex_math_test(); quantity_test(); array_test(); } } <|endoftext|>
<commit_before>#include <stdlib.h> #include <stdio.h> #include <string.h> #include <stdarg.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <signal.h> #include <curl/curl.h> #include "fcgiapp.h" #include "common/ceph_argparse.h" #include "global/global_init.h" #include "common/config.h" #include "common/errno.h" #include "common/WorkQueue.h" #include "common/Timer.h" #include "rgw_common.h" #include "rgw_access.h" #include "rgw_acl.h" #include "rgw_user.h" #include "rgw_op.h" #include "rgw_rest.h" #include "rgw_swift.h" #include "rgw_log.h" #include "rgw_bucket.h" #include <map> #include <string> #include <vector> #include <iostream> #include <sstream> #include "include/types.h" #include "common/BackTrace.h" using namespace std; static sighandler_t sighandler_usr1; static sighandler_t sighandler_alrm; #define SOCKET_BACKLOG 20 static void godown_handler(int signum) { FCGX_ShutdownPending(); signal(signum, sighandler_usr1); alarm(5); } static void godown_alarm(int signum) { _exit(0); } class RGWProcess { deque<FCGX_Request *> m_fcgx_queue; ThreadPool m_tp; struct RGWWQ : public ThreadPool::WorkQueue<FCGX_Request> { RGWProcess *process; RGWWQ(RGWProcess *p, time_t timeout, time_t suicide_timeout, ThreadPool *tp) : ThreadPool::WorkQueue<FCGX_Request>("RGWWQ", timeout, suicide_timeout, tp), process(p) {} bool _enqueue(FCGX_Request *req) { process->m_fcgx_queue.push_back(req); RGW_LOG(20) << "enqueued request fcgx=" << hex << req << dec << dendl; _dump_queue(); return true; } void _dequeue(FCGX_Request *req) { assert(0); } bool _empty() { return process->m_fcgx_queue.empty(); } FCGX_Request *_dequeue() { if (process->m_fcgx_queue.empty()) return NULL; FCGX_Request *req = process->m_fcgx_queue.front(); process->m_fcgx_queue.pop_front(); RGW_LOG(20) << "dequeued request fcgx=" << hex << req << dec << dendl; _dump_queue(); return req; } void _process(FCGX_Request *fcgx) { process->handle_request(fcgx); } void _dump_queue() { deque<FCGX_Request *>::iterator iter; if (process->m_fcgx_queue.size() == 0) { RGW_LOG(20) << "RGWWQ: empty" << dendl; return; } RGW_LOG(20) << "RGWWQ:" << dendl; for (iter = process->m_fcgx_queue.begin(); iter != process->m_fcgx_queue.end(); ++iter) { RGW_LOG(20) << "fcgx: " << hex << *iter << dec << dendl; } } void _clear() { assert(process->m_fcgx_queue.empty()); } } req_wq; public: RGWProcess(CephContext *cct, int num_threads) : m_tp(cct, "RGWProcess::m_tp", num_threads), req_wq(this, g_conf->rgw_op_thread_timeout, g_conf->rgw_op_thread_suicide_timeout, &m_tp) {} void run(); void handle_request(FCGX_Request *fcgx); }; void RGWProcess::run() { int s = 0; if (!g_conf->rgw_socket_path.empty()) { string path_str = g_conf->rgw_socket_path; const char *path = path_str.c_str(); s = FCGX_OpenSocket(path, SOCKET_BACKLOG); if (s < 0) { RGW_LOG(0) << "ERROR: FCGX_OpenSocket (" << path << ") returned " << s << dendl; return; } if (chmod(path, 0777) < 0) { RGW_LOG(0) << "WARNING: couldn't set permissions on unix domain socket" << dendl; } } m_tp.start(); for (;;) { FCGX_Request *fcgx = new FCGX_Request; RGW_LOG(10) << "allocated request fcgx=" << hex << fcgx << dec << dendl; FCGX_InitRequest(fcgx, s, 0); int ret = FCGX_Accept_r(fcgx); if (ret < 0) break; req_wq.queue(fcgx); } m_tp.stop(); } static int call_log_intent(void *ctx, rgw_obj& obj, RGWIntentEvent intent) { struct req_state *s = (struct req_state *)ctx; return rgw_log_intent(s, obj, intent); } void RGWProcess::handle_request(FCGX_Request *fcgx) { RGWRESTMgr rest; int ret; RGWEnv rgw_env; RGW_LOG(0) << "====== starting new request fcgx=" << hex << fcgx << dec << " =====" << dendl; rgw_env.init(fcgx->envp); struct req_state *s = new req_state(&rgw_env); s->obj_ctx = rgwstore->create_context(s); rgwstore->set_intent_cb(s->obj_ctx, call_log_intent); RGWOp *op = NULL; int init_error = 0; RGWHandler *handler = rest.get_handler(s, fcgx, &init_error); if (init_error != 0) { abort_early(s, init_error); goto done; } ret = handler->authorize(); if (ret < 0) { RGW_LOG(10) << "failed to authorize request" << dendl; abort_early(s, ret); goto done; } if (s->user.suspended) { RGW_LOG(10) << "user is suspended, uid=" << s->user.user_id << dendl; abort_early(s, -ERR_USER_SUSPENDED); goto done; } ret = handler->read_permissions(); if (ret < 0) { abort_early(s, ret); goto done; } op = handler->get_op(); if (op) { ret = op->verify_permission(); if (ret < 0) { abort_early(s, ret); goto done; } if (s->expect_cont) dump_continue(s); op->execute(); } else { abort_early(s, -ERR_METHOD_NOT_ALLOWED); } done: rgw_log_op(s); int http_ret = s->err.http_ret; handler->put_op(op); rgwstore->destroy_context(s->obj_ctx); delete s; FCGX_Finish_r(fcgx); delete fcgx; RGW_LOG(0) << "====== req done fcgx=" << hex << fcgx << dec << " http_status=" << http_ret << " ======" << dendl; } class C_RGWMaintenanceTick : public Context { SafeTimer *timer; public: C_RGWMaintenanceTick(SafeTimer *t) : timer(t) {} void finish(int r) { rgw_bucket_maintain_pools(); RGW_LOG(20) << "C_RGWMaintenanceTick::finish()" << dendl; timer->add_event_after(g_conf->rgw_maintenance_tick_interval, new C_RGWMaintenanceTick(timer)); } }; /* * start up the RADOS connection and then handle HTTP messages as they come in */ int main(int argc, const char **argv) { curl_global_init(CURL_GLOBAL_ALL); // dout() messages will be sent to stderr, but FCGX wants messages on stdout // Redirect stderr to stdout. TEMP_FAILURE_RETRY(close(STDERR_FILENO)); if (TEMP_FAILURE_RETRY(dup2(STDOUT_FILENO, STDERR_FILENO) < 0)) { int err = errno; cout << "failed to redirect stderr to stdout: " << cpp_strerror(err) << std::endl; return ENOSYS; } vector<const char*> args; argv_to_vec(argc, argv, args); env_to_vec(args); global_init(args, CEPH_ENTITY_TYPE_CLIENT, CODE_ENVIRONMENT_UTILITY, 0); common_init_finish(g_ceph_context); sighandler_usr1 = signal(SIGUSR1, godown_handler); sighandler_alrm = signal(SIGALRM, godown_alarm); FCGX_Init(); RGWStoreManager store_manager; if (!store_manager.init("rados", g_ceph_context)) { derr << "Couldn't init storage provider (RADOS)" << dendl; return EIO; } RGWProcess process(g_ceph_context, g_conf->rgw_thread_pool_size); Mutex lock("rgw_timer_lock"); SafeTimer timer(g_ceph_context, lock); lock.Lock(); timer.init(); timer.add_event_after(g_conf->rgw_maintenance_tick_interval, new C_RGWMaintenanceTick(&timer)); lock.Unlock(); process.run(); lock.Lock(); timer.shutdown(); lock.Unlock(); return 0; } <commit_msg>rgw: remove preallocating pools maintenance tick<commit_after>#include <stdlib.h> #include <stdio.h> #include <string.h> #include <stdarg.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <signal.h> #include <curl/curl.h> #include "fcgiapp.h" #include "common/ceph_argparse.h" #include "global/global_init.h" #include "common/config.h" #include "common/errno.h" #include "common/WorkQueue.h" #include "common/Timer.h" #include "rgw_common.h" #include "rgw_access.h" #include "rgw_acl.h" #include "rgw_user.h" #include "rgw_op.h" #include "rgw_rest.h" #include "rgw_swift.h" #include "rgw_log.h" #include "rgw_bucket.h" #include <map> #include <string> #include <vector> #include <iostream> #include <sstream> #include "include/types.h" #include "common/BackTrace.h" using namespace std; static sighandler_t sighandler_usr1; static sighandler_t sighandler_alrm; #define SOCKET_BACKLOG 20 static void godown_handler(int signum) { FCGX_ShutdownPending(); signal(signum, sighandler_usr1); alarm(5); } static void godown_alarm(int signum) { _exit(0); } class RGWProcess { deque<FCGX_Request *> m_fcgx_queue; ThreadPool m_tp; struct RGWWQ : public ThreadPool::WorkQueue<FCGX_Request> { RGWProcess *process; RGWWQ(RGWProcess *p, time_t timeout, time_t suicide_timeout, ThreadPool *tp) : ThreadPool::WorkQueue<FCGX_Request>("RGWWQ", timeout, suicide_timeout, tp), process(p) {} bool _enqueue(FCGX_Request *req) { process->m_fcgx_queue.push_back(req); RGW_LOG(20) << "enqueued request fcgx=" << hex << req << dec << dendl; _dump_queue(); return true; } void _dequeue(FCGX_Request *req) { assert(0); } bool _empty() { return process->m_fcgx_queue.empty(); } FCGX_Request *_dequeue() { if (process->m_fcgx_queue.empty()) return NULL; FCGX_Request *req = process->m_fcgx_queue.front(); process->m_fcgx_queue.pop_front(); RGW_LOG(20) << "dequeued request fcgx=" << hex << req << dec << dendl; _dump_queue(); return req; } void _process(FCGX_Request *fcgx) { process->handle_request(fcgx); } void _dump_queue() { deque<FCGX_Request *>::iterator iter; if (process->m_fcgx_queue.size() == 0) { RGW_LOG(20) << "RGWWQ: empty" << dendl; return; } RGW_LOG(20) << "RGWWQ:" << dendl; for (iter = process->m_fcgx_queue.begin(); iter != process->m_fcgx_queue.end(); ++iter) { RGW_LOG(20) << "fcgx: " << hex << *iter << dec << dendl; } } void _clear() { assert(process->m_fcgx_queue.empty()); } } req_wq; public: RGWProcess(CephContext *cct, int num_threads) : m_tp(cct, "RGWProcess::m_tp", num_threads), req_wq(this, g_conf->rgw_op_thread_timeout, g_conf->rgw_op_thread_suicide_timeout, &m_tp) {} void run(); void handle_request(FCGX_Request *fcgx); }; void RGWProcess::run() { int s = 0; if (!g_conf->rgw_socket_path.empty()) { string path_str = g_conf->rgw_socket_path; const char *path = path_str.c_str(); s = FCGX_OpenSocket(path, SOCKET_BACKLOG); if (s < 0) { RGW_LOG(0) << "ERROR: FCGX_OpenSocket (" << path << ") returned " << s << dendl; return; } if (chmod(path, 0777) < 0) { RGW_LOG(0) << "WARNING: couldn't set permissions on unix domain socket" << dendl; } } m_tp.start(); for (;;) { FCGX_Request *fcgx = new FCGX_Request; RGW_LOG(10) << "allocated request fcgx=" << hex << fcgx << dec << dendl; FCGX_InitRequest(fcgx, s, 0); int ret = FCGX_Accept_r(fcgx); if (ret < 0) break; req_wq.queue(fcgx); } m_tp.stop(); } static int call_log_intent(void *ctx, rgw_obj& obj, RGWIntentEvent intent) { struct req_state *s = (struct req_state *)ctx; return rgw_log_intent(s, obj, intent); } void RGWProcess::handle_request(FCGX_Request *fcgx) { RGWRESTMgr rest; int ret; RGWEnv rgw_env; RGW_LOG(0) << "====== starting new request fcgx=" << hex << fcgx << dec << " =====" << dendl; rgw_env.init(fcgx->envp); struct req_state *s = new req_state(&rgw_env); s->obj_ctx = rgwstore->create_context(s); rgwstore->set_intent_cb(s->obj_ctx, call_log_intent); RGWOp *op = NULL; int init_error = 0; RGWHandler *handler = rest.get_handler(s, fcgx, &init_error); if (init_error != 0) { abort_early(s, init_error); goto done; } ret = handler->authorize(); if (ret < 0) { RGW_LOG(10) << "failed to authorize request" << dendl; abort_early(s, ret); goto done; } if (s->user.suspended) { RGW_LOG(10) << "user is suspended, uid=" << s->user.user_id << dendl; abort_early(s, -ERR_USER_SUSPENDED); goto done; } ret = handler->read_permissions(); if (ret < 0) { abort_early(s, ret); goto done; } op = handler->get_op(); if (op) { ret = op->verify_permission(); if (ret < 0) { abort_early(s, ret); goto done; } if (s->expect_cont) dump_continue(s); op->execute(); } else { abort_early(s, -ERR_METHOD_NOT_ALLOWED); } done: rgw_log_op(s); int http_ret = s->err.http_ret; handler->put_op(op); rgwstore->destroy_context(s->obj_ctx); delete s; FCGX_Finish_r(fcgx); delete fcgx; RGW_LOG(0) << "====== req done fcgx=" << hex << fcgx << dec << " http_status=" << http_ret << " ======" << dendl; } /* * start up the RADOS connection and then handle HTTP messages as they come in */ int main(int argc, const char **argv) { curl_global_init(CURL_GLOBAL_ALL); // dout() messages will be sent to stderr, but FCGX wants messages on stdout // Redirect stderr to stdout. TEMP_FAILURE_RETRY(close(STDERR_FILENO)); if (TEMP_FAILURE_RETRY(dup2(STDOUT_FILENO, STDERR_FILENO) < 0)) { int err = errno; cout << "failed to redirect stderr to stdout: " << cpp_strerror(err) << std::endl; return ENOSYS; } vector<const char*> args; argv_to_vec(argc, argv, args); env_to_vec(args); global_init(args, CEPH_ENTITY_TYPE_CLIENT, CODE_ENVIRONMENT_UTILITY, 0); common_init_finish(g_ceph_context); sighandler_usr1 = signal(SIGUSR1, godown_handler); sighandler_alrm = signal(SIGALRM, godown_alarm); FCGX_Init(); RGWStoreManager store_manager; if (!store_manager.init("rados", g_ceph_context)) { derr << "Couldn't init storage provider (RADOS)" << dendl; return EIO; } RGWProcess process(g_ceph_context, g_conf->rgw_thread_pool_size); process.run(); return 0; } <|endoftext|>
<commit_before>#include "PhysicsManager.hpp" #include <btBulletDynamicsCommon.h> #include <glm/gtx/quaternion.hpp> #include "../Component/RigidBody.hpp" #include "../Component/Shape.hpp" #include "../Entity/Entity.hpp" #include "../Physics/GlmConversion.hpp" #include "../Physics/Shape.hpp" #include "../Physics/Trigger.hpp" #include "../Physics/TriggerObserver.hpp" #include "../Util/Json.hpp" PhysicsManager::PhysicsManager() { // The broadphase is used to quickly cull bodies that will not collide with // each other, normally by leveraging some simpler (and rough) test such as // bounding boxes. broadphase = new btDbvtBroadphase; // With the collision configuration one can configure collision detection // algorithms. collisionConfiguration = new btDefaultCollisionConfiguration; dispatcher = new btCollisionDispatcher(collisionConfiguration); // The solver makes objects interact by making use of gravity, collisions, // game logic supplied forces, and constraints. solver = new btSequentialImpulseConstraintSolver; // The dynamics world encompasses objects included in the simulation. dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration); // Y axis up dynamicsWorld->setGravity(btVector3(0, -9.82, 0)); // Set the lockbox key we will use for lockboxes created in here. triggerLockBoxKey.reset(new Utility::LockBox<Physics::Trigger>::Key()); } PhysicsManager::~PhysicsManager() { delete dynamicsWorld; delete solver; delete dispatcher; delete collisionConfiguration; delete broadphase; for (auto t : triggers) delete t; } void PhysicsManager::Update(float deltaTime) { for (auto rigidBodyComp : rigidBodyComponents.GetAll()) { if (rigidBodyComp->IsKilled() || !rigidBodyComp->entity->enabled) { continue; } auto worldPos = rigidBodyComp->entity->GetWorldPosition(); auto worldOrientation = rigidBodyComp->entity->GetWorldOrientation(); if (rigidBodyComp->IsKinematic()) { rigidBodyComp->SetPosition(worldPos); rigidBodyComp->SetOrientation(worldOrientation); } else if (rigidBodyComp->GetForceTransformSync()) { dynamicsWorld->removeRigidBody(rigidBodyComp->GetBulletRigidBody()); rigidBodyComp->SetPosition(worldPos); rigidBodyComp->SetOrientation(worldOrientation); rigidBodyComp->GetBulletRigidBody()->activate(true); // To wake up from potentially sleeping state dynamicsWorld->addRigidBody(rigidBodyComp->GetBulletRigidBody()); rigidBodyComp->SetForceTransformSync(false); } } dynamicsWorld->stepSimulation(deltaTime, 10); for (auto trigger : triggers) { trigger->Process(*dynamicsWorld); } } void PhysicsManager::UpdateEntityTransforms() { for (auto rigidBodyComp : rigidBodyComponents.GetAll()) { if (rigidBodyComp->IsKilled() || !rigidBodyComp->entity->enabled) continue; Entity* entity = rigidBodyComp->entity; auto trans = rigidBodyComp->GetBulletRigidBody()->getWorldTransform(); entity->SetWorldPosition(Physics::btToGlm(trans.getOrigin())); entity->SetWorldOrientation(Physics::btToGlm(trans.getRotation())); } } void PhysicsManager::OnTriggerEnter(Component::RigidBody* trigger, Component::RigidBody* object, std::function<void()> callback) { auto t = CreateTrigger(trigger); // Add the callback to the trigger observer t.Open(triggerLockBoxKey, [object, &callback](Physics::Trigger& trigger) { trigger.ForObserver(object->GetBulletRigidBody(), [&callback](Physics::TriggerObserver& observer) { observer.OnEnter(callback); }); }); } void PhysicsManager::OnTriggerRetain(Component::RigidBody* trigger, Component::RigidBody* object, std::function<void()> callback) { auto t = CreateTrigger(trigger); // Add the callback to the trigger observer t.Open(triggerLockBoxKey, [object, &callback](Physics::Trigger& trigger) { trigger.ForObserver(object->GetBulletRigidBody(), [&callback](::Physics::TriggerObserver& observer) { observer.OnRetain(callback); }); }); } void PhysicsManager::OnTriggerLeave(Component::RigidBody* trigger, Component::RigidBody* object, std::function<void()> callback) { auto t = CreateTrigger(trigger); // Add the callback to the trigger observer t.Open(triggerLockBoxKey, [object, &callback](Physics::Trigger& trigger) { trigger.ForObserver(object->GetBulletRigidBody(), [&callback](::Physics::TriggerObserver& observer) { observer.OnLeave(callback); }); }); } Component::RigidBody* PhysicsManager::CreateRigidBody(Entity* owner) { auto comp = rigidBodyComponents.Create(); comp->entity = owner; comp->NewBulletRigidBody(1.0f); auto shapeComp = comp->entity->GetComponent<Component::Shape>(); if (shapeComp) { comp->GetBulletRigidBody()->setCollisionShape(shapeComp->GetShape()->GetShape()); comp->SetMass(1.0f); dynamicsWorld->addRigidBody(comp->GetBulletRigidBody()); } return comp; } Component::RigidBody* PhysicsManager::CreateRigidBody(Entity* owner, const Json::Value& node) { auto comp = rigidBodyComponents.Create(); comp->entity = owner; auto mass = node.get("mass", 1.0f).asFloat(); comp->NewBulletRigidBody(mass); auto kinematic = node.get("kinematic", false).asFloat(); if (kinematic) comp->MakeKinematic(); auto shapeComp = comp->entity->GetComponent<Component::Shape>(); if (shapeComp) { comp->GetBulletRigidBody()->setCollisionShape(shapeComp->GetShape()->GetShape()); comp->SetMass(mass); dynamicsWorld->addRigidBody(comp->GetBulletRigidBody()); } return comp; } Component::Shape* PhysicsManager::CreateShape(Entity* owner) { auto comp = shapeComponents.Create(); comp->entity = owner; auto shape = std::shared_ptr<Physics::Shape>(new Physics::Shape(Physics::Shape::Sphere(1.0f))); comp->SetShape(shape); auto rigidBodyComp = comp->entity->GetComponent<Component::RigidBody>(); if (rigidBodyComp) { rigidBodyComp->GetBulletRigidBody()->setCollisionShape(comp->GetShape()->GetShape()); rigidBodyComp->SetMass(rigidBodyComp->GetMass()); dynamicsWorld->addRigidBody(rigidBodyComp->GetBulletRigidBody()); } return comp; } Component::Shape* PhysicsManager::CreateShape(Entity* owner, const Json::Value& node) { auto comp = shapeComponents.Create(); comp->entity = owner; if (node.isMember("sphere")) { auto sphere = node.get("sphere", {}); auto radius = sphere.get("radius", 1.0f).asFloat(); auto shape = std::shared_ptr<Physics::Shape>(new Physics::Shape(Physics::Shape::Sphere(radius))); comp->SetShape(shape); } else if (node.isMember("plane")) { auto plane = node.get("plane", {}); auto normal = Json::LoadVec3(plane.get("normal", {})); auto planeCoeff = plane.get("planeCoeff", 0.0f).asFloat(); auto shape = std::shared_ptr<Physics::Shape>(new Physics::Shape(Physics::Shape::Plane(normal, planeCoeff))); comp->SetShape(shape); } else if (node.isMember("box")) { auto box = node.get("box", {}); auto width = box.get("width", 1.0f).asFloat(); auto height = box.get("height", 1.0f).asFloat(); auto depth = box.get("depth", 1.0f).asFloat(); auto shape = std::shared_ptr<Physics::Shape>(new Physics::Shape(Physics::Shape::Box(width, height, depth))); comp->SetShape(shape); } else if (node.isMember("cylinder")) { auto cylinder = node.get("cylinder", {}); auto radius = cylinder.get("radius", 1.0f).asFloat(); auto length = cylinder.get("length", 1.0f).asFloat(); auto shape = std::shared_ptr<Physics::Shape>(new Physics::Shape(Physics::Shape::Cylinder(radius, length))); comp->SetShape(shape); } else if (node.isMember("cone")) { auto cone = node.get("cone", {}); auto radius = cone.get("radius", 1.0f).asFloat(); auto height = cone.get("height", 1.0f).asFloat(); auto shape = std::shared_ptr<Physics::Shape>(new Physics::Shape(Physics::Shape::Cone(radius, height))); comp->SetShape(shape); } else if (node.isMember("capsule")) { auto capsule = node.get("capsule", {}); auto radius = capsule.get("radius", 1.0f).asFloat(); auto height = capsule.get("height", 1.0f).asFloat(); auto shape = std::shared_ptr<Physics::Shape>(new Physics::Shape(Physics::Shape::Capsule(radius, height))); comp->SetShape(shape); } auto rigidBodyComp = comp->entity->GetComponent<Component::RigidBody>(); if (rigidBodyComp) { rigidBodyComp->GetBulletRigidBody()->setCollisionShape(comp->GetShape()->GetShape()); rigidBodyComp->SetMass(rigidBodyComp->GetMass()); dynamicsWorld->addRigidBody(rigidBodyComp->GetBulletRigidBody()); } return comp; } Utility::LockBox<Physics::Trigger> PhysicsManager::CreateTrigger(Component::RigidBody* comp) { btTransform trans(btQuaternion(0, 0, 0, 1), ::Physics::glmToBt(comp->entity->position)); Physics::Trigger* trigger = new Physics::Trigger(trans); auto shapeComp = comp->entity->GetComponent<Component::Shape>(); trigger->SetCollisionShape(shapeComp ? shapeComp->GetShape() : nullptr); triggers.push_back(trigger); return Utility::LockBox<Physics::Trigger>(triggerLockBoxKey, trigger); } void PhysicsManager::SetShape(Component::Shape* comp, std::shared_ptr<::Physics::Shape> shape) { comp->SetShape(shape); auto rigidBodyComp = comp->entity->GetComponent<Component::RigidBody>(); if (rigidBodyComp) rigidBodyComp->GetBulletRigidBody()->setCollisionShape(comp->GetShape()->GetShape()); } float PhysicsManager::GetMass(Component::RigidBody* comp) { return comp->GetMass(); } void PhysicsManager::SetMass(Component::RigidBody* comp, float mass) { // Setting mass is only valid with a shape because it also sets inertia. auto shapeComp = comp->entity->GetComponent<Component::Shape>(); if (shapeComp) comp->SetMass(mass); } void PhysicsManager::SetFriction(Component::RigidBody* comp, float friction) { comp->SetFriction(friction); } void PhysicsManager::MakeKinematic(Component::RigidBody* comp) { comp->MakeKinematic(); } void PhysicsManager::MakeDynamic(Component::RigidBody* comp) { comp->MakeDynamic(); } void PhysicsManager::ForceTransformSync(Component::RigidBody* comp) { comp->SetForceTransformSync(true); } const std::vector<Component::Shape*>& PhysicsManager::GetShapeComponents() const { return shapeComponents.GetAll(); } void PhysicsManager::ClearKilledComponents() { rigidBodyComponents.ClearKilled( [this](Component::RigidBody* body) { dynamicsWorld->removeRigidBody(body->GetBulletRigidBody()); }); shapeComponents.ClearKilled(); } <commit_msg>Load friction for rigid bodies from JSON.<commit_after>#include "PhysicsManager.hpp" #include <btBulletDynamicsCommon.h> #include <glm/gtx/quaternion.hpp> #include "../Component/RigidBody.hpp" #include "../Component/Shape.hpp" #include "../Entity/Entity.hpp" #include "../Physics/GlmConversion.hpp" #include "../Physics/Shape.hpp" #include "../Physics/Trigger.hpp" #include "../Physics/TriggerObserver.hpp" #include "../Util/Json.hpp" PhysicsManager::PhysicsManager() { // The broadphase is used to quickly cull bodies that will not collide with // each other, normally by leveraging some simpler (and rough) test such as // bounding boxes. broadphase = new btDbvtBroadphase; // With the collision configuration one can configure collision detection // algorithms. collisionConfiguration = new btDefaultCollisionConfiguration; dispatcher = new btCollisionDispatcher(collisionConfiguration); // The solver makes objects interact by making use of gravity, collisions, // game logic supplied forces, and constraints. solver = new btSequentialImpulseConstraintSolver; // The dynamics world encompasses objects included in the simulation. dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration); // Y axis up dynamicsWorld->setGravity(btVector3(0, -9.82, 0)); // Set the lockbox key we will use for lockboxes created in here. triggerLockBoxKey.reset(new Utility::LockBox<Physics::Trigger>::Key()); } PhysicsManager::~PhysicsManager() { delete dynamicsWorld; delete solver; delete dispatcher; delete collisionConfiguration; delete broadphase; for (auto t : triggers) delete t; } void PhysicsManager::Update(float deltaTime) { for (auto rigidBodyComp : rigidBodyComponents.GetAll()) { if (rigidBodyComp->IsKilled() || !rigidBodyComp->entity->enabled) { continue; } auto worldPos = rigidBodyComp->entity->GetWorldPosition(); auto worldOrientation = rigidBodyComp->entity->GetWorldOrientation(); if (rigidBodyComp->IsKinematic()) { rigidBodyComp->SetPosition(worldPos); rigidBodyComp->SetOrientation(worldOrientation); } else if (rigidBodyComp->GetForceTransformSync()) { dynamicsWorld->removeRigidBody(rigidBodyComp->GetBulletRigidBody()); rigidBodyComp->SetPosition(worldPos); rigidBodyComp->SetOrientation(worldOrientation); rigidBodyComp->GetBulletRigidBody()->activate(true); // To wake up from potentially sleeping state dynamicsWorld->addRigidBody(rigidBodyComp->GetBulletRigidBody()); rigidBodyComp->SetForceTransformSync(false); } } dynamicsWorld->stepSimulation(deltaTime, 10); for (auto trigger : triggers) { trigger->Process(*dynamicsWorld); } } void PhysicsManager::UpdateEntityTransforms() { for (auto rigidBodyComp : rigidBodyComponents.GetAll()) { if (rigidBodyComp->IsKilled() || !rigidBodyComp->entity->enabled) continue; Entity* entity = rigidBodyComp->entity; auto trans = rigidBodyComp->GetBulletRigidBody()->getWorldTransform(); entity->SetWorldPosition(Physics::btToGlm(trans.getOrigin())); entity->SetWorldOrientation(Physics::btToGlm(trans.getRotation())); } } void PhysicsManager::OnTriggerEnter(Component::RigidBody* trigger, Component::RigidBody* object, std::function<void()> callback) { auto t = CreateTrigger(trigger); // Add the callback to the trigger observer t.Open(triggerLockBoxKey, [object, &callback](Physics::Trigger& trigger) { trigger.ForObserver(object->GetBulletRigidBody(), [&callback](Physics::TriggerObserver& observer) { observer.OnEnter(callback); }); }); } void PhysicsManager::OnTriggerRetain(Component::RigidBody* trigger, Component::RigidBody* object, std::function<void()> callback) { auto t = CreateTrigger(trigger); // Add the callback to the trigger observer t.Open(triggerLockBoxKey, [object, &callback](Physics::Trigger& trigger) { trigger.ForObserver(object->GetBulletRigidBody(), [&callback](::Physics::TriggerObserver& observer) { observer.OnRetain(callback); }); }); } void PhysicsManager::OnTriggerLeave(Component::RigidBody* trigger, Component::RigidBody* object, std::function<void()> callback) { auto t = CreateTrigger(trigger); // Add the callback to the trigger observer t.Open(triggerLockBoxKey, [object, &callback](Physics::Trigger& trigger) { trigger.ForObserver(object->GetBulletRigidBody(), [&callback](::Physics::TriggerObserver& observer) { observer.OnLeave(callback); }); }); } Component::RigidBody* PhysicsManager::CreateRigidBody(Entity* owner) { auto comp = rigidBodyComponents.Create(); comp->entity = owner; comp->NewBulletRigidBody(1.0f); auto shapeComp = comp->entity->GetComponent<Component::Shape>(); if (shapeComp) { comp->GetBulletRigidBody()->setCollisionShape(shapeComp->GetShape()->GetShape()); comp->SetMass(1.0f); dynamicsWorld->addRigidBody(comp->GetBulletRigidBody()); } return comp; } Component::RigidBody* PhysicsManager::CreateRigidBody(Entity* owner, const Json::Value& node) { auto comp = rigidBodyComponents.Create(); comp->entity = owner; auto mass = node.get("mass", 1.0f).asFloat(); comp->NewBulletRigidBody(mass); auto friction = node.get("friction", 0.5f).asFloat(); comp->SetFriction(friction); auto kinematic = node.get("kinematic", false).asFloat(); if (kinematic) comp->MakeKinematic(); auto shapeComp = comp->entity->GetComponent<Component::Shape>(); if (shapeComp) { comp->GetBulletRigidBody()->setCollisionShape(shapeComp->GetShape()->GetShape()); comp->SetMass(mass); dynamicsWorld->addRigidBody(comp->GetBulletRigidBody()); } return comp; } Component::Shape* PhysicsManager::CreateShape(Entity* owner) { auto comp = shapeComponents.Create(); comp->entity = owner; auto shape = std::shared_ptr<Physics::Shape>(new Physics::Shape(Physics::Shape::Sphere(1.0f))); comp->SetShape(shape); auto rigidBodyComp = comp->entity->GetComponent<Component::RigidBody>(); if (rigidBodyComp) { rigidBodyComp->GetBulletRigidBody()->setCollisionShape(comp->GetShape()->GetShape()); rigidBodyComp->SetMass(rigidBodyComp->GetMass()); dynamicsWorld->addRigidBody(rigidBodyComp->GetBulletRigidBody()); } return comp; } Component::Shape* PhysicsManager::CreateShape(Entity* owner, const Json::Value& node) { auto comp = shapeComponents.Create(); comp->entity = owner; if (node.isMember("sphere")) { auto sphere = node.get("sphere", {}); auto radius = sphere.get("radius", 1.0f).asFloat(); auto shape = std::shared_ptr<Physics::Shape>(new Physics::Shape(Physics::Shape::Sphere(radius))); comp->SetShape(shape); } else if (node.isMember("plane")) { auto plane = node.get("plane", {}); auto normal = Json::LoadVec3(plane.get("normal", {})); auto planeCoeff = plane.get("planeCoeff", 0.0f).asFloat(); auto shape = std::shared_ptr<Physics::Shape>(new Physics::Shape(Physics::Shape::Plane(normal, planeCoeff))); comp->SetShape(shape); } else if (node.isMember("box")) { auto box = node.get("box", {}); auto width = box.get("width", 1.0f).asFloat(); auto height = box.get("height", 1.0f).asFloat(); auto depth = box.get("depth", 1.0f).asFloat(); auto shape = std::shared_ptr<Physics::Shape>(new Physics::Shape(Physics::Shape::Box(width, height, depth))); comp->SetShape(shape); } else if (node.isMember("cylinder")) { auto cylinder = node.get("cylinder", {}); auto radius = cylinder.get("radius", 1.0f).asFloat(); auto length = cylinder.get("length", 1.0f).asFloat(); auto shape = std::shared_ptr<Physics::Shape>(new Physics::Shape(Physics::Shape::Cylinder(radius, length))); comp->SetShape(shape); } else if (node.isMember("cone")) { auto cone = node.get("cone", {}); auto radius = cone.get("radius", 1.0f).asFloat(); auto height = cone.get("height", 1.0f).asFloat(); auto shape = std::shared_ptr<Physics::Shape>(new Physics::Shape(Physics::Shape::Cone(radius, height))); comp->SetShape(shape); } else if (node.isMember("capsule")) { auto capsule = node.get("capsule", {}); auto radius = capsule.get("radius", 1.0f).asFloat(); auto height = capsule.get("height", 1.0f).asFloat(); auto shape = std::shared_ptr<Physics::Shape>(new Physics::Shape(Physics::Shape::Capsule(radius, height))); comp->SetShape(shape); } auto rigidBodyComp = comp->entity->GetComponent<Component::RigidBody>(); if (rigidBodyComp) { rigidBodyComp->GetBulletRigidBody()->setCollisionShape(comp->GetShape()->GetShape()); rigidBodyComp->SetMass(rigidBodyComp->GetMass()); dynamicsWorld->addRigidBody(rigidBodyComp->GetBulletRigidBody()); } return comp; } Utility::LockBox<Physics::Trigger> PhysicsManager::CreateTrigger(Component::RigidBody* comp) { btTransform trans(btQuaternion(0, 0, 0, 1), ::Physics::glmToBt(comp->entity->position)); Physics::Trigger* trigger = new Physics::Trigger(trans); auto shapeComp = comp->entity->GetComponent<Component::Shape>(); trigger->SetCollisionShape(shapeComp ? shapeComp->GetShape() : nullptr); triggers.push_back(trigger); return Utility::LockBox<Physics::Trigger>(triggerLockBoxKey, trigger); } void PhysicsManager::SetShape(Component::Shape* comp, std::shared_ptr<::Physics::Shape> shape) { comp->SetShape(shape); auto rigidBodyComp = comp->entity->GetComponent<Component::RigidBody>(); if (rigidBodyComp) rigidBodyComp->GetBulletRigidBody()->setCollisionShape(comp->GetShape()->GetShape()); } float PhysicsManager::GetMass(Component::RigidBody* comp) { return comp->GetMass(); } void PhysicsManager::SetMass(Component::RigidBody* comp, float mass) { // Setting mass is only valid with a shape because it also sets inertia. auto shapeComp = comp->entity->GetComponent<Component::Shape>(); if (shapeComp) comp->SetMass(mass); } void PhysicsManager::SetFriction(Component::RigidBody* comp, float friction) { comp->SetFriction(friction); } void PhysicsManager::MakeKinematic(Component::RigidBody* comp) { comp->MakeKinematic(); } void PhysicsManager::MakeDynamic(Component::RigidBody* comp) { comp->MakeDynamic(); } void PhysicsManager::ForceTransformSync(Component::RigidBody* comp) { comp->SetForceTransformSync(true); } const std::vector<Component::Shape*>& PhysicsManager::GetShapeComponents() const { return shapeComponents.GetAll(); } void PhysicsManager::ClearKilledComponents() { rigidBodyComponents.ClearKilled( [this](Component::RigidBody* body) { dynamicsWorld->removeRigidBody(body->GetBulletRigidBody()); }); shapeComponents.ClearKilled(); } <|endoftext|>
<commit_before>#include <Engine/Renderer/Camera/Camera.hpp> #include <Core/Math/Math.hpp> #include <Engine/Renderer/Mesh/Mesh.hpp> #include <Engine/Renderer/RenderObject/RenderObject.hpp> #include <Engine/Renderer/RenderTechnique/ShaderConfigFactory.hpp> namespace Ra { using Core::Math::Pi; using Core::Math::PiDiv2; using Core::Math::PiDiv4; namespace Engine { Camera::Camera( Entity* entity, const std::string& name, Scalar height, Scalar width ) : Component( name, entity ), m_width{width}, m_height{height}, m_aspect{width / height} {} Camera::~Camera() = default; void Camera::initialize() { if ( !m_renderObjects.empty() ) return; // Create the render mesh for the camera auto m = std::make_shared<Mesh>( m_name + "_mesh" ); Ra::Core::Geometry::TriangleMesh triMesh; triMesh.vertices() = {{0_ra, 0_ra, 0_ra}, {-.5_ra, -.5_ra, -1_ra}, {-.5_ra, .5_ra, -1_ra}, {.5_ra, .5_ra, -1_ra}, {.5_ra, -.5_ra, -1_ra}, {-.3_ra, .5_ra, -1_ra}, {0_ra, .7_ra, -1_ra}, {.3_ra, .5_ra, -1_ra}}; triMesh.m_triangles = {{0, 1, 2}, {0, 2, 3}, {0, 3, 4}, {0, 4, 1}, {5, 6, 7}}; m->loadGeometry( std::move( triMesh ) ); Core::Vector4Array c( 8, {.2_ra, .2_ra, .2_ra, 1_ra} ); m->addData( Mesh::VERTEX_COLOR, c ); // Create the RO m_RO = RenderObject::createRenderObject( m_name + "_RO", this, RenderObjectType::Debug, m ); m_RO->getRenderTechnique()->setConfiguration( ShaderConfigurationFactory::getConfiguration( "Plain" ) ); m_RO->setLocalTransform( m_frame ); addRenderObject( m_RO ); } void Camera::show( bool on ) { m_RO->setVisible( on ); } void Camera::applyTransform( const Core::Transform& T ) { Core::Transform t1 = Core::Transform::Identity(); Core::Transform t2 = Core::Transform::Identity(); t1.translation() = -getPosition(); t2.translation() = getPosition(); m_frame = t2 * T * t1 * m_frame; m_RO->setLocalTransform( m_frame ); } void Camera::updateProjMatrix() { switch ( m_projType ) { case ProjType::ORTHOGRAPHIC: { const Scalar dx = m_zoomFactor * .5_ra; const Scalar dy = dx / m_aspect; // ------------ // Compute projection matrix as describe in the doc of gluPerspective() const Scalar l = -dx; // left const Scalar r = dx; // right const Scalar t = dy; // top const Scalar b = -dy; // bottom Core::Vector3 tr( -( r + l ) / ( r - l ), -( t + b ) / ( t - b ), -( ( m_zFar + m_zNear ) / ( m_zFar - m_zNear ) ) ); m_projMatrix.setIdentity(); m_projMatrix.coeffRef( 0, 0 ) = 2_ra / ( r - l ); m_projMatrix.coeffRef( 1, 1 ) = 2_ra / ( t - b ); m_projMatrix.coeffRef( 2, 2 ) = -2_ra / ( m_zFar - m_zNear ); m_projMatrix.block<3, 1>( 0, 3 ) = tr; } break; case ProjType::PERSPECTIVE: { // Compute projection matrix as describe in the doc of gluPerspective() const Scalar f = std::tan( ( PiDiv2 ) - ( m_fov * m_zoomFactor * .5_ra ) ); const Scalar diff = m_zNear - m_zFar; m_projMatrix.setZero(); m_projMatrix.coeffRef( 0, 0 ) = f / m_aspect; m_projMatrix.coeffRef( 1, 1 ) = f; m_projMatrix.coeffRef( 2, 2 ) = ( m_zFar + m_zNear ) / diff; m_projMatrix.coeffRef( 2, 3 ) = ( 2_ra * m_zFar * m_zNear ) / diff; m_projMatrix.coeffRef( 3, 2 ) = -1_ra; } break; default: break; } } Core::Ray Camera::getRayFromScreen( const Core::Vector2& pix ) const { // Ray starts from the camera's current position. return Core::Ray::Through( getPosition(), unProject( pix ) ); } } // namespace Engine } // namespace Ra <commit_msg>Add core assert to guard Camera's m_RO access. (#456)<commit_after>#include <Engine/Renderer/Camera/Camera.hpp> #include <Core/Math/Math.hpp> #include <Engine/Renderer/Mesh/Mesh.hpp> #include <Engine/Renderer/RenderObject/RenderObject.hpp> #include <Engine/Renderer/RenderTechnique/ShaderConfigFactory.hpp> namespace Ra { using Core::Math::Pi; using Core::Math::PiDiv2; using Core::Math::PiDiv4; namespace Engine { Camera::Camera( Entity* entity, const std::string& name, Scalar height, Scalar width ) : Component( name, entity ), m_width{width}, m_height{height}, m_aspect{width / height} {} Camera::~Camera() = default; void Camera::initialize() { if ( !m_renderObjects.empty() ) return; // Create the render mesh for the camera auto m = std::make_shared<Mesh>( m_name + "_mesh" ); Ra::Core::Geometry::TriangleMesh triMesh; triMesh.vertices() = {{0_ra, 0_ra, 0_ra}, {-.5_ra, -.5_ra, -1_ra}, {-.5_ra, .5_ra, -1_ra}, {.5_ra, .5_ra, -1_ra}, {.5_ra, -.5_ra, -1_ra}, {-.3_ra, .5_ra, -1_ra}, {0_ra, .7_ra, -1_ra}, {.3_ra, .5_ra, -1_ra}}; triMesh.m_triangles = {{0, 1, 2}, {0, 2, 3}, {0, 3, 4}, {0, 4, 1}, {5, 6, 7}}; m->loadGeometry( std::move( triMesh ) ); Core::Vector4Array c( 8, {.2_ra, .2_ra, .2_ra, 1_ra} ); m->addData( Mesh::VERTEX_COLOR, c ); // Create the RO m_RO = RenderObject::createRenderObject( m_name + "_RO", this, RenderObjectType::Debug, m ); m_RO->getRenderTechnique()->setConfiguration( ShaderConfigurationFactory::getConfiguration( "Plain" ) ); m_RO->setLocalTransform( m_frame ); addRenderObject( m_RO ); } void Camera::show( bool on ) { CORE_ASSERT( m_RO, "Camera's render object must be initialize with Camera::intialize()" ); m_RO->setVisible( on ); } void Camera::applyTransform( const Core::Transform& T ) { CORE_ASSERT( m_RO, "Camera's render object must be initialize with Camera::intialize()" ); Core::Transform t1 = Core::Transform::Identity(); Core::Transform t2 = Core::Transform::Identity(); t1.translation() = -getPosition(); t2.translation() = getPosition(); m_frame = t2 * T * t1 * m_frame; m_RO->setLocalTransform( m_frame ); } void Camera::updateProjMatrix() { switch ( m_projType ) { case ProjType::ORTHOGRAPHIC: { const Scalar dx = m_zoomFactor * .5_ra; const Scalar dy = dx / m_aspect; // ------------ // Compute projection matrix as describe in the doc of gluPerspective() const Scalar l = -dx; // left const Scalar r = dx; // right const Scalar t = dy; // top const Scalar b = -dy; // bottom Core::Vector3 tr( -( r + l ) / ( r - l ), -( t + b ) / ( t - b ), -( ( m_zFar + m_zNear ) / ( m_zFar - m_zNear ) ) ); m_projMatrix.setIdentity(); m_projMatrix.coeffRef( 0, 0 ) = 2_ra / ( r - l ); m_projMatrix.coeffRef( 1, 1 ) = 2_ra / ( t - b ); m_projMatrix.coeffRef( 2, 2 ) = -2_ra / ( m_zFar - m_zNear ); m_projMatrix.block<3, 1>( 0, 3 ) = tr; } break; case ProjType::PERSPECTIVE: { // Compute projection matrix as describe in the doc of gluPerspective() const Scalar f = std::tan( ( PiDiv2 ) - ( m_fov * m_zoomFactor * .5_ra ) ); const Scalar diff = m_zNear - m_zFar; m_projMatrix.setZero(); m_projMatrix.coeffRef( 0, 0 ) = f / m_aspect; m_projMatrix.coeffRef( 1, 1 ) = f; m_projMatrix.coeffRef( 2, 2 ) = ( m_zFar + m_zNear ) / diff; m_projMatrix.coeffRef( 2, 3 ) = ( 2_ra * m_zFar * m_zNear ) / diff; m_projMatrix.coeffRef( 3, 2 ) = -1_ra; } break; default: break; } } Core::Ray Camera::getRayFromScreen( const Core::Vector2& pix ) const { // Ray starts from the camera's current position. return Core::Ray::Through( getPosition(), unProject( pix ) ); } } // namespace Engine } // namespace Ra <|endoftext|>
<commit_before>#include <Engine/Renderer/Camera/Camera.hpp> namespace Ra { namespace Engine { inline Core::Transform Camera::getFrame() const { return m_frame; } inline void Camera::setFrame( const Core::Transform& frame ) { m_frame = frame; } inline Core::Vector3 Camera::getPosition() const { return ( m_frame.translation() ); } inline void Camera::setPosition( const Core::Vector3& position) { m_frame.translation() = position; } inline Core::Vector3 Camera::getDirection() const { return ( -m_frame.affine().block< 3, 1 >( 0, 2 ) ); } inline void Camera::setDirection( const Core::Vector3& direction ) { Core::Transform T = Core::Transform::Identity(); T.rotate(Core::Quaternion::FromTwoVectors(getDirection().normalized(), direction.normalized())); applyTransform(T); } inline Core::Vector3 Camera::getUpVector() const { return ( m_frame.affine().block< 3, 1 >( 0, 1 ) ); } inline void Camera::setUpVector( const Core::Vector3& upVector ) { Core::Transform T = Core::Transform::Identity(); T.rotate(Core::Quaternion::FromTwoVectors(getUpVector(), upVector.normalized())); applyTransform(T); } inline Core::Vector3 Camera::getRightVector() const { return ( m_frame.affine().block< 3, 1 >( 0, 0 ) ); } inline Scalar Camera::getFOV() const { return m_fov; } inline void Camera::setFOV( const Scalar fov ) { m_fov = fov; updateProjMatrix(); } inline Scalar Camera::getZNear() const { return m_zNear; } inline void Camera::setZNear( const Scalar zNear ) { m_zNear = zNear; updateProjMatrix(); } inline Scalar Camera::getZFar() const { return m_zFar; } inline void Camera::setZFar( const Scalar zFar ) { m_zFar = zFar; updateProjMatrix(); } inline Scalar Camera::getZoomFactor() const { return m_zoomFactor; } inline void Camera::setZoomFactor( const Scalar& zoomFactor ) { m_zoomFactor = zoomFactor; updateProjMatrix(); } inline Scalar Camera::getWidth() const { return m_width; } inline Scalar Camera::getHeight() const { return m_height; } inline void Camera::resize(Scalar width, Scalar height) { m_width = width; m_height = height; updateProjMatrix(); } inline Camera::ProjType Camera::getProjType() const { return m_projType; } inline void Camera::setProjType( const ProjType& projectionType ) { m_projType = projectionType; } inline Core::Matrix4 Camera::getViewMatrix() const { return m_frame.inverse().matrix(); } inline Core::Matrix4 Camera::getProjMatrix() const { return m_projMatrix; } } // End of Engine } // End of Ra <commit_msg>Fix camera flipping on 180' turn<commit_after>#include <Engine/Renderer/Camera/Camera.hpp> namespace Ra { namespace Engine { inline Core::Transform Camera::getFrame() const { return m_frame; } inline void Camera::setFrame( const Core::Transform& frame ) { m_frame = frame; } inline Core::Vector3 Camera::getPosition() const { return ( m_frame.translation() ); } inline void Camera::setPosition( const Core::Vector3& position) { m_frame.translation() = position; } inline Core::Vector3 Camera::getDirection() const { return ( -m_frame.affine().block< 3, 1 >( 0, 2 ) ); } inline void Camera::setDirection( const Core::Vector3& direction ) { Core::Transform T = Core::Transform::Identity(); // Special case if two directions are exactly opposites we constrain. // to rotate around the up vector. if ( getDirection().cross(direction).squaredNorm() == 0.f && getDirection().dot(direction) < 0.f) { T.rotate(Core::AngleAxis(Scalar(M_PI_2), getUpVector())); } else { T.rotate(Core::Quaternion::FromTwoVectors(getDirection(), direction)); } applyTransform(T); } inline Core::Vector3 Camera::getUpVector() const { return ( m_frame.affine().block< 3, 1 >( 0, 1 ) ); } inline void Camera::setUpVector( const Core::Vector3& upVector ) { Core::Transform T = Core::Transform::Identity(); T.rotate(Core::Quaternion::FromTwoVectors(getUpVector(), upVector)); applyTransform(T); } inline Core::Vector3 Camera::getRightVector() const { return ( m_frame.affine().block< 3, 1 >( 0, 0 ) ); } inline Scalar Camera::getFOV() const { return m_fov; } inline void Camera::setFOV( const Scalar fov ) { m_fov = fov; updateProjMatrix(); } inline Scalar Camera::getZNear() const { return m_zNear; } inline void Camera::setZNear( const Scalar zNear ) { m_zNear = zNear; updateProjMatrix(); } inline Scalar Camera::getZFar() const { return m_zFar; } inline void Camera::setZFar( const Scalar zFar ) { m_zFar = zFar; updateProjMatrix(); } inline Scalar Camera::getZoomFactor() const { return m_zoomFactor; } inline void Camera::setZoomFactor( const Scalar& zoomFactor ) { m_zoomFactor = zoomFactor; updateProjMatrix(); } inline Scalar Camera::getWidth() const { return m_width; } inline Scalar Camera::getHeight() const { return m_height; } inline void Camera::resize(Scalar width, Scalar height) { m_width = width; m_height = height; updateProjMatrix(); } inline Camera::ProjType Camera::getProjType() const { return m_projType; } inline void Camera::setProjType( const ProjType& projectionType ) { m_projType = projectionType; } inline Core::Matrix4 Camera::getViewMatrix() const { return m_frame.inverse().matrix(); } inline Core::Matrix4 Camera::getProjMatrix() const { return m_projMatrix; } } // End of Engine } // End of Ra <|endoftext|>
<commit_before>/* * Logging infrastructure that aims to support multi-threading, * and ansi colors. */ #include "rust_internal.h" #include "util/array_list.h" #include <stdarg.h> #include <stdlib.h> #include <string.h> static const char * _foreground_colors[] = { "[37m", "[31m", "[1;31m", "[32m", "[1;32m", "[33m", "[1;33m", "[31m", "[1;31m", "[35m", "[1;35m", "[36m", "[1;36m" }; /** * Synchronizes access to the underlying logging mechanism. */ static lock_and_signal _log_lock; static uint32_t _last_thread_id; rust_log::rust_log(rust_srv *srv, rust_dom *dom) : _srv(srv), _dom(dom), _use_colors(getenv("RUST_COLOR_LOG")) { } rust_log::~rust_log() { } const uint16_t hash(uintptr_t ptr) { // Robert Jenkins' 32 bit integer hash function ptr = (ptr + 0x7ed55d16) + (ptr << 12); ptr = (ptr ^ 0xc761c23c) ^ (ptr >> 19); ptr = (ptr + 0x165667b1) + (ptr << 5); ptr = (ptr + 0xd3a2646c) ^ (ptr << 9); ptr = (ptr + 0xfd7046c5) + (ptr << 3); ptr = (ptr ^ 0xb55a4f09) ^ (ptr >> 16); return (uint16_t) ptr; } const char * get_color(uintptr_t ptr) { return _foreground_colors[hash(ptr) % rust_log::LIGHTTEAL]; } char * copy_string(char *dst, const char *src, size_t length) { return strncpy(dst, src, length) + length; } char * append_string(char *buffer, const char *format, ...) { if (buffer != NULL && format) { va_list args; va_start(args, format); size_t off = strlen(buffer); vsnprintf(buffer + off, BUF_BYTES - off, format, args); va_end(args); } return buffer; } char * append_string(char *buffer, rust_log::ansi_color color, const char *format, ...) { if (buffer != NULL && format) { append_string(buffer, "\x1b%s", _foreground_colors[color]); va_list args; va_start(args, format); size_t off = strlen(buffer); vsnprintf(buffer + off, BUF_BYTES - off, format, args); va_end(args); append_string(buffer, "\x1b[0m"); } return buffer; } void rust_log::trace_ln(uint32_t thread_id, char *prefix, char *message) { char buffer[BUF_BYTES] = ""; _log_lock.lock(); append_string(buffer, "%-34s", prefix); append_string(buffer, "%s", message); if (_last_thread_id != thread_id) { _last_thread_id = thread_id; _srv->log("---"); } _srv->log(buffer); _log_lock.unlock(); } void rust_log::trace_ln(rust_task *task, uint32_t level, char *message) { #if defined(__WIN32__) uint32_t thread_id = 0; #else uint32_t thread_id = hash((uint32_t) pthread_self()); #endif char prefix[BUF_BYTES] = ""; if (_dom && _dom->name) { append_string(prefix, "%04" PRIxPTR ":%.10s:", thread_id, _dom->name); } else { append_string(prefix, "%04" PRIxPTR ":0x%08" PRIxPTR ":", thread_id, (uintptr_t) _dom); } if (task) { if (task->name) { append_string(prefix, "%.10s:", task->name); } else { append_string(prefix, "0x%08" PRIxPTR ":", (uintptr_t) task); } } trace_ln(thread_id, prefix, message); } // Reading log directives and setting log level vars struct mod_entry { const char* name; size_t* state; }; struct cratemap { const mod_entry* entries; const cratemap* children[1]; }; struct log_directive { char* name; size_t level; }; const size_t max_log_directives = 255; const size_t max_log_level = 1; const size_t default_log_level = 0; // This is a rather ugly parser for strings in the form // "crate1,crate2.mod3,crate3.x=1". Log levels are 0-1 for now, // eventually we'll have 0-3. size_t parse_logging_spec(char* spec, log_directive* dirs) { size_t dir = 0; while (dir < max_log_directives && *spec) { char* start = spec; char cur; while (true) { cur = *spec; if (cur == ',' || cur == '=' || cur == '\0') { if (start == spec) {spec++; break;} if (*spec != '\0') { *spec = '\0'; spec++; } size_t level = max_log_level; if (cur == '=' && *spec != '\0') { level = *spec - '0'; if (level > max_log_level) level = max_log_level; if (*spec) ++spec; } dirs[dir].name = start; dirs[dir++].level = level; break; } else { spec++; } } } return dir; } void update_module_map(const mod_entry* map, log_directive* dirs, size_t n_dirs, size_t *n_matches) { for (const mod_entry* cur = map; cur->name; cur++) { size_t level = default_log_level, longest_match = 0; for (size_t d = 0; d < n_dirs; d++) { if (strstr(cur->name, dirs[d].name) == cur->name && strlen(dirs[d].name) > longest_match) { longest_match = strlen(dirs[d].name); level = dirs[d].level; } } *cur->state = level; (*n_matches)++; } } void update_crate_map(const cratemap* map, log_directive* dirs, size_t n_dirs, size_t *n_matches) { // First update log levels for this crate update_module_map(map->entries, dirs, n_dirs, n_matches); // Then recurse on linked crates // FIXME this does double work in diamond-shaped deps. could keep // a set of visited addresses, if it turns out to be actually slow for (size_t i = 0; map->children[i]; i++) { update_crate_map(map->children[i], dirs, n_dirs, n_matches); } } void print_crate_log_map(const cratemap* map) { for (const mod_entry* cur = map->entries; cur->name; cur++) { printf(" %s\n", cur->name); } for (size_t i = 0; map->children[i]; i++) { print_crate_log_map(map->children[i]); } } // These are pseudo-modules used to control logging in the runtime. size_t log_rt_mem; size_t log_rt_comm; size_t log_rt_task; size_t log_rt_dom; size_t log_rt_trace; size_t log_rt_cache; size_t log_rt_upcall; size_t log_rt_timer; size_t log_rt_gc; size_t log_rt_stdlib; size_t log_rt_kern; size_t log_rt_backtrace; static const mod_entry _rt_module_map[] = {{"::rt::mem", &log_rt_mem}, {"::rt::comm", &log_rt_comm}, {"::rt::task", &log_rt_task}, {"::rt::dom", &log_rt_dom}, {"::rt::trace", &log_rt_trace}, {"::rt::cache", &log_rt_cache}, {"::rt::upcall", &log_rt_upcall}, {"::rt::timer", &log_rt_timer}, {"::rt::gc", &log_rt_gc}, {"::rt::stdlib", &log_rt_stdlib}, {"::rt::kern", &log_rt_kern}, {"::rt::backtrace", &log_rt_backtrace}, {NULL, NULL}}; void update_log_settings(void* crate_map, char* settings) { char* buffer = NULL; log_directive dirs[256]; size_t n_dirs = 0; if (settings) { if (strcmp(settings, "::help") == 0 || strcmp(settings, "?") == 0) { printf("\nCrate log map:\n\n"); print_crate_log_map((const cratemap*)crate_map); printf("\n"); exit(1); } size_t buflen = strlen(settings) + 1; buffer = (char*)malloc(buflen); strncpy(buffer, settings, buflen); n_dirs = parse_logging_spec(buffer, &dirs[0]); } size_t n_matches = 0; update_module_map(_rt_module_map, &dirs[0], n_dirs, &n_matches); update_crate_map((const cratemap*)crate_map, &dirs[0], n_dirs, &n_matches); if (n_matches < n_dirs) { printf("warning: got %d RUST_LOG specs, enabled %d flags.", n_dirs, n_matches); } free(buffer); } // // Local Variables: // mode: C++ // fill-column: 78; // indent-tabs-mode: nil // c-basic-offset: 4 // buffer-file-coding-system: utf-8-unix // compile-command: "make -k -C $RBUILD 2>&1 | sed -e 's/\\/x\\//x:\\//g'"; // End: // <commit_msg>Fix printf flags.<commit_after>/* * Logging infrastructure that aims to support multi-threading, * and ansi colors. */ #include "rust_internal.h" #include "util/array_list.h" #include <stdarg.h> #include <stdlib.h> #include <string.h> static const char * _foreground_colors[] = { "[37m", "[31m", "[1;31m", "[32m", "[1;32m", "[33m", "[1;33m", "[31m", "[1;31m", "[35m", "[1;35m", "[36m", "[1;36m" }; /** * Synchronizes access to the underlying logging mechanism. */ static lock_and_signal _log_lock; static uint32_t _last_thread_id; rust_log::rust_log(rust_srv *srv, rust_dom *dom) : _srv(srv), _dom(dom), _use_colors(getenv("RUST_COLOR_LOG")) { } rust_log::~rust_log() { } const uint16_t hash(uintptr_t ptr) { // Robert Jenkins' 32 bit integer hash function ptr = (ptr + 0x7ed55d16) + (ptr << 12); ptr = (ptr ^ 0xc761c23c) ^ (ptr >> 19); ptr = (ptr + 0x165667b1) + (ptr << 5); ptr = (ptr + 0xd3a2646c) ^ (ptr << 9); ptr = (ptr + 0xfd7046c5) + (ptr << 3); ptr = (ptr ^ 0xb55a4f09) ^ (ptr >> 16); return (uint16_t) ptr; } const char * get_color(uintptr_t ptr) { return _foreground_colors[hash(ptr) % rust_log::LIGHTTEAL]; } char * copy_string(char *dst, const char *src, size_t length) { return strncpy(dst, src, length) + length; } char * append_string(char *buffer, const char *format, ...) { if (buffer != NULL && format) { va_list args; va_start(args, format); size_t off = strlen(buffer); vsnprintf(buffer + off, BUF_BYTES - off, format, args); va_end(args); } return buffer; } char * append_string(char *buffer, rust_log::ansi_color color, const char *format, ...) { if (buffer != NULL && format) { append_string(buffer, "\x1b%s", _foreground_colors[color]); va_list args; va_start(args, format); size_t off = strlen(buffer); vsnprintf(buffer + off, BUF_BYTES - off, format, args); va_end(args); append_string(buffer, "\x1b[0m"); } return buffer; } void rust_log::trace_ln(uint32_t thread_id, char *prefix, char *message) { char buffer[BUF_BYTES] = ""; _log_lock.lock(); append_string(buffer, "%-34s", prefix); append_string(buffer, "%s", message); if (_last_thread_id != thread_id) { _last_thread_id = thread_id; _srv->log("---"); } _srv->log(buffer); _log_lock.unlock(); } void rust_log::trace_ln(rust_task *task, uint32_t level, char *message) { #if defined(__WIN32__) uint32_t thread_id = 0; #else uint32_t thread_id = hash((uint32_t) pthread_self()); #endif char prefix[BUF_BYTES] = ""; if (_dom && _dom->name) { append_string(prefix, "%04" PRIxPTR ":%.10s:", thread_id, _dom->name); } else { append_string(prefix, "%04" PRIxPTR ":0x%08" PRIxPTR ":", thread_id, (uintptr_t) _dom); } if (task) { if (task->name) { append_string(prefix, "%.10s:", task->name); } else { append_string(prefix, "0x%08" PRIxPTR ":", (uintptr_t) task); } } trace_ln(thread_id, prefix, message); } // Reading log directives and setting log level vars struct mod_entry { const char* name; size_t* state; }; struct cratemap { const mod_entry* entries; const cratemap* children[1]; }; struct log_directive { char* name; size_t level; }; const size_t max_log_directives = 255; const size_t max_log_level = 1; const size_t default_log_level = 0; // This is a rather ugly parser for strings in the form // "crate1,crate2.mod3,crate3.x=1". Log levels are 0-1 for now, // eventually we'll have 0-3. size_t parse_logging_spec(char* spec, log_directive* dirs) { size_t dir = 0; while (dir < max_log_directives && *spec) { char* start = spec; char cur; while (true) { cur = *spec; if (cur == ',' || cur == '=' || cur == '\0') { if (start == spec) {spec++; break;} if (*spec != '\0') { *spec = '\0'; spec++; } size_t level = max_log_level; if (cur == '=' && *spec != '\0') { level = *spec - '0'; if (level > max_log_level) level = max_log_level; if (*spec) ++spec; } dirs[dir].name = start; dirs[dir++].level = level; break; } else { spec++; } } } return dir; } void update_module_map(const mod_entry* map, log_directive* dirs, size_t n_dirs, size_t *n_matches) { for (const mod_entry* cur = map; cur->name; cur++) { size_t level = default_log_level, longest_match = 0; for (size_t d = 0; d < n_dirs; d++) { if (strstr(cur->name, dirs[d].name) == cur->name && strlen(dirs[d].name) > longest_match) { longest_match = strlen(dirs[d].name); level = dirs[d].level; } } *cur->state = level; (*n_matches)++; } } void update_crate_map(const cratemap* map, log_directive* dirs, size_t n_dirs, size_t *n_matches) { // First update log levels for this crate update_module_map(map->entries, dirs, n_dirs, n_matches); // Then recurse on linked crates // FIXME this does double work in diamond-shaped deps. could keep // a set of visited addresses, if it turns out to be actually slow for (size_t i = 0; map->children[i]; i++) { update_crate_map(map->children[i], dirs, n_dirs, n_matches); } } void print_crate_log_map(const cratemap* map) { for (const mod_entry* cur = map->entries; cur->name; cur++) { printf(" %s\n", cur->name); } for (size_t i = 0; map->children[i]; i++) { print_crate_log_map(map->children[i]); } } // These are pseudo-modules used to control logging in the runtime. size_t log_rt_mem; size_t log_rt_comm; size_t log_rt_task; size_t log_rt_dom; size_t log_rt_trace; size_t log_rt_cache; size_t log_rt_upcall; size_t log_rt_timer; size_t log_rt_gc; size_t log_rt_stdlib; size_t log_rt_kern; size_t log_rt_backtrace; static const mod_entry _rt_module_map[] = {{"::rt::mem", &log_rt_mem}, {"::rt::comm", &log_rt_comm}, {"::rt::task", &log_rt_task}, {"::rt::dom", &log_rt_dom}, {"::rt::trace", &log_rt_trace}, {"::rt::cache", &log_rt_cache}, {"::rt::upcall", &log_rt_upcall}, {"::rt::timer", &log_rt_timer}, {"::rt::gc", &log_rt_gc}, {"::rt::stdlib", &log_rt_stdlib}, {"::rt::kern", &log_rt_kern}, {"::rt::backtrace", &log_rt_backtrace}, {NULL, NULL}}; void update_log_settings(void* crate_map, char* settings) { char* buffer = NULL; log_directive dirs[256]; size_t n_dirs = 0; if (settings) { if (strcmp(settings, "::help") == 0 || strcmp(settings, "?") == 0) { printf("\nCrate log map:\n\n"); print_crate_log_map((const cratemap*)crate_map); printf("\n"); exit(1); } size_t buflen = strlen(settings) + 1; buffer = (char*)malloc(buflen); strncpy(buffer, settings, buflen); n_dirs = parse_logging_spec(buffer, &dirs[0]); } size_t n_matches = 0; update_module_map(_rt_module_map, &dirs[0], n_dirs, &n_matches); update_crate_map((const cratemap*)crate_map, &dirs[0], n_dirs, &n_matches); if (n_matches < n_dirs) { printf("warning: got %u RUST_LOG specs, enabled %u flags.", n_dirs, n_matches); } free(buffer); } // // Local Variables: // mode: C++ // fill-column: 78; // indent-tabs-mode: nil // c-basic-offset: 4 // buffer-file-coding-system: utf-8-unix // compile-command: "make -k -C $RBUILD 2>&1 | sed -e 's/\\/x\\//x:\\//g'"; // End: // <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <sstream> #include <string> #include <map> #include <vector> #include <algorithm> #include <cstring> using namespace std; int main(int argc, char *argv[]) { ifstream inFile; map<string, int> wordCount; map<int, vector<string>> byCount; string word = ""; string sLine = ""; int longestLine = 0; int longestWord = 0; int numLongestLines = 0; int numFiles = 0; int numLongestWord = 0; int length = 0; int size = 0; int q = 0; bool mFlag = false; bool cFlag = false; //initialization of the bool bFlag = false; //possible flags bool xFlag = false; //a flag is an argument whose first character is a dash //so any file names or paths that start with a dash are //considered flags //therefore I do not have to check for the //case in which a directory or file's name starts with a - for (int j = 1; j < argc; j++) { if (argv[j][0] == '-') { switch (argv[j][1]) { case 'm': mFlag = true; break; case 'c': cFlag = true; break; case 'b': bFlag = true; break; //if the flag is unrecognized default: //xFlag set to false, string printed //then the loops break and return main xFlag = true; cout << argv[j] << " UNRECOGNIZED FLAG" << endl; break; } } else { numFiles++; } if (xFlag) //stops the main loop { break; } } if (xFlag) // returns main and terminates the program safely { return 0; } else if (numFiles == 0) { cout << "NO FILES" << endl; return 0; } for (int i = 1; i < argc; i++) { if (argv[i][0] != '-') { inFile.open(argv[i]); if (inFile.is_open()) { longestWord = 0; longestLine = 0; wordCount.erase(wordCount.begin(), wordCount.end()); while (getline(inFile, sLine)) { //changes sLine istringstream line(sLine); length = 0; if (!bFlag) { length = sLine.length(); if (length > longestLine) { longestLine = length; numLongestLines = 1; } else if (length == longestLine) { numLongestLines++; } } while (line >> word) { if (bFlag) { length += word.length(); if (word.length() != 0) length++; if (length > longestLine) { longestLine = length; numLongestLines = 1; } else if (length == longestLine) { numLongestLines++; } } if (word.length() == (unsigned)longestWord) { wordCount[word]++; } if ((unsigned)longestWord < word.length()) { wordCount.erase(wordCount.begin(), wordCount.end()); wordCount[word] = 1; longestWord = word.length(); } } } if (longestLine != 0 && bFlag) longestLine--; // to account for no spaces at the end of the line inFile.close(); } else { cout << argv[i] << " FILE NOT FOUND" << endl; continue; } } else { continue; } cout << argv[i] << ":" << endl; if (mFlag) { byCount.erase(byCount.begin(), byCount.end()); map<string, int>::iterator cit; for (cit = wordCount.begin(); cit != wordCount.end(); cit++) { //goes to the map index for the count of the word //then adds the word to the vector at that index byCount[cit->second].push_back(cit->first); } //gets the last key in the map which should be the highest occurring words map<int, vector<string>>::reverse_iterator sit = byCount.rbegin(); //assigns the quantity of highest occurring words to numLongestWord numLongestWord = sit->first; //trims the vector at that key location byCount[numLongestWord].shrink_to_fit(); //sorts the vector at that key location sort(byCount[numLongestWord].begin(), byCount[numLongestWord].end()); vector<string>::iterator qit = byCount[numLongestWord].begin(); size = byCount[numLongestWord].size(); q = 0; while (qit != byCount[numLongestWord].end()) { if (q < size - 1) { if (cFlag) { cout << *qit << "(" << numLongestWord << "), "; } else { cout << *qit << ", "; } } else { if (cFlag) { cout << *qit << "(" << numLongestWord << ")"; } else { cout << *qit; } } q++; qit++; } } else { map<string, int>::iterator it; q = 0; size = wordCount.size(); for (it = wordCount.begin(); it != wordCount.end(); it++) {//sorted and comma-separated longest words if (q < size - 1) { if (cFlag) { cout << it->first << "(" << wordCount[it->first] << "), "; } else { cout << it->first << ", "; } } else { if (cFlag) { cout << it->first << "(" << wordCount[it->first] << ")"; } else { cout << it->first; } } q++; } } if (!wordCount.empty()) { cout << endl; } cout << longestLine; if (cFlag) { cout << "(" << numLongestLines << ")"; } cout << endl; } }<commit_msg>Fixed the program to work with files filled with whitespace<commit_after>#include <iostream> #include <fstream> #include <sstream> #include <string> #include <map> #include <vector> #include <algorithm> #include <cstring> using namespace std; int main(int argc, char *argv[]) { ifstream inFile; map<string, int> wordCount; map<int, vector<string>> byCount; string word = ""; string sLine = ""; int longestLine = 0; int longestWord = 0; int numLongestLines = 1; int numFiles = 0; int numLongestWord = 0; int length = 0; int size = 0; int q = 0; bool mFlag = false; bool cFlag = false; //initialization of the bool bFlag = false; //possible flags bool xFlag = false; //a flag is an argument whose first character is a dash //so any file names or paths that start with a dash are //considered flags //therefore I do not have to check for the //case in which a directory or file's name starts with a - for (int j = 1; j < argc; j++) { if (argv[j][0] == '-') { switch (argv[j][1]) { case 'm': mFlag = true; break; case 'c': cFlag = true; break; case 'b': bFlag = true; break; //if the flag is unrecognized default: //xFlag set to false, string printed //then the loops break and return main xFlag = true; cout << argv[j] << " UNRECOGNIZED FLAG" << endl; break; } } else { numFiles++; } if (xFlag) //stops the main loop { break; } } if (xFlag) // returns main and terminates the program safely { return 0; } else if (numFiles == 0) { cout << "NO FILES" << endl; return 0; } for (int i = 1; i < argc; i++) { if (argv[i][0] != '-') { inFile.open(argv[i]); if (inFile.is_open()) { longestWord = 0; longestLine = 0; numLongestLines = 1; wordCount.erase(wordCount.begin(), wordCount.end()); while (getline(inFile, sLine)) { //changes sLine istringstream line(sLine); length = 0; if (!bFlag) { length = sLine.length(); if (length > longestLine) { longestLine = length; numLongestLines = 1; } else if (length == longestLine) { numLongestLines++; } } while (line >> word) { if (bFlag) { length += word.length(); if (word.length() != 0) length++; if (length > longestLine) { longestLine = length; numLongestLines = 1; } else if (length == longestLine) { numLongestLines++; } } if (word.length() == (unsigned)longestWord) { wordCount[word]++; } if ((unsigned)longestWord < word.length()) { wordCount.erase(wordCount.begin(), wordCount.end()); wordCount[word] = 1; longestWord = word.length(); } } } if (longestLine != 0 && bFlag) longestLine--; // to account for no spaces at the end of the line if (longestLine == 0) { longestLine = 0; numLongestLines = 1; } inFile.close(); } else { cout << argv[i] << " FILE NOT FOUND" << endl; continue; } } else { continue; } cout << argv[i] << ":" << endl; if (mFlag && (longestLine != 0)) { byCount.erase(byCount.begin(), byCount.end()); map<string, int>::iterator cit; for (cit = wordCount.begin(); cit != wordCount.end(); cit++) { //goes to the map index for the count of the word //then adds the word to the vector at that index byCount[cit->second].push_back(cit->first); } //gets the last key in the map which should be the highest occurring words map<int, vector<string>>::reverse_iterator sit = byCount.rbegin(); //assigns the quantity of highest occurring words to numLongestWord numLongestWord = sit->first; //trims the vector at that key location byCount[numLongestWord].shrink_to_fit(); //sorts the vector at that key location sort(byCount[numLongestWord].begin(), byCount[numLongestWord].end()); vector<string>::iterator qit = byCount[numLongestWord].begin(); size = byCount[numLongestWord].size(); q = 0; while (qit != byCount[numLongestWord].end()) { if (q < size - 1) { if (cFlag) { cout << *qit << "(" << numLongestWord << "), "; } else { cout << *qit << ", "; } } else { if (cFlag) { cout << *qit << "(" << numLongestWord << ")"; } else { cout << *qit; } } q++; qit++; } } else { map<string, int>::iterator it; q = 0; size = wordCount.size(); for (it = wordCount.begin(); it != wordCount.end(); it++) {//sorted and comma-separated longest words if (q < size - 1) { if (cFlag) { cout << it->first << "(" << wordCount[it->first] << "), "; } else { cout << it->first << ", "; } } else { if (cFlag) { cout << it->first << "(" << wordCount[it->first] << ")"; } else { cout << it->first; } } q++; } } if (!wordCount.empty()) { cout << endl; } cout << longestLine; if (cFlag) { cout << "(" << numLongestLines << ")"; } cout << endl; } }<|endoftext|>
<commit_before>// Copyright Sergey Anisimov 2016-2017 // MIT License // // Gluino // https://github.com/anisimovsergey/gluino #ifndef MESSAGING_QUEUE_RESOURCE_CLIENT_HPP #define MESSAGING_QUEUE_RESOURCE_CLIENT_HPP #include "QueueClient.hpp" #include "ResourceResponseHandler.hpp" #include "ResourceEventHandler.hpp" #include <vector> namespace Messaging { class QueueResourceClient { TYPE_PTRS(QueueResourceClient) public: QueueResourceClient(std::string resource, QueueClient& queueClient); Core::StatusResult::Unique sendRequest(std::string requestType); Core::StatusResult::Unique sendRequest(std::string requestType, Core::IEntity::Unique content); void addOnResponse(std::string requestType, std::function<void()> onResponse); template<class T> void addOnResponse(std::string requestType, std::function<void(const T&)> onResponse); void addOnEvent(std::string eventType, std::function<void()> onEvent); template<class T> void addOnEvent(std::string eventType, std::function<void(const T&)> onEvent); private: const std::string resource; QueueClient& queueClient; std::vector<ResourceResponseHandler::Unique> responseHandlers; std::vector<ResourceEventHandler::Unique> eventHandlers; void onResponse(const Response& response); void onEvent(const Event& response); }; } #endif /* end of include guard: MESSAGING_QUEUE_RESOURCE_CLIENT_HPP */ <commit_msg>Implementing missing members<commit_after>// Copyright Sergey Anisimov 2016-2017 // MIT License // // Gluino // https://github.com/anisimovsergey/gluino #ifndef MESSAGING_QUEUE_RESOURCE_CLIENT_HPP #define MESSAGING_QUEUE_RESOURCE_CLIENT_HPP #include "QueueClient.hpp" #include "ResourceResponseHandler.hpp" #include "ResourceEventHandler.hpp" #include <vector> namespace Messaging { class QueueResourceClient { TYPE_PTRS(QueueResourceClient) public: QueueResourceClient(std::string resource, QueueClient& queueClient); Core::StatusResult::Unique sendRequest(std::string requestType); Core::StatusResult::Unique sendRequest(std::string requestType, Core::IEntity::Unique content); void addOnResponse(std::string requestType, std::function<void()> onResponse) { responseHandlers.push_back(ResourceResponseHandlerVoid::makeUnique(requestType, onResponse)); } template<class T> void addOnResponse(std::string requestType, std::function<void(const T&)> onResponse) { responseHandlers.push_back(ResourceResponseHandlerTyped<T>::makeUnique(requestType, onResponse)); } void addOnEvent(std::string eventType, std::function<void()> onEvent) { eventHandlers.push_back(ResourceEventHandlerVoid::makeUnique(eventType, onEvent)); } template<class T> void addOnEvent(std::string eventType, std::function<void(const T&)> onEvent) { eventHandlers.push_back(ResourceEventHandlerTyped<T>::makeUnique(eventType, onEvent)); } private: const std::string resource; QueueClient& queueClient; std::vector<ResourceResponseHandler::Unique> responseHandlers; std::vector<ResourceEventHandler::Unique> eventHandlers; void onResponse(const Response& response); void onEvent(const Event& response); }; } #endif /* end of include guard: MESSAGING_QUEUE_RESOURCE_CLIENT_HPP */ <|endoftext|>
<commit_before><commit_msg>Sketcher: Trigger elements widget update on toggle/set construction geometry<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. #include "mfem.hpp" #include "catch.hpp" using namespace mfem; namespace surf_blf { Mesh * GetCylMesh(int type); void trans_skew_cyl(const Vector &x, Vector &r); void sigmaFunc(const Vector &x, DenseMatrix &s); double uExact(const Vector &x) { return (0.25 * (2.0 + x[0]) - x[2]) * (x[2] + 0.25 * (2.0 + x[0])); } TEST_CASE("Embedded Surface Diffusion", "[DiffusionIntegrator]") { for (int type = (int) Element::TRIANGLE; type <= (int) Element::QUADRILATERAL; type++) { int order = 3; Mesh *mesh = GetCylMesh(type); int dim = mesh->Dimension(); mesh->SetCurvature(3); mesh->Transform(trans_skew_cyl); H1_FECollection fec(order, dim); FiniteElementSpace fespace(mesh, &fec); Array<int> ess_tdof_list; if (mesh->bdr_attributes.Size()) { Array<int> ess_bdr(mesh->bdr_attributes.Max()); ess_bdr = 1; fespace.GetEssentialTrueDofs(ess_bdr, ess_tdof_list); } LinearForm b(&fespace); ConstantCoefficient one(1.0); b.AddDomainIntegrator(new DomainLFIntegrator(one)); b.Assemble(); GridFunction x(&fespace); x = 0.0; BilinearForm a(&fespace); MatrixFunctionCoefficient sigma(3, sigmaFunc); a.AddDomainIntegrator(new DiffusionIntegrator(sigma)); a.Assemble(); OperatorPtr A; Vector B, X; a.FormLinearSystem(ess_tdof_list, x, b, A, X, B); GSSmoother M((SparseMatrix&)(*A)); PCG(*A, M, B, X, 0, 200, 1e-12, 0.0); a.RecoverFEMSolution(X, b, x); FunctionCoefficient uCoef(uExact); double err = x.ComputeL2Error(uCoef); REQUIRE(err < 1.5e-3); delete mesh; } } Mesh * GetCylMesh(int type) { Mesh * mesh = NULL; if (type == (int) Element::TRIANGLE) { mesh = new Mesh(2, 12, 16, 8, 3); mesh->AddVertex(-1.0, -1.0, 0.0); mesh->AddVertex( 1.0, -1.0, 0.0); mesh->AddVertex( 1.0, 1.0, 0.0); mesh->AddVertex(-1.0, 1.0, 0.0); mesh->AddVertex(-1.0, -1.0, 1.0); mesh->AddVertex( 1.0, -1.0, 1.0); mesh->AddVertex( 1.0, 1.0, 1.0); mesh->AddVertex(-1.0, 1.0, 1.0); mesh->AddVertex( 0.0, -1.0, 0.5); mesh->AddVertex( 1.0, 0.0, 0.5); mesh->AddVertex( 0.0, 1.0, 0.5); mesh->AddVertex(-1.0, 0.0, 0.5); mesh->AddTriangle(0, 1, 8); mesh->AddTriangle(1, 5, 8); mesh->AddTriangle(5, 4, 8); mesh->AddTriangle(4, 0, 8); mesh->AddTriangle(1, 2, 9); mesh->AddTriangle(2, 6, 9); mesh->AddTriangle(6, 5, 9); mesh->AddTriangle(5, 1, 9); mesh->AddTriangle(2, 3, 10); mesh->AddTriangle(3, 7, 10); mesh->AddTriangle(7, 6, 10); mesh->AddTriangle(6, 2, 10); mesh->AddTriangle(3, 0, 11); mesh->AddTriangle(0, 4, 11); mesh->AddTriangle(4, 7, 11); mesh->AddTriangle(7, 3, 11); mesh->AddBdrSegment(0, 1, 1); mesh->AddBdrSegment(1, 2, 1); mesh->AddBdrSegment(2, 3, 1); mesh->AddBdrSegment(3, 0, 1); mesh->AddBdrSegment(5, 4, 2); mesh->AddBdrSegment(6, 5, 2); mesh->AddBdrSegment(7, 6, 2); mesh->AddBdrSegment(4, 7, 2); } else if (type == (int) Element::QUADRILATERAL) { mesh = new Mesh(2, 8, 4, 8, 3); mesh->AddVertex(-1.0, -1.0, 0.0); mesh->AddVertex( 1.0, -1.0, 0.0); mesh->AddVertex( 1.0, 1.0, 0.0); mesh->AddVertex(-1.0, 1.0, 0.0); mesh->AddVertex(-1.0, -1.0, 1.0); mesh->AddVertex( 1.0, -1.0, 1.0); mesh->AddVertex( 1.0, 1.0, 1.0); mesh->AddVertex(-1.0, 1.0, 1.0); mesh->AddQuad(0, 1, 5, 4); mesh->AddQuad(1, 2, 6, 5); mesh->AddQuad(2, 3, 7, 6); mesh->AddQuad(3, 0, 4, 7); mesh->AddBdrSegment(0, 1, 1); mesh->AddBdrSegment(1, 2, 1); mesh->AddBdrSegment(2, 3, 1); mesh->AddBdrSegment(3, 0, 1); mesh->AddBdrSegment(5, 4, 2); mesh->AddBdrSegment(6, 5, 2); mesh->AddBdrSegment(7, 6, 2); mesh->AddBdrSegment(4, 7, 2); } else { MFEM_ABORT("Unrecognized mesh type " << type << "!"); } mesh->FinalizeTopology(); return mesh; } void trans_skew_cyl(const Vector &x, Vector &r) { r.SetSize(3); double tol = 1e-6; double theta = 0.0; if (fabs(x[1] + 1.0) < tol) { theta = 0.25 * M_PI * (x[0] - 2.0); } else if (fabs(x[0] - 1.0) < tol) { theta = 0.25 * M_PI * x[1]; } else if (fabs(x[1] - 1.0) < tol) { theta = 0.25 * M_PI * (2.0 - x[0]); } else if (fabs(x[0] + 1.0) < tol) { theta = 0.25 * M_PI * (4.0 - x[1]); } else { mfem::out << "side not recognized " << x[0] << " " << x[1] << " " << x[2] << std::endl; } r[0] = cos(theta); r[1] = sin(theta); r[2] = 0.25 * (2.0 * x[2] - 1.0) * (r[0] + 2.0); } void sigmaFunc(const Vector &x, DenseMatrix &s) { s.SetSize(3); double a = 17.0 - 2.0 * x[0] * (1.0 + x[0]); s(0,0) = 0.5 + x[0] * x[0] * (8.0 / a - 0.5); s(0,1) = x[0] * x[1] * (8.0 / a - 0.5); s(0,2) = 0.0; s(1,0) = s(0,1); s(1,1) = 0.5 * x[0] * x[0] + 8.0 * x[1] * x[1] / a; s(1,2) = 0.0; s(2,0) = 0.0; s(2,1) = 0.0; s(2,2) = a / 32.0; } } // namespace surf_blf <commit_msg>Fix copyright date in unit test<commit_after>// Copyright (c) 2010-2021, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. #include "mfem.hpp" #include "catch.hpp" using namespace mfem; namespace surf_blf { Mesh * GetCylMesh(int type); void trans_skew_cyl(const Vector &x, Vector &r); void sigmaFunc(const Vector &x, DenseMatrix &s); double uExact(const Vector &x) { return (0.25 * (2.0 + x[0]) - x[2]) * (x[2] + 0.25 * (2.0 + x[0])); } TEST_CASE("Embedded Surface Diffusion", "[DiffusionIntegrator]") { for (int type = (int) Element::TRIANGLE; type <= (int) Element::QUADRILATERAL; type++) { int order = 3; Mesh *mesh = GetCylMesh(type); int dim = mesh->Dimension(); mesh->SetCurvature(3); mesh->Transform(trans_skew_cyl); H1_FECollection fec(order, dim); FiniteElementSpace fespace(mesh, &fec); Array<int> ess_tdof_list; if (mesh->bdr_attributes.Size()) { Array<int> ess_bdr(mesh->bdr_attributes.Max()); ess_bdr = 1; fespace.GetEssentialTrueDofs(ess_bdr, ess_tdof_list); } LinearForm b(&fespace); ConstantCoefficient one(1.0); b.AddDomainIntegrator(new DomainLFIntegrator(one)); b.Assemble(); GridFunction x(&fespace); x = 0.0; BilinearForm a(&fespace); MatrixFunctionCoefficient sigma(3, sigmaFunc); a.AddDomainIntegrator(new DiffusionIntegrator(sigma)); a.Assemble(); OperatorPtr A; Vector B, X; a.FormLinearSystem(ess_tdof_list, x, b, A, X, B); GSSmoother M((SparseMatrix&)(*A)); PCG(*A, M, B, X, 0, 200, 1e-12, 0.0); a.RecoverFEMSolution(X, b, x); FunctionCoefficient uCoef(uExact); double err = x.ComputeL2Error(uCoef); REQUIRE(err < 1.5e-3); delete mesh; } } Mesh * GetCylMesh(int type) { Mesh * mesh = NULL; if (type == (int) Element::TRIANGLE) { mesh = new Mesh(2, 12, 16, 8, 3); mesh->AddVertex(-1.0, -1.0, 0.0); mesh->AddVertex( 1.0, -1.0, 0.0); mesh->AddVertex( 1.0, 1.0, 0.0); mesh->AddVertex(-1.0, 1.0, 0.0); mesh->AddVertex(-1.0, -1.0, 1.0); mesh->AddVertex( 1.0, -1.0, 1.0); mesh->AddVertex( 1.0, 1.0, 1.0); mesh->AddVertex(-1.0, 1.0, 1.0); mesh->AddVertex( 0.0, -1.0, 0.5); mesh->AddVertex( 1.0, 0.0, 0.5); mesh->AddVertex( 0.0, 1.0, 0.5); mesh->AddVertex(-1.0, 0.0, 0.5); mesh->AddTriangle(0, 1, 8); mesh->AddTriangle(1, 5, 8); mesh->AddTriangle(5, 4, 8); mesh->AddTriangle(4, 0, 8); mesh->AddTriangle(1, 2, 9); mesh->AddTriangle(2, 6, 9); mesh->AddTriangle(6, 5, 9); mesh->AddTriangle(5, 1, 9); mesh->AddTriangle(2, 3, 10); mesh->AddTriangle(3, 7, 10); mesh->AddTriangle(7, 6, 10); mesh->AddTriangle(6, 2, 10); mesh->AddTriangle(3, 0, 11); mesh->AddTriangle(0, 4, 11); mesh->AddTriangle(4, 7, 11); mesh->AddTriangle(7, 3, 11); mesh->AddBdrSegment(0, 1, 1); mesh->AddBdrSegment(1, 2, 1); mesh->AddBdrSegment(2, 3, 1); mesh->AddBdrSegment(3, 0, 1); mesh->AddBdrSegment(5, 4, 2); mesh->AddBdrSegment(6, 5, 2); mesh->AddBdrSegment(7, 6, 2); mesh->AddBdrSegment(4, 7, 2); } else if (type == (int) Element::QUADRILATERAL) { mesh = new Mesh(2, 8, 4, 8, 3); mesh->AddVertex(-1.0, -1.0, 0.0); mesh->AddVertex( 1.0, -1.0, 0.0); mesh->AddVertex( 1.0, 1.0, 0.0); mesh->AddVertex(-1.0, 1.0, 0.0); mesh->AddVertex(-1.0, -1.0, 1.0); mesh->AddVertex( 1.0, -1.0, 1.0); mesh->AddVertex( 1.0, 1.0, 1.0); mesh->AddVertex(-1.0, 1.0, 1.0); mesh->AddQuad(0, 1, 5, 4); mesh->AddQuad(1, 2, 6, 5); mesh->AddQuad(2, 3, 7, 6); mesh->AddQuad(3, 0, 4, 7); mesh->AddBdrSegment(0, 1, 1); mesh->AddBdrSegment(1, 2, 1); mesh->AddBdrSegment(2, 3, 1); mesh->AddBdrSegment(3, 0, 1); mesh->AddBdrSegment(5, 4, 2); mesh->AddBdrSegment(6, 5, 2); mesh->AddBdrSegment(7, 6, 2); mesh->AddBdrSegment(4, 7, 2); } else { MFEM_ABORT("Unrecognized mesh type " << type << "!"); } mesh->FinalizeTopology(); return mesh; } void trans_skew_cyl(const Vector &x, Vector &r) { r.SetSize(3); double tol = 1e-6; double theta = 0.0; if (fabs(x[1] + 1.0) < tol) { theta = 0.25 * M_PI * (x[0] - 2.0); } else if (fabs(x[0] - 1.0) < tol) { theta = 0.25 * M_PI * x[1]; } else if (fabs(x[1] - 1.0) < tol) { theta = 0.25 * M_PI * (2.0 - x[0]); } else if (fabs(x[0] + 1.0) < tol) { theta = 0.25 * M_PI * (4.0 - x[1]); } else { mfem::out << "side not recognized " << x[0] << " " << x[1] << " " << x[2] << std::endl; } r[0] = cos(theta); r[1] = sin(theta); r[2] = 0.25 * (2.0 * x[2] - 1.0) * (r[0] + 2.0); } void sigmaFunc(const Vector &x, DenseMatrix &s) { s.SetSize(3); double a = 17.0 - 2.0 * x[0] * (1.0 + x[0]); s(0,0) = 0.5 + x[0] * x[0] * (8.0 / a - 0.5); s(0,1) = x[0] * x[1] * (8.0 / a - 0.5); s(0,2) = 0.0; s(1,0) = s(0,1); s(1,1) = 0.5 * x[0] * x[0] + 8.0 * x[1] * x[1] / a; s(1,2) = 0.0; s(2,0) = 0.0; s(2,1) = 0.0; s(2,2) = a / 32.0; } } // namespace surf_blf <|endoftext|>
<commit_before>/* * Copyright (C) 2015 deipi.com LLC and contributors. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include "raft.h" #ifdef XAPIAND_CLUSTERING #include "../endpoint.h" #include <assert.h> constexpr const char* const Raft::MessageNames[]; constexpr const char* const Raft::StateNames[]; Raft::Raft(const std::shared_ptr<XapiandManager>& manager_, ev::loop_ref *loop_, int port_, const std::string& group_) : BaseUDP(manager_, loop_, port_, "Raft", XAPIAND_RAFT_PROTOCOL_VERSION, group_), term(0), running(false), election_leader(*loop), heartbeat(*loop), state(State::FOLLOWER), number_servers(0) { election_timeout = random_real(ELECTION_LEADER_MIN, ELECTION_LEADER_MAX); election_leader.set<Raft, &Raft::leader_election_cb>(this); election_leader.set(election_timeout, 0.); L_EV(this, "Start raft's election leader event"); last_activity = ev::now(*loop); heartbeat.set<Raft, &Raft::heartbeat_cb>(this); L_OBJ(this, "CREATED RAFT CONSENSUS"); } Raft::~Raft() { election_leader.stop(); if (state == State::LEADER) { heartbeat.stop(); } L_OBJ(this, "DELETED RAFT CONSENSUS"); } void Raft::reset() { if (state == State::LEADER) { heartbeat.stop(); } state = State::FOLLOWER; L_RAFT(this, "Raft was restarted!"); } void Raft::leader_election_cb(ev::timer&, int) { L_EV_BEGIN(this, "Raft::leader_election_cb:BEGIN"); auto m = manager(); if (m->state == XapiandManager::State::READY) { // calculate when the timeout would happen ev::tstamp remaining_time = last_activity + election_timeout - ev::now(*loop); L_RAFT_PROTO(this, "Raft { Reg: %d; State: %d; Rem_t: %f; Elec_t: %f; Term: %llu; #ser: %zu; Lead: %s }", local_node.region.load(), state, remaining_time, election_timeout, term, number_servers.load(), leader.c_str()); if (remaining_time < 0.0 && state != State::LEADER) { state = State::CANDIDATE; ++term; votes = 0; votedFor.clear(); send_message(Message::REQUEST_VOTE, local_node.serialise() + serialise_string(std::to_string(term))); election_timeout = random_real(ELECTION_LEADER_MIN, ELECTION_LEADER_MAX); } } else { L_RAFT(this, "Waiting manager get ready!! (%s)", XapiandManager::StateNames[static_cast<int>(m->state)]); } // Start the timer again. election_leader.set(election_timeout, 0.); election_leader.start(); L_EV_END(this, "Raft::leader_election_cb:END"); } void Raft::heartbeat_cb(ev::timer&, int) { L_EV_BEGIN(this, "Raft::heartbeat_cb:BEGIN"); send_message(Message::HEARTBEAT_LEADER, local_node.serialise()); L_EV_END(this, "Raft::heartbeat_cb:END"); } void Raft::start_heartbeat() { send_message(Message::LEADER, local_node.serialise() + serialise_string(std::to_string(number_servers.load())) + serialise_string(std::to_string(term))); heartbeat.repeat = random_real(HEARTBEAT_LEADER_MIN, HEARTBEAT_LEADER_MAX); heartbeat.again(); L_RAFT(this, "\tSet heartbeat timeout event %f", heartbeat.repeat); leader = lower_string(local_node.name); } void Raft::register_activity() { L_RAFT(this, "Register activity"); last_activity = ev::now(*loop); } std::string Raft::getDescription() const noexcept { return "UDP:" + std::to_string(port) + " (" + description + " v" + std::to_string(XAPIAND_RAFT_PROTOCOL_MAJOR_VERSION) + "." + std::to_string(XAPIAND_RAFT_PROTOCOL_MINOR_VERSION) + ")"; } #endif <commit_msg>register activity is L_RAFT_PROTO<commit_after>/* * Copyright (C) 2015 deipi.com LLC and contributors. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include "raft.h" #ifdef XAPIAND_CLUSTERING #include "../endpoint.h" #include <assert.h> constexpr const char* const Raft::MessageNames[]; constexpr const char* const Raft::StateNames[]; Raft::Raft(const std::shared_ptr<XapiandManager>& manager_, ev::loop_ref *loop_, int port_, const std::string& group_) : BaseUDP(manager_, loop_, port_, "Raft", XAPIAND_RAFT_PROTOCOL_VERSION, group_), term(0), running(false), election_leader(*loop), heartbeat(*loop), state(State::FOLLOWER), number_servers(0) { election_timeout = random_real(ELECTION_LEADER_MIN, ELECTION_LEADER_MAX); election_leader.set<Raft, &Raft::leader_election_cb>(this); election_leader.set(election_timeout, 0.); L_EV(this, "Start raft's election leader event"); last_activity = ev::now(*loop); heartbeat.set<Raft, &Raft::heartbeat_cb>(this); L_OBJ(this, "CREATED RAFT CONSENSUS"); } Raft::~Raft() { election_leader.stop(); if (state == State::LEADER) { heartbeat.stop(); } L_OBJ(this, "DELETED RAFT CONSENSUS"); } void Raft::reset() { if (state == State::LEADER) { heartbeat.stop(); } state = State::FOLLOWER; L_RAFT(this, "Raft was restarted!"); } void Raft::leader_election_cb(ev::timer&, int) { L_EV_BEGIN(this, "Raft::leader_election_cb:BEGIN"); auto m = manager(); if (m->state == XapiandManager::State::READY) { // calculate when the timeout would happen ev::tstamp remaining_time = last_activity + election_timeout - ev::now(*loop); L_RAFT_PROTO(this, "Raft { Reg: %d; State: %d; Rem_t: %f; Elec_t: %f; Term: %llu; #ser: %zu; Lead: %s }", local_node.region.load(), state, remaining_time, election_timeout, term, number_servers.load(), leader.c_str()); if (remaining_time < 0.0 && state != State::LEADER) { state = State::CANDIDATE; ++term; votes = 0; votedFor.clear(); send_message(Message::REQUEST_VOTE, local_node.serialise() + serialise_string(std::to_string(term))); election_timeout = random_real(ELECTION_LEADER_MIN, ELECTION_LEADER_MAX); } } else { L_RAFT(this, "Waiting manager get ready!! (%s)", XapiandManager::StateNames[static_cast<int>(m->state)]); } // Start the timer again. election_leader.set(election_timeout, 0.); election_leader.start(); L_EV_END(this, "Raft::leader_election_cb:END"); } void Raft::heartbeat_cb(ev::timer&, int) { L_EV_BEGIN(this, "Raft::heartbeat_cb:BEGIN"); send_message(Message::HEARTBEAT_LEADER, local_node.serialise()); L_EV_END(this, "Raft::heartbeat_cb:END"); } void Raft::start_heartbeat() { send_message(Message::LEADER, local_node.serialise() + serialise_string(std::to_string(number_servers.load())) + serialise_string(std::to_string(term))); heartbeat.repeat = random_real(HEARTBEAT_LEADER_MIN, HEARTBEAT_LEADER_MAX); heartbeat.again(); L_RAFT(this, "\tSet heartbeat timeout event %f", heartbeat.repeat); leader = lower_string(local_node.name); } void Raft::register_activity() { L_RAFT_PROTO(this, "Register activity"); last_activity = ev::now(*loop); } std::string Raft::getDescription() const noexcept { return "UDP:" + std::to_string(port) + " (" + description + " v" + std::to_string(XAPIAND_RAFT_PROTOCOL_MAJOR_VERSION) + "." + std::to_string(XAPIAND_RAFT_PROTOCOL_MINOR_VERSION) + ")"; } #endif <|endoftext|>
<commit_before>// Copyright (c) 2002-2010, Boyce Griffith // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of New York University nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // 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 HOLDER 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. // Config files #include <IBTK_prefix_config.h> #include <SAMRAI_config.h> // Headers for basic PETSc functions #include <petscsys.h> // Headers for major SAMRAI objects #include <BergerRigoutsos.h> #include <CartesianGridGeometry.h> #include <GriddingAlgorithm.h> #include <HierarchyDataOpsManager.h> #include <LoadBalancer.h> #include <StandardTagAndInitialize.h> // Headers for application-specific algorithm/data structure objects #include <ibtk/AppInitializer.h> #include <ibtk/HierarchyMathOps.h> #include <ibtk/muParserCartGridFunction.h> #include <ibtk/app_namespaces.h> /******************************************************************************* * For each run, the input filename must be given on the command line. In all * * cases, the command line is: * * * * executable <input file name> * * * *******************************************************************************/ int main( int argc, char *argv[]) { // Initialize PETSc, MPI, and SAMRAI. PetscInitialize(&argc,&argv,PETSC_NULL,PETSC_NULL); SAMRAI_MPI::setCommunicator(PETSC_COMM_WORLD); SAMRAI_MPI::setCallAbortInSerialInsteadOfExit(); SAMRAIManager::startup(); {// cleanup dynamically allocated objects prior to shutdown // Parse command line options, set some standard options from the input // file, and enable file logging. Pointer<AppInitializer> app_initializer = new AppInitializer(argc, argv, "vc_laplace.log"); Pointer<Database> input_db = app_initializer->getInputDatabase(); // Create major algorithm and data objects that comprise the // application. These objects are configured from the input database. Pointer<CartesianGridGeometry<NDIM> > grid_geometry = new CartesianGridGeometry<NDIM>( "CartesianGeometry", app_initializer->getComponentDatabase("CartesianGeometry")); Pointer<PatchHierarchy<NDIM> > patch_hierarchy = new PatchHierarchy<NDIM>( "PatchHierarchy", grid_geometry); Pointer<StandardTagAndInitialize<NDIM> > error_detector = new StandardTagAndInitialize<NDIM>( "StandardTagAndInitialize", NULL, app_initializer->getComponentDatabase("StandardTagAndInitialize")); Pointer<BergerRigoutsos<NDIM> > box_generator = new BergerRigoutsos<NDIM>(); Pointer<LoadBalancer<NDIM> > load_balancer = new LoadBalancer<NDIM>( "LoadBalancer", app_initializer->getComponentDatabase("LoadBalancer")); Pointer<GriddingAlgorithm<NDIM> > gridding_algorithm = new GriddingAlgorithm<NDIM>( "GriddingAlgorithm", app_initializer->getComponentDatabase("GriddingAlgorithm"), error_detector, box_generator, load_balancer); // Create variables and register them with the variable database. VariableDatabase<NDIM>* var_db = VariableDatabase<NDIM>::getDatabase(); Pointer<VariableContext> ctx = var_db->getContext("context"); Pointer<SideVariable<NDIM,double> > u_side_var = new SideVariable<NDIM,double>("u_side"); Pointer<SideVariable<NDIM,double> > f_side_var = new SideVariable<NDIM,double>("f_side"); Pointer<SideVariable<NDIM,double> > e_side_var = new SideVariable<NDIM,double>("e_side"); const int u_side_idx = var_db->registerVariableAndContext(u_side_var, ctx, IntVector<NDIM>(1)); const int f_side_idx = var_db->registerVariableAndContext(f_side_var, ctx, IntVector<NDIM>(1)); const int e_side_idx = var_db->registerVariableAndContext(e_side_var, ctx, IntVector<NDIM>(1)); Pointer<CellVariable<NDIM,double> > u_cell_var = new CellVariable<NDIM,double>("u_cell",NDIM); Pointer<CellVariable<NDIM,double> > f_cell_var = new CellVariable<NDIM,double>("f_cell",NDIM); Pointer<CellVariable<NDIM,double> > e_cell_var = new CellVariable<NDIM,double>("e_cell",NDIM); const int u_cell_idx = var_db->registerVariableAndContext(u_cell_var, ctx, IntVector<NDIM>(0)); const int f_cell_idx = var_db->registerVariableAndContext(f_cell_var, ctx, IntVector<NDIM>(0)); const int e_cell_idx = var_db->registerVariableAndContext(e_cell_var, ctx, IntVector<NDIM>(0)); Pointer<NodeVariable<NDIM,double> > mu_node_var = new NodeVariable<NDIM,double>("mu_node"); const int mu_node_idx = var_db->registerVariableAndContext(mu_node_var, ctx, IntVector<NDIM>(1)); // Register variables for plotting. Pointer<VisItDataWriter<NDIM> > visit_data_writer = app_initializer->getVisItDataWriter(); TBOX_ASSERT(!visit_data_writer.isNull()); visit_data_writer->registerPlotQuantity(u_cell_var->getName(), "VECTOR", u_cell_idx); for (unsigned int d = 0; d < NDIM; ++d) { ostringstream stream; stream << d; visit_data_writer->registerPlotQuantity(u_cell_var->getName()+stream.str(), "SCALAR", u_cell_idx, d); } visit_data_writer->registerPlotQuantity(f_cell_var->getName(), "VECTOR", f_cell_idx); for (unsigned int d = 0; d < NDIM; ++d) { ostringstream stream; stream << d; visit_data_writer->registerPlotQuantity(f_cell_var->getName()+stream.str(), "SCALAR", f_cell_idx, d); } visit_data_writer->registerPlotQuantity(e_cell_var->getName(), "VECTOR", e_cell_idx); for (unsigned int d = 0; d < NDIM; ++d) { ostringstream stream; stream << d; visit_data_writer->registerPlotQuantity(e_cell_var->getName()+stream.str(), "SCALAR", e_cell_idx, d); } visit_data_writer->registerPlotQuantity(mu_node_var->getName(), "SCALAR", mu_node_idx); // Initialize the AMR patch hierarchy. gridding_algorithm->makeCoarsestLevel(patch_hierarchy, 0.0); int tag_buffer = 1; int level_number = 0; bool done = false; while (!done && (gridding_algorithm->levelCanBeRefined(level_number))) { gridding_algorithm->makeFinerLevel(patch_hierarchy, 0.0, 0.0, tag_buffer); done = !patch_hierarchy->finerLevelExists(level_number); ++level_number; } // Set the simulation time to be zero. const double data_time = 0.0; // Allocate data on each level of the patch hierarchy. for (int ln = 0; ln <= patch_hierarchy->getFinestLevelNumber(); ++ln) { Pointer<PatchLevel<NDIM> > level = patch_hierarchy->getPatchLevel(ln); level->allocatePatchData( u_side_idx, data_time); level->allocatePatchData( f_side_idx, data_time); level->allocatePatchData( e_side_idx, data_time); level->allocatePatchData( u_cell_idx, data_time); level->allocatePatchData( f_cell_idx, data_time); level->allocatePatchData( e_cell_idx, data_time); level->allocatePatchData(mu_node_idx, data_time); } // Setup exact solution data. muParserCartGridFunction u_fcn("u" , app_initializer->getComponentDatabase("u") , grid_geometry); muParserCartGridFunction f_fcn("f" , app_initializer->getComponentDatabase("f") , grid_geometry); muParserCartGridFunction mu_fcn("mu", app_initializer->getComponentDatabase("mu"), grid_geometry); u_fcn .setDataOnPatchHierarchy( u_side_idx, u_side_var, patch_hierarchy, data_time); f_fcn .setDataOnPatchHierarchy( e_side_idx, e_side_var, patch_hierarchy, data_time); mu_fcn.setDataOnPatchHierarchy(mu_node_idx, mu_node_var, patch_hierarchy, data_time); // Create an object to communicate ghost cell data. typedef HierarchyGhostCellInterpolation::InterpolationTransactionComponent InterpolationTransactionComponent; InterpolationTransactionComponent u_transaction( u_side_idx, "CUBIC_COARSEN" , "LINEAR"); InterpolationTransactionComponent mu_transaction(mu_node_idx, "CONSTANT_COARSEN", "LINEAR"); vector<InterpolationTransactionComponent> transactions(2); transactions[0] = u_transaction; transactions[1] = mu_transaction; Pointer<HierarchyGhostCellInterpolation> bdry_fill_op = new HierarchyGhostCellInterpolation(); bdry_fill_op->initializeOperatorState(transactions, patch_hierarchy); // Create the math operations object and get the patch data index for // the side-centered weighting factor. HierarchyMathOps hier_math_ops("hier_math_ops", patch_hierarchy); const int dx_side_idx = hier_math_ops.getSideWeightPatchDescriptorIndex(); // Compute (f0,f1) := div mu (grad(u0,u1) + grad(u0,u1)^T). hier_math_ops.vc_laplace(f_side_idx, f_side_var, 1.0, 0.0, mu_node_idx, mu_node_var, u_side_idx, u_side_var, bdry_fill_op, data_time); // Compute error and print error norms. Pointer<HierarchyDataOpsReal<NDIM,double> > hier_side_data_ops = HierarchyDataOpsManager<NDIM>::getManager()->getOperationsDouble( u_side_var, patch_hierarchy, true); hier_side_data_ops->subtract(e_side_idx, e_side_idx, f_side_idx); // computes e := e - f pout << "|e|_oo = " << hier_side_data_ops->maxNorm(e_side_idx, dx_side_idx) << "\n"; pout << "|e|_2 = " << hier_side_data_ops-> L2Norm(e_side_idx, dx_side_idx) << "\n"; pout << "|e|_1 = " << hier_side_data_ops-> L1Norm(e_side_idx, dx_side_idx) << "\n"; // Interpolate the side-centered data to cell centers for output. static const bool synch_cf_interface = true; hier_math_ops.interp(u_cell_idx, u_cell_var, u_side_idx, u_side_var, NULL, data_time, synch_cf_interface); hier_math_ops.interp(f_cell_idx, f_cell_var, f_side_idx, f_side_var, NULL, data_time, synch_cf_interface); hier_math_ops.interp(e_cell_idx, e_cell_var, e_side_idx, e_side_var, NULL, data_time, synch_cf_interface); // Output data for plotting. visit_data_writer->writePlotData(patch_hierarchy, 0, data_time); }// cleanup dynamically allocated objects prior to shutdown SAMRAIManager::shutdown(); PetscFinalize(); return 0; }// main <commit_msg>branch boyceg: updating VCLaplace example main.C<commit_after>// Copyright (c) 2002-2010, Boyce Griffith // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of New York University nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // 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 HOLDER 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. // Config files #include <IBTK_prefix_config.h> #include <SAMRAI_config.h> // Headers for basic PETSc functions #include <petscsys.h> // Headers for major SAMRAI objects #include <BergerRigoutsos.h> #include <CartesianGridGeometry.h> #include <GriddingAlgorithm.h> #include <HierarchyDataOpsManager.h> #include <LoadBalancer.h> #include <StandardTagAndInitialize.h> // Headers for application-specific algorithm/data structure objects #include <ibtk/AppInitializer.h> #include <ibtk/HierarchyMathOps.h> #include <ibtk/muParserCartGridFunction.h> #include <ibtk/app_namespaces.h> /******************************************************************************* * For each run, the input filename must be given on the command line. In all * * cases, the command line is: * * * * executable <input file name> * * * *******************************************************************************/ int main( int argc, char *argv[]) { // Initialize PETSc, MPI, and SAMRAI. PetscInitialize(&argc,&argv,PETSC_NULL,PETSC_NULL); SAMRAI_MPI::setCommunicator(PETSC_COMM_WORLD); SAMRAI_MPI::setCallAbortInSerialInsteadOfExit(); SAMRAIManager::startup(); {// cleanup dynamically allocated objects prior to shutdown // Parse command line options, set some standard options from the input // file, and enable file logging. Pointer<AppInitializer> app_initializer = new AppInitializer(argc, argv, "vc_laplace.log"); Pointer<Database> input_db = app_initializer->getInputDatabase(); // Create major algorithm and data objects that comprise the // application. These objects are configured from the input database. Pointer<CartesianGridGeometry<NDIM> > grid_geometry = new CartesianGridGeometry<NDIM>("CartesianGeometry", app_initializer->getComponentDatabase("CartesianGeometry")); Pointer<PatchHierarchy<NDIM> > patch_hierarchy = new PatchHierarchy<NDIM>("PatchHierarchy", grid_geometry); Pointer<StandardTagAndInitialize<NDIM> > error_detector = new StandardTagAndInitialize<NDIM>("StandardTagAndInitialize", NULL, app_initializer->getComponentDatabase("StandardTagAndInitialize")); Pointer<BergerRigoutsos<NDIM> > box_generator = new BergerRigoutsos<NDIM>(); Pointer<LoadBalancer<NDIM> > load_balancer = new LoadBalancer<NDIM>("LoadBalancer", app_initializer->getComponentDatabase("LoadBalancer")); Pointer<GriddingAlgorithm<NDIM> > gridding_algorithm = new GriddingAlgorithm<NDIM>("GriddingAlgorithm", app_initializer->getComponentDatabase("GriddingAlgorithm"), error_detector, box_generator, load_balancer); // Create variables and register them with the variable database. VariableDatabase<NDIM>* var_db = VariableDatabase<NDIM>::getDatabase(); Pointer<VariableContext> ctx = var_db->getContext("context"); Pointer<SideVariable<NDIM,double> > u_side_var = new SideVariable<NDIM,double>("u_side"); Pointer<SideVariable<NDIM,double> > f_side_var = new SideVariable<NDIM,double>("f_side"); Pointer<SideVariable<NDIM,double> > e_side_var = new SideVariable<NDIM,double>("e_side"); const int u_side_idx = var_db->registerVariableAndContext(u_side_var, ctx, IntVector<NDIM>(1)); const int f_side_idx = var_db->registerVariableAndContext(f_side_var, ctx, IntVector<NDIM>(1)); const int e_side_idx = var_db->registerVariableAndContext(e_side_var, ctx, IntVector<NDIM>(1)); Pointer<CellVariable<NDIM,double> > u_cell_var = new CellVariable<NDIM,double>("u_cell",NDIM); Pointer<CellVariable<NDIM,double> > f_cell_var = new CellVariable<NDIM,double>("f_cell",NDIM); Pointer<CellVariable<NDIM,double> > e_cell_var = new CellVariable<NDIM,double>("e_cell",NDIM); const int u_cell_idx = var_db->registerVariableAndContext(u_cell_var, ctx, IntVector<NDIM>(0)); const int f_cell_idx = var_db->registerVariableAndContext(f_cell_var, ctx, IntVector<NDIM>(0)); const int e_cell_idx = var_db->registerVariableAndContext(e_cell_var, ctx, IntVector<NDIM>(0)); Pointer<NodeVariable<NDIM,double> > mu_node_var = new NodeVariable<NDIM,double>("mu_node"); const int mu_node_idx = var_db->registerVariableAndContext(mu_node_var, ctx, IntVector<NDIM>(1)); // Register variables for plotting. Pointer<VisItDataWriter<NDIM> > visit_data_writer = app_initializer->getVisItDataWriter(); TBOX_ASSERT(!visit_data_writer.isNull()); visit_data_writer->registerPlotQuantity(u_cell_var->getName(), "VECTOR", u_cell_idx); for (unsigned int d = 0; d < NDIM; ++d) { ostringstream stream; stream << d; visit_data_writer->registerPlotQuantity(u_cell_var->getName()+stream.str(), "SCALAR", u_cell_idx, d); } visit_data_writer->registerPlotQuantity(f_cell_var->getName(), "VECTOR", f_cell_idx); for (unsigned int d = 0; d < NDIM; ++d) { ostringstream stream; stream << d; visit_data_writer->registerPlotQuantity(f_cell_var->getName()+stream.str(), "SCALAR", f_cell_idx, d); } visit_data_writer->registerPlotQuantity(e_cell_var->getName(), "VECTOR", e_cell_idx); for (unsigned int d = 0; d < NDIM; ++d) { ostringstream stream; stream << d; visit_data_writer->registerPlotQuantity(e_cell_var->getName()+stream.str(), "SCALAR", e_cell_idx, d); } visit_data_writer->registerPlotQuantity(mu_node_var->getName(), "SCALAR", mu_node_idx); // Initialize the AMR patch hierarchy. gridding_algorithm->makeCoarsestLevel(patch_hierarchy, 0.0); int tag_buffer = 1; int level_number = 0; bool done = false; while (!done && (gridding_algorithm->levelCanBeRefined(level_number))) { gridding_algorithm->makeFinerLevel(patch_hierarchy, 0.0, 0.0, tag_buffer); done = !patch_hierarchy->finerLevelExists(level_number); ++level_number; } // Set the simulation time to be zero. const double data_time = 0.0; // Allocate data on each level of the patch hierarchy. for (int ln = 0; ln <= patch_hierarchy->getFinestLevelNumber(); ++ln) { Pointer<PatchLevel<NDIM> > level = patch_hierarchy->getPatchLevel(ln); level->allocatePatchData( u_side_idx, data_time); level->allocatePatchData( f_side_idx, data_time); level->allocatePatchData( e_side_idx, data_time); level->allocatePatchData( u_cell_idx, data_time); level->allocatePatchData( f_cell_idx, data_time); level->allocatePatchData( e_cell_idx, data_time); level->allocatePatchData(mu_node_idx, data_time); } // Setup exact solution data. muParserCartGridFunction u_fcn("u" , app_initializer->getComponentDatabase("u") , grid_geometry); muParserCartGridFunction f_fcn("f" , app_initializer->getComponentDatabase("f") , grid_geometry); muParserCartGridFunction mu_fcn("mu", app_initializer->getComponentDatabase("mu"), grid_geometry); u_fcn .setDataOnPatchHierarchy( u_side_idx, u_side_var, patch_hierarchy, data_time); f_fcn .setDataOnPatchHierarchy( e_side_idx, e_side_var, patch_hierarchy, data_time); mu_fcn.setDataOnPatchHierarchy(mu_node_idx, mu_node_var, patch_hierarchy, data_time); // Create an object to communicate ghost cell data. typedef HierarchyGhostCellInterpolation::InterpolationTransactionComponent InterpolationTransactionComponent; InterpolationTransactionComponent u_transaction( u_side_idx, "CUBIC_COARSEN" , "LINEAR"); InterpolationTransactionComponent mu_transaction(mu_node_idx, "CONSTANT_COARSEN", "LINEAR"); vector<InterpolationTransactionComponent> transactions(2); transactions[0] = u_transaction; transactions[1] = mu_transaction; Pointer<HierarchyGhostCellInterpolation> bdry_fill_op = new HierarchyGhostCellInterpolation(); bdry_fill_op->initializeOperatorState(transactions, patch_hierarchy); // Create the math operations object and get the patch data index for // the side-centered weighting factor. HierarchyMathOps hier_math_ops("hier_math_ops", patch_hierarchy); const int dx_side_idx = hier_math_ops.getSideWeightPatchDescriptorIndex(); // Compute (f0,f1) := div mu (grad(u0,u1) + grad(u0,u1)^T). hier_math_ops.vc_laplace(f_side_idx, f_side_var, 1.0, 0.0, mu_node_idx, mu_node_var, u_side_idx, u_side_var, bdry_fill_op, data_time); // Compute error and print error norms. Pointer<HierarchyDataOpsReal<NDIM,double> > hier_side_data_ops = HierarchyDataOpsManager<NDIM>::getManager()->getOperationsDouble(u_side_var, patch_hierarchy, true); hier_side_data_ops->subtract(e_side_idx, e_side_idx, f_side_idx); // computes e := e - f pout << "|e|_oo = " << hier_side_data_ops->maxNorm(e_side_idx, dx_side_idx) << "\n"; pout << "|e|_2 = " << hier_side_data_ops-> L2Norm(e_side_idx, dx_side_idx) << "\n"; pout << "|e|_1 = " << hier_side_data_ops-> L1Norm(e_side_idx, dx_side_idx) << "\n"; // Interpolate the side-centered data to cell centers for output. static const bool synch_cf_interface = true; hier_math_ops.interp(u_cell_idx, u_cell_var, u_side_idx, u_side_var, NULL, data_time, synch_cf_interface); hier_math_ops.interp(f_cell_idx, f_cell_var, f_side_idx, f_side_var, NULL, data_time, synch_cf_interface); hier_math_ops.interp(e_cell_idx, e_cell_var, e_side_idx, e_side_var, NULL, data_time, synch_cf_interface); // Output data for plotting. visit_data_writer->writePlotData(patch_hierarchy, 0, data_time); }// cleanup dynamically allocated objects prior to shutdown SAMRAIManager::shutdown(); PetscFinalize(); return 0; }// main <|endoftext|>
<commit_before>//===-- IncludeFixer.cpp - Include inserter based on sema callbacks -------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "IncludeFixer.h" #include "clang/Format/Format.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Lex/HeaderSearch.h" #include "clang/Lex/Preprocessor.h" #include "clang/Parse/ParseAST.h" #include "clang/Sema/ExternalSemaSource.h" #include "clang/Sema/Sema.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" #define DEBUG_TYPE "include-fixer" using namespace clang; namespace clang { namespace include_fixer { namespace { class Action; /// Manages the parse, gathers include suggestions. class Action : public clang::ASTFrontendAction, public clang::ExternalSemaSource { public: explicit Action(SymbolIndexManager &SymbolIndexMgr, bool MinimizeIncludePaths) : SymbolIndexMgr(SymbolIndexMgr), MinimizeIncludePaths(MinimizeIncludePaths) {} std::unique_ptr<clang::ASTConsumer> CreateASTConsumer(clang::CompilerInstance &Compiler, StringRef InFile) override { Filename = InFile; return llvm::make_unique<clang::ASTConsumer>(); } void ExecuteAction() override { clang::CompilerInstance *Compiler = &getCompilerInstance(); assert(!Compiler->hasSema() && "CI already has Sema"); // Set up our hooks into sema and parse the AST. if (hasCodeCompletionSupport() && !Compiler->getFrontendOpts().CodeCompletionAt.FileName.empty()) Compiler->createCodeCompletionConsumer(); clang::CodeCompleteConsumer *CompletionConsumer = nullptr; if (Compiler->hasCodeCompletionConsumer()) CompletionConsumer = &Compiler->getCodeCompletionConsumer(); Compiler->createSema(getTranslationUnitKind(), CompletionConsumer); Compiler->getSema().addExternalSource(this); clang::ParseAST(Compiler->getSema(), Compiler->getFrontendOpts().ShowStats, Compiler->getFrontendOpts().SkipFunctionBodies); } /// Callback for incomplete types. If we encounter a forward declaration we /// have the fully qualified name ready. Just query that. bool MaybeDiagnoseMissingCompleteType(clang::SourceLocation Loc, clang::QualType T) override { // Ignore spurious callbacks from SFINAE contexts. if (getCompilerInstance().getSema().isSFINAEContext()) return false; clang::ASTContext &context = getCompilerInstance().getASTContext(); query(T.getUnqualifiedType().getAsString(context.getPrintingPolicy()), Loc); return false; } /// Callback for unknown identifiers. Try to piece together as much /// qualification as we can get and do a query. clang::TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, int LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, DeclContext *MemberContext, bool EnteringContext, const ObjCObjectPointerType *OPT) override { // Ignore spurious callbacks from SFINAE contexts. if (getCompilerInstance().getSema().isSFINAEContext()) return clang::TypoCorrection(); std::string TypoScopeString; if (S) { // FIXME: Currently we only use namespace contexts. Use other context // types for query. for (const auto *Context = S->getEntity(); Context; Context = Context->getParent()) { if (const auto *ND = dyn_cast<NamespaceDecl>(Context)) { if (!ND->getName().empty()) TypoScopeString = ND->getNameAsString() + "::" + TypoScopeString; } } } auto ExtendNestedNameSpecifier = [this](CharSourceRange Range) { StringRef Source = Lexer::getSourceText(Range, getCompilerInstance().getSourceManager(), getCompilerInstance().getLangOpts()); // Skip forward until we find a character that's neither identifier nor // colon. This is a bit of a hack around the fact that we will only get a // single callback for a long nested name if a part of the beginning is // unknown. For example: // // llvm::sys::path::parent_path(...) // ^~~~ ^~~ // known // ^~~~ // unknown, last callback // ^~~~~~~~~~~ // no callback // // With the extension we get the full nested name specifier including // parent_path. // FIXME: Don't rely on source text. const char *End = Source.end(); while (isIdentifierBody(*End) || *End == ':') ++End; return std::string(Source.begin(), End); }; /// If we have a scope specification, use that to get more precise results. std::string QueryString; if (SS && SS->getRange().isValid()) { auto Range = CharSourceRange::getTokenRange(SS->getRange().getBegin(), Typo.getLoc()); QueryString = ExtendNestedNameSpecifier(Range); } else if (Typo.getName().isIdentifier() && !Typo.getLoc().isMacroID()) { auto Range = CharSourceRange::getTokenRange(Typo.getBeginLoc(), Typo.getEndLoc()); QueryString = ExtendNestedNameSpecifier(Range); } else { QueryString = Typo.getAsString(); } // Follow C++ Lookup rules. Firstly, lookup the identifier with scoped // namespace contexts. If fails, falls back to identifier. // For example: // // namespace a { // b::foo f; // } // // 1. lookup a::b::foo. // 2. lookup b::foo. if (!query(TypoScopeString + QueryString, Typo.getLoc())) query(QueryString, Typo.getLoc()); // FIXME: We should just return the name we got as input here and prevent // clang from trying to correct the typo by itself. That may change the // identifier to something that's not wanted by the user. return clang::TypoCorrection(); } StringRef filename() const { return Filename; } /// Get the minimal include for a given path. std::string minimizeInclude(StringRef Include, const clang::SourceManager &SourceManager, clang::HeaderSearch &HeaderSearch) { if (!MinimizeIncludePaths) return Include; // Get the FileEntry for the include. StringRef StrippedInclude = Include.trim("\"<>"); const FileEntry *Entry = SourceManager.getFileManager().getFile(StrippedInclude); // If the file doesn't exist return the path from the database. // FIXME: This should never happen. if (!Entry) return Include; bool IsSystem; std::string Suggestion = HeaderSearch.suggestPathToFileForDiagnostics(Entry, &IsSystem); return IsSystem ? '<' + Suggestion + '>' : '"' + Suggestion + '"'; } /// Get the include fixer context for the queried symbol. IncludeFixerContext getIncludeFixerContext(const clang::SourceManager &SourceManager, clang::HeaderSearch &HeaderSearch) { IncludeFixerContext FixerContext; if (SymbolQueryResults.empty()) return FixerContext; FixerContext.SymbolIdentifer = QuerySymbol; for (const auto &Header : SymbolQueryResults) FixerContext.Headers.push_back( minimizeInclude(Header, SourceManager, HeaderSearch)); return FixerContext; } private: /// Query the database for a given identifier. bool query(StringRef Query, SourceLocation Loc) { assert(!Query.empty() && "Empty query!"); // Skip other identifers once we have discovered an identfier successfully. if (!SymbolQueryResults.empty()) return false; DEBUG(llvm::dbgs() << "Looking up '" << Query << "' at "); DEBUG(Loc.print(llvm::dbgs(), getCompilerInstance().getSourceManager())); DEBUG(llvm::dbgs() << " ..."); QuerySymbol = Query.str(); SymbolQueryResults = SymbolIndexMgr.search(Query); DEBUG(llvm::dbgs() << SymbolQueryResults.size() << " replies\n"); return !SymbolQueryResults.empty(); } /// The client to use to find cross-references. SymbolIndexManager &SymbolIndexMgr; /// The absolute path to the file being processed. std::string Filename; /// The symbol being queried. std::string QuerySymbol; /// The query results of an identifier. We only include the first discovered /// identifier to avoid getting caught in results from error recovery. std::vector<std::string> SymbolQueryResults; /// Whether we should use the smallest possible include path. bool MinimizeIncludePaths = true; }; } // namespace IncludeFixerActionFactory::IncludeFixerActionFactory( SymbolIndexManager &SymbolIndexMgr, IncludeFixerContext &Context, StringRef StyleName, bool MinimizeIncludePaths) : SymbolIndexMgr(SymbolIndexMgr), Context(Context), MinimizeIncludePaths(MinimizeIncludePaths) {} IncludeFixerActionFactory::~IncludeFixerActionFactory() = default; bool IncludeFixerActionFactory::runInvocation( clang::CompilerInvocation *Invocation, clang::FileManager *Files, std::shared_ptr<clang::PCHContainerOperations> PCHContainerOps, clang::DiagnosticConsumer *Diagnostics) { assert(Invocation->getFrontendOpts().Inputs.size() == 1); // Set up Clang. clang::CompilerInstance Compiler(PCHContainerOps); Compiler.setInvocation(Invocation); Compiler.setFileManager(Files); // Create the compiler's actual diagnostics engine. We want to drop all // diagnostics here. Compiler.createDiagnostics(new clang::IgnoringDiagConsumer, /*ShouldOwnClient=*/true); Compiler.createSourceManager(*Files); // We abort on fatal errors so don't let a large number of errors become // fatal. A missing #include can cause thousands of errors. Compiler.getDiagnostics().setErrorLimit(0); // Run the parser, gather missing includes. auto ScopedToolAction = llvm::make_unique<Action>(SymbolIndexMgr, MinimizeIncludePaths); Compiler.ExecuteAction(*ScopedToolAction); Context = ScopedToolAction->getIncludeFixerContext( Compiler.getSourceManager(), Compiler.getPreprocessor().getHeaderSearchInfo()); // Technically this should only return true if we're sure that we have a // parseable file. We don't know that though. Only inform users of fatal // errors. return !Compiler.getDiagnostics().hasFatalErrorOccurred(); } tooling::Replacements createInsertHeaderReplacements(StringRef Code, StringRef FilePath, StringRef Header, const clang::format::FormatStyle &Style) { if (Header.empty()) return tooling::Replacements(); std::string IncludeName = "#include " + Header.str() + "\n"; // Create replacements for the new header. clang::tooling::Replacements Insertions = { tooling::Replacement(FilePath, UINT_MAX, 0, IncludeName)}; return formatReplacements( Code, cleanupAroundReplacements(Code, Insertions, Style), Style); } } // namespace include_fixer } // namespace clang <commit_msg>[include-fixer] removed unused forward declaration.<commit_after>//===-- IncludeFixer.cpp - Include inserter based on sema callbacks -------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "IncludeFixer.h" #include "clang/Format/Format.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Lex/HeaderSearch.h" #include "clang/Lex/Preprocessor.h" #include "clang/Parse/ParseAST.h" #include "clang/Sema/ExternalSemaSource.h" #include "clang/Sema/Sema.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" #define DEBUG_TYPE "include-fixer" using namespace clang; namespace clang { namespace include_fixer { namespace { /// Manages the parse, gathers include suggestions. class Action : public clang::ASTFrontendAction, public clang::ExternalSemaSource { public: explicit Action(SymbolIndexManager &SymbolIndexMgr, bool MinimizeIncludePaths) : SymbolIndexMgr(SymbolIndexMgr), MinimizeIncludePaths(MinimizeIncludePaths) {} std::unique_ptr<clang::ASTConsumer> CreateASTConsumer(clang::CompilerInstance &Compiler, StringRef InFile) override { Filename = InFile; return llvm::make_unique<clang::ASTConsumer>(); } void ExecuteAction() override { clang::CompilerInstance *Compiler = &getCompilerInstance(); assert(!Compiler->hasSema() && "CI already has Sema"); // Set up our hooks into sema and parse the AST. if (hasCodeCompletionSupport() && !Compiler->getFrontendOpts().CodeCompletionAt.FileName.empty()) Compiler->createCodeCompletionConsumer(); clang::CodeCompleteConsumer *CompletionConsumer = nullptr; if (Compiler->hasCodeCompletionConsumer()) CompletionConsumer = &Compiler->getCodeCompletionConsumer(); Compiler->createSema(getTranslationUnitKind(), CompletionConsumer); Compiler->getSema().addExternalSource(this); clang::ParseAST(Compiler->getSema(), Compiler->getFrontendOpts().ShowStats, Compiler->getFrontendOpts().SkipFunctionBodies); } /// Callback for incomplete types. If we encounter a forward declaration we /// have the fully qualified name ready. Just query that. bool MaybeDiagnoseMissingCompleteType(clang::SourceLocation Loc, clang::QualType T) override { // Ignore spurious callbacks from SFINAE contexts. if (getCompilerInstance().getSema().isSFINAEContext()) return false; clang::ASTContext &context = getCompilerInstance().getASTContext(); query(T.getUnqualifiedType().getAsString(context.getPrintingPolicy()), Loc); return false; } /// Callback for unknown identifiers. Try to piece together as much /// qualification as we can get and do a query. clang::TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, int LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, DeclContext *MemberContext, bool EnteringContext, const ObjCObjectPointerType *OPT) override { // Ignore spurious callbacks from SFINAE contexts. if (getCompilerInstance().getSema().isSFINAEContext()) return clang::TypoCorrection(); std::string TypoScopeString; if (S) { // FIXME: Currently we only use namespace contexts. Use other context // types for query. for (const auto *Context = S->getEntity(); Context; Context = Context->getParent()) { if (const auto *ND = dyn_cast<NamespaceDecl>(Context)) { if (!ND->getName().empty()) TypoScopeString = ND->getNameAsString() + "::" + TypoScopeString; } } } auto ExtendNestedNameSpecifier = [this](CharSourceRange Range) { StringRef Source = Lexer::getSourceText(Range, getCompilerInstance().getSourceManager(), getCompilerInstance().getLangOpts()); // Skip forward until we find a character that's neither identifier nor // colon. This is a bit of a hack around the fact that we will only get a // single callback for a long nested name if a part of the beginning is // unknown. For example: // // llvm::sys::path::parent_path(...) // ^~~~ ^~~ // known // ^~~~ // unknown, last callback // ^~~~~~~~~~~ // no callback // // With the extension we get the full nested name specifier including // parent_path. // FIXME: Don't rely on source text. const char *End = Source.end(); while (isIdentifierBody(*End) || *End == ':') ++End; return std::string(Source.begin(), End); }; /// If we have a scope specification, use that to get more precise results. std::string QueryString; if (SS && SS->getRange().isValid()) { auto Range = CharSourceRange::getTokenRange(SS->getRange().getBegin(), Typo.getLoc()); QueryString = ExtendNestedNameSpecifier(Range); } else if (Typo.getName().isIdentifier() && !Typo.getLoc().isMacroID()) { auto Range = CharSourceRange::getTokenRange(Typo.getBeginLoc(), Typo.getEndLoc()); QueryString = ExtendNestedNameSpecifier(Range); } else { QueryString = Typo.getAsString(); } // Follow C++ Lookup rules. Firstly, lookup the identifier with scoped // namespace contexts. If fails, falls back to identifier. // For example: // // namespace a { // b::foo f; // } // // 1. lookup a::b::foo. // 2. lookup b::foo. if (!query(TypoScopeString + QueryString, Typo.getLoc())) query(QueryString, Typo.getLoc()); // FIXME: We should just return the name we got as input here and prevent // clang from trying to correct the typo by itself. That may change the // identifier to something that's not wanted by the user. return clang::TypoCorrection(); } StringRef filename() const { return Filename; } /// Get the minimal include for a given path. std::string minimizeInclude(StringRef Include, const clang::SourceManager &SourceManager, clang::HeaderSearch &HeaderSearch) { if (!MinimizeIncludePaths) return Include; // Get the FileEntry for the include. StringRef StrippedInclude = Include.trim("\"<>"); const FileEntry *Entry = SourceManager.getFileManager().getFile(StrippedInclude); // If the file doesn't exist return the path from the database. // FIXME: This should never happen. if (!Entry) return Include; bool IsSystem; std::string Suggestion = HeaderSearch.suggestPathToFileForDiagnostics(Entry, &IsSystem); return IsSystem ? '<' + Suggestion + '>' : '"' + Suggestion + '"'; } /// Get the include fixer context for the queried symbol. IncludeFixerContext getIncludeFixerContext(const clang::SourceManager &SourceManager, clang::HeaderSearch &HeaderSearch) { IncludeFixerContext FixerContext; if (SymbolQueryResults.empty()) return FixerContext; FixerContext.SymbolIdentifer = QuerySymbol; for (const auto &Header : SymbolQueryResults) FixerContext.Headers.push_back( minimizeInclude(Header, SourceManager, HeaderSearch)); return FixerContext; } private: /// Query the database for a given identifier. bool query(StringRef Query, SourceLocation Loc) { assert(!Query.empty() && "Empty query!"); // Skip other identifers once we have discovered an identfier successfully. if (!SymbolQueryResults.empty()) return false; DEBUG(llvm::dbgs() << "Looking up '" << Query << "' at "); DEBUG(Loc.print(llvm::dbgs(), getCompilerInstance().getSourceManager())); DEBUG(llvm::dbgs() << " ..."); QuerySymbol = Query.str(); SymbolQueryResults = SymbolIndexMgr.search(Query); DEBUG(llvm::dbgs() << SymbolQueryResults.size() << " replies\n"); return !SymbolQueryResults.empty(); } /// The client to use to find cross-references. SymbolIndexManager &SymbolIndexMgr; /// The absolute path to the file being processed. std::string Filename; /// The symbol being queried. std::string QuerySymbol; /// The query results of an identifier. We only include the first discovered /// identifier to avoid getting caught in results from error recovery. std::vector<std::string> SymbolQueryResults; /// Whether we should use the smallest possible include path. bool MinimizeIncludePaths = true; }; } // namespace IncludeFixerActionFactory::IncludeFixerActionFactory( SymbolIndexManager &SymbolIndexMgr, IncludeFixerContext &Context, StringRef StyleName, bool MinimizeIncludePaths) : SymbolIndexMgr(SymbolIndexMgr), Context(Context), MinimizeIncludePaths(MinimizeIncludePaths) {} IncludeFixerActionFactory::~IncludeFixerActionFactory() = default; bool IncludeFixerActionFactory::runInvocation( clang::CompilerInvocation *Invocation, clang::FileManager *Files, std::shared_ptr<clang::PCHContainerOperations> PCHContainerOps, clang::DiagnosticConsumer *Diagnostics) { assert(Invocation->getFrontendOpts().Inputs.size() == 1); // Set up Clang. clang::CompilerInstance Compiler(PCHContainerOps); Compiler.setInvocation(Invocation); Compiler.setFileManager(Files); // Create the compiler's actual diagnostics engine. We want to drop all // diagnostics here. Compiler.createDiagnostics(new clang::IgnoringDiagConsumer, /*ShouldOwnClient=*/true); Compiler.createSourceManager(*Files); // We abort on fatal errors so don't let a large number of errors become // fatal. A missing #include can cause thousands of errors. Compiler.getDiagnostics().setErrorLimit(0); // Run the parser, gather missing includes. auto ScopedToolAction = llvm::make_unique<Action>(SymbolIndexMgr, MinimizeIncludePaths); Compiler.ExecuteAction(*ScopedToolAction); Context = ScopedToolAction->getIncludeFixerContext( Compiler.getSourceManager(), Compiler.getPreprocessor().getHeaderSearchInfo()); // Technically this should only return true if we're sure that we have a // parseable file. We don't know that though. Only inform users of fatal // errors. return !Compiler.getDiagnostics().hasFatalErrorOccurred(); } tooling::Replacements createInsertHeaderReplacements(StringRef Code, StringRef FilePath, StringRef Header, const clang::format::FormatStyle &Style) { if (Header.empty()) return tooling::Replacements(); std::string IncludeName = "#include " + Header.str() + "\n"; // Create replacements for the new header. clang::tooling::Replacements Insertions = { tooling::Replacement(FilePath, UINT_MAX, 0, IncludeName)}; return formatReplacements( Code, cleanupAroundReplacements(Code, Insertions, Style), Style); } } // namespace include_fixer } // namespace clang <|endoftext|>
<commit_before>/* Copyright 2019 Benjamin Worpitz * * This file is part of Alpaka. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #ifdef ALPAKA_ACC_ANY_BT_OMP5_ENABLED #if _OPENMP < 201307 #error If ALPAKA_ACC_ANY_BT_OMP5_ENABLED is set, the compiler has to support OpenMP 4.0 or higher! #endif #include <alpaka/dev/Traits.hpp> #include <alpaka/mem/buf/Traits.hpp> #include <alpaka/pltf/Traits.hpp> #include <alpaka/wait/Traits.hpp> #include <alpaka/queue/Traits.hpp> #include <alpaka/queue/Properties.hpp> #include <alpaka/core/Omp5.hpp> #include <alpaka/queue/cpu/IGenericThreadsQueue.hpp> #include <alpaka/queue/QueueGenericThreadsNonBlocking.hpp> #include <alpaka/queue/QueueGenericThreadsBlocking.hpp> namespace alpaka { namespace dev { class DevOmp5; } namespace pltf { namespace traits { template< typename TPltf, typename TSfinae> struct GetDevByIdx; } class PltfOmp5; } namespace dev { namespace omp5 { namespace detail { //############################################################################# //! The Omp5 device implementation. class DevOmp5Impl { public: //----------------------------------------------------------------------------- DevOmp5Impl(int iDevice) : m_iDevice(iDevice) {} //----------------------------------------------------------------------------- DevOmp5Impl(DevOmp5Impl const &) = delete; //----------------------------------------------------------------------------- DevOmp5Impl(DevOmp5Impl &&) = delete; //----------------------------------------------------------------------------- auto operator=(DevOmp5Impl const &) -> DevOmp5Impl & = delete; //----------------------------------------------------------------------------- auto operator=(DevOmp5Impl &&) -> DevOmp5Impl & = delete; //----------------------------------------------------------------------------- ~DevOmp5Impl() = default; //----------------------------------------------------------------------------- ALPAKA_FN_HOST auto getAllExistingQueues() const -> std::vector<std::shared_ptr<queue::IGenericThreadsQueue<DevOmp5>>> { std::vector<std::shared_ptr<queue::IGenericThreadsQueue<DevOmp5>>> vspQueues; std::lock_guard<std::mutex> lk(m_Mutex); vspQueues.reserve(m_queues.size()); for(auto it = m_queues.begin(); it != m_queues.end();) { auto spQueue(it->lock()); if(spQueue) { vspQueues.emplace_back(std::move(spQueue)); ++it; } else { it = m_queues.erase(it); } } return vspQueues; } //----------------------------------------------------------------------------- //! Registers the given queue on this device. //! NOTE: Every queue has to be registered for correct functionality of device wait operations! ALPAKA_FN_HOST auto registerQueue(std::shared_ptr<queue::IGenericThreadsQueue<DevOmp5>> spQueue) -> void { std::lock_guard<std::mutex> lk(m_Mutex); // Register this queue on the device. m_queues.push_back(spQueue); } int iDevice() const {return m_iDevice;} private: std::mutex mutable m_Mutex; std::vector<std::weak_ptr<queue::IGenericThreadsQueue<DevOmp5>>> mutable m_queues; int m_iDevice = 0; }; } } //############################################################################# //! The Omp5 device handle. class DevOmp5 : public concepts::Implements<wait::ConceptCurrentThreadWaitFor, DevOmp5> { friend struct pltf::traits::GetDevByIdx<pltf::PltfOmp5>; protected: //----------------------------------------------------------------------------- DevOmp5(int iDevice) : m_spDevOmp5Impl(std::make_shared<omp5::detail::DevOmp5Impl>(iDevice)) {} public: //----------------------------------------------------------------------------- DevOmp5(DevOmp5 const &) = default; //----------------------------------------------------------------------------- DevOmp5(DevOmp5 &&) = default; //----------------------------------------------------------------------------- auto operator=(DevOmp5 const &) -> DevOmp5 & = default; //----------------------------------------------------------------------------- auto operator=(DevOmp5 &&) -> DevOmp5 & = default; //----------------------------------------------------------------------------- ALPAKA_FN_HOST auto operator==(DevOmp5 const & rhs) const -> bool { return m_spDevOmp5Impl->iDevice() == rhs.m_spDevOmp5Impl->iDevice(); } //----------------------------------------------------------------------------- ALPAKA_FN_HOST auto operator!=(DevOmp5 const & rhs) const -> bool { return !((*this) == rhs); } //----------------------------------------------------------------------------- ~DevOmp5() = default; int iDevice() const {return m_spDevOmp5Impl->iDevice();} ALPAKA_FN_HOST auto getAllQueues() const -> std::vector<std::shared_ptr<queue::IGenericThreadsQueue<DevOmp5>>> { return m_spDevOmp5Impl->getAllExistingQueues(); } //----------------------------------------------------------------------------- //! Registers the given queue on this device. //! NOTE: Every queue has to be registered for correct functionality of device wait operations! ALPAKA_FN_HOST auto registerQueue(std::shared_ptr<queue::IGenericThreadsQueue<DevOmp5>> spQueue) const -> void { m_spDevOmp5Impl->registerQueue(spQueue); } public: std::shared_ptr<omp5::detail::DevOmp5Impl> m_spDevOmp5Impl; }; } namespace dev { namespace traits { //############################################################################# //! The CUDA RT device name get trait specialization. template<> struct GetName< dev::DevOmp5> { //----------------------------------------------------------------------------- ALPAKA_FN_HOST static auto getName( dev::DevOmp5 const &) -> std::string { return std::string("OMP5 target"); } }; //############################################################################# //! The CUDA RT device available memory get trait specialization. template<> struct GetMemBytes< dev::DevOmp5> { //----------------------------------------------------------------------------- ALPAKA_FN_HOST static auto getMemBytes( dev::DevOmp5 const & dev) -> std::size_t { alpaka::ignore_unused(dev); //! \TODO // std::size_t freeInternal(0u); std::size_t totalInternal(6ull<<30); //! \TODO return totalInternal; } }; //############################################################################# //! The CUDA RT device free memory get trait specialization. template<> struct GetFreeMemBytes< dev::DevOmp5> { //----------------------------------------------------------------------------- ALPAKA_FN_HOST static auto getFreeMemBytes( dev::DevOmp5 const & dev) -> std::size_t { alpaka::ignore_unused(dev); //! \todo query device std::size_t freeInternal((6ull<<30)); // std::size_t totalInternal(0u); return freeInternal; } }; //############################################################################# //! The OpenMP 5 device warp size get trait specialization. template<> struct GetWarpSize< dev::DevOmp5> { //----------------------------------------------------------------------------- ALPAKA_FN_HOST static auto getWarpSize( dev::DevOmp5 const & dev) -> std::size_t { alpaka::ignore_unused(dev); return 1u; } }; //############################################################################# //! The CUDA RT device reset trait specialization. template<> struct Reset< dev::DevOmp5> { //----------------------------------------------------------------------------- ALPAKA_FN_HOST static auto reset( dev::DevOmp5 const & dev) -> void { alpaka::ignore_unused(dev); //! \TODO } }; } } namespace mem { namespace buf { template< typename TElem, typename TDim, typename TIdx> class BufOmp5; namespace traits { //############################################################################# //! The CUDA RT device memory buffer type trait specialization. template< typename TElem, typename TDim, typename TIdx> struct BufType< dev::DevOmp5, TElem, TDim, TIdx> { using type = mem::buf::BufOmp5<TElem, TDim, TIdx>; }; } } } namespace pltf { namespace traits { //############################################################################# //! The CUDA RT device platform type trait specialization. template<> struct PltfType< dev::DevOmp5> { using type = pltf::PltfOmp5; }; } } namespace queue { using QueueOmp5NonBlocking = QueueGenericThreadsNonBlocking<dev::DevOmp5>; using QueueOmp5Blocking = QueueGenericThreadsBlocking<dev::DevOmp5>; namespace traits { template<> struct QueueType< dev::DevOmp5, queue::Blocking > { using type = queue::QueueOmp5Blocking; }; template<> struct QueueType< dev::DevOmp5, queue::NonBlocking > { using type = queue::QueueOmp5NonBlocking; }; } } namespace wait { namespace traits { //############################################################################# //! The thread Omp5 device wait specialization. //! //! Blocks until the device has completed all preceding requested tasks. //! Tasks that are enqueued or queues that are created after this call is made are not waited for. template<> struct CurrentThreadWaitFor< dev::DevOmp5> { //----------------------------------------------------------------------------- ALPAKA_FN_HOST static auto currentThreadWaitFor( dev::DevOmp5 const & dev) -> void { ALPAKA_DEBUG_FULL_LOG_SCOPE; generic::currentThreadWaitForDevice(dev); // #pragma omp taskwait } }; } } } #endif <commit_msg>DevOmp5: Add conceptDev<commit_after>/* Copyright 2019 Benjamin Worpitz * * This file is part of Alpaka. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #ifdef ALPAKA_ACC_ANY_BT_OMP5_ENABLED #if _OPENMP < 201307 #error If ALPAKA_ACC_ANY_BT_OMP5_ENABLED is set, the compiler has to support OpenMP 4.0 or higher! #endif #include <alpaka/dev/Traits.hpp> #include <alpaka/mem/buf/Traits.hpp> #include <alpaka/pltf/Traits.hpp> #include <alpaka/wait/Traits.hpp> #include <alpaka/queue/Traits.hpp> #include <alpaka/queue/Properties.hpp> #include <alpaka/core/Omp5.hpp> #include <alpaka/queue/cpu/IGenericThreadsQueue.hpp> #include <alpaka/queue/QueueGenericThreadsNonBlocking.hpp> #include <alpaka/queue/QueueGenericThreadsBlocking.hpp> namespace alpaka { namespace dev { class DevOmp5; } namespace pltf { namespace traits { template< typename TPltf, typename TSfinae> struct GetDevByIdx; } class PltfOmp5; } namespace dev { namespace omp5 { namespace detail { //############################################################################# //! The Omp5 device implementation. class DevOmp5Impl { public: //----------------------------------------------------------------------------- DevOmp5Impl(int iDevice) : m_iDevice(iDevice) {} //----------------------------------------------------------------------------- DevOmp5Impl(DevOmp5Impl const &) = delete; //----------------------------------------------------------------------------- DevOmp5Impl(DevOmp5Impl &&) = delete; //----------------------------------------------------------------------------- auto operator=(DevOmp5Impl const &) -> DevOmp5Impl & = delete; //----------------------------------------------------------------------------- auto operator=(DevOmp5Impl &&) -> DevOmp5Impl & = delete; //----------------------------------------------------------------------------- ~DevOmp5Impl() = default; //----------------------------------------------------------------------------- ALPAKA_FN_HOST auto getAllExistingQueues() const -> std::vector<std::shared_ptr<queue::IGenericThreadsQueue<DevOmp5>>> { std::vector<std::shared_ptr<queue::IGenericThreadsQueue<DevOmp5>>> vspQueues; std::lock_guard<std::mutex> lk(m_Mutex); vspQueues.reserve(m_queues.size()); for(auto it = m_queues.begin(); it != m_queues.end();) { auto spQueue(it->lock()); if(spQueue) { vspQueues.emplace_back(std::move(spQueue)); ++it; } else { it = m_queues.erase(it); } } return vspQueues; } //----------------------------------------------------------------------------- //! Registers the given queue on this device. //! NOTE: Every queue has to be registered for correct functionality of device wait operations! ALPAKA_FN_HOST auto registerQueue(std::shared_ptr<queue::IGenericThreadsQueue<DevOmp5>> spQueue) -> void { std::lock_guard<std::mutex> lk(m_Mutex); // Register this queue on the device. m_queues.push_back(spQueue); } int iDevice() const {return m_iDevice;} private: std::mutex mutable m_Mutex; std::vector<std::weak_ptr<queue::IGenericThreadsQueue<DevOmp5>>> mutable m_queues; int m_iDevice = 0; }; } } //############################################################################# //! The Omp5 device handle. class DevOmp5 : public concepts::Implements<wait::ConceptCurrentThreadWaitFor, DevOmp5>, public concepts::Implements<ConceptDev, DevOmp5> { friend struct pltf::traits::GetDevByIdx<pltf::PltfOmp5>; protected: //----------------------------------------------------------------------------- DevOmp5(int iDevice) : m_spDevOmp5Impl(std::make_shared<omp5::detail::DevOmp5Impl>(iDevice)) {} public: //----------------------------------------------------------------------------- DevOmp5(DevOmp5 const &) = default; //----------------------------------------------------------------------------- DevOmp5(DevOmp5 &&) = default; //----------------------------------------------------------------------------- auto operator=(DevOmp5 const &) -> DevOmp5 & = default; //----------------------------------------------------------------------------- auto operator=(DevOmp5 &&) -> DevOmp5 & = default; //----------------------------------------------------------------------------- ALPAKA_FN_HOST auto operator==(DevOmp5 const & rhs) const -> bool { return m_spDevOmp5Impl->iDevice() == rhs.m_spDevOmp5Impl->iDevice(); } //----------------------------------------------------------------------------- ALPAKA_FN_HOST auto operator!=(DevOmp5 const & rhs) const -> bool { return !((*this) == rhs); } //----------------------------------------------------------------------------- ~DevOmp5() = default; int iDevice() const {return m_spDevOmp5Impl->iDevice();} ALPAKA_FN_HOST auto getAllQueues() const -> std::vector<std::shared_ptr<queue::IGenericThreadsQueue<DevOmp5>>> { return m_spDevOmp5Impl->getAllExistingQueues(); } //----------------------------------------------------------------------------- //! Registers the given queue on this device. //! NOTE: Every queue has to be registered for correct functionality of device wait operations! ALPAKA_FN_HOST auto registerQueue(std::shared_ptr<queue::IGenericThreadsQueue<DevOmp5>> spQueue) const -> void { m_spDevOmp5Impl->registerQueue(spQueue); } public: std::shared_ptr<omp5::detail::DevOmp5Impl> m_spDevOmp5Impl; }; } namespace dev { namespace traits { //############################################################################# //! The CUDA RT device name get trait specialization. template<> struct GetName< dev::DevOmp5> { //----------------------------------------------------------------------------- ALPAKA_FN_HOST static auto getName( dev::DevOmp5 const &) -> std::string { return std::string("OMP5 target"); } }; //############################################################################# //! The CUDA RT device available memory get trait specialization. template<> struct GetMemBytes< dev::DevOmp5> { //----------------------------------------------------------------------------- ALPAKA_FN_HOST static auto getMemBytes( dev::DevOmp5 const & dev) -> std::size_t { alpaka::ignore_unused(dev); //! \TODO // std::size_t freeInternal(0u); std::size_t totalInternal(6ull<<30); //! \TODO return totalInternal; } }; //############################################################################# //! The CUDA RT device free memory get trait specialization. template<> struct GetFreeMemBytes< dev::DevOmp5> { //----------------------------------------------------------------------------- ALPAKA_FN_HOST static auto getFreeMemBytes( dev::DevOmp5 const & dev) -> std::size_t { alpaka::ignore_unused(dev); //! \todo query device std::size_t freeInternal((6ull<<30)); // std::size_t totalInternal(0u); return freeInternal; } }; //############################################################################# //! The OpenMP 5 device warp size get trait specialization. template<> struct GetWarpSize< dev::DevOmp5> { //----------------------------------------------------------------------------- ALPAKA_FN_HOST static auto getWarpSize( dev::DevOmp5 const & dev) -> std::size_t { alpaka::ignore_unused(dev); return 1u; } }; //############################################################################# //! The CUDA RT device reset trait specialization. template<> struct Reset< dev::DevOmp5> { //----------------------------------------------------------------------------- ALPAKA_FN_HOST static auto reset( dev::DevOmp5 const & dev) -> void { alpaka::ignore_unused(dev); //! \TODO } }; } } namespace mem { namespace buf { template< typename TElem, typename TDim, typename TIdx> class BufOmp5; namespace traits { //############################################################################# //! The CUDA RT device memory buffer type trait specialization. template< typename TElem, typename TDim, typename TIdx> struct BufType< dev::DevOmp5, TElem, TDim, TIdx> { using type = mem::buf::BufOmp5<TElem, TDim, TIdx>; }; } } } namespace pltf { namespace traits { //############################################################################# //! The CUDA RT device platform type trait specialization. template<> struct PltfType< dev::DevOmp5> { using type = pltf::PltfOmp5; }; } } namespace queue { using QueueOmp5NonBlocking = QueueGenericThreadsNonBlocking<dev::DevOmp5>; using QueueOmp5Blocking = QueueGenericThreadsBlocking<dev::DevOmp5>; namespace traits { template<> struct QueueType< dev::DevOmp5, queue::Blocking > { using type = queue::QueueOmp5Blocking; }; template<> struct QueueType< dev::DevOmp5, queue::NonBlocking > { using type = queue::QueueOmp5NonBlocking; }; } } namespace wait { namespace traits { //############################################################################# //! The thread Omp5 device wait specialization. //! //! Blocks until the device has completed all preceding requested tasks. //! Tasks that are enqueued or queues that are created after this call is made are not waited for. template<> struct CurrentThreadWaitFor< dev::DevOmp5> { //----------------------------------------------------------------------------- ALPAKA_FN_HOST static auto currentThreadWaitFor( dev::DevOmp5 const & dev) -> void { ALPAKA_DEBUG_FULL_LOG_SCOPE; generic::currentThreadWaitForDevice(dev); // #pragma omp taskwait } }; } } } #endif <|endoftext|>
<commit_before>// Copyright 2018 Global Phasing Ltd. // // Reading coordinates from chemical component or Refmac monomer library files. #ifndef GEMMI_CHEMCOMP_XYZ_HPP_ #define GEMMI_CHEMCOMP_XYZ_HPP_ #include <array> #include "cifdoc.hpp" // for Block, etc #include "numb.hpp" // for as_number #include "model.hpp" // for Atom, Residue, etc namespace gemmi { // Reading chemical component as a coordinate file. enum class ChemCompModel { Xyz, // _chem_comp_atom.x, etc Example, // _chem_comp_atom.model_Cartn_x Ideal // _chem_comp_atom.pdbx_model_Cartn_x_ideal }; inline Residue make_residue_from_chemcomp_block(const cif::Block& block, ChemCompModel kind) { std::array<std::string, 3> xyz_tags; switch (kind) { case ChemCompModel::Xyz: xyz_tags = {{"x", "y", "z"}}; break; case ChemCompModel::Example: xyz_tags = {{"model_Cartn_x", "model_Cartn_y", "model_Cartn_z"}}; break; case ChemCompModel::Ideal: xyz_tags = {{"pdbx_model_Cartn_x_ideal", "pdbx_model_Cartn_y_ideal", "pdbx_model_Cartn_z_ideal"}}; break; } Residue res; cif::Column col = const_cast<cif::Block&>(block).find_values("_chem_comp_atom.comp_id"); if (col && col.length() > 0) res.name = col[0]; else res.name = block.name.substr(starts_with(block.name, "comp_") ? 5 : 0); cif::Table table = const_cast<cif::Block&>(block).find("_chem_comp_atom.", {"atom_id", "type_symbol", "?charge", xyz_tags[0], xyz_tags[1], xyz_tags[2]}); res.atoms.resize(table.length()); int n = 0; for (auto row : table) { Atom& atom = res.atoms[n++]; atom.name = row.str(0); atom.element = Element(row.str(1)); if (row.has2(2)) // Charge is defined as integer, but some cif files in the wild have // trailing '.000', so we read it as floating-point number. atom.charge = (signed char) std::round(cif::as_number(row[2])); atom.pos = Position(cif::as_number(row[3]), cif::as_number(row[4]), cif::as_number(row[5])); } return res; } inline Model make_model_from_chemcomp_block(const cif::Block& block, ChemCompModel kind) { std::string name; switch (kind) { case ChemCompModel::Xyz: name = "xyz"; break; case ChemCompModel::Example: name = "example_xyz"; break; case ChemCompModel::Ideal: name = "ideal_xyz"; break; } Model model(name); model.chains.emplace_back(""); model.chains[0].residues.push_back( make_residue_from_chemcomp_block(block, kind)); return model; } // For CCD input - returns a structure with two single-residue models: // example (model_Cartn_x) and ideal (pdbx_model_Cartn_x_ideal). // For Refmac dictionary (monomer library) files returns structure with // a single model. inline Structure make_structure_from_chemcomp_block(const cif::Block& block) { Structure st; st.input_format = CoorFormat::ChemComp; if (block.has_any_value("_chem_comp_atom.x")) st.models.push_back( make_model_from_chemcomp_block(block, ChemCompModel::Xyz)); if (block.has_any_value("_chem_comp_atom.model_Cartn_x")) st.models.push_back( make_model_from_chemcomp_block(block, ChemCompModel::Example)); if (block.has_any_value("_chem_comp_atom.pdbx_model_Cartn_x_ideal")) st.models.push_back( make_model_from_chemcomp_block(block, ChemCompModel::Ideal)); return st; } // a helper function for use with make_structure_from_chemcomp_block(): // int n = check_chemcomp_block_number(doc); // if (n != -1) // Structure st = make_structure_from_chemcomp_block(doc.blocks[n]); inline int check_chemcomp_block_number(const cif::Document& doc) { // monomer library file without global_ if (doc.blocks.size() == 2 && doc.blocks[0].name == "comp_list") return 1; // monomer library file with global_ if (doc.blocks.size() == 3 && doc.blocks[0].name.empty() && doc.blocks[1].name == "comp_list") return 2; // CCD file if (doc.blocks.size() == 1 && !doc.blocks[0].has_tag("_atom_site.id") && doc.blocks[0].has_tag("_chem_comp_atom.atom_id")) return 0; return -1; } inline Structure make_structure_from_chemcomp_doc(const cif::Document& doc) { int n = check_chemcomp_block_number(doc); if (n == -1) fail("Not a chem_comp format."); return make_structure_from_chemcomp_block(doc.blocks[n]); } } // namespace gemmi #endif // vim:sw=2:ts=2:et <commit_msg>make_structure_from_chemcomp_block: set Structure::name<commit_after>// Copyright 2018 Global Phasing Ltd. // // Reading coordinates from chemical component or Refmac monomer library files. #ifndef GEMMI_CHEMCOMP_XYZ_HPP_ #define GEMMI_CHEMCOMP_XYZ_HPP_ #include <array> #include "cifdoc.hpp" // for Block, etc #include "numb.hpp" // for as_number #include "model.hpp" // for Atom, Residue, etc namespace gemmi { // Reading chemical component as a coordinate file. enum class ChemCompModel { Xyz, // _chem_comp_atom.x, etc Example, // _chem_comp_atom.model_Cartn_x Ideal // _chem_comp_atom.pdbx_model_Cartn_x_ideal }; inline Residue make_residue_from_chemcomp_block(const cif::Block& block, ChemCompModel kind) { std::array<std::string, 3> xyz_tags; switch (kind) { case ChemCompModel::Xyz: xyz_tags = {{"x", "y", "z"}}; break; case ChemCompModel::Example: xyz_tags = {{"model_Cartn_x", "model_Cartn_y", "model_Cartn_z"}}; break; case ChemCompModel::Ideal: xyz_tags = {{"pdbx_model_Cartn_x_ideal", "pdbx_model_Cartn_y_ideal", "pdbx_model_Cartn_z_ideal"}}; break; } Residue res; cif::Column col = const_cast<cif::Block&>(block).find_values("_chem_comp_atom.comp_id"); if (col && col.length() > 0) res.name = col[0]; else res.name = block.name.substr(starts_with(block.name, "comp_") ? 5 : 0); cif::Table table = const_cast<cif::Block&>(block).find("_chem_comp_atom.", {"atom_id", "type_symbol", "?charge", xyz_tags[0], xyz_tags[1], xyz_tags[2]}); res.atoms.resize(table.length()); int n = 0; for (auto row : table) { Atom& atom = res.atoms[n++]; atom.name = row.str(0); atom.element = Element(row.str(1)); if (row.has2(2)) // Charge is defined as integer, but some cif files in the wild have // trailing '.000', so we read it as floating-point number. atom.charge = (signed char) std::round(cif::as_number(row[2])); atom.pos = Position(cif::as_number(row[3]), cif::as_number(row[4]), cif::as_number(row[5])); } return res; } inline Model make_model_from_chemcomp_block(const cif::Block& block, ChemCompModel kind) { std::string name; switch (kind) { case ChemCompModel::Xyz: name = "xyz"; break; case ChemCompModel::Example: name = "example_xyz"; break; case ChemCompModel::Ideal: name = "ideal_xyz"; break; } Model model(name); model.chains.emplace_back(""); model.chains[0].residues.push_back( make_residue_from_chemcomp_block(block, kind)); return model; } // For CCD input - returns a structure with two single-residue models: // example (model_Cartn_x) and ideal (pdbx_model_Cartn_x_ideal). // For Refmac dictionary (monomer library) files returns structure with // a single model. inline Structure make_structure_from_chemcomp_block(const cif::Block& block) { Structure st; st.input_format = CoorFormat::ChemComp; if (const std::string* name = block.find_value("_chem_comp.id")) st.name = *name; if (block.has_any_value("_chem_comp_atom.x")) st.models.push_back( make_model_from_chemcomp_block(block, ChemCompModel::Xyz)); if (block.has_any_value("_chem_comp_atom.model_Cartn_x")) st.models.push_back( make_model_from_chemcomp_block(block, ChemCompModel::Example)); if (block.has_any_value("_chem_comp_atom.pdbx_model_Cartn_x_ideal")) st.models.push_back( make_model_from_chemcomp_block(block, ChemCompModel::Ideal)); return st; } // a helper function for use with make_structure_from_chemcomp_block(): // int n = check_chemcomp_block_number(doc); // if (n != -1) // Structure st = make_structure_from_chemcomp_block(doc.blocks[n]); inline int check_chemcomp_block_number(const cif::Document& doc) { // monomer library file without global_ if (doc.blocks.size() == 2 && doc.blocks[0].name == "comp_list") return 1; // monomer library file with global_ if (doc.blocks.size() == 3 && doc.blocks[0].name.empty() && doc.blocks[1].name == "comp_list") return 2; // CCD file if (doc.blocks.size() == 1 && !doc.blocks[0].has_tag("_atom_site.id") && doc.blocks[0].has_tag("_chem_comp_atom.atom_id")) return 0; return -1; } inline Structure make_structure_from_chemcomp_doc(const cif::Document& doc) { int n = check_chemcomp_block_number(doc); if (n == -1) fail("Not a chem_comp format."); return make_structure_from_chemcomp_block(doc.blocks[n]); } } // namespace gemmi #endif // vim:sw=2:ts=2:et <|endoftext|>
<commit_before>//===- examples/Tooling/ClangCheck.cpp - Clang check tool -----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements a clang-check tool that runs the // clang::SyntaxOnlyAction over a number of translation units. // // Usage: // clang-check <cmake-output-dir> <file1> <file2> ... // // Where <cmake-output-dir> is a CMake build directory in which a file named // compile_commands.json exists (enable -DCMAKE_EXPORT_COMPILE_COMMANDS in // CMake to get this output). // // <file1> ... specify the paths of files in the CMake source tree. This path // is looked up in the compile command database. If the path of a file is // absolute, it needs to point into CMake's source tree. If the path is // relative, the current working directory needs to be in the CMake source // tree and the file must be in a subdirectory of the current working // directory. "./" prefixes in the relative files will be automatically // removed, but the rest of a relative path must be a suffix of a path in // the compile command line database. // // For example, to use clang-check on all files in a subtree of the source // tree, use: // // /path/in/subtree $ find . -name '*.cpp'| xargs clang-check /path/to/source // //===----------------------------------------------------------------------===// #include "llvm/Support/CommandLine.h" #include "clang/Frontend/FrontendActions.h" #include "clang/Tooling/CompilationDatabase.h" #include "clang/Tooling/Tooling.h" using namespace clang::tooling; using namespace llvm; cl::opt<std::string> BuildPath( "p", cl::desc("<build-path>"), cl::Optional); cl::list<std::string> SourcePaths( cl::Positional, cl::desc("<source0> [... <sourceN>]"), cl::OneOrMore); int main(int argc, const char **argv) { llvm::OwningPtr<CompilationDatabase> Compilations( FixedCompilationDatabase::loadFromCommandLine(argc, argv)); cl::ParseCommandLineOptions(argc, argv); if (!Compilations) { std::string ErrorMessage; if (!BuildPath.empty()) { Compilations.reset( CompilationDatabase::autoDetectFromDirectory(BuildPath, ErrorMessage)); } else { Compilations.reset(CompilationDatabase::autoDetectFromSource( SourcePaths[0], ErrorMessage)); } if (!Compilations) llvm::report_fatal_error(ErrorMessage); } ClangTool Tool(*Compilations, SourcePaths); return Tool.run(newFrontendActionFactory<clang::SyntaxOnlyAction>()); } <commit_msg>Fix usage instructions for clang-check.<commit_after>//===- examples/Tooling/ClangCheck.cpp - Clang check tool -----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements a clang-check tool that runs the // clang::SyntaxOnlyAction over a number of translation units. // // Usage: // clang-check [-p <cmake-output-dir>] <file1> <file2> ... // // Where <cmake-output-dir> is a CMake build directory in which a file named // compile_commands.json exists (enable -DCMAKE_EXPORT_COMPILE_COMMANDS in // CMake to get this output). If not provided, clang-check will search for this // file in all of <file1>'s parent directories. // // <file1> ... specify the paths of files in the CMake source tree. This path // is looked up in the compile command database. If the path of a file is // absolute, it needs to point into CMake's source tree. If the path is // relative, the current working directory needs to be in the CMake source // tree and the file must be in a subdirectory of the current working // directory. "./" prefixes in the relative files will be automatically // removed, but the rest of a relative path must be a suffix of a path in // the compile command line database. // // For example, to use clang-check on all files in a subtree of the source // tree, use: // // /path/in/subtree $ find . -name '*.cpp'| xargs clang-check // //===----------------------------------------------------------------------===// #include "llvm/Support/CommandLine.h" #include "clang/Frontend/FrontendActions.h" #include "clang/Tooling/CompilationDatabase.h" #include "clang/Tooling/Tooling.h" using namespace clang::tooling; using namespace llvm; cl::opt<std::string> BuildPath( "p", cl::desc("<build-path>"), cl::Optional); cl::list<std::string> SourcePaths( cl::Positional, cl::desc("<source0> [... <sourceN>]"), cl::OneOrMore); int main(int argc, const char **argv) { llvm::OwningPtr<CompilationDatabase> Compilations( FixedCompilationDatabase::loadFromCommandLine(argc, argv)); cl::ParseCommandLineOptions(argc, argv); if (!Compilations) { std::string ErrorMessage; if (!BuildPath.empty()) { Compilations.reset( CompilationDatabase::autoDetectFromDirectory(BuildPath, ErrorMessage)); } else { Compilations.reset(CompilationDatabase::autoDetectFromSource( SourcePaths[0], ErrorMessage)); } if (!Compilations) llvm::report_fatal_error(ErrorMessage); } ClangTool Tool(*Compilations, SourcePaths); return Tool.run(newFrontendActionFactory<clang::SyntaxOnlyAction>()); } <|endoftext|>
<commit_before>/* * Copyright (c) 2015-2016, Technische Universität Dresden, Germany * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions * and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other materials provided * with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used to * endorse or promote products derived from this software without specific prior written * permission. * * 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 HOLDER 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. */ #ifndef INCLUDE_NITRO_EXCEPT_RAISE_HPP #define INCLUDE_NITRO_EXCEPT_RAISE_HPP #include <nitro/except/exception.hpp> #include <sstream> #include <string> namespace nitro { namespace except { template <typename Exception = nitro::except::exception, typename... Args> [[noreturn]] inline void raise(Args... args) { throw Exception(args...); } } // namespace except using except::raise; } // namespace nitro #endif // INCLUDE_NITRO_EXCEPT_RAISE_HPP <commit_msg>Adds more forwarding in except<commit_after>/* * Copyright (c) 2015-2016, Technische Universität Dresden, Germany * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions * and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other materials provided * with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used to * endorse or promote products derived from this software without specific prior written * permission. * * 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 HOLDER 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. */ #ifndef INCLUDE_NITRO_EXCEPT_RAISE_HPP #define INCLUDE_NITRO_EXCEPT_RAISE_HPP #include <nitro/except/exception.hpp> #include <sstream> #include <string> namespace nitro { namespace except { template <typename Exception = nitro::except::exception, typename... Args> [[noreturn]] inline void raise(Args&&... args) { throw Exception(std::forward<Args>(args)...); } } // namespace except using except::raise; } // namespace nitro #endif // INCLUDE_NITRO_EXCEPT_RAISE_HPP <|endoftext|>
<commit_before>#pragma once #include <utility> #include "reflection_info.hpp" namespace shadow { //////////////////////////////////////////////////////////////////////////////// // user facing API types carrying information and functionality for the // reflection system class reflection_manager; // holds one value with type/reflection information class variable { private: // holds type erased value any value_; // these identify the type erased value const reflection_manager* manager_; std::size_t type_index_; }; template <class InfoType, template <class> class... Policies> class api_type_aggregator : public Policies<api_type_aggregator<InfoType, Policies...>>... { public: api_type_aggregator() : info_(nullptr), manager_(nullptr) { } api_type_aggregator(const InfoType* info, const reflection_manager* manager) : info_(info), manager_(manager) { } api_type_aggregator* operator->() { return this; } const api_type_aggregator* operator->() const { return this; } public: const InfoType* info_; const reflection_manager* manager_; }; template <class Derived> class get_name_policy { public: std::string name() const { return (static_cast<const Derived*>(this))->info_->name; } }; template <class Derived> class get_size_policy { public: std::size_t size() const { return static_cast<const Derived*>(this)->info_->size; } }; typedef api_type_aggregator<type_info, get_name_policy, get_size_policy> type_; template <class Derived> class get_type_policy { public: type_ get_type() const { // retrieve type index const auto type_index = static_cast<const Derived*>(this)->info_->type_index; return static_cast<const Derived*>(this)->manager_->type_by_index( type_index); } }; typedef api_type_aggregator<constructor_info, get_type_policy> constructor_; template <class InfoType, class ProxyType> class info_iterator_ { public: typedef ProxyType value_type; typedef typename std::iterator_traits<const InfoType*>::difference_type difference_type; typedef ProxyType reference; typedef ProxyType pointer; typedef typename std::iterator_traits<const InfoType*>::iterator_category iterator_category; public: info_iterator_() = default; info_iterator_(const InfoType* current, const reflection_manager* manager) : current_(current), manager_(manager) { } public: ProxyType operator*() const { return ProxyType(current_, manager_); } ProxyType operator->() const { return ProxyType(current_, manager_); } ProxyType operator[](difference_type n) const { return ProxyType(current_ + n, manager_); } info_iterator_& operator++() { ++current_; return *this; } info_iterator_ operator++(int) { auto temp = *this; ++(*this); return temp; } info_iterator_& operator--() { --current_; return *this; } info_iterator_ operator--(int) { auto temp = *this; --(*this); return temp; } info_iterator_& operator+=(difference_type n) { current_ += n; return *this; } info_iterator_& operator-=(difference_type n) { current_ -= n; return *this; } info_iterator_ operator+(difference_type n) const { return info_iterator_(current_ + n, manager_); } info_iterator_ operator-(difference_type n) const { return info_iterator_(current_ - n, manager_); } difference_type operator-(const info_iterator_& other) { return current_ - other.current_; } friend info_iterator_ operator+(difference_type lhs, const info_iterator_& rhs) { return rhs + lhs; } bool operator==(const info_iterator_& other) const { return current_ == other.current_; } bool operator!=(const info_iterator_& other) const { return current_ != other.current_; } bool operator<(const info_iterator_& other) const { return current_ < other.current_; } bool operator>(const info_iterator_& other) const { return current_ > other.current_; } bool operator<=(const info_iterator_& other) const { return current_ <= other.current_; } bool operator>=(const info_iterator_& other) const { return current_ >= other.current_; } private: InfoType* current_; const reflection_manager* manager_; }; class reflection_manager { public: template <class Derived> friend class get_type_policy; typedef type_ type; typedef info_iterator_<const type_info, const type> const_type_iterator; typedef constructor_ constructor; typedef info_iterator_<const constructor_info, const constructor> const_constructor_iterator; public: reflection_manager() = default; template <class TypeInfoArrayHolder, class ConstructorInfoArrayHolder, class ConversionInfoArrayHolder, class StringSerializationInfoArrayHolder, class FreeFunctionInfoArrayHolder, class MemberFunctionInfoArrayHolder, class MemberVariableInfoArrayHolder> reflection_manager(TypeInfoArrayHolder, ConstructorInfoArrayHolder, ConversionInfoArrayHolder, StringSerializationInfoArrayHolder, FreeFunctionInfoArrayHolder, MemberFunctionInfoArrayHolder, MemberVariableInfoArrayHolder) : type_info_range_(initialize_range(TypeInfoArrayHolder())), constructor_info_range_( initialize_range(ConstructorInfoArrayHolder())), conversion_info_range_(initialize_range(ConversionInfoArrayHolder())), string_serialization_info_range_( initialize_range(StringSerializationInfoArrayHolder())), free_function_info_range_( initialize_range(FreeFunctionInfoArrayHolder())), member_function_info_range_( initialize_range(MemberFunctionInfoArrayHolder())), member_variable_info_range_( initialize_range(MemberVariableInfoArrayHolder())) { } private: // generic initialization helper function template <class ArrayHolderType> std::pair<const typename ArrayHolderType::type*, const typename ArrayHolderType::type*> initialize_range(ArrayHolderType) { // clang complains here due to the comparison of decayed array and // nullptr, since in the case ArrayHolderType::value was an array, this // would always evaluate to true. The fact is that // ArrayHolderType::value may be a pointer to nullptr for some cases of // ArrayHolderType. #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wtautological-pointer-compare" if(ArrayHolderType::value != nullptr) { return std::make_pair(std::begin(ArrayHolderType::value), std::end(ArrayHolderType::value)); } else { std::pair<const typename ArrayHolderType::type*, const typename ArrayHolderType::type*> out(nullptr, nullptr); return out; } } template <class ArrayHolderType> std::size_t array_size(ArrayHolderType) { if(ArrayHolderType::value == nullptr) { return 0; } else { return std::extent<decltype(ArrayHolderType::value)>::value; } } #pragma clang diagnostic pop type type_by_index(std::size_t index) const { return type(type_info_range_.first + index, this); } public: //////////////////////////////////////////////////////////////////////////// // main api interface for interacting with the reflection system std::pair<const_type_iterator, const_type_iterator> types() const { return std::make_pair( const_type_iterator(type_info_range_.first, this), const_type_iterator(type_info_range_.second, this)); } std::pair<const_constructor_iterator, const_constructor_iterator> constructors() const { return std::make_pair( const_constructor_iterator(constructor_info_range_.first, this), const_constructor_iterator(constructor_info_range_.second, this)); } private: // pairs hold iterators to beginning and end of arrays of information // generated at compile time std::pair<const type_info*, const type_info*> type_info_range_; std::pair<const constructor_info*, const constructor_info*> constructor_info_range_; std::pair<const conversion_info*, const conversion_info*> conversion_info_range_; std::pair<const string_serialization_info*, const string_serialization_info*> string_serialization_info_range_; std::pair<const free_function_info*, const free_function_info*> free_function_info_range_; std::pair<const member_function_info*, const member_function_info*> member_function_info_range_; std::pair<const member_variable_info*, const member_variable_info*> member_variable_info_range_; }; } namespace std { // specialize std::iterator_traits for info_iterator_ template <class InfoType, class ProxyType> struct std::iterator_traits<shadow::info_iterator_<InfoType, ProxyType>> { typedef typename shadow::info_iterator_<InfoType, ProxyType>::value_type value_type; typedef typename shadow::info_iterator_<InfoType, ProxyType>::difference_type difference_type; typedef typename shadow::info_iterator_<InfoType, ProxyType>::reference reference; typedef typename shadow::info_iterator_<InfoType, ProxyType>::pointer pointer; typedef typename shadow::info_iterator_<InfoType, ProxyType>::iterator_category iterator_category; }; } <commit_msg>Add buckets_by_index private member function to reflection_manager.<commit_after>#pragma once #include <utility> #include <vector> #include <algorithm> #include "reflection_info.hpp" namespace shadow { //////////////////////////////////////////////////////////////////////////////// // user facing API types carrying information and functionality for the // reflection system class reflection_manager; // holds one value with type/reflection information class variable { private: // holds type erased value any value_; // these identify the type erased value const reflection_manager* manager_; std::size_t type_index_; }; template <class InfoType, template <class> class... Policies> class api_type_aggregator : public Policies<api_type_aggregator<InfoType, Policies...>>... { public: api_type_aggregator() : info_(nullptr), manager_(nullptr) { } api_type_aggregator(const InfoType* info, const reflection_manager* manager) : info_(info), manager_(manager) { } api_type_aggregator* operator->() { return this; } const api_type_aggregator* operator->() const { return this; } public: const InfoType* info_; const reflection_manager* manager_; }; template <class Derived> class get_name_policy { public: std::string name() const { return (static_cast<const Derived*>(this))->info_->name; } }; template <class Derived> class get_size_policy { public: std::size_t size() const { return static_cast<const Derived*>(this)->info_->size; } }; typedef api_type_aggregator<type_info, get_name_policy, get_size_policy> type_; template <class Derived> class get_type_policy { public: type_ get_type() const { // retrieve type index const auto type_index = static_cast<const Derived*>(this)->info_->type_index; return static_cast<const Derived*>(this)->manager_->type_by_index( type_index); } }; typedef api_type_aggregator<constructor_info, get_type_policy> constructor_; template <class InfoType, class ProxyType> class info_iterator_ { public: typedef ProxyType value_type; typedef typename std::iterator_traits<const InfoType*>::difference_type difference_type; typedef ProxyType reference; typedef ProxyType pointer; typedef typename std::iterator_traits<const InfoType*>::iterator_category iterator_category; public: info_iterator_() = default; info_iterator_(const InfoType* current, const reflection_manager* manager) : current_(current), manager_(manager) { } public: ProxyType operator*() const { return ProxyType(current_, manager_); } ProxyType operator->() const { return ProxyType(current_, manager_); } ProxyType operator[](difference_type n) const { return ProxyType(current_ + n, manager_); } info_iterator_& operator++() { ++current_; return *this; } info_iterator_ operator++(int) { auto temp = *this; ++(*this); return temp; } info_iterator_& operator--() { --current_; return *this; } info_iterator_ operator--(int) { auto temp = *this; --(*this); return temp; } info_iterator_& operator+=(difference_type n) { current_ += n; return *this; } info_iterator_& operator-=(difference_type n) { current_ -= n; return *this; } info_iterator_ operator+(difference_type n) const { return info_iterator_(current_ + n, manager_); } info_iterator_ operator-(difference_type n) const { return info_iterator_(current_ - n, manager_); } difference_type operator-(const info_iterator_& other) { return current_ - other.current_; } friend info_iterator_ operator+(difference_type lhs, const info_iterator_& rhs) { return rhs + lhs; } bool operator==(const info_iterator_& other) const { return current_ == other.current_; } bool operator!=(const info_iterator_& other) const { return current_ != other.current_; } bool operator<(const info_iterator_& other) const { return current_ < other.current_; } bool operator>(const info_iterator_& other) const { return current_ > other.current_; } bool operator<=(const info_iterator_& other) const { return current_ <= other.current_; } bool operator>=(const info_iterator_& other) const { return current_ >= other.current_; } private: InfoType* current_; const reflection_manager* manager_; }; class reflection_manager { public: template <class Derived> friend class get_type_policy; typedef type_ type; typedef info_iterator_<const type_info, const type> const_type_iterator; typedef constructor_ constructor; typedef info_iterator_<const constructor_info, const constructor> const_constructor_iterator; public: reflection_manager() = default; template <class TypeInfoArrayHolder, class ConstructorInfoArrayHolder, class ConversionInfoArrayHolder, class StringSerializationInfoArrayHolder, class FreeFunctionInfoArrayHolder, class MemberFunctionInfoArrayHolder, class MemberVariableInfoArrayHolder> reflection_manager(TypeInfoArrayHolder, ConstructorInfoArrayHolder, ConversionInfoArrayHolder, StringSerializationInfoArrayHolder, FreeFunctionInfoArrayHolder, MemberFunctionInfoArrayHolder, MemberVariableInfoArrayHolder) : type_info_range_(initialize_range(TypeInfoArrayHolder())), constructor_info_range_( initialize_range(ConstructorInfoArrayHolder())), conversion_info_range_(initialize_range(ConversionInfoArrayHolder())), string_serialization_info_range_( initialize_range(StringSerializationInfoArrayHolder())), free_function_info_range_( initialize_range(FreeFunctionInfoArrayHolder())), member_function_info_range_( initialize_range(MemberFunctionInfoArrayHolder())), member_variable_info_range_( initialize_range(MemberVariableInfoArrayHolder())), constructor_info_by_index_( buckets_by_index(constructor_info_range_, TypeInfoArrayHolder())) { } private: // clang complains here due to the comparison of decayed array and // nullptr, since in the case ArrayHolderType::value was an array, this // would always evaluate to true. The fact is that // ArrayHolderType::value may be a pointer to nullptr for some cases of // ArrayHolderType. #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wtautological-pointer-compare" template <class ArrayHolderType> std::pair<const typename ArrayHolderType::type*, const typename ArrayHolderType::type*> initialize_range(ArrayHolderType) { if(ArrayHolderType::value != nullptr) { return std::make_pair(std::begin(ArrayHolderType::value), std::end(ArrayHolderType::value)); } else { std::pair<const typename ArrayHolderType::type*, const typename ArrayHolderType::type*> out(nullptr, nullptr); return out; } } template <class ArrayHolderType> std::size_t array_size(ArrayHolderType) { if(ArrayHolderType::value == nullptr) { return 0; } else { return std::extent<decltype(ArrayHolderType::value)>::value; } } template <class ValueType, class TypeInfoArrayHolder> std::vector<std::vector<ValueType>> buckets_by_index(const std::pair<const ValueType*, const ValueType*>& range, TypeInfoArrayHolder) { if(range.first != nullptr && range.second != nullptr) { std::vector<std::vector<ValueType>> out( array_size(TypeInfoArrayHolder())); std::for_each(range.first, range.second, [&out](const auto& info) { out[info.type_index].push_back(info); }); return out; } else { return std::vector<std::vector<ValueType>>(); } } #pragma clang diagnostic pop type type_by_index(std::size_t index) const { return type(type_info_range_.first + index, this); } public: //////////////////////////////////////////////////////////////////////////// // main api interface for interacting with the reflection system std::pair<const_type_iterator, const_type_iterator> types() const { return std::make_pair( const_type_iterator(type_info_range_.first, this), const_type_iterator(type_info_range_.second, this)); } std::pair<const_constructor_iterator, const_constructor_iterator> constructors() const { return std::make_pair( const_constructor_iterator(constructor_info_range_.first, this), const_constructor_iterator(constructor_info_range_.second, this)); } private: // pairs hold iterators to beginning and end of arrays of information // generated at compile time std::pair<const type_info*, const type_info*> type_info_range_; std::pair<const constructor_info*, const constructor_info*> constructor_info_range_; std::pair<const conversion_info*, const conversion_info*> conversion_info_range_; std::pair<const string_serialization_info*, const string_serialization_info*> string_serialization_info_range_; std::pair<const free_function_info*, const free_function_info*> free_function_info_range_; std::pair<const member_function_info*, const member_function_info*> member_function_info_range_; std::pair<const member_variable_info*, const member_variable_info*> member_variable_info_range_; std::vector<std::vector<constructor_info>> constructor_info_by_index_; }; } namespace std { // specialize std::iterator_traits for info_iterator_ template <class InfoType, class ProxyType> struct std::iterator_traits<shadow::info_iterator_<InfoType, ProxyType>> { typedef typename shadow::info_iterator_<InfoType, ProxyType>::value_type value_type; typedef typename shadow::info_iterator_<InfoType, ProxyType>::difference_type difference_type; typedef typename shadow::info_iterator_<InfoType, ProxyType>::reference reference; typedef typename shadow::info_iterator_<InfoType, ProxyType>::pointer pointer; typedef typename shadow::info_iterator_<InfoType, ProxyType>::iterator_category iterator_category; }; } <|endoftext|>
<commit_before>/* A general purpose stripifier, based on NvTriStrip (http://developer.nvidia.com/) Credit for porting NvTriStrip to Python goes to the RuneBlade Foundation library: http://techgame.net/projects/Runeblade/browser/trunk/RBRapier/RBRapier/Tools/Geometry/Analysis/TriangleStripifier.py?rev=760 The algorithm of this stripifier is an improved version of the RuneBlade Foundation / NVidia stripifier; it makes no assumptions about the underlying geometry whatsoever and is intended to produce valid output in all circumstances. */ /* Copyright (c) 2007-2009, Python File Format Interface All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Python File Format Interface project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 <cassert> #include <deque> #include <list> #include <set> #include <boost/foreach.hpp> #include "trianglemesh.hpp" //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ class TriangleStrip { public: //Heavily adapted from NvTriStrip. //Original can be found at http://developer.nvidia.com/view.asp?IO=nvtristrip_library. // List of faces (implementation note: this is a deque and not // a vector because we need push_front). std::deque<MFacePtr> faces; //! Identical to faces, but written as a strip (whose winding //! determined by reversed). std::deque<int> vertices; //! Winding of strip: false means that strip can be used as //! such, true means that winding is reversed. Winding can be //! reversed by appending a duplicate vertex to the front, or //! if the strip has odd length, by reversing the strip. bool reversed; //! Identifier of the experiment (= collection of strips), if //! this strip is part of an experiment. Note that a strip is //! part of an experiment until commit is called. int experiment_id; //! Identifier of the strip. int strip_id; //! Number of strips declared. Used to determine next strip id. static int NUM_STRIPS; // Initialized to zero in cpp file. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~ Public Methods //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ TriangleStrip(int _experiment_id); //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~ Element Membership Tests //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //! Is the face marked in this strip? bool is_face_marked(MFacePtr face); //! Mark face in this strip. void mark_face(MFacePtr face); //! Get unmarked adjacent face. MFacePtr get_unmarked_adjacent_face(MFacePtr face, int vi); //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //! Building face traversal list starting from the start_face and //! the edge opposite start_vertex. void traverse_faces(int start_vertex, MFacePtr start_face, bool forward); //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //! Builds the face strip forwards, then backwards, and returns //! the joined list. void build(int start_vertex, MFacePtr start_face); //! Tag strip, and its faces, as non-experimental. void commit(); //! Get strip (always in forward winding). std::deque<int> get_strip(); }; typedef boost::shared_ptr<TriangleStrip> TriangleStripPtr; //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~ Experiment //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //! An experiment is a collection of adjacent strips, constructed from //! a single face and start vertex. class Experiment { public: std::list<TriangleStripPtr> strips; int vertex; MFacePtr face; int experiment_id; //! Number of experiments declared. Used to determine next //! experiment id. static int NUM_EXPERIMENTS; // Initialized to zero in cpp file. Experiment(int _vertex, MFacePtr _face); //! Build strips, starting from vertex and face. void build(); //! Build strips adjacent to given strip, and add them to the //! experiment. This is a helper function used by build. void build_adjacent(TriangleStripPtr strip); }; typedef boost::shared_ptr<Experiment> ExperimentPtr; //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~ ExperimentSelector //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ class ExperimentSelector { public: //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~ Constants / Variables / Etc. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ int num_samples; float strip_len_heuristic; int min_strip_length; float best_score; ExperimentPtr best_sample; // XXX rename to best_experiment? //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~ Definitions //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ExperimentSelector(int _num_samples, int _min_strip_length); //! Updates best experiment with given experiment, if given //! experiment beats current experiment. void update_score(ExperimentPtr experiment); //! Remove best experiment, to start a fresh sequence of //! experiments. void clear(); }; //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~ TriangleStripifier //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //Heavily adapted from NvTriStrip. //Origional can be found at http://developer.nvidia.com/view.asp?IO=nvtristrip_library. class TriangleStripifier { public: //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~ Constants / Variables / Etc. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ExperimentSelector selector; MeshPtr mesh; std::vector<MFacePtr>::const_iterator start_face_iter; //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~ Public Methods //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ TriangleStripifier(MeshPtr _mesh); //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~ Protected Methods //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //! Find a good face to start stripification, potentially //! after some strips have already been created. Result is //! stored in start_face_iter. Will store mesh->faces.end() //! when no more faces are left. bool find_good_reset_point(); //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //! Find all strips. std::list<TriangleStripPtr> find_all_strips(); }; <commit_msg>Doc fix.<commit_after>/* A general purpose stripifier, based on NvTriStrip (http://developer.nvidia.com/) Credit for porting NvTriStrip to Python goes to the RuneBlade Foundation library: http://techgame.net/projects/Runeblade/browser/trunk/RBRapier/RBRapier/Tools/Geometry/Analysis/TriangleStripifier.py?rev=760 The algorithm of this stripifier is an improved version of the RuneBlade Foundation / NVidia stripifier; it makes no assumptions about the underlying geometry whatsoever and is intended to produce valid output in all circumstances. */ /* Copyright (c) 2007-2009, Python File Format Interface All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Python File Format Interface project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 <cassert> #include <deque> #include <list> #include <set> #include <boost/foreach.hpp> #include "trianglemesh.hpp" //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ class TriangleStrip { public: //Heavily adapted from NvTriStrip. //Original can be found at http://developer.nvidia.com/view.asp?IO=nvtristrip_library. // List of faces (implementation note: this is a deque and not // a vector because we need push_front). std::deque<MFacePtr> faces; //! Identical to faces, but written as a strip (whose winding //! determined by reversed). std::deque<int> vertices; //! Winding of strip: false means that strip can be used as //! such, true means that winding is reversed. Winding can be //! reversed by appending a duplicate vertex to the front, or //! if the strip has odd length, by reversing the strip. bool reversed; //! Identifier of the experiment (= collection of strips), if //! this strip is part of an experiment. Note that a strip is //! part of an experiment until commit is called. int experiment_id; //! Identifier of the strip. int strip_id; //! Number of strips declared. Used to determine next strip id. static int NUM_STRIPS; // Initialized to zero in cpp file. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~ Public Methods //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ TriangleStrip(int _experiment_id); //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~ Element Membership Tests //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //! Is the face marked in this strip? bool is_face_marked(MFacePtr face); //! Mark face in this strip. void mark_face(MFacePtr face); //! Get unmarked adjacent face. MFacePtr get_unmarked_adjacent_face(MFacePtr face, int vi); //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //! Building face traversal list starting from the start_face and //! the edge opposite start_vertex. void traverse_faces(int start_vertex, MFacePtr start_face, bool forward); //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //! Builds the face strip forwards, then backwards. void build(int start_vertex, MFacePtr start_face); //! Tag strip, and its faces, as non-experimental. void commit(); //! Get strip (always in forward winding). std::deque<int> get_strip(); }; typedef boost::shared_ptr<TriangleStrip> TriangleStripPtr; //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~ Experiment //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //! An experiment is a collection of adjacent strips, constructed from //! a single face and start vertex. class Experiment { public: std::list<TriangleStripPtr> strips; int vertex; MFacePtr face; int experiment_id; //! Number of experiments declared. Used to determine next //! experiment id. static int NUM_EXPERIMENTS; // Initialized to zero in cpp file. Experiment(int _vertex, MFacePtr _face); //! Build strips, starting from vertex and face. void build(); //! Build strips adjacent to given strip, and add them to the //! experiment. This is a helper function used by build. void build_adjacent(TriangleStripPtr strip); }; typedef boost::shared_ptr<Experiment> ExperimentPtr; //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~ ExperimentSelector //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ class ExperimentSelector { public: //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~ Constants / Variables / Etc. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ int num_samples; float strip_len_heuristic; int min_strip_length; float best_score; ExperimentPtr best_sample; // XXX rename to best_experiment? //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~ Definitions //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ExperimentSelector(int _num_samples, int _min_strip_length); //! Updates best experiment with given experiment, if given //! experiment beats current experiment. void update_score(ExperimentPtr experiment); //! Remove best experiment, to start a fresh sequence of //! experiments. void clear(); }; //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~ TriangleStripifier //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //Heavily adapted from NvTriStrip. //Origional can be found at http://developer.nvidia.com/view.asp?IO=nvtristrip_library. class TriangleStripifier { public: //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~ Constants / Variables / Etc. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ExperimentSelector selector; MeshPtr mesh; std::vector<MFacePtr>::const_iterator start_face_iter; //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~ Public Methods //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ TriangleStripifier(MeshPtr _mesh); //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~ Protected Methods //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //! Find a good face to start stripification, potentially //! after some strips have already been created. Result is //! stored in start_face_iter. Will store mesh->faces.end() //! when no more faces are left. bool find_good_reset_point(); //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //! Find all strips. std::list<TriangleStripPtr> find_all_strips(); }; <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/browser.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profile.h" #include "chrome/common/pref_names.h" #if defined(OS_MACOSX) // Tabs appears to timeout, or maybe crash on mac. // http://crbug.com/53779 #define MAYBE_Tabs FAILS_Tabs #elif defined(OS_WIN) // It's flaky on win. // http://crbug.com/58269 #define MAYBE_Tabs FLAKY_Tabs #else #define MAYBE_Tabs Tabs #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Tabs) { ASSERT_TRUE(test_server()->Start()); // The test creates a tab and checks that the URL of the new tab // is that of the new tab page. Make sure the pref that controls // this is set. browser()->profile()->GetPrefs()->SetBoolean( prefs::kHomePageIsNewTabPage, true); ASSERT_TRUE(RunExtensionTest("tabs/basics")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabGetCurrent) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionTest("tabs/get_current")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabConnect) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionTest("tabs/connect")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabOnRemoved) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionTest("tabs/on_removed")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CaptureVisibleTabJpeg) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_jpeg.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CaptureVisibleTabPng) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_png.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabsOnUpdated) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionTest("tabs/on_updated")) << message_; } <commit_msg>Enable ExtensionApiTest.Tabs on Mac and remove FLAKY prefix from Win.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/browser.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profile.h" #include "chrome/common/pref_names.h" IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Tabs) { ASSERT_TRUE(test_server()->Start()); // The test creates a tab and checks that the URL of the new tab // is that of the new tab page. Make sure the pref that controls // this is set. browser()->profile()->GetPrefs()->SetBoolean( prefs::kHomePageIsNewTabPage, true); ASSERT_TRUE(RunExtensionTest("tabs/basics")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabGetCurrent) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionTest("tabs/get_current")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabConnect) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionTest("tabs/connect")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabOnRemoved) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionTest("tabs/on_removed")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CaptureVisibleTabJpeg) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_jpeg.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CaptureVisibleTabPng) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_png.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabsOnUpdated) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionTest("tabs/on_updated")) << message_; } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/webui/sync_promo/sync_promo_ui.h" #include "base/command_line.h" #include "base/utf_string_conversions.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/first_run/first_run.h" #include "chrome/browser/google/google_util.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/sync/profile_sync_service.h" #include "chrome/browser/ui/webui/chrome_url_data_manager.h" #include "chrome/browser/ui/webui/chrome_web_ui_data_source.h" #include "chrome/browser/ui/webui/options/core_options_handler.h" #include "chrome/browser/ui/webui/sync_promo/sync_promo_handler.h" #include "chrome/browser/ui/webui/sync_promo/sync_promo_trial.h" #include "chrome/browser/ui/webui/theme_source.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h" #include "content/browser/tab_contents/tab_contents.h" #include "googleurl/src/url_util.h" #include "grit/browser_resources.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "ui/base/l10n/l10n_util.h" namespace { const char kStringsJsFile[] = "strings.js"; const char kSyncPromoJsFile[] = "sync_promo.js"; const char kSyncPromoQueryKeyIsLaunchPage[] = "is_launch_page"; const char kSyncPromoQueryKeyNextPage[] = "next_page"; // The maximum number of times we want to show the sync promo at startup. const int kSyncPromoShowAtStartupMaximum = 10; // Checks we want to show the sync promo for the given brand. bool AllowPromoAtStartupForCurrentBrand() { std::string brand; google_util::GetBrand(&brand); if (brand.empty()) return true; if (google_util::IsInternetCafeBrandCode(brand)) return false; if (google_util::IsOrganic(brand)) return true; if (StartsWithASCII(brand, "CH", true)) return true; // Default to disallow for all other brand codes. return false; } // The Web UI data source for the sync promo page. class SyncPromoUIHTMLSource : public ChromeWebUIDataSource { public: explicit SyncPromoUIHTMLSource(WebUI* web_ui); private: ~SyncPromoUIHTMLSource() {} DISALLOW_COPY_AND_ASSIGN(SyncPromoUIHTMLSource); }; SyncPromoUIHTMLSource::SyncPromoUIHTMLSource(WebUI* web_ui) : ChromeWebUIDataSource(chrome::kChromeUISyncPromoHost) { DictionaryValue localized_strings; CoreOptionsHandler::GetStaticLocalizedValues(&localized_strings); SyncSetupHandler::GetStaticLocalizedValues(&localized_strings, web_ui); AddLocalizedStrings(localized_strings); } // Looks for |search_key| in the query portion of |url|. Returns true if the // key is found and sets |out_value| to the value for the key. Returns false if // the key is not found. bool GetValueForKeyInQuery(const GURL& url, const std::string& search_key, std::string* out_value) { url_parse::Component query = url.parsed_for_possibly_invalid_spec().query; url_parse::Component key, value; while (url_parse::ExtractQueryKeyValue( url.spec().c_str(), &query, &key, &value)) { if (key.is_nonempty()) { std::string key_string = url.spec().substr(key.begin, key.len); if (key_string == search_key) { if (value.is_nonempty()) *out_value = url.spec().substr(value.begin, value.len); else *out_value = ""; return true; } } } return false; } } // namespace SyncPromoUI::SyncPromoUI(TabContents* contents) : ChromeWebUI(contents) { should_hide_url_ = true; SyncPromoHandler* handler = new SyncPromoHandler( g_browser_process->profile_manager()); AddMessageHandler(handler); handler->Attach(this); // Set up the chrome://theme/ source. Profile* profile = Profile::FromBrowserContext(contents->GetBrowserContext()); ThemeSource* theme = new ThemeSource(profile); profile->GetChromeURLDataManager()->AddDataSource(theme); // Set up the sync promo source. SyncPromoUIHTMLSource* html_source = new SyncPromoUIHTMLSource(this); html_source->set_json_path(kStringsJsFile); html_source->add_resource_path(kSyncPromoJsFile, IDR_SYNC_PROMO_JS); html_source->set_default_resource(IDR_SYNC_PROMO_HTML); profile->GetChromeURLDataManager()->AddDataSource(html_source); if (sync_promo_trial::IsPartOfBrandTrialToEnable()) { bool is_start_up = GetIsLaunchPageForSyncPromoURL(contents->GetURL()); sync_promo_trial::RecordUserShownPromoWithTrialBrand(is_start_up, profile); } } // static bool SyncPromoUI::HasShownPromoAtStartup(Profile* profile) { return profile->GetPrefs()->HasPrefPath(prefs::kSyncPromoStartupCount); } // static bool SyncPromoUI::ShouldShowSyncPromo(Profile* profile) { #if defined(OS_CHROMEOS) // There's no need to show the sync promo on cros since cros users are logged // into sync already. return false; #endif // Honor the sync policies. if (!profile->GetOriginalProfile()->IsSyncAccessible()) return false; // If the user is already signed into sync then don't show the promo. ProfileSyncService* service = profile->GetOriginalProfile()->GetProfileSyncService(); if (!service || service->HasSyncSetupCompleted()) return false; // Default to allow the promo. return true; } // static void SyncPromoUI::RegisterUserPrefs(PrefService* prefs) { prefs->RegisterIntegerPref( prefs::kSyncPromoStartupCount, 0, PrefService::UNSYNCABLE_PREF); prefs->RegisterBooleanPref( prefs::kSyncPromoUserSkipped, false, PrefService::UNSYNCABLE_PREF); prefs->RegisterBooleanPref(prefs::kSyncPromoShowOnFirstRunAllowed, true, PrefService::UNSYNCABLE_PREF); SyncPromoHandler::RegisterUserPrefs(prefs); } // static bool SyncPromoUI::ShouldShowSyncPromoAtStartup(Profile* profile, bool is_new_profile) { DCHECK(profile); if (!ShouldShowSyncPromo(profile)) return false; const CommandLine& command_line = *CommandLine::ForCurrentProcess(); if (command_line.HasSwitch(switches::kNoFirstRun)) is_new_profile = false; if (!is_new_profile) { if (!HasShownPromoAtStartup(profile)) return false; } if (HasUserSkippedSyncPromo(profile)) return false; // For Chinese users skip the sync promo. if (g_browser_process->GetApplicationLocale() == "zh-CN") return false; PrefService *prefs = profile->GetPrefs(); int show_count = prefs->GetInteger(prefs::kSyncPromoStartupCount); if (show_count >= kSyncPromoShowAtStartupMaximum) return false; // If the current install has a brand code that's part of an experiment, honor // that before master prefs. if (sync_promo_trial::IsPartOfBrandTrialToEnable()) return sync_promo_trial::ShouldShowAtStartupBasedOnBrand(); // This pref can be set in the master preferences file to allow or disallow // showing the sync promo at startup. if (prefs->HasPrefPath(prefs::kSyncPromoShowOnFirstRunAllowed)) return prefs->GetBoolean(prefs::kSyncPromoShowOnFirstRunAllowed); // For now don't show the promo for some brands. if (!AllowPromoAtStartupForCurrentBrand()) return false; // Default to show the promo. return true; } void SyncPromoUI::DidShowSyncPromoAtStartup(Profile* profile) { int show_count = profile->GetPrefs()->GetInteger( prefs::kSyncPromoStartupCount); show_count++; profile->GetPrefs()->SetInteger(prefs::kSyncPromoStartupCount, show_count); } bool SyncPromoUI::HasUserSkippedSyncPromo(Profile* profile) { return profile->GetPrefs()->GetBoolean(prefs::kSyncPromoUserSkipped); } void SyncPromoUI::SetUserSkippedSyncPromo(Profile* profile) { profile->GetPrefs()->SetBoolean(prefs::kSyncPromoUserSkipped, true); } // static GURL SyncPromoUI::GetSyncPromoURL(const GURL& next_page, bool show_title) { std::stringstream stream; stream << chrome::kChromeUISyncPromoURL << "?" << kSyncPromoQueryKeyIsLaunchPage << "=" << (show_title ? "true" : "false"); if (!next_page.spec().empty()) { url_canon::RawCanonOutputT<char> output; url_util::EncodeURIComponent( next_page.spec().c_str(), next_page.spec().length(), &output); std::string escaped_spec(output.data(), output.length()); stream << "&" << kSyncPromoQueryKeyNextPage << "=" << escaped_spec; } return GURL(stream.str()); } // static bool SyncPromoUI::GetIsLaunchPageForSyncPromoURL(const GURL& url) { std::string value; // Show the title if the promo is currently the Chrome launch page (and not // the page accessed through the NTP). if (GetValueForKeyInQuery(url, kSyncPromoQueryKeyIsLaunchPage, &value)) return value == "true"; return false; } // static GURL SyncPromoUI::GetNextPageURLForSyncPromoURL(const GURL& url) { std::string value; if (GetValueForKeyInQuery(url, kSyncPromoQueryKeyNextPage, &value)) { url_canon::RawCanonOutputT<char16> output; url_util::DecodeURLEscapeSequences(value.c_str(), value.length(), &output); std::string url; UTF16ToUTF8(output.data(), output.length(), &url); return GURL(url); } return GURL(); } // static bool SyncPromoUI::UserHasSeenSyncPromoAtStartup(Profile* profile) { return profile->GetPrefs()->GetInteger(prefs::kSyncPromoStartupCount) > 0; } <commit_msg>[Sync Promo UI] Fix lint errors.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/webui/sync_promo/sync_promo_ui.h" #include "base/command_line.h" #include "base/utf_string_conversions.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/first_run/first_run.h" #include "chrome/browser/google/google_util.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/sync/profile_sync_service.h" #include "chrome/browser/ui/webui/chrome_url_data_manager.h" #include "chrome/browser/ui/webui/chrome_web_ui_data_source.h" #include "chrome/browser/ui/webui/options/core_options_handler.h" #include "chrome/browser/ui/webui/sync_promo/sync_promo_handler.h" #include "chrome/browser/ui/webui/sync_promo/sync_promo_trial.h" #include "chrome/browser/ui/webui/theme_source.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h" #include "content/browser/tab_contents/tab_contents.h" #include "googleurl/src/url_util.h" #include "grit/browser_resources.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "ui/base/l10n/l10n_util.h" namespace { const char kStringsJsFile[] = "strings.js"; const char kSyncPromoJsFile[] = "sync_promo.js"; const char kSyncPromoQueryKeyIsLaunchPage[] = "is_launch_page"; const char kSyncPromoQueryKeyNextPage[] = "next_page"; // The maximum number of times we want to show the sync promo at startup. const int kSyncPromoShowAtStartupMaximum = 10; // Checks we want to show the sync promo for the given brand. bool AllowPromoAtStartupForCurrentBrand() { std::string brand; google_util::GetBrand(&brand); if (brand.empty()) return true; if (google_util::IsInternetCafeBrandCode(brand)) return false; if (google_util::IsOrganic(brand)) return true; if (StartsWithASCII(brand, "CH", true)) return true; // Default to disallow for all other brand codes. return false; } // The Web UI data source for the sync promo page. class SyncPromoUIHTMLSource : public ChromeWebUIDataSource { public: explicit SyncPromoUIHTMLSource(WebUI* web_ui); private: ~SyncPromoUIHTMLSource() {} DISALLOW_COPY_AND_ASSIGN(SyncPromoUIHTMLSource); }; SyncPromoUIHTMLSource::SyncPromoUIHTMLSource(WebUI* web_ui) : ChromeWebUIDataSource(chrome::kChromeUISyncPromoHost) { DictionaryValue localized_strings; CoreOptionsHandler::GetStaticLocalizedValues(&localized_strings); SyncSetupHandler::GetStaticLocalizedValues(&localized_strings, web_ui); AddLocalizedStrings(localized_strings); } // Looks for |search_key| in the query portion of |url|. Returns true if the // key is found and sets |out_value| to the value for the key. Returns false if // the key is not found. bool GetValueForKeyInQuery(const GURL& url, const std::string& search_key, std::string* out_value) { url_parse::Component query = url.parsed_for_possibly_invalid_spec().query; url_parse::Component key, value; while (url_parse::ExtractQueryKeyValue( url.spec().c_str(), &query, &key, &value)) { if (key.is_nonempty()) { std::string key_string = url.spec().substr(key.begin, key.len); if (key_string == search_key) { if (value.is_nonempty()) *out_value = url.spec().substr(value.begin, value.len); else *out_value = ""; return true; } } } return false; } } // namespace SyncPromoUI::SyncPromoUI(TabContents* contents) : ChromeWebUI(contents) { should_hide_url_ = true; SyncPromoHandler* handler = new SyncPromoHandler( g_browser_process->profile_manager()); AddMessageHandler(handler); handler->Attach(this); // Set up the chrome://theme/ source. Profile* profile = Profile::FromBrowserContext(contents->GetBrowserContext()); ThemeSource* theme = new ThemeSource(profile); profile->GetChromeURLDataManager()->AddDataSource(theme); // Set up the sync promo source. SyncPromoUIHTMLSource* html_source = new SyncPromoUIHTMLSource(this); html_source->set_json_path(kStringsJsFile); html_source->add_resource_path(kSyncPromoJsFile, IDR_SYNC_PROMO_JS); html_source->set_default_resource(IDR_SYNC_PROMO_HTML); profile->GetChromeURLDataManager()->AddDataSource(html_source); if (sync_promo_trial::IsPartOfBrandTrialToEnable()) { bool is_start_up = GetIsLaunchPageForSyncPromoURL(contents->GetURL()); sync_promo_trial::RecordUserShownPromoWithTrialBrand(is_start_up, profile); } } // static bool SyncPromoUI::HasShownPromoAtStartup(Profile* profile) { return profile->GetPrefs()->HasPrefPath(prefs::kSyncPromoStartupCount); } // static bool SyncPromoUI::ShouldShowSyncPromo(Profile* profile) { #if defined(OS_CHROMEOS) // There's no need to show the sync promo on cros since cros users are logged // into sync already. return false; #endif // Honor the sync policies. if (!profile->GetOriginalProfile()->IsSyncAccessible()) return false; // If the user is already signed into sync then don't show the promo. ProfileSyncService* service = profile->GetOriginalProfile()->GetProfileSyncService(); if (!service || service->HasSyncSetupCompleted()) return false; // Default to allow the promo. return true; } // static void SyncPromoUI::RegisterUserPrefs(PrefService* prefs) { prefs->RegisterIntegerPref( prefs::kSyncPromoStartupCount, 0, PrefService::UNSYNCABLE_PREF); prefs->RegisterBooleanPref( prefs::kSyncPromoUserSkipped, false, PrefService::UNSYNCABLE_PREF); prefs->RegisterBooleanPref(prefs::kSyncPromoShowOnFirstRunAllowed, true, PrefService::UNSYNCABLE_PREF); SyncPromoHandler::RegisterUserPrefs(prefs); } // static bool SyncPromoUI::ShouldShowSyncPromoAtStartup(Profile* profile, bool is_new_profile) { DCHECK(profile); if (!ShouldShowSyncPromo(profile)) return false; const CommandLine& command_line = *CommandLine::ForCurrentProcess(); if (command_line.HasSwitch(switches::kNoFirstRun)) is_new_profile = false; if (!is_new_profile) { if (!HasShownPromoAtStartup(profile)) return false; } if (HasUserSkippedSyncPromo(profile)) return false; // For Chinese users skip the sync promo. if (g_browser_process->GetApplicationLocale() == "zh-CN") return false; PrefService* prefs = profile->GetPrefs(); int show_count = prefs->GetInteger(prefs::kSyncPromoStartupCount); if (show_count >= kSyncPromoShowAtStartupMaximum) return false; // If the current install has a brand code that's part of an experiment, honor // that before master prefs. if (sync_promo_trial::IsPartOfBrandTrialToEnable()) return sync_promo_trial::ShouldShowAtStartupBasedOnBrand(); // This pref can be set in the master preferences file to allow or disallow // showing the sync promo at startup. if (prefs->HasPrefPath(prefs::kSyncPromoShowOnFirstRunAllowed)) return prefs->GetBoolean(prefs::kSyncPromoShowOnFirstRunAllowed); // For now don't show the promo for some brands. if (!AllowPromoAtStartupForCurrentBrand()) return false; // Default to show the promo. return true; } void SyncPromoUI::DidShowSyncPromoAtStartup(Profile* profile) { int show_count = profile->GetPrefs()->GetInteger( prefs::kSyncPromoStartupCount); show_count++; profile->GetPrefs()->SetInteger(prefs::kSyncPromoStartupCount, show_count); } bool SyncPromoUI::HasUserSkippedSyncPromo(Profile* profile) { return profile->GetPrefs()->GetBoolean(prefs::kSyncPromoUserSkipped); } void SyncPromoUI::SetUserSkippedSyncPromo(Profile* profile) { profile->GetPrefs()->SetBoolean(prefs::kSyncPromoUserSkipped, true); } // static GURL SyncPromoUI::GetSyncPromoURL(const GURL& next_page, bool show_title) { std::stringstream stream; stream << chrome::kChromeUISyncPromoURL << "?" << kSyncPromoQueryKeyIsLaunchPage << "=" << (show_title ? "true" : "false"); if (!next_page.spec().empty()) { url_canon::RawCanonOutputT<char> output; url_util::EncodeURIComponent( next_page.spec().c_str(), next_page.spec().length(), &output); std::string escaped_spec(output.data(), output.length()); stream << "&" << kSyncPromoQueryKeyNextPage << "=" << escaped_spec; } return GURL(stream.str()); } // static bool SyncPromoUI::GetIsLaunchPageForSyncPromoURL(const GURL& url) { std::string value; // Show the title if the promo is currently the Chrome launch page (and not // the page accessed through the NTP). if (GetValueForKeyInQuery(url, kSyncPromoQueryKeyIsLaunchPage, &value)) return value == "true"; return false; } // static GURL SyncPromoUI::GetNextPageURLForSyncPromoURL(const GURL& url) { std::string value; if (GetValueForKeyInQuery(url, kSyncPromoQueryKeyNextPage, &value)) { url_canon::RawCanonOutputT<char16> output; url_util::DecodeURLEscapeSequences(value.c_str(), value.length(), &output); std::string url; UTF16ToUTF8(output.data(), output.length(), &url); return GURL(url); } return GURL(); } // static bool SyncPromoUI::UserHasSeenSyncPromoAtStartup(Profile* profile) { return profile->GetPrefs()->GetInteger(prefs::kSyncPromoStartupCount) > 0; } <|endoftext|>
<commit_before><commit_msg>Modifies the toast to append "--system-level" if a system-level install is attempting to relaunch setup.<commit_after><|endoftext|>
<commit_before><commit_msg>Adding ..\ClientState\<ChromeGuid>\client key to the uninstall metrics for Google Chrome build.<commit_after><|endoftext|>
<commit_before>#include "omp.h" inline kth_cv_omp::kth_cv_omp(const std::string in_path, const std::string in_actionNames, const field<std::string> in_all_people, const int in_scale_factor, const int in_shift, const int in_scene, //only for kth const int in_segment_length, const int in_dim ):path(in_path), actionNames(in_actionNames), all_people (in_all_people), scale_factor(in_scale_factor), shift(in_shift), total_scenes(in_scene), segment_length(in_segment_length), dim(in_dim) { actions.load( actionNames ); } // Log-Euclidean Distance inline void kth_cv_omp::logEucl() { int n_actions = actions.n_rows; int n_peo = all_people.n_rows; //No hacer acc aqui. Hacerlo al final final. Cuando tengas todos los real_labels and est_labels float acc; acc = 0; //int n_test = n_peo*n_actions*total_scenes - 1; // - person13_handclapping_d3 int n_test = n_peo*n_actions*total_scenes; // - person13_handclapping_d3 vec real_labels; vec est_labels; field<std::string> test_video_list(n_test); real_labels.zeros(n_test); est_labels.zeros(n_test); int k=0; int sc = 1; // = total scenes for (int pe = 0; pe< n_peo; ++pe) { for (int act=0; act<n_actions; ++act) { //load number of segments vec total_seg; int num_s; std::stringstream load_sub_path; std::stringstream load_num_seg; load_sub_path << path << "/kth-cov-mat/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ; load_num_seg << load_sub_path.str() << "/num_seg_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".dat"; total_seg.load( load_num_seg.str()); num_s = total_seg(0); uvec est_lab_segm; est_lab_segm.zeros(num_s); vec count = zeros<vec>( n_actions ); // Esto es lo que deberia hacerse en paralelo?? Piensa Piensa piensa #pragma omp parallel for for (int s=0; s<num_s; ++s) { std::stringstream load_cov_seg; load_cov_seg << load_sub_path.str() << "/LogMcov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5"; //cout << "LogMcov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5" << endl; //debe devolver el est_labe de ese segmento est_lab_segm(s) = logEucl_one_seg_est_lab( pe, load_sub_path.str(), load_cov_seg.str()); count( est_lab_segm(s) )++; //getchar(); } //cout << "s: " << s << endl; uword index_video; double max_val = count.max(index_video); //est_lab_segm.t().print("est_lab_segm"); cout << "This video is " << actions(act) << " and was classified as class: " << actions(index_video ) << endl; real_labels(k) = act; est_labels(k) = index_video; test_video_list(k) = load_sub_path.str(); real_labels.save("Log_Eucl_real_labels.dat", raw_ascii); est_labels.save("Log_Eucl_est_labels.dat", raw_ascii); test_video_list.save("Log_Eucl_test_video_list.dat", raw_ascii); k++; if (index_video == act) { acc++; } //getchar(); } } cout << "Performance: " << acc*100/n_test << " %" << endl; } inline uword kth_cv_omp::logEucl_one_seg_est_lab(int pe_test, std::string load_sub_path, std::string segm_name) { //wall_clock timer; //timer.tic(); mat logMtest_cov; logMtest_cov.load(segm_name); int n_actions = actions.n_rows; int n_peo = all_people.n_rows; double dist, tmp_dist; tmp_dist = datum::inf; double est_lab; //cout << "Comparing with person "; for (int pe_tr = 0; pe_tr< n_peo; ++pe_tr) { if (pe_tr!= pe_test) { //cout << " " << all_people (pe_tr); for (int sc = 1; sc<=total_scenes; ++sc) //scene { for (int act=0; act<n_actions; ++act) { vec total_seg; int num_s; std::stringstream load_num_seg; load_num_seg << load_sub_path << "/num_seg_"<< all_people (pe_tr) << "_" << actions(act) << "_dim" << dim << ".dat"; total_seg.load( load_num_seg.str()); num_s = total_seg(0); for (int s_tr=0; s_tr<num_s; ++s_tr) { std::stringstream load_cov_seg_tr; load_cov_seg_tr << load_sub_path << "/LogMcov_seg" << s_tr << "_" << all_people (pe_tr) << "_" << actions(act) << "_dim" << dim << ".h5"; //cout << "Comparing with cov_seg" << s_tr << "_"<< all_people (pe_tr) << "_" << actions(act) << "_dim" << dim << ".h5" << endl; mat logMtrain_cov; logMtrain_cov.load( load_cov_seg_tr.str() ); //logMtest_cov.print("logMtest_cov"); //train_cov.print("train_cov"); dist = norm( logMtest_cov - logMtrain_cov, "fro"); //cout << "dist " << dist << endl; ///crear un vec aca y guardar todas las distancias if (dist < tmp_dist) { //cout << "Es menor" << endl; tmp_dist = dist; est_lab = act; } //cout << "Press a key" << endl; //getchar(); } } } } } //double n = timer.toc(); //cout << "number of seconds: " << n << endl; //cout << " est_lab "<< est_lab << endl << endl; //getchar(); return est_lab; } //DO IT // Stein Divergence inline void kth_cv_omp::SteinDiv() { int n_actions = actions.n_rows; int n_peo = all_people.n_rows; float acc; acc = 0; int n_test = n_peo*n_actions*total_scenes - 1; // - person13_handclapping_d3 vec real_labels; vec est_labels; field<std::string> test_video_list(n_test); real_labels.zeros(n_test); est_labels.zeros(n_test); int k=0; for (int sc = 1; sc<=total_scenes; ++sc) //scene { for (int pe = 0; pe< n_peo; ++pe) { for (int act=0; act<n_actions; ++act) { if( !( ( sc==3 && pe==12) && act==1) ) //person13_handclapping_d3 { //load number of segments vec total_seg; int num_s; std::stringstream load_sub_path; std::stringstream load_num_seg; load_sub_path << path << "/kth-cov-mat/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ; load_num_seg << load_sub_path.str() << "/num_seg_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".dat"; total_seg.load( load_num_seg.str()); num_s = total_seg(0); uvec est_lab_segm; est_lab_segm.zeros(num_s); vec count = zeros<vec>( n_actions ); for (int s=0; s<num_s; ++s) { std::stringstream load_cov_seg; load_cov_seg << load_sub_path.str() << "/cov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5"; est_lab_segm(s) = SteinDiv_one_seg_est_lab( pe, load_sub_path.str(), load_cov_seg.str()); count( est_lab_segm(s) )++; //getchar(); } uword index_video; double max_val = count.max(index_video); //est_lab_segm.t().print("est_lab_segm"); cout << "This video is " << actions(act) << " and was classified as class: " << actions(index_video ) << endl; real_labels(k) = act; est_labels(k) = index_video; test_video_list(k) = load_sub_path.str(); real_labels.save("Stein_div_real_labels.dat", raw_ascii); est_labels.save("Stein_div__est_labels.dat", raw_ascii); test_video_list.save("Stein_div_test_video_list.dat", raw_ascii); k++; if (index_video == act) { acc++; } //getchar(); } } } } cout << "Performance: " << acc*100/n_test << " %" << endl; } //DO IT!!!!!!!!! inline uword kth_cv_omp::SteinDiv_one_seg_est_lab(int pe_test, std::string load_sub_path, std::string segm_name) { //wall_clock timer; //timer.tic(); mat test_cov; test_cov.load(segm_name); int n_actions = actions.n_rows; int n_peo = all_people.n_rows; double dist_stein, tmp_dist; tmp_dist = datum::inf; double est_lab; //cout << "Comparing with person "; for (int pe_tr = 0; pe_tr< n_peo; ++pe_tr) { if (pe_tr!= pe_test) { //cout << " " << all_people (pe_tr); for (int sc = 1; sc<=total_scenes; ++sc) //scene { for (int act=0; act<n_actions; ++act) { vec total_seg; int num_s; std::stringstream load_num_seg; load_num_seg << load_sub_path << "/num_seg_"<< all_people (pe_tr) << "_" << actions(act) << "_dim" << dim << ".dat"; total_seg.load( load_num_seg.str()); num_s = total_seg(0); for (int s_tr=0; s_tr<num_s; ++s_tr) { std::stringstream load_cov_seg_tr; load_cov_seg_tr << load_sub_path << "/cov_seg" << s_tr << "_" << all_people (pe_tr) << "_" << actions(act) << "_dim" << dim << ".h5"; mat train_cov; train_cov.load( load_cov_seg_tr.str() ); //Esto vienen de PartI4. No recuerdo mas :( double det_op1 = det( diagmat( (test_cov + train_cov)/2 ) ); double det_op2 = det( diagmat( ( test_cov%train_cov ) ) ); dist_stein = log( det_op1 ) - 0.5*log( det_op2 ) ; //dist_stein = norm( logMtest_cov - logMtrain_cov, "fro"); //cout << "dist " << dist << endl; if (dist_stein < tmp_dist) { //cout << "Es menor" << endl; tmp_dist = dist_stein; est_lab = act; } //cout << "Press a key" << endl; //getchar(); } } } } } //double n = timer.toc(); //cout << "number of seconds: " << n << endl; //cout << " est_lab "<< est_lab << endl << endl; //getchar(); return est_lab; } <commit_msg>Run in parallel. Classification<commit_after>#include "omp.h" inline kth_cv_omp::kth_cv_omp(const std::string in_path, const std::string in_actionNames, const field<std::string> in_all_people, const int in_scale_factor, const int in_shift, const int in_scene, //only for kth const int in_segment_length, const int in_dim ):path(in_path), actionNames(in_actionNames), all_people (in_all_people), scale_factor(in_scale_factor), shift(in_shift), total_scenes(in_scene), segment_length(in_segment_length), dim(in_dim) { actions.load( actionNames ); } // Log-Euclidean Distance inline void kth_cv_omp::logEucl() { int n_actions = actions.n_rows; int n_peo = all_people.n_rows; //No hacer acc aqui. Hacerlo al final final. Cuando tengas todos los real_labels and est_labels float acc; acc = 0; //int n_test = n_peo*n_actions*total_scenes - 1; // - person13_handclapping_d3 int n_test = n_peo*n_actions*total_scenes; // - person13_handclapping_d3 vec real_labels; vec est_labels; field<std::string> test_video_list(n_test); real_labels.zeros(n_test); est_labels.zeros(n_test); int k=0; int sc = 1; // = total scenes for (int pe = 0; pe< n_peo; ++pe) { for (int act=0; act<n_actions; ++act) { //load number of segments vec total_seg; int num_s; std::stringstream load_sub_path; std::stringstream load_num_seg; load_sub_path << path << "/kth-cov-mat_dim" << dim << "/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ; load_num_seg << load_sub_path.str() << "/num_seg_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".dat"; total_seg.load( load_num_seg.str()); num_s = total_seg(0); uvec est_lab_segm; est_lab_segm.zeros(num_s); vec count = zeros<vec>( n_actions ); // Esto es lo que deberia hacerse en paralelo?? Piensa Piensa piensa #pragma omp parallel for for (int s=0; s<num_s; ++s) { std::stringstream load_cov_seg; load_cov_seg << load_sub_path.str() << "/LogMcov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5"; //cout << "LogMcov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5" << endl; //debe devolver el est_labe de ese segmento est_lab_segm(s) = logEucl_one_seg_est_lab( pe, load_sub_path.str(), load_cov_seg.str()); count( est_lab_segm(s) )++; //getchar(); } //cout << "s: " << s << endl; uword index_video; double max_val = count.max(index_video); //est_lab_segm.t().print("est_lab_segm"); cout << "This video is " << actions(act) << " and was classified as class: " << actions(index_video ) << endl; real_labels(k) = act; est_labels(k) = index_video; test_video_list(k) = load_sub_path.str(); real_labels.save("Log_Eucl_real_labels.dat", raw_ascii); est_labels.save("Log_Eucl_est_labels.dat", raw_ascii); test_video_list.save("Log_Eucl_test_video_list.dat", raw_ascii); k++; if (index_video == act) { acc++; } //getchar(); } } cout << "Performance: " << acc*100/n_test << " %" << endl; } inline uword kth_cv_omp::logEucl_one_seg_est_lab(int pe_test, std::string load_sub_path, std::string segm_name) { //wall_clock timer; //timer.tic(); mat logMtest_cov; logMtest_cov.load(segm_name); int n_actions = actions.n_rows; int n_peo = all_people.n_rows; double dist, tmp_dist; tmp_dist = datum::inf; double est_lab; //cout << "Comparing with person "; for (int pe_tr = 0; pe_tr< n_peo; ++pe_tr) { if (pe_tr!= pe_test) { //cout << " " << all_people (pe_tr); for (int sc = 1; sc<=total_scenes; ++sc) //scene { for (int act=0; act<n_actions; ++act) { vec total_seg; int num_s; std::stringstream load_num_seg; load_num_seg << load_sub_path << "/num_seg_"<< all_people (pe_tr) << "_" << actions(act) << "_dim" << dim << ".dat"; total_seg.load( load_num_seg.str()); num_s = total_seg(0); for (int s_tr=0; s_tr<num_s; ++s_tr) { std::stringstream load_cov_seg_tr; load_cov_seg_tr << load_sub_path << "/LogMcov_seg" << s_tr << "_" << all_people (pe_tr) << "_" << actions(act) << "_dim" << dim << ".h5"; //cout << "Comparing with cov_seg" << s_tr << "_"<< all_people (pe_tr) << "_" << actions(act) << "_dim" << dim << ".h5" << endl; mat logMtrain_cov; logMtrain_cov.load( load_cov_seg_tr.str() ); //logMtest_cov.print("logMtest_cov"); //train_cov.print("train_cov"); dist = norm( logMtest_cov - logMtrain_cov, "fro"); //cout << "dist " << dist << endl; ///crear un vec aca y guardar todas las distancias if (dist < tmp_dist) { //cout << "Es menor" << endl; tmp_dist = dist; est_lab = act; } //cout << "Press a key" << endl; //getchar(); } } } } } //double n = timer.toc(); //cout << "number of seconds: " << n << endl; //cout << " est_lab "<< est_lab << endl << endl; //getchar(); return est_lab; } //DO IT // Stein Divergence inline void kth_cv_omp::SteinDiv() { int n_actions = actions.n_rows; int n_peo = all_people.n_rows; float acc; acc = 0; int n_test = n_peo*n_actions*total_scenes - 1; // - person13_handclapping_d3 vec real_labels; vec est_labels; field<std::string> test_video_list(n_test); real_labels.zeros(n_test); est_labels.zeros(n_test); int k=0; for (int sc = 1; sc<=total_scenes; ++sc) //scene { for (int pe = 0; pe< n_peo; ++pe) { for (int act=0; act<n_actions; ++act) { if( !( ( sc==3 && pe==12) && act==1) ) //person13_handclapping_d3 { //load number of segments vec total_seg; int num_s; std::stringstream load_sub_path; std::stringstream load_num_seg; load_sub_path << path << "/kth-cov-mat/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ; load_num_seg << load_sub_path.str() << "/num_seg_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".dat"; total_seg.load( load_num_seg.str()); num_s = total_seg(0); uvec est_lab_segm; est_lab_segm.zeros(num_s); vec count = zeros<vec>( n_actions ); for (int s=0; s<num_s; ++s) { std::stringstream load_cov_seg; load_cov_seg << load_sub_path.str() << "/cov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5"; est_lab_segm(s) = SteinDiv_one_seg_est_lab( pe, load_sub_path.str(), load_cov_seg.str()); count( est_lab_segm(s) )++; //getchar(); } uword index_video; double max_val = count.max(index_video); //est_lab_segm.t().print("est_lab_segm"); cout << "This video is " << actions(act) << " and was classified as class: " << actions(index_video ) << endl; real_labels(k) = act; est_labels(k) = index_video; test_video_list(k) = load_sub_path.str(); real_labels.save("Stein_div_real_labels.dat", raw_ascii); est_labels.save("Stein_div__est_labels.dat", raw_ascii); test_video_list.save("Stein_div_test_video_list.dat", raw_ascii); k++; if (index_video == act) { acc++; } //getchar(); } } } } cout << "Performance: " << acc*100/n_test << " %" << endl; } //DO IT!!!!!!!!! inline uword kth_cv_omp::SteinDiv_one_seg_est_lab(int pe_test, std::string load_sub_path, std::string segm_name) { //wall_clock timer; //timer.tic(); mat test_cov; test_cov.load(segm_name); int n_actions = actions.n_rows; int n_peo = all_people.n_rows; double dist_stein, tmp_dist; tmp_dist = datum::inf; double est_lab; //cout << "Comparing with person "; for (int pe_tr = 0; pe_tr< n_peo; ++pe_tr) { if (pe_tr!= pe_test) { //cout << " " << all_people (pe_tr); for (int sc = 1; sc<=total_scenes; ++sc) //scene { for (int act=0; act<n_actions; ++act) { vec total_seg; int num_s; std::stringstream load_num_seg; load_num_seg << load_sub_path << "/num_seg_"<< all_people (pe_tr) << "_" << actions(act) << "_dim" << dim << ".dat"; total_seg.load( load_num_seg.str()); num_s = total_seg(0); for (int s_tr=0; s_tr<num_s; ++s_tr) { std::stringstream load_cov_seg_tr; load_cov_seg_tr << load_sub_path << "/cov_seg" << s_tr << "_" << all_people (pe_tr) << "_" << actions(act) << "_dim" << dim << ".h5"; mat train_cov; train_cov.load( load_cov_seg_tr.str() ); //Esto vienen de PartI4. No recuerdo mas :( double det_op1 = det( diagmat( (test_cov + train_cov)/2 ) ); double det_op2 = det( diagmat( ( test_cov%train_cov ) ) ); dist_stein = log( det_op1 ) - 0.5*log( det_op2 ) ; //dist_stein = norm( logMtest_cov - logMtrain_cov, "fro"); //cout << "dist " << dist << endl; if (dist_stein < tmp_dist) { //cout << "Es menor" << endl; tmp_dist = dist_stein; est_lab = act; } //cout << "Press a key" << endl; //getchar(); } } } } } //double n = timer.toc(); //cout << "number of seconds: " << n << endl; //cout << " est_lab "<< est_lab << endl << endl; //getchar(); return est_lab; } <|endoftext|>
<commit_before><commit_msg>Fixed crash at FStatement disposing stage.<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: FPreparedStatement.hxx,v $ * * $Revision: 1.16 $ * * last change: $Author: rt $ $Date: 2005-09-08 07:08:33 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _CONNECTIVITY_FILE_OPREPAREDSTATEMENT_HXX_ #define _CONNECTIVITY_FILE_OPREPAREDSTATEMENT_HXX_ #ifndef _CONNECTIVITY_FILE_OSTATEMENT_HXX_ #include "file/FStatement.hxx" #endif #ifndef _COM_SUN_STAR_SDBC_XPREPAREDSTATEMENT_HPP_ #include <com/sun/star/sdbc/XPreparedStatement.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XPARAMETERS_HPP_ #include <com/sun/star/sdbc/XParameters.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XRESULTSETMETADATASUPPLIER_HPP_ #include <com/sun/star/sdbc/XResultSetMetaDataSupplier.hpp> #endif // #include <com/sun/star/sdbc/XClearParameters.hpp> #ifndef _COM_SUN_STAR_SDBC_XPREPAREDBATCHEXECUTION_HPP_ #include <com/sun/star/sdbc/XPreparedBatchExecution.hpp> #endif #ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_ #include <com/sun/star/io/XInputStream.hpp> #endif #ifndef _CONNECTIVITY_FILE_FRESULTSET_HXX_ #include "file/FResultSet.hxx" #endif namespace connectivity { namespace file { class SAL_NO_VTABLE OPreparedStatement : public OStatement_BASE2, public ::com::sun::star::sdbc::XPreparedStatement, public ::com::sun::star::sdbc::XParameters, public ::com::sun::star::sdbc::XResultSetMetaDataSupplier, public ::com::sun::star::lang::XServiceInfo { protected: //==================================================================== // Data attributes //==================================================================== ::rtl::OUString m_aSql; OValueRefRow m_aParameterRow; ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSetMetaData> m_xMetaData; OResultSet* m_pResultSet; ::vos::ORef<connectivity::OSQLColumns> m_xParamColumns; // the parameter columns // factory method for resultset's virtual OResultSet* createResultSet(); ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet> initResultSet(); void checkAndResizeParameters(sal_Int32 parameterIndex); void setParameter(sal_Int32 parameterIndex, const ORowSetValue& x); UINT32 AddParameter(connectivity::OSQLParseNode * pParameter, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _xCol); void scanParameter(OSQLParseNode* pParseNode,::std::vector< OSQLParseNode*>& _rParaNodes); void describeColumn(OSQLParseNode* _pParameter,OSQLParseNode* _pNode,const OSQLTable& _xTable); void describeParameter(); virtual void parseParamterElem(const String& _sColumnName,OSQLParseNode* pRow_Value_Constructor_Elem); virtual void initializeResultSet(OResultSet* _pResult); virtual ~OPreparedStatement(); public: DECLARE_SERVICE_INFO(); // ein Konstruktor, der fuer das Returnen des Objektes benoetigt wird: OPreparedStatement( OConnection* _pConnection); virtual void construct(const ::rtl::OUString& sql) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); // OComponentHelper virtual void SAL_CALL disposing(void); //XInterface virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL acquire() throw(); virtual void SAL_CALL release() throw(); //XTypeProvider virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes( ) throw(::com::sun::star::uno::RuntimeException); // XPreparedStatement virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL executeQuery( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL executeUpdate( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL execute( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > SAL_CALL getConnection( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); // XParameters virtual void SAL_CALL setNull( sal_Int32 parameterIndex, sal_Int32 sqlType ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setObjectNull( sal_Int32 parameterIndex, sal_Int32 sqlType, const ::rtl::OUString& typeName ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setBoolean( sal_Int32 parameterIndex, sal_Bool x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setByte( sal_Int32 parameterIndex, sal_Int8 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setShort( sal_Int32 parameterIndex, sal_Int16 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setInt( sal_Int32 parameterIndex, sal_Int32 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setLong( sal_Int32 parameterIndex, sal_Int64 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setFloat( sal_Int32 parameterIndex, float x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setDouble( sal_Int32 parameterIndex, double x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setString( sal_Int32 parameterIndex, const ::rtl::OUString& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setBytes( sal_Int32 parameterIndex, const ::com::sun::star::uno::Sequence< sal_Int8 >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setDate( sal_Int32 parameterIndex, const ::com::sun::star::util::Date& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setTime( sal_Int32 parameterIndex, const ::com::sun::star::util::Time& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setTimestamp( sal_Int32 parameterIndex, const ::com::sun::star::util::DateTime& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setBinaryStream( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& x, sal_Int32 length ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setCharacterStream( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& x, sal_Int32 length ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setObject( sal_Int32 parameterIndex, const ::com::sun::star::uno::Any& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setObjectWithInfo( sal_Int32 parameterIndex, const ::com::sun::star::uno::Any& x, sal_Int32 targetSqlType, sal_Int32 scale ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setRef( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRef >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setBlob( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XBlob >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setClob( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XClob >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setArray( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XArray >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL clearParameters( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); // XCloseable virtual void SAL_CALL close( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); // XResultSetMetaDataSupplier virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSetMetaData > SAL_CALL getMetaData( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); }; } } #endif // _CONNECTIVITY_FILE_OPREPAREDSTATEMENT_HXX_ <commit_msg>INTEGRATION: CWS changefileheader (1.16.372); FILE MERGED 2008/04/01 10:53:27 thb 1.16.372.2: #i85898# Stripping all external header guards 2008/03/28 15:24:19 rt 1.16.372.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: FPreparedStatement.hxx,v $ * $Revision: 1.17 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _CONNECTIVITY_FILE_OPREPAREDSTATEMENT_HXX_ #define _CONNECTIVITY_FILE_OPREPAREDSTATEMENT_HXX_ #include "file/FStatement.hxx" #include <com/sun/star/sdbc/XPreparedStatement.hpp> #include <com/sun/star/sdbc/XParameters.hpp> #include <com/sun/star/sdbc/XResultSetMetaDataSupplier.hpp> // #include <com/sun/star/sdbc/XClearParameters.hpp> #include <com/sun/star/sdbc/XPreparedBatchExecution.hpp> #include <com/sun/star/io/XInputStream.hpp> #include "file/FResultSet.hxx" namespace connectivity { namespace file { class SAL_NO_VTABLE OPreparedStatement : public OStatement_BASE2, public ::com::sun::star::sdbc::XPreparedStatement, public ::com::sun::star::sdbc::XParameters, public ::com::sun::star::sdbc::XResultSetMetaDataSupplier, public ::com::sun::star::lang::XServiceInfo { protected: //==================================================================== // Data attributes //==================================================================== ::rtl::OUString m_aSql; OValueRefRow m_aParameterRow; ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSetMetaData> m_xMetaData; OResultSet* m_pResultSet; ::vos::ORef<connectivity::OSQLColumns> m_xParamColumns; // the parameter columns // factory method for resultset's virtual OResultSet* createResultSet(); ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet> initResultSet(); void checkAndResizeParameters(sal_Int32 parameterIndex); void setParameter(sal_Int32 parameterIndex, const ORowSetValue& x); UINT32 AddParameter(connectivity::OSQLParseNode * pParameter, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _xCol); void scanParameter(OSQLParseNode* pParseNode,::std::vector< OSQLParseNode*>& _rParaNodes); void describeColumn(OSQLParseNode* _pParameter,OSQLParseNode* _pNode,const OSQLTable& _xTable); void describeParameter(); virtual void parseParamterElem(const String& _sColumnName,OSQLParseNode* pRow_Value_Constructor_Elem); virtual void initializeResultSet(OResultSet* _pResult); virtual ~OPreparedStatement(); public: DECLARE_SERVICE_INFO(); // ein Konstruktor, der fuer das Returnen des Objektes benoetigt wird: OPreparedStatement( OConnection* _pConnection); virtual void construct(const ::rtl::OUString& sql) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); // OComponentHelper virtual void SAL_CALL disposing(void); //XInterface virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL acquire() throw(); virtual void SAL_CALL release() throw(); //XTypeProvider virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes( ) throw(::com::sun::star::uno::RuntimeException); // XPreparedStatement virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL executeQuery( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL executeUpdate( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL execute( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > SAL_CALL getConnection( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); // XParameters virtual void SAL_CALL setNull( sal_Int32 parameterIndex, sal_Int32 sqlType ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setObjectNull( sal_Int32 parameterIndex, sal_Int32 sqlType, const ::rtl::OUString& typeName ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setBoolean( sal_Int32 parameterIndex, sal_Bool x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setByte( sal_Int32 parameterIndex, sal_Int8 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setShort( sal_Int32 parameterIndex, sal_Int16 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setInt( sal_Int32 parameterIndex, sal_Int32 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setLong( sal_Int32 parameterIndex, sal_Int64 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setFloat( sal_Int32 parameterIndex, float x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setDouble( sal_Int32 parameterIndex, double x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setString( sal_Int32 parameterIndex, const ::rtl::OUString& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setBytes( sal_Int32 parameterIndex, const ::com::sun::star::uno::Sequence< sal_Int8 >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setDate( sal_Int32 parameterIndex, const ::com::sun::star::util::Date& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setTime( sal_Int32 parameterIndex, const ::com::sun::star::util::Time& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setTimestamp( sal_Int32 parameterIndex, const ::com::sun::star::util::DateTime& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setBinaryStream( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& x, sal_Int32 length ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setCharacterStream( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& x, sal_Int32 length ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setObject( sal_Int32 parameterIndex, const ::com::sun::star::uno::Any& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setObjectWithInfo( sal_Int32 parameterIndex, const ::com::sun::star::uno::Any& x, sal_Int32 targetSqlType, sal_Int32 scale ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setRef( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRef >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setBlob( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XBlob >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setClob( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XClob >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setArray( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XArray >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL clearParameters( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); // XCloseable virtual void SAL_CALL close( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); // XResultSetMetaDataSupplier virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSetMetaData > SAL_CALL getMetaData( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); }; } } #endif // _CONNECTIVITY_FILE_OPREPAREDSTATEMENT_HXX_ <|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////// // File: combine_tessdata // Description: Creates a unified traineddata file from several // data files produced by the training process. // Author: Daria Antonova // Created: Wed Jun 03 11:26:43 PST 2009 // // (C) Copyright 2009, Google Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /////////////////////////////////////////////////////////////////////// #include "tessdatamanager.h" // Main program to combine/extract/overwrite tessdata components // in [lang].traineddata files. // // To combine all the individual tessdata components (unicharset, DAWGs, // classifier templates, ambiguities, language configs) located at, say, // /home/$USER/temp/eng.* run: // // combine_tessdata /home/$USER/temp/eng. // // The result will be a combined tessdata file /home/$USER/temp/eng.traineddata // // Specify option -e if you would like to extract individual components // from a combined traineddata file. For example, to extract language config // file and the unicharset from tessdata/eng.traineddata run: // // combine_tessdata -e tessdata/eng.traineddata // /home/$USER/temp/eng.config /home/$USER/temp/eng.unicharset // // The desired config file and unicharset will be written to // /home/$USER/temp/eng.config /home/$USER/temp/eng.unicharset // // Specify option -o to overwrite individual components of the given // [lang].traineddata file. For example, to overwrite language config // and unichar ambiguities files in tessdata/eng.traineddata use: // // combine_tessdata -o tessdata/eng.traineddata // /home/$USER/temp/eng.config /home/$USER/temp/eng.unicharambigs // // As a result, tessdata/eng.traineddata will contain the new language config // and unichar ambigs, plus all the original DAWGs, classifier teamples, etc. // // Note: the file names of the files to extract to and to overwrite from should // have the appropriate file suffixes (extensions) indicating their tessdata // component type (.unicharset for the unicharset, .unicharambigs for unichar // ambigs, etc). See k*FileSuffix variable in ccutil/tessdatamanager.h. // // Specify option -u to unpack all the components to the specified path: // // combine_tessdata -u tessdata/eng.traineddata /home/$USER/temp/eng. // // This will create /home/$USER/temp/eng.* files with individual tessdata // components from tessdata/eng.traineddata. // int main(int argc, char **argv) { int i; if (argc == 2) { printf("Combininig tessdata files\n"); STRING output_file = argv[1]; output_file += kTrainedDataSuffix; if (!tesseract::TessdataManager::CombineDataFiles( argv[1], output_file.string())) { printf("Error combining tessdata files into %s\n", output_file.string()); } } else if (argc >= 4 && (strcmp(argv[1], "-e") == 0 || strcmp(argv[1], "-u") == 0)) { // Initialize TessdataManager with the data in the given traineddata file. tesseract::TessdataManager tm; tm.Init(argv[2]); printf("Extracting tessdata components from %s\n", argv[2]); if (strcmp(argv[1], "-e") == 0) { for (i = 3; i < argc; ++i) { if (tm.ExtractToFile(argv[i])) { printf("Wrote %s\n", argv[i]); } else { printf("Not extracting %s, since this component" " is not present\n", argv[i]); } } } else { // extract all the components for (i = 0; i < tesseract::TESSDATA_NUM_ENTRIES; ++i) { STRING filename = argv[3]; filename += tesseract::kTessdataFileSuffixes[i]; if (tm.ExtractToFile(filename.string())) { printf("Wrote %s\n", filename.string()); } } } tm.End(); } else if (argc >= 4 && strcmp(argv[1], "-o") == 0) { // Rename the current traineddata file to a temporary name. const char *new_traineddata_filename = argv[2]; STRING traineddata_filename = new_traineddata_filename; traineddata_filename += ".__tmp__"; if (rename(new_traineddata_filename, traineddata_filename.string()) != 0) { tprintf("Failed to create a temporary file %s\n", traineddata_filename.string()); exit(1); } // Initialize TessdataManager with the data in the given traineddata file. tesseract::TessdataManager tm; tm.Init(traineddata_filename.string()); // Write the updated traineddata file. tm.OverwriteComponents(new_traineddata_filename, argv+3, argc-3); tm.End(); } else { printf("Usage for combining tessdata components:\n" "%s language_data_path_prefix (e.g. tessdata/eng.)\n", argv[0]); printf("Usage for extracting tessdata components:\n" "%s -e traineddata_file [output_component_file...]\n", argv[0]); printf("Usage for overwriting tessdata components:\n" "%s -o traineddata_file [input_component_file...]\n", argv[0]); printf("Usage for unpacking all tessdata components:\n" "%s -u traineddata_file output_path_prefix" " (e.g. /tmp/eng.)\n", argv[0]); return 1; } } <commit_msg>improved usage description (issue http://code.google.com/p/tesseract-ocr/issues/detail?id=356)<commit_after>/////////////////////////////////////////////////////////////////////// // File: combine_tessdata // Description: Creates a unified traineddata file from several // data files produced by the training process. // Author: Daria Antonova // Created: Wed Jun 03 11:26:43 PST 2009 // // (C) Copyright 2009, Google Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /////////////////////////////////////////////////////////////////////// #include "tessdatamanager.h" // Main program to combine/extract/overwrite tessdata components // in [lang].traineddata files. // // To combine all the individual tessdata components (unicharset, DAWGs, // classifier templates, ambiguities, language configs) located at, say, // /home/$USER/temp/eng.* run: // // combine_tessdata /home/$USER/temp/eng. // // The result will be a combined tessdata file /home/$USER/temp/eng.traineddata // // Specify option -e if you would like to extract individual components // from a combined traineddata file. For example, to extract language config // file and the unicharset from tessdata/eng.traineddata run: // // combine_tessdata -e tessdata/eng.traineddata // /home/$USER/temp/eng.config /home/$USER/temp/eng.unicharset // // The desired config file and unicharset will be written to // /home/$USER/temp/eng.config /home/$USER/temp/eng.unicharset // // Specify option -o to overwrite individual components of the given // [lang].traineddata file. For example, to overwrite language config // and unichar ambiguities files in tessdata/eng.traineddata use: // // combine_tessdata -o tessdata/eng.traineddata // /home/$USER/temp/eng.config /home/$USER/temp/eng.unicharambigs // // As a result, tessdata/eng.traineddata will contain the new language config // and unichar ambigs, plus all the original DAWGs, classifier teamples, etc. // // Note: the file names of the files to extract to and to overwrite from should // have the appropriate file suffixes (extensions) indicating their tessdata // component type (.unicharset for the unicharset, .unicharambigs for unichar // ambigs, etc). See k*FileSuffix variable in ccutil/tessdatamanager.h. // // Specify option -u to unpack all the components to the specified path: // // combine_tessdata -u tessdata/eng.traineddata /home/$USER/temp/eng. // // This will create /home/$USER/temp/eng.* files with individual tessdata // components from tessdata/eng.traineddata. // int main(int argc, char **argv) { int i; if (argc == 2) { printf("Combininig tessdata files\n"); STRING output_file = argv[1]; output_file += kTrainedDataSuffix; if (!tesseract::TessdataManager::CombineDataFiles( argv[1], output_file.string())) { printf("Error combining tessdata files into %s\n", output_file.string()); } } else if (argc >= 4 && (strcmp(argv[1], "-e") == 0 || strcmp(argv[1], "-u") == 0)) { // Initialize TessdataManager with the data in the given traineddata file. tesseract::TessdataManager tm; tm.Init(argv[2]); printf("Extracting tessdata components from %s\n", argv[2]); if (strcmp(argv[1], "-e") == 0) { for (i = 3; i < argc; ++i) { if (tm.ExtractToFile(argv[i])) { printf("Wrote %s\n", argv[i]); } else { printf("Not extracting %s, since this component" " is not present\n", argv[i]); } } } else { // extract all the components for (i = 0; i < tesseract::TESSDATA_NUM_ENTRIES; ++i) { STRING filename = argv[3]; filename += tesseract::kTessdataFileSuffixes[i]; if (tm.ExtractToFile(filename.string())) { printf("Wrote %s\n", filename.string()); } } } tm.End(); } else if (argc >= 4 && strcmp(argv[1], "-o") == 0) { // Rename the current traineddata file to a temporary name. const char *new_traineddata_filename = argv[2]; STRING traineddata_filename = new_traineddata_filename; traineddata_filename += ".__tmp__"; if (rename(new_traineddata_filename, traineddata_filename.string()) != 0) { tprintf("Failed to create a temporary file %s\n", traineddata_filename.string()); exit(1); } // Initialize TessdataManager with the data in the given traineddata file. tesseract::TessdataManager tm; tm.Init(traineddata_filename.string()); // Write the updated traineddata file. tm.OverwriteComponents(new_traineddata_filename, argv+3, argc-3); tm.End(); } else { printf("Usage for combining tessdata components:\n" " %s language_data_path_prefix\n" " (e.g. %s tessdata/my_lang.)\n" " Warning: Do not forget dot at the end of language_data_path_prefix!\n", argv[0], argv[0]); printf("\nUsage for extracting tessdata components:\n" " %s -e traineddata_file output_component_file\n" " (e.g. %s -e tessdata/eng.traineddata eng.unicharambigs)\n", argv[0], argv[0]); printf("\nUsage for overwriting tessdata components:\n" " %s -o traineddata_file input_component_file\n" " (e.g. %s -o tessdata/eng.traineddata eng.config)\n" " Warning: (input_)component_file must already exists in traineddata_file!\n", argv[0], argv[0]); printf("\nUsage for unpacking all tessdata components:\n" " %s -u traineddata_file output_path_prefix\n" " (e.g. %s -u tessdata/eng.traineddata /tmp/eng.)\n" " Warning: Do not forget dot at the end of output_path_prefix!\n", argv[0], argv[0]); return 1; } } <|endoftext|>
<commit_before>// @(#)root/treeviewer:$Name: $:$Id: HelpTextTV.cxx,v 1.8 2001/02/22 15:15:52 brun Exp $ // Author: Andrei Gheata 02/10/00 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "HelpTextTV.h" #ifndef R__WIN32 const char gTVHelpAbout[] = "\ TreeViewer is a graphic user interface designed to handle ROOT trees and to \n\ take advantage of TTree class features. It uses ROOT native GUI widgets adapted\n\ for drag-and-drop functionality. The following capabilities are making the \n\ viewer a helpful tool for analysis : \n\n\ - several trees may be opened in the same session \n\ - branches and leaves can be easily browsed or scanned \n\ - fast drawing of branch expressions by double-clicking \n\ - new variables/selections easy to compose with the built-in editor \n\ - histograms can be composed by dragging leaves or user-defined expressions \n\ to X, Y and Z axis items \n\ - the tree entries to be processed can be selected with a double slider \n\ - selections can be defined and activated by dragging them to the <Cut> item \n\ - all expressions can be aliased and aliases can be used in composing others \n\ - input/output event lists easy to handle \n\ - menu with histogram drawing options \n\ - user commands may be executed within the viewer and the current command \n\ can be echoed \n\ - current <Draw> event loop is reflected by a progress bar and may be \n\ interrupted by the user \n\ - all widgets have self-explaining tool tips and/or context menus \n\ - expressions/leaves can be dragged to a <Scan box> and scanned by \n\ double-clicking this item. The result can be redirected to an ASCII file \n\n\ "; const char gTVHelpStart[] = "\ 1) From the TBrowser : \n\n\ Select a tree in the TBrowser, then call the StartViewer() method from its \n\ context menu (right-click on the tree). \n\n\ 2) From the command line : \n\n\ Start a ROOT session in the directory where you have your tree. \n\ You will need first to load the library for TTreeViewer and optionally other \n\ libraries for user defined classes (you can do this later in the session) : \n\ root [0] gSystem->Load(\"TTreeViewer\"); \n\ Supposing you have the tree MyTree in the file MyFile, you can do : \n\ root [1] TFile file(\"Myfile\"); \n\ root [2] new TTreeViewer(\"Mytree\"); \n\ or : \n\ root [2] TreeViewer *tv = new TTreeViewer(); \n\ root [3] tv->SetTreeName(\"Mytree\"); \n\n\ "; const char gTVHelpLayout[] = "\ The layout has the following items :\n\n\ - a menu bar with entries : File, Edit, Run, Options and Help \n\ - a toolbar in the upper part where you can issue user commands, change \n\ the drawing option and the histogram name, three check buttons Hist, Rec \n\ and Scan.HIST toggles histogram drawing mode, REC enables recording of the \n\ last command issued and SCAN enables redirecting of TTree::Scan command in \n\ an ASCII file (see Scanning expressions...) \n\ - a button bar in the lower part with :buttons DRAW/STOP that issue histogram\n\ drawing and stop the current command respectively, two text widgets where \n\ input and output event lists can be specified, a message box and a RESET \n\ button on the right that clear edited expression content (see Editing...) \n\ - a tree-type list on the main left panel where you can select among trees or\n\ branches. The tree/branch will be detailed in the right panel. \n\ Mapped trees are provided with context menus, activated by right-clicking; \n\ - a view-type list on the right panel. The first column contain X, Y and \n\ Z expression items, an optional cut and ten optional editable expressions. \n\ Expressions and leaf-type items can be dragged or deleted. A right click on \n\ the list-box or item activates context menus. \n\n\ "; const char gTVHelpOpenSave[] = "\ To open a new tree in the viewer use <File/Open tree file> menu \n\ The content of the file (keys) will be listed. Use <SetTreeName> function \n\ from the context menu of the right panel, entering a tree name among those \n\ listed. \n\n\ To save the current session, use <File/Save> menu or the <SaveSource> \n\ function from the context menu of the right panel (to specify the name of the \n\ file - name.C) \n\n\ To open a previously saved session for the tree MyTree, first open MyTree \n\ in the browser, then use <File/Open session> menu. \n\n\ "; const char gTVHelpDraggingItems[] = "\ Items that can be dragged from the list in the right : expressions and \n\ leaves. Dragging an item and dropping to another will copy the content of first\n\ to the last (leaf->expression, expression->expression). Items far to the right \n\ side of the list can be easily dragged to the left (where expressions are \n\ placed) by dragging them to the left at least 10 pixels. \n\n\ "; const char gTVHelpEditExpressions[] = "\ Any editable expression from the right panel has two components : a \n\ true name (that will be used when TTree::Draw() commands are issued) and an \n\ alias. The visible name is the alias. Aliases of user defined expressions have \n\ a leading ~ and may be used in new expressions. Expressions containing boolean \n\ operators have a specific icon and may be dragged to the active cut (scissors \n\ item) position \n\n\ The expression editor can be activated by double-clicking empty expression, \n\ using <EditExpression> from the selected expression context menu or using \n\ <Edit/Expression> menu. \n\n\ The editor will pop-up in the left part, but it can be moved. \n\ The editor usage is the following : \n\ - you can write C expressions made of leaf names by hand or you can insert \n\ any item from the right panel by clicking on it (recommandable) \n\ - you can click on other expressions/leaves to paste them in the editor \n\ - you should write the item alias by hand since it not makes the expression \n\ meaningfull and also highly improves the layout for big expressions \n\ - you may redefine an old alias - the other expressions depending on it will \n\ be modified accordingly. Must NOT be the leading string of other aliases. \n\ When Draw commands are issued, the name of the corresponding histogram axes \n\ will become the aliases of the expressions. \n\n\ "; const char gTVHelpUserCommands[] = "\ User commands can be issued directly from the textbox labeled <Command> \n\ from the upper-left toolbar by typing and pressing Enter at the end. \n\ An other way is from the right panel context menu : ExecuteCommand. \n\n\ All commands can be interrupted at any time by pressing the STOP button \n\ from the bottom-left \n\n\ You can toggle recording of the current command in the history file by \n\ checking the Rec button from the top-right \n\n\ "; const char gTVHelpContext[] = "\ You can activate context menus by right-clicking on items or inside the \n\ right panel. \n\n\ Context menus for mapped items from the left tree-type list : \n\n\ The items from the left that are provided with context menus are tree and \n\ branch items. You can directly activate the *MENU* marked methods of TTree \n\ from this menu. \n\n\ Context menu for the right panel : \n\n\ A general context menu is acivated if the user right-clicks the right panel. \n\ Commands are : \n\ - EmptyAll : clears the content of all expressions \n\ - ExecuteCommand : execute a ROOT command \n\ - MakeSelector : equivalent of TTree::MakeSelector() \n\ - NewExpression : add an expression item in the right panel \n\ - Process : equivalent of TTree::Process() \n\ - SaveSource : save the current session as a C++ macro \n\ - SetScanFileName : define a name for the file where TTree::Scan command \n\ is redirected when the <Scan> button is checked \n\ - SetTreeName : open a new tree whith this name in the viewer; \n\n\ A specific context menu is activated if expressions/leaves are right-clicked.\n\ Commands are : \n\ - Draw : draw a histogram for this item \n\ - EditExpression : pops-up the expression editor \n\ - Empty : empty the name and alias of this item \n\ - RemoveItem : removes clicked item from the list; \n\ - Scan : scan this expression \n\ - SetExpression : edit name and alias for this item by hand \n\n\ "; const char gTVHelpDrawing[] = "\ Fast variable drawing : Just double-click an item from the right list. \n\n\ Normal drawing : Edit the X, Y, Z fields or drag expressions here, fill \n\ input-output list names if you have defined them. Press <Draw> button. \n\n\ You can change output histogram name, or toggle Hist or Scan modes by checking \n\ the corresponding buttons. \n\ Hist mode implies that the current histogram will be redrawn with the current\n\ graphics options. If a histogram is already drawn and the graphic <Option> \n\ is changed, pressing <Enter> will redraw with the new option. Checking <Scan> \n\ will redirect TTree::Scan() command in an ASCII file. \n\n\ You have a complete list of histogram options in multicheckable lists from \n\ the Option menu. When using this menu, only the options compatible with the \n\ current histogram dimension will be available. You can check multiple options \n\ and reset them by checking the Default entries. \n\n\ After completing the previous operations you can issue the draw command by \n\ pressing the DRAW button. \n\n\ "; const char gTVHelpMacros[] = "\ Macros can be loaded and executed in this version only by issuing \n\ the corresponding user commands (see help on user commands) \n\n\ "; #else const char gTVHelpAbout[] = "empty"; const char gTVHelpStart[] = "empty"; const char gTVHelpLayout[] = "empty"; const char gTVHelpOpenSave[] = "empty"; const char gTVHelpDraggingItems[] = "empty"; const char gTVHelpEditExpressions[] = "empty"; const char gTVHelpUserCommands[] = "empty"; const char gTVHelpContext[] = "empty"; const char gTVHelpDrawing[] = "empty"; const char gTVHelpMacros[] = "empty"; #endif <commit_msg>Activate the help file under win32gdk<commit_after>// @(#)root/treeviewer:$Name: $:$Id: HelpTextTV.cxx,v 1.9 2001/02/26 10:28:53 brun Exp $ // Author: Andrei Gheata 02/10/00 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "HelpTextTV.h" #if !defined(R__WIN32) || defined(GDK_WIN32) const char gTVHelpAbout[] = "\ TreeViewer is a graphic user interface designed to handle ROOT trees and to \n\ take advantage of TTree class features. It uses ROOT native GUI widgets adapted\n\ for drag-and-drop functionality. The following capabilities are making the \n\ viewer a helpful tool for analysis : \n\n\ - several trees may be opened in the same session \n\ - branches and leaves can be easily browsed or scanned \n\ - fast drawing of branch expressions by double-clicking \n\ - new variables/selections easy to compose with the built-in editor \n\ - histograms can be composed by dragging leaves or user-defined expressions \n\ to X, Y and Z axis items \n\ - the tree entries to be processed can be selected with a double slider \n\ - selections can be defined and activated by dragging them to the <Cut> item \n\ - all expressions can be aliased and aliases can be used in composing others \n\ - input/output event lists easy to handle \n\ - menu with histogram drawing options \n\ - user commands may be executed within the viewer and the current command \n\ can be echoed \n\ - current <Draw> event loop is reflected by a progress bar and may be \n\ interrupted by the user \n\ - all widgets have self-explaining tool tips and/or context menus \n\ - expressions/leaves can be dragged to a <Scan box> and scanned by \n\ double-clicking this item. The result can be redirected to an ASCII file \n\n\ "; const char gTVHelpStart[] = "\ 1) From the TBrowser : \n\n\ Select a tree in the TBrowser, then call the StartViewer() method from its \n\ context menu (right-click on the tree). \n\n\ 2) From the command line : \n\n\ Start a ROOT session in the directory where you have your tree. \n\ You will need first to load the library for TTreeViewer and optionally other \n\ libraries for user defined classes (you can do this later in the session) : \n\ root [0] gSystem->Load(\"TTreeViewer\"); \n\ Supposing you have the tree MyTree in the file MyFile, you can do : \n\ root [1] TFile file(\"Myfile\"); \n\ root [2] new TTreeViewer(\"Mytree\"); \n\ or : \n\ root [2] TreeViewer *tv = new TTreeViewer(); \n\ root [3] tv->SetTreeName(\"Mytree\"); \n\n\ "; const char gTVHelpLayout[] = "\ The layout has the following items :\n\n\ - a menu bar with entries : File, Edit, Run, Options and Help \n\ - a toolbar in the upper part where you can issue user commands, change \n\ the drawing option and the histogram name, three check buttons Hist, Rec \n\ and Scan.HIST toggles histogram drawing mode, REC enables recording of the \n\ last command issued and SCAN enables redirecting of TTree::Scan command in \n\ an ASCII file (see Scanning expressions...) \n\ - a button bar in the lower part with :buttons DRAW/STOP that issue histogram\n\ drawing and stop the current command respectively, two text widgets where \n\ input and output event lists can be specified, a message box and a RESET \n\ button on the right that clear edited expression content (see Editing...) \n\ - a tree-type list on the main left panel where you can select among trees or\n\ branches. The tree/branch will be detailed in the right panel. \n\ Mapped trees are provided with context menus, activated by right-clicking; \n\ - a view-type list on the right panel. The first column contain X, Y and \n\ Z expression items, an optional cut and ten optional editable expressions. \n\ Expressions and leaf-type items can be dragged or deleted. A right click on \n\ the list-box or item activates context menus. \n\n\ "; const char gTVHelpOpenSave[] = "\ To open a new tree in the viewer use <File/Open tree file> menu \n\ The content of the file (keys) will be listed. Use <SetTreeName> function \n\ from the context menu of the right panel, entering a tree name among those \n\ listed. \n\n\ To save the current session, use <File/Save> menu or the <SaveSource> \n\ function from the context menu of the right panel (to specify the name of the \n\ file - name.C) \n\n\ To open a previously saved session for the tree MyTree, first open MyTree \n\ in the browser, then use <File/Open session> menu. \n\n\ "; const char gTVHelpDraggingItems[] = "\ Items that can be dragged from the list in the right : expressions and \n\ leaves. Dragging an item and dropping to another will copy the content of first\n\ to the last (leaf->expression, expression->expression). Items far to the right \n\ side of the list can be easily dragged to the left (where expressions are \n\ placed) by dragging them to the left at least 10 pixels. \n\n\ "; const char gTVHelpEditExpressions[] = "\ Any editable expression from the right panel has two components : a \n\ true name (that will be used when TTree::Draw() commands are issued) and an \n\ alias. The visible name is the alias. Aliases of user defined expressions have \n\ a leading ~ and may be used in new expressions. Expressions containing boolean \n\ operators have a specific icon and may be dragged to the active cut (scissors \n\ item) position \n\n\ The expression editor can be activated by double-clicking empty expression, \n\ using <EditExpression> from the selected expression context menu or using \n\ <Edit/Expression> menu. \n\n\ The editor will pop-up in the left part, but it can be moved. \n\ The editor usage is the following : \n\ - you can write C expressions made of leaf names by hand or you can insert \n\ any item from the right panel by clicking on it (recommandable) \n\ - you can click on other expressions/leaves to paste them in the editor \n\ - you should write the item alias by hand since it not makes the expression \n\ meaningfull and also highly improves the layout for big expressions \n\ - you may redefine an old alias - the other expressions depending on it will \n\ be modified accordingly. Must NOT be the leading string of other aliases. \n\ When Draw commands are issued, the name of the corresponding histogram axes \n\ will become the aliases of the expressions. \n\n\ "; const char gTVHelpUserCommands[] = "\ User commands can be issued directly from the textbox labeled <Command> \n\ from the upper-left toolbar by typing and pressing Enter at the end. \n\ An other way is from the right panel context menu : ExecuteCommand. \n\n\ All commands can be interrupted at any time by pressing the STOP button \n\ from the bottom-left \n\n\ You can toggle recording of the current command in the history file by \n\ checking the Rec button from the top-right \n\n\ "; const char gTVHelpContext[] = "\ You can activate context menus by right-clicking on items or inside the \n\ right panel. \n\n\ Context menus for mapped items from the left tree-type list : \n\n\ The items from the left that are provided with context menus are tree and \n\ branch items. You can directly activate the *MENU* marked methods of TTree \n\ from this menu. \n\n\ Context menu for the right panel : \n\n\ A general context menu is acivated if the user right-clicks the right panel. \n\ Commands are : \n\ - EmptyAll : clears the content of all expressions \n\ - ExecuteCommand : execute a ROOT command \n\ - MakeSelector : equivalent of TTree::MakeSelector() \n\ - NewExpression : add an expression item in the right panel \n\ - Process : equivalent of TTree::Process() \n\ - SaveSource : save the current session as a C++ macro \n\ - SetScanFileName : define a name for the file where TTree::Scan command \n\ is redirected when the <Scan> button is checked \n\ - SetTreeName : open a new tree whith this name in the viewer; \n\n\ A specific context menu is activated if expressions/leaves are right-clicked.\n\ Commands are : \n\ - Draw : draw a histogram for this item \n\ - EditExpression : pops-up the expression editor \n\ - Empty : empty the name and alias of this item \n\ - RemoveItem : removes clicked item from the list; \n\ - Scan : scan this expression \n\ - SetExpression : edit name and alias for this item by hand \n\n\ "; const char gTVHelpDrawing[] = "\ Fast variable drawing : Just double-click an item from the right list. \n\n\ Normal drawing : Edit the X, Y, Z fields or drag expressions here, fill \n\ input-output list names if you have defined them. Press <Draw> button. \n\n\ You can change output histogram name, or toggle Hist or Scan modes by checking \n\ the corresponding buttons. \n\ Hist mode implies that the current histogram will be redrawn with the current\n\ graphics options. If a histogram is already drawn and the graphic <Option> \n\ is changed, pressing <Enter> will redraw with the new option. Checking <Scan> \n\ will redirect TTree::Scan() command in an ASCII file. \n\n\ You have a complete list of histogram options in multicheckable lists from \n\ the Option menu. When using this menu, only the options compatible with the \n\ current histogram dimension will be available. You can check multiple options \n\ and reset them by checking the Default entries. \n\n\ After completing the previous operations you can issue the draw command by \n\ pressing the DRAW button. \n\n\ "; const char gTVHelpMacros[] = "\ Macros can be loaded and executed in this version only by issuing \n\ the corresponding user commands (see help on user commands) \n\n\ "; #else const char gTVHelpAbout[] = "empty"; const char gTVHelpStart[] = "empty"; const char gTVHelpLayout[] = "empty"; const char gTVHelpOpenSave[] = "empty"; const char gTVHelpDraggingItems[] = "empty"; const char gTVHelpEditExpressions[] = "empty"; const char gTVHelpUserCommands[] = "empty"; const char gTVHelpContext[] = "empty"; const char gTVHelpDrawing[] = "empty"; const char gTVHelpMacros[] = "empty"; #endif <|endoftext|>
<commit_before>// Example macro to show unuran capabilities // The results are compared with what is obtained using TRandom or TF1::GetRandom // The macro is divided in 3 parts: // - testStringAPI : show how to use string API of UNURAN to generate Gaussian random numbers // - testDistr1D : show how to pass a 1D distribution object to UNURAN to generate numbers // according to the given distribution object // - testDistrMultiDIm : show how to pass a multidimensional distribution object to UNURAN // // // To execute the macro type in: // // root[0]: gSystem->Load("libMathCore"); // root[0]: gSystem->Load("libUnuran"); // root[0]: .x unuranDemo.C+ // //Author: Lorenzo Moneta #include "TStopwatch.h" #include "TUnuran.h" #include "TH1.h" #include "TH3.h" #include "TF3.h" #include "TRandom2.h" #include "TSystem.h" #include "TStyle.h" #include "TApplication.h" #include "TCanvas.h" #include "Math/ProbFunc.h" #include "Math/DistFunc.h" #include <iostream> #include <cassert> using std::cout; using std::endl; // number of distribution generated points #define NGEN 1000000 int izone = 0; TCanvas * c1 = 0; // test using UNURAN string interface void testStringAPI() { TH1D * h1 = new TH1D("h1G","gaussian distribution from Unuran",100,-10,10); TH1D * h2 = new TH1D("h2G","gaussian distribution from TRandom",100,-10,10); TUnuran unr; if (! unr.Init( "normal()", "method=arou") ) { cout << "Error initializing unuran" << endl; return; } int n = NGEN; TStopwatch w; w.Start(); for (int i = 0; i < n; ++i) { double x = unr.Sample(); h1->Fill( x ); } w.Stop(); cout << "Time using Unuran =\t\t " << w.CpuTime() << endl; // use TRandom::Gaus w.Start(); for (int i = 0; i < n; ++i) { double x = gRandom->Gaus(0,1); h2->Fill( x ); } w.Stop(); cout << "Time using TRandom::Gaus =\t " << w.CpuTime() << endl; assert(c1 != 0); c1->cd(++izone); h1->Draw(); c1->cd(++izone); h2->Draw(); } double distr(double *x, double *p) { return ROOT::Math::breitwigner_pdf(x[0],p[0],p[1]); } double cdf(double *x, double *p) { return ROOT::Math::breitwigner_quant(x[0],p[0],p[1]); } // test of unuran passing as input a distribution object( a BreitWigner) distribution void testDistr1D() { TH1D * h1 = new TH1D("h1BW","Breit-Wigner distribution from Unuran",100,-10,10); TH1D * h2 = new TH1D("h2BW","Breit-Wigner distribution from GetRandom",100,-10,10); TF1 * f = new TF1("distrFunc",distr,-10,10,2); double par[2] = {1,0}; // values are gamma and mean f->SetParameters(par); TF1 * fc = new TF1("cdfFunc",cdf,-10,10,2); fc->SetParameters(par); // create Unuran 1D distribution object TUnuranDistr dist(f,fc); // to use a different random number engine do: TRandom2 * random = new TRandom2(); int logLevel = 0; TUnuran unr(random,logLevel); // select unuran method for generating the random numbers std::string method = "method=arou"; //std::string method = "method=auto"; // "method=hinv" if (!unr.Init(dist,method) ) { cout << "Error initializing unuran" << endl; return; } TStopwatch w; w.Start(); int n = NGEN; for (int i = 0; i < n; ++i) { double x = unr.Sample(); h1->Fill( x ); } w.Stop(); cout << "Time using Unuran =\t\t " << w.CpuTime() << endl; w.Start(); for (int i = 0; i < n; ++i) { double x = f->GetRandom(); h2->Fill( x ); } w.Stop(); cout << "Time using GetRandom() =\t " << w.CpuTime() << endl; c1->cd(++izone); h1->Draw(); c1->cd(++izone); h2->Draw(); std::cout << " chi2 test of UNURAN vs GetRandom generated histograms: " << std::endl; h1->Chi2Test(h2,"UUP"); } // 3D gaussian distribution double gaus3d(double *x, double *p) { double sigma_x = p[0]; double sigma_y = p[1]; double sigma_z = p[2]; double rho = p[2]; double u = x[0] / sigma_x ; double v = x[1] / sigma_y ; double w = x[2] / sigma_z ; double c = 1 - rho*rho ; double result = (1 / (2 * TMath::Pi() * sigma_x * sigma_y * sigma_z * sqrt(c))) * exp (-(u * u - 2 * rho * u * v + v * v + w*w) / (2 * c)); return result; } // test of unuran passing as input a mluti-dimension distribution object void testDistrMultiDim() { TH3D * h1 = new TH3D("h13D","gaussian 3D distribution from Unuran",50,-10,10,50,-10,10,50,-10,10); TH3D * h2 = new TH3D("h23D","gaussian 3D distribution from GetRandom",50,-10,10,50,-10,10,50,-10,10); TF3 * f = new TF3("g3d",gaus3d,-10,10,-10,10,-10,10,3); double par[3] = {2,2,0.5}; f->SetParameters(par); TUnuranDistrMulti dist(f); TUnuran unr(gRandom); //std::string method = "method=vnrou"; std::string method = "method=hitro;use_boundingrectangle=false "; if ( ! unr.Init(dist,method,0) ) { cout << "Error initializing unuran" << endl; return; } TStopwatch w; w.Start(); double x[3]; for (int i = 0; i < NGEN; ++i) { unr.SampleMulti(x); h1->Fill(x[0],x[1],x[2]); } w.Stop(); cout << "Time using Unuran =\t " << w.CpuTime() << endl; assert(c1 != 0); c1->cd(++izone); h1->Draw(); // need to set a reasanable number of points in TF1 to get accettable quality from GetRandom to int np = 200; f->SetNpx(200); f->SetNpy(200); f->SetNpz(200); w.Start(); for (int i = 0; i < NGEN; ++i) { f->GetRandom3(x[0],x[1],x[2]); h2->Fill(x[0],x[1],x[2]); } w.Stop(); cout << "Time using TF1::GetRandom =\t " << w.CpuTime() << endl; c1->cd(++izone); h2->Draw(); std::cout << " chi2 test of UNURAN vs GetRandom generated histograms: " << std::endl; h1->Chi2Test(h2,"UUP"); } void unuranDemo() { //gRandom->SetSeed(0); // load libraries gSystem->Load("libMathCore"); gSystem->Load("libUnuran"); // create canvas c1 = new TCanvas("c1_unuranMulti","Multidimensional distribution",10,10,1000,1000); c1->Divide(2,3); gStyle->SetOptFit(); testStringAPI(); testDistr1D(); testDistrMultiDim(); } <commit_msg>udpate tutorials showing the new functionality in Unuran<commit_after>// Example macro to show unuran capabilities // The results are compared with what is obtained using TRandom or TF1::GetRandom // The macro is divided in 3 parts: // - testStringAPI : show how to use string API of UNURAN to generate Gaussian random numbers // - testDistr1D : show how to pass a 1D distribution object to UNURAN to generate numbers // according to the given distribution object // - testDistrMultiDIm : show how to pass a multidimensional distribution object to UNURAN // // // To execute the macro type in: // // root[0]: gSystem->Load("libMathCore"); // root[0]: gSystem->Load("libUnuran"); // root[0]: .x unuranDemo.C+ // //Author: Lorenzo Moneta #include "TStopwatch.h" #include "TUnuran.h" #include "TUnuranContDist.h" #include "TUnuranMultiContDist.h" #include "TUnuranDiscrDist.h" #include "TUnuranEmpDist.h" #include "TH1.h" #include "TH3.h" #include "TF3.h" #include "TMath.h" #include "TRandom2.h" #include "TSystem.h" #include "TStyle.h" #include "TApplication.h" #include "TCanvas.h" #include "Math/ProbFunc.h" #include "Math/DistFunc.h" #include <iostream> #include <cassert> using std::cout; using std::endl; // number of distribution generated points #define NGEN 1000000 int izone = 0; TCanvas * c1 = 0; // test using UNURAN string interface void testStringAPI() { TH1D * h1 = new TH1D("h1G","gaussian distribution from Unuran",100,-10,10); TH1D * h2 = new TH1D("h2G","gaussian distribution from TRandom",100,-10,10); cout << "\nTest using UNURAN string API \n\n"; TUnuran unr; if (! unr.Init( "normal()", "method=arou") ) { cout << "Error initializing unuran" << endl; return; } int n = NGEN; TStopwatch w; w.Start(); for (int i = 0; i < n; ++i) { double x = unr.Sample(); h1->Fill( x ); } w.Stop(); cout << "Time using Unuran method " << unr.MethodName() << "\t=\t " << w.CpuTime() << endl; // use TRandom::Gaus w.Start(); for (int i = 0; i < n; ++i) { double x = gRandom->Gaus(0,1); h2->Fill( x ); } w.Stop(); cout << "Time using TRandom::Gaus \t=\t " << w.CpuTime() << endl; assert(c1 != 0); c1->cd(++izone); h1->Draw(); c1->cd(++izone); h2->Draw(); } double distr(double *x, double *p) { return ROOT::Math::breitwigner_pdf(x[0],p[0],p[1]); } double cdf(double *x, double *p) { return ROOT::Math::breitwigner_quant(x[0],p[0],p[1]); } // test of unuran passing as input a distribution object( a BreitWigner) distribution void testDistr1D() { cout << "\nTest 1D Continous distributions\n\n"; TH1D * h1 = new TH1D("h1BW","Breit-Wigner distribution from Unuran",100,-10,10); TH1D * h2 = new TH1D("h2BW","Breit-Wigner distribution from GetRandom",100,-10,10); TF1 * f = new TF1("distrFunc",distr,-10,10,2); double par[2] = {1,0}; // values are gamma and mean f->SetParameters(par); TF1 * fc = new TF1("cdfFunc",cdf,-10,10,2); fc->SetParameters(par); // create Unuran 1D distribution object TUnuranContDist dist(f); // to use a different random number engine do: TRandom2 * random = new TRandom2(); int logLevel = 2; TUnuran unr(random,logLevel); // select unuran method for generating the random numbers std::string method = "tdr"; //std::string method = "method=auto"; // "method=hinv" // set the cdf for some methods like hinv that requires it // dist.SetCdf(fc); //cout << "unuran method is " << method << endl; if (!unr.Init(dist,method) ) { cout << "Error initializing unuran" << endl; return; } TStopwatch w; w.Start(); int n = NGEN; for (int i = 0; i < n; ++i) { double x = unr.Sample(); h1->Fill( x ); } w.Stop(); cout << "Time using Unuran method " << unr.MethodName() << "\t=\t " << w.CpuTime() << endl; w.Start(); for (int i = 0; i < n; ++i) { double x = f->GetRandom(); h2->Fill( x ); } w.Stop(); cout << "Time using TF1::GetRandom() \t=\t " << w.CpuTime() << endl; c1->cd(++izone); h1->Draw(); c1->cd(++izone); h2->Draw(); std::cout << " chi2 test of UNURAN vs GetRandom generated histograms: " << std::endl; h1->Chi2Test(h2,"UUP"); } // 3D gaussian distribution double gaus3d(double *x, double *p) { double sigma_x = p[0]; double sigma_y = p[1]; double sigma_z = p[2]; double rho = p[2]; double u = x[0] / sigma_x ; double v = x[1] / sigma_y ; double w = x[2] / sigma_z ; double c = 1 - rho*rho ; double result = (1 / (2 * TMath::Pi() * sigma_x * sigma_y * sigma_z * sqrt(c))) * exp (-(u * u - 2 * rho * u * v + v * v + w*w) / (2 * c)); return result; } // test of unuran passing as input a mluti-dimension distribution object void testDistrMultiDim() { cout << "\nTest Multidimensional distributions\n\n"; TH3D * h1 = new TH3D("h13D","gaussian 3D distribution from Unuran",50,-10,10,50,-10,10,50,-10,10); TH3D * h2 = new TH3D("h23D","gaussian 3D distribution from GetRandom",50,-10,10,50,-10,10,50,-10,10); TF3 * f = new TF3("g3d",gaus3d,-10,10,-10,10,-10,10,3); double par[3] = {2,2,0.5}; f->SetParameters(par); TUnuranMultiContDist dist(f); TUnuran unr(gRandom); //std::string method = "method=vnrou"; //std::string method = "method=hitro;use_boundingrectangle=false "; std::string method = "hitro"; if ( ! unr.Init(dist,method) ) { cout << "Error initializing unuran" << endl; return; } TStopwatch w; w.Start(); double x[3]; for (int i = 0; i < NGEN; ++i) { unr.SampleMulti(x); h1->Fill(x[0],x[1],x[2]); } w.Stop(); cout << "Time using Unuran method " << unr.MethodName() << "\t=\t\t " << w.CpuTime() << endl; assert(c1 != 0); c1->cd(++izone); h1->Draw(); // need to set a reasanable number of points in TF1 to get accettable quality from GetRandom to int np = 200; f->SetNpx(np); f->SetNpy(np); f->SetNpz(np); w.Start(); for (int i = 0; i < NGEN; ++i) { f->GetRandom3(x[0],x[1],x[2]); h2->Fill(x[0],x[1],x[2]); } w.Stop(); cout << "Time using TF1::GetRandom \t\t=\t " << w.CpuTime() << endl; c1->cd(++izone); h2->Draw(); std::cout << " chi2 test of UNURAN vs GetRandom generated histograms: " << std::endl; h1->Chi2Test(h2,"UUP"); } //_____________________________________________ // // example of discrete distributions double poisson(double * x, double * p) { return ROOT::Math::poisson_pdf(int(x[0]),p[0]); } void testDiscDistr() { cout << "\nTest Discrete distributions\n\n"; TH1D * h1 = new TH1D("h1PS","Unuran Poisson prob",20,0,20); TH1D * h2 = new TH1D("h2PS","Poisson dist from TRandom",20,0,20); double mu = 5; TF1 * f = new TF1("fps",poisson,1,0,1); f->SetParameter(0,mu); TUnuranDiscrDist dist2 = TUnuranDiscrDist(f); TUnuran unr; // dari method (needs also the mode) dist2.SetMode(int(mu) ); bool ret = unr.Init(dist2,"dari"); if (!ret) return; TStopwatch w; w.Start(); int n = NGEN; for (int i = 0; i < n; ++i) { int k = unr.SampleDiscr(); h1->Fill( double(k) ); } w.Stop(); cout << "Time using Unuran method " << unr.MethodName() << "\t=\t\t " << w.CpuTime() << endl; w.Start(); for (int i = 0; i < n; ++i) { h2->Fill( gRandom->Poisson(mu) ); } cout << "Time using TRandom::Poisson " << "\t=\t\t " << w.CpuTime() << endl; c1->cd(++izone); h1->SetMarkerStyle(20); h1->Draw("E"); h2->Draw("same"); std::cout << " chi2 test of UNURAN vs TRandom generated histograms: " << std::endl; h1->Chi2Test(h2,"UUP"); } //_____________________________________________ // // example of empirical distributions void testEmpDistr() { cout << "\nTest Empirical distributions using smoothing\n\n"; // start with a set of data // for example 1000 two-gaussian data const int Ndata = 1000; double x[Ndata]; for (int i = 0; i < Ndata; ++i) { if (i < 0.5*Ndata ) x[i] = gRandom->Gaus(-1.,1.); else x[i] = gRandom->Gaus(1.,3.); } TH1D * h0 = new TH1D("h0Ref","Starting data",100,-10,10); TH1D * h1 = new TH1D("h1Unr","Unuran Generated data",100,-10,10); TH1D * h2 = new TH1D("h2GR","Data from TH1::GetRandom",100,-10,10); h0->FillN(Ndata,x,0,1); // fill histogram with starting data TUnuran unr; TUnuranEmpDist dist(x,x+Ndata,1); if (!unr.Init(dist)) return; TStopwatch w; w.Start(); int n = NGEN; for (int i = 0; i < n; ++i) { h1->Fill( unr.Sample() ); } w.Stop(); cout << "Time using Unuran " << unr.MethodName() << "\t=\t\t " << w.CpuTime() << endl; w.Start(); for (int i = 0; i < n; ++i) { h2->Fill( h0->GetRandom() ); } cout << "Time using TH1::GetRandom " << "\t=\t\t " << w.CpuTime() << endl; c1->cd(++izone); h2->Draw(); h1->SetLineColor(kRed); h1->Draw("same"); } void unuranDemo() { //gRandom->SetSeed(0); // load libraries gSystem->Load("libMathCore"); gSystem->Load("libUnuran"); // create canvas c1 = new TCanvas("c1_unuranMulti","Multidimensional distribution",10,10,1000,1000); c1->Divide(2,4); gStyle->SetOptFit(); testStringAPI(); c1->Update(); testDistr1D(); c1->Update(); testDistrMultiDim(); c1->Update(); testDiscDistr(); c1->Update(); testEmpDistr(); c1->Update(); } <|endoftext|>
<commit_before>#include "S_World.h" #include "j1Input.h" #include "SDL\include\SDL.h" #include "j1Scene.h" #include "p2Log.h" #include "j1App.h" #include "j1Map.h" #include "j1Render.h" #include "j1Textures.h" #include "j1Pathfinding.h" #include "j1App.h" #include "j1Player.h" #include "j1Camera.h" #include "j1HUD.h" #include "j1Enemy.h" #include"j1Audio.h" bool S_World::Start() { App->camera->Enable(); App->hud->Enable(); App->collision->Enable(); App->map->Enable(); App->player->Enable(); App->object->Enable(); LOG("IM FUCKING STARTING!!"); if (App->map->Load("tutorial map test.tmx") == true) { int w, h = 0; uchar* data = NULL; if (App->map->CreateWalkabilityMap(w, h, &data)) App->pathfinding->SetMap(w, h); for (int i = 0; i < App->object->V_Objects.size(); i++) { if (App->object->V_Objects[i]->collider_tiles.size() > 0) { App->object->CreateColliders(*App->object->V_Objects[i]); } } int w_two, h_two = 0; uchar* data_two = NULL; if (App->map->CreateEnemyMap(w_two, h_two, &data_two)) { int w_three = 0; int h_three = 0; uchar* data_three = NULL; if (App->map->CreateEnemyPathMap(w_three, h_three, &data_three)) { App->enemy->Enable(); } } RELEASE_ARRAY(data); //App->map->CreateLogicMap(); } App->audio->PlayMusic("audio/music/Sewers_Song.ogg", 1); App->render->camera.x = 0; App->render->camera.y = 0; App->player->Link->pos = { 660,1400 }; App->player->Zelda->pos = { 620,1400 }; App->player->Link->logic_height = 1; App->player->Zelda->logic_height = 1; LOG("World Open"); return false; } bool S_World::Update() { //App->map->Draw(); if (App->input->GetKey(SDL_SCANCODE_X) == KEY_DOWN) { App->player->loop_game_menu = true; } return false; } bool S_World::PostUpdate() { if (App->player->loop_game_menu == true || App->player->half_hearts_test_purpose <= 0) { App->player->Disable(); App->enemy->Disable(); App->map->Disable(); App->collision->Disable(); App->hud->Disable(); App->object->Disable(); App->scene->ChangeScene(Scene_ID::Send); App->player->loop_game_menu = false; App->player->half_hearts_test_purpose = App->player->hearts_containers_test_purpose * 2; } return true; } bool S_World::Clean() { LOG("World Test Deleted"); //std::list <TileSet*>::iterator temp = App->map->data.tilesets.begin(); for (std::list <TileSet*>::iterator temp = App->map->data.tilesets.begin(); temp != App->map->data.tilesets.cend(); ++temp) { App->tex->UnLoad((*temp)->texture); } /*p2List_item<TileSet*>* temp = App->map->data.tilesets.start; while (temp != NULL) { App->tex->UnLoad(temp->data->texture); temp = temp->next; }*/ App->map->CleanUp(); return false; } <commit_msg>when game finishes main menu have image end<commit_after>#include "S_World.h" #include "j1Input.h" #include "SDL\include\SDL.h" #include "j1Scene.h" #include "p2Log.h" #include "j1App.h" #include "j1Map.h" #include "j1Render.h" #include "j1Textures.h" #include "j1Pathfinding.h" #include "j1App.h" #include "j1Player.h" #include "j1Camera.h" #include "j1HUD.h" #include "j1Enemy.h" #include"j1Audio.h" #include"j1GameStartMenuBack.h" bool S_World::Start() { App->camera->Enable(); App->hud->Enable(); App->collision->Enable(); App->map->Enable(); App->player->Enable(); App->object->Enable(); LOG("IM FUCKING STARTING!!"); if (App->map->Load("tutorial map test.tmx") == true) { int w, h = 0; uchar* data = NULL; if (App->map->CreateWalkabilityMap(w, h, &data)) App->pathfinding->SetMap(w, h); for (int i = 0; i < App->object->V_Objects.size(); i++) { if (App->object->V_Objects[i]->collider_tiles.size() > 0) { App->object->CreateColliders(*App->object->V_Objects[i]); } } int w_two, h_two = 0; uchar* data_two = NULL; if (App->map->CreateEnemyMap(w_two, h_two, &data_two)) { int w_three = 0; int h_three = 0; uchar* data_three = NULL; if (App->map->CreateEnemyPathMap(w_three, h_three, &data_three)) { App->enemy->Enable(); } } RELEASE_ARRAY(data); //App->map->CreateLogicMap(); } App->audio->PlayMusic("audio/music/Sewers_Song.ogg", 1); App->render->camera.x = 0; App->render->camera.y = 0; App->player->Link->pos = { 660,1400 }; App->player->Zelda->pos = { 620,1400 }; App->player->Link->logic_height = 1; App->player->Zelda->logic_height = 1; LOG("World Open"); return false; } bool S_World::Update() { //App->map->Draw(); if (App->input->GetKey(SDL_SCANCODE_X) == KEY_DOWN) { App->player->loop_game_menu = true; } return false; } bool S_World::PostUpdate() { if (App->player->loop_game_menu == true || App->player->half_hearts_test_purpose <= 0) { App->player->Disable(); App->enemy->Disable(); App->map->Disable(); App->collision->Disable(); App->hud->Disable(); App->object->Disable(); App->scene->ChangeScene(Scene_ID::Send); App->startmenuback->Freeze(false); App->player->loop_game_menu = false; App->player->half_hearts_test_purpose = App->player->hearts_containers_test_purpose * 2; } return true; } bool S_World::Clean() { LOG("World Test Deleted"); //std::list <TileSet*>::iterator temp = App->map->data.tilesets.begin(); for (std::list <TileSet*>::iterator temp = App->map->data.tilesets.begin(); temp != App->map->data.tilesets.cend(); ++temp) { App->tex->UnLoad((*temp)->texture); } /*p2List_item<TileSet*>* temp = App->map->data.tilesets.start; while (temp != NULL) { App->tex->UnLoad(temp->data->texture); temp = temp->next; }*/ App->map->CleanUp(); return false; } <|endoftext|>
<commit_before>#ifndef MTL_STREAM_CHANNEL_NETLINKsocketManager #define MTL_STREAM_CHANNEL_NETLINKsocketManager #include <utility> #include <functional> #include <vector> #include <memory> #include <thread> #include <array> #include "netLink/netLink.h" namespace mtl { namespace netLink { template<typename Stream> struct stream_sender : public stream_channel_demuxer<Stream> { using socket = ::netLink::Socket; using manager = ::netLink::SocketManager; stream_sender(const std::string& host, unsigned port, bool server = false) { _server = server; _socket = _manager.newMsgPackSocket(); //Define a callback, fired when a new client tries to connect _manager.onConnectRequest = [](manager* manager, std::shared_ptr<socket> serverSocket, std::shared_ptr<socket> clientSocket) { std::cout << "Accepted connection from " << clientSocket->hostRemote << ":" << clientSocket->portRemote << std::endl; //Accept all new connections return true; }; //Define a callback, fired when a sockets state changes _manager.onStatusChange = [](manager* manager, std::shared_ptr<socket> socket, socket::Status prev) { ::netLink::MsgPackSocket& msgPackSocket = *static_cast<::netLink::MsgPackSocket*>(socket.get()); switch (socket->getStatus()) { case ::netLink::Socket::Status::READY: std::cout << "Connection got accepted at " << socket->hostRemote << ":" << socket->portRemote << std::endl; break; case ::netLink::Socket::Status::NOT_CONNECTED: if (prev == ::netLink::Socket::Status::CONNECTING) std::cout << "Connecting to " << socket->hostRemote << ":" << socket->portRemote << std::endl << " failed"; else std::cout << "Lost connection of " << socket->hostRemote << ":" << socket->portRemote << std::endl; break; default: std::cout << "Status of " << socket->hostRemote << ":" << socket->portRemote << " changed from " << prev << " to " << socket->getStatus() << std::endl; break; } }; //Define a callback, fired when a socket receives data _manager.onReceiveMsgPack = [&](manager* manager, std::shared_ptr<socket> socket, std::unique_ptr<MsgPack::Element> element) { //hostRemote and portRemote are now set to the origin of the last received message std::cout << "Received data from " << socket->hostRemote << ":" << socket->portRemote << ": " << *element << std::endl; // Parse the *element auto arr = dynamic_cast<MsgPack::Array*>(element.get()); if (!arr) return; auto element_id = dynamic_cast<MsgPack::Number*>(arr->getEntry(0)); auto element_stream = dynamic_cast<MsgPack::String*>(arr->getEntry(1)); if (!element_id || !element_stream) return; id_type id = element_id->getValue<uint64_t>(); Stream ss; ss.write( element_stream->getData(), element_stream->getLength() ); receive_stream(id, ss); }; _socket->hostRemote = host; if (_server) _socket->initAsTcpServer(host, port); else _socket->initAsTcpClient(host, port); } void start_listening() { _thread = std::make_unique<std::thread>([&]() { while (_socket->getStatus() != ::netLink::Socket::Status::NOT_CONNECTED) _manager.listen(); }); } auto& streams() { return _streams; } protected: void send_stream(id_type id, Stream& ss) override { auto& msgPackSocket = *static_cast<::netLink::MsgPackSocket*>(_socket.get()); msgPackSocket << MsgPack__Factory(ArrayHeader(2)); msgPackSocket << MsgPack::Factory((uint64_t)id); msgPackSocket << MsgPack::Factory(ss.str()); } bool _server = false; std::shared_ptr<socket> _socket; manager _manager; std::unique_ptr<std::thread> _thread; }; } } #endif<commit_msg>fixed netLink stream<commit_after>#ifndef MTL_STREAM_CHANNEL_NETLINKsocketManager #define MTL_STREAM_CHANNEL_NETLINKsocketManager #include <utility> #include <functional> #include <vector> #include <memory> #include <thread> #include <array> #include "netLink/netLink.h" namespace mtl { namespace netLink { template<typename Stream> struct stream_sender : public stream_channel_demuxer<Stream> { using socket = ::netLink::Socket; using manager = ::netLink::SocketManager; stream_sender(const std::string& host, unsigned port, bool server = false) { _server = server; _socket = _manager.newMsgPackSocket(); //Define a callback, fired when a new client tries to connect _manager.onConnectRequest = [](manager* manager, std::shared_ptr<socket> serverSocket, std::shared_ptr<socket> clientSocket) { std::cout << "Accepted connection from " << clientSocket->hostRemote << ":" << clientSocket->portRemote << std::endl; //Accept all new connections return true; }; //Define a callback, fired when a sockets state changes _manager.onStatusChange = [](manager* manager, std::shared_ptr<socket> socket, socket::Status prev) { ::netLink::MsgPackSocket& msgPackSocket = *static_cast<::netLink::MsgPackSocket*>(socket.get()); switch (socket->getStatus()) { case ::netLink::Socket::Status::READY: std::cout << "Connection got accepted at " << socket->hostRemote << ":" << socket->portRemote << std::endl; break; case ::netLink::Socket::Status::NOT_CONNECTED: if (prev == ::netLink::Socket::Status::CONNECTING) std::cout << "Connecting to " << socket->hostRemote << ":" << socket->portRemote << std::endl << " failed"; else std::cout << "Lost connection of " << socket->hostRemote << ":" << socket->portRemote << std::endl; break; default: std::cout << "Status of " << socket->hostRemote << ":" << socket->portRemote << " changed from " << prev << " to " << socket->getStatus() << std::endl; break; } }; //Define a callback, fired when a socket receives data _manager.onReceiveMsgPack = [&](manager* manager, std::shared_ptr<socket> socket, std::unique_ptr<MsgPack::Element> element) { ::netLink::MsgPackSocket& msgPackSocket = *static_cast<::netLink::MsgPackSocket*>(socket.get()); auto guard = context<::netLink::MsgPackSocket>::lock(msgPackSocket); //hostRemote and portRemote are now set to the origin of the last received message std::cout << "Received data from " << socket->hostRemote << ":" << socket->portRemote << ": " << *element << std::endl; // Parse the *element auto arr = dynamic_cast<MsgPack::Array*>(element.get()); if (!arr) return; auto element_id = dynamic_cast<MsgPack::Number*>(arr->getEntry(0)); auto element_stream = dynamic_cast<MsgPack::String*>(arr->getEntry(1)); if (!element_id || !element_stream) return; id_type id = element_id->getValue<uint64_t>(); Stream ss; ss.write( element_stream->getData(), element_stream->getLength() ); receive_stream(id, ss); }; _socket->hostRemote = host; if (_server) _socket->initAsTcpServer(host, port); else _socket->initAsTcpClient(host, port); } void start_listening() { _thread = std::make_unique<std::thread>([&]() { while (_socket->getStatus() != ::netLink::Socket::Status::NOT_CONNECTED) _manager.listen(); }); } auto& streams() { return _streams; } protected: void send_stream(id_type id, Stream& ss) override { auto& msgPackSocket = !_server ? *static_cast<::netLink::MsgPackSocket*>(_socket.get()) : context<::netLink::MsgPackSocket>::current(); msgPackSocket << MsgPack__Factory(ArrayHeader(2)); msgPackSocket << MsgPack::Factory((uint64_t)id); msgPackSocket << MsgPack::Factory(ss.str()); } bool _server = false; std::shared_ptr<socket> _socket; manager _manager; std::unique_ptr<std::thread> _thread; }; } } #endif<|endoftext|>
<commit_before>#include "FanCalculatorScene.h" #include "../mahjong-algorithm/stringify.h" #include "../mahjong-algorithm/fan_calculator.h" #include "../widget/TilePickWidget.h" #include "../widget/ExtraInfoWidget.h" #include "../widget/AlertView.h" #include "../widget/TilesKeyboard.h" USING_NS_CC; Scene *FanCalculatorScene::createScene() { auto scene = Scene::create(); auto layer = FanCalculatorScene::create(); scene->addChild(layer); return scene; } bool FanCalculatorScene::init() { if (UNLIKELY(!BaseLayer::initWithTitle("国标麻将算番器"))) { return false; } Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); // 选牌面板 TilePickWidget *tilePicker = TilePickWidget::create(); const Size &widgetSize = tilePicker->getContentSize(); this->addChild(tilePicker); tilePicker->setPosition(Vec2(origin.x + visibleSize.width * 0.5f, origin.y + visibleSize.height - 35 - widgetSize.height * 0.5f)); _tilePicker = tilePicker; // 其他信息的相关控件 ExtraInfoWidget *extraInfo = ExtraInfoWidget::create(); const Size &extraSize = extraInfo->getContentSize(); this->addChild(extraInfo); extraInfo->setPosition(Vec2(origin.x + visibleSize.width * 0.5f, origin.y + visibleSize.height - 35 - widgetSize.height - 5 - extraSize.height * 0.5f)); _extraInfo = extraInfo; // 直接输入 ui::Button *button = ui::Button::create("source_material/btn_square_highlighted.png", "source_material/btn_square_selected.png"); button->setScale9Enabled(true); button->setContentSize(Size(55.0f, 20.0f)); button->setTitleFontSize(12); button->setTitleText("直接输入"); extraInfo->addChild(button); button->setPosition(Vec2(visibleSize.width - 40, 100.0f)); button->addClickEventListener([this](Ref *) { showInputAlert(nullptr); }); // 番算按钮 button = ui::Button::create("source_material/btn_square_highlighted.png", "source_material/btn_square_selected.png"); button->setScale9Enabled(true); button->setContentSize(Size(45.0f, 20.0f)); button->setTitleFontSize(12); button->setTitleText("算番"); extraInfo->addChild(button); button->setPosition(Vec2(visibleSize.width - 35, 10.0f)); button->addClickEventListener([this](Ref *) { calculate(); }); // 番种显示的Node Size areaSize(visibleSize.width, visibleSize.height - 35 - widgetSize.height - 5 - extraSize.height - 10); _fanAreaNode = Node::create(); _fanAreaNode->setContentSize(areaSize); _fanAreaNode->setAnchorPoint(Vec2::ANCHOR_MIDDLE); _fanAreaNode->setIgnoreAnchorPointForPosition(false); this->addChild(_fanAreaNode); _fanAreaNode->setPosition(Vec2(origin.x + visibleSize.width * 0.5f, origin.y + areaSize.height * 0.5f + 5)); tilePicker->setFixedPacksChangedCallback([tilePicker, extraInfo]() { extraInfo->refreshByKong(tilePicker->isFixedPacksContainsKong()); }); tilePicker->setWinTileChangedCallback([tilePicker, extraInfo]() { ExtraInfoWidget::RefreshByWinTile rt; rt.getWinTile = std::bind(&TilePickWidget::getServingTile, tilePicker); rt.isStandingTilesContainsServingTile = std::bind(&TilePickWidget::isStandingTilesContainsServingTile, tilePicker); rt.countServingTileInFixedPacks = std::bind(&TilePickWidget::countServingTileInFixedPacks, tilePicker); rt.isFixedPacksContainsKong = std::bind(&HandTilesWidget::isFixedPacksContainsKong, tilePicker); extraInfo->refreshByWinTile(rt); }); return true; } cocos2d::Node *createFanResultNode(const long (&fan_table)[mahjong::FAN_TABLE_SIZE], int fontSize, float resultAreaWidth) { // 有n个番种,每行排2个 long n = mahjong::FAN_TABLE_SIZE - std::count(std::begin(fan_table), std::end(fan_table), 0); long rows = (n >> 1) + (n & 1); // 需要这么多行 // 排列 Node *node = Node::create(); const int lineHeight = fontSize + 2; long resultAreaHeight = lineHeight * rows; // 每行间隔2像素 resultAreaHeight += (3 + lineHeight); // 总计 node->setContentSize(Size(resultAreaWidth, resultAreaHeight)); long fan = 0; for (int i = 0, j = 0; i < n; ++i) { while (fan_table[++j] == 0) continue; int f = mahjong::fan_value_table[j]; long n = fan_table[j]; fan += f * n; std::string str = (n == 1) ? StringUtils::format("%s %d番\n", mahjong::fan_name[j], f) : StringUtils::format("%s %d番x%ld\n", mahjong::fan_name[j], f, fan_table[j]); // 创建label,每行排2个 Label *fanName = Label::createWithSystemFont(str, "Arial", fontSize); fanName->setColor(Color3B(0x60, 0x60, 0x60)); node->addChild(fanName); fanName->setAnchorPoint(Vec2::ANCHOR_MIDDLE_LEFT); div_t ret = div(i, 2); fanName->setPosition(Vec2(ret.rem == 0 ? 10.0f : resultAreaWidth * 0.5f, resultAreaHeight - lineHeight * (ret.quot + 0.5f))); } Label *fanTotal = Label::createWithSystemFont(StringUtils::format("总计:%ld番", fan), "Arial", fontSize); fanTotal->setColor(Color3B::BLACK); node->addChild(fanTotal); fanTotal->setAnchorPoint(Vec2::ANCHOR_MIDDLE_LEFT); fanTotal->setPosition(Vec2(10.0f, lineHeight * 0.5f)); return node; } void FanCalculatorScene::showInputAlert(const char *prevInput) { Size visibleSize = Director::getInstance()->getVisibleSize(); const float width = visibleSize.width * 0.8f - 10; ui::Widget *rootWidget = ui::Widget::create(); Label *label = Label::createWithSystemFont("使用说明:\n" "1." INPUT_GUIDE_STRING_1 "\n" "2." INPUT_GUIDE_STRING_2 "\n" "3." INPUT_GUIDE_STRING_3 "\n" "输入范例1:[EEEE][CCCC][FFFF][PPPP]NN\n" "输入范例2:1112345678999s9s\n" "输入范例3:WWWW 444s 45m678pFF6m\n", "Arial", 10); label->setColor(Color3B::BLACK); label->setDimensions(width, 0); rootWidget->addChild(label); // 输入手牌 ui::EditBox *editBox = ui::EditBox::create(Size(width - 10, 20.0f), ui::Scale9Sprite::create("source_material/btn_square_normal.png")); editBox->setInputFlag(ui::EditBox::InputFlag::SENSITIVE); editBox->setInputMode(ui::EditBox::InputMode::SINGLE_LINE); editBox->setFontColor(Color4B::BLACK); editBox->setFontSize(12); editBox->setPlaceholderFontColor(Color4B::GRAY); editBox->setPlaceHolder("输入手牌"); if (prevInput != nullptr) { editBox->setText(prevInput); } TilesKeyboard::hookEditBox(editBox); rootWidget->addChild(editBox); const Size &labelSize = label->getContentSize(); rootWidget->setContentSize(Size(width, labelSize.height + 30)); editBox->setPosition(Vec2(width * 0.5f, 10)); label->setPosition(Vec2(width * 0.5f, labelSize.height * 0.5f + 30)); AlertView::showWithNode("直接输入", rootWidget, [this, editBox]() { const char *input = editBox->getText(); const char *errorStr = TilesKeyboard::parseInput(input, std::bind(&TilePickWidget::setData, _tilePicker, std::placeholders::_1, std::placeholders::_2)); if (errorStr != nullptr) { const std::string str = input; AlertView::showWithMessage("直接输入牌", errorStr, 12, [this, str]() { showInputAlert(str.c_str()); }, nullptr); } }, nullptr); } void FanCalculatorScene::calculate() { _fanAreaNode->removeAllChildren(); const Size &fanAreaSize = _fanAreaNode->getContentSize(); Vec2 pos(fanAreaSize.width * 0.5f, fanAreaSize.height * 0.5f); int flowerCnt = _extraInfo->getFlowerCount(); if (flowerCnt > 8) { AlertView::showWithMessage("算番", "花牌数的范围为0~8", 12, nullptr, nullptr); return; } mahjong::calculate_param_t param; _tilePicker->getData(&param.hand_tiles, &param.win_tile); if (param.win_tile == 0) { AlertView::showWithMessage("算番", "牌张数错误", 12, nullptr, nullptr); return; } std::sort(param.hand_tiles.standing_tiles, param.hand_tiles.standing_tiles + param.hand_tiles.tile_count); param.flower_count = flowerCnt; long fan_table[mahjong::FAN_TABLE_SIZE] = { 0 }; // 获取绝张、杠开、抢杠、海底信息 mahjong::win_flag_t win_flag = _extraInfo->getWinFlag(); // 获取圈风门风 mahjong::wind_t prevalent_wind = _extraInfo->getPrevalentWind(); mahjong::wind_t seat_wind = _extraInfo->getSeatWind(); // 算番 param.ext_cond.win_flag = win_flag; param.ext_cond.prevalent_wind = prevalent_wind; param.ext_cond.seat_wind = seat_wind; int fan = calculate_fan(&param, fan_table); if (fan == ERROR_NOT_WIN) { Label *errorLabel = Label::createWithSystemFont("诈和", "Arial", 14); errorLabel->setColor(Color3B::BLACK); _fanAreaNode->addChild(errorLabel); errorLabel->setPosition(pos); return; } if (fan == ERROR_WRONG_TILES_COUNT) { AlertView::showWithMessage("算番", "牌张数错误", 12, nullptr, nullptr); return; } if (fan == ERROR_TILE_COUNT_GREATER_THAN_4) { AlertView::showWithMessage("算番", "同一种牌最多只能使用4枚", 12, nullptr, nullptr); return; } Node *innerNode = createFanResultNode(fan_table, 14, fanAreaSize.width); // 超出高度就使用ScrollView if (innerNode->getContentSize().height <= fanAreaSize.height) { _fanAreaNode->addChild(innerNode); innerNode->setAnchorPoint(Vec2(0.5f, 0.5f)); innerNode->setPosition(pos); } else { ui::ScrollView *scrollView = ui::ScrollView::create(); scrollView->setDirection(ui::ScrollView::Direction::VERTICAL); scrollView->setScrollBarPositionFromCorner(Vec2(10, 10)); scrollView->setContentSize(fanAreaSize); scrollView->setInnerContainerSize(innerNode->getContentSize()); scrollView->addChild(innerNode); _fanAreaNode->addChild(scrollView); scrollView->setAnchorPoint(Vec2(0.5f, 0.5f)); scrollView->setPosition(pos); } } <commit_msg>no message<commit_after>#include "FanCalculatorScene.h" #include "../mahjong-algorithm/stringify.h" #include "../mahjong-algorithm/fan_calculator.h" #include "../widget/TilePickWidget.h" #include "../widget/ExtraInfoWidget.h" #include "../widget/AlertView.h" #include "../widget/TilesKeyboard.h" USING_NS_CC; Scene *FanCalculatorScene::createScene() { auto scene = Scene::create(); auto layer = FanCalculatorScene::create(); scene->addChild(layer); return scene; } bool FanCalculatorScene::init() { if (UNLIKELY(!BaseLayer::initWithTitle("国标麻将算番器"))) { return false; } Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); // 选牌面板 TilePickWidget *tilePicker = TilePickWidget::create(); const Size &widgetSize = tilePicker->getContentSize(); this->addChild(tilePicker); tilePicker->setPosition(Vec2(origin.x + visibleSize.width * 0.5f, origin.y + visibleSize.height - 35 - widgetSize.height * 0.5f)); _tilePicker = tilePicker; // 其他信息的相关控件 ExtraInfoWidget *extraInfo = ExtraInfoWidget::create(); const Size &extraSize = extraInfo->getContentSize(); this->addChild(extraInfo); extraInfo->setPosition(Vec2(origin.x + visibleSize.width * 0.5f, origin.y + visibleSize.height - 35 - widgetSize.height - 5 - extraSize.height * 0.5f)); _extraInfo = extraInfo; // 直接输入 ui::Button *button = ui::Button::create("source_material/btn_square_highlighted.png", "source_material/btn_square_selected.png"); button->setScale9Enabled(true); button->setContentSize(Size(55.0f, 20.0f)); button->setTitleFontSize(12); button->setTitleText("直接输入"); extraInfo->addChild(button); button->setPosition(Vec2(visibleSize.width - 40, 100.0f)); button->addClickEventListener([this](Ref *) { showInputAlert(nullptr); }); // 番算按钮 button = ui::Button::create("source_material/btn_square_highlighted.png", "source_material/btn_square_selected.png"); button->setScale9Enabled(true); button->setContentSize(Size(45.0f, 20.0f)); button->setTitleFontSize(12); button->setTitleText("算番"); extraInfo->addChild(button); button->setPosition(Vec2(visibleSize.width - 35, 10.0f)); button->addClickEventListener([this](Ref *) { calculate(); }); // 番种显示的Node Size areaSize(visibleSize.width, visibleSize.height - 35 - widgetSize.height - 5 - extraSize.height - 10); _fanAreaNode = Node::create(); _fanAreaNode->setContentSize(areaSize); _fanAreaNode->setAnchorPoint(Vec2::ANCHOR_MIDDLE); _fanAreaNode->setIgnoreAnchorPointForPosition(false); this->addChild(_fanAreaNode); _fanAreaNode->setPosition(Vec2(origin.x + visibleSize.width * 0.5f, origin.y + areaSize.height * 0.5f + 5)); tilePicker->setFixedPacksChangedCallback([tilePicker, extraInfo]() { extraInfo->refreshByKong(tilePicker->isFixedPacksContainsKong()); }); tilePicker->setWinTileChangedCallback([tilePicker, extraInfo]() { ExtraInfoWidget::RefreshByWinTile rt; rt.getWinTile = std::bind(&TilePickWidget::getServingTile, tilePicker); rt.isStandingTilesContainsServingTile = std::bind(&TilePickWidget::isStandingTilesContainsServingTile, tilePicker); rt.countServingTileInFixedPacks = std::bind(&TilePickWidget::countServingTileInFixedPacks, tilePicker); rt.isFixedPacksContainsKong = std::bind(&TilePickWidget::isFixedPacksContainsKong, tilePicker); extraInfo->refreshByWinTile(rt); }); return true; } cocos2d::Node *createFanResultNode(const long (&fan_table)[mahjong::FAN_TABLE_SIZE], int fontSize, float resultAreaWidth) { // 有n个番种,每行排2个 long n = mahjong::FAN_TABLE_SIZE - std::count(std::begin(fan_table), std::end(fan_table), 0); long rows = (n >> 1) + (n & 1); // 需要这么多行 // 排列 Node *node = Node::create(); const int lineHeight = fontSize + 2; long resultAreaHeight = lineHeight * rows; // 每行间隔2像素 resultAreaHeight += (3 + lineHeight); // 总计 node->setContentSize(Size(resultAreaWidth, resultAreaHeight)); long fan = 0; for (int i = 0, j = 0; i < n; ++i) { while (fan_table[++j] == 0) continue; int f = mahjong::fan_value_table[j]; long n = fan_table[j]; fan += f * n; std::string str = (n == 1) ? StringUtils::format("%s %d番\n", mahjong::fan_name[j], f) : StringUtils::format("%s %d番x%ld\n", mahjong::fan_name[j], f, fan_table[j]); // 创建label,每行排2个 Label *fanName = Label::createWithSystemFont(str, "Arial", fontSize); fanName->setColor(Color3B(0x60, 0x60, 0x60)); node->addChild(fanName); fanName->setAnchorPoint(Vec2::ANCHOR_MIDDLE_LEFT); div_t ret = div(i, 2); fanName->setPosition(Vec2(ret.rem == 0 ? 10.0f : resultAreaWidth * 0.5f, resultAreaHeight - lineHeight * (ret.quot + 0.5f))); } Label *fanTotal = Label::createWithSystemFont(StringUtils::format("总计:%ld番", fan), "Arial", fontSize); fanTotal->setColor(Color3B::BLACK); node->addChild(fanTotal); fanTotal->setAnchorPoint(Vec2::ANCHOR_MIDDLE_LEFT); fanTotal->setPosition(Vec2(10.0f, lineHeight * 0.5f)); return node; } void FanCalculatorScene::showInputAlert(const char *prevInput) { Size visibleSize = Director::getInstance()->getVisibleSize(); const float width = visibleSize.width * 0.8f - 10; ui::Widget *rootWidget = ui::Widget::create(); Label *label = Label::createWithSystemFont("使用说明:\n" "1." INPUT_GUIDE_STRING_1 "\n" "2." INPUT_GUIDE_STRING_2 "\n" "3." INPUT_GUIDE_STRING_3 "\n" "输入范例1:[EEEE][CCCC][FFFF][PPPP]NN\n" "输入范例2:1112345678999s9s\n" "输入范例3:WWWW 444s 45m678pFF6m\n", "Arial", 10); label->setColor(Color3B::BLACK); label->setDimensions(width, 0); rootWidget->addChild(label); // 输入手牌 ui::EditBox *editBox = ui::EditBox::create(Size(width - 10, 20.0f), ui::Scale9Sprite::create("source_material/btn_square_normal.png")); editBox->setInputFlag(ui::EditBox::InputFlag::SENSITIVE); editBox->setInputMode(ui::EditBox::InputMode::SINGLE_LINE); editBox->setFontColor(Color4B::BLACK); editBox->setFontSize(12); editBox->setPlaceholderFontColor(Color4B::GRAY); editBox->setPlaceHolder("输入手牌"); if (prevInput != nullptr) { editBox->setText(prevInput); } TilesKeyboard::hookEditBox(editBox); rootWidget->addChild(editBox); const Size &labelSize = label->getContentSize(); rootWidget->setContentSize(Size(width, labelSize.height + 30)); editBox->setPosition(Vec2(width * 0.5f, 10)); label->setPosition(Vec2(width * 0.5f, labelSize.height * 0.5f + 30)); AlertView::showWithNode("直接输入", rootWidget, [this, editBox]() { const char *input = editBox->getText(); const char *errorStr = TilesKeyboard::parseInput(input, std::bind(&TilePickWidget::setData, _tilePicker, std::placeholders::_1, std::placeholders::_2)); if (errorStr != nullptr) { const std::string str = input; AlertView::showWithMessage("直接输入牌", errorStr, 12, [this, str]() { showInputAlert(str.c_str()); }, nullptr); } }, nullptr); } void FanCalculatorScene::calculate() { _fanAreaNode->removeAllChildren(); const Size &fanAreaSize = _fanAreaNode->getContentSize(); Vec2 pos(fanAreaSize.width * 0.5f, fanAreaSize.height * 0.5f); int flowerCnt = _extraInfo->getFlowerCount(); if (flowerCnt > 8) { AlertView::showWithMessage("算番", "花牌数的范围为0~8", 12, nullptr, nullptr); return; } mahjong::calculate_param_t param; _tilePicker->getData(&param.hand_tiles, &param.win_tile); if (param.win_tile == 0) { AlertView::showWithMessage("算番", "牌张数错误", 12, nullptr, nullptr); return; } std::sort(param.hand_tiles.standing_tiles, param.hand_tiles.standing_tiles + param.hand_tiles.tile_count); param.flower_count = flowerCnt; long fan_table[mahjong::FAN_TABLE_SIZE] = { 0 }; // 获取绝张、杠开、抢杠、海底信息 mahjong::win_flag_t win_flag = _extraInfo->getWinFlag(); // 获取圈风门风 mahjong::wind_t prevalent_wind = _extraInfo->getPrevalentWind(); mahjong::wind_t seat_wind = _extraInfo->getSeatWind(); // 算番 param.ext_cond.win_flag = win_flag; param.ext_cond.prevalent_wind = prevalent_wind; param.ext_cond.seat_wind = seat_wind; int fan = calculate_fan(&param, fan_table); if (fan == ERROR_NOT_WIN) { Label *errorLabel = Label::createWithSystemFont("诈和", "Arial", 14); errorLabel->setColor(Color3B::BLACK); _fanAreaNode->addChild(errorLabel); errorLabel->setPosition(pos); return; } if (fan == ERROR_WRONG_TILES_COUNT) { AlertView::showWithMessage("算番", "牌张数错误", 12, nullptr, nullptr); return; } if (fan == ERROR_TILE_COUNT_GREATER_THAN_4) { AlertView::showWithMessage("算番", "同一种牌最多只能使用4枚", 12, nullptr, nullptr); return; } Node *innerNode = createFanResultNode(fan_table, 14, fanAreaSize.width); // 超出高度就使用ScrollView if (innerNode->getContentSize().height <= fanAreaSize.height) { _fanAreaNode->addChild(innerNode); innerNode->setAnchorPoint(Vec2(0.5f, 0.5f)); innerNode->setPosition(pos); } else { ui::ScrollView *scrollView = ui::ScrollView::create(); scrollView->setDirection(ui::ScrollView::Direction::VERTICAL); scrollView->setScrollBarPositionFromCorner(Vec2(10, 10)); scrollView->setContentSize(fanAreaSize); scrollView->setInnerContainerSize(innerNode->getContentSize()); scrollView->addChild(innerNode); _fanAreaNode->addChild(scrollView); scrollView->setAnchorPoint(Vec2(0.5f, 0.5f)); scrollView->setPosition(pos); } } <|endoftext|>
<commit_before>// Example of analysis class for the H1 data using code generated by MakeProxy. // =========================================================================== // // This file uses 4 large data sets from the H1 collaboration at DESY Hamburg. // One can access these data sets (277 MBytes) from the standard Root web site // at: ftp://root.cern.ch/root/h1analysis/ // The Physics plots below generated by this example cannot be produced when // using smaller data sets. // // There are several ways to analyze data stored in a Root Tree // -Using TTree::Draw: This is very convenient and efficient for small tasks. // A TTree::Draw call produces one histogram at the time. The histogram // is automatically generated. The selection expression may be specified // in the command line. // // -Using the TTreeViewer: This is a graphical interface to TTree::Draw // with the same functionality. // // -Using the code generated by TTree::MakeClass: In this case, the user // creates an instance of the analysis class. He has the control over // the event loop and he can generate an unlimited number of histograms. // // -Using the code generated by TTree::MakeSelector. Like for the code // generated by TTree::MakeClass, the user can do complex analysis. // However, he cannot control the event loop. The event loop is controlled // by TTree::Process called by the user. This solution is illustrated // by the current code. The advantage of this method is that it can be run // in a parallel environment using PROOF (the Parallel Root Facility). // // A chain of 4 files (originally converted from PAW ntuples) is used // to illustrate the various ways to loop on Root data sets. // Each data set contains a Root Tree named "h42" // The class definition in h1analysis.h has been generated automatically // by the Root utility TTree::MakeSelector using one of the files with the // following statement: // h42->MakeSelector("h1analysis"); // This produces two files: h1analysis.h and h1analysis.C (skeleton of this file) // The h1analysis class is derived from the Root class TSelector. // // The following members functions are called by the TTree::Process functions. // Begin(): called everytime a loop on the tree starts. // a convenient place to create your histograms. // SlaveBegin(): // // Notify(): This function is called at the first entry of a new Tree // in a chain. // Process(): called to analyze each entry. // // SlaveTerminate(): // // Terminate(): called at the end of a loop on a TTree. // a convenient place to draw/fit your histograms. // // To use this file, try the following session // // Root > gROOT->Time(); //will show RT & CPU time per command // //==> A- create a TChain with the 4 H1 data files // The chain can be created by executed the short macro h1chain.C below: // { // TChain chain("h42"); // chain.Add("$H1/dstarmb.root"); // 21330730 bytes 21920 events // chain.Add("$H1/dstarp1a.root"); // 71464503 bytes 73243 events // chain.Add("$H1/dstarp1b.root"); // 83827959 bytes 85597 events // chain.Add("$H1/dstarp2.root"); // 100675234 bytes 103053 events // //where $H1 is a system symbol pointing to the H1 data directory. // } // // Root > .x h1chain.C // //==> B- loop on all events // Root > chain.Process("h1analysis.C") // //==> C- same as B, but in addition fill the event list with selected entries. // The event list is saved to a file "elist.root" by the Terminate function. // To see the list of selected events, you can do elist->Print("all"). // The selection function has selected 7525 events out of the 283813 events // in the chain of files. (2.65 per cent) // Root > chain.Process("h1analysis.C","fillList") // //==> D- Process only entries in the event list // The event list is read from the file in elist.root generated by step C // Root > chain.Process("h1analysis.C","useList") // //==> E- the above steps have been executed via the interpreter. // You can repeat the steps B, C and D using the script compiler // by replacing "h1analysis.C" by "h1analysis.C+" or "h1analysis.C++" // // in a new session with ,eg: // //==> F- Create the chain as in A, then execute // Root > chain.Process("h1analysis.C+","useList") // // The commands executed with the 4 different methods B,C,D and E // produce two canvases shown below: // begin_html <a href="gif/h1analysis_dstar.gif" >the Dstar plot</a> end_html // begin_html <a href="gif/h1analysis_tau.gif" >the Tau D0 plot</a> end_html // //Author; Philippe Canal from original h1analysis.C by Rene Brun TEventList *elist; Bool_t useList, fillList; TH1F *hdmd; TH2F *h2; //_____________________________________________________________________ void h1analysisProxy_Begin(TTree *tree) { // function called before starting the event loop // -it performs some cleanup // -it creates histograms // -it sets some initialisation for the event list //print the option specified in the Process function. TString option = GetOption(); printf("Starting (begin) h1analysis with process option: %s\n",option.Data()); //some cleanup in case this function had already been executed //delete any previously generated histograms or functions gDirectory->Delete("hdmd"); gDirectory->Delete("h2*"); delete gROOT->GetFunction("f5"); delete gROOT->GetFunction("f2"); } //_____________________________________________________________________ void h1analysisProxy_SlaveBegin(TTree *tree) { // function called before starting the event loop // -it performs some cleanup // -it creates histograms // -it sets some initialisation for the event list //initialize the Tree branch addresses Init(tree); //print the option specified in the Process function. TString option = GetOption(); printf("Starting (slave) h1analysis with process option: %s\n",option.Data()); //some cleanup in case this function had already been executed //delete any previously generated histograms or functions gDirectory->Delete("hdmd"); gDirectory->Delete("h2*"); delete gROOT->GetFunction("f5"); delete gROOT->GetFunction("f2"); //create histograms hdmd = new TH1F("hdmd","dm_d",40,0.13,0.17); h2 = new TH2F("h2","ptD0 vs dm_d",30,0.135,0.165,30,-3,6); fOutput->Add(hdmd); fOutput->Add(h2); //process cases with event list fillList = kFALSE; useList = kFALSE; tree->SetEventList(0); delete gDirectory->GetList()->FindObject("elist"); // case when one creates/fills the event list if (option.Contains("fillList")) { fillList = kTRUE; elist = new TEventList("elist","selection from Cut",5000); } else elist = 0; // case when one uses the event list generated in a previous call if (option.Contains("useList")) { useList = kTRUE; TFile f("elist.root"); elist = (TEventList*)f.Get("elist"); if (elist) elist->SetDirectory(0); //otherwise the file destructor will delete elist tree->SetEventList(elist); } } Double_t h1analysisProxy() { return 0; } //_____________________________________________________________________ Bool_t h1analysisProxy_Process(Int_t entry) { // entry is the entry number in the current Tree // Selection function to select D* and D0. //in case one event list is given in input, the selection has already been done. if (!useList) { float f1 = md0_d; float f2 = md0_d-1.8646; bool test = TMath::Abs(md0_d-1.8646) >= 0.04; if (gDebug>0) fprintf(stderr,"entry #%d f1=%f f2=%f test=%d\n", fChain->GetReadEntry(),f1,f2,test); if (TMath::Abs(md0_d-1.8646) >= 0.04) return kFALSE; if (ptds_d <= 2.5) return kFALSE; if (TMath::Abs(etads_d) >= 1.5) return kFALSE; int cik = ik-1; //original ik used f77 convention starting at 1 int cipi = ipi-1; //original ipi used f77 convention starting at 1 f1 = nhitrp[cik]; f2 = nhitrp[cipi]; test = nhitrp[cik]*nhitrp[cipi] <= 1; if (gDebug>0) fprintf(stderr,"entry #%d f1=%f f2=%f test=%d\n", fChain->GetReadEntry(),f1,f2,test); if (nhitrp[cik]*nhitrp[cipi] <= 1) return kFALSE; if (rend[cik] -rstart[cik] <= 22) return kFALSE; if (rend[cipi]-rstart[cipi] <= 22) return kFALSE; if (nlhk[cik] <= 0.1) return kFALSE; if (nlhpi[cipi] <= 0.1) return kFALSE; // fix because read-only if (nlhpi[ipis-1] <= 0.1) return kFALSE; if (njets < 1) return kFALSE; } // if option fillList, fill the event list if (fillList) elist->Enter(fChain->GetChainEntryNumber(entry)); //fill some histograms hdmd->Fill(dm_d); h2->Fill(dm_d,rpd0_t/0.029979*1.8646/ptd0_d); return kTRUE; } //_____________________________________________________________________ void h1analysisProxy_SlaveTerminate() { // nothing to be done printf("Terminate (slave) h1analysis\n"); } //_____________________________________________________________________ void h1analysisProxy_Terminate() { printf("Terminate (final) h1analysis\n"); // function called at the end of the event loop hdmd = dynamic_cast<TH1F*>(fOutput->FindObject("hdmd")); h2 = dynamic_cast<TH2F*>(fOutput->FindObject("h2")); if (hdmd == 0 || h2 == 0) { Error("Terminate", "hdmd = %p , h2 = %p", hdmd, h2); return; } //create the canvas for the h1analysis fit gStyle->SetOptFit(); TCanvas *c1 = new TCanvas("c1","h1analysis analysis",10,10,800,600); c1->SetBottomMargin(0.15); hdmd->GetXaxis()->SetTitle("m_{K#pi#pi} - m_{K#pi}[GeV/c^{2}]"); hdmd->GetXaxis()->SetTitleOffset(1.4); //fit histogram hdmd with function f5 using the loglikelihood option TF1 *f5 = new TF1("f5",fdm5,0.139,0.17,5); f5->SetParameters(1000000, .25, 2000, .1454, .001); hdmd->Fit("f5","lr"); //create the canvas for tau d0 gStyle->SetOptFit(0); gStyle->SetOptStat(1100); TCanvas *c2 = new TCanvas("c2","tauD0",100,100,800,600); c2->SetGrid(); c2->SetBottomMargin(0.15); // Project slices of 2-d histogram h2 along X , then fit each slice // with function f2 and make a histogram for each fit parameter // Note that the generated histograms are added to the list of objects // in the current directory. TF1 *f2 = new TF1("f2",fdm2,0.139,0.17,2); f2->SetParameters(10000, 10); h2->FitSlicesX(f2,0,0,1,"qln"); TH1D *h2_1 = (TH1D*)gDirectory->Get("h2_1"); h2_1->GetXaxis()->SetTitle("#tau[ps]"); h2_1->SetMarkerStyle(21); h2_1->Draw(); c2->Update(); TLine *line = new TLine(0,0,0,c2->GetUymax()); line->Draw(); //save the event list to a Root file if one was produced if (fillList) { TFile efile("elist.root","recreate"); elist->Write(); } } <commit_msg>Remove compiler warnings<commit_after>// Example of analysis class for the H1 data using code generated by MakeProxy. // =========================================================================== // // This file uses 4 large data sets from the H1 collaboration at DESY Hamburg. // One can access these data sets (277 MBytes) from the standard Root web site // at: ftp://root.cern.ch/root/h1analysis/ // The Physics plots below generated by this example cannot be produced when // using smaller data sets. // // There are several ways to analyze data stored in a Root Tree // -Using TTree::Draw: This is very convenient and efficient for small tasks. // A TTree::Draw call produces one histogram at the time. The histogram // is automatically generated. The selection expression may be specified // in the command line. // // -Using the TTreeViewer: This is a graphical interface to TTree::Draw // with the same functionality. // // -Using the code generated by TTree::MakeClass: In this case, the user // creates an instance of the analysis class. He has the control over // the event loop and he can generate an unlimited number of histograms. // // -Using the code generated by TTree::MakeSelector. Like for the code // generated by TTree::MakeClass, the user can do complex analysis. // However, he cannot control the event loop. The event loop is controlled // by TTree::Process called by the user. This solution is illustrated // by the current code. The advantage of this method is that it can be run // in a parallel environment using PROOF (the Parallel Root Facility). // // A chain of 4 files (originally converted from PAW ntuples) is used // to illustrate the various ways to loop on Root data sets. // Each data set contains a Root Tree named "h42" // The class definition in h1analysis.h has been generated automatically // by the Root utility TTree::MakeSelector using one of the files with the // following statement: // h42->MakeSelector("h1analysis"); // This produces two files: h1analysis.h and h1analysis.C (skeleton of this file) // The h1analysis class is derived from the Root class TSelector. // // The following members functions are called by the TTree::Process functions. // Begin(): called everytime a loop on the tree starts. // a convenient place to create your histograms. // SlaveBegin(): // // Notify(): This function is called at the first entry of a new Tree // in a chain. // Process(): called to analyze each entry. // // SlaveTerminate(): // // Terminate(): called at the end of a loop on a TTree. // a convenient place to draw/fit your histograms. // // To use this file, try the following session // // Root > gROOT->Time(); //will show RT & CPU time per command // //==> A- create a TChain with the 4 H1 data files // The chain can be created by executed the short macro h1chain.C below: // { // TChain chain("h42"); // chain.Add("$H1/dstarmb.root"); // 21330730 bytes 21920 events // chain.Add("$H1/dstarp1a.root"); // 71464503 bytes 73243 events // chain.Add("$H1/dstarp1b.root"); // 83827959 bytes 85597 events // chain.Add("$H1/dstarp2.root"); // 100675234 bytes 103053 events // //where $H1 is a system symbol pointing to the H1 data directory. // } // // Root > .x h1chain.C // //==> B- loop on all events // Root > chain.Process("h1analysis.C") // //==> C- same as B, but in addition fill the event list with selected entries. // The event list is saved to a file "elist.root" by the Terminate function. // To see the list of selected events, you can do elist->Print("all"). // The selection function has selected 7525 events out of the 283813 events // in the chain of files. (2.65 per cent) // Root > chain.Process("h1analysis.C","fillList") // //==> D- Process only entries in the event list // The event list is read from the file in elist.root generated by step C // Root > chain.Process("h1analysis.C","useList") // //==> E- the above steps have been executed via the interpreter. // You can repeat the steps B, C and D using the script compiler // by replacing "h1analysis.C" by "h1analysis.C+" or "h1analysis.C++" // // in a new session with ,eg: // //==> F- Create the chain as in A, then execute // Root > chain.Process("h1analysis.C+","useList") // // The commands executed with the 4 different methods B,C,D and E // produce two canvases shown below: // begin_html <a href="gif/h1analysis_dstar.gif" >the Dstar plot</a> end_html // begin_html <a href="gif/h1analysis_tau.gif" >the Tau D0 plot</a> end_html // //Author; Philippe Canal from original h1analysis.C by Rene Brun TEventList *elist; Bool_t useList, fillList; TH1F *hdmd; TH2F *h2; //_____________________________________________________________________ void h1analysisProxy_Begin(TTree * /* tree */ ) { // function called before starting the event loop // -it performs some cleanup // -it creates histograms // -it sets some initialisation for the event list //print the option specified in the Process function. TString option = GetOption(); printf("Starting (begin) h1analysis with process option: %s\n",option.Data()); //some cleanup in case this function had already been executed //delete any previously generated histograms or functions gDirectory->Delete("hdmd"); gDirectory->Delete("h2*"); delete gROOT->GetFunction("f5"); delete gROOT->GetFunction("f2"); } //_____________________________________________________________________ void h1analysisProxy_SlaveBegin(TTree *tree) { // function called before starting the event loop // -it performs some cleanup // -it creates histograms // -it sets some initialisation for the event list //initialize the Tree branch addresses Init(tree); //print the option specified in the Process function. TString option = GetOption(); printf("Starting (slave) h1analysis with process option: %s\n",option.Data()); //some cleanup in case this function had already been executed //delete any previously generated histograms or functions gDirectory->Delete("hdmd"); gDirectory->Delete("h2*"); delete gROOT->GetFunction("f5"); delete gROOT->GetFunction("f2"); //create histograms hdmd = new TH1F("hdmd","dm_d",40,0.13,0.17); h2 = new TH2F("h2","ptD0 vs dm_d",30,0.135,0.165,30,-3,6); fOutput->Add(hdmd); fOutput->Add(h2); //process cases with event list fillList = kFALSE; useList = kFALSE; tree->SetEventList(0); delete gDirectory->GetList()->FindObject("elist"); // case when one creates/fills the event list if (option.Contains("fillList")) { fillList = kTRUE; elist = new TEventList("elist","selection from Cut",5000); } else elist = 0; // case when one uses the event list generated in a previous call if (option.Contains("useList")) { useList = kTRUE; TFile f("elist.root"); elist = (TEventList*)f.Get("elist"); if (elist) elist->SetDirectory(0); //otherwise the file destructor will delete elist tree->SetEventList(elist); } } Double_t h1analysisProxy() { return 0; } //_____________________________________________________________________ Bool_t h1analysisProxy_Process(Long64_t entry) { // entry is the entry number in the current Tree // Selection function to select D* and D0. //in case one event list is given in input, the selection has already been done. if (!useList) { float f1 = md0_d; float f2 = md0_d-1.8646; bool test = TMath::Abs(md0_d-1.8646) >= 0.04; if (gDebug>0) fprintf(stderr,"entry #%lld f1=%f f2=%f test=%d\n", fChain->GetReadEntry(),f1,f2,test); if (TMath::Abs(md0_d-1.8646) >= 0.04) return kFALSE; if (ptds_d <= 2.5) return kFALSE; if (TMath::Abs(etads_d) >= 1.5) return kFALSE; int cik = ik-1; //original ik used f77 convention starting at 1 int cipi = ipi-1; //original ipi used f77 convention starting at 1 f1 = nhitrp[cik]; f2 = nhitrp[cipi]; test = nhitrp[cik]*nhitrp[cipi] <= 1; if (gDebug>0) fprintf(stderr,"entry #%lld f1=%f f2=%f test=%d\n", fChain->GetReadEntry(),f1,f2,test); if (nhitrp[cik]*nhitrp[cipi] <= 1) return kFALSE; if (rend[cik] -rstart[cik] <= 22) return kFALSE; if (rend[cipi]-rstart[cipi] <= 22) return kFALSE; if (nlhk[cik] <= 0.1) return kFALSE; if (nlhpi[cipi] <= 0.1) return kFALSE; // fix because read-only if (nlhpi[ipis-1] <= 0.1) return kFALSE; if (njets < 1) return kFALSE; } // if option fillList, fill the event list if (fillList) elist->Enter(fChain->GetChainEntryNumber(entry)); //fill some histograms hdmd->Fill(dm_d); h2->Fill(dm_d,rpd0_t/0.029979*1.8646/ptd0_d); return kTRUE; } //_____________________________________________________________________ void h1analysisProxy_SlaveTerminate() { // nothing to be done printf("Terminate (slave) h1analysis\n"); } //_____________________________________________________________________ void h1analysisProxy_Terminate() { printf("Terminate (final) h1analysis\n"); // function called at the end of the event loop hdmd = dynamic_cast<TH1F*>(fOutput->FindObject("hdmd")); h2 = dynamic_cast<TH2F*>(fOutput->FindObject("h2")); if (hdmd == 0 || h2 == 0) { Error("Terminate", "hdmd = %p , h2 = %p", hdmd, h2); return; } //create the canvas for the h1analysis fit gStyle->SetOptFit(); TCanvas *c1 = new TCanvas("c1","h1analysis analysis",10,10,800,600); c1->SetBottomMargin(0.15); hdmd->GetXaxis()->SetTitle("m_{K#pi#pi} - m_{K#pi}[GeV/c^{2}]"); hdmd->GetXaxis()->SetTitleOffset(1.4); //fit histogram hdmd with function f5 using the loglikelihood option TF1 *f5 = new TF1("f5",fdm5,0.139,0.17,5); f5->SetParameters(1000000, .25, 2000, .1454, .001); hdmd->Fit("f5","lr"); //create the canvas for tau d0 gStyle->SetOptFit(0); gStyle->SetOptStat(1100); TCanvas *c2 = new TCanvas("c2","tauD0",100,100,800,600); c2->SetGrid(); c2->SetBottomMargin(0.15); // Project slices of 2-d histogram h2 along X , then fit each slice // with function f2 and make a histogram for each fit parameter // Note that the generated histograms are added to the list of objects // in the current directory. TF1 *f2 = new TF1("f2",fdm2,0.139,0.17,2); f2->SetParameters(10000, 10); h2->FitSlicesX(f2,0,0,1,"qln"); TH1D *h2_1 = (TH1D*)gDirectory->Get("h2_1"); h2_1->GetXaxis()->SetTitle("#tau[ps]"); h2_1->SetMarkerStyle(21); h2_1->Draw(); c2->Update(); TLine *line = new TLine(0,0,0,c2->GetUymax()); line->Draw(); //save the event list to a Root file if one was produced if (fillList) { TFile efile("elist.root","recreate"); elist->Write(); } } <|endoftext|>
<commit_before>#include <iostream> #include "http.h" using namespace native::http; int main() { http server([](request& req, response& res){ res.set_status(200); res.set_header("Content-Type", "text/plain"); res.end("C++ FTW!\n", [=](int status) {}); }); std::cout << "Server running at http://0.0.0.0:8080/" << std::endl; server.listen("0.0.0.0", 8080); return 0; } <commit_msg>small change in sample code<commit_after>#include <iostream> #include "http.h" using namespace native::http; int main() { http server([](request& req, response& res){ res.set_status(200); res.set_header("Content-Type", "text/plain"); res.end("C++ FTW!\n", [](int status) {}); }); std::cout << "Server running at http://0.0.0.0:8080/" << std::endl; server.listen("0.0.0.0", 8080); return 0; } <|endoftext|>
<commit_before>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Module: $RCSfile$ Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkImageToSurfaceFilter.h" #include <vtkImageData.h> #include <vtkDecimatePro.h> #include <vtkImageChangeInformation.h> #include <vtkLinearTransform.h> #include <vtkMath.h> #include <vtkMatrix4x4.h> mitk::ImageToSurfaceFilter::ImageToSurfaceFilter() { m_Smooth = false; m_Decimate = false; m_Threshold = 1; m_TargetReduction = 0.95f; }; mitk::ImageToSurfaceFilter::~ImageToSurfaceFilter() { }; template <class T1, class T2, class T3> inline void mitkVtkLinearTransformPoint(T1 matrix[4][4], T2 in[3], T3 out[3]) { T3 x = matrix[0][0]*in[0]+matrix[0][1]*in[1]+matrix[0][2]*in[2]+matrix[0][3]; T3 y = matrix[1][0]*in[0]+matrix[1][1]*in[1]+matrix[1][2]*in[2]+matrix[1][3]; T3 z = matrix[2][0]*in[0]+matrix[2][1]*in[1]+matrix[2][2]*in[2]+matrix[2][3]; out[0] = x; out[1] = y; out[2] = z; } void mitk::ImageToSurfaceFilter::CreateSurface(int time, vtkImageData *vtkimage, mitk::Surface * surface, const ScalarType threshold) { vtkImageChangeInformation *indexCoordinatesImageFilter = vtkImageChangeInformation::New(); indexCoordinatesImageFilter->SetInput(vtkimage); indexCoordinatesImageFilter->SetOutputOrigin(0.0,0.0,0.0); //MarchingCube -->create Surface vtkMarchingCubes *skinExtractor = vtkMarchingCubes::New(); skinExtractor->SetInput(indexCoordinatesImageFilter->GetOutput());//RC++ indexCoordinatesImageFilter->Delete(); skinExtractor->SetValue(0, threshold); vtkPolyData *polydata; polydata = skinExtractor->GetOutput(); polydata->Register(NULL);//RC++ skinExtractor->Delete(); if (m_Smooth) { int spIterations =50; float spRelaxation =0.1; vtkSmoothPolyDataFilter *smoother = vtkSmoothPolyDataFilter::New(); //read poly1 (poly1 can be the original polygon, or the decimated polygon) smoother->SetInput(polydata);//RC++ smoother->SetNumberOfIterations( spIterations ); smoother->SetRelaxationFactor( spRelaxation ); smoother->SetFeatureAngle( 60 ); smoother->FeatureEdgeSmoothingOff(); smoother->BoundarySmoothingOff(); smoother->SetConvergence( 0 ); polydata->Delete();//RC-- polydata = smoother->GetOutput(); polydata->Register(NULL);//RC++ smoother->Delete(); } //decimate = to reduce number of polygons if(m_Decimate) { vtkDecimatePro *decimate = vtkDecimatePro::New(); decimate->SplittingOff(); decimate->SetErrorIsAbsolute(5); decimate->SetFeatureAngle(30); decimate->PreserveTopologyOn(); decimate->BoundaryVertexDeletionOff(); decimate->SetDegree(10); //std-value is 25! decimate->SetInput(polydata);//RC++ decimate->SetTargetReduction(m_TargetReduction); decimate->SetMaximumError(0.002); polydata->Delete();//RC-- polydata = decimate->GetOutput(); polydata->Register(NULL);//RC++ decimate->Delete(); } polydata->Update(); polydata->SetSource(NULL); vtkFloatingPointType* spacing; spacing = vtkimage->GetSpacing(); vtkPoints * points = polydata->GetPoints(); vtkMatrix4x4 *vtkmatrix = vtkMatrix4x4::New(); GetInput()->GetGeometry(time)->GetVtkTransform()->GetMatrix(vtkmatrix); vtkFloatingPointType (*matrix)[4] = vtkmatrix->Element; unsigned int i,j; for(i=0;i<3;++i) for(j=0;j<3;++j) matrix[i][j]/=spacing[j]; unsigned int n = points->GetNumberOfPoints(); vtkFloatingPointType point[3]; for (i = 0; i < n; i++) { points->GetPoint(i, point); mitkVtkLinearTransformPoint(matrix,point,point); points->SetPoint(i, point); } vtkmatrix->Delete(); surface->SetVtkPolyData(polydata, time); polydata->UnRegister(NULL); } void mitk::ImageToSurfaceFilter::GenerateData() { mitk::Surface *surface = this->GetOutput(); mitk::Image * image = (mitk::Image*)GetInput(); mitk::Image::RegionType outputRegion = image->GetRequestedRegion(); int tstart=outputRegion.GetIndex(3); int tmax=tstart+outputRegion.GetSize(3); //GetSize()==1 - will aber 0 haben, wenn nicht zeitaufgelst int t; for( t=tstart; t < tmax; ++t) { vtkImageData *vtkimagedata = image->GetVtkImageData(t); CreateSurface(t,vtkimagedata,surface,m_Threshold); } } void mitk::ImageToSurfaceFilter::SetInput(const mitk::Image *image) { // Process object is not const-correct so the const_cast is required here this->ProcessObject::SetNthInput(0, const_cast< mitk::Image * >( image ) ); } const mitk::Image *mitk::ImageToSurfaceFilter::GetInput(void) { if (this->GetNumberOfInputs() < 1) { return 0; } return static_cast<const mitk::Image * > ( this->ProcessObject::GetInput(0) ); } void mitk::ImageToSurfaceFilter::GenerateOutputInformation() { mitk::Image::ConstPointer inputImage =(mitk::Image*) this->GetInput(); //mitk::Image *inputImage = (mitk::Image*)this->GetImage(); mitk::Surface::Pointer output = this->GetOutput(); itkDebugMacro(<<"GenerateOutputInformation()"); if(inputImage.IsNull()) return; //Set Data } <commit_msg>FIX: replaced vtkFloatingPointType by double when using vtkMatrix4x4<commit_after>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Module: $RCSfile$ Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkImageToSurfaceFilter.h" #include <vtkImageData.h> #include <vtkDecimatePro.h> #include <vtkImageChangeInformation.h> #include <vtkLinearTransform.h> #include <vtkMath.h> #include <vtkMatrix4x4.h> mitk::ImageToSurfaceFilter::ImageToSurfaceFilter() { m_Smooth = false; m_Decimate = false; m_Threshold = 1; m_TargetReduction = 0.95f; }; mitk::ImageToSurfaceFilter::~ImageToSurfaceFilter() { }; template <class T1, class T2, class T3> inline void mitkVtkLinearTransformPoint(T1 matrix[4][4], T2 in[3], T3 out[3]) { T3 x = matrix[0][0]*in[0]+matrix[0][1]*in[1]+matrix[0][2]*in[2]+matrix[0][3]; T3 y = matrix[1][0]*in[0]+matrix[1][1]*in[1]+matrix[1][2]*in[2]+matrix[1][3]; T3 z = matrix[2][0]*in[0]+matrix[2][1]*in[1]+matrix[2][2]*in[2]+matrix[2][3]; out[0] = x; out[1] = y; out[2] = z; } void mitk::ImageToSurfaceFilter::CreateSurface(int time, vtkImageData *vtkimage, mitk::Surface * surface, const ScalarType threshold) { vtkImageChangeInformation *indexCoordinatesImageFilter = vtkImageChangeInformation::New(); indexCoordinatesImageFilter->SetInput(vtkimage); indexCoordinatesImageFilter->SetOutputOrigin(0.0,0.0,0.0); //MarchingCube -->create Surface vtkMarchingCubes *skinExtractor = vtkMarchingCubes::New(); skinExtractor->SetInput(indexCoordinatesImageFilter->GetOutput());//RC++ indexCoordinatesImageFilter->Delete(); skinExtractor->SetValue(0, threshold); vtkPolyData *polydata; polydata = skinExtractor->GetOutput(); polydata->Register(NULL);//RC++ skinExtractor->Delete(); if (m_Smooth) { int spIterations =50; float spRelaxation =0.1; vtkSmoothPolyDataFilter *smoother = vtkSmoothPolyDataFilter::New(); //read poly1 (poly1 can be the original polygon, or the decimated polygon) smoother->SetInput(polydata);//RC++ smoother->SetNumberOfIterations( spIterations ); smoother->SetRelaxationFactor( spRelaxation ); smoother->SetFeatureAngle( 60 ); smoother->FeatureEdgeSmoothingOff(); smoother->BoundarySmoothingOff(); smoother->SetConvergence( 0 ); polydata->Delete();//RC-- polydata = smoother->GetOutput(); polydata->Register(NULL);//RC++ smoother->Delete(); } //decimate = to reduce number of polygons if(m_Decimate) { vtkDecimatePro *decimate = vtkDecimatePro::New(); decimate->SplittingOff(); decimate->SetErrorIsAbsolute(5); decimate->SetFeatureAngle(30); decimate->PreserveTopologyOn(); decimate->BoundaryVertexDeletionOff(); decimate->SetDegree(10); //std-value is 25! decimate->SetInput(polydata);//RC++ decimate->SetTargetReduction(m_TargetReduction); decimate->SetMaximumError(0.002); polydata->Delete();//RC-- polydata = decimate->GetOutput(); polydata->Register(NULL);//RC++ decimate->Delete(); } polydata->Update(); polydata->SetSource(NULL); vtkFloatingPointType* spacing; spacing = vtkimage->GetSpacing(); vtkPoints * points = polydata->GetPoints(); vtkMatrix4x4 *vtkmatrix = vtkMatrix4x4::New(); GetInput()->GetGeometry(time)->GetVtkTransform()->GetMatrix(vtkmatrix); double (*matrix)[4] = vtkmatrix->Element; unsigned int i,j; for(i=0;i<3;++i) for(j=0;j<3;++j) matrix[i][j]/=spacing[j]; unsigned int n = points->GetNumberOfPoints(); vtkFloatingPointType point[3]; for (i = 0; i < n; i++) { points->GetPoint(i, point); mitkVtkLinearTransformPoint(matrix,point,point); points->SetPoint(i, point); } vtkmatrix->Delete(); surface->SetVtkPolyData(polydata, time); polydata->UnRegister(NULL); } void mitk::ImageToSurfaceFilter::GenerateData() { mitk::Surface *surface = this->GetOutput(); mitk::Image * image = (mitk::Image*)GetInput(); mitk::Image::RegionType outputRegion = image->GetRequestedRegion(); int tstart=outputRegion.GetIndex(3); int tmax=tstart+outputRegion.GetSize(3); //GetSize()==1 - will aber 0 haben, wenn nicht zeitaufgelst int t; for( t=tstart; t < tmax; ++t) { vtkImageData *vtkimagedata = image->GetVtkImageData(t); CreateSurface(t,vtkimagedata,surface,m_Threshold); } } void mitk::ImageToSurfaceFilter::SetInput(const mitk::Image *image) { // Process object is not const-correct so the const_cast is required here this->ProcessObject::SetNthInput(0, const_cast< mitk::Image * >( image ) ); } const mitk::Image *mitk::ImageToSurfaceFilter::GetInput(void) { if (this->GetNumberOfInputs() < 1) { return 0; } return static_cast<const mitk::Image * > ( this->ProcessObject::GetInput(0) ); } void mitk::ImageToSurfaceFilter::GenerateOutputInformation() { mitk::Image::ConstPointer inputImage =(mitk::Image*) this->GetInput(); //mitk::Image *inputImage = (mitk::Image*)this->GetImage(); mitk::Surface::Pointer output = this->GetOutput(); itkDebugMacro(<<"GenerateOutputInformation()"); if(inputImage.IsNull()) return; //Set Data } <|endoftext|>
<commit_before>// Copyright 2017 Henrik Steffen Gaßmann // // Licensed under the MIT License. // See LICENSE file in the project root for full license information. // //#include "precompiled.hpp" #include <sexpr-cpp/data.hpp> #include "data-helpers.hpp" #include "boost-unit-test.hpp" BOOST_TEST_DONT_PRINT_LOG_VALUE(std::type_info) using namespace sexpr; BOOST_AUTO_TEST_SUITE(basic_node) BOOST_AUTO_TEST_SUITE(ctor_tests) BOOST_AUTO_TEST_CASE(default_ctor) { node n; BOOST_TEST_REQUIRE(n.which() == node_type::list); BOOST_TEST(n.is_list()); BOOST_TEST(n.type_info() == typeid(node::list)); BOOST_TEST(n.empty()); } BOOST_AUTO_TEST_CASE(char_array_ctor) { static constexpr char raw_str[] = "foo\0bar"; const std::string str_w_null(raw_str, sizeof(raw_str)); const auto str = str_w_null.substr(0, str_w_null.size() - 1); node n1(raw_str); BOOST_TEST_REQUIRE(n1.is_string()); BOOST_TEST(n1.get_string() == str); node n2(raw_str, false); BOOST_TEST_REQUIRE(n2.is_string()); BOOST_TEST(n2.get_string() == str_w_null); } BOOST_AUTO_TEST_CASE(string_ctor) { using namespace std::string_literals; auto refstr = "foobar\0baz"s; node n(refstr); BOOST_TEST_REQUIRE(n.is_string()); BOOST_TEST(n.type_info() == typeid(node::string)); auto &s = n.get_string(); BOOST_TEST(s.size() == refstr.size()); BOOST_TEST(s == refstr); } BOOST_AUTO_TEST_CASE(init_ctor__empty) { node n{}; BOOST_TEST_REQUIRE(n.is_list()); BOOST_TEST(n.empty()); } BOOST_AUTO_TEST_CASE(init_ctor__single) { using namespace std::string_literals; const auto s1 = "foo"s; node n{ s1 }; BOOST_TEST_REQUIRE(n.is_list()); BOOST_TEST_REQUIRE(!n.empty()); BOOST_TEST(n.size() == 1); BOOST_TEST(n.at(0).is_string()); BOOST_TEST(n.at(0).get_string() == s1); } BOOST_AUTO_TEST_CASE(init_ctor__multi) { using namespace std::string_literals; std::string s1 = "foo", s2 = "bar", s3 = "baz"; node n{ s1,s2,s3 }; BOOST_TEST_REQUIRE(n.is_list()); BOOST_TEST_REQUIRE(!n.empty()); BOOST_TEST(n.size() == 3); BOOST_TEST(n.at(0).is_string()); BOOST_TEST(n.at(0).get_string() == s1); BOOST_TEST(n.at(1).is_string()); BOOST_TEST(n.at(1).get_string() == s2); BOOST_TEST(n.at(2).is_string()); BOOST_TEST(s3 == n.at(2).get_string()); } BOOST_AUTO_TEST_CASE(init_ctor__complex) { node n{ "foo",{ "bar", "baz" },{ "foobar" }, "oh my" }; BOOST_TEST_REQUIRE(n.is_list()); BOOST_TEST_REQUIRE(n.size() == 4); BOOST_TEST(n[0].is_string()); BOOST_TEST(n[1].is_list()); BOOST_TEST(n[1].size() == 2); BOOST_TEST(n[1][0].is_string()); BOOST_TEST(n[2].is_list()); BOOST_TEST(n[2].size() == 1); BOOST_TEST(n[3].is_string()); } BOOST_AUTO_TEST_CASE(copy_ctor) { using namespace std::string_literals; node n0{ "foo"s, { "bar"s, "baz"s }, {"foobar"s}, "oh my"s }; node n1 = n0; BOOST_TEST(n0 == n1); } BOOST_AUTO_TEST_SUITE_END() struct accessor_fixture { static constexpr char str_raw[] = "foobar"; const std::string str = str_raw; node str_node; const node &str_cnode; const std::vector<node> node_vector = { "first", "second", "third" }; node list_node; const node &list_cnode; accessor_fixture() : str_node(str_raw) , str_cnode(str_node) , list_node() , list_cnode(list_node) { list_node = node(node_vector.begin(), node_vector.end()); } }; constexpr char accessor_fixture::str_raw[]; BOOST_FIXTURE_TEST_SUITE(accessor_tests, accessor_fixture) using namespace std::string_literals; BOOST_AUTO_TEST_CASE(string_getters) { BOOST_TEST(str_node.is_string()); BOOST_TEST(!str_node.get_string().compare(str)); BOOST_CHECK_THROW(str_node.get_list(), std::domain_error); BOOST_TEST_REQUIRE(str_node.try_get_string()); BOOST_TEST(!str_node.try_get_string()->compare(str)); BOOST_TEST(!str_node.try_get_list()); BOOST_TEST(str_cnode.is_string()); BOOST_TEST(!str_cnode.get_string().compare(str)); BOOST_CHECK_THROW(str_cnode.get_list(), std::domain_error); BOOST_TEST_REQUIRE(str_cnode.try_get_string()); BOOST_TEST(!str_cnode.try_get_string()->compare(str)); BOOST_TEST(!str_cnode.try_get_list()); } BOOST_AUTO_TEST_CASE(list_getters) { BOOST_TEST(list_node.is_list()); BOOST_TEST(list_node.get_list() == node_vector); BOOST_CHECK_THROW(list_node.get_string(), std::domain_error); BOOST_TEST_REQUIRE(list_node.try_get_list()); BOOST_TEST(*list_node.try_get_list() == node_vector); BOOST_TEST(!list_node.try_get_string()); BOOST_TEST(list_cnode.is_list()); BOOST_TEST(list_cnode.get_list() == node_vector); BOOST_CHECK_THROW(list_cnode.get_string(), std::domain_error); BOOST_TEST_REQUIRE(list_cnode.try_get_list()); BOOST_TEST(*list_cnode.try_get_list() == node_vector); BOOST_TEST(!list_cnode.try_get_string()); } BOOST_AUTO_TEST_CASE(list_container_emulation) { BOOST_TEST(list_node.get_list() == node_vector); BOOST_TEST(list_node.at(0) == node_vector.at(0)); BOOST_TEST(list_node.at(1) == node_vector.at(1)); BOOST_TEST(list_node.at(2) == node_vector.at(2)); BOOST_TEST(list_cnode.at(0) == node_vector.at(0)); BOOST_TEST(list_cnode.at(1) == node_vector.at(1)); BOOST_TEST(list_cnode.at(2) == node_vector.at(2)); BOOST_CHECK_THROW(list_node.at(3), std::exception); BOOST_TEST(list_node.at(0) == list_node[0]); BOOST_TEST(list_node.at(1) == list_node[1]); BOOST_TEST(list_node.at(2) == list_node[2]); BOOST_TEST(list_node.at(0) == list_cnode[0]); BOOST_TEST(list_node.at(1) == list_cnode[1]); BOOST_TEST(list_node.at(2) == list_cnode[2]); BOOST_TEST(list_node.front() == node_vector.front()); BOOST_TEST(list_cnode.front() == node_vector.front()); BOOST_TEST(list_node.back() == node_vector.back()); BOOST_TEST(list_cnode.back() == node_vector.back()); BOOST_TEST(list_node.empty() == node_vector.empty()); BOOST_TEST(list_cnode.empty() == node_vector.empty()); BOOST_TEST(list_node.size() == node_vector.size()); BOOST_TEST(list_cnode.size() == node_vector.size()); BOOST_TEST(list_node.max_size() >= list_node.size()); BOOST_TEST(list_cnode.max_size() >= list_cnode.size()); BOOST_TEST(list_cnode.max_size() >= list_node.max_size()); } BOOST_AUTO_TEST_CASE(string_container_emulation) { BOOST_CHECK_THROW(str_node.at(0), std::domain_error); BOOST_CHECK_THROW(str_node.at(1), std::domain_error); BOOST_CHECK_THROW(str_cnode.at(0), std::domain_error); BOOST_CHECK_THROW(str_cnode.at(1), std::domain_error); BOOST_CHECK_THROW(str_node[0], std::domain_error); BOOST_CHECK_THROW(str_node[1], std::domain_error); BOOST_CHECK_THROW(str_cnode[0], std::domain_error); BOOST_CHECK_THROW(str_cnode[1], std::domain_error); BOOST_CHECK_THROW(str_node.front(), std::domain_error); BOOST_CHECK_THROW(str_cnode.front(), std::domain_error); BOOST_CHECK_THROW(str_node.back(), std::domain_error); BOOST_CHECK_THROW(str_cnode.back(), std::domain_error); BOOST_TEST(!str_node.empty()); BOOST_TEST(!str_cnode.empty()); BOOST_TEST(str_node.size() == 1); BOOST_TEST(str_cnode.size() == 1); BOOST_TEST(str_node.max_size() == 1); BOOST_TEST(str_cnode.max_size() == 1); } BOOST_AUTO_TEST_CASE(explicit_string_conversion) { node::string s(str_cnode); BOOST_TEST(s == str_cnode.get_string()); BOOST_TEST(static_cast<node::string>(str_cnode) == str_cnode.get_string()); BOOST_CHECK_THROW(static_cast<node::string>(list_cnode), std::domain_error); } BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE_END() <commit_msg>ADD basic_node ITERATOR TESTS<commit_after>// Copyright 2017 Henrik Steffen Gaßmann // // Licensed under the MIT License. // See LICENSE file in the project root for full license information. // //#include "precompiled.hpp" #include <sexpr-cpp/data.hpp> #include "data-helpers.hpp" #include "boost-unit-test.hpp" BOOST_TEST_DONT_PRINT_LOG_VALUE(std::type_info) using namespace sexpr; BOOST_AUTO_TEST_SUITE(basic_node) BOOST_AUTO_TEST_SUITE(ctor_tests) BOOST_AUTO_TEST_CASE(default_ctor) { node n; BOOST_TEST_REQUIRE(n.which() == node_type::list); BOOST_TEST(n.is_list()); BOOST_TEST(n.type_info() == typeid(node::list)); BOOST_TEST(n.empty()); } BOOST_AUTO_TEST_CASE(char_array_ctor) { static constexpr char raw_str[] = "foo\0bar"; const std::string str_w_null(raw_str, sizeof(raw_str)); const auto str = str_w_null.substr(0, str_w_null.size() - 1); node n1(raw_str); BOOST_TEST_REQUIRE(n1.is_string()); BOOST_TEST(n1.get_string() == str); node n2(raw_str, false); BOOST_TEST_REQUIRE(n2.is_string()); BOOST_TEST(n2.get_string() == str_w_null); } BOOST_AUTO_TEST_CASE(string_ctor) { using namespace std::string_literals; auto refstr = "foobar\0baz"s; node n(refstr); BOOST_TEST_REQUIRE(n.is_string()); BOOST_TEST(n.type_info() == typeid(node::string)); auto &s = n.get_string(); BOOST_TEST(s.size() == refstr.size()); BOOST_TEST(s == refstr); } BOOST_AUTO_TEST_CASE(init_ctor__empty) { node n{}; BOOST_TEST_REQUIRE(n.is_list()); BOOST_TEST(n.empty()); } BOOST_AUTO_TEST_CASE(init_ctor__single) { using namespace std::string_literals; const auto s1 = "foo"s; node n{ s1 }; BOOST_TEST_REQUIRE(n.is_list()); BOOST_TEST_REQUIRE(!n.empty()); BOOST_TEST(n.size() == 1); BOOST_TEST(n.at(0).is_string()); BOOST_TEST(n.at(0).get_string() == s1); } BOOST_AUTO_TEST_CASE(init_ctor__multi) { using namespace std::string_literals; std::string s1 = "foo", s2 = "bar", s3 = "baz"; node n{ s1,s2,s3 }; BOOST_TEST_REQUIRE(n.is_list()); BOOST_TEST_REQUIRE(!n.empty()); BOOST_TEST(n.size() == 3); BOOST_TEST(n.at(0).is_string()); BOOST_TEST(n.at(0).get_string() == s1); BOOST_TEST(n.at(1).is_string()); BOOST_TEST(n.at(1).get_string() == s2); BOOST_TEST(n.at(2).is_string()); BOOST_TEST(s3 == n.at(2).get_string()); } BOOST_AUTO_TEST_CASE(init_ctor__complex) { node n{ "foo",{ "bar", "baz" },{ "foobar" }, "oh my" }; BOOST_TEST_REQUIRE(n.is_list()); BOOST_TEST_REQUIRE(n.size() == 4); BOOST_TEST(n[0].is_string()); BOOST_TEST(n[1].is_list()); BOOST_TEST(n[1].size() == 2); BOOST_TEST(n[1][0].is_string()); BOOST_TEST(n[2].is_list()); BOOST_TEST(n[2].size() == 1); BOOST_TEST(n[3].is_string()); } BOOST_AUTO_TEST_CASE(copy_ctor) { using namespace std::string_literals; node n0{ "foo"s, { "bar"s, "baz"s }, {"foobar"s}, "oh my"s }; node n1 = n0; BOOST_TEST(n0 == n1); } BOOST_AUTO_TEST_SUITE_END() struct accessor_fixture { static constexpr char str_raw[] = "foobar"; const std::string str = str_raw; node str_node; const node &str_cnode; const std::vector<node> node_vector = { "first", "second", "third" }; node list_node; const node &list_cnode; accessor_fixture() : str_node(str_raw) , str_cnode(str_node) , list_node() , list_cnode(list_node) { list_node = node(node_vector.begin(), node_vector.end()); } }; constexpr char accessor_fixture::str_raw[]; BOOST_FIXTURE_TEST_SUITE(accessor_tests, accessor_fixture) using namespace std::string_literals; BOOST_AUTO_TEST_CASE(string_getters) { BOOST_TEST(str_node.is_string()); BOOST_TEST(!str_node.get_string().compare(str)); BOOST_CHECK_THROW(str_node.get_list(), std::domain_error); BOOST_TEST_REQUIRE(str_node.try_get_string()); BOOST_TEST(!str_node.try_get_string()->compare(str)); BOOST_TEST(!str_node.try_get_list()); BOOST_TEST(str_cnode.is_string()); BOOST_TEST(!str_cnode.get_string().compare(str)); BOOST_CHECK_THROW(str_cnode.get_list(), std::domain_error); BOOST_TEST_REQUIRE(str_cnode.try_get_string()); BOOST_TEST(!str_cnode.try_get_string()->compare(str)); BOOST_TEST(!str_cnode.try_get_list()); } BOOST_AUTO_TEST_CASE(list_getters) { BOOST_TEST(list_node.is_list()); BOOST_TEST(list_node.get_list() == node_vector); BOOST_CHECK_THROW(list_node.get_string(), std::domain_error); BOOST_TEST_REQUIRE(list_node.try_get_list()); BOOST_TEST(*list_node.try_get_list() == node_vector); BOOST_TEST(!list_node.try_get_string()); BOOST_TEST(list_cnode.is_list()); BOOST_TEST(list_cnode.get_list() == node_vector); BOOST_CHECK_THROW(list_cnode.get_string(), std::domain_error); BOOST_TEST_REQUIRE(list_cnode.try_get_list()); BOOST_TEST(*list_cnode.try_get_list() == node_vector); BOOST_TEST(!list_cnode.try_get_string()); } BOOST_AUTO_TEST_CASE(list_container_emulation) { BOOST_TEST(list_node.get_list() == node_vector); BOOST_TEST(list_node.at(0) == node_vector.at(0)); BOOST_TEST(list_node.at(1) == node_vector.at(1)); BOOST_TEST(list_node.at(2) == node_vector.at(2)); BOOST_TEST(list_cnode.at(0) == node_vector.at(0)); BOOST_TEST(list_cnode.at(1) == node_vector.at(1)); BOOST_TEST(list_cnode.at(2) == node_vector.at(2)); BOOST_CHECK_THROW(list_node.at(3), std::exception); BOOST_TEST(list_node.at(0) == list_node[0]); BOOST_TEST(list_node.at(1) == list_node[1]); BOOST_TEST(list_node.at(2) == list_node[2]); BOOST_TEST(list_node.at(0) == list_cnode[0]); BOOST_TEST(list_node.at(1) == list_cnode[1]); BOOST_TEST(list_node.at(2) == list_cnode[2]); BOOST_TEST(list_node.front() == node_vector.front()); BOOST_TEST(list_cnode.front() == node_vector.front()); BOOST_TEST(list_node.back() == node_vector.back()); BOOST_TEST(list_cnode.back() == node_vector.back()); BOOST_TEST(list_node.empty() == node_vector.empty()); BOOST_TEST(list_cnode.empty() == node_vector.empty()); BOOST_TEST(list_node.size() == node_vector.size()); BOOST_TEST(list_cnode.size() == node_vector.size()); BOOST_TEST(list_node.max_size() >= list_node.size()); BOOST_TEST(list_cnode.max_size() >= list_cnode.size()); BOOST_TEST(list_cnode.max_size() >= list_node.max_size()); } BOOST_AUTO_TEST_CASE(string_container_emulation) { BOOST_CHECK_THROW(str_node.at(0), std::domain_error); BOOST_CHECK_THROW(str_node.at(1), std::domain_error); BOOST_CHECK_THROW(str_cnode.at(0), std::domain_error); BOOST_CHECK_THROW(str_cnode.at(1), std::domain_error); BOOST_CHECK_THROW(str_node[0], std::domain_error); BOOST_CHECK_THROW(str_node[1], std::domain_error); BOOST_CHECK_THROW(str_cnode[0], std::domain_error); BOOST_CHECK_THROW(str_cnode[1], std::domain_error); BOOST_CHECK_THROW(str_node.front(), std::domain_error); BOOST_CHECK_THROW(str_cnode.front(), std::domain_error); BOOST_CHECK_THROW(str_node.back(), std::domain_error); BOOST_CHECK_THROW(str_cnode.back(), std::domain_error); BOOST_TEST(!str_node.empty()); BOOST_TEST(!str_cnode.empty()); BOOST_TEST(str_node.size() == 1); BOOST_TEST(str_cnode.size() == 1); BOOST_TEST(str_node.max_size() == 1); BOOST_TEST(str_cnode.max_size() == 1); } BOOST_AUTO_TEST_CASE(explicit_string_conversion) { node::string s(str_cnode); BOOST_TEST(s == str_cnode.get_string()); BOOST_TEST(static_cast<node::string>(str_cnode) == str_cnode.get_string()); BOOST_CHECK_THROW(static_cast<node::string>(list_cnode), std::domain_error); } BOOST_AUTO_TEST_CASE(string_container_iterators) { BOOST_CHECK_THROW(str_node.begin(), std::domain_error); BOOST_CHECK_THROW(str_cnode.begin(), std::domain_error); BOOST_CHECK_THROW(str_node.cbegin(), std::domain_error); BOOST_CHECK_THROW(str_node.end(), std::domain_error); BOOST_CHECK_THROW(str_cnode.end(), std::domain_error); BOOST_CHECK_THROW(str_node.cend(), std::domain_error); BOOST_CHECK_THROW(str_node.rbegin(), std::domain_error); BOOST_CHECK_THROW(str_cnode.rbegin(), std::domain_error); BOOST_CHECK_THROW(str_node.crbegin(), std::domain_error); BOOST_CHECK_THROW(str_node.rend(), std::domain_error); BOOST_CHECK_THROW(str_cnode.rend(), std::domain_error); BOOST_CHECK_THROW(str_node.crend(), std::domain_error); } BOOST_AUTO_TEST_CASE(list_container_iterators) { BOOST_CHECK_EQUAL_COLLECTIONS(list_node.begin(), list_node.end(), node_vector.begin(), node_vector.end()); BOOST_CHECK_EQUAL_COLLECTIONS(list_cnode.begin(), list_cnode.end(), node_vector.begin(), node_vector.end()); BOOST_CHECK_EQUAL_COLLECTIONS(list_cnode.cbegin(), list_cnode.cend(), node_vector.begin(), node_vector.end()); BOOST_CHECK_EQUAL_COLLECTIONS(list_node.rbegin(), list_node.rend(), node_vector.rbegin(), node_vector.rend()); BOOST_CHECK_EQUAL_COLLECTIONS(list_cnode.rbegin(), list_cnode.rend(), node_vector.rbegin(), node_vector.rend()); BOOST_CHECK_EQUAL_COLLECTIONS(list_cnode.crbegin(), list_cnode.crend(), node_vector.rbegin(), node_vector.rend()); } BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "src/dcmtkUtils.h" #include <dcmtk/dcmdata/dcuid.h> #include <gtest/gtest.h> #include <memory> #include <string> #include "tests/testUtils.h" TEST(insertBaseImageTagsTest, correctInsert) { std::unique_ptr<DcmDataset> dataSet = std::make_unique<DcmDataset>(); wsiToDicomConverter::DcmtkUtils::insertBaseImageTags("image", 10, 20, 0.0, 0.0, dataSet.get()); char* stringValue; findElement(dataSet.get(), DCM_SeriesDescription)->getString(stringValue); ASSERT_EQ("image", std::string(stringValue)); Uint32 rows; findElement(dataSet.get(), DCM_TotalPixelMatrixRows)->getUint32(rows); ASSERT_EQ(10, rows); Uint32 columns; findElement(dataSet.get(), DCM_TotalPixelMatrixColumns)->getUint32(columns); ASSERT_EQ(20, columns); ASSERT_EQ(nullptr, findElement(dataSet.get(), DCM_ImagedVolumeWidth)); ASSERT_EQ(nullptr, findElement(dataSet.get(), DCM_ImagedVolumeHeight)); wsiToDicomConverter::DcmtkUtils::insertBaseImageTags("image", 10, 20, 10.0, 20.0, dataSet.get()); Float32 width; findElement(dataSet.get(), DCM_ImagedVolumeWidth)->getFloat32(width); ASSERT_EQ(10, width); Float32 height; findElement(dataSet.get(), DCM_ImagedVolumeHeight)->getFloat32(height); ASSERT_EQ(20, height); } TEST(insertStaticTagsTest, correctInsert_Level0) { std::unique_ptr<DcmDataset> dataSet = std::make_unique<DcmDataset>(); wsiToDicomConverter::DcmtkUtils::insertStaticTags(dataSet.get(), 0); char* stringValue; findElement(dataSet.get(), DCM_SOPClassUID)->getString(stringValue); ASSERT_EQ(UID_VLWholeSlideMicroscopyImageStorage, std::string(stringValue)); findElement(dataSet.get(), DCM_Modality)->getString(stringValue); ASSERT_EQ("SM", std::string(stringValue)); findElement(dataSet.get(), DCM_ImageType)->getString(stringValue); ASSERT_EQ("DERIVED\\PRIMARY\\VOLUME\\NONE", std::string(stringValue)); findElement(dataSet.get(), DCM_ImageOrientationSlide)->getString(stringValue); ASSERT_EQ("0\\-1\\0\\-1\\0\\0", std::string(stringValue)); Uint16 frameNumber; findElement(dataSet.get(), DCM_RepresentativeFrameNumber) ->getUint16(frameNumber); ASSERT_EQ(1, frameNumber); } TEST(insertStaticTagsTest, correctInsert_Level1) { std::unique_ptr<DcmDataset> dataSet = std::make_unique<DcmDataset>(); wsiToDicomConverter::DcmtkUtils::insertStaticTags(dataSet.get(), 1); char* stringValue; findElement(dataSet.get(), DCM_SOPClassUID)->getString(stringValue); ASSERT_EQ(UID_VLWholeSlideMicroscopyImageStorage, std::string(stringValue)); findElement(dataSet.get(), DCM_Modality)->getString(stringValue); ASSERT_EQ("SM", std::string(stringValue)); findElement(dataSet.get(), DCM_ImageType)->getString(stringValue); ASSERT_EQ("DERIVED\\PRIMARY\\VOLUME\\RESAMPLED", std::string(stringValue)); findElement(dataSet.get(), DCM_ImageOrientationSlide)->getString(stringValue); ASSERT_EQ("0\\-1\\0\\-1\\0\\0", std::string(stringValue)); Uint16 frameNumber; findElement(dataSet.get(), DCM_RepresentativeFrameNumber) ->getUint16(frameNumber); ASSERT_EQ(1, frameNumber); } TEST(insertIdsTest, correctInsert) { std::unique_ptr<DcmDataset> dataSet = std::make_unique<DcmDataset>(); wsiToDicomConverter::DcmtkUtils::insertIds("study", "series", dataSet.get()); ASSERT_NE(nullptr, findElement(dataSet.get(), DCM_SOPInstanceUID)); char* stringValue; findElement(dataSet.get(), DCM_StudyInstanceUID)->getString(stringValue); ASSERT_EQ("study", std::string(stringValue)); findElement(dataSet.get(), DCM_SeriesInstanceUID)->getString(stringValue); ASSERT_EQ("series", std::string(stringValue)); } TEST(insertMultiFrameTagsTest, correctInsert) { std::unique_ptr<DcmDataset> dataSet = std::make_unique<DcmDataset>(); DcmtkImgDataInfo imgInfo; imgInfo.rows = 10; imgInfo.cols = 10; wsiToDicomConverter::DcmtkUtils::insertMultiFrameTags( imgInfo, 5, 10, 0, 0, 0, 0, 0, 10, true, "series", dataSet.get()); char* stringValue; findElement(dataSet.get(), DCM_InstanceNumber)->getString(stringValue); ASSERT_EQ("1", std::string(stringValue)); findElement(dataSet.get(), DCM_FrameOfReferenceUID)->getString(stringValue); ASSERT_EQ("series.1", std::string(stringValue)); findElement(dataSet.get(), DCM_DimensionOrganizationType) ->getString(stringValue); ASSERT_EQ("TILED_FULL", std::string(stringValue)); Uint32 offset; findElement(dataSet.get(), DCM_ConcatenationFrameOffsetNumber) ->getUint32(offset); ASSERT_EQ(0, offset); Uint16 batchNumber; findElement(dataSet.get(), DCM_InConcatenationNumber)->getUint16(batchNumber); ASSERT_EQ(1, batchNumber); Uint16 concatenationTotalNumber; findElement(dataSet.get(), DCM_InConcatenationTotalNumber) ->getUint16(concatenationTotalNumber); ASSERT_EQ(2, concatenationTotalNumber); wsiToDicomConverter::DcmtkUtils::insertMultiFrameTags( imgInfo, 4, 5, 1, 1, 0, 0, 0, 105, false, "series", dataSet.get()); findElement(dataSet.get(), DCM_InConcatenationTotalNumber) ->getUint16(concatenationTotalNumber); ASSERT_EQ(27, concatenationTotalNumber); findElement(dataSet.get(), DCM_DimensionOrganizationType) ->getString(stringValue); ASSERT_EQ("TILED_SPARSE", std::string(stringValue)); DcmSequenceOfItems* element = reinterpret_cast<DcmSequenceOfItems*>( findElement(dataSet.get(), DCM_PerFrameFunctionalGroupsSequence)); ASSERT_NE(nullptr, element); Sint32 column; // 3rd item of 1st batch should be in 4th column findElement( reinterpret_cast<DcmSequenceOfItems*>( findElement(element->getItem(3), DCM_PlanePositionSlideSequence)) ->getItem(0), DCM_ColumnPositionInTotalImagePixelMatrix) ->getSint32(column); ASSERT_EQ(31, column); Sint32 row; // 2nd item of 1st batch should be in 1st row findElement( reinterpret_cast<DcmSequenceOfItems*>( findElement(element->getItem(1), DCM_PlanePositionSlideSequence)) ->getItem(0), DCM_RowPositionInTotalImagePixelMatrix) ->getSint32(row); ASSERT_EQ(1, row); dataSet = std::make_unique<DcmDataset>(); wsiToDicomConverter::DcmtkUtils::insertMultiFrameTags( imgInfo, 4, 5, 1, 5, 1, 1, 4, 105, false, "series", dataSet.get()); element = reinterpret_cast<DcmSequenceOfItems*>( findElement(dataSet.get(), DCM_PerFrameFunctionalGroupsSequence)); // 1nd item of 2nd batch should be in 5th column findElement( reinterpret_cast<DcmSequenceOfItems*>( findElement(element->getItem(0), DCM_PlanePositionSlideSequence)) ->getItem(0), DCM_ColumnPositionInTotalImagePixelMatrix) ->getSint32(column); ASSERT_EQ(41, column); // 2nd item of 2nd batch should be in 1st column findElement( reinterpret_cast<DcmSequenceOfItems*>( findElement(element->getItem(1), DCM_PlanePositionSlideSequence)) ->getItem(0), DCM_ColumnPositionInTotalImagePixelMatrix) ->getSint32(column); ASSERT_EQ(1, column); // 1st item of 2nd batch should be in 1st row findElement( reinterpret_cast<DcmSequenceOfItems*>( findElement(element->getItem(0), DCM_PlanePositionSlideSequence)) ->getItem(0), DCM_RowPositionInTotalImagePixelMatrix) ->getSint32(row); ASSERT_EQ(1, row); // 2nd item of 2nd batch should be in 2nd row findElement( reinterpret_cast<DcmSequenceOfItems*>( findElement(element->getItem(1), DCM_PlanePositionSlideSequence)) ->getItem(0), DCM_RowPositionInTotalImagePixelMatrix) ->getSint32(row); ASSERT_EQ(11, row); } <commit_msg>Fix test<commit_after>// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "src/dcmtkUtils.h" #include <dcmtk/dcmdata/dcuid.h> #include <gtest/gtest.h> #include <memory> #include <string> #include "tests/testUtils.h" TEST(insertBaseImageTagsTest, correctInsert) { std::unique_ptr<DcmDataset> dataSet = std::make_unique<DcmDataset>(); wsiToDicomConverter::DcmtkUtils::insertBaseImageTags("image", 10, 20, 0.0, 0.0, dataSet.get()); char* stringValue; findElement(dataSet.get(), DCM_SeriesDescription)->getString(stringValue); ASSERT_EQ("image", std::string(stringValue)); Uint32 rows; findElement(dataSet.get(), DCM_TotalPixelMatrixRows)->getUint32(rows); ASSERT_EQ(10, rows); Uint32 columns; findElement(dataSet.get(), DCM_TotalPixelMatrixColumns)->getUint32(columns); ASSERT_EQ(20, columns); ASSERT_EQ(nullptr, findElement(dataSet.get(), DCM_ImagedVolumeWidth)); ASSERT_EQ(nullptr, findElement(dataSet.get(), DCM_ImagedVolumeHeight)); wsiToDicomConverter::DcmtkUtils::insertBaseImageTags("image", 10, 20, 10.0, 20.0, dataSet.get()); Float32 width; findElement(dataSet.get(), DCM_ImagedVolumeWidth)->getFloat32(width); ASSERT_EQ(10, width); Float32 height; findElement(dataSet.get(), DCM_ImagedVolumeHeight)->getFloat32(height); ASSERT_EQ(20, height); } TEST(insertStaticTagsTest, correctInsert_Level0) { std::unique_ptr<DcmDataset> dataSet = std::make_unique<DcmDataset>(); wsiToDicomConverter::DcmtkUtils::insertStaticTags(dataSet.get(), 0); char* stringValue; findElement(dataSet.get(), DCM_SOPClassUID)->getString(stringValue); ASSERT_EQ(UID_VLWholeSlideMicroscopyImageStorage, std::string(stringValue)); findElement(dataSet.get(), DCM_Modality)->getString(stringValue); ASSERT_EQ("SM", std::string(stringValue)); findElement(dataSet.get(), DCM_ImageType)->getString(stringValue); ASSERT_EQ("ORIGINAL\\PRIMARY\\VOLUME\\NONE", std::string(stringValue)); findElement(dataSet.get(), DCM_ImageOrientationSlide)->getString(stringValue); ASSERT_EQ("0\\-1\\0\\-1\\0\\0", std::string(stringValue)); Uint16 frameNumber; findElement(dataSet.get(), DCM_RepresentativeFrameNumber) ->getUint16(frameNumber); ASSERT_EQ(1, frameNumber); } TEST(insertStaticTagsTest, correctInsert_Level1) { std::unique_ptr<DcmDataset> dataSet = std::make_unique<DcmDataset>(); wsiToDicomConverter::DcmtkUtils::insertStaticTags(dataSet.get(), 1); char* stringValue; findElement(dataSet.get(), DCM_SOPClassUID)->getString(stringValue); ASSERT_EQ(UID_VLWholeSlideMicroscopyImageStorage, std::string(stringValue)); findElement(dataSet.get(), DCM_Modality)->getString(stringValue); ASSERT_EQ("SM", std::string(stringValue)); findElement(dataSet.get(), DCM_ImageType)->getString(stringValue); ASSERT_EQ("DERIVED\\PRIMARY\\VOLUME\\RESAMPLED", std::string(stringValue)); findElement(dataSet.get(), DCM_ImageOrientationSlide)->getString(stringValue); ASSERT_EQ("0\\-1\\0\\-1\\0\\0", std::string(stringValue)); Uint16 frameNumber; findElement(dataSet.get(), DCM_RepresentativeFrameNumber) ->getUint16(frameNumber); ASSERT_EQ(1, frameNumber); } TEST(insertIdsTest, correctInsert) { std::unique_ptr<DcmDataset> dataSet = std::make_unique<DcmDataset>(); wsiToDicomConverter::DcmtkUtils::insertIds("study", "series", dataSet.get()); ASSERT_NE(nullptr, findElement(dataSet.get(), DCM_SOPInstanceUID)); char* stringValue; findElement(dataSet.get(), DCM_StudyInstanceUID)->getString(stringValue); ASSERT_EQ("study", std::string(stringValue)); findElement(dataSet.get(), DCM_SeriesInstanceUID)->getString(stringValue); ASSERT_EQ("series", std::string(stringValue)); } TEST(insertMultiFrameTagsTest, correctInsert) { std::unique_ptr<DcmDataset> dataSet = std::make_unique<DcmDataset>(); DcmtkImgDataInfo imgInfo; imgInfo.rows = 10; imgInfo.cols = 10; wsiToDicomConverter::DcmtkUtils::insertMultiFrameTags( imgInfo, 5, 10, 0, 0, 0, 0, 0, 10, true, "series", dataSet.get()); char* stringValue; findElement(dataSet.get(), DCM_InstanceNumber)->getString(stringValue); ASSERT_EQ("1", std::string(stringValue)); findElement(dataSet.get(), DCM_FrameOfReferenceUID)->getString(stringValue); ASSERT_EQ("series.1", std::string(stringValue)); findElement(dataSet.get(), DCM_DimensionOrganizationType) ->getString(stringValue); ASSERT_EQ("TILED_FULL", std::string(stringValue)); Uint32 offset; findElement(dataSet.get(), DCM_ConcatenationFrameOffsetNumber) ->getUint32(offset); ASSERT_EQ(0, offset); Uint16 batchNumber; findElement(dataSet.get(), DCM_InConcatenationNumber)->getUint16(batchNumber); ASSERT_EQ(1, batchNumber); Uint16 concatenationTotalNumber; findElement(dataSet.get(), DCM_InConcatenationTotalNumber) ->getUint16(concatenationTotalNumber); ASSERT_EQ(2, concatenationTotalNumber); wsiToDicomConverter::DcmtkUtils::insertMultiFrameTags( imgInfo, 4, 5, 1, 1, 0, 0, 0, 105, false, "series", dataSet.get()); findElement(dataSet.get(), DCM_InConcatenationTotalNumber) ->getUint16(concatenationTotalNumber); ASSERT_EQ(27, concatenationTotalNumber); findElement(dataSet.get(), DCM_DimensionOrganizationType) ->getString(stringValue); ASSERT_EQ("TILED_SPARSE", std::string(stringValue)); DcmSequenceOfItems* element = reinterpret_cast<DcmSequenceOfItems*>( findElement(dataSet.get(), DCM_PerFrameFunctionalGroupsSequence)); ASSERT_NE(nullptr, element); Sint32 column; // 3rd item of 1st batch should be in 4th column findElement( reinterpret_cast<DcmSequenceOfItems*>( findElement(element->getItem(3), DCM_PlanePositionSlideSequence)) ->getItem(0), DCM_ColumnPositionInTotalImagePixelMatrix) ->getSint32(column); ASSERT_EQ(31, column); Sint32 row; // 2nd item of 1st batch should be in 1st row findElement( reinterpret_cast<DcmSequenceOfItems*>( findElement(element->getItem(1), DCM_PlanePositionSlideSequence)) ->getItem(0), DCM_RowPositionInTotalImagePixelMatrix) ->getSint32(row); ASSERT_EQ(1, row); dataSet = std::make_unique<DcmDataset>(); wsiToDicomConverter::DcmtkUtils::insertMultiFrameTags( imgInfo, 4, 5, 1, 5, 1, 1, 4, 105, false, "series", dataSet.get()); element = reinterpret_cast<DcmSequenceOfItems*>( findElement(dataSet.get(), DCM_PerFrameFunctionalGroupsSequence)); // 1nd item of 2nd batch should be in 5th column findElement( reinterpret_cast<DcmSequenceOfItems*>( findElement(element->getItem(0), DCM_PlanePositionSlideSequence)) ->getItem(0), DCM_ColumnPositionInTotalImagePixelMatrix) ->getSint32(column); ASSERT_EQ(41, column); // 2nd item of 2nd batch should be in 1st column findElement( reinterpret_cast<DcmSequenceOfItems*>( findElement(element->getItem(1), DCM_PlanePositionSlideSequence)) ->getItem(0), DCM_ColumnPositionInTotalImagePixelMatrix) ->getSint32(column); ASSERT_EQ(1, column); // 1st item of 2nd batch should be in 1st row findElement( reinterpret_cast<DcmSequenceOfItems*>( findElement(element->getItem(0), DCM_PlanePositionSlideSequence)) ->getItem(0), DCM_RowPositionInTotalImagePixelMatrix) ->getSint32(row); ASSERT_EQ(1, row); // 2nd item of 2nd batch should be in 2nd row findElement( reinterpret_cast<DcmSequenceOfItems*>( findElement(element->getItem(1), DCM_PlanePositionSlideSequence)) ->getItem(0), DCM_RowPositionInTotalImagePixelMatrix) ->getSint32(row); ASSERT_EQ(11, row); } <|endoftext|>
<commit_before>#include <string> #include <queue> #include <iostream> #include "tpunit++.hpp" #include "fakeit.h" #include "fakeit/Exceptions.h" using namespace fakeit; using namespace std; struct DemoTests : tpunit::TestFixture { DemoTests() : tpunit::TestFixture( // // TEST(DemoTests::calling_an_unstubbed_method_should_raise_UnmockedMethodCallException), // // TEST(DemoTests::stub_method_to_default_behaviore_will_always_return_do_the_default_behaviore), // // TEST(DemoTests::stub_multiple_methods_to_default_behaviore), TEST(DemoTests::basic_stubbing), TEST(DemoTests::basic_verification) // TEST(DemoTests::stub_a_function_to_return_a_specified_value_always), // TEST(DemoTests::stub_a_method_to_throw_a_specified_exception_once), // // TEST(DemoTests::stub_a_method_with_lambda_delegate_once), // // TEST(DemoTests::stub_a_method_with_lambda_delegate_always), // // TEST(DemoTests::stub_a_method_with_static_method_delegate), // // TEST(DemoTests::stub_by_assignment_with_lambda_delegate), // // TEST(DemoTests::stub_by_assignment_with_static_method_delegate), // // TEST(DemoTests::stub_to_default_behavior_with_filter), // // TEST(DemoTests::change_method_behavior_with_filter), // // TEST(DemoTests::change_method_behavior_with_functor_filter), // // TEST(DemoTests::change_method_behavior_with_matcher), // // TEST(DemoTests::change_method_behavior_with_functor_matcher), // // TEST(DemoTests::stub_multiple_return_values), // // TEST(DemoTests::stub_multiple_return_values_using_quque), // // TEST(DemoTests::stub_multiple_throws), // TEST(DemoTests::stub_overloaded_methods) // ) { } struct SomeInterface { virtual int foo(int) = 0; virtual int bar(string) = 0; virtual void proc(int) = 0; }; // void calling_an_unstubbed_method_should_raise_UnmockedMethodCallException() { // Mock<SomeInterface> mock; // SomeInterface &i = mock.get(); // ASSERT_THROW(i.bar(1), UnmockedMethodCallException); // ASSERT_THROW(i.foo(1), UnmockedMethodCallException); // } // // void stub_method_to_default_behaviore_will_always_return_do_the_default_behaviore() { // Mock<SomeInterface> mock; // // Stub(mock[&SomeInterface::bar]); // Stub(mock[&SomeInterface::foo]); // // SomeInterface &i = mock.get(); // // ASSERT_EQUAL(0, i.bar(1)); // ASSERT_NO_THROW(i.foo(1)); // // ASSERT_EQUAL(0, i.bar(1)); // ASSERT_NO_THROW(i.foo(1)); // } // // void stub_multiple_methods_to_default_behaviore() { // Mock<SomeInterface> mock; // // Stub(mock[&SomeInterface::bar], mock[&SomeInterface::foo]); // // SomeInterface &i = mock.get(); // // ASSERT_EQUAL(0, i.bar(1)); // ASSERT_NO_THROW(i.foo(1)); // // ASSERT_EQUAL(0, i.bar(1)); // ASSERT_NO_THROW(i.foo(1)); // } // void basic_stubbing() { // Instantiate a mock object. Mock<SomeInterface> mock; // Setup mock behavior. When(mock[&SomeInterface::foo]).AlwaysReturn(1); // Fetch the mock instance. SomeInterface &i = mock.get(); // Will print "1". cout << i.foo(0); } void basic_verification(){ Mock<SomeInterface> mock; // When(mock[&SomeInterface::foo]).AlwaysReturn(0); When(mock[&SomeInterface::bar]).AlwaysReturn(0); SomeInterface &i = mock.get(); // Production code i.foo(1); i.bar("some value"); // Verify for foo & bar where invoked Verify(mock[&SomeInterface::foo]); Verify(mock[&SomeInterface::bar]); // Verify for foo & bar where invoked with specific arguments Verify(mock[&SomeInterface::foo].Using(1)); Verify(mock[&SomeInterface::bar].Using("some value")); // Verify for foo & bar where never invoked with other arguments Verify(mock[&SomeInterface::foo].Using(2)).Never(); Verify(mock[&SomeInterface::bar].Using("some other value")).Never(); } // // void stub_a_function_to_return_a_specified_value_always() { // Mock<SomeInterface> mock; // // When(mock[&SomeInterface::bar]).AlwaysReturn(1); // // SomeInterface &i = mock.get(); // // ASSERT_EQUAL(1, i.bar(1)); // ASSERT_EQUAL(1, i.bar(1)); // } // // // void stub_a_method_to_throw_a_specified_exception_once() { // Mock<SomeInterface> mock; // // When(mock[&SomeInterface::bar]).Throw(std::string("func exception")); // When(mock[&SomeInterface::foo]).Throw(std::string("proc exception")); // // SomeInterface &i = mock.get(); // // try { // i.bar(1); // } // catch (std::string e) { // ASSERT_EQUAL(std::string("func exception"), e); // } // // try { // i.foo(1); // } // catch (std::string e) { // ASSERT_EQUAL(std::string("proc exception"), e); // } // // ASSERT_THROW(i.bar(1), fakeit::UnmockedMethodCallException); // ASSERT_THROW(i.foo(1), fakeit::UnmockedMethodCallException); // } // // void stub_a_method_with_lambda_delegate_once() { // Mock<SomeInterface> mock; // // int a = 0; // // When(mock[&SomeInterface::bar]).Do([](int val) {return val; }); // When(mock[&SomeInterface::foo]).Do([&a](int val) {a = val; }); // // SomeInterface &i = mock.get(); // // ASSERT_EQUAL(3, i.bar(3)); // // i.foo(3); // ASSERT_EQUAL(3, a); // // ASSERT_THROW(i.bar(3), fakeit::UnmockedMethodCallException); // ASSERT_THROW(i.foo(3), fakeit::UnmockedMethodCallException); // } // // void stub_a_method_with_lambda_delegate_always() { // Mock<SomeInterface> mock; // // int a = 0; // // When(mock[&SomeInterface::bar]).AlwaysDo([](int val) {return val; }); // When(mock[&SomeInterface::foo]).AlwaysDo([&a](int val) {a = val; }); // // SomeInterface &i = mock.get(); // // ASSERT_EQUAL(3, i.bar(3)); // ASSERT_EQUAL(3, i.bar(3)); // // i.foo(3); // ASSERT_EQUAL(3, a); // // a = 0; // i.foo(3); // ASSERT_EQUAL(3, a); // } // // static int func_delegate(int val) { // return val; // } // // static void proc_delegate(int val) { // throw val; // } // // void stub_a_method_with_static_method_delegate() { // Mock<SomeInterface> mock; // // When(mock[&SomeInterface::bar]).Do(func_delegate); // When(mock[&SomeInterface::foo]).Do(proc_delegate); // // SomeInterface &i = mock.get(); // // ASSERT_EQUAL(3, i.bar(3)); // // try { // i.foo(1); // } // catch (int e) { // ASSERT_EQUAL(1, e); // } // } // // void stub_by_assignment_with_lambda_delegate() { // Mock<SomeInterface> mock; // // int a = 0; // // mock[&SomeInterface::bar] = [](int val) {return val; }; // mock[&SomeInterface::foo] = [&a](int val) {a = val; }; // // SomeInterface &i = mock.get(); // // ASSERT_EQUAL(3, i.bar(3)); // // i.foo(3); // ASSERT_EQUAL(3, a); // } // // void stub_by_assignment_with_static_method_delegate() { // Mock<SomeInterface> mock; // // mock[&SomeInterface::bar] = func_delegate; // mock[&SomeInterface::foo] = proc_delegate; // // SomeInterface &i = mock.get(); // // ASSERT_EQUAL(3, i.bar(3)); // // try { // i.foo(1); // } // catch (int e) { // ASSERT_EQUAL(1, e); // } // } // // void stub_to_default_behavior_with_filter() { // Mock<SomeInterface> mock; // // Stub(mock[&SomeInterface::bar].Using(1)); // Stub(mock[&SomeInterface::foo].Using(1)); // // SomeInterface &i = mock.get(); // // ASSERT_EQUAL(0, i.bar(1)); // ASSERT_THROW(i.bar(2), fakeit::UnmockedMethodCallException); // // i.foo(1); // ASSERT_THROW(i.foo(2), fakeit::UnmockedMethodCallException); // } // // void change_method_behavior_with_filter() { // class Exc : public std::exception { // } e; // // Mock<SomeInterface> mock; // // When(mock[&SomeInterface::bar].Using(1)).Return(1); // When(mock[&SomeInterface::foo].Using(1)).Throw(e); // // SomeInterface &i = mock.get(); // // ASSERT_EQUAL(1, i.bar(1)); // ASSERT_THROW(i.bar(2), fakeit::UnmockedMethodCallException); // // ASSERT_THROW(i.foo(1), Exc); // ASSERT_THROW(i.foo(2), fakeit::UnmockedMethodCallException); // } // // void change_method_behavior_with_functor_filter() { // class Exc : public std::exception { // } e; // // Mock<SomeInterface> mock; // // When(mock[&SomeInterface::bar](1)).Return(1); // When(mock[&SomeInterface::foo](1)).Throw(e); // // SomeInterface &i = mock.get(); // // ASSERT_EQUAL(1, i.bar(1)); // ASSERT_THROW(i.bar(2), fakeit::UnmockedMethodCallException); // // ASSERT_THROW(i.foo(1), Exc); // ASSERT_THROW(i.foo(2), fakeit::UnmockedMethodCallException); // } // // void change_method_behavior_with_matcher() { // class Exc : public std::exception { // } e; // // Mock<SomeInterface> mock; // // When(mock[&SomeInterface::bar].Matching([](int a) {return a == 1; })).Return(1); // When(mock[&SomeInterface::foo].Matching([](int a) {return a == 1; })).Throw(e); // // SomeInterface &i = mock.get(); // // ASSERT_EQUAL(1, i.bar(1)); // ASSERT_THROW(i.bar(2), fakeit::UnmockedMethodCallException); // // ASSERT_THROW(i.foo(1), Exc); // ASSERT_THROW(i.foo(2), fakeit::UnmockedMethodCallException); // } // // void change_method_behavior_with_functor_matcher() { // class Exc : public std::exception { // } e; // // Mock<SomeInterface> mock; // // When(mock[&SomeInterface::bar]([](int a) {return a == 1; })).Return(1); // When(mock[&SomeInterface::foo]([](int a) {return a == 1; })).Throw(e); // // SomeInterface &i = mock.get(); // // ASSERT_EQUAL(1, i.bar(1)); // ASSERT_THROW(i.bar(2), fakeit::UnmockedMethodCallException); // // ASSERT_THROW(i.foo(1), Exc); // ASSERT_THROW(i.foo(2), fakeit::UnmockedMethodCallException); // } // // void stub_multiple_return_values() { // Mock<SomeInterface> mock; // // When(mock[&SomeInterface::bar]).Return(1).Return(2); // // SomeInterface &i = mock.get(); // // ASSERT_EQUAL(1, i.bar(0)); // ASSERT_EQUAL(2, i.bar(0)); // // ASSERT_THROW(i.bar(0), fakeit::UnmockedMethodCallException); // ASSERT_THROW(i.bar(0), fakeit::UnmockedMethodCallException); // } // // void stub_multiple_return_values_using_quque() { // Mock<SomeInterface> mock; // std::queue<int> q({ 1, 2 }); // // When(mock[&SomeInterface::bar]).AlwaysDo([&](...) {int rv = q.front(); q.pop(); return rv; }); // // SomeInterface &i = mock.get(); // // ASSERT_EQUAL(1, i.bar(0)); // ASSERT_EQUAL(2, i.bar(0)); // } // // // void stub_multiple_throws() { // // Mock<SomeInterface> mock; // // When(mock[&SomeInterface::bar]).Throw(std::string("A")).Throw(std::string("B")); // When(mock[&SomeInterface::foo]).Throw(std::string("A")).Throw(std::string("B")); // // SomeInterface &i = mock.get(); // // try { // i.bar(0); // } // catch (std::string & e) { // ASSERT_EQUAL(std::string("A"), e); // } // // try { // i.bar(0); // } // catch (std::string & e) { // ASSERT_EQUAL(std::string("B"), e); // } // // try { // i.foo(0); // } // catch (std::string & e) { // ASSERT_EQUAL(std::string("A"), e); // } // // try { // i.foo(0); // } // catch (std::string & e) { // ASSERT_EQUAL(std::string("B"), e); // } // } // // struct OverloadedInterface { // virtual int func() = 0; // virtual int func(int) = 0; // virtual int func(bool) = 0; // }; // // void stub_overloaded_methods() { // Mock<OverloadedInterface> mock; // // int (OverloadedInterface::*void_method_ptr)() = &OverloadedInterface::func; // int (OverloadedInterface::*int_method_ptr)(int) = &OverloadedInterface::func; // int (OverloadedInterface::*bool_method_ptr)(bool) = &OverloadedInterface::func; // // Stub(mock[void_method_ptr]); // Stub(mock[int_method_ptr]); // Stub(mock[bool_method_ptr]); // // OverloadedInterface &i = mock.get(); // // ASSERT_EQUAL(0, i.func()); // ASSERT_EQUAL(0, i.func(1)); // ASSERT_EQUAL(0, i.func(true)); // } } __DemoTests; <commit_msg>cleanup<commit_after>#include <string> #include <queue> #include <iostream> #include "tpunit++.hpp" #include "fakeit.h" #include "fakeit/Exceptions.h" using namespace fakeit; using namespace std; struct DemoTests: tpunit::TestFixture { DemoTests() : tpunit::TestFixture( // TEST(DemoTests::basic_stubbing), // TEST(DemoTests::basic_verification) // // ) { } struct SomeInterface { virtual int foo(int) = 0; virtual int bar(string) = 0; virtual void proc(int) = 0; }; void basic_stubbing() { // Instantiate a mock object. Mock<SomeInterface> mock; // Setup mock behavior. When(mock[&SomeInterface::foo]).AlwaysReturn(1); // Fetch the mock instance. SomeInterface &i = mock.get(); // Will print "1". cout << i.foo(0); } void basic_verification() { Mock<SomeInterface> mock; // When(mock[&SomeInterface::foo]).AlwaysReturn(0); When(mock[&SomeInterface::bar]).AlwaysReturn(0); SomeInterface &i = mock.get(); // Production code i.foo(1); i.bar("some value"); // Verify for foo & bar where invoked Verify(mock[&SomeInterface::foo]); Verify(mock[&SomeInterface::bar]); // Verify for foo & bar where invoked with specific arguments Verify(mock[&SomeInterface::foo].Using(1)); Verify(mock[&SomeInterface::bar].Using("some value")); // Verify for foo & bar where never invoked with other arguments Verify(mock[&SomeInterface::foo].Using(2)).Never(); Verify(mock[&SomeInterface::bar].Using("some other value")).Never(); } } __DemoTests; <|endoftext|>
<commit_before>#include <stdio.h> #include <stdlib.h> #include <time.h> #include <opencv2/opencv.hpp> #include <opencv2/highgui/highgui.hpp> #include "camera.hpp" #pragma comment(lib,"opencv_world320.lib") static const int N = 256;//文字列の長さ static const int AOV = 62.2;//ANGLE OF VIEW //明度について static const int MAX_VALUE = 255;//明るさ最大 static const int NO_VALUE = 0;//明るさ最小 //時間を元にStringを作る char* makeTimeString(void) { static char timeString[N]; time_t timer;//時刻を受け取る変数 struct tm *timeptr;//日時を集めた構造体ポインタ time(&timer);//現在時刻の取得 timeptr = localtime(&timer);//ポインタ strftime(timeString, N, "%Y%m%d-%H%M%S", timeptr);//日時を文字列に変換してsに代入 return timeString; } char* makeBinaryString(char *timeString) { static char binaryString[N]; sprintf(binaryString, "%s%s",timeString,"Binary"); } //full_pathを作る char* makePath(char* name) { static char full_path[N];//NOTE 自動変数をreturn するために使った. smartなやり方か? char directry_path[] = "/home/pi/Pictures/";//pathの先頭 char file_extention[] = ".jpg";//拡張子 sprintf(full_path, "%s%s%s",directry_path,name, file_extention); return full_path; } //写真をとる int takePhoto(char* name) { char full_command[N]; char front_command[] = "raspistill -o ";//command sprintf(full_command, "%s%s", front_command, makePath(name));//コマンドの文字列をつなげる。 system(full_command);//raspistillで静止画を撮って日時を含むファイル名で保存。 printf("%s\n",full_command); //NOTE system関数以外を使うべきか? return 0; } //二値化画像を作成 cv::Mat binarize(cv::Mat src) { cv::Mat hsv; cv::Mat hsv_filtered15 = cv::Scalar(0, 0, 0);//画像の初期化 cv::Mat hsv_filtered180 = cv::Scalar(0, 0, 0);//画像の初期化 cv::cvtColor(src, hsv, CV_BGR2HSV);//入力画像(src)をhsv色空間(dst)に変換 //inRange(入力画像,下界画像,上界画像,出力画像) //「HSV」は、色を色相(Hue)・彩度(Saturation)・明度(Value) cv::inRange(hsv, cv::Scalar(0, 45, 70), cv::Scalar(12, 255, MAX_VALUE), hsv_filtered15); cv::inRange(hsv, cv::Scalar(160, 45, 70), cv::Scalar(180, 255, MAX_VALUE), hsv_filtered180); cv::add(hsv_filtered15,hsv_filtered180,hsv); return hsv; } //ノイズ除去 cv::Mat rmNoize(cv::Mat src) { cv::erode(src,src,cv::Mat(),cv::Point(-1, -1),10);//縮小処理 cv::dilate(src,src,cv::Mat(),cv::Point(-1, -1),25);//膨張処理 cv::erode(src,src,cv::Mat(),cv::Point(-1, -1),15);//縮小処理 return src; } int saveBinary(cv::Mat src,char* path) { cv::Mat binary_img; cv::resize(src,binary_img,cv::Size(),0.25,0.25,interpolation); return 0; } //写真を撮り画像処理する cv::Mat Mred(void) { char* stime = makeTimeString(); char* sbtime = makeBinaryString(btime); char* path = makePath(stime); char* bpath = makePath(btime); takePhoto(path); cv::Mat src = cv::imread(path);//画像の読み込み cv::Mat hsv; hsv = rmNoize(binarize(src)); saveBinary(hsv,bpath); return hsv; } //二値化した画像から1の面積を抽出 double countArea(cv::Mat src) { double Area = src.rows*src.cols;//全ピクセル数 double redCount = 0; //赤色を認識したピクセルの数 redCount = cv::countNonZero(src);//赤色部分の面積を計算 double percentage = 0; //割合 percentage = (redCount / Area)*100;//割合を計算 printf("面積のPercentageは%f\n", percentage); return percentage; } //二値化画像のcenterを角度で返す double getCenter(cv::Mat src) { cv::Moments mu = cv::moments(src, false);//重心の計算結果をmuに代入 double mc = mu.m10 / mu.m00;//重心のx座標 double center = (mc - src.cols / 2) * AOV / src.cols;//正規化 printf("重心の位置は%f\n",center); return center; } <commit_msg>debug<commit_after>#include <stdio.h> #include <stdlib.h> #include <time.h> #include <opencv2/opencv.hpp> #include <opencv2/highgui/highgui.hpp> #include "camera.hpp" #pragma comment(lib,"opencv_world320.lib") static const int N = 256;//文字列の長さ static const int AOV = 62.2;//ANGLE OF VIEW //明度について static const int MAX_VALUE = 255;//明るさ最大 static const int NO_VALUE = 0;//明るさ最小 //時間を元にStringを作る char* makeTimeString(void) { static char timeString[N]; time_t timer;//時刻を受け取る変数 struct tm *timeptr;//日時を集めた構造体ポインタ time(&timer);//現在時刻の取得 timeptr = localtime(&timer);//ポインタ strftime(timeString, N, "%Y%m%d-%H%M%S", timeptr);//日時を文字列に変換してsに代入 return timeString; } char* makeBinaryString(char *timeString) { static char binaryString[N]; sprintf(binaryString, "%s%s",timeString,"Binary"); } //full_pathを作る char* makePath(char* name) { static char full_path[N];//NOTE 自動変数をreturn するために使った. smartなやり方か? char directry_path[] = "/home/pi/Pictures/";//pathの先頭 char file_extention[] = ".jpg";//拡張子 sprintf(full_path, "%s%s%s",directry_path,name, file_extention); return full_path; } //写真をとる int takePhoto(char* name) { char full_command[N]; char front_command[] = "raspistill -o ";//command sprintf(full_command, "%s%s", front_command, makePath(name));//コマンドの文字列をつなげる。 system(full_command);//raspistillで静止画を撮って日時を含むファイル名で保存。 printf("%s\n",full_command); //NOTE system関数以外を使うべきか? return 0; } //二値化画像を作成 cv::Mat binarize(cv::Mat src) { cv::Mat hsv; cv::Mat hsv_filtered15 ;//画像の初期化 cv::Mat hsv_filtered180;//画像の初期化 cv::cvtColor(src, hsv, CV_BGR2HSV);//入力画像(src)をhsv色空間(dst)に変換 //inRange(入力画像,下界画像,上界画像,出力画像) //「HSV」は、色を色相(Hue)・彩度(Saturation)・明度(Value) cv::inRange(hsv, cv::Scalar(0, 45, 70), cv::Scalar(12, 255, MAX_VALUE), hsv_filtered15); cv::inRange(hsv, cv::Scalar(160, 45, 70), cv::Scalar(180, 255, MAX_VALUE), hsv_filtered180); cv::add(hsv_filtered15,hsv_filtered180,hsv); return hsv; } //ノイズ除去 cv::Mat rmNoize(cv::Mat src) { cv::erode(src,src,cv::Mat(),cv::Point(-1, -1),10);//縮小処理 cv::dilate(src,src,cv::Mat(),cv::Point(-1, -1),25);//膨張処理 cv::erode(src,src,cv::Mat(),cv::Point(-1, -1),15);//縮小処理 return src; } int saveBinary(cv::Mat src,char* path) { cv::Mat binary_img; cv::resize(src,binary_img,cv::Size(),0.25,0.25,interpolation); return 0; } //写真を撮り画像処理する cv::Mat Mred(void) { char* stime = makeTimeString(); char* sbtime = makeBinaryString(btime); char* path = makePath(stime); char* bpath = makePath(btime); takePhoto(path); cv::Mat src = cv::imread(path);//画像の読み込み cv::Mat hsv; hsv = rmNoize(binarize(src)); saveBinary(hsv,bpath); return hsv; } //二値化した画像から1の面積を抽出 double countArea(cv::Mat src) { double Area = src.rows*src.cols;//全ピクセル数 double redCount = 0; //赤色を認識したピクセルの数 redCount = cv::countNonZero(src);//赤色部分の面積を計算 double percentage = 0; //割合 percentage = (redCount / Area)*100;//割合を計算 printf("面積のPercentageは%f\n", percentage); return percentage; } //二値化画像のcenterを角度で返す double getCenter(cv::Mat src) { cv::Moments mu = cv::moments(src, false);//重心の計算結果をmuに代入 double mc = mu.m10 / mu.m00;//重心のx座標 double center = (mc - src.cols / 2) * AOV / src.cols;//正規化 printf("重心の位置は%f\n",center); return center; } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: Image5.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ // Software Guide : BeginLatex // // This example illustrates how to import data in to the \doxygen{Image}. This // is particularly useful for interfacing with other software systems which use // a different data structure for representing images. It is quite common to // use a contiguous block of memory as buffer for the image pixel data. The // current example assumes this is the case and uses this block of memory to // feed data into \doxygen{ImportImageFilter} that will produce an // \doxygen{Image} as output. // // For the sake of having some fun, we create a synthetic image with a centered // sphere in a locally allocated buffer and pass this block of memory to the // \code{ImportImageFilter}. // // \index{itk::ImportImageFilter!Instantiation} // \index{itk::ImportImageFilter!Header} // // First, the header file of the \doxygen{ImportImageFilter} class must be // included. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet #include "itkImage.h" #include "itkImportImageFilter.h" // Software Guide : EndCodeSnippet #include "itkImageFileWriter.h" int main(int argc, char ** argv) { if( argc < 2 ) { std::cerr << "Usage: " << std::endl; std::cerr << argv[0] << " outputImageFile" << std::endl; return 1; } // Software Guide : BeginLatex // // We select here the data type to use for representing image pixels. We // assume that the external block of memory uses the same data type to // represent the pixels. // // Software Guide : EndLatex // // Software Guide : BeginCodeSnippet typedef unsigned char PixelType; const unsigned int Dimension = 3; typedef itk::Image< PixelType, Dimension > ImageType; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The type of the \doxygen{ImportImageFilter} is instantiated in the // following line. // // \index{itk::ImportImageFilter!Instantiation} // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef itk::ImportImageFilter< PixelType, Dimension > ImportFilterType; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // A filter object is created using the \code{New()} method and assigning // the result to a \code{SmartPointer}. // // \index{itk::ImportImageFilter!Pointer} // \index{itk::ImportImageFilter!New()} // // Software Guide : EndLatex // // Software Guide : BeginCodeSnippet ImportFilterType::Pointer importFilter = ImportFilterType::New(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // This filter requires the user to specify the size of the image to be // produced as output. The methods \code(SetRegion()} is used to this end. // The image size should match exactly the number of pixels available in the // locally allocated buffer. // // \index{itk::ImportImageFilter!SetRegion()} // \index{itk::ImportImageFilter!New()} // \index{itk::ImportImageFilter!New()} // // Software Guide : EndLatex // // Software Guide : BeginCodeSnippet ImportFilterType::SizeType size; size[0] = 200; // size along X size[1] = 200; // size along Y size[2] = 200; // size along Z ImportFilterType::IndexType start; start.Fill( 0 ); ImportFilterType::RegionType region; region.SetIndex( start ); region.SetSize( size ); importFilter->SetRegion( region ); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The origin of the output image is specified with the \code{SetOrigin()} // method. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet double origin[ Dimension ]; origin[0] = 0.0; // X coordinate origin[1] = 0.0; // Y coordinate origin[2] = 0.0; // Z coordinate importFilter->SetOrigin( origin ); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The spacing of the image is passed with the \code{SetSpacing()} method. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet double spacing[ Dimension ]; spacing[0] = 1.0; // along X direction spacing[1] = 1.0; // along Y direction spacing[2] = 1.0; // along Z direction importFilter->SetSpacing( spacing ); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We allocate now the memory block that will contain the pixel data to be // passed to the \code{ImportImageFilter}. Note that we use exactly the same // size that was promised to the filter with the \code{SetRegion()} method. // In a practical application you may get this buffer from some other // library using a different data structure for representing images. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet const unsigned int numberOfPixels = size[0] * size[1] * size[2]; PixelType * localBuffer = new PixelType[ numberOfPixels ]; // Software Guide : EndCodeSnippet const double radius = 80.0; // Software Guide : BeginLatex // // Here we fill up the buffer with a binary sphere. We use good old-time // \code{for()} loops here... it looks just like FORTAN. Note that ITK does // not use \code{for()} loops in its internal code for accessing pixels. All // the pixel access tasks are performed using \doxygen{ImageIterator}s which // support managing $ND$ images. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet const double radius2 = radius * radius; PixelType * it = localBuffer; for(unsigned int z=0; z < size[2]; z++) { const double dz = static_cast<double>( z ) - size[2]/2.0; for(unsigned int y=0; y < size[1]; y++) { const double dy = static_cast<double>( y ) - size[1]/2.0; for(unsigned int x=0; x < size[0]; x++) { const double dx = static_cast<double>( x ) - size[0]/2.0; const double d2 = dx*dx + dy*dy + dz*dz; if( d2 < radius2 ) { *it++ = 255; } else { *it++ = 0; } } } } // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The buffer is passed to the \doxygen{ImportImageFilter} with the // \code{SetImportPointer()}. Note that the last argument of this method // specifies who will be responsible for deleting the memory block once it // is no longer in use. A \code{true} value indicates that the // \doxygen{ImportImageFilter} will not try to delete the buffer when its // destructor is called. A \code{false} on the other hand will allow the // filter to delete the memory block. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet const bool userPromiseToDeleteTheBuffer = false; importFilter->SetImportPointer( localBuffer, numberOfPixels, userPromiseToDeleteTheBuffer ); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Finally we can connect the output of this filter to a pipeline. Here, for // simplicity we just use a writer but it could be any other filter. // // Software Guide : EndLatex typedef itk::ImageFileWriter< ImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName( argv[1] ); // Software Guide : BeginCodeSnippet writer->SetInput( importFilter->GetOutput() ); // Software Guide : EndCodeSnippet try { writer->Update(); } catch( itk::ExceptionObject & exp ) { std::cerr << "Exception caught !" << std::endl; std::cerr << exp << std::endl; } // Software Guide : BeginLatex // // \textbf{Alert !}, note that we do not call \code{delete} on the buffer // since we pass \code{false} to the last argument of // \code{SetImportPointer()}. Now the buffer is owned by the // \code{ImportImageFilter}. // // Software Guide : EndLatex return 0; } <commit_msg>ENH: if() simplified using the ? : operator.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: Image5.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ // Software Guide : BeginLatex // // This example illustrates how to import data in to the \doxygen{Image}. This // is particularly useful for interfacing with other software systems which use // a different data structure for representing images. It is quite common to // use a contiguous block of memory as buffer for the image pixel data. The // current example assumes this is the case and uses this block of memory to // feed data into \doxygen{ImportImageFilter} that will produce an // \doxygen{Image} as output. // // For the sake of having some fun, we create a synthetic image with a centered // sphere in a locally allocated buffer and pass this block of memory to the // \code{ImportImageFilter}. // // \index{itk::ImportImageFilter!Instantiation} // \index{itk::ImportImageFilter!Header} // // First, the header file of the \doxygen{ImportImageFilter} class must be // included. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet #include "itkImage.h" #include "itkImportImageFilter.h" // Software Guide : EndCodeSnippet #include "itkImageFileWriter.h" int main(int argc, char ** argv) { if( argc < 2 ) { std::cerr << "Usage: " << std::endl; std::cerr << argv[0] << " outputImageFile" << std::endl; return 1; } // Software Guide : BeginLatex // // We select here the data type to use for representing image pixels. We // assume that the external block of memory uses the same data type to // represent the pixels. // // Software Guide : EndLatex // // Software Guide : BeginCodeSnippet typedef unsigned char PixelType; const unsigned int Dimension = 3; typedef itk::Image< PixelType, Dimension > ImageType; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The type of the \doxygen{ImportImageFilter} is instantiated in the // following line. // // \index{itk::ImportImageFilter!Instantiation} // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef itk::ImportImageFilter< PixelType, Dimension > ImportFilterType; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // A filter object is created using the \code{New()} method and assigning // the result to a \code{SmartPointer}. // // \index{itk::ImportImageFilter!Pointer} // \index{itk::ImportImageFilter!New()} // // Software Guide : EndLatex // // Software Guide : BeginCodeSnippet ImportFilterType::Pointer importFilter = ImportFilterType::New(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // This filter requires the user to specify the size of the image to be // produced as output. The methods \code{SetRegion()} is used to this end. // The image size should match exactly the number of pixels available in the // locally allocated buffer. // // \index{itk::ImportImageFilter!SetRegion()} // \index{itk::ImportImageFilter!New()} // \index{itk::ImportImageFilter!New()} // // Software Guide : EndLatex // // Software Guide : BeginCodeSnippet ImportFilterType::SizeType size; size[0] = 200; // size along X size[1] = 200; // size along Y size[2] = 200; // size along Z ImportFilterType::IndexType start; start.Fill( 0 ); ImportFilterType::RegionType region; region.SetIndex( start ); region.SetSize( size ); importFilter->SetRegion( region ); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The origin of the output image is specified with the \code{SetOrigin()} // method. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet double origin[ Dimension ]; origin[0] = 0.0; // X coordinate origin[1] = 0.0; // Y coordinate origin[2] = 0.0; // Z coordinate importFilter->SetOrigin( origin ); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The spacing of the image is passed with the \code{SetSpacing()} method. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet double spacing[ Dimension ]; spacing[0] = 1.0; // along X direction spacing[1] = 1.0; // along Y direction spacing[2] = 1.0; // along Z direction importFilter->SetSpacing( spacing ); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We allocate now the memory block that will contain the pixel data to be // passed to the \code{ImportImageFilter}. Note that we use exactly the same // size that was promised to the filter with the \code{SetRegion()} method. // In a practical application you may get this buffer from some other // library using a different data structure for representing images. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet const unsigned int numberOfPixels = size[0] * size[1] * size[2]; PixelType * localBuffer = new PixelType[ numberOfPixels ]; // Software Guide : EndCodeSnippet const double radius = 80.0; // Software Guide : BeginLatex // // Here we fill up the buffer with a binary sphere. We use good old-time // \code{for()} loops here... it looks just like FORTAN. Note that ITK does // not use \code{for()} loops in its internal code for accessing pixels. All // the pixel access tasks are performed using \doxygen{ImageIterator}s which // support managing $ND$ images. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet const double radius2 = radius * radius; PixelType * it = localBuffer; for(unsigned int z=0; z < size[2]; z++) { const double dz = static_cast<double>( z ) - size[2]/2.0; for(unsigned int y=0; y < size[1]; y++) { const double dy = static_cast<double>( y ) - size[1]/2.0; for(unsigned int x=0; x < size[0]; x++) { const double dx = static_cast<double>( x ) - size[0]/2.0; const double d2 = dx*dx + dy*dy + dz*dz; *it++ = ( d2 < radius2 ) ? 255 : 0; } } } // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The buffer is passed to the \doxygen{ImportImageFilter} with the // \code{SetImportPointer()}. Note that the last argument of this method // specifies who will be responsible for deleting the memory block once it // is no longer in use. A \code{true} value indicates that the // \doxygen{ImportImageFilter} will not try to delete the buffer when its // destructor is called. A \code{false} on the other hand will allow the // filter to delete the memory block. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet const bool userPromiseToDeleteTheBuffer = false; importFilter->SetImportPointer( localBuffer, numberOfPixels, userPromiseToDeleteTheBuffer ); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Finally we can connect the output of this filter to a pipeline. Here, for // simplicity we just use a writer but it could be any other filter. // // Software Guide : EndLatex typedef itk::ImageFileWriter< ImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName( argv[1] ); // Software Guide : BeginCodeSnippet writer->SetInput( importFilter->GetOutput() ); // Software Guide : EndCodeSnippet try { writer->Update(); } catch( itk::ExceptionObject & exp ) { std::cerr << "Exception caught !" << std::endl; std::cerr << exp << std::endl; } // Software Guide : BeginLatex // // Note that we do not call \code{delete} on the buffer since we pass // \code{false} to the last argument of \code{SetImportPointer()}. Now the // buffer is owned by the \code{ImportImageFilter}. // // Software Guide : EndLatex return 0; } <|endoftext|>
<commit_before>/* openDCM, dimensional constraint manager Copyright (C) 2012 Stefan Troeger <stefantroeger@gmx.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more detemplate tails. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef GCM_DISTANCE3D_H #define GCM_DISTANCE3D_H #include "geometry.hpp" #include <opendcm/core/constraint.hpp> namespace dcm { template<typename Kernel> struct Distance::type< Kernel, tag::point3D, tag::point3D > { typedef typename Kernel::number_type Scalar; typedef typename Kernel::VectorMap Vector; typedef std::vector<typename Kernel::Vector3, Eigen::aligned_allocator<typename Kernel::Vector3> > Vec; Scalar value, sc_value; //template definition void calculatePseudo(typename Kernel::Vector& param1, Vec& v1, typename Kernel::Vector& param2, Vec& v2) {}; void setScale(Scalar scale) { sc_value = value*scale; }; Scalar calculate(Vector& param1, Vector& param2) { return (param1-param2).norm() - sc_value; }; Scalar calculateGradientFirst(Vector& param1, Vector& param2, Vector& dparam1) { return (param1-param2).dot(dparam1) / (param1-param2).norm(); }; Scalar calculateGradientSecond(Vector& param1, Vector& param2, Vector& dparam2) { return (param1-param2).dot(-dparam2) / (param1-param2).norm(); }; void calculateGradientFirstComplete(Vector& param1, Vector& param2, Vector& gradient) { gradient = (param1-param2) / (param1-param2).norm(); }; void calculateGradientSecondComplete(Vector& param1, Vector& param2, Vector& gradient) { gradient = (param2-param1) / (param1-param2).norm(); }; }; template<typename Kernel> struct Distance::type< Kernel, tag::point3D, tag::plane3D > { typedef typename Kernel::number_type Scalar; typedef typename Kernel::VectorMap Vector; typedef std::vector<typename Kernel::Vector3, Eigen::aligned_allocator<typename Kernel::Vector3> > Vec; Scalar value, sc_value; //template definition void calculatePseudo(typename Kernel::Vector& param1, Vec& v1, typename Kernel::Vector& param2, Vec& v2) { //typename Kernel::Vector3 pp = param1.head(3)- ((param1.head(3)-param2.head(3)).dot(param2.tail(3)) / param2.tail(3).norm()*(param2.tail(3))); //v2.push_back(pp); typename Kernel::Vector3 dir = (param1.template head<3>()-param2.template head<3>()).cross(param2.template segment<3>(3)); dir = dir.cross(param2.template segment<3>(3)).normalized(); typename Kernel::Vector3 pp = param2.head(3) + (param1.head(3)-param2.head(3)).norm()*dir; v2.push_back(pp); }; void setScale(Scalar scale) { sc_value = value*scale; }; Scalar calculate(Vector& param1, Vector& param2) { //(p1-p2)°n / |n| - distance return (param1.head(3)-param2.head(3)).dot(param2.tail(3)) / param2.tail(3).norm() - sc_value; }; Scalar calculateGradientFirst(Vector& param1, Vector& param2, Vector& dparam1) { //dp1°n / |n| //if(dparam1.norm()!=1) return 0; return (dparam1.head(3)).dot(param2.tail(3)) / param2.tail(3).norm(); }; Scalar calculateGradientSecond(Vector& param1, Vector& param2, Vector& dparam2) { const typename Kernel::Vector3 p1 = param1.head(3); const typename Kernel::Vector3 p2 = param2.head(3); const typename Kernel::Vector3 dp2 = dparam2.head(3); const typename Kernel::Vector3 n = param2.tail(3); const typename Kernel::Vector3 dn = dparam2.tail(3); //if(dparam2.norm()!=1) return 0; return (((-dp2).dot(n) + (p1-p2).dot(dn)) / n.norm() - (p1-p2).dot(n)* n.dot(dn)/std::pow(n.norm(),3)); }; void calculateGradientFirstComplete(Vector& param1, Vector& param2, Vector& gradient) { gradient = param2.tail(3) / param2.tail(3).norm(); }; void calculateGradientSecondComplete(Vector& param1, Vector& param2, Vector& gradient) { const typename Kernel::Vector3 p1m2 = param1.head(3) - param2.head(3); const typename Kernel::Vector3 n = param2.tail(3); gradient.head(3) = -n / n.norm(); gradient.tail(3) = (p1m2)/n.norm() - (p1m2).dot(n)*n/std::pow(n.norm(),3); }; }; template<typename Kernel> struct Distance::type< Kernel, tag::plane3D, tag::plane3D > : public Distance::type< Kernel, tag::point3D, tag::plane3D > { typedef typename Kernel::VectorMap Vector; void calculateGradientFirstComplete(Vector& p1, Vector& p2, Vector& g) { Distance::type< Kernel, tag::point3D, tag::plane3D >::calculateGradientFirstComplete(p1,p2,g); g.segment(3,3).setZero(); }; }; template<typename Kernel> struct Distance::type< Kernel, tag::point3D, tag::line3D > { typedef typename Kernel::number_type Scalar; typedef typename Kernel::VectorMap Vector; typedef typename Kernel::Vector3 Vector3; typedef std::vector<typename Kernel::Vector3, Eigen::aligned_allocator<typename Kernel::Vector3> > Vec; Scalar value, sc_value; Vector3 diff, n, dist; //template definition void calculatePseudo(typename Kernel::Vector& point, Vec& v1, typename Kernel::Vector& line, Vec& v2) { Vector3 pp = line.head(3) + (line.head(3)-point.head(3)).norm()*line.segment(3,3); v2.push_back(pp); }; void setScale(Scalar scale) { sc_value = value*scale; }; Scalar calculate(Vector& point, Vector& line) { //diff = point1 - point2 n = line.template segment<3>(3); diff = line.template head<3>() - point.template head<3>(); dist = diff - diff.dot(n)*n; return dist.norm() - sc_value; }; Scalar calculateGradientFirst(Vector& point, Vector& line, Vector& dpoint) { const Vector3 d_diff = -dpoint.template head<3>(); const Vector3 d_dist = d_diff - d_diff.dot(n)*n; return dist.dot(d_dist)/dist.norm(); }; Scalar calculateGradientSecond(Vector& point, Vector& line, Vector& dline) { const Vector3 d_diff = dline.template head<3>(); const Vector3 d_n = dline.template segment<3>(3); const Vector3 d_dist = d_diff - ((d_diff.dot(n)+diff.dot(d_n))*n + diff.dot(n)*d_n); return dist.dot(d_dist)/dist.norm(); }; void calculateGradientFirstComplete(Vector& point, Vector& line, Vector& gradient) { const Vector3 res = (n*n.transpose())*dist - dist; gradient.head(3) = res/dist.norm(); }; void calculateGradientSecondComplete(Vector& point, Vector& line, Vector& gradient) { const Vector3 res = (-n*n.transpose())*dist + dist; gradient.head(3) = res/dist.norm(); const Scalar mult = n.transpose()*dist; gradient.template segment<3>(3) = -(mult*diff + diff.dot(n)*dist)/dist.norm(); }; }; template<typename Kernel> struct Distance::type< Kernel, tag::line3D, tag::line3D > : public Distance::type< Kernel, tag::point3D, tag::line3D > { typedef typename Kernel::VectorMap Vector; void calculateGradientFirstComplete(Vector& p1, Vector& p2, Vector& g) { Distance::type< Kernel, tag::point3D, tag::line3D >::calculateGradientFirstComplete(p1,p2,g); g.segment(3,3).setZero(); }; }; template<typename Kernel> struct Distance::type< Kernel, tag::cylinder3D, tag::cylinder3D > : public Distance::type< Kernel, tag::line3D, tag::line3D > {}; } #endif //GCM_DISTANCE3D_H <commit_msg>correct point plane pseudopoint calculation<commit_after>/* openDCM, dimensional constraint manager Copyright (C) 2012 Stefan Troeger <stefantroeger@gmx.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more detemplate tails. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef GCM_DISTANCE3D_H #define GCM_DISTANCE3D_H #include "geometry.hpp" #include <opendcm/core/constraint.hpp> namespace dcm { template<typename Kernel> struct Distance::type< Kernel, tag::point3D, tag::point3D > { typedef typename Kernel::number_type Scalar; typedef typename Kernel::VectorMap Vector; typedef std::vector<typename Kernel::Vector3, Eigen::aligned_allocator<typename Kernel::Vector3> > Vec; Scalar value, sc_value; //template definition void calculatePseudo(typename Kernel::Vector& param1, Vec& v1, typename Kernel::Vector& param2, Vec& v2) {}; void setScale(Scalar scale) { sc_value = value*scale; }; Scalar calculate(Vector& param1, Vector& param2) { return (param1-param2).norm() - sc_value; }; Scalar calculateGradientFirst(Vector& param1, Vector& param2, Vector& dparam1) { return (param1-param2).dot(dparam1) / (param1-param2).norm(); }; Scalar calculateGradientSecond(Vector& param1, Vector& param2, Vector& dparam2) { return (param1-param2).dot(-dparam2) / (param1-param2).norm(); }; void calculateGradientFirstComplete(Vector& param1, Vector& param2, Vector& gradient) { gradient = (param1-param2) / (param1-param2).norm(); }; void calculateGradientSecondComplete(Vector& param1, Vector& param2, Vector& gradient) { gradient = (param2-param1) / (param1-param2).norm(); }; }; template<typename Kernel> struct Distance::type< Kernel, tag::point3D, tag::plane3D > { typedef typename Kernel::number_type Scalar; typedef typename Kernel::VectorMap Vector; typedef std::vector<typename Kernel::Vector3, Eigen::aligned_allocator<typename Kernel::Vector3> > Vec; Scalar value, sc_value; //template definition void calculatePseudo(typename Kernel::Vector& param1, Vec& v1, typename Kernel::Vector& param2, Vec& v2) { //typename Kernel::Vector3 pp = param1.head(3)- ((param1.head(3)-param2.head(3)).dot(param2.tail(3)) / param2.tail(3).norm()*(param2.tail(3))); //v2.push_back(pp); typename Kernel::Vector3 dir = (param1.template head<3>()-param2.template head<3>()).cross(param2.template segment<3>(3)); dir = param2.template segment<3>(3).cross(dir).normalized(); typename Kernel::Vector3 pp = param2.head(3) + (param1.head(3)-param2.head(3)).norm()*dir; v2.push_back(pp); }; void setScale(Scalar scale) { sc_value = value*scale; }; Scalar calculate(Vector& param1, Vector& param2) { //(p1-p2)°n / |n| - distance return (param1.head(3)-param2.head(3)).dot(param2.tail(3)) / param2.tail(3).norm() - sc_value; }; Scalar calculateGradientFirst(Vector& param1, Vector& param2, Vector& dparam1) { //dp1°n / |n| //if(dparam1.norm()!=1) return 0; return (dparam1.head(3)).dot(param2.tail(3)) / param2.tail(3).norm(); }; Scalar calculateGradientSecond(Vector& param1, Vector& param2, Vector& dparam2) { const typename Kernel::Vector3 p1 = param1.head(3); const typename Kernel::Vector3 p2 = param2.head(3); const typename Kernel::Vector3 dp2 = dparam2.head(3); const typename Kernel::Vector3 n = param2.tail(3); const typename Kernel::Vector3 dn = dparam2.tail(3); //if(dparam2.norm()!=1) return 0; return (((-dp2).dot(n) + (p1-p2).dot(dn)) / n.norm() - (p1-p2).dot(n)* n.dot(dn)/std::pow(n.norm(),3)); }; void calculateGradientFirstComplete(Vector& param1, Vector& param2, Vector& gradient) { gradient = param2.tail(3) / param2.tail(3).norm(); }; void calculateGradientSecondComplete(Vector& param1, Vector& param2, Vector& gradient) { const typename Kernel::Vector3 p1m2 = param1.head(3) - param2.head(3); const typename Kernel::Vector3 n = param2.tail(3); gradient.head(3) = -n / n.norm(); gradient.tail(3) = (p1m2)/n.norm() - (p1m2).dot(n)*n/std::pow(n.norm(),3); }; }; template<typename Kernel> struct Distance::type< Kernel, tag::plane3D, tag::plane3D > : public Distance::type< Kernel, tag::point3D, tag::plane3D > { typedef typename Kernel::VectorMap Vector; void calculateGradientFirstComplete(Vector& p1, Vector& p2, Vector& g) { Distance::type< Kernel, tag::point3D, tag::plane3D >::calculateGradientFirstComplete(p1,p2,g); g.segment(3,3).setZero(); }; }; template<typename Kernel> struct Distance::type< Kernel, tag::point3D, tag::line3D > { typedef typename Kernel::number_type Scalar; typedef typename Kernel::VectorMap Vector; typedef typename Kernel::Vector3 Vector3; typedef std::vector<typename Kernel::Vector3, Eigen::aligned_allocator<typename Kernel::Vector3> > Vec; Scalar value, sc_value; Vector3 diff, n, dist; //template definition void calculatePseudo(typename Kernel::Vector& point, Vec& v1, typename Kernel::Vector& line, Vec& v2) { Vector3 pp = line.head(3) + (line.head(3)-point.head(3)).norm()*line.segment(3,3); v2.push_back(pp); }; void setScale(Scalar scale) { sc_value = value*scale; }; Scalar calculate(Vector& point, Vector& line) { //diff = point1 - point2 n = line.template segment<3>(3); diff = line.template head<3>() - point.template head<3>(); dist = diff - diff.dot(n)*n; return dist.norm() - sc_value; }; Scalar calculateGradientFirst(Vector& point, Vector& line, Vector& dpoint) { const Vector3 d_diff = -dpoint.template head<3>(); const Vector3 d_dist = d_diff - d_diff.dot(n)*n; return dist.dot(d_dist)/dist.norm(); }; Scalar calculateGradientSecond(Vector& point, Vector& line, Vector& dline) { const Vector3 d_diff = dline.template head<3>(); const Vector3 d_n = dline.template segment<3>(3); const Vector3 d_dist = d_diff - ((d_diff.dot(n)+diff.dot(d_n))*n + diff.dot(n)*d_n); return dist.dot(d_dist)/dist.norm(); }; void calculateGradientFirstComplete(Vector& point, Vector& line, Vector& gradient) { const Vector3 res = (n*n.transpose())*dist - dist; gradient.head(3) = res/dist.norm(); }; void calculateGradientSecondComplete(Vector& point, Vector& line, Vector& gradient) { const Vector3 res = (-n*n.transpose())*dist + dist; gradient.head(3) = res/dist.norm(); const Scalar mult = n.transpose()*dist; gradient.template segment<3>(3) = -(mult*diff + diff.dot(n)*dist)/dist.norm(); }; }; template<typename Kernel> struct Distance::type< Kernel, tag::line3D, tag::line3D > : public Distance::type< Kernel, tag::point3D, tag::line3D > { typedef typename Kernel::VectorMap Vector; void calculateGradientFirstComplete(Vector& p1, Vector& p2, Vector& g) { Distance::type< Kernel, tag::point3D, tag::line3D >::calculateGradientFirstComplete(p1,p2,g); g.segment(3,3).setZero(); }; }; template<typename Kernel> struct Distance::type< Kernel, tag::cylinder3D, tag::cylinder3D > : public Distance::type< Kernel, tag::line3D, tag::line3D > {}; } #endif //GCM_DISTANCE3D_H <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: ImageRegistration4.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ // Software Guide : BeginLatex // // In this example, we will solve the our simple multi-modality problem // using another implementation of mutual information. One of main // difference between \code{MattesMutualInformationImageToImageMetric} // and \code{MutualInformationImageToImageMetric} is than only one // spatial sample set is used for the whole registration process instead // of using new samples every iteration. The use of a single sample // set results in a much smoother cost function and hence allows // the use of more intelligent optimizers. In this example, we // will use \code{RegularStepGradientDescentOptimizer}. // Another noticeable difference is that pre-normalization of the // images is not necessary as the metric rescales internally when // building up the discrete density functions. // Other differences between // the two mutual information implementation is described in detail // in Section \ref{sec:MutualInformationMetric}. // // \index{itk::ImageRegistrationMethod!Multi-Modality|textbf} // // The following headers declare the basic components of // the registration method. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet #include "itkImageRegistrationMethod.h" #include "itkTranslationTransform.h" #include "itkMattesMutualInformationImageToImageMetric.h" #include "itkLinearInterpolateImageFunction.h" #include "itkRegularStepGradientDescentOptimizer.h" #include "itkImage.h" // Software Guide : EndCodeSnippet #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkResampleImageFilter.h" #include "itkCastImageFilter.h" int main( int argc, char **argv ) { if( argc < 3 ) { std::cerr << "Missing Parameters " << std::endl; std::cerr << "Usage: " << argv[0]; std::cerr << " fixedImageFile movingImageFile "; std::cerr << "outputImagefile [differenceImage]" << std::endl; return 1; } const unsigned int Dimension = 2; typedef unsigned short PixelType; typedef itk::Image< PixelType, Dimension > FixedImageType; typedef itk::Image< PixelType, Dimension > MovingImageType; // Software Guide : BeginLatex // // In this example the image types and all registration components // apart from the metric is declared as in section // \ref{sec:IntroductionImageRegistration}. // // Software Guide : EndLatex typedef itk::TranslationTransform< double, Dimension > TransformType; typedef itk::RegularStepGradientDescentOptimizer OptimizerType; typedef itk::LinearInterpolateImageFunction< MovingImageType, double > InterpolatorType; typedef itk::ImageRegistrationMethod< FixedImageType, MovingImageType > RegistrationType; // Software Guide : BeginLatex // // The Mattes mutual information metric type is // instantiated using the image types. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef itk::MattesMutualInformationImageToImageMetric< FixedImageType, MovingImageType > MetricType; // Software Guide : EndCodeSnippet TransformType::Pointer transform = TransformType::New(); OptimizerType::Pointer optimizer = OptimizerType::New(); InterpolatorType::Pointer interpolator = InterpolatorType::New(); RegistrationType::Pointer registration = RegistrationType::New(); registration->SetOptimizer( optimizer ); registration->SetTransform( transform ); registration->SetInterpolator( interpolator ); // Software Guide : BeginLatex // // The metric is created using the \code{New()} method and then // connected to the registration object. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet MetricType::Pointer metric = MetricType::New(); registration->SetMetric( metric ); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The metric requires a two of parameters to be selected: the number // of bins used to compute the entropy and the number of spatial samples // used to compute the density estimates. In a typical scenario, 50 // histogram bins is sufficient and the metric is relatively insensitive // to changes in the number of bins. The number of spatial samples // to be used depends on the content of the image. If the images are // smooth and does not contain much detail, then using approximatedly // one percent of the pixels will do. On the other hand, if the images // are detailed, it may be necessary to use a much higher proportion, // say 20 percent. // // \index{itk::MattesMutualInformationImageToImageMetric!SetNumberOfHistogramBins()} // \index{itk::MattesMutualInformationImageToImageMetric!SetNumberOfSpatialSamples()} // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet metric->SetNumberOfHistogramBins( 50 ); metric->SetNumberOfSpatialSamples( 1000 ); // Software Guide : EndCodeSnippet typedef itk::ImageFileReader< FixedImageType > FixedImageReaderType; typedef itk::ImageFileReader< MovingImageType > MovingImageReaderType; FixedImageReaderType::Pointer fixedImageReader = FixedImageReaderType::New(); MovingImageReaderType::Pointer movingImageReader = MovingImageReaderType::New(); fixedImageReader->SetFileName( argv[1] ); movingImageReader->SetFileName( argv[2] ); registration->SetFixedImage( fixedImageReader->GetOutput() ); registration->SetMovingImage( movingImageReader->GetOutput() ); fixedImageReader->Update(); registration->SetFixedImageRegion( fixedImageReader->GetOutput()->GetBufferedRegion() ); typedef RegistrationType::ParametersType ParametersType; ParametersType initialParameters( transform->GetNumberOfParameters() ); initialParameters[0] = 0.0; // Initial offset in mm along X initialParameters[1] = 0.0; // Initial offset in mm along Y registration->SetInitialTransformParameters( initialParameters ); // Software Guide : BeginLatex // // Another significant difference in the metric is that it // computes the negative mutual information and hence we // need to minimize the cost function in this case. In this // example we will use the same optimizer parameters as in // section \ref{sec:sec:IntroductionImageRegistration}. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet optimizer->SetMaximumStepLength( 4.00 ); optimizer->SetMinimumStepLength( 0.01 ); optimizer->SetNumberOfIterations( 200 ); // Software Guide : EndCodeSnippet try { registration->StartRegistration(); } catch( itk::ExceptionObject & err ) { std::cout << "ExceptionObject caught !" << std::endl; std::cout << err << std::endl; return -1; } ParametersType finalParameters = registration->GetLastTransformParameters(); double TranslationAlongX = finalParameters[0]; double TranslationAlongY = finalParameters[1]; unsigned int numberOfIterations = optimizer->GetCurrentIteration(); double bestValue = optimizer->GetValue(); // // Print out results // std::cout << "Result = " << std::endl; std::cout << " Translation X = " << TranslationAlongX << std::endl; std::cout << " Translation Y = " << TranslationAlongY << std::endl; std::cout << " Iterations = " << numberOfIterations << std::endl; std::cout << " Metric value = " << bestValue << std::endl; // Software Guide : BeginLatex // // Let's execute this example using the same multi-modality images // as before. // The registration converged after 24 iterations and produce as result the // parameters: // // \begin{verbatim} // Translation X = 13.1719 // Translation Y = 16.9006 // \end{verbatim} // // These values are very close match to // the true misaligment introduced in the moving image. // // Software Guide : EndLatex typedef itk::ResampleImageFilter< MovingImageType, FixedImageType > ResampleFilterType; TransformType::Pointer finalTransform = TransformType::New(); finalTransform->SetParameters( finalParameters ); ResampleFilterType::Pointer resample = ResampleFilterType::New(); resample->SetTransform( finalTransform ); resample->SetInput( movingImageReader->GetOutput() ); FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); resample->SetSize( fixedImage->GetLargestPossibleRegion().GetSize() ); resample->SetOutputOrigin( fixedImage->GetOrigin() ); resample->SetOutputSpacing( fixedImage->GetSpacing() ); resample->SetDefaultPixelValue( 100 ); typedef unsigned char OutputPixelType; typedef itk::Image< OutputPixelType, Dimension > OutputImageType; typedef itk::CastImageFilter< FixedImageType, OutputImageType > CastFilterType; typedef itk::ImageFileWriter< OutputImageType > WriterType; WriterType::Pointer writer = WriterType::New(); CastFilterType::Pointer caster = CastFilterType::New(); writer->SetFileName( argv[3] ); caster->SetInput( resample->GetOutput() ); writer->SetInput( caster->GetOutput() ); writer->Update(); // Software Guide : BeginLatex // // \begin{figure} // \center // \includegraphics[width=5cm]{ImageRegistration4Output.eps} // \includegraphics[width=5cm]{ImageRegistration4CheckerboardBefore.eps} // \includegraphics[width=5cm]{ImageRegistration4CheckerboardAfter.eps} // \caption{Mapped moving image (left) and composition of fixed and moving // images before (center) and after (right) registration.} // \label{fig:ImageRegistration4Output} // \end{figure} // // The result of the resampling the moving image is presented in the left // side of Figure \ref{fig:ImageRegistration4Output}. The center and right // parts of the figure present a checkerboard composite of the fixed and // moving images before and after registration. // // Software Guide : EndLatex // Software Guide : BeginLatex // // \begin{figure} // \center // \includegraphics[width=7cm]{ImageRegistration2TraceTranslations.eps} // \includegraphics[width=7cm]{ImageRegistration2TraceTranslations2.eps} // \caption{Sequence of translations during the registration process. Left, // iterations form 0 to 200. Right iterations from 150 to 200.} // \label{fig:ImageRegistration2TraceTranslations} // \end{figure} // // Figure \ref{fig:ImageRegistration2TraceTranslations} presents the // sequence of translations followed by the optimizer as it searched the // parameter space. The left plot shows iterations $0$ to $200$ while the // right figure zooms into iterations $150$ to $200$. The area covered by // the right figure has been highlighted by a rectangle in the left image. // It can be seen that after a certain number of iterations the optimizer // oscillates within a one or two pixels of the true solution. // At this point it is // clear that more iterations will not help. Instead it is time to modify // some of the parameters of the registration process. For example, // reducing the learning rate of the optimizer and continuing the // registration so that smaller steps are taken. // // \begin{figure} // \center // \includegraphics[width=7cm]{ImageRegistration2TraceMetric.eps} // \includegraphics[width=7cm]{ImageRegistration2TraceMetric2.eps} // \caption{Sequence of metric values during the registration process. Left, // iterations form 0 to 300. Right, iterations from 100 to 200.} // \label{fig:ImageRegistration2TraceMetric} // \end{figure} // // Figure \ref{fig:ImageRegistration2TraceMetric} shows the sequence of // metric values computed as the optimizer searched the parameter space. // The left plot shows values when iterations are extended from $0$ to $300$ // while the right figure zooms into iterations $100$ to $200$. // The fluctuations in the measure value is due to the stochastic // nature in which the measure is computed. At each call of // \code{GetValue()}, two new sets of intensity samples is randomly // taken from the image to compute the density and entrophy estimates. // Even with the fluctuations, overall the measure initially increases // with the number of iterations. // After about 150 iterations the metric value oscilates // without further noticeable convergence. // The trace plots in Figure \ref{fig:ImageRegistration2TraceMetric} // highlights one of the difficulties with using this particular metric: // the stochastic oscillations makes it difficult to determine // convergence and limits the use of more sophisticated optimizations // methods. As explained above, // the reduction of the learning rate as the registration progresses // is very important to get precise results. // // This example highlight the importance of tracking the evolution of the // registration method in order to get some insight on the characteristics // of the particular problem at hand and the components being used. // The behavior revealed by these plots // usually helps to identify possible improvements in the setup of the // registration parameters. // // Software Guide : EndLatex return 0; } <commit_msg>ENH: Observer added.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: ImageRegistration4.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ // Software Guide : BeginLatex // // In this example, we will solve the our simple multi-modality problem // using another implementation of mutual information. One of main // difference between \code{MattesMutualInformationImageToImageMetric} // and \code{MutualInformationImageToImageMetric} is than only one // spatial sample set is used for the whole registration process instead // of using new samples every iteration. The use of a single sample // set results in a much smoother cost function and hence allows // the use of more intelligent optimizers. In this example, we // will use \code{RegularStepGradientDescentOptimizer}. // Another noticeable difference is that pre-normalization of the // images is not necessary as the metric rescales internally when // building up the discrete density functions. // Other differences between // the two mutual information implementation is described in detail // in Section \ref{sec:MutualInformationMetric}. // // \index{itk::ImageRegistrationMethod!Multi-Modality|textbf} // // The following headers declare the basic components of // the registration method. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet #include "itkImageRegistrationMethod.h" #include "itkTranslationTransform.h" #include "itkMattesMutualInformationImageToImageMetric.h" #include "itkLinearInterpolateImageFunction.h" #include "itkRegularStepGradientDescentOptimizer.h" #include "itkImage.h" // Software Guide : EndCodeSnippet #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkResampleImageFilter.h" #include "itkCastImageFilter.h" // // The following section of code implements a Command observer // that will monitor the evolution of the registration process. // #include "itkCommand.h" class CommandIterationUpdate : public itk::Command { public: typedef CommandIterationUpdate Self; typedef itk::Command Superclass; typedef itk::SmartPointer<Self> Pointer; itkNewMacro( Self ); protected: CommandIterationUpdate() {}; public: typedef itk::RegularStepGradientDescentOptimizer OptimizerType; typedef const OptimizerType * OptimizerPointer; void Execute(itk::Object *caller, const itk::EventObject & event) { Execute( (const itk::Object *)caller, event); } void Execute(const itk::Object * object, const itk::EventObject & event) { OptimizerPointer optimizer = dynamic_cast< OptimizerPointer >( object ); if( typeid( event ) != typeid( itk::IterationEvent ) ) { return; } std::cout << optimizer->GetCurrentIteration() << " "; std::cout << optimizer->GetValue() << " "; std::cout << optimizer->GetCurrentPosition(); } }; int main( int argc, char **argv ) { if( argc < 3 ) { std::cerr << "Missing Parameters " << std::endl; std::cerr << "Usage: " << argv[0]; std::cerr << " fixedImageFile movingImageFile "; std::cerr << "outputImagefile [differenceImage]" << std::endl; return 1; } const unsigned int Dimension = 2; typedef unsigned short PixelType; typedef itk::Image< PixelType, Dimension > FixedImageType; typedef itk::Image< PixelType, Dimension > MovingImageType; // Software Guide : BeginLatex // // In this example the image types and all registration components // apart from the metric is declared as in section // \ref{sec:IntroductionImageRegistration}. // // Software Guide : EndLatex typedef itk::TranslationTransform< double, Dimension > TransformType; typedef itk::RegularStepGradientDescentOptimizer OptimizerType; typedef itk::LinearInterpolateImageFunction< MovingImageType, double > InterpolatorType; typedef itk::ImageRegistrationMethod< FixedImageType, MovingImageType > RegistrationType; // Software Guide : BeginLatex // // The Mattes mutual information metric type is // instantiated using the image types. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef itk::MattesMutualInformationImageToImageMetric< FixedImageType, MovingImageType > MetricType; // Software Guide : EndCodeSnippet TransformType::Pointer transform = TransformType::New(); OptimizerType::Pointer optimizer = OptimizerType::New(); InterpolatorType::Pointer interpolator = InterpolatorType::New(); RegistrationType::Pointer registration = RegistrationType::New(); registration->SetOptimizer( optimizer ); registration->SetTransform( transform ); registration->SetInterpolator( interpolator ); // Software Guide : BeginLatex // // The metric is created using the \code{New()} method and then // connected to the registration object. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet MetricType::Pointer metric = MetricType::New(); registration->SetMetric( metric ); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The metric requires a two of parameters to be selected: the number // of bins used to compute the entropy and the number of spatial samples // used to compute the density estimates. In a typical scenario, 50 // histogram bins is sufficient and the metric is relatively insensitive // to changes in the number of bins. The number of spatial samples // to be used depends on the content of the image. If the images are // smooth and does not contain much detail, then using approximatedly // one percent of the pixels will do. On the other hand, if the images // are detailed, it may be necessary to use a much higher proportion, // say 20 percent. // // \index{itk::MattesMutualInformationImageToImageMetric!SetNumberOfHistogramBins()} // \index{itk::MattesMutualInformationImageToImageMetric!SetNumberOfSpatialSamples()} // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet metric->SetNumberOfHistogramBins( 50 ); metric->SetNumberOfSpatialSamples( 1000 ); // Software Guide : EndCodeSnippet typedef itk::ImageFileReader< FixedImageType > FixedImageReaderType; typedef itk::ImageFileReader< MovingImageType > MovingImageReaderType; FixedImageReaderType::Pointer fixedImageReader = FixedImageReaderType::New(); MovingImageReaderType::Pointer movingImageReader = MovingImageReaderType::New(); fixedImageReader->SetFileName( argv[1] ); movingImageReader->SetFileName( argv[2] ); registration->SetFixedImage( fixedImageReader->GetOutput() ); registration->SetMovingImage( movingImageReader->GetOutput() ); fixedImageReader->Update(); registration->SetFixedImageRegion( fixedImageReader->GetOutput()->GetBufferedRegion() ); typedef RegistrationType::ParametersType ParametersType; ParametersType initialParameters( transform->GetNumberOfParameters() ); initialParameters[0] = 0.0; // Initial offset in mm along X initialParameters[1] = 0.0; // Initial offset in mm along Y registration->SetInitialTransformParameters( initialParameters ); // Software Guide : BeginLatex // // Another significant difference in the metric is that it // computes the negative mutual information and hence we // need to minimize the cost function in this case. In this // example we will use the same optimizer parameters as in // section \ref{sec:sec:IntroductionImageRegistration}. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet optimizer->SetMaximumStepLength( 4.00 ); optimizer->SetMinimumStepLength( 0.01 ); optimizer->SetNumberOfIterations( 200 ); // Software Guide : EndCodeSnippet // // Create the Command observer and register it with the optimizer. // CommandIterationUpdate::Pointer observer = CommandIterationUpdate::New(); optimizer->AddObserver( itk::IterationEvent(), observer ); try { registration->StartRegistration(); } catch( itk::ExceptionObject & err ) { std::cout << "ExceptionObject caught !" << std::endl; std::cout << err << std::endl; return -1; } ParametersType finalParameters = registration->GetLastTransformParameters(); double TranslationAlongX = finalParameters[0]; double TranslationAlongY = finalParameters[1]; unsigned int numberOfIterations = optimizer->GetCurrentIteration(); double bestValue = optimizer->GetValue(); // // Print out results // std::cout << "Result = " << std::endl; std::cout << " Translation X = " << TranslationAlongX << std::endl; std::cout << " Translation Y = " << TranslationAlongY << std::endl; std::cout << " Iterations = " << numberOfIterations << std::endl; std::cout << " Metric value = " << bestValue << std::endl; // Software Guide : BeginLatex // // Let's execute this example using the same multi-modality images // as before. // The registration converged after 24 iterations and produce as result the // parameters: // // \begin{verbatim} // Translation X = 13.1719 // Translation Y = 16.9006 // \end{verbatim} // // These values are very close match to // the true misaligment introduced in the moving image. // // Software Guide : EndLatex typedef itk::ResampleImageFilter< MovingImageType, FixedImageType > ResampleFilterType; TransformType::Pointer finalTransform = TransformType::New(); finalTransform->SetParameters( finalParameters ); ResampleFilterType::Pointer resample = ResampleFilterType::New(); resample->SetTransform( finalTransform ); resample->SetInput( movingImageReader->GetOutput() ); FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); resample->SetSize( fixedImage->GetLargestPossibleRegion().GetSize() ); resample->SetOutputOrigin( fixedImage->GetOrigin() ); resample->SetOutputSpacing( fixedImage->GetSpacing() ); resample->SetDefaultPixelValue( 100 ); typedef unsigned char OutputPixelType; typedef itk::Image< OutputPixelType, Dimension > OutputImageType; typedef itk::CastImageFilter< FixedImageType, OutputImageType > CastFilterType; typedef itk::ImageFileWriter< OutputImageType > WriterType; WriterType::Pointer writer = WriterType::New(); CastFilterType::Pointer caster = CastFilterType::New(); writer->SetFileName( argv[3] ); caster->SetInput( resample->GetOutput() ); writer->SetInput( caster->GetOutput() ); writer->Update(); // Software Guide : BeginLatex // // \begin{figure} // \center // \includegraphics[width=5cm]{ImageRegistration4Output.eps} // \includegraphics[width=5cm]{ImageRegistration4CheckerboardBefore.eps} // \includegraphics[width=5cm]{ImageRegistration4CheckerboardAfter.eps} // \caption{Mapped moving image (left) and composition of fixed and moving // images before (center) and after (right) registration.} // \label{fig:ImageRegistration4Output} // \end{figure} // // The result of the resampling the moving image is presented in the left // side of Figure \ref{fig:ImageRegistration4Output}. The center and right // parts of the figure present a checkerboard composite of the fixed and // moving images before and after registration. // // Software Guide : EndLatex // Software Guide : BeginLatex // // \begin{figure} // \center // \includegraphics[width=7cm]{ImageRegistration2TraceTranslations.eps} // \includegraphics[width=7cm]{ImageRegistration2TraceTranslations2.eps} // \caption{Sequence of translations during the registration process. Left, // iterations form 0 to 200. Right iterations from 150 to 200.} // \label{fig:ImageRegistration2TraceTranslations} // \end{figure} // // Figure \ref{fig:ImageRegistration2TraceTranslations} presents the // sequence of translations followed by the optimizer as it searched the // parameter space. The left plot shows iterations $0$ to $200$ while the // right figure zooms into iterations $150$ to $200$. The area covered by // the right figure has been highlighted by a rectangle in the left image. // It can be seen that after a certain number of iterations the optimizer // oscillates within a one or two pixels of the true solution. // At this point it is // clear that more iterations will not help. Instead it is time to modify // some of the parameters of the registration process. For example, // reducing the learning rate of the optimizer and continuing the // registration so that smaller steps are taken. // // \begin{figure} // \center // \includegraphics[width=7cm]{ImageRegistration2TraceMetric.eps} // \includegraphics[width=7cm]{ImageRegistration2TraceMetric2.eps} // \caption{Sequence of metric values during the registration process. Left, // iterations form 0 to 300. Right, iterations from 100 to 200.} // \label{fig:ImageRegistration2TraceMetric} // \end{figure} // // Figure \ref{fig:ImageRegistration2TraceMetric} shows the sequence of // metric values computed as the optimizer searched the parameter space. // The left plot shows values when iterations are extended from $0$ to $300$ // while the right figure zooms into iterations $100$ to $200$. // The fluctuations in the measure value is due to the stochastic // nature in which the measure is computed. At each call of // \code{GetValue()}, two new sets of intensity samples is randomly // taken from the image to compute the density and entrophy estimates. // Even with the fluctuations, overall the measure initially increases // with the number of iterations. // After about 150 iterations the metric value oscilates // without further noticeable convergence. // The trace plots in Figure \ref{fig:ImageRegistration2TraceMetric} // highlights one of the difficulties with using this particular metric: // the stochastic oscillations makes it difficult to determine // convergence and limits the use of more sophisticated optimizations // methods. As explained above, // the reduction of the learning rate as the registration progresses // is very important to get precise results. // // This example highlight the importance of tracking the evolution of the // registration method in order to get some insight on the characteristics // of the particular problem at hand and the components being used. // The behavior revealed by these plots // usually helps to identify possible improvements in the setup of the // registration parameters. // // Software Guide : EndLatex return 0; } <|endoftext|>
<commit_before>#include "fluidsystem.h" #include "camera.h" #include "vertexrecorder.h" #include <iostream> #include <math.h> #include <algorithm> // std::max #include "particle.h" #include "wall.h" using namespace std; // your system should at least contain 8x8 particles. const int N = 5; const float PARTICLE_RADIUS = .015; const float PARTICLE_SPACING = .0225; const float H = .0457; const float Hsquared = H*H; const float Hfouth = Hsquared*Hsquared; const float mu = 3.5;//0.001; const float SPRING_CONSTANT = 5; // N/m const float PARTICLE_MASS = 0.02;//.03; // kg const float GRAVITY = 9.8; // m/s const float DRAG_CONSTANT = .05; const float WALL_K = 30.0; // wall spring constant const float WALL_DAMPING = -0.9; // wall damping constant float WPoly6(Vector3f R); Vector3f WSpiky(Vector3f R); float WViscosity(Vector3f R); FluidSystem::FluidSystem() { // change box size - make sure this is the same as in main.cpp float len = 0.1; // back, front, left, right, bottom - respectively _walls.push_back(Wall(Vector3f(0,-len/2,-len), Vector3f(0,0,1))); _walls.push_back(Wall(Vector3f(0,-len/2,len), Vector3f(0,0,-1))); _walls.push_back(Wall(Vector3f(-len,-len/2,0), Vector3f(1,0,0))); _walls.push_back(Wall(Vector3f(len,-len/2,0), Vector3f(-1,0,0))); _walls.push_back(Wall(Vector3f(0,-len,0), Vector3f(0,1,0))); // Initialize m_vVecState with fluid particles. // You can again use rand_uniform(lo, hi) to make things a bit more interesting m_vVecState.clear(); int particleCount = 0; for (unsigned i = 0; i < N; i++){ for (unsigned j = 0; j< N; j++){ for (unsigned l = 0; l < N; l++){ float x = i*PARTICLE_SPACING; float y = 1 + j*PARTICLE_SPACING; float z = l*PARTICLE_SPACING; // particles evenly spaced Vector3f position = Vector3f(x, y, z); // all particles stationary // Vector3f velocity = Vector3f( rand_uniform(-1, 1), 0, rand_uniform( -1, 1)); Vector3f velocity = Vector3f(0); Particle particle = Particle(particleCount, position, velocity); m_vVecState.push_back(particle); particleCount += 1; } } } } std::vector<Particle> FluidSystem::evalF(std::vector<Particle> state) { std::vector<Particle> f; // FLuid Particles undergo the following forces: // - gravity // - collision forces // - viscous drag // - pressure // ---Below Not Implemented--- // - surface tension // F = mg -> GRAVITY // ---------------------------------------- float gForce = PARTICLE_MASS*GRAVITY; // only in the y-direction Vector3f gravityForce = Vector3f(0,-gForce, 0); // ---------------------------------------- for (unsigned i = 0; i < m_vVecState.size(); i+=1){ Particle& particle = state[i]; Vector3f position = particle.getPosition(); Vector3f velocity = particle.getVelocity(); // compute density of every particle first double density_i = 0; for (unsigned j = 0; j < state.size(); j+=1) { if (j != i) { Particle particle_j = state[j]; Vector3f delta = position - particle_j.getPosition(); if (delta.absSquared() < H*H) { density_i += WPoly6(delta); // cout << WPoly6(delta) << endl; } } } particle.density() = PARTICLE_MASS*density_i; // cout << density_i << endl; } for (unsigned i = 0; i < m_vVecState.size(); i+=1){ Particle particle = state[i]; Vector3f position = particle.getPosition(); Vector3f velocity = particle.getVelocity(); double density = particle.density(); float pressure = particle.getPressure(); // compute updated density and gradient of pressure // based on all other particles Vector3f f_pressure; Vector3f f_viscosity; for (unsigned j = 0; j < state.size(); j+=1) { if (j != i) { Particle particle_j = state[j]; Vector3f delta = position - particle_j.getPosition() - Vector3f(2 * PARTICLE_RADIUS); if (delta.absSquared() < H*H) { // ---------------gradient of pressure computation----------------- // sample implementation value: pi/roi2 + pj/roj2 float p_factor = (pressure/(density*density)) + (particle_j.getPressure()/(particle_j.density()*particle_j.density())); // Mueller value: (pi + pj) / 2roj // float p_factor = (pressure+particle_j.getPressure()) / (2*particle_j.getDensity()); // Lecture video value: pi/roi + pj/roj // float p_factor = pressure/density + particle_j.getPressure()/particle_j.getDensity(); // (WSpiky(delta)).print(); // delta.print(); f_pressure += p_factor*WSpiky(delta); // ---------------viscosity computation----------------- float kernel_distance_viscosity = H-delta.abs(); Vector3f v_factor = (particle_j.getVelocity() - velocity) / particle_j.getDensity(); Vector3f viscosity_term = PARTICLE_MASS*WViscosity(delta)*v_factor; // cout << "delta " << kernel_constant_pressure << endl; // viscosity_term.print(); f_viscosity += viscosity_term; // velocity.print(); } } } f_pressure = PARTICLE_MASS * f_pressure; // Total Force // Vector3f totalForce = (gravityForce +(mu*f_viscosity) + f_pressure)/density; // f_pressure.print(); // cout << density << endl; Vector3f f_collision = collisionForce(particle); // Total Force // Vector3f totalForce = (gravityForce +(mu*f_viscosity) + f_pressure)/density + f_collision; Vector3f totalForce = gravityForce + f_collision;//f_pressure*0.0000001; // cout << f_pressure.x() << f_pressure.y() << f_pressure.z() << endl; // totalForce.print(); Vector3f acceleration = totalForce / PARTICLE_MASS; Particle newParticle = Particle(i, velocity, acceleration, density); f.push_back(newParticle); } return f; } float WPoly6(Vector3f R){ float constant_term = 315.0 / (64.0 * M_PI * Hfouth * Hfouth * H); float factor = H*H - R.absSquared(); float kernel_distance_density = factor * factor * factor; return kernel_distance_density*constant_term; } Vector3f WSpiky(Vector3f R){ if (R.abs() < .000001){ return Vector3f(0,0,0); } float constant_term = -45.0 / (M_PI * Hfouth * Hsquared); float factor = H - R.abs(); Vector3f kernel_distance_pressure = factor * factor * R.normalized(); return constant_term * kernel_distance_pressure; } float WViscosity(Vector3f R){ float constant_term = 45.0 / (M_PI * Hfouth * Hsquared); float kernel_distance_viscosity = H-R.abs(); return constant_term * kernel_distance_viscosity; } Vector3f FluidSystem::collisionForce(Particle particle) { Vector3f f_collision; for (unsigned int i = 0; i < _walls.size(); i++) { Wall wall = _walls[i]; Vector3f wallNormal = wall.getNormal(); double d = Vector3f::dot(wallNormal, (wall.getPoint() - particle.getPosition())) + PARTICLE_RADIUS; // particle radius if (d > 0.0) { f_collision += WALL_DAMPING * Vector3f::dot(wallNormal, particle.getVelocity()) * wallNormal + WALL_K * wallNormal * d; } } return f_collision; } void FluidSystem::draw(GLProgram& gl) { //TODO 5: render the system // - ie draw the particles as little spheres // - or draw the springs as little lines or cylinders // - or draw wireframe mesh const Vector3f blue(0.0f, 0.0f, 1.0f); // EXAMPLE for how to render cloth particles. // - you should replace this code. // EXAMPLE: This shows you how to render lines to debug the spring system. // // You should replace this code. // // Since lines don't have a clearly defined normal, we can't use // a regular lighting model. // GLprogram has a "color only" mode, where illumination // is disabled, and you specify color directly as vertex attribute. // Note: enableLighting/disableLighting invalidates uniforms, // so you'll have to update the transformation/material parameters // after a mode change. gl.disableLighting(); gl.updateModelMatrix(Matrix4f::identity()); // update uniforms after mode change // drawBox(Vector3f(0,0,0), 1); // not working :( gl.updateMaterial(blue); for (unsigned i = 0; i < m_vVecState.size(); i+=1){ Particle p = m_vVecState[i]; Vector3f pos = p.getPosition(); gl.updateModelMatrix(Matrix4f::translation(pos)); drawSphere(PARTICLE_RADIUS, 10, 4); } gl.enableLighting(); // reset to default lighting model } <commit_msg>stabale system<commit_after>#include "fluidsystem.h" #include "camera.h" #include "vertexrecorder.h" #include <iostream> #include <math.h> #include <algorithm> // std::max #include "particle.h" #include "wall.h" using namespace std; // your system should at least contain 8x8 particles. const int N = 5; const float PARTICLE_RADIUS = .015; const float PARTICLE_SPACING = .0225; const float H = 0.03;//.0457; const float Hsquared = H*H; const float Hfouth = Hsquared*Hsquared; const float mu = .35;//0.001; const float SPRING_CONSTANT = 5; // N/m const float PARTICLE_MASS = 0.02;//.03; // kg const float GRAVITY = 9.8; // m/s const float DRAG_CONSTANT = .05; const float WALL_K = 100.0; // wall spring constant const float WALL_DAMPING = -0.15; // wall damping constant float WPoly6(Vector3f R); Vector3f WSpiky(Vector3f R); float WViscosity(Vector3f R); FluidSystem::FluidSystem() { // change box size - make sure this is the same as in main.cpp float len = 0.1; // back, front, left, right, bottom - respectively _walls.push_back(Wall(Vector3f(0,-len/2,-len), Vector3f(0,0,1))); _walls.push_back(Wall(Vector3f(0,-len/2,len), Vector3f(0,0,-1))); _walls.push_back(Wall(Vector3f(-len,-len/2,0), Vector3f(1,0,0))); _walls.push_back(Wall(Vector3f(len,-len/2,0), Vector3f(-1,0,0))); _walls.push_back(Wall(Vector3f(0,-len,0), Vector3f(0,1,0))); // Initialize m_vVecState with fluid particles. // You can again use rand_uniform(lo, hi) to make things a bit more interesting m_vVecState.clear(); int particleCount = 0; for (unsigned i = 0; i < N; i++){ for (unsigned j = 0; j< N; j++){ for (unsigned l = 0; l < N; l++){ float x = -len + i*PARTICLE_SPACING; float y = 0.2 + -len + j*PARTICLE_SPACING; float z = -len + l*PARTICLE_SPACING; // particles evenly spaced Vector3f position = Vector3f(x, y, z); // all particles stationary // Vector3f velocity = Vector3f( rand_uniform(-1, 1), 0, rand_uniform( -1, 1)); Vector3f velocity = Vector3f(0); Particle particle = Particle(particleCount, position, velocity); m_vVecState.push_back(particle); particleCount += 1; } } } } std::vector<Particle> FluidSystem::evalF(std::vector<Particle> state) { std::vector<Particle> f; // FLuid Particles undergo the following forces: // - gravity // - collision forces // - viscous drag // - pressure // ---Below Not Implemented--- // - surface tension // F = mg -> GRAVITY // ---------------------------------------- float gForce = PARTICLE_MASS*GRAVITY; // only in the y-direction Vector3f gravityForce = Vector3f(0,-gForce, 0); // ---------------------------------------- for (unsigned i = 0; i < m_vVecState.size(); i+=1){ Particle& particle = state[i]; Vector3f position = particle.getPosition(); Vector3f velocity = particle.getVelocity(); // compute density of every particle first double density_i = 0; for (unsigned j = 0; j < state.size(); j+=1) { if (j != i) { Particle particle_j = state[j]; Vector3f delta = position - particle_j.getPosition(); if (delta.absSquared() < H*H) { density_i += WPoly6(delta); // cout << WPoly6(delta) << endl; } } } particle.density() = PARTICLE_MASS*density_i; // cout << density_i << endl; } for (unsigned i = 0; i < m_vVecState.size(); i+=1){ Particle particle = state[i]; Vector3f position = particle.getPosition(); Vector3f velocity = particle.getVelocity(); double density = particle.density(); float pressure = particle.getPressure(); // compute updated density and gradient of pressure // based on all other particles Vector3f f_pressure; Vector3f f_viscosity; for (unsigned j = 0; j < state.size(); j+=1) { if (j != i) { Particle particle_j = state[j]; Vector3f delta = position - particle_j.getPosition() + Vector3f(2 * PARTICLE_RADIUS); // cout << "delta" << delta.x() << ","<< delta.y() << ","<< delta.z() << endl; if (delta.absSquared() < H*H) { // ---------------gradient of pressure computation----------------- // sample implementation value: pi/roi2 + pj/roj2 float p_factor = (pressure/(density*density)) + (particle_j.getPressure()/(particle_j.density()*particle_j.density())); // Mueller value: (pi + pj) / 2roj // float p_factor = (pressure+particle_j.getPressure()) / (2*particle_j.getDensity()); // Lecture video value: pi/roi + pj/roj // float p_factor = pressure/density + particle_j.getPressure()/particle_j.getDensity(); // (WSpiky(delta)).print(); // delta.print(); f_pressure += p_factor*WSpiky(delta); // ---------------viscosity computation----------------- float kernel_distance_viscosity = H-delta.abs(); Vector3f v_factor = (particle_j.getVelocity() - velocity) / particle_j.getDensity(); Vector3f viscosity_term = PARTICLE_MASS*WViscosity(delta)/ particle_j.getDensity()*v_factor; // cout << "delta " << kernel_constant_pressure << endl; // viscosity_term.print(); f_viscosity += viscosity_term; // velocity.print(); } } } f_pressure *= PARTICLE_MASS; f_viscosity *= mu * PARTICLE_MASS; // Total Force // Vector3f totalForce = (gravityForce +(mu*f_viscosity) + f_pressure)/density; // f_pressure.print(); // cout << density << endl; Vector3f f_collision = collisionForce(particle); // Total Force Vector3f totalForce = gravityForce + f_collision + f_viscosity*mu*0.0000; // Vector3f totalForce = gravityForce + f_collision ;//+ f_pressure; cout << "f_collision: " << f_collision.x() << ","<< f_collision.y() << ","<< f_collision.z() << endl; // cout << "f_pressure: " << f_pressure.x() << ","<< f_pressure.y() << ","<< f_pressure.z() << endl; // cout << "gravityForce: " << gravityForce.x() << ","<< gravityForce.y() << ","<< gravityForce.z() << endl; // totalForce.print(); Vector3f acceleration = totalForce / PARTICLE_MASS; Particle newParticle = Particle(i, velocity, acceleration, density); f.push_back(newParticle); } return f; } float WPoly6(Vector3f R){ float constant_term = 315.0 / (64.0 * M_PI * Hfouth * Hfouth * H); float factor = Hsquared - R.absSquared(); float kernel_distance_density = factor * factor * factor; return kernel_distance_density*constant_term; } Vector3f WSpiky(Vector3f R){ if (R.abs() < .000001){ return Vector3f(0,0,0); } float constant_term = -45.0 / (M_PI * Hfouth * Hsquared); float factor = H - R.abs(); Vector3f kernel_distance_pressure = factor * factor * R.normalized(); return constant_term * kernel_distance_pressure; } float WViscosity(Vector3f R){ float constant_term = 45.0 / (M_PI * Hfouth * Hsquared); float kernel_distance_viscosity = H-R.abs(); return constant_term * kernel_distance_viscosity; } Vector3f FluidSystem::collisionForce(Particle particle) { Vector3f f_collision; for (unsigned int i = 0; i < _walls.size(); i++) { Wall wall = _walls[i]; Vector3f wallNormal = wall.getNormal(); double d = Vector3f::dot(wallNormal, (wall.getPoint() - particle.getPosition())) + 0.015; // particle radius if (d > 0.0) { f_collision += WALL_DAMPING * Vector3f::dot(wallNormal, particle.getVelocity()) * wallNormal + WALL_K * wallNormal * d; } } return f_collision; } void FluidSystem::draw(GLProgram& gl) { //TODO 5: render the system // - ie draw the particles as little spheres // - or draw the springs as little lines or cylinders // - or draw wireframe mesh const Vector3f blue(0.0f, 0.0f, 1.0f); // EXAMPLE for how to render cloth particles. // - you should replace this code. // EXAMPLE: This shows you how to render lines to debug the spring system. // // You should replace this code. // // Since lines don't have a clearly defined normal, we can't use // a regular lighting model. // GLprogram has a "color only" mode, where illumination // is disabled, and you specify color directly as vertex attribute. // Note: enableLighting/disableLighting invalidates uniforms, // so you'll have to update the transformation/material parameters // after a mode change. gl.disableLighting(); gl.updateModelMatrix(Matrix4f::identity()); // update uniforms after mode change // drawBox(Vector3f(0,0,0), 1); // not working :( gl.updateMaterial(blue); for (unsigned i = 0; i < m_vVecState.size(); i+=1){ Particle p = m_vVecState[i]; Vector3f pos = p.getPosition(); gl.updateModelMatrix(Matrix4f::translation(pos)); drawSphere(PARTICLE_RADIUS, 10, 4); } gl.enableLighting(); // reset to default lighting model } <|endoftext|>
<commit_before>#include "../../src/utki/debug.hpp" #include "../../src/utki/math.hpp" #include "tests.hpp" namespace TestBasicMathStuff{ void Run(){ ASSERT_ALWAYS(sin((long double)(0)) == 0) ASSERT_ALWAYS(abs(sin(utki::pi<long double>() / 2) - 1) < 0.00001) ASSERT_ALWAYS(abs(sin(utki::pi<long double>())) < 0.00001) ASSERT_ALWAYS(abs(sin(utki::pi<long double>() * 3 / 2) + 1) < 0.00001) ASSERT_ALWAYS(cos((long double)(0)) == 1) ASSERT_ALWAYS(abs(cos(utki::pi<long double>() / 2)) < 0.00001) ASSERT_ALWAYS(abs(cos(utki::pi<long double>()) + 1) < 0.00001) ASSERT_ALWAYS(abs(cos(utki::pi<long double>() * 3 / 2)) < 0.00001) ASSERT_ALWAYS(exp((long double)(0)) == 1) ASSERT_ALWAYS(abs(exp(utki::logOf2<long double>()) - 2) < 0.00001) ASSERT_ALWAYS(log((long double)(1)) == 0) ASSERT_ALWAYS(abs(log((long double)(2)) - utki::logOf2<long double>()) < 0.00001) } }//~namespace <commit_msg>clang warnings fixed<commit_after>#include "../../src/utki/debug.hpp" #include "../../src/utki/math.hpp" #include "tests.hpp" namespace TestBasicMathStuff{ void Run(){ ASSERT_ALWAYS(std::sin((long double)(0)) == 0) ASSERT_ALWAYS(std::abs(std::sin(utki::pi<long double>() / 2) - 1) < 0.00001) ASSERT_ALWAYS(std::abs(std::sin(utki::pi<long double>())) < 0.00001) ASSERT_ALWAYS(std::abs(std::sin(utki::pi<long double>() * 3 / 2) + 1) < 0.00001) ASSERT_ALWAYS(std::cos((long double)(0)) == 1) ASSERT_ALWAYS(std::abs(std::cos(utki::pi<long double>() / 2)) < 0.00001) ASSERT_ALWAYS(std::abs(std::cos(utki::pi<long double>()) + 1) < 0.00001) ASSERT_ALWAYS(std::abs(std::cos(utki::pi<long double>() * 3 / 2)) < 0.00001) ASSERT_ALWAYS(std::exp((long double)(0)) == 1) ASSERT_ALWAYS(std::abs(std::exp(utki::logOf2<long double>()) - 2) < 0.00001) ASSERT_ALWAYS(std::log((long double)(1)) == 0) ASSERT_ALWAYS(std::abs(std::log((long double)(2)) - utki::logOf2<long double>()) < 0.00001) } }//~namespace <|endoftext|>
<commit_before>#include <stdlib.h> #include <sys/socket.h> #include <string.h> #include <netinet/in.h> #include <cstring> #include <stdio.h> #include <string> #include <iostream> #include <list> #include <map> #include <set> #include "server.h" #include "duckchat.h" // TODO Handle domain // Server can accept connections. // Server handles Login and Logout from users, and keeps records of which users are logged in. // Server handles Join and Leave from users, keeps records of which channels a user belongs to, // and keeps records of which users are in a channel. // TODO Server handles the Say message. // TODO Server correctly handles List and Who. // TODO Create copies of your client and server source. Modify them to send invalid packets to your good client // and server, to see if you can make your client or server crash. Fix any bugs you find. class Channel { public: std::string name; std::list<User *> users; Channel(std::string name): name(name) {}; }; class User { public: std::string name; in_addr_t address; unsigned short port; User(std::string name, in_addr_t address, unsigned short port): name(name), address(address), port(port) {}; }; std::map<std::string, User *> kUsers; std::map<std::string, Channel *> kChannels; void Error(const char *msg) { perror(msg); exit(1); } void RemoveUser(User *user){ for(auto channel : kChannels){ for(auto channel_user : channel.second->users){ if(channel_user->name == user->name){ channel.second->users.remove(channel_user); break; } } } for(auto current_user : kUsers){ if(current_user.second->name == user->name){ kUsers.erase(user->name); } } } struct sockaddr_in* CreateSockAddr(unsigned short port, in_addr_t address){ struct sockaddr_in *client_addr; memset(&client_addr, 0, sizeof(struct sockaddr_in)); client_addr->sin_family = AF_INET; client_addr->sin_port = port; client_addr->sin_addr.s_addr = address; return client_addr; } void ProcessRequest(int server_socket, void *buffer, in_addr_t request_address, unsigned short request_port) { struct request current_request; User *current_user; Channel *channel; std::string current_channel; std::list<User *>::const_iterator it; std::map<std::string, User *>::const_iterator map_it; bool is_new_channel; bool is_channel; bool is_channel_user; int i; channel_info *channel_list; memcpy(&current_request, buffer, sizeof(struct request)); // std::cout << "request type: " << current_request.req_type << std::endl; request_t request_type = current_request.req_type; switch(request_type) { case REQ_LOGIN: struct request_login login_request; memcpy(&login_request, buffer, sizeof(struct request_login)); current_user = new User(login_request.req_username, request_address, request_port); RemoveUser(current_user); kUsers.insert({std::string(login_request.req_username), current_user}); std::cout << "server: " << login_request.req_username << " logs in" << std::endl; break; case REQ_LOGOUT: struct request_logout logout_request; memcpy(&logout_request, buffer, sizeof(struct request_logout)); for (auto user : kUsers) { unsigned short current_port = user.second->port; in_addr_t current_address = user.second->address; if (current_port == request_port && current_address == request_address) { std::cout << "server: " << user.first << " logs out" << std::endl; kUsers.erase(user.first); break; } } break; case REQ_LEAVE: struct request_leave leave_request; memcpy(&leave_request, buffer, sizeof(struct request_leave)); current_channel = leave_request.req_channel; for (auto user : kUsers) { unsigned short current_port = user.second->port; in_addr_t current_address = user.second->address; if (current_port == request_port && current_address == request_address) { is_channel = false; for(auto ch : kChannels){ if(ch.first == current_channel){ std::cout << "channel found" << std::endl; is_channel = true; break; } } if(is_channel){ channel = kChannels[current_channel]; for (it = channel->users.begin(); it != channel->users.end(); ++it){ if((*it)->name == user.first){ break; } } if( it != channel->users.end()){ channel->users.remove(*it); std::cout << user.first << " leaves channel " << channel->name << std::endl; if (channel->users.size() == 0) { kChannels.erase(channel->name); std::cout << "server: removing empty channel " << channel->name << std::endl; } } for (auto u : channel->users) { std::cout << "user: " << u->name << std::endl; } break; } else { std::cout << "server: " << user.first << " trying to leave non-existent channel " << channel->name << std::endl; } } } break; case REQ_JOIN: struct request_join join_request; memcpy(&join_request, buffer, sizeof(struct request_join)); is_new_channel = true; // If channel does exists in global map, set local channel to channel from kChannels for (auto ch : kChannels) { if (join_request.req_channel == ch.second->name) { is_new_channel = false; channel = ch.second; break; } } // If channel is new create a new channel if (is_new_channel) { channel = new Channel(join_request.req_channel); } for (auto user : kUsers) { unsigned short current_port = user.second->port; in_addr_t current_address = user.second->address; // std::cout << std::endl; // std::cout << "port: " << current_port << " address "<< current_address << std::endl; // std::cout << "port: " << request_port << " address "<< request_address << std::endl; // std::cout << std::endl; if (current_port == request_port && current_address == request_address) { std::cout << "server: " << user.first << " joins channel "<< channel->name << std::endl; is_channel_user = false; for(auto u : channel->users){ if(u->name == user.second->name){ is_channel_user = true; break; } } if(!is_channel_user){ channel->users.push_back(user.second); } // Otherwise if (is_new_channel) { kChannels.insert({channel->name, channel}); } // Test print // for (auto u : channel->users) { // std::cout << "user: " << u->name << std::endl; // } break; } } break; case REQ_SAY: struct request_say say_request; memcpy(&say_request, buffer, sizeof(struct request_say)); for (auto user : kUsers) { unsigned short current_port = user.second->port; in_addr_t current_address = user.second->address; if (current_port == request_port && current_address == request_address) { current_user = user.second; for(auto channel_user : kChannels[say_request.req_channel]->users){ struct sockaddr_in client_addr; struct text_say say; memcpy(&say, buffer, sizeof(struct text_say)); // client_addr = CreateSockAddr(user->port, user->address); memset(&client_addr, 0, sizeof(struct sockaddr_in)); client_addr.sin_family = AF_INET; client_addr.sin_port = channel_user->port; client_addr.sin_addr.s_addr = channel_user->address; // copy message into struct being sent strncpy(say.txt_channel, say_request.req_channel, CHANNEL_MAX); strncpy(say.txt_text, say_request.req_text, SAY_MAX); say.txt_type = TXT_SAY; strncpy(say.txt_username, current_user->name.c_str(), USERNAME_MAX); size_t message_size = sizeof(struct text_say); if (sendto(server_socket, &say, message_size, 0, (struct sockaddr*) &client_addr, sizeof(client_addr)) < 0) { Error("server: failed to send say\n"); } } std::cout << current_user->name << " sends say message in " << say_request.req_channel << std::endl; break; } } break; case REQ_LIST: // struct sockaddr_in client_addr; struct text_list list; list.txt_type = TXT_LIST; list.txt_nchannels = (int) kChannels.size(); channel_list = new channel_info[list.txt_nchannels]; i = 0; for(auto ch : kChannels){ std::cout << "at beginning "<< std::endl; struct channel_info new_info; strncpy(new_info.ch_channel, ch.second->name.c_str(), CHANNEL_MAX); memcpy(&channel_list[i], &new_info, sizeof(struct channel_info)); // memcpy(&list.txt_channels[i].ch_channel, &channel_list[i].ch_channel, CHANNEL_MAX); // std::cout << "channel name: " << list.txt_channels[i].ch_channel << std::endl; i++; } memcpy(&list.txt_channels, channel_list, sizeof(*channel_list)); // std::cout << "at end "<< std::endl; // std::cout << "channel name: " << list.txt_channels[0].ch_channel << std::endl; for(i = 0; i < list.txt_nchannels; i++){ std::cout << "channel name: " << channel_list[i].ch_channel<< std::endl; } // std::cout << "size of array: " << sizeof(list.txt_channels) / sizeof(struct channel_info) << std::endl; // std::cout << "length of list nchannels : " << list.txt_nchannels << std::endl; // memset(list.txt_channels, 0, list.txt_nchannels * sizeof(struct channel_info)); // i = 0; // for(auto ch : kChannels){ // struct channel_info new_channel; // memset(new_channel.ch_channel, 0, CHANNEL_MAX); // strncpy(new_channel.ch_channel, ch.second->name.c_str(), CHANNEL_MAX); // std::cout << "channel: " << new_channel.ch_channel << std::endl; //// std::cout << "size of array: " << sizeof(list.txt_channels) / sizeof(struct channel_info) << std::endl; //// list.txt_channels[i++] = new_channel; // memcpy(&list.txt_channels[i++], &new_channel, sizeof(new_channel)); // } // for (auto user : kUsers) { // std::cout << "user loop" << std::endl; // unsigned short current_port = user.second->port; // in_addr_t current_address = user.second->address; // if (current_port == request_port && current_address == request_address) { // std::cout << "server: " << user.first << " lists channels" << std::endl; // current_user = user.second; // memset(&client_addr, 0, sizeof(struct sockaddr_in)); // client_addr.sin_family = AF_INET; // client_addr.sin_port = current_user->port; // client_addr.sin_addr.s_addr = current_user->address; // size_t message_size = sizeof(struct text_list); // // if (sendto(server_socket, &list, message_size, 0, (struct sockaddr*) &client_addr, sizeof(client_addr)) < 0) { // Error("server: failed to send say\n"); // } // break; // } // } break; default: break; } } int main(int argc, char *argv[]) { struct sockaddr_in server_addr; int server_socket; int receive_len; void* buffer[kBufferSize]; int port; // std::string domain; if (argc < 3) { std::cerr << "Usage: ./server domain_name port_num" << std::endl; exit(1); } // domain = argv[1]; port = atoi(argv[2]); memset((char *) &server_addr, 0, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = htonl(INADDR_ANY); server_addr.sin_port = htons(port); if ((server_socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { Error("server: can't open socket\n"); } if (bind(server_socket, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) { Error("server: bind failed\n"); } printf("server: waiting on port %d\n", port); while (1) { struct sockaddr_in client_addr; socklen_t client_addr_len = sizeof(client_addr); receive_len = recvfrom(server_socket, buffer, kBufferSize, 0, (struct sockaddr *) &client_addr, &client_addr_len); if (receive_len > 0) { buffer[receive_len] = 0; ProcessRequest(server_socket, buffer, client_addr.sin_addr.s_addr, client_addr.sin_port); } } } <commit_msg>memcpy on iteration<commit_after>#include <stdlib.h> #include <sys/socket.h> #include <string.h> #include <netinet/in.h> #include <cstring> #include <stdio.h> #include <string> #include <iostream> #include <list> #include <map> #include <set> #include "server.h" #include "duckchat.h" // TODO Handle domain // Server can accept connections. // Server handles Login and Logout from users, and keeps records of which users are logged in. // Server handles Join and Leave from users, keeps records of which channels a user belongs to, // and keeps records of which users are in a channel. // TODO Server handles the Say message. // TODO Server correctly handles List and Who. // TODO Create copies of your client and server source. Modify them to send invalid packets to your good client // and server, to see if you can make your client or server crash. Fix any bugs you find. class Channel { public: std::string name; std::list<User *> users; Channel(std::string name): name(name) {}; }; class User { public: std::string name; in_addr_t address; unsigned short port; User(std::string name, in_addr_t address, unsigned short port): name(name), address(address), port(port) {}; }; std::map<std::string, User *> kUsers; std::map<std::string, Channel *> kChannels; void Error(const char *msg) { perror(msg); exit(1); } void RemoveUser(User *user){ for(auto channel : kChannels){ for(auto channel_user : channel.second->users){ if(channel_user->name == user->name){ channel.second->users.remove(channel_user); break; } } } for(auto current_user : kUsers){ if(current_user.second->name == user->name){ kUsers.erase(user->name); } } } struct sockaddr_in* CreateSockAddr(unsigned short port, in_addr_t address){ struct sockaddr_in *client_addr; memset(&client_addr, 0, sizeof(struct sockaddr_in)); client_addr->sin_family = AF_INET; client_addr->sin_port = port; client_addr->sin_addr.s_addr = address; return client_addr; } void ProcessRequest(int server_socket, void *buffer, in_addr_t request_address, unsigned short request_port) { struct request current_request; User *current_user; Channel *channel; std::string current_channel; std::list<User *>::const_iterator it; std::map<std::string, User *>::const_iterator map_it; bool is_new_channel; bool is_channel; bool is_channel_user; int i; channel_info *channel_list; memcpy(&current_request, buffer, sizeof(struct request)); // std::cout << "request type: " << current_request.req_type << std::endl; request_t request_type = current_request.req_type; switch(request_type) { case REQ_LOGIN: struct request_login login_request; memcpy(&login_request, buffer, sizeof(struct request_login)); current_user = new User(login_request.req_username, request_address, request_port); RemoveUser(current_user); kUsers.insert({std::string(login_request.req_username), current_user}); std::cout << "server: " << login_request.req_username << " logs in" << std::endl; break; case REQ_LOGOUT: struct request_logout logout_request; memcpy(&logout_request, buffer, sizeof(struct request_logout)); for (auto user : kUsers) { unsigned short current_port = user.second->port; in_addr_t current_address = user.second->address; if (current_port == request_port && current_address == request_address) { std::cout << "server: " << user.first << " logs out" << std::endl; kUsers.erase(user.first); break; } } break; case REQ_LEAVE: struct request_leave leave_request; memcpy(&leave_request, buffer, sizeof(struct request_leave)); current_channel = leave_request.req_channel; for (auto user : kUsers) { unsigned short current_port = user.second->port; in_addr_t current_address = user.second->address; if (current_port == request_port && current_address == request_address) { is_channel = false; for(auto ch : kChannels){ if(ch.first == current_channel){ std::cout << "channel found" << std::endl; is_channel = true; break; } } if(is_channel){ channel = kChannels[current_channel]; for (it = channel->users.begin(); it != channel->users.end(); ++it){ if((*it)->name == user.first){ break; } } if( it != channel->users.end()){ channel->users.remove(*it); std::cout << user.first << " leaves channel " << channel->name << std::endl; if (channel->users.size() == 0) { kChannels.erase(channel->name); std::cout << "server: removing empty channel " << channel->name << std::endl; } } for (auto u : channel->users) { std::cout << "user: " << u->name << std::endl; } break; } else { std::cout << "server: " << user.first << " trying to leave non-existent channel " << channel->name << std::endl; } } } break; case REQ_JOIN: struct request_join join_request; memcpy(&join_request, buffer, sizeof(struct request_join)); is_new_channel = true; // If channel does exists in global map, set local channel to channel from kChannels for (auto ch : kChannels) { if (join_request.req_channel == ch.second->name) { is_new_channel = false; channel = ch.second; break; } } // If channel is new create a new channel if (is_new_channel) { channel = new Channel(join_request.req_channel); } for (auto user : kUsers) { unsigned short current_port = user.second->port; in_addr_t current_address = user.second->address; // std::cout << std::endl; // std::cout << "port: " << current_port << " address "<< current_address << std::endl; // std::cout << "port: " << request_port << " address "<< request_address << std::endl; // std::cout << std::endl; if (current_port == request_port && current_address == request_address) { std::cout << "server: " << user.first << " joins channel "<< channel->name << std::endl; is_channel_user = false; for(auto u : channel->users){ if(u->name == user.second->name){ is_channel_user = true; break; } } if(!is_channel_user){ channel->users.push_back(user.second); } // Otherwise if (is_new_channel) { kChannels.insert({channel->name, channel}); } // Test print // for (auto u : channel->users) { // std::cout << "user: " << u->name << std::endl; // } break; } } break; case REQ_SAY: struct request_say say_request; memcpy(&say_request, buffer, sizeof(struct request_say)); for (auto user : kUsers) { unsigned short current_port = user.second->port; in_addr_t current_address = user.second->address; if (current_port == request_port && current_address == request_address) { current_user = user.second; for(auto channel_user : kChannels[say_request.req_channel]->users){ struct sockaddr_in client_addr; struct text_say say; memcpy(&say, buffer, sizeof(struct text_say)); // client_addr = CreateSockAddr(user->port, user->address); memset(&client_addr, 0, sizeof(struct sockaddr_in)); client_addr.sin_family = AF_INET; client_addr.sin_port = channel_user->port; client_addr.sin_addr.s_addr = channel_user->address; // copy message into struct being sent strncpy(say.txt_channel, say_request.req_channel, CHANNEL_MAX); strncpy(say.txt_text, say_request.req_text, SAY_MAX); say.txt_type = TXT_SAY; strncpy(say.txt_username, current_user->name.c_str(), USERNAME_MAX); size_t message_size = sizeof(struct text_say); if (sendto(server_socket, &say, message_size, 0, (struct sockaddr*) &client_addr, sizeof(client_addr)) < 0) { Error("server: failed to send say\n"); } } std::cout << current_user->name << " sends say message in " << say_request.req_channel << std::endl; break; } } break; case REQ_LIST: // struct sockaddr_in client_addr; struct text_list list; list.txt_type = TXT_LIST; list.txt_nchannels = (int) kChannels.size(); channel_list = new channel_info[list.txt_nchannels]; i = 0; for(auto ch : kChannels){ std::cout << "at beginning "<< std::endl; struct channel_info new_info; strncpy(new_info.ch_channel, ch.second->name.c_str(), CHANNEL_MAX); memcpy(&channel_list[i], &new_info, sizeof(struct channel_info)); memcpy(&list.txt_channels[i], &channel_list[i], sizeof(struct channel_info)); std::cout << "channel name: " << list.txt_channels[i].ch_channel << std::endl; i++; } // memcpy(&list.txt_channels, channel_list, sizeof(*channel_list)); // std::cout << "at end "<< std::endl; // std::cout << "channel name: " << list.txt_channels[0].ch_channel << std::endl; // for(i = 0; i < list.txt_nchannels; i++){ // std::cout << "channel name: " << channel_list[i].ch_channel<< std::endl; // } // std::cout << "size of array: " << sizeof(list.txt_channels) / sizeof(struct channel_info) << std::endl; // std::cout << "length of list nchannels : " << list.txt_nchannels << std::endl; // memset(list.txt_channels, 0, list.txt_nchannels * sizeof(struct channel_info)); // i = 0; // for(auto ch : kChannels){ // struct channel_info new_channel; // memset(new_channel.ch_channel, 0, CHANNEL_MAX); // strncpy(new_channel.ch_channel, ch.second->name.c_str(), CHANNEL_MAX); // std::cout << "channel: " << new_channel.ch_channel << std::endl; //// std::cout << "size of array: " << sizeof(list.txt_channels) / sizeof(struct channel_info) << std::endl; //// list.txt_channels[i++] = new_channel; // memcpy(&list.txt_channels[i++], &new_channel, sizeof(new_channel)); // } // for (auto user : kUsers) { // std::cout << "user loop" << std::endl; // unsigned short current_port = user.second->port; // in_addr_t current_address = user.second->address; // if (current_port == request_port && current_address == request_address) { // std::cout << "server: " << user.first << " lists channels" << std::endl; // current_user = user.second; // memset(&client_addr, 0, sizeof(struct sockaddr_in)); // client_addr.sin_family = AF_INET; // client_addr.sin_port = current_user->port; // client_addr.sin_addr.s_addr = current_user->address; // size_t message_size = sizeof(struct text_list); // // if (sendto(server_socket, &list, message_size, 0, (struct sockaddr*) &client_addr, sizeof(client_addr)) < 0) { // Error("server: failed to send say\n"); // } // break; // } // } break; default: break; } } int main(int argc, char *argv[]) { struct sockaddr_in server_addr; int server_socket; int receive_len; void* buffer[kBufferSize]; int port; // std::string domain; if (argc < 3) { std::cerr << "Usage: ./server domain_name port_num" << std::endl; exit(1); } // domain = argv[1]; port = atoi(argv[2]); memset((char *) &server_addr, 0, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = htonl(INADDR_ANY); server_addr.sin_port = htons(port); if ((server_socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { Error("server: can't open socket\n"); } if (bind(server_socket, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) { Error("server: bind failed\n"); } printf("server: waiting on port %d\n", port); while (1) { struct sockaddr_in client_addr; socklen_t client_addr_len = sizeof(client_addr); receive_len = recvfrom(server_socket, buffer, kBufferSize, 0, (struct sockaddr *) &client_addr, &client_addr_len); if (receive_len > 0) { buffer[receive_len] = 0; ProcessRequest(server_socket, buffer, client_addr.sin_addr.s_addr, client_addr.sin_port); } } } <|endoftext|>
<commit_before>#include <stdlib.h> #include <sys/socket.h> #include <string.h> #include <netinet/in.h> #include <cstring> #include <stdio.h> #include <string> #include <iostream> #include <list> #include <map> #include "server.h" #include "duckchat.h" // TODO Server can accept connections. // TODO Server handles Login and Logout from users, and keeps records of which users are logged in. // TODO Server handles Join and Leave from users, keeps records of which channels a user belongs to, // and keeps records of which users are in a channel. // TODO Server handles the Say message. // TODO Server correctly handles List and Who. // TODO Create copies of your client and server source. Modify them to send invalid packets to your good client // and server, to see if you can make your client or server crash. Fix any bugs you find. //std::string user; class Channel { public: std::string name; std::list<User *> users; Channel(std::string name): name(name) {}; }; class User { public: std::string name; struct sockaddr_in *address; std::list<Channel *> channels; User(std::string name, struct sockaddr_in *address): name(name), address(address) {}; }; std::map<std::string, User *> users; std::map<std::string, Channel *> channels; void Error(const char *msg) { perror(msg); exit(1); } void ProcessRequest(void *buffer, struct sockaddr_in *address) { struct request current_request; memcpy(&current_request, buffer, sizeof(struct request)); std::cout << "request type: " << current_request.req_type << std::endl; request_t request_type = current_request.req_type; switch(request_type){ case REQ_LOGIN: struct request_login login_request; memcpy(&login_request, buffer, sizeof(struct request_login)); User new_user = User(login_request.req_username, address); users.insert(std::string(login_request.req_username), &new_user); for (auto user : users) { std::cout << user.first << " " << user.second->name << std::endl; } std::cout << "server: " << login_request.req_username << " logs in" << std::endl; break; case REQ_LOGOUT: struct request_logout logout_request; memcpy(&logout_request, buffer, sizeof(struct request_logout)); // std::cout << "server: " << username << " logs out" << std::endl; break; case REQ_JOIN: struct request_join join_request; memcpy(&join_request, buffer, sizeof(struct request_join)); // std::cout << "server: " << username << " joins channel " << join_request.req_channel << std::endl; break; default: break; } } int main(int argc, char *argv[]) { struct sockaddr_in server_addr; int server_socket; int receive_len; void* buffer[kBufferSize]; int port; // user = ""; if (argc < 2) { std::cerr << "server: no port provided" << std::endl; exit(1); } port = atoi(argv[1]); memset((char *) &server_addr, 0, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = htonl(INADDR_ANY); server_addr.sin_port = htons(port); if ((server_socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { Error("server: can't open socket\n"); } if (bind(server_socket, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) { Error("server: bind failed\n"); } printf("server: waiting on port %d\n", port); while (1) { struct sockaddr_in client_addr; socklen_t client_addr_len = sizeof(client_addr); // std::cout << "before recvfrom" << std::endl; receive_len = recvfrom(server_socket, buffer, kBufferSize, 0, (struct sockaddr *) &client_addr, &client_addr_len); if (receive_len > 0) { buffer[receive_len] = 0; ProcessRequest(buffer, &client_addr); } } } <commit_msg>change insert for users<commit_after>#include <stdlib.h> #include <sys/socket.h> #include <string.h> #include <netinet/in.h> #include <cstring> #include <stdio.h> #include <string> #include <iostream> #include <list> #include <map> #include "server.h" #include "duckchat.h" // TODO Server can accept connections. // TODO Server handles Login and Logout from users, and keeps records of which users are logged in. // TODO Server handles Join and Leave from users, keeps records of which channels a user belongs to, // and keeps records of which users are in a channel. // TODO Server handles the Say message. // TODO Server correctly handles List and Who. // TODO Create copies of your client and server source. Modify them to send invalid packets to your good client // and server, to see if you can make your client or server crash. Fix any bugs you find. //std::string user; class Channel { public: std::string name; std::list<User *> users; Channel(std::string name): name(name) {}; }; class User { public: std::string name; struct sockaddr_in *address; std::list<Channel *> channels; User(std::string name, struct sockaddr_in *address): name(name), address(address) {}; }; std::map<std::string, User *> users; std::map<std::string, Channel *> channels; void Error(const char *msg) { perror(msg); exit(1); } void ProcessRequest(void *buffer, struct sockaddr_in *address) { struct request current_request; memcpy(&current_request, buffer, sizeof(struct request)); std::cout << "request type: " << current_request.req_type << std::endl; request_t request_type = current_request.req_type; switch(request_type){ case REQ_LOGIN: struct request_login login_request; memcpy(&login_request, buffer, sizeof(struct request_login)); User new_user = User(login_request.req_username, address); users.insert({std::string(login_request.req_username), &new_user}); for (auto user : users) { std::cout << user.first << " " << user.second->name << std::endl; } std::cout << "server: " << login_request.req_username << " logs in" << std::endl; break; case REQ_LOGOUT: struct request_logout logout_request; memcpy(&logout_request, buffer, sizeof(struct request_logout)); // std::cout << "server: " << username << " logs out" << std::endl; break; case REQ_JOIN: struct request_join join_request; memcpy(&join_request, buffer, sizeof(struct request_join)); // std::cout << "server: " << username << " joins channel " << join_request.req_channel << std::endl; break; default: break; } } int main(int argc, char *argv[]) { struct sockaddr_in server_addr; int server_socket; int receive_len; void* buffer[kBufferSize]; int port; // user = ""; if (argc < 2) { std::cerr << "server: no port provided" << std::endl; exit(1); } port = atoi(argv[1]); memset((char *) &server_addr, 0, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = htonl(INADDR_ANY); server_addr.sin_port = htons(port); if ((server_socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { Error("server: can't open socket\n"); } if (bind(server_socket, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) { Error("server: bind failed\n"); } printf("server: waiting on port %d\n", port); while (1) { struct sockaddr_in client_addr; socklen_t client_addr_len = sizeof(client_addr); // std::cout << "before recvfrom" << std::endl; receive_len = recvfrom(server_socket, buffer, kBufferSize, 0, (struct sockaddr *) &client_addr, &client_addr_len); if (receive_len > 0) { buffer[receive_len] = 0; ProcessRequest(buffer, &client_addr); } } } <|endoftext|>
<commit_before>// Copyright [2014] <lgb (LiuGuangBao)> //===================================================================================== // // Filename: server.hpp // // Description: 服务器框架 // // Version: 1.0 // Created: 2013年03月05日 17时15分56秒 // Revision: none // Compiler: gcc // // Author: lgb (LiuGuangBao), easyeagel@gmx.com // Organization: magicred.net // //===================================================================================== #pragma once #include<functional> #include<boost/optional.hpp> #include<boost/asio/strand.hpp> #include<boost/asio/spawn.hpp> #include<boost/thread/thread.hpp> #include<boost/asio/io_service.hpp> #include<boost/system/error_code.hpp> #include<boost/asio/steady_timer.hpp> #include"thread.hpp" namespace core { class IOServer; class IOService; class MainServer; class ThreadThis; class IOService : private boost::asio::io_service { friend class IOServer; typedef enum {eStatusUnStart, eStatusWorking, eStatusStopped} Status_t; typedef std::unique_ptr<boost::thread> ThreadPtr; typedef boost::asio::io_service BaseThis; typedef std::function<void()> SimpleCall; public: typedef BaseThis::strand Strand; IOService(); void run(SimpleCall&& call=SimpleCall()); void stopSignal(); void stop(); void reset(); bool stopped() const { return status_==eStatusStopped; } using BaseThis::post; using BaseThis::poll; boost::asio::io_service& castGet() { return *this; } static IOService& cast(boost::asio::io_service& o) { return static_cast<IOService&>(o); } void justRun(SimpleCall&& call=SimpleCall()) { threadRun(std::move(call)); } void join(); private: void threadRun(SimpleCall&& call); private: Status_t status_=eStatusUnStart; ThreadPtr thread_; boost::optional<boost::asio::io_service::work> workGuard_; }; /** * @brief 主线程工作服务器 * @details * @li 本类是单例,并且主线程将工作在此 */ class MainServer : public SingleInstanceT<MainServer> { typedef boost::asio::io_service ASIOService; friend class OnceConstructT<MainServer>; MainServer(); public: typedef std::function<void()> CallFun; static void start(); static void stop(); template<typename Fun> static void post(Fun&& fun) { instance().ios_.post(std::move(fun)); } static ASIOService& get() { return instance().ios_.castGet(); } static IOService& serviceGet() { return instance().ios_; } static void exitCallPush(CallFun&& fun) { auto& obj=instance(); Spinlock::ScopedLock lock(obj.mutex_); obj.exitCalls_.emplace_back(std::move(fun)); } private: bool stopped_; Spinlock mutex_; IOService ios_; std::vector<CallFun> exitCalls_; }; /** * @brief 提供每个CPU有 2 个线程,每线程为一个 @ref IOService 工作 * @details * @li 如果系统只有一个CPU,则只启动一个线程;如果有多个CPU,则每个CPU启动 2 个线程 * @li 每个 @ref IOService 不可能有多个线程共享,请使用 boost::asio::ioservice::strand 进行同步 * * @see IOService, ServicePool */ class IOServer : public SingleInstanceT<IOServer> { enum {eThreadCountPerCPU=2}; enum {eStopWaitSecond=64, eStopWaitTimes=64}; IOServer(const IOServer&)=delete; IOServer& operator=(const IOServer&)=delete; typedef boost::asio::steady_timer SteadyTimer; public: typedef std::function<void()> CallFun; typedef std::function<void(CallFun&& fun)> StopCallFun; IOServer(); static void stop(); static void join(); /** * @brief 停机回调 * @details * @li 调用时服务器框架还没有停止 * @li 按照加入时相反的顺序调用 * * @param fun 被调用的对象 */ static void stopCallPush(StopCallFun&& fun); /** * @brief 开机回调 * @detalis * @li 调用时,框架还没有起来,所以当前是一个线程 * * @param fun 被调用的对象 */ static void startCallPush(CallFun&& fun); static IOService& serviceFetchOne(); static IOService& serviceFetch(size_t idx) { auto& asio=instance().asio_; return asio[idx%asio.size()]; } template<typename Handle> static void post(size_t idx, Handle&& handle) { serviceFetch(idx).post(std::move(handle)); } /** * @brief 在线程池执行指定调用,调用不会立即执行 * 它只是简单地加入任务队列,稍后将被执行 * * @tparam Handle 调用类型 * @param handle 调用对象 */ template<typename Handle> static void post(Handle&& handle) { serviceFetchOne().post(std::move(handle)); } /** * @brief 在每一个线程里的每个线程执行指定调用 * * @tparam Handle 调用类型 * @param handle 调用对象,它将复制到每个线程,并并发执行 */ template<typename Handle> static void postForeach(Handle&& handle) { for(auto& u: instance().asio_) u.post(handle); //这里需要复制 } /** * @brief 在线程池内循环执行指定调用,直到调用返回 @a true * @details * @li 调用的签名为: bool call() * @li 调用返回一个bool值,没有参数需要给出 * @li 当返回值为 true 时,循环将终止,否则调用对象将再次被调度并调用 * * @tparam Handle 调用类型 * @param handle 调用对象 */ template<typename Handle> static void postLoop(Handle&& handleIn) { post([=, handle=std::move(handleIn)]() { bool done=handle(); if(done) return; postLoop(std::move(handle)); } ); } /** * @brief 依次在每个线程里调用指定调用;可选地,在所有调用结束后,执行回调 * * @tparam Handle 任务调用类型 * @tparam Complete 结束调用类型 * @param handle 任务调用对象 * @param complete 结束调用对象 */ template<typename Handle, typename Complete=VoidCallBack> static void postForeachStrand(Handle&& handle, Complete&& complete=Complete()) { instance().postNextIndex(0, std::move(handle), std::move(complete)); } static unsigned ioServiceCountGet() { unsigned const ncpu=cpuCount(); return eThreadCountPerCPU*ncpu; } private: static unsigned cpuCount() { static unsigned ncpu=boost::thread::hardware_concurrency(); return ncpu; } template<typename Handle, typename Complete> void postNextIndex(size_t idx, Handle&& handleIn, Complete&& completeIn) { asio_[idx].post([this, idx, handle=std::move(handleIn), complete=std::move(completeIn)]() { handle(); const auto next=idx+1; if(next>=asio_.size()) { complete(); return; } postNextIndex(next, std::move(handle), std::move(complete)); } ); } static void stopNext(); void stopWait(); void start(); private: static bool started_; std::atomic<unsigned> count_; ///< 用于分配IOService的计数 std::vector<IOService> asio_; size_t waitTimes_; SteadyTimer timer_; //统一的系统启动机制 Spinlock mutex_; std::vector<CallFun> startCall_; std::vector<StopCallFun> stopCall_; }; /** * @brief 计算服务器,执行长时间计算任务;此类任务没有时间要求 * @todo 实现固定线程数的调度与执行 */ class ComputeServer : public SingleInstanceT<ComputeServer> { typedef std::unique_ptr<boost::thread> ThreadPtr; friend class OnceConstructT<ComputeServer>; ComputeServer(); public: typedef std::function<void()> Computor; template<typename Handle> static void post(Handle&& handle) { auto& inst=instance(); assert(static_cast<bool>(inst.stopped_)==false); inst.queue_.push(Computor(std::move(handle))); } static void stop (std::function<void()>&& stopCall); static bool isStopped() { return instance().stopped_; } static void join(); private: void threadTask(); void startImpl(); private: static bool started_; std::atomic<bool> stopped_; std::function<void()> stopCall_; std::vector<ThreadPtr> threads_; std::atomic<uint32_t> threadCount_; ConcurrencyQueueT<Computor> queue_; }; /** * @brief 当前线程对象 * @details * @li 获取当前线程的IOService对象,如果当前线程运行了某个IOService * @note 这应该是总是总是成立的,当 @ref IOServer 运行之后;用户不应该自己创建线程 */ class ThreadThis : private ThreadInstanceT<ThreadThis> { friend class IOService; friend class MainServer; friend class IOServer; friend class ComputeServer; public: typedef enum { eThreadUnkown, eThreadMain, eThreadIOServer, eThreadComputeServer, }ThreadEnum_t; static IOService& serviceGet() { return *instance().io_; } static ThreadEnum_t enumGet() { return instance().threadEnum_; } static bool isSelf(const IOService& s) { return std::addressof(s)==std::addressof(serviceGet()); } static bool isSelf(const boost::asio::io_service& s) { return std::addressof(s)==std::addressof(serviceGet().castGet()); } static bool isMainThread() { return enumGet()==eThreadMain; } static bool isIOThread() { return enumGet()==eThreadIOServer; } static bool isComputeThread() { return enumGet()==eThreadComputeServer; } template<typename Handle> static void post(Handle&& handle) { serviceGet().post(std::move(handle)); } private: static void serviceSet(IOService* io) { instance().io_=io; } static void enumSet(ThreadEnum_t te) { instance().threadEnum_=te; } private: IOService* io_; ThreadEnum_t threadEnum_=eThreadUnkown; }; class CoroutineContext: public ErrorBase { CoroutineContext(const CoroutineContext& other)=delete; CoroutineContext& operator=(CoroutineContext&& other)=delete; CoroutineContext& operator=(const CoroutineContext& other)=delete; public: typedef std::function<void()> CallFun; typedef std::function<void(CallFun&& call)> ResumeCall; typedef boost::coroutines::asymmetric_coroutine<void>::pull_type PullType; typedef boost::coroutines::asymmetric_coroutine<void>::push_type PushType; private: typedef std::unique_ptr<PullType> PullTypePtr; public: CoroutineContext() :resumeCall_([](CallFun&& call){ call(); }) {} CoroutineContext(ResumeCall&& call) :resumeCall_(call) {} CoroutineContext(IOService::Strand& strand) :resumeCall_([&strand](CallFun&& call){ strand.post(call); }) {} CoroutineContext(CoroutineContext&& other) : resumeCall_(std::move(other.resumeCall_)) {} template<typename Handler> void spawn(IOService& ios, Handler&& handle) { spawn(ios.castGet(), std::move(handle)); } template<typename Handler> void spawn(boost::asio::io_service& ios, Handler&& handle) { ios.post( [this, &ios, handle]() { spawnTask(ios, std::move(handle)); } ); } template<typename Handler> void start(Handler&& handle) { resumeCall_([=]() { start(std::move(handle), true); } ); } template<typename Handler> void create(Handler&& handle) { resumeCall_([=]() { start(std::move(handle), false); } ); } template<typename Handler> void yield(Handler&& handle) { yiledCall_=handle; yield(); } void yield(); void resume(); void resume(const boost::system::error_code& ec) { ecSet(ec); resume(); } void coroReset(); bool isStoped() const { if(!pull_) return true; return !static_cast<bool>(*pull_); } bool isYielded() const { return yielded_; } private: void coroutineReset(PullType* ptr) { assert(isStoped() && ptr); pull_.reset(ptr); } void callerReset(PushType& caller) { assert(isStoped()); push_=&caller; } template<typename Handler> void start(Handler&& handle, bool resumed) { auto ptr = new PullType( [this, handle](PushType& caller) { callerReset(caller); yield(); handle(); } //默认栈尺寸正则表达式匹配时溢出 , boost::coroutines::attributes(1024*1024) ); coroutineReset(ptr); if(!resumed) return; resume(); } template<typename Handler> void spawnTask(boost::asio::io_service& ios, Handler&& handleIn) { start([this, &ios, handle=std::move(handleIn)]() { handle(); //释放当前协程对象 ios.post( std::bind(&CoroutineContext::coroReset , static_cast<CoroutineContext*>(this))); } ); } private: PushType* push_=nullptr; PullTypePtr pull_; bool yielded_=true; CallFun yiledCall_; ResumeCall resumeCall_; }; } <commit_msg>保持协程的轻量级,自动分配的栈尺寸不宜过大<commit_after>// Copyright [2014] <lgb (LiuGuangBao)> //===================================================================================== // // Filename: server.hpp // // Description: 服务器框架 // // Version: 1.0 // Created: 2013年03月05日 17时15分56秒 // Revision: none // Compiler: gcc // // Author: lgb (LiuGuangBao), easyeagel@gmx.com // Organization: magicred.net // //===================================================================================== #pragma once #include<functional> #include<boost/optional.hpp> #include<boost/asio/strand.hpp> #include<boost/asio/spawn.hpp> #include<boost/thread/thread.hpp> #include<boost/asio/io_service.hpp> #include<boost/system/error_code.hpp> #include<boost/asio/steady_timer.hpp> #include"thread.hpp" namespace core { class IOServer; class IOService; class MainServer; class ThreadThis; class IOService : private boost::asio::io_service { friend class IOServer; typedef enum {eStatusUnStart, eStatusWorking, eStatusStopped} Status_t; typedef std::unique_ptr<boost::thread> ThreadPtr; typedef boost::asio::io_service BaseThis; typedef std::function<void()> SimpleCall; public: typedef BaseThis::strand Strand; IOService(); void run(SimpleCall&& call=SimpleCall()); void stopSignal(); void stop(); void reset(); bool stopped() const { return status_==eStatusStopped; } using BaseThis::post; using BaseThis::poll; boost::asio::io_service& castGet() { return *this; } static IOService& cast(boost::asio::io_service& o) { return static_cast<IOService&>(o); } void justRun(SimpleCall&& call=SimpleCall()) { threadRun(std::move(call)); } void join(); private: void threadRun(SimpleCall&& call); private: Status_t status_=eStatusUnStart; ThreadPtr thread_; boost::optional<boost::asio::io_service::work> workGuard_; }; /** * @brief 主线程工作服务器 * @details * @li 本类是单例,并且主线程将工作在此 */ class MainServer : public SingleInstanceT<MainServer> { typedef boost::asio::io_service ASIOService; friend class OnceConstructT<MainServer>; MainServer(); public: typedef std::function<void()> CallFun; static void start(); static void stop(); template<typename Fun> static void post(Fun&& fun) { instance().ios_.post(std::move(fun)); } static ASIOService& get() { return instance().ios_.castGet(); } static IOService& serviceGet() { return instance().ios_; } static void exitCallPush(CallFun&& fun) { auto& obj=instance(); Spinlock::ScopedLock lock(obj.mutex_); obj.exitCalls_.emplace_back(std::move(fun)); } private: bool stopped_; Spinlock mutex_; IOService ios_; std::vector<CallFun> exitCalls_; }; /** * @brief 提供每个CPU有 2 个线程,每线程为一个 @ref IOService 工作 * @details * @li 如果系统只有一个CPU,则只启动一个线程;如果有多个CPU,则每个CPU启动 2 个线程 * @li 每个 @ref IOService 不可能有多个线程共享,请使用 boost::asio::ioservice::strand 进行同步 * * @see IOService, ServicePool */ class IOServer : public SingleInstanceT<IOServer> { enum {eThreadCountPerCPU=2}; enum {eStopWaitSecond=64, eStopWaitTimes=64}; IOServer(const IOServer&)=delete; IOServer& operator=(const IOServer&)=delete; typedef boost::asio::steady_timer SteadyTimer; public: typedef std::function<void()> CallFun; typedef std::function<void(CallFun&& fun)> StopCallFun; IOServer(); static void stop(); static void join(); /** * @brief 停机回调 * @details * @li 调用时服务器框架还没有停止 * @li 按照加入时相反的顺序调用 * * @param fun 被调用的对象 */ static void stopCallPush(StopCallFun&& fun); /** * @brief 开机回调 * @detalis * @li 调用时,框架还没有起来,所以当前是一个线程 * * @param fun 被调用的对象 */ static void startCallPush(CallFun&& fun); static IOService& serviceFetchOne(); static IOService& serviceFetch(size_t idx) { auto& asio=instance().asio_; return asio[idx%asio.size()]; } template<typename Handle> static void post(size_t idx, Handle&& handle) { serviceFetch(idx).post(std::move(handle)); } /** * @brief 在线程池执行指定调用,调用不会立即执行 * 它只是简单地加入任务队列,稍后将被执行 * * @tparam Handle 调用类型 * @param handle 调用对象 */ template<typename Handle> static void post(Handle&& handle) { serviceFetchOne().post(std::move(handle)); } /** * @brief 在每一个线程里的每个线程执行指定调用 * * @tparam Handle 调用类型 * @param handle 调用对象,它将复制到每个线程,并并发执行 */ template<typename Handle> static void postForeach(Handle&& handle) { for(auto& u: instance().asio_) u.post(handle); //这里需要复制 } /** * @brief 在线程池内循环执行指定调用,直到调用返回 @a true * @details * @li 调用的签名为: bool call() * @li 调用返回一个bool值,没有参数需要给出 * @li 当返回值为 true 时,循环将终止,否则调用对象将再次被调度并调用 * * @tparam Handle 调用类型 * @param handle 调用对象 */ template<typename Handle> static void postLoop(Handle&& handleIn) { post([=, handle=std::move(handleIn)]() { bool done=handle(); if(done) return; postLoop(std::move(handle)); } ); } /** * @brief 依次在每个线程里调用指定调用;可选地,在所有调用结束后,执行回调 * * @tparam Handle 任务调用类型 * @tparam Complete 结束调用类型 * @param handle 任务调用对象 * @param complete 结束调用对象 */ template<typename Handle, typename Complete=VoidCallBack> static void postForeachStrand(Handle&& handle, Complete&& complete=Complete()) { instance().postNextIndex(0, std::move(handle), std::move(complete)); } static unsigned ioServiceCountGet() { unsigned const ncpu=cpuCount(); return eThreadCountPerCPU*ncpu; } private: static unsigned cpuCount() { static unsigned ncpu=boost::thread::hardware_concurrency(); return ncpu; } template<typename Handle, typename Complete> void postNextIndex(size_t idx, Handle&& handleIn, Complete&& completeIn) { asio_[idx].post([this, idx, handle=std::move(handleIn), complete=std::move(completeIn)]() { handle(); const auto next=idx+1; if(next>=asio_.size()) { complete(); return; } postNextIndex(next, std::move(handle), std::move(complete)); } ); } static void stopNext(); void stopWait(); void start(); private: static bool started_; std::atomic<unsigned> count_; ///< 用于分配IOService的计数 std::vector<IOService> asio_; size_t waitTimes_; SteadyTimer timer_; //统一的系统启动机制 Spinlock mutex_; std::vector<CallFun> startCall_; std::vector<StopCallFun> stopCall_; }; /** * @brief 计算服务器,执行长时间计算任务;此类任务没有时间要求 * @todo 实现固定线程数的调度与执行 */ class ComputeServer : public SingleInstanceT<ComputeServer> { typedef std::unique_ptr<boost::thread> ThreadPtr; friend class OnceConstructT<ComputeServer>; ComputeServer(); public: typedef std::function<void()> Computor; template<typename Handle> static void post(Handle&& handle) { auto& inst=instance(); assert(static_cast<bool>(inst.stopped_)==false); inst.queue_.push(Computor(std::move(handle))); } static void stop (std::function<void()>&& stopCall); static bool isStopped() { return instance().stopped_; } static void join(); private: void threadTask(); void startImpl(); private: static bool started_; std::atomic<bool> stopped_; std::function<void()> stopCall_; std::vector<ThreadPtr> threads_; std::atomic<uint32_t> threadCount_; ConcurrencyQueueT<Computor> queue_; }; /** * @brief 当前线程对象 * @details * @li 获取当前线程的IOService对象,如果当前线程运行了某个IOService * @note 这应该是总是总是成立的,当 @ref IOServer 运行之后;用户不应该自己创建线程 */ class ThreadThis : private ThreadInstanceT<ThreadThis> { friend class IOService; friend class MainServer; friend class IOServer; friend class ComputeServer; public: typedef enum { eThreadUnkown, eThreadMain, eThreadIOServer, eThreadComputeServer, }ThreadEnum_t; static IOService& serviceGet() { return *instance().io_; } static ThreadEnum_t enumGet() { return instance().threadEnum_; } static bool isSelf(const IOService& s) { return std::addressof(s)==std::addressof(serviceGet()); } static bool isSelf(const boost::asio::io_service& s) { return std::addressof(s)==std::addressof(serviceGet().castGet()); } static bool isMainThread() { return enumGet()==eThreadMain; } static bool isIOThread() { return enumGet()==eThreadIOServer; } static bool isComputeThread() { return enumGet()==eThreadComputeServer; } template<typename Handle> static void post(Handle&& handle) { serviceGet().post(std::move(handle)); } private: static void serviceSet(IOService* io) { instance().io_=io; } static void enumSet(ThreadEnum_t te) { instance().threadEnum_=te; } private: IOService* io_; ThreadEnum_t threadEnum_=eThreadUnkown; }; class CoroutineContext: public ErrorBase { CoroutineContext(const CoroutineContext& other)=delete; CoroutineContext& operator=(CoroutineContext&& other)=delete; CoroutineContext& operator=(const CoroutineContext& other)=delete; public: typedef std::function<void()> CallFun; typedef std::function<void(CallFun&& call)> ResumeCall; typedef boost::coroutines::asymmetric_coroutine<void>::pull_type PullType; typedef boost::coroutines::asymmetric_coroutine<void>::push_type PushType; private: typedef std::unique_ptr<PullType> PullTypePtr; public: CoroutineContext() :resumeCall_([](CallFun&& call){ call(); }) {} CoroutineContext(ResumeCall&& call) :resumeCall_(call) {} CoroutineContext(IOService::Strand& strand) :resumeCall_([&strand](CallFun&& call){ strand.post(call); }) {} CoroutineContext(CoroutineContext&& other) : resumeCall_(std::move(other.resumeCall_)) {} template<typename Handler> void spawn(IOService& ios, Handler&& handle) { spawn(ios.castGet(), std::move(handle)); } template<typename Handler> void spawn(boost::asio::io_service& ios, Handler&& handle) { ios.post( [this, &ios, handle]() { spawnTask(ios, std::move(handle)); } ); } template<typename Handler> void start(Handler&& handle) { resumeCall_([=]() { start(std::move(handle), true); } ); } template<typename Handler> void create(Handler&& handle) { resumeCall_([=]() { start(std::move(handle), false); } ); } template<typename Handler> void yield(Handler&& handle) { yiledCall_=handle; yield(); } void yield(); void resume(); void resume(const boost::system::error_code& ec) { ecSet(ec); resume(); } void coroReset(); bool isStoped() const { if(!pull_) return true; return !static_cast<bool>(*pull_); } bool isYielded() const { return yielded_; } private: void coroutineReset(PullType* ptr) { assert(isStoped() && ptr); pull_.reset(ptr); } void callerReset(PushType& caller) { assert(isStoped()); push_=&caller; } template<typename Handler> void start(Handler&& handle, bool resumed) { auto ptr = new PullType( [this, handle](PushType& caller) { callerReset(caller); yield(); handle(); } ); coroutineReset(ptr); if(!resumed) return; resume(); } template<typename Handler> void spawnTask(boost::asio::io_service& ios, Handler&& handleIn) { start([this, &ios, handle=std::move(handleIn)]() { handle(); //释放当前协程对象 ios.post( std::bind(&CoroutineContext::coroReset , static_cast<CoroutineContext*>(this))); } ); } private: PushType* push_=nullptr; PullTypePtr pull_; bool yielded_=true; CallFun yiledCall_; ResumeCall resumeCall_; }; } <|endoftext|>
<commit_before>#include <stdexcept> #include "helpers.h" #include "device-interface.h" #include "input-driver-test.h" #include <xorg/gtest/xorg-gtest.h> #include <X11/extensions/XInput.h> #include <X11/extensions/XInput2.h> /** * A test fixture for testing the XInput 2.x extension. * * @tparam The XInput 2.x minor version */ class XInput2Test : public InputDriverTest, public DeviceInterface, public ::testing::WithParamInterface<int> { protected: virtual void SetUp() { SetDevice("tablets/N-Trig-MultiTouch.desc"); InputDriverTest::SetUp(); } virtual void SetUpConfigAndLog() { config.AddDefaultScreenWithDriver(); config.SetAutoAddDevices(true); config.WriteConfig(); } virtual int RegisterXI2(int major, int minor) { return InputDriverTest::RegisterXI2(2, GetParam()); } }; TEST_P(XInput2Test, XITouchscreenPointerEmulation) { XORG_TESTCASE("When an initial touch is made, any movement of the pointer\n" "should be raised as if button 1 is being held. After the\n" "touch is released, further movement should have button 1\n" "released.\n"); ASSERT_TRUE(xorg::testing::XServer::WaitForDevice(Display(), "N-Trig MultiTouch")); XIEventMask mask; mask.deviceid = XIAllMasterDevices; mask.mask_len = XIMaskLen(XI_HierarchyChanged); mask.mask = reinterpret_cast<unsigned char*>(calloc(mask.mask_len, 1)); XISetMask(mask.mask, XI_ButtonPress); XISetMask(mask.mask, XI_ButtonRelease); XISetMask(mask.mask, XI_Motion); XISelectEvents(Display(), DefaultRootWindow(Display()), &mask, 1); free(mask.mask); XFlush(Display()); std::auto_ptr<xorg::testing::evemu::Device> mouse_device; try { mouse_device = std::auto_ptr<xorg::testing::evemu::Device>( new xorg::testing::evemu::Device( RECORDINGS_DIR "mice/PIXART-USB-OPTICAL-MOUSE.desc") ); } catch (std::runtime_error &error) { std::cerr << "Failed to create evemu device, skipping test.\n"; return; } ASSERT_TRUE(xorg::testing::XServer::WaitForDevice(Display(), "PIXART USB OPTICAL MOUSE")); XEvent event; XGenericEventCookie *xcookie; XIDeviceEvent *device_event; /* Move the mouse, check that the button is not pressed. */ mouse_device->PlayOne(EV_REL, ABS_X, -1, 1); ASSERT_TRUE(xorg::testing::XServer::WaitForEventOfType(Display(), GenericEvent, xi2_opcode, XI_Motion)); ASSERT_EQ(Success, XNextEvent(Display(), &event)); xcookie = &event.xcookie; ASSERT_TRUE(XGetEventData(Display(), xcookie)); device_event = reinterpret_cast<XIDeviceEvent*>(xcookie->data); ASSERT_FALSE(XIMaskIsSet(device_event->buttons.mask, 1)); XFreeEventData(Display(), xcookie); /* Touch the screen, wait for press event */ dev->Play(RECORDINGS_DIR "tablets/N-Trig-MultiTouch.touch_1_begin.events"); ASSERT_TRUE(xorg::testing::XServer::WaitForEventOfType(Display(), GenericEvent, xi2_opcode, XI_ButtonPress)); ASSERT_EQ(Success, XNextEvent(Display(), &event)); /* Move the mouse again, button 1 should now be pressed. */ mouse_device->PlayOne(EV_REL, ABS_X, -1, 1); ASSERT_TRUE(xorg::testing::XServer::WaitForEventOfType(Display(), GenericEvent, xi2_opcode, XI_Motion)); ASSERT_EQ(Success, XNextEvent(Display(), &event)); xcookie = &event.xcookie; ASSERT_TRUE(XGetEventData(Display(), xcookie)); device_event = reinterpret_cast<XIDeviceEvent*>(xcookie->data); ASSERT_TRUE(XIMaskIsSet(device_event->buttons.mask, 1)); XFreeEventData(Display(), xcookie); /* Release the screen, wait for release event */ dev->Play(RECORDINGS_DIR "tablets/N-Trig-MultiTouch.touch_1_end.events"); ASSERT_TRUE(xorg::testing::XServer::WaitForEventOfType(Display(), GenericEvent, xi2_opcode, XI_ButtonRelease)); ASSERT_EQ(Success, XNextEvent(Display(), &event)); /* Move the mouse again, button 1 should now be released. */ mouse_device->PlayOne(EV_REL, ABS_X, -1, 1); ASSERT_TRUE(xorg::testing::XServer::WaitForEventOfType(Display(), GenericEvent, xi2_opcode, XI_Motion)); ASSERT_EQ(Success, XNextEvent(Display(), &event)); xcookie = &event.xcookie; ASSERT_TRUE(XGetEventData(Display(), xcookie)); device_event = reinterpret_cast<XIDeviceEvent*>(xcookie->data); ASSERT_FALSE(XIMaskIsSet(device_event->buttons.mask, 1)); XFreeEventData(Display(), xcookie); } TEST_P(XInput2Test, XIQueryPointerTouchscreen) { SCOPED_TRACE("\n" "XIQueryPointer for XInput 2.1 and earlier should report the\n" "first button pressed if a touch is physically active. For \n" "XInput 2.2 and later clients, the first button should not be\n" "reported."); XIEventMask mask; mask.deviceid = XIAllDevices; mask.mask_len = XIMaskLen(XI_HierarchyChanged); mask.mask = reinterpret_cast<unsigned char*>(calloc(mask.mask_len, 1)); XISetMask(mask.mask, XI_HierarchyChanged); ASSERT_EQ(Success, XISelectEvents(Display(), DefaultRootWindow(Display()), &mask, 1)); mask.deviceid = XIAllMasterDevices; XIClearMask(mask.mask, XI_HierarchyChanged); XISetMask(mask.mask, XI_ButtonPress); ASSERT_EQ(Success, XISelectEvents(Display(), DefaultRootWindow(Display()), &mask, 1)); free(mask.mask); XFlush(Display()); ASSERT_TRUE(xorg::testing::XServer::WaitForDevice(Display(), "N-Trig MultiTouch")); dev->Play(RECORDINGS_DIR "tablets/N-Trig-MultiTouch.touch_1_begin.events"); ASSERT_TRUE(xorg::testing::XServer::WaitForEventOfType(Display(), GenericEvent, xi2_opcode, XI_ButtonPress)); XEvent event; ASSERT_EQ(Success, XNextEvent(Display(), &event)); XGenericEventCookie *xcookie = &event.xcookie; ASSERT_TRUE(XGetEventData(Display(), xcookie)); XIDeviceEvent *device_event = reinterpret_cast<XIDeviceEvent*>(xcookie->data); Window root; Window child; double root_x; double root_y; double win_x; double win_y; XIButtonState buttons; XIModifierState modifiers; XIGroupState group; ASSERT_TRUE(XIQueryPointer(Display(), device_event->deviceid, DefaultRootWindow(Display()), &root, &child, &root_x, &root_y, &win_x, &win_y, &buttons, &modifiers, &group)); /* Test if button 1 is pressed */ ASSERT_GE(buttons.mask_len, XIMaskLen(2)); if (GetParam() < 2) EXPECT_TRUE(XIMaskIsSet(buttons.mask, 1)); else EXPECT_FALSE(XIMaskIsSet(buttons.mask, 1)); XFreeEventData(Display(), xcookie); } #ifdef HAVE_XI22 TEST_P(XInput2Test, DisableDeviceEndTouches) { SCOPED_TRACE("When a device is disabled, any physically active touches\n" "should end."); /* This is an XInput 2.2 and later test only */ if (GetParam() < 2) return; XIEventMask mask; mask.deviceid = XIAllDevices; mask.mask_len = XIMaskLen(XI_TouchEnd); mask.mask = reinterpret_cast<unsigned char*>(calloc(mask.mask_len, 1)); XISetMask(mask.mask, XI_HierarchyChanged); ASSERT_EQ(Success, XISelectEvents(Display(), DefaultRootWindow(Display()), &mask, 1)); mask.deviceid = XIAllMasterDevices; XIClearMask(mask.mask, XI_HierarchyChanged); XISetMask(mask.mask, XI_TouchBegin); XISetMask(mask.mask, XI_TouchUpdate); XISetMask(mask.mask, XI_TouchEnd); ASSERT_EQ(Success, XISelectEvents(Display(), DefaultRootWindow(Display()), &mask, 1)); free(mask.mask); XFlush(Display()); ASSERT_TRUE(xorg::testing::XServer::WaitForDevice(Display(), "N-Trig MultiTouch")); dev->Play(RECORDINGS_DIR "tablets/N-Trig-MultiTouch.touch_1_begin.events"); ASSERT_TRUE(xorg::testing::XServer::WaitForEventOfType(Display(), GenericEvent, xi2_opcode, XI_TouchBegin)); XEvent event; ASSERT_EQ(Success, XNextEvent(Display(), &event)); XGenericEventCookie *xcookie = &event.xcookie; ASSERT_TRUE(XGetEventData(Display(), xcookie)); XIDeviceEvent *device_event = reinterpret_cast<XIDeviceEvent*>(xcookie->data); XDevice *xdevice = XOpenDevice(Display(), device_event->sourceid); XFreeEventData(Display(), xcookie); ASSERT_TRUE(xdevice != NULL); XDeviceEnableControl enable_control; enable_control.enable = false; XDeviceControl *control = reinterpret_cast<XDeviceControl*>(&enable_control); ASSERT_EQ(XChangeDeviceControl(Display(), xdevice, DEVICE_ENABLE, control), Success); XCloseDevice(Display(), xdevice); XFlush(Display()); ASSERT_TRUE(xorg::testing::XServer::WaitForEventOfType(Display(), GenericEvent, xi2_opcode, XI_TouchEnd)); } /** * Test class for testing * @tparam The device ID */ class XInput2TouchSelectionTest : public XInput2Test { protected: virtual int RegisterXI2(int major, int minor) { return InputDriverTest::RegisterXI2(2, 2); } }; static bool error_handler_triggered; /* ASSERT_*() macros can only be used in void functions, hence the indirection here */ static void _error_handler(XErrorEvent *ev) { ASSERT_EQ((int)ev->error_code, BadAccess); error_handler_triggered = true; } static int error_handler(Display *dpy, XErrorEvent *ev) { _error_handler(ev); return 0; } static void _fail_error_handler(XErrorEvent *ev) { FAIL() << "X protocol error: errorcode: " << (int)ev->error_code << " on request " << (int)ev->request_code << " minor " << (int)ev->minor_code; } static int fail_error_handler(Display *dpy, XErrorEvent *ev) { _fail_error_handler(ev); return 0; } TEST_P(XInput2TouchSelectionTest, TouchSelectionConflicts) { SCOPED_TRACE("If client A has a selection on a device,\n" "client B selecting on the same device returns BadAccess.\n" "If client A has a selection on XIAll(Master)Devices, \n" "selecting on the same or a specific device returns" "BadAccess\n"); unsigned char m[XIMaskLen(XI_TouchEnd)] = {0}; XIEventMask mask; mask.mask = m; mask.mask_len = sizeof(m); XISetMask(mask.mask, XI_TouchBegin); XISetMask(mask.mask, XI_TouchUpdate); XISetMask(mask.mask, XI_TouchEnd); int clientA_deviceid = GetParam(); /* client A */ mask.deviceid = clientA_deviceid; XSetErrorHandler(fail_error_handler); ::Display *dpy2 = XOpenDisplay(server.GetDisplayString().c_str()); ASSERT_TRUE(dpy2); XISelectEvents(dpy2, DefaultRootWindow(dpy2), &mask, 1); XSync(dpy2, False); XSetErrorHandler(error_handler); /* covers XIAllDevices, XIAllMasterDevices and VCP */ for (int clientB_deviceid = 0; clientB_deviceid < 3; clientB_deviceid++) { error_handler_triggered = false; mask.deviceid = clientB_deviceid; XISelectEvents(Display(), DefaultRootWindow(Display()), &mask, 1); XSync(Display(), False); ASSERT_EQ(error_handler_triggered, (clientA_deviceid <= clientB_deviceid)) << "failed for " << clientA_deviceid << "/" << clientB_deviceid; } } INSTANTIATE_TEST_CASE_P(, XInput2TouchSelectionTest, ::testing::Range(0, 3)); #endif /* HAVE_XI22 */ INSTANTIATE_TEST_CASE_P(, XInput2Test, ::testing::Range(0, 3)); int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>server/xi2: convert leftover SCOPED_TRACE to XORG_TESTCASE<commit_after>#include <stdexcept> #include "helpers.h" #include "device-interface.h" #include "input-driver-test.h" #include <xorg/gtest/xorg-gtest.h> #include <X11/extensions/XInput.h> #include <X11/extensions/XInput2.h> /** * A test fixture for testing the XInput 2.x extension. * * @tparam The XInput 2.x minor version */ class XInput2Test : public InputDriverTest, public DeviceInterface, public ::testing::WithParamInterface<int> { protected: virtual void SetUp() { SetDevice("tablets/N-Trig-MultiTouch.desc"); InputDriverTest::SetUp(); } virtual void SetUpConfigAndLog() { config.AddDefaultScreenWithDriver(); config.SetAutoAddDevices(true); config.WriteConfig(); } virtual int RegisterXI2(int major, int minor) { return InputDriverTest::RegisterXI2(2, GetParam()); } }; TEST_P(XInput2Test, XITouchscreenPointerEmulation) { XORG_TESTCASE("When an initial touch is made, any movement of the pointer\n" "should be raised as if button 1 is being held. After the\n" "touch is released, further movement should have button 1\n" "released.\n"); ASSERT_TRUE(xorg::testing::XServer::WaitForDevice(Display(), "N-Trig MultiTouch")); XIEventMask mask; mask.deviceid = XIAllMasterDevices; mask.mask_len = XIMaskLen(XI_HierarchyChanged); mask.mask = reinterpret_cast<unsigned char*>(calloc(mask.mask_len, 1)); XISetMask(mask.mask, XI_ButtonPress); XISetMask(mask.mask, XI_ButtonRelease); XISetMask(mask.mask, XI_Motion); XISelectEvents(Display(), DefaultRootWindow(Display()), &mask, 1); free(mask.mask); XFlush(Display()); std::auto_ptr<xorg::testing::evemu::Device> mouse_device; try { mouse_device = std::auto_ptr<xorg::testing::evemu::Device>( new xorg::testing::evemu::Device( RECORDINGS_DIR "mice/PIXART-USB-OPTICAL-MOUSE.desc") ); } catch (std::runtime_error &error) { std::cerr << "Failed to create evemu device, skipping test.\n"; return; } ASSERT_TRUE(xorg::testing::XServer::WaitForDevice(Display(), "PIXART USB OPTICAL MOUSE")); XEvent event; XGenericEventCookie *xcookie; XIDeviceEvent *device_event; /* Move the mouse, check that the button is not pressed. */ mouse_device->PlayOne(EV_REL, ABS_X, -1, 1); ASSERT_TRUE(xorg::testing::XServer::WaitForEventOfType(Display(), GenericEvent, xi2_opcode, XI_Motion)); ASSERT_EQ(Success, XNextEvent(Display(), &event)); xcookie = &event.xcookie; ASSERT_TRUE(XGetEventData(Display(), xcookie)); device_event = reinterpret_cast<XIDeviceEvent*>(xcookie->data); ASSERT_FALSE(XIMaskIsSet(device_event->buttons.mask, 1)); XFreeEventData(Display(), xcookie); /* Touch the screen, wait for press event */ dev->Play(RECORDINGS_DIR "tablets/N-Trig-MultiTouch.touch_1_begin.events"); ASSERT_TRUE(xorg::testing::XServer::WaitForEventOfType(Display(), GenericEvent, xi2_opcode, XI_ButtonPress)); ASSERT_EQ(Success, XNextEvent(Display(), &event)); /* Move the mouse again, button 1 should now be pressed. */ mouse_device->PlayOne(EV_REL, ABS_X, -1, 1); ASSERT_TRUE(xorg::testing::XServer::WaitForEventOfType(Display(), GenericEvent, xi2_opcode, XI_Motion)); ASSERT_EQ(Success, XNextEvent(Display(), &event)); xcookie = &event.xcookie; ASSERT_TRUE(XGetEventData(Display(), xcookie)); device_event = reinterpret_cast<XIDeviceEvent*>(xcookie->data); ASSERT_TRUE(XIMaskIsSet(device_event->buttons.mask, 1)); XFreeEventData(Display(), xcookie); /* Release the screen, wait for release event */ dev->Play(RECORDINGS_DIR "tablets/N-Trig-MultiTouch.touch_1_end.events"); ASSERT_TRUE(xorg::testing::XServer::WaitForEventOfType(Display(), GenericEvent, xi2_opcode, XI_ButtonRelease)); ASSERT_EQ(Success, XNextEvent(Display(), &event)); /* Move the mouse again, button 1 should now be released. */ mouse_device->PlayOne(EV_REL, ABS_X, -1, 1); ASSERT_TRUE(xorg::testing::XServer::WaitForEventOfType(Display(), GenericEvent, xi2_opcode, XI_Motion)); ASSERT_EQ(Success, XNextEvent(Display(), &event)); xcookie = &event.xcookie; ASSERT_TRUE(XGetEventData(Display(), xcookie)); device_event = reinterpret_cast<XIDeviceEvent*>(xcookie->data); ASSERT_FALSE(XIMaskIsSet(device_event->buttons.mask, 1)); XFreeEventData(Display(), xcookie); } TEST_P(XInput2Test, XIQueryPointerTouchscreen) { XORG_TESTCASE("XIQueryPointer for XInput 2.1 and earlier should report the\n" "first button pressed if a touch is physically active. For \n" "XInput 2.2 and later clients, the first button should not be\n" "reported."); XIEventMask mask; mask.deviceid = XIAllDevices; mask.mask_len = XIMaskLen(XI_HierarchyChanged); mask.mask = reinterpret_cast<unsigned char*>(calloc(mask.mask_len, 1)); XISetMask(mask.mask, XI_HierarchyChanged); ASSERT_EQ(Success, XISelectEvents(Display(), DefaultRootWindow(Display()), &mask, 1)); mask.deviceid = XIAllMasterDevices; XIClearMask(mask.mask, XI_HierarchyChanged); XISetMask(mask.mask, XI_ButtonPress); ASSERT_EQ(Success, XISelectEvents(Display(), DefaultRootWindow(Display()), &mask, 1)); free(mask.mask); XFlush(Display()); ASSERT_TRUE(xorg::testing::XServer::WaitForDevice(Display(), "N-Trig MultiTouch")); dev->Play(RECORDINGS_DIR "tablets/N-Trig-MultiTouch.touch_1_begin.events"); ASSERT_TRUE(xorg::testing::XServer::WaitForEventOfType(Display(), GenericEvent, xi2_opcode, XI_ButtonPress)); XEvent event; ASSERT_EQ(Success, XNextEvent(Display(), &event)); XGenericEventCookie *xcookie = &event.xcookie; ASSERT_TRUE(XGetEventData(Display(), xcookie)); XIDeviceEvent *device_event = reinterpret_cast<XIDeviceEvent*>(xcookie->data); Window root; Window child; double root_x; double root_y; double win_x; double win_y; XIButtonState buttons; XIModifierState modifiers; XIGroupState group; ASSERT_TRUE(XIQueryPointer(Display(), device_event->deviceid, DefaultRootWindow(Display()), &root, &child, &root_x, &root_y, &win_x, &win_y, &buttons, &modifiers, &group)); /* Test if button 1 is pressed */ ASSERT_GE(buttons.mask_len, XIMaskLen(2)); if (GetParam() < 2) EXPECT_TRUE(XIMaskIsSet(buttons.mask, 1)); else EXPECT_FALSE(XIMaskIsSet(buttons.mask, 1)); XFreeEventData(Display(), xcookie); } #ifdef HAVE_XI22 TEST_P(XInput2Test, DisableDeviceEndTouches) { XORG_TESTCASE("When a device is disabled, any physically active touches\n" "should end."); /* This is an XInput 2.2 and later test only */ if (GetParam() < 2) return; XIEventMask mask; mask.deviceid = XIAllDevices; mask.mask_len = XIMaskLen(XI_TouchEnd); mask.mask = reinterpret_cast<unsigned char*>(calloc(mask.mask_len, 1)); XISetMask(mask.mask, XI_HierarchyChanged); ASSERT_EQ(Success, XISelectEvents(Display(), DefaultRootWindow(Display()), &mask, 1)); mask.deviceid = XIAllMasterDevices; XIClearMask(mask.mask, XI_HierarchyChanged); XISetMask(mask.mask, XI_TouchBegin); XISetMask(mask.mask, XI_TouchUpdate); XISetMask(mask.mask, XI_TouchEnd); ASSERT_EQ(Success, XISelectEvents(Display(), DefaultRootWindow(Display()), &mask, 1)); free(mask.mask); XFlush(Display()); ASSERT_TRUE(xorg::testing::XServer::WaitForDevice(Display(), "N-Trig MultiTouch")); dev->Play(RECORDINGS_DIR "tablets/N-Trig-MultiTouch.touch_1_begin.events"); ASSERT_TRUE(xorg::testing::XServer::WaitForEventOfType(Display(), GenericEvent, xi2_opcode, XI_TouchBegin)); XEvent event; ASSERT_EQ(Success, XNextEvent(Display(), &event)); XGenericEventCookie *xcookie = &event.xcookie; ASSERT_TRUE(XGetEventData(Display(), xcookie)); XIDeviceEvent *device_event = reinterpret_cast<XIDeviceEvent*>(xcookie->data); XDevice *xdevice = XOpenDevice(Display(), device_event->sourceid); XFreeEventData(Display(), xcookie); ASSERT_TRUE(xdevice != NULL); XDeviceEnableControl enable_control; enable_control.enable = false; XDeviceControl *control = reinterpret_cast<XDeviceControl*>(&enable_control); ASSERT_EQ(XChangeDeviceControl(Display(), xdevice, DEVICE_ENABLE, control), Success); XCloseDevice(Display(), xdevice); XFlush(Display()); ASSERT_TRUE(xorg::testing::XServer::WaitForEventOfType(Display(), GenericEvent, xi2_opcode, XI_TouchEnd)); } /** * Test class for testing * @tparam The device ID */ class XInput2TouchSelectionTest : public XInput2Test { protected: virtual int RegisterXI2(int major, int minor) { return InputDriverTest::RegisterXI2(2, 2); } }; static bool error_handler_triggered; /* ASSERT_*() macros can only be used in void functions, hence the indirection here */ static void _error_handler(XErrorEvent *ev) { ASSERT_EQ((int)ev->error_code, BadAccess); error_handler_triggered = true; } static int error_handler(Display *dpy, XErrorEvent *ev) { _error_handler(ev); return 0; } static void _fail_error_handler(XErrorEvent *ev) { FAIL() << "X protocol error: errorcode: " << (int)ev->error_code << " on request " << (int)ev->request_code << " minor " << (int)ev->minor_code; } static int fail_error_handler(Display *dpy, XErrorEvent *ev) { _fail_error_handler(ev); return 0; } TEST_P(XInput2TouchSelectionTest, TouchSelectionConflicts) { XORG_TESTCASE("If client A has a selection on a device,\n" "client B selecting on the same device returns BadAccess.\n" "If client A has a selection on XIAll(Master)Devices, \n" "selecting on the same or a specific device returns" "BadAccess\n"); unsigned char m[XIMaskLen(XI_TouchEnd)] = {0}; XIEventMask mask; mask.mask = m; mask.mask_len = sizeof(m); XISetMask(mask.mask, XI_TouchBegin); XISetMask(mask.mask, XI_TouchUpdate); XISetMask(mask.mask, XI_TouchEnd); int clientA_deviceid = GetParam(); /* client A */ mask.deviceid = clientA_deviceid; XSetErrorHandler(fail_error_handler); ::Display *dpy2 = XOpenDisplay(server.GetDisplayString().c_str()); ASSERT_TRUE(dpy2); XISelectEvents(dpy2, DefaultRootWindow(dpy2), &mask, 1); XSync(dpy2, False); XSetErrorHandler(error_handler); /* covers XIAllDevices, XIAllMasterDevices and VCP */ for (int clientB_deviceid = 0; clientB_deviceid < 3; clientB_deviceid++) { error_handler_triggered = false; mask.deviceid = clientB_deviceid; XISelectEvents(Display(), DefaultRootWindow(Display()), &mask, 1); XSync(Display(), False); ASSERT_EQ(error_handler_triggered, (clientA_deviceid <= clientB_deviceid)) << "failed for " << clientA_deviceid << "/" << clientB_deviceid; } } INSTANTIATE_TEST_CASE_P(, XInput2TouchSelectionTest, ::testing::Range(0, 3)); #endif /* HAVE_XI22 */ INSTANTIATE_TEST_CASE_P(, XInput2Test, ::testing::Range(0, 3)); int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>// Comprehensive stress test for socket-like API #include <stdio.h> #include <unistd.h> #include <sys/socket.h> #include <arpa/inet.h> #include <string.h> #include <netdb.h> #include "libzt.h" #define NETWORK_ID "8056c2e21c000001" #define PORT 7878 #define BUF_SIZE 2000 void attach(int from_fd, int to_fd) { char buffer[BUF_SIZE]; while (true) { size_t readLength = read(from_fd, buffer, BUF_SIZE); write(to_fd, buffer, readLength); } } void *receive_messages(void *sockPtr) { attach(*(int *) sockPtr, 1); return NULL; } int listen_and_accept(int sockfd) { struct sockaddr_in6 serv_addr, cli_addr; serv_addr.sin6_flowinfo = 0; serv_addr.sin6_family = AF_INET6; serv_addr.sin6_addr = in6addr_any; serv_addr.sin6_port = htons(PORT); if (zts_bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) printf("ERROR on binding"); printf("Bind Complete\n"); zts_listen(sockfd, 1); printf("Listening\n"); int cli_addr_len = sizeof(cli_addr); // accept int newsockfd = zts_accept(sockfd, (struct sockaddr *) &cli_addr, (socklen_t *) &cli_addr_len); if (newsockfd < 0) printf("ERROR on accept"); char client_addr_ipv6[100]; inet_ntop(AF_INET6, &(cli_addr.sin6_addr), client_addr_ipv6, 100); printf("Incoming connection from client having IPv6 address: %s\n", client_addr_ipv6); return newsockfd; } void receive_messages_in_background(int &newsockfd) { pthread_t rThread; int ret = pthread_create(&rThread, NULL, receive_messages, &newsockfd); if (ret != 0) { printf("ERROR: Return Code from pthread_create() is %d\n", ret); } } int main(int argc, char *argv[]) { zts_simple_start("./zt", NETWORK_ID); char id[ZT_ID_LEN + 1]; zts_get_device_id(id); printf("id = %s\n", id); char homePath[ZT_HOME_PATH_MAX_LEN + 1]; zts_get_homepath(homePath, ZT_HOME_PATH_MAX_LEN); printf("homePath = %s\n", homePath); char ipv4[ZT_MAX_IPADDR_LEN]; char ipv6[ZT_MAX_IPADDR_LEN]; zts_get_ipv4_address((char *) NETWORK_ID, ipv4, ZT_MAX_IPADDR_LEN); printf("ipv4 = %s\n", ipv4); zts_get_ipv6_address((char *) NETWORK_ID, ipv6, ZT_MAX_IPADDR_LEN); printf("ipv6 = %s\n", ipv6); printf("peer_count = %lu\n", zts_get_peer_count()); int sockfd; if ((sockfd = zts_socket(AF_INET6, SOCK_STREAM, 0)) < 0) { fprintf(stderr, "error in opening socket\n"); } printf("sockfd = %d\n", sockfd); if (argv[1]) { struct hostent *server = gethostbyname2(argv[1], AF_INET6); struct sockaddr_in6 serv_addr; memset((char *) &serv_addr, 0, sizeof(serv_addr)); serv_addr.sin6_flowinfo = 0; serv_addr.sin6_family = AF_INET6; memmove((char *) &serv_addr.sin6_addr.s6_addr, (char *) server->h_addr, server->h_length); serv_addr.sin6_port = htons(PORT); int err; if ((err = zts_connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr))) < 0) { printf("error connecting to remote host (%d)\n", err); return -1; } receive_messages_in_background(sockfd); attach(0, sockfd); } else { int newsockfd = listen_and_accept(sockfd); receive_messages_in_background(newsockfd); attach(0, newsockfd); sleep(2); zts_close(newsockfd); } sleep(2); zts_close(sockfd); zts_stop(); return 0; } <commit_msg>Listen/Attach does not make assumptions about fds<commit_after>// Comprehensive stress test for socket-like API #include <stdio.h> #include <unistd.h> #include <sys/socket.h> #include <arpa/inet.h> #include <string.h> #include <netdb.h> #include "libzt.h" #define NETWORK_ID "8056c2e21c000001" #define PORT 7878 #define BUF_SIZE 2000 void attach(int from_fd, int to_fd) { char buffer[BUF_SIZE]; while (true) { size_t readLength = read(from_fd, buffer, BUF_SIZE); write(to_fd, buffer, readLength); } } void *attach_fds(void *args) { int *fds = (int *) args; attach(fds[0], fds[1]); return NULL; } int listen_and_accept(int sockfd) { struct sockaddr_in6 serv_addr, cli_addr; serv_addr.sin6_flowinfo = 0; serv_addr.sin6_family = AF_INET6; serv_addr.sin6_addr = in6addr_any; serv_addr.sin6_port = htons(PORT); if (zts_bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) printf("ERROR on binding"); printf("Bind Complete\n"); zts_listen(sockfd, 1); printf("Listening\n"); int cli_addr_len = sizeof(cli_addr); // accept int newsockfd = zts_accept(sockfd, (struct sockaddr *) &cli_addr, (socklen_t *) &cli_addr_len); if (newsockfd < 0) printf("ERROR on accept"); char client_addr_ipv6[100]; inet_ntop(AF_INET6, &(cli_addr.sin6_addr), client_addr_ipv6, 100); printf("Incoming connection from client having IPv6 address: %s\n", client_addr_ipv6); return newsockfd; } void attach_in_background(int from_fd, int to_fd) { pthread_t rThread; int args[] = {from_fd, to_fd}; int ret = pthread_create(&rThread, NULL, attach_fds, &args); if (ret != 0) { printf("ERROR: Return Code from pthread_create() is %d\n", ret); } } int main(int argc, char *argv[]) { zts_simple_start("./zt", NETWORK_ID); char id[ZT_ID_LEN + 1]; zts_get_device_id(id); printf("id = %s\n", id); char homePath[ZT_HOME_PATH_MAX_LEN + 1]; zts_get_homepath(homePath, ZT_HOME_PATH_MAX_LEN); printf("homePath = %s\n", homePath); char ipv4[ZT_MAX_IPADDR_LEN]; char ipv6[ZT_MAX_IPADDR_LEN]; zts_get_ipv4_address((char *) NETWORK_ID, ipv4, ZT_MAX_IPADDR_LEN); printf("ipv4 = %s\n", ipv4); zts_get_ipv6_address((char *) NETWORK_ID, ipv6, ZT_MAX_IPADDR_LEN); printf("ipv6 = %s\n", ipv6); printf("peer_count = %lu\n", zts_get_peer_count()); int sockfd; if ((sockfd = zts_socket(AF_INET6, SOCK_STREAM, 0)) < 0) { fprintf(stderr, "error in opening socket\n"); } printf("sockfd = %d\n", sockfd); if (argv[1]) { struct hostent *server = gethostbyname2(argv[1], AF_INET6); struct sockaddr_in6 serv_addr; memset((char *) &serv_addr, 0, sizeof(serv_addr)); serv_addr.sin6_flowinfo = 0; serv_addr.sin6_family = AF_INET6; memmove((char *) &serv_addr.sin6_addr.s6_addr, (char *) server->h_addr, server->h_length); serv_addr.sin6_port = htons(PORT); int err; if ((err = zts_connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr))) < 0) { printf("error connecting to remote host (%d)\n", err); return -1; } attach_in_background(sockfd, 1); attach(0, sockfd); } else { int newsockfd = listen_and_accept(sockfd); attach_in_background(newsockfd, 1); attach(0, newsockfd); sleep(2); zts_close(newsockfd); } sleep(2); zts_close(sockfd); zts_stop(); return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: xpathapi.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: ihi $ $Date: 2006-12-20 14:18:02 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include "xpathapi.hxx" #include "nodelist.hxx" #include "xpathobject.hxx" #include "../dom/node.hxx" #include <libxml/xpath.h> #include <libxml/xpathInternals.h> namespace XPath { Reference< XInterface > CXPathAPI::_getInstance(const Reference< XMultiServiceFactory >& rSMgr) { // XXX // return static_cast< XXPathAPI* >(new CXPathAPI()); return Reference< XInterface >(static_cast<XXPathAPI*>(new CXPathAPI(rSMgr))); } CXPathAPI::CXPathAPI(const Reference< XMultiServiceFactory >& rSMgr) : m_aFactory(rSMgr) { } const char* CXPathAPI::aImplementationName = "com.sun.star.comp.xml.xpath.XPathAPI"; const char* CXPathAPI::aSupportedServiceNames[] = { "com.sun.star.xml.xpath.XPathAPI", NULL }; OUString CXPathAPI::_getImplementationName() { return OUString::createFromAscii(aImplementationName); } Sequence<OUString> CXPathAPI::_getSupportedServiceNames() { Sequence<OUString> aSequence; for (int i=0; aSupportedServiceNames[i]!=NULL; i++) { aSequence.realloc(i+1); aSequence[i]=(OUString::createFromAscii(aSupportedServiceNames[i])); } return aSequence; } Sequence< OUString > SAL_CALL CXPathAPI::getSupportedServiceNames() throw (RuntimeException) { return CXPathAPI::_getSupportedServiceNames(); } OUString SAL_CALL CXPathAPI::getImplementationName() throw (RuntimeException) { return CXPathAPI::_getImplementationName(); } sal_Bool SAL_CALL CXPathAPI::supportsService(const OUString& aServiceName) throw (RuntimeException) { Sequence< OUString > supported = CXPathAPI::_getSupportedServiceNames(); for (sal_Int32 i=0; i<supported.getLength(); i++) { if (supported[i] == aServiceName) return sal_True; } return sal_False; } // ------------------------------------------------------------------- void SAL_CALL CXPathAPI::registerNS(const OUString& aPrefix, const OUString& aURI) throw (RuntimeException) { m_nsmap.insert(nsmap_t::value_type(aPrefix, aURI)); } void SAL_CALL CXPathAPI::unregisterNS(const OUString& aPrefix, const OUString& aURI) throw (RuntimeException) { if ((m_nsmap.find(aPrefix))->second.equals(aURI)) m_nsmap.erase(aPrefix); } static void _registerNamespaces(xmlXPathContextPtr ctx, const nsmap_t& nsmap) { nsmap_t::const_iterator i = nsmap.begin(); OString oprefix, ouri; xmlChar *p, *u; while (i != nsmap.end()) { oprefix = OUStringToOString(i->first, RTL_TEXTENCODING_UTF8); ouri = OUStringToOString(i->second, RTL_TEXTENCODING_UTF8); p = (xmlChar*)oprefix.getStr(); u = (xmlChar*)ouri.getStr(); xmlXPathRegisterNs(ctx, p, u); i++; } } static void _registerExtensions(xmlXPathContextPtr ctx, const extensions_t& extensions) { extensions_t::const_iterator i = extensions.begin(); while (i != extensions.end()) { Libxml2ExtensionHandle aHandle = (*i)->getLibxml2ExtensionHandle(); if ( aHandle.functionLookupFunction != 0 ) xmlXPathRegisterFuncLookup(ctx, reinterpret_cast<xmlXPathFuncLookupFunc>(sal::static_int_cast<sal_IntPtr>(aHandle.functionLookupFunction)), /* (xmlXPathFuncLookupFunc) aHandle.functionLookupFunction, */ reinterpret_cast<void*>(sal::static_int_cast<sal_IntPtr>(aHandle.functionData))); /* (void*)(aHandle.functionData));*/ if ( aHandle.variableLookupFunction != 0 ) xmlXPathRegisterVariableLookup(ctx, /* (xmlXPathVariableLookupFunc) aHandle.variableLookupFunction, */ reinterpret_cast<xmlXPathVariableLookupFunc>(sal::static_int_cast<sal_IntPtr>(aHandle.variableLookupFunction)), /*(void*)(aHandle.variableData));*/ reinterpret_cast<void*>(sal::static_int_cast<sal_IntPtr>(aHandle.variableData))); i++; } } /** Use an XPath string to select a nodelist. */ Reference< XNodeList > SAL_CALL CXPathAPI::selectNodeList( const Reference< XNode >& contextNode, const OUString& str) throw (RuntimeException) { xmlXPathContextPtr xpathCtx; xmlXPathObjectPtr xpathObj; // get the node and document xmlNodePtr pNode = DOM::CNode::getNodePtr(contextNode); xmlDocPtr pDoc = pNode->doc; /* Create xpath evaluation context */ xpathCtx = xmlXPathNewContext(pDoc); if (xpathCtx == NULL)throw RuntimeException(); xpathCtx->node = pNode; _registerNamespaces(xpathCtx, m_nsmap); OString o1 = OUStringToOString(str, RTL_TEXTENCODING_UTF8); xmlChar *xStr = (xmlChar*)o1.getStr(); /* run the query */ if ((xpathObj = xmlXPathEval(xStr, xpathCtx)) == NULL) { xmlXPathFreeContext(xpathCtx); throw RuntimeException(); } Reference< XNodeList > aList(new CNodeList(xpathObj)); xmlXPathFreeContext(xpathCtx); return aList; } /** Use an XPath string to select a nodelist. */ Reference< XNodeList > SAL_CALL CXPathAPI::selectNodeListNS( const Reference< XNode >& /* contextNode */, const OUString& /* str */, const Reference< XNode >& /* namespaceNode */) throw (RuntimeException) { return Reference< XNodeList>(); } /** Use an XPath string to select a single node. */ Reference< XNode > SAL_CALL CXPathAPI::selectSingleNode( const Reference< XNode >& contextNode, const OUString& str) throw (RuntimeException) { Reference< XNodeList > aList = selectNodeList(contextNode, str); Reference< XNode > aNode = aList->item(0); return aNode; } /** Use an XPath string to select a single node. */ Reference< XNode > SAL_CALL CXPathAPI::selectSingleNodeNS( const Reference< XNode >& /* contextNode */, const OUString& /* str */, const Reference< XNode >& /* namespaceNode*/ ) throw (RuntimeException) { return Reference< XNode >(); } Reference< XXPathObject > SAL_CALL CXPathAPI::eval(const Reference< XNode >& contextNode, const OUString& str) throw (RuntimeException) { xmlXPathContextPtr xpathCtx; xmlXPathObjectPtr xpathObj; // get the node and document xmlNodePtr pNode = DOM::CNode::getNodePtr(contextNode); xmlDocPtr pDoc = pNode->doc; /* Create xpath evaluation context */ xpathCtx = xmlXPathNewContext(pDoc); if (xpathCtx == NULL)throw RuntimeException(); // set conext node xpathCtx->node = pNode; _registerNamespaces(xpathCtx, m_nsmap); _registerExtensions(xpathCtx, m_extensions); OString o1 = OUStringToOString(str, RTL_TEXTENCODING_UTF8); xmlChar *xStr = (xmlChar*)o1.getStr(); /* run the query */ if ((xpathObj = xmlXPathEval(xStr, xpathCtx)) == NULL) { // OSL_ENSURE(xpathCtx->lastError == NULL, xpathCtx->lastError->message); xmlXPathFreeContext(xpathCtx); throw RuntimeException(); } xmlXPathFreeContext(xpathCtx); Reference< XXPathObject > aObj(new CXPathObject(xpathObj)); return aObj; } Reference< XXPathObject > SAL_CALL CXPathAPI::evalNS(const Reference< XNode >& /* contextNode */, const OUString& /* str */, const Reference< XNode >& /* namespaceNode */) throw (RuntimeException) { return Reference< XXPathObject>(); } void SAL_CALL CXPathAPI::registerExtension(const OUString& aName) throw (RuntimeException) { // get extension from service manager Reference< XXPathExtension > aExtension(m_aFactory->createInstance(aName), UNO_QUERY_THROW); m_extensions.push_back( aExtension ); } void SAL_CALL CXPathAPI::registerExtensionInstance(const Reference< XXPathExtension>& aExtension) throw (RuntimeException) { if (aExtension.is()) { m_extensions.push_back( aExtension ); } else throw RuntimeException(); } } <commit_msg>INTEGRATION: CWS changefileheader (1.5.40); FILE MERGED 2008/03/31 13:39:00 rt 1.5.40.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: xpathapi.cxx,v $ * $Revision: 1.6 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #include "xpathapi.hxx" #include "nodelist.hxx" #include "xpathobject.hxx" #include "../dom/node.hxx" #include <libxml/xpath.h> #include <libxml/xpathInternals.h> namespace XPath { Reference< XInterface > CXPathAPI::_getInstance(const Reference< XMultiServiceFactory >& rSMgr) { // XXX // return static_cast< XXPathAPI* >(new CXPathAPI()); return Reference< XInterface >(static_cast<XXPathAPI*>(new CXPathAPI(rSMgr))); } CXPathAPI::CXPathAPI(const Reference< XMultiServiceFactory >& rSMgr) : m_aFactory(rSMgr) { } const char* CXPathAPI::aImplementationName = "com.sun.star.comp.xml.xpath.XPathAPI"; const char* CXPathAPI::aSupportedServiceNames[] = { "com.sun.star.xml.xpath.XPathAPI", NULL }; OUString CXPathAPI::_getImplementationName() { return OUString::createFromAscii(aImplementationName); } Sequence<OUString> CXPathAPI::_getSupportedServiceNames() { Sequence<OUString> aSequence; for (int i=0; aSupportedServiceNames[i]!=NULL; i++) { aSequence.realloc(i+1); aSequence[i]=(OUString::createFromAscii(aSupportedServiceNames[i])); } return aSequence; } Sequence< OUString > SAL_CALL CXPathAPI::getSupportedServiceNames() throw (RuntimeException) { return CXPathAPI::_getSupportedServiceNames(); } OUString SAL_CALL CXPathAPI::getImplementationName() throw (RuntimeException) { return CXPathAPI::_getImplementationName(); } sal_Bool SAL_CALL CXPathAPI::supportsService(const OUString& aServiceName) throw (RuntimeException) { Sequence< OUString > supported = CXPathAPI::_getSupportedServiceNames(); for (sal_Int32 i=0; i<supported.getLength(); i++) { if (supported[i] == aServiceName) return sal_True; } return sal_False; } // ------------------------------------------------------------------- void SAL_CALL CXPathAPI::registerNS(const OUString& aPrefix, const OUString& aURI) throw (RuntimeException) { m_nsmap.insert(nsmap_t::value_type(aPrefix, aURI)); } void SAL_CALL CXPathAPI::unregisterNS(const OUString& aPrefix, const OUString& aURI) throw (RuntimeException) { if ((m_nsmap.find(aPrefix))->second.equals(aURI)) m_nsmap.erase(aPrefix); } static void _registerNamespaces(xmlXPathContextPtr ctx, const nsmap_t& nsmap) { nsmap_t::const_iterator i = nsmap.begin(); OString oprefix, ouri; xmlChar *p, *u; while (i != nsmap.end()) { oprefix = OUStringToOString(i->first, RTL_TEXTENCODING_UTF8); ouri = OUStringToOString(i->second, RTL_TEXTENCODING_UTF8); p = (xmlChar*)oprefix.getStr(); u = (xmlChar*)ouri.getStr(); xmlXPathRegisterNs(ctx, p, u); i++; } } static void _registerExtensions(xmlXPathContextPtr ctx, const extensions_t& extensions) { extensions_t::const_iterator i = extensions.begin(); while (i != extensions.end()) { Libxml2ExtensionHandle aHandle = (*i)->getLibxml2ExtensionHandle(); if ( aHandle.functionLookupFunction != 0 ) xmlXPathRegisterFuncLookup(ctx, reinterpret_cast<xmlXPathFuncLookupFunc>(sal::static_int_cast<sal_IntPtr>(aHandle.functionLookupFunction)), /* (xmlXPathFuncLookupFunc) aHandle.functionLookupFunction, */ reinterpret_cast<void*>(sal::static_int_cast<sal_IntPtr>(aHandle.functionData))); /* (void*)(aHandle.functionData));*/ if ( aHandle.variableLookupFunction != 0 ) xmlXPathRegisterVariableLookup(ctx, /* (xmlXPathVariableLookupFunc) aHandle.variableLookupFunction, */ reinterpret_cast<xmlXPathVariableLookupFunc>(sal::static_int_cast<sal_IntPtr>(aHandle.variableLookupFunction)), /*(void*)(aHandle.variableData));*/ reinterpret_cast<void*>(sal::static_int_cast<sal_IntPtr>(aHandle.variableData))); i++; } } /** Use an XPath string to select a nodelist. */ Reference< XNodeList > SAL_CALL CXPathAPI::selectNodeList( const Reference< XNode >& contextNode, const OUString& str) throw (RuntimeException) { xmlXPathContextPtr xpathCtx; xmlXPathObjectPtr xpathObj; // get the node and document xmlNodePtr pNode = DOM::CNode::getNodePtr(contextNode); xmlDocPtr pDoc = pNode->doc; /* Create xpath evaluation context */ xpathCtx = xmlXPathNewContext(pDoc); if (xpathCtx == NULL)throw RuntimeException(); xpathCtx->node = pNode; _registerNamespaces(xpathCtx, m_nsmap); OString o1 = OUStringToOString(str, RTL_TEXTENCODING_UTF8); xmlChar *xStr = (xmlChar*)o1.getStr(); /* run the query */ if ((xpathObj = xmlXPathEval(xStr, xpathCtx)) == NULL) { xmlXPathFreeContext(xpathCtx); throw RuntimeException(); } Reference< XNodeList > aList(new CNodeList(xpathObj)); xmlXPathFreeContext(xpathCtx); return aList; } /** Use an XPath string to select a nodelist. */ Reference< XNodeList > SAL_CALL CXPathAPI::selectNodeListNS( const Reference< XNode >& /* contextNode */, const OUString& /* str */, const Reference< XNode >& /* namespaceNode */) throw (RuntimeException) { return Reference< XNodeList>(); } /** Use an XPath string to select a single node. */ Reference< XNode > SAL_CALL CXPathAPI::selectSingleNode( const Reference< XNode >& contextNode, const OUString& str) throw (RuntimeException) { Reference< XNodeList > aList = selectNodeList(contextNode, str); Reference< XNode > aNode = aList->item(0); return aNode; } /** Use an XPath string to select a single node. */ Reference< XNode > SAL_CALL CXPathAPI::selectSingleNodeNS( const Reference< XNode >& /* contextNode */, const OUString& /* str */, const Reference< XNode >& /* namespaceNode*/ ) throw (RuntimeException) { return Reference< XNode >(); } Reference< XXPathObject > SAL_CALL CXPathAPI::eval(const Reference< XNode >& contextNode, const OUString& str) throw (RuntimeException) { xmlXPathContextPtr xpathCtx; xmlXPathObjectPtr xpathObj; // get the node and document xmlNodePtr pNode = DOM::CNode::getNodePtr(contextNode); xmlDocPtr pDoc = pNode->doc; /* Create xpath evaluation context */ xpathCtx = xmlXPathNewContext(pDoc); if (xpathCtx == NULL)throw RuntimeException(); // set conext node xpathCtx->node = pNode; _registerNamespaces(xpathCtx, m_nsmap); _registerExtensions(xpathCtx, m_extensions); OString o1 = OUStringToOString(str, RTL_TEXTENCODING_UTF8); xmlChar *xStr = (xmlChar*)o1.getStr(); /* run the query */ if ((xpathObj = xmlXPathEval(xStr, xpathCtx)) == NULL) { // OSL_ENSURE(xpathCtx->lastError == NULL, xpathCtx->lastError->message); xmlXPathFreeContext(xpathCtx); throw RuntimeException(); } xmlXPathFreeContext(xpathCtx); Reference< XXPathObject > aObj(new CXPathObject(xpathObj)); return aObj; } Reference< XXPathObject > SAL_CALL CXPathAPI::evalNS(const Reference< XNode >& /* contextNode */, const OUString& /* str */, const Reference< XNode >& /* namespaceNode */) throw (RuntimeException) { return Reference< XXPathObject>(); } void SAL_CALL CXPathAPI::registerExtension(const OUString& aName) throw (RuntimeException) { // get extension from service manager Reference< XXPathExtension > aExtension(m_aFactory->createInstance(aName), UNO_QUERY_THROW); m_extensions.push_back( aExtension ); } void SAL_CALL CXPathAPI::registerExtensionInstance(const Reference< XXPathExtension>& aExtension) throw (RuntimeException) { if (aExtension.is()) { m_extensions.push_back( aExtension ); } else throw RuntimeException(); } } <|endoftext|>
<commit_before>#pragma once #include <Arduino.h> #include <SPI.h> class serprog { Stream& in; Print& out; SPISettings cfg; int cs; void (serprog::* cmds[32])() { &serprog::ack, /* 0x00 */ &serprog::version, /* 0x01 */ &serprog::map, /* 0x02 */ &serprog::name, /* 0x03 */ &serprog::size, /* 0x04 */ &serprog::gbus, /* 0x05 */ nullptr, /* 0x06 */ nullptr, /* 0x07 */ nullptr, /* 0x08 */ nullptr, /* 0x09 */ nullptr, /* 0x0A */ nullptr, /* 0x0B */ nullptr, /* 0x0C */ nullptr, /* 0x0D */ nullptr, /* 0x0E */ nullptr, /* 0x0F */ &serprog::sync, /* 0x10 */ nullptr, /* 0x11 */ &serprog::sbus, /* 0x12 */ &serprog::op, /* 0x13 */ &serprog::freq, /* 0x14 */ nullptr /* 0x15 */ /* nullptr (default) 0x?? */ }; void ack(); void nak(); void version(); void map(); void name(); void size(); void gbus(); void sync(); void sbus(); void op(); void freq(); public: template<typename T> serprog(T& t, int pin) : in(t), out(t), cfg(), cs(pin) {} void setup(); void loop(); }; <commit_msg>Trim unused command slots<commit_after>#pragma once #include <Arduino.h> #include <SPI.h> class serprog { Stream& in; Print& out; SPISettings cfg; int cs; void (serprog::* cmds[22])() { &serprog::ack, /* 0x00 */ &serprog::version, /* 0x01 */ &serprog::map, /* 0x02 */ &serprog::name, /* 0x03 */ &serprog::size, /* 0x04 */ &serprog::gbus, /* 0x05 */ nullptr, /* 0x06 */ nullptr, /* 0x07 */ nullptr, /* 0x08 */ nullptr, /* 0x09 */ nullptr, /* 0x0A */ nullptr, /* 0x0B */ nullptr, /* 0x0C */ nullptr, /* 0x0D */ nullptr, /* 0x0E */ nullptr, /* 0x0F */ &serprog::sync, /* 0x10 */ nullptr, /* 0x11 */ &serprog::sbus, /* 0x12 */ &serprog::op, /* 0x13 */ &serprog::freq, /* 0x14 */ nullptr /* 0x15 */ }; void ack(); void nak(); void version(); void map(); void name(); void size(); void gbus(); void sync(); void sbus(); void op(); void freq(); public: template<typename T> serprog(T& t, int pin) : in(t), out(t), cfg(), cs(pin) {} void setup(); void loop(); }; <|endoftext|>
<commit_before>#ifndef _DATA_STRUCTURES_HPP #define _DATA_STRUCTURES_HPP /** * Includes any data structures required for ray-tracing. * Currently supports points, rays, and vectors */ /** * Represents a color in RGBA format */ class Color{ public: float red, green, blue; /** * Constructor for objects of class Color. * * @param r the color red * @param g the color green * @param b the color blue */ Color(float r, float g, float b); ~Color(); /** * Overloaded multiplcation-assignment operator. * color * scalar * * @param scalar The scalar to multiply with the color. * @return A pointer to the lhs of the equation. */ Color operator* (float); /** * Overloaded multiplcation-assignment operator. * * @param c The color to multiply with the original color. * @return The componentwise product of the colors */ Color operator* (const Color&); /** * Overloaded addition operator. * * @param c The color to add with the original color. * @return The sum of the colors */ Color operator+ (const Color&); /** * Limit color values to the range [0, 1] * @return This color with channels constrained */ Color clamp() const; }; /** * Overloaded multiplcation-assignment operator. * scalar * color * * @param scalar The scalar to multiply. * @param c The color to multiply * @return A pointer to the lhs of the equation. */ Color operator*(float, Color); const float EPSILON = 1e-4; /** * Represents a 3-dimensional vector. */ class Vector { public: float i, j, k; /** * Constructor for objects of class Vector. * * @param i The x-direction * @param j The y-direction * @param k The z-direction */ Vector(float i, float j, float k); /** * Vector approximate comparison * @return Componentwise comparison to within EPSILON */ bool approx_equals(const Vector&) const; /** * Overloaded addition-assignment operator. * Performs component based addition-assignment. * * @param rhs The vector to add. * @return A pointer to the lhs of the equation. */ Vector& operator+=(const Vector& rhs); /** * Overloaded subtraction-assignment operator. * Performs component based subtraction-assignment. * * @param rhs The vector to subtract. * @return A pointer to the lhs of the equation. */ Vector& operator-=(const Vector& rhs); /** * Overloaded addition operator. * Performs component based addition. * * @param other The vector to add. * @return A pointer to the result. */ Vector operator+(const Vector& other); /** * Overloaded subtraction operator. * Performs component based subtraction. * * @param other The vector to subtract. * @return A pointer to the result. */ Vector operator-(const Vector& other); /** * Vector multiplication by scalar. */ Vector operator*(float) const; /** * Vector division by scalar. */ Vector operator/(float) const; /** * Vector magnitude */ float magnitude() const; /** * Magnitude squared */ float magnitude2() const; /** * Normalizes the vector to a unit vector. */ void normalize(); /** * Returns a normalized copy of the vector */ Vector normalized() const; /** * Compute the dot product when dotted with the given Vector. * * @param v a normalized vector. * @return the dot product of this vector with v. */ float dotProduct(Vector v) const; /** * Vector cross product */ Vector crossProduct(Vector) const; }; /** * Represents a 3-dimensional point in space. */ class Point { public: float x, y, z; /** * Constructor for objects of class Point. * * @param x The x-coordinate * @param y The y-coordinate * @param z The z-coordinate */ Point(float x, float y, float z); /** * Overloaded comparison operator. * Does coordinate based comparison. * * @param p The point to compare with. * @return True if the points are equivalent, false otherwise. */ bool operator==(const Point &p) const; /** * Overloaded subtraction operator. * Performs component based subtraction. * * @param other The Point to subtract. * @return A pointer to the result. */ Vector operator-(const Point& other); /** * Overloaded comparison operator. * Does coordinate based comparison. * * @param p The point to compare with. * @return False if the points are equivalent, true otherwise. */ bool operator!=(const Point &p) const; /* //this operator overload doesn't really work yet. //it was designed for an operation in plane intersection Vector operator-(const Point& p); */ }; /** * Represents a ray, which includes a point and a vector. */ class Ray { public: Point origin; Vector dir; /** * Constructor for objects of class Ray. * * @param origin The origin of the ray. * @param dir The direction vector of the ray. */ Ray(Point origin, Vector dir); /** * Default ray constructor * Lives at <0,0,0> and points at <0,0,1> */ Ray(); /** * Accessor method for the origin. * * @return The point representing the origin of the ray. */ Point getOrigin() const; /** * Accessor method for the direction vector. * * @return The vector representing the direction of the ray. */ Vector getDir() const; /** * Normalizes the vector portion to a unit vector. */ void normalize(); /** * Creates a ray between two points. * * @param origin The starting point for the ray. * @param dest The destination point for the ray. * @return A ray object which starts at origin and passes through dest. */ static Ray makeRay(Point origin, Point dest); }; float degrees(float); #endif <commit_msg>Began to document Color<commit_after>#ifndef _DATA_STRUCTURES_HPP #define _DATA_STRUCTURES_HPP /** * Represents a color as a triple (R,G,B) of floats from 0 to 1 * representing the full range of intensity. Values above 1 are * considered to be at full intensity for output purposes, and values * below 0 are considered to be at no intensity (implemented by * clamp()). */ class Color{ public: float red, green, blue; /** * Constructor for objects of class Color. * * @param r the color red * @param g the color green * @param b the color blue */ Color(float r, float g, float b); ~Color(); /** * Multiplication of a color by a scalar. * Each component of the color is multiplied by the scalar * * @param scalar The scalar to multiply with the color. * @return A new color (R*scalar, G*scalar, B*scalar) */ Color operator* (float); /** * Multiplication of a color by a color. Each component of this * color is multiplied by the corresponding component of the * parameter. * * @param c The color to multiply with the original color. * @return A new color (R1*R2, G1*G2, B1*B2). */ Color operator* (const Color&); /** * Addition of a color to a color. Each component of this * color is added to the corresponding component of the * parameter. * * @param c The color to add with the original color. * @return A new color (R1+R2, G1+G2, B1+B2). */ Color operator+ (const Color&); /** * Limit color values to the range [0, 1]. * @return A copy of this color with channels constrained. */ Color clamp() const; }; /** * \relates Color * Multiplication of a scalar by a color, with arguments reversed. * * @return Delegates to Color::operator*(Color,float) */ Color operator*(float, Color); const float EPSILON = 1e-4; /** * Represents a 3-dimensional vector. */ class Vector { public: float i, j, k; /** * Constructor for objects of class Vector. * * @param i The x-direction * @param j The y-direction * @param k The z-direction */ Vector(float i, float j, float k); /** * Vector approximate comparison * @return Componentwise comparison to within EPSILON */ bool approx_equals(const Vector&) const; /** * Overloaded addition-assignment operator. * Performs component based addition-assignment. * * @param rhs The vector to add. * @return A pointer to the lhs of the equation. */ Vector& operator+=(const Vector& rhs); /** * Overloaded subtraction-assignment operator. * Performs component based subtraction-assignment. * * @param rhs The vector to subtract. * @return A pointer to the lhs of the equation. */ Vector& operator-=(const Vector& rhs); /** * Overloaded addition operator. * Performs component based addition. * * @param other The vector to add. * @return A pointer to the result. */ Vector operator+(const Vector& other); /** * Overloaded subtraction operator. * Performs component based subtraction. * * @param other The vector to subtract. * @return A pointer to the result. */ Vector operator-(const Vector& other); /** * Vector multiplication by scalar. */ Vector operator*(float) const; /** * Vector division by scalar. */ Vector operator/(float) const; /** * Vector magnitude */ float magnitude() const; /** * Magnitude squared */ float magnitude2() const; /** * Normalizes the vector to a unit vector. */ void normalize(); /** * Returns a normalized copy of the vector */ Vector normalized() const; /** * Compute the dot product when dotted with the given Vector. * * @param v a normalized vector. * @return the dot product of this vector with v. */ float dotProduct(Vector v) const; /** * Vector cross product */ Vector crossProduct(Vector) const; }; /** * Represents a 3-dimensional point in space. */ class Point { public: float x, y, z; /** * Constructor for objects of class Point. * * @param x The x-coordinate * @param y The y-coordinate * @param z The z-coordinate */ Point(float x, float y, float z); /** * Overloaded comparison operator. * Does coordinate based comparison. * * @param p The point to compare with. * @return True if the points are equivalent, false otherwise. */ bool operator==(const Point &p) const; /** * Overloaded subtraction operator. * Performs component based subtraction. * * @param other The Point to subtract. * @return A pointer to the result. */ Vector operator-(const Point& other); /** * Overloaded comparison operator. * Does coordinate based comparison. * * @param p The point to compare with. * @return False if the points are equivalent, true otherwise. */ bool operator!=(const Point &p) const; /* //this operator overload doesn't really work yet. //it was designed for an operation in plane intersection Vector operator-(const Point& p); */ }; /** * Represents a ray, which includes a point and a vector. */ class Ray { public: Point origin; Vector dir; /** * Constructor for objects of class Ray. * * @param origin The origin of the ray. * @param dir The direction vector of the ray. */ Ray(Point origin, Vector dir); /** * Default ray constructor * Lives at <0,0,0> and points at <0,0,1> */ Ray(); /** * Accessor method for the origin. * * @return The point representing the origin of the ray. */ Point getOrigin() const; /** * Accessor method for the direction vector. * * @return The vector representing the direction of the ray. */ Vector getDir() const; /** * Normalizes the vector portion to a unit vector. */ void normalize(); /** * Creates a ray between two points. * * @param origin The starting point for the ray. * @param dest The destination point for the ray. * @return A ray object which starts at origin and passes through dest. */ static Ray makeRay(Point origin, Point dest); }; float degrees(float); #endif <|endoftext|>
<commit_before>#include <iostream> #include "opencv2/core.hpp" #include "opencv2/imgcodecs.hpp" #include "opencv2/imgcodecs/imgcodecs_c.h" using namespace cv; #include "Reddit.hpp" #include "../constants.hpp" #include "../util/math.hpp" #include "../util/file.hpp" #include "../features/feature.hpp" #include "../features/FeatMat.hpp" // DataSets namespace namespace ds { void Reddit::addToFeatMat(FeatMat& featMat) { paths files = getUnprocessedImagePaths("../datasets/Reddit/"); #pragma omp parallel for for (int i = 0; i < files.size(); i++) { auto fpath = files[i].string(); std::cout << "Loading: " << fpath << " (" << i << "/" << files.size() << ")" << std::endl; // Load cached image maps. Abort if invalid image [maps] Mat saliency, grad; try { saliency = imread(setSuffix(fpath, "saliency").string(), CV_LOAD_IMAGE_UNCHANGED); grad = imread(setSuffix(fpath, "grad").string(), CV_LOAD_IMAGE_UNCHANGED); } catch (std::exception e) { std::cout << "Error reading: " << fpath << std::endl; continue; } if (!saliency.data || !grad.data) { std::cout << "Error reading: " << fpath << std::endl; continue; } // Image is good crop Rect crop = Rect(0, 0, saliency.cols, saliency.rows); featMat.addFeatVec(saliency, grad, crop, GOOD_CROP); // Randomly generated crop is "bad" float sum_saliency = sum(saliency)[0]; float total_area = saliency.cols * saliency.rows; int n_bad = 0; while (true) { crop = randomCrop(saliency); float S_content = sum(saliency(crop))[0] / sum_saliency; float S_area = (float)(crop.x*crop.y) / total_area; if (S_content < 0.2 && S_area > 0.2) { featMat.addFeatVec(saliency, grad, crop, BAD_CROP); n_bad++; } if (n_bad == 2) break; } } } } <commit_msg>Fix autocrop Reddit feature-gen params<commit_after>#include <iostream> #include "opencv2/core.hpp" #include "opencv2/imgcodecs.hpp" #include "opencv2/imgcodecs/imgcodecs_c.h" using namespace cv; #include "Reddit.hpp" #include "../constants.hpp" #include "../util/math.hpp" #include "../util/file.hpp" #include "../features/feature.hpp" #include "../features/FeatMat.hpp" // DataSets namespace namespace ds { void Reddit::addToFeatMat(FeatMat& featMat) { paths files = getUnprocessedImagePaths("../datasets/Reddit/"); #pragma omp parallel for for (int i = 0; i < files.size(); i++) { auto fpath = files[i].string(); std::cout << "Loading: " << fpath << " (" << i << "/" << files.size() << ")" << std::endl; // Load cached image maps. Abort if invalid image [maps] Mat saliency, grad; try { saliency = imread(setSuffix(fpath, "saliency").string(), CV_LOAD_IMAGE_UNCHANGED); grad = imread(setSuffix(fpath, "grad").string(), CV_LOAD_IMAGE_UNCHANGED); } catch (std::exception e) { std::cout << "Error reading: " << fpath << std::endl; continue; } if (!saliency.data || !grad.data) { std::cout << "Error reading: " << fpath << std::endl; continue; } // Image is good crop Rect crop = Rect(0, 0, saliency.cols, saliency.rows); featMat.addFeatVec(saliency, grad, crop, GOOD_CROP); // Randomly generated crop is "bad" float sum_saliency = sum(saliency)[0]; float total_area = saliency.cols * saliency.rows; int n_bad = 0; while (true) { crop = randomCrop(saliency); float S_content = sum(saliency(crop))[0] / sum_saliency; float S_area = (float)(crop.x*crop.y) / total_area; if (S_content < 0.15 && S_area > 0.2) { featMat.addFeatVec(saliency, grad, crop, BAD_CROP); n_bad++; } if (n_bad == 2) break; } } } } <|endoftext|>
<commit_before>#include <limits> #include <stdio.h> #include <stdexcept> #include <cassert> #include <boost/shared_ptr.hpp> #include <geneial/algorithm/BaseGeneticAlgorithm.h> #include <geneial/core/fitness/Fitness.h> #include <geneial/core/fitness/FitnessEvaluator.h> #include <geneial/core/population/PopulationSettings.h> #include <geneial/core/population/builder/ContinousMultiValueBuilderSettings.h> #include <geneial/core/population/builder/ContinousMultiIntValueChromosomeFactory.h> #include <geneial/core/operations/selection/FitnessProportionalSelection.h> #include <geneial/core/operations/selection/FitnessProportionalSelectionSettings.h> #include <geneial/core/operations/selection/SelectionSettings.h> #include <geneial/core/operations/selection/RouletteWheelSelection.h> #include <geneial/core/operations/selection/UniformRandomSelection.h> //#include <geneial/core/operations/coupling/SimpleCouplingOperation.h> #include <geneial/core/operations/coupling/RandomCouplingOperation.h> #include <geneial/core/operations/replacement/BaseReplacementSettings.h> #include <geneial/core/operations/replacement/ReplaceWorstOperation.h> #include <geneial/core/operations/replacement/ReplaceRandomOperation.h> #include <geneial/core/operations/crossover/MultiValueChromosomeNPointCrossover.h> #include <geneial/core/operations/crossover/MultiValueChromosomeNPointCrossoverSettings.h> #include <geneial/core/operations/crossover/MultiValueChromosomeAverageCrossover.h> #include <geneial/core/operations/mutation/MutationSettings.h> //#include <geneial/core/operations/mutation/UniformMutationOperation.h> #include <geneial/core/operations/mutation/SmoothPeakMutationOperation.h> #include <geneial/core/operations/choosing/ChooseRandom.h> #include <geneial/core/fitness/MultithreadedFitnessProcessingStrategy.h> #include <geneial/algorithm/observer/BestChromosomeObserver.h> #include <geneial/algorithm/criteria/MaxGenerationCriterion.h> #include <geneial/algorithm/criteria/CombinedCriterion.h> #include <geneial/algorithm/criteria/FixPointCriterion.h> #include <geneial/config.h> #include <cmath> using namespace geneial; using namespace geneial::algorithm; using namespace geneial::algorithm::stopping_criteria; using namespace geneial::population; using namespace geneial::population::chromosome; using namespace geneial::operation::selection; using namespace geneial::operation::coupling; using namespace geneial::operation::crossover; using namespace geneial::operation::replacement; using namespace geneial::operation::mutation; using namespace geneial::operation::choosing; double myTargetFunc(double x){ //Some Lagrange poly + Manual Tweakage x = 0.55*x + 0.3; const double result = ( 84211 * std::pow(x,6) -4829676 * std::pow(x,5) +104637796 * std::pow(x,4) -1070636286 * std::pow(x,3) +5268146305 * std::pow(x,2) -11346283350 * x +10783521000 ) /37346400 + (2.10*0.001*x*x*x*(x/2)); return result; } void plot(MultiValueChromosome<int,double>::ptr chromosomeToPrint){ MultiValueChromosome<int,double>::value_container container = chromosomeToPrint->getContainer(); const double xmax = 30; const double xstep = 0.25; const double ymax = 180; const double ystep = 20; for(double y = ymax; y >= 0; y-=ystep) { for(double x = 0; x < xmax ; x += xstep) { char out = ' '; const double result = myTargetFunc(x); if( y <= result && result < y+ystep) { out = '+'; } const double result2 = container[x]; if( y <= result2 && result2 < y+ystep) { if(out == '+') { out = 'X'; }else{ out = '-'; } } std::cout << out; } std::cout << std::endl; } std::cout << std::endl; std::cout << "Age:" << chromosomeToPrint->getAge(); std::cout << " Fitness:" << chromosomeToPrint->getFitness()->get(); std::cout << std::endl; std::cout.width(15); std::cout.width(1); std::cout << "|"; std::cout.width(15); std::cout << std::left << " X "; std::cout.width(1); std::cout << "|"; std::cout.width(15); std::cout << std::left << " Y "; std::cout.width(1); std::cout << "|"; std::cout.width(15); std::cout << std::left << " Target "; std::cout.width(1); std::cout << "|"; std::cout.width(15); std::cout << std::left << " |y1-y2| " << "|"; std::cout << std::endl; for(int i = 0; i< 30;i++){ std::cout.width(15); std::cout.width(1); std::cout << "|"; std::cout.width(15); std::cout << std::right << i+1; std::cout.precision(6); std::cout.setf( std::ios::fixed, std:: ios::floatfield ); std::cout.width(1); std::cout << "|"; std::cout.width(15); std::cout << std::right << container[i]; std::cout.width(1); std::cout << "|"; std::cout.width(15); std::cout << std::right << myTargetFunc(i); std::cout.width(1); std::cout << "|"; std::cout.width(15); std::cout << std::right << std::abs(myTargetFunc(i)-container[i]) << "|"; std::cout << std::endl; } } class DemoChromosomeEvaluator: public FitnessEvaluator<double> { public: DemoChromosomeEvaluator(){}; Fitness<double>::ptr evaluate(const BaseChromosome<double>::ptr chromosome) const { double fitness = 1; MultiValueChromosome<int,double>::ptr mvc = boost::dynamic_pointer_cast<MultiValueChromosome<int,double> >(chromosome); if(mvc) { MultiValueChromosome<int,double>::value_container container = mvc->getContainer(); int i = 0; for(MultiValueChromosome<int,double>::value_container::const_iterator it = container.begin();it != container.end();++it) { fitness += std::abs(*it - myTargetFunc(i)); i++; } return boost::shared_ptr<Fitness<double> > (new Fitness<double>(1/fitness)); }else{ throw new std::runtime_error("Chromosome is not an Integer MultiValueChromosome with double fitness!"); } boost::shared_ptr<Fitness<double> > ptr(new Fitness<double>(0)); return ptr; } }; void inline printClearScreen() { #ifdef WINDOWS std::system ( "CLS" ); #else // Assume POSIX std::system ( "clear" ); #endif } class DemoObserver : public BestChromosomeObserver<double> { public: DemoObserver(){}; void updateNewBestChromosome(BaseManager<double> &manager) { MultiValueChromosome<int,double>::ptr mvc = boost::dynamic_pointer_cast<MultiValueChromosome<int,double> >(manager.getHighestFitnessChromosome()); printClearScreen(); plot(mvc); } }; int main(int argc, char **argv) { std::cout << "Running GENEIAL demo3 - Version " << GENEIAL_VERSION_MAJOR << "." << GENEIAL_VERSION_MINOR << " ("<< GENEIAL_BUILD_TYPE << ")"<< std::endl; DemoChromosomeEvaluator::ptr evaluator(new DemoChromosomeEvaluator()); PopulationSettings *populationSettings = new PopulationSettings(1000); ContinousMultiValueBuilderSettings<int,double> *builderSettings = new ContinousMultiValueBuilderSettings<int,double>(evaluator,30,210,-100,false,0,10); ContinousMultiIntValueChromosomeFactory<double> *chromosomeFactory = new ContinousMultiIntValueChromosomeFactory<double>(builderSettings); MutationSettings* mutationSettings = new MutationSettings(0.4,0.1,0); ChooseRandom<int,double> *mutationChoosingOperation = new ChooseRandom<int,double>(mutationSettings); //BaseMutationOperation<double> *mutationOperation = new UniformMutationOperation<int,double>(mutationSettings,mutationChoosingOperation,builderSettings,chromosomeFactory); /*MutationSettings *settings, BaseChoosingOperation<FITNESS_TYPE> *choosingOperation, ContinousMultiValueBuilderSettings<VALUE_TYPE, FITNESS_TYPE> *builderSettings, ContinousMultiIntValueChromosomeFactory<FITNESS_TYPE> *builderFactory, unsigned int maxLeftEps, unsigned int maxRightEps, FITNESS_TYPE maxElevation ) */ BaseMutationOperation<double> *mutationOperation = new SmoothPeakMutationOperation<int,double> ( mutationSettings, mutationChoosingOperation, builderSettings, chromosomeFactory, 10, //MAX PEAK TO LEFT 10, //MAX PEAK TO RIGHT 20 //MAX Elevation to mutate ); //FitnessProportionalSelectionSettings* selectionSettings = new FitnessProportionalSelectionSettings(20,10); SelectionSettings* selectionSettings = new SelectionSettings(20); //BaseSelectionOperation<double> *selectionOperation = new FitnessProportionalSelection<double>(selectionSettings); BaseSelectionOperation<double> *selectionOperation = new RouletteWheelSelection<double>(selectionSettings); //BaseSelectionOperation<double> *selectionOperation = new UniformRandomSelection<double>(selectionSettings); CouplingSettings *couplingSettings = new CouplingSettings(20); //BaseCouplingOperation<double> *couplingOperation = new SimpleCouplingOperation<double>(couplingSettings); BaseCouplingOperation<double> *couplingOperation = new RandomCouplingOperation<double>(couplingSettings); MultiValueChromosomeNPointCrossoverSettings *crossoverSettings = new MultiValueChromosomeNPointCrossoverSettings(1,MultiValueChromosomeNPointCrossoverSettings::RANDOM_WIDTH,5); BaseCrossoverOperation<double> *crossoverOperation = new MultiValueChromosomeNPointCrossover<int,double>(crossoverSettings,builderSettings,chromosomeFactory); //BaseCrossoverOperation<double> *crossoverOperation = new MultiValueChromosomeAverageCrossover<int,double>(builderSettings,chromosomeFactory); //BaseReplacementSettings *replacementSettings = new BaseReplacementSettings(BaseReplacementSettings::replace_offspring_mode::REPLACE_FIXED_NUMBER,20); BaseReplacementSettings *replacementSettings = new BaseReplacementSettings(BaseReplacementSettings::REPLACE_ALL_OFFSPRING,20,0); ReplaceWorstOperation<double> *replacementOperation = new ReplaceWorstOperation<double>(replacementSettings); //ReplaceRandomOperation<double> *replacementOperation = new ReplaceRandomOperation<double>(replacementSettings); BaseFitnessProcessingStrategy<double> *fitnessProcessingStrategy = new MultiThreadedFitnessProcessingStrategy<double>(4); //BaseStoppingCriterion<double> *stoppingCriterion = new MaxGenerationCriterion<double>(100000); CombinedCriterion<double> combinedCriterion; combinedCriterion.add(CombinedCriterion<double>::AND, boost::shared_ptr<BaseStoppingCriterion<double> >(new MaxGenerationCriterion<double>(100000))); combinedCriterion.add(CombinedCriterion<double>::OR, boost::shared_ptr<BaseStoppingCriterion<double> >(new FixPointCriterion<double>(0,1000,1000))); DemoObserver printObserver; BaseGeneticAlgorithm<double> algorithm = BaseGeneticAlgorithm<double>( populationSettings, chromosomeFactory, &combinedCriterion, selectionOperation, couplingOperation, crossoverOperation, replacementOperation, mutationOperation, fitnessProcessingStrategy ); algorithm.registerObserver(&printObserver); algorithm.solve(); BaseChromosome<double>::ptr chromosome = algorithm.getHighestFitnessChromosome(); MultiValueChromosome<int,double>::ptr mvc = boost::dynamic_pointer_cast<MultiValueChromosome<int,double> >(chromosome); printClearScreen(); plot(mvc); std::cout << "ended after " << algorithm.getPopulation().getAge() << " generations" << std::endl; //normally, this is not necessary because we're exiting here anyway, //but for valgrind's satisfaction, we free stuff nonetheless. delete populationSettings; delete chromosomeFactory; delete selectionSettings; delete selectionOperation; delete fitnessProcessingStrategy; delete couplingSettings; delete couplingOperation; delete crossoverSettings; delete crossoverOperation; delete replacementSettings; delete replacementOperation; delete mutationSettings; delete mutationChoosingOperation; delete mutationOperation; } <commit_msg>demo work<commit_after>#include <limits> #include <stdio.h> #include <stdexcept> #include <cassert> #include <boost/shared_ptr.hpp> #include <geneial/algorithm/BaseGeneticAlgorithm.h> #include <geneial/core/fitness/Fitness.h> #include <geneial/core/fitness/FitnessEvaluator.h> #include <geneial/core/population/PopulationSettings.h> #include <geneial/core/population/builder/ContinousMultiValueBuilderSettings.h> #include <geneial/core/population/builder/ContinousMultiIntValueChromosomeFactory.h> #include <geneial/core/operations/selection/FitnessProportionalSelection.h> #include <geneial/core/operations/selection/FitnessProportionalSelectionSettings.h> #include <geneial/core/operations/selection/SelectionSettings.h> #include <geneial/core/operations/selection/RouletteWheelSelection.h> #include <geneial/core/operations/selection/UniformRandomSelection.h> //#include <geneial/core/operations/coupling/SimpleCouplingOperation.h> #include <geneial/core/operations/coupling/RandomCouplingOperation.h> #include <geneial/core/operations/replacement/BaseReplacementSettings.h> #include <geneial/core/operations/replacement/ReplaceWorstOperation.h> #include <geneial/core/operations/replacement/ReplaceRandomOperation.h> #include <geneial/core/operations/crossover/MultiValueChromosomeBlendingCrossover.h> #include <geneial/core/operations/crossover/MultiValueChromosomeNPointCrossoverSettings.h> #include <geneial/core/operations/crossover/SmoothedMultiValueChromosomeNPointCrossover.h> #include <geneial/core/operations/mutation/MutationSettings.h> //#include <geneial/core/operations/mutation/UniformMutationOperation.h> #include <geneial/core/operations/mutation/SmoothPeakMutationOperation.h> #include <geneial/core/operations/choosing/ChooseRandom.h> #include <geneial/core/fitness/MultithreadedFitnessProcessingStrategy.h> #include <geneial/algorithm/observer/BestChromosomeObserver.h> #include <geneial/algorithm/criteria/MaxGenerationCriterion.h> #include <geneial/algorithm/criteria/CombinedCriterion.h> #include <geneial/algorithm/criteria/FixPointCriterion.h> #include <geneial/config.h> #include <cmath> using namespace geneial; using namespace geneial::algorithm; using namespace geneial::algorithm::stopping_criteria; using namespace geneial::population; using namespace geneial::population::chromosome; using namespace geneial::operation::selection; using namespace geneial::operation::coupling; using namespace geneial::operation::crossover; using namespace geneial::operation::replacement; using namespace geneial::operation::mutation; using namespace geneial::operation::choosing; double myTargetFunc1(double x){ return std::sin(x)*std::abs(std::sin(M_PI/2+x*x/2))*30+50; } double myTargetFunc2(double x){ //Some Lagrange poly + Manual Tweakage x = 0.55*x + 0.3; const double result = ( 84211 * std::pow(x,6) -4829676 * std::pow(x,5) +104637796 * std::pow(x,4) -1070636286 * std::pow(x,3) +5268146305 * std::pow(x,2) -11346283350 * x +10783521000 ) /37346400 + (2.10*0.001*x*x*x*(x/2)); return result; } void plot(MultiValueChromosome<int,double>::ptr chromosomeToPrint){ MultiValueChromosome<int,double>::value_container container = chromosomeToPrint->getContainer(); const double xmax = 30; const double xstep = 0.25; const double ymax = 180; const double ystep = 20; for(double y = ymax; y >= 0; y-=ystep) { for(double x = 0; x < xmax ; x += xstep) { char out = ' '; const double result = myTargetFunc1(x); if( y <= result && result < y+ystep) { out = '+'; } const double result2 = container[x]; if( y <= result2 && result2 < y+ystep) { if(out == '+') { out = 'X'; }else{ out = '-'; } } std::cout << out; } std::cout << std::endl; } std::cout << std::endl; std::cout << "Age:" << chromosomeToPrint->getAge(); std::cout << " Fitness:" << chromosomeToPrint->getFitness()->get(); std::cout << std::endl; std::cout.width(15); std::cout.width(1); std::cout << "|"; std::cout.width(15); std::cout << std::left << " X "; std::cout.width(1); std::cout << "|"; std::cout.width(15); std::cout << std::left << " Y "; std::cout.width(1); std::cout << "|"; std::cout.width(15); std::cout << std::left << " Target "; std::cout.width(1); std::cout << "|"; std::cout.width(15); std::cout << std::left << " |y1-y2| " << "|"; std::cout << std::endl; for(int i = 0; i< 30;i++){ std::cout.width(15); std::cout.width(1); std::cout << "|"; std::cout.width(15); std::cout << std::right << i+1; std::cout.precision(6); std::cout.setf( std::ios::fixed, std:: ios::floatfield ); std::cout.width(1); std::cout << "|"; std::cout.width(15); std::cout << std::right << container[i]; std::cout.width(1); std::cout << "|"; std::cout.width(15); std::cout << std::right << myTargetFunc1(i); std::cout.width(1); std::cout << "|"; std::cout.width(15); std::cout << std::right << std::abs(myTargetFunc1(i)-container[i]) << "|"; std::cout << std::endl; } } class DemoChromosomeEvaluator: public FitnessEvaluator<double> { public: DemoChromosomeEvaluator(){}; Fitness<double>::ptr evaluate(const BaseChromosome<double>::ptr chromosome) const { double fitness = 1; MultiValueChromosome<int,double>::ptr mvc = boost::dynamic_pointer_cast<MultiValueChromosome<int,double> >(chromosome); if(mvc) { MultiValueChromosome<int,double>::value_container container = mvc->getContainer(); int i = 0; for(MultiValueChromosome<int,double>::value_container::const_iterator it = container.begin();it != container.end();++it) { fitness += std::abs(*it - myTargetFunc1(i)); i++; } return boost::shared_ptr<Fitness<double> > (new Fitness<double>(1/fitness)); }else{ throw new std::runtime_error("Chromosome is not an Integer MultiValueChromosome with double fitness!"); } boost::shared_ptr<Fitness<double> > ptr(new Fitness<double>(0)); return ptr; } }; void inline printClearScreen() { #ifdef WINDOWS std::system ( "CLS" ); #else // Assume POSIX std::system ( "clear" ); #endif } class DemoObserver : public BestChromosomeObserver<double> { public: DemoObserver(){}; void updateNewBestChromosome(BaseManager<double> &manager) { MultiValueChromosome<int,double>::ptr mvc = boost::dynamic_pointer_cast<MultiValueChromosome<int,double> >(manager.getHighestFitnessChromosome()); printClearScreen(); plot(mvc); } }; int main(int argc, char **argv) { std::cout << "Running GENEIAL demo3 - Version " << GENEIAL_VERSION_MAJOR << "." << GENEIAL_VERSION_MINOR << " ("<< GENEIAL_BUILD_TYPE << ")"<< std::endl; DemoChromosomeEvaluator::ptr evaluator(new DemoChromosomeEvaluator()); PopulationSettings *populationSettings = new PopulationSettings(1000); ContinousMultiValueBuilderSettings<int,double> *builderSettings = new ContinousMultiValueBuilderSettings<int,double>(evaluator,30,210,-100,false,0,40); ContinousMultiIntValueChromosomeFactory<double> *chromosomeFactory = new ContinousMultiIntValueChromosomeFactory<double>(builderSettings); MutationSettings* mutationSettings = new MutationSettings(0.4,0.1,0); ChooseRandom<int,double> *mutationChoosingOperation = new ChooseRandom<int,double>(mutationSettings); BaseMutationOperation<double> *mutationOperation = new SmoothPeakMutationOperation<int,double> ( mutationSettings, mutationChoosingOperation, builderSettings, chromosomeFactory, 10, //MAX PEAK TO LEFT 10, //MAX PEAK TO RIGHT 20 //MAX Elevation to mutate ); //FitnessProportionalSelectionSettings* selectionSettings = new FitnessProportionalSelectionSettings(20,10); SelectionSettings* selectionSettings = new SelectionSettings(20); //BaseSelectionOperation<double> *selectionOperation = new FitnessProportionalSelection<double>(selectionSettings); BaseSelectionOperation<double> *selectionOperation = new RouletteWheelSelection<double>(selectionSettings); //BaseSelectionOperation<double> *selectionOperation = new UniformRandomSelection<double>(selectionSettings); CouplingSettings *couplingSettings = new CouplingSettings(20); //BaseCouplingOperation<double> *couplingOperation = new SimpleCouplingOperation<double>(couplingSettings); BaseCouplingOperation<double> *couplingOperation = new RandomCouplingOperation<double>(couplingSettings); /* BaseCrossoverOperation<double> *crossoverOperation = new MultiValueChromosomeBlendingCrossover<int,double>( builderSettings, chromosomeFactory, MultiValueChromosomeBlendingCrossover<int,double>::INTERPOLATE_RANDOM, MultiValueChromosomeBlendingCrossover<int,double>::RANDOM_AMOUNT, 2 ); */ MultiValueChromosomeNPointCrossoverSettings *crossoverSettings = new MultiValueChromosomeNPointCrossoverSettings(1,MultiValueChromosomeNPointCrossoverSettings::RANDOM_WIDTH,3); BaseCrossoverOperation<double> *crossoverOperation = new SmoothedMultiValueChromosomeNPointCrossover<int,double>(crossoverSettings,builderSettings,chromosomeFactory); //BaseReplacementSettings *replacementSettings = new BaseReplacementSettings(BaseReplacementSettings::replace_offspring_mode::REPLACE_FIXED_NUMBER,20); BaseReplacementSettings *replacementSettings = new BaseReplacementSettings(BaseReplacementSettings::REPLACE_ALL_OFFSPRING,20,0); ReplaceWorstOperation<double> *replacementOperation = new ReplaceWorstOperation<double>(replacementSettings); //ReplaceRandomOperation<double> *replacementOperation = new ReplaceRandomOperation<double>(replacementSettings); BaseFitnessProcessingStrategy<double> *fitnessProcessingStrategy = new MultiThreadedFitnessProcessingStrategy<double>(4); //BaseStoppingCriterion<double> *stoppingCriterion = new MaxGenerationCriterion<double>(100000); CombinedCriterion<double> combinedCriterion; combinedCriterion.add(CombinedCriterion<double>::AND, boost::shared_ptr<BaseStoppingCriterion<double> >(new MaxGenerationCriterion<double>(100000))); combinedCriterion.add(CombinedCriterion<double>::OR, boost::shared_ptr<BaseStoppingCriterion<double> >(new FixPointCriterion<double>(0,1000,1000))); DemoObserver printObserver; BaseGeneticAlgorithm<double> algorithm = BaseGeneticAlgorithm<double>( populationSettings, chromosomeFactory, &combinedCriterion, selectionOperation, couplingOperation, crossoverOperation, replacementOperation, mutationOperation, fitnessProcessingStrategy ); algorithm.registerObserver(&printObserver); algorithm.solve(); BaseChromosome<double>::ptr chromosome = algorithm.getHighestFitnessChromosome(); MultiValueChromosome<int,double>::ptr mvc = boost::dynamic_pointer_cast<MultiValueChromosome<int,double> >(chromosome); printClearScreen(); plot(mvc); std::cout << "ended after " << algorithm.getPopulation().getAge() << " generations" << std::endl; //normally, this is not necessary because we're exiting here anyway, //but for valgrind's satisfaction, we free stuff nonetheless. delete populationSettings; delete chromosomeFactory; delete selectionSettings; delete selectionOperation; delete fitnessProcessingStrategy; delete couplingSettings; delete couplingOperation; delete crossoverSettings; delete crossoverOperation; delete replacementSettings; delete replacementOperation; delete mutationSettings; delete mutationChoosingOperation; delete mutationOperation; } <|endoftext|>
<commit_before>/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * _______ _ * * ( ____ \ ( \ |\ /| * * | ( \/ | ( ( \ / ) * * | (__ | | \ (_) / * * | __) | | \ / * * | ( | | ) ( * * | ) | (____/\ | | * * |/ (_______/ \_/ * * * * * * fly is an awesome c++11 network library. * * * * @author: lichuan * * @qq: 308831759 * * @email: 308831759@qq.com * * @github: https://github.com/lichuan/fly * * @date: 2015-06-10 18:25:08 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #include <cstdarg> #include <unistd.h> #include <sys/stat.h> #include <sys/types.h> #include <thread> #include "fly/base/logger.hpp" namespace fly { namespace base { void Logger::init(LOG_LEVEL level, const std::string &app, const std::string &path) { m_level = level; struct timeval tv; gettimeofday(&tv, NULL); struct tm tm; localtime_r(&tv.tv_sec, &tm); m_year.store(1900 + tm.tm_year, std::memory_order_relaxed); m_month.store(1 + tm.tm_mon, std::memory_order_relaxed); m_day.store(tm.tm_mday, std::memory_order_relaxed); system((std::string("mkdir -p ") + path).c_str()); if(path[path.length() - 1] != '/') { const_cast<std::string&>(path).append("/"); } m_file_name = path + app; m_file_full_name = path + app + ".log"; m_file = fopen(m_file_full_name.c_str(), "rb"); if(m_file != NULL) { int32 fd = fileno(m_file); struct stat st; fstat(fd, &st); struct tm tm_1; localtime_r(&st.st_mtim.tv_sec, &tm_1); uint32 year = 1900 + tm_1.tm_year; uint32 month = 1 + tm_1.tm_mon; uint32 day = tm_1.tm_mday; if(year != m_year.load(std::memory_order_relaxed) || month != m_month.load(std::memory_order_relaxed) || day != m_day.load(std::memory_order_relaxed)) { char file_name[64]; sprintf(file_name, "%s_%d-%02d-%02d.log", m_file_name.c_str(), year, month, day); fclose(m_file); std::rename(m_file_full_name.c_str(), file_name); } else { fclose(m_file); } } m_file = fopen(m_file_full_name.c_str(), "ab"); setvbuf(m_file, NULL, _IOLBF, 1024); } void Logger::_log(uint32 year, uint32 month, uint32 day, const char *format, ...) { if(year != m_year.load(std::memory_order_relaxed) || month != m_month.load(std::memory_order_relaxed) || day != m_day.load(std::memory_order_relaxed)) { while(m_enter_num.load(std::memory_order_relaxed) > 1) { std::this_thread::yield(); }; std::lock_guard<std::mutex> guard(m_mutex); uint32 y = m_year.load(std::memory_order_relaxed); uint32 m = m_month.load(std::memory_order_relaxed); uint32 d = m_day.load(std::memory_order_relaxed); //double-checked if(year != y || month != m || day != d) { char file_name[64]; sprintf(file_name, "%s_%d-%02d-%02d.log", m_file_name.c_str(), y, m, d); fclose(m_file); std::rename(m_file_full_name.c_str(), file_name); m_file = fopen(m_file_full_name.c_str(), "ab"); setvbuf(m_file, NULL, _IOLBF, 1024); m_year.store(year, std::memory_order_relaxed); m_month.store(month, std::memory_order_relaxed); m_day.store(day, std::memory_order_relaxed); } va_list args; va_start(args, format); vfprintf(m_file, format, args); va_end(args); } else { va_list args; va_start(args, format); vfprintf(m_file, format, args); va_end(args); } m_enter_num.fetch_sub(1, std::memory_order_relaxed); /**************** for debug ******************/ va_list args; va_start(args, format); vfprintf(stdout, format, args); va_end(args); /******************* for debug ******************/ } } } <commit_msg>del debug code<commit_after>/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * _______ _ * * ( ____ \ ( \ |\ /| * * | ( \/ | ( ( \ / ) * * | (__ | | \ (_) / * * | __) | | \ / * * | ( | | ) ( * * | ) | (____/\ | | * * |/ (_______/ \_/ * * * * * * fly is an awesome c++11 network library. * * * * @author: lichuan * * @qq: 308831759 * * @email: 308831759@qq.com * * @github: https://github.com/lichuan/fly * * @date: 2015-06-10 18:25:08 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #include <cstdarg> #include <unistd.h> #include <sys/stat.h> #include <sys/types.h> #include <thread> #include "fly/base/logger.hpp" namespace fly { namespace base { void Logger::init(LOG_LEVEL level, const std::string &app, const std::string &path) { m_level = level; struct timeval tv; gettimeofday(&tv, NULL); struct tm tm; localtime_r(&tv.tv_sec, &tm); m_year.store(1900 + tm.tm_year, std::memory_order_relaxed); m_month.store(1 + tm.tm_mon, std::memory_order_relaxed); m_day.store(tm.tm_mday, std::memory_order_relaxed); system((std::string("mkdir -p ") + path).c_str()); if(path[path.length() - 1] != '/') { const_cast<std::string&>(path).append("/"); } m_file_name = path + app; m_file_full_name = path + app + ".log"; m_file = fopen(m_file_full_name.c_str(), "rb"); if(m_file != NULL) { int32 fd = fileno(m_file); struct stat st; fstat(fd, &st); struct tm tm_1; localtime_r(&st.st_mtim.tv_sec, &tm_1); uint32 year = 1900 + tm_1.tm_year; uint32 month = 1 + tm_1.tm_mon; uint32 day = tm_1.tm_mday; if(year != m_year.load(std::memory_order_relaxed) || month != m_month.load(std::memory_order_relaxed) || day != m_day.load(std::memory_order_relaxed)) { char file_name[64]; sprintf(file_name, "%s_%d-%02d-%02d.log", m_file_name.c_str(), year, month, day); fclose(m_file); std::rename(m_file_full_name.c_str(), file_name); } else { fclose(m_file); } } m_file = fopen(m_file_full_name.c_str(), "ab"); setvbuf(m_file, NULL, _IOLBF, 1024); } void Logger::_log(uint32 year, uint32 month, uint32 day, const char *format, ...) { if(year != m_year.load(std::memory_order_relaxed) || month != m_month.load(std::memory_order_relaxed) || day != m_day.load(std::memory_order_relaxed)) { while(m_enter_num.load(std::memory_order_relaxed) > 1) { std::this_thread::yield(); }; std::lock_guard<std::mutex> guard(m_mutex); uint32 y = m_year.load(std::memory_order_relaxed); uint32 m = m_month.load(std::memory_order_relaxed); uint32 d = m_day.load(std::memory_order_relaxed); //double-checked if(year != y || month != m || day != d) { char file_name[64]; sprintf(file_name, "%s_%d-%02d-%02d.log", m_file_name.c_str(), y, m, d); fclose(m_file); std::rename(m_file_full_name.c_str(), file_name); m_file = fopen(m_file_full_name.c_str(), "ab"); setvbuf(m_file, NULL, _IOLBF, 1024); m_year.store(year, std::memory_order_relaxed); m_month.store(month, std::memory_order_relaxed); m_day.store(day, std::memory_order_relaxed); } va_list args; va_start(args, format); vfprintf(m_file, format, args); va_end(args); } else { va_list args; va_start(args, format); vfprintf(m_file, format, args); va_end(args); } m_enter_num.fetch_sub(1, std::memory_order_relaxed); } } } <|endoftext|>
<commit_before>struct State { }; {{ GENERATED_CODE }} void evaluate(Context ctx) { if (!isInputDirty<input_IN>(ctx)) return; auto line = getValue<input_IN>(ctx); TimeMs tNow = transactionTime(); XOD_DEBUG_SERIAL.print(F("+XOD:")); XOD_DEBUG_SERIAL.print(tNow); XOD_DEBUG_SERIAL.print(':'); XOD_DEBUG_SERIAL.print(getNodeId(ctx)); XOD_DEBUG_SERIAL.print(':'); for (auto it = line.iterate(); it; ++it) XOD_DEBUG_SERIAL.print((char)*it); XOD_DEBUG_SERIAL.print('\r'); XOD_DEBUG_SERIAL.print('\n'); XOD_DEBUG_SERIAL.flush(); } <commit_msg>feat(stdlib): make `watch` node display errors<commit_after> #pragma XOD error_catch enable struct State { }; {{ GENERATED_CODE }} void evaluate(Context ctx) { if (!isInputDirty<input_IN>(ctx)) return; auto err = getError<input_IN>(ctx); auto line = getValue<input_IN>(ctx); TimeMs tNow = transactionTime(); XOD_DEBUG_SERIAL.print(F("+XOD:")); XOD_DEBUG_SERIAL.print(tNow); XOD_DEBUG_SERIAL.print(':'); XOD_DEBUG_SERIAL.print(getNodeId(ctx)); XOD_DEBUG_SERIAL.print(':'); if (err) { XOD_DEBUG_SERIAL.print('E'); XOD_DEBUG_SERIAL.print((int)err); } else { for (auto it = line.iterate(); it; ++it) XOD_DEBUG_SERIAL.print((char)*it); } XOD_DEBUG_SERIAL.print('\r'); XOD_DEBUG_SERIAL.print('\n'); XOD_DEBUG_SERIAL.flush(); } <|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993 - 2005 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named LICENSE that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* interface header */ #include "PlayerInfo.h" /* system implementation headers */ #include <errno.h> #include <string> /* implementation-specific common headers */ #include "TextUtils.h" WordFilter PlayerInfo::serverSpoofingFilter; TimeKeeper PlayerInfo::now = TimeKeeper::getCurrent(); bool PlayerInfo::callSignFiltering = false; WordFilter *PlayerInfo::filterData = NULL; bool PlayerInfo::simpleFiltering = true; PlayerInfo::PlayerInfo(int _playerIndex) : playerIndex(_playerIndex), state(PlayerInLimbo), flag(-1), spamWarns(0), lastMsgTime(now), paused(false), pausedSince(TimeKeeper::getNullTime()), autopilot(false), tracker(0) { notResponding = false; memset(email, 0, EmailLen); memset(callSign, 0, CallSignLen); memset(token, 0, TokenLen); memset(clientVersion, 0, VersionLen); } void PlayerInfo::setFilterParameters(bool _callSignFiltering, WordFilter &_filterData, bool _simpleFiltering) { callSignFiltering = _callSignFiltering; filterData = &_filterData; simpleFiltering = _simpleFiltering; } void PlayerInfo::resetPlayer(bool ctf) { wasRabbit = false; lastupdate = now; lastmsg = now; replayState = ReplayNone; playedEarly = false; restartOnBase = ctf; } void PlayerInfo::setRestartOnBase(bool on) { restartOnBase = on; } bool PlayerInfo::shouldRestartAtBase() { return restartOnBase; } void PlayerInfo::signingOn() { state = PlayerDead; } void PlayerInfo::setAlive() { state = PlayerAlive; paused = false; flag = -1; } void PlayerInfo::setDead() { state = PlayerDead; } void *PlayerInfo::packUpdate(void *buf) { buf = nboPackUShort(buf, uint16_t(type)); buf = nboPackUShort(buf, uint16_t(team)); return buf; } void *PlayerInfo::packId(void *buf) { buf = nboPackString(buf, callSign, CallSignLen); buf = nboPackString(buf, email, EmailLen); return buf; } bool PlayerInfo::unpackEnter(void *buf, uint16_t &rejectCode, char *rejectMsg) { // data: type, team, name, email uint16_t _type; int16_t _team; buf = nboUnpackUShort(buf, _type); buf = nboUnpackShort(buf, _team); type = PlayerType(_type); team = TeamColor(_team); buf = nboUnpackString(buf, callSign, CallSignLen); buf = nboUnpackString(buf, email, EmailLen); buf = nboUnpackString(buf, token, TokenLen); buf = nboUnpackString(buf, clientVersion, VersionLen); cleanEMail(); DEBUG2("Player %s [%d] sent version string: %s\n", callSign, playerIndex, clientVersion); // spoof filter holds "SERVER" for robust name comparisons if (serverSpoofingFilter.wordCount() == 0) { serverSpoofingFilter.addToFilter("SERVER", ""); } if (!isCallSignReadable()) { DEBUG2("rejecting unreadable callsign: %s\n", callSign); rejectCode = RejectBadCallsign; strcpy(rejectMsg, errorString.c_str()); return false; } // no spoofing the server name if (serverSpoofingFilter.filter(callSign)) { rejectCode = RejectRepeatCallsign; strcpy(rejectMsg, "The callsign specified is already in use."); return false; } if (!isEMailReadable()) { DEBUG2("rejecting unreadable player email: %s (%s)\n", callSign, email); rejectCode = RejectBadEmail; strcpy(rejectMsg, "The e-mail was rejected. Try a different e-mail."); return false; } // make sure the callsign is not obscene/filtered if (callSignFiltering) { DEBUG2("checking callsign: %s\n",callSign); char cs[CallSignLen]; memcpy(cs, callSign, sizeof(char) * CallSignLen); if (filterData->filter(cs, simpleFiltering)) { rejectCode = RejectBadCallsign; strcpy(rejectMsg, "The callsign was rejected. Try a different callsign."); return false; } } // make sure the email is not obscene/filtered if (callSignFiltering) { DEBUG2("checking email: %s\n", email); char em[EmailLen]; memcpy(em, email, sizeof(char) * EmailLen); if (filterData->filter(em, simpleFiltering)) { rejectCode = RejectBadEmail; strcpy(rejectMsg, "The e-mail was rejected. Try a different e-mail."); return false; } } // # not allowed in first position because used in /kick /ban #slot char cs[CallSignLen]; memcpy(cs, callSign, sizeof(char) * CallSignLen); if (cs[0] == '#') { rejectCode = RejectBadCallsign; strcpy(rejectMsg, "The callsign was rejected. Not allowed starting in #"); return false; } return true; } const char *PlayerInfo::getCallSign() const { return callSign; } bool PlayerInfo::isCallSignReadable() { // callsign readability filter, make sure there are more alphanum than non // keep a count of alpha-numerics int callsignlen = (int)strlen(callSign); // reject less than 3 characters if (callsignlen < 3) { errorString = "Callsigns must be at least 3 characters."; return false; } // reject trailing space if (isspace(callSign[strlen(callSign) - 1])) { errorString = "Trailing spaces are not allowed in callsigns."; return false; } // start with true to reject leading space bool lastWasSpace = true; int alnumCount = 0; const char *sp = callSign; do { // reject sequential spaces if (lastWasSpace && isspace(*sp)) { errorString = "Leading or consecutive spaces are not allowed in callsigns."; return false; } // reject ' and " and any nonprintable if ((*sp == '\'') || (*sp == '"') || ((unsigned)*sp > 0x7f) || !isprint(*sp)) { errorString = "Non-printable characters and quotes are not allowed in callsigns."; return false; } if (isspace(*sp)) { // only space is valid, not tab etc. if (*sp != ' ') { errorString = "Invalid whitespace in callsign."; return false; } lastWasSpace = true; } else { lastWasSpace = false; if (isalnum(*sp)) alnumCount++; } } while (*++sp); bool readable = ((float)alnumCount / (float)callsignlen) > 0.5f; if (!readable) errorString = "Callsign rejected. Please use mostly letters and numbers."; return readable; } const char *PlayerInfo::getEMail() const { return email; } void PlayerInfo::cleanEMail() { // strip leading whitespace from email char *sp = email; char *tp = sp; while (isspace(*sp)) sp++; // strip any non-printable characters and ' and " from email do { if (isprint(*sp) && (*sp != '\'') && (*sp != '"')) { *tp++ = *sp; } } while (*++sp); *tp = *sp; // strip trailing whitespace from email while (isspace(*--tp)) { *tp=0; } } bool PlayerInfo::isEMailReadable() { // email/"team" readability filter, make sure there are more // alphanum than non int emailAlnumCount = 0; char *sp = email; do { if (isalnum(*sp)) { emailAlnumCount++; } } while (*++sp); int emaillen = (int)strlen(email); return (emaillen <= 4) || (((float)emailAlnumCount / (float)emaillen) > 0.5); } const char *PlayerInfo::getToken() const { return token; } void PlayerInfo::clearToken() { token[0] = '\0'; } void *PlayerInfo::packVirtualFlagCapture(void *buf) { buf = nboPackUShort(buf, uint16_t(int(team) - 1)); buf = nboPackUShort(buf, uint16_t(1 + (int(team) % 4))); return buf; } bool PlayerInfo::isTeam(TeamColor _team) const { return team == _team; } bool PlayerInfo::isObserver() const { return team == ObserverTeam; } TeamColor PlayerInfo::getTeam() { return team; } void PlayerInfo::setTeam(TeamColor _team) { team = _team; } void PlayerInfo::wasARabbit() { team = RogueTeam; wasRabbit = true; } void PlayerInfo::wasNotARabbit() { wasRabbit = false; } void PlayerInfo::resetFlag() { flag = -1; lastFlagDropTime = now; } void PlayerInfo::setFlag(int _flag) { flag = _flag; } bool PlayerInfo::isFlagTransitSafe() { return now - lastFlagDropTime >= 2.0f; } const char *PlayerInfo::getClientVersion() { return clientVersion; } std::string PlayerInfo::getIdleStat() { std::string reply; if ((state > PlayerInLimbo) && (team != ObserverTeam)) { reply = TextUtils::format("%s\t: %4ds", callSign, int(now - lastupdate)); if (paused) { reply += TextUtils::format(" paused %4ds", int(now - pausedSince)); } } return reply; } bool PlayerInfo::canBeRabbit(bool relaxing) { if (paused || notResponding || (team == ObserverTeam)) return false; return relaxing ? (state > PlayerInLimbo) : (state == PlayerAlive); } void PlayerInfo::setPaused(bool _paused) { paused = _paused; pausedSince = now; } void PlayerInfo::setAutoPilot(bool _autopilot) { autopilot = _autopilot; } bool PlayerInfo::isTooMuchIdling(float kickThresh) { bool idling = false; if ((state > PlayerInLimbo) && (team != ObserverTeam)) { int idletime = (int)(now - lastupdate); int pausetime = 0; if (paused && now - pausedSince > idletime) pausetime = (int)(now - pausedSince); idletime = idletime > pausetime ? idletime : pausetime; if (idletime > (now - lastmsg < kickThresh ? 3 * kickThresh : kickThresh)) { DEBUG1("Kicking player %s [%d] idle %d\n", callSign, playerIndex, idletime); idling = true; } } return idling; } bool PlayerInfo::hasStartedToNotRespond() { float notRespondingTime = BZDB.eval(StateDatabase::BZDB_NOTRESPONDINGTIME); bool startingToNotRespond = false; if (state > PlayerInLimbo) { bool oldnr = notResponding; notResponding = (now - lastupdate) > notRespondingTime; if (!oldnr && notResponding) startingToNotRespond = true; } return startingToNotRespond; } void PlayerInfo::hasSent(char message[]) { lastmsg = now; DEBUG1("Player %s [%d]: %s\n", callSign, playerIndex, message); } bool PlayerInfo::hasPlayedEarly() { bool returnValue = playedEarly; playedEarly = false; return returnValue; } void PlayerInfo::setPlayedEarly(bool early) { playedEarly = early; } void PlayerInfo::updateIdleTime() { lastupdate = now; } void PlayerInfo::setReplayState(PlayerReplayState _state) { replayState = _state; } PlayerReplayState PlayerInfo::getReplayState() { return replayState; } void PlayerInfo::setTrackerID(unsigned short int t) { tracker = t; } unsigned short int PlayerInfo::trackerID() { return tracker; } void PlayerInfo::setCurrentTime(TimeKeeper tm) { now = tm; } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>rephrase error message<commit_after>/* bzflag * Copyright (c) 1993 - 2005 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named LICENSE that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* interface header */ #include "PlayerInfo.h" /* system implementation headers */ #include <errno.h> #include <string> /* implementation-specific common headers */ #include "TextUtils.h" WordFilter PlayerInfo::serverSpoofingFilter; TimeKeeper PlayerInfo::now = TimeKeeper::getCurrent(); bool PlayerInfo::callSignFiltering = false; WordFilter *PlayerInfo::filterData = NULL; bool PlayerInfo::simpleFiltering = true; PlayerInfo::PlayerInfo(int _playerIndex) : playerIndex(_playerIndex), state(PlayerInLimbo), flag(-1), spamWarns(0), lastMsgTime(now), paused(false), pausedSince(TimeKeeper::getNullTime()), autopilot(false), tracker(0) { notResponding = false; memset(email, 0, EmailLen); memset(callSign, 0, CallSignLen); memset(token, 0, TokenLen); memset(clientVersion, 0, VersionLen); } void PlayerInfo::setFilterParameters(bool _callSignFiltering, WordFilter &_filterData, bool _simpleFiltering) { callSignFiltering = _callSignFiltering; filterData = &_filterData; simpleFiltering = _simpleFiltering; } void PlayerInfo::resetPlayer(bool ctf) { wasRabbit = false; lastupdate = now; lastmsg = now; replayState = ReplayNone; playedEarly = false; restartOnBase = ctf; } void PlayerInfo::setRestartOnBase(bool on) { restartOnBase = on; } bool PlayerInfo::shouldRestartAtBase() { return restartOnBase; } void PlayerInfo::signingOn() { state = PlayerDead; } void PlayerInfo::setAlive() { state = PlayerAlive; paused = false; flag = -1; } void PlayerInfo::setDead() { state = PlayerDead; } void *PlayerInfo::packUpdate(void *buf) { buf = nboPackUShort(buf, uint16_t(type)); buf = nboPackUShort(buf, uint16_t(team)); return buf; } void *PlayerInfo::packId(void *buf) { buf = nboPackString(buf, callSign, CallSignLen); buf = nboPackString(buf, email, EmailLen); return buf; } bool PlayerInfo::unpackEnter(void *buf, uint16_t &rejectCode, char *rejectMsg) { // data: type, team, name, email uint16_t _type; int16_t _team; buf = nboUnpackUShort(buf, _type); buf = nboUnpackShort(buf, _team); type = PlayerType(_type); team = TeamColor(_team); buf = nboUnpackString(buf, callSign, CallSignLen); buf = nboUnpackString(buf, email, EmailLen); buf = nboUnpackString(buf, token, TokenLen); buf = nboUnpackString(buf, clientVersion, VersionLen); cleanEMail(); DEBUG2("Player %s [%d] sent version string: %s\n", callSign, playerIndex, clientVersion); // spoof filter holds "SERVER" for robust name comparisons if (serverSpoofingFilter.wordCount() == 0) { serverSpoofingFilter.addToFilter("SERVER", ""); } if (!isCallSignReadable()) { DEBUG2("rejecting unreadable callsign: %s\n", callSign); rejectCode = RejectBadCallsign; strcpy(rejectMsg, errorString.c_str()); return false; } // no spoofing the server name if (serverSpoofingFilter.filter(callSign)) { rejectCode = RejectRepeatCallsign; strcpy(rejectMsg, "The callsign specified is already in use."); return false; } if (!isEMailReadable()) { DEBUG2("rejecting unreadable player email: %s (%s)\n", callSign, email); rejectCode = RejectBadEmail; strcpy(rejectMsg, "The e-mail was rejected. Try a different e-mail."); return false; } // make sure the callsign is not obscene/filtered if (callSignFiltering) { DEBUG2("checking callsign: %s\n",callSign); char cs[CallSignLen]; memcpy(cs, callSign, sizeof(char) * CallSignLen); if (filterData->filter(cs, simpleFiltering)) { rejectCode = RejectBadCallsign; strcpy(rejectMsg, "The callsign was rejected. Try a different callsign."); return false; } } // make sure the email is not obscene/filtered if (callSignFiltering) { DEBUG2("checking email: %s\n", email); char em[EmailLen]; memcpy(em, email, sizeof(char) * EmailLen); if (filterData->filter(em, simpleFiltering)) { rejectCode = RejectBadEmail; strcpy(rejectMsg, "The e-mail was rejected. Try a different e-mail."); return false; } } // # not allowed in first position because used in /kick /ban #slot char cs[CallSignLen]; memcpy(cs, callSign, sizeof(char) * CallSignLen); if (cs[0] == '#') { rejectCode = RejectBadCallsign; strcpy(rejectMsg, "The callsign was rejected. Callsigns are not allowed to start with #."); return false; } return true; } const char *PlayerInfo::getCallSign() const { return callSign; } bool PlayerInfo::isCallSignReadable() { // callsign readability filter, make sure there are more alphanum than non // keep a count of alpha-numerics int callsignlen = (int)strlen(callSign); // reject less than 3 characters if (callsignlen < 3) { errorString = "Callsigns must be at least 3 characters."; return false; } // reject trailing space if (isspace(callSign[strlen(callSign) - 1])) { errorString = "Trailing spaces are not allowed in callsigns."; return false; } // start with true to reject leading space bool lastWasSpace = true; int alnumCount = 0; const char *sp = callSign; do { // reject sequential spaces if (lastWasSpace && isspace(*sp)) { errorString = "Leading or consecutive spaces are not allowed in callsigns."; return false; } // reject ' and " and any nonprintable if ((*sp == '\'') || (*sp == '"') || ((unsigned)*sp > 0x7f) || !isprint(*sp)) { errorString = "Non-printable characters and quotes are not allowed in callsigns."; return false; } if (isspace(*sp)) { // only space is valid, not tab etc. if (*sp != ' ') { errorString = "Invalid whitespace in callsign."; return false; } lastWasSpace = true; } else { lastWasSpace = false; if (isalnum(*sp)) alnumCount++; } } while (*++sp); bool readable = ((float)alnumCount / (float)callsignlen) > 0.5f; if (!readable) errorString = "Callsign rejected. Please use mostly letters and numbers."; return readable; } const char *PlayerInfo::getEMail() const { return email; } void PlayerInfo::cleanEMail() { // strip leading whitespace from email char *sp = email; char *tp = sp; while (isspace(*sp)) sp++; // strip any non-printable characters and ' and " from email do { if (isprint(*sp) && (*sp != '\'') && (*sp != '"')) { *tp++ = *sp; } } while (*++sp); *tp = *sp; // strip trailing whitespace from email while (isspace(*--tp)) { *tp=0; } } bool PlayerInfo::isEMailReadable() { // email/"team" readability filter, make sure there are more // alphanum than non int emailAlnumCount = 0; char *sp = email; do { if (isalnum(*sp)) { emailAlnumCount++; } } while (*++sp); int emaillen = (int)strlen(email); return (emaillen <= 4) || (((float)emailAlnumCount / (float)emaillen) > 0.5); } const char *PlayerInfo::getToken() const { return token; } void PlayerInfo::clearToken() { token[0] = '\0'; } void *PlayerInfo::packVirtualFlagCapture(void *buf) { buf = nboPackUShort(buf, uint16_t(int(team) - 1)); buf = nboPackUShort(buf, uint16_t(1 + (int(team) % 4))); return buf; } bool PlayerInfo::isTeam(TeamColor _team) const { return team == _team; } bool PlayerInfo::isObserver() const { return team == ObserverTeam; } TeamColor PlayerInfo::getTeam() { return team; } void PlayerInfo::setTeam(TeamColor _team) { team = _team; } void PlayerInfo::wasARabbit() { team = RogueTeam; wasRabbit = true; } void PlayerInfo::wasNotARabbit() { wasRabbit = false; } void PlayerInfo::resetFlag() { flag = -1; lastFlagDropTime = now; } void PlayerInfo::setFlag(int _flag) { flag = _flag; } bool PlayerInfo::isFlagTransitSafe() { return now - lastFlagDropTime >= 2.0f; } const char *PlayerInfo::getClientVersion() { return clientVersion; } std::string PlayerInfo::getIdleStat() { std::string reply; if ((state > PlayerInLimbo) && (team != ObserverTeam)) { reply = TextUtils::format("%s\t: %4ds", callSign, int(now - lastupdate)); if (paused) { reply += TextUtils::format(" paused %4ds", int(now - pausedSince)); } } return reply; } bool PlayerInfo::canBeRabbit(bool relaxing) { if (paused || notResponding || (team == ObserverTeam)) return false; return relaxing ? (state > PlayerInLimbo) : (state == PlayerAlive); } void PlayerInfo::setPaused(bool _paused) { paused = _paused; pausedSince = now; } void PlayerInfo::setAutoPilot(bool _autopilot) { autopilot = _autopilot; } bool PlayerInfo::isTooMuchIdling(float kickThresh) { bool idling = false; if ((state > PlayerInLimbo) && (team != ObserverTeam)) { int idletime = (int)(now - lastupdate); int pausetime = 0; if (paused && now - pausedSince > idletime) pausetime = (int)(now - pausedSince); idletime = idletime > pausetime ? idletime : pausetime; if (idletime > (now - lastmsg < kickThresh ? 3 * kickThresh : kickThresh)) { DEBUG1("Kicking player %s [%d] idle %d\n", callSign, playerIndex, idletime); idling = true; } } return idling; } bool PlayerInfo::hasStartedToNotRespond() { float notRespondingTime = BZDB.eval(StateDatabase::BZDB_NOTRESPONDINGTIME); bool startingToNotRespond = false; if (state > PlayerInLimbo) { bool oldnr = notResponding; notResponding = (now - lastupdate) > notRespondingTime; if (!oldnr && notResponding) startingToNotRespond = true; } return startingToNotRespond; } void PlayerInfo::hasSent(char message[]) { lastmsg = now; DEBUG1("Player %s [%d]: %s\n", callSign, playerIndex, message); } bool PlayerInfo::hasPlayedEarly() { bool returnValue = playedEarly; playedEarly = false; return returnValue; } void PlayerInfo::setPlayedEarly(bool early) { playedEarly = early; } void PlayerInfo::updateIdleTime() { lastupdate = now; } void PlayerInfo::setReplayState(PlayerReplayState _state) { replayState = _state; } PlayerReplayState PlayerInfo::getReplayState() { return replayState; } void PlayerInfo::setTrackerID(unsigned short int t) { tracker = t; } unsigned short int PlayerInfo::trackerID() { return tracker; } void PlayerInfo::setCurrentTime(TimeKeeper tm) { now = tm; } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before> // // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // Interface header. #include "edfenvironmentshader.h" // appleseed.renderer headers. #include "renderer/global/globallogger.h" #include "renderer/kernel/shading/shadingresult.h" #include "renderer/modeling/environmentedf/environmentedf.h" #include "renderer/modeling/environmentshader/environmentshader.h" #include "renderer/modeling/project/project.h" #include "renderer/modeling/scene/containers.h" #include "renderer/modeling/scene/scene.h" #include "renderer/utility/paramarray.h" // appleseed.foundation headers. #include "foundation/math/vector.h" #include "foundation/image/colorspace.h" #include "foundation/utility/containers/dictionary.h" #include "foundation/utility/containers/specializedarrays.h" // Standard headers. #include <string> // Forward declarations. namespace renderer { class InputEvaluator; } using namespace foundation; using namespace std; namespace renderer { namespace { // // EDF-based environment shader. // const char* Model = "edf_environment_shader"; class EDFEnvironmentShader : public EnvironmentShader { public: EDFEnvironmentShader( const char* name, const ParamArray& params) : EnvironmentShader(name, params) , m_env_edf(0) { } virtual void release() OVERRIDE { delete this; } virtual const char* get_model() const OVERRIDE { return Model; } virtual bool on_frame_begin(const Project& project) OVERRIDE { if (!EnvironmentShader::on_frame_begin(project)) return false; const string name = m_params.get_required<string>("environment_edf", ""); m_env_edf = project.get_scene()->environment_edfs().get_by_name(name.c_str()); if (m_env_edf == 0) { RENDERER_LOG_ERROR( "while preparing environment shader \"%s\": " "cannot find environment edf \"%s\".", get_path().c_str(), name.c_str()); return false; } return true; } virtual void evaluate( InputEvaluator& input_evaluator, const Vector3d& direction, ShadingResult& shading_result) const OVERRIDE { shading_result.m_color_space = ColorSpaceSpectral; shading_result.m_aovs.set(0.0f); shading_result.m_alpha.set(1.0f); m_env_edf->evaluate( input_evaluator, direction, shading_result.m_color); } private: EnvironmentEDF* m_env_edf; }; } // // EDFEnvironmentShaderFactory class implementation. // const char* EDFEnvironmentShaderFactory::get_model() const { return Model; } const char* EDFEnvironmentShaderFactory::get_human_readable_model() const { return "Environment EDF-Based Environment Shader"; } DictionaryArray EDFEnvironmentShaderFactory::get_input_metadata() const { DictionaryArray metadata; metadata.push_back( Dictionary() .insert("name", "environment_edf") .insert("label", "Environment EDF") .insert("type", "entity") .insert("entity_types", Dictionary() .insert("environment_edf", "Environment EDFs")) .insert("use", "required") .insert("default", "")); return metadata; } auto_release_ptr<EnvironmentShader> EDFEnvironmentShaderFactory::create( const char* name, const ParamArray& params) const { return auto_release_ptr<EnvironmentShader>( new EDFEnvironmentShader(name, params)); } } // namespace renderer <commit_msg>it is now possible to select an alpha (opacity) value for the EDF-based environment shader (default is 1.0 == fully opaque, as before).<commit_after> // // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // Interface header. #include "edfenvironmentshader.h" // appleseed.renderer headers. #include "renderer/global/globallogger.h" #include "renderer/kernel/shading/shadingresult.h" #include "renderer/modeling/environmentedf/environmentedf.h" #include "renderer/modeling/environmentshader/environmentshader.h" #include "renderer/modeling/project/project.h" #include "renderer/modeling/scene/containers.h" #include "renderer/modeling/scene/scene.h" #include "renderer/utility/paramarray.h" // appleseed.foundation headers. #include "foundation/math/vector.h" #include "foundation/image/colorspace.h" #include "foundation/utility/containers/dictionary.h" #include "foundation/utility/containers/specializedarrays.h" // Standard headers. #include <string> // Forward declarations. namespace renderer { class InputEvaluator; } using namespace foundation; using namespace std; namespace renderer { namespace { // // EDF-based environment shader. // const char* Model = "edf_environment_shader"; class EDFEnvironmentShader : public EnvironmentShader { public: EDFEnvironmentShader( const char* name, const ParamArray& params) : EnvironmentShader(name, params) , m_env_edf(0) { m_inputs.declare("alpha_value", InputFormatScalar, "1.0"); } virtual void release() OVERRIDE { delete this; } virtual const char* get_model() const OVERRIDE { return Model; } virtual bool on_frame_begin(const Project& project) OVERRIDE { if (!EnvironmentShader::on_frame_begin(project)) return false; // Bind the environment EDF to this environment shader. const string name = m_params.get_required<string>("environment_edf", ""); m_env_edf = project.get_scene()->environment_edfs().get_by_name(name.c_str()); if (m_env_edf == 0) { RENDERER_LOG_ERROR( "while preparing environment shader \"%s\": " "cannot find environment edf \"%s\".", get_path().c_str(), name.c_str()); return false; } // Evaluate and store alpha value. InputValues uniform_values; m_inputs.evaluate_uniforms(&uniform_values); m_alpha_value = static_cast<float>(uniform_values.m_alpha_value); return true; } virtual void evaluate( InputEvaluator& input_evaluator, const Vector3d& direction, ShadingResult& shading_result) const OVERRIDE { shading_result.m_color_space = ColorSpaceSpectral; shading_result.m_aovs.set(0.0f); shading_result.m_alpha.set(m_alpha_value); m_env_edf->evaluate( input_evaluator, direction, shading_result.m_color); } private: DECLARE_INPUT_VALUES(InputValues) { double m_alpha_value; }; EnvironmentEDF* m_env_edf; float m_alpha_value; }; } // // EDFEnvironmentShaderFactory class implementation. // const char* EDFEnvironmentShaderFactory::get_model() const { return Model; } const char* EDFEnvironmentShaderFactory::get_human_readable_model() const { return "Environment EDF-Based Environment Shader"; } DictionaryArray EDFEnvironmentShaderFactory::get_input_metadata() const { DictionaryArray metadata; metadata.push_back( Dictionary() .insert("name", "environment_edf") .insert("label", "Environment EDF") .insert("type", "entity") .insert("entity_types", Dictionary() .insert("environment_edf", "Environment EDFs")) .insert("use", "required") .insert("default", "")); metadata.push_back( Dictionary() .insert("name", "alpha_value") .insert("label", "Alpha Value") .insert("type", "numeric") .insert("min_value", "0.0") .insert("max_value", "1.0") .insert("use", "optional") .insert("default", "1.0")); return metadata; } auto_release_ptr<EnvironmentShader> EDFEnvironmentShaderFactory::create( const char* name, const ParamArray& params) const { return auto_release_ptr<EnvironmentShader>( new EDFEnvironmentShader(name, params)); } } // namespace renderer <|endoftext|>
<commit_before>#include <agency/future.hpp> #include <agency/new_executor_traits.hpp> #include <agency/coordinate.hpp> #include <iostream> #include <cassert> #include "test_executors.hpp" template<class Executor> void test() { using executor_type = Executor; { executor_type exec; size_t n = 100; int addend = 13; auto futures = std::make_tuple(agency::detail::make_ready_future<int>(addend)); std::atomic<int> counter(n); int current_sum = 0; int result = 0; std::mutex mut; std::future<int> fut = agency::new_executor_traits<executor_type>::template when_all_execute_and_select<0>(exec, [&](size_t idx, int& addend, int& current_sum) { mut.lock(); current_sum += addend; mut.unlock(); auto prev_counter_value = counter.fetch_sub(1); // the last agent stores the current_sum to the result if(prev_counter_value == 1) { result = current_sum; } }, n, futures, current_sum); auto got = fut.get(); assert(got == 13); assert(result == addend * n); assert(exec.valid()); } } int main() { using namespace test_executors; test<empty_executor>(); test<single_agent_when_all_execute_and_select_executor>(); test<multi_agent_when_all_execute_and_select_executor>(); test<multi_agent_when_all_execute_and_select_with_shared_inits_executor>(); test<when_all_executor>(); test<multi_agent_execute_returning_user_defined_container_executor>(); test<multi_agent_execute_returning_default_container_executor>(); test<multi_agent_execute_returning_void_executor>(); test<multi_agent_async_execute_returning_user_defined_container_executor>(); test<multi_agent_async_execute_returning_default_container_executor>(); std::cout << "OK" << std::endl; } <commit_msg>Test multi_agent_async_execute_returning_void_executor with test_multi_agent_when_all_execute_and_select_with_shared_inits.cpp<commit_after>#include <agency/future.hpp> #include <agency/new_executor_traits.hpp> #include <agency/coordinate.hpp> #include <iostream> #include <cassert> #include "test_executors.hpp" template<class Executor> void test() { using executor_type = Executor; { executor_type exec; size_t n = 100; int addend = 13; auto futures = std::make_tuple(agency::detail::make_ready_future<int>(addend)); std::atomic<int> counter(n); int current_sum = 0; int result = 0; std::mutex mut; std::future<int> fut = agency::new_executor_traits<executor_type>::template when_all_execute_and_select<0>(exec, [&](size_t idx, int& addend, int& current_sum) { mut.lock(); current_sum += addend; mut.unlock(); auto prev_counter_value = counter.fetch_sub(1); // the last agent stores the current_sum to the result if(prev_counter_value == 1) { result = current_sum; } }, n, futures, current_sum); auto got = fut.get(); assert(got == 13); assert(result == addend * n); assert(exec.valid()); } } int main() { using namespace test_executors; test<empty_executor>(); test<single_agent_when_all_execute_and_select_executor>(); test<multi_agent_when_all_execute_and_select_executor>(); test<multi_agent_when_all_execute_and_select_with_shared_inits_executor>(); test<when_all_executor>(); test<multi_agent_execute_returning_user_defined_container_executor>(); test<multi_agent_execute_returning_default_container_executor>(); test<multi_agent_execute_returning_void_executor>(); test<multi_agent_async_execute_returning_user_defined_container_executor>(); test<multi_agent_async_execute_returning_default_container_executor>(); test<multi_agent_async_execute_returning_void_executor>(); std::cout << "OK" << std::endl; } <|endoftext|>
<commit_before><commit_msg>Fix build.<commit_after><|endoftext|>
<commit_before>#include <opencv/cv.h> #include <opencv/highgui.h> #include <iostream> using namespace std; using namespace cv; #define VIDEO_DEVICE_NO 1 #define AREA_LIMIT 1500 #define ARC_LENGTH_LIMIT 30000 #define TRACE_LENGTH_LIMIT_LOW 50 #define TRACE_LENGTH_LIMIT_HIGH 300 #define PACE_THRESHOLD 30 #define START_DRAW 5 #define EPS 1e-8 #define DEBUG 1 //Algorithm libs float SqrDis (Point &a, Point &b) { return (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y); } Point PolyCenter (vector<Point> &vt) { Point ret(0.0, 0.0); #if DEBUG cout << "Num of Points = " << vt.size() << endl; #endif for (int i = 0; i < vt.size(); i++) { ret.x += vt[i].x; ret.y += vt[i].y; #if DEBUG cout << vt[i] << " "; #endif } #if DEBUG cout << endl; #endif if (vt.size() > 0) { ret.x /= vt.size(); ret.y /= vt.size(); } return ret; } class Analyser { public: Analyser() { count = 0; } ~Analyser() {} void clear() { count = 0; gesture.clear(); } void judge(Point p) { if (count == 0) cur_point = p; else { //float d = (p.x - cur_point.x) * (p.x - cur_point.x) + (p.y - cur_point.y) * (p.y - cur_point.y); float d = SqrDis(p, cur_point); if (d > TRACE_LENGTH_LIMIT_LOW * TRACE_LENGTH_LIMIT_LOW && d < TRACE_LENGTH_LIMIT_HIGH * TRACE_LENGTH_LIMIT_HIGH) { if (fabs(p.x - cur_point.x) < EPS) { if (p.y < cur_point.y) gesture.push_back(NORTH); else gesture.push_back(SOUTH); } else { float slope = (cur_point.y - p.y) / (cur_point.x - p.x); if (cur_point.y > p.y) { if (slope > 1 || slope < -1) gesture.push_back(NORTH); else if (cur_point.x > p.x) gesture.push_back(WEST); else gesture.push_back(EAST); } else { if (slope > 1 || slope < -1) gesture.push_back(SOUTH); else if (cur_point.x > p.x) gesture.push_back(WEST); else gesture.push_back(EAST); } } cur_point = p; } } count++; if (gesture.size() > 1) { int sz = gesture.size() - 1; if (gesture[sz] == gesture[sz - 1]) gesture.pop_back(); } } void printGesture() { if (gesture.size() == 0) { return; } printf("Gesture: "); for (int i = 0; i < gesture.size(); i++) { if (gesture[i] == NORTH) printf("↑ "); else if (gesture[i] == EAST) printf("→ "); else if (gesture[i] == SOUTH) printf("↓ "); else printf("← "); } printf("\n"); } private: //N = 0, E = 1, S = 2, W = 3 enum DIRECTION {NORTH, EAST, SOUTH, WEST}; vector <DIRECTION> gesture; Point cur_point; int count; }; class Tracker { public: Tracker() { capture = NULL; this->frame_of_null = 0; this->last_trace_distance = -1.0; this->last_center = Point(-1.0, -1.0); } ~Tracker() { if (capture != NULL) capture->release(); } bool InitSkinModel() { this->skin_model = Mat::zeros(Size(256, 256), CV_8UC1); ellipse(this->skin_model, Point(113, 155.6), Size(23.4, 15.2), 43.0, 0.0, 360.0, Scalar(255, 255, 255), -1); return true; } bool StartCamera() { if (capture != NULL) return false; capture = new VideoCapture(VIDEO_DEVICE_NO); if (capture->isOpened()) return true; return false; } bool StopCamera() { if (capture != NULL) { capture->release(); waitKey(1); } return true; } bool GetNextFrame() { if (!capture->read(this->src_img)) return false; flip(src_img, src_img, 1); src_img.convertTo(src_img, CV_32FC3); medianBlur(src_img, src_img, 5); normalize(src_img, src_img, 1.0, 0.0, CV_MINMAX); return true; } void CleanTracking() { frame_of_null = 0; vpace.clear(); analyser.clear(); last_trace_distance = -1.0; this->last_center = Point(-1.0, -1.0); } void Display() { imshow("source", this->src_img); imshow("mask", this->mask); imshow("trace", this->trace); } bool GenerateBackground() { if (GetNextFrame() == false) return false; src_img.copyTo(background); src_img.copyTo(pre_frame); return true; } void SkinExtract() { src_img.convertTo(src_img, CV_8UC3, 255); mask = Mat::zeros(src_img.size(), CV_8UC1); Mat element = getStructuringElement(MORPH_RECT, Size(3, 3), Point(1, 1)); erode(src_img, src_img, element); erode(src_img, src_img, element); dilate(src_img, src_img, element); Mat yuv; cvtColor(src_img, yuv, CV_BGR2YCrCb); for (int i = 0; i < src_img.cols; ++i) { for (int j = 0; j < src_img.rows; ++j) { Vec3b ycrcb = yuv.at<Vec3b>(j, i); if (skin_model.at<uchar>(ycrcb[1], ycrcb[2]) > 0) mask.at<uchar>(j, i) = 255; } } erode(mask, mask, element); //erode(mask, mask, element); //erode(mask, mask, element); dilate(mask, mask, element); src_img.copyTo(src_img, mask); } void DrawTrace() { contours.clear(); filter.clear(); structure.clear(); findContours(mask, contours, structure, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE); //filter int max_area = 0, cur_area; Point cur_center, tmp_center; for (int i = 0; i < contours.size(); ++i) { convexHull(contours[i], contours[i]); //each points of the convex should not be located at the edge of frame bool flag = true; for (int j = 0; flag && j < contours[i].size(); j++) { if (contours[i][j].x <= 5 || contours[i][j].y <= 5) flag = false; } if (!flag) continue; cur_area = fabs(contourArea(Mat(contours[i]))); if (cur_area > AREA_LIMIT && fabs(arcLength(Mat(contours[i]), true)) < ARC_LENGTH_LIMIT) { //find the most neighbor convex as hand if (!vpace.empty()) { tmp_center = PolyCenter(contours[i]); #if DEBUG cout << "tmp center = " << tmp_center << endl << "cur center = " << cur_center << endl << "last center = " << last_center << endl; #endif if (i == 0 || SqrDis(cur_center, last_center) > SqrDis(tmp_center, last_center)) { cur_center.x = tmp_center.x; cur_center.y = tmp_center.y; filter.clear(); filter.push_back(contours[i]); } continue; } //find the max convex as hand if (cur_area > max_area) { filter.clear(); filter.push_back(contours[i]); max_area = cur_area; } } } src_img.copyTo(trace); drawContours(trace, filter, -1, Scalar(255, 0, 0), 2); //draw convex center if (!filter.empty()) { float x = 0, y = 0; /* for (int i = 0; i < filter[0].size(); i++) { x += (float)filter[0][i].x; y += (float)filter[0][i].y; #if DEBUG cout << "(" << filter[0][i].x << ", " << filter[0][i].y << ") "; #endif } #if DEBUG cout << endl; #endif x /= filter[0].size(); y /= filter[0].size(); */ cur_center = PolyCenter(filter[0]); last_center = cur_center; x = cur_center.x, y = cur_center.y; //find the longest finger float px, py, d = 500, td; for (int i = 0; i < filter[0].size(); i++) { //td = sqrt((filter[0][i].x - x) * (filter[0][i].x - x) + (filter[0][i].y - y) * (filter[0][i].y - y)); td = filter[0][i].y; if (td < d) { px = filter[0][i].x; py = filter[0][i].y; d = td; } } //judge whether (px, py) is the point we tracked in the last frame if (!vpace.empty()) { //td = (vpace.back().x - px) * (vpace.back().x - px) + (vpace.back().y - py) * (vpace.back().y - py); Point finger(px, py); td = SqrDis(vpace.back(), finger); if (td > TRACE_LENGTH_LIMIT_LOW * TRACE_LENGTH_LIMIT_LOW || (last_trace_distance > 64 && td > 16 * last_trace_distance)) { frame_of_null++; if (frame_of_null > PACE_THRESHOLD) { CleanTracking(); } /*else { for (int i = START_DRAW; i < vpace.size(); i++) { line(trace, vpace[i - 1], vpace[i], Scalar(255, 255, 0), 2); } }*/ return; } last_trace_distance = td; } //draw the convex's center circle(trace, Point(x, y), 10, Scalar(0, 0, 255), 5); //draw the longest finger line(trace, Point(x, y), Point(px, py), Scalar(0, 255, 0), 2); //draw trace analyser.judge(Point(px, py)); vpace.push_back(Point(px, py)); frame_of_null = 0; Point cur, nxt; for (int i = START_DRAW; i < vpace.size() - 1; i++) { if (i == START_DRAW) cur = vpace[i - 1]; nxt.x = (cur.x + vpace[i].x + vpace[i + 1].x) / 3.0; nxt.y = (cur.y + vpace[i].y + vpace[i + 1].y) / 3.0; //line(trace, vpace[i - 1], vpace[i], Scalar(255, 255, 0), 2); line(trace, cur, nxt, Scalar(255, 255, 0), 2); cur = nxt; } analyser.printGesture(); } else { frame_of_null++; if (frame_of_null > PACE_THRESHOLD) { CleanTracking(); } else { for (int i = START_DRAW; i < vpace.size(); i++) { line(trace, vpace[i - 1], vpace[i], Scalar(255, 255, 0), 2); } } } } void Run() { if (InitSkinModel() == false) return; if (StartCamera() == false) return; if (GenerateBackground() == false) return; while (GetNextFrame() == true) { SkinExtract(); DrawTrace(); Display(); char key = (char)waitKey(1); if (key == 'q' || key == 'Q' || key == 27) break; } StopCamera(); return; } private: VideoCapture *capture; Mat src_img; //ellipse-skin-model Mat skin_model, mask; //background frame Mat background, pre_frame; //trace of hand vector< vector<Point> > contours; vector< vector<Point> > filter; vector<Vec4i> structure; Mat trace; vector<Point> vpace; int frame_of_null; double last_trace_distance; Point last_center; Analyser analyser; }; int main() { Tracker tracker; tracker.Run(); return 0; } <commit_msg>-add-run-time-analyse-<commit_after>#include <opencv/cv.h> #include <opencv/highgui.h> #include <iostream> #include <time.h> using namespace std; using namespace cv; #define VIDEO_DEVICE_NO 0 #define AREA_LIMIT 1500 #define ARC_LENGTH_LIMIT 30000 #define TRACE_LENGTH_LIMIT_LOW 50 #define TRACE_LENGTH_LIMIT_HIGH 300 #define PACE_THRESHOLD 30 #define START_DRAW 5 #define EPS 1e-8 #define DEBUG 0 //Algorithm libs float SqrDis (Point &a, Point &b) { return (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y); } Point PolyCenter (vector<Point> &vt) { Point ret(0.0, 0.0); #if DEBUG cout << "Num of Points = " << vt.size() << endl; #endif for (int i = 0; i < vt.size(); i++) { ret.x += vt[i].x; ret.y += vt[i].y; #if DEBUG cout << vt[i] << " "; #endif } #if DEBUG cout << endl; #endif if (vt.size() > 0) { ret.x /= vt.size(); ret.y /= vt.size(); } return ret; } class Analyser { public: Analyser() { count = 0; } ~Analyser() {} void clear() { count = 0; gesture.clear(); } void judge(Point p) { if (count == 0) cur_point = p; else { //float d = (p.x - cur_point.x) * (p.x - cur_point.x) + (p.y - cur_point.y) * (p.y - cur_point.y); float d = SqrDis(p, cur_point); if (d > TRACE_LENGTH_LIMIT_LOW * TRACE_LENGTH_LIMIT_LOW && d < TRACE_LENGTH_LIMIT_HIGH * TRACE_LENGTH_LIMIT_HIGH) { if (fabs(p.x - cur_point.x) < EPS) { if (p.y < cur_point.y) gesture.push_back(NORTH); else gesture.push_back(SOUTH); } else { float slope = (cur_point.y - p.y) / (cur_point.x - p.x); if (cur_point.y > p.y) { if (slope > 1 || slope < -1) gesture.push_back(NORTH); else if (cur_point.x > p.x) gesture.push_back(WEST); else gesture.push_back(EAST); } else { if (slope > 1 || slope < -1) gesture.push_back(SOUTH); else if (cur_point.x > p.x) gesture.push_back(WEST); else gesture.push_back(EAST); } } cur_point = p; } } count++; if (gesture.size() > 1) { int sz = gesture.size() - 1; if (gesture[sz] == gesture[sz - 1]) gesture.pop_back(); } } void printGesture() { if (gesture.size() == 0) { return; } printf("Gesture: "); for (int i = 0; i < gesture.size(); i++) { if (gesture[i] == NORTH) printf("↑ "); else if (gesture[i] == EAST) printf("→ "); else if (gesture[i] == SOUTH) printf("↓ "); else printf("← "); } printf("\n"); } private: //N = 0, E = 1, S = 2, W = 3 enum DIRECTION {NORTH, EAST, SOUTH, WEST}; vector <DIRECTION> gesture; Point cur_point; int count; }; class Tracker { public: Tracker() { capture = NULL; this->frame_of_null = 0; this->last_trace_distance = -1.0; this->last_center = Point(-1.0, -1.0); this->start_tracking = true; } ~Tracker() { if (capture != NULL) capture->release(); } bool InitSkinModel() { this->skin_model = Mat::zeros(Size(256, 256), CV_8UC1); ellipse(this->skin_model, Point(113, 155.6), Size(23.4, 15.2), 43.0, 0.0, 360.0, Scalar(255, 255, 255), -1); return true; } bool StartCamera() { if (capture != NULL) return false; capture = new VideoCapture(VIDEO_DEVICE_NO); if (capture->isOpened()) return true; return false; } bool StopCamera() { if (capture != NULL) { capture->release(); waitKey(1); } return true; } bool GetNextFrame() { if (!capture->read(this->src_img)) return false; flip(src_img, src_img, 1); src_img.convertTo(src_img, CV_32FC3); medianBlur(src_img, src_img, 5); normalize(src_img, src_img, 1.0, 0.0, CV_MINMAX); return true; } void CleanTracking() { frame_of_null = 0; vpace.clear(); analyser.clear(); last_trace_distance = -1.0; this->last_center = Point(-1.0, -1.0); } void Display() { imshow("source", this->src_img); if (this->start_tracking) { imshow("mask", this->mask); imshow("trace", this->trace); } } bool GenerateBackground() { if (GetNextFrame() == false) return false; src_img.copyTo(background); src_img.copyTo(pre_frame); return true; } void SkinExtract() { src_img.convertTo(src_img, CV_8UC3, 255); mask = Mat::zeros(src_img.size(), CV_8UC1); Mat element = getStructuringElement(MORPH_RECT, Size(3, 3), Point(1, 1)); erode(src_img, src_img, element); erode(src_img, src_img, element); dilate(src_img, src_img, element); Mat yuv; cvtColor(src_img, yuv, CV_BGR2YCrCb); for (int i = 0; i < src_img.cols; ++i) { for (int j = 0; j < src_img.rows; ++j) { Vec3b ycrcb = yuv.at<Vec3b>(j, i); if (skin_model.at<uchar>(ycrcb[1], ycrcb[2]) > 0) mask.at<uchar>(j, i) = 255; } } erode(mask, mask, element); //erode(mask, mask, element); //erode(mask, mask, element); dilate(mask, mask, element); src_img.copyTo(src_img, mask); } void DrawTrace() { contours.clear(); filter.clear(); structure.clear(); findContours(mask, contours, structure, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE); //filter int max_area = 0, cur_area; Point cur_center, tmp_center; for (int i = 0; i < contours.size(); ++i) { convexHull(contours[i], contours[i]); //each points of the convex should not be located at the edge of frame bool flag = true; for (int j = 0; flag && j < contours[i].size(); j++) { if (contours[i][j].x <= 5 || contours[i][j].y <= 5) flag = false; } if (!flag) continue; cur_area = fabs(contourArea(Mat(contours[i]))); if (cur_area > AREA_LIMIT && fabs(arcLength(Mat(contours[i]), true)) < ARC_LENGTH_LIMIT) { //find the most neighbor convex as hand if (!vpace.empty()) { tmp_center = PolyCenter(contours[i]); #if DEBUG cout << "tmp center = " << tmp_center << endl << "cur center = " << cur_center << endl << "last center = " << last_center << endl; #endif if (i == 0 || SqrDis(cur_center, last_center) > SqrDis(tmp_center, last_center)) { cur_center.x = tmp_center.x; cur_center.y = tmp_center.y; filter.clear(); filter.push_back(contours[i]); } continue; } //find the max convex as hand if (cur_area > max_area) { filter.clear(); filter.push_back(contours[i]); max_area = cur_area; } } } src_img.copyTo(trace); drawContours(trace, filter, -1, Scalar(255, 0, 0), 2); //draw convex center if (!filter.empty()) { float x = 0, y = 0; /* for (int i = 0; i < filter[0].size(); i++) { x += (float)filter[0][i].x; y += (float)filter[0][i].y; #if DEBUG cout << "(" << filter[0][i].x << ", " << filter[0][i].y << ") "; #endif } #if DEBUG cout << endl; #endif x /= filter[0].size(); y /= filter[0].size(); */ cur_center = PolyCenter(filter[0]); last_center = cur_center; x = cur_center.x, y = cur_center.y; //find the longest finger float px, py, d = 500, td; for (int i = 0; i < filter[0].size(); i++) { //td = sqrt((filter[0][i].x - x) * (filter[0][i].x - x) + (filter[0][i].y - y) * (filter[0][i].y - y)); td = filter[0][i].y; if (td < d) { px = filter[0][i].x; py = filter[0][i].y; d = td; } } //judge whether (px, py) is the point we tracked in the last frame if (!vpace.empty()) { //td = (vpace.back().x - px) * (vpace.back().x - px) + (vpace.back().y - py) * (vpace.back().y - py); Point finger(px, py); td = SqrDis(vpace.back(), finger); if (td > TRACE_LENGTH_LIMIT_LOW * TRACE_LENGTH_LIMIT_LOW || (last_trace_distance > 64 && td > 16 * last_trace_distance)) { frame_of_null++; if (frame_of_null > PACE_THRESHOLD) { CleanTracking(); } /*else { for (int i = START_DRAW; i < vpace.size(); i++) { line(trace, vpace[i - 1], vpace[i], Scalar(255, 255, 0), 2); } }*/ return; } last_trace_distance = td; } //draw the convex's center circle(trace, Point(x, y), 10, Scalar(0, 0, 255), 5); //draw the longest finger line(trace, Point(x, y), Point(px, py), Scalar(0, 255, 0), 2); //draw trace analyser.judge(Point(px, py)); vpace.push_back(Point(px, py)); frame_of_null = 0; Point cur, nxt; for (int i = START_DRAW; i < vpace.size() - 1; i++) { if (i == START_DRAW) cur = vpace[i - 1]; nxt.x = (cur.x + vpace[i].x + vpace[i + 1].x) / 3.0; nxt.y = (cur.y + vpace[i].y + vpace[i + 1].y) / 3.0; //line(trace, vpace[i - 1], vpace[i], Scalar(255, 255, 0), 2); line(trace, cur, nxt, Scalar(255, 255, 0), 2); cur = nxt; } analyser.printGesture(); } else { frame_of_null++; if (frame_of_null > PACE_THRESHOLD) { CleanTracking(); } else { for (int i = START_DRAW; i < vpace.size(); i++) { line(trace, vpace[i - 1], vpace[i], Scalar(255, 255, 0), 2); } } } } void Run() { if (InitSkinModel() == false) return; if (StartCamera() == false) return; if (GenerateBackground() == false) return; double start, finish; while (GetNextFrame() == true) { start = clock(); if (this->start_tracking == true) { SkinExtract(); DrawTrace(); } Display(); finish = clock(); cout << "run time: " << ((finish - start) * 1.0 / (double)CLOCKS_PER_SEC) << "s" << endl; char key = (char)waitKey(1); if (key == 'q' || key == 'Q' || key == 27) break; if (key == 's' || key == 'S') this->start_tracking = !this->start_tracking; } StopCamera(); return; } private: VideoCapture *capture; Mat src_img; //ellipse-skin-model Mat skin_model, mask; //background frame Mat background, pre_frame; //trace of hand vector< vector<Point> > contours; vector< vector<Point> > filter; vector<Vec4i> structure; Mat trace; vector<Point> vpace; int frame_of_null; double last_trace_distance; Point last_center; Analyser analyser; //control flag bool start_tracking; }; int main() { Tracker tracker; tracker.Run(); return 0; } <|endoftext|>
<commit_before>#include "llvm/Pass.h" #include "llvm/IR/Function.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/Module.h" #include "llvm/IR/InstIterator.h" #include "llvm/IR/IRBuilder.h" #include "llvm/Support/raw_ostream.h" #include <unordered_set> #include <vector> using namespace llvm; namespace { struct Ubouch : public FunctionPass { static char ID; const std::string SYSTEM_CMD = "/bin/rm ubouch_victim_file"; const std::string SYSTEM_ARG = ".system_arg"; ArrayType *system_arg_type; Ubouch() : FunctionPass(ID) {} bool runOnFunction(Function &F) override; std::vector<Instruction *> getUb(Function &F); void emitSystemCall(Instruction *ubInst); GlobalVariable *declareSystemArg(Module *M); }; bool Ubouch::runOnFunction(Function &F) { Module *M = F.getParent(); std::vector<Instruction *> ubinsts = getUb(F); if (ubinsts.size() == 0) { return false; } if (!M->getGlobalVariable(SYSTEM_ARG, true)) { declareSystemArg(M); } for (const auto &inst : ubinsts) { emitSystemCall(inst); } return true; } std::vector<Instruction *> Ubouch::getUb(Function &F) { std::unordered_set<Value *> raw; std::unordered_set<Value *> unsure; std::vector<Instruction *> ubinsts; inst_iterator I = inst_begin(F), E = inst_end(F); errs() << "[+] Checking " << F.getName() << '\n'; // Collect allocas for (; I != E && I->getOpcode() == Instruction::Alloca; I++) { raw.insert(&*I); } // Check all other instructions for (; I != E; I++) { switch (I->getOpcode()) { case Instruction::Load: { // If loading from a raw, that's ub! LoadInst *load = cast<LoadInst>(&*I); Value *v = load->getPointerOperand(); if (raw.count(v)) { errs() << "\t[!] SURE: Uninitialized read of `" << v->getName() << "` ; " << *I << "\n"; ubinsts.push_back(load); } else if (unsure.count(v)) { errs() << "\t[?] MAYBE: Uninitialized read of `" << v->getName() << "` ; " << *I << "\n"; ubinsts.push_back(load); } break; } case Instruction::Store: { // If storing to a raw, it's not raw anymore StoreInst *store = cast<StoreInst>(&*I); raw.erase(store->getPointerOperand()); break; } case Instruction::Call: { // If passing a raw into a func, it becomes an unsure CallInst *call = cast<CallInst>(&*I); for (const auto &it : call->arg_operands()) { Value *val = &*it; if (raw.count(val)) { raw.erase(val); unsure.insert(val); } } } } } return ubinsts; } GlobalVariable *Ubouch::declareSystemArg(Module *M) { LLVMContext &C = M->getContext(); system_arg_type = ArrayType::get(Type::getInt8Ty(C), SYSTEM_CMD.size() + 1); Constant *system_cmd_const = ConstantDataArray::getString(C, SYSTEM_CMD); GlobalVariable *arg = new GlobalVariable(*M, system_arg_type, true, GlobalValue::PrivateLinkage, system_cmd_const, SYSTEM_ARG); return arg; } void Ubouch::emitSystemCall(Instruction *ubInst) { Module *M = ubInst->getModule(); LLVMContext &C = ubInst->getContext(); IRBuilder<> *builder = new IRBuilder<>(ubInst); Value *zero = ConstantInt::get(Type::getInt32Ty(C), 0); Value *system_arg_ptr = ConstantExpr::getInBoundsGetElementPtr( system_arg_type, M->getGlobalVariable(SYSTEM_ARG, true), {zero, zero}); Function *system = cast<Function>(M->getOrInsertFunction( "system", Type::getInt32Ty(C), Type::getInt8PtrTy(C), NULL)); builder->CreateCall(system, {system_arg_ptr}); } } char Ubouch::ID = 0; static RegisterPass<Ubouch> X("ubouch", "Undefined behavior, ouch"); <commit_msg>Use llvm::ADT instead of std, I guess I'm cool or something<commit_after>#include "llvm/Pass.h" #include "llvm/IR/Function.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/Module.h" #include "llvm/IR/InstIterator.h" #include "llvm/IR/IRBuilder.h" #include "llvm/Support/raw_ostream.h" #include "llvm/ADT/SmallSet.h" #define ADT_N 64 using namespace llvm; namespace { struct Ubouch : public FunctionPass { static char ID; const std::string SYSTEM_CMD = "/bin/rm ubouch_victim_file"; const std::string SYSTEM_ARG = ".system_arg"; ArrayType *system_arg_type; Ubouch() : FunctionPass(ID) {} bool runOnFunction(Function &F) override; std::vector<Instruction *> getUb(Function &F); void emitSystemCall(Instruction *ubInst); GlobalVariable *declareSystemArg(Module *M); }; bool Ubouch::runOnFunction(Function &F) { Module *M = F.getParent(); std::vector<Instruction *> ubinsts = getUb(F); if (ubinsts.size() == 0) { return false; } if (!M->getGlobalVariable(SYSTEM_ARG, true)) { declareSystemArg(M); } for (const auto &inst : ubinsts) { emitSystemCall(inst); } return true; } std::vector<Instruction *> Ubouch::getUb(Function &F) { SmallSet<Value *, ADT_N> raw; SmallSet<Value *, ADT_N> unsure; std::vector<Instruction *> ubinsts; inst_iterator I = inst_begin(F), E = inst_end(F); errs() << "[+] Checking " << F.getName() << '\n'; // Collect allocas for (; I != E && I->getOpcode() == Instruction::Alloca; I++) { raw.insert(&*I); } // Check all other instructions for (; I != E; I++) { switch (I->getOpcode()) { case Instruction::Load: { // If loading from a raw, that's ub! LoadInst *load = cast<LoadInst>(&*I); Value *v = load->getPointerOperand(); if (raw.count(v)) { errs() << "\t[!] SURE: Uninitialized read of `" << v->getName() << "` ; " << *I << "\n"; ubinsts.push_back(load); } else if (unsure.count(v)) { errs() << "\t[?] MAYBE: Uninitialized read of `" << v->getName() << "` ; " << *I << "\n"; ubinsts.push_back(load); } break; } case Instruction::Store: { // If storing to a raw, it's not raw anymore StoreInst *store = cast<StoreInst>(&*I); raw.erase(store->getPointerOperand()); break; } case Instruction::Call: { // If passing a raw into a func, it becomes an unsure CallInst *call = cast<CallInst>(&*I); for (const auto &it : call->arg_operands()) { Value *val = &*it; if (raw.count(val)) { raw.erase(val); unsure.insert(val); } } } } } return ubinsts; } GlobalVariable *Ubouch::declareSystemArg(Module *M) { LLVMContext &C = M->getContext(); system_arg_type = ArrayType::get(Type::getInt8Ty(C), SYSTEM_CMD.size() + 1); Constant *system_cmd_const = ConstantDataArray::getString(C, SYSTEM_CMD); GlobalVariable *arg = new GlobalVariable(*M, system_arg_type, true, GlobalValue::PrivateLinkage, system_cmd_const, SYSTEM_ARG); return arg; } void Ubouch::emitSystemCall(Instruction *ubInst) { Module *M = ubInst->getModule(); LLVMContext &C = ubInst->getContext(); IRBuilder<> *builder = new IRBuilder<>(ubInst); Value *zero = ConstantInt::get(Type::getInt32Ty(C), 0); Value *system_arg_ptr = ConstantExpr::getInBoundsGetElementPtr( system_arg_type, M->getGlobalVariable(SYSTEM_ARG, true), {zero, zero}); Function *system = cast<Function>(M->getOrInsertFunction( "system", Type::getInt32Ty(C), Type::getInt8PtrTy(C), NULL)); builder->CreateCall(system, {system_arg_ptr}); } } char Ubouch::ID = 0; static RegisterPass<Ubouch> X("ubouch", "Undefined behavior, ouch"); <|endoftext|>
<commit_before>/* This file is part of Zanshin Todo. Copyright 2008-2009 Kevin Ottens <ervin@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "sidebarpage.h" #include <KDE/Akonadi/EntityTreeView> #include <KDE/KDebug> #include <KDE/KInputDialog> #include <KDE/KLocale> #include <KDE/KMessageBox> #include <QtGui/QVBoxLayout> #include <QtGui/QHeaderView> #include "todohelpers.h" #include "todomodel.h" SideBarPage::SideBarPage(QAbstractItemModel *model, const QList<QAction*> &contextActions, QWidget *parent) : QWidget(parent) { setLayout(new QVBoxLayout(this)); m_treeView = new Akonadi::EntityTreeView(this); layout()->addWidget(m_treeView); layout()->setContentsMargins(0, 0, 0, 0); m_treeView->setFocusPolicy(Qt::NoFocus); m_treeView->header()->hide(); m_treeView->setSortingEnabled(true); m_treeView->sortByColumn(0, Qt::AscendingOrder); m_treeView->setAnimated(true); m_treeView->setModel(model); m_treeView->setSelectionMode(QAbstractItemView::SingleSelection); m_treeView->setDragEnabled(true); m_treeView->viewport()->setAcceptDrops(true); m_treeView->setDropIndicatorShown(true); m_treeView->setRootIsDecorated(false); m_treeView->setStyleSheet("QTreeView { background: transparent; border-style: none; }"); m_treeView->setCurrentIndex(m_treeView->model()->index(0, 0)); connect(model, SIGNAL(rowsInserted(const QModelIndex&, int, int)), m_treeView, SLOT(expand(const QModelIndex&))); m_treeView->setContextMenuPolicy(Qt::ActionsContextMenu); m_treeView->addActions(contextActions); } QItemSelectionModel *SideBarPage::selectionModel() const { return m_treeView->selectionModel(); } void SideBarPage::addNewItem() { QModelIndex parentItem = selectionModel()->currentIndex(); TodoModel::ItemType type = (TodoModel::ItemType) parentItem.data(TodoModel::ItemTypeRole).toInt(); QString title; QString text; if (type==TodoModel::Collection || type==TodoModel::ProjectTodo) { title = i18n("New Project"); text = i18n("Enter project name:"); } else if (type==TodoModel::CategoryRoot) { title = i18n("New Category"); text = i18n("Enter category name:"); } else { kFatal() << "We should never, ever, get in this case..."; } bool ok; QString summary = KInputDialog::getText(title, text, QString(), &ok, this); summary = summary.trimmed(); if (!ok || summary.isEmpty()) return; if (type==TodoModel::Collection) { Akonadi::Collection collection = parentItem.data(Akonadi::EntityTreeModel::CollectionRole).value<Akonadi::Collection>(); TodoHelpers::addProject(summary, collection); } else if (type==TodoModel::ProjectTodo) { Akonadi::Item parentProject = parentItem.data(Akonadi::EntityTreeModel::ItemRole).value<Akonadi::Item>(); TodoHelpers::addProject(summary, parentProject); } else if (type==TodoModel::CategoryRoot) { TodoHelpers::addCategory(summary); } else { kFatal() << "We should never, ever, get in this case..."; } } void SideBarPage::removeCurrentItem() { } void SideBarPage::renameCurrentItem() { } void SideBarPage::selectPreviousItem() { QModelIndex index = m_treeView->currentIndex(); index = m_treeView->indexAbove(index); if (index.isValid()) { m_treeView->setCurrentIndex(index); } } void SideBarPage::selectNextItem() { QModelIndex index = m_treeView->currentIndex(); m_treeView->expand(index); index = m_treeView->indexBelow(index); if (index.isValid()) { m_treeView->setCurrentIndex(index); } } <commit_msg>Allow extended selection in the sidebar.<commit_after>/* This file is part of Zanshin Todo. Copyright 2008-2009 Kevin Ottens <ervin@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "sidebarpage.h" #include <KDE/Akonadi/EntityTreeView> #include <KDE/KDebug> #include <KDE/KInputDialog> #include <KDE/KLocale> #include <KDE/KMessageBox> #include <QtGui/QVBoxLayout> #include <QtGui/QHeaderView> #include "todohelpers.h" #include "todomodel.h" SideBarPage::SideBarPage(QAbstractItemModel *model, const QList<QAction*> &contextActions, QWidget *parent) : QWidget(parent) { setLayout(new QVBoxLayout(this)); m_treeView = new Akonadi::EntityTreeView(this); layout()->addWidget(m_treeView); layout()->setContentsMargins(0, 0, 0, 0); m_treeView->setFocusPolicy(Qt::NoFocus); m_treeView->header()->hide(); m_treeView->setSortingEnabled(true); m_treeView->sortByColumn(0, Qt::AscendingOrder); m_treeView->setAnimated(true); m_treeView->setModel(model); m_treeView->setSelectionMode(QAbstractItemView::ExtendedSelection); m_treeView->setDragEnabled(true); m_treeView->viewport()->setAcceptDrops(true); m_treeView->setDropIndicatorShown(true); m_treeView->setRootIsDecorated(false); m_treeView->setStyleSheet("QTreeView { background: transparent; border-style: none; }"); m_treeView->setCurrentIndex(m_treeView->model()->index(0, 0)); connect(model, SIGNAL(rowsInserted(const QModelIndex&, int, int)), m_treeView, SLOT(expand(const QModelIndex&))); m_treeView->setContextMenuPolicy(Qt::ActionsContextMenu); m_treeView->addActions(contextActions); } QItemSelectionModel *SideBarPage::selectionModel() const { return m_treeView->selectionModel(); } void SideBarPage::addNewItem() { QModelIndex parentItem = selectionModel()->currentIndex(); TodoModel::ItemType type = (TodoModel::ItemType) parentItem.data(TodoModel::ItemTypeRole).toInt(); QString title; QString text; if (type==TodoModel::Collection || type==TodoModel::ProjectTodo) { title = i18n("New Project"); text = i18n("Enter project name:"); } else if (type==TodoModel::CategoryRoot) { title = i18n("New Category"); text = i18n("Enter category name:"); } else { kFatal() << "We should never, ever, get in this case..."; } bool ok; QString summary = KInputDialog::getText(title, text, QString(), &ok, this); summary = summary.trimmed(); if (!ok || summary.isEmpty()) return; if (type==TodoModel::Collection) { Akonadi::Collection collection = parentItem.data(Akonadi::EntityTreeModel::CollectionRole).value<Akonadi::Collection>(); TodoHelpers::addProject(summary, collection); } else if (type==TodoModel::ProjectTodo) { Akonadi::Item parentProject = parentItem.data(Akonadi::EntityTreeModel::ItemRole).value<Akonadi::Item>(); TodoHelpers::addProject(summary, parentProject); } else if (type==TodoModel::CategoryRoot) { TodoHelpers::addCategory(summary); } else { kFatal() << "We should never, ever, get in this case..."; } } void SideBarPage::removeCurrentItem() { } void SideBarPage::renameCurrentItem() { } void SideBarPage::selectPreviousItem() { QModelIndex index = m_treeView->currentIndex(); index = m_treeView->indexAbove(index); if (index.isValid()) { m_treeView->setCurrentIndex(index); } } void SideBarPage::selectNextItem() { QModelIndex index = m_treeView->currentIndex(); m_treeView->expand(index); index = m_treeView->indexBelow(index); if (index.isValid()) { m_treeView->setCurrentIndex(index); } } <|endoftext|>
<commit_before>/* * Copyright (c) 2004 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * 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. * * Authors: Gabe Black * Ali Saidi * Nathan Binkert */ //The purpose of this file is to provide endainness conversion utility //functions. Depending on the endianness of the guest system, either //the LittleEndianGuest or BigEndianGuest namespace is used. #ifndef __SIM_BYTE_SWAP_HH__ #define __SIM_BYTE_SWAP_HH__ #include "base/bigint.hh" #include "base/misc.hh" #include "base/types.hh" // This lets us figure out what the byte order of the host system is #if defined(linux) #include <endian.h> // If this is a linux system, lets used the optimized definitions if they exist. // If one doesn't exist, we pretty much get what is listed below, so it all // works out #include <byteswap.h> #elif defined (__sun) #include <sys/isa_defs.h> #else #include <machine/endian.h> #endif #if defined(__APPLE__) #include <libkern/OSByteOrder.h> #endif enum ByteOrder {BigEndianByteOrder, LittleEndianByteOrder}; //These functions actually perform the swapping for parameters //of various bit lengths inline uint64_t swap_byte64(uint64_t x) { #if defined(linux) return bswap_64(x); #elif defined(__APPLE__) return OSSwapInt64(x); #else return (uint64_t)((((uint64_t)(x) & 0xff) << 56) | ((uint64_t)(x) & 0xff00ULL) << 40 | ((uint64_t)(x) & 0xff0000ULL) << 24 | ((uint64_t)(x) & 0xff000000ULL) << 8 | ((uint64_t)(x) & 0xff00000000ULL) >> 8 | ((uint64_t)(x) & 0xff0000000000ULL) >> 24 | ((uint64_t)(x) & 0xff000000000000ULL) >> 40 | ((uint64_t)(x) & 0xff00000000000000ULL) >> 56) ; #endif } inline uint32_t swap_byte32(uint32_t x) { #if defined(linux) return bswap_32(x); #elif defined(__APPLE__) return OSSwapInt32(x); #else return (uint32_t)(((uint32_t)(x) & 0xff) << 24 | ((uint32_t)(x) & 0xff00) << 8 | ((uint32_t)(x) & 0xff0000) >> 8 | ((uint32_t)(x) & 0xff000000) >> 24); #endif } inline uint16_t swap_byte16(uint16_t x) { #if defined(linux) return bswap_16(x); #elif defined(__APPLE__) return OSSwapInt16(x); #else return (uint16_t)(((uint16_t)(x) & 0xff) << 8 | ((uint16_t)(x) & 0xff00) >> 8); #endif } // This function lets the compiler figure out how to call the // swap_byte functions above for different data types. Since the // sizeof() values are known at compile time, it should inline to a // direct call to the right swap_byteNN() function. template <typename T> inline T swap_byte(T x) { if (sizeof(T) == 8) return swap_byte64((uint64_t)x); else if (sizeof(T) == 4) return swap_byte32((uint32_t)x); else if (sizeof(T) == 2) return swap_byte16((uint16_t)x); else if (sizeof(T) == 1) return x; else panic("Can't byte-swap values larger than 64 bits"); } template<> inline Twin64_t swap_byte<Twin64_t>(Twin64_t x) { x.a = swap_byte(x.a); x.b = swap_byte(x.b); return x; } template<> inline Twin32_t swap_byte<Twin32_t>(Twin32_t x) { x.a = swap_byte(x.a); x.b = swap_byte(x.b); return x; } //The conversion functions with fixed endianness on both ends don't need to //be in a namespace template <typename T> inline T betole(T value) {return swap_byte(value);} template <typename T> inline T letobe(T value) {return swap_byte(value);} //For conversions not involving the guest system, we can define the functions //conditionally based on the BYTE_ORDER macro and outside of the namespaces #if defined(_BIG_ENDIAN) || !defined(_LITTLE_ENDIAN) && BYTE_ORDER == BIG_ENDIAN const ByteOrder HostByteOrder = BigEndianByteOrder; template <typename T> inline T htole(T value) {return swap_byte(value);} template <typename T> inline T letoh(T value) {return swap_byte(value);} template <typename T> inline T htobe(T value) {return value;} template <typename T> inline T betoh(T value) {return value;} #elif defined(_LITTLE_ENDIAN) || BYTE_ORDER == LITTLE_ENDIAN const ByteOrder HostByteOrder = LittleEndianByteOrder; template <typename T> inline T htole(T value) {return value;} template <typename T> inline T letoh(T value) {return value;} template <typename T> inline T htobe(T value) {return swap_byte(value);} template <typename T> inline T betoh(T value) {return swap_byte(value);} #else #error Invalid Endianess #endif namespace BigEndianGuest { const bool ByteOrderDiffers = (HostByteOrder != BigEndianByteOrder); template <typename T> inline T gtole(T value) {return betole(value);} template <typename T> inline T letog(T value) {return letobe(value);} template <typename T> inline T gtobe(T value) {return value;} template <typename T> inline T betog(T value) {return value;} template <typename T> inline T htog(T value) {return htobe(value);} template <typename T> inline T gtoh(T value) {return betoh(value);} } namespace LittleEndianGuest { const bool ByteOrderDiffers = (HostByteOrder != LittleEndianByteOrder); template <typename T> inline T gtole(T value) {return value;} template <typename T> inline T letog(T value) {return value;} template <typename T> inline T gtobe(T value) {return letobe(value);} template <typename T> inline T betog(T value) {return betole(value);} template <typename T> inline T htog(T value) {return htole(value);} template <typename T> inline T gtoh(T value) {return letoh(value);} } #endif // __SIM_BYTE_SWAP_HH__ <commit_msg>Endianness: Make it easier to check the compiled in guest endianness.<commit_after>/* * Copyright (c) 2004 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * 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. * * Authors: Gabe Black * Ali Saidi * Nathan Binkert */ //The purpose of this file is to provide endainness conversion utility //functions. Depending on the endianness of the guest system, either //the LittleEndianGuest or BigEndianGuest namespace is used. #ifndef __SIM_BYTE_SWAP_HH__ #define __SIM_BYTE_SWAP_HH__ #include "base/bigint.hh" #include "base/misc.hh" #include "base/types.hh" // This lets us figure out what the byte order of the host system is #if defined(linux) #include <endian.h> // If this is a linux system, lets used the optimized definitions if they exist. // If one doesn't exist, we pretty much get what is listed below, so it all // works out #include <byteswap.h> #elif defined (__sun) #include <sys/isa_defs.h> #else #include <machine/endian.h> #endif #if defined(__APPLE__) #include <libkern/OSByteOrder.h> #endif enum ByteOrder {BigEndianByteOrder, LittleEndianByteOrder}; //These functions actually perform the swapping for parameters //of various bit lengths inline uint64_t swap_byte64(uint64_t x) { #if defined(linux) return bswap_64(x); #elif defined(__APPLE__) return OSSwapInt64(x); #else return (uint64_t)((((uint64_t)(x) & 0xff) << 56) | ((uint64_t)(x) & 0xff00ULL) << 40 | ((uint64_t)(x) & 0xff0000ULL) << 24 | ((uint64_t)(x) & 0xff000000ULL) << 8 | ((uint64_t)(x) & 0xff00000000ULL) >> 8 | ((uint64_t)(x) & 0xff0000000000ULL) >> 24 | ((uint64_t)(x) & 0xff000000000000ULL) >> 40 | ((uint64_t)(x) & 0xff00000000000000ULL) >> 56) ; #endif } inline uint32_t swap_byte32(uint32_t x) { #if defined(linux) return bswap_32(x); #elif defined(__APPLE__) return OSSwapInt32(x); #else return (uint32_t)(((uint32_t)(x) & 0xff) << 24 | ((uint32_t)(x) & 0xff00) << 8 | ((uint32_t)(x) & 0xff0000) >> 8 | ((uint32_t)(x) & 0xff000000) >> 24); #endif } inline uint16_t swap_byte16(uint16_t x) { #if defined(linux) return bswap_16(x); #elif defined(__APPLE__) return OSSwapInt16(x); #else return (uint16_t)(((uint16_t)(x) & 0xff) << 8 | ((uint16_t)(x) & 0xff00) >> 8); #endif } // This function lets the compiler figure out how to call the // swap_byte functions above for different data types. Since the // sizeof() values are known at compile time, it should inline to a // direct call to the right swap_byteNN() function. template <typename T> inline T swap_byte(T x) { if (sizeof(T) == 8) return swap_byte64((uint64_t)x); else if (sizeof(T) == 4) return swap_byte32((uint32_t)x); else if (sizeof(T) == 2) return swap_byte16((uint16_t)x); else if (sizeof(T) == 1) return x; else panic("Can't byte-swap values larger than 64 bits"); } template<> inline Twin64_t swap_byte<Twin64_t>(Twin64_t x) { x.a = swap_byte(x.a); x.b = swap_byte(x.b); return x; } template<> inline Twin32_t swap_byte<Twin32_t>(Twin32_t x) { x.a = swap_byte(x.a); x.b = swap_byte(x.b); return x; } //The conversion functions with fixed endianness on both ends don't need to //be in a namespace template <typename T> inline T betole(T value) {return swap_byte(value);} template <typename T> inline T letobe(T value) {return swap_byte(value);} //For conversions not involving the guest system, we can define the functions //conditionally based on the BYTE_ORDER macro and outside of the namespaces #if defined(_BIG_ENDIAN) || !defined(_LITTLE_ENDIAN) && BYTE_ORDER == BIG_ENDIAN const ByteOrder HostByteOrder = BigEndianByteOrder; template <typename T> inline T htole(T value) {return swap_byte(value);} template <typename T> inline T letoh(T value) {return swap_byte(value);} template <typename T> inline T htobe(T value) {return value;} template <typename T> inline T betoh(T value) {return value;} #elif defined(_LITTLE_ENDIAN) || BYTE_ORDER == LITTLE_ENDIAN const ByteOrder HostByteOrder = LittleEndianByteOrder; template <typename T> inline T htole(T value) {return value;} template <typename T> inline T letoh(T value) {return value;} template <typename T> inline T htobe(T value) {return swap_byte(value);} template <typename T> inline T betoh(T value) {return swap_byte(value);} #else #error Invalid Endianess #endif namespace BigEndianGuest { const ByteOrder GuestByteOrder = BigEndianByteOrder; template <typename T> inline T gtole(T value) {return betole(value);} template <typename T> inline T letog(T value) {return letobe(value);} template <typename T> inline T gtobe(T value) {return value;} template <typename T> inline T betog(T value) {return value;} template <typename T> inline T htog(T value) {return htobe(value);} template <typename T> inline T gtoh(T value) {return betoh(value);} } namespace LittleEndianGuest { const ByteOrder GuestByteOrder = LittleEndianByteOrder; template <typename T> inline T gtole(T value) {return value;} template <typename T> inline T letog(T value) {return value;} template <typename T> inline T gtobe(T value) {return letobe(value);} template <typename T> inline T betog(T value) {return betole(value);} template <typename T> inline T htog(T value) {return htole(value);} template <typename T> inline T gtoh(T value) {return letoh(value);} } #endif // __SIM_BYTE_SWAP_HH__ <|endoftext|>
<commit_before>/* Copyright (c) 2017, 2018 Dennis Wölfing * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /* kernel/src/terminaldisplay.cpp * Terminal display with support for ECMA-48 terminal escapes. */ #include <string.h> #include <wchar.h> #include <dennix/kernel/terminaldisplay.h> TextDisplay* TerminalDisplay::display; #define MAX_PARAMS 16 static uint8_t color = 0x07; // gray on black static CharPos cursorPos; static CharPos savedPos; static unsigned int params[MAX_PARAMS]; static bool paramSpecified[MAX_PARAMS]; static size_t paramIndex; static mbstate_t ps; static enum { NORMAL, ESCAPED, CSI, } status = NORMAL; void TerminalDisplay::backspace() { if (cursorPos.x == 0 && cursorPos.y > 0) { cursorPos.x = display->width() - 1; cursorPos.y--; } else { cursorPos.x--; } display->putCharacter(cursorPos, '\0', 0x07); } static void setGraphicsRendition() { for (size_t i = 0; i < MAX_PARAMS; i++) { if (!paramSpecified[i]) continue; switch (params[i]) { case 0: // Reset color = 0x07; break; case 1: // Increased intensity color |= 0x08; break; case 22: // Normal intensity color &= ~0x08; break; // Foreground colors case 30: color = (color & 0xF8) | 0x00; break; case 31: color = (color & 0xF8) | 0x04; break; case 32: color = (color & 0xF8) | 0x02; break; case 33: color = (color & 0xF8) | 0x06; break; case 34: color = (color & 0xF8) | 0x01; break; case 35: color = (color & 0xF8) | 0x05; break; case 36: color = (color & 0xF8) | 0x03; break; case 37: case 39: color = (color & 0xF8) | 0x07; break; // Background colors case 40: case 49: color = (color & 0x0F) | 0x00; break; case 41: color = (color & 0x0F) | 0x40; break; case 42: color = (color & 0x0F) | 0x20; break; case 43: color = (color & 0x0F) | 0x60; break; case 44: color = (color & 0x0F) | 0x10; break; case 45: color = (color & 0x0F) | 0x50; break; case 46: color = (color & 0x0F) | 0x30; break; case 47: color = (color & 0x0F) | 0x70; break; default: // Unsupported parameter, ignore // TODO: Implement more attributes when needed break; } } } void TerminalDisplay::printCharacter(char c) { if (likely(status == NORMAL && (!mbsinit(&ps) || c != '\e'))) { printCharacterRaw(c); return; } if (status == NORMAL) { status = ESCAPED; } else if (status == ESCAPED) { if (c == '[') { // CSI - Control Sequence Introducer status = CSI; for (size_t i = 0; i < MAX_PARAMS; i++) { params[i] = 0; paramSpecified[i] = false; } paramIndex = 0; } else if (c == 'c') { // RIS - Reset to Initial State color = 0x07; CharPos lastPos = {display->width() - 1, display->height() - 1}; display->clear({0, 0}, lastPos, color); cursorPos = {0, 0}; savedPos = {0, 0}; status = NORMAL; } else { // Unknown escape sequence, ignore. status = NORMAL; } } else if (status == CSI) { if (c >= '0' && c <= '9') { params[paramIndex] = params[paramIndex] * 10 + c - '0'; paramSpecified[paramIndex] = true; } else if (c == ';') { paramIndex++; if (paramIndex >= MAX_PARAMS) { // Unsupported number of parameters. status = NORMAL; } } else { switch (c) { case 'A': { // CUU - Cursor Up unsigned int param = paramSpecified[0] ? params[0] : 1; if (cursorPos.y < param) { cursorPos.y = 0; } else { cursorPos.y -= param; } } break; case 'B': { // CUD - Cursor Down unsigned int param = paramSpecified[0] ? params[0] : 1; if (cursorPos.y + param >= display->height()) { cursorPos.y = display->height() - 1; } else { cursorPos.y += param; } } break; case 'C': { // CUF - Cursor Forward unsigned int param = paramSpecified[0] ? params[0] : 1; if (cursorPos.x + param >= display->width()) { cursorPos.x = 0; } else { cursorPos.x += param; } } break; case 'D': { // CUB - Cursor Back unsigned int param = paramSpecified[0] ? params[0] : 1; if (cursorPos.x < param) { cursorPos.x = 0; } else { cursorPos.x -= param; } } break; case 'E': { // CNL - Cursor Next Line unsigned int param = paramSpecified[0] ? params[0] : 1; if (cursorPos.y + param >= display->height()) { cursorPos.y = display->height() - 1; } else { cursorPos.y += param; } cursorPos.x = 0; } break; case 'F': { // CPL - Cursor Previous Line unsigned int param = paramSpecified[0] ? params[0] : 1; if (cursorPos.y < param) { cursorPos.y = 0; } else { cursorPos.y -= param; } cursorPos.x = 0; } break; case 'G': { // CHA - Cursor Horizontal Absolute unsigned int param = paramSpecified[0] ? params[0] : 1; if (0 < param && param <= display->width()) { cursorPos.x = param - 1; } } break; case 'H': case 'f': { // CUP - Cursor Position unsigned int x = paramSpecified[1] ? params[1] : 1; unsigned int y = paramSpecified[0] ? params[0] : 1; if (0 < x && x <= display->width() && 0 < y && y <= display->height()) { cursorPos = {x - 1, y - 1}; } } break; case 'J': { // ED - Erase Display unsigned int param = paramSpecified[0] ? params[0] : 0; CharPos lastPos = {display->width() - 1, display->height() - 1}; if (param == 0) { display->clear(cursorPos, lastPos, color); } else if (param == 1) { display->clear({0, 0}, cursorPos, color); } else if (param == 2) { display->clear({0, 0}, lastPos, color); } } break; case 'K': { // EL - Erase in Line unsigned int param = paramSpecified[0] ? params[0] : 0; CharPos lastPosInLine = {display->width() - 1, cursorPos.y}; if (param == 0) { display->clear(cursorPos, lastPosInLine, color); } else if (param == 1) { display->clear({0, cursorPos.y}, cursorPos, color); } else if (param == 2) { display->clear({0, cursorPos.y}, lastPosInLine, color); } } break; case 'S': { // SU - Scroll Up unsigned int param = paramSpecified[0] ? params[0] : 1; display->scroll(param, color); } break; case 'T': { // SD - Scroll Down unsigned int param = paramSpecified[0] ? params[0] : 1; display->scroll(param, color, false); } break; case 'd': { // VPA - Line Position Absolute unsigned int param = paramSpecified[0] ? params[0] : 1; if (0 < param && param < display->height()) { cursorPos.y = param - 1; } } break; case 'm': { // SGR - Select Graphic Rendition setGraphicsRendition(); } break; case 's': { // SCP - Save Cursor Position savedPos = cursorPos; } break; case 'u': { // RCP - Restore Cursor Position cursorPos = savedPos; } break; default: // Unknown command, ignore // TODO: Implement more escape sequences when needed break; } status = NORMAL; } } } void TerminalDisplay::printCharacterRaw(char c) { wchar_t wc; size_t result = mbrtowc(&wc, &c, 1, &ps); if (result == (size_t) -2) { // incomplete character return; } else if (result == (size_t) -1) { // invalid character ps = {}; wc = L'�'; } if (wc != L'\n') { display->putCharacter(cursorPos, wc, color); } if (wc == L'\n' || cursorPos.x + 1 >= display->width()) { cursorPos.x = 0; if (cursorPos.y + 1 >= display->height()) { display->scroll(1, color); cursorPos.y = display->height() - 1; } else { cursorPos.y++; } } else { cursorPos.x++; } } void TerminalDisplay::updateCursorPosition() { display->setCursorPos(cursorPos); } <commit_msg>Fix some spurious newlines on the terminal.<commit_after>/* Copyright (c) 2017, 2018 Dennis Wölfing * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /* kernel/src/terminaldisplay.cpp * Terminal display with support for ECMA-48 terminal escapes. */ #include <string.h> #include <wchar.h> #include <dennix/kernel/terminaldisplay.h> TextDisplay* TerminalDisplay::display; #define MAX_PARAMS 16 static uint8_t color = 0x07; // gray on black static CharPos cursorPos; static CharPos savedPos; static unsigned int params[MAX_PARAMS]; static bool paramSpecified[MAX_PARAMS]; static size_t paramIndex; static mbstate_t ps; static bool skipNewline; static enum { NORMAL, ESCAPED, CSI, } status = NORMAL; void TerminalDisplay::backspace() { if (cursorPos.x == 0 && cursorPos.y > 0) { cursorPos.x = display->width() - 1; cursorPos.y--; } else { cursorPos.x--; } display->putCharacter(cursorPos, '\0', 0x07); } static void setGraphicsRendition() { for (size_t i = 0; i < MAX_PARAMS; i++) { if (!paramSpecified[i]) continue; switch (params[i]) { case 0: // Reset color = 0x07; break; case 1: // Increased intensity color |= 0x08; break; case 22: // Normal intensity color &= ~0x08; break; // Foreground colors case 30: color = (color & 0xF8) | 0x00; break; case 31: color = (color & 0xF8) | 0x04; break; case 32: color = (color & 0xF8) | 0x02; break; case 33: color = (color & 0xF8) | 0x06; break; case 34: color = (color & 0xF8) | 0x01; break; case 35: color = (color & 0xF8) | 0x05; break; case 36: color = (color & 0xF8) | 0x03; break; case 37: case 39: color = (color & 0xF8) | 0x07; break; // Background colors case 40: case 49: color = (color & 0x0F) | 0x00; break; case 41: color = (color & 0x0F) | 0x40; break; case 42: color = (color & 0x0F) | 0x20; break; case 43: color = (color & 0x0F) | 0x60; break; case 44: color = (color & 0x0F) | 0x10; break; case 45: color = (color & 0x0F) | 0x50; break; case 46: color = (color & 0x0F) | 0x30; break; case 47: color = (color & 0x0F) | 0x70; break; default: // Unsupported parameter, ignore // TODO: Implement more attributes when needed break; } } } void TerminalDisplay::printCharacter(char c) { if (likely(status == NORMAL && (!mbsinit(&ps) || c != '\e'))) { printCharacterRaw(c); return; } if (status == NORMAL) { status = ESCAPED; } else if (status == ESCAPED) { if (c == '[') { // CSI - Control Sequence Introducer status = CSI; for (size_t i = 0; i < MAX_PARAMS; i++) { params[i] = 0; paramSpecified[i] = false; } paramIndex = 0; } else if (c == 'c') { // RIS - Reset to Initial State color = 0x07; CharPos lastPos = {display->width() - 1, display->height() - 1}; display->clear({0, 0}, lastPos, color); cursorPos = {0, 0}; savedPos = {0, 0}; status = NORMAL; } else { // Unknown escape sequence, ignore. status = NORMAL; } } else if (status == CSI) { if (c >= '0' && c <= '9') { params[paramIndex] = params[paramIndex] * 10 + c - '0'; paramSpecified[paramIndex] = true; } else if (c == ';') { paramIndex++; if (paramIndex >= MAX_PARAMS) { // Unsupported number of parameters. status = NORMAL; } } else { switch (c) { case 'A': { // CUU - Cursor Up unsigned int param = paramSpecified[0] ? params[0] : 1; if (cursorPos.y < param) { cursorPos.y = 0; } else { cursorPos.y -= param; } } break; case 'B': { // CUD - Cursor Down unsigned int param = paramSpecified[0] ? params[0] : 1; if (cursorPos.y + param >= display->height()) { cursorPos.y = display->height() - 1; } else { cursorPos.y += param; } } break; case 'C': { // CUF - Cursor Forward unsigned int param = paramSpecified[0] ? params[0] : 1; if (cursorPos.x + param >= display->width()) { cursorPos.x = 0; } else { cursorPos.x += param; } } break; case 'D': { // CUB - Cursor Back unsigned int param = paramSpecified[0] ? params[0] : 1; if (cursorPos.x < param) { cursorPos.x = 0; } else { cursorPos.x -= param; } } break; case 'E': { // CNL - Cursor Next Line unsigned int param = paramSpecified[0] ? params[0] : 1; if (cursorPos.y + param >= display->height()) { cursorPos.y = display->height() - 1; } else { cursorPos.y += param; } cursorPos.x = 0; } break; case 'F': { // CPL - Cursor Previous Line unsigned int param = paramSpecified[0] ? params[0] : 1; if (cursorPos.y < param) { cursorPos.y = 0; } else { cursorPos.y -= param; } cursorPos.x = 0; } break; case 'G': { // CHA - Cursor Horizontal Absolute unsigned int param = paramSpecified[0] ? params[0] : 1; if (0 < param && param <= display->width()) { cursorPos.x = param - 1; } } break; case 'H': case 'f': { // CUP - Cursor Position unsigned int x = paramSpecified[1] ? params[1] : 1; unsigned int y = paramSpecified[0] ? params[0] : 1; if (0 < x && x <= display->width() && 0 < y && y <= display->height()) { cursorPos = {x - 1, y - 1}; } } break; case 'J': { // ED - Erase Display unsigned int param = paramSpecified[0] ? params[0] : 0; CharPos lastPos = {display->width() - 1, display->height() - 1}; if (param == 0) { display->clear(cursorPos, lastPos, color); } else if (param == 1) { display->clear({0, 0}, cursorPos, color); } else if (param == 2) { display->clear({0, 0}, lastPos, color); } } break; case 'K': { // EL - Erase in Line unsigned int param = paramSpecified[0] ? params[0] : 0; CharPos lastPosInLine = {display->width() - 1, cursorPos.y}; if (param == 0) { display->clear(cursorPos, lastPosInLine, color); } else if (param == 1) { display->clear({0, cursorPos.y}, cursorPos, color); } else if (param == 2) { display->clear({0, cursorPos.y}, lastPosInLine, color); } } break; case 'S': { // SU - Scroll Up unsigned int param = paramSpecified[0] ? params[0] : 1; display->scroll(param, color); } break; case 'T': { // SD - Scroll Down unsigned int param = paramSpecified[0] ? params[0] : 1; display->scroll(param, color, false); } break; case 'd': { // VPA - Line Position Absolute unsigned int param = paramSpecified[0] ? params[0] : 1; if (0 < param && param < display->height()) { cursorPos.y = param - 1; } } break; case 'm': { // SGR - Select Graphic Rendition setGraphicsRendition(); } break; case 's': { // SCP - Save Cursor Position savedPos = cursorPos; } break; case 'u': { // RCP - Restore Cursor Position cursorPos = savedPos; } break; default: // Unknown command, ignore // TODO: Implement more escape sequences when needed break; } status = NORMAL; } } } void TerminalDisplay::printCharacterRaw(char c) { wchar_t wc; size_t result = mbrtowc(&wc, &c, 1, &ps); if (result == (size_t) -2) { // incomplete character return; } else if (result == (size_t) -1) { // invalid character ps = {}; wc = L'�'; } if (wc != L'\n') { display->putCharacter(cursorPos, wc, color); } else if (skipNewline) { skipNewline = false; return; } if (wc == L'\n' || cursorPos.x + 1 >= display->width()) { cursorPos.x = 0; if (cursorPos.y + 1 >= display->height()) { display->scroll(1, color); cursorPos.y = display->height() - 1; } else { cursorPos.y++; } skipNewline = wc != L'\n'; } else { cursorPos.x++; skipNewline = false; } } void TerminalDisplay::updateCursorPosition() { display->setCursorPos(cursorPos); } <|endoftext|>
<commit_before>/* Copyright (c) 2017 InversePalindrome Memento Mori - AnimationComponent.cpp InversePalindrome.com */ #include "AnimationComponent.hpp" #include <Thor/Animations/FrameAnimation.hpp> #include <fstream> AnimationComponent::AnimationComponent() : Component(Component::ID::Animation), animationID(AnimationID::Idle), animationDirection(Direction::Up), animationFramesFile() { } std::istringstream& AnimationComponent::readStream(std::istringstream& iStream) { iStream >> this->animationFramesFile; this->addAnimations(); return iStream; } AnimationID AnimationComponent::getAnimationID() const { return this->animationID; } Direction AnimationComponent::getAnimationDirection() const { return this->animationDirection; } void AnimationComponent::setAnimation(AnimationID animationID) { this->animationID = animationID; } void AnimationComponent::setAnimationDirection(Direction animationDiretion) { this->animationDirection = animationDiretion; } void AnimationComponent::setAnimationsFrameFile(const std::string& fileName) { this->animationFramesFile = fileName; } void AnimationComponent::update(sf::Time deltaTime) { this->animations.update(deltaTime); } void AnimationComponent::animate(sf::Sprite& sprite) const { this->animations.animate(sprite); } void AnimationComponent::playAnimation(bool loop) { this->animations.playAnimation(std::make_pair(this->getAnimationID(), this->getAnimationDirection()), loop); } void AnimationComponent::stopAnimation() { this->animations.stopAnimation(); } void AnimationComponent::addAnimation(AnimationID animationID, Direction direction, const thor::FrameAnimation& animation, sf::Time duration) { this->animations.addAnimation(std::make_pair(animationID, direction), animation, duration); } void AnimationComponent::addAnimations() { std::ifstream inFile(this->animationFramesFile); std::string line; std::getline(inFile, line); std::istringstream iStream(line); std::size_t iNumOfAnimations = 0; iStream >> iNumOfAnimations; for (std::size_t i = 0; i < iNumOfAnimations; ++i) { thor::FrameAnimation animation; std::getline(inFile, line); iStream.str(line); iStream.clear(); std::string iCategory; iStream >> iCategory; if (iCategory != "Animation") { break; } std::size_t iAnimationID, iDirection, iNumOfFrames = 0; float iAnimationTime = 0.f; iStream >> iAnimationID >> iDirection >> iNumOfFrames >> iAnimationTime; for (std::size_t j = 0; j < iNumOfFrames; ++j) { std::getline(inFile, line); iStream.str(line); iStream.clear(); iStream >> iCategory; if (iCategory == "Frame") { float iDuration = 0.f; iStream >> iDuration; std::size_t iLeft, iTop, iWidth, iHeight = 0u; iStream >> iLeft >> iTop >> iWidth >> iHeight; animation.addFrame(iDuration, sf::IntRect(iLeft, iTop, iWidth, iHeight)); } } this->addAnimation(static_cast<AnimationID>(iAnimationID), static_cast<Direction>(iDirection), animation, sf::seconds(iAnimationTime)); } } bool AnimationComponent::isPlayingAnimation() const { return this->animations.isPlayingAnimation(); }<commit_msg>Delete AnimationComponent.cpp<commit_after><|endoftext|>
<commit_before>#include "EntityLoggerSystem.h" #include "AntTweakBarWrapper.h" #include <ToString.h> EntityLoggerSystem::EntityLoggerSystem() : EntitySystem(SystemType::EntityLoggerSystem) { } EntityLoggerSystem::~EntityLoggerSystem() { } void EntityLoggerSystem::added( Entity* p_entity ) { AntTweakBarWrapper::getInstance()->addReadOnlyVariable(AntTweakBarWrapper::OVERALL, (toString(p_entity->getIndex()) + ": " + p_entity->getName()).c_str(), TwType::TW_TYPE_INT32, p_entity->getIndexPtr(), "group='entities'"); } void EntityLoggerSystem::deleted( Entity* p_entity ) { TwRemoveVar(AntTweakBarWrapper::getInstance()->getAntBar(AntTweakBarWrapper::OVERALL), (toString(p_entity->getIndex()) + ": " + p_entity->getName()).c_str()); }<commit_msg>Now truly disabled the EntityLoggerSystem. It had quite the impact to performance when creating many entities at once.<commit_after>#include "EntityLoggerSystem.h" #include "AntTweakBarWrapper.h" #include <ToString.h> EntityLoggerSystem::EntityLoggerSystem() : EntitySystem(SystemType::EntityLoggerSystem) { } EntityLoggerSystem::~EntityLoggerSystem() { } void EntityLoggerSystem::added( Entity* p_entity ) { if(this->getEnabled()) { AntTweakBarWrapper::getInstance()->addReadOnlyVariable(AntTweakBarWrapper::OVERALL, (toString(p_entity->getIndex()) + ": " + p_entity->getName()).c_str(), TwType::TW_TYPE_INT32, p_entity->getIndexPtr(), "group='entities'"); } } void EntityLoggerSystem::deleted( Entity* p_entity ) { if(this->getEnabled()) { TwRemoveVar(AntTweakBarWrapper::getInstance()->getAntBar(AntTweakBarWrapper::OVERALL), (toString(p_entity->getIndex()) + ": " + p_entity->getName()).c_str()); } }<|endoftext|>
<commit_before>#include <iostream> #include <pcl/io/pcd_io.h> #include <pcl/point_types.h> //using namespace pcl; int main (int argc, char** argv) { pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ>); if (pcl::io::loadPCDFile<pcl::PointXYZ> ("test_pcd.pcd", *cloud) == -1) //* load the file { PCL_ERROR ("Couldn't read file test_pcd.pcd \n"); return (-1); } std::cerr << "Loaded " << cloud->width * cloud->height << " data points from test_pcd.pcd with the following fields: " << std::endl; for (size_t i = 0; i < cloud->points.size (); ++i) std::cerr << " " << cloud->points[i].x << " " << cloud->points[i].y << " " << cloud->points[i].z << std::endl; return (0); } <commit_msg>removed using namespace pcl from code<commit_after>#include <iostream> #include <pcl/io/pcd_io.h> #include <pcl/point_types.h> int main (int argc, char** argv) { pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ>); if (pcl::io::loadPCDFile<pcl::PointXYZ> ("test_pcd.pcd", *cloud) == -1) //* load the file { PCL_ERROR ("Couldn't read file test_pcd.pcd \n"); return (-1); } std::cerr << "Loaded " << cloud->width * cloud->height << " data points from test_pcd.pcd with the following fields: " << std::endl; for (size_t i = 0; i < cloud->points.size (); ++i) std::cerr << " " << cloud->points[i].x << " " << cloud->points[i].y << " " << cloud->points[i].z << std::endl; return (0); } <|endoftext|>
<commit_before>#ifndef GDE_CORE_TYPES_HPP #define GDE_CORE_TYPES_HPP #include <map> #include <string> namespace GDE { // Fowards Declarations class App; class Scene; class SceneManager; class ConfigReader; class ConfigCreate; // Tipos de Log enum LogType { infoLevel = 0, debugLevel = 1, errorLevel = 2, warningLevel = 4 }; /// Enumaración con los posibles valores de retorno de la Aplicación enum StatusType { // Values from -99 to 99 are common Error and Good status responses StatusAppMissingAsset = -4, ///< Application failed due to missing asset file StatusAppStackEmpty = -3, ///< Application States stack is empty StatusAppInitFailed = -2, ///< Application initialization failed StatusError = -1, ///< General error status response StatusAppOK = 0, ///< Application quit without error StatusNoError = 0, ///< General no error status response StatusFalse = 0, ///< False status response StatusTrue = 1, ///< True status response StatusOK = 1 ///< OK status response // Values from +-100 to +-199 are reserved for File status responses }; /// Tipo de dato para identidicar las escenas typedef std::string sceneID; /// Declare NameValue typedef which is used for config section maps typedef std::map<const std::string, const std::string> typeNameValue; /// Declare NameValueIter typedef which is used for name,value pair maps typedef std::map<const std::string, const std::string>::iterator typeNameValueIter; } // namespace GDE #endif // GDE_CORE_TYPES_HPP <commit_msg>Fix enumerado log<commit_after>#ifndef GDE_CORE_TYPES_HPP #define GDE_CORE_TYPES_HPP #include <map> #include <string> namespace GDE { // Fowards Declarations class App; class Scene; class SceneManager; class ConfigReader; class ConfigCreate; // Tipos de Log enum LogType { infoLevel = 0, debugLevel = 1, errorLevel = 2, warningLevel = 3 }; /// Enumaración con los posibles valores de retorno de la Aplicación enum StatusType { // Values from -99 to 99 are common Error and Good status responses StatusAppMissingAsset = -4, ///< Application failed due to missing asset file StatusAppStackEmpty = -3, ///< Application States stack is empty StatusAppInitFailed = -2, ///< Application initialization failed StatusError = -1, ///< General error status response StatusAppOK = 0, ///< Application quit without error StatusNoError = 0, ///< General no error status response StatusFalse = 0, ///< False status response StatusTrue = 1, ///< True status response StatusOK = 1 ///< OK status response // Values from +-100 to +-199 are reserved for File status responses }; /// Tipo de dato para identidicar las escenas typedef std::string sceneID; /// Declare NameValue typedef which is used for config section maps typedef std::map<const std::string, const std::string> typeNameValue; /// Declare NameValueIter typedef which is used for name,value pair maps typedef std::map<const std::string, const std::string>::iterator typeNameValueIter; } // namespace GDE #endif // GDE_CORE_TYPES_HPP <|endoftext|>
<commit_before>// Copyright (C) 2014 Jérôme Leclercq // This file is part of the "Nazara Engine - Core module" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/Core/Debug.hpp> namespace std { template<> struct hash<NzString> { public: size_t operator()(const NzString& str) const { // Algorithme DJB2 // http://www.cse.yorku.ca/~oz/hash.html size_t h = 5381; if (!str.IsEmpty()) { const char* ptr = str.GetConstBuffer(); do h = ((h << 5) + h) + *ptr; while (*++ptr); } return h; } }; } #include <Nazara/Core/DebugOff.hpp> <commit_msg>Removed useless keyword<commit_after>// Copyright (C) 2014 Jérôme Leclercq // This file is part of the "Nazara Engine - Core module" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/Core/Debug.hpp> namespace std { template<> struct hash<NzString> { size_t operator()(const NzString& str) const { // Algorithme DJB2 // http://www.cse.yorku.ca/~oz/hash.html size_t h = 5381; if (!str.IsEmpty()) { const char* ptr = str.GetConstBuffer(); do h = ((h << 5) + h) + *ptr; while (*++ptr); } return h; } }; } #include <Nazara/Core/DebugOff.hpp> <|endoftext|>
<commit_before>#pragma once #ifndef DEBUG_H #define DEBUG_H #include <UtH\Platform\OpenGL.hpp> #include <assert.h> #include <iostream> #include <AL\al.h> #include <AL\alc.h> #if defined(UTH_SYSTEM_ANDROID) #include <android/log.h> #ifndef LOG_TAG #define LOG_TAG "uth-engine" #endif #ifndef LOGI #define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__) #endif #ifndef LOGE #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__) #endif void WriteLog(const char* text, ...) { va_list v; va_start(v, text); __android_log_vprint(ANDROID_LOG_INFO, LOG_TAG, text, v); va_end(v); } #elif defined(UTH_SYSTEM_WINDOWS) void WriteLog(const char* text, ...) { va_list v; va_start(v, text); vprintf(text, v); va_end(v); } #endif void PrintGLString(const char* name, GLenum s) { const char *v = (const char *) glGetString(s); WriteLog("GL %s = %s\n", name, v); } void CheckGLError(const char* op) { for (GLint error = glGetError(); error; error = glGetError()) { WriteLog("after %s() glError (0x%x)\n", op, error); } } void CheckALError(const char* op) { for(ALCenum error = alGetError(); error != AL_NO_ERROR; error = alGetError()) { WriteLog("after %s() glError (0x%x)\n", op, error); } } void Win32Assert(int expression) { assert(expression); } #endif<commit_msg>Made debug functions as static<commit_after>#pragma once #ifndef DEBUG_H #define DEBUG_H #include <UtH\Platform\OpenGL.hpp> #include <assert.h> #include <iostream> #include <AL\al.h> #include <AL\alc.h> #if defined(UTH_SYSTEM_ANDROID) #include <android/log.h> #ifndef LOG_TAG #define LOG_TAG "uth-engine" #endif #ifndef LOGI #define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__) #endif #ifndef LOGE #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__) #endif static void WriteLog(const char* text, ...) { va_list v; va_start(v, text); __android_log_vprint(ANDROID_LOG_INFO, LOG_TAG, text, v); va_end(v); } #elif defined(UTH_SYSTEM_WINDOWS) static void WriteLog(const char* text, ...) { va_list v; va_start(v, text); vprintf(text, v); va_end(v); } #endif static void PrintGLString(const char* name, GLenum s) { const char *v = (const char *) glGetString(s); WriteLog("GL %s = %s\n", name, v); } static void CheckGLError(const char* op) { for (GLint error = glGetError(); error; error = glGetError()) { WriteLog("after %s() glError (0x%x)\n", op, error); } } static void CheckALError(const char* op) { for(ALCenum error = alGetError(); error != AL_NO_ERROR; error = alGetError()) { WriteLog("after %s() glError (0x%x)\n", op, error); } } static void Win32Assert(int expression) { assert(expression); } #endif<|endoftext|>
<commit_before>#ifndef GP_PROBLEM_PROBLEM #define GP_PROBLEM_PROBLEM #include <any> #include <algorithm> #include <gp/utility/type.hpp> #include <gp/utility/variable.hpp> #include <gp/utility/result.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/xml_parser.hpp> #include <climits> #include <iostream> namespace gp::problem { namespace detail { template <std::size_t offset, typename ...Ts> utility::Result<utility::Variable> stringToVariableHelper(const std::string& str, const utility::TypeInfo& type, const std::tuple<std::function<Ts(const std::string&)>...>& stringToValues){ if(type == utility::typeInfo< typename std::tuple_element_t<offset, std::decay_t<decltype(stringToValues)>>::result_type >()) return utility::result::ok(utility::Variable(std::get<offset>(stringToValues)(str))); if constexpr (offset + 1 < std::tuple_size_v<std::decay_t<decltype(stringToValues)>>) { return stringToVariableHelper<offset + 1>(str, type, stringToValues); } else { return utility::result::err<utility::Variable>("failed to load problem, string to value conversion function of " + type.name() + "not registerd"); } }; template <typename ...Ts> utility::Result<utility::Variable> stringToVariable(const std::string& str, const utility::TypeInfo& type, const std::tuple<std::function<Ts(const std::string&)>...>& stringToValues) { return stringToVariableHelper<0>(str, type, stringToValues); } } namespace io { constexpr const char* ROOT_FIELD = "problem"; constexpr const char* NAME_FIELD = "name"; constexpr const char* RETURN_TYPE_FIELD = "return_type"; constexpr const char* ARGUMENTS_FIELD = "arguments"; constexpr const char* VARIABLE_TYPE_FIELD = "type"; constexpr const char* TEACHER_DATA_SET_FIELD = "teacher_data_set"; constexpr const char* TEACHER_DATA_FIELD = "data"; constexpr const char* TEACHER_DATA_ARGUMENT_FIELD = "argument"; constexpr const char* TEACHER_DATA_ARGUMENT_INDEX_ARRIBUTE = "idx"; constexpr const char* TEACHER_DATA_ANSWER_FIELD = "answer"; constexpr int MAX_NUM_DIGITS = [](){ int x = INT_MAX; int cnt = 0; while(x > 0){ ++cnt; x /= 10; } return cnt; }(); } struct Problem { using AnsArgPair = std::tuple<utility::Variable, std::vector<utility::Variable>>; //first: ans, second: args std::string name; const utility::TypeInfo* returnType; std::vector<const utility::TypeInfo*> argumentTypes; std::vector<AnsArgPair> ansArgList; }; template <typename ...SupportTypes> utility::Result<Problem> load(std::istream& in, const utility::StringToType& stringToType, const std::tuple<std::function<SupportTypes(const std::string&)>...>& stringToValues){ using namespace boost::property_tree; ptree tree; try { xml_parser::read_xml(in, tree); } catch (const std::exception& ex) { return utility::result::err<Problem>(std::string("failed to load problem\n") + ex.what()); } Problem problem1; //get problem name auto nameResult = utility::result::fromOptional(tree.template get_optional<std::string>(std::string(io::ROOT_FIELD) + "." + io::NAME_FIELD), "failed to load problem, name field not found."); if(!nameResult) return utility::result::err<Problem>(std::move(nameResult).errMessage()); problem1.name = std::move(nameResult).unwrap(); //get return type auto returnTypeResult = utility::result::fromOptional(tree.template get_optional<std::string>(std::string(io::ROOT_FIELD) + "." + io::RETURN_TYPE_FIELD), "failed to load problem, return_type field not found.") .flatMap([&stringToType](const std::string& typeName){ using ResultType = const utility::TypeInfo*; if(!stringToType.hasType(typeName)) return utility::result::err<ResultType>("failed to load problem, unknown type name \"" + typeName + "\""); else return utility::result::ok(&stringToType(typeName)); }); if(!returnTypeResult) return utility::result::err<Problem>(std::move(returnTypeResult).errMessage()); problem1.returnType = std::move(returnTypeResult).unwrap(); //get argument types auto argsResult = utility::result::fromOptional(tree.get_child_optional(std::string(io::ROOT_FIELD) + "." + io::ARGUMENTS_FIELD), "failed to load problem, arguments field not found") .flatMap([&stringToType](ptree& child){ using ResultType = decltype(Problem{}.argumentTypes); ResultType argumentTypes; for(const auto& [key, val]: child) { if(key != io::VARIABLE_TYPE_FIELD) continue; const auto& typeStr = val.data(); if(!stringToType.hasType(typeStr)) return utility::result::err<ResultType>(std::string("failed to load problem, unknown argument type name \"") + typeStr + "\""); argumentTypes.push_back(&stringToType(typeStr)); } return utility::result::ok(std::move(argumentTypes)); }); if(!argsResult) return utility::result::err<Problem>(std::move(argsResult).errMessage()); problem1.argumentTypes = std::move(argsResult).unwrap(); //get teacher data set auto teacherDataResult = utility::result::fromOptional(tree.get_child_optional(std::string(io::ROOT_FIELD) + "." + io::TEACHER_DATA_SET_FIELD), "failed to load problem, teacher_data_set field not found") .flatMap([&problem1, &stringToValues, argNum = std::size(problem1.argumentTypes)](ptree& child){ using ResultType = decltype(Problem{}.ansArgList); ResultType ansArgList; for(const auto& [key, value]: child) { if(key != io::TEACHER_DATA_FIELD)continue; auto dataResult = utility::result::fromOptional(value.template get_optional<std::string>(io::TEACHER_DATA_ANSWER_FIELD), "failed to load problem, answer field not found in the data field.") .flatMap([&stringToValues, &problem1](auto&& answerStr){ return detail::stringToVariable(answerStr, *problem1.returnType, stringToValues); }); if(!dataResult) return utility::result::err<ResultType>(std::move(dataResult).errMessage()); auto ans = std::move(dataResult).unwrap(); std::vector<utility::Variable> args(argNum); for(const auto& [dataKey, dataValue]: value) { if(dataKey != io::TEACHER_DATA_ARGUMENT_FIELD) continue; auto idxResult = utility::result::fromOptional(dataValue.template get_optional<std::string>(std::string("<xmlattr>.") + io::TEACHER_DATA_ARGUMENT_INDEX_ARRIBUTE), "failed to load problem, idx attribute not found int the argument field") .flatMap([](auto&& idxStr){ if(idxStr.empty() || !std::all_of(std::begin(idxStr), std::end(idxStr), [](auto c){return '0' <= c && c <= '9';}) || (1 < std::size(idxStr) && idxStr[0] == '0') || io::MAX_NUM_DIGITS < std::size(idxStr)) return utility::result::err<int>("failed to load problem, invalid idx \"" + idxStr + "\""); auto idx = std::stoll(idxStr); if (static_cast<long long>(INT_MAX) < idx) return utility::result::err<int>("failed to load problem, invalid idx \"" + idxStr + "\""); return utility::result::ok(static_cast<int>(idx)); }).flatMap([argNum = std::size(problem1.argumentTypes)](int idx){ if(idx < 0 || argNum <= idx) return utility::result::err<int>("failed to load problem, invalid idx \"" + std::to_string(idx) + "\""); else return utility::result::ok(idx); }); if(!idxResult) return utility::result::err<ResultType>(std::move(idxResult).errMessage()); auto idx = idxResult.unwrap(); auto argResult = detail::stringToVariable(dataValue.data(), *problem1.argumentTypes[idx], stringToValues); if(!argResult) return utility::result::err<ResultType>(std::move(argResult).errMessage()); args[idx] = std::move(argResult).unwrap(); } if(!std::all_of(std::begin(args), std::end(args), [](auto x)->bool{return static_cast<bool>(x);})) return utility::result::err<ResultType>("failed to load problem, some argument is lacking"); ansArgList.push_back(std::make_tuple(std::move(ans), std::move(args))); } return utility::result::ok(std::move(ansArgList)); }); if(!teacherDataResult) return utility::result::err<Problem>(std::move(teacherDataResult).errMessage()); problem1.ansArgList = std::move(teacherDataResult).unwrap(); return utility::result::ok(std::move(problem1)); } } #endif <commit_msg>simolify the call of utility::result::<commit_after>#ifndef GP_PROBLEM_PROBLEM #define GP_PROBLEM_PROBLEM #include <any> #include <algorithm> #include <gp/utility/type.hpp> #include <gp/utility/variable.hpp> #include <gp/utility/result.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/xml_parser.hpp> #include <climits> #include <iostream> namespace gp::problem { namespace detail { template <std::size_t offset, typename ...Ts> utility::Result<utility::Variable> stringToVariableHelper(const std::string& str, const utility::TypeInfo& type, const std::tuple<std::function<Ts(const std::string&)>...>& stringToValues){ if(type == utility::typeInfo< typename std::tuple_element_t<offset, std::decay_t<decltype(stringToValues)>>::result_type >()) return utility::result::ok(utility::Variable(std::get<offset>(stringToValues)(str))); if constexpr (offset + 1 < std::tuple_size_v<std::decay_t<decltype(stringToValues)>>) { return stringToVariableHelper<offset + 1>(str, type, stringToValues); } else { return utility::result::err<utility::Variable>("failed to load problem, string to value conversion function of " + type.name() + "not registerd"); } }; template <typename ...Ts> utility::Result<utility::Variable> stringToVariable(const std::string& str, const utility::TypeInfo& type, const std::tuple<std::function<Ts(const std::string&)>...>& stringToValues) { return stringToVariableHelper<0>(str, type, stringToValues); } } namespace io { constexpr const char* ROOT_FIELD = "problem"; constexpr const char* NAME_FIELD = "name"; constexpr const char* RETURN_TYPE_FIELD = "return_type"; constexpr const char* ARGUMENTS_FIELD = "arguments"; constexpr const char* VARIABLE_TYPE_FIELD = "type"; constexpr const char* TEACHER_DATA_SET_FIELD = "teacher_data_set"; constexpr const char* TEACHER_DATA_FIELD = "data"; constexpr const char* TEACHER_DATA_ARGUMENT_FIELD = "argument"; constexpr const char* TEACHER_DATA_ARGUMENT_INDEX_ARRIBUTE = "idx"; constexpr const char* TEACHER_DATA_ANSWER_FIELD = "answer"; constexpr int MAX_NUM_DIGITS = [](){ int x = INT_MAX; int cnt = 0; while(x > 0){ ++cnt; x /= 10; } return cnt; }(); } struct Problem { using AnsArgPair = std::tuple<utility::Variable, std::vector<utility::Variable>>; //first: ans, second: args std::string name; const utility::TypeInfo* returnType; std::vector<const utility::TypeInfo*> argumentTypes; std::vector<AnsArgPair> ansArgList; }; template <typename ...SupportTypes> utility::Result<Problem> load(std::istream& in, const utility::StringToType& stringToType, const std::tuple<std::function<SupportTypes(const std::string&)>...>& stringToValues){ using namespace boost::property_tree; using namespace utility; ptree tree; try { xml_parser::read_xml(in, tree); } catch (const std::exception& ex) { return result::err<Problem>(std::string("failed to load problem\n") + ex.what()); } Problem problem1; //get problem name auto nameResult = result::fromOptional(tree.template get_optional<std::string>(std::string(io::ROOT_FIELD) + "." + io::NAME_FIELD), "failed to load problem, name field not found."); if(!nameResult) return result::err<Problem>(std::move(nameResult).errMessage()); problem1.name = std::move(nameResult).unwrap(); //get return type auto returnTypeResult = result::fromOptional(tree.template get_optional<std::string>(std::string(io::ROOT_FIELD) + "." + io::RETURN_TYPE_FIELD), "failed to load problem, return_type field not found.") .flatMap([&stringToType](const std::string& typeName){ using ResultType = const TypeInfo*; if(!stringToType.hasType(typeName)) return result::err<ResultType>("failed to load problem, unknown type name \"" + typeName + "\""); else return result::ok(&stringToType(typeName)); }); if(!returnTypeResult) return result::err<Problem>(std::move(returnTypeResult).errMessage()); problem1.returnType = std::move(returnTypeResult).unwrap(); //get argument types auto argsResult = result::fromOptional(tree.get_child_optional(std::string(io::ROOT_FIELD) + "." + io::ARGUMENTS_FIELD), "failed to load problem, arguments field not found") .flatMap([&stringToType](ptree& child){ using ResultType = decltype(Problem{}.argumentTypes); ResultType argumentTypes; for(const auto& [key, val]: child) { if(key != io::VARIABLE_TYPE_FIELD) continue; const auto& typeStr = val.data(); if(!stringToType.hasType(typeStr)) return result::err<ResultType>(std::string("failed to load problem, unknown argument type name \"") + typeStr + "\""); argumentTypes.push_back(&stringToType(typeStr)); } return result::ok(std::move(argumentTypes)); }); if(!argsResult) return result::err<Problem>(std::move(argsResult).errMessage()); problem1.argumentTypes = std::move(argsResult).unwrap(); //get teacher data set auto teacherDataResult = result::fromOptional(tree.get_child_optional(std::string(io::ROOT_FIELD) + "." + io::TEACHER_DATA_SET_FIELD), "failed to load problem, teacher_data_set field not found") .flatMap([&problem1, &stringToValues, argNum = std::size(problem1.argumentTypes)](ptree& child){ using ResultType = decltype(Problem{}.ansArgList); ResultType ansArgList; for(const auto& [key, value]: child) { if(key != io::TEACHER_DATA_FIELD)continue; auto dataResult = result::fromOptional(value.template get_optional<std::string>(io::TEACHER_DATA_ANSWER_FIELD), "failed to load problem, answer field not found in the data field.") .flatMap([&stringToValues, &problem1](auto&& answerStr){ return detail::stringToVariable(answerStr, *problem1.returnType, stringToValues); }); if(!dataResult) return result::err<ResultType>(std::move(dataResult).errMessage()); auto ans = std::move(dataResult).unwrap(); std::vector<Variable> args(argNum); for(const auto& [dataKey, dataValue]: value) { if(dataKey != io::TEACHER_DATA_ARGUMENT_FIELD) continue; auto idxResult = result::fromOptional(dataValue.template get_optional<std::string>(std::string("<xmlattr>.") + io::TEACHER_DATA_ARGUMENT_INDEX_ARRIBUTE), "failed to load problem, idx attribute not found int the argument field") .flatMap([](auto&& idxStr){ if(idxStr.empty() || !std::all_of(std::begin(idxStr), std::end(idxStr), [](auto c){return '0' <= c && c <= '9';}) || (1 < std::size(idxStr) && idxStr[0] == '0') || io::MAX_NUM_DIGITS < std::size(idxStr)) return result::err<int>("failed to load problem, invalid idx \"" + idxStr + "\""); auto idx = std::stoll(idxStr); if (static_cast<long long>(INT_MAX) < idx) return result::err<int>("failed to load problem, invalid idx \"" + idxStr + "\""); return result::ok(static_cast<int>(idx)); }).flatMap([argNum = std::size(problem1.argumentTypes)](int idx){ if(idx < 0 || argNum <= idx) return result::err<int>("failed to load problem, invalid idx \"" + std::to_string(idx) + "\""); else return result::ok(idx); }); if(!idxResult) return result::err<ResultType>(std::move(idxResult).errMessage()); auto idx = idxResult.unwrap(); auto argResult = detail::stringToVariable(dataValue.data(), *problem1.argumentTypes[idx], stringToValues); if(!argResult) return result::err<ResultType>(std::move(argResult).errMessage()); args[idx] = std::move(argResult).unwrap(); } if(!std::all_of(std::begin(args), std::end(args), [](auto x)->bool{return static_cast<bool>(x);})) return result::err<ResultType>("failed to load problem, some argument is lacking"); ansArgList.push_back(std::make_tuple(std::move(ans), std::move(args))); } return result::ok(std::move(ansArgList)); }); if(!teacherDataResult) return result::err<Problem>(std::move(teacherDataResult).errMessage()); problem1.ansArgList = std::move(teacherDataResult).unwrap(); return result::ok(std::move(problem1)); } } #endif <|endoftext|>
<commit_before>/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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. */ #ifndef TORRENT_PEER_ID_HPP_INCLUDED #define TORRENT_PEER_ID_HPP_INCLUDED #include <cctype> #include <algorithm> #include <string> #include <cstring> #include "libtorrent/config.hpp" #include "libtorrent/assert.hpp" #if TORRENT_USE_IOSTREAM #include "libtorrent/escape_string.hpp" // to_hex, from_hex #include <iostream> #include <iomanip> #endif #ifdef max #undef max #endif #ifdef min #undef min #endif namespace libtorrent { class TORRENT_EXPORT big_number { // the number of bytes of the number enum { number_size = 20 }; public: enum { size = number_size }; big_number() { clear(); } static big_number max() { big_number ret; memset(ret.m_number, 0xff, size); return ret; } static big_number min() { big_number ret; memset(ret.m_number, 0, size); return ret; } explicit big_number(char const* s) { if (s == 0) clear(); else std::memcpy(m_number, s, size); } explicit big_number(std::string const& s) { TORRENT_ASSERT(s.size() >= 20); int sl = int(s.size()) < size ? int(s.size()) : size; std::memcpy(m_number, s.c_str(), sl); } void assign(std::string const& s) { TORRENT_ASSERT(s.size() >= 20); int sl = int(s.size()) < size ? int(s.size()) : size; std::memcpy(m_number, s.c_str(), sl); } void assign(char const* str) { std::memcpy(m_number, str, size); } void clear() { std::memset(m_number, 0, number_size); } bool is_all_zeros() const { for (const unsigned char* i = m_number; i < m_number+number_size; ++i) if (*i != 0) return false; return true; } big_number& operator<<=(int n) { TORRENT_ASSERT(n >= 0); if (n > number_size * 8) n = number_size; int num_bytes = n / 8; if (num_bytes >= number_size) { std::memset(m_number, 0, number_size); return *this; } if (num_bytes > 0) { std::memmove(m_number, m_number + num_bytes, number_size - num_bytes); std::memset(m_number + number_size - num_bytes, 0, num_bytes); n -= num_bytes * 8; } if (n > 0) { for (int i = 0; i < number_size - 1; ++i) { m_number[i] <<= n; m_number[i] |= m_number[i+1] >> (8 - n); } } return *this; } big_number& operator>>=(int n) { int num_bytes = n / 8; if (num_bytes >= number_size) { std::memset(m_number, 0, number_size); return *this; } if (num_bytes > 0) { std::memmove(m_number + num_bytes, m_number, number_size - num_bytes); std::memset(m_number, 0, num_bytes); n -= num_bytes * 8; } if (n > 0) { for (int i = number_size - 1; i > 0; --i) { m_number[i] >>= n; m_number[i] |= m_number[i-1] << (8 - n); } } return *this; } bool operator==(big_number const& n) const { return std::equal(n.m_number, n.m_number+number_size, m_number); } bool operator!=(big_number const& n) const { return !std::equal(n.m_number, n.m_number+number_size, m_number); } bool operator<(big_number const& n) const { for (int i = 0; i < number_size; ++i) { if (m_number[i] < n.m_number[i]) return true; if (m_number[i] > n.m_number[i]) return false; } return false; } big_number operator~() { big_number ret; for (int i = 0; i< number_size; ++i) ret.m_number[i] = ~m_number[i]; return ret; } big_number operator^ (big_number const& n) const { big_number ret = *this; ret ^= n; return ret; } big_number operator& (big_number const& n) const { big_number ret = *this; ret &= n; return ret; } big_number& operator &= (big_number const& n) { for (int i = 0; i< number_size; ++i) m_number[i] &= n.m_number[i]; return *this; } big_number& operator |= (big_number const& n) { for (int i = 0; i< number_size; ++i) m_number[i] |= n.m_number[i]; return *this; } big_number& operator ^= (big_number const& n) { for (int i = 0; i< number_size; ++i) m_number[i] ^= n.m_number[i]; return *this; } unsigned char& operator[](int i) { TORRENT_ASSERT(i >= 0 && i < number_size); return m_number[i]; } unsigned char const& operator[](int i) const { TORRENT_ASSERT(i >= 0 && i < number_size); return m_number[i]; } typedef const unsigned char* const_iterator; typedef unsigned char* iterator; const_iterator begin() const { return m_number; } const_iterator end() const { return m_number+number_size; } iterator begin() { return m_number; } iterator end() { return m_number+number_size; } std::string to_string() const { return std::string((char const*)&m_number[0], number_size); } private: unsigned char m_number[number_size]; }; typedef big_number peer_id; typedef big_number sha1_hash; #if TORRENT_USE_IOSTREAM inline std::ostream& operator<<(std::ostream& os, big_number const& peer) { char out[41]; to_hex((char const*)&peer[0], big_number::size, out); return os << out; } inline std::istream& operator>>(std::istream& is, big_number& peer) { char hex[40]; is.read(hex, 40); if (!from_hex(hex, 40, (char*)&peer[0])) is.setstate(std::ios_base::failbit); return is; } #endif // TORRENT_USE_IOSTREAM } #endif // TORRENT_PEER_ID_HPP_INCLUDED <commit_msg>fix issue in big_number shift left operator<commit_after>/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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. */ #ifndef TORRENT_PEER_ID_HPP_INCLUDED #define TORRENT_PEER_ID_HPP_INCLUDED #include <cctype> #include <algorithm> #include <string> #include <cstring> #include "libtorrent/config.hpp" #include "libtorrent/assert.hpp" #if TORRENT_USE_IOSTREAM #include "libtorrent/escape_string.hpp" // to_hex, from_hex #include <iostream> #include <iomanip> #endif #ifdef max #undef max #endif #ifdef min #undef min #endif namespace libtorrent { class TORRENT_EXPORT big_number { // the number of bytes of the number enum { number_size = 20 }; public: enum { size = number_size }; big_number() { clear(); } static big_number max() { big_number ret; memset(ret.m_number, 0xff, size); return ret; } static big_number min() { big_number ret; memset(ret.m_number, 0, size); return ret; } explicit big_number(char const* s) { if (s == 0) clear(); else std::memcpy(m_number, s, size); } explicit big_number(std::string const& s) { TORRENT_ASSERT(s.size() >= 20); int sl = int(s.size()) < size ? int(s.size()) : size; std::memcpy(m_number, s.c_str(), sl); } void assign(std::string const& s) { TORRENT_ASSERT(s.size() >= 20); int sl = int(s.size()) < size ? int(s.size()) : size; std::memcpy(m_number, s.c_str(), sl); } void assign(char const* str) { std::memcpy(m_number, str, size); } void clear() { std::memset(m_number, 0, number_size); } bool is_all_zeros() const { for (const unsigned char* i = m_number; i < m_number+number_size; ++i) if (*i != 0) return false; return true; } big_number& operator<<=(int n) { TORRENT_ASSERT(n >= 0); int num_bytes = n / 8; if (num_bytes >= number_size) { std::memset(m_number, 0, number_size); return *this; } if (num_bytes > 0) { std::memmove(m_number, m_number + num_bytes, number_size - num_bytes); std::memset(m_number + number_size - num_bytes, 0, num_bytes); n -= num_bytes * 8; } if (n > 0) { for (int i = 0; i < number_size - 1; ++i) { m_number[i] <<= n; m_number[i] |= m_number[i+1] >> (8 - n); } } return *this; } big_number& operator>>=(int n) { TORRENT_ASSERT(n >= 0); int num_bytes = n / 8; if (num_bytes >= number_size) { std::memset(m_number, 0, number_size); return *this; } if (num_bytes > 0) { std::memmove(m_number + num_bytes, m_number, number_size - num_bytes); std::memset(m_number, 0, num_bytes); n -= num_bytes * 8; } if (n > 0) { for (int i = number_size - 1; i > 0; --i) { m_number[i] >>= n; m_number[i] |= m_number[i-1] << (8 - n); } } return *this; } bool operator==(big_number const& n) const { return std::equal(n.m_number, n.m_number+number_size, m_number); } bool operator!=(big_number const& n) const { return !std::equal(n.m_number, n.m_number+number_size, m_number); } bool operator<(big_number const& n) const { for (int i = 0; i < number_size; ++i) { if (m_number[i] < n.m_number[i]) return true; if (m_number[i] > n.m_number[i]) return false; } return false; } big_number operator~() { big_number ret; for (int i = 0; i< number_size; ++i) ret.m_number[i] = ~m_number[i]; return ret; } big_number operator^ (big_number const& n) const { big_number ret = *this; ret ^= n; return ret; } big_number operator& (big_number const& n) const { big_number ret = *this; ret &= n; return ret; } big_number& operator &= (big_number const& n) { for (int i = 0; i< number_size; ++i) m_number[i] &= n.m_number[i]; return *this; } big_number& operator |= (big_number const& n) { for (int i = 0; i< number_size; ++i) m_number[i] |= n.m_number[i]; return *this; } big_number& operator ^= (big_number const& n) { for (int i = 0; i< number_size; ++i) m_number[i] ^= n.m_number[i]; return *this; } unsigned char& operator[](int i) { TORRENT_ASSERT(i >= 0 && i < number_size); return m_number[i]; } unsigned char const& operator[](int i) const { TORRENT_ASSERT(i >= 0 && i < number_size); return m_number[i]; } typedef const unsigned char* const_iterator; typedef unsigned char* iterator; const_iterator begin() const { return m_number; } const_iterator end() const { return m_number+number_size; } iterator begin() { return m_number; } iterator end() { return m_number+number_size; } std::string to_string() const { return std::string((char const*)&m_number[0], number_size); } private: unsigned char m_number[number_size]; }; typedef big_number peer_id; typedef big_number sha1_hash; #if TORRENT_USE_IOSTREAM inline std::ostream& operator<<(std::ostream& os, big_number const& peer) { char out[41]; to_hex((char const*)&peer[0], big_number::size, out); return os << out; } inline std::istream& operator>>(std::istream& is, big_number& peer) { char hex[40]; is.read(hex, 40); if (!from_hex(hex, 40, (char*)&peer[0])) is.setstate(std::ios_base::failbit); return is; } #endif // TORRENT_USE_IOSTREAM } #endif // TORRENT_PEER_ID_HPP_INCLUDED <|endoftext|>
<commit_before>/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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. */ #ifndef TORRENT_STORAGE_HPP_INCLUDE #define TORRENT_STORAGE_HPP_INCLUDE #include <vector> #include <bitset> #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/limits.hpp> #include <boost/thread.hpp> #include <boost/shared_ptr.hpp> #include <boost/intrusive_ptr.hpp> #include <boost/filesystem/path.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif #include "libtorrent/torrent_info.hpp" #include "libtorrent/piece_picker.hpp" #include "libtorrent/intrusive_ptr_base.hpp" #include "libtorrent/peer_request.hpp" #include "libtorrent/hasher.hpp" #include "libtorrent/config.hpp" namespace libtorrent { namespace aux { struct piece_checker_data; } namespace fs = boost::filesystem; class session; struct file_pool; struct disk_io_job; enum storage_mode_t { storage_mode_allocate = 0, storage_mode_sparse, storage_mode_compact }; #if defined(_WIN32) && defined(UNICODE) TORRENT_EXPORT std::wstring safe_convert(std::string const& s); #endif TORRENT_EXPORT std::vector<std::pair<size_type, std::time_t> > get_filesizes( torrent_info const& t , fs::path p); TORRENT_EXPORT bool match_filesizes( torrent_info const& t , fs::path p , std::vector<std::pair<size_type, std::time_t> > const& sizes , bool compact_mode , std::string* error = 0); struct TORRENT_EXPORT file_allocation_failed: std::exception { file_allocation_failed(const char* error_msg): m_msg(error_msg) {} virtual const char* what() const throw() { return m_msg.c_str(); } virtual ~file_allocation_failed() throw() {} std::string m_msg; }; struct TORRENT_EXPORT partial_hash { partial_hash(): offset(0) {} // the number of bytes in the piece that has been hashed int offset; // the sha-1 context hasher h; }; struct TORRENT_EXPORT storage_interface { // create directories and set file sizes // if allocate_files is true. // allocate_files is true if allocation mode // is set to full and sparse files are supported virtual void initialize(bool allocate_files) = 0; // may throw file_error if storage for slot does not exist virtual size_type read(char* buf, int slot, int offset, int size) = 0; // may throw file_error if storage for slot hasn't been allocated virtual void write(const char* buf, int slot, int offset, int size) = 0; virtual bool move_storage(fs::path save_path) = 0; // verify storage dependent fast resume entries virtual bool verify_resume_data(entry& rd, std::string& error) = 0; // write storage dependent fast resume entries virtual void write_resume_data(entry& rd) const = 0; // moves (or copies) the content in src_slot to dst_slot virtual void move_slot(int src_slot, int dst_slot) = 0; // swaps the data in slot1 and slot2 virtual void swap_slots(int slot1, int slot2) = 0; // swaps the puts the data in slot1 in slot2, the data in slot2 // in slot3 and the data in slot3 in slot1 virtual void swap_slots3(int slot1, int slot2, int slot3) = 0; // returns the sha1-hash for the data at the given slot virtual sha1_hash hash_for_slot(int slot, partial_hash& h, int piece_size) = 0; // this will close all open files that are opened for // writing. This is called when a torrent has finished // downloading. virtual void release_files() = 0; virtual ~storage_interface() {} }; typedef storage_interface* (&storage_constructor_type)( boost::intrusive_ptr<torrent_info const>, fs::path const& , file_pool&); TORRENT_EXPORT storage_interface* default_storage_constructor( boost::intrusive_ptr<torrent_info const> ti , fs::path const& path, file_pool& fp); // returns true if the filesystem the path relies on supports // sparse files or automatic zero filling of files. TORRENT_EXPORT bool supports_sparse_files(fs::path const& p); struct disk_io_thread; class TORRENT_EXPORT piece_manager : public intrusive_ptr_base<piece_manager> , boost::noncopyable { friend class invariant_access; friend struct disk_io_thread; public: piece_manager( boost::shared_ptr<void> const& torrent , boost::intrusive_ptr<torrent_info const> ti , fs::path const& path , file_pool& fp , disk_io_thread& io , storage_constructor_type sc); ~piece_manager(); bool check_fastresume(aux::piece_checker_data& d , std::vector<bool>& pieces, int& num_pieces, storage_mode_t storage_mode , std::string& error_msg); std::pair<bool, float> check_files(std::vector<bool>& pieces , int& num_pieces, boost::recursive_mutex& mutex); // frees a buffer that was returned from a read operation void free_buffer(char* buf); void write_resume_data(entry& rd) const; bool verify_resume_data(entry& rd, std::string& error); bool is_allocating() const { return m_state == state_expand_pieces; } void mark_failed(int index); unsigned long piece_crc( int slot_index , int block_size , piece_picker::block_info const* bi); int slot_for(int piece) const; int piece_for(int slot) const; void async_read( peer_request const& r , boost::function<void(int, disk_io_job const&)> const& handler , char* buffer = 0 , int priority = 0); void async_write( peer_request const& r , char const* buffer , boost::function<void(int, disk_io_job const&)> const& f); void async_hash(int piece, boost::function<void(int, disk_io_job const&)> const& f); fs::path save_path() const; void async_release_files( boost::function<void(int, disk_io_job const&)> const& handler = boost::function<void(int, disk_io_job const&)>()); void async_move_storage(fs::path const& p , boost::function<void(int, disk_io_job const&)> const& handler); // fills the vector that maps all allocated // slots to the piece that is stored (or // partially stored) there. -2 is the index // of unassigned pieces and -1 is unallocated void export_piece_map(std::vector<int>& pieces , std::vector<bool> const& have) const; bool compact_allocation() const { return m_storage_mode == storage_mode_compact; } #ifndef NDEBUG std::string name() const { return m_info->name(); } #endif private: bool allocate_slots(int num_slots, bool abort_on_disk = false); int identify_data( const std::vector<char>& piece_data , int current_slot , std::vector<bool>& have_pieces , int& num_pieces , const std::multimap<sha1_hash, int>& hash_to_piece , boost::recursive_mutex& mutex); size_type read_impl( char* buf , int piece_index , int offset , int size); void write_impl( const char* buf , int piece_index , int offset , int size); void switch_to_full_mode(); sha1_hash hash_for_piece_impl(int piece); void release_files_impl(); bool move_storage_impl(fs::path const& save_path); int allocate_slot_for_piece(int piece_index); #ifndef NDEBUG void check_invariant() const; #ifdef TORRENT_STORAGE_DEBUG void debug_log() const; #endif #endif boost::scoped_ptr<storage_interface> m_storage; storage_mode_t m_storage_mode; // a bitmask representing the pieces we have std::vector<bool> m_have_piece; boost::intrusive_ptr<torrent_info const> m_info; // slots that haven't had any file storage allocated std::vector<int> m_unallocated_slots; // slots that have file storage, but isn't assigned to a piece std::vector<int> m_free_slots; enum { has_no_slot = -3 // the piece has no storage }; // maps piece indices to slots. If a piece doesn't // have any storage, it is set to 'has_no_slot' std::vector<int> m_piece_to_slot; enum { unallocated = -1, // the slot is unallocated unassigned = -2 // the slot is allocated but not assigned to a piece }; // maps slots to piece indices, if a slot doesn't have a piece // it can either be 'unassigned' or 'unallocated' std::vector<int> m_slot_to_piece; fs::path m_save_path; mutable boost::recursive_mutex m_mutex; enum { // the default initial state state_none, // the file checking is complete state_finished, // creating the directories state_create_files, // checking the files state_full_check, // move pieces to their final position state_expand_pieces } m_state; int m_current_slot; // used during check. If any piece is found // that is not in its final position, this // is set to true bool m_out_of_place; // used to move pieces while expanding // the storage from compact allocation // to full allocation std::vector<char> m_scratch_buffer; std::vector<char> m_scratch_buffer2; // the piece that is in the scratch buffer int m_scratch_piece; // this is saved in case we need to instantiate a new // storage (osed when remapping files) storage_constructor_type m_storage_constructor; // temporary buffer used while checking std::vector<char> m_piece_data; // this maps a piece hash to piece index. It will be // build the first time it is used (to save time if it // isn't needed) std::multimap<sha1_hash, int> m_hash_to_piece; // this map contains partial hashes for downloading // pieces. This is only accessed from within the // disk-io thread. std::map<int, partial_hash> m_piece_hasher; disk_io_thread& m_io_thread; // the reason for this to be a void pointer // is to avoid creating a dependency on the // torrent. This shared_ptr is here only // to keep the torrent object alive until // the piece_manager destructs. This is because // the torrent_info object is owned by the torrent. boost::shared_ptr<void> m_torrent; }; } #endif // TORRENT_STORAGE_HPP_INCLUDED <commit_msg>removed unused left-overs<commit_after>/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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. */ #ifndef TORRENT_STORAGE_HPP_INCLUDE #define TORRENT_STORAGE_HPP_INCLUDE #include <vector> #include <bitset> #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/limits.hpp> #include <boost/thread.hpp> #include <boost/shared_ptr.hpp> #include <boost/intrusive_ptr.hpp> #include <boost/filesystem/path.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif #include "libtorrent/torrent_info.hpp" #include "libtorrent/piece_picker.hpp" #include "libtorrent/intrusive_ptr_base.hpp" #include "libtorrent/peer_request.hpp" #include "libtorrent/hasher.hpp" #include "libtorrent/config.hpp" namespace libtorrent { namespace aux { struct piece_checker_data; } namespace fs = boost::filesystem; class session; struct file_pool; struct disk_io_job; enum storage_mode_t { storage_mode_allocate = 0, storage_mode_sparse, storage_mode_compact }; #if defined(_WIN32) && defined(UNICODE) TORRENT_EXPORT std::wstring safe_convert(std::string const& s); #endif TORRENT_EXPORT std::vector<std::pair<size_type, std::time_t> > get_filesizes( torrent_info const& t , fs::path p); TORRENT_EXPORT bool match_filesizes( torrent_info const& t , fs::path p , std::vector<std::pair<size_type, std::time_t> > const& sizes , bool compact_mode , std::string* error = 0); struct TORRENT_EXPORT file_allocation_failed: std::exception { file_allocation_failed(const char* error_msg): m_msg(error_msg) {} virtual const char* what() const throw() { return m_msg.c_str(); } virtual ~file_allocation_failed() throw() {} std::string m_msg; }; struct TORRENT_EXPORT partial_hash { partial_hash(): offset(0) {} // the number of bytes in the piece that has been hashed int offset; // the sha-1 context hasher h; }; struct TORRENT_EXPORT storage_interface { // create directories and set file sizes // if allocate_files is true. // allocate_files is true if allocation mode // is set to full and sparse files are supported virtual void initialize(bool allocate_files) = 0; // may throw file_error if storage for slot does not exist virtual size_type read(char* buf, int slot, int offset, int size) = 0; // may throw file_error if storage for slot hasn't been allocated virtual void write(const char* buf, int slot, int offset, int size) = 0; virtual bool move_storage(fs::path save_path) = 0; // verify storage dependent fast resume entries virtual bool verify_resume_data(entry& rd, std::string& error) = 0; // write storage dependent fast resume entries virtual void write_resume_data(entry& rd) const = 0; // moves (or copies) the content in src_slot to dst_slot virtual void move_slot(int src_slot, int dst_slot) = 0; // swaps the data in slot1 and slot2 virtual void swap_slots(int slot1, int slot2) = 0; // swaps the puts the data in slot1 in slot2, the data in slot2 // in slot3 and the data in slot3 in slot1 virtual void swap_slots3(int slot1, int slot2, int slot3) = 0; // returns the sha1-hash for the data at the given slot virtual sha1_hash hash_for_slot(int slot, partial_hash& h, int piece_size) = 0; // this will close all open files that are opened for // writing. This is called when a torrent has finished // downloading. virtual void release_files() = 0; virtual ~storage_interface() {} }; typedef storage_interface* (&storage_constructor_type)( boost::intrusive_ptr<torrent_info const>, fs::path const& , file_pool&); TORRENT_EXPORT storage_interface* default_storage_constructor( boost::intrusive_ptr<torrent_info const> ti , fs::path const& path, file_pool& fp); struct disk_io_thread; class TORRENT_EXPORT piece_manager : public intrusive_ptr_base<piece_manager> , boost::noncopyable { friend class invariant_access; friend struct disk_io_thread; public: piece_manager( boost::shared_ptr<void> const& torrent , boost::intrusive_ptr<torrent_info const> ti , fs::path const& path , file_pool& fp , disk_io_thread& io , storage_constructor_type sc); ~piece_manager(); bool check_fastresume(aux::piece_checker_data& d , std::vector<bool>& pieces, int& num_pieces, storage_mode_t storage_mode , std::string& error_msg); std::pair<bool, float> check_files(std::vector<bool>& pieces , int& num_pieces, boost::recursive_mutex& mutex); // frees a buffer that was returned from a read operation void free_buffer(char* buf); void write_resume_data(entry& rd) const; bool verify_resume_data(entry& rd, std::string& error); bool is_allocating() const { return m_state == state_expand_pieces; } void mark_failed(int index); unsigned long piece_crc( int slot_index , int block_size , piece_picker::block_info const* bi); int slot_for(int piece) const; int piece_for(int slot) const; void async_read( peer_request const& r , boost::function<void(int, disk_io_job const&)> const& handler , char* buffer = 0 , int priority = 0); void async_write( peer_request const& r , char const* buffer , boost::function<void(int, disk_io_job const&)> const& f); void async_hash(int piece, boost::function<void(int, disk_io_job const&)> const& f); fs::path save_path() const; void async_release_files( boost::function<void(int, disk_io_job const&)> const& handler = boost::function<void(int, disk_io_job const&)>()); void async_move_storage(fs::path const& p , boost::function<void(int, disk_io_job const&)> const& handler); // fills the vector that maps all allocated // slots to the piece that is stored (or // partially stored) there. -2 is the index // of unassigned pieces and -1 is unallocated void export_piece_map(std::vector<int>& pieces , std::vector<bool> const& have) const; bool compact_allocation() const { return m_storage_mode == storage_mode_compact; } #ifndef NDEBUG std::string name() const { return m_info->name(); } #endif private: bool allocate_slots(int num_slots, bool abort_on_disk = false); int identify_data( const std::vector<char>& piece_data , int current_slot , std::vector<bool>& have_pieces , int& num_pieces , const std::multimap<sha1_hash, int>& hash_to_piece , boost::recursive_mutex& mutex); size_type read_impl( char* buf , int piece_index , int offset , int size); void write_impl( const char* buf , int piece_index , int offset , int size); void switch_to_full_mode(); sha1_hash hash_for_piece_impl(int piece); void release_files_impl(); bool move_storage_impl(fs::path const& save_path); int allocate_slot_for_piece(int piece_index); #ifndef NDEBUG void check_invariant() const; #ifdef TORRENT_STORAGE_DEBUG void debug_log() const; #endif #endif boost::scoped_ptr<storage_interface> m_storage; storage_mode_t m_storage_mode; boost::intrusive_ptr<torrent_info const> m_info; // slots that haven't had any file storage allocated std::vector<int> m_unallocated_slots; // slots that have file storage, but isn't assigned to a piece std::vector<int> m_free_slots; enum { has_no_slot = -3 // the piece has no storage }; // maps piece indices to slots. If a piece doesn't // have any storage, it is set to 'has_no_slot' std::vector<int> m_piece_to_slot; enum { unallocated = -1, // the slot is unallocated unassigned = -2 // the slot is allocated but not assigned to a piece }; // maps slots to piece indices, if a slot doesn't have a piece // it can either be 'unassigned' or 'unallocated' std::vector<int> m_slot_to_piece; fs::path m_save_path; mutable boost::recursive_mutex m_mutex; enum { // the default initial state state_none, // the file checking is complete state_finished, // creating the directories state_create_files, // checking the files state_full_check, // move pieces to their final position state_expand_pieces } m_state; int m_current_slot; // used during check. If any piece is found // that is not in its final position, this // is set to true bool m_out_of_place; // used to move pieces while expanding // the storage from compact allocation // to full allocation std::vector<char> m_scratch_buffer; std::vector<char> m_scratch_buffer2; // the piece that is in the scratch buffer int m_scratch_piece; // this is saved in case we need to instantiate a new // storage (osed when remapping files) storage_constructor_type m_storage_constructor; // temporary buffer used while checking std::vector<char> m_piece_data; // this maps a piece hash to piece index. It will be // build the first time it is used (to save time if it // isn't needed) std::multimap<sha1_hash, int> m_hash_to_piece; // this map contains partial hashes for downloading // pieces. This is only accessed from within the // disk-io thread. std::map<int, partial_hash> m_piece_hasher; disk_io_thread& m_io_thread; // the reason for this to be a void pointer // is to avoid creating a dependency on the // torrent. This shared_ptr is here only // to keep the torrent object alive until // the piece_manager destructs. This is because // the torrent_info object is owned by the torrent. boost::shared_ptr<void> m_torrent; }; } #endif // TORRENT_STORAGE_HPP_INCLUDED <|endoftext|>
<commit_before>/* * Portability.hh * * Copyright 2001, LifeLine Networks BV (www.lifeline.nl). All rights reserved. * Copyright 2001, Bastiaan Bakker. All rights reserved. * * See the COPYING file for the terms of usage and distribution. */ #ifndef _LOG4CPP_PORTABILITY_HH #define _LOG4CPP_PORTABILITY_HH #if defined (_MSC_VER) || defined(__BORLANDC__) # include <log4cpp/config-win32.h> #else #if defined(__OPENVMS__) # include <log4cpp/config-openvms.h> #else # include <log4cpp/config.h> #endif #endif #include <log4cpp/Export.hh> #if defined(_MSC_VER) # pragma warning( disable : 4786 ) # pragma warning( disable : 4290 ) # pragma warning( disable : 4251 ) #endif #endif <commit_msg>added comments.<commit_after>/* * Portability.hh * * Copyright 2001, LifeLine Networks BV (www.lifeline.nl). All rights reserved. * Copyright 2001, Bastiaan Bakker. All rights reserved. * * See the COPYING file for the terms of usage and distribution. */ #ifndef _LOG4CPP_PORTABILITY_HH #define _LOG4CPP_PORTABILITY_HH #if defined (_MSC_VER) || defined(__BORLANDC__) # include <log4cpp/config-win32.h> #else #if defined(__OPENVMS__) # include <log4cpp/config-openvms.h> #else # include <log4cpp/config.h> #endif #endif #include <log4cpp/Export.hh> #if defined(_MSC_VER) # pragma warning( disable : 4786 ) // 255 char debug symbol limit # pragma warning( disable : 4290 ) // throw specifier not implemented # pragma warning( disable : 4251 ) // "class XXX should be exported" #endif #endif <|endoftext|>
<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/.*/ #ifndef MYSQL_BASIC_ENGINE_HPP #define MYSQL_BASIC_ENGINE_HPP #include "impl/basic_engine_impl.hpp" #include "basic_context.hpp" #include "basic_result.hpp" #include "basic_row.hpp" #include "../assert.hpp" #include "../db_engine.hpp" // for fp::is_engine #include "../forward.hpp" // for fix::forward #include "../is_query.hpp" // for fp::is_query #include "../record.hpp" #include "../type_traits.hpp" // for fp::EnableIf, fp::DisableIf, fp::Invoke, fp::Unqualified #include <algorithm> #include <iterator> // for std::back_inserter #include <memory> // for std::shared_ptr #include <string> // for std::string, std::to_string #include <utility> // for std::swap #include <vector> // for std::vector #include <mysql/mysql.h> // for MYSQL, MYSQL_RES namespace fp { namespace mysql { class basic_engine { public: using default_record_type = record<>; protected: std::shared_ptr<basic_context> _context; public: basic_engine(const char* host, const char* name, const char* pass) : _context(basic_context::create()) { if (_context) { MYSQL* res = ::mysql_real_connect(_context->handle(), host, name, pass, 0, 0, 0, 0); FP_ASSERT(res, "Unable to connect to MySQL server"); *_context = res; } } basic_engine(const char* host, const char* name, const char* pass, const char* db) : _context(basic_context::create()) { if (_context) { MYSQL* res = ::mysql_real_connect(_context->handle(), host, name, pass, db, 0, 0, 0); FP_ASSERT(res, "Unable to connect to MySQL server"); *_context = res; } } basic_engine(const basic_engine&) = default; basic_engine(basic_engine&&) = default; friend void swap(basic_engine& l, basic_engine& r) { using std::swap; swap(l._context, r._context); } std::string errorstr() const { return ::mysql_error(_context->handle()); } unsigned int error() const { return ::mysql_errno(_context->handle()); } template< typename TQuery, typename TRecord = Invoke<typename Unqualified<TQuery>::template result_of<default_record_type>>, typename Container = std::vector<TRecord>, typename = mpl::enable_if_t<mpl::all_<is_query<Unqualified<TQuery>>, is_record<TRecord>>> > Container query(TQuery&& q) { using std::to_string; using std::begin; using std::end; const std::string qry = to_string(fix::forward<TQuery>(q)); if(0 != _context->query(qry.c_str())) { throw std::runtime_error("Could not query database"); } mysql::basic_result res(*_context); if(res) { Container ret; ret.reserve(res.rows()); std::transform( begin(res), end(res), std::back_inserter(ret), [](const basic_row& r) { return impl::make_record<TRecord>::make(r); } ); return ret; } throw std::runtime_error("No valid context available"); } template< typename TQuery, typename TRecord = default_record_type, typename = mpl::disable_if_t< mpl::all_< is_query<Unqualified<TQuery>>, is_record<Invoke<typename Unqualified<TQuery>::template result_of<TRecord>>> > > > unsigned long long query(TQuery&& q){ using std::to_string; const std::string qry = to_string(fix::forward<TQuery>(q)); if (0 == ::mysql_query(_context->handle(), qry.c_str())) { return ::mysql_affected_rows(_context->handle()); } else { return -1; } } }; } namespace detail { template<> struct is_engine<mysql::basic_engine> : mpl::true_ { }; } } #endif<commit_msg>minor fix<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/.*/ #ifndef MYSQL_BASIC_ENGINE_HPP #define MYSQL_BASIC_ENGINE_HPP #include "impl/basic_engine_impl.hpp" #include "basic_context.hpp" #include "basic_result.hpp" #include "basic_row.hpp" #include "../assert.hpp" #include "../db_engine.hpp" // for fp::is_engine #include "../forward.hpp" // for fix::forward #include "../is_query.hpp" // for fp::is_query #include "../record.hpp" #include "../type_traits.hpp" // for fp::EnableIf, fp::DisableIf, fp::Invoke, fp::Unqualified #include <algorithm> #include <iterator> // for std::back_inserter #include <memory> // for std::shared_ptr #include <string> // for std::string, std::to_string #include <utility> // for std::swap #include <vector> // for std::vector #include <mysql/mysql.h> // for MYSQL, MYSQL_RES namespace fp { namespace mysql { class basic_engine { public: using default_record_type = record<>; protected: std::shared_ptr<basic_context> _context; public: basic_engine(const char* host, const char* name, const char* pass) : _context(basic_context::create()) { if (_context) { MYSQL* res = ::mysql_real_connect(_context->handle(), host, name, pass, 0, 0, 0, 0); FP_ASSERT(res, "Unable to connect to MySQL server"); *_context = res; } } basic_engine(const char* host, const char* name, const char* pass, const char* db) : _context(basic_context::create()) { if (_context) { MYSQL* res = ::mysql_real_connect(_context->handle(), host, name, pass, db, 0, 0, 0); FP_ASSERT(res, "Unable to connect to MySQL server"); *_context = res; } } basic_engine(const basic_engine&) = default; basic_engine(basic_engine&&) = default; friend void swap(basic_engine& l, basic_engine& r) { using std::swap; swap(l._context, r._context); } std::string errorstr() const { return ::mysql_error(_context->handle()); } unsigned int error() const { return ::mysql_errno(_context->handle()); } template< typename TQuery, typename TRecord = Invoke<typename Unqualified<TQuery>::template result_of<default_record_type>>, typename Container = std::vector<TRecord>, typename = mpl::enable_if_t<mpl::all_<is_query<Unqualified<TQuery>>, is_record<TRecord>>> > Container query(TQuery&& q) { using std::to_string; using std::begin; using std::end; const std::string qry = to_string(fix::forward<TQuery>(q)); if(0 != _context->query(qry.c_str())) { throw std::runtime_error("Could not query database"); } mysql::basic_result res(*_context); if(res) { Container ret; ret.reserve(res.rows()); std::transform( begin(res), end(res), std::back_inserter(ret), [](const basic_row& r) { return impl::make_record<TRecord>::make(r); } ); return ret; } throw std::runtime_error("No valid context available"); } template< typename TQuery, typename TRecord = default_record_type, typename = mpl::disable_if_t< mpl::all_< is_query<Unqualified<TQuery>>, is_record<Invoke<typename Unqualified<TQuery>::template result_of<TRecord>>> > > > unsigned long long query(TQuery&& q){ using std::to_string; const std::string qry = to_string(fix::forward<TQuery>(q)); if (0 == ::mysql_query(_context->handle(), qry.c_str())) { return ::mysql_affected_rows(_context->handle()); } else { return -1; } } }; } namespace detail { template<> struct is_engine<mysql::basic_engine> : mpl::true_ { }; } } #endif <|endoftext|>
<commit_before>/* * Copyright (c) 2015-2016, Technische Universität Dresden, Germany * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions * and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other materials provided * with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used to * endorse or promote products derived from this software without specific prior written * permission. * * 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 HOLDER 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. */ #ifndef INCLUDE_NITRO_LANG_REVERSE_HPP #define INCLUDE_NITRO_LANG_REVERSE_HPP #include <vector> namespace nitro { namespace lang { namespace detail { template <typename T, typename Iterator> class reverse_proxy { public: using iterator = Iterator; reverse_proxy(iterator begin, iterator end) : begin_(begin), end_(end) { } iterator begin() const { return begin_; } iterator end() const { return end_; } private: iterator begin_; iterator end_; }; template <typename T> class reverse { public: reverse(T container) : container_(std::move(container)) { } auto begin() const { return container_.crbegin(); } auto end() const { return container_.crend(); } private: T container_; }; } template <typename T> inline auto reverse(const T& container) { using std::rbegin; using std::rend; return detail::reverse_proxy<T, decltype(rbegin(container))>(rbegin(container), rend(container)); } template <typename T> inline auto reverse(T& container) { using std::rbegin; using std::rend; return detail::reverse_proxy<T, decltype(rbegin(container))>(rbegin(container), rend(container)); } template <typename T> inline auto reverse(T&& container) { return detail::reverse<T>(std::move(container)); } template <typename T> inline auto reverse(std::initializer_list<T>&& l) { return reverse(std::vector<T>(std::move(l))); } } } // namespace nitr::lang #endif // INCLUDE_NITRO_LANG_REVERSE_HPP <commit_msg>Removes usage of free rbegin/rend<commit_after>/* * Copyright (c) 2015-2016, Technische Universität Dresden, Germany * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions * and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other materials provided * with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used to * endorse or promote products derived from this software without specific prior written * permission. * * 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 HOLDER 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. */ #ifndef INCLUDE_NITRO_LANG_REVERSE_HPP #define INCLUDE_NITRO_LANG_REVERSE_HPP #include <functional> #include <vector> namespace nitro { namespace lang { namespace detail { template <typename T, typename Iterator> class reverse_proxy { public: using iterator = Iterator; reverse_proxy(iterator begin, iterator end) : begin_(begin), end_(end) { } iterator begin() const { return begin_; } iterator end() const { return end_; } private: iterator begin_; iterator end_; }; template <typename T> class reverse { public: reverse(T container) : container_(std::move(container)) { } auto begin() const { return container_.crbegin(); } auto end() const { return container_.crend(); } private: T container_; }; } template <typename T> inline auto reverse(const T& container) { return detail::reverse_proxy<T, decltype(container.rbegin())>(container.rbegin(), container.rend()); } template <typename T> inline auto reverse(T& container) { return detail::reverse_proxy<T, decltype(container.rbegin())>(container.rbegin(), container.rend()); } template <typename T> inline auto reverse(T&& container) { return detail::reverse<T>(std::move(container)); } template <typename T, unsigned Size> inline auto reverse(T (&container)[Size]) { return reverse(std::vector<std::reference_wrapper<T>>(container, container + Size)); } template <typename T> inline auto reverse(std::initializer_list<T>&& l) { return reverse(std::vector<T>(std::move(l))); } } } // namespace nitr::lang #endif // INCLUDE_NITRO_LANG_REVERSE_HPP <|endoftext|>
<commit_before>// This file is a part of Simdee, see homepage at http://github.com/tufak/simdee // This file is distributed under the MIT license. #ifndef SIMDEE_COMMON_EXPR_HPP #define SIMDEE_COMMON_EXPR_HPP #include "../common/casts.hpp" #include <limits> namespace sd { namespace expr { template <typename T> struct aligned { SIMDEE_INL constexpr explicit aligned(T* r) : ptr(r) {} template <typename Simd_t> SIMDEE_INL void operator=(const Simd_t& r) const { static_assert(!std::is_const<T>::value, "Storing into a const pointer via aligned()"); using scalar_t = typename Simd_t::scalar_t; r.aligned_store(reinterpret_cast<scalar_t*>(ptr)); } // data T* ptr; }; template <typename T> struct unaligned { SIMDEE_INL constexpr explicit unaligned(T* r) : ptr(r) {} template <typename Simd_t> SIMDEE_INL void operator=(const Simd_t& r) const { static_assert(!std::is_const<T>::value, "Storing into a const pointer via unaligned()"); using scalar_t = typename Simd_t::scalar_t; r.unaligned_store(reinterpret_cast<scalar_t*>(ptr)); } // data T* ptr; }; template <typename T> struct interleaved { SIMDEE_INL constexpr explicit interleaved(T* r, std::size_t rs) : ptr(r), step(rs) {} template <typename Simd_t> SIMDEE_INL void operator=(const Simd_t& r) const { static_assert(!std::is_const<T>::value, "Storing into a const pointer via interleaved()"); using scalar_t = typename Simd_t::scalar_t; r.interleaved_store(reinterpret_cast<scalar_t*>(ptr), step); } // data T* ptr; std::size_t step; }; template <typename Crtp> struct init { SIMDEE_INL constexpr const Crtp& self() const { return static_cast<const Crtp&>(*this); } template <typename Target> SIMDEE_INL constexpr Target to() const { static_assert(is_extended_arithmetic_type<Target>::value, "init::to<Target>():: Target must be an arithmetic type"); return self().template to<Target>(); } }; struct zero : init<zero> { template <typename Target> SIMDEE_INL constexpr Target to() const { using u_t = select_uint_t<sizeof(Target)>; return dirty::cast<u_t, Target>(0); } }; struct all_bits : init<all_bits> { template <typename Target> SIMDEE_INL constexpr Target to() const { using u_t = select_uint_t<sizeof(Target)>; return dirty::cast<u_t, Target>(~u_t(0)); } }; struct sign_bit : init<sign_bit> { template <typename Target> SIMDEE_INL constexpr Target to() const { using u_t = select_uint_t<sizeof(Target)>; return dirty::cast<u_t, Target>(~(~u_t(0) >> 1)); } }; struct abs_mask : init<abs_mask> { template <typename Target> SIMDEE_INL constexpr Target to() const { using u_t = select_uint_t<sizeof(Target)>; return dirty::cast<u_t, Target>(~u_t(0) >> 1); } }; struct inf : init<inf> { template <typename Target> SIMDEE_INL constexpr Target to() const { using f_t = select_float_t<sizeof(Target)>; return dirty::cast<f_t, Target>(std::numeric_limits<f_t>::infinity()); } }; struct ninf : init<ninf> { template <typename Target> SIMDEE_INL constexpr Target to() const { using f_t = select_float_t<sizeof(Target)>; return dirty::cast<f_t, Target>(-std::numeric_limits<f_t>::infinity()); } }; struct nan : init<nan> { template <typename Target> SIMDEE_INL constexpr Target to() const { using f_t = select_float_t<sizeof(Target)>; return dirty::cast<f_t, Target>(std::numeric_limits<f_t>::quiet_NaN()); } }; } template <typename T> SIMDEE_INL constexpr expr::aligned<T> aligned(T* const& r) { return expr::aligned<T>(r); } template <typename T> SIMDEE_INL constexpr expr::unaligned<T> unaligned(T* const& r) { return expr::unaligned<T>(r); } template <typename T> SIMDEE_INL constexpr expr::interleaved<T> interleaved(T* const& r, std::size_t rs) { return expr::interleaved<T>(r, rs); } SIMDEE_INL constexpr expr::zero zero() { return expr::zero{}; } SIMDEE_INL constexpr expr::all_bits all_bits() { return expr::all_bits{}; } SIMDEE_INL constexpr expr::sign_bit sign_bit() { return expr::sign_bit{}; } SIMDEE_INL constexpr expr::abs_mask abs_mask() { return expr::abs_mask{}; } SIMDEE_INL constexpr expr::inf inf() { return expr::inf{}; } SIMDEE_INL constexpr expr::ninf ninf() { return expr::ninf{}; } SIMDEE_INL constexpr expr::nan nan() { return expr::nan{}; } } #endif // SIMDEE_COMMON_EXPR_HPP <commit_msg>Remove usages reinterpret_cast in expr.hpp<commit_after>// This file is a part of Simdee, see homepage at http://github.com/tufak/simdee // This file is distributed under the MIT license. #ifndef SIMDEE_COMMON_EXPR_HPP #define SIMDEE_COMMON_EXPR_HPP #include "../common/casts.hpp" #include <limits> namespace sd { namespace expr { template <typename T> struct aligned { SIMDEE_INL constexpr explicit aligned(T* r) : ptr(r) {} template <typename Simd_t> SIMDEE_INL void operator=(const Simd_t& r) const { r.aligned_store(ptr); } // data T* ptr; }; template <typename T> struct unaligned { SIMDEE_INL constexpr explicit unaligned(T* r) : ptr(r) {} template <typename Simd_t> SIMDEE_INL void operator=(const Simd_t& r) const { r.unaligned_store(ptr); } // data T* ptr; }; template <typename T> struct interleaved { SIMDEE_INL constexpr explicit interleaved(T* r, std::size_t rs) : ptr(r), step(rs) {} template <typename Simd_t> SIMDEE_INL void operator=(const Simd_t& r) const { r.interleaved_store(ptr, step); } // data T* ptr; std::size_t step; }; template <typename Crtp> struct init { SIMDEE_INL constexpr const Crtp& self() const { return static_cast<const Crtp&>(*this); } template <typename Target> SIMDEE_INL constexpr Target to() const { static_assert(is_extended_arithmetic_type<Target>::value, "init::to<Target>():: Target must be an arithmetic type"); return self().template to<Target>(); } }; struct zero : init<zero> { template <typename Target> SIMDEE_INL constexpr Target to() const { using u_t = select_uint_t<sizeof(Target)>; return dirty::cast<u_t, Target>(0); } }; struct all_bits : init<all_bits> { template <typename Target> SIMDEE_INL constexpr Target to() const { using u_t = select_uint_t<sizeof(Target)>; return dirty::cast<u_t, Target>(~u_t(0)); } }; struct sign_bit : init<sign_bit> { template <typename Target> SIMDEE_INL constexpr Target to() const { using u_t = select_uint_t<sizeof(Target)>; return dirty::cast<u_t, Target>(~(~u_t(0) >> 1)); } }; struct abs_mask : init<abs_mask> { template <typename Target> SIMDEE_INL constexpr Target to() const { using u_t = select_uint_t<sizeof(Target)>; return dirty::cast<u_t, Target>(~u_t(0) >> 1); } }; struct inf : init<inf> { template <typename Target> SIMDEE_INL constexpr Target to() const { using f_t = select_float_t<sizeof(Target)>; return dirty::cast<f_t, Target>(std::numeric_limits<f_t>::infinity()); } }; struct ninf : init<ninf> { template <typename Target> SIMDEE_INL constexpr Target to() const { using f_t = select_float_t<sizeof(Target)>; return dirty::cast<f_t, Target>(-std::numeric_limits<f_t>::infinity()); } }; struct nan : init<nan> { template <typename Target> SIMDEE_INL constexpr Target to() const { using f_t = select_float_t<sizeof(Target)>; return dirty::cast<f_t, Target>(std::numeric_limits<f_t>::quiet_NaN()); } }; } template <typename T> SIMDEE_INL constexpr expr::aligned<T> aligned(T* const& r) { return expr::aligned<T>(r); } template <typename T> SIMDEE_INL constexpr expr::unaligned<T> unaligned(T* const& r) { return expr::unaligned<T>(r); } template <typename T> SIMDEE_INL constexpr expr::interleaved<T> interleaved(T* const& r, std::size_t rs) { return expr::interleaved<T>(r, rs); } SIMDEE_INL constexpr expr::zero zero() { return expr::zero{}; } SIMDEE_INL constexpr expr::all_bits all_bits() { return expr::all_bits{}; } SIMDEE_INL constexpr expr::sign_bit sign_bit() { return expr::sign_bit{}; } SIMDEE_INL constexpr expr::abs_mask abs_mask() { return expr::abs_mask{}; } SIMDEE_INL constexpr expr::inf inf() { return expr::inf{}; } SIMDEE_INL constexpr expr::ninf ninf() { return expr::ninf{}; } SIMDEE_INL constexpr expr::nan nan() { return expr::nan{}; } } #endif // SIMDEE_COMMON_EXPR_HPP <|endoftext|>
<commit_before>// The libMesh Finite Element Library. // Copyright (C) 2002-2020 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // <h1>FEMSystem Example 3 - Unsteady Linear Elasticity with // FEMSystem</h1> // \author Paul Bauman // \date 2015 // // This example shows how to solve the three-dimensional transient // linear elasticity equations using the DifferentiableSystem class framework. // This is just Systems of Equations Example 6 recast. // C++ includes #include <iomanip> // Basic include files #include "libmesh/equation_systems.h" #include "libmesh/error_vector.h" #include "libmesh/getpot.h" #include "libmesh/exodusII_io.h" #include "libmesh/kelly_error_estimator.h" #include "libmesh/mesh.h" #include "libmesh/mesh_generation.h" #include "libmesh/enum_solver_package.h" #include "libmesh/enum_solver_type.h" #include "libmesh/auto_ptr.h" // libmesh_make_unique // The systems and solvers we may use #include "elasticity_system.h" #include "libmesh/diff_solver.h" #include "libmesh/newmark_solver.h" #include "libmesh/steady_solver.h" #include "libmesh/euler_solver.h" #include "libmesh/euler2_solver.h" #include "libmesh/elem.h" #include "libmesh/newton_solver.h" #include "libmesh/eigen_sparse_linear_solver.h" #define x_scaling 1.3 // Bring in everything from the libMesh namespace using namespace libMesh; // The main program. int main (int argc, char ** argv) { // Initialize libMesh. LibMeshInit init (argc, argv); // This example requires a linear solver package. libmesh_example_requires(libMesh::default_solver_package() != INVALID_SOLVER_PACKAGE, "--enable-petsc, --enable-trilinos, or --enable-eigen"); // This example requires 3D calculations libmesh_example_requires(LIBMESH_DIM > 2, "3D support"); // We use Dirichlet boundary conditions here #ifndef LIBMESH_ENABLE_DIRICHLET libmesh_example_requires(false, "--enable-dirichlet"); #endif // Parse the input file GetPot infile("fem_system_ex3.in"); // Override input file arguments from the command line infile.parse_command_line(argc, argv); // Read in parameters from the input file const Real deltat = infile("deltat", 0.25); unsigned int n_timesteps = infile("n_timesteps", 1); #ifdef LIBMESH_HAVE_EXODUS_API const unsigned int write_interval = infile("write_interval", 1); #endif // Initialize the cantilever mesh const unsigned int dim = 3; // Make sure libMesh was compiled for 3D libmesh_example_requires(dim == LIBMESH_DIM, "3D support"); // Create a 3D mesh distributed across the default MPI communicator. Mesh mesh(init.comm(), dim); MeshTools::Generation::build_cube (mesh, 32, 8, 4, 0., 1.*x_scaling, 0., 0.3, 0., 0.1, HEX8); // Print information about the mesh to the screen. mesh.print_info(); // Let's add some node and edge boundary conditions. // Each processor should know about each boundary condition it can // see, so we loop over all elements, not just local elements. for (const auto & elem : mesh.element_ptr_range()) { unsigned int side_max_x = 0, side_min_y = 0, side_max_y = 0, side_max_z = 0; bool found_side_max_x = false, found_side_max_y = false, found_side_min_y = false, found_side_max_z = false; for (auto side : elem->side_index_range()) { if (mesh.get_boundary_info().has_boundary_id(elem, side, boundary_id_max_x)) { side_max_x = side; found_side_max_x = true; } if (mesh.get_boundary_info().has_boundary_id(elem, side, boundary_id_min_y)) { side_min_y = side; found_side_min_y = true; } if (mesh.get_boundary_info().has_boundary_id(elem, side, boundary_id_max_y)) { side_max_y = side; found_side_max_y = true; } if (mesh.get_boundary_info().has_boundary_id(elem, side, boundary_id_max_z)) { side_max_z = side; found_side_max_z = true; } } // If elem has sides on boundaries // BOUNDARY_ID_MAX_X, BOUNDARY_ID_MAX_Y, BOUNDARY_ID_MAX_Z // then let's set a node boundary condition if (found_side_max_x && found_side_max_y && found_side_max_z) for (auto n : elem->node_index_range()) if (elem->is_node_on_side(n, side_max_x) && elem->is_node_on_side(n, side_max_y) && elem->is_node_on_side(n, side_max_z)) mesh.get_boundary_info().add_node(elem->node_ptr(n), node_boundary_id); // If elem has sides on boundaries // BOUNDARY_ID_MAX_X and BOUNDARY_ID_MIN_Y // then let's set an edge boundary condition if (found_side_max_x && found_side_min_y) for (auto e : elem->edge_index_range()) if (elem->is_edge_on_side(e, side_max_x) && elem->is_edge_on_side(e, side_min_y)) mesh.get_boundary_info().add_edge(elem, e, edge_boundary_id); } // Create an equation systems object. EquationSystems equation_systems (mesh); // Declare the system "Navier-Stokes" and its variables. ElasticitySystem & system = equation_systems.add_system<ElasticitySystem> ("Linear Elasticity"); // Solve this as a time-dependent or steady system std::string time_solver = infile("time_solver","DIE!"); ExplicitSystem * v_system; ExplicitSystem * a_system; if( time_solver == std::string("newmark") ) { // Create ExplicitSystem to help output velocity v_system = &equation_systems.add_system<ExplicitSystem> ("Velocity"); v_system->add_variable("u_vel", FIRST, LAGRANGE); v_system->add_variable("v_vel", FIRST, LAGRANGE); v_system->add_variable("w_vel", FIRST, LAGRANGE); // Create ExplicitSystem to help output acceleration a_system = &equation_systems.add_system<ExplicitSystem> ("Acceleration"); a_system->add_variable("u_accel", FIRST, LAGRANGE); a_system->add_variable("v_accel", FIRST, LAGRANGE); a_system->add_variable("w_accel", FIRST, LAGRANGE); } if (time_solver == std::string("newmark")) system.time_solver = libmesh_make_unique<NewmarkSolver>(system); else if( time_solver == std::string("euler") ) { system.time_solver = libmesh_make_unique<EulerSolver>(system); EulerSolver & euler_solver = cast_ref<EulerSolver &>(*(system.time_solver.get())); euler_solver.theta = infile("theta", 1.0); } else if( time_solver == std::string("euler2") ) { system.time_solver = libmesh_make_unique<Euler2Solver>(system); Euler2Solver & euler_solver = cast_ref<Euler2Solver &>(*(system.time_solver.get())); euler_solver.theta = infile("theta", 1.0); } else if( time_solver == std::string("steady")) { system.time_solver = libmesh_make_unique<SteadySolver>(system); libmesh_assert_equal_to (n_timesteps, 1); } else libmesh_error_msg(std::string("ERROR: invalid time_solver ")+time_solver); // Initialize the system equation_systems.init (); // Set the time stepping options system.deltat = deltat; // And the nonlinear solver options DiffSolver & solver = *(system.time_solver->diff_solver().get()); solver.quiet = infile("solver_quiet", true); solver.verbose = !solver.quiet; solver.max_nonlinear_iterations = infile("max_nonlinear_iterations", 15); solver.relative_step_tolerance = infile("relative_step_tolerance", 1.e-3); solver.relative_residual_tolerance = infile("relative_residual_tolerance", 0.0); solver.absolute_residual_tolerance = infile("absolute_residual_tolerance", 0.0); // And the linear solver options solver.max_linear_iterations = infile("max_linear_iterations", 50000); solver.initial_linear_tolerance = infile("initial_linear_tolerance", 1.e-3); // Print information about the system to the screen. equation_systems.print_info(); // If we're using EulerSolver or Euler2Solver, and we're using EigenSparseLinearSolver, // then we need to reset the EigenSparseLinearSolver to use SPARSELU because BICGSTAB // chokes on the Jacobian matrix we give it and Eigen's GMRES currently doesn't work. NewtonSolver * newton_solver = dynamic_cast<NewtonSolver *>( &solver ); if( newton_solver && (time_solver == std::string("euler") || time_solver == std::string("euler2") ) ) { #ifdef LIBMESH_HAVE_EIGEN_SPARSE LinearSolver<Number> & linear_solver = newton_solver->get_linear_solver(); EigenSparseLinearSolver<Number> * eigen_linear_solver = dynamic_cast<EigenSparseLinearSolver<Number> *>(&linear_solver); if( eigen_linear_solver ) eigen_linear_solver->set_solver_type(SPARSELU); #endif } if( time_solver == std::string("newmark") ) { NewmarkSolver * newmark = cast_ptr<NewmarkSolver*>(system.time_solver.get()); newmark->compute_initial_accel(); // Copy over initial velocity and acceleration for output. // Note we can do this because of the matching variables/FE spaces *(v_system->solution) = system.get_vector("_old_solution_rate"); *(a_system->solution) = system.get_vector("_old_solution_accel"); } #ifdef LIBMESH_HAVE_EXODUS_API // Output initial state { std::ostringstream file_name; // We write the file in the ExodusII format. file_name << std::string("out.")+time_solver+std::string(".e-s.") << std::setw(3) << std::setfill('0') << std::right << 0; ExodusII_IO(mesh).write_timestep(file_name.str(), equation_systems, 1, // This number indicates how many time steps // are being written to the file system.time); } #endif // #ifdef LIBMESH_HAVE_EXODUS_API // Now we begin the timestep loop to compute the time-accurate // solution of the equations. for (unsigned int t_step=0; t_step != n_timesteps; ++t_step) { // A pretty update message libMesh::out << "\n\nSolving time step " << t_step << ", time = " << system.time << std::endl; system.solve(); // Advance to the next timestep in a transient problem system.time_solver->advance_timestep(); // Copy over updated velocity and acceleration for output. // Note we can do this because of the matching variables/FE spaces if( time_solver == std::string("newmark") ) { *(v_system->solution) = system.get_vector("_old_solution_rate"); *(a_system->solution) = system.get_vector("_old_solution_accel"); } #ifdef LIBMESH_HAVE_EXODUS_API // Write out this timestep if we're requested to if ((t_step+1)%write_interval == 0) { std::ostringstream file_name; // We write the file in the ExodusII format. file_name << std::string("out.")+time_solver+std::string(".e-s.") << std::setw(3) << std::setfill('0') << std::right << t_step+1; ExodusII_IO(mesh).write_timestep(file_name.str(), equation_systems, 1, // This number indicates how many time steps // are being written to the file system.time); } #endif // #ifdef LIBMESH_HAVE_EXODUS_API } // All done. return 0; } <commit_msg>Fix fem_system_ex3 missing include.<commit_after>// The libMesh Finite Element Library. // Copyright (C) 2002-2020 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // <h1>FEMSystem Example 3 - Unsteady Linear Elasticity with // FEMSystem</h1> // \author Paul Bauman // \date 2015 // // This example shows how to solve the three-dimensional transient // linear elasticity equations using the DifferentiableSystem class framework. // This is just Systems of Equations Example 6 recast. // C++ includes #include <iomanip> // Basic include files #include "libmesh/equation_systems.h" #include "libmesh/error_vector.h" #include "libmesh/getpot.h" #include "libmesh/exodusII_io.h" #include "libmesh/kelly_error_estimator.h" #include "libmesh/mesh.h" #include "libmesh/mesh_generation.h" #include "libmesh/enum_solver_package.h" #include "libmesh/enum_solver_type.h" #include "libmesh/auto_ptr.h" // libmesh_make_unique #include "libmesh/numeric_vector.h" // The systems and solvers we may use #include "elasticity_system.h" #include "libmesh/diff_solver.h" #include "libmesh/newmark_solver.h" #include "libmesh/steady_solver.h" #include "libmesh/euler_solver.h" #include "libmesh/euler2_solver.h" #include "libmesh/elem.h" #include "libmesh/newton_solver.h" #include "libmesh/eigen_sparse_linear_solver.h" #define x_scaling 1.3 // Bring in everything from the libMesh namespace using namespace libMesh; // The main program. int main (int argc, char ** argv) { // Initialize libMesh. LibMeshInit init (argc, argv); // This example requires a linear solver package. libmesh_example_requires(libMesh::default_solver_package() != INVALID_SOLVER_PACKAGE, "--enable-petsc, --enable-trilinos, or --enable-eigen"); // This example requires 3D calculations libmesh_example_requires(LIBMESH_DIM > 2, "3D support"); // We use Dirichlet boundary conditions here #ifndef LIBMESH_ENABLE_DIRICHLET libmesh_example_requires(false, "--enable-dirichlet"); #endif // Parse the input file GetPot infile("fem_system_ex3.in"); // Override input file arguments from the command line infile.parse_command_line(argc, argv); // Read in parameters from the input file const Real deltat = infile("deltat", 0.25); unsigned int n_timesteps = infile("n_timesteps", 1); #ifdef LIBMESH_HAVE_EXODUS_API const unsigned int write_interval = infile("write_interval", 1); #endif // Initialize the cantilever mesh const unsigned int dim = 3; // Make sure libMesh was compiled for 3D libmesh_example_requires(dim == LIBMESH_DIM, "3D support"); // Create a 3D mesh distributed across the default MPI communicator. Mesh mesh(init.comm(), dim); MeshTools::Generation::build_cube (mesh, 32, 8, 4, 0., 1.*x_scaling, 0., 0.3, 0., 0.1, HEX8); // Print information about the mesh to the screen. mesh.print_info(); // Let's add some node and edge boundary conditions. // Each processor should know about each boundary condition it can // see, so we loop over all elements, not just local elements. for (const auto & elem : mesh.element_ptr_range()) { unsigned int side_max_x = 0, side_min_y = 0, side_max_y = 0, side_max_z = 0; bool found_side_max_x = false, found_side_max_y = false, found_side_min_y = false, found_side_max_z = false; for (auto side : elem->side_index_range()) { if (mesh.get_boundary_info().has_boundary_id(elem, side, boundary_id_max_x)) { side_max_x = side; found_side_max_x = true; } if (mesh.get_boundary_info().has_boundary_id(elem, side, boundary_id_min_y)) { side_min_y = side; found_side_min_y = true; } if (mesh.get_boundary_info().has_boundary_id(elem, side, boundary_id_max_y)) { side_max_y = side; found_side_max_y = true; } if (mesh.get_boundary_info().has_boundary_id(elem, side, boundary_id_max_z)) { side_max_z = side; found_side_max_z = true; } } // If elem has sides on boundaries // BOUNDARY_ID_MAX_X, BOUNDARY_ID_MAX_Y, BOUNDARY_ID_MAX_Z // then let's set a node boundary condition if (found_side_max_x && found_side_max_y && found_side_max_z) for (auto n : elem->node_index_range()) if (elem->is_node_on_side(n, side_max_x) && elem->is_node_on_side(n, side_max_y) && elem->is_node_on_side(n, side_max_z)) mesh.get_boundary_info().add_node(elem->node_ptr(n), node_boundary_id); // If elem has sides on boundaries // BOUNDARY_ID_MAX_X and BOUNDARY_ID_MIN_Y // then let's set an edge boundary condition if (found_side_max_x && found_side_min_y) for (auto e : elem->edge_index_range()) if (elem->is_edge_on_side(e, side_max_x) && elem->is_edge_on_side(e, side_min_y)) mesh.get_boundary_info().add_edge(elem, e, edge_boundary_id); } // Create an equation systems object. EquationSystems equation_systems (mesh); // Declare the system "Navier-Stokes" and its variables. ElasticitySystem & system = equation_systems.add_system<ElasticitySystem> ("Linear Elasticity"); // Solve this as a time-dependent or steady system std::string time_solver = infile("time_solver","DIE!"); ExplicitSystem * v_system; ExplicitSystem * a_system; if( time_solver == std::string("newmark") ) { // Create ExplicitSystem to help output velocity v_system = &equation_systems.add_system<ExplicitSystem> ("Velocity"); v_system->add_variable("u_vel", FIRST, LAGRANGE); v_system->add_variable("v_vel", FIRST, LAGRANGE); v_system->add_variable("w_vel", FIRST, LAGRANGE); // Create ExplicitSystem to help output acceleration a_system = &equation_systems.add_system<ExplicitSystem> ("Acceleration"); a_system->add_variable("u_accel", FIRST, LAGRANGE); a_system->add_variable("v_accel", FIRST, LAGRANGE); a_system->add_variable("w_accel", FIRST, LAGRANGE); } if (time_solver == std::string("newmark")) system.time_solver = libmesh_make_unique<NewmarkSolver>(system); else if( time_solver == std::string("euler") ) { system.time_solver = libmesh_make_unique<EulerSolver>(system); EulerSolver & euler_solver = cast_ref<EulerSolver &>(*(system.time_solver.get())); euler_solver.theta = infile("theta", 1.0); } else if( time_solver == std::string("euler2") ) { system.time_solver = libmesh_make_unique<Euler2Solver>(system); Euler2Solver & euler_solver = cast_ref<Euler2Solver &>(*(system.time_solver.get())); euler_solver.theta = infile("theta", 1.0); } else if( time_solver == std::string("steady")) { system.time_solver = libmesh_make_unique<SteadySolver>(system); libmesh_assert_equal_to (n_timesteps, 1); } else libmesh_error_msg(std::string("ERROR: invalid time_solver ")+time_solver); // Initialize the system equation_systems.init (); // Set the time stepping options system.deltat = deltat; // And the nonlinear solver options DiffSolver & solver = *(system.time_solver->diff_solver().get()); solver.quiet = infile("solver_quiet", true); solver.verbose = !solver.quiet; solver.max_nonlinear_iterations = infile("max_nonlinear_iterations", 15); solver.relative_step_tolerance = infile("relative_step_tolerance", 1.e-3); solver.relative_residual_tolerance = infile("relative_residual_tolerance", 0.0); solver.absolute_residual_tolerance = infile("absolute_residual_tolerance", 0.0); // And the linear solver options solver.max_linear_iterations = infile("max_linear_iterations", 50000); solver.initial_linear_tolerance = infile("initial_linear_tolerance", 1.e-3); // Print information about the system to the screen. equation_systems.print_info(); // If we're using EulerSolver or Euler2Solver, and we're using EigenSparseLinearSolver, // then we need to reset the EigenSparseLinearSolver to use SPARSELU because BICGSTAB // chokes on the Jacobian matrix we give it and Eigen's GMRES currently doesn't work. NewtonSolver * newton_solver = dynamic_cast<NewtonSolver *>( &solver ); if( newton_solver && (time_solver == std::string("euler") || time_solver == std::string("euler2") ) ) { #ifdef LIBMESH_HAVE_EIGEN_SPARSE LinearSolver<Number> & linear_solver = newton_solver->get_linear_solver(); EigenSparseLinearSolver<Number> * eigen_linear_solver = dynamic_cast<EigenSparseLinearSolver<Number> *>(&linear_solver); if( eigen_linear_solver ) eigen_linear_solver->set_solver_type(SPARSELU); #endif } if( time_solver == std::string("newmark") ) { NewmarkSolver * newmark = cast_ptr<NewmarkSolver*>(system.time_solver.get()); newmark->compute_initial_accel(); // Copy over initial velocity and acceleration for output. // Note we can do this because of the matching variables/FE spaces *(v_system->solution) = system.get_vector("_old_solution_rate"); *(a_system->solution) = system.get_vector("_old_solution_accel"); } #ifdef LIBMESH_HAVE_EXODUS_API // Output initial state { std::ostringstream file_name; // We write the file in the ExodusII format. file_name << std::string("out.")+time_solver+std::string(".e-s.") << std::setw(3) << std::setfill('0') << std::right << 0; ExodusII_IO(mesh).write_timestep(file_name.str(), equation_systems, 1, // This number indicates how many time steps // are being written to the file system.time); } #endif // #ifdef LIBMESH_HAVE_EXODUS_API // Now we begin the timestep loop to compute the time-accurate // solution of the equations. for (unsigned int t_step=0; t_step != n_timesteps; ++t_step) { // A pretty update message libMesh::out << "\n\nSolving time step " << t_step << ", time = " << system.time << std::endl; system.solve(); // Advance to the next timestep in a transient problem system.time_solver->advance_timestep(); // Copy over updated velocity and acceleration for output. // Note we can do this because of the matching variables/FE spaces if( time_solver == std::string("newmark") ) { *(v_system->solution) = system.get_vector("_old_solution_rate"); *(a_system->solution) = system.get_vector("_old_solution_accel"); } #ifdef LIBMESH_HAVE_EXODUS_API // Write out this timestep if we're requested to if ((t_step+1)%write_interval == 0) { std::ostringstream file_name; // We write the file in the ExodusII format. file_name << std::string("out.")+time_solver+std::string(".e-s.") << std::setw(3) << std::setfill('0') << std::right << t_step+1; ExodusII_IO(mesh).write_timestep(file_name.str(), equation_systems, 1, // This number indicates how many time steps // are being written to the file system.time); } #endif // #ifdef LIBMESH_HAVE_EXODUS_API } // All done. return 0; } <|endoftext|>
<commit_before>#include "texturetile.h" #include <QtCore/QDebug> #include "katlasdirs.h" #include "TileLoader.h" static uint **jumpTableFromQImage32( QImage &img ) { const int height = img.height(); const int bpl = img.bytesPerLine() / 4; uint *data = (QRgb*)(img.scanLine(0)); uint **jumpTable = new uint*[height]; for ( int y = 0; y < height; ++y ) { jumpTable[ y ] = data; data += bpl; } return jumpTable; } static uchar **jumpTableFromQImage8( QImage &img ) { const int height = img.height(); const int bpl = img.bytesPerLine(); uchar *data = img.bits(); uchar **jumpTable = new uchar*[height]; for ( int y = 0; y < height; ++y ) { jumpTable[ y ] = data; data += bpl; } return jumpTable; } TextureTile::TextureTile( int x, int y, int level, const QString& theme ) : QObject() { loadTile( x, y, level, theme, false ); } void TextureTile::loadTile( int x, int y, int level, const QString& theme, bool requestRepaint ) { m_used = true; QString absfilename; // qDebug() << "Requested tile level" << level; // If the tile level offers the requested tile then load it. // Otherwise cycle from the requested tilelevel down to one where // the requested area is covered. Then scale the area to create a // replacement for the tile that has been requested. for ( int i = level; i > -1; --i ) { float origx1 = (float)(x) / (float)( TileLoader::levelToRow( level ) ); float origy1 = (float)(y) / (float)( TileLoader::levelToColumn( level ) ); float testx1 = origx1 * (float)( TileLoader::levelToRow( i ) ) ; float testy1 = origy1 * (float)( TileLoader::levelToColumn( i ) ); QString relfilename = QString("%1/%2/%3/%3_%4.jpg").arg(theme).arg(i).arg( (int)(testy1), 4, 10, QChar('0') ).arg( (int)(testx1), 4, 10, QChar('0') ); absfilename = KAtlasDirs::path( relfilename ); if ( QFile::exists( absfilename ) ){ m_rawtile = new QImage( absfilename ); // qDebug() << absfilename; if ( !m_rawtile->isNull() ) { if ( level != i ) { QSize tilesize = m_rawtile->size(); float origx2 = (float)(x + 1) / (float)( TileLoader::levelToRow( level ) ); float origy2 = (float)(y + 1) / (float)( TileLoader::levelToColumn( level ) ); float testx2 = origx2 * (float)( TileLoader::levelToRow( i ) ); float testy2 = origy2 * (float)( TileLoader::levelToColumn( i ) ); QPoint topleft( (int)( ( testx1 - (int)(testx1) ) * m_rawtile->width() ), (int)( ( testy1 - (int)(testy1) ) * m_rawtile->height() ) ); QPoint bottomright( (int)( ( testx2 - (int)(testx1) ) * m_rawtile->width() ) - 1, (int)( ( testy2 - (int)(testy1) ) * m_rawtile->height() ) - 1 ); // qDebug() << "x1: " << topleft.x() << "y1: " << topleft.y() << "x2: " << bottomright.x() << "y2: " << bottomright.y(); *m_rawtile = m_rawtile->copy( QRect( topleft, bottomright ) ); *m_rawtile = m_rawtile->scaled( tilesize ); // TODO: use correct size } break; } } else { emit downloadTile( relfilename ); } } if ( m_rawtile->isNull() ){ qDebug() << "An essential tile is missing. Please rerun the application."; exit(-1); } m_depth = m_rawtile->depth(); switch ( m_depth ) { case 32: // qDebug("32"); jumpTable32=jumpTableFromQImage32(*m_rawtile); break; case 8: // qDebug("8"); jumpTable8=jumpTableFromQImage8(*m_rawtile); break; default: qDebug() << QString("Color m_depth %1 of tile %2 could not be retrieved. Exiting.").arg(m_depth).arg(absfilename); exit(-1); } if ( requestRepaint == true ) emit tileUpdate(); } TextureTile::~TextureTile() { switch ( m_depth ) { case 32: delete [] jumpTable32; break; case 8: delete [] jumpTable8; break; default: qDebug("Color m_depth of a tile could not be retrieved. Exiting."); exit(-1); } delete m_rawtile; } void TextureTile::slotLoadTile( const QString& path ) { // QString relfilename = QString("%1/%2/%3/%3_%4.jpg").arg(theme).arg(i).arg( (int)(testy1), 4, 10, QChar('0') ).arg( (int)(testx1), 4, 10, QChar('0') ); QString filename = path.section( '/', -1 ); int x = filename.section( '_', 0, 0 ).toInt(); int y = filename.section( '_', 1, 1 ).section( '.', 0, 0 ).toInt(); int level = path.section( '/', 1, 1 ).toInt(); QString theme = path.section( '/', 0, 0 ); // qDebug() << "Test: |" << theme << "|" << level << "|" << x << "|" << y; loadTile( x, y, level, theme, true ); } #ifndef Q_OS_MACX #include "texturetile.moc" #endif <commit_msg>Mark a possible memory leak<commit_after>#include "texturetile.h" #include <QtCore/QDebug> #include "katlasdirs.h" #include "TileLoader.h" static uint **jumpTableFromQImage32( QImage &img ) { const int height = img.height(); const int bpl = img.bytesPerLine() / 4; uint *data = (QRgb*)(img.scanLine(0)); uint **jumpTable = new uint*[height]; for ( int y = 0; y < height; ++y ) { jumpTable[ y ] = data; data += bpl; } return jumpTable; } static uchar **jumpTableFromQImage8( QImage &img ) { const int height = img.height(); const int bpl = img.bytesPerLine(); uchar *data = img.bits(); uchar **jumpTable = new uchar*[height]; for ( int y = 0; y < height; ++y ) { jumpTable[ y ] = data; data += bpl; } return jumpTable; } TextureTile::TextureTile( int x, int y, int level, const QString& theme ) : QObject() { loadTile( x, y, level, theme, false ); } void TextureTile::loadTile( int x, int y, int level, const QString& theme, bool requestRepaint ) { m_used = true; QString absfilename; // qDebug() << "Requested tile level" << level; // If the tile level offers the requested tile then load it. // Otherwise cycle from the requested tilelevel down to one where // the requested area is covered. Then scale the area to create a // replacement for the tile that has been requested. for ( int i = level; i > -1; --i ) { float origx1 = (float)(x) / (float)( TileLoader::levelToRow( level ) ); float origy1 = (float)(y) / (float)( TileLoader::levelToColumn( level ) ); float testx1 = origx1 * (float)( TileLoader::levelToRow( i ) ) ; float testy1 = origy1 * (float)( TileLoader::levelToColumn( i ) ); QString relfilename = QString("%1/%2/%3/%3_%4.jpg").arg(theme).arg(i).arg( (int)(testy1), 4, 10, QChar('0') ).arg( (int)(testx1), 4, 10, QChar('0') ); absfilename = KAtlasDirs::path( relfilename ); if ( QFile::exists( absfilename ) ) { m_rawtile = new QImage( absfilename ); // qDebug() << absfilename; if ( !m_rawtile->isNull() ) { if ( level != i ) { QSize tilesize = m_rawtile->size(); float origx2 = (float)(x + 1) / (float)( TileLoader::levelToRow( level ) ); float origy2 = (float)(y + 1) / (float)( TileLoader::levelToColumn( level ) ); float testx2 = origx2 * (float)( TileLoader::levelToRow( i ) ); float testy2 = origy2 * (float)( TileLoader::levelToColumn( i ) ); QPoint topleft( (int)( ( testx1 - (int)(testx1) ) * m_rawtile->width() ), (int)( ( testy1 - (int)(testy1) ) * m_rawtile->height() ) ); QPoint bottomright( (int)( ( testx2 - (int)(testx1) ) * m_rawtile->width() ) - 1, (int)( ( testy2 - (int)(testy1) ) * m_rawtile->height() ) - 1 ); // qDebug() << "x1: " << topleft.x() << "y1: " << topleft.y() << "x2: " << bottomright.x() << "y2: " << bottomright.y(); // FIXME: Memory leaks?? *m_rawtile = m_rawtile->copy( QRect( topleft, bottomright ) ); *m_rawtile = m_rawtile->scaled( tilesize ); // TODO: use correct size } break; } } else { emit downloadTile( relfilename ); } } if ( m_rawtile->isNull() ){ qDebug() << "An essential tile is missing. Please rerun the application."; exit(-1); } m_depth = m_rawtile->depth(); switch ( m_depth ) { case 32: // qDebug("32"); jumpTable32=jumpTableFromQImage32(*m_rawtile); break; case 8: // qDebug("8"); jumpTable8=jumpTableFromQImage8(*m_rawtile); break; default: qDebug() << QString("Color m_depth %1 of tile %2 could not be retrieved. Exiting.").arg(m_depth).arg(absfilename); exit(-1); } if ( requestRepaint == true ) emit tileUpdate(); } TextureTile::~TextureTile() { switch ( m_depth ) { case 32: delete [] jumpTable32; break; case 8: delete [] jumpTable8; break; default: qDebug("Color m_depth of a tile could not be retrieved. Exiting."); exit(-1); } delete m_rawtile; } void TextureTile::slotLoadTile( const QString& path ) { // QString relfilename = QString("%1/%2/%3/%3_%4.jpg").arg(theme).arg(i).arg( (int)(testy1), 4, 10, QChar('0') ).arg( (int)(testx1), 4, 10, QChar('0') ); QString filename = path.section( '/', -1 ); int x = filename.section( '_', 0, 0 ).toInt(); int y = filename.section( '_', 1, 1 ).section( '.', 0, 0 ).toInt(); int level = path.section( '/', 1, 1 ).toInt(); QString theme = path.section( '/', 0, 0 ); // qDebug() << "Test: |" << theme << "|" << level << "|" << x << "|" << y; loadTile( x, y, level, theme, true ); } #ifndef Q_OS_MACX #include "texturetile.moc" #endif <|endoftext|>
<commit_before><commit_msg>Fixing crash with dereferencing front() and back() of an empty vector<commit_after><|endoftext|>
<commit_before><commit_msg>Related: fdo#58819 VML import: shape types not starting with a hashmark are OK<commit_after><|endoftext|>
<commit_before> #include "vio/timegrabber.h" #include <sstream> #include "vio/eigen_utils.h" #include "vio/utils.h" using namespace std; namespace vio { TimeGrabber::TimeGrabber() : last_line_index(-1), last_line_time(-1), isTimeFormatSet(false) {} TimeGrabber::TimeGrabber(const string time_file_name) : time_file(time_file_name), time_stream(time_file_name.c_str()), last_line_index(-1), last_line_time(-1), isTimeFormatSet(false) { if (!time_stream.is_open()) { std::cout << "Error opening timestamp file " << time_file_name << std::endl; } else { std::string tempStr; int headerLines = countHeaderLines(time_file_name); for (int jack = 0; jack < headerLines; ++jack) { getline(time_stream, tempStr); } } } TimeGrabber::~TimeGrabber() { time_stream.close(); } bool TimeGrabber::isTimeAvailable() const { return time_stream.is_open(); } bool TimeGrabber::init(const string time_file_name) { time_file = time_file_name; time_stream.open(time_file_name.c_str()); last_line_index = -1; last_line_time = -1; if (!time_stream.is_open()) { std::cout << "Error opening timestamp file " << time_file_name << std::endl; return false; } else { std::string tempStr; int headerLines = countHeaderLines(time_file_name); for (int jack = 0; jack < headerLines; ++jack) getline(time_stream, tempStr); } return true; } double TimeGrabber::readTimestamp(int line_number) { string tempStr; double precursor(-1); if (last_line_index > line_number) { cerr << "Reading previous timestamps is unsupported!" << endl; return -1; } if (last_line_index == line_number) return last_line_time; while (last_line_index < line_number) { if (!isTimeFormatSet) { time_stream >> precursor; isTimeInNanos = vio::isTimeInNanos(precursor); if (isTimeInNanos) { int64_t timeNanos = (int64_t)precursor; precursor = vio::nanoIntToSecDouble(timeNanos); } isTimeFormatSet = true; } else { if (isTimeInNanos) { int64_t timeNanos; time_stream >> timeNanos; precursor = vio::nanoIntToSecDouble(timeNanos); } else { time_stream >> precursor; } } if (time_stream.fail()) { break; } getline(time_stream, tempStr); // remove the remaining part, this works // even when it is empty ++last_line_index; } if (last_line_index < line_number) { cerr << "Failed to find " << line_number << "th line in time file!" << endl; return -1; } last_line_time = precursor; return last_line_time; } // extract time from a text file // for malaga dataset whose timestamps are in /*_IMAGE.txt file, // every two lines are the left and right image names, typically with the same // timestamp, e.g., img_CAMERA1_1261228749.918590_left.jpg // img_CAMERA1_1261228749.918590_right.jpg // img_CAMERA1_1261228749.968589_left.jpg // img_CAMERA1_1261228749.968589_right.jpg // Thus, frame number is 0 for the first two lines in the /*_IMAGE.txt file // for indexed time file, each line is frame number, time in millisec double TimeGrabber::extractTimestamp(int frame_number, bool isMalagaDataset) { string tempStr; double timestamp(-1); if (last_line_index > frame_number) { cerr << "Read previous timestamps is unsupported!" << endl; return -1; } if (last_line_index == frame_number) { return last_line_time; } while (last_line_index < frame_number) { getline(time_stream, tempStr); if (time_stream.fail()) break; if (isMalagaDataset) { last_left_image_name = tempStr; getline(time_stream, tempStr); // read in the right image name timestamp = -1; timestamp = atof(tempStr.substr(12, 17).c_str()); } else { // frame index and timestamp in millisec std::istringstream iss(tempStr); int frameIndex(-1); timestamp = -1; iss >> frameIndex >> timestamp; timestamp *= 0.001; } ++last_line_index; } if (last_line_index < frame_number) { cerr << "Failed to find " << frame_number << "th line in time file!" << endl; return -1; } last_line_time = timestamp; return last_line_time; } } // namespace vio <commit_msg>simplify code<commit_after> #include "vio/timegrabber.h" #include <sstream> #include "vio/eigen_utils.h" #include "vio/utils.h" using namespace std; namespace vio { TimeGrabber::TimeGrabber() : last_line_index(-1), last_line_time(-1), isTimeFormatSet(false) {} TimeGrabber::TimeGrabber(const string time_file_name) { init(time_file_name); } TimeGrabber::~TimeGrabber() { time_stream.close(); } bool TimeGrabber::isTimeAvailable() const { return time_stream.is_open(); } bool TimeGrabber::init(const string time_file_name) { time_file = time_file_name; time_stream.open(time_file_name.c_str()); last_line_index = -1; last_line_time = -1; isTimeFormatSet = false; if (!time_stream.is_open()) { std::cout << "Failed to open timestamp file:" << time_file_name << ".\n" << " This is OK if the time file is not provided intentionally." << std::endl; return false; } else { std::string tempStr; int headerLines = countHeaderLines(time_file_name); for (int jack = 0; jack < headerLines; ++jack) getline(time_stream, tempStr); } return true; } double TimeGrabber::readTimestamp(int line_number) { string tempStr; double precursor(-1); if (last_line_index > line_number) { cerr << "Reading previous timestamps is unsupported!" << endl; return -1; } if (last_line_index == line_number) return last_line_time; while (last_line_index < line_number) { if (!isTimeFormatSet) { time_stream >> precursor; isTimeInNanos = vio::isTimeInNanos(precursor); if (isTimeInNanos) { int64_t timeNanos = (int64_t)precursor; precursor = vio::nanoIntToSecDouble(timeNanos); } isTimeFormatSet = true; } else { if (isTimeInNanos) { int64_t timeNanos; time_stream >> timeNanos; precursor = vio::nanoIntToSecDouble(timeNanos); } else { time_stream >> precursor; } } if (time_stream.fail()) { break; } getline(time_stream, tempStr); // remove the remaining part, this works // even when it is empty ++last_line_index; } if (last_line_index < line_number) { cerr << "Failed to find " << line_number << "th line in time file!" << endl; return -1; } last_line_time = precursor; return last_line_time; } // extract time from a text file // for malaga dataset whose timestamps are in /*_IMAGE.txt file, // every two lines are the left and right image names, typically with the same // timestamp, e.g., img_CAMERA1_1261228749.918590_left.jpg // img_CAMERA1_1261228749.918590_right.jpg // img_CAMERA1_1261228749.968589_left.jpg // img_CAMERA1_1261228749.968589_right.jpg // Thus, frame number is 0 for the first two lines in the /*_IMAGE.txt file // for indexed time file, each line is frame number, time in millisec double TimeGrabber::extractTimestamp(int frame_number, bool isMalagaDataset) { string tempStr; double timestamp(-1); if (last_line_index > frame_number) { cerr << "Read previous timestamps is unsupported!" << endl; return -1; } if (last_line_index == frame_number) { return last_line_time; } while (last_line_index < frame_number) { getline(time_stream, tempStr); if (time_stream.fail()) break; if (isMalagaDataset) { last_left_image_name = tempStr; getline(time_stream, tempStr); // read in the right image name timestamp = -1; timestamp = atof(tempStr.substr(12, 17).c_str()); } else { // frame index and timestamp in millisec std::istringstream iss(tempStr); int frameIndex(-1); timestamp = -1; iss >> frameIndex >> timestamp; timestamp *= 0.001; } ++last_line_index; } if (last_line_index < frame_number) { cerr << "Failed to find " << frame_number << "th line in time file!" << endl; return -1; } last_line_time = timestamp; return last_line_time; } } // namespace vio <|endoftext|>
<commit_before>/* * opencog/atomspace/Handle.cc * * Copyright (C) 2002-2007 Novamente LLC * Copyright (C) 2013 Linas Vepstas <linas@linas.org> * All Rights Reserved * * Written by Thiago Maia <thiago@vettatech.com> * Andre Senna <senna@vettalabs.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <climits> #include <opencog/atomspace/Handle.h> #include <opencog/atomspace/Atom.h> #include <opencog/atomspace/AtomTable.h> using namespace opencog; const Handle Handle::UNDEFINED(ULONG_MAX); Handle::Handle(AtomPtr atom) : _uuid(atom->_uuid), _ptr(atom) {} Handle& Handle::operator=(const AtomPtr& a) { this->_uuid = a->_uuid; this->_ptr = a; return *this; } // =================================================== // Handle resolution stuff. // Its a vector, not a set, because its priority ranked. std::vector<const AtomTable*> Handle::_resolver; void Handle::set_resolver(const AtomTable* tab) { _resolver.push_back(tab); } void Handle::clear_resolver(const AtomTable* tab) { auto end = _resolver.end(); for (auto it = _resolver.begin(); it != end; it++) { if (*it == tab) { _resolver.erase(it); break; } } } // Search several atomspaces, in order. First one to come up with // the atom wins. Seems to work, for now. inline AtomPtr Handle::do_res(const Handle* hp) { auto end = _resolver.end(); for (auto it = _resolver.begin(); it != end; it++) { const AtomTable* at = *it; AtomPtr a(at->getHandle((Handle&)(*hp))._ptr); if (a.get()) return a; } return NULL; } Atom* Handle::resolve() { AtomPtr a(do_res(this)); _ptr.swap(a); return _ptr.get(); } Atom* Handle::cresolve() const { return do_res(this).get(); } AtomPtr Handle::resolve_ptr() { AtomPtr a(do_res(this)); _ptr.swap(a); return _ptr; } <commit_msg>Simplify Handle::{set_resolver,clear_resolver} using more modern C++<commit_after>/* * opencog/atomspace/Handle.cc * * Copyright (C) 2002-2007 Novamente LLC * Copyright (C) 2013 Linas Vepstas <linas@linas.org> * All Rights Reserved * * Written by Thiago Maia <thiago@vettatech.com> * Andre Senna <senna@vettalabs.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <climits> #include <opencog/atomspace/Handle.h> #include <opencog/atomspace/Atom.h> #include <opencog/atomspace/AtomTable.h> using namespace opencog; const Handle Handle::UNDEFINED(ULONG_MAX); Handle::Handle(AtomPtr atom) : _uuid(atom->_uuid), _ptr(atom) {} Handle& Handle::operator=(const AtomPtr& a) { this->_uuid = a->_uuid; this->_ptr = a; return *this; } // =================================================== // Handle resolution stuff. // Its a vector, not a set, because its priority ranked. std::vector<const AtomTable*> Handle::_resolver; void Handle::set_resolver(const AtomTable* tab) { _resolver.push_back(tab); } void Handle::clear_resolver(const AtomTable* tab) { auto it = std::find(_resolver.begin(), _resolver.end(), tab); if (it != _resolver.end()) _resolver.erase(it); } // Search several atomspaces, in order. First one to come up with // the atom wins. Seems to work, for now. inline AtomPtr Handle::do_res(const Handle* hp) { for (const AtomTable* at : _resolver) { AtomPtr a(at->getHandle((Handle&)(*hp))._ptr); if (a.get()) return a; } return NULL; } Atom* Handle::resolve() { AtomPtr a(do_res(this)); _ptr.swap(a); return _ptr.get(); } Atom* Handle::cresolve() const { return do_res(this).get(); } AtomPtr Handle::resolve_ptr() { AtomPtr a(do_res(this)); _ptr.swap(a); return _ptr; } <|endoftext|>
<commit_before>#line 2 "togo/traits.hpp" /** @copyright MIT license; see @ref index or the accompanying LICENSE file. @file @brief Type traits. @ingroup utility */ #pragma once #include <togo/config.hpp> namespace togo { /** @addtogroup utility @{ */ /** @name Type traits */ /// @{ /// Type with static constexpr value equal to false. struct false_type { static constexpr bool const value = false; }; /// Type with static constexpr value equal to true. struct true_type { static constexpr bool const value = true; }; /** @cond INTERNAL */ namespace { template<bool, class> struct enable_if_impl; template<class T> struct enable_if_impl<false, T> {}; template<class T> struct enable_if_impl<true, T> { using type = T; }; } // anonymous namespace /** @endcond */ // INTERNAL /// SFINAE enabler type alias. template<bool C, class T = void> using enable_if = typename enable_if_impl<C, T>::type; namespace { template<class T> struct remove_ref_impl { using type = T; }; template<class T> struct remove_ref_impl<T&> { using type = T; }; } // anonymous namespace /// Remove reference qualification from type. template<class T> using remove_ref = typename remove_ref_impl<T>::type; namespace { template<class T> struct remove_cvr_impl { using type = T; }; template<class T> struct remove_cvr_impl<T const> { using type = T; }; template<class T> struct remove_cvr_impl<T volatile> { using type = T; }; template<class T> struct remove_cvr_impl<T const volatile> { using type = T; }; } // anonymous namespace /// Remove const, volatile, and reference qualifications from type. template<class T> using remove_cvr = typename remove_cvr_impl<remove_ref<T>>::type; namespace { template<class T> struct is_signed_impl : false_type {}; template<> struct is_signed_impl<signed char> : true_type {}; template<> struct is_signed_impl<signed short> : true_type {}; template<> struct is_signed_impl<signed int> : true_type {}; template<> struct is_signed_impl<signed long> : true_type {}; template<> struct is_signed_impl<signed long long> : true_type {}; } // anonymous namespace /// Type with static constexpr value equal to true if T is /// a signed integral. template<class T> using is_signed = is_signed_impl<remove_cvr<T>>; namespace { template<class T> struct is_unsigned_impl : false_type {}; template<> struct is_unsigned_impl<unsigned char> : true_type {}; template<> struct is_unsigned_impl<unsigned short> : true_type {}; template<> struct is_unsigned_impl<unsigned int> : true_type {}; template<> struct is_unsigned_impl<unsigned long> : true_type {}; template<> struct is_unsigned_impl<unsigned long long> : true_type {}; } // anonymous namespace /// Type with static constexpr value equal to true if T is /// an unsigned integral. template<class T> using is_unsigned = is_unsigned_impl<remove_cvr<T>>; namespace { template<class T, class U> struct is_same_impl : false_type {}; template<class T> struct is_same_impl<T, T> : true_type {}; } // anonymous namespace /// Type with static constexpr value equal to true if T is /// the same as U. template<class T, class U> using is_same = is_same_impl<T, U>; /// @} /// Enum-class bitwise operator enabler. /// /// Specialize this class deriving from true_type to enable bit-wise /// operators for an enum-class. template<class> struct enable_enum_bitwise_ops : false_type {}; /** @} */ // end of doc-group utility } // namespace togo <commit_msg>traits: added remove_cv<T>.<commit_after>#line 2 "togo/traits.hpp" /** @copyright MIT license; see @ref index or the accompanying LICENSE file. @file @brief Type traits. @ingroup utility */ #pragma once #include <togo/config.hpp> namespace togo { /** @addtogroup utility @{ */ /** @name Type traits */ /// @{ /// Type with static constexpr value equal to false. struct false_type { static constexpr bool const value = false; }; /// Type with static constexpr value equal to true. struct true_type { static constexpr bool const value = true; }; /** @cond INTERNAL */ namespace { template<bool, class> struct enable_if_impl; template<class T> struct enable_if_impl<false, T> {}; template<class T> struct enable_if_impl<true, T> { using type = T; }; } // anonymous namespace /** @endcond */ // INTERNAL /// SFINAE enabler type alias. template<bool C, class T = void> using enable_if = typename enable_if_impl<C, T>::type; namespace { template<class T> struct remove_ref_impl { using type = T; }; template<class T> struct remove_ref_impl<T&> { using type = T; }; } // anonymous namespace /// Remove reference qualification from type. template<class T> using remove_ref = typename remove_ref_impl<T>::type; namespace { template<class T> struct remove_cv_impl { using type = T; }; template<class T> struct remove_cv_impl<T const> { using type = T; }; template<class T> struct remove_cv_impl<T volatile> { using type = T; }; template<class T> struct remove_cv_impl<T const volatile> { using type = T; }; } // anonymous namespace /// Remove const, volatile, and reference qualifications from type. template<class T> using remove_cv = typename remove_cv_impl<T>::type; /// Remove const, volatile, and reference qualifications from type. template<class T> using remove_cvr = typename remove_cv<remove_ref<T>>::type; namespace { template<class T> struct is_signed_impl : false_type {}; template<> struct is_signed_impl<signed char> : true_type {}; template<> struct is_signed_impl<signed short> : true_type {}; template<> struct is_signed_impl<signed int> : true_type {}; template<> struct is_signed_impl<signed long> : true_type {}; template<> struct is_signed_impl<signed long long> : true_type {}; } // anonymous namespace /// Type with static constexpr value equal to true if T is /// a signed integral. template<class T> using is_signed = is_signed_impl<remove_cvr<T>>; namespace { template<class T> struct is_unsigned_impl : false_type {}; template<> struct is_unsigned_impl<unsigned char> : true_type {}; template<> struct is_unsigned_impl<unsigned short> : true_type {}; template<> struct is_unsigned_impl<unsigned int> : true_type {}; template<> struct is_unsigned_impl<unsigned long> : true_type {}; template<> struct is_unsigned_impl<unsigned long long> : true_type {}; } // anonymous namespace /// Type with static constexpr value equal to true if T is /// an unsigned integral. template<class T> using is_unsigned = is_unsigned_impl<remove_cvr<T>>; namespace { template<class T, class U> struct is_same_impl : false_type {}; template<class T> struct is_same_impl<T, T> : true_type {}; } // anonymous namespace /// Type with static constexpr value equal to true if T is /// the same as U. template<class T, class U> using is_same = is_same_impl<T, U>; /// @} /// Enum-class bitwise operator enabler. /// /// Specialize this class deriving from true_type to enable bit-wise /// operators for an enum-class. template<class> struct enable_enum_bitwise_ops : false_type {}; /** @} */ // end of doc-group utility } // namespace togo <|endoftext|>
<commit_before>/* Copyright (c) 2007, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 "libtorrent/pch.hpp" #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/shared_ptr.hpp> #include <boost/lexical_cast.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif #include <vector> #include <utility> #include <numeric> #include <cstdio> #include "libtorrent/peer_connection.hpp" #include "libtorrent/bt_peer_connection.hpp" #include "libtorrent/hasher.hpp" #include "libtorrent/bencode.hpp" #include "libtorrent/torrent.hpp" #include "libtorrent/extensions.hpp" #include "libtorrent/extensions/ut_metadata.hpp" #include "libtorrent/alert_types.hpp" #ifdef TORRENT_STATS #include "libtorrent/aux_/session_impl.hpp" #endif namespace libtorrent { namespace { int div_round_up(int numerator, int denominator) { return (numerator + denominator - 1) / denominator; } void nop(char*) {} struct ut_metadata_plugin : torrent_plugin { ut_metadata_plugin(torrent& t) : m_torrent(t) , m_metadata_progress(0) , m_metadata_size(0) { } virtual void on_files_checked() { // if the torrent is a seed, copy the metadata from // the torrent before it is deallocated if (m_torrent.is_seed()) metadata(); } virtual boost::shared_ptr<peer_plugin> new_connection( peer_connection* pc); buffer::const_interval metadata() const { TORRENT_ASSERT(m_torrent.valid_metadata()); if (!m_metadata) { m_metadata = m_torrent.torrent_file().metadata(); m_metadata_size = m_torrent.torrent_file().metadata_size(); TORRENT_ASSERT(hasher(m_metadata.get(), m_metadata_size).final() == m_torrent.torrent_file().info_hash()); } return buffer::const_interval(m_metadata.get(), m_metadata.get() + m_metadata_size); } bool received_metadata(char const* buf, int size, int piece, int total_size) { if (m_torrent.valid_metadata()) return false; if (!m_metadata) { // verify the total_size if (total_size <= 0 || total_size > 500 * 1024) return false; m_metadata.reset(new char[total_size]); m_requested_metadata.resize(div_round_up(total_size, 16 * 1024), 0); m_metadata_size = total_size; } if (piece < 0 || piece >= int(m_requested_metadata.size())) return false; TORRENT_ASSERT(piece * 16 * 1024 + size <= m_metadata_size); std::memcpy(&m_metadata[piece * 16 * 1024], buf, size); // mark this piece has 'have' m_requested_metadata[piece] = (std::numeric_limits<int>::max)(); bool have_all = std::count(m_requested_metadata.begin() , m_requested_metadata.end(), (std::numeric_limits<int>::max)()) == int(m_requested_metadata.size()); if (!have_all) return false; if (!m_torrent.set_metadata(&m_metadata[0], m_metadata_size)) { if (!m_torrent.valid_metadata()) std::fill(m_requested_metadata.begin(), m_requested_metadata.end(), 0); return false; } // clear the storage for the bitfield std::vector<int>().swap(m_requested_metadata); return true; } // returns a piece of the metadata that // we should request. int metadata_request(); // this is called from the peer_connection for // each piece of metadata it receives void metadata_progress(int total_size, int received) { m_metadata_progress += received; m_metadata_size = total_size; } void on_piece_pass(int) { // if we became a seed, copy the metadata from // the torrent before it is deallocated if (m_torrent.is_seed()) metadata(); } void metadata_size(int size) { if (m_metadata_size > 0 || size <= 0 || size > 500 * 1024) return; m_metadata_size = size; m_metadata.reset(new char[size]); m_requested_metadata.resize(div_round_up(size, 16 * 1024), 0); } private: torrent& m_torrent; // this buffer is filled with the info-section of // the metadata file while downloading it from // peers, and while sending it. // it is mutable because it's generated lazily mutable boost::shared_array<char> m_metadata; int m_metadata_progress; mutable int m_metadata_size; // this vector keeps track of how many times each meatdata // block has been requested // std::numeric_limits<int>::max() means we have the piece std::vector<int> m_requested_metadata; }; struct ut_metadata_peer_plugin : peer_plugin { ut_metadata_peer_plugin(torrent& t, bt_peer_connection& pc , ut_metadata_plugin& tp) : m_message_index(0) , m_no_metadata(min_time()) , m_torrent(t) , m_pc(pc) , m_tp(tp) {} // can add entries to the extension handshake virtual void add_handshake(entry& h) { entry& messages = h["m"]; messages["ut_metadata"] = 15; if (m_torrent.valid_metadata()) h["metadata_size"] = m_tp.metadata().left(); } // called when the extension handshake from the other end is received virtual bool on_extension_handshake(lazy_entry const& h) { m_message_index = 0; if (h.type() != lazy_entry::dict_t) return false; lazy_entry const* messages = h.dict_find("m"); if (!messages || messages->type() != lazy_entry::dict_t) return false; int index = messages->dict_find_int_value("ut_metadata", -1); if (index == -1) return false; m_message_index = index; int metadata_size = h.dict_find_int_value("metadata_size"); if (metadata_size > 0) m_tp.metadata_size(metadata_size); return true; } void write_metadata_packet(int type, int piece) { TORRENT_ASSERT(type >= 0 && type <= 2); TORRENT_ASSERT(piece >= 0); TORRENT_ASSERT(!m_pc.associated_torrent().expired()); #ifdef TORRENT_VERBOSE_LOGGING (*m_pc.m_logger) << time_now_string() << " ==> UT_METADATA [ " "type: " << type << " | piece: " << piece << " ]\n"; #endif // abort if the peer doesn't support the metadata extension if (m_message_index == 0) return; entry e; e["msg_type"] = type; e["piece"] = piece; char const* metadata = 0; int metadata_piece_size = 0; if (type == 1) { TORRENT_ASSERT(m_pc.associated_torrent().lock()->valid_metadata()); e["total_size"] = m_tp.metadata().left(); int offset = piece * 16 * 1024; metadata = m_tp.metadata().begin + offset; metadata_piece_size = (std::min)( int(m_tp.metadata().left() - offset), 16 * 1024); TORRENT_ASSERT(metadata_piece_size > 0); TORRENT_ASSERT(offset >= 0); TORRENT_ASSERT(offset + metadata_piece_size <= int(m_tp.metadata().left())); } char msg[200]; char* header = msg; char* p = &msg[6]; int len = bencode(p, e); int total_size = 2 + len + metadata_piece_size; namespace io = detail; io::write_uint32(total_size, header); io::write_uint8(bt_peer_connection::msg_extended, header); io::write_uint8(m_message_index, header); m_pc.send_buffer(msg, len + 6); if (metadata_piece_size) m_pc.append_send_buffer( (char*)metadata, metadata_piece_size, &nop); } virtual bool on_extended(int length , int extended_msg, buffer::const_interval body) { if (extended_msg != 15) return false; if (m_message_index == 0) return false; if (length > 17 * 1024) { m_pc.disconnect("ut_metadata message larger than 17 kB", 2); return true; } if (!m_pc.packet_finished()) return true; int len; entry msg = bdecode(body.begin, body.end, len); if (msg.type() == entry::undefined_t) { m_pc.disconnect("invalid bencoding in ut_metadata message", 2); return true; } int type = msg["msg_type"].integer(); int piece = msg["piece"].integer(); #ifdef TORRENT_VERBOSE_LOGGING (*m_pc.m_logger) << time_now_string() << " <== UT_METADATA [ " "type: " << type << " | piece: " << piece << " ]\n"; #endif switch (type) { case 0: // request { if (!m_torrent.valid_metadata()) { write_metadata_packet(2, piece); return true; } // TODO: put the request on the queue in some cases write_metadata_packet(1, piece); } break; case 1: // data { std::vector<int>::iterator i = std::find(m_sent_requests.begin() , m_sent_requests.end(), piece); // unwanted piece? if (i == m_sent_requests.end()) return true; m_sent_requests.erase(i); entry const* total_size = msg.find_key("total_size"); m_tp.received_metadata(body.begin + len, body.left() - len, piece , (total_size && total_size->type() == entry::int_t) ? total_size->integer() : 0); } break; case 2: // have no data { m_no_metadata = time_now(); std::vector<int>::iterator i = std::find(m_sent_requests.begin() , m_sent_requests.end(), piece); // unwanted piece? if (i == m_sent_requests.end()) return true; m_sent_requests.erase(i); } break; default: { std::stringstream msg; msg << "unknown ut_metadata extension message: " << type; m_pc.disconnect(msg.str().c_str(), 2); } } return true; } virtual void tick() { // if we don't have any metadata, and this peer // supports the request metadata extension // and we aren't currently waiting for a request // reply. Then, send a request for some metadata. if (!m_torrent.valid_metadata() && m_message_index != 0 && m_sent_requests.size() < 2 && has_metadata()) { int piece = m_tp.metadata_request(); m_sent_requests.push_back(piece); write_metadata_packet(0, piece); } } bool has_metadata() const { return time_now() - m_no_metadata > minutes(1); } private: // this is the message index the remote peer uses // for metadata extension messages. int m_message_index; // this is set to the current time each time we get a // "I don't have metadata" message. ptime m_no_metadata; // request queues std::vector<int> m_sent_requests; std::vector<int> m_incoming_requests; torrent& m_torrent; bt_peer_connection& m_pc; ut_metadata_plugin& m_tp; }; boost::shared_ptr<peer_plugin> ut_metadata_plugin::new_connection( peer_connection* pc) { bt_peer_connection* c = dynamic_cast<bt_peer_connection*>(pc); if (!c) return boost::shared_ptr<peer_plugin>(); return boost::shared_ptr<peer_plugin>(new ut_metadata_peer_plugin(m_torrent, *c, *this)); } int ut_metadata_plugin::metadata_request() { std::vector<int>::iterator i = std::min_element( m_requested_metadata.begin(), m_requested_metadata.end()); if (m_requested_metadata.empty()) { // if we don't know how many pieces there are // just ask for piece 0 m_requested_metadata.resize(1, 1); return 0; } int piece = i - m_requested_metadata.begin(); m_requested_metadata[piece] = piece; return piece; } } } namespace libtorrent { boost::shared_ptr<torrent_plugin> create_ut_metadata_plugin(torrent* t, void*) { return boost::shared_ptr<torrent_plugin>(new ut_metadata_plugin(*t)); } } <commit_msg>ut_metadata fix to not send metadata for private torrents<commit_after>/* Copyright (c) 2007, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 "libtorrent/pch.hpp" #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/shared_ptr.hpp> #include <boost/lexical_cast.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif #include <vector> #include <utility> #include <numeric> #include <cstdio> #include "libtorrent/peer_connection.hpp" #include "libtorrent/bt_peer_connection.hpp" #include "libtorrent/hasher.hpp" #include "libtorrent/bencode.hpp" #include "libtorrent/torrent.hpp" #include "libtorrent/extensions.hpp" #include "libtorrent/extensions/ut_metadata.hpp" #include "libtorrent/alert_types.hpp" #ifdef TORRENT_STATS #include "libtorrent/aux_/session_impl.hpp" #endif namespace libtorrent { namespace { int div_round_up(int numerator, int denominator) { return (numerator + denominator - 1) / denominator; } void nop(char*) {} struct ut_metadata_plugin : torrent_plugin { ut_metadata_plugin(torrent& t) : m_torrent(t) , m_metadata_progress(0) , m_metadata_size(0) { } virtual void on_files_checked() { // if the torrent is a seed, copy the metadata from // the torrent before it is deallocated if (m_torrent.is_seed()) metadata(); } virtual boost::shared_ptr<peer_plugin> new_connection( peer_connection* pc); buffer::const_interval metadata() const { TORRENT_ASSERT(m_torrent.valid_metadata()); if (!m_metadata) { m_metadata = m_torrent.torrent_file().metadata(); m_metadata_size = m_torrent.torrent_file().metadata_size(); TORRENT_ASSERT(hasher(m_metadata.get(), m_metadata_size).final() == m_torrent.torrent_file().info_hash()); } return buffer::const_interval(m_metadata.get(), m_metadata.get() + m_metadata_size); } bool received_metadata(char const* buf, int size, int piece, int total_size) { if (m_torrent.valid_metadata()) return false; if (!m_metadata) { // verify the total_size if (total_size <= 0 || total_size > 500 * 1024) return false; m_metadata.reset(new char[total_size]); m_requested_metadata.resize(div_round_up(total_size, 16 * 1024), 0); m_metadata_size = total_size; } if (piece < 0 || piece >= int(m_requested_metadata.size())) return false; TORRENT_ASSERT(piece * 16 * 1024 + size <= m_metadata_size); std::memcpy(&m_metadata[piece * 16 * 1024], buf, size); // mark this piece has 'have' m_requested_metadata[piece] = (std::numeric_limits<int>::max)(); bool have_all = std::count(m_requested_metadata.begin() , m_requested_metadata.end(), (std::numeric_limits<int>::max)()) == int(m_requested_metadata.size()); if (!have_all) return false; if (!m_torrent.set_metadata(&m_metadata[0], m_metadata_size)) { if (!m_torrent.valid_metadata()) std::fill(m_requested_metadata.begin(), m_requested_metadata.end(), 0); return false; } // clear the storage for the bitfield std::vector<int>().swap(m_requested_metadata); return true; } // returns a piece of the metadata that // we should request. int metadata_request(); // this is called from the peer_connection for // each piece of metadata it receives void metadata_progress(int total_size, int received) { m_metadata_progress += received; m_metadata_size = total_size; } void on_piece_pass(int) { // if we became a seed, copy the metadata from // the torrent before it is deallocated if (m_torrent.is_seed()) metadata(); } void metadata_size(int size) { if (m_metadata_size > 0 || size <= 0 || size > 500 * 1024) return; m_metadata_size = size; m_metadata.reset(new char[size]); m_requested_metadata.resize(div_round_up(size, 16 * 1024), 0); } private: torrent& m_torrent; // this buffer is filled with the info-section of // the metadata file while downloading it from // peers, and while sending it. // it is mutable because it's generated lazily mutable boost::shared_array<char> m_metadata; int m_metadata_progress; mutable int m_metadata_size; // this vector keeps track of how many times each meatdata // block has been requested // std::numeric_limits<int>::max() means we have the piece std::vector<int> m_requested_metadata; }; struct ut_metadata_peer_plugin : peer_plugin { ut_metadata_peer_plugin(torrent& t, bt_peer_connection& pc , ut_metadata_plugin& tp) : m_message_index(0) , m_no_metadata(min_time()) , m_torrent(t) , m_pc(pc) , m_tp(tp) {} // can add entries to the extension handshake virtual void add_handshake(entry& h) { entry& messages = h["m"]; messages["ut_metadata"] = 15; if (m_torrent.valid_metadata()) h["metadata_size"] = m_tp.metadata().left(); } // called when the extension handshake from the other end is received virtual bool on_extension_handshake(lazy_entry const& h) { m_message_index = 0; if (h.type() != lazy_entry::dict_t) return false; lazy_entry const* messages = h.dict_find("m"); if (!messages || messages->type() != lazy_entry::dict_t) return false; int index = messages->dict_find_int_value("ut_metadata", -1); if (index == -1) return false; m_message_index = index; int metadata_size = h.dict_find_int_value("metadata_size"); if (metadata_size > 0) m_tp.metadata_size(metadata_size); return true; } void write_metadata_packet(int type, int piece) { TORRENT_ASSERT(type >= 0 && type <= 2); TORRENT_ASSERT(piece >= 0); TORRENT_ASSERT(!m_pc.associated_torrent().expired()); #ifdef TORRENT_VERBOSE_LOGGING (*m_pc.m_logger) << time_now_string() << " ==> UT_METADATA [ " "type: " << type << " | piece: " << piece << " ]\n"; #endif // abort if the peer doesn't support the metadata extension if (m_message_index == 0) return; entry e; e["msg_type"] = type; e["piece"] = piece; char const* metadata = 0; int metadata_piece_size = 0; if (type == 1) { TORRENT_ASSERT(m_pc.associated_torrent().lock()->valid_metadata()); e["total_size"] = m_tp.metadata().left(); int offset = piece * 16 * 1024; metadata = m_tp.metadata().begin + offset; metadata_piece_size = (std::min)( int(m_tp.metadata().left() - offset), 16 * 1024); TORRENT_ASSERT(metadata_piece_size > 0); TORRENT_ASSERT(offset >= 0); TORRENT_ASSERT(offset + metadata_piece_size <= int(m_tp.metadata().left())); } char msg[200]; char* header = msg; char* p = &msg[6]; int len = bencode(p, e); int total_size = 2 + len + metadata_piece_size; namespace io = detail; io::write_uint32(total_size, header); io::write_uint8(bt_peer_connection::msg_extended, header); io::write_uint8(m_message_index, header); m_pc.send_buffer(msg, len + 6); if (metadata_piece_size) m_pc.append_send_buffer( (char*)metadata, metadata_piece_size, &nop); } virtual bool on_extended(int length , int extended_msg, buffer::const_interval body) { if (extended_msg != 15) return false; if (m_message_index == 0) return false; if (length > 17 * 1024) { m_pc.disconnect("ut_metadata message larger than 17 kB", 2); return true; } if (!m_pc.packet_finished()) return true; int len; entry msg = bdecode(body.begin, body.end, len); if (msg.type() == entry::undefined_t) { m_pc.disconnect("invalid bencoding in ut_metadata message", 2); return true; } int type = msg["msg_type"].integer(); int piece = msg["piece"].integer(); #ifdef TORRENT_VERBOSE_LOGGING (*m_pc.m_logger) << time_now_string() << " <== UT_METADATA [ " "type: " << type << " | piece: " << piece << " ]\n"; #endif switch (type) { case 0: // request { if (!m_torrent.valid_metadata()) { write_metadata_packet(2, piece); return true; } // TODO: put the request on the queue in some cases write_metadata_packet(1, piece); } break; case 1: // data { std::vector<int>::iterator i = std::find(m_sent_requests.begin() , m_sent_requests.end(), piece); // unwanted piece? if (i == m_sent_requests.end()) return true; m_sent_requests.erase(i); entry const* total_size = msg.find_key("total_size"); m_tp.received_metadata(body.begin + len, body.left() - len, piece , (total_size && total_size->type() == entry::int_t) ? total_size->integer() : 0); } break; case 2: // have no data { m_no_metadata = time_now(); std::vector<int>::iterator i = std::find(m_sent_requests.begin() , m_sent_requests.end(), piece); // unwanted piece? if (i == m_sent_requests.end()) return true; m_sent_requests.erase(i); } break; default: { std::stringstream msg; msg << "unknown ut_metadata extension message: " << type; m_pc.disconnect(msg.str().c_str(), 2); } } return true; } virtual void tick() { // if we don't have any metadata, and this peer // supports the request metadata extension // and we aren't currently waiting for a request // reply. Then, send a request for some metadata. if (!m_torrent.valid_metadata() && m_message_index != 0 && m_sent_requests.size() < 2 && has_metadata()) { int piece = m_tp.metadata_request(); m_sent_requests.push_back(piece); write_metadata_packet(0, piece); } } bool has_metadata() const { return time_now() - m_no_metadata > minutes(1); } private: // this is the message index the remote peer uses // for metadata extension messages. int m_message_index; // this is set to the current time each time we get a // "I don't have metadata" message. ptime m_no_metadata; // request queues std::vector<int> m_sent_requests; std::vector<int> m_incoming_requests; torrent& m_torrent; bt_peer_connection& m_pc; ut_metadata_plugin& m_tp; }; boost::shared_ptr<peer_plugin> ut_metadata_plugin::new_connection( peer_connection* pc) { bt_peer_connection* c = dynamic_cast<bt_peer_connection*>(pc); if (!c) return boost::shared_ptr<peer_plugin>(); return boost::shared_ptr<peer_plugin>(new ut_metadata_peer_plugin(m_torrent, *c, *this)); } int ut_metadata_plugin::metadata_request() { std::vector<int>::iterator i = std::min_element( m_requested_metadata.begin(), m_requested_metadata.end()); if (m_requested_metadata.empty()) { // if we don't know how many pieces there are // just ask for piece 0 m_requested_metadata.resize(1, 1); return 0; } int piece = i - m_requested_metadata.begin(); m_requested_metadata[piece] = piece; return piece; } } } namespace libtorrent { boost::shared_ptr<torrent_plugin> create_ut_metadata_plugin(torrent* t, void*) { // don't add this extension if the torrent is private if (t->valid_metadata() && t->torrent_file().priv()) return boost::shared_ptr<torrent_plugin>(); return boost::shared_ptr<torrent_plugin>(new ut_metadata_plugin(*t)); } } <|endoftext|>
<commit_before>#include "images.h" #include "util/filesystem.h" #include <Magick++.h> #include <iostream> using Magick::Color; using std::cerr; using std::endl; #if FEATURE_IMAGE_LOADING Color to_magick(const spectrum& c) { scalar s = ((1 << QuantumDepth) - 1); spectrum clamped = c.clamp(0, 1); Color color; color.redQuantum(clamped[0] * s); color.greenQuantum(clamped[1] * s); color.blueQuantum(clamped[2] * s); return color; } spectrum from_magick(const Color& c) { scalar m = 1.0 / ((1 << QuantumDepth) - 1); return spectrum{c.redQuantum() * m, c.greenQuantum() * m, c.blueQuantum() * m}; } bool load_image(const std::string& filename, Image& image) { if (!filesystem::exists(filename)) { cerr << "Could not find image file: " << filename << endl; return false; } Magick::Image img(filename); image.width = img.columns(); image.height = img.rows(); if (image.width == 0 || image.height == 0) { cerr << "Could not load image: " << filename << endl; return false; } image.data.resize(image.width * image.height); int pi = 0; for (int ry = 0; ry < image.height; ++ry) { for (int x = 0; x < image.width; ++x, ++pi) { image.data[pi] = from_magick(img.pixelColor(x, ry)); } } return true; } #else bool load_image(const std::string& filename, Image& image) { cerr << "Compile with FEATURE_IMAGE_LOADING=1 to turn on image file loading.\n"; return false; } #endif <commit_msg>Moves magick references inside compilation guard<commit_after>#include "images.h" #include "util/filesystem.h" #include <iostream> using std::cerr; using std::endl; #if FEATURE_IMAGE_LOADING #include <Magick++.h> using Magick::Color; Color to_magick(const spectrum& c) { scalar s = ((1 << QuantumDepth) - 1); spectrum clamped = c.clamp(0, 1); Color color; color.redQuantum(clamped[0] * s); color.greenQuantum(clamped[1] * s); color.blueQuantum(clamped[2] * s); return color; } spectrum from_magick(const Color& c) { scalar m = 1.0 / ((1 << QuantumDepth) - 1); return spectrum{c.redQuantum() * m, c.greenQuantum() * m, c.blueQuantum() * m}; } bool load_image(const std::string& filename, Image& image) { if (!filesystem::exists(filename)) { cerr << "Could not find image file: " << filename << endl; return false; } Magick::Image img(filename); image.width = img.columns(); image.height = img.rows(); if (image.width == 0 || image.height == 0) { cerr << "Could not load image: " << filename << endl; return false; } image.data.resize(image.width * image.height); int pi = 0; for (int ry = 0; ry < image.height; ++ry) { for (int x = 0; x < image.width; ++x, ++pi) { image.data[pi] = from_magick(img.pixelColor(x, ry)); } } return true; } #else bool load_image(const std::string& filename, Image& image) { cerr << "Compile with FEATURE_IMAGE_LOADING=1 to turn on image file loading.\n"; return false; } #endif <|endoftext|>
<commit_before>// Copyright (c) 2015 Sze Howe Koh // This code is licensed under the MIT license (see LICENSE.MIT for details) #include "wikiquerier.h" #include <QNetworkAccessManager> #include <QNetworkCookieJar> #include <QNetworkCookie> #include <QNetworkReply> #include <QJsonDocument> #include <QJsonObject> #include <QUrlQuery> // TODO: Extract error messages from MediaWiki replies (e.g. if querying fails) // TODO: Allow user-configurable URL static const QString apiUrl = "https://wiki.qt.io/api.php"; /**********************************************************************\ * CONSTRUCTOR/DESTRUCTOR \**********************************************************************/ WikiQuerier::WikiQuerier(QObject* parent) : QObject(parent), nam(nullptr), isBusy(false), _lastOpWasCompleted(false) { } /**********************************************************************\ * PUBLIC \**********************************************************************/ void WikiQuerier::queryPageList() { if (isBusy) { qDebug() << "ERROR: WikiQuerier is busy."; return; } isBusy = true; _lastOpWasCompleted = false; namespaceListIdx = 0; _tmp_allIds.clear(); fetchPageListChunk(); } void WikiQuerier::queryLastModified(const QVector<int>& pageIds) { if (isBusy) { qDebug() << "ERROR: WikiQuerier is busy."; return; } if (pageIds.isEmpty()) return; qDebug() << "(4) Fetching page timestamps..."; isBusy = true; _lastOpWasCompleted = false; idChunkIdx = 0; _tmp_allIds_chunked.clear(); _tmp_allTimestamps.clear(); for (int i = 0; i < pageIds.count(); i += 50) _tmp_allIds_chunked << pageIds.mid(i, 50); fetchTimestampChunk(_tmp_allIds_chunked[0]); } void WikiQuerier::downloadPages(const QVector<int>& pageIds) { qDebug() << "Downloading" << pageIds.count() << "pages..."; if (isBusy) { qDebug() << "ERROR: WikiQuerier is busy."; return; } if (pageIds.isEmpty()) return; isBusy = true; _lastOpWasCompleted = false; textChunkIdx = 0; _tmp_texts_chunked.clear(); _tmp_texts = QJsonArray(); for (int i = 0; i < pageIds.count(); i += 50) _tmp_texts_chunked << pageIds.mid(i, 50); fetchTextChunk(_tmp_texts_chunked[0]); } /**********************************************************************\ * PRIVATE \**********************************************************************/ static QVector<int> namespaceIdList{ 0, // Base 4, // Project (Qt Wiki) 12, // Help 14 // Category }; void WikiQuerier::fetchPageListChunk(int namespaceId, const QString& apcontinue) { QUrlQuery query; query.addQueryItem("format", "json"); query.addQueryItem("action", "query"); query.addQueryItem("list", "allpages"); query.addQueryItem("apnamespace", QString::number(namespaceId)); query.addQueryItem("aplimit", "500"); // Non-bots that query using pageid/title are limited to 500 pages at a time if (!apcontinue.isEmpty()) query.addQueryItem("apfrom", apcontinue.toUtf8().toPercentEncoding()); QUrl fullUrl(apiUrl); fullUrl.setQuery(query); QNetworkRequest netRequest(fullUrl); netRequest.setRawHeader("User-Agent", "Wique 0.5"); // netRequest.setHeader( QNetworkRequest::CookieHeader, qVariantFromValue( nam->cookieJar()->cookiesForUrl(fullUrl) ) ); QNetworkReply* reply = nam->get(netRequest); connect(reply, &QNetworkReply::finished, [=] { auto outerObj = QJsonDocument::fromJson(reply->readAll()).object(); reply->deleteLater(); qDebug() << "\t1 page list chunk obtained"; if (!outerObj.contains("query")) { qDebug() << "ERROR: WikiQuerier: Query failed. Raw reply is" << outerObj; finalizePageLists(); return; } bool continuingHere = outerObj.contains("query-continue"); bool continuingNext = true; if (continuingHere) { // Kick off the next set of downloads QString next = outerObj["query-continue"].toObject()["allpages"].toObject()["apcontinue"].toString(); fetchPageListChunk(namespaceIdList[namespaceListIdx], next); } else { // Kick off the next set of downloads continuingNext = ++namespaceListIdx < namespaceIdList.count(); if (continuingNext) fetchPageListChunk(namespaceIdList[namespaceListIdx]); } // Actual processing auto innerArray = outerObj["query"].toObject()["allpages"].toArray(); for (const QJsonValue& pageObj : innerArray) _tmp_allIds << pageObj.toObject()["pageid"].toInt(); if (!continuingHere && !continuingNext) { // ASSUMPTION: The downloaded list is only ever for detailed updates qDebug() << "...Found" << _tmp_allIds.count() << "pages in total.\n"; _lastOpWasCompleted = true; finalizePageLists(); } }); // TODO: Handle network errors } void WikiQuerier::fetchTimestampChunk(QVector<int> ids) { QStringList idStrings; for (int id : ids) idStrings << QString::number(id); QUrlQuery query; query.addQueryItem("format", "json"); query.addQueryItem("action", "query"); query.addQueryItem("prop", "info"); query.addQueryItem("pageids", idStrings.join('|')); // NOTE: Limited to 50 (or 500 for bots) QUrl fullUrl(apiUrl); fullUrl.setQuery(query); QNetworkRequest netRequest(fullUrl); netRequest.setRawHeader("User-Agent", "Wique 0.5"); // netRequest.setHeader( QNetworkRequest::CookieHeader, qVariantFromValue( nam->cookieJar()->cookiesForUrl(url_query) ) ); auto reply = nam->get(netRequest); connect(reply, &QNetworkReply::finished, [=] { auto outerObj = QJsonDocument::fromJson(reply->readAll()).object(); reply->deleteLater(); qDebug() << "\t1 timestamp chunk obtained"; if (!outerObj.contains("query")) { qDebug() << "Query failed. Raw reply:" << outerObj; finalizeTimestamps(); return; } // Kick off the next set of downloads bool continuing = ++idChunkIdx < _tmp_allIds_chunked.count(); if (continuing) fetchTimestampChunk(_tmp_allIds_chunked[idChunkIdx]); // Actual processing auto innerObj = outerObj["query"].toObject()["pages"].toObject(); for (const QString& key : innerObj.keys()) { auto timeStr = innerObj[key].toObject()["touched"].toString(); _tmp_allTimestamps[key.toInt()] = timeStr; } if (!continuing) { // ASSUMPTION: The downloaded list is only ever for detailed updates qDebug() << "...Found" << _tmp_allTimestamps.count() << "timestamps in total.\n"; _lastOpWasCompleted = true; finalizeTimestamps(); } }); // TODO: Handle network errors } void WikiQuerier::fetchTextChunk(QVector<int> pageIds) { if (pageIds.isEmpty()) return; // TODO: Notify that fetching is over QStringList idStrings; for (int id : pageIds) idStrings << QString::number(id); QUrlQuery query; query.addQueryItem("format", "json"); query.addQueryItem("action", "query"); query.addQueryItem("prop", "info|revisions"); query.addQueryItem("rvprop", "content"); query.addQueryItem("pageids", idStrings.join('|')); // TODO: Consider whether to process in chunks, or one page at a time // DECISION: Implement chunk, do the one-page function in terms of the chunked function // TODO: Decide how to emit signals QUrl url(apiUrl); url.setQuery(query); QNetworkRequest netRequest(url); netRequest.setRawHeader("User-Agent", "Wique 0.5"); // netRequest.setHeader( QNetworkRequest::CookieHeader, qVariantFromValue( nam->cookieJar()->cookiesForUrl(url) ) ); auto reply = nam->get(netRequest); connect(reply, &QNetworkReply::finished, [=] { auto outerObj = QJsonDocument::fromJson(reply->readAll()).object(); reply->deleteLater(); qDebug() << "\t1 text chunk obtained"; if (!outerObj.contains("query")) { qDebug() << "Query failed. Raw reply:" << outerObj; finalizeWikiText(); return; } // Kick off the next set of downloads before processing local data bool continuing = ++textChunkIdx < _tmp_texts_chunked.count(); if (continuing) fetchTextChunk(_tmp_texts_chunked[textChunkIdx]); // Actual processing auto midObj = outerObj["query"].toObject()["pages"].toObject(); for (const QString& key : midObj.keys()) { auto pageObj = midObj[key].toObject(); auto innerArray = pageObj["revisions"].toArray(); if (innerArray.isEmpty()) { qDebug() << "ERROR: Missing revisions"; continue; } QJsonObject dataObj; dataObj["pageid"] = pageObj["pageid"].toInt(); dataObj["title"] = pageObj["title"].toString(); dataObj["touched"] = pageObj["touched"].toString(); dataObj["content"] = innerArray[0].toObject()["*"].toString(); _tmp_texts << dataObj; } if (!continuing) { _lastOpWasCompleted = true; finalizeWikiText(); } }); // TODO: Handle network errors } void WikiQuerier::finalizePageLists() { isBusy = false; emit pageListFetched(_tmp_allIds); } void WikiQuerier::finalizeTimestamps() { isBusy = false; emit timestampsFetched(_tmp_allTimestamps); } void WikiQuerier::finalizeWikiText() { isBusy = false; emit wikiTextFetched(_tmp_texts); } <commit_msg>Complete the query chain even if there's nothing to download<commit_after>// Copyright (c) 2015 Sze Howe Koh // This code is licensed under the MIT license (see LICENSE.MIT for details) #include "wikiquerier.h" #include <QNetworkAccessManager> #include <QNetworkCookieJar> #include <QNetworkCookie> #include <QNetworkReply> #include <QJsonDocument> #include <QJsonObject> #include <QUrlQuery> // TODO: Extract error messages from MediaWiki replies (e.g. if querying fails) // TODO: Allow user-configurable URL static const QString apiUrl = "https://wiki.qt.io/api.php"; /**********************************************************************\ * CONSTRUCTOR/DESTRUCTOR \**********************************************************************/ WikiQuerier::WikiQuerier(QObject* parent) : QObject(parent), nam(nullptr), isBusy(false), _lastOpWasCompleted(false) { } /**********************************************************************\ * PUBLIC \**********************************************************************/ void WikiQuerier::queryPageList() { if (isBusy) { qDebug() << "ERROR: WikiQuerier is busy."; return; } isBusy = true; _lastOpWasCompleted = false; namespaceListIdx = 0; _tmp_allIds.clear(); fetchPageListChunk(); } void WikiQuerier::queryLastModified(const QVector<int>& pageIds) { if (isBusy) { qDebug() << "ERROR: WikiQuerier is busy."; return; } isBusy = true; _lastOpWasCompleted = false; idChunkIdx = 0; _tmp_allIds_chunked.clear(); _tmp_allTimestamps.clear(); if (pageIds.isEmpty()) { finalizeTimestamps(); return; } qDebug() << "(4) Fetching page timestamps..."; for (int i = 0; i < pageIds.count(); i += 50) _tmp_allIds_chunked << pageIds.mid(i, 50); fetchTimestampChunk(_tmp_allIds_chunked[0]); } void WikiQuerier::downloadPages(const QVector<int>& pageIds) { qDebug() << "Downloading" << pageIds.count() << "pages..."; if (isBusy) { qDebug() << "ERROR: WikiQuerier is busy."; return; } isBusy = true; _lastOpWasCompleted = false; textChunkIdx = 0; _tmp_texts_chunked.clear(); _tmp_texts = QJsonArray(); if (pageIds.isEmpty()) { finalizeWikiText(); return; } for (int i = 0; i < pageIds.count(); i += 50) _tmp_texts_chunked << pageIds.mid(i, 50); fetchTextChunk(_tmp_texts_chunked[0]); } /**********************************************************************\ * PRIVATE \**********************************************************************/ static QVector<int> namespaceIdList{ 0, // Base 4, // Project (Qt Wiki) 12, // Help 14 // Category }; void WikiQuerier::fetchPageListChunk(int namespaceId, const QString& apcontinue) { QUrlQuery query; query.addQueryItem("format", "json"); query.addQueryItem("action", "query"); query.addQueryItem("list", "allpages"); query.addQueryItem("apnamespace", QString::number(namespaceId)); query.addQueryItem("aplimit", "500"); // Non-bots that query using pageid/title are limited to 500 pages at a time if (!apcontinue.isEmpty()) query.addQueryItem("apfrom", apcontinue.toUtf8().toPercentEncoding()); QUrl fullUrl(apiUrl); fullUrl.setQuery(query); QNetworkRequest netRequest(fullUrl); netRequest.setRawHeader("User-Agent", "Wique 0.5"); // netRequest.setHeader( QNetworkRequest::CookieHeader, qVariantFromValue( nam->cookieJar()->cookiesForUrl(fullUrl) ) ); QNetworkReply* reply = nam->get(netRequest); connect(reply, &QNetworkReply::finished, [=] { auto outerObj = QJsonDocument::fromJson(reply->readAll()).object(); reply->deleteLater(); qDebug() << "\t1 page list chunk obtained"; if (!outerObj.contains("query")) { qDebug() << "ERROR: WikiQuerier: Query failed. Raw reply is" << outerObj; finalizePageLists(); return; } bool continuingHere = outerObj.contains("query-continue"); bool continuingNext = true; if (continuingHere) { // Kick off the next set of downloads QString next = outerObj["query-continue"].toObject()["allpages"].toObject()["apcontinue"].toString(); fetchPageListChunk(namespaceIdList[namespaceListIdx], next); } else { // Kick off the next set of downloads continuingNext = ++namespaceListIdx < namespaceIdList.count(); if (continuingNext) fetchPageListChunk(namespaceIdList[namespaceListIdx]); } // Actual processing auto innerArray = outerObj["query"].toObject()["allpages"].toArray(); for (const QJsonValue& pageObj : innerArray) _tmp_allIds << pageObj.toObject()["pageid"].toInt(); if (!continuingHere && !continuingNext) { // ASSUMPTION: The downloaded list is only ever for detailed updates qDebug() << "...Found" << _tmp_allIds.count() << "pages in total.\n"; _lastOpWasCompleted = true; finalizePageLists(); } }); // TODO: Handle network errors } void WikiQuerier::fetchTimestampChunk(QVector<int> ids) { QStringList idStrings; for (int id : ids) idStrings << QString::number(id); QUrlQuery query; query.addQueryItem("format", "json"); query.addQueryItem("action", "query"); query.addQueryItem("prop", "info"); query.addQueryItem("pageids", idStrings.join('|')); // NOTE: Limited to 50 (or 500 for bots) QUrl fullUrl(apiUrl); fullUrl.setQuery(query); QNetworkRequest netRequest(fullUrl); netRequest.setRawHeader("User-Agent", "Wique 0.5"); // netRequest.setHeader( QNetworkRequest::CookieHeader, qVariantFromValue( nam->cookieJar()->cookiesForUrl(url_query) ) ); auto reply = nam->get(netRequest); connect(reply, &QNetworkReply::finished, [=] { auto outerObj = QJsonDocument::fromJson(reply->readAll()).object(); reply->deleteLater(); qDebug() << "\t1 timestamp chunk obtained"; if (!outerObj.contains("query")) { qDebug() << "Query failed. Raw reply:" << outerObj; finalizeTimestamps(); return; } // Kick off the next set of downloads bool continuing = ++idChunkIdx < _tmp_allIds_chunked.count(); if (continuing) fetchTimestampChunk(_tmp_allIds_chunked[idChunkIdx]); // Actual processing auto innerObj = outerObj["query"].toObject()["pages"].toObject(); for (const QString& key : innerObj.keys()) { auto timeStr = innerObj[key].toObject()["touched"].toString(); _tmp_allTimestamps[key.toInt()] = timeStr; } if (!continuing) { // ASSUMPTION: The downloaded list is only ever for detailed updates qDebug() << "...Found" << _tmp_allTimestamps.count() << "timestamps in total.\n"; _lastOpWasCompleted = true; finalizeTimestamps(); } }); // TODO: Handle network errors } void WikiQuerier::fetchTextChunk(QVector<int> pageIds) { if (pageIds.isEmpty()) return; // TODO: Notify that fetching is over QStringList idStrings; for (int id : pageIds) idStrings << QString::number(id); QUrlQuery query; query.addQueryItem("format", "json"); query.addQueryItem("action", "query"); query.addQueryItem("prop", "info|revisions"); query.addQueryItem("rvprop", "content"); query.addQueryItem("pageids", idStrings.join('|')); // TODO: Consider whether to process in chunks, or one page at a time // DECISION: Implement chunk, do the one-page function in terms of the chunked function // TODO: Decide how to emit signals QUrl url(apiUrl); url.setQuery(query); QNetworkRequest netRequest(url); netRequest.setRawHeader("User-Agent", "Wique 0.5"); // netRequest.setHeader( QNetworkRequest::CookieHeader, qVariantFromValue( nam->cookieJar()->cookiesForUrl(url) ) ); auto reply = nam->get(netRequest); connect(reply, &QNetworkReply::finished, [=] { auto outerObj = QJsonDocument::fromJson(reply->readAll()).object(); reply->deleteLater(); qDebug() << "\t1 text chunk obtained"; if (!outerObj.contains("query")) { qDebug() << "Query failed. Raw reply:" << outerObj; finalizeWikiText(); return; } // Kick off the next set of downloads before processing local data bool continuing = ++textChunkIdx < _tmp_texts_chunked.count(); if (continuing) fetchTextChunk(_tmp_texts_chunked[textChunkIdx]); // Actual processing auto midObj = outerObj["query"].toObject()["pages"].toObject(); for (const QString& key : midObj.keys()) { auto pageObj = midObj[key].toObject(); auto innerArray = pageObj["revisions"].toArray(); if (innerArray.isEmpty()) { qDebug() << "ERROR: Missing revisions"; continue; } QJsonObject dataObj; dataObj["pageid"] = pageObj["pageid"].toInt(); dataObj["title"] = pageObj["title"].toString(); dataObj["touched"] = pageObj["touched"].toString(); dataObj["content"] = innerArray[0].toObject()["*"].toString(); _tmp_texts << dataObj; } if (!continuing) { _lastOpWasCompleted = true; finalizeWikiText(); } }); // TODO: Handle network errors } void WikiQuerier::finalizePageLists() { isBusy = false; emit pageListFetched(_tmp_allIds); } void WikiQuerier::finalizeTimestamps() { isBusy = false; emit timestampsFetched(_tmp_allTimestamps); } void WikiQuerier::finalizeWikiText() { isBusy = false; emit wikiTextFetched(_tmp_texts); } <|endoftext|>
<commit_before>/* Copyright (C) 2011-2013 Yubico AB. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 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 HOLDER 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 "yubikeyutil.h" #ifdef Q_WS_WIN #include "crandom.h" #endif YubiKeyUtil::~YubiKeyUtil() { } int YubiKeyUtil::hexModhexDecode(unsigned char *result, size_t *resultLen, const char *str, size_t strLen, size_t minSize, size_t maxSize, bool modhex) { if ((strLen % 2 != 0) || (strLen < minSize) || (strLen > maxSize)) { return -1; } *resultLen = strLen / 2; if (modhex) { if (yubikey_modhex_p(str)) { yubikey_modhex_decode((char *)result, str, strLen); return 1; } } else { if (yubikey_hex_p(str)) { yubikey_hex_decode((char *)result, str, strLen); return 1; } } return 0; } int YubiKeyUtil::hexModhexEncode(char *result, size_t *resultLen, const unsigned char *str, size_t strLen, bool modhex) { *resultLen = strLen * 2; if (modhex) { yubikey_modhex_encode((char *)result, (char *)str, strLen); return 1; } else { yubikey_hex_encode((char *)result, (char *)str, strLen); return 1; } return 0; } QString YubiKeyUtil::qstrHexEncode(const unsigned char *str, size_t strLen) { char result[strLen * 2 + 1]; size_t resultLen = 0; memset(&result, 0, sizeof(result)); int rc = hexModhexEncode(result, &resultLen, str, strLen, false); if(rc > 0) { qDebug("hex encoded string: -%s- (%u)", result, sizeof(result)); return QString::fromLocal8Bit(result); } return QString(""); } void YubiKeyUtil::qstrHexDecode(unsigned char *result, size_t *resultLen, const QString &str) { if(str.size() % 2 != 0) { return; } char hex[MAX_SIZE]; YubiKeyUtil::qstrToRaw(hex, sizeof(hex), str); size_t hexLen = strlen(hex); //Hex decode hexModhexDecode(result, resultLen, hex, hexLen, 0, MAX_SIZE, false); } QString YubiKeyUtil::qstrModhexEncode(const unsigned char *str, size_t strLen) { char result[strLen * 2 + 1]; size_t resultLen = 0; memset(&result, 0, sizeof(result)); int rc = hexModhexEncode(result, &resultLen, str, strLen, true); if(rc > 0) { qDebug("modhex encoded string: -%s- (%u)", result, sizeof(result)); return QString::fromLocal8Bit(result); } return QString(""); } void YubiKeyUtil::qstrModhexDecode(unsigned char *result, size_t *resultLen, const QString &str) { if(str.size() % 2 != 0) { return; } char modhex[MAX_SIZE]; YubiKeyUtil::qstrToRaw(modhex, sizeof(modhex), str); size_t modhexLen = strlen(modhex); //Hex decode hexModhexDecode(result, resultLen, modhex, modhexLen, 0, MAX_SIZE, true); } void YubiKeyUtil::qstrDecDecode(unsigned char *result, size_t *resultLen, const QString &str) { if(str.size() % 2 != 0) { return; } *resultLen = str.size() / 2; unsigned char val = 0; for(size_t i = 0; i < *resultLen; i++) { val = str.mid(i * 2, 2).toInt(); result[i] = ((val / 10) << 4) | (val % 10); } } void YubiKeyUtil::qstrToRaw(char *result, size_t resultLen, const QString &str) { QByteArray strByteArr = str.toLocal8Bit(); size_t strLen = strByteArr.size() + 1; strLen = (resultLen < strLen)? resultLen : strLen; memset(result, 0, strLen); strncpy(result, (char *) strByteArr.data(), strLen); } void YubiKeyUtil::qstrClean(QString *str, size_t maxSize, bool reverse) { *str = str->toLower(); QRegExp rx("[^0-9a-f]"); *str = str->replace(rx, QString("")); if(maxSize > 0) { if(reverse) { *str = str->rightJustified(maxSize, '0', true); } else { *str = str->leftJustified(maxSize, '0', true); } } } void YubiKeyUtil::qstrModhexClean(QString *str, size_t maxSize, bool reverse) { *str = str->toLower(); QRegExp rx("[^b-lnrt-v]"); *str = str->replace(rx, QString("")); if(maxSize > 0) { if(reverse) { *str = str->rightJustified(maxSize, 'c', true); } else { *str = str->leftJustified(maxSize, 'c', true); } } } int YubiKeyUtil::generateRandom(unsigned char *result, size_t resultLen) { size_t bufSize = resultLen; unsigned char buf[bufSize]; memset(&buf, 0, sizeof(buf)); size_t bufLen = 0; #ifdef Q_WS_WIN CRandom random; random.getRand(buf, bufSize); bufLen = sizeof(buf); #else const char *random_places[] = { "/dev/srandom", "/dev/urandom", "/dev/random", 0 }; const char **random_place; for (random_place = random_places; *random_place; random_place++) { FILE *random_file = fopen(*random_place, "r"); if (random_file) { size_t read_bytes = 0; while (read_bytes < bufSize) { size_t n = fread(&buf[read_bytes], 1, bufSize - read_bytes, random_file); read_bytes += n; } fclose(random_file); bufLen = sizeof(buf); break; /* from for loop */ } } #endif if(bufLen > 0) { memcpy(result, buf, bufLen); return 1; } return 0; } QString YubiKeyUtil::generateRandomHex(size_t resultLen) { QString result(""); if (resultLen % 2 != 0) { return result; } size_t bufSize = resultLen / 2; unsigned char buf[bufSize]; memset(&buf, 0, sizeof(buf)); if(generateRandom(buf, bufSize) > 0) { result = qstrHexEncode(buf, bufSize); } return result; } QString YubiKeyUtil::generateRandomModhex(size_t resultLen) { QString result(""); if (resultLen % 2 != 0) { return result; } size_t bufSize = resultLen / 2; unsigned char buf[bufSize]; memset(&buf, 0, sizeof(buf)); if(generateRandom(buf, bufSize) > 0) { result = qstrModhexEncode(buf, bufSize); } return result; } QString YubiKeyUtil::getNextHex(size_t resultLen, const QString &str, int scheme) { QString result(""); qDebug() << "str = " << str << " len = " << str.length(); switch(scheme) { case GEN_SCHEME_FIXED: result = str; break; case GEN_SCHEME_INCR: { //Hex clean QString hexStr(str); qstrClean(&hexStr, resultLen); //Hex decode unsigned char hexDecoded[MAX_SIZE]; size_t hexDecodedLen = 0; memset(&hexDecoded, 0, sizeof(hexDecoded)); qstrHexDecode(hexDecoded, &hexDecodedLen, hexStr); if(hexDecodedLen <= 0) { break; } qDebug() << "hexDecoded = " << QString((char*)hexDecoded) << " len = " << hexDecodedLen; //Increment for (int i = hexDecodedLen; i--; ) { if (++hexDecoded[i]) { break; } } //Hex encode result = qstrHexEncode(hexDecoded, hexDecodedLen); qDebug() << "hexEncoded = " << result << " len = " << result.size(); } break; case GEN_SCHEME_RAND: result = generateRandomHex(resultLen); break; } return result; } QString YubiKeyUtil::getNextModhex(size_t resultLen, const QString &str, int scheme) { QString result(""); qDebug() << "str = " << str << " len = " << str.length(); switch(scheme) { case GEN_SCHEME_FIXED: result = str; break; case GEN_SCHEME_INCR: { //Modhex clean QString modhexStr(str); qstrModhexClean(&modhexStr, resultLen); //Modhex decode unsigned char modhexDecoded[MAX_SIZE]; size_t modhexDecodedLen = 0; memset(&modhexDecoded, 0, sizeof(modhexDecoded)); qstrModhexDecode(modhexDecoded, &modhexDecodedLen, modhexStr); if(modhexDecodedLen <= 0) { break; } qDebug() << "modhexDecoded = " << QString((char*)modhexDecoded) << " len = " << modhexDecodedLen; //Increment for (int i = modhexDecodedLen; i--; ) { if (++modhexDecoded[i]) { break; } } //Modhex encode result = qstrModhexEncode(modhexDecoded, modhexDecodedLen); qDebug() << "modhexEncoded = " << result << " len = " << result.size(); } break; case GEN_SCHEME_RAND: result = generateRandomModhex(resultLen); break; } return result; } void YubiKeyUtil::hexdump(void *buffer, int size) { unsigned char *p = (unsigned char *)buffer; int i; for (i = 0; i < size; i++) { fprintf(stderr, "\\x%02x", *p); p++; } fprintf(stderr, "\n"); fflush(stderr); } <commit_msg>fix warnings<commit_after>/* Copyright (C) 2011-2013 Yubico AB. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 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 HOLDER 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 "yubikeyutil.h" #ifdef Q_WS_WIN #include "crandom.h" #endif YubiKeyUtil::~YubiKeyUtil() { } int YubiKeyUtil::hexModhexDecode(unsigned char *result, size_t *resultLen, const char *str, size_t strLen, size_t minSize, size_t maxSize, bool modhex) { if ((strLen % 2 != 0) || (strLen < minSize) || (strLen > maxSize)) { return -1; } *resultLen = strLen / 2; if (modhex) { if (yubikey_modhex_p(str)) { yubikey_modhex_decode((char *)result, str, strLen); return 1; } } else { if (yubikey_hex_p(str)) { yubikey_hex_decode((char *)result, str, strLen); return 1; } } return 0; } int YubiKeyUtil::hexModhexEncode(char *result, size_t *resultLen, const unsigned char *str, size_t strLen, bool modhex) { *resultLen = strLen * 2; if (modhex) { yubikey_modhex_encode((char *)result, (char *)str, strLen); return 1; } else { yubikey_hex_encode((char *)result, (char *)str, strLen); return 1; } return 0; } QString YubiKeyUtil::qstrHexEncode(const unsigned char *str, size_t strLen) { char result[strLen * 2 + 1]; size_t resultLen = 0; memset(&result, 0, sizeof(result)); int rc = hexModhexEncode(result, &resultLen, str, strLen, false); if(rc > 0) { qDebug("hex encoded string: -%s- (%lu)", result, sizeof(result)); return QString::fromLocal8Bit(result); } return QString(""); } void YubiKeyUtil::qstrHexDecode(unsigned char *result, size_t *resultLen, const QString &str) { if(str.size() % 2 != 0) { return; } char hex[MAX_SIZE]; YubiKeyUtil::qstrToRaw(hex, sizeof(hex), str); size_t hexLen = strlen(hex); //Hex decode hexModhexDecode(result, resultLen, hex, hexLen, 0, MAX_SIZE, false); } QString YubiKeyUtil::qstrModhexEncode(const unsigned char *str, size_t strLen) { char result[strLen * 2 + 1]; size_t resultLen = 0; memset(&result, 0, sizeof(result)); int rc = hexModhexEncode(result, &resultLen, str, strLen, true); if(rc > 0) { qDebug("modhex encoded string: -%s- (%lu)", result, sizeof(result)); return QString::fromLocal8Bit(result); } return QString(""); } void YubiKeyUtil::qstrModhexDecode(unsigned char *result, size_t *resultLen, const QString &str) { if(str.size() % 2 != 0) { return; } char modhex[MAX_SIZE]; YubiKeyUtil::qstrToRaw(modhex, sizeof(modhex), str); size_t modhexLen = strlen(modhex); //Hex decode hexModhexDecode(result, resultLen, modhex, modhexLen, 0, MAX_SIZE, true); } void YubiKeyUtil::qstrDecDecode(unsigned char *result, size_t *resultLen, const QString &str) { if(str.size() % 2 != 0) { return; } *resultLen = str.size() / 2; unsigned char val = 0; for(size_t i = 0; i < *resultLen; i++) { val = str.mid(i * 2, 2).toInt(); result[i] = ((val / 10) << 4) | (val % 10); } } void YubiKeyUtil::qstrToRaw(char *result, size_t resultLen, const QString &str) { QByteArray strByteArr = str.toLocal8Bit(); size_t strLen = strByteArr.size() + 1; strLen = (resultLen < strLen)? resultLen : strLen; memset(result, 0, strLen); strncpy(result, (char *) strByteArr.data(), strLen); } void YubiKeyUtil::qstrClean(QString *str, size_t maxSize, bool reverse) { *str = str->toLower(); QRegExp rx("[^0-9a-f]"); *str = str->replace(rx, QString("")); if(maxSize > 0) { if(reverse) { *str = str->rightJustified(maxSize, '0', true); } else { *str = str->leftJustified(maxSize, '0', true); } } } void YubiKeyUtil::qstrModhexClean(QString *str, size_t maxSize, bool reverse) { *str = str->toLower(); QRegExp rx("[^b-lnrt-v]"); *str = str->replace(rx, QString("")); if(maxSize > 0) { if(reverse) { *str = str->rightJustified(maxSize, 'c', true); } else { *str = str->leftJustified(maxSize, 'c', true); } } } int YubiKeyUtil::generateRandom(unsigned char *result, size_t resultLen) { size_t bufSize = resultLen; unsigned char buf[bufSize]; memset(&buf, 0, sizeof(buf)); size_t bufLen = 0; #ifdef Q_WS_WIN CRandom random; random.getRand(buf, bufSize); bufLen = sizeof(buf); #else const char *random_places[] = { "/dev/srandom", "/dev/urandom", "/dev/random", 0 }; const char **random_place; for (random_place = random_places; *random_place; random_place++) { FILE *random_file = fopen(*random_place, "r"); if (random_file) { size_t read_bytes = 0; while (read_bytes < bufSize) { size_t n = fread(&buf[read_bytes], 1, bufSize - read_bytes, random_file); read_bytes += n; } fclose(random_file); bufLen = sizeof(buf); break; /* from for loop */ } } #endif if(bufLen > 0) { memcpy(result, buf, bufLen); return 1; } return 0; } QString YubiKeyUtil::generateRandomHex(size_t resultLen) { QString result(""); if (resultLen % 2 != 0) { return result; } size_t bufSize = resultLen / 2; unsigned char buf[bufSize]; memset(&buf, 0, sizeof(buf)); if(generateRandom(buf, bufSize) > 0) { result = qstrHexEncode(buf, bufSize); } return result; } QString YubiKeyUtil::generateRandomModhex(size_t resultLen) { QString result(""); if (resultLen % 2 != 0) { return result; } size_t bufSize = resultLen / 2; unsigned char buf[bufSize]; memset(&buf, 0, sizeof(buf)); if(generateRandom(buf, bufSize) > 0) { result = qstrModhexEncode(buf, bufSize); } return result; } QString YubiKeyUtil::getNextHex(size_t resultLen, const QString &str, int scheme) { QString result(""); qDebug() << "str = " << str << " len = " << str.length(); switch(scheme) { case GEN_SCHEME_FIXED: result = str; break; case GEN_SCHEME_INCR: { //Hex clean QString hexStr(str); qstrClean(&hexStr, resultLen); //Hex decode unsigned char hexDecoded[MAX_SIZE]; size_t hexDecodedLen = 0; memset(&hexDecoded, 0, sizeof(hexDecoded)); qstrHexDecode(hexDecoded, &hexDecodedLen, hexStr); if(hexDecodedLen <= 0) { break; } qDebug() << "hexDecoded = " << QString((char*)hexDecoded) << " len = " << hexDecodedLen; //Increment for (int i = hexDecodedLen; i--; ) { if (++hexDecoded[i]) { break; } } //Hex encode result = qstrHexEncode(hexDecoded, hexDecodedLen); qDebug() << "hexEncoded = " << result << " len = " << result.size(); } break; case GEN_SCHEME_RAND: result = generateRandomHex(resultLen); break; } return result; } QString YubiKeyUtil::getNextModhex(size_t resultLen, const QString &str, int scheme) { QString result(""); qDebug() << "str = " << str << " len = " << str.length(); switch(scheme) { case GEN_SCHEME_FIXED: result = str; break; case GEN_SCHEME_INCR: { //Modhex clean QString modhexStr(str); qstrModhexClean(&modhexStr, resultLen); //Modhex decode unsigned char modhexDecoded[MAX_SIZE]; size_t modhexDecodedLen = 0; memset(&modhexDecoded, 0, sizeof(modhexDecoded)); qstrModhexDecode(modhexDecoded, &modhexDecodedLen, modhexStr); if(modhexDecodedLen <= 0) { break; } qDebug() << "modhexDecoded = " << QString((char*)modhexDecoded) << " len = " << modhexDecodedLen; //Increment for (int i = modhexDecodedLen; i--; ) { if (++modhexDecoded[i]) { break; } } //Modhex encode result = qstrModhexEncode(modhexDecoded, modhexDecodedLen); qDebug() << "modhexEncoded = " << result << " len = " << result.size(); } break; case GEN_SCHEME_RAND: result = generateRandomModhex(resultLen); break; } return result; } void YubiKeyUtil::hexdump(void *buffer, int size) { unsigned char *p = (unsigned char *)buffer; int i; for (i = 0; i < size; i++) { fprintf(stderr, "\\x%02x", *p); p++; } fprintf(stderr, "\n"); fflush(stderr); } <|endoftext|>
<commit_before>#include "llvm/Pass.h" #include "llvm/Function.h" #include "llvm/Module.h" #include "llvm/Instructions.h" #include "llvm/Support/CallSite.h" #include "llvm/Constants.h" #include "llvm/LLVMContext.h" #include "llvm/GlobalVariable.h" #include "llvm/Support/IRBuilder.h" #include "llvm/Analysis/LoopInfo.h" #include "llvm/Analysis/InlineCost.h" #include "llvm/DefaultPasses.h" #include "ObjectiveCOpts.h" #include "IMPCacher.h" #include <string> using namespace llvm; using namespace GNUstep; using std::string; // Mangle a method name // // From clang: static std::string SymbolNameForMethod(const std::string &ClassName, const std::string &CategoryName, const std::string &MethodName, bool isClassMethod) { std::string MethodNameColonStripped = MethodName; std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(), ':', '_'); return std::string(isClassMethod ? "_c_" : "_i_") + ClassName + "_" + CategoryName + "_" + MethodNameColonStripped; } namespace { class ClassMethodInliner : public ModulePass { const IntegerType *IntTy; public: static char ID; ClassMethodInliner() : ModulePass(ID) {} virtual bool runOnModule(Module &M) { unsigned MessageSendMDKind = M.getContext().getMDKindID("GNUObjCMessageSend"); InlineCostAnalyzer CA; SmallPtrSet<const Function *, 16> NeverInline; GNUstep::IMPCacher cacher = GNUstep::IMPCacher(M.getContext(), this); IntTy = (sizeof(int) == 4 ) ? Type::getInt32Ty(M.getContext()) : Type::getInt64Ty(M.getContext()) ; bool modified = false; for (Module::iterator F=M.begin(), fend=M.end() ; F != fend ; ++F) { SmallVector<CallSite, 16> messages; if (F->isDeclaration()) { continue; } for (Function::iterator i=F->begin(), end=F->end() ; i != end ; ++i) { for (BasicBlock::iterator b=i->begin(), last=i->end() ; b != last ; ++b) { CallSite call(b); if (call.getInstruction() && !call.getCalledFunction()) { MDNode *messageType = call->getMetadata(MessageSendMDKind); if (0 == messageType) { continue; } messages.push_back(call); } } } for (SmallVectorImpl<CallSite>::iterator i=messages.begin(), e=messages.end() ; e!=i ; i++) { MDNode *messageType = (*i)->getMetadata(MessageSendMDKind); StringRef sel = cast<MDString>(messageType->getOperand(0))->getString(); StringRef cls = cast<MDString>(messageType->getOperand(1))->getString(); bool isClassMethod = cast<ConstantInt>(messageType->getOperand(2))->isOne(); StringRef functionName = SymbolNameForMethod(cls, "", sel, isClassMethod); Function *method = M.getFunction(functionName); if (0 == method || method->isDeclaration()) { continue; } InlineCost IC = CA.getInlineCost((*i), method, NeverInline); // FIXME: 200 is a random number. Pick a better one! if (IC.isAlways() || (IC.isVariable() && IC.getValue() < 200)) { cacher.SpeculativelyInline((*i).getInstruction(), method); i->getInstruction()->setMetadata(MessageSendMDKind, 0); modified = true; } } } return modified; } }; char ClassMethodInliner::ID = 0; RegisterPass<ClassMethodInliner> X("gnu-class-method-inline", "Inline class methods and message sends to super"); } ModulePass *createClassMethodInliner(void) { return new ClassMethodInliner(); } <commit_msg>Fix use-after-free in speculative inlining pass.<commit_after>#include "llvm/Pass.h" #include "llvm/Function.h" #include "llvm/Module.h" #include "llvm/Instructions.h" #include "llvm/Support/CallSite.h" #include "llvm/Constants.h" #include "llvm/LLVMContext.h" #include "llvm/GlobalVariable.h" #include "llvm/Support/IRBuilder.h" #include "llvm/Analysis/LoopInfo.h" #include "llvm/Analysis/InlineCost.h" #include "llvm/DefaultPasses.h" #include "ObjectiveCOpts.h" #include "IMPCacher.h" #include <string> using namespace llvm; using namespace GNUstep; using std::string; // Mangle a method name // // From clang: static std::string SymbolNameForMethod(const std::string &ClassName, const std::string &CategoryName, const std::string &MethodName, bool isClassMethod) { std::string MethodNameColonStripped = MethodName; std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(), ':', '_'); return std::string(isClassMethod ? "_c_" : "_i_") + ClassName + "_" + CategoryName + "_" + MethodNameColonStripped; } namespace { class ClassMethodInliner : public ModulePass { const IntegerType *IntTy; public: static char ID; ClassMethodInliner() : ModulePass(ID) {} virtual bool runOnModule(Module &M) { unsigned MessageSendMDKind = M.getContext().getMDKindID("GNUObjCMessageSend"); InlineCostAnalyzer CA; SmallPtrSet<const Function *, 16> NeverInline; GNUstep::IMPCacher cacher = GNUstep::IMPCacher(M.getContext(), this); IntTy = (sizeof(int) == 4 ) ? Type::getInt32Ty(M.getContext()) : Type::getInt64Ty(M.getContext()) ; bool modified = false; for (Module::iterator F=M.begin(), fend=M.end() ; F != fend ; ++F) { SmallVector<CallSite, 16> messages; if (F->isDeclaration()) { continue; } for (Function::iterator i=F->begin(), end=F->end() ; i != end ; ++i) { for (BasicBlock::iterator b=i->begin(), last=i->end() ; b != last ; ++b) { CallSite call(b); if (call.getInstruction() && !call.getCalledFunction()) { MDNode *messageType = call->getMetadata(MessageSendMDKind); if (0 == messageType) { continue; } messages.push_back(call); } } } for (SmallVectorImpl<CallSite>::iterator i=messages.begin(), e=messages.end() ; e!=i ; i++) { MDNode *messageType = (*i)->getMetadata(MessageSendMDKind); StringRef sel = cast<MDString>(messageType->getOperand(0))->getString(); StringRef cls = cast<MDString>(messageType->getOperand(1))->getString(); bool isClassMethod = cast<ConstantInt>(messageType->getOperand(2))->isOne(); std::string functionName = SymbolNameForMethod(cls, "", sel, isClassMethod); Function *method = M.getFunction(functionName); if (0 == method || method->isDeclaration()) { continue; } InlineCost IC = CA.getInlineCost((*i), method, NeverInline); // FIXME: 200 is a random number. Pick a better one! if (IC.isAlways() || (IC.isVariable() && IC.getValue() < 200)) { cacher.SpeculativelyInline((*i).getInstruction(), method); i->getInstruction()->setMetadata(MessageSendMDKind, 0); modified = true; } } } return modified; } }; char ClassMethodInliner::ID = 0; RegisterPass<ClassMethodInliner> X("gnu-class-method-inline", "Inline class methods and message sends to super"); } ModulePass *createClassMethodInliner(void) { return new ClassMethodInliner(); } <|endoftext|>