What does glfwGetWindowUserPointer do? - glfw

When looking through the GLFW reference I came across the glfwGetWindowUserPointer function (and the glfwSetWindowUserPointer function). In the reference it says the following about the user-pointer:
Each window has a user pointer that can be set with glfwSetWindowUserPointer and fetched with glfwGetWindowUserPointer. This can be used for any purpose you need and will not be modified by GLFW throughout the life-time of the window.
Now I wonder for what purpose one could use this?

I am not going to take credit for this answer, as it is not my answer, but the answer of someone else on the GLFW forum.
A UserData field is a fairly common paradigm in C APIs that lets the user access contextual data from within callbacks without needing to make everything global. In essence, it lets you associate an arbitrary piece of data relevant to your program with a glfw window.
If you are trying to use glfw in a program that follows object-oriented design, for example, you can use this pointer to store the address of the instance that is handling a particular window, and forward the callbacks (which have to be static functions, because of the way the API works) to the appropriate member functions.

Related

Is it a good idea to expose Vulkan's function pointers globally?

I just loaded a shared library for the first time at runtime. What I am currently doing is that I create an explicit context where all function pointers are loaded.
It would roughly look like this in C++
auto entry = load_vk(..);
auto instance = entry.CreateInstance(...);
VkInstancePointer vk = load_vk_static_fn(instance);
vk.CreateDevice(...);
The problem is that I am not sure about the lifetime of this. I would need to access vk across different threads, so I am currently wrapping it in a shared_ptr<VkInstancePointer>. I also unload the library in the destructor.
The sort of problem that I am having is that I want to make the vulkan api a bit more convenient so that I am able to write
physical_device.create_logical_device(...);
But that would mean that a physical_device needs to contain a shared_ptr<VkInstancePointer>. That means that a lot of stuff will have an additional overhead of an atomic counter increment.
I am wondering if I could just load the vulkan function pointers globally?
load_entry();
auto instance = CreateInstance();
load_instance_fp(instance);
auto device = CreateDevice(..);
I usually never use globals but it seems that it would make sense here.
Do I ever want to unload the Vulkan library at some point?
There are two kinds of function pointers in Vulkan: instance function pointers and device function pointers.
Instance function pointers are retrieved via vkGetInstanceProcAddr. This function can retrieve function pointers for functions that are device-independent. That is, for functions that deal with creating/managing/destroying devices, as opposed to functions that talk directly to a device (ie: any function that takes a VkDevice, VkQueue or VkCommandBuffer).
But it also can retrieve pointers for functions that talk to the device itself . These functions can talk to any Vulkan device, whether it was created before or after the function pointers were retrieved.
By contrast, vkGetDeviceProcAddr gets device function pointers. These function pointers are specific to a device; they cannot be used with a different device from the one they were created with.
So you can create global function pointers which can be used from any thread to talk to any device. But they have to be instance function pointers.
Or you can just let the Vulkan SDK do its job and handle all of this for you.
Do I ever want to unload the Vulkan library at some point?
I don't know of a reason why you would want to. Users generally can't install new versions of a driver-level system like Vulkan without a restart of the machine. And even if you could, your code wouldn't know what to do with its new stuff, since your code was written against a lower version.

