CmRenderSystem.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  1. /*
  2. -----------------------------------------------------------------------------
  3. This source file is part of OGRE
  4. (Object-oriented Graphics Rendering Engine)
  5. For the latest info, see http://www.ogre3d.org/
  6. Copyright (c) 2000-2011 Torus Knot Software Ltd
  7. Permission is hereby granted, free of charge, to any person obtaining a copy
  8. of this software and associated documentation files (the "Software"), to deal
  9. in the Software without restriction, including without limitation the rights
  10. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. copies of the Software, and to permit persons to whom the Software is
  12. furnished to do so, subject to the following conditions:
  13. The above copyright notice and this permission notice shall be included in
  14. all copies or substantial portions of the Software.
  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. */
  24. // RenderSystem implementation
  25. // Note that most of this class is abstract since
  26. // we cannot know how to implement the behaviour without
  27. // being aware of the 3D API. However there are a few
  28. // simple functions which can have a base implementation
  29. #include "CmRenderSystem.h"
  30. #include "CmViewport.h"
  31. #include "CmException.h"
  32. #include "CmRenderTarget.h"
  33. #include "CmRenderWindow.h"
  34. #include "CmHardwarePixelBuffer.h"
  35. #include "CmHardwareOcclusionQuery.h"
  36. #include "CmCommandQueue.h"
  37. #include "CmDeferredRenderContext.h"
  38. #include "boost/bind.hpp"
  39. #if CM_DEBUG_MODE
  40. #define THROW_IF_NOT_RENDER_THREAD throwIfNotRenderThread();
  41. #else
  42. #define THROW_IF_NOT_RENDER_THREAD
  43. #endif
  44. namespace CamelotEngine {
  45. static const TexturePtr sNullTexPtr;
  46. //-----------------------------------------------------------------------
  47. RenderSystem::RenderSystem()
  48. : mActiveRenderTarget(0)
  49. , mCullingMode(CULL_CLOCKWISE)
  50. , mVsync(false)
  51. , mVSyncInterval(1)
  52. , mInvertVertexWinding(false)
  53. , mDisabledTexUnitsFrom(0)
  54. , mVertexProgramBound(false)
  55. , mGeometryProgramBound(false)
  56. , mFragmentProgramBound(false)
  57. , mClipPlanesDirty(true)
  58. , mCurrentCapabilities(nullptr)
  59. , mRenderThreadFunc(nullptr)
  60. , mRenderThreadShutdown(false)
  61. , mCommandQueue(nullptr)
  62. , mMaxCommandNotifyId(0)
  63. {
  64. }
  65. //-----------------------------------------------------------------------
  66. RenderSystem::~RenderSystem()
  67. {
  68. shutdown_internal();
  69. delete mCurrentCapabilities;
  70. mCurrentCapabilities = 0;
  71. }
  72. //-----------------------------------------------------------------------
  73. void RenderSystem::startUp()
  74. {
  75. mRenderThreadId = CM_THREAD_CURRENT_ID;
  76. mCommandQueue = new CommandQueue(CM_THREAD_CURRENT_ID);
  77. initRenderThread();
  78. queueCommand(boost::bind(&RenderSystem::startUp_internal, this));
  79. }
  80. //-----------------------------------------------------------------------
  81. void RenderSystem::startUp_internal()
  82. {
  83. THROW_IF_NOT_RENDER_THREAD;
  84. mVertexProgramBound = false;
  85. mGeometryProgramBound = false;
  86. mFragmentProgramBound = false;
  87. }
  88. //-----------------------------------------------------------------------
  89. void RenderSystem::shutdown(void)
  90. {
  91. queueCommand(boost::bind(&RenderSystem::shutdown_internal, this), true);
  92. // TODO - What if something gets queued between these two calls?
  93. shutdownRenderThread();
  94. }
  95. //-----------------------------------------------------------------------
  96. void RenderSystem::shutdown_internal(void)
  97. {
  98. // TODO - I should probably sync this up to make sure no other threads are doing anything while shutdown is in progress
  99. // Remove all the render targets.
  100. // (destroy primary target last since others may depend on it)
  101. RenderTarget* primary = 0;
  102. for (auto it = mRenderTargets.begin(); it != mRenderTargets.end(); ++it)
  103. {
  104. if (!primary && (*it)->isPrimary())
  105. primary = *it;
  106. else
  107. delete *it;
  108. }
  109. delete primary;
  110. mRenderTargets.clear();
  111. mPrioritisedRenderTargets.clear();
  112. if(mCommandQueue != nullptr)
  113. {
  114. delete mCommandQueue;
  115. mCommandQueue = nullptr;
  116. }
  117. }
  118. //-----------------------------------------------------------------------
  119. void RenderSystem::swapAllRenderTargetBuffers(bool waitForVSync)
  120. {
  121. THROW_IF_NOT_RENDER_THREAD;
  122. // Update all in order of priority
  123. // This ensures render-to-texture targets get updated before render windows
  124. RenderTargetPriorityMap::iterator itarg, itargend;
  125. itargend = mPrioritisedRenderTargets.end();
  126. for( itarg = mPrioritisedRenderTargets.begin(); itarg != itargend; ++itarg )
  127. {
  128. if( itarg->second->isActive())
  129. itarg->second->swapBuffers(waitForVSync);
  130. }
  131. }
  132. //---------------------------------------------------------------------------------------------
  133. RenderWindow* RenderSystem::createRenderWindow(const String &name, unsigned int width, unsigned int height,
  134. bool fullScreen, const NameValuePairList *miscParams)
  135. {
  136. AsyncOp op;
  137. if(miscParams != nullptr)
  138. op = queueReturnCommand(boost::bind(&RenderSystem::createRenderWindow_internal, this, name, width, height, fullScreen, *miscParams, _1), true);
  139. else
  140. op = queueReturnCommand(boost::bind(&RenderSystem::createRenderWindow_internal, this, name, width, height, fullScreen, NameValuePairList(), _1), true);
  141. return op.getReturnValue<RenderWindow*>();
  142. }
  143. //---------------------------------------------------------------------------------------------
  144. void RenderSystem::destroyRenderWindow(RenderWindow* renderWindow)
  145. {
  146. THROW_IF_NOT_RENDER_THREAD;
  147. destroyRenderTarget(renderWindow);
  148. }
  149. //---------------------------------------------------------------------------------------------
  150. void RenderSystem::destroyRenderTexture(RenderTexture* renderTexture)
  151. {
  152. THROW_IF_NOT_RENDER_THREAD;
  153. destroyRenderTarget(renderTexture);
  154. }
  155. //---------------------------------------------------------------------------------------------
  156. void RenderSystem::destroyRenderTarget(RenderTarget* renderTarget)
  157. {
  158. THROW_IF_NOT_RENDER_THREAD;
  159. detachRenderTarget(*renderTarget);
  160. delete renderTarget;
  161. }
  162. //---------------------------------------------------------------------------------------------
  163. void RenderSystem::attachRenderTarget( RenderTarget &target )
  164. {
  165. THROW_IF_NOT_RENDER_THREAD;
  166. assert( target.getPriority() < CM_NUM_RENDERTARGET_GROUPS );
  167. mRenderTargets.push_back(&target);
  168. mPrioritisedRenderTargets.insert(
  169. RenderTargetPriorityMap::value_type(target.getPriority(), &target ));
  170. }
  171. //---------------------------------------------------------------------------------------------
  172. void RenderSystem::detachRenderTarget(RenderTarget& renderTarget)
  173. {
  174. THROW_IF_NOT_RENDER_THREAD;
  175. auto it = std::find(mRenderTargets.begin(), mRenderTargets.end(), &renderTarget);
  176. RenderTarget* foundRT = nullptr;
  177. if( it != mRenderTargets.end() )
  178. {
  179. foundRT = *it;
  180. /* Remove the render target from the priority groups. */
  181. RenderTargetPriorityMap::iterator itarg, itargend;
  182. itargend = mPrioritisedRenderTargets.end();
  183. for( itarg = mPrioritisedRenderTargets.begin(); itarg != itargend; ++itarg )
  184. {
  185. if( itarg->second == *it ) {
  186. mPrioritisedRenderTargets.erase( itarg );
  187. break;
  188. }
  189. }
  190. mRenderTargets.erase( it );
  191. }
  192. /// If detached render target is the active render target, reset active render target
  193. if(foundRT == mActiveRenderTarget)
  194. mActiveRenderTarget = 0;
  195. }
  196. //---------------------------------------------------------------------------------------------
  197. const RenderSystemCapabilities* RenderSystem::getCapabilities(void) const
  198. {
  199. THROW_IF_NOT_RENDER_THREAD;
  200. return mCurrentCapabilities;
  201. }
  202. //---------------------------------------------------------------------------------------------
  203. const DriverVersion& RenderSystem::getDriverVersion(void) const
  204. {
  205. THROW_IF_NOT_RENDER_THREAD;
  206. return mDriverVersion;
  207. }
  208. //-----------------------------------------------------------------------
  209. Viewport RenderSystem::getViewport(void)
  210. {
  211. THROW_IF_NOT_RENDER_THREAD;
  212. return mActiveViewport;
  213. }
  214. //-----------------------------------------------------------------------
  215. void RenderSystem::setSamplerState(UINT16 texUnit, const SamplerState& tl)
  216. {
  217. THROW_IF_NOT_RENDER_THREAD;
  218. // This method is only ever called to set a texture unit to valid details
  219. // The method _disableTextureUnit is called to turn a unit off
  220. // Set texture layer filtering
  221. setTextureFiltering(texUnit,
  222. tl.getTextureFiltering(FT_MIN),
  223. tl.getTextureFiltering(FT_MAG),
  224. tl.getTextureFiltering(FT_MIP));
  225. // Set texture layer filtering
  226. setTextureAnisotropy(texUnit, tl.getTextureAnisotropy());
  227. // Set mipmap biasing
  228. setTextureMipmapBias(texUnit, tl.getTextureMipmapBias());
  229. // Texture addressing mode
  230. const UVWAddressingMode& uvw = tl.getTextureAddressingMode();
  231. setTextureAddressingMode(texUnit, uvw);
  232. }
  233. //-----------------------------------------------------------------------
  234. void RenderSystem::disableTextureUnit(UINT16 texUnit)
  235. {
  236. THROW_IF_NOT_RENDER_THREAD;
  237. setTexture(texUnit, false, sNullTexPtr);
  238. }
  239. //---------------------------------------------------------------------
  240. void RenderSystem::disableTextureUnitsFrom(UINT16 texUnit)
  241. {
  242. THROW_IF_NOT_RENDER_THREAD;
  243. UINT16 disableTo = CM_MAX_TEXTURE_LAYERS;
  244. if (disableTo > mDisabledTexUnitsFrom)
  245. disableTo = mDisabledTexUnitsFrom;
  246. mDisabledTexUnitsFrom = texUnit;
  247. for (UINT16 i = texUnit; i < disableTo; ++i)
  248. {
  249. disableTextureUnit(i);
  250. }
  251. }
  252. //-----------------------------------------------------------------------
  253. void RenderSystem::setTextureFiltering(UINT16 unit, FilterOptions minFilter,
  254. FilterOptions magFilter, FilterOptions mipFilter)
  255. {
  256. THROW_IF_NOT_RENDER_THREAD;
  257. setTextureFiltering(unit, FT_MIN, minFilter);
  258. setTextureFiltering(unit, FT_MAG, magFilter);
  259. setTextureFiltering(unit, FT_MIP, mipFilter);
  260. }
  261. //-----------------------------------------------------------------------
  262. bool RenderSystem::getWaitForVerticalBlank(void) const
  263. {
  264. THROW_IF_NOT_RENDER_THREAD;
  265. return mVsync;
  266. }
  267. //-----------------------------------------------------------------------
  268. void RenderSystem::setWaitForVerticalBlank(bool enabled)
  269. {
  270. THROW_IF_NOT_RENDER_THREAD;
  271. mVsync = enabled;
  272. }
  273. //-----------------------------------------------------------------------
  274. void RenderSystem::setInvertVertexWinding_(bool invert)
  275. {
  276. THROW_IF_NOT_RENDER_THREAD;
  277. mInvertVertexWinding = invert;
  278. }
  279. //-----------------------------------------------------------------------
  280. bool RenderSystem::getInvertVertexWinding(void) const
  281. {
  282. THROW_IF_NOT_RENDER_THREAD;
  283. return mInvertVertexWinding;
  284. }
  285. //-----------------------------------------------------------------------
  286. CullingMode RenderSystem::getCullingMode(void) const
  287. {
  288. THROW_IF_NOT_RENDER_THREAD;
  289. return mCullingMode;
  290. }
  291. //---------------------------------------------------------------------
  292. void RenderSystem::addClipPlane (const Plane &p)
  293. {
  294. THROW_IF_NOT_RENDER_THREAD;
  295. mClipPlanes.push_back(p);
  296. mClipPlanesDirty = true;
  297. }
  298. //---------------------------------------------------------------------
  299. void RenderSystem::addClipPlane (float A, float B, float C, float D)
  300. {
  301. THROW_IF_NOT_RENDER_THREAD;
  302. addClipPlane(Plane(A, B, C, D));
  303. }
  304. //---------------------------------------------------------------------
  305. void RenderSystem::setClipPlanes(const PlaneList& clipPlanes)
  306. {
  307. THROW_IF_NOT_RENDER_THREAD;
  308. if (clipPlanes != mClipPlanes)
  309. {
  310. mClipPlanes = clipPlanes;
  311. mClipPlanesDirty = true;
  312. }
  313. }
  314. //---------------------------------------------------------------------
  315. void RenderSystem::resetClipPlanes()
  316. {
  317. THROW_IF_NOT_RENDER_THREAD;
  318. if (!mClipPlanes.empty())
  319. {
  320. mClipPlanes.clear();
  321. mClipPlanesDirty = true;
  322. }
  323. }
  324. //-----------------------------------------------------------------------
  325. void RenderSystem::bindGpuProgram(GpuProgramHandle prg)
  326. {
  327. THROW_IF_NOT_RENDER_THREAD;
  328. switch(prg->getBindingDelegate_internal()->getType())
  329. {
  330. case GPT_VERTEX_PROGRAM:
  331. // mark clip planes dirty if changed (programmable can change space)
  332. if (!mVertexProgramBound && !mClipPlanes.empty())
  333. mClipPlanesDirty = true;
  334. mVertexProgramBound = true;
  335. break;
  336. case GPT_GEOMETRY_PROGRAM:
  337. mGeometryProgramBound = true;
  338. break;
  339. case GPT_FRAGMENT_PROGRAM:
  340. mFragmentProgramBound = true;
  341. break;
  342. }
  343. }
  344. //-----------------------------------------------------------------------
  345. void RenderSystem::unbindGpuProgram(GpuProgramType gptype)
  346. {
  347. THROW_IF_NOT_RENDER_THREAD;
  348. switch(gptype)
  349. {
  350. case GPT_VERTEX_PROGRAM:
  351. // mark clip planes dirty if changed (programmable can change space)
  352. if (mVertexProgramBound && !mClipPlanes.empty())
  353. mClipPlanesDirty = true;
  354. mVertexProgramBound = false;
  355. break;
  356. case GPT_GEOMETRY_PROGRAM:
  357. mGeometryProgramBound = false;
  358. break;
  359. case GPT_FRAGMENT_PROGRAM:
  360. mFragmentProgramBound = false;
  361. break;
  362. }
  363. }
  364. //-----------------------------------------------------------------------
  365. bool RenderSystem::isGpuProgramBound(GpuProgramType gptype)
  366. {
  367. THROW_IF_NOT_RENDER_THREAD;
  368. switch(gptype)
  369. {
  370. case GPT_VERTEX_PROGRAM:
  371. return mVertexProgramBound;
  372. case GPT_GEOMETRY_PROGRAM:
  373. return mGeometryProgramBound;
  374. case GPT_FRAGMENT_PROGRAM:
  375. return mFragmentProgramBound;
  376. }
  377. // Make compiler happy
  378. return false;
  379. }
  380. //-----------------------------------------------------------------------
  381. void RenderSystem::render(const RenderOperation& op)
  382. {
  383. THROW_IF_NOT_RENDER_THREAD;
  384. // sort out clip planes
  385. // have to do it here in case of matrix issues
  386. if (mClipPlanesDirty)
  387. {
  388. setClipPlanesImpl(mClipPlanes);
  389. mClipPlanesDirty = false;
  390. }
  391. }
  392. /************************************************************************/
  393. /* PRIVATE */
  394. /************************************************************************/
  395. void RenderSystem::initRenderThread()
  396. {
  397. mRenderThreadFunc = new RenderWorkerFunc(this);
  398. #if CM_THREAD_SUPPORT
  399. CM_THREAD_CREATE(t, *mRenderThreadFunc);
  400. mRenderThread = t;
  401. CM_LOCK_MUTEX_NAMED(mRenderThreadStartMutex, lock)
  402. CM_THREAD_WAIT(mRenderThreadStartCondition, mRenderThreadStartMutex, lock)
  403. #else
  404. CM_EXCEPT(InternalErrorException, "Attempting to start a render thread but Camelot isn't compiled with thread support.");
  405. #endif
  406. }
  407. void RenderSystem::runRenderThread()
  408. {
  409. mRenderThreadId = CM_THREAD_CURRENT_ID;
  410. CM_THREAD_NOTIFY_ALL(mRenderThreadStartCondition)
  411. while(true)
  412. {
  413. if(mRenderThreadShutdown)
  414. return;
  415. // Wait until we get some ready commands
  416. vector<CommandQueue::Command>::type* commands = nullptr;
  417. {
  418. CM_LOCK_MUTEX_NAMED(mCommandQueueMutex, lock)
  419. while(mCommandQueue->isEmpty())
  420. CM_THREAD_WAIT(mCommandReadyCondition, mCommandQueueMutex, lock)
  421. commands = mCommandQueue->flush();
  422. }
  423. // Play commands
  424. mCommandQueue->playback(commands, boost::bind(&RenderSystem::commandCompletedNotify, this, _1));
  425. }
  426. }
  427. void RenderSystem::shutdownRenderThread()
  428. {
  429. mRenderThreadShutdown = true;
  430. // Wake all threads. They will quit after they see the shutdown flag
  431. CM_THREAD_NOTIFY_ALL(mCommandReadyCondition)
  432. mRenderThread->join();
  433. CM_THREAD_DESTROY(mRenderThread);
  434. mRenderThread = nullptr;
  435. mRenderThreadId = CM_THREAD_CURRENT_ID;
  436. }
  437. DeferredRenderContextPtr RenderSystem::createDeferredContext()
  438. {
  439. return DeferredRenderContextPtr(new DeferredRenderContext(this, CM_THREAD_CURRENT_ID));
  440. }
  441. AsyncOp RenderSystem::queueReturnCommand(boost::function<void(AsyncOp&)> commandCallback, bool blockUntilComplete)
  442. {
  443. #ifdef CM_DEBUG_MODE
  444. if(CM_THREAD_CURRENT_ID == getRenderThreadId())
  445. CM_EXCEPT(InternalErrorException, "You are not allowed to call this method on the render thread!");
  446. #endif
  447. AsyncOp op;
  448. UINT32 commandId = -1;
  449. {
  450. CM_LOCK_MUTEX(mCommandQueueMutex);
  451. if(blockUntilComplete)
  452. {
  453. commandId = mMaxCommandNotifyId++;
  454. op = mCommandQueue->queueReturn(commandCallback, true, commandId);
  455. }
  456. else
  457. op = mCommandQueue->queueReturn(commandCallback);
  458. }
  459. CM_THREAD_NOTIFY_ALL(mCommandReadyCondition);
  460. if(blockUntilComplete)
  461. blockUntilCommandCompleted(commandId);
  462. return op;
  463. }
  464. void RenderSystem::queueCommand(boost::function<void()> commandCallback, bool blockUntilComplete)
  465. {
  466. #ifdef CM_DEBUG_MODE
  467. if(CM_THREAD_CURRENT_ID == getRenderThreadId())
  468. CM_EXCEPT(InternalErrorException, "You are not allowed to call this method on the render thread!");
  469. #endif
  470. UINT32 commandId = -1;
  471. {
  472. CM_LOCK_MUTEX(mCommandQueueMutex);
  473. if(blockUntilComplete)
  474. {
  475. commandId = mMaxCommandNotifyId++;
  476. mCommandQueue->queue(commandCallback, true, commandId);
  477. }
  478. else
  479. mCommandQueue->queue(commandCallback);
  480. }
  481. CM_THREAD_NOTIFY_ALL(mCommandReadyCondition);
  482. if(blockUntilComplete)
  483. blockUntilCommandCompleted(commandId);
  484. }
  485. void RenderSystem::blockUntilCommandCompleted(UINT32 commandId)
  486. {
  487. CM_LOCK_MUTEX_NAMED(mCommandNotifyMutex, lock);
  488. while(true)
  489. {
  490. // Check if our command id is in the completed list
  491. auto iter = mCommandsCompleted.begin();
  492. for(; iter != mCommandsCompleted.end(); ++iter)
  493. {
  494. if(*iter == commandId)
  495. break;
  496. }
  497. if(iter != mCommandsCompleted.end())
  498. {
  499. mCommandsCompleted.erase(iter);
  500. break;
  501. }
  502. CM_THREAD_WAIT(mCommandCompleteCondition, mCommandNotifyMutex, lock);
  503. }
  504. }
  505. void RenderSystem::commandCompletedNotify(UINT32 commandId)
  506. {
  507. {
  508. CM_LOCK_MUTEX(mCommandNotifyMutex);
  509. mCommandsCompleted.push_back(commandId);
  510. }
  511. CM_THREAD_NOTIFY_ALL(mCommandCompleteCondition);
  512. }
  513. void RenderSystem::throwIfNotRenderThread() const
  514. {
  515. if(CM_THREAD_CURRENT_ID != getRenderThreadId())
  516. CM_EXCEPT(InternalErrorException, "Calling the render system from a non-render thread!");
  517. }
  518. /************************************************************************/
  519. /* THREAD WORKER */
  520. /************************************************************************/
  521. RenderSystem::RenderWorkerFunc::RenderWorkerFunc(RenderSystem* rs)
  522. :mRS(rs)
  523. {
  524. assert(mRS != nullptr);
  525. }
  526. void RenderSystem::RenderWorkerFunc::operator()()
  527. {
  528. mRS->runRenderThread();
  529. }
  530. }
  531. #undef THROW_IF_NOT_RENDER_THREAD