OSGWidget.cpp 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. // Include own headers
  2. #include "OSGWidget.hpp"
  3. // Include modules
  4. #include "PickHandler.hpp"
  5. #include "TrackPointRenderer.hpp"
  6. // Include dependencies
  7. #include <osgViewer/Viewer>
  8. #include <osg/ShapeDrawable>
  9. #include <osg/Geode>
  10. #include <osgDB/ReadFile>
  11. #include <osg/Group>
  12. #include <osg/Switch>
  13. #include <osg/MatrixTransform>
  14. #include <osg/Matrix>
  15. #include <osgGA/TrackballManipulator>
  16. #include <osgUtil/LineSegmentIntersector>
  17. #include <osgUtil/IntersectionVisitor>
  18. #include <osgUtil/MeshOptimizers>
  19. #include <osg/PolygonMode>
  20. #include <osgDB/WriteFile>
  21. #include <osg/Material>
  22. #include <osg/StateSet>
  23. #include <cassert>
  24. #include <stdexcept>
  25. #include <vector>
  26. #include <QDebug>
  27. #include <QKeyEvent>
  28. #include <QPainter>
  29. #include <QWheelEvent>
  30. namespace osgWidget {
  31. void Viewer::setupThreading() {
  32. if (_threadingModel == SingleThreaded) {
  33. if (_threadsRunning) {
  34. stopThreading();
  35. }
  36. } else {
  37. if (!_threadsRunning) {
  38. startThreading();
  39. }
  40. }
  41. }
  42. }
  43. void OSGWidget::fixMaterialState(osg::ref_ptr<osg::Node> node) {
  44. osg::StateSet* stateSet = node->getOrCreateStateSet();
  45. osg::Material* material = new osg::Material;
  46. material->setColorMode(osg::Material::AMBIENT_AND_DIFFUSE);
  47. stateSet->setAttributeAndModes(material, osg::StateAttribute::ON);
  48. stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
  49. }
  50. OSGWidget::OSGWidget(QWidget* parent): QOpenGLWidget(parent),
  51. graphicsWindow_(new osgViewer::GraphicsWindowEmbedded(this->x(), this->y(), this->width(), this->height())),
  52. _viewer(new osgWidget::Viewer),
  53. selectionActive_(false),
  54. selectionFinished_(true)
  55. {
  56. this->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
  57. // Root node of the scene
  58. _root = new osg::Group;
  59. // Create the camera
  60. float aspectRatio = static_cast<float>(this->width()) / static_cast<float>(this->height());
  61. auto pixelRatio = this->devicePixelRatio();
  62. osg::Camera* camera = new osg::Camera;
  63. camera->setViewport(0, 0, this->width() * pixelRatio, this->height() * pixelRatio);
  64. camera->setClearColor(osg::Vec4(0.2f, 0.1875f, 0.375f, 1.0f));
  65. camera->setProjectionMatrixAsPerspective(30.0f, aspectRatio, 1.0f, 1000.0f);
  66. camera->setGraphicsContext(graphicsWindow_);
  67. // Create the viewer
  68. _view = new osgViewer::View;
  69. _view->setCamera(camera);
  70. _view->setSceneData(_root);
  71. // Create coordinate axes
  72. _coordinateAxes = new osg::Geode;
  73. osg::ref_ptr<osg::ShapeDrawable> zAxis = new osg::ShapeDrawable();
  74. zAxis->setShape(new osg::Cylinder(osg::Vec3(0.0f, 0.0f, 0.0f), 0.1f, 100.0f));
  75. zAxis->setColor(osg::Vec4(1.0f, 1.0f, 1.0f, 1.0f));
  76. _coordinateAxes->addDrawable(zAxis.get());
  77. OSGWidget::fixMaterialState(_coordinateAxes);
  78. _root->addChild(_coordinateAxes);
  79. _mesh = new osg::Geode;
  80. // Attach a manipulator (it's usually done for us when we use viewer.run())
  81. osg::ref_ptr<osgGA::TrackballManipulator> tm = new osgGA::TrackballManipulator;
  82. tm->setAllowThrow(false);
  83. _view->setCameraManipulator(tm);
  84. _viewer->addView(_view);
  85. _viewer->setThreadingModel(osgViewer::CompositeViewer::SingleThreaded);
  86. _viewer->realize();
  87. _picker = new PickHandler(this, _root);
  88. _root->addChild(_picker->getPickerRoot());
  89. _view->addEventHandler(_picker);
  90. // This ensures that the widget will receive keyboard events. This focus
  91. // policy is not set by default. The default, Qt::NoFocus, will result in
  92. // keyboard events that are ignored.
  93. this->setFocusPolicy(Qt::StrongFocus);
  94. this->setMinimumSize(100, 100);
  95. // Ensures that the widget receives mouse move events even though no
  96. // mouse button has been pressed. We require this in order to let the
  97. // graphics window switch viewports properly.
  98. this->setMouseTracking(true);
  99. _pointRoot = new osg::Group;
  100. _root->addChild(_pointRoot.get());
  101. _pointRenderer = new TrackPointRenderer(this, _pointRoot);
  102. }
  103. OSGWidget::~OSGWidget() {
  104. }
  105. void OSGWidget::renderBaseMesh(const osg::ref_ptr<osg::Vec3Array> vertices, const osg::ref_ptr<osg::Vec3Array> normals) {
  106. _root->removeChild(_mesh);
  107. osg::ref_ptr<osg::Geometry> meshGeometry = new osg::Geometry;
  108. meshGeometry->setVertexArray(vertices.get());
  109. meshGeometry->setNormalArray(normals.get(), osg::Array::BIND_PER_VERTEX);
  110. meshGeometry->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::TRIANGLES, 0, vertices->getNumElements()));
  111. osgUtil::optimizeMesh(meshGeometry.get());
  112. _mesh->addDrawable(meshGeometry.get());
  113. OSGWidget::fixMaterialState(_mesh);
  114. _root->addChild(_mesh);
  115. _picker->updateRenderer();
  116. }
  117. osg::ref_ptr<osg::Geode> OSGWidget::getMesh() {
  118. return _mesh;
  119. }
  120. PickHandler* OSGWidget::getPicker() {
  121. return _picker;
  122. }
  123. TrackPointRenderer* OSGWidget::getPointRenderer() {
  124. return _pointRenderer;
  125. }
  126. void OSGWidget::paintEvent(QPaintEvent*) {
  127. this->makeCurrent();
  128. QPainter painter(this);
  129. painter.setRenderHint(QPainter::Antialiasing);
  130. this->paintGL();
  131. painter.end();
  132. this->doneCurrent();
  133. }
  134. void OSGWidget::paintGL() {
  135. _viewer->frame();
  136. }
  137. void OSGWidget::resizeGL(int width, int height) {
  138. this->getEventQueue()->windowResize(this->x(), this->y(), width, height);
  139. graphicsWindow_->resized(this->x(), this->y(), width, height);
  140. this->onResize(width, height);
  141. }
  142. void OSGWidget::keyPressEvent(QKeyEvent* event) {
  143. QString keyString = event->text();
  144. const char* keyData = keyString.toLocal8Bit().data();
  145. if (event->key() == Qt::Key_H) {
  146. this->onHome();
  147. return;
  148. }
  149. this->getEventQueue()->keyPress(osgGA::GUIEventAdapter::KeySymbol(*keyData));
  150. }
  151. void OSGWidget::keyReleaseEvent(QKeyEvent* event) {
  152. QString keyString = event->text();
  153. const char* keyData = keyString.toLocal8Bit().data();
  154. this->getEventQueue()->keyRelease(osgGA::GUIEventAdapter::KeySymbol(*keyData));
  155. }
  156. void OSGWidget::mouseMoveEvent(QMouseEvent* event) {
  157. auto pixelRatio = this->devicePixelRatio();
  158. this->getEventQueue()->mouseMotion(static_cast<float>(event->position().x() * pixelRatio), static_cast<float>(event->position().y() * pixelRatio));
  159. }
  160. void OSGWidget::mousePressEvent(QMouseEvent* event) {
  161. unsigned int button = 0;
  162. switch(event->button()) {
  163. case Qt::LeftButton:
  164. button = 1;
  165. break;
  166. case Qt::MiddleButton:
  167. button = 2;
  168. break;
  169. case Qt::RightButton:
  170. button = 3;
  171. break;
  172. default:
  173. break;
  174. }
  175. auto pixelRatio = this->devicePixelRatio();
  176. this->getEventQueue()->mouseButtonPress(static_cast<float>(event->position().x() * pixelRatio), static_cast<float>(event->position().y() * pixelRatio), button);
  177. }
  178. void OSGWidget::mouseReleaseEvent(QMouseEvent* event) {
  179. unsigned int button = 0;
  180. switch(event->button()) {
  181. case Qt::LeftButton:
  182. button = 1;
  183. break;
  184. case Qt::MiddleButton:
  185. button = 2;
  186. break;
  187. case Qt::RightButton:
  188. button = 3;
  189. break;
  190. default:
  191. break;
  192. }
  193. auto pixelRatio = this->devicePixelRatio();
  194. this->getEventQueue()->mouseButtonRelease(static_cast<float>(pixelRatio * event->position().x()), static_cast<float>(pixelRatio * event->position().y()), button);
  195. }
  196. void OSGWidget::wheelEvent(QWheelEvent* event) {
  197. event->accept();
  198. int delta = event->angleDelta().y();
  199. osgGA::GUIEventAdapter::ScrollingMotion motion = delta > 0 ? osgGA::GUIEventAdapter::SCROLL_UP : osgGA::GUIEventAdapter::SCROLL_DOWN;
  200. this->getEventQueue()->mouseScroll(motion);
  201. }
  202. bool OSGWidget::event(QEvent* event) {
  203. bool handled = QOpenGLWidget::event(event);
  204. // This ensures that the OSG widget is always going to be repainted after the
  205. // user performed some interaction. Doing this in the event handler ensures
  206. // that we don't forget about some event and prevents duplicate code.
  207. switch(event->type()) {
  208. case QEvent::KeyPress:
  209. case QEvent::KeyRelease:
  210. case QEvent::MouseButtonDblClick:
  211. case QEvent::MouseButtonPress:
  212. case QEvent::MouseButtonRelease:
  213. case QEvent::MouseMove:
  214. case QEvent::Wheel:
  215. this->update();
  216. break;
  217. case QEvent::Resize:
  218. this->onResize(this->width(), this->height());
  219. break;
  220. default:
  221. break;
  222. }
  223. return handled;
  224. }
  225. void OSGWidget::onHome() {
  226. osgViewer::ViewerBase::Views views;
  227. _viewer->getViews( views );
  228. for(std::size_t i = 0; i < views.size(); i++) {
  229. osgViewer::View* view = views.at(i);
  230. view->home();
  231. }
  232. }
  233. void OSGWidget::onResize(int width, int height) {
  234. std::vector<osg::Camera*> cameras;
  235. _viewer->getCameras(cameras);
  236. assert(cameras.size() == 1);
  237. auto pixelRatio = this->devicePixelRatio();
  238. cameras[0]->setViewport(0, 0, width * pixelRatio, height * pixelRatio);
  239. }
  240. osgGA::EventQueue* OSGWidget::getEventQueue() const {
  241. osgGA::EventQueue* eventQueue = graphicsWindow_->getEventQueue();
  242. if (eventQueue) {
  243. return eventQueue;
  244. } else {
  245. throw std::runtime_error("Unable to obtain valid event queue");
  246. }
  247. }