Are there any plans or existing projects to port OpenGL API to C++? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 9 years ago.
Improve this question
The OpenGL standard pages states that the OpenGL is callable from C and C++. The API, however, is of course in pure C. As the OpenGL uses for example a lot of enumerations, using enum-classes (from C++11) could greatly reduce number of errors and make the API more feasible for beginners. It could be seen that lot of the bindings like OpenTK (for C#) are created; creating good C++ API shouldn't be much harder.
I weren't able to find anything that was more than an obscure wrapper, hence my questions:
Is there a well-known C++ wrapper using C++11 facilities for OpenGL? and if not,
Is something like this planned by anyone well-known (which especially means the Khronos)?
The whole way OpenGL works does not really well map to OOP: http://www.opengl.org/wiki/Common_Mistakes#The_Object_Oriented_Language_Problem
What's not stated in this article is the context affinity problem. In OpenGL everything happens on the context, so a class "Texture", to be correct would be nothing more than a glorifed handle to be used with the context.
This is wrong:
class Texture {
/* ... */
public:
void bind();
}
It would only work if the texture was part of the currently active context.
This is no better either:
class Texture {
/* ... */
public:
void bind(Context &ctx);
}
The texture still must be part of the context ctx, and it would only work, if ctx was active at the moment.
So what about this:
class Context {
/* ... */
public:
void bindTextureToUnit(TextureUnit &tu, Texture &t);
};
Better, but still not correct as the context must be the one currently active in the current thread. You may think "oh, I'll just throw an exception if context is not active". Please don't do this.
So what about this
class ActiveContext : Context {
/* ... */
public:
void bindTextureToUnit(TextureUnit &tu, Texture &t);
}
Now you've ended up with making sure that there can be only one ActiveContext instance per thread. Which ends you up in all kinds of weird thread singleton mess.
In fact I numerously tried to implement a clean and sane mapping from OpenGL state and objects into a set of C++ classes, but there are always cases where is simply doesn't work out or ends up in horrible code mess.
IMHO it's far better to not try mapping the OpenGL API into a set of C++ classes (it can't be done sanely), but instead use the regular OpenGL API from specialized classes. Any OpenGL context management is so dependent in the program in questions, that it must be tailored specifically to said program.
Wrapping OpenGL and an OpenGL object model are two different concepts. OpenGL entities can easily be made into objects to wrap their functionality and indeed if you want to write a renderer that can be instantiated with, say, either OpenGL or D3D, this is a strict necessity.
I have classes like this:
class Device
class State
class Buffer
class BufferUniform
class BufferVertices
class BufferIndices
class BufferArray
class Texture
class Texture1d
class Texture2d
class Texture3d
class TextureCubeMap
class TextureArray
class TextureRender
class TextureFrame
class Shader
class ShaderPixel
class ShaderVertex
class ShaderGeometry
class ShaderEvaluator
class ShaderTessellator
class ShaderProgram
class ShaderGenerator
class ShaderGeneratorParser
class ShaderGeneratorNode
class ShaderGeneratorCondition
... and either a D3D or an OpenGL version of each. Renderer<...> is instantiated with one set or the other at compile-time, depending on whether I want D3D or OpenGL to do the work.
Is there a well-known C++ wrapper using C++11 facilities for OpenGL? and if not,
No. There have been some attempts at it.
Is something like this planned by anyone well-known (which especially means the Khronos)?
The Khronos ARB doesn't really try to communicate directly with us about upcoming stuff. However, I highly doubt that they care about this sort of thing.
As for anyone else, again, there are some independent projects out there. But generally speaking, people who use OpenGL aren't that interested in doing this sort of thing.
The basic facts are these: OpenGL objects are directly associated with some global concept. Namely, the OpenGL context. Those objects can only be manipulated when the context they exist within (since objects can be shared between contexts) are active.
Therefore, any C++ object-oriented system must decide how fault-tolerant it wants to be. That is, what kinds of assurances that it wants to provide. If you call a function that operates on an object, how certain will you be that this call succeeds?
Here's a list of the levels of assurances that could reasonably be provided:
Completely Anal
In this case, you ensure that every function call either succeeds or properly detects an erroneous condition and fails properly.
In order to pull this off, you need an explicit OpenGL context object. Every OpenGL object must be associated with a share group among contexts (or a specific context itself, if an object type is not shareable).
All object member functions will have to take a context object, which must be the context to which they belong or a member of the share group for that context. There would have to be a per-thread cache of the context, so that they can check to see if the current context is the one they were given, and make it current if it is not.
When a context is destroyed, every object that relied on that context's existence must instantly become non-functional. Thus, every such object needs to have access to some tag (such as via a std::weak_ptr) to let them know that all of their function calls will fail.
If the objects are going to be properly RAII'd, then each object must be able to ensure that a context that they can be destroyed in (ie: glDelete* function) is current. And if it isn't, they need to make one current. So basically, every object needs to hold a reference to a valid context or otherwise needs to be able to create one.
On a personal note, I find this all to be painfully silly. No API is this fault tolerant, nor does it need to be. There's a lot of pointless babysitting and sharing of information. C++ is not a safe language, so it shouldn't waste good memory and/or performance just to provide you this level of safety.
Sane
Here, we get rid of the context-based safety checks. It is up to you the user to make sure that the proper contexts are current before trying to use any object in any way. This is just as true of C++. The main feature of this API is just being nicer than the raw C API.
The OpenGL objects would be RAII style, but they would also have a "dispose" function, which can be called if you want them to clear themselves without deleting their corresponding objects. This is useful if you're shutting down a context and don't want to have to run through and destruct all of the objects.
This system would basically assume that you're wanting pure Direct State Access for these classes. So none of the modifying member functions actually bind the object to the context. They can achieve that in one of several ways:
Use EXT_DSA or the equivalent, where available.
If EXT_DSA or equivalent is not available, store the modified state and send the modifications the next time this object is bound.
Or just bind it, make the modification, and unbind it.
Certain kinds of modifications can't use #2. For example, glBufferData, glBufferSubData and glTexSubImage*D calls. The user really expects them to happen now. These functions should be named in such a way that they are distinguishable from guaranteed non-binding functions.
Any such binding functions should make no effort to restore the previous bound state of the object.
Permissive
Basically, there's a 1:1 correspondence between C++ member functions and C functions. Sure, you'll use C++ operator overloading and such to reduce the needless variations of functions. But when it comes right down to it, you're pretty much writing your C++ code the way you did your C code.
Objects may employ RAII, but they won't provide any real convenience beyond that. Member functions will either bind the object themselves or expect you to have bound them. Or they will use DSA and fail if DSA isn't available.
Why bother?
At the end of the day, there's really nothing much to gain from having a C++ interface to OpenGL. Sure, you get RAII. Well, you can get RAII just fine by using a std::unique_ptr with a special deleter functor (yes, really, this is very possible). But beyond some slight convenience with the API, what real expressive power do you gain that you did not have before?
If you're serious about using OpenGL to develop an application, you're probably going to build a rendering system that, relative to the rest of your code, abstracts OpenGL's concepts away. So nobody would see your fancy C++ interface besides your renderer. And your renderer could just as easily use OpenGL's C API. Why build your renderer off of an abstraction if it buys you pretty much nothing.
And if you're just toying around with OpenGL... what does it matter? Just use the interface you have.

