Sign in to follow this  
FlyingSolo

OpenGL SDL. would YOU recommend it ?

Recommended Posts

Hi folks, after quite a few problems with NeHe's basecode when resizing my opengl window on various different systems(esp Win7 grrrr) I had SDL recommended to me. It looks like a breeze to incorporate SDL and it's not only multi-platform but handles things like keyboard and mouse events too. However, development seems to be stalled from what I can see - which is a worry. 1.3 seems to be vaporware and I really don't like that it creates a DOS/Command window in addition to the main window. I'd be far happier going on the recommendation of people far more knowledgeable and experienced than me since I'm pretty new to opengl. All I'm looking for really is something that will handle the window management for me, the opengl is already pretty much complete. Opinions and advice greatly appreciated. Thanks.

Share this post


Link to post
Share on other sites
Quote:
Original post by FlyingSolo
I really don't like that it creates a DOS/Command window in addition to the main window.

This has nothing to do with SDL, it depends on your project settings (whether it's a console or Win32 subsystem).

Quote:

All I'm looking for really is something that will handle the window management for me, the opengl is already pretty much complete.

SDL is great for this task:

SDL_GL_SetAttribute(SDL_GL_xxx, vvv); // set the OpenGL attributes like VSync, double buffer, etc.
SDL_SetVideoMode(640, 480, 32, SDL_OPENGL);

while (running)
{
SDL_Event evt;
while (SDL_PollEvent(&evt)) /* handle events */;

// render GL stuff
SDL_GL_SwapBuffers();
}

That's all it takes to get GL running with SDL.

You might also want to look into SFML, which is very similar.

Share this post


Link to post
Share on other sites
SDL also runs in a tighter loop so its faster than the other predecessor window API's. It handles event for you, just use this code

SDL_Event event;

int main(int argc, char **argv)
{
while ( !quit )
{
while ( SDL_PollEvent(&event) )
{
if ( event.type == SDL_QUIT )
quit = true
if ( event.type == SDL_KEYDOWN )
{
if ( event.key.keysym.sym == SDLK_ESCAPE )
quit = true
}
}
}

SDL_Quit();
}


and also the init functions might look like this

bool Init(void)
{
if ( SDL_Init( SDL_INIT_VIDEO | SDL_INIT_TIMER ) < 0 )
return false;

if ( SDL_SetVideoMode( screenWidth, screenHeight, bitsperpixel, SDL_OPENGL | SDL_GL_DOUBLEBUFFER ) == NULL )
return false;

//setup opengl stuff
return true;
}

and the documentation is pretty easy to follow, such as the event struct and the keycodes

Share this post


Link to post
Share on other sites
SDL is a mature and capable library. Some big studios have used it when porting their games to Linux.

SDL 1.3 is available, you can build it and use it, for the "core" stuff it works. There are rough edges (particularly around the new features) and it does seem to be taking forever to get released, I would agree there. Then again these are volunteers contributing. I wouldn't classiffy it as vapourware though.

But yes, I would highly recommend SDL to accompany OpenGL.

And as nullsquared mentions, the console window is nothing to do with SDL.

Share this post


Link to post
Share on other sites

Yessir I'd recommend it. My current project utilizes SDL. My only personal issue with it is actually concerning SDL_net, which apparently is only usable for TCP communications, wheras my project uses the UDP protocol... thus I was forced to use winsock as I am comfortable incorporating it into my source.


I think you might get something out of checking out my engine 'method', WIP but it's opensource: www.van-noland.com

Share this post


Link to post
Share on other sites
You can use UDP with SDL_Net. That said, the sockets interface is virtually identical across all operating systems, so it doesn't buy you too much and it makes it hard to do some things (I don't believe it is possible to make a socket non-blocking, for instance).

Share this post


Link to post
Share on other sites
Well I guess that answered my question! Thank you all for some great replies.

But... with a very simple program I'm seeing memory usage increasing at about 4k/sec for no apparent reason.

Am I missing something with SDL? It seemed insanely easy to set up.

My wee test prog is below (error checking removed for some clarity). All this does is clear to yellow and draw a red quad.


