diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 7aefeab1..826a32ba 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -4,7 +4,7 @@ set(CMAKE_AUTOUIC ON) set(CMAKE_AUTOMOC ON) set(CMAKE_AUTORCC ON) -SET(CMAKE_CXX_STANDARD 17) +SET(CMAKE_CXX_STANDARD 11) SET(CMAKE_CXX_STANDARD_REQUIRED ON) SET(CMAKE_INCLUDE_CURRENT_DIR ON) @@ -85,8 +85,9 @@ INCLUDE_DIRECTORIES( ${CMAKE_CURRENT_SOURCE_DIR} ${Thirdparty}/spdlog/include ${Thirdparty}/breakpad/include - ${Thirdparty}/3rdParty_x64/include - ${Thirdparty}/OpenSceneGraph-3.6.5/include + ${Thirdparty}/3rdparty_vc15/include + ${Thirdparty}/OSG-3.5.1/include + ${Thirdparty}/OSGEARTH-2.8/include ${Thirdparty}/TritonSDK/PublicHeaders ${Thirdparty}/matlab/include # ${Thirdparty}/Python39/include @@ -94,8 +95,9 @@ INCLUDE_DIRECTORIES( LINK_DIRECTORIES( ${Thirdparty}/spdlog/lib - ${Thirdparty}/3rdParty_x64/lib - ${Thirdparty}/OpenSceneGraph-3.6.5/lib + ${Thirdparty}/3rdparty_vc15/lib + ${Thirdparty}/OSG-3.5.1/lib + ${Thirdparty}/OSGEARTH-2.8/lib ${Thirdparty}/matlab/lib/win64/microsoft ${Thirdparty}/TritonSDK/lib/vc143/x64 # ${Thirdparty}/Python39/libs @@ -167,6 +169,7 @@ target_link_libraries( osgWidget osgText osgEarth + osgEarthUtil Triton-MT-DLL libeng libmx diff --git a/src/common/CrashHandler.cpp b/src/common/CrashHandler.cpp index 19ffadac..ec627ecd 100644 --- a/src/common/CrashHandler.cpp +++ b/src/common/CrashHandler.cpp @@ -1,5 +1,6 @@ #include "CrashHandler.h" +#if 0 #include #include #include @@ -79,7 +80,6 @@ std::unique_ptr exceptionHandler; #endif bool InstallCrashHandler() { #if NDEBUG - FindFileForDelete("D:/pcm"); QString appDirPath = QCoreApplication::applicationDirPath() + "/crash"; QDir dir; if (!dir.exists(appDirPath)) { @@ -94,7 +94,7 @@ bool InstallCrashHandler() { #if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__) exceptionHandler.reset(new google_breakpad::ExceptionHandler( - appDirPath.toStdWString(), NULL, OnMinidumpCallback, NULL, + appDirPath.toStdWString(), nullptr, OnMinidumpCallback, nullptr, google_breakpad::ExceptionHandler::HANDLER_ALL)); #else exceptionHandler.reset(new google_breakpad::ExceptionHandler( @@ -106,7 +106,10 @@ bool InstallCrashHandler() { return true; } -void TestCrash() { - volatile int* a = (int*)(nullptr); - *a = 1; +#else + +bool InstallCrashHandler() { + return false; } + +#endif diff --git a/src/common/CrashHandler.h b/src/common/CrashHandler.h index d5380a74..705c34e2 100644 --- a/src/common/CrashHandler.h +++ b/src/common/CrashHandler.h @@ -1,5 +1,4 @@ #pragma once -bool InstallCrashHandler(); -void TestCrash(); \ No newline at end of file +bool InstallCrashHandler(); \ No newline at end of file diff --git a/src/effects/ConeWave.cpp b/src/effects/ConeWave.cpp index 4c7fbd3f..afd41314 100644 --- a/src/effects/ConeWave.cpp +++ b/src/effects/ConeWave.cpp @@ -239,7 +239,9 @@ void ConeWave::CreateTexturedCone(osg::Geode* geode) { // baseColorUniform_ = new osg::Uniform("baseColor", baseColor_); // stateset->setMode(GL_CULL_FACE, osg::StateAttribute::ON); // stateset->addUniform(baseColorUniform_); - // // stateset->setAttributeAndModes(program, osg::StateAttribute::ON); +// // stateset->osg::ref_ptr program = new osg::Program(); +program->addShader(vertexShader); +program->addShader(fragmentShader);(program, osg::StateAttribute::ON); // // stateset->setAttributeAndModes(new osg::Depth(osg::Depth::LESS, 0.0, 1.0, false)); // // levelCountUniform_ = new osg::Uniform("num", float(levelCount_)); @@ -256,7 +258,8 @@ void ConeWave::CreateTexturedCone(osg::Geode* geode) { #include #include #include -#include +#include +#include #include "scene/SceneContent.h" @@ -326,15 +329,13 @@ void WaveBeamConeCallBack::operator()(osg::Node *node, osg::NodeVisitor *nv) { osg::Matrix mConeRate = osg::Matrix::rotate(osg::Vec3d(0, 1, 0), (mTarget*m).getTrans()); mtCone->setMatrix(mConeRate);//mTarget*m - //更改cone的形状---------------------------------------- double length = (mTarget*m).getTrans().length(); double angle = osg::DegreesToRadians(m_angle); double radius = std::tan(angle*0.5) * length; int splitCount = 20; double angleStep = osg::PI * 2.0 / splitCount; - - //侧面 + for (int i = 1; i <= splitCount + 1; i++) { double tempAngle = (i - 1)*angleStep; osg::Vec3 pos(radius * cos(tempAngle), length, radius * sin(tempAngle) + 3); @@ -342,8 +343,7 @@ void WaveBeamConeCallBack::operator()(osg::Node *node, osg::NodeVisitor *nv) { } m_pointVector->at(splitCount + 2) = osg::Vec3(0, length, 0); - - //底面 + for (int i = splitCount + 3; i <= splitCount + 3 + splitCount; i++) { double tempAngle = (i - splitCount - 3) *angleStep; osg::Vec3 pos(radius * cos(tempAngle), length, radius * sin(tempAngle) + 3); @@ -383,10 +383,11 @@ void ConeWave::createWaveBeamCone(osg::MatrixTransform* node, double angle, doub osg::ref_ptr vertex = new osg::Vec3Array; osg::ref_ptr normal = new osg::Vec3Array; osg::ref_ptr drawElemUInt = new osg::DrawElementsUInt(GL_TRIANGLE_FAN); - osg::ref_ptr drawElemUInt2 = new osg::DrawElementsUInt(GL_TRIANGLE_FAN); + // osg::ref_ptr drawElemUInt2 = new osg::DrawElementsUInt(GL_TRIANGLE_FAN); geom->setVertexArray(vertex); geom->setNormalArray(normal); geode->addDrawable(geom); + geode->getOrCreateStateSet()->setRenderingHint(osg::StateSet::TRANSPARENT_BIN); vertex->push_back(osg::Vec3(0, 0, 0)); drawElemUInt->push_back(0); @@ -395,7 +396,7 @@ void ConeWave::createWaveBeamCone(osg::MatrixTransform* node, double angle, doub //侧面 for (int i = 0; i <= splitCount; i++) { double tempAngle = i*angleStep; - osg::Vec3 pos(radius * cos(tempAngle), length, radius * sin(tempAngle) + 3); + osg::Vec3 pos(radius * cos(tempAngle), radius * sin(tempAngle) + 3, length); vertex->push_back(osg::Vec3(pos)); pos.normalize(); @@ -403,46 +404,52 @@ void ConeWave::createWaveBeamCone(osg::MatrixTransform* node, double angle, doub drawElemUInt->push_back(i + 1); } - //底面 - int indexBegin = vertex->size(); - vertex->push_back(osg::Vec3(0, length, 0)); - drawElemUInt2->push_back(indexBegin); - normal->push_back(osg::Vec3(0, 1, 0)); - for (int i = 0; i <= splitCount; i++) { - double tempAngle = i*angleStep; - osg::Vec3 pos(radius * cos(tempAngle), length, radius * sin(tempAngle) + 3); - vertex->push_back(osg::Vec3(pos)); - - normal->push_back(osg::Vec3(0, 1, 0)); - drawElemUInt2->push_back(indexBegin + i + 1); - } + // //底面 + // int indexBegin = vertex->size(); + // vertex->push_back(osg::Vec3(0, length, 0)); + // drawElemUInt2->push_back(indexBegin); + // normal->push_back(osg::Vec3(0, 1, 0)); + // for (int i = 0; i <= splitCount; i++) { + // double tempAngle = i*angleStep; + // osg::Vec3 pos(radius * cos(tempAngle), length, radius * sin(tempAngle) + 3); + // vertex->push_back(osg::Vec3(pos)); + // + // normal->push_back(osg::Vec3(0, 1, 0)); + // drawElemUInt2->push_back(indexBegin + i + 1); + // } geom->setNormalBinding(osg::Geometry::BIND_PER_VERTEX); geom->addPrimitiveSet(drawElemUInt); - geom->addPrimitiveSet(drawElemUInt2); - - //创建材质对象 + // geom->addPrimitiveSet(drawElemUInt2); + osg::ref_ptr mat = new osg::Material; - //设置正面散射颜色 mat->setDiffuse(osg::Material::FRONT, osg::Vec4(1.0, 1.0, 0.0, 0.3));//1.0, 0.0, 0.0, 0.3 - //设置正面镜面颜色 mat->setSpecular(osg::Material::FRONT, osg::Vec4(1.0, 0.0, 0.0, 0.3));//1.0, 0.0, 0.0, 0.3 - + geode->getOrCreateStateSet()->setAttribute(mat.get()); geode->getOrCreateStateSet()->setMode(GL_RESCALE_NORMAL, osg::StateAttribute::ON); - //设置透明效果 + geode->getOrCreateStateSet()->setMode(GL_BLEND, osg::StateAttribute::ON); geode->getOrCreateStateSet()->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON); geode->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF); - - //设置渲染顺序 仿真模型被波束遮盖 ,1000000-指的是若有1000000个Node 则此节点最后一个被渲染 + geode->getOrCreateStateSet()->setRenderBinDetails(12, "RenderBin"); osg::ref_ptr mtCone = new osg::MatrixTransform; - // mtCone->addChild(nodeFX); + mtCone->addChild(geode); - //给callback中赋值 + const char* path = "D:/Project/DYTSrouce/bin/Release/resources/textures/block.png"; + osg::Image* image = osgDB::readImageFile(path); + osg::ref_ptr pTexture2D = new osg::Texture2D; + pTexture2D->setImage(image); + pTexture2D->setWrap(osg::Texture::WRAP_S , osg::Texture::CLAMP_TO_EDGE); + pTexture2D->setWrap(osg::Texture::WRAP_T , osg::Texture::REPEAT); + pTexture2D->setFilter( osg::Texture::MIN_FILTER, osg::Texture::LINEAR ); + pTexture2D->setFilter( osg::Texture::MAG_FILTER, osg::Texture::LINEAR ); + geode->getOrCreateStateSet()->setTextureAttribute(0, pTexture2D); + geode->getOrCreateStateSet()->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::ON); + WaveBeamConeCallBack* coneCallBack = new WaveBeamConeCallBack; coneCallBack->m_angle = angle; coneCallBack->m_length = length; @@ -453,8 +460,7 @@ void ConeWave::createWaveBeamCone(osg::MatrixTransform* node, double angle, doub coneCallBack->m_geode = geode; coneCallBack->m_geom = geom; coneCallBack->m_pointVector = vertex; - - //添加到模型中 + // osg::MatrixTransform* mtR = dynamic_cast(node->getChild(0)); // osg::MatrixTransform* mtS = dynamic_cast(mtR->getChild(0)); // mtR->addChild(mtCone); @@ -514,8 +520,9 @@ void ConeWave::changeWaveBeamConeAppearance( osg::Vec4 color, osg::Vec4 lineColo _waveBeamCone->removeChild(coneCallBack->m_geode); _waveBeamCone->addChild(coneCallBack->m_nodeFX); + coneCallBack->m_nodeFX->setWireframeColor(lineColor); - coneCallBack->m_nodeFX->setWireframeLineWidth(lineWidth); + coneCallBack->m_nodeFX->setWireframeLineWidth(static_cast(lineWidth)); } } } diff --git a/src/effects/ConeWave.h b/src/effects/ConeWave.h index 0d2a65fa..f754f5c5 100644 --- a/src/effects/ConeWave.h +++ b/src/effects/ConeWave.h @@ -70,7 +70,6 @@ private: #include #include "viewer/UpdateRenderStd.h" -//三维实体的圆锥波束 class ConeWave : public osg::Geode , public UpdateRenderStd { diff --git a/src/effects/DashedLine.cpp b/src/effects/DashedLine.cpp index d0228f07..18d1d801 100644 --- a/src/effects/DashedLine.cpp +++ b/src/effects/DashedLine.cpp @@ -102,7 +102,7 @@ void DashedLine::CreateTexturedCone(osg::Geode* geode) { "#version 330\n" "in vec4 osg_Vertex;\n" "in vec2 osg_MultiTexCoord0;\n" - "uniform mat4 osg_ModelViewProjectionMatrix;\n"//ǰOSGĹ۲ + "uniform mat4 osg_ModelViewProjectionMatrix;\n"//��ǰOSG������Ĺ۲���� "uniform float time;\n" "out vec2 texCoord;\n" "void main()\n" @@ -151,7 +151,8 @@ void DashedLine::UpdateRotaion() { float height = direction.length(); cylinder_->setHeight(height); - cylinderDrawable_->build(); + // cylinderDrawable_->b(); + // cylinderDrawable_- osg::Vec3 center = (start_ + end_) * 0.5f; direction.normalize(); diff --git a/src/main.cpp b/src/main.cpp index 66651a6a..8ef35d34 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,3 +1,4 @@ + #include "app/Application.h" #include "common/SpdLogger.h" @@ -5,23 +6,397 @@ #include "common/CrashHandler.h" #include "ui/MainFrame.h" +#include "ui/MainWindow.h" +#include "viewer/OsgWidget.h" + +#include +#include +#include + +#include +#include + +#include + +#include +#include +#include +#include +// #include + +#include "osgqt/GraphicsWindowQt.h" +#include "scene/ui/CompositeWidgetManager.h" +#include "scene/ui/QueryElevationWidget.h" + +#ifndef LC +#define LC "DYT" +#endif + +const unsigned int MASK_2D = 0xF0000000; +std::string path = "D:\\Project\\DYT\\Source\\bin\\Release\\data\\"; + +bool scrollWindow(osgWidget::Event& ev) { + // The first thing we need to do is make sure we have a Frame object... + osgWidget::Frame* frame = dynamic_cast(ev.getWindow()); + + if(!frame) return false; + + // And now we need to make sure our Frame has a valid internal EmbeddedWindow widget. + osgWidget::Window::EmbeddedWindow* ew = + dynamic_cast(frame->getEmbeddedWindow()) + ; + + if(!ew) return false; + + // Lets get the visible area so that we can use it to make sure our scrolling action + // is necessary in the first place. + const osgWidget::Quad& va = ew->getWindow()->getVisibleArea(); + + // The user wants to scroll up; make sure that the visible area's Y origin isn't already + // at 0.0f, 0.0f. + if(ev.getWindowManager()->isMouseScrollingUp() && va[1] != 0.0f) + ew->getWindow()->addVisibleArea(0, -20) + ; + + else if(va[1] <= (ew->getWindow()->getHeight() - ew->getHeight())) + ew->getWindow()->addVisibleArea(0, 20) + ; + + // We need to manually call update to make sure the visible area scissoring is done + // properly. + frame->update(); + + return true; +} + +bool changeTheme(osgWidget::Event& ev) { + std::string theme; + + if(ev.key == osgGA::GUIEventAdapter::KEY_Right) + theme = "osgWidget/theme-1.png" + ; + + else if(ev.key == osgGA::GUIEventAdapter::KEY_Left) + theme = "osgWidget/theme-2.png" + ; + + else return false; + + osgWidget::Frame* frame = dynamic_cast(ev.getWindow()); + + if(!frame) return false; + + // This is just one way to access all our Widgets; we could just as well have used: + // + // for(osgWidget::Frame::Iterator i = frame.begin(); i != frame.end() i++) {} + // + // ...and it have worked, too. + for(unsigned int row = 0; row < 3; row++) { + for(unsigned int col = 0; col < 3; col++) { + frame->getByRowCol(row, col)->setImage(theme); + } + } + + return true; +} + + +osg::Node* createUiExample(osgViewer::View* viewer, osgWidget::WindowManager* wm) { + if(!wm) return nullptr; + + // viewer.setUpViewInWindow( + // 50, + // 50, + // static_cast(wm->getWidth()), + // static_cast(wm->getHeight()) + // ); + + osg::Group* group = new osg::Group(); + osg::Camera* camera = wm->createParentOrthoCamera(); + + group->addChild(camera); + + viewer->addEventHandler(new osgWidget::MouseHandler(wm)); + viewer->addEventHandler(new osgWidget::KeyboardHandler(wm)); + viewer->addEventHandler(new osgWidget::ResizeHandler(wm, camera)); + viewer->addEventHandler(new osgWidget::CameraSwitchHandler(wm, camera)); + viewer->addEventHandler(new osgViewer::StatsHandler()); + viewer->addEventHandler(new osgViewer::WindowSizeHandler()); + viewer->addEventHandler(new osgGA::StateSetManipulator( + viewer->getCamera()->getOrCreateStateSet() + )); + + wm->resizeAllWindows(); + return group; +} + +void creatWidget(osgViewer::View* viewer, osg::Group* root) { + osgWidget::WindowManager* wm = new osgWidget::WindowManager( + viewer, + 1280.0f, + 1024.0f, + MASK_2D, + osgWidget::WindowManager::WM_PICK_DEBUG + //osgWidget::WindowManager::WM_NO_INVERT_Y + ); + + osgWidget::Frame* frame = osgWidget::Frame::createSimpleFrameFromTheme( + "frame", + osgDB::readRefImageFile("osgWidget/theme.png"), + 40.0f, + 40.0f, + osgWidget::Frame::FRAME_ALL + ); + osgWidget::Box* box = new osgWidget::Box("images", osgWidget::Box::VERTICAL); + osgWidget::Widget* img1 = new osgWidget::Widget("im1", 512.0f, 512.0f); + osgWidget::Widget* img2 = new osgWidget::Widget("im2", 512.0f, 512.0f); + osgWidget::Widget* img3 = new osgWidget::Widget("im3", 512.0f, 512.0f); + osgWidget::Widget* img4 = new osgWidget::Widget("im4", 512.0f, 512.0f); + + img1->setImage(path + "osgWidget/scrolled1.jpg", true); + img2->setImage(path + "osgWidget/scrolled2.jpg", true); + img3->setImage(path + "osgWidget/scrolled3.jpg", true); + img4->setImage(path + "osgWidget/scrolled4.jpg", true); + + img1->setMinimumSize(10.0f, 10.0f); + img2->setMinimumSize(10.0f, 10.0f); + img3->setMinimumSize(10.0f, 10.0f); + img4->setMinimumSize(10.0f, 10.0f); + + box->addWidget(img1); + box->addWidget(img2); + box->addWidget(img3); + box->addWidget(img4); + box->setEventMask(osgWidget::EVENT_NONE); + + //frame->getEmbeddedWindow()->setWindow(box); + frame->setWindow(box); + frame->getEmbeddedWindow()->setColor(1.0f, 1.0f, 1.0f, 1.0f); + frame->resize(300.0f, 300.0f); + frame->addCallback(new osgWidget::Callback(&scrollWindow, osgWidget::EVENT_MOUSE_SCROLL)); + frame->addCallback(new osgWidget::Callback(&changeTheme, osgWidget::EVENT_KEY_DOWN)); + + wm->addChild(frame); + + osg::Node* ui = createUiExample(viewer, wm); + root->addChild(ui); +} + +void configureView( osgViewer::View* view ) +{ + // default uniform values: + // GLUtils::setGlobalDefaults(view->getCamera()->getOrCreateStateSet()); + + // add some stock OSG handlers: + view->addEventHandler(new osgViewer::StatsHandler()); + view->addEventHandler(new osgViewer::WindowSizeHandler()); + view->addEventHandler(new osgViewer::ThreadingHandler()); + view->addEventHandler(new osgViewer::LODScaleHandler()); + view->addEventHandler(new osgGA::StateSetManipulator(view->getCamera()->getOrCreateStateSet())); + view->addEventHandler(new osgViewer::RecordCameraPathHandler()); + view->addEventHandler(new osgViewer::ScreenCaptureHandler()); +} + + +osg::Node* LoadEarth(const std::string& earth, osgViewer::CompositeViewer* viewer) { + osg::ref_ptr node = osgDB::readNodeFile(earth); + + osg::ref_ptr mapNode = osgEarth::MapNode::get(node.get()); + if ( !mapNode.valid() ) + { + OE_WARN << LC << "Loaded scene graph does not contain a MapNode - aborting" << std::endl; + return 0L; + } + + // collect the views + osgViewer::Viewer::Views views; + if (viewer) + { + viewer->getViews(views); + } + + // warn about not having an earth manip + for (osgViewer::Viewer::Views::iterator view = views.begin(); view != views.end(); ++view) + { + osgEarth::Util::EarthManipulator* manip = dynamic_cast((*view)->getCameraManipulator()); + if ( manip == 0L ) + { + OE_WARN << LC << "Helper used before installing an EarthManipulator" << std::endl; + } + } + + // a root node to hold everything: + osg::Group* root = new osg::Group(); + + root->addChild( node ); + + // parses common cmdline arguments and apply to the first view: + // if ( !views.empty() ) + // { + // parse( mapNode.get(), args, views.front(), root, userContainer ); + // + // float lodscale; + // if (args.read("--lodscale", lodscale)) + // { + // LODScaleGroup* g = new LODScaleGroup(); + // g->setLODScaleFactor(osg::maximum(lodscale, 0.0001f)); + // osgEarth::insertGroup(g, mapNode->getParent(0)); + // OE_NOTICE << "LOD Scale set to: " << lodscale << std::endl; + // } + // } + + // configures each view with some stock goodies + for (osgViewer::Viewer::Views::iterator view = views.begin(); view != views.end(); ++view) + { + configureView( *view ); + } + +#ifdef OSG_GL3_AVAILABLE + if (viewer) + { + viewer->setRealizeOperation(new GL3RealizeOperation()); + } +#endif + + return root; +} + +class ViewerWidget : public QWidget, public osgViewer::CompositeViewer +{ +public: + ViewerWidget(QWidget* parent = 0, Qt::WindowFlags f = 0, osgViewer::ViewerBase::ThreadingModel threadingModel=osgViewer::CompositeViewer::SingleThreaded) : QWidget(parent, f) + { + setThreadingModel(threadingModel); + + // disable the default setting of viewer.done() by pressing Escape. + setKeyEventSetsDone(0); + + std::string earthPath = "D:/Project/DYT/Tool/TritonSample/TritonSample/triton.earth"; + // osg::Node* node = osgDB::readNodeFile(); + osg::Node* node =LoadEarth(earthPath, this); + if ( !node ) { + return; + } + + + // Group to hold all our annotation elements. + // osg::Group* annoGroup = new osg::Group(); + // osgEarth::MapNode::get(node)->addChild( annoGroup ); + + QWidget* widget1 = addViewWidget( createGraphicsWindow(0,0,100,100), node); + // QWidget* widget2 = addViewWidget( createGraphicsWindow(0,0,100,100), osgDB::readRefNodeFile("glider.osgt") ); + // QWidget* widget3 = addViewWidget( createGraphicsWindow(0,0,100,100), osgDB::readRefNodeFile("axes.osgt") ); + // QWidget* widget4 = addViewWidget( createGraphicsWindow(0,0,100,100), osgDB::readRefNodeFile("fountain.osgt") ); + // QWidget* popupWidget = addViewWidget( createGraphicsWindow(900,100,320,240,"Popup window",true), osgDB::readRefNodeFile("dumptruck.osgt") ); + // popupWidget->show(); + + + + QGridLayout* grid = new QGridLayout; + grid->addWidget( widget1, 0, 0 ); + // grid->addWidget( widget2, 0, 1 ); + // grid->addWidget( widget3, 1, 0 ); + // grid->addWidget( widget4, 1, 1 ); + setLayout( grid ); + + connect( &_timer, SIGNAL(timeout()), this, SLOT(update()) ); + _timer.start( 10 ); + } + + QWidget* addViewWidget( osgQt::GraphicsWindowQt* gw, osg::ref_ptr scene ) + { + osgViewer::View* view = new osgViewer::View; + addView( view ); + view->setCameraManipulator( new osgEarth::Util::EarthManipulator() ); + configureView(view); + + osg::Camera* camera = view->getCamera(); + camera->setGraphicsContext( gw ); + + const osg::GraphicsContext::Traits* traits = gw->getTraits(); + + camera->setClearColor( osg::Vec4(0.2, 0.2, 0.6, 1.0) ); + camera->setViewport( new osg::Viewport(0, 0, traits->width, traits->height) ); + camera->setProjectionMatrixAsPerspective(30.0f, static_cast(traits->width)/static_cast(traits->height), 1.0f, 10000.0f ); + + creatWidget(view, scene->asGroup()); + + osgEarth::MapNode* mapNode = osgEarth::MapNode::findMapNode(scene); + if ( !mapNode ) + return gw->getGLWidget(); + + auto skyDome_ = osgEarth::Util::SkyNode::create(mapNode); + if (!mapNode) { + LOG_WARN("eart map node is nullptr"); + return gw->getGLWidget(); + } + skyDome_->attach(view); + skyDome_->getSunLight()->setAmbient(osg::Vec4(0.5,0.5,0.5,1.0)); + scene->asGroup()->addChild(skyDome_); + + skyDome_->setDateTime(osgEarth::DateTime(2024, 12, 24, 3)); + + view->setSceneData( scene ); + view->addEventHandler( new osgViewer::StatsHandler ); + // view->setCameraManipulator( new osgGA::MultiTouchTrackballManipulator ); + gw->setTouchEventsEnabled( true ); + return gw->getGLWidget(); + } + + osgQt::GraphicsWindowQt* createGraphicsWindow( int x, int y, int w, int h, const std::string& name="", bool windowDecoration=false ) + { + osg::DisplaySettings* ds = osg::DisplaySettings::instance().get(); + osg::ref_ptr traits = new osg::GraphicsContext::Traits; + traits->windowName = name; + traits->windowDecoration = windowDecoration; + traits->x = x; + traits->y = y; + traits->width = w; + traits->height = h; + traits->doubleBuffer = true; + traits->alpha = ds->getMinimumNumAlphaBits(); + traits->stencil = ds->getMinimumNumStencilBits(); + traits->sampleBuffers = ds->getMultiSamples(); + traits->samples = ds->getNumMultiSamples(); + + return new osgQt::GraphicsWindowQt(traits.get()); + } + + virtual void paintEvent( QPaintEvent* /*event*/ ) + { frame(); } + +protected: + + QTimer _timer; +}; int main(int argc, char* argv[]) { SpdLogger logger("logs/log.txt", 5); - - Application::setAttribute(Qt::AA_EnableHighDpiScaling); - - Application app(argc, argv); - app.setAttribute(Qt::AA_DontCreateNativeWidgetSiblings); - InstallCrashHandler(); - - RecourceHelper::ChangeSkin("default"); - - int ret = 0; + // + // Application::setAttribute(Qt::AA_EnableHighDpiScaling); + // + // Application app(argc, argv); + // app.setAttribute(Qt::AA_DontCreateNativeWidgetSiblings); + // InstallCrashHandler(); + // + // RecourceHelper::ChangeSkin("default"); + // + // MainFrame mainWindow; + // mainWindow.showMaximized(); + // + // int ret = app.exec(); + // return ret; - MainFrame mainWindow; - mainWindow.showMaximized(); - - ret = app.exec(); - return ret; + osg::ArgumentParser arguments(&argc, argv); + + // Qt5 is currently crashing and reporting "Cannot make QOpenGLContext current in a different thread" when the viewer is run multi-threaded, this is regression from Qt4 + osgViewer::ViewerBase::ThreadingModel threadingModel = osgViewer::ViewerBase::SingleThreaded; + + QApplication app(argc, argv); + OsgWidget* viewWidget = new OsgWidget(nullptr, Qt::Widget); + // ViewerWidget* viewWidget = new ViewerWidget(nullptr, Qt::Widget, threadingModel); + viewWidget->setGeometry( 100, 100, 800, 600 ); + viewWidget->Initialize(); + viewWidget->show(); + return app.exec(); } diff --git a/src/scene/OEScene.cpp b/src/scene/OEScene.cpp index cde9cd6f..d4ab5071 100644 --- a/src/scene/OEScene.cpp +++ b/src/scene/OEScene.cpp @@ -6,8 +6,8 @@ #include #include #include -#include -#include +#include +#include #include #include @@ -25,161 +25,71 @@ const osgEarth::SpatialReference* g_srs_{ nullptr }; - OEScene::OEScene() { osgDB::FilePathList& pathList = osgDB::Registry::instance()->getDataFilePathList(); const std::string& basePath = RecourceHelper::Get().GetBasePath().toStdString(); pathList.push_back(basePath + "/resources/earth/"); pathList.push_back(basePath + "/resources/textures/"); - root_ = new osg::Group; + + Init(); } - -void OEScene::InitEventHandle(class OsgView* view) { - if (nullptr == view) { - LOG_WARN("view is nullptr"); - return; - } - - //view->GetView()->addEventHandler(new osgEarth::Util::EarthManipulator()); - - view->GetView()->addEventHandler(new osgViewer::HelpHandler); - view->GetView()->addEventHandler(new osgViewer::StatsHandler); -} - -void OEScene::AttachView(OsgView* view) { - if (nullptr == view) { - LOG_WARN("view is nullptr"); - return; - } - - osg::Node* rootNode = view->GetView()->getSceneData(); - if (nullptr != rootNode) { - int parantCount = rootNode->getNumParents(); - for (int i = 0; i < parantCount; ++i) { - rootNode->getParent(i)->removeChild(rootNode); - } - root_->addChild(rootNode); - } - - view->GetView()->setSceneData(root_); - - earthRootNode_ = osgDB::readNodeFile("triton.earth"); +void OEScene::AttachView(osgViewer::View* view) { dyt_check(nullptr != earthRootNode_); - logarithmicDepthBuffer_ = std::make_unique(); - - earthMapNode_ = osgEarth::MapNode::get(earthRootNode_); - dyt_check(nullptr != earthMapNode_); - LOG_INFO("earth map node get success: {}", earthMapNode_.valid()); - g_srs_ = earthMapNode_->getMapSRS(); - - entityRoot_ = new osg::Group; - root_->addChild(entityRoot_); - - skyDome_ = osgEarth::SkyNode::create(); + skyDome_ = osgEarth::Util::SkyNode::create(earthMapNode_); if (!earthMapNode_) { LOG_WARN("eart map node is nullptr"); return; } - root_->addChild(skyDome_); - skyDome_->addChild(earthMapNode_); - skyDome_->attach(view->GetView()); - skyDome_->setAtmosphereVisible(true); - skyDome_->setSunVisible(true); - skyDome_->setMoonVisible(true); - skyDome_->setStarsVisible(true); + dyt_check(nullptr != earthManipulator_); + view->setCameraManipulator(earthManipulator_); + skyDome_->attach(view); + skyDome_->getSunLight()->setAmbient(osg::Vec4(0.5,0.5,0.5,1.0)); + addChild(skyDome_); + + view->setCameraManipulator( new osgEarth::Util::EarthManipulator() ); skyDome_->setDateTime(osgEarth::DateTime(2024, 12, 24, 3)); - skyDome_->setSimulationTimeTracksDateTime(true); - logarithmicDepthBuffer_->install(view->GetView()->getCamera()); - - ConeWave* coneWave = new ConeWave; - - osgEarth::GeoTransform *geo = new osgEarth::GeoTransform; - entityRoot_->addChild(geo); - - osgEarth::GeoPoint pos(g_srs_, 120.000000,25.000000,600.000000); - geo->setPosition(pos); - coneWave->createWaveBeamCone(geo, 45, 6000, osg::Vec4(1.0, 0.0, 0.0, 0.3), - osg::Vec4(1.0, 1.0, 0.0, 0.3), 30); - osg::MatrixTransform* mt =coneWave->getWaveBeamCone(); - geo->addChild(mt); + view->setSceneData(this); + curentView_ = view; } -void OEScene::DetachView(OsgView* view) { - if (nullptr != earthRootNode_) { - std::vector parents = earthRootNode_->getParents(); - for (const auto& parent : parents) { - parent->removeChild(earthRootNode_); - } - } - logarithmicDepthBuffer_->uninstall(view->GetView()->getCamera()); - view->GetView()->setSceneData(nullptr); - +void OEScene::DetachView(osgViewer::View* view) { + view->setSceneData(nullptr); } -#define USE_CUSTOM_SHADER - -osg::ref_ptr OEScene::LoadCubeMapTextures(const std::string& dir) { - enum { - POS_X, NEG_X, POS_Y, NEG_Y, POS_Z, NEG_Z - }; - - std::string filenames[6]; - - std::string basePath = RecourceHelper::Get().GetBasePath().toStdString(); - - filenames[POS_X] = basePath + "/resources/textures/" + dir + "/east.png"; - filenames[NEG_X] = basePath + "/resources/textures/" + dir + "/west.png"; - filenames[POS_Z] = basePath + "/resources/textures/" + dir + "/north.png"; - filenames[NEG_Z] = basePath + "/resources/textures/" + dir + "/south.png"; - filenames[POS_Y] = basePath + "/resources/textures/" + dir + "/down.png"; - filenames[NEG_Y] = basePath + "/resources/textures/" + dir + "/up.png"; - - osg::ref_ptr cubeMap = new osg::TextureCubeMap; - cubeMap->setInternalFormat(GL_RGBA); - - cubeMap->setFilter(osg::Texture::MIN_FILTER, osg::Texture::LINEAR_MIPMAP_LINEAR); - cubeMap->setFilter(osg::Texture::MAG_FILTER, osg::Texture::LINEAR); - cubeMap->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE); - cubeMap->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE); - - cubeMap->setImage(osg::TextureCubeMap::NEGATIVE_X, osgDB::readImageFile(filenames[NEG_X])); - cubeMap->setImage(osg::TextureCubeMap::POSITIVE_X, osgDB::readImageFile(filenames[POS_X])); - cubeMap->setImage(osg::TextureCubeMap::NEGATIVE_Y, osgDB::readImageFile(filenames[NEG_Y])); - cubeMap->setImage(osg::TextureCubeMap::POSITIVE_Y, osgDB::readImageFile(filenames[POS_Y])); - cubeMap->setImage(osg::TextureCubeMap::NEGATIVE_Z, osgDB::readImageFile(filenames[NEG_Z])); - cubeMap->setImage(osg::TextureCubeMap::POSITIVE_Z, osgDB::readImageFile(filenames[POS_Z])); - - return cubeMap; -} - -osg::Group* OEScene::GetData() { - return root_; -} - - - -void OEScene::AddToScene(osg::Node* node) { +bool OEScene::AddToScene(osg::Node* node) const { dyt_check(nullptr != entityRoot_); - entityRoot_->addChild(node); - /* osgOcean::OceanScene* oceanScene = GetOceanScene(); - if (nullptr == oceanScene) { - LOG_WARN("oceanScene is nullptr"); - return; - } - - node->setNodeMask(oceanScene->getNormalSceneMask() | - oceanScene->getReflectedSceneMask() | - oceanScene->getRefractedSceneMask() | - CAST_SHADOW | RECEIVE_SHADOW); - oceanScene->addChild(node);*/ - /* osg::Group* root = GetScene(); - root->addChild(node);*/ + return entityRoot_->addChild(node); } +// +// void OEScene::InitEventHandle(osgViewer::View* view) { +// if (nullptr == view) { +// LOG_WARN("view is nullptr"); +// return; +// } +// +// //view->GetView()->addEventHandler(new osgEarth::Util::EarthManipulator()); +// +// view->addEventHandler(new osgViewer::HelpHandler); +// view->addEventHandler(new osgViewer::StatsHandler); +// } + +// void OEScene::DetachView(osgViewer::View* view) { +// if (nullptr != earthRootNode_) { +// std::vector parents = earthRootNode_->getParents(); +// for (const auto& parent : parents) { +// parent->removeChild(earthRootNode_); +// } +// } +// logarithmicDepthBuffer_->uninstall(view->getCamera()); +// view->setSceneData(nullptr); +// +// } + OESceneUI* OEScene::GetOrCreateSceneUI() { if (sceneUI_) { LOG_INFO("scene ui is already attached"); @@ -189,3 +99,32 @@ OESceneUI* OEScene::GetOrCreateSceneUI() { sceneUI_ = new OESceneUI(this); return sceneUI_.get(); } + +osg::Viewport* OEScene::GetViewport() const { + dyt_check(nullptr != curentView_); + + return curentView_->getCamera()->getViewport(); +} + +const osgEarth::SpatialReference* OEScene::GetSrs() { + dyt_check(nullptr != g_srs_); + return g_srs_; +} + +void OEScene::Init() { + std::string earthPath = "D:/Project/DYT/Tool/TritonSample/TritonSample/triton.earth"; + // earthRootNode_ = osgDB::readNodeFile("triton.earth"); + earthRootNode_ = osgDB::readNodeFile(earthPath); + dyt_check(nullptr != earthRootNode_); + addChild(earthRootNode_); + + earthMapNode_ = osgEarth::MapNode::get(earthRootNode_); + dyt_check(nullptr != earthMapNode_); + LOG_INFO("earth map node get success: {}", earthMapNode_.valid()); + g_srs_ = earthMapNode_->getMapSRS(); + + earthManipulator_ = new osgEarth::Util::EarthManipulator(); + + entityRoot_ = new osg::Group; + addChild(entityRoot_); +} diff --git a/src/scene/OEScene.h b/src/scene/OEScene.h index f3f5dc18..0639363d 100644 --- a/src/scene/OEScene.h +++ b/src/scene/OEScene.h @@ -1,56 +1,50 @@ #pragma once -#include -#include - -#include -#include -#include -#include - -//#include "scene/SkyDome.h" +#include +#include #include "common/SpdLogger.h" #include "config.h" #include "scene/ui/OESceneUI.h" -class OsgView; -class OEScene : public osg::Referenced { +namespace osgEarth { +namespace Util { + class EarthManipulator; +} +} + +class OEScene : public osg::Group { public: OEScene(); - void InitEventHandle(OsgView* view); - void AttachView(OsgView* view); - void DetachView(OsgView* view); - - osg::ref_ptr LoadCubeMapTextures(const std::string& dir); - - inline osg::Vec4f IntColor(unsigned r, unsigned g, unsigned b, unsigned a = 255) { - float div = 1.f / 255.f; - return osg::Vec4f(div * (float)r, div * (float)g, div * float(b), div * (float)a); - } - - osg::Group* GetData(); - - inline osg::Group* GetScene(void) { - return root_.get(); - } + void AttachView(osgViewer::View* view); + void DetachView(osgViewer::View* view); + bool AddToScene(osg::Node* node) const; + osgEarth::MapNode* GetMapNode(void) const { dyt_check(earthMapNode_.valid()); return earthMapNode_; } - void AddToScene(osg::Node* node); - OESceneUI* GetOrCreateSceneUI(); + osgEarth::Util::EarthManipulator* GetManipulater() const { + return earthManipulator_.get(); + } + + osg::Viewport* GetViewport() const; + + static const osgEarth::SpatialReference* GetSrs(); + +private: + void Init(); private: - osg::ref_ptr root_; osg::ref_ptr earthRootNode_; + osg::ref_ptr earthManipulator_; osg::ref_ptr earthMapNode_; osg::ref_ptr entityRoot_; - osg::ref_ptr skyDome_; - std::unique_ptr logarithmicDepthBuffer_; + osg::ref_ptr skyDome_; osg::ref_ptr sceneUI_; + osgViewer::View* curentView_ {nullptr}; }; diff --git a/src/scene/TritonAPIWrapper.cpp b/src/scene/TritonAPIWrapper.cpp deleted file mode 100644 index 73e24fef..00000000 --- a/src/scene/TritonAPIWrapper.cpp +++ /dev/null @@ -1,114 +0,0 @@ -/* -*-c++-*- */ -/* osgEarth - Geospatial SDK for OpenSceneGraph - * Copyright 2020 Pelican Mapping - * http://osgearth.org - * - * osgEarth is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see - */ -#include "TritonAPIWrapper.h" -#include - -#define LC "[TritonAPI] " - -using namespace osgEarth::Triton; - -#define SETGET_EXPLICIT(NS, SETTER, GETTER, TYPE) \ - void NS :: SETTER (TYPE value) { HANDLE-> SETTER (value); } \ - TYPE NS :: GETTER () const { return HANDLE -> GETTER (); } - -#define SETGET(NS, FUNC, TYPE) \ - SETGET_EXPLICIT(NS, Set##FUNC, Get##FUNC, TYPE) - -#define TOVEC3(X) ::Triton::Vector3(X.x(),X.y(),X.z()) -#define FROMVEC3(X) osg::Vec3(X.x,X.y,X.z) - -//................................ -#undef HANDLE -#define HANDLE ((::Triton::BreakingWavesParameters*)_handle) - -SETGET(BreakingWavesParameters, Steepness, float); -SETGET(BreakingWavesParameters, Wavelength, float); - -//................................ -#undef HANDLE -#define HANDLE ((::Triton::Environment*)_handle) - -BreakingWavesParameters Environment::GetBreakingWavesParameters() const { - return BreakingWavesParameters((uintptr_t)&HANDLE->GetBreakingWavesParameters()); -} -void Environment::SetDirectionalLight(const osg::Vec3& dir, const osg::Vec3& color) { - HANDLE->SetDirectionalLight(TOVEC3(dir), TOVEC3(color)); -} -osg::Vec3 Environment::GetLightDirection() const { - const ::Triton::Vector3& v = HANDLE->GetLightDirection(); - return FROMVEC3(v); -} -osg::Vec3 Environment::GetDirectionalLightColor() const { - const ::Triton::Vector3& v = HANDLE->GetDirectionalLightColor(); - return FROMVEC3(v); -} -void Environment::SetAmbientLight(const osg::Vec3& color) { - HANDLE->SetAmbientLight(TOVEC3(color)); -} -osg::Vec3 Environment::GetAmbientLightColor() const { - const ::Triton::Vector3& v = HANDLE->GetAmbientLightColor(); - return FROMVEC3(v); -} -void Environment::SimulateSeaState(double bscale, double winddir) { - HANDLE->SimulateSeaState(bscale, winddir); -} -void Environment::SetAboveWaterVisibility(double visibility, osg::Vec3 fog_color) { - HANDLE->SetAboveWaterVisibility(visibility, TOVEC3(fog_color)); -} -void Environment::GetAboveWaterVisibility(double &visibility, osg::Vec3 &fog_color) const { - ::Triton::Vector3 triton_fog_col; - HANDLE->GetAboveWaterVisibility(visibility, triton_fog_col); - fog_color = FROMVEC3(triton_fog_col); -} -void Environment::SetEnvironmentMap(GLuint cubeMap, const osg::Matrixd &textureMatrix) { - ::Triton::Matrix3 triton_tex_mat( - textureMatrix(0, 0), textureMatrix(0, 1), textureMatrix(0, 2), - textureMatrix(1, 0), textureMatrix(1, 1), textureMatrix(1, 2), - textureMatrix(2, 0), textureMatrix(2, 1), textureMatrix(2, 2)); - ::Triton::TextureHandle tex_handle = (::Triton::TextureHandle)(static_cast(cubeMap)); - HANDLE->SetEnvironmentMap(tex_handle, triton_tex_mat); -} -GLuint Environment::GetEnvironmentMap() const { - ::Triton::TextureHandle tex_handle = HANDLE->GetEnvironmentMap(); - return static_cast((size_t)tex_handle); -} -osg::Matrixd Environment::GetEnvironmentMapMatrix() const { - ::Triton::Matrix3 m = HANDLE->GetEnvironmentMapMatrix(); - osg::Matrixd env_map_matrix( - m.elem[0][0], m.elem[0][1], m.elem[0][2], 0, - m.elem[1][0], m.elem[1][1], m.elem[1][2], 0, - m.elem[2][0], m.elem[2][1], m.elem[2][2], 0, - 0, 0, 0, 1); - return env_map_matrix; -} -SETGET(Environment, SunIntensity, float); - -//................................ -#undef HANDLE -#define HANDLE ((::Triton::Ocean*)_handle) - -SETGET(Ocean, Choppiness, float); -//SETGET(Ocean, MaximumWavePeriod, double); -SETGET_EXPLICIT(Ocean, EnableSpray, SprayEnabled, bool); -SETGET_EXPLICIT(Ocean, EnableGodRays, GodRaysEnabled, bool); -SETGET(Ocean, GodRaysFade, float); - -void Ocean::EnableWireframe(bool wireframe) { HANDLE->EnableWireframe(wireframe); } -void Ocean::SetQuality(OceanQuality value) { HANDLE->SetQuality((::Triton::OceanQuality)value); } -OceanQuality Ocean::GetQuality() const { return (OceanQuality)HANDLE->GetQuality(); } diff --git a/src/scene/TritonAPIWrapper.h b/src/scene/TritonAPIWrapper.h deleted file mode 100644 index f1921ad6..00000000 --- a/src/scene/TritonAPIWrapper.h +++ /dev/null @@ -1,112 +0,0 @@ -/* -*-c++-*- */ -/* osgEarth - Geospatial SDK for OpenSceneGraph - * Copyright 2020 Pelican Mapping - * http://osgearth.org - * - * osgEarth is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see - */ -#ifndef OSGEARTH_TRITON_API_WRAPPER -#define OSGEARTH_TRITON_API_WRAPPER 1 - -//#include "Common" -#include -#include -#include -#include // for uintptr_t - -namespace osgEarth { - namespace Util { - class OceanNode; - } -} - -namespace osgEarth { namespace Triton -{ - /** Enumerates the ocean quality settings used in Ocean::SetQuality() */ - enum OceanQuality { - GOOD, - BETTER, - BEST - }; - - class BreakingWavesParameters - { - public: - void SetSteepness(float); - float GetSteepness() const; - - void SetWavelength(float); - float GetWavelength() const; - - public: - BreakingWavesParameters(uintptr_t handle) : _handle(handle) { } - uintptr_t _handle; - }; - - class Environment - { - public: - void SetDirectionalLight(const osg::Vec3& dir, const osg::Vec3& color); - osg::Vec3 GetLightDirection() const; - osg::Vec3 GetDirectionalLightColor() const; - - void SetAmbientLight(const osg::Vec3& color); - osg::Vec3 GetAmbientLightColor() const; - - void SetSunIntensity(float intensity); - float GetSunIntensity() const; - - BreakingWavesParameters GetBreakingWavesParameters() const; - - void SimulateSeaState(double bs, double winddir); - - void SetAboveWaterVisibility(double visibility, osg::Vec3 fog_color); - void GetAboveWaterVisibility(double &visibility, osg::Vec3 &fog_color) const; - - void SetEnvironmentMap(GLuint id, const osg::Matrixd &textureMatrix = osg::Matrixd()); - GLuint GetEnvironmentMap() const; - osg::Matrixd GetEnvironmentMapMatrix() const; - public: - Environment(uintptr_t handle) : _handle(handle) { } - uintptr_t _handle; - }; - - class Ocean - { - public: - void SetChoppiness(float); - float GetChoppiness() const; - - void EnableWireframe(bool wireframe); - - void SetQuality(OceanQuality value); - OceanQuality GetQuality() const; - - void EnableSpray(bool enabled); - bool SprayEnabled() const; - - void EnableGodRays(bool enabled); - bool GodRaysEnabled() const; - - void SetGodRaysFade(float fadeAmount); - float GetGodRaysFade() const; - - public: - Ocean(uintptr_t handle) : _handle(handle) { } - uintptr_t _handle; - }; - -} } // namespace osgEarth::SilverLining - -#endif // OSGEARTH_TRITON_API_WRAPPER diff --git a/src/scene/TritonCallback.h b/src/scene/TritonCallback.h deleted file mode 100644 index 122aa23c..00000000 --- a/src/scene/TritonCallback.h +++ /dev/null @@ -1,39 +0,0 @@ -/* -*-c++-*- */ -/* osgEarth - Geospatial SDK for OpenSceneGraph - * Copyright 2020 Pelican Mapping - * http://osgearth.org - * - * osgEarth is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see - */ -#ifndef OSGEARTH_TRITON_CALLBACK_H -#define OSGEARTH_TRITON_CALLBACK_H 1 - -#include "TritonAPIWrapper.h" - -namespace osgEarth { namespace Triton -{ - /** - * A callback that lets you execute code in the proper context. - */ - class Callback : public osg::Referenced - { - public: - virtual void onInitialize(Environment& env, Ocean& ocean) { } - - virtual void onDrawOcean(Environment& env, Ocean& ocean) { } - }; - -} } // namespace osgEarth::Triton - -#endif // OSGEARTH_TRITON_CALLBACK_H diff --git a/src/scene/TritonContext.cpp b/src/scene/TritonContext.cpp deleted file mode 100644 index f6edc18a..00000000 --- a/src/scene/TritonContext.cpp +++ /dev/null @@ -1,229 +0,0 @@ -/* -*-c++-*- */ -/* osgEarth - Geospatial SDK for OpenSceneGraph - * Copyright 2020 Pelican Mapping - * http://osgearth.org - * - * osgEarth is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see - */ -#include "TritonContext.h" -#include -#include -#include -#include -#include -#include - -#define LC "[TritonContext] " - -using namespace osgEarth::Triton; - - -TritonContext::TritonContext(const TritonLayer::Options& options) : -_options ( options ), -_initAttempted ( false ), -_initFailed ( false ), -_resourceLoader ( 0L ), -_environment ( 0L ), -_environmentWrapper ( 0L ), -_ocean ( 0L ), -_oceanWrapper ( 0L ) -{ - //nop -} - -TritonContext::~TritonContext() -{ - if (_oceanWrapper) - delete _oceanWrapper; - - if (_environmentWrapper) - delete _environmentWrapper; -} - -void -TritonContext::setSRS(const osgEarth::SpatialReference* srs) -{ - _srs = srs; -} - -void -TritonContext::setCallback(Callback* callback) -{ - _callback = callback; -} - -bool -TritonContext::passHeightMapToTriton() const -{ - return _options.useHeightMap() == true; -} - -int -TritonContext::getHeightMapSize() const -{ - return osg::clampBetween(_options.heightMapSize().get(), 64u, 2048u); -} - -const std::string& -TritonContext::getMaskLayerName() const -{ - return _options.maskLayer().externalLayerName().get(); -} - -void -TritonContext::initialize(osg::RenderInfo& renderInfo) -{ - if ( !_initAttempted && !_initFailed ) - { - // lock/double-check: - std::lock_guard excl(_initMutex); - if ( !_initAttempted && !_initFailed ) - { - _initAttempted = true; - - std::string resourcePath = _options.resourcePath().get(); - if (resourcePath.empty() && ::getenv("TRITON_PATH")) - { - resourcePath = osgDB::concatPaths(::getenv("TRITON_PATH"), "Resources"); - } - - if ( resourcePath.empty() ) - { - const QString dir = QString("%1/TritonResources").arg(QApplication::applicationDirPath()); - resourcePath = dir.toStdString(); - } - - _resourceLoader = new ::Triton::ResourceLoader(resourcePath.c_str()); - - _environment = new ::Triton::Environment(); - - _environmentWrapper = new Environment((uintptr_t)_environment); - - _environment->SetLicenseCode( - _options.user()->c_str(), - _options.licenseCode()->c_str() ); - - // "WGS84" is used to represent any ellipsoid. - ::Triton::CoordinateSystem cs = - _srs->isGeographic() ? ::Triton::WGS84_ZUP : - ::Triton::FLAT_ZUP; - - // Set the ellipsoid to match the one in our map's SRS. - if ( _srs->isGeographic() ) - { - const Ellipsoid& ellipsoid = _srs->getEllipsoid(); - - std::string eqRadius = Stringify() << ellipsoid.getRadiusEquator(); - std::string poRadius = Stringify() << ellipsoid.getRadiusPolar(); - - _environment->SetConfigOption( "equatorial-earth-radius-meters", eqRadius.c_str() ); - _environment->SetConfigOption( "polar-earth-radius-meters", poRadius.c_str() ); - } - - //_environment->SetConfigOption("avoid-opengl-stalls", "yes"); - //_environment->SetConfigOption("fft-texture-update-frame-delayed", "yes"); - - float openGLVersion = osg::getGLVersionNumber(); - enum ::Triton::Renderer tritonOpenGlVersion = ::Triton::OPENGL_2_0; -#ifndef OSG_GL_FIXED_FUNCTION_AVAILABLE - if( openGLVersion >= 4.1 ) - tritonOpenGlVersion = ::Triton::OPENGL_4_1; - else if( openGLVersion >= 4.0 ) - tritonOpenGlVersion = ::Triton::OPENGL_4_0; - else if( openGLVersion >= 3.2 ) - tritonOpenGlVersion = ::Triton::OPENGL_3_2; -#endif - - ::Triton::EnvironmentError err = _environment->Initialize( - cs, - tritonOpenGlVersion, - _resourceLoader ); - - if ( err == ::Triton::SUCCEEDED ) - { - ::Triton::WindFetch wf; - wf.SetWind( 10.0, 0.0 ); - _environment->AddWindFetch( wf ); - - _ocean = ::Triton::Ocean::Create( - _environment, - ::Triton::JONSWAP, - true ); // enableHeightTests - activated GetHeight for intersections - } - - if ( _ocean ) - { - _oceanWrapper = new Ocean((uintptr_t)_ocean); - - // fire init callback if available - if (_callback.valid()) - { - _callback->onInitialize(getEnvironmentWrapper(), getOceanWrapper()); - } - - OE_INFO << LC << "Triton initialized OK!" << std::endl; - } - else - { - _initFailed = true; - OE_WARN << LC << "Triton initialization failed- err=" << err << std::endl; - } - } - } -} - -bool -TritonContext::intersect(const osg::Vec3d& start, const osg::Vec3d& dir, float& out_height, osg::Vec3f& out_normal) const -{ - ::Triton::Vector3 p(start.ptr()); - ::Triton::Vector3 d(dir.ptr()); - ::Triton::Vector3 normal; - bool ok = _ocean->GetHeight(p, d, out_height, normal); - out_normal.set(normal.x, normal.y, normal.z); - return ok; -} - -void -TritonContext::resizeGLObjectBuffers(unsigned maxSize) -{ - osg::Object::resizeGLObjectBuffers(maxSize); -} - -void -TritonContext::releaseGLObjects(osg::State* state) const -{ - osg::Object::releaseGLObjects(state); - - OE_DEBUG << LC << "Triton shutting down - releasing GL resources\n"; - if (state) - { - if ( _ocean ) - { - delete _ocean; - _ocean = 0L; - } - - if ( _environment ) - { - delete _environment; - _environment = 0L; - } - - if ( _resourceLoader ) - { - delete _resourceLoader; - _resourceLoader = 0L; - } - } -} diff --git a/src/scene/TritonContext.h b/src/scene/TritonContext.h deleted file mode 100644 index dee9d4cf..00000000 --- a/src/scene/TritonContext.h +++ /dev/null @@ -1,115 +0,0 @@ -/* -*-c++-*- */ -/* osgEarth - Geospatial SDK for OpenSceneGraph - * Copyright 2020 Pelican Mapping - * http://osgearth.org - * - * osgEarth is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see - */ -#ifndef OSGEARTH_TRITON_CONTEXT_H -#define OSGEARTH_TRITON_CONTEXT_H - -#include -#include // Triton -#include "TritonLayer.h" -#include "TritonAPIWrapper.h" -#include "TritonCallback.h" -#include -#include -#include - -namespace osgEarth { - class SpatialReference; -} - -namespace osgEarth { namespace Triton -{ - /** - * Contains all the Triton SDK handles. - */ - class TritonContext : public osg::Object - { - public: - META_Object(osgEarth, TritonContext); - - TritonContext(const TritonLayer::Options&); - - /** Sets the spatial reference system of the map */ - void setSRS(const osgEarth::SpatialReference* srs); - - /** Sets the user callback */ - void setCallback(Callback* callback); - Callback* getCallback() const { return _callback.get(); } - - public: // accessors - - bool ready() const { return _initAttempted && !_initFailed; } - - /** Spatial reference of the map */ - const osgEarth::SpatialReference* getSRS() const { return _srs.get(); } - - void initialize(osg::RenderInfo& renderInfo); - - bool intersect(const osg::Vec3d& start, const osg::Vec3d& dir, float& out_height, osg::Vec3f& out_normal) const; - - ::Triton::Environment* getEnvironment() { return _environment; } - Environment& getEnvironmentWrapper() const { return *_environmentWrapper; } - - ::Triton::Ocean* getOcean() { return _ocean; } - Ocean& getOceanWrapper() const { return *_oceanWrapper; } - - bool passHeightMapToTriton() const; - - int getHeightMapSize() const; - - const std::string& getMaskLayerName() const; - - public: // osg::Object - - void resizeGLObjectBuffers(unsigned maxSize); - - /** If State is non-zero, this function releases any associated OpenGL objects for - * the specified graphics context. Otherwise, releases OpenGL objects - * for all graphics contexts. */ - void releaseGLObjects(osg::State* state) const; - - protected: - - virtual ~TritonContext(); - - // hidden ctors (for META_Object) - TritonContext() { } - TritonContext(const TritonContext&, const osg::CopyOp&) { } - - private: - TritonLayer::Options _options; - - bool _initAttempted; - bool _initFailed; - std::mutex _initMutex; - - osg::ref_ptr _srs; - - mutable ::Triton::ResourceLoader* _resourceLoader; - mutable ::Triton::Environment* _environment; - mutable ::Triton::Ocean* _ocean; - - Environment* _environmentWrapper; - Ocean* _oceanWrapper; - - osg::ref_ptr _callback; - }; - -} } // namespace osgEarth::Triton - -#endif // OSGEARTH_TRITON_CONTEXT_H \ No newline at end of file diff --git a/src/scene/TritonDrawable.cpp b/src/scene/TritonDrawable.cpp deleted file mode 100644 index b21c8579..00000000 --- a/src/scene/TritonDrawable.cpp +++ /dev/null @@ -1,330 +0,0 @@ -/* -*-c++-*- */ -/* osgEarth - Geospatial SDK for OpenSceneGraph - * Copyright 2020 Pelican Mapping - * http://osgearth.org - * - * osgEarth is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see - */ -#include "TritonContext.h" -#include "TritonDrawable.h" -#include "TritonHeightMap.h" -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -#undef LC -#define LC "[TritonDrawable] " - -//#define DEBUG_HEIGHTMAP - -using namespace osgEarth::Triton; - - -TritonDrawable::TritonDrawable(TritonContext* TRITON) : - _TRITON(TRITON) -{ - // call this to ensure draw() gets called every frame. - setSupportsDisplayList( false ); - setUseVertexBufferObjects( false ); - - // dynamic variance prevents update/cull overlap when drawing this - setDataVariance( osg::Object::DYNAMIC ); - - _wgs84 = SpatialReference::get("wgs84"); - _ecef = _wgs84->getGeocentricSRS(); -} - -TritonDrawable::~TritonDrawable() -{ - //nop -} - -void -TritonDrawable::setMaskLayer(const osgEarth::ImageLayer* layer) -{ - _maskLayer = layer; -} - -void -TritonDrawable::setHeightMapGenerator(TritonHeightMap* value) -{ - _heightMapGenerator = value; -} - -void -TritonDrawable::setPlanarReflectionMap(osg::Texture2D* map) -{ - _planarReflectionMap = map; -} - -void -TritonDrawable::setPlanarReflectionProjection(osg::RefMatrix* proj) -{ - _planarReflectionProjection = proj; -} - -osg::BoundingBox -TritonDrawable::computeBoundingBox() const -{ - return osg::BoundingBox(); -} - -namespace { - -// Wrapper around Ocean->GetShaderObject() to account for API changes from Triton 3.x to 4.x -GLint -getOceanShader(::Triton::Ocean* ocean, ::Triton::Shaders shaderProgram, void* context, const ::Triton::Camera* camera) -{ -#if (TRITON_MAJOR_VERSION >= 4) - return (GLint)ocean->GetShaderObject( shaderProgram, context, camera ); -#else - return (GLint)ocean->GetShaderObject( shaderProgram ); -#endif -} - -} - -void -TritonDrawable::drawImplementation(osg::RenderInfo& renderInfo) const -{ - OE_GL_ZONE; - - osg::State* state = renderInfo.getState(); - - state->disableAllVertexArrays(); - - _TRITON->initialize( renderInfo ); - if ( !_TRITON->ready() ) - return; - - // Configure the height map generator. - // If configuration fails, attempt to continue without a heightmap. - if (_heightMapGenerator.valid()) - { - bool configOK = _heightMapGenerator->configure(_TRITON->getHeightMapSize(), *state); - if (configOK == false) - { - _heightMapGenerator = 0L; - OE_WARN << LC << "Failed to establish a legal FBO configuration; disabling height map generator!" << std::endl; - } - } - - ::Triton::Environment* environment = _TRITON->getEnvironment(); - - // Find or create the Triton camera for this OSG camera: - CameraLocal& local = _local.get(renderInfo.getCurrentCamera()); - if (local._tritonCam == 0L) - { - local._tritonCam = environment->CreateCamera(); - local._tritonCam->SetName(renderInfo.getCurrentCamera()->getName().c_str()); - } - ::Triton::Camera* tritonCam = local._tritonCam; - - auto cid = GLUtils::getSharedContextID(*state); - osgEarth::NativeProgramAdapterCollection& adapters = _adapters[cid]; - if ( adapters.empty() ) - { - OE_DEBUG << LC << "Initializing Triton program adapters" << std::endl; - const std::vector prefixes = { "osg_", "oe_" }; - adapters.push_back( new osgEarth::NativeProgramAdapter(state, getOceanShader(_TRITON->getOcean(), ::Triton::WATER_SURFACE, 0L, tritonCam), prefixes, "WATER_SURFACE")); - adapters.push_back( new osgEarth::NativeProgramAdapter(state, getOceanShader(_TRITON->getOcean(), ::Triton::WATER_SURFACE_PATCH, 0L, tritonCam), prefixes, "WATER_SURFACE_PATCH")); - adapters.push_back( new osgEarth::NativeProgramAdapter(state, getOceanShader(_TRITON->getOcean(), ::Triton::GOD_RAYS, 0L, tritonCam), prefixes, "GOD_RAYS")); - adapters.push_back( new osgEarth::NativeProgramAdapter(state, getOceanShader(_TRITON->getOcean(), ::Triton::SPRAY_PARTICLES, 0L, tritonCam), prefixes, "SPRAY_PARTICLES")); - adapters.push_back( new osgEarth::NativeProgramAdapter(state, getOceanShader(_TRITON->getOcean(), ::Triton::WAKE_SPRAY_PARTICLES, 0L, tritonCam), prefixes, "WAKE_SPRAY_PARTICLES")); -#if 0 - // In older Triton (3.91), this line causes problems in Core profile and prevents the ocean from drawing. In newer Triton (4.01), - // this line causes a crash because there is no context passed in to GetShaderObject(), resulting in multiple NULL references. - adapters.push_back( new osgEarth::NativeProgramAdapter(state, getOceanShader(_TRITON->getOcean(), ::Triton::WATER_DECALS, 0L, tritonCam), prefixes, "WATER_DECALS")); -#endif - } - adapters.apply( state ); - - - // Pass the final view and projection matrices into Triton. - if ( environment ) - { - tritonCam->SetCameraMatrix(state->getModelViewMatrix().ptr()); - tritonCam->SetProjectionMatrix(state->getProjectionMatrix().ptr()); - } - - // Calculate sea level based on the camera: - if (_verticalDatum.valid()) - { - GeoPoint cam(_ecef, osg::Vec3d(0, 0, 0) * state->getInitialInverseViewMatrix(), ALTMODE_ABSOLUTE); - cam.transformInPlace(_wgs84); - auto msl = _verticalDatum->hae2msl(cam.y(), cam.x(), 0.0); - environment->SetSeaLevel(-msl); - } - - if (_heightMapGenerator.valid()) - { - GLint texName; - osg::Matrix hMM; - if (_heightMapGenerator->getTextureAndMatrix(renderInfo, texName, hMM)) - { - // copy the OSG matrix to a Triton matrix: - ::Triton::Matrix4 texMat( - hMM(0, 0), hMM(0, 1), hMM(0, 2), hMM(0, 3), - hMM(1, 0), hMM(1, 1), hMM(1, 2), hMM(1, 3), - hMM(2, 0), hMM(2, 1), hMM(2, 2), hMM(2, 3), - hMM(3, 0), hMM(3, 1), hMM(3, 2), hMM(3, 3)); - - environment->SetHeightMap((::Triton::TextureHandle)texName, texMat, 0L, tritonCam); - - //OE_DEBUG << LC << "Updating height map, FN=" << renderInfo.getState()->getFrameStamp()->getFrameNumber() << std::endl; - } - } - - state->dirtyAllVertexArrays(); - - // Now light and draw the ocean: - if ( environment ) - { - // User pre-draw callback: - if (_TRITON->getCallback()) - { - _TRITON->getCallback()->onDrawOcean( - _TRITON->getEnvironmentWrapper(), - _TRITON->getOceanWrapper()); - } - - osg::Light* light = renderInfo.getView() ? renderInfo.getView()->getLight() : NULL; - - // This is the light attached to View so there are no transformations above.. - // But in general case you would need to accumulate all transforms above the light into this matrix - osg::Matrix lightLocalToWorldMatrix = osg::Matrix::identity(); - - // If you don't know where the sun lightsource is attached and don't know its local to world matrix you may use - // following elaborate scheme to grab the light source while drawing Triton ocean: - // - Install cull callback to catch CullVisitor and record pointer to its associated RenderStage - // I was hoping RenderStage can be found from renderInfo in drawImplementation but I didn't figure how ... - // - When TritonDrawable::drawImplementation is called all lights will be already applied to OpenGL - // then just find proper infinite directional light by scanning renderStage->PositionalStateContainer. - // - Note that we canot scan for the lights inside cull because they may not be traversed before Triton drawable - // - When you found interesting ligt source that can work as Sun, read its modelview matrix and lighting params - // Multiply light position by ( modelview * inverse camera view ) and pass this to Triton with lighting colors - - if ( light && light->getPosition().w() == 0 ) - { - osg::Vec4 ambient = light->getAmbient(); - osg::Vec4 diffuse = light->getDiffuse(); - osg::Vec4 position = light->getPosition(); - - // Compute light position/direction in the world - position = position * lightLocalToWorldMatrix; - - // Diffuse direction and color - environment->SetDirectionalLight( - ::Triton::Vector3( position[0], position[1], position[2] ), - ::Triton::Vector3( diffuse[0], diffuse[1], diffuse[2] ) ); - - // Sun-based ambient value: - osg::Vec3d up = osg::Vec3d(0,0,0) * renderInfo.getCurrentCamera()->getInverseViewMatrix(); - up.normalize(); - osg::Vec3d pos3 = osg::Vec3d(position.x(), position.y(), position.z()); - pos3.normalize(); - float dot = osg::clampAbove(up*pos3, 0.0); dot*=dot; - float sunAmbient = (float)osg::clampBetween( dot, 0.0f, 0.88f ); - float fa = osg::maximum(sunAmbient, ambient[0]); - - // Ambient color based on the zenith color in the cube map - environment->SetAmbientLight( ::Triton::Vector3(fa, fa, fa) ); - } - - else - { - environment->SetDirectionalLight( ::Triton::Vector3(0,0,1), ::Triton::Vector3(1,1,1) ); - environment->SetAmbientLight( ::Triton::Vector3(0.88f, 0.88f, 0.88f) ); - } - - if ( _cubeMap.valid() ) - { - // Build transform from our cube map orientation space to native Triton orientation - // See worldToCubeMap function used in SkyBox to orient sky texture so that sky is up and earth is down - osg::Matrix m = osg::Matrix::rotate( osg::PI_2, osg::X_AXIS ); // = worldToCubeMap - - ::Triton::Matrix3 transformFromYUpToZUpCubeMapCoords( - m(0,0), m(0,1), m(0,2), - m(1,0), m(1,1), m(1,2), - m(2,0), m(2,1), m(2,2) ); - - // Grab the cube map from our sky box and give it to Triton to use as an _environment map - // GLenum texture = renderInfo.getState()->getLastAppliedTextureAttribute( _stage, osg::StateAttribute::TEXTURE ); - environment->SetEnvironmentMap( - (::Triton::TextureHandle)_cubeMap->getTextureObject(cid)->id(), - transformFromYUpToZUpCubeMapCoords ); - - if( _planarReflectionMap.valid() && _planarReflectionProjection.valid() ) - { - osg::Matrix & p = *_planarReflectionProjection; - - ::Triton::Matrix3 planarProjection( - p(0,0), p(0,1), p(0,2), - p(1,0), p(1,1), p(1,2), - p(2,0), p(2,1), p(2,2) ); - - environment->SetPlanarReflectionMap( - (::Triton::TextureHandle)_planarReflectionMap->getTextureObject(cid)->id(), - planarProjection, - 0.125 ); - } - } - - // Draw the ocean for the current time sample - if ( _TRITON->getOcean() ) - { - osg::GLExtensions* ext = osg::GLExtensions::Get(cid, true); - - bool writeDepth = true; - const osg::Depth* depth = static_cast(state->getLastAppliedAttribute(osg::StateAttribute::DEPTH)); - if (depth) - writeDepth = depth->getWriteMask(); - - double simTime = renderInfo.getView()->getFrameStamp()->getSimulationTime(); - simTime = fmod(simTime, 86400.0); - - _TRITON->getOcean()->Draw( - simTime, - writeDepth, // depth writes - true, // draw water - true, // draw particles - NULL, // optional context - tritonCam); - - } - } - - // Put GL back in a state that won't confuse the OSG state tracking: - state->dirtyAllVertexArrays(); - state->dirtyAllAttributes(); - state->dirtyAllModes(); - -#ifndef OSG_GL_FIXED_FUNCTION_AVAILABLE - // Keep OSG from reapplying GL_LIGHTING on next state change after dirtyAllModes(). - state->setModeValidity(GL_LIGHTING, false); -#endif - - // Keep an eye on this. - // I had to remove something similar in another module (Rex engine) because it was causing - // positional attributes (like clip planes) to re-apply with an incorrect MVM. -gw - state->apply(); -} diff --git a/src/scene/TritonDrawable.h b/src/scene/TritonDrawable.h deleted file mode 100644 index 95f28727..00000000 --- a/src/scene/TritonDrawable.h +++ /dev/null @@ -1,102 +0,0 @@ -/* -*-c++-*- */ -/* osgEarth - Geospatial SDK for OpenSceneGraph - * Copyright 2020 Pelican Mapping - * http://osgearth.org - * - * osgEarth is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see - */ -#ifndef OSGEARTH_TRITON_DRAWABLE_H -#define OSGEARTH_TRITON_DRAWABLE_H - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -const unsigned int TRITON_OCEAN_MASK = 0x4; // 0100 - -namespace osgEarth { namespace Triton -{ - class TritonContext; - class TritonHeightMap; - - /** - * Custom drawable for rendering the Triton ocean effects - */ - class TritonDrawable : public osg::Drawable - { - public: - TritonDrawable(TritonContext* TRITON); - - //! Layer to use as an ocean rendering mask - void setMaskLayer(const osgEarth::ImageLayer* maskLayer); - - //! Height map generator to use to mask out the ocean where the - //! terrain has positive elevation - void setHeightMapGenerator(TritonHeightMap* heightMap); - - //! Vertical datum to use to calculate sea level - void setVerticalDatum(VerticalDatum* value) { - _verticalDatum = value; - } - - //! Gets the Triton Camera associated with an osg Camera - ::Triton::Camera* getTritonCam(const osg::Camera* cam) { - return _local.get(cam)._tritonCam; - } - - void setPlanarReflectionMap(osg::Texture2D* map); - - void setPlanarReflectionProjection(osg::RefMatrix* proj); - - public: // osg::Drawable - - void drawImplementation(osg::RenderInfo& ri) const override; - - osg::BoundingBox computeBoundingBox() const override; - - protected: - virtual ~TritonDrawable(); - - osg::observer_ptr _TRITON; - osg::observer_ptr _maskLayer; - osg::ref_ptr _cubeMap; - - osg::ref_ptr _planarReflectionMap; - osg::ref_ptr _planarReflectionProjection; - - mutable osg::ref_ptr _heightMapGenerator; - - osg::ref_ptr _verticalDatum; - osg::ref_ptr _wgs84, _ecef; - - mutable osg::buffered_object _adapters; - - struct CameraLocal - { - ::Triton::Camera* _tritonCam = nullptr; - }; - mutable PerObjectFastMap _local; - }; - -} } // namespace osgEarth::Triton - -#endif // OSGEARTH_TRITON_DRAWABLE_H diff --git a/src/scene/TritonHeightMap.cpp b/src/scene/TritonHeightMap.cpp deleted file mode 100644 index c0057d7a..00000000 --- a/src/scene/TritonHeightMap.cpp +++ /dev/null @@ -1,434 +0,0 @@ -/* -*-c++-*- */ -/* osgEarth - Geospatial SDK for OpenSceneGraph - * Copyright 2020 Pelican Mapping - * http://osgearth.org - * - * osgEarth is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see - */ -#include "TritonHeightMap.h" -#include "TritonContext.h" -#include -#include -#include -#include - -#define LC "[TritonHeightMap] " - -using namespace osgEarth::Triton; - -namespace -{ - const char* vertexShader = - "#pragma import_defines(OE_TRITON_MASK_MATRIX);\n" - - "// terrain SDK:\n" - "float oe_terrain_getElevation(); \n" - - "out float oe_triton_elev;\n" - - "#ifdef OE_TRITON_MASK_MATRIX\n" - "out vec2 maskCoords;\n" - "uniform mat4 OE_TRITON_MASK_MATRIX;\n" - "vec4 oe_layer_tilec;\n" - "#endif\n" - - "void oe_triton_setupHeightMap(inout vec4 unused) \n" - "{ \n" - " oe_triton_elev = oe_terrain_getElevation(); \n" - "#ifdef OE_TRITON_MASK_MATRIX\n" - " maskCoords = (OE_TRITON_MASK_MATRIX * oe_layer_tilec).st;\n" - "#endif\n" - "} \n"; - - // The fragment shader simply takes the texture index that we generated - // in the vertex shader and does a texture lookup. In this case we're - // just wholesale replacing the color, so if the map had any existing - // imagery, this will overwrite it. - - const char* fragmentShader = - "#pragma import_defines(OE_TRITON_MASK_SAMPLER);\n" - - "in float oe_triton_elev;\n" - - "#ifdef OE_TRITON_MASK_SAMPLER\n" - "in vec2 maskCoords;\n" - "uniform sampler2D OE_TRITON_MASK_SAMPLER;\n" - "#endif\n" - - "out vec4 out_height; \n" - - "void oe_triton_drawHeightMap(inout vec4 unused) \n" - "{ \n" -#ifdef DEBUG_HEIGHTMAP - // Map to black = -500m, white = +500m - " float nHeight = clamp(oe_triton_elev / 1000.0 + 0.5, 0.0, 1.0);\n" -#else - " float nHeight = oe_triton_elev;\n" - - "#ifdef OE_TRITON_MASK_SAMPLER\n" - " float mask = texture(OE_TRITON_MASK_SAMPLER, maskCoords).a;\n" - " nHeight *= mask; \n" - "#endif\n" - -#endif - " out_height = vec4( nHeight, 0.0, 0.0, 1.0 ); \n" - "} \n"; - - struct TerrainDirtyCallback : public osgEarth::TerrainCallback - { - osg::observer_ptr _hm; - TerrainDirtyCallback(TritonHeightMap* hm) : _hm(hm) { } - void onTileUpdate(const osgEarth::TileKey&, osg::Node*, osgEarth::TerrainCallbackContext&) - { - osg::ref_ptr hm; - if (_hm.lock(hm)) - hm->dirty(); - } - }; -} - -TritonHeightMap::TritonHeightMap() : -_texSize(0u), -_internalFormat((GLint)0), -_sourceFormat((GLenum)0) -{ - setCullingActive(false); -} - -TritonHeightMap::~TritonHeightMap() -{ - osgEarth::TerrainEngineNode* t = dynamic_cast(_terrain.get()); - if (t) - { - t->getTerrain()->removeTerrainCallback(static_cast(_terrainCallback.get())); - _terrainCallback = NULL; - } -} - -void -TritonHeightMap::setTerrain(osg::Node* node) -{ - _terrain = node; - - osgEarth::TerrainEngineNode* t = dynamic_cast(node); - if (t) - { - TerrainDirtyCallback* cb = new TerrainDirtyCallback(this); - t->getTerrain()->addTerrainCallback(cb); - _terrainCallback = cb; - } -} - -void -TritonHeightMap::setMaskLayer(const osgEarth::ImageLayer* layer) -{ - _maskLayer = layer; -} - -void -TritonHeightMap::SetDirty::operator()(CameraLocal& local) -{ - local._mvpw.makeIdentity(); -} - -void -TritonHeightMap::dirty() -{ - SetDirty setDirty; - _local.forEach(setDirty); -} - -bool -TritonHeightMap::configure(unsigned texSize, osg::State& state) -{ - bool result = true; - - if (_texSize == 0u) - { - // first time through, single-lane and set up FBO parameters. - static std::mutex s_mutex; - std::lock_guard lock(s_mutex); - - if (_texSize == 0u) - { - _texSize = texSize; - if (!getBestFBOConfig(state, _internalFormat, _sourceFormat)) - { - result = false; - } - } - } - return result; -} - -namespace { - struct Format { - Format(GLint i, GLenum s, const std::string& n) : - internalFormat(i), sourceFormat(s), name(n) { } - GLint internalFormat; - GLenum sourceFormat; - std::string name; - }; -} - -bool -TritonHeightMap::getBestFBOConfig(osg::State& state, GLint& out_internalFormat, GLenum& out_sourceFormat) -{ -#ifdef GL_LUMINANCE_FLOAT16_ATI -# define GL_LUMINANCE_FLOAT16_ATI 0x881E -#endif - - std::vector formats; - -#ifdef GL_R16F - formats.push_back(Format(GL_R16F, GL_RED, "GL_R16F")); -#endif -#ifdef GL_LUMINANCE16F_ARB - formats.push_back(Format(GL_LUMINANCE16F_ARB, GL_LUMINANCE, "GL_LUMINANCE16F_ARB")); -#endif -#ifdef GL_LUMINANCE_FLOAT16_ATI - formats.push_back(Format(GL_LUMINANCE_FLOAT16_ATI, GL_LUMINANCE, "GL_LUMINANCE_FLOAT16_ATI")); -#endif -#ifdef GL_R32F - formats.push_back(Format(GL_R32F, GL_RED, "GL_R32F")); -#endif -#ifdef GL_LUMINANCE32F_ARB - formats.push_back(Format(GL_LUMINANCE32F_ARB, GL_LUMINANCE, "GL_LUMINANCE32F_ARB")); -#endif -#ifdef GL_RGB16F_ARB - formats.push_back(Format(GL_RGB16F_ARB, GL_RGB, "GL_RGB16F_ARB")); -#endif -#ifdef GL_RGBA16F_ARB - formats.push_back(Format(GL_RGBA16F_ARB, GL_RGBA, "GL_RGBA16F_ARB")); -#endif -#ifdef GL_RGB32F_ARB - formats.push_back(Format(GL_RGB32F_ARB, GL_RGB, "GL_RGB32F_ARB")); -#endif -#ifdef GL_RGBA32F_ARB - formats.push_back(Format(GL_RGBA32F_ARB, GL_RGBA, "GL_RGBA32F_ARB")); -#endif - - - auto cid = GLUtils::getSharedContextID(state); - osg::GLExtensions* ext = osg::GLExtensions::Get(cid, true); - - osg::State::CheckForGLErrors check = state.getCheckForGLErrors(); - state.setCheckForGLErrors(state.NEVER_CHECK_GL_ERRORS); - - bool found = false; - - for(int i=0; i tex = new osg::Texture2D(); - tex->setTextureSize(1, 1); - tex->setInternalFormat( format.internalFormat ); - tex->setSourceFormat ( format.sourceFormat ); - - osg::ref_ptr fbo = new osg::FrameBufferObject(); - fbo->setAttachment( osg::Camera::COLOR_BUFFER0, osg::FrameBufferAttachment(tex.get()) ); - - fbo->apply( state ); - - GLenum status = ext->glCheckFramebufferStatus(GL_FRAMEBUFFER_EXT); - - fbo->releaseGLObjects( &state ); - tex->releaseGLObjects( &state ); - - if ( status == GL_FRAMEBUFFER_COMPLETE_EXT ) - { - out_internalFormat = format.internalFormat; - out_sourceFormat = format.sourceFormat; - found = true; - } - } - - state.setCheckForGLErrors(check); - - return found; -} - -bool -TritonHeightMap::isConfigurationComplete() const -{ - return - _texSize > 0u && - _internalFormat != (GLint)0 && - _sourceFormat != (GLenum)0; -} - -void -TritonHeightMap::setup(CameraLocal& local, const std::string& name) -{ - // make sure the FBO params are configured: - if (!isConfigurationComplete()) - return; - - local._frameNum = 0u; - - local._tex = new osg::Texture2D(); - local._tex->setName(Stringify() << "Triton HM (" << name << ")"); - local._tex->setTextureSize(_texSize, _texSize); - local._tex->setInternalFormat( _internalFormat ); - local._tex->setSourceFormat( _sourceFormat ); - local._tex->setFilter(osg::Texture2D::MIN_FILTER, osg::Texture2D::LINEAR); - local._tex->setFilter(osg::Texture2D::MAG_FILTER, osg::Texture2D::LINEAR); - - // Triton prob doesn't need this but it's good practice - if (_sourceFormat == GL_RED) - { - local._tex->setSwizzle(osg::Vec4i(GL_RED, GL_RED, GL_RED, GL_ONE)); - } - - local._rtt = new osg::Camera(); - local._rtt->setName(local._tex->getName()); - local._rtt->setReferenceFrame(osg::Transform::ABSOLUTE_RF_INHERIT_VIEWPOINT); - local._rtt->setClearMask(GL_COLOR_BUFFER_BIT); //GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); - local._rtt->setClearColor(osg::Vec4(-1000.0, -1000.0, -1000.0, 1.0f)); - local._rtt->setViewport(0, 0, _texSize, _texSize); - local._rtt->setRenderOrder(osg::Camera::PRE_RENDER); - local._rtt->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT); - local._rtt->setImplicitBufferAttachmentMask(0, 0); - local._rtt->attach(osg::Camera::COLOR_BUFFER0, local._tex.get()); - //local._rtt->setCullMask( ~TRITON_OCEAN_MASK ); - local._rtt->setAllowEventFocus(false); - local._rtt->setDrawBuffer(GL_FRONT); - local._rtt->setReadBuffer(GL_FRONT); - local._rtt->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR); - - // TODO: create this once and just re-use it for all RTT cameras - osg::StateSet* rttSS = local._rtt->getOrCreateStateSet(); - - osgEarth::VirtualProgram* rttVP = osgEarth::VirtualProgram::getOrCreate(rttSS); - rttVP->setName("Triton Height Map"); - rttVP->setFunction( "oe_triton_setupHeightMap", vertexShader, VirtualProgram::LOCATION_VERTEX_MODEL); - rttVP->setFunction( "oe_triton_drawHeightMap", fragmentShader, VirtualProgram::LOCATION_FRAGMENT_OUTPUT); - rttVP->setInheritShaders(false); - - osg::StateAttribute::OverrideValue off = osg::StateAttribute::OFF | osg::StateAttribute::OVERRIDE; - rttSS->setDefine("OE_IS_DEPTH_CAMERA"); - rttSS->setDefine("OE_TERRAIN_RENDER_IMAGERY", off); - rttSS->setDefine("OE_TERRAIN_RENDER_NORMAL_MAP", off); - rttSS->setDefine("OE_TERRAIN_BLEND_IMAGERY", off); - rttSS->setDefine("OE_TERRAIN_MORPH_GEOMETRY", off); - - osg::ref_ptr maskLayer; - if (_maskLayer.lock(maskLayer)) - { - rttSS->setDefine("OE_TRITON_MASK_SAMPLER", maskLayer->getSharedTextureUniformName()); - rttSS->setDefine("OE_TRITON_MASK_MATRIX", maskLayer->getSharedTextureMatrixUniformName()); - OE_DEBUG << LC << "Using mask layer \"" << maskLayer->getName() << "\", sampler=" << maskLayer->getSharedTextureUniformName() << ", matrix=" << maskLayer->getSharedTextureMatrixUniformName() << std::endl; - } - - if (_terrain.valid()) - { - local._rtt->addChild(_terrain.get()); - } - else - { - OE_WARN << LC << "Illegal: no terrain set (must call setTerrain)" << std::endl; - } -} - -#define MAXABS4(A,B,C,D) \ - osg::maximum(fabs(A), osg::maximum(fabs(B), osg::maximum(fabs(C),fabs(D)))) - -void -TritonHeightMap::update(CameraLocal& local, const osg::Camera* cam, osgEarth::Horizon* horizon) -{ - osg::Vec3d eye = osg::Vec3d(0,0,0) * cam->getInverseViewMatrix(); - - double hd = horizon->getDistanceToVisibleHorizon(); - - local._rtt->setProjectionMatrix(osg::Matrix::ortho(-hd, hd, -hd, hd, 1.0, eye.length())); - local._rtt->setViewMatrixAsLookAt(eye, osg::Vec3d(0.0,0.0,0.0), osg::Vec3d(0.0,0.0,1.0)); - - static const osg::Matrixd scaleBias( - 0.5, 0.0, 0.0, 0.0, - 0.0, 0.5, 0.0, 0.0, - 0.0, 0.0, 0.5, 0.0, - 0.5, 0.5, 0.5, 1.0); - - // Matrix that Triton will use to position the heightmap for sampling. - local._texMatrix = local._rtt->getViewMatrix() * local._rtt->getProjectionMatrix() * scaleBias; -} - -void -TritonHeightMap::traverse(osg::NodeVisitor& nv) -{ - if (nv.getVisitorType() == nv.CULL_VISITOR) - { - osgUtil::CullVisitor* cv = osgEarth::Culling::asCullVisitor(nv); - const osg::Camera* camera = cv->getCurrentCamera(); - if (camera) - { - CameraLocal& local = _local.get(camera); - - if (isConfigurationComplete()) - { - // create the RTT for this camera on first encounter: - if (!local._rtt.valid()) - { - setup(local, camera->getName()); - } - - // only update when the MVPW changes. - if (local._mvpw != *cv->getMVPW()) - { - // update the RTT based on the current camera: - osg::ref_ptr horizon; - ObjectStorage::get(&nv, horizon); - update(local, camera, horizon); - - // finally, traverse the camera to build the height map. - local._rtt->accept(nv); - - local._frameNum = nv.getFrameStamp()->getFrameNumber(); - local._mvpw = *cv->getMVPW(); - } - } - else - { - //OE_DEBUG << LC << "Configuration not yet complete..." << std::endl; - } - } - } -} - -bool -TritonHeightMap::getTextureAndMatrix(osg::RenderInfo& ri, GLint& out_texName, osg::Matrix& out_matrix) -{ - if (!isConfigurationComplete()) - return false; - - CameraLocal& local = _local.get(ri.getCurrentCamera()); - if (!local._tex.valid()) - return false; - - // did the texture change? - //OE_DEBUG << "FN=" << ri.getState()->getFrameStamp()->getFrameNumber() << "; localFN=" << local._frameNum << std::endl; - - if (ri.getState()->getFrameStamp()->getFrameNumber() > local._frameNum) - return false; - - auto cid = GLUtils::getSharedContextID(*ri.getState()); - osg::Texture::TextureObject* obj = local._tex->getTextureObject(cid); - if (!obj) - return false; - - out_texName = obj->id(); - out_matrix = local._texMatrix; - return true; -} diff --git a/src/scene/TritonHeightMap.h b/src/scene/TritonHeightMap.h deleted file mode 100644 index b7896a7f..00000000 --- a/src/scene/TritonHeightMap.h +++ /dev/null @@ -1,109 +0,0 @@ -/* -*-c++-*- */ -/* osgEarth - Geospatial SDK for OpenSceneGraph - * Copyright 2020 Pelican Mapping - * http://osgearth.org - * - * osgEarth is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see - */ -#ifndef OSGEARTH_TRITON_HEIGHT_MAP -#define OSGEARTH_TRITON_HEIGHT_MAP 1 - -#include -#include -#include -#include -#include - -namespace osgEarth { - class Horizon; -} - -namespace osgEarth { namespace Triton -{ - /** - * Creates a height map that Triton can use to mask out the ocean where - * the terrain is above sea level. - */ - class TritonHeightMap : public osg::Node - { - public: - - TritonHeightMap(); - - //! Sets the root of the terrain scene graph - void setTerrain(osg::Node*); - - //! Sets the masking layer - void setMaskLayer(const osgEarth::ImageLayer* layer); - - //! Configure the generator; return success t/f - bool configure(unsigned texSize, osg::State& state); - - //! Fetch the heightmap texture and matrix generated for a camera. - bool getTextureAndMatrix(osg::RenderInfo&, GLint& out_texName, osg::Matrix& out_matrix); - - //! Mark all height maps (for all cameras) for regeneration - void dirty(); - - public: // osg::Node - - void traverse(osg::NodeVisitor&); - - protected: - - virtual ~TritonHeightMap(); - - private: - - struct CameraLocal - { - osg::ref_ptr _rtt; - osg::ref_ptr _tex; - osg::Matrix _texMatrix; - osg::Matrix _mvpw; - unsigned _frameNum; - }; - - typedef osgEarth::PerObjectFastMap Locals; - - struct SetDirty : public Locals::Functor - { - void operator()(CameraLocal&); - }; - - //! Sets up an RTT camera for the first time - void setup(CameraLocal& local, const std::string& name); - - //! Updates an RTT camera for the new view/projection matrices of the camera - void update(CameraLocal& local, const osg::Camera*, osgEarth::Horizon*); - - //! Whether FBO configuration has happened yet - bool isConfigurationComplete() const; - - //! Figures out the best FBO format on this GPU - static bool getBestFBOConfig(osg::State& state, GLint& internalFormat, GLenum& sourceFormat); - - - Locals _local; - osg::observer_ptr _terrain; - unsigned _texSize; - GLint _internalFormat; - GLenum _sourceFormat; - osg::observer_ptr _maskLayer; - osg::ref_ptr _terrainCallback; - }; - -} } // namespace osgEarth::Triton - -#endif // OSGEARTH_TRITON_HEIGHT_MAP diff --git a/src/scene/TritonIntersections.cpp b/src/scene/TritonIntersections.cpp deleted file mode 100644 index 727dbd64..00000000 --- a/src/scene/TritonIntersections.cpp +++ /dev/null @@ -1,51 +0,0 @@ -/* -*-c++-*- */ -/* osgEarth - Geospatial SDK for OpenSceneGraph - * Copyright 2020 Pelican Mapping - * http://osgearth.org - * - * osgEarth is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see - */ -#include "TritonIntersections.h" - -using namespace osgEarth; -using namespace osgEarth::Triton; - -TritonIntersections::TritonIntersections() : -_maxRange(1.0, Units::KILOMETERS) -{ -} - -void -TritonIntersections::setAnchor(const GeoPoint& value) -{ - _anchor = value; - - // zero out the other stuff: - _anchor.z() = 0.0; - _anchor.altitudeMode() = ALTMODE_ABSOLUTE; -} - -void -TritonIntersections::addLocalPoint(const osg::Vec3d& p) -{ - _input.push_back(p); - _heights.resize(_input.size()); - _normals.resize(_input.size()); -} - -void -TritonIntersections::setMaxRange(const Distance& range) -{ - _maxRange = range; -} diff --git a/src/scene/TritonIntersections.h b/src/scene/TritonIntersections.h deleted file mode 100644 index de35c76a..00000000 --- a/src/scene/TritonIntersections.h +++ /dev/null @@ -1,72 +0,0 @@ -/* -*-c++-*- */ -/* osgEarth - Geospatial SDK for OpenSceneGraph - * Copyright 2020 Pelican Mapping - * http://osgearth.org - * - * osgEarth is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see - */ -#ifndef OSGEARTH_TRITON_INTERSECTIONS -#define OSGEARTH_TRITON_INTERSECTIONS 1 - -#include -#include -#include "TritonCallback.h" - -namespace osgEarth { namespace Triton -{ - /** - * Pass this structure to TritonLayer and it will automatically - * populate the results with ocean wave intersections (local coordinates - * and normals.) - */ - class TritonIntersections : public osg::Referenced - { - public: - //! Construct an empty set - TritonIntersections(); - - //! Anchor point for intersectsions in this set. Only the X and Y - //! components are used. Any local points you add to this set will - //! be in the local coordinate system (LTP) around this anchor point. - void setAnchor(const GeoPoint& p); - - //! Adds a point to the intersection set. The point should be in the - //! local coordinate system of the anchor point. - void addLocalPoint(const osg::Vec3d& p); - - //! Maximum range at which to perform intersections. Beyond this - //! range Triton will skip this set. Default is 2km. - void setMaxRange(const Distance& value); - const Distance& getMaxRange() const { return _maxRange; } - - //! Vector of input local points added by addLocalPoint. - const std::vector& getInput() const { return _input; } - - //! Vector of heights resulting from the intersection tests. - const std::vector& getHeights() const { return _heights; } - - //! Vector of normals resulting from the intersection tests. - const std::vector& getNormals() const { return _normals; } - - private: - GeoPoint _anchor; - std::vector _input; - std::vector _heights; - std::vector _normals; - Distance _maxRange; - friend class TritonLayerNode; - }; -} } - -#endif // OSGEARTH_TRITON_INTERSECTIONS diff --git a/src/scene/TritonLayer.cpp b/src/scene/TritonLayer.cpp deleted file mode 100644 index 5c5092b9..00000000 --- a/src/scene/TritonLayer.cpp +++ /dev/null @@ -1,386 +0,0 @@ -/* -*-c++-*- */ -/* osgEarth - Geospatial SDK for OpenSceneGraph - * Copyright 2020 Pelican Mapping - * http://osgearth.org - * - * osgEarth is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see - */ -#include "TritonLayer.h" -#include "TritonContext.h" -#include "TritonDrawable.h" -#include "TritonHeightMap.h" -#include "TritonCallback.h" - -#include -#include -#include -#include -#include -#include - -#include - -#define LC "[TritonLayer] " - -using namespace osgEarth::Triton; - -namespace osgEarth { namespace Triton -{ - class TritonLayerNode : public osg::Group - { - public: - TritonLayerNode(osgEarth::Triton::TritonLayer* layer, - LayerReference& mask) : - _tritonLayer(layer), - _maskLayer(mask), - _callback(0L), - _needsMapNode(true) - { - // To detect the map node: - ADJUST_UPDATE_TRAV_COUNT(this, +1); - - // Disable bounds culling - setCullingActive(false); - } - - ~TritonLayerNode() - { - //nop - } - - void setUserCallback(osgEarth::Triton::Callback* callback) - { - _callback = callback; - } - - void dirty() - { - create(); - } - - /** MapNode to use; will be discovered automatically if not set here */ - void setMapNode(osgEarth::MapNode* mapNode) - { - if (!mapNode) - { - this->removeChildren(0, this->getNumChildren()); - _drawable = 0L; - _TRITON = 0L; - _needsMapNode = true; - } - else - { - _mapNode = mapNode; - create(); - } - } - - void create() - { - this->removeChildren(0, this->getNumChildren()); - _drawable = 0L; - - osg::ref_ptr mapNode; - if (!_mapNode.lock(mapNode)) - return; - - const osgEarth::Map* map = mapNode->getMap(); - - // create an object to house Triton data and resources. - if (!_TRITON.valid()) - _TRITON = new TritonContext(_tritonLayer->options()); - - if (map) - _TRITON->setSRS(map->getSRS()); - - if (_callback.valid()) - _TRITON->setCallback(_callback.get()); - - TritonDrawable* drawable = new TritonDrawable(_TRITON.get()); - _drawable = drawable; - _drawable->setNodeMask(TRITON_OCEAN_MASK); - drawable->setMaskLayer(_maskLayer.getLayer()); - this->addChild(_drawable); - - // Place in the depth-sorted bin and set a rendering order. - // We want Triton to render after the terrain. - _drawable->getOrCreateStateSet()->setRenderBinDetails( - _tritonLayer->getRenderBinNumber(), - "DepthSortedBin"); - - // Install a vdatum for sea level calculations: - auto vdatum = VerticalDatum::get(_tritonLayer->options().vdatum().value()); - if (vdatum) - drawable->setVerticalDatum(vdatum); - - // If the user requested a height map, install it now. - // Configuration of the height map generator will take place later when - // we have a valid graphics context. - if (_tritonLayer->getUseHeightMap() == true) - { - TritonHeightMap* heightMapGen = new TritonHeightMap(); - heightMapGen->setTerrain(mapNode->getTerrainEngine()->getNode()); - if (_maskLayer.getLayer()) - heightMapGen->setMaskLayer(_maskLayer.getLayer()); - this->addChild(heightMapGen); - drawable->setHeightMapGenerator(heightMapGen); - } - } - - void traverse(osg::NodeVisitor& nv) - { - if (nv.getVisitorType() == nv.UPDATE_VISITOR) - { - // Find a MapNode in the traversal path if necessary: - if (_needsMapNode) - { - osgEarth::MapNode* mapNode = osgEarth::findInNodePath(nv); - if (mapNode) - { - setMapNode(mapNode); - _needsMapNode = false; - ADJUST_UPDATE_TRAV_COUNT(this, -1); - } - } - } - - else if (nv.getVisitorType() == nv.CULL_VISITOR && _drawable && _TRITON.valid() && _TRITON->getOcean()) - { - // Update any intersections. - // For now this is running in the CULL traversal, which is not ideal. - // However the Triton Ocean::GetHeight method requires a pointer to the Triton "camera" - // and under our framework this is only available in CULL or DRAW. - // Running the intersection in eithe CULL or DRAW will result in a frame - // incoherency w.r.t the Triton update() call that updates the ocean state. - ::Triton::Ocean* ocean = _TRITON->getOcean(); - - // Find the TritonCam associated with this osg Cam - osgUtil::CullVisitor* cv = dynamic_cast(&nv); - ::Triton::Camera* tritonCam = static_cast(_drawable)->getTritonCam(cv->getCurrentCamera()); - - osg::Vec3d eye = osg::Vec3d(0,0,0) * cv->getCurrentCamera()->getInverseViewMatrix(); - - for(std::vector >::iterator i = _isect.begin(); - i != _isect.end(); - ++i) - { - TritonIntersections* ir = i->get(); - - // allocate enough space for the output: - ir->_input.resize(ir->_input.size()); - ir->_normals.resize(ir->_input.size()); - - osg::Matrix local2world; - ir->_anchor.createLocalToWorld(local2world); - - // Make sure it's in range so as not to waste cycles: - osg::Vec3d anchor = osg::Vec3d(0,0,0) * local2world; - double m = ir->getMaxRange().as(Units::METERS); - if ((eye-anchor).length2() > (m)) - { - continue; - } - - osg::Matrix world2local; - world2local.invert(local2world); - - for(unsigned i=0; i_input.size(); ++i) - { - const osg::Vec3d& local = ir->_input[i]; - - // transform the ray to world coordinates - osg::Vec3d start = local * local2world; - osg::Vec3d dir = osg::Matrix::transform3x3(local2world, osg::Vec3d(0,0,1)); - - // intersect the ocean - float& out_height = ir->_heights[i]; - ::Triton::Vector3 out_normalT; - - bool ok = ocean->GetHeight( - ::Triton::Vector3(start.x(), start.y(), start.z()), - ::Triton::Vector3(dir.x(), dir.y(), dir.z()), - out_height, - out_normalT, - true, // visualCorrelation - true, // includeWakes - true, // highResolution - true, // threadSafe, - 0L, // intersectionPoint, - true, // autoFlip - tritonCam); - - if (ok) - { - // populate the output data in local coordinates - osg::Vec3d& normal = ir->_normals[i]; - normal.set(out_normalT.x, out_normalT.y, out_normalT.z); - normal = osg::Matrix::transform3x3(normal, world2local); - } - else - { - // todo...what? - OE_WARN << "GetHeight returned false dude" << std::endl; - } - } - } - } - - osg::Group::traverse(nv); - } - - osg::ref_ptr _TRITON; - osg::Drawable* _drawable; - LayerReference& _maskLayer; - osg::observer_ptr _mapNode; - osg::observer_ptr _tritonLayer; - osg::ref_ptr _callback; - bool _needsMapNode; - std::vector > _isect; - - }; -} } - -//........................................................................ - -void -TritonLayer::Options::fromConfig(const osgEarth::Config& conf) -{ - conf.get("user", _user); - conf.get("license_code", _licenseCode); - conf.get("resource_path", _resourcePath); - conf.get("use_height_map", _useHeightMap); - conf.get("height_map_size", _heightMapSize); - conf.get("render_bin_number", _renderBinNumber); - conf.get("max_altitude", _maxAltitude); - conf.get("vdatum", vdatum()); - maskLayer().get(conf, "mask_layer"); -} - -osgEarth::Config -TritonLayer::Options::getConfig() const -{ - osgEarth::Config conf = osgEarth::VisibleLayer::Options::getConfig(); - conf.set("user", _user); - conf.set("license_code", _licenseCode); - conf.set("resource_path", _resourcePath); - conf.set("use_height_map", _useHeightMap); - conf.set("height_map_size", _heightMapSize); - conf.set("render_bin_number", _renderBinNumber); - conf.set("max_altitude", _maxAltitude); - conf.set("vdatum", vdatum()); - maskLayer().set(conf, "mask_layer"); - - return conf; -} - -//........................................................................ - -/** Register this layer so it can be used in an earth file */ -namespace osgEarth { namespace Triton -{ - REGISTER_OSGEARTH_LAYER(triton, TritonLayer); - REGISTER_OSGEARTH_LAYER(triton_ocean, TritonLayer); -} } - -OE_LAYER_PROPERTY_IMPL(TritonLayer, std::string, UserName, user); -OE_LAYER_PROPERTY_IMPL(TritonLayer, std::string, LicenseCode, licenseCode); -OE_LAYER_PROPERTY_IMPL(TritonLayer, std::string, ResourcePath, resourcePath); -OE_LAYER_PROPERTY_IMPL(TritonLayer, bool, UseHeightMap, useHeightMap); -OE_LAYER_PROPERTY_IMPL(TritonLayer, unsigned, HeightMapSize, heightMapSize); -OE_LAYER_PROPERTY_IMPL(TritonLayer, int, RenderBinNumber, renderBinNumber); -OE_LAYER_PROPERTY_IMPL(TritonLayer, float, MaxAltitude, maxAltitude); -OE_LAYER_PROPERTY_IMPL(TritonLayer, std::string, VerticalDatum, vdatum); - -void -TritonLayer::init() -{ - super::init(); - - _seaLevel = 0.0f; - - // Trick to force the VisibleLayer to install its opacity shader, - // which a modified Triton user-functions.glsl shader needs in order to control - // sea surface opacity. - float opacity = getOpacity(); - setOpacity(0.0f); - setOpacity(opacity); - - this->setName("Triton"); - setRenderType(RENDERTYPE_CUSTOM); - - ElevationLOD* lod = new ElevationLOD(); - _root = lod; - if (options().maxAltitude().isSet()) - { - OE_DEBUG << LC << "Setting max altitude = " << options().maxAltitude().get() << std::endl; - lod->setMaxElevation(options().maxAltitude().get()); - } - - _tritonNode = new TritonLayerNode(this, options().maskLayer()); - _root->addChild(_tritonNode.get()); -} - -void -TritonLayer::setUserCallback(Callback* callback) -{ - static_cast(_tritonNode.get())->setUserCallback(callback); -} - -osg::Node* -TritonLayer::getNode() const -{ - return _root.get(); -} - -void -TritonLayer::setMaskLayer(osgEarth::ImageLayer* maskLayer) -{ - options().maskLayer().setLayer(maskLayer); - static_cast(_tritonNode.get())->dirty(); -} - -osgEarth::ImageLayer* -TritonLayer::getMaskLayer() const -{ - return options().maskLayer().getLayer(); -} - -void -TritonLayer::addedToMap(const osgEarth::Map* map) -{ - VisibleLayer::addedToMap(map); - options().maskLayer().addedToMap(map); -} - -void -TritonLayer::removedFromMap(const osgEarth::Map* map) -{ - VisibleLayer::removedFromMap(map); - options().maskLayer().removedFromMap(map); - setMaskLayer(0L); -} - -void -TritonLayer::addIntersections(TritonIntersections* value) -{ - TritonLayerNode* node = static_cast(_tritonNode.get()); - node->_isect.push_back(value); -} - -osgEarth::Config -TritonLayer::getConfig() const -{ - osgEarth::Config c = osgEarth::VisibleLayer::getConfig(); - return c; -} diff --git a/src/scene/TritonLayer.h b/src/scene/TritonLayer.h deleted file mode 100644 index d5b6cd0c..00000000 --- a/src/scene/TritonLayer.h +++ /dev/null @@ -1,125 +0,0 @@ -/* -*-c++-*- */ -/* osgEarth - Geospatial SDK for OpenSceneGraph - * Copyright 2020 Pelican Mapping - * http://osgearth.org - * - * osgEarth is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see - */ -#ifndef OSGEARTH_TRITON_LAYER -#define OSGEARTH_TRITON_LAYER 1 - -#include -#include -#include -#include "TritonCallback.h" -#include "TritonIntersections.h" - -namespace osgEarth { namespace Triton -{ - /** - * Node that roots the Triton adapter. - */ - class TritonLayer : public osgEarth::VisibleLayer - { - public: - class Options : public osgEarth::VisibleLayer::Options { - public: - META_LayerOptions(osgEarth, Options, osgEarth::VisibleLayer::Options); - OE_OPTION(std::string, user); - OE_OPTION(std::string, licenseCode); - OE_OPTION(std::string, resourcePath); - OE_OPTION(bool, useHeightMap, true); - OE_OPTION(unsigned, heightMapSize, 1024); - OE_OPTION(int, renderBinNumber, 12); - OE_OPTION(float, maxAltitude, 50000.0f); - OE_OPTION(std::string, vdatum, "egm96"); - OE_OPTION_LAYER(osgEarth::ImageLayer, maskLayer); - virtual Config getConfig() const; - private: - void fromConfig(const Config& conf); - }; - - public: - META_Layer(osgEarth, TritonLayer, Options, osgEarth::VisibleLayer, triton); - - //! Sets the user callback that's invoked when Triton start up - void setUserCallback(Triton::Callback* callback); - - //! User name for license - void setUserName(const std::string& value); - const std::string& getUserName() const; - - //! License code - void setLicenseCode(const std::string& value); - const std::string& getLicenseCode() const; - - //! Triton resource path - void setResourcePath(const std::string& value); - const std::string& getResourcePath() const; - - //! Whether to use a height map to fade out the ocean at the coastline - void setUseHeightMap(const bool& value); - const bool& getUseHeightMap() const; - - //! Size in texels of the height map (each dimension) - void setHeightMapSize(const unsigned& value); - const unsigned& getHeightMapSize() const; - - //! Render bin number to use for the ocean rendering - void setRenderBinNumber(const int& value); - const int& getRenderBinNumber() const; - - //! Masking layer for the ocean - void setMaskLayer(osgEarth::ImageLayer* maskLayer); - osgEarth::ImageLayer* getMaskLayer() const; - - //! Maximum visibility altitude - void setMaxAltitude(const float& value); - const float& getMaxAltitude() const; - - //! Vertical datum to use to calculate sea level - void setVerticalDatum(const std::string& value); - const std::string& getVerticalDatum() const; - - //! Adds an intersection set. - //! Each frame, Triton will perform intersections against the ocean surface - //! (including the waves) and populate the set with the results. - void addIntersections(TritonIntersections*); - - public: // Layer - - virtual osg::Node* getNode() const; - - //! Serialize - virtual Config getConfig() const; - - protected: // Layer - - virtual void init(); - - virtual void addedToMap(const class osgEarth::Map*); - - virtual void removedFromMap(const class osgEarth::Map*); - - private: - - osg::ref_ptr _root; - osg::ref_ptr _tritonNode; - float _seaLevel; - float _opacity; - }; - -} } // namespace osgEarth::Triton - -#endif // OSGEARTH_TRITON_LAYER diff --git a/src/scene/ui/CompositeHandle.cpp b/src/scene/ui/CompositeHandle.cpp index de85ae1d..3a62fca5 100644 --- a/src/scene/ui/CompositeHandle.cpp +++ b/src/scene/ui/CompositeHandle.cpp @@ -3,151 +3,23 @@ #include -CompositeHandle::CompositeHandle(CompositeWidgetManager* cw) :_cw(cw), -_operate(cw->GetcanvasO()), -_N(cw->GetcanvasN()), -_light(cw->GetcanvasFX()), -_background(cw->GetcanvasBackGround()), -_num(0), -_move(false) +CompositeHandle::CompositeHandle(CompositeWidgetManager* cw) + : _cw(cw), + _operate(cw->GetcanvasO()), + _N(cw->GetcanvasN()), + _light(cw->GetcanvasFX()), + _background(cw->GetcanvasBackGround()), + _num(0), + _move(false) { } -CompositeHandle::~CompositeHandle(void) -{ -} - - bool CompositeHandle::handle(const osgGA::GUIEventAdapter&ea, osgGA::GUIActionAdapter& aa) { - if (_num != 0) - { - _cw->_local_y = sin(_angle); - _cw->_local_x = cos(_angle); - - _angle = _angle + _num; - _cw->SendPosition(); - - if ((_num >= 0 && _angle >= osg::PI_2) || (_num < 0 && _angle < osg::PI_2)) - { - _cw->_local_y = sin(osg::PI_2); - _cw->_local_x = cos(osg::PI_2); - - _cw->SendPosition(); - - _num = 0; - _cw->_autoHome = false; - _cw->_N = false; - } - return false; + if (ea.getEventType() == osgGA::GUIEventAdapter::FRAME) { + } - else - { - switch (ea.getEventType()) - { - case osgGA::GUIEventAdapter::DRAG: - { - if (_cw->_state == CompositeWidgetManager::MOUSE_DRAG) - { - _cw->SendPosition(); - } - break; - } - case osgGA::GUIEventAdapter::PUSH: - { - _cw->_N = false; + // compass_->update_(); - break; - } - case osgGA::GUIEventAdapter::DOUBLECLICK: - { - if (_cw->_N == true) - { - _num = (45 - _N->getRotate())*osg::PI / (100 * 180); - - if (_num != 0) - { - _angle = (_N->getRotate() - 45)*osg::PI / 180 + osg::PI_2; - - _cw->_autoHome = true; - } - return true; - } - else if (ea.getX() >= _cw->_center_x - 42 && - ea.getX() < _cw->_center_x + 42 && - ea.getY() > _cw->_center_y - 42 && - ea.getY() < _cw->_center_y + 42) - { - return true; - } - - break; - } - default: - break; - } - - switch (_cw->_state) - { - case CompositeWidgetManager::MOUSE_PUSH: - { - if (_cw->_N != true || _cw->_autoHome == false) - { - _cw->SendPosition(); - - if (_cw->_local_y < 0) - { - if (_cw->_local_x > 0) - { - _light->setRotate(45 - (180 - 90 * asinf(_cw->_local_x / sqrtf(_cw->_local_x*_cw->_local_x + _cw->_local_y*_cw->_local_y)) / osg::PI_2)); - } - else - { - _light->setRotate(45 - (-180 - 90 * asinf(_cw->_local_x / sqrtf(_cw->_local_x*_cw->_local_x + _cw->_local_y*_cw->_local_y)) / osg::PI_2)); - } - } - else - { - _light->setRotate(45 - 90 * asinf(_cw->_local_x / sqrtf(_cw->_local_x*_cw->_local_x + _cw->_local_y*_cw->_local_y)) / osg::PI_2); - } - - _light->getByName("light")->setColor(1, 1, 1, 0.5); - _light->resize(); - } - break; - } - case CompositeWidgetManager::MOUSE_RELEASE: - { - _cw->_state = CompositeWidgetManager::DEFAULT; - - _light->getByName("light")->setColor(1, 1, 1, 0); - break; - } - case CompositeWidgetManager::MOUSE_DRAG: - { - break; - } - default: - { - if (ea.getX() > _cw->_center_x - 50 && - ea.getY() > _cw->_center_y - 200) - { - if (_cw->_center == 1) - { - _operate->getByName("center")->setColor(1, 1, 1, 1); - } - _background->getByName("backGround4")->setColor(1, 1, 1, 1); - } - else { - if (_cw->_center == 1) - { - _operate->getByName("center")->setColor(1, 1, 1, 0.1); - } - _background->getByName("backGround4")->setColor(1, 1, 1, 0); - } - } - break; - } - } return false; } \ No newline at end of file diff --git a/src/scene/ui/CompositeHandle.h b/src/scene/ui/CompositeHandle.h index 74709657..c94159ff 100644 --- a/src/scene/ui/CompositeHandle.h +++ b/src/scene/ui/CompositeHandle.h @@ -14,9 +14,9 @@ class CompositeHandle :public osgGA::GUIEventHandler public: CompositeHandle(CompositeWidgetManager* cw); - ~CompositeHandle(void); + ~CompositeHandle(void) override = default; - virtual bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter&); + bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter&) override; private: osgWidget::Canvas* _operate; diff --git a/src/scene/ui/CompositeWidgetManager.cpp b/src/scene/ui/CompositeWidgetManager.cpp index eaded4cd..81a16651 100644 --- a/src/scene/ui/CompositeWidgetManager.cpp +++ b/src/scene/ui/CompositeWidgetManager.cpp @@ -1,5 +1,6 @@ #include "CompositeWidgetManager.h" +#include "BackGroundWidget.h" #include "common/RecourceHelper.h" #include "viewer/OsgViewUI.h" @@ -114,7 +115,7 @@ void CompositeWidgetManager::ResetCanvasPosition(double x, double y) void CompositeWidgetManager::SendPosition() { - _mouseDirection = osg::Vec2(_local_x, _local_y); + _mouseDirection = osg::Vec2(static_cast(_local_x), static_cast(_local_y)); if (_center == 0 && _state != CompositeWidgetManager::MOUSE_DRAG && _autoHome != true) { QVariantList varList; @@ -127,13 +128,14 @@ void CompositeWidgetManager::SendPosition() QVariantList varList; varList.push_back(QVariant(_mouseDirection.x())); varList.push_back(QVariant(_mouseDirection.y())); + //emit signalHeading(QVariant(varList)); } else { osg::Vec2 pos = _mouseDirection; - pos[0] = pos.x()* 0.2; - pos[1] = pos.y()* 0.1; + pos[0] = pos.x()* 0.2f; + pos[1] = pos.y()* 0.1f; QVariantList varList; varList.push_back(QVariant(pos.x())); @@ -142,8 +144,7 @@ void CompositeWidgetManager::SendPosition() } } -void CompositeWidgetManager::SetHeading(double angle) -{ +void CompositeWidgetManager::SetHeading(double angle) { _canvasN->setRotate(angle + 45); _canvasN->update(); } @@ -156,6 +157,13 @@ void CompositeWidgetManager::AttachViewUI(OsgViewUI* ui) { ui->addChild(_canvasBackGround); } +void CompositeWidgetManager::AttachViewUI(osgWidget::WindowManager* ui) { + ui->addChild(_canvasO); + ui->addChild(_canvasN); + ui->addChild(_canvasFX); + ui->addChild(_canvasBackGround); +} + //void CompositeWidgetManager::slotHeading(double angle) //{ // SetHeading(angle); diff --git a/src/scene/ui/CompositeWidgetManager.h b/src/scene/ui/CompositeWidgetManager.h index 2997fc84..7cfaf0d9 100644 --- a/src/scene/ui/CompositeWidgetManager.h +++ b/src/scene/ui/CompositeWidgetManager.h @@ -1,13 +1,9 @@ #ifndef CompositeWidgetManager_h__ #define CompositeWidgetManager_h__ -#include "BackGroundWidget.h" -#include "CompositeHandle.h" + #include "CompositeWidget.h" #include "ZoomWidget.h" -#include "ZoomHandle.h" - -#include #include @@ -35,6 +31,7 @@ public: } void AttachViewUI(class OsgViewUI* ui); + void AttachViewUI(osgWidget::WindowManager* ui); // // diff --git a/src/scene/ui/OESceneUI.cpp b/src/scene/ui/OESceneUI.cpp index 5a1898cc..25957f5f 100644 --- a/src/scene/ui/OESceneUI.cpp +++ b/src/scene/ui/OESceneUI.cpp @@ -29,7 +29,7 @@ void OESceneUI::InitUI(OsgViewUI* ui) { compositeWidgetManager_ = new CompositeWidgetManager(); compositeWidgetManager_->AttachViewUI(ui); - zoomManager_ = new ZoomManager(); + zoomManager_ = new ZoomManager(oeScene_); zoomManager_->AttachViewUI(ui); queryElevationWidget_ = new QueryElevationWidget(oeScene_); diff --git a/src/scene/ui/ZoomManager.cpp b/src/scene/ui/ZoomManager.cpp index 5742bd0c..8c11ea14 100644 --- a/src/scene/ui/ZoomManager.cpp +++ b/src/scene/ui/ZoomManager.cpp @@ -1,11 +1,15 @@ #include "ZoomManager.h" +#include + #include "config.h" #include "common/SpdLogger.h" #include "viewer/OsgViewUI.h" #include "common/RecourceHelper.h" +#include "scene/OEScene.h" -ZoomManager::ZoomManager(void) +ZoomManager::ZoomManager(OEScene* oeScene) + : oeScene_(oeScene) { zoom = 0.0; state = ZoomManager::DEFAULT; @@ -17,12 +21,20 @@ ZoomManager::ZoomManager(void) _canvasZoom->setStrata(osgWidget::Window::STRATA_FOREGROUND); const std::string texturePath = RecourceHelper::Get().GetResourcesPath().toStdString(); - _lessen = new ZoomWidget("lessen", 18, 20, texturePath + "/northarrow/zoom_down.png", "lessen", osgWidget::Widget::LAYER_TOP, this); - _enlargement = new ZoomWidget("enlargement", 18, 20, texturePath + "/northarrow/zoom_up.png", "enlargement", osgWidget::Widget::LAYER_TOP, this); - _zoomBackground = new BackGroundWidget("zoomBackground", 18, 144, texturePath + "/northarrow/zoomactive.png"); - _bar = new ZoomWidget("bar", 17, 10, texturePath + "/northarrow/zoombar_norm.png", "bar", osgWidget::Widget::LAYER_TOP, this); - _bar_ = new BackGroundWidget("bar_", 18, 12, texturePath + "/northarrow/zoombar_norm_.png"); - _zoomBackground_shadow = new BackGroundWidget("background_shadow", 18, 144, texturePath + "/northarrow/zoombackground.png"); + _lessen = new ZoomWidget("lessen", 18, 20, texturePath + "/northarrow/zoom_down.png", + "lessen", osgWidget::Widget::LAYER_TOP, this); + _enlargement = new ZoomWidget("enlargement", 18, 20, + texturePath + "/northarrow/zoom_up.png", "enlargement", + osgWidget::Widget::LAYER_TOP, this); + _zoomBackground = new BackGroundWidget("zoomBackground", 18, 144, + texturePath + "/northarrow/zoomactive.png"); + _bar = new ZoomWidget("bar", 17, 10, + texturePath + "/northarrow/zoombar_norm.png", "bar", + osgWidget::Widget::LAYER_TOP, this); + _bar_ = new BackGroundWidget("bar_", 18, 12, + texturePath + "/northarrow/zoombar_norm_.png"); + _zoomBackground_shadow = new BackGroundWidget("background_shadow", 18, 144, + texturePath + "/northarrow/zoombackground.png"); _canvasZoom->addWidget(_lessen, 0, 0); _canvasZoom->addWidget(_enlargement, 0, 124); @@ -54,7 +66,7 @@ void ZoomManager::ResetCanvasPosition(double x, double y) void ZoomManager::SendZoom() { _zoomNum[0] = zoom; - + slotZoom(); //emit signalZoom(QVariant(_zoomNum[0])); } @@ -63,3 +75,49 @@ void ZoomManager::AttachViewUI(OsgViewUI* ui) { ui->addChild(_canvasZoom); } + + +void ZoomManager::slotZoom() { + double val = _zoomNum[0]; + double dx = val*(-1.0)*(0.0005);// dx不起作用 + double dy = val*(-1.0)*(0.0005); + + // dx *= getSettings()->getMouseSensitivity(); + // dy *= getSettings()->getMouseSensitivity(); + + double minAlt = 500.0; + double maxAlt = 35000000.0; + auto em = oeScene_->GetManipulater(); + auto vp = em->getViewpoint(); + vp.setRange(vp.getRange() * 1.1); + em->setViewpoint(vp); + // + // double scale = 1.0f + dy; + // double distance = em->getDistance() * scale; + // distance = std::max(distance, maxAlt); + // + // // if (!OEScene::GetSrs()->isGeographic()) + // // { + // // osg::Viewport* vp = oeScene_->GetViewport(); + // // if (vp) + // // { + // // double ar = vp->width() / vp->height(); + // // double y = distance * tan(0.5*osg::DegreesToRadians(em->)); + // // double x = y * ar; + // // + // // osgEarth::GeoExtent extentMap = oeScene_->getMap()->getProfile()->getExtent(); + // // + // // if ((_center.y() - y) < extentMap.yMin()) + // // { + // // return; + // // } + // // if ((_center.y() + y) > extentMap.yMax()) + // // { + // // return; + // // } + // // } + // // } + // + // em->setDistance(distance); +} + diff --git a/src/scene/ui/ZoomManager.h b/src/scene/ui/ZoomManager.h index d483aafd..5f2d5acd 100644 --- a/src/scene/ui/ZoomManager.h +++ b/src/scene/ui/ZoomManager.h @@ -12,7 +12,7 @@ class ZoomManager : public osg::Referenced { public: - ZoomManager(void); + ZoomManager(class OEScene* oeScene); ~ZoomManager(void); void ResetCanvasPosition(double x, double y); @@ -27,6 +27,9 @@ public: //signals: // void signalZoom(QVariant var); +protected: + void slotZoom(); + private: osgWidget::Canvas* _canvasZoom; @@ -39,6 +42,8 @@ private: int _zoomNum[1]; + class OEScene* oeScene_; + public: enum STATE { MOUSE_PUSH, diff --git a/src/scene/ui/ZoomWidget.cpp b/src/scene/ui/ZoomWidget.cpp index 0b8cbb27..3b314078 100644 --- a/src/scene/ui/ZoomWidget.cpp +++ b/src/scene/ui/ZoomWidget.cpp @@ -30,10 +30,6 @@ ZoomWidget::ZoomWidget(std::string name, _pZoomManager = pZoomManager; } -ZoomWidget::~ZoomWidget(void) -{ -} - bool ZoomWidget::mousePush(double x, double y, const osgWidget::WindowManager* wm) { _pZoomManager->state = ZoomManager::MOUSE_PUSH; diff --git a/src/scene/ui/ZoomWidget.h b/src/scene/ui/ZoomWidget.h index ba244fa7..e4af9b3d 100644 --- a/src/scene/ui/ZoomWidget.h +++ b/src/scene/ui/ZoomWidget.h @@ -21,7 +21,7 @@ public: osgWidget::Widget::Layer layer, ZoomManager *pZoomManager); - ~ZoomWidget(void); + ~ZoomWidget(void) override = default; bool mousePush(double, double, const osgWidget::WindowManager*); bool mouseRelease(double, double, const osgWidget::WindowManager*); diff --git a/src/translations/Dyt_zh_CN.ts b/src/translations/Dyt_zh_CN.ts index 6a64aaad..d9ee43d8 100644 --- a/src/translations/Dyt_zh_CN.ts +++ b/src/translations/Dyt_zh_CN.ts @@ -356,7 +356,7 @@ new workspace - 新建空间 + @@ -386,7 +386,7 @@ warning - 警告 + @@ -454,33 +454,29 @@ MainFrame - + Dyt - Dyt + - + file manager - 文件管理 + - + simu manager - 仿真管理 + - + play manager - 回放管理 + - window manager - 窗口管理 - - - + system manager - 系统管理 + @@ -491,132 +487,132 @@ - + model elements - 实体 + - + attribte - 属性 + - + Wave Curve - + Speed Curve - + 3D Curve - + Target number - + Signal-to-noise ratio - + Azimuth line of sight - + Pitch gaze angle - + azimuth - + Pitch angle - + attribute - 属性 + - + Doppler - + course - + Speed - + longitude - + latitude - + distance - + velocity - + Radial dimensions - + Target RCS - + Report Table - + Signal Indicator Lamp - + ParamSetting - + Matlab File - + name: 5year 0412 @@ -626,57 +622,76 @@ Release Track - 取消关注 + - + Add boke Entity - + Add lsjhqt Entity - + Add nimizi Entity - + Add tkdlj Entity - + Add jiaofan Entity - + Add satellite Entity - + Track - 关注 + - + Add Mesh Component - + Add Path Component - + Delete - 删除 + + + + + OsgWidget + + + + warning + + + + + default workspace failed + + + + + open dyt file failed + @@ -692,7 +707,7 @@ PlayManagerMenu - 播放管理菜单 + @@ -700,12 +715,12 @@ play - 播放 + stop - 停止 + @@ -725,28 +740,12 @@ up - 加速 + down - 减速 - - - question - 警告 - - - - - - - - - - - has not workspace - 空间不存在 + @@ -758,14 +757,26 @@ warning - 警告 + + + + + + + + + + + + has not workspace + pause - 暂停 + @@ -773,7 +784,7 @@ attribute - 属性 + @@ -827,12 +838,12 @@ QObject - + error - + the appliaction is crash @@ -1104,7 +1115,7 @@ Name - 名称 + @@ -1205,7 +1216,7 @@ Name - 名称 + @@ -1226,18 +1237,18 @@ QtOsgViewWidget - - + + warning - 警告 + - + default workspace failed - + open dyt file failed @@ -1253,7 +1264,7 @@ Path - 路径 + @@ -1472,12 +1483,12 @@ Property - 属性 + Value - + @@ -1503,7 +1514,7 @@ Name - 名称 + @@ -1585,28 +1596,28 @@ SystemManagerMenu - 系统管理菜单 + exit - 退出 + ui setting - ui设置 + question - 询问 + are you sure to exit - 确定退出 + @@ -1673,52 +1684,52 @@ New WorkSpace - 新建空间 + Name - 名称 + input workspace name - 空间名称 + Path - 路径 + select workspace save path - 选择路径 + ... - + describe - 描述 + Sure - 确认 + Cancel - 取消 + new workspace - 新建空间 + @@ -1728,46 +1739,42 @@ warning - 警告 + name or save path is empty, please check it - 名称或者路径为空 + save current workspace? - 保存当前空间? + current path is contains current folder, do you want to overwrite it? - 当前空间已存在,是否替换? + removeRecursively failed - 删除失败 + mkpath failed - 创建路径失败 + name is exits - 名称已存在 - - - create workSpace failed - 创建空间失败 + save spaceWork directory - 保存空间目录 + diff --git a/src/ui/FramelessDelegateWin.cpp b/src/ui/FramelessDelegateWin.cpp index cebb2b02..cac264d7 100644 --- a/src/ui/FramelessDelegateWin.cpp +++ b/src/ui/FramelessDelegateWin.cpp @@ -96,7 +96,8 @@ bool FramelessDelegateWin::nativeEvent(const QByteArray & eventType, void* messa auto rc = workRect_; if (!rc) return false; - if (auto ret = DefWindowProcW(msg->hwnd, WM_NCCALCSIZE, msg->wParam, msg->lParam); ret) { + auto ret = DefWindowProcW(msg->hwnd, WM_NCCALCSIZE, msg->wParam, msg->lParam); + if ( ret) { *result = ret; return true; } @@ -108,7 +109,8 @@ bool FramelessDelegateWin::nativeEvent(const QByteArray & eventType, void* messa } else { const auto clientRect = reinterpret_cast(msg->lParam); const auto before = *clientRect; - if (auto ret = DefWindowProcW(msg->hwnd, WM_NCCALCSIZE, msg->wParam, msg->lParam); ret) { + auto ret = DefWindowProcW(msg->hwnd, WM_NCCALCSIZE, msg->wParam, msg->lParam); + if ( ret) { *result = ret; return true; } @@ -276,7 +278,7 @@ void FramelessDelegateWin::CheckMonitorChanged() { auto newMonitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONULL); if (newMonitor != monitor_) { monitor_ = newMonitor; - auto ret = GetScreenNativeWorkRect(hwnd); + std::optional ret = GetScreenNativeWorkRect(hwnd); if ( !!ret) workRect_ = ret; } diff --git a/src/ui/FramelessDelegateWin.h b/src/ui/FramelessDelegateWin.h index a6502bea..6875007d 100644 --- a/src/ui/FramelessDelegateWin.h +++ b/src/ui/FramelessDelegateWin.h @@ -12,72 +12,209 @@ namespace std { }; constexpr explicit nullopt_t(_Tag) {} }; - inline constexpr nullopt_t nullopt{ nullopt_t::_Tag{} }; + constexpr nullopt_t nullopt{ nullopt_t::_Tag{} }; + class bad_optional_access : public std::exception + { + public: + const char* what() const noexcept override + { + return "bad optional access"; + } + }; - template + template class optional { public: - optional() : has_value_(false) {} - optional(const T& value) : has_value_(true), value_(value) {} - optional(T&& value) : has_value_(true), value_(std::move(value)) {} - optional(nullopt_t) : has_value_(false) {} + constexpr optional() noexcept : _engaged(false) {} + constexpr optional(nullopt_t) noexcept : _engaged(false) {} - bool has_value() const { - return has_value_; - } - - T& value() { - if (!has_value_) { - throw std::runtime_error("optional has no value"); + optional(const optional& other) : _engaged(other._engaged) { + if (other._engaged) { + new (_storage) T(*other); } - return value_; } - const T& value() const { - if (!has_value_) { - throw std::runtime_error("optional has no value"); + optional(optional&& other) noexcept : _engaged(other._engaged) { + if (other._engaged) { + new (_storage) T(std::move(*other)); + other._engaged = false; } - return value_; } - // * -> ʹʹøӷ - T& operator*() { - return value(); - } - - const T& operator*() const { - return value(); - } - - T* operator->() { - return &value(); - } - - const T* operator->() const { - return &value(); - } - - bool operator==(const optional& other) const { - if (has_value_ && other.has_value_) { - return value_ == other.value_; + optional& operator=(const optional& other) + { + if(this == &other) + return *this; + if(_engaged && other._engaged) + { + **this = *other; + } + else if(other._engaged) + { + new (_storage) T(*other); + _engaged = true; + } else if(_engaged) + { + reset(); } - return has_value_ == other.has_value_; + + return *this; + } - bool operator!=(const optional& other) const { - return !(*this == other); + optional& operator=(optional&& other) noexcept + { + if(this == &other) + return *this; + if(_engaged && other._engaged) + { + **this = std::move(*other); + + } else if (other._engaged) + { + new(_storage) T(std::move(*other)); + _engaged = true; + + } else if(_engaged) + { + reset(); + } + other._engaged = false; + return *this; } - bool operator!() const { - return !has_value(); + optional(const T& value) : _engaged(true) { + new (_storage) T(value); + } + + optional(T&& value) : _engaged(true) { + new (_storage) T(std::move(value)); + } + + ~optional() { + reset(); + } + + void reset() noexcept { + if (_engaged) { + reinterpret_cast(_storage)->~T(); + _engaged = false; + } + } + + constexpr bool has_value() const noexcept + { + return _engaged; + } + + T& operator*() & + { + if(!_engaged) + throw std::bad_optional_access(); + return *reinterpret_cast(_storage); + } + const T& operator*() const& + { + if(!_engaged) + throw std::bad_optional_access(); + return *reinterpret_cast(_storage); + } + + T&& operator*() && + { + if(!_engaged) + throw std::bad_optional_access(); + return std::move(*reinterpret_cast(_storage)); + } + + const T&& operator*() const&& + { + if(!_engaged) + throw std::bad_optional_access(); + return std::move(*reinterpret_cast(_storage)); + } + + T* operator->() { + return reinterpret_cast(_storage); + } + const T* operator->() const { + return reinterpret_cast(_storage); + } + + explicit operator bool() const noexcept { + return _engaged; } private: - bool has_value_; - T value_; + bool _engaged; + char _storage[sizeof(T)]; }; + + // + // template + // class optional { + // public: + // optional() : has_value_(false) {} + // optional(const T& value) : has_value_(true), value_(value) {} + // optional(T&& value) : has_value_(true), value_(std::move(value)) {} + // optional(nullopt_t) : has_value_(false) {} + // + // bool has_value() const { + // return has_value_; + // } + // + // T& value() { + // if (!has_value_) { + // throw std::runtime_error("optional has no value"); + // } + // return value_; + // } + // + // const T& value() const { + // if (!has_value_) { + // throw std::runtime_error("optional has no value"); + // } + // return value_; + // } + // + // T& operator*() { + // return value(); + // } + // + // const T& operator*() const { + // return value(); + // } + // + // T* operator->() { + // return &value(); + // } + // + // const T* operator->() const { + // return &value(); + // } + // + // bool operator==(const optional& other) const { + // if (has_value_ && other.has_value_) { + // return value_ == other.value_; + // } + // return has_value_ == other.has_value_; + // } + // + // bool operator!=(const optional& other) const { + // return !(*this == other); + // } + // + // bool operator!() const { + // return !has_value(); + // } + // + // private: + // bool has_value_; + // T value_; + // }; + } #endif diff --git a/src/ui/MainFrame.cpp b/src/ui/MainFrame.cpp index 855f9bd5..e351078d 100644 --- a/src/ui/MainFrame.cpp +++ b/src/ui/MainFrame.cpp @@ -26,6 +26,7 @@ #include "common/SpdLogger.h" #include "ui_MainFrame.h" +#include "viewer/OsgWidget.h" MainFrame* s_instance { nullptr }; @@ -115,9 +116,9 @@ void MainFrame::InitUI() { MainWindow* mainWindow = new MainWindow(this); layout->addWidget(mainWindow); - QtOsgViewWidget* viewWidget = mainWindow->GetViewWidget(); - connect(fileMenu, &FileManagerMenu::LoadDyt, viewWidget, &QtOsgViewWidget::OnLoadDyt); - connect(viewWidget, &QtOsgViewWidget::signalResetWorkSpace, mainWindow, &MainWindow::slotResetWorkSpace); + OsgWidget* viewWidget = mainWindow->GetViewWidget(); + connect(fileMenu, &FileManagerMenu::LoadDyt, viewWidget, &OsgWidget::OnLoadDyt); + connect(viewWidget, &OsgWidget::signalResetWorkSpace, mainWindow, &MainWindow::slotResetWorkSpace); connect(system_, &SystemManagerMenu::signalShowUISetting, mainWindow, &MainWindow::slotShowUISetting); diff --git a/src/ui/MainWindow.cpp b/src/ui/MainWindow.cpp index 112041d5..9621afc2 100644 --- a/src/ui/MainWindow.cpp +++ b/src/ui/MainWindow.cpp @@ -1,12 +1,5 @@ #include "MainWindow.h" -#include -#include - -#include -#include -#include -#include #include #include "PropertyBrowser.h" @@ -34,6 +27,7 @@ #include "Matlab/MatlabObject.h" #include "ui_MainWindow.h" +#include "viewer/OsgWidget.h" MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent) @@ -83,7 +77,7 @@ void MainWindow::InitUI() { connect(modelBrowser_, &ModelBrowser::WorkSpaceChange, propertyBrowser_, &PropertyBrowser::OnWorkSpaceChange); connect(modelBrowser_, &ModelBrowser::EntityChange, propertyBrowser_, &PropertyBrowser::OnEntityChange); - qtOsgViewWidget_ = new QtOsgViewWidget; + qtOsgViewWidget_ = new OsgWidget; qtOsgViewWidget_->Initialize(); m_mapDockWidget.insert("PropertyBrowser", attribte); @@ -138,14 +132,14 @@ void MainWindow::InitUI() { targetUITable_ = new TargetListWgt; QStringList headerLabels; - headerLabels << tr("Target number") << tr("Signal-to-noise ratio") //QString::fromLocal8Bit("Ŀ") << QString::fromLocal8Bit("") - << tr("Azimuth line of sight") << tr("Pitch gaze angle") // QString::fromLocal8Bit("λ߽") << QString::fromLocal8Bit("߽") - << tr("azimuth") << tr("Pitch angle") // QString::fromLocal8Bit("λ") << QString::fromLocal8Bit("") - << tr("attribute") << tr("Doppler") // QString::fromLocal8Bit("") << QString::fromLocal8Bit("") - << tr("course") << tr("Speed") // QString::fromLocal8Bit("") << QString::fromLocal8Bit("") - << tr("longitude") << tr("latitude") // QString::fromLocal8Bit("") << QString::fromLocal8Bit("γ") - << tr("distance") << tr("velocity") // QString::fromLocal8Bit("") << QString::fromLocal8Bit("ٶ") - << tr("Radial dimensions") << tr("Target RCS"); // QString::fromLocal8Bit("ߴ") << QString::fromLocal8Bit("ĿRCS"); + headerLabels << tr("Target number") << tr("Signal-to-noise ratio") + << tr("Azimuth line of sight") << tr("Pitch gaze angle") + << tr("azimuth") << tr("Pitch angle") + << tr("attribute") << tr("Doppler") + << tr("course") << tr("Speed") + << tr("longitude") << tr("latitude") + << tr("distance") << tr("velocity") + << tr("Radial dimensions") << tr("Target RCS"); targetUITable_->SetHeader(headerLabels); //const QString reportPath = RecourceHelper::Get().GetBasePath() + "/workspace/Report.txt"; diff --git a/src/ui/MainWindow.h b/src/ui/MainWindow.h index 13d0abc8..4f5e65a1 100644 --- a/src/ui/MainWindow.h +++ b/src/ui/MainWindow.h @@ -21,7 +21,7 @@ public: class ModelBrowser* GetModelBrowser() const { return modelBrowser_; } - class QtOsgViewWidget* GetViewWidget() const { + class OsgWidget* GetViewWidget() const { return qtOsgViewWidget_; } @@ -55,7 +55,7 @@ private: class ModelBrowser* modelBrowser_{ nullptr }; class PropertyBrowser* propertyBrowser_{ nullptr }; class QWebEngineView* webEngineView_{ nullptr }; - class QtOsgViewWidget* qtOsgViewWidget_{ nullptr }; + class OsgWidget* qtOsgViewWidget_{ nullptr }; class FitCurveDialog* fitCurveDlg_{ nullptr }; class FitCurveDialog* fitYLgCurveDlg_{ nullptr }; diff --git a/src/ui/ModelBrowser/ModelTreeWidget.cpp b/src/ui/ModelBrowser/ModelTreeWidget.cpp index 87eebfc4..edf45cf7 100644 --- a/src/ui/ModelBrowser/ModelTreeWidget.cpp +++ b/src/ui/ModelBrowser/ModelTreeWidget.cpp @@ -5,7 +5,7 @@ #include #include -#include +#include #include "common/RecourceHelper.h" #include "common/SpdLogger.h" @@ -108,8 +108,7 @@ void ModelTreeWidget::contextMenuEvent(QContextMenuEvent* event) { PopupEntityMenu(event, entity); } else { QMenu menu(this); - - // Ӳ˵ + QAction* addEntiy = new QAction(tr("Add boke Entity"), this); connect(addEntiy, &QAction::triggered, [this]() { OnAddMeshEntity("boke/boke.ive", "boke"); @@ -152,7 +151,7 @@ void ModelTreeWidget::contextMenuEvent(QContextMenuEvent* event) { ); menu.addAction(addEntiy); - // ʾ˵ + // ��ʾ�˵� menu.exec(event->globalPos()); } @@ -253,12 +252,10 @@ void ModelTreeWidget::PopupEntityMenu(QContextMenuEvent* event, Entity* entity) OnTrackEntity(entity); } ); - - // Ӳ˵ + addEntiy = new QAction(tr("Add Mesh Component"), this); menu.addAction(addEntiy); - - // ˵ӵ˵ + addEntiy = new QAction(tr("Add Path Component"), this); menu.addAction(addEntiy); connect(addEntiy, &QAction::triggered, [this, entity]() { @@ -272,8 +269,7 @@ void ModelTreeWidget::PopupEntityMenu(QContextMenuEvent* event, Entity* entity) OnDeleteEntity(entity); } ); - - // ʾ˵ + menu.exec(event->globalPos()); } diff --git a/src/utils/StringUtils.cpp b/src/utils/StringUtils.cpp index 92a28cbf..a26ee6e8 100644 --- a/src/utils/StringUtils.cpp +++ b/src/utils/StringUtils.cpp @@ -68,9 +68,9 @@ std::string StringUtils::ViewpointToString(const osgEarth::Viewpoint& value) { double latitude = location->y(); double altitude = location->z(); - double heading = value.heading().get(); - double pitch = value.pitch().get(); - double range = value.range().get(); + double heading = value.heading().get().getValue(); + double pitch = value.pitch().get().getValue(); + double range = value.range().get().getValue(); std::stringstream ss; ss << std::fixed << std::setprecision(6); diff --git a/src/viewer/CameraControlManipulator.cpp b/src/viewer/CameraControlManipulator.cpp index a0bfe567..2c47f927 100644 --- a/src/viewer/CameraControlManipulator.cpp +++ b/src/viewer/CameraControlManipulator.cpp @@ -143,11 +143,7 @@ void CameraControlManipulator::setByMatrix(const osg::Matrixd& matrix) { fixVerticalAxis(_center, _rotation, true); } break; - - default: - break; } - } /** Get the position of the manipulator as 4x4 Matrix.*/ @@ -196,9 +192,6 @@ osg::Matrixd CameraControlManipulator::getMatrix() const { osg::Matrixd::translate(_center); } break; - - default: - break; } return matrix; @@ -347,8 +340,6 @@ void CameraControlManipulator::rotateYawPitch(osg::Quat& rotation, const double } while (true); } bool CameraControlManipulator::calcMovement() { - - // return if less then two events have been added. if (_ga_t0.get() == NULL || _ga_t1.get() == NULL) return false; @@ -361,7 +352,7 @@ bool CameraControlManipulator::calcMovement() { // get delta time double eventTimeDelta = _ga_t0->getTime() - _ga_t1->getTime(); if (eventTimeDelta < 0.) { - OSG_WARN << "Manipulator warning: eventTimeDelta = " << eventTimeDelta << std::endl; + OSG_WARN << "Manipulator warning: eventTimeDelta = " << eventTimeDelta; eventTimeDelta = 0.; } @@ -1184,7 +1175,7 @@ bool CameraControlManipulator::handleMouseWheel(const osgGA::GUIEventAdapter& ea view->getCamera()->getProjectionMatrixAsOrtho(left, right, bottom, top, zNear, zFar); - float scale = 1.0f + dy; + float scale = 1.0f + static_cast(dy); _distance *= scale; diff --git a/src/viewer/OsgView.cpp b/src/viewer/OsgView.cpp index aeef86e8..cc5c95ff 100644 --- a/src/viewer/OsgView.cpp +++ b/src/viewer/OsgView.cpp @@ -19,17 +19,6 @@ #include "viewer/OsgCameraManipulator.h" #include "viewer/OsgViewUI.h" -enum KeyboardModifier { - NoModifier = 0x00000000, - ShiftModifier = 0x02000000, - ControlModifier = 0x04000000, - AltModifier = 0x08000000, - MetaModifier = 0x10000000, - KeypadModifier = 0x20000000, - GroupSwitchModifier = 0x40000000, - KeyboardModifierMask = 0xfe000000 -}; - OsgView::OsgView(QObject* parent) noexcept : QObject(parent) { LOG_INFO("actor, self={}", fmt::ptr(this)); @@ -39,51 +28,11 @@ OsgView::~OsgView() { LOG_INFO("dctor, self={}", fmt::ptr(this)); } -void OsgView::InitGraphiceWindow(int x, int y, int width, int height, - WId windowHandle, const char* name, bool windowDecoration) { -#ifdef _WIN32 - osg::Referenced* windata = new osgViewer::GraphicsWindowWin32::WindowData(HWND(windowHandle)); -#endif // _WIN32 - osg::DisplaySettings* ds = osg::DisplaySettings::instance().get(); - osg::GraphicsContext::Traits* traits = new osg::GraphicsContext::Traits(ds); - traits->windowName = name; - traits->x = x; - traits->y = y; - traits->width = width; - traits->height = height; - traits->alpha = ds->getMinimumNumAlphaBits(); - traits->stencil = ds->getMinimumNumStencilBits(); - traits->sampleBuffers = ds->getMultiSamples(); - traits->samples = ds->getNumMultiSamples(); - traits->windowDecoration = windowDecoration; - traits->doubleBuffer = true; - traits->sharedContext = nullptr; - traits->setInheritedWindowPixelFormat = true; -#ifdef _WIN32 - traits->inheritedWindowData = windata; -#endif - graphiceWindow_ = osg::GraphicsContext::createGraphicsContext(traits); -#if USE_OCEAN - graphiceWindow_->getState()->setUseModelViewAndProjectionUniforms(false); - graphiceWindow_->getState()->setUseVertexAttributeAliasing(true); -#endif -} - void OsgView::InitView(osgViewer::View* pView) { - if (nullptr == pView || nullptr == graphiceWindow_) { + if (nullptr == pView) { return; } - osg::Camera* pCamera = pView->getCamera(); - pCamera->setGraphicsContext(graphiceWindow_); - const osg::GraphicsContext::Traits* traits = graphiceWindow_->getTraits(); - pCamera->setViewport(new osg::Viewport(0, 0, traits->width, traits->height)); -#if USE_OCEAN - pCamera->setProjectionMatrixAsPerspective(45.0, - static_cast(traits->width) / - static_cast(traits->height), - 0.1, 1000.0); - pCamera->setComputeNearFarMode(osg::CullSettings::COMPUTE_NEAR_FAR_USING_PRIMITIVES); -#endif + view_ = pView; } @@ -91,68 +40,6 @@ osgViewer::View* OsgView::GetView() const { return view_.get(); } -void OsgView::Resize(int x, int y, int width, int height) { - if (nullptr != graphiceWindow_) { - graphiceWindow_->resized(x, y, width, height); - GetEventQueue()->windowResize(x, y, width, height); - } - - if (!view_.valid()) { - LOG_INFO("m_pView is not valid"); - return; - } - osg::Camera* pCamera = view_->getCamera(); - pCamera->setViewport(new osg::Viewport(x, y, width, height)); -#if USE_OCEAN - pCamera->setProjectionMatrixAsPerspective(45.0, - static_cast(width) / static_cast(height), - 0.1, 1000.0); -#endif - if (viewUI_) { - viewUI_->Resize(width, height); - } - view_->requiresRedraw(); -} - -void OsgView::MouseMotion(int x, int y) { - Q_UNUSED(x); - Q_UNUSED(y); -} - -void OsgView::MousePress(int x, int y, unsigned int button) { - Q_UNUSED(x); - Q_UNUSED(y); - Q_UNUSED(button); -} - -void OsgView::MouseRelease(int x, int y, unsigned int button) { - Q_UNUSED(x); - Q_UNUSED(y); - Q_UNUSED(button); -} - -void OsgView::MouseWheel(int wheel) { - Q_UNUSED(wheel); -} - -void OsgView::KeyPress(QKeyEvent* keyInput) { - int osgKey = KeyMapQtOsg::RemapKey(keyInput->key()); - GetEventQueue()->keyPress(osgKey); -} - -void OsgView::KeyRelease(QKeyEvent* keyInput) { - int osgKey = KeyMapQtOsg::RemapKey(keyInput->key()); - GetEventQueue()->keyRelease(osgKey); -} - -void OsgView::SetKeyModifiers(int mask) { - int keyMask = 0; - if (mask & ShiftModifier) keyMask |= osgGA::GUIEventAdapter::MODKEY_SHIFT; - if (mask & ControlModifier) keyMask |= osgGA::GUIEventAdapter::MODKEY_CTRL; - if (mask & AltModifier) keyMask |= osgGA::GUIEventAdapter::MODKEY_ALT; - GetEventQueue()->getCurrentEventState()->setModKeyMask(keyMask); -} - void OsgView::Initialize(OsgCameraManipulator* cameraManipulator) { if (initialized_) { return; @@ -185,9 +72,6 @@ void OsgView::Uninitialize(void) { } initialized_ = false; - if (nullptr != graphiceWindow_) { - graphiceWindow_->clear(); - } } bool OsgView::SetCameraManipulator(OsgCameraManipulator* cameraManipulator) { @@ -204,8 +88,3 @@ bool OsgView::SetCameraManipulator(OsgCameraManipulator* cameraManipulator) { view_->setCameraManipulator(cameraMainp); return true; } - -osgGA::EventQueue* OsgView::GetEventQueue() const { - assert(nullptr != view_); - return view_->getEventQueue(); -} diff --git a/src/viewer/OsgView.h b/src/viewer/OsgView.h index 47b4a977..561ac9ee 100644 --- a/src/viewer/OsgView.h +++ b/src/viewer/OsgView.h @@ -12,20 +12,9 @@ class OsgView : public QObject { public: OsgView(QObject* parent = nullptr) noexcept; ~OsgView(); - - void InitGraphiceWindow(int x, int y, int width, int height, - WId windowHandle, const char* name = "", - bool windowDecoration = false); + void InitView(osgViewer::View* pView); osgViewer::View* GetView(void) const; - void Resize(int x, int y, int width, int height); - void MouseMotion(int x, int y); - void MousePress(int x, int y, unsigned int button); - void MouseRelease(int x, int y, unsigned int button); - void MouseWheel(int wheel); - void KeyPress(QKeyEvent* keyInput); - void KeyRelease(QKeyEvent* keyInput); - void SetKeyModifiers(int mask); void Initialize(OsgCameraManipulator* cameraManipulator); void Uninitialize(void); @@ -37,11 +26,8 @@ public: return cameraManipulator_; } -protected: - osgGA::EventQueue* GetEventQueue() const; private: - osg::ref_ptr graphiceWindow_; osg::ref_ptr view_; osg::ref_ptr viewUI_; OsgCameraManipulator* cameraManipulator_{ nullptr }; diff --git a/src/viewer/OsgViewer.cpp b/src/viewer/OsgViewer.cpp index f6e15c09..303d2652 100644 --- a/src/viewer/OsgViewer.cpp +++ b/src/viewer/OsgViewer.cpp @@ -4,7 +4,6 @@ #include #include -#include #include #include "common/SpdLogger.h" @@ -21,14 +20,6 @@ OsgViewer::OsgViewer(QObject* parent) noexcept LOG_INFO("actor, self={}", fmt::ptr(this)); //compositeViewer_->getDatabasePager()->setUnrefImageDataAfterApplyPolicy(true, false); - osgEarth::initialize(); - compositeViewer_ = new osgViewer::CompositeViewer; - compositeViewer_->setReleaseContextAtEndOfFrameHint(false); - compositeViewer_->setKeyEventSetsDone(0); - osgDB::Registry::instance()->getObjectWrapperManager()->findWrapper("osg::Image"); - // compositeViewer_->getDatabasePager()->setUnrefImageDataAfterApplyPolicy( true, false ); - compositeViewer_->setThreadingModel(osgViewer::ViewerBase::ThreadingModel::SingleThreaded); - } OsgViewer::~OsgViewer() { @@ -54,27 +45,6 @@ void OsgViewer::OnFrame(void) { qApp->postEvent(this, new QEvent(sOsgViewUpdateEvent)); } -OsgView* OsgViewer::CreateView(int x, int y, int width, int height, void* winHandle) { - OsgView* view = new OsgView(this); - if (nullptr == view) { - return nullptr; - } - - view->InitGraphiceWindow(x, y, width, height, reinterpret_cast(winHandle), "dytView"); - - OnAddView(view, x, y, width, height); - //compositeViewer_->setRealizeOperation(new osgEarth::GL3RealizeOperation()); - return view; -} - -void OsgViewer::DestroyView(OsgView* osgView) { - if (nullptr == osgView) { - return; - } - - OnRemoveView(osgView); -} - bool OsgViewer::IsDone() const { assert(nullptr != compositeViewer_); bool done = compositeViewer_->done(); @@ -94,7 +64,6 @@ bool OsgViewer::Initialize(void) { return initalized_; } initalized_ = true; - compositeViewer_->setRealizeOperation(new osgEarth::GL3RealizeOperation()); return initalized_; } diff --git a/src/viewer/OsgViewer.h b/src/viewer/OsgViewer.h index 05a88c2b..d3589ed4 100644 --- a/src/viewer/OsgViewer.h +++ b/src/viewer/OsgViewer.h @@ -18,11 +18,14 @@ class OsgViewer : public QObject, public Singleton { public: explicit OsgViewer(QObject* parent = nullptr) noexcept; ~OsgViewer() override; + + void SetViewer(osgViewer::CompositeViewer* viewer) { + compositeViewer_ = viewer; + } void OnDestory(); void OnFrame(void); - class OsgView* CreateView(int x, int y, int width, int height, void* winHandle); - void DestroyView(OsgView* view); + bool IsDone(void) const; OsgView* GetView() const; @@ -43,7 +46,7 @@ protected: void RenderUpdate(); private: - osg::ref_ptr compositeViewer_; + osgViewer::CompositeViewer* compositeViewer_; bool initalized_{ false }; using OsgViewSet = std::set; diff --git a/src/viewer/OsgWidget.cpp b/src/viewer/OsgWidget.cpp index 880418e3..41bf41e6 100644 --- a/src/viewer/OsgWidget.cpp +++ b/src/viewer/OsgWidget.cpp @@ -1,71 +1,142 @@ #include "viewer/OsgWidget.h" -#include + #include +#include +#include #include +#include +#include -#include "viewer/OSGRendererImpl.h" +#include +#include +#include "OsgView.h" +#include "OsgViewer.h" +#include "common/SpdLogger.h" +#include "scene/OEScene.h" +#include "ui/MainFrame.h" +#include "workspace/WorkSpaceManager.h" +#include "workspace/WorkSpace.h" -OsgWidget::OsgWidget(QWidget* parent) - : QOpenGLWidget(parent) - , renderer_(nullptr) -{ - +static void ConfigureView( osgViewer::View* view ) { + view->addEventHandler(new osgViewer::StatsHandler()); + view->addEventHandler(new osgViewer::WindowSizeHandler()); + view->addEventHandler(new osgViewer::ThreadingHandler()); + view->addEventHandler(new osgViewer::LODScaleHandler()); + view->addEventHandler(new osgGA::StateSetManipulator(view->getCamera()->getOrCreateStateSet())); + view->addEventHandler(new osgViewer::RecordCameraPathHandler()); + view->addEventHandler(new osgViewer::ScreenCaptureHandler()); } -void OsgWidget::initializeGL() + +OsgWidget::OsgWidget(QWidget* parent, Qt::WindowFlags f) + : QWidget(parent, f) { - renderer_ = new OSGRendererImpl(this); - renderer_->setup(this); - QScreen *screen = windowHandle() && windowHandle()->screen() ? windowHandle()->screen() : qApp->screens().front(); - renderer_->setupOSG(width(), height(), screen->devicePixelRatio()); - emit initialized(); + // // setAttribute(Qt::WA_PaintOnScreen, true); + // // setAttribute(Qt::WA_StaticContents, true); + // // setAttribute(Qt::WA_NoSystemBackground, true); + // setAttribute(Qt::WA_OpaquePaintEvent, true); + // // setAttribute(Qt::WA_DontCreateNativeAncestors, false); + + setThreadingModel(osgViewer::ViewerBase::SingleThreaded); + setMouseTracking(true); + setKeyEventSetsDone(0); + + connect( &timer_, SIGNAL(timeout()), this, SLOT(update()) ); + timer_.start( 10 ); } -void OsgWidget::resizeGL(int w, int h) -{ - QScreen *screen = windowHandle() && windowHandle()->screen() ? windowHandle()->screen() : qApp->screens().front(); - renderer_->resize(w, h, screen->devicePixelRatio()); +void OsgWidget::Initialize() { + QHBoxLayout* layout = new QHBoxLayout(this); + activeScene_ = new OEScene(); + QWidget* widget = addViewWidget( createGraphicsWindow(0,0,100,100)); + layout->addWidget(widget); + + viewUI_ = new OsgViewUI(view_, 100,100); + viewUI_->AddUI(activeScene_->GetOrCreateSceneUI()); } -void OsgWidget::paintGL() -{ - renderer_->render(); +void OsgWidget::LoadDefaultScene() { + dyt_check(nullptr != activeScene_); + if (nullptr == WorkSpaceManager::Get().LoadDefaultWorkspace(activeScene_)) { + LOG_ERROR("load default workspace failed"); + QMessageBox::warning(this, tr("warning"), tr("default workspace failed")); + } } -void OsgWidget::keyPressEvent(QKeyEvent *event) -{ - renderer_->keyPressEvent(event); +void OsgWidget::OnLoadDyt(const QString& path) { + LOG_INFO("load dyt path:{}", path.toStdString()); + WorkSpace* workSpace = WorkSpaceManager::Get().LoadDyt(path); + if (nullptr == workSpace) { + QMessageBox::warning(&MainFrame::Get(), tr("warning"), + tr("open dyt file failed"), QMessageBox::Ok); + return; + } + + const QString& name = workSpace->GetName(); + const QString windowTitle = MainFrame::Get().windowTitle(); + + MainFrame::Get().setWindowTitle(windowTitle + "-" + name); + WorkSpaceManager::Get().SetCurrent(workSpace); + if (nullptr != workspace_ && workspace_ != workSpace) { + workspace_->Unlaod(); + } + + workspace_ = workSpace; + + emit signalResetWorkSpace(); } -void OsgWidget::keyReleaseEvent(QKeyEvent *event) -{ - renderer_->keyReleaseEvent(event); +osgQt::GraphicsWindowQt* OsgWidget::createGraphicsWindow(int x, int y, int w, int h, const std::string& name, + bool windowDecoration) { + osg::DisplaySettings* ds = osg::DisplaySettings::instance().get(); + osg::ref_ptr traits = new osg::GraphicsContext::Traits; + traits->windowName = name; + traits->windowDecoration = windowDecoration; + traits->x = x; + traits->y = y; + traits->width = w; + traits->height = h; + traits->doubleBuffer = true; + traits->alpha = ds->getMinimumNumAlphaBits(); + traits->stencil = ds->getMinimumNumStencilBits(); + traits->sampleBuffers = ds->getMultiSamples(); + traits->samples = ds->getNumMultiSamples(); + + return new osgQt::GraphicsWindowQt(traits.get()); } -void OsgWidget::mousePressEvent(QMouseEvent *event) -{ - renderer_->mousePressEvent(event); +QWidget* OsgWidget::addViewWidget(osgQt::GraphicsWindowQt* gw) { + view_ = new osgViewer::View; + addView( view_ ); + ConfigureView(view_); + + osg::Camera* camera = view_->getCamera(); + camera->setGraphicsContext( gw ); + + const osg::GraphicsContext::Traits* traits = gw->getTraits(); + + camera->setClearColor( osg::Vec4(0.2f, 0.2f, 0.6f, 1.0) ); + camera->setViewport( new osg::Viewport(0, 0, traits->width, traits->height) ); + camera->setProjectionMatrixAsPerspective(30.0f, static_cast(traits->width)/static_cast(traits->height), 1.0f, 10000.0f ); + + activeScene_->AttachView(view_); + return gw->getGLWidget(); } -void OsgWidget::mouseReleaseEvent(QMouseEvent *event) -{ - renderer_->mouseReleaseEvent(event); +void OsgWidget::resizeEvent(QResizeEvent* event) { + QWidget::resizeEvent(event); + + if (nullptr == view_) { + return; + } + qreal devicePixelRatio = screen()->devicePixelRatio(); + const QSize& size = event->size(); + viewUI_->Resize(size.width() * devicePixelRatio, size.height() * devicePixelRatio); } -void OsgWidget::mouseDoubleClickEvent(QMouseEvent *event) -{ - renderer_->mouseDoubleClickEvent(event); -} - -void OsgWidget::mouseMoveEvent(QMouseEvent *event) -{ - renderer_->mouseMoveEvent(event); -} - -void OsgWidget::wheelEvent(QWheelEvent *event) -{ - renderer_->wheelEvent(event); +void OsgWidget::paintEvent(QPaintEvent*) { + frame(); } diff --git a/src/viewer/OsgWidget.h b/src/viewer/OsgWidget.h index f33e6bed..82b75205 100644 --- a/src/viewer/OsgWidget.h +++ b/src/viewer/OsgWidget.h @@ -1,30 +1,40 @@ #pragma once -#include +#include +#include +#include "osgqt/GraphicsWindowQt.h" -class OSGRendererImpl; +class OEScene; -class OsgWidget : public QOpenGLWidget { +class OsgWidget : public QWidget, public osgViewer::CompositeViewer { Q_OBJECT public: - OsgWidget(QWidget *parent = nullptr); - + OsgWidget(QWidget *parent = nullptr, Qt::WindowFlags f = nullptr); + + void Initialize(void); + void LoadDefaultScene(void); + void OnLoadDyt(const QString& path); + signals: - void initialized(); + void signalResetWorkSpace(); + void signalScaleInfo(const QString&); protected: - void initializeGL() override; - void resizeGL(int w, int h) override; - void paintGL() override; - - void keyPressEvent( QKeyEvent* event ) override; - void keyReleaseEvent( QKeyEvent* event ) override; - void mousePressEvent( QMouseEvent* event ) override; - void mouseReleaseEvent( QMouseEvent* event ) override; - void mouseDoubleClickEvent( QMouseEvent* event ) override; - void mouseMoveEvent( QMouseEvent* event ) override; - void wheelEvent( QWheelEvent* event ) override; + osgQt::GraphicsWindowQt* createGraphicsWindow( int x, int y, int w, int h, + const std::string& name="", bool windowDecoration=false ); + QWidget* addViewWidget( osgQt::GraphicsWindowQt* gw); + + void resizeEvent(QResizeEvent* event) override; + void paintEvent( QPaintEvent* /*event*/ ) override; + private: - OSGRendererImpl *renderer_; + QTimer timer_; + + osg::ref_ptr activeScene_; + osg::ref_ptr viewUI_; + class WorkSpace* workspace_{ nullptr }; + osg::ref_ptr view_; + // class OsgView* view_{nullptr}; }; + diff --git a/src/viewer/QtOsgViewWidget.cpp b/src/viewer/QtOsgViewWidget.cpp index a57a24a0..d53d110e 100644 --- a/src/viewer/QtOsgViewWidget.cpp +++ b/src/viewer/QtOsgViewWidget.cpp @@ -13,12 +13,10 @@ #include #include -#include -#include +#include #include #include "config.h" -#include "app/Application.h" #include "common/SpdLogger.h" #include "viewer/OsgView.h" #include "viewer/OsgViewer.h" @@ -52,12 +50,12 @@ QtOsgViewWidget::~QtOsgViewWidget() { void QtOsgViewWidget::keyPressEvent(QKeyEvent* event) { assert(nullptr != view_); - view_->KeyPress(event); + // view_->KeyPress(event); } void QtOsgViewWidget::keyReleaseEvent(QKeyEvent* event) { assert(nullptr != view_); - view_->KeyRelease(event); + // view_->KeyRelease(event); } void QtOsgViewWidget::Initialize(void) { @@ -68,17 +66,17 @@ void QtOsgViewWidget::Initialize(void) { WId handle= winId(); double pixelRatio = screen()->devicePixelRatio(); - view_ = OsgViewer::Get().CreateView(x(), y(), width() * pixelRatio, height() * pixelRatio, reinterpret_cast(handle)); - if (nullptr == view_) { - LOG_ERROR("view is nullptr"); - return; - } + // view_ = OsgViewer::Get().CreateView(x(), y(), width() * pixelRatio, height() * pixelRatio, reinterpret_cast(handle)); + // if (nullptr == view_) { + // LOG_ERROR("view is nullptr"); + // return; + // } setMouseTracking(true); activeScene_ = new OEScene; - activeScene_->AttachView(view_); - activeScene_->InitEventHandle(view_); + // activeScene_->AttachView(view_); + // activeScene_->InitEventHandle(view_); osgEarth::Util::EarthManipulator* manipulator = new osgEarth::Util::EarthManipulator; @@ -118,10 +116,10 @@ void QtOsgViewWidget::Uninitialize(void) { scene_ = nullptr; }*/ - if (nullptr != view_) { - view_->Uninitialize(); - OsgViewer::Get().DestroyView(view_); - } + // if (nullptr != view_) { + // view_->Uninitialize(); + // OsgViewer::Get().DestroyView(view_); + // } } void QtOsgViewWidget::LoadDefaultScene(void) { @@ -161,6 +159,6 @@ void QtOsgViewWidget::resizeEvent(QResizeEvent* event) { devicePixelRatio_ = screen()->devicePixelRatio(); const QSize& size = event->size(); - view_->Resize(0, 0, size.width() * devicePixelRatio_, size.height() * devicePixelRatio_); + // view_->Resize(0, 0, size.width() * devicePixelRatio_, size.height() * devicePixelRatio_); } diff --git a/src/workspace/WorkSpaceManager.cpp b/src/workspace/WorkSpaceManager.cpp index 798f214e..680ab069 100644 --- a/src/workspace/WorkSpaceManager.cpp +++ b/src/workspace/WorkSpaceManager.cpp @@ -116,6 +116,7 @@ bool WorkSpaceManager::Remove(WorkSpace* workspace) { return true; } workSpaces_.erase(itor); + return true; } WorkSpace* WorkSpaceManager::LoadDyt(const QString& dyt) {