CmGLRenderSystem.cpp 78 KB

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