2
0

CmGLRenderSystem.cpp 94 KB

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