Jan
09
2010
0

Overloaded Virtual Methods

This week I came by a new kind of bug that I’ve never had before, and is up the top of bugs I’ve came by when using CodeWarrior, the top still being invisible syntax.

Though I don’t think anything can top that, it can be hell if you have garbage at the end of a line, and you can’t see it when even though the compiler tells you something is wrong, luckily to solve that one, you just press a key or change someone on the same line and it makes it visible.

Anyways, this bug is caused by having overloaded pure virtual or virtual methods in a base class, but only implementing some of the them in the derived class.

It causes the compiler to not acknowledge any of the other overloaded functions, which you can end up spending a lot of time trying to solve if you’re not familiar with it.

The below code shows an example base class for causing this error.

class BaseClass
{
    //
    // Functions
    public:
        //
        //
        BaseClass()
        {
        }

        //
        //
        virtual ~BaseClass()
        {
        }

        //
        //
        virtual int Multiply( const int inValue1 )
        {
            return 2 * inValue;
        }

        //
        //
        virtual int Multiply( const int inValue1, const int inValue2 )
        {
            return 2 * inValue1 * inValue2;
        }
};

If in the derived class you implement one of these, as shown below, and then try to access one of the other overloaded that are only implemented in the base, the error will happen, telling you something like there are no overloaded versions of that function that take that parameters you are giving.

class DerivedClass : public BaseClass
{
    //
    // Functions
    public:
        DerivedClass()
            :
            BaseClass()
        {
        }

        //
        //
        int Multiply( const int inValue1 )
        {
            return 3 * inValue1;
        }
};

//
//
int Main()
{
    DerivedClass testClass;
    return testClass.Multiply( 2, 3 );
}

Now I’m sure I had use overloaded virtual functions before, so why was this happening now. So after a bit of searching I found out that only some compilers have support for this.

The reason the error occurs, is because the compiler generates a list of virtual function names to link to in the class. However, if it fails to find a function matching the name of what is being called, it will check the base.

Because we had overloaded only one of overloaded virtual functions, it ended its search in the derived class. And when it tries to associate the correct function call with the correct function, it notices that the function has a different number of parameters to that which is recorded in the list, and causes an error.

Now there is a way around it, you explicitly tell the compiler to use the functions listed in the base by use of the “using” keyword.

class DerivedClass : public BaseClass
{
    //
    // Functions
    public:
        //
        //
        DerivedClass()
            :
            BaseClass()
        {
        }

        //
        //
        using BaseClass::Multiply;

        //
        //
        int Multiply( const int inValue1 )
        {
            return 3 * inValue1;
        }
};

//
//
int Main()
{
    DerivedClass testClass;
    return testClass.Multiply( 2, 3 );
}

This will not error, since when the compiler is generating a list of functions, it will also include the Multiply functions in the base. The using keyword also has scope, so putting it in public will make the functions accessible outside the class.

Written by Kaluriel in: Code | Tags:
Jan
03
2010
0

C# – Endian Swap

In 1726, there were tensions between Lilliput and Blefuscu, the problem being soft-boiled eggs. The inhabitants of Lilliput crack open their eggs at the small end, while the inhabitants of Blefuscu crack open theirs at the big end.

In 2010, while writing a Midi file parser in C#, I needed the ability to swap the endian of the data, since Midi files are stored as Big Endian, converting them into Little Endian.

I would have thought there would be some function within the BitConverter class to be able to swap, but there didn’t appear to be, so I wrote my own.

Since swapping endian is just reversing the byte order, the simplest method would be to get the bytes of a number, and reverse the array, then reconstruct the number using the reversed bytes.

//
//
using System;

//
//
namespace Midi
{
    class Endian
    {
        //
        //
        public static UInt16 SwapUInt16( UInt16 inValue )
        {
            byte[] byteArray = BitConverter.GetBytes(inValue);
            Array.Reverse(byteArray);
            return BitConverter.ToUInt16(byteArray,0);
        }

        //
        //
        public static UInt32 SwapUInt32( UInt32 inValue )
        {
            byte[] byteArray = BitConverter.GetBytes(inValue);
            Array.Reverse(byteArray);
            return BitConverter.ToUInt32(byteArray,0);
        }
    }
}

But this method is slower than just using a bitshift.

//
//
using System;

//
//
namespace Midi
{
    class Endian
    {
        //
        //
        public static UInt16 SwapUInt16( UInt16 inValue )
        {
            return (UInt16)( ((inValue & 0xff00) >> 8) |
                             ((inValue & 0x00ff) << 8) );
        }

