Beispiel #1
0
void Fl_Date_Time::encode_time(double& dt,const char *tim) {
   char  bdat[32];
   short timePart[4] = { 0, 0, 0, 0},
         partNumber = 0;
   char  *ptr = NULL;
   bool  afternoon = false;

   upperCase(bdat, tim, sizeof(bdat));

   if (!trimRight(bdat)) {
      dt = 0;
      return;
   }

   if (strcmp(bdat,"TIME") == 0) {
      dt = Time();        // Sets the current date
      return;
   } else {
      char *p = strstr(bdat,"AM");
      if (p) {
         *p = 0;
      } else {
         p = strstr(bdat,"PM");
         if (p) {
            *p = 0;
            afternoon = true;
         }
      }
      trimRight(bdat);
      int len = strlen(bdat);
      for (int i = 0; i <= len && partNumber < 4; i++) {
         char c = bdat[i];
         if (c == timeSeparator || c == ' ' || c == '.' || c == 0) {
            if (ptr) { // end of token
               bdat[i] = 0;
               timePart[partNumber] = (short) atoi(ptr);
               partNumber++;
               ptr = NULL;
            }
         } else {
            if (!isdigit(c)) {
               dt = 0;
               return;
            }
            if (!ptr) ptr = bdat + i;
         }
      }
      if (afternoon && timePart[0] != 12)
         timePart[0] = short(timePart[0] + 12);
      encode_time(dt,timePart[0],timePart[1],timePart[2],timePart[3]);
   }
}
Beispiel #2
0
static std::string readLanguageFromPPS()
{
    static const char* langfile = "/pps/services/confstr/_CS_LOCALE";
    int fd = ::open(langfile, O_RDONLY);
    if (fd < 0) {
        slog2f(0, ID_G11N, SLOG2_ERROR, "GlobalizationNDK::readLanguageFromPPS: unable to open PPS file: %s.", langfile);
        return std::string();
    }

    static const int PPS_BUFFER_READ_SIZE = 2048;
    char buffer[PPS_BUFFER_READ_SIZE];
    ssize_t read = ::read(fd, buffer, PPS_BUFFER_READ_SIZE - 1);
    ::close(fd);

    if (read <= 0) {
        slog2f(0, ID_G11N, SLOG2_ERROR, "GlobalizationNDK::readLanguageFromPPS: unable to read PPS file: %s.", langfile);
        return std::string();
    }

    std::string content(buffer, read);
    size_t pos = content.find_first_of("::");

    if (pos == std::string::npos) {
        slog2f(0, ID_G11N, SLOG2_ERROR, "GlobalizationNDK::readLanguageFromPPS: unable to find signature \"_CS_LOCALE::\" in PPS file: %s.", langfile);
        return std::string();
    }

    std::string lang = content.substr(pos + 2);// 2 is strlen("::");
    return trimRight(lang);
}
Beispiel #3
0
bool Parser::hasMoreCommands() {
	if (f_.eof()) {	// No more file to check.
		return false;
	}

	// We have to look ahead for commands, skipping comments and blank lines.
	std::istream::streampos parsed_pos 	= f_.tellg(); // Saving stream state.
	std::ios::iostate 		status 		= f_.rdstate();
	f_.clear();

	bool res 					= false;
	unsigned int lines_read 	= 0; 	// So that if there's an error it displays where.
	do {
		std::string s;
		std::getline(f_, s);
		lines_read++;
		trimLeft(s);
		trimRight(s);
		if (!s.empty() && !isComment(s)) { 	// Found a command line...
			if (!validCommand(s)) { 	// ...but it's an invalid line!
				std::cerr << "Error at line ";
				std::cerr << current_line_number_ + lines_read;
				std::cerr << ". '" << s << "': Invalid line" << std::endl;
				throw std::runtime_error("Invalid line");
			}
			res = true;
			goto done;
		}
	} while (!f_.eof());

done:	
	f_.seekg(parsed_pos);		// Restoring stream to its original state.
	f_.setstate(status);
	return res;
}
Beispiel #4
0
void test(const char *s)
{
    std::string str;
    if (s) str = s;
    trimRight(str, " ");
    printf("[%s] => [%s]\n", s, str.c_str());
}
Beispiel #5
0
void Eliza::verify_keyword_boundary(std::string keyWord, int pos) {
	bool bFrontWordsAloud = 0;
	bool bBackWordsAloud = 0;

	m_bWrongBoundary = 0;
	
	if(keyWord[0] != '_') {
		bFrontWordsAloud = 1;
	} else {
		trimLeft(keyWord, '_');
	}
	
	char lastChar = keyWord[keyWord.length()-1];
	if(lastChar != '_') {
		bBackWordsAloud = 1;
	} else {
		trimRight(keyWord, '_');
	}

	keyWord.insert(0, " ");
	keyWord.append(" ");
	
	if(!bFrontWordsAloud && pos > 0) {
		m_bWrongBoundary = 1;
	}

	else if(!bBackWordsAloud && (pos + keyWord.length()) != m_sInput.length()) {
		m_bWrongBoundary = 1;
	}

	else if(bBackWordsAloud && (pos + keyWord.length()) == m_sInput.length()) {
		m_bWrongBoundary = 1;
	}
}
Beispiel #6
0
  ustring trim( ustring &str, const ustring trimChars)
  {
    trimRight( str, trimChars );
    trimLeft( str, trimChars );

    return str;
  }
