Posts Tagged ‘c++’

Posted by Tatyana at 2 March 2010

Category: Uncategorized

Tags: , , , , , ,

Templates in C++ are the way functions and classes operate with generic types. This allows a function or class to work on many different data types without being rewritten for each one [wiki].

Note that there is a difference between class template and a template class: class template is a template used to generate template classes. You cannot declare an object of a class template. Template class is an instance of a class template.

Here we are going to look at 3 main clas templates that are very useful in game and 3D design: Point, Vector and Matrix class templates.

Point and Point3D:

Here is how a simple Point template will look like in C++. This template is constructed to support multiple dimensions like Point2D, 3D and so on:

template <class T, int n> class Point {
protected:
	T mat[n];
	 void cp(const Point<T,n> &p)
    {
		memcpy(mat, p.mat, n*sizeof(T) );
	 }

    void cp(const T p[n])
    {
		memcpy(mat, p, n*sizeof(T) );
	}

    void cp(const T &val)
    {
		for (int i=0; i<n; i++)
			mat[i] = val;
    }

public:
	// new constructor
	Point(const T pt[n])
	{
		cp(pt);
	}

	// copy constructor
	Point(const Point<T,n> &cp)
	{
		this->cp(cp);
	}

	// default constructor
	Point()
	{
		for (int i=0; i<n; i++)
			mat[i] = 0;
	}
	virtual ~Point(void) {};
};

Templates are of great utility to programmers in C++, especially when combined with multiple inheritance and operator overloading. Here vi can add multiple operator overloading functions to our Point class template, for example addition:

        //Point + some value
	Point<T,n> &operator+=(const T &val)
    {
		for (int i=0; i<n; i++)
			mat[i] += val;

		return (*this);
    }

    //sum of two Points
    Point<T,n> &operator+=(Point<T,n> &pt)
    {
		for (int i=0; i<n; i++)
			mat[i] += pt[i];

		return (*this);
    }

A Point3D class template will look like this:

template <class T> class Point3D : public Point<T,3> {
public:
	Point3D() : Point<T,3>() {};

	Point3D(const Point3D<T> &p) : Point<T,3>(p) {
		for (int i=0; i<3; i++)
		mat[i] = p.mat[i];
	}
	Point3D( const T px, const T py, const T pz)
	{
		mat[0]=px; mat[1]=py; mat[2]=pz;
	}
};

An example of how we can use it is a motion programming:

	Point3D<float> EulerAngle(float sensitivity, double x, double y, double z) {
		return Point3D<float> (
				sensitivity*cos(z),
				sensitivity*sin(z),
				0
		);
	}

Popularity: 1% [?]

Posted by Kent at 20 December 2009

Category: Dev, c++

Tags: , , ,

Open Visual Studio command prompt.

Go to the folder you installed the source files in.

Execute configure with the wanted options.

S:\Qt\2009.04\qt>configure -debug-and-release -fast -no-webkit -opensource

This is the Qt for Windows Open Source Edition.

You are licensed to use this software under the terms of
the GNU General Public License (GPL) version 3
or the GNU Lesser General Public License (LGPL) version 2.1.

Type '3' to view the GNU General Public License version 3 (GPLv3).
Type 'L' to view the Lesser GNU General Public License version 2.1 (LGPLv2.1).
Type 'y' to accept this license offer.
Type 'n' to decline this license offer.

Do you accept the terms of the license?

Wait.

Then execute nmake and wait.

“configure” command line options

Usage: configure [-buildkey <key>]
 [-release] [-debug] [-debug-and-release] [-shared] [-static]
 [-no-fast] [-fast] [-no-exceptions] [-exceptions]
 [-no-accessibility] [-accessibility] [-no-rtti] [-rtti]
 [-no-stl] [-stl] [-no-sql-<driver>] [-qt-sql-<driver>]
 [-plugin-sql-<driver>] [-system-sqlite] [-arch <arch>]
 [-D <define>] [-I <includepath>] [-L <librarypath>]
 [-help] [-no-dsp] [-dsp] [-no-vcproj] [-vcproj]
 [-no-qmake] [-qmake] [-dont-process] [-process]
 [-no-style-<style>] [-qt-style-<style>] [-redo]
 [-saveconfig <config>] [-loadconfig <config>]
 [-qt-zlib] [-system-zlib] [-no-gif] [-qt-gif] [-no-libpng]
 [-qt-libpng] [-system-libpng] [-no-libtiff] [-qt-libtiff]
 [-system-libtiff] [-no-libjpeg] [-qt-libjpeg] [-system-libjpeg]
 [-no-libmng] [-qt-libmng] [-system-libmng] [-no-qt3support] [-mmx]
 [-no-mmx] [-3dnow] [-no-3dnow] [-sse] [-no-sse] [-sse2] [-no-sse2]
 [-no-iwmmxt] [-iwmmxt] [-direct3d] [-openssl] [-openssl-linked]
 [-no-openssl] [-no-dbus] [-dbus] [-dbus-linked] [-platform <spec>]
 [-qtnamespace <namespace>] [-qtlibinfix <infix>] [-no-phonon]
 [-phonon] [-no-phonon-backend] [-phonon-backend]
 [-no-webkit] [-webkit]
 [-no-scripttools] [-scripttools]
 [-graphicssystem raster|opengl]

