Sunday, 14 November 2010

RGB/HSV in HLSL

My present work has brought me into contact with HLSL pixel shaders. Many of these involve colour manipulations, so a fast and efficient conversions between RGB and HSV (or HSL) colour spaces would seem to be readily available and optimised to death. Strangely, this doesn't seem to be the case. Even shaders given as examples by NVIDIA and ATI are somewhat simplistic. The Wikipedia page's pseudo-code suggested the following HLSL code:

float3 HSVtoRGB(float3 HSV)
{
    float3 RGB = 0;
    float C = HSV.z * HSV.y;
    float H = HSV.x * 6;
    float X = C * (1 - abs(fmod(H, 2) - 1));
    if (HSV.y != 0)
    {
        float I = floor(H);
        if (I == 0) { RGB = float3(C, X, 0); }
        else if (I == 1) { RGB = float3(X, C, 0); }
        else if (I == 2) { RGB = float3(0, C, X); }
        else if (I == 3) { RGB = float3(0, X, C); }
        else if (I == 4) { RGB = float3(X, 0, C); }
        else { RGB = float3(C, 0, X); }
    }
    float M = HSV.z - C;
    return RGB + M;
}

float3 RGBtoHSV(float3 RGB)
{
    float3 HSV = 0;
    float M = min(RGB.r, min(RGB.g, RGB.b));
    HSV.z = max(RGB.r, max(RGB.g, RGB.b));
    float C = HSV.z - M;
    if (C != 0)
    {
        HSV.y = C / HSV.z;
        float3 D = (((HSV.z - RGB) / 6) + (C / 2)) / C;
        if (RGB.r == HSV.z)
            HSV.x = D.b - D.g;
        else if (RGB.g == HSV.z)
            HSV.x = (1.0/3.0) + D.r - D.b;
        else if (RGB.b == HSV.z)
            HSV.x = (2.0/3.0) + D.g - D.r;
        if ( HSV.x < 0.0 ) { HSV.x += 1.0; }
        if ( HSV.x > 1.0 ) { HSV.x -= 1.0; }
    }
    return HSV;
}


Even to my eyes, these looked far than optimal. However, a quick glance at the HSV graph on the Wiki page suggests an optimisation for 'HSVtoRGB' which doesn't involve branching or conditional predicates.


float3 Hue(float H)
{
    float R = abs(H * 6 - 3) - 1;
    float G = 2 - abs(H * 6 - 2);
    float B = 2 - abs(H * 6 - 4);
    return saturate(float3(R,G,B));
}

float3 HSVtoRGB(in float3 HSV)
{
    return ((Hue(HSV.x) - 1) * HSV.y + 1) * HSV.z;
}


This is particularly efficient because 'abs' and 'saturate' are "free" operations on a lot of GPU pipelines.

The reverse conversion is a bit more tricky, and if you're really obsessed with performance on Xbox360, or the like, you'll need to drop down into shader assembler to utilise the vector 'max4' instruction instead of the scalar alternatives:

float3 RGBtoHSV(in float3 RGB)
{
    float3 HSV = 0;
#if NO_ASM
    HSV.z = max(RGB.r, max(RGB.g, RGB.b));
    float M = min(RGB.r, min(RGB.g, RGB.b));
    float C = HSV.z - M;
#else
    float4 RGBM = RGB.rgbr;
    asm { max4 HSV.z, RGBM };
    asm { max4 RGBM.w, -RGBM };
    float C = HSV.z + RGBM.w;
#endif
    if (C != 0)
    {
        HSV.y = C / HSV.z;
        float3 Delta = (HSV.z - RGB) / C;
        Delta.rgb -= Delta.brg;
        Delta.rg += float2(2,4);
        if (RGB.r >= HSV.z)
            HSV.x = Delta.b;
        else if (RGB.g >= HSV.z)
            HSV.x = Delta.r;
        else
            HSV.x = Delta.g;
        HSV.x = frac(HSV.x / 6);
    }
    return HSV;
}


