2
votes

I am attempting to improvise some sort of hardware instancing in my game. I wish to draw multiple trees with only one Draw Call.

So far, I have set up a class which holds the model, texture, and an array of Matrices. Each matrix corresponds to a location of one tree in the game world.

I have determined to use 50 copies of object as hard coded limit within my class and my shader.

I am sure that the matrices generated are correct ones. Using Basic effect with multiple draw calls and switching out World matrices between them does yield in correct number of trees on their correct locations.

I have tried a shot-in-the dark approach:

float4x4 View;
float4x4 Projection;
float4x4 World[50];

...

VertexShaderOutput VertexShaderFunction(VertexShaderInput input)
{
    VertexShaderOutput output[50];

    for (int i=0; i<50; i++)
    {
        float4 worldPosition = mul(input.Position, World[i]);
        float4 viewPosition = mul(worldPosition, View);
        output[i].Position = mul(viewPosition, Projection);
        output[i].texCoord = input.texCoord;

        return output[i];
    }

}

To my surprise, this actually did compile, and to even greater surprise, didn't melt my GPU.

To not so big of a surprise, this draws only one tree, the first one, as the loop ends as soon as it hits the "return" keyword as any sane mind would expect it to.

I have tried my google-fu skills with googling this kind of problem, but majority of the results deal with C++ code (I'm using C# + XNA), and their approach to the problem is basically to collect all needed model's vertices and forward all that, as one huge model drawn with one World matrix position.

Is there a reliable way to draw one model using an array of World matrices on a shader, or must I collect all vertex data and batch it that way?

1
You might have better luck with this kind of rendering question on gamedev.stackexchange.com ... even if this isn't game development, the people there may deal with this kind of thing more often.Beska
OK thank you, I will try there as well :)Eudaimonium

1 Answers

0
votes

There is a whole part of XNA dedicated to hardware instancing. You will need to be able to write your own shader, which is not terribly tough to learn. You basically provide the shader with an array of matrices and one geometry mesh and the shader will the mesh once for each world matrix. This method also allows you to pass more then an alternate world matrix to each instance, such as alternate texture coordinates.