DaleR

Programming, mostly.

Pre-multiplied alpha is alpha blending done correctly. It involves changing your alpha blending states, and ensuring your texture colour channels (R, G, B) are pre-multiplied (hence the name) with the alpha channel (A).

Firstly the alpha blending operations will have to be changed:

  • Set your source alpha blend to ONE (probably instead of SRCALPHA) – How solid our source texture appears depends on our alpha value alone (pre-multiplied colour channels at work here).
  • Set your destination blend to INVSRCALPHA – The more solid our texture appears, the less light we should let through from behind
// Standard fare alpha texture operations
Device.SetTextureStageState(0, TextureStage.AlphaArg1, TextureArgument.Texture);
Device.SetTextureStageState(0, TextureStage.AlphaArg2, TextureArgument.Diffuse);
Device.SetTextureStageState(0, TextureStage.AlphaOperation, TextureOperation.Modulate);

// Important
Device.SetRenderState(RenderState.AlphaBlendEnable, True);

// New alpha blending render states
Device.SetRenderState(RenderState.SourceBlend, Blend.One);
Device.SetRenderState(RenderState.DestinationBlend, Blend.InverseSourceAlpha);

The next part is loading the texture data and calculating the new colour channel values – below is a C# snippet for reading a 32-bit bitmap and performing this calculation. We take a bitmap that has been loaded into memory, iterate over each pixel in the image, calculate our new R, G and B values and save them back into the bitmap. Using SetPixel and GetPixel would be far too slow so this example locks the bitmap data and accesses the colour values directly.

[StructLayout(LayoutKind.Sequential, Pack=1)]
struct RgbaColor
{
    // Huh?! turns out PixelFormat.Format32bppArgb should
    // actually be called Format32bppBgra.
    public byte Blue;
    public byte Green;
    public byte Red;
    public byte Alpha;
}

public unsafe static class DangerousTextureLoader
{
    private static Texture LoadFromBitmap(Bitmap bitmap)
    {
        // Lock the entire bitmap for Read/Write access as we'll be reading the pixel
        // colour values and altering them in-place.
        var bmlock = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height),
                                     ImageLockMode.ReadWrite, bitmap.PixelFormat);

        // This code only works with 32bit argb images
        Debug.Assert(bmlock.PixelFormat == PixelFormat.Format32bppArgb);

        var ptr = (byte*) bmlock.Scan0.ToPointer();

        for (var y = 0; y < bmlock.Height; y++)
        {
            for (var x = 0; x < bmlock.Width; x++)
            {
                // Obtain the memory location where our pixel data resides and cast it
                // into a struct to improve sanity.
                var color = (RgbaColor*)(ptr + (y * bmlock.Stride) + (x * sizeof(RgbaColor)));

                var alphaFloat = (*color).Alpha/255.0f;

                (*color).Red = Convert.ToByte(alphaFloat * (*color).Red);
                (*color).Green = Convert.ToByte(alphaFloat * (*color).Green);
                (*color).Blue = Convert.ToByte(alphaFloat * (*color).Blue);
            }
        }

        // SlimDX specific stuff here
        var newTexture = new Texture(_device, bitmap.Width, bitmap.Height, 0,
            Usage.None, GetD3DFormat(bitmap.PixelFormat), Pool.Managed);

        // SlimDX specific stuff
        var textureLock = newTexture.LockRectangle(0, LockFlags.None);
        textureLock.Data.WriteRange(bmlock.Scan0, bmlock.Height * bmlock.Stride);

        // The bitmap lock is freed here
        bitmap.UnlockBits(bmlock);

        // SlimDX specific stuff
        newTexture.UnlockRectangle(0);
        newTexture.FilterTexture(0, Filter.Default);

        return newTexture;
    }
}

You can read a better explanation and a link to a research paper at TomF’s tech blog. He also highlights how pre-multiplied alpha will help compress your textures using DXTn formats.

I’ve been spending the past few months working on a top-down zombie survival co-op game, it’s still very much still in the workshed, but there’s plenty of screenshots over  at the zombie hq.

