CmGLRenderSystem.cpp 74 KB

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