示例#1
0
void BitBltGrabber::init()
{
	_hdcDesktop = GetDC(GetDesktopWindow());
	if (_hdcDesktop == NULL)
		throw exception(strstream() << "GetDC failed - error code is " << GetLastError());

	_hdcCapture = CreateCompatibleDC(_hdcDesktop);
	if (_hdcCapture == NULL)
		throw exception(strstream() << "CreateCompatibleDC failed - error code is " << GetLastError());
}
示例#2
0
    WORD AssemblyParser::ParseRegister(const std::string& token)
    {
        auto reg_op = (*InstructionSet)[token.substr(0,1)];
        WORD register_index = 0;

        //TODO: would be nice to use a regex?
        if (reg_op == OP_ACC)
        {
            register_index = 0;
        }
        else if(reg_op == OP_REG)
        {
            std::istringstream strstream( token.substr(1, token.length()) );
            std::string subtoken;
            std::getline(strstream, subtoken, ',');

            register_index = stoi(subtoken);
        }
        else
        {
            register_index = BAD_REGISTER_INDEX;
        }

        return register_index;
    }
示例#3
0
size_t PlainHeader::load(unsigned char *ptr, unsigned char *ptrMax, ProgressListener *listener)
{
    size_t count = 0;

    // Read ControlInformation
    ControlInformation controlInformation;
    count += controlInformation.load(&ptr[count], ptrMax);

	std::string format = controlInformation.getFormat();
	uint32_t headerSize = controlInformation.getUint("length");

	// FIXME: Use format to create custom parser.
	if(format!=HDTVocabulary::HEADER_NTRIPLES) {
		throw "This Header format is not supported";
	}

    string str(&ptr[count], &ptr[count+headerSize]);

    // Convert into a stringstream
    stringstream strstream(str, stringstream::in);
    triples.clear();

    // Parse header
    RDFParserNtriples parser(strstream, NTRIPLES);
    while(parser.hasNext()) {
        TripleString *ts = parser.next();
        triples.push_back(*ts);
    }

    count+=headerSize;

    return count;
}
示例#4
0
void PlainHeader::load(std::istream & input, ControlInformation &controlInformation, ProgressListener *listener)
{
	std::string format = controlInformation.getFormat();
	uint32_t headerSize = controlInformation.getUint("length");

	// FIXME: Use format to create custom parser.
	if(format!=HDTVocabulary::HEADER_NTRIPLES) {
		throw "This Header format is not supported";
	}
	
	// Read all header into a string
	string str(headerSize,'\0');
	input.read(&str[0], headerSize);
	if(input.gcount()!=headerSize) {
	    throw "Error reading header";
	}

	// Convert into a stringstream
	stringstream strstream(str, stringstream::in);
    triples.clear();

	// Parse header
	RDFParserNtriples parser(strstream, NTRIPLES);
	while(parser.hasNext()) {
		TripleString *ts = parser.next();
		triples.push_back(*ts);
    }
}
示例#5
0
文件: FPGroup.cpp 项目: dpantele/crag
FPGroup FPGroup::triangulatePresentation( ) const
{
  int new_gen_num = numOfGenerators;
  char str[10];
  
  // rename old generators to avoid collisions
  vector< string > new_gen_names = initializeGenNames( numOfGenerators );
  vector< Word > new_relators;
  
  int new_gens_num = 0;
  for( vector< Word >::const_iterator r_it=theRelators.begin( ) ; r_it!=theRelators.end( ) ; ++r_it ) {
    
    const Word& rel = *r_it;
    int len = rel.length( );
    if( len>3 ) {

      // initial setup (first 3 letters)
      Word::const_iterator r_it = rel.begin( );
      int g1 = *r_it++;
      int g2 = *r_it++;
      int g3 = *r_it++;
      strstream(str,10) << (++new_gens_num) << ends;
      new_gen_names.push_back( string( "x" ).append( str ) );
      new_relators.push_back( Word( g1 )*Word( g2 )*Word( -new_gens_num ) );
      
      // iterations
      for( int i=0 ; i<len-4 ; ++i, ++r_it ) {
        strstream(str,10) << (++new_gens_num) << ends;
        new_gen_names.push_back( string( "x" ).append( str ) );
        int new_gen = new_gen_names.size( );
        new_relators.push_back( Word( new_gens_num-1 ) * Word(g3) * Generator( -new_gens_num ) );
        g3 = *r_it;
      }
      
      // the last relator
      new_relators.push_back( Word( g3 ) * Generator( *r_it ) * Word( -new_gens_num ) );
    } else
      new_relators.push_back( rel );
  }

  return FPGroup( FiniteAlphabet( new_gen_names) , new_relators );
}
示例#6
0
	VideoSender* VideoSender::create(VideoSenderType type)
	{
		switch (type)
		{
			case VT_NULL: return new NullVideoSender();
			case VT_QT: return new QtVideoSender();
			case VT_DEFAULT: return new VideoSenderFFmpeg();
		}
	
		throw exception(strstream() << "Could not create video sender of type " << type);
	}
