• 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
Cadde

OpenGL
[SOLVED] I am supposed to use Transpose but when i do...

8 posts in this topic

I have been trying many different languages revolving around DirectX and even had a stab at OpenGL but i finally settled on C# + SlimDX because it's been the most comfortable solution for me.

So, i am making a custom engine for a game i intend to make. It's not going to be a fully fledged engine but more like a support framework.

----

Anyways, the question / problem i am facing right now is that i am (supposedly?) running DirectX 11 and made a simple triangle to play with so i could continue making a camera class. I set up my world, view and projection matrices and a basic color shader.
I started getting very strange issues however as i went along. First i got the RH vs LH wrong but that got sorted (I think) and then things got really wonky.

If i Matrix.Transpose my world, view and projection matrices before sending them to the shader my screen turns completely <color of triangle>!
That is, whatever color of the triangle i assign my view is filled with it. Having tried to "solve" any matrix issues i might have had in my camera class etc for about 4 hours straight i re-built a lot of the cbuffer updating procedures thinking something went wrong there.
Out of a "fluke" i commented out the Matrix.Transpose lines and VOILA. Everything worked as it should!

So... I know i am supposed to use Matrix.Transpose with DX11 but when i do it breaks.
When i don't it works as intended.
How can this be?

Thanks in advance for any clues or information on the subject.
//Cadde
1

Share this post


Link to post
Share on other sites
Well, actually you don't have to transpose the matrices, unless your shaders expects it (which is the normal case, afaik).

Best regards!
0

Share this post


Link to post
Share on other sites
Well it turns out that i did something wrong when setting the constant buffers after all. I thought there wasn't an Effect class in SlimDX.Direct3D11 but lo and behold there was one. So i started using that and now everything behaves as it should.

Still don't need to use Matrix.Transpose though... Which is weird since i am using the LH coordinate system and haven't done anything in the shader to make the switch.
I will probably find out later as i go along...

Another question as well though. I kinda feel that i am not in (as) complete control with effects rather than VertexShader and PixelShader. I much prefer to do things as low level / non "wrappery" as possible without it becoming a groundwork nightmare.
Is there any difference in performance between using the Effect class and using VertexShader/PixelShader classes?

And what happened really? I mean, the matrices i sent to the shader where fine yet the shader misbehaved greatly and made all kinds of wonky vertex transformations. It looked like i was looking through a fisheye lens.
After i started using effects and used Effect.GetVariableByName("").AsMatrix.SetMatrix() it behaved normally.

Sorry, don't have the code i used prior but i am thinking i was updating the wrong registers or whatever. I am new at this so ya, terminology is not right.
But i would love to have a working example on how it should be done.

[CODE]
cbuffer worldBuffer : register(b0)
{
matrix worldMatrix;
}
cbuffer viewBuffer : register(b1)
{
matrix viewMatrix;
}
cbuffer projectionBuffer : register(b2)
{
matrix projectionMatrix;
}
[/CODE]

Like, how would i go at sending matrices to each of these?
The reason i split them up like that is because the projection will only be set on initialization and viewport resize, view only once per frame and world once per model / mesh.
0

Share this post


Link to post
Share on other sites
Can you show any of the vertex / pixel shader code? It may give some clues why your matrices behave in the described way.

I'm not using the effects framework at this moment so I can't help you with it.

To update a constant buffer (with out the effect framework), you'll need to create constant buffer in the program side and bind it to the desired register. The program side constant buffer should be at least the same size as defined in the shader, and the program side structure containing the data should be the same as in the shader, in order to map correct variables to correct constants.

It is a good idea to split the constant buffers. It is suggested, however, that one shader doesn't use variables from more than 4-5 different constant buffers. Apparently there may be some performance penalties. So, in that sense, view matrix and projection matrix could be in the same buffer. You'd probably want to save some shader cycles too by providing a view-projection matrix, which you'll need to update every frame.

Best regards!
0

Share this post


