std::vector<materialInfo> AaMaterialFileParser::parseMaterialFile(std::string file) { std::string line; std::vector<materialInfo> mats; std::ifstream inStream( file, std::ios::in); // exit program if unable to open file. if (!inStream) { std::cerr << "File could not be opened\n"; return mats; } bool error=false; while(getline(inStream,line) && !error) { StringUtils::trimToNextWord(line); //load material if (boost::starts_with(line, "material")) { materialInfo mat; line.erase(0,8); line=StringUtils::onlyNextWord(line); mat.name=line; bool valid=false; //get material start while(getline(inStream,line) && !error) { if(StringUtils::getToken(line,"{")) { valid=true; break; } } if(!valid) { error=true; continue; } valid=false; //get material info while(getline(inStream,line) && !error) { //vs if(StringUtils::getToken(line,"vertex_ref")) { line=StringUtils::onlyNextWord(line); mat.vs_ref=line; continue; } //ps if(StringUtils::getToken(line,"pixel_ref")) { line=StringUtils::onlyNextWord(line); mat.ps_ref=line; continue; } //features if (StringUtils::getToken(line, "feature")) { mat.features.push_back(StringUtils::onlyNextWord(line)); continue; } //rs if(StringUtils::getToken(line,"depth_write_off")) { mat.renderStateDesc.depth_write=0; continue; } else if(StringUtils::getToken(line,"depth_check_off")) { mat.renderStateDesc.depth_check=0; continue; } else if(StringUtils::getToken(line,"culling_none")) { mat.renderStateDesc.culling=0; continue; } else if(StringUtils::getToken(line,"alpha_blend")) { mat.renderStateDesc.alpha_blend=1; continue; } //params to mat cbuffer if(StringUtils::getToken(line,"default_params")) { //get texture start while(getline(inStream,line) && !error) { if(StringUtils::getToken(line,"{")) { valid=true; break; } } if(!valid) { error=true; continue; } //get const value while(getline(inStream,line) && !error) { StringUtils::trimToNextWord(line); //ending if(StringUtils::getToken(line,"}")) { valid=true; break; } if(!boost::starts_with(line,"//") && !line.empty()) { std::string name = StringUtils::onlyNextWordAndContinue(line); StringUtils::trimToNextWord(line); std::vector<float> values; while (!line.empty()) { values.push_back(boost::lexical_cast<float>(StringUtils::onlyNextWordAndContinue(line))); StringUtils::trimToNextWord(line); } mat.defaultParams[name] = values; continue; } } if(!valid) error=true; valid=false; } //UAVs if(StringUtils::getToken(line,"UAV")) { mat.psuavs.push_back(StringUtils::onlyNextWord(line)); } //textures if(StringUtils::getToken(line,"texture")) { textureInfo tex; valid=false; bool toPS = true; bool toVS = false; if(boost::starts_with(line, "_vs")) { toPS = false; toVS = true; } //get texture start while(getline(inStream,line) && !error) { if(StringUtils::getToken(line,"{")) { valid=true; break; } } if(!valid) { error=true; continue; } //get texture info while(getline(inStream,line) && !error) { //file if(StringUtils::getToken(line,"name")) { line=StringUtils::onlyNextWord(line); tex.file=line; continue; } //filtering if(StringUtils::getToken(line,"filtering")) { StringUtils::trimToNextWord(line); tex.defaultSampler = false; if(boost::starts_with(line, "bil")) tex.filter=Bilinear; else if(boost::starts_with(line, "aniso")) tex.filter=Anisotropic; else if(boost::starts_with(line, "none")) tex.filter=None; else tex.filter=Anisotropic; continue; } //filtering if(StringUtils::getToken(line,"border")) { tex.defaultSampler = false; StringUtils::trimToNextWord(line); if(boost::starts_with(line, "clamp")) tex.bordering=TextureBorder_Clamp; else if(boost::starts_with(line, "warp")) tex.bordering=TextureBorder_Clamp; else if(StringUtils::getToken(line,"color")) { tex.bordering=TextureBorder_BorderColor; for (int i = 0; i<4; i++) { std::string c = StringUtils::onlyNextWordAndContinue(line); tex.border_color[i] = boost::lexical_cast<float>(c); } } else tex.bordering=TextureBorder_Clamp; continue; } //ending if(StringUtils::getToken(line,"}")) { valid=true; break; } } if(!valid) error=true; else { if(toPS) mat.pstextures.push_back(tex); if(toVS) mat.vstextures.push_back(tex); }//valid tex valid=false; } //ending if(StringUtils::getToken(line,"}")) { valid=true; break; } } if(!valid) error=true; else mats.push_back(mat); } } return mats; }
bool ccPolyline::fromFile_MeOnly(QFile& in, short dataVersion, int flags) { if (!ccHObject::fromFile_MeOnly(in, dataVersion, flags)) return false; if (dataVersion<28) return false; //as the associated cloud (=vertices) can't be saved directly (as it may be shared by multiple polylines) //we only store its unique ID (dataVersion>=28) --> we hope we will find it at loading time (i.e. this //is the responsibility of the caller to make sure that all dependencies are saved together) uint32_t vertUniqueID = 0; if (in.read((char*)&vertUniqueID,4) < 0) return ReadError(); //[DIRTY] WARNING: temporarily, we set the vertices unique ID in the 'm_associatedCloud' pointer!!! *(uint32_t*)(&m_theAssociatedCloud) = vertUniqueID; //number of points (references to) (dataVersion>=28) uint32_t pointCount = 0; if (in.read((char*)&pointCount,4) < 0) return ReadError(); if (!reserve(pointCount)) return false; //points (references to) (dataVersion>=28) for (uint32_t i=0; i<pointCount; ++i) { uint32_t pointIndex = 0; if (in.read((char*)&pointIndex,4) < 0) return ReadError(); addPointIndex(pointIndex); } //'global shift & scale' (dataVersion>=39) if (dataVersion >= 39) { if (!loadShiftInfoFromFile(in)) return ReadError(); } else { m_globalScale = 1.0; m_globalShift = CCVector3d(0,0,0); } QDataStream inStream(&in); //Closing state (dataVersion>=28) inStream >> m_isClosed; //RGB Color (dataVersion>=28) inStream >> m_rgbColor.r; inStream >> m_rgbColor.g; inStream >> m_rgbColor.b; //2D mode (dataVersion>=28) inStream >> m_mode2D; //Foreground mode (dataVersion>=28) inStream >> m_foreground; //Width of the line (dataVersion>=31) if (dataVersion >= 31) ccSerializationHelper::CoordsFromDataStream(inStream,flags,&m_width,1); else m_width = 0; return true; }
bool ClipboardData::Restore(HWND hwndOwner, ExtendedClipboardDataMessage& extendedClipboardDataMessage) { ClipboardHolder holder(hwndOwner); if (!holder.m_bIsOpen) { return false; } if (!::EmptyClipboard()) { return false; } m_lengthText = m_lengthRTF = m_lengthHTML = m_lengthDIB = 0; int nCompressedDataLength = extendedClipboardDataMessage.GetBufferLength() - extendedClipboardDataMessage.GetDataLength(); m_crc = crc32(0L, Z_NULL, 0); if (nCompressedDataLength == 0) { // no data beyond the flags return true; } rdr::MemInStream inStream(extendedClipboardDataMessage.GetCurrentPos(), nCompressedDataLength); rdr::ZlibInStream compressedStream; compressedStream.setUnderlying(&inStream, nCompressedDataLength); int length = 0; bool bFailed = false; if (extendedClipboardDataMessage.HasFlag(clipText)) { length = (int)compressedStream.readU32(); if (length > 0) { // get the incoming UTF-8 text BYTE* pIncomingText = new BYTE[length]; compressedStream.readBytes(pIncomingText, length); m_crc = crc32(m_crc, pIncomingText, length); // now we have to translate to UTF-16 int nConvertedSize = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pIncomingText, length, NULL, 0); if (nConvertedSize > 0) { HGLOBAL hData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, nConvertedSize * sizeof(wchar_t)); if (hData) { BYTE* pData = (BYTE*)GlobalLock(hData); if (pData) { int nFinalConvertedSize = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pIncomingText, length, (LPWSTR)pData, nConvertedSize); GlobalUnlock(hData); if (nFinalConvertedSize > 0) { if (::SetClipboardData(ClipboardSettings::formatUnicodeText, hData)) { hData = NULL; m_lengthText = nConvertedSize * sizeof(wchar_t); } else { bFailed = true; } } } } if (hData) { GlobalFree(hData); } } if (pIncomingText) { delete[] pIncomingText; } if (bFailed) { return false; } } } if (extendedClipboardDataMessage.HasFlag(clipRTF)) { length = (int)compressedStream.readU32(); if (length > 0) { HGLOBAL hData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, length); if (!hData) return false; BYTE* pData = (BYTE*)GlobalLock(hData); if (pData) { compressedStream.readBytes(pData, length); GlobalUnlock(hData); if (::SetClipboardData(ClipboardSettings::formatRTF, hData)) { hData = NULL; m_lengthRTF = length; } else { bFailed = true; } } if (hData) { GlobalFree(hData); } } } if (extendedClipboardDataMessage.HasFlag(clipHTML)) { length = (int)compressedStream.readU32(); if (length > 0) { HGLOBAL hData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, length); if (!hData) return false; BYTE* pData = (BYTE*)GlobalLock(hData); if (pData) { compressedStream.readBytes(pData, length); GlobalUnlock(hData); if (!::SetClipboardData(ClipboardSettings::formatHTML, hData)) { hData = NULL; m_lengthHTML = length; } else { bFailed = true; } } if (hData) { GlobalFree(hData); } } } if (extendedClipboardDataMessage.HasFlag(clipDIB)) { length = (int)compressedStream.readU32(); if (length > 0) { HGLOBAL hData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, length); if (!hData) return false; BYTE* pData = (BYTE*)GlobalLock(hData); if (pData) { compressedStream.readBytes(pData, length); GlobalUnlock(hData); if (!::SetClipboardData(ClipboardSettings::formatDIB, hData)) { hData = NULL; m_lengthDIB = length; } else { bFailed = true; } } if (hData) { GlobalFree(hData); } } } // we can ignore everything else return true; }
bool wxCurlHTTP::Put(const char* buffer, size_t size, const wxString& szRemoteFile /*= wxEmptyString*/) { wxMemoryInputStream inStream(buffer, size); return Put(inStream, szRemoteFile); }
bool ccColorScale::fromFile(QFile& in, short dataVersion, int flags) { if (dataVersion < 27) //structure appeared at version 27! return false; QDataStream inStream(&in); //name (dataVersion>=27) inStream >> m_name; //UUID (dataVersion>=27) inStream >> m_uuid; //relative state (dataVersion>=27) if (in.read((char*)&m_relative, sizeof(bool)) < 0) return ReadError(); //Absolute min value (dataVersion>=27) if (in.read((char*)&m_absoluteMinValue, sizeof(double)) < 0) return ReadError(); //Absolute range (dataVersion>=27) if (in.read((char*)&m_absoluteRange, sizeof(double)) < 0) return ReadError(); //locked state (dataVersion>=27) if (in.read((char*)&m_locked, sizeof(bool)) < 0) return ReadError(); //steps list (dataVersion>=27) { //steps count uint32_t stepCount = 0; if (in.read((char*)&stepCount, 4) < 0) return ReadError(); //read each step m_steps.clear(); for (uint32_t i = 0; i < stepCount; ++i) { double relativePos = 0.0; QColor color(Qt::white); inStream >> relativePos; inStream >> color; m_steps.push_back(ccColorScaleElement(relativePos, color)); } update(); } //custom labels (dataVersion>=40) if (dataVersion >= 40) { //custom label count uint32_t labelCount = 0; if (in.read((char*)&labelCount, 4) < 0) return ReadError(); try { for (uint32_t i = 0; i < labelCount; ++i) { double label = 0.0; inStream >> label; m_customLabels.insert(label); } } catch (const std::bad_alloc&) { //not enough memory return MemoryError(); } }
string record::makeRecord() { ifstream inStream("/proc/diskstats"); // open file location for linux disk stats if (!inStream.is_open()) { // close program if there is an issue reading from the linux folder std::cout << "Error: file could not be opened. Program will terminate.\n"; exit(0); } string report[6]; for (int index = 0; index < 6; index++) { //initialize report array report[index] = "N/A"; } string inputString; getline(inStream, inputString); long loc = inputString.find("sda"); if (loc > 0) { // remove 1st three fields since they aren't used inputString = inputString.substr(loc); inputString = inputString.substr(inputString.find(' ') + 1); } int diskData[11]; for (int index = 0; index < 11; index++) { // put 11 data elements from disk into array std::istringstream convert(inputString.substr(0, inputString.find(' ')).c_str()); inputString = inputString.substr(inputString.find(' ') + 1); convert >> diskData[index]; } if (configInfo.getBlk_read() == 1) { // report[0] float temp = diskData[0]; std::stringstream ss; // use stringstream to convert from string to float ss << temp; std::string tempString = ss.str(); report[0] = tempString; // put value in report array (to be written to file) } if (configInfo.getBlk_reads() == 1) { //report[1] float temp = ((float)diskData[0] / (float)diskData[3]) * 1000; std::stringstream ss; // use stringstream to convert from string to float ss << temp; std::string tempString = ss.str(); report[1] = tempString; // put value in report array (to be written to file) } if (configInfo.getKb_reads() == 1) { //report[2] // amount of data blocks read from disk per second in kb/s - size of sector is 1kb float temp = (((float)diskData[0] / (float)diskData[3]) * 1000) * 2; std::stringstream ss; ss << temp; // use stringstream to convert from string to float std::string tempString = ss.str(); report[2] = tempString; // put value in report array (to be written to file) } if (configInfo.getBlk_write() == 1) { //report[3] float temp = diskData[4]; std::stringstream ss; ss << temp; // use stringstream to convert from string to float std::string tempString = ss.str(); report[3] = tempString; // put value in report array (to be written to file) } if (configInfo.getBlk_writes() == 1) { //report[4] // number of data blocks written to disk per second - 4/7 float temp = ((float)diskData[4] / (float)diskData[7]) * 1000; std::stringstream ss; ss << temp; // use stringstream to convert from string to float std::string tempString = ss.str(); report[4] = tempString; // put value in report array (to be written to file) } if (configInfo.getKb_writes() == 1) { //report[5] // number of data blocks written to disk per second - in kb/s float temp = (((float)diskData[4] / (float)diskData[7]) * 1000) * 2; std::stringstream ss; ss << temp; // use stringstream to convert from string to float std::string tempString = ss.str(); report[5] = tempString; // put value in report array (to be written to file) } std::stringstream out(""); for (int index = 0; index < 6; index++) { out << report[index] << "\t"; } return out.str(); // return string of formatted data }
QStringList DBBrowserDB::decodeCSV(const QString & csvfilename, char sep, char quote, int maxrecords, int * numfields) { QFile file(csvfilename); QStringList result; *numfields = 0; int recs = 0; if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { return result; } //Other than QFile, the QTextStream-class properly detects 2-Byte QChars and converts them accordingly (UTF-8) QTextStream inStream(&file); QProgressDialog progress(QObject::tr("Decoding CSV file..."), QObject::tr("Cancel"), 0, file.size()); progress.setWindowModality(Qt::ApplicationModal); while (!inStream.atEnd()) { bool inquotemode = false; bool inescapemode = false; QString line = ""; QString current = ""; line = inStream.readLine(); //For every Line, we iterate over the single QChars QString::ConstIterator i = line.begin(); while (i != line.end()) { QChar c = *i; if (c==quote){ if (inquotemode){ if (inescapemode){ inescapemode = false; //add the escaped char here current.append(c); } else { //are we escaping, or just finishing the quote? i++; //Performing lookahead using the iterator QChar d = *i; if (d==quote) { inescapemode = true; } else { inquotemode = false; } i--; } } else { inquotemode = true; } } else if (c==sep) { if (inquotemode){ //add the sep here current.append(c); } else { //not quoting, start new record result << current; current = ""; } } else if (c==10 || c==13) { if (inquotemode){ //add the newline/carrier return current.append(c); } } else if (c==32) { // Only append blanks if we are inside of quotes if (inquotemode) { current.append(c); } } else {//another character type current.append(c); } i++; } //Moved this block from (c==10), as line-separation is now handeled by the outer-loop result << current; if (*numfields == 0){ *numfields = result.count(); } recs++; progress.setValue(file.pos()); qApp->processEvents(); if ( (progress.wasCanceled() || recs>maxrecords) && maxrecords!=-1) { break; } } file.close(); return result; }
Mesh* ObjLoader::loadOBJ(const char * path) { printf("[ObjLoader] Loading OBJ file %s...\n", path); std::vector<unsigned int> vertexIndices, uvIndices, normalIndices; std::vector<glm::vec3> temp_vertices; std::vector<glm::vec2> temp_uvs; std::vector<glm::vec3> temp_normals; std::ifstream inStream(path); if (!inStream) { printf("[ObjLoader] Impossible to open the file ! Are you in the right path ?\n"); return NULL; } std::vector<tinyobj::shape_t> shapes; std::vector<tinyobj::material_t> materials; std::string filepath(path); std::string err = tinyobj::LoadObj(shapes, materials, path, filepath.substr(0, filepath.find_last_of("\\/")+1).c_str()); if (!err.empty()) { std::cerr << "[ObjLoader] [tinyobj] " << err << std::endl; exit(1); } std::cout << "[OBJLoader] # of shapes : " << shapes.size() << std::endl; std::cout << "[OBJLoader] # of materials : " << materials.size() << std::endl; std::vector<Material*> materiallist; for (size_t i = 0; i < materials.size(); i++) { Material* material = new Material(); // ResourceManager::instance()->createMaterial(path).get(); // new Material(); material->diffuse = glm::vec3(materials[i].diffuse[0], materials[i].diffuse[1], materials[i].diffuse[2]); material->ambient = glm::vec3(materials[i].ambient[0], materials[i].ambient[1], materials[i].ambient[2]); material->specular = glm::vec3(materials[i].specular[0], materials[i].specular[1], materials[i].specular[2]); material->shininess = materials[i].shininess; material->dissolve = materials[i].dissolve; material->program = ResourceManager::instance()->createShader("./shaders/generic").get(); // material->program = new ShaderProgram(); // material->program->load("./shaders/vertex.glsl", "./shaders/fragment.glsl"); materiallist.push_back(material); printf("material[%ld].name = %s\n", i, materials[i].name.c_str()); printf(" material.Ka = (%f, %f ,%f)\n", materials[i].ambient[0], materials[i].ambient[1], materials[i].ambient[2]); printf(" material.Kd = (%f, %f ,%f)\n", materials[i].diffuse[0], materials[i].diffuse[1], materials[i].diffuse[2]); printf(" material.Ks = (%f, %f ,%f)\n", materials[i].specular[0], materials[i].specular[1], materials[i].specular[2]); printf(" material.Tr = (%f, %f ,%f)\n", materials[i].transmittance[0], materials[i].transmittance[1], materials[i].transmittance[2]); printf(" material.Ke = (%f, %f ,%f)\n", materials[i].emission[0], materials[i].emission[1], materials[i].emission[2]); printf(" material.Ns = %f\n", materials[i].shininess); printf(" material.Ni = %f\n", materials[i].ior); printf(" material.dissolve = %f\n", materials[i].dissolve); printf(" material.illum = %d\n", materials[i].illum); printf(" material.map_Ka = %s\n", materials[i].ambient_texname.c_str()); printf(" material.map_Kd = %s\n", materials[i].diffuse_texname.c_str()); printf(" material.map_Ks = %s\n", materials[i].specular_texname.c_str()); printf(" material.map_Ns = %s\n", materials[i].normal_texname.c_str()); printf("\n"); } Mesh* mesh = new Mesh(); Material* material = ResourceManager::instance()->createMaterial(path).get(); /* new Material(); material->program = new ShaderProgram(); material->program->load("./shaders/vertex.glsl", "./shaders/fragment.glsl");*/ mesh->material = material; for (size_t i = 0; i < shapes.size(); i++) { VertexBuffer *vertexBuffer = new VertexBuffer(); SubMesh *submesh = new SubMesh(); submesh->mesh = mesh; if (shapes[i].mesh.material_ids.size() > 0 && shapes[i].mesh.material_ids[0] != -1) { submesh->material = materiallist[shapes[i].mesh.material_ids[0]]; printf("hethethet %d", shapes[i].mesh.material_ids[0]); } mesh->subMeshes.push_back(submesh); printf("shape[%ld].name = %s\n", i, shapes[i].name.c_str()); printf("Size of shape[%ld].indices: %ld\n", i, shapes[i].mesh.indices.size()); printf("Size of shape[%ld].material_ids: %ld\n", i, shapes[i].mesh.material_ids.size()); assert((shapes[i].mesh.indices.size() % 3) == 0); for (size_t f = 0; f < shapes[i].mesh.indices.size() / 3; f++) { vertexBuffer->addIndex(shapes[i].mesh.indices[3*f+0]); vertexBuffer->addIndex(shapes[i].mesh.indices[3*f+1]); vertexBuffer->addIndex(shapes[i].mesh.indices[3*f+2]); printf(" idx[%ld] mat_id = %d\n", f, shapes[i].mesh.material_ids[f]); } printf("shape[%ld].vertices: %ld\n", i, shapes[i].mesh.positions.size()); printf("shape[%ld].normals: %ld\n", i, shapes[i].mesh.normals.size()); printf("shape[%ld].texcoords: %ld\n", i, shapes[i].mesh.texcoords.size()); assert((shapes[i].mesh.positions.size() % 3) == 0); assert((shapes[i].mesh.normals.size() % 3) == 0); for (size_t v = 0; v < shapes[i].mesh.positions.size() / 3; v++) { glm::vec3 vertex = glm::vec3(shapes[i].mesh.positions[3*v+0], shapes[i].mesh.positions[3*v+1], shapes[i].mesh.positions[3*v+2]); vertexBuffer->addVertex(vertex); glm::vec3 normal = glm::vec3(shapes[i].mesh.normals[3*v+0], shapes[i].mesh.normals[3*v+1], shapes[i].mesh.normals[3*v+2]); vertexBuffer->addNormal(normal); if (shapes[i].mesh.texcoords.size()) { glm::vec2 uv = glm::vec2(shapes[i].mesh.texcoords[2*v+0], shapes[i].mesh.texcoords[2*v+1]); vertexBuffer->addUV(uv); } } vertexBuffer->upload(); submesh->vertexBuffer = vertexBuffer; } return mesh; }
wxThread::ExitCode ModderTask::TaskStart() { // Get the mod list ModList *modList = m_inst->GetModList(); wxFileName mcBin = m_inst->GetBinDir(); wxFileName mcJar = m_inst->GetMCJar(); wxFileName mcBackup = m_inst->GetMCBackup(); // Nothing to do if there are no jar mods to install, no backup and just the mc jar if(mcJar.FileExists() && !mcBackup.FileExists() && modList->empty()) { m_inst->SetNeedsRebuild(false); return (ExitCode)1; } SetStatus(_("Installing mods - backing up minecraft.jar...")); if (!mcBackup.FileExists() && !wxCopyFile(mcJar.GetFullPath(), mcBackup.GetFullPath())) { OnFail(_("Failed to back up minecraft.jar")); return (ExitCode)0; } if (mcJar.FileExists() && !wxRemoveFile(mcJar.GetFullPath())) { OnFail(_("Failed to delete old minecraft.jar")); return (ExitCode)0; } // TODO: good spot for user cancel check? or not... TaskStep(); // STEP 1 SetStatus(_("Installing mods - Opening minecraft.jar")); wxFFileOutputStream jarStream(mcJar.GetFullPath()); wxZipOutputStream zipOut(jarStream); // Files already added to the jar. // These files will be skipped. std::set<wxString> addedFiles; // Modify the jar TaskStep(); // STEP 2 SetStatus(_("Installing mods - Adding mod files...")); for (ModList::const_reverse_iterator iter = modList->rbegin(); iter != modList->rend(); iter++) { wxFileName modFileName = iter->GetFileName(); SetStatus(_("Installing mods - Adding ") + modFileName.GetFullName()); if (iter->IsZipMod()) { wxFFileInputStream modStream(modFileName.GetFullPath()); wxZipInputStream zipStream(modStream); std::auto_ptr<wxZipEntry> entry; while (entry.reset(zipStream.GetNextEntry()), entry.get() != NULL) { if (entry->IsDir()) continue; wxString name = entry->GetName(); if (addedFiles.count(name) == 0) { if (!zipOut.CopyEntry(entry.release(), zipStream)) break; addedFiles.insert(name); } } } else { wxFileName destFileName = modFileName; destFileName.MakeRelativeTo(m_inst->GetInstModsDir().GetFullPath()); wxString destFile = destFileName.GetFullPath(); if (addedFiles.count(destFile) == 0) { wxFFileInputStream input(modFileName.GetFullPath()); zipOut.PutNextEntry(destFile); zipOut.Write(input); addedFiles.insert(destFile); } } } { wxFFileInputStream inStream(mcBackup.GetFullPath()); wxZipInputStream zipIn(inStream); std::auto_ptr<wxZipEntry> entry; while (entry.reset(zipIn.GetNextEntry()), entry.get() != NULL) { wxString name = entry->GetName(); if (!name.Matches("META-INF*") && addedFiles.count(name) == 0) { if (!zipOut.CopyEntry(entry.release(), zipIn)) break; addedFiles.insert(name); } } } // Recompress the jar TaskStep(); // STEP 3 SetStatus(_("Installing mods - Recompressing jar...")); m_inst->SetNeedsRebuild(false); m_inst->UpdateVersion(true); return (ExitCode)1; }
int main(void) { setlocale(LC_ALL, ".1251");// Русификация // Создание входящего потока и его открытие ifstream inStream("readme.txt"); // Проверка на открытие файла if (!inStream.is_open()) { cout << "Ошибка открытия файла file.txt" << endl; system("pause"); exit(1); } // Создание динамического массива NOTE NOTE *notes = new NOTE[8]; char tmpSurname[200];// Временная переменная фамилии int tmpPhoneNumber(0);// Временная переменная номера телефона int tmpBirthday[3] = { 0 };// Временная переменная даты рождения char tmpSeparator(' ');// Символ разделяющий дату рождения // Цикл чтения из файла for (int i = 0; i < 8; i++) { // Считывание данных во временные переменные inStream >> tmpSurname >> tmpPhoneNumber >> tmpBirthday[0] >> tmpSeparator >> tmpBirthday[1] >> tmpSeparator >> tmpBirthday[2]; // Создание временного объекта NOTE NOTE tmpNote(tmpSurname, tmpPhoneNumber, tmpBirthday[0], tmpBirthday[1], tmpBirthday[2]); // Вставка временного объекта в массив notes notes[i] = tmpNote; } // Закрываем поток inStream.close(); /* Вывод массива до сортировки */ cout << endl << "Вывод массива до сортировки: " << endl << endl; for (int i = 0; i < 8; i++) notes[i].show(); // Сортируем массив NOTE selectSort(notes, 8); /* Вывод массива после сортировки */ cout << endl << "Вывод массива после сортировки: " << endl << endl; for (int i = 0; i < 8; i++) notes[i].show(); // Ввод месяца cout << "Введите пожалуйста фамилию для сравнения: "; cin >> tmpSurname; // Преобразование символов из иероглифов в русскую раскладку OemToCharA(tmpSurname, tmpSurname); // Очистка экрана system("cls"); // Поиск информации for (int i = 0, count = 0; i <= 8; i++) { // Если пройдясь по всем записям и не нашлось ни одного совпадения if ((i == 8) && count == 0) cout << "Нет соответствующей записи" << endl; // Если прошлись по всем записям и нашлись совпадения else if (i == 8 && count != 0) break; // Если не закончились записи, ищем совпадения else if (notes[i] == tmpSurname) { // Вывод notes[i].show(); // Увеличение счётчика count++; } } // Приостановка программы для просмотра результата system("pause"); return NULL;// Передача управления операционной системе }
void MDAL::DriverFlo2D::parseTIMDEPFile( const std::string &datFileName, const std::vector<double> &elevations ) { // TIMDEP.OUT // this file is optional, so if not present, reading is skipped // time (separate line) // For every Vertex: // FLO2D: ELEM NUMber (indexed from 1), depth, velocity, velocity x, velocity y // FLO2DPro: ELEM NUMber (indexed from 1), depth, velocity, velocity x, velocity y, water surface elevation std::string inFile( fileNameFromDir( datFileName, "TIMDEP.OUT" ) ); if ( !MDAL::fileExists( inFile ) ) { return; } std::ifstream inStream( inFile, std::ifstream::in ); std::string line; size_t nVertexs = mMesh->verticesCount(); size_t ntimes = 0; double time = 0.0; size_t face_idx = 0; std::shared_ptr<DatasetGroup> depthDsGroup = std::make_shared< DatasetGroup >( name(), mMesh.get(), datFileName, "Depth" ); depthDsGroup->setIsOnVertices( false ); depthDsGroup->setIsScalar( true ); std::shared_ptr<DatasetGroup> waterLevelDsGroup = std::make_shared< DatasetGroup >( name(), mMesh.get(), datFileName, "Water Level" ); waterLevelDsGroup->setIsOnVertices( false ); waterLevelDsGroup->setIsScalar( true ); std::shared_ptr<DatasetGroup> flowDsGroup = std::make_shared< DatasetGroup >( name(), mMesh.get(), datFileName, "Velocity" ); flowDsGroup->setIsOnVertices( false ); flowDsGroup->setIsScalar( false ); std::shared_ptr<MDAL::MemoryDataset> flowDataset; std::shared_ptr<MDAL::MemoryDataset> depthDataset; std::shared_ptr<MDAL::MemoryDataset> waterLevelDataset; while ( std::getline( inStream, line ) ) { line = MDAL::rtrim( line ); std::vector<std::string> lineParts = MDAL::split( line, ' ' ); if ( lineParts.size() == 1 ) { time = MDAL::toDouble( line ); ntimes++; if ( depthDataset ) addDatasetToGroup( depthDsGroup, depthDataset ); if ( flowDataset ) addDatasetToGroup( flowDsGroup, flowDataset ); if ( waterLevelDataset ) addDatasetToGroup( waterLevelDsGroup, waterLevelDataset ); depthDataset = std::make_shared< MemoryDataset >( depthDsGroup.get() ); flowDataset = std::make_shared< MemoryDataset >( flowDsGroup.get() ); waterLevelDataset = std::make_shared< MemoryDataset >( waterLevelDsGroup.get() ); depthDataset->setTime( time ); flowDataset->setTime( time ); waterLevelDataset->setTime( time ); face_idx = 0; } else if ( ( lineParts.size() == 5 ) || ( lineParts.size() == 6 ) ) { // new Vertex for time if ( !depthDataset || !flowDataset || !waterLevelDataset ) throw MDAL_Status::Err_UnknownFormat; if ( face_idx == nVertexs ) throw MDAL_Status::Err_IncompatibleMesh; // this is magnitude: getDouble(lineParts[2]); flowDataset->values()[2 * face_idx] = getDouble( lineParts[3] ); flowDataset->values()[2 * face_idx + 1] = getDouble( lineParts[4] ); double depth = getDouble( lineParts[1] ); depthDataset->values()[face_idx] = depth; if ( !is_nodata( depth ) ) depth += elevations[face_idx]; waterLevelDataset->values()[face_idx] = depth; face_idx ++; } else { throw MDAL_Status::Err_UnknownFormat; } } if ( depthDataset ) addDatasetToGroup( depthDsGroup, depthDataset ); if ( flowDataset ) addDatasetToGroup( flowDsGroup, flowDataset ); if ( waterLevelDataset ) addDatasetToGroup( waterLevelDsGroup, waterLevelDataset ); depthDsGroup->setStatistics( MDAL::calculateStatistics( depthDsGroup ) ); flowDsGroup->setStatistics( MDAL::calculateStatistics( flowDsGroup ) ); waterLevelDsGroup->setStatistics( MDAL::calculateStatistics( waterLevelDsGroup ) ); mMesh->datasetGroups.push_back( depthDsGroup ); mMesh->datasetGroups.push_back( flowDsGroup ); mMesh->datasetGroups.push_back( waterLevelDsGroup ); }
void ModderTask::TaskStart() { // Get the mod list const ModList *modList = m_inst->GetModList(); wxFileName mcBin = m_inst->GetBinDir(); wxFileName mcJar = m_inst->GetMCJar(); wxFileName mcBackup = m_inst->GetMCBackup(); SetStatus(_("Installing mods - backing up minecraft.jar...")); if (!mcBackup.FileExists() && !wxCopyFile(mcJar.GetFullPath(), mcBackup.GetFullPath())) { OnFail(_("Failed to back up minecraft.jar")); return; } if (mcJar.FileExists() && !wxRemoveFile(mcJar.GetFullPath())) { OnFail(_("Failed to delete old minecraft.jar")); return; } if (TestDestroy()) return; TaskStep(); // STEP 1 SetStatus(_("Installing mods - Opening minecraft.jar")); wxFFileOutputStream jarStream(mcJar.GetFullPath()); wxZipOutputStream zipOut(jarStream); { wxFFileInputStream inStream(mcBackup.GetFullPath()); wxZipInputStream zipIn(inStream); std::auto_ptr<wxZipEntry> entry; while (entry.reset(zipIn.GetNextEntry()), entry.get() != NULL) if (!entry->GetName().Matches(_("META-INF*"))) if (!zipOut.CopyEntry(entry.release(), zipIn)) break; } // Modify the jar TaskStep(); // STEP 2 SetStatus(_("Installing mods - Adding mod files...")); for (ConstModIterator iter = modList->begin(); iter != modList->end(); iter++) { wxFileName modFileName = iter->GetFileName(); SetStatus(_("Installing mods - Adding ") + modFileName.GetFullName()); if (iter->IsZipMod()) { wxFFileInputStream modStream(modFileName.GetFullPath()); TransferZipArchive(modStream, zipOut); } else { wxFileName destFileName = modFileName; destFileName.MakeRelativeTo(m_inst->GetInstModsDir().GetFullPath()); wxFFileInputStream input(modFileName.GetFullPath()); zipOut.PutNextEntry(destFileName.GetFullPath()); zipOut.Write(input); } } // Recompress the jar TaskStep(); // STEP 3 SetStatus(_("Installing mods - Recompressing jar...")); m_inst->SetNeedsRebuild(false); }
bool LzNTunnelsSynthesis::loadBaseClearanceTemplateData(OutputClearanceImageType type) { hasinitBaseClearanceData = false; baseClearandeData.initMaps(); QFile file; QString in; QString typefilename = ""; switch (type) { case OutputClearanceImageType::OutType_B_NeiRan: typefilename = "BaseClearance_B_NeiRan.sec"; break; case OutputClearanceImageType::OutType_B_DianLi: typefilename = "BaseClearance_B_DianLi.sec"; break; case OutputClearanceImageType::OutType_D_NeiRan: typefilename = "BaseClearance_D_NeiRan.sec"; break; case OutputClearanceImageType::OutType_D_DianLi: typefilename = "BaseClearance_D_DianLi.sec"; break; default: typefilename = "BaseClearance_B_DianLi.sec"; break; } QString filename = QString::fromLocal8Bit(templatepath.c_str()) + "/" + typefilename; qDebug() << "filename " << filename; file.setFileName(filename); // Currently here for debugging purposes qDebug() << "Reading file: " << filename.toLocal8Bit().data() << endl; if (file.open(QIODevice::ReadOnly | QIODevice::Text)) { QTextStream inStream(&file); // readfile in = inStream.readLine(); int height; int left; int right; while(!(in.isNull())) { height = in.section("\t",0,0).toInt(); left = in.section("\t",1,1).toInt(); // Reads in fifth column: signal-to-noise ratio right = in.section("\t",2,2).toInt(); baseClearandeData.updateToMapVals(height, (float)left, (float)right); in = inStream.readLine(); } file.close(); qDebug() << "read_end" << endl; hasinitBaseClearanceData = true; return true; } // Do some proper debugging here at some point... else { std::cout << "Problem reading file: " << filename.toLocal8Bit().data() << std::endl; hasinitBaseClearanceData = false; return false; } }
int main() { QFile testfile("test.mobi"); testfile.open(QIODevice::ReadOnly); QDataStream inStream(&testfile); /* file starts with pdb header, * 4bytes at 60 should be 'BOOK' * 4bytes at 64 should be 'MOBI' * if file is a valid .mobi */ //goto pos 60 if (!testfile.seek(60)) { printf("failed to seek to offset 60\n"); return 0; } //read 8 bytes char * tmpchar = new char[8]; if (inStream.readRawData(tmpchar,8) != 8) { printf("failed to read 8 bytes\n"); return 0; } //check'em if (strncmp(tmpchar,"BOOKMOBI",8) == 0) printf ( "got MOBI header\n"); /* position 76 has number of PDB records * records follow straight after * */ //goto pos 76 testfile.seek(76); delete tmpchar; tmpchar = new char[2]; unsigned int records = 0 ; if (inStream.readRawData(tmpchar,2) == 2) { records = bytesToInt(tmpchar,0,2) ; //needs a batter way to figure it out printf ( "mobi records : %d \n", records); } printf("parsing record0\n"); //records start at 78 and take up 8*records bytes of data //http://wiki.mobileread.com/wiki/PDB#Palm_Database_Format testfile.seek(78); delete tmpchar; tmpchar = new char[8]; //4b - record offset from start of file //1b - record flags //3b - record id testfile.seek(testfile.pos() + 8*records); /* for (int i=0;i<records;i++) { printf("record %d\n", i); if (inStream.readRawData(tmpchar,8) != 8) { printf("file ended prematurely. exiting\n"); return 0; } //printbytes(tmpchar,8); unsigned int offset = bytesToInt(tmpchar,0,4) ; //needs a batter way to figure it out int flags = tmpchar2[4]; unsigned int record_id = bytesToInt(tmpchar,5,2); printf ( " -- offset : %0x [%d] \n", offset, offset); printf ( " -- flags : %0x [%d] \n", flags, flags); printf ( " -- record_id : %0x [%d] \n", record_id, record_id); } */ /* there are 2 bytes of padding after records, skip them */ testfile.seek(testfile.pos() + 2); /* 16 byte palmdoc header starts here, read it */ delete tmpchar; //save this location as reference for later qint64 header0pos = testfile.pos(); /* tmpchar = new char[16]; testresult = inStream.readRawData(tmpchar,16); if (testresult == 16) { printbytes(tmpchar,16); //we don't really need this, just for verification printf("compression : %0x \n",bytesToInt(tmpchar,0,2)); printf("dummy : %0x (expected 0)\n",bytesToInt(tmpchar,2,2)); printf("textLength : %0x \n",bytesToInt(tmpchar,4,4)); printf("recCount : %0x \n",bytesToInt(tmpchar,8,2)); printf("recSize : %0x (expected 0x1000)\n",bytesToInt(tmpchar,10,2)); printf("encType : %0x \n",bytesToInt(tmpchar,12,2)); printf("unk : %0x \n",bytesToInt(tmpchar,14,2)); } */ /* instead of parsing, we just go over it and skip to record #0 that follows */ testfile.seek(testfile.pos() + 16); //go through MOBI header //first let's see if we have a header, 4 bytes should be 'MOBI', 16 bytes from beginning of PalmDoc header tmpchar = new char[4]; if ((inStream.readRawData(tmpchar,4) == 4) && (strncmp(tmpchar,"MOBI",4) == 0)) printf("got MOBI header in record 0\n"); //next up is header length that includes that 'MOBI' signature just read. unsigned int mobiHeaderSize = 0; if (inStream.readRawData(tmpchar,4) == 4) { mobiHeaderSize = bytesToInt(tmpchar,0,4); } printf("mobi header size : %d [ %0x ]\n", mobiHeaderSize, mobiHeaderSize); printf("EXTH should start at %llx\n", mobiHeaderSize + header0pos + 0x10); //add 16 bytes for palmdoc header parsed previously //check if EXTH record exists testfile.seek(header0pos + 0x80) ; //location of EXTH flags in header; bool got_exth_header = false; if (inStream.readRawData(tmpchar,4) == 4) { // printbytes(tmpchar,4); unsigned int exth_flags = bytesToInt(tmpchar,0,4); if ( exth_flags & 0x40) got_exth_header = true; } if (!got_exth_header) { printf("EXTH not found, exiting\n"); return 0; } printf("EXTH header exists\n"); //if EXTH header size is not divisible by 4, it has to be padded to a multiple of 4, and then actual data starts. int exth_padding = 0; if (mobiHeaderSize % 4 ) exth_padding = 4 - mobiHeaderSize % 4 ; printf(" exth padding : %d\n", exth_padding); //go through EXTH header, if found (indicated in MOBI header) //navigating to start of EXTH printf("seeking to exth header\n"); qint64 exth_pos = header0pos + mobiHeaderSize+0x10; //first palmdoc entry offset + 16bytes + entire mobi header is where exth starts testfile.seek(exth_pos); printf("at position %llu [ %llx ]\n", testfile.pos(), testfile.pos()); /* 'EXTH' 4 bytes - length of entire header 4 bytes - number of records < records follow > record { 4 bytes type 4 bytes length of entire record (that is, including 8 bytes for type and length) length-8 actual record data } 0-3 bytes padding (in exth_padding) */ delete tmpchar; tmpchar = new char [12]; printf("reading 12 bytes\n"); if (inStream.readRawData(tmpchar,12) == 12) { // printbytes(tmpchar,12); if (strncpy(tmpchar,"EXTH",4) == 0) printf("got EXTH header\n"); unsigned int headerlength = bytesToInt(tmpchar,4,4); unsigned int exthRecords = bytesToInt(tmpchar,8,4); printf("header is %x long \n", headerlength); printf("there are %x records \n",exthRecords); //go through the EXTH records for (unsigned int j=0;j<exthRecords;j++) { char * tmprecord = new char [8]; if (inStream.readRawData(tmprecord,8) ==8 ) { // printf("record %d/%d\n",j,exthRecords); unsigned int recType = bytesToInt(tmprecord,0,4); // printf(" type : %d\n",recType); unsigned int recLength = bytesToInt(tmprecord,4,4); // printf(" length : %0x\n", recLength); char * recordData = new char[(int)recLength - 8]; if (inStream.readRawData(recordData,(int)recLength - 8) == (int)recLength -8) { // printf(" data : %s\n", recordData); // printbytes(recordData,(int)recLength -8); } switch (recType) { case 100: printf("author : %s \n", recordData); break; case 106: printf("date : %s \n", recordData); break; case 105: printf("genre : %s \n", recordData); break; case 503: printf("title : %s \n", recordData); break; case 524: printf("lang : %s \n", recordData); break; default: break; } } delete tmprecord; } } return 0; }
shaderRefMaps AaMaterialFileParser::parseShaderFile(std::string file) { std::string line; shaderRefMaps shds; std::string name; std::ifstream inStream( file, std::ios::in); // exit program if unable to open file. if (!inStream) { std::cerr << "File could not be opened\n"; return shds; } bool error=false; while(getline(inStream,line) && !error) { StringUtils::trimToNextWord(line); //load shader if (boost::starts_with(line, "vertex_shader") || boost::starts_with(line, "pixel_shader")) { bool pixel; if (boost::starts_with(line, "vertex_shader")) { pixel=false; line.erase(0,13); } else { pixel=true; line.erase(0,12); } shaderRef shader; shader.shader=NULL; shader.usedBuffersFlag=0; shader.perMatConstBufferSize = 0; line=StringUtils::onlyNextWord(line); name=line; bool valid=false; //get shader start while(getline(inStream,line) && !error) { if(StringUtils::getToken(line,"{")) { valid=true; break; } } if(!valid) { error=true; continue; } valid=false; //get shader info while(getline(inStream,line) && !error) { if(StringUtils::getToken(line,"file")) { line=StringUtils::onlyNextWord(line); shader.file=line; continue; } if(StringUtils::getToken(line,"entry")) { line=StringUtils::onlyNextWord(line); shader.entry=line; continue; } if(StringUtils::getToken(line,"profile")) { line=StringUtils::onlyNextWord(line); shader.profile=line; continue; } if(StringUtils::getToken(line,"cbuffer")) { if(StringUtils::getToken(line,"per_frame")) { shader.usedBuffersFlag |= PER_FRAME; } else if(StringUtils::getToken(line,"per_object")) { shader.usedBuffersFlag |= PER_OBJECT; } else if(StringUtils::getToken(line,"per_material")) { shader.usedBuffersFlag |= PER_MATERIAL; valid=false; //get constants start while(getline(inStream,line) && !error) { if(StringUtils::getToken(line,"{")) { valid=true; break; } } if(!valid) { error=true; continue; } valid=false; int varPosition = 0; //get consts info while(getline(inStream,line)) { StringUtils::trimToNextWord(line); //ending if(StringUtils::getToken(line,"}")) { valid=true; break; } else if(boost::starts_with(line, "float")) { line.erase(0,5); ConstantInfo info; info.size = boost::lexical_cast<int>(StringUtils::onlyNextWordAndContinue(line)); info.position = varPosition; varPosition+=info.size; std::string var = StringUtils::onlyNextWordAndContinue(line); std::string defautValue = StringUtils::onlyNextWordAndContinue(line); int ii=0; while(!defautValue.empty()) { info.defaultValue[ii] = boost::lexical_cast<float>(defautValue); ii++; defautValue = StringUtils::onlyNextWordAndContinue(line); } shader.perMatConstBufferSize+=info.size; info.size*=4; info.position*=4; shader.perMatVars[var] = info; continue; } } if(!valid) { error=true; continue; } } else error=true; continue; } //ending if(StringUtils::getToken(line,"}")) { valid=true; break; } } if(!valid) error=true; else { if(pixel) shds.pixelShaderRefs.insert(std::pair<std::string,shaderRef>(name,shader)); else shds.vertexShaderRefs.insert(std::pair<std::string,shaderRef>(name,shader)); } } } return shds; }
MolChemicalFeatureFactory *buildFeatFactoryFromString(std::string fdefString) { std::istringstream inStream(fdefString); std::istream &instrm = static_cast<std::istream &>(inStream); return buildFeatureFactory(instrm); }
STDMETHODIMP CHandler::Extract(const UInt32* indices, UInt32 numItems, Int32 _aTestMode, IArchiveExtractCallback *extractCallback) { COM_TRY_BEGIN bool testMode = (_aTestMode != 0); bool allFilesMode = (numItems == UInt32(-1)); if (allFilesMode) numItems = _numItems; if (numItems == 0) return S_OK; UInt64 totalSize = 0; UInt32 i; for (i = 0; i < numItems; i++) totalSize += _items[allFilesMode ? i : indices[i]].Size; extractCallback->SetTotal(totalSize); UInt64 currentTotalSize = 0; UInt64 currentItemSize; NCompress::CCopyCoder *copyCoderSpec = new NCompress::CCopyCoder(); CMyComPtr<ICompressCoder> copyCoder = copyCoderSpec; CLocalProgress *lps = new CLocalProgress; CMyComPtr<ICompressProgressInfo> progress = lps; lps->Init(extractCallback, false); CLimitedSequentialInStream *streamSpec = new CLimitedSequentialInStream; CMyComPtr<ISequentialInStream> inStream(streamSpec); streamSpec->SetStream(_inStream); for (i = 0; i < numItems; i++, currentTotalSize += currentItemSize) { lps->InSize = lps->OutSize = currentTotalSize; RINOK(lps->SetCur()); CMyComPtr<ISequentialOutStream> realOutStream; Int32 askMode = testMode ? NArchive::NExtract::NAskMode::kTest : NArchive::NExtract::NAskMode::kExtract; UInt32 index = allFilesMode ? i : indices[i]; const CItem &item = _items[index]; RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); currentItemSize = item.Size; if (!testMode && (!realOutStream)) continue; RINOK(extractCallback->PrepareOperation(askMode)); if (testMode) { RINOK(extractCallback->SetOperationResult(NArchive::NExtract::NOperationResult::kOK)); continue; } RINOK(_inStream->Seek(_startPos + item.Offset, STREAM_SEEK_SET, NULL)); streamSpec->Init(item.Size); RINOK(copyCoder->Code(inStream, realOutStream, NULL, NULL, progress)); realOutStream.Release(); RINOK(extractCallback->SetOperationResult((copyCoderSpec->TotalSize == item.Size) ? NArchive::NExtract::NOperationResult::kOK: NArchive::NExtract::NOperationResult::kDataError)); } return S_OK; COM_TRY_END }
/** * @test Verify that the API for struct deployments works */ TEST_F(DeploymentTest, StructWithDeployment) { CommonAPI::SomeIP::Message message; CommonAPI::SomeIP::StructDeployment< CommonAPI::EmptyDeployment, CommonAPI::SomeIP::IntegerDeployment<uint8_t> > ed_0(0, nullptr, nullptr); CommonAPI::SomeIP::StructDeployment< CommonAPI::EmptyDeployment, CommonAPI::SomeIP::IntegerDeployment<uint8_t> > ed_1(1, nullptr, nullptr); CommonAPI::SomeIP::StructDeployment< CommonAPI::EmptyDeployment, CommonAPI::SomeIP::IntegerDeployment<uint8_t> > ed_2(2, nullptr, nullptr); CommonAPI::SomeIP::StructDeployment< CommonAPI::EmptyDeployment, CommonAPI::SomeIP::IntegerDeployment<uint8_t> > ed_4(4, nullptr, nullptr); message = CommonAPI::SomeIP::Message::createMethodCall( CommonAPI::SomeIP::Address(0, 0, 0, 0), 515, false); { CommonAPI::SomeIP::OutputStream outStream(message, false); v1_0::commonapi::someip::deploymenttest::TestInterface::tStruct_w4 outv(true, 100); outStream.writeValue(outv, &ed_0); EXPECT_FALSE(outStream.hasError()); outStream.flush(); CommonAPI::SomeIP::InputStream inStream(message, false); v1_0::commonapi::someip::deploymenttest::TestInterface::tStruct_w4 inv; inStream.readValue(inv, &ed_0); EXPECT_FALSE(inStream.hasError()); EXPECT_EQ(outv, inv); } { CommonAPI::SomeIP::OutputStream outStream(message, false); v1_0::commonapi::someip::deploymenttest::TestInterface::tStruct_w4 outv(true, 100); outStream.writeValue(outv, &ed_1); EXPECT_FALSE(outStream.hasError()); outStream.flush(); CommonAPI::SomeIP::InputStream inStream(message, false); v1_0::commonapi::someip::deploymenttest::TestInterface::tStruct_w4 inv; inStream.readValue(inv, &ed_1); EXPECT_FALSE(inStream.hasError()); EXPECT_EQ(outv, inv); } { CommonAPI::SomeIP::OutputStream outStream(message, false); v1_0::commonapi::someip::deploymenttest::TestInterface::tStruct_w4 outv(true, 100); outStream.writeValue(outv, &ed_2); EXPECT_FALSE(outStream.hasError()); outStream.flush(); CommonAPI::SomeIP::InputStream inStream(message, false); v1_0::commonapi::someip::deploymenttest::TestInterface::tStruct_w4 inv; inStream.readValue(inv, &ed_2); EXPECT_FALSE(inStream.hasError()); EXPECT_EQ(outv, inv); } { CommonAPI::SomeIP::OutputStream outStream(message, false); v1_0::commonapi::someip::deploymenttest::TestInterface::tStruct_w4 outv(true, 100); outStream.writeValue(outv, &ed_4); EXPECT_FALSE(outStream.hasError()); outStream.flush(); CommonAPI::SomeIP::InputStream inStream(message, false); v1_0::commonapi::someip::deploymenttest::TestInterface::tStruct_w4 inv; inStream.readValue(inv, &ed_4); EXPECT_FALSE(inStream.hasError()); EXPECT_EQ(outv, inv); } }
ChemicalReaction *RxnBlockToChemicalReaction(const std::string &rxnBlock) { std::istringstream inStream(rxnBlock); unsigned int line = 0; return RxnDataStreamToChemicalReaction(inStream, line); };
static int filter_picture(const SkString& inFile, const SkString& outFile) { SkAutoTDelete<SkPicture> inPicture; SkFILEStream inStream(inFile.c_str()); if (inStream.isValid()) { inPicture.reset(SkPicture::CreateFromStream(&inStream)); } if (NULL == inPicture.get()) { SkDebugf("Could not read file %s\n", inFile.c_str()); return -1; } int localCount[SK_ARRAY_COUNT(gOptTable)]; memset(localCount, 0, sizeof(localCount)); SkDebugCanvas debugCanvas(inPicture->width(), inPicture->height()); debugCanvas.setBounds(inPicture->width(), inPicture->height()); inPicture->draw(&debugCanvas); // delete the initial save and restore since replaying the commands will // re-add them if (debugCanvas.getSize() > 1) { debugCanvas.deleteDrawCommandAt(0); debugCanvas.deleteDrawCommandAt(debugCanvas.getSize()-1); } bool changed = true; int numBefore = debugCanvas.getSize(); while (changed) { changed = false; for (int i = 0; i < debugCanvas.getSize(); ++i) { for (size_t opt = 0; opt < SK_ARRAY_COUNT(gOptTable); ++opt) { if ((*gOptTable[opt].fCheck)(&debugCanvas, i)) { (*gOptTable[opt].fApply)(&debugCanvas, i); ++gOptTable[opt].fNumTimesApplied; ++localCount[opt]; if (debugCanvas.getSize() == i) { // the optimization removed all the remaining operations break; } opt = 0; // try all the opts all over again changed = true; } } } } int numAfter = debugCanvas.getSize(); if (!outFile.isEmpty()) { SkPictureRecorder recorder; SkCanvas* canvas = recorder.beginRecording(inPicture->width(), inPicture->height(), NULL, 0); debugCanvas.draw(canvas); SkAutoTUnref<SkPicture> outPicture(recorder.endRecording()); SkFILEWStream outStream(outFile.c_str()); outPicture->serialize(&outStream); } bool someOptFired = false; for (size_t opt = 0; opt < SK_ARRAY_COUNT(gOptTable); ++opt) { if (0 != localCount[opt]) { SkDebugf("%d: %d ", opt, localCount[opt]); someOptFired = true; } } if (!someOptFired) { SkDebugf("No opts fired\n"); } else { SkDebugf("\t before: %d after: %d delta: %d\n", numBefore, numAfter, numBefore-numAfter); } return 0; }
bool wxCurlHTTP::Put(const wxString& szFilePath, const wxString& szRemoteFile /*= wxEmptyString*/) { wxFFileInputStream inStream(szFilePath); return Put(inStream, szRemoteFile); }
DrmInStream DcfContainer::getDecryptContent(uint8_t* decryptKey) const { DrmInStream inStream(this,decryptKey); return inStream; }
void PhraseDictionaryFuzzyMatch::InitializeForInput(InputType const& inputSentence) { char dirName[] = "/tmp/moses.XXXXXX"; char *temp = mkdtemp(dirName); CHECK(temp); string dirNameStr(dirName); string inFileName(dirNameStr + "/in"); ofstream inFile(inFileName.c_str()); for (size_t i = 1; i < inputSentence.GetSize() - 1; ++i) { inFile << inputSentence.GetWord(i); } inFile << endl; inFile.close(); long translationId = inputSentence.GetTranslationId(); string ptFileName = m_FuzzyMatchWrapper->Extract(translationId, dirNameStr); // populate with rules for this sentence PhraseDictionaryNodeMemory &rootNode = m_collection[translationId]; FormatType format = MosesFormat; // data from file InputFileStream inStream(ptFileName); // copied from class LoaderStandard PrintUserTime("Start loading fuzzy-match phrase model"); const StaticData &staticData = StaticData::Instance(); const std::string& factorDelimiter = staticData.GetFactorDelimiter(); string lineOrig; size_t count = 0; while(getline(inStream, lineOrig)) { const string *line; if (format == HieroFormat) { // reformat line UTIL_THROW(util::Exception, "Cannot be Hiero format"); //line = ReformatHieroRule(lineOrig); } else { // do nothing to format of line line = &lineOrig; } vector<string> tokens; vector<float> scoreVector; TokenizeMultiCharSeparator(tokens, *line , "|||" ); if (tokens.size() != 4 && tokens.size() != 5) { stringstream strme; strme << "Syntax error at " << ptFileName << ":" << count; UserMessage::Add(strme.str()); abort(); } const string &sourcePhraseString = tokens[0] , &targetPhraseString = tokens[1] , &scoreString = tokens[2] , &alignString = tokens[3]; bool isLHSEmpty = (sourcePhraseString.find_first_not_of(" \t", 0) == string::npos); if (isLHSEmpty && !staticData.IsWordDeletionEnabled()) { TRACE_ERR( ptFileName << ":" << count << ": pt entry contains empty target, skipping\n"); continue; } Tokenize<float>(scoreVector, scoreString); const size_t numScoreComponents = GetNumScoreComponents(); if (scoreVector.size() != numScoreComponents) { stringstream strme; strme << "Size of scoreVector != number (" << scoreVector.size() << "!=" << numScoreComponents << ") of score components on line " << count; UserMessage::Add(strme.str()); abort(); } CHECK(scoreVector.size() == numScoreComponents); // parse source & find pt node // constituent labels Word *sourceLHS; Word *targetLHS; // source Phrase sourcePhrase( 0); sourcePhrase.CreateFromString(Input, m_input, sourcePhraseString, factorDelimiter, &sourceLHS); // create target phrase obj TargetPhrase *targetPhrase = new TargetPhrase(); targetPhrase->CreateFromString(Output, m_output, targetPhraseString, factorDelimiter, &targetLHS); // rest of target phrase targetPhrase->SetAlignmentInfo(alignString); targetPhrase->SetTargetLHS(targetLHS); //targetPhrase->SetDebugOutput(string("New Format pt ") + line); // component score, for n-best output std::transform(scoreVector.begin(),scoreVector.end(),scoreVector.begin(),TransformScore); std::transform(scoreVector.begin(),scoreVector.end(),scoreVector.begin(),FloorScore); targetPhrase->GetScoreBreakdown().Assign(this, scoreVector); targetPhrase->Evaluate(sourcePhrase, GetFeaturesToApply()); TargetPhraseCollection &phraseColl = GetOrCreateTargetPhraseCollection(rootNode, sourcePhrase, *targetPhrase, sourceLHS); phraseColl.Add(targetPhrase); count++; if (format == HieroFormat) { // reformat line delete line; } else { // do nothing } } // sort and prune each target phrase collection SortAndPrune(rootNode); //removedirectoryrecursively(dirName); }
void InstConsoleWindow::OnGenReportClicked(wxCommandEvent& event) { wxString crashReportString = GetCrashReport(); const int id_pastebin = 1; const int id_file = 2; const int id_clipboard = 3; AdvancedMsgDialog::ButtonDefList btns; btns.push_back(AdvancedMsgDialog::ButtonDef(_("Send to Pastebin"), id_pastebin)); btns.push_back(AdvancedMsgDialog::ButtonDef(_("Save to File"), id_file)); btns.push_back(AdvancedMsgDialog::ButtonDef(_("Copy to Clipboard"), id_clipboard)); btns.push_back(AdvancedMsgDialog::ButtonDef(_("&Cancel"), wxID_CANCEL)); AdvancedMsgDialog msgDlg(this, _("A crash report has been generated. " "What would you like to do with it?"), btns, _("Crash Report")); crashReportIsOpen = true; msgDlg.CenterOnParent(); int response = msgDlg.ShowModal(); if (response == id_pastebin) // Pastebin { PastebinTask *task = new PastebinTask(crashReportString); TaskProgressDialog tDlg(this); if (tDlg.ShowModal(task)) { wxTextEntryDialog urlDialog(this, _("Your error report has been" " sent to the URL listed below."), _("Success"), task->GetPasteURL(), wxOK | wxCENTER); urlDialog.ShowModal(); } else { wxMessageBox(_("Failed to send the crash report to pastebin. " "Please check your internet connection."), _("Error")); } delete task; } else if (response == id_file) // Save to file { wxFileDialog saveReportDlg(this, _("Save Crash Report"), wxGetCwd(), wxDateTime::Now().Format("MultiMC_Report_%m-%d-%Y_%H-%M-%S.txt"), "*.txt", wxFD_SAVE | wxFD_OVERWRITE_PROMPT); if (saveReportDlg.ShowModal() != wxID_CANCEL) { wxFFileOutputStream outStream(saveReportDlg.GetFilename()); wxStringInputStream inStream(crashReportString); outStream.Write(inStream); } } else if (response == id_clipboard) { if (wxTheClipboard->Open()) { wxTheClipboard->SetData(new wxTextDataObject(crashReportString)); wxTheClipboard->Close(); } } crashReportIsOpen = false; }
MatrixFloat::MatrixFloat(const std::string& str) { std::istringstream inStream(str); operator>>(inStream,*this); return; }
static bool testSerialization(Bitstream::MetadataType metadataType) { QByteArray array; QDataStream outStream(&array, QIODevice::WriteOnly); Bitstream out(outStream, metadataType); SharedObjectPointer testObjectWrittenA = new TestSharedObjectA(randFloat(), TestSharedObjectA::SECOND_TEST_ENUM, TestSharedObjectA::TestFlags(TestSharedObjectA::FIRST_TEST_FLAG | TestSharedObjectA::THIRD_TEST_FLAG)); out << testObjectWrittenA; SharedObjectPointer testObjectWrittenB = new TestSharedObjectB(randFloat(), createRandomBytes(), TestSharedObjectB::THIRD_TEST_ENUM, TestSharedObjectB::SECOND_TEST_FLAG); out << testObjectWrittenB; TestMessageC messageWritten = createRandomMessageC(); out << QVariant::fromValue(messageWritten); QByteArray endWritten = "end"; out << endWritten; out.flush(); QDataStream inStream(array); Bitstream in(inStream, metadataType); in.addMetaObjectSubstitution("TestSharedObjectA", &TestSharedObjectB::staticMetaObject); in.addMetaObjectSubstitution("TestSharedObjectB", &TestSharedObjectA::staticMetaObject); in.addTypeSubstitution("TestMessageC", TestMessageA::Type); in.addTypeSubstitution("TestSharedObjectA::TestEnum", "TestSharedObjectB::TestEnum"); in.addTypeSubstitution("TestSharedObjectB::TestEnum", "TestSharedObjectA::TestEnum"); in.addTypeSubstitution("TestSharedObjectA::TestFlags", "TestSharedObjectB::TestFlags"); in.addTypeSubstitution("TestSharedObjectB::TestFlags", "TestSharedObjectA::TestFlags"); SharedObjectPointer testObjectReadA; in >> testObjectReadA; if (!testObjectReadA || testObjectReadA->metaObject() != &TestSharedObjectB::staticMetaObject) { qDebug() << "Wrong class for A" << testObjectReadA << metadataType; return true; } if (metadataType == Bitstream::FULL_METADATA && (static_cast<TestSharedObjectA*>(testObjectWrittenA.data())->getFoo() != static_cast<TestSharedObjectB*>(testObjectReadA.data())->getFoo() || static_cast<TestSharedObjectB*>(testObjectReadA.data())->getBaz() != TestSharedObjectB::SECOND_TEST_ENUM || static_cast<TestSharedObjectB*>(testObjectReadA.data())->getBong() != TestSharedObjectB::TestFlags(TestSharedObjectB::FIRST_TEST_FLAG | TestSharedObjectB::THIRD_TEST_FLAG))) { QDebug debug = qDebug() << "Failed to transfer shared field from A to B"; testObjectWrittenA->dump(debug); testObjectReadA->dump(debug); return true; } SharedObjectPointer testObjectReadB; in >> testObjectReadB; if (!testObjectReadB || testObjectReadB->metaObject() != &TestSharedObjectA::staticMetaObject) { qDebug() << "Wrong class for B" << testObjectReadB << metadataType; return true; } if (metadataType == Bitstream::FULL_METADATA && (static_cast<TestSharedObjectB*>(testObjectWrittenB.data())->getFoo() != static_cast<TestSharedObjectA*>(testObjectReadB.data())->getFoo() || static_cast<TestSharedObjectA*>(testObjectReadB.data())->getBaz() != TestSharedObjectA::THIRD_TEST_ENUM || static_cast<TestSharedObjectA*>(testObjectReadB.data())->getBong() != TestSharedObjectA::SECOND_TEST_FLAG)) { QDebug debug = qDebug() << "Failed to transfer shared field from B to A"; testObjectWrittenB->dump(debug); testObjectReadB->dump(debug); return true; } QVariant messageRead; in >> messageRead; if (!messageRead.isValid() || messageRead.userType() != TestMessageA::Type) { qDebug() << "Wrong type for message" << messageRead; return true; } if (metadataType == Bitstream::FULL_METADATA && messageWritten.foo != messageRead.value<TestMessageA>().foo) { QDebug debug = qDebug() << "Failed to transfer shared field between messages" << messageWritten.foo << messageRead.value<TestMessageA>().foo; return true; } QByteArray endRead; in >> endRead; if (endWritten != endRead) { qDebug() << "End tag mismatch." << endRead; return true; } return false; }
//copies downloaded versions file into internal data structure; void B9UpdateManager::CopyInRemoteEntries() { QString entryPlatform; remoteEntries.clear(); currentReply->setTextModeEnabled(true); QTextStream inStream(currentReply); B9UpdateEntry entry; while(!inStream.atEnd()) { inStream >> entry.localLocationTag; if(entry.localLocationTag.startsWith("//")) { inStream.readLine(); inStream.skipWhiteSpace(); continue; } entry.fileName = StreamInTextQuotes(inStream); inStream >> entry.version; inStream >> entryPlatform; if(entryPlatform == "ANY") { entry.OSDir = "COMMON/"; remoteEntries.push_back(entry); } else { #ifdef Q_OS_WIN if((entryPlatform == "WIN")) { entry.OSDir = "WINDOWS/"; #endif #ifdef Q_OS_MAC if((entryPlatform == "MAC")) { entry.OSDir = "MAC/"; #endif #ifdef Q_OS_LINUX if((entryPlatform == "LINUX")) { entry.OSDir = "LINUX/"; #endif remoteEntries.push_back(entry); } } inStream.skipWhiteSpace(); } qDebug() << "UpdateManager: " << remoteEntries.size() << " Remote Entrees Loaded"; } void B9UpdateManager::CopyInLocalEntries() { localEntries.clear(); QFile localvfile(CROSS_OS_GetDirectoryFromLocationTag("APPLICATION_DIR") + "/FileVersions.txt"); localvfile.open(QIODevice::ReadOnly); QTextStream stream(&localvfile); while(!stream.atEnd()) { B9UpdateEntry newEntry; stream >> newEntry.localLocationTag; newEntry.fileName = StreamInTextQuotes(stream); stream >> newEntry.version; //as we read in from local fileversions.txt, it is possible that the local file //is missing even though it is listed in the text file, //to counter this, we need to actuall check if the file exists. // and set the version to a really low number so it has to be updated later on. if(!QFile::exists(CROSS_OS_GetDirectoryFromLocationTag(newEntry.localLocationTag) + "/" + newEntry.fileName)) newEntry.version = -1; localEntries.push_back(newEntry); stream.skipWhiteSpace();//eat up new line } localvfile.close(); qDebug() << "UpdateManager: " << localEntries.size() << " Local Entrees Loaded"; } //compare remote entries and local entries and fill a updateEntries list //so we know to whole list of files to be updates void B9UpdateManager::CalculateUpdateEntries() { int r; int l; bool dne; updateEntries.clear(); for(r = 0; r < remoteEntries.size(); r++) { dne = true; for(l = 0; l < localEntries.size(); l++) { if(localEntries[l].fileName == remoteEntries[r].fileName) { dne = false; if(NeedsUpdated(localEntries[l],remoteEntries[r])) { updateEntries.push_back(remoteEntries[r]); } } } if(dne == true)//if there isnt a file match local we still to update { updateEntries.push_back(remoteEntries[r]); } } }
void Boonas::doClip(QString infile, QString normalx, QString normaly, QString normalz, QString px, QString py, QString pz) { // set up to impliment an outfile but not needed yet // set up base variables Point planeP(px.toFloat(), py.toFloat(), pz.toFloat()); QString outfile = "temporary"; Vector planeN(normalx.toFloat(), normaly.toFloat(), normalz.toFloat()); float x, y, z; Point* thisPoint = 0; Point* lastPoint = 0; Point* firstPoint = 0; float lastD = 0; float thisD = 0; float firstD = 0; bool firstObjectIn = false; bool firstObjectOut = false; bool firstTimeThisRun = true; // set up test bariables bool again = true; bool lastPointOut = false; bool thisPointOut = false; bool lastPointOn = false; bool thisPointOn = false; orig -> reset(); // orig is at start // set up file to write in poly's to infile.append(".poly"); QFile* theInDestination; theInDestination = new QFile(infile); theInDestination -> remove(); theInDestination -> open(QIODevice::ReadWrite | QIODevice::Text); QTextStream inStream( theInDestination ); // set up file to write out poly's to outfile.append(".poly"); QFile* theOutDestination; theOutDestination = new QFile(outfile); theOutDestination -> remove(); theOutDestination -> open(QIODevice::ReadWrite | QIODevice::Text); QTextStream outStream( theOutDestination ); // run through the list do // do this loop while ther is more in orig, one more will be left after { cursor = orig -> getCurrent(); // cursor is current cursor -> reset(); //change color respectively for each object x = cursor -> getX(); y = cursor -> getY(); z = cursor -> getZ(); if(colorValue != 0) { delete colorValue; colorValue = 0; } colorValue = new Point(x, y, z); cursor -> advance(); //inStream << "newObject" << endl; //outStream << "newObject" << endl; lastPoint = 0; thisPoint = 0; firstObjectIn = false; firstObjectOut = false; firstTimeThisRun = true; if(!(orig -> isNotLast())) { again = false; } do { x = cursor -> getX(); // get point y = cursor -> getY(); z = cursor -> getZ(); if(thisPoint != 0)// if curpoint is not null, make it so { delete thisPoint; } thisPoint = new Point(x, y, z);// create new point if(firstTimeThisRun) { firstTimeThisRun = false; firstPoint = new Point(x, y, z); firstD = dot((*thisPoint - planeP), planeN); } thisD = dot((*thisPoint - planeP), planeN); if(dot((*thisPoint - planeP), planeN) > 0)// in { thisPointOut = false; thisPointOn = false; } else if(dot((*thisPoint - planeP), planeN) < 0)// out { thisPointOut = true; thisPointOn = false; } else// on { thisPointOn = true; } if(lastPoint == 0) // if there is not a last point { lastPoint = new Point(thisPoint -> x(), thisPoint -> y(), thisPoint -> z()); lastPointOut = thisPointOut; lastPointOn = thisPointOn; lastD = thisD; } else { // do test to see if last was out and this was in. and delete whats necisarry if(lastPointOn) // last point was on add it { if(firstObjectIn == false) { inStream << "newObject" << endl; inStream << colorValue -> x() << " " << colorValue -> y() << " " << colorValue -> z() << " 1" << endl; firstObjectIn = true; } if(firstObjectOut == false) { outStream << "newObject" << endl; outStream << colorValue -> x() << " " << colorValue -> y() << " " << colorValue -> z() << " 1" << endl; firstObjectOut = true; } outStream << lastPoint -> x() << " " << lastPoint -> y() << " " << lastPoint -> z() << " " << 1 << endl; inStream << lastPoint -> x() << " " << lastPoint -> y() << " " << lastPoint -> z() << " " << 1 << endl; } else if(lastPointOut && thisPointOut) // only add to outstream { if(firstObjectOut == false) { outStream << "newObject" << endl; // put out color vector outStream << colorValue -> x() << " " << colorValue -> y() << " "<< colorValue -> z() << " 1" << endl; firstObjectOut = true; } outStream << lastPoint -> x() << " " << lastPoint -> y() << " " << lastPoint -> z() << " " << 1 << endl; } else if((lastPointOut == false) && (thisPointOut == false)) // only add to instream { if(firstObjectIn == false) { inStream << "newObject" << endl; // put out color vector inStream << colorValue -> x() << " " << colorValue -> y() << " " << colorValue -> z() << " 1" << endl; firstObjectIn = true; } inStream << lastPoint -> x() << " " << lastPoint -> y() << " " << lastPoint -> z() << " " << 1 << endl; } else if((lastPointOut == false) && thisPointOut) // add last point to in, and the center to in and out { if(firstObjectIn == false) { inStream << "newObject" << endl; // put out color vector inStream << colorValue -> x() << " " << colorValue -> y() << " " << colorValue -> z() << " 1" << endl; firstObjectIn = true; } if(firstObjectOut == false) { outStream << "newObject" << endl; // put out color vector outStream << colorValue -> x() << " " << colorValue -> y() << " " << colorValue -> z() << " 1" << endl; firstObjectOut = true; } inStream << lastPoint -> x() << " " << lastPoint -> y() << " " << lastPoint -> z() << " " << 1 << endl; *lastPoint = getCenter(lastPoint, thisPoint, lastD, thisD); //returns center inStream << lastPoint -> x() << " " << lastPoint -> y() << " " << lastPoint -> z() << " " << 1 << endl; outStream << lastPoint -> x()<< " " << lastPoint -> y() << " " << lastPoint -> z() << " " << 1 << endl; } else // lastpoint out, this point in, add center to both, advance { if(firstObjectIn == false) { inStream << "newObject" << endl; // put out color vector inStream << colorValue -> x() << " " << colorValue -> y() << " " << colorValue -> z() << " 1" << endl; firstObjectIn = true; } if(firstObjectOut == false) { outStream << "newObject" << endl; // put out color vector outStream << colorValue -> x() << " " << colorValue -> y() << " " << colorValue -> z() << " 1" << endl; firstObjectOut = true; } *lastPoint = getCenter(lastPoint, thisPoint, lastD, thisD); //returns center inStream << lastPoint -> x() << " " << lastPoint -> y() << " " << lastPoint -> z() << " " << 1 << endl; outStream << lastPoint -> x() << " " << lastPoint -> y() << " " << lastPoint -> z() << " " << 1 << endl; } // remove it delete lastPoint; // transfer this point to last, get ready to run again lastPoint = new Point(thisPoint -> x(), thisPoint -> y(), thisPoint -> z()); lastPointOut = thisPointOut; lastPointOn = thisPointOn; lastD = thisD; } cursor -> advance(); } while(cursor -> hasNext()); // run through the points and mult! // this is the last point in this object x = cursor -> getX(); // get point y = cursor -> getY(); z = cursor -> getZ(); if(thisPoint != 0) { delete thisPoint; } thisPoint = new Point(x, y, z);// create new point thisD = dot((*thisPoint - planeP), planeN); if(dot((*thisPoint - planeP), planeN) > 0)// in { thisPointOut = false; thisPointOn = false; } else if(dot((*thisPoint - planeP), planeN) < 0)// out { thisPointOut = true; thisPointOn = false; } else// on { thisPointOn = true; } if(lastPoint != 0) // there was a last point { if(lastPointOn) // last point was on add it { if(firstObjectIn == false) { inStream << "newObject" << endl; // put out color vector inStream << colorValue -> x() << " " << colorValue -> y() << " " << colorValue -> z() << " 1" << endl; firstObjectIn = true; } if(firstObjectOut == false) { outStream << "newObject" << endl; // put out color vector outStream << colorValue -> x() << " " << colorValue -> y() << " " << colorValue -> z() << " 1" << endl; firstObjectOut = true; } outStream << lastPoint -> x() << " " << lastPoint -> y() << " " << lastPoint -> z() << " " << 1 << endl; inStream << lastPoint -> x() << " " << lastPoint -> y() << " " << lastPoint -> z() << " " << 1 << endl; } else if(lastPointOut && thisPointOut) // only add to outstream { if(firstObjectOut == false) { outStream << "newObject" << endl; // put out color vector outStream << colorValue -> x() << " " << colorValue -> y() << " " << colorValue -> z() << " 1" << endl; firstObjectOut = true; } outStream << lastPoint -> x() << " " << lastPoint -> y() << " " << lastPoint -> z() << " " << 1 << endl; } else if((lastPointOut == false) && (thisPointOut == false)) // only add to instream { if(firstObjectIn == false) { inStream << "newObject" << endl; // put out color vector inStream << colorValue -> x() << " " << colorValue -> y() << " " << colorValue -> z() << " 1" << endl; firstObjectIn = true; } inStream << lastPoint -> x() << " " << lastPoint -> y() << " " << lastPoint -> z() << " " << 1 << endl; } else if((lastPointOut == false) && thisPointOut) // add last point to in, and the center to in and out { if(firstObjectIn == false) { inStream << "newObject" << endl; // put out color vector inStream << colorValue -> x() << " " << colorValue -> y() << " " << colorValue -> z() << " 1" << endl; firstObjectIn = true; } if(firstObjectOut == false) { outStream << "newObject" << endl; // put out color vector outStream << colorValue -> x() << " " << colorValue -> y() << " " << colorValue -> z() << " 1" << endl; firstObjectOut = true; } inStream << lastPoint -> x() << " " << lastPoint -> y() << " " << lastPoint -> z() << " " << 1 << endl; *lastPoint = getCenter(lastPoint, thisPoint, lastD, thisD); //returns center inStream << lastPoint -> x() << " " << lastPoint -> y() << " " << lastPoint -> z() << " " << 1 << endl; outStream << lastPoint -> x() << " " << lastPoint -> y() << " " << lastPoint -> z() << " " << 1 << endl; } else // lastpoint out, this point in, add center to both, advance { if(firstObjectIn == false) { inStream << "newObject" << endl; // put out color vector inStream << colorValue -> x() << " " << colorValue -> y() << " " << colorValue -> z() << " 1" << endl; firstObjectIn = true; } if(firstObjectOut == false) { outStream << "newObject" << endl; // put out color vector outStream << colorValue -> x() << " " << colorValue -> y() << " " << colorValue -> z() << " 1" << endl; firstObjectOut = true; } *lastPoint = getCenter(lastPoint, thisPoint, lastD, thisD); //returns center inStream << lastPoint -> x() << " " << lastPoint -> y() << " " << lastPoint -> z() << " " << 1 << endl; outStream << lastPoint -> x() << " " << lastPoint -> y() << " " << lastPoint -> z() << " " << 1 << endl; } // remove it delete lastPoint; } thisD = dot((*thisPoint - planeP), planeN); // do the test for the last point! if(dot((*thisPoint - planeP), planeN) > 0)// in { if(firstObjectIn == false) { inStream << "newObject" << endl; // put out color vector inStream << colorValue -> x() << " " << colorValue -> y() << " " << colorValue -> z() << " 1" << endl; firstObjectIn = true; } inStream << thisPoint -> x() << " " << thisPoint -> y() << " " << thisPoint -> z() << " " << 1 << endl; } else if(dot((*thisPoint - planeP), planeN) < 0)// out { if(firstObjectOut == false) { outStream << "newObject" << endl; // put out color vector outStream << colorValue -> x() << " " << colorValue -> y() << " " << colorValue -> z() << " 1" << endl; firstObjectOut = true; } outStream << thisPoint -> x() << " " << thisPoint -> y() << " " << thisPoint -> z() << " " << 1 << endl; } else// on { if(firstObjectIn == false) { inStream << "newObject" << endl; // put out color vector inStream << colorValue -> x() << " " << colorValue -> y() << " " << colorValue -> z() << " 1" << endl; firstObjectIn = true; } if(firstObjectOut == false) { outStream << "newObject" << endl; // put out color vector outStream << colorValue -> x() << " " << colorValue -> y() << " " << colorValue -> z() << " 1" << endl; firstObjectOut = true; } inStream << thisPoint -> x() << " " << thisPoint -> y() << " " << thisPoint -> z() << " " << 1 << endl; outStream << thisPoint -> x() << " " << thisPoint -> y() << " " << thisPoint -> z() << " " << 1 << endl; } //special compare for case where first point was out, and last point was in, or first point was in and last is out, take care of looping if(firstPoint != 0)// if this isn't a one point set, should never happen, but speed isn't an issue and can't be too sure { // substitute values so code can be copied and pasted from above! lastPoint = thisPoint; lastD = thisD; thisPoint = firstPoint; thisD = firstD; // right now lastpoint is the last point, and this point is the first point of the set // we are ready to do a normal case // find out if the first point was in or out if(dot((*thisPoint - planeP), planeN) > 0)// in { thisPointOut = false; thisPointOn = false; } else if(dot((*thisPoint - planeP), planeN) < 0)// out { thisPointOut = true; thisPointOn = false; } else// on { thisPointOn = true; } //find out if the last point was in or out if(dot((*lastPoint - planeP), planeN) > 0)// in { lastPointOut = false; lastPointOn = false; } else if(dot((*lastPoint - planeP), planeN) < 0)// out { lastPointOut = true; lastPointOn = false; } else// on { lastPointOn = true; } //put midpoint out to files accordingly, remember, do NOT add last point twice! if((lastPointOut == false) && thisPointOut) // add the center to in and out { if(firstObjectIn == false) { inStream << "newObject" << endl; // put out color vector inStream << colorValue -> x() << " " << colorValue -> y() << " " << colorValue -> z() << " 1" << endl; firstObjectIn = true; } if(firstObjectOut == false) { outStream << "newObject" << endl; // put out color vector outStream << colorValue -> x() << " " << colorValue -> y() << " " << colorValue -> z() << " 1" << endl; firstObjectOut = true; } *lastPoint = getCenter(lastPoint, thisPoint, lastD, thisD); //returns center inStream << lastPoint -> x() << " " << lastPoint -> y() << " " << lastPoint -> z() << " " << 1 << endl; outStream << lastPoint -> x() << " " << lastPoint -> y() << " " << lastPoint -> z() << " " << 1 << endl; } else if(lastPointOut && (thisPointOut == false)) // lastpoint out, this point in, add center to both, advance { if(firstObjectIn == false) { inStream << "newObject" << endl; // put out color vector inStream << colorValue -> x() << " " << colorValue -> y() << " " << colorValue -> z() << " 1" << endl; firstObjectIn = true; } if(firstObjectOut == false) { outStream << "newObject" << endl; // put out color vector outStream << colorValue -> x() << " " << colorValue -> y() << " " << colorValue -> z() << " 1" << endl; firstObjectOut = true; } *lastPoint = getCenter(lastPoint, thisPoint, lastD, thisD); //returns center inStream << lastPoint -> x() << " " << lastPoint -> y() << " " << lastPoint -> z() << " " << 1 << endl; outStream << lastPoint -> x() << " " << lastPoint -> y() << " " << lastPoint -> z() << " " << 1 << endl; } } cursor -> reset(); orig -> advance(); // advance what were working with } while(again); orig -> reset(); theInDestination -> close(); theOutDestination -> close(); theOutDestination -> remove(); // remove it untill we use it, has a bug, but not needed so no need to fix return; }