Installation options:

 You may use these options to turn on strict plugin loading:

 -buildkey <key> .... Build the Qt library and plugins using the specified
 <key>.  When the library loads plugins, it will only
 load those that have a matching <key>.

Configure options:

 The defaults (*) are usually acceptable. A plus (+) denotes a default value
 that needs to be evaluated. If the evaluation succeeds, the feature is
 included. Here is a short explanation of each option:

 -release ........... Compile and link Qt with debugging turned off.
 *  -debug ............. Compile and link Qt with debugging turned on.
 +  -debug-and-release . Compile and link two Qt libraries, with and without
 debugging turned on.

 -opensource ........ Compile and link the Open-Source Edition of Qt.
 -commercial ........ Compile and link the Commercial Edition of Qt.

 -developer-build ... Compile and link Qt with Qt developer options
 (including auto-tests exporting)

 *  -shared ............ Create and use shared Qt libraries.
 -static ............ Create and use static Qt libraries.

 -ltcg .............. Use Link Time Code Generation. (Release builds only)
 *  -no-ltcg ........... Do not use Link Time Code Generation.

 *  -no-fast ........... Configure Qt normally by generating Makefiles for all
 project files.
 -fast .............. Configure Qt quickly by generating Makefiles only for
 library and subdirectory targets.  All other Makefiles
 are created as wrappers which will in turn run qmake

 -no-exceptions ..... Disable exceptions on platforms that support it.
 *  -exceptions ........ Enable exceptions on platforms that support it.

 -no-accessibility .. Do not compile Windows Active Accessibility support.
 *  -accessibility ..... Compile Windows Active Accessibility support.

 -no-stl ............ Do not compile STL support.
 *  -stl ............... Compile STL support.

 -no-sql-<driver> ... Disable SQL <driver> entirely, by default none are
 turned on.
 -qt-sql-<driver> ... Enable a SQL <driver> in the Qt Library.
 -plugin-sql-<driver> Enable SQL <driver> as a plugin to be linked to at run
 time.
 Available values for <driver>:
 mysql
 psql
 oci
 odbc
 tds
 db2
 +                         sqlite
 sqlite2
 ibase
 (drivers marked with a '+' have been detected as
 available on this system)

 -system-sqlite ..... Use sqlite from the operating system.

 -no-qt3support ..... Disables the Qt 3 support functionality.

 -no-opengl ......... Disables OpenGL functionality

 -platform <spec> ... The operating system and compiler you are building on.
 (default %QMAKESPEC%)

 -xplatform <spec> .. The operating system and compiler you are cross
 compiling to.

 See the README file for a list of supported operating
 systems and compilers.

 -qtnamespace <namespace> Wraps all Qt library code in 'namespace name {...}
 -qtlibinfix <infix> Renames all Qt* libs to Qt*<infix>

 -D <define> ........ Add an explicit define to the preprocessor.
 -I <includepath> ... Add an explicit include path.
 -L <librarypath> ... Add an explicit library path.
 -l <libraryname> ... Add an explicit library name, residing in a
 librarypath.

 -graphicssystem <sys> Specify which graphicssystem should be used.
 Available values for <sys>:
 *                         raster - Software rasterizer
 opengl - Using OpenGL accelleration, experimental!
 -help, -h, -? ...... Display this information.