Link to post
Share on other sites
By default, shaders assume that matrices in constant buffers are stored in a column-major memory layout and will emit code based on that when compiling vector/matrix multiplications. You can change or work around this in 4 ways:[list=1]
[*]By declaring the matrix variable with the "row_major" modifier in your shader
[*]By passing D3D10_SHADER_PACK_MATRIX_ROW_MAJOR when compiling the shader (sorry, I don't know what the SlimDX enum equivalent of this is)
[*]By using transpose() in your shader. In most cases won't actually reorder the data in registers or anything like that, instead it will just cause the compiler to emit different code for the mul() intrinsic.
[*]By switching the order of the vector and matrix parameters that you pass to mul(). Normally you will do mul(vector, matrix), but if you do mul(matrix, vector) it's equivalent to calling transpose() on the matrix.
[/list]
If you don't do any of these things, then you'll need to pre-transpose your matrices when setting their value in the constant buffer. Historically the Effects framework has always handled doing this for you, which inevitably causes confusion when people try handling shaders manually.
1

Share this post


Link to post
Share on other sites
Ok, so i decided to make a test bed for this particular thing because like i said, i cannot come to grasps with how to use the constant buffers.
It has all been written from scratch to make a proper test this time.

Program.cs
[code]using System;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
using SlimDX;
using SlimDX.Direct3D11;
using SlimDX.DXGI;
using SlimDX.D3DCompiler;
using SlimDX.Windows;
using Device = SlimDX.Direct3D11.Device;
using Buffer = SlimDX.Direct3D11.Buffer;
using Resource = SlimDX.Direct3D11.Resource;
namespace SlimDX_Testbed
{
static class Program
{
[STAThread]
static void Main()
{
// ----------------------------------------------------------------------------------------------------
// Form, device, render target and viewport creation.
RenderForm form = new RenderForm("SlimDX Testbed");
Device device;
DeviceContext context;
SwapChain swapChain;
FeatureLevel[] featureLevels;
RenderTargetView renderTarget;
Viewport viewport;

// Width and height of form and viewport etc.
int width = 1600;
int height = 900;
form.ClientSize = new Size(width, height);
featureLevels = new[]
{
FeatureLevel.Level_11_0,
FeatureLevel.Level_10_1,
FeatureLevel.Level_10_0,
};
// Create device and swap chain.
Device.CreateWithSwapChain
(
DriverType.Hardware, DeviceCreationFlags.Debug,
featureLevels,
new SwapChainDescription
{
BufferCount = 2,
Flags = SwapChainFlags.AllowModeSwitch,
IsWindowed = true,
ModeDescription = new ModeDescription
{
Format = Format.R8G8B8A8_UNorm,
Width = width,
Height = height,
RefreshRate = new Rational(60, 1),
Scaling = DisplayModeScaling.Unspecified,
ScanlineOrdering = DisplayModeScanlineOrdering.Progressive,
},
OutputHandle = form.Handle,
SampleDescription = new SampleDescription(1, 0),
SwapEffect = SwapEffect.Discard,
Usage = Usage.RenderTargetOutput,
},
out device, out swapChain
);
// Assign the context.
context = device.ImmediateContext;
// Create the render target view.
using (Resource resource = Resource.FromSwapChain<Texture2D>(swapChain, 0))
renderTarget = new RenderTargetView
(
device, resource,
new RenderTargetViewDescription
{
Dimension = RenderTargetViewDimension.Texture2D,
Format = Format.R8G8B8A8_UNorm,
MipSlice = 0,
}
);
// Create the viewport.
viewport = new Viewport(0.0f, 0.0f, width, height, 0.0f, 1.0f);
// Assign the render targets and viewport to the context.
context.OutputMerger.SetTargets(renderTarget);
context.Rasterizer.SetViewports(viewport);

// ----------------------------------------------------------------------------------------------------
// Model
DataStream vertexData;
DataStream indexData;

Buffer vertexBuffer;
Buffer indexBuffer;
VertexBufferBinding[] binding;

int vertexCount = 8;
int indexCount = 36;
// Create the vertex data stream.
vertexData = new DataStream(12 * vertexCount, true, true);

// Create a 1x1x1 cube.
// We will be using TriangleList primitive topology here.
vertexData.Write(new Vector3(-1.0f, 1.0f, 1.0f)); // FTL 0
vertexData.Write(new Vector3( 1.0f, 1.0f, 1.0f)); // FTR 1
vertexData.Write(new Vector3(-1.0f, -1.0f, 1.0f)); // FBL 2
vertexData.Write(new Vector3( 1.0f, -1.0f, 1.0f)); // FBR 3
vertexData.Write(new Vector3(-1.0f, 1.0f, -1.0f)); // BTL 4
vertexData.Write(new Vector3( 1.0f, 1.0f, -1.0f)); // BTR 5
vertexData.Write(new Vector3(-1.0f, -1.0f, -1.0f)); // BBL 6
vertexData.Write(new Vector3( 1.0f, -1.0f, -1.0f)); // BBR 7

// Create the index data stream.
indexData = new DataStream(sizeof(UInt32) * indexCount, true, true);
// Assign the indices for 12 triangles making up the cube
indexData.WriteRange<UInt32>
(
new UInt32[]
{
// Front
0, 1, 2, // 1
2, 1, 3, // 2
// Right
1, 5, 3, // 1
3, 5, 7, // 2
// Back
5, 4, 7, // 1
7, 4, 6, // 2
// Left
4, 0, 6, // 1
6, 0, 2, // 2
// Top
4, 5, 0, // 1
0, 5, 1, // 2
// Bottom
2, 3, 6, // 1
6, 3, 7, // 2
}
);
// return the reading positions.
vertexData.Position = 0;
indexData.Position = 0;
// Create the vertex buffer.
vertexBuffer = new Buffer
(
device, vertexData,
new BufferDescription
{
BindFlags = BindFlags.VertexBuffer,
CpuAccessFlags = CpuAccessFlags.None,
OptionFlags = ResourceOptionFlags.None,
SizeInBytes = 12 * vertexCount,
StructureByteStride = 0,
Usage = ResourceUsage.Default,
}
);
// Create the index buffer.
indexBuffer = new Buffer
(
device, indexData,
new BufferDescription
{
BindFlags = BindFlags.IndexBuffer,
CpuAccessFlags = CpuAccessFlags.None,
OptionFlags = ResourceOptionFlags.None,
SizeInBytes = sizeof(UInt32) * indexCount,
StructureByteStride = 0,
Usage = ResourceUsage.Default,
}
);
// Create the vertex bidnings.
binding = new[]
{
new VertexBufferBinding(vertexBuffer, 12, 0),
};
// Assign the vertex and index buffers to the rendering pipeline.
context.InputAssembler.SetVertexBuffers(0, binding);
context.InputAssembler.SetIndexBuffer(indexBuffer, Format.R32_UInt, 0);
// ----------------------------------------------------------------------------------------------------
// Shaders.
VertexShader vertexShader;
PixelShader pixelShader;

InputElement[] elements;
InputLayout layout;
ShaderSignature inputSignature;
// Create the vertex shader.
using (ShaderBytecode bytecode = ShaderBytecode.CompileFromFile("ColorShader.fx", "VShader", "vs_5_0", ShaderFlags.Debug | ShaderFlags.EnableStrictness, EffectFlags.None))
{
inputSignature = ShaderSignature.GetInputSignature(bytecode);
vertexShader = new VertexShader(device, bytecode);
}
// Create the pixel shader.
using (ShaderBytecode bytecode = ShaderBytecode.CompileFromFile("ColorShader.fx", "PShader", "ps_5_0", ShaderFlags.Debug | ShaderFlags.EnableStrictness, EffectFlags.None))
pixelShader = new PixelShader(device, bytecode);
elements = new[]
{
new InputElement("POSITION", 0, Format.R32G32B32_Float, 0),
};
layout = new InputLayout(device, inputSignature, elements);
// Set the vertex and pixel shaders to the active rendering pipeline.
context.VertexShader.Set(vertexShader);
context.PixelShader.Set(pixelShader);
// Set the layout and primitive topology.
context.InputAssembler.InputLayout = layout;
context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;

// ----------------------------------------------------------------------------------------------------
// Matrices
Matrix world = Matrix.Identity;
Matrix view = Matrix.Identity;
Matrix projection = Matrix.PerspectiveFovRH(ToRad(45.0f), (float)width / height, 0.0f, 10000.0f);
Matrix viewProjection = view * projection;

DataStream worldMatrixData;
Buffer worldMatrixBuffer;
DataStream viewProjectionMatrixData;
Buffer viewProjectionMatrixBuffer;
// Create the world matrix data stream.
worldMatrixData = new DataStream(64, true, true);
// Create the world matrix buffer.
worldMatrixBuffer = new Buffer
(
device,
new BufferDescription
{
BindFlags = BindFlags.ConstantBuffer,
CpuAccessFlags = CpuAccessFlags.None,
OptionFlags = ResourceOptionFlags.None,
SizeInBytes = 64,
StructureByteStride = 0,
Usage = ResourceUsage.Default,
}
);
// Create the combined view and projection matrix data stream.
viewProjectionMatrixData = new DataStream(64, true, true);
// Create the combined view and projection matrix buffer.
viewProjectionMatrixBuffer = new Buffer
(
device,
new BufferDescription
{
BindFlags = BindFlags.ConstantBuffer,
CpuAccessFlags = CpuAccessFlags.None,
OptionFlags = ResourceOptionFlags.None,
SizeInBytes = 64,
StructureByteStride = 0,
Usage = ResourceUsage.Default,
}
);
Buffer[] constantBuffers = new[]
{
worldMatrixBuffer,
viewProjectionMatrixBuffer,
};
context.VertexShader.SetConstantBuffers(constantBuffers, 0, 2);
// ----------------------------------------------------------------------------------------------------
// Application loop.
Stopwatch sw = new Stopwatch();

double lastUpdate = 0.0f;
double updateFrequency = 1.0f / 20;
form.KeyDown += (o, e) =>
{
if (e.KeyCode == Keys.Escape)
form.Close();
};
MessagePump.Run
(
form,
() =>
{
if (!sw.IsRunning)
sw.Start();
// Update every <updateFrequency> seconds.
if (sw.Elapsed.TotalSeconds - lastUpdate >= updateFrequency)
{
// UPDATE()

// Set the view matrix.
// Set the "camera" (view) to 0, 0, 0 looking down the negative Z axis using 0, 1, 0 as the up vector.
view = Matrix.LookAtRH(new Vector3(0.0f, 0.0f, 0.0f), new Vector3(0.0f, 0.0f, -1.0f), Vector3.UnitY);
// Update the viewProjection matrix.
viewProjection = projection * view;

// Commented this out because it doesn't behave as it should.
// viewProjection = Matrix.Transpose(viewProjection);
// Update the matrix constant buffers.
viewProjectionMatrixData.Write(viewProjection);
viewProjectionMatrixData.Position = 0;
context.UpdateSubresource(new DataBox(0, 0, viewProjectionMatrixData), viewProjectionMatrixBuffer, 0);
lastUpdate = sw.Elapsed.TotalSeconds;
}

// RENDER()
// Set the world matrix.

// Move the cube along the z axis between -10.0f and 10.0f.
float z = (float)Math.Cos(sw.Elapsed.TotalSeconds) * 20;
world = Matrix.Translation(new Vector3(0.0f, 0.0f, z));
// Commented this out because it doesn't behave as it should.
//world = Matrix.Transpose(world);

// Update the matrix constant buffers.
worldMatrixData.Write(world);
worldMatrixData.Position = 0;
context.UpdateSubresource(new DataBox(0, 0, worldMatrixData), worldMatrixBuffer, 0);
context.ClearRenderTargetView(renderTarget, new Color4(1.0f, 0.0f, 0.1f, 0.2f));
context.DrawIndexed(indexCount, 0, 0);
swapChain.Present(0, PresentFlags.None);
}
);

// ----------------------------------------------------------------------------------------------------
// Cleanup.

// Matrix constant buffers.
if (worldMatrixBuffer != null) worldMatrixBuffer.Dispose();
if (viewProjectionMatrixBuffer != null) viewProjectionMatrixBuffer.Dispose();
if (worldMatrixData != null)
{
worldMatrixData.Close();
worldMatrixData.Dispose();
}
if (viewProjectionMatrixData != null)
{
viewProjectionMatrixData.Close();
viewProjectionMatrixData.Dispose();
}
// Shaders.
if (inputSignature != null) inputSignature.Dispose();
if (layout != null) layout.Dispose();
if (pixelShader != null) pixelShader.Dispose();
if (vertexShader != null) vertexShader.Dispose();
// Model.
if (indexBuffer != null) indexBuffer.Dispose();
if (vertexBuffer != null) vertexBuffer.Dispose();
if (indexData != null)
{
indexData.Close();
indexData.Dispose();
}

if (vertexData != null)
{
vertexData.Close();
vertexData.Dispose();
}

// Device etc.
if (renderTarget != null) renderTarget.Dispose();
if (swapChain != null) swapChain.Dispose();
if (context != null) context.Dispose();
if (device != null) device.Dispose();
if (form != null) form.Dispose();
// Happy smiley faces in yo face brah! =)
}
// Converts degrees to radians.
static float ToRad(float value)
{
return (float)(Math.PI / 180) * value;
}
}
}
[/code]

ColorShader.fx
[code]cbuffer WorldMatrixBuffer : register(cb0)
{
matrix world;
};
cbuffer ViewProjectionMatrixBuffer : register(cb1)
{
matrix viewProjection;
};
struct VS_IN
{
float3 position : POSITION;
};
struct PS_IN
{
float4 position : SV_POSITION;
};
PS_IN VShader(VS_IN input)
{
PS_IN output;
output.position = float4(input.position, 1.0);
output.position = mul(output.position, world);
output.position = mul(output.position, viewProjection);
return output;
}
float4 PShader(PS_IN input) : SV_Target
{
return float4(1.0, 1.0, 0.0, 1.0);
}[/code]

Still not getting my view and projection matrices to update or behave properly.
If i comment the "output.position = mul(output.position, viewProjection);" line i get alternating dark blue and yellow as the model moves back and forth.
If i uncomment the Matrix.Transpose lines i get the same effect except the yellow phases are shorter.

As always, really appreciate the help here!
//Cadde

EDIT: Forgot to attach the solution. Edited by Cadde
0

Share this post


Link to post
Share on other sites
Bump and update.

I converted the code in the DirectX SDK for Direct3D 11 Tutorial 7 into SlimDX code line by line. (Or at least i think i did)
Only a few minor changes/additions needed to be made considering c++ is by far superior to C# when it comes to sizeof() and other such "unsafe" and dangerous things... (UGH)

Either way, here is the conversion (Attached file) if anyone is interested in looking at it. I experience the same problems as before... Nothing get's shown on screen when using UpdateSubresource and SetConstantbuffers.
I know the code works in C++ but it doesn't do it when i convert to C# and SlimDX.

I am at a total loss here.
Thanks for any assistance!
//Cadde

EDIT:

Some additional information...

Using SlimDX January 2012 version.
.Net 2.0
Tried 32 and 64 bit SlimDX dll's for .net 2.0

It works when i use the Effect class. But doing it the "right" way doesn't work at all for me.
0

Share this post


Link to post
Share on other sites
[quote name='Mike.Popoloski' timestamp='1331650569' post='4921660']
In your vertex buffer binding you set the stride to 0 when it should actually be sizeof(SimpleVertex), which is 20.
[/quote]

DOH!
It works, you are a god and all that.
Now i have a working example to go from to fix my other ones. Thanks!

EDIT:

Ok, this is what i have learned for all this so far.
[list=1]
[*]For projection, a near plane of 0.0f does [color=#ff0000][b]NOT [/b][/color]work.
[*]One does indeed need to transpose the matrices. How i managed to get anything useful out of not transposing them i will never know. (Matrix math is still beyond me...)
[*]It helps to pay attention when you code, as Mike pointed out you have to set a proper stride.
[*]It was initially very unclear to me how to use constant buffers and the answer from Mike on [url="http://stackoverflow.com/questions/4962225/setting-up-the-constant-buffer-using-slimdx"]stackoverflow[/url] never mentioned that you had to set then to the shaders using SetConstantBuffers. This could have been realized had i known anything about D3D in the first place or by simply looking into the DX SDK examples.
[/list]
Point is, never give up and when you get stuck make sure you don't start assuming things as i did.

Now, a quick example on how to properly update constant buffers in case anyone else finds themselves in a similar situation:

A simple shader with 3 constant buffers:
[code]cbuffer WorldMatrixBuffer : register(b0)
{
matrix world;
};
cbuffer ViewMatrixBuffer : register(b1)
{
matrix view;
};
cbuffer ProjectionMatrixBuffer : register(b2)
{
matrix projection;
};
struct VS_IN
{
float4 position : POSITION;
};
struct PS_IN
{
float4 position : SV_POSITION;
};
PS_IN VShader(VS_IN input)
{
PS_IN output;
output.position = input.position;
output.position = mul(output.position, world);
output.position = mul(output.position, view);
output.position = mul(output.position, projection);
return output;
}
float4 PShader(PS_IN input) : SV_Target
{
return float4(1.0, 1.0, 0.0, 1.0);
}[/code]

This will take in a vertex buffer, multiply it's positions by the world, view and projection matrices that are defined in their own separate constant buffers.
It passes the information along down the rasterizer where each pixel is set to a solid yellow color.
One could gain a little bit of performance by multiplying the view and projection matrices before sending them to the shader and using a combined viewProjection cbuffer to reduce the number of mul() operations in the vertex shader stage. For the sake of clarity i have decided not to do this here.

The registers (b0, b1 and b2) are defined so we can assign them in code using their respective indexes (slots) and to update and assign them you need (in code):
[list=1]
[*]A Buffer with the ConstantBuffer bind, Default resource usage and in this case, no CPU access flags.
[*]A data stream to write matrix data to. A matrix is 64 bytes large (float4x4, 16 floats of 4 bytes each) thus you need to have 64 bytes of memory allocated to write to these constant buffers.
[*]A context to call UpdateSubresoruce().
[/list]
Sample code:
[code] // Create the projection matrix buffer.
projectionMatrixBuffer = new Buffer
(
device,
new BufferDescription
{
BindFlags = BindFlags.ConstantBuffer,
CpuAccessFlags = CpuAccessFlags.None,
SizeInBytes = Marshal.SizeOf(projection),
Usage = ResourceUsage.Default,
}
);
// Update the projection constant buffer.
using (DataStream data = new DataStream(Marshal.SizeOf(projection), true, true))
{
data.Write(Matrix.Transpose(projection));
data.Position = 0;
context.UpdateSubresource(new DataBox(0, 0, data), projectionMatrixBuffer, 0);
}[/code]

So first we create a buffer with the proper buffer description. Marshal.SizeOf() resides in System.Runtime.InteropServices and is used to determine the size of Types (Classes) and objects (assigned variables) which is helpful if you don't want to manually calculate the size of each constant buffer.
In this case i write the matrix directly to the stream but if your cbuffer has more than one element in it it may be useful to create a structure or class to contain all elements of the constant buffer in it before writing to the buffer.

For example:
[code] [StructLayout(LayoutKind.Sequential)]
class HerpClass
{
public Matrix world;
public Matrix view;
public Matrix projection;
}
struct HerpStruct
{
public Matrix world;
public Matrix view;
public Matrix projection;
}
...
int classSize = Marshal.SizeOf(typeof(HerpClass)); // Is 192 (64 * 3)
int structSize = Marshal.SizeOf(typeof(HerpStruct)); // Is 192 (64 * 3)[/code]

Adding any private variables to these classes will still count towards the total size of the class/structure so don't do it. (No i didn't either btw if you thought so, i just want to cover this incase someone gets any ideas.)
The reason you need "[StructLayout(LayoutKind.Sequential)]" on the class is because otherwise Marshal.SizeOf will produce an ArgumentException that reads "HerpClass cannot be marshaled as an unmanaged structure; no meaningful size or offset can be computed."
Thus, using a struct is your best option and structs and classes are pretty much the same things anyways.

Yes, you can create a constructor thus enabling you to use "new HerpClass(world, view, projection);" if you so desire.

Right, moving on...
Before you render you need to set the buffers to the vertex shader (and pixel shader where needed, they are separate) and to do that you do this:

[code] // Set the vertex and pixel shaders to the active rendering pipeline.
context.VertexShader.Set(vertexShader);
context.VertexShader.SetConstantBuffers(new Buffer[] { worldMatrixBuffer }, 0, 1);
context.VertexShader.SetConstantBuffers(new Buffer[] { viewMatrixBuffer }, 1, 1);
context.VertexShader.SetConstantBuffers(new Buffer[] { projectionMatrixBuffer }, 2, 1);
context.PixelShader.Set(pixelShader);
context.DrawIndexed(indexCount, 0, 0);
[/code]

Now, i included the Vertex/PixelShader.Set() here as well as the DrawIndexed and Present calls for clarity.
You can do it any way you like, but the gist of it all is you set them BEFORE the draw calls.
Obviously setting the projection for each mesh you draw is excessive and wastes precious cycles. You only need to set the projection when you change the shader or your projection changes. Like from a form resize or if you are zooming the view or changing the view distance.
The same applies with the view matrix, that only needs to be when the camera moves or you switch shaders.

To summarize then.[list=1]
[*]Create buffers in code that match the buffers in the shader.
[*]Write to the buffers in code when the world, view or projection matrices change using a data stream and update them in the context using UpdateSubresource.
[*]Set them to the shader using SetConstantBuffers when the shader is changed. The second argument to the function call is the index as defined in the shader file.
[/list]
Happy coding!
//Cadde

And once again, thanks for the assist! Edited by Cadde
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

  • Similar Content

    • By DaniDesu
      #include "MyEngine.h" int main() { MyEngine myEngine; myEngine.run(); return 0; } MyEngine.h
      #pragma once #include "MyWindow.h" #include "MyShaders.h" #include "MyShapes.h" class MyEngine { private: GLFWwindow * myWindowHandle; MyWindow * myWindow; public: MyEngine(); ~MyEngine(); void run(); }; MyEngine.cpp
      #include "MyEngine.h" MyEngine::MyEngine() { MyWindow myWindow(800, 600, "My Game Engine"); this->myWindow = &myWindow; myWindow.createWindow(); this->myWindowHandle = myWindow.getWindowHandle(); // Load all OpenGL function pointers for use gladLoadGLLoader((GLADloadproc)glfwGetProcAddress); } MyEngine::~MyEngine() { this->myWindow->destroyWindow(); } void MyEngine::run() { MyShaders myShaders("VertexShader.glsl", "FragmentShader.glsl"); MyShapes myShapes; GLuint vertexArrayObjectHandle; float coordinates[] = { 0.5f, 0.5f, 0.0f, 0.5f, -0.5f, 0.0f, -0.5f, 0.5f, 0.0f }; vertexArrayObjectHandle = myShapes.drawTriangle(coordinates); while (!glfwWindowShouldClose(this->myWindowHandle)) { glClearColor(0.5f, 0.5f, 0.5f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Draw something glUseProgram(myShaders.getShaderProgram()); glBindVertexArray(vertexArrayObjectHandle); glDrawArrays(GL_TRIANGLES, 0, 3); glfwSwapBuffers(this->myWindowHandle); glfwPollEvents(); } } MyShaders.h
      #pragma once #include <glad\glad.h> #include <GLFW\glfw3.h> #include "MyFileHandler.h" class MyShaders { private: const char * vertexShaderFileName; const char * fragmentShaderFileName; const char * vertexShaderCode; const char * fragmentShaderCode; GLuint vertexShaderHandle; GLuint fragmentShaderHandle; GLuint shaderProgram; void compileShaders(); public: MyShaders(const char * vertexShaderFileName, const char * fragmentShaderFileName); ~MyShaders(); GLuint getShaderProgram(); const char * getVertexShaderCode(); const char * getFragmentShaderCode(); }; MyShaders.cpp
      #include "MyShaders.h" MyShaders::MyShaders(const char * vertexShaderFileName, const char * fragmentShaderFileName) { this->vertexShaderFileName = vertexShaderFileName; this->fragmentShaderFileName = fragmentShaderFileName; // Load shaders from files MyFileHandler myVertexShaderFileHandler(this->vertexShaderFileName); this->vertexShaderCode = myVertexShaderFileHandler.readFile(); MyFileHandler myFragmentShaderFileHandler(this->fragmentShaderFileName); this->fragmentShaderCode = myFragmentShaderFileHandler.readFile(); // Compile shaders this->compileShaders(); } MyShaders::~MyShaders() { } void MyShaders::compileShaders() { this->vertexShaderHandle = glCreateShader(GL_VERTEX_SHADER); this->fragmentShaderHandle = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(this->vertexShaderHandle, 1, &(this->vertexShaderCode), NULL); glShaderSource(this->fragmentShaderHandle, 1, &(this->fragmentShaderCode), NULL); glCompileShader(this->vertexShaderHandle); glCompileShader(this->fragmentShaderHandle); this->shaderProgram = glCreateProgram(); glAttachShader(this->shaderProgram, this->vertexShaderHandle); glAttachShader(this->shaderProgram, this->fragmentShaderHandle); glLinkProgram(this->shaderProgram); return; } GLuint MyShaders::getShaderProgram() { return this->shaderProgram; } const char * MyShaders::getVertexShaderCode() { return this->vertexShaderCode; } const char * MyShaders::getFragmentShaderCode() { return this->fragmentShaderCode; } MyWindow.h
      #pragma once #include <glad\glad.h> #include <GLFW\glfw3.h> class MyWindow { private: GLFWwindow * windowHandle; int windowWidth; int windowHeight; const char * windowTitle; public: MyWindow(int windowWidth, int windowHeight, const char * windowTitle); ~MyWindow(); GLFWwindow * getWindowHandle(); void createWindow(); void MyWindow::destroyWindow(); }; MyWindow.cpp
      #include "MyWindow.h" MyWindow::MyWindow(int windowWidth, int windowHeight, const char * windowTitle) { this->windowHandle = NULL; this->windowWidth = windowWidth; this->windowWidth = windowWidth; this->windowHeight = windowHeight; this->windowTitle = windowTitle; glfwInit(); } MyWindow::~MyWindow() { } GLFWwindow * MyWindow::getWindowHandle() { return this->windowHandle; } void MyWindow::createWindow() { // Use OpenGL 3.3 and GLSL 3.3 glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); // Limit backwards compatibility glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // Prevent resizing window glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); // Create window this->windowHandle = glfwCreateWindow(this->windowWidth, this->windowHeight, this->windowTitle, NULL, NULL); glfwMakeContextCurrent(this->windowHandle); } void MyWindow::destroyWindow() { glfwTerminate(); } MyShapes.h
      #pragma once #include <glad\glad.h> #include <GLFW\glfw3.h> class MyShapes { public: MyShapes(); ~MyShapes(); GLuint & drawTriangle(float coordinates[]); }; MyShapes.cpp
      #include "MyShapes.h" MyShapes::MyShapes() { } MyShapes::~MyShapes() { } GLuint & MyShapes::drawTriangle(float coordinates[]) { GLuint vertexBufferObject{}; GLuint vertexArrayObject{}; // Create a VAO glGenVertexArrays(1, &vertexArrayObject); glBindVertexArray(vertexArrayObject); // Send vertices to the GPU glGenBuffers(1, &vertexBufferObject); glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObject); glBufferData(GL_ARRAY_BUFFER, sizeof(coordinates), coordinates, GL_STATIC_DRAW); // Dertermine the interpretation of the array buffer glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3*sizeof(float), (void *)0); glEnableVertexAttribArray(0); // Unbind the buffers glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); return vertexArrayObject; } MyFileHandler.h
      #pragma once #include <cstdio> #include <cstdlib> class MyFileHandler { private: const char * fileName; unsigned long fileSize; void setFileSize(); public: MyFileHandler(const char * fileName); ~MyFileHandler(); unsigned long getFileSize(); const char * readFile(); }; MyFileHandler.cpp
      #include "MyFileHandler.h" MyFileHandler::MyFileHandler(const char * fileName) { this->fileName = fileName; this->setFileSize(); } MyFileHandler::~MyFileHandler() { } void MyFileHandler::setFileSize() { FILE * fileHandle = NULL; fopen_s(&fileHandle, this->fileName, "rb"); fseek(fileHandle, 0L, SEEK_END); this->fileSize = ftell(fileHandle); rewind(fileHandle); fclose(fileHandle); return; } unsigned long MyFileHandler::getFileSize() { return (this->fileSize); } const char * MyFileHandler::readFile() { char * buffer = (char *)malloc((this->fileSize)+1); FILE * fileHandle = NULL; fopen_s(&fileHandle, this->fileName, "rb"); fread(buffer, this->fileSize, sizeof(char), fileHandle); fclose(fileHandle); buffer[this->fileSize] = '\0'; return buffer; } VertexShader.glsl
      #version 330 core layout (location = 0) vec3 VertexPositions; void main() { gl_Position = vec4(VertexPositions, 1.0f); } FragmentShader.glsl
      #version 330 core out vec4 FragmentColor; void main() { FragmentColor = vec4(1.0f, 0.0f, 0.0f, 1.0f); } I am attempting to create a simple engine/graphics utility using some object-oriented paradigms. My first goal is to get some output from my engine, namely, a simple red triangle.
      For this goal, the MyShapes class will be responsible for defining shapes such as triangles, polygons etc. Currently, there is only a drawTriangle() method implemented, because I first wanted to see whether it works or not before attempting to code other shape drawing methods.
      The constructor of the MyEngine class creates a GLFW window (GLAD is also initialized here to load all OpenGL functionality), and the myEngine.run() method in Main.cpp is responsible for firing up the engine. In this run() method, the shaders get loaded from files via the help of my FileHandler class. The vertices for the triangle are processed by the myShapes.drawTriangle() method where a vertex array object, a vertex buffer object and vertrex attributes are set for this purpose.
      The while loop in the run() method should be outputting me the desired red triangle, but all I get is a grey window area. Why?
      Note: The shaders are compiling and linking without any errors.
      (Note: I am aware that this code is not using any good software engineering practices (e.g. exceptions, error handling). I am planning to implement them later, once I get the hang of OpenGL.)

       
    • By KarimIO
      EDIT: I thought this was restricted to Attribute-Created GL contexts, but it isn't, so I rewrote the post.
      Hey guys, whenever I call SwapBuffers(hDC), I get a crash, and I get a "Too many posts were made to a semaphore." from Windows as I call SwapBuffers. What could be the cause of this?
      Update: No crash occurs if I don't draw, just clear and swap.
      static PIXELFORMATDESCRIPTOR pfd = // pfd Tells Windows How We Want Things To Be { sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor 1, // Version Number PFD_DRAW_TO_WINDOW | // Format Must Support Window PFD_SUPPORT_OPENGL | // Format Must Support OpenGL PFD_DOUBLEBUFFER, // Must Support Double Buffering PFD_TYPE_RGBA, // Request An RGBA Format 32, // Select Our Color Depth 0, 0, 0, 0, 0, 0, // Color Bits Ignored 0, // No Alpha Buffer 0, // Shift Bit Ignored 0, // No Accumulation Buffer 0, 0, 0, 0, // Accumulation Bits Ignored 24, // 24Bit Z-Buffer (Depth Buffer) 0, // No Stencil Buffer 0, // No Auxiliary Buffer PFD_MAIN_PLANE, // Main Drawing Layer 0, // Reserved 0, 0, 0 // Layer Masks Ignored }; if (!(hDC = GetDC(windowHandle))) return false; unsigned int PixelFormat; if (!(PixelFormat = ChoosePixelFormat(hDC, &pfd))) return false; if (!SetPixelFormat(hDC, PixelFormat, &pfd)) return false; hRC = wglCreateContext(hDC); if (!hRC) { std::cout << "wglCreateContext Failed!\n"; return false; } if (wglMakeCurrent(hDC, hRC) == NULL) { std::cout << "Make Context Current Second Failed!\n"; return false; } ... // OGL Buffer Initialization glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); glBindVertexArray(vao); glUseProgram(myprogram); glDrawElements(GL_TRIANGLES, indexCount, GL_UNSIGNED_SHORT, (void *)indexStart); SwapBuffers(GetDC(window_handle));  
    • By Tchom
      Hey devs!
       
      I've been working on a OpenGL ES 2.0 android engine and I have begun implementing some simple (point) lighting. I had something fairly simple working, so I tried to get fancy and added color-tinting light. And it works great... with only one or two lights. Any more than that, the application drops about 15 frames per light added (my ideal is at least 4 or 5). I know implementing lighting is expensive, I just didn't think it was that expensive. I'm fairly new to the world of OpenGL and GLSL, so there is a good chance I've written some crappy shader code. If anyone had any feedback or tips on how I can optimize this code, please let me know.
       
      Vertex Shader
      uniform mat4 u_MVPMatrix; uniform mat4 u_MVMatrix; attribute vec4 a_Position; attribute vec3 a_Normal; attribute vec2 a_TexCoordinate; varying vec3 v_Position; varying vec3 v_Normal; varying vec2 v_TexCoordinate; void main() { v_Position = vec3(u_MVMatrix * a_Position); v_TexCoordinate = a_TexCoordinate; v_Normal = vec3(u_MVMatrix * vec4(a_Normal, 0.0)); gl_Position = u_MVPMatrix * a_Position; } Fragment Shader
      precision mediump float; uniform vec4 u_LightPos["+numLights+"]; uniform vec4 u_LightColours["+numLights+"]; uniform float u_LightPower["+numLights+"]; uniform sampler2D u_Texture; varying vec3 v_Position; varying vec3 v_Normal; varying vec2 v_TexCoordinate; void main() { gl_FragColor = (texture2D(u_Texture, v_TexCoordinate)); float diffuse = 0.0; vec4 colourSum = vec4(1.0); for (int i = 0; i < "+numLights+"; i++) { vec3 toPointLight = vec3(u_LightPos[i]); float distance = length(toPointLight - v_Position); vec3 lightVector = normalize(toPointLight - v_Position); float diffuseDiff = 0.0; // The diffuse difference contributed from current light diffuseDiff = max(dot(v_Normal, lightVector), 0.0); diffuseDiff = diffuseDiff * (1.0 / (1.0 + ((1.0-u_LightPower[i])* distance * distance))); //Determine attenuatio diffuse += diffuseDiff; gl_FragColor.rgb *= vec3(1.0) / ((vec3(1.0) + ((vec3(1.0) - vec3(u_LightColours[i]))*diffuseDiff))); //The expensive part } diffuse += 0.1; //Add ambient light gl_FragColor.rgb *= diffuse; } Am I making any rookie mistakes? Or am I just being unrealistic about what I can do? Thanks in advance
    • By yahiko00
      Hi,
      Not sure to post at the right place, if not, please forgive me...
      For a game project I am working on, I would like to implement a 2D starfield as a background.
      I do not want to deal with static tiles, since I plan to slowly animate the starfield. So, I am trying to figure out how to generate a random starfield for the entire map.
      I feel that using a uniform distribution for the stars will not do the trick. Instead I would like something similar to the screenshot below, taken from the game Star Wars: Empire At War (all credits to Lucasfilm, Disney, and so on...).

      Is there someone who could have an idea of a distribution which could result in such a starfield?
      Any insight would be appreciated
    • By afraidofdark
      I have just noticed that, in quake 3 and half - life, dynamic models are effected from light map. For example in dark areas, gun that player holds seems darker. How did they achieve this effect ? I can use image based lighting techniques however (Like placing an environment probe and using it for reflections and ambient lighting), this tech wasn't used in games back then, so there must be a simpler method to do this.
      Here is a link that shows how modern engines does it. Indirect Lighting Cache It would be nice if you know a paper that explains this technique. Can I apply this to quake 3' s light map generator and bsp format ?
  • Popular Now