int main() { char* filepath = new char[200]; fileHandle(&filepath); ObjGeo objgeo; storeGeo(filepath, objgeo); float surfaceareavalue = 0; surfaceareavalue = surfaceAreaCal(objgeo); std::cout << "\n====================\nsurface area = " << surfaceareavalue << "\n===================="<< std::endl; freeGeo(objgeo); }
bool OptimizationController::IsOptimizationDisabledForAssembly(const wxString& assemblyPath) { wxString iniFilePath = GetIniPathFromAssemblyPath(assemblyPath); unique_handle fileHandle(CreateFile(iniFilePath, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0)); if (fileHandle.get() == INVALID_HANDLE_VALUE) return false; LARGE_INTEGER fileSize; if (GetFileSizeEx(fileHandle.get(), &fileSize)) { return fileSize.QuadPart == IniFileSize; } return false; }
void g2m::interpret_file() { lineVector.clear(); nanotimer timer; timer.start(); gcode_lines=0; if ( file.endsWith(".ngc") ) { // push g-code lines to ui: QFile fileHandle( file ); QString gline; if ( fileHandle.open( QIODevice::ReadOnly | QIODevice::Text) ) { // file opened successfully QTextStream t( &fileHandle ); // use a text stream // until end of file... while ( !t.atEnd() ) { // read and parse the command line gline = t.readLine(); // line of text excluding '\n' emit gcodeLineMessage(gline); gcode_lines++; } fileHandle.close(); } emit debugMessage( tr("g2m: interpreting %1").arg(file) ); interpret(); // reads from file } else if (file.endsWith(".canon")) { //just process each line if (!chooseToolTable()) { infoMsg("Can't find tool table. Aborting."); return; } std::ifstream inFile(file.toAscii()); std::string sLine; while(std::getline(inFile, sLine)) { if (sLine.length() > 1) { //helps to prevent segfault in canonLine::cmdMatch() processCanonLine(sLine); // requires no interpret() } } } else { emit debugMessage( tr("File name must end with .ngc or .canon!") ); return; } double e = timer.getElapsedS(); emit debugMessage( tr("g2m: Total time to process that file: ") + timer.humanreadable(e) ) ; //std::cout << "Total time to process that file: " << timer.humanreadable(e).toStdString() << std::endl; }
int main() { string WORKDIR; fileHandle(WORKDIR); std::ifstream objFileIn; //objFileIn.open(WORKDIR, std::ios::in); NameRefvol namevol; storeNameRefvol(WORKDIR , namevol); NameRefvolEdit(namevol); deformFunction(WORKDIR, namevol); return 1; }
bool OptimizationController::DisableOptimization() { //wxFile iniFile(this->iniPath, wxFile::OpenMode::write); unique_handle fileHandle(CreateFile(iniPath, GENERIC_WRITE, 0, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0)); if (*fileHandle == INVALID_HANDLE_VALUE) return false; DWORD written; wxScopedCharTypeBuffer<char> anciiString = IniFileContent.ToAscii(); if (WriteFile(fileHandle.get(), anciiString.data(), anciiString.length(), &written, nullptr)) { return true; } return false; }
CAudioContainerLookupTableSA::CAudioContainerLookupTableSA( const SString& strPath ) { std::ifstream fileHandle ( FromUTF8( strPath ), std::ios::binary ); if ( !fileHandle ) return; while (true) { SAudioLookupEntrySA* entry = new SAudioLookupEntrySA; if ( !fileHandle.read ( reinterpret_cast<char*> ( entry ), sizeof ( SAudioLookupEntrySA ) ) ) break; m_Entries[entry->index].push_back ( entry ); } fileHandle.close (); }
std::string FileUtils::read_file(const std::string &fileName) { std::string line; std::string file_contents; std::ifstream fileHandle (fileName.c_str()); if (fileHandle.is_open()) { while ( getline (fileHandle,line) ) { file_contents += line; file_contents.push_back('\n'); } fileHandle.close(); } else { std::cout<<"There was an error loading the file "<<fileName<<std::endl; } return file_contents; }
bool DkUtils::moveToTrash(const QString& filePath) { QFileInfo fileInfo(filePath); if (!fileInfo.exists()) { qDebug() << "Sorry, I cannot delete a non-existing file: " << filePath; return false; } // code is based on:http://stackoverflow.com/questions/17964439/move-files-to-trash-recycle-bin-in-qt #ifdef Q_OS_WIN std::wstring winPath = (fileInfo.isSymLink()) ? qStringToStdWString(fileInfo.symLinkTarget()) : qStringToStdWString(filePath); winPath.append(1, L'\0'); // path string must be double nul-terminated SHFILEOPSTRUCTW shfos = {}; shfos.hwnd = nullptr; // handle to window that will own generated windows, if applicable shfos.wFunc = FO_DELETE; shfos.pFrom = winPath.c_str(); shfos.pTo = nullptr; // not used for deletion operations shfos.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_SILENT; // use the recycle bin const int retVal = SHFileOperationW(&shfos); return retVal == 0; // true if no error code //#elif Q_OS_LINUX // bool TrashInitialized = false; // QString TrashPath; // QString TrashPathInfo; // QString TrashPathFiles; // // if( !TrashInitialized ) { // QStringList paths; // const char* xdg_data_home = getenv( "XDG_DATA_HOME" ); // if( xdg_data_home ){ // qDebug() << "XDG_DATA_HOME not yet tested"; // QString xdgTrash( xdg_data_home ); // paths.append( xdgTrash + "/Trash" ); // } // QString home = QStandardPaths::writableLocation( QStandardPaths::HomeLocation ); // paths.append( home + "/.local/share/Trash" ); // paths.append( home + "/.trash" ); // foreach( QString path, paths ){ // if( TrashPath.isEmpty() ){ // QDir dir( path ); // if( dir.exists() ){ // TrashPath = path; // } // } // } // if (TrashPath.isEmpty()) // return false; // TrashPathInfo = TrashPath + "/info"; // TrashPathFiles = TrashPath + "/files"; // if (!QDir(TrashPathInfo).exists() || !QDir(TrashPathFiles).exists()) // return false; // TrashInitialized = true; // } // // QString info; // info += "[Trash Info]\nPath="; // info += filePath; // info += "\nDeletionDate="; // info += QDateTime::currentDateTime().toString("yyyy-MM-ddThh:mm:ss.zzzZ"); // info += "\n"; // QString trashname = fileInfo.fileName(); // QString infopath = TrashPathInfo + "/" + trashname + ".trashinfo"; // QString trashPath = TrashPathFiles + "/" + trashname; // int nr = 1; // while( QFileInfo( infopath ).exists() || QFileInfo( trashPath ).exists() ){ // nr++; // trashname = fileInfo.baseName() + "." + QString::number( nr ); // if( !fileInfo.completeSuffix().isEmpty() ){ // trashname += QString( "." ) + fileInfo.completeSuffix(); // } // infopath = TrashPathInfo + "/" + trashname + ".trashinfo"; // trashPath = TrashPathFiles + "/" + trashname; // } // QDir dir; // if( !dir.rename( filePath, trashPath )) { // return false; // } // File infofile; // infofile.createUtf8( infopath, info ); // return true; #else QFile fileHandle(filePath); return fileHandle.remove(); #endif return false; // should never be hit }
khPresenceMask::khPresenceMask(const std::string &filename) : numLevels(0), beginLevel(MaxFusionLevel), // opposites ends so we can endLevel(0) { // load the real values uint64 fileSize; time_t mtime; if (!khGetFileInfo(filename, fileSize, mtime)) { throw khErrnoException( kh::tr("Unable to get file size for %1").arg(filename)); } // open the file, read & verify the header khReadFileCloser fileHandle(::open(filename.c_str(), O_RDONLY)); if (fileHandle.fd() < 0) { throw khErrnoException(kh::tr("Unable to open %1").arg(filename)); } PresenceHeader header; if (!khReadAll(fileHandle.fd(), &header, sizeof(header))) { throw khErrnoException(kh::tr("Unable to read header %1"). arg(filename)); } header.LittleEndianToHost(); if (memcmp(header.magic, PresenceHeader::themagic, sizeof(header.magic)) != 0) { throw khException(kh::tr("Corrupted header (magic) %1"). arg(filename)); } if (header.presenceFormatVersion == 1) { // nothing to do here } else { throw khException(kh::tr ("Unsupported format version (%1) for %2"). arg(header.presenceFormatVersion).arg(filename)); } #if 0 printf("presenceFormatVersion = %d\n", header.presenceFormatVersion); printf("totalFileSize = %u\n", header.totalFileSize); printf("numLevels = %u\n", header.numLevels); #endif // some sanity checks if (header.totalFileSize != fileSize) { throw khException(kh::tr("Corrupted header (file size) %1"). arg(filename)); } if (header.numLevels > NumFusionLevels) { throw khException(kh::tr("Corrupted header (num levels) %1"). arg(filename)); } // set my member now that I know what it shold be numLevels = header.numLevels; // mmap the entire index uchar *filebuf = static_cast<uchar*>(mmap(0, header.totalFileSize, PROT_READ, MAP_PRIVATE, fileHandle.fd(), 0)); if (filebuf == MAP_FAILED) { throw khErrnoException(kh::tr("Unable to mmap %1").arg(filename)); } khMunmapGuard munmapGuard(filebuf, header.totalFileSize); PresenceLevelRecord *recs = reinterpret_cast<PresenceLevelRecord*>(filebuf + sizeof(PresenceHeader)); for (uint i = 0; i < header.numLevels; ++i) { PresenceLevelRecord rec = recs[i]; rec.LittleEndianToHost(); #if 0 printf(" ----- level %d -----\n", rec.levelNum); printf(" presenceBufferOffset = %u\n", rec.presenceBufferOffset); printf(" presenceBufferSize = %u\n", rec.presenceBufferSize); printf(" startRow = %u\n", rec.startRow); printf(" startCol = %u\n", rec.startCol); printf(" numRows = %u\n", rec.numRows); printf(" numCols = %u\n", rec.numCols); #endif // sanity check the index (in case it got corrupted) if (rec.levelNum >= NumFusionLevels) { throw khException (kh::tr("Corrupted level header (levelNum) %1: level %2"). arg(filename).arg(rec.levelNum)); } if (rec.presenceBufferSize != khLevelPresenceMask::CalcBufferSize(rec.numRows, rec.numCols)) { throw khException (kh::tr("Corrupted level header (size) %1: level %2"). arg(filename).arg(rec.levelNum)); } if (rec.presenceBufferOffset + rec.presenceBufferSize > header.totalFileSize) { throw khException (kh::tr("Corrupted level header (offset) %1: level %2"). arg(filename).arg(rec.levelNum)); } levels[rec.levelNum] = TransferOwnership( new khLevelPresenceMask (rec.levelNum, khExtents<uint32>(RowColOrder, rec.startRow, rec.startRow + rec.numRows, rec.startCol, rec.startCol + rec.numCols), filebuf + rec.presenceBufferOffset)); if (rec.levelNum >= endLevel) endLevel = rec.levelNum+1; if (rec.levelNum < beginLevel) beginLevel = rec.levelNum; } if (numLevels != endLevel - beginLevel) { throw khException (kh::tr("Corrupted header (min/max/num) %1"). arg(filename)); } // munmapGuard's destructor will call munmap // fileHandle's destructor will take care of closing the file }
// ============================================== // // Load a mesh material from a file t_error ResourceManager::LoadMeshMaterial (const char* filename, Mesh* mesh) { // load the mesh material file ifstream fileHandle( filename ); if ( !fileHandle.is_open() ) { Log( str( format( "Error opening material file (%1%)" ) % filename ), LOG_ERROR ); throw BadFileException(filename); } // parse mtl file string buffer; while ( fileHandle.good() ) { getline( fileHandle, buffer ); if ( buffer.empty() ) continue; // setup tokenizer CharSeparator tokenSeparator( " \t" ); CharTokenizer tokens( buffer, tokenSeparator ); CharTokenizer::iterator token = tokens.begin(); CharTokenizer::iterator lastToken = tokens.end(); // Log ( str( format( "buffer: %1%" ) % (buffer) ) ); // Log ( str( format( "token: %1%" ) % (*token) ) ); if ( (*token)[0] == '#' ) { continue; } // comment else if ( (*token) == "Ka" ) { // ambient colour float r = tokenToFloat(++token); float g = tokenToFloat(++token); float b = tokenToFloat(++token); Log( str( format( "Ka: %1%,%2%,%3%" ) % r % g % b ), LOG_DEBUG ); mesh->color_ambient = fTriple( r, g, b ); } else if ( (*token) == "Kd" ) { // diffuse colour float r = tokenToFloat(++token); float g = tokenToFloat(++token); float b = tokenToFloat(++token); Log( str( format( "Kd: %1%,%2%,%3%" ) % r % g % b ), LOG_DEBUG ); mesh->color_diffuse = fTriple( r, g, b ); } else if ( (*token) == "Ks" ) { // specular colour float r = tokenToFloat(++token); float g = tokenToFloat(++token); float b = tokenToFloat(++token); Log( str( format( "Ks: %1%,%2%,%3%" ) % r % g % b ), LOG_DEBUG ); mesh->color_specular = fTriple( r, g, b ); } else if ( (*token) == "map_Kd" ) { // texture // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // TODO: load texture in resource mgr; use a lookup table to find the gl id and point to that string texFilename = *(++token); mesh->loadTexture( texFilename.c_str(), MeshRenderData::MESH_RENDER_TEXTURE ); // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! } else if ( (*token) == "bump" ) { // bumpmap string texFilename = *(++token); mesh->loadTexture( texFilename.c_str(), MeshRenderData::MESH_RENDER_TEXBUMP ); } else { Log ( str( format( "Unknown line: %1%" ) % buffer ) ); } } fileHandle.close(); return NO_ERROR; }
// ============================================== // // Load a mesh from a file Entity* ResourceManager::LoadMesh (RenderGroup* renderer, const char* filename) { // load the mesh file ifstream fileHandle( filename ); if ( !fileHandle.is_open() ) { Log( str( format( "Error opening mesh file (%1%)" ) % filename ), LOG_ERROR ); throw BadFileException(filename); } // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // TODO: store mesh elsewhere Mesh* mesh; if (renderer) { mesh = new Mesh(true); mesh->renderData->gl = renderer->program->programid; glGenTextures(2, mesh->renderData->textures); } else { mesh = new Mesh(false); } // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // parse obj file string buffer; while ( fileHandle.good() ) { getline( fileHandle, buffer ); if ( buffer.empty() ) continue; // setup tokenizer CharSeparator tokenSeparator( " \t" ); CharTokenizer tokens( buffer, tokenSeparator ); CharTokenizer::iterator token = tokens.begin(); CharTokenizer::iterator lastToken = tokens.end(); // Log ( str( format( "buffer: %1%" ) % (buffer) ) ); // Log ( str( format( "token: %1%" ) % (*token) ) ); if ( (*token)[0] == '#' ) { continue; } // comment else if ( (*token) == "v" ) { // vertex float x = tokenToFloat(++token); float y = tokenToFloat(++token); float z = tokenToFloat(++token); mesh->addVertex( x, y, z ); } else if ( (*token) == "vn" ) { // vertex normal float x = tokenToFloat(++token); float y = tokenToFloat(++token); float z = tokenToFloat(++token); mesh->addVertexNormal( x, y, z ); } else if ( *token == "vt" ) { // vertex texcoord float s = tokenToFloat(++token); float t = tokenToFloat(++token); mesh->addVertexTex( s, t ); } else if ( *token == "f" ) { // face /* each face contains 3 or more vertices * * Vertex only format is: v1 v2 v3 ... * Vertex/Texture format: v1/vt1 v2/vt2 v3/vt3 ... * Vertex/Tex/Norm format: v1/vt1/vn1 v2/vt2/vn2 v3/vt3/vn3 ... * Vertex/Normal format: v1//vn1 v2//vn2 v3//vn3 ... * **/ (++token); ushort point_index = 0; // this helps with auto-face texcoord deciding (in case no UV mapping is specified) short v_index, n_index, t_index; do { // setup sub-tokenizer (vert, norm, texcoord) v_index = -1, n_index = -1, t_index = -1; // NOTE: -1 means nonexistent; do NOT use ushort since 0 is a legal index CharTokenizer v_indices( (*token), CharSeparator("/ ","",boost::keep_empty_tokens) ); CharTokenizer::iterator index = v_indices.begin(); for (uchar tokenIndex=0; (index) != v_indices.end() && tokenIndex <= 2 ; ++tokenIndex, ++index ) { if ( (*index).empty() ) continue; switch (tokenIndex) { case 0: // Vertex Index // Log( str( format( "Face Index: %1%" ) % tokenToUShort( index ) ) ); v_index = tokenToUShort( index ) - 1; break; case 1: // Texcoord Index // Log( str( format( "Tex Index: %1%" ) % tokenToUShort( index ) ) ); t_index = tokenToUShort( index ) -1; break; case 2: // Norm Index // Log( str( format( "Norm Index: %1%" ) % tokenToUShort( index ) ) ); n_index = tokenToUShort( index ) -1; break; } } // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // if no texcoord specified then create one // TODO: this assumes we're running quads, provide a NON-HARDCODED solution if ( t_index == -1 ) { if ( mesh->texcoords.empty() ) { float top = 0.0f, bottom = 1.0f; // TODO: test st coords for correct top/bottom mesh->texcoords.push_back( 1.0f ); // bottom right mesh->texcoords.push_back( bottom ); mesh->texcoords.push_back( 1.0f ); // top right mesh->texcoords.push_back( top ); mesh->texcoords.push_back( 0.0f ); // top left mesh->texcoords.push_back( top ); mesh->texcoords.push_back( 0.0f ); // bottom left mesh->texcoords.push_back( bottom ); } t_index = point_index % 4; } // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! mesh->pushVertex( v_index, t_index, n_index ); point_index++; } while( (++token) != tokens.end() ); if ( point_index == 3 ) { // tri-face; since we're expecting quads just overlap the 2 end points mesh->pushVertex( v_index, t_index, n_index ); } } else if ( *token == "mtllib" ) { // material file // TODO: test that this will work on Windows (\\ path end could return only \ which may break the mtl filename) ushort path_ending = string( filename ).find_last_of( "/\\" ) + 1; // works for /home/user/.. or c:\\programfiles\\.. string mtlFilename = string( filename ).substr( 0, path_ending ).append( *(++token) ); // load material file if ( LoadMeshMaterial( mtlFilename.c_str(), mesh ) & ERROR ) { Log( str( format( "Error opening material file (%1%)" ) % mtlFilename ), LOG_ERROR ); throw BadFileException(mtlFilename); } Log( str( format( "Loaded material file (%1%)" ) % mtlFilename ), LOG_INFO ); } else { Log ( str( format( "Unknown line: %1%" ) % buffer ) ); } } fileHandle.close(); // finish the entity construction mesh->setupRenderData(); Entity* entity = new Entity(); entity->mesh = mesh; entity->updateAABB(); world->entities.push_back(entity); if (renderer) renderer->entities.push_back(entity); return entity; }
int main(int argc, char **argv) { // we need the -schema <schema>, -input <json file or directory containing $(basename schema)*.json> and -pass <bool> QStringList arguments; std::string schema, input; bool pass = true; for (int i = 0; i < argc; i++) { if (argv[i][0] == '-') { switch (argv[i][1]) { case 's': if (strcmp(argv[i], "-schema") == 0) { schema = argv[++i]; continue; } break; case 'i': if (strcmp(argv[i], "-input") == 0) { input = argv[++i]; continue; } break; case 'p': if (strcmp(argv[i], "-pass") == 0) { pass = strcmp(argv[++i], "0") != 0; continue; } break; case '-': if (strcmp(argv[i], "--help") == 0) { printUsage(stdout, 1, argc, argv); } } } arguments += argv[i]; } raw_buffer schemaData; QFileInfo schemaFileInfo(QString::fromStdString(schema)); FilePtr schemaFile(map(schemaFileInfo.absoluteFilePath(), schemaData)); if (schemaFile.isNull()) printUsage(stderr, 2, argc, argv); resolutionDir = schemaFileInfo.dir(); qDebug() << "Looking for schemas in" << resolutionDir.absolutePath(); QList<FilePtr> fileHandles; pjson::testc::Inputs jsonInput; QString inputQStr = QString::fromStdString(input); QFileInfo inputInfo(inputQStr); QDir inputsDir(inputInfo.dir()); if (inputInfo.isDir()) { QStringList nameFilters; nameFilters += QFileInfo(QString::fromStdString(schema)).completeBaseName() + "*.json"; QFileInfoList tests = inputsDir.entryInfoList(nameFilters, QDir::Files | QDir::Readable, QDir::Name); for (int i = 0; i < tests.size(); i++) { jsonInput.fileNames << tests.at(i).absoluteFilePath(); } } else { jsonInput.fileNames += inputQStr; } for (int i = 0; i < jsonInput.fileNames.size(); i++) { raw_buffer fileData; FilePtr fileHandle(map(jsonInput.fileNames.at(i), fileData)); if (fileHandle == NULL) { destroyFiles(fileHandles); printUsage(stderr, 3, argc, argv); } fileHandles += fileHandle; jsonInput.fileData += fileData; } if (jsonInput.fileData.size() == 0) { fprintf(stderr, "No json inputs found to validate against in %s\n", input.c_str()); printUsage(stderr, 4, argc, argv); } Q_ASSERT(jsonInput.fileData.size() == jsonInput.fileNames.size()); pjson::testc::TestSchema schemaTester(schemaData, jsonInput, pass); return QTest::qExec(&schemaTester, arguments); }