Third Party Libraries:

 -qt-zlib ........... Use the zlib bundled with Qt.
 +  -system-zlib ....... Use zlib from the operating system.
 See http://www.gzip.org/zlib

 -no-gif ............ Do not compile the plugin for GIF reading support.
 +  -qt-gif ............ Compile the plugin for GIF reading support.
 See also src/plugins/imageformats/gif/qgifhandler.h

 -no-libpng ......... Do not compile in PNG support.
 -qt-libpng ......... Use the libpng bundled with Qt.
 +  -system-libpng ..... Use libpng from the operating system.
 See http://www.libpng.org/pub/png

 -no-libmng ......... Do not compile in MNG support.
 -qt-libmng ......... Use the libmng bundled with Qt.
 +  -system-libmng ..... Use libmng from the operating system.
 See See http://www.libmng.com

 -no-libtiff ........ Do not compile the plugin for TIFF support.
 -qt-libtiff ........ Use the libtiff bundled with Qt.
 +  -system-libtiff .... Use libtiff from the operating system.
 See http://www.libtiff.org

 -no-libjpeg ........ Do not compile the plugin for JPEG support.
 -qt-libjpeg ........ Use the libjpeg bundled with Qt.
 +  -system-libjpeg .... Use libjpeg from the operating system.
 See http://www.ijg.org

Qt for Windows only:

 -no-dsp ............ Do not generate VC++ .dsp files.
 *  -dsp ............... Generate VC++ .dsp files, only if spec "win32-msvc".

 -no-vcproj ......... Do not generate VC++ .vcproj files.
 *  -vcproj ............ Generate VC++ .vcproj files, only if platform
 "win32-msvc.net".

 -no-incredibuild-xge Do not add IncrediBuild XGE distribution commands to
 custom build steps.
 +  -incredibuild-xge .. Add IncrediBuild XGE distribution commands to custom
 build steps. This will distribute MOC and UIC steps,
 and other custom buildsteps which are added to the
 INCREDIBUILD_XGE variable.
 (The IncrediBuild distribution commands are only added
 to Visual Studio projects)

 -no-plugin-manifests Do not embed manifests in plugins.
 *  -plugin-manifests .. Embed manifests in plugins.

 -no-qmake .......... Do not compile qmake.
 *  -qmake ............. Compile qmake.

 -dont-process ...... Do not generate Makefiles/Project files. This will
 override -no-fast if specified.
 *  -process ........... Generate Makefiles/Project files.

 -no-rtti ........... Do not compile runtime type information.
 *  -rtti .............. Compile runtime type information.

 -no-mmx ............ Do not compile with use of MMX instructions
 +  -mmx ............... Compile with use of MMX instructions
 -no-3dnow .......... Do not compile with use of 3DNOW instructions
 +  -3dnow ............. Compile with use of 3DNOW instructions
 -no-sse ............ Do not compile with use of SSE instructions
 +  -sse ............... Compile with use of SSE instructions
 -no-sse2 ........... Do not compile with use of SSE2 instructions
 +  -sse2 .............. Compile with use of SSE2 instructions
 +  -direct3d .......... Compile in Direct3D support (experimental - see
 INSTALL for more info)
 -no-openssl ........ Do not compile in OpenSSL support
 +  -openssl ........... Compile in run-time OpenSSL support
 -openssl-linked .... Compile in linked OpenSSL support
 -no-dbus ........... Do not compile in D-Bus support
 +  -dbus .............. Compile in D-Bus support and load libdbus-1 dynamicall
 y
 -dbus-linked ....... Compile in D-Bus support and link to libdbus-1
 -no-phonon ......... Do not compile in the Phonon module
 +  -phonon ............ Compile the Phonon module (Phonon is built if a decent
 C++ compiler is used.)
 -no-phonon-backend . Do not compile the platform-specific Phonon backend-pl
 ugin
 *  -phonon-backend .... Compile in the platform-specific Phonon backend-plugin
 -no-webkit ......... Do not compile in the WebKit module
 +  -webkit ............ Compile in the WebKit module (WebKit is built if a
 decent C++ compiler is used.)
 -no-scripttools .... Do not build the QtScriptTools module.
 *  -scripttools ....... Build the QtScriptTools module.
 -arch <arch> ....... Specify an architecture.
 Available values for <arch>:
 *                         windows
 windowsce
 boundschecker
 generic

 -no-style-<style> .. Disable <style> entirely.
 -qt-style-<style> .. Enable <style> in the Qt Library.
 Available styles:
 *                         windows
 +                         windowsxp
 +                         windowsvista
 *                         plastique
 *                         cleanlooks
 *                         motif
 *                         cde
 windowsce
 windowsmobile

 -loadconfig <config> Run configure with the parameters from file configure_
 <config>.cache.
 -saveconfig <config> Run configure and save the parameters in file
 configure_<config>.cache.
 -redo .............. Run configure with the same parameters as last time.

