Reg__ @ Twitter Twitter Updates

reg__ Delicious Bookmarks

Facebook

Recommended Productions

FX Batch Compiler 1.1

This Windows application supports compilation of FX effect files and HLSL shader files using fxc command line compiler included in DirectX SDK. You can compile many files at time or one file with different settings.

Features:

  • Write compilation scripts in a simple language by specifying parameters for fxc.exe.
  • Compile multiple shaders at time.
  • Compile only shaders that need rebuild checked by file modification time.
  • Review success or failure, warning and error count and compiler output for every task.
  • Compile single HLSL source file with different parameters and preprocessor macros.

Date: 2011-02-09

Download:
FxBatchCompiler_1-1.exe
FxBatchCompiler-1.1-bin.zip
FxBatchCompiler-1.1-src.zip

Block Wizard

My first Flash game. Coded with FlashDevelop in ActionScript 3.

Date: 2010-04-06

CommonLib 9.0

Universal library for C++, created especially with game programmers in mind. Includes: math module (vectors, matrices, quaternions, planes, rich set of collision functions and more), string operations, conversions, smart pointers, configuration files handling, date and time module, exception class hierarchy for error handling, file system handling, stream class hierarchy, FreeList - free memory allocator, complex logger, profiler, library for threading and synchronization, tokenizer, wrappers for compression with zlib.

Language: C++. Platforms: Windows and Linux. License: GNU LGPL. Optional support for Unicode. Optional integration with D3DX. Documentation made with Doxygen.

Date: 2009-12-16

Download:
CommonLib_9_0.zip (4.92 MB)

Aqua Fish 2

Game for children - clone of PacMan. Player swims as a fish and collects points, as well as special items. Player also have to run away from enemies or destroy them. 60 maps in 6 different titlesets. Low hardware requirements. See also YouTube video. Game was published by Play Publishing company.

GameDev Calc

Calculator for game programmers. Basic data unit is a vector of 1-4 floating point numbers, which can be treated as (x,y,z,w) vector or (r,g,b,a) color. Next to basic calculations like addition, multiplication or sinus, vector operations are also available, e.g. vector normalization, conversion between degrees and radians, color conversion between RGB and HSB, finding linear an quadratic function coefficients and much more. Instead of entering single number, here you can see all the history of your calculations in form of stack and all operations are performed on that stack. Data can be entered and retrieved in different formats, like "D3DXVECTOR4(0.0f, 0.5f, 0.752f, 1.0f)" or "0xFF0080C0". Platform: Windows. Language: C#. License: GNU GPL.

Download:
GameDevCalc_1-0.zip (53.06 KB)
GameDevCalc_1-0_src.zip (50.73 KB)

RSS Feed: Adam Sawicki - Homepage (Blog) Blog

19:01
Fri
27
Jan 2012

Unusual RAII from LibVLC

RAII (Resource Acquisition Is Intialization) is a programming technique recommended in C++ for managing and freeing all kinds of resources, like allocated memory or opened files. It involves creating on the stack (by value) an object of some class that will automatically free contained resources in its destructor, at the end of the scope. That's how smart pointers work. Using it is not only needed for exception safety. It generally helps not to forget about freeing resources, like when doing return or break in the middle of the code, as well as not to duplicate this freeing code.

When working with LibVLC library, I've spotted an interesting RAII-like pattern in its source code. It is based on a local structure inside a function, which holds resources and frees in its destructor these resources that are already acquired - like this:

bool DoLotsOfStuff()
{
    struct Resources
    {
        int* array;
        FILE* file;

        ~Resources()
        {
            if( file )
                fclose( file );
            if( array )
                delete[] array;
        }
    } resources = { 0 };

    // Do some startup...

    if( CheckSomeError() )
        return false;

    resources.array = new int[1024];

    // Do some work...

    if( CheckSomeError() )
        return false;

    resources.file = fopen( fileName, "rb" );
    if( resources.file == NULL )
        return false;

    // Do some more work...

    if( CheckSomeError() )
        return false;

    // array is freed and file is closed no matter if control reached here or returned earlier.
    
    return true;
}

Comments (1) | Tags: c++

22:01
Wed
25
Jan 2012

Why do I Publish Source Code?

I like Open Source. Not in the way that some like Linux and hate Windows, but I just believe that to read or use a piece of code is often more helpful than to read only an abstract description of some algorithm. That's why I publish source of my personal projects. I can see many passionate programmers - like these from Warsztat - are not so enthusiastic to disclosing their sources. I was wondering why and here I'd like to share my thoughts on this subject, in hope I convince some of you to make your personal projects Open Source :)

