vector drawing lib Anti-Grain combined with Ogre

February 4th, 2012 No comments

developed a little ogre application:
http://www.ogre3d.org/forums/viewtopic.php?f=11&t=68749

Categories: coding, Ogre3D Tags:

trim trailing spaces from files

January 31st, 2012 No comments
1
2
find . -name "*.h" -print0 | xargs -0 perl -pi -e 's/ +$//'
find . -name "*.cpp" -print0 | xargs -0 perl -pi -e 's/ +$//'
Categories: coding Tags:

python and windows terminal colors: the lightweight version

January 3rd, 2012 No comments

its hard to get colored output on windows if you do not want to pull in any dependencies, so i wrote my own little class. The handy thing is, that it wraps around the stdout and parses the stream to colorize the output.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import sys
import ctypes

# Constants from the Windows API
class WTCW: #WindowsTerminalColourWrapper:
    WRAPPERS = ['{', '}']
   
    # windows api constants: DO NOT CHANGE
    STD_INPUT_HANDLE = -10 ; STD_OUTPUT_HANDLE= -11 ; STD_ERROR_HANDLE = -12
    FG_BLUE = 0x01 ; FG_GREEN= 0x02 ; FG_RED  = 0x04 ; FG_INTENSITY = 0x08 ; BG_BLUE = 0x10 ; BG_GREEN= 0x20 ; BG_RED  = 0x40 ; BG_INTENSITY = 0x80
    colors = {'r': FG_RED, 'g':FG_GREEN, 'b':FG_BLUE, 'R':BG_RED, 'G':BG_GREEN, 'B':BG_BLUE, 'i':FG_INTENSITY, 'I':BG_INTENSITY, 'w':FG_RED|FG_GREEN|FG_BLUE }
   
    def _get_csbi_attributes(self):
        import struct
        csbi = ctypes.create_string_buffer(22) ; res = ctypes.windll.kernel32.GetConsoleScreenBufferInfo(self.handle, csbi) ; assert res
        (bufx, bufy, curx, cury, wattr, left, top, right, bottom, maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw)
        return wattr
    def __init__(self, stream, defColor = ''):
        self.stream = stream ; self.defColor = self._parseColor(defColor)
        self.handle = ctypes.windll.kernel32.GetStdHandle(self.STD_OUTPUT_HANDLE)
        self.reset  = self._get_csbi_attributes()
    def __del__(self): self.resetColor()
    def _parseColor(self, str):
        colval = 0
        for c in str:
            if c.lower() == 'x':
                self.resetColor()
                break
            colval |= self.colors[c]
        return colval
   
    def write(self, data):
        if self.defColor != 0:
            self.setColour(defColor)
        parts = data.split(self.WRAPPERS[0])
        for part in parts:
            f = part.find(self.WRAPPERS[1])
            if f != -1:
                self.setColour(self._parseColor(part[0:f]))
                self.stream.write(part[f+len(self.WRAPPERS[1]):])
            else:
                self.stream.write(part)
            self.stream.flush()
        #self.resetColor() #uncomment this to reset the color after every invocation
    def __getattr__(self, attr): return getattr(self.stream, attr)
    def setColour(self, col): ctypes.windll.kernel32.SetConsoleTextAttribute(self.handle, col)
    def resetColor(self): ctypes.windll.kernel32.SetConsoleTextAttribute(self.handle, self.reset)

#how to use: wrap around streams
sys.stdout = WTCW(sys.stdout)
#sys.stderr = WTCW(sys.stderr)

# examples, syntax is {color}:
print '{r}red {g}green {b}blue {x}normal'
print '{rgb}white {rg}yellow {rb}purple {gb}turquois {x}normal'
print '{w}white {rg}yellow {rb}purple {gb}turquois {x}normal'
print '{ri}red {gi}green {bi}blue {x}normal'
print '{R}red {G}green {B}blue {x}normal'
print '{rG}red {gR}green {bR}blue {x}normal'
print '{rGI}red {gRI}green {bRI}blue {x}normal'

the output looks like this:

if you want a good solution when you do not care about dependencies, i would suggest reading this thread

Categories: coding, python Tags:

MFC and mouse wheel focus

December 14th, 2011 No comments

So i am developing a little MFC application using the VS wizard. It features a main (central) view where i am drawing via GDIPlus. Everything worked quite well, until i tried adding mouse wheel support. Turns out, the control that has focus will get wheel events, and no one else. Since i dont want to click into the window before its usable, i have added this little workaround, should work well for the default MFC applications:

1
2
3
4
5
6
7
8
9
10
11
12
BOOL CMainFrame::PreTranslateMessage( MSG* pMsg )
{
    // big workaround for stupid windows behavior:
    if(pMsg->message == WM_MOUSEWHEEL && GetCapture() == NULL)
    {
        // if the mousewheel was used, send it to the window below the cursor, no matter if it has the focus or not.
        pMsg->hwnd = ::WindowFromPoint(pMsg->pt);
        pMsg->lParam = MAKELPARAM(pMsg->pt.x, pMsg->pt.y);
    }
    // return control to the default handlers
    return CFrameWndEx::PreTranslateMessage(pMsg);
}

