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

Whats the shader data a Material class holds?

22 posts in this topic

Ive been cycling between crister ericson, hodgman and spiro posts, trying to wrap my head on the subject "rendering system".
Im stuck right now on what exactly a material class does.
 
A material references a shader "resource", with means a combination of shaders programs (vs, ps, etc.)
 
This shader resources a material holds, is it a single permutation of a shader, or a material can access all of the permutation of the shader it references?
 
Say I have a cube with a material, if my cube changes environment, so that the number of lights change, do I need to just use another permutation on the material(material holds a permutation info), the shader itself updates its permuation info(so all material with this shader now will use the new permutation),  do I need to change the cube material (another material with the right permutation)? or do I need to update the shader on the material(so the material got a new shader)?
 
Also, when is that a material finds out what cbuffers slots to use? This is shader stuff, say you know what cbuffers a shader use cause youre using reflection at asset loading time, materials comes from models right? Not from HLSL files..I fail to see when things get linked up (shader permutations compilation, models loading, environment lighting info being updated to shader cbuffers..)
0

Share this post


Link to post
Share on other sites

Cannot comment on the cbuffer slot issue, but I'd recommend that the material holds a reference to a "base" shader, from which permutations can be built/requested, and the rendering system chooses, during runtime, the actual shader permutation based on the object's lighting environment.

 

1

Share this post


Link to post
Share on other sites

This is how I do it (this is based on Hodgman posts):

 

At asset build time I assign each material a set of base "shader resources" (one for each pass the material should be drawn in).

 

The material chooses the right permutation of each "shader resource" based on what it needs and then, using the correct shader permutation, it finds out which cbuffers/textures slots to use using shader reflection.

 

A material will contain a bitset where each bit specifies a shader feature that the material needs and the Renderer will use that bitset to choose the right shader permutation every time the material is used. So you can change this list to change the material appearance by changing the bitset. 

 

The number of lights or other external factors shouldn't modify the material, after all they're external factors.

So in my engine I have a class called Actor (basically a Model instance), that holds a pointer to a Model and vectors like position, rotation, etc.

The Actor also has a bitset, like the Materials, that will dynamically be updated based on the Actor/lights positions, so the Renderer will get the bitsets from Material/Actor/Geometry and other classes in order to choose the right shader permutation.

Edited by TiagoCosta
2

Share this post


Link to post
Share on other sites

Do multiple pass  materiasl end up on the render queue as totally independent draw calls-stategroups pairs ? I mean, will they be sorted in a way that a pass will be executed, than lots of object passes can be executed, than the second pass can be executed later, is that right?

 

On crister ericsons theres a material/pass key, so I assume all objects with the same material have their pass 1 executed in a row, than all pass 2 are executed later, but then,

how things like shadow map creation works? Shadow map is a global thing right(not a material thing, objects with different materials will need a shadow too)? So I dont see how it can work with that crister ericson "per material pass sorting", as objects of a material will be drawn before object with different materials, that also cast shadows, so material 1 objects will not be affected by shadows from material 2...get what I mean? I believe all objects that cast shadows, material independent, must be sorted so that all shadow mapping creation pass is executed first. Is my logic correct?

Edited by Icebone1000
0

Share this post


Link to post
Share on other sites

You can consider shadow map a whole independent scene view to be rendered (different camera, different rendertarget, different culling) so to me it seems most logical that it would also have its own dedicated renderqueue. There would be higher-level logic in the renderer which renders the shadow map renderqueues first.

 

But yes, generally multipass materials would get broken down into independent drawcalls just like you describe.

1

Share this post


Link to post
Share on other sites

As you can tell, there is no real definition of a material, it's just a collection of data that describes how to draw your geometry. Everybody has their own ways of implementing the material. For instance, mine is responsible for matching MaterialParameters (diffuseColor, specularColor, randomAttributes), to shader constants, and for binding textures. I have a unique material per shader, and per pass.

0

Share this post


Link to post
Share on other sites