Beispiel #7
0
void trim(char *buffer)
{
    ASSERT(buffer != NULL);
    trimLeft(buffer);
    trimRight(buffer);
    return;
}
Beispiel #8
0
// trim all left and right characters that is specified by
// the string "characters"
void trimLR(std::string &str, std::string characters) {
	int len = characters.length();
	for(int i = 0; i < len; ++i) {
		trimLeft( str, characters[i] );
		trimRight( str, characters[i] );
	}
}
Beispiel #9
0
/**
 * Read from the socket until a '\n' characters is found.
 */
char *readLine(int socket)
{
    char tline[MAX_LINE_LEN];
    char *line;

    int lineLength = 0;
    ssize_t charactersRead = 0;

    while((charactersRead = read(socket, tline + lineLength, 1)) < MAX_LINE_LEN) {
        if (charactersRead == SOCKET_ERROR) {
            perror("Failure reading from socket");
            fprintf(stderr, "Error: Problem reading HTTP headers (%d)\n", errno);
            exit(2);
        }
        lineLength += charactersRead;
        if (tline[lineLength - 1] == '\n') {
            break;
        }
    }
    tline[lineLength] = 0;

    trimRight(tline);
    line = (char *) malloc((strlen(tline) + 1) * sizeof(char));
    strcpy(line, tline);
    return line;
}
Beispiel #10
0
void Eliza::preProcessResponse() {
	if(is_template(m_sResponse)) {
		findSymbol(m_sResponse);
		if(m_sKeyWord == m_sInput) {
			m_sSuffix = m_sInput;
		} else if(!m_bMemoryRecall){
			extract_suffix();
		} else {
			m_bMemoryRecall = 0;
		}
		if(m_sSuffix.length() == 0) {
			while(is_template(m_sResponse) && response_list.size() > 1) {
				response_list.erase(response_list.begin());
				m_sResponse = response_list[0];
			}
			if(is_template(m_sResponse)) {
				response_list = topicChanger;
				select_response();
			}
		}
		if(m_sSuffix.length() > 0 && m_sSymbol != "%") {
			transpose_sentence(m_sSuffix);
			correct_sentence(m_sSuffix);
			trimRight(m_sSuffix, ' ');
			m_sSuffix.insert(0, " ");
		}
		replace(m_sResponse, m_sSymbol, m_sSuffix);
	}
	if(m_sUserName != "USER") {
		replace(m_sResponse, "USER", m_sUserName);
	}
}
Beispiel #11
0
  void IsotopeDistribution::merge(double resolution, double min_prob)
  {
    // Sort by mass and trim the tails of the container
    sortByMass();
    trimLeft(min_prob);
    trimRight(min_prob);
    
    ContainerType raw = distribution_;
    double mass_range = (raw.back().getMZ() - raw.front().getMZ());
    UInt output_size = ceil(mass_range / resolution);
    if (output_size > distribution_.size())
    {
      throw Exception::IllegalArgument(__FILE__,
                                       __LINE__,
                                       OPENMS_PRETTY_FUNCTION,
                                       "New Isotope Distribution "
                                       "has more points than the old one.");
    }

    distribution_.clear();
    ContainerType distribution(output_size, Peak1D(0, 0));
    double delta = mass_range / output_size;

    for (auto& p : raw)
    {
      UInt index = round((p.getMZ() - raw.front().getMZ())/resolution);
      if (index >= distribution.size()) {continue;}
      double mass = raw.front().getMZ() + (index * delta);
      distribution[index].setMZ(mass);
      distribution[index].setIntensity(distribution[index].getIntensity() + p.getIntensity());
    }
    distribution_ = distribution;
    trimIntensities(min_prob);
  }
