OGLGraphics.cpp 72 KB

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