        //
        //
        public static UInt32 SwapUInt32( UInt32 inValue )
        {
            return (UInt32)( ((inValue & 0xff000000) >> 24) |
                             ((inValue & 0x00ff0000) >> 8) |
                             ((inValue & 0x0000ff00) << 8) |
                             ((inValue & 0x000000ff) << 24) );
        }
    }
}

Since any the there are only 16 bit and 32 bit numbers in the Midi file format, and anything larger is of Variable Length Quantity, these are the only two required.

Written by Kaluriel in: Code | Tags: , ,
Dec
23
2009
0

Midi Delta Time Ticks to Seconds

One of the main problems with parsing midi files, is the amount of bad documentation people has put on their websites for converting delta time ticks into seconds or milliseconds.

Eventually I got ahold of the Midi Standard 1.0 which helped me solve this riddle for when calculating it myself, and will hopefully help others who have this problem.

When calculating delta time, “Set Tempo” and “Time Signature” meta events need to be handled. Also remember that the raw denominator for “Time Signature” meta events needs to be used as the exponent for raising two to a power:

const float kTimeSignatureDenominator = powf( 2, rawTimeSignatureDenominator );

This first page will cover correctly calculating “Beats Per Minute” (BPM) correctly. And although a lot of examples seem to think you require this to convert delta time ticks to seconds or milliseconds, you don’t.

What is a Beat?

In music, there is something called a Bar, which is a segment of time defined by a given number of beats of a given duration. The values which define a Bar, are called the Time Signature.

A Time Signature, is two numbers, one on top of the other. The numerator describes the number of Beats in a Bar, while the denominator describes of what note value a Beat is.

So 4/4 would be four quarter-notes per Bar, while 4/2 would be four half-notes per Bar, 4/8 would be four eighth-notes per Bar, and 2/4 would be two quarter-notes per Bar.

Calculating BPM

Now a lot of examples say to default the tempo to 120 BPM, and the time signature to 4/4, which is correct. But when handling the “Set Tempo” meta event, the same examples just use the value straight out to calculate the BPM, which is incorrect if the time signature has changed.

The “Set Tempo” meta event in midi only deals in quarter notes, so if the time signature is 4/8, a quarter-note is not a Beat since its described as an eighth-note, so using it to calculate BPM  on its own is incorrect.

const float kOneMinuteInMicroseconds = 60000000;

// This is wrong if the time signature is not 4/4
float BPM = kOneMinuteInMicroseconds / newMicrosecondsPerQuarterNote;

So how do we solve this? We use the new time signature to scale our BPM to the correct value.

const float kOneMinuteInMicroseconds = 60000000;
const float kTimeSignatureNumerator = 4.0f; // For show only, use the actual time signature numerator
const float kTimeSignatureDenominator = 4.0f; // For show only, use the actual time signature denominator
// This is correct
float BPM = ( kOneMinuteInMicroseconds / newMicrosecondsPerQuarterNote ) * ( kTimeSignatureDenominator / 4.0f );

In the code above, we divide the time signature denominator by four (The number four is the denominator value for quarter note), this gives us the number of notes per quarter note. Four divided by four is one, so the BPM remains the same.

If the value of kTimeSignatureDenominator was “8.0f”, then eight divided by four is two (there are two eighth-notes in a quarter note).

The next page will cover the actual conversion of delta time ticks to seconds (or milliseconds).

Written by Kaluriel in: Code | Tags: , , ,

Pages: 1 2


Dec
22
2009
0

C# – Midi Variable Length Quantity

On the way home on the train for Christmas, I began porting my Midi parsing class over to C#.

The snippet below shows how to read to read a Variable Length Quantity (sometimes known as a Variable Length Value).

The way it works is very simple, it checks the first byte to see if the MSB is set, if it set it will keep iterating, moving along one byte and doing the same, shifting the previous value across 7 bits until the MSB isn’t set.

If it isn’t set on the initial test, the value from that byte will be used for the value of the VLQ.

//
//
using System;

//
//
namespace Midi
{
    class VariableLengthQuantity
    {
        //
        // Functions
        public VariableLengthQuantity( byte[] inVariableData, int inOffset )
        {
            int offset = inOffset;

            // At least one byte is always used
            m_value = inVariableData[offset];
            m_numBytes = 1;
            ++offset;

            //
            if( ((m_value & 0x80) != 0) )
            {
                UInt32 c;

                //
                m_value &= 0x7F;

                //
                do
                {
                    //
                    c = inVariableData[offset];

                    //
                    m_value = (m_value << 7) + (c & 0x7F);

                    //
                    ++m_numBytes;
                    ++offset;
                } while( (c & 0x80) != 0 );
            }
        }

