CmGLRenderSystem.cpp 92 KB

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