<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2000-2012 Tor<NAME> Ltd

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/

#include "OgreException.h"
#include "OgreLogManager.h"
#include "OgreStringConverter.h"
#include "OgreRoot.h"

#include "OgreGLXGLSupport.h"
#include "OgreGLXUtils.h"
#include "OgreGLXWindow.h"
#include "OgreGLXRenderTexture.h"

#include <X11/extensions/Xrandr.h>

GLenum glxewContextInit(Ogre::GLSupport *glSupport);

static Display *_currentDisplay;
static Display *_getCurrentDisplay(void) { return _currentDisplay; }

namespace Ogre 
{
	//-------------------------------------------------------------------------------------------------//
	template<class C> void remove_duplicates(C& c)
	{
		std::sort(c.begin(), c.end());
		typename C::iterator p = std::unique(c.begin(), c.end());
		c.erase(p, c.end());
	}

	//-------------------------------------------------------------------------------------------------//
	GLXGLSupport::GLXGLSupport() : mGLDisplay(0), mXDisplay(0)
	{
		// A connection that might be shared with the application for GL rendering:
		mGLDisplay = getGLDisplay();
		
		// A connection that is NOT shared to enable independent event processing:
		mXDisplay  = getXDisplay();
		
		int dummy;
		
		if (XQueryExtension(mXDisplay, "RANDR", &dummy, &dummy, &dummy))
		{
			XRRScreenConfiguration *screenConfig;
			
			screenConfig = XRRGetScreenInfo(mXDisplay, DefaultRootWindow(mXDisplay));
			
			if (screenConfig) 
			{
				XRRScreenSize *screenSizes;
				int nSizes = 0;
				Rotation currentRotation;
				int currentSizeID = XRRConfigCurrentConfiguration(screenConfig, &currentRotation);
				
				screenSizes = XRRConfigSizes(screenConfig, &nSizes);
				
				mCurrentMode.first.first = screenSizes[currentSizeID].width;
				mCurrentMode.first.second = screenSizes[currentSizeID].height;
				mCurrentMode.second = XRRConfigCurrentRate(screenConfig);
				
				mOriginalMode = mCurrentMode;
				
				for(int sizeID = 0; sizeID < nSizes; sizeID++) 
				{
					short *rates;
					int nRates = 0;
					
					rates = XRRConfigRates(screenConfig, sizeID, &nRates);
					
					for (int rate = 0; rate < nRates; rate++)
					{
						VideoMode mode;
						
						mode.first.first = screenSizes[sizeID].width;
						mode.first.second = screenSizes[sizeID].height;
						mode.second = rates[rate];
						
						mVideoModes.push_back(mode);
					}
				}
				XRRFreeScreenConfigInfo(screenConfig);
			}
		}
		else
		{
			mCurrentMode.first.first = DisplayWidth(mXDisplay, DefaultScreen(mXDisplay));
			mCurrentMode.first.second = DisplayHeight(mXDisplay, DefaultScreen(mXDisplay));
			mCurrentMode.second = 0;
			
			mOriginalMode = mCurrentMode;
			
			mVideoModes.push_back(mCurrentMode);
		}
		
		GLXFBConfig *fbConfigs;
		int config, nConfigs = 0;
		
		fbConfigs = chooseFBConfig(NULL, &nConfigs);
		
		for (config = 0; config < nConfigs; config++)
		{
			int caveat, samples;
			
			getFBConfigAttrib (fbConfigs[config], GLX_CONFIG_CAVEAT, &caveat);
			
			if (caveat != GLX_SLOW_CONFIG)
			{
				getFBConfigAttrib (fbConfigs[config], GLX_SAMPLES, &samples);
				mSampleLevels.push_back(StringConverter::toString(samples));
			}
		}
		
		XFree (fbConfigs);
		
		remove_duplicates(mSampleLevels);
	}

	//-------------------------------------------------------------------------------------------------//
	GLXGLSupport::~GLXGLSupport() 
	{
		if (mXDisplay)
			XCloseDisplay(mXDisplay);
		
		if (! mIsExternalDisplay && mGLDisplay)
			XCloseDisplay(mGLDisplay);
	}
	