        //
        //
        public UInt32 Value
        {
            get
            {
                return m_value;
            }
        }

        //
        //
        public UInt32 NumBytes
        {
            get
            {
                return m_numBytes;
            }
        }

        //
        // Attributes
        UInt32 m_value;
        UInt32 m_numBytes;
    }
}
Written by Kaluriel in: Code | Tags: , ,
Oct
06
2009
0

Mutable and Volatile Keywords

I’ve seen mutable used only a few times, and not thought much about it until recently went I was reading about what it does on MSDN. This keyword makes a variable ignore whether a function is const or not within a class.

Below is an example of one way it could be used.

class MyClass
{
 //
 // Functions
 public:
  //
  //
  MyClass()
   :
   m_value( 10 ),
   m_valueGetCount( 0 )
  {
  }

  //
  //
  int GetValue() const
  {
   // Class variable can be changed despite function being declared const
   ++m_valueGetCount;
   return m_value;
  }

  //
  //
  unsigned int ValueGetCount() const
  {
    return m_valueGetCount;
  }

 //
 // Attributes
 private:
  int m_value;
  mutable unsigned int m_valueGetCount;
};

My experiences with it have been for thread synchronization objects I use such as my Semaphore class. For some reason the MacOSX implementation of the semaphore doesn’t allow me to get the count, so I had to add a variable myself.

The mutable keyword allowed me to keep the class usable within a const scope, which the use of const_cast().

Another keyword I seem to use with threads a lot is volatile. It prevents variable value being cached, forcing it be read from memory every single time it is access.

//
//
namespace
{
 volatile bool l_myBoolean = true;
}

//
//
void main()
{
 //
 createSomeOtherThread();

 //
 while( l_myBoolean )
 {
  // do nothing
 }
}

//
//
int someOtherThread( void * inParam )
{
 l_myBoolean = false;
 return 0;
}

In the case of a while loop that relies on a boolean that gets updated in another thread, this has the potentially that the compiler will cache it and thus the loop will never end.

Written by Kaluriel in: Code | Tags: ,
Sep
19
2009
0

Athena: Word Wrap

Athena: Word WrapOne thing I hate doing is writing classes that will output text, as well as handle special character sequences that get replaced by images. And while all this is happening, having it word wrap as well.

So I wrote a quick word wrap template class today that will do this. It doesn’t give line spacing yet, which I’m still unsure whether or not it should be this.

The way it works is when you create the word wrap object, you can pass to it’s constructor a value for the maximum width a line can be, this can be a floating point value, or an integer (it defaults to integer).

Then you call Parse() and give it a string, it will go through that string, checking the width of characters until the accumulated character widths are greater than the maximum width, or a new line is found. It will output this line of characters and move onto the next bit.

If it finds a word that is longer than maximum width, it will do one of two things. First if it is at the start of a newline, it will cut the word at the point it goes over. If it is already part way into a line, it will cause a new line and put the word on the next line.

I’ve included with this blog entry the header for the word wrap class, it comes as part of a test project in Xcode (it uses the Lorem Ipsum text), but the source and headers should work in another C++ IDE.

Download Source: Athena Word Wrap Source (Version 1.0.0)
Written by Kaluriel in: Athena, Code | Tags: , ,
Sep
10
2009
0

Athena: Bezier Curves

Bezier CurveWhen animations are exported from Maya through COLLADA files, they come out in a variety of formats depending on how the animation was implemented, and what is being animated.

One format is the bezier curve, a curve made from four points. Two fo the points are the start and end position, and the other two are control points that describe how it should curve.

Bezier Curve ApplicationSince all three axis can be animated, I made it possible to make a 3-component vector bezier class using the bezier class I created, and just calculate the point coefficients once, passing them to the bezier class to get the position. This of course only works if the time length for curves are the same on all three axis.

I’ve made a sample, it is an Xcode project that uses GLUT to render a 2D bezier and a 3D bezier. The code should work with other IDEs. One thing I should warn is that this bezier class only works when the time step is constant between the control point and it’s respective point.

P0 (0, 0) … keypoint 0
P1 (2, 10) … keypoint 1
C0 (0.666667, 42.6212) … control point 0
C1 (1.33333, 10) … control point 1

T0 = (C0 – P0) -> (2, 42.6212)
T1 = (P1 – C1) -> (2, 0)

The above sample is from the COLLADA forum, as you can see the time step is 2 for both T0 and T1. The same post describes how to calculate the S0 if your time step is not constant.

Download Source: Athena Bezier Source (Version 1.0.0)
Written by Kaluriel in: Athena, Code | Tags: , ,
Jul
05
2009
0

