• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
NathanRidley

SharpDX - How to set my vertex shader to take an instance's world matrix as input

6 posts in this topic

In the tutorials and books I've been reading so far, I've learned how to create a constant buffer and put in a world matrix as part of that buffer. The world matrix is just an identity matrix, assuming that all models in the scene are already positioned correctly in the scene. I have a simple rainbow cube and for the next step in my learning, I want to create several instances of the cube at different positions, scales and orientations. Creating the matrix for each instance is easy enough, but I'm having trouble trying to work out how to create a vertex shader that takes, as one of its inputs, the matrix representing an instance's world transform. I was under the impression that I could use any semantic name in Direct3D11, hence my use of "INSTANCE" in the code below. If I can't do that, I'm not sure what I actually need to do.

 

here's what my shader wrapper in C# looks like:

using SharpDX.D3DCompiler;
using SharpDX.Direct3D11;
using SharpDX.DXGI;
using Device = SharpDX.Direct3D11.Device;

namespace SharpDx4.Direct3D.Shaders
{
    public class DefaultVertexShader : ICompiledVertexShader
    {
        public DefaultVertexShader(Device device)
        {
            var shaderSource = Shaders.DefaultShaders;
            ShaderSignature signature;
            using (var bytecode = ShaderBytecode.Compile(shaderSource, "VShader", "vs_5_0"))
            {
                signature = ShaderSignature.GetInputSignature(bytecode);
                Shader = new VertexShader(device, bytecode);
            }
            var elements = new[]
            {
                new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0),
                new InputElement("INSTANCE", 0, Format.R32G32B32A32_Float, 0, 0, InputClassification.PerInstanceData, 1),
                new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 12, 0)
            };
            InputLayout = new InputLayout(device, signature, elements);
        }

        public VertexShader Shader { get; private set; }
        public InputLayout InputLayout { get; private set; }

        public void Dispose()
        {
            Shader.Dispose();
        }
    }
}

Here's the class I'm using to hold a model's buffer data:

using System;
using System.Linq;
using SharpDX;
using SharpDX.Direct3D11;
using SharpDx4.Direct3D.Shaders;
using SharpDx4.Game.Geometry;
using Buffer = SharpDX.Direct3D11.Buffer;

namespace SharpDx4.Direct3D
{
    public class ModelDeviceData : IDisposable
    {
        public Model Model { get; set; }
        public VertexBufferBinding VerticesBufferBinding { get; set; }
        public VertexBufferBinding InstancesBufferBinding { get; set; }
        public Buffer IndicesBuffer { get; set; }
        public ICompiledVertexShader VertexShader { get; set; }
        public ICompiledPixelShader PixelShader { get; set; }
            
        public void Dispose()
        {
            VerticesBufferBinding.Buffer.Dispose();
            InstancesBufferBinding.Buffer.Dispose();
            IndicesBuffer.Dispose();
        }

        public ModelDeviceData(Model model, Device device)
        {
            Model = model;
            var vertices = Helpers.CreateBuffer(device, BindFlags.VertexBuffer, model.Vertices);
            var instances = Helpers.CreateBuffer(device, BindFlags.VertexBuffer, Model.Instances.Select(m => m.WorldMatrix).ToArray());
            VerticesBufferBinding = new VertexBufferBinding(vertices, Utilities.SizeOf<ColoredVertex>(), 0);
            InstancesBufferBinding = new VertexBufferBinding(instances, Utilities.SizeOf<Matrix>(), 0);
            IndicesBuffer = Helpers.CreateBuffer(device, BindFlags.IndexBuffer, model.Triangles);
        }
    }
}

And here's the shader code I've been mucking with.

cbuffer ConstantBuffer : register(b0)
{
    matrix World;
    matrix View;
    matrix Projection;
}

struct VIn
{
    float4 position: POSITION;
    matrix instance: INSTANCE;
    float4 color: COLOR;
};

struct VOut
{
    float4 position : SV_POSITION;
    float4 color : COLOR;
};

VOut VShader(VIn input)
{
    VOut output;
    output.position = mul(input.position, input.instance);
    output.position = mul(output.position, View);
    output.position = mul(output.position, Projection);
    output.color = input.color;
    return output;
}

When I try to run this, the line which instantiates an instance of InputLayout throws the following exception:

 

HRESULT: [0x80070057], Module: [General], ApiCode: [E_INVALIDARG/Invalid Arguments], Message: The parameter is incorrect.

 

As a beginner, obviously I'm doing something terribly wrong. Can anyone help me work out what that is? For the record I'm aware that there is such a thing as hardware instancing, but that's, like, chapter 15 in my book and I'm only up to chapter 5 so far. Yes I'm impatient, but please humour me; I'd like to get some results doing it this way first.

0

Share this post


Link to post
Share on other sites

