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

DX11
Creating a Shader class

4 posts in this topic

Hello! I am working on a class for my game engine called NXShader which will allow me to load my shaders easily like this:

NXShader(HWND*, WCHAR*, const string&, const string&);

The next thing I would like to add is the ability to dynamically set shader parameters if that makes any sense. Kind of similar to how shader parameters were handled in XNA:

Effect.Parameters["parameter"].SetValue(value); 

I want to be able to do something like this with my NXShader class:

NXShader* shader = new NXShader(nullptr, L"Texture.fx", "VS", "PS");
shader->SetParameter(parameter name, value);

But I am not actually sure about to do this. The class is currently set up like this:

Header:

struct MatrixBufferType
	{
		XMMATRIX World;
		XMMATRIX View;
		XMMATRIX Projection;
	};

	struct NEXENGINE_API NXShader
	{
		public:
			NXShader(){}
			NXShader(HWND*, WCHAR*, const string&, const string&);
			HRESULT Initialize(HWND*);
			bool SetShaderParameters(XMMATRIX&, XMMATRIX&, XMMATRIX&);
			bool SetShaderParameters(XMMATRIX&, XMMATRIX&, XMMATRIX&, NXTexture2D*);
			void Dispose();

			HRESULT CompileShaderFromFile(WCHAR*, LPCSTR, LPCSTR, ID3DBlob**);

			WCHAR* TargetProfile = L"_4_0";
			std::string VertexShaderEntry;
			std::string PixelShaderEntry;

			WCHAR* Name;
			ID3D11VertexShader* VertexShader;
			ID3D11PixelShader* PixelShader;
			ID3D11InputLayout* Layout;
			ID3D11Buffer* MatrixBuffer;
	};

Source:

#include "stdafx.h"
#include "NXShader.h"
#include <d3dcompiler.h>
#include "NXTypes.h"

#pragma comment(lib, "d3d11.lib")
#pragma comment(lib, "d3dcompiler.lib")

namespace NexEngine
{
	NXShader::NXShader(HWND* wnd, WCHAR* shaderName, const string& vsEntry, const string& psEntry)
	{
		Name = shaderName;
		VertexShaderEntry = vsEntry;
		VertexShader = 0;
		PixelShaderEntry = psEntry;
		PixelShader = 0;
		Layout = 0;
		MatrixBuffer = 0;

		HRESULT result;

		result = Initialize(wnd);
		if (FAILED(result))
			return;
	}

	HRESULT NXShader::Initialize(HWND* hwnd)
	{
		HRESULT result;
		D3D11_BUFFER_DESC matrixBufferDesc;
		ID3DBlob* pVSBlob = nullptr;
		result = CompileShaderFromFile(Name, VertexShaderEntry.c_str(), "vs_4_0", &pVSBlob);
		if (FAILED(result))
		{
			MessageBox(nullptr,
				L"The FX file cannot be compiled.  Please run this executable from the directory that contains the FX file.", L"Error", MB_OK);
			exit(0);
			return result;
		}

		result = NXGPU::GetDevice()->CreateVertexShader(pVSBlob->GetBufferPointer(), pVSBlob->GetBufferSize(), nullptr, &VertexShader);
		if (FAILED(result))
		{
			pVSBlob->Release();
			MessageBox(nullptr, L"Failed To Create Vertex Shader.", L"Error", MB_OK);
			return result;
		}

		ID3DBlob* pPSBlob = nullptr;
		result = CompileShaderFromFile(Name, PixelShaderEntry.c_str(), "ps_4_0", &pPSBlob);
		if (FAILED(result))
		{
			MessageBox(nullptr,
				L"The FX file cannot be compiled.  Please run this executable from the directory that contains the FX file.", L"Error", MB_OK);
			exit(0);
			return result;
		}

		result = NXGPU::GetDevice()->CreatePixelShader(pPSBlob->GetBufferPointer(), pPSBlob->GetBufferSize(), nullptr, &PixelShader);
		pPSBlob->Release();
		if (FAILED(result))
		{
			MessageBox(nullptr, L"Failed To Create Pixel Shader.", L"Error", MB_OK);
			return result;
		}
		pPSBlob = 0;

		result = NXGPU::GetDevice()->CreateInputLayout(NXVertex::InputElements, NXVertex::InputElementCount, pVSBlob->GetBufferPointer(),
			pVSBlob->GetBufferSize(), &Layout);


		pVSBlob->Release();
		if (FAILED(result))
		{
			MessageBox(nullptr, L"Failed To Create Input Layout.", L"Error", MB_OK);
			exit(0);
			return result;
		}
		pVSBlob = 0;
		
		matrixBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
		matrixBufferDesc.ByteWidth = sizeof(MatrixBufferType);
		matrixBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
		matrixBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
		matrixBufferDesc.MiscFlags = 0;
		matrixBufferDesc.StructureByteStride = 0;

		result = NXGPU::GetDevice()->CreateBuffer(&matrixBufferDesc, NULL, &MatrixBuffer);
		if (FAILED(result))
		{
			MessageBox(nullptr, L"Faield to Create Matrix Buffer", L"Error", MB_OK);
			exit(0);
			return result;
		}

		return S_OK;
	}

