Using Ogre within an SDL window

Problems building or running the engine, queries about how to use features etc.
Post Reply
Creyn
Gnoblar
Posts: 8
Joined: Thu Oct 29, 2009 3:38 am

Using Ogre within an SDL window

Post by Creyn »

Over the past year I've been developing an application in SDL that I now would like to use Ogre in.

I read in http://www.ogre3d.org/wiki/index.php/Using_SDL_Input that the use of currentGLContext would allow me to issue ogre commands within an SDL window.

This is my code:

Code: Select all

	Ogre::NameValuePairList misc;
	misc["currentGLContext"] = Ogre::String("True");

	root->initialise(false);

	RenderWindow *renderWindow = root->createRenderWindow("MainRenderWindow", 1024, 768, false, &misc);
	renderWindow->setVisible(true);
Problem is, this ends up creating a second window and I am left with two black screens (even the original window isn't rendering what is previously was).

I greatly appreciate any help
User avatar
Froyok
Gnoblar
Posts: 23
Joined: Tue Sep 01, 2009 1:04 pm
Location: France
Contact:

Re: Using Ogre within an SDL window

Post by Froyok »

I use Ogre and SDL too, that's my old code (only code into the main, but it's work), I hope that can help you :

Code: Select all

#include "Ogre.h"
#include <SDL/SDL.h>
#include <SDL/SDL_syswm.h>

int main(int argc, char *argv[])
{
//=================================================
//-------------------------------------------------
//=================================================

//setting is an object who read a xml file, just to setting the window
    Setting config;
    SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO);
    SDL_WM_SetCaption(config.getWinName().c_str(), NULL); //name from the config object
    putenv("SDL_VIDEO_WINDOW_POS=center"); //pour centrer la fenêtre/to center the window

    int winSetting; //get fullscreen setting from config object
    if(config.getWinFullscreen())
        winSetting = SDL_FULLSCREEN | SDL_OPENGL;
    else
        winSetting = SDL_OPENGL;

    SDL_SetVideoMode(config.getWinSizeWidth(), config.getWinSizeHeight(), config.getWinColors(), winSetting);
    SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE,16);

    // Create Ogre Root and initialise it (but don't try create a window)
    LogManager* logMgr = new LogManager;
    Log *log = LogManager::getSingleton().createLog("dooce.log", true, true, false);
    Root *root = new Root("plugins.cfg");
    root->restoreConfig();
    RenderWindow *renderWindow = root->initialise(false);

//=================================================
//-------------------------------------------------
//=================================================

    // Set parameters to pass to createRenderWindow()
    NameValuePairList misc;
    misc["vsync"] = String("No"); // TODO: Need to figure out why I need this under Linux...

#ifdef _WINDOWS
   SDL_SysWMinfo wmInfo;
   SDL_VERSION(&wmInfo.version);
   SDL_GetWMInfo(&wmInfo);

   unsigned long winHandle = reinterpret_cast<size_t>(wmInfo.window);
   unsigned long winGlContext = reinterpret_cast<size_t>(wmInfo.hglrc);

   misc["externalWindowHandle"] = StringConverter::toString(winHandle);
   misc["externalGLContext"] = StringConverter::toString(winGlContext);
   misc["externalGLControl"] = String("True");
#else
    misc["currentGLContext"] = String("True");
#endif

    renderWindow = root->createRenderWindow(config.getWinName(), config.getWinSizeWidth(), config.getWinSizeHeight(), config.getWinFullscreen(), &misc);

//=======================================================================================================
//-------------------------------------------------------------------------------------------------------
//=======================================================================================================
//OLD Version

    // Setup resources... manual, I prefer
    TextureManager::getSingleton().setDefaultNumMipmaps(5);
    ResourceGroupManager::getSingleton().addResourceLocation("media", "FileSystem");
    ResourceGroupManager::getSingleton().addResourceLocation("media/materials/scripts", "FileSystem");
    ResourceGroupManager::getSingleton().addResourceLocation("media/materials/textures", "FileSystem");
    ResourceGroupManager::getSingleton().addResourceLocation("media/materials/programs", "FileSystem");
/*
//New version, but make crash for me
    Ogre::ConfigFile cf;
    cf.load("resources.cfg");

    // Go through all sections & settings in the file
    Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator();

    Ogre::String secName, typeName, archName;
    while (seci.hasMoreElements())
    {
        secName = seci.peekNextKey();
        Ogre::ConfigFile::SettingsMultiMap *settings = seci.getNext();
        Ogre::ConfigFile::SettingsMultiMap::iterator i;
        for (i = settings->begin(); i != settings->end(); ++i)
        {
            typeName = i->first;
            archName = i->second;
            Ogre::ResourceGroupManager::getSingleton().addResourceLocation(
                    archName, typeName, secName);
        }
    }*/