示例#7
0
void BitBltGrabber::grab(const Rect& rect, Buffer* destination)
{
	resizeBitmapIfNecessary(rect.w, rect.h);

	SelectObject(_hdcCapture, _hBitmap);

	BOOL result = BitBlt(_hdcCapture, 0, 0, rect.w, rect.h, _hdcDesktop, rect.x, rect.y, SRCCOPY | CAPTUREBLT);
	if (result == FALSE)
		throw exception(strstream() << "Failed to BitBlt with error code " << GetLastError());

	// draw mouse cursor into buffer
	if (_grabMouseCursor)
	{
		grabCursor(rect, _hdcCapture);
	}
	
	int lines = GetDIBits(_hdcDesktop, _hBitmap, 0, _captureSize.height, _bmpBuffer, &_bmpInfo, DIB_RGB_COLORS);
	if (lines == 0)
		throw exception(strstream() << "Failed to GetDIBits with return " << lines << " and with error code " << GetLastError());

	copyBitmapToBuffer(_bmpBuffer, rect.w * 4, lines, destination);
}
示例#8
0
文件: FPGroup.cpp 项目: dpantele/crag
vector< string > FPGroup::initializeGenNames( int num )
{
  vector< string > result( num );
  
  char str[10];
  for( int t=0 ; t<num ; ++t ) {
    strstream(str,10) << t << ends;
    // itoa( t , str , 10 );
    result[t] = "x";
    result[t].append( str );
  }
  return result;
}
osgDB::ReaderWriter::ReadResult ReaderWriterGZ::readFile(ObjectType objectType, const std::string &fullFileName, const osgDB::ReaderWriter::Options *options) const
{
    std::string ext = osgDB::getLowerCaseFileExtension(fullFileName);

    if (!acceptsExtension(ext))
        return ReadResult::FILE_NOT_HANDLED;

    if (osgDB::containsServerAddress(fullFileName))
        return ReadResult::FILE_NOT_HANDLED;

    osgDB::ReaderWriter *rw = 0;

    if (osgDB::equalCaseInsensitive(ext, "osgz"))
    {
        rw = osgDB::Registry::instance()->getReaderWriterForExtension("osg");
        OSG_INFO << "osgz ReaderWriter " << rw << std::endl;
    }
    else if (osgDB::equalCaseInsensitive(ext, "ivez"))
    {
        rw = osgDB::Registry::instance()->getReaderWriterForExtension("ive");
        OSG_INFO << "ivez ReaderWriter " << rw << std::endl;
    }
    else
    {
        std::string baseFileName = osgDB::getNameLessExtension(fullFileName);
        std::string baseExt      = osgDB::getLowerCaseFileExtension(baseFileName);
        rw = osgDB::Registry::instance()->getReaderWriterForExtension(baseExt);
        OSG_INFO << baseExt << " ReaderWriter " << rw << std::endl;
    }


    std::string fileName = osgDB::findDataFile(fullFileName, options);
    if (fileName.empty())
        return ReadResult::FILE_NOT_FOUND;

    // code for setting up the database path so that internally referenced file are searched for on relative paths.
    osg::ref_ptr<Options> local_opt = options ? static_cast<Options*>(options->clone(osg::CopyOp::SHALLOW_COPY)) : new Options;
    local_opt->getDatabasePathList().push_front(osgDB::getFilePath(fileName));

    osgDB::ifstream fin(fileName.c_str(), std::ios::binary | std::ios::in);
    if (!fin)
        return ReadResult::ERROR_IN_READING_FILE;


    std::string dest;
    read(fin, dest);

    std::stringstream strstream(dest);

    return readFile(objectType, rw, strstream, local_opt.get());
}
示例#10
0
void TagLargerSelector::matchNode(NodeId nodeID, const shared_ptr<TileIdentifier>& ti, RenderAttributes* attributes) const {
	Node* node = geodata->getNode(nodeID);
	auto entry = node->getTags().find(tag);

	if (entry != node->getTags().end()) {
		std::stringstream strstream(entry->second.str());
		int tagvalue;
		strstream >> tagvalue;

		// !strstream is true if the string value could be converted to int
		if (!strstream.bad() && tagvalue > value) {
			next->matchNode(nodeID, ti, attributes);
		}
	}
示例#11
0
void IDnsResource::encodeName(const std::string& decodedName, char* result, size_t& resultLen)
{
	resultLen = 0;
	std::stringstream strstream(decodedName);
    std::string word;
    while (getline(strstream, word, '.'))
    {
    	result[0] = word.length();
    	result++;
    	memcpy(result, word.c_str(), word.length());
    	result += word.length();
    	resultLen += word.length() + 1;
    }

    // add '\0' at the end
    result[0] = 0;
    resultLen++;
}
示例#12
0
文件: uos.cpp 项目: JoeGlancy/uos
int consoleSession(Console &console, int userIndex)
{
	int r = 0;
	std::string input;
	
	while (1)
	{
		input = console.read();
		std::transform(input.begin(), input.end(), input.begin(), ::toupper);
		// split the string of input
		std::stringstream strstream(input);	// strstream is used for splitting 
											// the input
		std::istream_iterator<std::string> start(strstream);
		std::istream_iterator<std::string> end;
		std::vector<std::string> input_split(start, end);
		strstream.clear();

		if (input_split.size() < 1)
			continue;

		// console.write((std::string) "You entered " + input + "\n");
		if (input_split[0] == "EXIT")
		{
			r = 0;
			break;
		}
		else if (input_split[0] == "LOGOUT")
		{
			r = 1;
			break;
		}
		// you can put more commands here, eg:
		//   else if (input_split[0] = "COMMAND") {
		//       console.write((char*)"COMMAND was run\n");
		//   }
		else
		{
			console.write(input_split[0]);
			console.write(": command not found\n");
		}
	}

	return r;
}
示例#13
0
std::pair<std::string, bool> CommandManager::ProcessCommand(const std::string &command) {
    std::vector<std::string> tok_com;
    std::stringstream strstream(command);
    std::string token = "";
    while (getline(strstream, token, ' ')) {
        tok_com.push_back(token);
    }
    if(tok_com.empty()) {
        return std::pair<std::string, bool>("", false);
    }
    auto result = std::pair<std::string, bool>(tok_com[0], true);
    auto func = commands.find(tok_com[0]);
    if(func != commands.end()) {
        status = func->second(tok_com);
    } else {
        result.second = false;
    }
    return result;
}
 bool wordPattern(string pattern, string str) {
     istringstream strstream(str);
     int i=0;
     map<char,string> a1;
     map<string,char> a2;
     while(i<pattern.size() && strstream>>str)
     {
         if(a1.find(pattern[i])!=a1.end() && a2.find(str)!=a2.end())
         {
             if(a1[pattern[i]]!=str || a2[str]!=pattern[i])
             return false;
         }
         else if(a1.find(pattern[i])==a1.end() && a2.find(str)==a2.end())
         {
             a1[pattern[i]]=str;
             a2[str]=pattern[i];
         }
         else
         return false;
         i++;
     }
     if(i<pattern.size() || strstream>>str) return false;
     return true;
 }
示例#15
0
    //TODO: need to rework
    //Parse whole line first
    //Get number of arguments
    //Get base op code
    //Get first argument register offset if exists
    //Get second argument register offset if exists
    //Calculate op_code
    //Get first value argument if exists (i.e. RAM address)
    //Get second value argument if exists (i.e. register or value)
    void AssemblyParser::Parse(const ASSEMBLY &assembly, Model::Memory &memory, PROGRAM_ASSEMBLY_MAP &program_map)
    {
        ADDRESS byte_address = memory.GetTopAddress();
        std::map<std::string, ADDRESS> tag_map;
        unsigned int line_number = 0;
        bool found_begin = false;
        bool found_end = false;

        for (auto line : assembly) 
        {
            line_number++;

            if (line == PROGRAM_BEGIN && !found_begin)
            {
                found_begin = true;
                memory.SetValue(byte_address++, Model::OpCode::GetOpCode(OP_BEGIN, 0));
            }
            else if (line == PROGRAM_END && !found_end)
            {
                found_end = true;
                memory.SetValue(byte_address++, Model::OpCode::GetOpCode(OP_END, 0));
            }
            else if (found_begin && !line.empty())
            {
                std::istringstream strstream(line);
                std::string token;
                std::getline(strstream, token, ' ');

                //TODO: tags are any strings (a-z, A-Z, ending with :)
                //Tags must be defined before use

                //TODO: subroutines are blocks beginning with a tag and ending with ROUTINE_RET

                if (token.substr(0,1) == COMMENT_BEGIN)
                {
                    continue;
                }
                else if (token.back() == TAG_END)
                {
                    tag_map[token.substr(0,token.length() - 1)] = byte_address;
                    memory.SetValue(byte_address++, OP_NOP);
                }
                else
                {
                    program_map[line_number] = byte_address;

                    auto base_op_code = ParseInstruction(token);


                    auto num_arguments = Model::OpCode::GetNumArguments(base_op_code);

                    if (num_arguments >= 1)
                    {
                        std::getline(strstream, token, ' ');
                        int register_index = 0;
                        auto op_code = Model::OpCode::GetOpCode(base_op_code, register_index);

                        //TODO: get rid of comma
                        if (base_op_code == OP_JMP)
                        {
                            if (tag_map.find(token) != tag_map.end())
                            {
                                memory.SetValue(byte_address++, op_code);
                                memory.SetValue(byte_address++, tag_map[token]);
                            }
                        }
                        else
                        {
                            register_index = ParseRegister(token);
                            op_code = Model::OpCode::GetOpCode(base_op_code, register_index);
                            memory.SetValue(byte_address++, op_code);
                        }

                        if (num_arguments >= 2)
                        {
                            std::getline(strstream, token, ' ');
                            auto value = ParseRegValue(token);
                            memory.SetValue(byte_address++, value);
                        }

                        //TODO: what if more arguments? i.e. what about inline comments
                    }
                    else
                    {
                        memory.SetValue(byte_address++, base_op_code);
                    }
                }
            }
        }
    }
示例#16
0
bool LoaderIDE::load(const std::string &filename, const PedStatsList &stats) {
    std::ifstream str(filename);

    if (!str.is_open()) return false;

    auto find_stat_id = [&](const std::string &name) {
        auto it =
            std::find_if(stats.begin(), stats.end(),
                         [&](const PedStats &a) { return a.name_ == name; });
        if (it == stats.end()) {
            return -1;
        }
        return it->id_;
    };

    SectionTypes section = NONE;
    while (!str.eof()) {
        std::string line;
        getline(str, line);
        line.erase(std::find_if(line.rbegin(), line.rend(),
                                std::not1(std::ptr_fun<int, int>(std::isspace)))
                       .base(),
                   line.end());

        if (!line.empty() && line[0] == '#') continue;

        if (line == "end") {
            section = NONE;
        } else if (section == NONE) {
            if (line == "objs") {
                section = OBJS;
            } else if (line == "tobj") {
                section = TOBJ;
            } else if (line == "peds") {
                section = PEDS;
            } else if (line == "cars") {
                section = CARS;
            } else if (line == "hier") {
                section = HIER;
            } else if (line == "2dfx") {
                section = TWODFX;
            } else if (line == "path") {
                section = PATH;
            }
        } else {
            // Remove ALL the whitespace!!
            line.erase(remove_if(line.begin(), line.end(), isspace),
                       line.end());

            std::stringstream strstream(line);
            std::string buff;

            switch (section) {
                default:
                    break;
                case OBJS:
                case TOBJ: {  // Supports Type 1, 2 and 3
                    auto objs =
                        std::unique_ptr<SimpleModelInfo>(new SimpleModelInfo);

                    getline(strstream, buff, ',');
                    objs->setModelID(atoi(buff.c_str()));

                    getline(strstream, objs->name, ',');
                    getline(strstream, objs->textureslot, ',');

                    getline(strstream, buff, ',');
                    objs->setNumAtomics(atoi(buff.c_str()));

                    for (int i = 0; i < objs->getNumAtomics(); i++) {
                        getline(strstream, buff, ',');
                        objs->setLodDistance(i, atof(buff.c_str()));
                    }

                    objs->determineFurthest();

                    getline(strstream, buff, ',');
                    objs->flags = atoi(buff.c_str());

                    // Keep reading TOBJ data
                    if (section == LoaderIDE::TOBJ) {
                        getline(strstream, buff, ',');
                        objs->timeOn = atoi(buff.c_str());
                        getline(strstream, buff, ',');
                        objs->timeOff = atoi(buff.c_str());
                    } else {
                        objs->timeOn = 0;
                        objs->timeOff = 24;
                    }

                    objects.emplace(objs->id(), std::move(objs));
                    break;
                }
                case CARS: {
                    auto cars =
                        std::unique_ptr<VehicleModelInfo>(new VehicleModelInfo);

                    getline(strstream, buff, ',');
                    cars->setModelID(std::atoi(buff.c_str()));

                    getline(strstream, cars->name, ',');
                    getline(strstream, cars->textureslot, ',');

                    getline(strstream, buff, ',');
                    cars->vehicletype_ =
                        VehicleModelInfo::findVehicleType(buff);

                    getline(strstream, cars->handling_, ',');
                    getline(strstream, cars->vehiclename_, ',');
                    getline(strstream, buff, ',');
                    cars->vehicleclass_ =
                        VehicleModelInfo::findVehicleClass(buff);

                    getline(strstream, buff, ',');
                    cars->frequency_ = std::atoi(buff.c_str());

                    getline(strstream, buff, ',');
                    cars->level_ = std::atoi(buff.c_str());

                    getline(strstream, buff, ',');
                    cars->componentrules_ = std::atoi(buff.c_str());

                    switch (cars->vehicletype_) {
                        case VehicleModelInfo::CAR:
                            getline(strstream, buff, ',');
                            cars->wheelmodel_ = std::atoi(buff.c_str());
                            getline(strstream, buff, ',');
                            cars->wheelscale_ = std::atof(buff.c_str());
                            break;
                        case VehicleModelInfo::PLANE:
                            /// @todo load LOD
                            getline(strstream, buff, ',');
                            // cars->planeLOD_ = std::atoi(buff.c_str());
                            break;
                        default:
                            break;
                    }

                    objects.emplace(cars->id(), std::move(cars));
                    break;
                }
                case PEDS: {
                    auto peds = std::unique_ptr<PedModelInfo>(new PedModelInfo);

                    getline(strstream, buff, ',');
                    peds->setModelID(std::atoi(buff.c_str()));

                    getline(strstream, peds->name, ',');
                    getline(strstream, peds->textureslot, ',');

                    getline(strstream, buff, ',');
                    peds->pedtype_ = PedModelInfo::findPedType(buff);

                    std::string behaviour;
                    getline(strstream, behaviour, ',');
                    peds->statindex_ = find_stat_id(behaviour);
                    getline(strstream, peds->animgroup_, ',');

                    getline(strstream, buff, ',');
                    peds->carsmask_ = std::atoi(buff.c_str());

                    objects.emplace(peds->id(), std::move(peds));
                    break;
                }
                case PATH: {
                    PathData path;

                    std::string type;
                    getline(strstream, type, ',');
                    if (type == "ped") {
                        path.type = PathData::PATH_PED;
                    } else if (type == "car") {
                        path.type = PathData::PATH_CAR;
                    }

                    std::string id;
                    getline(strstream, id, ',');
                    path.ID = atoi(id.c_str());

                    getline(strstream, path.modelName);

                    std::string linebuff, buff;
                    for (size_t p = 0; p < 12; ++p) {
                        PathNode node;

                        getline(str, linebuff);
                        std::stringstream buffstream(linebuff);

                        getline(buffstream, buff, ',');
                        switch (atoi(buff.c_str())) {
                            case 0:
                                node.type = PathNode::EMPTY;
                                break;
                            case 2:
                                node.type = PathNode::INTERNAL;
                                break;
                            case 1:
                                node.type = PathNode::EXTERNAL;
                                break;
                        }

                        if (node.type == PathNode::EMPTY) {
                            continue;
                        }

                        getline(buffstream, buff, ',');
                        node.next = atoi(buff.c_str());

                        getline(buffstream, buff, ',');  // "Always 0"

                        getline(buffstream, buff, ',');
                        node.position.x = atof(buff.c_str()) * 1 / 16.f;

                        getline(buffstream, buff, ',');
                        node.position.y = atof(buff.c_str()) * 1 / 16.f;

                        getline(buffstream, buff, ',');
                        node.position.z = atof(buff.c_str()) * 1 / 16.f;

                        getline(buffstream, buff, ',');
                        node.size = atof(buff.c_str()) * 1 / 16.f;

                        getline(buffstream, buff, ',');
                        node.other_thing = atoi(buff.c_str());

                        getline(buffstream, buff, ',');
                        node.other_thing2 = atoi(buff.c_str());

                        path.nodes.push_back(node);
                    }

                    auto &object = objects[path.ID];
                    auto simple = dynamic_cast<SimpleModelInfo *>(object.get());
                    simple->paths.push_back(path);

                    break;
                }
                case HIER: {
                    auto hier =
                        std::unique_ptr<ClumpModelInfo>(new ClumpModelInfo);

                    getline(strstream, buff, ',');
                    hier->setModelID(std::atoi(buff.c_str()));

                    getline(strstream, hier->name, ',');
                    getline(strstream, hier->textureslot, ',');

                    objects.emplace(hier->id(), std::move(hier));
                    break;
                }
            }
        }
    }

    return true;
}
示例#17
0
文件: uos.cpp 项目: JoeGlancy/uos
int main(int argc, char *argv[])
{
	int r = 0;
	Console console;
	std::string input;
	bool userIsLoggedIn = false;
	
	console.init();
	
	while (1)
	{
		input = console.read();
		std::transform(input.begin(), input.end(), input.begin(), ::toupper);
		// split the string of input
		std::stringstream strstream(input); // strstream is used for splitting 
											// the input
		std::istream_iterator<std::string> start(strstream);
		std::istream_iterator<std::string> end;
		std::vector<std::string> input_split(start, end);
		strstream.clear();

		if (input_split.size() < 1)
			break;
		
		if (input_split[0] == "LOGON")
		{
			bool founduser = false, foundpass = false;
			std::string username;
			// user wants to log on
			console.delay(750);
			
			if (input_split.size() < 2)
			{
				console.write("\nENTER USERNAME NOW\n\n");
				username = console.read();
				console.delay(750);
			}
			else
			    username = input_split[1];
			
			for (int i = 0; i<arraysize(usernames); i++)
			{
				if (username == usernames[i])
				{
					founduser = true;
					console.write("\nENTER PASSWORD NOW\n\n");
					std::string password = console.read();
					if (password == userpasswords[i])
					{
						userIsLoggedIn = true;
						foundpass = true;
						console.write("\nWELCOME, ");
						console.write(username);
						console.write(".\n\n");
						r = consoleSession(console, i);
					}
					else
						console.write("\nERROR - INCORRECT PASSWORD\n\n");
				}
			}
			
			if (!founduser)
				console.write("\nERROR - USER DOES NOT EXIST\n\n");
			else
			{
				if (userIsLoggedIn)
				{
					if (r == 0)
					    break;
					else
					    userIsLoggedIn = false;
				}
			}
		}
		else if (input_split[0] == "EXIT")
			break;
		else
			console.write("\nERROR - USER MUST BE LOGGED ON\n");

		console.writeNoDelay("\n");
	}

	return 0;
}
示例#18
0
文件: parse.cpp 项目: cran/RcppTOML
// [[Rcpp::export]]
Rcpp::List tomlparseImpl(const std::string input,
                         bool verbose=false,
                         bool fromfile=true,
                         bool includize=false) {

    if (fromfile && access(input.c_str(), R_OK)) {
        Rcpp::stop("Cannot read given file '" + input + "'.");
    }

    std::shared_ptr<cpptoml::table> g;

    if (fromfile) {
        if (includize) {
            includize::toml_preprocessor pp(input.c_str());
            cpptoml::parser included_parser(pp);
            g = included_parser.parse();
        } else {
            g = cpptoml::parse_file(input.c_str());
        }
    } else {
        std::stringstream strstream(input);
        cpptoml::parser p(strstream);
        g = p.parse();
    }
    
    if (verbose) {
        Rcpp::Rcout << "<default print method>\n" 
                    << (*g)
                    << "</default print method>\n" 
                    << std::endl;
    }

    Rcpp::StretchyList sl;
    for (auto & p : (*g)) {

        if (p.second->is_table_array()) {
            if (verbose) Rcpp::Rcout << "TableArray: " << p.first << std::endl;
            //auto ga = std::dynamic_pointer_cast<cpptoml::table_array>(p.second);
            Rcpp::StretchyList l;
            auto arr = g->get_table_array(p.first)->get();
            auto ait = arr.begin();
            while (ait != arr.end()) {
                auto ta = std::dynamic_pointer_cast<cpptoml::table>(*ait);
                l.push_back (getTable(ta, verbose));
                ++ait;
            }
            sl.push_back(Rcpp::Named(p.first) = Rcpp::as<Rcpp::List>(l));

        } else if (p.second->is_table()) {
            auto ga = std::dynamic_pointer_cast<cpptoml::table>(p.second);
            if (verbose) Rcpp::Rcout << "Table: " << p.first << std::endl;
            sl.push_back(Rcpp::Named(p.first) = getTable(ga, verbose));

        } else if (p.second->is_array()) {
            auto ga = std::dynamic_pointer_cast<cpptoml::array>(p.second);
            if (verbose) Rcpp::Rcout << "Array: " << p.first << std::endl;
            sl.push_back(Rcpp::Named(p.first) = getArray(*ga)); 

        } else if (p.second->is_value()) {
            if (verbose) {
                Rcpp::Rcout << "Value: " << p.first << "\n  :";
                printValue(Rcpp::Rcout, p.second);
                Rcpp::Rcout << std::endl;
            }
            sl.push_back(Rcpp::Named(p.first) = getValue(p.second)); 
            
        } else {
            if (verbose) Rcpp::Rcout << "Other: " << p.first << std::endl;
            sl.push_front(p.first); 
        }
    }
    
    return Rcpp::as<Rcpp::List>(sl);
}
示例#19
0
bool LoaderIPL::load(std::istream &str) {
    SectionTypes section = NONE;
    while (!str.eof()) {
        std::string line;
        getline(str, line);
        line.erase(std::find_if(line.rbegin(), line.rend(),
                                [](auto c) { return !std::isspace(c); })
                       .base(),
                   line.end());

        if (!line.empty() && line[0] == '#') {
            // nothing, just a comment
        } else if (line == "end")  // terminating a section
        {
            section = NONE;
        } else if (section == NONE)  // starting a new section
        {
            if (line == "inst") {
                section = INST;
            }
            if (line == "pick") {
                section = PICK;
            }
            if (line == "cull") {
                section = CULL;
            }
            if (line == "zone") {
                section = ZONE;
            }
        } else  // regular entry
        {
            if (section == INST) {
                std::string id;
                std::string model;
                std::string posX, posY, posZ;
                std::string scaleX, scaleY, scaleZ;
                std::string rotX, rotY, rotZ, rotW;

                std::stringstream strstream(line);

                // read all the contents of the line
                getline(strstream, id, ',');
                getline(strstream, model, ',');
                getline(strstream, posX, ',');
                getline(strstream, posY, ',');
                getline(strstream, posZ, ',');
                getline(strstream, scaleX, ',');
                getline(strstream, scaleY, ',');
                getline(strstream, scaleZ, ',');
                getline(strstream, rotX, ',');
                getline(strstream, rotY, ',');
                getline(strstream, rotZ, ',');
                getline(strstream, rotW, ',');

                m_instances.emplace_back(
                    lexical_cast<int>(id),  // ID
                    model.substr(1, model.size() - 1),
                    glm::vec3(lexical_cast<float>(posX),
                              lexical_cast<float>(posY),
                              lexical_cast<float>(posZ)),
                    glm::vec3(lexical_cast<float>(scaleX),
                              lexical_cast<float>(scaleY),
                              lexical_cast<float>(scaleZ)),
                    glm::normalize(glm::quat(
                        -lexical_cast<float>(rotW), lexical_cast<float>(rotX),
                        lexical_cast<float>(rotY), lexical_cast<float>(rotZ))));
            } else if (section == ZONE) {
                ZoneData zone;

                std::stringstream strstream(line);

                std::string value;

                getline(strstream, value, ',');
                zone.name = value;

                getline(strstream, value, ',');
                zone.type = lexical_cast<int>(value);

                getline(strstream, value, ',');
                zone.min.x = lexical_cast<float>(value);
                getline(strstream, value, ',');
                zone.min.y = lexical_cast<float>(value);
                getline(strstream, value, ',');
                zone.min.z = lexical_cast<float>(value);

                getline(strstream, value, ',');
                zone.max.x = lexical_cast<float>(value);
                getline(strstream, value, ',');
                zone.max.y = lexical_cast<float>(value);
                getline(strstream, value, ',');
                zone.max.z = lexical_cast<float>(value);

                getline(strstream, value, ',');
                zone.island = lexical_cast<int>(value);

                for (int i = 0; i < ZONE_GANG_COUNT; i++) {
                    zone.gangCarDensityDay[i] = zone.gangCarDensityNight[i] =
                        zone.gangDensityDay[i] = zone.gangDensityNight[i] = 0;
                }

                zone.pedGroupDay = 0;
                zone.pedGroupNight = 0;

                zones.push_back(std::move(zone));
            }
        }
    }

    return true;
}
示例#20
0
    bool
    STLReader::
    read_stla(std::istream& _in, TriMeshModelPtr t) const
    {

        if (!t)
        {
            return false;
        }

        unsigned int               i;
        Eigen::Vector3f            v;
        Eigen::Vector3f            n;
        std::vector<unsigned int> vhandles;

        CmpVec comp(eps_);
        std::map<Eigen::Vector3f, unsigned int, CmpVec>            vMap(comp);
        std::map<Eigen::Vector3f, unsigned int, CmpVec>::iterator  vMapIt;

        std::string line;

        bool facet_normal(false);

        while (_in && !_in.eof())
        {

            // Get one line
            std::getline(_in, line);

            if (_in.bad())
            {
                VR_ERROR << "  Warning! Could not read stream properly!\n";
                return false;
            }

            // Trim Both leading and trailing spaces
            trimStdString(line);

            // Normal found?
            if (line.find("facet normal") != std::string::npos)
            {
                std::stringstream strstream(line);

                std::string garbage;

                // facet
                strstream >> garbage;

                // normal
                strstream >> garbage;

                strstream >> n[0];
                strstream >> n[1];
                strstream >> n[2];

                facet_normal = true;
            }

            // Detected a triangle
            if ((line.find("outer") != std::string::npos) || (line.find("OUTER") != std::string::npos))
            {

                vhandles.clear();

                for (i = 0; i < 3; ++i)
                {
                    // Get one vertex
                    std::getline(_in, line);
                    trimStdString(line);

                    std::stringstream strstream(line);

                    std::string garbage;
                    strstream >> garbage;

                    strstream >> v[0];
                    strstream >> v[1];
                    strstream >> v[2];

                    v *= scaling;

                    // has vector been referenced before?
                    if ((vMapIt = vMap.find(v)) == vMap.end())
                    {
                        // No : add vertex and remember idx/vector mapping
                        int handle = int (t->vertices.size());
                        t->addVertex(v);//_bi.add_vertex(v);
                        vhandles.push_back(handle);
                        vMap[v] = handle;
                    }
                    else
                        // Yes : get index from map
                    {
                        vhandles.push_back(vMapIt->second);
                    }
                }

                // Add face only if it is not degenerated
                if ((vhandles[0] != vhandles[1]) &&
                    (vhandles[0] != vhandles[2]) &&
                    (vhandles[1] != vhandles[2]))
                {
                    MathTools::TriangleFace f;
                    f.set(vhandles[0], vhandles[1], vhandles[2]);

                    if (facet_normal)
                    {
                        unsigned int noId = t->normals.size();
                        t->addNormal(n);
                        f.setNormal(noId, noId, noId);
                    }

                    int fh = int(t->faces.size());
                    t->addFace(f);
                    //_bi.add_face(vhandles);
                    facet_normal = false;
                }
            }
示例#21
0
Mesh :: Mesh( char const *filename ) {
    ifstream infile;
    try{
        infile.open(filename);
    }catch(exception &e){
        cout<<"can't open the file "<<filename<<endl;
        exit(0);
    }
    string tmp;
    int n;
    //read vertexes
    getline(infile, tmp);
    istringstream strstream(tmp); 
    strstream>>tmp>>n;
    vlist = new vector<Vector>();
    for(int i = 0; i < n; i++){
        getline(infile, tmp);
        strstream.clear();
        strstream.str(tmp);
        Vector vc;
        strstream>>vc.x>>vc.y>>vc.z;
        vlist->push_back(vc);
    }
    //read normals
    getline(infile, tmp);
    strstream.clear();
    strstream.str(tmp);
    strstream>>tmp>>n;
    nlist = new vector<Vector>();
    for(int i = 0; i < n; i++){
        getline(infile, tmp);
        strstream.clear();
        strstream.str(tmp);
        Vector vc;
        strstream>>vc.x>>vc.y>>vc.z;
        nlist->push_back(vc);
    }
    flist = new vector<vector<pair<int,int> > > ;
    
    //read faces
    getline(infile, tmp);
    strstream.clear();
    strstream.str(tmp);
    strstream>>tmp>>n;
    for(int i = 0; i < n; i++){
        getline(infile, tmp);
        int beg = 0, end = 0, j = 0, num = 0;
        while(tmp[j] > '9' || tmp[j] < '0'){
            j++;
        }
        beg = j;
        while(tmp[j] <= '9' && tmp[j] >= '0'){
            j++;
        }
        end = j;
        num = atoi(tmp.substr(beg, end - beg).c_str());
        vector<pair<int,int> > face;
        for(int k = 0; k < num; k++){
            int vindex, nindex;
            while(tmp[j] > '9' || tmp[j] < '0'){
                j++;
            }
            beg = j;
            while(tmp[j] <= '9' && tmp[j] >= '0'){
                j++;
            }
            end = j;
            vindex = atoi(tmp.substr(beg, end - beg).c_str());
            while(tmp[j] > '9' || tmp[j] < '0'){
                j++;
            }
            beg = j;
            while(tmp[j] <= '9' && tmp[j] >= '0'){
                j++;
            }
            end = j;
            nindex = atoi(tmp.substr(beg, end - beg).c_str());
            pair<int,int> mp(vindex,nindex);
            face.push_back(mp);
        }
        flist->push_back(face);
    }
    //read tlist
    getline(infile, tmp);
    strstream.clear();
    strstream.str(tmp);
    strstream>>tmp>>n;
    tlist = new vector<pair<float,float> >();
    for(int i = 0; i < n; i++){
        getline(infile, tmp);
        strstream.clear();
        strstream.str(tmp);
        pair<float,float> mp;
        strstream>>mp.first>>mp.second;
        tlist->push_back(mp);
    }
    
    //read tlist
    getline(infile, tmp);
    strstream.clear();
    strstream.str(tmp);
    strstream>>tmp;
    tmap = new vector<vector<int> >();
    for(int i = 0; i < flist->size(); i++){
        getline(infile, tmp);
        vector<int> texture;
        int beg = 0, end = 0,j = 0,count = 0;
        while(j < tmp.size() && (tmp[j] < '0' || tmp[j] >'9')){
            j++;
        }
        beg = j;
        for(count = 0; count < flist->at(i).size(); count++){
            while(j < tmp.size() && (tmp[j] >= '0' && tmp[j] <='9')){
                j++;
            }
            end = j;
            texture.push_back(atoi(tmp.substr(beg, end - beg).c_str()));
            while(j < tmp.size() && (tmp[j] < '0' || tmp[j] >'9')){
                j++;
            }
            beg = j;
        }
        tmap->push_back(texture);
    }
    
    infile.close();
}
示例#22
0
bool LoaderIDE::load(const std::string &filename)
{
	std::ifstream str(filename);

	if ( ! str.is_open())
		return false;

	SectionTypes section = NONE;
	while( ! str.eof()) {
		std::string line;
		getline(str, line);
		line.erase(std::find_if(line.rbegin(), line.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), line.end());

		if ( ! line.empty() && line[0] == '#')
			continue;

		if (line == "end") {
			section = NONE;
		} else if(section == NONE) {
			if (line == "objs") {
				section = OBJS;
			} else if (line == "tobj") {
				section = TOBJ;
			} else if (line == "peds") {
				section = PEDS;
			} else if (line == "cars") {
				section = CARS;
			} else if (line == "hier") {
				section = HIER;
			} else if (line == "2dfx") {
				section = TWODFX;
			} else if (line == "path") {
				section = PATH;
			}
		} else {
			// Remove ALL the whitespace!!
			line.erase(remove_if(line.begin(), line.end(), isspace), line.end());

			std::stringstream strstream(line);

			switch (section) {
			default: break;
			case OBJS:
			case TOBJ: { // Supports Type 1, 2 and 3
				std::shared_ptr<ObjectData> objs(new ObjectData);

				std::string id, numClumps, flags,
				            modelName, textureName;
				
				// Read the content of the line
				getline(strstream, id, ',');
				getline(strstream, modelName, ',');
				getline(strstream, textureName, ',');
				getline(strstream, numClumps, ',');

				objs->numClumps = atoi(numClumps.c_str());
				for (size_t i = 0; i < objs->numClumps; i++) {
					std::string drawDistance;
					getline(strstream, drawDistance, ',');
					objs->drawDistance[i] = atoi(drawDistance.c_str());
				}

				getline(strstream, flags, ',');
				
				// Keep reading TOBJ data
				if(section == LoaderIDE::TOBJ) {
					std::string buff;
					getline(strstream, buff, ',');
					objs->timeOn = atoi(buff.c_str());
					getline(strstream, buff, ',');
					objs->timeOff = atoi(buff.c_str());
				}
				else {
					objs->timeOff = objs->timeOn = 0;
				}

				// Put stuff in our struct
				objs->ID          = atoi(id.c_str());
				objs->flags       = atoi(flags.c_str());
				objs->modelName   = modelName;
				objs->textureName = textureName;
				objs->LOD         = false;

				if(modelName.find("LOD", 0,3) != modelName.npos
						&& modelName != "LODistancoast01") {
					objs->LOD = true;
				}

				objects.insert({objs->ID, objs});
				break;
			}
			case CARS: {
				std::shared_ptr<VehicleData> cars(new VehicleData);

				std::string id, type, classType, frequency, lvl,
				            comprules, wheelModelID, wheelScale;

				getline(strstream, id, ',');
				getline(strstream, cars->modelName, ',');
				getline(strstream, cars->textureName, ',');
				getline(strstream, type, ',');
				getline(strstream, cars->handlingID, ',');
				getline(strstream, cars->gameName, ',');
				getline(strstream, classType, ',');
				getline(strstream, frequency, ',');
				getline(strstream, lvl, ',');
				getline(strstream, comprules, ',');
				getline(strstream, wheelModelID, ',');
				getline(strstream, wheelScale, ',');

				cars->ID = atoi(id.c_str());
				cars->frequency = atoi(frequency.c_str());
				cars->lvl = atoi(lvl.c_str());
				cars->comprules = atoi(comprules.c_str());

				if (type == "car") {
					cars->type = VehicleData::CAR;
					cars->wheelModelID = atoi(wheelModelID.c_str());
					cars->wheelScale = atof(wheelScale.c_str());
				} else if (type == "boat") {
					cars->type = VehicleData::BOAT;
				} else if (type == "train") {
					cars->type = VehicleData::TRAIN;
					cars->modelLOD = atoi(wheelModelID.c_str());
				} else if (type == "plane") {
					cars->type = VehicleData::PLANE;
				} else if (type == "heli") {
					cars->type = VehicleData::HELI;
				}

				const std::map<VehicleData::VehicleClass, std::string> classTypes{
					{VehicleData::IGNORE,      "ignore"},
					{VehicleData::NORMAL,      "normal"},
					{VehicleData::POORFAMILY,  "poorfamily"},
					{VehicleData::RICHFAMILY,  "richfamily"},
					{VehicleData::EXECUTIVE,   "executive"},
					{VehicleData::WORKER,      "worker"},
					{VehicleData::BIG,         "big"},
					{VehicleData::TAXI,        "taxi"},
					{VehicleData::MOPED,       "moped"},
					{VehicleData::MOTORBIKE,   "motorbike"},
					{VehicleData::LEISUREBOAT, "leisureboat"},
					{VehicleData::WORKERBOAT,  "workerboat"},
					{VehicleData::BICYCLE,     "bicycle"},
					{VehicleData::ONFOOT,      "onfoot"},
				};
				for (auto &a : classTypes) {
					if (classType == a.second) {
						cars->classType = a.first;
						break;
					}
				}

				objects.insert({cars->ID, cars});
				break;
			}
			case PEDS: {
				std::shared_ptr<CharacterData> peds(new CharacterData);

				std::string id, driveMask;

				getline(strstream, id, ',');
				getline(strstream, peds->modelName, ',');
				getline(strstream, peds->textureName, ',');
				getline(strstream, peds->type, ',');
				getline(strstream, peds->behaviour, ',');
				getline(strstream, peds->animGroup, ',');
				getline(strstream, driveMask, ',');

				peds->ID = atoi(id.c_str());
				peds->driveMask = atoi(driveMask.c_str());

				objects.insert({peds->ID, peds});
				break;
			}
			case PATH: {
				PathData path;

				std::string type;
				getline(strstream, type, ',');
				if( type == "ped" ) {
					path.type = PathData::PATH_PED;
				}
				else if( type == "car") {
					path.type = PathData::PATH_CAR;
				}

				std::string id;
				getline(strstream, id, ',');
				path.ID = atoi(id.c_str());

				getline(strstream, path.modelName);

				std::string linebuff, buff;
				for( size_t p = 0; p < 12; ++p ) {
						PathNode node;

						getline(str, linebuff);
						std::stringstream buffstream(linebuff);

						getline(buffstream, buff, ',');
						switch(atoi(buff.c_str())) {
							case 0:
								node.type = PathNode::EMPTY;
								break;
							case 2:
								node.type = PathNode::INTERNAL;
								break;
							case 1:
								node.type = PathNode::EXTERNAL;
								break;
						}

						if( node.type == PathNode::EMPTY ) {
								continue;
						}

						getline(buffstream, buff, ',');
						node.next = atoi(buff.c_str());

						getline(buffstream, buff, ','); // "Always 0"

						getline(buffstream, buff, ',');
						node.position.x = atof(buff.c_str()) * 1/16.f;

						getline(buffstream, buff, ',');
						node.position.y = atof(buff.c_str()) * 1/16.f;

						getline(buffstream, buff, ',');
						node.position.z = atof(buff.c_str()) * 1/16.f;

						getline(buffstream, buff, ',');
						node.size = atof(buff.c_str()) * 1/16.f;

						getline(buffstream, buff, ',');
						node.other_thing = atoi(buff.c_str());

						getline(buffstream, buff, ',');
						node.other_thing2 = atoi(buff.c_str());

						path.nodes.push_back(node);
					}

					auto& object = objects[path.ID];
					auto instance = std::dynamic_pointer_cast<ObjectData>(object);
					instance->paths.push_back(path);

					break;
				}
			case HIER: {
				std::shared_ptr<CutsceneObjectData> cut(new CutsceneObjectData);

				std::string id;

				getline(strstream, id, ',');
				getline(strstream, cut->modelName, ',');
				getline(strstream, cut->textureName, ',');

				cut->ID = atoi(id.c_str());

				objects.insert({cut->ID, cut});
				break;
			}
			}
		}

	}

	return true;
}