OGLGraphics.cpp 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232
  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_BEGINRENDER);
  359. return true;
  360. }
  361. void Graphics::EndFrame()
  362. {
  363. PROFILE(EndRendering);
  364. if (!IsInitialized())
  365. return;
  366. SendEvent(E_ENDRENDER);
  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. for (Vector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  1674. {
  1675. if ((*i) == object)
  1676. {
  1677. gpuObjects_.Erase(i);
  1678. return;
  1679. }
  1680. }
  1681. }
  1682. unsigned Graphics::GetAlphaFormat()
  1683. {
  1684. return GL_ALPHA;
  1685. }
  1686. unsigned Graphics::GetLuminanceFormat()
  1687. {
  1688. return GL_LUMINANCE;
  1689. }
  1690. unsigned Graphics::GetLuminanceAlphaFormat()
  1691. {
  1692. return GL_LUMINANCE_ALPHA;
  1693. }
  1694. unsigned Graphics::GetRGBFormat()
  1695. {
  1696. return GL_RGB;
  1697. }
  1698. unsigned Graphics::GetRGBAFormat()
  1699. {
  1700. return GL_RGBA;
  1701. }
  1702. unsigned Graphics::GetDepthFormat()
  1703. {
  1704. return GL_DEPTH_COMPONENT24;
  1705. }
  1706. unsigned Graphics::GetDepthStencilFormat()
  1707. {
  1708. return GL_DEPTH24_STENCIL8_EXT;
  1709. }
  1710. void Graphics::CreateRenderTargets()
  1711. {
  1712. if (mode_ != RENDER_FORWARD)
  1713. {
  1714. if (!diffBuffer_)
  1715. {
  1716. diffBuffer_ = new Texture2D(context_);
  1717. diffBuffer_->SetSize(0, 0, GetRGBAFormat(), TEXTURE_RENDERTARGET);
  1718. }
  1719. if (!normalBuffer_)
  1720. {
  1721. normalBuffer_ = new Texture2D(context_);
  1722. normalBuffer_->SetSize(0, 0, GetRGBAFormat(), TEXTURE_RENDERTARGET);
  1723. }
  1724. if (!depthBuffer_)
  1725. {
  1726. depthBuffer_ = new Texture2D(context_);
  1727. depthBuffer_->SetSize(0, 0, GetDepthFormat(), TEXTURE_DEPTHSTENCIL);
  1728. }
  1729. // If deferred antialiasing is used, reserve screen buffer
  1730. // (later we will probably want the screen buffer reserved in any case, to do for example distortion effects,
  1731. // which will also be useful in forward rendering)
  1732. if (multiSample_ > 1)
  1733. {
  1734. screenBuffer_ = new Texture2D(context_);
  1735. screenBuffer_->SetSize(0, 0, GetRGBAFormat(), TEXTURE_RENDERTARGET);
  1736. screenBuffer_->SetFilterMode(FILTER_BILINEAR);
  1737. }
  1738. else
  1739. screenBuffer_.Reset();
  1740. }
  1741. else
  1742. {
  1743. diffBuffer_.Reset();
  1744. normalBuffer_.Reset();
  1745. depthBuffer_.Reset();
  1746. screenBuffer_.Reset();
  1747. }
  1748. }
  1749. void Graphics::ResetCachedState()
  1750. {
  1751. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  1752. {
  1753. vertexBuffers_[i] = 0;
  1754. elementMasks_[i] = 0;
  1755. }
  1756. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1757. {
  1758. textures_[i] = 0;
  1759. textureTypes_[i] = 0;
  1760. }
  1761. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1762. renderTargets_[i] = 0;
  1763. depthStencil_ = 0;
  1764. viewport_ = IntRect(0, 0, 0, 0);
  1765. viewTexture_ = 0;
  1766. indexBuffer_ = 0;
  1767. vertexShader_ = 0;
  1768. pixelShader_ = 0;
  1769. shaderProgram_ = 0;
  1770. blendMode_ = BLEND_REPLACE;
  1771. alphaTest_ = false;
  1772. alphaTestMode_ = CMP_ALWAYS;
  1773. alphaRef_ = 0.0f;
  1774. textureAnisotropy_ = 1;
  1775. colorWrite_ = true;
  1776. cullMode_ = CULL_NONE;
  1777. constantDepthBias_ = 0.0f;
  1778. slopeScaledDepthBias_ = 0.0f;
  1779. depthTestMode_ = CMP_ALWAYS;
  1780. depthWrite_ = true;
  1781. fillMode_ = FILL_SOLID;
  1782. scissorTest_ = false;
  1783. scissorRect_ = IntRect::ZERO;
  1784. stencilTest_ = false;
  1785. stencilTestMode_ = CMP_ALWAYS;
  1786. stencilPass_ = OP_KEEP;
  1787. stencilFail_ = OP_KEEP;
  1788. stencilZFail_ = OP_KEEP;
  1789. stencilRef_ = 0;
  1790. stencilMask_ = M_MAX_UNSIGNED;
  1791. impl_->activeTexture_ = 0;
  1792. impl_->drawBuffers_ = M_MAX_UNSIGNED;
  1793. impl_->enabledAttributes_ = 0;
  1794. impl_->fboBound_ = false;
  1795. }
  1796. void Graphics::SetDrawBuffers()
  1797. {
  1798. // Calculate the bit combination of non-zero color rendertargets to first check if the combination changed
  1799. unsigned newDrawBuffers = 0;
  1800. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1801. {
  1802. if (renderTargets_[i])
  1803. newDrawBuffers |= 1 << i;
  1804. }
  1805. if (newDrawBuffers == impl_->drawBuffers_)
  1806. return;
  1807. // Check for no color rendertargets (depth rendering only)
  1808. if (!newDrawBuffers)
  1809. glDrawBuffer(GL_NONE);
  1810. else
  1811. {
  1812. int drawBufferIds[4];
  1813. unsigned drawBufferCount = 0;
  1814. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1815. {
  1816. if (renderTargets_[i])
  1817. drawBufferIds[drawBufferCount++] = GL_COLOR_ATTACHMENT0_EXT + i;
  1818. }
  1819. glDrawBuffers(drawBufferCount, (const GLenum*)drawBufferIds);
  1820. }
  1821. glReadBuffer(GL_NONE);
  1822. }
  1823. void Graphics::Release()
  1824. {
  1825. if (!impl_->window_)
  1826. return;
  1827. diffBuffer_.Reset();
  1828. normalBuffer_.Reset();
  1829. depthBuffer_.Reset();
  1830. screenBuffer_.Reset();
  1831. depthTextures_.Clear();
  1832. // If GPU objects exist ie. it's a context delete/recreate, not Close(), tell them to save and release themselves
  1833. for (Vector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  1834. (*i)->OnDeviceLost();
  1835. if (impl_->fbo_)
  1836. {
  1837. glDeleteFramebuffersEXT(1, &impl_->fbo_);
  1838. impl_->fbo_ = 0;
  1839. }
  1840. // When the new context is initialized, it will have default state again
  1841. ResetCachedState();
  1842. ClearParameterSources();
  1843. {
  1844. MutexLock lock(GetStaticMutex());
  1845. SetWindowContext(impl_->window_, 0);
  1846. glfwCloseWindow(impl_->window_);
  1847. impl_->window_ = 0;
  1848. }
  1849. }
  1850. void Graphics::SetTextureUnitMappings()
  1851. {
  1852. // Map texture units
  1853. textureUnits_["NormalMap"] = TU_NORMAL;
  1854. textureUnits_["DiffMap"] = TU_DIFFUSE;
  1855. textureUnits_["DiffCubeMap"] = TU_DIFFUSE;
  1856. textureUnits_["SpecMap"] = TU_SPECULAR;
  1857. textureUnits_["EmissiveMap"] = TU_EMISSIVE;
  1858. textureUnits_["DetailMap"] = TU_DETAIL;
  1859. textureUnits_["EnvironmentMap"] = TU_ENVIRONMENT;
  1860. textureUnits_["EnvironmentCubeMap"] = TU_ENVIRONMENT;
  1861. textureUnits_["LightRampMap"] = TU_LIGHTRAMP;
  1862. textureUnits_["LightSpotMap"] = TU_LIGHTSPOT;
  1863. textureUnits_["LightCubeMap"] = TU_LIGHTSPOT;
  1864. textureUnits_["ShadowMap"] = TU_SHADOWMAP;
  1865. textureUnits_["DiffBuffer"] = TU_DIFFBUFFER;
  1866. textureUnits_["NormalBuffer"] = TU_NORMALBUFFER;
  1867. textureUnits_["DepthBuffer"] = TU_DEPTHBUFFER;
  1868. }
  1869. void RegisterGraphicsLibrary(Context* context)
  1870. {
  1871. Animation::RegisterObject(context);
  1872. Material::RegisterObject(context);
  1873. Model::RegisterObject(context);
  1874. Shader::RegisterObject(context);
  1875. Technique::RegisterObject(context);
  1876. Texture2D::RegisterObject(context);
  1877. TextureCube::RegisterObject(context);
  1878. Camera::RegisterObject(context);
  1879. Drawable::RegisterObject(context);
  1880. Light::RegisterObject(context);
  1881. StaticModel::RegisterObject(context);
  1882. Skybox::RegisterObject(context);
  1883. AnimatedModel::RegisterObject(context);
  1884. AnimationController::RegisterObject(context);
  1885. BillboardSet::RegisterObject(context);
  1886. ParticleEmitter::RegisterObject(context);
  1887. DebugRenderer::RegisterObject(context);
  1888. Octree::RegisterObject(context);
  1889. Zone::RegisterObject(context);
  1890. }