OGLGraphics.cpp 62 KB

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