CmGLRenderSystem.cpp 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647
  1. /*
  2. -----------------------------------------------------------------------------
  3. This source file is part of OGRE
  4. (Object-oriented Graphics Rendering Engine)
  5. For the latest info, see http://www.ogre3d.org
  6. Copyright (c) 2000-2011 Torus Knot Software Ltd
  7. Permission is hereby granted, free of charge, to any person obtaining a copy
  8. of this software and associated documentation files (the "Software"), to deal
  9. in the Software without restriction, including without limitation the rights
  10. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. copies of the Software, and to permit persons to whom the Software is
  12. furnished to do so, subject to the following conditions:
  13. The above copyright notice and this permission notice shall be included in*
  14. all copies or substantial portions of the Software.
  15. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. THE SOFTWARE.s
  22. -----------------------------------------------------------------------------
  23. */
  24. #include "CmGLRenderSystem.h"
  25. #include "CmRenderSystem.h"
  26. #include "CmCamera.h"
  27. #include "CmGLTextureManager.h"
  28. #include "CmGLHardwareVertexBuffer.h"
  29. #include "CmGLHardwareIndexBuffer.h"
  30. #include "CmGLDefaultHardwareBufferManager.h"
  31. #include "CmGLUtil.h"
  32. #include "CmGLGpuProgram.h"
  33. #include "ATI_FS_GLGpuProgram.h"
  34. #include "CmGLGpuProgramManager.h"
  35. #include "CmException.h"
  36. #include "CmGLSLExtSupport.h"
  37. #include "CmGLHardwareOcclusionQuery.h"
  38. #include "CmGLContext.h"
  39. #include "CmGLFBORenderTexture.h"
  40. #include "CmGLPBRenderTexture.h"
  41. // Convenience macro from ARB_vertex_buffer_object spec
  42. #define VBO_BUFFER_OFFSET(i) ((char *)NULL + (i))
  43. #if CM_THREAD_SUPPORT != 1
  44. GLenum glewContextInit (CamelotEngine::GLSupport *glSupport);
  45. #endif
  46. namespace CamelotEngine {
  47. // Callback function used when registering GLGpuPrograms
  48. GpuProgram* createGLArbGpuProgram(GpuProgramType gptype, const String& syntaxCode)
  49. {
  50. GLArbGpuProgram* ret = new GLArbGpuProgram();
  51. ret->setType(gptype);
  52. ret->setSyntaxCode(syntaxCode);
  53. return ret;
  54. }
  55. GpuProgram* createGL_ATI_FS_GpuProgram(GpuProgramType gptype, const String& syntaxCode)
  56. {
  57. ATI_FS_GLGpuProgram* ret = new ATI_FS_GLGpuProgram();
  58. ret->setType(gptype);
  59. ret->setSyntaxCode(syntaxCode);
  60. return ret;
  61. }
  62. GLRenderSystem::GLRenderSystem()
  63. : mDepthWrite(true), mStencilMask(0xFFFFFFFF),
  64. mGLSLProgramFactory(0),
  65. mCgProgramFactory(0),
  66. mActiveTextureUnit(0)
  67. {
  68. size_t i;
  69. // Get our GLSupport
  70. mGLSupport = getGLSupport();
  71. mWorldMatrix = Matrix4::IDENTITY;
  72. mViewMatrix = Matrix4::IDENTITY;
  73. initConfigOptions();
  74. mColourWrite[0] = mColourWrite[1] = mColourWrite[2] = mColourWrite[3] = true;
  75. for (i = 0; i < CM_MAX_TEXTURE_LAYERS; i++)
  76. {
  77. // Dummy value
  78. mTextureCoordIndex[i] = 99;
  79. mTextureTypes[i] = 0;
  80. }
  81. mActiveRenderTarget = 0;
  82. mCurrentContext = 0;
  83. mMainContext = 0;
  84. mGLInitialised = false;
  85. mCurrentLights = 0;
  86. mMinFilter = FO_LINEAR;
  87. mMipFilter = FO_POINT;
  88. mCurrentVertexProgram = 0;
  89. mCurrentGeometryProgram = 0;
  90. mCurrentFragmentProgram = 0;
  91. }
  92. GLRenderSystem::~GLRenderSystem()
  93. {
  94. shutdown();
  95. // Destroy render windows
  96. RenderTargetMap::iterator i;
  97. for (i = mRenderTargets.begin(); i != mRenderTargets.end(); ++i)
  98. {
  99. delete i->second;
  100. }
  101. mRenderTargets.clear();
  102. if(mGLSupport)
  103. delete mGLSupport;
  104. }
  105. const String& GLRenderSystem::getName(void) const
  106. {
  107. static String strName("GLRenderSystem");
  108. return strName;
  109. }
  110. void GLRenderSystem::initConfigOptions(void)
  111. {
  112. mGLSupport->addConfig();
  113. }
  114. ConfigOptionMap& GLRenderSystem::getConfigOptions(void)
  115. {
  116. return mGLSupport->getConfigOptions();
  117. }
  118. void GLRenderSystem::setConfigOption(const String &name, const String &value)
  119. {
  120. mGLSupport->setConfigOption(name, value);
  121. }
  122. String GLRenderSystem::validateConfigOptions(void)
  123. {
  124. // XXX Return an error string if something is invalid
  125. return mGLSupport->validateConfig();
  126. }
  127. RenderWindow* GLRenderSystem::_initialise(bool autoCreateWindow, const String& windowTitle)
  128. {
  129. mGLSupport->start();
  130. RenderWindow* autoWindow = mGLSupport->createWindow(autoCreateWindow, this, windowTitle);
  131. RenderSystem::_initialise(autoCreateWindow, windowTitle);
  132. return autoWindow;
  133. }
  134. RenderSystemCapabilities* GLRenderSystem::createRenderSystemCapabilities() const
  135. {
  136. RenderSystemCapabilities* rsc = new RenderSystemCapabilities();
  137. rsc->setCategoryRelevant(CAPS_CATEGORY_GL, true);
  138. rsc->setDriverVersion(mDriverVersion);
  139. const char* deviceName = (const char*)glGetString(GL_RENDERER);
  140. const char* vendorName = (const char*)glGetString(GL_VENDOR);
  141. rsc->setDeviceName(deviceName);
  142. rsc->setRenderSystemName(getName());
  143. // determine vendor
  144. if (strstr(vendorName, "NVIDIA"))
  145. rsc->setVendor(GPU_NVIDIA);
  146. else if (strstr(vendorName, "ATI"))
  147. rsc->setVendor(GPU_ATI);
  148. else if (strstr(vendorName, "Intel"))
  149. rsc->setVendor(GPU_INTEL);
  150. else if (strstr(vendorName, "S3"))
  151. rsc->setVendor(GPU_S3);
  152. else if (strstr(vendorName, "Matrox"))
  153. rsc->setVendor(GPU_MATROX);
  154. else if (strstr(vendorName, "3DLabs"))
  155. rsc->setVendor(GPU_3DLABS);
  156. else if (strstr(vendorName, "SiS"))
  157. rsc->setVendor(GPU_SIS);
  158. else
  159. rsc->setVendor(GPU_UNKNOWN);
  160. // Supports fixed-function
  161. rsc->setCapability(RSC_FIXED_FUNCTION);
  162. // Check for hardware mipmapping support.
  163. if(GLEW_VERSION_1_4 || GLEW_SGIS_generate_mipmap)
  164. {
  165. bool disableAutoMip = false;
  166. #if CM_PLATFORM == CM_PLATFORM_APPLE || CM_PLATFORM == CM_PLATFORM_LINUX
  167. // Apple & Linux ATI drivers have faults in hardware mipmap generation
  168. if (rsc->getVendor() == GPU_ATI)
  169. disableAutoMip = true;
  170. #endif
  171. // The Intel 915G frequently corrupts textures when using hardware mip generation
  172. // I'm not currently sure how many generations of hardware this affects,
  173. // so for now, be safe.
  174. if (rsc->getVendor() == GPU_INTEL)
  175. disableAutoMip = true;
  176. // SiS chipsets also seem to have problems with this
  177. if (rsc->getVendor() == GPU_SIS)
  178. disableAutoMip = true;
  179. if (!disableAutoMip)
  180. rsc->setCapability(RSC_AUTOMIPMAP);
  181. }
  182. // Check for blending support
  183. if(GLEW_VERSION_1_3 ||
  184. GLEW_ARB_texture_env_combine ||
  185. GLEW_EXT_texture_env_combine)
  186. {
  187. rsc->setCapability(RSC_BLENDING);
  188. }
  189. // Check for Multitexturing support and set number of texture units
  190. if(GLEW_VERSION_1_3 ||
  191. GLEW_ARB_multitexture)
  192. {
  193. GLint units;
  194. glGetIntegerv( GL_MAX_TEXTURE_UNITS, &units );
  195. if (GLEW_ARB_fragment_program)
  196. {
  197. // Also check GL_MAX_TEXTURE_IMAGE_UNITS_ARB since NV at least
  198. // only increased this on the FX/6x00 series
  199. GLint arbUnits;
  200. glGetIntegerv( GL_MAX_TEXTURE_IMAGE_UNITS_ARB, &arbUnits );
  201. if (arbUnits > units)
  202. units = arbUnits;
  203. }
  204. rsc->setNumTextureUnits(units);
  205. }
  206. else
  207. {
  208. // If no multitexture support then set one texture unit
  209. rsc->setNumTextureUnits(1);
  210. }
  211. // Check for Anisotropy support
  212. if(GLEW_EXT_texture_filter_anisotropic)
  213. {
  214. rsc->setCapability(RSC_ANISOTROPY);
  215. }
  216. // Check for DOT3 support
  217. if(GLEW_VERSION_1_3 ||
  218. GLEW_ARB_texture_env_dot3 ||
  219. GLEW_EXT_texture_env_dot3)
  220. {
  221. rsc->setCapability(RSC_DOT3);
  222. }
  223. // Check for cube mapping
  224. if(GLEW_VERSION_1_3 ||
  225. GLEW_ARB_texture_cube_map ||
  226. GLEW_EXT_texture_cube_map)
  227. {
  228. rsc->setCapability(RSC_CUBEMAPPING);
  229. }
  230. // Point sprites
  231. if (GLEW_VERSION_2_0 || GLEW_ARB_point_sprite)
  232. {
  233. rsc->setCapability(RSC_POINT_SPRITES);
  234. }
  235. // Check for point parameters
  236. if (GLEW_VERSION_1_4)
  237. {
  238. rsc->setCapability(RSC_POINT_EXTENDED_PARAMETERS);
  239. }
  240. if (GLEW_ARB_point_parameters)
  241. {
  242. rsc->setCapability(RSC_POINT_EXTENDED_PARAMETERS_ARB);
  243. }
  244. if (GLEW_EXT_point_parameters)
  245. {
  246. rsc->setCapability(RSC_POINT_EXTENDED_PARAMETERS_EXT);
  247. }
  248. // Check for hardware stencil support and set bit depth
  249. GLint stencil;
  250. glGetIntegerv(GL_STENCIL_BITS,&stencil);
  251. if(stencil)
  252. {
  253. rsc->setCapability(RSC_HWSTENCIL);
  254. rsc->setStencilBufferBitDepth(stencil);
  255. }
  256. if(GLEW_VERSION_1_5 || GLEW_ARB_vertex_buffer_object)
  257. {
  258. if (!GLEW_ARB_vertex_buffer_object)
  259. {
  260. rsc->setCapability(RSC_GL1_5_NOVBO);
  261. }
  262. rsc->setCapability(RSC_VBO);
  263. }
  264. if(GLEW_ARB_vertex_program)
  265. {
  266. rsc->setCapability(RSC_VERTEX_PROGRAM);
  267. // Vertex Program Properties
  268. rsc->setVertexProgramConstantBoolCount(0);
  269. rsc->setVertexProgramConstantIntCount(0);
  270. GLint floatConstantCount;
  271. glGetProgramivARB(GL_VERTEX_PROGRAM_ARB, GL_MAX_PROGRAM_LOCAL_PARAMETERS_ARB, &floatConstantCount);
  272. rsc->setVertexProgramConstantFloatCount(floatConstantCount);
  273. rsc->addShaderProfile("arbvp1");
  274. rsc->addGpuProgramProfile(GPP_VS_1_1, "arbvp1"); // TODO - I don't know if any of these GpuProgramProfile mappings are correct!
  275. rsc->addGpuProgramProfile(GPP_VS_2_0, "arbvp1");
  276. rsc->addGpuProgramProfile(GPP_VS_2_a, "arbvp1");
  277. rsc->addGpuProgramProfile(GPP_VS_2_x, "arbvp1");
  278. if (GLEW_NV_vertex_program2_option)
  279. {
  280. rsc->addShaderProfile("vp30");
  281. rsc->addGpuProgramProfile(GPP_VS_3_0, "vp30"); // TODO - I don't know if any of these GpuProgramProfile mappings are correct!
  282. rsc->addGpuProgramProfile(GPP_VS_4_0, "vp30");
  283. }
  284. if (GLEW_NV_vertex_program3)
  285. {
  286. rsc->addShaderProfile("vp40");
  287. rsc->addGpuProgramProfile(GPP_VS_3_0, "vp40"); // TODO - I don't know if any of these GpuProgramProfile mappings are correct!
  288. rsc->addGpuProgramProfile(GPP_VS_4_0, "vp40");
  289. }
  290. if (GLEW_NV_vertex_program4)
  291. {
  292. rsc->addShaderProfile("gp4vp");
  293. rsc->addShaderProfile("gpu_vp");
  294. }
  295. }
  296. if (GLEW_NV_register_combiners2 &&
  297. GLEW_NV_texture_shader)
  298. {
  299. rsc->setCapability(RSC_FRAGMENT_PROGRAM);
  300. }
  301. // NFZ - check for ATI fragment shader support
  302. if (GLEW_ATI_fragment_shader)
  303. {
  304. rsc->setCapability(RSC_FRAGMENT_PROGRAM);
  305. // no boolean params allowed
  306. rsc->setFragmentProgramConstantBoolCount(0);
  307. // no integer params allowed
  308. rsc->setFragmentProgramConstantIntCount(0);
  309. // only 8 Vector4 constant floats supported
  310. rsc->setFragmentProgramConstantFloatCount(8);
  311. rsc->addShaderProfile("ps_1_4");
  312. rsc->addShaderProfile("ps_1_3");
  313. rsc->addShaderProfile("ps_1_2");
  314. rsc->addShaderProfile("ps_1_1");
  315. rsc->addGpuProgramProfile(GPP_PS_1_1, "ps_1_1"); // TODO - I don't know if any of these GpuProgramProfile mappings are correct!
  316. rsc->addGpuProgramProfile(GPP_PS_1_2, "ps_1_2");
  317. rsc->addGpuProgramProfile(GPP_PS_1_3, "ps_1_3");
  318. rsc->addGpuProgramProfile(GPP_PS_1_4, "ps_1_4");
  319. }
  320. if (GLEW_ARB_fragment_program)
  321. {
  322. rsc->setCapability(RSC_FRAGMENT_PROGRAM);
  323. // Fragment Program Properties
  324. rsc->setFragmentProgramConstantBoolCount(0);
  325. rsc->setFragmentProgramConstantIntCount(0);
  326. GLint floatConstantCount;
  327. glGetProgramivARB(GL_FRAGMENT_PROGRAM_ARB, GL_MAX_PROGRAM_LOCAL_PARAMETERS_ARB, &floatConstantCount);
  328. rsc->setFragmentProgramConstantFloatCount(floatConstantCount);
  329. rsc->addShaderProfile("arbfp1");
  330. rsc->addGpuProgramProfile(GPP_PS_1_1, "arbfp1"); // TODO - I don't know if any of these GpuProgramProfile mappings are correct!
  331. rsc->addGpuProgramProfile(GPP_PS_1_2, "arbfp1");
  332. rsc->addGpuProgramProfile(GPP_PS_1_3, "arbfp1");
  333. rsc->addGpuProgramProfile(GPP_PS_1_4, "arbfp1");
  334. rsc->addGpuProgramProfile(GPP_PS_2_0, "arbfp1");
  335. rsc->addGpuProgramProfile(GPP_PS_2_a, "arbfp1");
  336. rsc->addGpuProgramProfile(GPP_PS_2_b, "arbfp1");
  337. rsc->addGpuProgramProfile(GPP_PS_2_x, "arbfp1");
  338. if (GLEW_NV_fragment_program_option)
  339. {
  340. rsc->addShaderProfile("fp30");
  341. rsc->addGpuProgramProfile(GPP_PS_3_0, "fp30"); // TODO - I don't know if any of these GpuProgramProfile mappings are correct!
  342. rsc->addGpuProgramProfile(GPP_PS_3_x, "fp30");
  343. rsc->addGpuProgramProfile(GPP_PS_4_0, "fp30");
  344. }
  345. if (GLEW_NV_fragment_program2)
  346. {
  347. rsc->addShaderProfile("fp40");
  348. rsc->addGpuProgramProfile(GPP_PS_3_0, "fp40"); // TODO - I don't know if any of these GpuProgramProfile mappings are correct!
  349. rsc->addGpuProgramProfile(GPP_PS_3_x, "fp40");
  350. rsc->addGpuProgramProfile(GPP_PS_4_0, "fp40");
  351. }
  352. }
  353. rsc->addShaderProfile("cg");
  354. // NFZ - Check if GLSL is supported
  355. if ( GLEW_VERSION_2_0 ||
  356. (GLEW_ARB_shading_language_100 &&
  357. GLEW_ARB_shader_objects &&
  358. GLEW_ARB_fragment_shader &&
  359. GLEW_ARB_vertex_shader) )
  360. {
  361. rsc->addShaderProfile("glsl");
  362. }
  363. // Check if geometry shaders are supported
  364. if (GLEW_VERSION_2_0 &&
  365. GLEW_EXT_geometry_shader4)
  366. {
  367. rsc->setCapability(RSC_GEOMETRY_PROGRAM);
  368. rsc->addShaderProfile("nvgp4");
  369. //Also add the CG profiles
  370. rsc->addShaderProfile("gpu_gp");
  371. rsc->addShaderProfile("gp4gp");
  372. rsc->setGeometryProgramConstantBoolCount(0);
  373. rsc->setGeometryProgramConstantIntCount(0);
  374. GLint floatConstantCount = 0;
  375. glGetIntegerv(GL_MAX_GEOMETRY_UNIFORM_COMPONENTS_EXT, &floatConstantCount);
  376. rsc->setGeometryProgramConstantFloatCount(floatConstantCount);
  377. GLint maxOutputVertices;
  378. glGetIntegerv(GL_MAX_GEOMETRY_OUTPUT_VERTICES_EXT,&maxOutputVertices);
  379. rsc->setGeometryProgramNumOutputVertices(maxOutputVertices);
  380. }
  381. //Check if render to vertex buffer (transform feedback in OpenGL)
  382. if (GLEW_VERSION_2_0 &&
  383. GLEW_NV_transform_feedback)
  384. {
  385. rsc->setCapability(RSC_HWRENDER_TO_VERTEX_BUFFER);
  386. }
  387. // Check for texture compression
  388. if(GLEW_VERSION_1_3 || GLEW_ARB_texture_compression)
  389. {
  390. rsc->setCapability(RSC_TEXTURE_COMPRESSION);
  391. // Check for dxt compression
  392. if(GLEW_EXT_texture_compression_s3tc)
  393. {
  394. #if defined(__APPLE__) && defined(__PPC__)
  395. // Apple on ATI & PPC has errors in DXT
  396. if (mGLSupport->getGLVendor().find("ATI") == std::string::npos)
  397. #endif
  398. rsc->setCapability(RSC_TEXTURE_COMPRESSION_DXT);
  399. }
  400. // Check for vtc compression
  401. if(GLEW_NV_texture_compression_vtc)
  402. {
  403. rsc->setCapability(RSC_TEXTURE_COMPRESSION_VTC);
  404. }
  405. }
  406. // Scissor test is standard in GL 1.2 (is it emulated on some cards though?)
  407. rsc->setCapability(RSC_SCISSOR_TEST);
  408. // As are user clipping planes
  409. rsc->setCapability(RSC_USER_CLIP_PLANES);
  410. // 2-sided stencil?
  411. if (GLEW_VERSION_2_0 || GLEW_EXT_stencil_two_side)
  412. {
  413. rsc->setCapability(RSC_TWO_SIDED_STENCIL);
  414. }
  415. // stencil wrapping?
  416. if (GLEW_VERSION_1_4 || GLEW_EXT_stencil_wrap)
  417. {
  418. rsc->setCapability(RSC_STENCIL_WRAP);
  419. }
  420. // Check for hardware occlusion support
  421. if(GLEW_VERSION_1_5 || GLEW_ARB_occlusion_query)
  422. {
  423. // Some buggy driver claim that it is GL 1.5 compliant and
  424. // not support ARB_occlusion_query
  425. if (!GLEW_ARB_occlusion_query)
  426. {
  427. rsc->setCapability(RSC_GL1_5_NOHWOCCLUSION);
  428. }
  429. rsc->setCapability(RSC_HWOCCLUSION);
  430. }
  431. else if (GLEW_NV_occlusion_query)
  432. {
  433. // Support NV extension too for old hardware
  434. rsc->setCapability(RSC_HWOCCLUSION);
  435. }
  436. // UBYTE4 always supported
  437. rsc->setCapability(RSC_VERTEX_FORMAT_UBYTE4);
  438. // Infinite far plane always supported
  439. rsc->setCapability(RSC_INFINITE_FAR_PLANE);
  440. // Check for non-power-of-2 texture support
  441. if(GLEW_ARB_texture_non_power_of_two)
  442. {
  443. rsc->setCapability(RSC_NON_POWER_OF_2_TEXTURES);
  444. }
  445. // Check for Float textures
  446. if(GLEW_ATI_texture_float || GLEW_ARB_texture_float)
  447. {
  448. rsc->setCapability(RSC_TEXTURE_FLOAT);
  449. }
  450. // 3D textures should be supported by GL 1.2, which is our minimum version
  451. rsc->setCapability(RSC_TEXTURE_3D);
  452. // Check for framebuffer object extension
  453. if(GLEW_EXT_framebuffer_object)
  454. {
  455. // Probe number of draw buffers
  456. // Only makes sense with FBO support, so probe here
  457. if(GLEW_VERSION_2_0 ||
  458. GLEW_ARB_draw_buffers ||
  459. GLEW_ATI_draw_buffers)
  460. {
  461. GLint buffers;
  462. glGetIntegerv(GL_MAX_DRAW_BUFFERS_ARB, &buffers);
  463. rsc->setNumMultiRenderTargets(std::min<int>(buffers, (GLint)CM_MAX_MULTIPLE_RENDER_TARGETS));
  464. rsc->setCapability(RSC_MRT_DIFFERENT_BIT_DEPTHS);
  465. if(!GLEW_VERSION_2_0)
  466. {
  467. // Before GL version 2.0, we need to get one of the extensions
  468. if(GLEW_ARB_draw_buffers)
  469. rsc->setCapability(RSC_FBO_ARB);
  470. if(GLEW_ATI_draw_buffers)
  471. rsc->setCapability(RSC_FBO_ATI);
  472. }
  473. // Set FBO flag for all 3 'subtypes'
  474. rsc->setCapability(RSC_FBO);
  475. }
  476. rsc->setCapability(RSC_HWRENDER_TO_TEXTURE);
  477. }
  478. // Check GLSupport for PBuffer support
  479. if(mGLSupport->supportsPBuffers())
  480. {
  481. // Use PBuffers
  482. rsc->setCapability(RSC_HWRENDER_TO_TEXTURE);
  483. rsc->setCapability(RSC_PBUFFER);
  484. }
  485. // Point size
  486. if (GLEW_VERSION_1_4)
  487. {
  488. float ps;
  489. glGetFloatv(GL_POINT_SIZE_MAX, &ps);
  490. rsc->setMaxPointSize(ps);
  491. }
  492. else
  493. {
  494. GLint vSize[2];
  495. glGetIntegerv(GL_POINT_SIZE_RANGE,vSize);
  496. rsc->setMaxPointSize((float)vSize[1]);
  497. }
  498. // Vertex texture fetching
  499. if (mGLSupport->checkExtension("GL_ARB_vertex_shader"))
  500. {
  501. GLint vUnits;
  502. glGetIntegerv(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB, &vUnits);
  503. rsc->setNumVertexTextureUnits(static_cast<UINT16>(vUnits));
  504. if (vUnits > 0)
  505. {
  506. rsc->setCapability(RSC_VERTEX_TEXTURE_FETCH);
  507. }
  508. // GL always shares vertex and fragment texture units (for now?)
  509. rsc->setVertexTextureUnitsShared(true);
  510. }
  511. // Mipmap LOD biasing?
  512. if (GLEW_VERSION_1_4 || GLEW_EXT_texture_lod_bias)
  513. {
  514. rsc->setCapability(RSC_MIPMAP_LOD_BIAS);
  515. }
  516. // Alpha to coverage?
  517. if (mGLSupport->checkExtension("GL_ARB_multisample"))
  518. {
  519. // Alpha to coverage always 'supported' when MSAA is available
  520. // although card may ignore it if it doesn't specifically support A2C
  521. rsc->setCapability(RSC_ALPHA_TO_COVERAGE);
  522. }
  523. // Advanced blending operations
  524. if(GLEW_VERSION_2_0)
  525. {
  526. rsc->setCapability(RSC_ADVANCED_BLEND_OPERATIONS);
  527. }
  528. return rsc;
  529. }
  530. void GLRenderSystem::initialiseFromRenderSystemCapabilities(RenderSystemCapabilities* caps, RenderTarget* primary)
  531. {
  532. if(caps->getRenderSystemName() != getName())
  533. {
  534. CM_EXCEPT(InvalidParametersException,
  535. "Trying to initialize GLRenderSystem from RenderSystemCapabilities that do not support OpenGL");
  536. }
  537. // set texture the number of texture units
  538. mFixedFunctionTextureUnits = caps->getNumTextureUnits();
  539. //In GL there can be less fixed function texture units than general
  540. //texture units. Get the minimum of the two.
  541. if (caps->hasCapability(RSC_FRAGMENT_PROGRAM))
  542. {
  543. GLint maxTexCoords = 0;
  544. glGetIntegerv(GL_MAX_TEXTURE_COORDS_ARB, &maxTexCoords);
  545. if (mFixedFunctionTextureUnits > maxTexCoords)
  546. {
  547. mFixedFunctionTextureUnits = maxTexCoords;
  548. }
  549. }
  550. if(caps->hasCapability(RSC_GL1_5_NOVBO))
  551. {
  552. // Assign ARB functions same to GL 1.5 version since
  553. // interface identical
  554. glBindBufferARB = glBindBuffer;
  555. glBufferDataARB = glBufferData;
  556. glBufferSubDataARB = glBufferSubData;
  557. glDeleteBuffersARB = glDeleteBuffers;
  558. glGenBuffersARB = glGenBuffers;
  559. glGetBufferParameterivARB = glGetBufferParameteriv;
  560. glGetBufferPointervARB = glGetBufferPointerv;
  561. glGetBufferSubDataARB = glGetBufferSubData;
  562. glIsBufferARB = glIsBuffer;
  563. glMapBufferARB = glMapBuffer;
  564. glUnmapBufferARB = glUnmapBuffer;
  565. }
  566. if(caps->hasCapability(RSC_VBO))
  567. {
  568. HardwareBufferManager::startUp(new GLHardwareBufferManager);
  569. }
  570. else
  571. {
  572. HardwareBufferManager::startUp(new GLDefaultHardwareBufferManager);
  573. }
  574. // GPU Program Manager setup
  575. GpuProgramManager::startUp(new GLGpuProgramManager());
  576. GLGpuProgramManager* gpuProgramManager = static_cast<GLGpuProgramManager*>(GpuProgramManager::instancePtr());
  577. if(caps->hasCapability(RSC_VERTEX_PROGRAM))
  578. {
  579. if(caps->isShaderProfileSupported("arbvp1"))
  580. {
  581. gpuProgramManager->registerProgramFactory("arbvp1", createGLArbGpuProgram);
  582. }
  583. if(caps->isShaderProfileSupported("vp30"))
  584. {
  585. gpuProgramManager->registerProgramFactory("vp30", createGLArbGpuProgram);
  586. }
  587. if(caps->isShaderProfileSupported("vp40"))
  588. {
  589. gpuProgramManager->registerProgramFactory("vp40", createGLArbGpuProgram);
  590. }
  591. if(caps->isShaderProfileSupported("gp4vp"))
  592. {
  593. gpuProgramManager->registerProgramFactory("gp4vp", createGLArbGpuProgram);
  594. }
  595. if(caps->isShaderProfileSupported("gpu_vp"))
  596. {
  597. gpuProgramManager->registerProgramFactory("gpu_vp", createGLArbGpuProgram);
  598. }
  599. }
  600. if(caps->hasCapability(RSC_GEOMETRY_PROGRAM))
  601. {
  602. //TODO : Should these be createGLArbGpuProgram or createGLGpuNVparseProgram?
  603. if(caps->isShaderProfileSupported("nvgp4"))
  604. {
  605. gpuProgramManager->registerProgramFactory("nvgp4", createGLArbGpuProgram);
  606. }
  607. if(caps->isShaderProfileSupported("gp4gp"))
  608. {
  609. gpuProgramManager->registerProgramFactory("gp4gp", createGLArbGpuProgram);
  610. }
  611. if(caps->isShaderProfileSupported("gpu_gp"))
  612. {
  613. gpuProgramManager->registerProgramFactory("gpu_gp", createGLArbGpuProgram);
  614. }
  615. }
  616. if(caps->hasCapability(RSC_FRAGMENT_PROGRAM))
  617. {
  618. if(caps->isShaderProfileSupported("ps_1_4"))
  619. {
  620. gpuProgramManager->registerProgramFactory("ps_1_4", createGL_ATI_FS_GpuProgram);
  621. }
  622. if(caps->isShaderProfileSupported("ps_1_3"))
  623. {
  624. gpuProgramManager->registerProgramFactory("ps_1_3", createGL_ATI_FS_GpuProgram);
  625. }
  626. if(caps->isShaderProfileSupported("ps_1_2"))
  627. {
  628. gpuProgramManager->registerProgramFactory("ps_1_2", createGL_ATI_FS_GpuProgram);
  629. }
  630. if(caps->isShaderProfileSupported("ps_1_1"))
  631. {
  632. gpuProgramManager->registerProgramFactory("ps_1_1", createGL_ATI_FS_GpuProgram);
  633. }
  634. if(caps->isShaderProfileSupported("arbfp1"))
  635. {
  636. gpuProgramManager->registerProgramFactory("arbfp1", createGLArbGpuProgram);
  637. }
  638. if(caps->isShaderProfileSupported("fp40"))
  639. {
  640. gpuProgramManager->registerProgramFactory("fp40", createGLArbGpuProgram);
  641. }
  642. if(caps->isShaderProfileSupported("fp30"))
  643. {
  644. gpuProgramManager->registerProgramFactory("fp30", createGLArbGpuProgram);
  645. }
  646. }
  647. if(caps->isShaderProfileSupported("glsl"))
  648. {
  649. // NFZ - check for GLSL vertex and fragment shader support successful
  650. mGLSLProgramFactory = new GLSLProgramFactory();
  651. HighLevelGpuProgramManager::instance().addFactory(mGLSLProgramFactory);
  652. }
  653. if(caps->isShaderProfileSupported("cg"))
  654. {
  655. // NFZ - check for GLSL vertex and fragment shader support successful
  656. mCgProgramFactory = new CgProgramFactory();
  657. HighLevelGpuProgramManager::instance().addFactory(mCgProgramFactory);
  658. }
  659. if(caps->hasCapability(RSC_HWOCCLUSION))
  660. {
  661. if(caps->hasCapability(RSC_GL1_5_NOHWOCCLUSION))
  662. {
  663. // Assign ARB functions same to GL 1.5 version since
  664. // interface identical
  665. glBeginQueryARB = glBeginQuery;
  666. glDeleteQueriesARB = glDeleteQueries;
  667. glEndQueryARB = glEndQuery;
  668. glGenQueriesARB = glGenQueries;
  669. glGetQueryObjectivARB = glGetQueryObjectiv;
  670. glGetQueryObjectuivARB = glGetQueryObjectuiv;
  671. glGetQueryivARB = glGetQueryiv;
  672. glIsQueryARB = glIsQuery;
  673. }
  674. }
  675. /// Do this after extension function pointers are initialised as the extension
  676. /// is used to probe further capabilities.
  677. ConfigOptionMap::iterator cfi = getConfigOptions().find("RTT Preferred Mode");
  678. // RTT Mode: 0 use whatever available, 1 use PBuffers, 2 force use copying
  679. int rttMode = 0;
  680. if (cfi != getConfigOptions().end())
  681. {
  682. if (cfi->second.currentValue == "PBuffer")
  683. {
  684. rttMode = 1;
  685. }
  686. else if (cfi->second.currentValue == "Copy")
  687. {
  688. rttMode = 2;
  689. }
  690. }
  691. // Check for framebuffer object extension
  692. if(caps->hasCapability(RSC_FBO) && rttMode < 1)
  693. {
  694. // Before GL version 2.0, we need to get one of the extensions
  695. if(caps->hasCapability(RSC_FBO_ARB))
  696. GLEW_GET_FUN(__glewDrawBuffers) = glDrawBuffersARB;
  697. else if(caps->hasCapability(RSC_FBO_ATI))
  698. GLEW_GET_FUN(__glewDrawBuffers) = glDrawBuffersATI;
  699. if(caps->hasCapability(RSC_HWRENDER_TO_TEXTURE))
  700. {
  701. // Create FBO manager
  702. // TODO LOG PORT - Log this somewhere?
  703. //LogManager::getSingleton().logMessage("GL: Using GL_EXT_framebuffer_object for rendering to textures (best)");
  704. GLRTTManager::startUp(new GLFBOManager(false));
  705. }
  706. }
  707. else
  708. {
  709. // Check GLSupport for PBuffer support
  710. if(caps->hasCapability(RSC_PBUFFER) && rttMode < 2)
  711. {
  712. if(caps->hasCapability(RSC_HWRENDER_TO_TEXTURE))
  713. {
  714. // Use PBuffers
  715. GLRTTManager::startUp(new GLPBRTTManager(mGLSupport, primary));
  716. // TODO LOG PORT - Log this somewhere?
  717. //LogManager::getSingleton().logMessage("GL: Using PBuffers for rendering to textures");
  718. }
  719. }
  720. else
  721. {
  722. // No pbuffer support either -- fallback to simplest copying from framebuffer
  723. GLRTTManager::startUp(new GLCopyingRTTManager());
  724. // TODO LOG PORT - Log this somewhere?
  725. //LogManager::getSingleton().logMessage("GL: Using framebuffer copy for rendering to textures (worst)");
  726. //LogManager::getSingleton().logMessage("GL: Warning: RenderTexture size is restricted to size of framebuffer. If you are on Linux, consider using GLX instead of SDL.");
  727. }
  728. // Downgrade number of simultaneous targets
  729. caps->setNumMultiRenderTargets(1);
  730. }
  731. /// Create the texture manager
  732. TextureManager::startUp(new GLTextureManager(*mGLSupport));
  733. mGLInitialised = true;
  734. }
  735. void GLRenderSystem::reinitialise(void)
  736. {
  737. this->shutdown();
  738. this->_initialise(true);
  739. }
  740. void GLRenderSystem::shutdown(void)
  741. {
  742. RenderSystem::shutdown();
  743. // Deleting the GLSL program factory
  744. if (mGLSLProgramFactory)
  745. {
  746. // Remove from manager safely
  747. HighLevelGpuProgramManager::instance().removeFactory(mGLSLProgramFactory);
  748. delete mGLSLProgramFactory;
  749. mGLSLProgramFactory = 0;
  750. }
  751. // Deleting Cg GLSL program factory
  752. if (mCgProgramFactory)
  753. {
  754. // Remove from manager safely
  755. HighLevelGpuProgramManager::instance().removeFactory(mCgProgramFactory);
  756. delete mCgProgramFactory;
  757. mCgProgramFactory = 0;
  758. }
  759. // Deleting the GPU program manager and hardware buffer manager. Has to be done before the mGLSupport->stop().
  760. GpuProgramManager::shutDown();
  761. HardwareBufferManager::shutDown();
  762. GLRTTManager::shutDown();
  763. // Delete extra threads contexts
  764. for (GLContextList::iterator i = mBackgroundContextList.begin();
  765. i != mBackgroundContextList.end(); ++i)
  766. {
  767. GLContext* pCurContext = *i;
  768. pCurContext->releaseContext();
  769. delete pCurContext;
  770. }
  771. mBackgroundContextList.clear();
  772. mGLSupport->stop();
  773. mStopRendering = true;
  774. TextureManager::shutDown();
  775. // There will be a new initial window and so forth, thus any call to test
  776. // some params will access an invalid pointer, so it is best to reset
  777. // the whole state.
  778. mGLInitialised = 0;
  779. }
  780. //---------------------------------------------------------------------
  781. bool GLRenderSystem::_createRenderWindows(const RenderWindowDescriptionList& renderWindowDescriptions,
  782. RenderWindowList& createdWindows)
  783. {
  784. // Call base render system method.
  785. if (false == RenderSystem::_createRenderWindows(renderWindowDescriptions, createdWindows))
  786. return false;
  787. // Simply call _createRenderWindow in a loop.
  788. for (size_t i = 0; i < renderWindowDescriptions.size(); ++i)
  789. {
  790. const RenderWindowDescription& curRenderWindowDescription = renderWindowDescriptions[i];
  791. RenderWindow* curWindow = NULL;
  792. curWindow = createRenderWindow(curRenderWindowDescription.name,
  793. curRenderWindowDescription.width,
  794. curRenderWindowDescription.height,
  795. curRenderWindowDescription.useFullScreen,
  796. &curRenderWindowDescription.miscParams);
  797. createdWindows.push_back(curWindow);
  798. }
  799. return true;
  800. }
  801. //---------------------------------------------------------------------
  802. RenderWindow* GLRenderSystem::createRenderWindow(const String &name,
  803. unsigned int width, unsigned int height, bool fullScreen,
  804. const NameValuePairList *miscParams)
  805. {
  806. if (mRenderTargets.find(name) != mRenderTargets.end())
  807. {
  808. CM_EXCEPT(InvalidParametersException,
  809. "Window with name '" + name + "' already exists");
  810. }
  811. // Create the window
  812. RenderWindow* win = mGLSupport->newWindow(name, width, height,
  813. fullScreen, miscParams);
  814. attachRenderTarget( *win );
  815. if (!mGLInitialised)
  816. {
  817. // set up glew and GLSupport
  818. initialiseContext(win);
  819. std::vector<CamelotEngine::String> tokens = StringUtil::split(mGLSupport->getGLVersion(), ".");
  820. if (!tokens.empty())
  821. {
  822. mDriverVersion.major = parseInt(tokens[0]);
  823. if (tokens.size() > 1)
  824. mDriverVersion.minor = parseInt(tokens[1]);
  825. if (tokens.size() > 2)
  826. mDriverVersion.release = parseInt(tokens[2]);
  827. }
  828. mDriverVersion.build = 0;
  829. // Initialise GL after the first window has been created
  830. // TODO: fire this from emulation options, and don't duplicate float and Current capabilities
  831. mRealCapabilities = createRenderSystemCapabilities();
  832. // use real capabilities if custom capabilities are not available
  833. if(!mUseCustomCapabilities)
  834. mCurrentCapabilities = mRealCapabilities;
  835. initialiseFromRenderSystemCapabilities(mCurrentCapabilities, win);
  836. // Initialise the main context
  837. _oneTimeContextInitialization();
  838. if(mCurrentContext)
  839. mCurrentContext->setInitialized();
  840. }
  841. return win;
  842. }
  843. void GLRenderSystem::initialiseContext(RenderWindow* primary)
  844. {
  845. // Set main and current context
  846. mMainContext = 0;
  847. primary->getCustomAttribute("GLCONTEXT", &mMainContext);
  848. mCurrentContext = mMainContext;
  849. // Set primary context as active
  850. if(mCurrentContext)
  851. mCurrentContext->setCurrent();
  852. // Setup GLSupport
  853. mGLSupport->initialiseExtensions();
  854. // Get extension function pointers
  855. #if CM_THREAD_SUPPORT != 1
  856. glewContextInit(mGLSupport);
  857. #endif
  858. }
  859. //-----------------------------------------------------------------------
  860. MultiRenderTarget * GLRenderSystem::createMultiRenderTarget(const String & name)
  861. {
  862. MultiRenderTarget *retval = GLRTTManager::instancePtr()->createMultiRenderTarget(name);
  863. attachRenderTarget( *retval );
  864. return retval;
  865. }
  866. //-----------------------------------------------------------------------
  867. void GLRenderSystem::destroyRenderWindow(RenderWindow* pWin)
  868. {
  869. // Find it to remove from list
  870. RenderTargetMap::iterator i = mRenderTargets.begin();
  871. while (i != mRenderTargets.end())
  872. {
  873. if (i->second == pWin)
  874. {
  875. mRenderTargets.erase(i);
  876. delete pWin;
  877. break;
  878. }
  879. }
  880. }
  881. //-----------------------------------------------------------------------------
  882. void GLRenderSystem::makeGLMatrix(GLfloat gl_matrix[16], const Matrix4& m)
  883. {
  884. size_t x = 0;
  885. for (size_t i = 0; i < 4; i++)
  886. {
  887. for (size_t j = 0; j < 4; j++)
  888. {
  889. gl_matrix[x] = m[j][i];
  890. x++;
  891. }
  892. }
  893. }
  894. //-----------------------------------------------------------------------------
  895. void GLRenderSystem::setPointParameters(float size,
  896. bool attenuationEnabled, float constant, float linear, float quadratic,
  897. float minSize, float maxSize)
  898. {
  899. float val[4] = {1, 0, 0, 1};
  900. if(attenuationEnabled)
  901. {
  902. // Point size is still calculated in pixels even when attenuation is
  903. // enabled, which is pretty awkward, since you typically want a viewport
  904. // independent size if you're looking for attenuation.
  905. // So, scale the point size up by viewport size (this is equivalent to
  906. // what D3D does as standard)
  907. size = size * mActiveViewport->getActualHeight();
  908. minSize = minSize * mActiveViewport->getActualHeight();
  909. if (maxSize == 0.0f)
  910. maxSize = mCurrentCapabilities->getMaxPointSize(); // pixels
  911. else
  912. maxSize = maxSize * mActiveViewport->getActualHeight();
  913. // XXX: why do I need this for results to be consistent with D3D?
  914. // Equations are supposedly the same once you factor in vp height
  915. float correction = 0.005f;
  916. // scaling required
  917. val[0] = constant;
  918. val[1] = linear * correction;
  919. val[2] = quadratic * correction;
  920. val[3] = 1;
  921. if (mCurrentCapabilities->hasCapability(RSC_VERTEX_PROGRAM))
  922. glEnable(GL_VERTEX_PROGRAM_POINT_SIZE);
  923. }
  924. else
  925. {
  926. if (maxSize == 0.0f)
  927. maxSize = mCurrentCapabilities->getMaxPointSize();
  928. if (mCurrentCapabilities->hasCapability(RSC_VERTEX_PROGRAM))
  929. glDisable(GL_VERTEX_PROGRAM_POINT_SIZE);
  930. }
  931. // no scaling required
  932. // GL has no disabled flag for this so just set to constant
  933. glPointSize(size);
  934. if (mCurrentCapabilities->hasCapability(RSC_POINT_EXTENDED_PARAMETERS))
  935. {
  936. glPointParameterfv(GL_POINT_DISTANCE_ATTENUATION, val);
  937. glPointParameterf(GL_POINT_SIZE_MIN, minSize);
  938. glPointParameterf(GL_POINT_SIZE_MAX, maxSize);
  939. }
  940. else if (mCurrentCapabilities->hasCapability(RSC_POINT_EXTENDED_PARAMETERS_ARB))
  941. {
  942. glPointParameterfvARB(GL_POINT_DISTANCE_ATTENUATION, val);
  943. glPointParameterfARB(GL_POINT_SIZE_MIN, minSize);
  944. glPointParameterfARB(GL_POINT_SIZE_MAX, maxSize);
  945. }
  946. else if (mCurrentCapabilities->hasCapability(RSC_POINT_EXTENDED_PARAMETERS_EXT))
  947. {
  948. glPointParameterfvEXT(GL_POINT_DISTANCE_ATTENUATION, val);
  949. glPointParameterfEXT(GL_POINT_SIZE_MIN, minSize);
  950. glPointParameterfEXT(GL_POINT_SIZE_MAX, maxSize);
  951. }
  952. }
  953. //-----------------------------------------------------------------------------
  954. void GLRenderSystem::setTexture(size_t stage, bool enabled, const TexturePtr &texPtr)
  955. {
  956. GLTexturePtr tex = std::static_pointer_cast<GLTexture>(texPtr);
  957. GLenum lastTextureType = mTextureTypes[stage];
  958. if (!activateGLTextureUnit(stage))
  959. return;
  960. if (enabled)
  961. {
  962. if (tex)
  963. {
  964. // note used
  965. mTextureTypes[stage] = tex->getGLTextureTarget();
  966. }
  967. else
  968. // assume 2D
  969. mTextureTypes[stage] = GL_TEXTURE_2D;
  970. if(lastTextureType != mTextureTypes[stage] && lastTextureType != 0)
  971. {
  972. if (stage < mFixedFunctionTextureUnits)
  973. {
  974. glDisable( lastTextureType );
  975. }
  976. }
  977. if (stage < mFixedFunctionTextureUnits)
  978. {
  979. glEnable( mTextureTypes[stage] );
  980. }
  981. if(tex)
  982. glBindTexture( mTextureTypes[stage], tex->getGLID() );
  983. else
  984. {
  985. glBindTexture( mTextureTypes[stage], static_cast<GLTextureManager*>(&TextureManager::instance())->getWarningTextureID() );
  986. }
  987. }
  988. else
  989. {
  990. if (stage < mFixedFunctionTextureUnits)
  991. {
  992. if (lastTextureType != 0)
  993. {
  994. glDisable( mTextureTypes[stage] );
  995. }
  996. glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
  997. }
  998. // bind zero texture
  999. glBindTexture(GL_TEXTURE_2D, 0);
  1000. }
  1001. activateGLTextureUnit(0);
  1002. }
  1003. //-----------------------------------------------------------------------------
  1004. GLint GLRenderSystem::getTextureAddressingMode(
  1005. SamplerState::TextureAddressingMode tam) const
  1006. {
  1007. switch(tam)
  1008. {
  1009. default:
  1010. case SamplerState::TAM_WRAP:
  1011. return GL_REPEAT;
  1012. case SamplerState::TAM_MIRROR:
  1013. return GL_MIRRORED_REPEAT;
  1014. case SamplerState::TAM_CLAMP:
  1015. return GL_CLAMP_TO_EDGE;
  1016. case SamplerState::TAM_BORDER:
  1017. return GL_CLAMP_TO_BORDER;
  1018. }
  1019. }
  1020. //-----------------------------------------------------------------------------
  1021. void GLRenderSystem::setTextureAddressingMode(size_t stage, const SamplerState::UVWAddressingMode& uvw)
  1022. {
  1023. if (!activateGLTextureUnit(stage))
  1024. return;
  1025. glTexParameteri( mTextureTypes[stage], GL_TEXTURE_WRAP_S,
  1026. getTextureAddressingMode(uvw.u));
  1027. glTexParameteri( mTextureTypes[stage], GL_TEXTURE_WRAP_T,
  1028. getTextureAddressingMode(uvw.v));
  1029. glTexParameteri( mTextureTypes[stage], GL_TEXTURE_WRAP_R,
  1030. getTextureAddressingMode(uvw.w));
  1031. activateGLTextureUnit(0);
  1032. }
  1033. //-----------------------------------------------------------------------------
  1034. void GLRenderSystem::setTextureBorderColor(size_t stage, const Color& colour)
  1035. {
  1036. GLfloat border[4] = { colour.r, colour.g, colour.b, colour.a };
  1037. if (activateGLTextureUnit(stage))
  1038. {
  1039. glTexParameterfv( mTextureTypes[stage], GL_TEXTURE_BORDER_COLOR, border);
  1040. activateGLTextureUnit(0);
  1041. }
  1042. }
  1043. //-----------------------------------------------------------------------------
  1044. void GLRenderSystem::setTextureMipmapBias(size_t stage, float bias)
  1045. {
  1046. if (mCurrentCapabilities->hasCapability(RSC_MIPMAP_LOD_BIAS))
  1047. {
  1048. if (activateGLTextureUnit(stage))
  1049. {
  1050. glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, bias);
  1051. activateGLTextureUnit(0);
  1052. }
  1053. }
  1054. }
  1055. //-----------------------------------------------------------------------------
  1056. GLint GLRenderSystem::getBlendMode(SceneBlendFactor ogreBlend) const
  1057. {
  1058. switch(ogreBlend)
  1059. {
  1060. case SBF_ONE:
  1061. return GL_ONE;
  1062. case SBF_ZERO:
  1063. return GL_ZERO;
  1064. case SBF_DEST_COLOUR:
  1065. return GL_DST_COLOR;
  1066. case SBF_SOURCE_COLOUR:
  1067. return GL_SRC_COLOR;
  1068. case SBF_ONE_MINUS_DEST_COLOUR:
  1069. return GL_ONE_MINUS_DST_COLOR;
  1070. case SBF_ONE_MINUS_SOURCE_COLOUR:
  1071. return GL_ONE_MINUS_SRC_COLOR;
  1072. case SBF_DEST_ALPHA:
  1073. return GL_DST_ALPHA;
  1074. case SBF_SOURCE_ALPHA:
  1075. return GL_SRC_ALPHA;
  1076. case SBF_ONE_MINUS_DEST_ALPHA:
  1077. return GL_ONE_MINUS_DST_ALPHA;
  1078. case SBF_ONE_MINUS_SOURCE_ALPHA:
  1079. return GL_ONE_MINUS_SRC_ALPHA;
  1080. };
  1081. // to keep compiler happy
  1082. return GL_ONE;
  1083. }
  1084. void GLRenderSystem::setSceneBlending(SceneBlendFactor sourceFactor, SceneBlendFactor destFactor, SceneBlendOperation op )
  1085. {
  1086. GLint sourceBlend = getBlendMode(sourceFactor);
  1087. GLint destBlend = getBlendMode(destFactor);
  1088. if(sourceFactor == SBF_ONE && destFactor == SBF_ZERO)
  1089. {
  1090. glDisable(GL_BLEND);
  1091. }
  1092. else
  1093. {
  1094. glEnable(GL_BLEND);
  1095. glBlendFunc(sourceBlend, destBlend);
  1096. }
  1097. GLint func = GL_FUNC_ADD;
  1098. switch(op)
  1099. {
  1100. case SBO_ADD:
  1101. func = GL_FUNC_ADD;
  1102. break;
  1103. case SBO_SUBTRACT:
  1104. func = GL_FUNC_SUBTRACT;
  1105. break;
  1106. case SBO_REVERSE_SUBTRACT:
  1107. func = GL_FUNC_REVERSE_SUBTRACT;
  1108. break;
  1109. case SBO_MIN:
  1110. func = GL_MIN;
  1111. break;
  1112. case SBO_MAX:
  1113. func = GL_MAX;
  1114. break;
  1115. }
  1116. if(GLEW_VERSION_1_4 || GLEW_ARB_imaging)
  1117. {
  1118. glBlendEquation(func);
  1119. }
  1120. else if(GLEW_EXT_blend_minmax && (func == GL_MIN || func == GL_MAX))
  1121. {
  1122. glBlendEquationEXT(func);
  1123. }
  1124. }
  1125. //-----------------------------------------------------------------------------
  1126. void GLRenderSystem::setSeparateSceneBlending(
  1127. SceneBlendFactor sourceFactor, SceneBlendFactor destFactor,
  1128. SceneBlendFactor sourceFactorAlpha, SceneBlendFactor destFactorAlpha,
  1129. SceneBlendOperation op, SceneBlendOperation alphaOp )
  1130. {
  1131. GLint sourceBlend = getBlendMode(sourceFactor);
  1132. GLint destBlend = getBlendMode(destFactor);
  1133. GLint sourceBlendAlpha = getBlendMode(sourceFactorAlpha);
  1134. GLint destBlendAlpha = getBlendMode(destFactorAlpha);
  1135. if(sourceFactor == SBF_ONE && destFactor == SBF_ZERO &&
  1136. sourceFactorAlpha == SBF_ONE && destFactorAlpha == SBF_ZERO)
  1137. {
  1138. glDisable(GL_BLEND);
  1139. }
  1140. else
  1141. {
  1142. glEnable(GL_BLEND);
  1143. glBlendFuncSeparate(sourceBlend, destBlend, sourceBlendAlpha, destBlendAlpha);
  1144. }
  1145. GLint func = GL_FUNC_ADD, alphaFunc = GL_FUNC_ADD;
  1146. switch(op)
  1147. {
  1148. case SBO_ADD:
  1149. func = GL_FUNC_ADD;
  1150. break;
  1151. case SBO_SUBTRACT:
  1152. func = GL_FUNC_SUBTRACT;
  1153. break;
  1154. case SBO_REVERSE_SUBTRACT:
  1155. func = GL_FUNC_REVERSE_SUBTRACT;
  1156. break;
  1157. case SBO_MIN:
  1158. func = GL_MIN;
  1159. break;
  1160. case SBO_MAX:
  1161. func = GL_MAX;
  1162. break;
  1163. }
  1164. switch(alphaOp)
  1165. {
  1166. case SBO_ADD:
  1167. alphaFunc = GL_FUNC_ADD;
  1168. break;
  1169. case SBO_SUBTRACT:
  1170. alphaFunc = GL_FUNC_SUBTRACT;
  1171. break;
  1172. case SBO_REVERSE_SUBTRACT:
  1173. alphaFunc = GL_FUNC_REVERSE_SUBTRACT;
  1174. break;
  1175. case SBO_MIN:
  1176. alphaFunc = GL_MIN;
  1177. break;
  1178. case SBO_MAX:
  1179. alphaFunc = GL_MAX;
  1180. break;
  1181. }
  1182. if(GLEW_VERSION_2_0) {
  1183. glBlendEquationSeparate(func, alphaFunc);
  1184. }
  1185. else if(GLEW_EXT_blend_equation_separate) {
  1186. glBlendEquationSeparateEXT(func, alphaFunc);
  1187. }
  1188. }
  1189. //-----------------------------------------------------------------------------
  1190. void GLRenderSystem::setAlphaRejectSettings(CompareFunction func, unsigned char value, bool alphaToCoverage)
  1191. {
  1192. bool a2c = false;
  1193. static bool lasta2c = false;
  1194. if(func == CMPF_ALWAYS_PASS)
  1195. {
  1196. glDisable(GL_ALPHA_TEST);
  1197. }
  1198. else
  1199. {
  1200. glEnable(GL_ALPHA_TEST);
  1201. a2c = alphaToCoverage;
  1202. glAlphaFunc(convertCompareFunction(func), value / 255.0f);
  1203. }
  1204. if (a2c != lasta2c && getCapabilities()->hasCapability(RSC_ALPHA_TO_COVERAGE))
  1205. {
  1206. if (a2c)
  1207. glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE);
  1208. else
  1209. glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE);
  1210. lasta2c = a2c;
  1211. }
  1212. }
  1213. //-----------------------------------------------------------------------------
  1214. void GLRenderSystem::setViewport(Viewport *vp)
  1215. {
  1216. // Check if viewport is different
  1217. if (vp != mActiveViewport)
  1218. {
  1219. RenderTarget* target;
  1220. target = vp->getTarget();
  1221. setRenderTarget(target);
  1222. mActiveViewport = vp;
  1223. GLsizei x, y, w, h;
  1224. // Calculate the "lower-left" corner of the viewport
  1225. w = vp->getActualWidth();
  1226. h = vp->getActualHeight();
  1227. x = vp->getActualLeft();
  1228. y = vp->getActualTop();
  1229. if (!target->requiresTextureFlipping())
  1230. {
  1231. // Convert "upper-left" corner to "lower-left"
  1232. y = target->getHeight() - h - y;
  1233. }
  1234. glViewport(x, y, w, h);
  1235. // Configure the viewport clipping
  1236. glScissor(x, y, w, h);
  1237. }
  1238. }
  1239. void GLRenderSystem::setLights()
  1240. {
  1241. // TODO PORT - I'm not using fixed pipeline lights. Remove this later
  1242. //for (size_t i = 0; i < MAX_LIGHTS; ++i)
  1243. //{
  1244. // if (mLights[i] != NULL)
  1245. // {
  1246. // Light* lt = mLights[i];
  1247. // setGLLightPositionDirection(lt, GL_LIGHT0 + i);
  1248. // }
  1249. //}
  1250. }
  1251. //-----------------------------------------------------------------------------
  1252. void GLRenderSystem::beginFrame(void)
  1253. {
  1254. if (!mActiveViewport)
  1255. CM_EXCEPT(InvalidStateException,
  1256. "Cannot begin frame - no viewport selected.");
  1257. // Activate the viewport clipping
  1258. glEnable(GL_SCISSOR_TEST);
  1259. }
  1260. //-----------------------------------------------------------------------------
  1261. void GLRenderSystem::endFrame(void)
  1262. {
  1263. // Deactivate the viewport clipping.
  1264. glDisable(GL_SCISSOR_TEST);
  1265. // unbind GPU programs at end of frame
  1266. // this is mostly to avoid holding bound programs that might get deleted
  1267. // outside via the resource manager
  1268. unbindGpuProgram(GPT_VERTEX_PROGRAM);
  1269. unbindGpuProgram(GPT_FRAGMENT_PROGRAM);
  1270. }
  1271. //-----------------------------------------------------------------------------
  1272. void GLRenderSystem::setCullingMode(CullingMode mode)
  1273. {
  1274. mCullingMode = mode;
  1275. // NB: Because two-sided stencil API dependence of the front face, we must
  1276. // use the same 'winding' for the front face everywhere. As the OGRE default
  1277. // culling mode is clockwise, we also treat anticlockwise winding as front
  1278. // face for consistently. On the assumption that, we can't change the front
  1279. // face by glFrontFace anywhere.
  1280. GLenum cullMode;
  1281. switch( mode )
  1282. {
  1283. case CULL_NONE:
  1284. glDisable( GL_CULL_FACE );
  1285. return;
  1286. default:
  1287. case CULL_CLOCKWISE:
  1288. if (mActiveRenderTarget &&
  1289. ((mActiveRenderTarget->requiresTextureFlipping() && !mInvertVertexWinding) ||
  1290. (!mActiveRenderTarget->requiresTextureFlipping() && mInvertVertexWinding)))
  1291. {
  1292. cullMode = GL_FRONT;
  1293. }
  1294. else
  1295. {
  1296. cullMode = GL_BACK;
  1297. }
  1298. break;
  1299. case CULL_ANTICLOCKWISE:
  1300. if (mActiveRenderTarget &&
  1301. ((mActiveRenderTarget->requiresTextureFlipping() && !mInvertVertexWinding) ||
  1302. (!mActiveRenderTarget->requiresTextureFlipping() && mInvertVertexWinding)))
  1303. {
  1304. cullMode = GL_BACK;
  1305. }
  1306. else
  1307. {
  1308. cullMode = GL_FRONT;
  1309. }
  1310. break;
  1311. }
  1312. glEnable( GL_CULL_FACE );
  1313. glCullFace( cullMode );
  1314. }
  1315. //-----------------------------------------------------------------------------
  1316. void GLRenderSystem::setDepthBufferParams(bool depthTest, bool depthWrite, CompareFunction depthFunction)
  1317. {
  1318. setDepthBufferCheckEnabled(depthTest);
  1319. setDepthBufferWriteEnabled(depthWrite);
  1320. setDepthBufferFunction(depthFunction);
  1321. }
  1322. //-----------------------------------------------------------------------------
  1323. void GLRenderSystem::setDepthBufferCheckEnabled(bool enabled)
  1324. {
  1325. if (enabled)
  1326. {
  1327. glClearDepth(1.0f);
  1328. glEnable(GL_DEPTH_TEST);
  1329. }
  1330. else
  1331. {
  1332. glDisable(GL_DEPTH_TEST);
  1333. }
  1334. }
  1335. //-----------------------------------------------------------------------------
  1336. void GLRenderSystem::setDepthBufferWriteEnabled(bool enabled)
  1337. {
  1338. GLboolean flag = enabled ? GL_TRUE : GL_FALSE;
  1339. glDepthMask( flag );
  1340. // Store for reference in _beginFrame
  1341. mDepthWrite = enabled;
  1342. }
  1343. //-----------------------------------------------------------------------------
  1344. void GLRenderSystem::setDepthBufferFunction(CompareFunction func)
  1345. {
  1346. glDepthFunc(convertCompareFunction(func));
  1347. }
  1348. //-----------------------------------------------------------------------------
  1349. void GLRenderSystem::setDepthBias(float constantBias, float slopeScaleBias)
  1350. {
  1351. if (constantBias != 0 || slopeScaleBias != 0)
  1352. {
  1353. glEnable(GL_POLYGON_OFFSET_FILL);
  1354. glEnable(GL_POLYGON_OFFSET_POINT);
  1355. glEnable(GL_POLYGON_OFFSET_LINE);
  1356. glPolygonOffset(-slopeScaleBias, -constantBias);
  1357. }
  1358. else
  1359. {
  1360. glDisable(GL_POLYGON_OFFSET_FILL);
  1361. glDisable(GL_POLYGON_OFFSET_POINT);
  1362. glDisable(GL_POLYGON_OFFSET_LINE);
  1363. }
  1364. }
  1365. //-----------------------------------------------------------------------------
  1366. void GLRenderSystem::setColorBufferWriteEnabled(bool red, bool green, bool blue, bool alpha)
  1367. {
  1368. glColorMask(red, green, blue, alpha);
  1369. // record this
  1370. mColourWrite[0] = red;
  1371. mColourWrite[1] = blue;
  1372. mColourWrite[2] = green;
  1373. mColourWrite[3] = alpha;
  1374. }
  1375. //-----------------------------------------------------------------------------
  1376. String GLRenderSystem::getErrorDescription(long errCode) const
  1377. {
  1378. const GLubyte *errString = gluErrorString (errCode);
  1379. return (errString != 0) ? String((const char*) errString) : StringUtil::BLANK;
  1380. }
  1381. VertexElementType GLRenderSystem::getColorVertexElementType(void) const
  1382. {
  1383. return VET_COLOUR_ABGR;
  1384. }
  1385. void GLRenderSystem::_convertProjectionMatrix(const Matrix4& matrix,
  1386. Matrix4& dest, bool forGpuProgram)
  1387. {
  1388. // no any conversion request for OpenGL
  1389. dest = matrix;
  1390. }
  1391. //---------------------------------------------------------------------
  1392. void GLRenderSystem::setPolygonMode(PolygonMode level)
  1393. {
  1394. GLenum glmode;
  1395. switch(level)
  1396. {
  1397. case PM_POINTS:
  1398. glmode = GL_POINT;
  1399. break;
  1400. case PM_WIREFRAME:
  1401. glmode = GL_LINE;
  1402. break;
  1403. default:
  1404. case PM_SOLID:
  1405. glmode = GL_FILL;
  1406. break;
  1407. }
  1408. glPolygonMode(GL_FRONT_AND_BACK, glmode);
  1409. }
  1410. //---------------------------------------------------------------------
  1411. void GLRenderSystem::setStencilCheckEnabled(bool enabled)
  1412. {
  1413. if (enabled)
  1414. {
  1415. glEnable(GL_STENCIL_TEST);
  1416. }
  1417. else
  1418. {
  1419. glDisable(GL_STENCIL_TEST);
  1420. }
  1421. }
  1422. //---------------------------------------------------------------------
  1423. void GLRenderSystem::setStencilBufferParams(CompareFunction func,
  1424. UINT32 refValue, UINT32 mask, StencilOperation stencilFailOp,
  1425. StencilOperation depthFailOp, StencilOperation passOp,
  1426. bool twoSidedOperation)
  1427. {
  1428. bool flip;
  1429. mStencilMask = mask;
  1430. if (twoSidedOperation)
  1431. {
  1432. if (!mCurrentCapabilities->hasCapability(RSC_TWO_SIDED_STENCIL))
  1433. CM_EXCEPT(InvalidParametersException, "2-sided stencils are not supported");
  1434. // NB: We should always treat CCW as front face for consistent with default
  1435. // culling mode. Therefore, we must take care with two-sided stencil settings.
  1436. flip = (mInvertVertexWinding && !mActiveRenderTarget->requiresTextureFlipping()) ||
  1437. (!mInvertVertexWinding && mActiveRenderTarget->requiresTextureFlipping());
  1438. if(GLEW_VERSION_2_0) // New GL2 commands
  1439. {
  1440. // Back
  1441. glStencilMaskSeparate(GL_BACK, mask);
  1442. glStencilFuncSeparate(GL_BACK, convertCompareFunction(func), refValue, mask);
  1443. glStencilOpSeparate(GL_BACK,
  1444. convertStencilOp(stencilFailOp, !flip),
  1445. convertStencilOp(depthFailOp, !flip),
  1446. convertStencilOp(passOp, !flip));
  1447. // Front
  1448. glStencilMaskSeparate(GL_FRONT, mask);
  1449. glStencilFuncSeparate(GL_FRONT, convertCompareFunction(func), refValue, mask);
  1450. glStencilOpSeparate(GL_FRONT,
  1451. convertStencilOp(stencilFailOp, flip),
  1452. convertStencilOp(depthFailOp, flip),
  1453. convertStencilOp(passOp, flip));
  1454. }
  1455. else // EXT_stencil_two_side
  1456. {
  1457. glEnable(GL_STENCIL_TEST_TWO_SIDE_EXT);
  1458. // Back
  1459. glActiveStencilFaceEXT(GL_BACK);
  1460. glStencilMask(mask);
  1461. glStencilFunc(convertCompareFunction(func), refValue, mask);
  1462. glStencilOp(
  1463. convertStencilOp(stencilFailOp, !flip),
  1464. convertStencilOp(depthFailOp, !flip),
  1465. convertStencilOp(passOp, !flip));
  1466. // Front
  1467. glActiveStencilFaceEXT(GL_FRONT);
  1468. glStencilMask(mask);
  1469. glStencilFunc(convertCompareFunction(func), refValue, mask);
  1470. glStencilOp(
  1471. convertStencilOp(stencilFailOp, flip),
  1472. convertStencilOp(depthFailOp, flip),
  1473. convertStencilOp(passOp, flip));
  1474. }
  1475. }
  1476. else
  1477. {
  1478. if(!GLEW_VERSION_2_0)
  1479. glDisable(GL_STENCIL_TEST_TWO_SIDE_EXT);
  1480. flip = false;
  1481. glStencilMask(mask);
  1482. glStencilFunc(convertCompareFunction(func), refValue, mask);
  1483. glStencilOp(
  1484. convertStencilOp(stencilFailOp, flip),
  1485. convertStencilOp(depthFailOp, flip),
  1486. convertStencilOp(passOp, flip));
  1487. }
  1488. }
  1489. //---------------------------------------------------------------------
  1490. GLint GLRenderSystem::convertCompareFunction(CompareFunction func) const
  1491. {
  1492. switch(func)
  1493. {
  1494. case CMPF_ALWAYS_FAIL:
  1495. return GL_NEVER;
  1496. case CMPF_ALWAYS_PASS:
  1497. return GL_ALWAYS;
  1498. case CMPF_LESS:
  1499. return GL_LESS;
  1500. case CMPF_LESS_EQUAL:
  1501. return GL_LEQUAL;
  1502. case CMPF_EQUAL:
  1503. return GL_EQUAL;
  1504. case CMPF_NOT_EQUAL:
  1505. return GL_NOTEQUAL;
  1506. case CMPF_GREATER_EQUAL:
  1507. return GL_GEQUAL;
  1508. case CMPF_GREATER:
  1509. return GL_GREATER;
  1510. };
  1511. // to keep compiler happy
  1512. return GL_ALWAYS;
  1513. }
  1514. //---------------------------------------------------------------------
  1515. GLint GLRenderSystem::convertStencilOp(StencilOperation op, bool invert) const
  1516. {
  1517. switch(op)
  1518. {
  1519. case SOP_KEEP:
  1520. return GL_KEEP;
  1521. case SOP_ZERO:
  1522. return GL_ZERO;
  1523. case SOP_REPLACE:
  1524. return GL_REPLACE;
  1525. case SOP_INCREMENT:
  1526. return invert ? GL_DECR : GL_INCR;
  1527. case SOP_DECREMENT:
  1528. return invert ? GL_INCR : GL_DECR;
  1529. case SOP_INCREMENT_WRAP:
  1530. return invert ? GL_DECR_WRAP_EXT : GL_INCR_WRAP_EXT;
  1531. case SOP_DECREMENT_WRAP:
  1532. return invert ? GL_INCR_WRAP_EXT : GL_DECR_WRAP_EXT;
  1533. case SOP_INVERT:
  1534. return GL_INVERT;
  1535. };
  1536. // to keep compiler happy
  1537. return SOP_KEEP;
  1538. }
  1539. //---------------------------------------------------------------------
  1540. GLuint GLRenderSystem::getCombinedMinMipFilter(void) const
  1541. {
  1542. switch(mMinFilter)
  1543. {
  1544. case FO_ANISOTROPIC:
  1545. case FO_LINEAR:
  1546. switch(mMipFilter)
  1547. {
  1548. case FO_ANISOTROPIC:
  1549. case FO_LINEAR:
  1550. // linear min, linear mip
  1551. return GL_LINEAR_MIPMAP_LINEAR;
  1552. case FO_POINT:
  1553. // linear min, point mip
  1554. return GL_LINEAR_MIPMAP_NEAREST;
  1555. case FO_NONE:
  1556. // linear min, no mip
  1557. return GL_LINEAR;
  1558. }
  1559. break;
  1560. case FO_POINT:
  1561. case FO_NONE:
  1562. switch(mMipFilter)
  1563. {
  1564. case FO_ANISOTROPIC:
  1565. case FO_LINEAR:
  1566. // nearest min, linear mip
  1567. return GL_NEAREST_MIPMAP_LINEAR;
  1568. case FO_POINT:
  1569. // nearest min, point mip
  1570. return GL_NEAREST_MIPMAP_NEAREST;
  1571. case FO_NONE:
  1572. // nearest min, no mip
  1573. return GL_NEAREST;
  1574. }
  1575. break;
  1576. }
  1577. // should never get here
  1578. return 0;
  1579. }
  1580. //---------------------------------------------------------------------
  1581. void GLRenderSystem::setTextureFiltering(size_t unit,
  1582. FilterType ftype, FilterOptions fo)
  1583. {
  1584. if (!activateGLTextureUnit(unit))
  1585. return;
  1586. switch(ftype)
  1587. {
  1588. case FT_MIN:
  1589. mMinFilter = fo;
  1590. // Combine with existing mip filter
  1591. glTexParameteri(
  1592. mTextureTypes[unit],
  1593. GL_TEXTURE_MIN_FILTER,
  1594. getCombinedMinMipFilter());
  1595. break;
  1596. case FT_MAG:
  1597. switch (fo)
  1598. {
  1599. case FO_ANISOTROPIC: // GL treats linear and aniso the same
  1600. case FO_LINEAR:
  1601. glTexParameteri(
  1602. mTextureTypes[unit],
  1603. GL_TEXTURE_MAG_FILTER,
  1604. GL_LINEAR);
  1605. break;
  1606. case FO_POINT:
  1607. case FO_NONE:
  1608. glTexParameteri(
  1609. mTextureTypes[unit],
  1610. GL_TEXTURE_MAG_FILTER,
  1611. GL_NEAREST);
  1612. break;
  1613. }
  1614. break;
  1615. case FT_MIP:
  1616. mMipFilter = fo;
  1617. // Combine with existing min filter
  1618. glTexParameteri(
  1619. mTextureTypes[unit],
  1620. GL_TEXTURE_MIN_FILTER,
  1621. getCombinedMinMipFilter());
  1622. break;
  1623. }
  1624. activateGLTextureUnit(0);
  1625. }
  1626. //---------------------------------------------------------------------
  1627. GLfloat GLRenderSystem::_getCurrentAnisotropy(size_t unit)
  1628. {
  1629. GLfloat curAniso = 0;
  1630. glGetTexParameterfv(mTextureTypes[unit],
  1631. GL_TEXTURE_MAX_ANISOTROPY_EXT, &curAniso);
  1632. return curAniso ? curAniso : 1;
  1633. }
  1634. //---------------------------------------------------------------------
  1635. void GLRenderSystem::setTextureAnisotropy(size_t unit, unsigned int maxAnisotropy)
  1636. {
  1637. if (!mCurrentCapabilities->hasCapability(RSC_ANISOTROPY))
  1638. return;
  1639. if (!activateGLTextureUnit(unit))
  1640. return;
  1641. GLfloat largest_supported_anisotropy = 0;
  1642. glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &largest_supported_anisotropy);
  1643. if (maxAnisotropy > largest_supported_anisotropy)
  1644. maxAnisotropy = largest_supported_anisotropy ?
  1645. static_cast<UINT32>(largest_supported_anisotropy) : 1;
  1646. if (_getCurrentAnisotropy(unit) != maxAnisotropy)
  1647. glTexParameterf(mTextureTypes[unit], GL_TEXTURE_MAX_ANISOTROPY_EXT, (float)maxAnisotropy);
  1648. activateGLTextureUnit(0);
  1649. }
  1650. //---------------------------------------------------------------------
  1651. void GLRenderSystem::setVertexDeclaration(VertexDeclarationPtr decl)
  1652. {
  1653. }
  1654. //---------------------------------------------------------------------
  1655. void GLRenderSystem::setVertexBufferBinding(VertexBufferBinding* binding)
  1656. {
  1657. }
  1658. //---------------------------------------------------------------------
  1659. void GLRenderSystem::render(const RenderOperation& op)
  1660. {
  1661. // Call super class
  1662. RenderSystem::render(op);
  1663. void* pBufferData = 0;
  1664. bool multitexturing = (getCapabilities()->getNumTextureUnits() > 1);
  1665. const VertexDeclaration::VertexElementList& decl =
  1666. op.vertexData->vertexDeclaration->getElements();
  1667. VertexDeclaration::VertexElementList::const_iterator elem, elemEnd;
  1668. elemEnd = decl.end();
  1669. vector<GLuint>::type attribsBound;
  1670. for (elem = decl.begin(); elem != elemEnd; ++elem)
  1671. {
  1672. if (!op.vertexData->vertexBufferBinding->isBufferBound(elem->getSource()))
  1673. continue; // skip unbound elements
  1674. HardwareVertexBufferPtr vertexBuffer =
  1675. op.vertexData->vertexBufferBinding->getBuffer(elem->getSource());
  1676. if(mCurrentCapabilities->hasCapability(RSC_VBO))
  1677. {
  1678. glBindBufferARB(GL_ARRAY_BUFFER_ARB,
  1679. static_cast<const GLHardwareVertexBuffer*>(vertexBuffer.get())->getGLBufferId());
  1680. pBufferData = VBO_BUFFER_OFFSET(elem->getOffset());
  1681. }
  1682. else
  1683. {
  1684. pBufferData = static_cast<const GLDefaultHardwareVertexBuffer*>(vertexBuffer.get())->getDataPtr(elem->getOffset());
  1685. }
  1686. if (op.vertexData->vertexStart)
  1687. {
  1688. pBufferData = static_cast<char*>(pBufferData) + op.vertexData->vertexStart * vertexBuffer->getVertexSize();
  1689. }
  1690. unsigned int i = 0;
  1691. VertexElementSemantic sem = elem->getSemantic();
  1692. bool isCustomAttrib = false;
  1693. if (mCurrentVertexProgram)
  1694. isCustomAttrib = mCurrentVertexProgram->isAttributeValid(sem, elem->getIndex());
  1695. // Custom attribute support
  1696. // tangents, binormals, blendweights etc always via this route
  1697. // builtins may be done this way too
  1698. if (isCustomAttrib)
  1699. {
  1700. GLint attrib = mCurrentVertexProgram->getAttributeIndex(sem, elem->getIndex());
  1701. unsigned short typeCount = VertexElement::getTypeCount(elem->getType());
  1702. GLboolean normalised = GL_FALSE;
  1703. switch(elem->getType())
  1704. {
  1705. case VET_COLOUR:
  1706. case VET_COLOUR_ABGR:
  1707. case VET_COLOUR_ARGB:
  1708. // Because GL takes these as a sequence of single unsigned bytes, count needs to be 4
  1709. // VertexElement::getTypeCount treats them as 1 (RGBA)
  1710. // Also need to normalise the fixed-point data
  1711. typeCount = 4;
  1712. normalised = GL_TRUE;
  1713. break;
  1714. default:
  1715. break;
  1716. };
  1717. glVertexAttribPointerARB(
  1718. attrib,
  1719. typeCount,
  1720. GLHardwareBufferManager::getGLType(elem->getType()),
  1721. normalised,
  1722. static_cast<GLsizei>(vertexBuffer->getVertexSize()),
  1723. pBufferData);
  1724. glEnableVertexAttribArrayARB(attrib);
  1725. attribsBound.push_back(attrib);
  1726. }
  1727. else
  1728. {
  1729. // fixed-function & builtin attribute support
  1730. switch(sem)
  1731. {
  1732. case VES_POSITION:
  1733. glVertexPointer(VertexElement::getTypeCount(
  1734. elem->getType()),
  1735. GLHardwareBufferManager::getGLType(elem->getType()),
  1736. static_cast<GLsizei>(vertexBuffer->getVertexSize()),
  1737. pBufferData);
  1738. glEnableClientState( GL_VERTEX_ARRAY );
  1739. break;
  1740. case VES_NORMAL:
  1741. glNormalPointer(
  1742. GLHardwareBufferManager::getGLType(elem->getType()),
  1743. static_cast<GLsizei>(vertexBuffer->getVertexSize()),
  1744. pBufferData);
  1745. glEnableClientState( GL_NORMAL_ARRAY );
  1746. break;
  1747. case VES_DIFFUSE:
  1748. glColorPointer(4,
  1749. GLHardwareBufferManager::getGLType(elem->getType()),
  1750. static_cast<GLsizei>(vertexBuffer->getVertexSize()),
  1751. pBufferData);
  1752. glEnableClientState( GL_COLOR_ARRAY );
  1753. break;
  1754. case VES_SPECULAR:
  1755. if (GLEW_EXT_secondary_color)
  1756. {
  1757. glSecondaryColorPointerEXT(4,
  1758. GLHardwareBufferManager::getGLType(elem->getType()),
  1759. static_cast<GLsizei>(vertexBuffer->getVertexSize()),
  1760. pBufferData);
  1761. glEnableClientState( GL_SECONDARY_COLOR_ARRAY );
  1762. }
  1763. break;
  1764. case VES_TEXTURE_COORDINATES:
  1765. if (mCurrentVertexProgram)
  1766. {
  1767. // Programmable pipeline - direct UV assignment
  1768. glClientActiveTextureARB(GL_TEXTURE0 + elem->getIndex());
  1769. glTexCoordPointer(
  1770. VertexElement::getTypeCount(elem->getType()),
  1771. GLHardwareBufferManager::getGLType(elem->getType()),
  1772. static_cast<GLsizei>(vertexBuffer->getVertexSize()),
  1773. pBufferData);
  1774. glEnableClientState( GL_TEXTURE_COORD_ARRAY );
  1775. }
  1776. else
  1777. {
  1778. // fixed function matching to units based on tex_coord_set
  1779. for (i = 0; i < mDisabledTexUnitsFrom; i++)
  1780. {
  1781. // Only set this texture unit's texcoord pointer if it
  1782. // is supposed to be using this element's index
  1783. if (mTextureCoordIndex[i] == elem->getIndex() && i < mFixedFunctionTextureUnits)
  1784. {
  1785. if (multitexturing)
  1786. glClientActiveTextureARB(GL_TEXTURE0 + i);
  1787. glTexCoordPointer(
  1788. VertexElement::getTypeCount(elem->getType()),
  1789. GLHardwareBufferManager::getGLType(elem->getType()),
  1790. static_cast<GLsizei>(vertexBuffer->getVertexSize()),
  1791. pBufferData);
  1792. glEnableClientState( GL_TEXTURE_COORD_ARRAY );
  1793. }
  1794. }
  1795. }
  1796. break;
  1797. default:
  1798. break;
  1799. };
  1800. } // isCustomAttrib
  1801. }
  1802. if (multitexturing)
  1803. glClientActiveTextureARB(GL_TEXTURE0);
  1804. // Find the correct type to render
  1805. GLint primType;
  1806. //Use adjacency if there is a geometry program and it requested adjacency info
  1807. bool useAdjacency = (mGeometryProgramBound && mCurrentGeometryProgram->isAdjacencyInfoRequired());
  1808. switch (op.operationType)
  1809. {
  1810. case RenderOperation::OT_POINT_LIST:
  1811. primType = GL_POINTS;
  1812. break;
  1813. case RenderOperation::OT_LINE_LIST:
  1814. primType = useAdjacency ? GL_LINES_ADJACENCY_EXT : GL_LINES;
  1815. break;
  1816. case RenderOperation::OT_LINE_STRIP:
  1817. primType = useAdjacency ? GL_LINE_STRIP_ADJACENCY_EXT : GL_LINE_STRIP;
  1818. break;
  1819. default:
  1820. case RenderOperation::OT_TRIANGLE_LIST:
  1821. primType = useAdjacency ? GL_TRIANGLES_ADJACENCY_EXT : GL_TRIANGLES;
  1822. break;
  1823. case RenderOperation::OT_TRIANGLE_STRIP:
  1824. primType = useAdjacency ? GL_TRIANGLE_STRIP_ADJACENCY_EXT : GL_TRIANGLE_STRIP;
  1825. break;
  1826. case RenderOperation::OT_TRIANGLE_FAN:
  1827. primType = GL_TRIANGLE_FAN;
  1828. break;
  1829. }
  1830. if (op.useIndexes)
  1831. {
  1832. if(mCurrentCapabilities->hasCapability(RSC_VBO))
  1833. {
  1834. glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB,
  1835. static_cast<GLHardwareIndexBuffer*>(
  1836. op.indexData->indexBuffer.get())->getGLBufferId());
  1837. pBufferData = VBO_BUFFER_OFFSET(
  1838. op.indexData->indexStart * op.indexData->indexBuffer->getIndexSize());
  1839. }
  1840. else
  1841. {
  1842. pBufferData = static_cast<GLDefaultHardwareIndexBuffer*>(
  1843. op.indexData->indexBuffer.get())->getDataPtr(
  1844. op.indexData->indexStart * op.indexData->indexBuffer->getIndexSize());
  1845. }
  1846. GLenum indexType = (op.indexData->indexBuffer->getType() == HardwareIndexBuffer::IT_16BIT) ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT;
  1847. glDrawElements(primType, op.indexData->indexCount, indexType, pBufferData);
  1848. }
  1849. else
  1850. {
  1851. glDrawArrays(primType, 0, op.vertexData->vertexCount);
  1852. }
  1853. glDisableClientState( GL_VERTEX_ARRAY );
  1854. // only valid up to GL_MAX_TEXTURE_UNITS, which is recorded in mFixedFunctionTextureUnits
  1855. if (multitexturing)
  1856. {
  1857. for (int i = 0; i < mFixedFunctionTextureUnits; i++)
  1858. {
  1859. glClientActiveTextureARB(GL_TEXTURE0 + i);
  1860. glDisableClientState( GL_TEXTURE_COORD_ARRAY );
  1861. }
  1862. glClientActiveTextureARB(GL_TEXTURE0);
  1863. }
  1864. else
  1865. {
  1866. glDisableClientState( GL_TEXTURE_COORD_ARRAY );
  1867. }
  1868. glDisableClientState( GL_NORMAL_ARRAY );
  1869. glDisableClientState( GL_COLOR_ARRAY );
  1870. if (GLEW_EXT_secondary_color)
  1871. {
  1872. glDisableClientState( GL_SECONDARY_COLOR_ARRAY );
  1873. }
  1874. // unbind any custom attributes
  1875. for (vector<GLuint>::type::iterator ai = attribsBound.begin(); ai != attribsBound.end(); ++ai)
  1876. {
  1877. glDisableVertexAttribArrayARB(*ai);
  1878. }
  1879. glColor4f(1,1,1,1);
  1880. if (GLEW_EXT_secondary_color)
  1881. {
  1882. glSecondaryColor3fEXT(0.0f, 0.0f, 0.0f);
  1883. }
  1884. }
  1885. //---------------------------------------------------------------------
  1886. void GLRenderSystem::bindGpuProgram(GpuProgram* prg)
  1887. {
  1888. GLGpuProgram* glprg = static_cast<GLGpuProgram*>(prg);
  1889. // Unbind previous gpu program first.
  1890. //
  1891. // Note:
  1892. // 1. Even if both previous and current are the same object, we can't
  1893. // bypass re-bind completely since the object itself maybe modified.
  1894. // But we can bypass unbind based on the assumption that object
  1895. // internally GL program type shouldn't be changed after it has
  1896. // been created. The behavior of bind to a GL program type twice
  1897. // should be same as unbind and rebind that GL program type, even
  1898. // for difference objects.
  1899. // 2. We also assumed that the program's type (vertex or fragment) should
  1900. // not be changed during it's in using. If not, the following switch
  1901. // statement will confuse GL state completely, and we can't fix it
  1902. // here. To fix this case, we must coding the program implementation
  1903. // itself, if type is changing (during load/unload, etc), and it's inuse,
  1904. // unbind and notify render system to correct for its state.
  1905. //
  1906. switch (glprg->getType())
  1907. {
  1908. case GPT_VERTEX_PROGRAM:
  1909. if (mCurrentVertexProgram != glprg)
  1910. {
  1911. if (mCurrentVertexProgram)
  1912. mCurrentVertexProgram->unbindProgram();
  1913. mCurrentVertexProgram = glprg;
  1914. }
  1915. break;
  1916. case GPT_FRAGMENT_PROGRAM:
  1917. if (mCurrentFragmentProgram != glprg)
  1918. {
  1919. if (mCurrentFragmentProgram)
  1920. mCurrentFragmentProgram->unbindProgram();
  1921. mCurrentFragmentProgram = glprg;
  1922. }
  1923. break;
  1924. case GPT_GEOMETRY_PROGRAM:
  1925. if (mCurrentGeometryProgram != glprg)
  1926. {
  1927. if (mCurrentGeometryProgram)
  1928. mCurrentGeometryProgram->unbindProgram();
  1929. mCurrentGeometryProgram = glprg;
  1930. }
  1931. break;
  1932. }
  1933. // Bind the program
  1934. glprg->bindProgram();
  1935. RenderSystem::bindGpuProgram(prg);
  1936. }
  1937. //---------------------------------------------------------------------
  1938. void GLRenderSystem::unbindGpuProgram(GpuProgramType gptype)
  1939. {
  1940. if (gptype == GPT_VERTEX_PROGRAM && mCurrentVertexProgram)
  1941. {
  1942. mActiveVertexGpuProgramParameters = nullptr;
  1943. mCurrentVertexProgram->unbindProgram();
  1944. mCurrentVertexProgram = 0;
  1945. }
  1946. else if (gptype == GPT_GEOMETRY_PROGRAM && mCurrentGeometryProgram)
  1947. {
  1948. mActiveGeometryGpuProgramParameters = nullptr;
  1949. mCurrentGeometryProgram->unbindProgram();
  1950. mCurrentGeometryProgram = 0;
  1951. }
  1952. else if (gptype == GPT_FRAGMENT_PROGRAM && mCurrentFragmentProgram)
  1953. {
  1954. mActiveFragmentGpuProgramParameters = nullptr;
  1955. mCurrentFragmentProgram->unbindProgram();
  1956. mCurrentFragmentProgram = 0;
  1957. }
  1958. RenderSystem::unbindGpuProgram(gptype);
  1959. }
  1960. //---------------------------------------------------------------------
  1961. void GLRenderSystem::bindGpuProgramParameters(GpuProgramType gptype, GpuProgramParametersSharedPtr params, UINT16 mask)
  1962. {
  1963. // Set textures
  1964. const GpuNamedConstants& consts = params->getConstantDefinitions();
  1965. for(auto iter = consts.map.begin(); iter != consts.map.end(); ++iter)
  1966. {
  1967. const GpuConstantDefinition& def = iter->second;
  1968. if(def.variability & mask)
  1969. {
  1970. if(def.constType == GCT_SAMPLER2D || def.constType == GCT_SAMPLERCUBE || def.constType == GCT_SAMPLER1D
  1971. || def.constType == GCT_SAMPLER2DSHADOW || def.constType == GCT_SAMPLER3D || def.constType == GCT_SAMPLER1DSHADOW)
  1972. {
  1973. TextureRef curTexture = params->getTexture(def.physicalIndex);
  1974. setTexture(def.physicalIndex, true, curTexture.getInternalPtr());
  1975. const SamplerState& samplerState = params->getSamplerState(def.physicalIndex);
  1976. setTextureUnitSettings(def.physicalIndex, curTexture.getInternalPtr(), samplerState);
  1977. }
  1978. }
  1979. }
  1980. switch (gptype)
  1981. {
  1982. case GPT_VERTEX_PROGRAM:
  1983. mActiveVertexGpuProgramParameters = params;
  1984. mCurrentVertexProgram->bindProgramParameters(params, mask);
  1985. break;
  1986. case GPT_GEOMETRY_PROGRAM:
  1987. mActiveGeometryGpuProgramParameters = params;
  1988. mCurrentGeometryProgram->bindProgramParameters(params, mask);
  1989. break;
  1990. case GPT_FRAGMENT_PROGRAM:
  1991. mActiveFragmentGpuProgramParameters = params;
  1992. mCurrentFragmentProgram->bindProgramParameters(params, mask);
  1993. break;
  1994. }
  1995. }
  1996. //---------------------------------------------------------------------
  1997. void GLRenderSystem::setClipPlanesImpl(const PlaneList& clipPlanes)
  1998. {
  1999. // A note on GL user clipping:
  2000. // When an ARB vertex program is enabled in GL, user clipping is completely
  2001. // disabled. There is no way around this, it's just turned off.
  2002. // When using GLSL, user clipping can work but you have to include a
  2003. // glClipVertex command in your vertex shader.
  2004. // Thus the planes set here may not actually be respected.
  2005. size_t i = 0;
  2006. size_t numClipPlanes;
  2007. GLdouble clipPlane[4];
  2008. // Save previous modelview
  2009. glMatrixMode(GL_MODELVIEW);
  2010. glPushMatrix();
  2011. // just load view matrix (identity world)
  2012. GLfloat mat[16];
  2013. makeGLMatrix(mat, mViewMatrix);
  2014. glLoadMatrixf(mat);
  2015. numClipPlanes = clipPlanes.size();
  2016. for (i = 0; i < numClipPlanes; ++i)
  2017. {
  2018. GLenum clipPlaneId = static_cast<GLenum>(GL_CLIP_PLANE0 + i);
  2019. const Plane& plane = clipPlanes[i];
  2020. if (i >= 6/*GL_MAX_CLIP_PLANES*/)
  2021. {
  2022. CM_EXCEPT(RenderingAPIException, "Unable to set clip plane");
  2023. }
  2024. clipPlane[0] = plane.normal.x;
  2025. clipPlane[1] = plane.normal.y;
  2026. clipPlane[2] = plane.normal.z;
  2027. clipPlane[3] = plane.d;
  2028. glClipPlane(clipPlaneId, clipPlane);
  2029. glEnable(clipPlaneId);
  2030. }
  2031. // disable remaining clip planes
  2032. for ( ; i < 6/*GL_MAX_CLIP_PLANES*/; ++i)
  2033. {
  2034. glDisable(static_cast<GLenum>(GL_CLIP_PLANE0 + i));
  2035. }
  2036. // restore matrices
  2037. glPopMatrix();
  2038. }
  2039. //---------------------------------------------------------------------
  2040. void GLRenderSystem::setScissorTest(bool enabled, size_t left,
  2041. size_t top, size_t right, size_t bottom)
  2042. {
  2043. // If request texture flipping, use "upper-left", otherwise use "lower-left"
  2044. bool flipping = mActiveRenderTarget->requiresTextureFlipping();
  2045. // GL measures from the bottom, not the top
  2046. size_t targetHeight = mActiveRenderTarget->getHeight();
  2047. // Calculate the "lower-left" corner of the viewport
  2048. GLsizei x = 0, y = 0, w = 0, h = 0;
  2049. if (enabled)
  2050. {
  2051. glEnable(GL_SCISSOR_TEST);
  2052. // NB GL uses width / height rather than right / bottom
  2053. x = left;
  2054. if (flipping)
  2055. y = top;
  2056. else
  2057. y = targetHeight - bottom;
  2058. w = right - left;
  2059. h = bottom - top;
  2060. glScissor(x, y, w, h);
  2061. }
  2062. else
  2063. {
  2064. glDisable(GL_SCISSOR_TEST);
  2065. // GL requires you to reset the scissor when disabling
  2066. w = mActiveViewport->getActualWidth();
  2067. h = mActiveViewport->getActualHeight();
  2068. x = mActiveViewport->getActualLeft();
  2069. if (flipping)
  2070. y = mActiveViewport->getActualTop();
  2071. else
  2072. y = targetHeight - mActiveViewport->getActualTop() - h;
  2073. glScissor(x, y, w, h);
  2074. }
  2075. }
  2076. //---------------------------------------------------------------------
  2077. void GLRenderSystem::clearFrameBuffer(unsigned int buffers,
  2078. const Color& colour, float depth, unsigned short stencil)
  2079. {
  2080. bool colourMask = !mColourWrite[0] || !mColourWrite[1]
  2081. || !mColourWrite[2] || !mColourWrite[3];
  2082. GLbitfield flags = 0;
  2083. if (buffers & FBT_COLOUR)
  2084. {
  2085. flags |= GL_COLOR_BUFFER_BIT;
  2086. // Enable buffer for writing if it isn't
  2087. if (colourMask)
  2088. {
  2089. glColorMask(true, true, true, true);
  2090. }
  2091. glClearColor(colour.r, colour.g, colour.b, colour.a);
  2092. }
  2093. if (buffers & FBT_DEPTH)
  2094. {
  2095. flags |= GL_DEPTH_BUFFER_BIT;
  2096. // Enable buffer for writing if it isn't
  2097. if (!mDepthWrite)
  2098. {
  2099. glDepthMask( GL_TRUE );
  2100. }
  2101. glClearDepth(depth);
  2102. }
  2103. if (buffers & FBT_STENCIL)
  2104. {
  2105. flags |= GL_STENCIL_BUFFER_BIT;
  2106. // Enable buffer for writing if it isn't
  2107. glStencilMask(0xFFFFFFFF);
  2108. glClearStencil(stencil);
  2109. }
  2110. // Should be enable scissor test due the clear region is
  2111. // relied on scissor box bounds.
  2112. GLboolean scissorTestEnabled = glIsEnabled(GL_SCISSOR_TEST);
  2113. if (!scissorTestEnabled)
  2114. {
  2115. glEnable(GL_SCISSOR_TEST);
  2116. }
  2117. // Sets the scissor box as same as viewport
  2118. GLint viewport[4] = { 0, 0, 0, 0 };
  2119. GLint scissor[4] = { 0, 0, 0, 0 };
  2120. glGetIntegerv(GL_VIEWPORT, viewport);
  2121. glGetIntegerv(GL_SCISSOR_BOX, scissor);
  2122. bool scissorBoxDifference =
  2123. viewport[0] != scissor[0] || viewport[1] != scissor[1] ||
  2124. viewport[2] != scissor[2] || viewport[3] != scissor[3];
  2125. if (scissorBoxDifference)
  2126. {
  2127. glScissor(viewport[0], viewport[1], viewport[2], viewport[3]);
  2128. }
  2129. // Clear buffers
  2130. glClear(flags);
  2131. // Restore scissor box
  2132. if (scissorBoxDifference)
  2133. {
  2134. glScissor(scissor[0], scissor[1], scissor[2], scissor[3]);
  2135. }
  2136. // Restore scissor test
  2137. if (!scissorTestEnabled)
  2138. {
  2139. glDisable(GL_SCISSOR_TEST);
  2140. }
  2141. // Reset buffer write state
  2142. if (!mDepthWrite && (buffers & FBT_DEPTH))
  2143. {
  2144. glDepthMask( GL_FALSE );
  2145. }
  2146. if (colourMask && (buffers & FBT_COLOUR))
  2147. {
  2148. glColorMask(mColourWrite[0], mColourWrite[1], mColourWrite[2], mColourWrite[3]);
  2149. }
  2150. if (buffers & FBT_STENCIL)
  2151. {
  2152. glStencilMask(mStencilMask);
  2153. }
  2154. }
  2155. //---------------------------------------------------------------------
  2156. float GLRenderSystem::getHorizontalTexelOffset(void)
  2157. {
  2158. // No offset in GL
  2159. return 0.0f;
  2160. }
  2161. //---------------------------------------------------------------------
  2162. float GLRenderSystem::getVerticalTexelOffset(void)
  2163. {
  2164. // No offset in GL
  2165. return 0.0f;
  2166. }
  2167. //---------------------------------------------------------------------
  2168. void GLRenderSystem::_oneTimeContextInitialization()
  2169. {
  2170. if (GLEW_VERSION_1_2)
  2171. {
  2172. // Set nicer lighting model -- d3d9 has this by default
  2173. glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
  2174. glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, 1);
  2175. }
  2176. if (GLEW_VERSION_1_4)
  2177. {
  2178. glEnable(GL_COLOR_SUM);
  2179. glDisable(GL_DITHER);
  2180. }
  2181. // Check for FSAA
  2182. // Enable the extension if it was enabled by the GLSupport
  2183. if (mGLSupport->checkExtension("GL_ARB_multisample"))
  2184. {
  2185. int fsaa_active = false;
  2186. glGetIntegerv(GL_SAMPLE_BUFFERS_ARB,(GLint*)&fsaa_active);
  2187. if(fsaa_active)
  2188. {
  2189. glEnable(GL_MULTISAMPLE_ARB);
  2190. }
  2191. }
  2192. }
  2193. //---------------------------------------------------------------------
  2194. void GLRenderSystem::_switchContext(GLContext *context)
  2195. {
  2196. // Unbind GPU programs and rebind to new context later, because
  2197. // scene manager treat render system as ONE 'context' ONLY, and it
  2198. // cached the GPU programs using state.
  2199. if (mCurrentVertexProgram)
  2200. mCurrentVertexProgram->unbindProgram();
  2201. if (mCurrentGeometryProgram)
  2202. mCurrentGeometryProgram->unbindProgram();
  2203. if (mCurrentFragmentProgram)
  2204. mCurrentFragmentProgram->unbindProgram();
  2205. // Disable lights
  2206. mCurrentLights = 0;
  2207. // Disable textures
  2208. disableTextureUnitsFrom(0);
  2209. // It's ready for switching
  2210. if (mCurrentContext)
  2211. mCurrentContext->endCurrent();
  2212. mCurrentContext = context;
  2213. mCurrentContext->setCurrent();
  2214. // Check if the context has already done one-time initialisation
  2215. if(!mCurrentContext->getInitialized())
  2216. {
  2217. _oneTimeContextInitialization();
  2218. mCurrentContext->setInitialized();
  2219. }
  2220. // Rebind GPU programs to new context
  2221. if (mCurrentVertexProgram)
  2222. mCurrentVertexProgram->bindProgram();
  2223. if (mCurrentGeometryProgram)
  2224. mCurrentGeometryProgram->bindProgram();
  2225. if (mCurrentFragmentProgram)
  2226. mCurrentFragmentProgram->bindProgram();
  2227. // Must reset depth/colour write mask to according with user desired, otherwise,
  2228. // clearFrameBuffer would be wrong because the value we are recorded may be
  2229. // difference with the really state stored in GL context.
  2230. glDepthMask(mDepthWrite);
  2231. glColorMask(mColourWrite[0], mColourWrite[1], mColourWrite[2], mColourWrite[3]);
  2232. glStencilMask(mStencilMask);
  2233. }
  2234. //---------------------------------------------------------------------
  2235. void GLRenderSystem::setRenderTarget(RenderTarget *target)
  2236. {
  2237. // Unbind frame buffer object
  2238. if(mActiveRenderTarget)
  2239. GLRTTManager::instancePtr()->unbind(mActiveRenderTarget);
  2240. mActiveRenderTarget = target;
  2241. // Switch context if different from current one
  2242. GLContext *newContext = 0;
  2243. target->getCustomAttribute("GLCONTEXT", &newContext);
  2244. if(newContext && mCurrentContext != newContext)
  2245. {
  2246. _switchContext(newContext);
  2247. }
  2248. // Bind frame buffer object
  2249. GLRTTManager::instancePtr()->bind(target);
  2250. if (GLEW_EXT_framebuffer_sRGB)
  2251. {
  2252. // Enable / disable sRGB states
  2253. if (target->isHardwareGammaEnabled())
  2254. {
  2255. glEnable(GL_FRAMEBUFFER_SRGB_EXT);
  2256. // Note: could test GL_FRAMEBUFFER_SRGB_CAPABLE_EXT here before
  2257. // enabling, but GL spec says incapable surfaces ignore the setting
  2258. // anyway. We test the capability to enable isHardwareGammaEnabled.
  2259. }
  2260. else
  2261. {
  2262. glDisable(GL_FRAMEBUFFER_SRGB_EXT);
  2263. }
  2264. }
  2265. }
  2266. //---------------------------------------------------------------------
  2267. void GLRenderSystem::_unregisterContext(GLContext *context)
  2268. {
  2269. if(mCurrentContext == context) {
  2270. // Change the context to something else so that a valid context
  2271. // remains active. When this is the main context being unregistered,
  2272. // we set the main context to 0.
  2273. if(mCurrentContext != mMainContext) {
  2274. _switchContext(mMainContext);
  2275. } else {
  2276. /// No contexts remain
  2277. mCurrentContext->endCurrent();
  2278. mCurrentContext = 0;
  2279. mMainContext = 0;
  2280. }
  2281. }
  2282. }
  2283. //---------------------------------------------------------------------
  2284. float GLRenderSystem::getMinimumDepthInputValue(void)
  2285. {
  2286. // Range [-1.0f, 1.0f]
  2287. return -1.0f;
  2288. }
  2289. //---------------------------------------------------------------------
  2290. float GLRenderSystem::getMaximumDepthInputValue(void)
  2291. {
  2292. // Range [-1.0f, 1.0f]
  2293. return 1.0f;
  2294. }
  2295. //---------------------------------------------------------------------
  2296. void GLRenderSystem::registerThread()
  2297. {
  2298. CM_LOCK_MUTEX(mThreadInitMutex)
  2299. // This is only valid once we've created the main context
  2300. if (!mMainContext)
  2301. {
  2302. CM_EXCEPT(InvalidParametersException,
  2303. "Cannot register a background thread before the main context has been created.");
  2304. }
  2305. // Create a new context for this thread. Cloning from the main context
  2306. // will ensure that resources are shared with the main context
  2307. // We want a separate context so that we can safely create GL
  2308. // objects in parallel with the main thread
  2309. GLContext* newContext = mMainContext->clone();
  2310. mBackgroundContextList.push_back(newContext);
  2311. // Bind this new context to this thread.
  2312. newContext->setCurrent();
  2313. _oneTimeContextInitialization();
  2314. newContext->setInitialized();
  2315. }
  2316. //---------------------------------------------------------------------
  2317. void GLRenderSystem::unregisterThread()
  2318. {
  2319. // nothing to do here?
  2320. // Don't need to worry about active context, just make sure we delete
  2321. // on shutdown.
  2322. }
  2323. //---------------------------------------------------------------------
  2324. bool GLRenderSystem::activateGLTextureUnit(size_t unit)
  2325. {
  2326. if (mActiveTextureUnit != unit)
  2327. {
  2328. if (GLEW_VERSION_1_2 && unit < getCapabilities()->getNumTextureUnits())
  2329. {
  2330. glActiveTextureARB(GL_TEXTURE0 + unit);
  2331. mActiveTextureUnit = unit;
  2332. return true;
  2333. }
  2334. else if (!unit)
  2335. {
  2336. // always ok to use the first unit
  2337. return true;
  2338. }
  2339. else
  2340. {
  2341. return false;
  2342. }
  2343. }
  2344. else
  2345. {
  2346. return true;
  2347. }
  2348. }
  2349. //---------------------------------------------------------------------
  2350. unsigned int GLRenderSystem::getDisplayMonitorCount() const
  2351. {
  2352. return mGLSupport->getDisplayMonitorCount();
  2353. }
  2354. }