Although we haven't managed to get rid of the 'if' statements, they typically compile down to one conditionally predicated block and two conditional assignments.

Even against the startlingly successful optimisations produced by the current batch of HLSL compilers, these refactorings produce excellent results. The round-trip conversions (RGB-to-HSV-to-RGB) are typically three times faster than the simplistic implementations. For a pixel shader, that's not to be sneezed at.

Sunday, 7 November 2010

SketchUp to Reality

Google's SketchUp is an amazing bit of tech; but how many people use it in anger? From drawing to real-life, instead of the other way round? The work-in-progress known as Pear Tree House has actually benefited from the application of SketchUp to produce working plans for the building of a cedar and glass "loggia" (a posh word for "a lean-to without sides"). The original technical drawings and load calcs were done professionally, but I transferred the plans to SketchUp to help us get a feel for how everything fits together, and, more importantly, getting the roof lines correct.

The real-life results are surprisingly close to the plans I put together back in March 2010:


Saturday, 6 November 2010

ZX Spectrum Fine Art

I've been trawling through old demoscene, low-resolution art lately; in particular, images that can be displayed on a bog-standard Sinclair ZX Spectrum. These were limited to 256-by-192 pixels, with each 8-by-8 patch limited to only two colours from a very small palette. Most artwork of the 1980s was confined to loading screens, some very clever indeed:


But, even today, people still dabble in the arcane skills involved in getting something half-decent out of the huge constraints. As a quick exercise, I looked for an iconic painting to recreate in ZX Spectrum graphics. Something simplistic with blocks of solid colour would be ideal. I chose David Hockney's "A Bigger Splash":


Oh dear...

Sunday, 26 September 2010

Gratuitous Aphorism #3

Patient: Doctor, doctor! It hurts when I do this [Waves arm unnaturally above head]
Doctor: Well, don't do it, then!

Saturday, 4 September 2010

Samsung N220 Netbook

New hardware here at chez chilliant. I cute, little 10.1" netbook from Samsung. As is my wont, I researched the marketplace quite thoroughly, so I had to set myself a budget of £300 to prune the options. My requirements came down to:

  • Small size,
  • Good build quality,
  • Enough computing power to pursue hobby programming,
  • Ability to playback videos easily,
  • Good battery life.

The UK version of the Samsung N220 ticks all the right boxes, not least because it has a Broadcom CrystalHD Decoder built-in, unlike its foreign cousins, bizarrely. It means I can copy recorded programmes directly from my Topfield TF5800 PVR and play them back at native resolution (720x576 or 1024x576) with no lost frames and good (backlit LED) display.

The keyboard is a little under-size, so takes a lot of getting use to, particularly the tiny cursor keys, but I'm typing this (on a train) with not too much trouble.

With a battery life of supposedly up to 12 hours (I get about 7 hours with my usage profile), it's not disastrous if I forget to plug it back into the mains of an evening after a few days of commuting. Interestingly, after punting around in the Control Panel and settings, I came across a BIOS setting to only charge the 6-cell battery to 80% capacity in order to extend the lifetime of the battery pack. The very fact that this is a BIOS setting suggests that modern computers do a lot more when "switched off" than I ever imagined.

Thursday, 8 July 2010

Thursday, 17 June 2010

Unifont

I've just added a new demo: Unifont. I've tried to compose as many useful bitmap glyphs from a single, small image (128-by-64 pixels) as possible. I'm up to almost one thousand.

I've found out a lot about character sets, code pages and Unicode in general. And I was pleased to see all the glyphs from the Sinclair ZX Spectrum character set have a one-to-one mapping to Unicode code-points. But bizarrely, this isn't the case for the Sinclair ZX81:


The half, grey-shaded block elements (two above "D" and "E") and their inverses have no Unicode equivalents. Shocking!

This is obviously just a clerical error on the part of the Unicode standards team; I can't imagine them knowingly missing out glyphs from such an important character set. But I'm going to start a petition to get them instated as soon as possible:
  1. Ian Taylor
  2. ...