OGLGraphics.cpp 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 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 "Graphics.h"
  32. #include "GraphicsEvents.h"
  33. #include "GraphicsImpl.h"
  34. #include "IndexBuffer.h"
  35. #include "Light.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 "Technique.h"
  49. #include "Texture2D.h"
  50. #include "TextureCube.h"
  51. #include "VertexBuffer.h"
  52. #include "Zone.h"
  53. #include <stdio.h>
  54. #ifdef _MSC_VER
  55. #include <float.h>
  56. #else
  57. // From http://stereopsis.com/FPU.html
  58. #define FPU_CW_PREC_MASK 0x0300
  59. #define FPU_CW_PREC_SINGLE 0x0000
  60. #define FPU_CW_PREC_DOUBLE 0x0200
  61. #define FPU_CW_PREC_EXTENDED 0x0300
  62. #define FPU_CW_ROUND_MASK 0x0c00
  63. #define FPU_CW_ROUND_NEAR 0x0000
  64. #define FPU_CW_ROUND_DOWN 0x0400
  65. #define FPU_CW_ROUND_UP 0x0800
  66. #define FPU_CW_ROUND_CHOP 0x0c00
  67. inline unsigned GetFPUState()
  68. {
  69. unsigned control = 0;
  70. __asm__ __volatile__ ("fnstcw %0" : "=m" (control));
  71. return control;
  72. }
  73. inline void SetFPUState(unsigned control)
  74. {
  75. __asm__ __volatile__ ("fldcw %0" : : "m" (control));
  76. }
  77. #endif
  78. #include "DebugNew.h"
  79. static const unsigned glCmpFunc[] =
  80. {
  81. GL_ALWAYS,
  82. GL_EQUAL,
  83. GL_NOTEQUAL,
  84. GL_LESS,
  85. GL_LEQUAL,
  86. GL_GREATER,
  87. GL_GEQUAL
  88. };
  89. static const unsigned glSrcBlend[] =
  90. {
  91. GL_ONE,
  92. GL_ONE,
  93. GL_DST_COLOR,
  94. GL_SRC_ALPHA,
  95. GL_SRC_ALPHA,
  96. GL_ONE,
  97. GL_ONE_MINUS_DST_ALPHA
  98. };
  99. static const unsigned glDestBlend[] =
  100. {
  101. GL_ZERO,
  102. GL_ONE,
  103. GL_ZERO,
  104. GL_ONE_MINUS_SRC_ALPHA,
  105. GL_ONE,
  106. GL_ONE_MINUS_SRC_ALPHA,
  107. GL_DST_ALPHA
  108. };
  109. static const unsigned glStencilOps[] =
  110. {
  111. GL_KEEP,
  112. GL_ZERO,
  113. GL_REPLACE,
  114. GL_INCR_WRAP,
  115. GL_DECR_WRAP
  116. };
  117. static unsigned numInstances = 0;
  118. static const String noParameter;
  119. int CloseCallback(GLFWwindow window)
  120. {
  121. // Do not let GLFW close the window, rather do it ourselves in a controlled fashion
  122. Context* context = GetWindowContext(window);
  123. if (context)
  124. {
  125. Graphics* graphics = context->GetSubsystem<Graphics>();
  126. if (graphics)
  127. graphics->Close();
  128. }
  129. return GL_FALSE;
  130. }
  131. OBJECTTYPESTATIC(Graphics);
  132. Graphics::Graphics(Context* context_) :
  133. Object(context_),
  134. impl_(new GraphicsImpl()),
  135. mode_(RENDER_FORWARD),
  136. width_(0),
  137. height_(0),
  138. multiSample_(1),
  139. fullscreen_(false),
  140. vsync_(false),
  141. flushGPU_(true),
  142. renderTargetSupport_(false),
  143. deferredSupport_(false),
  144. numPrimitives_(0),
  145. numBatches_(0),
  146. immediateVertexCount_(0),
  147. defaultTextureFilterMode_(FILTER_BILINEAR),
  148. shadowMapFormat_(0),
  149. hiresShadowMapFormat_(0),
  150. shaderParameterFrame_(0)
  151. {
  152. ResetCachedState();
  153. SetTextureUnitMappings();
  154. {
  155. MutexLock lock(GetStaticMutex());
  156. if (!numInstances)
  157. glfwInit();
  158. ++numInstances;
  159. }
  160. }
  161. Graphics::~Graphics()
  162. {
  163. Close();
  164. delete impl_;
  165. impl_ = 0;
  166. {
  167. MutexLock lock(GetStaticMutex());
  168. --numInstances;
  169. if (!numInstances)
  170. glfwTerminate();
  171. }
  172. }
  173. void Graphics::SetWindowTitle(const String& windowTitle)
  174. {
  175. windowTitle_ = windowTitle;
  176. if (impl_->window_)
  177. glfwSetWindowTitle(impl_->window_, windowTitle_.CString());
  178. }
  179. bool Graphics::SetMode(RenderMode mode, int width, int height, bool fullscreen, bool vsync, int multiSample)
  180. {
  181. PROFILE(SetScreenMode);
  182. multiSample = Clamp(multiSample, 1, 16);
  183. if (IsInitialized() && mode == mode_ && width == width_ && height == height_ && fullscreen == fullscreen_ &&
  184. vsync == vsync_ && multiSample == multiSample_)
  185. return true;
  186. // If only vsync changes, do not destroy/recreate the context
  187. if (IsInitialized() && mode == mode_ && width == width_ && height == height_ && fullscreen == fullscreen_ &&
  188. multiSample == multiSample_ && vsync != vsync_)
  189. {
  190. glfwSwapInterval(vsync ? 1 : 0);
  191. vsync_ = vsync;
  192. return true;
  193. }
  194. // If zero dimensions in windowed mode, set default. If zero in fullscreen, use desktop mode
  195. if (!width || !height)
  196. {
  197. if (!fullscreen)
  198. {
  199. width = 800;
  200. height = 600;
  201. }
  202. else
  203. {
  204. GLFWvidmode mode;
  205. glfwGetDesktopMode(&mode);
  206. width = mode.width;
  207. height = mode.height;
  208. }
  209. }
  210. // Close the existing window
  211. Release();
  212. {
  213. // GLFW window parameters and the window list are static, so need to operate under static lock
  214. MutexLock lock(GetStaticMutex());
  215. glfwOpenWindowHint(GLFW_RED_BITS, 8);
  216. glfwOpenWindowHint(GLFW_GREEN_BITS, 8);
  217. glfwOpenWindowHint(GLFW_BLUE_BITS, 8);
  218. glfwOpenWindowHint(GLFW_ALPHA_BITS, 0);
  219. glfwOpenWindowHint(GLFW_DEPTH_BITS, 24);
  220. glfwOpenWindowHint(GLFW_STENCIL_BITS, 8);
  221. glfwOpenWindowHint(GLFW_WINDOW_NO_RESIZE, GL_TRUE);
  222. if (multiSample > 1 && mode == RENDER_FORWARD)
  223. glfwOpenWindowHint(GLFW_FSAA_SAMPLES, multiSample);
  224. else
  225. glfwOpenWindowHint(GLFW_FSAA_SAMPLES, 0);
  226. impl_->window_ = glfwOpenWindow(width, height, fullscreen ? GLFW_FULLSCREEN : GLFW_WINDOWED, windowTitle_.CString(), 0);
  227. if (!impl_->window_)
  228. {
  229. LOGERROR("Could not open window");
  230. return false;
  231. }
  232. // If OpenGL extensions not yet initialized, initialize now
  233. if (!GLeeInitialized())
  234. GLeeInit();
  235. if (!_GLEE_VERSION_2_0)
  236. {
  237. LOGERROR("OpenGL 2.0 is required");
  238. glfwCloseWindow(impl_->window_);
  239. return false;
  240. }
  241. // Set window close callback
  242. glfwSetWindowCloseCallback(CloseCallback);
  243. // Mimic Direct3D way of setting FPU into round-to-nearest, single precision mode
  244. // This is actually needed for ODE to behave predictably in float mode
  245. #ifdef _MSC_VER
  246. _controlfp(_RC_NEAR | _PC_24, _MCW_RC | _MCW_PC);
  247. #else
  248. unsigned control = GetFPUState();
  249. control &= ~(FPU_CW_PREC_MASK | FPU_CW_ROUND_MASK);
  250. control |= (FPU_CW_PREC_SINGLE | FPU_CW_ROUND_NEAR);
  251. SetFPUState(control);
  252. #endif
  253. // Associate GLFW window with the execution context
  254. SetWindowContext(impl_->window_, context_);
  255. }
  256. // Set vsync
  257. glfwSwapInterval(vsync ? 1 : 0);
  258. // Query for system backbuffer depth
  259. glGetIntegerv(GL_DEPTH_BITS, &impl_->windowDepthBits_);
  260. impl_->depthBits_ = impl_->windowDepthBits_;
  261. // Create the FBO if fully supported
  262. if (_GLEE_EXT_framebuffer_object && _GLEE_EXT_packed_depth_stencil)
  263. {
  264. glGenFramebuffersEXT(1, &impl_->fbo_);
  265. // Shadows, render targets and deferred rendering all depend on FBO & packed depth stencil
  266. shadowMapFormat_ = GL_DEPTH_COMPONENT16;
  267. hiresShadowMapFormat_ = GL_DEPTH_COMPONENT24;
  268. renderTargetSupport_ = true;
  269. deferredSupport_ = true;
  270. }
  271. // Set initial state to match Direct3D
  272. glEnable(GL_DEPTH_TEST);
  273. SetCullMode(CULL_CCW);
  274. SetDepthTest(CMP_LESSEQUAL);
  275. glfwGetWindowSize(impl_->window_, &width_, &height_);
  276. fullscreen_ = fullscreen;
  277. vsync_ = vsync;
  278. mode_ = mode;
  279. multiSample_ = multiSample;
  280. // Reset rendertargets and viewport for the new screen mode
  281. ResetRenderTargets();
  282. viewTexture_ = 0;
  283. // Clear the window to black now, because GPU object restore may take time
  284. Clear(CLEAR_COLOR);
  285. glfwSwapBuffers();
  286. // Create deferred rendering buffers as necessary
  287. CreateRenderTargets();
  288. // Let GPU objects restore themselves
  289. for (Vector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  290. (*i)->OnDeviceReset();
  291. if (multiSample > 1)
  292. LOGINFO("Set screen mode " + String(width_) + "x" + String(height_) + " " + (fullscreen_ ? "fullscreen" : "windowed") +
  293. " multisample " + String(multiSample));
  294. else
  295. LOGINFO("Set screen mode " + String(width_) + "x" + String(height_) + " " + (fullscreen_ ? "fullscreen" : "windowed"));
  296. using namespace ScreenMode;
  297. VariantMap eventData;
  298. eventData[P_WIDTH] = width_;
  299. eventData[P_HEIGHT] = height_;
  300. eventData[P_FULLSCREEN] = fullscreen_;
  301. SendEvent(E_SCREENMODE, eventData);
  302. return true;
  303. }
  304. bool Graphics::SetMode(int width, int height)
  305. {
  306. return SetMode(mode_, width, height, fullscreen_, vsync_, multiSample_);
  307. }
  308. bool Graphics::SetMode(RenderMode mode)
  309. {
  310. return SetMode(mode, width_, height_, fullscreen_, vsync_, multiSample_);
  311. }
  312. bool Graphics::ToggleFullscreen()
  313. {
  314. return SetMode(mode_, width_, height_, !fullscreen_, vsync_, multiSample_);
  315. }
  316. void Graphics::Close()
  317. {
  318. if (!IsInitialized())
  319. return;
  320. // Release all GPU objects that still exist
  321. for (Vector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  322. (*i)->Release();
  323. gpuObjects_.Clear();
  324. // Actually close the window
  325. Release();
  326. }
  327. bool Graphics::TakeScreenShot(Image& destImage)
  328. {
  329. PROFILE(TakeScreenShot);
  330. ResetRenderTargets();
  331. destImage.SetSize(width_, height_, 3);
  332. glReadPixels(0, 0, width_, height_, GL_RGB, GL_UNSIGNED_BYTE, destImage.GetData());
  333. return true;
  334. }
  335. void Graphics::SetFlushGPU(bool enable)
  336. {
  337. flushGPU_ = enable;
  338. }
  339. bool Graphics::BeginFrame()
  340. {
  341. PROFILE(BeginRendering);
  342. if (!IsInitialized())
  343. return false;
  344. // If we should be fullscreen, but are not currently active, do not render
  345. if (fullscreen_ && (!glfwGetWindowParam(impl_->window_, GLFW_ACTIVE) || glfwGetWindowParam(impl_->window_, GLFW_ICONIFIED)))
  346. return false;
  347. // Set default rendertarget and depth buffer
  348. ResetRenderTargets();
  349. viewTexture_ = 0;
  350. // Cleanup textures from previous frame
  351. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  352. SetTexture(i, 0);
  353. // Enable color and depth write
  354. SetColorWrite(true);
  355. SetDepthWrite(true);
  356. numPrimitives_ = 0;
  357. numBatches_ = 0;
  358. SendEvent(E_BEGINRENDERING);
  359. return true;
  360. }
  361. void Graphics::EndFrame()
  362. {
  363. PROFILE(EndRendering);
  364. if (!IsInitialized())
  365. return;
  366. SendEvent(E_ENDRENDERING);
  367. glfwSwapBuffers();
  368. }
  369. void Graphics::Clear(unsigned flags, const Color& color, float depth, unsigned stencil)
  370. {
  371. bool oldColorWrite = colorWrite_;
  372. bool oldDepthWrite = depthWrite_;
  373. if (flags & CLEAR_COLOR && !oldColorWrite)
  374. SetColorWrite(true);
  375. if (flags & CLEAR_DEPTH && !oldDepthWrite)
  376. SetDepthWrite(true);
  377. unsigned glFlags = 0;
  378. if (flags & CLEAR_COLOR)
  379. {
  380. glFlags |= GL_COLOR_BUFFER_BIT;
  381. glClearColor(color.r_, color.g_, color.b_, color.a_);
  382. }
  383. if (flags & CLEAR_DEPTH)
  384. {
  385. glFlags |= GL_DEPTH_BUFFER_BIT;
  386. glClearDepth(depth);
  387. }
  388. if (flags & CLEAR_STENCIL)
  389. {
  390. glFlags |= GL_STENCIL_BUFFER_BIT;
  391. glClearStencil(stencil);
  392. }
  393. glClear(glFlags);
  394. SetColorWrite(oldColorWrite);
  395. SetDepthWrite(oldDepthWrite);
  396. }
  397. void Graphics::Draw(PrimitiveType type, unsigned vertexStart, unsigned vertexCount)
  398. {
  399. if (!vertexCount)
  400. return;
  401. unsigned primitiveCount = 0;
  402. switch (type)
  403. {
  404. case TRIANGLE_LIST:
  405. primitiveCount = vertexCount / 3;
  406. glDrawArrays(GL_TRIANGLES, vertexStart, vertexCount);
  407. break;
  408. case LINE_LIST:
  409. primitiveCount = vertexCount / 2;
  410. glDrawArrays(GL_LINES, vertexStart, vertexCount);
  411. break;
  412. }
  413. numPrimitives_ += primitiveCount;
  414. ++numBatches_;
  415. }
  416. void Graphics::Draw(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned minVertex, unsigned vertexCount)
  417. {
  418. if (!indexCount || !indexBuffer_)
  419. return;
  420. unsigned primitiveCount = 0;
  421. unsigned indexSize = indexBuffer_->GetIndexSize();
  422. switch (type)
  423. {
  424. case TRIANGLE_LIST:
  425. primitiveCount = indexCount / 3;
  426. if (indexSize == sizeof(unsigned short))
  427. glDrawElements(GL_TRIANGLES, indexCount, GL_UNSIGNED_SHORT, (const GLvoid*)(indexStart * indexSize));
  428. else
  429. glDrawElements(GL_TRIANGLES, indexCount, GL_UNSIGNED_INT, (const GLvoid*)(indexStart * indexSize));
  430. break;
  431. case LINE_LIST:
  432. primitiveCount = indexCount / 2;
  433. if (indexSize == sizeof(unsigned short))
  434. glDrawElements(GL_LINES, indexCount, GL_UNSIGNED_SHORT, (const GLvoid*)(indexStart * indexSize));
  435. else
  436. glDrawElements(GL_LINES, indexCount, GL_UNSIGNED_INT, (const GLvoid*)(indexStart * indexSize));
  437. break;
  438. }
  439. numPrimitives_ += primitiveCount;
  440. ++numBatches_;
  441. }
  442. void Graphics::DrawInstanced(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned minVertex, unsigned vertexCount, unsigned instanceCount)
  443. {
  444. }
  445. void Graphics::SetVertexBuffer(VertexBuffer* buffer)
  446. {
  447. Vector<VertexBuffer*> vertexBuffers(1);
  448. PODVector<unsigned> elementMasks(1);
  449. vertexBuffers[0] = buffer;
  450. elementMasks[0] = MASK_DEFAULT;
  451. SetVertexBuffers(vertexBuffers, elementMasks);
  452. }
  453. bool Graphics::SetVertexBuffers(const Vector<VertexBuffer*>& buffers, const PODVector<unsigned>& elementMasks,
  454. unsigned instanceOffset)
  455. {
  456. if (buffers.Size() > MAX_VERTEX_STREAMS)
  457. {
  458. LOGERROR("Too many vertex buffers");
  459. return false;
  460. }
  461. if (buffers.Size() != elementMasks.Size())
  462. {
  463. LOGERROR("Amount of element masks and vertex buffers does not match");
  464. return false;
  465. }
  466. // If no valid shader to determine the attribute bindings, can not set vertex buffers
  467. if (!shaderProgram_)
  468. return false;
  469. const int* attributeLocations = shaderProgram_->GetAttributeLocations();
  470. bool changed = false;
  471. unsigned newAttributes = 0;
  472. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  473. {
  474. VertexBuffer* buffer = 0;
  475. unsigned elementMask = 0;
  476. if (i < buffers.Size())
  477. {
  478. buffer = buffers[i];
  479. elementMask = elementMasks[i];
  480. if (elementMask == MASK_DEFAULT && buffer)
  481. elementMask = buffers[i]->GetElementMask();
  482. }
  483. // If buffer and element mask have stayed the same, skip to the next buffer
  484. if (buffer == vertexBuffers_[i] && elementMask == elementMasks_[i])
  485. continue;
  486. vertexBuffers_[i] = buffer;
  487. elementMasks_[i] = elementMask;
  488. changed = true;
  489. if (!buffer)
  490. continue;
  491. glBindBuffer(GL_ARRAY_BUFFER, buffer->GetGPUObject());
  492. unsigned vertexSize = buffer->GetVertexSize();
  493. for (unsigned j = 0; j < MAX_VERTEX_ELEMENTS; ++j)
  494. {
  495. // If shader does not use the attribute, do not bind it (bandwidth optimization)
  496. int attributeIndex = attributeLocations[j];
  497. if (attributeIndex < 0)
  498. continue;
  499. unsigned elementBit = 1 << j;
  500. unsigned attributeBit = 1 << attributeIndex;
  501. if (elementMask & elementBit)
  502. {
  503. newAttributes |= attributeBit;
  504. // Enable attribute if not enabled yet
  505. if ((impl_->enabledAttributes_ & attributeBit) == 0)
  506. {
  507. glEnableVertexAttribArray(attributeIndex);
  508. impl_->enabledAttributes_ |= attributeBit;
  509. }
  510. // Set the attribute pointer
  511. glVertexAttribPointer(attributeIndex, VertexBuffer::elementComponents[j], VertexBuffer::elementType[j],
  512. VertexBuffer::elementNormalize[j], vertexSize, (const GLvoid*)(buffer->GetElementOffset((VertexElement)j)));
  513. }
  514. }
  515. }
  516. if (!changed)
  517. return true;
  518. // Now check which vertex attributes should be disabled
  519. unsigned disableAttributes = impl_->enabledAttributes_ & (~newAttributes);
  520. int disableIndex = 0;
  521. while (disableAttributes)
  522. {
  523. if (disableAttributes & 1)
  524. {
  525. glDisableVertexAttribArray(disableIndex);
  526. impl_->enabledAttributes_ &= ~(1 << disableIndex);
  527. }
  528. disableAttributes >>= 1;
  529. ++disableIndex;
  530. }
  531. return true;
  532. }
  533. bool Graphics::SetVertexBuffers(const Vector<SharedPtr<VertexBuffer> >& buffers, const PODVector<unsigned>&
  534. elementMasks, unsigned instanceOffset)
  535. {
  536. if (buffers.Size() > MAX_VERTEX_STREAMS)
  537. {
  538. LOGERROR("Too many vertex buffers");
  539. return false;
  540. }
  541. if (buffers.Size() != elementMasks.Size())
  542. {
  543. LOGERROR("Amount of element masks and vertex buffers does not match");
  544. return false;
  545. }
  546. // If no valid shader to determine the attribute bindings, can not set vertex buffers
  547. if (!shaderProgram_)
  548. return false;
  549. const int* attributeLocations = shaderProgram_->GetAttributeLocations();
  550. bool changed = false;
  551. unsigned newAttributes = 0;
  552. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  553. {
  554. VertexBuffer* buffer = 0;
  555. unsigned elementMask = 0;
  556. if (i < buffers.Size())
  557. {
  558. buffer = buffers[i];
  559. elementMask = elementMasks[i];
  560. if (elementMask == MASK_DEFAULT && buffer)
  561. elementMask = buffers[i]->GetElementMask();
  562. }
  563. // If buffer and element mask have stayed the same, skip to the next buffer
  564. if (buffer == vertexBuffers_[i] && elementMask == elementMasks_[i])
  565. continue;
  566. vertexBuffers_[i] = buffer;
  567. elementMasks_[i] = elementMask;
  568. changed = true;
  569. if (!buffer)
  570. continue;
  571. glBindBuffer(GL_ARRAY_BUFFER, buffer->GetGPUObject());
  572. unsigned vertexSize = buffer->GetVertexSize();
  573. for (unsigned j = 0; j < MAX_VERTEX_ELEMENTS; ++j)
  574. {
  575. // If shader does not use the attribute, do not bind it (bandwidth optimization)
  576. int attributeIndex = attributeLocations[j];
  577. if (attributeIndex < 0)
  578. continue;
  579. unsigned elementBit = 1 << j;
  580. unsigned attributeBit = 1 << attributeIndex;
  581. if (elementMask & elementBit)
  582. {
  583. newAttributes |= attributeBit;
  584. // Enable attribute if not enabled yet
  585. if ((impl_->enabledAttributes_ & attributeBit) == 0)
  586. {
  587. glEnableVertexAttribArray(attributeIndex);
  588. impl_->enabledAttributes_ |= attributeBit;
  589. }
  590. // Set the attribute pointer
  591. glVertexAttribPointer(attributeIndex, VertexBuffer::elementComponents[j], VertexBuffer::elementType[j],
  592. VertexBuffer::elementNormalize[j], vertexSize, (const GLvoid*)(buffer->GetElementOffset((VertexElement)j)));
  593. }
  594. }
  595. }
  596. if (!changed)
  597. return true;
  598. // Now check which vertex attributes should be disabled
  599. unsigned disableAttributes = impl_->enabledAttributes_ & (~newAttributes);
  600. int disableIndex = 0;
  601. while (disableAttributes)
  602. {
  603. if (disableAttributes & 1)
  604. {
  605. glDisableVertexAttribArray(disableIndex);
  606. impl_->enabledAttributes_ &= ~(1 << disableIndex);
  607. }
  608. disableAttributes >>= 1;
  609. ++disableIndex;
  610. }
  611. return true;
  612. }
  613. void Graphics::SetIndexBuffer(IndexBuffer* buffer)
  614. {
  615. if (indexBuffer_ == buffer)
  616. return;
  617. if (buffer)
  618. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer->GetGPUObject());
  619. else
  620. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
  621. indexBuffer_ = buffer;
  622. }
  623. void Graphics::SetShaders(ShaderVariation* vs, ShaderVariation* ps)
  624. {
  625. if (vs == vertexShader_ && ps == pixelShader_)
  626. return;
  627. // Compile the shaders now if not yet compiled. If already attempted, do not retry
  628. if (vs && !vs->IsCompiled())
  629. {
  630. if (vs->GetCompilerOutput().Empty())
  631. {
  632. PROFILE(CompileVertexShader);
  633. bool success = vs->Create();
  634. if (success)
  635. LOGDEBUG("Compiled vertex shader " + vs->GetName());
  636. else
  637. {
  638. LOGERROR("Failed to compile vertex shader " + vs->GetName() + ":\n" + vs->GetCompilerOutput());
  639. vs = 0;
  640. }
  641. }
  642. else
  643. vs = 0;
  644. }
  645. if (ps && !ps->IsCompiled())
  646. {
  647. if (ps->GetCompilerOutput().Empty())
  648. {
  649. PROFILE(CompilePixelShader);
  650. bool success = ps->Create();
  651. if (success)
  652. LOGDEBUG("Compiled pixel shader " + ps->GetName());
  653. else
  654. {
  655. LOGERROR("Failed to compile pixel shader " + ps->GetName() + ":\n" + ps->GetCompilerOutput());
  656. ps = 0;
  657. }
  658. }
  659. else
  660. ps = 0;
  661. }
  662. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  663. {
  664. vertexBuffers_[i] = 0;
  665. elementMasks_[i] = 0;
  666. }
  667. if (!vs || !ps)
  668. {
  669. glUseProgram(0);
  670. vertexShader_ = 0;
  671. pixelShader_ = 0;
  672. shaderProgram_ = 0;
  673. }
  674. else
  675. {
  676. vertexShader_ = vs;
  677. pixelShader_ = ps;
  678. Pair<ShaderVariation*, ShaderVariation*> combination(vs, ps);
  679. ShaderProgramMap::Iterator i = shaderPrograms_.Find(combination);
  680. if (i != shaderPrograms_.End())
  681. {
  682. // Use the existing linked program
  683. if (i->second_->IsLinked())
  684. {
  685. glUseProgram(i->second_->GetGPUObject());
  686. shaderProgram_ = i->second_;
  687. }
  688. else
  689. {
  690. glUseProgram(0);
  691. shaderProgram_ = 0;
  692. }
  693. }
  694. else
  695. {
  696. // Link a new combination
  697. SharedPtr<ShaderProgram> newProgram(new ShaderProgram(this, vs, ps));
  698. if (newProgram->Link())
  699. {
  700. LOGDEBUG("Linked vertex shader " + vs->GetName() + " and pixel shader " + ps->GetName());
  701. // Note: Link() calls glUseProgram() to set the texture sampler uniforms,
  702. // so it is not necessary to call it again
  703. shaderProgram_ = newProgram;
  704. }
  705. else
  706. {
  707. LOGERROR("Failed to link vertex shader " + vs->GetName() + " and pixel shader " + ps->GetName() + ":\n" +
  708. newProgram->GetLinkerOutput());
  709. glUseProgram(0);
  710. shaderProgram_ = 0;
  711. }
  712. shaderPrograms_[combination] = newProgram;
  713. }
  714. }
  715. }
  716. void Graphics::SetShaderParameter(StringHash param, const bool* data, unsigned count)
  717. {
  718. // Not supported
  719. }
  720. void Graphics::SetShaderParameter(StringHash param, const float* data, unsigned count)
  721. {
  722. if (shaderProgram_)
  723. {
  724. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  725. if (info)
  726. {
  727. switch (info->type_)
  728. {
  729. case GL_FLOAT:
  730. glUniform1fv(info->location_, count, data);
  731. break;
  732. case GL_FLOAT_VEC2:
  733. glUniform2fv(info->location_, count / 2, data);
  734. break;
  735. case GL_FLOAT_VEC3:
  736. glUniform3fv(info->location_, count / 3, data);
  737. break;
  738. case GL_FLOAT_VEC4:
  739. glUniform4fv(info->location_, count / 4, data);
  740. break;
  741. case GL_FLOAT_MAT3:
  742. glUniformMatrix3fv(info->location_, count / 9, GL_TRUE, data);
  743. break;
  744. case GL_FLOAT_MAT4:
  745. glUniformMatrix4fv(info->location_, count / 16, GL_TRUE, data);
  746. break;
  747. }
  748. }
  749. }
  750. }
  751. void Graphics::SetShaderParameter(StringHash param, const int* data, unsigned count)
  752. {
  753. if (shaderProgram_)
  754. {
  755. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  756. if (info)
  757. {
  758. switch (info->type_)
  759. {
  760. case GL_INT:
  761. glUniform1iv(info->location_, count, data);
  762. break;
  763. case GL_INT_VEC2:
  764. glUniform2iv(info->location_, count / 2, data);
  765. break;
  766. case GL_INT_VEC3:
  767. glUniform3iv(info->location_, count / 3, data);
  768. break;
  769. case GL_INT_VEC4:
  770. glUniform4iv(info->location_, count / 4, data);
  771. break;
  772. }
  773. }
  774. }
  775. }
  776. void Graphics::SetShaderParameter(StringHash param, float value)
  777. {
  778. if (shaderProgram_)
  779. {
  780. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  781. if (info)
  782. glUniform1fv(info->location_, 1, &value);
  783. }
  784. }
  785. void Graphics::SetShaderParameter(StringHash param, const Color& color)
  786. {
  787. SetShaderParameter(param, color.GetData(), 4);
  788. }
  789. void Graphics::SetShaderParameter(StringHash param, const Matrix3& matrix)
  790. {
  791. if (shaderProgram_)
  792. {
  793. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  794. if (info)
  795. glUniformMatrix3fv(info->location_, 1, GL_TRUE, matrix.GetData());
  796. }
  797. }
  798. void Graphics::SetShaderParameter(StringHash param, const Vector3& vector)
  799. {
  800. if (shaderProgram_)
  801. {
  802. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  803. if (info)
  804. {
  805. // Check the uniform type to avoid mismatch
  806. switch (info->type_)
  807. {
  808. case GL_FLOAT:
  809. glUniform1fv(info->location_, 1, vector.GetData());
  810. break;
  811. case GL_FLOAT_VEC2:
  812. glUniform2fv(info->location_, 1, vector.GetData());
  813. break;
  814. case GL_FLOAT_VEC3:
  815. glUniform3fv(info->location_, 1, vector.GetData());
  816. break;
  817. }
  818. }
  819. }
  820. }
  821. void Graphics::SetShaderParameter(StringHash param, const Matrix4& matrix)
  822. {
  823. if (shaderProgram_)
  824. {
  825. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  826. if (info)
  827. glUniformMatrix4fv(info->location_, 1, GL_TRUE, matrix.GetData());
  828. }
  829. }
  830. void Graphics::SetShaderParameter(StringHash param, const Vector4& vector)
  831. {
  832. if (shaderProgram_)
  833. {
  834. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  835. if (info)
  836. {
  837. // Check the uniform type to avoid mismatch
  838. switch (info->type_)
  839. {
  840. case GL_FLOAT:
  841. glUniform1fv(info->location_, 1, vector.GetData());
  842. break;
  843. case GL_FLOAT_VEC2:
  844. glUniform2fv(info->location_, 1, vector.GetData());
  845. break;
  846. case GL_FLOAT_VEC3:
  847. glUniform3fv(info->location_, 1, vector.GetData());
  848. break;
  849. case GL_FLOAT_VEC4:
  850. glUniform4fv(info->location_, 1, vector.GetData());
  851. break;
  852. }
  853. }
  854. }
  855. }
  856. void Graphics::SetShaderParameter(StringHash param, const Matrix3x4& matrix)
  857. {
  858. if (shaderProgram_)
  859. {
  860. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  861. if (info)
  862. {
  863. float data[16];
  864. data[0] = matrix.m00_;
  865. data[1] = matrix.m01_;
  866. data[2] = matrix.m02_;
  867. data[3] = matrix.m03_;
  868. data[4] = matrix.m10_;
  869. data[5] = matrix.m11_;
  870. data[6] = matrix.m12_;
  871. data[7] = matrix.m13_;
  872. data[8] = matrix.m20_;
  873. data[9] = matrix.m21_;
  874. data[10] = matrix.m22_;
  875. data[11] = matrix.m23_;
  876. data[12] = 0.0f;
  877. data[13] = 0.0f;
  878. data[14] = 0.0f;
  879. data[15] = 1.0f;
  880. glUniformMatrix4fv(info->location_, 1, GL_TRUE, data);
  881. }
  882. }
  883. }
  884. bool Graphics::NeedParameterUpdate(StringHash param, const void* source)
  885. {
  886. if (shaderProgram_)
  887. return shaderProgram_->NeedParameterUpdate(param, source, shaderParameterFrame_);
  888. return false;
  889. }
  890. bool Graphics::NeedTextureUnit(TextureUnit unit)
  891. {
  892. if (shaderProgram_ && shaderProgram_->HasTextureUnit(unit))
  893. return true;
  894. return false;
  895. }
  896. void Graphics::ClearParameterSources()
  897. {
  898. ++shaderParameterFrame_;
  899. }
  900. void Graphics::ClearTransformSources()
  901. {
  902. if (shaderProgram_)
  903. {
  904. shaderProgram_->ClearParameterSource(VSP_MODEL);
  905. shaderProgram_->ClearParameterSource(VSP_VIEWPROJ);
  906. }
  907. }
  908. void Graphics::CleanupShaderPrograms()
  909. {
  910. for (ShaderProgramMap::Iterator i = shaderPrograms_.Begin(); i != shaderPrograms_.End();)
  911. {
  912. ShaderProgramMap::Iterator current = i++;
  913. ShaderVariation* vs = current->second_->GetVertexShader();
  914. ShaderVariation* ps = current->second_->GetPixelShader();
  915. if (!vs || !ps || !vs->GetGPUObject() || !ps->GetGPUObject())
  916. shaderPrograms_.Erase(current);
  917. }
  918. }
  919. void Graphics::SetTexture(unsigned index, Texture* texture)
  920. {
  921. if (index >= MAX_TEXTURE_UNITS)
  922. return;
  923. // Check if texture is currently bound as a render target. In that case, use its backup texture, or blank if not defined
  924. if (texture)
  925. {
  926. if (renderTargets_[0] && renderTargets_[0]->GetParentTexture() == texture)
  927. texture = texture->GetBackupTexture();
  928. // Check also for the view texture, in case a specific rendering pass does not bind the destination render target,
  929. // but should still not sample it either
  930. else if (texture == viewTexture_)
  931. texture = texture->GetBackupTexture();
  932. }
  933. if (textures_[index] != texture)
  934. {
  935. if (impl_->activeTexture_ != index)
  936. {
  937. glActiveTexture(GL_TEXTURE0 + index);
  938. impl_->activeTexture_ = index;
  939. }
  940. if (texture)
  941. {
  942. unsigned glType = texture->GetTarget();
  943. if (glType != textureTypes_[index])
  944. {
  945. if (textureTypes_[index])
  946. glDisable(textureTypes_[index]);
  947. glEnable(glType);
  948. textureTypes_[index] = glType;
  949. }
  950. glBindTexture(glType, texture->GetGPUObject());
  951. if (texture->GetParametersDirty())
  952. texture->UpdateParameters();
  953. }
  954. else
  955. {
  956. if (textureTypes_[index])
  957. glBindTexture(textureTypes_[index], 0);
  958. }
  959. textures_[index] = texture;
  960. }
  961. else
  962. {
  963. if (texture && texture->GetParametersDirty())
  964. {
  965. if (impl_->activeTexture_ != index)
  966. {
  967. glActiveTexture(GL_TEXTURE0 + index);
  968. impl_->activeTexture_ = index;
  969. }
  970. glBindTexture(texture->GetTarget(), texture->GetGPUObject());
  971. texture->UpdateParameters();
  972. }
  973. }
  974. }
  975. void Graphics::SetTextureForUpdate(Texture* texture)
  976. {
  977. if (impl_->activeTexture_ != 0)
  978. {
  979. glActiveTexture(GL_TEXTURE0);
  980. impl_->activeTexture_ = 0;
  981. }
  982. glBindTexture(texture->GetTarget(), texture->GetGPUObject());
  983. textures_[0] = texture;
  984. }
  985. void Graphics::SetDefaultTextureFilterMode(TextureFilterMode mode)
  986. {
  987. if (mode != defaultTextureFilterMode_)
  988. {
  989. defaultTextureFilterMode_ = mode;
  990. SetTextureParametersDirty();
  991. }
  992. }
  993. void Graphics::SetTextureAnisotropy(unsigned level)
  994. {
  995. if (level != textureAnisotropy_)
  996. {
  997. textureAnisotropy_ = level;
  998. SetTextureParametersDirty();
  999. }
  1000. }
  1001. void Graphics::SetTextureParametersDirty()
  1002. {
  1003. for (Vector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  1004. {
  1005. Texture* texture = dynamic_cast<Texture*>(*i);
  1006. if (texture)
  1007. texture->SetParametersDirty();
  1008. }
  1009. }
  1010. void Graphics::ResetRenderTargets()
  1011. {
  1012. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1013. SetRenderTarget(i, (RenderSurface*)0);
  1014. SetDepthStencil((RenderSurface*)0);
  1015. }
  1016. void Graphics::ResetRenderTarget(unsigned index)
  1017. {
  1018. SetRenderTarget(index, (RenderSurface*)0);
  1019. }
  1020. void Graphics::ResetDepthStencil()
  1021. {
  1022. SetDepthStencil((RenderSurface*)0);
  1023. }
  1024. void Graphics::SetRenderTarget(unsigned index, RenderSurface* renderTarget)
  1025. {
  1026. if (index >= MAX_RENDERTARGETS || !impl_->fbo_)
  1027. return;
  1028. if (renderTarget != renderTargets_[index])
  1029. {
  1030. renderTargets_[index] = renderTarget;
  1031. // If the rendertarget is also bound as a texture, replace with backup texture or null
  1032. if (renderTarget)
  1033. {
  1034. Texture* parentTexture = renderTarget->GetParentTexture();
  1035. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1036. {
  1037. if (textures_[i] == parentTexture)
  1038. SetTexture(i, textures_[i]->GetBackupTexture());
  1039. }
  1040. }
  1041. // Bind the FBO to be able to make changes to it
  1042. if (!impl_->fboBound_)
  1043. {
  1044. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, impl_->fbo_);
  1045. impl_->fboBound_ = true;
  1046. }
  1047. if (renderTarget)
  1048. {
  1049. Texture* texture = renderTarget->GetParentTexture();
  1050. // If texture's parameters are dirty, update before attaching
  1051. if (texture->GetParametersDirty())
  1052. {
  1053. SetTextureForUpdate(texture);
  1054. texture->UpdateParameters();
  1055. SetTexture(0, 0);
  1056. }
  1057. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT + index, renderTarget->GetTarget(), texture->GetGPUObject(), 0);
  1058. }
  1059. else
  1060. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT + index, GL_TEXTURE_2D, 0, 0);
  1061. // Disable color buffer writing/reading if only a depth texture is to be used:
  1062. // otherwise it is an OpenGL error (incomplete framebuffer)
  1063. SetDrawBuffers();
  1064. // If all rendertargets and the depth buffer are not textures, revert to backbuffer rendering
  1065. bool noFBO = (depthStencil_ == 0);
  1066. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1067. {
  1068. if (renderTargets_[i])
  1069. {
  1070. noFBO = false;
  1071. break;
  1072. }
  1073. }
  1074. if (noFBO && impl_->fboBound_)
  1075. {
  1076. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
  1077. impl_->fboBound_ = false;
  1078. }
  1079. }
  1080. }
  1081. void Graphics::SetRenderTarget(unsigned index, Texture2D* renderTexture)
  1082. {
  1083. RenderSurface* renderTarget = 0;
  1084. if (renderTexture)
  1085. renderTarget = renderTexture->GetRenderSurface();
  1086. SetRenderTarget(index, renderTarget);
  1087. }
  1088. void Graphics::SetDepthStencil(RenderSurface* depthStencil)
  1089. {
  1090. if (impl_->fbo_ && depthStencil != depthStencil_)
  1091. {
  1092. // If we are using a rendertarget texture, it is required in OpenGL to also have an own depth stencil
  1093. // Create a new depth stencil texture as necessary to be able to provide similar behaviour.
  1094. if (renderTargets_[0] && !depthStencil)
  1095. {
  1096. int width = renderTargets_[0]->GetWidth();
  1097. int height = renderTargets_[0]->GetHeight();
  1098. int searchKey = (width << 16) | height;
  1099. HashMap<int, SharedPtr<Texture2D> >::Iterator i = depthTextures_.Find(searchKey);
  1100. if (i != depthTextures_.End())
  1101. depthStencil = i->second_->GetRenderSurface();
  1102. else
  1103. {
  1104. SharedPtr<Texture2D> newDepthTexture(new Texture2D(context_));
  1105. newDepthTexture->SetSize(width, height, GetDepthStencilFormat(), TEXTURE_DEPTHSTENCIL);
  1106. depthTextures_[searchKey] = newDepthTexture;
  1107. depthStencil = newDepthTexture->GetRenderSurface();
  1108. }
  1109. }
  1110. /// \todo Should check that the texture actually is in depth format
  1111. depthStencil_ = depthStencil;
  1112. // Bind the FBO to be able to make changes to it
  1113. if (!impl_->fboBound_)
  1114. {
  1115. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, impl_->fbo_);
  1116. impl_->fboBound_ = true;
  1117. }
  1118. if (depthStencil)
  1119. {
  1120. // Bind either a renderbuffer or a depth texture, depending on what is available
  1121. unsigned renderBufferID = depthStencil->GetRenderBuffer();
  1122. if (!renderBufferID)
  1123. {
  1124. Texture* texture = depthStencil->GetParentTexture();
  1125. // If texture's parameters are dirty, update before attaching
  1126. if (texture->GetParametersDirty())
  1127. {
  1128. SetTextureForUpdate(texture);
  1129. texture->UpdateParameters();
  1130. SetTexture(0, 0);
  1131. }
  1132. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, texture->GetGPUObject(), 0);
  1133. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0);
  1134. impl_->depthBits_ = texture->GetDepthBits();
  1135. }
  1136. else
  1137. {
  1138. glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, renderBufferID);
  1139. glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, renderBufferID);
  1140. impl_->depthBits_ = 24;
  1141. }
  1142. }
  1143. else
  1144. {
  1145. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0);
  1146. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0);
  1147. impl_->depthBits_ = impl_->windowDepthBits_;
  1148. }
  1149. // Disable color buffer writing/reading if only a depth texture is to be used:
  1150. // otherwise it is an OpenGL error (incomplete framebuffer)
  1151. SetDrawBuffers();
  1152. // If all rendertargets and the depth buffer are not textures, revert to backbuffer rendering
  1153. bool noFBO = (depthStencil_ == 0);
  1154. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1155. {
  1156. if (renderTargets_[i])
  1157. {
  1158. noFBO = false;
  1159. break;
  1160. }
  1161. }
  1162. if (noFBO && impl_->fboBound_)
  1163. {
  1164. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
  1165. impl_->fboBound_ = false;
  1166. }
  1167. }
  1168. // Reset viewport and scissor test
  1169. IntVector2 viewSize = GetRenderTargetDimensions();
  1170. SetViewport(IntRect(0, 0, viewSize.x_, viewSize.y_));
  1171. }
  1172. void Graphics::SetDepthStencil(Texture2D* depthTexture)
  1173. {
  1174. RenderSurface* depthStencil = 0;
  1175. if (depthTexture)
  1176. depthStencil = depthTexture->GetRenderSurface();
  1177. SetDepthStencil(depthStencil);
  1178. }
  1179. void Graphics::SetViewport(const IntRect& rect)
  1180. {
  1181. IntVector2 rtSize = GetRenderTargetDimensions();
  1182. IntRect rectCopy = rect;
  1183. if (rectCopy.right_ <= rectCopy.left_)
  1184. rectCopy.right_ = rectCopy.left_ + 1;
  1185. if (rectCopy.bottom_ <= rectCopy.top_)
  1186. rectCopy.bottom_ = rectCopy.top_ + 1;
  1187. rectCopy.left_ = Clamp(rectCopy.left_, 0, rtSize.x_);
  1188. rectCopy.top_ = Clamp(rectCopy.top_, 0, rtSize.y_);
  1189. rectCopy.right_ = Clamp(rectCopy.right_, 0, rtSize.x_);
  1190. rectCopy.bottom_ = Clamp(rectCopy.bottom_, 0, rtSize.y_);
  1191. if (rectCopy != viewport_)
  1192. {
  1193. // Use Direct3D convention with the vertical coordinates ie. 0 is top
  1194. glViewport(rectCopy.left_, rtSize.y_ - rectCopy.bottom_, rectCopy.right_ - rectCopy.left_, rectCopy.bottom_ - rectCopy.top_);
  1195. viewport_ = rectCopy;
  1196. }
  1197. // Disable scissor test, needs to be re-enabled by the user
  1198. SetScissorTest(false);
  1199. }
  1200. void Graphics::SetViewTexture(Texture* texture)
  1201. {
  1202. viewTexture_ = texture;
  1203. // Check for the view texture being currently bound
  1204. if (texture)
  1205. {
  1206. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1207. {
  1208. if (textures_[i] == texture)
  1209. SetTexture(i, textures_[i]->GetBackupTexture());
  1210. }
  1211. }
  1212. }
  1213. void Graphics::SetAlphaTest(bool enable, CompareMode mode, float alphaRef)
  1214. {
  1215. if (enable != alphaTest_)
  1216. {
  1217. if (enable)
  1218. glEnable(GL_ALPHA_TEST);
  1219. else
  1220. glDisable(GL_ALPHA_TEST);
  1221. alphaTest_ = enable;
  1222. }
  1223. if (enable)
  1224. {
  1225. alphaRef = Clamp(alphaRef, 0.0f, 1.0f);
  1226. if (mode != alphaTestMode_ || alphaRef != alphaRef_)
  1227. {
  1228. glAlphaFunc(glCmpFunc[mode], alphaRef);
  1229. alphaTestMode_ = mode;
  1230. alphaRef_ = alphaRef;
  1231. }
  1232. }
  1233. }
  1234. void Graphics::SetBlendMode(BlendMode mode)
  1235. {
  1236. if (mode != blendMode_)
  1237. {
  1238. if (mode == BLEND_REPLACE)
  1239. glDisable(GL_BLEND);
  1240. else
  1241. {
  1242. glEnable(GL_BLEND);
  1243. glBlendFunc(glSrcBlend[mode], glDestBlend[mode]);
  1244. }
  1245. blendMode_ = mode;
  1246. }
  1247. }
  1248. void Graphics::SetColorWrite(bool enable)
  1249. {
  1250. if (enable != colorWrite_)
  1251. {
  1252. if (enable)
  1253. glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
  1254. else
  1255. glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
  1256. colorWrite_ = enable;
  1257. }
  1258. }
  1259. void Graphics::SetCullMode(CullMode mode)
  1260. {
  1261. if (mode != cullMode_)
  1262. {
  1263. if (mode == CULL_NONE)
  1264. glDisable(GL_CULL_FACE);
  1265. else
  1266. {
  1267. // Use Direct3D convention, ie. clockwise vertices define a front face
  1268. glEnable(GL_CULL_FACE);
  1269. glCullFace(mode == CULL_CCW ? GL_FRONT : GL_BACK);
  1270. }
  1271. cullMode_ = mode;
  1272. }
  1273. }
  1274. void Graphics::SetDepthBias(float constantBias, float slopeScaledBias)
  1275. {
  1276. if (constantBias != constantDepthBias_ || slopeScaledBias != slopeScaledDepthBias_)
  1277. {
  1278. if (constantBias != 0.0f || slopeScaledBias != 0.0f)
  1279. {
  1280. // Bring the constant bias from Direct3D9 scale to OpenGL (depends on depth buffer bitdepth)
  1281. // Zero depth bits may be returned if using the packed depth stencil format. Assume 24bit in that case
  1282. int depthBits = Min(impl_->depthBits_, 23);
  1283. if (!depthBits)
  1284. depthBits = 23;
  1285. float adjustedConstantBias = constantBias * (float)(1 << (depthBits - 1));
  1286. float adjustedSlopeScaledBias = slopeScaledBias + 1.0f;
  1287. glEnable(GL_POLYGON_OFFSET_FILL);
  1288. glEnable(GL_POLYGON_OFFSET_LINE);
  1289. glPolygonOffset(adjustedSlopeScaledBias, adjustedConstantBias);
  1290. }
  1291. else
  1292. {
  1293. glDisable(GL_POLYGON_OFFSET_FILL);
  1294. glDisable(GL_POLYGON_OFFSET_LINE);
  1295. }
  1296. constantDepthBias_ = constantBias;
  1297. slopeScaledDepthBias_ = slopeScaledBias;
  1298. }
  1299. }
  1300. void Graphics::SetDepthTest(CompareMode mode)
  1301. {
  1302. if (mode != depthTestMode_)
  1303. {
  1304. glDepthFunc(glCmpFunc[mode]);
  1305. depthTestMode_ = mode;
  1306. }
  1307. }
  1308. void Graphics::SetDepthWrite(bool enable)
  1309. {
  1310. if (enable != depthWrite_)
  1311. {
  1312. glDepthMask(enable ? GL_TRUE : GL_FALSE);
  1313. depthWrite_ = enable;
  1314. }
  1315. }
  1316. void Graphics::SetFillMode(FillMode mode)
  1317. {
  1318. if (mode != fillMode_)
  1319. {
  1320. glPolygonMode(GL_FRONT_AND_BACK, mode == FILL_SOLID ? GL_FILL : GL_LINE);
  1321. fillMode_ = mode;
  1322. }
  1323. }
  1324. void Graphics::SetScissorTest(bool enable, const Rect& rect, bool borderInclusive)
  1325. {
  1326. // During some light rendering loops, a full rect is toggled on/off repeatedly.
  1327. // Disable scissor in that case to reduce state changes
  1328. if (rect.min_.x_ <= 0.0f && rect.min_.y_ <= 0.0f && rect.max_.y_ >= 1.0f && rect.max_.y_ >= 1.0f)
  1329. enable = false;
  1330. // Check for illegal rect, disable in that case
  1331. if (rect.max_.x_ < rect.min_.x_ || rect.max_.y_ < rect.min_.y_)
  1332. enable = false;
  1333. if (enable)
  1334. {
  1335. IntVector2 rtSize(GetRenderTargetDimensions());
  1336. IntVector2 viewSize(viewport_.right_ - viewport_.left_, viewport_.bottom_ - viewport_.top_);
  1337. IntVector2 viewPos(viewport_.left_, viewport_.top_);
  1338. IntRect intRect;
  1339. int expand = borderInclusive ? 1 : 0;
  1340. intRect.left_ = Clamp((int)((rect.min_.x_ + 1.0f) * 0.5f * viewSize.x_) + viewPos.x_, 0, rtSize.x_ - 1);
  1341. intRect.top_ = Clamp((int)((-rect.max_.y_ + 1.0f) * 0.5f * viewSize.y_) + viewPos.y_, 0, rtSize.y_ - 1);
  1342. intRect.right_ = Clamp((int)((rect.max_.x_ + 1.0f) * 0.5f * viewSize.x_) + viewPos.x_ + expand, 0, rtSize.x_);
  1343. intRect.bottom_ = Clamp((int)((-rect.min_.y_ + 1.0f) * 0.5f * viewSize.y_) + viewPos.y_ + expand, 0, rtSize.y_);
  1344. if (intRect.right_ == intRect.left_)
  1345. intRect.right_++;
  1346. if (intRect.bottom_ == intRect.top_)
  1347. intRect.bottom_++;
  1348. if (intRect.right_ < intRect.left_ || intRect.bottom_ < intRect.top_)
  1349. enable = false;
  1350. if (enable && scissorRect_ != intRect)
  1351. {
  1352. // Use Direct3D convention with the vertical coordinates ie. 0 is top
  1353. glScissor(intRect.left_, rtSize.y_ - intRect.bottom_, intRect.right_ - intRect.left_, intRect.bottom_ - intRect.top_);
  1354. scissorRect_ = intRect;
  1355. }
  1356. }
  1357. else
  1358. scissorRect_ = IntRect::ZERO;
  1359. if (enable != scissorTest_)
  1360. {
  1361. if (enable)
  1362. glEnable(GL_SCISSOR_TEST);
  1363. else
  1364. glDisable(GL_SCISSOR_TEST);
  1365. scissorTest_ = enable;
  1366. }
  1367. }
  1368. void Graphics::SetScissorTest(bool enable, const IntRect& rect)
  1369. {
  1370. IntVector2 rtSize(GetRenderTargetDimensions());
  1371. IntVector2 viewSize(viewport_.right_ - viewport_.left_, viewport_.bottom_ - viewport_.top_);
  1372. IntVector2 viewPos(viewport_.left_, viewport_.top_);
  1373. // Full scissor is same as disabling the test
  1374. if (rect.left_ <= 0 && rect.right_ >= viewSize.x_ && rect.top_ <= 0 && rect.bottom_ >= viewSize.y_)
  1375. enable = false;
  1376. // Check for illegal rect, disable in that case
  1377. if (rect.right_ < rect.left_ || rect.bottom_ < rect.top_)
  1378. enable = false;
  1379. if (enable)
  1380. {
  1381. IntRect intRect;
  1382. intRect.left_ = Clamp(rect.left_ + viewPos.x_, 0, rtSize.x_ - 1);
  1383. intRect.top_ = Clamp(rect.top_ + viewPos.y_, 0, rtSize.y_ - 1);
  1384. intRect.right_ = Clamp(rect.right_ + viewPos.x_, 0, rtSize.x_);
  1385. intRect.bottom_ = Clamp(rect.bottom_ + viewPos.y_, 0, rtSize.y_);
  1386. if (intRect.right_ == intRect.left_)
  1387. intRect.right_++;
  1388. if (intRect.bottom_ == intRect.top_)
  1389. intRect.bottom_++;
  1390. if (intRect.right_ < intRect.left_ || intRect.bottom_ < intRect.top_)
  1391. enable = false;
  1392. if (enable && scissorRect_ != intRect)
  1393. {
  1394. // Use Direct3D convention with the vertical coordinates ie. 0 is top
  1395. glScissor(intRect.left_, rtSize.y_ - intRect.bottom_, intRect.right_ - intRect.left_, intRect.bottom_ - intRect.top_);
  1396. scissorRect_ = intRect;
  1397. }
  1398. }
  1399. else
  1400. scissorRect_ = IntRect::ZERO;
  1401. if (enable != scissorTest_)
  1402. {
  1403. if (enable)
  1404. glEnable(GL_SCISSOR_TEST);
  1405. else
  1406. glDisable(GL_SCISSOR_TEST);
  1407. scissorTest_ = enable;
  1408. }
  1409. }
  1410. void Graphics::SetStreamFrequency(unsigned index, unsigned frequency)
  1411. {
  1412. }
  1413. void Graphics::ResetStreamFrequencies()
  1414. {
  1415. }
  1416. void Graphics::SetStencilTest(bool enable, CompareMode mode, StencilOp pass, StencilOp fail, StencilOp zFail, unsigned stencilRef, unsigned stencilMask)
  1417. {
  1418. if (enable != stencilTest_)
  1419. {
  1420. if (enable)
  1421. glEnable(GL_STENCIL_TEST);
  1422. else
  1423. glDisable(GL_STENCIL_TEST);
  1424. stencilTest_ = enable;
  1425. }
  1426. if (enable)
  1427. {
  1428. if (mode != stencilTestMode_ || stencilRef != stencilRef_ || stencilMask != stencilMask_)
  1429. {
  1430. glStencilFunc(glCmpFunc[mode], stencilRef, stencilMask);
  1431. stencilTestMode_ = mode;
  1432. stencilRef_ = stencilRef;
  1433. stencilMask_ = stencilMask;
  1434. }
  1435. if (pass != stencilPass_ || fail != stencilFail_ || zFail != stencilZFail_)
  1436. {
  1437. glStencilOp(glStencilOps[fail], glStencilOps[zFail], glStencilOps[pass]);
  1438. stencilPass_ = pass;
  1439. stencilFail_ = fail;
  1440. stencilZFail_ = zFail;
  1441. }
  1442. }
  1443. }
  1444. bool Graphics::BeginImmediate(PrimitiveType type, unsigned vertexCount, unsigned elementMask)
  1445. {
  1446. if (immediateVertexCount_)
  1447. {
  1448. LOGERROR("New immediate draw operation started before ending the last one");
  1449. return false;
  1450. }
  1451. if (!(elementMask & MASK_POSITION))
  1452. {
  1453. LOGERROR("Immediate draw operation must contain vertex positions");
  1454. return false;
  1455. }
  1456. if (!vertexCount)
  1457. return true;
  1458. // Resize the buffer if it is too small
  1459. unsigned vertexSize = VertexBuffer::GetVertexSize(elementMask);
  1460. if (immediateVertexData_.Size() < vertexCount * vertexSize)
  1461. immediateVertexData_.Resize(vertexCount * vertexSize);
  1462. // Note: the data pointer gets pre-decremented here, because the first call to DefineVertex() will increment it
  1463. immediateDataPtr_ = &immediateVertexData_[0] - vertexSize;
  1464. immediateType_= type;
  1465. immediateVertexCount_ = vertexCount;
  1466. immediateVertexSize_ = vertexSize;
  1467. immediateElementMask_ = elementMask;
  1468. immediateCurrentVertex_ = 0;
  1469. unsigned dataOffset = 0;
  1470. for (unsigned i = ELEMENT_POSITION; i <= ELEMENT_TEXCOORD1; ++i)
  1471. {
  1472. immediateElementOffsets_[i] = dataOffset;
  1473. if (elementMask & (1 << i))
  1474. dataOffset += VertexBuffer::elementSize[i];
  1475. }
  1476. return true;
  1477. }
  1478. bool Graphics::DefineVertex(const Vector3& vertex)
  1479. {
  1480. if (!immediateVertexCount_ || immediateCurrentVertex_ >= immediateVertexCount_)
  1481. return false;
  1482. immediateDataPtr_ += immediateVertexSize_;
  1483. ++immediateCurrentVertex_;
  1484. float* dest = (float*)(immediateDataPtr_ + immediateElementOffsets_[ELEMENT_POSITION]);
  1485. const float* src = vertex.GetData();
  1486. dest[0] = src[0];
  1487. dest[1] = src[1];
  1488. dest[2] = src[2];
  1489. return true;
  1490. }
  1491. bool Graphics::DefineNormal(const Vector3& normal)
  1492. {
  1493. if (!immediateVertexCount_ || !(immediateElementMask_ & MASK_NORMAL) || !immediateCurrentVertex_)
  1494. return false;
  1495. float* dest = (float*)(immediateDataPtr_ + immediateElementOffsets_[ELEMENT_NORMAL]);
  1496. const float* src = normal.GetData();
  1497. dest[0] = src[0];
  1498. dest[1] = src[1];
  1499. dest[2] = src[2];
  1500. return true;
  1501. }
  1502. bool Graphics::DefineTexCoord(const Vector2& texCoord)
  1503. {
  1504. if (!immediateVertexCount_ || !(immediateElementMask_ & MASK_TEXCOORD1) || !immediateCurrentVertex_)
  1505. return false;
  1506. float* dest = (float*)(immediateDataPtr_ + immediateElementOffsets_[ELEMENT_TEXCOORD1]);
  1507. const float* src = texCoord.GetData();
  1508. dest[0] = src[0];
  1509. dest[1] = src[1];
  1510. return true;
  1511. }
  1512. bool Graphics::DefineColor(const Color& color)
  1513. {
  1514. if (!immediateVertexCount_ || !(immediateElementMask_ & MASK_COLOR) || !immediateCurrentVertex_)
  1515. return false;
  1516. unsigned* dest = (unsigned*)(immediateDataPtr_ + immediateElementOffsets_[ELEMENT_COLOR]);
  1517. *dest = color.ToUInt();
  1518. return true;
  1519. }
  1520. bool Graphics::DefineColor(unsigned color)
  1521. {
  1522. if (!immediateVertexCount_ || !(immediateElementMask_ & MASK_COLOR) || !immediateCurrentVertex_)
  1523. return false;
  1524. unsigned* dest = (unsigned*)(immediateDataPtr_ + immediateElementOffsets_[ELEMENT_COLOR]);
  1525. *dest = color;
  1526. return true;
  1527. }
  1528. void Graphics::EndImmediate()
  1529. {
  1530. if (immediateVertexCount_)
  1531. {
  1532. SetVertexBuffer(0);
  1533. SetIndexBuffer(0);
  1534. if (shaderProgram_)
  1535. {
  1536. const int* attributeLocations = shaderProgram_->GetAttributeLocations();
  1537. unsigned vertexSize = VertexBuffer::GetVertexSize(immediateElementMask_);
  1538. glBindBuffer(GL_ARRAY_BUFFER, 0);
  1539. for (unsigned i = ELEMENT_POSITION; i <= ELEMENT_TEXCOORD1; ++i)
  1540. {
  1541. unsigned attributeIndex = attributeLocations[i];
  1542. unsigned attributeBit = 1 << attributeIndex;
  1543. unsigned elementBit = 1 << i;
  1544. if (immediateElementMask_ & elementBit)
  1545. {
  1546. if ((impl_->enabledAttributes_ & attributeBit) == 0)
  1547. {
  1548. glEnableVertexAttribArray(attributeIndex);
  1549. impl_->enabledAttributes_ |= attributeBit;
  1550. }
  1551. glVertexAttribPointer(attributeIndex, VertexBuffer::elementComponents[i], VertexBuffer::elementType[i],
  1552. VertexBuffer::elementNormalize[i], vertexSize, (const GLvoid*)&immediateVertexData_[immediateElementOffsets_[i]]);
  1553. }
  1554. else if (impl_->enabledAttributes_ & attributeBit)
  1555. {
  1556. glDisableVertexAttribArray(attributeIndex);
  1557. impl_->enabledAttributes_ &= ~attributeBit;
  1558. }
  1559. }
  1560. Draw(immediateType_, 0, immediateVertexCount_);
  1561. }
  1562. immediateVertexCount_ = 0;
  1563. }
  1564. }
  1565. void Graphics::SetForceSM2(bool enable)
  1566. {
  1567. }
  1568. bool Graphics::IsInitialized() const
  1569. {
  1570. return impl_->window_ != 0;
  1571. }
  1572. unsigned char* Graphics::GetImmediateDataPtr() const
  1573. {
  1574. if (!immediateVertexCount_)
  1575. {
  1576. LOGERROR("Immediate draw operation not started");
  1577. return 0;
  1578. }
  1579. return const_cast<unsigned char*>(&immediateVertexData_[0]);
  1580. }
  1581. void* Graphics::GetWindowHandle() const
  1582. {
  1583. return impl_->window_;
  1584. }
  1585. PODVector<IntVector2> Graphics::GetResolutions() const
  1586. {
  1587. static const unsigned MAX_MODES = 256;
  1588. GLFWvidmode modes[MAX_MODES];
  1589. unsigned count = glfwGetVideoModes(modes, MAX_MODES);
  1590. PODVector<IntVector2> ret;
  1591. for (unsigned i = 0; i < count; ++i)
  1592. {
  1593. int width = modes[i].width;
  1594. int height = modes[i].height;
  1595. // Store mode if unique
  1596. bool unique = true;
  1597. for (unsigned j = 0; j < ret.Size(); ++i)
  1598. {
  1599. if (ret[j].x_ == width && ret[j].y_ == height)
  1600. {
  1601. unique = false;
  1602. break;
  1603. }
  1604. }
  1605. if (unique)
  1606. ret.Push(IntVector2(width, height));
  1607. }
  1608. return ret;
  1609. }
  1610. PODVector<int> Graphics::GetMultiSampleLevels() const
  1611. {
  1612. PODVector<int> ret;
  1613. // No multisampling always supported
  1614. ret.Push(1);
  1615. /// \todo Implement properly, if possible
  1616. return ret;
  1617. }
  1618. VertexBuffer* Graphics::GetVertexBuffer(unsigned index) const
  1619. {
  1620. return index < MAX_VERTEX_STREAMS ? vertexBuffers_[index] : 0;
  1621. }
  1622. TextureUnit Graphics::GetTextureUnit(const String& name)
  1623. {
  1624. Map<String, TextureUnit>::Iterator i = textureUnits_.Find(name);
  1625. if (i != textureUnits_.End())
  1626. return i->second_;
  1627. else
  1628. return MAX_TEXTURE_UNITS;
  1629. }
  1630. const String& Graphics::GetTextureUnitName(TextureUnit unit)
  1631. {
  1632. for (Map<String, TextureUnit>::Iterator i = textureUnits_.Begin(); i != textureUnits_.End(); ++i)
  1633. {
  1634. if (i->second_ == unit)
  1635. return i->first_;
  1636. }
  1637. return noParameter;
  1638. }
  1639. Texture* Graphics::GetTexture(unsigned index) const
  1640. {
  1641. return index < MAX_TEXTURE_UNITS ? textures_[index] : 0;
  1642. }
  1643. RenderSurface* Graphics::GetRenderTarget(unsigned index) const
  1644. {
  1645. return index < MAX_RENDERTARGETS ? renderTargets_[index] : 0;
  1646. }
  1647. IntVector2 Graphics::GetRenderTargetDimensions() const
  1648. {
  1649. int width, height;
  1650. if (renderTargets_[0])
  1651. {
  1652. width = renderTargets_[0]->GetWidth();
  1653. height = renderTargets_[0]->GetHeight();
  1654. }
  1655. else if (depthStencil_)
  1656. {
  1657. width = depthStencil_->GetWidth();
  1658. height = depthStencil_->GetHeight();
  1659. }
  1660. else
  1661. {
  1662. width = width_;
  1663. height = height_;
  1664. }
  1665. return IntVector2(width, height);
  1666. }
  1667. void Graphics::AddGPUObject(GPUObject* object)
  1668. {
  1669. gpuObjects_.Push(object);
  1670. }
  1671. void Graphics::RemoveGPUObject(GPUObject* object)
  1672. {
  1673. Vector<GPUObject*>::Iterator i = gpuObjects_.Find(object);
  1674. if (i != gpuObjects_.End())
  1675. gpuObjects_.Erase(i);
  1676. }
  1677. unsigned Graphics::GetAlphaFormat()
  1678. {
  1679. return GL_ALPHA;
  1680. }
  1681. unsigned Graphics::GetLuminanceFormat()
  1682. {
  1683. return GL_LUMINANCE;
  1684. }
  1685. unsigned Graphics::GetLuminanceAlphaFormat()
  1686. {
  1687. return GL_LUMINANCE_ALPHA;
  1688. }
  1689. unsigned Graphics::GetRGBFormat()
  1690. {
  1691. return GL_RGB;
  1692. }
  1693. unsigned Graphics::GetRGBAFormat()
  1694. {
  1695. return GL_RGBA;
  1696. }
  1697. unsigned Graphics::GetDepthFormat()
  1698. {
  1699. return GL_DEPTH_COMPONENT24;
  1700. }
  1701. unsigned Graphics::GetDepthStencilFormat()
  1702. {
  1703. return GL_DEPTH24_STENCIL8_EXT;
  1704. }
  1705. void Graphics::CreateRenderTargets()
  1706. {
  1707. if (mode_ != RENDER_FORWARD)
  1708. {
  1709. if (!diffBuffer_)
  1710. {
  1711. diffBuffer_ = new Texture2D(context_);
  1712. diffBuffer_->SetSize(0, 0, GetRGBAFormat(), TEXTURE_RENDERTARGET);
  1713. }
  1714. if (!normalBuffer_)
  1715. {
  1716. normalBuffer_ = new Texture2D(context_);
  1717. normalBuffer_->SetSize(0, 0, GetRGBAFormat(), TEXTURE_RENDERTARGET);
  1718. }
  1719. if (!depthBuffer_)
  1720. {
  1721. depthBuffer_ = new Texture2D(context_);
  1722. depthBuffer_->SetSize(0, 0, GetDepthFormat(), TEXTURE_DEPTHSTENCIL);
  1723. }
  1724. // If deferred antialiasing is used, reserve screen buffer
  1725. // (later we will probably want the screen buffer reserved in any case, to do for example distortion effects,
  1726. // which will also be useful in forward rendering)
  1727. if (multiSample_ > 1)
  1728. {
  1729. screenBuffer_ = new Texture2D(context_);
  1730. screenBuffer_->SetSize(0, 0, GetRGBAFormat(), TEXTURE_RENDERTARGET);
  1731. screenBuffer_->SetFilterMode(FILTER_BILINEAR);
  1732. }
  1733. else
  1734. screenBuffer_.Reset();
  1735. }
  1736. else
  1737. {
  1738. diffBuffer_.Reset();
  1739. normalBuffer_.Reset();
  1740. depthBuffer_.Reset();
  1741. screenBuffer_.Reset();
  1742. }
  1743. }
  1744. void Graphics::ResetCachedState()
  1745. {
  1746. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  1747. {
  1748. vertexBuffers_[i] = 0;
  1749. elementMasks_[i] = 0;
  1750. }
  1751. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1752. {
  1753. textures_[i] = 0;
  1754. textureTypes_[i] = 0;
  1755. }
  1756. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1757. renderTargets_[i] = 0;
  1758. depthStencil_ = 0;
  1759. viewport_ = IntRect(0, 0, 0, 0);
  1760. viewTexture_ = 0;
  1761. indexBuffer_ = 0;
  1762. vertexShader_ = 0;
  1763. pixelShader_ = 0;
  1764. shaderProgram_ = 0;
  1765. blendMode_ = BLEND_REPLACE;
  1766. alphaTest_ = false;
  1767. alphaTestMode_ = CMP_ALWAYS;
  1768. alphaRef_ = 0.0f;
  1769. textureAnisotropy_ = 1;
  1770. colorWrite_ = true;
  1771. cullMode_ = CULL_NONE;
  1772. constantDepthBias_ = 0.0f;
  1773. slopeScaledDepthBias_ = 0.0f;
  1774. depthTestMode_ = CMP_ALWAYS;
  1775. depthWrite_ = true;
  1776. fillMode_ = FILL_SOLID;
  1777. scissorTest_ = false;
  1778. scissorRect_ = IntRect::ZERO;
  1779. stencilTest_ = false;
  1780. stencilTestMode_ = CMP_ALWAYS;
  1781. stencilPass_ = OP_KEEP;
  1782. stencilFail_ = OP_KEEP;
  1783. stencilZFail_ = OP_KEEP;
  1784. stencilRef_ = 0;
  1785. stencilMask_ = M_MAX_UNSIGNED;
  1786. impl_->activeTexture_ = 0;
  1787. impl_->drawBuffers_ = M_MAX_UNSIGNED;
  1788. impl_->enabledAttributes_ = 0;
  1789. impl_->fboBound_ = false;
  1790. }
  1791. void Graphics::SetDrawBuffers()
  1792. {
  1793. // Calculate the bit combination of non-zero color rendertargets to first check if the combination changed
  1794. unsigned newDrawBuffers = 0;
  1795. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1796. {
  1797. if (renderTargets_[i])
  1798. newDrawBuffers |= 1 << i;
  1799. }
  1800. if (newDrawBuffers == impl_->drawBuffers_)
  1801. return;
  1802. // Check for no color rendertargets (depth rendering only)
  1803. if (!newDrawBuffers)
  1804. glDrawBuffer(GL_NONE);
  1805. else
  1806. {
  1807. int drawBufferIds[4];
  1808. unsigned drawBufferCount = 0;
  1809. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1810. {
  1811. if (renderTargets_[i])
  1812. drawBufferIds[drawBufferCount++] = GL_COLOR_ATTACHMENT0_EXT + i;
  1813. }
  1814. glDrawBuffers(drawBufferCount, (const GLenum*)drawBufferIds);
  1815. }
  1816. glReadBuffer(GL_NONE);
  1817. }
  1818. void Graphics::Release()
  1819. {
  1820. if (!impl_->window_)
  1821. return;
  1822. diffBuffer_.Reset();
  1823. normalBuffer_.Reset();
  1824. depthBuffer_.Reset();
  1825. screenBuffer_.Reset();
  1826. depthTextures_.Clear();
  1827. // If GPU objects exist ie. it's a context delete/recreate, not Close(), tell them to save and release themselves
  1828. for (Vector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  1829. (*i)->OnDeviceLost();
  1830. if (impl_->fbo_)
  1831. {
  1832. glDeleteFramebuffersEXT(1, &impl_->fbo_);
  1833. impl_->fbo_ = 0;
  1834. }
  1835. // When the new context is initialized, it will have default state again
  1836. ResetCachedState();
  1837. ClearParameterSources();
  1838. {
  1839. MutexLock lock(GetStaticMutex());
  1840. SetWindowContext(impl_->window_, 0);
  1841. glfwCloseWindow(impl_->window_);
  1842. impl_->window_ = 0;
  1843. }
  1844. }
  1845. void Graphics::SetTextureUnitMappings()
  1846. {
  1847. // Map texture units
  1848. textureUnits_["NormalMap"] = TU_NORMAL;
  1849. textureUnits_["DiffMap"] = TU_DIFFUSE;
  1850. textureUnits_["DiffCubeMap"] = TU_DIFFUSE;
  1851. textureUnits_["SpecMap"] = TU_SPECULAR;
  1852. textureUnits_["EmissiveMap"] = TU_EMISSIVE;
  1853. textureUnits_["DetailMap"] = TU_DETAIL;
  1854. textureUnits_["EnvironmentMap"] = TU_ENVIRONMENT;
  1855. textureUnits_["EnvironmentCubeMap"] = TU_ENVIRONMENT;
  1856. textureUnits_["LightRampMap"] = TU_LIGHTRAMP;
  1857. textureUnits_["LightSpotMap"] = TU_LIGHTSPOT;
  1858. textureUnits_["LightCubeMap"] = TU_LIGHTSPOT;
  1859. textureUnits_["ShadowMap"] = TU_SHADOWMAP;
  1860. textureUnits_["DiffBuffer"] = TU_DIFFBUFFER;
  1861. textureUnits_["NormalBuffer"] = TU_NORMALBUFFER;
  1862. textureUnits_["DepthBuffer"] = TU_DEPTHBUFFER;
  1863. }
  1864. void RegisterGraphicsLibrary(Context* context)
  1865. {
  1866. Animation::RegisterObject(context);
  1867. Material::RegisterObject(context);
  1868. Model::RegisterObject(context);
  1869. Shader::RegisterObject(context);
  1870. Technique::RegisterObject(context);
  1871. Texture2D::RegisterObject(context);
  1872. TextureCube::RegisterObject(context);
  1873. Camera::RegisterObject(context);
  1874. Drawable::RegisterObject(context);
  1875. Light::RegisterObject(context);
  1876. StaticModel::RegisterObject(context);
  1877. Skybox::RegisterObject(context);
  1878. AnimatedModel::RegisterObject(context);
  1879. AnimationController::RegisterObject(context);
  1880. BillboardSet::RegisterObject(context);
  1881. ParticleEmitter::RegisterObject(context);
  1882. DebugRenderer::RegisterObject(context);
  1883. Octree::RegisterObject(context);
  1884. Zone::RegisterObject(context);
  1885. }