OSGWidget.cpp 8.5 KB

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