//Initialize :
    ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
//=======================================================================================================
//-------------------------------------------------------------------------------------------------------
//=======================================================================================================

    // Create scene manager for displaying an object
    Level level;
    Ogre::SceneType scene_type;
    if(level.getType() == "interior")
        scene_type = ST_INTERIOR;
    else if(level.getType() == "landscape")
        scene_type = ST_EXTERIOR_REAL_FAR;
    else
        scene_type = ST_GENERIC;

    cout << "1" << endl;
    ColourValue fadeColour( 0,0,0 );
    //cout << "colour = " << renderWindow->getViewport(0)->getBackgroundColour() << endl;
    //renderWindow->getViewport(0)->setBackgroundColour( fadeColour );


    SceneManager *sceneManager = root->createSceneManager(ST_EXTERIOR_REAL_FAR/*scene_type*/, "Default SceneManager");
    sceneManager->setShadowTechnique(SHADOWTYPE_STENCIL_ADDITIVE);
	sceneManager->setShadowTextureSize(128);
	sceneManager->setShadowColour(ColourValue(0.6, 0.6, 0.6));

    sceneManager->setFog( FOG_LINEAR, fadeColour, 0.0, 50, 500 );

        Plane plane2;
        plane2.d = 100;
        plane2.normal = Vector3::NEGATIVE_UNIT_Y;

        //sceneManager->setWorldGeometry( "media/terrain.cfg" );

        sceneManager->setSkyPlane( true, plane2, "Examples/CloudySky", 500, 20, true, 0.5, 150, 150 );



		Plane plane;
		plane.normal = Vector3::UNIT_Y;
		plane.d = 100;
		MeshManager::getSingleton().createPlane("Myplane",
			ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, plane,
			1500,1500,20,20,true,1,60,60,Vector3::UNIT_Z);
		Entity* pPlaneEnt = sceneManager->createEntity( "plane", "Myplane" );
		pPlaneEnt->setMaterialName("Examples/Rockwall");
		pPlaneEnt->setCastShadows(false);
		sceneManager->getRootSceneNode()->createChildSceneNode(Vector3(0,80,0/*-50,99,0*/))->attachObject(pPlaneEnt);



    // Create camera and position it
    Camera *camera = sceneManager->createCamera("Camera_tps");
    camera->setPosition(250,5,250);
    camera->lookAt(0,5,0);
    camera->setNearClipDistance(1.0);
    camera->setFarClipDistance(1000.0f);

    // Create viewport and attach the camera to it
    Viewport *viewport = renderWindow->addViewport(camera);
    const Real aspectRatio = Real(viewport->getActualWidth()) / Real(viewport->getActualHeight());
    camera->setAspectRatio(aspectRatio);

    // Light everything up so it is visible
    sceneManager->setAmbientLight(ColourValue(0.0, 0.0, 0.0));
    SceneNode *node = sceneManager->getRootSceneNode()->createChildSceneNode("childNode");
    Light* lightSun = sceneManager->createLight("sun");
    lightSun->setPosition(0,25,250);
    node->attachObject(lightSun);

    Entity* head = sceneManager->createEntity("Head", "models/ogrehead.mesh");
    head->setMaterialName("Examples/EnvMappedRustySteel");
    head->setCastShadows( true );
    node->attachObject(head);

    //head2
    SceneNode *node2 = sceneManager->getRootSceneNode()->createChildSceneNode("childNode2");
    Entity* head2 = sceneManager->createEntity("Head2", "models/ogrehead.mesh");
    head2->setMaterialName("Examples/EnvMappedRustySteel");
    head2->setCastShadows( true );
    node2->attachObject(head2);
    node2->setPosition(-50,0,0);


    //head3
    SceneNode *node3 = sceneManager->getRootSceneNode()->createChildSceneNode("childNode3");
    Entity* head3 = sceneManager->createEntity("Head3", "models/ogrehead.mesh");
    head3->setMaterialName("Examples/EnvMappedRustySteel");
    head3->setCastShadows( true );
    node3->attachObject(head3);
    node3->setPosition(100,0,75);

    //head4
    SceneNode *node4 = sceneManager->getRootSceneNode()->createChildSceneNode("childNode4");
    Entity* head4 = sceneManager->createEntity("Head4", "models/ogrehead.mesh");
    head4->setMaterialName("Examples/EnvMappedRustySteel");
    head4->setCastShadows( true );
    node4->attachObject(head4);
    node4->setPosition(65,0,100);