	//-------------------------------------------------------------------------------------------------//
	void GLXGLSupport::addConfig(void) 
	{
		ConfigOption optFullScreen;
		ConfigOption optVideoMode;
		ConfigOption optDisplayFrequency;
		ConfigOption optVSync;
		ConfigOption optFSAA;
		ConfigOption optRTTMode;
		ConfigOption optSRGB;
#ifdef RTSHADER_SYSTEM_BUILD_CORE_SHADERS
		ConfigOption optEnableFixedPipeline;
#endif
		
		optFullScreen.name = "Full Screen";
		optFullScreen.immutable = false;
		
		optVideoMode.name = "Video Mode";
		optVideoMode.immutable = false;
		
		optDisplayFrequency.name = "Display Frequency";
		optDisplayFrequency.immutable = false;
		
		optVSync.name = "VSync";
		optVSync.immutable = false;
		
		optFSAA.name = "FSAA";
		optFSAA.immutable = false;
		
		optRTTMode.name = "RTT Preferred Mode";
		optRTTMode.immutable = false;
		
		optSRGB.name = "sRGB Gamma Conversion";
		optSRGB.immutable = false;

#ifdef RTSHADER_SYSTEM_BUILD_CORE_SHADERS
		optEnableFixedPipeline.name = "Fixed Pipeline Enabled";
		optEnableFixedPipeline.possibleValues.push_back( "Yes" );
		optEnableFixedPipeline.possibleValues.push_back( "No" );
		optEnableFixedPipeline.currentValue = "Yes";
		optEnableFixedPipeline.immutable = false;
#endif

		optFullScreen.possibleValues.push_back("No");
		optFullScreen.possibleValues.push_back("Yes");
		
		optFullScreen.currentValue = optFullScreen.possibleValues[1];
		
		VideoModes::const_iterator value = mVideoModes.begin();
		VideoModes::const_iterator end = mVideoModes.end();
		
		for (; value != end; value++)
		{
			String mode = StringConverter::toString(value->first.first,4) + " x " + StringConverter::toString(value->first.second,4);
			
			optVideoMode.possibleValues.push_back(mode);
		}
		
		remove_duplicates(optVideoMode.possibleValues);
		
		optVideoMode.currentValue = StringConverter::toString(mCurrentMode.first.first,4) + " x " + StringConverter::toString(mCurrentMode.first.second,4);
		
		refreshConfig();
		
		if (GLXEW_SGI_swap_control)
		{
			optVSync.possibleValues.push_back("No");
			optVSync.possibleValues.push_back("Yes");
			
			optVSync.currentValue = optVSync.possibleValues[0];
		}
		
		// Is it worth checking for GL_EXT_framebuffer_object ?
		optRTTMode.possibleValues.push_back("FBO");
		
		if (GLXEW_VERSION_1_3)
		{
			optRTTMode.possibleValues.push_back("PBuffer");
		}
		
		optRTTMode.possibleValues.push_back("Copy");
		
		optRTTMode.currentValue = optRTTMode.possibleValues[0];
		
		if (! mSampleLevels.empty())
		{
			StringVector::const_iterator value = mSampleLevels.begin();
			StringVector::const_iterator end = mSampleLevels.end();
			
			for (; value != end; value++)
			{
				optFSAA.possibleValues.push_back(*value);
			}
			
			optFSAA.currentValue = optFSAA.possibleValues[0];
		}
		
		if (GLXEW_EXT_framebuffer_sRGB)
		{	
			optSRGB.possibleValues.push_back("No");
			optSRGB.possibleValues.push_back("Yes");

			optSRGB.currentValue = optSRGB.possibleValues[0];
		}

		mOptions[optFullScreen.name] = optFullScreen;
		mOptions[optVideoMode.name] = optVideoMode;
		mOptions[optDisplayFrequency.name] = optDisplayFrequency;
		mOptions[optVSync.name] = optVSync;
		mOptions[optRTTMode.name] = optRTTMode;
		mOptions[optFSAA.name] = optFSAA;
		mOptions[optSRGB.name] = optSRGB;
#ifdef RTSHADER_SYSTEM_BUILD_CORE_SHADERS
		mOptions[optEnableFixedPipeline.name] = optEnableFixedPipeline;
#endif
		
		refreshConfig();
	}
	
	//-------------------------------------------------------------------------------------------------//
	void GLXGLSupport::refreshConfig(void) 
	{
		ConfigOptionMap::iterator optVideoMode = mOptions.find("Video Mode");
		ConfigOptionMap::iterator optDisplayFrequency = mOptions.find("Display Frequency");
		
		if (optVideoMode != mOptions.end() && optDisplayFrequency != mOptions.end())
		{
			optDisplayFrequency->second.possibleValues.clear();
			
			VideoModes::const_iterator value = mVideoModes.begin();
			VideoModes::const_iterator end = mVideoModes.end();
			
			for (; value != end; value++)
			{
				String mode = StringConverter::toString(value->first.first,4) + " x " + StringConverter::toString(value->first.second,4);
				
				if (mode == optVideoMode->second.currentValue)
				{
					String frequency = StringConverter::toString(value->second) + " Hz";
					
					optDisplayFrequency->second.possibleValues.push_back(frequency);
				}
			}
			
			if (! optDisplayFrequency->second.possibleValues.empty())
			{
				optDisplayFrequency->second.currentValue = optDisplayFrequency->second.possibleValues[0];
			}
			else
			{
				optVideoMode->second.currentValue = StringConverter::toString(mVideoModes[0].first.first,4) + " x " + StringConverter::toString(mVideoModes[0].first.second,4);
				optDisplayFrequency->second.currentValue = StringConverter::toString(mVideoModes[0].second) + " Hz";
			}
		}
	}
	
	//-------------------------------------------------------------------------------------------------//
	void GLXGLSupport::setConfigOption(const String &name, const String &value)
	{
		ConfigOptionMap::iterator option = mOptions.find(name);
		
		if(option == mOptions.end())
		{
			OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, "Option named " + name + " does not exist.", "GLXGLSupport::setConfigOption" );
		}
		else
		{
			option->second.currentValue = value;
		}
		