Qt for Windows CE only:

 -no-iwmmxt ......... Do not compile with use of IWMMXT instructions
 +  -iwmmxt ............ Do compile with use of IWMMXT instructions (Qt for
 Windows CE on Arm only)
 *  -no-crt ............ Do not add the C runtime to default deployment rules
 -qt-crt ............ Qt identifies C runtime during project generation
 -crt <path> ........ Specify path to C runtime used for project generation.
 -no-cetest ......... Do not compile Windows CE remote test application
 +  -cetest ............ Compile Windows CE remote test application
 -signature <file> .. Use file for signing the target project
 -opengl-es-cm ...... Enable support for OpenGL ES Common
 -opengl-es-cl ...... Enable support for OpenGL ES Common Lite
 -opengl-es-2 ....... Enable support for OpenGL ES 2.0
 *  -phonon-wince-ds9 .. Enable Phonon Direct Show 9 backend for Windows CE

Popularity: 14% [?]

Posted by Kent at 29 November 2008

Category: Dev, Memorable, c++

Tags: , , , ,

Intro

A couple of months ago Boost came to me when I started in a new job just out of Uni, and I got impressed from day 1. Not only because in my previous experience Boost gave incredibly large errors[1] but what Boost really is and what the collection of libraries in Boost can do to easily avoid many of the pitfalls with C++ programming.

Obtaining Boost is easy, simple and free. Boost’s license explicitly states it’s free as in free beer, and you can use Boost in commercial applications without breaking the license agreement.

How to build Boost

Most libraries in Boost are header only, so you don’t have to build Boost to get started with it. However, a couple of the libraries requires to be built.

Linux

Building Boost under Linux is very easy. Supposing you have a working development environment on your computer, you’ll only have to do these steps to build Boost.

wget http://surfnet.dl.sourceforge.net/sourceforge/boost/boost_1_37_0.tar.gz
tar zxvf boost_1_37_0.tar.gz
cd boost_1_37_0
./configure
make

Then you’ll have a working Linux build of Boost.

Windows

Building Boost on Windows is a bit harder than on Linux, but it’s not rocket science :) .

  1. Download and extract Boost to some folder.
  2. Download bjam.exe and put it in the root Boost folder.
  3. Invoke bjam with stage=complete + the options from the docs.
  4. Wait
  5. Now you should have a complete set of libraries.

Example 1

Memory leak

/*
 * C++ example with a memory leak in an exception
 */

#include <iostream>

void throwErrorWithMemLeak()
{
    try
    {
        // Allocate 1kB buffer
        char *buffer = new char[1024];

        // Throw
        throw 1;

        // Free up buffer
        delete buffer;
    }
    catch(const int e)
    {
        // printf("We have a memory leak\n");
    }
}

int main(int args, char **argc)
{
    // A simple case of when an exception leads to a memory leak

    // Iterate the throwing function 1024 times, creating a 1MB memeory leak
    for (size_t i=0; i<1024; i++)
    {
        throwErrorWithMemLeak();
    }

    return 0;
}

Compile with

g++ -ggdb3 ex1_memleak.cpp -o ex1_memleak

And run it with valgrind to see the memory leak in action.

valgrind ./ex1_memleak --leak-check=full
==21831== Memcheck, a memory error detector.
==21831== Copyright (C) 2002-2007, and GNU GPL'd, by Julian Seward et al.
==21831== Using LibVEX rev 1854, a library for dynamic binary translation.
==21831== Copyright (C) 2004-2007, and GNU GPL'd, by OpenWorks LLP.
==21831== Using valgrind-3.3.1, a dynamic binary instrumentation framework.
==21831== Copyright (C) 2000-2007, and GNU GPL'd, by Julian Seward et al.
==21831== For more details, rerun with: -v
==21831==
==21831==
==21831== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 4 from 1)
==21831== malloc/free: in use at exit: 1,048,576 bytes in 1,024 blocks.
==21831== malloc/free: 2,048 allocs, 1,024 frees, 1,167,360 bytes allocated.
==21831== For counts of detected errors, rerun with: -v
==21831== searching for pointers to 1,024 not-freed blocks.
==21831== checked 158,760 bytes.
==21831==
==21831== LEAK SUMMARY:
==21831==    definitely lost: 1,048,576 bytes in 1,024 blocks.
==21831==      possibly lost: 0 bytes in 0 blocks.
==21831==    still reachable: 0 bytes in 0 blocks.
==21831==         suppressed: 0 bytes in 0 blocks.