How can I link to callback functions in Lua such that the callbacks will be updated when the scripts are reloaded?

I'm implementing Lua scripting in my game using LuaBind, and one of the things I'm not clear on is the logistics of reloading the scripts live ingame.
Currently, using the LuaBind C++ class luabind::object, I save references to Lua callbacks directly in the classes that use them. Then I can use luabind::call_function using that object in order to call the Lua code from the C++ code.
I haven't tested this yet, but my assumption is that if I reload the scripts, then all the functions will be redefined, BUT the references to the OLD functions will still exist in the form of the luabind::object held by the C++ code. I would like to be able to swap out the old for the new without manually having to manage this for every script hook in the game.
How best to change this so the process works?
My first thought is to not save a reference to the function directly, but maybe save the function name instead, and grab the function by name every time we want to call it. I'm looking for better ideas!
My first thought is to not save a reference to the function directly, but maybe save the function name instead, and grab the function by name every time we want to call it.
If your classes are calling global functions with known names, then that pretty much solves your problem. No need to grab a reference in advance; it's not going to make a measurable performance difference. I think call_function supports passing the function name as a string anyway, right?
You typically store reference to a function value when the Lua script is registering a callback. In that case, it's much better than storing a name, because it allows the Lua script to register functions which are local, anonymous, ect.
If you really had to grab the value value in advance, as you're doing now (and there's really no reason to do that, but we'll pretend it's necessary), I would add a layer of indirection. You could have a LuaFunctionReference class which encapsulates a global name. During instantiation, it grabs a reference to the function the global contains. These objects could be acquired from a factory which maintains a list of all such references. When you reload a script, you could have the factory/manager/pool/etc. object iterate through the references and have them update themselves, so all the references tucked away in classes throughout the system would be updated.

