Search code examples
c#c++xnahlsl

HLSL: Returning an array of float4?


I have the following function in HLSL:

float4[] GetAllTiles(float type) {
    float4 tiles[128];
    int i=0;

    [unroll(32768)] for(int x=0;x<MapWidth;x++) {
        [unroll(32768)] for(int y=0;y<MapHeight;y++) {

            float2 coordinate = float2(x,y);
            float4 entry = tex2D(MapLayoutSampler, coordinate);
            float entryType=GetTileType(entry);
            if(entryType == type) {
                tiles[i++]=entry;
            }

        }
    }

    return tiles;
}

However, it says that it can't define a return type of float4[]. How do I do this?


Solution

  • In short: You can't return an array of floats defined in the function in HLSL.

    HLSL code (on the GPU) is not like C code on the CPU. It is executed concurrently on many GPU cores.

    HLSL code gets executed at every vertex (in the vertex shader) or every at pixel (in the pixel shader). So for every vertex you give the GPU, this code will be executed.

    This HLSL introduction should give you a sense of how a few lines of HLSL code get executed on every pixel, producing a new image from the input:

    http://www.neatware.com/lbstudio/web/hlsl.html

    In your example code, you are looping over the entire map, which is probably not what you want to do at all, as the function you posted will be executed at every pixel (or vertex) given in your input.

    Transferring your logic from the CPU to the GPU via HLSL code can be very difficult, as GPUs are not currently designed to do general purpose computation. The task you are trying to do must be very parallel, and if you want it to be fast on the GPU, then you need to express the problem in terms of drawing images, and reading from textures.

    Read the tutorial I linked to get started with HLSL :)