guiTSControl.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "platform/platform.h"
  23. #include "gui/3d/guiTSControl.h"
  24. #include "gui/core/guiOffscreenCanvas.h"
  25. #include "console/engineAPI.h"
  26. #include "scene/sceneManager.h"
  27. #include "lighting/lightManager.h"
  28. #include "gfx/sim/debugDraw.h"
  29. #include "gfx/gfxTransformSaver.h"
  30. #include "gfx/screenshot.h"
  31. #include "math/mathUtils.h"
  32. #include "gui/core/guiCanvas.h"
  33. #include "scene/reflectionManager.h"
  34. #include "postFx/postEffectManager.h"
  35. #include "gfx/gfxTransformSaver.h"
  36. #include "gfx/gfxDrawUtil.h"
  37. #include "gfx/gfxDebugEvent.h"
  38. #include "core/stream/fileStream.h"
  39. #include "platform/output/IDisplayDevice.h"
  40. #include "T3D/gameBase/extended/extendedMove.h"
  41. #define TS_OVERLAY_SCREEN_WIDTH 0.75
  42. IMPLEMENT_CONOBJECT( GuiTSCtrl );
  43. ConsoleDocClass( GuiTSCtrl,
  44. "@brief Abstract base class for controls that render 3D scenes.\n\n"
  45. "GuiTSCtrl is the base class for controls that render 3D camera views in Torque. The class itself "
  46. "does not implement a concrete scene rendering. Use GuiObjectView to display invidiual shapes in "
  47. "the Gui and GameTSCtrl to render full scenes.\n\n"
  48. "@see GameTSCtrl\n"
  49. "@see GuiObjectView\n"
  50. "@ingroup Gui3D\n"
  51. );
  52. U32 GuiTSCtrl::smFrameCount = 0;
  53. bool GuiTSCtrl::smUseLatestDisplayTransform = true;
  54. Vector<GuiTSCtrl*> GuiTSCtrl::smAwakeTSCtrls;
  55. ImplementEnumType( GuiTSRenderStyles,
  56. "Style of rendering for a GuiTSCtrl.\n\n"
  57. "@ingroup Gui3D" )
  58. { GuiTSCtrl::RenderStyleStandard, "standard" },
  59. { GuiTSCtrl::RenderStyleStereoSideBySide, "stereo side by side" },
  60. { GuiTSCtrl::RenderStyleStereoSeparate, "stereo separate" },
  61. EndImplementEnumType;
  62. //-----------------------------------------------------------------------------
  63. namespace
  64. {
  65. void _drawLine( const Point3F &p0, const Point3F &p1, const ColorI &color, F32 width )
  66. {
  67. F32 x1, x2, y1, y2, z1, z2;
  68. x1 = p0.x;
  69. y1 = p0.y;
  70. z1 = p0.z;
  71. x2 = p1.x;
  72. y2 = p1.y;
  73. z2 = p1.z;
  74. //
  75. // Convert Line a----------b
  76. //
  77. // Into Quad v0---------v1
  78. // a b
  79. // v2---------v3
  80. //
  81. Point2F start(x1, y1);
  82. Point2F end(x2, y2);
  83. Point2F perp, lineVec;
  84. // handle degenerate case where point a = b
  85. if(x1 == x2 && y1 == y2)
  86. {
  87. perp.set(0.0f, width * 0.5f);
  88. lineVec.set(0.1f, 0.0f);
  89. }
  90. else
  91. {
  92. perp.set(start.y - end.y, end.x - start.x);
  93. lineVec.set(end.x - start.x, end.y - start.y);
  94. perp.normalize(width * 0.5f);
  95. lineVec.normalize(0.1f);
  96. }
  97. start -= lineVec;
  98. end += lineVec;
  99. GFXVertexBufferHandle<GFXVertexPCT> verts(GFX, 4, GFXBufferTypeVolatile);
  100. verts.lock();
  101. verts[0].point.set( start.x+perp.x, start.y+perp.y, z1 );
  102. verts[1].point.set( end.x+perp.x, end.y+perp.y, z2 );
  103. verts[2].point.set( start.x-perp.x, start.y-perp.y, z1 );
  104. verts[3].point.set( end.x-perp.x, end.y-perp.y, z2 );
  105. verts[0].color = color;
  106. verts[1].color = color;
  107. verts[2].color = color;
  108. verts[3].color = color;
  109. verts.unlock();
  110. GFX->setVertexBuffer( verts );
  111. GFXStateBlockDesc desc;
  112. desc.setCullMode(GFXCullNone);
  113. desc.setZReadWrite(false);
  114. desc.setBlend(true, GFXBlendSrcAlpha, GFXBlendInvSrcAlpha);
  115. GFX->setStateBlockByDesc( desc );
  116. GFX->setupGenericShaders();
  117. GFX->drawPrimitive( GFXTriangleStrip, 0, 2 );
  118. }
  119. }
  120. //-----------------------------------------------------------------------------
  121. GuiTSCtrl::GuiTSCtrl()
  122. {
  123. mCameraZRot = 0;
  124. mForceFOV = 0;
  125. mReflectPriority = 1.0f;
  126. mRenderStyle = RenderStyleStandard;
  127. mSaveModelview.identity();
  128. mSaveProjection.identity();
  129. mSaveViewport.set( 0, 0, 10, 10 );
  130. mSaveWorldToScreenScale.set( 0, 0 );
  131. mLastCameraQuery.cameraMatrix.identity();
  132. mLastCameraQuery.fov = 45.0f;
  133. mLastCameraQuery.object = NULL;
  134. mLastCameraQuery.farPlane = 10.0f;
  135. mLastCameraQuery.nearPlane = 0.01f;
  136. mLastCameraQuery.projectionOffset = Point2F::Zero;
  137. mLastCameraQuery.hasFovPort = false;
  138. mLastCameraQuery.hasStereoTargets = false;
  139. mLastCameraQuery.ortho = false;
  140. }
  141. //-----------------------------------------------------------------------------
  142. void GuiTSCtrl::initPersistFields()
  143. {
  144. addGroup( "Camera" );
  145. addField("cameraZRot", TypeF32, Offset(mCameraZRot, GuiTSCtrl),
  146. "Z rotation angle of camera." );
  147. addField("forceFOV", TypeF32, Offset(mForceFOV, GuiTSCtrl),
  148. "The vertical field of view in degrees or zero to use the normal camera FOV." );
  149. endGroup( "Camera" );
  150. addGroup( "Rendering" );
  151. addField( "reflectPriority", TypeF32, Offset( mReflectPriority, GuiTSCtrl ),
  152. "The share of the per-frame reflection update work this control's rendering should run.\n"
  153. "The reflect update priorities of all visible GuiTSCtrls are added together and each control is assigned "
  154. "a share of the per-frame reflection update time according to its percentage of the total priority value." );
  155. addField("renderStyle", TYPEID< RenderStyles >(), Offset(mRenderStyle, GuiTSCtrl),
  156. "Indicates how this control should render its contents." );
  157. endGroup( "Rendering" );
  158. Parent::initPersistFields();
  159. }
  160. //-----------------------------------------------------------------------------
  161. void GuiTSCtrl::consoleInit()
  162. {
  163. Con::addVariable("$TSControl::frameCount", TypeS32, &smFrameCount, "The number of frames that have been rendered since this control was created.\n"
  164. "@ingroup Rendering\n");
  165. Con::addVariable("$TSControl::useLatestDisplayTransform", TypeBool, &smUseLatestDisplayTransform, "Use the latest view transform when rendering stereo instead of the one calculated by the last move.\n"
  166. "@ingroup Rendering\n");
  167. }
  168. //-----------------------------------------------------------------------------
  169. bool GuiTSCtrl::onWake()
  170. {
  171. if ( !Parent::onWake() )
  172. return false;
  173. // Add ourselves to the active viewport list.
  174. AssertFatal( !smAwakeTSCtrls.contains( this ),
  175. "GuiTSCtrl::onWake - This control is already in the awake list!" );
  176. smAwakeTSCtrls.push_back( this );
  177. // For VR
  178. mLastCameraQuery.drawCanvas = getRoot();
  179. return true;
  180. }
  181. //-----------------------------------------------------------------------------
  182. void GuiTSCtrl::onSleep()
  183. {
  184. Parent::onSleep();
  185. AssertFatal( smAwakeTSCtrls.contains( this ),
  186. "GuiTSCtrl::onSleep - This control is not in the awake list!" );
  187. smAwakeTSCtrls.remove( this );
  188. }
  189. //-----------------------------------------------------------------------------
  190. void GuiTSCtrl::onPreRender()
  191. {
  192. setUpdate();
  193. }
  194. //-----------------------------------------------------------------------------
  195. bool GuiTSCtrl::processCameraQuery(CameraQuery *)
  196. {
  197. return false;
  198. }
  199. //-----------------------------------------------------------------------------
  200. void GuiTSCtrl::renderWorld(const RectI& /*updateRect*/)
  201. {
  202. }
  203. //-----------------------------------------------------------------------------
  204. F32 GuiTSCtrl::projectRadius( F32 dist, F32 radius ) const
  205. {
  206. // Fixup any negative or zero distance so we
  207. // don't get a divide by zero.
  208. dist = dist > 0.0f ? dist : 0.001f;
  209. return ( radius / dist ) * mSaveWorldToScreenScale.y;
  210. }
  211. //-----------------------------------------------------------------------------
  212. bool GuiTSCtrl::project( const Point3F &pt, Point3F *dest ) const
  213. {
  214. return MathUtils::mProjectWorldToScreen(pt,dest,mSaveViewport,mSaveModelview,mSaveProjection);
  215. }
  216. //-----------------------------------------------------------------------------
  217. bool GuiTSCtrl::unproject( const Point3F &pt, Point3F *dest ) const
  218. {
  219. MathUtils::mProjectScreenToWorld(pt,dest,mSaveViewport,mSaveModelview,mSaveProjection,mLastCameraQuery.farPlane,mLastCameraQuery.nearPlane);
  220. return true;
  221. }
  222. //-----------------------------------------------------------------------------
  223. F32 GuiTSCtrl::calculateViewDistance(F32 radius)
  224. {
  225. F32 fov = mLastCameraQuery.fov;
  226. F32 wwidth;
  227. F32 wheight;
  228. F32 renderWidth = (mRenderStyle == RenderStyleStereoSideBySide) ? F32(getWidth())*0.5f : F32(getWidth());
  229. F32 renderHeight = F32(getHeight());
  230. F32 aspectRatio = renderWidth / renderHeight;
  231. // Use the FOV to calculate the viewport height scale
  232. // then generate the width scale from the aspect ratio.
  233. if(!mLastCameraQuery.ortho)
  234. {
  235. wheight = mLastCameraQuery.nearPlane * mTan(mLastCameraQuery.fov / 2.0f);
  236. wwidth = aspectRatio * wheight;
  237. }
  238. else
  239. {
  240. wheight = mLastCameraQuery.fov;
  241. wwidth = aspectRatio * wheight;
  242. }
  243. // Now determine if we should use the width
  244. // fov or height fov.
  245. //
  246. // If the window is taller than it is wide, use the
  247. // width fov to keep the object completely in view.
  248. if (wheight > wwidth)
  249. fov = mAtan( wwidth / mLastCameraQuery.nearPlane ) * 2.0f;
  250. return radius / mTan(fov / 2.0f);
  251. }
  252. //-----------------------------------------------------------------------------
  253. static FovPort CalculateFovPortForCanvas(const RectI viewport, const CameraQuery &cameraQuery)
  254. {
  255. F32 wwidth;
  256. F32 wheight;
  257. F32 renderWidth = viewport.extent.x;
  258. F32 renderHeight = viewport.extent.y;
  259. F32 aspectRatio = renderWidth / renderHeight;
  260. // Use the FOV to calculate the viewport height scale
  261. // then generate the width scale from the aspect ratio.
  262. if(!cameraQuery.ortho)
  263. {
  264. wheight = /*cameraQuery.nearPlane * */ mTan(cameraQuery.fov / 2.0f);
  265. wwidth = aspectRatio * wheight;
  266. }
  267. else
  268. {
  269. wheight = cameraQuery.fov;
  270. wwidth = aspectRatio * wheight;
  271. }
  272. F32 hscale = wwidth * 2.0f / renderWidth;
  273. F32 vscale = wheight * 2.0f / renderHeight;
  274. F32 left = 0.0f * hscale - wwidth;
  275. F32 right = renderWidth * hscale - wwidth;
  276. F32 top = wheight - vscale * 0.0f;
  277. F32 bottom = wheight - vscale * renderHeight;
  278. FovPort fovPort;
  279. fovPort.upTan = top;
  280. fovPort.downTan = -bottom;
  281. fovPort.leftTan = -left;
  282. fovPort.rightTan = right;
  283. return fovPort;
  284. }
  285. void GuiTSCtrl::_internalRender(RectI viewport, Frustum &frustum)
  286. {
  287. GFXTransformSaver saver;
  288. Point2I renderSize = viewport.extent;
  289. if (mReflectPriority > 0)
  290. {
  291. // Get the total reflection priority.
  292. F32 totalPriority = 0;
  293. for (U32 i = 0; i < smAwakeTSCtrls.size(); i++)
  294. if (smAwakeTSCtrls[i]->isVisible())
  295. totalPriority += smAwakeTSCtrls[i]->mReflectPriority;
  296. REFLECTMGR->update(mReflectPriority / totalPriority,
  297. getExtent(),
  298. mLastCameraQuery);
  299. }
  300. if (mForceFOV != 0)
  301. mLastCameraQuery.fov = mDegToRad(mForceFOV);
  302. if (mCameraZRot)
  303. {
  304. MatrixF rotMat(EulerF(0, 0, mDegToRad(mCameraZRot)));
  305. mLastCameraQuery.cameraMatrix.mul(rotMat);
  306. }
  307. GFX->setViewport(viewport);
  308. // Clear the zBuffer so GUI doesn't hose object rendering accidentally
  309. GFX->clear(GFXClearZBuffer, ColorI(20, 20, 20), 1.0f, 0);
  310. GFX->setFrustum(frustum);
  311. mSaveProjection = GFX->getProjectionMatrix();
  312. if (mLastCameraQuery.ortho)
  313. {
  314. mOrthoWidth = frustum.getWidth();
  315. mOrthoHeight = frustum.getHeight();
  316. }
  317. // We're going to be displaying this render at size of this control in
  318. // pixels - let the scene know so that it can calculate e.g. reflections
  319. // correctly for that final display result.
  320. gClientSceneGraph->setDisplayTargetResolution(renderSize);
  321. // Set the GFX world matrix to the world-to-camera transform, but don't
  322. // change the cameraMatrix in mLastCameraQuery. This is because
  323. // mLastCameraQuery.cameraMatrix is supposed to contain the camera-to-world
  324. // transform. In-place invert would save a copy but mess up any GUIs that
  325. // depend on that value.
  326. MatrixF worldToCamera = mLastCameraQuery.cameraMatrix;
  327. worldToCamera.inverse();
  328. GFX->setWorldMatrix(worldToCamera);
  329. mSaveProjection = GFX->getProjectionMatrix();
  330. mSaveModelview = GFX->getWorldMatrix();
  331. mSaveViewport = viewport;
  332. mSaveWorldToScreenScale = GFX->getWorldToScreenScale();
  333. mSaveFrustum = GFX->getFrustum();
  334. mSaveFrustum.setTransform(mLastCameraQuery.cameraMatrix);
  335. // Set the default non-clip projection as some
  336. // objects depend on this even in non-reflect cases.
  337. gClientSceneGraph->setNonClipProjection(mSaveProjection);
  338. // Give the post effect manager the worldToCamera, and cameraToScreen matrices
  339. PFXMGR->setFrameMatrices(mSaveModelview, mSaveProjection);
  340. renderWorld(viewport);
  341. DebugDrawer::get()->render();
  342. // Render the canvas overlay if its available
  343. if (mStereoCanvas.getPointer() && mStereoGuiTarget.getPointer() && mStereoCanvas->size() != 0)
  344. {
  345. GFXDEBUGEVENT_SCOPE(StereoGui_Render, ColorI(255, 0, 0));
  346. MatrixF proj(1);
  347. Frustum originalFrustum = frustum;
  348. GFXTextureObject *texObject = mStereoGuiTarget->getTexture(0);
  349. const FovPort *currentFovPort = GFX->getStereoFovPort();
  350. const MatrixF *eyeTransforms = GFX->getStereoEyeTransforms();
  351. const Point3F *eyeOffset = GFX->getStereoEyeOffsets();
  352. Frustum gfxFrustum = originalFrustum;
  353. GFX->setClipRect(viewport);
  354. GFX->setViewport(viewport);
  355. GFX->setFrustum(frustum);
  356. MatrixF eyeWorldTrans(1);
  357. if (mLastCameraQuery.currentEye != -1)
  358. {
  359. eyeWorldTrans.setPosition(Point3F(eyeOffset[mLastCameraQuery.currentEye].x, eyeOffset[mLastCameraQuery.currentEye].y, eyeOffset[mLastCameraQuery.currentEye].z));
  360. }
  361. MatrixF eyeWorld(1);
  362. eyeWorld.mul(eyeWorldTrans);
  363. eyeWorld.inverse();
  364. GFX->setWorldMatrix(eyeWorld);
  365. GFX->setViewMatrix(MatrixF::Identity);
  366. if (!mStereoOverlayVB.getPointer())
  367. {
  368. mStereoOverlayVB.set(GFX, 4, GFXBufferTypeStatic);
  369. GFXVertexPCT *verts = mStereoOverlayVB.lock(0, 4);
  370. F32 texLeft = 0.0f;
  371. F32 texRight = 1.0f;
  372. F32 texTop = 1.0f;
  373. F32 texBottom = 0.0f;
  374. F32 rectRatio = gfxFrustum.getWidth() / gfxFrustum.getHeight();
  375. F32 rectWidth = gfxFrustum.getWidth() * TS_OVERLAY_SCREEN_WIDTH;
  376. F32 rectHeight = rectWidth * rectRatio;
  377. F32 screenLeft = -rectWidth * 0.5;
  378. F32 screenRight = rectWidth * 0.5;
  379. F32 screenTop = -rectHeight * 0.5;
  380. F32 screenBottom = rectHeight * 0.5;
  381. const F32 fillConv = 0.0f;
  382. const F32 frustumDepthAdjusted = gfxFrustum.getNearDist() + 0.012;
  383. verts[0].point.set(screenLeft - fillConv, frustumDepthAdjusted, screenTop - fillConv);
  384. verts[1].point.set(screenRight - fillConv, frustumDepthAdjusted, screenTop - fillConv);
  385. verts[2].point.set(screenLeft - fillConv, frustumDepthAdjusted, screenBottom - fillConv);
  386. verts[3].point.set(screenRight - fillConv, frustumDepthAdjusted, screenBottom - fillConv);
  387. verts[0].color = verts[1].color = verts[2].color = verts[3].color = ColorI(255, 255, 255, 255);
  388. verts[0].texCoord.set(texLeft, texTop);
  389. verts[1].texCoord.set(texRight, texTop);
  390. verts[2].texCoord.set(texLeft, texBottom);
  391. verts[3].texCoord.set(texRight, texBottom);
  392. mStereoOverlayVB.unlock();
  393. }
  394. if (!mStereoGuiSB.getPointer())
  395. {
  396. // DrawBitmapStretchSR
  397. GFXStateBlockDesc bitmapStretchSR;
  398. bitmapStretchSR.setCullMode(GFXCullNone);
  399. bitmapStretchSR.setZReadWrite(false, false);
  400. bitmapStretchSR.setBlend(true, GFXBlendSrcAlpha, GFXBlendInvSrcAlpha);
  401. bitmapStretchSR.samplersDefined = true;
  402. bitmapStretchSR.samplers[0] = GFXSamplerStateDesc::getClampLinear();
  403. bitmapStretchSR.samplers[0].minFilter = GFXTextureFilterPoint;
  404. bitmapStretchSR.samplers[0].mipFilter = GFXTextureFilterPoint;
  405. bitmapStretchSR.samplers[0].magFilter = GFXTextureFilterPoint;
  406. mStereoGuiSB = GFX->createStateBlock(bitmapStretchSR);
  407. }
  408. GFX->setPrimitiveBuffer(NULL);
  409. GFX->setVertexBuffer(mStereoOverlayVB);
  410. GFX->setStateBlock(mStereoGuiSB);
  411. GFX->setTexture(0, texObject);
  412. GFX->setupGenericShaders(GFXDevice::GSModColorTexture);
  413. GFX->drawPrimitive(GFXTriangleStrip, 0, 2);
  414. }
  415. saver.restore();
  416. }
  417. //-----------------------------------------------------------------------------
  418. void GuiTSCtrl::onRender(Point2I offset, const RectI &updateRect)
  419. {
  420. // Save the current transforms so we can restore
  421. // it for child control rendering below.
  422. GFXTransformSaver saver;
  423. bool renderingToTarget = false;
  424. mLastCameraQuery.displayDevice = NULL;
  425. if (!processCameraQuery(&mLastCameraQuery))
  426. {
  427. // We have no camera, but render the GUI children
  428. // anyway. This makes editing GuiTSCtrl derived
  429. // controls easier in the GuiEditor.
  430. renderChildControls(offset, updateRect);
  431. return;
  432. }
  433. // jamesu - currently a little bit of a hack. Ideally we need to ditch the viewports in the query data and just rely on the display device
  434. if (mLastCameraQuery.displayDevice)
  435. {
  436. if (mRenderStyle == RenderStyleStereoSideBySide)
  437. {
  438. mLastCameraQuery.displayDevice->setDrawMode(GFXDevice::RS_StereoSideBySide);
  439. }
  440. else if (mRenderStyle == RenderStyleStereoSeparate)
  441. {
  442. mLastCameraQuery.displayDevice->setDrawMode(GFXDevice::RS_StereoSeparate);
  443. }
  444. else
  445. {
  446. mLastCameraQuery.displayDevice->setDrawMode(GFXDevice::RS_Standard);
  447. }
  448. // The connection's display device may want to set the projection offset
  449. if (mLastCameraQuery.displayDevice->providesProjectionOffset())
  450. {
  451. mLastCameraQuery.projectionOffset = mLastCameraQuery.displayDevice->getProjectionOffset();
  452. }
  453. // The connection's display device may want to set the eye offset
  454. if (mLastCameraQuery.displayDevice->providesEyeOffsets())
  455. {
  456. mLastCameraQuery.displayDevice->getEyeOffsets(mLastCameraQuery.eyeOffset);
  457. }
  458. // Grab field of view for both eyes
  459. if (mLastCameraQuery.displayDevice->providesFovPorts())
  460. {
  461. mLastCameraQuery.displayDevice->getFovPorts(mLastCameraQuery.fovPort);
  462. mLastCameraQuery.hasFovPort = true;
  463. }
  464. mLastCameraQuery.displayDevice->getStereoViewports(mLastCameraQuery.stereoViewports);
  465. mLastCameraQuery.displayDevice->getStereoTargets(mLastCameraQuery.stereoTargets);
  466. mLastCameraQuery.hasStereoTargets = mLastCameraQuery.stereoTargets[0];
  467. }
  468. GFXTargetRef origTarget = GFX->getActiveRenderTarget();
  469. U32 origStyle = GFX->getCurrentRenderStyle();
  470. // Set up the appropriate render style
  471. U32 prevRenderStyle = GFX->getCurrentRenderStyle();
  472. Point2F prevProjectionOffset = GFX->getCurrentProjectionOffset();
  473. Point2I renderSize = getExtent();
  474. Frustum frustum;
  475. mLastCameraQuery.currentEye = -1;
  476. if (mRenderStyle == RenderStyleStereoSideBySide)
  477. {
  478. GFX->setCurrentRenderStyle(GFXDevice::RS_StereoSideBySide);
  479. GFX->setCurrentProjectionOffset(mLastCameraQuery.projectionOffset);
  480. GFX->setStereoEyeOffsets(mLastCameraQuery.eyeOffset);
  481. if (!mLastCameraQuery.hasStereoTargets)
  482. {
  483. // Need to calculate our current viewport here
  484. mLastCameraQuery.stereoViewports[0] = updateRect;
  485. mLastCameraQuery.stereoViewports[0].extent.x /= 2;
  486. mLastCameraQuery.stereoViewports[1] = mLastCameraQuery.stereoViewports[0];
  487. mLastCameraQuery.stereoViewports[1].point.x += mLastCameraQuery.stereoViewports[1].extent.x;
  488. }
  489. if (!mLastCameraQuery.hasFovPort)
  490. {
  491. // Need to make our own fovPort
  492. mLastCameraQuery.fovPort[0] = CalculateFovPortForCanvas(mLastCameraQuery.stereoViewports[0], mLastCameraQuery);
  493. mLastCameraQuery.fovPort[1] = CalculateFovPortForCanvas(mLastCameraQuery.stereoViewports[1], mLastCameraQuery);
  494. }
  495. GFX->setStereoFovPort(mLastCameraQuery.fovPort); // NOTE: this specifies fov for BOTH eyes
  496. GFX->setSteroViewports(mLastCameraQuery.stereoViewports);
  497. GFX->setStereoTargets(mLastCameraQuery.stereoTargets);
  498. MatrixF myTransforms[2];
  499. Frustum frustum;
  500. if (smUseLatestDisplayTransform)
  501. {
  502. // Use the view matrix determined from the display device
  503. myTransforms[0] = mLastCameraQuery.eyeTransforms[0];
  504. myTransforms[1] = mLastCameraQuery.eyeTransforms[1];
  505. }
  506. else
  507. {
  508. // Use the view matrix determined from the control object
  509. myTransforms[0] = mLastCameraQuery.cameraMatrix;
  510. myTransforms[1] = mLastCameraQuery.cameraMatrix;
  511. QuatF qrot = mLastCameraQuery.cameraMatrix;
  512. Point3F pos = mLastCameraQuery.cameraMatrix.getPosition();
  513. Point3F rotEyePos;
  514. myTransforms[0].setPosition(pos + qrot.mulP(mLastCameraQuery.eyeOffset[0], &rotEyePos));
  515. myTransforms[1].setPosition(pos + qrot.mulP(mLastCameraQuery.eyeOffset[1], &rotEyePos));
  516. }
  517. GFX->setStereoEyeTransforms(myTransforms);
  518. // Allow render size to originate from the render target
  519. if (mLastCameraQuery.stereoTargets[0])
  520. {
  521. renderSize = mLastCameraQuery.stereoViewports[0].extent;
  522. renderingToTarget = true;
  523. }
  524. // NOTE: these calculations are essentially overridden later by the fov port settings when rendering each eye.
  525. MathUtils::makeFovPortFrustum(&frustum, mLastCameraQuery.ortho, mLastCameraQuery.nearPlane, mLastCameraQuery.farPlane, mLastCameraQuery.fovPort[0]);
  526. GFX->activateStereoTarget(-1);
  527. _internalRender(RectI(updateRect.point, updateRect.extent), frustum);
  528. // Notify device we've rendered the right, thus the last stereo frame.
  529. GFX->getDeviceEventSignal().trigger(GFXDevice::deRightStereoFrameRendered);
  530. // Render preview
  531. if (mLastCameraQuery.displayDevice)
  532. {
  533. GFXTexHandle previewTexture = mLastCameraQuery.displayDevice->getPreviewTexture();
  534. if (!previewTexture.isNull())
  535. {
  536. GFX->setActiveRenderTarget(origTarget);
  537. GFX->setCurrentRenderStyle(origStyle);
  538. GFX->setClipRect(updateRect);
  539. renderDisplayPreview(updateRect, previewTexture);
  540. }
  541. }
  542. }
  543. else if (mRenderStyle == RenderStyleStereoSeparate && mLastCameraQuery.displayDevice)
  544. {
  545. // In this case we render the scene twice to different render targets, then
  546. // render the final composite view
  547. GFX->setCurrentRenderStyle(GFXDevice::RS_StereoSeparate);
  548. GFX->setStereoEyeOffsets(mLastCameraQuery.eyeOffset);
  549. GFX->setStereoFovPort(mLastCameraQuery.fovPort); // NOTE: this specifies fov for BOTH eyes
  550. GFX->setSteroViewports(mLastCameraQuery.stereoViewports);
  551. GFX->setStereoTargets(mLastCameraQuery.stereoTargets);
  552. MatrixF myTransforms[2];
  553. if (smUseLatestDisplayTransform)
  554. {
  555. // Use the view matrix determined from the display device
  556. myTransforms[0] = mLastCameraQuery.eyeTransforms[0];
  557. myTransforms[1] = mLastCameraQuery.eyeTransforms[1];
  558. }
  559. else
  560. {
  561. // Use the view matrix determined from the control object
  562. myTransforms[0] = mLastCameraQuery.cameraMatrix;
  563. myTransforms[1] = mLastCameraQuery.cameraMatrix;
  564. QuatF qrot = mLastCameraQuery.cameraMatrix;
  565. Point3F pos = mLastCameraQuery.cameraMatrix.getPosition();
  566. Point3F rotEyePos;
  567. myTransforms[0].setPosition(pos + qrot.mulP(mLastCameraQuery.eyeOffset[0], &rotEyePos));
  568. myTransforms[1].setPosition(pos + qrot.mulP(mLastCameraQuery.eyeOffset[1], &rotEyePos));
  569. }
  570. MatrixF origMatrix = mLastCameraQuery.cameraMatrix;
  571. // Left
  572. MathUtils::makeFovPortFrustum(&frustum, mLastCameraQuery.ortho, mLastCameraQuery.nearPlane, mLastCameraQuery.farPlane, mLastCameraQuery.fovPort[0]);
  573. mLastCameraQuery.cameraMatrix = myTransforms[0];
  574. frustum.update();
  575. GFX->activateStereoTarget(0);
  576. mLastCameraQuery.currentEye = 0;
  577. _internalRender(RectI(Point2I(0, 0), mLastCameraQuery.stereoTargets[0]->getSize()), frustum);
  578. GFX->getDeviceEventSignal().trigger(GFXDevice::deLeftStereoFrameRendered);
  579. // Right
  580. GFX->activateStereoTarget(1);
  581. mLastCameraQuery.currentEye = 1;
  582. MathUtils::makeFovPortFrustum(&frustum, mLastCameraQuery.ortho, mLastCameraQuery.nearPlane, mLastCameraQuery.farPlane, mLastCameraQuery.fovPort[1]);
  583. mLastCameraQuery.cameraMatrix = myTransforms[1];
  584. frustum.update();
  585. _internalRender(RectI(Point2I(0, 0), mLastCameraQuery.stereoTargets[1]->getSize()), frustum);
  586. GFX->getDeviceEventSignal().trigger(GFXDevice::deRightStereoFrameRendered);
  587. mLastCameraQuery.cameraMatrix = origMatrix;
  588. // Render preview
  589. if (mLastCameraQuery.displayDevice)
  590. {
  591. GFXTexHandle previewTexture = mLastCameraQuery.displayDevice->getPreviewTexture();
  592. if (!previewTexture.isNull())
  593. {
  594. GFX->setActiveRenderTarget(origTarget);
  595. GFX->setCurrentRenderStyle(origStyle);
  596. GFX->setClipRect(updateRect);
  597. renderDisplayPreview(updateRect, previewTexture);
  598. }
  599. }
  600. }
  601. else
  602. {
  603. #ifdef TORQUE_OS_MAC
  604. Point2I screensize = getRoot()->getWindowSize();
  605. tempRect.point.y = screensize.y - (tempRect.point.y + tempRect.extent.y);
  606. #endif
  607. // set up the camera and viewport stuff:
  608. F32 wwidth;
  609. F32 wheight;
  610. F32 renderWidth = F32(renderSize.x);
  611. F32 renderHeight = F32(renderSize.y);
  612. F32 aspectRatio = renderWidth / renderHeight;
  613. // Use the FOV to calculate the viewport height scale
  614. // then generate the width scale from the aspect ratio.
  615. if (!mLastCameraQuery.ortho)
  616. {
  617. wheight = mLastCameraQuery.nearPlane * mTan(mLastCameraQuery.fov / 2.0f);
  618. wwidth = aspectRatio * wheight;
  619. }
  620. else
  621. {
  622. wheight = mLastCameraQuery.fov;
  623. wwidth = aspectRatio * wheight;
  624. }
  625. F32 hscale = wwidth * 2.0f / renderWidth;
  626. F32 vscale = wheight * 2.0f / renderHeight;
  627. F32 left = (updateRect.point.x - offset.x) * hscale - wwidth;
  628. F32 right = (updateRect.point.x + updateRect.extent.x - offset.x) * hscale - wwidth;
  629. F32 top = wheight - vscale * (updateRect.point.y - offset.y);
  630. F32 bottom = wheight - vscale * (updateRect.point.y + updateRect.extent.y - offset.y);
  631. frustum.set(mLastCameraQuery.ortho, left, right, top, bottom, mLastCameraQuery.nearPlane, mLastCameraQuery.farPlane);
  632. // Manipulate the frustum for tiled screenshots
  633. const bool screenShotMode = gScreenShot && gScreenShot->isPending();
  634. if (screenShotMode)
  635. {
  636. gScreenShot->tileFrustum(frustum);
  637. GFX->setViewMatrix(MatrixF::Identity);
  638. }
  639. RectI tempRect = updateRect;
  640. #ifdef TORQUE_OS_MAC
  641. Point2I screensize = getRoot()->getWindowSize();
  642. tempRect.point.y = screensize.y - (tempRect.point.y + tempRect.extent.y);
  643. #endif
  644. _internalRender(tempRect, frustum);
  645. }
  646. // TODO: Some render to sort of overlay system?
  647. // Allow subclasses to render 2D elements.
  648. GFX->setActiveRenderTarget(origTarget);
  649. GFX->setCurrentRenderStyle(origStyle);
  650. GFX->setClipRect(updateRect);
  651. renderGui(offset, updateRect);
  652. if (shouldRenderChildControls())
  653. {
  654. renderChildControls(offset, updateRect);
  655. }
  656. smFrameCount++;
  657. }
  658. //-----------------------------------------------------------------------------
  659. void GuiTSCtrl::drawLine( Point3F p0, Point3F p1, const ColorI &color, F32 width )
  660. {
  661. if ( !mSaveFrustum.clipSegment( p0, p1 ) )
  662. return;
  663. MathUtils::mProjectWorldToScreen( p0, &p0, mSaveViewport, mSaveModelview, mSaveProjection );
  664. MathUtils::mProjectWorldToScreen( p1, &p1, mSaveViewport, mSaveModelview, mSaveProjection );
  665. p0.x = mClampF( p0.x, 0.0f, mSaveViewport.extent.x );
  666. p0.y = mClampF( p0.y, 0.0f, mSaveViewport.extent.y );
  667. p1.x = mClampF( p1.x, 0.0f, mSaveViewport.extent.x );
  668. p1.y = mClampF( p1.y, 0.0f, mSaveViewport.extent.y );
  669. p0.z = p1.z = 0.0f;
  670. _drawLine( p0, p1, color, width );
  671. }
  672. //-----------------------------------------------------------------------------
  673. void GuiTSCtrl::drawLineList( const Vector<Point3F> &points, const ColorI color, F32 width )
  674. {
  675. for ( S32 i = 0; i < points.size() - 1; i++ )
  676. drawLine( points[i], points[i+1], color, width );
  677. }
  678. //-----------------------------------------------------------------------------
  679. void GuiTSCtrl::setStereoGui(GuiOffscreenCanvas *canvas)
  680. {
  681. mStereoGuiTarget = canvas ? canvas->getTarget() : NULL;
  682. mStereoCanvas = canvas;
  683. }
  684. //-----------------------------------------------------------------------------
  685. void GuiTSCtrl::renderDisplayPreview(const RectI &updateRect, GFXTexHandle &previewTexture)
  686. {
  687. GFX->setWorldMatrix(MatrixF(1));
  688. GFX->setViewMatrix(MatrixF::Identity);
  689. GFX->setClipRect(updateRect);
  690. GFX->getDrawUtil()->drawRectFill(RectI(Point2I(0, 0), Point2I(1024, 768)), ColorI::BLACK);
  691. GFX->getDrawUtil()->drawRect(RectI(Point2I(0, 0), Point2I(1024, 768)), ColorI::RED);
  692. if (!mStereoPreviewVB.getPointer())
  693. {
  694. mStereoPreviewVB.set(GFX, 4, GFXBufferTypeStatic);
  695. GFXVertexPCT *verts = mStereoPreviewVB.lock(0, 4);
  696. F32 texLeft = 0.0f;
  697. F32 texRight = 1.0f;
  698. F32 texTop = 0.0f;
  699. F32 texBottom = 1.0f;
  700. F32 rectWidth = updateRect.extent.x;
  701. F32 rectHeight = updateRect.extent.y;
  702. F32 screenLeft = 0;
  703. F32 screenRight = rectWidth;
  704. F32 screenTop = 0;
  705. F32 screenBottom = rectHeight;
  706. const F32 fillConv = 0.0f;
  707. const F32 frustumDepthAdjusted = 0.0f;
  708. verts[0].point.set(screenLeft - fillConv, screenTop - fillConv, 0.f);
  709. verts[1].point.set(screenRight - fillConv, screenTop - fillConv, 0.f);
  710. verts[2].point.set(screenLeft - fillConv, screenBottom - fillConv, 0.f);
  711. verts[3].point.set(screenRight - fillConv, screenBottom - fillConv, 0.f);
  712. verts[0].color = verts[1].color = verts[2].color = verts[3].color = ColorI(255, 255, 255, 255);
  713. verts[0].texCoord.set(texLeft, texTop);
  714. verts[1].texCoord.set(texRight, texTop);
  715. verts[2].texCoord.set(texLeft, texBottom);
  716. verts[3].texCoord.set(texRight, texBottom);
  717. mStereoPreviewVB.unlock();
  718. }
  719. if (!mStereoPreviewSB.getPointer())
  720. {
  721. // DrawBitmapStretchSR
  722. GFXStateBlockDesc bitmapStretchSR;
  723. bitmapStretchSR.setCullMode(GFXCullNone);
  724. bitmapStretchSR.setZReadWrite(false, false);
  725. bitmapStretchSR.setBlend(false, GFXBlendSrcAlpha, GFXBlendInvSrcAlpha);
  726. bitmapStretchSR.samplersDefined = true;
  727. bitmapStretchSR.samplers[0] = GFXSamplerStateDesc::getClampLinear();
  728. bitmapStretchSR.samplers[0].minFilter = GFXTextureFilterPoint;
  729. bitmapStretchSR.samplers[0].mipFilter = GFXTextureFilterPoint;
  730. bitmapStretchSR.samplers[0].magFilter = GFXTextureFilterPoint;
  731. mStereoPreviewSB = GFX->createStateBlock(bitmapStretchSR);
  732. }
  733. GFX->setVertexBuffer(mStereoPreviewVB);
  734. GFX->setStateBlock(mStereoPreviewSB);
  735. GFX->setTexture(0, previewTexture);
  736. GFX->setupGenericShaders(GFXDevice::GSModColorTexture);
  737. GFX->drawPrimitive(GFXTriangleStrip, 0, 2);
  738. }
  739. //=============================================================================
  740. // Console Methods.
  741. //=============================================================================
  742. // MARK: ---- Console Methods ----
  743. //-----------------------------------------------------------------------------
  744. DefineEngineMethod( GuiTSCtrl, unproject, Point3F, ( Point3F screenPosition ),,
  745. "Transform 3D screen-space coordinates (x, y, depth) to world space.\n"
  746. "This method can be, for example, used to find the world-space position relating to the current mouse cursor position.\n"
  747. "@param screenPosition The x/y position on the screen plus the depth from the screen-plane outwards.\n"
  748. "@return The world-space position corresponding to the given screen-space coordinates." )
  749. {
  750. Point3F worldPos;
  751. object->unproject( screenPosition, &worldPos );
  752. return worldPos;
  753. }
  754. //-----------------------------------------------------------------------------
  755. DefineEngineMethod( GuiTSCtrl, project, Point3F, ( Point3F worldPosition ),,
  756. "Transform world-space coordinates to screen-space (x, y, depth) coordinates.\n"
  757. "@param worldPosition The world-space position to transform to screen-space.\n"
  758. "@return The " )
  759. {
  760. Point3F screenPos;
  761. object->project( worldPosition, &screenPos );
  762. return screenPos;
  763. }
  764. //-----------------------------------------------------------------------------
  765. DefineEngineMethod( GuiTSCtrl, getWorldToScreenScale, Point2F, (),,
  766. "Get the ratio between world-space units and pixels.\n"
  767. "@return The amount of world-space units covered by the extent of a single pixel." )
  768. {
  769. return object->getWorldToScreenScale();
  770. }
  771. //-----------------------------------------------------------------------------
  772. DefineEngineMethod( GuiTSCtrl, calculateViewDistance, F32, ( F32 radius ),,
  773. "Given the camera's current FOV, get the distance from the camera's viewpoint at which the given radius will fit in the render area.\n"
  774. "@param radius Radius in world-space units which should fit in the view.\n"
  775. "@return The distance from the viewpoint at which the given radius would be fully visible." )
  776. {
  777. return object->calculateViewDistance( radius );
  778. }
  779. DefineEngineMethod( GuiTSCtrl, setStereoGui, void, ( GuiOffscreenCanvas* canvas ),,
  780. "Sets the current stereo texture to an offscreen canvas\n"
  781. "@param canvas The desired canvas." )
  782. {
  783. object->setStereoGui(canvas);
  784. }