It overrides “PreTranslateMessage” and redirects the mouse wheel message to the window below the mouse cursor.

Categories: cpp Tags:

dinkumware

August 22nd, 2011 No comments

you know them? well if you code under windows you probably use their software:

Dinkum STL library by P.J. Plauger (http://www.dinkumware.com/) commercial STL implementation widely used, since it was licensed in is co-maintained by Microsoft and it is the STL implementation that ships with Visual Studio.
There are many different implementations of the STL, all based on the language standard but nevertheless differing from each other, making it transparent for the programmer, enabling specialization and rapid evolution of the code base.

(http://en.wikibooks.org/wiki/C++_Programming/STL)

http://www.dinkumware.com/

Categories: coding Tags:

Ogre-MeshTool

August 15th, 2011 No comments

the new project: http://code.google.com/p/ogre-meshtool/

also, seems my work was mentioned in the Ogre News #12: http://www.ogre3d.org/2011/08/11/ogre-news-12 (the Ogre Procedural bit)

Categories: coding Tags:

OgreMeshy

August 12th, 2011 No comments

just contributed to that project: Ogre Meshy

my changes

Categories: coding, OSS Tags:

how to format bytes as a human readable string without branching

August 8th, 2011 1 comment

its actually not so complicated:

1
2
3
4
5
6
7
8
9
std::string formatBytes(unsigned long bytes)
{
        char tmp[128] = "";
        const char *si_prefix[] = { "B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
        const int base = 1024;
    int c = std::min((int)(log((double)bytes)/log((double)base)), (int)sizeof(si_prefix) - 1);
    sprintf(tmp, "%1.2f %s", bytes / pow((double)base, c), si_prefix[c]);
        return std::string(tmp);
}
Categories: coding, cpp Tags:

using c++ templates with function pointers

August 2nd, 2011 No comments

so, i am currently writing an XML parser and one part of the code processes attributes of a XML node:

1
2
3
4
5
6
7
Real radius = 1.0f;
if(n->first_attribute("radius"))
  radius   = StringConverter::parseReal(n->first_attribute("radius")->value());

int segments = 8;
if(n->first_attribute("segments"))
  segments = StringConverter::parseInt(n->first_attribute("segments")->value());

so this is very boring to write and also error-prone. So i came up with this handy template that calls the Setter you define with the correct argument:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// some parsing helpers
void parseArgument(const char *str, int &res) { res =Ogre::StringConverter::parseInt(str); }
void parseArgument(const char *str, unsigned int &res) { res =Ogre::StringConverter::parseInt(str); }
void parseArgument(const char *str, Ogre::Real &res) { res = Ogre::StringConverter::parseReal(str); }
void parseArgument(const char *str, Ogre::Vector3 &res) { res = Ogre::StringConverter::parseVector3(str); }
void parseArgument(const char *str, Ogre::Vector2 &res) { res = Ogre::StringConverter::parseVector2(str); }

template <class TVarType>
TVarType getAttribute(xml_node<> *node, const char *attribute_name, const TVarType defaultValue)
{
    TVarType val = defaultValue;
    xml_attribute<> *atr = node->first_attribute(attribute_name);
    if(atr)
        parseArgument(atr->value(), val);
    return val;
}

// template function that calls a setter with an attribute value
template <class TClass,  class TVarType>
TVarType useAttributeForSetter(xml_node<> *node, const char *attribute_name, const TVarType defaultValue, TClass& (TClass::*setterFunction)(TVarType), TClass &instance, bool setDefault = true)
{
    TVarType val = defaultValue;
    xml_attribute<> *atr = node->first_attribute(attribute_name);
    if(atr)
    {
        parseArgument(atr->value(), val);
        // now try to use the setter
        (instance.*setterFunction)(val);
    } else if(!atr && setDefault)
    {
        (instance.*setterFunction)(val);
    }
    return val;
}

and now it looks much easier:

1
2
3
4
CircleShape cs = CircleShape();
// where the magic happens ;)
useAttributeForSetter<CircleShape, Real>(n, "radius", 1, &CircleShape::setRadius, cs);
useAttributeForSetter<CircleShape, unsigned int>(n, "segments", 8, &CircleShape::setNumSeg, cs);
Categories: cpp Tags:

free up cached memory in linux

May 31st, 2011 No comments

if you look at the free memory with “free -m” and then look with “top” what uses the memory, you will see a huge gap sometimes. This is the cached memory.

If you want to free it, you can execute this:

1
echo 1 > /proc/sys/vm/drop_caches
Categories: gentoo Tags: