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

Class to store different uniforms (variant like)

6 posts in this topic

Hello,
As I moved my rendering into centralized Renderer class, I can't use direct GL calls (glUniform*) to set uniforms where I know their value, but I have to pass them all as a part of draw command to renderer. Perfectly I'd have something like:

[source lang="cpp"]std::map< std::string, Uniform > uniforms;

uniforms["mvp"] = Uniform(glm::mat4(0.0));

uniforms["alpha"] = Uniform(0.56f);

glm::vec4 sunpos = world->getsunpos();
uniforms["sunpos"] = Uniform(sunpos);[/source]

For now I need support for: float, int, vec2, vec3, vec4, mat4, but later I may also need uniform structs. From what I know this is typical variant class that stores values of different types. I wanted to ask you for best solution, because the one I managed to hack so far is not perfect, is a bit bloated with nasty switches and requires me to initialize Uniform only by passing "new" into constructor (so this doesn't work: Uniform(mvp) or Uniform(glm::mat4(0.0)), only this: Uniform(new glm::mat4(mvp)).

I will show code for one sample value:

[source lang="cpp"]UniformValue::UniformValue(std::string name, glm::vec2* value)
{
m_Name = name;
m_Data = static_cast< void* >(value);
m_Type = UniformValue::Vec2;
}

UniformValue::~UniformValue()
{
switch(m_Type)
{
case Vec2:
delete static_cast< glm::vec2* >(m_Data);
break;
}
}

glm::vec2 UniformValue::ToVec2() const
{
return *(static_cast< glm::vec2* >(m_Data));
}

void UniformValue::Apply(Shader* shader) const
{
switch(m_Type)
{
case Vec2:
shader->SetUniform(m_Name, ToVec2());
break;
}
}[/source]

I'm not entirely sure this is the best solution to my problem. Do you guys know any better? Especially if they allow me to pass local variables (Uniform(model) instead of Uniform(new glm::mat4(model))) and not have to use "new" in constructor.

I was thinking about using [b]unions [/b]but I'm not sure they will work with glm::mat4 and other more complex objects (non-POD).

PS. Also solution should be pretty quick and not initialize unecessary things (like passing variable, copying it, then allocating some new one in the final step) - setting uniforms happens for all drawing commands every frame so it shouldn't be too unoptimized, because maybe its not much, but its done very often. Edited by noizex
0

Share this post


Link to post
Share on other sites
my personal solution, but frankly I hate it, I think it is just a failed moment of having fun with C++, and that you can just go implement duplicated functions it is just a small part of the underlying layers of en engine you rarely need to put your nose into anyways. once its written its written.

anyways:

http://paste.blixt.org/8871931

PS note: the code=cpp tag in that forum is reaaaally buggy. impossible to post my snippet of code without losing entire lines !! Edited by Lightness1024
0

Share this post


Link to post
Share on other sites
hm, I see maybe that is not totally what you wanted, maybe you wanted a 'deferred storage' to be able to get and mutate your uniforms multiple times in a frame and only once actually upload it to the driver, so you wanted a way of managing that store ? which my solution doesn't provide of course. but it can maybe give you some ideas for ways to handle multiple types.

Also about the "nasty switch", check your assembly code, but it gets more optimized than anything that can be written by hand. Most people wrongly assume switches are stupid comparators that tries every value until finding the good one, but actually it uses optimal hashing / research or binary selection during code generation since all constants are integers and known. Edited by Lightness1024
1

Share this post


Link to post
Share on other sites
The trick with stuff like this is to first off, write a bunch of overloaded version of glUniformXYZ() which takes C++ types and a slot and sets the uniform.

Then you can write templated setter classes which you can store in the map.

Then you can write a simple interface to the uniforms map which takes a string and an arbitrary type and puts a setter into the map.

Then you just iterate over the map calling the setter through an interface.

If you do this neatly, BTW, you can arrange to store either a value or a reference into the map. So you can express "Set this uniform to integer 7, but set that one to the value of this integer over here" in the same uniforms group.

If you make the setters a PIMPL interface with a templated inner class constructed inplace into a convenient array of spare memory and set up copy operators properly, then the setters are plain value objects and hence can be stored directly in the map. All this avoids nasty casts and will properly type-check things at compile time. (Because if you try and store an X and there ultimately isn't a suitable glUniformXYZ then the code won't build). And you can hotwire it to use your own vector/matrix classes and write them into the GLSL versions.

I've probably got some code somewhere if that doesn't make sense.
1

Share this post


Link to post
Share on other sites
Wow, thanks! Thats a lot of very useful input, I was worried that this topic won't get any answer as it was few days and noone responded to it [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img]

[b]@Lightness1024: [/b]
Yeah, <code> tag is broken unfortunately, it seems to strip template braces because they're similar to HTML tags - it should escape them but it doesnt. Putting space between braces and the template parameter helps, but it requires changing all code so probably better using some external pastebin for longer code. Thanks for code sample, I will try and comprehend it, although I see Boost there and I try to stay away from it as my code already has a lot of external libraries. And I completly agree about switch not being bad speed-wise, I meant it more from a programmer's perspective - adding another type requires you to fill few switch statements which is error-prone, rather than speed of actual code.

[b]@Katie: [/b]
Ok, my shader already has overloaded functions that take glm::vecs and glm::mats, floats etc. But not sure what you mean about templated setter class and how to store different types in one map. Some code sample would be great, because it sounds like it could be a good and clean solution, but I'm not sure I understand 100% of it.

[b]@Hodgman[/b]
Your solution is probably fastest because it works on simple structs and you can then copy it into UBO - only potential drawback I can see is that it requires you to have really well-thought-of concept of what uniforms you need, even on object/mesh-level. Right now I use UBO for "render pass" information like camera projection & view matrices. I also plan to have one lower level UBO (for things like material), then we go down to per-object state and here I'm not sure, because uniforms can really vary per object. I can be wrong of course, because for now I only have very similar objects rendered (they use the same uniforms and stuff like that) but I can't know what the future will bring. Thats the reason why I made the lowest level based on setting uniforms rather than a buffer, because then I don't have to rely on some static structure of UBO.

But now that I think about it more and more, I may just go for UBO till the moment where my uniforms can't fit one structure. Well, I can even have few structs for different objects - only thing it requires is making new struct definition, instead of freely setting any uniform I want through some SetUniform(name, val) call. Edited by noizex
0

Share this post


Link to post
Share on other sites
OK, so the usual trick about storing different types in a map is to go at it like this;

You create an envelope class which implements your interface and in turn delegates the work to an interface pointer. You create a suitable templated class into that interface pointer.

Like this;

[CODE]
class Inner
{
virtual void doStuff(<params>)=0;
virtual Inner *cloneAt(void *address)=0;
}


template<class DATA>
class InnerTempl
{
DATA data;
virtual void doStuff(<params>) { // in here you can use 'data' to work on it, and it has the right type. }

InnerTempl(const DATA &d):data(d) {}
virtual Inner *cloneAt(void *address)
{
return new(address) InnerTempl(data);
}
}


class Outer
{
Inner *pInner;
void doStuff(<params>) { pInner->doStuff(<params>); }

template <class X> assign(const X &x) { pInner=new InnerTempl<X>(x); }
}
[/CODE]

So far, so good.

You can store Outers in a map. There's some issues about memory management and you'll need to flesh those out into real classes.

Avoiding the memory management can be done reasonably neatly if you're careful.
Start with this;

[CODE]
class Outer
{
Inner *pInner;
unsigned char space[32]; // you'll need to pick a size here that's big enough for your purposes.
void doStuff(<params>) { pInner->doStuff(<params>); }
template <class X> assign(const X &x) { pInner=new(space) InnerTempl<X>(x); }
template <class X> operator=(const X &x) { pInner=new(space) InnerTempl<X>(x); }
};
[/CODE]

Now you don't need a separate inner object, so there's one less memory alloc and no loose pointers. It's a bit hacky and relies on picking a size that's 'big enough' but games development is ~1% genius and 99% hacking that genius to work practically.

STL mandates objects in maps must be copyable. And this then, is why we implemented cloneAt. Note that it needs the virtual dispatching to end up in a function which knows what type DATA really is.

Add to Outer an assignment operator.

Outer &operator=(const Outer &other) { pInner = other.pInner->cloneAt(space); }

Likewise, implement a copy constructor.

STL mandates objects in maps must have a null constructor. Make it have a null pInner to start with & add all the exception handling to cope with that and you're done.

Now you can store arbitrary types in the map by just assigning to them and iterate through them calling doStuff() on each one.

[CODE]
typedef map<string,Outer> MYMAP;
MYMAP mymap;
myMap["foo"]=1.5;
myMap["foo"]=vec3(0,0,7);

[/CODE]

Job done.


Then in this case, doStuff() probably takes an integer slot and then calls an overloaded glUniform() function passing "data" in.

Mine looks like this;

[CODE]
void glUniform(int slot,int value) { glUniform1i (slot,value);}
void glUniform(int slot,unsigned int value) { glUniform1i (slot,value);}
void glUniform(int slot,float value) { glUniform1f (slot,value);}
void glUniform(int slot,const vec2 &value) {glUniform2fv(slot,1,value.ptr());}
void glUniform(int slot,const vec3 &value) { glUniform3fv(slot,1,value.ptr());}
void glUniform(int slot,const vec4 &value) { glUniform4fv(slot,1,value.ptr());}
void glUniform(int slot,const ivec2 &value) { glUniform2iv(slot,1,value.ptr());}
void glUniform(int slot,const ivec3 &value) { glUniform3iv(slot,1,value.ptr());}
void glUniform(int slot,const ivec4 &value) { glUniform4iv(slot,1,value.ptr());}
void glUniform(int slot,const matrix &value){ glUniformMatrix4fv(slot,1,GL_FALSE,value.ptr());}

// I have my CPU vector classes named to match the GLSL ones because I got bored of accidentally using the wrong ones all the time.
// generally ptr() gets a base pointer to real data in the classes.
[/CODE]
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