First, I can hear an argument sometimes telling that you are ashamed of showing your code because you think it is bad. My answer to this can only be: you are probably wrong. Do you really believe that the "professional", "commercial" code inside companies - which is usually evolving for years, maintained by many people, modified to reflect constantly chaging requirements and written in a rush - is better than yours? Not necessarily. Or maybe you think that your code would be better if you put lots of additional comments in it, code in more object-oriented fashion or use more design patterns? Again, I don't think so.

You may also be afraid that someone looks at your code and tells that you are a beginner? Well, you may be right but... what's wrong with that? You code shows the level of your skill in programming and you shouldn't avoid showing who you really are. Remember that on the Internet there is always more beginner programmers who can learn from you than the advanced ones that could potentially make fun of your code. If you are afraid of headhunters searching the Internet, please keep in mind that when applying for a job, you may be asked to send samples of your code anyway - just as I was.

Second argument I can hear is: "But it's just my project, I don't want to make it Free Software developed by the community like Linux". That's a stereotype. Opening your sources doesn't mean the project cannot be developed by only you and will automatically be modified by some others programmers. Such thinking is just like when I hear somebody telling that programming in C++ means you extensively use OOP, while never use global variables, macros or printf. I've never received an email with a patch or other proposal for particular change in my code or collaboration in developing of my project. Even for my projects that are GNU GPL, I only get suggestions that I should add or modify some features.

If so, is it worth publishing source code anyway? My practice clearly answers yes, but not to start a community open source project. I sometimes receive emails asking about a piece of code for an algorithm I've decribed on my webpage, but I didn't provide code for. Programmers from around the world are constantly challenged with tasks they haven't done before, whether at work or at university. Their problems can be similar to yours. They Google for solutions. Your small niche place in the Web or a post on the forum can be of great help for such people.

Comments (2) | Tags: philosophy

19:31
Mon
23
Jan 2012

The Concept of Wait Cursor

When coding a GUI application, sometimes we have to conduct lengthy operation like loading or saving a file. It would be perfect if every such operation was done on separate, background thread while main thread - the one responsible for windowed interface - would show progress and allow to cancel the operation at any time. But multithreaded programming is hard, so some (not so critical and not so long) operations, like loading a configuration file, are usually done on the main thread, freezing the whole GUI. It's OK as long as the operation takes no longer than a fraction of second or several seconds - just like loading and parsing small configuration file, unless the file is located on a floppy disk :)

But it's good to show to the user that some operation is being performed so he doesn't get angry and terminate your application so quickly. Changing mouse cursor from "Normal" to "Wait" is useful here, so GUI libraries provide functionality for this.

In C#, we do it by setting Cursor property of a Form. Assuming we are inside a method of a Form:

Cursor = Cursors.WaitCursor;
// Lengthy process...
Cursor = Cursors.Default;

Just don't forget to restore default cursor no matter what's the result of the operation. try-finally section can be useful here to make the wait cursor "exception-safe". Good news is that if you wish to show a MessageBox informing user about an error that happened between setting the cursor to WaitCursor and restoring it, the cursor will change to Default automatically for the time the message window is shown.

It may be tempting to use Application.UseWaitCursor instead, but this method is worse. It requires to go back to main message loop before the cursor change takes effect, so if you set Application.UseWaitCursor = true; then do some time-consuming process inside same function and set Application.UseWaitCursor = false; at the end, user won't see changed cursor at all, whereas setting Cursor property of a form takes effect immediately.

wxWidgets library makes it easy to change cursor to "busy" - as they call it - and restore it at the end of C++ scope by creating an object of class wxBusyCursor on the stack. It will change cursor in its constructor and automatically restore it in destructor of the object.

{
    wxBusyCursor busyCursor;
    // Lengthy process...
}

MFC library also has such class. It is called CWaitCursor.

If you know the way to show wait cursor in other GUI libraries, post it in a comment.

Comments (2) | Tags: wxwidgets .net mfc gui

20:11
Mon
16
Jan 2012

Duplicated Values in C++ Enums

There is a feature in C++ and other programming languages that allows assigning particular numeric values to elements in enums, even same values to many elements. I've recently heard somebody telling that it is completely useless. I can't agree with that. Let me give an example from the source of the scripting language I recently code at home. Enum representing language operators makes use of the order of numeric values to easily determine the number of arguments for each operator. I've defined special elements in this enum to mark the beginning of operators that take one, two or three arguments.

enum OP
{
    OP_UNKNOWN,

