OGLGraphics.cpp 77 KB

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