Beispiel #12
0
// removes punctuation from the input
// and do some more preprocessing
void Eliza::preProcessInput() {
	if(m_sInput.length() > 0) {
		tok.cleanString(m_sInput, " ?!,;");
		trimRight(m_sInput, '.');
		UpperCase(m_sInput);
		m_sInput.insert(0, " ");
		m_sInput.append(" ");
	}
}
Beispiel #13
0
  ustring trimC( ustring str, const ustring trimChars)
  {
    ustring copy=str;

    trimRight(copy, trimChars);
    trimLeft(copy, trimChars );

    return copy;
  }
Beispiel #14
0
string
filenameFromPathname(const string &path)
{
    string strippedPath(trimRight(trimLeft(path, "\t "), "\t "));
    // special-case the root
    if (strippedPath == "/")
    {
        return strippedPath;
    }
    // directories are components too
    strippedPath = trimRight(strippedPath, "/");
    vector<string> pathComponents(split(path, '/'));
    if (pathComponents.size() == 0)
    {
        THROW(ArgExc, "Expected at least one component of path '" << path << "', but saw none");
    }
    return pathComponents[pathComponents.size() -1];
}
Beispiel #15
0
double str2double(const std::wstring &str, double fallback /* = 0.0 */)
{
  wchar_t *end = NULL;
  std::wstring tmp = trimRight(str);
  double result = wcstod(tmp.c_str(), &end);
  if (end == NULL || *end == '\0')
    return result;

  return fallback;
}
Beispiel #16
0
int64_t str2int64(const std::string &str, int64_t fallback /* = 0 */)
{
  char *end = NULL;
  std::string tmp = trimRight(str);
  int64_t result = strtoll(tmp.c_str(), &end, 0);
  if (end == NULL || *end == '\0')
    return result;

  return fallback;
}
void CBot::find_subject()
{
	m_sSubject.erase(); // resets subject variable
	trimRight(m_sInput, " ");
	size_t pos = m_sInput.find(m_sKeyWord);
	if(pos != std::string::npos)
	{
		m_sSubject = m_sInput.substr(pos + m_sKeyWord.length() - 1, m_sInput.length());		
	}
}
Beispiel #18
0
uint64_t str2uint64(const std::wstring &str, uint64_t fallback /* = 0 */)
{
  wchar_t *end = NULL;
  std::wstring tmp = trimRight(str);
  uint64_t result = wcstoull(tmp.c_str(), &end, 0);
  if (end == NULL || *end == '\0')
    return result;

  return fallback;
}
Beispiel #19
0
//Reads the input file line by line
void readInput()
{
	std::string temp;
	std::stringstream sstream;
	while (std::getline(std::cin, temp))
	{
		trimLeft(temp);
		trimRight(temp);
		input.push_back(temp);
	}
}
Beispiel #20
0
string
modulenameFromFilename(const string &filename)
{
    // blank filename is an error
    string strippedFilename(trimRight(trimLeft(filename, "\t "), "\t "));
    if (strippedFilename == "")
    {
        THROW(ArgExc, "Expected non-blank filename");
    }
    vector<string> filenameComponents(split(strippedFilename, '.'));
    return filenameComponents[0];
}
Beispiel #21
0
void Parser::advance() {
/* PRE: hasMoreCommands() == true 
=> next non-comment line contains a valid command. */
	std::string s;
	do {
		std::getline(f_, s);
		current_line_number_++;
		trimLeft(s);
	} while (isComment(s) || s.empty());

	trimRight(s);
	current_line_ = s;
}
Beispiel #22
0
void Parser::advance() {
/* PRE: hasMoreCommands() == true 
=> next non-comment line contains a valid command. */
	std::string s;
	do {
		std::getline(f_, s);
		current_line_number_++;
		trimLeft(s);
	} while (isComment(s) || s.empty());

	trimRight(s);
	// Saving the line in lower case:
	std::transform(s.begin(), s.end(), s.begin(), ::tolower);
	current_line_ = s;
}
Beispiel #23
0
int main () {
	int c=0;
	char s[100];
	for(;;){
		switch(GetMenu("Input String;Trim right;Trim Left;Trim Mid;Print Output",5,1))
		{	
			case 1:c++;inputs(s);while(getchar() != '\n');break;
			case 2:if(c!=0)trimRight(s);else printf("\t%s\n","Input String First !"); break;
			case 3:if(c!=0)trimLeft(s);else printf("\t%s\n","Input String First !");break;
			case 4:if(c!=0)trimMid(s);else printf("\t%s\n","Input String First !");break;
			case 5:if(c!=0)printf("\tOutput String :\"%s\"\n",s);else printf("\t%s\n","Input String First !");break;
			case 0:return 0;
		}
	}
}
Beispiel #24
0
// transpose a complete sentence
void Eliza::transpose_sentence( std::string &str ) {
	std::string thisWord = "";
	std::string tempStr = "";
	vstring stringToken;
	tok.setDelim(" !?,-");
	trimRight(str, '.');
	tok.tokenize(str, stringToken);
	int nTokNum = stringToken.size();
	for(int i = 0; i < nTokNum; ++i) {
		thisWord = stringToken[i];
		transpose(thisWord);
		tempStr += thisWord + " ";
	}
	str = tempStr;
}
bus_shift* readInput(const char* path, int num, std::map<std::string,int> *powerMap)
{
        bus_shift* bss = (bus_shift*)malloc(sizeof(bus_shift) * num);
        char buffer[512];
        FILE* fr = fopen(path, "r");
        int i = 0;
        while(fgets(buffer, 512, fr) != NULL)
        {
                trimRight(buffer);
                setBusShift(&bss[i++], buffer, powerMap);
        }   

                                    
        return bss;
}
Beispiel #26
0
string ofxEliza::ask(string _inputString){
    // gets input from the user
    save_prev_input();
    m_sInput = _inputString;
    saveLog("USER");
    
    // Finds and display a response
    // to the current input of the user.
    // removes punctuation from the input
    // and do some more preprocessing
    if(m_sInput.length() > 0) {
		tok.cleanString(m_sInput, " ?!,;");
		trimRight(m_sInput, '.');
		UpperCase(m_sInput);
		m_sInput.insert(0, " ");
		m_sInput.append(" ");
	}
    
    save_prev_responses();
    save_prev_response();
    
    if(null_input()) {
        handle_null_input();
    } else if(user_repeat()) {
        handle_user_repetition();
    } else if(short_input()) {
        handle_short_input();
    }
    else {
        reset_repeat_count();
        reset_short_input_count();
        find_response();
    }
    
    select_response();
    preProcessResponse();
    handle_repetition();
    
    saveLog("ELIZA");
    
    return m_sResponse;
}
Beispiel #27
0
/**
 * Modify str in place to erase whitespace on the left and right.
 * @param str
 */