    OP_UNARY,
    OP_NEG = OP_UNARY, // -x
    OP_BIT_NOT,        // ~x
    OP_LOG_NOT,        // !x
    OP_PRE_INC,        // ++x
    OP_PRE_DEC,        // --x
    OP_POST_INC,       // x++
    OP_POST_DEC,       // x--
    // ...

    OP_BINARY,
    OP_ADD = OP_BINARY, // x + y
    OP_SUB,             // x - y
    OP_MUL,             // x * y
    OP_DIV,             // x / y
    OP_MOD,             // x % y
    // ...

    OP_TERNARY,
    OP_CONDITIONAL = OP_TERNARY, // ?:

    NUM_OPS
};

uint GetOpNumArguments(OP op)
{
    if (op == OP_UNKNOWN) return 0;
    else if (op < OP_BINARY)  return 1;
    else if (op < OP_TERNARY) return 2;
    else if (op < NUM_OPS)    return 3;
    else return 0;
}

Comments (2) | Tags: c++

20:32
Fri
06
Jan 2012

Resizing Images to Generate Thumbnails in PHP

Some time ago I came across a problem of calculating an image size for automatically generated thumbnail for gallery script coded in PHP. It required a moment's thought, so I'd like to share this algorithm. In fact there will be two algorithms.

First code scales the image down with following rules: Destination size will not exceed given thumbnail size, but the width or height can be smaller to always preserve aspect ratio. Images smaller than thumbnail size are not magnified.

Inputs:
$src_size_x, $src_size_y - Source image size.
THUMBNAIL_SIZE_X, THUMBNAIL_SIZE_Y - Constants defining thumbnail size.

Outputs:
$dst_size_x, $dst_size_y - Destination thumbnail size.

if( $src_size_x <= THUMBNAIL_SIZE_X && $src_size_y <= THUMBNAIL_SIZE_Y )
{
  $dst_size_x = $src_size_x;
  $dst_size_y = $src_size_y;
}
else
{
  $dst_size_x = THUMBNAIL_SIZE_X;
  $dst_size_y = (int)( $src_size_y * THUMBNAIL_SIZE_X / $src_size_x );
  
  if( $dst_size_y > THUMBNAIL_SIZE_Y )
  {
    $dst_size_x = (int)( $src_size_x * THUMBNAIL_SIZE_Y / $src_size_y );
    $dst_size_y = THUMBNAIL_SIZE_Y;
  }
}

Second algorithm also helps with generating image thumbnails, but works differently. It assumes that destination image will always be of size (THUMBNAIL_SIZE_X, THUMBNAIL_SIZE_Y), while source iamge can be cropped to select only the center of the image if it has different aspect ratio than the thumbnail.

Inputs to this algorithm are the same, while outputs are:

$src_x, $src_y - Offset in the source image to begin copying from.
$src_w, $src_h - Size of the rectangle to select from cropped source image.

The code that uses this algorithm should then select from the source image a rectangle with left-top position ($src_x, $src_y), size ($src_w, $src_h) and copy it, with scaling and resampling, to the destination image with the size exactly (THUMBNAIL_SIZE_X, THUMBNAIL_SIZE_Y). That's what imagecopyresampled function from GD library can do. This algorithm does not handle cases where source image is smaller than thumbnail.

$src_h = $src_size_y;
$src_w = (int)( $src_h * THUMBNAIL_SIZE_X / THUMBNAIL_SIZE_Y );

if( $src_w <= $src_size_x )
{
  $src_x = ( $src_size_x - $src_w ) / 2;
  $src_y = 0;
}
else
{
  $src_w = $src_size_x;
  $src_h = (int)( $src_w * THUMBNAIL_SIZE_Y / THUMBNAIL_SIZE_X );
  $src_x = 0;
  $src_y = ( $src_size_y - $src_h ) / 2;
}

Comments (0) | Tags: webdev algorithms php

23:00
Wed
04
Jan 2012

Fast, Heuristic Disk Search

In March 2007 I've written an algorithm which I called "Fast, heuristic disk search" and published it in my article Szybkie, heurystyczne przeszukiwanie dysku (in Polish) on codeguru.pl. Today I went back to it, improved it a bit and I think it is a good opportunity to present it once again, this time in English :)

The problem is about searching hard disk, looking for a file or directory with particular name. Naive approach, which is used by file searching functions in programs like Total Commander, uses depth-first search, so it enters C:\, then C:\Program Files, then C:\Program Files\Adobe etc., spending lots of time in places where it probably won't find the file we are looking for.