//=================================================
//-------------------------------------------------
//=================================================

    Camera_tps camera_tps;
    Uint32 last_time,current_time,elapsed_time; //time animation
    Uint32 start_time,stop_time; //frame limit

    //Light
    double pos = 100;
    int dist = 250;
    bool pos_bool = true;

    //SDL
    SDL_Event event;
    bool continuer = true;
    last_time = SDL_GetTicks();

    SDL_WarpMouse(config.getWinSizeWidth()/2, config.getWinSizeHeight()/2);
    SDL_WM_GrabInput(SDL_GRAB_ON);
    SDL_ShowCursor(SDL_DISABLE);

    while(continuer)
    {

        start_time = SDL_GetTicks();
        while(SDL_PollEvent(&event))
        {
            switch(event.type)
            {
                case SDL_QUIT:
                continuer = false;
                break;
                case SDL_KEYDOWN:
                    switch (event.key.keysym.sym)
                    {
                        case SDLK_ESCAPE:
                        continuer = false;
                        break;
                        default:
                        camera_tps.OnKeyboard(event.key);
                        break;
                    }
                break;

                case SDL_KEYUP: //on utilise pas de keyup, on donne donc tout à la caméra
                camera_tps.OnKeyboard(event.key);
                break;

                case SDL_MOUSEMOTION: //la souris est bougée, ça n'interesse que la caméra
                camera_tps.OnMouseMotion(event.motion);
                break;

                case SDL_MOUSEBUTTONUP:
                case SDL_MOUSEBUTTONDOWN: //tous les évenements boutons (up ou down) sont donnés à la caméra
                camera_tps.OnMouseButton(event.button);
                break;
            }
        }

        //timing
        current_time = SDL_GetTicks();
        elapsed_time = current_time - last_time;
        last_time = current_time;

        //input camera
        camera_tps.animate(elapsed_time);
        camera_tps.calcul_angles();
        /*camera->setPosition(
                            camera_tps.get_px(),
                            camera_tps.get_py(),
                            camera_tps.get_pz()
                            );
        camera->lookAt(
                        camera_tps.get_lx(),
                        camera_tps.get_ly(),
                        camera_tps.get_lz()
                        );
        camera_tps.print();*/


        //-----------------------------------------
        lightSun->setPosition(0,50,pos);
        camera->setPosition(pos,5,150);
        camera->lookAt(0,0,0);

        if(pos >= dist)
        {
            pos = dist;
            pos_bool = false;
        }
        else if(pos <= -dist)
        {
            pos = -dist;
            pos_bool = true;
        }

        if(pos_bool)
            pos += 0.055*elapsed_time;
        else
            pos -= 0.055*elapsed_time;
        //-----------------------------------------


        //refresh screen after drawing
        root->renderOneFrame();
        ///#ifdef _WINDOWS
        SDL_GL_SwapBuffers();
        ///#endif

        //SDL_Delay(16);

    }

//=================================================
//-------------------------------------------------
//=================================================


    SDL_WM_GrabInput(SDL_GRAB_OFF);
    SDL_ShowCursor(SDL_ENABLE);
    SDL_WarpMouse(config.getWinSizeWidth()/2, config.getWinSizeHeight()/2);


    delete root;
    root = 0;
    SDL_Quit();

    return 0;
}
If you want more informations, no problem, ask me ! :)
Technical Artist @ Allegorithmic
:) - !Portfolio! - Twitter - LinkedIn
Creyn
Gnoblar
Posts: 8
Joined: Thu Oct 29, 2009 3:38 am

Re: Using Ogre within an SDL window

Post by Creyn »

Thank you very much! I was able to find out what I was doing wrong
User avatar
xadhoom
Minaton
Posts: 973
Joined: Fri Dec 28, 2007 4:35 pm
Location: Germany
x 1

Re: Using Ogre within an SDL window

Post by xadhoom »

Hey Crey!

Would you mind to post your approach here if it works? Do you have any differences to the wiki approach?

@Foryok: Thanks for sharing! Which SDL version, Ogre version?

Thanks, xad
User avatar
Froyok
Gnoblar
Posts: 23
Joined: Tue Sep 01, 2009 1:04 pm
Location: France
Contact:

Re: Using Ogre within an SDL window

Post by Froyok »

xadhoom wrote:@Foryok: Thanks for sharing! Which SDL version, Ogre version?