I do all of this in the tools, during "data compilation" time.
First I compile the shaders, which tells me their cbuffer layouts (which variables are in which cbuffer structures, and which slots/stagse each structure should be bound to).
Then I parse the artists material descriptions (which for me, are in the COLLADA files), and use the above structure information to create byte-arrays of cbuffer data.
Then I create binding commands, to bind these structures to the appropriate slots/stages (e.g. bind cbuffer structure #1 to pixel shader slot #3).
Then I save these cbuffers and binding commands into a "material file", which contains links to other resource files (textures, shaders, etc) and contains StateGroups and cbuffers to be used as "materials".

Are your binding commands immutable? You create it once and they never change/get updated (like a binding command changing the slot it binds to)?

 

considering something like this:

stategroup environment - bind lights cbuffer (needs current shader slot info)
stategroup camera - bind viewport, bind render target, bind view projection cbuffer (needs current shader slot info)
drawable{
    stategroup material - bind blend state, bind shaders, bind textures (needs its shader slot info), bind color cbuffer (needs its shader slot info), bind sampler (needs its shader slot info)
    state bind world cbuffer (needs current shader slot info)
}

 

My difficult is managing the binding commands. Say I have 2 drawables with different materials, each material have different shaders with different cbuffers layout (consider different slots usage only..).

I cant hold binding commands for none of these groups (except the material group), because they change depending on the current shader/material bound, so Id have to create the commands at runtime based on the drawable material, this sounds terrible. So if Id only update the commands, it would look like:

drawable::draw( renderQueue, envLights, camera, whatever external thing dependent on the godam shader ){

 states = m_material.GetBindsForEnvLights(envLights);//that would update an existing bind command //or material.shader.Get.. // or material.CreateBindsForEnvLights(envLights),
 states += m_material.GetBindsForCamera(camera);
 states += m_material.GetItsOwnBinds();
 states += m_material.GetBindsForInstance(world);

renderQueue.submit( states, m_drawcall, m_drawableSortKey); //sortKey: camera, material...yupi
}

Thats what I can think of..

Keep in mind that my current batch tests are also comparing the bind commands addresses, with means duplicated bind commands will not be batched out..So I think I need to use existing binds always, but I also need to change them per "material current bound", witch doesnt make any sense..

if I update a existing bind command, it will update for all previous drawables already submited onto the queue, since its the same..Wich means I cant have, for example, 2 drawables with the same material but different  world/light/camera cbuffer binding submitted on the queue.

The last solution would have a different bind command for all possible combination : cameras x materials, lights x materials, drawable worlds x materials..Unless I start to compare by operator == on the bind commands batch tests..

 

The only thing I can think is defining obligatory cbuffers layouts: "drawable", "camera", "environment", "other"..

That way I dont depend on the shader bound anymore...but I know its lame. =_=

Am I too off? Perhaps I should go lame for start..

 

(note that Im rellying on virtuals(instead of that sinister blob thing) and not doing anything data driven for simplicity)

0

Share this post


Link to post
Share on other sites

My difficult is managing the binding commands. Say I have 2 drawables with different materials, each material have different shaders with different cbuffers layout (consider different slots usage only..).

(Are you using shader permutations? If not you should consider start using them.)

Different materials simply use different permutations of the same shader. So make the cbuffers layous the same in all permutations. (Check the 2nd paragraph of Hodgman reply to that topic).

 

Sure you'll be binding some data that is not needed in some cases, but you won't have to deal with the complexity that a more dynamic system would introduce. Plus number of bound constant buffers will be the same, so go with the "lame" approach and only try to optimize if you find that it's hurting performance.
 

0

Share this post


Link to post
Share on other sites

My difficult is managing the binding commands. Say I have 2 drawables with different materials, each material have different shaders with different cbuffers layout (consider different slots usage only..).

(Are you using shader permutations? If not you should consider start using them.)

Different materials simply use different permutations of the same shader. So make the cbuffers layous the same in all permutations. (Check the 2nd paragraph of Hodgman reply to that topic).

 

Sure you'll be binding some data that is not needed in some cases, but you won't have to deal with the complexity that a more dynamic system would introduce. Plus number of bound constant buffers will be the same, so go with the "lame" approach and only try to optimize if you find that it's hurting performance.
 

I meant materials with completely different shader effects, not just different permutations for the same effect.

In my understanding, you`re not meant to use the same shader for all objects. Do you do something like different queues for different shaders?

Edited by Icebone1000
0

Share this post


Link to post
Share on other sites
This is an interesting thread - I'm getting to my material system very soon - you guys keep mentioning the 'cbuffer' - what exactly is that?

Apologies for piggy backing this one but it might help me and others to understand some of the terminology. Also, what's a 'state group'?

Thanks
0

Share this post


Link to post
Share on other sites

This is an interesting thread - I'm getting to my material system very soon - you guys keep mentioning the 'cbuffer' - what exactly is that?

Apologies for piggy backing this one but it might help me and others to understand some of the terminology. Also, what's a 'state group'?

Thanks

cbuffer(constant buffer) is how hlsl shader language handles variables (the ones that will be constant during all vertex/pixel/any shader program processing, like world view projection matrices, color, anything you set for a specific vertex buffer and a draw call), theyr like a struct you create in your shader file, bind to a specific register "index". Check dx documentation for more details.

 

State group is specific to Hodgman rendering system, it refers to a list of "pipeline states setters", commands that set things like cbuffers, blend state, shaders, texture..etc.

check this post:

http://www.gamedev.net/topic/605065-renderqueue-design-theory-and-implementation/#entry4828468

 

One can gather a great amount of info by just following Hodgman footprints on these forums.

0

Share this post


Link to post
Share on other sites

If you're in OpenGL land, cbuffers are called UBOs (a buffer object that holds uniforms).

 

State group is specific to Hodgman rendering system, it refers to a list of "pipeline states setters", commands that set things like cbuffers, blend state, shaders, texture..etc

Yeah I use the concept in my engine (described above), but I picked it up numerous other engines that also used the same idea.

Also, in D3D9/10, there are API level "state blocks", which are similar (a container for certain Set<State> commands), but I don't use these wink.png

0

Share this post


Link to post
Share on other sites

Thanks guys..

 

cbuffer(constant buffer) is how hlsl shader language handles variables (the ones that will be constant during all vertex/pixel/any shader program processing, like world view projection matrices, color, anything you set for a specific vertex buffer and a draw call), theyr like a struct you create in your shader file, bind to a specific register "index". Check dx documentation for more details.

 

So where I just set things like worldviewmatrix and viewprojectionmatrix separately, a cbuffer means you can bundle all that up into one structure and send the whole thing to the shader - I see...

 

Also, in D3D9/10, there are API level "state blocks", which are similar (a container for certain Set<State> commands), but I don't use these

 

Thanks, got it now...  back to the story, gents rolleyes.gif 

0

Share this post


Link to post
Share on other sites

But how do you update the cbuffers, if a object moves/is animated etc.?

I think the cbuffer could either be a part of the object, but this would force all types of objects to have a common layout.

Or do you have some kind of offset or pointer array from which you copy the data into the buffers, before you draw the objects? This would allow having different data layouts, but would cause lots of copying of data...

0

Share this post


Link to post
Share on other sites

If data is being generated by the engine and then input into a shader, then yes, the shader and the engine need to agree upon the layout of that data.

For a simple object, this might be some standard cbuffer that just contains a 'world' matrix - this is basically the objects 'render transform component'. For an animated object it might be a cbuffer containing an array of bone matrices.

You might have another standardized cbuffer that contains the view-proj matrix that's owned by the camera, etc.

 

Not every cbuffer layout needs to be standardized like this, just ones that contain data that's generated by the engine, like matrices.

 

Often material settings (colours, texture scales, etc) can be set just once, by looking up a variables location within a cbuffer by name. In my engine, I build these kinds of material cbuffers offline using a tool (which reads the values from an artist's DAE file, and matches them up with the cbuffer layout written in the shader code), but you can also do this at runtime when necessary.

Edited by Hodgman
0

Share this post


Link to post
Share on other sites

high lvl object data -> cbuffer data -> update subresource (data being copied)

 

This also annoys me, on a higer lvl I end up working with more readable/manageable data, instead of using cbuffer raw data, so I end up having a update that copies data to cbuffer and then copies data to ID3D11Buffer..Is it viable to work straight on a cbuffer data so that you dont need to copy data to it?[edit] answered on previous post[/edit]

 

Im doing this way (my system is "working", but its barely tested (got things rendering yesterday), so it might be really lame and full of yet to detect bugs):

 

my cbuffer class:

#pragma once

// system/standard headers

#include <D3D11.h>
#include <boost/smart_ptr.hpp>

namespace render{

	//========================================================================
	// holds CBs actual data(values)
	//========================================================================
	class ConstantBuffer{

		typedef UINT byteoffset;

		UINT m_nBytes;
		UINT m_nVariables;

		boost::scoped_array<BYTE> m_variablesBuffer;
		boost::scoped_array<byteoffset> m_variablesOffsets;
		boost::scoped_array<UINT> m_variablesSizes;

		bool m_bNeedUpdate;	// used to check if it needs update to the pipeline

	public:

		//------------------------------------------------------------------------
		// ctor
		//------------------------------------------------------------------------
		ConstantBuffer( const UINT size_p, const UINT nVariables_p, const UINT * pVariablesSizes_p )
			:	m_variablesBuffer(new BYTE[size_p]()),
				m_variablesOffsets(new byteoffset[nVariables_p]),
				m_variablesSizes(new UINT[nVariables_p]){

			m_nBytes = size_p;
			m_nVariables = nVariables_p;
			m_bNeedUpdate = false;

			UINT iOffsetCache = 0;
			for( UINT it = 0; it < m_nVariables; ++it ){

				m_variablesOffsets[it] = iOffsetCache;
				m_variablesSizes[it] = pVariablesSizes_p[it];

				iOffsetCache += m_variablesSizes[it];
			}
		}
		
		UINT GetSize() const{
			return m_nBytes;
		}

		//------------------------------------------------------------------------
		// Set variable by index
		//------------------------------------------------------------------------
		void SetVariable( UINT index_p, const BYTE* data_p ){

			memcpy( &m_variablesBuffer[ m_variablesOffsets[index_p] ], data_p, m_variablesSizes[index_p] );
			m_bNeedUpdate = true;
		}

		//------------------------------------------------------------------------
		// Set the entire buffer at once
		//------------------------------------------------------------------------
		void Set( const BYTE * data_p ){

			memcpy( m_variablesBuffer.get(), data_p, m_nBytes );
			m_bNeedUpdate = true;
		}

		//------------------------------------------------------------------------
		// Test if buffer data was modified since last update call, than updates it,
		// or not.
		//------------------------------------------------------------------------
		void Update( ID3D11DeviceContext * pContext_p, ID3D11Buffer *& pConstantBuffer_p ){

			if( m_bNeedUpdate ){

				pContext_p->UpdateSubresource( pConstantBuffer_p, 0, NULL, m_variablesBuffer.get(), 0, 0 );
				m_bNeedUpdate = false;
			}
		}
	};

	typedef boost::shared_ptr<ConstantBuffer> shared_CBuffer_ptr;
}

Then my binder cbuff command :

class BindVSConstantBuffer : public Binder{

	UINT m_iStartSlot;
	ID3D11Buffer *m_pConstantBuffer;
	boost::shared_ptr<render::ConstantBuffer> m_pConstantBufferData;

public:

	BindVSConstantBuffer( UINT iSlot_p, ID3D11Buffer *pConstantBuffers_p,  const boost::shared_ptr<render::ConstantBuffer> & pConstBufferData_p )
		:
	  Binder( 1LL << (E_VS_CBuffer0 + iSlot_p), E_BIND(E_VS_CBuffer0 + iSlot_p) ),
	  m_iStartSlot( iSlot_p ), m_pConstantBuffer( pConstantBuffers_p ),
	  m_pConstantBufferData(pConstBufferData_p){

		  assert( iSlot_p < 4);	// handling up to 4 cbuffers slot
	  }
	 
	//------------------------------------------------------------------------
	// Updates data to the buffer before binding it.
	//------------------------------------------------------------------------
	virtual void Execute( ID3D11DeviceContext * pDeviceContext_p ){

		m_pConstantBufferData->Update( pDeviceContext_p, m_pConstantBuffer );

		pDeviceContext_p->VSSetConstantBuffers( m_iStartSlot, 1, &m_pConstantBuffer);
	}
};
Edited by Icebone1000
0

Share this post


Link to post
Share on other sites

I was very messed on this issue in my renderer and still could not come up with tidy solution.

Material is somehow much connected to the geometry.

I have a CShader class, it contains informations:

1- vertex declaration

2- compiled shader

then CMesh class that contains:

1-Vertex/Index Buffers

2- texture information

3- Cshader to use with the mesh (precisely 1)

 

Then in rendering, draw method of the CMesh looks up the vertex declaration of CShader instance and bounds vertex buffers streams accordingly, you have to assure CMesh has all of the streams vertex declaration asks though. Then textures are bound according to material ids. Then Scene Node info is passed to uniform data... and I draw. I also wrote more Render methods for CMesh if I needed to display it with another material, like RenderShadowVolume, or RenderDefferedLight(CLight) - this one is used only on screen aligned quad to render lightning after front passes.... and so on. I think that rendering instructions are so volatile that any "think for me" leads to no help.

0

Share this post


Link to post
Share on other sites

class ConstantBuffer

I did it almost exacly the same, but I'm not completly happy with it:

I pack all the data for one object together and build a reflection of the object (name->offset array) and a buffer reflection (name->offset&size), from which I create something like a copy-instruction (arrays of sourcOffset, destinationOffset, dataSize) which copys all the data from the source offset to the buffer offset.

But it is all a bit messy right now...sad.png

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