		if (name == "Video Mode")
		{
			ConfigOptionMap::iterator opt;
			if((opt = mOptions.find("Full Screen")) != mOptions.end())
			{
				if (opt->second.currentValue == "Yes")
					refreshConfig();
			}
		}
	}

	//-------------------------------------------------------------------------------------------------//
	String GLXGLSupport::validateConfig(void) 
	{
		// TO DO
		return StringUtil::BLANK;
	}

	//-------------------------------------------------------------------------------------------------//
	RenderWindow* GLXGLSupport::createWindow(bool autoCreateWindow, GLRenderSystem* renderSystem, const String& windowTitle) 
	{
		RenderWindow *window = 0;
		
		if (autoCreateWindow) 
		{
			ConfigOptionMap::iterator opt;
			ConfigOptionMap::iterator end = mOptions.end();
			NameValuePairList miscParams;
			
			bool fullscreen = false;
			uint w = 800, h = 600;
			
			if((opt = mOptions.find("Full Screen")) != end)
				fullscreen = (opt->second.currentValue == "Yes");
			
			if((opt = mOptions.find("Display Frequency")) != end)
				miscParams["displayFrequency"] = opt->second.currentValue;
			
			if((opt = mOptions.find("Video Mode")) != end)
			{
				String val = opt->second.currentValue;
				String::size_type pos = val.find('x');
				
				if (pos != String::npos)
				{
					w = StringConverter::parseUnsignedInt(val.substr(0, pos));
					h = StringConverter::parseUnsignedInt(val.substr(pos + 1));
				}
			}
			
			if((opt = mOptions.find("FSAA")) != end)
				miscParams["FSAA"] = opt->second.currentValue;
			
			if((opt = mOptions.find("VSync")) != end)
				miscParams["vsync"] = opt->second.currentValue;

			if((opt = mOptions.find("sRGB Gamma Conversion")) != end)
				miscParams["gamma"] = opt->second.currentValue;
			
#ifdef RTSHADER_SYSTEM_BUILD_CORE_SHADERS
			opt = mOptions.find("Fixed Pipeline Enabled");
			if (opt == mOptions.end())
				OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Can't find Fixed Pipeline enabled options!", "Win32GLSupport::createWindow");
			bool enableFixedPipeline = (opt->second.currentValue == "Yes");
			renderSystem->setFixedPipelineEnabled(enableFixedPipeline);
#endif

			window = renderSystem->_createRenderWindow(windowTitle, w, h, fullscreen, &miscParams);
		} 
		
		return window;
	}
	
	//-------------------------------------------------------------------------------------------------//
	RenderWindow* GLXGLSupport::newWindow(const String &name, unsigned int width, unsigned int height, bool fullScreen, const NameValuePairList *miscParams)
	{
		GLXWindow* window = new GLXWindow(this);
		
		window->create(name, width, height, fullScreen, miscParams);
		
		return window;
	}

	//-------------------------------------------------------------------------------------------------//
	GLPBuffer *GLXGLSupport::createPBuffer(PixelComponentType format, size_t width, size_t height)
	{
		return new GLXPBuffer(this, format, width, height);
	}
	
	//-------------------------------------------------------------------------------------------------//
	void GLXGLSupport::start() 
	{
		LogManager::getSingleton().logMessage(
			"******************************\n"
			"*** Starting GLX Subsystem ***\n"
			"******************************");
	}

	//-------------------------------------------------------------------------------------------------//
	void GLXGLSupport::stop() 
	{
		LogManager::getSingleton().logMessage(
			"******************************\n"
			"*** Stopping GLX Subsystem ***\n"
			"******************************");
	}

	//-------------------------------------------------------------------------------------------------//
	void* GLXGLSupport::getProcAddress(const String& procname) {
		return (void*)glXGetProcAddressARB((const GLubyte*)procname.c_str());
	}
	
	//-------------------------------------------------------------------------------------------------//
	void GLXGLSupport::initialiseExtensions(void)
	{
		assert (mGLDisplay);
		
		GLSupport::initialiseExtensions();
		
		const char* extensionsString;
		
		// This is more realistic than using glXGetClientString:
		extensionsString = glXQueryExtensionsString(mGLDisplay, DefaultScreen(mGLDisplay));
		
		LogManager::getSingleton().stream() << "Supported GLX extensions: " << extensionsString;
		
		std::stringstream ext;
		String instr;
		
		ext << extensionsString;
		
		while(ext >> instr)
		{
			extensionList.insert(instr);
		}
	}

	//-------------------------------------------------------------------------------------------------//
	// Returns the FBConfig behind a GLXContext
   
	GLXFBConfig GLXGLSupport::getFBConfigFromContext(::GLXContext context)
	{
		GLXFBConfig fbConfig = 0;
		
		if (GLXEW_VERSION_1_3)
		{
			int fbConfigAttrib[] = {
				GLX_FBCONFIG_ID, 0, 
				None
			};
			GLXFBConfig *fbConfigs;
			int nElements = 0;
			
			glXQueryContext(mGLDisplay, context, GLX_FBCONFIG_ID, &fbConfigAttrib[1]);
			fbConfigs = glXChooseFBConfig(mGLDisplay, DefaultScreen(mGLDisplay), fbConfigAttrib, &nElements);
			
			if (nElements)
			{
				fbConfig = fbConfigs[0];
				XFree(fbConfigs);
			}
		}
		else if (GLXEW_EXT_import_context && GLXEW_SGIX_fbconfig)
		{
			VisualID visualid;
			
			if (glXQueryContextInfoEXT(mGLDisplay, context, GLX_VISUAL_ID, (int*)&visualid))
			{
				fbConfig = getFBConfigFromVisualID(visualid);
			}
		}
	
		return fbConfig;
	}
	
	//-------------------------------------------------------------------------------------------------//
	// Returns the FBConfig behind a GLXDrawable, or returns 0 when 
	//   missing GLX_SGIX_fbconfig and drawable is Window (unlikely), OR
	//   missing GLX_VERSION_1_3 and drawable is a GLXPixmap (possible).
	
	GLXFBConfig GLXGLSupport::getFBConfigFromDrawable(GLXDrawable drawable, unsigned int *width, unsigned int *height)
	{
		GLXFBConfig fbConfig = 0;
		
		if (GLXEW_VERSION_1_3)
		{
			int fbConfigAttrib[] = {
				GLX_FBCONFIG_ID, 0, 
				None
			};
			GLXFBConfig *fbConfigs;
			int nElements = 0;
			
			glXQueryDrawable (mGLDisplay, drawable, GLX_FBCONFIG_ID, (unsigned int*)&fbConfigAttrib[1]);
			
			fbConfigs = glXChooseFBConfig(mGLDisplay, DefaultScreen(mGLDisplay), fbConfigAttrib, &nElements);
			
			if (nElements)
			{
				fbConfig = fbConfigs[0];
				XFree (fbConfigs);
				
				glXQueryDrawable(mGLDisplay, drawable, GLX_WIDTH, width);
				glXQueryDrawable(mGLDisplay, drawable, GLX_HEIGHT, height);
			}
		}
		
		if (! fbConfig && GLXEW_SGIX_fbconfig)
		{
			XWindowAttributes windowAttrib;
			
			if (XGetWindowAttributes(mGLDisplay, drawable, &windowAttrib))
			{
				VisualID visualid = XVisualIDFromVisual(windowAttrib.visual);
				
				fbConfig = getFBConfigFromVisualID(visualid);
				
				*width = windowAttrib.width;
				*height = windowAttrib.height;
			}
		}
		
		return fbConfig;
	}

	//-------------------------------------------------------------------------------------------------//
	// Finds a GLXFBConfig compatible with a given VisualID.

	GLXFBConfig GLXGLSupport::getFBConfigFromVisualID(VisualID visualid)
	{
		GLXFBConfig fbConfig = 0;
		
		if (GLXEW_SGIX_fbconfig && glXGetFBConfigFromVisualSGIX)
		{
			XVisualInfo visualInfo;
			
			visualInfo.screen = DefaultScreen(mGLDisplay);
			visualInfo.depth = DefaultDepth(mGLDisplay, DefaultScreen(mGLDisplay));
			visualInfo.visualid = visualid;
			
			fbConfig = glXGetFBConfigFromVisualSGIX(mGLDisplay, &visualInfo);
		}
		
		if (! fbConfig)
		{
			int minAttribs[] = {
				GLX_DRAWABLE_TYPE,  GLX_WINDOW_BIT || GLX_PIXMAP_BIT,
				GLX_RENDER_TYPE,	GLX_RGBA_BIT,
				GLX_RED_SIZE,	   1,
				GLX_BLUE_SIZE,	  1,
				GLX_GREEN_SIZE,	 1,
				None
			};
			int nConfigs = 0;
			
			GLXFBConfig *fbConfigs = chooseFBConfig(minAttribs, &nConfigs);
			
			for (int i = 0; i < nConfigs && ! fbConfig; i++)
			{
				XVisualInfo *visualInfo = getVisualFromFBConfig(fbConfigs[i]);
				
				if (visualInfo->visualid == visualid)
					fbConfig = fbConfigs[i];
				
				XFree(visualInfo);
			}

			XFree(fbConfigs);
		}
		
		return fbConfig;
	}

	//-------------------------------------------------------------------------------------------------//
	// A helper class for the implementation of selectFBConfig

	class FBConfigAttribs
	{
	public:
		FBConfigAttribs(const int* attribs)
		{
			fields[GLX_CONFIG_CAVEAT] = GLX_NONE;
			
			for (int i = 0; attribs[2*i]; i++)
			{
				fields[attribs[2*i]] = attribs[2*i+1];
			}
		}

		void load(GLXGLSupport* const glSupport, GLXFBConfig fbConfig)
		{
			std::map<int,int>::iterator it;
			
			for (it = fields.begin(); it != fields.end(); it++)
			{
				it->second = 0;

				glSupport->getFBConfigAttrib(fbConfig, it->first, &it->second);
			}
		}

		bool operator>(FBConfigAttribs& alternative)
		{
			// Caveats are best avoided, but might be needed for anti-aliasing
			
			if (fields[GLX_CONFIG_CAVEAT] != alternative.fields[GLX_CONFIG_CAVEAT])
			{
				if (fields[GLX_CONFIG_CAVEAT] == GLX_SLOW_CONFIG)
					return false;
				
				if (fields.find(GLX_SAMPLES) != fields.end() && 
					fields[GLX_SAMPLES] < alternative.fields[GLX_SAMPLES])
					return false;
			}
			
			std::map<int,int>::iterator it;
			
			for (it = fields.begin(); it != fields.end(); it++)
			{
				if (it->first != GLX_CONFIG_CAVEAT && fields[it->first] > alternative.fields[it->first])
					return true;
			}
			
			return false;
		}
		
		std::map<int,int> fields;
	};

	//-------------------------------------------------------------------------------------------------//
	// Finds an FBConfig that possesses each of minAttribs and gets as close 
	// as possible to each of the maxAttribs without exceeding them.
	// Resembles glXChooseFBConfig, but is forgiving to platforms
	// that do not support the attributes listed in the maxAttribs.
	
	GLXFBConfig GLXGLSupport::selectFBConfig (const int* minAttribs, const int *maxAttribs)
	{
		GLXFBConfig *fbConfigs;
		GLXFBConfig fbConfig = 0;
		int config, nConfigs = 0;
		
		fbConfigs = chooseFBConfig(minAttribs, &nConfigs);
		
		// this is a fix for cases where chooseFBConfig is not supported.
		// On the 10/2010 chooseFBConfig was not supported on VirtualBox
		// http://www.virtualbox.org/ticket/7195
		if (!nConfigs) 		
		{ 		    
			fbConfigs = glXGetFBConfigs(mGLDisplay, DefaultScreen(mGLDisplay), &nConfigs); 		
		}
		
		if (! nConfigs) 
			return 0;
		
		fbConfig = fbConfigs[0];
		
		if (maxAttribs)
		{
			FBConfigAttribs maximum(maxAttribs);
			FBConfigAttribs best(maxAttribs);
			FBConfigAttribs candidate(maxAttribs);
			
			best.load(this, fbConfig);
			
			for (config = 1; config < nConfigs; config++)
			{
				candidate.load(this, fbConfigs[config]);
				
				if (candidate > maximum)
					continue;
				
				if (candidate > best)
				{
					fbConfig = fbConfigs[config];		
					
					best.load(this, fbConfig);
				}
			}
		}

		XFree (fbConfigs);
		return fbConfig;
	}

	//-------------------------------------------------------------------------------------------------//
	bool GLXGLSupport::loadIcon(const std::string &name, Pixmap *pixmap, Pixmap *bitmap)
	{
		Image image;
		int width, height;
		char* imageData;
		
		try 
		{<commit_msg>added check for icon existance in bool GLXGLSupport<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2000-2012 <NAME>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/

#include "OgreException.h"
#include "OgreLogManager.h"
#include "OgreStringConverter.h"
#include "OgreRoot.h"

#include "OgreGLXGLSupport.h"
#include "OgreGLXUtils.h"
#include "OgreGLXWindow.h"
#include "OgreGLXRenderTexture.h"

#include <X11/extensions/Xrandr.h>

GLenum glxewContextInit(Ogre::GLSupport *glSupport);

static Display *_currentDisplay;
static Display *_getCurrentDisplay(void) { return _currentDisplay; }

namespace Ogre 
{
	//-------------------------------------------------------------------------------------------------//
	template<class C> void remove_duplicates(C& c)
	{
		std::sort(c.begin(), c.end());
		typename C::iterator p = std::unique(c.begin(), c.end());
		c.erase(p, c.end());
	}

	//-------------------------------------------------------------------------------------------------//
	GLXGLSupport::GLXGLSupport() : mGLDisplay(0), mXDisplay(0)
	{
		// A connection that might be shared with the application for GL rendering:
		mGLDisplay = getGLDisplay();
		
		// A connection that is NOT shared to enable independent event processing:
		mXDisplay  = getXDisplay();
		
		int dummy;
		
		if (XQueryExtension(mXDisplay, "RANDR", &dummy, &dummy, &dummy))
		{
			XRRScreenConfiguration *screenConfig;
			
			screenConfig = XRRGetScreenInfo(mXDisplay, DefaultRootWindow(mXDisplay));
			
			if (screenConfig) 
			{
				XRRScreenSize *screenSizes;
				int nSizes = 0;
				Rotation currentRotation;
				int currentSizeID = XRRConfigCurrentConfiguration(screenConfig, &currentRotation);
				
				screenSizes = XRRConfigSizes(screenConfig, &nSizes);
				
				mCurrentMode.first.first = screenSizes[currentSizeID].width;
				mCurrentMode.first.second = screenSizes[currentSizeID].height;
				mCurrentMode.second = XRRConfigCurrentRate(screenConfig);
				
				mOriginalMode = mCurrentMode;
				
				for(int sizeID = 0; sizeID < nSizes; sizeID++) 
				{
					short *rates;
					int nRates = 0;
					
					rates = XRRConfigRates(screenConfig, sizeID, &nRates);
					
					for (int rate = 0; rate < nRates; rate++)
					{
						VideoMode mode;
						
						mode.first.first = screenSizes[sizeID].width;
						mode.first.second = screenSizes[sizeID].height;
						mode.second = rates[rate];
						
						mVideoModes.push_back(mode);
					}
				}
				XRRFreeScreenConfigInfo(screenConfig);
			}
		}
		else
		{
			mCurrentMode.first.first = DisplayWidth(mXDisplay, DefaultScreen(mXDisplay));
			mCurrentMode.first.second = DisplayHeight(mXDisplay, DefaultScreen(mXDisplay));
			mCurrentMode.second = 0;
			
			mOriginalMode = mCurrentMode;
			
			mVideoModes.push_back(mCurrentMode);
		}
		
		GLXFBConfig *fbConfigs;
		int config, nConfigs = 0;
		
		fbConfigs = chooseFBConfig(NULL, &nConfigs);
		
		for (config = 0; config < nConfigs; config++)
		{
			int caveat, samples;
			
			getFBConfigAttrib (fbConfigs[config], GLX_CONFIG_CAVEAT, &caveat);
			
			if (caveat != GLX_SLOW_CONFIG)
			{
				getFBConfigAttrib (fbConfigs[config], GLX_SAMPLES, &samples);
				mSampleLevels.push_back(StringConverter::toString(samples));
			}
		}
		
		XFree (fbConfigs);
		
		remove_duplicates(mSampleLevels);
	}

	//-------------------------------------------------------------------------------------------------//
	GLXGLSupport::~GLXGLSupport() 
	{
		if (mXDisplay)
			XCloseDisplay(mXDisplay);
		
		if (! mIsExternalDisplay && mGLDisplay)
			XCloseDisplay(mGLDisplay);
	}
	
	//-------------------------------------------------------------------------------------------------//
	void GLXGLSupport::addConfig(void) 
	{
		ConfigOption optFullScreen;
		ConfigOption optVideoMode;
		ConfigOption optDisplayFrequency;
		ConfigOption optVSync;
		ConfigOption optFSAA;
		ConfigOption optRTTMode;
		ConfigOption optSRGB;
#ifdef RTSHADER_SYSTEM_BUILD_CORE_SHADERS
		ConfigOption optEnableFixedPipeline;
#endif
		
		optFullScreen.name = "Full Screen";
		optFullScreen.immutable = false;
		
		optVideoMode.name = "Video Mode";
		optVideoMode.immutable = false;
		
		optDisplayFrequency.name = "Display Frequency";
		optDisplayFrequency.immutable = false;
		
		optVSync.name = "VSync";
		optVSync.immutable = false;
		
		optFSAA.name = "FSAA";
		optFSAA.immutable = false;
		
		optRTTMode.name = "RTT Preferred Mode";
		optRTTMode.immutable = false;
		
		optSRGB.name = "sRGB Gamma Conversion";
		optSRGB.immutable = false;

#ifdef RTSHADER_SYSTEM_BUILD_CORE_SHADERS
		optEnableFixedPipeline.name = "Fixed Pipeline Enabled";
		optEnableFixedPipeline.possibleValues.push_back( "Yes" );
		optEnableFixedPipeline.possibleValues.push_back( "No" );
		optEnableFixedPipeline.currentValue = "Yes";
		optEnableFixedPipeline.immutable = false;
#endif

		optFullScreen.possibleValues.push_back("No");
		optFullScreen.possibleValues.push_back("Yes");
		
		optFullScreen.currentValue = optFullScreen.possibleValues[1];
		
		VideoModes::const_iterator value = mVideoModes.begin();
		VideoModes::const_iterator end = mVideoModes.end();
		
		for (; value != end; value++)
		{
			String mode = StringConverter::toString(value->first.first,4) + " x " + StringConverter::toString(value->first.second,4);
			
			optVideoMode.possibleValues.push_back(mode);
		}
		
		remove_duplicates(optVideoMode.possibleValues);
		
		optVideoMode.currentValue = StringConverter::toString(mCurrentMode.first.first,4) + " x " + StringConverter::toString(mCurrentMode.first.second,4);
		
		refreshConfig();
		
		if (GLXEW_SGI_swap_control)
		{
			optVSync.possibleValues.push_back("No");
			optVSync.possibleValues.push_back("Yes");
			
			optVSync.currentValue = optVSync.possibleValues[0];
		}
		
		// Is it worth checking for GL_EXT_framebuffer_object ?
		optRTTMode.possibleValues.push_back("FBO");
		
		if (GLXEW_VERSION_1_3)
		{
			optRTTMode.possibleValues.push_back("PBuffer");
		}
		
		optRTTMode.possibleValues.push_back("Copy");
		
		optRTTMode.currentValue = optRTTMode.possibleValues[0];
		
		if (! mSampleLevels.empty())
		{
			StringVector::const_iterator value = mSampleLevels.begin();
			StringVector::const_iterator end = mSampleLevels.end();
			
			for (; value != end; value++)
			{
				optFSAA.possibleValues.push_back(*value);
			}
			
			optFSAA.currentValue = optFSAA.possibleValues[0];
		}
		
		if (GLXEW_EXT_framebuffer_sRGB)
		{	
			optSRGB.possibleValues.push_back("No");
			optSRGB.possibleValues.push_back("Yes");

			optSRGB.currentValue = optSRGB.possibleValues[0];
		}

		mOptions[optFullScreen.name] = optFullScreen;
		mOptions[optVideoMode.name] = optVideoMode;
		mOptions[optDisplayFrequency.name] = optDisplayFrequency;
		mOptions[optVSync.name] = optVSync;
		mOptions[optRTTMode.name] = optRTTMode;
		mOptions[optFSAA.name] = optFSAA;
		mOptions[optSRGB.name] = optSRGB;
#ifdef RTSHADER_SYSTEM_BUILD_CORE_SHADERS
		mOptions[optEnableFixedPipeline.name] = optEnableFixedPipeline;
#endif
		
		refreshConfig();
	}
	
	//-------------------------------------------------------------------------------------------------//
	void GLXGLSupport::refreshConfig(void) 
	{
		ConfigOptionMap::iterator optVideoMode = mOptions.find("Video Mode");
		ConfigOptionMap::iterator optDisplayFrequency = mOptions.find("Display Frequency");
		
		if (optVideoMode != mOptions.end() && optDisplayFrequency != mOptions.end())
		{
			optDisplayFrequency->second.possibleValues.clear();
			
			VideoModes::const_iterator value = mVideoModes.begin();
			VideoModes::const_iterator end = mVideoModes.end();
			
			for (; value != end; value++)
			{
				String mode = StringConverter::toString(value->first.first,4) + " x " + StringConverter::toString(value->first.second,4);
				
				if (mode == optVideoMode->second.currentValue)
				{
					String frequency = StringConverter::toString(value->second) + " Hz";
					
					optDisplayFrequency->second.possibleValues.push_back(frequency);
				}
			}
			
			if (! optDisplayFrequency->second.possibleValues.empty())
			{
				optDisplayFrequency->second.currentValue = optDisplayFrequency->second.possibleValues[0];
			}
			else
			{
				optVideoMode->second.currentValue = StringConverter::toString(mVideoModes[0].first.first,4) + " x " + StringConverter::toString(mVideoModes[0].first.second,4);
				optDisplayFrequency->second.currentValue = StringConverter::toString(mVideoModes[0].second) + " Hz";
			}
		}
	}
	
	//-------------------------------------------------------------------------------------------------//
	void GLXGLSupport::setConfigOption(const String &name, const String &value)
	{
		ConfigOptionMap::iterator option = mOptions.find(name);
		
		if(option == mOptions.end())
		{
			OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, "Option named " + name + " does not exist.", "GLXGLSupport::setConfigOption" );
		}
		else
		{
			option->second.currentValue = value;
		}
		
		if (name == "Video Mode")
		{
			ConfigOptionMap::iterator opt;
			if((opt = mOptions.find("Full Screen")) != mOptions.end())
			{
				if (opt->second.currentValue == "Yes")
					refreshConfig();
			}
		}
	}

	//-------------------------------------------------------------------------------------------------//
	String GLXGLSupport::validateConfig(void) 
	{
		// TO DO
		return StringUtil::BLANK;
	}

	//-------------------------------------------------------------------------------------------------//
	RenderWindow* GLXGLSupport::createWindow(bool autoCreateWindow, GLRenderSystem* renderSystem, const String& windowTitle) 
	{
		RenderWindow *window = 0;
		
		if (autoCreateWindow) 
		{
			ConfigOptionMap::iterator opt;
			ConfigOptionMap::iterator end = mOptions.end();
			NameValuePairList miscParams;
			
			bool fullscreen = false;
			uint w = 800, h = 600;
			
			if((opt = mOptions.find("Full Screen")) != end)
				fullscreen = (opt->second.currentValue == "Yes");
			
			if((opt = mOptions.find("Display Frequency")) != end)
				miscParams["displayFrequency"] = opt->second.currentValue;
			
			if((opt = mOptions.find("Video Mode")) != end)
			{
				String val = opt->second.currentValue;
				String::size_type pos = val.find('x');
				
				if (pos != String::npos)
				{
					w = StringConverter::parseUnsignedInt(val.substr(0, pos));
					h = StringConverter::parseUnsignedInt(val.substr(pos + 1));
				}
			}
			
			if((opt = mOptions.find("FSAA")) != end)
				miscParams["FSAA"] = opt->second.currentValue;
			
			if((opt = mOptions.find("VSync")) != end)
				miscParams["vsync"] = opt->second.currentValue;

			if((opt = mOptions.find("sRGB Gamma Conversion")) != end)
				miscParams["gamma"] = opt->second.currentValue;
			
#ifdef RTSHADER_SYSTEM_BUILD_CORE_SHADERS
			opt = mOptions.find("Fixed Pipeline Enabled");
			if (opt == mOptions.end())
				OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Can't find Fixed Pipeline enabled options!", "Win32GLSupport::createWindow");
			bool enableFixedPipeline = (opt->second.currentValue == "Yes");
			renderSystem->setFixedPipelineEnabled(enableFixedPipeline);
#endif

			window = renderSystem->_createRenderWindow(windowTitle, w, h, fullscreen, &miscParams);
		} 
		
		return window;
	}
	
	//-------------------------------------------------------------------------------------------------//
	RenderWindow* GLXGLSupport::newWindow(const String &name, unsigned int width, unsigned int height, bool fullScreen, const NameValuePairList *miscParams)
	{
		GLXWindow* window = new GLXWindow(this);
		
		window->create(name, width, height, fullScreen, miscParams);
		
		return window;
	}

	//-------------------------------------------------------------------------------------------------//
	GLPBuffer *GLXGLSupport::createPBuffer(PixelComponentType format, size_t width, size_t height)
	{
		return new GLXPBuffer(this, format, width, height);
	}
	
	//-------------------------------------------------------------------------------------------------//
	void GLXGLSupport::start() 
	{
		LogManager::getSingleton().logMessage(
			"******************************\n"
			"*** Starting GLX Subsystem ***\n"
			"******************************");
	}

	//-------------------------------------------------------------------------------------------------//
	void GLXGLSupport::stop() 
	{
		LogManager::getSingleton().logMessage(
			"******************************\n"
			"*** Stopping GLX Subsystem ***\n"
			"******************************");
	}

	//-------------------------------------------------------------------------------------------------//
	void* GLXGLSupport::getProcAddress(const String& procname) {
		return (void*)glXGetProcAddressARB((const GLubyte*)procname.c_str());
	}
	
	//-------------------------------------------------------------------------------------------------//
	void GLXGLSupport::initialiseExtensions(void)
	{
		assert (mGLDisplay);
		
		GLSupport::initialiseExtensions();
		
		const char* extensionsString;
		
		// This is more realistic than using glXGetClientString:
		extensionsString = glXQueryExtensionsString(mGLDisplay, DefaultScreen(mGLDisplay));
		
		LogManager::getSingleton().stream() << "Supported GLX extensions: " << extensionsString;
		
		std::stringstream ext;
		String instr;
		
		ext << extensionsString;
		
		while(ext >> instr)
		{
			extensionList.insert(instr);
		}
	}

	//-------------------------------------------------------------------------------------------------//
	// Returns the FBConfig behind a GLXContext
   
	GLXFBConfig GLXGLSupport::getFBConfigFromContext(::GLXContext context)
	{
		GLXFBConfig fbConfig = 0;
		
		if (GLXEW_VERSION_1_3)
		{
			int fbConfigAttrib[] = {
				GLX_FBCONFIG_ID, 0, 
				None
			};
			GLXFBConfig *fbConfigs;
			int nElements = 0;
			
			glXQueryContext(mGLDisplay, context, GLX_FBCONFIG_ID, &fbConfigAttrib[1]);
			fbConfigs = glXChooseFBConfig(mGLDisplay, DefaultScreen(mGLDisplay), fbConfigAttrib, &nElements);
			
			if (nElements)
			{
				fbConfig = fbConfigs[0];
				XFree(fbConfigs);
			}
		}
		else if (GLXEW_EXT_import_context && GLXEW_SGIX_fbconfig)
		{
			VisualID visualid;
			
			if (glXQueryContextInfoEXT(mGLDisplay, context, GLX_VISUAL_ID, (int*)&visualid))
			{
				fbConfig = getFBConfigFromVisualID(visualid);
			}
		}
	
		return fbConfig;
	}
	
	//-------------------------------------------------------------------------------------------------//
	// Returns the FBConfig behind a GLXDrawable, or returns 0 when 
	//   missing GLX_SGIX_fbconfig and drawable is Window (unlikely), OR
	//   missing GLX_VERSION_1_3 and drawable is a GLXPixmap (possible).
	
	GLXFBConfig GLXGLSupport::getFBConfigFromDrawable(GLXDrawable drawable, unsigned int *width, unsigned int *height)
	{
		GLXFBConfig fbConfig = 0;
		
		if (GLXEW_VERSION_1_3)
		{
			int fbConfigAttrib[] = {
				GLX_FBCONFIG_ID, 0, 
				None
			};
			GLXFBConfig *fbConfigs;
			int nElements = 0;
			
			glXQueryDrawable (mGLDisplay, drawable, GLX_FBCONFIG_ID, (unsigned int*)&fbConfigAttrib[1]);
			
			fbConfigs = glXChooseFBConfig(mGLDisplay, DefaultScreen(mGLDisplay), fbConfigAttrib, &nElements);
			
			if (nElements)
			{
				fbConfig = fbConfigs[0];
				XFree (fbConfigs);
				
				glXQueryDrawable(mGLDisplay, drawable, GLX_WIDTH, width);
				glXQueryDrawable(mGLDisplay, drawable, GLX_HEIGHT, height);
			}
		}
		
		if (! fbConfig && GLXEW_SGIX_fbconfig)
		{
			XWindowAttributes windowAttrib;
			
			if (XGetWindowAttributes(mGLDisplay, drawable, &windowAttrib))
			{
				VisualID visualid = XVisualIDFromVisual(windowAttrib.visual);
				
				fbConfig = getFBConfigFromVisualID(visualid);
				
				*width = windowAttrib.width;
				*height = windowAttrib.height;
			}
		}
		
		return fbConfig;
	}

	//-------------------------------------------------------------------------------------------------//
	// Finds a GLXFBConfig compatible with a given VisualID.

	GLXFBConfig GLXGLSupport::getFBConfigFromVisualID(VisualID visualid)
	{
		GLXFBConfig fbConfig = 0;
		
		if (GLXEW_SGIX_fbconfig && glXGetFBConfigFromVisualSGIX)
		{
			XVisualInfo visualInfo;
			
			visualInfo.screen = DefaultScreen(mGLDisplay);
			visualInfo.depth = DefaultDepth(mGLDisplay, DefaultScreen(mGLDisplay));
			visualInfo.visualid = visualid;
			
			fbConfig = glXGetFBConfigFromVisualSGIX(mGLDisplay, &visualInfo);
		}
		
		if (! fbConfig)
		{
			int minAttribs[] = {
				GLX_DRAWABLE_TYPE,  GLX_WINDOW_BIT || GLX_PIXMAP_BIT,
				GLX_RENDER_TYPE,	GLX_RGBA_BIT,
				GLX_RED_SIZE,	   1,
				GLX_BLUE_SIZE,	  1,
				GLX_GREEN_SIZE,	 1,
				None
			};
			int nConfigs = 0;
			
			GLXFBConfig *fbConfigs = chooseFBConfig(minAttribs, &nConfigs);
			
			for (int i = 0; i < nConfigs && ! fbConfig; i++)
			{
				XVisualInfo *visualInfo = getVisualFromFBConfig(fbConfigs[i]);
				
				if (visualInfo->visualid == visualid)
					fbConfig = fbConfigs[i];
				
				XFree(visualInfo);
			}

			XFree(fbConfigs);
		}
		
		return fbConfig;
	}

	//-------------------------------------------------------------------------------------------------//
	// A helper class for the implementation of selectFBConfig

	class FBConfigAttribs
	{
	public:
		FBConfigAttribs(const int* attribs)
		{
			fields[GLX_CONFIG_CAVEAT] = GLX_NONE;
			
			for (int i = 0; attribs[2*i]; i++)
			{
				fields[attribs[2*i]] = attribs[2*i+1];
			}
		}

		void load(GLXGLSupport* const glSupport, GLXFBConfig fbConfig)
		{
			std::map<int,int>::iterator it;
			
			for (it = fields.begin(); it != fields.end(); it++)
			{
				it->second = 0;

				glSupport->getFBConfigAttrib(fbConfig, it->first, &it->second);
			}
		}

		bool operator>(FBConfigAttribs& alternative)
		{
			// Caveats are best avoided, but might be needed for anti-aliasing
			
			if (fields[GLX_CONFIG_CAVEAT] != alternative.fields[GLX_CONFIG_CAVEAT])
			{
				if (fields[GLX_CONFIG_CAVEAT] == GLX_SLOW_CONFIG)
					return false;
				
				if (fields.find(GLX_SAMPLES) != fields.end() && 
					fields[GLX_SAMPLES] < alternative.fields[GLX_SAMPLES])
					return false;
			}
			
			std::map<int,int>::iterator it;
			
			for (it = fields.begin(); it != fields.end(); it++)
			{
				if (it->first != GLX_CONFIG_CAVEAT && fields[it->first] > alternative.fields[it->first])
					return true;
			}
			
			return false;
		}
		
		std::map<int,int> fields;
	};

	//-------------------------------------------------------------------------------------------------//
	// Finds an FBConfig that possesses each of minAttribs and gets as close 
	// as possible to each of the maxAttribs without exceeding them.
	// Resembles glXChooseFBConfig, but is forgiving to platforms
	// that do not support the attributes listed in the maxAttribs.
	
	GLXFBConfig GLXGLSupport::selectFBConfig (const int* minAttribs, const int *maxAttribs)
	{
		GLXFBConfig *fbConfigs;
		GLXFBConfig fbConfig = 0;
		int config, nConfigs = 0;
		
		fbConfigs = chooseFBConfig(minAttribs, &nConfigs);
		
		// this is a fix for cases where chooseFBConfig is not supported.
		// On the 10/2010 chooseFBConfig was not supported on VirtualBox
		// http://www.virtualbox.org/ticket/7195
		if (!nConfigs) 		
		{ 		    
			fbConfigs = glXGetFBConfigs(mGLDisplay, DefaultScreen(mGLDisplay), &nConfigs); 		
		}
		
		if (! nConfigs) 
			return 0;
		
		fbConfig = fbConfigs[0];
		
		if (maxAttribs)
		{
			FBConfigAttribs maximum(maxAttribs);
			FBConfigAttribs best(maxAttribs);
			FBConfigAttribs candidate(maxAttribs);
			
			best.load(this, fbConfig);
			
			for (config = 1; config < nConfigs; config++)
			{
				candidate.load(this, fbConfigs[config]);
				
				if (candidate > maximum)
					continue;
				
				if (candidate > best)
				{
					fbConfig = fbConfigs[config];		
					
					best.load(this, fbConfig);
				}
			}
		}

		XFree (fbConfigs);
		return fbConfig;
	}

	//-------------------------------------------------------------------------------------------------//
	bool GLXGLSupport::loadIcon(const std::string &name, Pixmap *pixmap, Pixmap *bitmap)
	{
		Image image;
		int width, height;
		char* imageData;
                
                if (! Ogre::ResourceGroupManager::getSingleton().resourceExists(ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, name)) 
                    return false;
                
		try 
		{
{'fraction_non_alphanumeric': 0.20956064429403579, 'fraction_numerical': 0.004433648562601702, 'mean_word_length': 2.5143378087187136, 'pattern_counts': {'":': 0, '<': 39, '<?xml version=': 0, '>': 93, 'https://': 0, 'lorem ipsum': 0, 'www.': 4, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6950970', 'n_tokens_mistral': 15274, 'n_tokens_neox': 12667, 'n_words': 2585}