• 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
Gavin Williams

Constant Buffers

3 posts in this topic

Hi,

I have always used the effects framework to manage my shaders, but I decided to introduce constant buffers, as I'm about to implement geometry instancing and I figured it would give me greater control. And also it was about time I get to know how they work. But I don't think I'm doing it right as my wall sections are just disappearing. So can anyone see what I'm doing wrong ..

So here's all the relevant code :

The CBufferStruct ...

[CODE]
/// <summary>
/// CBufferStruct
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct CBufferStruct
{
public Matrix mWorld;
public Matrix mView;
public Matrix mProj;
public static readonly int SizeInBytes = Marshal.SizeOf(typeof(CBufferStruct));
}
[/CODE]

Then in the Walls constructor ...

[CODE]
// create cBuffer
BufferDescription bufferDescription = new BufferDescription()
{
BindFlags = BindFlags.ConstantBuffer,
CpuAccessFlags = CpuAccessFlags.None,
OptionFlags = ResourceOptionFlags.None,
SizeInBytes = CBufferStruct.SizeInBytes,
Usage = ResourceUsage.Default,
};
cBuffer = new Buffer(SlimDXGraphics.Device11, bufferDescription);
cBufferStruct = new CBufferStruct()
{
mProj = new Matrix(),
mView = new Matrix(),
mWorld = Matrix.Translation(new Vector3()),
//padding = new Matrix()
};
[/CODE]

Then in Walls.RenderToGBuffer() ...

[CODE]
foreach (Chunk chunk in map.VisibleChunks)
{
//if (!(chunk.Coords.X == 1 && chunk.Coords.Y == 1)) // debug code to selectively render a single terrain chunk
foreach (KeyValuePair<int, List<Point>> kVPair in chunk.wallInstanceCollectionsDictionary)
{
foreach (Point p in kVPair.Value)
{
context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(map.wall000.VertexBuffer, VertexPCNT.SizeInBytes, 0));
cBufferStruct.mProj = camera.ProjMatrix;
cBufferStruct.mView = camera.ViewMatrix;
cBufferStruct.mWorld = Matrix.Translation(new Vector3(p.X, p.Y, 0));

using (DataStream data = new DataStream(CBufferStruct.SizeInBytes, true, true))
{
data.Position = 0;
data.Write(cBufferStruct);
context.UpdateSubresource(new DataBox(0, 0, data), cBuffer, 0);
data.Dispose();
}
// now bind the constant buffer to the pipeline
context.VertexShader.SetConstantBuffer(cBuffer, 0); // not sure about this, some examples don't have it

// configure vertex shader ------------------------------------------------------------
//effect_Walls.GetVariableByName("gWorld").AsMatrix().SetMatrix(Matrix.Translation(new Vector3(p.X, p.Y, 0)));
//effect_Walls.GetVariableByName("gView").AsMatrix().SetMatrix(camera.ViewMatrix);
//effect_Walls.GetVariableByName("gProj").AsMatrix().SetMatrix(camera.ProjMatrix);
effect_Walls.GetVariableByName("gTexture").AsResource().SetResource(map.SRVWallTexture);
// draw -------------------------------------------------------------------------------
for (int pass = 0; pass < effectTech_Walls.Description.PassCount; ++pass)
{
EffectPass Pass = effectTech_Walls.GetPassByIndex(pass);
System.Diagnostics.Debug.Assert(Pass.IsValid, "Invalid EffectPass");
Pass.Apply(context);
if (map.wall000.IndexCount == 0)
context.Draw(map.wall000.VertexCount, 0);
else
context.DrawIndexed(map.wall000.IndexCount, 0, 0);
};
}
}
}
[/CODE]

Edit : And here's the shader vars ...

[CODE]
// constant buffers need to be a multiple of 16 byte in size
cbuffer gConstantBuffer : register (b0)
{
// spacial transforms
float4x4 gWorld;
float4x4 gView;
float4x4 gProj;
// padding
//float4x4 padding;
}
Texture2D<float4> gTexture : register (t0);
[/CODE]


Thanks for any help or comments. Edited by Gavin Williams
0

Share this post


Link to post
Share on other sites
You probably just need to transpose your matrices. By default shaders expect column-major matrices in constant buffers, which means transposing row-major matrices when setting them into a constant buffer. The effects framework does this for you, so a lot of people hit this bug when handling constant buffers themselves for the first time.

FYI, you can tell the compiler to expect row-major matrices using a compile flag. You can also mark the matrix with "row_major" in your HLSL code to do the same thing on a per-matrix basis.
1

Share this post


Link to post
Share on other sites
Ok, I didn't know that, thanks. So i set the compiler flag ...

[CODE]
ShaderBytecode shaderByteCode = ShaderBytecode.CompileFromFile(
"Walls/effect_Walls.fx",
"fx_5_0",
ShaderFlags.EnableStrictness | ShaderFlags.Debug | ShaderFlags.OptimizationLevel0 | ShaderFlags.PackMatrixRowMajor,
EffectFlags.None);
[/CODE]

But still nothing.

Edit : I'm removing the effects framework code just to make sure it's not hiding some mismatched binding or something.

Edit 2 : Here's the updated render code, having removed the effects framework ... but still nothing :

[CODE]
/// <summary>
public void RenderToGBuffer(Viewport viewport, ICamera camera, Map map)
{
DeviceContext context = SlimDXGraphics.Device11.ImmediateContext;

// configure input assembler ----------------------------------------------------------
context.InputAssembler.InputLayout = layout;
context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
// set the shaders
context.VertexShader.Set(vertexShader);
context.PixelShader.Set(pixelShader);

// configure rasterizer ---------------------------------------------------------------
context.Rasterizer.SetViewports(viewport);
context.Rasterizer.State = SlimDXGraphics.RasterState_Solid;

context.OutputMerger.BlendState = SlimDXGraphics.BlendState_Transparent;
foreach (Chunk chunk in map.VisibleChunks)
{
foreach (KeyValuePair<int, List<Point>> kVPair in chunk.wallInstanceCollectionsDictionary)
{
// configure input assembler specific to the wall segment shape
context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(map.wall000.VertexBuffer, VertexPCNT.SizeInBytes, 0));

foreach (Point p in kVPair.Value)
{
// set shader variables specific for each wall section (this will be unnecessary with instancing)
// and even without it, the view & proj matrices need only be set for the entire world view frame render pass
cBufferStruct.mProj = camera.ProjMatrix;
cBufferStruct.mView = camera.ViewMatrix;
cBufferStruct.mWorld = Matrix.Translation(new Vector3(p.X, p.Y, 0));

using (DataStream data = new DataStream(CBufferStruct.SizeInBytes, true, true))
{
data.Position = 0;
data.Write(cBufferStruct);
context.UpdateSubresource(new DataBox(0, 0, data), cBuffer, 0);
data.Dispose();
}
// now bind the constant buffer to the pipeline
context.VertexShader.SetConstantBuffer(cBuffer, 0);

context.PixelShader.SetShaderResource(map.SRVWallTexture, 0);

// draw -------------------------------------------------------------------------------
if (map.wall000.IndexCount == 0)
context.Draw(map.wall000.VertexCount, 0);
else
context.DrawIndexed(map.wall000.IndexCount, 0, 0);
}
}
}
[/CODE] Edited by Gavin Williams
1

Share this post


Link to post
Share on other sites
Ok, the above code is ok. It turned out that I was passing in the wrong camera. Which seems strange because it works when i use the effects framework. I'm not sure what's going on there, but the specific problem of using the cBuffer is solved. Thanks MJP for telling me about the Matrix issue. Edited by Gavin Williams
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