Thanks, xad
Hay, it's Froyok ! :lol: (Or, it's a joke, with For Yok ! :ninja: )
I use code::blocks, Ogre v1.6.1 [Shoggoth] (22 January 2009), and SDL devel 1.2.14 mingw32.
Technical Artist @ Allegorithmic
:) - !Portfolio! - Twitter - LinkedIn
User avatar
xadhoom
Minaton
Posts: 973
Joined: Fri Dec 28, 2007 4:35 pm
Location: Germany
x 1

Re: Using Ogre within an SDL window

Post by xadhoom »

Ah, I see. Thanks Froyok!

I hope the SDL team finds a nice way to allow external windows in future releases, too (at least their todo file in the repsitory mentiones this for at least a year now...). I tried the SVN version some time ago and did not succeed.

xad
User avatar
Froyok
Gnoblar
Posts: 23
Joined: Tue Sep 01, 2009 1:04 pm
Location: France
Contact:

Re: Using Ogre within an SDL window

Post by Froyok »

xadhoom wrote:Ah, I see. Thanks Froyok!

I hope the SDL team finds a nice way to allow external windows in future releases, too (at least their todo file in the repsitory mentiones this for at least a year now...). I tried the SVN version some time ago and did not succeed.

xad
For multiple window, look SFML.
http://www.sfml-dev.org/index-fr.php

You can use too sfml and ogre as the sdl, but I don't know how sorry.
Technical Artist @ Allegorithmic
:) - !Portfolio! - Twitter - LinkedIn
User avatar
emarcotte
Kobold
Posts: 37
Joined: Thu Nov 20, 2008 9:05 pm
Location: Anywhere but here
Contact:

Re: Using Ogre within an SDL window

Post by emarcotte »

Sorry for digging up an old thread, but I'd love to be able to use SDL.

I posted on the old(er) thread about SDL and ogre 1.6 and at one point I sort of had it working inconsistently at best on linux w/ Nvidia. It seemed like there must have been some sort of odd race condition or something because something like every 3rd run would display graphics.

I just re-tried with a newer project of mine and discovered (after working through a few other issues with viewports/cegui) that CEGUI renders correctly consistently, but any 3d objects do not show up.

I'm curious if you've tried this on linux and had success, basically. If so, any idea what I could be missing? My setup routine looks very similar to yours (as it is basically what was in the old thread).
Linaxys
Gnoblar
Posts: 11
Joined: Tue Apr 21, 2009 4:37 pm

Re: Using Ogre within an SDL window

Post by Linaxys »

Hey, sorry to dig up that thread.
I'm having a problem with the method described in the wiki, it returns nothing :(

But, I've found a solution !
Use SDL 1.3 from their source repository or snapshot.
And do like this :

Code: Select all

	mWindow = mRoot->createRenderWindow("Window", Width, Height, Fullscreen);

	unsigned long hWnd = 0;
	mWindow->getCustomAttribute("WINDOW", &hWnd);

	SDL_CreateWindowFrom((void*)hWnd);
It works nicely, but the input management has changed a lot...
User avatar
emarcotte
Kobold
Posts: 37
Joined: Thu Nov 20, 2008 9:05 pm
Location: Anywhere but here
Contact:

Re: Using Ogre within an SDL window

Post by emarcotte »

Do you know if FBO's work correctly -- that is, for example, using a recent CEGUI checkout?

I recently discovered that FBOs were not working very well with SDL 1.2 + OGRE. When using CEGUI's new Animation support, textures would become corrupted. Additionally, the other RTT methods all showed a mirrored version of the texture while it was animating. Very strange. Wish I could figure it out.
Linaxys
Gnoblar
Posts: 11
Joined: Tue Apr 21, 2009 4:37 pm

Re: Using Ogre within an SDL window

Post by Linaxys »

Hey,

I'm currently using the last version of CEGUI (not checkout, I took from the library source).
And I think it's nicely working, I'm just using SDL for the input, because OIS doesn't return the ASCII code when I release a key.
So I don't know why there would be a problem with CEGUI, I've just used the new "SDL_CreateWindowFrom" from SDL 1.3 code repository to make the SDL input working correctly with Ogre.
User avatar
emarcotte
Kobold
Posts: 37
Joined: Thu Nov 20, 2008 9:05 pm
Location: Anywhere but here
Contact:

Re: Using Ogre within an SDL window

Post by emarcotte »

Do you know which revision you're at from the SDL HG repo? I just did a clone, built it, started converting over my code and it fails on the CreateWindowFrom:

Code: Select all

