CmRenderSystem.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  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 "CmPixelBuffer.h"
  35. #include "CmOcclusionQuery.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(nullptr)
  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. , mActiveViewport(nullptr)
  64. {
  65. }
  66. //-----------------------------------------------------------------------
  67. RenderSystem::~RenderSystem()
  68. {
  69. // Base classes need to call virtual destroy_internal method (queue it on render thread)
  70. // TODO - What if something gets queued between the queued call to destroy_internal and this!?
  71. shutdownRenderThread();
  72. if(mCommandQueue != nullptr)
  73. {
  74. delete mCommandQueue;
  75. mCommandQueue = nullptr;
  76. }
  77. delete mCurrentCapabilities;
  78. mCurrentCapabilities = 0;
  79. }
  80. //-----------------------------------------------------------------------
  81. void RenderSystem::initialize()
  82. {
  83. mRenderThreadId = CM_THREAD_CURRENT_ID;
  84. mCommandQueue = new CommandQueue(CM_THREAD_CURRENT_ID);
  85. initRenderThread();
  86. queueCommand(boost::bind(&RenderSystem::initialize_internal, this), true);
  87. }
  88. //-----------------------------------------------------------------------
  89. void RenderSystem::initialize_internal()
  90. {
  91. THROW_IF_NOT_RENDER_THREAD;
  92. mVertexProgramBound = false;
  93. mGeometryProgramBound = false;
  94. mFragmentProgramBound = false;
  95. }
  96. //-----------------------------------------------------------------------
  97. void RenderSystem::destroy_internal()
  98. {
  99. // Remove all the render targets.
  100. mRenderTargets.clear();
  101. mPrioritisedRenderTargets.clear();
  102. }
  103. //-----------------------------------------------------------------------
  104. void RenderSystem::swapAllRenderTargetBuffers(bool waitForVSync)
  105. {
  106. THROW_IF_NOT_RENDER_THREAD;
  107. // Update all in order of priority
  108. // This ensures render-to-texture targets get updated before render windows
  109. RenderTargetPriorityMap::iterator itarg, itargend;
  110. itargend = mPrioritisedRenderTargets.end();
  111. for( itarg = mPrioritisedRenderTargets.begin(); itarg != itargend; ++itarg )
  112. {
  113. if( itarg->second->isActive())
  114. itarg->second->swapBuffers(waitForVSync);
  115. }
  116. }
  117. //---------------------------------------------------------------------------------------------
  118. void RenderSystem::destroyRenderWindow(RenderWindow* renderWindow)
  119. {
  120. THROW_IF_NOT_RENDER_THREAD;
  121. destroyRenderTarget(renderWindow);
  122. }
  123. //---------------------------------------------------------------------------------------------
  124. void RenderSystem::destroyRenderTexture(RenderTexture* renderTexture)
  125. {
  126. THROW_IF_NOT_RENDER_THREAD;
  127. destroyRenderTarget(renderTexture);
  128. }
  129. //---------------------------------------------------------------------------------------------
  130. void RenderSystem::destroyRenderTarget(RenderTarget* renderTarget)
  131. {
  132. THROW_IF_NOT_RENDER_THREAD;
  133. detachRenderTarget(*renderTarget);
  134. delete renderTarget;
  135. }
  136. //---------------------------------------------------------------------------------------------
  137. void RenderSystem::attachRenderTarget( RenderTarget &target )
  138. {
  139. THROW_IF_NOT_RENDER_THREAD;
  140. assert( target.getPriority() < CM_NUM_RENDERTARGET_GROUPS );
  141. mRenderTargets.push_back(&target);
  142. mPrioritisedRenderTargets.insert(
  143. RenderTargetPriorityMap::value_type(target.getPriority(), &target ));
  144. }
  145. //---------------------------------------------------------------------------------------------
  146. void RenderSystem::detachRenderTarget(RenderTarget& renderTarget)
  147. {
  148. THROW_IF_NOT_RENDER_THREAD;
  149. auto it = std::find(mRenderTargets.begin(), mRenderTargets.end(), &renderTarget);
  150. RenderTarget* foundRT = nullptr;
  151. if( it != mRenderTargets.end() )
  152. {
  153. foundRT = *it;
  154. /* Remove the render target from the priority groups. */
  155. RenderTargetPriorityMap::iterator itarg, itargend;
  156. itargend = mPrioritisedRenderTargets.end();
  157. for( itarg = mPrioritisedRenderTargets.begin(); itarg != itargend; ++itarg )
  158. {
  159. if( itarg->second == *it ) {
  160. mPrioritisedRenderTargets.erase( itarg );
  161. break;
  162. }
  163. }
  164. mRenderTargets.erase( it );
  165. }
  166. /// If detached render target is the active render target, reset active render target
  167. if(foundRT == mActiveRenderTarget)
  168. mActiveRenderTarget = 0;
  169. }
  170. //---------------------------------------------------------------------------------------------
  171. const RenderSystemCapabilities* RenderSystem::getCapabilities(void) const
  172. {
  173. THROW_IF_NOT_RENDER_THREAD;
  174. return mCurrentCapabilities;
  175. }
  176. //---------------------------------------------------------------------------------------------
  177. const DriverVersion& RenderSystem::getDriverVersion(void) const
  178. {
  179. THROW_IF_NOT_RENDER_THREAD;
  180. return mDriverVersion;
  181. }
  182. //-----------------------------------------------------------------------
  183. const Viewport* RenderSystem::getViewport(void)
  184. {
  185. THROW_IF_NOT_RENDER_THREAD;
  186. return mActiveViewport;
  187. }
  188. //-----------------------------------------------------------------------
  189. void RenderSystem::disableTextureUnit(GpuProgramType gptype, UINT16 texUnit)
  190. {
  191. THROW_IF_NOT_RENDER_THREAD;
  192. setTexture(gptype, texUnit, false, sNullTexPtr);
  193. }
  194. //-----------------------------------------------------------------------
  195. bool RenderSystem::getWaitForVerticalBlank(void) const
  196. {
  197. THROW_IF_NOT_RENDER_THREAD;
  198. return mVsync;
  199. }
  200. //-----------------------------------------------------------------------
  201. void RenderSystem::setWaitForVerticalBlank(bool enabled)
  202. {
  203. THROW_IF_NOT_RENDER_THREAD;
  204. mVsync = enabled;
  205. }
  206. //---------------------------------------------------------------------
  207. void RenderSystem::addClipPlane (const Plane &p)
  208. {
  209. THROW_IF_NOT_RENDER_THREAD;
  210. mClipPlanes.push_back(p);
  211. mClipPlanesDirty = true;
  212. }
  213. //---------------------------------------------------------------------
  214. void RenderSystem::addClipPlane (float A, float B, float C, float D)
  215. {
  216. THROW_IF_NOT_RENDER_THREAD;
  217. addClipPlane(Plane(A, B, C, D));
  218. }
  219. //---------------------------------------------------------------------
  220. void RenderSystem::setClipPlanes(const PlaneList& clipPlanes)
  221. {
  222. THROW_IF_NOT_RENDER_THREAD;
  223. if (clipPlanes != mClipPlanes)
  224. {
  225. mClipPlanes = clipPlanes;
  226. mClipPlanesDirty = true;
  227. }
  228. }
  229. //---------------------------------------------------------------------
  230. void RenderSystem::resetClipPlanes()
  231. {
  232. THROW_IF_NOT_RENDER_THREAD;
  233. if (!mClipPlanes.empty())
  234. {
  235. mClipPlanes.clear();
  236. mClipPlanesDirty = true;
  237. }
  238. }
  239. //-----------------------------------------------------------------------
  240. void RenderSystem::bindGpuProgram(GpuProgramHandle prg)
  241. {
  242. THROW_IF_NOT_RENDER_THREAD;
  243. switch(prg->getBindingDelegate()->getType())
  244. {
  245. case GPT_VERTEX_PROGRAM:
  246. // mark clip planes dirty if changed (programmable can change space)
  247. if (!mVertexProgramBound && !mClipPlanes.empty())
  248. mClipPlanesDirty = true;
  249. mVertexProgramBound = true;
  250. break;
  251. case GPT_GEOMETRY_PROGRAM:
  252. mGeometryProgramBound = true;
  253. break;
  254. case GPT_FRAGMENT_PROGRAM:
  255. mFragmentProgramBound = true;
  256. break;
  257. }
  258. }
  259. //-----------------------------------------------------------------------
  260. void RenderSystem::unbindGpuProgram(GpuProgramType gptype)
  261. {
  262. THROW_IF_NOT_RENDER_THREAD;
  263. switch(gptype)
  264. {
  265. case GPT_VERTEX_PROGRAM:
  266. // mark clip planes dirty if changed (programmable can change space)
  267. if (mVertexProgramBound && !mClipPlanes.empty())
  268. mClipPlanesDirty = true;
  269. mVertexProgramBound = false;
  270. break;
  271. case GPT_GEOMETRY_PROGRAM:
  272. mGeometryProgramBound = false;
  273. break;
  274. case GPT_FRAGMENT_PROGRAM:
  275. mFragmentProgramBound = false;
  276. break;
  277. }
  278. }
  279. //-----------------------------------------------------------------------
  280. bool RenderSystem::isGpuProgramBound(GpuProgramType gptype)
  281. {
  282. THROW_IF_NOT_RENDER_THREAD;
  283. switch(gptype)
  284. {
  285. case GPT_VERTEX_PROGRAM:
  286. return mVertexProgramBound;
  287. case GPT_GEOMETRY_PROGRAM:
  288. return mGeometryProgramBound;
  289. case GPT_FRAGMENT_PROGRAM:
  290. return mFragmentProgramBound;
  291. }
  292. // Make compiler happy
  293. return false;
  294. }
  295. //-----------------------------------------------------------------------
  296. void RenderSystem::render(const RenderOperation& op)
  297. {
  298. THROW_IF_NOT_RENDER_THREAD;
  299. // sort out clip planes
  300. // have to do it here in case of matrix issues
  301. if (mClipPlanesDirty)
  302. {
  303. setClipPlanesImpl(mClipPlanes);
  304. mClipPlanesDirty = false;
  305. }
  306. setVertexDeclaration(op.vertexData->vertexDeclaration);
  307. auto vertexBuffers = op.vertexData->getBuffers();
  308. for(auto iter = vertexBuffers.begin(); iter != vertexBuffers.end() ; ++iter)
  309. setVertexBuffer(iter->first, iter->second);
  310. setDrawOperation(op.operationType);
  311. if (op.useIndexes)
  312. {
  313. setIndexBuffer(op.indexData->indexBuffer);
  314. drawIndexed(op.indexData->indexStart, op.indexData->indexCount, op.vertexData->vertexCount);
  315. }
  316. else
  317. draw(op.vertexData->vertexCount);
  318. }
  319. /************************************************************************/
  320. /* PRIVATE */
  321. /************************************************************************/
  322. void RenderSystem::initRenderThread()
  323. {
  324. #if !CM_FORCE_SINGLETHREADED_RENDERING
  325. mRenderThreadFunc = new RenderWorkerFunc(this);
  326. #if CM_THREAD_SUPPORT
  327. CM_THREAD_CREATE(t, *mRenderThreadFunc);
  328. mRenderThread = t;
  329. CM_LOCK_MUTEX_NAMED(mRenderThreadStartMutex, lock)
  330. CM_THREAD_WAIT(mRenderThreadStartCondition, mRenderThreadStartMutex, lock)
  331. #else
  332. CM_EXCEPT(InternalErrorException, "Attempting to start a render thread but Camelot isn't compiled with thread support.");
  333. #endif
  334. #endif
  335. }
  336. void RenderSystem::runRenderThread()
  337. {
  338. #if !CM_FORCE_SINGLETHREADED_RENDERING
  339. mRenderThreadId = CM_THREAD_CURRENT_ID;
  340. CM_THREAD_NOTIFY_ALL(mRenderThreadStartCondition)
  341. while(true)
  342. {
  343. // Wait until we get some ready commands
  344. vector<CommandQueue::Command>::type* commands = nullptr;
  345. {
  346. CM_LOCK_MUTEX_NAMED(mCommandQueueMutex, lock)
  347. while(mCommandQueue->isEmpty())
  348. {
  349. if(mRenderThreadShutdown)
  350. return;
  351. CM_THREAD_WAIT(mCommandReadyCondition, mCommandQueueMutex, lock);
  352. }
  353. commands = mCommandQueue->flush();
  354. }
  355. // Play commands
  356. mCommandQueue->playback(commands, boost::bind(&RenderSystem::commandCompletedNotify, this, _1));
  357. }
  358. #endif
  359. }
  360. void RenderSystem::shutdownRenderThread()
  361. {
  362. #if !CM_FORCE_SINGLETHREADED_RENDERING
  363. {
  364. CM_LOCK_MUTEX(mCommandQueueMutex);
  365. mRenderThreadShutdown = true;
  366. }
  367. // Wake all threads. They will quit after they see the shutdown flag
  368. CM_THREAD_NOTIFY_ALL(mCommandReadyCondition);
  369. mRenderThread->join();
  370. CM_THREAD_DESTROY(mRenderThread);
  371. mRenderThread = nullptr;
  372. mRenderThreadId = CM_THREAD_CURRENT_ID;
  373. #endif
  374. }
  375. DeferredRenderContextPtr RenderSystem::createDeferredContext()
  376. {
  377. return DeferredRenderContextPtr(new DeferredRenderContext(this, CM_THREAD_CURRENT_ID));
  378. }
  379. AsyncOp RenderSystem::queueReturnCommand(boost::function<void(AsyncOp&)> commandCallback, bool blockUntilComplete)
  380. {
  381. AsyncOp op;
  382. if(CM_THREAD_CURRENT_ID == getRenderThreadId())
  383. {
  384. commandCallback(op); // Execute immediately
  385. return op;
  386. }
  387. UINT32 commandId = -1;
  388. {
  389. CM_LOCK_MUTEX(mCommandQueueMutex);
  390. if(blockUntilComplete)
  391. {
  392. commandId = mMaxCommandNotifyId++;
  393. op = mCommandQueue->queueReturn(commandCallback, true, commandId);
  394. }
  395. else
  396. op = mCommandQueue->queueReturn(commandCallback);
  397. }
  398. CM_THREAD_NOTIFY_ALL(mCommandReadyCondition);
  399. if(blockUntilComplete)
  400. blockUntilCommandCompleted(commandId);
  401. return op;
  402. }
  403. void RenderSystem::queueCommand(boost::function<void()> commandCallback, bool blockUntilComplete)
  404. {
  405. if(CM_THREAD_CURRENT_ID == getRenderThreadId())
  406. {
  407. commandCallback(); // Execute immediately
  408. return;
  409. }
  410. UINT32 commandId = -1;
  411. {
  412. CM_LOCK_MUTEX(mCommandQueueMutex);
  413. if(blockUntilComplete)
  414. {
  415. commandId = mMaxCommandNotifyId++;
  416. mCommandQueue->queue(commandCallback, true, commandId);
  417. }
  418. else
  419. mCommandQueue->queue(commandCallback);
  420. }
  421. CM_THREAD_NOTIFY_ALL(mCommandReadyCondition);
  422. if(blockUntilComplete)
  423. blockUntilCommandCompleted(commandId);
  424. }
  425. void RenderSystem::blockUntilCommandCompleted(UINT32 commandId)
  426. {
  427. #if !CM_FORCE_SINGLETHREADED_RENDERING
  428. CM_LOCK_MUTEX_NAMED(mCommandNotifyMutex, lock);
  429. while(true)
  430. {
  431. // Check if our command id is in the completed list
  432. auto iter = mCommandsCompleted.begin();
  433. for(; iter != mCommandsCompleted.end(); ++iter)
  434. {
  435. if(*iter == commandId)
  436. break;
  437. }
  438. if(iter != mCommandsCompleted.end())
  439. {
  440. mCommandsCompleted.erase(iter);
  441. break;
  442. }
  443. CM_THREAD_WAIT(mCommandCompleteCondition, mCommandNotifyMutex, lock);
  444. }
  445. #endif
  446. }
  447. void RenderSystem::commandCompletedNotify(UINT32 commandId)
  448. {
  449. {
  450. CM_LOCK_MUTEX(mCommandNotifyMutex);
  451. mCommandsCompleted.push_back(commandId);
  452. }
  453. CM_THREAD_NOTIFY_ALL(mCommandCompleteCondition);
  454. }
  455. void RenderSystem::throwIfNotRenderThread() const
  456. {
  457. #if !CM_FORCE_SINGLETHREADED_RENDERING
  458. if(CM_THREAD_CURRENT_ID != getRenderThreadId())
  459. CM_EXCEPT(InternalErrorException, "Calling the render system from a non-render thread!");
  460. #endif
  461. }
  462. /************************************************************************/
  463. /* THREAD WORKER */
  464. /************************************************************************/
  465. RenderSystem::RenderWorkerFunc::RenderWorkerFunc(RenderSystem* rs)
  466. :mRS(rs)
  467. {
  468. assert(mRS != nullptr);
  469. }
  470. void RenderSystem::RenderWorkerFunc::operator()()
  471. {
  472. mRS->runRenderThread();
  473. }
  474. }
  475. #undef THROW_IF_NOT_RENDER_THREAD