static void
trim(string& str)
{
  trimLeft(str);
  trimRight(str);
}
Beispiel #28
0
OBJMesh* objMeshLoad(const char* filename)
{
	int linenum = 0;
	int warning = 0;
	int fatalError = 0;
	
	//open the ascii file
	FILE* file = fopen(filename, "r");
	
	//check it actually opened
	if (!file)
	{
		perror(filename);
		return NULL;
	}
	
	//the mesh we're going to return
	OBJMesh* mesh = (OBJMesh*)malloc(sizeof(OBJMesh));
	memset(mesh, 0, sizeof(OBJMesh));
	
	//we don't know how much data the obj file has, so we start with one and keep realloc-ing double
	ReallocArray vertices, faceSets, vertexHash, positions, normals, texCoords, triangles;
	initArray(&vertexHash, sizeof(VertHash*)); //array of hash record pointers (for freeing)
	initArray(&positions, sizeof(float) * 3);
	initArray(&normals, sizeof(float) * 3);
	initArray(&texCoords, sizeof(float) * 2);
	initArray(&triangles, sizeof(unsigned int) * 3);
	initArray(&faceSets, sizeof(OBJFaceSet));
	vertices.size = 0; //vertices are allocated later (at first face)
	
	//obj indices start at 1. we'll use the zero element for "error", giving with zero data
	positions.size = 1;
	normals.size = 1;
	texCoords.size = 1;
	allocArray(&positions);
	allocArray(&normals);
	allocArray(&texCoords);
	memset(positions.data, 0, positions.blockSize);
	memset(normals.data, 0, normals.blockSize);
	memset(texCoords.data, 0, texCoords.blockSize);
	
	//vertex combinations v/t/n are not always the same index. different vertex
	//combinations are hashed and reused, saving memory
	//see uthash.h (http://uthash.sourceforge.net/)
	VertHash* vertexRecords = NULL;
	
	//materials are referenced by name. this hash maps a name to material index
	MatHash* materialRecords = NULL;
	
	//whether the mesh contains normals or texture coordinates, and hence
	//the vertex data stride, is decided at the first face line ("f ...")
	int reachedFirstFace = 0;
	
	//current shading state
	int smoothShaded = 1;
	
	//start reading, line by line
	char* tmpTok;
	char line[OBJ_MAX_LINE_LEN];
	while (fgets(line, OBJ_MAX_LINE_LEN, file) != NULL)
	{
		//split line by spaces
		strtok_r(line, " ", &tmpTok);
		
		//what data does this line give us, if any?
		if (line[0] == 'v')
		{
			//this line contains vertex data
			if (line[1] == '\0') //\0 as strtok replaced the space
			{
				//position data. allocate more memory if needed
				positions.size++;
				allocArray(&positions);
				
				//read data from string
				((float*)positions.data)[(positions.size-1)*3+0] = readTokFloat(&tmpTok, &warning);
				((float*)positions.data)[(positions.size-1)*3+1] = readTokFloat(&tmpTok, &warning);
				((float*)positions.data)[(positions.size-1)*3+2] = readTokFloat(&tmpTok, &warning);
			}
			else if (line[1] == 'n')
			{
				//normal data. allocate more memory if needed
				normals.size++;
				allocArray(&normals);
				
				//read data from string
				((float*)normals.data)[(normals.size-1)*3+0] = readTokFloat(&tmpTok, &warning);
				((float*)normals.data)[(normals.size-1)*3+1] = readTokFloat(&tmpTok, &warning);
				((float*)normals.data)[(normals.size-1)*3+2] = readTokFloat(&tmpTok, &warning);
			}
			else if (line[1] == 't')
			{
				//texture data. allocate more memory if needed
				texCoords.size++;
				allocArray(&texCoords);
				
				//read data from string
				((float*)texCoords.data)[(texCoords.size-1)*2+0] = readTokFloat(&tmpTok, &warning);
				((float*)texCoords.data)[(texCoords.size-1)*2+1] = readTokFloat(&tmpTok, &warning);
			}
		}
		else if (line[0] == 'f')
		{
			//this line contains face data. this may have many vertices
			//but we just want triangles. so we triangulate.
			//NOTE: ALL vertex data must be given before being referenced by a face
			//NOTE: At least one vt or vn must be specified before the first f, or the rest will be ignored
			if (!reachedFirstFace)
			{
				//must have previously specified vertex positions
				if (positions.size == 1)
				{
					fatalError = 1;
					break;
				}
				
				//calculate vertex stride
				mesh->hasNormals = (normals.size > 1) ? 1 : 0;
				mesh->hasTexCoords = (texCoords.size > 1) ? 1 : 0;
				mesh->normalOffset = 3 * sizeof(float);
				mesh->texcoordOffset = mesh->normalOffset + mesh->hasNormals * 3 * sizeof(float);
				mesh->stride = mesh->texcoordOffset + mesh->hasTexCoords * 2 * sizeof(float);
				initArray(&vertices, mesh->stride);
				reachedFirstFace = 1;
			}
			
			//start by extracting groups of vertex data (pos/tex/norm)
			int i = 0;
			char* vert[OBJ_MAX_POLYGON];
			while ((vert[i] = strtok_r(NULL, " ", &tmpTok)) != NULL && i < OBJ_MAX_POLYGON)
				++i;
			
			//triangulate using the "fan" method
			int triVert = 0; //triVert contains the current face's vertex index. may not equal v as vertices can be ignored. 
			int triangulate[2];
			for (int v = 0; v < i; ++v)
			{
				//split groups by "/" and store in inds[3]
				int t = 0;
				int inds[3];
				char* tok = strtok_r(vert[v], "/", &tmpTok);
				while (tok != NULL && t < 3)
				{
					inds[t++] = atoi(tok);
					tok = strtok_r(NULL, "/", &tmpTok);
				}
				while (t < 3)
					inds[t++] = 0;
				
				//set provided, yet unused indices as invalid. this
				//prevents unnecessary unique vertices being created
				if (!mesh->hasTexCoords)
					inds[1] = -1;
				if (!mesh->hasNormals)
					inds[2] = -1;
					
				//ignore vertex if position indices are out of bounds
				if (inds[0] < 0 || inds[0] >= positions.size)
				{
					warning = 1;
					continue;
				}
				
				//use zero for out of bound normals and texture coordinates
				if ((mesh->hasTexCoords && (inds[1] < 0 || inds[1] >= texCoords.size)) ||
					(mesh->hasNormals && (inds[2] < 0 || inds[2] >= normals.size)))
				{
					warning = 1;
				}
					
				//since vertices will be reused a lot, we need to hash the v/t/n combination
				int uniqueVertIndex;
				
				//check if the vertex already exists in hash
				VertHash h;
				VertHash* found = NULL;
				memset(&h, 0, sizeof(VertHash));
				h.key.v = inds[0];
				h.key.t = inds[1];
				h.key.n = inds[2];
				//printf("looking up %i/%i/%i\n", h.key.v, h.key.t, h.key.n);
				HASH_FIND(hh, vertexRecords, &h.key, sizeof(VertHashKey), found);
				//printf("done looking up\n");
				if (found)
				{
					//found. use that vertex
					//printf("vert %i/%i/%i already exists as %i\n", inds[0], inds[1], inds[2], found->index);
					uniqueVertIndex = found->index;
				}
				else
				{
					//printf("new vert %i/%i/%i\n", inds[0], inds[1], inds[2]);
				
					//not found. create a new vertex
					uniqueVertIndex = vertices.size++;
					allocArray(&vertices);
					
					//copy data for vertex
					memcpy(((float*)vertices.data) + uniqueVertIndex * mesh->stride / sizeof(float), 
						((float*)positions.data) + inds[0] * 3,
						sizeof(float) * 3);
					if (mesh->hasTexCoords)
						memcpy(((float*)vertices.data) + (uniqueVertIndex * mesh->stride + mesh->texcoordOffset) / sizeof(float),
						((float*)texCoords.data) + inds[1] * 2,
						sizeof(float) * 2);
					if (mesh->hasNormals)
						memcpy(((float*)vertices.data) + (uniqueVertIndex * mesh->stride + mesh->normalOffset) / sizeof(float),
						((float*)normals.data) + inds[2] * 3,
						sizeof(float) * 3);
					
					//add vertex to hash table
					vertexHash.size++;
					allocArray(&vertexHash);
					VertHash* newRecord = (VertHash*)malloc(sizeof(VertHash));
					((VertHash**)vertexHash.data)[vertexHash.size-1] = newRecord; //store pointer to quickly free hash records later
					
					h.index = uniqueVertIndex;
					*newRecord = h;
					
					HASH_ADD(hh, vertexRecords, key, sizeof(VertHashKey), newRecord);
				}
				
				if (triVert == 0)
				{
					//store the first vertex
					triangulate[0] = uniqueVertIndex;
				}
				else if (triVert > 1)
				{
					//printf("tri %i->%i->%i\n", triangulate[0], triangulate[1], uniqueVertIndex);
					
					//this is at least the 3rd vertex - we have a new triangle to add
					//always create triangles between the current, previous and first vertex
					triangles.size++;
					allocArray(&triangles);
				
					//read data from string
					((unsigned int*)triangles.data)[(triangles.size-1)*3+0] = triangulate[0];
					((unsigned int*)triangles.data)[(triangles.size-1)*3+1] = triangulate[1];
					((unsigned int*)triangles.data)[(triangles.size-1)*3+2] = uniqueVertIndex;
					
				}
				//store the last vertex
				triangulate[1] = uniqueVertIndex;
				++triVert;
			}
		}
		else if (strcmp(line, "usemtl") == 0)
		{
			//the material state has changed - create a new faceset
			char* mtlname = strtok_r(NULL, " ", &tmpTok);
			trimRight(mtlname);
			
			//find the corresponding material
			MatHash* matRecord;
			HASH_FIND_STR(materialRecords, mtlname, matRecord);
			if (matRecord)
			{
				//printf("material: '%s'\n", mtlname);
				setFaceSet(&faceSets, matRecord->index, smoothShaded, triangles.size * 3);
			}
			else
			{
				warning = 1;
				printf("Undefined material: '%s'\n", mtlname);
				setFaceSet(&faceSets, -1, -1, triangles.size * 3);
			}
		}
		else if (strcmp(line, "mtllib") == 0)
		{
			//load all materials from the given .mtl file
			if (mesh->numMaterials > 0)
			{
				fatalError = 1; //shouldn't specify multiple .mtl files
				break;
			}
			char* mtlname = strtok_r(NULL, " ", &tmpTok);
			trimRight(mtlname);
			if (mtlname)
				parseMaterials(mesh, mtlname);
				
			//add all materials to the hash
			MatHash* matRecord;
			for (int m = 0; m < mesh->numMaterials; ++m)
			{
				HASH_FIND_STR(materialRecords, mesh->materials[m].name, matRecord);
				if (matRecord)
				{
					warning = 1;
					printf("Multiple materials with name '%s'\n", mesh->materials[m].name);
					continue; //can't have multiple definitions of the same material
				}
				matRecord = (MatHash*)malloc(sizeof(MatHash));
				matRecord->name = mesh->materials[m].name;
				matRecord->index = m;
				HASH_ADD_KEYPTR(hh, materialRecords, matRecord->name, strlen(matRecord->name), matRecord);
			}
		}
		else if (line[0] == 's')
		{
			#if !IGNORE_SMOOTHING
			//smooth shading has been changed - create a new faceset
			char* smooth = strtok_r(NULL, " ", &tmpTok);
			trimRight(smooth);
			smoothShaded = atoi(smooth);
			if (strcmp(smooth, "on") == 0) smoothShaded = 1;
			if (strcmp(smooth, "off") == 0) smoothShaded = 0;
			setFaceSet(&faceSets, -1, smoothShaded, triangles.size * 3);
			#endif
		}
		//options o and g are ignored
		
		linenum++; //for warnings/errors
	}
	setFaceSet(&faceSets, -1, -1, triangles.size * 3); //update end of final faceset
	
	//fill the rest of the mesh structure
	exactAllocArray(&vertices);
	exactAllocArray(&triangles);
	exactAllocArray(&faceSets);
	mesh->vertices = (float*)vertices.data;
	mesh->indices = (unsigned int*)triangles.data;
	mesh->facesets = (OBJFaceSet*)faceSets.data;
	mesh->numVertices = vertices.size;
	mesh->numIndices = triangles.size * 3;
	mesh->numFacesets = faceSets.size;
	
	//cleanup
	//NOTE: vertices and indices are used in the returned mesh data and are not freed
	
	MatHash* matRecord;
	MatHash* matTmp;
	HASH_ITER(hh, materialRecords, matRecord, matTmp) {
	  HASH_DEL(materialRecords, matRecord);
	  free(matRecord);
	}
Beispiel #29
0
/**
 * Renders the schedule's contents to a text stream.
 *
 * @param structuredOutput Output will be structured and padded with spaces and
 *                         newlines for alignment and breaks. Used with
 *                         fixed-width character output.
 */
void Schedule::render(QTextStream &os, bool structuredOutput)
{
    OutputState state;
    
    if (_contextRoot.isListEmpty()) return; // Nothing to print.

    // Initialize the state.
    state.addBefore(new OutputState(_contextRoot.next()));

    QStringList completedLines;
    String line;
    String linePrefix;

    // Rendering of lines will continue until all contexts have been
    // completed.
    while (!state.allDone())
    {
        OutputState *s, *next;
        if (structuredOutput) line = "";

        // A part of the line is taken from all of the current contexts.
        for (s = state.next(); !s->isRoot(); s = next)
        {
            next = s->next();
            if (structuredOutput)
            {
                // ctxLine will be exactly as long as the context is wide.
                String ctxLine = s->filledLine(completedLines);

                // Is there a need to print padding?
                int prevEdge = 0;
                if (!s->prev()->isRoot())
                    prevEdge = s->prev()->context()->rightEdge() + 1;
                for (; prevEdge < s->context()->leftEdge(); prevEdge++)
                    line += " ";

                // This context's contribution to the line.
                line += ctxLine;
            }
            else
            {
                // The lines are printed directly to the completedLines list.
                s->rawOutput(line, linePrefix, completedLines);

                if (advance(state))
                    break;
            }
        }
        if (structuredOutput)
        {
            // Now the line can be printed.
            completedLines << trimRight(line);
        }

        // Advance as long as possible.
        while (advance(state)) {}
    }

    if (!structuredOutput)
    {
        // Finish up with the current line.
        completedLines << line;
    }

    bool useCarriageReturns = (_proc.macros().find("CR_NL") != 0);

    // Print out the completed lines to the output stream.
    foreach (QString s, completedLines)
    {
        if (!structuredOutput)
        {
            // Filter out any remaining control characters.
            s.replace(QChar(OutputContext::CtrlAnchor), "");
        }

        line = s + "\n";
        if (useCarriageReturns)
        {
            line.replace("\n", "\r\n");
        }
        os << line;
    }
}
std::string& Utils::trim( std::string& str )
{
    return trimLeft( trimRight( str ) );
}