D3D11 in C++ should have same theory so I hope I can help you.

 

Mesh Vertices (B0) and Instance Data (B1) has to come from different buffers, as far as I can see you do have them. Next you need to bind them at once, for example B0 to slot0 and B1 to slot1. Your Input Layout has to reflect that as well, currently it says everything comes from slot0:

            var elements = new[]
            {
                new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0),
                new InputElement("INSTANCE", 0, Format.R32G32B32A32_Float, 0, 0, InputClassification.PerInstanceData, 1),
                new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 12, 0)
            };

5th argument defines in which slot data is, so you need to change it to 1 for instance data.

0

Share this post


Link to post
Share on other sites

Thanks, though that didn't fix the problem. I tried changing my shader like so:

struct VIn
{
	float4 position: POSITION;
	float4 instance0: INSTANCE0;
	float4 instance1: INSTANCE1;
	float4 instance2: INSTANCE2;
	float4 instance3: INSTANCE3;
	float4 color: COLOR;
};

VOut VShader(VIn input)
{
	VOut output;
	matrix world = { input.instance0, input.instance1, input.instance2, input.instance3 };
	output.position = mul(input.position, world);
	output.position = mul(output.position, View);
	output.position = mul(output.position, Projection);
	output.color = input.color;
	return output;
}

And my input layout code:

var elements = new[]
{
	new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0),
	new InputElement("INSTANCE0", 0, Format.R32G32B32A32_Float, 0, 0, InputClassification.PerInstanceData, 1),
	new InputElement("INSTANCE1", 1, Format.R32G32B32A32_Float, 0, 0, InputClassification.PerInstanceData, 1),
	new InputElement("INSTANCE2", 2, Format.R32G32B32A32_Float, 0, 0, InputClassification.PerInstanceData, 1),
	new InputElement("INSTANCE3", 3, Format.R32G32B32A32_Float, 0, 0, InputClassification.PerInstanceData, 1),
	new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 12, 0)
};
InputLayout = new InputLayout(device, signature, elements);

But still no luck.

0

Share this post


Link to post
Share on other sites

Number of observations:

 

When supplying a Matrix4x4 as a varying parameter, it's going to be stored as 4 float4's, so your input layout needs to reflect this (like in the second one, although breaking it explicitly is perfectly valid, but there's no reason to do so). Although it still doesn't look right, the slot and offsets are wrong, and if I understand your code correctly the order is wrong too. You have a ColoredVertex, which I assume is the Position/Color, these are in the first buffer. Then you have a second buffer with all the world matrices for each instance. It should look more like this:

var elements = new[]
{
    new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0),
    new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 12, 0, InputClassification.PerVertexData, 0),
    new InputElement("INSTANCE", 0, Format.R32G32B32A32_Float, 0, 1, InputClassification.PerInstanceData, 1),
    new InputElement("INSTANCE", 1, Format.R32G32B32A32_Float, 16, 1, InputClassification.PerInstanceData, 1),
    new InputElement("INSTANCE", 2, Format.R32G32B32A32_Float, 32, 1, InputClassification.PerInstanceData, 1),
    new InputElement("INSTANCE", 3, Format.R32G32B32A32_Float, 48, 1, InputClassification.PerInstanceData, 1),
};

Note this matches the order of your two input buffers (ColorVertex in the first buffer, the Matrix in the second buffer).

 

And your HLSL struct:

struct VIn
{
float3 position : POSITION;
float4 color : COLOR
matrix4x4 instance : INSTANCE
};

Note you're declaring the position as R32G32B32, which is a float3. Also, all the zeros in the input layout you wanted the offset to be computed automatically? That's -1 (and SharpDX has that has a static property called AppendAligned). And of course, make sure you transpose the matrices when you write them into your buffers.

 

Edit:

 

For the input layout: the semantic name you don't need to include the index, just "INSTANCE" and you set the semantic index in the input element. Missed that when I copied the code.

Edited by Starnick
1

Share this post


Link to post
Share on other sites

Hmm, so I tried to follow your advice and I'm still getting the same exception. Is there any way to get slightly more useful information from DirectX/SharpDX as to exactly what it has a problem with?

 

I've uploaded my code to GitHub to make things a bit easier. The files in question are at:

 

https://github.com/axefrog/game-dev-learning/blob/master/SharpDx4/Direct3D/Shaders/DefaultShaders.fx

https://github.com/axefrog/game-dev-learning/blob/master/SharpDx4/Direct3D/Shaders/DefaultVertexShader.cs

https://github.com/axefrog/game-dev-learning/blob/master/SharpDx4/Direct3D/ModelDeviceData.cs

0

Share this post


Link to post
Share on other sites

Turns out my parameter names were wrong. When setting up the InputLayout object, I should have named all four matrix rows just "INSTANCE".

0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0