	bool NXShader::SetShaderParameters(XMMATRIX& view, XMMATRIX& world, XMMATRIX& proj)
	{
		HRESULT result;
		D3D11_MAPPED_SUBRESOURCE mappedResource;
		MatrixBufferType* dataPtr;
		unsigned int bufferNumber;

		world = XMMatrixTranspose(world);
		view = XMMatrixTranspose(view);
		proj = XMMatrixTranspose(proj);

		result = NXGPU::GetDeviceContext()->Map(MatrixBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
		if (FAILED(result))
		{
			return false;
		}

		dataPtr = (MatrixBufferType*) mappedResource.pData;

		dataPtr->World = world;
		dataPtr->View = view;
		dataPtr->Projection = proj;

		NXGPU::GetDeviceContext()->Unmap(MatrixBuffer, 0);

		bufferNumber = 0;

		NXGPU::GetDeviceContext()->VSSetConstantBuffers(bufferNumber, 1, &MatrixBuffer);

		return true;
	}

	bool NXShader::SetShaderParameters(XMMATRIX& view, XMMATRIX& world, XMMATRIX& proj, NXTexture2D* texture)
	{
		HRESULT result;
		D3D11_MAPPED_SUBRESOURCE mappedResource;
		MatrixBufferType* dataPtr;
		unsigned int bufferNumber;

		world = XMMatrixTranspose(world);
		view = XMMatrixTranspose(view);
		proj = XMMatrixTranspose(proj);

		result = NXGPU::GetDeviceContext()->Map(MatrixBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
		if (FAILED(result))
		{
			return false;
		}

		dataPtr = (MatrixBufferType*) mappedResource.pData;

		dataPtr->World = world;
		dataPtr->View = view;
		dataPtr->Projection = proj;

		NXGPU::GetDeviceContext()->Unmap(MatrixBuffer, 0);

		bufferNumber = 0;

		NXGPU::GetDeviceContext()->VSSetConstantBuffers(bufferNumber, 1, &MatrixBuffer);

		NXGPU::GetDeviceContext()->PSSetShaderResources(0, 1, &texture->Texture);

		return true;
	}

	void NXShader::Dispose()
	{
		if (MatrixBuffer)
		{
			MatrixBuffer->Release();
			MatrixBuffer = 0;
		}

		if (Layout)
		{
			Layout->Release();
			Layout = 0;
		}

		if (PixelShader)
		{
			PixelShader->Release();
			PixelShader = 0;
		}

		if (VertexShader)
		{
			VertexShader->Release();
			VertexShader = 0;
		}

		return;
	}

	HRESULT NXShader::CompileShaderFromFile(WCHAR* szFileName, LPCSTR szEntryPoint, LPCSTR szShaderModel, ID3DBlob** ppBlobOut)
	{
		HRESULT hr = S_OK;

		DWORD dwShaderFlags = D3DCOMPILE_ENABLE_STRICTNESS;
#if defined( DEBUG ) || defined( _DEBUG )
		// Set the D3DCOMPILE_DEBUG flag to embed debug information in the shaders.
		// Setting this flag improves the shader debugging experience, but still allows 
		// the shaders to be optimized and to run exactly the way they will run in 
		// the release configuration of this program.
		dwShaderFlags |= D3DCOMPILE_DEBUG;
#endif

		ID3DBlob* pErrorBlob;
		hr = D3DCompileFromFile(szFileName, nullptr, nullptr, szEntryPoint, szShaderModel,
			dwShaderFlags, 0, ppBlobOut, &pErrorBlob);
		if (FAILED(hr))
		{
			if (pErrorBlob != nullptr)
				OutputDebugStringA((char*) pErrorBlob->GetBufferPointer());
			if (pErrorBlob) pErrorBlob->Release();
			return hr;
		}
		if (pErrorBlob) pErrorBlob->Release();

		return S_OK;
	}
} 

I would like to remove the SetShaderParameter bool methods above, and replace them with something like this:

void SetParameter(const string&, float);
void SetParameter(const string&, int);
void SetParameter(const string&, XMMatrix*)
void SetParameter...etc.

This would really help me out. The class can currently compile and load Pixel/Vertex shaders correctly:

kum0.png

 

But I seem to limited to setting parameters by creating a bunch of constant buffers for each cbuffer in my shaders. Is there a way to do what I am trying to do in DX11? Thanks! smile.png

Edited by KoldGames
0

Share this post


Link to post
Share on other sites
Sure, there's a way. You could create a mapping from string to a structure member.

There's really no reason to go that route though. Event the DX9 effects framework essentially uses cbuffers on the back end, with the strings just being mappings.

You really shouldn't be using strings for this though, its not a particularly efficient idea.
1

Share this post


Link to post
Share on other sites

Hey, thanks for the replies!

Sure, there's a way. You could create a mapping from string to a structure member.

There's really no reason to go that route though. Event the DX9 effects framework essentially uses cbuffers on the back end, with the strings just being mappings.

You really shouldn't be using strings for this though, its not a particularly efficient idea.

What would you recommend to replace the strings? Is WCHAR or char good?

 

The way shader constants have changed from D3D9 to 11, and the fact that D3D, even in version 9, never really had per-shader constants (they were always global state, the old Effects framework just never exposed that well), means that you're probably better off separating your constants from your shaders, otherwise you've got an artificial coupling that's only going to hinder you as you go forward.

 

As an example, what would you propose to do if you had two different vertex shaders but they both needed to use the same matrices?  Your current design doesn't handle this requirement, instead forcing you to upload the matrices twice.  However, D3D itself doesn't (and never did) require you to do that.

 

If what you really want is just a D3D11 version of the old Effects framework (which it looks like is what you're designing towards), there is one provided with the DirectX SDK (I don't know about newer Windows SDK versions) in source-code-only form; you'll find it in C:\Program Files (x86)\Microsoft DirectX SDK (June 2010)\Samples\C++\Effects11 and you can compile it and link to it.

 

Personally I've just got a much more lightweight shader class that just contains creation and destruction code for the types of shaders (and input layouts) I'm interested in, using a hash of the bytecode and a global shader cache to avoid creating the same object more than once, some simple state change management, and otherwise I handle cbuffer updates completely separately and via the raw API.

Hey! Thanks for the info! It is really helpful. smile.png

Edited by KoldGames
0

Share this post


Link to post
Share on other sites

The way I do it in my engine is that I add meta data for my shaders, describing the size of the constant, it's register, it's name, whatever information I may need. Then in my game I have a SetUniform call that takes in a name or an enum that corresponds to known constants, a void*, and the size of the uniform. Then I map the name/id to a global shader cache, and apply it from there. It takes  a bit of setup to work, but that's all handled by tools now. And I can create custom uniforms without having to cram it into some sort of pre-defined register index.

1

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 lonewolff
      Hi Guys,
      I am just wondering if it is possible to acquire the address of the backbuffer if an API (based on DX11) only exposes the 'device' and 'context' pointers?
      Any advice would be greatly appreciated
    • By MarcusAseth
      bool InitDirect3D::Init() { if (!D3DApp::Init()) { return false; } //Additional Initialization //Disable Alt+Enter Fullscreen Toggle shortkey IDXGIFactory* factory; CreateDXGIFactory(__uuidof(IDXGIFactory), reinterpret_cast<void**>(&factory)); factory->MakeWindowAssociation(mhWindow, DXGI_MWA_NO_WINDOW_CHANGES); factory->Release(); return true; }  
      As stated on the title and displayed on the code above, regardless of it Alt+Enter still takes effect...
      I recall something from the book during the swapChain creation, where in order to create it one has to use the same factory used to create the ID3D11Device, therefore I tested and indeed using that same factory indeed it work.
      How is that one particular factory related to my window and how come the MakeWindowAssociation won't take effect with a newly created factory?
      Also what's even the point of being able to create this Factories if they won't work,?(except from that one associated with the ID3D11Device) 
    • By ProfL
      Can anyone recommend a wrapper for Direct3D 11 that is similarly simple to use as SFML? I don't need all the image formats etc. BUT I want a simple way to open a window, allocate a texture, buffer, shader.
    • By lucky6969b
      Q1:
      Since there is no more fixed pipeline rendering in DX11, for every part of rendering in DX11, do I need to create a brand-new vertex shader and pixel shader... or at least I have to find one relevant online. If you work on skinned meshes and other effects originally worked in DX9 fixed pipeline, do I have to rework everything by now?
       
      Q2:
      For assimp, if it originally was designed for DX9, like it is coupled to a DX9 device for creating meshes and materials etc. Do I have to add in the DX11 device in the assimp, or can I just leave the assimp to remain in DX9 and after the meshes are loaded, I just convert the vertex buffers and index buffers into DX11 buffers?
      Thanks
      Jack
    • By MarcusAseth
      This header is mentioned in the book I'm reading but there is no documentation on msdn... Is it like an... outdated and abandoned header?
      If so, what's the current default/recomended library for handling errors with directX?
  • Popular Now