This game, whilst rather rudimentary in it’s presentation, is actually designed to be a realistic zombie apocalypse survival simulator. We used a team of zombie survival experts* to plan situations that would call for coordination, teamwork and an assortment of firearms and melee weapons.

* they watched Dawn of the Dead once or twice. We did try and use somebody who’d watched Resident Evil 2, but he was past saving.

Last month I finished my second exam [70-562] – this means I’m now an MCTS in developing ASP.net Web Applications(hurrah!), unfortunately I have to print my own certificate (boo!).

I got quite a lot out of reading through the self paced training kits – though they’re DULL AS HELL, and full of errata. Lots of little unknown unknowns in my knowledge of C# and ASP.net got patched, and I learnt quite a bit about stuff I have never come across in my job or in my spare time.

The big downside to taking the examinations is the interface you’re forced with using – it’s bloody awful. Lack of mouse-wheel enabled scrolling of the question and answers, 800×600 resolution, no option to switch mouse buttons for lefties (minor point but still, it was a bit frustrating), and a strange UI behaviour where, if you click a radio button of a selected answer, it deselects it! – so my belt&braces OCD make-sure-I’ve-clicked-my-correct-answer method caught me out a few times. Despite the unnecessary hurdles, I made it through – seriously Microsoft, fix the interface.

Project-wise, I’m currently working on a top-down multiplay zombie shooter – Its in it’s infancy at the moment but you can find some early screen-shots on the Daybreak project webpage.

Legume is on hold for the meantime – it’s not dead – unlike zombies – which are.

Yup version 0.2 is available – obtain it via googlecode or pypi. I’ve made substantial changes to the API and the guts so it’s completely incompatible with version 0.1.

The API documentation for Legume 0.1 is now available, and will be updated regularly as more is added.

Version 0.2?

The work on the documentation and removing the bugs listed on the google-code page is towards the next release of Legume, which in all probability will be in the new-year. Stay tuned :)

I’m currently working through the process of re-building my development server and have got to the stage of configuring the backup of my subversion repository to Amazon’s S3 storage ‘cloud’. Due to the inevitability of having to do it again in the near future I’m going to document how I keep my repository backed up, for myself, and for everyone else:

(This guide is assuming a freshly-squeezed Ubuntu 9.04 server install)

0. Obtain an AWS account if you haven’t already – making note of the Access key and Secret key, you’ll need them in step 2.

1. Install s3cmd

root@trogdor:~# sudo apt-get install s3cmd

2. Configure s3cmd and follow the onscreen instructions

root@trogdor:~# s3cmd --configure

3. Create the backup location

root@trogdor:~# mkdir /var/nightly_backup

4. Create the backup script (/var/nightly_backup/backup.sh)

#!/bin/bash
svnadmin dump --quiet /var/svn/repos | gzip > /var/nightly_backup/svn.gz
s3cmd sync /var/nightly_backup s3://backup_bucket/nightly_backup/

5. Make the backup script executable

root@trogdor:~# chmod +x /var/nightly_backup

6. Amend /etc /crontab to run the backup at a suitable time (3am in this case)

... contents of /etc /crontab ...
0 3 * * * root /var/nightly_backup/backup.sh

7. Wait until 3am, or run /var/nightly_backup/backup.sh.

8. Download an S3 browser such as S3 Browser (Windows) or Jets3t (Java)

9. Configure your S3 browser of choice to point to your AWS account to confim that the backup completed successfully.

10. ?

11. Profit.

It’s been a few months in the making, but now legume has gotten to a point that I thought it worthy of a 0.1 release. The basic feature-set is complete, so it’s in a usable state, that is if anybody can be be faced with using it yet, as at the moment there’s very little (read: nothing) in the way of documentation or user guides.

The release is available via pypi or google code, and I think that softpedia has already snapped it up.

As for the name: “It’s not a nut, it’s a legume! phew!” (Ricky Gervais, Animals).

