diff options
| author | Comment <tim@gray.(none)> | 2013-09-08 13:11:02 +0100 |
|---|---|---|
| committer | Comment <tim@gray.(none)> | 2013-09-08 13:11:02 +0100 |
| commit | 1ff03ea63d79549db86422837f47916a42f23eb9 (patch) | |
| tree | 1631546f60cb830749d6fe64d8af0911d9afcfe5 | |
| parent | 512a2738e9f2fc74f109dabada357cc20c2a3412 (diff) | |
refactoring utils
| -rw-r--r-- | rotord/src/graph.cpp | 14 | ||||
| -rw-r--r-- | rotord/src/graph.h | 2 | ||||
| -rw-r--r-- | rotord/src/nodes_audio_analysis.cpp | 6 | ||||
| -rw-r--r-- | rotord/src/nodes_drawing.h | 2 | ||||
| -rwxr-xr-x | rotord/src/ofUtils.cpp | 745 | ||||
| -rwxr-xr-x | rotord/src/ofUtils.h | 223 | ||||
| -rw-r--r-- | rotord/src/rendercontext.cpp | 14 | ||||
| -rwxr-xr-x | rotord/src/rotor.cpp | 10 | ||||
| -rwxr-xr-x | rotord/src/rotor.h | 12 | ||||
| -rwxr-xr-x | rotord/src/rotord.cpp | 2 | ||||
| -rw-r--r-- | rotord/src/utils.cpp | 111 | ||||
| -rw-r--r-- | rotord/src/utils.h | 86 | ||||
| -rwxr-xr-x | rotord/src/xmlIO.cpp | 20 | ||||
| -rwxr-xr-x | rotord/src/xmlIO.h | 2 |
14 files changed, 239 insertions, 1010 deletions
diff --git a/rotord/src/graph.cpp b/rotord/src/graph.cpp index f54b18c..313df2a 100644 --- a/rotord/src/graph.cpp +++ b/rotord/src/graph.cpp @@ -3,7 +3,7 @@ using namespace Rotor; using Poco::Logger; -const string Graph::toString(){ +const string Graph::graphToString(){ string xmlgraph; if (loaded) { xml.copyXmlToString(xmlgraph); @@ -51,7 +51,7 @@ bool Graph::preview(xmlIO &XML,string &node,string &_format,int frame,int w,int if (nodes.find(node)!=nodes.end()){ float t=frame/framerate; XML.addTag("preview"); - XML.addAttribute("preview","frame",ofToString(frame),0); + XML.addAttribute("preview","frame",toString(frame),0); XML.addAttribute("preview","nodeID",node,0); XML.pushTag("preview"); if (dynamic_cast<Signal_node*>(nodes[node])){ @@ -113,7 +113,7 @@ bool Graph::video_render(const string &output_filename,const float framerate) { Logger& logger = Logger::get("Rotor"); - logger.information("Video_output rendering "+output_filename+": "+ofToString(duration)+" seconds at "+ofToString(framerate)+" fps, audio frame size: "+ofToString(exporter.get_audio_framesize())); + logger.information("Video_output rendering "+output_filename+": "+toString(duration)+" seconds at "+toString(framerate)+" fps, audio frame size: "+toString(exporter.get_audio_framesize())); //25fps video and 43.06640625fps audio? hmm //how to get the timecodes correct for the interleaved files @@ -128,7 +128,7 @@ bool Graph::video_render(const string &output_filename,const float framerate) { //does audioloader output interleaved samples? samples_in_frame=(audioloader.codecContext->sample_rate)/framerate; string whether=usingaudio?"Loading":"Cannot load"; - logger.information(whether+" audio file: "+audio_filename+", each frame contains "+ofToString(samples_in_frame)+" samples at "+ofToString(audioloader.codecContext->sample_rate)+" hz"); + logger.information(whether+" audio file: "+audio_filename+", each frame contains "+toString(samples_in_frame)+" samples at "+toString(audioloader.codecContext->sample_rate)+" hz"); audioframe=new uint16_t[(samples_in_frame+exporter.get_audio_framesize())*audioloader.codecContext->channels]; } @@ -203,7 +203,7 @@ bool Graph::video_render(const string &output_filename,const float framerate) { float mtime = ((end.tv_sec-start.tv_sec) + (end.tv_usec-start.tv_usec)/1000000.0) + 0.5; - logger.information("Video_output: rendered "+output_filename+": in "+ofToString(mtime)+" seconds"); + logger.information("Video_output: rendered "+output_filename+": in "+toString(mtime)+" seconds"); if (usingaudio) { audioloader.close(); @@ -454,7 +454,7 @@ bool Graph::parseXml(string media_path){ string parameter=xml.getAttribute("parameter","name","",i4); if (nodes[nodeID]->parameters.find(parameter)!=nodes[nodeID]->parameters.end()) { string val=xml.getAttribute("parameter","value","",i4); - if (val!="") nodes[nodeID]->parameters.find(parameter)->second->value=ofToFloat(val); + if (val!="") nodes[nodeID]->parameters.find(parameter)->second->value=toFloat(val); string fromID=xml.getAttribute("parameter","from","",i4); if (nodes.find(fromID)!=nodes.end()) { if (!nodes[nodeID]->parameters[parameter]->connect(nodes[fromID])){ @@ -473,7 +473,7 @@ bool Graph::parseXml(string media_path){ string parameter=xml.getAttribute("parameter_input","name","",i4); if (nodes[nodeID]->parameters.find(parameter)!=nodes[nodeID]->parameters.end()) { string val=xml.getAttribute("parameter_input","value","",i4); - if (val!="") nodes[nodeID]->parameters.find(parameter)->second->value=ofToFloat(val); + if (val!="") nodes[nodeID]->parameters.find(parameter)->second->value=toFloat(val); string fromID=xml.getAttribute("parameter_input","from","",i4); if (nodes.find(fromID)!=nodes.end()) { if (!nodes[nodeID]->parameters[parameter]->connect(nodes[fromID])){ diff --git a/rotord/src/graph.h b/rotord/src/graph.h index df6564d..231d784 100644 --- a/rotord/src/graph.h +++ b/rotord/src/graph.h @@ -45,7 +45,7 @@ namespace Rotor { bool loaded; float duration; float framerate; - const string toString(); + const string graphToString(); xmlIO xml; bool audio_loaded; string audio_filename; diff --git a/rotord/src/nodes_audio_analysis.cpp b/rotord/src/nodes_audio_analysis.cpp index c997cae..74b0574 100644 --- a/rotord/src/nodes_audio_analysis.cpp +++ b/rotord/src/nodes_audio_analysis.cpp @@ -86,7 +86,7 @@ namespace Rotor{ string vdata; for (int i=0;i<width;i++){ if (i>0) vdata+=","; - vdata+=ofToString(vectordata[i]); + vdata+=toString(vectordata[i]); } XML.addValue("data",vdata); } @@ -115,7 +115,7 @@ namespace Rotor{ string Vamp_node::get_features(){ string data; for (auto i: analyser.features) { - data=data+" ["+ofToString(i.second.number)+":"+ofToString(i.first); + data=data+" ["+toString(i.second.number)+":"+toString(i.first); if (i.second.values.size()) { data+=" ("; bool first=true; @@ -124,7 +124,7 @@ namespace Rotor{ first=false; } else data+=","; - data=data+ofToString(j); + data=data+toString(j); } data+=") "; } diff --git a/rotord/src/nodes_drawing.h b/rotord/src/nodes_drawing.h index 370c0fb..34a2679 100644 --- a/rotord/src/nodes_drawing.h +++ b/rotord/src/nodes_drawing.h @@ -62,7 +62,7 @@ namespace Rotor { void vector_output(cairo_t * cr,const Frame_spec &frame){ string text; if (parameters["number"]->value>-99999998.0f){ - text=ofToString(parameters["number"]->value,4); + text=toString(parameters["number"]->value,4); } else text=attributes["text"]->value; cairo_text_extents_t te; diff --git a/rotord/src/ofUtils.cpp b/rotord/src/ofUtils.cpp deleted file mode 100755 index 7d7d9cc..0000000 --- a/rotord/src/ofUtils.cpp +++ /dev/null @@ -1,745 +0,0 @@ -#include "ofUtils.h" -//#include "ofImage.h" -//#include "ofTypes.h" -//#include "ofGraphics.h" -//#include "ofAppRunner.h" - -#include "Poco/String.h" -#include "Poco/LocalDateTime.h" -#include "Poco/DateTimeFormatter.h" - -#include <cctype> // for toupper - - - -/* -#ifdef TARGET_WIN32 - #ifndef _MSC_VER - #include <unistd.h> // this if for MINGW / _getcwd - #include <sys/param.h> // for MAXPATHLEN - #endif -#endif - - -#if defined(TARGET_OF_IPHONE) || defined(TARGET_OSX ) || defined(TARGET_LINUX) - #include <sys/time.h> -#endif - -#ifdef TARGET_OSX - #ifndef TARGET_OF_IPHONE - #include <mach-o/dyld.h> - #include <sys/param.h> // for MAXPATHLEN - #endif -#endif - -#ifdef TARGET_WIN32 - #include <mmsystem.h> - #ifdef _MSC_VER - #include <direct.h> - #endif - -#endif -*/ - -#ifndef MAXPATHLEN - #define MAXPATHLEN 1024 -#endif - - -static bool enableDataPath = true; -//static unsigned long startTime = ofGetSystemTime(); // better at the first frame ?? (currently, there is some delay from static init, to running. -//static unsigned long startTimeMicros = ofGetSystemTimeMicros(); - -/* -//-------------------------------------- -unsigned long ofGetElapsedTimeMillis(){ - return ofGetSystemTime() - startTime; -} - -//-------------------------------------- -unsigned long ofGetElapsedTimeMicros(){ - return ofGetSystemTimeMicros() - startTimeMicros; -} - -//-------------------------------------- -float ofGetElapsedTimef(){ - return ofGetElapsedTimeMicros() / 1000000.0f; -} - -//-------------------------------------- -void ofResetElapsedTimeCounter(){ - startTime = ofGetSystemTime(); - startTimeMicros = ofGetSystemTimeMicros(); -} -*/ -//======================================= -// this is from freeglut, and used internally: -/* Platform-dependent time in milliseconds, as an unsigned 32-bit integer. - * This value wraps every 49.7 days, but integer overflows cancel - * when subtracting an initial start time, unless the total time exceeds - * 32-bit, where the GLUT API return value is also overflowed. - */ -/* -unsigned long ofGetSystemTime( ) { - #ifndef TARGET_WIN32 - struct timeval now; - gettimeofday( &now, NULL ); - return now.tv_usec/1000 + now.tv_sec*1000; - #else - #if defined(_WIN32_WCE) - return GetTickCount(); - #else - return timeGetTime(); - #endif - #endif -} -*/ - -/* -unsigned long ofGetSystemTimeMicros( ) { - #ifndef TARGET_WIN32 - struct timeval now; - gettimeofday( &now, NULL ); - return now.tv_usec + now.tv_sec*1000000; - #else - #if defined(_WIN32_WCE) - return GetTickCount()*1000; - #else - return timeGetTime()*1000; - #endif - #endif -} -*/ -//-------------------------------------------------- -unsigned int ofGetUnixTime(){ - return (unsigned int)time(NULL); -} - -//default ofGetTimestampString returns in this format: 2011-01-15-18-29-35-299 -//-------------------------------------------------- -string ofGetTimestampString(){ - string timeFormat = "%Y-%m-%d-%H-%M-%S-%i"; - Poco::LocalDateTime now; - return Poco::DateTimeFormatter::format(now, timeFormat); -} - -//specify the string format - eg: %Y-%m-%d-%H-%M-%S-%i ( 2011-01-15-18-29-35-299 ) -//-------------------------------------------------- -string ofGetTimestampString(string timestampFormat){ - Poco::LocalDateTime now; - return Poco::DateTimeFormatter::format(now, timestampFormat); -} - -//-------------------------------------------------- -int ofGetSeconds(){ - time_t curr; - tm local; - time(&curr); - local =*(localtime(&curr)); - return local.tm_sec; -} - -//-------------------------------------------------- -int ofGetMinutes(){ - time_t curr; - tm local; - time(&curr); - local =*(localtime(&curr)); - return local.tm_min; -} - -//-------------------------------------------------- -int ofGetHours(){ - time_t curr; - tm local; - time(&curr); - local =*(localtime(&curr)); - return local.tm_hour; -} - -//-------------------------------------------------- -int ofGetYear(){ - time_t curr; - tm local; - time(&curr); - local =*(localtime(&curr)); - int year = local.tm_year + 1900; - return year; -} - -//-------------------------------------------------- -int ofGetMonth(){ - time_t curr; - tm local; - time(&curr); - local =*(localtime(&curr)); - int month = local.tm_mon + 1; - return month; -} - -//-------------------------------------------------- -int ofGetDay(){ - time_t curr; - tm local; - time(&curr); - local =*(localtime(&curr)); - return local.tm_mday; -} - -//-------------------------------------------------- -int ofGetWeekday(){ - time_t curr; - tm local; - time(&curr); - local =*(localtime(&curr)); - return local.tm_wday; -} - -//-------------------------------------------------- -void ofEnableDataPath(){ - enableDataPath = true; -} - -//-------------------------------------------------- -void ofDisableDataPath(){ - enableDataPath = false; -} - -//-------------------------------------------------- -//use ofSetDataPathRoot() to override this -static string & dataPathRoot(){ -#if defined TARGET_OSX - static string * dataPathRoot = new string("../../../data/"); -#elif defined TARGET_ANDROID - static string * dataPathRoot = new string("sdcard/"); -#elif defined(TARGET_LINUX) - static string * dataPathRoot = new string(ofFilePath::join(ofFilePath::getCurrentExeDir(), "data/")); -#else - static string * dataPathRoot = new string("data/"); -#endif - return *dataPathRoot; -} - -static bool & isDataPathSet(){ - static bool * dataPathSet = new bool(false); - return * dataPathSet; -} - -//-------------------------------------------------- -void ofSetDataPathRoot(string newRoot){ - string newPath = ""; - - #ifdef TARGET_OSX - #ifndef TARGET_OF_IPHONE - char path[MAXPATHLEN]; - uint32_t size = sizeof(path); - - if (_NSGetExecutablePath(path, &size) == 0){ - //printf("executable path is %s\n", path); - string pathStr = string(path); - - //theo: check this with having '/' as a character in a folder name - OSX treats the '/' as a ':' - //checked with spaces too! - - vector < string> pathBrokenUp = ofSplitString( pathStr, "/"); - - newPath = ""; - - for(int i = 0; i < pathBrokenUp.size()-1; i++){ - newPath += pathBrokenUp[i]; - newPath += "/"; - } - - //cout << newPath << endl; // some sanity checks here - //system( "pwd" ); - - chdir ( newPath.c_str() ); - //system("pwd"); - }else{ - ofLog(OF_LOG_FATAL_ERROR, "buffer too small; need size %u\n", size); - } - #endif - #endif - - dataPathRoot() = newRoot; - isDataPathSet() = true; -} - -//-------------------------------------------------- -string ofToDataPath(string path, bool makeAbsolute){ - - if (!isDataPathSet()) - ofSetDataPathRoot(dataPathRoot()); - - if( enableDataPath ){ - - //check if absolute path has been passed or if data path has already been applied - //do we want to check for C: D: etc ?? like substr(1, 2) == ':' ?? - if( path.length()==0 || (path.substr(0,1) != "/" && path.substr(1,1) != ":" && path.substr(0,dataPathRoot().length()) != dataPathRoot())){ - path = dataPathRoot()+path; - } - - if(makeAbsolute && (path.length()==0 || path.substr(0,1) != "/")){ - /* - #if !defined( TARGET_OF_IPHONE) & !defined(TARGET_ANDROID) - - #ifndef TARGET_WIN32 - char currDir[1024]; - path = "/"+path; - path = getcwd(currDir, 1024)+path; - - #else - - char currDir[1024]; - path = "\\"+path; - path = _getcwd(currDir, 1024)+path; - std::replace( path.begin(), path.end(), '/', '\\' ); // fix any unixy paths... - - - #endif - - - #else - //do we need iphone specific code here? - #endif - */ - } - - } - return path; -} - -//---------------------------------------- -template <> -string ofToHex(const string& value) { - ostringstream out; - // how many bytes are in the string - int numBytes = value.size(); - for(int i = 0; i < numBytes; i++) { - // print each byte as a 2-character wide hex value - out << setfill('0') << setw(2) << hex << (unsigned int) ((unsigned char)value[i]); - } - return out.str(); -} - -//---------------------------------------- -string ofToHex(const char* value) { - // this function is necessary if you want to print a string - // using a syntax like ofToHex("test") - return ofToHex((string) value); -} - -//---------------------------------------- -int ofToInt(const string& intString) { - int x = 0; - istringstream cur(intString); - cur >> x; - return x; -} - -//---------------------------------------- -int ofHexToInt(const string& intHexString) { - int x = 0; - istringstream cur(intHexString); - cur >> hex >> x; - return x; -} - -//---------------------------------------- -char ofHexToChar(const string& charHexString) { - int x = 0; - istringstream cur(charHexString); - cur >> hex >> x; - return (char) x; -} - -//---------------------------------------- -float ofHexToFloat(const string& floatHexString) { - union intFloatUnion { - int x; - float f; - } myUnion; - myUnion.x = 0; - istringstream cur(floatHexString); - cur >> hex >> myUnion.x; - return myUnion.f; -} - -//---------------------------------------- -string ofHexToString(const string& stringHexString) { - stringstream out; - stringstream stream(stringHexString); - // a hex string has two characters per byte - int numBytes = stringHexString.size() / 2; - for(int i = 0; i < numBytes; i++) { - string curByte; - // grab two characters from the hex string - stream >> setw(2) >> curByte; - // prepare to parse the two characters - stringstream curByteStream(curByte); - int cur = 0; - // parse the two characters as a hex-encoded int - curByteStream >> hex >> cur; - // add the int as a char to our output stream - out << (char) cur; - } - return out.str(); -} - -//---------------------------------------- -float ofToFloat(const string& floatString) { - float x = 0; - istringstream cur(floatString); - cur >> x; - return x; -} - -//---------------------------------------- -bool ofToBool(const string& boolString) { - static const string trueString = "true"; - static const string falseString = "false"; - string lower = Poco::toLower(boolString); - if(lower == trueString) { - return true; - } - if(lower == falseString) { - return false; - } - bool x = false; - istringstream cur(lower); - cur >> x; - return x; -} - -//---------------------------------------- -char ofToChar(const string& charString) { - char x = '\0'; - istringstream cur(charString); - cur >> x; - return x; -} - -//---------------------------------------- -template <> string ofToBinary(const string& value) { - stringstream out; - int numBytes = value.size(); - for(int i = 0; i < numBytes; i++) { - bitset<8> bitBuffer(value[i]); - out << bitBuffer; - } - return out.str(); -} - -//---------------------------------------- -string ofToBinary(const char* value) { - // this function is necessary if you want to print a string - // using a syntax like ofToBinary("test") - return ofToBinary((string) value); -} - -//---------------------------------------- -int ofBinaryToInt(const string& value) { - const int intSize = sizeof(int) * 8; - bitset<intSize> binaryString(value); - return (int) binaryString.to_ulong(); -} - -//---------------------------------------- -char ofBinaryToChar(const string& value) { - const int charSize = sizeof(char) * 8; - bitset<charSize> binaryString(value); - return (char) binaryString.to_ulong(); -} - -//---------------------------------------- -float ofBinaryToFloat(const string& value) { - const int floatSize = sizeof(float) * 8; - bitset<floatSize> binaryString(value); - union ulongFloatUnion { - unsigned long result; - float f; - } myUFUnion; - myUFUnion.result = binaryString.to_ulong(); - return myUFUnion.f; -} -//---------------------------------------- -string ofBinaryToString(const string& value) { - ostringstream out; - stringstream stream(value); - bitset<8> byteString; - int numBytes = value.size() / 8; - for(int i = 0; i < numBytes; i++) { - stream >> byteString; - out << (char) byteString.to_ulong(); - } - return out.str(); -} - -//-------------------------------------------------- -vector <string> ofSplitString(const string & source, const string & delimiter, bool ignoreEmpty, bool trim) { - vector<string> result; - if (delimiter.empty()) { - result.push_back(source); - return result; - } - string::const_iterator substart = source.begin(), subend; - while (true) { - subend = search(substart, source.end(), delimiter.begin(), delimiter.end()); - string sub(substart, subend); - if(trim) { - Poco::trimInPlace(sub); - } - if (!ignoreEmpty || !sub.empty()) { - result.push_back(sub); - } - if (subend == source.end()) { - break; - } - substart = subend + delimiter.size(); - } - return result; -} - -//-------------------------------------------------- -string ofJoinString(vector <string> stringElements, const string & delimiter){ - string resultString = ""; - int numElements = stringElements.size(); - - for(int k = 0; k < numElements; k++){ - if( k < numElements-1 ){ - resultString += stringElements[k] + delimiter; - } else { - resultString += stringElements[k]; - } - } - - return resultString; -} - -//-------------------------------------------------- -void ofStringReplace(string& input, string searchStr, string replaceStr){ - size_t uPos = 0; - size_t uFindLen = searchStr.length(); - size_t uReplaceLen = replaceStr.length(); - - if( uFindLen == 0 ){ - return; - } - - for( ;(uPos = input.find( searchStr, uPos )) != std::string::npos; ){ - input.replace( uPos, uFindLen, replaceStr ); - uPos += uReplaceLen; - } -} - -//-------------------------------------------------- -bool ofIsStringInString(string haystack, string needle){ - return ( strstr(haystack.c_str(), needle.c_str() ) != NULL ); -} - -//-------------------------------------------------- -string ofToLower(const string & src){ - string dst(src); - transform(src.begin(),src.end(),dst.begin(),::tolower); - return dst; -} - -//-------------------------------------------------- -string ofToUpper(const string & src){ - string dst(src); - transform(src.begin(),src.end(),dst.begin(),::toupper); - return dst; -} - -//-------------------------------------------------- -string ofVAArgsToString(const char * format, ...){ - // variadic args to string: - // http://www.codeproject.com/KB/string/string_format.aspx - static char aux_buffer[10000]; - string retStr(""); - if (NULL != format){ - - va_list marker; - - // initialize variable arguments - va_start(marker, format); - - // Get formatted string length adding one for NULL - size_t len = vsprintf(aux_buffer, format, marker) + 1; - - // Reset variable arguments - va_end(marker); - - if (len > 0) - { - va_list args; - - // initialize variable arguments - va_start(args, format); - - // Create a char vector to hold the formatted string. - vector<char> buffer(len, '\0'); - vsprintf(&buffer[0], format, args); - retStr = &buffer[0]; - va_end(args); - } - - } - return retStr; -} - -string ofVAArgsToString(const char * format, va_list args){ - // variadic args to string: - // http://www.codeproject.com/KB/string/string_format.aspx - char aux_buffer[10000]; - string retStr(""); - if (NULL != format){ - - // Get formatted string length adding one for NULL - vsprintf(aux_buffer, format, args); - retStr = aux_buffer; - - } - return retStr; -} - -/* -//-------------------------------------------------- -void ofLaunchBrowser(string url){ - - // http://support.microsoft.com/kb/224816 - - //make sure it is a properly formatted url - if(Poco::icompare(url.substr(0,7), "http://") != 0 && - Poco::icompare(url.substr(0,8), "https://") != 0) { - ofLog(OF_LOG_WARNING, "ofLaunchBrowser: url must begin http:// or https://"); - return; - } - - //---------------------------- - #ifdef TARGET_WIN32 - //---------------------------- - - #if (_MSC_VER) - // microsoft visual studio yaks about strings, wide chars, unicode, etc - ShellExecuteA(NULL, "open", url.c_str(), - NULL, NULL, SW_SHOWNORMAL); - #else - ShellExecute(NULL, "open", url.c_str(), - NULL, NULL, SW_SHOWNORMAL); - #endif - - //---------------------------- - #endif - //---------------------------- - - //-------------------------------------- - #ifdef TARGET_OSX - //-------------------------------------- - // ok gotta be a better way then this, - // this is what I found... - string commandStr = "open "+url; - system(commandStr.c_str()); - //---------------------------- - #endif - //---------------------------- - - //-------------------------------------- - #ifdef TARGET_LINUX - //-------------------------------------- - string commandStr = "xdg-open "+url; - int ret = system(commandStr.c_str()); - if(ret!=0) ofLog(OF_LOG_ERROR,"ofLaunchBrowser: couldn't open browser"); - //---------------------------- - #endif - //---------------------------- -} - -//-------------------------------------------------- -string ofGetVersionInfo(){ - string version; - stringstream sstr; - sstr << "of version: " << OF_VERSION << endl; - return sstr.str(); -} -*/ -//---- new to 006 -//from the forums http://www.openframeworks.cc/forum/viewtopic.php?t=1413 -/* -//-------------------------------------------------- -void ofSaveScreen(string filename) { - ofImage screen; - screen.allocate(ofGetWidth(), ofGetHeight(), OF_IMAGE_COLOR); - screen.grabScreen(0, 0, ofGetWidth(), ofGetHeight()); - screen.saveImage(filename); -} - -//-------------------------------------------------- -void ofSaveViewport(string filename) { - // because ofSaveScreen doesn't related to viewports - ofImage screen; - ofRectangle view = ofGetCurrentViewport(); - screen.allocate(view.width, view.height, OF_IMAGE_COLOR); - screen.grabScreen(0, 0, view.width, view.height); - screen.saveImage(filename); -} - -//-------------------------------------------------- -int saveImageCounter = 0; -void ofSaveFrame(bool bUseViewport){ - string fileName = ofToString(saveImageCounter) + ".png"; - if (bUseViewport){ - ofSaveViewport(fileName); - } else { - ofSaveScreen(fileName); - } - saveImageCounter++; -} - -//-------------------------------------------------- -string ofSystem(string command){ - FILE * ret = NULL; -#ifdef TARGET_WIN32 - ret = _popen(command.c_str(),"r"); -#else - ret = popen(command.c_str(),"r"); -#endif - - string strret; - char c; - - if (ret == NULL){ - ofLogError() << "ofSystem: error opening return file"; - }else{ - do { - c = fgetc (ret); - strret += c; - } while (c != EOF); - fclose (ret); - } - - return strret; -} - -//-------------------------------------------------- -ofTargetPlatform ofGetTargetPlatform(){ -#ifdef TARGET_LINUX - if(ofSystem("uname -m").find("x86_64")==0) - return OF_TARGET_LINUX64; - else - return OF_TARGET_LINUX; -#elif defined(TARGET_OSX) - return OF_TARGET_OSX; -#elif defined(TARGET_WIN32) - #if (_MSC_VER) - return OF_TARGET_WINVS; - #else - return OF_TARGET_WINGCC; - #endif -#elif defined(TARGET_ANDROID) - return OF_TARGET_ANDROID; -#elif defined(TARGET_OF_IPHONE) - return OF_TARGET_IPHONE; -#endif -} -*/
\ No newline at end of file diff --git a/rotord/src/ofUtils.h b/rotord/src/ofUtils.h deleted file mode 100755 index 0567e22..0000000 --- a/rotord/src/ofUtils.h +++ /dev/null @@ -1,223 +0,0 @@ -#pragma once - -//#include "ofConstants.h" - - -// core: --------------------------- -#include <cstdio> -#include <cstdarg> -#include <cmath> -#include <ctime> -#include <cstdlib> -#include <string> -#include <iostream> -#include <vector> -#include <cstring> -#include <sstream> //for ostringsream -#include <iomanip> //for setprecision -#include <fstream> -#include <algorithm> - -#include <bitset> // for ofToBinary - - - - -//#include "ofLog.h" - -/*#ifdef TARGET_WIN32 // for ofLaunchBrowser - #include <shellapi.h> -#endif -*/ - - -using namespace std; - -int ofNextPow2(int input); - -void ofResetElapsedTimeCounter(); // this happens on the first frame -float ofGetElapsedTimef(); -unsigned long ofGetElapsedTimeMillis(); -unsigned long ofGetElapsedTimeMicros(); -int ofGetFrameNum(); - -int ofGetSeconds(); -int ofGetMinutes(); -int ofGetHours(); - -//number of seconds since 1970 -unsigned int ofGetUnixTime(); - - -/* -unsigned long ofGetSystemTime( ); // system time in milliseconds; -unsigned long ofGetSystemTimeMicros( ); // system time in microseconds; - - //returns -string ofGetTimestampString(); -string ofGetTimestampString(string timestampFormat); - - -int ofGetYear(); -int ofGetMonth(); -int ofGetDay(); -int ofGetWeekday(); - -void ofLaunchBrowser(string url); -*/ -void ofEnableDataPath(); -void ofDisableDataPath(); -string ofToDataPath(string path, bool absolute=false); - -template<class T> -void ofRandomize(vector<T>& values) { - random_shuffle(values.begin(), values.end()); -} - -template<class T, class BoolFunction> -void ofRemove(vector<T>& values, BoolFunction shouldErase) { - values.erase(remove_if(values.begin(), values.end(), shouldErase), values.end()); -} - -template<class T> -void ofSort(vector<T>& values) { - sort(values.begin(), values.end()); -} -template<class T, class BoolFunction> -void ofSort(vector<T>& values, BoolFunction compare) { - sort(values.begin(), values.end(), compare); -} - -template <class T> -unsigned int ofFind(const vector<T>& values, const T& target) { - return distance(values.begin(), find(values.begin(), values.end(), target)); -} - -template <class T> -bool ofContains(const vector<T>& values, const T& target) { - return ofFind(values, target) != values.size(); -} - -//set the root path that ofToDataPath will use to search for files relative to the app -//the path must have a trailing slash (/) !!!! -void ofSetDataPathRoot( string root ); - -template <class T> -string ofToString(const T& value){ - ostringstream out; - out << value; - return out.str(); -} - -/// like sprintf "%4f" format, in this example precision=4 -template <class T> -string ofToString(const T& value, int precision){ - ostringstream out; - out << fixed << setprecision(precision) << value; - return out.str(); -} - -/// like sprintf "% 4d" or "% 4f" format, in this example width=4, fill=' ' -template <class T> -string ofToString(const T& value, int width, char fill ){ - ostringstream out; - out << fixed << setfill(fill) << setw(width) << value; - return out.str(); -} - -/// like sprintf "%04.2d" or "%04.2f" format, in this example precision=2, width=4, fill='0' -template <class T> -string ofToString(const T& value, int precision, int width, char fill ){ - ostringstream out; - out << fixed << setfill(fill) << setw(width) << setprecision(precision) << value; - return out.str(); -} - -template<class T> -string ofToString(const vector<T>& values) { - stringstream out; - int n = values.size(); - out << "{"; - if(n > 0) { - for(int i = 0; i < n - 1; i++) { - out << values[i] << ", "; - } - out << values[n - 1]; - } - out << "}"; - return out.str(); -} - -template <class T> -string ofToHex(const T& value) { - ostringstream out; - // pretend that the value is a bunch of bytes - unsigned char* valuePtr = (unsigned char*) &value; - // the number of bytes is determined by the datatype - int numBytes = sizeof(T); - // the bytes are stored backwards (least significant first) - for(int i = numBytes - 1; i >= 0; i--) { - // print each byte out as a 2-character wide hex value - out << setfill('0') << setw(2) << hex << (int) valuePtr[i]; - } - return out.str(); -} -template <> -string ofToHex(const string& value); -string ofToHex(const char* value); - -int ofHexToInt(const string& intHexString); -char ofHexToChar(const string& charHexString); -float ofHexToFloat(const string& floatHexString); -string ofHexToString(const string& stringHexString); - -int ofToInt(const string& intString); -char ofToChar(const string& charString); -float ofToFloat(const string& floatString); -bool ofToBool(const string& boolString); - -template <class T> -string ofToBinary(const T& value) { - ostringstream out; - const char* data = (const char*) &value; - // the number of bytes is determined by the datatype - int numBytes = sizeof(T); - // the bytes are stored backwards (least significant first) - for(int i = numBytes - 1; i >= 0; i--) { - bitset<8> cur(data[i]); - out << cur; - } - return out.str(); -} -template <> -string ofToBinary(const string& value); -string ofToBinary(const char* value); - -int ofBinaryToInt(const string& value); -char ofBinaryToChar(const string& value); -float ofBinaryToFloat(const string& value); -string ofBinaryToString(const string& value); - -string ofGetVersionInfo(); - -void ofSaveScreen(string filename); -void ofSaveFrame(bool bUseViewport = false); -void ofSaveViewport(string filename); - -//-------------------------------------------------- -vector <string> ofSplitString(const string & source, const string & delimiter, bool ignoreEmpty = false, bool trim = false); -string ofJoinString(vector <string> stringElements, const string & delimiter); -void ofStringReplace(string& input, string searchStr, string replaceStr); -bool ofIsStringInString(string haystack, string needle); - -string ofToLower(const string & src); -string ofToUpper(const string & src); - -string ofVAArgsToString(const char * format, ...); -string ofVAArgsToString(const char * format, va_list args); - -string ofSystem(string command); - -//ofTargetPlatform ofGetTargetPlatform(); - - diff --git a/rotord/src/rendercontext.cpp b/rotord/src/rendercontext.cpp index d88bd68..8b4053f 100644 --- a/rotord/src/rendercontext.cpp +++ b/rotord/src/rendercontext.cpp @@ -76,8 +76,8 @@ void Render_context::session_command(const Session_command& command,xmlIO& XML,H if (state!=RENDERING) { Poco::StringTokenizer t1(command.body,","); if (t1.count()>1){ - int w=ofToInt(t1[0]); - int h=ofToInt(t1[1]); + int w=toInt(t1[0]); + int h=toInt(t1[1]); if (graph.set_resolution(w,h)){ logger.information("resolution set to "+t1[0]+"x"+t1[1]); XML.addValue("status","resolution set to "+t1[0]+"x"+t1[1]); @@ -163,7 +163,7 @@ void Render_context::session_command(const Session_command& command,xmlIO& XML,H status=HTTPResponse::HTTP_OK; //XML.addValue("patchbay",graph.toString()); logger.information("Requested graph"); - XML.loadFromBuffer(graph.toString()); + XML.loadFromBuffer(graph.graphToString()); } else { logger.error("ERROR: graph not loaded: check XML"); @@ -239,7 +239,7 @@ void Render_context::session_command(const Session_command& command,xmlIO& XML,H //direct call for testing float framerate=25.0f; //if (command.size()>2) { - // framerate=ofToFloat(command.id); + // framerate=toFloat(command.id); //} string signal_xml; if (false) { //graph.signal_render(signal_xml,framerate)){ @@ -327,7 +327,7 @@ void Render_context::session_command(const Session_command& command,xmlIO& XML,H else { status=HTTPResponse::HTTP_BAD_REQUEST; logger.error("ERROR: Could not create preview"); - XML.addValue("error","Could not preview node '"+preview_node+"', frame "+ofToString(frame)+" at "+ofToString(width)+"x"+ofToString(height)); + XML.addValue("error","Could not preview node '"+preview_node+"', frame "+toString(frame)+" at "+toString(width)+"x"+toString(height)); } } else { @@ -380,7 +380,7 @@ void Render_context::session_command(const Session_command& command,xmlIO& XML,H if(state==RENDERING){ status=HTTPResponse::HTTP_OK; XML.addValue("status","Rendering video"); - XML.addValue("progress",ofToString(graph.progress)); + XML.addValue("progress",toString(graph.progress)); } else { logger.error("ERROR: Render progress requested but not rendering"); @@ -392,7 +392,7 @@ void Render_context::session_command(const Session_command& command,xmlIO& XML,H if (state==IDLE) { output_filename=output_dir+command.body; if (command.body!="") { -// output_framerate=ofToFloat(command.body); +// output_framerate=toFloat(command.body); } add_queue(Session_task(command.uid,RENDER)); status=HTTPResponse::HTTP_OK; diff --git a/rotord/src/rotor.cpp b/rotord/src/rotor.cpp index 8905a6e..ee18dbd 100755 --- a/rotord/src/rotor.cpp +++ b/rotord/src/rotor.cpp @@ -91,10 +91,10 @@ bool Video_loader::load(const string &_filename){ isLoaded=player.open(uri); if (isLoaded){ logger.information("Video_loader loaded "+_filename+": "\ - +ofToString(player.getNumberOfFrames())+" frames, "\ - +ofToString(player.getFrameRate())+" fps, "\ - +ofToString(player.getWidth())+"x"+ofToString(player.getHeight())\ - +", channels:"+ofToString(player.getNumberOfChannels())); + +toString(player.getNumberOfFrames())+" frames, "\ + +toString(player.getFrameRate())+" fps, "\ + +toString(player.getWidth())+"x"+toString(player.getHeight())\ + +", channels:"+toString(player.getNumberOfChannels())); return true; } @@ -124,7 +124,7 @@ Image* Video_loader::output(const Frame_spec &frame){ if (wanted!=lastframe){ if (!player.fetchFrame(frame.w,frame.h,wanted)) { //seek fail Logger& logger = Logger::get("Rotor"); - logger.error("Video_loader failed to seek frame "+ofToString(wanted)+" of "+attributes["filename"]->value); + logger.error("Video_loader failed to seek frame "+toString(wanted)+" of "+attributes["filename"]->value); if (image.w>0) return ℑ //just return the previous frame if possible else return nullptr; diff --git a/rotord/src/rotor.h b/rotord/src/rotor.h index b504e5f..310809f 100755 --- a/rotord/src/rotor.h +++ b/rotord/src/rotor.h @@ -85,9 +85,9 @@ namespace Rotor { b=(c&0xFF0000)>>16; } Colour(std::string s){ - r=(uint8_t)ofHexToChar(s.substr(0,2)); - g=(uint8_t)ofHexToChar(s.substr(2,2)); - b=(uint8_t)ofHexToChar(s.substr(4,2)); + r=(uint8_t)hexToChar(s.substr(0,2)); + g=(uint8_t)hexToChar(s.substr(2,2)); + b=(uint8_t)hexToChar(s.substr(4,2)); } float Rfloat(){ return ((float)r)/255.0f; @@ -193,8 +193,8 @@ namespace Rotor { string title; bool duplicate_inputs; string find_setting(map<string,string> &settings,string key,string def=""){ if (settings.find(key)!=settings.end()) return settings[key]; else return def;}; - float find_setting(map<string,string> &settings,string key,float def){ if (settings.find(key)!=settings.end()) return ofToFloat(settings[key]); else return def;}; - int find_setting(map<string,string> &settings,string key,int def){ if (settings.find(key)!=settings.end()) return ofToInt(settings[key]); else return def;}; + float find_setting(map<string,string> &settings,string key,float def){ if (settings.find(key)!=settings.end()) return toFloat(settings[key]); else return def;}; + int find_setting(map<string,string> &settings,string key,int def){ if (settings.find(key)!=settings.end()) return toInt(settings[key]); else return def;}; void base_settings(map<string,string> &settings) { description=find_setting(settings,"description"); type=find_setting(settings,"type"); @@ -219,7 +219,7 @@ namespace Rotor { } } void set_parameter(const std::string &key,const std::string &value){ - if (parameters.find(key)!=parameters.end()) parameters[key]->value=ofToFloat(value); + if (parameters.find(key)!=parameters.end()) parameters[key]->value=toFloat(value); }; }; class Signal_node: public Node{ diff --git a/rotord/src/rotord.cpp b/rotord/src/rotord.cpp index 51c21ab..cdc38fe 100755 --- a/rotord/src/rotord.cpp +++ b/rotord/src/rotord.cpp @@ -291,7 +291,7 @@ int RotorServer::main(const std::vector<std::string>& args){ } else logger.information("settings.xml not found, using defaults"); - logger.information("rotord running on port "+ofToString(port)); + logger.information("rotord running on port "+toString(port)); port = (unsigned short) config().getInt("port", port); //override from command line diff --git a/rotord/src/utils.cpp b/rotord/src/utils.cpp index 9828124..cd12aa4 100644 --- a/rotord/src/utils.cpp +++ b/rotord/src/utils.cpp @@ -27,3 +27,114 @@ bool fgreater(const float u,const float v){ if (v-u>FLOAT_THRESHOLD) return true; else return false; }; + +//---------------------------------------- +template <> +string toHex(const string& value) { + ostringstream out; + // how many bytes are in the string + int numBytes = value.size(); + for(int i = 0; i < numBytes; i++) { + // print each byte as a 2-character wide hex value + out << setfill('0') << setw(2) << hex << (unsigned int) ((unsigned char)value[i]); + } + return out.str(); +} + +//---------------------------------------- +string toHex(const char* value) { + // this function is necessary if you want to print a string + // using a syntax like toHex("test") + return toHex((string) value); +} + +//---------------------------------------- +int toInt(const string& intString) { + int x = 0; + istringstream cur(intString); + cur >> x; + return x; +} + +//---------------------------------------- +int hexToInt(const string& intHexString) { + int x = 0; + istringstream cur(intHexString); + cur >> hex >> x; + return x; +} + +//---------------------------------------- +char hexToChar(const string& charHexString) { + int x = 0; + istringstream cur(charHexString); + cur >> hex >> x; + return (char) x; +} + +//---------------------------------------- +float hexToFloat(const string& floatHexString) { + union intFloatUnion { + int x; + float f; + } myUnion; + myUnion.x = 0; + istringstream cur(floatHexString); + cur >> hex >> myUnion.x; + return myUnion.f; +} + +//---------------------------------------- +string hexToString(const string& stringHexString) { + stringstream out; + stringstream stream(stringHexString); + // a hex string has two characters per byte + int numBytes = stringHexString.size() / 2; + for(int i = 0; i < numBytes; i++) { + string curByte; + // grab two characters from the hex string + stream >> setw(2) >> curByte; + // prepare to parse the two characters + stringstream curByteStream(curByte); + int cur = 0; + // parse the two characters as a hex-encoded int + curByteStream >> hex >> cur; + // add the int as a char to our output stream + out << (char) cur; + } + return out.str(); +} + +//---------------------------------------- +float toFloat(const string& floatString) { + float x = 0; + istringstream cur(floatString); + cur >> x; + return x; +} + +//---------------------------------------- +bool toBool(const string& boolString) { + static const string trueString = "true"; + static const string falseString = "false"; + string lower = Poco::toLower(boolString); + if(lower == trueString) { + return true; + } + if(lower == falseString) { + return false; + } + bool x = false; + istringstream cur(lower); + cur >> x; + return x; +} + +//---------------------------------------- +char toChar(const string& charString) { + char x = '\0'; + istringstream cur(charString); + cur >> x; + return x; +} + diff --git a/rotord/src/utils.h b/rotord/src/utils.h index 3859afe..d9df488 100644 --- a/rotord/src/utils.h +++ b/rotord/src/utils.h @@ -1,4 +1,13 @@ +#ifndef ROTOR_utils_H +#define ROTOR_utils_H + #include <cmath> +#include <string> +#include <sstream> +#include <vector> +#include <iomanip> + +#include "Poco/String.h" #define FLOAT_THRESHOLD .001f @@ -8,3 +17,80 @@ bool fless_or_equal(const float u,const float v); bool fgreater_or_equal(const float u,const float v); bool fless(const float u,const float v); bool fgreater(const float u,const float v); + + +template <class T> +std::string toString(const T& value){ + std::ostringstream out; + out << value; + return out.str(); +} + +/// like sprintf "%4f" format, in this example precision=4 +template <class T> +std::string toString(const T& value, int precision){ + std::ostringstream out; + out << std::fixed << std::setprecision(precision) << value; + return out.str(); +} + +/// like sprintf "% 4d" or "% 4f" format, in this example width=4, fill=' ' +template <class T> +std::string toString(const T& value, int width, char fill ){ + std::ostringstream out; + out << std::fixed << std::setfill(fill) << std::setw(width) << value; + return out.str(); +} + +/// like sprintf "%04.2d" or "%04.2f" format, in this example precision=2, width=4, fill='0' +template <class T> +std::string toString(const T& value, int precision, int width, char fill ){ + std::ostringstream out; + out << std::fixed << std::setfill(fill) << std::setw(width) << std::setprecision(precision) << value; + return out.str(); +} + +template<class T> +std::string toString(const std::vector<T>& values) { + std::stringstream out; + int n = values.size(); + out << "{"; + if(n > 0) { + for(int i = 0; i < n - 1; i++) { + out << values[i] << ", "; + } + out << values[n - 1]; + } + out << "}"; + return out.str(); +} + +template <class T> +std::string toHex(const T& value) { + std::ostringstream out; + // pretend that the value is a bunch of bytes + unsigned char* valuePtr = (unsigned char*) &value; + // the number of bytes is determined by the datatype + int numBytes = sizeof(T); + // the bytes are stored backwards (least significant first) + for(int i = numBytes - 1; i >= 0; i--) { + // print each byte out as a 2-character wide hex value + out << std::setfill('0') << std::setw(2) << std::hex << (int) valuePtr[i]; + } + return out.str(); +} +template <> +std::string toHex(const std::string& value); +std::string toHex(const char* value); + +int hexToInt(const std::string& intHexstring); +char hexToChar(const std::string& charHexString); +float hexToFloat(const std::string& floatHexString); +std::string hexToString(const std::string& stringHexString); + +int toInt(const std::string& intString); +char toChar(const std::string& charString); +float toFloat(const std::string& floatString); +bool toBool(const std::string& boolString); + +#endif diff --git a/rotord/src/xmlIO.cpp b/rotord/src/xmlIO.cpp index 3a7ec61..f2abe27 100755 --- a/rotord/src/xmlIO.cpp +++ b/rotord/src/xmlIO.cpp @@ -70,7 +70,7 @@ void xmlIO::clear(){ //--------------------------------------------------------- bool xmlIO::loadFile(const string& xmlFile){ - //string fullXmlFile = ofToDataPath(xmlFile); + //string fullXmlFile = toDataPath(xmlFile); bool loadOkay = doc.LoadFile(xmlFile); @@ -88,7 +88,7 @@ bool xmlIO::loadFile(const string& xmlFile){ //--------------------------------------------------------- bool xmlIO::saveFile(const string& xmlFile){ - //string fullXmlFile = ofToDataPath(xmlFile); + //string fullXmlFile = toDataPath(xmlFile); return doc.SaveFile(xmlFile); } @@ -142,7 +142,7 @@ void xmlIO::removeTag(const string& tag, int which){ int xmlIO::getValue(const string& tag, int defaultValue, int which){ TiXmlHandle valHandle(NULL); if (readTag(tag, valHandle, which)){ - return ofToInt(valHandle.ToText()->Value()); + return toInt(valHandle.ToText()->Value()); } return defaultValue; } @@ -151,7 +151,7 @@ int xmlIO::getValue(const string& tag, int defaultValue, int which){ double xmlIO::getValue(const string& tag, double defaultValue, int which){ TiXmlHandle valHandle(NULL); if (readTag(tag, valHandle, which)){ - return ofToFloat(valHandle.ToText()->Value()); + return toFloat(valHandle.ToText()->Value()); } return defaultValue; } @@ -361,13 +361,13 @@ int xmlIO::writeTag(const string& tag, const string& valueStr, int which){ //--------------------------------------------------------- int xmlIO::setValue(const string& tag, int value, int which){ - int tagID = writeTag(tag, ofToString(value).c_str(), which) -1; + int tagID = writeTag(tag, toString(value).c_str(), which) -1; return tagID; } //--------------------------------------------------------- int xmlIO::setValue(const string& tag, double value, int which){ - int tagID = writeTag(tag, ofToString(value).c_str(), which) -1; + int tagID = writeTag(tag, toString(value).c_str(), which) -1; return tagID; } @@ -379,13 +379,13 @@ int xmlIO::setValue(const string& tag, const string& value, int which){ //--------------------------------------------------------- int xmlIO::addValue(const string& tag, int value){ - int tagID = writeTag(tag, ofToString(value).c_str(), -1) -1; + int tagID = writeTag(tag, toString(value).c_str(), -1) -1; return tagID; } //--------------------------------------------------------- int xmlIO::addValue(const string& tag, double value){ - int tagID = writeTag(tag, ofToString(value).c_str(), -1) -1; + int tagID = writeTag(tag, toString(value).c_str(), -1) -1; return tagID; } @@ -407,7 +407,7 @@ int xmlIO::addTag(const string& tag){ //--------------------------------------------------------- int xmlIO::addAttribute(const string& tag, const string& attribute, int value, int which){ - int tagID = writeAttribute(tag, attribute, ofToString(value).c_str(), which) -1; + int tagID = writeAttribute(tag, attribute, toString(value).c_str(), which) -1; return tagID; } @@ -418,7 +418,7 @@ int xmlIO::addAttribute(const string& tag, const string& attribute, int value){ //--------------------------------------------------------- int xmlIO::addAttribute(const string& tag, const string& attribute, double value, int which){ - int tagID = writeAttribute(tag, attribute, ofToString(value).c_str(), which) -1; + int tagID = writeAttribute(tag, attribute, toString(value).c_str(), which) -1; return tagID; } diff --git a/rotord/src/xmlIO.h b/rotord/src/xmlIO.h index 84db7ca..2048c8d 100755 --- a/rotord/src/xmlIO.h +++ b/rotord/src/xmlIO.h @@ -6,7 +6,7 @@ #include <string.h> #include <vector> #include "tinyxml.h" -#include "ofUtils.h" +#include "utils.h" using namespace std; |