What's the best way to set 'deep' configuration options?

Assume there is a function that requires a configuration setting as an input, but this function is called several levels deep from the top-level 'main' function.
What's the best way, in terms of best programming practices, to pass this setting to the function?
One way is to just use a global variable and set that at the top level function and read it in the target function, but I assume that that is considered bad programming practice.
Another way is to pass the setting as an argument all the way from the top, through the several intermediate functions, all the way down to the final target function. This seems very tedious though and perhaps error-prone.
Are there other approaches?
You can use your language of choice for your answer, but FYI, I'm using C/C++, Perl, and Matlab.
I like singleton objects for configuration. It's a shared resource that should only ever have one instance. When you try to create a new object, you get the existing one. You don't worry about global variables or subroutine or method parameters. Simply get a new configuration object and use it as long as you need it.
There's an example in Gang of Four for C++.
Leave the procedural programming style with deep call stacks behind and the answer becomes a banality.
Remodel your program to take advantage of modern object-orientation. Perl roles make for flat hierarchies. A configuration is then just an attribute.
A system I work with uses a Publish-Subscribe (Observer Pattern) implementation to propagate settings/configuration changes to objects that need to know about them.
The object (Subscriber, or Observer in the original Gang of Four description) that needs to be notified of settings changes:
Inherits from Subscriber.
Attaches itself (subscribes) to the Publisher via the Publisher's Attach method.
Is notified by the Publisher whenever settings/configuration changes occur.
We use a variant that allows Subscribers to poll Publishers for settings/configuration data on demand.
Using the Publish-Subscribe pattern minimizes coupling between the object that manages the settings, and the objects that need them.
In matlab, I always have a script allParam.m, where I set all the parameters.
If a function needs one of those parameters, I just call the script, and it is set.

Single Document project structure

I have previously asked about the proper way of accessing member variables present in the project. In the project, I have CWinapp-derived class, CMainFrm class, a list of different view classes. However, currently, I have instances of different user-defined classes instantiated in the CWinApp-derived class, while the rest of the classes use a pointer obtained from AfxGetApp() function, and then access the different user-defined classes. I was told by some community members on the MFC newsgroup that this is a very bad design (i.e. the parent should not know anything about an app-class, view class, or document class). However, I'm not sure how otherwise I can access various user-defined classes without using this design. It would be great to hear some suggestions as I'm not familiar enough with MFC to come up with proper search terms.
"(i.e. the parent should not know anything about an app-class, view class, or document class)"
I'm not sure I understand this sentence, what do you mean with 'parent' here?
Anyway, in my opinion, the design you describe isn't really a problem. It's a trade off: do you either pass these classes to all functions that need them, complicating their use and API, or do you store them as a sort of global variables like you're doing? It depends on the data that is accessed, and how often. Data that is needed in many places can just as well be 'global'.
There are multiple ways of making data 'global': make it a member of CWinApp (that is, your CWinApp-derived class), or of CMainFrame, or do you make an actual 'global variable', or do you make a singleton, ...
The problem with global variables is that it becomes hard to figure out who accesses it when and from where. If you data as a member of CWinApp, you can access it through an accessor function and trace access from there (through log messages, break point, ...) This, in my opinion, mitigates most of the problems associated with global variables. What I usually do nowadays is use a Loki singleton.
The reason that is stated in your post for not making data a member of CWinApp, as a decoupling issue, is (in the context that you've presented it) a bit strange imo. If certain classes need access, they'll need to know of those data structures anyway, and their storage location is irrelevant. Maybe it's just because I don't know about the specifics of your design.