Game developers know that searching algorithm can be significantly improved by using some heuristics that will drive algorithm towards (probably) right direction. We do it in A* pathfinding. Does a similar principle could be used also when searching for a file?

My particular problem was configuring a program with path to a console tool, let's say fxc.exe shader compiler from DirectX SDK. We could present a textbox where user has to enter path to this tool. We could also make "Browse" button with an open file dialog to simplify locating it. But wouldn't be great if program tried to locate it automatically on first run? Some installed programs store path in a registry key, but if it doesn't, we have no idea where could it be if we don't look for it among files and directories on hard disk.

My algorithm tries to locate given file or directory in given time limit by searching all given directories and their subdirectories. The improvement I propose here is inteligent management of the order in which we process these directories.

  • I start from root directories like C:\, D:\ as well as directories that are particularly interesting in our case, like Program Files.
  • I perform breadth-first search instead of depth-first search. This way I don't waste time in some deeply nested, uninteresting subdirectories.
  • I first process directories that look interesting because they contain some strings in their names that indicate we move in the right direction.

The algorithm uses two collections: a queue of directories to process and a set of already visisted directories. Here is the code in C#:

Read full entry > | Comments (0) | Tags: algorithms .net

23:53
Fri
16
Dec 2011

Parsing Numeric Constants

As a personal project I started coding a scripting language. First thing I want to do is parsing of integer and floating point numeric constants. My decision about what syntax to support is based on C++ language, but with some modifications.

Integer constant in C++ can be written as:

123    Decimal       Starting with non-zero digit
0x7B   Hexadecimal   Starting with "0x"
0173   Octal         Starting with "0"

It can also be suffixed with "u" for unsigned type and "l" for long or "ll" for "long long".

"l" makes no sense in Visual C++ because "long" type is equal to normal "int" - it has 32 bits, even in 64-bit code. So I'd prefer to use "long" as type and "ll" as suffix for 64-bit numbers.

I also don't like the octal form. First, I can't see any use of it. In the whole computer science I've seen only one situation where octal system is used: file permissions in Unix. I didn't see any single use of octal form in C++ code. On the other hand, I think preceding number with zeros shouldn't change its meaning, so the choice of "0" as prefix for octal system (instead of, for example, "0o") is very unfortunate in my opinion.

It would be much more useful if we could place binary numbers in code. Java 7 introduces such syntax with "0b" prefix. It has also another interesting feature I like - it allows underscores in numeric literals so you can make long constants more readable by grouping digits, like "0b0011_1010".

I'd like to support decimal, hexadecimal and binary numbers in my language. Regular expressions that match these are:

[0-9][0-9_]*[Uu]?[Ll]?
0[Xx][0-9A-Fa-f_]+[Uu]?[Ll]?
0[Bb][01_]+[Uu]?[Ll]?

Floating-point numbers are more sophisticated. A constant that uses all possible features might look like this:

111.222e-3f

Question is which parts are required and which are optional? It may seem that floating-point numbers and their representation in code is something obvious, but there actually are subtle differences between programming languages. "111" is obviously an integer constant, but is the presence of a dot with no digits on the left, no digits on the right, an exponent part or "f" suffix enough to for a proper floating-point constant?

111.222   C++: OK      HLSL: OK      C#: OK
111.      C++: OK      HLSL: OK      C#: Error
.222      C++: OK      HLSL: OK      C#: OK
111e3     C++: OK      HLSL: OK      C#: OK
111f      C++: Error   HLSL: Error   C#: OK

I want to support all these options, so regular expressions that match floating-point constants in my language are:

[0-9]+[Ff]
[0-9]+([eE][+-]?[0-9]+)[Ff]?
[0-9]+\.[0-9]*([eE][+-]?[0-9]+)?[Ff]?
\.[0-9]+([eE][+-]?[0-9]+)?[Ff]?

Comments (3) | Tags: languages compilers

22:46
Thu
01
Dec 2011

C++/CLI Tutorial

I finished and present my latest production - a tutorial for C++/CLI programming language. C++/CLI is an extension to C++ made by Microsoft and available in Visual Studio / Visual C++ IDE. At the same time it is one of the languages of .NET platform, next to C# or VB.NET. With it you can freely mix native and managed code, which gives extraordinary power in some applications. I've been using this language in my previous job and now I want to share this piece of knowledge. Here is the PDF document and ZIP archive with sample source code:

Comments (0) | Tags: teaching productions .net c++

Older entries >

STAT NO AD [Stat] [Admin] [STAT NO AD] [pub] [Mirror] Copyright © 2004-2012 Adam Sawicki
Copyright © 2004-2012 Adam Sawicki