bool aService::copyFile(const QString& srcFileName, const QString& destFileName, bool replaceIfExists) { QFile srcFile(srcFileName); QFile destFile(destFileName); if(!srcFile.exists()) { aLog::print(aLog::MT_ERROR, QObject::tr("aService copy: source file %1 not exist").arg(srcFileName)); return false; } if(destFile.exists() && !replaceIfExists) { aLog::print(aLog::MT_ERROR, QObject::tr("aService copy: replace destination file %1").arg(destFileName)); return false; } if(!srcFile.open( IO_ReadOnly )) { aLog::print(aLog::MT_ERROR, QObject::tr("aService copy: source file %1 open for read error").arg(srcFileName)); return false; } if(!destFile.open( IO_WriteOnly)) { aLog::print(aLog::MT_ERROR, QObject::tr("aService copy: destination file %1 open for write error").arg(destFileName)); return false; } const int BUFFER_SIZE = 1024; Q_INT8 buffer[BUFFER_SIZE]; QDataStream srcStream(&srcFile); QDataStream destStream(&destFile); while(!srcStream.atEnd()) { int i = 0; while(!srcStream.atEnd() && i < BUFFER_SIZE) { srcStream >> buffer[i]; i++; } for(int k = 0; k < i; k++) { destStream << buffer[k]; } } srcFile.close(); destFile.close(); aLog::print(aLog::MT_INFO, QObject::tr("aService copy file %1 to %2 ok").arg(srcFileName).arg(destFileName)); return true; }
bool fileCopy(const string& src, const string& dest) { ifstream srcFile(src,ios_base::binary); ofstream destFile(dest, ios_base::binary); char buffer[1024]; while(!srcFile.eof()){ srcFile.read(buffer, 1024); destFile.write(buffer,1024); } return true; }
void MainWindow::copyFile() { QFile srcFile(m_srcFileDir+m_fileName); QFile dstFile(m_dstFileDir+m_fileName); if (srcFile.exists() && dstFile.exists()) { dstFile.remove(); srcFile.copy(m_srcFileDir+m_fileName,m_dstFileDir+m_fileName); m_status->setText("Copied file successfully."); }else { // TODO m_status->setText("Failed to copy file."); } }
// Function that copies content of source to destination // Destination file will be overwritten // Supports only small files bool Helper::copyFile(const QString& source, const QString& destination) { QFile srcFile(source); if(!srcFile.open(QIODevice::ReadOnly)) return false; QByteArray data = srcFile.readAll(); srcFile.close(); QFile destFile(destination); if(!destFile.open(QIODevice::WriteOnly)) return false; destFile.write(data); destFile.close(); return true; }
void DocumentsDir::generateTemplateDir() { QFileInfoList fil( QDir(":/templates/").entryInfoList() ); QDir templatesDir( getTemplatesDirName() ); if( !templatesDir.mkpath( "." ) ) { return; } foreach( const QFileInfo &fi, fil ) { QString srcFile( fi.absoluteFilePath() ); QString destFile( templatesDir.absoluteFilePath( fi.fileName() ) ); if( QFile::copy( srcFile, destFile ) ) { QFile::setPermissions( destFile, QFile::permissions( destFile ) | QFile::WriteUser ); } }
void VMacResFile::DebugTest() { // look for a "test.rsrc" file in same folder as the app // and duplicate it VFilePath sourcePath = VProcess::Get()->GetExecutableFolderPath(); sourcePath.SetFileName(VStr63("test.rsrc")); DebugMsg("Looking for file = %V\n", &sourcePath); VMacResFile srcFile(sourcePath, FA_READ, false); sourcePath.SetFileName(VStr63("test copy.rsrc")); VMacResFile dstFile(sourcePath, FA_READ_WRITE, true); VError error = srcFile.CopyResourcesInto(dstFile); dstFile.Close(); srcFile.Close(); }
boost::optional<utils::net::NetworkPath> buildRemote(const utils::VirtualPrintable& source, const Host& targetHost, const utils::compiler::Compiler& compiler) { // create a temporary local source file char sourceFile[] = P_tmpdir "/srcXXXXXX"; int src = mkstemp(sourceFile); assert_ne(src, -1); close(src); // write source to file std::fstream srcFile(sourceFile, std::fstream::out); srcFile << source << "\n"; srcFile.close(); // build remotely auto res = buildRemote(toVector(nfs::NetworkPath(sourceFile)), "binary", targetHost, compiler); // delete source file if(boost::filesystem::exists(sourceFile)) { boost::filesystem::remove(sourceFile); } return res; }
void FileArchiveEntry::WriteData(rOStream& stream) { const int BUFFER_SIZE = 1024; rIFileStream srcFile(_path); if (srcFile.IsOk()) { char buffer[BUFFER_SIZE]; size_t bytesRead = 0; do { srcFile.Read(buffer, BUFFER_SIZE); size_t readCount = srcFile.ReadCount(); stream.Write(buffer, readCount); bytesRead += readCount; } while (bytesRead < _size); } }
bool VProjectItemFile::MoveTo(const XBOX::VURL& inSrcURL,const XBOX::VURL& inDestURL) { bool ok = false; VFilePath srcFilePath; inSrcURL.GetFilePath(srcFilePath); VFile srcFile(srcFilePath); if (srcFile.Exists()) { VFilePath destFilePath; inDestURL.GetFilePath(destFilePath); VFile destFile(destFilePath); if (!destFile.Exists()) { if (srcFile.Move(destFilePath, NULL) == VE_OK) ok = true; } } return ok; }
void DecodingFile(QString fPath, HCRYPTKEY hKey) { QFile myFile(fPath); QString fName = myFile.fileName(); QRegExp rx("[^eFile.dat]"); int typeLen = 0; rx.indexIn(fName, typeLen); QFile srcFile("1" + fName.mid(0, typeLen)); DWORD blockLen = 0, fDataSize; BYTE* fData; myFile.open(QIODevice::ReadOnly); if (!myFile.exists()) { QMessageBox::critical(0, "Ошибка", "Файл не выбран", QMessageBox::Ok); return; } srcFile.open(QIODevice::WriteOnly); CryptDecrypt(hKey, 0, true, 0, NULL, &blockLen); fData = new BYTE[blockLen]; memset(fData, 0, blockLen); while ((fDataSize = myFile.read((char*) fData, blockLen))) { if (!CryptDecrypt(hKey, 0, fDataSize < blockLen, 0, fData, &fDataSize)) { QMessageBox::critical(0, "Ошибка", "Шифрование данных. " + GetErrorString(GetLastError()), QMessageBox::Ok); return; } srcFile.write((char*)fData, fDataSize); memset(fData, 0, blockLen); } delete[] fData; myFile.close(); srcFile.close(); }
void MainWindow::on_action_New_triggered() { qDebug() << "on_action_New_triggered"; QString fileName = QFileDialog::getOpenFileName(this, tr("Open file"), QDir::currentPath(), tr("Lua files (*.lua)")); QFile srcFile(fileName); if (!srcFile.open(QIODevice::ReadWrite | QIODevice::Text)) { return; } QByteArray content = srcFile.readAll(); if (!content.length()) { qWarning() << "No such file or directory ..."; srcFile.close(); return; } QFileInfo sourceFile(fileName); ui->tabWidget->setTabText(0, sourceFile.fileName()); ui->plainTextEdit->setPlainText(QString(content)); srcFile.close(); }
void Downloader::copyFile(Job* job, const QString& source, QFile* file, QString* sha1, QCryptographicHash::Algorithm alg) { QFile srcFile(source); if (!srcFile.open(QFile::ReadOnly)) { job->setErrorMessage(QObject::tr("Error opening file: %1"). arg(source)); } else { qint64 srcSize = srcFile.size(); const int SZ = 8192; char* data = new char[SZ]; qint64 progress = 0; QCryptographicHash crypto(alg); while(true) { qint64 c = srcFile.read(data, SZ); if (c <= 0) break; if (sha1) crypto.addData(data, c); if (file) file->write(data, c); progress += c; if (srcSize != 0) job->setProgress(((double) progress) / srcSize); } if (sha1) *sha1 = crypto.result().toHex().toLower(); srcFile.close(); delete[] data; } job->complete(); }
// Format of aFileNames is [srcFile]|[dstFile] GLDEF_C TInt E32Main() { CTrapCleanup* cleanup = CTrapCleanup::New(); TBuf<KMaxFileName*2> names; User::CommandLine(names); TInt pos = names.Find(KSeparator); TFileName srcFile(names.Mid(0, pos)); TFileName dstFile(names.Mid(pos + 1, names.Length() - (pos + 1))); TInt err = KErrNone; TRAP(err, CopyFileL(srcFile, dstFile)); if (err == KErrNone) { RDebug::Print(_L("CFileMan Copy file '%S' to '%S' succeeded.\n"), &srcFile, &dstFile); } else { RDebug::Print(_L("CFileMan Copy file '%S' to '%S' failed with error = %d.\n"), &srcFile, &dstFile, err); } delete cleanup; return err; }
bool ResourcePackager::WritePackageFile(const String& destFilePath) { buildBase_->BuildLog("Writing package"); SharedPtr<File> dest(new File(context_, destFilePath, FILE_WRITE)); if (!dest->IsOpen()) { buildBase_->BuildError("Could not open output file " + destFilePath); return false; } // Write ID, number of files & placeholder for checksum WriteHeader(dest); for (unsigned i = 0; i < resourceEntries_.Size(); i++) { BuildResourceEntry* entry = resourceEntries_[i]; // Write entry (correct offset is still unknown, will be filled in later) dest->WriteString(entry->packagePath_); dest->WriteUInt(entry->offset_); dest->WriteUInt(entry->size_); dest->WriteUInt(entry->checksum_); } unsigned totalDataSize = 0; // Write file data, calculate checksums & correct offsets for (unsigned i = 0; i < resourceEntries_.Size(); i++) { BuildResourceEntry* entry = resourceEntries_[i]; entry->offset_ = dest->GetSize(); File srcFile(context_, entry->absolutePath_); if (!srcFile.IsOpen()) { buildBase_->BuildError("Could not open input file " + entry->absolutePath_); return false; } unsigned dataSize = entry->size_; totalDataSize += dataSize; SharedArrayPtr<unsigned char> buffer(new unsigned char[dataSize]); if (srcFile.Read(&buffer[0], dataSize) != dataSize) { buildBase_->BuildError("Could not read input file " + entry->absolutePath_); return false; } srcFile.Close(); for (unsigned j = 0; j < dataSize; ++j) { checksum_ = SDBMHash(checksum_, buffer[j]); entry->checksum_ = SDBMHash(entry->checksum_, buffer[j]); } // might not want to compress for WebGL //if (!compress_) //{ // PrintLine(entries_[i].name_ + " size " + String(dataSize)); // dest.Write(&buffer[0], entries_[i].size_); //} //else //{ unsigned compressedBlockSize_ = 32768; SharedArrayPtr<unsigned char> compressBuffer(new unsigned char[LZ4_compressBound(compressedBlockSize_)]); unsigned pos = 0; unsigned totalPackedBytes = 0; while (pos < dataSize) { unsigned unpackedSize = compressedBlockSize_; if (pos + unpackedSize > dataSize) unpackedSize = dataSize - pos; unsigned packedSize = LZ4_compressHC((const char*)&buffer[pos], (char*)compressBuffer.Get(), unpackedSize); if (!packedSize) { buildBase_->BuildError("LZ4 compression failed for file " + entry->absolutePath_ + " at offset " + pos); return false; } dest->WriteUShort(unpackedSize); dest->WriteUShort(packedSize); dest->Write(compressBuffer.Get(), packedSize); totalPackedBytes += 6 + packedSize; pos += unpackedSize; } buildBase_->BuildLog(entry->absolutePath_ + " in " + String(dataSize) + " out " + String(totalPackedBytes)); } //} // Write package size to the end of file to allow finding it linked to an executable file unsigned currentSize = dest->GetSize(); dest->WriteUInt(currentSize + sizeof(unsigned)); // Write header again with correct offsets & checksums dest->Seek(0); WriteHeader(dest); for (unsigned i = 0; i < resourceEntries_.Size(); i++) { BuildResourceEntry* entry = resourceEntries_[i]; dest->WriteString(entry->packagePath_); dest->WriteUInt(entry->offset_); dest->WriteUInt(entry->size_); dest->WriteUInt(entry->checksum_); } buildBase_->BuildLog("Number of files " + String(resourceEntries_.Size())); buildBase_->BuildLog("File data size " + String(totalDataSize)); buildBase_->BuildLog("Package size " + String(dest->GetSize())); return true; }
int main(int argc, char *argv[]) { #if QT_VERSION < 0x050000 qInstallMsgHandler(myMessageHandler); #else qInstallMessageHandler(myMessageHandler); #endif QCoreApplication app(argc, argv); if (argc != 2) { qCritical("Usage: autotranslate <target-dir>"); return -1; } QDir srcDir(app.arguments().value(1),"*.ts",QDir::Name,QDir::Files); if (!srcDir.exists()) { qCritical("Source directory '%s' not found.",srcDir.dirName().toLocal8Bit().constData()); return -1; } QDirIterator srcIt(srcDir); while (srcIt.hasNext()) { QFile srcFile(srcIt.next()); if (srcFile.open(QFile::ReadOnly)) { QDomDocument doc; if (doc.setContent(&srcFile,true)) { qDebug("Generation auto translation from '%s'.",srcFile.fileName().toLocal8Bit().constData()); QDomElement rootElem = doc.firstChildElement("TS"); rootElem.setAttribute("language",rootElem.attribute("sourcelanguage","en")); QDomElement contextElem = rootElem.firstChildElement("context"); while(!contextElem.isNull()) { QDomElement messageElem = contextElem.firstChildElement("message"); while(!messageElem.isNull()) { QDomElement sourceElem = messageElem.firstChildElement("source"); QDomElement translationElem = messageElem.firstChildElement("translation"); if (!sourceElem.isNull() && !translationElem.isNull()) if (translationElem.attribute("type")=="unfinished" && translationElem.text().isEmpty()) { QString sourceText = sourceElem.text(); if (messageElem.attribute("numerus") == "yes") qWarning("Untranslated numerus message: \"%s\"", sourceText.toLocal8Bit().constData()); else { translationElem.removeChild(translationElem.firstChild()); translationElem.appendChild(doc.createTextNode(sourceText)); translationElem.removeAttribute("type"); } } messageElem = messageElem.nextSiblingElement("message"); } contextElem = contextElem.nextSiblingElement("context"); } srcFile.close(); if (srcFile.open(QFile::WriteOnly|QFile::Truncate)) { srcFile.write(doc.toByteArray()); srcFile.close(); } else qWarning("Failed to open destination file '%s' for write.",srcFile.fileName().toLocal8Bit().constData()); } else qWarning("Invalid translation source file '%s'.",srcFile.fileName().toLocal8Bit().constData()); srcFile.close(); } else qWarning("Could not open translation source file '%s'.",srcFile.fileName().toLocal8Bit().constData()); } return 0; }
int main (int argc, char ** argv) { cl_int errNum; cl_uint numPlatforms; cl_uint numDevices; cl_paltform_id * platformIDs; cl_device_id * deviceIDs; cl_context context = NULL; cl_command_queue queue; cl_program program; cl_kernel kernel; cl_mem inputSignalBuffer; cl_mem outputSignalBuffer; cl_mem maskBuffer; errNum = clGetPlatformIDs (0, NULL, &numPlatforms); checkErr ((errNum != CL_SUCCESS) ? errNum : (numPlatforms <= 0 ? -1 : CL_SUCCESS), "clGetPlatformIDs"); platformIDs = (cl_platform_id *)alloca(sizeof(cl_platform_id) * numPlatforms); errNum = clGetPlatformIDs (numPlatforms, platformIDs, NULL); checkErr ((errNum != CL_SUCCESS) ? errNum : (numPlatforms <= 0 ? -1 : CL_SUCCESS), "clGetPlatformIDs"); deviceIDs = NULL; cl_uint i; for (i = 0; i < numPlatforms; i++) { errNum = clGetDeviceIDs (platformIDs[i], CL_DEVICE_TYPE_CPU, 0, NULL, &numDevices); if (errNum != CL_SUCCESS && errNum != CL_DEVICE_NOT_FOUND) { checkErr (errNum, "clGetDeviceIDs"); } else if (numDevices > 0) { deviceIDs = (cl_device_id *)alloca(sizeof(cl_device_id) * numDevices); errNum = clGetDeviceIDs (platformIDs[i], CL_DEVICE_TYPE_CPU, numDevices, &deviceIDs[0], NULL); checkErr (errNum, "clGetDeviceIDs"); break; } } if (deviceIDs == NULL) { std::cout << "No CPU device found" << std::endl; exit (-1); } cl_context_properties contextProperties[] = { CL_CONTEXT_PLATFORM, (cl_context_properties)platformIDs[i], 0 }; context = clCreateContext (contextProperties, numDevices, deviceIDs, &contextCallback, NULL, &errNum); checkErr (errNum, "clCreateContext"); std::ifstream srcFile ("Convolution.cl"); checkErr (srcFile.is_open() ? CL_SUCCESS : -1, "reading Convolution.cl"); std::string srcProg(std::istreambuf_iterator<char>(srcFile), (std::istreambuf_iterator<char>())); const char * src = srcProg.c_str(); size_t length = srcProg.length(); program = clCreateProgramWithSource (context, 1, &src, &length, &errNum); checkErr (errNum, "clCreateProgramWithSource"); inputSignalBuffer = clCreateBuffer (context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(cl_uint) * inputSignalHeight * inputSignalWidth, static_cast<void *>(inputSignal), &errNum); checkErr (errNum, "clCreateBuffer (inputSignal)"); maskBuffer = clCreateBuffer (context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(cl_uint) * maskHeight * maskWidth, static_cast<void *>(mask), &errNum); checkErr (errNum, "clCreateBuffer(mask)"); outputSignalBuffer = clCreateBuffer(context, CL_MEM_WRITE_ONLY, sizeof(cl_uint) * outputSignalHeight * outputSignalWidth, NULL, &errNum); checkErr (errNum, "clCreateBuffer(outputSignal)"); queue = clCreateCommandQueue (context, deviceIDs[0], 0, &errNum); checkErr (errNum, "clCreateCommandQueue"); errNum = clSetKernelArg (kernel, 0, sizeof(cl_mem), &inputSignalBuffer); errNum |= clSetKernelArg (kernel, 1, sizeof(cl_mem), &maskBuffer); errNum |= clSetKernelArg (kernel, 2, sizeof(cl_mem), &outputSignalBuffer); errNum |= clSetKernelArg (kernel, 3, sizeof(cl_uint), &inputSignalWidth); errNum |= clSetKernelArg (kernel, 4, sizeof(cl_uint), &maskWidth); checkErr (errNum, "clSetKernelArg"); const size_t globalWorkSize[1] = { outputSignalWidth * outputSingalHeight }; const size_t localWorkSize[1] = { 1 }; errNum = clEnqueueNDRangeKernel ( queue, kernel, 1, NULL, globalWorkSize, localWorkSize, 0, NULL, NULL ); checkErr (errNum, "clEnqueueNDRangeKernel"); errNum = clEnqueueReadBuffer (queue, outputSignalBuffer, CL_TRUE, 0, sizeof(cl_uint) * outputSignalHeight * outputSignalHeight, outputSignal, 0, NULL, NULL); checkErr (errNum, "clEnqueueReadBuffer"); for (int y = 0; y < outputSignalHeight; y++) { for (int x = 0; x < outputSignalWidth; x++) { std::cout << outputSignal[x][y] << " "; } std::cout << std::endl; } return 0; }
int main(int argc, char *argv[]) { int verbose=2; std::string srcFileName="-"; int maxTries=INT_MAX; std::string name="perfect"; //std::string writeCpp=""; std::string method="default"; int wV=0; unsigned maxHash=0; double maxTime=600; double maxMem=4000; double solveTime=0.0; std::string csvLogDst; urng.seed(time(0)); try { int ia = 1; while (ia < argc) { if (!strcmp(argv[ia], "--verbose")) { if ((argc - ia) < 2) throw std::runtime_error("No argument to --verbose"); verbose = atoi(argv[ia + 1]); ia += 2; } else if (!strcmp(argv[ia], "--input")) { if ((argc - ia) < 2) throw std::runtime_error("No argument to --input"); srcFileName = argv[ia + 1]; ia += 2; } else if (!strcmp(argv[ia], "--csv-log")) { if ((argc - ia) < 3) throw std::runtime_error("No argument to --csv-dst"); csvLogPrefix = argv[ia + 1]; csvLogDst = argv[ia + 2]; ia += 3; } else if (!strcmp(argv[ia], "--wa")) { if ((argc - ia) < 2) throw std::runtime_error("No argument to --wa"); wA = atoi(argv[ia + 1]); if (wA < 1) throw std::runtime_error("Can't have wa < 1"); if (wA > 12) throw std::runtime_error("wa > 12 is unexpectedly large (edit code if you are sure)."); ia += 2; } else if (!strcmp(argv[ia], "--wo")) { if ((argc - ia) < 2) throw std::runtime_error("No argument to --wo"); wO = atoi(argv[ia + 1]); if (wO < 1) throw std::runtime_error("Can't have wo < 1"); if (wO > 16) throw std::runtime_error("wo > 16 is unexpectedly large (edit code if you are sure)."); ia += 2; } else if (!strcmp(argv[ia], "--wv")) { if ((argc - ia) < 2) throw std::runtime_error("No argument to --wv"); wV = atoi(argv[ia + 1]); if (wV < 0) throw std::runtime_error("Can't have wv < 0"); ia += 2; } else if (!strcmp(argv[ia], "--wi")) { if ((argc - ia) < 2) throw std::runtime_error("No argument to --wi"); wI = atoi(argv[ia + 1]); if (wI < 1) throw std::runtime_error("Can't have wi < 1"); if (wI > 32) throw std::runtime_error("wo > 32 is unexpectedly large (edit code if you are sure)."); ia += 2; } else if (!strcmp(argv[ia], "--max-time")) { if ((argc - ia) < 2) throw std::runtime_error("No argument to --max-time"); maxTime = strtod(argv[ia + 1], 0); ia += 2; } else if (!strcmp(argv[ia], "--max-mem")) { if ((argc - ia) < 2) throw std::runtime_error("No argument to --max-mem"); maxMem = strtod(argv[ia + 1], 0); ia += 2; } else if (!strcmp(argv[ia], "--method")) { if ((argc - ia) < 2) throw std::runtime_error("No argument to --method"); method = argv[ia + 1]; ia += 2; } else if (!strcmp(argv[ia], "--max-hash")) { if ((argc - ia) < 2) throw std::runtime_error("No argument to --max-hash"); maxHash = atoi(argv[ia + 1]); ia += 2; } else if (!strcmp(argv[ia], "--minimal")) { if ((argc - ia) < 1) throw std::runtime_error("No argument to --minimal"); maxHash=UINT_MAX; ia += 1; /*} else if (!strcmp(argv[ia], "--write-cpp")) { if ((argc - ia) < 2) throw std::runtime_error("Not enough arguments to --write-cpp"); writeCpp = argv[ia + 1]; ia += 2;*/ } else { throw std::runtime_error(std::string("Didn't understand argument ") + argv[ia]); } } if(!csvLogDst.empty()){ if(csvLogDst=="-"){ pCsvDst = &std::cout; }else{ csvLogFile.open(csvLogDst); if(!csvLogFile.is_open()){ throw std::runtime_error("Couldn't open csv log destination."); } pCsvDst=&csvLogFile; } } if(verbose>0){ fprintf(stderr, "Setting limits of %f seconds CPU time and %f MB of memory.\n", maxTime, maxMem); setTimeAndSpaceLimit(maxTime, maxMem); } if (method == "default") { if (verbose > 0) { method = "minisat_weighted"; std::cerr << "Selecting default method = " << method << "\n"; } } if (verbose > 0) { std::cerr << "Loading input from " << (srcFileName == "-" ? "<stdin>" : srcFileName) << ".\n"; } key_value_set problem; if (srcFileName == "-") { problem = parse_key_value_set(std::cin); } else { std::ifstream srcFile(srcFileName); if (!srcFile.is_open()) throw std::runtime_error("Couldn't open source file " + srcFileName); problem = parse_key_value_set(srcFile); } if (verbose > 1) { std::cerr << "Input key value pairs:\n"; problem.print(std::cerr, " "); std::cerr << "nKeys = " << problem.size() << "\n"; std::cerr << "wKey = " << problem.getKeyWidth() << "\n"; std::cerr << "wValue = " << problem.getValueWidth() << "\n"; } if(maxHash==UINT_MAX){ if(verbose>0){ std::cerr << " Building minimal hash.\n"; } problem.setMaxHash(maxHash); }else if(maxHash>0){ if(verbose>0){ std::cerr << " Setting maxHash="<<maxHash<<"\n"; } problem.setMaxHash(maxHash); } if (wI == -1) { wI = problem.getKeyWidth(); if (verbose > 0) { std::cerr << "Auto-selecting wI = " << wI << "\n"; } } else { if (wI < (int) problem.getKeyWidth()) { throw std::runtime_error("Specified key width does not cover all keys."); } } if (wO == -1) { unsigned nKeys = problem.keys_size(); wO = (unsigned) ceil(log(nKeys) / log(2.0)); if (verbose > 0) { std::cerr << "Auto-selecting wO = " << wO << " based on nKeys = " << nKeys << "\n"; } } else { if ((1u << wO) < problem.keys_size()) { throw std::runtime_error("Specified output width cannot span number of keys."); } } if (verbose > 0) { std::cerr << "Group load factor is 2^wO / nKeyGroups = " << problem.keys_size() << " / " << (1 << wO) << " = " << problem.keys_size() / (double) (1 << wO) << "\n"; std::cerr << "True load factor is 2^wO / nKeysDistinct = " << problem.keys_size_distinct() << " / " << (1 << wO) << " = " << problem.keys_size_distinct() / (double) (1 << wO) << "\n"; } BitHash result; startTime=cpuTime(); tries = 1; bool success = false; while (tries < maxTries) { if (verbose > 0) { std::cerr << " Attempt " << tries << "\n"; } if (verbose > 0) { std::cerr << " Creating bit hash...\n"; } auto bh = (method == "minisat_weighted") ? makeWeightedBitHash(urng, problem, wO, wI, wA) : makeBitHash( urng, wO, wI, wA); if (verbose > 0) { std::cerr << " Converting to CNF...\n"; } cnf_problem prob; to_cnf(bh, problem.keys(), prob, problem.getMaxHash()); if (verbose > 0) { std::cerr << " Solving problem with minisat...\n"; } auto sol = minisat_solve(prob, verbose); if (sol.empty()) { if (verbose > 0) { std::cerr << " No solution\n"; } } else { if (verbose > 0) { std::cerr << " Checking raw...\n"; } if (verbose > 0) { std::cerr << " Substituting...\n"; } auto back = substitute(bh, prob, sol); if (verbose > 0) { std::cerr << " checking...\n"; } if (!back.is_solution(problem)) throw std::runtime_error("Failed post substitution check."); success = true; result = back; break; } tries++; } double finishTime=cpuTime(); solveTime=finishTime-startTime; if(pCsvDst){ (*pCsvDst)<<csvLogPrefix<<", "<<wO<<", "<<wI<<", "<<wA<<", "<<solveTime<<", "<<tries<<", "<<(success?"Success":"OutOfAttempts")<<"\n"; } if (!success) { if(pCsvDst) { exit(0); }else{ exit(1); } } if(verbose>1){ for(const auto &kv : problem){ auto key = *kv.first.variants_begin(); std::cerr<<" "<<key<<" -> "<<result(key)<<"\n"; } } // Print the two back to back result.print(std::cout); problem.print(std::cout); }catch(Minisat::OutOfMemoryException &e){ if(pCsvDst){ (*pCsvDst)<<csvLogPrefix<<", "<<wO<<", "<<wI<<", "<<wA<<", "<<solveTime<<", "<<tries<<", "<<"OutOfMemory"<<"\n"; pCsvDst->flush(); } std::cerr<<"Memory limit exceeded."; _exit(pCsvDst ? 0 : 1); }catch(std::exception &e){ if(pCsvDst){ (*pCsvDst)<<csvLogPrefix<<", "<<wO<<", "<<wI<<", "<<wA<<", "<<solveTime<<", "<<tries<<", "<<"Exception"<<"\n"; pCsvDst->flush(); } std::cerr<<"Caught exception : "; print_exception(e); std::cerr.flush(); _exit(pCsvDst ? 0 : 1); } return 0; }
ssize_t AaptAssets::slurpFromArgs(Bundle* bundle) { int count; int totalCount = 0; int i; int arg = 0; FileType type; const char* res; const int N = bundle->getFileSpecCount(); /* * If a package manifest was specified, include that first. */ if (bundle->getAndroidManifestFile() != NULL) { // place at root of zip. String8 srcFile(bundle->getAndroidManifestFile()); addFile(srcFile.getPathLeaf(), AaptGroupEntry(), srcFile.getPathDir(), NULL, String8()); totalCount++; } /* * If a directory of custom assets was supplied, slurp 'em up. */ if (bundle->getAssetSourceDir()) { const char* assetDir = bundle->getAssetSourceDir(); FileType type = getFileType(assetDir); if (type == kFileTypeNonexistent) { fprintf(stderr, "ERROR: asset directory '%s' does not exist\n", assetDir); return UNKNOWN_ERROR; } if (type != kFileTypeDirectory) { fprintf(stderr, "ERROR: '%s' is not a directory\n", assetDir); return UNKNOWN_ERROR; } String8 assetRoot(assetDir); sp<AaptDir> assetAaptDir = makeDir(String8(kAssetDir)); AaptGroupEntry group; count = assetAaptDir->slurpFullTree(bundle, assetRoot, group, String8()); if (count < 0) { totalCount = count; goto bail; } if (count > 0) { mGroupEntries.add(group); } totalCount += count; if (bundle->getVerbose()) printf("Found %d custom asset file%s in %s\n", count, (count==1) ? "" : "s", assetDir); } /* * If a directory of resource-specific assets was supplied, slurp 'em up. */ res = bundle->getResourceSourceDir(); if (res) { type = getFileType(res); if (type == kFileTypeNonexistent) { fprintf(stderr, "ERROR: resource directory '%s' does not exist\n", res); return UNKNOWN_ERROR; } if (type == kFileTypeDirectory) { count = slurpResourceTree(bundle, String8(res)); if (count < 0) { totalCount = count; goto bail; } totalCount += count; } else { fprintf(stderr, "ERROR: '%s' is not a directory\n", res); return UNKNOWN_ERROR; } } /* * Now do any additional raw files. */ for (int arg=0; arg<N; arg++) { const char* assetDir = bundle->getFileSpecEntry(arg); FileType type = getFileType(assetDir); if (type == kFileTypeNonexistent) { fprintf(stderr, "ERROR: input directory '%s' does not exist\n", assetDir); return UNKNOWN_ERROR; } if (type != kFileTypeDirectory) { fprintf(stderr, "ERROR: '%s' is not a directory\n", assetDir); return UNKNOWN_ERROR; } String8 assetRoot(assetDir); if (bundle->getVerbose()) printf("Processing raw dir '%s'\n", (const char*) assetDir); /* * Do a recursive traversal of subdir tree. We don't make any * guarantees about ordering, so we're okay with an inorder search * using whatever order the OS happens to hand back to us. */ count = slurpFullTree(bundle, assetRoot, AaptGroupEntry(), String8()); if (count < 0) { /* failure; report error and remove archive */ totalCount = count; goto bail; } totalCount += count; if (bundle->getVerbose()) printf("Found %d asset file%s in %s\n", count, (count==1) ? "" : "s", assetDir); } count = validate(); if (count != NO_ERROR) { totalCount = count; goto bail; } bail: return totalCount; }
// main() for simple buffer and sub-buffer example // int main(int argc, char** argv) { cl_int errNum; cl_uint numPlatforms; cl_uint numDevices; cl_platform_id * platformIDs; cl_device_id * deviceIDs; cl_context context; cl_program program; std::vector<cl_kernel> kernels; std::vector<cl_command_queue> queues; std::vector<cl_mem> buffers; int * inputOutput; std::cout << "Simple buffer and sub-buffer Example" << std::endl; // First, select an OpenCL platform to run on. errNum = clGetPlatformIDs(0, NULL, &numPlatforms); checkErr( (errNum != CL_SUCCESS) ? errNum : (numPlatforms <= 0 ? -1 : CL_SUCCESS), "clGetPlatformIDs"); platformIDs = (cl_platform_id *)alloca(sizeof(cl_platform_id) * numPlatforms); std::cout << "Number of platforms: \t" << numPlatforms << std::endl; errNum = clGetPlatformIDs(numPlatforms, platformIDs, NULL); checkErr( (errNum != CL_SUCCESS) ? errNum : (numPlatforms <= 0 ? -1 : CL_SUCCESS), "clGetPlatformIDs"); std::ifstream srcFile("simple.cl"); checkErr(srcFile.is_open() ? CL_SUCCESS : -1, "reading simple.cl"); std::string srcProg( std::istreambuf_iterator<char>(srcFile), (std::istreambuf_iterator<char>())); const char * src = srcProg.c_str(); size_t length = srcProg.length(); deviceIDs = NULL; DisplayPlatformInfo( platformIDs[PLATFORM_INDEX], CL_PLATFORM_VENDOR, "CL_PLATFORM_VENDOR"); errNum = clGetDeviceIDs( platformIDs[PLATFORM_INDEX], CL_DEVICE_TYPE_ALL, 0, NULL, &numDevices); if (errNum != CL_SUCCESS && errNum != CL_DEVICE_NOT_FOUND){ checkErr(errNum, "clGetDeviceIDs"); } deviceIDs = (cl_device_id *)alloca( sizeof(cl_device_id) * numDevices); errNum = clGetDeviceIDs( platformIDs[PLATFORM_INDEX], CL_DEVICE_TYPE_ALL, numDevices, &deviceIDs[0], NULL); checkErr(errNum, "clGetDeviceIDs"); cl_context_properties contextProperties[] = { CL_CONTEXT_PLATFORM, (cl_context_properties)platformIDs[PLATFORM_INDEX], 0 }; context = clCreateContext( contextProperties, numDevices, deviceIDs, NULL, NULL, &errNum); checkErr(errNum, "clCreateContext"); // Create program from source program = clCreateProgramWithSource( context, 1, &src, &length, &errNum); checkErr(errNum, "clCreateProgramWithSource"); // Build program errNum = clBuildProgram( program, numDevices, deviceIDs, "-I.", NULL, NULL); if (errNum != CL_SUCCESS){ // Determine the reason for the error char buildLog[16384]; clGetProgramBuildInfo( program, deviceIDs[0], CL_PROGRAM_BUILD_LOG, sizeof(buildLog), buildLog, NULL); std::cerr << "Error in OpenCL C source: " << std::endl; std::cerr << buildLog; checkErr(errNum, "clBuildProgram"); } // create buffers and sub-buffers inputOutput = new int[NUM_BUFFER_ELEMENTS * numDevices]; for (unsigned int i = 0; i < NUM_BUFFER_ELEMENTS * numDevices; i++) { inputOutput[i] = i; } // create a single buffer to cover all the input data cl_mem buffer = clCreateBuffer( context, CL_MEM_READ_WRITE, sizeof(int) * NUM_BUFFER_ELEMENTS * numDevices, NULL, &errNum); checkErr(errNum, "clCreateBuffer"); buffers.push_back(buffer); // now for all devices other than the first create a sub-buffer for (unsigned int i = 1; i < numDevices; i++) { cl_buffer_region region = { NUM_BUFFER_ELEMENTS * i * sizeof(int), NUM_BUFFER_ELEMENTS * sizeof(int) }; buffer = clCreateSubBuffer( buffers[0], CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &errNum); checkErr(errNum, "clCreateSubBuffer"); buffers.push_back(buffer); } // Create command queues for (int i = 0; i < numDevices; i++) { InfoDevice<cl_device_type>::display(deviceIDs[i], CL_DEVICE_TYPE, "CL_DEVICE_TYPE"); cl_command_queue queue = clCreateCommandQueue( context, deviceIDs[i], 0, &errNum); checkErr(errNum, "clCreateCommandQueue"); queues.push_back(queue); cl_kernel kernel = clCreateKernel( program, "square", &errNum); checkErr(errNum, "clCreateKernel(square)"); errNum = clSetKernelArg( kernel, 0, sizeof(cl_mem), (void *)&buffers[i]); checkErr(errNum, "clSetKernelArg(square)"); kernels.push_back(kernel); // Write input data clEnqueueWriteBuffer( queues[0], buffers[0], CL_TRUE, 0, sizeof(int) * NUM_BUFFER_ELEMENTS * numDevices, (void*)inputOutput, 0, NULL, NULL); std::vector<cl_event> events; // call kernel for each device for (int i = 0; i < queues.size(); i++) { cl_event event; size_t gWI = NUM_BUFFER_ELEMENTS; errNum = clEnqueueNDRangeKernel( queues[i], kernels[i], 1, NULL, (const size_t*)&gWI, (const size_t*)NULL, 0, 0, &event); events.push_back(event); } // Technically don't need this as we are doing a blocking read // with in-order queue. clWaitForEvents(events.size(), events.data()); // Read back computed data clEnqueueReadBuffer( queues[0], buffers[0], CL_TRUE, 0, sizeof(int) * NUM_BUFFER_ELEMENTS * numDevices, (void*)inputOutput, 0, NULL, NULL); // Display output in rows for (unsigned i = 0; i < numDevices; i++) { for (unsigned elems = i * NUM_BUFFER_ELEMENTS; elems < ((i+1) * NUM_BUFFER_ELEMENTS); elems++) { std::cout << " " << inputOutput[elems]; } std::cout << std::endl; } std::cout << "Program completed successfully" << std::endl; return 0; } }
mxAPPLICATION_ENTRY_POINT int mxAppMain() { SetupBaseUtil setupBase; //FileLogUtil fileLog; SetupCoreUtil setupCore; const String srcFileName( "D:/dev/_assets/_diplomarbeit/iryoku-head/Head.sdkmesh" //"D:/research/_current/iryoku-separable-sss-f61b44c/Demo/Media/Head.sdkmesh" //"D:/dev/_assets/Head.sdkmesh" ); FileReader srcFile( srcFileName ); CHK_VRET_X_IF_NOT( srcFile.IsOpen(), -1 ); StaticTriangleMeshData staticMeshData; { SDKMesh sdkMesh; if( FAILED(sdkMesh.Create(mxTO_UNICODE( srcFileName ))) ) { return -1; } const SDKMESH_HEADER& header = *sdkMesh.GetHeader(); (void)header; const UINT numMeshes = sdkMesh.GetNumMeshes(); Assert(numMeshes == 1); const UINT iFirstMesh = 0; const UINT numSubsets = sdkMesh.GetNumSubsets( iFirstMesh ); Assert( numSubsets == 1 ); const UINT iFirstSubset = 0; const SDKMESH_SUBSET* pSubset = sdkMesh.GetSubset( iFirstMesh, iFirstSubset ); const UINT numVertices = pSubset->VertexCount; const UINT numIndices = pSubset->IndexCount; const UINT numVBs = sdkMesh.GetNumVBs(); Assert( numVBs == 1 ); const UINT numIBs = sdkMesh.GetNumIBs(); Assert( numIBs == 1 ); const SDKMeshVertex* srcVertices = (const SDKMeshVertex*) sdkMesh.GetRawVerticesAt(0); const SDKMESH_INDEX_TYPE indexType = sdkMesh.GetIndexType( iFirstMesh ); Assert( indexType == SDKMESH_INDEX_TYPE::IT_16BIT ); const UINT16* srcIndices = (const UINT16*) sdkMesh.GetRawIndicesAt(0); { TList< Vec3D > & positions = staticMeshData.positions; TList< Vec2D > & texCoords = staticMeshData.texCoords; TList< Vec3D > & normals = staticMeshData.normals; //TList< Vec3D > & binormals = staticMeshData.binormals; TList< Vec3D > & tangents = staticMeshData.tangents; positions.SetNum( numVertices ); texCoords.SetNum( numVertices ); normals.SetNum( numVertices ); tangents.SetNum( numVertices ); staticMeshData.localBounds.Clear(); for( UINT iVertex = 0; iVertex < numVertices; iVertex++ ) { const SDKMeshVertex & srcVertex = srcVertices[ iVertex ]; Assert( srcVertex.normal.IsNormalized() ); Assert( srcVertex.tangent.IsNormalized() ); positions[ iVertex ] = srcVertex.position; texCoords[ iVertex ] = srcVertex.texCoord; normals[ iVertex ] = srcVertex.normal; tangents[ iVertex ] = srcVertex.tangent; staticMeshData.localBounds.AddPoint( srcVertex.position ); } staticMeshData.indices.AddBytes( srcIndices, numIndices * sizeof srcIndices[0] ); staticMeshData.indexStride = sizeof srcIndices[0]; MeshPart & firstBatch = staticMeshData.batches.Add(); { firstBatch.baseVertex = pSubset->VertexStart; firstBatch.startIndex = pSubset->IndexStart; firstBatch.indexCount = pSubset->IndexCount; firstBatch.vertexCount = pSubset->VertexCount; } } } const String dstPathName( //"D:/dev/_assets" "R:/" ); String dstFileName( "iryoku-Head" ); //srcFileName.ExtractFileBase( dstFileName ); dstFileName += ".static_mesh"; FileWriter dstFile( dstPathName + dstFileName ); CHK_VRET_X_IF_NOT( dstFile.IsOpen(), -1 ); ArchivePODWriter archive( dstFile ); staticMeshData.Serialize( archive ); return 0; }
bool ModuleListInstance::replaceProjectFileContents(const QString& file) { clearWrittenFlags(); QStringList doc; QFile srcFile(file); int stage = 0; if(srcFile.open(QIODevice::ReadOnly | QIODevice::Text)) { while(!srcFile.atEnd()) { QString text = srcFile.readLine(); QString strippedText = text.simplified(); if(!strippedText.startsWith("//")) { if(text.contains("Torque3D::beginConfig(", Qt::CaseInsensitive)) { // We need to have written all move classes and module paths by now writeUnhandledMoveClasses(doc); writeUnhandledModulePaths(doc); // Now write out the beginConfig() line doc << text; // Next stage stage = 1; } else if(text.contains("Torque3D::endConfig(", Qt::CaseInsensitive)) { // We need to have written all modules by now writeUnhandledModules(doc); writeUnhandledProjectDefines(doc); // Now write out the endConfig() line doc << text; // Next stage stage = 2; } else if(stage == 0 && strippedText.startsWith("$")) { // Prior to the beginConfig() stage. Here we may find move classes and module paths. bool handled = false; // Start by checking for a move class handled = handleMoveClass(text); // Should we try to handle a module path? if(!handled) { handled = handleModulePath(text); } doc << text; } else if(stage == 1 && text.contains("includeModule(")) { // Deal with the module handleModule(doc, text); } else if(stage == 1 && text.contains("addProjectDefine(")) { // Deal with the project define handleProjectDefine(doc, text); } else { // Just write out the line doc << text; } } else { doc << text; } } srcFile.close(); } else { return false; } // Write out the new file if(srcFile.open(QIODevice::WriteOnly | QIODevice::Text)) { for(int i=0; i<doc.count(); ++i) { srcFile.write(doc.at(i).toLocal8Bit()); } srcFile.close(); } else { return false; } return true; }
bool ModuleListInstance::readProjectFile(const QString& path) { clearData(); mFileSource = path; QFile srcFile(path); int stage = 0; if(srcFile.open(QIODevice::ReadOnly | QIODevice::Text)) { while(!srcFile.atEnd()) { QString text = srcFile.readLine(); QString strippedText = text.simplified(); if(!strippedText.startsWith("//")) { if(text.contains("Torque3D::beginConfig(", Qt::CaseInsensitive)) { // We now check for modules and project defines. On to the next stage. stage = 1; } else if(text.contains("Torque3D::endConfig(", Qt::CaseInsensitive)) { // Done checking for modules and project defines. On to the next stage. stage = 2; } else if(stage == 0 && strippedText.startsWith("$")) { // Could be a move class variable or a module path. Start with // a move class. bool handled = readMoveClass(text); if(!handled) { // Not a move class so try a module path. readModulePath(text); } } else if(stage == 1 && text.contains("includeModule(")) { // Handle the module readModule(text); } else if(stage == 1 && text.contains("addProjectDefine(")) { // Handle the project define readProjectDefine(text); } } } srcFile.close(); } else { return false; } return true; }
// --------------------------------------------------------------------------- // Name: osCopyFile // Description: Copies a file from sourcePath to destinationPath, overwriting if // allowOverwrite is true. Only the file being copied is considered // success (i.e. allowOverwrite = false with an existing // destinationPath is considered a failure). // Return Val: bool - Success / failure. // Author: AMD Developer Tools Team // Date: 8/7/2012 // --------------------------------------------------------------------------- bool osCopyFile(const osFilePath& sourcePath, const osFilePath& destinationPath, bool allowOverwrite) { bool retVal = false; // If the source file exists (and is not a directory, etc): if (!sourcePath.isRegularFile()) { return retVal; } // Check if exist and writable if (destinationPath.isRegularFile()) { if (!allowOverwrite) { return retVal; } else { osFile dstFile(destinationPath); { if (!dstFile.deleteFile()) { return retVal; } } } } // Copy file gtSize_t read = 0; gtSize_t totRead = 0; gtSize_t bufSize = 1024; gtByte buffer[bufSize]; osFile srcFile(sourcePath); unsigned long srcSize(0); osFile dstFile(destinationPath); bool bSrc = srcFile.open(osChannel::OS_BINARY_CHANNEL, osFile::OS_OPEN_TO_READ); bool bDst = dstFile.open(osChannel::OS_BINARY_CHANNEL, osFile::OS_OPEN_TO_WRITE); if (bSrc && bDst) { srcFile.getSize(srcSize); while (srcFile.readAvailableData((gtByte*)&buffer, bufSize, read) && read != 0) { totRead += read; dstFile.write(buffer, read); } } if (bSrc) { srcFile.close(); } if (bDst) { dstFile.close(); } // Verify the output file, allowing 0 size files to be copied if (((totRead != 0) || (0 == srcSize)) && destinationPath.isRegularFile()) { retVal = true; } return retVal; }
int main(int argc, char *argv[]) { cl_int errNum; cl_uint nPlataformas; cl_uint nDispositivos; cl_platform_id *listaPlataformaID; cl_device_id *listaDispositivoID; cl_context contexto = NULL; cl_command_queue fila; cl_program programa; cl_kernel kernel; cl_mem Abuffer; cl_mem Bbuffer; cl_mem Cbuffer; cl_event evento; // Constantes // Matrizes A, B e C // Tamanhos: // A: l x m // B: m x n // C: l x n --- C = A x B int nn = atoi(argv[1]); const unsigned int l = nn; const unsigned int m = nn; const unsigned int n = nn; /* const unsigned int l = atoi(argv[1]); const unsigned int m = atoi(argv[1]); const unsigned int n = atoi(argv[1]); cl_uint A[l][m]; cl_uint B[m][n]; cl_uint C[l][n]; */ cl_uint **A; A = (cl_uint **)malloc(sizeof(cl_uint *)*l); cl_uint **C; C = (cl_uint **)malloc(sizeof(cl_uint *)*l); cl_uint **B; B = (cl_uint **)malloc(sizeof(cl_uint *)*l); // Preenchendo as matrizes for ( int x = 0; x < l ; x ++ ) { A[x] = (cl_uint *)malloc(sizeof(cl_uint)*m); B[x] = (cl_uint *)malloc(sizeof(cl_uint)*m); C[x] = (cl_uint *)malloc(sizeof(cl_uint)*m); for (int y = 0; y < m ; y ++ ) { A[x][y] = x + y*2; } } for ( int x = 0; x < m ; x ++ ) { for (int y = 0; y < n ; y ++ ) { B[x][y] = 3*x + y; B[x][y] |= 1; } } ///// Selecionando uma plataforma OpenCL para rodar // Atribuindo a nPlataformas o número de plataformas disponíveis errNum = clGetPlatformIDs(0, NULL, &nPlataformas); checkErr( (errNum != CL_SUCCESS) ? errNum : (nPlataformas <= 0 ? -1 : CL_SUCCESS), "clGetPlataformsIDs"); // Se não houve erro, alocar memória para cl_platform_id listaPlataformaID = (cl_platform_id *)alloca(sizeof(cl_platform_id)*nPlataformas); // Atribuindo uma plataforma ao listaPlataformaID errNum = clGetPlatformIDs(nPlataformas, listaPlataformaID, NULL); std::cout << "#Plataformas: " << nPlataformas << std::endl; checkErr( (errNum != CL_SUCCESS) ? errNum : (nPlataformas <= 0 ? -1 : CL_SUCCESS), "clGetPlatformIDs"); // Iterando na lista de plataformas até achar uma que suporta um dispositivo de CPU. Se isso não ocorrer, acusar erro. cl_uint i; for (i=0; i < nPlataformas; i++) { // Atribuindo o número de dispositivos de GPU a nDispositivos errNum = clGetDeviceIDs ( listaPlataformaID[i], // CL_DEVICE_TYPE_ALL, // CL_DEVICE_TYPE_CPU, CL_DEVICE_TYPE_GPU, 0, NULL, &nDispositivos ); if (errNum != CL_SUCCESS && errNum != CL_DEVICE_NOT_FOUND) { infoPlataforma(listaPlataformaID, i); checkErr (errNum, "clGetDeviceIDs"); } // Conferindo se há dispositivos de CPU else if (nDispositivos > 0) { // Atribuindo um dispositivo a uma listaDispositivoID listaDispositivoID = (cl_device_id *)alloca(sizeof(cl_device_id)*nDispositivos); errNum = clGetDeviceIDs ( listaPlataformaID[i], // CL_DEVICE_TYPE_ALL, // CL_DEVICE_TYPE_CPU, CL_DEVICE_TYPE_GPU, nDispositivos, &listaDispositivoID[0], NULL); checkErr(errNum, "clGetPlatformIDs"); break; } } // Crindo um contexto no dispositivo/plataforma selecionada std::cout << "Adicionando dispositivos OpenCL de numero " << i << std::endl; infoPlataforma(listaPlataformaID, i); cl_context_properties propContexto[] = { CL_CONTEXT_PLATFORM, (cl_context_properties)listaPlataformaID[i], 0 }; contexto = clCreateContext( propContexto, nDispositivos, listaDispositivoID, &contextCallback, NULL, &errNum ); checkErr(errNum, "clCreateContext"); // Carregando o arquivo-fonte cl para póstuma compilação feita em runtime std::ifstream srcFile("mMatrix.cl"); // Conferindo se ele foi aberto checkErr(srcFile.is_open() ? CL_SUCCESS : -1, "lendo mMatrix.cl"); std::string srcProg ( std::istreambuf_iterator<char>(srcFile), (std::istreambuf_iterator<char>())); const char *fonte = srcProg.c_str(); size_t tamanho = srcProg.length(); // Criando programa da fonte programa = clCreateProgramWithSource ( contexto, 1, &fonte, &tamanho, &errNum); checkErr(errNum, "clCreateProgramWithSource"); // Compilando programa errNum = clBuildProgram ( programa, nDispositivos, listaDispositivoID, NULL, NULL, NULL); if (errNum != CL_SUCCESS) { // Verificando se houve erro // Determinando o motivo do erro char logCompilacao[16384]; clGetProgramBuildInfo ( programa, listaDispositivoID[0], CL_PROGRAM_BUILD_LOG, sizeof(logCompilacao), logCompilacao, NULL); std::cerr << "Erro no kernel: " << std::endl; std::cerr << logCompilacao; checkErr(errNum, "clBuildProgram"); } // Criando o objeto do Kernel kernel = clCreateKernel ( programa, "multiplyMatrix", &errNum); checkErr(errNum, "clCreateKernel"); // Alocando Buffers Abuffer = clCreateBuffer ( contexto, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(cl_uint)*l*m, (A), &errNum); checkErr(errNum, "clCreateBuffer(A)"); Bbuffer = clCreateBuffer ( contexto, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(cl_uint)*m*n, (B), &errNum); checkErr(errNum, "clCreateBuffer(B)"); Cbuffer = clCreateBuffer ( contexto, CL_MEM_WRITE_ONLY, sizeof(cl_uint)*l*n, NULL, &errNum); checkErr(errNum, "clCreateBuffer(C)"); // Escolhendo o primeiro dispositivo e criando a fila de comando fila = clCreateCommandQueue ( contexto, listaDispositivoID[0], CL_QUEUE_PROFILING_ENABLE, &errNum); checkErr(errNum, "clCreateCommandQueue"); // Setando os argumentos da função do Kernel errNum = clSetKernelArg(kernel, 0, sizeof(cl_mem), &Abuffer); errNum |= clSetKernelArg(kernel, 1, sizeof(cl_mem), &Bbuffer); errNum |= clSetKernelArg(kernel, 2, sizeof(cl_mem), &Cbuffer); errNum |= clSetKernelArg(kernel, 3, sizeof(cl_uint), &l); errNum |= clSetKernelArg(kernel, 4, sizeof(cl_uint), &m); errNum |= clSetKernelArg(kernel, 5, sizeof(cl_uint), &n); checkErr(errNum, "clSetKernelArg"); // Definindo o número de work-items globais e locais const size_t globalWorkSize[2] = { l, n }; const size_t localWorkSize[2] = { 8, 8 }; // Enfileirando o Kernel para execução através da matriz errNum = clEnqueueNDRangeKernel ( fila, kernel, 2, NULL, globalWorkSize, localWorkSize, 0, NULL, &evento); checkErr(errNum, "clEnqueueNDRangeKernel"); cl_ulong ev_start_time=(cl_ulong)0; cl_ulong ev_end_time=(cl_ulong)0; clFinish(fila); errNum = clWaitForEvents(1, &evento); errNum |= clGetEventProfilingInfo(evento, CL_PROFILING_COMMAND_START, sizeof(cl_ulong), &ev_start_time, NULL); errNum |= clGetEventProfilingInfo(evento, CL_PROFILING_COMMAND_END, sizeof(cl_ulong), &ev_end_time, NULL); double run_time_gpu = (double)(ev_end_time - ev_start_time)/1000; // in usec errNum = clEnqueueReadBuffer ( fila, Cbuffer, CL_TRUE, 0, sizeof(cl_uint)*l*n, C, 0, NULL, NULL); checkErr(errNum, "clEnqueueReadBuffer"); /* // Imprimindo saída do resultado for(int x = l-1; x < l; x++) { for( int y=0; y<m; y++) { std::cout << A[x][y] << " "; } std::cout << std::endl; } std::cout << std::endl; for(int x = m-1; x < m; x++) { for( int y=0; y<n; y++) { std::cout << B[x][y] << " "; } std::cout << std::endl; } std::cout << std::endl; for(int x = l-1; x < l; x++) { for( int y=0; y<n; y++) { std::cout << C[x][y] << " "; } std::cout << std::endl; } */ std::cout << std::endl << std::fixed; std::cout << "Tempo de execução: " << std::setprecision(6) << run_time_gpu/1000000 << "ms"; std::cout << std::endl; std::cout << run_time_gpu*1.0e-6; std::cout << std::endl; return 0; }
/** reads the configuration file .cuterc*/ void readConfig() { QDir dir = QDir::home(); if( !dir.cd(".cute") ){ dir.cd(".cute"); QFileInfo fi(dir, ".cute"); if(fi.exists()){ if(fi.isDir()) QMessageBox::warning(qApp->mainWidget(), "CUTE", "Cannot cd into .cute"); else QMessageBox::warning(qApp->mainWidget(), "CUTE", "Cannot create directory"); } else{ QMessageBox::information(qApp->mainWidget(), "CUTE", "Creating ~/.cute directory"); if(!dir.mkdir(".cute")) QMessageBox::information(qApp->mainWidget(), "CUTE", "Could not create ~/.cute directory"); else{ dir.cd(".cute"); if(!dir.mkdir("scripts")) QMessageBox::information(qApp->mainWidget(), "CUTE", "Could not create ~/.cute/scripts directory"); if(!dir.mkdir("macros")) QMessageBox::information(qApp->mainWidget(), "CUTE", "Could not create ~/.cute/macros directory"); if(!dir.mkdir("sessions")) QMessageBox::information(qApp->mainWidget(), "CUTE", "Could not create ~/.cute/sessions directory"); } } } // if cute version >= 0.1.6 langs dir is required if( !QDir(QDir::homeDirPath()+QDir::separator()+".cute"+QDir::separator()+"langs").exists() ) { QDir destDir = QDir::home(); destDir.cd(".cute"); destDir.mkdir("langs"); destDir.cd("langs"); QDir srcDir(LANG_DIR); QString data; QStringList dirList = srcDir.entryList(); for( int i = 2; i < dirList.count(); i++) if( QFileInfo(srcDir.absPath()+QDir::separator()+dirList[i]).isFile()) { QFile srcFile(srcDir.absPath()+QDir::separator()+dirList[i]); QFile destFile(destDir.absPath()+QDir::separator()+dirList[i]); if(destFile.exists()) continue; QTextStream destStream(&destFile); QTextStream srcStream(&srcFile); srcFile.open(IO_ReadOnly); destFile.open(IO_WriteOnly); data = srcStream.read(); destStream << data; srcFile.close(); destFile.close(); } } QFile file(QDir::homeDirPath()+"/.cuterc"); if(!file.exists()){ QMessageBox::information(qApp->mainWidget(), "CUTE", "Creating ~/.cuterc"); file.open(IO_ReadOnly); file.close(); return; } //FILE *c_file = fopen("/home/heiko/.cuterc", "r"); //PyRun_SimpleFile(c_file, ".cuterc"); QString const_cmd("execfile(\".cuterc\")\n"); dir = QDir::current(); QDir::setCurrent( QDir::homeDirPath() ); char *cmd = new char[1024]; strcpy(cmd, const_cmd.latin1()); PyRun_SimpleString(cmd); // read language config files QDir langDir = QDir(QDir::homeDirPath()+QDir::separator()+".cute"+QDir::separator()+"langs"); QStringList langEntryList = langDir.entryList(); QString langFile; for( int i = 2; i < langEntryList.count(); i++ ){ QString langFile = langDir.absPath()+QDir::separator()+langEntryList[i]; QFileInfo fi(langDir, langFile); if(fi.isFile()){ langFile = QString("execfile(\"")+langFile+QString("\")\n"); char *cmd = strdup(langFile); PyRun_SimpleString( cmd ); } } QDir::setCurrent( dir.absPath() ); }
bool CloneThread::cloneFiles(const QStringList &absoluteSourceFiles, const QStringList &absoluteDestinationFiles, const quint64 totalSize) { if (absoluteSourceFiles.length() != absoluteDestinationFiles.length()) { mError = tr("Amount of source files not equals to amount of destination files"); qCritical() << "Error:" << mError; return false; } char buffer[BUFFER_SIZE]; quint64 totalProgress = 0; qint64 timeStart = QDateTime::currentMSecsSinceEpoch(); for (int i=0; !mTerminated && i<absoluteSourceFiles.length(); ++i) { QString srcFileName = absoluteSourceFiles.at(i); QString destFileName = absoluteDestinationFiles.at(i); qDebug() << "Cloning:" << srcFileName; QFile srcFile(srcFileName); QFile destFile(destFileName); if (!srcFile.exists()) { mError = tr("File not found: %1").arg(QDir::toNativeSeparators(srcFileName)); qCritical() << "Error:" << mError; return false; } QString destFilePath = destFileName.left(destFileName.lastIndexOf("/")); if (!QDir().mkpath(destFilePath)) { mError = tr("Impossible to create path: %1").arg(QDir::toNativeSeparators(destFilePath)); qCritical() << "Error:" << mError; return false; } if (!srcFile.open(QIODevice::ReadOnly)) { mError = tr("Impossible to open file: %1").arg(QDir::toNativeSeparators(srcFileName)); qCritical() << "Error:" << mError; return false; } if (!destFile.open(QIODevice::WriteOnly)) { mError = tr("Impossible to create file: %1").arg(QDir::toNativeSeparators(destFileName)); qCritical() << "Error:" << mError; return false; } quint64 fileProgress = 0; quint64 fileSize = srcFile.size(); while (!mTerminated && !srcFile.atEnd()) { qint64 bytes = srcFile.read(buffer, BUFFER_SIZE); if (bytes < 0) { mError = tr("Impossible to read file: %1").arg(QDir::toNativeSeparators(srcFileName)); qCritical() << "Error:" << mError; return false; } if (destFile.write(buffer, bytes) != bytes) { mError = tr("Impossible to write file: %1").arg(QDir::toNativeSeparators(destFileName)); qCritical() << "Error:" << mError; return false; } fileProgress += bytes; totalProgress += bytes; if (fileSize && totalSize) { qint64 curTime = QDateTime::currentMSecsSinceEpoch(); if (curTime > timeStart + 1000) { timeStart = curTime; emit OnProgressChanged(srcFileName, fileProgress * 100 / fileSize, totalProgress * 100 / totalSize); } } } srcFile.close(); destFile.close(); } return !mTerminated; }
bool ModelImport::ImportObj(const std::string& srcFilename, std::string& dstFilename) { const AssetLib::AssetDef& rAssetDef = AssetLib::Model::GetAssetDef(); std::ifstream srcFile(srcFilename); assert(srcFile.is_open()); std::ofstream dstFile(dstFilename, std::ios::binary); assert(dstFile.is_open()); // Write header AssetLib::BinFileHeader header; header.binUID = AssetLib::BinFileHeader::kUID; header.assetUID = rAssetDef.GetAssetUID(); header.version = rAssetDef.GetBinVersion(); header.srcHash = Hashing::SHA1(); dstFile.write((char*)&header, sizeof(header)); // Build and write the main geo data GeoData geo; ObjData obj; char line[1024]; int lineNum = 0; // for debugging while (srcFile.getline(line, 1024)) { ++lineNum; char* context = nullptr; char* tok = strtok_s(line, " ", &context); if (strcmp(tok, "v") == 0) { // Position Vec3 pos; pos.x = (float)atof(strtok_s(nullptr, " ", &context)); pos.y = (float)atof(strtok_s(nullptr, " ", &context)); pos.z = (float)atof(strtok_s(nullptr, " ", &context)); obj.positions.push_back(pos); } else if (strcmp(tok, "vn") == 0) { // Normal Vec3 norm; norm.x = (float)atof(strtok_s(nullptr, " ", &context)); norm.y = (float)atof(strtok_s(nullptr, " ", &context)); norm.z = (float)atof(strtok_s(nullptr, " ", &context)); obj.normals.push_back(norm); } else if (strcmp(tok, "vt") == 0) { // Tex coord Vec2 uv; uv.x = (float)atof(strtok_s(nullptr, " ", &context)); uv.y = (float)atof(strtok_s(nullptr, " ", &context)); obj.texcoords.push_back(uv); } else if (strcmp(tok, "f") == 0) { // Face for (int i = 0; i < 3; ++i) { ObjVertex objVert; objVert.iPos = atoi(strtok_s(nullptr, "/ ", &context)) - 1; objVert.iUv = atoi(strtok_s(nullptr, "/ ", &context)) - 1; objVert.iNorm = atoi(strtok_s(nullptr, "/ ", &context)) - 1; // Find matching vert to re-use. int reuseIndex = -1; for (int v = (int)obj.verts.size() - 1; v >= 0; --v) { const ObjVertex& otherVert = obj.verts[v]; if (otherVert.iPos == objVert.iPos && otherVert.iUv == objVert.iUv && otherVert.iNorm == objVert.iNorm) { reuseIndex = v; break; } } if (reuseIndex >= 0) { geo.indices.push_back((uint16)reuseIndex); } else { geo.indices.push_back((uint16)geo.positions.size()); Color color = { 1.f, 1.f, 1.f, 1.f }; geo.positions.push_back(obj.positions[objVert.iPos]); geo.texcoords.push_back(obj.texcoords[objVert.iUv]); geo.normals.push_back(obj.normals[objVert.iNorm]); geo.colors.push_back(color); obj.verts.push_back(objVert); } } } else if (strcmp(tok, "usemtl") == 0) { std::string material = strtok_s(nullptr, " ", &context); obj.materials.push_back(material); obj.subobjectStartIndices.push_back((uint)geo.indices.size()); } } obj.subobjectStartIndices.push_back((uint)geo.indices.size()); geo.tangents.resize(geo.positions.size()); geo.bitangents.resize(geo.positions.size()); // TODO: Tangents/bitangents for shared verts for (uint i = 0; i < geo.indices.size(); i += 3) { uint v0 = geo.indices[i + 0]; uint v1 = geo.indices[i + 1]; uint v2 = geo.indices[i + 2]; const Vec3& pos0 = geo.positions[v0]; const Vec3& pos1 = geo.positions[v1]; const Vec3& pos2 = geo.positions[v2]; const Vec2& uv0 = geo.texcoords[v0]; const Vec2& uv1 = geo.texcoords[v1]; const Vec2& uv2 = geo.texcoords[v2]; Vec3 edge1 = pos1 - pos0; Vec3 edge2 = pos2 - pos0; Vec2 uvEdge1 = uv1 - uv0; Vec2 uvEdge2 = uv2 - uv0; float r = 1.f / (uvEdge1.y * uvEdge2.x - uvEdge1.x * uvEdge2.y); Vec3 tangent = (edge1 * -uvEdge2.y + edge2 * uvEdge1.y) * r; Vec3 bitangent = (edge1 * -uvEdge2.x + edge2 * uvEdge1.x) * r; tangent = Vec3Normalize(tangent); bitangent = Vec3Normalize(bitangent); geo.tangents[v0] = geo.tangents[v1] = geo.tangents[v2] = tangent; geo.bitangents[v0] = geo.bitangents[v1] = geo.bitangents[v2] = bitangent; } // Calc radius Vec3 vMin(FLT_MAX, FLT_MAX, FLT_MAX); Vec3 vMax(-FLT_MIN, -FLT_MIN, -FLT_MIN); for (int i = (int)geo.positions.size() - 1; i >= 0; --i) { vMin.x = std::min(geo.positions[i].x, vMin.x); vMax.x = std::max(geo.positions[i].x, vMax.x); vMin.y = std::min(geo.positions[i].y, vMin.y); vMax.y = std::max(geo.positions[i].y, vMax.y); vMin.z = std::min(geo.positions[i].z, vMin.z); vMax.z = std::max(geo.positions[i].z, vMax.z); } Vec3 modelBoundsMin(FLT_MAX, FLT_MAX, FLT_MAX); Vec3 modelBoundsMax(-FLT_MIN, -FLT_MIN, -FLT_MIN); uint totalVertCount = 0; for (int i = 0; i < obj.subobjectStartIndices.size() - 1; ++i) { AssetLib::Model::SubObject subobj; strcpy_s(subobj.materialName, obj.materials[i].c_str()); subobj.indexCount = obj.subobjectStartIndices[i + 1] - obj.subobjectStartIndices[i]; uint16 vertMin = -1; uint16 vertMax = 0; subobj.boundsMin = Vec3(FLT_MAX, FLT_MAX, FLT_MAX); subobj.boundsMax = Vec3(-FLT_MIN, -FLT_MIN, -FLT_MIN); for (uint tri = obj.subobjectStartIndices[i]; tri < obj.subobjectStartIndices[i + 1]; ++tri) { uint16 iVert = geo.indices[tri]; vertMin = std::min(iVert, vertMin); vertMax = std::max(iVert, vertMax); subobj.boundsMin.x = std::min(geo.positions[iVert].x, subobj.boundsMin.x); subobj.boundsMax.x = std::max(geo.positions[iVert].x, subobj.boundsMax.x); subobj.boundsMin.y = std::min(geo.positions[iVert].y, subobj.boundsMin.y); subobj.boundsMax.y = std::max(geo.positions[iVert].y, subobj.boundsMax.y); subobj.boundsMin.z = std::min(geo.positions[iVert].z, subobj.boundsMin.z); subobj.boundsMax.z = std::max(geo.positions[iVert].z, subobj.boundsMax.z); } subobj.vertCount = (vertMax - vertMin) + 1; totalVertCount += subobj.vertCount; modelBoundsMin = Vec3Min(modelBoundsMin, subobj.boundsMin); modelBoundsMax = Vec3Max(modelBoundsMax, subobj.boundsMax); geo.subobjects.push_back(subobj); } assert(totalVertCount == (uint)geo.positions.size()); AssetLib::Model modelBin; modelBin.totalVertCount = totalVertCount; modelBin.totalIndexCount = (uint)geo.indices.size(); modelBin.boundsMin = modelBoundsMin; modelBin.boundsMax = modelBoundsMax; modelBin.subObjectCount = (uint)geo.subobjects.size(); modelBin.subobjects.offset = 0; modelBin.positions.offset = modelBin.subobjects.offset + modelBin.subobjects.CalcSize(modelBin.subObjectCount); modelBin.texcoords.offset = modelBin.positions.offset + modelBin.positions.CalcSize(totalVertCount); modelBin.normals.offset = modelBin.texcoords.offset + modelBin.texcoords.CalcSize(totalVertCount); modelBin.colors.offset = modelBin.normals.offset + modelBin.normals.CalcSize(totalVertCount); modelBin.tangents.offset = modelBin.colors.offset + modelBin.colors.CalcSize(totalVertCount); modelBin.bitangents.offset = modelBin.tangents.offset + modelBin.tangents.CalcSize(totalVertCount); modelBin.indices.offset = modelBin.bitangents.offset + modelBin.bitangents.CalcSize(totalVertCount); dstFile.write((char*)&modelBin, sizeof(AssetLib::Model)); dstFile.write((char*)geo.subobjects.data(), sizeof(geo.subobjects[0]) * geo.subobjects.size()); dstFile.write((char*)geo.positions.data(), sizeof(geo.positions[0]) * geo.positions.size()); dstFile.write((char*)geo.texcoords.data(), sizeof(geo.texcoords[0]) * geo.texcoords.size()); dstFile.write((char*)geo.normals.data(), sizeof(geo.normals[0]) * geo.normals.size()); dstFile.write((char*)geo.colors.data(), sizeof(geo.colors[0]) * geo.colors.size()); dstFile.write((char*)geo.tangents.data(), sizeof(geo.tangents[0]) * geo.tangents.size()); dstFile.write((char*)geo.bitangents.data(), sizeof(geo.bitangents[0]) * geo.bitangents.size()); dstFile.write((char*)geo.indices.data(), sizeof(geo.indices[0]) * geo.indices.size()); return true; }
int main(int argc, char *argv[]) { qInstallMsgHandler(myMessageHandler); QCoreApplication app(argc, argv); if (argc != 3) { qCritical("Usage: autotranslate <destination-dir> <source-dir>."); return -1; } QDir dstDir(app.arguments().value(1)); if (!dstDir.exists()) { qCritical("Destination directory '%s' not found.",dstDir.dirName().toLocal8Bit().constData()); return -1; } QDir srcDir(app.arguments().value(2),"*.ts",QDir::Name,QDir::Files); if (!srcDir.exists()) { qCritical("Source directory '%s' not found.",srcDir.dirName().toLocal8Bit().constData()); return -1; } QDirIterator srcIt(srcDir); while (srcIt.hasNext()) { QFile srcFile(srcIt.next()); if (srcFile.open(QFile::ReadOnly)) { QDomDocument doc; if (doc.setContent(&srcFile,true)) { qDebug("Generation auto translation from '%s'.",srcFile.fileName().toLocal8Bit().constData()); QDomElement rootElem = doc.firstChildElement("TS"); rootElem.setAttribute("language",rootElem.attribute("sourcelanguage","en")); QDomElement contextElem = rootElem.firstChildElement("context"); while(!contextElem.isNull()) { QDomElement messageElem = contextElem.firstChildElement("message"); while(!messageElem.isNull()) { QDomElement sourceElem = messageElem.firstChildElement("source"); QDomElement translationElem = messageElem.firstChildElement("translation"); if (!sourceElem.isNull() && !translationElem.isNull()) { QString sourceText = sourceElem.text(); if (messageElem.attribute("numerus") == "yes") { QDomElement numerusEelem = translationElem.firstChildElement("numerusform"); while(!numerusEelem.isNull()) { numerusEelem.removeChild(numerusEelem.firstChild()); numerusEelem.appendChild(doc.createTextNode(sourceText)); numerusEelem = numerusEelem.nextSiblingElement("numerusform"); } } else { translationElem.removeChild(translationElem.firstChild()); translationElem.appendChild(doc.createTextNode(sourceText)); } translationElem.removeAttribute("type"); } messageElem = messageElem.nextSiblingElement("message"); } contextElem = contextElem.nextSiblingElement("context"); } srcFile.close(); QFileInfo srcFileInfo(srcDir.absoluteFilePath(srcFile.fileName())); QFile dstFile(dstDir.absoluteFilePath(srcFileInfo.fileName())); if (dstFile.open(QFile::WriteOnly|QFile::Truncate)) { dstFile.write(doc.toByteArray()); dstFile.close(); } else { qWarning("Failed to open destination file '%s' for write.",dstFile.fileName().toLocal8Bit().constData()); } } else { qWarning("Invalid translation source file '%s'.",srcFile.fileName().toLocal8Bit().constData()); } srcFile.close(); } else { qWarning("Could not open translation source file '%s'.",srcFile.fileName().toLocal8Bit().constData()); } } return 0; }
nsresult nsEudoraMailbox::ImportMailbox(uint32_t *pBytes, bool *pAbort, const PRUnichar *pName, nsIFile *pSrc, nsIMsgFolder *dstFolder, int32_t *pMsgCount) { nsCOMPtr<nsIFile> tocFile; nsCOMPtr<nsIInputStream> srcInputStream; nsCOMPtr<nsIInputStream> tocInputStream; nsCOMPtr<nsIOutputStream> mailOutputStream; bool importWithoutToc = true; bool deleteToc = false; nsCOMPtr<nsIFile> mailFile; if (pMsgCount) *pMsgCount = 0; nsresult rv = pSrc->GetFileSize(&m_mailSize); rv = NS_NewLocalFileInputStream(getter_AddRefs(srcInputStream), pSrc); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr<nsIFile> srcFile(pSrc); // First, get the index file for this mailbox rv = FindTOCFile(pSrc, getter_AddRefs(tocFile), &deleteToc); if (NS_SUCCEEDED(rv) && tocFile) { IMPORT_LOG0("Reading euroda toc file: "); DUMP_FILENAME(tocFile, true); // Read the toc and import the messages rv = ImportMailboxUsingTOC(pBytes, pAbort, srcInputStream, tocFile, dstFolder, pMsgCount); // clean up if (deleteToc) DeleteFile(tocFile); // If we were able to import with the TOC, then we don't need to bother // importing without the TOC. if (NS_SUCCEEDED(rv)) { importWithoutToc = false; IMPORT_LOG0("Imported mailbox: "); DUMP_FILENAME(pSrc, false); IMPORT_LOG0(" Using TOC: "); DUMP_FILENAME(tocFile, true); } else { IMPORT_LOG0("*** Error importing with TOC - will import without TOC.\n"); } } // pSrc must be Released before returning if (importWithoutToc) { // The source file contains partially constructed mail messages, // and attachments. We should first investigate if we can use the mailnews msgCompose // stuff to do the work for us. If not we have to scan the mailboxes and do TONS // of work to properly reconstruct the message - Eudora is so nice that it strips things // like MIME headers, character encoding, and attachments - beautiful! rv = pSrc->GetFileSize(&m_mailSize); SimpleBufferTonyRCopiedOnce readBuffer; SimpleBufferTonyRCopiedOnce headers; SimpleBufferTonyRCopiedOnce body; SimpleBufferTonyRCopiedOnce copy; headers.m_convertCRs = true; body.m_convertCRs = true; copy.Allocate(kCopyBufferSize); readBuffer.Allocate(kMailReadBufferSize); ReadFileState state; state.offset = 0; state.size = m_mailSize; state.pFile = pSrc; IMPORT_LOG0("Reading mailbox\n"); if (NS_SUCCEEDED(rv)) { nsCString defaultDate; nsAutoCString bodyType; IMPORT_LOG0("Reading first message\n"); nsCOMPtr<nsIOutputStream> outputStream; nsCOMPtr<nsIMsgPluggableStore> msgStore; rv = dstFolder->GetMsgStore(getter_AddRefs(msgStore)); NS_ENSURE_SUCCESS(rv, rv); while (!*pAbort && NS_SUCCEEDED(rv = ReadNextMessage( &state, readBuffer, headers, body, defaultDate, bodyType, NULL))) { if (pBytes) *pBytes += body.m_writeOffset - 1 + headers.m_writeOffset - 1; nsCOMPtr<nsIMsgDBHdr> msgHdr; bool reusable; rv = msgStore->GetNewMsgOutputStream(dstFolder, getter_AddRefs(msgHdr), &reusable, getter_AddRefs(outputStream)); if (NS_FAILED(rv)) break; rv = ImportMessage(headers, body, defaultDate, bodyType, outputStream, pMsgCount); if (NS_SUCCEEDED(rv)) msgStore->FinishNewMessage(outputStream, msgHdr); else { msgStore->DiscardNewMessage(outputStream, msgHdr); IMPORT_LOG0( "*** Error importing message\n"); } if (!reusable) outputStream->Close(); if (!readBuffer.m_bytesInBuf && (state.offset >= state.size)) break; } if (outputStream) outputStream->Close(); } else { IMPORT_LOG0("*** Error creating file spec for composition\n"); } } return rv; }
// main() for simple buffer and sub-buffer example // int main(int argc, char** argv) { std::cout << "Simple Image Processing Example" << std::endl; // First, select an OpenCL platform to run on. errNum = clGetPlatformIDs(0, NULL, &numPlatforms); checkErr( (errNum != CL_SUCCESS) ? errNum : (numPlatforms <= 0 ? -1 : CL_SUCCESS), "clGetPlatformIDs"); platformIDs = (cl_platform_id *)alloca(sizeof(cl_platform_id) * numPlatforms); std::cout << "Number of platforms: \t" << numPlatforms << std::endl; errNum = clGetPlatformIDs(numPlatforms, platformIDs, NULL); checkErr( (errNum != CL_SUCCESS) ? errNum : (numPlatforms <= 0 ? -1 : CL_SUCCESS), "clGetPlatformIDs"); std::ifstream srcFile("gaussian_filter.cl"); checkErr(srcFile.is_open() ? CL_SUCCESS : -1, "reading simple.cl"); std::string srcProg( std::istreambuf_iterator<char>(srcFile), (std::istreambuf_iterator<char>())); const char * src = srcProg.c_str(); size_t length = srcProg.length(); deviceIDs = NULL; DisplayPlatformInfo( platformIDs[PLATFORM_INDEX], CL_PLATFORM_VENDOR, "CL_PLATFORM_VENDOR"); errNum = clGetDeviceIDs( platformIDs[PLATFORM_INDEX], CL_DEVICE_TYPE_ALL, 0, NULL, &numDevices); if (errNum != CL_SUCCESS && errNum != CL_DEVICE_NOT_FOUND){ checkErr(errNum, "clGetDeviceIDs"); } deviceIDs = (cl_device_id *)alloca(sizeof(cl_device_id) * numDevices); errNum = clGetDeviceIDs( platformIDs[PLATFORM_INDEX], CL_DEVICE_TYPE_ALL, numDevices, &deviceIDs[0], NULL); checkErr(errNum, "clGetDeviceIDs"); cl_context_properties contextProperties[] = { CL_CONTEXT_PLATFORM, (cl_context_properties)platformIDs[PLATFORM_INDEX], 0 }; context = clCreateContext( contextProperties, numDevices, deviceIDs, NULL, NULL, &errNum); checkErr(errNum, "clCreateContext"); // Create program from source program = clCreateProgramWithSource( context, 1, &src, &length, &errNum); checkErr(errNum, "clCreateProgramWithSource"); // Build program errNum = clBuildProgram( program, numDevices, deviceIDs, "-I.", NULL, NULL); if (errNum != CL_SUCCESS){ // Determine the reason for the error char buildLog[16384]; clGetProgramBuildInfo( program, deviceIDs[0], CL_PROGRAM_BUILD_LOG, sizeof(buildLog), buildLog, NULL); std::cerr << "Error in OpenCL C source: " << std::endl; std::cerr << buildLog; checkErr(errNum, "clBuildProgram"); } // Create a command commands // if(!(commands = clCreateCommandQueue(context, deviceIDs[0], 0, &errNum))) { std::cout << "Failed to create a command commands!" << std::endl; cleanKill(EXIT_FAILURE); } cl_kernel kernel = clCreateKernel(program, "gaussian_filter", &errNum); checkErr(errNum, "clCreateKernel(gaussian_filter)"); if(!doesGPUSupportImageObjects){ cleanKill(EXIT_FAILURE); } inputImage = LoadImage(context, (char*)"rgba.png", width, height); cl_image_format format; format.image_channel_order = CL_RGBA; format.image_channel_data_type = CL_UNORM_INT8; outputImage = clCreateImage2D(context, CL_MEM_WRITE_ONLY, &format, width, height, 0, NULL, &errNum); if(there_was_an_error(errNum)){ std::cout << "Output Image Buffer creation error!" << std::endl; cleanKill(EXIT_FAILURE); } if (!inputImage || !outputImage ){ std::cout << "Failed to allocate device memory!" << std::endl; cleanKill(EXIT_FAILURE); } char *buffer = new char [width * height * 4]; size_t origin[3] = { 0, 0, 0 }; size_t region[3] = { width, height, 1}; sampler = clCreateSampler(context, CL_FALSE, // Non-normalized coordinates CL_ADDRESS_CLAMP_TO_EDGE, CL_FILTER_NEAREST, &errNum); if(there_was_an_error(errNum)){ std::cout << "Error creating CL sampler object." << std::endl; cleanKill(EXIT_FAILURE); } // Set the kernel arguments errNum = clSetKernelArg(kernel, 0, sizeof(cl_mem), &inputImage); errNum |= clSetKernelArg(kernel, 1, sizeof(cl_mem), &outputImage); errNum |= clSetKernelArg(kernel, 2, sizeof(cl_sampler), &sampler); errNum |= clSetKernelArg(kernel, 3, sizeof(cl_int), &width); errNum |= clSetKernelArg(kernel, 4, sizeof(cl_int), &height); if (errNum != CL_SUCCESS) { std::cerr << "Error setting kernel arguments." << std::endl; std::cerr << print_cl_errstring(errNum) << std::endl; cleanKill(EXIT_FAILURE); } //errNum = clGetKernelWorkGroupInfo(kernel, deviceIDs, CL_KERNEL_WORK_GROUP_SIZE, sizeof(unsigned short)* height*width*4, &local, NULL); // if (errNum != CL_SUCCESS) // { // cout << print_cl_errstring(err) << endl; // if(err == CL_INVALID_VALUE){ // cout << "if param_name is not valid, or if size in bytes specified by param_value_size " // << "is less than the size of return type as described in the table above and " // << "param_value is not NULL." << endl; // } // cout << "Error: Failed to retrieve kernel work group info!" << err << endl; // cleanKill(EXIT_FAILURE); // } std::cout << "Max work group size is " << CL_DEVICE_MAX_WORK_GROUP_SIZE << std::endl; std::cout << "Max work item size is " << CL_DEVICE_MAX_WORK_ITEM_SIZES << std::endl; size_t localWorkSize[2]; size_t globalWorkSize[2]; localWorkSize[0] = 1; localWorkSize[1] = localWorkSize[0]; globalWorkSize[0] = width*height; globalWorkSize[1] = globalWorkSize[0]; //CL_INVALID_WORK_GROUP_SIZE if local_work_size is specified and number of work-items specified by global_work_size is not evenly divisable by size of work-group given by local_work_size //size_t globalWorkSize[2] = { RoundUp(localWorkSize[0], width), RoundUp(localWorkSize[1], height)}; // size_t globalWorkSize[1] = {sizeof(unsigned short)* height * width}; // size_t localWorkSize[1] = {64}; // Queue the kernel up for execution errNum = clEnqueueNDRangeKernel(commands, kernel, 2, NULL, globalWorkSize, localWorkSize, 0, NULL, NULL); if (errNum != CL_SUCCESS){ std::cerr << "Error queuing kernel for execution." << std::endl; std::cerr << print_cl_errstring(errNum) << std::endl; cleanKill(EXIT_FAILURE); } // Wait for the command commands to get serviced before reading back results // clFinish(commands); // Read back computed data errNum = clEnqueueReadImage(commands, outputImage, CL_TRUE, origin, region, 0, 0, buffer, 0, NULL, NULL); SaveImage((char*)"outRGBA.png", (char*)buffer, width, height); std::cout << "Program completed successfully" << std::endl; return 0; }