Browse Source

Split GL and D3D9 into separate dlls

Marko Pintera 13 years ago
parent
commit
2abf1aa49c
100 changed files with 9227 additions and 5 deletions
  1. 20 0
      CamelotClient/CamelotClient.cpp
  2. 100 0
      CamelotClient/CamelotClient.vcxproj
  3. 36 0
      CamelotClient/CamelotClient.vcxproj.filters
  4. 40 0
      CamelotClient/ReadMe.txt
  5. 8 0
      CamelotClient/stdafx.cpp
  6. 0 0
      CamelotClient/stdafx.h
  7. 0 0
      CamelotClient/targetver.h
  8. 73 5
      CamelotD3D9Renderer/CamelotD3D9Renderer.vcxproj
  9. 157 0
      CamelotD3D9Renderer/CamelotD3D9Renderer.vcxproj.filters
  10. 152 0
      CamelotD3D9Renderer/Include/CmD3D9Device.h
  11. 76 0
      CamelotD3D9Renderer/Include/CmD3D9DeviceManager.h
  12. 80 0
      CamelotD3D9Renderer/Include/CmD3D9Driver.h
  13. 52 0
      CamelotD3D9Renderer/Include/CmD3D9DriverList.h
  14. 149 0
      CamelotD3D9Renderer/Include/CmD3D9GpuProgram.h
  15. 51 0
      CamelotD3D9Renderer/Include/CmD3D9GpuProgramManager.h
  16. 126 0
      CamelotD3D9Renderer/Include/CmD3D9HLSLProgram.h
  17. 52 0
      CamelotD3D9Renderer/Include/CmD3D9HLSLProgramFactory.h
  18. 74 0
      CamelotD3D9Renderer/Include/CmD3D9HardwareBufferManager.h
  19. 101 0
      CamelotD3D9Renderer/Include/CmD3D9HardwareIndexBuffer.h
  20. 115 0
      CamelotD3D9Renderer/Include/CmD3D9HardwareOcclusionQuery.h
  21. 157 0
      CamelotD3D9Renderer/Include/CmD3D9HardwarePixelBuffer.h
  22. 99 0
      CamelotD3D9Renderer/Include/CmD3D9HardwareVertexBuffer.h
  23. 115 0
      CamelotD3D9Renderer/Include/CmD3D9Mappings.h
  24. 59 0
      CamelotD3D9Renderer/Include/CmD3D9MultiRenderTarget.h
  25. 119 0
      CamelotD3D9Renderer/Include/CmD3D9Prerequisites.h
  26. 359 0
      CamelotD3D9Renderer/Include/CmD3D9RenderSystem.h
  27. 0 0
      CamelotD3D9Renderer/Include/CmD3D9RenderSystemFactory.h
  28. 133 0
      CamelotD3D9Renderer/Include/CmD3D9RenderWindow.h
  29. 76 0
      CamelotD3D9Renderer/Include/CmD3D9Resource.h
  30. 113 0
      CamelotD3D9Renderer/Include/CmD3D9ResourceManager.h
  31. 243 0
      CamelotD3D9Renderer/Include/CmD3D9Texture.h
  32. 54 0
      CamelotD3D9Renderer/Include/CmD3D9TextureManager.h
  33. 90 0
      CamelotD3D9Renderer/Include/CmD3D9VertexDeclaration.h
  34. 63 0
      CamelotD3D9Renderer/Include/CmD3D9VideoMode.h
  35. 55 0
      CamelotD3D9Renderer/Include/CmD3D9VideoModeList.h
  36. 0 0
      CamelotD3D9Renderer/Source/CmD3D9Device.cpp
  37. 0 0
      CamelotD3D9Renderer/Source/CmD3D9DeviceManager.cpp
  38. 0 0
      CamelotD3D9Renderer/Source/CmD3D9Driver.cpp
  39. 0 0
      CamelotD3D9Renderer/Source/CmD3D9DriverList.cpp
  40. 0 0
      CamelotD3D9Renderer/Source/CmD3D9GpuProgram.cpp
  41. 0 0
      CamelotD3D9Renderer/Source/CmD3D9GpuProgramManager.cpp
  42. 584 0
      CamelotD3D9Renderer/Source/CmD3D9HLSLProgram.cpp
  43. 0 0
      CamelotD3D9Renderer/Source/CmD3D9HLSLProgramFactory.cpp
  44. 0 0
      CamelotD3D9Renderer/Source/CmD3D9HardwareBufferManager.cpp
  45. 0 0
      CamelotD3D9Renderer/Source/CmD3D9HardwareIndexBuffer.cpp
  46. 0 0
      CamelotD3D9Renderer/Source/CmD3D9HardwareOcclusionQuery.cpp
  47. 0 0
      CamelotD3D9Renderer/Source/CmD3D9HardwarePixelBuffer.cpp
  48. 0 0
      CamelotD3D9Renderer/Source/CmD3D9HardwareVertexBuffer.cpp
  49. 0 0
      CamelotD3D9Renderer/Source/CmD3D9Mappings.cpp
  50. 0 0
      CamelotD3D9Renderer/Source/CmD3D9MultiRenderTarget.cpp
  51. 0 0
      CamelotD3D9Renderer/Source/CmD3D9RenderSystem.cpp
  52. 0 0
      CamelotD3D9Renderer/Source/CmD3D9RenderSystemFactory.cpp
  53. 0 0
      CamelotD3D9Renderer/Source/CmD3D9RenderWindow.cpp
  54. 0 0
      CamelotD3D9Renderer/Source/CmD3D9Resource.cpp
  55. 0 0
      CamelotD3D9Renderer/Source/CmD3D9ResourceManager.cpp
  56. 0 0
      CamelotD3D9Renderer/Source/CmD3D9Texture.cpp
  57. 0 0
      CamelotD3D9Renderer/Source/CmD3D9TextureManager.cpp
  58. 0 0
      CamelotD3D9Renderer/Source/CmD3D9VertexDeclaration.cpp
  59. 0 0
      CamelotD3D9Renderer/Source/CmD3D9VideoMode.cpp
  60. 0 0
      CamelotD3D9Renderer/Source/CmD3D9VideoModeList.cpp
  61. 161 0
      CamelotGLRenderer/CamelotGLRenderer.vcxproj
  62. 255 0
      CamelotGLRenderer/CamelotGLRenderer.vcxproj.filters
  63. 41 0
      CamelotGLRenderer/Include/CmGLATIFSInit.h
  64. 75 0
      CamelotGLRenderer/Include/CmGLContext.h
  65. 133 0
      CamelotGLRenderer/Include/CmGLDefaultHardwareBufferManager.h
  66. 54 0
      CamelotGLRenderer/Include/CmGLFBOMultiRenderTarget.h
  67. 195 0
      CamelotGLRenderer/Include/CmGLFBORenderTexture.h
  68. 96 0
      CamelotGLRenderer/Include/CmGLFrameBufferObject.h
  69. 118 0
      CamelotGLRenderer/Include/CmGLGpuProgram.h
  70. 59 0
      CamelotGLRenderer/Include/CmGLGpuProgramManager.h
  71. 139 0
      CamelotGLRenderer/Include/CmGLHardwareBufferManager.h
  72. 70 0
      CamelotGLRenderer/Include/CmGLHardwareIndexBuffer.h
  73. 108 0
      CamelotGLRenderer/Include/CmGLHardwareOcclusionQuery.h
  74. 138 0
      CamelotGLRenderer/Include/CmGLHardwarePixelBuffer.h
  75. 69 0
      CamelotGLRenderer/Include/CmGLHardwareVertexBuffer.h
  76. 106 0
      CamelotGLRenderer/Include/CmGLPBRenderTexture.h
  77. 62 0
      CamelotGLRenderer/Include/CmGLPBuffer.h
  78. 100 0
      CamelotGLRenderer/Include/CmGLPixelFormat.h
  79. 107 0
      CamelotGLRenderer/Include/CmGLPrerequisites.h
  80. 484 0
      CamelotGLRenderer/Include/CmGLRenderSystem.h
  81. 35 0
      CamelotGLRenderer/Include/CmGLRenderSystemFactory.h
  82. 131 0
      CamelotGLRenderer/Include/CmGLRenderTexture.h
  83. 137 0
      CamelotGLRenderer/Include/CmGLSupport.h
  84. 104 0
      CamelotGLRenderer/Include/CmGLTexture.h
  85. 65 0
      CamelotGLRenderer/Include/CmGLTextureManager.h
  86. 58 0
      CamelotGLRenderer/Include/CmWin32Context.h
  87. 90 0
      CamelotGLRenderer/Include/CmWin32GLSupport.h
  88. 48 0
      CamelotGLRenderer/Include/CmWin32Prerequisites.h
  89. 55 0
      CamelotGLRenderer/Include/CmWin32RenderTexture.h
  90. 89 0
      CamelotGLRenderer/Include/CmWin32Window.h
  91. 104 0
      CamelotGLRenderer/Source/CmGLATIFSInit.cpp
  92. 63 0
      CamelotGLRenderer/Source/CmGLContext.cpp
  93. 169 0
      CamelotGLRenderer/Source/CmGLDefaultHardwareBufferManager.cpp
  94. 89 0
      CamelotGLRenderer/Source/CmGLFBOMultiRenderTarget.cpp
  95. 504 0
      CamelotGLRenderer/Source/CmGLFBORenderTexture.cpp
  96. 321 0
      CamelotGLRenderer/Source/CmGLFrameBufferObject.cpp
  97. 236 0
      CamelotGLRenderer/Source/CmGLGpuProgram.cpp
  98. 66 0
      CamelotGLRenderer/Source/CmGLGpuProgramManager.cpp
  99. 270 0
      CamelotGLRenderer/Source/CmGLHardwareBufferManager.cpp
  100. 242 0
      CamelotGLRenderer/Source/CmGLHardwareIndexBuffer.cpp

+ 20 - 0
CamelotClient/CamelotClient.cpp

@@ -0,0 +1,20 @@
+// CamelotClient.cpp : Defines the entry point for the console application.
+//
+
+#include "stdafx.h"
+
+#include "CmApplication.h"
+
+using namespace CamelotEngine;
+
+int _tmain(int argc, _TCHAR* argv[])
+{
+	gApplication().startUp("RenderSystemD3D9.dll");
+
+	int a = 5;
+
+	gApplication().shutDown();
+
+	return 0;
+}
+

+ 100 - 0
CamelotClient/CamelotClient.vcxproj

@@ -0,0 +1,100 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup Label="ProjectConfigurations">
+    <ProjectConfiguration Include="Debug|Win32">
+      <Configuration>Debug</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|Win32">
+      <Configuration>Release</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+  </ItemGroup>
+  <PropertyGroup Label="Globals">
+    <ProjectGuid>{67137A0D-7A67-4D0C-9FBF-AF904FABEF05}</ProjectGuid>
+    <Keyword>Win32Proj</Keyword>
+    <RootNamespace>CamelotClient</RootNamespace>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <UseDebugLibraries>true</UseDebugLibraries>
+    <PlatformToolset>v110</PlatformToolset>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <UseDebugLibraries>false</UseDebugLibraries>
+    <PlatformToolset>v110</PlatformToolset>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <PropertyGroup Label="UserMacros" />
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <LinkIncremental>true</LinkIncremental>
+    <OutDir>..\bin\$(Configuration)\</OutDir>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <LinkIncremental>false</LinkIncremental>
+    <OutDir>..\bin\$(Configuration)\</OutDir>
+  </PropertyGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <ClCompile>
+      <PrecompiledHeader>
+      </PrecompiledHeader>
+      <WarningLevel>Level3</WarningLevel>
+      <Optimization>Disabled</Optimization>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <AdditionalIncludeDirectories>..\CamelotRenderer\Include;..\CamelotD3D9Renderer\Include;..\CamelotUtility\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+    </ClCompile>
+    <Link>
+      <SubSystem>Console</SubSystem>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <AdditionalDependencies>CamelotRenderer.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalLibraryDirectories>..\lib\$(Configuration);%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <ClCompile>
+      <WarningLevel>Level3</WarningLevel>
+      <PrecompiledHeader>
+      </PrecompiledHeader>
+      <Optimization>MaxSpeed</Optimization>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <IntrinsicFunctions>true</IntrinsicFunctions>
+      <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <AdditionalIncludeDirectories>..\CamelotRenderer\Include;..\CamelotD3D9Renderer\Include;..\CamelotUtility\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+    </ClCompile>
+    <Link>
+      <SubSystem>Console</SubSystem>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <EnableCOMDATFolding>true</EnableCOMDATFolding>
+      <OptimizeReferences>true</OptimizeReferences>
+      <AdditionalLibraryDirectories>..\lib\$(Configuration)</AdditionalLibraryDirectories>
+      <AdditionalDependencies>CamelotRenderer.lib;%(AdditionalDependencies)</AdditionalDependencies>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemGroup>
+    <Text Include="ReadMe.txt" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="stdafx.h" />
+    <ClInclude Include="targetver.h" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="CamelotClient.cpp" />
+    <ClCompile Include="stdafx.cpp" />
+  </ItemGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>

+ 36 - 0
CamelotClient/CamelotClient.vcxproj.filters

@@ -0,0 +1,36 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <Filter Include="Source Files">
+      <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
+      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+    </Filter>
+    <Filter Include="Header Files">
+      <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
+      <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
+    </Filter>
+    <Filter Include="Resource Files">
+      <UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
+      <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
+    </Filter>
+  </ItemGroup>
+  <ItemGroup>
+    <Text Include="ReadMe.txt" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="stdafx.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="targetver.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="stdafx.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="CamelotClient.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+  </ItemGroup>
+</Project>

+ 40 - 0
CamelotClient/ReadMe.txt

@@ -0,0 +1,40 @@
+========================================================================
+    CONSOLE APPLICATION : CamelotClient Project Overview
+========================================================================
+
+AppWizard has created this CamelotClient application for you.
+
+This file contains a summary of what you will find in each of the files that
+make up your CamelotClient application.
+
+
+CamelotClient.vcxproj
+    This is the main project file for VC++ projects generated using an Application Wizard.
+    It contains information about the version of Visual C++ that generated the file, and
+    information about the platforms, configurations, and project features selected with the
+    Application Wizard.
+
+CamelotClient.vcxproj.filters
+    This is the filters file for VC++ projects generated using an Application Wizard. 
+    It contains information about the association between the files in your project 
+    and the filters. This association is used in the IDE to show grouping of files with
+    similar extensions under a specific node (for e.g. ".cpp" files are associated with the
+    "Source Files" filter).
+
+CamelotClient.cpp
+    This is the main application source file.
+
+/////////////////////////////////////////////////////////////////////////////
+Other standard files:
+
+StdAfx.h, StdAfx.cpp
+    These files are used to build a precompiled header (PCH) file
+    named CamelotClient.pch and a precompiled types file named StdAfx.obj.
+
+/////////////////////////////////////////////////////////////////////////////
+Other notes:
+
+AppWizard uses "TODO:" comments to indicate parts of the source code you
+should add to or customize.
+
+/////////////////////////////////////////////////////////////////////////////

+ 8 - 0
CamelotClient/stdafx.cpp

@@ -0,0 +1,8 @@
+// stdafx.cpp : source file that includes just the standard includes
+// CamelotClient.pch will be the pre-compiled header
+// stdafx.obj will contain the pre-compiled type information
+
+#include "stdafx.h"
+
+// TODO: reference any additional headers you need in STDAFX.H
+// and not in this file

+ 0 - 0
CamelotRenderer/stdafx.h → CamelotClient/stdafx.h


+ 0 - 0
CamelotRenderer/targetver.h → CamelotClient/targetver.h


+ 73 - 5
CamelotD3D9Renderer/CamelotD3D9Renderer.vcxproj

@@ -16,17 +16,17 @@
   </PropertyGroup>
   </PropertyGroup>
   <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
   <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
   <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
   <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
+    <ConfigurationType>DynamicLibrary</ConfigurationType>
     <UseDebugLibraries>true</UseDebugLibraries>
     <UseDebugLibraries>true</UseDebugLibraries>
     <PlatformToolset>v110</PlatformToolset>
     <PlatformToolset>v110</PlatformToolset>
-    <CharacterSet>MultiByte</CharacterSet>
+    <CharacterSet>NotSet</CharacterSet>
   </PropertyGroup>
   </PropertyGroup>
   <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
   <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
-    <ConfigurationType>Application</ConfigurationType>
+    <ConfigurationType>DynamicLibrary</ConfigurationType>
     <UseDebugLibraries>false</UseDebugLibraries>
     <UseDebugLibraries>false</UseDebugLibraries>
     <PlatformToolset>v110</PlatformToolset>
     <PlatformToolset>v110</PlatformToolset>
     <WholeProgramOptimization>true</WholeProgramOptimization>
     <WholeProgramOptimization>true</WholeProgramOptimization>
-    <CharacterSet>MultiByte</CharacterSet>
+    <CharacterSet>NotSet</CharacterSet>
   </PropertyGroup>
   </PropertyGroup>
   <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
   <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
   <ImportGroup Label="ExtensionSettings">
   <ImportGroup Label="ExtensionSettings">
@@ -38,14 +38,24 @@
     <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
     <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
   </ImportGroup>
   </ImportGroup>
   <PropertyGroup Label="UserMacros" />
   <PropertyGroup Label="UserMacros" />
-  <PropertyGroup />
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <OutDir>..\bin\$(Configuration)\</OutDir>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <OutDir>..\bin\$(Configuration)\</OutDir>
+  </PropertyGroup>
   <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
   <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
     <ClCompile>
     <ClCompile>
       <WarningLevel>Level3</WarningLevel>
       <WarningLevel>Level3</WarningLevel>
       <Optimization>Disabled</Optimization>
       <Optimization>Disabled</Optimization>
+      <AdditionalIncludeDirectories>C:\Program Files %28x86%29\Microsoft DirectX SDK %28June 2010%29\Include;.\Include;..\CamelotRenderer\Include;..\CamelotUtility\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>CM_RSD3D9_DLL;_WINDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>
     </ClCompile>
     </ClCompile>
     <Link>
     <Link>
       <GenerateDebugInformation>true</GenerateDebugInformation>
       <GenerateDebugInformation>true</GenerateDebugInformation>
+      <AdditionalDependencies>d3d9.lib;d3dx9.lib;DxErr.lib;dxguid.lib;CamelotRenderer.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalLibraryDirectories>C:\Program Files %28x86%29\Microsoft DirectX SDK %28June 2010%29\Lib\x86;..\lib\$(Configuration);%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
+      <ImportLibrary>..\lib\$(Configuration)\$(TargetName).lib</ImportLibrary>
     </Link>
     </Link>
   </ItemDefinitionGroup>
   </ItemDefinitionGroup>
   <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
   <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
@@ -54,14 +64,72 @@
       <Optimization>MaxSpeed</Optimization>
       <Optimization>MaxSpeed</Optimization>
       <FunctionLevelLinking>true</FunctionLevelLinking>
       <FunctionLevelLinking>true</FunctionLevelLinking>
       <IntrinsicFunctions>true</IntrinsicFunctions>
       <IntrinsicFunctions>true</IntrinsicFunctions>
+      <AdditionalIncludeDirectories>C:\Program Files %28x86%29\Microsoft DirectX SDK %28June 2010%29\Include;.\Include;..\CamelotRenderer\Include;..\CamelotUtility\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>CM_RSD3D9_DLL;_WINDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>
     </ClCompile>
     </ClCompile>
     <Link>
     <Link>
       <GenerateDebugInformation>true</GenerateDebugInformation>
       <GenerateDebugInformation>true</GenerateDebugInformation>
       <EnableCOMDATFolding>true</EnableCOMDATFolding>
       <EnableCOMDATFolding>true</EnableCOMDATFolding>
       <OptimizeReferences>true</OptimizeReferences>
       <OptimizeReferences>true</OptimizeReferences>
+      <AdditionalDependencies>d3d9.lib;d3dx9.lib;DxErr.lib;dxguid.lib;CamelotRenderer.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalLibraryDirectories>C:\Program Files %28x86%29\Microsoft DirectX SDK %28June 2010%29\Lib\x86;..\lib\$(Configuration)</AdditionalLibraryDirectories>
+      <ImportLibrary>..\lib\$(Configuration)\$(TargetName).lib</ImportLibrary>
     </Link>
     </Link>
   </ItemDefinitionGroup>
   </ItemDefinitionGroup>
   <ItemGroup>
   <ItemGroup>
+    <ClInclude Include="Include\CmD3D9Device.h" />
+    <ClInclude Include="Include\CmD3D9DeviceManager.h" />
+    <ClInclude Include="Include\CmD3D9Driver.h" />
+    <ClInclude Include="Include\CmD3D9DriverList.h" />
+    <ClInclude Include="Include\CmD3D9GpuProgram.h" />
+    <ClInclude Include="Include\CmD3D9GpuProgramManager.h" />
+    <ClInclude Include="Include\CmD3D9HardwareBufferManager.h" />
+    <ClInclude Include="Include\CmD3D9HardwareIndexBuffer.h" />
+    <ClInclude Include="Include\CmD3D9HardwareOcclusionQuery.h" />
+    <ClInclude Include="Include\CmD3D9HardwarePixelBuffer.h" />
+    <ClInclude Include="Include\CmD3D9HardwareVertexBuffer.h" />
+    <ClInclude Include="Include\CmD3D9HLSLProgram.h" />
+    <ClInclude Include="Include\CmD3D9HLSLProgramFactory.h" />
+    <ClInclude Include="Include\CmD3D9Mappings.h" />
+    <ClInclude Include="Include\CmD3D9MultiRenderTarget.h" />
+    <ClInclude Include="Include\CmD3D9Prerequisites.h" />
+    <ClInclude Include="Include\CmD3D9RenderSystem.h" />
+    <ClInclude Include="Include\CmD3D9RenderSystemFactory.h" />
+    <ClInclude Include="Include\CmD3D9RenderWindow.h" />
+    <ClInclude Include="Include\CmD3D9Resource.h" />
+    <ClInclude Include="Include\CmD3D9ResourceManager.h" />
+    <ClInclude Include="Include\CmD3D9Texture.h" />
+    <ClInclude Include="Include\CmD3D9TextureManager.h" />
+    <ClInclude Include="Include\CmD3D9VertexDeclaration.h" />
+    <ClInclude Include="Include\CmD3D9VideoMode.h" />
+    <ClInclude Include="Include\CmD3D9VideoModeList.h" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="Source\CmD3D9Device.cpp" />
+    <ClCompile Include="Source\CmD3D9DeviceManager.cpp" />
+    <ClCompile Include="Source\CmD3D9Driver.cpp" />
+    <ClCompile Include="Source\CmD3D9DriverList.cpp" />
+    <ClCompile Include="Source\CmD3D9GpuProgram.cpp" />
+    <ClCompile Include="Source\CmD3D9GpuProgramManager.cpp" />
+    <ClCompile Include="Source\CmD3D9HardwareBufferManager.cpp" />
+    <ClCompile Include="Source\CmD3D9HardwareIndexBuffer.cpp" />
+    <ClCompile Include="Source\CmD3D9HardwareOcclusionQuery.cpp" />
+    <ClCompile Include="Source\CmD3D9HardwarePixelBuffer.cpp" />
+    <ClCompile Include="Source\CmD3D9HardwareVertexBuffer.cpp" />
+    <ClCompile Include="Source\CmD3D9HLSLProgram.cpp" />
+    <ClCompile Include="Source\CmD3D9HLSLProgramFactory.cpp" />
+    <ClCompile Include="Source\CmD3D9Mappings.cpp" />
+    <ClCompile Include="Source\CmD3D9MultiRenderTarget.cpp" />
+    <ClCompile Include="Source\CmD3D9RenderSystem.cpp" />
+    <ClCompile Include="Source\CmD3D9RenderSystemFactory.cpp" />
+    <ClCompile Include="Source\CmD3D9RenderWindow.cpp" />
+    <ClCompile Include="Source\CmD3D9Resource.cpp" />
+    <ClCompile Include="Source\CmD3D9ResourceManager.cpp" />
+    <ClCompile Include="Source\CmD3D9Texture.cpp" />
+    <ClCompile Include="Source\CmD3D9TextureManager.cpp" />
+    <ClCompile Include="Source\CmD3D9VertexDeclaration.cpp" />
+    <ClCompile Include="Source\CmD3D9VideoMode.cpp" />
+    <ClCompile Include="Source\CmD3D9VideoModeList.cpp" />
   </ItemGroup>
   </ItemGroup>
   <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
   <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
   <ImportGroup Label="ExtensionTargets">
   <ImportGroup Label="ExtensionTargets">

+ 157 - 0
CamelotD3D9Renderer/CamelotD3D9Renderer.vcxproj.filters

@@ -14,4 +14,161 @@
       <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
       <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
     </Filter>
     </Filter>
   </ItemGroup>
   </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="Include\CmD3D9Device.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="Include\CmD3D9DeviceManager.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="Include\CmD3D9Driver.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="Include\CmD3D9DriverList.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="Include\CmD3D9GpuProgram.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="Include\CmD3D9GpuProgramManager.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="Include\CmD3D9HardwareBufferManager.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="Include\CmD3D9HardwareIndexBuffer.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="Include\CmD3D9HardwareOcclusionQuery.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="Include\CmD3D9HardwarePixelBuffer.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="Include\CmD3D9HardwareVertexBuffer.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="Include\CmD3D9HLSLProgram.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="Include\CmD3D9HLSLProgramFactory.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="Include\CmD3D9Mappings.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="Include\CmD3D9MultiRenderTarget.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="Include\CmD3D9Prerequisites.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="Include\CmD3D9RenderSystem.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="Include\CmD3D9RenderSystemFactory.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="Include\CmD3D9RenderWindow.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="Include\CmD3D9Resource.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="Include\CmD3D9ResourceManager.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="Include\CmD3D9Texture.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="Include\CmD3D9TextureManager.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="Include\CmD3D9VertexDeclaration.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="Include\CmD3D9VideoMode.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="Include\CmD3D9VideoModeList.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="Source\CmD3D9Device.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\CmD3D9DeviceManager.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\CmD3D9Driver.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\CmD3D9DriverList.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\CmD3D9GpuProgram.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\CmD3D9GpuProgramManager.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\CmD3D9HardwareBufferManager.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\CmD3D9HardwareIndexBuffer.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\CmD3D9HardwareOcclusionQuery.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\CmD3D9HardwarePixelBuffer.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\CmD3D9HardwareVertexBuffer.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\CmD3D9HLSLProgram.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\CmD3D9HLSLProgramFactory.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\CmD3D9Mappings.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\CmD3D9MultiRenderTarget.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\CmD3D9RenderSystem.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\CmD3D9RenderSystemFactory.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\CmD3D9RenderWindow.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\CmD3D9Resource.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\CmD3D9ResourceManager.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\CmD3D9Texture.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\CmD3D9TextureManager.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\CmD3D9VertexDeclaration.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\CmD3D9VideoMode.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\CmD3D9VideoModeList.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+  </ItemGroup>
 </Project>
 </Project>

+ 152 - 0
CamelotD3D9Renderer/Include/CmD3D9Device.h

