OGLGraphics.cpp 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2012 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  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.
  22. //
  23. #include "Precompiled.h"
  24. #include "AnimatedModel.h"
  25. #include "Animation.h"
  26. #include "AnimationController.h"
  27. #include "BillboardSet.h"
  28. #include "Camera.h"
  29. #include "Context.h"
  30. #include "DebugRenderer.h"
  31. #include "DecalSet.h"
  32. #include "Graphics.h"
  33. #include "GraphicsEvents.h"
  34. #include "GraphicsImpl.h"
  35. #include "IndexBuffer.h"
  36. #include "Log.h"
  37. #include "Material.h"
  38. #include "Mutex.h"
  39. #include "Octree.h"
  40. #include "ParticleEmitter.h"
  41. #include "ProcessUtils.h"
  42. #include "Profiler.h"
  43. #include "RenderSurface.h"
  44. #include "Shader.h"
  45. #include "ShaderProgram.h"
  46. #include "ShaderVariation.h"
  47. #include "Skybox.h"
  48. #include "StringUtils.h"
  49. #include "Technique.h"
  50. #include "Terrain.h"
  51. #include "TerrainPatch.h"
  52. #include "Texture2D.h"
  53. #include "TextureCube.h"
  54. #include "VertexBuffer.h"
  55. #include "Zone.h"
  56. #include <stdio.h>
  57. #include "DebugNew.h"
  58. #ifdef GL_ES_VERSION_2_0
  59. #define GL_DEPTH_COMPONENT24 GL_DEPTH_COMPONENT24_OES
  60. #define GL_FRAMEBUFFER_EXT GL_FRAMEBUFFER
  61. #define GL_RENDERBUFFER_EXT GL_RENDERBUFFER
  62. #define GL_COLOR_ATTACHMENT0_EXT GL_COLOR_ATTACHMENT0
  63. #define GL_DEPTH_ATTACHMENT_EXT GL_DEPTH_ATTACHMENT
  64. #define GL_STENCIL_ATTACHMENT_EXT GL_STENCIL_ATTACHMENT
  65. #define GL_FRAMEBUFFER_COMPLETE_EXT GL_FRAMEBUFFER_COMPLETE
  66. #define glClearDepth glClearDepthf
  67. #define glBindFramebufferEXT glBindFramebuffer
  68. #define glFramebufferTexture2DEXT glFramebufferTexture2D
  69. #define glFramebufferRenderbufferEXT glFramebufferRenderbuffer
  70. #define glGenFramebuffersEXT glGenFramebuffers
  71. #define glDeleteFramebuffersEXT glDeleteFramebuffers
  72. #define glCheckFramebufferStatusEXT glCheckFramebufferStatus
  73. #endif
  74. static const unsigned glCmpFunc[] =
  75. {
  76. GL_ALWAYS,
  77. GL_EQUAL,
  78. GL_NOTEQUAL,
  79. GL_LESS,
  80. GL_LEQUAL,
  81. GL_GREATER,
  82. GL_GEQUAL
  83. };
  84. static const unsigned glSrcBlend[] =
  85. {
  86. GL_ONE,
  87. GL_ONE,
  88. GL_DST_COLOR,
  89. GL_SRC_ALPHA,
  90. GL_SRC_ALPHA,
  91. GL_ONE,
  92. GL_ONE_MINUS_DST_ALPHA
  93. };
  94. static const unsigned glDestBlend[] =
  95. {
  96. GL_ZERO,
  97. GL_ONE,
  98. GL_ZERO,
  99. GL_ONE_MINUS_SRC_ALPHA,
  100. GL_ONE,
  101. GL_ONE_MINUS_SRC_ALPHA,
  102. GL_DST_ALPHA
  103. };
  104. static const unsigned glStencilOps[] =
  105. {
  106. GL_KEEP,
  107. GL_ZERO,
  108. GL_REPLACE,
  109. GL_INCR_WRAP,
  110. GL_DECR_WRAP
  111. };
  112. static unsigned numInstances = 0;
  113. static const unsigned MAX_FRAMEBUFFER_AGE = 2000;
  114. OBJECTTYPESTATIC(Graphics);
  115. bool CheckExtension(const String& name)
  116. {
  117. String extensions((const char*)glGetString(GL_EXTENSIONS));
  118. return extensions.Find(name) != String::NPOS;
  119. }
  120. Graphics::Graphics(Context* context_) :
  121. Object(context_),
  122. impl_(new GraphicsImpl()),
  123. externalWindow_(0),
  124. width_(0),
  125. height_(0),
  126. multiSample_(1),
  127. fullscreen_(false),
  128. vsync_(false),
  129. tripleBuffer_(false),
  130. lightPrepassSupport_(false),
  131. deferredSupport_(false),
  132. hardwareDepthSupport_(false),
  133. anisotropySupport_(false),
  134. dxtTextureSupport_(false),
  135. etcTextureSupport_(false),
  136. pvrtcTextureSupport_(false),
  137. numPrimitives_(0),
  138. numBatches_(0),
  139. maxScratchBufferRequest_(0),
  140. shadowMapFormat_(GL_DEPTH_COMPONENT16),
  141. hiresShadowMapFormat_(GL_DEPTH_COMPONENT24),
  142. defaultTextureFilterMode_(FILTER_BILINEAR)
  143. {
  144. SetTextureUnitMappings();
  145. ResetCachedState();
  146. // If first instance in this process, initialize SDL under static mutex. Note that Graphics subsystem will also be in charge
  147. // of shutting down SDL as a whole, so it should be the last SDL-using subsystem (Audio and Input also use SDL) alive
  148. {
  149. MutexLock lock(GetStaticMutex());
  150. if (!numInstances)
  151. SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_JOYSTICK | SDL_INIT_NOPARACHUTE);
  152. ++numInstances;
  153. }
  154. }
  155. Graphics::~Graphics()
  156. {
  157. Close();
  158. delete impl_;
  159. impl_ = 0;
  160. // If last instance in this process, shut down SDL under static mutex
  161. {
  162. MutexLock lock(GetStaticMutex());
  163. --numInstances;
  164. if (!numInstances)
  165. SDL_Quit();
  166. }
  167. }
  168. void Graphics::SetExternalWindow(void* window)
  169. {
  170. if (!impl_->window_)
  171. externalWindow_ = window;
  172. else
  173. LOGERROR("Window already opened, can not set external window");
  174. }
  175. void Graphics::SetWindowTitle(const String& windowTitle)
  176. {
  177. windowTitle_ = windowTitle;
  178. if (impl_->window_)
  179. SDL_SetWindowTitle(impl_->window_, windowTitle_.CString());
  180. }
  181. bool Graphics::SetMode(int width, int height, bool fullscreen, bool vsync, bool tripleBuffer, int multiSample)
  182. {
  183. PROFILE(SetScreenMode);
  184. multiSample = Clamp(multiSample, 1, 16);
  185. if (IsInitialized() && width == width_ && height == height_ && fullscreen == fullscreen_ &&
  186. vsync == vsync_ && tripleBuffer == tripleBuffer_ && multiSample == multiSample_)
  187. return true;
  188. // If only vsync changes, do not destroy/recreate the context
  189. if (IsInitialized() && width == width_ && height == height_ && fullscreen == fullscreen_ &&
  190. tripleBuffer == tripleBuffer_ && multiSample == multiSample_ && vsync != vsync_)
  191. {
  192. SDL_GL_SetSwapInterval(vsync ? 1 : 0);
  193. vsync_ = vsync;
  194. return true;
  195. }
  196. // If zero dimensions in windowed mode, set default. If zero in fullscreen, use desktop mode
  197. if (!width || !height)
  198. {
  199. if (!fullscreen)
  200. {
  201. width = 800;
  202. height = 600;
  203. }
  204. else
  205. {
  206. SDL_DisplayMode mode;
  207. SDL_GetDesktopDisplayMode(0, &mode);
  208. width = mode.w;
  209. height = mode.h;
  210. }
  211. }
  212. // With an external window, only the size can change after initial setup, so do not recreate context
  213. if (!externalWindow_ || !impl_->context_)
  214. {
  215. // Close the existing window and OpenGL context, mark GPU objects as lost
  216. Release(false, true);
  217. {
  218. // SDL window parameters are static, so need to operate under static lock
  219. MutexLock lock(GetStaticMutex());
  220. #ifdef IOS
  221. SDL_SetHint(SDL_HINT_ORIENTATIONS, "LandscapeLeft LandscapeRight");
  222. #endif
  223. SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
  224. SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
  225. SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
  226. SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
  227. SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
  228. SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 0);
  229. #ifndef GL_ES_VERSION_2_0
  230. SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
  231. #else
  232. SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 0);
  233. #endif
  234. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
  235. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
  236. if (multiSample > 1)
  237. {
  238. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
  239. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, multiSample);
  240. }
  241. else
  242. {
  243. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0);
  244. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0);
  245. }
  246. unsigned flags = SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN;
  247. int x = fullscreen ? 0 : SDL_WINDOWPOS_UNDEFINED;
  248. int y = fullscreen ? 0 : SDL_WINDOWPOS_UNDEFINED;
  249. if (fullscreen)
  250. flags |= SDL_WINDOW_FULLSCREEN | SDL_WINDOW_BORDERLESS;
  251. if (!externalWindow_)
  252. impl_->window_ = SDL_CreateWindow(windowTitle_.CString(), x, y, width, height, flags);
  253. else
  254. {
  255. if (!impl_->window_)
  256. impl_->window_ = SDL_CreateWindowFrom(externalWindow_);
  257. fullscreen = false;
  258. }
  259. if (!impl_->window_)
  260. {
  261. LOGERROR("Could not open window");
  262. return false;
  263. }
  264. // Create/restore context and GPU objects and set initial renderstate
  265. Restore();
  266. if (!impl_->context_)
  267. {
  268. LOGERROR("Could not create OpenGL context");
  269. return false;
  270. }
  271. // If OpenGL extensions not yet initialized, initialize now
  272. #ifndef GL_ES_VERSION_2_0
  273. if (!GLeeInitialized())
  274. GLeeInit();
  275. if (!_GLEE_VERSION_2_0)
  276. {
  277. LOGERROR("OpenGL 2.0 is required");
  278. Release(true, true);
  279. return false;
  280. }
  281. if (!CheckExtension("EXT_framebuffer_object") || !CheckExtension("EXT_packed_depth_stencil"))
  282. {
  283. LOGERROR("EXT_framebuffer_object and EXT_packed_depth_stencil OpenGL extensions are required");
  284. Release(true, true);
  285. return false;
  286. }
  287. dxtTextureSupport_ = CheckExtension("EXT_texture_compression_s3tc");
  288. anisotropySupport_ = CheckExtension("EXT_texture_filter_anisotropic");
  289. #else
  290. dxtTextureSupport_ = CheckExtension("EXT_texture_compression_dxt1");
  291. etcTextureSupport_ = CheckExtension("OES_compressed_ETC1_RGB8_texture");
  292. pvrtcTextureSupport_ = CheckExtension("IMG_texture_compression_pvrtc");
  293. #endif
  294. }
  295. }
  296. // Set vsync
  297. SDL_GL_SetSwapInterval(vsync ? 1 : 0);
  298. // Store the system FBO on IOS now
  299. #ifdef IOS
  300. glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint*)&impl_->systemFbo_);
  301. #endif
  302. fullscreen_ = fullscreen;
  303. vsync_ = vsync;
  304. tripleBuffer_ = tripleBuffer;
  305. multiSample_ = multiSample;
  306. SDL_GetWindowSize(impl_->window_, &width_, &height_);
  307. // Reset rendertargets and viewport for the new screen mode
  308. ResetRenderTargets();
  309. // Clear the initial window contents to black
  310. Clear(CLEAR_COLOR);
  311. SDL_GL_SwapWindow(impl_->window_);
  312. CheckFeatureSupport();
  313. if (multiSample > 1)
  314. LOGINFO("Set screen mode " + String(width_) + "x" + String(height_) + " " + (fullscreen_ ? "fullscreen" : "windowed") +
  315. " multisample " + String(multiSample));
  316. else
  317. LOGINFO("Set screen mode " + String(width_) + "x" + String(height_) + " " + (fullscreen_ ? "fullscreen" : "windowed"));
  318. using namespace ScreenMode;
  319. VariantMap eventData;
  320. eventData[P_WIDTH] = width_;
  321. eventData[P_HEIGHT] = height_;
  322. eventData[P_FULLSCREEN] = fullscreen_;
  323. SendEvent(E_SCREENMODE, eventData);
  324. return true;
  325. }
  326. bool Graphics::SetMode(int width, int height)
  327. {
  328. return SetMode(width, height, fullscreen_, vsync_, tripleBuffer_, multiSample_);
  329. }
  330. bool Graphics::ToggleFullscreen()
  331. {
  332. return SetMode(width_, height_, !fullscreen_, vsync_, tripleBuffer_, multiSample_);
  333. }
  334. void Graphics::Close()
  335. {
  336. if (!IsInitialized())
  337. return;
  338. // Actually close the window
  339. Release(true, true);
  340. }
  341. bool Graphics::TakeScreenShot(Image& destImage)
  342. {
  343. PROFILE(TakeScreenShot);
  344. ResetRenderTargets();
  345. destImage.SetSize(width_, height_, 3);
  346. glReadPixels(0, 0, width_, height_, GL_RGB, GL_UNSIGNED_BYTE, destImage.GetData());
  347. return true;
  348. }
  349. bool Graphics::BeginFrame()
  350. {
  351. if (!IsInitialized() || IsDeviceLost())
  352. return false;
  353. // If using an external window, check it for size changes, and reset screen mode if necessary
  354. if (externalWindow_)
  355. {
  356. int width, height;
  357. SDL_GetWindowSize(impl_->window_, &width, &height);
  358. if (width != width_ || height != height_)
  359. SetMode(width, height);
  360. }
  361. // Set default rendertarget and depth buffer
  362. ResetRenderTargets();
  363. // Cleanup textures from previous frame
  364. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  365. SetTexture(i, 0);
  366. // Enable color and depth write
  367. SetColorWrite(true);
  368. SetDepthWrite(true);
  369. numPrimitives_ = 0;
  370. numBatches_ = 0;
  371. SendEvent(E_BEGINRENDERING);
  372. return true;
  373. }
  374. void Graphics::EndFrame()
  375. {
  376. if (!IsInitialized())
  377. return;
  378. PROFILE(Present);
  379. SendEvent(E_ENDRENDERING);
  380. SDL_GL_SwapWindow(impl_->window_);
  381. // Clean up FBO's that have not been used for a long time, and too large scratch buffers
  382. CleanupFramebuffers(false);
  383. CleanupScratchBuffers();
  384. }
  385. void Graphics::Clear(unsigned flags, const Color& color, float depth, unsigned stencil)
  386. {
  387. if (impl_->fboDirty_)
  388. CommitFramebuffer();
  389. #ifdef GL_ES_VERSION_2_0
  390. flags &= ~CLEAR_STENCIL;
  391. #endif
  392. bool oldColorWrite = colorWrite_;
  393. bool oldDepthWrite = depthWrite_;
  394. if (flags & CLEAR_COLOR && !oldColorWrite)
  395. SetColorWrite(true);
  396. if (flags & CLEAR_DEPTH && !oldDepthWrite)
  397. SetDepthWrite(true);
  398. if (flags & CLEAR_STENCIL && stencilWriteMask_ != M_MAX_UNSIGNED)
  399. glStencilMask(M_MAX_UNSIGNED);
  400. unsigned glFlags = 0;
  401. if (flags & CLEAR_COLOR)
  402. {
  403. glFlags |= GL_COLOR_BUFFER_BIT;
  404. glClearColor(color.r_, color.g_, color.b_, color.a_);
  405. }
  406. if (flags & CLEAR_DEPTH)
  407. {
  408. glFlags |= GL_DEPTH_BUFFER_BIT;
  409. glClearDepth(depth);
  410. }
  411. if (flags & CLEAR_STENCIL)
  412. {
  413. glFlags |= GL_STENCIL_BUFFER_BIT;
  414. glClearStencil(stencil);
  415. }
  416. // If viewport is less than full screen, set a scissor to limit the clear
  417. /// \todo Any user-set scissor test will be lost
  418. IntVector2 viewSize = GetRenderTargetDimensions();
  419. if (viewport_.left_ != 0 || viewport_.top_ != 0 || viewport_.right_ != viewSize.x_ || viewport_.bottom_ != viewSize.y_)
  420. SetScissorTest(true, IntRect(0, 0, viewport_.right_ - viewport_.left_, viewport_.bottom_ - viewport_.top_));
  421. else
  422. SetScissorTest(false);
  423. glClear(glFlags);
  424. SetScissorTest(false);
  425. SetColorWrite(oldColorWrite);
  426. SetDepthWrite(oldDepthWrite);
  427. if (flags & CLEAR_STENCIL && stencilWriteMask_ != M_MAX_UNSIGNED)
  428. glStencilMask(stencilWriteMask_);
  429. }
  430. bool Graphics::ResolveToTexture(Texture2D* destination, const IntRect& viewport)
  431. {
  432. if (!destination || !destination->GetRenderSurface() || destination->GetWidth() != width_ ||
  433. destination->GetHeight() != height_)
  434. return false;
  435. IntRect vpCopy = viewport;
  436. if (vpCopy.right_ <= vpCopy.left_)
  437. vpCopy.right_ = vpCopy.left_ + 1;
  438. if (vpCopy.bottom_ <= vpCopy.top_)
  439. vpCopy.bottom_ = vpCopy.top_ + 1;
  440. vpCopy.left_ = Clamp(vpCopy.left_, 0, width_);
  441. vpCopy.top_ = Clamp(vpCopy.top_, 0, height_);
  442. vpCopy.right_ = Clamp(vpCopy.right_, 0, width_);
  443. vpCopy.bottom_ = Clamp(vpCopy.bottom_, 0, height_);
  444. // Make sure the FBO is not in use
  445. ResetRenderTargets();
  446. // Use Direct3D convention with the vertical coordinates ie. 0 is top
  447. SetTextureForUpdate(destination);
  448. glCopyTexSubImage2D(GL_TEXTURE_2D, 0, vpCopy.left_, height_ - vpCopy.bottom_, vpCopy.left_, height_ - vpCopy.bottom_,
  449. vpCopy.right_ - vpCopy.left_, vpCopy.bottom_ - vpCopy.top_);
  450. SetTexture(0, 0);
  451. return true;
  452. }
  453. void Graphics::Draw(PrimitiveType type, unsigned vertexStart, unsigned vertexCount)
  454. {
  455. if (!vertexCount)
  456. return;
  457. if (impl_->fboDirty_)
  458. CommitFramebuffer();
  459. unsigned primitiveCount = 0;
  460. switch (type)
  461. {
  462. case TRIANGLE_LIST:
  463. primitiveCount = vertexCount / 3;
  464. glDrawArrays(GL_TRIANGLES, vertexStart, vertexCount);
  465. break;
  466. case LINE_LIST:
  467. primitiveCount = vertexCount / 2;
  468. glDrawArrays(GL_LINES, vertexStart, vertexCount);
  469. break;
  470. }
  471. numPrimitives_ += primitiveCount;
  472. ++numBatches_;
  473. }
  474. void Graphics::Draw(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned minVertex, unsigned vertexCount)
  475. {
  476. if (!indexCount || !indexBuffer_ || !indexBuffer_->GetGPUObject())
  477. return;
  478. if (impl_->fboDirty_)
  479. CommitFramebuffer();
  480. unsigned primitiveCount = 0;
  481. unsigned indexSize = indexBuffer_->GetIndexSize();
  482. switch (type)
  483. {
  484. case TRIANGLE_LIST:
  485. primitiveCount = indexCount / 3;
  486. if (indexSize == sizeof(unsigned short))
  487. glDrawElements(GL_TRIANGLES, indexCount, GL_UNSIGNED_SHORT, (const GLvoid*)(indexStart * indexSize));
  488. else
  489. glDrawElements(GL_TRIANGLES, indexCount, GL_UNSIGNED_INT, (const GLvoid*)(indexStart * indexSize));
  490. break;
  491. case LINE_LIST:
  492. primitiveCount = indexCount / 2;
  493. if (indexSize == sizeof(unsigned short))
  494. glDrawElements(GL_LINES, indexCount, GL_UNSIGNED_SHORT, (const GLvoid*)(indexStart * indexSize));
  495. else
  496. glDrawElements(GL_LINES, indexCount, GL_UNSIGNED_INT, (const GLvoid*)(indexStart * indexSize));
  497. break;
  498. }
  499. numPrimitives_ += primitiveCount;
  500. ++numBatches_;
  501. }
  502. void Graphics::DrawInstanced(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned minVertex, unsigned vertexCount, unsigned instanceCount)
  503. {
  504. }
  505. void Graphics::SetVertexBuffer(VertexBuffer* buffer)
  506. {
  507. Vector<VertexBuffer*> vertexBuffers(1);
  508. PODVector<unsigned> elementMasks(1);
  509. vertexBuffers[0] = buffer;
  510. elementMasks[0] = MASK_DEFAULT;
  511. SetVertexBuffers(vertexBuffers, elementMasks);
  512. }
  513. bool Graphics::SetVertexBuffers(const Vector<VertexBuffer*>& buffers, const PODVector<unsigned>& elementMasks,
  514. unsigned instanceOffset)
  515. {
  516. if (buffers.Size() > MAX_VERTEX_STREAMS)
  517. {
  518. LOGERROR("Too many vertex buffers");
  519. return false;
  520. }
  521. if (buffers.Size() != elementMasks.Size())
  522. {
  523. LOGERROR("Amount of element masks and vertex buffers does not match");
  524. return false;
  525. }
  526. bool changed = false;
  527. unsigned newAttributes = 0;
  528. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  529. {
  530. VertexBuffer* buffer = 0;
  531. unsigned elementMask = 0;
  532. if (i < buffers.Size() && buffers[i])
  533. {
  534. buffer = buffers[i];
  535. if (elementMasks[i] == MASK_DEFAULT)
  536. elementMask = buffer->GetElementMask();
  537. else
  538. elementMask = buffer->GetElementMask() & elementMasks[i];
  539. }
  540. // If buffer and element mask have stayed the same, skip to the next buffer
  541. if (buffer == vertexBuffers_[i] && elementMask == elementMasks_[i] && !changed)
  542. {
  543. newAttributes |= elementMask;
  544. continue;
  545. }
  546. vertexBuffers_[i] = buffer;
  547. elementMasks_[i] = elementMask;
  548. changed = true;
  549. // Beware buffers with missing OpenGL objects, as binding a zero buffer object means accessing CPU memory for vertex data,
  550. // in which case the pointer will be invalid and cause a crash
  551. if (!buffer || !buffer->GetGPUObject())
  552. continue;
  553. glBindBuffer(GL_ARRAY_BUFFER, buffer->GetGPUObject());
  554. unsigned vertexSize = buffer->GetVertexSize();
  555. for (unsigned j = 0; j < MAX_VERTEX_ELEMENTS; ++j)
  556. {
  557. unsigned elementBit = 1 << j;
  558. if (elementMask & elementBit)
  559. {
  560. newAttributes |= elementBit;
  561. // Enable attribute if not enabled yet
  562. if ((impl_->enabledAttributes_ & elementBit) == 0)
  563. {
  564. glEnableVertexAttribArray(j);
  565. impl_->enabledAttributes_ |= elementBit;
  566. }
  567. // Set the attribute pointer
  568. glVertexAttribPointer(j, VertexBuffer::elementComponents[j], VertexBuffer::elementType[j],
  569. VertexBuffer::elementNormalize[j], vertexSize, (const GLvoid*)(buffer->GetElementOffset((VertexElement)j)));
  570. }
  571. }
  572. }
  573. if (!changed)
  574. return true;
  575. // Now check which vertex attributes should be disabled
  576. unsigned disableAttributes = impl_->enabledAttributes_ & (~newAttributes);
  577. int disableIndex = 0;
  578. while (disableAttributes)
  579. {
  580. if (disableAttributes & 1)
  581. {
  582. glDisableVertexAttribArray(disableIndex);
  583. impl_->enabledAttributes_ &= ~(1 << disableIndex);
  584. }
  585. disableAttributes >>= 1;
  586. ++disableIndex;
  587. }
  588. return true;
  589. }
  590. bool Graphics::SetVertexBuffers(const Vector<SharedPtr<VertexBuffer> >& buffers, const PODVector<unsigned>&
  591. elementMasks, unsigned instanceOffset)
  592. {
  593. if (buffers.Size() > MAX_VERTEX_STREAMS)
  594. {
  595. LOGERROR("Too many vertex buffers");
  596. return false;
  597. }
  598. if (buffers.Size() != elementMasks.Size())
  599. {
  600. LOGERROR("Amount of element masks and vertex buffers does not match");
  601. return false;
  602. }
  603. bool changed = false;
  604. unsigned newAttributes = 0;
  605. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  606. {
  607. VertexBuffer* buffer = 0;
  608. unsigned elementMask = 0;
  609. if (i < buffers.Size() && buffers[i])
  610. {
  611. buffer = buffers[i];
  612. if (elementMasks[i] == MASK_DEFAULT)
  613. elementMask = buffer->GetElementMask();
  614. else
  615. elementMask = buffer->GetElementMask() & elementMasks[i];
  616. }
  617. if (buffer == vertexBuffers_[i] && elementMask == elementMasks_[i] && !changed)
  618. {
  619. newAttributes |= elementMask;
  620. continue;
  621. }
  622. vertexBuffers_[i] = buffer;
  623. elementMasks_[i] = elementMask;
  624. changed = true;
  625. if (!buffer || !buffer->GetGPUObject())
  626. continue;
  627. glBindBuffer(GL_ARRAY_BUFFER, buffer->GetGPUObject());
  628. unsigned vertexSize = buffer->GetVertexSize();
  629. for (unsigned j = 0; j < MAX_VERTEX_ELEMENTS; ++j)
  630. {
  631. unsigned elementBit = 1 << j;
  632. if (elementMask & elementBit)
  633. {
  634. newAttributes |= elementBit;
  635. if ((impl_->enabledAttributes_ & elementBit) == 0)
  636. {
  637. glEnableVertexAttribArray(j);
  638. impl_->enabledAttributes_ |= elementBit;
  639. }
  640. glVertexAttribPointer(j, VertexBuffer::elementComponents[j], VertexBuffer::elementType[j],
  641. VertexBuffer::elementNormalize[j], vertexSize, (const GLvoid*)(buffer->GetElementOffset((VertexElement)j)));
  642. }
  643. }
  644. }
  645. if (!changed)
  646. return true;
  647. unsigned disableAttributes = impl_->enabledAttributes_ & (~newAttributes);
  648. int disableIndex = 0;
  649. while (disableAttributes)
  650. {
  651. if (disableAttributes & 1)
  652. {
  653. glDisableVertexAttribArray(disableIndex);
  654. impl_->enabledAttributes_ &= ~(1 << disableIndex);
  655. }
  656. disableAttributes >>= 1;
  657. ++disableIndex;
  658. }
  659. return true;
  660. }
  661. void Graphics::SetIndexBuffer(IndexBuffer* buffer)
  662. {
  663. if (indexBuffer_ == buffer)
  664. return;
  665. if (buffer)
  666. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer->GetGPUObject());
  667. else
  668. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
  669. indexBuffer_ = buffer;
  670. }
  671. void Graphics::SetShaders(ShaderVariation* vs, ShaderVariation* ps)
  672. {
  673. if (vs == vertexShader_ && ps == pixelShader_)
  674. return;
  675. ClearParameterSources();
  676. // Compile the shaders now if not yet compiled. If already attempted, do not retry
  677. if (vs && !vs->IsCompiled())
  678. {
  679. if (vs->GetCompilerOutput().Empty())
  680. {
  681. PROFILE(CompileVertexShader);
  682. bool success = vs->Create();
  683. if (success)
  684. LOGDEBUG("Compiled vertex shader " + vs->GetName());
  685. else
  686. {
  687. LOGERROR("Failed to compile vertex shader " + vs->GetName() + ":\n" + vs->GetCompilerOutput());
  688. vs = 0;
  689. }
  690. }
  691. else
  692. vs = 0;
  693. }
  694. if (ps && !ps->IsCompiled())
  695. {
  696. if (ps->GetCompilerOutput().Empty())
  697. {
  698. PROFILE(CompilePixelShader);
  699. bool success = ps->Create();
  700. if (success)
  701. LOGDEBUG("Compiled pixel shader " + ps->GetName());
  702. else
  703. {
  704. LOGERROR("Failed to compile pixel shader " + ps->GetName() + ":\n" + ps->GetCompilerOutput());
  705. ps = 0;
  706. }
  707. }
  708. else
  709. ps = 0;
  710. }
  711. if (!vs || !ps)
  712. {
  713. glUseProgram(0);
  714. vertexShader_ = 0;
  715. pixelShader_ = 0;
  716. shaderProgram_ = 0;
  717. }
  718. else
  719. {
  720. vertexShader_ = vs;
  721. pixelShader_ = ps;
  722. Pair<ShaderVariation*, ShaderVariation*> combination(vs, ps);
  723. ShaderProgramMap::Iterator i = shaderPrograms_.Find(combination);
  724. if (i != shaderPrograms_.End())
  725. {
  726. // Use the existing linked program
  727. if (i->second_->IsLinked())
  728. {
  729. glUseProgram(i->second_->GetGPUObject());
  730. shaderProgram_ = i->second_;
  731. }
  732. else
  733. {
  734. glUseProgram(0);
  735. shaderProgram_ = 0;
  736. }
  737. }
  738. else
  739. {
  740. // Link a new combination
  741. SharedPtr<ShaderProgram> newProgram(new ShaderProgram(this, vs, ps));
  742. if (newProgram->Link())
  743. {
  744. LOGDEBUG("Linked vertex shader " + vs->GetName() + " and pixel shader " + ps->GetName());
  745. // Note: Link() calls glUseProgram() to set the texture sampler uniforms,
  746. // so it is not necessary to call it again
  747. shaderProgram_ = newProgram;
  748. }
  749. else
  750. {
  751. LOGERROR("Failed to link vertex shader " + vs->GetName() + " and pixel shader " + ps->GetName() + ":\n" +
  752. newProgram->GetLinkerOutput());
  753. glUseProgram(0);
  754. shaderProgram_ = 0;
  755. }
  756. shaderPrograms_[combination] = newProgram;
  757. }
  758. }
  759. }
  760. void Graphics::SetShaderParameter(StringHash param, const float* data, unsigned count)
  761. {
  762. if (shaderProgram_)
  763. {
  764. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  765. if (info)
  766. {
  767. switch (info->type_)
  768. {
  769. case GL_FLOAT:
  770. glUniform1fv(info->location_, count, data);
  771. break;
  772. case GL_FLOAT_VEC2:
  773. glUniform2fv(info->location_, count / 2, data);
  774. break;
  775. case GL_FLOAT_VEC3:
  776. glUniform3fv(info->location_, count / 3, data);
  777. break;
  778. case GL_FLOAT_VEC4:
  779. glUniform4fv(info->location_, count / 4, data);
  780. break;
  781. case GL_FLOAT_MAT3:
  782. count = Min((int)count, (int)NUM_TEMP_MATRICES * 9);
  783. Matrix3::BulkTranspose(&tempMatrices3_[0].m00_, data, count / 9);
  784. glUniformMatrix3fv(info->location_, count / 9, GL_FALSE, tempMatrices3_[0].Data());
  785. break;
  786. case GL_FLOAT_MAT4:
  787. count = Min((int)count, (int)NUM_TEMP_MATRICES * 16);
  788. Matrix4::BulkTranspose(&tempMatrices4_[0].m00_, data, count / 16);
  789. glUniformMatrix4fv(info->location_, count / 16, GL_FALSE, tempMatrices4_[0].Data());
  790. break;
  791. }
  792. }
  793. }
  794. }
  795. void Graphics::SetShaderParameter(StringHash param, float value)
  796. {
  797. if (shaderProgram_)
  798. {
  799. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  800. if (info)
  801. glUniform1fv(info->location_, 1, &value);
  802. }
  803. }
  804. void Graphics::SetShaderParameter(StringHash param, const Color& color)
  805. {
  806. SetShaderParameter(param, color.Data(), 4);
  807. }
  808. void Graphics::SetShaderParameter(StringHash param, const Matrix3& matrix)
  809. {
  810. if (shaderProgram_)
  811. {
  812. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  813. if (info)
  814. glUniformMatrix3fv(info->location_, 1, GL_FALSE, matrix.Transpose().Data());
  815. }
  816. }
  817. void Graphics::SetShaderParameter(StringHash param, const Vector3& vector)
  818. {
  819. if (shaderProgram_)
  820. {
  821. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  822. if (info)
  823. {
  824. // Check the uniform type to avoid mismatch
  825. switch (info->type_)
  826. {
  827. case GL_FLOAT:
  828. glUniform1fv(info->location_, 1, vector.Data());
  829. break;
  830. case GL_FLOAT_VEC2:
  831. glUniform2fv(info->location_, 1, vector.Data());
  832. break;
  833. case GL_FLOAT_VEC3:
  834. glUniform3fv(info->location_, 1, vector.Data());
  835. break;
  836. }
  837. }
  838. }
  839. }
  840. void Graphics::SetShaderParameter(StringHash param, const Matrix4& matrix)
  841. {
  842. if (shaderProgram_)
  843. {
  844. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  845. if (info)
  846. glUniformMatrix4fv(info->location_, 1, GL_FALSE, matrix.Transpose().Data());
  847. }
  848. }
  849. void Graphics::SetShaderParameter(StringHash param, const Vector4& vector)
  850. {
  851. if (shaderProgram_)
  852. {
  853. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  854. if (info)
  855. {
  856. // Check the uniform type to avoid mismatch
  857. switch (info->type_)
  858. {
  859. case GL_FLOAT:
  860. glUniform1fv(info->location_, 1, vector.Data());
  861. break;
  862. case GL_FLOAT_VEC2:
  863. glUniform2fv(info->location_, 1, vector.Data());
  864. break;
  865. case GL_FLOAT_VEC3:
  866. glUniform3fv(info->location_, 1, vector.Data());
  867. break;
  868. case GL_FLOAT_VEC4:
  869. glUniform4fv(info->location_, 1, vector.Data());
  870. break;
  871. }
  872. }
  873. }
  874. }
  875. void Graphics::SetShaderParameter(StringHash param, const Matrix3x4& matrix)
  876. {
  877. if (shaderProgram_)
  878. {
  879. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  880. if (info)
  881. {
  882. float data[16];
  883. data[0] = matrix.m00_;
  884. data[1] = matrix.m10_;
  885. data[2] = matrix.m20_;
  886. data[3] = 0.0f;
  887. data[4] = matrix.m01_;
  888. data[5] = matrix.m11_;
  889. data[6] = matrix.m21_;
  890. data[7] = 0.0f;
  891. data[8] = matrix.m02_;
  892. data[9] = matrix.m12_;
  893. data[10] = matrix.m22_;
  894. data[11] = 0.0f;
  895. data[12] = matrix.m03_;
  896. data[13] = matrix.m13_;
  897. data[14] = matrix.m23_;
  898. data[15] = 1.0f;
  899. glUniformMatrix4fv(info->location_, 1, GL_FALSE, data);
  900. }
  901. }
  902. }
  903. bool Graphics::NeedParameterUpdate(ShaderParameterGroup group, const void* source)
  904. {
  905. if ((unsigned)shaderParameterSources_[group] == M_MAX_UNSIGNED || shaderParameterSources_[group] != source)
  906. {
  907. shaderParameterSources_[group] = source;
  908. return true;
  909. }
  910. else
  911. return false;
  912. }
  913. bool Graphics::HasShaderParameter(ShaderType type, StringHash param)
  914. {
  915. return shaderProgram_ && shaderProgram_->HasParameter(param);
  916. }
  917. bool Graphics::HasTextureUnit(TextureUnit unit)
  918. {
  919. return shaderProgram_ && shaderProgram_->HasTextureUnit(unit);
  920. }
  921. void Graphics::ClearParameterSource(ShaderParameterGroup group)
  922. {
  923. shaderParameterSources_[group] = (const void*)M_MAX_UNSIGNED;
  924. }
  925. void Graphics::ClearParameterSources()
  926. {
  927. for (unsigned i = 0; i < MAX_SHADER_PARAMETER_GROUPS; ++i)
  928. shaderParameterSources_[i] = (const void*)M_MAX_UNSIGNED;
  929. }
  930. void Graphics::ClearTransformSources()
  931. {
  932. shaderParameterSources_[SP_CAMERA] = (const void*)M_MAX_UNSIGNED;
  933. shaderParameterSources_[SP_OBJECTTRANSFORM] = (const void*)M_MAX_UNSIGNED;
  934. }
  935. void Graphics::CleanupShaderPrograms()
  936. {
  937. for (ShaderProgramMap::Iterator i = shaderPrograms_.Begin(); i != shaderPrograms_.End();)
  938. {
  939. ShaderProgramMap::Iterator current = i++;
  940. ShaderVariation* vs = current->second_->GetVertexShader();
  941. ShaderVariation* ps = current->second_->GetPixelShader();
  942. if (!vs || !ps || !vs->GetGPUObject() || !ps->GetGPUObject())
  943. shaderPrograms_.Erase(current);
  944. }
  945. }
  946. void Graphics::SetTexture(unsigned index, Texture* texture)
  947. {
  948. if (index >= MAX_TEXTURE_UNITS)
  949. return;
  950. // Check if texture is currently bound as a rendertarget. In that case, use its backup texture, or blank if not defined
  951. if (texture)
  952. {
  953. if (texture == viewTexture_ || (renderTargets_[0] && renderTargets_[0]->GetParentTexture() == texture))
  954. texture = texture->GetBackupTexture();
  955. }
  956. if (textures_[index] != texture)
  957. {
  958. if (impl_->activeTexture_ != index)
  959. {
  960. glActiveTexture(GL_TEXTURE0 + index);
  961. impl_->activeTexture_ = index;
  962. }
  963. if (texture)
  964. {
  965. unsigned glType = texture->GetTarget();
  966. if (glType != textureTypes_[index])
  967. {
  968. if (textureTypes_[index])
  969. glDisable(textureTypes_[index]);
  970. glEnable(glType);
  971. textureTypes_[index] = glType;
  972. }
  973. glBindTexture(glType, texture->GetGPUObject());
  974. if (texture->GetParametersDirty())
  975. texture->UpdateParameters();
  976. }
  977. else
  978. {
  979. if (textureTypes_[index])
  980. glBindTexture(textureTypes_[index], 0);
  981. }
  982. textures_[index] = texture;
  983. }
  984. else
  985. {
  986. if (texture && texture->GetParametersDirty())
  987. {
  988. if (impl_->activeTexture_ != index)
  989. {
  990. glActiveTexture(GL_TEXTURE0 + index);
  991. impl_->activeTexture_ = index;
  992. }
  993. glBindTexture(texture->GetTarget(), texture->GetGPUObject());
  994. texture->UpdateParameters();
  995. }
  996. }
  997. }
  998. void Graphics::SetTextureForUpdate(Texture* texture)
  999. {
  1000. if (impl_->activeTexture_ != 0)
  1001. {
  1002. glActiveTexture(GL_TEXTURE0);
  1003. impl_->activeTexture_ = 0;
  1004. }
  1005. glBindTexture(texture->GetTarget(), texture->GetGPUObject());
  1006. textures_[0] = texture;
  1007. }
  1008. void Graphics::SetDefaultTextureFilterMode(TextureFilterMode mode)
  1009. {
  1010. if (mode != defaultTextureFilterMode_)
  1011. {
  1012. defaultTextureFilterMode_ = mode;
  1013. SetTextureParametersDirty();
  1014. }
  1015. }
  1016. void Graphics::SetTextureAnisotropy(unsigned level)
  1017. {
  1018. if (level != textureAnisotropy_)
  1019. {
  1020. textureAnisotropy_ = level;
  1021. SetTextureParametersDirty();
  1022. }
  1023. }
  1024. void Graphics::SetTextureParametersDirty()
  1025. {
  1026. for (Vector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  1027. {
  1028. Texture* texture = dynamic_cast<Texture*>(*i);
  1029. if (texture)
  1030. texture->SetParametersDirty();
  1031. }
  1032. }
  1033. void Graphics::ResetRenderTargets()
  1034. {
  1035. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1036. SetRenderTarget(i, (RenderSurface*)0);
  1037. SetDepthStencil((RenderSurface*)0);
  1038. SetViewport(IntRect(0, 0, width_, height_));
  1039. }
  1040. void Graphics::ResetRenderTarget(unsigned index)
  1041. {
  1042. SetRenderTarget(index, (RenderSurface*)0);
  1043. }
  1044. void Graphics::ResetDepthStencil()
  1045. {
  1046. SetDepthStencil((RenderSurface*)0);
  1047. }
  1048. void Graphics::SetRenderTarget(unsigned index, RenderSurface* renderTarget)
  1049. {
  1050. if (index >= MAX_RENDERTARGETS)
  1051. return;
  1052. if (renderTarget != renderTargets_[index])
  1053. {
  1054. renderTargets_[index] = renderTarget;
  1055. // If the rendertarget is also bound as a texture, replace with backup texture or null
  1056. if (renderTarget)
  1057. {
  1058. Texture* parentTexture = renderTarget->GetParentTexture();
  1059. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1060. {
  1061. if (textures_[i] == parentTexture)
  1062. SetTexture(i, textures_[i]->GetBackupTexture());
  1063. }
  1064. }
  1065. impl_->fboDirty_ = true;
  1066. }
  1067. }
  1068. void Graphics::SetRenderTarget(unsigned index, Texture2D* texture)
  1069. {
  1070. RenderSurface* renderTarget = 0;
  1071. if (texture)
  1072. renderTarget = texture->GetRenderSurface();
  1073. SetRenderTarget(index, renderTarget);
  1074. }
  1075. void Graphics::SetDepthStencil(RenderSurface* depthStencil)
  1076. {
  1077. // If we are using a rendertarget texture, it is required in OpenGL to also have an own depth-stencil
  1078. // Create a new depth-stencil texture as necessary to be able to provide similar behaviour as Direct3D9
  1079. if (renderTargets_[0] && !depthStencil)
  1080. {
  1081. int width = renderTargets_[0]->GetWidth();
  1082. int height = renderTargets_[0]->GetHeight();
  1083. // Direct3D9 default depth-stencil can not be used when rendertarget is larger than the window.
  1084. // Check size similarly
  1085. if (width <= width_ && height <= height_)
  1086. {
  1087. int searchKey = (width << 16) | height;
  1088. HashMap<int, SharedPtr<Texture2D> >::Iterator i = depthTextures_.Find(searchKey);
  1089. if (i != depthTextures_.End())
  1090. depthStencil = i->second_->GetRenderSurface();
  1091. else
  1092. {
  1093. SharedPtr<Texture2D> newDepthTexture(new Texture2D(context_));
  1094. newDepthTexture->SetSize(width, height, GetDepthStencilFormat(), TEXTURE_DEPTHSTENCIL);
  1095. depthTextures_[searchKey] = newDepthTexture;
  1096. depthStencil = newDepthTexture->GetRenderSurface();
  1097. }
  1098. }
  1099. }
  1100. if (depthStencil != depthStencil_)
  1101. {
  1102. depthStencil_ = depthStencil;
  1103. impl_->fboDirty_ = true;
  1104. }
  1105. }
  1106. void Graphics::SetDepthStencil(Texture2D* texture)
  1107. {
  1108. RenderSurface* depthStencil = 0;
  1109. if (texture)
  1110. depthStencil = texture->GetRenderSurface();
  1111. SetDepthStencil(depthStencil);
  1112. }
  1113. void Graphics::SetViewTexture(Texture* texture)
  1114. {
  1115. viewTexture_ = texture;
  1116. if (viewTexture_)
  1117. {
  1118. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1119. {
  1120. if (textures_[i] == viewTexture_)
  1121. SetTexture(i, textures_[i]->GetBackupTexture());
  1122. }
  1123. }
  1124. }
  1125. void Graphics::SetViewport(const IntRect& rect)
  1126. {
  1127. if (impl_->fboDirty_)
  1128. CommitFramebuffer();
  1129. IntVector2 rtSize = GetRenderTargetDimensions();
  1130. IntRect rectCopy = rect;
  1131. if (rectCopy.right_ <= rectCopy.left_)
  1132. rectCopy.right_ = rectCopy.left_ + 1;
  1133. if (rectCopy.bottom_ <= rectCopy.top_)
  1134. rectCopy.bottom_ = rectCopy.top_ + 1;
  1135. rectCopy.left_ = Clamp(rectCopy.left_, 0, rtSize.x_);
  1136. rectCopy.top_ = Clamp(rectCopy.top_, 0, rtSize.y_);
  1137. rectCopy.right_ = Clamp(rectCopy.right_, 0, rtSize.x_);
  1138. rectCopy.bottom_ = Clamp(rectCopy.bottom_, 0, rtSize.y_);
  1139. // Use Direct3D convention with the vertical coordinates ie. 0 is top
  1140. glViewport(rectCopy.left_, rtSize.y_ - rectCopy.bottom_, rectCopy.right_ - rectCopy.left_, rectCopy.bottom_ - rectCopy.top_);
  1141. viewport_ = rectCopy;
  1142. // Disable scissor test, needs to be re-enabled by the user
  1143. SetScissorTest(false);
  1144. }
  1145. void Graphics::SetBlendMode(BlendMode mode)
  1146. {
  1147. if (mode != blendMode_)
  1148. {
  1149. if (mode == BLEND_REPLACE)
  1150. glDisable(GL_BLEND);
  1151. else
  1152. {
  1153. glEnable(GL_BLEND);
  1154. glBlendFunc(glSrcBlend[mode], glDestBlend[mode]);
  1155. }
  1156. blendMode_ = mode;
  1157. }
  1158. }
  1159. void Graphics::SetColorWrite(bool enable)
  1160. {
  1161. if (enable != colorWrite_)
  1162. {
  1163. if (enable)
  1164. glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
  1165. else
  1166. glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
  1167. colorWrite_ = enable;
  1168. }
  1169. }
  1170. void Graphics::SetCullMode(CullMode mode)
  1171. {
  1172. if (mode != cullMode_)
  1173. {
  1174. if (mode == CULL_NONE)
  1175. glDisable(GL_CULL_FACE);
  1176. else
  1177. {
  1178. // Use Direct3D convention, ie. clockwise vertices define a front face
  1179. glEnable(GL_CULL_FACE);
  1180. glCullFace(mode == CULL_CCW ? GL_FRONT : GL_BACK);
  1181. }
  1182. cullMode_ = mode;
  1183. }
  1184. }
  1185. void Graphics::SetDepthBias(float constantBias, float slopeScaledBias)
  1186. {
  1187. if (constantBias != constantDepthBias_ || slopeScaledBias != slopeScaledDepthBias_)
  1188. {
  1189. #ifndef GL_ES_VERSION_2_0
  1190. if (slopeScaledBias != 0.0f)
  1191. {
  1192. // OpenGL constant bias is unreliable and dependant on depth buffer bitdepth, apply in the projection matrix instead
  1193. float adjustedSlopeScaledBias = slopeScaledBias + 1.0f;
  1194. glEnable(GL_POLYGON_OFFSET_FILL);
  1195. glPolygonOffset(adjustedSlopeScaledBias, 0.0f);
  1196. }
  1197. else
  1198. glDisable(GL_POLYGON_OFFSET_FILL);
  1199. #endif
  1200. constantDepthBias_ = constantBias;
  1201. slopeScaledDepthBias_ = slopeScaledBias;
  1202. shaderParameterSources_[SP_CAMERA] = (const void*)M_MAX_UNSIGNED;
  1203. }
  1204. }
  1205. void Graphics::SetDepthTest(CompareMode mode)
  1206. {
  1207. if (mode != depthTestMode_)
  1208. {
  1209. glDepthFunc(glCmpFunc[mode]);
  1210. depthTestMode_ = mode;
  1211. }
  1212. }
  1213. void Graphics::SetDepthWrite(bool enable)
  1214. {
  1215. if (enable != depthWrite_)
  1216. {
  1217. glDepthMask(enable ? GL_TRUE : GL_FALSE);
  1218. depthWrite_ = enable;
  1219. }
  1220. }
  1221. void Graphics::SetScissorTest(bool enable, const Rect& rect, bool borderInclusive)
  1222. {
  1223. // During some light rendering loops, a full rect is toggled on/off repeatedly.
  1224. // Disable scissor in that case to reduce state changes
  1225. if (rect.min_.x_ <= 0.0f && rect.min_.y_ <= 0.0f && rect.max_.x_ >= 1.0f && rect.max_.y_ >= 1.0f)
  1226. enable = false;
  1227. if (enable)
  1228. {
  1229. IntVector2 rtSize(GetRenderTargetDimensions());
  1230. IntVector2 viewSize(viewport_.right_ - viewport_.left_, viewport_.bottom_ - viewport_.top_);
  1231. IntVector2 viewPos(viewport_.left_, viewport_.top_);
  1232. IntRect intRect;
  1233. int expand = borderInclusive ? 1 : 0;
  1234. intRect.left_ = Clamp((int)((rect.min_.x_ + 1.0f) * 0.5f * viewSize.x_) + viewPos.x_, 0, rtSize.x_ - 1);
  1235. intRect.top_ = Clamp((int)((-rect.max_.y_ + 1.0f) * 0.5f * viewSize.y_) + viewPos.y_, 0, rtSize.y_ - 1);
  1236. intRect.right_ = Clamp((int)((rect.max_.x_ + 1.0f) * 0.5f * viewSize.x_) + viewPos.x_ + expand, 0, rtSize.x_);
  1237. intRect.bottom_ = Clamp((int)((-rect.min_.y_ + 1.0f) * 0.5f * viewSize.y_) + viewPos.y_ + expand, 0, rtSize.y_);
  1238. if (intRect.right_ == intRect.left_)
  1239. intRect.right_++;
  1240. if (intRect.bottom_ == intRect.top_)
  1241. intRect.bottom_++;
  1242. if (intRect.right_ < intRect.left_ || intRect.bottom_ < intRect.top_)
  1243. enable = false;
  1244. if (enable && scissorRect_ != intRect)
  1245. {
  1246. // Use Direct3D convention with the vertical coordinates ie. 0 is top
  1247. glScissor(intRect.left_, rtSize.y_ - intRect.bottom_, intRect.right_ - intRect.left_, intRect.bottom_ - intRect.top_);
  1248. scissorRect_ = intRect;
  1249. }
  1250. }
  1251. else
  1252. scissorRect_ = IntRect::ZERO;
  1253. if (enable != scissorTest_)
  1254. {
  1255. if (enable)
  1256. glEnable(GL_SCISSOR_TEST);
  1257. else
  1258. glDisable(GL_SCISSOR_TEST);
  1259. scissorTest_ = enable;
  1260. }
  1261. }
  1262. void Graphics::SetScissorTest(bool enable, const IntRect& rect)
  1263. {
  1264. IntVector2 rtSize(GetRenderTargetDimensions());
  1265. IntVector2 viewSize(viewport_.right_ - viewport_.left_, viewport_.bottom_ - viewport_.top_);
  1266. IntVector2 viewPos(viewport_.left_, viewport_.top_);
  1267. if (enable)
  1268. {
  1269. IntRect intRect;
  1270. intRect.left_ = Clamp(rect.left_ + viewPos.x_, 0, rtSize.x_ - 1);
  1271. intRect.top_ = Clamp(rect.top_ + viewPos.y_, 0, rtSize.y_ - 1);
  1272. intRect.right_ = Clamp(rect.right_ + viewPos.x_, 0, rtSize.x_);
  1273. intRect.bottom_ = Clamp(rect.bottom_ + viewPos.y_, 0, rtSize.y_);
  1274. if (intRect.right_ == intRect.left_)
  1275. intRect.right_++;
  1276. if (intRect.bottom_ == intRect.top_)
  1277. intRect.bottom_++;
  1278. if (intRect.right_ < intRect.left_ || intRect.bottom_ < intRect.top_)
  1279. enable = false;
  1280. if (enable && scissorRect_ != intRect)
  1281. {
  1282. // Use Direct3D convention with the vertical coordinates ie. 0 is top
  1283. glScissor(intRect.left_, rtSize.y_ - intRect.bottom_, intRect.right_ - intRect.left_, intRect.bottom_ - intRect.top_);
  1284. scissorRect_ = intRect;
  1285. }
  1286. }
  1287. else
  1288. scissorRect_ = IntRect::ZERO;
  1289. if (enable != scissorTest_)
  1290. {
  1291. if (enable)
  1292. glEnable(GL_SCISSOR_TEST);
  1293. else
  1294. glDisable(GL_SCISSOR_TEST);
  1295. scissorTest_ = enable;
  1296. }
  1297. }
  1298. void Graphics::SetStreamFrequency(unsigned index, unsigned frequency)
  1299. {
  1300. }
  1301. void Graphics::ResetStreamFrequencies()
  1302. {
  1303. }
  1304. void Graphics::SetStencilTest(bool enable, CompareMode mode, StencilOp pass, StencilOp fail, StencilOp zFail, unsigned stencilRef, unsigned compareMask, unsigned writeMask)
  1305. {
  1306. #ifndef GL_ES_VERSION_2_0
  1307. if (enable != stencilTest_)
  1308. {
  1309. if (enable)
  1310. glEnable(GL_STENCIL_TEST);
  1311. else
  1312. glDisable(GL_STENCIL_TEST);
  1313. stencilTest_ = enable;
  1314. }
  1315. if (enable)
  1316. {
  1317. if (mode != stencilTestMode_ || stencilRef != stencilRef_ || compareMask != stencilCompareMask_)
  1318. {
  1319. glStencilFunc(glCmpFunc[mode], stencilRef, compareMask);
  1320. stencilTestMode_ = mode;
  1321. stencilRef_ = stencilRef;
  1322. stencilCompareMask_ = compareMask;
  1323. }
  1324. if (writeMask != stencilWriteMask_)
  1325. {
  1326. glStencilMask(writeMask);
  1327. stencilWriteMask_ = writeMask;
  1328. }
  1329. if (pass != stencilPass_ || fail != stencilFail_ || zFail != stencilZFail_)
  1330. {
  1331. glStencilOp(glStencilOps[fail], glStencilOps[zFail], glStencilOps[pass]);
  1332. stencilPass_ = pass;
  1333. stencilFail_ = fail;
  1334. stencilZFail_ = zFail;
  1335. }
  1336. }
  1337. #endif
  1338. }
  1339. void Graphics::SetForceSM2(bool enable)
  1340. {
  1341. }
  1342. bool Graphics::IsInitialized() const
  1343. {
  1344. return impl_->window_ != 0;
  1345. }
  1346. bool Graphics::IsDeviceLost() const
  1347. {
  1348. // On iOS treat window minimization as device loss, as it is forbidden to access OpenGL when minimized
  1349. #ifdef IOS
  1350. if (impl_->window_ && (SDL_GetWindowFlags(impl_->window_) & SDL_WINDOW_MINIMIZED) != 0)
  1351. return true;
  1352. #endif
  1353. return impl_->context_ == 0;
  1354. }
  1355. PODVector<IntVector2> Graphics::GetResolutions() const
  1356. {
  1357. PODVector<IntVector2> ret;
  1358. unsigned numModes = SDL_GetNumDisplayModes(0);
  1359. for (unsigned i = 0; i < numModes; ++i)
  1360. {
  1361. SDL_DisplayMode mode;
  1362. SDL_GetDisplayMode(0, i, &mode);
  1363. int width = mode.w;
  1364. int height = mode.h;
  1365. // Store mode if unique
  1366. bool unique = true;
  1367. for (unsigned j = 0; j < ret.Size(); ++j)
  1368. {
  1369. if (ret[j].x_ == width && ret[j].y_ == height)
  1370. {
  1371. unique = false;
  1372. break;
  1373. }
  1374. }
  1375. if (unique)
  1376. ret.Push(IntVector2(width, height));
  1377. }
  1378. return ret;
  1379. }
  1380. PODVector<int> Graphics::GetMultiSampleLevels() const
  1381. {
  1382. PODVector<int> ret;
  1383. // No multisampling always supported
  1384. ret.Push(1);
  1385. /// \todo Implement properly, if possible
  1386. return ret;
  1387. }
  1388. unsigned Graphics::GetFormat(CompressedFormat format) const
  1389. {
  1390. switch (format)
  1391. {
  1392. case CF_DXT1:
  1393. return dxtTextureSupport_ ? GL_COMPRESSED_RGBA_S3TC_DXT1_EXT : 0;
  1394. #ifndef GL_ES_VERSION_2_0
  1395. case CF_DXT3:
  1396. return dxtTextureSupport_ ? GL_COMPRESSED_RGBA_S3TC_DXT3_EXT : 0;
  1397. case CF_DXT5:
  1398. return dxtTextureSupport_ ? GL_COMPRESSED_RGBA_S3TC_DXT5_EXT : 0;
  1399. #else
  1400. case CF_ETC1:
  1401. return etcTextureSupport_ ? GL_ETC1_RGB8_OES : 0;
  1402. case CF_PVRTC_RGB_2BPP:
  1403. return pvrtcTextureSupport_ ? COMPRESSED_RGB_PVRTC_2BPPV1_IMG : 0;
  1404. case CF_PVRTC_RGB_4BPP:
  1405. return pvrtcTextureSupport_ ? COMPRESSED_RGB_PVRTC_4BPPV1_IMG : 0;
  1406. case CF_PVRTC_RGBA_2BPP:
  1407. return pvrtcTextureSupport_ ? COMPRESSED_RGBA_PVRTC_2BPPV1_IMG : 0;
  1408. case CF_PVRTC_RGBA_4BPP:
  1409. return pvrtcTextureSupport_ ? COMPRESSED_RGBA_PVRTC_4BPPV1_IMG : 0;
  1410. #endif
  1411. }
  1412. return 0;
  1413. }
  1414. VertexBuffer* Graphics::GetVertexBuffer(unsigned index) const
  1415. {
  1416. return index < MAX_VERTEX_STREAMS ? vertexBuffers_[index] : 0;
  1417. }
  1418. TextureUnit Graphics::GetTextureUnit(const String& name)
  1419. {
  1420. HashMap<String, TextureUnit>::Iterator i = textureUnits_.Find(name);
  1421. if (i != textureUnits_.End())
  1422. return i->second_;
  1423. else
  1424. return MAX_TEXTURE_UNITS;
  1425. }
  1426. const String& Graphics::GetTextureUnitName(TextureUnit unit)
  1427. {
  1428. for (HashMap<String, TextureUnit>::Iterator i = textureUnits_.Begin(); i != textureUnits_.End(); ++i)
  1429. {
  1430. if (i->second_ == unit)
  1431. return i->first_;
  1432. }
  1433. return String::EMPTY;
  1434. }
  1435. Texture* Graphics::GetTexture(unsigned index) const
  1436. {
  1437. return index < MAX_TEXTURE_UNITS ? textures_[index] : 0;
  1438. }
  1439. RenderSurface* Graphics::GetRenderTarget(unsigned index) const
  1440. {
  1441. return index < MAX_RENDERTARGETS ? renderTargets_[index] : 0;
  1442. }
  1443. IntVector2 Graphics::GetRenderTargetDimensions() const
  1444. {
  1445. int width, height;
  1446. if (renderTargets_[0])
  1447. {
  1448. width = renderTargets_[0]->GetWidth();
  1449. height = renderTargets_[0]->GetHeight();
  1450. }
  1451. else if (depthStencil_)
  1452. {
  1453. width = depthStencil_->GetWidth();
  1454. height = depthStencil_->GetHeight();
  1455. }
  1456. else
  1457. {
  1458. width = width_;
  1459. height = height_;
  1460. }
  1461. return IntVector2(width, height);
  1462. }
  1463. void Graphics::AddGPUObject(GPUObject* object)
  1464. {
  1465. gpuObjects_.Push(object);
  1466. }
  1467. void Graphics::RemoveGPUObject(GPUObject* object)
  1468. {
  1469. gpuObjects_.Erase(gpuObjects_.Find(object));
  1470. }
  1471. void* Graphics::ReserveScratchBuffer(unsigned size)
  1472. {
  1473. if (!size)
  1474. return 0;
  1475. if (size > maxScratchBufferRequest_)
  1476. maxScratchBufferRequest_ = size;
  1477. // First check for a free buffer that is large enough
  1478. for (Vector<ScratchBuffer>::Iterator i = scratchBuffers_.Begin(); i != scratchBuffers_.End(); ++i)
  1479. {
  1480. if (!i->reserved_ && i->size_ >= size)
  1481. {
  1482. i->reserved_ = true;
  1483. return i->data_.Get();
  1484. }
  1485. }
  1486. // Then check if a free buffer can be resized
  1487. for (Vector<ScratchBuffer>::Iterator i = scratchBuffers_.Begin(); i != scratchBuffers_.End(); ++i)
  1488. {
  1489. if (!i->reserved_)
  1490. {
  1491. i->data_ = new unsigned char[size];
  1492. i->size_ = size;
  1493. i->reserved_ = true;
  1494. LOGDEBUG("Resized scratch buffer to size " + String(size));
  1495. return i->data_.Get();
  1496. }
  1497. }
  1498. // Finally allocate a new buffer
  1499. ScratchBuffer newBuffer;
  1500. newBuffer.data_ = new unsigned char[size];
  1501. newBuffer.size_ = size;
  1502. newBuffer.reserved_ = true;
  1503. scratchBuffers_.Push(newBuffer);
  1504. return newBuffer.data_.Get();
  1505. LOGDEBUG("Allocated scratch buffer with size " + String(size));
  1506. }
  1507. void Graphics::FreeScratchBuffer(void* buffer)
  1508. {
  1509. if (!buffer)
  1510. return;
  1511. for (Vector<ScratchBuffer>::Iterator i = scratchBuffers_.Begin(); i != scratchBuffers_.End(); ++i)
  1512. {
  1513. if (i->reserved_ && i->data_.Get() == buffer)
  1514. {
  1515. i->reserved_ = false;
  1516. return;
  1517. }
  1518. }
  1519. LOGWARNING("Reserved scratch buffer " + ToStringHex((unsigned)buffer) + " not found");
  1520. }
  1521. void Graphics::CleanupScratchBuffers()
  1522. {
  1523. for (Vector<ScratchBuffer>::Iterator i = scratchBuffers_.Begin(); i != scratchBuffers_.End(); ++i)
  1524. {
  1525. if (!i->reserved_ && i->size_ > maxScratchBufferRequest_ * 2)
  1526. {
  1527. i->data_ = maxScratchBufferRequest_ > 0 ? new unsigned char[maxScratchBufferRequest_] : 0;
  1528. i->size_ = maxScratchBufferRequest_;
  1529. LOGDEBUG("Resized scratch buffer to size " + String(maxScratchBufferRequest_));
  1530. }
  1531. }
  1532. maxScratchBufferRequest_ = 0;
  1533. }
  1534. void Graphics::Release(bool clearGPUObjects, bool closeWindow)
  1535. {
  1536. if (!impl_->window_)
  1537. return;
  1538. if (clearGPUObjects)
  1539. {
  1540. // Shutting down: release all GPU objects that still exist
  1541. for (Vector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  1542. (*i)->Release();
  1543. gpuObjects_.Clear();
  1544. }
  1545. else
  1546. {
  1547. // We are not shutting down, but recreating the context: mark GPU objects lost
  1548. for (Vector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  1549. (*i)->OnDeviceLost();
  1550. }
  1551. CleanupFramebuffers(true);
  1552. depthTextures_.Clear();
  1553. shaderPrograms_.Clear();
  1554. if (impl_->context_)
  1555. {
  1556. // Do not log this message if we are exiting
  1557. if (!clearGPUObjects)
  1558. LOGINFO("OpenGL context lost");
  1559. MutexLock lock(GetStaticMutex());
  1560. SDL_GL_DeleteContext(impl_->context_);
  1561. impl_->context_ = 0;
  1562. }
  1563. if (closeWindow)
  1564. {
  1565. MutexLock lock(GetStaticMutex());
  1566. SDL_ShowCursor(SDL_TRUE);
  1567. // Do not destroy external window except when shutting down
  1568. if (!externalWindow_ || clearGPUObjects)
  1569. {
  1570. SDL_DestroyWindow(impl_->window_);
  1571. impl_->window_ = 0;
  1572. }
  1573. }
  1574. }
  1575. void Graphics::Restore()
  1576. {
  1577. if (!impl_->window_)
  1578. return;
  1579. // Ensure first that the context exists
  1580. if (!impl_->context_)
  1581. {
  1582. impl_->context_ = SDL_GL_CreateContext(impl_->window_);
  1583. #ifdef IOS
  1584. glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint*)&impl_->systemFbo_);
  1585. #endif
  1586. ResetCachedState();
  1587. }
  1588. if (!impl_->context_)
  1589. return;
  1590. for (Vector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  1591. (*i)->OnDeviceReset();
  1592. }
  1593. void Graphics::CleanupRenderSurface(RenderSurface* surface)
  1594. {
  1595. if (!surface)
  1596. return;
  1597. // Flush pending FBO changes first if any
  1598. CommitFramebuffer();
  1599. unsigned currentFbo = impl_->boundFbo_;
  1600. // Go through all FBOs and clean up the surface from them
  1601. for (HashMap<unsigned long long, FrameBufferObject>::Iterator i = impl_->frameBuffers_.Begin();
  1602. i != impl_->frameBuffers_.End(); ++i)
  1603. {
  1604. for (unsigned j = 0; j < MAX_RENDERTARGETS; ++j)
  1605. {
  1606. if (i->second_.colorAttachments_[j] == surface)
  1607. {
  1608. if (currentFbo != i->second_.fbo_)
  1609. {
  1610. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, i->second_.fbo_);
  1611. currentFbo = i->second_.fbo_;
  1612. }
  1613. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT + j, GL_TEXTURE_2D, 0, 0);
  1614. i->second_.colorAttachments_[j] = 0;
  1615. // Mark drawbuffer bits to need recalculation
  1616. i->second_.drawBuffers_ = M_MAX_UNSIGNED;
  1617. }
  1618. }
  1619. if (i->second_.depthAttachment_ == surface)
  1620. {
  1621. if (currentFbo != i->second_.fbo_)
  1622. {
  1623. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, i->second_.fbo_);
  1624. currentFbo = i->second_.fbo_;
  1625. }
  1626. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0);
  1627. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0);
  1628. i->second_.depthAttachment_ = 0;
  1629. }
  1630. }
  1631. // Restore previously bound FBO now if needed
  1632. if (currentFbo != impl_->boundFbo_)
  1633. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, impl_->boundFbo_);
  1634. }
  1635. unsigned Graphics::GetAlphaFormat()
  1636. {
  1637. return GL_ALPHA;
  1638. }
  1639. unsigned Graphics::GetLuminanceFormat()
  1640. {
  1641. return GL_LUMINANCE;
  1642. }
  1643. unsigned Graphics::GetLuminanceAlphaFormat()
  1644. {
  1645. return GL_LUMINANCE_ALPHA;
  1646. }
  1647. unsigned Graphics::GetRGBFormat()
  1648. {
  1649. return GL_RGB;
  1650. }
  1651. unsigned Graphics::GetRGBAFormat()
  1652. {
  1653. return GL_RGBA;
  1654. }
  1655. unsigned Graphics::GetFloatFormat()
  1656. {
  1657. #ifndef GL_ES_VERSION_2_0
  1658. return GL_LUMINANCE32F_ARB;
  1659. #else
  1660. return GL_LUMINANCE;
  1661. #endif
  1662. }
  1663. unsigned Graphics::GetLinearDepthFormat()
  1664. {
  1665. // OpenGL FBO specs state that color attachments must have the same format; therefore must encode linear depth to RGBA
  1666. // manually if not using a readable hardware depth texture
  1667. return GL_RGBA;
  1668. }
  1669. unsigned Graphics::GetDepthStencilFormat()
  1670. {
  1671. #ifndef GL_ES_VERSION_2_0
  1672. return GL_DEPTH24_STENCIL8_EXT;
  1673. #else
  1674. return GL_DEPTH_COMPONENT;
  1675. #endif
  1676. }
  1677. void Graphics::CheckFeatureSupport()
  1678. {
  1679. // Check supported features: light pre-pass, deferred rendering and hardware depth texture
  1680. lightPrepassSupport_ = false;
  1681. deferredSupport_ = false;
  1682. hardwareDepthSupport_ = false;
  1683. int numSupportedRTs = 1;
  1684. #ifndef GL_ES_VERSION_2_0
  1685. glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS_EXT, &numSupportedRTs);
  1686. // For now hardware depth texture is only tested for on NVIDIA hardware because of visual artifacts and slowdown on ATI
  1687. String vendorString = String((const char*)glGetString(GL_VENDOR)).ToUpper();
  1688. if (vendorString.Find("NVIDIA") != String::NPOS)
  1689. {
  1690. SharedPtr<Texture2D> depthTexture(new Texture2D(context_));
  1691. hardwareDepthSupport_ = true;
  1692. // Note: Texture2D::SetSize() requires hardwareDepthSupport_ == true to create a texture instead of a renderbuffer
  1693. depthTexture->SetSize(256, 256, GetDepthStencilFormat(), TEXTURE_DEPTHSTENCIL);
  1694. SetDepthStencil(depthTexture);
  1695. // If hardware depth textures work, this means also light pre-pass is automatically supported
  1696. if (CheckFramebuffer())
  1697. {
  1698. lightPrepassSupport_ = true;
  1699. if (numSupportedRTs >= 3)
  1700. deferredSupport_ = true;
  1701. }
  1702. else
  1703. hardwareDepthSupport_ = false;
  1704. ResetDepthStencil();
  1705. }
  1706. if (!hardwareDepthSupport_)
  1707. {
  1708. // If hardware depth is not supported, must support 2 rendertargets for light pre-pass, and 4 for deferred
  1709. if (numSupportedRTs >= 2)
  1710. lightPrepassSupport_ = true;
  1711. if (numSupportedRTs >= 4)
  1712. deferredSupport_ = true;
  1713. }
  1714. #else
  1715. if (!CheckExtension("GL_OES_depth_texture"))
  1716. {
  1717. shadowMapFormat_ = 0;
  1718. hiresShadowMapFormat_ = 0;
  1719. }
  1720. else
  1721. {
  1722. shadowMapFormat_ = GL_DEPTH_COMPONENT;
  1723. hiresShadowMapFormat_ = 0;
  1724. hardwareDepthSupport_ = true;
  1725. }
  1726. #endif
  1727. }
  1728. void Graphics::CommitFramebuffer()
  1729. {
  1730. if (!impl_->fboDirty_)
  1731. return;
  1732. impl_->fboDirty_ = false;
  1733. // First check if no framebuffer is needed. In that case simply return to backbuffer rendering
  1734. bool noFbo = !depthStencil_;
  1735. if (noFbo)
  1736. {
  1737. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1738. {
  1739. if (renderTargets_[i])
  1740. {
  1741. noFbo = false;
  1742. break;
  1743. }
  1744. }
  1745. }
  1746. if (noFbo)
  1747. {
  1748. if (impl_->boundFbo_ != impl_->systemFbo_)
  1749. {
  1750. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, impl_->systemFbo_);
  1751. impl_->boundFbo_ = impl_->systemFbo_;
  1752. }
  1753. return;
  1754. }
  1755. // Search for a new framebuffer based on format & size, or create new
  1756. IntVector2 rtSize = Graphics::GetRenderTargetDimensions();
  1757. unsigned format = 0;
  1758. if (renderTargets_[0])
  1759. format = renderTargets_[0]->GetParentTexture()->GetFormat();
  1760. else if (depthStencil_)
  1761. format = depthStencil_->GetParentTexture()->GetFormat();
  1762. unsigned long long fboKey = (rtSize.x_ << 16 | rtSize.y_) | (((unsigned long long)format) << 32);
  1763. HashMap<unsigned long long, FrameBufferObject>::Iterator i = impl_->frameBuffers_.Find(fboKey);
  1764. if (i == impl_->frameBuffers_.End())
  1765. {
  1766. FrameBufferObject newFbo;
  1767. glGenFramebuffersEXT(1, &newFbo.fbo_);
  1768. i = impl_->frameBuffers_.Insert(MakePair(fboKey, newFbo));
  1769. }
  1770. i->second_.useTimer_.Reset();
  1771. if (impl_->boundFbo_ != i->second_.fbo_)
  1772. {
  1773. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, i->second_.fbo_);
  1774. impl_->boundFbo_ = i->second_.fbo_;
  1775. }
  1776. #ifndef GL_ES_VERSION_2_0
  1777. // Setup readbuffers & drawbuffers if needed
  1778. if (i->second_.readBuffers_ != GL_NONE)
  1779. {
  1780. glReadBuffer(GL_NONE);
  1781. i->second_.readBuffers_ = GL_NONE;
  1782. }
  1783. // Calculate the bit combination of non-zero color rendertargets to first check if the combination changed
  1784. unsigned newDrawBuffers = 0;
  1785. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1786. {
  1787. if (renderTargets_[i])
  1788. newDrawBuffers |= 1 << i;
  1789. }
  1790. if (newDrawBuffers != i->second_.drawBuffers_)
  1791. {
  1792. // Check for no color rendertargets (depth rendering only)
  1793. if (!newDrawBuffers)
  1794. glDrawBuffer(GL_NONE);
  1795. else
  1796. {
  1797. int drawBufferIds[4];
  1798. unsigned drawBufferCount = 0;
  1799. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1800. {
  1801. if (renderTargets_[i])
  1802. drawBufferIds[drawBufferCount++] = GL_COLOR_ATTACHMENT0_EXT + i;
  1803. }
  1804. glDrawBuffers(drawBufferCount, (const GLenum*)drawBufferIds);
  1805. }
  1806. i->second_.drawBuffers_ = newDrawBuffers;
  1807. }
  1808. #endif
  1809. for (unsigned j = 0; j < MAX_RENDERTARGETS; ++j)
  1810. {
  1811. if (renderTargets_[j])
  1812. {
  1813. Texture* texture = renderTargets_[j]->GetParentTexture();
  1814. // If texture's parameters are dirty, update before attaching
  1815. if (texture->GetParametersDirty())
  1816. {
  1817. SetTextureForUpdate(texture);
  1818. texture->UpdateParameters();
  1819. SetTexture(0, 0);
  1820. }
  1821. if (i->second_.colorAttachments_[j] != renderTargets_[j])
  1822. {
  1823. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT + j, renderTargets_[j]->GetTarget(),
  1824. texture->GetGPUObject(), 0);
  1825. i->second_.colorAttachments_[j] = renderTargets_[j];
  1826. }
  1827. }
  1828. else
  1829. {
  1830. if (i->second_.colorAttachments_[j])
  1831. {
  1832. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT + j, GL_TEXTURE_2D, 0, 0);
  1833. i->second_.colorAttachments_[j] = 0;
  1834. }
  1835. }
  1836. }
  1837. if (depthStencil_)
  1838. {
  1839. // Bind either a renderbuffer or a depth texture, depending on what is available
  1840. Texture* texture = depthStencil_->GetParentTexture();
  1841. #ifndef GL_ES_VERSION_2_0
  1842. bool hasStencil = texture->GetFormat() == GetDepthStencilFormat();
  1843. #else
  1844. bool hasStencil = false;
  1845. #endif
  1846. unsigned renderBufferID = depthStencil_->GetRenderBuffer();
  1847. if (!renderBufferID)
  1848. {
  1849. // If texture's parameters are dirty, update before attaching
  1850. if (texture->GetParametersDirty())
  1851. {
  1852. SetTextureForUpdate(texture);
  1853. texture->UpdateParameters();
  1854. SetTexture(0, 0);
  1855. }
  1856. if (i->second_.depthAttachment_ != depthStencil_)
  1857. {
  1858. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, texture->GetGPUObject(), 0);
  1859. if (hasStencil)
  1860. {
  1861. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D,
  1862. texture->GetGPUObject(), 0);
  1863. }
  1864. else
  1865. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0);
  1866. i->second_.depthAttachment_ = depthStencil_;
  1867. }
  1868. }
  1869. else
  1870. {
  1871. if (i->second_.depthAttachment_ != depthStencil_)
  1872. {
  1873. glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, renderBufferID);
  1874. if (hasStencil)
  1875. {
  1876. glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT,
  1877. renderBufferID);
  1878. }
  1879. else
  1880. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0);
  1881. i->second_.depthAttachment_ = depthStencil_;
  1882. }
  1883. }
  1884. }
  1885. else
  1886. {
  1887. if (i->second_.depthAttachment_)
  1888. {
  1889. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0);
  1890. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0);
  1891. i->second_.depthAttachment_ = 0;
  1892. }
  1893. }
  1894. }
  1895. bool Graphics::CheckFramebuffer()
  1896. {
  1897. return glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT) == GL_FRAMEBUFFER_COMPLETE_EXT;
  1898. }
  1899. void Graphics::CleanupFramebuffers(bool contextLost)
  1900. {
  1901. if (!contextLost)
  1902. {
  1903. for (HashMap<unsigned long long, FrameBufferObject>::Iterator i = impl_->frameBuffers_.Begin();
  1904. i != impl_->frameBuffers_.End();)
  1905. {
  1906. HashMap<unsigned long long, FrameBufferObject>::Iterator current = i++;
  1907. if (current->second_.fbo_ != impl_->boundFbo_ && current->second_.useTimer_.GetMSec(false) >
  1908. MAX_FRAMEBUFFER_AGE)
  1909. {
  1910. glDeleteFramebuffersEXT(1, &current->second_.fbo_);
  1911. impl_->frameBuffers_.Erase(current);
  1912. }
  1913. }
  1914. }
  1915. else
  1916. {
  1917. impl_->boundFbo_ = 0;
  1918. impl_->frameBuffers_.Clear();
  1919. }
  1920. }
  1921. void Graphics::ResetCachedState()
  1922. {
  1923. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  1924. {
  1925. vertexBuffers_[i] = 0;
  1926. elementMasks_[i] = 0;
  1927. }
  1928. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1929. {
  1930. textures_[i] = 0;
  1931. textureTypes_[i] = 0;
  1932. }
  1933. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1934. renderTargets_[i] = 0;
  1935. depthStencil_ = 0;
  1936. viewTexture_ = 0;
  1937. viewport_ = IntRect(0, 0, 0, 0);
  1938. indexBuffer_ = 0;
  1939. vertexShader_ = 0;
  1940. pixelShader_ = 0;
  1941. shaderProgram_ = 0;
  1942. blendMode_ = BLEND_REPLACE;
  1943. textureAnisotropy_ = 1;
  1944. colorWrite_ = true;
  1945. cullMode_ = CULL_NONE;
  1946. constantDepthBias_ = 0.0f;
  1947. slopeScaledDepthBias_ = 0.0f;
  1948. depthTestMode_ = CMP_ALWAYS;
  1949. depthWrite_ = false;
  1950. scissorTest_ = false;
  1951. scissorRect_ = IntRect::ZERO;
  1952. stencilTest_ = false;
  1953. stencilTestMode_ = CMP_ALWAYS;
  1954. stencilPass_ = OP_KEEP;
  1955. stencilFail_ = OP_KEEP;
  1956. stencilZFail_ = OP_KEEP;
  1957. stencilRef_ = 0;
  1958. stencilCompareMask_ = M_MAX_UNSIGNED;
  1959. stencilWriteMask_ = M_MAX_UNSIGNED;
  1960. impl_->activeTexture_ = 0;
  1961. impl_->enabledAttributes_ = 0;
  1962. impl_->boundFbo_ = impl_->systemFbo_;
  1963. // Set initial state to match Direct3D
  1964. if (impl_->context_)
  1965. {
  1966. glEnable(GL_DEPTH_TEST);
  1967. SetCullMode(CULL_CCW);
  1968. SetDepthTest(CMP_LESSEQUAL);
  1969. SetDepthWrite(true);
  1970. }
  1971. }
  1972. void Graphics::SetTextureUnitMappings()
  1973. {
  1974. textureUnits_["DiffMap"] = TU_DIFFUSE;
  1975. textureUnits_["DiffCubeMap"] = TU_DIFFUSE;
  1976. textureUnits_["NormalMap"] = TU_NORMAL;
  1977. textureUnits_["SpecMap"] = TU_SPECULAR;
  1978. textureUnits_["EmissiveMap"] = TU_EMISSIVE;
  1979. textureUnits_["EnvironmentMap"] = TU_ENVIRONMENT;
  1980. textureUnits_["EnvironmentCubeMap"] = TU_ENVIRONMENT;
  1981. textureUnits_["LightRampMap"] = TU_LIGHTRAMP;
  1982. textureUnits_["LightSpotMap"] = TU_LIGHTSHAPE;
  1983. textureUnits_["LightCubeMap"] = TU_LIGHTSHAPE;
  1984. textureUnits_["ShadowMap"] = TU_SHADOWMAP;
  1985. textureUnits_["FaceSelectCubeMap"] = TU_FACESELECT;
  1986. textureUnits_["IndirectionCubeMap"] = TU_INDIRECTION;
  1987. textureUnits_["AlbedoBuffer"] = TU_ALBEDOBUFFER;
  1988. textureUnits_["NormalBuffer"] = TU_NORMALBUFFER;
  1989. textureUnits_["DepthBuffer"] = TU_DEPTHBUFFER;
  1990. textureUnits_["LightBuffer"] = TU_LIGHTBUFFER;
  1991. }
  1992. void RegisterGraphicsLibrary(Context* context)
  1993. {
  1994. Animation::RegisterObject(context);
  1995. Material::RegisterObject(context);
  1996. Model::RegisterObject(context);
  1997. Shader::RegisterObject(context);
  1998. Technique::RegisterObject(context);
  1999. Texture2D::RegisterObject(context);
  2000. TextureCube::RegisterObject(context);
  2001. Camera::RegisterObject(context);
  2002. Drawable::RegisterObject(context);
  2003. Light::RegisterObject(context);
  2004. StaticModel::RegisterObject(context);
  2005. Skybox::RegisterObject(context);
  2006. AnimatedModel::RegisterObject(context);
  2007. AnimationController::RegisterObject(context);
  2008. BillboardSet::RegisterObject(context);
  2009. ParticleEmitter::RegisterObject(context);
  2010. DecalSet::RegisterObject(context);
  2011. Terrain::RegisterObject(context);
  2012. TerrainPatch::RegisterObject(context);
  2013. DebugRenderer::RegisterObject(context);
  2014. Octree::RegisterObject(context);
  2015. Zone::RegisterObject(context);
  2016. }