C# – Mono on Mac OS X

Mono Project LogoI’m always up for trying new ways of not having to boot up VMWare Fusion, and when searching for C# code, I came by a blog about something using Mono. Mono is a cross platform solution for using .NET and it is open source, which means I can write, compile and execute C# in MacOSX.

I found its strangely easy to setup, though I have yet to get WinForms to work from the examples, I have got console apps working. And with the console app, I have been able to use XPath.

The only downside was it took an hour to download from their website, which is quite bad for only 50MB.

Written by Kaluriel in: Code | Tags: , , , ,
Jul
04
2009
0

C# – XPath and Converting a Relative Path to Absolute

Star Ocean - The Last HopeToday whilst doing some C# programming, I came by a path within a file that was relative to the path I was reading it from. Since my application wasn’t in the same place, and I didn’t want it to be be for it to be, I needed to convert it to an absolute path.

This is C#, it should be simple right?

Well apparently System.IO.Path.Combine() doesn’t take into account “./” or “../” and just concatenates and added an additional forward slash if needed.

After a bit of searching, and many different examples (most of which just converted absolute to relative), I found what I needed. This method used System.IO.Path.GetFullPath() with System.IO.Path.Combine() (If I used the relative path on its own with GetFullPath() I just got the relative path from the current executable directory).

I made it into a single function I can call but I was surprised that there wasn’t something already to do this considering what C# has impressed me with so far for thinking ahead.

//
//
using System.IO;

//
//
static string GetAbsoluteFromRelative( string inBasePath, string inRelativePath )
{
return Path.GetFullPath( Path.Combine( inBasePath, inRelativePath ) );
}

It hasn’t tainted my image of C# though, I still adore it for its XML XPath node iterator library thing that has MySQL searching features.

I also found a spiffy thing I didn’t know about XPath as well. If I have a set of data like so.

<FileList>

<Folder>

<File>MyFile</File>

</Folder>

<File>MyOtherFile</File>

</FileList>

I can iterate through all file nodes within file list with a double-slash before “File” within my node select call.

XPathNavigator nav;

// ...

XPathNodeIterator fileNodes = nav.Select("/FileList//File");

while( fileNodes.MoveNext() )
{
Console.WriteLine( fileNodes.Current.Value );
}

I still seem to have problems with namespaces in some XML documents though (ones without them seem to make searching a hassle).

Written by Kaluriel in: Code | Tags: , ,
Jul
01
2009
0

Athena: Wiimote and Mac OS X

Wiimote USB DrivesSince solving the problem of the rumbling on the XBox 360 pad, I’ve grown bored of it, and decided to branch out trying to get more controllers working in my engine.

So a few days ago I started with the Wiimote, I had planned to try to the PS3 controller but I didn’t have one, so borrowing one of my housemates Wiimotes I set to work.

There is quite a lot of documentation on the Wiimote at the moment, whether it is the correct way to do things is questionable, since there are cases like “1? – it is set to 1 by the Wii” and “set this to 0×55 at memory address X and set to 0×00 at memory address Y to enable it”.

I started with website called The Wiimote Project, but as their documentation grew scarce I found a better site (which it seemed to copy it all from anyways) called WiiBrew. The WiiBrew wiki is quite comprehensive and within a few minutes I already had the LEDs flashing.

I won’t go into a lot of detail, I’ll just show the basics that I’ve got to grips with from the documentation on WiiBrew – LEDs + Motor, Buttons, and Battery.

Connecting the Wiimote

Connecting the Wiimote to a Mac is far simpler than it is for XBox 360, for a start its a Bluetooth device that operates using the normal protocols and it doesn’t require a key to activate. To connect, first turn on Bluetooth on your Mac, and then select “Set up Bluetooth Device…“.

Follow on the onscreen instructions, and when it gets to the point where it is searching for nearby Bluetooth devices, press 1 + 2 to soft synchronize if the Wiimote isn’t bound to another device, or the sync button to hard synchronize (unbinds the Wiimote from anything it remembers).

When it appears, select it and click the “Passkey Options…” button. Select the “Do not use a passkey with this device” option and then OK. Continue on and the device will be setup and connected. You can’t actually tell since the LEDs are still blinking, but if you have done it correctly, the Bluetooth icon should be different, or the menu will have a disconnect option for the device just setup.

Written by Kaluriel in: Athena, Code, Tutorials | Tags: , , , , , , , ,

Pages: 1 2 3 4


Theme: TheBuckmaker.com Blog Themes | The best Webhosting Plans, Eigenes Internet Radio