#0  0x00000032f3e80022 in __strlen_sse2 () from /lib64/libc.so.6
#1  0x00000032f3e7fd46 in strdup () from /lib64/libc.so.6
#2  0x00007ffff7dbc1fa in X11_GetWindowTitle (_this=<value optimized out>, xwindow=88080386) at src/video/x11/SDL_x11window.c:779
#3  0x00007ffff7dbc534 in X11_CreateWindowFrom (_this=0x8be130, window=0x8c1890, data=0x5400002) at src/video/x11/SDL_x11window.c:756
#4  0x00007ffff7da7b05 in SDL_CreateWindowFrom (data=0x5400002) at src/video/SDL_video.c:960
Any ideas?
Linaxys
Gnoblar
Posts: 11
Joined: Tue Apr 21, 2009 4:37 pm

Re: Using Ogre within an SDL window

Post by Linaxys »

Argh, I was doing it under windows, I've downloaded the tar.gz snapshot from August 14th.
But did you try the "currentGLContext" method ?
User avatar
emarcotte
Kobold
Posts: 37
Joined: Thu Nov 20, 2008 9:05 pm
Location: Anywhere but here
Contact:

Re: Using Ogre within an SDL window

Post by emarcotte »

Yes I've been using the currentGLX context method for some time. Only recently I discovered that the FBO support in Ogre was not working correctly when SDL created the window. I have no idea why. I discovered it by using the latest CEGUI which defaults to using render to texture for various operations now. Basically I would get texture corruptions with anything but the "Copy" render to texture mode. Even then I got the texture mirrored in the bottom left corner of the screen.


It would be so great if this would just work. I really would prefer to stick with SDL.
pencilcheck
Kobold
Posts: 38
Joined: Sat Feb 05, 2011 8:08 am

Re: Using Ogre within an SDL window

Post by pencilcheck »

sorry to dig up this old thread too. But I wonder have anyone figured out a way to let ogre render to SDL window without having to move to SDL 1.3 yet?
User avatar
emarcotte
Kobold
Posts: 37
Joined: Thu Nov 20, 2008 9:05 pm
Location: Anywhere but here
Contact:

Re: Using Ogre within an SDL window

Post by emarcotte »

Nope, I got stuck on FBO's being busted. I never got 1.3 to work on linux either.
pencilcheck
Kobold
Posts: 38
Joined: Sat Feb 05, 2011 8:08 am

Re: Using Ogre within an SDL window

Post by pencilcheck »

maybe someone can submit a patch to sdl 1.2 to fix this?
User avatar
Jabberwocky
OGRE Moderator
OGRE Moderator
Posts: 2819
Joined: Mon Mar 05, 2007 11:17 pm
Location: Canada
x 218
Contact:

Re: Using Ogre within an SDL window

Post by Jabberwocky »

emarcotte wrote:Yes I've been using the currentGLX context method for some time. Only recently I discovered that the FBO support in Ogre was not working correctly when SDL created the window. I have no idea why. I discovered it by using the latest CEGUI which defaults to using render to texture for various operations now. Basically I would get texture corruptions with anything but the "Copy" render to texture mode. Even then I got the texture mirrored in the bottom left corner of the screen.


It would be so great if this would just work. I really would prefer to stick with SDL.
I've switched to using SDL2.0 with ogre (via "currentGLContext"). I'm also using CEGUI. Everything seems to work fine. Here's a separate thread on it.
Image
User avatar
emarcotte
Kobold
Posts: 37
Joined: Thu Nov 20, 2008 9:05 pm
Location: Anywhere but here
Contact:

Re: Using Ogre within an SDL window

Post by emarcotte »

Cool. I was just thinking about trying sdl again yesterday. Will check that thread!
TTimo
Gnoblar
Posts: 8
Joined: Wed Dec 28, 2011 9:39 pm

Re: Using Ogre within an SDL window

Post by TTimo »

If you want some example code, es_core does SDL2+Ogre initialization on Windows, GNU/Linux and MacOS X: https://github.com/TTimo/es_core/blob/3 ... n.cpp#L121
scrawl
OGRE Expert User
OGRE Expert User
Posts: 1119
Joined: Sat Jan 01, 2011 7:57 pm
x 216

Re: Using Ogre within an SDL window

Post by scrawl »

That looks great TTimo, but have you found a way to get it to work with the D3D renderers? While I'm a linux guy myself and convinced that GL is the future, we can't drop the DX RSes in our project just yet. So has anyone had success with Ogre3d+D3D+SDL2?
TTimo
Gnoblar
Posts: 8
Joined: Wed Dec 28, 2011 9:39 pm

Re: Using Ogre within an SDL window

Post by TTimo »

Ah sorry I really haven't tried anything with D3D, for the reasons you mention :)
Post Reply