#pragma comment(lib, "Glu32.lib")
#include &lt;windows.h&gt; #include &lt;stdio.h&gt; #include "SDL.h"
#include "SDL_opengl.h"

SDL_Surface* screen;
SDL_Event event;


void InitGL(void)
{
glClearColor( 1.0f, 1.0f, 0.0f, 0.0f );
glViewport( 0, 0, 800, 600 );
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
glOrtho(0.0f, 800, 600, 0.0f, -1.0f, 1.0f);
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
}


void Resize(GLsizei width, GLsizei height)
{
if (height==0) { height=1; } glViewport(0,0,width,height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glOrtho(0.0f, 800, 600, 0.0f, -1.0f, 1.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}


void DrawScene(void)
{
glColor4f(1.0f,0.0f,0.0f,1.0f);
glBegin(GL_QUADS);
glVertex2d(200,200);
glVertex2d(400,200);
glVertex2d(400,400);
glVertex2d(200,400);
glEnd();
}


int WINAPI WinMain( HINSTANCE hInstance, // Instance
HINSTANCE hPrevInstance, // Previous Instance
LPSTR lpCmdLine, // Command Line Parameters
int nCmdShow) // Window Show State
{
SDL_Init(SDL_INIT_VIDEO);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER,1);
screen = SDL_SetVideoMode(800,600,16,SDL_OPENGL | SDL_HWSURFACE | SDL_RESIZABLE);
InitGL();

while (1)
{
while( SDL_PollEvent( &event ) )
{
switch( event.type )
{
case SDL_KEYDOWN:
switch ( event.key.keysym.sym )
{
case SDLK_ESCAPE: exit(0); break;
default: break;
}
case SDL_VIDEORESIZE: //User resized window
screen = SDL_SetVideoMode(event.resize.w, event.resize.h, 16, SDL_OPENGL | SDL_HWSURFACE | SDL_RESIZABLE); // Create new window
Resize(event.resize.w, event.resize.h);
break; //Event handled, fetch next :)
case SDL_QUIT: exit (0); break;
default: break;
}
}
DrawScene();
SDL_GL_SwapBuffers();
SDL_Delay( 50 );
}

}


[Edited by - FlyingSolo on February 14, 2010 2:34:48 PM]

Share this post


Link to post
Share on other sites
The only thing I see right off is that you appear to be bypassing the SDL implementation of WinMain(). Without digging around a bit I couldn't tell you what the consequences of this would be, but I imagine it might cause some problems.

If you check out some SDL tutorials (the Lazy Foo tutorials are good, assuming you haven't already read them), you'll see that your typical SDL-based application has what appears to be a 'normal' main() function. There's actually some macros at work that allow SDL to create a 'main' function appropriate for the target platform and operating system, but you don't need to worry about that - just write main() as you would normally, and everything should work correctly. (Note that since in this context 'main' is actually a user-defined function, you must use the 'main' signature that matches what SDL expects, and you can't omit the return value as you could in a 'real' main function.)

Oh, and to get your code to format more nicely, you can use [ source ] tags (no spaces).

Share this post


Link to post
Share on other sites
I guess you are using WinMain function because of the additional console window.
As was said above: use a normal main function and add the following options to the Visual Studio's linker:
/SUBSYSTEM:WINDOWS
/ENTRY:mainCRTStartup
This will disable the additional console window.

Share this post


Link to post
Share on other sites
Thank you one and all - excellent stuff, I've learned a lot.

Thanks for the heads up on the console, that's my inexperience with Visual C.

Tried setting up a new SDL project using Windows (/SUBSYSTEM:WINDOWS) but now I'm up to my armpits with msvcrt linker issues - I've seen these before and have no idea how to resolve them. Seems I'm not alone there though.

SDL apps have to be built as Multi-threaded DLL ? That means redisting the msvcr90.dll file with my app - that's new.

finally got a good handle on opengl, SDL is a breeze, it's the rotten compiler that's holding me up! Sometimes life just doesn't seem fair!

The Lazy Foo tut's don't work btw (msvcrt errors as above) which is a shame. Guess they're for 2005 not 2008.

More to learn - thanks all.

Share this post


Link to post
Share on other sites
Qt Logo

I recommend dropping SDL and similar libraries in favor of Qt. It is free, cross platform, it has excellent documentation and it is in active development. It provides you with much much more that SDL. Especially with a complete GUI library and a high level hardware accelerated painting engine.

Share this post


Link to post
Share on other sites
Quote:
Original post by FlyingSolo
SDL apps have to be built as Multi-threaded DLL ? That means redisting the msvcr90.dll file with my app - that's new.

Yes, unless you rebuild SDL with another option.
Quote:

More to learn - thanks all.

My exact settings for compiling with SDL on MSVC2008 are:
SDLmain.lib
SDL.lib
(in that order)
/SUBSYSTEM:CONSOLE in linker command line settings
int main(int argc, char **argv) for the main function

Share this post


Link to post
Share on other sites
Once again - thanks to all! Although google is an invaluable tool these days, there is no substitute for people with real experience. I really do appreciate your help. I know us relative newbies are a pain in the ass !

All seems to be working happily with SDL now although I did have some fun with some demo code I found. Pressing the ALT key would cause the app to resize to something like 32767x100 :) Sorted now thank God.

I did look at Qt briefly a while back, I think it would be like using the entire 101st Airborne to break up a bar fight though. My app, although complex, is relatively small. I've bookmarked that though for future projects though.

Thanks for the MSVC tips, always very useful to have. I've been using Delphi since v1.0 and boy does that spoil you. You can give no thought whatsoever to setup and just concentrate on your code - it really does rock. (but I love C !)

Big thanks to M$ for making Visual C a freebie, but as with most modern software it's bloated and there are more options and tweaks than I could shake a sh1tty stick at! I started on DEC PDP-8i's about 30 years ago and it was a lot less complex then!

So, for now - it all seems happy again, and my goal of getting this running on the Mac and possibly Linux too has been made easier by SDL - and you guys.

Thank you all ! :-)

Share this post


Link to post
Share on other sites
Quote:
Original post by FlyingSolo
I'd be far happier going on the recommendation of people far more knowledgeable and experienced than me since I'm pretty new to opengl.



I've used SDL for a long time now and have recently started folding OpenGL into my SDL programming experience.

I've used Allegro (back in the day), SFML, and tinkered around with DirectX. SDL is the most intuitive and best documented of all the libraries I've used. Combined with OpenGL, you can get some pretty fast graphics in place with lucid audio and user input handling.

SDL has several child projects that help round it off more thoroughly. SDL_image is pretty much necessary for me because I tend to store my sprites in a format other than .BMP. SDL_ttf is a bit obnoxious and I just defer to OpenGL for showing text. SDL_mixer is rather necessary and not very hard to learn.

I've never bothered with socket programming so I can't comment on SDL_net.

In short, I'd recommend SDL. It's portable and it just plain works. Maybe I'm just too dumb but I never could get SDLdotNET (the C# wrapper for SDL) or SFML to really work for me and DirectX gives me ulcers. I've gotten the best results in the least amount of time with good, old-fashioned SDL projects.

Share this post


Link to post
Share on other sites
SDL is a jack of all trades and a master of none.

For example of the lack of optimization, I complained on the mailing list that "SDL_SemWait() on Windows calls WaitForSingleObject(), which obtains a kernel lock all of the time and thus has significant overhead even when it returns right away--from an Intel forum, it's about 40 times slower than a user-space lock. It would make sense to change this to only call when the program actually expects it to block. A user-space lock should be done using interlocked operations similar to the way it's in pthreads-win32, then WFSO called if it has to wait." then I was told to make a change myself I felt it necessary. I used pthreads instead and specialized substitutes can be optimally selected to replace all other aspects of SDL as well.

Share this post


Link to post
Share on other sites
@Prune

It is much a volunteer project. If you have taken the time to do this research, and go so far as to tell them what the problem is and how it could be fixed, why not fix it? Thus this issue would no longer exist.

Share this post


Link to post
Share on other sites
Quote:
Original post by Ectara
@Prune

It is much a volunteer project. If you have taken the time to do this research, and go so far as to tell them what the problem is and how it could be fixed, why not fix it? Thus this issue would no longer exist.
Prune's example isn't the only one, and while his is a relatively technical issue, some of the others aren't.

A personal gripe of mine: we have been waiting since sometime in 2003 for the SDL_WM_ToggleFullScreen() function to be implemented outside of linux. The function has been in the API all this time, but somehow, it never quite is implemented...

Share this post


Link to post
Share on other sites
Quote:
Original post by Steve132
I really like FreeGLUT. Its under active development and really simple, its designed to work with OpenGL from the start, AND it works with OpenGL 3.0. I like it a lot.
Another worthy choice is glfw-lite, unfortunately only available from the subversion repository. Basically, they stripped all the cruft (threading, image loading, etc.) out of glfw, and updated it considerably.

Share this post


Link to post
Share on other sites
Quote:
Original post by FlyingSolo
Hi folks,
after quite a few problems with NeHe's basecode when resizing my opengl window on various different systems(esp Win7 grrrr) I had SDL recommended to me.


I've never touched SDL. However, I have been using OpenGL for many years. I would really recommend that you try and get the base code working, if for no other reason than understanding how to implement an OpenGL context fully in Windows. I'm using OpenGL under Windows 7 and have had no trouble with it at all.

SDL may be the best thing for your project; I simply do not know. However, using it to avoid learning how / having to solve a problem will only cause you headaches in the future.

Also, the NeHe tutorials are not the best way to get started. They have caused me a great deal of frustration. Many of them are poorly written and the Windows code is horrible. When I was starting to learn Windows programming a couple of years ago, I made the mistake of trying to use the NeHe examples. I ended up getting more information and understanding out of a 10 year old Windows 95 game programming book.

Exactly what problems are you having?

Share this post


Link to post
Share on other sites
I like SFML because it is a bit more modular than SDL. In terms of window management and input events, it is pretty much identical to SDL, but you have the ability to link just the system and window libraries and just leave out all the crap you don't need, like the sprite system, sound, and networking to help keep your namespaces uncluttered.

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  

  • Announcements

  • Forum Statistics

    • Total Topics
      628338
    • Total Posts
      2982167
  • Similar Content

    • By test opty
      Hi all,
       
      I'm starting OpenGL using a tut on the Web. But at this point I would like to know the primitives needed for creating a window using OpenGL. So on Windows and using MS VS 2017, what is the simplest code required to render a window with the title of "First Rectangle", please?
       
       
    • By DejayHextrix
      Hi, New here. 
      I need some help. My fiance and I like to play this mobile game online that goes by real time. Her and I are always working but when we have free time we like to play this game. We don't always got time throughout the day to Queue Buildings, troops, Upgrades....etc.... 
      I was told to look into DLL Injection and OpenGL/DirectX Hooking. Is this true? Is this what I need to learn? 
      How do I read the Android files, or modify the files, or get the in-game tags/variables for the game I want? 
      Any assistance on this would be most appreciated. I been everywhere and seems no one knows or is to lazy to help me out. It would be nice to have assistance for once. I don't know what I need to learn. 
      So links of topics I need to learn within the comment section would be SOOOOO.....Helpful. Anything to just get me started. 
      Thanks, 
      Dejay Hextrix 
    • By mellinoe
      Hi all,
      First time poster here, although I've been reading posts here for quite a while. This place has been invaluable for learning graphics programming -- thanks for a great resource!
      Right now, I'm working on a graphics abstraction layer for .NET which supports D3D11, Vulkan, and OpenGL at the moment. I have implemented most of my planned features already, and things are working well. Some remaining features that I am planning are Compute Shaders, and some flavor of read-write shader resources. At the moment, my shaders can just get simple read-only access to a uniform (or constant) buffer, a texture, or a sampler. Unfortunately, I'm having a tough time grasping the distinctions between all of the different kinds of read-write resources that are available. In D3D alone, there seem to be 5 or 6 different kinds of resources with similar but different characteristics. On top of that, I get the impression that some of them are more or less "obsoleted" by the newer kinds, and don't have much of a place in modern code. There seem to be a few pivots:
      The data source/destination (buffer or texture) Read-write or read-only Structured or unstructured (?) Ordered vs unordered (?) These are just my observations based on a lot of MSDN and OpenGL doc reading. For my library, I'm not interested in exposing every possibility to the user -- just trying to find a good "middle-ground" that can be represented cleanly across API's which is good enough for common scenarios.
      Can anyone give a sort of "overview" of the different options, and perhaps compare/contrast the concepts between Direct3D, OpenGL, and Vulkan? I'd also be very interested in hearing how other folks have abstracted these concepts in their libraries.
    • By aejt
      I recently started getting into graphics programming (2nd try, first try was many years ago) and I'm working on a 3d rendering engine which I hope to be able to make a 3D game with sooner or later. I have plenty of C++ experience, but not a lot when it comes to graphics, and while it's definitely going much better this time, I'm having trouble figuring out how assets are usually handled by engines.
      I'm not having trouble with handling the GPU resources, but more so with how the resources should be defined and used in the system (materials, models, etc).
      This is my plan now, I've implemented most of it except for the XML parts and factories and those are the ones I'm not sure of at all:
      I have these classes:
      For GPU resources:
      Geometry: holds and manages everything needed to render a geometry: VAO, VBO, EBO. Texture: holds and manages a texture which is loaded into the GPU. Shader: holds and manages a shader which is loaded into the GPU. For assets relying on GPU resources:
      Material: holds a shader resource, multiple texture resources, as well as uniform settings. Mesh: holds a geometry and a material. Model: holds multiple meshes, possibly in a tree structure to more easily support skinning later on? For handling GPU resources:
      ResourceCache<T>: T can be any resource loaded into the GPU. It owns these resources and only hands out handles to them on request (currently string identifiers are used when requesting handles, but all resources are stored in a vector and each handle only contains resource's index in that vector) Resource<T>: The handles given out from ResourceCache. The handles are reference counted and to get the underlying resource you simply deference like with pointers (*handle).  
      And my plan is to define everything into these XML documents to abstract away files:
      Resources.xml for ref-counted GPU resources (geometry, shaders, textures) Resources are assigned names/ids and resource files, and possibly some attributes (what vertex attributes does this geometry have? what vertex attributes does this shader expect? what uniforms does this shader use? and so on) Are reference counted using ResourceCache<T> Assets.xml for assets using the GPU resources (materials, meshes, models) Assets are not reference counted, but they hold handles to ref-counted resources. References the resources defined in Resources.xml by names/ids. The XMLs are loaded into some structure in memory which is then used for loading the resources/assets using factory classes:
      Factory classes for resources:
      For example, a texture factory could contain the texture definitions from the XML containing data about textures in the game, as well as a cache containing all loaded textures. This means it has mappings from each name/id to a file and when asked to load a texture with a name/id, it can look up its path and use a "BinaryLoader" to either load the file and create the resource directly, or asynchronously load the file's data into a queue which then can be read from later to create the resources synchronously in the GL context. These factories only return handles.
      Factory classes for assets:
      Much like for resources, these classes contain the definitions for the assets they can load. For example, with the definition the MaterialFactory will know which shader, textures and possibly uniform a certain material has, and with the help of TextureFactory and ShaderFactory, it can retrieve handles to the resources it needs (Shader + Textures), setup itself from XML data (uniform values), and return a created instance of requested material. These factories return actual instances, not handles (but the instances contain handles).
       
       
      Is this a good or commonly used approach? Is this going to bite me in the ass later on? Are there other more preferable approaches? Is this outside of the scope of a 3d renderer and should be on the engine side? I'd love to receive and kind of advice or suggestions!
      Thanks!
    • By nedondev
      I 'm learning how to create game by using opengl with c/c++ coding, so here is my fist game. In video description also have game contain in Dropbox. May be I will make it better in future.
      Thanks.
  • Popular Now