2
0

CmGLRenderSystem.cpp 89 KB

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