void ofxRGBDCaptureGui::loadDefaultDirectory(){ //create it if it doesn't exist string defaultDir = "depthframes"; if(!ofDirectory(defaultDir).exists()){ ofDirectory(defaultDir).create(true); } loadDirectory(defaultDir); }
//-------------------------------------------------------------- bool testApp::loadVideoFile(string hiResPath, string lowResPath){ hasHiresVideo = (hiResPath != ""); if(hasHiresVideo){ if(hiResPlayer != NULL){ delete hiResPlayer; } hiResPlayer = new ofVideoPlayer(); if(!hiResPlayer->loadMovie(hiResPath)){ ofSystemAlertDialog("Load Failed -- Couldn't load hi res video file."); return false; } } //must at least have a low res player //string lowResPath = ofFilePath::removeExt(path) + "_small.mov"; if(lowResPlayer != NULL){ delete lowResPlayer; } lowResPlayer = new ofVideoPlayer(); if(!lowResPlayer->loadMovie(lowResPath)){ ofSystemAlertDialog("Load Failed -- Couldn't load low res video file."); return false; } if(hasHiresVideo){ renderer.setTextureScale(1.0*lowResPlayer->getWidth()/hiResPlayer->getWidth(), 1.0*lowResPlayer->getHeight()/hiResPlayer->getHeight()); } else { //refer to the calibration stats float fullsizedWidth = renderer.getRGBCalibration().getDistortedIntrinsics().getImageSize().width; float fullsizedHeight = renderer.getRGBCalibration().getDistortedIntrinsics().getImageSize().height; cout << "image size is " << fullsizedWidth << " " << fullsizedHeight << endl; renderer.setTextureScale(1.0*lowResPlayer->getWidth()/fullsizedWidth, 1.0*lowResPlayer->getHeight()/fullsizedHeight); } renderer.setRGBTexture(*lowResPlayer); string videoThumbsPath = ofFilePath::removeExt(lowResPath); if(!ofDirectory(videoThumbsPath).exists()){ ofDirectory(videoThumbsPath).create(true); } videoTimelineElement.setup(); // timeline.setDurationInFrames(lowResPlayer->getTotalNumFrames()); videoTimelineElement.setVideoPlayer(*lowResPlayer, videoThumbsPath); lowResPlayer->play(); lowResPlayer->setSpeed(0); return true; }
void ofxDepthImageRecorder::updateTakes(){ for(int i = 0; i < takes.size(); i++){ delete takes[i]; } takes.clear(); cout << "updating takes " << endl; ofDirectory dir = ofDirectory(targetDirectory); dir.listDir(); dir.sort(); for(int i = 0; i < dir.numFiles(); i++){ if(dir.getName(i) == "_calibration" || dir.getName(i) == "_RenderBin"){ continue; } ofxRGBDScene* t = new ofxRGBDScene(); t->loadFromFolder(dir.getPath(i)); if(t->hasDepth){ takes.push_back(t); } else{ ofLogWarning("ofxDepthImageRecorder::updateTakes -- Take " + dir.getPath(i) + " has no depth images"); delete t; } } encoderThread.lock(); for(int i = 0; i < takes.size(); i++){ encodeDirectories.push( takes[i] ); } encoderThread.unlock(); }
//---------- void Register::traverseDirectoryImages(string dataPath, vector<string> outputNamespace) { if (ofDirectory::doesDirectoryExist(dataPath)) { ofDirectory files; files.listDir(dataPath); for (int i = 0; i<files.size(); i++) { const auto filename = files.getPath(i); auto outputName = ofFilePath::getBaseName(filename); //check if it's a subfolder if (ofDirectory(filename).isDirectory()) { auto innerNamespace = outputNamespace; innerNamespace.push_back(outputName); this->traverseDirectoryImages(dataPath + "/" + outputName, innerNamespace); } //if not, check whether it has the right extension const auto extension = ofFilePath::getFileExt(filename); if (!(extension == "png" || extension == "jpeg" || extension == "jpg")) { continue; } //transform the output name to include namespace transformName(outputName, outputNamespace); //insert and load the image if (this->images.find(outputName) != this->images.end()) { continue; } this->images.insert(pair<string, ofImage>(outputName, ofImage())); this->images[outputName].loadImage(filename); ofLogNotice("ofxAssets") << "Loaded image asset '" << outputName << "'" << endl; } } }
void ofxDepthImageRecorder::incrementTake(){ char takeString[1024] ; sprintf(takeString, "TAKE_%02d_%02d_%02d_%02d_%02d", ofGetMonth(), ofGetDay(), ofGetHours(), ofGetMinutes(), ofGetSeconds()); currentFolderPrefix = string(takeString); ofDirectory dir(targetDirectory + "/" + currentFolderPrefix); dir.create(true); ofDirectory depthDir = ofDirectory(dir.getOriginalDirectory() + "/depth/"); depthDir.create(true); //create a color folder for good measure ofDirectory colorDir = ofDirectory(dir.getOriginalDirectory() + "/color/"); colorDir.create(true); currentFrame = 0; recordingStartTime = msaTimer.getAppTimeMillis(); }
//-------------------------------------------------------------- void testApp::setup(){ //// utils char tmpstr[2000]; ofFile f = ofFile(); ofDirectory dir = ofDirectory(); /// indexes rota = 0; nimg = 0; nsnd = 9; image_duration = 0.1; image_timer = 0; silence_timer = 0; silence_trigger = false; //// LOAD IMAGES string rep_images = "intelligentsia/images/"; dir.open(rep_images); dir.allowExt("jpg"); dir.listDir(); Nimgs = dir.numFiles(); cout << Nimgs << endl; for (int i = 0; i < Nimgs; i++){ sprintf(tmpstr, "%s_%dx%d.jpeg",dir.getPath(i).c_str(), ofGetScreenWidth(), ofGetScreenHeight()); if (f.doesFileExist(tmpstr)) images[i].loadImage(tmpstr); else { images[i].loadImage(dir.getPath(i)); pt = scaleSize(images[i].width, images[i].height, ofGetScreenWidth(), ofGetScreenHeight()); images[i].resize(pt.x,pt.y); cout << "will save" << tmpstr << endl; images[i].saveImage(tmpstr); } cout << dir.getPath(i) << endl; }; //// LOAD SOUND string rep_sounds = "intelligentsia/sons/"; dir.open(rep_sounds); dir.allowExt("wav"); dir.listDir(); Nsnds = dir.numFiles(); cout << Nsnds << endl; for (int i = 0; i < Nsnds; i++){ sounds[i].loadSound(dir.getPath(i)); cout << dir.getPath(i) << endl; }; sounds[nsnd].play(); // GRAPHICS ofHideCursor(); ofSetFrameRate(120); ofSetVerticalSync(true); }
void ofApp::playRandomTrack(string dirPath) { dir = ofDirectory(dirPath); dir.listDir(); string song = dir.getPath(ofRandom(dir.size())); songName = ofFilePath::getBaseName(song); //plays a random file from the directory NewNoise.load(song); NewNoise.play(); ofLog() << songName; }
//-------------------------------------------------------------- void testApp::keyPressed(int key){ if(timeline.isModal()){ return; } if(key == ' '){ timeline.togglePlay(); } if(key == 'T'){ camTrack.addKeyframe(); } if(key == 'L'){ camTrack.lockCameraToTrack = !camTrack.lockCameraToTrack; if(!camTrack.lockCameraToTrack){ cam.setAnglesFromOrientation(); } } if(key == 'R'){ rendering = !rendering; if(rendering){ currentFrameNumber = 0; char fileName[1024]; sprintf(fileName, "frame_%02d_%02d_%02d/", ofGetDay(), ofGetHours(), ofGetMinutes() ); renderFolder = string(fileName); ofDirectory(renderFolder).create(true); } timeline.stop(); player.getVideoPlayer()->stop(); timeline.setPercentComplete(timeline.getInOutRange().min); timeline.play(); } if(key == 'f'){ ofToggleFullscreen(); } if(key == 'S'){ loadShader(); } if(key == '1'){ particleRenderer.sampleTextureColors(player.getVideoPlayer()->getPixelsRef()); } if(key == 'P'){ generateAmbientParticles(); } }
void ofApp::loadImages() { imagesDir = ofDirectory("Head-Images/"); imagesDir.allowExt("png"); imagesDir.listDir(); for (int i = 0; i < imagesDir.size(); i++) { ofImage * anImage = new ofImage(imagesDir.getPath(i)); images.push_back(anImage); } }
//---------- void Register::traverseDirectoryShaders(string dataPath, vector<string> outputNamespace) { if (ofDirectory::doesDirectoryExist(dataPath)) { ofDirectory files; files.listDir(dataPath); for (int i = 0; i<files.size(); i++) { const auto filename = files.getPath(i); auto outputName = ofFilePath::getBaseName(filename); //check if it's a subfolder if (ofDirectory(filename).isDirectory()) { auto innerNamespace = outputNamespace; innerNamespace.push_back(outputName); this->traverseDirectoryShaders(dataPath + "/" + outputName, innerNamespace); } //if not, check whether it has the right extension const auto extension = ofFilePath::getFileExt(filename); if (!(extension == "vert" || extension == "frag" || extension == "geom")) { continue; } //transform the output name to include namespace transformName(outputName, outputNamespace); //check if the shader already exists (this often happens when you hit a .vert file and we've already loaded when we hit the .geom) if (this->shaders.find(outputName) != this->shaders.end()) { continue; } //insert the shader this->shaders.insert(pair<string, ofShader>(outputName, ofShader())); auto & shader = this->shaders[outputName]; //load any available shader stages const auto withoutExtension = filename.substr(0, filename.length() - extension.length() - 1); if (ofFile::doesFileExist(withoutExtension + ".frag")) shader.setupShaderFromFile(GL_FRAGMENT_SHADER, withoutExtension + ".frag"); if (ofFile::doesFileExist(withoutExtension + ".vert")) shader.setupShaderFromFile(GL_VERTEX_SHADER, withoutExtension + ".vert"); #ifndef TARGET_IPHONE_SIMULATOR if (ofFile::doesFileExist(withoutExtension + ".geom")) shader.setupShaderFromFile(GL_GEOMETRY_SHADER, withoutExtension + ".geom"); #endif shader.linkProgram(); ofLogNotice("ofxAssets") << "Loaded shader asset '" << outputName << "'" << endl; } } }
void Menu::loadMenuItems(ofDirectory directory, ofPtr< MenuItem > currentItem){ // Each directory in the Presentations directory is a MenuItem: // - Directories with a presentation.xml file are Presentations. // - Directories with subdirectories are Categories. int i, size; // Check if there is a presentation.xml file. directory.listDir(); directory.sort(); size = directory.size(); for(i = 0; i < size; i++){ ofFile file = directory.getFile(i); if (file.isDirectory()){ ofPtr<MenuItem> item(new MenuItem()); item->name = file.getFileName(); item->parent = currentItem; ofFile presentation = ofFile(file.getAbsolutePath() + "/presentation.xml"); if(presentation.exists()){ // Directory is a Presentation. item->isCategory = false; item->path = file.getAbsolutePath(); } else { // Directory is a Category. item->isCategory = true; item->path = currentItem->path + " \/ " + item->name; // Add MenuItem to navigate up. ofPtr<MenuItem> itemUp(new MenuItem); itemUp->name = "..."; itemUp->isMenuUp = true; itemUp->font = &font_small; itemUp->parent = item; item->items.push_back(itemUp); loadMenuItems(ofDirectory(file.path()), item); } item->font = &font_small; currentItem->items.push_back(item); } } if(currentItem->items.size() > 0){ currentItem->items[0]->select(); } }
void ofApp::scan_dir_imgs(ofDirectory dir){ ofDirectory new_dir; int size = dir.listDir(); for (int i = 0; i < size; i++){ if (dir.getFile(i).isDirectory()){ new_dir = ofDirectory(dir.getFile(i).getAbsolutePath()); new_dir.listDir(); new_dir.sort(); scan_dir_imgs(new_dir); } else if (std::find(std::begin(allowed_ext), std::end(allowed_ext), dir.getFile(i).getExtension()) != std::end(allowed_ext)) { imageFiles.push_back(dir.getFile(i)); } } }
void ofApp::beginRenderMode(){ cout<<"render mode"<<endl; setResolution(render_width, render_height); //set minimal lag of audio behind video vwt->setAudioDelay(1./frame_rate_limit + 1./audio_sample_rate); //open a new wav file and write header stringstream file_name; cur_save_dir = ofDirectory(ofGetTimestampString()); cur_save_dir.create(); file_name << cur_save_dir.path()<<ofToDataPath("/audio.wav"); openAudioFile(file_name.str()); }
//-------------------------------------------------------------- void testApp::keyPressed(int key){ if(key == ' '){ timeline.togglePlay(); } if(key == 'g'){ generate(); } if(key == 't'){ traverse(); } if(key == 'T'){ camTrack.addKeyframe(); } if(key == 'L'){ camTrack.lockCameraToTrack = !camTrack.lockCameraToTrack; if(!camTrack.lockCameraToTrack){ cam.setAnglesFromOrientation(); } } if(key == 'f'){ ofToggleFullscreen(); } if(key == 'R'){ rendering = !rendering; if(rendering){ char folder[1024]; sprintf(folder, "frames_%02d_%02d_%02d/",ofGetDay(), ofGetHours(), ofGetMinutes()); renderFolder = folder; frameNum = 0; ofDirectory(renderFolder).create(true); timeline.setCurrentFrame(timeline.getInFrame()); timeline.play(); } } if(key == 'S'){ loadShader(); } }
vector<string> ofx2DPro::getPresets(){ vector<string> presets; string presetPath = getDataPath()+"Presets/"; ofDirectory presetsFolder = ofDirectory(presetPath); if(presetsFolder.exists()){ presetsFolder.listDir(); for(int i = 0; i < presetsFolder.size(); i++){ if(presetsFolder.getFile(i).isDirectory() && ofFilePath::removeTrailingSlash(presetsFolder.getName(i)) != "Working" && presetsFolder.getName(i).at(0) != '_') //use leading _ to hide folders { presets.push_back(presetsFolder.getName(i)); } } } return presets; }
//-------------------------------------------------------------- void MagicMirrorApp::setup(){ // camera connection camGrabber = new ofVideoGrabber(); camGrabber->setDeviceID(CONF_CAM_ID); camGrabber->initGrabber(CONF_CAM_W, CONF_CAM_H); camBuffer = new unsigned char[CONF_CAM_W * CONF_CAM_H * 3]; backgroundTexture.allocate(CONF_CAM_W, CONF_CAM_H, GL_RGB); // create a view object, will handle the drawing stuff view = new GLView(CONF_CAM_W, CONF_CAM_H); // create an init the marker-tracker and load camera intrinsic calibration file tracker = new ARToolKitPlus::TrackerSingleMarker(CONF_CAM_W, CONF_CAM_H); char* absolutPath; Tools::copyStringToBuf(ofDirectory(CONF_CAM_FILE).getAbsolutePath(), &absolutPath); if ( tracker->init(absolutPath, 1.0f, 100.0f) ) { configureTracker(); } else { delete camGrabber; delete view; std::exit(1); } // get instance of the content loader content = ContentLoader::getInstance(); content->loadContents(CONF_CONTENT_DIR); // to ensure the window has the configured size (could be changed by fullscreen mode) ofSetWindowShape(CONF_CAM_W, CONF_CAM_H); if (ofGetScreenWidth() < CONF_CAM_W) { // Window is bigger then Screen ... isl case ... move max to left (screen top) ofSetWindowPosition( (ofGetScreenWidth() - CONF_CAM_W), (ofGetScreenHeight() - CONF_CAM_H)/2 ); } infoAnimation = new InfoAnimation(); #if CONF_INFO_SHOW_ON_START == 1 lastTimeMarkerFound = 0; #else lastTimeMarkerFound = Tools::getMicros() / 1000L; #endif }
//-------------------------------------------------------------- void testApp::setup() { moviesLoaded = false; ofSystemAlertDialog("Select directory of calibration clips"); ofFileDialogResult r = ofSystemLoadDialog("Calibration Directory", true); if(r.bSuccess) { movieDirectory = ofDirectory(r.getPath()); movieDirectory.allowExt("mov"); movieDirectory.allowExt("mp4"); movieDirectory.listDir(); for(int i = 0; i < movieDirectory.numFiles(); i++) { ofVideoPlayer p; p.loadMovie( movieDirectory.getPath(i) ); videoplayers.push_back( p ); } currentMovie = 0; moviesLoaded = true; } }
//--------- void Register::addAddon(string addonName) { if (this->addonList.find(addonName) != this->addonList.end()) { ofLogWarning("ofxAddons::Register::addAddon") << "Addon [" << addonName << "] has already been added to the ofxAssets::Register."; return; } //whilst we're in debug build mode, we'll actually copy over the assets from the addon's folder #if defined(__DEBUGGING__) || defined(_DEBUG) //if we're still debugging in the build location, copy in latest assets auto checkDir = ofDirectory("../../../../../addons/" + addonName + "/data/assets/" + addonName); if (checkDir.exists()) { ofLogNotice("ofxAssets") << "Copying in addon files from " << checkDir.getOriginalDirectory(); checkDir.copyTo("assets/" + addonName, true, true); } else { ofLogNotice("ofxAssets") << "Cannot copy in addon assets since folder doesn't exist : " << checkDir.getOriginalDirectory(); } #endif this->addonList.insert(addonName); this->loadAssets(addonName); }
//-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ for(auto item : dragInfo.files) { if (ofFile(item).isDirectory()) { ofSetWindowTitle(item); auto dir = ofDirectory(); dir.sort(); dir.listDir(item); int index = 0; decoder.reset(); ofImage loader; for (auto & file : dir.getFiles()) { this->processFile(file); } decoder.update(); } else { ofFile file(item); this->processFile(file); } } }
void Project::load(const std::string& path, const std::string& name) { _sketchDir = ofDirectory(ofToDataPath(path + "/sketch")); _data.clear(); if (_sketchDir.exists()) { _sketchDir.listDir(); std::vector<ofFile> files = _sketchDir.getFiles(); int classCounter = 0; for (std::size_t i = 0; i < files.size(); ++i) { ofFile file = files[i]; if (file.getBaseName() == name) { file.open(file.getAbsolutePath()); _data["projectFile"]["name"] = file.getBaseName(); _data["projectFile"]["fileName"] = file.getFileName(); _data["projectFile"]["fileContents"] = file.readToBuffer().getText(); } else if (file.getExtension() == SKETCH_FILE_EXTENSION) { file.open(file.getAbsolutePath()); _data["classes"][classCounter]["name"] = file.getBaseName(); _data["classes"][classCounter]["fileName"] = file.getFileName(); _data["classes"][classCounter]["fileContents"] = file.readToBuffer().getText(); classCounter++; } } _loadAddons(); _isLoaded = true; } }
bool ofxRGBDRenderer::setup(string calibrationDirectory){ if(!ofDirectory(calibrationDirectory).exists()){ ofLogError("ofxRGBDRenderer --- Calibration directory doesn't exist: " + calibrationDirectory); return false; } depthCalibration.load(calibrationDirectory+"/depthCalib.yml"); rgbCalibration.load(calibrationDirectory+"/rgbCalib.yml"); loadMat(rotationDepthToRGB, calibrationDirectory+"/rotationDepthToRGB.yml"); loadMat(translationDepthToRGB, calibrationDirectory+"/translationDepthToRGB.yml"); depthToRGBView = ofxCv::makeMatrix(rotationDepthToRGB, translationDepthToRGB); ofPushView(); rgbCalibration.getDistortedIntrinsics().loadProjectionMatrix(); glGetFloatv(GL_PROJECTION_MATRIX, rgbProjection.getPtr()); ofPopView(); calibrationSetup = true; return true; }
//---------- void Register::traverseDirectoryFonts(string dataPath, vector<string> outputNamespace) { if (ofDirectory::doesDirectoryExist(dataPath)) { ofDirectory files; files.listDir(dataPath); for (int i = 0; i<files.size(); i++) { const auto filename = files.getPath(i); auto outputName = ofFilePath::getBaseName(filename); //check if it's a subfolder if (ofDirectory(filename).isDirectory()) { auto innerNamespace = outputNamespace; innerNamespace.push_back(outputName); this->traverseDirectoryFonts(dataPath + "/" + outputName, innerNamespace); } //if not, check whether it has the right extension const auto extension = ofFilePath::getFileExt(filename); if (!(extension == "ttf")) { continue; } //transform the output name to include namespace transformName(outputName, outputNamespace); //check it's not already loaded if (this->fontFilenames.find(outputName) != this->fontFilenames.end()) { continue; } //register the font for lazy loading later this->fontFilenames.insert(pair<string, string>(outputName, filename)); ofLogNotice("ofxAssets") << "Found font asset '" << outputName << "'" << endl; } } }
Menu::Menu(void){ // Default variables. visible = true; menuX = 650; menuY = 250; // Load Menu resources. font_small.loadFont("DroidSans.ttf", 12); font_large.loadFont("DroidSans.ttf", 18); img_hdd.loadImage("hdd.png"); // Load menu items. ofPtr<MenuItem> item(new MenuItem()); item->name = "Presentations"; item->path = "Presentations"; rootItem = item; activeItem = item; loadMenuItems(ofDirectory("Presentations"), item); // Listen to events for drawing, mouse and keyboard. addListeners(); }
//-------------------------------------------------------------- void ofApp::setup(){ // SETUP // imageDir, imageSavePath = location of images, path to save the final grid image // nx, ny = size of the grid (make sure there are at least nx*ny images in imageDir!) // w, h = size of the image thumbnails // perplexity, theta (for t-SNE, see 'example' for explanation of these) // -------------- SET FILE I/O --------------- string imageDir = "../../../../../../../../../Volumes/BenSnell/torsos-7k/photos-jpg"; // source directory string folderName = "torsos_7k_all"; // destination directory // ------------------------------------------- nx = 87; ny = 87; w = 340; h = 510; perplexity = 75; theta = 0.001; ///////////////////////////////////////////////////////////////////// // CCV activations -> t-SNE embedding -> grid assignments // get images recursively from directory ofLog() << "Gathering images..."; ofDirectory dir = ofDirectory(imageDir); scan_dir_imgs(dir); if (imageFiles.size() < nx * ny) { ofLog(OF_LOG_ERROR, "There are less images in the directory than the grid size requested (nx*ny="+ofToString((nx*ny))+"). Exiting to save you trouble..."); // ofExit(); // not enough images to fill the grid, so quitting } // load all the images // for(int i=0; i<nx*ny; i++) { // if (i % 20 == 0) ofLog() << " - loading image "<<i<<" / "<<nx*ny<<" ("<<dir.size()<<" in dir)"; // images.push_back(ofImage()); // images.back().load(imageFiles[i]); //// images.back().resize(w, h); // ADDED -- DOES THIS WORK? // } for(int i=0; i<imageFiles.size(); i++) { if (i % 20 == 0) ofLog() << " - loading image "<<i<<" / "<<imageFiles.size()<<" ("<<dir.size()<<" in dir)"; images.push_back(ofImage()); images.back().load(imageFiles[i]); // images.back().resize(w, h); // ADDED -- DOES THIS WORK? } // resize images to w x h for (int i=0; i<images.size(); i++) { if (images[i].getWidth() > images[i].getHeight()) { images[i].crop((images[i].getWidth()-images[i].getHeight()) * 0.5, 0, images[i].getHeight(), images[i].getHeight()); } else if (images[i].getHeight() > images[i].getWidth()) { images[i].crop(0, (images[i].getHeight()-images[i].getWidth()) * 0.5, images[i].getWidth(), images[i].getWidth()); } images[i].resize(w, h); } // setup ofxCcv ccv.setup("image-net-2012.sqlite3"); // encode all of the images with ofxCcv ofLog() << "Encoding images..."; for (int i=0; i<images.size(); i++) { if (i % 20 == 0) ofLog() << " - encoding image "<<i<<" / "<<images.size(); vector<float> encoding = ccv.encode(images[i], ccv.numLayers()-1); encodings.push_back(encoding); } // run t-SNE and load image points to imagePoints ofLog() << "Run t-SNE on images"; tsneVecs = tsne.run(encodings, 2, perplexity, theta, true); // tsneVecs contains {x, y} for each image in images // save tsne ofFile tsneFile; tsneFile.open(folderName + "/" + "tsne_only_metadata.csv", ofFile::WriteOnly); tsneFile << "image_name,tsne_x,tsne_y"; for (int i = 0; i < images.size(); i++) { tsneFile << "\n"; tsneFile << imageFiles[i].getFileName() << ","; tsneFile << ofToString(tsneVecs[i][0]) << ","; tsneFile << ofToString(tsneVecs[i][1]); } tsneFile.close(); ofExit(); // TEMP!!! // solve assignment grid vector<ofVec2f> tsnePoints; // convert vector<double> to ofVec2f for (auto t : tsneVecs) tsnePoints.push_back(ofVec2f(t[0], t[1])); vector<ofVec2f> gridPoints = makeGrid(nx, ny); solvedGrid = solver.match(tsnePoints, gridPoints, false); // export data to csv containing names and positions of images bool bExport = true; if (bExport) { int nImages = images.size(); //nx * ny; ofFile file; file.open(folderName + "/" + "tsne_metadata.csv", ofFile::WriteOnly); file << "image_name,grid_row,grid_column,grid_x_norm,grid_y_norm,tsne_x,tsne_y"; for (int i = 0; i < nImages; i++) { file << "\n"; file << imageFiles[i].getFileName() << ","; file << ofToString(solvedGrid[i].x * (nx-1)) << ","; file << ofToString(solvedGrid[i].y * (ny-1)) << ","; file << ofToString(solvedGrid[i].x) << ","; file << ofToString(solvedGrid[i].y) << ","; file << ofToString(tsneVecs[i][0]) << ","; file << ofToString(tsneVecs[i][1]); } file.close(); } // save image grid bool bSaveGrid = true; if (bSaveGrid) { string imageGridName = "tsne_grid.png"; ofFbo fbo; fbo.allocate(nx * w, ny * h); fbo.begin(); ofClear(0, 0); ofBackground(0); for (int i=0; i<solvedGrid.size(); i++) { float x = (fbo.getWidth() - w) * solvedGrid[i].x; float y = (fbo.getHeight() - h) * solvedGrid[i].y; images[i].draw(x, y, w, h); } fbo.end(); ofImage img; fbo.readToPixels(img); img.save(folderName + "/" + imageGridName); } // save image clusters bool bSaveClusters = true; float imgScale = 0.5; if (bSaveClusters) { string imageClustersName = "tsne_clusters.png"; ofFbo fbo; fbo.allocate(nx * w, ny * h); fbo.begin(); ofClear(0, 0); ofBackground(255); for (int i=0; i<tsneVecs.size(); i++) { float x = (fbo.getWidth() - w) * tsneVecs[i][0]; float y = (fbo.getHeight() - h) * tsneVecs[i][1]; ofSetColor(255, 180); images[i].draw(x, y, w * imgScale, h * imgScale); ofSetColor(0); ofDrawBitmapString(imageFiles[i].getFileName(), x, y + h * imgScale); } fbo.end(); ofImage img; fbo.readToPixels(img); img.save(folderName + "/" + imageClustersName); } // setup gui gui.setup(); gui.add(scale.set("scale", 1.0, 0.0, 1.0)); }
//-------------------------------------------------------------- void testApp::setup(){ // ofSetFrameRate(30); ofSystemAlertDialog("Load a directory of .xkcd files"); ofFileDialogResult r = ofSystemLoadDialog("Load uncompressed xkcd directory", true); if(r.bSuccess){ ofDirectory dir(r.getPath()); dir.allowExt("xkcd"); dir.listDir(); unsigned short* lastbuf = new unsigned short[640*480]; unsigned short* tempbuf = new unsigned short[640*480]; string pngDirPath = r.getPath() + "_pngs"; ofDirectory pngDir = ofDirectory(pngDirPath); if(!pngDir.exists()){ pngDir.create(true); } ofSystemAlertDialog("Optionally load a pairing file to fix"); r = ofSystemLoadDialog("Load pairing file to repair", false); if(r.bSuccess){ pairingFileLoaded = true; pairingFileName = r.getPath(); oldPairing.loadPairingFile(pairingFileName); } else{ pairingFileLoaded = false; } time_t original = 0; time_t last = 0; int total; int currentOutputFile = 0; for(int i = 0; i < dir.numFiles(); i++){ string path = dir.getPath(i); memcpy(lastbuf, tempbuf, sizeof(unsigned short)*640*480); decoder.readDepthFrame(path, tempbuf); //check if we have a matching pair for this frame int thisDepthFrame = ofToInt(dir.getName(i).substr(dir.getName(i).find(".xkcd")-5,5) ); if(pairingFileLoaded){ for(int p = 0; p < oldPairing.getPairs().size(); p++){ VideoDepthPair pair = oldPairing.getPairs()[p]; if(pair.depthFrame == thisDepthFrame){ pair.depthFrame = currentOutputFile; newPairing.addAlignedPair(pair); cout << "CONVERTED PAIR: " << thisDepthFrame << " to " << pair.depthFrame << endl; break; } } } //check for duplicate if(i != 0){ bool identical = true; for (int p = 0; p < 640*480; p++) { if(lastbuf[p] != tempbuf[p]){ identical = false; break; } } if(identical) continue; } char framestr[1024]; sprintf(framestr, "%05d", currentOutputFile); string newPath = pngDirPath + "/frame__" + string(framestr) + ".png"; decoder.saveToCompressedPng(newPath, tempbuf); currentOutputFile++; struct stat fileInfo; int r = stat(path.c_str(), &fileInfo); time_t t = fileInfo.st_mtimespec.tv_sec; if(i == 0){ original = t; last = 0; } if( (t-original) != last){ cout << "time " << last << " had " << total << " frames " << endl; total = 1; last = t-original; } else{ total++; } //cout << "file " << path << " created at " << ( t-original ) << " " << fileInfo.st_mtimespec.tv_nsec << endl; cout << "saved " << path << " to " << newPath << endl; } if(pairingFileLoaded){ newPairing.savePairingFile(pairingFileName+".corrected.xml"); } } }
bool ofxRGBDScene::loadFromFolder(string sourceMediaFolder, bool countFrames){ clear(); calibrationFolder = ""; videoPath = ""; alternativeHiResVideoPath = ""; pairingsFile = ""; mediaFolder = sourceMediaFolder; if(sourceMediaFolder.find("_calibration") != string::npos) { ofLogWarning("ofxRGBDScene::loadFromFolder -- Discarding _calibration folder"); return false; } if(sourceMediaFolder.find("_Renderbin/") != string::npos){ ofLogWarning("ofxRGBDScene::loadFromFolder -- Discarding Render Bin"); return false; } ofDirectory dataDirectory(mediaFolder); if(!dataDirectory.exists()){ ofLogWarning("ofxRGBDScene::loadFromFolder -- folder " + mediaFolder + " -- Directory doesn't exist."); return false; } if(!dataDirectory.isDirectory()){ ofLogWarning("ofxRGBDScene::loadFromFolder -- folder " + mediaFolder + " -- Isn't a directory!"); return false; } dataDirectory.listDir(); int numFiles = dataDirectory.numFiles(); if(numFiles == 0){ ofLogWarning("ofxRGBDScene::loadFromFolder -- folder " + mediaFolder + " -- Directory is empty."); return false; } vector<string> components = ofSplitString( mediaFolder, "/"); name = components[components.size()-1]; ////////////////////////////////////////////// // DEPTH ////////////////////////////////////////////// bool depthFolderFound = false; for(int i = 0; i < dataDirectory.numFiles(); i++){ if(dataDirectory.getFile(i).isDirectory() && (dataDirectory.getName(i).find("depth") != string::npos || dataDirectory.getName(i).find("TAKE") != string::npos) ){ depthFolder = dataDirectory.getPath(i); depthFolderFound = true; } } if(!depthFolderFound){ depthFolder = mediaFolder + "/depth/"; } ofDirectory depthDirectory = ofDirectory(depthFolder); //potentially a legacy folder. check to see if there are +20 PNG or raws's //indicating the files need to be moved ofDirectory mainDirectory(sourceMediaFolder); mainDirectory.allowExt("png"); mainDirectory.allowExt("raw"); mainDirectory.listDir(); if(mainDirectory.numFiles() > 20){ //create the depth directory if we haven't yet if(!depthDirectory.exists()){ depthDirectory.create(); } //move all the files from the main folder into the depth directory for(int i = 0; i < mainDirectory.numFiles(); i++){ string destinationPath = ofFilePath::getEnclosingDirectory(mainDirectory.getPath(i)) + "depth/" + mainDirectory.getName(i); //cout << "ofxRGBDScene -- Legacy Format -- moved to " << destinationPath << endl; //mainDirectory.getFile(i).moveTo( destinationPath ); } } if(depthDirectory.exists()){ if(countFrames){ ofDirectory compresseDepthFrames(depthFolder); compresseDepthFrames.allowExt("png"); compressedDepthFrameCount = compresseDepthFrames.listDir(); ofDirectory uncompressedDepthFrames(depthFolder); uncompressedDepthFrames.allowExt("raw"); uncompressedDepthFrameCount = uncompressedDepthFrames.listDir(); totalDepthFrameCount = uncompressedDepthFrameCount + compressedDepthFrameCount; hasDepth = (totalDepthFrameCount > 0); } else { //guess it hasDepth = true; } } ////////////////////////////////////////////// // END DEPTH ////////////////////////////////////////////// ////////////////////////////////////////////// // COLOR ////////////////////////////////////////////// string colorFolder = mediaFolder + "/color/"; ofDirectory colorDirectory = ofDirectory(colorFolder); ofDirectory mainDirectoryColor = ofDirectory(sourceMediaFolder); //TODO: make an xml file for video formats mainDirectoryColor.allowExt("mov"); mainDirectoryColor.allowExt("mpg"); mainDirectoryColor.allowExt("mepg"); mainDirectoryColor.allowExt("mp4"); mainDirectoryColor.listDir(); //move the movies into the color/ dir if they are hanging outside if(mainDirectoryColor.numFiles() > 0){ if(!colorDirectory.exists()){ colorDirectory.create(); } for(int i = 0; i < mainDirectoryColor.numFiles(); i++){ string destinationPath = ofFilePath::getEnclosingDirectory(mainDirectoryColor.getPath(i)) + "color/" + mainDirectoryColor.getName(i); // cout << "ofxRGBDScene -- Legacy Format -- moved to " << destinationPath << endl; // mainDirectoryColor.getFile(i).moveTo( destinationPath ); } } if(colorDirectory.exists()){ //TODO: make an xml file for video formats colorDirectory.allowExt("mpeg"); colorDirectory.allowExt("mov"); colorDirectory.allowExt("mpg"); colorDirectory.allowExt("mp4"); colorDirectory.listDir(); if(colorDirectory.numFiles() == 0){ hasColor = false; } else if(colorDirectory.numFiles() == 1){ hasColor = true; videoPath = colorDirectory.getPath(0); } else { int largestIndex = 0; int smallestIndex = 0; uint64_t largestSize = colorDirectory.getFile(0).getSize(); uint64_t smallestSize = colorDirectory.getFile(0).getSize(); for(int i = 0; i < colorDirectory.numFiles(); i++){ uint64_t size = colorDirectory.getFile(i).getSize(); cout << colorDirectory.getName(i) << " size is " << size << endl; if(largestSize < size){ largestSize = size; largestIndex = i; } if(size < smallestSize){ smallestSize = size; smallestIndex = i; } } hasColor = true; hasAlternativeHiResVideo = true; alternativeHiResVideoPath = colorDirectory.getPath(largestIndex); videoPath = colorDirectory.getPath(smallestIndex); // cout << "video path is " << videoPath << " alternative is " << alternativeHiResVideoPath << endl; // cout << "largest size is " << largestSize << " smallest size is " << smallestSize << endl; } if(hasColor){ videoThumbsPath = ofFilePath::removeExt(videoPath); if(!ofDirectory(videoThumbsPath).exists()){ ofDirectory(videoThumbsPath).create(true); } } } ////////////////////////////////////////////// // END COLOR ////////////////////////////////////////////// ////////////////////////////////////////////// // PAIRINGS FILE ////////////////////////////////////////////// if(hasColor){ ofDirectory mainDirectoryPairings = ofDirectory(sourceMediaFolder); mainDirectoryPairings.allowExt("xml"); mainDirectoryPairings.listDir(); for(int i = 0; i < mainDirectoryPairings.numFiles(); i++){ if(mainDirectoryPairings.getName(i).find("pairings") != string::npos){ pairingsFile = mainDirectoryPairings.getPath(i); hasPairings = true; } if(mainDirectoryPairings.getName(i).find("xyshift") != string::npos){ xyshiftFile = mainDirectoryPairings.getPath(i); hasXYShift = true; } } if(!hasPairings){ pairingsFile = mediaFolder + "/pairings.xml"; } if(!hasXYShift){ xyshiftFile = mediaFolder + "/xyshift.xml"; } } ////////////////////////////////////////////// // END PAIRINGS FILE ////////////////////////////////////////////// ////////////////////////////////////////////// // CALIBRATION ////////////////////////////////////////////// if(hasColor){ vector<string> calibrationFolders; calibrationFolders.push_back(mediaFolder + "/_calibration/matrices/"); calibrationFolders.push_back(mediaFolder + "/calibration/"); calibrationFolders.push_back(mediaFolder + "/../_calibration/matrices/"); for(int i = 0; i < calibrationFolders.size(); i++){ ofDirectory calibrationDirectory = ofDirectory(calibrationFolders[i]); hasCalibration = calibrationDirectory.exists(); if(hasCalibration){ calibrationFolder = calibrationFolders[i]; break; } } } ////////////////////////////////////////////// // END CALIBRATION ////////////////////////////////////////////// ////////////////////////////////////////////// // REPORT ////////////////////////////////////////////// bool debug = true; if(debug){ cout << "REPORT FOR " << sourceMediaFolder << endl; cout << "has DEPTH? " << (hasDepth ? "YES" : "NO") << endl; if(hasDepth){ cout << " # COMPRESSED DEPTH FRAMES " << compressedDepthFrameCount << endl; if(uncompressedDepthFrameCount > 0){ cout << " # UNCOMPRESSED DEPTH FRAMES " << uncompressedDepthFrameCount << endl; } } cout << "has COLOR? " << (hasColor ? "YES" : "NO") << endl; if(hasColor){ cout << "has VIDEO " << (hasColor ? "YES" : "NO") << endl; cout << "has HI RES " << (hasAlternativeHiResVideo ? "YES" : "NO") << endl; cout << "has CALIBRATION " << (hasCalibration ? "YES" : "NO") << endl; cout << "has PAIRINGS " << (hasPairings ? "YES" : "NO") << endl; if(hasPairings){ cout << "pairings! " << pairingsFile << endl; } } } ////////////////////////////////////////////// // END REPORT ////////////////////////////////////////////// return valid(); }
TownDashboardRenderer::TownDashboardRenderer() { //allocate fbos _exportFbo.allocate(PRINT_DIMENSIONS_WIDTH, PRINT_DIMENSIONS_HEIGHT); _blackPassFbo.allocate(PRINT_DIMENSIONS_WIDTH, PRINT_DIMENSIONS_HEIGHT, GL_RGB); _typeLayerFbo.allocate(PRINT_DIMENSIONS_WIDTH, PRINT_DIMENSIONS_HEIGHT); _glowPassFbo.allocate(PRINT_DIMENSIONS_WIDTH, PRINT_DIMENSIONS_HEIGHT); //load images blendImage.load("images/textBlendLayer.png"); //load localised search images ofDirectory localesDir = ofDirectory("images/locales"); localesDir.listDir(); for(int i = 0; i < localesDir.size(); i++){ auto path = localesDir.getPath(i); ofFile f = ofFile(path); if(f.isDirectory()) { ofImage img = ofImage(path + "/searchingNoGlow.png"); string localPath = path.substr(path.find_last_of("/") + 1, path.length()); searchStringImages[localPath] = img; } } searchingStringImage = searchStringImages[_locale]; // backgroundImage.load("images/bgNew.png"); glow.allocate(PRINT_DIMENSIONS_WIDTH, PRINT_DIMENSIONS_HEIGHT, GL_RGBA); glow.setRadius(15); glow.setPasses(4); //these are the curves cv.push_back(ofVec2f(2147,1297)); cv.push_back(ofVec2f(2104,1336)); cv.push_back(ofVec2f(2057,1374)); cv.push_back(ofVec2f(2005,1412)); cv.push_back(ofVec2f(1950,1446)); cv.push_back(ofVec2f(1897,1483)); cv.push_back(ofVec2f(1837,1517)); cv.push_back(ofVec2f(1779,1550)); cv.push_back(ofVec2f(1720,1580)); cv.push_back(ofVec2f(1660,1608)); cv.push_back(ofVec2f(1597,1635)); cv.push_back(ofVec2f(1537,1657)); spline2D.reserve(cv.size()); for( auto p : cv) { spline2D.push_back(p); } spline2D.setInterpolation(msa::kInterpolationLinear); spline2D.setUseLength(false); _debugMode = false; font.load("Pleyo.otf", 13, true, true, true, 0.3, 300); font.setLetterSpacing(1.00); }
//-------------------------------------------------------------------------- void testApp::setupControlPanel(){ ofxControlPanel::setBackgroundColor(simpleColor(30, 30, 30, 200)); ofxControlPanel::setTextColor(simpleColor(80, 240, 240, 255)); panel.setup("controls", 0, 0, 300, 750); panel.addPanel("general controls", 4, false); panel.addPanel("animation controls", 4, false); panel.addPanel("render controls", 4, false); panel.addPanel("camera params", 4, false); panel.addPanel("debug params", 4, false); //--------- general params panel.setWhichPanel("general controls"); panel.setWhichColumn(0); panel.addToggle("export screenshots", "exportScreenshots", false); panel.addToggle("convert to png after load", "bConvertToPng", false); panel.addToggle("auto change face", "bAutoChange", false); panel.addSlider("change face time", "changeTime", 28.2, 8.0, 60.0, false); panel.addChartPlotter("fps", guiStatVarPointer("app fps", &appFps, GUI_VAR_FLOAT, true, 2), 200, 80, 200, 8, 100); panel.addToggle("restart at 3.00am", "bRestart", false); panel.addSlider("restart hour", "restartHour", 3, 1, 23, true); panel.addSlider("restart minute", "restartMinute", 0, 0, 59, true); panel.addToggle("player mode", "toggle_mode", false); //--------- animation params panel.setWhichPanel("animation controls"); panel.setWhichColumn(0); panel.addSlider("particle targetForce", "particle_targetForce", 1.0, 0.0, 1.0, false); panel.addSlider("noise scale in", "noise_scale_input", 0.57, 0.0, 1.0, false); panel.addSlider("noise scale out", "noise_scale_output", 0.5, 0.0, 1.0, false); panel.addChartPlotter("fps", guiStatVarPointer("app fps", &appFps, GUI_VAR_FLOAT, true, 2), 200, 80, 200, 8, 100); panel.addSlider("random offset", "randomOffset", 0, 0, 10, false); panel.addSlider("slow momentum", "slowMomentum", .3, 0, 1, false); panel.addSlider("particle speed", "particle_speed", 24.7, 0, 50, false); panel.addSlider("particle spread", "particle_spread", 100, 2, 100, false); panel.addSlider("particle viscosity", "particle_viscosity", 0.167, 0.0, 0.5, false); panel.addSlider("particle independence", "particle_independence", 0.178, 0.0, 0.8, false); panel.addSlider("particle neighborhood", "particle_neighborhood", 1292, 100, 2000, false); //--------- render params panel.setWhichPanel("render controls"); panel.setWhichColumn(0); panel.addToggle("do ghetto fbo trails", "do_trails", false); panel.addSlider("fboTrails scale", "fboScale", 0.04, 0.001, 0.5, false); panel.addChartPlotter("fps", guiStatVarPointer("app fps", &appFps, GUI_VAR_FLOAT, true, 2), 200, 80, 200, 8, 100); panel.addSlider("max brightness", "maxBrightness", 0, 0, 255, true); panel.addSlider("rgb brightness", "rgbBrightness", 3, 0, 10, false); panel.addSlider("point brightness", "point_brightness", 10, 0, 20.0, false); panel.addSlider("dof focus offset", "focus_offset", 0, -1000, 1000, false); panel.addSlider("aberration", "aberration", 0.021, 0.005, 0.2, false); panel.addSlider("aperture", "aperture", 0.025, 0.001, 0.2, false); panel.addSlider("max point size", "maxPointSize", 21.3, 5, 40, false); panel.addSlider("sphere alpha", "sphere_alpha", 0.66, 0.0, 1.0, false); panel.addSlider("sphere red", "sphere_red", 0, 0.0, 1.0, false); panel.addSlider("sphere green", "sphere_green", 0.35, 0.0, 1.0, false); panel.addSlider("sphere blue", "sphere_blue", 0.47, 0.0, 1.0, false); // - - -- - --- - camera param eters panel.setWhichPanel("camera params"); panel.setWhichColumn(0); panel.addToggle("persistent mode", "persistentMode", true); panel.addSlider("rotation momentum", "rotationMomentum", .9, .5, 1, false); panel.addSlider("position momentum", "positionMomentum", .99, .5, 1, false); panel.addSlider("zoom momentum", "zoomMomentum", .99, .5, 1, false); panel.addSlider("fov", "fov", 60, 1, 180, false); panel.addSlider("min zoom", "minZoom", 400, 0, 400, false); panel.addSlider("max zoom", "maxZoom", 10000, 400, 20000, false); panel.addSlider("reset delay", "resetDelay", 4, 0, 10, false); panel.addSlider("reset length", "resetLength", 2, 0, 10, false); panel.addSlider("rotation speed", "rotationSpeed", .0005, 0, .001, false); panel.addSlider("zoom speed", "zoomSpeed", 1, 0, 4, false); panel.addSlider("zoom scale factor", "zoomScaleFactor", .005, 0, .01, false); panel.addToggle("smart focal plane", "smartFocalPlane", true); //--------- general params panel.setWhichPanel("debug params"); panel.setWhichColumn(0); panel.addToggle("draw particles", "bDrawParticles", true); panel.addToggle("freeze particles", "bFreezeParticles", false); panel.addToggle("draw white", "drawWhite", false); panel.selectedPanel = 0; panel.loadSettings("appSettings.xml"); panel.setValueB("toggle_mode", false); panel.setValueB("bAutoChange", ofDirectory(scanFolder).exists()); //Particle::globalOffset.set(0, 1. / 3, 2. / 3); }
void FileImporter::threadedFunction(){ ofDirectory ad = ofDirectory(annotationfolderPath); if(!ad.exists()){ ofFileDialogResult f = ofSystemLoadDialog("analysisFiles",true); ad = ofDirectory(f.filePath); if(!ad.exists() || !f.bSuccess){ ofExit(); } } curAnnotationPath = ad.path(); for(BaseFileLoader::loaders_map_type::iterator it = BaseFileLoader::getMap()->begin() ; it!=BaseFileLoader::getMap()->end() ; ++it){ ad.allowExt(it->first); } ad.listDir(); vector<ofFile> segL = ad.getFiles(); if(!segL.size()){ ofLogError("FileImporter","No valid file in " + ad.path()+" ,allowed extentions :"); return; } int globalCount=0; getSubset(annotationfolderPath+"Viza/best.json"); preCache(segL); totalNumFile= segL.size(); int numContainers = 0; numSong = 0; dbgTime = ofGetElapsedTimef(); queue.cancelAll(); BaseFileLoader::audioFolderPath = audiofolderPath; numDone = 0; { ofScopedLock sl(mutex); for(std::vector<ofFile>::iterator p=segL.begin();p!= segL.end();++p){ int contwatch = numContainers; BaseFileLoader * curLoader = BaseFileLoader::getMap()->at(p->getExtension())(ofToString(contwatch)); // indicate context for task curLoader->containerBlock.parsedFile = p->path(); curLoader->fillContainerBlock(p->path()); curLoader->containerBlock.containerIdx = numContainers; curLoader->containerBlock.songIdx = numSong; queue.start(curLoader); numSong+=1; numContainers+= curLoader->containerBlock.numElements; if( contwatch != numContainers){ globalCount++; } else{ ofLogWarning("FileImporter") << "nothing to add for file " << p->path(); } } } ofLogNotice("FileImporter","importing "+ofToString(globalCount)+" annotation files"); }
//-------------------------------------------------------------- void testApp::setup() { /* INTRO */ // Preamble cout << "Starting Program " << endl; cout << " ----- \n" << endl; // Set Log Level (To Ensure Serial Debug Info Prints) ofSetLogLevel(OF_LOG_NOTICE); // Read Credentials File credentials = ofBufferFromFile("settings/credentials.txt"); host = credentials.getFirstLine(); username = credentials.getNextLine(); password = credentials.getNextLine(); port = credentials.getNextLine(); // Set Paths pathToDataDirectory = "../../../MEDIA"; pathToLogsDirectory = "../../../LOGS"; pathToUploadsDirectory = "/filefrontend/data/files/uploads/"; /* READ EXISTING FILES */ // Set Path To Root Data Folder string mediaPath = pathToDataDirectory; mediaDirectory = ofDirectory(mediaPath); //Allow Media Types mediaDirectory.allowExt("jpg"); mediaDirectory.allowExt("png"); mediaDirectory.allowExt("mp4"); mediaDirectory.allowExt("zip"); // List mediaDirectory.sort(); mediaDirectory.listDir(); cout << "Media Directory Has " << mediaDirectory.size() << " Valid Files \n" << endl; existingFileNames.resize(mediaDirectory.size()); for (int i = 0; i < mediaDirectory.size(); i++) { existingFileNames[i] = mediaDirectory.getName(i); cout << "Existing File Name #" << i << " is " << existingFileNames[i] << endl; } cout << "Existing Parse Success! \n" << endl; // Connect try { cout << "Attempting To Connect To FTP:" << endl; // Log In To FTP client.setup(host, username, password, 21); client.setVerbose(true); cout << "Connection Success! \n" << endl; } catch(int e) { cout << "The Exception #" << e << " Occured." << endl; } /* LIST REMOTE FILES */ // List Files try { cout << "Attempting To List All Files:" << endl; // Assign List Of Directory To Base String Vector fileNames = client.list(pathToUploadsDirectory); // Resize Trimmed Vector To Match trimmedFileNames.resize(fileNames.size()); existingFileNames.resize(trimmedFileNames.size()); // Loop Through File Names, Trim At Path, And Assign To New Vector for(int i = 0; i < fileNames.size(); i++) { cout << "Original Item #" << i << " is " << fileNames[i] << endl; vector<string> trimmedName = ofSplitString(fileNames[i], "uploads/"); trimmedFileNames[i] = trimmedName[1]; } cout << "" << endl; // Loop Through New Vector To Make Sure for(int i = 0; i < trimmedFileNames.size(); i++) { cout << "Trimmed Item #" << i << " is " << trimmedFileNames[i] << endl; } cout << "Listing Success!\n" << endl; } catch(int e) { cout << "The Exception #" << e << " Occured." << endl; } /* COMPARE EXISTING AND REMOTE FILES */ // Compare Files cout << "Attempting To Compare All Files:" << endl; for(int i = 0; i < trimmedFileNames.size(); i++) { Boolean match = false; // Set Boolean To Test Matches for(int j = 0; j < existingFileNames.size(); j++) { // If The Current File Matches Any File In The Existing List if(trimmedFileNames[i].compare(existingFileNames[j]) == 0 ) { match = true; break; } // Otherwise Mark It As New else { match = false; } } // Test if(match) { cout << "The File " << trimmedFileNames[i] << " Has Previously Been Downloaded" << endl; } else { cout << "The File " << trimmedFileNames[i] << " Seems To Be New" << endl; newFileNames.push_back(trimmedFileNames[i]); // Add To New List } } cout << "Comparing Success!\n" << endl; /* DOWNLOAD NEW FILES */ // Get Files try { cout << "Attempting To Download " << newFileNames.size() << " Files:" << endl; // Download All Files From Uploads Directory To Data Directory for(int i = 0; i < newFileNames.size(); i++) { cout << "Downloading The File " << newFileNames[i] << endl; client.get(newFileNames[i], ofToDataPath(""), pathToUploadsDirectory); } cout << "Downloading Success!\n" << endl; } catch(int e) { cout << "The Exception #" << e << " Occured." << endl; } /* MOVE FILES */ cout << "Listing Files In Data Directory" << endl; // Set Path To Root Data Folder string dataPath = ""; dataDirectory = ofDirectory(dataPath); //Allow Media Types dataDirectory.allowExt("jpg"); dataDirectory.allowExt("png"); dataDirectory.allowExt("mp4"); dataDirectory.allowExt("zip"); // List dataDirectory.sort(); dataDirectory.listDir(); cout << "Data Directory Has " << dataDirectory.size() << " Valid Files" << endl; // Move To Data Directory cout << "Moving To Data Directory" << endl; for (int i = 0; i < dataDirectory.size(); i++) { ofFile file = dataDirectory.getFile(i); cout << "Moving File #" << i << endl; file.moveTo(pathToDataDirectory, true, false); } cout << "Moving Success!\n" << endl; }