From 58b40f7ed298f6b612f45ba4b4ecf3089045037c Mon Sep 17 00:00:00 2001 From: tosh Date: Wed, 17 Apr 2013 00:37:21 +0200 Subject: [PATCH 01/14] adds Log class --- interface/src/Log.cpp | 278 ++++++++++++++++++++++++++++++++++++++++++ interface/src/Log.h | 58 +++++++++ 2 files changed, 336 insertions(+) create mode 100644 interface/src/Log.cpp create mode 100644 interface/src/Log.h diff --git a/interface/src/Log.cpp b/interface/src/Log.cpp new file mode 100644 index 0000000000..a30b3b3963 --- /dev/null +++ b/interface/src/Log.cpp @@ -0,0 +1,278 @@ +// +// Log.cpp +// interface +// +// Created by Tobias Schwinger on 4/14/13. +// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// + +#include "Log.h" + +#include "InterfaceConfig.h" + +#include +#include + +#include "Util.h" +#include "ScopedLock.h" + +namespace { + // anonymous namespace - everything in here only exists within this very .cpp file + + unsigned const CHARACTER_BUFFER_SIZE = 16384; + unsigned const LINE_BUFFER_SIZE = 256; + unsigned const MAX_MESSAGE_LENGTH = 512; + + bool const TEXT_MONOSPACED = false; + + float const TEXT_RED = 0.7f; + float const TEXT_GREEN = 0.6f; + float const TEXT_BLUE = 1.0f; + + // magic constants from the GLUT spec + // http://www.opengl.org/resources/libraries/glut/spec3/node78.html + // ultimately this stuff should be handled in Util?? + float const CHAR_UP = 119.05f; + float const CHAR_DOWN = 33.33f; + float const CHAR_WIDTH = 104.76f; + // derived values + float const CHAR_HEIGHT = CHAR_UP + CHAR_DOWN; + float const CHAR_FRACT_BASELINE = CHAR_DOWN / CHAR_HEIGHT; + + // unsigned integer division rounded towards infinity + unsigned divRoundUp(unsigned l, unsigned r) { return (l + r - 1) / r; } +} + +Log::Log(FILE* tPipeTo, unsigned bufferedLines, + unsigned defaultLogWidth, unsigned defaultCharWidth, unsigned defaultCharHeight) : + + _ptrStream(tPipeTo), + _arrChars(0l), + _arrLines(0l), + _valLogWidth(defaultLogWidth) { + + pthread_mutex_init(& _mtx, 0l); + + // allocate twice as much (so we have spare space for a copy not to block + // logging from other threads during 'render') + _arrChars = new char[CHARACTER_BUFFER_SIZE * 2]; + _ptrCharsEnd = _arrChars + CHARACTER_BUFFER_SIZE; + _arrLines = new char*[LINE_BUFFER_SIZE * 2]; + _ptrLinesEnd = _arrLines + LINE_BUFFER_SIZE; + + // initialize the log to all empty lines + _arrChars[0] = '\0'; + _itrWritePos = _arrChars; + _itrWriteLineStart = _arrChars; + _itrLastLine = _arrLines; + _valWrittenInLine = 0; + memset(_arrLines, 0, LINE_BUFFER_SIZE * sizeof(char*)); + + setCharacterSize(defaultCharWidth, defaultCharHeight); +} + + +Log::~Log() { + + delete[] _arrChars; + delete[] _arrLines; +} + +inline void Log::addMessage(char const* ptr) { + + // precondition: mutex is locked so noone gets in our way + + while (*ptr != '\0') { + char c = *ptr++; + + if (c == '\t') { + + // found TAB -> write SPACE + c = ' '; + + } else if (c == '\n') { + + // found LF -> write NUL (c == '\0' tells us to wrap, below) + c = '\0'; + } + *_itrWritePos++ = c; + + if (_itrWritePos == _ptrCharsEnd) { + + // reached the end of the circular character buffer? -> start over + _itrWritePos = _arrChars; + } + + if (++_valWrittenInLine >= _valLineLength || c == '\0') { + + // new line? store its start to the line buffer and mark next line as empty + ++_itrLastLine; + if (_itrLastLine == _ptrLinesEnd) { + _itrLastLine = _arrLines; + _arrLines[1] = 0l; + } else if (_itrLastLine + 1 == _ptrLinesEnd) { + _arrLines[0] = 0l; + } else { + _itrLastLine[1] = 0l; + } + *_itrLastLine = _itrWriteLineStart; + + // remember start position in character buffer for next line and reset character count + _itrWriteLineStart = _itrWritePos; + _valWrittenInLine = 0; + } + } + +} + +void Log::operator()(char const* fmt, ...) { + + va_list args; + va_start(args,fmt); + pthread_mutex_lock(& _mtx); + + // print to buffer + char buf[MAX_MESSAGE_LENGTH]; + if (vsnprintf(buf, MAX_MESSAGE_LENGTH, fmt, args) > 0) { + + // all fine? eventually T-pipe to posix file and add message to log + if (_ptrStream != 0l) { + fprintf(_ptrStream, "%s", buf); + } + addMessage(buf); + + } else { + + // error? -> mutter on stream or stderr + fprintf(_ptrStream != 0l ? _ptrStream : stderr, + "Log: Failed to log message with format string = \"%s\".\n", fmt); + } + + pthread_mutex_unlock(& _mtx); + va_end(args); +} + +void Log::setLogWidth(unsigned pixels) { + + pthread_mutex_lock(& _mtx); + _valLogWidth = pixels; + _valLineLength = _valLogWidth / _valCharWidth; + pthread_mutex_unlock(& _mtx); +} + +void Log::setCharacterSize(unsigned width, unsigned height) { + + pthread_mutex_lock(& _mtx); + _valCharWidth = width; + _valCharHeight = height; + _valCharYoffset = height * CHAR_FRACT_BASELINE; + _valCharScale = float(width) / CHAR_WIDTH; + _valCharAspect = (height * CHAR_WIDTH) / (width * CHAR_HEIGHT); + _valLineLength = _valLogWidth / _valCharWidth; + pthread_mutex_unlock(& _mtx); +} + +void Log::render(unsigned screenWidth, unsigned screenHeight) { + + // rendering might take some time, so create a local copy of the portion we need + // instead of having to hold the mutex all the time + pthread_mutex_lock(& _mtx); + + // determine number of visible lines + unsigned showLines = divRoundUp(screenHeight, _valCharHeight); + + char** lastLine = _itrLastLine; + char** firstLine = _itrLastLine; + + if (! *lastLine) { + // empty log + pthread_mutex_unlock(& _mtx); + return; + } + + // scan for first line + for (int n = 2; n <= showLines; ++n) { + + char** prevFirstLine = firstLine; + --firstLine; + if (firstLine < _arrLines) { + firstLine = _ptrLinesEnd - 1; + } + if (! *firstLine) { + firstLine = prevFirstLine; + showLines = n - 1; + break; + } + } + + // copy the line buffer portion into a contiguous region at _ptrLinesEnd + if (firstLine <= lastLine) { + + memcpy(_ptrLinesEnd, firstLine, showLines * sizeof(char*)); + + } else { + + unsigned atEnd = _ptrLinesEnd - firstLine; + memcpy(_ptrLinesEnd, firstLine, atEnd * sizeof(char*)); + memcpy(_ptrLinesEnd + atEnd, _arrLines, (showLines - atEnd) * sizeof(char*)); + } + + // copy relevant char buffer portion and determine information to remap the line pointers + char* firstChar = *firstLine; + char* lastChar = *lastLine + strlen(*lastLine) + 1; + ptrdiff_t charOffset = _ptrCharsEnd - firstChar, charOffsetBeforeFirst = 0; + if (firstChar <= lastChar) { + + memcpy(_ptrCharsEnd, firstChar, lastChar - firstChar); + + } else { + + unsigned atEnd = _ptrCharsEnd - firstChar; + memcpy(_ptrCharsEnd, firstChar, atEnd); + memcpy(_ptrCharsEnd + atEnd, _arrChars, lastChar - _arrChars); + + charOffsetBeforeFirst = _ptrCharsEnd + atEnd - _arrChars; + } + + // get values for rendering + unsigned logWidth = _valLogWidth; + if (logWidth > screenWidth) { + logWidth = screenWidth; + } + int yStart = int((screenHeight - _valCharYoffset) / _valCharAspect); + int yStep = int(_valCharHeight / _valCharAspect); + float yScale = _valCharAspect; + + pthread_mutex_unlock(& _mtx); + // ok, we got all we need + + // render text + char** line = _ptrLinesEnd + showLines; + int x = screenWidth - _valLogWidth; + + glPushMatrix(); + glScalef(1.0f, yScale, 1.0f); + + for (int y = yStart; y > 0; y -= yStep) { + + // get character pointer + char* chars = *--line; + if (! chars) { + break; + } + + // remap character pointer it to copied buffer + chars += chars >= firstChar ? charOffset : charOffsetBeforeFirst; + + // render the string + drawtext(x, y, _valCharScale, 0.0f, 1.0f, int(TEXT_MONOSPACED), + chars, TEXT_RED, TEXT_GREEN, TEXT_BLUE); + +//fprintf(stderr, "Log::render, message = \"%s\"\n", chars); + } + + glPopMatrix(); +} + + + diff --git a/interface/src/Log.h b/interface/src/Log.h new file mode 100644 index 0000000000..269e4f5330 --- /dev/null +++ b/interface/src/Log.h @@ -0,0 +1,58 @@ +// +// Log.h +// interface +// +// Created by Tobias Schwinger on 4/14/13. +// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// + +#ifndef __interface__Log__ +#define __interface__Log__ + +#include +#include +#include + +class Log { + + FILE* _ptrStream; + char* _arrChars; + char* _ptrCharsEnd; + char** _arrLines; + char** _ptrLinesEnd; + + char* _itrWritePos; // character position to write to + char* _itrWriteLineStart; // character position where line being written starts + char** _itrLastLine; // last line in the log + unsigned _valWrittenInLine; // character counter for line wrapping + unsigned _valLineLength; // number of characters before line wrap + + unsigned _valLogWidth; // width of the log in pixels + unsigned _valCharWidth; // width of a character in pixels + unsigned _valCharHeight; // height of a character in pixels + unsigned _valCharYoffset; // baseline offset in pixels + float _valCharScale; // scale factor + float _valCharAspect; // aspect (h/w) + + pthread_mutex_t _mtx; +public: + + explicit Log(FILE* tPipeTo = stdout, unsigned bufferedLines = 1024, + unsigned defaultLogWidth = 240, unsigned defaultCharWidth = 12, unsigned defaultCharHeight = 24); + ~Log(); + + void setLogWidth(unsigned pixels); + void setCharacterSize(unsigned width, unsigned height); + + void operator()(char const* fmt, ...); + + void render(unsigned screenWidth, unsigned screenHeight); + +private: + + inline void addMessage(char const*); + inline void recalcLineLength(); +}; + +#endif + From cf3e2635c140d5f8e7aadda8f31b1d88d777b1b0 Mon Sep 17 00:00:00 2001 From: tosh Date: Wed, 17 Apr 2013 00:38:21 +0200 Subject: [PATCH 02/14] brings Log class into stable state --- interface/src/Log.cpp | 14 ++++++++++++-- interface/src/Log.h | 2 +- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/interface/src/Log.cpp b/interface/src/Log.cpp index a30b3b3963..a7e69699d8 100644 --- a/interface/src/Log.cpp +++ b/interface/src/Log.cpp @@ -18,12 +18,13 @@ namespace { // anonymous namespace - everything in here only exists within this very .cpp file + // just as 'static' on every effective line in plain C unsigned const CHARACTER_BUFFER_SIZE = 16384; unsigned const LINE_BUFFER_SIZE = 256; unsigned const MAX_MESSAGE_LENGTH = 512; - bool const TEXT_MONOSPACED = false; + bool const TEXT_MONOSPACED = true; float const TEXT_RED = 0.7f; float const TEXT_GREEN = 0.6f; @@ -117,6 +118,11 @@ inline void Log::addMessage(char const* ptr) { } *_itrLastLine = _itrWriteLineStart; + // terminate line, unless done already + if (c != '\0') { + *_itrWritePos++ = '\0'; + } + // remember start position in character buffer for next line and reset character count _itrWriteLineStart = _itrWritePos; _valWrittenInLine = 0; @@ -249,7 +255,10 @@ void Log::render(unsigned screenWidth, unsigned screenHeight) { // render text char** line = _ptrLinesEnd + showLines; int x = screenWidth - _valLogWidth; - + + + GLint matrixMode; + glGetIntegerv(GL_MATRIX_MODE, & matrixMode); glPushMatrix(); glScalef(1.0f, yScale, 1.0f); @@ -272,6 +281,7 @@ void Log::render(unsigned screenWidth, unsigned screenHeight) { } glPopMatrix(); + glMatrixMode(matrixMode); } diff --git a/interface/src/Log.h b/interface/src/Log.h index 269e4f5330..e7213404ed 100644 --- a/interface/src/Log.h +++ b/interface/src/Log.h @@ -38,7 +38,7 @@ class Log { public: explicit Log(FILE* tPipeTo = stdout, unsigned bufferedLines = 1024, - unsigned defaultLogWidth = 240, unsigned defaultCharWidth = 12, unsigned defaultCharHeight = 24); + unsigned defaultLogWidth = 240, unsigned defaultCharWidth = 10, unsigned defaultCharHeight = 24); ~Log(); void setLogWidth(unsigned pixels); From dc4dc887acd21353b0f8383969c25ad25573b5a1 Mon Sep 17 00:00:00 2001 From: tosh Date: Wed, 17 Apr 2013 00:38:39 +0200 Subject: [PATCH 03/14] silences warning about deprecated conversion of string literal to char* --- interface/src/Util.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interface/src/Util.h b/interface/src/Util.h index 56bc16f5d1..ab48e0885a 100644 --- a/interface/src/Util.h +++ b/interface/src/Util.h @@ -38,7 +38,7 @@ float angle_to(glm::vec3 head_pos, glm::vec3 source_pos, float render_yaw, float float randFloat(); void render_world_box(); void render_vector(glm::vec3 * vec); -int widthText(float scale, int mono, char *string); +int widthText(float scale, int mono, char const* string); void drawtext(int x, int y, float scale, float rotate, float thick, int mono, char const* string, float r=1.0, float g=1.0, float b=1.0); void drawvec3(int x, int y, float scale, float rotate, float thick, int mono, glm::vec3 vec, From e811410f77cbfbe6bd8f0fd1c6adcc5e18e5da13 Mon Sep 17 00:00:00 2001 From: tosh Date: Wed, 17 Apr 2013 00:39:35 +0200 Subject: [PATCH 04/14] works around GLUT bugs related to monospace glyphs --- interface/src/Util.cpp | 37 ++++++++++++++++++++++++++++++++++--- 1 file changed, 34 insertions(+), 3 deletions(-) diff --git a/interface/src/Util.cpp b/interface/src/Util.cpp index 637204dc83..0caf87bc94 100644 --- a/interface/src/Util.cpp +++ b/interface/src/Util.cpp @@ -13,6 +13,13 @@ #include "world.h" #include "Util.h" +using namespace std; + +// no clue which versions are affected... +#define WORKAROUND_BROKEN_GLUT_STROKES +// see http://www.opengl.org/resources/libraries/glut/spec3/node78.html +static float MONO_STROKE_WIDTH_GLUT = 104.76; + // Return the azimuth angle in degrees between two points. float azimuth_to(glm::vec3 head_pos, glm::vec3 source_pos) { return atan2(head_pos.x - source_pos.x, head_pos.z - source_pos.z) * 180.0f / PIf; @@ -107,12 +114,17 @@ double diffclock(timeval *clock1,timeval *clock2) return diffms; } -int widthText(float scale, int mono, char *string) { +int widthText(float scale, int mono, char const* string) { int width = 0; if (!mono) { width = scale * glutStrokeLength(GLUT_STROKE_ROMAN, (const unsigned char *) string); } else { +#ifndef WORKAROUND_BROKEN_GLUT_STROKES width = scale * glutStrokeLength(GLUT_STROKE_MONO_ROMAN, (const unsigned char *) string); +#else + // return value is unreliable, so just calculate it + width = scale * float(strlen(string)) * MONO_STROKE_WIDTH_GLUT; +#endif } return width; } @@ -134,8 +146,27 @@ void drawtext(int x, int y, float scale, float rotate, float thick, int mono, len = (int) strlen(string); for (i = 0; i < len; i++) { - if (!mono) glutStrokeCharacter(GLUT_STROKE_ROMAN, int(string[i])); - else glutStrokeCharacter(GLUT_STROKE_MONO_ROMAN, int(string[i])); + if (!mono) { + glutStrokeCharacter(GLUT_STROKE_ROMAN, int(string[i])); + } else { +#ifdef WORKAROUND_BROKEN_GLUT_STROKES + if (string[i] != 'm') { +#endif + glutStrokeCharacter(GLUT_STROKE_MONO_ROMAN, int(string[i])); +#ifdef WORKAROUND_BROKEN_GLUT_STROKES + } else { + // some glut implementations have a broken 'm'... + unsigned char tmpStr[2]; + tmpStr[0] = string[i]; + tmpStr[1] = '\0'; + float scale = MONO_STROKE_WIDTH_GLUT / glutStrokeLength(GLUT_STROKE_ROMAN, tmpStr); + glScalef(scale, 1.0f, 1.0f); + glutStrokeCharacter(GLUT_STROKE_ROMAN, int(string[i])); + // stay humble on the stack - might be in projection mode + glScalef(1.0f / scale, 1.0f, 1.0f); + } +#endif + } } glPopMatrix(); From 3be23b3faa8297c4dc849feab5eb91f57b0f3250 Mon Sep 17 00:00:00 2001 From: tosh Date: Wed, 17 Apr 2013 00:48:27 +0200 Subject: [PATCH 05/14] integrates logging --- interface/src/main.cpp | 51 +++++++++++++++++++++++------------------- 1 file changed, 28 insertions(+), 23 deletions(-) diff --git a/interface/src/main.cpp b/interface/src/main.cpp index 7a992e8dcc..ad0c8f3ad9 100644 --- a/interface/src/main.cpp +++ b/interface/src/main.cpp @@ -47,6 +47,8 @@ #include #include +#include "Log.h" + #include "Field.h" #include "world.h" #include "Util.h" @@ -98,6 +100,8 @@ int fullscreen = 0; bool wantColorRandomizer = true; // for addSphere and load file +Log printLog; + Oscilloscope audioScope(256,200,true); ViewFrustum viewFrustum; // current state of view frustum, perspective, orientation, etc. @@ -323,9 +327,9 @@ void init(void) marker_capturer.position_updated(&position_updated); marker_capturer.frame_updated(&marker_frame_available); if(!marker_capturer.init_capture()){ - printf("Camera-based marker capture initialized.\n"); + printLog("Camera-based marker capture initialized.\n"); }else{ - printf("Error initializing camera-based marker capture.\n"); + printLog("Error initializing camera-based marker capture.\n"); } } #endif @@ -558,13 +562,13 @@ void render_view_frustum() { } /* - printf("position.x=%f, position.y=%f, position.z=%f\n", position.x, position.y, position.z); - printf("direction.x=%f, direction.y=%f, direction.z=%f\n", direction.x, direction.y, direction.z); - printf("up.x=%f, up.y=%f, up.z=%f\n", up.x, up.y, up.z); - printf("right.x=%f, right.y=%f, right.z=%f\n", right.x, right.y, right.z); - printf("fov=%f\n", fov); - printf("nearClip=%f\n", nearClip); - printf("farClip=%f\n", farClip); + printLog("position.x=%f, position.y=%f, position.z=%f\n", position.x, position.y, position.z); + printLog("direction.x=%f, direction.y=%f, direction.z=%f\n", direction.x, direction.y, direction.z); + printLog("up.x=%f, up.y=%f, up.z=%f\n", up.x, up.y, up.z); + printLog("right.x=%f, right.y=%f, right.z=%f\n", right.x, right.y, right.z); + printLog("fov=%f\n", fov); + printLog("nearClip=%f\n", nearClip); + printLog("farClip=%f\n", farClip); */ // Set the viewFrustum up with the correct position and orientation of the camera @@ -884,6 +888,7 @@ void display(void) glLineWidth(1.0f); glPointSize(1.0f); displayStats(); + printLog.render(WIDTH, HEIGHT); } // Show menu @@ -1101,7 +1106,7 @@ void sendVoxelServerEraseAll() { sprintf(message,"%c%s",'Z',"erase all"); int messageSize = strlen(message) + 1; AgentList::getInstance()->broadcastToAgents((unsigned char*) message, messageSize, &AGENT_TYPE_VOXEL, 1); -}\ +} void sendVoxelServerAddScene() { char message[100]; @@ -1139,11 +1144,11 @@ void addRandomSphere(bool wantColorRandomizer) float s = 0.001; // size of voxels to make up surface of sphere bool solid = false; - printf("random sphere\n"); - printf("radius=%f\n",r); - printf("xc=%f\n",xc); - printf("yc=%f\n",yc); - printf("zc=%f\n",zc); + printLog("random sphere\n"); + printLog("radius=%f\n",r); + printLog("xc=%f\n",xc); + printLog("yc=%f\n",yc); + printLog("zc=%f\n",zc); voxels.createSphere(r,xc,yc,zc,s,solid,wantColorRandomizer); } @@ -1417,7 +1422,7 @@ void reshape(int width, int height) farClip = ::myCamera.getFarClip(); } - //printf("reshape() width=%d, height=%d, aspectRatio=%f fov=%f near=%f far=%f \n", + //printLog("reshape() width=%d, height=%d, aspectRatio=%f fov=%f near=%f far=%f \n", // width,height,aspectRatio,fov,nearClip,farClip); // Tell our viewFrustum about this change @@ -1515,7 +1520,7 @@ int main(int argc, const char * argv[]) // Handle Local Domain testing with the --local command line if (cmdOptionExists(argc, argv, "--local")) { - printf("Local Domain MODE!\n"); + printLog("Local Domain MODE!\n"); int ip = getLocalAddress(); sprintf(DOMAIN_IP,"%d.%d.%d.%d", (ip & 0xFF), ((ip >> 8) & 0xFF),((ip >> 16) & 0xFF), ((ip >> 24) & 0xFF)); } @@ -1555,11 +1560,11 @@ int main(int argc, const char * argv[]) viewFrustumOffsetCamera.setNearClip(0.1); viewFrustumOffsetCamera.setFarClip(500.0); - printf( "Created Display Window.\n" ); + printLog( "Created Display Window.\n" ); initMenu(); initDisplay(); - printf( "Initialized Display.\n" ); + printLog( "Initialized Display.\n" ); glutDisplayFunc(display); glutReshapeFunc(reshape); @@ -1573,7 +1578,7 @@ int main(int argc, const char * argv[]) glutIdleFunc(idle); init(); - printf( "Init() complete.\n" ); + printLog( "Init() complete.\n" ); // Check to see if the user passed in a command line option for randomizing colors if (cmdOptionExists(argc, argv, "--NoColorRandomizer")) { @@ -1585,17 +1590,17 @@ int main(int argc, const char * argv[]) const char* voxelsFilename = getCmdOption(argc, argv, "-i"); if (voxelsFilename) { voxels.loadVoxelsFile(voxelsFilename,wantColorRandomizer); - printf("Local Voxel File loaded.\n"); + printLog("Local Voxel File loaded.\n"); } // create thread for receipt of data via UDP pthread_create(&networkReceiveThread, NULL, networkReceive, NULL); - printf("Network receive thread created.\n"); + printLog("Network receive thread created.\n"); glutTimerFunc(1000, Timer, 0); glutMainLoop(); - printf("Normal exit.\n"); + printLog("Normal exit.\n"); ::terminate(); return EXIT_SUCCESS; } From 9ea3c58087b78a03730c6f37e810302717701290 Mon Sep 17 00:00:00 2001 From: tosh Date: Wed, 17 Apr 2013 05:06:28 +0200 Subject: [PATCH 06/14] removes leftover #include --- interface/src/Log.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/interface/src/Log.cpp b/interface/src/Log.cpp index a7e69699d8..97d36d165c 100644 --- a/interface/src/Log.cpp +++ b/interface/src/Log.cpp @@ -14,7 +14,6 @@ #include #include "Util.h" -#include "ScopedLock.h" namespace { // anonymous namespace - everything in here only exists within this very .cpp file From 81cae86559cd9509043cf80e21dab17fd21134a1 Mon Sep 17 00:00:00 2001 From: tosh Date: Wed, 17 Apr 2013 18:35:10 +0200 Subject: [PATCH 07/14] brings logging component to stable state --- interface/src/Log.cpp | 78 +++++++++++++++++++++++++++--------------- interface/src/Log.h | 22 +++++++++--- interface/src/main.cpp | 2 -- 3 files changed, 69 insertions(+), 33 deletions(-) diff --git a/interface/src/Log.cpp b/interface/src/Log.cpp index 97d36d165c..5f5381addd 100644 --- a/interface/src/Log.cpp +++ b/interface/src/Log.cpp @@ -19,9 +19,9 @@ namespace { // anonymous namespace - everything in here only exists within this very .cpp file // just as 'static' on every effective line in plain C - unsigned const CHARACTER_BUFFER_SIZE = 16384; - unsigned const LINE_BUFFER_SIZE = 256; - unsigned const MAX_MESSAGE_LENGTH = 512; + unsigned const CHARACTER_BUFFER_SIZE = 16384; // number of character that are buffered + unsigned const LINE_BUFFER_SIZE = 256; // number of lines that are buffered + unsigned const MAX_MESSAGE_LENGTH = 512; // maximum number of characters for a message bool const TEXT_MONOSPACED = true; @@ -31,7 +31,7 @@ namespace { // magic constants from the GLUT spec // http://www.opengl.org/resources/libraries/glut/spec3/node78.html - // ultimately this stuff should be handled in Util?? + // ultimately this stuff should be in Util.h?? float const CHAR_UP = 119.05f; float const CHAR_DOWN = 33.33f; float const CHAR_WIDTH = 104.76f; @@ -82,7 +82,13 @@ inline void Log::addMessage(char const* ptr) { // precondition: mutex is locked so noone gets in our way + // T-pipe, if requested + if (_ptrStream != 0l) { + fprintf(_ptrStream, "%s", ptr); + } + while (*ptr != '\0') { + // process the characters char c = *ptr++; if (c == '\t') { @@ -98,7 +104,6 @@ inline void Log::addMessage(char const* ptr) { *_itrWritePos++ = c; if (_itrWritePos == _ptrCharsEnd) { - // reached the end of the circular character buffer? -> start over _itrWritePos = _arrChars; } @@ -107,19 +112,28 @@ inline void Log::addMessage(char const* ptr) { // new line? store its start to the line buffer and mark next line as empty ++_itrLastLine; + if (_itrLastLine == _ptrLinesEnd) { _itrLastLine = _arrLines; - _arrLines[1] = 0l; - } else if (_itrLastLine + 1 == _ptrLinesEnd) { - _arrLines[0] = 0l; - } else { _itrLastLine[1] = 0l; + } else if (_itrLastLine + 1 != _ptrLinesEnd) { + _itrLastLine[1] = 0l; + } else { + _arrLines[0] = 0l; } *_itrLastLine = _itrWriteLineStart; + // debug mode: make sure all line pointers we write here are valid + assert(! (_itrLastLine < _arrLines || _itrLastLine >= _ptrLinesEnd)); + assert(! (*_itrLastLine < _arrChars || *_itrLastLine >= _ptrCharsEnd)); + // terminate line, unless done already if (c != '\0') { *_itrWritePos++ = '\0'; + + if (_itrWritePos == _ptrCharsEnd) { + _itrWritePos = _arrChars; + } } // remember start position in character buffer for next line and reset character count @@ -138,12 +152,10 @@ void Log::operator()(char const* fmt, ...) { // print to buffer char buf[MAX_MESSAGE_LENGTH]; - if (vsnprintf(buf, MAX_MESSAGE_LENGTH, fmt, args) > 0) { + int n = vsnprintf(buf, MAX_MESSAGE_LENGTH, fmt, args); + if (n > 0) { - // all fine? eventually T-pipe to posix file and add message to log - if (_ptrStream != 0l) { - fprintf(_ptrStream, "%s", buf); - } + // all fine? log the message addMessage(buf); } else { @@ -208,6 +220,10 @@ void Log::render(unsigned screenWidth, unsigned screenHeight) { showLines = n - 1; break; } + + // debug mode: make sure all line pointers we find here are valid + assert(! (firstLine < _arrLines || firstLine >= _ptrLinesEnd)); + assert(! (*firstLine < _arrChars || *firstLine >= _ptrCharsEnd)); } // copy the line buffer portion into a contiguous region at _ptrLinesEnd @@ -222,39 +238,35 @@ void Log::render(unsigned screenWidth, unsigned screenHeight) { memcpy(_ptrLinesEnd + atEnd, _arrLines, (showLines - atEnd) * sizeof(char*)); } - // copy relevant char buffer portion and determine information to remap the line pointers + // copy relevant char buffer portion and determine information to remap the pointers char* firstChar = *firstLine; char* lastChar = *lastLine + strlen(*lastLine) + 1; ptrdiff_t charOffset = _ptrCharsEnd - firstChar, charOffsetBeforeFirst = 0; if (firstChar <= lastChar) { - memcpy(_ptrCharsEnd, firstChar, lastChar - firstChar); + memcpy(_ptrCharsEnd, firstChar, lastChar - firstChar + 1); } else { unsigned atEnd = _ptrCharsEnd - firstChar; memcpy(_ptrCharsEnd, firstChar, atEnd); - memcpy(_ptrCharsEnd + atEnd, _arrChars, lastChar - _arrChars); + memcpy(_ptrCharsEnd + atEnd, _arrChars, lastChar + 1 - _arrChars); charOffsetBeforeFirst = _ptrCharsEnd + atEnd - _arrChars; } // get values for rendering - unsigned logWidth = _valLogWidth; - if (logWidth > screenWidth) { - logWidth = screenWidth; - } + float scaleFactor = _valCharScale; int yStart = int((screenHeight - _valCharYoffset) / _valCharAspect); int yStep = int(_valCharHeight / _valCharAspect); float yScale = _valCharAspect; - pthread_mutex_unlock(& _mtx); - // ok, we got all we need - // render text char** line = _ptrLinesEnd + showLines; int x = screenWidth - _valLogWidth; + pthread_mutex_unlock(& _mtx); + // ok, we got all we need GLint matrixMode; glGetIntegerv(GL_MATRIX_MODE, & matrixMode); @@ -263,17 +275,26 @@ void Log::render(unsigned screenWidth, unsigned screenHeight) { for (int y = yStart; y > 0; y -= yStep) { + // debug mode: check line pointer is valid + assert(! (line < _ptrLinesEnd || line >= _ptrLinesEnd + (_ptrLinesEnd - _arrLines))); + // get character pointer - char* chars = *--line; - if (! chars) { + if (--line < _ptrLinesEnd) { break; } + char* chars = *line; + + // debug mode: check char pointer we find is valid + assert(! (chars < _arrChars || chars >= _ptrCharsEnd)); // remap character pointer it to copied buffer chars += chars >= firstChar ? charOffset : charOffsetBeforeFirst; + // debug mode: check char pointer is still valid (in new range) + assert(! (chars < _ptrCharsEnd || chars >= _ptrCharsEnd + (_ptrCharsEnd - _arrChars))); + // render the string - drawtext(x, y, _valCharScale, 0.0f, 1.0f, int(TEXT_MONOSPACED), + drawtext(x, y, scaleFactor, 0.0f, 1.0f, int(TEXT_MONOSPACED), chars, TEXT_RED, TEXT_GREEN, TEXT_BLUE); //fprintf(stderr, "Log::render, message = \"%s\"\n", chars); @@ -283,5 +304,8 @@ void Log::render(unsigned screenWidth, unsigned screenHeight) { glMatrixMode(matrixMode); } +Log printLog; + + diff --git a/interface/src/Log.h b/interface/src/Log.h index e7213404ed..98f32196ac 100644 --- a/interface/src/Log.h +++ b/interface/src/Log.h @@ -13,8 +13,17 @@ #include #include -class Log { +class Log; +// +// Call it as you would call 'printf'. +// +extern Log printLog; + +// +// Logging subsystem. +// +class Log { FILE* _ptrStream; char* _arrChars; char* _ptrCharsEnd; @@ -35,6 +44,7 @@ class Log { float _valCharAspect; // aspect (h/w) pthread_mutex_t _mtx; + public: explicit Log(FILE* tPipeTo = stdout, unsigned bufferedLines = 1024, @@ -44,14 +54,18 @@ public: void setLogWidth(unsigned pixels); void setCharacterSize(unsigned width, unsigned height); - void operator()(char const* fmt, ...); - void render(unsigned screenWidth, unsigned screenHeight); + void operator()(char const* fmt, ...); + private: + // don't copy/assign + Log(Log const&); // = delete; + Log& operator=(Log const&); // = delete; inline void addMessage(char const*); - inline void recalcLineLength(); + + friend class LogStream; // for optional iostream-style interface that has to be #included separately }; #endif diff --git a/interface/src/main.cpp b/interface/src/main.cpp index 3a085f2a15..af60e5d8ba 100644 --- a/interface/src/main.cpp +++ b/interface/src/main.cpp @@ -100,8 +100,6 @@ int fullscreen = 0; bool wantColorRandomizer = true; // for addSphere and load file -Log printLog; - Oscilloscope audioScope(256,200,true); ViewFrustum viewFrustum; // current state of view frustum, perspective, orientation, etc. From e7810179def123db8f0c67ee7a53ffcd03714be3 Mon Sep 17 00:00:00 2001 From: tosh Date: Wed, 17 Apr 2013 19:03:39 +0200 Subject: [PATCH 08/14] reduces default character size --- interface/src/Log.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interface/src/Log.h b/interface/src/Log.h index 98f32196ac..bb74f33933 100644 --- a/interface/src/Log.h +++ b/interface/src/Log.h @@ -48,7 +48,7 @@ class Log { public: explicit Log(FILE* tPipeTo = stdout, unsigned bufferedLines = 1024, - unsigned defaultLogWidth = 240, unsigned defaultCharWidth = 10, unsigned defaultCharHeight = 24); + unsigned defaultLogWidth = 240, unsigned defaultCharWidth = 6, unsigned defaultCharHeight = 20); ~Log(); void setLogWidth(unsigned pixels); From 349e89aaa68da88fca5cfd55d0164672df1e006c Mon Sep 17 00:00:00 2001 From: tosh Date: Wed, 17 Apr 2013 19:04:10 +0200 Subject: [PATCH 09/14] integrates logging for interface --- interface/src/Audio.cpp | 25 ++++++----- interface/src/Camera.cpp | 3 +- interface/src/Head.cpp | 6 +-- interface/src/OGlProgram.h | 49 +++++++++++---------- interface/src/SerialInterface.cpp | 6 +-- interface/src/SerialInterface.h | 1 + interface/src/Util.cpp | 35 ++++++++------- interface/src/VoxelSystem.cpp | 24 +++++----- interface/src/main.cpp | 2 +- interface/src/starfield/Config.h | 1 + interface/src/starfield/Controller.h | 10 ++--- interface/src/starfield/Loader.h | 11 +++-- interface/src/starfield/renderer/Renderer.h | 12 ++--- 13 files changed, 96 insertions(+), 89 deletions(-) diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index 578e1368c8..4762970019 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -19,6 +19,7 @@ #include #include "Audio.h" #include "Util.h" +#include "Log.h" Oscilloscope * scope; @@ -115,7 +116,7 @@ int audioCallback (const void *inputBuffer, int16_t *inputLeft = ((int16_t **) inputBuffer)[0]; // int16_t *inputRight = ((int16_t **) inputBuffer)[1]; - //printf("Audio callback at %6.0f\n", usecTimestampNow()/1000); + //printLog("Audio callback at %6.0f\n", usecTimestampNow()/1000); if (inputLeft != NULL) { @@ -231,21 +232,21 @@ int audioCallback (const void *inputBuffer, if (ringBuffer->getEndOfLastWrite() != NULL) { if (!ringBuffer->isStarted() && ringBuffer->diffLastWriteNextOutput() < PACKET_LENGTH_SAMPLES + JITTER_BUFFER_SAMPLES) { - //printf("Held back, buffer has %d of %d samples required.\n", ringBuffer->diffLastWriteNextOutput(), PACKET_LENGTH_SAMPLES + JITTER_BUFFER_SAMPLES); + //printLog("Held back, buffer has %d of %d samples required.\n", ringBuffer->diffLastWriteNextOutput(), PACKET_LENGTH_SAMPLES + JITTER_BUFFER_SAMPLES); } else if (ringBuffer->diffLastWriteNextOutput() < PACKET_LENGTH_SAMPLES) { ringBuffer->setStarted(false); starve_counter++; packetsReceivedThisPlayback = 0; - //printf("Starved #%d\n", starve_counter); + //printLog("Starved #%d\n", starve_counter); data->wasStarved = 10; // Frames to render the indication that the system was starved. } else { if (!ringBuffer->isStarted()) { ringBuffer->setStarted(true); - //printf("starting playback %3.1f msecs delayed \n", (usecTimestampNow() - usecTimestamp(&firstPlaybackTimer))/1000.0); + //printLog("starting playback %3.1f msecs delayed \n", (usecTimestampNow() - usecTimestamp(&firstPlaybackTimer))/1000.0); } else { - //printf("pushing buffer\n"); + //printLog("pushing buffer\n"); } // play whatever we have in the audio buffer @@ -391,12 +392,12 @@ void *receiveAudioViaUDP(void *args) { } double tDiff = diffclock(&previousReceiveTime, ¤tReceiveTime); - //printf("tDiff %4.1f\n", tDiff); + //printLog("tDiff %4.1f\n", tDiff); // Discard first few received packets for computing jitter (often they pile up on start) if (totalPacketsReceived > 3) stdev.addValue(tDiff); if (stdev.getSamples() > 500) { sharedAudioData->measuredJitter = stdev.getStDev(); - //printf("Avg: %4.2f, Stdev: %4.2f\n", stdev.getAverage(), sharedAudioData->measuredJitter); + //printLog("Avg: %4.2f, Stdev: %4.2f\n", stdev.getAverage(), sharedAudioData->measuredJitter); stdev.reset(); } @@ -407,7 +408,7 @@ void *receiveAudioViaUDP(void *args) { packetsReceivedThisPlayback++; } else { - //printf("Audio packet received at %6.0f\n", usecTimestampNow()/1000); + //printLog("Audio packet received at %6.0f\n", usecTimestampNow()/1000); } if (packetsReceivedThisPlayback == 1) gettimeofday(&firstPlaybackTimer, NULL); @@ -494,8 +495,8 @@ Audio::Audio(Oscilloscope *s, Head *linkedHead) return; error: - fprintf(stderr, "-- Failed to initialize portaudio --\n"); - fprintf(stderr, "PortAudio error (%d): %s\n", paError, Pa_GetErrorText(paError)); + printLog("-- Failed to initialize portaudio --\n"); + printLog("PortAudio error (%d): %s\n", paError, Pa_GetErrorText(paError)); initialized = false; delete[] audioData; } @@ -629,8 +630,8 @@ bool Audio::terminate () return true; error: - fprintf(stderr, "-- portaudio termination error --\n"); - fprintf(stderr, "PortAudio error (%d): %s\n", paError, Pa_GetErrorText(paError)); + printLog("-- portaudio termination error --\n"); + printLog("PortAudio error (%d): %s\n", paError, Pa_GetErrorText(paError)); return false; } diff --git a/interface/src/Camera.cpp b/interface/src/Camera.cpp index d557e2050c..1333196b02 100644 --- a/interface/src/Camera.cpp +++ b/interface/src/Camera.cpp @@ -6,6 +6,7 @@ //--------------------------------------------------------------------- #include +// #include "Log.h" #include "Camera.h" @@ -67,6 +68,6 @@ void Camera::update( float deltaTime ) _orientation.pitch ( _pitch ); _orientation.roll ( _roll ); - //printf( "orientation.front = %f, %f, %f\n", _orientation.front.x, _orientation.front.y, _orientation.front.z ); + //printLog( "orientation.front = %f, %f, %f\n", _orientation.front.x, _orientation.front.y, _orientation.front.z ); } diff --git a/interface/src/Head.cpp b/interface/src/Head.cpp index 658e749eed..8545f11969 100644 --- a/interface/src/Head.cpp +++ b/interface/src/Head.cpp @@ -346,13 +346,13 @@ void Head::simulate(float deltaTime) { if (! previousHandBeingMoved ){ initializeBodySprings(); usingSprings = true; - //printf( "just started moving hand\n" ); + //printLog( "just started moving hand\n" ); } } else { if ( previousHandBeingMoved ){ usingSprings = false; - //printf( "just stopped moving hand\n" ); + //printLog( "just stopped moving hand\n" ); } } @@ -962,7 +962,7 @@ void Head::updateSkeleton() { for (int b=0; b // These includes are for serial port reading/writing diff --git a/interface/src/Util.cpp b/interface/src/Util.cpp index 4cfe67d20c..49292c499c 100644 --- a/interface/src/Util.cpp +++ b/interface/src/Util.cpp @@ -13,6 +13,7 @@ #include #include +#include "Log.h" #include "world.h" #include "Util.h" @@ -258,7 +259,7 @@ void renderOrientationDirections( glm::vec3 position, Orientation orientation, f } void testOrientationClass() { - printf("\n----------\ntestOrientationClass()\n----------\n\n"); + printLog("\n----------\ntestOrientationClass()\n----------\n\n"); oTestCase tests[] = { // - inputs ------------, outputs -------------------- ------------------- ---------------------------- @@ -297,43 +298,43 @@ void testOrientationClass() { glm::vec3 up = o1.getUp(); glm::vec3 right = o1.getRight(); - printf("\n-----\nTest: %d - yaw=%f , pitch=%f , roll=%f \n\n",i+1,yaw,pitch,roll); + printLog("\n-----\nTest: %d - yaw=%f , pitch=%f , roll=%f \n\n",i+1,yaw,pitch,roll); - printf(" +front.x=%f, front.y=%f, front.z=%f\n",front.x,front.y,front.z); + printLog(" +front.x=%f, front.y=%f, front.z=%f\n",front.x,front.y,front.z); if (front.x == tests[i].frontX && front.y == tests[i].frontY && front.z == tests[i].frontZ) { - printf(" front vector PASSES!\n"); + printLog(" front vector PASSES!\n"); } else { - printf(" front vector FAILED! expected: \n"); - printf(" front.x=%f, front.y=%f, front.z=%f\n",tests[i].frontX,tests[i].frontY,tests[i].frontZ); + printLog(" front vector FAILED! expected: \n"); + printLog(" front.x=%f, front.y=%f, front.z=%f\n",tests[i].frontX,tests[i].frontY,tests[i].frontZ); passed = false; } - printf(" +up.x=%f, up.y=%f, up.z=%f\n",up.x,up.y,up.z); + printLog(" +up.x=%f, up.y=%f, up.z=%f\n",up.x,up.y,up.z); if (up.x == tests[i].upX && up.y == tests[i].upY && up.z == tests[i].upZ) { - printf(" up vector PASSES!\n"); + printLog(" up vector PASSES!\n"); } else { - printf(" up vector FAILED! expected: \n"); - printf(" up.x=%f, up.y=%f, up.z=%f\n",tests[i].upX,tests[i].upY,tests[i].upZ); + printLog(" up vector FAILED! expected: \n"); + printLog(" up.x=%f, up.y=%f, up.z=%f\n",tests[i].upX,tests[i].upY,tests[i].upZ); passed = false; } - printf(" +right.x=%f, right.y=%f, right.z=%f\n",right.x,right.y,right.z); + printLog(" +right.x=%f, right.y=%f, right.z=%f\n",right.x,right.y,right.z); if (right.x == tests[i].rightX && right.y == tests[i].rightY && right.z == tests[i].rightZ) { - printf(" right vector PASSES!\n"); + printLog(" right vector PASSES!\n"); } else { - printf(" right vector FAILED! expected: \n"); - printf(" right.x=%f, right.y=%f, right.z=%f\n",tests[i].rightX,tests[i].rightY,tests[i].rightZ); + printLog(" right vector FAILED! expected: \n"); + printLog(" right.x=%f, right.y=%f, right.z=%f\n",tests[i].rightX,tests[i].rightY,tests[i].rightZ); passed = false; } if (!passed) { - printf("\n-----\nTest: %d - FAILED! \n----------\n\n",i+1); + printLog("\n-----\nTest: %d - FAILED! \n----------\n\n",i+1); failedCount++; } } - printf("\n-----\nTotal Failed: %d out of %d \n----------\n\n",failedCount,totalTests); - printf("\n----------DONE----------\n\n"); + printLog("\n-----\nTotal Failed: %d out of %d \n----------\n\n",failedCount,totalTests); + printLog("\n----------DONE----------\n\n"); } diff --git a/interface/src/VoxelSystem.cpp b/interface/src/VoxelSystem.cpp index ba12218f45..412c0aac75 100644 --- a/interface/src/VoxelSystem.cpp +++ b/interface/src/VoxelSystem.cpp @@ -17,6 +17,8 @@ #include #include #include +#include "Log.h" + #include "VoxelSystem.h" const int MAX_VOXELS_PER_SYSTEM = 250000; @@ -136,15 +138,15 @@ void VoxelSystem::parseData(unsigned char* sourceBuffer, int numBytes) { int commandLength = strlen(command); // commands are null terminated strings int totalLength = 1+commandLength+1; - printf("got Z message len(%d)= %s\n", numBytes, command); + printLog("got Z message len(%d)= %s\n", numBytes, command); while (totalLength <= numBytes) { if (0==strcmp(command,(char*)"erase all")) { - printf("got Z message == erase all\n"); + printLog("got Z message == erase all\n"); tree->eraseAllVoxels(); } if (0==strcmp(command,(char*)"add scene")) { - printf("got Z message == add scene - NOT SUPPORTED ON INTERFACE\n"); + printLog("got Z message == add scene - NOT SUPPORTED ON INTERFACE\n"); } totalLength += commandLength+1; } @@ -194,14 +196,14 @@ int VoxelSystem::treeToArrays(VoxelNode *currentNode, float nodePosition[3]) { float viewerZ = swapXandZ ? viewerPosition[0] : viewerPosition[2]; // debugging code. - //printf("treeToArrays() halfUnitForVoxel=%f\n",halfUnitForVoxel); - //printf("treeToArrays() viewerPosition {x,y,z or [0],[1],[2]} ={%f,%f,%f}\n", - // viewerPosition[0],viewerPosition[1],viewerPosition[2]); - //printf("treeToArrays() nodePosition {x,y,z or [0],[1],[2]} = {%f,%f,%f}\n", - // nodePosition[0],nodePosition[1],nodePosition[2]); + //printLog("treeToArrays() halfUnitForVoxel=%f\n",halfUnitForVoxel); + //printLog("treeToArrays() viewerPosition {x,y,z or [0],[1],[2]} ={%f,%f,%f}\n", + // viewerPosition[0],viewerPosition[1],viewerPosition[2]); + //printLog("treeToArrays() nodePosition {x,y,z or [0],[1],[2]} = {%f,%f,%f}\n", + // nodePosition[0],nodePosition[1],nodePosition[2]); //float* vertices = firstVertexForCode(currentNode->octalCode); - //printf("treeToArrays() firstVerticesForCode(currentNode->octalCode)={x,y,z or [0],[1],[2]} = {%f,%f,%f}\n", - // vertices[0],vertices[1],vertices[2]); + //printLog("treeToArrays() firstVerticesForCode(currentNode->octalCode)={x,y,z or [0],[1],[2]} = {%f,%f,%f}\n", + // vertices[0],vertices[1],vertices[2]); //delete []vertices; float distanceToVoxelCenter = sqrtf(powf(viewerX - nodePosition[0] - halfUnitForVoxel, 2) + @@ -209,7 +211,7 @@ int VoxelSystem::treeToArrays(VoxelNode *currentNode, float nodePosition[3]) { powf(viewerZ - nodePosition[2] - halfUnitForVoxel, 2)); int boundaryPosition = boundaryDistanceForRenderLevel(*currentNode->octalCode + 1); - //printf("treeToArrays() distanceToVoxelCenter=%f boundaryPosition=%d\n",distanceToVoxelCenter,boundaryPosition); + //printLog("treeToArrays() distanceToVoxelCenter=%f boundaryPosition=%d\n",distanceToVoxelCenter,boundaryPosition); bool alwaysDraw = false; // XXXBHG - temporary debug code. Flip this to true to disable LOD blurring diff --git a/interface/src/main.cpp b/interface/src/main.cpp index af60e5d8ba..3248dae02c 100644 --- a/interface/src/main.cpp +++ b/interface/src/main.cpp @@ -151,7 +151,7 @@ float renderPitchRate = 0.f; // Where one's own agent begins in the world (needs to become a dynamic thing passed to the program) glm::vec3 start_location(6.1f, 0, 1.4f); -int statsOn = 0; // Whether to show onscreen text overlay with stats +bool statsOn = true; // Whether to show onscreen text overlay with stats bool starsOn = false; // Whether to display the stars bool paintOn = false; // Whether to paint voxels as you fly around VoxelDetail paintingVoxel; // The voxel we're painting if we're painting diff --git a/interface/src/starfield/Config.h b/interface/src/starfield/Config.h index 001af23a5f..5a9e43477d 100644 --- a/interface/src/starfield/Config.h +++ b/interface/src/starfield/Config.h @@ -39,6 +39,7 @@ #include "InterfaceConfig.h" #include "OGlProgram.h" +#include "Log.h" #include #include diff --git a/interface/src/starfield/Controller.h b/interface/src/starfield/Controller.h index 329119bbc4..8e97a4bcf0 100644 --- a/interface/src/starfield/Controller.h +++ b/interface/src/starfield/Controller.h @@ -211,7 +211,7 @@ namespace starfield { return false; } -// fprintf(stderr, "Stars.cpp: setResolution(%d)\n", k); +// printLog("Stars.cpp: setResolution(%d)\n", k); #if STARFIELD_MULTITHREADING if (k != _valTileResolution.load(memory_order_relaxed)) @@ -251,7 +251,7 @@ namespace starfield { VertexOrder scanner(tiling); radix2InplaceSort(_seqInput.begin(), _seqInput.end(), scanner); -// fprintf(stderr, +// printLog( // "Stars.cpp: recreateRenderer(%d, %d, %d, %d)\n", n, k, b, bMin); recreateRenderer(n, k, b, bMin); @@ -266,7 +266,7 @@ namespace starfield { assert(overalloc >= realloc && realloc >= 0.0); assert(overalloc <= 1.0 && realloc <= 1.0); -// fprintf(stderr, +// printLog( // "Stars.cpp: changeLOD(%lf, %lf, %lf)\n", factor, overalloc, realloc); size_t n, nRender; @@ -307,7 +307,7 @@ namespace starfield { _valLodBrightness = b; #endif -// fprintf(stderr, "Stars.cpp: " +// printLog("Stars.cpp: " // "fraction = %lf, oaFract = %lf, n = %d, n' = %d, bMin = %d, b = %d\n", // fraction, oaFract, toBufSize(oaFract * last)), n, bMin, b); @@ -327,7 +327,7 @@ namespace starfield { recreateRenderer(n, _valTileResolution, b, bMin); -// fprintf(stderr, "Stars.cpp: LOD reallocation\n"); +// printLog("Stars.cpp: LOD reallocation\n"); // publish new lod state diff --git a/interface/src/starfield/Loader.h b/interface/src/starfield/Loader.h index 03dfd18a53..283ee3bffd 100644 --- a/interface/src/starfield/Loader.h +++ b/interface/src/starfield/Loader.h @@ -45,13 +45,12 @@ namespace starfield { if (! UrlReader::readUrl(url, *this)) { - fprintf(stderr, "%s:%d: %s\n", + printLog("%s:%d: %s\n", _strUrl, _valLineNo, getError()); return false; } - fprintf(stderr, "Stars.cpp: read %u vertices, using %lu\n", - _valRecordsRead, _ptrVertices->size()); + printLog("Stars.cpp: read %u vertices, using %lu\n", _valRecordsRead, _ptrVertices->size()); return true; } @@ -72,7 +71,7 @@ namespace starfield { _ptrVertices->clear(); _ptrVertices->reserve(_valLimit); -// fprintf(stderr, "Stars.cpp: loader begin %s\n", url); +// printLog("Stars.cpp: loader begin %s\n", url); } size_t transfer(char* input, size_t bytes) { @@ -111,7 +110,7 @@ namespace starfield { } else { - fprintf(stderr, "Stars.cpp:%d: Bad input from %s\n", + printLog("Stars.cpp:%d: Bad input from %s\n", _valLineNo, _strUrl); } @@ -136,7 +135,7 @@ namespace starfield { // remember the brightness at its top if (_valRecordsRead == _valLimit) { -// fprintf(stderr, "Stars.cpp: vertex limit reached -> heap mode\n"); +// printLog("Stars.cpp: vertex limit reached -> heap mode\n"); make_heap( _ptrVertices->begin(), _ptrVertices->end(), diff --git a/interface/src/starfield/renderer/Renderer.h b/interface/src/starfield/renderer/Renderer.h index 03bc0b5763..5bde4d40da 100644 --- a/interface/src/starfield/renderer/Renderer.h +++ b/interface/src/starfield/renderer/Renderer.h @@ -125,7 +125,7 @@ namespace starfield { mat4 const& orientation, BrightnessLevel minBright) { -// fprintf(stderr, " +// printLog(" // Stars.cpp: rendering at minimal brightness %d\n", minBright); float halfPersp = perspective * 0.5f; @@ -160,7 +160,7 @@ namespace starfield { unsigned tileIndex = _objTiling.getTileIndex(azimuth, altitude); -// fprintf(stderr, "Stars.cpp: starting on tile #%d\n", tileIndex); +// printLog("Stars.cpp: starting on tile #%d\n", tileIndex); #if STARFIELD_DEBUG_LOD @@ -245,7 +245,7 @@ namespace starfield { if (bv >= b) ++count_active; -// fprintf(stderr, "Stars.cpp: Vertex %d on tile #%d\n", vertexIndex, tileIndex); +// printLog("Stars.cpp: Vertex %d on tile #%d\n", vertexIndex, tileIndex); // write converted vertex _arrData[vertexIndex++] = *i; @@ -376,7 +376,7 @@ namespace starfield { float dal = halfSlice; float adjustedNear = cos(_valHalfPersp + sqrt(daz * daz + dal * dal)); -// fprintf(stderr, "Stars.cpp: checking tile #%d, w = %f, near = %f\n", i, w, nearClip); +// printLog("Stars.cpp: checking tile #%d, w = %f, near = %f\n", i, w, nearClip); return w > adjustedNear; } @@ -486,10 +486,10 @@ namespace starfield { void glBatch(GLfloat const* matrix, GLsizei n_ranges) { -// fprintf(stderr, "Stars.cpp: rendering %d-multibatch\n", n_ranges); +// printLog("Stars.cpp: rendering %d-multibatch\n", n_ranges); // for (int i = 0; i < n_ranges; ++i) -// fprintf(stderr, "Stars.cpp: Batch #%d - %d stars @ %d\n", i, +// printLog("Stars.cpp: Batch #%d - %d stars @ %d\n", i, // _arrBatchOffs[i], _arrBatchCount[i]); glDisable(GL_DEPTH_TEST); From e55863a662b7f80d7f9e6117ba78f738dce038d8 Mon Sep 17 00:00:00 2001 From: tosh Date: Wed, 17 Apr 2013 19:46:00 +0200 Subject: [PATCH 10/14] integrates logging for 'shared' library --- interface/src/Log.cpp | 22 ++++++++++++++++------ interface/src/Log.h | 10 +++++++++- interface/src/main.cpp | 5 ++++- libraries/shared/src/AgentList.cpp | 12 +++++++----- libraries/shared/src/AgentList.h | 2 ++ libraries/shared/src/CounterStats.cpp | 6 +++--- libraries/shared/src/PerfStat.cpp | 6 +++++- libraries/shared/src/SharedUtil.cpp | 21 ++++++++++++--------- libraries/shared/src/UDPSocket.cpp | 12 ++++++++---- libraries/shared/src/shared_Log.cpp | 17 +++++++++++++++++ libraries/shared/src/shared_Log.h | 20 ++++++++++++++++++++ 11 files changed, 103 insertions(+), 30 deletions(-) create mode 100644 libraries/shared/src/shared_Log.cpp create mode 100644 libraries/shared/src/shared_Log.h diff --git a/interface/src/Log.cpp b/interface/src/Log.cpp index 5f5381addd..3bfbe19a93 100644 --- a/interface/src/Log.cpp +++ b/interface/src/Log.cpp @@ -144,10 +144,7 @@ inline void Log::addMessage(char const* ptr) { } -void Log::operator()(char const* fmt, ...) { - - va_list args; - va_start(args,fmt); +int Log::vprint(char const* fmt, va_list args) { pthread_mutex_lock(& _mtx); // print to buffer @@ -166,6 +163,14 @@ void Log::operator()(char const* fmt, ...) { } pthread_mutex_unlock(& _mtx); + return n; +} + +void Log::operator()(char const* fmt, ...) { + + va_list args; + va_start(args,fmt); + vprint(fmt, args); va_end(args); } @@ -304,8 +309,13 @@ void Log::render(unsigned screenWidth, unsigned screenHeight) { glMatrixMode(matrixMode); } -Log printLog; - +Log logger; +int printLog(char const* fmt, ...) { + va_list args; + va_start(args,fmt); + logger.vprint(fmt, args); + va_end(args); +} diff --git a/interface/src/Log.h b/interface/src/Log.h index bb74f33933..7def966c32 100644 --- a/interface/src/Log.h +++ b/interface/src/Log.h @@ -10,6 +10,7 @@ #define __interface__Log__ #include +#include #include #include @@ -18,7 +19,13 @@ class Log; // // Call it as you would call 'printf'. // -extern Log printLog; +int printLog(char const* fmt, ...); + +// +// Global instance. +// +extern Log logger; + // // Logging subsystem. @@ -57,6 +64,7 @@ public: void render(unsigned screenWidth, unsigned screenHeight); void operator()(char const* fmt, ...); + int vprint(char const* fmt, va_list); private: // don't copy/assign diff --git a/interface/src/main.cpp b/interface/src/main.cpp index 3248dae02c..d40129580b 100644 --- a/interface/src/main.cpp +++ b/interface/src/main.cpp @@ -889,7 +889,7 @@ void display(void) glLineWidth(1.0f); glPointSize(1.0f); displayStats(); - printLog.render(WIDTH, HEIGHT); + logger.render(WIDTH, HEIGHT); } // Show menu @@ -1514,6 +1514,9 @@ void audioMixerUpdate(in_addr_t newMixerAddress, in_port_t newMixerPort) { int main(int argc, const char * argv[]) { + shared::printLog = ::printLog; + + // Quick test of the Orientation class on startup! testOrientationClass(); diff --git a/libraries/shared/src/AgentList.cpp b/libraries/shared/src/AgentList.cpp index 2751527d37..05e6c5db06 100644 --- a/libraries/shared/src/AgentList.cpp +++ b/libraries/shared/src/AgentList.cpp @@ -21,6 +21,8 @@ #include #endif +using shared::printLog; + const char * SOLO_AGENT_TYPES_STRING = "MV"; char DOMAIN_HOSTNAME[] = "highfidelity.below92.com"; char DOMAIN_IP[100] = ""; // IP Address will be re-set by lookup on startup @@ -37,7 +39,7 @@ AgentList* AgentList::createInstance(char ownerType, unsigned int socketListenPo if (_sharedInstance == NULL) { _sharedInstance = new AgentList(ownerType, socketListenPort); } else { - printf("AgentList createInstance called with existing instance.\n"); + printLog("AgentList createInstance called with existing instance.\n"); } return _sharedInstance; @@ -45,7 +47,7 @@ AgentList* AgentList::createInstance(char ownerType, unsigned int socketListenPo AgentList* AgentList::getInstance() { if (_sharedInstance == NULL) { - printf("AgentList getInstance called before call to createInstance. Returning NULL pointer.\n"); + printLog("AgentList getInstance called before call to createInstance. Returning NULL pointer.\n"); } return _sharedInstance; @@ -391,12 +393,12 @@ void *checkInWithDomainServer(void *args) { sockaddr_in tempAddress; memcpy(&tempAddress.sin_addr, pHostInfo->h_addr_list[0], pHostInfo->h_length); strcpy(DOMAIN_IP, inet_ntoa(tempAddress.sin_addr)); - printf("Domain server: %s \n", DOMAIN_HOSTNAME); + printLog("Domain server: %s \n", DOMAIN_HOSTNAME); } else { - printf("Failed lookup domainserver\n"); + printLog("Failed lookup domainserver\n"); } - } else printf("Using static domainserver IP: %s\n", DOMAIN_IP); + } else printLog("Using static domainserver IP: %s\n", DOMAIN_IP); while (!domainServerCheckinStopFlag) { diff --git a/libraries/shared/src/AgentList.h b/libraries/shared/src/AgentList.h index e01147db9f..e8ff98fe80 100644 --- a/libraries/shared/src/AgentList.h +++ b/libraries/shared/src/AgentList.h @@ -12,6 +12,8 @@ #include #include #include + +#include "shared_Log.h" #include "Agent.h" #include "UDPSocket.h" diff --git a/libraries/shared/src/CounterStats.cpp b/libraries/shared/src/CounterStats.cpp index b86cfd37f2..51d991f0f1 100644 --- a/libraries/shared/src/CounterStats.cpp +++ b/libraries/shared/src/CounterStats.cpp @@ -19,7 +19,7 @@ #endif #include #include - +#include "shared_Log.h" //private: // long int currentCount; @@ -98,7 +98,7 @@ void CounterStatHistory::recordSample(double thisTime, long thisCount) { this->currentTime = thisTime; this->currentDelta = thisDelta; - //printf("CounterStatHistory[%s]::recordSample(thisTime %lf, thisCount= %ld)\n",this->name.c_str(),thisTime,thisCount); + //printLog("CounterStatHistory[%s]::recordSample(thisTime %lf, thisCount= %ld)\n",this->name.c_str(),thisTime,thisCount); // if more than 1/10th of a second has passed, then record // things in our rolling history @@ -115,7 +115,7 @@ void CounterStatHistory::recordSample(double thisTime, long thisCount) { this->timeSamples[this->sampleAt]=thisTime; this->deltaSamples[this->sampleAt]=thisDelta; - //printf("CounterStatHistory[%s]::recordSample() ACTUALLY RECORDING IT sampleAt=%d thisTime %lf, thisCount= %ld)\n",this->name.c_str(),this->sampleAt,thisTime,thisCount); + //printLog("CounterStatHistory[%s]::recordSample() ACTUALLY RECORDING IT sampleAt=%d thisTime %lf, thisCount= %ld)\n",this->name.c_str(),this->sampleAt,thisTime,thisCount); } diff --git a/libraries/shared/src/PerfStat.cpp b/libraries/shared/src/PerfStat.cpp index a6e849aeb0..a312f65c1b 100644 --- a/libraries/shared/src/PerfStat.cpp +++ b/libraries/shared/src/PerfStat.cpp @@ -14,6 +14,10 @@ #include #include +#include "shared_Log.h" + +using shared::printLog; + // Static class members initialization here! std::map > PerfStat::groupHistoryMap; bool PerfStat::wantDebugOut = false; @@ -55,7 +59,7 @@ PerfStat::~PerfStat() { } if (wantDebugOut) { - printf("PerfStats: %s elapsed:%f average:%lf count:%ld total:%lf ut:%d us:%d ue:%d t:%ld s:%ld e:%ld\n", + printLog("PerfStats: %s elapsed:%f average:%lf count:%ld total:%lf ut:%d us:%d ue:%d t:%ld s:%ld e:%ld\n", this->group.c_str(),elapsed,average,count,totalTime, (end.tv_usec-start.tv_usec),start.tv_usec,end.tv_usec, (end.tv_sec-start.tv_sec),start.tv_sec,end.tv_sec diff --git a/libraries/shared/src/SharedUtil.cpp b/libraries/shared/src/SharedUtil.cpp index 8fb8645730..dbd94a089d 100644 --- a/libraries/shared/src/SharedUtil.cpp +++ b/libraries/shared/src/SharedUtil.cpp @@ -12,6 +12,7 @@ #ifdef _WIN32 #include "Syssocket.h" #endif +#include "shared_Log.h" #include "SharedUtil.h" #include "OctalCode.h" @@ -19,6 +20,8 @@ #include #endif +using shared::printLog; + double usecTimestamp(timeval *time) { return (time->tv_sec * 1000000.0 + time->tv_usec); } @@ -50,13 +53,13 @@ bool randomBoolean() { } void outputBits(unsigned char byte) { - printf("%d: ", byte); + printLog("%d: ", byte); for (int i = 0; i < 8; i++) { - printf("%d", byte >> (7 - i) & 1); + printLog("%d", byte >> (7 - i) & 1); } - printf("\n"); + printLog("\n"); } int numberOfOnes(unsigned char byte) { @@ -328,14 +331,14 @@ void printVoxelCode(unsigned char* voxelCode) { unsigned int voxelSizeInOctets = (voxelSizeInBits/3); unsigned int voxelBufferSize = voxelSizeInBytes+1+3; // 1 for size, 3 for color - printf("octets=%d\n",octets); - printf("voxelSizeInBits=%d\n",voxelSizeInBits); - printf("voxelSizeInBytes=%d\n",voxelSizeInBytes); - printf("voxelSizeInOctets=%d\n",voxelSizeInOctets); - printf("voxelBufferSize=%d\n",voxelBufferSize); + printLog("octets=%d\n",octets); + printLog("voxelSizeInBits=%d\n",voxelSizeInBits); + printLog("voxelSizeInBytes=%d\n",voxelSizeInBytes); + printLog("voxelSizeInOctets=%d\n",voxelSizeInOctets); + printLog("voxelBufferSize=%d\n",voxelBufferSize); for(int i=0;i #endif +#include "shared_Log.h" + +using shared::printLog; + sockaddr_in destSockaddr, senderAddress; bool socketMatch(sockaddr *first, sockaddr *second) { @@ -104,7 +108,7 @@ UDPSocket::UDPSocket(int listeningPort) { handle = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (handle <= 0) { - printf("Failed to create socket.\n"); + printLog("Failed to create socket.\n"); return; } @@ -117,7 +121,7 @@ UDPSocket::UDPSocket(int listeningPort) { bind_address.sin_port = htons((uint16_t) listeningPort); if (bind(handle, (const sockaddr*) &bind_address, sizeof(sockaddr_in)) < 0) { - printf("Failed to bind socket to port %d.\n", listeningPort); + printLog("Failed to bind socket to port %d.\n", listeningPort); return; } @@ -127,7 +131,7 @@ UDPSocket::UDPSocket(int listeningPort) { tv.tv_usec = 500000; setsockopt(handle, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof tv); - printf("Created UDP socket listening on port %d.\n", listeningPort); + printLog("Created UDP socket listening on port %d.\n", listeningPort); } UDPSocket::~UDPSocket() { @@ -196,7 +200,7 @@ int UDPSocket::send(sockaddr *destAddress, const void *data, size_t byteLength) 0, (sockaddr *) destAddress, sizeof(sockaddr_in)); if (sent_bytes != byteLength) { - printf("Failed to send packet: %s\n", strerror(errno)); + printLog("Failed to send packet: %s\n", strerror(errno)); return false; } diff --git a/libraries/shared/src/shared_Log.cpp b/libraries/shared/src/shared_Log.cpp new file mode 100644 index 0000000000..ad8cd2d9c0 --- /dev/null +++ b/libraries/shared/src/shared_Log.cpp @@ -0,0 +1,17 @@ +// +// Log.cpp +// hifi +// +// Created by Tobias Schwinger on 4/17/13. +// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// + +#include "shared_Log.h" + +#include + +namespace shared { + using namespace std; + + int (* printLog)(char const*, ...) = & printf; +} diff --git a/libraries/shared/src/shared_Log.h b/libraries/shared/src/shared_Log.h new file mode 100644 index 0000000000..4916ddf5c1 --- /dev/null +++ b/libraries/shared/src/shared_Log.h @@ -0,0 +1,20 @@ +// +// shared_Log.h +// hifi +// +// Created by Tobias Schwinger on 4/17/13. +// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// + +#ifndef __hifi__shared_Log__ +#define __hifi__shared_Log__ + +namespace shared { + + // variable that can be set from outside to redirect the log output + // of this library + extern int (* printLog)(char const*, ...); +} + +#endif /* defined(__hifi__shared_Log__) */ + From 493fafb213b55967647225b42a895f32058d8392 Mon Sep 17 00:00:00 2001 From: tosh Date: Wed, 17 Apr 2013 19:48:30 +0200 Subject: [PATCH 11/14] adds optional LogStream for cpp iostream-style logging --- interface/src/LogStream.h | 106 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 106 insertions(+) create mode 100644 interface/src/LogStream.h diff --git a/interface/src/LogStream.h b/interface/src/LogStream.h new file mode 100644 index 0000000000..88e5d4fff0 --- /dev/null +++ b/interface/src/LogStream.h @@ -0,0 +1,106 @@ +// +// LogStream.h +// interface +// +// Created by Tobias Schwinger on 4/17/13. +// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// + +#ifndef __interface__LogStream__ +#define __interface__LogStream__ + +#include + +#include "Log.h" + +// +// Makes the logging facility accessible as a C++ stream. +// +// Example: +// +// // somewhere central - ideally one per thread (else pass 'true' as +// // second constructor argument and compromise some efficiency) +// LogStream lOut(printLog); +// +// // elsewhere: +// lOut << "Hello there!" << std::endl; +// +class LogStream { + std::ostringstream _objOutStream; + Log& _refLog; + bool _flgThreadSafe; +public: + inline LogStream(Log& log, bool threadSafe = false); + + class StreamRef; friend class StreamRef; + + template< typename T > friend inline LogStream::StreamRef const operator<<(LogStream&, T const&); + +private: + // don't + LogStream(LogStream const&); // = delete; + LogStream& operator=(LogStream const&); // = delete; + + inline void ostreamBegin(); + inline void ostreamEnd(); +}; + +inline LogStream::LogStream(Log& log, bool threadSafe) : + _objOutStream(std::ios_base::out), _refLog(log), _flgThreadSafe(threadSafe) { } + +inline void LogStream::ostreamBegin() { + + if (_flgThreadSafe) { + // the user wants to share this LogStream among threads, + // so lock the global log here, already + pthread_mutex_lock(& _refLog._mtx); + } + _objOutStream.str(""); +} + +inline void LogStream::ostreamEnd() { + + if (! _flgThreadSafe) { + // haven't locked, so far (we have memory for each thread) + pthread_mutex_lock(& _refLog._mtx); + } + _refLog.addMessage(_objOutStream.str().c_str()); + pthread_mutex_unlock(& _refLog._mtx); +} + + +// +// The Log::StreamRef class makes operator<< work. It... +// +class LogStream::StreamRef { + mutable LogStream* _ptrLogStream; + typedef std::ostream& (*manipulator)(std::ostream&); + + friend class LogStream; + + template< typename T > friend inline LogStream::StreamRef const operator<<(LogStream&, T const&); + StreamRef(LogStream* log) : _ptrLogStream(log) { } +public: + // ...forwards << operator calls to stringstream... + template< typename T > StreamRef const operator<<(T const& x) const { _ptrLogStream->_objOutStream << x; return *this; } + // ...has to dance around to make manipulators (such as std::hex, std::endl) work... + StreamRef const operator<<(manipulator x) const { _ptrLogStream->_objOutStream << x; return *this; } + // ...informs the logger that a stream has ended when it has the responsibility... + ~StreamRef() { if (_ptrLogStream != 0l) { _ptrLogStream->ostreamEnd(); } } + // ...which is passed on upon copy. + StreamRef(StreamRef const& other) : _ptrLogStream(other._ptrLogStream) { other._ptrLogStream = 0l; } + +private: + // don't + StreamRef& operator=(StreamRef const&); // = delete; +}; + +template< typename T > inline LogStream::StreamRef const operator<<(LogStream& s, T const& x) { + + s.ostreamBegin(); + s._objOutStream << x; + return LogStream::StreamRef(& s); // calls streamEnd at the end of the stream expression +} + + +#endif From 4ddbbd62093fa2e5d228b6c0d488ae5151f26d17 Mon Sep 17 00:00:00 2001 From: tosh Date: Wed, 17 Apr 2013 20:01:33 +0200 Subject: [PATCH 12/14] fixes misplaced include .h -> .cpp --- libraries/shared/src/AgentList.cpp | 1 + libraries/shared/src/AgentList.h | 1 - 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/shared/src/AgentList.cpp b/libraries/shared/src/AgentList.cpp index 05e6c5db06..6ca05ba6a1 100644 --- a/libraries/shared/src/AgentList.cpp +++ b/libraries/shared/src/AgentList.cpp @@ -14,6 +14,7 @@ #include "AgentTypes.h" #include "PacketHeaders.h" #include "SharedUtil.h" +#include "shared_Log.h" #ifdef _WIN32 #include "Syssocket.h" diff --git a/libraries/shared/src/AgentList.h b/libraries/shared/src/AgentList.h index e8ff98fe80..b87aadf8a9 100644 --- a/libraries/shared/src/AgentList.h +++ b/libraries/shared/src/AgentList.h @@ -13,7 +13,6 @@ #include #include -#include "shared_Log.h" #include "Agent.h" #include "UDPSocket.h" From f899ff9378a00d2683a8321d7ef8c05e4ebc5556 Mon Sep 17 00:00:00 2001 From: tosh Date: Wed, 17 Apr 2013 20:01:58 +0200 Subject: [PATCH 13/14] adds logging support to voxels library --- interface/src/main.cpp | 34 +++++++++++----------- libraries/voxels/src/Plane.cpp | 6 +++- libraries/voxels/src/ViewFrustum.cpp | 43 +++++++++++++++------------- libraries/voxels/src/VoxelNode.cpp | 7 +++-- libraries/voxels/src/VoxelTree.cpp | 20 +++++++------ 5 files changed, 61 insertions(+), 49 deletions(-) diff --git a/interface/src/main.cpp b/interface/src/main.cpp index d40129580b..c024a03ba9 100644 --- a/interface/src/main.cpp +++ b/interface/src/main.cpp @@ -48,6 +48,8 @@ #include #include "Log.h" +#include "shared_Log.h" +#include "voxels_Log.h" #include "Field.h" #include "world.h" @@ -134,7 +136,7 @@ Cloud cloud(0, // Particles false // Wrap ); -VoxelSystem voxels; +VoxelSystem voxSys; Field field; #ifndef _WIN32 @@ -243,28 +245,28 @@ void displayStats(void) } std::stringstream voxelStats; - voxelStats << "Voxels Rendered: " << voxels.getVoxelsRendered(); + voxelStats << "Voxels Rendered: " << voxSys.getVoxelsRendered(); drawtext(10, statsVerticalOffset + 70, 0.10f, 0, 1.0, 0, (char *)voxelStats.str().c_str()); voxelStats.str(""); - voxelStats << "Voxels Created: " << voxels.getVoxelsCreated() << " (" << voxels.getVoxelsCreatedRunningAverage() + voxelStats << "Voxels Created: " << voxSys.getVoxelsCreated() << " (" << voxSys.getVoxelsCreatedRunningAverage() << "/sec in last "<< COUNTETSTATS_TIME_FRAME << " seconds) "; drawtext(10, statsVerticalOffset + 250, 0.10f, 0, 1.0, 0, (char *)voxelStats.str().c_str()); voxelStats.str(""); - voxelStats << "Voxels Colored: " << voxels.getVoxelsColored() << " (" << voxels.getVoxelsColoredRunningAverage() + voxelStats << "Voxels Colored: " << voxSys.getVoxelsColored() << " (" << voxSys.getVoxelsColoredRunningAverage() << "/sec in last "<< COUNTETSTATS_TIME_FRAME << " seconds) "; drawtext(10, statsVerticalOffset + 270, 0.10f, 0, 1.0, 0, (char *)voxelStats.str().c_str()); voxelStats.str(""); - voxelStats << "Voxels Bytes Read: " << voxels.getVoxelsBytesRead() - << " (" << voxels.getVoxelsBytesReadRunningAverage() << "/sec in last "<< COUNTETSTATS_TIME_FRAME << " seconds) "; + voxelStats << "Voxels Bytes Read: " << voxSys.getVoxelsBytesRead() + << " (" << voxSys.getVoxelsBytesReadRunningAverage() << "/sec in last "<< COUNTETSTATS_TIME_FRAME << " seconds) "; drawtext(10, statsVerticalOffset + 290,0.10f, 0, 1.0, 0, (char *)voxelStats.str().c_str()); voxelStats.str(""); - long int voxelsBytesPerColored = voxels.getVoxelsColored() ? voxels.getVoxelsBytesRead()/voxels.getVoxelsColored() : 0; - long int voxelsBytesPerColoredAvg = voxels.getVoxelsColoredRunningAverage() ? - voxels.getVoxelsBytesReadRunningAverage()/voxels.getVoxelsColoredRunningAverage() : 0; + long int voxelsBytesPerColored = voxSys.getVoxelsColored() ? voxSys.getVoxelsBytesRead()/voxSys.getVoxelsColored() : 0; + long int voxelsBytesPerColoredAvg = voxSys.getVoxelsColoredRunningAverage() ? + voxSys.getVoxelsBytesReadRunningAverage()/voxSys.getVoxelsColoredRunningAverage() : 0; voxelStats << "Voxels Bytes per Colored: " << voxelsBytesPerColored << " (" << voxelsBytesPerColoredAvg << "/sec in last "<< COUNTETSTATS_TIME_FRAME << " seconds) "; @@ -301,8 +303,8 @@ void initDisplay(void) void init(void) { - voxels.init(); - voxels.setViewerHead(&myAvatar); + voxSys.init(); + voxSys.setViewerHead(&myAvatar); myAvatar.setRenderYaw(startYaw); headMouseX = WIDTH/2; @@ -817,7 +819,7 @@ void display(void) // Draw voxels if ( showingVoxels ) { - voxels.render(); + voxSys.render(); } // Draw field vectors @@ -1151,7 +1153,7 @@ void addRandomSphere(bool wantColorRandomizer) printLog("yc=%f\n",yc); printLog("zc=%f\n",zc); - voxels.createSphere(r,xc,yc,zc,s,solid,wantColorRandomizer); + voxSys.createSphere(r,xc,yc,zc,s,solid,wantColorRandomizer); } @@ -1313,7 +1315,7 @@ void *networkReceive(void *args) case PACKET_HEADER_VOXEL_DATA: case PACKET_HEADER_Z_COMMAND: case PACKET_HEADER_ERASE_VOXEL: - voxels.parseData(incomingPacket, bytesReceived); + voxSys.parseData(incomingPacket, bytesReceived); break; case PACKET_HEADER_BULK_AVATAR_DATA: AgentList::getInstance()->processBulkAgentData(&senderAddress, @@ -1515,7 +1517,7 @@ void audioMixerUpdate(in_addr_t newMixerAddress, in_port_t newMixerPort) { int main(int argc, const char * argv[]) { shared::printLog = ::printLog; - + voxels::printLog = ::printLog; // Quick test of the Orientation class on startup! testOrientationClass(); @@ -1599,7 +1601,7 @@ int main(int argc, const char * argv[]) // Voxel File. If so, load it now. const char* voxelsFilename = getCmdOption(argc, argv, "-i"); if (voxelsFilename) { - voxels.loadVoxelsFile(voxelsFilename,wantColorRandomizer); + voxSys.loadVoxelsFile(voxelsFilename,wantColorRandomizer); printLog("Local Voxel File loaded.\n"); } diff --git a/libraries/voxels/src/Plane.cpp b/libraries/voxels/src/Plane.cpp index fa23affe6c..083f6cf46e 100755 --- a/libraries/voxels/src/Plane.cpp +++ b/libraries/voxels/src/Plane.cpp @@ -5,6 +5,10 @@ #include "Plane.h" #include +#include "voxels_Log.h" + +using voxels::printLog; + // These are some useful utilities that vec3 is missing float vec3_length(const glm::vec3& v) { return((float)sqrt(v.x*v.x + v.y*v.y + v.z*v.z)); @@ -79,5 +83,5 @@ float Plane::distance(const glm::vec3 &p) { } void Plane::print() { - //printf("Plane(");normal.print();printf("# %f)",d); + //printLog("Plane(");normal.print();printLog("# %f)",d); } diff --git a/libraries/voxels/src/ViewFrustum.cpp b/libraries/voxels/src/ViewFrustum.cpp index dbf5e061bf..de126eae50 100644 --- a/libraries/voxels/src/ViewFrustum.cpp +++ b/libraries/voxels/src/ViewFrustum.cpp @@ -9,6 +9,9 @@ // #include "ViewFrustum.h" +#include "voxels_Log.h" + +using voxels::printLog; ViewFrustum::ViewFrustum() : _position(glm::vec3(0,0,0)), @@ -95,39 +98,39 @@ void ViewFrustum::calculate() { void ViewFrustum::dump() { - printf("position.x=%f, position.y=%f, position.z=%f\n", this->_position.x, this->_position.y, this->_position.z); - printf("direction.x=%f, direction.y=%f, direction.z=%f\n", this->_direction.x, this->_direction.y, this->_direction.z); - printf("up.x=%f, up.y=%f, up.z=%f\n", this->_up.x, this->_up.y, this->_up.z); - printf("right.x=%f, right.y=%f, right.z=%f\n", this->_right.x, this->_right.y, this->_right.z); + printLog("position.x=%f, position.y=%f, position.z=%f\n", this->_position.x, this->_position.y, this->_position.z); + printLog("direction.x=%f, direction.y=%f, direction.z=%f\n", this->_direction.x, this->_direction.y, this->_direction.z); + printLog("up.x=%f, up.y=%f, up.z=%f\n", this->_up.x, this->_up.y, this->_up.z); + printLog("right.x=%f, right.y=%f, right.z=%f\n", this->_right.x, this->_right.y, this->_right.z); - printf("farDist=%f\n", this->_farClip); - printf("farHeight=%f\n", this->_farHeight); - printf("farWidth=%f\n", this->_farWidth); + printLog("farDist=%f\n", this->_farClip); + printLog("farHeight=%f\n", this->_farHeight); + printLog("farWidth=%f\n", this->_farWidth); - printf("nearDist=%f\n", this->_nearClip); - printf("nearHeight=%f\n", this->_nearHeight); - printf("nearWidth=%f\n", this->_nearWidth); + printLog("nearDist=%f\n", this->_nearClip); + printLog("nearHeight=%f\n", this->_nearHeight); + printLog("nearWidth=%f\n", this->_nearWidth); - printf("farCenter.x=%f, farCenter.y=%f, farCenter.z=%f\n", + printLog("farCenter.x=%f, farCenter.y=%f, farCenter.z=%f\n", this->_farCenter.x, this->_farCenter.y, this->_farCenter.z); - printf("farTopLeft.x=%f, farTopLeft.y=%f, farTopLeft.z=%f\n", + printLog("farTopLeft.x=%f, farTopLeft.y=%f, farTopLeft.z=%f\n", this->_farTopLeft.x, this->_farTopLeft.y, this->_farTopLeft.z); - printf("farTopRight.x=%f, farTopRight.y=%f, farTopRight.z=%f\n", + printLog("farTopRight.x=%f, farTopRight.y=%f, farTopRight.z=%f\n", this->_farTopRight.x, this->_farTopRight.y, this->_farTopRight.z); - printf("farBottomLeft.x=%f, farBottomLeft.y=%f, farBottomLeft.z=%f\n", + printLog("farBottomLeft.x=%f, farBottomLeft.y=%f, farBottomLeft.z=%f\n", this->_farBottomLeft.x, this->_farBottomLeft.y, this->_farBottomLeft.z); - printf("farBottomRight.x=%f, farBottomRight.y=%f, farBottomRight.z=%f\n", + printLog("farBottomRight.x=%f, farBottomRight.y=%f, farBottomRight.z=%f\n", this->_farBottomRight.x, this->_farBottomRight.y, this->_farBottomRight.z); - printf("nearCenter.x=%f, nearCenter.y=%f, nearCenter.z=%f\n", + printLog("nearCenter.x=%f, nearCenter.y=%f, nearCenter.z=%f\n", this->_nearCenter.x, this->_nearCenter.y, this->_nearCenter.z); - printf("nearTopLeft.x=%f, nearTopLeft.y=%f, nearTopLeft.z=%f\n", + printLog("nearTopLeft.x=%f, nearTopLeft.y=%f, nearTopLeft.z=%f\n", this->_nearTopLeft.x, this->_nearTopLeft.y, this->_nearTopLeft.z); - printf("nearTopRight.x=%f, nearTopRight.y=%f, nearTopRight.z=%f\n", + printLog("nearTopRight.x=%f, nearTopRight.y=%f, nearTopRight.z=%f\n", this->_nearTopRight.x, this->_nearTopRight.y, this->_nearTopRight.z); - printf("nearBottomLeft.x=%f, nearBottomLeft.y=%f, nearBottomLeft.z=%f\n", + printLog("nearBottomLeft.x=%f, nearBottomLeft.y=%f, nearBottomLeft.z=%f\n", this->_nearBottomLeft.x, this->_nearBottomLeft.y, this->_nearBottomLeft.z); - printf("nearBottomRight.x=%f, nearBottomRight.y=%f, nearBottomRight.z=%f\n", + printLog("nearBottomRight.x=%f, nearBottomRight.y=%f, nearBottomRight.z=%f\n", this->_nearBottomRight.x, this->_nearBottomRight.y, this->_nearBottomRight.z); } diff --git a/libraries/voxels/src/VoxelNode.cpp b/libraries/voxels/src/VoxelNode.cpp index 7300af814a..d0b65f060f 100644 --- a/libraries/voxels/src/VoxelNode.cpp +++ b/libraries/voxels/src/VoxelNode.cpp @@ -8,6 +8,7 @@ #include #include "SharedUtil.h" +//#include "voxels_Log.h" #include "VoxelNode.h" #include "OctalCode.h" @@ -76,7 +77,7 @@ bool VoxelNode::collapseIdenticalLeaves() { // if no child, or child doesn't have a color if (children[i] == NULL || children[i]->color[3] != 1) { allChildrenMatch=false; - //printf("SADNESS child missing or not colored! i=%d\n",i); + //printLog("SADNESS child missing or not colored! i=%d\n",i); break; } else { if (i==0) { @@ -92,7 +93,7 @@ bool VoxelNode::collapseIdenticalLeaves() { if (allChildrenMatch) { - //printf("allChildrenMatch: pruning tree\n"); + //printLog("allChildrenMatch: pruning tree\n"); for (int i = 0; i < 8; i++) { delete children[i]; // delete all the child nodes children[i]=NULL; // set it to NULL @@ -111,4 +112,4 @@ void VoxelNode::setRandomColor(int minimumBrightness) { } color[3] = 1; -} \ No newline at end of file +} diff --git a/libraries/voxels/src/VoxelTree.cpp b/libraries/voxels/src/VoxelTree.cpp index 2f18b8af50..8a56487de3 100644 --- a/libraries/voxels/src/VoxelTree.cpp +++ b/libraries/voxels/src/VoxelTree.cpp @@ -13,6 +13,7 @@ #include #include #include "SharedUtil.h" +#include "voxels_Log.h" #include "PacketHeaders.h" #include "CounterStats.h" #include "OctalCode.h" @@ -20,6 +21,7 @@ #include // to load voxels from file #include // to load voxels from file +using voxels::printLog; int boundaryDistanceForRenderLevel(unsigned int renderLevel) { switch (renderLevel) { @@ -416,7 +418,7 @@ unsigned char * VoxelTree::loadBitstreamBuffer(unsigned char *& bitstreamBuffer, void VoxelTree::processRemoveVoxelBitstream(unsigned char * bitstream, int bufferSizeBytes) { // XXXBHG: validate buffer is at least 4 bytes long? other guards?? unsigned short int itemNumber = (*((unsigned short int*)&bitstream[1])); - printf("processRemoveVoxelBitstream() receivedBytes=%d itemNumber=%d\n",bufferSizeBytes,itemNumber); + printLog("processRemoveVoxelBitstream() receivedBytes=%d itemNumber=%d\n",bufferSizeBytes,itemNumber); int atByte = 3; unsigned char* pVoxelData = (unsigned char*)&bitstream[3]; while (atByte < bufferSizeBytes) { @@ -424,7 +426,7 @@ void VoxelTree::processRemoveVoxelBitstream(unsigned char * bitstream, int buffe int voxelDataSize = bytesRequiredForCodeLength(octets)+3; // 3 for color! float* vertices = firstVertexForCode(pVoxelData); - printf("deleting voxel at: %f,%f,%f\n",vertices[0],vertices[1],vertices[2]); + printLog("deleting voxel at: %f,%f,%f\n",vertices[0],vertices[1],vertices[2]); delete []vertices; deleteVoxelCodeFromTree(pVoxelData); @@ -510,11 +512,11 @@ void VoxelTree::loadVoxelsFile(const char* fileName, bool wantColorRandomizer) { int totalBytesRead = 0; if(file.is_open()) { - printf("loading file...\n"); + printLog("loading file...\n"); bool bail = false; while (!file.eof() && !bail) { file.get(octets); - //printf("octets=%d...\n",octets); + //printLog("octets=%d...\n",octets); totalBytesRead++; lengthInBytes = bytesRequiredForCodeLength(octets)-1; //(octets*3/8)+1; unsigned char * voxelData = new unsigned char[lengthInBytes+1+3]; @@ -536,14 +538,14 @@ void VoxelTree::loadVoxelsFile(const char* fileName, bool wantColorRandomizer) { file.get(colorRead); blue = (unsigned char)colorRead; - printf("voxel color from file red:%d, green:%d, blue:%d \n",red,green,blue); + printLog("voxel color from file red:%d, green:%d, blue:%d \n",red,green,blue); vCount++; int colorRandomizer = wantColorRandomizer ? randIntInRange (-5, 5) : 0; voxelData[lengthInBytes+1] = std::max(0,std::min(255,red + colorRandomizer)); voxelData[lengthInBytes+2] = std::max(0,std::min(255,green + colorRandomizer)); voxelData[lengthInBytes+3] = std::max(0,std::min(255,blue + colorRandomizer)); - printf("voxel color after rand red:%d, green:%d, blue:%d\n", + printLog("voxel color after rand red:%d, green:%d, blue:%d\n", voxelData[lengthInBytes+1], voxelData[lengthInBytes+2], voxelData[lengthInBytes+3]); //printVoxelCode(voxelData); @@ -608,7 +610,7 @@ void VoxelTree::createSphere(float r,float xc, float yc, float zc, float s, bool // If you also iterate form the interior of the sphere to the radius, makeing // larger and larger sphere's you'd end up with a solid sphere. And lots of voxels! for (; ri <= (r+(s/2.0)); ri+=s) { - //printf("radius: ri=%f ri+s=%f (r+(s/2.0))=%f\n",ri,ri+s,(r+(s/2.0))); + //printLog("radius: ri=%f ri+s=%f (r+(s/2.0))=%f\n",ri,ri+s,(r+(s/2.0))); for (float theta=0.0; theta <= 2*M_PI; theta += angleDelta) { for (float phi=0.0; phi <= M_PI; phi += angleDelta) { t++; // total voxels @@ -622,7 +624,7 @@ void VoxelTree::createSphere(float r,float xc, float yc, float zc, float s, bool // only use our actual desired color on the outer edge, otherwise // use our "average" color if (ri+(s*2.0)>=r) { - //printf("painting candy shell radius: ri=%f r=%f\n",ri,r); + //printLog("painting candy shell radius: ri=%f r=%f\n",ri,r); red = wantColorRandomizer ? randomColorValue(165) : r1+((r2-r1)*gradient); green = wantColorRandomizer ? randomColorValue(165) : g1+((g2-g1)*gradient); blue = wantColorRandomizer ? randomColorValue(165) : b1+((b2-b1)*gradient); @@ -630,7 +632,7 @@ void VoxelTree::createSphere(float r,float xc, float yc, float zc, float s, bool unsigned char* voxelData = pointToVoxel(x,y,z,s,red,green,blue); this->readCodeColorBufferToTree(voxelData); - //printf("voxel data for x:%f y:%f z:%f s:%f\n",x,y,z,s); + //printLog("voxel data for x:%f y:%f z:%f s:%f\n",x,y,z,s); //printVoxelCode(voxelData); delete voxelData; } From bf5f54c9d047ea74fa8bac4eac4f300b4da977a7 Mon Sep 17 00:00:00 2001 From: tosh Date: Wed, 17 Apr 2013 20:14:29 +0200 Subject: [PATCH 14/14] integrates logging for 'avatars' library, fixes missig return in Log.cpp, adds _lib suffix for log callback namespaces and reverts voxels -> voxLib rename in main --- interface/src/Log.cpp | 4 ++- interface/src/main.cpp | 36 ++++++++++++++------------- libraries/avatars/src/Orientation.cpp | 20 ++++++++------- libraries/avatars/src/avatars_Log.cpp | 17 +++++++++++++ libraries/avatars/src/avatars_Log.h | 20 +++++++++++++++ libraries/shared/src/AgentList.cpp | 2 +- libraries/shared/src/PerfStat.cpp | 2 +- libraries/shared/src/SharedUtil.cpp | 2 +- libraries/shared/src/UDPSocket.cpp | 2 +- libraries/shared/src/shared_Log.cpp | 4 +-- libraries/shared/src/shared_Log.h | 2 +- libraries/voxels/src/Plane.cpp | 2 +- libraries/voxels/src/ViewFrustum.cpp | 2 +- libraries/voxels/src/VoxelNode.cpp | 2 ++ libraries/voxels/src/VoxelTree.cpp | 2 +- libraries/voxels/src/voxels_Log.cpp | 17 +++++++++++++ libraries/voxels/src/voxels_Log.h | 20 +++++++++++++++ 17 files changed, 119 insertions(+), 37 deletions(-) create mode 100644 libraries/avatars/src/avatars_Log.cpp create mode 100644 libraries/avatars/src/avatars_Log.h create mode 100644 libraries/voxels/src/voxels_Log.cpp create mode 100644 libraries/voxels/src/voxels_Log.h diff --git a/interface/src/Log.cpp b/interface/src/Log.cpp index 3bfbe19a93..454a64a0fb 100644 --- a/interface/src/Log.cpp +++ b/interface/src/Log.cpp @@ -313,9 +313,11 @@ Log logger; int printLog(char const* fmt, ...) { + int result; va_list args; va_start(args,fmt); - logger.vprint(fmt, args); + result = logger.vprint(fmt, args); va_end(args); + return result; } diff --git a/interface/src/main.cpp b/interface/src/main.cpp index c024a03ba9..31cd2cd07e 100644 --- a/interface/src/main.cpp +++ b/interface/src/main.cpp @@ -50,6 +50,7 @@ #include "Log.h" #include "shared_Log.h" #include "voxels_Log.h" +#include "avatars_Log.h" #include "Field.h" #include "world.h" @@ -136,7 +137,7 @@ Cloud cloud(0, // Particles false // Wrap ); -VoxelSystem voxSys; +VoxelSystem voxels; Field field; #ifndef _WIN32 @@ -245,28 +246,28 @@ void displayStats(void) } std::stringstream voxelStats; - voxelStats << "Voxels Rendered: " << voxSys.getVoxelsRendered(); + voxelStats << "Voxels Rendered: " << voxels.getVoxelsRendered(); drawtext(10, statsVerticalOffset + 70, 0.10f, 0, 1.0, 0, (char *)voxelStats.str().c_str()); voxelStats.str(""); - voxelStats << "Voxels Created: " << voxSys.getVoxelsCreated() << " (" << voxSys.getVoxelsCreatedRunningAverage() + voxelStats << "Voxels Created: " << voxels.getVoxelsCreated() << " (" << voxels.getVoxelsCreatedRunningAverage() << "/sec in last "<< COUNTETSTATS_TIME_FRAME << " seconds) "; drawtext(10, statsVerticalOffset + 250, 0.10f, 0, 1.0, 0, (char *)voxelStats.str().c_str()); voxelStats.str(""); - voxelStats << "Voxels Colored: " << voxSys.getVoxelsColored() << " (" << voxSys.getVoxelsColoredRunningAverage() + voxelStats << "Voxels Colored: " << voxels.getVoxelsColored() << " (" << voxels.getVoxelsColoredRunningAverage() << "/sec in last "<< COUNTETSTATS_TIME_FRAME << " seconds) "; drawtext(10, statsVerticalOffset + 270, 0.10f, 0, 1.0, 0, (char *)voxelStats.str().c_str()); voxelStats.str(""); - voxelStats << "Voxels Bytes Read: " << voxSys.getVoxelsBytesRead() - << " (" << voxSys.getVoxelsBytesReadRunningAverage() << "/sec in last "<< COUNTETSTATS_TIME_FRAME << " seconds) "; + voxelStats << "Voxels Bytes Read: " << voxels.getVoxelsBytesRead() + << " (" << voxels.getVoxelsBytesReadRunningAverage() << "/sec in last "<< COUNTETSTATS_TIME_FRAME << " seconds) "; drawtext(10, statsVerticalOffset + 290,0.10f, 0, 1.0, 0, (char *)voxelStats.str().c_str()); voxelStats.str(""); - long int voxelsBytesPerColored = voxSys.getVoxelsColored() ? voxSys.getVoxelsBytesRead()/voxSys.getVoxelsColored() : 0; - long int voxelsBytesPerColoredAvg = voxSys.getVoxelsColoredRunningAverage() ? - voxSys.getVoxelsBytesReadRunningAverage()/voxSys.getVoxelsColoredRunningAverage() : 0; + long int voxelsBytesPerColored = voxels.getVoxelsColored() ? voxels.getVoxelsBytesRead()/voxels.getVoxelsColored() : 0; + long int voxelsBytesPerColoredAvg = voxels.getVoxelsColoredRunningAverage() ? + voxels.getVoxelsBytesReadRunningAverage()/voxels.getVoxelsColoredRunningAverage() : 0; voxelStats << "Voxels Bytes per Colored: " << voxelsBytesPerColored << " (" << voxelsBytesPerColoredAvg << "/sec in last "<< COUNTETSTATS_TIME_FRAME << " seconds) "; @@ -303,8 +304,8 @@ void initDisplay(void) void init(void) { - voxSys.init(); - voxSys.setViewerHead(&myAvatar); + voxels.init(); + voxels.setViewerHead(&myAvatar); myAvatar.setRenderYaw(startYaw); headMouseX = WIDTH/2; @@ -819,7 +820,7 @@ void display(void) // Draw voxels if ( showingVoxels ) { - voxSys.render(); + voxels.render(); } // Draw field vectors @@ -1153,7 +1154,7 @@ void addRandomSphere(bool wantColorRandomizer) printLog("yc=%f\n",yc); printLog("zc=%f\n",zc); - voxSys.createSphere(r,xc,yc,zc,s,solid,wantColorRandomizer); + voxels.createSphere(r,xc,yc,zc,s,solid,wantColorRandomizer); } @@ -1315,7 +1316,7 @@ void *networkReceive(void *args) case PACKET_HEADER_VOXEL_DATA: case PACKET_HEADER_Z_COMMAND: case PACKET_HEADER_ERASE_VOXEL: - voxSys.parseData(incomingPacket, bytesReceived); + voxels.parseData(incomingPacket, bytesReceived); break; case PACKET_HEADER_BULK_AVATAR_DATA: AgentList::getInstance()->processBulkAgentData(&senderAddress, @@ -1516,8 +1517,9 @@ void audioMixerUpdate(in_addr_t newMixerAddress, in_port_t newMixerPort) { int main(int argc, const char * argv[]) { - shared::printLog = ::printLog; - voxels::printLog = ::printLog; + shared_lib::printLog = & ::printLog; + voxels_lib::printLog = & ::printLog; + avatars_lib::printLog = & ::printLog; // Quick test of the Orientation class on startup! testOrientationClass(); @@ -1601,7 +1603,7 @@ int main(int argc, const char * argv[]) // Voxel File. If so, load it now. const char* voxelsFilename = getCmdOption(argc, argv, "-i"); if (voxelsFilename) { - voxSys.loadVoxelsFile(voxelsFilename,wantColorRandomizer); + voxels.loadVoxelsFile(voxelsFilename,wantColorRandomizer); printLog("Local Voxel File loaded.\n"); } diff --git a/libraries/avatars/src/Orientation.cpp b/libraries/avatars/src/Orientation.cpp index 8eeb3dd0ff..2ee190d2d5 100755 --- a/libraries/avatars/src/Orientation.cpp +++ b/libraries/avatars/src/Orientation.cpp @@ -7,7 +7,9 @@ #include "Orientation.h" #include +#include "avatars_Log.h" +using avatars_lib::printLog; static bool testingForNormalizationAndOrthogonality = true; @@ -101,7 +103,7 @@ void Orientation::testForOrthogonalAndNormalizedVectors( float epsilon ) { if (( rightLength > 1.0f + epsilon ) || ( rightLength < 1.0f - epsilon )) { - printf( "Error in Orientation class: right direction length is %f \n", rightLength ); + printLog( "Error in Orientation class: right direction length is %f \n", rightLength ); } assert ( rightLength > 1.0f - epsilon ); assert ( rightLength < 1.0f + epsilon ); @@ -109,7 +111,7 @@ void Orientation::testForOrthogonalAndNormalizedVectors( float epsilon ) { if (( upLength > 1.0f + epsilon ) || ( upLength < 1.0f - epsilon )) { - printf( "Error in Orientation class: up direction length is %f \n", upLength ); + printLog( "Error in Orientation class: up direction length is %f \n", upLength ); } assert ( upLength > 1.0f - epsilon ); assert ( upLength < 1.0f + epsilon ); @@ -117,7 +119,7 @@ void Orientation::testForOrthogonalAndNormalizedVectors( float epsilon ) { if (( frontLength > 1.0f + epsilon ) || ( frontLength < 1.0f - epsilon )) { - printf( "Error in Orientation class: front direction length is %f \n", frontLength ); + printLog( "Error in Orientation class: front direction length is %f \n", frontLength ); } assert ( frontLength > 1.0f - epsilon ); assert ( frontLength < 1.0f + epsilon ); @@ -137,22 +139,22 @@ void Orientation::testForOrthogonalAndNormalizedVectors( float epsilon ) { if ( rightDiff > epsilon ) { - printf( "Error in Orientation class: right direction not orthogonal to up and/or front. " ); - printf( "The tested cross of up and front is off by %f \n", rightDiff ); + printLog( "Error in Orientation class: right direction not orthogonal to up and/or front. " ); + printLog( "The tested cross of up and front is off by %f \n", rightDiff ); } assert ( rightDiff < epsilon ); if ( upDiff > epsilon ) { - printf( "Error in Orientation class: up direction not orthogonal to front and/or right. " ); - printf( "The tested cross of front and right is off by %f \n", upDiff ); + printLog( "Error in Orientation class: up direction not orthogonal to front and/or right. " ); + printLog( "The tested cross of front and right is off by %f \n", upDiff ); } assert ( upDiff < epsilon ); if ( frontDiff > epsilon ) { - printf( "Error in Orientation class: front direction not orthogonal to right and/or up. " ); - printf( "The tested cross of right and up is off by %f \n", frontDiff ); + printLog( "Error in Orientation class: front direction not orthogonal to right and/or up. " ); + printLog( "The tested cross of right and up is off by %f \n", frontDiff ); } assert ( frontDiff < epsilon ); } diff --git a/libraries/avatars/src/avatars_Log.cpp b/libraries/avatars/src/avatars_Log.cpp new file mode 100644 index 0000000000..da8712b755 --- /dev/null +++ b/libraries/avatars/src/avatars_Log.cpp @@ -0,0 +1,17 @@ +// +// avatars_Log.cpp +// hifi +// +// Created by Tobias Schwinger on 4/17/13. +// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// + +#include "shared_Log.h" + +#include + +namespace avatars_lib { + using namespace std; + + int (* printLog)(char const*, ...) = & printf; +} diff --git a/libraries/avatars/src/avatars_Log.h b/libraries/avatars/src/avatars_Log.h new file mode 100644 index 0000000000..1d07cf46bf --- /dev/null +++ b/libraries/avatars/src/avatars_Log.h @@ -0,0 +1,20 @@ +// +// avatars_Log.h +// hifi +// +// Created by Tobias Schwinger on 4/17/13. +// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// + +#ifndef __hifi__avatars_Log__ +#define __hifi__avatars_Log__ + +namespace avatars_lib { + + // variable that can be set from outside to redirect the log output + // of this library + extern int (* printLog)(char const*, ...); +} + +#endif /* defined(__hifi__avatars_Log__) */ + diff --git a/libraries/shared/src/AgentList.cpp b/libraries/shared/src/AgentList.cpp index 86564d21e0..d246d460b5 100644 --- a/libraries/shared/src/AgentList.cpp +++ b/libraries/shared/src/AgentList.cpp @@ -22,7 +22,7 @@ #include #endif -using shared::printLog; +using shared_lib::printLog; const char * SOLO_AGENT_TYPES_STRING = "MV"; char DOMAIN_HOSTNAME[] = "highfidelity.below92.com"; diff --git a/libraries/shared/src/PerfStat.cpp b/libraries/shared/src/PerfStat.cpp index a312f65c1b..2c3dcf93b7 100644 --- a/libraries/shared/src/PerfStat.cpp +++ b/libraries/shared/src/PerfStat.cpp @@ -16,7 +16,7 @@ #include "shared_Log.h" -using shared::printLog; +using shared_lib::printLog; // Static class members initialization here! std::map > PerfStat::groupHistoryMap; diff --git a/libraries/shared/src/SharedUtil.cpp b/libraries/shared/src/SharedUtil.cpp index dbd94a089d..39333f858e 100644 --- a/libraries/shared/src/SharedUtil.cpp +++ b/libraries/shared/src/SharedUtil.cpp @@ -20,7 +20,7 @@ #include #endif -using shared::printLog; +using shared_lib::printLog; double usecTimestamp(timeval *time) { return (time->tv_sec * 1000000.0 + time->tv_usec); diff --git a/libraries/shared/src/UDPSocket.cpp b/libraries/shared/src/UDPSocket.cpp index a61dbeb20a..94565f43ee 100644 --- a/libraries/shared/src/UDPSocket.cpp +++ b/libraries/shared/src/UDPSocket.cpp @@ -22,7 +22,7 @@ #include "shared_Log.h" -using shared::printLog; +using shared_lib::printLog; sockaddr_in destSockaddr, senderAddress; diff --git a/libraries/shared/src/shared_Log.cpp b/libraries/shared/src/shared_Log.cpp index ad8cd2d9c0..93a5c74714 100644 --- a/libraries/shared/src/shared_Log.cpp +++ b/libraries/shared/src/shared_Log.cpp @@ -1,5 +1,5 @@ // -// Log.cpp +// shared_Log.cpp // hifi // // Created by Tobias Schwinger on 4/17/13. @@ -10,7 +10,7 @@ #include -namespace shared { +namespace shared_lib { using namespace std; int (* printLog)(char const*, ...) = & printf; diff --git a/libraries/shared/src/shared_Log.h b/libraries/shared/src/shared_Log.h index 4916ddf5c1..29c1a4ed57 100644 --- a/libraries/shared/src/shared_Log.h +++ b/libraries/shared/src/shared_Log.h @@ -9,7 +9,7 @@ #ifndef __hifi__shared_Log__ #define __hifi__shared_Log__ -namespace shared { +namespace shared_lib { // variable that can be set from outside to redirect the log output // of this library diff --git a/libraries/voxels/src/Plane.cpp b/libraries/voxels/src/Plane.cpp index 083f6cf46e..2f0d43925b 100755 --- a/libraries/voxels/src/Plane.cpp +++ b/libraries/voxels/src/Plane.cpp @@ -7,7 +7,7 @@ #include "voxels_Log.h" -using voxels::printLog; +using voxels_lib::printLog; // These are some useful utilities that vec3 is missing float vec3_length(const glm::vec3& v) { diff --git a/libraries/voxels/src/ViewFrustum.cpp b/libraries/voxels/src/ViewFrustum.cpp index de126eae50..867b47922f 100644 --- a/libraries/voxels/src/ViewFrustum.cpp +++ b/libraries/voxels/src/ViewFrustum.cpp @@ -11,7 +11,7 @@ #include "ViewFrustum.h" #include "voxels_Log.h" -using voxels::printLog; +using voxels_lib::printLog; ViewFrustum::ViewFrustum() : _position(glm::vec3(0,0,0)), diff --git a/libraries/voxels/src/VoxelNode.cpp b/libraries/voxels/src/VoxelNode.cpp index d0b65f060f..5f36ad9e59 100644 --- a/libraries/voxels/src/VoxelNode.cpp +++ b/libraries/voxels/src/VoxelNode.cpp @@ -12,6 +12,8 @@ #include "VoxelNode.h" #include "OctalCode.h" +// using voxels_lib::printLog; + VoxelNode::VoxelNode() { octalCode = NULL; diff --git a/libraries/voxels/src/VoxelTree.cpp b/libraries/voxels/src/VoxelTree.cpp index 8a56487de3..87a8ea9307 100644 --- a/libraries/voxels/src/VoxelTree.cpp +++ b/libraries/voxels/src/VoxelTree.cpp @@ -21,7 +21,7 @@ #include // to load voxels from file #include // to load voxels from file -using voxels::printLog; +using voxels_lib::printLog; int boundaryDistanceForRenderLevel(unsigned int renderLevel) { switch (renderLevel) { diff --git a/libraries/voxels/src/voxels_Log.cpp b/libraries/voxels/src/voxels_Log.cpp new file mode 100644 index 0000000000..6fd637a1ec --- /dev/null +++ b/libraries/voxels/src/voxels_Log.cpp @@ -0,0 +1,17 @@ +// +// voxels_Log.cpp +// hifi +// +// Created by Tobias Schwinger on 4/17/13. +// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// + +#include "voxels_Log.h" + +#include + +namespace voxels_lib { + using namespace std; + + int (* printLog)(char const*, ...) = & printf; +} diff --git a/libraries/voxels/src/voxels_Log.h b/libraries/voxels/src/voxels_Log.h new file mode 100644 index 0000000000..3403058a3d --- /dev/null +++ b/libraries/voxels/src/voxels_Log.h @@ -0,0 +1,20 @@ +// +// voxels_Log.h +// hifi +// +// Created by Tobias Schwinger on 4/17/13. +// Copyright (c) 2013 High Fidelity, Inc. All rights reserved. +// + +#ifndef __hifi__voxels_Log__ +#define __hifi__voxels_Log__ + +namespace voxels_lib { + + // variable that can be set from outside to redirect the log output + // of this library + extern int (* printLog)(char const*, ...); +} + +#endif /* defined(__hifi__voxels_Log__) */ +