@@ -0,0 +1,152 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+(Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2011 Torus Knot Software 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.
+-----------------------------------------------------------------------------
+*/
+#ifndef __D3D9Device_H__
+#define __D3D9Device_H__
+
+#include "CmD3D9Prerequisites.h"
+#include "CmRenderTarget.h"
+
+namespace CamelotEngine {
+
+	class D3D9RenderWindow;
+	class D3D9DeviceManager;
+
+	/** High level interface of Direct3D9 Device.
+	Provide useful methods for device handling.
+	*/
+	class CM_D3D9_EXPORT D3D9Device
+	{
+
+	// Interface.
+	public:
+		void					attachRenderWindow		(D3D9RenderWindow* renderWindow);
+		void					detachRenderWindow		(D3D9RenderWindow* renderWindow);
+	
+		bool					acquire					();
+		
+		void					release					();		
+		void					destroy					();		
+		
+		bool					isDeviceLost			();				
+		IDirect3DDevice9*		getD3D9Device			();
+					
+		UINT					getAdapterNumber		() const;
+		D3DDEVTYPE				getDeviceType			() const;
+		bool					isMultihead				() const;					
+		bool					isAutoDepthStencil		() const;
+		
+		const D3DCAPS9&			getD3D9DeviceCaps		() const;
+		D3DFORMAT				getBackBufferFormat		() const;
+
+		bool					validate				(D3D9RenderWindow* renderWindow);
+		void					invalidate				(D3D9RenderWindow* renderWindow);
+
+		void					present					(D3D9RenderWindow* renderWindow);
+		
+		IDirect3DSurface9*		getDepthBuffer			(D3D9RenderWindow* renderWindow);
+		IDirect3DSurface9*		getBackBuffer			(D3D9RenderWindow* renderWindow);
+
+		UINT32					getRenderWindowCount	() const;
+		D3D9RenderWindow*		getRenderWindow			(UINT32 index);
+		UINT32					getLastPresentFrame		() const { return mLastPresentFrame; }
+
+		void					setAdapterOrdinalIndex  (D3D9RenderWindow* renderWindow, UINT32 adapterOrdinalInGroupIndex);
+		void					copyContentsToMemory(D3D9RenderWindow* window, const PixelData &dst, RenderTarget::FrameBuffer buffer);
+		void					clearDeviceStreams		();
+	
+	public:
+		D3D9Device	(D3D9DeviceManager* deviceManager,
+					 UINT adapterNumber, 
+					 HMONITOR hMonitor, 
+					 D3DDEVTYPE devType, 
+					 DWORD behaviorFlags);
+		~D3D9Device	();
+
+	protected:			
+		D3D9DeviceManager*				mpDeviceManager;			// The manager of this device instance.
+		IDirect3DDevice9*				mpDevice;					// Will hold the device interface.				
+		UINT							mAdapterNumber;				// The adapter that this device belongs to.	
+		HMONITOR						mMonitor;					// The monitor that this device belongs to.
+		D3DDEVTYPE						mDeviceType;				// Device type.	
+		static HWND						msSharedFocusWindow;		// The shared focus window in case of multiple full screen render windows.
+		HWND							mFocusWindow;				// The focus window this device attached to.			
+		DWORD							mBehaviorFlags;				// The behavior of this device.		
+		D3DPRESENT_PARAMETERS*			mPresentationParams;		// Presentation parameters which the device was created with. May be
+																	// an array of presentation parameters in case of multi-head device.				
+		UINT							mPresentationParamsCount;	// Number of presentation parameters elements.		
+		D3DCAPS9						mD3D9DeviceCaps;			// Device caps.	
+		bool							mD3D9DeviceCapsValid;		// True if device caps initialized.				
+		D3DDEVICE_CREATION_PARAMETERS	mCreationParams;			// Creation parameters.
+		UINT32							mLastPresentFrame;			// Last frame that this device present method called.
+		bool							mDeviceLost;				// True if device entered lost state.
+	
+		struct RenderWindowResources
+		{
+			IDirect3DSwapChain9* 	swapChain;						// Swap chain interface.
+			UINT32					adapterOrdinalInGroupIndex;		// Relative index of the render window in the group.
+			UINT32					presentParametersIndex;			// Index of present parameter in the shared array of the device.
+			IDirect3DSurface9*	 	backBuffer;						// The back buffer of the render window.
+			IDirect3DSurface9*	 	depthBuffer;					// The depth buffer of the render window.
+			D3DPRESENT_PARAMETERS	presentParameters;				// Present parameters of the render window.
+			bool					acquired;						// True if resources acquired.			
+		};		
+		typedef map<D3D9RenderWindow*, RenderWindowResources*>::type RenderWindowToResorucesMap;
+		typedef RenderWindowToResorucesMap::iterator				 RenderWindowToResorucesIterator;
+
+		RenderWindowToResorucesMap mMapRenderWindowToResoruces;		// Map between render window to resources.
+
+
+	protected:
+		RenderWindowToResorucesIterator getRenderWindowIterator (D3D9RenderWindow* renderWindow);
+
+		bool					acquire							(D3D9RenderWindow* renderWindow);
+		bool					reset							();
+		void					updatePresentationParameters	();
+		void					updateRenderWindowsIndices		();
+		
+		void					createD3D9Device				();
+		void					releaseD3D9Device				();
+		void					releaseRenderWindowResources	(RenderWindowResources* renderWindowResources);
+		void					acquireRenderWindowResources	(RenderWindowToResorucesIterator it);		
+		void					setupDeviceStates				();
+		void					notifyDeviceLost				();
+
+		void					validateFocusWindow				();
+		void					validateBackBufferSize			(D3D9RenderWindow* renderWindow);
+		bool					validateDisplayMonitor			(D3D9RenderWindow* renderWindow);
+		bool					validateDeviceState				(D3D9RenderWindow* renderWindow);
+		bool					isSwapChainWindow				(D3D9RenderWindow* renderWindow);
+		D3D9RenderWindow*		getPrimaryWindow				();
+		void					setSharedWindowHandle			(HWND hSharedHWND);
+
+	private:
+		friend class D3D9DeviceManager;
+		friend class D3D9RenderSystem;
+	};
+}
+#endif

+ 76 - 0
CamelotD3D9Renderer/Include/CmD3D9DeviceManager.h

@@ -0,0 +1,76 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+(Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2011 Torus Knot Software 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.
+-----------------------------------------------------------------------------
+*/
+#ifndef __D3D9DeviceManager_H__
+#define __D3D9DeviceManager_H__
+
+#include "CmD3D9Prerequisites.h"
+
+namespace CamelotEngine {
+
+	class D3D9Device;
+	class D3D9RenderWindow;
+
+	/** Device manager interface.
+	*/
+	class CM_D3D9_EXPORT D3D9DeviceManager
+	{	
+
+	// Interface.
+	public:		
+		void				setActiveDevice					(D3D9Device* device);
+		D3D9Device*			getActiveDevice					();
+		void				setActiveRenderTargetDevice		(D3D9Device* device);
+		D3D9Device*			getActiveRenderTargetDevice		();		
+		UINT				getDeviceCount					();
+		D3D9Device*			getDevice						(UINT index);			
+		void				linkRenderWindow				(D3D9RenderWindow* renderWindow);
+		void				destroyInactiveRenderDevices	();
+		void				notifyOnDeviceDestroy			(D3D9Device* device);
+		D3D9Device*			getDeviceFromD3D9Device			(IDirect3DDevice9* d3d9Device);
+		
+	public:
+		D3D9DeviceManager	();
+		~D3D9DeviceManager	();
+
+	protected:		
+		typedef vector<D3D9Device*>::type		 DeviceList;
+		typedef DeviceList::iterator			 DeviceIterator;
+		typedef DeviceList::const_iterator		 ConstDeviceIterator;
+		typedef vector<D3D9RenderWindow*>::type  D3D9RenderWindowList;
+
+	protected:
+		D3D9Device*			selectDevice		(D3D9RenderWindow* renderWindow, D3D9RenderWindowList& renderWindowsGroup);
+		D3D9Driver*			findDriver			(D3D9RenderWindow* renderWindow);
+
+		
+		DeviceList								mRenderDevices;		
+		D3D9Device*								mActiveDevice;
+		D3D9Device*								mActiveRenderWindowDevice;		
+	};
+}
+#endif

+ 80 - 0
CamelotD3D9Renderer/Include/CmD3D9Driver.h

@@ -0,0 +1,80 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+    (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2011 Torus Knot Software 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.
+-----------------------------------------------------------------------------
+*/
+#ifndef __D3D9DRIVER_H__
+#define __D3D9DRIVER_H__
+
+#include "CmD3D9Prerequisites.h"
+#include "CmString.h"
+
+namespace CamelotEngine
+{
+
+	class D3D9VideoModeList;
+	class D3D9VideoMode;
+
+	class CM_D3D9_EXPORT D3D9Driver
+	{
+	
+	public:
+		// Constructors
+		D3D9Driver();						// Default
+		D3D9Driver( const D3D9Driver &ob );	// Copy
+		D3D9Driver( unsigned int adapterNumber, 
+			const D3DCAPS9& deviceCaps,
+			const D3DADAPTER_IDENTIFIER9& adapterIdentifer, 
+			const D3DDISPLAYMODE& desktopDisplayMode);
+		~D3D9Driver();
+
+				
+		const D3DCAPS9&		getD3D9DeviceCaps	() const { return mD3D9DeviceCaps; }
+		String				DriverName			() const;
+		String				DriverDescription	() const;
+				
+		unsigned int					getAdapterNumber	() const { return mAdapterNumber; }
+		const D3DADAPTER_IDENTIFIER9&	getAdapterIdentifier() const { return mAdapterIdentifier; }
+		const D3DDISPLAYMODE&			getDesktopMode		() const { return mDesktopDisplayMode; }
+		D3D9VideoModeList*				getVideoModeList	();
+			
+	private:				
+		// Adapter number.
+		unsigned int			mAdapterNumber;
+		
+		// Device caps.
+		D3DCAPS9				mD3D9DeviceCaps;		
+		
+		// Adapter identifier
+		D3DADAPTER_IDENTIFIER9	mAdapterIdentifier;
+
+		// Desktop display mode.
+		D3DDISPLAYMODE			mDesktopDisplayMode;
+
+		// Video modes list.
+		D3D9VideoModeList*		mpVideoModeList;	
+	};
+}
+#endif

+ 52 - 0
CamelotD3D9Renderer/Include/CmD3D9DriverList.h

@@ -0,0 +1,52 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+    (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2011 Torus Knot Software 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.
+-----------------------------------------------------------------------------
+*/
+#ifndef __D3D9DRIVERLIST_H__
+#define __D3D9DRIVERLIST_H__
+
+#include "CmD3D9Prerequisites.h"
+#include "CmD3D9Driver.h"
+
+namespace CamelotEngine 
+{
+	class CM_D3D9_EXPORT D3D9DriverList
+	{
+	private:
+		vector<D3D9Driver>::type mDriverList;
+		
+	public:
+		D3D9DriverList();
+		~D3D9DriverList();
+
+		BOOL enumerate();
+		size_t count() const;
+		D3D9Driver* item( size_t index );
+
+		D3D9Driver* item( const String &name );
+	};
+}
+#endif

+ 149 - 0
CamelotD3D9Renderer/Include/CmD3D9GpuProgram.h

@@ -0,0 +1,149 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+    (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2011 Torus Knot Software 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.
+-----------------------------------------------------------------------------
+*/
+#ifndef __D3D9GpuProgram_H_
+#define __D3D9GpuProgram_H_
+
+// Precompiler options
+#include "CmD3D9Prerequisites.h"
+#include "CmGpuProgram.h"
+#include "CmD3D9Resource.h"
+
+namespace CamelotEngine {
+
+    /** Direct3D implementation of a few things common to low-level vertex & fragment programs. */
+    class CM_D3D9_EXPORT D3D9GpuProgram : public GpuProgram, public D3D9Resource
+    {   
+    public:
+        D3D9GpuProgram();
+        ~D3D9GpuProgram();
+
+		virtual void load(void);
+		/** Loads this program to specified device */
+		virtual void load(IDirect3DDevice9* d3d9Device);
+		/** Overridden from GpuProgram */
+		virtual void unload(void);
+
+        /** Sets whether matrix packing in column-major order. */ 
+        void setColumnMajorMatrices(bool columnMajor) { mColumnMajorMatrices = columnMajor; }
+        /** Gets whether matrix packed in column-major order. */
+        bool getColumnMajorMatrices(void) const { return mColumnMajorMatrices; }
+
+		/** Tells the program to load from some externally created microcode instead of a file or source. 
+		*/
+		void setExternalMicrocode(const void* pMicrocode, size_t size);
+        /** Tells the program to load from some externally created microcode instead of a file or source. 
+        @remarks
+            add ref count to pMicrocode when setting
+        */ 
+        void setExternalMicrocode(ID3DXBuffer* pMicrocode);
+        /** Gets the external microcode buffer, if any. */
+        LPD3DXBUFFER getExternalMicrocode(void);
+    protected:
+        /** Overridden from GpuProgram */
+        void loadFromSource(void);
+		/** Loads this program from source to specified device */
+		void loadFromSource(IDirect3DDevice9* d3d9Device);        
+		/** Loads this program from microcode, must be overridden by subclasses. */
+        virtual void loadFromMicrocode(IDirect3DDevice9* d3d9Device, ID3DXBuffer* microcode) = 0;
+
+
+        /** Creates a new parameters object compatible with this program definition. 
+        @remarks
+            It is recommended that you use this method of creating parameters objects
+            rather than going direct to GpuProgramManager, because this method will
+            populate any implementation-specific extras (like named parameters) where
+            they are appropriate.
+        */
+        virtual GpuProgramParametersSharedPtr createParameters(void);
+	protected:    
+		bool mColumnMajorMatrices;
+		ID3DXBuffer* mpExternalMicrocode;
+
+    };
+
+    /** Direct3D implementation of low-level vertex programs. */
+    class CM_D3D9_EXPORT D3D9GpuVertexProgram : public D3D9GpuProgram
+    {  
+    public:
+        D3D9GpuVertexProgram();
+		~D3D9GpuVertexProgram();
+        
+		void unload(void);
+
+		/// Gets the vertex shader
+        IDirect3DVertexShader9* getVertexShader(void);
+
+		// Called immediately after the Direct3D device has been created.
+		virtual void notifyOnDeviceCreate(IDirect3DDevice9* d3d9Device);
+
+		// Called before the Direct3D device is going to be destroyed.
+		virtual void notifyOnDeviceDestroy(IDirect3DDevice9* d3d9Device);
+
+    protected:
+        void loadFromMicrocode(IDirect3DDevice9* d3d9Device, ID3DXBuffer* microcode);
+
+	protected:
+		typedef map<IDirect3DDevice9*, IDirect3DVertexShader9*>::type   DeviceToVertexShaderMap;
+		typedef DeviceToVertexShaderMap::iterator						DeviceToVertexShaderIterator;
+	
+		DeviceToVertexShaderMap		mMapDeviceToVertexShader;	
+    };
+
+    /** Direct3D implementation of low-level fragment programs. */
+    class CM_D3D9_EXPORT D3D9GpuFragmentProgram : public D3D9GpuProgram
+    {  
+    public:
+        D3D9GpuFragmentProgram();
+		~D3D9GpuFragmentProgram();
+
+		void unload(void);
+
+        /// Gets the pixel shader
+        IDirect3DPixelShader9* getPixelShader(void);
+
+		// Called immediately after the Direct3D device has been created.
+		virtual void notifyOnDeviceCreate(IDirect3DDevice9* d3d9Device);
+
+		// Called before the Direct3D device is going to be destroyed.
+		virtual void notifyOnDeviceDestroy(IDirect3DDevice9* d3d9Device);
+
+    protected:
+        void loadFromMicrocode(IDirect3DDevice9* d3d9Device, ID3DXBuffer* microcode);
+
+	protected:
+		typedef map<IDirect3DDevice9*, IDirect3DPixelShader9*>::type	DeviceToPixelShaderMap;
+		typedef DeviceToPixelShaderMap::iterator						DeviceToPixelShaderIterator;
+
+		DeviceToPixelShaderMap		mMapDeviceToPixelShader;			
+    };
+
+	typedef std::shared_ptr<D3D9GpuProgram> D3D9GpuProgramPtr;
+}
+
+
+#endif

+ 51 - 0
CamelotD3D9Renderer/Include/CmD3D9GpuProgramManager.h

@@ -0,0 +1,51 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+    (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2011 Torus Knot Software 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.
+-----------------------------------------------------------------------------
+*/
+#ifndef __D3D9GpuProgramManager_H__
+#define __D3D9GpuProgramManager_H__
+
+#include "CmD3D9Prerequisites.h"
+#include "CmGpuProgram.h"
+#include "CmGpuProgramManager.h"
+
+namespace CamelotEngine {
+
+    class CM_D3D9_EXPORT D3D9GpuProgramManager : public GpuProgramManager
+    {
+    public:
+		GpuProgramPtr createProgram(const String& code, GpuProgramType gptype, const String& syntaxCode);
+    public:
+        D3D9GpuProgramManager();
+		~D3D9GpuProgramManager();
+
+	protected:
+		GpuProgram* create( GpuProgramType gptype, const String& syntaxCode);
+    };
+
+}
+
+#endif

+ 126 - 0
CamelotD3D9Renderer/Include/CmD3D9HLSLProgram.h

@@ -0,0 +1,126 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+(Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2011 Torus Knot Software 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.
+-----------------------------------------------------------------------------
+*/
+#ifndef __D3D9HLSLProgram_H__
+#define __D3D9HLSLProgram_H__
+
+#include "CmD3D9Prerequisites.h"
+#include "CmHighLevelGpuProgram.h"
+
+namespace CamelotEngine {
+    /** Specialisation of HighLevelGpuProgram to provide support for D3D9 
+        High-Level Shader Language (HLSL).
+    @remarks
+        Note that the syntax of D3D9 HLSL is identical to nVidia's Cg language, therefore
+        unless you know you will only ever be deploying on Direct3D, or you have some specific
+        reason for not wanting to use the Cg plugin, I suggest you use Cg instead since that
+        can produce programs for OpenGL too.
+    */
+    class CM_D3D9_EXPORT D3D9HLSLProgram : public HighLevelGpuProgram
+    {
+    protected:
+        /** Internal load implementation, must be implemented by subclasses.
+        */
+        void loadFromSource(void);
+        /** Internal method for creating an appropriate low-level program from this
+        high-level program, must be implemented by subclasses. */
+        void createLowLevelImpl(void);
+        /// Internal unload implementation, must be implemented by subclasses
+        void unloadHighLevelImpl(void);
+        /// Populate the passed parameters with name->index map, must be overridden
+        void buildConstantDefinitions() const;
+
+        // Recursive utility method for buildParamNameMap
+        void processParamElement(D3DXHANDLE parent, String prefix, unsigned int index) const;
+		void populateDef(D3DXCONSTANT_DESC& d3dDesc, GpuConstantDefinition& def) const;
+
+        String mPreprocessorDefines;
+        bool mColumnMajorMatrices;
+
+        LPD3DXBUFFER mpMicroCode;
+        LPD3DXCONSTANTTABLE mpConstTable;
+
+	public:
+		LPD3DXBUFFER getMicroCode();
+	public:
+		/// Shader optimisation level
+		enum OptimisationLevel
+		{
+			/// default - no optimisation in debug mode, OPT_1 in release mode
+			OPT_DEFAULT,
+			/// No optimisation
+			OPT_NONE,
+			/// Optimisation level 0
+			OPT_0, 
+			/// Optimisation level 1
+			OPT_1,
+			/// Optimisation level 2
+			OPT_2, 
+			/// Optimisation level 3
+			OPT_3
+		};
+	protected:
+		OptimisationLevel mOptimisationLevel;
+
+    public:
+        D3D9HLSLProgram();
+        ~D3D9HLSLProgram();
+
+        /** Sets the entry point for this program ie the first method called. */
+        void setEntryPoint(const String& entryPoint) { mEntryPoint = entryPoint; }
+        /** Gets the entry point defined for this program. */
+        const String& getEntryPoint(void) const { return mEntryPoint; }
+        /** Sets the shader target to compile down to, e.g. 'vs_1_1'. */
+        void setTarget(const String& target);
+        /** Gets the shader target to compile down to, e.g. 'vs_1_1'. */
+        const String getTarget(void) const;
+        /** Sets the preprocessor defines use to compile the program. */
+        void setPreprocessorDefines(const String& defines) { mPreprocessorDefines = defines; }
+        /** Sets the preprocessor defines use to compile the program. */
+        const String& getPreprocessorDefines(void) const { return mPreprocessorDefines; }
+        /** Sets whether matrix packing in column-major order. */ 
+        void setColumnMajorMatrices(bool columnMajor) { mColumnMajorMatrices = columnMajor; }
+        /** Gets whether matrix packed in column-major order. */
+        bool getColumnMajorMatrices(void) const { return mColumnMajorMatrices; }
+		/** Sets the optimisation level to use.
+		@param opt Optimisation level
+		*/
+		void setOptimisationLevel(OptimisationLevel opt) { mOptimisationLevel = opt; }
+
+		/** Gets the optimisation level to use. */
+		OptimisationLevel getOptimisationLevel() const { return mOptimisationLevel; }
+
+        /// Overridden from GpuProgram
+        bool isSupported(void) const;
+        /// Overridden from GpuProgram
+        GpuProgramParametersSharedPtr createParameters(void);
+        /// Overridden from GpuProgram
+        const String& getLanguage(void) const;
+    };
+}
+
+#endif

+ 52 - 0
CamelotD3D9Renderer/Include/CmD3D9HLSLProgramFactory.h

@@ -0,0 +1,52 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+(Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2011 Torus Knot Software 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.
+-----------------------------------------------------------------------------
+*/
+#ifndef __D3D9HLSLProgramFactory_H__
+#define __D3D9HLSLProgramFactory_H__
+
+#include "CmD3D9Prerequisites.h"
+#include "CmHighLevelGpuProgramManager.h"
+
+namespace CamelotEngine
+{
+    /** Factory class for D3D9 HLSL programs. */
+    class CM_D3D9_EXPORT D3D9HLSLProgramFactory : public HighLevelGpuProgramFactory
+    {
+    protected:
+		static String sLanguageName;
+    public:
+        D3D9HLSLProgramFactory();
+        ~D3D9HLSLProgramFactory();
+		/// Get the name of the language this factory creates programs for
+		const String& getLanguage(void) const;
+        HighLevelGpuProgram* create(const String& source, const String& entryPoint, GpuProgramProfile profile);
+		void destroy(HighLevelGpuProgram* prog);
+
+    };
+}
+
+#endif

+ 74 - 0
CamelotD3D9Renderer/Include/CmD3D9HardwareBufferManager.h

@@ -0,0 +1,74 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+    (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2011 Torus Knot Software 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.
+-----------------------------------------------------------------------------
+*/
+#ifndef __D3D9HARWAREBUFFERMANAGER_H__
+#define __D3D9HARWAREBUFFERMANAGER_H__
+
+#include "CmD3D9Prerequisites.h"
+#include "CmHardwareBufferManager.h"
+
+namespace CamelotEngine {
+
+    /** Implementation of HardwareBufferManager for D3D9. */
+    class CM_D3D9_EXPORT D3D9HardwareBufferManagerBase : public HardwareBufferManagerBase
+    {
+    protected:     
+        /// Internal method for creates a new vertex declaration, may be overridden by certain rendering APIs
+        VertexDeclaration* createVertexDeclarationImpl(void);
+        /// Internal method for destroys a vertex declaration, may be overridden by certain rendering APIs
+        void destroyVertexDeclarationImpl(VertexDeclaration* decl);
+
+    public:
+        D3D9HardwareBufferManagerBase();
+        ~D3D9HardwareBufferManagerBase();
+        /// Creates a vertex buffer
+		HardwareVertexBufferPtr 
+            createVertexBuffer(size_t vertexSize, size_t numVerts, HardwareBuffer::Usage usage, bool useShadowBuffer = false);
+		/// Create a hardware vertex buffer
+		HardwareIndexBufferPtr 
+            createIndexBuffer(HardwareIndexBuffer::IndexType itype, size_t numIndexes, HardwareBuffer::Usage usage, bool useShadowBuffer = false);
+    };
+
+	/// D3D9HardwareBufferManagerBase as a Singleton
+	class CM_D3D9_EXPORT D3D9HardwareBufferManager : public HardwareBufferManager
+	{
+	public:
+		D3D9HardwareBufferManager()
+			: HardwareBufferManager(new D3D9HardwareBufferManagerBase()) 
+		{
+
+		}
+		~D3D9HardwareBufferManager()
+		{
+			delete mImpl;
+		}
+	};
+
+}
+
+
+#endif

+ 101 - 0
CamelotD3D9Renderer/Include/CmD3D9HardwareIndexBuffer.h

@@ -0,0 +1,101 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+    (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2011 Torus Knot Software 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.
+-----------------------------------------------------------------------------
+*/
+#ifndef __D3D9HARDWAREINDEXBUFFER_H__
+#define __D3D9HARDWAREINDEXBUFFER_H__
+
+#include "CmD3D9Prerequisites.h"
+#include "CmHardwareIndexBuffer.h"
+#include "CmD3D9Resource.h"
+
+namespace CamelotEngine { 
+
+
+    class CM_D3D9_EXPORT D3D9HardwareIndexBuffer : public HardwareIndexBuffer, public D3D9Resource
+    {
+  
+    public:
+		D3D9HardwareIndexBuffer(HardwareBufferManagerBase* mgr, IndexType idxType, size_t numIndexes, 
+			HardwareBuffer::Usage usage, bool useSystemMem, bool useShadowBuffer);
+        ~D3D9HardwareIndexBuffer();
+        /** See HardwareBuffer. */
+        void readData(size_t offset, size_t length, void* pDest);
+        /** See HardwareBuffer. */
+        void writeData(size_t offset, size_t length, const void* pSource,
+				bool discardWholeBuffer = false);
+
+		// Called immediately after the Direct3D device has been created.
+		virtual void notifyOnDeviceCreate(IDirect3DDevice9* d3d9Device);
+
+		// Called before the Direct3D device is going to be destroyed.
+		virtual void notifyOnDeviceDestroy(IDirect3DDevice9* d3d9Device);
+
+		// Called immediately after the Direct3D device has entered a lost state.
+		virtual void notifyOnDeviceLost(IDirect3DDevice9* d3d9Device);
+
+		// Called immediately after the Direct3D device has been reset
+		virtual void notifyOnDeviceReset(IDirect3DDevice9* d3d9Device);
+
+		// Create the actual index buffer.
+		void createBuffer(IDirect3DDevice9* d3d9Device, D3DPOOL ePool);
+	
+		/// Get the D3D-specific index buffer
+        IDirect3DIndexBuffer9* getD3DIndexBuffer(void);		
+
+	protected:
+		struct BufferResources
+		{
+			IDirect3DIndexBuffer9*		mBuffer;
+			bool						mOutOfDate;
+			size_t						mLockOffset;
+			size_t						mLockLength;
+			LockOptions					mLockOptions;
+			UINT32						mLastUsedFrame;
+		};
+
+	protected:
+		/** See HardwareBuffer. */
+		void* lockImpl(size_t offset, size_t length, LockOptions options);
+		/** See HardwareBuffer. */
+		void unlockImpl(void);
+		// updates buffer resources from system memory buffer.
+		bool updateBufferResources(const char* systemMemoryBuffer, BufferResources* bufferResources);
+
+	protected:		
+		typedef map<IDirect3DDevice9*, BufferResources*>::type	DeviceToBufferResourcesMap;
+		typedef DeviceToBufferResourcesMap::iterator			DeviceToBufferResourcesIterator;
+
+		DeviceToBufferResourcesMap	mMapDeviceToBufferResources;	// Map between device to buffer resources.	
+		D3DINDEXBUFFER_DESC			mBufferDesc;					// Buffer description.		
+		char*						mSystemMemoryBuffer;			// Consistent system memory buffer for multiple devices support.
+    };
+}
+
+
+
+#endif
+

+ 115 - 0
CamelotD3D9Renderer/Include/CmD3D9HardwareOcclusionQuery.h

@@ -0,0 +1,115 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+(Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org
+
+Copyright (c) 2000-2011 Torus Knot Software 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.
+-----------------------------------------------------------------------------
+*/
+
+#ifndef _D3D9HARWAREOCCLUSIONQUERY_H__
+#define _D3D9HARWAREOCCLUSIONQUERY_H__
+
+#include "CmD3D9Prerequisites.h"
+#include "CmHardwareOcclusionQuery.h"
+#include "CmD3D9Resource.h"
+
+
+namespace CamelotEngine {
+
+	// If you use multiple rendering passes you can test only the first pass and all other passes don't have to be rendered 
+	// if the first pass results has too few pixels visible.
+
+	// Be sure to render all occluder first and whats out so the RenderQue don't switch places on 
+	// the occluding objects and the tested objects because it thinks it's more effective..
+
+	/**
+	* This is a class that is the DirectX9 implementation of 
+	* hardware occlusion testing.
+	*
+	* @author Lee Sandberg, email [email protected]
+	*
+	* Updated on 12/7/2004 by Chris McGuirk
+	* Updated on 4/8/2005 by Tuan Kuranes email: [email protected]
+	*/
+	class CM_D3D9_EXPORT D3D9HardwareOcclusionQuery : public HardwareOcclusionQuery, public D3D9Resource
+	{
+		//----------------------------------------------------------------------
+		// Public methods
+		//--
+	public:
+
+		/**
+		* Default object constructor
+		* 
+		*/
+		D3D9HardwareOcclusionQuery();
+
+		/**
+		* Object destructor
+		*/
+		~D3D9HardwareOcclusionQuery();
+
+		//------------------------------------------------------------------
+		// Occlusion query functions (see base class documentation for this)
+		//--
+
+		void beginOcclusionQuery();	
+		void endOcclusionQuery();
+		bool pullOcclusionQuery( unsigned int* NumOfFragments);
+		unsigned int getLastQuerysPixelcount();
+        bool isStillOutstanding(void);
+	
+		// Called immediately after the Direct3D device has been created.
+		virtual void notifyOnDeviceCreate(IDirect3DDevice9* d3d9Device);
+
+		// Called before the Direct3D device is going to be destroyed.
+		virtual void notifyOnDeviceDestroy(IDirect3DDevice9* d3d9Device);
+		
+		// Called immediately after the Direct3D device has entered a lost state.
+		// This is the place to release non-managed resources.
+		virtual void notifyOnDeviceLost(IDirect3DDevice9* d3d9Device);
+
+		// Called immediately after the Direct3D device has been reset.
+		// This is the place to create non-managed resources.
+		virtual void notifyOnDeviceReset(IDirect3DDevice9* d3d9Device);
+	
+
+	private:
+		void createQuery(IDirect3DDevice9* d3d9Device);
+		void releaseQuery(IDirect3DDevice9* d3d9Device);
+
+		//----------------------------------------------------------------------
+		// private members
+		//--
+	private:					
+		typedef map<IDirect3DDevice9*, IDirect3DQuery9*>::type DeviceToQueryMap;
+		typedef DeviceToQueryMap::iterator					   DeviceToQueryIterator;
+
+		DeviceToQueryMap				mMapDeviceToQuery;		
+	};
+
+
+}
+
+
+#endif

+ 157 - 0
CamelotD3D9Renderer/Include/CmD3D9HardwarePixelBuffer.h

@@ -0,0 +1,157 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+    (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2011 Torus Knot Software 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.
+-----------------------------------------------------------------------------
+*/
+#ifndef __D3D9PIXELBUFFER_H__
+#define __D3D9PIXELBUFFER_H__
+
+#include "CmD3D9Prerequisites.h"
+#include "CmHardwarePixelBuffer.h"
+
+namespace CamelotEngine {
+
+	class D3D9Texture;
+	class D3D9RenderTexture;
+
+	class CM_D3D9_EXPORT D3D9HardwarePixelBuffer: public HardwarePixelBuffer
+	{
+	protected:		
+		struct BufferResources
+		{			
+			/// Surface abstracted by this buffer
+			IDirect3DSurface9* surface;
+			/// AA Surface abstracted by this buffer
+			IDirect3DSurface9* fSAASurface;
+			/// Volume abstracted by this buffer
+			IDirect3DVolume9* volume;
+			/// Temporary surface in main memory if direct locking of mSurface is not possible
+			IDirect3DSurface9* tempSurface;
+			/// Temporary volume in main memory if direct locking of mVolume is not possible
+			IDirect3DVolume9* tempVolume;
+			/// Mip map texture.
+			IDirect3DBaseTexture9 *mipTex;			
+		};
+
+		typedef map<IDirect3DDevice9*, BufferResources*>::type	DeviceToBufferResourcesMap;
+		typedef DeviceToBufferResourcesMap::iterator			DeviceToBufferResourcesIterator;
+
+		/// Map between device to buffer resources.
+		DeviceToBufferResourcesMap	mMapDeviceToBufferResources;
+				
+		/// Mipmapping
+		bool mDoMipmapGen;
+		bool mHWMipmaps;
+		
+		/// Render target
+		D3D9RenderTexture* mRenderTexture;
+
+		// The owner texture if exists.
+		D3D9Texture* mOwnerTexture;
+		
+		// The current lock flags of this surface.
+		DWORD mLockFlags;
+
+		// Device access mutex.
+		CM_STATIC_MUTEX(msDeviceAccessMutex)		
+	protected:
+		/// Lock a box
+		PixelData lockImpl(const Box lockBox,  LockOptions options);
+		PixelData lockBuffer(BufferResources* bufferResources, const Box &lockBox, DWORD flags);
+
+		/// Unlock a box
+		void unlockImpl(void);
+		void unlockBuffer(BufferResources* bufferResources);
+
+		BufferResources* getBufferResources(IDirect3DDevice9* d3d9Device);
+		BufferResources* createBufferResources();
+	
+		/// updates render texture.
+		void updateRenderTexture(bool writeGamma, UINT32 fsaa, const String& srcName);
+		/// destroy render texture.
+		void destroyRenderTexture();
+
+		void blit(IDirect3DDevice9* d3d9Device, const HardwarePixelBufferPtr &src,
+				const Box &srcBox, const Box &dstBox, 
+				BufferResources* srcBufferResources, 
+				BufferResources* dstBufferResources);
+		void blitFromMemory(const PixelData &src, const Box &dstBox, BufferResources* dstBufferResources);
+
+		void blitToMemory(const Box &srcBox, const PixelData &dst, BufferResources* srcBufferResources, IDirect3DDevice9* d3d9Device);
+			
+	public:
+		D3D9HardwarePixelBuffer(HardwareBuffer::Usage usage, 
+			D3D9Texture* ownerTexture);
+		~D3D9HardwarePixelBuffer();
+
+		/// Call this to associate a D3D surface or volume with this pixel buffer
+		void bind(IDirect3DDevice9 *dev, IDirect3DSurface9 *mSurface, IDirect3DSurface9* fsaaSurface,
+				  bool writeGamma, UINT32 fsaa, const String& srcName, IDirect3DBaseTexture9 *mipTex);
+		void bind(IDirect3DDevice9 *dev, IDirect3DVolume9 *mVolume, IDirect3DBaseTexture9 *mipTex);
+		
+		/// @copydoc HardwarePixelBuffer::blit
+        void blit(const HardwarePixelBufferPtr &src, const Box &srcBox, const Box &dstBox);
+		
+		/// @copydoc HardwarePixelBuffer::blitFromMemory
+		void blitFromMemory(const PixelData &src, const Box &dstBox);
+	
+		/// @copydoc HardwarePixelBuffer::blitToMemory
+		void blitToMemory(const Box &srcBox, const PixelData &dst);
+		
+		/// Internal function to update mipmaps on update of level 0
+		void _genMipmaps(IDirect3DBaseTexture9* mipTex);
+		
+		/// Function to set mipmap generation
+		void _setMipmapping(bool doMipmapGen, bool HWMipmaps);
+		
+		
+		/// Get rendertarget for z slice
+		RenderTexture *getRenderTarget(size_t zoffset);
+
+		/// Accessor for surface
+		IDirect3DSurface9 *getSurface(IDirect3DDevice9* d3d9Device);
+		
+		/// Accessor for AA surface
+		IDirect3DSurface9 *getFSAASurface(IDirect3DDevice9* d3d9Device);
+
+		/// Notify TextureBuffer of destruction of render target
+        virtual void _clearSliceRTT(size_t zoffset);
+
+		/// Release surfaces held by this pixel buffer.
+		void releaseSurfaces(IDirect3DDevice9* d3d9Device);
+
+		/// Destroy resources associated with the given device.
+		void destroyBufferResources(IDirect3DDevice9* d3d9Device);
+
+		// Called when device state is changing. Access to any device should be locked.
+		// Relevant for multi thread application.
+		static void lockDeviceAccess();
+
+		// Called when device state change completed. Access to any device is allowed.
+		// Relevant for multi thread application.
+		static void unlockDeviceAccess();
+	};
+};
+#endif

+ 99 - 0
CamelotD3D9Renderer/Include/CmD3D9HardwareVertexBuffer.h

@@ -0,0 +1,99 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+    (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2011 Torus Knot Software 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.
+-----------------------------------------------------------------------------
+*/
+#ifndef __D3D9HARDWAREVERTEXBUFFER_H__
+#define __D3D9HARDWAREVERTEXBUFFER_H__
+
+#include "CmD3D9Prerequisites.h"
+#include "CmHardwareVertexBuffer.h"
+#include "CmD3D9Resource.h"
+
+namespace CamelotEngine {
+
+    /// Specialisation of HardwareVertexBuffer for D3D9
+    class CM_D3D9_EXPORT D3D9HardwareVertexBuffer : public HardwareVertexBuffer, public D3D9Resource
+    {   
+
+    public:
+		D3D9HardwareVertexBuffer(HardwareBufferManagerBase* mgr, size_t vertexSize, 
+			size_t numVertices, HardwareBuffer::Usage usage, bool useSystemMem, bool useShadowBuffer);
+        ~D3D9HardwareVertexBuffer();
+        /** See HardwareBuffer. */
+        void readData(size_t offset, size_t length, void* pDest);
+        /** See HardwareBuffer. */
+        void writeData(size_t offset, size_t length, const void* pSource,
+				bool discardWholeBuffer = false);
+	
+		// Called immediately after the Direct3D device has been created.
+		virtual void notifyOnDeviceCreate(IDirect3DDevice9* d3d9Device);
+
+		// Called before the Direct3D device is going to be destroyed.
+		virtual void notifyOnDeviceDestroy(IDirect3DDevice9* d3d9Device);
+
+		// Called immediately after the Direct3D device has entered a lost state.
+		virtual void notifyOnDeviceLost(IDirect3DDevice9* d3d9Device);
+
+		// Called immediately after the Direct3D device has been reset
+		virtual void notifyOnDeviceReset(IDirect3DDevice9* d3d9Device);
+
+		// Create the actual vertex buffer.
+		void createBuffer(IDirect3DDevice9* d3d9Device, D3DPOOL ePool);
+		
+        /// Get D3D9-specific vertex buffer
+        IDirect3DVertexBuffer9* getD3D9VertexBuffer(void);
+
+	protected:	
+		struct BufferResources
+		{
+			IDirect3DVertexBuffer9*		mBuffer;
+			bool						mOutOfDate;
+			size_t						mLockOffset;
+			size_t						mLockLength;
+			LockOptions					mLockOptions;
+			UINT32						mLastUsedFrame;
+		};
+
+	protected:		
+		/** See HardwareBuffer. */
+		void* lockImpl(size_t offset, size_t length, LockOptions options);		
+		/** See HardwareBuffer. */
+		void unlockImpl(void);			
+		// updates buffer resources from system memory buffer.
+		bool updateBufferResources(const char* systemMemoryBuffer, BufferResources* bufferResources);		
+
+	protected:
+		typedef map<IDirect3DDevice9*, BufferResources*>::type	DeviceToBufferResourcesMap;
+		typedef DeviceToBufferResourcesMap::iterator			DeviceToBufferResourcesIterator;
+
+		DeviceToBufferResourcesMap	mMapDeviceToBufferResources;	// Map between device to buffer resources.
+		D3DVERTEXBUFFER_DESC		mBufferDesc;					// Buffer description.		
+		char*						mSystemMemoryBuffer;			// Consistent system memory buffer for multiple devices support.
+    };
+
+}
+#endif
+

+ 115 - 0
CamelotD3D9Renderer/Include/CmD3D9Mappings.h

@@ -0,0 +1,115 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+    (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2011 Torus Knot Software 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.
+-----------------------------------------------------------------------------
+*/
+#ifndef __D3D9MAPPINGS_H__
+#define __D3D9MAPPINGS_H__
+
+#include "CmD3D9Prerequisites.h"
+#include "CmCommon.h"
+#include "CmRenderSystem.h"
+#include "CmHardwareBuffer.h"
+#include "CmHardwareIndexBuffer.h"
+
+namespace CamelotEngine 
+{
+	class CM_D3D9_EXPORT D3D9Mappings
+	{
+	public:
+		/// enum identifying D3D9 tex. types
+		enum eD3DTexType
+		{
+			/// standard texture
+			D3D_TEX_TYPE_NORMAL,
+			/// cube texture
+			D3D_TEX_TYPE_CUBE,
+			/// volume texture
+			D3D_TEX_TYPE_VOLUME,
+			/// just to have it...
+			D3D_TEX_TYPE_NONE
+		};
+
+		/// enum identifying D3D9 filter usage type
+		enum eD3DFilterUsage
+		{
+			/// min filter
+			D3D_FUSAGE_MIN,
+			/// mag filter
+			D3D_FUSAGE_MAG,
+			/// mip filter
+			D3D_FUSAGE_MIP
+		};
+
+		/// return a D3D9 equivalent for a Ogre ShadeOptions value
+		static DWORD get(ShadeOptions so);
+		/// return a D3D9 equivalent for a Ogre TexCoordCalsMethod value
+		static DWORD get(TexCoordCalcMethod m, const D3DCAPS9& caps);
+		/// return a D3D9 equivalent for a Ogre TextureAddressingMode value
+		static D3DTEXTUREADDRESS get(TextureState::TextureAddressingMode tam, const D3DCAPS9& devCaps);
+		/// return a D3D9 equivalent for a Ogre SceneBlendFactor value
+		static D3DBLEND get(SceneBlendFactor sbf);
+		/// return a D3D9 equivlalent for a Ogre SceneBlendOperation value
+		static D3DBLENDOP get(SceneBlendOperation sbo);
+		/// return a D3D9 equivalent for a Ogre CompareFunction value
+		static DWORD get(CompareFunction cf);
+		/// return a D3D9 equivalent for a Ogre CillingMode value
+		static DWORD get(CullingMode cm, bool flip);
+		/// return a D3D9 equivalent for a Ogre FogMode value
+		static D3DFOGMODE get(FogMode fm);
+		/// return a D3D9 equivalent for a Ogre PolygonMode value
+		static D3DFILLMODE get(PolygonMode level);
+		/// return a D3D9 equivalent for a Ogre StencilOperation value
+		static DWORD get(StencilOperation op, bool invert = false);
+		/// return a D3D9 state type for Ogre FilterType value
+		static D3DSAMPLERSTATETYPE get(FilterType ft);
+		/// return a D3D9 filter option for Ogre FilterType & FilterOption value
+		static DWORD get(FilterType ft, FilterOptions fo, const D3DCAPS9& devCaps, eD3DTexType texType);
+		/// return the D3DtexType equivalent of a Ogre tex. type
+		static eD3DTexType get(TextureType ogreTexType);
+        /// return the combination of D3DUSAGE values for Ogre buffer usage
+        static DWORD get(HardwareBuffer::Usage usage);
+        /// Get lock options
+        static DWORD get(HardwareBuffer::LockOptions options, HardwareBuffer::Usage usage);
+        /// Get index type
+        static D3DFORMAT get(HardwareIndexBuffer::IndexType itype);
+		/// Get vertex data type
+		static D3DDECLTYPE get(VertexElementType vType);
+		/// Get vertex semantic
+		static D3DDECLUSAGE get(VertexElementSemantic sem);
+        // Convert matrix to D3D style
+        static 	D3DXMATRIX makeD3DXMatrix( const Matrix4& mat );
+        // Convert matrix from D3D style
+        static Matrix4 convertD3DXMatrix( const D3DXMATRIX& mat );
+
+		/// utility method, convert D3D9 pixel format to Ogre pixel format
+		static PixelFormat _getPF(D3DFORMAT d3dPF);
+		/// utility method, convert Ogre pixel format to D3D9 pixel format
+		static D3DFORMAT _getPF(PixelFormat ogrePF);
+		/// utility method, find closest Ogre pixel format that D3D9 can support
+		static PixelFormat _getClosestSupportedPF(PixelFormat ogrePF);
+	};
+}
+#endif

+ 59 - 0
CamelotD3D9Renderer/Include/CmD3D9MultiRenderTarget.h

@@ -0,0 +1,59 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+    (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2011 Torus Knot Software 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.
+-----------------------------------------------------------------------------
+*/
+#ifndef __D3D9MULTIRENDERTARGET_H__
+#define __D3D9MULTIRENDERTARGET_H__
+
+#include "CmD3D9Prerequisites.h"
+#include "CmTexture.h"
+#include "CmRenderTexture.h"
+#include "CmException.h"
+#include "CmD3D9HardwarePixelBuffer.h"
+
+namespace CamelotEngine {
+	class CM_D3D9_EXPORT D3D9MultiRenderTarget : public MultiRenderTarget
+	{
+	public:
+		D3D9MultiRenderTarget(const String &name);
+		~D3D9MultiRenderTarget();
+
+        virtual void update(bool swapBuffers);
+
+		virtual void getCustomAttribute( const String& name, void *pData );
+
+		bool requiresTextureFlipping() const { return false; }
+	private:
+		D3D9HardwarePixelBuffer *mRenderTargets[CM_MAX_MULTIPLE_RENDER_TARGETS];
+		virtual void bindSurfaceImpl(size_t attachment, RenderTexture *target);
+		virtual void unbindSurfaceImpl(size_t attachment);
+
+		/** Check surfaces and update RenderTarget extent */
+		void checkAndUpdate();
+	};
+};
+
+#endif

+ 119 - 0
CamelotD3D9Renderer/Include/CmD3D9Prerequisites.h

@@ -0,0 +1,119 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+    (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2011 Torus Knot Software 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.
+-----------------------------------------------------------------------------
+*/
+#ifndef __D3D9PREREQUISITES_H__
+#define __D3D9PREREQUISITES_H__
+
+#include "CmPrerequisites.h"
+#ifdef __MINGW32__
+#  include "WIN32/OgreMinGWSupport.h" // extra defines for MinGW to deal with DX SDK
+#endif
+
+#if CM_THREAD_SUPPORT
+#define OGRE_LOCK_RECURSIVE_MUTEX(name)   name.lock();
+#define OGRE_UNLOCK_RECURSIVE_MUTEX(name) name.unlock();
+#else
+#define OGRE_LOCK_RECURSIVE_MUTEX(name) 
+#define OGRE_UNLOCK_RECURSIVE_MUTEX(name)
+#endif
+
+
+#if CM_THREAD_SUPPORT == 1
+#define D3D9_DEVICE_ACCESS_LOCK				OGRE_LOCK_RECURSIVE_MUTEX(msDeviceAccessMutex);
+#define D3D9_DEVICE_ACCESS_UNLOCK			OGRE_UNLOCK_RECURSIVE_MUTEX(msDeviceAccessMutex);
+#define D3D9_DEVICE_ACCESS_CRITICAL_SECTION	CM_LOCK_MUTEX(msDeviceAccessMutex)
+#else
+#define D3D9_DEVICE_ACCESS_LOCK	
+#define D3D9_DEVICE_ACCESS_UNLOCK
+#define D3D9_DEVICE_ACCESS_CRITICAL_SECTION
+#endif
+
+// Define versions for if DirectX is in use (Win32 only)
+#define DIRECT3D_VERSION 0x0900
+
+// some D3D commonly used macros
+#define SAFE_DELETE(p)       { if(p) { delete (p);     (p)=NULL; } }
+#define SAFE_DELETE_ARRAY(p) { if(p) { delete[] (p);   (p)=NULL; } }
+#define SAFE_RELEASE(p)      { if(p) { (p)->Release(); (p)=NULL; } }
+
+// enable extended d3d debug 
+#if CM_DEBUG_MODE
+#	define D3D_DEBUG_INFO
+#endif
+
+#define WIN32_LEAN_AND_MEAN
+#if !defined(NOMINMAX) && defined(_MSC_VER)
+#	define NOMINMAX // required to stop windows.h messing up std::min
+#endif
+#include <d3d9.h>
+#include <d3dx9.h>
+#include <DxErr.h>
+
+
+namespace CamelotEngine
+{
+	// Predefine classes
+	class D3D9RenderSystem;
+	class D3D9RenderWindow;
+	class D3D9Texture;
+	class D3D9TextureManager;
+	class D3D9Driver;
+	class D3D9DriverList;
+	class D3D9VideoMode;
+	class D3D9VideoModeList;
+	class D3D9GpuProgram;
+	class D3D9GpuProgramManager;
+    class D3D9HardwareBufferManager;
+    class D3D9HardwareIndexBuffer;
+    class D3D9HLSLProgramFactory;
+    class D3D9HLSLProgram;
+    class D3D9VertexDeclaration;
+	class D3D9Resource;
+
+// Should we ask D3D to manage vertex/index buffers automatically?
+// Doing so avoids lost devices, but also has a performance impact
+// which is unacceptably bad when using very large buffers
+#define OGRE_D3D_MANAGE_BUFFERS 1 // TODO - Keep this on or off? I'll probably want to turn it off at some point
+
+    //-------------------------------------------
+	// Windows setttings
+	//-------------------------------------------
+#if (CM_PLATFORM == CM_PLATFORM_WIN32) && !defined(CM_STATIC_LIB)
+#	ifdef CM_RSD3D9_DLL
+#		define CM_D3D9_EXPORT __declspec(dllexport)
+#	else
+#       if defined( __MINGW32__ )
+#           define CM_D3D9_EXPORT
+#       else
+#    		define CM_D3D9_EXPORT __declspec(dllimport)
+#       endif
+#	endif
+#else
+#	define CM_D3D9_EXPORT
+#endif	// OGRE_WIN32
+}
+#endif

+ 359 - 0
CamelotD3D9Renderer/Include/CmD3D9RenderSystem.h

@@ -0,0 +1,359 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+    (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org
+
+Copyright (c) 2000-2011 Torus Knot Software 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.
+-----------------------------------------------------------------------------
+*/
+#ifndef __D3D9RENDERSYSTEM_H__
+#define __D3D9RENDERSYSTEM_H__
+
+#include "CmD3D9Prerequisites.h"
+#include "CmString.h"
+#include "CmConfigOptionMap.h"
+#include "CmRenderSystem.h"
+#include "CmRenderSystemCapabilities.h"
+#include "CmD3D9Mappings.h"
+
+namespace CamelotEngine 
+{
+	class D3D9DriverList;
+	class D3D9Driver;
+	class D3D9Device;
+	class D3D9DeviceManager;
+	class D3D9ResourceManager;
+
+	/**
+	Implementation of DirectX9 as a rendering system.
+	*/
+	class CM_D3D9_EXPORT D3D9RenderSystem : public RenderSystem
+	{
+	private:
+		/// Direct3D
+		IDirect3D9*	 mpD3D;		
+		// Stored options
+		ConfigOptionMap mOptions;
+		size_t mFSAASamples;
+		String mFSAAHint;
+
+		/// instance
+		HINSTANCE mhInstance;
+
+		/// List of D3D drivers installed (video cards)
+		D3D9DriverList* mDriverList;
+		/// Currently active driver
+		D3D9Driver* mActiveD3DDriver;
+		/// NVPerfHUD allowed?
+		bool mUseNVPerfHUD;
+		/// Per-stage constant support? (not in main caps since D3D specific & minor)
+		bool mPerStageConstantSupport;
+		/// Fast singleton access.
+		static D3D9RenderSystem* msD3D9RenderSystem;
+
+		/// structure holding texture unit settings for every stage
+		struct sD3DTextureStageDesc
+		{
+			/// the type of the texture
+			D3D9Mappings::eD3DTexType texType;
+			/// which texCoordIndex to use
+			size_t coordIndex;
+			/// type of auto tex. calc. used
+			TexCoordCalcMethod autoTexCoordType;
+            /// Frustum, used if the above is projection
+            const Frustum *frustum;
+			/// texture 
+			IDirect3DBaseTexture9 *pTex;
+			/// vertex texture 
+			IDirect3DBaseTexture9 *pVertexTex;
+		} mTexStageDesc[CM_MAX_TEXTURE_LAYERS];
+
+		D3D9DriverList* getDirect3DDrivers();
+		void refreshD3DSettings();
+        void refreshFSAAOptions();
+				
+		// state management methods, very primitive !!!
+		HRESULT __SetRenderState(D3DRENDERSTATETYPE state, DWORD value);
+		HRESULT __SetSamplerState(DWORD sampler, D3DSAMPLERSTATETYPE type, DWORD value);
+		HRESULT __SetTextureStageState(DWORD stage, D3DTEXTURESTAGESTATETYPE type, DWORD value);
+
+		HRESULT __SetFloatRenderState(D3DRENDERSTATETYPE state, float value)
+		{
+#if OGRE_DOUBLE_PRECISION == 1
+			float temp = static_cast<float>(value);
+			return __SetRenderState(state, *((LPDWORD)(&temp)));
+#else
+			return __SetRenderState(state, *((LPDWORD)(&value)));
+#endif
+		}
+
+		/// return anisotropy level
+		DWORD _getCurrentAnisotropy(size_t unit);
+		/// check if a FSAA is supported
+		bool _checkMultiSampleQuality(D3DMULTISAMPLE_TYPE type, DWORD *outQuality, D3DFORMAT format, UINT adapterNum, D3DDEVTYPE deviceType, BOOL fullScreen);
+		
+		D3D9HardwareBufferManager* mHardwareBufferManager;
+		D3D9GpuProgramManager* mGpuProgramManager;
+        D3D9HLSLProgramFactory* mHLSLProgramFactory;
+		D3D9ResourceManager* mResourceManager;
+		D3D9DeviceManager* mDeviceManager;
+
+		size_t mLastVertexSourceCount;
+
+
+        /// Internal method for populating the capabilities structure
+		virtual RenderSystemCapabilities* createRenderSystemCapabilities() const;
+		RenderSystemCapabilities* updateRenderSystemCapabilities(D3D9RenderWindow* renderWindow);
+
+		/** See RenderSystem definition */
+		virtual void initialiseFromRenderSystemCapabilities(RenderSystemCapabilities* caps, RenderTarget* primary);
+
+
+        void convertVertexShaderCaps(RenderSystemCapabilities* rsc) const;
+        void convertPixelShaderCaps(RenderSystemCapabilities* rsc) const;
+		bool checkVertexTextureFormats(D3D9RenderWindow* renderWindow) const;
+		
+        HashMap<IDirect3DDevice9*, unsigned short> mCurrentLights;
+        /// Saved last view matrix
+        Matrix4 mViewMatrix;
+
+		D3DXMATRIX mDxViewMat, mDxProjMat, mDxWorldMat;
+	
+		typedef vector<D3D9RenderWindow*>::type D3D9RenderWindowList;
+		// List of additional windows after the first (swap chains)
+		D3D9RenderWindowList mRenderWindows;
+		
+		/** Mapping of texture format -> DepthStencil. Used as cache by _getDepthStencilFormatFor
+		*/
+		typedef HashMap<unsigned int, D3DFORMAT> DepthStencilHash;
+		DepthStencilHash mDepthStencilHash;
+
+		/** Mapping of depthstencil format -> depthstencil buffer
+			Keep one depthstencil buffer around for every format that is used, it must be large
+			enough to hold the largest rendering target.
+			This is used as cache by _getDepthStencilFor.
+		*/
+		struct ZBufferIdentifier
+		{
+			IDirect3DDevice9* device;
+			D3DFORMAT format;
+			D3DMULTISAMPLE_TYPE multisampleType;
+		};
+		struct ZBufferRef
+		{
+			IDirect3DSurface9 *surface;
+			size_t width, height;
+		};
+		struct ZBufferIdentifierComparator
+		{
+			bool operator()(const ZBufferIdentifier& z0, const ZBufferIdentifier& z1) const;
+		};
+		
+		typedef deque<ZBufferRef>::type ZBufferRefQueue;
+		typedef map<ZBufferIdentifier, ZBufferRefQueue, ZBufferIdentifierComparator>::type ZBufferHash;
+		ZBufferHash mZBufferHash;		
+
+	protected:
+		void setClipPlanesImpl(const PlaneList& clipPlanes);		
+	public:
+		// constructor
+		D3D9RenderSystem( HINSTANCE hInstance );
+		// destructor
+		~D3D9RenderSystem();
+
+		virtual void initConfigOptions();
+
+		// Overridden RenderSystem functions
+		String validateConfigOptions();
+		RenderWindow* _initialise( bool autoCreateWindow, const String& windowTitle = "OGRE Render Window"  );
+		/// @copydoc RenderSystem::_createRenderWindow
+		RenderWindow* _createRenderWindow(const String &name, unsigned int width, unsigned int height, 
+			bool fullScreen, const NameValuePairList *miscParams = 0);
+		
+		/// @copydoc RenderSystem::_createRenderWindows
+		bool _createRenderWindows(const RenderWindowDescriptionList& renderWindowDescriptions, 
+			RenderWindowList& createdWindows);
+
+		/**
+         * Set current render target to target, enabling its GL context if needed
+         */
+		void _setRenderTarget(RenderTarget *target);
+		
+		/// @copydoc RenderSystem::createMultiRenderTarget
+		virtual MultiRenderTarget * createMultiRenderTarget(const String & name);
+
+		String getErrorDescription( long errorNumber ) const;
+		const String& getName() const;
+		// Low-level overridden members
+		void setConfigOption( const String &name, const String &value );
+		void reinitialise();
+		void shutdown();
+		void setAmbientLight( float r, float g, float b );
+		void setShadingType( ShadeOptions so );
+		void setLightingEnabled( bool enabled );
+		void destroyRenderTarget(const String& name);
+		VertexElementType getColourVertexElementType() const;
+		void setStencilCheckEnabled(bool enabled);
+        void setStencilBufferParams(CompareFunction func = CMPF_ALWAYS_PASS, 
+            UINT32 refValue = 0, UINT32 mask = 0xFFFFFFFF, 
+            StencilOperation stencilFailOp = SOP_KEEP, 
+            StencilOperation depthFailOp = SOP_KEEP,
+            StencilOperation passOp = SOP_KEEP, 
+            bool twoSidedOperation = false);
+        void setNormaliseNormals(bool normalise);
+
+		// Low-level overridden members, mainly for internal use
+		void _setWorldMatrix( const Matrix4 &m );
+		void _setViewMatrix( const Matrix4 &m );
+		void _setProjectionMatrix( const Matrix4 &m );
+		void _setSurfaceParams( const Color &ambient, const Color &diffuse, const Color &specular, const Color &emissive, float shininess, TrackVertexColourType tracking );
+		void _setPointSpritesEnabled(bool enabled);
+		void _setPointParameters(float size, bool attenuationEnabled, 
+			float constant, float linear, float quadratic, float minSize, float maxSize);
+		void _setTexture(size_t unit, bool enabled, const TexturePtr &texPtr);
+		void _setVertexTexture(size_t unit, const TexturePtr& tex);
+		void _disableTextureUnit(size_t texUnit);
+		void _setTextureCoordSet( size_t unit, size_t index );
+        void _setTextureCoordCalculation(size_t unit, TexCoordCalcMethod m, 
+            const Frustum* frustum = 0);
+        void _setTextureAddressingMode(size_t stage, const TextureState::UVWAddressingMode& uvw);
+        void _setTextureBorderColour(size_t stage, const Color& colour);
+		void _setTextureMipmapBias(size_t unit, float bias);
+		void _setTextureMatrix( size_t unit, const Matrix4 &xform );
+		void _setSceneBlending( SceneBlendFactor sourceFactor, SceneBlendFactor destFactor, SceneBlendOperation op );
+		void _setSeparateSceneBlending( SceneBlendFactor sourceFactor, SceneBlendFactor destFactor, SceneBlendFactor sourceFactorAlpha, SceneBlendFactor destFactorAlpha, SceneBlendOperation op, SceneBlendOperation alphaOp );
+		void _setAlphaRejectSettings( CompareFunction func, unsigned char value, bool alphaToCoverage );
+		void _setViewport( Viewport *vp );		
+		void _beginFrame();
+		virtual RenderSystemContext* _pauseFrame(void);
+		virtual void _resumeFrame(RenderSystemContext* context);
+		void _endFrame();		
+		void _setCullingMode( CullingMode mode );
+		void _setDepthBufferParams( bool depthTest = true, bool depthWrite = true, CompareFunction depthFunction = CMPF_LESS_EQUAL );
+		void _setDepthBufferCheckEnabled( bool enabled = true );
+		void _setColourBufferWriteEnabled(bool red, bool green, bool blue, bool alpha);
+		void _setDepthBufferWriteEnabled(bool enabled = true);
+		void _setDepthBufferFunction( CompareFunction func = CMPF_LESS_EQUAL );
+		void _setDepthBias(float constantBias, float slopeScaleBias);
+		void _setFog( FogMode mode = FOG_NONE, const Color& colour = Color::White, float expDensity = 1.0, float linearStart = 0.0, float linearEnd = 1.0 );
+		void _convertProjectionMatrix(const Matrix4& matrix,
+            Matrix4& dest, bool forGpuProgram = false);
+		void _makeProjectionMatrix(const Radian& fovy, float aspect, float nearPlane, float farPlane, 
+            Matrix4& dest, bool forGpuProgram = false);
+		void _makeProjectionMatrix(float left, float right, float bottom, float top, float nearPlane, 
+            float farPlane, Matrix4& dest, bool forGpuProgram = false);
+		void _makeOrthoMatrix(const Radian& fovy, float aspect, float nearPlane, float farPlane, 
+            Matrix4& dest, bool forGpuProgram = false);
+        void _applyObliqueDepthProjection(Matrix4& matrix, const Plane& plane, 
+            bool forGpuProgram);
+		void _setPolygonMode(PolygonMode level);
+        void _setTextureUnitFiltering(size_t unit, FilterType ftype, FilterOptions filter);
+		void _setTextureLayerAnisotropy(size_t unit, unsigned int maxAnisotropy);
+		void setVertexDeclaration(VertexDeclaration* decl);
+		void setVertexBufferBinding(VertexBufferBinding* binding);
+        void _render(const RenderOperation& op);
+        /** See
+          RenderSystem
+         */
+        void bindGpuProgram(GpuProgram* prg);
+        /** See
+          RenderSystem
+         */
+        void unbindGpuProgram(GpuProgramType gptype);
+        /** See
+          RenderSystem
+         */
+		void bindGpuProgramParameters(GpuProgramType gptype, 
+			GpuProgramParametersSharedPtr params, UINT16 variabilityMask);
+        void bindGpuProgramPassIterationParameters(GpuProgramType gptype);
+
+        void setScissorTest(bool enabled, size_t left = 0, size_t top = 0, size_t right = 800, size_t bottom = 600);
+        void clearFrameBuffer(unsigned int buffers, 
+            const Color& colour = Color::Black, 
+            float depth = 1.0f, unsigned short stencil = 0);
+		void setClipPlane (UINT16 index, float A, float B, float C, float D);
+		void enableClipPlane (UINT16 index, bool enable);
+        HardwareOcclusionQuery* createHardwareOcclusionQuery();
+        float getHorizontalTexelOffset();
+        float getVerticalTexelOffset();
+        float getMinimumDepthInputValue();
+        float getMaximumDepthInputValue();
+		void registerThread();
+		void unregisterThread();
+		void preExtraThreadsStarted();
+		void postExtraThreadsStarted();		
+		
+		static D3D9ResourceManager* getResourceManager();
+		static D3D9DeviceManager* getDeviceManager();
+		static IDirect3D9* getDirect3D9();
+		static UINT	getResourceCreationDeviceCount();
+		static IDirect3DDevice9* getResourceCreationDevice(UINT index);
+		static IDirect3DDevice9* getActiveD3D9Device();
+		
+		/**
+			Get the matching Z-Buffer identifier for a certain render target
+		*/
+		ZBufferIdentifier getZBufferIdentifier(RenderTarget* rt);
+
+		/** Check which depthStencil formats can be used with a certain pixel format,
+			and return the best suited.
+		*/
+		D3DFORMAT _getDepthStencilFormatFor(D3DFORMAT fmt);
+
+		/** Get a depth stencil surface that is compatible with an internal pixel format and
+			multisample type.
+			@returns A directx surface, or 0 if there is no compatible depthstencil possible.
+		*/
+		IDirect3DSurface9* _getDepthStencilFor(D3DFORMAT fmt, D3DMULTISAMPLE_TYPE multisample, DWORD multisample_quality, size_t width, size_t height);
+
+		/** Clear all cached depth stencil surfaces
+		*/
+		void _cleanupDepthStencils(IDirect3DDevice9* d3d9Device);
+
+        /** Check whether or not filtering is supported for the precise texture format requested
+        with the given usage options.
+        */
+        bool _checkTextureFilteringSupported(TextureType ttype, PixelFormat format, int usage);
+
+		/// Take in some requested FSAA settings and output supported D3D settings
+		void determineFSAASettings(IDirect3DDevice9* d3d9Device, size_t fsaa, const String& fsaaHint, D3DFORMAT d3dPixelFormat, 
+			bool fullScreen, D3DMULTISAMPLE_TYPE *outMultisampleType, DWORD *outMultisampleQuality);
+
+		/// @copydoc RenderSystem::getDisplayMonitorCount
+		unsigned int getDisplayMonitorCount() const;
+		
+	protected:	
+		/// Notify when a device has been lost.
+		void notifyOnDeviceLost(D3D9Device* device);
+
+		/// Notify when a device has been reset.
+		void notifyOnDeviceReset(D3D9Device* device);
+		
+		typedef map<RenderTarget*, ZBufferRef>::type TargetDepthStencilMap;
+		TargetDepthStencilMap mCheckedOutTextures;
+
+	private:
+		friend class D3D9Device;
+		friend class D3D9DeviceManager;		
+	};
+}
+#endif

+ 0 - 0
CamelotRenderer/CmD3D9RenderSystemFactory.h → CamelotD3D9Renderer/Include/CmD3D9RenderSystemFactory.h


+ 133 - 0
CamelotD3D9Renderer/Include/CmD3D9RenderWindow.h

@@ -0,0 +1,133 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+    (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2011 Torus Knot Software 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.
+-----------------------------------------------------------------------------
+*/
+#ifndef __D3D9RENDERWINDOW_H__
+#define __D3D9RENDERWINDOW_H__
+
+#include "CmD3D9Prerequisites.h"
+#include "CmRenderWindow.h"
+#include "CmD3D9Device.h"
+
+namespace CamelotEngine 
+{
+	class CM_D3D9_EXPORT D3D9RenderWindow : public RenderWindow
+	{
+	public:
+		/** Constructor.
+		@param instance The application instance
+		@param driver The root driver
+		@param deviceIfSwapChain The existing D3D device to create an additional swap chain from, if this is not
+			the first window.
+		*/
+		D3D9RenderWindow					(HINSTANCE instance);
+		~D3D9RenderWindow					();
+		
+		
+		void				create				(const String& name, unsigned int width, unsigned int height,
+												 bool fullScreen, const NameValuePairList *miscParams);
+		void				setFullscreen		(bool fullScreen, unsigned int width, unsigned int height);
+		void				destroy				(void);
+		bool				isActive			() const;
+		bool				isVisible			() const;
+		bool 				isClosed			() const { return mClosed; }
+		bool				isVSync				() const { return mVSync; }
+		void 				reposition			(int left, int top);
+		void 				resize				(unsigned int width, unsigned int height);
+		void 				swapBuffers			( bool waitForVSync = true );
+		HWND 				getWindowHandle		() const { return mHWnd; }				
+		IDirect3DDevice9*	getD3D9Device		();
+		D3D9Device*			getDevice			();
+		void				setDevice			(D3D9Device* device);
+
+		void				getCustomAttribute	(const String& name, void* pData);
+		
+		/** Overridden - see RenderTarget.
+		*/
+		void				copyContentsToMemory	(const PixelData &dst, FrameBuffer buffer);
+		bool				requiresTextureFlipping	() const { return false; }
+
+		// Method for dealing with resize / move & 3d library
+		void				windowMovedOrResized	();
+	
+		/// Build the presentation parameters used with this window
+		void				buildPresentParameters	(D3DPRESENT_PARAMETERS* presentParams);
+		
+
+		/// @copydoc RenderTarget::_beginUpdate
+		void _beginUpdate();
+	
+		/// @copydoc RenderTarget::_updateViewport
+		void _updateViewport(Viewport* viewport, bool updateStatistics = true);
+
+		/// @copydoc RenderTarget::_endUpdate
+		void _endUpdate();
+
+		/// Accessor for render surface
+		IDirect3DSurface9* getRenderSurface();
+
+		/// Are we in the middle of switching between fullscreen and windowed
+		bool _getSwitchingFullscreen() const;
+		
+		/// Indicate that fullscreen / windowed switching has finished
+		void _finishSwitchingFullscreen();
+	
+		/// Returns true if this window use depth buffer.
+		bool isDepthBuffered() const;
+
+		/// Returns true if this window should use NV perf hud adapter.
+		bool isNvPerfHUDEnable() const;
+
+		/** Validate the device for this window. */
+		bool _validateDevice();
+
+		void adjustWindow(unsigned int clientWidth, unsigned int clientHeight, 
+			DWORD style, unsigned int* winWidth, unsigned int* winHeight);
+
+	protected:
+		HINSTANCE					mInstance;				// Process instance
+		D3D9Device* 				mDevice;				// D3D9 device wrapper class.
+		bool						mDeviceValid;			// Device was validation succeeded.
+		HWND						mHWnd;					// Win32 Window handle		
+		bool						mIsExternal;			// window not created by Ogre
+		bool						mClosed;				// Is this window destroyed.		
+		bool						mSwitchingFullscreen;	// Are we switching from fullscreen to windowed or vice versa		
+		D3DMULTISAMPLE_TYPE			mFSAAType;				// AA type.
+		DWORD						mFSAAQuality;			// AA quality.
+		UINT						mDisplayFrequency;		// Display frequency.
+		bool						mVSync;					// Use vertical sync or not.
+		unsigned int				mVSyncInterval;		
+		bool						mUseNVPerfHUD;			// Use NV Perf HUD.
+		DWORD						mStyle;					// Window style currently used for this window.
+		// Desired width / height after resizing
+		unsigned int mDesiredWidth;
+		unsigned int mDesiredHeight;
+
+
+		void updateWindowRect();
+	};
+}
+#endif

+ 76 - 0
CamelotD3D9Renderer/Include/CmD3D9Resource.h

@@ -0,0 +1,76 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+(Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2011 Torus Knot Software 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.
+-----------------------------------------------------------------------------
+*/
+#ifndef __D3D9Resource_H__
+#define __D3D9Resource_H__
+
+#include "CmD3D9Prerequisites.h"
+
+namespace CamelotEngine {
+
+	/** Represents a Direct3D rendering resource.
+	Provide unified interface to
+	handle various device states.
+	*/
+	class CM_D3D9_EXPORT D3D9Resource
+	{
+
+	// Interface.
+	public:
+
+		// Called immediately after the Direct3D device has been created.
+		virtual void notifyOnDeviceCreate(IDirect3DDevice9* d3d9Device) {}
+
+		// Called before the Direct3D device is going to be destroyed.
+		virtual void notifyOnDeviceDestroy(IDirect3DDevice9* d3d9Device) {}
+
+		// Called immediately after the Direct3D device has entered a lost state.
+		// This is the place to release non-managed resources.
+		virtual void notifyOnDeviceLost(IDirect3DDevice9* d3d9Device) {}
+
+		// Called immediately after the Direct3D device has been reset.
+		// This is the place to create non-managed resources.
+		virtual void notifyOnDeviceReset(IDirect3DDevice9* d3d9Device) {}
+
+		// Called when device state is changing. Access to any device should be locked.
+		// Relevant for multi thread application.
+		static void lockDeviceAccess();
+
+		// Called when device state change completed. Access to any device is allowed.
+		// Relevant for multi thread application.
+		static void unlockDeviceAccess();
+
+
+	public:
+		D3D9Resource			();
+		virtual ~D3D9Resource	();
+
+	protected:
+		CM_STATIC_MUTEX(msDeviceAccessMutex)		
+	};
+}
+#endif

+ 113 - 0
CamelotD3D9Renderer/Include/CmD3D9ResourceManager.h

@@ -0,0 +1,113 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+(Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2011 Torus Knot Software 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.
+-----------------------------------------------------------------------------
+*/
+#ifndef __D3D9ResourceManager_H__
+#define __D3D9ResourceManager_H__
+
+#include "CmD3D9Prerequisites.h"
+
+namespace CamelotEngine {
+
+	enum D3D9ResourceCreationPolicy
+	{
+		// Creates the rendering resource on the current active device that needs it.
+		// This policy should be used when video memory consumption should be minimized but
+		// it might cause some performance issues when using loader resource thread since
+		// a resource that was not created on specified device will be created on demand during
+		// the rendering process and might cause the FPS to drop down. 
+		RCP_CREATE_ON_ACTIVE_DEVICE,
+
+		// Create the rendering resource on every existing device. 		
+		// This policy should be used when working intensively with a background loader thread.
+		// In that case when multiple devices exist, the resource will be created on each device
+		// and will be ready to use in the rendering thread. 
+		// The draw back can be some video memory waste in case that each device render different
+		// scene and doesn't really need all the resources.
+		RCP_CREATE_ON_ALL_DEVICES
+	};
+	
+	class CM_D3D9_EXPORT D3D9ResourceManager
+	{
+
+	// Interface.
+	public:
+
+		// Called immediately after the Direct3D device has been created.
+		void notifyOnDeviceCreate	(IDirect3DDevice9* d3d9Device);
+
+		// Called before the Direct3D device is going to be destroyed.
+		void notifyOnDeviceDestroy	(IDirect3DDevice9* d3d9Device);
+
+		// Called immediately after the Direct3D device has entered a lost state.
+		void notifyOnDeviceLost		(IDirect3DDevice9* d3d9Device);
+
+		// Called immediately after the Direct3D device has been reset.
+		void notifyOnDeviceReset	(IDirect3DDevice9* d3d9Device);
+
+		// Called when device state is changing. Access to any device should be locked.
+		// Relevant for multi thread application.
+		void lockDeviceAccess		();
+
+		// Called when device state change completed. Access to any device is allowed.
+		// Relevant for multi thread application.
+		void unlockDeviceAccess		();
+		
+		D3D9ResourceManager			();
+		~D3D9ResourceManager		();		
+
+		void						setCreationPolicy	(D3D9ResourceCreationPolicy creationPolicy);
+		D3D9ResourceCreationPolicy	getCreationPolicy	() const;
+		
+	// Friends.
+	protected:
+		friend class D3D9Resource;
+	
+	// Types.
+	protected:
+		typedef vector<D3D9Resource*>::type		ResourceContainer;
+		typedef ResourceContainer::iterator		ResourceContainerIterator;
+
+	// Protected methods.
+	protected:
+		
+		// Called when new resource created.
+		void _notifyResourceCreated		(D3D9Resource* pResource);
+
+		// Called when resource is about to be destroyed.
+		void _notifyResourceDestroyed	(D3D9Resource* pResource);
+				
+
+	// Attributes.
+	protected:		
+		CM_MUTEX(mResourcesMutex)
+		ResourceContainer			mResources;
+		D3D9ResourceCreationPolicy	mResourceCreationPolicy;
+		long						mDeviceAccessLockCount;		
+	};
+}
+
+#endif

+ 243 - 0
CamelotD3D9Renderer/Include/CmD3D9Texture.h

@@ -0,0 +1,243 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+    (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2011 Torus Knot Software 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.
+-----------------------------------------------------------------------------
+*/
+#ifndef __D3D9TEXTURE_H__
+#define __D3D9TEXTURE_H__
+
+#include "CmD3D9Prerequisites.h"
+#include "CmTexture.h"
+#include "CmRenderTexture.h"
+#include "CmException.h"
+#include "CmD3D9HardwarePixelBuffer.h"
+#include "CmD3D9Resource.h"
+
+namespace CamelotEngine {
+	class CM_D3D9_EXPORT D3D9Texture : public Texture, public D3D9Resource
+	{
+	protected:	
+
+		struct TextureResources
+		{
+			/// 1D/2D normal texture pointer
+			IDirect3DTexture9* pNormTex;	
+			/// cubic texture pointer
+			IDirect3DCubeTexture9* pCubeTex;	
+			/// Volume texture
+			IDirect3DVolumeTexture9* pVolumeTex;
+			/// actual texture pointer
+			IDirect3DBaseTexture9* pBaseTex;
+			/// Optional FSAA surface
+			IDirect3DSurface9* pFSAASurface;			
+		};
+		
+		typedef map<IDirect3DDevice9*, TextureResources*>::type	DeviceToTextureResourcesMap;
+		typedef DeviceToTextureResourcesMap::iterator			DeviceToTextureResourcesIterator;
+
+		/// Map between device to texture resources.
+		DeviceToTextureResourcesMap	mMapDeviceToTextureResources;
+
+
+		/// Vector of pointers to subsurfaces
+		typedef vector<HardwarePixelBufferPtr>::type SurfaceList;
+		SurfaceList	mSurfaceList;
+		/// cube texture individual face names
+		String							mCubeFaceNames[6];	
+		/// The memory pool being used
+		D3DPOOL							mD3DPool;
+		// Dynamic textures?
+		bool                            mDynamicTextures;
+		
+		/// Is hardware gamma supported (read)?
+		bool mHwGammaReadSupported;
+		/// Is hardware gamma supported (write)?
+		bool mHwGammaWriteSupported;
+		D3DMULTISAMPLE_TYPE mFSAAType;
+		DWORD mFSAAQuality;
+		
+		// TODO PORT - Loading tex from streams not supported
+        // needed to store data between prepareImpl and loadImpl
+        //typedef SharedPtr<vector<MemoryDataStreamPtr>::type > LoadedStreams;
+
+		/// internal method, load a cube texture
+		//void _loadCubeTex(IDirect3DDevice9* d3d9Device, const LoadedStreams &loadedStreams);
+		/// internal method, load a normal texture
+		//void _loadNormTex(IDirect3DDevice9* d3d9Device, const LoadedStreams &loadedStreams);
+		/// internal method, load a volume texture
+		//void _loadVolumeTex(IDirect3DDevice9* d3d9Device, const LoadedStreams &loadedStreams);
+
+		/// internal method, prepare a cube texture
+		//LoadedStreams _prepareCubeTex();
+		/// internal method, prepare a normal texture
+		//LoadedStreams _prepareNormTex();
+		/// internal method, prepare a volume texture
+		//LoadedStreams _prepareVolumeTex();
+
+		/// internal method, create a blank normal 1D/2D texture		
+		void _createNormTex(IDirect3DDevice9* d3d9Device);
+		/// internal method, create a blank cube texture		
+		void _createCubeTex(IDirect3DDevice9* d3d9Device);
+		/// internal method, create a blank cube texture		
+		void _createVolumeTex(IDirect3DDevice9* d3d9Device);
+
+		/// internal method, return a D3D pixel format for texture creation
+		D3DFORMAT _chooseD3DFormat(IDirect3DDevice9* d3d9Device);
+
+		/// @copydoc Resource::calculateSize
+		size_t calculateSize(void) const;
+		/// @copydoc Texture::createInternalResources
+		void createInternalResources(void);
+		/// @copydoc Texture::freeInternalResources
+		void freeInternalResources(void);
+		/// @copydoc Texture::createInternalResourcesImpl
+		void createInternalResourcesImpl(void);
+		/// Creates this texture resources on the specified device.
+		void createInternalResourcesImpl(IDirect3DDevice9* d3d9Device);
+		/// free internal resources
+		void freeInternalResourcesImpl(void);
+		/// internal method, set Texture class source image protected attributes
+		void _setSrcAttributes(unsigned long width, unsigned long height, unsigned long depth, PixelFormat format);
+		/// internal method, set Texture class final texture protected attributes
+		void _setFinalAttributes(IDirect3DDevice9* d3d9Device, TextureResources* textureResources, 
+			unsigned long width, unsigned long height, unsigned long depth, PixelFormat format);
+		/// internal method, return the best by hardware supported filter method
+		D3DTEXTUREFILTERTYPE _getBestFilterMethod(IDirect3DDevice9* d3d9Device);
+		/// internal method, return true if the device/texture combination can use dynamic textures
+		bool _canUseDynamicTextures(IDirect3DDevice9* d3d9Device, DWORD srcUsage, D3DRESOURCETYPE srcType, D3DFORMAT srcFormat);
+		/// internal method, return true if the device/texture combination can auto gen. mip maps
+		bool _canAutoGenMipmaps(IDirect3DDevice9* d3d9Device, DWORD srcUsage, D3DRESOURCETYPE srcType, D3DFORMAT srcFormat);
+		/// internal method, return true if the device/texture combination can use hardware gamma
+		bool _canUseHardwareGammaCorrection(IDirect3DDevice9* d3d9Device, DWORD srcUsage, D3DRESOURCETYPE srcType, D3DFORMAT srcFormat, bool forwriting);
+		
+		/// internal method, the cube map face name for the spec. face index
+		String _getCubeFaceName(unsigned char face) const
+		{ assert(face < 6); return mCubeFaceNames[face]; }
+		
+		/// internal method, create D3D9HardwarePixelBuffers for every face and
+		/// mipmap level. This method must be called after the D3D texture object was created
+		void _createSurfaceList(IDirect3DDevice9* d3d9Device, TextureResources* textureResources);
+
+        /// overriden from Resource
+        void loadImpl();		 
+		/// Loads this texture into the specified device.
+		void loadImpl(IDirect3DDevice9* d3d9Device);
+        /// overriden from Resource
+        void prepareImpl();
+        /// overriden from Resource
+        void unprepareImpl();
+		/// overriden from Resource
+		void postLoadImpl();
+
+		/// gets the texture resources attached to the given device.
+		TextureResources* getTextureResources(IDirect3DDevice9* d3d9Device);
+
+		/// allocates new texture resources structure attached to the given device.
+		TextureResources* allocateTextureResources(IDirect3DDevice9* d3d9Device);
+
+		/// creates this texture resources according to the current settings.
+		void createTextureResources(IDirect3DDevice9* d3d9Device);
+
+		/// frees the given texture resources.
+		void freeTextureResources(IDirect3DDevice9* d3d9Device, TextureResources* textureResources);
+
+		void determinePool();
+
+        /** Vector of pointers to streams that were pulled from disk by
+            prepareImpl  but have yet to be pushed into texture memory
+            by loadImpl.  Should be cleared on load and on unprepare.
+        */
+		// TODO PORT - Loading tex from streams not supported
+        //LoadedStreams mLoadedStreams;
+
+		friend class D3D9HardwarePixelBuffer;
+	public:
+		/// constructor 
+        D3D9Texture();
+		/// destructor
+		~D3D9Texture();
+
+		/// overridden from Texture
+		void copyToTexture( TexturePtr& target );
+
+
+		/// @copydoc Texture::getBuffer
+		HardwarePixelBufferPtr getBuffer(size_t face, size_t mipmap);
+		
+		/// retrieves a pointer to the actual texture
+		IDirect3DBaseTexture9 *getTexture();		
+		/// retrieves a pointer to the normal 1D/2D texture
+		IDirect3DTexture9 *getNormTexture();
+		/// retrieves a pointer to the cube texture
+		IDirect3DCubeTexture9 *getCubeTexture();
+
+		/** Indicates whether the hardware gamma is actually enabled and supported. 
+		@remarks
+			Because hardware gamma might not actually be supported, we need to 
+			ignore it sometimes. Because D3D doesn't encode sRGB in the format but
+			as a sampler state, and we don't want to change the original requested
+			hardware gamma flag (e.g. serialisation) we need another indicator.
+		*/
+		bool isHardwareGammaReadToBeUsed() const { return mHwGamma && mHwGammaReadSupported; }
+					
+		/// Will this texture need to be in the default pool?
+		bool useDefaultPool();
+
+		// Called immediately after the Direct3D device has been created.
+		virtual void notifyOnDeviceCreate(IDirect3DDevice9* d3d9Device);
+
+		// Called before the Direct3D device is going to be destroyed.
+		virtual void notifyOnDeviceDestroy(IDirect3DDevice9* d3d9Device);
+
+		// Called immediately after the Direct3D device has entered a lost state.
+		virtual void notifyOnDeviceLost(IDirect3DDevice9* d3d9Device);
+
+		// Called immediately after the Direct3D device has been reset
+		virtual void notifyOnDeviceReset(IDirect3DDevice9* d3d9Device);	
+    };
+
+	typedef std::shared_ptr<D3D9Texture> D3D9TexturePtr;
+
+    /// RenderTexture implementation for D3D9
+    class CM_D3D9_EXPORT D3D9RenderTexture : public RenderTexture
+    {
+    public:
+		D3D9RenderTexture(const String &name, D3D9HardwarePixelBuffer *buffer, bool writeGamma, UINT32 fsaa);
+        ~D3D9RenderTexture() {}
+
+		virtual void update(bool swap);
+
+		virtual void getCustomAttribute( const String& name, void *pData );
+
+		bool requiresTextureFlipping() const { return false; }
+
+		/// Override needed to deal with FSAA
+		void swapBuffers(bool waitForVSync = true);
+
+	};
+
+}
+
+#endif

+ 54 - 0
CamelotD3D9Renderer/Include/CmD3D9TextureManager.h

@@ -0,0 +1,54 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+    (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2011 Torus Knot Software 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.
+-----------------------------------------------------------------------------
+*/
+#ifndef __D3D9TEXTUREMANAGER_H__
+#define __D3D9TEXTUREMANAGER_H__
+
+#include "CmD3D9Prerequisites.h"
+#include "CmD3D9Texture.h"
+#include "CmTextureManager.h"
+
+namespace CamelotEngine 
+{
+	class CM_D3D9_EXPORT D3D9TextureManager : public TextureManager
+	{
+	public:
+		D3D9TextureManager();
+		~D3D9TextureManager();
+
+		/// @copydoc TextureManager::getNativeFormat
+		PixelFormat getNativeFormat(TextureType ttype, PixelFormat format, int usage);
+
+        /// @copydoc TextureManager::isHardwareFilteringSupported
+        bool isHardwareFilteringSupported(TextureType ttype, PixelFormat format, int usage,
+            bool preciseFormatOnly = false);		
+
+	protected:		
+		D3D9Texture* createImpl();
+	};
+}
+#endif

+ 90 - 0
CamelotD3D9Renderer/Include/CmD3D9VertexDeclaration.h

@@ -0,0 +1,90 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+    (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2011 Torus Knot Software 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.
+-----------------------------------------------------------------------------
+*/
+#ifndef __D3D9VERTEXDECLARATION_H__
+#define __D3D9VERTEXDECLARATION_H__
+
+#include "CmD3D9Prerequisites.h"
+#include "CmHardwareVertexBuffer.h"
+#include "CmD3D9Resource.h"
+
+namespace CamelotEngine { 
+
+    /** Specialisation of VertexDeclaration for D3D9 */
+    class CM_D3D9_EXPORT D3D9VertexDeclaration : public VertexDeclaration, public D3D9Resource
+    {
+    
+    public:
+        D3D9VertexDeclaration();
+        ~D3D9VertexDeclaration();
+        
+        /** See VertexDeclaration */
+        const VertexElement& addElement(unsigned short source, size_t offset, VertexElementType theType,
+            VertexElementSemantic semantic, unsigned short index = 0);
+
+        /** See VertexDeclaration */
+        const VertexElement& insertElement(unsigned short atPosition,
+            unsigned short source, size_t offset, VertexElementType theType,
+            VertexElementSemantic semantic, unsigned short index = 0);
+
+        /** See VertexDeclaration */
+        void removeElement(unsigned short elem_index);
+		
+		/** See VertexDeclaration */
+		void removeElement(VertexElementSemantic semantic, unsigned short index = 0);
+
+		/** See VertexDeclaration */
+		void removeAllElements(void);
+
+
+        /** See VertexDeclaration */
+        void modifyElement(unsigned short elem_index, unsigned short source, size_t offset, VertexElementType theType,
+            VertexElementSemantic semantic, unsigned short index = 0);
+
+		// Called immediately after the Direct3D device has been created.
+		virtual void notifyOnDeviceCreate(IDirect3DDevice9* d3d9Device);
+
+		// Called before the Direct3D device is going to be destroyed.
+		virtual void notifyOnDeviceDestroy(IDirect3DDevice9* d3d9Device);
+
+        /** Gets the D3D9-specific vertex declaration. */
+        IDirect3DVertexDeclaration9* getD3DVertexDeclaration(void);
+
+	protected:
+		void	releaseDeclaration();
+
+
+	protected:        
+		typedef map<IDirect3DDevice9*, IDirect3DVertexDeclaration9*>::type	DeviceToDeclarationMap;
+		typedef DeviceToDeclarationMap::iterator							DeviceToDeclarationIterator;
+
+		DeviceToDeclarationMap		mMapDeviceToDeclaration;
+    };
+
+}
+
+#endif

+ 63 - 0
CamelotD3D9Renderer/Include/CmD3D9VideoMode.h

@@ -0,0 +1,63 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+    (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2011 Torus Knot Software 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.
+-----------------------------------------------------------------------------
+*/
+#ifndef __D3D9VIDEOMODE_H__
+#define __D3D9VIDEOMODE_H__
+
+#include "CmD3D9Prerequisites.h"
+#include "CmString.h"
+
+namespace CamelotEngine 
+{
+	static unsigned int modeCount = 0;
+
+	class CM_D3D9_EXPORT D3D9VideoMode
+	{
+	private:
+		D3DDISPLAYMODE mDisplayMode;
+		unsigned int modeNumber;
+
+	public:
+		D3D9VideoMode() { modeNumber = ++modeCount; ZeroMemory( &mDisplayMode, sizeof(D3DDISPLAYMODE) ); }
+		D3D9VideoMode( const D3D9VideoMode &ob ) { modeNumber = ++modeCount; mDisplayMode = ob.mDisplayMode; }
+		D3D9VideoMode( D3DDISPLAYMODE d3ddm ) { modeNumber = ++modeCount; mDisplayMode = d3ddm; }
+		~D3D9VideoMode()
+		{
+			modeCount--;
+		}
+
+		unsigned int getWidth() const { return mDisplayMode.Width; }
+		unsigned int getHeight() const { return mDisplayMode.Height; }
+		D3DFORMAT getFormat() const { return mDisplayMode.Format; }
+		unsigned int getRefreshRate() const { return mDisplayMode.RefreshRate; }
+		unsigned int getColourDepth() const;
+		D3DDISPLAYMODE getDisplayMode() const { return mDisplayMode; }
+		void increaseRefreshRate(unsigned int rr) { mDisplayMode.RefreshRate = rr; } 
+		String getDescription() const;
+	};
+}
+#endif

+ 55 - 0
CamelotD3D9Renderer/Include/CmD3D9VideoModeList.h

@@ -0,0 +1,55 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+    (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2011 Torus Knot Software 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.
+-----------------------------------------------------------------------------
+*/
+#ifndef __D3D9VIDEOMODELIST_H__
+#define __D3D9VIDEOMODELIST_H__
+
+#include "CmD3D9Prerequisites.h"
+#include "CmD3D9Driver.h"
+#include "CmD3D9VideoMode.h"
+
+namespace CamelotEngine 
+{
+	class CM_D3D9_EXPORT D3D9VideoModeList
+	{
+	private:
+		D3D9Driver* mpDriver;
+		vector<D3D9VideoMode>::type mModeList;
+
+	public:
+		D3D9VideoModeList( D3D9Driver* pDriver );
+		~D3D9VideoModeList();
+
+		BOOL enumerate();
+
+		D3D9VideoMode* item( size_t index );
+		size_t count();
+
+		D3D9VideoMode* item( const String &name );
+	};
+}
+#endif

+ 0 - 0
CamelotRenderer/CmD3D9Device.cpp → CamelotD3D9Renderer/Source/CmD3D9Device.cpp


+ 0 - 0
CamelotRenderer/CmD3D9DeviceManager.cpp → CamelotD3D9Renderer/Source/CmD3D9DeviceManager.cpp


+ 0 - 0
CamelotRenderer/CmD3D9Driver.cpp → CamelotD3D9Renderer/Source/CmD3D9Driver.cpp


+ 0 - 0
CamelotRenderer/CmD3D9DriverList.cpp → CamelotD3D9Renderer/Source/CmD3D9DriverList.cpp


+ 0 - 0
CamelotRenderer/CmD3D9GpuProgram.cpp → CamelotD3D9Renderer/Source/CmD3D9GpuProgram.cpp


+ 0 - 0
CamelotRenderer/CmD3D9GpuProgramManager.cpp → CamelotD3D9Renderer/Source/CmD3D9GpuProgramManager.cpp


+ 584 - 0
CamelotD3D9Renderer/Source/CmD3D9HLSLProgram.cpp

@@ -0,0 +1,584 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+(Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2011 Torus Knot Software 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 "CmD3D9HLSLProgram.h"
+#include "CmGpuProgramManager.h"
+#include "CmD3D9GpuProgram.h"
+#include "CmException.h"
+#include "CmRenderSystem.h"
+#include "CmRenderSystemManager.h"
+
+namespace CamelotEngine {
+	class CM_D3D9_EXPORT HLSLIncludeHandler : public ID3DXInclude
+	{
+	public:
+		HLSLIncludeHandler(HighLevelGpuProgram* sourceProgram) 
+			: mProgram(sourceProgram) {}
+		~HLSLIncludeHandler() {}
+		
+		STDMETHOD(Open)(D3DXINCLUDE_TYPE IncludeType,
+			LPCSTR pFileName,
+			LPCVOID pParentData,
+			LPCVOID *ppData,
+			UINT *pByteLen
+			)
+		{
+			// TODO PORT - I'm not sure what to do with this. It will probably break something in its current state.
+
+			//// find & load source code
+			//DataStreamPtr stream = 
+			//	ResourceGroupManager::getSingleton().openResource(
+			//	String(pFileName), mProgram->getGroup(), true, mProgram);
+
+			//String source = stream->getAsString();
+			//// copy into separate c-string
+			//// Note - must NOT copy the null terminator, otherwise this will terminate
+			//// the entire program string!
+			//*pByteLen = static_cast<UINT>(source.length());
+			//char* pChar = new char[*pByteLen];
+			//memcpy(pChar, source.c_str(), *pByteLen);
+			//*ppData = pChar;
+
+			assert(false); // TODO - Include files not supported until I can figure out how to handle them
+
+			return S_OK;
+		}
+
+		STDMETHOD(Close)(LPCVOID pData)
+		{
+			char* pChar = (char*)pData;
+			delete [] pChar;
+			return S_OK;
+		}
+	protected:
+		HighLevelGpuProgram* mProgram;
+
+
+	};
+
+	String gpuProgramProfileToHLSLProfile(GpuProgramProfile profile)
+	{
+		switch(profile)
+		{
+		case GPP_PS_1_1:
+			return "ps_1_1";
+		case GPP_PS_1_2:
+			return "ps_1_2";
+		case GPP_PS_1_3:
+			return "ps_1_3";
+		case GPP_PS_1_4:
+			return "ps_1_4";
+		case GPP_PS_2_0:
+			return "ps_2_0";
+		case GPP_PS_2_a:
+			return "ps_2_a";
+		case GPP_PS_2_b:
+			return "ps_2_b";
+		case GPP_PS_3_0:
+			return "ps_3_0";
+		case GPP_VS_1_1:
+			return "vs_1_1";
+		case GPP_VS_2_0:
+			return "vs_2_0";
+		case GPP_VS_2_a:
+			return "vs_2_a";
+		case GPP_VS_3_0:
+			return "vs_3_1";
+		default:
+			assert(false); // Unsupported profile
+		}
+
+		return "";
+	}
+
+    //-----------------------------------------------------------------------
+    //-----------------------------------------------------------------------
+    void D3D9HLSLProgram::loadFromSource(void)
+    {
+        // Populate preprocessor defines
+        String stringBuffer;
+
+        vector<D3DXMACRO>::type defines;
+        const D3DXMACRO* pDefines = 0;
+        if (!mPreprocessorDefines.empty())
+        {
+            stringBuffer = mPreprocessorDefines;
+
+            // Split preprocessor defines and build up macro array
+            D3DXMACRO macro;
+            String::size_type pos = 0;
+            while (pos != String::npos)
+            {
+                macro.Name = &stringBuffer[pos];
+                macro.Definition = 0;
+
+				String::size_type start_pos=pos;
+
+                // Find delims
+                pos = stringBuffer.find_first_of(";,=", pos);
+
+				if(start_pos==pos)
+				{
+					if(pos==stringBuffer.length())
+					{
+						break;
+					}
+					pos++;
+					continue;
+				}
+
+                if (pos != String::npos)
+                {
+                    // Check definition part
+                    if (stringBuffer[pos] == '=')
+                    {
+                        // Setup null character for macro name
+                        stringBuffer[pos++] = '\0';
+                        macro.Definition = &stringBuffer[pos];
+                        pos = stringBuffer.find_first_of(";,", pos);
+                    }
+                    else
+                    {
+                        // No definition part, define as "1"
+                        macro.Definition = "1";
+                    }
+
+                    if (pos != String::npos)
+                    {
+                        // Setup null character for macro name or definition
+                        stringBuffer[pos++] = '\0';
+                    }
+                }
+				else
+				{
+					macro.Definition = "1";
+				}
+				if(strlen(macro.Name)>0)
+				{
+					defines.push_back(macro);
+				}
+				else
+				{
+					break;
+				}
+            }
+
+            // Add NULL terminator
+            macro.Name = 0;
+            macro.Definition = 0;
+            defines.push_back(macro);
+
+            pDefines = &defines[0];
+        }
+
+        // Populate compile flags
+        DWORD compileFlags = 0;
+        if (mColumnMajorMatrices)
+            compileFlags |= D3DXSHADER_PACKMATRIX_COLUMNMAJOR;
+        else
+            compileFlags |= D3DXSHADER_PACKMATRIX_ROWMAJOR;
+
+#if CM_DEBUG_MODE
+		compileFlags |= D3DXSHADER_DEBUG;
+#endif
+		switch (mOptimisationLevel)
+		{
+		case OPT_DEFAULT:
+			compileFlags |= D3DXSHADER_OPTIMIZATION_LEVEL1;
+			break;
+		case OPT_NONE:
+			compileFlags |= D3DXSHADER_SKIPOPTIMIZATION;
+			break;
+		case OPT_0:
+			compileFlags |= D3DXSHADER_OPTIMIZATION_LEVEL0;
+			break;
+		case OPT_1:
+			compileFlags |= D3DXSHADER_OPTIMIZATION_LEVEL1;
+			break;
+		case OPT_2:
+			compileFlags |= D3DXSHADER_OPTIMIZATION_LEVEL2;
+			break;
+		case OPT_3:
+			compileFlags |= D3DXSHADER_OPTIMIZATION_LEVEL3;
+			break;
+		}
+
+
+        LPD3DXBUFFER errors = 0;
+
+		// include handler
+		HLSLIncludeHandler includeHandler(this);
+
+		String hlslProfile = gpuProgramProfileToHLSLProfile(mProfile);
+
+        // Compile & assemble into microcode
+        HRESULT hr = D3DXCompileShader(
+            mSource.c_str(),
+            static_cast<UINT>(mSource.length()),
+            pDefines,
+            &includeHandler, 
+            mEntryPoint.c_str(),
+            hlslProfile.c_str(),
+            compileFlags,
+            &mpMicroCode,
+            &errors,
+            &mpConstTable);
+
+        if (FAILED(hr))
+        {
+            String message = "Cannot assemble D3D9 high-level shader ";
+			
+			if( errors )
+			{
+				message += String(" Errors:\n") + static_cast<const char*>(errors->GetBufferPointer());
+				errors->Release();
+			}
+
+            OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, message,
+                "D3D9HLSLProgram::loadFromSource");
+        }
+
+
+    }
+    //-----------------------------------------------------------------------
+    void D3D9HLSLProgram::createLowLevelImpl(void)
+    {
+		if (!mCompileError)
+		{
+			String hlslProfile = gpuProgramProfileToHLSLProfile(mProfile);
+
+			// Create a low-level program, give it the same name as us
+			mAssemblerProgram = 
+				GpuProgramManager::getSingleton().createProgram(
+					"",// dummy source, since we'll be using microcode
+					mType, 
+					hlslProfile);
+			static_cast<D3D9GpuProgram*>(mAssemblerProgram.get())->setExternalMicrocode(mpMicroCode);
+		}
+
+    }
+    //-----------------------------------------------------------------------
+    void D3D9HLSLProgram::unloadHighLevelImpl(void)
+    {
+        SAFE_RELEASE(mpMicroCode);
+        SAFE_RELEASE(mpConstTable);
+
+    }
+    //-----------------------------------------------------------------------
+    void D3D9HLSLProgram::buildConstantDefinitions() const
+    {
+        // Derive parameter names from const table
+        assert(mpConstTable && "Program not loaded!");
+        // Get contents of the constant table
+        D3DXCONSTANTTABLE_DESC desc;
+        HRESULT hr = mpConstTable->GetDesc(&desc);
+
+		createParameterMappingStructures(true);
+
+        if (FAILED(hr))
+        {
+            OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, 
+                "Cannot retrieve constant descriptions from HLSL program.", 
+                "D3D9HLSLProgram::buildParameterNameMap");
+        }
+        // Iterate over the constants
+        for (unsigned int i = 0; i < desc.Constants; ++i)
+        {
+            // Recursively descend through the structure levels
+            processParamElement(NULL, "", i);
+        }
+
+        
+    }
+    //-----------------------------------------------------------------------
+    void D3D9HLSLProgram::processParamElement(D3DXHANDLE parent, String prefix, 
+        unsigned int index) const
+    {
+        D3DXHANDLE hConstant = mpConstTable->GetConstant(parent, index);
+
+        // Since D3D HLSL doesn't deal with naming of array and struct parameters
+        // automatically, we have to do it by hand
+
+        D3DXCONSTANT_DESC desc;
+        unsigned int numParams = 1;
+        HRESULT hr = mpConstTable->GetConstantDesc(hConstant, &desc, &numParams);
+        if (FAILED(hr))
+        {
+            OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, 
+                "Cannot retrieve constant description from HLSL program.", 
+                "D3D9HLSLProgram::processParamElement");
+        }
+
+        String paramName = desc.Name;
+        // trim the odd '$' which appears at the start of the names in HLSL
+        if (paramName.at(0) == '$')
+            paramName.erase(paramName.begin());
+
+		// Also trim the '[0]' suffix if it exists, we will add our own indexing later
+		if (StringUtil::endsWith(paramName, "[0]", false))
+		{
+			paramName.erase(paramName.size() - 3);
+		}
+
+
+        if (desc.Class == D3DXPC_STRUCT)
+        {
+            // work out a new prefix for nested members, if it's an array, we need an index
+            prefix = prefix + paramName + ".";
+            // Cascade into struct
+            for (unsigned int i = 0; i < desc.StructMembers; ++i)
+            {
+                processParamElement(hConstant, prefix, i);
+            }
+        }
+        else
+        {
+            // Process params
+            if (desc.Type == D3DXPT_FLOAT || desc.Type == D3DXPT_INT || desc.Type == D3DXPT_BOOL)
+            {
+                size_t paramIndex = desc.RegisterIndex;
+                String name = prefix + paramName;
+                
+				GpuConstantDefinition def;
+				def.logicalIndex = paramIndex;
+				// populate type, array size & element size
+				populateDef(desc, def);
+				if (def.isFloat())
+				{
+					def.physicalIndex = mFloatLogicalToPhysical->bufferSize;
+					CM_LOCK_MUTEX(mFloatLogicalToPhysical->mutex)
+					mFloatLogicalToPhysical->map.insert(
+						GpuLogicalIndexUseMap::value_type(paramIndex, 
+						GpuLogicalIndexUse(def.physicalIndex, def.arraySize * def.elementSize, GPV_GLOBAL)));
+					mFloatLogicalToPhysical->bufferSize += def.arraySize * def.elementSize;
+					mConstantDefs->floatBufferSize = mFloatLogicalToPhysical->bufferSize;
+				}
+				else
+				{
+					def.physicalIndex = mIntLogicalToPhysical->bufferSize;
+					CM_LOCK_MUTEX(mIntLogicalToPhysical->mutex)
+					mIntLogicalToPhysical->map.insert(
+						GpuLogicalIndexUseMap::value_type(paramIndex, 
+						GpuLogicalIndexUse(def.physicalIndex, def.arraySize * def.elementSize, GPV_GLOBAL)));
+					mIntLogicalToPhysical->bufferSize += def.arraySize * def.elementSize;
+					mConstantDefs->intBufferSize = mIntLogicalToPhysical->bufferSize;
+				}
+
+                mConstantDefs->map.insert(GpuConstantDefinitionMap::value_type(name, def));
+
+				// Now deal with arrays
+				mConstantDefs->generateConstantDefinitionArrayEntries(name, def);
+            }
+        }
+            
+    }
+	//-----------------------------------------------------------------------
+	void D3D9HLSLProgram::populateDef(D3DXCONSTANT_DESC& d3dDesc, GpuConstantDefinition& def) const
+	{
+		def.arraySize = d3dDesc.Elements;
+		switch(d3dDesc.Type)
+		{
+		case D3DXPT_INT:
+			switch(d3dDesc.Columns)
+			{
+			case 1:
+				def.constType = GCT_INT1;
+				break;
+			case 2:
+				def.constType = GCT_INT2;
+				break;
+			case 3:
+				def.constType = GCT_INT3;
+				break;
+			case 4:
+				def.constType = GCT_INT4;
+				break;
+			} // columns
+			break;
+		case D3DXPT_FLOAT:
+			switch(d3dDesc.Class)
+			{
+			case D3DXPC_MATRIX_COLUMNS:
+			case D3DXPC_MATRIX_ROWS:
+				{
+					int firstDim, secondDim;
+					firstDim = d3dDesc.RegisterCount / d3dDesc.Elements;
+					if (d3dDesc.Class == D3DXPC_MATRIX_ROWS)
+					{
+						secondDim = d3dDesc.Columns;
+					}
+					else
+					{
+						secondDim = d3dDesc.Rows;
+					}
+					switch(firstDim)
+					{
+					case 2:
+						switch(secondDim)
+						{
+						case 2:
+							def.constType = GCT_MATRIX_2X2;
+							def.elementSize = 8; // HLSL always packs
+							break;
+						case 3:
+							def.constType = GCT_MATRIX_2X3;
+							def.elementSize = 8; // HLSL always packs
+							break;
+						case 4:
+							def.constType = GCT_MATRIX_2X4;
+							def.elementSize = 8; 
+							break;
+						} // columns
+						break;
+					case 3:
+						switch(secondDim)
+						{
+						case 2:
+							def.constType = GCT_MATRIX_3X2;
+							def.elementSize = 12; // HLSL always packs
+							break;
+						case 3:
+							def.constType = GCT_MATRIX_3X3;
+							def.elementSize = 12; // HLSL always packs
+							break;
+						case 4:
+							def.constType = GCT_MATRIX_3X4;
+							def.elementSize = 12; 
+							break;
+						} // columns
+						break;
+					case 4:
+						switch(secondDim)
+						{
+						case 2:
+							def.constType = GCT_MATRIX_4X2;
+							def.elementSize = 16; // HLSL always packs
+							break;
+						case 3:
+							def.constType = GCT_MATRIX_4X3;
+							def.elementSize = 16; // HLSL always packs
+							break;
+						case 4:
+							def.constType = GCT_MATRIX_4X4;
+							def.elementSize = 16; 
+							break;
+						} // secondDim
+						break;
+
+					} // firstDim
+				}
+				break;
+			case D3DXPC_SCALAR:
+			case D3DXPC_VECTOR:
+				switch(d3dDesc.Columns)
+				{
+				case 1:
+					def.constType = GCT_FLOAT1;
+					break;
+				case 2:
+					def.constType = GCT_FLOAT2;
+					break;
+				case 3:
+					def.constType = GCT_FLOAT3;
+					break;
+				case 4:
+					def.constType = GCT_FLOAT4;
+					break;
+				} // columns
+				break;
+			}
+		default:
+			// not mapping samplers, don't need to take the space 
+			break;
+		};
+
+		// D3D9 pads to 4 elements
+		def.elementSize = GpuConstantDefinition::getElementSize(def.constType, true);
+
+
+	}
+
+	LPD3DXBUFFER D3D9HLSLProgram::getMicroCode()
+	{
+		return mpMicroCode;
+	}
+
+	const String D3D9HLSLProgram::getTarget(void) const
+	{
+		return gpuProgramProfileToHLSLProfile(mProfile);
+	}
+
+    //-----------------------------------------------------------------------
+    D3D9HLSLProgram::D3D9HLSLProgram()
+        : HighLevelGpuProgram()
+        , mPreprocessorDefines()
+        , mColumnMajorMatrices(true)
+        , mpMicroCode(NULL), mpConstTable(NULL)
+		, mOptimisationLevel(OPT_DEFAULT)
+	{
+    }
+    //-----------------------------------------------------------------------
+    D3D9HLSLProgram::~D3D9HLSLProgram()
+    {
+        unloadHighLevel();
+    }
+    //-----------------------------------------------------------------------
+    bool D3D9HLSLProgram::isSupported(void) const
+    {
+        if (mCompileError || !isRequiredCapabilitiesSupported())
+            return false;
+
+		String hlslProfile = gpuProgramProfileToHLSLProfile(mProfile);
+
+		RenderSystem* rs = CamelotEngine::RenderSystemManager::getActive();
+		return rs->getCapabilities()->isShaderProfileSupported(hlslProfile);
+    }
+    //-----------------------------------------------------------------------
+    GpuProgramParametersSharedPtr D3D9HLSLProgram::createParameters(void)
+    {
+        // Call superclass
+        GpuProgramParametersSharedPtr params = HighLevelGpuProgram::createParameters();
+
+        // Need to transpose matrices if compiled with column-major matrices
+        params->setTransposeMatrices(mColumnMajorMatrices);
+
+        return params;
+    }
+    //-----------------------------------------------------------------------
+    void D3D9HLSLProgram::setTarget(const String& target)
+    {
+        //mTarget = target;
+    }
+
+    //-----------------------------------------------------------------------
+    const String& D3D9HLSLProgram::getLanguage(void) const
+    {
+        static const String language = "hlsl";
+
+        return language;
+    }
+}

+ 0 - 0
CamelotRenderer/CmD3D9HLSLProgramFactory.cpp → CamelotD3D9Renderer/Source/CmD3D9HLSLProgramFactory.cpp


+ 0 - 0
CamelotRenderer/CmD3D9HardwareBufferManager.cpp → CamelotD3D9Renderer/Source/CmD3D9HardwareBufferManager.cpp


+ 0 - 0
CamelotRenderer/CmD3D9HardwareIndexBuffer.cpp → CamelotD3D9Renderer/Source/CmD3D9HardwareIndexBuffer.cpp


+ 0 - 0
CamelotRenderer/CmD3D9HardwareOcclusionQuery.cpp → CamelotD3D9Renderer/Source/CmD3D9HardwareOcclusionQuery.cpp


+ 0 - 0
CamelotRenderer/CmD3D9HardwarePixelBuffer.cpp → CamelotD3D9Renderer/Source/CmD3D9HardwarePixelBuffer.cpp


+ 0 - 0
CamelotRenderer/CmD3D9HardwareVertexBuffer.cpp → CamelotD3D9Renderer/Source/CmD3D9HardwareVertexBuffer.cpp


+ 0 - 0
CamelotRenderer/CmD3D9Mappings.cpp → CamelotD3D9Renderer/Source/CmD3D9Mappings.cpp


+ 0 - 0
CamelotRenderer/CmD3D9MultiRenderTarget.cpp → CamelotD3D9Renderer/Source/CmD3D9MultiRenderTarget.cpp


+ 0 - 0
CamelotRenderer/CmD3D9RenderSystem.cpp → CamelotD3D9Renderer/Source/CmD3D9RenderSystem.cpp


+ 0 - 0
CamelotRenderer/CmD3D9RenderSystemFactory.cpp → CamelotD3D9Renderer/Source/CmD3D9RenderSystemFactory.cpp


+ 0 - 0
CamelotRenderer/CmD3D9RenderWindow.cpp → CamelotD3D9Renderer/Source/CmD3D9RenderWindow.cpp


+ 0 - 0
CamelotRenderer/CmD3D9Resource.cpp → CamelotD3D9Renderer/Source/CmD3D9Resource.cpp


+ 0 - 0
CamelotRenderer/CmD3D9ResourceManager.cpp → CamelotD3D9Renderer/Source/CmD3D9ResourceManager.cpp


+ 0 - 0
CamelotRenderer/CmD3D9Texture.cpp → CamelotD3D9Renderer/Source/CmD3D9Texture.cpp


+ 0 - 0
CamelotRenderer/CmD3D9TextureManager.cpp → CamelotD3D9Renderer/Source/CmD3D9TextureManager.cpp


+ 0 - 0
CamelotRenderer/CmD3D9VertexDeclaration.cpp → CamelotD3D9Renderer/Source/CmD3D9VertexDeclaration.cpp


+ 0 - 0
CamelotRenderer/CmD3D9VideoMode.cpp → CamelotD3D9Renderer/Source/CmD3D9VideoMode.cpp


+ 0 - 0
CamelotRenderer/CmD3D9VideoModeList.cpp → CamelotD3D9Renderer/Source/CmD3D9VideoModeList.cpp


+ 161 - 0
CamelotGLRenderer/CamelotGLRenderer.vcxproj

@@ -0,0 +1,161 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup Label="ProjectConfigurations">
+    <ProjectConfiguration Include="Debug|Win32">
+      <Configuration>Debug</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|Win32">
+      <Configuration>Release</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+  </ItemGroup>
+  <PropertyGroup Label="Globals">
+    <ProjectGuid>{F58FF869-2EA6-4FFF-AB84-328C531BA9D9}</ProjectGuid>
+    <RootNamespace>CamelotGLRenderer</RootNamespace>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
+    <ConfigurationType>DynamicLibrary</ConfigurationType>
+    <UseDebugLibraries>true</UseDebugLibraries>
+    <PlatformToolset>v110</PlatformToolset>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
+    <ConfigurationType>DynamicLibrary</ConfigurationType>
+    <UseDebugLibraries>false</UseDebugLibraries>
+    <PlatformToolset>v110</PlatformToolset>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <PropertyGroup Label="UserMacros" />
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <OutDir>..\bin\$(Configuration)\</OutDir>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <OutDir>..\bin\$(Configuration)\</OutDir>
+  </PropertyGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <ClCompile>
+      <WarningLevel>Level3</WarningLevel>
+      <Optimization>Disabled</Optimization>
+      <AdditionalIncludeDirectories>./Source/win32;./Source/GLSL/include;./Source/atifs/include;../CamelotUtility/Include;../CamelotRenderer/Include;./Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>_WINDLL;CM_RSGL_DLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+    </ClCompile>
+    <Link>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <AdditionalDependencies>glu32.lib;opengl32.lib;CamelotRenderer.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <ImportLibrary>..lib\$(Configuration)\$(TargetName).lib</ImportLibrary>
+      <AdditionalLibraryDirectories>..\lib\$(Configuration);%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <ClCompile>
+      <WarningLevel>Level3</WarningLevel>
+      <Optimization>MaxSpeed</Optimization>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <IntrinsicFunctions>true</IntrinsicFunctions>
+      <AdditionalIncludeDirectories>./Source/win32;./Source/GLSL/include;./Source/atifs/include;../CamelotUtility/Include;../CamelotRenderer/Include;./Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>_WINDLL;CM_RSGL_DLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+    </ClCompile>
+    <Link>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <EnableCOMDATFolding>true</EnableCOMDATFolding>
+      <OptimizeReferences>true</OptimizeReferences>
+      <AdditionalDependencies>glu32.lib;opengl32.lib;CamelotRenderer.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <ImportLibrary>..lib\$(Configuration)\$(TargetName).lib</ImportLibrary>
+      <AdditionalLibraryDirectories>..\lib\$(Configuration)</AdditionalLibraryDirectories>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemGroup>
+    <ClInclude Include="Include\CmGLATIFSInit.h" />
+    <ClInclude Include="Include\CmGLContext.h" />
+    <ClInclude Include="Include\CmGLDefaultHardwareBufferManager.h" />
+    <ClInclude Include="Include\CmGLFBOMultiRenderTarget.h" />
+    <ClInclude Include="Include\CmGLFBORenderTexture.h" />
+    <ClInclude Include="Include\CmGLFrameBufferObject.h" />
+    <ClInclude Include="Include\CmGLGpuProgram.h" />
+    <ClInclude Include="Include\CmGLGpuProgramManager.h" />
+    <ClInclude Include="Include\CmGLHardwareBufferManager.h" />
+    <ClInclude Include="Include\CmGLHardwareIndexBuffer.h" />
+    <ClInclude Include="Include\CmGLHardwareOcclusionQuery.h" />
+    <ClInclude Include="Include\CmGLHardwarePixelBuffer.h" />
+    <ClInclude Include="Include\CmGLHardwareVertexBuffer.h" />
+    <ClInclude Include="Include\CmGLPBRenderTexture.h" />
+    <ClInclude Include="Include\CmGLPBuffer.h" />
+    <ClInclude Include="Include\CmGLPixelFormat.h" />
+    <ClInclude Include="Include\CmGLPrerequisites.h" />
+    <ClInclude Include="Include\CmGLRenderSystem.h" />
+    <ClInclude Include="Include\CmGLRenderSystemFactory.h" />
+    <ClInclude Include="Include\CmGLRenderTexture.h" />
+    <ClInclude Include="Include\CmGLSupport.h" />
+    <ClInclude Include="Include\CmGLTexture.h" />
+    <ClInclude Include="Include\CmGLTextureManager.h" />
+    <ClInclude Include="Include\CmWin32Context.h" />
+    <ClInclude Include="Include\CmWin32GLSupport.h" />
+    <ClInclude Include="Include\CmWin32Prerequisites.h" />
+    <ClInclude Include="Include\CmWin32RenderTexture.h" />
+    <ClInclude Include="Include\CmWin32Window.h" />
+    <ClInclude Include="Source\atifs\include\ATI_FS_GLGpuProgram.h" />
+    <ClInclude Include="Source\atifs\include\Compiler2Pass.h" />
+    <ClInclude Include="Source\atifs\include\ps_1_4.h" />
+    <ClInclude Include="Source\GLSL\include\CmGLSLExtSupport.h" />
+    <ClInclude Include="Source\GLSL\include\CmGLSLGpuProgram.h" />
+    <ClInclude Include="Source\GLSL\include\CmGLSLLinkProgram.h" />
+    <ClInclude Include="Source\GLSL\include\CmGLSLLinkProgramManager.h" />
+    <ClInclude Include="Source\GLSL\include\CmGLSLPreprocessor.h" />
+    <ClInclude Include="Source\GLSL\include\CmGLSLProgram.h" />
+    <ClInclude Include="Source\GLSL\include\CmGLSLProgramFactory.h" />
+    <ClInclude Include="Source\win32\CmGLUtil.h" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="Source\atifs\src\ATI_FS_GLGpuProgram.cpp" />
+    <ClCompile Include="Source\atifs\src\Compiler2Pass.cpp" />
+    <ClCompile Include="Source\atifs\src\ps_1_4.cpp" />
+    <ClCompile Include="Source\CmGLATIFSInit.cpp" />
+    <ClCompile Include="Source\CmGLContext.cpp" />
+    <ClCompile Include="Source\CmGLDefaultHardwareBufferManager.cpp" />
+    <ClCompile Include="Source\CmGLFBOMultiRenderTarget.cpp" />
+    <ClCompile Include="Source\CmGLFBORenderTexture.cpp" />
+    <ClCompile Include="Source\CmGLFrameBufferObject.cpp" />
+    <ClCompile Include="Source\CmGLGpuProgram.cpp" />
+    <ClCompile Include="Source\CmGLGpuProgramManager.cpp" />
+    <ClCompile Include="Source\CmGLHardwareBufferManager.cpp" />
+    <ClCompile Include="Source\CmGLHardwareIndexBuffer.cpp" />
+    <ClCompile Include="Source\CmGLHardwareOcclusionQuery.cpp" />
+    <ClCompile Include="Source\CmGLHardwarePixelBuffer.cpp" />
+    <ClCompile Include="Source\CmGLHardwareVertexBuffer.cpp" />
+    <ClCompile Include="Source\CmGLPBRenderTexture.cpp" />
+    <ClCompile Include="Source\CmGLPixelFormat.cpp" />
+    <ClCompile Include="Source\CmGLRenderSystem.cpp" />
+    <ClCompile Include="Source\CmGLRenderSystemFactory.cpp" />
+    <ClCompile Include="Source\CmGLRenderTexture.cpp" />
+    <ClCompile Include="Source\CmGLSupport.cpp" />
+    <ClCompile Include="Source\CmGLTexture.cpp" />
+    <ClCompile Include="Source\CmGLTextureManager.cpp" />
+    <ClCompile Include="Source\CmWin32GLSupport.cpp" />
+    <ClCompile Include="Source\CmWin32RenderTexture.cpp" />
+    <ClCompile Include="Source\CmWin32Window.cpp" />
+    <ClCompile Include="Source\glew.cpp" />
+    <ClCompile Include="Source\GLSL\src\CmGLSLExtSupport.cpp" />
+    <ClCompile Include="Source\GLSL\src\CmGLSLGpuProgram.cpp" />
+    <ClCompile Include="Source\GLSL\src\CmGLSLLinkProgram.cpp" />
+    <ClCompile Include="Source\GLSL\src\CmGLSLLinkProgramManager.cpp" />
+    <ClCompile Include="Source\GLSL\src\CmGLSLPreprocessor.cpp" />
+    <ClCompile Include="Source\GLSL\src\CmGLSLProgram.cpp" />
+    <ClCompile Include="Source\GLSL\src\CmGLSLProgramFactory.cpp" />
+    <ClCompile Include="Source\win32\CmWin32Context.cpp" />
+  </ItemGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>

+ 255 - 0
CamelotGLRenderer/CamelotGLRenderer.vcxproj.filters

@@ -0,0 +1,255 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <Filter Include="Source Files">
+      <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
+      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+    </Filter>
+    <Filter Include="Header Files">
+      <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
+      <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
+    </Filter>
+    <Filter Include="Resource Files">
+      <UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
+      <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
+    </Filter>
+    <Filter Include="ATIFS">
+      <UniqueIdentifier>{2c02e8a0-bcb2-415a-8740-10cb94cfbb80}</UniqueIdentifier>
+    </Filter>
+    <Filter Include="GLSL">
+      <UniqueIdentifier>{23f5e949-4542-49d4-86f9-d24656b5de08}</UniqueIdentifier>
+    </Filter>
+    <Filter Include="Win32">
+      <UniqueIdentifier>{c85ecca8-4719-49f1-879b-93a27c8da4aa}</UniqueIdentifier>
+    </Filter>
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="Include\CmGLATIFSInit.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="Include\CmGLContext.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="Include\CmGLDefaultHardwareBufferManager.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="Include\CmGLFBOMultiRenderTarget.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="Include\CmGLFBORenderTexture.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="Include\CmGLFrameBufferObject.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="Include\CmGLGpuProgram.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="Include\CmGLGpuProgramManager.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="Include\CmGLHardwareBufferManager.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="Include\CmGLHardwareIndexBuffer.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="Include\CmGLHardwareOcclusionQuery.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="Include\CmGLHardwarePixelBuffer.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="Include\CmGLHardwareVertexBuffer.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="Include\CmGLPBRenderTexture.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="Include\CmGLPBuffer.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="Include\CmGLPixelFormat.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="Include\CmGLPrerequisites.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="Include\CmGLRenderSystem.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="Include\CmGLRenderSystemFactory.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="Include\CmGLRenderTexture.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="Include\CmGLSupport.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="Include\CmGLTexture.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="Include\CmGLTextureManager.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="Include\CmWin32Context.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="Include\CmWin32GLSupport.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="Include\CmWin32Prerequisites.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="Include\CmWin32RenderTexture.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="Include\CmWin32Window.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="Source\atifs\include\ATI_FS_GLGpuProgram.h">
+      <Filter>ATIFS</Filter>
+    </ClInclude>
+    <ClInclude Include="Source\atifs\include\Compiler2Pass.h">
+      <Filter>ATIFS</Filter>
+    </ClInclude>
+    <ClInclude Include="Source\atifs\include\ps_1_4.h">
+      <Filter>ATIFS</Filter>
+    </ClInclude>
+    <ClInclude Include="Source\GLSL\include\CmGLSLExtSupport.h">
+      <Filter>GLSL</Filter>
+    </ClInclude>
+    <ClInclude Include="Source\GLSL\include\CmGLSLGpuProgram.h">
+      <Filter>GLSL</Filter>
+    </ClInclude>
+    <ClInclude Include="Source\GLSL\include\CmGLSLLinkProgram.h">
+      <Filter>GLSL</Filter>
+    </ClInclude>
+    <ClInclude Include="Source\GLSL\include\CmGLSLLinkProgramManager.h">
+      <Filter>GLSL</Filter>
+    </ClInclude>
+    <ClInclude Include="Source\GLSL\include\CmGLSLPreprocessor.h">
+      <Filter>GLSL</Filter>
+    </ClInclude>
+    <ClInclude Include="Source\GLSL\include\CmGLSLProgram.h">
+      <Filter>GLSL</Filter>
+    </ClInclude>
+    <ClInclude Include="Source\GLSL\include\CmGLSLProgramFactory.h">
+      <Filter>GLSL</Filter>
+    </ClInclude>
+    <ClInclude Include="Source\win32\CmGLUtil.h">
+      <Filter>Win32</Filter>
+    </ClInclude>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="Source\atifs\src\ATI_FS_GLGpuProgram.cpp">
+      <Filter>ATIFS</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\atifs\src\Compiler2Pass.cpp">
+      <Filter>ATIFS</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\atifs\src\ps_1_4.cpp">
+      <Filter>ATIFS</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\GLSL\src\CmGLSLExtSupport.cpp">
+      <Filter>GLSL</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\GLSL\src\CmGLSLGpuProgram.cpp">
+      <Filter>GLSL</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\GLSL\src\CmGLSLLinkProgram.cpp">
+      <Filter>GLSL</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\GLSL\src\CmGLSLLinkProgramManager.cpp">
+      <Filter>GLSL</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\GLSL\src\CmGLSLPreprocessor.cpp">
+      <Filter>GLSL</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\GLSL\src\CmGLSLProgram.cpp">
+      <Filter>GLSL</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\GLSL\src\CmGLSLProgramFactory.cpp">
+      <Filter>GLSL</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\win32\CmWin32Context.cpp">
+      <Filter>Win32</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\CmGLATIFSInit.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\CmGLContext.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\CmGLDefaultHardwareBufferManager.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\CmGLFBOMultiRenderTarget.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\CmGLFBORenderTexture.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\CmGLFrameBufferObject.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\CmGLGpuProgram.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\CmGLGpuProgramManager.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\CmGLHardwareBufferManager.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\CmGLHardwareIndexBuffer.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\CmGLHardwareOcclusionQuery.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\CmGLHardwarePixelBuffer.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\CmGLHardwareVertexBuffer.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\CmGLPBRenderTexture.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\CmGLPixelFormat.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\CmGLRenderSystem.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\CmGLRenderSystemFactory.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\CmGLRenderTexture.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\CmGLSupport.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\CmGLTexture.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\CmGLTextureManager.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\CmWin32GLSupport.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\CmWin32RenderTexture.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\CmWin32Window.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="Source\glew.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+  </ItemGroup>
+</Project>

+ 41 - 0
CamelotGLRenderer/Include/CmGLATIFSInit.h

@@ -0,0 +1,41 @@
+/*
+	ATI fragment shader Extension header file.
+	setup by NFZ
+	extracted from ATI 8500 SDK
+
+** GL_ATI_fragment_shader
+**
+** Support:
+**   Rage 128 * based  : Not Supported
+**   Radeon   * based  : Not Supported
+**   R200     * based  : Supported
+**   R200 : 8500, 9000, 9100, 9200
+**   also works on R300 but pointless since ARBFP1.0 supported
+*/
+
+
+#ifndef _GL_ATI_FRAGMENT_SHADER_H_
+#define _GL_ATI_FRAGMENT_SHADER_H_
+
+#include "CmGLSupport.h"
+
+// ATI_fragment_program functions
+extern PFNGLGENFRAGMENTSHADERSATIPROC        glGenFragmentShadersATI_ptr;
+extern PFNGLBINDFRAGMENTSHADERATIPROC        glBindFragmentShaderATI_ptr;
+extern PFNGLDELETEFRAGMENTSHADERATIPROC      glDeleteFragmentShaderATI_ptr;
+extern PFNGLBEGINFRAGMENTSHADERATIPROC       glBeginFragmentShaderATI_ptr;
+extern PFNGLENDFRAGMENTSHADERATIPROC         glEndFragmentShaderATI_ptr;
+extern PFNGLPASSTEXCOORDATIPROC              glPassTexCoordATI_ptr;
+extern PFNGLSAMPLEMAPATIPROC                 glSampleMapATI_ptr;
+extern PFNGLCOLORFRAGMENTOP1ATIPROC          glColorFragmentOp1ATI_ptr;
+extern PFNGLCOLORFRAGMENTOP2ATIPROC          glColorFragmentOp2ATI_ptr;
+extern PFNGLCOLORFRAGMENTOP3ATIPROC          glColorFragmentOp3ATI_ptr;
+extern PFNGLALPHAFRAGMENTOP1ATIPROC          glAlphaFragmentOp1ATI_ptr;
+extern PFNGLALPHAFRAGMENTOP2ATIPROC          glAlphaFragmentOp2ATI_ptr;
+extern PFNGLALPHAFRAGMENTOP3ATIPROC          glAlphaFragmentOp3ATI_ptr;
+extern PFNGLSETFRAGMENTSHADERCONSTANTATIPROC glSetFragmentShaderConstantATI_ptr;
+
+bool InitATIFragmentShaderExtensions(CamelotEngine::GLSupport& glSupport);
+
+#endif	//_GL_ATI_FRAGMENT_SHADER_H_
+

+ 75 - 0
CamelotGLRenderer/Include/CmGLContext.h

@@ -0,0 +1,75 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+    (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2011 Torus Knot Software 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.
+-----------------------------------------------------------------------------
+*/
+#ifndef __OgreGLContext_H__
+#define __OgreGLContext_H__
+
+#include "CmGLPrerequisites.h"
+
+namespace CamelotEngine {
+
+    /**
+     * Class that encapsulates an GL context. (IE a window/pbuffer). This is a 
+     * virtual base class which should be implemented in a GLSupport.
+     * This object can also be used to cache renderstate if we decide to do so
+     * in the future.
+     */
+    class CM_RSGL_EXPORT GLContext
+    {
+    public:
+        GLContext();
+        virtual ~GLContext();
+
+        /**
+         * Enable the context. All subsequent rendering commands will go here.
+         */
+        virtual void setCurrent() = 0;
+        /**
+         * This is called before another context is made current. By default,
+         * nothing is done here.
+         */
+        virtual void endCurrent() = 0;
+        
+        bool getInitialized() { return initialized; };
+        void setInitialized() { initialized = true; };
+
+		/** Create a new context based on the same window/pbuffer as this
+			context - mostly useful for additional threads.
+		@note The caller is responsible for deleting the returned context.
+		*/
+		virtual GLContext* clone() const = 0;
+
+		/**
+		* Release the render context.
+		*/
+		virtual void releaseContext() {}
+    protected:
+        bool initialized;
+    };
+}
+
+#endif

+ 133 - 0
CamelotGLRenderer/Include/CmGLDefaultHardwareBufferManager.h

@@ -0,0 +1,133 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+    (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2011 Torus Knot Software 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.
+-----------------------------------------------------------------------------
+*/
+
+#ifndef __GLDefaultHardwareBufferManager_H__
+#define __GLDefaultHardwareBufferManager_H__
+
+#include "CmGLPrerequisites.h"
+#include "CmHardwareBufferManager.h"
+#include "CmHardwareVertexBuffer.h"
+#include "CmHardwareIndexBuffer.h"
+
+namespace CamelotEngine {
+
+    /// Specialisation of HardwareVertexBuffer for emulation
+    class CM_RSGL_EXPORT GLDefaultHardwareVertexBuffer : public HardwareVertexBuffer 
+    {
+	protected:
+		unsigned char* mpData;
+        /// @copydoc HardwareBuffer::lock
+        void* lockImpl(size_t offset, size_t length, LockOptions options);
+        /// @copydoc HardwareBuffer::unlock
+        void unlockImpl(void);
+
+    public:
+		GLDefaultHardwareVertexBuffer(size_t vertexSize, size_t numVertices, HardwareBuffer::Usage usage);
+		GLDefaultHardwareVertexBuffer(HardwareBufferManagerBase* mgr, size_t vertexSize, size_t numVertices, 
+            HardwareBuffer::Usage usage);
+        ~GLDefaultHardwareVertexBuffer();
+        /// @copydoc HardwareBuffer::readData
+        void readData(size_t offset, size_t length, void* pDest);
+        /// @copydoc HardwareBuffer::writeData
+
+        void writeData(size_t offset, size_t length, const void* pSource,
+				bool discardWholeBuffer = false);
+        /** Override HardwareBuffer to turn off all shadowing. */
+        void* lock(size_t offset, size_t length, LockOptions options);
+        /** Override HardwareBuffer to turn off all shadowing. */
+		void unlock(void);
+
+        //void* getDataPtr(void) const { return (void*)mpData; }
+        void* getDataPtr(size_t offset) const { return (void*)(mpData + offset); }
+    };
+
+	/// Specialisation of HardwareIndexBuffer for emulation
+    class CM_RSGL_EXPORT GLDefaultHardwareIndexBuffer : public HardwareIndexBuffer
+    {
+	protected:
+		unsigned char* mpData;
+        /// @copydoc HardwareBuffer::lock
+        void* lockImpl(size_t offset, size_t length, LockOptions options);
+        /// @copydoc HardwareBuffer::unlock
+        void unlockImpl(void);
+    public:
+		GLDefaultHardwareIndexBuffer(IndexType idxType, size_t numIndexes, HardwareBuffer::Usage usage);
+        ~GLDefaultHardwareIndexBuffer();
+        /// @copydoc HardwareBuffer::readData
+        void readData(size_t offset, size_t length, void* pDest);
+        /// @copydoc HardwareBuffer::writeData
+        void writeData(size_t offset, size_t length, const void* pSource,
+				bool discardWholeBuffer = false);
+        /** Override HardwareBuffer to turn off all shadowing. */
+        void* lock(size_t offset, size_t length, LockOptions options);
+        /** Override HardwareBuffer to turn off all shadowing. */
+        void unlock(void);
+
+        void* getDataPtr(size_t offset) const { return (void*)(mpData + offset); }
+    };
+
+	/** Specialisation of HardwareBufferManager to emulate hardware buffers.
+	@remarks
+		You might want to instantiate this class if you want to utilise
+		classes like MeshSerializer without having initialised the 
+		rendering system (which is required to create a 'real' hardware
+		buffer manager.
+	*/
+	class CM_RSGL_EXPORT GLDefaultHardwareBufferManagerBase : public HardwareBufferManagerBase
+	{
+    public:
+        GLDefaultHardwareBufferManagerBase();
+        ~GLDefaultHardwareBufferManagerBase();
+        /// Creates a vertex buffer
+		HardwareVertexBufferPtr 
+            createVertexBuffer(size_t vertexSize, size_t numVerts, 
+				HardwareBuffer::Usage usage, bool useShadowBuffer = false);
+		/// Create a hardware vertex buffer
+		HardwareIndexBufferPtr 
+            createIndexBuffer(HardwareIndexBuffer::IndexType itype, size_t numIndexes, 
+				HardwareBuffer::Usage usage, bool useShadowBuffer = false);
+
+    };
+
+	/// GLDefaultHardwareBufferManagerBase as a Singleton
+	class CM_RSGL_EXPORT GLDefaultHardwareBufferManager : public HardwareBufferManager
+	{
+	public:
+		GLDefaultHardwareBufferManager()
+			: HardwareBufferManager(new GLDefaultHardwareBufferManagerBase()) 
+		{
+
+		}
+		~GLDefaultHardwareBufferManager()
+		{
+			delete mImpl;
+		}
+	};
+}
+
+#endif

+ 54 - 0
CamelotGLRenderer/Include/CmGLFBOMultiRenderTarget.h

@@ -0,0 +1,54 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+    (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2011 Torus Knot Software 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.
+-----------------------------------------------------------------------------
+*/
+
+#ifndef __GLMULTIRENDERTARGET_H__
+#define __GLMULTIRENDERTARGET_H__
+
+#include "CmGLFrameBufferObject.h"
+
+namespace CamelotEngine {
+	/** MultiRenderTarget for GL. Requires the FBO extension.
+	*/
+	class CM_RSGL_EXPORT GLFBOMultiRenderTarget : public MultiRenderTarget
+	{
+	public:
+		GLFBOMultiRenderTarget(GLFBOManager *manager, const String &name);
+		~GLFBOMultiRenderTarget();
+
+		virtual void getCustomAttribute( const String& name, void *pData );
+
+		bool requiresTextureFlipping() const { return true; }
+	private:
+		virtual void bindSurfaceImpl(size_t attachment, RenderTexture *target);
+		virtual void unbindSurfaceImpl(size_t attachment); 
+		GLFrameBufferObject fbo;
+	};
+
+}
+
+#endif // __GLTEXTURE_H__

+ 195 - 0
CamelotGLRenderer/Include/CmGLFBORenderTexture.h

@@ -0,0 +1,195 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+    (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2011 Torus Knot Software 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.
+-----------------------------------------------------------------------------
+*/
+#ifndef __OgreGLFBORTT_H__
+#define __OgreGLFBORTT_H__
+
+#include "CmGLRenderTexture.h"
+#include "CmGLContext.h"
+#include "CmGLFrameBufferObject.h"
+
+/// Extra GL constants
+#define GL_DEPTH24_STENCIL8_EXT                           0x88F0
+
+
+namespace CamelotEngine {
+    class GLFBOManager;
+
+    /** RenderTexture for GL FBO
+    */
+    class CM_RSGL_EXPORT GLFBORenderTexture: public GLRenderTexture
+    {
+    public:
+        GLFBORenderTexture(GLFBOManager *manager, const String &name, const GLSurfaceDesc &target, bool writeGamma, UINT32 fsaa);
+
+        virtual void getCustomAttribute(const String& name, void* pData);
+
+		/// Override needed to deal with multisample buffers
+		virtual void swapBuffers(bool waitForVSync = true);
+    protected:
+        GLFrameBufferObject mFB;
+    };
+    
+    /** Factory for GL Frame Buffer Objects, and related things.
+    */
+    class CM_RSGL_EXPORT GLFBOManager: public GLRTTManager
+    {
+    public:
+        GLFBOManager(bool atimode);
+		~GLFBOManager();
+        
+        /** Bind a certain render target if it is a FBO. If it is not a FBO, bind the
+            main frame buffer.
+        */
+        void bind(RenderTarget *target);
+        
+        /** Unbind a certain render target. No-op for FBOs.
+        */
+        void unbind(RenderTarget *target) {};
+        
+        /** Get best depth and stencil supported for given internalFormat
+        */
+        void getBestDepthStencil(GLenum internalFormat, GLenum *depthFormat, GLenum *stencilFormat);
+        
+        /** Create a texture rendertarget object
+        */
+        virtual GLFBORenderTexture *createRenderTexture(const String &name, 
+			const GLSurfaceDesc &target, bool writeGamma, UINT32 fsaa);
+
+		/** Create a multi render target 
+		*/
+		virtual MultiRenderTarget* createMultiRenderTarget(const String & name);
+        
+        /** Request a render buffer. If format is GL_NONE, return a zero buffer.
+        */
+        GLSurfaceDesc requestRenderBuffer(GLenum format, size_t width, size_t height, UINT32 fsaa);
+        /** Request the specify render buffer in case shared somewhere. Ignore
+            silently if surface.buffer is 0.
+        */
+        void requestRenderBuffer(const GLSurfaceDesc &surface);
+        /** Release a render buffer. Ignore silently if surface.buffer is 0.
+        */
+        void releaseRenderBuffer(const GLSurfaceDesc &surface);
+        
+        /** Check if a certain format is usable as FBO rendertarget format
+        */
+        bool checkFormat(PixelFormat format) { return mProps[format].valid; }
+        
+        /** Get a FBO without depth/stencil for temporary use, like blitting between textures.
+        */
+        GLuint getTemporaryFBO() { return mTempFBO; }
+    private:
+        /** Frame Buffer Object properties for a certain texture format.
+        */
+        struct FormatProperties
+        {
+            bool valid; // This format can be used as RTT (FBO)
+            
+            /** Allowed modes/properties for this pixel format
+            */
+            struct Mode
+            {
+                size_t depth;     // Depth format (0=no depth)
+                size_t stencil;   // Stencil format (0=no stencil)
+            };
+            
+            vector<Mode>::type modes;
+        };
+        /** Properties for all internal formats defined by OGRE
+        */
+        FormatProperties mProps[PF_COUNT];
+        
+        /** Stencil and depth renderbuffers of the same format are re-used between surfaces of the 
+            same size and format. This can save a lot of memory when a large amount of rendertargets
+            are used.
+        */
+        struct RBFormat
+        {
+            RBFormat(GLenum inFormat, size_t inWidth, size_t inHeight, UINT32 fsaa):
+                format(inFormat), width(inWidth), height(inHeight), samples(fsaa)
+            {}
+            GLenum format;
+            size_t width;
+            size_t height;
+			UINT32 samples;
+            // Overloaded comparison operator for usage in map
+            bool operator < (const RBFormat &other) const
+            {
+                if(format < other.format)
+                {
+                    return true;
+                }
+                else if(format == other.format)
+                {
+                    if(width < other.width)
+                    {
+                        return true;
+                    }
+                    else if(width == other.width)
+                    {
+                        if(height < other.height)
+                            return true;
+						else if (height == other.height)
+						{
+							if (samples < other.samples)
+								return true;
+						}
+                    }
+                }
+                return false;
+            }
+        };
+        struct RBRef
+        {
+            RBRef(){}
+            RBRef(GLRenderBuffer *inBuffer):
+                buffer(inBuffer), refcount(1)
+            { }
+            GLRenderBuffer *buffer;
+            size_t refcount;
+        };
+        typedef map<RBFormat, RBRef>::type RenderBufferMap;
+        RenderBufferMap mRenderBufferMap;
+        // map(format, sizex, sizey) -> [GLSurface*,refcount]
+        
+        /** Temporary FBO identifier
+         */
+        GLuint mTempFBO;
+        
+		/// Buggy ATI driver?
+		bool mATIMode;
+        
+        /** Detect allowed FBO formats */
+        void detectFBOFormats();
+        GLuint _tryFormat(GLenum depthFormat, GLenum stencilFormat);
+        bool _tryPackedFormat(GLenum packedFormat);
+    };
+    
+
+}
+
+#endif

+ 96 - 0
CamelotGLRenderer/Include/CmGLFrameBufferObject.h

@@ -0,0 +1,96 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+    (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2011 Torus Knot Software 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.
+-----------------------------------------------------------------------------
+*/
+#ifndef __OgreGLFBO_H__
+#define __OgreGLFBO_H__
+
+#include "CmGLRenderTexture.h"
+#include "CmGLContext.h"
+
+namespace CamelotEngine {
+    
+    /** Frame Buffer Object abstraction.
+    */
+    class CM_RSGL_EXPORT GLFrameBufferObject
+    {
+    public:
+        GLFrameBufferObject(GLFBOManager *manager, UINT32 fsaa);
+        ~GLFrameBufferObject();
+        //void bindSurface(size_t attachment, RenderTarget *target);
+        /** Bind a surface to a certain attachment point.
+            attachment: 0..CM_MAX_MULTIPLE_RENDER_TARGETS-1
+        */
+        void bindSurface(size_t attachment, const GLSurfaceDesc &target);
+        /** Unbind attachment
+        */
+        void unbindSurface(size_t attachment);
+        
+        /** Bind FrameBufferObject
+        */
+        void bind();
+
+		/** Swap buffers - only useful when using multisample buffers.
+		*/
+		void swapBuffers();
+		
+		/// Get the GL id for the FBO
+		GLuint getGLFBOID() const { return mFB; }
+		/// Get the GL id for the multisample FBO
+		GLuint getGLMultisampleFBOID() const { return mMultisampleFB; }
+        
+        /// Accessors
+        size_t getWidth();
+        size_t getHeight();
+        PixelFormat getFormat();
+        
+        GLFBOManager *getManager() { return mManager; }
+		const GLSurfaceDesc &getSurface(size_t attachment) { return mColour[attachment]; }
+    private:
+        GLFBOManager *mManager;
+		GLsizei mNumSamples;
+        GLuint mFB;
+		GLuint mMultisampleFB;
+		GLSurfaceDesc mMultisampleColourBuffer;
+        GLSurfaceDesc mDepth;
+        GLSurfaceDesc mStencil;
+        // Arbitrary number of texture surfaces
+        GLSurfaceDesc mColour[CM_MAX_MULTIPLE_RENDER_TARGETS];
+
+
+		/** Initialise object (find suitable depth and stencil format).
+            Must be called every time the bindings change.
+            It fails with an exception (ERR_INVALIDPARAMS) if:
+            - Attachment point 0 has no binding
+            - Not all bound surfaces have the same size
+            - Not all bound surfaces have the same internal format
+        */
+        void initialise();
+    };
+
+}
+
+#endif

+ 118 - 0
CamelotGLRenderer/Include/CmGLGpuProgram.h

@@ -0,0 +1,118 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+(Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2011 Torus Knot Software 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.
+-----------------------------------------------------------------------------
+*/
+
+#ifndef __GLGpuProgram_H__
+#define __GLGpuProgram_H__
+
+#include "CmGLPrerequisites.h"
+#include "CmGpuProgram.h"
+#include "CmHardwareVertexBuffer.h"
+
+namespace CamelotEngine {
+
+    /** Generalised low-level GL program, can be applied to multiple types (eg ARB and NV) */
+    class CM_RSGL_EXPORT GLGpuProgram : public GpuProgram
+    {
+    public:
+        GLGpuProgram();
+        virtual ~GLGpuProgram();
+
+        /// Execute the binding functions for this program
+        virtual void bindProgram(void) {}
+        /// Execute the binding functions for this program
+        virtual void unbindProgram(void) {}
+
+        /// Execute the param binding functions for this program
+		virtual void bindProgramParameters(GpuProgramParametersSharedPtr params, UINT16 mask) {}
+		/// Bind just the pass iteration parameters
+		virtual void bindProgramPassIterationParameters(GpuProgramParametersSharedPtr params) {}
+
+
+        /// Get the assigned GL program id
+        const GLuint getProgramID(void) const
+        { return mProgramID; }
+
+		/** Get the attribute index for a given semantic. 
+		@remarks
+			This can be used to identify the attribute index to bind non-builtin
+			attributes like tangent and binormal.
+		*/
+		virtual GLuint getAttributeIndex(VertexElementSemantic semantic, UINT32 index);
+		/** Test whether attribute index for a given semantic is valid. 
+		*/
+		virtual bool isAttributeValid(VertexElementSemantic semantic, UINT32 index);
+
+		/** Get the fixed attribute bindings normally used by GL for a semantic. */
+		static GLuint getFixedAttributeIndex(VertexElementSemantic semantic, UINT32 index);
+
+    protected:
+		/** Overridden from GpuProgram, do nothing */
+		void loadFromSource(void) {}
+        /// @copydoc Resource::unloadImpl
+        void unloadImpl(void) {}
+
+        GLuint mProgramID;
+        GLenum mProgramType;
+    };
+
+    /** Specialisation of the GL low-level program for ARB programs. */
+    class CM_RSGL_EXPORT GLArbGpuProgram : public GLGpuProgram
+    {
+    public:
+        GLArbGpuProgram();
+        virtual ~GLArbGpuProgram();
+
+        /// @copydoc GpuProgram::setType
+        void setType(GpuProgramType t);
+
+
+        /// Execute the binding functions for this program
+        void bindProgram(void);
+        /// Execute the unbinding functions for this program
+        void unbindProgram(void);
+        /// Execute the param binding functions for this program
+		void bindProgramParameters(GpuProgramParametersSharedPtr params, UINT16 mask);
+		/// Bind just the pass iteration parameters
+		void bindProgramPassIterationParameters(GpuProgramParametersSharedPtr params);
+
+        /// Get the GL type for the program
+        const GLuint getProgramType(void) const
+        { return mProgramType; }
+
+    protected:
+        void loadFromSource(void);
+        /// @copydoc Resource::unloadImpl
+        void unloadImpl(void);
+
+    };
+
+
+
+}; // namespace CamelotEngine
+
+#endif // __GLGpuProgram_H__

+ 59 - 0
CamelotGLRenderer/Include/CmGLGpuProgramManager.h

@@ -0,0 +1,59 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+(Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2011 Torus Knot Software 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.
+-----------------------------------------------------------------------------
+*/
+
+#ifndef __GLGpuProgramManager_H__
+#define __GLGpuProgramManager_H__
+
+#include "CmGLPrerequisites.h"
+#include "CmGpuProgramManager.h"
+
+namespace CamelotEngine {
+
+class CM_RSGL_EXPORT GLGpuProgramManager : public GpuProgramManager
+{
+public:
+    typedef GpuProgram* (*CreateGpuProgramCallback)(GpuProgramType gptype, const String& syntaxCode);
+
+private:
+    typedef map<String, CreateGpuProgramCallback>::type ProgramMap;
+    ProgramMap mProgramMap;
+
+protected:
+    /// Specialised create method with specific parameters
+    GpuProgram* create(GpuProgramType gptype, const String& syntaxCode);
+
+public:
+    GLGpuProgramManager();
+    ~GLGpuProgramManager();
+    bool registerProgramFactory(const String& syntaxCode, CreateGpuProgramCallback createFn);
+    bool unregisterProgramFactory(const String& syntaxCode);
+};
+
+}; //namespace CamelotEngine
+
+#endif //__GLGpuProgramManager_H__

+ 139 - 0
CamelotGLRenderer/Include/CmGLHardwareBufferManager.h

@@ -0,0 +1,139 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+    (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2011 Torus Knot Software 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.
+-----------------------------------------------------------------------------
+*/
+#ifndef __GLHARWAREBUFFERMANAGER_H__
+#define __GLHARWAREBUFFERMANAGER_H__
+
+#include "CmGLPrerequisites.h"
+#include "CmHardwareBufferManager.h"
+
+namespace CamelotEngine {
+
+// Default threshold at which glMapBuffer becomes more efficient than glBufferSubData (32k?)
+#	define OGRE_GL_DEFAULT_MAP_BUFFER_THRESHOLD (1024 * 32)
+
+
+    /** Implementation of HardwareBufferManager for OpenGL. */
+    class CM_RSGL_EXPORT GLHardwareBufferManagerBase : public HardwareBufferManagerBase
+    {
+	protected:
+		char* mScratchBufferPool;
+		CM_MUTEX(mScratchMutex)
+		size_t mMapBufferThreshold;
+
+    public:
+        GLHardwareBufferManagerBase();
+        ~GLHardwareBufferManagerBase();
+        /// Creates a vertex buffer
+        HardwareVertexBufferPtr createVertexBuffer(size_t vertexSize, 
+            size_t numVerts, HardwareBuffer::Usage usage, bool useShadowBuffer = false);
+        /// Create a hardware vertex buffer
+        HardwareIndexBufferPtr createIndexBuffer(
+            HardwareIndexBuffer::IndexType itype, size_t numIndexes, 
+            HardwareBuffer::Usage usage, bool useShadowBuffer = false);
+        /// Utility function to get the correct GL usage based on HBU's
+        static GLenum getGLUsage(unsigned int usage);
+
+        /// Utility function to get the correct GL type based on VET's
+        static GLenum getGLType(unsigned int type);
+
+		/** Allocator method to allow us to use a pool of memory as a scratch
+			area for hardware buffers. This is because glMapBuffer is incredibly
+			inefficient, seemingly no matter what options we give it. So for the
+			period of lock/unlock, we will instead allocate a section of a local
+			memory pool, and use glBufferSubDataARB / glGetBufferSubDataARB
+			instead.
+		*/
+		void* allocateScratch(UINT32 size);
+
+		/// @see allocateScratch
+		void deallocateScratch(void* ptr);
+
+		/** Threshold after which glMapBuffer is used and not glBufferSubData
+		*/
+		const size_t getGLMapBufferThreshold() const;
+		void setGLMapBufferThreshold( const size_t value );
+    };
+
+	/// GLHardwareBufferManagerBase as a Singleton
+	class CM_RSGL_EXPORT GLHardwareBufferManager : public HardwareBufferManager
+	{
+	public:
+		GLHardwareBufferManager()
+			: HardwareBufferManager(new GLHardwareBufferManagerBase()) 
+		{
+
+		}
+		~GLHardwareBufferManager()
+		{
+			delete mImpl;
+		}
+
+
+
+		/// Utility function to get the correct GL usage based on HBU's
+		static GLenum getGLUsage(unsigned int usage) 
+		{ return GLHardwareBufferManagerBase::getGLUsage(usage); }
+
+		/// Utility function to get the correct GL type based on VET's
+		static GLenum getGLType(unsigned int type)
+		{ return GLHardwareBufferManagerBase::getGLType(type); }
+
+		/** Allocator method to allow us to use a pool of memory as a scratch
+		area for hardware buffers. This is because glMapBuffer is incredibly
+		inefficient, seemingly no matter what options we give it. So for the
+		period of lock/unlock, we will instead allocate a section of a local
+		memory pool, and use glBufferSubDataARB / glGetBufferSubDataARB
+		instead.
+		*/
+		void* allocateScratch(UINT32 size)
+		{
+			return static_cast<GLHardwareBufferManagerBase*>(mImpl)->allocateScratch(size);
+		}
+
+		/// @see allocateScratch
+		void deallocateScratch(void* ptr)
+		{
+			static_cast<GLHardwareBufferManagerBase*>(mImpl)->deallocateScratch(ptr);
+		}
+
+		/** Threshold after which glMapBuffer is used and not glBufferSubData
+		*/
+		const size_t getGLMapBufferThreshold() const
+		{
+			return static_cast<GLHardwareBufferManagerBase*>(mImpl)->getGLMapBufferThreshold();
+		}
+		void setGLMapBufferThreshold( const size_t value )
+		{
+			static_cast<GLHardwareBufferManagerBase*>(mImpl)->setGLMapBufferThreshold(value);
+		}
+
+	};
+
+}
+
+#endif // __GLHARWAREBUFFERMANAGER_H__

+ 70 - 0
CamelotGLRenderer/Include/CmGLHardwareIndexBuffer.h

@@ -0,0 +1,70 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+    (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2011 Torus Knot Software 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.
+-----------------------------------------------------------------------------
+*/
+#ifndef __GLHARDWAREINDEXBUFFER_H__
+#define __GLHARDWAREINDEXBUFFER_H__
+
+#include "CmGLPrerequisites.h"
+#include "CmHardwareIndexBuffer.h"
+
+namespace CamelotEngine { 
+
+
+    class CM_RSGL_EXPORT GLHardwareIndexBuffer : public HardwareIndexBuffer
+    {
+    private:
+        GLuint mBufferId;
+		// Scratch buffer handling
+		bool mLockedToScratch;
+		size_t mScratchOffset;
+		size_t mScratchSize;
+		void* mScratchPtr;
+		bool mScratchUploadOnUnlock;
+    protected:
+        /** See HardwareBuffer. */
+        void* lockImpl(size_t offset, size_t length, LockOptions options);
+        /** See HardwareBuffer. */
+        void unlockImpl(void);
+    public:
+        GLHardwareIndexBuffer(HardwareBufferManagerBase* mgr, IndexType idxType, size_t numIndexes, 
+            HardwareBuffer::Usage usage, bool useShadowBuffer); 
+        ~GLHardwareIndexBuffer();
+        /** See HardwareBuffer. */
+        void readData(size_t offset, size_t length, void* pDest);
+        /** See HardwareBuffer. */
+        void writeData(size_t offset, size_t length, 
+            const void* pSource, bool discardWholeBuffer = false);
+        /** See HardwareBuffer. */
+        void _updateFromShadow(void);
+
+        GLuint getGLBufferId(void) const { return mBufferId; }
+    };
+
+}
+
+#endif // __GLHARDWAREINDEXBUFFER_H__
+

+ 108 - 0
CamelotGLRenderer/Include/CmGLHardwareOcclusionQuery.h

@@ -0,0 +1,108 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+    (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org
+
+Copyright (c) 2000-2011 Torus Knot Software 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.
+-----------------------------------------------------------------------------
+*/
+
+/*
+The nVidia occlusion query extension is defined in glext.h so you don't 
+need anything else. You do need to look up the function, we provide a 
+GLSupport class to do this, which has platform implementations for 
+getProcAddress. Check the way that extensions like glActiveTextureARB are 
+initialised and used in glRenderSystem and copy what is done there.
+
+
+
+  To do: fix so dx7 and DX9 checks and flags if HW Occlusion is supported
+  See the openGl dito for ideas what to do.
+
+*/
+
+
+
+//GL_ActiveTextureARB_Func* glActiveTextureARB_ptr = (GL_ActiveTextureARB_Func)mGLSupport->getProcAddress("glActiveTextureARB");
+
+#ifndef __GLHARDWAREOCCLUSIONQUERY_H__
+#define __GLHARDWAREOCCLUSIONQUERY_H__
+
+#include "CmGLPrerequisites.h"
+#include "CmHardwareOcclusionQuery.h"
+
+
+namespace CamelotEngine { 
+
+
+// If you use multiple rendering passes you can test only the first pass and all other passes don't have to be rendered 
+// if the first pass result has too few pixels visible.
+
+// Be sure to render all occluder first and whats out so the RenderQue don't switch places on 
+// the occluding objects and the tested objects because it thinks it's more effective..
+
+
+/**
+  * This is a class that is the base class of the query class for 
+  * hardware occlusion.
+  *
+  * @author Lee Sandberg email: [email protected]
+  * Updated on 13/9/2005 by Tuan Kuranes email: [email protected]
+  */
+
+class CM_RSGL_EXPORT GLHardwareOcclusionQuery : public HardwareOcclusionQuery
+{
+//----------------------------------------------------------------------
+// Public methods
+//--
+public:
+	/**
+	  * Default object constructor
+	  * 
+	  */
+	GLHardwareOcclusionQuery();
+	/**
+	  * Object destructor
+	  */
+	~GLHardwareOcclusionQuery();
+
+	//------------------------------------------------------------------
+	// Occlusion query functions (see base class documentation for this)
+	//--
+	void beginOcclusionQuery();
+	void endOcclusionQuery();
+	bool pullOcclusionQuery( unsigned int* NumOfFragments); 
+	bool isStillOutstanding(void);
+
+
+    //----------------------------------------------------------------------
+    // private members
+    //--
+    private:
+
+	    GLuint			mQueryID;
+};
+
+}
+
+#endif 
+

+ 138 - 0
CamelotGLRenderer/Include/CmGLHardwarePixelBuffer.h

@@ -0,0 +1,138 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+    (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2011 Torus Knot Software 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.
+-----------------------------------------------------------------------------
+*/
+#ifndef __GLPIXELBUFFER_H__
+#define __GLPIXELBUFFER_H__
+
+#include "CmGLPrerequisites.h"
+#include "CmHardwarePixelBuffer.h"
+
+namespace CamelotEngine {
+	class CM_RSGL_EXPORT GLHardwarePixelBuffer: public HardwarePixelBuffer
+	{
+	protected:  
+		/// Lock a box
+		PixelData lockImpl(const Box lockBox,  LockOptions options);
+
+		/// Unlock a box
+		void unlockImpl(void);
+        
+		// Internal buffer; either on-card or in system memory, freed/allocated on demand
+		// depending on buffer usage
+		PixelData mBuffer;
+        GLenum mGLInternalFormat; // GL internal format
+		LockOptions mCurrentLockOptions;
+		
+		// Buffer allocation/freeage
+		void allocateBuffer();
+		void freeBuffer();
+		// Upload a box of pixels to this buffer on the card
+		virtual void upload(const PixelData &data, const Box &dest);
+		// Download a box of pixels from the card
+		virtual void download(const PixelData &data);
+	public:
+        /// Should be called by HardwareBufferManager
+        GLHardwarePixelBuffer(size_t mWidth, size_t mHeight, size_t mDepth,
+                PixelFormat mFormat,
+                HardwareBuffer::Usage usage);
+		
+		/// @copydoc HardwarePixelBuffer::blitFromMemory
+		void blitFromMemory(const PixelData &src, const Box &dstBox);
+		
+		/// @copydoc HardwarePixelBuffer::blitToMemory
+		void blitToMemory(const Box &srcBox, const PixelData &dst);
+		
+		~GLHardwarePixelBuffer();
+        
+        /** Bind surface to frame buffer. Needs FBO extension.
+        */
+        virtual void bindToFramebuffer(GLenum attachment, size_t zoffset);
+        GLenum getGLFormat() { return mGLInternalFormat; }
+	};
+
+    /** Texture surface.
+    */
+    class CM_RSGL_EXPORT GLTextureBuffer: public GLHardwarePixelBuffer
+	{
+    public:
+        /** Texture constructor */
+		GLTextureBuffer(const String &baseName, GLenum target, GLuint id, GLint face, 
+			GLint level, Usage usage, bool softwareMipmap, bool writeGamma, UINT32 fsaa);
+        ~GLTextureBuffer();
+        
+        /// @copydoc HardwarePixelBuffer::bindToFramebuffer
+        virtual void bindToFramebuffer(GLenum attachment, size_t zoffset);
+        /// @copydoc HardwarePixelBuffer::getRenderTarget
+        RenderTexture* getRenderTarget(size_t);
+        /// Upload a box of pixels to this buffer on the card
+		virtual void upload(const PixelData &data, const Box &dest);
+		// Download a box of pixels from the card
+		virtual void download(const PixelData &data);
+  
+        /// Hardware implementation of blitFromMemory
+        virtual void blitFromMemory(const PixelData &src_orig, const Box &dstBox);
+        
+        /// Notify TextureBuffer of destruction of render target
+        void _clearSliceRTT(size_t zoffset)
+        {
+            mSliceTRT[zoffset] = 0;
+        }
+        /// Copy from framebuffer
+        void copyFromFramebuffer(size_t zoffset);
+        /// @copydoc HardwarePixelBuffer::blit
+        void blit(const HardwarePixelBufferPtr &src, const Box &srcBox, const Box &dstBox);
+        // Blitting implementation
+        void blitFromTexture(GLTextureBuffer *src, const Box &srcBox, const Box &dstBox);
+    protected:
+        // In case this is a texture level
+		GLenum mTarget;
+		GLenum mFaceTarget; // same as mTarget in case of GL_TEXTURE_xD, but cubemap face for cubemaps
+		GLuint mTextureID;
+		GLint mFace;
+		GLint mLevel;
+		bool mSoftwareMipmap;		// Use GLU for mip mapping
+        
+        typedef vector<RenderTexture*>::type SliceTRT;
+        SliceTRT mSliceTRT;
+    };
+     /** Renderbuffer surface.  Needs FBO extension.
+     */
+    class CM_RSGL_EXPORT GLRenderBuffer: public GLHardwarePixelBuffer
+	{
+    public:
+        GLRenderBuffer(GLenum format, size_t width, size_t height, GLsizei numSamples);
+        ~GLRenderBuffer();
+        
+        /// @copydoc GLHardwarePixelBuffer::bindToFramebuffer
+        virtual void bindToFramebuffer(GLenum attachment, size_t zoffset);
+    protected:
+        // In case this is a render buffer
+        GLuint mRenderbufferID;
+    };
+};
+
+#endif

+ 69 - 0
CamelotGLRenderer/Include/CmGLHardwareVertexBuffer.h

@@ -0,0 +1,69 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+    (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2011 Torus Knot Software 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.
+-----------------------------------------------------------------------------
+*/
+#ifndef __GLHARDWAREVERTEXBUFFER_H__
+#define __GLHARDWAREVERTEXBUFFER_H__
+
+#include "CmGLPrerequisites.h"
+#include "CmHardwareVertexBuffer.h"
+
+namespace CamelotEngine {
+
+    /// Specialisation of HardwareVertexBuffer for OpenGL
+    class CM_RSGL_EXPORT GLHardwareVertexBuffer : public HardwareVertexBuffer 
+    {
+    private:
+        GLuint mBufferId;
+		// Scratch buffer handling
+		bool mLockedToScratch;
+		size_t mScratchOffset;
+		size_t mScratchSize;
+		void* mScratchPtr;
+		bool mScratchUploadOnUnlock;
+
+    protected:
+        /** See HardwareBuffer. */
+        void* lockImpl(size_t offset, size_t length, LockOptions options);
+        /** See HardwareBuffer. */
+        void unlockImpl(void);
+    public:
+        GLHardwareVertexBuffer(HardwareBufferManagerBase* mgr, size_t vertexSize, size_t numVertices, 
+            HardwareBuffer::Usage usage, bool useShadowBuffer); 
+        ~GLHardwareVertexBuffer();
+        /** See HardwareBuffer. */
+        void readData(size_t offset, size_t length, void* pDest);
+        /** See HardwareBuffer. */
+        void writeData(size_t offset, size_t length, 
+            const void* pSource, bool discardWholeBuffer = false);
+        /** See HardwareBuffer. */
+        void _updateFromShadow(void);
+
+        GLuint getGLBufferId(void) const { return mBufferId; }
+    };
+
+}
+#endif // __GLHARDWAREVERTEXBUFFER_H__

+ 106 - 0
CamelotGLRenderer/Include/CmGLPBRenderTexture.h

@@ -0,0 +1,106 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+    (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2011 Torus Knot Software 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.
+-----------------------------------------------------------------------------
+*/
+
+#ifndef __GLPBRENDERTEXTURE_H__
+#define __GLPBRENDERTEXTURE_H__
+
+#include "CmGLRenderTexture.h"
+#include "CmGLPBuffer.h"
+namespace CamelotEngine {
+    
+    /** RenderTexture that uses a PBuffer (offscreen rendering context) for rendering.
+    */
+    class GLPBRTTManager;
+    class CM_RSGL_EXPORT GLPBRenderTexture: public GLRenderTexture
+    {
+    public:
+        GLPBRenderTexture(GLPBRTTManager *manager, const String &name, const GLSurfaceDesc &target, bool writeGamma, UINT32 fsaa);
+        virtual ~GLPBRenderTexture();
+        
+        virtual void getCustomAttribute(const String& name, void* pData);
+    protected:
+        GLPBRTTManager *mManager;
+        PixelComponentType mPBFormat;
+    };
+        
+    /** Manager for rendertextures and PBuffers (offscreen rendering contexts)
+    */
+    class CM_RSGL_EXPORT GLPBRTTManager: public GLRTTManager
+    {
+    public:
+        GLPBRTTManager(GLSupport *support, RenderTarget *mainwindow);
+        virtual ~GLPBRTTManager();
+        
+        /** @copydoc GLRTTManager::createRenderTexture
+        */
+        virtual RenderTexture *createRenderTexture(const String &name, 
+			const GLSurfaceDesc &target, bool writeGamma, UINT32 fsaa);
+        
+         /** @copydoc GLRTTManager::checkFormat
+        */
+        virtual bool checkFormat(PixelFormat format);
+        
+        /** @copydoc GLRTTManager::bind
+        */
+        virtual void bind(RenderTarget *target);
+        
+        /** @copydoc GLRTTManager::unbind
+        */
+        virtual void unbind(RenderTarget *target);
+        
+        /** Create PBuffer for a certain pixel format and size
+        */
+        void requestPBuffer(PixelComponentType ctype, size_t width, size_t height);
+        
+        /** Release PBuffer for a certain pixel format
+        */
+        void releasePBuffer(PixelComponentType ctype);
+        
+        /** Get GL rendering context for a certain component type and size.
+        */
+        GLContext *getContextFor(PixelComponentType ctype, size_t width, size_t height);
+    protected:
+        /** GLSupport reference, used to create PBuffers */
+        GLSupport *mSupport;
+		/** Primary window reference */
+		RenderTarget *mMainWindow;
+		/** Primary window context */
+		GLContext *mMainContext;
+        /** Reference to a PBuffer, with refcount */
+        struct PBRef
+        {
+            PBRef(): pb(0),refcount(0) {}
+            GLPBuffer* pb;
+            size_t refcount;
+        };
+        /** Type to map each component type to a PBuffer */
+        PBRef mPBuffers[PCT_COUNT];
+    };
+}
+
+#endif // __GLPBRENDERTEXTURE_H__

+ 62 - 0
CamelotGLRenderer/Include/CmGLPBuffer.h

@@ -0,0 +1,62 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+    (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2011 Torus Knot Software 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.
+-----------------------------------------------------------------------------
+*/
+
+#ifndef __GLPBUFFER_H__
+#define __GLPBUFFER_H__
+
+#include "CmGLPrerequisites.h"
+
+namespace CamelotEngine {
+    /** An off-screen rendering context. These contexts are always RGBA for simplicity, speed and
+        convience, but the component format is configurable.
+    */
+    class CM_RSGL_EXPORT GLPBuffer
+    {
+    public:
+        GLPBuffer(PixelComponentType format, size_t width, size_t height);
+        virtual ~GLPBuffer();
+        
+        /** Get the GL context that needs to be active to render to this PBuffer.
+        */
+        virtual GLContext *getContext() = 0;
+        
+        PixelComponentType getFormat() { return mFormat; }
+        size_t getWidth() { return mWidth; }
+        size_t getHeight() { return mHeight; }
+        
+        /** Get PBuffer component format for an OGRE pixel format.
+         */
+        static PixelComponentType getPixelComponentType(PixelFormat fmt);
+    protected:
+        PixelComponentType mFormat;
+        size_t mWidth, mHeight;
+    };
+    
+}
+
+#endif // __GLPBRENDERTEXTURE_H__

+ 100 - 0
CamelotGLRenderer/Include/CmGLPixelFormat.h

@@ -0,0 +1,100 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+    (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2011 Torus Knot Software 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.
+-----------------------------------------------------------------------------
+*/
+#ifndef __GLPIXELFORMAT_H__
+#define __GLPIXELFORMAT_H__
+
+#include "CmGLPrerequisites.h"
+#include "CmPixelUtil.h"
+namespace CamelotEngine {
+    
+	/**
+	* Class to do pixel format mapping between GL and OGRE
+	*/
+	class CM_RSGL_EXPORT GLPixelUtil
+	{
+	public:
+		/** Takes the OGRE pixel format and returns the appropriate GL one
+			@returns a GLenum describing the format, or 0 if there is no exactly matching 
+			one (and conversion is needed)
+		*/
+		static GLenum getGLOriginFormat(PixelFormat mFormat);
+	
+		/** Takes the OGRE pixel format and returns type that must be provided
+			to GL as data type for reading it into the GPU
+			@returns a GLenum describing the data type, or 0 if there is no exactly matching 
+			one (and conversion is needed)
+		*/
+		static GLenum getGLOriginDataType(PixelFormat mFormat);
+        
+        /**	Takes the OGRE pixel format and returns the type that must be provided
+			to GL as internal format. GL_NONE if no match exists.
+		@param mFormat The pixel format
+		@param hwGamma Whether a hardware gamma-corrected version is requested
+		*/
+		static GLenum getGLInternalFormat(PixelFormat mFormat, bool hwGamma = false);
+	
+		/**	Takes the OGRE pixel format and returns the type that must be provided
+			to GL as internal format. If no match exists, returns the closest match.
+		@param mFormat The pixel format
+		@param hwGamma Whether a hardware gamma-corrected version is requested
+		*/
+		static GLenum getClosestGLInternalFormat(PixelFormat mFormat, bool hwGamma = false);
+		
+		/**	Function to get the closest matching OGRE format to an internal GL format. To be
+			precise, the format will be chosen that is most efficient to transfer to the card 
+			without losing precision.
+			@remarks It is valid for this function to always return PF_A8R8G8B8.
+		*/
+		static PixelFormat getClosestOGREFormat(GLenum fmt);
+	
+		/** Returns the maximum number of Mipmaps that can be generated until we reach
+			the mininum format possible. This does not count the base level.
+			@param width
+				The width of the area
+			@param height
+				The height of the area
+			@param depth
+				The depth of the area
+			@param format
+				The format of the area
+			@remarks
+				In case that the format is non-compressed, this simply returns
+				how many times we can divide this texture in 2 until we reach 1x1.
+				For compressed formats, constraints apply on minimum size and alignment
+				so this might differ.
+		*/
+		static size_t getMaxMipmaps(size_t width, size_t height, size_t depth, PixelFormat format);
+        
+        /** Returns next power-of-two size if required by render system, in case
+            RSC_NON_POWER_OF_2_TEXTURES is supported it returns value as-is.
+        */
+        static size_t optionalPO2(size_t value);
+	};
+};
+
+#endif

+ 107 - 0
CamelotGLRenderer/Include/CmGLPrerequisites.h

@@ -0,0 +1,107 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+    (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2011 Torus Knot Software 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.
+-----------------------------------------------------------------------------
+*/
+#ifndef __GLPrerequisites_H__
+#define __GLPrerequisites_H__
+
+#include "CmPrerequisites.h"
+
+namespace CamelotEngine {
+    // Forward declarations
+    class GLSupport;
+    class GLRenderSystem;
+    class GLTexture;
+    class GLTextureManager;
+    class GLGpuProgram;
+    class GLContext;
+    class GLRTTManager;
+    class GLFBOManager;
+    class GLHardwarePixelBuffer;
+    class GLRenderBuffer;
+}
+
+#if CM_THREAD_SUPPORT == 1
+#	define GLEW_MX
+#endif
+
+#if CM_PLATFORM == CM_PLATFORM_WIN32
+#if !defined( __MINGW32__ )
+#   define WIN32_LEAN_AND_MEAN
+#  ifndef NOMINMAX
+#	define NOMINMAX // required to stop windows.h messing up std::min
+#  endif
+#endif
+#   include <windows.h>
+#   include <wingdi.h>
+#   include <GL/glew.h>
+#   include <GL/wglew.h>
+#   include <GL/glu.h>
+#elif CM_PLATFORM == CM_PLATFORM_LINUX
+#   include <GL/glew.h>
+#   include <GL/glu.h>
+#   define GL_GLEXT_PROTOTYPES
+#elif CM_PLATFORM == CM_PLATFORM_APPLE
+#   include <GL/glew.h>
+#   include <OpenGL/glu.h>
+#elif CM_PLATFORM == OGRE_PLATFORM_IPHONE
+#   include <OpenGLES/ES1/gl.h>
+#   include <OpenGLES/ES1/glext.h>
+#endif
+
+#if CM_THREAD_SUPPORT == 1
+	// implemented in OgreGLContext.cpp
+	GLEWContext * glewGetContext();
+
+#	if CM_PLATFORM == CM_PLATFORM_WIN32
+	// implemented in OgreWin32Context.cpp
+	WGLEWContext * wglewGetContext();
+#	endif
+
+#endif
+
+/// Lots of generated code in here which triggers the new VC CRT security warnings
+#if !defined( _CRT_SECURE_NO_DEPRECATE )
+#define _CRT_SECURE_NO_DEPRECATE
+#endif
+
+#if (CM_PLATFORM == CM_PLATFORM_WIN32) && !defined(__MINGW32__) && !defined(CM_STATIC_LIB)
+#	ifdef CM_RSGL_DLL
+#		define CM_RSGL_EXPORT __declspec(dllexport)
+#	else
+#       if defined( __MINGW32__ )
+#           define CM_RSGL_EXPORT
+#       else
+#    		define CM_RSGL_EXPORT __declspec(dllimport)
+#       endif
+#	endif
+#elif defined ( CM_GCC_VISIBILITY )
+#    define CM_RSGL_EXPORT  __attribute__ ((visibility("default")))
+#else
+#    define CM_RSGL_EXPORT
+#endif
+
+#endif //#ifndef __GLPrerequisites_H__

+ 484 - 0
CamelotGLRenderer/Include/CmGLRenderSystem.h

@@ -0,0 +1,484 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+    (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org
+
+Copyright (c) 2000-2011 Torus Knot Software 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.
+-----------------------------------------------------------------------------
+*/
+#ifndef __GLRenderSystem_H__
+#define __GLRenderSystem_H__
+
+#include "CmGLPrerequisites.h"
+#include "CmRenderSystem.h"
+#include "CmGLHardwareBufferManager.h"
+#include "CmGLGpuProgramManager.h"
+#include "CmGLSLProgramFactory.h"
+#include "CmConfigOptionMap.h"
+#include "CmVector4.h"
+
+namespace CamelotEngine {
+    /**
+      Implementation of GL as a rendering system.
+     */
+    class CM_RSGL_EXPORT GLRenderSystem : public RenderSystem
+    {
+    private:
+        /// Rendering loop control
+        bool mStopRendering;
+
+        /// View matrix to set world against
+        Matrix4 mViewMatrix;
+        Matrix4 mWorldMatrix;
+        Matrix4 mTextureMatrix;
+
+        /// Last min & mip filtering options, so we can combine them
+        FilterOptions mMinFilter;
+        FilterOptions mMipFilter;
+
+        /// What texture coord set each texture unit is using
+        size_t mTextureCoordIndex[CM_MAX_TEXTURE_LAYERS];
+
+        /// Holds texture type settings for every stage
+        GLenum mTextureTypes[CM_MAX_TEXTURE_LAYERS];
+
+		/// Number of fixed-function texture units
+		unsigned short mFixedFunctionTextureUnits;
+
+        void initConfigOptions(void);
+        void initInputDevices(void);
+        void processInputDevices(void);
+
+        void makeGLMatrix(GLfloat gl_matrix[16], const Matrix4& m);
+ 
+        GLint getBlendMode(SceneBlendFactor ogreBlend) const;
+		GLint getTextureAddressingMode(TextureState::TextureAddressingMode tam) const;
+				void initialiseContext(RenderWindow* primary);
+
+        void setLights();
+
+        /// Store last depth write state
+        bool mDepthWrite;
+		/// Store last stencil mask state
+		UINT32 mStencilMask;
+		/// Store last colour write state
+		bool mColourWrite[4];
+
+        GLint convertCompareFunction(CompareFunction func) const;
+        GLint convertStencilOp(StencilOperation op, bool invert = false) const;
+
+		/// Internal method for anisotropy validation
+		GLfloat _getCurrentAnisotropy(size_t unit);
+		
+        /// GL support class, used for creating windows etc.
+        GLSupport* mGLSupport;
+
+        bool mUseAutoTextureMatrix;
+        GLfloat mAutoTextureMatrix[16];
+
+        /// Check if the GL system has already been initialised
+        bool mGLInitialised;
+
+        HardwareBufferManager* mHardwareBufferManager;
+        GLGpuProgramManager* mGpuProgramManager;
+		GLSLProgramFactory* mGLSLProgramFactory;
+
+        unsigned short mCurrentLights;
+
+        GLuint getCombinedMinMipFilter(void) const;
+
+        GLGpuProgram* mCurrentVertexProgram;
+        GLGpuProgram* mCurrentFragmentProgram;
+		GLGpuProgram* mCurrentGeometryProgram;
+
+		/* The main GL context - main thread only */
+        GLContext *mMainContext;
+        /* The current GL context  - main thread only */
+        GLContext *mCurrentContext;
+		typedef list<GLContext*>::type GLContextList;
+		/// List of background thread contexts
+		GLContextList mBackgroundContextList;
+
+        /** Manager object for creating render textures.
+            Direct render to texture via GL_EXT_framebuffer_object is preferable 
+			to pbuffers, which depend on the GL support used and are generally 
+			unwieldy and slow. However, FBO support for stencil buffers is poor.
+        */
+        GLRTTManager *mRTTManager;
+
+		UINT16 mActiveTextureUnit;
+
+	protected:
+		void setClipPlanesImpl(const PlaneList& clipPlanes);
+		bool activateGLTextureUnit(size_t unit);
+    public:
+        // Default constructor / destructor
+        GLRenderSystem();
+        ~GLRenderSystem();
+
+        // ----------------------------------
+        // Overridden RenderSystem functions
+        // ----------------------------------
+        /** See
+          RenderSystem
+         */
+        const String& getName(void) const;
+        /** See
+          RenderSystem
+         */
+        ConfigOptionMap& getConfigOptions(void);
+        /** See
+          RenderSystem
+         */
+        void setConfigOption(const String &name, const String &value);
+        /** See
+          RenderSystem
+         */
+        String validateConfigOptions(void);
+        /** See
+          RenderSystem
+         */
+        RenderWindow* _initialise(bool autoCreateWindow, const String& windowTitle = "OGRE Render Window");
+        /** See
+          RenderSystem
+         */
+				virtual RenderSystemCapabilities* createRenderSystemCapabilities() const;
+        /** See
+          RenderSystem
+         */
+				void initialiseFromRenderSystemCapabilities(RenderSystemCapabilities* caps, RenderTarget* primary);
+        /** See
+          RenderSystem
+         */
+        void reinitialise(void); // Used if settings changed mid-rendering
+        /** See
+          RenderSystem
+         */
+        void shutdown(void);
+
+        /** See
+          RenderSystem
+         */
+        void setAmbientLight(float r, float g, float b);
+        /** See
+          RenderSystem
+         */
+        void setShadingType(ShadeOptions so);
+        /** See
+          RenderSystem
+         */
+        void setLightingEnabled(bool enabled);
+        
+		/// @copydoc RenderSystem::_createRenderWindow
+		RenderWindow* _createRenderWindow(const String &name, unsigned int width, unsigned int height, 
+			bool fullScreen, const NameValuePairList *miscParams = 0);
+
+		/// @copydoc RenderSystem::_createRenderWindows
+		bool _createRenderWindows(const RenderWindowDescriptionList& renderWindowDescriptions, 
+			RenderWindowList& createdWindows);
+
+		
+		/// @copydoc RenderSystem::createMultiRenderTarget
+		virtual MultiRenderTarget * createMultiRenderTarget(const String & name); 
+		
+        /** See
+          RenderSystem
+         */
+        void destroyRenderWindow(RenderWindow* pWin);
+        /** See
+          RenderSystem
+         */
+        String getErrorDescription(long errorNumber) const;
+
+        /** See
+          RenderSystem
+         */
+        VertexElementType getColourVertexElementType(void) const;
+        /** See
+          RenderSystem
+         */
+        void setNormaliseNormals(bool normalise);
+
+        // -----------------------------
+        // Low-level overridden members
+        // -----------------------------
+        /** See
+          RenderSystem
+         */
+		bool areFixedFunctionLightsInViewSpace() const { return true; }
+        /** See
+          RenderSystem
+         */
+        void _setWorldMatrix(const Matrix4 &m);
+        /** See
+          RenderSystem
+         */
+        void _setViewMatrix(const Matrix4 &m);
+        /** See
+          RenderSystem
+         */
+        void _setProjectionMatrix(const Matrix4 &m);
+        /** See
+          RenderSystem
+         */
+        void _setSurfaceParams(const Color &ambient,
+            const Color &diffuse, const Color &specular,
+            const Color &emissive, float shininess,
+            TrackVertexColourType tracking);
+        /** See
+          RenderSystem
+         */
+		void _setPointParameters(float size, bool attenuationEnabled, 
+			float constant, float linear, float quadratic, float minSize, float maxSize);
+        /** See
+          RenderSystem
+         */
+		void _setPointSpritesEnabled(bool enabled);
+		/** See
+          RenderSystem
+         */
+        void _setTexture(size_t unit, bool enabled, const TexturePtr &tex);
+        /** See
+          RenderSystem
+         */
+        void _setTextureCoordSet(size_t stage, size_t index);
+        /** See
+          RenderSystem
+         */
+        void _setTextureCoordCalculation(size_t stage, TexCoordCalcMethod m, 
+            const Frustum* frustum = 0);
+        /** See
+          RenderSystem
+         */
+        void _setTextureAddressingMode(size_t stage, const TextureState::UVWAddressingMode& uvw);
+        /** See
+          RenderSystem
+         */
+        void _setTextureBorderColour(size_t stage, const Color& colour);
+		/** See
+		  RenderSystem
+		 */
+		void _setTextureMipmapBias(size_t unit, float bias);
+        /** See
+          RenderSystem
+         */
+        void _setTextureMatrix(size_t stage, const Matrix4& xform);
+        /** See
+          RenderSystem
+         */
+        void _setSceneBlending(SceneBlendFactor sourceFactor, SceneBlendFactor destFactor, SceneBlendOperation op );
+        /** See
+          RenderSystem
+         */
+		void _setSeparateSceneBlending(SceneBlendFactor sourceFactor, SceneBlendFactor destFactor, SceneBlendFactor sourceFactorAlpha, SceneBlendFactor destFactorAlpha, SceneBlendOperation op, SceneBlendOperation alphaOp );
+        /** See
+          RenderSystem
+         */
+		void _setSceneBlendingOperation(SceneBlendOperation op);
+		/** See
+          RenderSystem
+         */
+		void _setSeparateSceneBlendingOperation(SceneBlendOperation op, SceneBlendOperation alphaOp);
+		/** See
+          RenderSystem
+         */
+        void _setAlphaRejectSettings(CompareFunction func, unsigned char value, bool alphaToCoverage);
+        /** See
+          RenderSystem
+         */
+        void _setViewport(Viewport *vp);
+        /** See
+          RenderSystem
+         */
+        void _beginFrame(void);
+        /** See
+          RenderSystem
+         */
+        void _endFrame(void);
+        /** See
+          RenderSystem
+         */
+        void _setCullingMode(CullingMode mode);
+        /** See
+          RenderSystem
+         */
+        void _setDepthBufferParams(bool depthTest = true, bool depthWrite = true, CompareFunction depthFunction = CMPF_LESS_EQUAL);
+        /** See
+          RenderSystem
+         */
+        void _setDepthBufferCheckEnabled(bool enabled = true);
+        /** See
+          RenderSystem
+         */
+        void _setDepthBufferWriteEnabled(bool enabled = true);
+        /** See
+          RenderSystem
+         */
+        void _setDepthBufferFunction(CompareFunction func = CMPF_LESS_EQUAL);
+        /** See
+          RenderSystem
+         */
+        void _setDepthBias(float constantBias, float slopeScaleBias);
+        /** See
+          RenderSystem
+         */
+        void _setColourBufferWriteEnabled(bool red, bool green, bool blue, bool alpha);
+		/** See
+          RenderSystem
+         */
+        void _setFog(FogMode mode, const Color& colour, float density, float start, float end);
+        /** See
+          RenderSystem
+         */
+        void _convertProjectionMatrix(const Matrix4& matrix,
+            Matrix4& dest, bool forGpuProgram = false);
+        /** See
+          RenderSystem
+         */
+        void _makeProjectionMatrix(const Radian& fovy, float aspect, float nearPlane, float farPlane, 
+            Matrix4& dest, bool forGpuProgram = false);
+        /** See
+          RenderSystem
+         */
+        void _makeProjectionMatrix(float left, float right, float bottom, float top, 
+            float nearPlane, float farPlane, Matrix4& dest, bool forGpuProgram = false);
+        /** See
+          RenderSystem
+         */
+		void _makeOrthoMatrix(const Radian& fovy, float aspect, float nearPlane, float farPlane, 
+            Matrix4& dest, bool forGpuProgram = false);
+        /** See
+        RenderSystem
+        */
+        void _applyObliqueDepthProjection(Matrix4& matrix, const Plane& plane, 
+            bool forGpuProgram);
+        /** See
+          RenderSystem
+         */
+        void setClipPlane (UINT16 index, float A, float B, float C, float D);
+        /** See
+          RenderSystem
+         */
+        void enableClipPlane (UINT16 index, bool enable);
+        /** See
+          RenderSystem
+         */
+        void _setPolygonMode(PolygonMode level);
+        /** See
+          RenderSystem
+         */
+        void setStencilCheckEnabled(bool enabled);
+        /** See
+          RenderSystem.
+         */
+        void setStencilBufferParams(CompareFunction func = CMPF_ALWAYS_PASS, 
+            UINT32 refValue = 0, UINT32 mask = 0xFFFFFFFF, 
+            StencilOperation stencilFailOp = SOP_KEEP, 
+            StencilOperation depthFailOp = SOP_KEEP,
+            StencilOperation passOp = SOP_KEEP, 
+            bool twoSidedOperation = false);
+        /** See
+          RenderSystem
+         */
+        void _setTextureUnitFiltering(size_t unit, FilterType ftype, FilterOptions filter);
+        /** See
+          RenderSystem
+         */
+		void _setTextureLayerAnisotropy(size_t unit, unsigned int maxAnisotropy);
+        /** See
+          RenderSystem
+         */
+		void setVertexDeclaration(VertexDeclaration* decl);
+        /** See
+          RenderSystem
+         */
+		void setVertexBufferBinding(VertexBufferBinding* binding);
+        /** See
+          RenderSystem
+         */
+        void _render(const RenderOperation& op);
+        /** See
+          RenderSystem
+         */
+        void bindGpuProgram(GpuProgram* prg);
+        /** See
+          RenderSystem
+         */
+        void unbindGpuProgram(GpuProgramType gptype);
+        /** See
+          RenderSystem
+         */
+		void bindGpuProgramParameters(GpuProgramType gptype, 
+			GpuProgramParametersSharedPtr params, UINT16 variabilityMask);
+		/** See
+		  RenderSystem
+		 */
+		void bindGpuProgramPassIterationParameters(GpuProgramType gptype);
+        /** See
+          RenderSystem
+         */
+        void setScissorTest(bool enabled, size_t left = 0, size_t top = 0, size_t right = 800, size_t bottom = 600) ;
+        void clearFrameBuffer(unsigned int buffers, 
+            const Color& colour = Color::Black, 
+            float depth = 1.0f, unsigned short stencil = 0);
+        HardwareOcclusionQuery* createHardwareOcclusionQuery(void);
+        float getHorizontalTexelOffset(void);
+        float getVerticalTexelOffset(void);
+        float getMinimumDepthInputValue(void);
+        float getMaximumDepthInputValue(void);
+		CM_MUTEX(mThreadInitMutex)
+		void registerThread();
+		void unregisterThread();
+		void preExtraThreadsStarted();
+		void postExtraThreadsStarted();
+
+        // ----------------------------------
+        // GLRenderSystem specific members
+        // ----------------------------------
+        /** One time initialization for the RenderState of a context. Things that
+            only need to be set once, like the LightingModel can be defined here.
+         */
+        void _oneTimeContextInitialization();
+        /** Switch GL context, dealing with involved internal cached states too
+        */
+        void _switchContext(GLContext *context);
+        /**
+         * Set current render target to target, enabling its GL context if needed
+         */
+        void _setRenderTarget(RenderTarget *target);
+        /** Unregister a render target->context mapping. If the context of target 
+            is the current context, change the context to the main context so it
+            can be destroyed safely. 
+            
+            @note This is automatically called by the destructor of 
+            GLContext.
+         */
+        void _unregisterContext(GLContext *context);
+		/** Returns the main context */
+		GLContext* _getMainContext() {return mMainContext;} 
+
+		/// @copydoc RenderSystem::getDisplayMonitorCount
+		unsigned int getDisplayMonitorCount() const;
+    };
+}
+#endif
+

+ 35 - 0
CamelotGLRenderer/Include/CmGLRenderSystemFactory.h

@@ -0,0 +1,35 @@
+#pragma once
+
+#include <string>
+#include "CmRenderSystemFactory.h"
+#include "CmRenderSystemManager.h"
+#include "CmGLRenderSystem.h"
+
+namespace CamelotEngine
+{
+	const std::string SystemName = "GLRenderSystem";
+
+	class GLRenderSystemFactory : public RenderSystemFactory
+	{
+	public:
+		virtual RenderSystemPtr create();
+		virtual const std::string& name() const { return SystemName; }
+
+	private:
+		class InitOnStart
+		{
+		public:
+			InitOnStart() 
+			{ 
+				static RenderSystemFactoryPtr newFactory;
+				if(newFactory == nullptr)
+				{
+					newFactory = RenderSystemFactoryPtr(new GLRenderSystemFactory());
+					RenderSystemManager::registerRenderSystemFactory(newFactory);
+				}
+			}
+		};
+
+		static InitOnStart initOnStart; // Makes sure factory is registered on program start
+	};
+}

+ 131 - 0
CamelotGLRenderer/Include/CmGLRenderTexture.h

@@ -0,0 +1,131 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+    (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2011 Torus Knot Software 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.
+-----------------------------------------------------------------------------
+*/
+
+#ifndef __GLRENDERTEXTURE_H__
+#define __GLRENDERTEXTURE_H__
+
+#include "CmGLTexture.h"
+
+namespace CamelotEngine {
+    /** GL surface descriptor. Points to a 2D surface that can be rendered to. 
+    */
+    struct GLSurfaceDesc
+    {
+    public:
+        GLHardwarePixelBuffer *buffer;
+        size_t zoffset;
+		UINT32 numSamples;
+
+		GLSurfaceDesc() :buffer(0), zoffset(0), numSamples(0) {}
+    };
+    
+    /** Base class for GL Render Textures
+    */
+    class CM_RSGL_EXPORT GLRenderTexture: public RenderTexture
+    {
+    public:
+        GLRenderTexture(const String &name, const GLSurfaceDesc &target, bool writeGamma, UINT32 fsaa);
+        virtual ~GLRenderTexture();
+        
+        bool requiresTextureFlipping() const { return true; }
+    };
+    
+    /** Manager/factory for RenderTextures.
+    */
+    class CM_RSGL_EXPORT GLRTTManager: public Singleton<GLRTTManager>
+    {
+    public:
+        virtual ~GLRTTManager();
+        
+        /** Create a texture rendertarget object
+        */
+        virtual RenderTexture *createRenderTexture(const String &name, const GLSurfaceDesc &target, bool writeGamma, UINT32 fsaa) = 0;
+        
+         /** Check if a certain format is usable as rendertexture format
+        */
+        virtual bool checkFormat(PixelFormat format) = 0;
+        
+        /** Bind a certain render target.
+        */
+        virtual void bind(RenderTarget *target) = 0;
+        
+        /** Unbind a certain render target. This is called before binding another RenderTarget, and
+            before the context is switched. It can be used to do a copy, or just be a noop if direct
+            binding is used.
+        */
+        virtual void unbind(RenderTarget *target) = 0;
+
+		/** Create a multi render target 
+		*/
+		virtual MultiRenderTarget* createMultiRenderTarget(const String & name);
+        
+        /** Get the closest supported alternative format. If format is supported, returns format.
+        */
+        virtual PixelFormat getSupportedAlternative(PixelFormat format);
+    };
+    
+    /** RenderTexture for simple copying from frame buffer
+    */
+    class GLCopyingRTTManager;
+    class CM_RSGL_EXPORT GLCopyingRenderTexture: public GLRenderTexture
+    {
+    public:
+        GLCopyingRenderTexture(GLCopyingRTTManager *manager, const String &name, const GLSurfaceDesc &target, 
+			bool writeGamma, UINT32 fsaa);
+        
+        virtual void getCustomAttribute(const String& name, void* pData);
+    };
+    
+    /** Simple, copying manager/factory for RenderTextures. This is only used as the last fallback if
+        both PBuffers and FBOs aren't supported.
+    */
+    class CM_RSGL_EXPORT GLCopyingRTTManager: public GLRTTManager
+    {
+    public:
+        GLCopyingRTTManager();
+        virtual ~GLCopyingRTTManager();
+        
+        /** @copydoc GLRTTManager::createRenderTexture
+        */
+        virtual RenderTexture *createRenderTexture(const String &name, const GLSurfaceDesc &target, bool writeGamma, UINT32 fsaa);
+        
+        /** @copydoc GLRTTManager::checkFormat
+        */
+        virtual bool checkFormat(PixelFormat format);
+        
+        /** @copydoc GLRTTManager::bind
+        */
+        virtual void bind(RenderTarget *target);
+        
+        /** @copydoc GLRTTManager::unbind
+        */
+        virtual void unbind(RenderTarget *target);
+    };
+}
+
+#endif // __GLTEXTURE_H__

+ 137 - 0
CamelotGLRenderer/Include/CmGLSupport.h

@@ -0,0 +1,137 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+    (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2011 Torus Knot Software 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.
+-----------------------------------------------------------------------------
+*/
+#ifndef OGRE_GLSUPPORT_H
+#define OGRE_GLSUPPORT_H
+
+#include "CmGLPrerequisites.h"
+#include "CmGLRenderSystem.h"
+
+#include "CmRenderWindow.h"
+#include "CmConfigOptionMap.h"
+#include "CmGLPBuffer.h"
+
+namespace CamelotEngine
+{
+    
+class CM_RSGL_EXPORT GLSupport
+{
+public:
+    GLSupport() { }
+    virtual ~GLSupport() { }
+
+    /**
+    * Add any special config values to the system.
+    * Must have a "Full Screen" value that is a bool and a "Video Mode" value
+    * that is a string in the form of wxh
+    */
+    virtual void addConfig() = 0;
+
+	virtual void setConfigOption(const String &name, const String &value);
+
+    /**
+    * Make sure all the extra options are valid
+    * @return string with error message
+    */
+    virtual String validateConfig() = 0;
+
+	virtual ConfigOptionMap& getConfigOptions(void);
+
+	virtual RenderWindow* createWindow(bool autoCreateWindow, GLRenderSystem* renderSystem, const String& windowTitle) = 0;
+
+	/// @copydoc RenderSystem::_createRenderWindow
+	virtual RenderWindow* newWindow(const String &name, unsigned int width, unsigned int height, 
+		bool fullScreen, const NameValuePairList *miscParams = 0) = 0;
+
+    virtual bool supportsPBuffers();
+    virtual GLPBuffer *createPBuffer(PixelComponentType format, size_t width, size_t height);
+
+    /**
+    * Start anything special
+    */
+    virtual void start() = 0;
+    /**
+    * Stop anything special
+    */
+    virtual void stop() = 0;
+
+    /**
+    * Get vendor information
+    */
+    const String& getGLVendor(void) const
+    {
+        return mVendor;
+    }
+
+    /**
+    * Get version information
+    */
+    const String& getGLVersion(void) const
+    {
+        return mVersion;
+    }
+
+    /**
+    * Compare GL version numbers
+    */
+    bool checkMinGLVersion(const String& v) const;
+
+    /**
+    * Check if an extension is available
+    */
+    virtual bool checkExtension(const String& ext) const;
+    /**
+    * Get the address of a function
+    */
+    virtual void* getProcAddress(const String& procname) = 0;
+
+    /** Initialises GL extensions, must be done AFTER the GL context has been
+        established.
+    */
+    virtual void initialiseExtensions();
+
+	/// @copydoc RenderSystem::getDisplayMonitorCount
+	virtual unsigned int getDisplayMonitorCount() const
+	{
+		return 1;
+	}
+
+protected:
+	// Stored options
+    ConfigOptionMap mOptions;
+
+	// This contains the complete list of supported extensions
+    set<String>::type extensionList;
+private:
+    String mVersion;
+    String mVendor;
+
+}; // class GLSupport
+
+}; // namespace CamelotEngine
+
+#endif // OGRE_GLSUPPORT_H

+ 104 - 0
CamelotGLRenderer/Include/CmGLTexture.h

@@ -0,0 +1,104 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+    (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2011 Torus Knot Software 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.
+-----------------------------------------------------------------------------
+*/
+
+#ifndef __GLTEXTURE_H__
+#define __GLTEXTURE_H__
+
+#include "CmGLPrerequisites.h"
+#include "CmRenderTexture.h"
+#include "CmTexture.h"
+#include "CmGLSupport.h"
+#include "CmHardwarePixelBuffer.h"
+
+namespace CamelotEngine {
+
+    class CM_RSGL_EXPORT GLTexture : public Texture
+    {
+    public:
+        // Constructor
+        GLTexture(GLSupport& support);
+
+        virtual ~GLTexture();      
+
+        void createRenderTexture();
+			
+		/// @copydoc Texture::getBuffer
+		HardwarePixelBufferPtr getBuffer(size_t face, size_t mipmap);
+
+        // Takes the OGRE texture type (1d/2d/3d/cube) and returns the appropriate GL one
+        GLenum getGLTextureTarget(void) const;
+
+        GLuint getGLID() const
+        {
+            return mTextureID;
+        }
+		
+		void getCustomAttribute(const String& name, void* pData);
+
+    protected:
+		/// @copydoc Texture::createInternalResourcesImpl
+		void createInternalResourcesImpl(void);
+        /// @copydoc Resource::prepareImpl
+        void prepareImpl(void);
+        /// @copydoc Resource::unprepareImpl
+        void unprepareImpl(void);
+        /// @copydoc Resource::loadImpl
+        void loadImpl(void);
+        /// @copydoc Resource::freeInternalResourcesImpl
+        void freeInternalResourcesImpl(void);
+
+		/** internal method, create GLHardwarePixelBuffers for every face and
+			 mipmap level. This method must be called after the GL texture object was created,
+			the number of mipmaps was set (GL_TEXTURE_MAX_LEVEL) and glTexImageXD was called to
+			actually allocate the buffer
+		*/
+		void _createSurfaceList();
+
+        /// Used to hold images between calls to prepare and load.
+        //typedef SharedPtr<vector<Image>::type > LoadedImages;
+
+        /** Vector of images that were pulled from disk by
+            prepareLoad but have yet to be pushed into texture memory
+            by loadImpl.  Images should be deleted by loadImpl and unprepareImpl.
+        */
+        //LoadedImages mLoadedImages;
+
+
+    private:
+        GLuint mTextureID;
+        GLSupport& mGLSupport;
+		
+		/// Vector of pointers to subsurfaces
+		typedef vector<HardwarePixelBufferPtr>::type SurfaceList;
+		SurfaceList	mSurfaceList;
+    };
+
+	typedef std::shared_ptr<GLTexture> GLTexturePtr;
+}
+
+#endif // __GLTEXTURE_H__

+ 65 - 0
CamelotGLRenderer/Include/CmGLTextureManager.h

@@ -0,0 +1,65 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+    (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2011 Torus Knot Software 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.
+-----------------------------------------------------------------------------
+*/
+
+#ifndef __GLTextureManager_H__
+#define __GLTextureManager_H__
+
+#include "CmGLPrerequisites.h"
+#include "CmGLTexture.h"
+#include "CmGLSupport.h"
+#include "CmTextureManager.h"
+
+namespace CamelotEngine {
+    /** GL-specific implementation of a TextureManager */
+    class CM_RSGL_EXPORT GLTextureManager : public TextureManager
+    {
+    public:
+        GLTextureManager(GLSupport& support);
+        virtual ~GLTextureManager();
+
+		GLuint getWarningTextureID() { return mWarningTextureID; }
+
+		/// @copydoc TextureManager::getNativeFormat
+		PixelFormat getNativeFormat(TextureType ttype, PixelFormat format, int usage);
+
+        /// @copydoc TextureManager::isHardwareFilteringSupported
+        bool isHardwareFilteringSupported(TextureType ttype, PixelFormat format, int usage,
+            bool preciseFormatOnly = false);
+
+    protected:
+        /// @copydoc ResourceManager::createImpl
+        Texture* createImpl();
+
+		/// Internal method to create a warning texture (bound when a texture unit is blank)
+		void createWarningTexture();
+
+        GLSupport& mGLSupport;
+		GLuint mWarningTextureID;
+    };
+}
+#endif

+ 58 - 0
CamelotGLRenderer/Include/CmWin32Context.h

@@ -0,0 +1,58 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+    (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2011 Torus Knot Software 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.
+-----------------------------------------------------------------------------
+*/
+#ifndef __OgreW32Context_H__
+#define __OgreW32Context_H__
+
+#include "CmWin32Prerequisites.h"
+#include "CmGLContext.h"
+
+namespace CamelotEngine {
+
+    class CM_RSGL_EXPORT Win32Context: public GLContext
+    {
+    public:
+        Win32Context(HDC     HDC,
+                     HGLRC   Glrc);
+        virtual ~Win32Context();
+
+        /** See GLContext */
+        virtual void setCurrent();
+		/** See GLContext */
+		virtual void endCurrent();
+		/// @copydoc GLContext::clone
+		GLContext* clone() const;
+
+		virtual void releaseContext();
+
+	protected:
+        HDC     mHDC;
+        HGLRC   mGlrc;
+    };
+}
+
+#endif

+ 90 - 0
CamelotGLRenderer/Include/CmWin32GLSupport.h

@@ -0,0 +1,90 @@
+#ifndef __OgreWin32GLSupport_H__
+#define __OgreWin32GLSupport_H__
+
+#include "CmWin32Prerequisites.h"
+#include "CmGLSupport.h"
+#include "CmGLRenderSystem.h"
+
+namespace CamelotEngine
+{
+    
+	class CM_RSGL_EXPORT Win32GLSupport : public GLSupport
+	{
+	public:
+        Win32GLSupport();
+		/**
+		* Add any special config values to the system.
+		* Must have a "Full Screen" value that is a bool and a "Video Mode" value
+		* that is a string in the form of wxhxb
+		*/
+		void addConfig();
+
+		void setConfigOption(const String &name, const String &value);
+
+		/**
+		* Make sure all the extra options are valid
+		*/
+		String validateConfig();
+
+		virtual RenderWindow* createWindow(bool autoCreateWindow, GLRenderSystem* renderSystem, const String& windowTitle = "OGRE Render Window");
+		
+		/// @copydoc RenderSystem::_createRenderWindow
+		virtual RenderWindow* newWindow(const String &name, unsigned int width, unsigned int height, 
+			bool fullScreen, const NameValuePairList *miscParams = 0);
+
+		
+		/**
+		* Start anything special
+		*/
+		void start();
+		/**
+		* Stop anything special
+		*/
+		void stop();
+
+		/**
+		* Get the address of a function
+		*/
+		void* getProcAddress(const String& procname);
+
+		/**
+		 * Initialise extensions
+		 */
+		virtual void initialiseExtensions();
+		
+
+		bool selectPixelFormat(HDC hdc, int colourDepth, int multisample, bool hwGamma);
+
+		virtual bool supportsPBuffers();
+		virtual GLPBuffer *createPBuffer(PixelComponentType format, size_t width, size_t height);
+		virtual unsigned int getDisplayMonitorCount() const;
+	private:
+		// Allowed video modes
+		vector<DEVMODE>::type mDevModes;
+		Win32Window *mInitialWindow;
+		vector<int>::type mFSAALevels;
+		bool mHasPixelFormatARB;
+        bool mHasMultisample;
+		bool mHasHardwareGamma;
+
+		struct DisplayMonitorInfo
+		{
+			HMONITOR		hMonitor;
+			MONITORINFOEX	monitorInfoEx;
+		};
+
+		typedef vector<DisplayMonitorInfo>::type DisplayMonitorInfoList;
+		typedef DisplayMonitorInfoList::iterator DisplayMonitorInfoIterator;
+
+		DisplayMonitorInfoList mMonitorInfoList;
+
+		void refreshConfig();
+		void initialiseWGL();
+		static LRESULT CALLBACK dummyWndProc(HWND hwnd, UINT umsg, WPARAM wp, LPARAM lp);
+		static BOOL CALLBACK sCreateMonitorsInfoEnumProc(HMONITOR hMonitor, HDC hdcMonitor, 
+			LPRECT lprcMonitor, LPARAM dwData);
+	};
+
+}
+
+#endif

+ 48 - 0
CamelotGLRenderer/Include/CmWin32Prerequisites.h

@@ -0,0 +1,48 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+    (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2011 Torus Knot Software 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.
+-----------------------------------------------------------------------------
+*/
+#ifndef __OgreWin32Prerequisites_H__
+#define __OgreWin32Prerequisites_H__
+
+#include <windows.h>
+
+#include <CmGLPrerequisites.h>
+
+
+namespace CamelotEngine {
+    // Forward declarations
+    class Win32GLSupport;
+    class Win32Window;
+    class Win32Context;
+
+
+	// Useful error method implemented in Win32GLSupport
+	String translateWGLError();
+}
+
+
+#endif

+ 55 - 0
CamelotGLRenderer/Include/CmWin32RenderTexture.h

@@ -0,0 +1,55 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+    (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2011 Torus Knot Software 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.
+-----------------------------------------------------------------------------
+*/
+
+#ifndef __Win32RT_H__
+#define __Win32RT_H__
+
+#include "CmWin32Prerequisites.h"
+#include "CmWin32Context.h"
+#include "CmGLPBuffer.h"
+
+namespace CamelotEngine {
+    class CM_RSGL_EXPORT Win32PBuffer : public GLPBuffer
+    {
+	public:
+		Win32PBuffer(PixelComponentType format, size_t width, size_t height);
+		~Win32PBuffer();
+	    
+		virtual GLContext *getContext() { return mContext; }
+    protected:
+        void createPBuffer();
+		void destroyPBuffer();
+
+		HDC		mHDC;
+		HGLRC	mGlrc;
+		HPBUFFERARB mPBuffer;
+        Win32Context *mContext;
+    };
+}
+
+#endif

+ 89 - 0
CamelotGLRenderer/Include/CmWin32Window.h

@@ -0,0 +1,89 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+    (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2011 Torus Knot Software 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.
+-----------------------------------------------------------------------------
+*/
+
+#ifndef __Win32Window_H__
+#define __Win32Window_H__
+
+#include "CmWin32Prerequisites.h"
+#include "CmRenderWindow.h"
+
+namespace CamelotEngine {
+    class CM_RSGL_EXPORT Win32Window : public RenderWindow
+    {
+    public:
+        Win32Window(Win32GLSupport &glsupport);
+        ~Win32Window();
+
+       void create(const String& name, unsigned int width, unsigned int height,
+	            bool fullScreen, const NameValuePairList *miscParams);
+	   void setFullscreen(bool fullScreen, unsigned int width, unsigned int height);
+        void destroy(void);
+		bool isActive(void) const;
+        bool isVisible() const;
+        bool isClosed(void) const;
+        void reposition(int left, int top);
+        void resize(unsigned int width, unsigned int height);
+        void swapBuffers(bool waitForVSync);
+
+		/** Overridden - see RenderTarget. */
+		virtual void copyContentsToMemory(const PixelData &dst, FrameBuffer buffer);
+
+		bool requiresTextureFlipping() const { return false; }
+
+		HWND getWindowHandle() const { return mHWnd; }
+		HDC getHDC() const { return mHDC; }
+		
+		// Method for dealing with resize / move & 3d library
+		virtual void windowMovedOrResized(void);
+
+		void getCustomAttribute( const String& name, void* pData );
+
+        /** Used to set the active state of the render target.
+        */
+        virtual void setActive( bool state );
+
+		void adjustWindow(unsigned int clientWidth, unsigned int clientHeight, 
+			unsigned int* winWidth, unsigned int* winHeight);
+
+	protected:
+		Win32GLSupport &mGLSupport;
+		HWND	mHWnd;					// Win32 Window handle
+		HDC		mHDC;
+		HGLRC	mGlrc;
+        bool    mIsExternal;
+		char*   mDeviceName;
+		bool    mIsExternalGLControl;
+		bool	mIsExternalGLContext;
+        bool    mSizing;
+		bool	mClosed;
+        int     mDisplayFrequency;      // fullscreen only, to restore display
+        Win32Context *mContext;
+    };
+}
+
+#endif

+ 104 - 0
CamelotGLRenderer/Source/CmGLATIFSInit.cpp

@@ -0,0 +1,104 @@
+/*
+	ATI fragment shader Extension program file.
+	setup by NFZ
+	extracted from ATI 8500 SDK
+
+** GL_ATI_fragment_shader
+**
+** Support:
+**   Rage 128 * based  : Not Supported
+**   Radeon   * based  : Not Supported
+**   R200     * based  : Supported
+**   R200 : 8500, 9000, 9100, 9200
+**   also works on R300 but pointless since ARBFP1.0 supported
+*/
+
+#include "CmGLATIFSInit.h"
+#include "CmGLPrerequisites.h"
+
+// ATI_fragment_program functions
+PFNGLGENFRAGMENTSHADERSATIPROC        glGenFragmentShadersATI_ptr=NULL;
+PFNGLBINDFRAGMENTSHADERATIPROC        glBindFragmentShaderATI_ptr=NULL;
+PFNGLDELETEFRAGMENTSHADERATIPROC      glDeleteFragmentShaderATI_ptr=NULL;
+PFNGLBEGINFRAGMENTSHADERATIPROC       glBeginFragmentShaderATI_ptr=NULL;
+PFNGLENDFRAGMENTSHADERATIPROC         glEndFragmentShaderATI_ptr=NULL;
+PFNGLPASSTEXCOORDATIPROC              glPassTexCoordATI_ptr=NULL;
+PFNGLSAMPLEMAPATIPROC                 glSampleMapATI_ptr=NULL;
+PFNGLCOLORFRAGMENTOP1ATIPROC          glColorFragmentOp1ATI_ptr=NULL;
+PFNGLCOLORFRAGMENTOP2ATIPROC          glColorFragmentOp2ATI_ptr=NULL;
+PFNGLCOLORFRAGMENTOP3ATIPROC          glColorFragmentOp3ATI_ptr=NULL;
+PFNGLALPHAFRAGMENTOP1ATIPROC          glAlphaFragmentOp1ATI_ptr=NULL;
+PFNGLALPHAFRAGMENTOP2ATIPROC          glAlphaFragmentOp2ATI_ptr=NULL;
+PFNGLALPHAFRAGMENTOP3ATIPROC          glAlphaFragmentOp3ATI_ptr=NULL;
+PFNGLSETFRAGMENTSHADERCONSTANTATIPROC glSetFragmentShaderConstantATI_ptr=NULL;
+
+bool InitATIFragmentShaderExtensions(CamelotEngine::GLSupport& glSupport)
+{
+    static bool init = false;
+    //char *extList;
+
+    if(init) return init;
+
+	
+	/* confirm that the version of OpenGL supports ATI fragment shader */
+	/* done in GLRenderSystem
+    extList = (char *)glGetString(GL_EXTENSIONS);
+
+    if (strstr(extList, "GL_ATI_fragment_shader") == NULL)  {
+		//MessageBox(NULL, "GL_ATI_fragment_shader extension not supported", "GL Extension error", MB_OK);
+		// ** should raise exception
+		init = false;
+		return false;
+    }
+
+	*/
+
+
+	glGenFragmentShadersATI_ptr    = (PFNGLGENFRAGMENTSHADERSATIPROC) glSupport.getProcAddress("glGenFragmentShadersATI");
+	glBindFragmentShaderATI_ptr    = (PFNGLBINDFRAGMENTSHADERATIPROC) glSupport.getProcAddress("glBindFragmentShaderATI");
+	glDeleteFragmentShaderATI_ptr  = (PFNGLDELETEFRAGMENTSHADERATIPROC) glSupport.getProcAddress("glDeleteFragmentShaderATI");
+	glBeginFragmentShaderATI_ptr   = (PFNGLBEGINFRAGMENTSHADERATIPROC) glSupport.getProcAddress("glBeginFragmentShaderATI");
+	glEndFragmentShaderATI_ptr     = (PFNGLENDFRAGMENTSHADERATIPROC) glSupport.getProcAddress("glEndFragmentShaderATI");
+	glPassTexCoordATI_ptr          = (PFNGLPASSTEXCOORDATIPROC) glSupport.getProcAddress("glPassTexCoordATI");
+	glSampleMapATI_ptr             = (PFNGLSAMPLEMAPATIPROC) glSupport.getProcAddress("glSampleMapATI");
+	glColorFragmentOp1ATI_ptr      = (PFNGLCOLORFRAGMENTOP1ATIPROC) glSupport.getProcAddress("glColorFragmentOp1ATI");
+	glColorFragmentOp2ATI_ptr      = (PFNGLCOLORFRAGMENTOP2ATIPROC) glSupport.getProcAddress("glColorFragmentOp2ATI");
+	glColorFragmentOp3ATI_ptr      = (PFNGLCOLORFRAGMENTOP3ATIPROC) glSupport.getProcAddress("glColorFragmentOp3ATI");
+	glAlphaFragmentOp1ATI_ptr      = (PFNGLALPHAFRAGMENTOP1ATIPROC) glSupport.getProcAddress("glAlphaFragmentOp1ATI");
+	glAlphaFragmentOp2ATI_ptr      = (PFNGLALPHAFRAGMENTOP2ATIPROC) glSupport.getProcAddress("glAlphaFragmentOp2ATI");
+	glAlphaFragmentOp3ATI_ptr      = (PFNGLALPHAFRAGMENTOP3ATIPROC) glSupport.getProcAddress("glAlphaFragmentOp3ATI");
+	glSetFragmentShaderConstantATI_ptr = (PFNGLSETFRAGMENTSHADERCONSTANTATIPROC) glSupport.getProcAddress("glSetFragmentShaderConstantATI");
+
+	if (glGenFragmentShadersATI_ptr == NULL) return false;
+
+	if (glBindFragmentShaderATI_ptr == NULL) return false;
+
+	if (glDeleteFragmentShaderATI_ptr == NULL) return false;
+
+	if (glBeginFragmentShaderATI_ptr == NULL) return false;
+
+	if (glEndFragmentShaderATI_ptr == NULL) return false;
+
+	if (glPassTexCoordATI_ptr == NULL) return false;
+
+	if (glColorFragmentOp1ATI_ptr == NULL) return false;
+
+	if (glColorFragmentOp2ATI_ptr == NULL) return false;
+
+	if (glColorFragmentOp3ATI_ptr == NULL) return false;
+
+	if (glAlphaFragmentOp1ATI_ptr == NULL) return false;
+
+	if (glAlphaFragmentOp2ATI_ptr == NULL) return false;
+
+	if (glAlphaFragmentOp2ATI_ptr == NULL) return false;
+
+	if (glAlphaFragmentOp3ATI_ptr == NULL) return false;
+
+	if (glSetFragmentShaderConstantATI_ptr == NULL) return false;
+
+    init = true;
+
+	return true;
+}
+

+ 63 - 0
CamelotGLRenderer/Source/CmGLContext.cpp

@@ -0,0 +1,63 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+    (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2011 Torus Knot Software 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 "CmGLContext.h"
+
+namespace CamelotEngine {
+    // Empty base class
+    GLContext::GLContext():
+        initialized(false) {
+    }
+    
+    GLContext::~GLContext() {        
+    }
+    
+    void GLContext::endCurrent() {
+    }
+    
+}
+
+#if CM_THREAD_SUPPORT == 1
+
+// declared in CmGLPrerequisites.h 
+GLEWContext * glewGetContext()
+{
+	using namespace CamelotEngine;
+	static CM_THREAD_POINTER_VAR(GLEWContext, GLEWContextsPtr);
+
+	GLEWContext * currentGLEWContextsPtr =  CM_THREAD_POINTER_GET(GLEWContextsPtr);
+	if (currentGLEWContextsPtr == NULL)
+	{
+		currentGLEWContextsPtr = new GLEWContext();
+		CM_THREAD_POINTER_SET(GLEWContextsPtr, currentGLEWContextsPtr);
+		memset(currentGLEWContextsPtr, 0, sizeof(GLEWContext));
+		glewInit();
+	}
+	return currentGLEWContextsPtr;
+}
+#endif

+ 169 - 0
CamelotGLRenderer/Source/CmGLDefaultHardwareBufferManager.cpp

@@ -0,0 +1,169 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+(Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2011 Torus Knot Software 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 "CmGLDefaultHardwareBufferManager.h"
+#include "CmException.h"
+
+namespace CamelotEngine {
+
+	GLDefaultHardwareVertexBuffer::GLDefaultHardwareVertexBuffer(size_t vertexSize, size_t numVertices, 
+																 HardwareBuffer::Usage usage)
+	: HardwareVertexBuffer(0, vertexSize, numVertices, usage, true, false) // always software, never shadowed
+	{
+		mpData = static_cast<unsigned char*>(_aligned_malloc(mSizeInBytes, CM_SIMD_ALIGNMENT));
+	}
+	//-----------------------------------------------------------------------
+	GLDefaultHardwareVertexBuffer::GLDefaultHardwareVertexBuffer(HardwareBufferManagerBase* mgr, size_t vertexSize, size_t numVertices, 
+		HardwareBuffer::Usage usage)
+        : HardwareVertexBuffer(mgr, vertexSize, numVertices, usage, true, false) // always software, never shadowed
+	{
+        mpData = static_cast<unsigned char*>(_aligned_malloc(mSizeInBytes, CM_SIMD_ALIGNMENT));
+	}
+	//-----------------------------------------------------------------------
+    GLDefaultHardwareVertexBuffer::~GLDefaultHardwareVertexBuffer()
+	{
+		_aligned_free(mpData);
+	}
+	//-----------------------------------------------------------------------
+    void* GLDefaultHardwareVertexBuffer::lockImpl(size_t offset, size_t length, LockOptions options)
+	{
+        // Only for use internally, no 'locking' as such
+		return mpData + offset;
+	}
+	//-----------------------------------------------------------------------
+	void GLDefaultHardwareVertexBuffer::unlockImpl(void)
+	{
+        // Nothing to do
+	}
+	//-----------------------------------------------------------------------
+    void* GLDefaultHardwareVertexBuffer::lock(size_t offset, size_t length, LockOptions options)
+	{
+        mIsLocked = true;
+		return mpData + offset;
+	}
+	//-----------------------------------------------------------------------
+	void GLDefaultHardwareVertexBuffer::unlock(void)
+	{
+        mIsLocked = false;
+        // Nothing to do
+	}
+	//-----------------------------------------------------------------------
+    void GLDefaultHardwareVertexBuffer::readData(size_t offset, size_t length, void* pDest)
+	{
+		assert((offset + length) <= mSizeInBytes);
+		memcpy(pDest, mpData + offset, length);
+	}
+	//-----------------------------------------------------------------------
+    void GLDefaultHardwareVertexBuffer::writeData(size_t offset, size_t length, const void* pSource,
+			bool discardWholeBuffer)
+	{
+		assert((offset + length) <= mSizeInBytes);
+		// ignore discard, memory is not guaranteed to be zeroised
+		memcpy(mpData + offset, pSource, length);
+
+	}
+	//-----------------------------------------------------------------------
+
+	GLDefaultHardwareIndexBuffer::GLDefaultHardwareIndexBuffer(IndexType idxType, 
+		size_t numIndexes, HardwareBuffer::Usage usage) 
+		: HardwareIndexBuffer(0, idxType, numIndexes, usage, true, false) // always software, never shadowed
+	{
+		mpData = new unsigned char[mSizeInBytes];
+	}
+	//-----------------------------------------------------------------------
+    GLDefaultHardwareIndexBuffer::~GLDefaultHardwareIndexBuffer()
+	{
+		delete [] mpData;
+	}
+	//-----------------------------------------------------------------------
+    void* GLDefaultHardwareIndexBuffer::lockImpl(size_t offset, size_t length, LockOptions options)
+	{
+        // Only for use internally, no 'locking' as such
+		return mpData + offset;
+	}
+	//-----------------------------------------------------------------------
+	void GLDefaultHardwareIndexBuffer::unlockImpl(void)
+	{
+        // Nothing to do
+	}
+	//-----------------------------------------------------------------------
+    void* GLDefaultHardwareIndexBuffer::lock(size_t offset, size_t length, LockOptions options)
+	{
+        mIsLocked = true;
+		return mpData + offset;
+	}
+	//-----------------------------------------------------------------------
+	void GLDefaultHardwareIndexBuffer::unlock(void)
+	{
+        mIsLocked = false;
+        // Nothing to do
+	}
+	//-----------------------------------------------------------------------
+    void GLDefaultHardwareIndexBuffer::readData(size_t offset, size_t length, void* pDest)
+	{
+		assert((offset + length) <= mSizeInBytes);
+		memcpy(pDest, mpData + offset, length);
+	}
+	//-----------------------------------------------------------------------
+    void GLDefaultHardwareIndexBuffer::writeData(size_t offset, size_t length, const void* pSource,
+			bool discardWholeBuffer)
+	{
+		assert((offset + length) <= mSizeInBytes);
+		// ignore discard, memory is not guaranteed to be zeroised
+		memcpy(mpData + offset, pSource, length);
+
+	}
+	//-----------------------------------------------------------------------
+	
+	
+    //-----------------------------------------------------------------------
+    GLDefaultHardwareBufferManagerBase::GLDefaultHardwareBufferManagerBase()
+	{
+	}
+    //-----------------------------------------------------------------------
+    GLDefaultHardwareBufferManagerBase::~GLDefaultHardwareBufferManagerBase()
+	{
+        destroyAllDeclarations();
+        destroyAllBindings();
+	}
+    //-----------------------------------------------------------------------
+	HardwareVertexBufferPtr 
+        GLDefaultHardwareBufferManagerBase::createVertexBuffer(size_t vertexSize, 
+		size_t numVerts, HardwareBuffer::Usage usage, bool useShadowBuffer)
+	{
+		return HardwareVertexBufferPtr(
+			new GLDefaultHardwareVertexBuffer(this, vertexSize, numVerts, usage));
+	}
+    //-----------------------------------------------------------------------
+	HardwareIndexBufferPtr 
+        GLDefaultHardwareBufferManagerBase::createIndexBuffer(HardwareIndexBuffer::IndexType itype, 
+		size_t numIndexes, HardwareBuffer::Usage usage, bool useShadowBuffer)
+	{
+		return HardwareIndexBufferPtr(
+			new GLDefaultHardwareIndexBuffer(itype, numIndexes, usage) );
+	}
+}

+ 89 - 0
CamelotGLRenderer/Source/CmGLFBOMultiRenderTarget.cpp

@@ -0,0 +1,89 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+    (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2011 Torus Knot Software 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 "CmGLFBOMultiRenderTarget.h"
+#include "CmGLPixelFormat.h"
+#include "CmGLHardwarePixelBuffer.h"
+
+namespace CamelotEngine {
+
+	GLFBOMultiRenderTarget::GLFBOMultiRenderTarget(GLFBOManager *manager, const String &name):
+		MultiRenderTarget(name),
+		fbo(manager, 0 /* TODO: multisampling on MRTs? */)
+	{
+	}
+	GLFBOMultiRenderTarget::~GLFBOMultiRenderTarget()
+	{
+	}
+
+
+	void GLFBOMultiRenderTarget::bindSurfaceImpl(size_t attachment, RenderTexture *target)
+
+	{
+
+		/// Check if the render target is in the rendertarget->FBO map
+        GLFrameBufferObject *fbobj = 0;
+        target->getCustomAttribute("FBO", &fbobj);
+		assert(fbobj);
+		fbo.bindSurface(attachment, fbobj->getSurface(0));
+
+
+
+		// Initialise?
+
+		
+
+		// Set width and height
+
+		mWidth = fbo.getWidth();
+
+		mHeight = fbo.getHeight();
+
+	}
+
+
+
+	void GLFBOMultiRenderTarget::unbindSurfaceImpl(size_t attachment)
+	{
+		fbo.unbindSurface(attachment);
+
+		// Set width and height
+
+		mWidth = fbo.getWidth();
+
+		mHeight = fbo.getHeight();
+	}
+
+	void GLFBOMultiRenderTarget::getCustomAttribute( const String& name, void *pData )
+	{
+		if(name=="FBO")
+        {
+            *static_cast<GLFrameBufferObject **>(pData) = &fbo;
+        }
+	}
+}

+ 504 - 0
CamelotGLRenderer/Source/CmGLFBORenderTexture.cpp

@@ -0,0 +1,504 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+    (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2011 Torus Knot Software 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 "CmGLFBORenderTexture.h"
+#include "CmGLPixelFormat.h"
+#include "CmGLHardwarePixelBuffer.h"
+#include "CmGLFBOMultiRenderTarget.h"
+
+namespace CamelotEngine {
+
+//-----------------------------------------------------------------------------    
+    GLFBORenderTexture::GLFBORenderTexture(GLFBOManager *manager, const String &name,
+        const GLSurfaceDesc &target, bool writeGamma, UINT32 fsaa):
+        GLRenderTexture(name, target, writeGamma, fsaa),
+        mFB(manager, fsaa)
+    {
+        // Bind target to surface 0 and initialise
+        mFB.bindSurface(0, target);
+        // Get attributes
+        mWidth = mFB.getWidth();
+        mHeight = mFB.getHeight();
+    }
+
+    void GLFBORenderTexture::getCustomAttribute(const String& name, void* pData)
+    {
+        if(name=="FBO")
+        {
+            *static_cast<GLFrameBufferObject **>(pData) = &mFB;
+        }
+		else if (name == "GL_FBOID")
+		{
+            *static_cast<GLuint*>(pData) = mFB.getGLFBOID();
+		}
+		else if (name == "GL_MULTISAMPLEFBOID")
+		{
+            *static_cast<GLuint*>(pData) = mFB.getGLMultisampleFBOID();
+		}
+    }
+
+	void GLFBORenderTexture::swapBuffers(bool waitForVSync)
+	{
+		mFB.swapBuffers();
+	}
+   
+/// Size of probe texture
+#define PROBE_SIZE 16
+
+/// Stencil and depth formats to be tried
+static const GLenum stencilFormats[] =
+{
+    GL_NONE,                    // No stencil
+    GL_STENCIL_INDEX1_EXT,
+    GL_STENCIL_INDEX4_EXT,
+    GL_STENCIL_INDEX8_EXT,
+    GL_STENCIL_INDEX16_EXT
+};
+static const size_t stencilBits[] =
+{
+    0, 1, 4, 8, 16
+};
+#define STENCILFORMAT_COUNT (sizeof(stencilFormats)/sizeof(GLenum))
+
+static const GLenum depthFormats[] =
+{
+    GL_NONE,
+    GL_DEPTH_COMPONENT16,
+    GL_DEPTH_COMPONENT24,    // Prefer 24 bit depth
+    GL_DEPTH_COMPONENT32,
+    GL_DEPTH24_STENCIL8_EXT // packed depth / stencil
+};
+static const size_t depthBits[] =
+{
+    0,16,24,32,24
+};
+#define DEPTHFORMAT_COUNT (sizeof(depthFormats)/sizeof(GLenum))
+
+	GLFBOManager::GLFBOManager(bool atimode):
+		mATIMode(atimode)
+    {
+        detectFBOFormats();
+        
+        glGenFramebuffersEXT(1, &mTempFBO);
+    }
+
+	GLFBOManager::~GLFBOManager()
+	{
+		if(!mRenderBufferMap.empty())
+		{
+			// TODO LOG PORT - Log this somewhere
+			//LogManager::getSingleton().logMessage("GL: Warning! GLFBOManager destructor called, but not all renderbuffers were released.");
+		}
+        
+        glDeleteFramebuffersEXT(1, &mTempFBO);      
+	}
+
+    /** Try a certain FBO format, and return the status. Also sets mDepthRB and mStencilRB.
+        @returns true    if this combo is supported
+                 false   if this combo is not supported
+    */
+    GLuint GLFBOManager::_tryFormat(GLenum depthFormat, GLenum stencilFormat)
+    {
+        GLuint status, depthRB = 0, stencilRB = 0;
+        bool failed = false; // flag on GL errors
+
+        if(depthFormat != GL_NONE)
+        {
+            /// Generate depth renderbuffer
+            glGenRenderbuffersEXT(1, &depthRB);
+            /// Bind it to FBO
+            glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, depthRB);
+            
+            /// Allocate storage for depth buffer
+            glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, depthFormat,
+                                PROBE_SIZE, PROBE_SIZE);
+            
+            /// Attach depth
+            glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT,
+                                    GL_RENDERBUFFER_EXT, depthRB);
+        }
+
+        if(stencilFormat != GL_NONE)
+        {
+            /// Generate stencil renderbuffer
+            glGenRenderbuffersEXT(1, &stencilRB);
+            /// Bind it to FBO
+            glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, stencilRB);
+            glGetError(); // NV hack
+            /// Allocate storage for stencil buffer
+            glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, stencilFormat,
+                                PROBE_SIZE, PROBE_SIZE); 
+            if(glGetError() != GL_NO_ERROR) // NV hack
+                failed = true;
+            /// Attach stencil
+            glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT,
+                            GL_RENDERBUFFER_EXT, stencilRB);
+            if(glGetError() != GL_NO_ERROR) // NV hack
+                failed = true;
+        }
+        
+        status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
+        /// If status is negative, clean up
+        // Detach and destroy
+        glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, 0);
+        glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, 0);
+        if (depthRB)
+            glDeleteRenderbuffersEXT(1, &depthRB);
+        if (stencilRB)
+            glDeleteRenderbuffersEXT(1, &stencilRB);
+        
+        return status == GL_FRAMEBUFFER_COMPLETE_EXT && !failed;
+    }
+    
+    /** Try a certain packed depth/stencil format, and return the status.
+        @returns true    if this combo is supported
+                 false   if this combo is not supported
+    */
+    bool GLFBOManager::_tryPackedFormat(GLenum packedFormat)
+    {
+        GLuint packedRB = 0;
+        bool failed = false; // flag on GL errors
+
+        /// Generate renderbuffer
+        glGenRenderbuffersEXT(1, &packedRB);
+
+        /// Bind it to FBO
+        glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, packedRB);
+
+        /// Allocate storage for buffer
+        glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, packedFormat, PROBE_SIZE, PROBE_SIZE);
+        glGetError(); // NV hack
+
+        /// Attach depth
+        glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT,
+            GL_RENDERBUFFER_EXT, packedRB);
+        if(glGetError() != GL_NO_ERROR) // NV hack
+            failed = true;
+
+        /// Attach stencil
+        glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT,
+            GL_RENDERBUFFER_EXT, packedRB);
+        if(glGetError() != GL_NO_ERROR) // NV hack
+            failed = true;
+
+        GLuint status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
+
+        /// Detach and destroy
+        glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, 0);
+        glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, 0);
+        glDeleteRenderbuffersEXT(1, &packedRB);
+
+        return status == GL_FRAMEBUFFER_COMPLETE_EXT && !failed;
+    }
+
+    /** Detect which internal formats are allowed as RTT
+        Also detect what combinations of stencil and depth are allowed with this internal
+        format.
+    */
+    void GLFBOManager::detectFBOFormats()
+    {
+        // Try all formats, and report which ones work as target
+        GLuint fb = 0, tid = 0;
+        GLint old_drawbuffer = 0, old_readbuffer = 0;
+        GLenum target = GL_TEXTURE_2D;
+
+        glGetIntegerv (GL_DRAW_BUFFER, &old_drawbuffer);
+        glGetIntegerv (GL_READ_BUFFER, &old_readbuffer);
+
+        for(size_t x=0; x<PF_COUNT; ++x)
+        {
+            mProps[x].valid = false;
+
+			// Fetch GL format token
+			GLenum fmt = GLPixelUtil::getGLInternalFormat((PixelFormat)x);
+            if(fmt == GL_NONE && x!=0)
+                continue;
+
+			// No test for compressed formats
+			if(PixelUtil::isCompressed((PixelFormat)x))
+				continue;
+
+			// Buggy ATI cards *crash* on non-RGB(A) formats
+			int depths[4];
+			PixelUtil::getBitDepths((PixelFormat)x, depths);
+			if(fmt!=GL_NONE && mATIMode && (!depths[0] || !depths[1] || !depths[2]))
+				continue;
+
+            // Create and attach framebuffer
+            glGenFramebuffersEXT(1, &fb);
+            glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fb);
+            if (fmt!=GL_NONE)
+            {
+				// Create and attach texture
+				glGenTextures(1, &tid);
+				glBindTexture(target, tid);
+				
+                // Set some default parameters so it won't fail on NVidia cards         
+				if (GLEW_VERSION_1_2)
+					glTexParameteri(target, GL_TEXTURE_MAX_LEVEL, 0);
+                glTexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+                glTexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
+                glTexParameteri(target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+                glTexParameteri(target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
+                            
+				glTexImage2D(target, 0, fmt, PROBE_SIZE, PROBE_SIZE, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
+				glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT,
+                                target, tid, 0);
+            }
+			else
+			{
+				// Draw to nowhere -- stencil/depth only
+				glDrawBuffer(GL_NONE);
+				glReadBuffer(GL_NONE);
+			}
+            // Check status
+            GLuint status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
+
+			// Ignore status in case of fmt==GL_NONE, because no implementation will accept
+			// a buffer without *any* attachment. Buffers with only stencil and depth attachment
+			// might still be supported, so we must continue probing.
+            if(fmt == GL_NONE || status == GL_FRAMEBUFFER_COMPLETE_EXT)
+            {
+                mProps[x].valid = true;
+				StringUtil::StrStreamType str;
+				str << "FBO " << PixelUtil::getFormatName((PixelFormat)x) 
+					<< " depth/stencil support: ";
+
+                // For each depth/stencil formats
+                for (size_t depth = 0; depth < DEPTHFORMAT_COUNT; ++depth)
+                {
+                    if (depthFormats[depth] != GL_DEPTH24_STENCIL8_EXT)
+                    {
+                        // General depth/stencil combination
+
+                        for (size_t stencil = 0; stencil < STENCILFORMAT_COUNT; ++stencil)
+                        {
+                            //StringUtil::StrStreamType l;
+                            //l << "Trying " << PixelUtil::getFormatName((PixelFormat)x) 
+                            //	<< " D" << depthBits[depth] 
+                            //	<< "S" << stencilBits[stencil];
+                            //LogManager::getSingleton().logMessage(l.str());
+
+                            if (_tryFormat(depthFormats[depth], stencilFormats[stencil]))
+                            {
+                                /// Add mode to allowed modes
+                                str << "D" << depthBits[depth] << "S" << stencilBits[stencil] << " ";
+                                FormatProperties::Mode mode;
+                                mode.depth = depth;
+                                mode.stencil = stencil;
+                                mProps[x].modes.push_back(mode);
+                            }
+                        }
+                    }
+                    else
+                    {
+                        // Packed depth/stencil format
+
+// #if OGRE_PLATFORM == OGRE_PLATFORM_LINUX
+// It now seems as if this workaround now *breaks* nvidia cards on Linux with the 169.12 drivers on Linux
+#if 0
+                        // Only query packed depth/stencil formats for 32-bit
+                        // non-floating point formats (ie not R32!) 
+                        // Linux nVidia driver segfaults if you query others
+                        if (PixelUtil::getNumElemBits((PixelFormat)x) != 32 ||
+                            PixelUtil::isFloatingPoint((PixelFormat)x))
+                        {
+                            continue;
+                        }
+#endif
+
+                        if (_tryPackedFormat(depthFormats[depth]))
+                        {
+                            /// Add mode to allowed modes
+                            str << "Packed-D" << depthBits[depth] << "S" << 8 << " ";
+                            FormatProperties::Mode mode;
+                            mode.depth = depth;
+                            mode.stencil = 0;   // unuse
+                            mProps[x].modes.push_back(mode);
+                        }
+                    }
+                }
+            }
+            // Delete texture and framebuffer
+            glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
+            glDeleteFramebuffersEXT(1, &fb);
+			
+			// Workaround for NVIDIA / Linux 169.21 driver problem
+			// see http://www.ogre3d.org/phpBB2/viewtopic.php?t=38037&start=25
+			glFinish();
+			
+            if (fmt!=GL_NONE)
+                glDeleteTextures(1, &tid);
+        }
+
+        // It seems a bug in nVidia driver: glBindFramebufferEXT should restore
+        // draw and read buffers, but in some unclear circumstances it won't.
+        glDrawBuffer(old_drawbuffer);
+        glReadBuffer(old_readbuffer);
+
+		String fmtstring = "";
+        for(size_t x=0; x<PF_COUNT; ++x)
+        {
+            if(mProps[x].valid)
+                fmtstring += PixelUtil::getFormatName((PixelFormat)x)+" ";
+        }
+    }
+    void GLFBOManager::getBestDepthStencil(GLenum internalFormat, GLenum *depthFormat, GLenum *stencilFormat)
+    {
+        const FormatProperties &props = mProps[internalFormat];
+        /// Decide what stencil and depth formats to use
+        /// [best supported for internal format]
+        size_t bestmode=0;
+        int bestscore=-1;
+        for(size_t mode=0; mode<props.modes.size(); mode++)
+        {
+#if 0
+            /// Always prefer D24S8
+            if(stencilBits[props.modes[mode].stencil]==8 &&
+                depthBits[props.modes[mode].depth]==24)
+            {
+                bestmode = mode;
+                break;
+            }
+#endif
+            int desirability = 0;
+            /// Find most desirable mode
+            /// desirability == 0            if no depth, no stencil
+            /// desirability == 1000...2000  if no depth, stencil
+            /// desirability == 2000...3000  if depth, no stencil
+            /// desirability == 3000+        if depth and stencil
+            /// beyond this, the total numer of bits (stencil+depth) is maximised
+            if(props.modes[mode].stencil)
+                desirability += 1000;
+            if(props.modes[mode].depth)
+                desirability += 2000;
+            if(depthBits[props.modes[mode].depth]==24) // Prefer 24 bit for now
+                desirability += 500;
+			if(depthFormats[props.modes[mode].depth]==GL_DEPTH24_STENCIL8_EXT) // Prefer 24/8 packed 
+				desirability += 5000;
+            desirability += stencilBits[props.modes[mode].stencil] + depthBits[props.modes[mode].depth];
+            
+            if(desirability>bestscore)
+            {
+                bestscore = desirability;
+                bestmode = mode;
+            }
+        }
+        *depthFormat = depthFormats[props.modes[bestmode].depth];
+        *stencilFormat = stencilFormats[props.modes[bestmode].stencil];
+    }
+
+    GLFBORenderTexture *GLFBOManager::createRenderTexture(const String &name, 
+		const GLSurfaceDesc &target, bool writeGamma, UINT32 fsaa)
+    {
+        GLFBORenderTexture *retval = new GLFBORenderTexture(this, name, target, writeGamma, fsaa);
+        return retval;
+    }
+	MultiRenderTarget *GLFBOManager::createMultiRenderTarget(const String & name)
+	{
+		return new GLFBOMultiRenderTarget(this, name);
+	}
+
+    void GLFBOManager::bind(RenderTarget *target)
+    {
+        /// Check if the render target is in the rendertarget->FBO map
+        GLFrameBufferObject *fbo = 0;
+        target->getCustomAttribute("FBO", &fbo);
+        if(fbo)
+            fbo->bind();
+        else
+            // Old style context (window/pbuffer) or copying render texture
+            glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
+    }
+    
+    GLSurfaceDesc GLFBOManager::requestRenderBuffer(GLenum format, size_t width, size_t height, UINT32 fsaa)
+    {
+        GLSurfaceDesc retval;
+        retval.buffer = 0; // Return 0 buffer if GL_NONE is requested
+        if(format != GL_NONE)
+        {
+            RBFormat key(format, width, height, fsaa);
+            RenderBufferMap::iterator it = mRenderBufferMap.find(key);
+            if(it != mRenderBufferMap.end())
+            {
+                retval.buffer = it->second.buffer;
+                retval.zoffset = 0;
+				retval.numSamples = fsaa;
+                // Increase refcount
+                ++it->second.refcount;
+            }
+            else
+            {
+                // New one
+                GLRenderBuffer *rb = new GLRenderBuffer(format, width, height, fsaa);
+                mRenderBufferMap[key] = RBRef(rb);
+                retval.buffer = rb;
+                retval.zoffset = 0;
+				retval.numSamples = fsaa;
+            }
+        }
+        //std::cerr << "Requested renderbuffer with format " << std::hex << format << std::dec << " of " << width << "x" << height << " :" << retval.buffer << std::endl;
+        return retval;
+    }
+    //-----------------------------------------------------------------------
+    void GLFBOManager::requestRenderBuffer(const GLSurfaceDesc &surface)
+    {
+        if(surface.buffer == 0)
+            return;
+        RBFormat key(surface.buffer->getGLFormat(), surface.buffer->getWidth(), surface.buffer->getHeight(), surface.numSamples);
+        RenderBufferMap::iterator it = mRenderBufferMap.find(key);
+        assert(it != mRenderBufferMap.end());
+        if (it != mRenderBufferMap.end())   // Just in case
+        {
+            assert(it->second.buffer == surface.buffer);
+            // Increase refcount
+            ++it->second.refcount;
+        }
+    }
+    //-----------------------------------------------------------------------
+    void GLFBOManager::releaseRenderBuffer(const GLSurfaceDesc &surface)
+    {
+        if(surface.buffer == 0)
+            return;
+        RBFormat key(surface.buffer->getGLFormat(), surface.buffer->getWidth(), surface.buffer->getHeight(), surface.numSamples);
+        RenderBufferMap::iterator it = mRenderBufferMap.find(key);
+        if(it != mRenderBufferMap.end())
+		{
+			// Decrease refcount
+			--it->second.refcount;
+			if(it->second.refcount==0)
+			{
+				// If refcount reaches zero, delete buffer and remove from map
+				delete it->second.buffer;
+				mRenderBufferMap.erase(it);
+				//std::cerr << "Destroyed renderbuffer of format " << std::hex << key.format << std::dec
+				//        << " of " << key.width << "x" << key.height << std::endl;
+			}
+		}
+    }
+}

+ 321 - 0
CamelotGLRenderer/Source/CmGLFrameBufferObject.cpp

@@ -0,0 +1,321 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+    (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2011 Torus Knot Software 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 "CmGLFrameBufferObject.h"
+#include "CmGLPixelFormat.h"
+#include "CmGLHardwarePixelBuffer.h"
+#include "CmGLFBORenderTexture.h"
+#include "CmRenderSystemManager.h"
+
+namespace CamelotEngine {
+
+//-----------------------------------------------------------------------------
+    GLFrameBufferObject::GLFrameBufferObject(GLFBOManager *manager, UINT32 fsaa):
+        mManager(manager), mNumSamples(fsaa)
+    {
+        /// Generate framebuffer object
+        glGenFramebuffersEXT(1, &mFB);
+		// check multisampling
+		if (GLEW_EXT_framebuffer_blit && GLEW_EXT_framebuffer_multisample)
+		{
+			// check samples supported
+			glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, mFB);
+			GLint maxSamples;
+			glGetIntegerv(GL_MAX_SAMPLES_EXT, &maxSamples);
+			glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
+			mNumSamples = std::min(mNumSamples, (GLsizei)maxSamples);
+		}
+		else
+		{
+			mNumSamples = 0;
+		}
+		// will we need a second FBO to do multisampling?
+		if (mNumSamples)
+		{
+			glGenFramebuffersEXT(1, &mMultisampleFB);
+		}
+		else
+		{
+			mMultisampleFB = 0;
+		}
+        /// Initialise state
+        mDepth.buffer=0;
+        mStencil.buffer=0;
+        for(size_t x=0; x<CM_MAX_MULTIPLE_RENDER_TARGETS; ++x)
+        {
+            mColour[x].buffer=0;
+        }
+    }
+    GLFrameBufferObject::~GLFrameBufferObject()
+    {
+        mManager->releaseRenderBuffer(mDepth);
+        mManager->releaseRenderBuffer(mStencil);
+		mManager->releaseRenderBuffer(mMultisampleColourBuffer);
+        /// Delete framebuffer object
+        glDeleteFramebuffersEXT(1, &mFB);        
+		if (mMultisampleFB)
+			glDeleteFramebuffersEXT(1, &mMultisampleFB);
+
+    }
+    void GLFrameBufferObject::bindSurface(size_t attachment, const GLSurfaceDesc &target)
+    {
+        assert(attachment < CM_MAX_MULTIPLE_RENDER_TARGETS);
+        mColour[attachment] = target;
+		// Re-initialise
+		if(mColour[0].buffer)
+			initialise();
+    }
+    void GLFrameBufferObject::unbindSurface(size_t attachment)
+    {
+        assert(attachment < CM_MAX_MULTIPLE_RENDER_TARGETS);
+        mColour[attachment].buffer = 0;
+		// Re-initialise if buffer 0 still bound
+		if(mColour[0].buffer)
+		{
+			initialise();
+		}
+    }
+    void GLFrameBufferObject::initialise()
+    {
+		// Release depth and stencil, if they were bound
+        mManager->releaseRenderBuffer(mDepth);
+        mManager->releaseRenderBuffer(mStencil);
+		mManager->releaseRenderBuffer(mMultisampleColourBuffer);
+        /// First buffer must be bound
+        if(!mColour[0].buffer)
+        {
+            OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, 
+            "Attachment 0 must have surface attached",
+		 	"GLFrameBufferObject::initialise");
+        }
+
+		// If we're doing multisampling, then we need another FBO which contains a
+		// renderbuffer which is set up to multisample, and we'll blit it to the final 
+		// FBO afterwards to perform the multisample resolve. In that case, the 
+		// mMultisampleFB is bound during rendering and is the one with a depth/stencil
+
+        /// Store basic stats
+        size_t width = mColour[0].buffer->getWidth();
+        size_t height = mColour[0].buffer->getHeight();
+        GLuint format = mColour[0].buffer->getGLFormat();
+        PixelFormat ogreFormat = mColour[0].buffer->getFormat();
+        UINT16 maxSupportedMRTs = CamelotEngine::RenderSystemManager::getActive()->getCapabilities()->getNumMultiRenderTargets();
+
+		// Bind simple buffer to add colour attachments
+		glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, mFB);
+
+        /// Bind all attachment points to frame buffer
+        for(size_t x=0; x<maxSupportedMRTs; ++x)
+        {
+            if(mColour[x].buffer)
+            {
+                if(mColour[x].buffer->getWidth() != width || mColour[x].buffer->getHeight() != height)
+                {
+                    StringStream ss;
+                    ss << "Attachment " << x << " has incompatible size ";
+                    ss << mColour[x].buffer->getWidth() << "x" << mColour[x].buffer->getHeight();
+                    ss << ". It must be of the same as the size of surface 0, ";
+                    ss << width << "x" << height;
+                    ss << ".";
+                    OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, ss.str(), "GLFrameBufferObject::initialise");
+                }
+                if(mColour[x].buffer->getGLFormat() != format)
+                {
+                    StringStream ss;
+                    ss << "Attachment " << x << " has incompatible format.";
+                    OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, ss.str(), "GLFrameBufferObject::initialise");
+                }
+	            mColour[x].buffer->bindToFramebuffer(GL_COLOR_ATTACHMENT0_EXT+x, mColour[x].zoffset);
+            }
+            else
+            {
+                // Detach
+                glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT+x,
+                    GL_RENDERBUFFER_EXT, 0);
+            }
+        }
+
+		// Now deal with depth / stencil
+		if (mMultisampleFB)
+		{
+			// Bind multisample buffer
+			glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, mMultisampleFB);
+
+			// Create AA render buffer (colour)
+			// note, this can be shared too because we blit it to the final FBO
+			// right after the render is finished
+			mMultisampleColourBuffer = mManager->requestRenderBuffer(format, width, height, mNumSamples);
+
+			// Attach it, because we won't be attaching below and non-multisample has
+			// actually been attached to other FBO
+			mMultisampleColourBuffer.buffer->bindToFramebuffer(GL_COLOR_ATTACHMENT0_EXT, 
+				mMultisampleColourBuffer.zoffset);
+
+			// depth & stencil will be dealt with below
+
+		}
+
+        /// Find suitable depth and stencil format that is compatible with colour format
+        GLenum depthFormat, stencilFormat;
+        mManager->getBestDepthStencil(ogreFormat, &depthFormat, &stencilFormat);
+        
+        /// Request surfaces
+        mDepth = mManager->requestRenderBuffer(depthFormat, width, height, mNumSamples);
+		if (depthFormat == GL_DEPTH24_STENCIL8_EXT)
+		{
+			// bind same buffer to depth and stencil attachments
+            mManager->requestRenderBuffer(mDepth);
+			mStencil = mDepth;
+		}
+		else
+		{
+			// separate stencil
+			mStencil = mManager->requestRenderBuffer(stencilFormat, width, height, mNumSamples);
+		}
+        
+        /// Attach/detach surfaces
+        if(mDepth.buffer)
+        {
+            mDepth.buffer->bindToFramebuffer(GL_DEPTH_ATTACHMENT_EXT, mDepth.zoffset);
+        }
+        else
+        {
+            glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT,
+                GL_RENDERBUFFER_EXT, 0);
+        }
+        if(mStencil.buffer)
+        {
+            mStencil.buffer->bindToFramebuffer(GL_STENCIL_ATTACHMENT_EXT, mStencil.zoffset);
+        }
+        else
+        {
+            glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT,
+                GL_RENDERBUFFER_EXT, 0);
+        }
+
+		/// Do glDrawBuffer calls
+		GLenum bufs[CM_MAX_MULTIPLE_RENDER_TARGETS];
+		GLsizei n=0;
+		for(size_t x=0; x<CM_MAX_MULTIPLE_RENDER_TARGETS; ++x)
+		{
+			// Fill attached colour buffers
+			if(mColour[x].buffer)
+			{
+				bufs[x] = GL_COLOR_ATTACHMENT0_EXT + x;
+				// Keep highest used buffer + 1
+				n = x+1;
+			}
+			else
+			{
+				bufs[x] = GL_NONE;
+			}
+		}
+		if(glDrawBuffers)
+		{
+			/// Drawbuffer extension supported, use it
+			glDrawBuffers(n, bufs);
+		}
+		else
+		{
+			/// In this case, the capabilities will not show more than 1 simultaneaous render target.
+			glDrawBuffer(bufs[0]);
+		}
+		if (mMultisampleFB)
+		{
+			// we need a read buffer because we'll be blitting to mFB
+			glReadBuffer(bufs[0]);
+		}
+		else
+		{
+			/// No read buffer, by default, if we want to read anyway we must not forget to set this.
+			glReadBuffer(GL_NONE);
+		}
+        
+        /// Check status
+        GLuint status;
+        status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
+        
+        /// Bind main buffer
+        glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
+        
+        switch(status)
+        {
+        case GL_FRAMEBUFFER_COMPLETE_EXT:
+            // All is good
+            break;
+        case GL_FRAMEBUFFER_UNSUPPORTED_EXT:
+            OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, 
+            "All framebuffer formats with this texture internal format unsupported",
+		 	"GLFrameBufferObject::initialise");
+        default:
+            OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, 
+            "Framebuffer incomplete or other FBO status error",
+		 	"GLFrameBufferObject::initialise");
+        }
+        
+    }
+    void GLFrameBufferObject::bind()
+    {
+        /// Bind it to FBO
+		if (mMultisampleFB)
+			glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, mMultisampleFB);
+		else
+			glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, mFB);
+    }
+
+	void GLFrameBufferObject::swapBuffers()
+	{
+		if (mMultisampleFB)
+		{
+			// blit from multisample buffer to final buffer, triggers resolve
+			size_t width = mColour[0].buffer->getWidth();
+			size_t height = mColour[0].buffer->getHeight();
+			glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, mMultisampleFB);
+			glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, mFB);
+			glBlitFramebufferEXT(0, 0, width, height, 0, 0, width, height, GL_COLOR_BUFFER_BIT, GL_NEAREST);
+
+		}
+	}
+
+    size_t GLFrameBufferObject::getWidth()
+    {
+        assert(mColour[0].buffer);
+        return mColour[0].buffer->getWidth();
+    }
+    size_t GLFrameBufferObject::getHeight()
+    {
+        assert(mColour[0].buffer);
+        return mColour[0].buffer->getHeight();
+    }
+    PixelFormat GLFrameBufferObject::getFormat()
+    {
+        assert(mColour[0].buffer);
+        return mColour[0].buffer->getFormat();
+    }
+//-----------------------------------------------------------------------------
+}

+ 236 - 0
CamelotGLRenderer/Source/CmGLGpuProgram.cpp

@@ -0,0 +1,236 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+(Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2011 Torus Knot Software 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 "CmGLGpuProgram.h"
+#include "CmException.h"
+
+using namespace CamelotEngine;
+
+GLenum getGLShaderType(GpuProgramType programType)
+{
+	switch (programType)
+	{
+		case GPT_VERTEX_PROGRAM:
+		default:
+			return GL_VERTEX_PROGRAM_ARB;
+		case GPT_GEOMETRY_PROGRAM:
+			return GL_GEOMETRY_PROGRAM_NV;
+		case GPT_FRAGMENT_PROGRAM:
+			return GL_FRAGMENT_PROGRAM_ARB;
+	}
+}
+
+GLGpuProgram::GLGpuProgram() 
+    : GpuProgram()
+{
+    //if (createParamDictionary("GLGpuProgram"))
+    //{
+    //    setupBaseParamDictionary();
+    //}
+}
+
+GLGpuProgram::~GLGpuProgram()
+{
+    // have to call this here reather than in Resource destructor
+    // since calling virtual methods in base destructors causes crash
+    unload(); 
+}
+
+GLuint GLGpuProgram::getAttributeIndex(VertexElementSemantic semantic, CamelotEngine::UINT32 index)
+{
+	return getFixedAttributeIndex(semantic, index);
+}
+
+GLuint GLGpuProgram::getFixedAttributeIndex(VertexElementSemantic semantic, CamelotEngine::UINT32 index)
+{
+	// Some drivers (e.g. OS X on nvidia) incorrectly determine the attribute binding automatically
+	// and end up aliasing existing built-ins. So avoid! Fixed builtins are: 
+
+	//  a  builtin				custom attrib name
+	// ----------------------------------------------
+	//	0  gl_Vertex			vertex
+	//  1  n/a					blendWeights		
+	//	2  gl_Normal			normal
+	//	3  gl_Color				colour
+	//	4  gl_SecondaryColor	secondary_colour
+	//	5  gl_FogCoord			fog_coord
+	//  7  n/a					blendIndices
+	//	8  gl_MultiTexCoord0	uv0
+	//	9  gl_MultiTexCoord1	uv1
+	//	10 gl_MultiTexCoord2	uv2
+	//	11 gl_MultiTexCoord3	uv3
+	//	12 gl_MultiTexCoord4	uv4
+	//	13 gl_MultiTexCoord5	uv5
+	//	14 gl_MultiTexCoord6	uv6, tangent
+	//	15 gl_MultiTexCoord7	uv7, binormal
+	switch(semantic)
+	{
+	case VES_POSITION:
+		return 0;
+	case VES_BLEND_WEIGHTS:
+		return 1;
+	case VES_NORMAL:
+		return 2;
+	case VES_DIFFUSE:
+		return 3;
+	case VES_SPECULAR:
+		return 4;
+	case VES_BLEND_INDICES:
+		return 7;
+	case VES_TEXTURE_COORDINATES:
+		return 8 + index;
+	case VES_TANGENT:
+		return 14;
+	case VES_BINORMAL:
+		return 15;
+	default:
+		assert(false && "Missing attribute!");
+		return 0;
+	};
+
+}
+
+bool GLGpuProgram::isAttributeValid(VertexElementSemantic semantic, CamelotEngine::UINT32 index)
+{
+	// default implementation
+	switch(semantic)
+	{
+		case VES_POSITION:
+		case VES_NORMAL:
+		case VES_DIFFUSE:
+		case VES_SPECULAR:
+		case VES_TEXTURE_COORDINATES:
+			return false;
+		case VES_BLEND_WEIGHTS:
+		case VES_BLEND_INDICES:
+		case VES_BINORMAL:
+		case VES_TANGENT:
+			return true; // with default binding
+	}
+
+    return false;
+}
+
+GLArbGpuProgram::GLArbGpuProgram() 
+    : GLGpuProgram()
+{
+    glGenProgramsARB(1, &mProgramID);
+}
+
+GLArbGpuProgram::~GLArbGpuProgram()
+{
+    // have to call this here reather than in Resource destructor
+    // since calling virtual methods in base destructors causes crash
+    unload(); 
+}
+
+void GLArbGpuProgram::setType(GpuProgramType t)
+{
+    GLGpuProgram::setType(t);
+	mProgramType = getGLShaderType(t);
+}
+
+void GLArbGpuProgram::bindProgram(void)
+{
+    glEnable(mProgramType);
+    glBindProgramARB(mProgramType, mProgramID);
+}
+
+void GLArbGpuProgram::unbindProgram(void)
+{
+    glBindProgramARB(mProgramType, 0);
+    glDisable(mProgramType);
+}
+
+void GLArbGpuProgram::bindProgramParameters(GpuProgramParametersSharedPtr params, CamelotEngine::UINT16 mask)
+{
+    GLenum type = getGLShaderType(mType);
+    
+	// only supports float constants
+	GpuLogicalBufferStructPtr floatStruct = params->getFloatLogicalBufferStruct();
+
+	for (GpuLogicalIndexUseMap::const_iterator i = floatStruct->map.begin();
+		i != floatStruct->map.end(); ++i)
+	{
+		if (i->second.variability & mask)
+		{
+			size_t logicalIndex = i->first;
+			const float* pFloat = params->getFloatPointer(i->second.physicalIndex);
+			// Iterate over the params, set in 4-float chunks (low-level)
+			for (size_t j = 0; j < i->second.currentSize; j+=4)
+			{
+				glProgramLocalParameter4fvARB(type, logicalIndex, pFloat);
+				pFloat += 4;
+				++logicalIndex;
+			}
+		}
+	}
+}
+
+void GLArbGpuProgram::bindProgramPassIterationParameters(GpuProgramParametersSharedPtr params)
+{
+    if (params->hasPassIterationNumber())
+    {
+		GLenum type = getGLShaderType(mType);
+
+		size_t physicalIndex = params->getPassIterationNumberIndex();
+		size_t logicalIndex = params->getFloatLogicalIndexForPhysicalIndex(physicalIndex);
+		const float* pFloat = params->getFloatPointer(physicalIndex);
+        glProgramLocalParameter4fvARB(type, (GLuint)logicalIndex, pFloat);
+    }
+
+}
+
+void GLArbGpuProgram::unloadImpl(void)
+{
+    glDeleteProgramsARB(1, &mProgramID);
+}
+
+void GLArbGpuProgram::loadFromSource(void)
+{
+    if (GL_INVALID_OPERATION == glGetError()) {
+		// TODO LOG PORT LOG - Log this somewhere
+        //LogManager::getSingleton().logMessage("Invalid Operation before loading program "+mName);
+
+    }
+    glBindProgramARB(mProgramType, mProgramID);
+    glProgramStringARB(mProgramType, GL_PROGRAM_FORMAT_ASCII_ARB, (GLsizei)mSource.length(), mSource.c_str());
+
+    if (GL_INVALID_OPERATION == glGetError())
+    {
+        GLint errPos;
+        glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &errPos);
+		String errPosStr = toString(errPos);
+        char* errStr = (char*)glGetString(GL_PROGRAM_ERROR_STRING_ARB);
+        // XXX New exception code?
+        OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, 
+            "Cannot load GL vertex program.  Line " + errPosStr + ":\n" + errStr, "");
+    }
+    glBindProgramARB(mProgramType, 0);
+}
+

+ 66 - 0
CamelotGLRenderer/Source/CmGLGpuProgramManager.cpp

@@ -0,0 +1,66 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+(Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2011 Torus Knot Software 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 "CmGLGpuProgramManager.h"
+#include "CmGLGpuProgram.h"
+
+using namespace CamelotEngine;
+
+GLGpuProgramManager::GLGpuProgramManager()
+{
+    // Superclass sets up members 
+}
+
+
+GLGpuProgramManager::~GLGpuProgramManager()
+{
+}
+
+bool GLGpuProgramManager::registerProgramFactory(const String& syntaxCode, CreateGpuProgramCallback createFn)
+{
+    return mProgramMap.insert(ProgramMap::value_type(syntaxCode, createFn)).second;
+}
+
+bool GLGpuProgramManager::unregisterProgramFactory(const String& syntaxCode)
+{
+    return mProgramMap.erase(syntaxCode) != 0;
+}
+
+GpuProgram* GLGpuProgramManager::create(GpuProgramType gptype, const String& syntaxCode)
+{
+    ProgramMap::const_iterator iter = mProgramMap.find(syntaxCode);
+    if(iter == mProgramMap.end())
+    {
+        // No factory, this is an unsupported syntax code, probably for another rendersystem
+        // Create a basic one, it doesn't matter what it is since it won't be used
+        return new GLGpuProgram();
+    }
+    
+    return (iter->second)(gptype, syntaxCode);
+}
+

+ 270 - 0
CamelotGLRenderer/Source/CmGLHardwareBufferManager.cpp

@@ -0,0 +1,270 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+    (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2011 Torus Knot Software 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 "CmGLHardwareBufferManager.h"
+#include "CmGLHardwareVertexBuffer.h"
+#include "CmGLHardwareIndexBuffer.h"
+#include "CmHardwareBuffer.h"
+#include "CmRenderSystem.h"
+#include "CmRenderSystemCapabilities.h"
+#include "CmRenderSystemManager.h"
+
+namespace CamelotEngine {
+    //-----------------------------------------------------------------------
+	// Scratch pool management (32 bit structure)
+	struct GLScratchBufferAlloc
+	{
+		/// Size in bytes
+		UINT32 size: 31;
+		/// Free? (pack with size)
+		UINT32 free: 1;
+	};
+	#define SCRATCH_POOL_SIZE 1 * 1024 * 1024
+	#define SCRATCH_ALIGNMENT 32
+	//---------------------------------------------------------------------
+    GLHardwareBufferManagerBase::GLHardwareBufferManagerBase() 
+		: mScratchBufferPool(NULL), mMapBufferThreshold(OGRE_GL_DEFAULT_MAP_BUFFER_THRESHOLD)
+    {
+		// Init scratch pool
+		// TODO make it a configurable size?
+		// 32-bit aligned buffer
+		mScratchBufferPool = static_cast<char*>(_aligned_malloc(SCRATCH_POOL_SIZE, SCRATCH_ALIGNMENT));
+		GLScratchBufferAlloc* ptrAlloc = (GLScratchBufferAlloc*)mScratchBufferPool;
+		ptrAlloc->size = SCRATCH_POOL_SIZE - sizeof(GLScratchBufferAlloc);
+		ptrAlloc->free = 1;
+
+		// non-Win32 machines are having issues glBufferSubData, looks like buffer corruption
+		// disable for now until we figure out where the problem lies			
+#	if CM_PLATFORM != CM_PLATFORM_WIN32
+		mMapBufferThreshold = 0;
+#	endif
+
+		// Win32 machines with ATI GPU are having issues glMapBuffer, looks like buffer corruption
+		// disable for now until we figure out where the problem lies			
+#	if CM_PLATFORM == CM_PLATFORM_WIN32
+		if (CamelotEngine::RenderSystemManager::getActive()->getCapabilities()->getVendor() == GPU_ATI) 
+		{
+			mMapBufferThreshold = 0xffffffffUL  /* maximum unsigned long value */;
+		}
+#	endif
+
+    }
+    //-----------------------------------------------------------------------
+    GLHardwareBufferManagerBase::~GLHardwareBufferManagerBase()
+    {
+        destroyAllDeclarations();
+        destroyAllBindings();
+
+		_aligned_free(mScratchBufferPool);
+    }
+    //-----------------------------------------------------------------------
+    HardwareVertexBufferPtr GLHardwareBufferManagerBase::createVertexBuffer(
+        size_t vertexSize, size_t numVerts, HardwareBuffer::Usage usage, bool useShadowBuffer)
+    {
+		GLHardwareVertexBuffer* buf = 
+			new GLHardwareVertexBuffer(this, vertexSize, numVerts, usage, useShadowBuffer);
+		{
+			CM_LOCK_MUTEX(mVertexBuffersMutex)
+			mVertexBuffers.insert(buf);
+		}
+		return HardwareVertexBufferPtr(buf);
+    }
+    //-----------------------------------------------------------------------
+    HardwareIndexBufferPtr 
+    GLHardwareBufferManagerBase::createIndexBuffer(
+        HardwareIndexBuffer::IndexType itype, size_t numIndexes, 
+        HardwareBuffer::Usage usage, bool useShadowBuffer)
+    {
+		GLHardwareIndexBuffer* buf = 
+			new GLHardwareIndexBuffer(this, itype, numIndexes, usage, useShadowBuffer);
+		{
+			CM_LOCK_MUTEX(mIndexBuffersMutex)
+			mIndexBuffers.insert(buf);
+		}
+		return HardwareIndexBufferPtr(buf);
+    }
+    //---------------------------------------------------------------------
+    GLenum GLHardwareBufferManagerBase::getGLUsage(unsigned int usage)
+    {
+        switch(usage)
+        {
+        case HardwareBuffer::HBU_STATIC:
+        case HardwareBuffer::HBU_STATIC_WRITE_ONLY:
+            return GL_STATIC_DRAW_ARB;
+        case HardwareBuffer::HBU_DYNAMIC:
+        case HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY:
+            return GL_DYNAMIC_DRAW_ARB;
+        case HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY_DISCARDABLE:
+            return GL_STREAM_DRAW_ARB;
+        default:
+            return GL_DYNAMIC_DRAW_ARB;
+        };
+    }
+    //---------------------------------------------------------------------
+    GLenum GLHardwareBufferManagerBase::getGLType(unsigned int type)
+    {
+        switch(type)
+        {
+            case VET_FLOAT1:
+            case VET_FLOAT2:
+            case VET_FLOAT3:
+            case VET_FLOAT4:
+                return GL_FLOAT;
+            case VET_SHORT1:
+            case VET_SHORT2:
+            case VET_SHORT3:
+            case VET_SHORT4:
+                return GL_SHORT;
+            case VET_COLOUR:
+			case VET_COLOUR_ABGR:
+			case VET_COLOUR_ARGB:
+            case VET_UBYTE4:
+                return GL_UNSIGNED_BYTE;
+            default:
+                return 0;
+        };
+    }
+	//---------------------------------------------------------------------
+	//---------------------------------------------------------------------
+	void* GLHardwareBufferManagerBase::allocateScratch(UINT32 size)
+	{
+		// simple forward link search based on alloc sizes
+		// not that fast but the list should never get that long since not many
+		// locks at once (hopefully)
+		CM_LOCK_MUTEX(mScratchMutex)
+
+
+		// Alignment - round up the size to 32 bits
+		// control blocks are 32 bits too so this packs nicely
+		if (size % 4 != 0)
+		{
+			size += 4 - (size % 4);
+		}
+
+		UINT32 bufferPos = 0;
+		while (bufferPos < SCRATCH_POOL_SIZE)
+		{
+			GLScratchBufferAlloc* pNext = (GLScratchBufferAlloc*)(mScratchBufferPool + bufferPos);
+			// Big enough?
+			if (pNext->free && pNext->size >= size)
+			{
+				// split? And enough space for control block
+				if(pNext->size > size + sizeof(GLScratchBufferAlloc))
+				{
+					UINT32 offset = (UINT32)sizeof(GLScratchBufferAlloc) + size;
+
+					GLScratchBufferAlloc* pSplitAlloc = (GLScratchBufferAlloc*)
+						(mScratchBufferPool + bufferPos + offset);
+					pSplitAlloc->free = 1;
+					// split size is remainder minus new control block
+					pSplitAlloc->size = pNext->size - size - sizeof(GLScratchBufferAlloc);
+
+					// New size of current
+					pNext->size = size;
+				}
+				// allocate and return
+				pNext->free = 0;
+
+				// return pointer just after this control block (++ will do that for us)
+				return ++pNext;
+
+			}
+
+			bufferPos += (UINT32)sizeof(GLScratchBufferAlloc) + pNext->size;
+
+		}
+
+		// no available alloc
+		return 0;
+
+	}
+	//---------------------------------------------------------------------
+	void GLHardwareBufferManagerBase::deallocateScratch(void* ptr)
+	{
+		CM_LOCK_MUTEX(mScratchMutex)
+
+		// Simple linear search dealloc
+		UINT32 bufferPos = 0;
+		GLScratchBufferAlloc* pLast = 0;
+		while (bufferPos < SCRATCH_POOL_SIZE)
+		{
+			GLScratchBufferAlloc* pCurrent = (GLScratchBufferAlloc*)(mScratchBufferPool + bufferPos);
+			
+			// Pointers match?
+			if ((mScratchBufferPool + bufferPos + sizeof(GLScratchBufferAlloc))
+				== ptr)
+			{
+				// dealloc
+				pCurrent->free = 1;
+				
+				// merge with previous
+				if (pLast && pLast->free)
+				{
+					// adjust buffer pos
+					bufferPos -= (pLast->size + (UINT32)sizeof(GLScratchBufferAlloc));
+					// merge free space
+					pLast->size += pCurrent->size + sizeof(GLScratchBufferAlloc);
+					pCurrent = pLast;
+				}
+
+				// merge with next
+				UINT32 offset = bufferPos + pCurrent->size + (UINT32)sizeof(GLScratchBufferAlloc);
+				if (offset < SCRATCH_POOL_SIZE)
+				{
+					GLScratchBufferAlloc* pNext = (GLScratchBufferAlloc*)(
+						mScratchBufferPool + offset);
+					if (pNext->free)
+					{
+						pCurrent->size += pNext->size + sizeof(GLScratchBufferAlloc);
+					}
+				}
+
+				// done
+				return;
+			}
+
+			bufferPos += (UINT32)sizeof(GLScratchBufferAlloc) + pCurrent->size;
+			pLast = pCurrent;
+
+		}
+
+		// Should never get here unless there's a corruption
+		assert (false && "Memory deallocation error");
+
+
+	}
+	//---------------------------------------------------------------------
+	const size_t GLHardwareBufferManagerBase::getGLMapBufferThreshold() const
+	{
+		return mMapBufferThreshold;
+	}
+	//---------------------------------------------------------------------
+	void GLHardwareBufferManagerBase::setGLMapBufferThreshold( const size_t value )
+	{
+		mMapBufferThreshold = value;
+	}
+}

+ 242 - 0
CamelotGLRenderer/Source/CmGLHardwareIndexBuffer.cpp

@@ -0,0 +1,242 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+    (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2011 Torus Knot Software 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 "CmGLHardwareIndexBuffer.h"
+#include "CmGLHardwareBufferManager.h"
+#include "CmException.h"
+
+namespace CamelotEngine {
+
+	//---------------------------------------------------------------------
+    GLHardwareIndexBuffer::GLHardwareIndexBuffer(HardwareBufferManagerBase* mgr, IndexType idxType,
+        size_t numIndexes, HardwareBuffer::Usage usage, bool useShadowBuffer)
+        : HardwareIndexBuffer(mgr, idxType, numIndexes, usage, false, useShadowBuffer)
+    {
+        glGenBuffersARB( 1, &mBufferId );
+
+        if (!mBufferId)
+        {
+            OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, 
+                "Cannot create GL index buffer", 
+                "GLHardwareIndexBuffer::GLHardwareIndexBuffer");
+        }
+
+        glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, mBufferId);
+
+        // Initialise buffer and set usage
+        glBufferDataARB(GL_ELEMENT_ARRAY_BUFFER_ARB, mSizeInBytes, NULL, 
+            GLHardwareBufferManager::getGLUsage(usage));
+
+        //std::cerr << "creating index buffer " << mBufferId << std::endl;
+    }
+	//---------------------------------------------------------------------
+    GLHardwareIndexBuffer::~GLHardwareIndexBuffer()
+    {
+        glDeleteBuffersARB(1, &mBufferId);
+    }
+	//---------------------------------------------------------------------
+    void* GLHardwareIndexBuffer::lockImpl(size_t offset, 
+        size_t length, LockOptions options)
+    {
+        GLenum access = 0;
+
+        if(mIsLocked)
+        {
+            OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, 
+                "Invalid attempt to lock an index buffer that has already been locked",
+                    "GLHardwareIndexBuffer::lock");
+        }
+
+        
+		void* retPtr = 0;
+
+		GLHardwareBufferManager* glBufManager = static_cast<GLHardwareBufferManager*>(HardwareBufferManager::getSingletonPtr());
+
+		// Try to use scratch buffers for smaller buffers
+		if( length < glBufManager->getGLMapBufferThreshold() )
+		{
+			retPtr = glBufManager->allocateScratch((UINT32)length);
+			if (retPtr)
+			{
+				mLockedToScratch = true;
+				mScratchOffset = offset;
+				mScratchSize = length;
+				mScratchPtr = retPtr;
+				mScratchUploadOnUnlock = (options != HBL_READ_ONLY);
+
+				if (options != HBL_DISCARD)
+				{
+					// have to read back the data before returning the pointer
+					readData(offset, length, retPtr);
+				}
+			}
+		}
+
+		if (!retPtr)
+		{
+			glBindBufferARB( GL_ELEMENT_ARRAY_BUFFER_ARB, mBufferId );
+			// Use glMapBuffer
+			if(options == HBL_DISCARD)
+			{
+				// Discard the buffer
+				glBufferDataARB(GL_ELEMENT_ARRAY_BUFFER_ARB, mSizeInBytes, NULL, 
+					GLHardwareBufferManager::getGLUsage(mUsage));
+			}
+			if (mUsage & HBU_WRITE_ONLY)
+				access = GL_WRITE_ONLY_ARB;
+			else if (options == HBL_READ_ONLY)
+				access = GL_READ_ONLY_ARB;
+			else
+				access = GL_READ_WRITE_ARB;
+
+			void* pBuffer = glMapBufferARB( GL_ELEMENT_ARRAY_BUFFER_ARB, access );
+
+			if(pBuffer == 0)
+			{
+				OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, 
+					"Index Buffer: Out of memory", 
+					"GLHardwareIndexBuffer::lock");
+			}
+
+			// return offsetted
+			retPtr = static_cast<void*>(
+				static_cast<unsigned char*>(pBuffer) + offset);
+
+			mLockedToScratch = false;
+
+		}
+		mIsLocked = true;
+		return retPtr;
+    }
+	//---------------------------------------------------------------------
+	void GLHardwareIndexBuffer::unlockImpl(void)
+    {
+		if (mLockedToScratch)
+		{
+			if (mScratchUploadOnUnlock)
+			{
+				// have to write the data back to vertex buffer
+				writeData(mScratchOffset, mScratchSize, mScratchPtr, 
+					mScratchOffset == 0 && mScratchSize == getSizeInBytes());
+			}
+
+			// deallocate from scratch buffer
+			static_cast<GLHardwareBufferManager*>(
+				HardwareBufferManager::getSingletonPtr())->deallocateScratch(mScratchPtr);
+
+			mLockedToScratch = false;
+		}
+		else
+		{
+
+			glBindBufferARB( GL_ELEMENT_ARRAY_BUFFER_ARB, mBufferId );
+
+			if(!glUnmapBufferARB( GL_ELEMENT_ARRAY_BUFFER_ARB ))
+			{
+				OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, 
+					"Buffer data corrupted, please reload", 
+					"GLHardwareIndexBuffer::unlock");
+			}
+		}
+
+        mIsLocked = false;
+    }
+	//---------------------------------------------------------------------
+    void GLHardwareIndexBuffer::readData(size_t offset, size_t length, 
+        void* pDest)
+    {
+        if(mUseShadowBuffer)
+        {
+            // get data from the shadow buffer
+            void* srcData = mpShadowBuffer->lock(offset, length, HBL_READ_ONLY);
+            memcpy(pDest, srcData, length);
+            mpShadowBuffer->unlock();
+        }
+        else
+        {
+            glBindBufferARB( GL_ELEMENT_ARRAY_BUFFER_ARB, mBufferId );
+            glGetBufferSubDataARB(GL_ELEMENT_ARRAY_BUFFER_ARB, offset, length, pDest);
+        }
+    }
+	//---------------------------------------------------------------------
+    void GLHardwareIndexBuffer::writeData(size_t offset, size_t length, 
+            const void* pSource, bool discardWholeBuffer)
+    {
+        glBindBufferARB( GL_ELEMENT_ARRAY_BUFFER_ARB, mBufferId );
+
+        // Update the shadow buffer
+        if(mUseShadowBuffer)
+        {
+            void* destData = mpShadowBuffer->lock(offset, length, 
+                discardWholeBuffer ? HBL_DISCARD : HBL_NORMAL);
+            memcpy(destData, pSource, length);
+            mpShadowBuffer->unlock();
+        }
+
+        if (offset == 0 && length == mSizeInBytes)
+        {
+            glBufferDataARB(GL_ELEMENT_ARRAY_BUFFER_ARB, mSizeInBytes, pSource,
+                GLHardwareBufferManager::getGLUsage(mUsage));
+        }
+        else
+        {
+            if(discardWholeBuffer)
+            {
+                glBufferDataARB(GL_ELEMENT_ARRAY_BUFFER_ARB, mSizeInBytes, NULL,
+                    GLHardwareBufferManager::getGLUsage(mUsage));
+            }
+
+            // Now update the real buffer
+            glBufferSubDataARB(GL_ELEMENT_ARRAY_BUFFER_ARB, offset, length, pSource);
+        }
+    }
+	//---------------------------------------------------------------------
+    void GLHardwareIndexBuffer::_updateFromShadow(void)
+    {
+        if (mUseShadowBuffer && mShadowUpdated && !mSuppressHardwareUpdate)
+        {
+            const void *srcData = mpShadowBuffer->lock(
+                mLockStart, mLockSize, HBL_READ_ONLY);
+
+            glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, mBufferId);
+
+            // Update whole buffer if possible, otherwise normal
+            if (mLockStart == 0 && mLockSize == mSizeInBytes)
+            {
+                glBufferDataARB(GL_ELEMENT_ARRAY_BUFFER_ARB, mSizeInBytes, srcData,
+                    GLHardwareBufferManager::getGLUsage(mUsage));
+            }
+            else
+            {
+                glBufferSubDataARB(GL_ELEMENT_ARRAY_BUFFER_ARB, mLockStart, mLockSize, srcData);
+            }
+
+            mpShadowBuffer->unlock();
+            mShadowUpdated = false;
+        }
+    }
+}

Some files were not shown because too many files changed in this diff