openFrameworks 007 - utils

42,082 views

Published on

openFrameworks 007 - utils

Published in: Technology, Education
1 Comment
7 Likes
Statistics
Notes
  • Dear Sir/Mam I hope you are doing well !! I specialise in digital marketing services including social media marketing, email campaign creation, copywriting, web content creation and design and search engine optimisation. I also specialise in Website Design, Re-design Website Design, Ecommerce Website, CMS Websites, Mobile Apps, PSD to HTML, PSD to Wordpress, psd to magento, Logo & Graphic Design CMS/CRM Website Design etc. If you are interested in hiring me for any of the above services please get in touch and we can discuss the details. Kind regards Nida
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
No Downloads
Views
Total views
42,082
On SlideShare
0
From Embeds
0
Number of Embeds
32,016
Actions
Shares
0
Downloads
211
Comments
1
Likes
7
Embeds 0
No embeds

No notes for slide
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • openFrameworks 007 - utils

    1. 1. openFrameworks utils
    2. 2. Utils date screenshots noiselist helpers remote loading logging string threading file utilsmanipulation system tools constants
    3. 3. date int ofGetSeconds() Get seconds of current time int ofGetMinutes() Get minutes of current time int ofGetHours() Get hours of current time int ofGetYear() Get current year int ofGetMonth() Get current month int ofGetDay() Get current day int ofGetWeekDay Get current weekday unsigned int ofGetUnixTime() Timestamp since 1970unsigned long ofGetSystemTime() System time in millisstring ofGetSystemTimeMicros() System time in micros string ofGetTimestampString() Timestamp since 1970 as string
    4. 4. list helpersRemove items from a vector. void ofRemove(vector<T>&, BoolFunction shouldErase) Step 1. Create a custom remove functor class MyOwnRemover{ public: bool operator()(const string& str) { return str == "roxlu"; } };
    5. 5. list helpersvoid ofRemove(vector<T>&, BoolFunction shouldErase) Step 2. use ofRemove with remove functor void testApp::setup(){ // create list with strings. vector<string> mystrings; mystrings.push_back("diederick"); mystrings.push_back("openframeworks"); mystrings.push_back("supercool"); mystrings.push_back("roxlu"); mystrings.push_back("do not remove"); mystrings.push_back("roxlu"); // show before removing items. for(int i = 0; i < mystrings.size(); ++i) { cout << "before: " << mystrings[i] << endl; } cout << "=======" << endl; // remove items using my own remover! ofRemove(mystrings, MyOwnRemover()); for(int i = 0; i < mystrings.size(); ++i) { cout << "after: " << mystrings[i] << endl; } }
    6. 6. Summary ofRemove list helpers void ofRemove(vector<T>&, BoolFunction shouldErase)class MyOwnRemover{ void testApp::setup(){public: bool operator()(const string& str) { // create list with strings. return str == "roxlu"; vector<string> mystrings; } mystrings.push_back("diederick");}; mystrings.push_back("openframeworks"); mystrings.push_back("supercool"); mystrings.push_back("roxlu"); mystrings.push_back("do not remove"); mystrings.push_back("roxlu"); // show before removing items. for(int i = 0; i < mystrings.size(); ++i) { Result } cout << "before: " << mystrings[i] << endl; before: diederick cout << "=======" << endl; before: openframeworks before: supercool before: roxlu before: do not remove // remove items using my own remover! before: roxlu ofRemove(mystrings, MyOwnRemover()); ======= after: diederick for(int i = 0; i < mystrings.size(); ++i) { after: openframeworks cout << "after: " << mystrings[i] << endl; after: supercool after: do not remove } }
    7. 7. Randomize a vector list helpers void ofRandomize(vector<T>&)void testApp::setup(){ // create list with strings. vector<string> mystrings; mystrings.push_back("diederick"); mystrings.push_back("openframeworks"); Result mystrings.push_back("supercool"); random: roxlu mystrings.push_back("roxlu"); random: roxlu mystrings.push_back("do not remove"); random: supercool mystrings.push_back("roxlu"); random: openframeworks random: do not remove ofRandomize(mystrings); random: diederick // show before removing items. for(int i = 0; i < mystrings.size(); ++i) { cout << "random: " << mystrings[i] << endl; }}
    8. 8. Sort a vector list helpers void ofSort(vector<T>&)void testApp::setup(){ // create list with strings. vector<string> mystrings; mystrings.push_back("diederick"); mystrings.push_back("openframeworks"); Result mystrings.push_back("supercool"); sorted: diederick mystrings.push_back("roxlu"); sorted: do not remove mystrings.push_back("do not remove"); sorted: openframeworks mystrings.push_back("roxlu"); sorted: roxlu sorted: roxlu ofSort(mystrings); sorted: supercool // show before removing items. for(int i = 0; i < mystrings.size(); ++i) { cout << "sorted: " << mystrings[i] << endl; }}
    9. 9. Find entry in vector list helpers unsigned int ofFind(vector<T>&, const T& target)void testApp::setup(){ vector<string> mystrings; mystrings.push_back("diederick"); mystrings.push_back("openframeworks"); Result mystrings.push_back("supercool"); mystrings.push_back("roxlu"); do not remove <-- mystrings.push_back("do not remove"); mystrings.push_back("roxlu"); string fstr = "do not remove"; unsigned int num_found = ofFind(mystrings, fstr); if(num_found) { cout << mystrings[num_found] << " <-- “ << endl; }}
    10. 10. Check if entry exists list helpers bool ofContains(vector<T>&, const T& target) // create list with strings. vector<string> mystrings; mystrings.push_back("diederick"); mystrings.push_back("openframeworks"); Result mystrings.push_back("supercool"); mystrings.push_back("roxlu"); do not remove in mystrings mystrings.push_back("do not remove"); mystrings.push_back("roxlu"); string fstr = "do not remove"; bool contains = ofContains(mystrings, fstr); if(contains) { cout << fstr << " in mystrings" << endl; }
    11. 11. string manipulation Split a string vector<string> ofSplitString( const string& source ,const string& delimiters ,bool ignoreEmpty = false ,bool trim = false ); Result string items = "one|two|three|four|five |||test|"; part: one vector<string> parts = ofSplitString(items,"|",true,true); part: two for(int i = 0; i < parts.size(); ++i) { part: three cout << "part: " << parts[i] << "" << endl; part: four } part: five part: test
    12. 12. string manipulation Split a string vector<string> ofJoinString(vector<string>, const string delim) vector<string> loose_parts; Result loose_parts.push_back("I"); loose_parts.push_back("need"); I-need-some-OF-examples! loose_parts.push_back("some"); loose_parts.push_back("OF"); loose_parts.push_back("examples!"); string joined_string = ofJoinString(loose_parts, "-"); cout << joined_string << endl;
    13. 13. string manipulationIs a string in a string?bool ofIsStringInString(string haystack, string needle) string haystack_str = "Im searching for a needle in this haystack"; if(ofIsStringInString(haystack_str, "searching")) { cout << "yes, searching is in the string" << endl; } Result yes, searching is in the string
    14. 14. string manipulationCase conversionstring ofToUpper(const string& src)string ofToLower(const string& src) string str = "Just some string"; cout << ofToLower(str) << " = ofToLower" << endl; cout << ofToUpper(str) << " = ofToUpper" << endl; Result just some string = ofToLower JUST SOME STRING = ofToUpper
    15. 15. string manipulationType / hex conversion Convert int,float,uint,char,?? string ofToString(const T&) to string string ofToHex(string|char) int ofHexToInt(const string&) string ofHexToChar(const string&) float ofHexToFloat(const string&) string ofHexToString(const string&)
    16. 16. string manipulationString conversions Convert int,float,uint,char,?? string ofToString(const T&) to string int ofToInt(const string& str) Convert string to int char ofToChar(const string& str) Convert string to char float ofToFloat(const string& str) Convert string to float bool ofToBool(const string& str) Convert string to bool
    17. 17. string manipulationBinary utils string ofToBinary(const string& str) String to binary int ofBinaryToInt(const string& str) From binary to int char ofBinaryToChar(const string& str) From binary to char float ofBinaryToFloat(const string& str) From binary to float
    18. 18. screenshotsScreenshots Save what’s drawn to a file named by the current frame. void ofSaveFrame() The file is saved into the data directory. Save the current screen to a void ofSaveScreen(string filename) file in the data directory. void ofSaveViewport(string filename) Save current viewport to file
    19. 19. screenshots Screenshotsvoid testApp::draw(){ // create filename (each call we increment the counter) static int screen_num = 0; ++screen_num; char buf[512]; sprintf(buf,"screen_%04d.jpg",screen_num); // draw a simple circle at the center of screen and save it to image file. ofCircle(ofGetWidth() *0.5,ofGetHeight()*0.5,40); ofSaveScreen(buf);}
    20. 20. screenshots Screenshotsvoid testApp::draw(){ // create filename (each call we increment the counter) static int screen_num = 0; ++screen_num; char buf[512]; sprintf(buf,"screen_%04d.jpg",screen_num); // draw a simple circle at the center of screen and save it to image file. ofCircle(ofGetWidth() *0.5,ofGetHeight()*0.5,40); ofSaveScreen(buf);}
    21. 21. remote loadingLoad from url (synchronous) ofHttpResponse ofLoadURL(string url) ofHttpResponse resp = ofLoadURL("http://roxlu.com/ofloadurl.txt"); cout << resp.data << endl; ResultThis is just a test!
    22. 22. remote loadingLoad from url (async) int ofLoadURLAsync(string url, string name)• Loads asynchronous• Returns ID of process• You need to listen for URL notifications in testApp::urlResponse(ofHttpResponse&)
    23. 23. remote loadingAsynchronous loading Step 1. declare urlResponse in class header which wants to get notifications class testApp : public ofBaseApp{ public: void urlResponse(ofHttpResponse & response); }Step 2. define urlResponse in class which wants to get notificationsvoid testApp::urlResponse(ofHttpResponse & response){ if(response.status==200 && response.request.name == "async_req"){ img.loadImage(response.data); loading=false; } else{ cout << response.status << " " << response.error << endl; if(response.status!=-1) loading=false; }}
    24. 24. Asynchronous loading remote loadingStep 3. enable URL notificationsvoid testApp::setup(){ ofRegisterURLNotification(this);}Recap URL loading functionsofHttpResponse ofLoadURL(string url)int ofLoadURLAsync(string url, string name=””)void ofRemoveURLRequest(int id)void ofRemoveAllURLRequests()
    25. 25. threadingThreading in OF• Very easy to create threads using ofThread• Locking using lock/unlock() functions• Easy start/stop/joining• Just implement threadedFunction()• I.e. used to perform background processes
    26. 26. threadingCreating a threadStep 1. Create your thread class which extends ofThreadclass MyCustomThread : public ofThread {protected: virtual void threadedFunction() { while(true) { cout << "My own custom thread!" << endl; ofSleepMillis(3000); } }};Step 2. Create member in testApp.hclass testApp : public ofBaseApp{ public: MyCustomThread my_thread; ...}
    27. 27. threadingCreating a threadStep 3. Start the thread by calling startThread()void testApp::setup(){ // creates a non-blocking thread. (not verbose) my_thread.startThread(false, false);}
    28. 28. system toolsSystem tools void ofSystemAlertDialog(string) Show system Alert window ofFileDialogResult ofSystemLoadDialog(string Show system File Load windowtitle, bool folderselection) window ofFileDialogResult ofSystemSaveDialog(string Show system File Save defaultname, string messagename) window
    29. 29. system toolsSystem tools void testApp::setup(){ ofSystemAlertDialog("Whoot! Look out!"); }
    30. 30. system toolsSystem tools ofFileDialogResult dialog_result = ofSystemLoadDialog("Load image",false); if(dialog_result.bSuccess) { cout << "name: " << dialog_result.getName() << endl; cout << "file path: " << dialog_result.getPath() << endl; }
    31. 31. noiseSimplex noise 1D, 2D, 3D and 4Dfloat ofNoise(float) simplex noise.float ofNoise(float, float) Returns values infloat ofNoise(float, float, float) rangefloat ofNoise(float, float,float,float) 0.0 - 1.0 1D, 2D, 3D and 4Dfloat ofSignedNoise(float) simplex noise.float ofSignedNoise(float, float) Returns values infloat ofSignedNoise(float, float, float) rangefloat ofSignedNoise(float, float,float,float) -1.0 - 1.0
    32. 32. noiseSimplex noise float scale = 0.001; float scale = 0.01; float scale = 0.1; float scale = 0.7; void testApp::draw(){ float scale = 0.001; glBegin(GL_LINE_STRIP); for(float i = 0; i < ofGetWidth(); ++i) { glVertex2f(i,ofNoise(i*scale) * 50); } glEnd(); }
    33. 33. logging Logging• Simple logging to console or file• Support for basic log levels• Log level filtering• More advanced stuff, see ofxLogger (file rotation)
    34. 34. loggingLogging Set level to log. Only this void ofSetLogLevel(ofLogLevel) level will show up in console or file ofLogLevel ofGetLogLevel() Get current log level void ofLogToFile(string path) Log to path void ofLogToConsole() Log to console (default)
    35. 35. loggingLogging ofSetLogLevel(OF_LOG_VERBOSE); ofLog(OF_LOG_VERBOSE,"log something"); ofLog(OF_LOG_VERBOSE,"Something to log"); ofLog(OF_LOG_VERBOSE,"Something else to log"); ResultOF: OF_VERBOSE: log somethingOF: OF_VERBOSE: Something to logOF: OF_VERBOSE: Something else to log
    36. 36. loggingLogging Set level to log. Only this void ofSetLogLevel(ofLogLevel) level will show up in console or file ofLogLevel ofGetLogLevel() Get current log level void ofLogToFile(string path) Log to path void ofLogToConsole() Log to console (default)
    37. 37. file utilsFile utils ofBuffer Raw byte buffer class ofFilePath A file system path ofFile File class; handy functions ofDirectory Directory class; i.e. dirlists
    38. 38. file utils ofBuffer ofBuffer• Allows you to store raw data• This is useful when working on networked applications or hardware (arduino) when you want to use a custom protocol.Two handy global functions:ofBuffer ofBufferFromFile(const string& p, bool binary = false)bool ofBufferToFile(const string& p, ofBuffer& buf, bool bin=false);
    39. 39. file utils ofBuffer ofBuffer string data = "This isnjust a bunchnof rawndata withn somenline breaks."; ofBuffer buffer; buffer.set(data.c_str(), data.size()); while(!buffer.isLastLine()) { cout << "Buffer line: " << buffer.getNextLine() << endl; } Result Buffer line: This is Buffer line: just a bunch Buffer line: of raw Buffer line: data with Buffer line: some Buffer line: line breaks.
    40. 40. file utils ofBufferread file into buffer // read from file into buffer ofBuffer buf = ofBufferFromFile("of.log"); cout << "********" << endl << buf << endl << "********" << endl;Other functions...void set(const char*, int size)bool set(istream&)bool writeTo(ostream &stream)void clear()void allocate(long)char* getBinaryBuffer()const char* getBinaryBuffer()string getText()string getNextLine()string getFirstLine()bool isLastLine()
    41. 41. file utils ofFilePath File paths• Just easy class to play with paths• Use this for cleaning up paths, retrieving absolute paths, retrieving basenames, filenames, enclosing directories, current working dir.• All member functions are static
    42. 42. file utils ofFilePathFile pathsstatic string getFileExt(string filename)static string removeExt(string filename)static string addLeadingSlash(string path)static string addTrailingSlash(string path)static string removeTrailingSlash(string path)static string getPathForDirectory(string path)static string getAbsolutePath(string path, bool rel_data = true)static bool isAbsolute(string path)static string getFileName(string f,bool rel_data = true)static string getBaseName(string file)static string getEnclosingDirectory(string p, bool rel_data = true)static string getCurrentWorkingDirectory()
    43. 43. file utils ofFilePathFile pathscout << ofFilePath::getPathForDirectory("~/Documents");/Users/roxlu/Documents/cout << ofFilePath::getPathForDirectory("data");data/string path = "/just/some/path/photo.jpg";cout << ofFilePath::getFileExt(path);jpgstring path = "/just/some/path/photo.jpg";cout << ofFilePath::removeExt(path);/just/some/path/photostring path = "/just/some/path/photo.jpg";cout << ofFilePath::getFilename(path) << endl;photo.jpg
    44. 44. file utils ofFilePathFile pathsstring path = "/just/some/path/photo.jpg";cout << ofFilePath::getBaseName(path) << endl;photostring path = "/just/some/path/photo.jpg";cout << ofFilePath::getEnclosingDirectory(path) << endl;/just/some/path/cout << ofFilePath::getCurrentWorkingDirectory() << endl;/Users/roxlu/Documents/programming/c++/of/git/apps/examples/emptyExample/bin/emptyExampleDebug.app/Contents/MacOS/
    45. 45. file utils ofFileofFilebool open(string path, Mode m=ReadOnly, bool binary=false)bool changeMode(Mode m, bool binary=false)void close() bool canExecute()bool exists() bool isFile()string path() bool isLink()string getExtension() bool isDirectory()string getFileName() bool isDevice(string getBaseName() bool isHiddenstring getEnclosingDirectory() void setWriteble(bool writable)string getAbsolutePath() void setReadOnly(bool readable)bool canRead() void setExecutable(bool exec)bool canWrite() uint64_t getSize()
    46. 46. file utils ofFileofFilebool copyTo(string path, bool rel_to_data = true, bool overwrite = false)bool moveTo(string path, bool rel_to_data = true, bool overwrite = false)bool renameTo(string path, bool rel_to_data = true, bool overwrite = false)ofFile <> ofBufferofBuffer readToBuffer()bool writeFromBuffer(ofBuffer& buffer)bool renameTo(string path, bool rel_to_data = true, bool overwrite = false)
    47. 47. file utils ofFileofFile - static functionsstatic bool copyFromTo(string src, string dest, bool rel_to_data = true, bool overwrite = false)static bool moveFromTo(string src, string dest, bool rel_to_data = true, bool overwrite = false)static bool doesFileExist(string path,bool rel_to_data = true)static bool removeFile(string path,bool rel_to_data = true)
    48. 48. file utils ofDirectoryofDirectory• Similar to ofFile• Lots of handy function for moving, renaming, copying, deleting, file listing, etc...void open(string path) void setWriteble(bool writable)void close() void setReadOnly(bool readable)bool create(bool recursive = true)bool exists() void setExecutable(bool exec)string path() For more functions ofFileUtils.hbool canRead()bool canWrite()bool canExecute()bool isDirectory()bool isHidden()bool remove(bool recursive)
    49. 49. file utils ofDirectoryRetrieve all jpegs from a directoryofDirectory dir;dir.allowExt("jpg");int num_jpegs_in_datapath = dir.listDir(ofToDataPath(".",true));cout << "Num files in data path : " << num_jpegs_in_datapath << endl;for(int i = 0; i < num_jpegs_in_datapath; ++i) { cout << dir.getPath(i) << endl;}Result/Users/roxlu/Documents/programming/c++/of/git/apps/examples/emptyExample/bin/data/screen_0001.jpg/Users/roxlu/Documents/programming/c++/of/git/apps/examples/emptyExample/bin/data/screen_0002.jpg/Users/roxlu/Documents/programming/c++/of/git/apps/examples/emptyExample/bin/data/screen_0003.jpg/Users/roxlu/Documents/programming/c++/of/git/apps/examples/emptyExample/bin/data/screen_0004.jpg/Users/roxlu/Documents/programming/c++/of/git/apps/examples/emptyExample/bin/data/screen_0005.jpg/Users/roxlu/Documents/programming/c++/of/git/apps/examples/emptyExample/bin/data/screen_0006.jpg
    50. 50. file utils ofDirectorySome static functionsstatic bool createDirectory(string path, bool rel_to_data = true, bool recursive = false)static bool isDirectoryEmtpy(string path, bool rel_to_data = true)static bool doesDirectoryExist(string path, bool rel_to_data = true)static bool removeDirectory(string path, bool deleteIfNotEmpty, bool bRelativeToData = true)
    51. 51. constantsDevelopment Math/TrigOF_VERSION HALF_PI CLAMP(val,min,max)OF_VERSION_MINOR PI ABS(x)TARGET_WIN32 TWO_PI OF_OUTLINETARGET_OF_IPHONE FOUR_PI OF_FILLEDTARGET_ANDROID DEG_TO_RADTARGET_LINUS RAD_TO_DEG WindowTARGET_OPENGLES MIN(x,y) OF_WINDOW OF_FULLSCREENOF_USING_POCO MAX(x,y) OF_GAME_MODE
    52. 52. constantsRectangle modes Pixel formats Blend modesOF_RECTMODE_CORNER OF_PIXELS_MONO OF_BLENDMODE_DISABLEDOF_RECTMODE_CENTER OF_PIXELS_RGB OF_BLENDMODE_ALPHA OF_PIXELS_RGBA OF_BLENDMODE_ADDImage types OF_PIXELS_BGRA OF_BLENDMODE_SUBTRACTOF_IMAGE_GRAYSCALE OF_PIXELS_RGB565 OF_BLENDMODE_MULTIPLYOF_IMAGE_COLOR OF_BLENDMODE_SCREENOF_IMAGE_COLOR_ALPHAOF_IMAGE_UNDEFINED
    53. 53. constantsOrientations ofLoopTypeOF_ORIENTATION_UNKNOWN OF_LOOP_NONEOF_ORIENTATION_DEFAULT OF_LOOP_PALINDROMEOF_ORIENTATION_90_LEFT OF_LOOP_NORMALOF_ORIENTATION_180OF_ORIENTATION_90_RIGHTFor more defines see ofConstants
    54. 54. constantsFunction keys Cursor keysOF_KEY_F1 OF_KEY_LEFTOF_KEY_F2 OF_KEY_RIGHT... OF_KEY_DOWNOF_KEY_F12 OF_KEY_UPSpecial keysOF_KEY_PAGE_UP OF_KEY_INSERT OF_KEY_ALTOF_KEY_PAGE_DOWN OF_KEY_RETURN OF_KEY_SHIFTOF_KEY_HOME OF_KEY_ESC OF_KEY_BACKSPACEOF_KEY_END OF_KEY_CTRL OF_KEY_DELFor more defines see ofConstants
    55. 55. roxluwww.roxlu.com

    ×