As you can see, we’ve lost 1 megabyte of memory into the void. If this were a long running program, even small memory leaks could be disastrous if it’s allowed to grow unlimited.

No memory leak

/*
 * C++ example without a memory leak in an exception
 */

#include <iostream>

#include <boost/scoped_ptr.hpp>

void throwErrorWithMemLeak()
{
    try
    {
        // Allocate 1kB buffer in an scoped pointer
        boost::scoped_ptr<char> buffer( new char[1024] );

        // Throw
        throw 1;

        // Free up buffer (we really don't need this)
        // scoped_ptr.reset( 0 );
    }
    catch(const int e)
    {
    }
}

int main(int args, char **argc)
{
    // A simple case of when an exception doesn't lead to a memory leak

    // Iterate the throwing function 1024 times, creating a possible 1MB
    // memory leak, but scoped_ptr prevents it gracefully.
    for (size_t i=0; i<1024; i++)
    {
        throwErrorWithMemLeak();
    }

    return 0;
}

Compile with

g++ -ggdb3 -I../boost_1_37_0/ ex1_no_memleak.cpp -o ex1_no_memleak

Run with valgrind

valgrind ./ex1_no_memleak
==21902== Memcheck, a memory error detector.
==21902== Copyright (C) 2002-2007, and GNU GPL'd, by Julian Seward et al.
==21902== Using LibVEX rev 1854, a library for dynamic binary translation.
==21902== Copyright (C) 2004-2007, and GNU GPL'd, by OpenWorks LLP.
==21902== Using valgrind-3.3.1, a dynamic binary instrumentation framework.
==21902== Copyright (C) 2000-2007, and GNU GPL'd, by Julian Seward et al.
==21902== For more details, rerun with: -v
==21902==
==21902== ERROR SUMMARY: 1024 errors from 1 contexts (suppressed: 4 from 1)
==21902== malloc/free: in use at exit: 0 bytes in 0 blocks.
==21902== malloc/free: 2,048 allocs, 2,048 frees, 1,167,360 bytes allocated.
==21902== For counts of detected errors, rerun with: -v
==21902== All heap blocks were freed -- no leaks are possible.

No memory leaks!

This is only one small fraction of Boost, but yet a very powerful one. I’m in awe over Boost!

Popularity: 82% [?]

Posted by Kent at 13 January 2007

Category: Dev, Interessant, Mathematics

Tags: , , , , ,

Collision Detection

To determine if two spheres are colliding, we take the sum of the radiuses and compare it with the length from the centers of the spheres. If the lenght is smaller than the sum of the radiuses, we have a collision.

Difference vector (the length is the distance between those two spheres):
vec{d} = s1.pos - s2.pos

Then the length is computed:
distance = vec{d}.length = sqrt{vec{d}.x^2 + vec{d}.y^2 + vec{d}.z^2}

Sum of the radiuses:
sumradius = s1.radius + s2.radius

If distance<sumradius the we have a collision to take care of.

Collision Response

This is the little more trickier part, but with some basics explained, it should be pretty straight forward.

First, find the vector which will serve as a basis vector (x-axis), in an arbiary direction. It have to be normalized to get realistic results.
vec{x} = s1.pos - s2.pos
vec{x}.normalize()

Then we calculate the x-direction velocity vector and the perpendicular y-vector.
vec{v1} = s1.vel
x1 = x.dot(vec{v1})
vec{v1x} = vec{x} * x1
vec{v1y} = vec{v1} - vec{v1x}
m1 = s1.mass

Same procedure for the other sphere.
vec{x} = vec{x}*-1
vec{v2} = s2.vel
x2 = vec{x}.dot(vec{v2})
vec{v2x} = vec{x} * x2
vec{v2y} = vec{v2} - vec{v2x}
m2 = s2.mass

Then we mix and play around with some of Newtons laws to obtain a formula for the speed (in vector format) after the collision.
s1.vel = vec{v1x}{(m1-m2)/(m1+m2)} + vec{v2x}{(2*m2)/(m1+m2)} + vec{v1y}
s2.vel = vec{v1x}{(2*m1)/(m1+m2)} + vec{v2x}{(m2-m1)/(m1+m2)} + vec{v2y}

And it actually works! :)

Sample application:

Source code in subversion repository.

Popularity: 18% [?]