A guide to creating a simplistic .exe python package installer:

  1. Create a setup.py file in the directory above your package directory:
    MyPythonPackage
    setup.py
    
  2. Copy the following in setup.py:
    from distutils.core import setup
    import setuptools
    import sys
    
    setup(name='MyAmazingLibrary',
        version='0.1',
        description='My Amazing Library',
        author='My Name',
        url='http://code.google.com/p/MyAmazingLibrary/',
        packages=setuptools.find_packages('.'),
        package_dir = {'':'.'},
    )
  3. Open a command prompt in the directory containing the setup.py and execute
    python setup.py bdist_wininst
    
  4. Observe how the installer appears in the newly created dist directory.

Additional Notes

  • To specify that the installer is only for a specific Python install use the –target-version option with setup.py, eg:
    python setup.py bdist_wininst --target-version=2.5
    
  • Swap bdist_wininst to bdist_msi to create a Windows Installer for your python package.

Update: for the latest code please check nevent.py in the legume google code repository

Typically, event handling in python either involves storing a function pointer and invoking it at some pointer later-on, or inheriting a base-class and overriding event handler stubs. Storing a single function pointer does not permit event handler chaining, but is the easiest method to expand upon, and acts as a replacement for event handler stubs in classes.

Expected usage of the Event handler:

def example_handler(param):
    print "1", param

example_event= Event()
example_event += example_handler
example_event('Hello!')

And the output:

1 Hello!
2 Hello!

A basic structure to the event handler class is shown below:

class EventError(Exception): pass

class Event(object):
    def __init__(self):
        self._handlers = []

    def __iadd__(self, other):
        if other not in self._handlers:
            self._handlers.append(other)
        else:
            raise EventError, \
                   'Event %s error: Handler %s is already bound' \
                   % (self, other)
        return self

    def __isub__(self, other):
        try:
            self._handlers.remove(other)
        except IndexError, e:
            raise EventError, \
                   'Event %s error: Handler %s is not bound' \
                   % (self, other)
        return self

    def __call__(self, sender, args):
        result = None
        for handler in self._handlers:
            result = handler(sender, args)
        return result

    def is_handled_by(self, handler):
        return handler in self._handlers

Note how overriding __iadd__ provides a syntax identical to C# for adding extra handlers onto the event handler chain – marvelous.

This code is actually based off the event handling used in the legume network library, see
nevent.py in the legume google code repository for the code in use, and to see any further changes.

One thing the unittest module is missing for me is a green bar of success (or a red bar of fail), so here’s one I cooked up to scratch my itch (windows only at the mo’, sorry):

import sys
import ctypes
import unittest

class GreenBarRunner(unittest.TextTestRunner):
    FOREGROUND_GREEN= 0x0A
    FOREGROUND_RED  = 0x0C
    FOREGROUND_WHITE= 0x0F
    FOREGROUND_YELLOW=0x0E

    def __init__(self, verbosity=2):
        unittest.TextTestRunner.__init__(self, verbosity=verbosity)
        STD_OUTPUT_HANDLE = -11
        self.std_out_handle = ctypes.windll.kernel32.GetStdHandle(
            STD_OUTPUT_HANDLE)

    def set_color(self, color):
        bool = ctypes.windll.kernel32.SetConsoleTextAttribute(
            self.std_out_handle, color)
        return bool

    def run(self, test):
        r = unittest.TextTestRunner.run(self, test)

        failed_count = len(r.failures)
        errored_count = len(r.errors)
        total = r.testsRun
        ok_count = total - (failed_count + errored_count)

        sys.stdout.write('\n[')
        self.set_color(self.FOREGROUND_RED)
        sys.stdout.write('#' * errored_count)
        self.set_color(self.FOREGROUND_YELLOW)
        sys.stdout.write('#' * failed_count)
        self.set_color(self.FOREGROUND_GREEN)
        sys.stdout.write('#' * ok_count)
        self.set_color(self.FOREGROUND_WHITE)
        sys.stdout.write(']\n')

Usage:

suite = unittest.TestLoader().loadTestsFromModule(example_module)
GreenBarRunner(verbosity=2).run(suite)

It’ll execute the TextTestRunner so you won’t lose the test names and stack traces and afterwards display a red/yellow/green bar:

GreenBarTestRunner

Ta-da.