diff --git a/.github/labels.yml b/.github/labels.yml index 0e25a1a7e2..997768c8de 100644 --- a/.github/labels.yml +++ b/.github/labels.yml @@ -80,6 +80,10 @@ - changed-files: - any-glob-to-any-file: ['src/Mod/Spreadsheet/**/*'] +"Mod: Start": +- changed-files: + - any-glob-to-any-file: ['src/Mod/Start/**/*'] + "Mod: Surface": - changed-files: - any-glob-to-any-file: ['src/Mod/Surface/**/*/'] diff --git a/.github/workflows/auto-close_stale_issues_and_pull-requests.yml b/.github/workflows/auto-close_stale_issues_and_pull-requests.yml index ffcafbbd90..9433dbe202 100644 --- a/.github/workflows/auto-close_stale_issues_and_pull-requests.yml +++ b/.github/workflows/auto-close_stale_issues_and_pull-requests.yml @@ -22,7 +22,7 @@ jobs: steps: - name: '🧹 Tag & close stale unconfirmed bugs' id: stale_issues - uses: actions/stale@v9.0.0 + uses: actions/stale@v9.1.0 with: repo-token: ${{ secrets.GITHUB_TOKEN }} days-before-stale: -1 @@ -49,7 +49,7 @@ jobs: - name: '🧹 Close stale requested feedback issues' id: awaiting_issues - uses: actions/stale@v9.0.0 + uses: actions/stale@v9.1.0 with: repo-token: ${{ secrets.GITHUB_TOKEN }} days-before-stale: -1 @@ -77,7 +77,7 @@ jobs: - name: '🧹 Tag & close inactive issues' id: inactive_issues - uses: actions/stale@v9.0.0 + uses: actions/stale@v9.1.0 with: repo-token: ${{ secrets.GITHUB_TOKEN }} days-before-stale: -1 @@ -108,7 +108,7 @@ jobs: - name: '🧹 Tag & close inactive PRs' id: inactive_pr - uses: actions/stale@v9.0.0 + uses: actions/stale@v9.1.0 with: repo-token: ${{ secrets.GITHUB_TOKEN }} days-before-stale: -1 diff --git a/.github/workflows/sub_buildUbuntu.yml b/.github/workflows/sub_buildUbuntu.yml index dab94d42b2..4d704ac2bd 100644 --- a/.github/workflows/sub_buildUbuntu.yml +++ b/.github/workflows/sub_buildUbuntu.yml @@ -76,66 +76,8 @@ jobs: with: submodules: true - name: Install FreeCAD dependencies - run: | - sudo apt-get update -qq - sudo apt-get install -y --no-install-recommends \ - ccache \ - doxygen \ - graphviz \ - imagemagick \ - libboost-date-time-dev \ - libboost-dev \ - libboost-filesystem-dev \ - libboost-graph-dev \ - libboost-iostreams-dev \ - libboost-program-options-dev \ - libboost-python-dev \ - libboost-regex-dev \ - libboost-serialization-dev \ - libboost-thread-dev \ - libcoin-dev \ - libeigen3-dev \ - libkdtree++-dev \ - libmedc-dev \ - libocct-data-exchange-dev \ - libocct-ocaf-dev \ - libocct-visualization-dev \ - libopencv-dev \ - libproj-dev \ - libpyside2-dev \ - libqt5opengl5-dev \ - libqt5svg5-dev \ - libqt5x11extras5-dev \ - libshiboken2-dev \ - libspnav-dev \ - libvtk7-dev \ - libx11-dev \ - libxerces-c-dev \ - libyaml-cpp-dev \ - libzipios++-dev \ - netgen \ - netgen-headers \ - ninja-build \ - occt-draw \ - pyqt5-dev-tools \ - pyside2-tools \ - python3-dev \ - python3-git \ - python3-markdown \ - python3-matplotlib \ - python3-packaging \ - python3-pivy \ - python3-ply \ - python3-pyside2.qtcore \ - python3-pyside2.qtgui \ - python3-pyside2.qtnetwork \ - python3-pyside2.qtsvg \ - python3-pyside2.qtwidgets \ - qtbase5-dev \ - qttools5-dev \ - shiboken2 \ - swig \ - xvfb + run: ./package/ubuntu/install-apt-packages.sh + - name: Make needed directories, files and initializations id: Init run: | diff --git a/.github/workflows/sub_lint.yml b/.github/workflows/sub_lint.yml index ab28e819da..ca829e3dbc 100644 --- a/.github/workflows/sub_lint.yml +++ b/.github/workflows/sub_lint.yml @@ -108,7 +108,7 @@ on: -readability/nolint, +readability/nul, +readability/strings, - +readability/todo, + -readability/todo, +readability/utf8, +runtime/arrays, +runtime/casting, diff --git a/cMake/FindPySide6.cmake b/cMake/FindPySide6.cmake index 8f97f0ec4c..847fef3ee0 100644 --- a/cMake/FindPySide6.cmake +++ b/cMake/FindPySide6.cmake @@ -4,17 +4,13 @@ # cMake find_package() call find_package(PySide6 CONFIG QUIET) -if(NOT PySide6_FOUND) - if(NOT PySide6_INCLUDE_DIRS AND TARGET PySide6::pyside6) - get_property(PySide6_INCLUDE_DIRS TARGET PySide6::pyside6 PROPERTY INTERFACE_INCLUDE_DIRECTORIES) - endif() - if(NOT PySide6_INCLUDE_DIRS) - find_pip_package(PySide6) - else() - set(PySide6_FOUND ON) - endif() +if(NOT PySide6_INCLUDE_DIRS AND TARGET PySide6::pyside6) + get_property(PySide6_INCLUDE_DIRS TARGET PySide6::pyside6 PROPERTY INTERFACE_INCLUDE_DIRECTORIES) +endif() +if(NOT PySide6_INCLUDE_DIRS) + find_pip_package(PySide6) endif() # Also provide the old-style variables so we don't have to update everything yet diff --git a/cMake/FreeCAD_Helpers/CompilerChecksAndSetups.cmake b/cMake/FreeCAD_Helpers/CompilerChecksAndSetups.cmake index 1d3c233df1..7dda6ad4d7 100644 --- a/cMake/FreeCAD_Helpers/CompilerChecksAndSetups.cmake +++ b/cMake/FreeCAD_Helpers/CompilerChecksAndSetups.cmake @@ -48,6 +48,8 @@ macro(CompilerChecksAndSetups) configure_file(${CMAKE_SOURCE_DIR}/src/config.h.cmake ${CMAKE_CURRENT_BINARY_DIR}/config.h) add_definitions(-DHAVE_CONFIG_H) + set(CMAKE_CXX_FLAGS "-fdiagnostics-color ${CMAKE_CXX_FLAGS}") + # For now only set pedantic option for clang if(CMAKE_COMPILER_IS_CLANGXX) set(CMAKE_CXX_FLAGS "-Wall -Wextra -Wpedantic -Wno-write-strings ${CMAKE_CXX_FLAGS}") diff --git a/cMake/FreeCAD_Helpers/InitializeFreeCADBuildOptions.cmake b/cMake/FreeCAD_Helpers/InitializeFreeCADBuildOptions.cmake index 995810d52b..6e8c8e42b0 100644 --- a/cMake/FreeCAD_Helpers/InitializeFreeCADBuildOptions.cmake +++ b/cMake/FreeCAD_Helpers/InitializeFreeCADBuildOptions.cmake @@ -13,6 +13,8 @@ macro(InitializeFreeCADBuildOptions) option(FREECAD_USE_FREETYPE "Builds the features using FreeType libs" ON) option(FREECAD_BUILD_DEBIAN "Prepare for a build of a Debian package" OFF) option(FREECAD_CHECK_PIVY "Check for pivy version using Python at build time" ON) + option(FREECAD_PARALLEL_COMPILE_JOBS "Compilation jobs pool size to fit memory limitations.") + option(FREECAD_PARALLEL_LINK_JOBS "Linkage jobs pool size to fit memory limitations.") option(BUILD_WITH_CONDA "Set ON if you build FreeCAD with conda" OFF) option(BUILD_DYNAMIC_LINK_PYTHON "If OFF extension-modules do not link against python-libraries" ON) option(INSTALL_TO_SITEPACKAGES "If ON the freecad root namespace (python) is installed into python's site-packages" ON) @@ -77,8 +79,6 @@ macro(InitializeFreeCADBuildOptions) "Community Edition" ) - configure_file(${CMAKE_SOURCE_DIR}/src/QtOpenGL.h.cmake ${CMAKE_BINARY_DIR}/src/QtOpenGL.h) - option(BUILD_DESIGNER_PLUGIN "Build and install the designer plugin" OFF) if(APPLE) @@ -208,4 +208,22 @@ macro(InitializeFreeCADBuildOptions) "Please choose another build directory! Or disable the option BUILD_FORCE_DIRECTORY.") endif() endif() + + if(FREECAD_PARALLEL_COMPILE_JOBS) + if(CMAKE_GENERATOR MATCHES "Ninja") + set_property(GLOBAL APPEND PROPERTY JOB_POOLS compile_job_pool=${FREECAD_PARALLEL_COMPILE_JOBS}) + set(CMAKE_JOB_POOL_COMPILE compile_job_pool) + else() + message(WARNING "Job pooling is only available with Ninja generators.") + endif() + endif() + + if(FREECAD_PARALLEL_LINK_JOBS) + if(CMAKE_GENERATOR MATCHES "Ninja") + set_property(GLOBAL APPEND PROPERTY JOB_POOLS link_job_pool=${FREECAD_PARALLEL_LINK_JOBS}) + set(CMAKE_JOB_POOL_LINK link_job_pool) + else() + message(WARNING "Job pooling is only available with Ninja generators.") + endif() + endif() endmacro(InitializeFreeCADBuildOptions) diff --git a/cMake/FreeCAD_Helpers/PrintFinalReport.cmake b/cMake/FreeCAD_Helpers/PrintFinalReport.cmake index 1f1cbe86b3..14cf57bd89 100644 --- a/cMake/FreeCAD_Helpers/PrintFinalReport.cmake +++ b/cMake/FreeCAD_Helpers/PrintFinalReport.cmake @@ -89,6 +89,8 @@ macro(PrintFinalReport) value(FREECAD_CREATE_MAC_APP) value(FREECAD_USE_PYBIND11) value(FREECAD_USE_EXTERNAL_KDL) + value(FREECAD_USE_PYSIDE) + value(FREECAD_USE_SHIBOKEN) value(BUILD_ADDONMGR) value(BUILD_BIM) value(BUILD_ASSEMBLY) diff --git a/cMake/FreeCAD_Helpers/SetupOpenGL.cmake b/cMake/FreeCAD_Helpers/SetupOpenGL.cmake index 4ce3924817..1999087981 100644 --- a/cMake/FreeCAD_Helpers/SetupOpenGL.cmake +++ b/cMake/FreeCAD_Helpers/SetupOpenGL.cmake @@ -1,6 +1,11 @@ macro(SetupOpenGL) # -------------------------------- OpenGL -------------------------------- + # If on a system with both a legacy GL library and GLVND, prefer the legacy library. + # This is probably needed until we no longer have any gl.*ARB calls in the codebase + # See, e.g. SoBrepFaceSet.cpp + set(OpenGL_GL_PREFERENCE LEGACY) + find_package(OpenGL) include(FindPackageMessage) if(OPENGL_GLU_FOUND) diff --git a/cMake/FreeCAD_Helpers/SetupShibokenAndPyside.cmake b/cMake/FreeCAD_Helpers/SetupShibokenAndPyside.cmake index 45c10fc2f4..778225d4a4 100644 --- a/cMake/FreeCAD_Helpers/SetupShibokenAndPyside.cmake +++ b/cMake/FreeCAD_Helpers/SetupShibokenAndPyside.cmake @@ -59,7 +59,7 @@ macro(SetupShibokenAndPyside) find_package(PySide${PYSIDE_MAJOR_VERSION} QUIET) - if(${PYSIDE_MAJOR_VERSION} EQUAL 5) + if(${PYSIDE_MAJOR_VERSION} EQUAL 2) # Our internal FindPySide6.cmake file already provides these for PySide6 if(NOT PYSIDE_INCLUDE_DIR AND TARGET PySide${PYSIDE_MAJOR_VERSION}::pyside${PYSIDE_MAJOR_VERSION}) get_property(PYSIDE_INCLUDE_DIR TARGET PySide${PYSIDE_MAJOR_VERSION}::pyside${PYSIDE_MAJOR_VERSION} PROPERTY INTERFACE_INCLUDE_DIRECTORIES) diff --git a/cMake/FreeCadMacros.cmake b/cMake/FreeCadMacros.cmake index f234416cd3..5a169f587d 100644 --- a/cMake/FreeCadMacros.cmake +++ b/cMake/FreeCadMacros.cmake @@ -156,13 +156,13 @@ macro(generate_from_py BASE_NAME) if(NOT EXISTS "${SOURCE_CPP_PATH}") # assures the source files are generated at least once message(STATUS "${SOURCE_CPP_PATH}") - execute_process(COMMAND "${PYTHON_EXECUTABLE}" "${TOOL_NATIVE_PATH}" --outputPath "${OUTPUT_NATIVE_PATH}" "${SOURCE_NATIVE_PATH}" + execute_process(COMMAND "${Python3_EXECUTABLE}" "${TOOL_NATIVE_PATH}" --outputPath "${OUTPUT_NATIVE_PATH}" "${SOURCE_NATIVE_PATH}" WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" COMMAND_ERROR_IS_FATAL ANY ) endif() add_custom_command( OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/${BASE_NAME}_.h" "${CMAKE_CURRENT_BINARY_DIR}/${BASE_NAME}_.cpp" - COMMAND ${PYTHON_EXECUTABLE} "${TOOL_NATIVE_PATH}" --outputPath "${OUTPUT_NATIVE_PATH}" ${BASE_NAME}.pyi + COMMAND ${Python3_EXECUTABLE} "${TOOL_NATIVE_PATH}" --outputPath "${OUTPUT_NATIVE_PATH}" ${BASE_NAME}.pyi MAIN_DEPENDENCY "${BASE_NAME}.pyi" DEPENDS "${CMAKE_SOURCE_DIR}/src/Tools/bindings/templates/templateClassPyExport.py" diff --git a/package/ubuntu/install-apt-packages.sh b/package/ubuntu/install-apt-packages.sh new file mode 100755 index 0000000000..9cf5f44e52 --- /dev/null +++ b/package/ubuntu/install-apt-packages.sh @@ -0,0 +1,68 @@ +#!/bin/bash +set -euo pipefail + +# Update package lists quietly +sudo apt-get update -qq + +packages=( + ccache + doxygen + graphviz + imagemagick + libboost-date-time-dev + libboost-dev + libboost-filesystem-dev + libboost-graph-dev + libboost-iostreams-dev + libboost-program-options-dev + libboost-python-dev + libboost-regex-dev + libboost-serialization-dev + libboost-thread-dev + libcoin-dev + libeigen3-dev + libkdtree++-dev + libmedc-dev + libocct-data-exchange-dev + libocct-ocaf-dev + libocct-visualization-dev + libopencv-dev + libproj-dev + libpyside2-dev + libqt5opengl5-dev + libqt5svg5-dev + libqt5x11extras5-dev + libshiboken2-dev + libspnav-dev + libvtk7-dev + libx11-dev + libxerces-c-dev + libyaml-cpp-dev + libzipios++-dev + netgen + netgen-headers + ninja-build + occt-draw + pyqt5-dev-tools + pyside2-tools + python3-dev + python3-git + python3-markdown + python3-matplotlib + python3-packaging + python3-pivy + python3-ply + python3-pyside2.qtcore + python3-pyside2.qtgui + python3-pyside2.qtnetwork + python3-pyside2.qtsvg + python3-pyside2.qtwidgets + qtbase5-dev + qttools5-dev + shiboken2 + swig + xvfb +) + +# Install all packages +sudo apt-get install -y --no-install-recommends "${packages[@]}" diff --git a/src/3rdParty/3Dconnexion/inc/SpaceMouse/CCookieCollection.hpp b/src/3rdParty/3Dconnexion/inc/SpaceMouse/CCookieCollection.hpp index 4b810ee647..3823f8eb7c 100644 --- a/src/3rdParty/3Dconnexion/inc/SpaceMouse/CCookieCollection.hpp +++ b/src/3rdParty/3Dconnexion/inc/SpaceMouse/CCookieCollection.hpp @@ -18,6 +18,7 @@ // #include // stdlib +#include #include #include #include diff --git a/src/App/Application.cpp b/src/App/Application.cpp index 05402889d2..507b063f51 100644 --- a/src/App/Application.cpp +++ b/src/App/Application.cpp @@ -1365,7 +1365,7 @@ void Application::addImportType(const char* Type, const char* ModuleName) std::string::size_type next = item.filter.find_first_of(" )", pos+1); std::string::size_type len = next-pos-2; std::string type = item.filter.substr(pos+2,len); - item.types.push_back(type); + item.types.push_back(std::move(type)); pos = item.filter.find("*.", next); } @@ -1373,12 +1373,12 @@ void Application::addImportType(const char* Type, const char* ModuleName) if (strncmp(Type, "FreeCAD", 7) == 0) { std::string AppName = Config()["ExeName"]; AppName += item.filter.substr(7); - item.filter = AppName; + item.filter = std::move(AppName); // put to the front of the array - _mImportTypes.insert(_mImportTypes.begin(),item); + _mImportTypes.insert(_mImportTypes.begin(),std::move(item)); } else { - _mImportTypes.push_back(item); + _mImportTypes.push_back(std::move(item)); } } @@ -1488,7 +1488,7 @@ void Application::addExportType(const char* Type, const char* ModuleName) std::string::size_type next = item.filter.find_first_of(" )", pos+1); std::string::size_type len = next-pos-2; std::string type = item.filter.substr(pos+2,len); - item.types.push_back(type); + item.types.push_back(std::move(type)); pos = item.filter.find("*.", next); } @@ -1496,12 +1496,12 @@ void Application::addExportType(const char* Type, const char* ModuleName) if (strncmp(Type, "FreeCAD", 7) == 0) { std::string AppName = Config()["ExeName"]; AppName += item.filter.substr(7); - item.filter = AppName; + item.filter = std::move(AppName); // put to the front of the array - _mExportTypes.insert(_mExportTypes.begin(),item); + _mExportTypes.insert(_mExportTypes.begin(),std::move(item)); } else { - _mExportTypes.push_back(item); + _mExportTypes.push_back(std::move(item)); } } @@ -1670,7 +1670,7 @@ void Application::slotBeforeRecompute(const Document& doc) void Application::slotOpenTransaction(const Document& d, string s) { - this->signalOpenTransaction(d, s); + this->signalOpenTransaction(d, std::move(s)); } void Application::slotCommitTransaction(const Document& d) @@ -1748,7 +1748,7 @@ void Application::destruct() // now save all other parameter files auto& paramMgr = _pcSingleton->mpcPramManager; - for (auto it : paramMgr) { + for (const auto &it : paramMgr) { if ((it.second != _pcSysParamMngr) && (it.second != _pcUserParamMngr)) { if (it.second->HasSerializer() && !it.second->IgnoreSave()) { Base::Console().Log("Saving %s...\n", it.first.c_str()); @@ -2454,7 +2454,7 @@ void processProgramOptions(const variables_map& vm, std::map(); - mConfig["SaveFile"] = file; + mConfig["SaveFile"] = vm["output"].as(); } if (vm.count("hidden")) { @@ -2524,7 +2523,7 @@ void processProgramOptions(const variables_map& vm, std::map Application::getCmdLineFiles() // getting file name std::ostringstream temp; temp << "OpenFile" << i; - - std::string file(mConfig[temp.str()]); - files.push_back(file); + files.emplace_back(mConfig[temp.str()]); } return files; @@ -3405,7 +3402,7 @@ void Application::ExtractUserPath() // Set the default macro directory // - std::vector macrodirs = subdirs; + std::vector macrodirs = std::move(subdirs); // Last use in this method, just move macrodirs.emplace_back("Macro"); std::filesystem::path macro = findPath(dataHome, customData, macrodirs, true); mConfig["UserMacroPath"] = Base::FileInfo::pathToString(macro) + PATHSEP; diff --git a/src/App/CMakeLists.txt b/src/App/CMakeLists.txt index e367a4cea1..697512470b 100644 --- a/src/App/CMakeLists.txt +++ b/src/App/CMakeLists.txt @@ -20,9 +20,6 @@ IF(DOCDIR) add_definitions(-DDOCDIR="${DOCDIR}") ENDIF(DOCDIR) -#if you want to use the old DAG structure uncomment this line -#add_definitions(-DUSE_OLD_DAG) - # ----------------------------------------------------------------------------- #write relevant cmake variables to a file for later access with python. Exported are all variables @@ -56,6 +53,10 @@ include_directories( ${CMAKE_BINARY_DIR}/src ${CMAKE_SOURCE_DIR}/src ${CMAKE_CURRENT_BINARY_DIR} +) + +include_directories( + SYSTEM ${Boost_INCLUDE_DIRS} ${PYCXX_INCLUDE_DIR} ${Python3_INCLUDE_DIRS} @@ -274,7 +275,6 @@ SET(FreeCADApp_CPP_SRCS AutoTransaction.cpp Branding.cpp CleanupProcess.cpp - Color.cpp ColorModel.cpp ComplexGeoData.cpp ComplexGeoDataPyImp.cpp @@ -304,7 +304,6 @@ SET(FreeCADApp_HPP_SRCS AutoTransaction.h Branding.h CleanupProcess.h - Color.h ColorModel.h ComplexGeoData.h ElementMap.h diff --git a/src/App/ColorModel.cpp b/src/App/ColorModel.cpp index 80e778c244..706ad52b24 100644 --- a/src/App/ColorModel.cpp +++ b/src/App/ColorModel.cpp @@ -138,8 +138,8 @@ void ColorField::rebuild() fConstant = -fAscent * fMin; } -// fuellt das Array von Farbe 1, Index 1 bis Farbe 2, Index 2 -void ColorField::interpolate(Color clCol1, std::size_t usInd1, Color clCol2, std::size_t usInd2) +// fills the array from color 1, index 1 to color 2, index 2 +void ColorField::interpolate(Base::Color clCol1, std::size_t usInd1, Base::Color clCol2, std::size_t usInd2) { float fStep = 1.0f, fLen = float(usInd2 - usInd1); @@ -154,7 +154,7 @@ void ColorField::interpolate(Color clCol1, std::size_t usInd1, Color clCol2, std float ucR = clCol1.r + fR * fStep; float ucG = clCol1.g + fG * fStep; float ucB = clCol1.b + fB * fStep; - colorField[i] = Color(ucR, ucG, ucB); + colorField[i] = Base::Color(ucR, ucG, ucB); fStep += 1.0f; } } @@ -370,20 +370,20 @@ bool ColorLegend::setValue(std::size_t ulPos, float fVal) } } -Color ColorLegend::getColor(std::size_t ulPos) const +Base::Color ColorLegend::getColor(std::size_t ulPos) const { if (ulPos < colorFields.size()) { return colorFields[ulPos]; } else { - return Color(); + return Base::Color(); } } // color as: 0x00rrggbb uint32_t ColorLegend::getPackedColor(std::size_t ulPos) const { - Color clRGB = getColor(ulPos); + Base::Color clRGB = getColor(ulPos); return clRGB.getPackedValue(); } @@ -402,7 +402,7 @@ std::size_t ColorLegend::addMin(const std::string& rclName) names.push_front(rclName); values.push_front(values.front() - 1.0f); - Color clNewRGB; + Base::Color clNewRGB; clNewRGB.r = ((float)rand() / (float)RAND_MAX); clNewRGB.g = ((float)rand() / (float)RAND_MAX); clNewRGB.b = ((float)rand() / (float)RAND_MAX); @@ -417,7 +417,7 @@ std::size_t ColorLegend::addMax(const std::string& rclName) names.push_back(rclName); values.push_back(values.back() + 1.0f); - Color clNewRGB; + Base::Color clNewRGB; clNewRGB.r = ((float)rand() / (float)RAND_MAX); clNewRGB.g = ((float)rand() / (float)RAND_MAX); clNewRGB.b = ((float)rand() / (float)RAND_MAX); @@ -481,7 +481,7 @@ void ColorLegend::resize(std::size_t ulCt) bool ColorLegend::setColor(std::size_t ulPos, float ucRed, float ucGreen, float ucBlue) { if (ulPos < names.size()) { - colorFields[ulPos] = Color(ucRed, ucGreen, ucBlue); + colorFields[ulPos] = Base::Color(ucRed, ucGreen, ucBlue); return true; } diff --git a/src/App/ColorModel.h b/src/App/ColorModel.h index 8a5a897b3f..34379f81b3 100644 --- a/src/App/ColorModel.h +++ b/src/App/ColorModel.h @@ -32,7 +32,6 @@ #include #include - namespace App { @@ -64,7 +63,7 @@ namespace App class AppExport ValueFloatToRGB { public: - virtual Color getColor(float fVal) const = 0; + virtual Base::Color getColor(float fVal) const = 0; protected: ValueFloatToRGB() = default; @@ -87,7 +86,7 @@ public: { return colors.size(); } - std::vector colors; + std::vector colors; }; class AppExport ColorModelBlueGreenRed: public ColorModel @@ -96,11 +95,11 @@ public: ColorModelBlueGreenRed() : ColorModel(5) { - colors[0] = Color(0, 0, 1); - colors[1] = Color(0, 1, 1); - colors[2] = Color(0, 1, 0); - colors[3] = Color(1, 1, 0); - colors[4] = Color(1, 0, 0); + colors[0] = Base::Color(0, 0, 1); + colors[1] = Base::Color(0, 1, 1); + colors[2] = Base::Color(0, 1, 0); + colors[3] = Base::Color(1, 1, 0); + colors[4] = Base::Color(1, 0, 0); } }; @@ -110,9 +109,9 @@ public: ColorModelBlueCyanGreen() : ColorModel(3) { - colors[0] = Color(0, 0, 1); - colors[1] = Color(0, 1, 1); - colors[2] = Color(0, 1, 0); + colors[0] = Base::Color(0, 0, 1); + colors[1] = Base::Color(0, 1, 1); + colors[2] = Base::Color(0, 1, 0); } }; @@ -122,9 +121,9 @@ public: ColorModelGreenYellowRed() : ColorModel(3) { - colors[0] = Color(0, 1, 0); - colors[1] = Color(1, 1, 0); - colors[2] = Color(1, 0, 0); + colors[0] = Base::Color(0, 1, 0); + colors[1] = Base::Color(1, 1, 0); + colors[2] = Base::Color(1, 0, 0); } }; @@ -134,11 +133,11 @@ public: ColorModelRedGreenBlue() : ColorModel(5) { - colors[0] = Color(1, 0, 0); - colors[1] = Color(1, 1, 0); - colors[2] = Color(0, 1, 0); - colors[3] = Color(0, 1, 1); - colors[4] = Color(0, 0, 1); + colors[0] = Base::Color(1, 0, 0); + colors[1] = Base::Color(1, 1, 0); + colors[2] = Base::Color(0, 1, 0); + colors[3] = Base::Color(0, 1, 1); + colors[4] = Base::Color(0, 0, 1); } }; @@ -148,9 +147,9 @@ public: ColorModelGreenCyanBlue() : ColorModel(3) { - colors[0] = Color(0, 1, 0); - colors[1] = Color(0, 1, 1); - colors[2] = Color(0, 0, 1); + colors[0] = Base::Color(0, 1, 0); + colors[1] = Base::Color(0, 1, 1); + colors[2] = Base::Color(0, 0, 1); } }; @@ -160,9 +159,9 @@ public: ColorModelRedYellowGreen() : ColorModel(3) { - colors[0] = Color(1, 0, 0); - colors[1] = Color(1, 1, 0); - colors[2] = Color(0, 1, 0); + colors[0] = Base::Color(1, 0, 0); + colors[1] = Base::Color(1, 1, 0); + colors[2] = Base::Color(0, 1, 0); } }; @@ -172,11 +171,11 @@ public: ColorModelBlueWhiteRed() : ColorModel(5) { - colors[0] = Color(0, 0, 1); - colors[1] = Color(float(85.0 / 255), float(170.0 / 255), 1); - colors[2] = Color(1, 1, 1); - colors[3] = Color(1, float(85.0 / 255), 0); - colors[4] = Color(1, 0, 0); + colors[0] = Base::Color(0, 0, 1); + colors[1] = Base::Color(float(85.0 / 255), float(170.0 / 255), 1); + colors[2] = Base::Color(1, 1, 1); + colors[3] = Base::Color(1, float(85.0 / 255), 0); + colors[4] = Base::Color(1, 0, 0); } }; @@ -186,9 +185,9 @@ public: ColorModelBlueWhite() : ColorModel(3) { - colors[0] = Color(0, 0, 1); - colors[1] = Color(float(85.0 / 255), float(170.0 / 255), 1); - colors[2] = Color(1, 1, 1); + colors[0] = Base::Color(0, 0, 1); + colors[1] = Base::Color(float(85.0 / 255), float(170.0 / 255), 1); + colors[2] = Base::Color(1, 1, 1); } }; @@ -198,9 +197,9 @@ public: ColorModelWhiteRed() : ColorModel(3) { - colors[0] = Color(1, 1, 1); - colors[1] = Color(1, float(85.0 / 255), 0); - colors[2] = Color(1, 0, 0); + colors[0] = Base::Color(1, 1, 1); + colors[1] = Base::Color(1, float(85.0 / 255), 0); + colors[2] = Base::Color(1, 0, 0); } }; @@ -210,8 +209,8 @@ public: ColorModelBlackWhite() : ColorModel(2) { - colors[0] = Color(0, 0, 0); - colors[1] = Color(1, 1, 1); + colors[0] = Base::Color(0, 0, 0); + colors[1] = Base::Color(1, 1, 1); } }; @@ -221,8 +220,8 @@ public: ColorModelBlackGray() : ColorModel(2) { - colors[0] = Color(0.0f, 0.0f, 0.0f); - colors[1] = Color(0.5f, 0.5f, 0.5f); + colors[0] = Base::Color(0.0f, 0.0f, 0.0f); + colors[1] = Base::Color(0.5f, 0.5f, 0.5f); } }; @@ -232,8 +231,8 @@ public: ColorModelGrayWhite() : ColorModel(2) { - colors[0] = Color(0.5f, 0.5f, 0.5f); - colors[1] = Color(1.0f, 1.0f, 1.0f); + colors[0] = Base::Color(0.5f, 0.5f, 0.5f); + colors[1] = Base::Color(1.0f, 1.0f, 1.0f); } }; @@ -243,8 +242,8 @@ public: ColorModelWhiteBlack() : ColorModel(2) { - colors[0] = Color(1, 1, 1); - colors[1] = Color(0, 0, 0); + colors[0] = Base::Color(1, 1, 1); + colors[1] = Base::Color(0, 0, 0); } }; @@ -254,8 +253,8 @@ public: ColorModelWhiteGray() : ColorModel(2) { - colors[0] = Color(1.0f, 1.0f, 1.0f); - colors[1] = Color(0.5f, 0.5f, 0.5f); + colors[0] = Base::Color(1.0f, 1.0f, 1.0f); + colors[1] = Base::Color(0.5f, 0.5f, 0.5f); } }; @@ -265,8 +264,8 @@ public: ColorModelGrayBlack() : ColorModel(2) { - colors[0] = Color(0.5f, 0.5f, 0.5f); - colors[1] = Color(0.0f, 0.0f, 0.0f); + colors[0] = Base::Color(0.5f, 0.5f, 0.5f); + colors[1] = Base::Color(0.0f, 0.0f, 0.0f); } }; @@ -320,7 +319,7 @@ public: { return colorModel; } - void setDirect(std::size_t usInd, Color clCol) + void setDirect(std::size_t usInd, Base::Color clCol) { colorField[usInd] = clCol; } @@ -333,11 +332,11 @@ public: return fMax; } - Color getColor(std::size_t usIndex) const + Base::Color getColor(std::size_t usIndex) const { return colorField[usIndex]; } - inline Color getColor(float fVal) const; + inline Base::Color getColor(float fVal) const; inline std::size_t getColorIndex(float fVal) const; protected: @@ -345,13 +344,13 @@ protected: float fMin, fMax; float fAscent, fConstant; // Index := _fConstant + _fAscent * WERT std::size_t ctColors; - std::vector colorField; + std::vector colorField; void rebuild(); - void interpolate(Color clCol1, std::size_t usPos1, Color clCol2, std::size_t usPos2); + void interpolate(Base::Color clCol1, std::size_t usPos1, Base::Color clCol2, std::size_t usPos2); }; -inline Color ColorField::getColor(float fVal) const +inline Base::Color ColorField::getColor(float fVal) const { // if the value is outside or at the border of the range std::size_t ct = colorModel.getCountColors() - 1; @@ -362,16 +361,16 @@ inline Color ColorField::getColor(float fVal) const return colorModel.colors[ct]; } - // get the color field position (with 0 < t < 1) + // get the Base::Color field position (with 0 < t < 1) float t = (fVal - fMin) / (fMax - fMin); - Color col(1.0f, 1.0f, 1.0f); // white as default + Base::Color col(1.0f, 1.0f, 1.0f); // white as default for (std::size_t i = 0; i < ct; i++) { float r = (float)(i + 1) / (float)ct; if (t < r) { // calculate the exact position in the subrange float s = t * float(ct) - float(i); - Color c1 = colorModel.colors[i]; - Color c2 = colorModel.colors[i + 1]; + Base::Color c1 = colorModel.colors[i]; + Base::Color c2 = colorModel.colors[i + 1]; col.r = (1.0f - s) * c1.r + s * c2.r; col.g = (1.0f - s) * c1.g + s * c2.g; col.b = (1.0f - s) * c1.b + s * c2.b; @@ -484,11 +483,11 @@ public: return profile.fMax; } - inline Color getColor(float fVal) const; + inline Base::Color getColor(float fVal) const; inline std::size_t getColorIndex(float fVal) const; private: - inline Color _getColor(float fVal) const; + inline Base::Color _getColor(float fVal) const; protected: void createStandardPacks(); @@ -525,7 +524,7 @@ public: void removeFirst(); void removeLast(); - Color getColor(std::size_t ulPos) const; + Base::Color getColor(std::size_t ulPos) const; uint32_t getPackedColor(std::size_t ulPos) const; bool setColor(std::size_t ulPos, float ucRed, float ucGreen, float ucBlue); bool setColor(std::size_t ulPos, unsigned long ulColor); @@ -548,17 +547,17 @@ public: inline float getMinValue() const; inline float getMaxValue() const; - inline Color getColor(float fVal) const; + inline Base::Color getColor(float fVal) const; inline std::size_t getColorIndex(float fVal) const; protected: - std::deque colorFields; + std::deque colorFields; std::deque names; std::deque values; bool outsideGrayed {false}; }; -inline Color ColorLegend::getColor(float fVal) const +inline Base::Color ColorLegend::getColor(float fVal) const { std::deque::const_iterator pI; for (pI = values.begin(); pI != values.end(); ++pI) { @@ -569,7 +568,7 @@ inline Color ColorLegend::getColor(float fVal) const if (outsideGrayed) { if ((pI == values.begin()) || (pI == values.end())) { - return Color(0.5f, 0.5f, 0.5f); + return Base::Color(0.5f, 0.5f, 0.5f); } else { return colorFields[pI - values.begin() - 1]; @@ -617,23 +616,23 @@ inline float ColorLegend::getMaxValue() const return values.back(); } -inline Color ColorGradient::getColor(float fVal) const +inline Base::Color ColorGradient::getColor(float fVal) const { - Color color = _getColor(fVal); + Base::Color Color = _getColor(fVal); if (isOutsideInvisible()) { if (isOutOfRange(fVal)) { - color.a = 0.2F; + Color.a = 0.2F; } } - return color; + return Color; } -inline Color ColorGradient::_getColor(float fVal) const +inline Base::Color ColorGradient::_getColor(float fVal) const { if (isOutsideGrayed()) { if (isOutOfRange(fVal)) { - return Color(0.5f, 0.5f, 0.5f); + return Base::Color(0.5f, 0.5f, 0.5f); } } diff --git a/src/App/Document.cpp b/src/App/Document.cpp index f0c5d0c0c6..ecf12cc3a7 100644 --- a/src/App/Document.cpp +++ b/src/App/Document.cpp @@ -78,13 +78,6 @@ recompute path. Also, it enables more complicated dependencies beyond trees. #include #include -#ifdef USE_OLD_DAG -#include -#include -#include -#include -#endif // USE_OLD_DAG - #include #include #include @@ -2934,15 +2927,7 @@ std::vector Document::getDependentDocuments(std::vector& objs) { -#ifdef USE_OLD_DAG - _buildDependencyList(objs.empty() ? d->objectArray : objs, - false, - 0, - &d->DepList, - &d->VertexObjectList); -#else (void)objs; -#endif } /** @@ -2973,156 +2958,6 @@ void Document::renameObjectIdentifiers( } } -#ifdef USE_OLD_DAG -int Document::recompute(const std::vector& objs, bool force) -{ - if (testStatus(Document::Recomputing)) { - // this is clearly a bug in the calling instance - throw Base::RuntimeError("Nested recomputes of a document are not allowed"); - } - - int objectCount = 0; - - // The 'SkipRecompute' flag can be (tmp.) set to avoid too many - // time expensive recomputes - if (!force && testStatus(Document::SkipRecompute)) { - return 0; - } - - Base::ObjectStatusLocker exe(Document::Recomputing, this); - - // delete recompute log - d->clearRecomputeLog(); - - // updates the dependency graph - _rebuildDependencyList(objs); - - std::list make_order; - DependencyList::out_edge_iterator j, jend; - - try { - // this sort gives the execute - boost::topological_sort(d->DepList, std::front_inserter(make_order)); - } - catch (const std::exception& e) { - std::cerr << "Document::recompute: " << e.what() << std::endl; - return -1; - } - - // caching vertex to DocObject - for (std::map::const_iterator It1 = d->VertexObjectList.begin(); - It1 != d->VertexObjectList.end(); - ++It1) { - d->vertexMap[It1->second] = It1->first; - } - -#ifdef FC_LOGFEATUREUPDATE - std::clog << "make ordering: " << std::endl; -#endif - - std::set recomputeList; - - for (std::list::reverse_iterator i = make_order.rbegin(); i != make_order.rend(); ++i) { - DocumentObject* Cur = d->vertexMap[*i]; - // Because of PropertyXLink, we should account for external objects - // TODO: make sure it is safe to rely on getNameInDocument() to check if - // object is in the document. If it crashes, then we should fix the code - // to properly nullify getNameInDocument(), rather than revert back to - // the inefficient isIn() - // if (!Cur || !isIn(Cur)) continue; - if (!Cur || !Cur->getNameInDocument()) { - continue; - } -#ifdef FC_LOGFEATUREUPDATE - std::clog << Cur->getNameInDocument() << " dep on:"; -#endif - bool NeedUpdate = false; - - // ask the object if it should be recomputed - if (Cur->mustExecute() == 1 || Cur->ExpressionEngine.depsAreTouched()) { -#ifdef FC_LOGFEATUREUPDATE - std::clog << "[touched]"; -#endif - NeedUpdate = true; - } - else { // if (Cur->mustExecute() == -1) - // update if one of the dependencies is touched - for (boost::tie(j, jend) = out_edges(*i, d->DepList); j != jend; ++j) { - DocumentObject* Test = d->vertexMap[target(*j, d->DepList)]; - - if (!Test) { - continue; - } -#ifdef FC_LOGFEATUREUPDATE - std::clog << " " << Test->getNameInDocument(); -#endif - if (Test->isTouched()) { - NeedUpdate = true; -#ifdef FC_LOGFEATUREUPDATE - std::clog << "[touched]"; -#endif - } - } - } - // if one touched recompute - if (NeedUpdate) { - Cur->touch(); -#ifdef FC_LOGFEATUREUPDATE - std::clog << " => Recompute feature"; -#endif - recomputeList.insert(Cur); - } -#ifdef FC_LOGFEATUREUPDATE - std::clog << std::endl; -#endif - } - -#ifdef FC_LOGFEATUREUPDATE - std::clog << "Have to recompute the following document objects" << std::endl; - for (std::set::const_iterator it = recomputeList.begin(); - it != recomputeList.end(); - ++it) { - std::clog << " " << (*it)->getNameInDocument() << std::endl; - } -#endif - - for (std::list::reverse_iterator i = make_order.rbegin(); i != make_order.rend(); ++i) { - DocumentObject* Cur = d->vertexMap[*i]; - if (!Cur || !isIn(Cur)) { - continue; - } - - if (recomputeList.find(Cur) != recomputeList.end() - || Cur->ExpressionEngine.depsAreTouched()) { - if (_recomputeFeature(Cur)) { - // if something happened break execution of recompute - d->vertexMap.clear(); - return -1; - } - signalRecomputedObject(*Cur); - ++objectCount; - } - } - - // reset all touched - for (std::map::iterator it = d->vertexMap.begin(); - it != d->vertexMap.end(); - ++it) { - // TODO: check the TODO comments above for details - // if ((it->second) && isIn(it->second)) - if ((it->second) && it->second->getNameInDocument()) { - it->second->purgeTouched(); - } - } - d->vertexMap.clear(); - - signalRecomputed(*this); - - return objectCount; -} - -#else // ifdef USE_OLD_DAG - int Document::recompute(const std::vector& objs, bool force, bool* hasError, @@ -3315,8 +3150,6 @@ int Document::recompute(const std::vector& objs, return objectCount; } -#endif // USE_OLD_DAG - /*! Does almost the same as topologicalSort() until no object with an input degree of zero can be found. It then searches for objects with an output degree of zero until neither @@ -3912,20 +3745,6 @@ void Document::removeObject(const char* sName) signalTransactionRemove(*pos->second, 0); } -#ifdef USE_OLD_DAG - if (!d->vertexMap.empty()) { - // recompute of document is running - for (std::map::iterator it = d->vertexMap.begin(); - it != d->vertexMap.end(); - ++it) { - if (it->second == pos->second) { - it->second = 0; // just nullify the pointer - break; - } - } - } -#endif // USE_OLD_DAG - // Before deleting we must nullify all dependent objects breakDependency(pos->second, true); diff --git a/src/App/DocumentObject.cpp b/src/App/DocumentObject.cpp index ef4fdde3a9..138161db7f 100644 --- a/src/App/DocumentObject.cpp +++ b/src/App/DocumentObject.cpp @@ -468,27 +468,11 @@ std::vector DocumentObject::getOutListOfProperty(App::Prop return ret; } -#ifdef USE_OLD_DAG -std::vector DocumentObject::getInList(void) const -{ - if (_pDoc) { - return _pDoc->getInList(this); - } - else { - return std::vector(); - } -} - -#else // ifndef USE_OLD_DAG - const std::vector& DocumentObject::getInList() const { return _inList; } -#endif // if USE_OLD_DAG - - // The original algorithm is highly inefficient in some special case. // Considering an object is linked by every other objects. After excluding this // object, there is another object linked by every other of the remaining @@ -513,41 +497,6 @@ void DocumentObject::getInListEx(std::set& inSet, bool recursive, std::vector* inList) const { -#ifdef USE_OLD_DAG - std::map> outLists; - - // Old DAG does not have pre-built InList, and must calculate The InList by - // going through all objects' OutLists. So we collect all objects and their - // outLists first here. - for (auto doc : GetApplication().getDocuments()) { - for (auto obj : doc->getObjects()) { - if (!obj || !obj->isAttachedToDocument() || obj == this) { - continue; - } - const auto& outList = obj->getOutList(); - outLists[obj].insert(outList.begin(), outList.end()); - } - } - - std::stack pendings; - pendings.push(const_cast(this)); - while (pendings.size()) { - auto obj = pendings.top(); - pendings.pop(); - for (auto& v : outLists) { - if (v.first == obj) { - continue; - } - auto& outList = v.second; - // Check the outList to see if the object is there, and pend the - // object for recursive check if it's not already in the inList - if (outList.find(obj) != outList.end() && inSet.insert(v.first).second && recursive) { - pendings.push(v.first); - } - } - } -#else // USE_OLD_DAG - if (!recursive) { inSet.insert(_inList.begin(), _inList.end()); if (inList) { @@ -570,8 +519,6 @@ void DocumentObject::getInListEx(std::set& inSet, } } } - -#endif } std::set DocumentObject::getInListEx(bool recursive) const @@ -618,7 +565,6 @@ std::vector DocumentObject::getOutListRecursive() const // helper for isInInListRecursive() bool _isInInListRecursive(const DocumentObject* act, const DocumentObject* checkObj, int depth) { -#ifndef USE_OLD_DAG for (auto obj : act->getInList()) { if (obj == checkObj) { return true; @@ -633,11 +579,6 @@ bool _isInInListRecursive(const DocumentObject* act, const DocumentObject* check return true; } } -#else - (void)act; - (void)checkObj; - (void)depth; -#endif return false; } @@ -649,23 +590,17 @@ bool DocumentObject::isInInListRecursive(DocumentObject* linkTo) const bool DocumentObject::isInInList(DocumentObject* linkTo) const { -#ifndef USE_OLD_DAG if (std::find(_inList.begin(), _inList.end(), linkTo) != _inList.end()) { return true; } else { return false; } -#else - (void)linkTo; - return false; -#endif } // helper for isInOutListRecursive() bool _isInOutListRecursive(const DocumentObject* act, const DocumentObject* checkObj, int depth) { -#ifndef USE_OLD_DAG for (auto obj : act->getOutList()) { if (obj == checkObj) { return true; @@ -680,11 +615,6 @@ bool _isInOutListRecursive(const DocumentObject* act, const DocumentObject* chec return true; } } -#else - (void)act; - (void)checkObj; - (void)depth; -#endif return false; } @@ -1321,29 +1251,21 @@ void DocumentObject::unsetupObject() void App::DocumentObject::_removeBackLink(DocumentObject* rmvObj) { -#ifndef USE_OLD_DAG // do not use erase-remove idom, as this erases ALL entries that match. we only want to remove a // single one. auto it = std::find(_inList.begin(), _inList.end(), rmvObj); if (it != _inList.end()) { _inList.erase(it); } -#else - (void)rmvObj; -#endif } void App::DocumentObject::_addBackLink(DocumentObject* newObj) { -#ifndef USE_OLD_DAG // we need to add all links, even if they are available multiple times. The reason for this is // the removal: If a link loses this object it removes the backlink. If we would have added it // only once this removal would clear the object from the inlist, even though there may be other // link properties from this object that link to us. _inList.push_back(newObj); -#else - (void)newObj; -#endif // USE_OLD_DAG } int DocumentObject::setElementVisible(const char* element, bool visible) diff --git a/src/App/DocumentObject.h b/src/App/DocumentObject.h index c26a085731..860d3af357 100644 --- a/src/App/DocumentObject.h +++ b/src/App/DocumentObject.h @@ -293,12 +293,8 @@ public: void clearOutListCache() const; /// get all possible paths from this to another object following the OutList std::vector> getPathsByOutList(App::DocumentObject* to) const; -#ifdef USE_OLD_DAG /// get all objects link to this object - std::vector getInList(void) const -#else const std::vector& getInList() const; -#endif /// get all objects link directly or indirectly to this object std::vector getInListRecursive() const; /** Get a set of all objects linking to this object, including possible external parent objects diff --git a/src/App/FeatureTest.cpp b/src/App/FeatureTest.cpp index 4d5592447f..1a2ab12c21 100644 --- a/src/App/FeatureTest.cpp +++ b/src/App/FeatureTest.cpp @@ -70,7 +70,7 @@ FeatureTest::FeatureTest() ADD_PROPERTY(ConstraintFloat, (5.0)); ConstraintFloat.setConstraints(&floatPercent); - App::Color c; + Base::Color c; App::Material mat(App::Material::GOLD); ADD_PROPERTY(Colour, (c)); ADD_PROPERTY(ColourList, (c)); diff --git a/src/App/Material.cpp b/src/App/Material.cpp index 89c55430d1..3da7b57c23 100644 --- a/src/App/Material.cpp +++ b/src/App/Material.cpp @@ -327,7 +327,7 @@ App::Material Material::getDefaultAppearance() ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); - auto getColor = [hGrp](const char* parameter, App::Color& color) { + auto getColor = [hGrp](const char* parameter, Base::Color& color) { uint32_t packed = color.getPackedRGB(); packed = hGrp->GetUnsigned(parameter, packed); color.setPackedRGB(packed); @@ -351,10 +351,10 @@ App::Material Material::getDefaultAppearance() float red = static_cast(intRandom(0, 255)) / 255.0F; float green = static_cast(intRandom(0, 255)) / 255.0F; float blue = static_cast(intRandom(0, 255)) / 255.0F; - mat.diffuseColor = App::Color(red, green, blue); + mat.diffuseColor = Base::Color(red, green, blue); } else { - // Color = (204, 204, 230) = 3435980543UL + // Base::Color = (204, 204, 230) = 3435980543UL getColor("DefaultShapeColor", mat.diffuseColor); } diff --git a/src/App/Material.h b/src/App/Material.h index e578d00b62..9a6bcad85e 100644 --- a/src/App/Material.h +++ b/src/App/Material.h @@ -24,7 +24,7 @@ #ifndef APP_MATERIAL_H #define APP_MATERIAL_H -#include +#include namespace App { @@ -104,7 +104,7 @@ public: * \li Ruby * \li Emerald * Furthermore there two additional modes \a Default which defines a kind of grey metallic and - * user defined that does nothing. The Color and the other properties of the material are + * user defined that does nothing. The Base::Color and the other properties of the material are * defined in the range [0-1]. If \a MatName is an unknown material name then the type * USER_DEFINED is set and the material doesn't get changed. */ @@ -125,10 +125,10 @@ public: /** @name Properties */ //@{ // NOLINTBEGIN - Color ambientColor; /**< Defines the ambient color. */ - Color diffuseColor; /**< Defines the diffuse color. */ - Color specularColor; /**< Defines the specular color. */ - Color emissiveColor; /**< Defines the emissive color. */ + Base::Color ambientColor; /**< Defines the ambient color. */ + Base::Color diffuseColor; /**< Defines the diffuse color. */ + Base::Color specularColor; /**< Defines the specular color. */ + Base::Color emissiveColor; /**< Defines the emissive color. */ float shininess; float transparency; std::string image; diff --git a/src/App/MaterialPy.xml b/src/App/MaterialPy.xml index 60b2567f9d..1b1fca66fc 100644 --- a/src/App/MaterialPy.xml +++ b/src/App/MaterialPy.xml @@ -64,7 +64,7 @@ Satin, Metalized, Neon GNC, Chrome, Aluminium, Obsidian, Neon PHC, Jade, Ruby or public: - static App::Color toColor(PyObject* value); + static Base::Color toColor(PyObject* value); diff --git a/src/App/MaterialPyImp.cpp b/src/App/MaterialPyImp.cpp index 867ac18280..6bdd068be6 100644 --- a/src/App/MaterialPyImp.cpp +++ b/src/App/MaterialPyImp.cpp @@ -32,9 +32,9 @@ using namespace App; -Color MaterialPy::toColor(PyObject* value) +Base::Color MaterialPy::toColor(PyObject* value) { - Color cCol; + Base::Color cCol; if (PyTuple_Check(value) && (PyTuple_Size(value) == 3 || PyTuple_Size(value) == 4)) { PyObject* item {}; item = PyTuple_GetItem(value, 0); diff --git a/src/App/PropertyLinks.cpp b/src/App/PropertyLinks.cpp index 8869e199e6..070ce1c5fc 100644 --- a/src/App/PropertyLinks.cpp +++ b/src/App/PropertyLinks.cpp @@ -690,7 +690,6 @@ PropertyLink::~PropertyLink() void PropertyLink::resetLink() { // in case this property gets dynamically removed -#ifndef USE_OLD_DAG // maintain the back link in the DocumentObject class if it is from a document object if (_pcScope != LinkScope::Hidden && _pcLink && getContainer() && getContainer()->isDerivedFrom()) { @@ -703,8 +702,6 @@ void PropertyLink::resetLink() } } } -#endif - _pcLink = nullptr; } void PropertyLink::setValue(App::DocumentObject* lValue) @@ -716,7 +713,7 @@ void PropertyLink::setValue(App::DocumentObject* lValue) } aboutToSetValue(); -#ifndef USE_OLD_DAG + // maintain the back link in the DocumentObject class if it is from a document object if (_pcScope != LinkScope::Hidden && parent) { // before accessing internals make sure the object is not about to be destroyed @@ -730,7 +727,7 @@ void PropertyLink::setValue(App::DocumentObject* lValue) } } } -#endif + _pcLink = lValue; hasSetValue(); } @@ -895,7 +892,7 @@ PropertyLinkList::PropertyLinkList() = default; PropertyLinkList::~PropertyLinkList() { // in case this property gety dynamically removed -#ifndef USE_OLD_DAG + // maintain the back link in the DocumentObject class if (_pcScope != LinkScope::Hidden && !_lValueList.empty() && getContainer() && getContainer()->isDerivedFrom()) { @@ -910,7 +907,6 @@ PropertyLinkList::~PropertyLinkList() } } } -#endif } void PropertyLinkList::setSize(int newSize) @@ -921,11 +917,10 @@ void PropertyLinkList::setSize(int newSize) continue; } _nameMap.erase(obj->getNameInDocument()); -#ifndef USE_OLD_DAG + if (_pcScope != LinkScope::Hidden) { obj->_removeBackLink(static_cast(getContainer())); } -#endif } _lValueList.resize(newSize); } @@ -955,7 +950,6 @@ void PropertyLinkList::set1Value(int idx, DocumentObject* const& value) _nameMap.clear(); -#ifndef USE_OLD_DAG if (getContainer() && getContainer()->isDerivedFrom()) { App::DocumentObject* parent = static_cast(getContainer()); // before accessing internals make sure the object is not about to be destroyed @@ -969,7 +963,6 @@ void PropertyLinkList::set1Value(int idx, DocumentObject* const& value) } } } -#endif inherited::set1Value(idx, value); } @@ -993,7 +986,6 @@ void PropertyLinkList::setValues(const std::vector& value) } _nameMap.clear(); -#ifndef USE_OLD_DAG // maintain the back link in the DocumentObject class if (parent) { // before accessing internals make sure the object is not about to be destroyed @@ -1011,7 +1003,7 @@ void PropertyLinkList::setValues(const std::vector& value) } } } -#endif + inherited::setValues(value); } @@ -1298,7 +1290,7 @@ PropertyLinkSub::PropertyLinkSub() = default; PropertyLinkSub::~PropertyLinkSub() { // in case this property is dynamically removed -#ifndef USE_OLD_DAG + if (_pcLinkSub && getContainer() && getContainer()->isDerivedFrom()) { App::DocumentObject* parent = static_cast(getContainer()); @@ -1310,7 +1302,6 @@ PropertyLinkSub::~PropertyLinkSub() } } } -#endif } void PropertyLinkSub::setSyncSubObject(bool enable) @@ -1340,7 +1331,7 @@ void PropertyLinkSub::setValue(App::DocumentObject* lValue, } } aboutToSetValue(); -#ifndef USE_OLD_DAG + if (parent) { // before accessing internals make sure the object is not about to be destroyed // otherwise the backlink contains dangling pointers @@ -1353,7 +1344,7 @@ void PropertyLinkSub::setValue(App::DocumentObject* lValue, } } } -#endif + _pcLinkSub = lValue; _cSubList = std::move(subs); if (shadows.size() == _cSubList.size()) { @@ -2176,7 +2167,7 @@ PropertyLinkSubList::PropertyLinkSubList() = default; PropertyLinkSubList::~PropertyLinkSubList() { // in case this property is dynamically removed -#ifndef USE_OLD_DAG + // maintain backlinks if (!_lValueList.empty() && getContainer() && getContainer()->isDerivedFrom()) { @@ -2191,7 +2182,6 @@ PropertyLinkSubList::~PropertyLinkSubList() } } } -#endif } void PropertyLinkSubList::setSyncSubObject(bool enable) @@ -2228,7 +2218,6 @@ void PropertyLinkSubList::setValue(DocumentObject* lValue, const char* SubName) auto parent = Base::freecad_dynamic_cast(getContainer()); verifyObject(lValue, parent); -#ifndef USE_OLD_DAG // maintain backlinks if (parent) { // before accessing internals make sure the object is not about to be destroyed @@ -2244,7 +2233,6 @@ void PropertyLinkSubList::setValue(DocumentObject* lValue, const char* SubName) } } } -#endif if (lValue) { aboutToSetValue(); @@ -2276,7 +2264,6 @@ void PropertyLinkSubList::setValues(const std::vector& lValue, "PropertyLinkSubList::setValues: size of subelements list != size of objects list"); } -#ifndef USE_OLD_DAG // maintain backlinks. if (parent) { // before accessing internals make sure the object is not about to be destroyed @@ -2299,7 +2286,6 @@ void PropertyLinkSubList::setValues(const std::vector& lValue, } } } -#endif aboutToSetValue(); _lValueList = lValue; @@ -2338,7 +2324,6 @@ void PropertyLinkSubList::setValues(std::vector&& lValue, "PropertyLinkSubList::setValues: size of subelements list != size of objects list"); } -#ifndef USE_OLD_DAG // maintain backlinks. if (parent) { // before accessing internals make sure the object is not about to be destroyed @@ -2361,7 +2346,6 @@ void PropertyLinkSubList::setValues(std::vector&& lValue, } } } -#endif aboutToSetValue(); _lValueList = std::move(lValue); @@ -2382,7 +2366,6 @@ void PropertyLinkSubList::setValue(DocumentObject* lValue, const std::vector(getContainer()); verifyObject(lValue, parent); -#ifndef USE_OLD_DAG // maintain backlinks. if (parent) { // before accessing internals make sure the object is not about to be destroyed @@ -2403,7 +2386,6 @@ void PropertyLinkSubList::setValue(DocumentObject* lValue, const std::vector(getContainer()); verifyObject(obj, parent); -#ifndef USE_OLD_DAG // maintain backlinks. if (parent) { // before accessing internals make sure the object is not about to be destroyed @@ -2454,7 +2435,6 @@ void PropertyLinkSubList::addValue(App::DocumentObject* obj, } } } -#endif std::vector valueList; std::vector subList; @@ -3850,11 +3830,11 @@ void PropertyXLink::restoreLink(App::DocumentObject* lValue) setFlag(LinkDetached, false); setFlag(LinkRestoring); aboutToSetValue(); -#ifndef USE_OLD_DAG + if (!owner->testStatus(ObjectStatus::Destroy) && _pcScope != LinkScope::Hidden) { lValue->_addBackLink(owner); } -#endif + _pcLink = lValue; updateElementReference(nullptr); hasSetValue(); @@ -3910,7 +3890,7 @@ void PropertyXLink::setValue(App::DocumentObject* lValue, } setFlag(LinkDetached, false); -#ifndef USE_OLD_DAG + if (!owner->testStatus(ObjectStatus::Destroy) && _pcScope != LinkScope::Hidden) { if (_pcLink) { _pcLink->_removeBackLink(owner); @@ -3919,7 +3899,7 @@ void PropertyXLink::setValue(App::DocumentObject* lValue, lValue->_addBackLink(owner); } } -#endif + if (docInfo != info) { unlink(); docInfo = info; @@ -3969,11 +3949,11 @@ void PropertyXLink::setValue(std::string&& filename, } setFlag(LinkDetached, false); aboutToSetValue(); -#ifndef USE_OLD_DAG + if (_pcLink && !owner->testStatus(ObjectStatus::Destroy) && _pcScope != LinkScope::Hidden) { _pcLink->_removeBackLink(owner); } -#endif + _pcLink = nullptr; if (docInfo != info) { unlink(); @@ -5965,7 +5945,7 @@ void PropertyXLinkContainer::clearDeps() if (!owner || !owner->isAttachedToDocument()) { return; } -#ifndef USE_OLD_DAG + if (!owner->testStatus(ObjectStatus::Destroy)) { for (auto& v : _Deps) { auto obj = v.first; @@ -5975,7 +5955,7 @@ void PropertyXLinkContainer::clearDeps() } } } -#endif + _Deps.clear(); _XLinks.clear(); _LinkRestored = false; diff --git a/src/App/PropertyStandard.cpp b/src/App/PropertyStandard.cpp index c89e4d1b6f..ac6fe61e51 100644 --- a/src/App/PropertyStandard.cpp +++ b/src/App/PropertyStandard.cpp @@ -2223,7 +2223,7 @@ PropertyColor::~PropertyColor() = default; //************************************************************************** // Base class implementer -void PropertyColor::setValue(const Color& col) +void PropertyColor::setValue(const Base::Color& col) { aboutToSetValue(); _cCol = col; @@ -2244,7 +2244,7 @@ void PropertyColor::setValue(float r, float g, float b, float a) hasSetValue(); } -const Color& PropertyColor::getValue() const +const Base::Color& PropertyColor::getValue() const { return _cCol; } @@ -2267,7 +2267,7 @@ PyObject* PropertyColor::getPyObject() void PropertyColor::setPyObject(PyObject* value) { - App::Color cCol; + Base::Color cCol; if (PyTuple_Check(value) && (PyTuple_Size(value) == 3 || PyTuple_Size(value) == 4)) { PyObject* item; item = PyTuple_GetItem(value, 0); @@ -2407,7 +2407,7 @@ PyObject* PropertyColorList::getPyObject() return list; } -Color PropertyColorList::getPyValue(PyObject* item) const +Base::Color PropertyColorList::getPyValue(PyObject* item) const { PropertyColor col; col.setPyObject(item); @@ -2451,7 +2451,7 @@ void PropertyColorList::RestoreDocFile(Base::Reader& reader) Base::InputStream str(reader); uint32_t uCt = 0; str >> uCt; - std::vector values(uCt); + std::vector values(uCt); uint32_t value; // must be 32 bit long for (auto& it : values) { str >> value; @@ -2474,7 +2474,7 @@ void PropertyColorList::Paste(const Property& from) unsigned int PropertyColorList::getMemSize() const { - return static_cast(_lValueList.size() * sizeof(Color)); + return static_cast(_lValueList.size() * sizeof(Base::Color)); } //************************************************************************** @@ -2495,7 +2495,7 @@ void PropertyMaterial::setValue(const Material& mat) hasSetValue(); } -void PropertyMaterial::setValue(const Color& col) +void PropertyMaterial::setValue(const Base::Color& col) { setDiffuseColor(col); } @@ -2515,7 +2515,7 @@ const Material& PropertyMaterial::getValue() const return _cMat; } -void PropertyMaterial::setAmbientColor(const Color& col) +void PropertyMaterial::setAmbientColor(const Base::Color& col) { aboutToSetValue(); _cMat.ambientColor = col; @@ -2536,7 +2536,7 @@ void PropertyMaterial::setAmbientColor(uint32_t rgba) hasSetValue(); } -void PropertyMaterial::setDiffuseColor(const Color& col) +void PropertyMaterial::setDiffuseColor(const Base::Color& col) { aboutToSetValue(); _cMat.diffuseColor = col; @@ -2557,7 +2557,7 @@ void PropertyMaterial::setDiffuseColor(uint32_t rgba) hasSetValue(); } -void PropertyMaterial::setSpecularColor(const Color& col) +void PropertyMaterial::setSpecularColor(const Base::Color& col) { aboutToSetValue(); _cMat.specularColor = col; @@ -2578,7 +2578,7 @@ void PropertyMaterial::setSpecularColor(uint32_t rgba) hasSetValue(); } -void PropertyMaterial::setEmissiveColor(const Color& col) +void PropertyMaterial::setEmissiveColor(const Base::Color& col) { aboutToSetValue(); _cMat.emissiveColor = col; @@ -2613,22 +2613,22 @@ void PropertyMaterial::setTransparency(float val) hasSetValue(); } -const Color& PropertyMaterial::getAmbientColor() const +const Base::Color& PropertyMaterial::getAmbientColor() const { return _cMat.ambientColor; } -const Color& PropertyMaterial::getDiffuseColor() const +const Base::Color& PropertyMaterial::getDiffuseColor() const { return _cMat.diffuseColor; } -const Color& PropertyMaterial::getSpecularColor() const +const Base::Color& PropertyMaterial::getSpecularColor() const { return _cMat.specularColor; } -const Color& PropertyMaterial::getEmissiveColor() const +const Base::Color& PropertyMaterial::getEmissiveColor() const { return _cMat.emissiveColor; } @@ -2816,7 +2816,7 @@ void PropertyMaterialList::setValue(int index, const Material& mat) hasSetValue(); } -void PropertyMaterialList::setAmbientColor(const Color& col) +void PropertyMaterialList::setAmbientColor(const Base::Color& col) { aboutToSetValue(); setMinimumSizeOne(); @@ -2846,7 +2846,7 @@ void PropertyMaterialList::setAmbientColor(uint32_t rgba) hasSetValue(); } -void PropertyMaterialList::setAmbientColor(int index, const Color& col) +void PropertyMaterialList::setAmbientColor(int index, const Base::Color& col) { verifyIndex(index); @@ -2876,7 +2876,7 @@ void PropertyMaterialList::setAmbientColor(int index, uint32_t rgba) hasSetValue(); } -void PropertyMaterialList::setDiffuseColor(const Color& col) +void PropertyMaterialList::setDiffuseColor(const Base::Color& col) { aboutToSetValue(); setMinimumSizeOne(); @@ -2906,7 +2906,7 @@ void PropertyMaterialList::setDiffuseColor(uint32_t rgba) hasSetValue(); } -void PropertyMaterialList::setDiffuseColor(int index, const Color& col) +void PropertyMaterialList::setDiffuseColor(int index, const Base::Color& col) { verifyIndex(index); @@ -2936,7 +2936,7 @@ void PropertyMaterialList::setDiffuseColor(int index, uint32_t rgba) hasSetValue(); } -void PropertyMaterialList::setDiffuseColors(const std::vector& colors) +void PropertyMaterialList::setDiffuseColors(const std::vector& colors) { aboutToSetValue(); setSize(colors.size(), _lValueList[0]); @@ -2947,7 +2947,7 @@ void PropertyMaterialList::setDiffuseColors(const std::vector& color hasSetValue(); } -void PropertyMaterialList::setSpecularColor(const Color& col) +void PropertyMaterialList::setSpecularColor(const Base::Color& col) { aboutToSetValue(); setMinimumSizeOne(); @@ -2977,7 +2977,7 @@ void PropertyMaterialList::setSpecularColor(uint32_t rgba) hasSetValue(); } -void PropertyMaterialList::setSpecularColor(int index, const Color& col) +void PropertyMaterialList::setSpecularColor(int index, const Base::Color& col) { verifyIndex(index); @@ -3007,7 +3007,7 @@ void PropertyMaterialList::setSpecularColor(int index, uint32_t rgba) hasSetValue(); } -void PropertyMaterialList::setEmissiveColor(const Color& col) +void PropertyMaterialList::setEmissiveColor(const Base::Color& col) { aboutToSetValue(); setMinimumSizeOne(); @@ -3037,7 +3037,7 @@ void PropertyMaterialList::setEmissiveColor(uint32_t rgba) hasSetValue(); } -void PropertyMaterialList::setEmissiveColor(int index, const Color& col) +void PropertyMaterialList::setEmissiveColor(int index, const Base::Color& col) { verifyIndex(index); @@ -3118,29 +3118,29 @@ void PropertyMaterialList::setTransparencies(const std::vector& transpare hasSetValue(); } -const Color& PropertyMaterialList::getAmbientColor() const +const Base::Color& PropertyMaterialList::getAmbientColor() const { return _lValueList[0].ambientColor; } -const Color& PropertyMaterialList::getAmbientColor(int index) const +const Base::Color& PropertyMaterialList::getAmbientColor(int index) const { return _lValueList[index].ambientColor; } -const Color& PropertyMaterialList::getDiffuseColor() const +const Base::Color& PropertyMaterialList::getDiffuseColor() const { return _lValueList[0].diffuseColor; } -const Color& PropertyMaterialList::getDiffuseColor(int index) const +const Base::Color& PropertyMaterialList::getDiffuseColor(int index) const { return _lValueList[index].diffuseColor; } -std::vector PropertyMaterialList::getDiffuseColors() const +std::vector PropertyMaterialList::getDiffuseColors() const { - std::vector list; + std::vector list; for (auto& material : _lValueList) { list.push_back(material.diffuseColor); } @@ -3148,22 +3148,22 @@ std::vector PropertyMaterialList::getDiffuseColors() const return list; } -const Color& PropertyMaterialList::getSpecularColor() const +const Base::Color& PropertyMaterialList::getSpecularColor() const { return _lValueList[0].specularColor; } -const Color& PropertyMaterialList::getSpecularColor(int index) const +const Base::Color& PropertyMaterialList::getSpecularColor(int index) const { return _lValueList[index].specularColor; } -const Color& PropertyMaterialList::getEmissiveColor() const +const Base::Color& PropertyMaterialList::getEmissiveColor() const { return _lValueList[0].emissiveColor; } -const Color& PropertyMaterialList::getEmissiveColor(int index) const +const Base::Color& PropertyMaterialList::getEmissiveColor(int index) const { return _lValueList[index].emissiveColor; } diff --git a/src/App/PropertyStandard.h b/src/App/PropertyStandard.h index e85f985323..437c4beb97 100644 --- a/src/App/PropertyStandard.h +++ b/src/App/PropertyStandard.h @@ -999,7 +999,7 @@ protected: }; -/** Color properties +/** Base::Color properties * This is the father of all properties handling colors. */ class AppExport PropertyColor: public Property @@ -1021,13 +1021,13 @@ public: /** Sets the property */ - void setValue(const Color& col); + void setValue(const Base::Color& col); void setValue(float r, float g, float b, float a = 1.0F); void setValue(uint32_t rgba); /** This method returns a string representation of the property */ - const Color& getValue() const; + const Base::Color& getValue() const; const char* getEditorName() const override { @@ -1045,7 +1045,7 @@ public: unsigned int getMemSize() const override { - return sizeof(Color); + return sizeof(Base::Color); } bool isSame(const Property& other) const override @@ -1058,10 +1058,10 @@ public: } private: - Color _cCol; + Base::Color _cCol; }; -class AppExport PropertyColorList: public PropertyListsT +class AppExport PropertyColorList: public PropertyListsT { TYPESYSTEM_HEADER_WITH_OVERRIDE(); @@ -1091,7 +1091,7 @@ public: unsigned int getMemSize() const override; protected: - Color getPyValue(PyObject* py) const override; + Base::Color getPyValue(PyObject* py) const override; }; @@ -1118,19 +1118,19 @@ public: /** Sets the property */ void setValue(const Material& mat); - void setValue(const Color& col); + void setValue(const Base::Color& col); void setValue(float r, float g, float b, float a = 1.0F); void setValue(uint32_t rgba); - void setAmbientColor(const Color& col); + void setAmbientColor(const Base::Color& col); void setAmbientColor(float r, float g, float b, float a = 1.0F); void setAmbientColor(uint32_t rgba); - void setDiffuseColor(const Color& col); + void setDiffuseColor(const Base::Color& col); void setDiffuseColor(float r, float g, float b, float a = 1.0F); void setDiffuseColor(uint32_t rgba); - void setSpecularColor(const Color& col); + void setSpecularColor(const Base::Color& col); void setSpecularColor(float r, float g, float b, float a = 1.0F); void setSpecularColor(uint32_t rgba); - void setEmissiveColor(const Color& col); + void setEmissiveColor(const Base::Color& col); void setEmissiveColor(float r, float g, float b, float a = 1.0F); void setEmissiveColor(uint32_t rgba); void setShininess(float); @@ -1139,10 +1139,10 @@ public: /** This method returns a string representation of the property */ const Material& getValue() const; - const Color& getAmbientColor() const; - const Color& getDiffuseColor() const; - const Color& getSpecularColor() const; - const Color& getEmissiveColor() const; + const Base::Color& getAmbientColor() const; + const Base::Color& getDiffuseColor() const; + const Base::Color& getSpecularColor() const; + const Base::Color& getEmissiveColor() const; double getShininess() const; double getTransparency() const; @@ -1204,32 +1204,32 @@ public: void setValue(const Material& mat); void setValue(int index, const Material& mat); - void setAmbientColor(const Color& col); + void setAmbientColor(const Base::Color& col); void setAmbientColor(float r, float g, float b, float a = 1.0F); void setAmbientColor(uint32_t rgba); - void setAmbientColor(int index, const Color& col); + void setAmbientColor(int index, const Base::Color& col); void setAmbientColor(int index, float r, float g, float b, float a = 1.0F); void setAmbientColor(int index, uint32_t rgba); - void setDiffuseColor(const Color& col); + void setDiffuseColor(const Base::Color& col); void setDiffuseColor(float r, float g, float b, float a = 1.0F); void setDiffuseColor(uint32_t rgba); - void setDiffuseColor(int index, const Color& col); + void setDiffuseColor(int index, const Base::Color& col); void setDiffuseColor(int index, float r, float g, float b, float a = 1.0F); void setDiffuseColor(int index, uint32_t rgba); - void setDiffuseColors(const std::vector& colors); + void setDiffuseColors(const std::vector& colors); - void setSpecularColor(const Color& col); + void setSpecularColor(const Base::Color& col); void setSpecularColor(float r, float g, float b, float a = 1.0F); void setSpecularColor(uint32_t rgba); - void setSpecularColor(int index, const Color& col); + void setSpecularColor(int index, const Base::Color& col); void setSpecularColor(int index, float r, float g, float b, float a = 1.0F); void setSpecularColor(int index, uint32_t rgba); - void setEmissiveColor(const Color& col); + void setEmissiveColor(const Base::Color& col); void setEmissiveColor(float r, float g, float b, float a = 1.0F); void setEmissiveColor(uint32_t rgba); - void setEmissiveColor(int index, const Color& col); + void setEmissiveColor(int index, const Base::Color& col); void setEmissiveColor(int index, float r, float g, float b, float a = 1.0F); void setEmissiveColor(int index, uint32_t rgba); @@ -1240,18 +1240,18 @@ public: void setTransparency(int index, float); void setTransparencies(const std::vector& transparencies); - const Color& getAmbientColor() const; - const Color& getAmbientColor(int index) const; + const Base::Color& getAmbientColor() const; + const Base::Color& getAmbientColor(int index) const; - const Color& getDiffuseColor() const; - const Color& getDiffuseColor(int index) const; - std::vector getDiffuseColors() const; + const Base::Color& getDiffuseColor() const; + const Base::Color& getDiffuseColor(int index) const; + std::vector getDiffuseColors() const; - const Color& getSpecularColor() const; - const Color& getSpecularColor(int index) const; + const Base::Color& getSpecularColor() const; + const Base::Color& getSpecularColor(int index) const; - const Color& getEmissiveColor() const; - const Color& getEmissiveColor(int index) const; + const Base::Color& getEmissiveColor() const; + const Base::Color& getEmissiveColor(int index) const; float getShininess() const; float getShininess(int index) const; diff --git a/src/App/Transactions.cpp b/src/App/Transactions.cpp index ebf1c47fe7..988e2d20e7 100644 --- a/src/App/Transactions.cpp +++ b/src/App/Transactions.cpp @@ -464,7 +464,6 @@ void TransactionDocumentObject::applyDel(Document& Doc, TransactionalObject* pcO if (status == Del) { DocumentObject* obj = static_cast(pcObj); -#ifndef USE_OLD_DAG // Make sure the backlinks of all linked objects are updated. As the links of the removed // object are never set to [] they also do not remove the backlink. But as they are // not in the document anymore we need to remove them anyway to ensure a correct graph @@ -472,7 +471,6 @@ void TransactionDocumentObject::applyDel(Document& Doc, TransactionalObject* pcO for (auto link : list) { link->_removeBackLink(obj); } -#endif // simply filling in the saved object Doc._removeObject(obj); @@ -485,13 +483,11 @@ void TransactionDocumentObject::applyNew(Document& Doc, TransactionalObject* pcO DocumentObject* obj = static_cast(pcObj); Doc._addObject(obj, _NameInDocument.c_str()); -#ifndef USE_OLD_DAG // make sure the backlinks of all linked objects are updated auto list = obj->getOutList(); for (auto link : list) { link->_addBackLink(obj); } -#endif } } diff --git a/src/App/private/DocumentP.h b/src/App/private/DocumentP.h index c7e73b6098..98b6457939 100644 --- a/src/App/private/DocumentP.h +++ b/src/App/private/DocumentP.h @@ -92,11 +92,6 @@ struct DocumentP unsigned int UndoMaxStackSize; std::string programVersion; mutable HasherMap hashers; -#ifdef USE_OLD_DAG - DependencyList DepList; - std::map VertexObjectList; - std::map vertexMap; -#endif // USE_OLD_DAG std::multimap> _RecomputeLog; diff --git a/src/Base/Axis.pyi b/src/Base/Axis.pyi new file mode 100644 index 0000000000..060d238276 --- /dev/null +++ b/src/Base/Axis.pyi @@ -0,0 +1,85 @@ +from Metadata import export +from PyObjectBase import PyObjectBase +from Vector import Vector +from Placement import Placement +from Axis import Axis +from typing import overload + +@export( + Constructor=True, + Delete=True, +) +class Axis(PyObjectBase): + """ + Base.Axis class. + + An Axis defines a direction and a position (base) in 3D space. + + The following constructors are supported: + + Axis() + Empty constructor. + + Axis(axis) + Copy constructor. + axis : Base.Axis + + Axis(base, direction) + Define from a position and a direction. + base : Base.Vector + direction : Base.Vector + """ + + Base: Vector = ... + """Base position vector of the Axis.""" + + Direction: Vector = ... + """Direction vector of the Axis.""" + + # fmt: off + @overload + def __init__(self) -> None: ... + @overload + def __init__(self, axis: Axis) -> None: ... + @overload + def __init__(self, base: Vector, direction: Vector) -> None: ... + # fmt: on + + def copy(self) -> Axis: + """ + copy() -> Base.Axis + + Returns a copy of this Axis. + """ + ... + + def move(self, vector: Vector) -> None: + """ + move(vector) -> None + + Move the axis base along the given vector. + + vector : Base.Vector + Vector by which to move the axis. + """ + ... + + def multiply(self, placement: Placement) -> Axis: + """ + multiply(placement) -> Base.Axis + + Multiply this axis by a placement. + + placement : Base.Placement + Placement by which to multiply the axis. + """ + ... + + def reversed(self) -> Axis: + """ + reversed() -> Base.Axis + + Compute the reversed axis. This returns a new Base.Axis with + the original direction reversed. + """ + ... diff --git a/src/Base/BaseClass.pyi b/src/Base/BaseClass.pyi new file mode 100644 index 0000000000..15425dd6a4 --- /dev/null +++ b/src/Base/BaseClass.pyi @@ -0,0 +1,31 @@ +from Metadata import constmethod +from PyObjectBase import PyObjectBase +from typing import List, Final + +class BaseClass(PyObjectBase): + """ + This is the base class + + Author: Juergen Riegel (FreeCAD@juergen-riegel.net) + Licence: LGPL + """ + + TypeId: Final[str] = "" + """Is the type of the FreeCAD object with module domain""" + + Module: Final[str] = "" + """Module in which this class is defined""" + + @constmethod + def isDerivedFrom(self, typeName: str) -> bool: + """ + Returns true if given type is a father + """ + ... + + @constmethod + def getAllDerivedFrom(self) -> List[object]: + """ + Returns all descendants + """ + ... diff --git a/src/Base/BoundBox.pyi b/src/Base/BoundBox.pyi new file mode 100644 index 0000000000..368a29eb2b --- /dev/null +++ b/src/Base/BoundBox.pyi @@ -0,0 +1,370 @@ +from Metadata import export, constmethod +from PyObjectBase import PyObjectBase +from Vector import Vector +from Matrix import Matrix +from typing import overload, Any, Final, Tuple, Union + +@export( + TwinPointer="BoundBox3d", + Constructor=True, + Delete=True, +) +class BoundBox(PyObjectBase): + """ + Base.BoundBox class. + + This class represents a bounding box. + A bounding box is a rectangular cuboid which is a way to describe outer + boundaries and is obtained from a lot of 3D types. + It is often used to check if a 3D entity lies in the range of another object. + Checking for bounding interference first can save a lot of computing time! + An invalid BoundBox is represented by inconsistent values at each direction: + The maximum float value of the system at the minimum coordinates, and the + opposite value at the maximum coordinates. + + The following constructors are supported: + + BoundBox() + Empty constructor. Returns an invalid BoundBox. + + BoundBox(boundBox) + Copy constructor. + boundBox : Base.BoundBox + + BoundBox(xMin, yMin=0, zMin=0, xMax=0, yMax=0, zMax=0) + Define from the minimum and maximum values at each direction. + xMin : float + Minimum value at x-coordinate. + yMin : float + Minimum value at y-coordinate. + zMin : float + Minimum value at z-coordinate. + xMax : float + Maximum value at x-coordinate. + yMax : float + Maximum value at y-coordinate. + zMax : float + Maximum value at z-coordinate. + + App.BoundBox(min, max) + Define from two containers representing the minimum and maximum values of the + coordinates in each direction. + min : Base.Vector, tuple + Minimum values of the coordinates. + max : Base.Vector, tuple + Maximum values of the coordinates. + + Author: Juergen Riegel (FreeCAD@juergen-riegel.net) + Licence: LGPL + """ + + Center: Final[Any] = None + """Center point of the bounding box.""" + + XMax: float = 0.0 + """The maximum x boundary position.""" + + YMax: float = 0.0 + """The maximum y boundary position.""" + + ZMax: float = 0.0 + """The maximum z boundary position.""" + + XMin: float = 0.0 + """The minimum x boundary position.""" + + YMin: float = 0.0 + """The minimum y boundary position.""" + + ZMin: float = 0.0 + """The minimum z boundary position.""" + + XLength: Final[float] = 0.0 + """Length of the bounding box in x direction.""" + + YLength: Final[float] = 0.0 + """Length of the bounding box in y direction.""" + + ZLength: Final[float] = 0.0 + """Length of the bounding box in z direction.""" + + DiagonalLength: Final[float] = 0.0 + """Diagonal length of the bounding box.""" + + # fmt: off + @overload + def __init__(self) -> None: ... + @overload + def __init__(self, boundBox: "BoundBox") -> None: ... + @overload + def __init__( + self, + xMin: float, + yMin: float = 0, + zMin: float = 0, + xMax: float = 0, + yMax: float = 0, + zMax: float = 0, + ) -> None: ... + @overload + def __init__( + self, + min: Union[Vector, Tuple[float, float, float]], + max: Union[Vector, Tuple[float, float, float]], + ) -> None: ... + # fmt: on + + def setVoid(self) -> None: + """ + setVoid() -> None + + Invalidate the bounding box. + """ + ... + + @constmethod + def isValid(self) -> bool: + """ + isValid() -> bool + + Checks if the bounding box is valid. + """ + ... + + @overload + def add(self, minMax: Vector) -> None: ... + @overload + def add(self, minMax: Tuple[float, float, float]) -> None: ... + @overload + def add(self, x: float, y: float, z: float) -> None: ... + def add(self, *args: Any, **kwargs: Any) -> None: + """ + add(minMax) -> None + add(x, y, z) -> None + + Increase the maximum values or decrease the minimum values of this BoundBox by + replacing the current values with the given values, so the bounding box can grow + but not shrink. + + minMax : Base.Vector, tuple + Values to enlarge at each direction. + x : float + Value to enlarge at x-direction. + y : float + Value to enlarge at y-direction. + z : float + Value to enlarge at z-direction. + """ + ... + + @constmethod + def getPoint(self, index: int) -> Vector: + """ + getPoint(index) -> Base.Vector + + Get the point of the given index. + The index must be in the range of [0, 7]. + + index : int + """ + ... + + @constmethod + def getEdge(self, index: int) -> Tuple[Vector, ...]: + """ + getEdge(index) -> tuple of Base.Vector + + Get the edge points of the given index. + The index must be in the range of [0, 11]. + + index : int + """ + ... + + @overload + def closestPoint(self, point: Vector) -> Vector: ... + @overload + def closestPoint(self, x: float, y: float, z: float) -> Vector: ... + @constmethod + def closestPoint(self, *args: Any, **kwargs: Any) -> Vector: + """ + closestPoint(point) -> Base.Vector + closestPoint(x, y, z) -> Base.Vector + + Get the closest point of the bounding box to the given point. + + point : Base.Vector, tuple + Coordinates of the given point. + x : float + X-coordinate of the given point. + y : float + Y-coordinate of the given point. + z : float + Z-coordinate of the given point. + """ + ... + + @overload + def intersect(self, boundBox2: "BoundBox") -> bool: ... + @overload + def intersect( + self, + base: Union[Vector, Tuple[float, float, float]], + dir: Union[Vector, Tuple[float, float, float]], + ) -> bool: ... + def intersect(self, *args: Any) -> bool: + """ + intersect(boundBox2) -> bool + intersect(base, dir) -> bool + + Checks if the given object intersects with this bounding box. That can be + another bounding box or a line specified by base and direction. + + boundBox2 : Base.BoundBox + base : Base.Vector, tuple + dir : Base.Vector, tuple + """ + ... + + def intersected(self, boundBox2: "BoundBox") -> "BoundBox": + """ + intersected(boundBox2) -> Base.BoundBox + + Returns the intersection of this and the given bounding box. + + boundBox2 : Base.BoundBox + """ + ... + + def united(self, boundBox2: "BoundBox") -> "BoundBox": + """ + united(boundBox2) -> Base.BoundBox + + Returns the union of this and the given bounding box. + + boundBox2 : Base.BoundBox + """ + ... + + def enlarge(self, variation: float) -> None: + """ + enlarge(variation) -> None + + Decrease the minimum values and increase the maximum values by the given value. + A negative value shrinks the bounding box. + + variation : float + """ + ... + + def getIntersectionPoint(self, base: Vector, dir: Vector, epsilon: float = 0.0001) -> Vector: + """ + getIntersectionPoint(base, dir, epsilon=0.0001) -> Base.Vector + + Calculate the intersection point of a line with the bounding box. + The base point must lie inside the bounding box, if not an exception is thrown. + + base : Base.Vector + Base point of the line. + dir : Base.Vector + Direction of the line. + epsilon : float + Bounding box size tolerance. + """ + ... + + @overload + def move(self, displacement: Vector) -> None: ... + @overload + def move(self, displacement: Tuple[float, float, float]) -> None: ... + @overload + def move(self, x: float, y: float, z: float) -> None: ... + def move(self, *args: Any, **kwargs: Any) -> None: + """ + move(displacement) -> None + move(x, y, z) -> None + + Move the bounding box by the given values. + + displacement : Base.Vector, tuple + Displacement at each direction. + x : float + Displacement at x-direction. + y : float + Displacement at y-direction. + z : float + Displacement at z-direction. + """ + ... + + @overload + def scale(self, factor: Vector) -> None: ... + @overload + def scale(self, factor: Tuple[float, float, float]) -> None: ... + @overload + def scale(self, x: float, y: float, z: float) -> None: ... + def scale(self, *args: Any, **kwargs: Any) -> None: + """ + scale(factor) -> None + scale(x, y, z) -> None + + Scale the bounding box by the given values. + + factor : Base.Vector, tuple + Factor scale at each direction. + x : float + Scale at x-direction. + y : float + Scale at y-direction. + z : float + Scale at z-direction. + """ + ... + + def transformed(self, matrix: Matrix) -> "BoundBox": + """ + transformed(matrix) -> Base.BoundBox + + Returns a new BoundBox containing the transformed rectangular cuboid + represented by this BoundBox. + + matrix : Base.Matrix + Transformation matrix. + """ + ... + + def isCutPlane(self, base: Vector, normal: Vector) -> bool: + """ + isCutPlane(base, normal) -> bool + + Check if the plane specified by base and normal intersects (cuts) this bounding + box. + + base : Base.Vector + normal : Base.Vector + """ + ... + + @overload + def isInside(self, object: Vector) -> bool: ... + @overload + def isInside(self, object: "BoundBox") -> bool: ... + @overload + def isInside(self, x: float, y: float, z: float) -> bool: ... + def isInside(self, *args: Any) -> bool: + """ + isInside(object) -> bool + isInside(x, y, z) -> bool + + Check if a point or a bounding box is inside this bounding box. + + object : Base.Vector, Base.BoundBox + Object to check if it is inside this bounding box. + x : float + X-coordinate of the point to check. + y : float + Y-coordinate of the point to check. + z : float + Z-coordinate of the point to check. + """ + ... diff --git a/src/Base/CMakeLists.txt b/src/Base/CMakeLists.txt index f318c9989d..df4eb45bc1 100644 --- a/src/Base/CMakeLists.txt +++ b/src/Base/CMakeLists.txt @@ -10,6 +10,10 @@ include_directories( ${CMAKE_SOURCE_DIR}/src ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_CURRENT_SOURCE_DIR} +) + +include_directories( + SYSTEM ${Boost_INCLUDE_DIRS} ${PYCXX_INCLUDE_DIR} ${Python3_INCLUDE_DIRS} @@ -75,18 +79,31 @@ if(${CMAKE_SYSTEM_NAME} STREQUAL "Linux") endif() generate_from_xml(TypePy) +generate_from_py(Type) generate_from_xml(BaseClassPy) +generate_from_py(BaseClass) generate_from_xml(BoundBoxPy) +generate_from_py(BoundBox) generate_from_xml(CoordinateSystemPy) +generate_from_py(CoordinateSystem) generate_from_xml(PersistencePy) +generate_from_py(Persistence) generate_from_xml(VectorPy) +generate_from_py(Vector) generate_from_xml(MatrixPy) +generate_from_py(Matrix) generate_from_xml(RotationPy) +generate_from_py(Rotation) generate_from_xml(PlacementPy) +generate_from_py(Placement) generate_from_xml(AxisPy) +generate_from_py(Axis) generate_from_xml(UnitPy) +generate_from_py(Unit) generate_from_xml(QuantityPy) +generate_from_py(Quantity) generate_from_xml(PrecisionPy) +generate_from_py(Precision) generate_from_any(Parameter.xsd Parameter.inl xmlSchemeString) if(SWIG_FOUND) @@ -174,6 +191,7 @@ SET(FreeCADBase_CPP_SRCS Builder3D.cpp Console.cpp ConsoleObserver.cpp + Color.cpp CoordinateSystem.cpp CoordinateSystemPyImp.cpp Debugger.cpp @@ -245,6 +263,7 @@ SET(FreeCADBase_HPP_SRCS Console.h ConsoleObserver.h Converter.h + Color.h CoordinateSystem.h Debugger.h DualNumber.h diff --git a/src/App/Color.cpp b/src/Base/Color.cpp similarity index 99% rename from src/App/Color.cpp rename to src/Base/Color.cpp index 0d2d93e165..b5619d1e36 100644 --- a/src/App/Color.cpp +++ b/src/Base/Color.cpp @@ -30,7 +30,7 @@ #include "Color.h" -using namespace App; +using namespace Base; // NOLINTNEXTLINE(bugprone-easily-swappable-parameters) diff --git a/src/App/Color.h b/src/Base/Color.h similarity index 79% rename from src/App/Color.h rename to src/Base/Color.h index c0241d1329..09cc698cd4 100644 --- a/src/App/Color.h +++ b/src/Base/Color.h @@ -33,7 +33,7 @@ #include // NOLINTBEGIN(readability-magic-numbers) -namespace App +namespace Base { template @@ -86,7 +86,7 @@ private: /** Color class */ -class AppExport Color +class BaseExport Color { public: /** @@ -226,7 +226,92 @@ public: float r {}, g {}, b {}, a {}; }; -} // namespace App +// Specialization for Color +template<> +struct color_traits +{ + using color_type = Base::Color; + color_traits() = default; + explicit color_traits(const color_type& ct) + : ct(ct) + {} + float redF() const + { + return ct.r; + } + float greenF() const + { + return ct.g; + } + float blueF() const + { + return ct.b; + } + float alphaF() const + { + return ct.a; + } + void setRedF(float red) + { + ct.r = red; + } + void setGreenF(float green) + { + ct.g = green; + } + void setBlueF(float blue) + { + ct.b = blue; + } + void setAlphaF(float alpha) + { + ct.a = alpha; + } + int red() const + { + return int(std::lround(ct.r * 255.0F)); + } + int green() const + { + return int(std::lround(ct.g * 255.0F)); + } + int blue() const + { + return int(std::lround(ct.b * 255.0F)); + } + int alpha() const + { + return int(std::lround(ct.a * 255.0F)); + } + void setRed(int red) + { + ct.r = static_cast(red) / 255.0F; + } + void setGreen(int green) + { + ct.g = static_cast(green) / 255.0F; + } + void setBlue(int blue) + { + ct.b = static_cast(blue) / 255.0F; + } + void setAlpha(int alpha) + { + ct.a = static_cast(alpha) / 255.0F; + } + static color_type makeColor(int red, int green, int blue, int alpha = 255) + { + return color_type {static_cast(red) / 255.0F, + static_cast(green) / 255.0F, + static_cast(blue) / 255.0F, + static_cast(alpha) / 255.0F}; + } + +private: + color_type ct; +}; + +} // namespace Base // NOLINTEND(readability-magic-numbers) #endif // APP_COLOR_H diff --git a/src/Base/Console.h b/src/Base/Console.h index b2bd857e90..03f41d07ae 100644 --- a/src/Base/Console.h +++ b/src/Base/Console.h @@ -1169,7 +1169,17 @@ template(notifiername, format); diff --git a/src/Base/CoordinateSystem.pyi b/src/Base/CoordinateSystem.pyi new file mode 100644 index 0000000000..041fa695ea --- /dev/null +++ b/src/Base/CoordinateSystem.pyi @@ -0,0 +1,93 @@ +from Metadata import export, constmethod +from PyObjectBase import PyObjectBase +from Axis import Axis as AxisPy +from Vector import Vector +from Placement import Placement +from Rotation import Rotation +from typing import Union + +@export( + Constructor=True, + Delete=True, +) +class CoordinateSystem(PyObjectBase): + """ + Base.CoordinateSystem class. + + An orthonormal right-handed coordinate system in 3D space. + + CoordinateSystem() + Empty constructor. + + Author: Juergen Riegel (FreeCAD@juergen-riegel.net) + Licence: LGPL + """ + + Axis: AxisPy = None + """Set or get axis.""" + + XDirection: Vector = None + """Set or get X-direction.""" + + YDirection: Vector = None + """Set or get Y-direction.""" + + ZDirection: Vector = None + """Set or get Z-direction.""" + + Position: Vector = None + """Set or get position.""" + + def setAxes(self, axis: Union[AxisPy, Vector], xDir: Vector) -> None: + """ + setAxes(axis, xDir) -> None + + Set axis or Z-direction, and X-direction. + The X-direction is determined from the orthonormal compononent of `xDir` + with respect to `axis` direction. + + axis : Base.Axis, Base.Vector + xDir : Base.Vector + """ + ... + + @constmethod + def displacement(self, coordSystem2: "CoordinateSystem") -> Placement: + """ + displacement(coordSystem2) -> Base.Placement + + Computes the placement from this to the passed coordinate system `coordSystem2`. + + coordSystem2 : Base.CoordinateSystem + """ + ... + + def transformTo(self, vector: Vector) -> Vector: + """ + transformTo(vector) -> Base.Vector + + Computes the coordinates of the point in coordinates of this coordinate system. + + vector : Base.Vector + """ + ... + + def transform(self, trans: Union[Rotation, Placement]) -> None: + """ + transform(trans) -> None + + Applies a transformation on this coordinate system. + + trans : Base.Rotation, Base.Placement + """ + ... + + def setPlacement(self, placement: Placement) -> None: + """ + setPlacment(placement) -> None + + Set placement to the coordinate system. + + placement : Base.Placement + """ + ... diff --git a/src/Base/Matrix.pyi b/src/Base/Matrix.pyi new file mode 100644 index 0000000000..8ba42df1b3 --- /dev/null +++ b/src/Base/Matrix.pyi @@ -0,0 +1,445 @@ +from Vector import Vector +from Metadata import export, constmethod, class_declarations, no_args +from PyObjectBase import PyObjectBase +from enum import IntEnum +from typing import overload, Union, Tuple, Sequence + +class ScaleType(IntEnum): + Other = -1 + NoScaling = 0 + NonUniformRight = 1 + NonUniformLeft = 2 + Uniform = 3 + +@export( + TwinPointer="Matrix4D", + Constructor=True, + Delete=True, + NumberProtocol=True, + RichCompare=True, +) +@class_declarations( + """public: + MatrixPy(const Matrix4D & mat, PyTypeObject *T = &Type) + :PyObjectBase(new Matrix4D(mat),T){} + Matrix4D value() const + { return *(getMatrixPtr()); } + """ +) +class Matrix(PyObjectBase): + """ + Base.Matrix class. + + A 4x4 Matrix. + In particular, this matrix can represent an affine transformation, that is, + given a 3D vector `x`, apply the transformation y = M*x + b, where the matrix + `M` is a linear map and the vector `b` is a translation. + `y` can be obtained using a linear transformation represented by the 4x4 matrix + `A` conformed by the augmented 3x4 matrix (M|b), augmented by row with + (0,0,0,1), therefore: (y, 1) = A*(x, 1). + + The following constructors are supported: + + Matrix() + Empty constructor. + + Matrix(matrix) + Copy constructor. + matrix : Base.Matrix. + + Matrix(*coef) + Define from 16 coefficients of the 4x4 matrix. + coef : sequence of float + The sequence can have up to 16 elements which complete the matrix by rows. + + Matrix(vector1, vector2, vector3, vector4) + Define from four 3D vectors which represent the columns of the 3x4 submatrix, + useful to represent an affine transformation. The fourth row is made up by + (0,0,0,1). + vector1 : Base.Vector + vector2 : Base.Vector + vector3 : Base.Vector + vector4 : Base.Vector + Default to (0,0,0). Optional. + + Author: Juergen Riegel (FreeCAD@juergen-riegel.net) + Licence: LGPL + """ + + A11: float = 0.0 + """The (1,1) matrix element.""" + A12: float = 0.0 + """The (1,2) matrix element.""" + A13: float = 0.0 + """The (1,3) matrix element.""" + A14: float = 0.0 + """The (1,4) matrix element.""" + A21: float = 0.0 + """The (2,1) matrix element.""" + A22: float = 0.0 + """The (2,2) matrix element.""" + A23: float = 0.0 + """The (2,3) matrix element.""" + A24: float = 0.0 + """The (2,4) matrix element.""" + A31: float = 0.0 + """The (3,1) matrix element.""" + A32: float = 0.0 + """The (3,2) matrix element.""" + A33: float = 0.0 + """The (3,3) matrix element.""" + A34: float = 0.0 + """The (3,4) matrix element.""" + A41: float = 0.0 + """The (4,1) matrix element.""" + A42: float = 0.0 + """The (4,2) matrix element.""" + A43: float = 0.0 + """The (4,3) matrix element.""" + A44: float = 0.0 + """The (4,4) matrix element.""" + + A: Sequence[float] = [] + """The matrix elements.""" + + @overload + def move(self, vector: Vector) -> None: ... + @overload + def move(self, x: float, y: float, z: float) -> None: ... + def move(self, *args) -> None: + """ + move(vector) -> None + move(x, y, z) -> None + + Move the matrix along a vector, equivalent to left multiply the matrix + by a pure translation transformation. + + vector : Base.Vector, tuple + x : float + `x` translation. + y : float + `y` translation. + z : float + `z` translation. + """ + ... + + @overload + def scale(self, vector: Vector) -> None: ... + @overload + def scale(self, x: float, y: float, z: float) -> None: ... + @overload + def scale(self, factor: float) -> None: ... + def scale(self, *args) -> None: + """ + scale(vector) -> None + scale(x, y, z) -> None + scale(factor) -> None + + Scale the first three rows of the matrix. + + vector : Base.Vector + x : float + First row factor scale. + y : float + Second row factor scale. + z : float + Third row factor scale. + factor : float + global factor scale. + """ + ... + + @constmethod + def hasScale(self, tol: float = 0) -> ScaleType: + """ + hasScale(tol=0) -> ScaleType + + Return an enum value of ScaleType. Possible values are: + Uniform, NonUniformLeft, NonUniformRight, NoScaling or Other + if it's not a scale matrix. + + tol : float + """ + ... + + @constmethod + def decompose(self) -> Tuple["Matrix", "Matrix", "Matrix", "Matrix"]: + """ + decompose() -> Base.Matrix, Base.Matrix, Base.Matrix, Base.Matrix + + Return a tuple of matrices representing shear, scale, rotation and move. + So that matrix = move * rotation * scale * shear. + """ + ... + + @no_args + def nullify(self) -> None: + """ + nullify() -> None + + Make this the null matrix. + """ + ... + + @no_args + @constmethod + def isNull(self) -> bool: + """ + isNull() -> bool + + Check if this is the null matrix. + """ + ... + + @no_args + def unity(self) -> None: + """ + unity() -> None + + Make this matrix to unity (4D identity matrix). + """ + ... + + @constmethod + def isUnity(self, tol: float = 0.0) -> bool: + """ + isUnity([tol=0.0]) -> bool + + Check if this is the unit matrix (4D identity matrix). + """ + ... + + def transform(self, vector: Vector, matrix2: "Matrix") -> None: + """ + transform(vector, matrix2) -> None + + Transform the matrix around a given point. + Equivalent to left multiply the matrix by T*M*T_inv, where M is `matrix2`, T the + translation generated by `vector` and T_inv the inverse translation. + For example, if `matrix2` is a rotation, the result is the transformation generated + by the current matrix followed by a rotation around the point represented by `vector`. + + vector : Base.Vector + matrix2 : Base.Matrix + """ + ... + + @constmethod + def col(self, index: int) -> Vector: + """ + col(index) -> Base.Vector + + Return the vector of a column, that is, the vector generated by the three + first elements of the specified column. + + index : int + Required column index. + """ + ... + + def setCol(self, index: int, vector: Vector) -> None: + """ + setCol(index, vector) -> None + + Set the vector of a column, that is, the three first elements of the specified + column by index. + + index : int + Required column index. + vector : Base.Vector + """ + ... + + @constmethod + def row(self, index: int) -> Vector: + """ + row(index) -> Base.Vector + + Return the vector of a row, that is, the vector generated by the three + first elements of the specified row. + + index : int + Required row index. + """ + ... + + def setRow(self, index: int, vector: Vector) -> None: + """ + setRow(index, vector) -> None + + Set the vector of a row, that is, the three first elements of the specified + row by index. + + index : int + Required row index. + vector : Base.Vector + """ + ... + + @no_args + @constmethod + def diagonal(self) -> Vector: + """ + diagonal() -> Base.Vector + + Return the diagonal of the 3x3 leading principal submatrix as vector. + """ + ... + + def setDiagonal(self, vector: Vector) -> None: + """ + setDiagonal(vector) -> None + + Set the diagonal of the 3x3 leading principal submatrix. + + vector : Base.Vector + """ + ... + + def rotateX(self, angle: float) -> None: + """ + rotateX(angle) -> None + + Rotate around X axis. + + angle : float + Angle in radians. + """ + ... + + def rotateY(self, angle: float) -> None: + """ + rotateY(angle) -> None + + Rotate around Y axis. + + angle : float + Angle in radians. + """ + ... + + def rotateZ(self, angle: float) -> None: + """ + rotateZ(angle) -> None + + Rotate around Z axis. + + angle : float + Angle in radians. + """ + ... + + @overload + def multiply(self, matrix: "Matrix") -> "Matrix": ... + @overload + def multiply(self, vector: Vector) -> Vector: ... + @constmethod + def multiply(self, obj: Union["Matrix", Vector]) -> Union["Matrix", Vector]: + """ + multiply(matrix) -> Base.Matrix + multiply(vector) -> Base.Vector + + Right multiply the matrix by the given object. + If the argument is a vector, this is augmented to the 4D vector (`vector`, 1). + + matrix : Base.Matrix + vector : Base.Vector + """ + ... + + @constmethod + def multVec(self, vector: Vector) -> Vector: + """ + multVec(vector) -> Base.Vector + + Compute the transformed vector using the matrix. + + vector : Base.Vector + """ + ... + + @no_args + def invert(self) -> None: + """ + invert() -> None + + Compute the inverse matrix in-place, if possible. + """ + ... + + @no_args + @constmethod + def inverse(self) -> "Matrix": + """ + inverse() -> Base.Matrix + + Compute the inverse matrix, if possible. + """ + ... + + @no_args + def transpose(self) -> None: + """ + transpose() -> None + + Transpose the matrix in-place. + """ + ... + + @no_args + @constmethod + def transposed(self) -> "Matrix": + """ + transposed() -> Base.Matrix + + Returns a transposed copy of this matrix. + """ + ... + + @no_args + @constmethod + def determinant(self) -> float: + """ + determinant() -> float + + Compute the determinant of the matrix. + """ + ... + + @constmethod + def isOrthogonal(self, tol: float = 1e-6) -> float: + """ + isOrthogonal(tol=1e-6) -> float + + Checks if the matrix is orthogonal, i.e. M * M^T = k*I and returns + the multiple of the identity matrix. If it's not orthogonal 0 is returned. + + tol : float + Tolerance used to check orthogonality. + """ + ... + + @constmethod + def submatrix(self, dim: int) -> "Matrix": + """ + submatrix(dim) -> Base.Matrix + + Get the leading principal submatrix of the given dimension. + The (4 - `dim`) remaining dimensions are completed with the + corresponding identity matrix. + + dim : int + Dimension parameter must be in the range [1,4]. + """ + ... + + @no_args + @constmethod + def analyze(self) -> str: + """ + analyze() -> str + + Analyzes the type of transformation. + """ + ... diff --git a/src/Base/Parameter.cpp b/src/Base/Parameter.cpp index ecc8cda610..9a7ca96709 100644 --- a/src/Base/Parameter.cpp +++ b/src/Base/Parameter.cpp @@ -1252,6 +1252,55 @@ void ParameterGrp::RemoveUnsigned(const char* Name) Notify(Name); } +Base::Color ParameterGrp::GetColor(const char* Name, Base::Color lPreset) const +{ + auto packed = GetUnsigned(Name, lPreset.getPackedValue()); + + return Color(static_cast(packed)); +} + +void ParameterGrp::SetColor(const char* Name, Base::Color lValue) +{ + SetUnsigned(Name, lValue.getPackedValue()); +} + +std::vector ParameterGrp::GetColors(const char* sFilter) const +{ + auto packed = GetUnsigneds(sFilter); + std::vector result; + + std::transform(packed.begin(), + packed.end(), + std::back_inserter(result), + [](const unsigned long lValue) { + return Color(static_cast(lValue)); + }); + + return result; +} + +std::vector> +ParameterGrp::GetColorMap(const char* sFilter) const +{ + auto packed = GetUnsignedMap(sFilter); + std::vector> result; + + std::transform(packed.begin(), + packed.end(), + std::back_inserter(result), + [](const std::pair& lValue) { + return std::make_pair(lValue.first, + Color(static_cast(lValue.second))); + }); + + return result; +} + +void ParameterGrp::RemoveColor(const char* Name) +{ + RemoveUnsigned(Name); +} + void ParameterGrp::RemoveGrp(const char* Name) { if (!_pGroupNode) { diff --git a/src/Base/Parameter.h b/src/Base/Parameter.h index affcf63293..d025274679 100644 --- a/src/Base/Parameter.h +++ b/src/Base/Parameter.h @@ -52,6 +52,7 @@ using PyObject = struct _object; #include "Handle.h" #include "Observer.h" +#include "Color.h" #ifdef _MSC_VER #pragma warning(disable : 4251) @@ -83,7 +84,6 @@ XERCES_CPP_NAMESPACE_END class ParameterManager; - /** The parameter container class * This is the base class of all classes handle parameter. * The class contains a map of key-value pairs in a grouping @@ -350,6 +350,21 @@ public: void RemoveUnsigned(const char* Name); //@} + /** @name methods for Colors handling, colors are persisted as packed uints */ + //@{ + /// read color value or give default + Base::Color GetColor(const char* Name, Base::Color lPreset = Base::Color(1.0, 1.0, 1.0)) const; + /// set a color value + void SetColor(const char* Name, Base::Color lValue); + /// get a vector of all color values in this group + std::vector GetColors(const char* sFilter = nullptr) const; + /// get a map with all color values and the keys of this group + std::vector> + GetColorMap(const char* sFilter = nullptr) const; + /// remove a color value from this group + void RemoveColor(const char* Name); + //@} + /** @name methods for Float handling */ //@{ diff --git a/src/Base/Persistence.pyi b/src/Base/Persistence.pyi new file mode 100644 index 0000000000..06c8506653 --- /dev/null +++ b/src/Base/Persistence.pyi @@ -0,0 +1,45 @@ +from Metadata import constmethod +from BaseClass import BaseClass +from typing import Final + +class Persistence(BaseClass): + """ + Base.Persistence class. + + Class to dump and restore the content of an object. + + Author: Juergen Riegel (FreeCAD@juergen-riegel.net) + Licence: LGPL + """ + + Content: Final[str] = "" + """Content of the object in XML representation.""" + + MemSize: Final[int] = 0 + """Memory size of the object in bytes.""" + + @constmethod + def dumpContent(self, *, Compression: int = 3) -> bytearray: + """ + dumpContent(Compression=3) -> bytearray + + Dumps the content of the object, both the XML representation and the additional + data files required, into a byte representation. + + Compression : int + Set the data compression level in the range [0,9]. Set to 0 for no compression. + """ + ... + + def restoreContent(self, obj: object) -> None: + # TODO: Starting with Python 3.12, collections.abc.Buffer can be used for type hinting + """ + restoreContent(obj) -> None + + Restore the content of the object from a byte representation as stored by `dumpContent`. + It could be restored from any Python object implementing the buffer protocol. + + obj : buffer + Object with buffer protocol support. + """ + ... diff --git a/src/Base/Placement.pyi b/src/Base/Placement.pyi new file mode 100644 index 0000000000..4939e57ed9 --- /dev/null +++ b/src/Base/Placement.pyi @@ -0,0 +1,257 @@ +from Metadata import export, constmethod, class_declarations +from PyObjectBase import PyObjectBase +from Matrix import Matrix as MatrixPy +from Rotation import Rotation as RotationPy +from Vector import Vector +from typing import Sequence, overload + +@export( + Constructor=True, + Delete=True, + NumberProtocol=True, + RichCompare=True, +) +@class_declarations( + """public: + PlacementPy(const Placement & pla, PyTypeObject *T = &Type) + :PyObjectBase(new Placement(pla),T){} + Placement value() const + { return *(getPlacementPtr()); } + """ +) +class Placement(PyObjectBase): + """ + Base.Placement class. + + A Placement defines an orientation (rotation) and a position (base) in 3D space. + It is used when no scaling or other distortion is needed. + + The following constructors are supported: + + Placement() + Empty constructor. + + Placement(placement) + Copy constructor. + placement : Base.Placement + + Placement(matrix) + Define from a 4D matrix consisting of rotation and translation. + matrix : Base.Matrix + + Placement(base, rotation) + Define from position and rotation. + base : Base.Vector + rotation : Base.Rotation + + Placement(base, rotation, center) + Define from position and rotation with center. + base : Base.Vector + rotation : Base.Rotation + center : Base.Vector + + Placement(base, axis, angle) + define position and rotation. + base : Base.Vector + axis : Base.Vector + angle : float + """ + + Base: Vector = None + """Vector to the Base Position of the Placement.""" + + Rotation: Vector = None + """Orientation of the placement expressed as rotation.""" + + Matrix: MatrixPy = None + """Set/get matrix representation of the placement.""" + + # fmt: off + @overload + def __init__(self) -> None: ... + @overload + def __init__(self, placement: "Placement") -> None: ... + @overload + def __init__(self, matrix: MatrixPy) -> None: ... + @overload + def __init__(self, base: Vector, rotation: RotationPy) -> None: ... + @overload + def __init__(self, base: Vector, rotation: RotationPy, center: Vector) -> None: ... + @overload + def __init__(self, base: Vector, axis: Vector, angle: float) -> None: ... + # fmt: on + + @constmethod + def copy(self) -> "Placement": + """ + copy() -> Base.Placement + + Returns a copy of this placement. + """ + ... + + def move(self, vector: Vector) -> None: + """ + move(vector) -> None + + Move the placement along a vector. + + vector : Base.Vector + Vector by which to move the placement. + """ + ... + + def translate(self, vector: Vector) -> None: + """ + translate(vector) -> None + + Alias to move(), to be compatible with TopoShape.translate(). + + vector : Base.Vector + Vector by which to move the placement. + """ + ... + + @overload + def rotate( + self, center: Sequence[float], axis: Sequence[float], angle: float, *, comp: bool = False + ) -> None: ... + def rotate(self, center: Vector, axis: Vector, angle: float, *, comp: bool = False) -> None: + """ + rotate(center, axis, angle, comp) -> None + + Rotate the current placement around center and axis with the given angle. + This method is compatible with TopoShape.rotate() if the (optional) keyword + argument comp is True (default=False). + + center : Base.Vector, sequence of float + Rotation center. + axis : Base.Vector, sequence of float + Rotation axis. + angle : float + Rotation angle in degrees. + comp : bool + optional keyword only argument, if True (default=False), + behave like TopoShape.rotate() (i.e. the resulting placements are interchangeable). + """ + ... + + @constmethod + def multiply(self, placement: "Placement") -> "Placement": + """ + multiply(placement) -> Base.Placement + + Right multiply this placement with another placement. + Also available as `*` operator. + + placement : Base.Placement + Placement by which to multiply this placement. + """ + ... + + @constmethod + def multVec(self, vector: Vector) -> Vector: + """ + multVec(vector) -> Base.Vector + + Compute the transformed vector using the placement. + + vector : Base.Vector + Vector to be transformed. + """ + ... + + @constmethod + def toMatrix(self) -> MatrixPy: + """ + toMatrix() -> Base.Matrix + + Compute the matrix representation of the placement. + """ + ... + + @constmethod + def inverse(self) -> "Placement": + """ + inverse() -> Base.Placement + + Compute the inverse placement. + """ + ... + + @constmethod + def pow(self, t: float, shorten: bool = True) -> "Placement": + """ + pow(t, shorten=True) -> Base.Placement + + Raise this placement to real power using ScLERP interpolation. + Also available as `**` operator. + + t : float + Real power. + shorten : bool + If True, ensures rotation quaternion is net positive to make + the path shorter. + """ + ... + + @constmethod + def sclerp(self, placement2: "Placement", t: float, shorten: bool = True) -> "Placement": + """ + sclerp(placement2, t, shorten=True) -> Base.Placement + + Screw Linear Interpolation (ScLERP) between this placement and `placement2`. + Interpolation is a continuous motion along a helical path parametrized by `t` + made of equal transforms if discretized. + If quaternions of rotations of the two placements differ in sign, the interpolation + will take a long path. + + placement2 : Base.Placement + t : float + Parameter of helical path. t=0 returns this placement, t=1 returns + `placement2`. t can also be outside of [0, 1] range for extrapolation. + shorten : bool + If True, the signs are harmonized before interpolation and the interpolation + takes the shorter path. + """ + ... + + @constmethod + def slerp(self, placement2: "Placement", t: float) -> "Placement": + """ + slerp(placement2, t) -> Base.Placement + + Spherical Linear Interpolation (SLERP) between this placement and `placement2`. + This function performs independent interpolation of rotation and movement. + Result of such interpolation might be not what application expects, thus this tool + might be considered for simple cases or for interpolating between small intervals. + For more complex cases you better use the advanced sclerp() function. + + placement2 : Base.Placement + t : float + Parameter of the path. t=0 returns this placement, t=1 returns `placement2`. + """ + ... + + @constmethod + def isIdentity(self, tol: float = 0.0) -> bool: + """ + isIdentity([tol=0.0]) -> bool + + Returns True if the placement has no displacement and no rotation. + Matrix representation is the 4D identity matrix. + tol : float + Tolerance used to check for identity. + If tol is negative or zero, no tolerance is used. + """ + ... + + @constmethod + def isSame(self, other: "Placement", tol: float = 0.0) -> bool: + """ + isSame(Base.Placement, [tol=0.0]) -> bool + + Checks whether this and the given placement are the same. + The default tolerance is set to 0.0 + """ + ... diff --git a/src/Base/PreCompiled.h b/src/Base/PreCompiled.h index 4259835689..1e5fa96dbb 100644 --- a/src/Base/PreCompiled.h +++ b/src/Base/PreCompiled.h @@ -78,6 +78,7 @@ #include #include #include +#include // streams #include diff --git a/src/Base/Precision.pyi b/src/Base/Precision.pyi new file mode 100644 index 0000000000..ebc70d8988 --- /dev/null +++ b/src/Base/Precision.pyi @@ -0,0 +1,79 @@ +from PyObjectBase import PyObjectBase + +class Precision(PyObjectBase): + """ + This is the Precision class + + Author: Werner Mayer (wmayer@users.sourceforge.net) + Licence: LGPL + """ + + @staticmethod + def angular() -> float: + """ + Returns the recommended precision value when checking the equality of two angles (given in radians) + """ + ... + + @staticmethod + def confusion() -> float: + """ + Returns the recommended precision value when checking coincidence of two points in real space + """ + ... + + @staticmethod + def squareConfusion() -> float: + """ + Returns square of confusion + """ + ... + + @staticmethod + def intersection() -> float: + """ + Returns the precision value in real space, frequently used by intersection algorithms + """ + ... + + @staticmethod + def approximation() -> float: + """ + Returns the precision value in real space, frequently used by approximation algorithms + """ + ... + + @staticmethod + def parametric() -> float: + """ + Convert a real space precision to a parametric space precision + """ + ... + + @staticmethod + def isInfinite() -> bool: + """ + Returns True if R may be considered as an infinite number + """ + ... + + @staticmethod + def isPositiveInfinite() -> bool: + """ + Returns True if R may be considered as a positive infinite number + """ + ... + + @staticmethod + def isNegativeInfinite() -> bool: + """ + Returns True if R may be considered as a negative infinite number + """ + ... + + @staticmethod + def infinite() -> float: + """ + Returns a big number that can be considered as infinite + """ + ... diff --git a/src/Base/PyObjectBase.pyi b/src/Base/PyObjectBase.pyi new file mode 100644 index 0000000000..624434f693 --- /dev/null +++ b/src/Base/PyObjectBase.pyi @@ -0,0 +1,6 @@ +class PyObjectBase: + """ + The most base class for Python bindings. + """ + + ... diff --git a/src/Base/Quantity.pyi b/src/Base/Quantity.pyi new file mode 100644 index 0000000000..4e6f621fa7 --- /dev/null +++ b/src/Base/Quantity.pyi @@ -0,0 +1,107 @@ +from Metadata import export, constmethod +from PyObjectBase import PyObjectBase +from typing import overload, Final, Tuple, Union +from Unit import Unit as UnitPy + +@export( + NumberProtocol=True, + RichCompare=True, + Constructor=True, + Delete=True, +) +class Quantity(PyObjectBase): + """ + Quantity + defined by a value and a unit. + + The following constructors are supported: + Quantity() -- empty constructor + Quantity(Value) -- empty constructor + Quantity(Value,Unit) -- empty constructor + Quantity(Quantity) -- copy constructor + Quantity(string) -- arbitrary mixture of numbers and chars defining a Quantity + + Author: Juergen Riegel (FreeCAD@juergen-riegel.net) + Licence: LGPL + """ + + Value: float = ... + """Numeric Value of the Quantity (in internal system mm,kg,s)""" + + Unit: UnitPy = ... + """Unit of the Quantity""" + + UserString: Final[str] = ... + """Unit of the Quantity""" + + Format: dict = ... + """Format of the Quantity""" + + # fmt: off + @overload + def __init__(self) -> None: ... + @overload + def __init__(self, value: float) -> None: ... + @overload + def __init__(self, value: float, unit: UnitPy) -> None: ... + @overload + def __init__(self, quantity: "Quantity") -> None: ... + @overload + def __init__(self, string: str) -> None: ... + # fmt: on + + @constmethod + def toStr(self, decimals: int = ...) -> str: + """ + toStr([decimals]) + + Returns a string representation rounded to number of decimals. If no decimals are specified then + the internal precision is used + """ + ... + + @overload + def toStr(self) -> str: ... + @overload + def toStr(self, decimals: int) -> str: ... + @constmethod + def getUserPreferred(self) -> Tuple["Quantity", str]: + """ + Returns a quantity with the translation factor and a string with the prevered unit + """ + ... + + @overload + def getValueAs(self, unit: str) -> float: ... + @overload + def getValueAs(self, translation: float, unit_signature: int) -> float: ... + @overload + def getValueAs(self, unit: UnitPy) -> float: ... + @overload + def getValueAs(self, quantity: "Quantity") -> float: ... + @constmethod + def getValueAs(self, *args) -> float: + """ + Returns a floating point value as the provided unit + + Following parameters are allowed: + getValueAs('m/s') # unit string to parse + getValueAs(2.45,1) # translation value and unit signature + getValueAs(FreeCAD.Units.Pascal) # predefined standard units + getValueAs(Qantity('N/m^2')) # a quantity + getValueAs(Unit(0,1,0,0,0,0,0,0)) # a unit + """ + ... + + @constmethod + def __round__(self, ndigits: int = ...) -> Union[int, float]: + """ + Returns the Integral closest to x, rounding half toward even. + When an argument is passed, work like built-in round(x, ndigits). + """ + ... + + @overload + def __round__(self) -> int: ... + @overload + def __round__(self, ndigits: int) -> float: ... diff --git a/src/Base/Rotation.pyi b/src/Base/Rotation.pyi new file mode 100644 index 0000000000..20b52cc9f8 --- /dev/null +++ b/src/Base/Rotation.pyi @@ -0,0 +1,275 @@ +from Metadata import export, constmethod, class_declarations +from PyObjectBase import PyObjectBase +from Vector import Vector +from Matrix import Matrix +from typing import overload, Tuple, List, Final + +@export( + Constructor=True, + Delete=True, + NumberProtocol=True, + RichCompare=True, +) +@class_declarations( + """public: + RotationPy(const Rotation & mat, PyTypeObject *T = &Type) + :PyObjectBase(new Rotation(mat),T){} + Rotation value() const + { return *(getRotationPtr()); } + """ +) +class Rotation(PyObjectBase): + """ + Base.Rotation class. + + A Rotation using a quaternion. + + The following constructors are supported: + + Rotation() + Empty constructor. + + Rotation(rotation) + Copy constructor. + + Rotation(Axis, Radian) + Rotation(Axis, Degree) + Define from an axis and an angle (in radians or degrees according to the keyword). + Axis : Base.Vector + Radian : float + Degree : float + + Rotation(vector_start, vector_end) + Define from two vectors (rotation from/to vector). + vector_start : Base.Vector + vector_end : Base.Vector + + Rotation(angle1, angle2, angle3) + Define from three floats (Euler angles) as yaw-pitch-roll in XY'Z'' convention. + angle1 : float + angle2 : float + angle3 : float + + Rotation(seq, angle1, angle2, angle3) + Define from one string and three floats (Euler angles) as Euler rotation + of a given type. Call toEulerAngles() for supported sequence types. + seq : str + angle1 : float + angle2 : float + angle3 : float + + Rotation(x, y, z, w) + Define from four floats (quaternion) where the quaternion is specified as: + q = xi+yj+zk+w, i.e. the last parameter is the real part. + x : float + y : float + z : float + w : float + + Rotation(dir1, dir2, dir3, seq) + Define from three vectors that define rotated axes directions plus an optional + 3-characher string of capital letters 'X', 'Y', 'Z' that sets the order of + importance of the axes (e.g., 'ZXY' means z direction is followed strictly, + x is used but corrected if necessary, y is ignored). + dir1 : Base.Vector + dir2 : Base.Vector + dir3 : Base.Vector + seq : str + + Rotation(matrix) + Define from a matrix rotation in the 4D representation. + matrix : Base.Matrix + + Rotation(*coef) + Define from 16 or 9 elements which represent the rotation in the 4D matrix + representation or in the 3D matrix representation, respectively. + coef : sequence of float + + Author: Juergen Riegel (FreeCAD@juergen-riegel.net) + Licence: LGPL + """ + + Q: Tuple[float, ...] = () + """The rotation elements (as quaternion).""" + + Axis: object = None + """The rotation axis of the quaternion.""" + + RawAxis: Final[object] = None + """The rotation axis without normalization.""" + + Angle: float = 0.0 + """The rotation angle of the quaternion.""" + + # TODO: Provide strongly-typed enum for `seq` + # fmt: off + @overload + def __init__(self) -> None: ... + @overload + def __init__(self, rotation: "Rotation") -> None: ... + @overload + def __init__(self, axis: Vector, angle: float) -> None: ... + @overload + def __init__(self, vector_start: Vector, vector_end: Vector) -> None: ... + @overload + def __init__(self, angle1: float, angle2: float, angle3: float) -> None: ... + @overload + def __init__(self, seq: str, angle1: float, angle2: float, angle3: float) -> None: ... + @overload + def __init__(self, x: float, y: float, z: float, w: float) -> None: ... + @overload + def __init__(self, dir1: Vector, dir2: Vector, dir3: Vector, seq: str) -> None: ... + @overload + def __init__(self, matrix: Matrix) -> None: ... + @overload + def __init__(self, *coef: float) -> None: ... + # fmt: on + + def invert(self) -> None: + """ + invert() -> None + + Sets the rotation to its inverse. + """ + ... + + @constmethod + def inverted(self) -> "Rotation": + """ + inverted() -> Base.Rotation + + Returns the inverse of the rotation. + """ + ... + + def isSame(self, rotation: "Rotation", tol: float = 0) -> bool: + """ + isSame(rotation, tol=0) -> bool + + Checks if `rotation` perform the same transformation as this rotation. + + rotation : Base.Rotation + tol : float + Tolerance used to compare both rotations. + If tol is negative or zero, no tolerance is used. + """ + ... + + @constmethod + def multiply(self, rotation: "Rotation") -> "Rotation": + """ + multiply(rotation) -> Base.Rotation + + Right multiply this rotation with another rotation. + + rotation : Base.Rotation + Rotation by which to multiply this rotation. + """ + ... + + @constmethod + def multVec(self, vector: Vector) -> Vector: + """ + multVec(vector) -> Base.Vector + + Compute the transformed vector using the rotation. + + vector : Base.Vector + Vector to be transformed. + """ + ... + + @constmethod + def slerp(self, rotation2: "Rotation", t: float) -> "Rotation": + """ + slerp(rotation2, t) -> Base.Rotation + + Spherical Linear Interpolation (SLERP) of this rotation and `rotation2`. + + t : float + Parameter of the path. t=0 returns this rotation, t=1 returns `rotation2`. + """ + ... + + def setYawPitchRoll(self, angle1: float, angle2: float, angle3: float) -> None: + """ + setYawPitchRoll(angle1, angle2, angle3) -> None + + Set the Euler angles of this rotation as yaw-pitch-roll in XY'Z'' convention. + + angle1 : float + Angle around yaw axis in degrees. + angle2 : float + Angle around pitch axis in degrees. + angle3 : float + Angle around roll axis in degrees. + """ + ... + + @constmethod + def getYawPitchRoll(self) -> Tuple[float, float, float]: + """ + getYawPitchRoll() -> tuple + + Get the Euler angles of this rotation as yaw-pitch-roll in XY'Z'' convention. + The angles are given in degrees. + """ + ... + + def setEulerAngles(self, seq: str, angle1: float, angle2: float, angle3: float) -> None: + """ + setEulerAngles(seq, angle1, angle2, angle3) -> None + + Set the Euler angles in a given sequence for this rotation. + The angles must be given in degrees. + + seq : str + Euler sequence name. All possible values given by toEulerAngles(). + angle1 : float + angle2 : float + angle3 : float + """ + ... + + @constmethod + def toEulerAngles(self, seq: str = "") -> List[float]: + """ + toEulerAngles(seq) -> list + + Get the Euler angles in a given sequence for this rotation. + + seq : str + Euler sequence name. If not given, the function returns + all possible values of `seq`. Optional. + """ + ... + + @constmethod + def toMatrix(self) -> Matrix: + """ + toMatrix() -> Base.Matrix + + Convert the rotation to a 4D matrix representation. + """ + ... + + @constmethod + def isNull(self) -> bool: + """ + isNull() -> bool + + Returns True if all values in the quaternion representation are zero. + """ + ... + + @constmethod + def isIdentity(self, tol: float = 0) -> bool: + """ + isIdentity(tol=0) -> bool + + Returns True if the rotation equals the 4D identity matrix. + tol : float + Tolerance used to check for identity. + If tol is negative or zero, no tolerance is used. + """ + ... diff --git a/src/Base/Tools2D.h b/src/Base/Tools2D.h index 251c8139bb..9bc10d19c3 100644 --- a/src/Base/Tools2D.h +++ b/src/Base/Tools2D.h @@ -119,6 +119,7 @@ public: inline BoundBox2d(double fX1, double fY1, double fX2, double fY2); ~BoundBox2d() = default; inline bool IsValid() const; + inline bool IsInfinite() const; inline bool IsEqual(const BoundBox2d& bbox, double tolerance) const; // operators @@ -477,6 +478,11 @@ inline bool BoundBox2d::IsValid() const return (MaxX >= MinX) && (MaxY >= MinY); } +inline bool BoundBox2d::IsInfinite() const +{ + return MaxX >= DOUBLE_MAX && MaxY >= DOUBLE_MAX && MinX <= -DOUBLE_MAX && MinY <= -DOUBLE_MAX; +} + inline bool BoundBox2d::IsEqual(const BoundBox2d& bbox, double tolerance) const { return Vector2d(MinX, MinY).IsEqual(Vector2d(bbox.MinX, bbox.MinY), tolerance) diff --git a/src/Base/Type.pyi b/src/Base/Type.pyi new file mode 100644 index 0000000000..e8a550e59a --- /dev/null +++ b/src/Base/Type.pyi @@ -0,0 +1,143 @@ +from Metadata import export, forward_declarations, constmethod +from PyObjectBase import PyObjectBase +from typing import List, Final + +@export( + Twin="BaseType", + TwinPointer="BaseType", + Delete=True, +) +@forward_declarations( + """ +namespace Base { + using BaseType = Type; +}""" +) +class Type(PyObjectBase): + """ + BaseTypePy class. + + This class provides functionality related to type management in the Base module. It's not intended for direct instantiation but for accessing type information and creating instances of various types. Instantiation is possible for classes that inherit from the Base::BaseClass class and are not abstract. + + Author: Juergen Riegel (FreeCAD@juergen-riegel.net) + Licence: LGPL + """ + + Name: Final[str] = "" + """The name of the type id.""" + + Key: Final[int] = 0 + """The key of the type id.""" + + Module: Final[str] = "" + """Module in which this class is defined.""" + + @staticmethod + def fromName(name: str) -> "Type": + """ + fromName(name) -> Base.BaseType + + Returns a type object by name. + + name : str + """ + ... + + @staticmethod + def fromKey(key: int) -> "Type": + """ + fromKey(key) -> Base.BaseType + + Returns a type id object by key. + + key : int + """ + ... + + @staticmethod + def getNumTypes() -> int: + """ + getNumTypes() -> int + + Returns the number of type ids created so far. + """ + ... + + @staticmethod + def getBadType() -> "Type": + """ + getBadType() -> Base.BaseType + + Returns an invalid type id. + """ + ... + + @staticmethod + def getAllDerivedFrom(type: str) -> List[str]: + """ + getAllDerivedFrom(type) -> list + + Returns all descendants from the given type id. + + type : str, Base.BaseType + """ + ... + + @constmethod + def getParent(self) -> "Type": + """ + getParent() -> Base.BaseType + + Returns the parent type id. + """ + ... + + @constmethod + def isBad(self) -> bool: + """ + isBad() -> bool + + Checks if the type id is invalid. + """ + ... + + @constmethod + def isDerivedFrom(self, type: str) -> bool: + """ + isDerivedFrom(type) -> bool + + Returns true if given type id is a father of this type id. + + type : str, Base.BaseType + """ + ... + + @constmethod + def getAllDerived(self) -> List[object]: + """ + getAllDerived() -> list + + Returns all descendants from this type id. + """ + ... + + def createInstance(self) -> object: + """ + createInstance() -> object + + Creates an instance of this type id. + """ + ... + + @staticmethod + def createInstanceByName(name: str, load: bool = False) -> object: + """ + createInstanceByName(name, load=False) -> object + + Creates an instance of the named type id. + + name : str + load : bool + Load named type id module. + """ + ... diff --git a/src/Base/Unit.pyi b/src/Base/Unit.pyi new file mode 100644 index 0000000000..7f5426394a --- /dev/null +++ b/src/Base/Unit.pyi @@ -0,0 +1,54 @@ +from Metadata import export +from PyObjectBase import PyObjectBase +from Quantity import Quantity +from Unit import Unit +from typing import Final, Tuple, overload + +@export( + NumberProtocol=True, + RichCompare=True, + Constructor=True, + Delete=True, +) +class Unit(PyObjectBase): + """ + Unit + defines a unit type, calculate and compare. + + The following constructors are supported: + Unit() -- empty constructor + Unit(i1,i2,i3,i4,i5,i6,i7,i8) -- unit signature + Unit(Quantity) -- copy unit from Quantity + Unit(Unit) -- copy constructor + Unit(string) -- parse the string for units + + Author: Juergen Riegel (FreeCAD@juergen-riegel.net) + Licence: LGPL + """ + + @overload + def __init__(self) -> None: ... + @overload + def __init__( + self, + i1: float, + i2: float, + i3: float, + i4: float, + i5: float, + i6: float, + i7: float, + i8: float, + ) -> None: ... + @overload + def __init__(self, quantity: Quantity) -> None: ... + @overload + def __init__(self, unit: Unit) -> None: ... + @overload + def __init__(self, string: str) -> None: ... + + Type: Final[str] = ... + """holds the unit type as a string, e.g. 'Area'.""" + + Signature: Final[Tuple] = ... + """Returns the signature.""" diff --git a/src/Base/Vector.pyi b/src/Base/Vector.pyi new file mode 100644 index 0000000000..37ebf0416a --- /dev/null +++ b/src/Base/Vector.pyi @@ -0,0 +1,320 @@ +from Metadata import export, constmethod, sequence_protocol, class_declarations +from PyObjectBase import PyObjectBase +from typing import overload, Sequence, TYPE_CHECKING + +@export( + TwinPointer="Vector3d", + Include="Base/Vector3D.h", + Constructor=True, + Delete=True, + NumberProtocol=True, + RichCompare=True, +) +@sequence_protocol( + sq_length=True, + sq_concat=False, + sq_repeat=False, + sq_item=True, + mp_subscript=True, + sq_ass_item=True, + mp_ass_subscript=False, + sq_contains=False, + sq_inplace_concat=False, + sq_inplace_repeat=False, +) +@class_declarations( + """public: + VectorPy(const Vector3d & vec, PyTypeObject *T = &Type) + :PyObjectBase(new Vector3d(vec),T){} + VectorPy(const Vector3f & vec, PyTypeObject *T = &Type) + :PyObjectBase(new Vector3d(vec.x,vec.y,vec.z),T){} + Vector3d value() const + { return *(getVectorPtr()); } +private: + Py::List sequence; + """ +) +class Vector(PyObjectBase): + """ + Base.Vector class. + + This class represents a 3D float vector. + Useful to represent points in the 3D space. + + The following constructors are supported: + + Vector(x=0, y=0, z=0) + x : float + y : float + z : float + + Vector(vector) + Copy constructor. + vector : Base.Vector + + Vector(seq) + Define from a sequence of float. + seq : sequence of float. + + Author: Juergen Riegel (FreeCAD@juergen-riegel.net) + Licence: LGPL + """ + + Length: float = 0.0 + """Gets or sets the length of this vector.""" + + x: float = 0.0 + """Gets or sets the X component of this vector.""" + + y: float = 0.0 + """Gets or sets the Y component of this vector.""" + + z: float = 0.0 + """Gets or sets the Z component of this vector.""" + + # fmt: off + @overload + def __init__(self, *, x: float = 0, y: float = 0, z: float = 0) -> None: ... + @overload + def __init__(self, vector: "Vector") -> None: ... + @overload + def __init__(self, seq: Sequence[float]) -> None: ... + # fmt: on + + @constmethod + def __reduce__(self) -> tuple: + """ + __reduce__() -> tuple + + Serialization of Vector objects. + """ + ... + + @constmethod + def add(self, vector2: "Vector") -> "Vector": + """ + add(vector2) -> Base.Vector + + Returns the sum of this vector and `vector2`. + + vector2 : Base.Vector + """ + ... + + @constmethod + def sub(self, vector2: "Vector") -> "Vector": + """ + sub(vector2) -> Base.Vector + + Returns the difference of this vector and `vector2`. + + vector2 : Base.Vector + """ + ... + + @constmethod + def negative(self) -> "Vector": + """ + negative() -> Base.Vector + + Returns the negative (opposite) of this vector. + """ + ... + + def scale(self, x: float, y: float, z: float) -> "Vector": + """ + scale(x, y, z) -> Base.Vector + + Scales in-place this vector by the given factor in each component. + + x : float + x-component factor scale. + y : float + y-component factor scale. + z : float + z-component factor scale. + """ + ... + + def multiply(self, factor: float) -> "Vector": + """ + multiply(factor) -> Base.Vector + + Multiplies in-place each component of this vector by a single factor. + Equivalent to scale(factor, factor, factor). + + factor : float + """ + ... + + @constmethod + def dot(self, vector2: "Vector") -> float: + """ + dot(vector2) -> float + + Returns the scalar product (dot product) between this vector and `vector2`. + + vector2 : Base.Vector + """ + ... + + @constmethod + def cross(self, vector2: "Vector") -> "Vector": + """ + cross(vector2) -> Base.Vector + + Returns the vector product (cross product) between this vector and `vector2`. + + vector2 : Base.Vector + """ + ... + + @constmethod + def isOnLineSegment(self, vector1: "Vector", vector2: "Vector") -> bool: + """ + isOnLineSegment(vector1, vector2) -> bool + + Checks if this vector is on the line segment generated by `vector1` and `vector2`. + + vector1 : Base.Vector + vector2 : Base.Vector + """ + ... + + @constmethod + def getAngle(self, vector2: "Vector") -> float: + """ + getAngle(vector2) -> float + + Returns the angle in radians between this vector and `vector2`. + + vector2 : Base.Vector + """ + ... + + def normalize(self) -> "Vector": + """ + normalize() -> Base.Vector + + Normalizes in-place this vector to the length of 1.0. + """ + ... + + @constmethod + def isEqual(self, vector2: "Vector", tol: float = 0) -> bool: + """ + isEqual(vector2, tol=0) -> bool + + Checks if the distance between the points represented by this vector + and `vector2` is less or equal to the given tolerance. + + vector2 : Base.Vector + tol : float + """ + ... + + @constmethod + def isParallel(self, vector2: "Vector", tol: float = 0) -> bool: + """ + isParallel(vector2, tol=0) -> bool + + Checks if this vector and `vector2` are + parallel less or equal to the given tolerance. + + vector2 : Base.Vector + tol : float + """ + ... + + @constmethod + def isNormal(self, vector2: "Vector", tol: float = 0) -> bool: + """ + isNormal(vector2, tol=0) -> bool + + Checks if this vector and `vector2` are + normal less or equal to the given tolerance. + + vector2 : Base.Vector + tol : float + """ + ... + + def projectToLine(self, point: "Vector", dir: "Vector") -> "Vector": + """ + projectToLine(point, dir) -> Base.Vector + + Projects `point` on a line that goes through the origin with the direction `dir`. + The result is the vector from `point` to the projected point. + The operation is equivalent to dir_n.cross(dir_n.cross(point)), where `dir_n` is + the vector `dir` normalized. + The method modifies this vector instance according to result and does not + depend on the vector itself. + + point : Base.Vector + dir : Base.Vector + """ + ... + + def projectToPlane(self, base: "Vector", normal: "Vector") -> "Vector": + """ + projectToPlane(base, normal) -> Base.Vector + + Projects in-place this vector on a plane defined by a base point + represented by `base` and a normal defined by `normal`. + + base : Base.Vector + normal : Base.Vector + """ + ... + + @constmethod + def distanceToPoint(self, point2: "Vector") -> float: + """ + distanceToPoint(point2) -> float + + Returns the distance to another point represented by `point2`. + . + point : Base.Vector + """ + ... + + @constmethod + def distanceToLine(self, base: "Vector", dir: "Vector") -> float: + """ + distanceToLine(base, dir) -> float + + Returns the distance between the point represented by this vector + and a line defined by a base point represented by `base` and a + direction `dir`. + + base : Base.Vector + dir : Base.Vector + """ + ... + + @constmethod + def distanceToLineSegment(self, point1: "Vector", point2: "Vector") -> "Vector": + """ + distanceToLineSegment(point1, point2) -> Base.Vector + + Returns the vector between the point represented by this vector and the point + on the line segment with the shortest distance. The line segment is defined by + `point1` and `point2`. + + point1 : Base.Vector + point2 : Base.Vector + """ + ... + + @constmethod + def distanceToPlane(self, base: "Vector", normal: "Vector") -> float: + """ + distanceToPlane(base, normal) -> float + + Returns the distance between this vector and a plane defined by a + base point represented by `base` and a normal defined by `normal`. + + base : Base.Vector + normal : Base.Vector + """ + ... diff --git a/src/Base/Vector3D.h b/src/Base/Vector3D.h index ff931c0d1f..62ad1fb5f1 100644 --- a/src/Base/Vector3D.h +++ b/src/Base/Vector3D.h @@ -101,6 +101,10 @@ template class Vector3 { public: + static const Vector3 UnitX; + static const Vector3 UnitY; + static const Vector3 UnitZ; + using num_type = float_type; using traits_type = float_traits; [[nodiscard]] static constexpr num_type epsilon() @@ -256,7 +260,12 @@ public: //@} }; -// global functions +template +Vector3 const Vector3::UnitX(1.0, 0.0, 0.0); +template +Vector3 const Vector3::UnitY(0.0, 1.0, 0.0); +template +Vector3 const Vector3::UnitZ(0.0, 0.0, 1.0); /// Returns the distance between two points template diff --git a/src/Gui/CMakeLists.txt b/src/Gui/CMakeLists.txt index 094d42b0ad..fb7a3e1640 100644 --- a/src/Gui/CMakeLists.txt +++ b/src/Gui/CMakeLists.txt @@ -58,6 +58,10 @@ include_directories( ${CMAKE_CURRENT_BINARY_DIR}/TaskView ${CMAKE_CURRENT_BINARY_DIR}/Quarter ${CMAKE_CURRENT_BINARY_DIR}/DAGView +) + +include_directories( + SYSTEM ${Boost_INCLUDE_DIRS} ${EIGEN3_INCLUDE_DIR} ${PYCXX_INCLUDE_DIR} @@ -98,7 +102,7 @@ endif(MSVC) if (TARGET Coin::Coin) list(APPEND FreeCADGui_LIBS Coin::Coin) else() - include_directories(${COIN3D_INCLUDE_DIRS}) + include_directories(SYSTEM ${COIN3D_INCLUDE_DIRS}) link_directories(${COIN3D_LIB_DIRS}) list(APPEND FreeCADGui_LIBS ${COIN3D_LIBRARIES}) endif() @@ -112,6 +116,7 @@ if (WIN32) endif() include_directories( + SYSTEM ${QtCore_INCLUDE_DIRS} ${QtWidgets_INCLUDE_DIRS} ${QtOpenGL_INCLUDE_DIRS} @@ -135,6 +140,7 @@ list(APPEND FreeCADGui_LIBS if(${Qt5WinExtras_FOUND}) include_directories( + SYSTEM ${Qt5WinExtras_INCLUDE_DIRS} ) list(APPEND FreeCADGui_LIBS @@ -148,7 +154,7 @@ IF(SPNAV_FOUND AND FREECAD_USE_3DCONNEXION_LEGACY) add_definitions(-DSPNAV_USE_X11) if (FREECAD_QT_MAJOR_VERSION EQUAL 5 AND UNIX AND NOT APPLE) find_package(Qt5X11Extras REQUIRED) - include_directories(${Qt5X11Extras_INCLUDE_DIRS}) + include_directories(SYSTEM ${Qt5X11Extras_INCLUDE_DIRS}) list(APPEND FreeCADGui_LIBS ${Qt5X11Extras_LIBRARIES}) # Note that Qt6 has removed the QtX11Extras files endif() @@ -186,6 +192,7 @@ IF(SPNAV_FOUND AND FREECAD_USE_3DCONNEXION_LEGACY) add_definitions(-DSPNAV_FOUND) include_directories( + SYSTEM ${SPNAV_INCLUDE_DIR} ) list(APPEND FreeCADGui_LIBS @@ -196,6 +203,7 @@ ENDIF(SPNAV_FOUND AND FREECAD_USE_3DCONNEXION_LEGACY) IF(OCULUS_FOUND) add_definitions(-DOCULUS_FOUND) include_directories( + SYSTEM ${OCULUS_INCLUDE_DIRS} ) list(APPEND FreeCADGui_LIBS @@ -206,6 +214,7 @@ ENDIF(OCULUS_FOUND) if(FREECAD_USE_SHIBOKEN) add_definitions(-DHAVE_SHIBOKEN${PYSIDE_MAJOR_VERSION}) include_directories( + SYSTEM ${SHIBOKEN_INCLUDE_DIR} ) if (SHIBOKEN_LIBRARY) @@ -227,6 +236,7 @@ endif(FREECAD_USE_SHIBOKEN) if(FREECAD_USE_PYSIDE) include_directories( + SYSTEM ${PYSIDE_INCLUDE_DIR} ${PYSIDE_INCLUDE_DIR}/QtCore ${PYSIDE_INCLUDE_DIR}/QtGui @@ -247,6 +257,7 @@ if(FREECAD_USE_PYSIDE) endif () endif (PYSIDE_LIBRARY) include_directories( + SYSTEM ${PYSIDE_INCLUDE_DIR}/QtWidgets ) add_definitions(-DHAVE_PYSIDE${PYSIDE_MAJOR_VERSION}) @@ -1069,6 +1080,7 @@ SET(Inventor_CPP_SRCS Inventor/So3DAnnotation.cpp Inventor/SoAutoZoomTranslation.cpp Inventor/SoAxisCrossKit.cpp + Inventor/SoFCPlacementIndicatorKit.cpp Inventor/SoDrawingGrid.cpp Inventor/SoFCBackgroundGradient.cpp Inventor/SoFCBoundingBox.cpp @@ -1101,6 +1113,7 @@ SET(Inventor_SRCS Inventor/SmSwitchboard.h Inventor/SoAutoZoomTranslation.h Inventor/SoAxisCrossKit.h + Inventor/SoFCPlacementIndicatorKit.h Inventor/SoDrawingGrid.h Inventor/SoFCBackgroundGradient.h Inventor/SoFCBoundingBox.h diff --git a/src/Gui/CommandFeat.cpp b/src/Gui/CommandFeat.cpp index de54763b75..b2e5504b82 100644 --- a/src/Gui/CommandFeat.cpp +++ b/src/Gui/CommandFeat.cpp @@ -95,7 +95,7 @@ void StdCmdRandomColor::activated(int iMsg) auto fGrn = (float)rand()/fMax; auto fBlu = (float)rand()/fMax; // NOLINTEND - auto objColor = App::Color(fRed, fGrn, fBlu); + auto objColor = Base::Color(fRed, fGrn, fBlu); auto vpLink = dynamic_cast(view); if (vpLink) { diff --git a/src/Gui/Dialogs/DlgAbout.cpp b/src/Gui/Dialogs/DlgAbout.cpp index 9186620266..45b253a232 100644 --- a/src/Gui/Dialogs/DlgAbout.cpp +++ b/src/Gui/Dialogs/DlgAbout.cpp @@ -668,7 +668,6 @@ void AboutDialog::copyToClipboard() if (ifcopenshellVerAsStr) { str << "IfcOpenShell " << ifcopenshellVerAsStr << ", "; - Py_DECREF(ifcopenshellVerAsStr); } Py_DECREF(ifcopenshellVer); } diff --git a/src/Gui/Dialogs/DlgMaterialPropertiesImp.h b/src/Gui/Dialogs/DlgMaterialPropertiesImp.h index 3b760c3196..be12ff28a5 100644 --- a/src/Gui/Dialogs/DlgMaterialPropertiesImp.h +++ b/src/Gui/Dialogs/DlgMaterialPropertiesImp.h @@ -29,9 +29,13 @@ #include #include -namespace App +namespace Base { class Color; +} + +namespace App +{ class Material; } diff --git a/src/Gui/Document.cpp b/src/Gui/Document.cpp index 2edff11f6b..18b71de9c9 100644 --- a/src/Gui/Document.cpp +++ b/src/Gui/Document.cpp @@ -36,6 +36,7 @@ # include # include # include +# include # include # include # include @@ -1999,11 +2000,11 @@ MDIView *Document::createView(const Base::Type& typeId) std::list theViews = this->getMDIViewsOfType(typeId); if (typeId == View3DInventor::getClassTypeId()) { - QtGLWidget* shareWidget = nullptr; + QOpenGLWidget* shareWidget = nullptr; // VBO rendering doesn't work correctly when we don't share the OpenGL widgets if (!theViews.empty()) { auto firstView = static_cast(theViews.front()); - shareWidget = qobject_cast(firstView->getViewer()->getGLWidget()); + shareWidget = qobject_cast(firstView->getViewer()->getGLWidget()); const char *ppReturn = nullptr; firstView->onMsg("GetCamera",&ppReturn); diff --git a/src/Gui/Flag.cpp b/src/Gui/Flag.cpp index 5d1fcde8fe..3d975110de 100644 --- a/src/Gui/Flag.cpp +++ b/src/Gui/Flag.cpp @@ -43,7 +43,7 @@ using namespace Gui; // Embed complete widgets Flag::Flag(QWidget* parent) - : QtGLWidget(parent), coord(0.0f, 0.0f, 0.0f) + : QOpenGLWidget(parent), coord(0.0f, 0.0f, 0.0f) { this->setFixedHeight(20); setAutoFillBackground(true); @@ -124,7 +124,7 @@ void Flag::setText(const QString& t) void Flag::resizeEvent(QResizeEvent* e) { - QtGLWidget::resizeEvent(e); + QOpenGLWidget::resizeEvent(e); } void Flag::mouseMoveEvent(QMouseEvent *e) diff --git a/src/Gui/Flag.h b/src/Gui/Flag.h index 240eaf2409..6a1e92a331 100644 --- a/src/Gui/Flag.h +++ b/src/Gui/Flag.h @@ -25,6 +25,7 @@ #define GUI_FLAG_H #include +#include #include #include #include @@ -36,7 +37,7 @@ class View3DInventorViewer; /** * @author Werner Mayer */ -class GuiExport Flag : public QtGLWidget +class GuiExport Flag : public QOpenGLWidget { Q_OBJECT diff --git a/src/Gui/GLPainter.cpp b/src/Gui/GLPainter.cpp index 28838b7d23..600d2afb71 100644 --- a/src/Gui/GLPainter.cpp +++ b/src/Gui/GLPainter.cpp @@ -25,6 +25,8 @@ #ifndef _PreComp_ #endif +#include + #include "GLPainter.h" #include "View3DInventorViewer.h" @@ -51,7 +53,7 @@ bool GLPainter::begin(QPaintDevice * device) if (viewer) return false; - viewer = dynamic_cast(device); + viewer = dynamic_cast(device); if (!viewer) return false; diff --git a/src/Gui/GLPainter.h b/src/Gui/GLPainter.h index 19e6bac343..cae84007e0 100644 --- a/src/Gui/GLPainter.h +++ b/src/Gui/GLPainter.h @@ -38,10 +38,10 @@ #include #include -#include #include class QPaintDevice; +class QOpenGLWidget; namespace Gui { class View3DInventorViewer; @@ -75,10 +75,10 @@ public: //@} private: - QtGLWidget* viewer{nullptr}; GLfloat depthrange[2]; GLdouble projectionmatrix[16]; GLint width{0}, height{0}; + QOpenGLWidget* viewer{nullptr}; bool logicOp{false}; bool lineStipple{false}; }; diff --git a/src/Gui/Inventor/SoAxisCrossKit.cpp b/src/Gui/Inventor/SoAxisCrossKit.cpp index ec95db0f03..d60457ae16 100644 --- a/src/Gui/Inventor/SoAxisCrossKit.cpp +++ b/src/Gui/Inventor/SoAxisCrossKit.cpp @@ -52,7 +52,7 @@ # include #endif -#include +#include #include #include "SoAxisCrossKit.h" @@ -225,23 +225,23 @@ SoAxisCrossKit::createAxes() set("zAxis.appearance.drawStyle", "lineWidth 1"); unsigned long colorLong; - App::Color color; + Base::Color color; std::stringstream parameterstring; colorLong = Gui::ViewParams::instance()->getAxisXColor(); - color = App::Color(static_cast(colorLong)); + color = Base::Color(static_cast(colorLong)); parameterstring << "diffuseColor " << color.r << " " << color.g << " " << color.b; set("xAxis.appearance.material", parameterstring.str().c_str()); set("xHead.appearance.material", parameterstring.str().c_str()); colorLong = Gui::ViewParams::instance()->getAxisYColor(); - color = App::Color(static_cast(colorLong)); + color = Base::Color(static_cast(colorLong)); parameterstring << "diffuseColor " << color.r << " " << color.g << " " << color.b; set("yAxis.appearance.material", parameterstring.str().c_str()); set("yHead.appearance.material", parameterstring.str().c_str()); colorLong = Gui::ViewParams::instance()->getAxisZColor(); - color = App::Color(static_cast(colorLong)); + color = Base::Color(static_cast(colorLong)); parameterstring << "diffuseColor " << color.r << " " << color.g << " " << color.b; set("zAxis.appearance.material", parameterstring.str().c_str()); set("zHead.appearance.material", parameterstring.str().c_str()); diff --git a/src/Gui/Inventor/SoFCPlacementIndicatorKit.cpp b/src/Gui/Inventor/SoFCPlacementIndicatorKit.cpp new file mode 100644 index 0000000000..2da7d24382 --- /dev/null +++ b/src/Gui/Inventor/SoFCPlacementIndicatorKit.cpp @@ -0,0 +1,287 @@ +// SPDX-License-Identifier: LGPL-2.1-or-later +/**************************************************************************** + * * + * Copyright (c) 2024 Kacper Donat * + * * + * This file is part of FreeCAD. * + * * + * FreeCAD 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.1 of the * + * License, or (at your option) any later version. * + * * + * FreeCAD 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 FreeCAD. If not, see * + * . * + * * + ***************************************************************************/ + + +#include "PreCompiled.h" + +#ifndef _PreComp_ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#endif + +#include "SoFCPlacementIndicatorKit.h" + +#include "So3DAnnotation.h" +#include "SoAxisCrossKit.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace Gui +{ + +SO_KIT_SOURCE(SoFCPlacementIndicatorKit); + +SoFCPlacementIndicatorKit::SoFCPlacementIndicatorKit() +{ + SO_KIT_CONSTRUCTOR(SoFCPlacementIndicatorKit); + + SO_KIT_ADD_CATALOG_ENTRY(root, SoShapeScale, false, this, "", true); + + SO_KIT_INIT_INSTANCE(); + + SO_NODE_ADD_FIELD(coloredAxis, (true)); + SO_NODE_ADD_FIELD(scaleFactor, (scaleFactorDefault)); + SO_NODE_ADD_FIELD(axisLength, (axisLengthDefault)); + + SO_NODE_ADD_FIELD(parts, (AxisCross)); + SO_NODE_DEFINE_ENUM_VALUE(Part, Axes); + SO_NODE_DEFINE_ENUM_VALUE(Part, PlaneIndicator); + SO_NODE_DEFINE_ENUM_VALUE(Part, Labels); + SO_NODE_DEFINE_ENUM_VALUE(Part, ArrowHeads); + SO_NODE_DEFINE_ENUM_VALUE(Part, AxisCross); + SO_NODE_DEFINE_ENUM_VALUE(Part, AllParts); + SO_NODE_SET_SF_ENUM_TYPE(parts, Part); + + SO_NODE_ADD_FIELD(axes, (AllAxes)); + SO_NODE_DEFINE_ENUM_VALUE(Axes, X); + SO_NODE_DEFINE_ENUM_VALUE(Axes, Y); + SO_NODE_DEFINE_ENUM_VALUE(Axes, Z); + SO_NODE_DEFINE_ENUM_VALUE(Axes, AllAxes); + SO_NODE_SET_SF_ENUM_TYPE(axes, Axes); + + auto root = SO_GET_ANY_PART(this, "root", SoShapeScale); + root->scaleFactor.connectFrom(&scaleFactor); + + recomputeGeometry(); +} + +void SoFCPlacementIndicatorKit::initClass() +{ + SO_KIT_INIT_CLASS(SoFCPlacementIndicatorKit, SoBaseKit, "BaseKit"); +} + +void SoFCPlacementIndicatorKit::notify(SoNotList* l) +{ + SoField* field = l->getLastField(); + + if (field == &parts || field == &axes || field == &axisLength) { + // certainly this is not the fastest way to recompute the geometry as it does recreate + // everything from the scratch. It is however very easy to implement and this node should + // not really change too often so the performance penalty is better than making code that + // is harder to maintain. + recomputeGeometry(); + return; + } + + SoBaseKit::notify(l); +} + +void SoFCPlacementIndicatorKit::recomputeGeometry() +{ + auto root = SO_GET_ANY_PART(this, "root", SoShapeScale); + root->setPart("shape", createGeometry()); +} + +SoSeparator* SoFCPlacementIndicatorKit::createGeometry() +{ + auto sep = new SoSeparator(); + + auto pcBaseColor = new SoBaseColor(); + pcBaseColor->rgb.setValue(0.7f, 0.7f, 0.5f); + + auto pcLightModel = new SoLightModel(); + pcLightModel->model = SoLightModel::BASE_COLOR; + + sep->addChild(pcBaseColor); + sep->addChild(pcLightModel); + + if (parts.getValue() & PlaneIndicator) { + sep->addChild(createPlaneIndicator()); + } + + if (parts.getValue() & Axes) { + sep->addChild(createAxes()); + } + + return sep; +} + +SoSeparator* SoFCPlacementIndicatorKit::createAxes() +{ + const auto cylinderOffset = axisLength.getValue() / 2.f; + + const auto createAxis = [&](const char* label, + Base::Vector3d axis, + uint32_t packedColor, + const double offset) { + Base::Color axisColor(packedColor); + + auto sep = new SoSeparator; + + auto rotation = Base::Rotation(Base::Vector3d::UnitY, axis); + auto pcTranslate = new SoTransform(); + pcTranslate->translation.setValue( + Base::convertTo((cylinderOffset + offset) * axis)); + pcTranslate->rotation.setValue(Base::convertTo(rotation)); + + auto pcArrowShaft = new SoCylinder(); + pcArrowShaft->radius = axisThickness / 2.0f; + pcArrowShaft->height = axisLength; + + if (coloredAxis.getValue()) { + auto pcBaseColor = new SoBaseColor(); + pcBaseColor->rgb.setValue(Base::convertTo(axisColor)); + + sep->addChild(pcBaseColor); + } + + sep->addChild(pcTranslate); + sep->addChild(pcArrowShaft); + + if (parts.getValue() & ArrowHeads) { + auto pcArrowHeadTranslation = new SoTranslation(); + pcArrowHeadTranslation->translation.setValue(0.0, cylinderOffset, 0.0); + + auto pcArrowHead = new SoCone(); + pcArrowHead->bottomRadius = arrowHeadRadius; + pcArrowHead->height = arrowHeadHeight; + + auto pcArrowHeadSeparator = new SoSeparator(); + pcArrowHeadSeparator->addChild(pcArrowHeadTranslation); + pcArrowHeadSeparator->addChild(pcArrowHead); + + sep->addChild(pcArrowHeadSeparator); + } + + if (parts.getValue() & Labels) { + auto pcLabelSeparator = new SoSeparator(); + + auto pcLabelTranslation = new SoTranslation(); + pcLabelTranslation->translation.setValue(0.0, cylinderOffset + labelOffset, 0.0); + pcLabelSeparator->addChild(pcLabelTranslation); + + auto pcAxisLabel = new SoFrameLabel(); + pcAxisLabel->string.setValue(label); + pcAxisLabel->textColor.setValue(1.0, 1.0, 1.0); + pcAxisLabel->horAlignment = SoImage::CENTER; + pcAxisLabel->vertAlignment = SoImage::HALF; + pcAxisLabel->border = false; + pcAxisLabel->frame = false; + pcAxisLabel->textUseBaseColor = true; + pcAxisLabel->size = labelFontSize; + + pcLabelSeparator->addChild(pcAxisLabel); + + sep->addChild(pcLabelSeparator); + } + + return sep; + }; + + auto sep = new SoSeparator; + + auto xyOffset = (parts.getValue() & PlaneIndicator) + ? planeIndicatorRadius + planeIndicatorMargin + : axisMargin; + + if (axes.getValue() & X) { + sep->addChild(createAxis("X", + Base::Vector3d::UnitX, + ViewParams::instance()->getAxisXColor(), + xyOffset)); + } + + if (axes.getValue() & Y) { + sep->addChild(createAxis("Y", + Base::Vector3d::UnitY, + ViewParams::instance()->getAxisYColor(), + xyOffset)); + } + + if (axes.getValue() & Z) { + auto zOffset = (parts.getValue() & PlaneIndicator) + ? planeIndicatorMargin + : axisMargin; + sep->addChild(createAxis("Z", + Base::Vector3d::UnitZ, + ViewParams::instance()->getAxisZColor(), + zOffset)); + } + + return sep; +} + +SoSeparator* SoFCPlacementIndicatorKit::createPlaneIndicator() +{ + // cylinders are aligned with Y axis for some reason + auto rotation = Base::Rotation(Base::Vector3d::UnitY, Base::Vector3d::UnitZ); + + auto pcRotation = new SoRotation(); + pcRotation->rotation = Base::convertTo(rotation); + + auto pcComplexity = new SoComplexity(); + pcComplexity->value = 1.0f; + + auto pcCylinder = new SoCylinder(); + pcCylinder->height = 0.f; + pcCylinder->radius = planeIndicatorRadius; + pcCylinder->parts = SoCylinder::TOP; + + const auto gray = Base::Color(0.75f, 0.75f, 0.75f); + + auto pcMaterial = new SoMaterial(); + pcMaterial->diffuseColor.setValue(Base::convertTo(gray)); + pcMaterial->ambientColor.connectFrom(&pcMaterial->diffuseColor); + pcMaterial->transparency = planeIndicatorTransparency; + + auto sep = new SoSeparator; + + sep->addChild(pcRotation); + sep->addChild(pcMaterial); + sep->addChild(pcComplexity); + sep->addChild(pcCylinder); + + return sep; +} + +SoFCPlacementIndicatorKit::~SoFCPlacementIndicatorKit() = default; + +} // namespace Gui diff --git a/src/Gui/Inventor/SoFCPlacementIndicatorKit.h b/src/Gui/Inventor/SoFCPlacementIndicatorKit.h new file mode 100644 index 0000000000..2346c8d5fe --- /dev/null +++ b/src/Gui/Inventor/SoFCPlacementIndicatorKit.h @@ -0,0 +1,103 @@ +// SPDX-License-Identifier: LGPL-2.1-or-later +/**************************************************************************** + * * + * Copyright (c) 2024 Kacper Donat * + * * + * This file is part of FreeCAD. * + * * + * FreeCAD 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.1 of the * + * License, or (at your option) any later version. * + * * + * FreeCAD 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 FreeCAD. If not, see * + * . * + * * + ***************************************************************************/ + +#ifndef SOFCPLACEMENTINDICATORKIT_H +#define SOFCPLACEMENTINDICATORKIT_H + +#include + +#include + +namespace Gui { + +class GuiExport SoFCPlacementIndicatorKit : public SoBaseKit { + using inherited = SoBaseKit; + + static constexpr double planeIndicatorRadius = 0.4f; + static constexpr double planeIndicatorMargin = 0.2f; + static constexpr double planeIndicatorTransparency = 0.3f; + + static constexpr double axisMargin = 0.0f; + static constexpr double axisLengthDefault = 0.6f; + static constexpr double axisThickness = 0.065f; + + static constexpr double arrowHeadRadius = axisThickness * 1.25f; + static constexpr double arrowHeadHeight = arrowHeadRadius * 3.f; + + static constexpr double labelOffset = 0.4f; + static constexpr int labelFontSize = 9; + + static constexpr double scaleFactorDefault = 40.f; + + SO_KIT_HEADER(SoFCPlacementIndicatorKit); + + SO_KIT_CATALOG_ENTRY_HEADER(root); + +public: + SoFCPlacementIndicatorKit(); + static void initClass(); + + void notify(SoNotList* l) override; + + // clang-format off + enum Part + { + Axes = 1 << 0, + PlaneIndicator = 1 << 1, + Labels = 1 << 2, + ArrowHeads = 1 << 3, + + // common configurations + AllParts = Axes | PlaneIndicator | Labels | ArrowHeads, + AxisCross = Axes | Labels | ArrowHeads + }; + + enum Axis + { + X = 1 << 0, + Y = 1 << 1, + Z = 1 << 2, + AllAxes = X | Y | Z + }; + // clang-format on + + SoSFEnum parts; + SoSFEnum axes; + SoSFBool coloredAxis; + SoSFFloat scaleFactor; + SoSFFloat axisLength; + +private: + void recomputeGeometry(); + + SoSeparator* createOriginIndicator(); + SoSeparator* createGeometry(); + SoSeparator* createAxes(); + SoSeparator* createPlaneIndicator(); + + ~SoFCPlacementIndicatorKit() override; +}; + +} // Gui + +#endif //SOFCPLACEMENTINDICATORKIT_H diff --git a/src/Gui/MainWindow.cpp b/src/Gui/MainWindow.cpp index c02f15cdf6..4bc644ce7f 100644 --- a/src/Gui/MainWindow.cpp +++ b/src/Gui/MainWindow.cpp @@ -40,6 +40,7 @@ # include # include # include +# include # include # include # include @@ -115,7 +116,7 @@ #include "View3DInventor.h" #include "View3DInventorViewer.h" #include "Dialogs/DlgObjectSelection.h" -#include +#include FC_LOG_LEVEL_INIT("MainWindow",false,true,true) @@ -2348,15 +2349,15 @@ void MainWindow::setWindowTitle(const QString& string) auto format = QStringLiteral("#statusBar{color: %1}"); if (strcmp(sReason, "colorText") == 0) { unsigned long col = rclGrp.GetUnsigned(sReason); - this->msg = format.arg(App::Color::fromPackedRGB(col).name()); + this->msg = format.arg(Base::Color::fromPackedRGB(col).name()); } else if (strcmp(sReason, "colorWarning") == 0) { unsigned long col = rclGrp.GetUnsigned(sReason); - this->wrn = format.arg(App::Color::fromPackedRGB(col).name()); + this->wrn = format.arg(Base::Color::fromPackedRGB(col).name()); } else if (strcmp(sReason, "colorError") == 0) { unsigned long col = rclGrp.GetUnsigned(sReason); - this->err = format.arg(App::Color::fromPackedRGB(col).name()); + this->err = format.arg(Base::Color::fromPackedRGB(col).name()); } else if (strcmp(sReason, "colorCritical") == 0) { unsigned long col = rclGrp.GetUnsigned(sReason); diff --git a/src/Gui/ManualAlignment.cpp b/src/Gui/ManualAlignment.cpp index 419acfd717..10d54bf429 100644 --- a/src/Gui/ManualAlignment.cpp +++ b/src/Gui/ManualAlignment.cpp @@ -30,6 +30,7 @@ # include # include # include +# include # include # include # include @@ -352,7 +353,7 @@ public: bool smoothing = false; bool glformat = false; int samples = View3DInventorViewer::getNumSamples(); - QtGLFormat f; + QSurfaceFormat f; if (samples > 1) { glformat = true; diff --git a/src/Gui/MouseSelection.cpp b/src/Gui/MouseSelection.cpp index 7160f06bee..bf90a4054a 100644 --- a/src/Gui/MouseSelection.cpp +++ b/src/Gui/MouseSelection.cpp @@ -23,6 +23,7 @@ #include "PreCompiled.h" #ifndef _PreComp_ +#include #include #include #include @@ -575,7 +576,7 @@ void RubberbandSelection::initialize() rubberband.setViewer(_pcView3D); rubberband.setWorking(false); _pcView3D->addGraphicsItem(&rubberband); - if (QtGLFramebufferObject::hasOpenGLFramebufferObjects()) { + if (QOpenGLFramebufferObject::hasOpenGLFramebufferObjects()) { _pcView3D->setRenderType(View3DInventorViewer::Image); } _pcView3D->redraw(); @@ -586,7 +587,7 @@ void RubberbandSelection::terminate(bool abort) Q_UNUSED(abort) _pcView3D->removeGraphicsItem(&rubberband); - if (QtGLFramebufferObject::hasOpenGLFramebufferObjects()) { + if (QOpenGLFramebufferObject::hasOpenGLFramebufferObjects()) { _pcView3D->setRenderType(View3DInventorViewer::Native); } _pcView3D->redraw(); diff --git a/src/Gui/NaviCube.cpp b/src/Gui/NaviCube.cpp index d84e9ad2c2..2e25fc0440 100644 --- a/src/Gui/NaviCube.cpp +++ b/src/Gui/NaviCube.cpp @@ -41,11 +41,13 @@ # include # include # include +# include # include +# include # include #endif -#include +#include #include #include @@ -177,9 +179,9 @@ public: float m_InactiveOpacity = 0.5; SbVec2s m_PosOffset = SbVec2s(0,0); - App::Color m_xColor; - App::Color m_yColor; - App::Color m_zColor; + Base::Color m_xColor; + Base::Color m_yColor; + Base::Color m_zColor; bool m_Prepared = false; static vector m_commands; @@ -196,7 +198,7 @@ private: SbVec2s m_PosAreaBase = SbVec2s(0,0); SbVec2s m_PosAreaSize = SbVec2s(0,0); - QtGLFramebufferObject* m_PickingFramebuffer; + QOpenGLFramebufferObject* m_PickingFramebuffer; Gui::View3DInventorViewer* m_View3DInventorViewer; map m_Faces; @@ -704,8 +706,8 @@ void NaviCubeImplementation::prepare() if (m_PickingFramebuffer) delete m_PickingFramebuffer; m_PickingFramebuffer = - new QtGLFramebufferObject(2 * m_CubeWidgetSize, 2 * m_CubeWidgetSize, - QtGLFramebufferObject::CombinedDepthStencil); + new QOpenGLFramebufferObject(2 * m_CubeWidgetSize, 2 * m_CubeWidgetSize, + QOpenGLFramebufferObject::CombinedDepthStencil); m_View3DInventorViewer->getSoRenderManager()->scheduleRedraw(); } @@ -935,7 +937,7 @@ NaviCubeImplementation::PickId NaviCubeImplementation::pickFace(short x, short y GLubyte pixels[4] = {0}; if (m_PickingFramebuffer && std::abs(x) <= m_CubeWidgetSize / 2 && std::abs(y) <= m_CubeWidgetSize / 2) { - static_cast(m_View3DInventorViewer->viewport())->makeCurrent(); + static_cast(m_View3DInventorViewer->viewport())->makeCurrent(); m_PickingFramebuffer->bind(); glViewport(0, 0, m_CubeWidgetSize * 2, m_CubeWidgetSize * 2); @@ -946,7 +948,7 @@ NaviCubeImplementation::PickId NaviCubeImplementation::pickFace(short x, short y glReadPixels(2 * x + m_CubeWidgetSize, 2 * y + m_CubeWidgetSize, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, &pixels); m_PickingFramebuffer->release(); - static_cast(m_View3DInventorViewer->viewport())->doneCurrent(); + static_cast(m_View3DInventorViewer->viewport())->doneCurrent(); } return pixels[3] == 255 ? static_cast(pixels[0]) : PickId::None; } @@ -1191,11 +1193,11 @@ void NaviCube::updateColors() unsigned long colorLong; colorLong = Gui::ViewParams::instance()->getAxisXColor(); - m_NaviCubeImplementation->m_xColor = App::Color(static_cast(colorLong)); + m_NaviCubeImplementation->m_xColor = Base::Color(static_cast(colorLong)); colorLong = Gui::ViewParams::instance()->getAxisYColor(); - m_NaviCubeImplementation->m_yColor = App::Color(static_cast(colorLong)); + m_NaviCubeImplementation->m_yColor = Base::Color(static_cast(colorLong)); colorLong = Gui::ViewParams::instance()->getAxisZColor(); - m_NaviCubeImplementation->m_zColor = App::Color(static_cast(colorLong)); + m_NaviCubeImplementation->m_zColor = Base::Color(static_cast(colorLong)); } void NaviCube::setNaviCubeCommands(const std::vector& cmd) diff --git a/src/Gui/PrefWidgets.cpp b/src/Gui/PrefWidgets.cpp index abd41dda7c..c3e69656bd 100644 --- a/src/Gui/PrefWidgets.cpp +++ b/src/Gui/PrefWidgets.cpp @@ -30,7 +30,7 @@ #include #include -#include +#include #include "PrefWidgets.h" @@ -562,12 +562,12 @@ void PrefColorButton::restorePreferences() if (!m_Restored) m_Default = color(); - unsigned int icol = App::Color::asPackedRGBA(m_Default); + unsigned int icol = Base::Color::asPackedRGBA(m_Default); unsigned long lcol = static_cast(icol); lcol = getWindowParameter()->GetUnsigned(entryName(), lcol); icol = static_cast(lcol); - QColor value = App::Color::fromPackedRGBA(icol); + QColor value = Base::Color::fromPackedRGBA(icol); if (!this->allowTransparency()) value.setAlpha(0xff); setColor(value); @@ -583,7 +583,7 @@ void PrefColorButton::savePreferences() QColor col = color(); // (r,g,b,a) with a = 255 (opaque) - unsigned int icol = App::Color::asPackedRGBA(col); + unsigned int icol = Base::Color::asPackedRGBA(col); unsigned long lcol = static_cast(icol); getWindowParameter()->SetUnsigned( entryName(), lcol ); } diff --git a/src/Gui/PreferencePages/DlgSettingsEditor.cpp b/src/Gui/PreferencePages/DlgSettingsEditor.cpp index 4ccde4fdab..6567533e73 100644 --- a/src/Gui/PreferencePages/DlgSettingsEditor.cpp +++ b/src/Gui/PreferencePages/DlgSettingsEditor.cpp @@ -26,7 +26,7 @@ #include #endif -#include +#include #include #include @@ -85,63 +85,63 @@ DlgSettingsEditor::DlgSettingsEditor(QWidget* parent) d = new DlgSettingsEditorP(); QColor col; col = qApp->palette().windowText().color(); - unsigned int lText = App::Color::asPackedRGB(col); + unsigned int lText = Base::Color::asPackedRGB(col); d->colormap.push_back( QPair(QString::fromLatin1(QT_TR_NOOP("Text")), lText)); - unsigned int lBookmarks = App::Color::asPackedRGB(QColor(Qt::cyan)); + unsigned int lBookmarks = Base::Color::asPackedRGB(QColor(Qt::cyan)); d->colormap.push_back( QPair(QString::fromLatin1(QT_TR_NOOP("Bookmark")), lBookmarks)); - unsigned int lBreakpnts = App::Color::asPackedRGB(QColor(Qt::red)); + unsigned int lBreakpnts = Base::Color::asPackedRGB(QColor(Qt::red)); d->colormap.push_back( QPair(QString::fromLatin1(QT_TR_NOOP("Breakpoint")), lBreakpnts)); - unsigned int lKeywords = App::Color::asPackedRGB(QColor(Qt::blue)); + unsigned int lKeywords = Base::Color::asPackedRGB(QColor(Qt::blue)); d->colormap.push_back( QPair(QString::fromLatin1(QT_TR_NOOP("Keyword")), lKeywords)); - unsigned int lComments = App::Color::asPackedRGB(QColor(0, 170, 0)); + unsigned int lComments = Base::Color::asPackedRGB(QColor(0, 170, 0)); d->colormap.push_back( QPair(QString::fromLatin1(QT_TR_NOOP("Comment")), lComments)); - unsigned int lBlockCom = App::Color::asPackedRGB(QColor(160, 160, 164)); + unsigned int lBlockCom = Base::Color::asPackedRGB(QColor(160, 160, 164)); d->colormap.push_back( QPair(QString::fromLatin1(QT_TR_NOOP("Block comment")), lBlockCom)); - unsigned int lNumbers = App::Color::asPackedRGB(QColor(Qt::blue)); + unsigned int lNumbers = Base::Color::asPackedRGB(QColor(Qt::blue)); d->colormap.push_back( QPair(QString::fromLatin1(QT_TR_NOOP("Number")), lNumbers)); - unsigned int lStrings = App::Color::asPackedRGB(QColor(Qt::red)); + unsigned int lStrings = Base::Color::asPackedRGB(QColor(Qt::red)); d->colormap.push_back( QPair(QString::fromLatin1(QT_TR_NOOP("String")), lStrings)); - unsigned int lCharacter = App::Color::asPackedRGB(QColor(Qt::red)); + unsigned int lCharacter = Base::Color::asPackedRGB(QColor(Qt::red)); d->colormap.push_back( QPair(QString::fromLatin1(QT_TR_NOOP("Character")), lCharacter)); - unsigned int lClass = App::Color::asPackedRGB(QColor(255, 170, 0)); + unsigned int lClass = Base::Color::asPackedRGB(QColor(255, 170, 0)); d->colormap.push_back( QPair(QString::fromLatin1(QT_TR_NOOP("Class name")), lClass)); - unsigned int lDefine = App::Color::asPackedRGB(QColor(255, 170, 0)); + unsigned int lDefine = Base::Color::asPackedRGB(QColor(255, 170, 0)); d->colormap.push_back( QPair(QString::fromLatin1(QT_TR_NOOP("Define name")), lDefine)); - unsigned int lOperat = App::Color::asPackedRGB(QColor(160, 160, 164)); + unsigned int lOperat = Base::Color::asPackedRGB(QColor(160, 160, 164)); d->colormap.push_back( QPair(QString::fromLatin1(QT_TR_NOOP("Operator")), lOperat)); - unsigned int lPyOutput = App::Color::asPackedRGB(QColor(170, 170, 127)); + unsigned int lPyOutput = Base::Color::asPackedRGB(QColor(170, 170, 127)); d->colormap.push_back( QPair(QString::fromLatin1(QT_TR_NOOP("Python output")), lPyOutput)); - unsigned int lPyError = App::Color::asPackedRGB(QColor(Qt::red)); + unsigned int lPyError = Base::Color::asPackedRGB(QColor(Qt::red)); d->colormap.push_back( QPair(QString::fromLatin1(QT_TR_NOOP("Python error")), lPyError)); - unsigned int lCLine = App::Color::asPackedRGB(QColor(224, 224, 224)); + unsigned int lCLine = Base::Color::asPackedRGB(QColor(224, 224, 224)); d->colormap.push_back( QPair(QString::fromLatin1(QT_TR_NOOP("Current line highlight")), lCLine)); @@ -195,14 +195,14 @@ void DlgSettingsEditor::onDisplayItemsCurrentItemChanged(QTreeWidgetItem* item) { int index = ui->displayItems->indexOfTopLevelItem(item); unsigned int col = d->colormap[index].second; - ui->colorButton->setColor(App::Color::fromPackedRGB(col)); + ui->colorButton->setColor(Base::Color::fromPackedRGB(col)); } /** Updates the color map if a color was changed */ void DlgSettingsEditor::onColorButtonChanged() { QColor col = ui->colorButton->color(); - unsigned int lcol = App::Color::asPackedRGB(col); + unsigned int lcol = Base::Color::asPackedRGB(col); int index = ui->displayItems->indexOfTopLevelItem(ui->displayItems->currentItem()); d->colormap[index].second = lcol; @@ -272,7 +272,7 @@ void DlgSettingsEditor::loadSettings() auto col = static_cast(textColor); col = hGrp->GetUnsigned(textType.toLatin1(), col); textColor = static_cast(col); - QColor color = App::Color::fromPackedRGB(col); + QColor color = Base::Color::fromPackedRGB(col); pythonSyntax->setColor(textType, color); } diff --git a/src/Gui/PreferencePages/DlgSettingsLightSources.cpp b/src/Gui/PreferencePages/DlgSettingsLightSources.cpp index d39fe4bf50..034017a009 100644 --- a/src/Gui/PreferencePages/DlgSettingsLightSources.cpp +++ b/src/Gui/PreferencePages/DlgSettingsLightSources.cpp @@ -327,6 +327,10 @@ void DlgSettingsLightSources::resetSettingsToDefaults() { PreferencePage::resetSettingsToDefaults(); + hGrp->RemoveASCII("HeadlightDirection"); + hGrp->RemoveASCII("BacklightDirection"); + hGrp->RemoveASCII("FillLightDirection"); + loadSettings(); configureViewer(); } diff --git a/src/Gui/PythonConsole.cpp b/src/Gui/PythonConsole.cpp index bed38eb94f..13b8e8c537 100644 --- a/src/Gui/PythonConsole.cpp +++ b/src/Gui/PythonConsole.cpp @@ -37,7 +37,7 @@ #endif #include -#include +#include #include "PythonConsole.h" #include "PythonConsolePy.h" @@ -947,7 +947,7 @@ void PythonConsole::changeEvent(QEvent *e) else if (e->type() == QEvent::StyleChange) { QPalette pal = qApp->palette(); QColor color = pal.windowText().color(); - unsigned int text = App::Color::asPackedRGB(color); + unsigned int text = Base::Color::asPackedRGB(color); auto value = static_cast(text); // if this parameter is not already set use the style's window text color value = getWindowParameter()->GetUnsigned("Text", value); diff --git a/src/Gui/QtAll.h b/src/Gui/QtAll.h index 0bb24bdc1d..055414db28 100644 --- a/src/Gui/QtAll.h +++ b/src/Gui/QtAll.h @@ -87,6 +87,7 @@ #include #include #include +#include #include #include #include diff --git a/src/Gui/Quarter/QuarterWidget.cpp b/src/Gui/Quarter/QuarterWidget.cpp index 96a3bf66f1..bcc76dd297 100644 --- a/src/Gui/Quarter/QuarterWidget.cpp +++ b/src/Gui/Quarter/QuarterWidget.cpp @@ -70,6 +70,7 @@ #include #include #include +#include #include #include #include @@ -230,7 +231,7 @@ public: }; /*! constructor */ -QuarterWidget::QuarterWidget(const QtGLFormat & format, QWidget * parent, const QtGLWidget * sharewidget, Qt::WindowFlags f) +QuarterWidget::QuarterWidget(const QSurfaceFormat & format, QWidget * parent, const QOpenGLWidget * sharewidget, Qt::WindowFlags f) : inherited(parent) { Q_UNUSED(f); @@ -238,15 +239,15 @@ QuarterWidget::QuarterWidget(const QtGLFormat & format, QWidget * parent, const } /*! constructor */ -QuarterWidget::QuarterWidget(QWidget * parent, const QtGLWidget * sharewidget, Qt::WindowFlags f) +QuarterWidget::QuarterWidget(QWidget * parent, const QOpenGLWidget * sharewidget, Qt::WindowFlags f) : inherited(parent) { Q_UNUSED(f); - this->constructor(QtGLFormat(), sharewidget); + this->constructor(QSurfaceFormat(), sharewidget); } /*! constructor */ -QuarterWidget::QuarterWidget(QtGLContext * context, QWidget * parent, const QtGLWidget * sharewidget, Qt::WindowFlags f) +QuarterWidget::QuarterWidget(QOpenGLContext * context, QWidget * parent, const QOpenGLWidget * sharewidget, Qt::WindowFlags f) : inherited(parent) { Q_UNUSED(f); @@ -254,7 +255,7 @@ QuarterWidget::QuarterWidget(QtGLContext * context, QWidget * parent, const QtGL } void -QuarterWidget::constructor(const QtGLFormat & format, const QtGLWidget * sharewidget) +QuarterWidget::constructor(const QSurfaceFormat & format, const QOpenGLWidget * sharewidget) { QGraphicsScene* scene = new QGraphicsScene(this); setScene(scene); @@ -856,7 +857,7 @@ void QuarterWidget::paintEvent(QPaintEvent* event) glMatrixMode(GL_PROJECTION); - QtGLWidget* w = static_cast(this->viewport()); + QOpenGLWidget* w = static_cast(this->viewport()); if (!w->isValid()) { qWarning() << "No valid GL context found!"; return; diff --git a/src/Gui/Quarter/QuarterWidget.h b/src/Gui/Quarter/QuarterWidget.h index 81ecfe9a04..0e9b806745 100644 --- a/src/Gui/Quarter/QuarterWidget.h +++ b/src/Gui/Quarter/QuarterWidget.h @@ -39,10 +39,12 @@ #include #include #include -#include #include "Basic.h" +class QOpenGLContext; +class QOpenGLWidget; +class QSurfaceFormat; class QMenu; class SoNode; @@ -114,9 +116,9 @@ public: public: - explicit QuarterWidget(QWidget * parent = nullptr, const QtGLWidget * sharewidget = nullptr, Qt::WindowFlags f = Qt::WindowFlags()); - explicit QuarterWidget(QtGLContext * context, QWidget * parent = nullptr, const QtGLWidget * sharewidget = nullptr, Qt::WindowFlags f = Qt::WindowFlags()); - explicit QuarterWidget(const QtGLFormat & format, QWidget * parent = nullptr, const QtGLWidget * shareWidget = nullptr, Qt::WindowFlags f = Qt::WindowFlags()); + explicit QuarterWidget(QWidget * parent = nullptr, const QOpenGLWidget * sharewidget = nullptr, Qt::WindowFlags f = Qt::WindowFlags()); + explicit QuarterWidget(QOpenGLContext * context, QWidget * parent = nullptr, const QOpenGLWidget * sharewidget = nullptr, Qt::WindowFlags f = Qt::WindowFlags()); + explicit QuarterWidget(const QSurfaceFormat & format, QWidget * parent = nullptr, const QOpenGLWidget * shareWidget = nullptr, Qt::WindowFlags f = Qt::WindowFlags()); ~QuarterWidget() override; TransparencyType transparencyType() const; @@ -203,7 +205,7 @@ protected: virtual bool updateDevicePixelRatio(); private: - void constructor(const QtGLFormat& format, const QtGLWidget* sharewidget); + void constructor(const QSurfaceFormat& format, const QOpenGLWidget* sharewidget); friend class QuarterWidgetP; class QuarterWidgetP * pimpl; bool initialized; diff --git a/src/Gui/Quarter/QuarterWidgetP.cpp b/src/Gui/Quarter/QuarterWidgetP.cpp index a469517566..bdfb46cdd5 100644 --- a/src/Gui/Quarter/QuarterWidgetP.cpp +++ b/src/Gui/Quarter/QuarterWidgetP.cpp @@ -42,6 +42,8 @@ #include #include #include +#include +#include #include #include @@ -63,12 +65,12 @@ using namespace SIM::Coin3D::Quarter; class QuarterWidgetP_cachecontext { public: uint32_t id; - SbList widgetlist; + SbList widgetlist; }; static SbList * cachecontext_list = nullptr; -QuarterWidgetP::QuarterWidgetP(QuarterWidget * masterptr, const QtGLWidget * sharewidget) +QuarterWidgetP::QuarterWidgetP(QuarterWidget * masterptr, const QOpenGLWidget * sharewidget) : master(masterptr), scene(nullptr), eventfilter(nullptr), @@ -104,7 +106,7 @@ QuarterWidgetP::QuarterWidgetP(QuarterWidget * masterptr, const QtGLWidget * sha QuarterWidgetP::~QuarterWidgetP() { - QtGLWidget* glMaster = static_cast(this->master->viewport()); + QOpenGLWidget* glMaster = static_cast(this->master->viewport()); removeFromCacheContext(this->cachecontext, glMaster); delete this->contextmenu; } @@ -133,7 +135,7 @@ QuarterWidgetP::getCacheContextId() const } QuarterWidgetP_cachecontext * -QuarterWidgetP::findCacheContext(QuarterWidget * widget, const QtGLWidget * sharewidget) +QuarterWidgetP::findCacheContext(QuarterWidget * widget, const QOpenGLWidget * sharewidget) { if (!cachecontext_list) { // FIXME: static memory leak @@ -144,34 +146,34 @@ QuarterWidgetP::findCacheContext(QuarterWidget * widget, const QtGLWidget * shar for (int j = 0; j < cachecontext->widgetlist.getLength(); j++) { if (cachecontext->widgetlist[j] == sharewidget) { - cachecontext->widgetlist.append(static_cast(widget->viewport())); + cachecontext->widgetlist.append(static_cast(widget->viewport())); return cachecontext; } } } QuarterWidgetP_cachecontext * cachecontext = new QuarterWidgetP_cachecontext; cachecontext->id = SoGLCacheContextElement::getUniqueCacheContext(); - cachecontext->widgetlist.append(static_cast(widget->viewport())); + cachecontext->widgetlist.append(static_cast(widget->viewport())); cachecontext_list->append(cachecontext); return cachecontext; } void -QuarterWidgetP::removeFromCacheContext(QuarterWidgetP_cachecontext * context, const QtGLWidget * widget) +QuarterWidgetP::removeFromCacheContext(QuarterWidgetP_cachecontext * context, const QOpenGLWidget * widget) { - context->widgetlist.removeItem((const QtGLWidget*) widget); + context->widgetlist.removeItem((const QOpenGLWidget*) widget); if (context->widgetlist.getLength() == 0) { // last context in this share group? assert(cachecontext_list); for (int i = 0; i < cachecontext_list->getLength(); i++) { if ((*cachecontext_list)[i] == context) { - QtGLContext* glcontext = widget->context(); + QOpenGLContext* glcontext = widget->context(); if (glcontext) { // set the context while calling destructingContext() (might trigger OpenGL calls) if (glcontext->isValid()) { - const_cast (widget)->makeCurrent(); + const_cast (widget)->makeCurrent(); } // fetch the cc_glglue context instance as a workaround for a bug fixed in Coin r12818 (void) cc_glglue_instance(context->id); @@ -180,7 +182,7 @@ QuarterWidgetP::removeFromCacheContext(QuarterWidgetP_cachecontext * context, co SoContextHandler::destructingContext(context->id); if (glcontext) { if (glcontext->isValid()) { - const_cast (widget)->doneCurrent(); + const_cast (widget)->doneCurrent(); } } delete context; @@ -191,9 +193,9 @@ QuarterWidgetP::removeFromCacheContext(QuarterWidgetP_cachecontext * context, co } void -QuarterWidgetP::replaceGLWidget(const QtGLWidget * newviewport) +QuarterWidgetP::replaceGLWidget(const QOpenGLWidget * newviewport) { - QtGLWidget* oldviewport = static_cast(this->master->viewport()); + QOpenGLWidget* oldviewport = static_cast(this->master->viewport()); cachecontext->widgetlist.removeItem(oldviewport); cachecontext->widgetlist.append(newviewport); } diff --git a/src/Gui/Quarter/QuarterWidgetP.h b/src/Gui/Quarter/QuarterWidgetP.h index c0ed5e01ad..80f16fd2a8 100644 --- a/src/Gui/Quarter/QuarterWidgetP.h +++ b/src/Gui/Quarter/QuarterWidgetP.h @@ -36,8 +36,8 @@ #include #include #include -#include +class QOpenGLWidget; class SoNode; class SoCamera; @@ -61,7 +61,7 @@ class ContextMenu; class QuarterWidgetP { public: - QuarterWidgetP(class QuarterWidget * master, const QtGLWidget * sharewidget); + QuarterWidgetP(class QuarterWidget * master, const QOpenGLWidget * sharewidget); ~QuarterWidgetP(); SoCamera * searchForCamera(SoNode * root); @@ -109,11 +109,11 @@ public: mutable ContextMenu * contextmenu; static bool nativeEventFilter(void * message, long * result); - void replaceGLWidget(const QtGLWidget * newviewport); + void replaceGLWidget(const QOpenGLWidget * newviewport); private: - QuarterWidgetP_cachecontext * findCacheContext(QuarterWidget * widget, const QtGLWidget * sharewidget); - static void removeFromCacheContext(QuarterWidgetP_cachecontext * context, const QtGLWidget * widget); + QuarterWidgetP_cachecontext * findCacheContext(QuarterWidget * widget, const QOpenGLWidget * sharewidget); + static void removeFromCacheContext(QuarterWidgetP_cachecontext * context, const QOpenGLWidget * widget); }; #endif // QUARTER_QUARTERWIDGETP_H diff --git a/src/Gui/Quarter/SoQTQuarterAdaptor.cpp b/src/Gui/Quarter/SoQTQuarterAdaptor.cpp index 72dddc75a3..aae4454ebd 100644 --- a/src/Gui/Quarter/SoQTQuarterAdaptor.cpp +++ b/src/Gui/Quarter/SoQTQuarterAdaptor.cpp @@ -34,11 +34,16 @@ #include #include -#if !defined(FC_OS_MACOSX) +# ifdef FC_OS_WIN32 +# include +# endif +# ifdef FC_OS_MACOSX +# include +# else # include -# include # include -#endif +# include +# endif #include "SoQTQuarterAdaptor.h" @@ -148,7 +153,7 @@ constexpr const int defaultSize = 100; // NOLINTBEGIN(readability-implicit-bool-conversion) SIM::Coin3D::Quarter::SoQTQuarterAdaptor::SoQTQuarterAdaptor(QWidget* parent, - const QtGLWidget* sharewidget, + const QOpenGLWidget* sharewidget, Qt::WindowFlags flags) : QuarterWidget(parent, sharewidget, flags) , matrixaction(SbViewportRegion(defaultSize, defaultSize)) @@ -156,9 +161,9 @@ SIM::Coin3D::Quarter::SoQTQuarterAdaptor::SoQTQuarterAdaptor(QWidget* parent, init(); } -SIM::Coin3D::Quarter::SoQTQuarterAdaptor::SoQTQuarterAdaptor(const QtGLFormat& format, +SIM::Coin3D::Quarter::SoQTQuarterAdaptor::SoQTQuarterAdaptor(const QSurfaceFormat& format, QWidget* parent, - const QtGLWidget* shareWidget, + const QOpenGLWidget* shareWidget, Qt::WindowFlags flags) : QuarterWidget(format, parent, shareWidget, flags) , matrixaction(SbViewportRegion(defaultSize, defaultSize)) @@ -166,9 +171,9 @@ SIM::Coin3D::Quarter::SoQTQuarterAdaptor::SoQTQuarterAdaptor(const QtGLFormat& f init(); } -SIM::Coin3D::Quarter::SoQTQuarterAdaptor::SoQTQuarterAdaptor(QtGLContext* context, +SIM::Coin3D::Quarter::SoQTQuarterAdaptor::SoQTQuarterAdaptor(QOpenGLContext* context, QWidget* parent, - const QtGLWidget* sharewidget, + const QOpenGLWidget* sharewidget, Qt::WindowFlags flags) : QuarterWidget(context, parent, sharewidget, flags) , matrixaction(SbViewportRegion(defaultSize, defaultSize)) @@ -638,7 +643,7 @@ void SIM::Coin3D::Quarter::SoQTQuarterAdaptor::draw2DString( const char* str, SbVec2s glsize, SbVec2f position, - App::Color color = App::Color(1.0F, 1.0F, 0.0F)) // retains yellow as default color + Base::Color color = Base::Color(1.0F, 1.0F, 0.0F)) // retains yellow as default color { // Store GL state. glPushAttrib(GL_ENABLE_BIT|GL_CURRENT_BIT); diff --git a/src/Gui/Quarter/SoQTQuarterAdaptor.h b/src/Gui/Quarter/SoQTQuarterAdaptor.h index 8cfe271cb9..f2ac4f6b65 100644 --- a/src/Gui/Quarter/SoQTQuarterAdaptor.h +++ b/src/Gui/Quarter/SoQTQuarterAdaptor.h @@ -27,10 +27,13 @@ #include #include -#include +#include #include "QuarterWidget.h" +class QOpenGLContext; +class QOpenGLWidget; +class QSurfaceFormat; class SbViewportRegion; class SoCamera; @@ -50,15 +53,15 @@ class QUARTER_DLL_API SoQTQuarterAdaptor : public QuarterWidget { public: explicit SoQTQuarterAdaptor(QWidget* parent = nullptr, - const QtGLWidget* sharewidget = nullptr, + const QOpenGLWidget* sharewidget = nullptr, Qt::WindowFlags flags = Qt::WindowFlags()); - explicit SoQTQuarterAdaptor(const QtGLFormat& format, + explicit SoQTQuarterAdaptor(const QSurfaceFormat& format, QWidget* parent = nullptr, - const QtGLWidget* shareWidget = nullptr, + const QOpenGLWidget* shareWidget = nullptr, Qt::WindowFlags flags = Qt::WindowFlags()); - explicit SoQTQuarterAdaptor(QtGLContext* context, + explicit SoQTQuarterAdaptor(QOpenGLContext* context, QWidget* parent = nullptr, - const QtGLWidget* sharewidget = nullptr, + const QOpenGLWidget* sharewidget = nullptr, Qt::WindowFlags flags = Qt::WindowFlags()); ~SoQTQuarterAdaptor() override; @@ -152,7 +155,7 @@ private: SoNode * m_storedcamera = nullptr; protected: - static void draw2DString(const char * str, SbVec2s glsize, SbVec2f position, App::Color color); + static void draw2DString(const char * str, SbVec2s glsize, SbVec2f position, Base::Color color); static void printString(const char * str); SbVec2f framesPerSecond; // NOLINT }; diff --git a/src/Gui/ReportView.cpp b/src/Gui/ReportView.cpp index 7a61bb5933..2e6f90d048 100644 --- a/src/Gui/ReportView.cpp +++ b/src/Gui/ReportView.cpp @@ -32,7 +32,7 @@ #endif #include -#include +#include #include "ReportView.h" #include "Application.h" @@ -566,7 +566,7 @@ void ReportOutput::changeEvent(QEvent *ev) if (ev->type() == QEvent::StyleChange) { QPalette pal = qApp->palette(); QColor color = pal.windowText().color(); - unsigned int text = App::Color::asPackedRGB(color); + unsigned int text = Base::Color::asPackedRGB(color); auto value = static_cast(text); // if this parameter is not already set use the style's window text color value = getWindowParameter()->GetUnsigned("colorText", value); @@ -831,7 +831,7 @@ void ReportOutput::OnChange(Base::Subject &rCaller, const char * sR } else if (strcmp(sReason, "colorText") == 0) { unsigned long col = rclGrp.GetUnsigned( sReason ); - reportHl->setTextColor(App::Color::fromPackedRGB(col)); + reportHl->setTextColor(Base::Color::fromPackedRGB(col)); } else if (strcmp(sReason, "colorCriticalText") == 0) { unsigned long col = rclGrp.GetUnsigned( sReason ); @@ -839,15 +839,15 @@ void ReportOutput::OnChange(Base::Subject &rCaller, const char * sR } else if (strcmp(sReason, "colorLogging") == 0) { unsigned long col = rclGrp.GetUnsigned( sReason ); - reportHl->setLogColor(App::Color::fromPackedRGB(col)); + reportHl->setLogColor(Base::Color::fromPackedRGB(col)); } else if (strcmp(sReason, "colorWarning") == 0) { unsigned long col = rclGrp.GetUnsigned( sReason ); - reportHl->setWarningColor(App::Color::fromPackedRGB(col)); + reportHl->setWarningColor(Base::Color::fromPackedRGB(col)); } else if (strcmp(sReason, "colorError") == 0) { unsigned long col = rclGrp.GetUnsigned( sReason ); - reportHl->setErrorColor(App::Color::fromPackedRGB(col)); + reportHl->setErrorColor(Base::Color::fromPackedRGB(col)); } else if (strcmp(sReason, "checkGoToEnd") == 0) { gotoEnd = rclGrp.GetBool(sReason, gotoEnd); diff --git a/src/Gui/Selection/SelectionObserverPython.cpp b/src/Gui/Selection/SelectionObserverPython.cpp index 2d41f5c45a..a2434fa2f6 100644 --- a/src/Gui/Selection/SelectionObserverPython.cpp +++ b/src/Gui/Selection/SelectionObserverPython.cpp @@ -34,8 +34,6 @@ std::vector SelectionObserverPython::_instances; void SelectionObserverPythonHandler::init(PyObject* obj) { - this->inst = obj; - #undef FC_PY_ELEMENT #define FC_PY_ELEMENT(_name) FC_PY_GetCallable(obj,#_name,py_##_name); FC_PY_SEL_OBSERVER @@ -209,7 +207,7 @@ void SelectionObserverPythonHandler::removePreselection(const SelectionChanges& SelectionObserverPython::SelectionObserverPython(const Py::Object& obj, ResolveMode resolve) - : SelectionObserver(true, resolve) + : SelectionObserver(true, resolve), inst(obj) { this->init(obj.ptr()); } diff --git a/src/Gui/Selection/SelectionObserverPython.h b/src/Gui/Selection/SelectionObserverPython.h index 5eed3a217c..ea574464a1 100644 --- a/src/Gui/Selection/SelectionObserverPython.h +++ b/src/Gui/Selection/SelectionObserverPython.h @@ -52,8 +52,6 @@ protected: private: - PyObject* inst{nullptr}; - #define FC_PY_SEL_OBSERVER \ FC_PY_ELEMENT(onSelectionChanged) \ FC_PY_ELEMENT(addSelection) \ diff --git a/src/Gui/Selection/SoFCSelection.cpp b/src/Gui/Selection/SoFCSelection.cpp index b5dc26de5e..c85781a87b 100644 --- a/src/Gui/Selection/SoFCSelection.cpp +++ b/src/Gui/Selection/SoFCSelection.cpp @@ -884,7 +884,7 @@ SoFCSelection::redrawHighlighted(SoAction * action , SbBool doHighlight ) SoState *state = action->getState(); - QtGLWidget* window; + QOpenGLWidget* window; SoGLRenderAction *glAction; SoGLWidgetElement::get(state, window); SoGLRenderActionElement::get(state, glAction); diff --git a/src/Gui/Selection/SoFCSelectionContext.cpp b/src/Gui/Selection/SoFCSelectionContext.cpp index 63cf241841..8ab9a3886f 100644 --- a/src/Gui/Selection/SoFCSelectionContext.cpp +++ b/src/Gui/Selection/SoFCSelectionContext.cpp @@ -125,8 +125,8 @@ int SoFCSelectionContext::merge(int status, SoFCSelectionContextBasePtr &output, ///////////////////////////////////////////////////////////////////////////////////// bool SoFCSelectionContextEx::setColors( - const std::map &colors, const std::string &element) { - std::map tmp; + const std::map &colors, const std::string &element) { + std::map tmp; auto it = colors.find(""); if(it!=colors.end()) tmp[-1] = it->second; @@ -149,7 +149,7 @@ bool SoFCSelectionContextEx::setColors( return true; } -uint32_t SoFCSelectionContextEx::packColor(const App::Color &c, bool &hasTransparency) { +uint32_t SoFCSelectionContextEx::packColor(const Base::Color &c, bool &hasTransparency) { float trans = std::max(trans0,c.a); if(trans>0) hasTransparency = true; diff --git a/src/Gui/Selection/SoFCSelectionContext.h b/src/Gui/Selection/SoFCSelectionContext.h index 1b669ac2a0..3d92e00b1a 100644 --- a/src/Gui/Selection/SoFCSelectionContext.h +++ b/src/Gui/Selection/SoFCSelectionContext.h @@ -105,11 +105,11 @@ using SoFCSelectionContextExPtr = std::shared_ptr; struct GuiExport SoFCSelectionContextEx : SoFCSelectionContext { - std::map colors; + std::map colors; float trans0 = 0.0; - bool setColors(const std::map &colors, const std::string &element); - uint32_t packColor(const App::Color &c, bool &hasTransparency); + bool setColors(const std::map &colors, const std::string &element); + uint32_t packColor(const Base::Color &c, bool &hasTransparency); bool applyColor(int idx, std::vector &packedColors, bool &hasTransparency); bool isSingleColor(uint32_t &color, bool &hasTransparency); diff --git a/src/Gui/Selection/SoFCUnifiedSelection.cpp b/src/Gui/Selection/SoFCUnifiedSelection.cpp index 79460ba148..1bf440887a 100644 --- a/src/Gui/Selection/SoFCUnifiedSelection.cpp +++ b/src/Gui/Selection/SoFCUnifiedSelection.cpp @@ -70,6 +70,8 @@ # include #endif +#include + #include #include #include @@ -788,7 +790,7 @@ void SoFCUnifiedSelection::GLRenderBelowPath(SoGLRenderAction * action) // this is called when a selection gate forbade to select an object // and the user moved the mouse to an empty area this->preSelection = -1; - QtGLWidget* window; + QOpenGLWidget* window; SoState *state = action->getState(); SoGLWidgetElement::get(state, window); QWidget* parent = window ? window->parentWidget() : nullptr; diff --git a/src/Gui/Selection/SoFCUnifiedSelection.h b/src/Gui/Selection/SoFCUnifiedSelection.h index ec5c8c55c8..2f234b55ef 100644 --- a/src/Gui/Selection/SoFCUnifiedSelection.h +++ b/src/Gui/Selection/SoFCUnifiedSelection.h @@ -297,7 +297,7 @@ public: return overrideColor; } - void setColorOverride(App::Color c) { + void setColorOverride(Base::Color c) { overrideColor = true; colorOverride = SbColor(c.r,c.g,c.b); transOverride = c.a; @@ -425,13 +425,13 @@ public: _secondary = enable; } - const std::map &getColors() const { + const std::map &getColors() const { return _colors; } - void setColors(const std::map &colors) { + void setColors(const std::map &colors) { _colors = colors; } - void swapColors(std::map &colors) { + void swapColors(std::map &colors) { _colors.swap(colors); } @@ -447,7 +447,7 @@ private: Type _type; SbColor _color; const SoDetail* _det{nullptr}; - std::map _colors; + std::map _colors; bool _secondary; }; diff --git a/src/Gui/SoFCColorBar.cpp b/src/Gui/SoFCColorBar.cpp index 7ab1f6ebd3..4308baa992 100644 --- a/src/Gui/SoFCColorBar.cpp +++ b/src/Gui/SoFCColorBar.cpp @@ -291,7 +291,7 @@ void SoFCColorBar::customize(SoFCColorBarBase* child) } } -App::Color SoFCColorBar::getColor( float fVal ) const +Base::Color SoFCColorBar::getColor( float fVal ) const { return this->getActiveBar()->getColor( fVal ); } diff --git a/src/Gui/SoFCColorBar.h b/src/Gui/SoFCColorBar.h index c6b1fc5235..165ff9ff2d 100644 --- a/src/Gui/SoFCColorBar.h +++ b/src/Gui/SoFCColorBar.h @@ -76,7 +76,7 @@ public: * * This method must be implemented in subclasses. */ - App::Color getColor(float fVal) const override = 0; + Base::Color getColor(float fVal) const override = 0; /** * Returns always true if the color bar is in mode to show colors to arbitrary values of \a fVal, * otherwise true is returned if \a fVal is within the specified parameter range, if not false is @@ -191,7 +191,7 @@ public: /** * Returns the associated color to the value \a fVal of the currently active color bar. */ - App::Color getColor(float fVal) const override; + Base::Color getColor(float fVal) const override; /** * Sets whether values outside the range should be in gray, */ diff --git a/src/Gui/SoFCColorGradient.cpp b/src/Gui/SoFCColorGradient.cpp index 706d067a14..50c7a15190 100644 --- a/src/Gui/SoFCColorGradient.cpp +++ b/src/Gui/SoFCColorGradient.cpp @@ -105,7 +105,7 @@ const char* SoFCColorGradient::getColorBarName() const void SoFCColorGradient::applyFormat(const SoLabelTextFormat& fmt) { - auto textColor = App::Color(fmt.textColor); + auto textColor = Base::Color(fmt.textColor); for (int j = 0; j < labels->getNumChildren(); j++) { if (labels->getChild(j)->getTypeId() == SoBaseColor::getClassTypeId()) { @@ -131,7 +131,7 @@ void SoFCColorGradient::setMarkerLabel(const SoMFString& label) auto trans = new SoTransform; SoLabelTextFormat fmt = getFormat(); - auto textColor = App::Color(fmt.textColor); + auto textColor = Base::Color(fmt.textColor); auto textFont = new SoFont; auto color = new SoBaseColor; textFont->name.setValue("Helvetica,Arial,Times New Roman"); @@ -356,7 +356,7 @@ SoMaterial* SoFCColorGradient::createMaterial() const auto mat = new SoMaterial; mat->diffuseColor.setNum(2 * numColors); for (int k = 0; k < numColors; k++) { - App::Color col = model.colors[numColors - k - 1]; + Base::Color col = model.colors[numColors - k - 1]; mat->diffuseColor.set1Value(2 * k, col.r, col.g, col.b); mat->diffuseColor.set1Value(2 * k + 1, col.r, col.g, col.b); } diff --git a/src/Gui/SoFCColorGradient.h b/src/Gui/SoFCColorGradient.h index 4d5ffd3240..d6a87f3d7c 100644 --- a/src/Gui/SoFCColorGradient.h +++ b/src/Gui/SoFCColorGradient.h @@ -58,7 +58,7 @@ public: /** * Returns the associated color to the value \a fVal. */ - App::Color getColor (float fVal) const override { return _cColGrad.getColor(fVal); } + Base::Color getColor (float fVal) const override { return _cColGrad.getColor(fVal); } void setOutsideGrayed (bool bVal) override { _cColGrad.setOutsideGrayed(bVal); } /** * Returns always true if the gradient is in mode to show colors to arbitrary values of \a fVal, diff --git a/src/Gui/SoFCColorLegend.cpp b/src/Gui/SoFCColorLegend.cpp index a94b0062ec..03c04a257a 100644 --- a/src/Gui/SoFCColorLegend.cpp +++ b/src/Gui/SoFCColorLegend.cpp @@ -339,7 +339,7 @@ void SoFCColorLegend::setColorLegend(const App::ColorLegend& legend) auto mat = new SoMaterial; mat->diffuseColor.setNum(intFields); for (std::size_t k = 0; k < numFields; k++) { - App::Color col = legend.getColor(k); + Base::Color col = legend.getColor(k); mat->diffuseColor.set1Value(k, col.r, col.g, col.b); } diff --git a/src/Gui/SoFCColorLegend.h b/src/Gui/SoFCColorLegend.h index 8353829243..ef9aeace98 100644 --- a/src/Gui/SoFCColorLegend.h +++ b/src/Gui/SoFCColorLegend.h @@ -58,7 +58,7 @@ public: void setColorLegend (const App::ColorLegend& legend); unsigned short getColorIndex (float fVal) const { return _currentLegend.getColorIndex(fVal); } - App::Color getColor (float fVal) const override { return _currentLegend.getColor(fVal); } + Base::Color getColor (float fVal) const override { return _currentLegend.getColor(fVal); } void setOutsideGrayed (bool bVal) override { _currentLegend.setOutsideGrayed(bVal); } bool isVisible (float) const override { return false; } float getMinValue () const override { return _currentLegend.getMinValue(); } diff --git a/src/Gui/SoFCDB.cpp b/src/Gui/SoFCDB.cpp index da5bf7309c..54041e8a84 100644 --- a/src/Gui/SoFCDB.cpp +++ b/src/Gui/SoFCDB.cpp @@ -79,6 +79,8 @@ #include "propertyeditor/PropertyItem.h" #include "ArcEngine.h" +#include + using namespace Gui; using namespace Gui::Inventor; @@ -148,6 +150,7 @@ void Gui::SoFCDB::init() SoMouseWheelEvent ::initClass(); So3DAnnotation ::initClass(); SoDelayedAnnotationsElement ::initClass(); + SoFCPlacementIndicatorKit ::initClass(); PropertyItem ::init(); PropertySeparatorItem ::init(); diff --git a/src/Gui/SoFCInteractiveElement.cpp b/src/Gui/SoFCInteractiveElement.cpp index 497ddd62dc..1f347e6caa 100644 --- a/src/Gui/SoFCInteractiveElement.cpp +++ b/src/Gui/SoFCInteractiveElement.cpp @@ -86,14 +86,14 @@ void SoGLWidgetElement::init(SoState * state) SoGLWidgetElement::~SoGLWidgetElement() = default; -void SoGLWidgetElement::set(SoState * state, QtGLWidget * window) +void SoGLWidgetElement::set(SoState * state, QOpenGLWidget * window) { auto elem = static_cast (SoElement::getElement(state, classStackIndex)); elem->window = window; } -void SoGLWidgetElement::get(SoState * state, QtGLWidget *& window) +void SoGLWidgetElement::get(SoState * state, QOpenGLWidget *& window) { const auto that = static_cast (SoElement::getConstElement(state, classStackIndex)); diff --git a/src/Gui/SoFCInteractiveElement.h b/src/Gui/SoFCInteractiveElement.h index 41eb54ca37..4f540ee4c4 100644 --- a/src/Gui/SoFCInteractiveElement.h +++ b/src/Gui/SoFCInteractiveElement.h @@ -29,9 +29,9 @@ #include #include -#include #include +class QOpenGLWidget; namespace Gui { /** @@ -73,14 +73,14 @@ public: SbBool matches(const SoElement * element) const override; SoElement * copyMatchInfo() const override; - static void set(SoState * state, QtGLWidget * window); - static void get(SoState * state, QtGLWidget *& window); + static void set(SoState * state, QOpenGLWidget * window); + static void get(SoState * state, QOpenGLWidget *& window); protected: ~SoGLWidgetElement() override; protected: - QtGLWidget * window; + QOpenGLWidget * window; }; class GuiExport SoGLRenderActionElement : public SoElement { @@ -117,7 +117,7 @@ public: static void initClass(); SoGLWidgetNode(); - QtGLWidget * window{nullptr}; + QOpenGLWidget * window{nullptr}; void doAction(SoAction * action) override; void GLRender(SoGLRenderAction * action) override; diff --git a/src/Gui/SoFCOffscreenRenderer.cpp b/src/Gui/SoFCOffscreenRenderer.cpp index 46df0a5641..91164936d1 100644 --- a/src/Gui/SoFCOffscreenRenderer.cpp +++ b/src/Gui/SoFCOffscreenRenderer.cpp @@ -43,6 +43,8 @@ # include #endif +#include +#include #include #include @@ -563,9 +565,9 @@ SoQtOffscreenRenderer::makeFrameBuffer(int width, int height, int samples) viewport.setWindowSize(width, height); - QtGLFramebufferObjectFormat fmt; + QOpenGLFramebufferObjectFormat fmt; fmt.setSamples(samples); - fmt.setAttachment(QtGLFramebufferObject::Depth); + fmt.setAttachment(QOpenGLFramebufferObject::Depth); // With enabled alpha a transparent background is supported but // at the same time breaks semi-transparent models. A workaround // is to use a certain background color using GL_RGB as texture @@ -573,7 +575,7 @@ SoQtOffscreenRenderer::makeFrameBuffer(int width, int height, int samples) // replaces it with the color requested by the user. fmt.setInternalTextureFormat(this->texFormat); - framebuffer = new QtGLFramebufferObject(width, height, fmt); + framebuffer = new QOpenGLFramebufferObject(width, height, fmt); cache_context = SoGLCacheContextElement::getUniqueCacheContext(); // unique per pixel buffer object, just to be sure } diff --git a/src/Gui/SoFCOffscreenRenderer.h b/src/Gui/SoFCOffscreenRenderer.h index 5354dc1137..3134cb71ea 100644 --- a/src/Gui/SoFCOffscreenRenderer.h +++ b/src/Gui/SoFCOffscreenRenderer.h @@ -27,12 +27,21 @@ #include #include +#ifdef FC_OS_MACOSX +# include +#else +# ifdef FC_OS_WIN32 +# include +# endif // FC_OS_WIN32 +# include +#endif // FC_OS_MACOSX + #include #include -#include #include +class QOpenGLFramebufferObject; namespace Gui { @@ -136,7 +145,7 @@ private: SbBool renderFromBase(SoBase * base); void makeFrameBuffer(int width, int height, int samples); - QtGLFramebufferObject* framebuffer; + QOpenGLFramebufferObject* framebuffer; uint32_t cache_context; // our unique context id SbViewportRegion viewport; diff --git a/src/Gui/SoTextLabel.cpp b/src/Gui/SoTextLabel.cpp index 1a4a29c0aa..6e533bea98 100644 --- a/src/Gui/SoTextLabel.cpp +++ b/src/Gui/SoTextLabel.cpp @@ -58,8 +58,6 @@ #include #endif -#include - #include "SoTextLabel.h" #include "SoFCInteractiveElement.h" #include "Tools.h" @@ -307,7 +305,7 @@ SoStringLabel::SoStringLabel() */ void SoStringLabel::GLRender(SoGLRenderAction *action) { - QtGLWidget* window; + QOpenGLWidget* window; SoState * state = action->getState(); state->push(); SoLazyElement::setLightModel(state, SoLazyElement::BASE_COLOR); @@ -381,6 +379,7 @@ SoFrameLabel::SoFrameLabel() SO_NODE_ADD_FIELD(frame, (true)); SO_NODE_ADD_FIELD(border, (true)); SO_NODE_ADD_FIELD(backgroundUseBaseColor, (false)); + SO_NODE_ADD_FIELD(textUseBaseColor, (false)); //SO_NODE_ADD_FIELD(image, (SbVec2s(0,0), 0, NULL)); } @@ -508,6 +507,15 @@ void SoFrameLabel::GLRender(SoGLRenderAction *action) } } + if (textUseBaseColor.getValue()) { + SoState* state = action->getState(); + const SbColor& diffuse = SoLazyElement::getDiffuse(state, 0); + + if (diffuse != this->textColor.getValue()) { + this->textColor.setValue(diffuse); + } + } + inherited::GLRender(action); } diff --git a/src/Gui/SoTextLabel.h b/src/Gui/SoTextLabel.h index 56b9726711..d2dcf43b91 100644 --- a/src/Gui/SoTextLabel.h +++ b/src/Gui/SoTextLabel.h @@ -120,6 +120,7 @@ public: SoSFBool frame; SoSFBool border; SoSFBool backgroundUseBaseColor; + SoSFBool textUseBaseColor; //SoSFImage image; QPixmap iconPixmap; diff --git a/src/Gui/SplitView3DInventor.cpp b/src/Gui/SplitView3DInventor.cpp index 94e7ec4a72..027da10e26 100644 --- a/src/Gui/SplitView3DInventor.cpp +++ b/src/Gui/SplitView3DInventor.cpp @@ -24,6 +24,7 @@ #ifndef _PreComp_ # include +# include # include # include # include @@ -580,7 +581,7 @@ SplitView3DInventor::SplitView3DInventor(int views, Gui::Document* pcDocument, Q bool smoothing = false; bool glformat = false; int samples = View3DInventorViewer::getNumSamples(); - QtGLFormat f; + QSurfaceFormat f; if (samples > 1) { glformat = true; diff --git a/src/Gui/TaskElementColors.cpp b/src/Gui/TaskElementColors.cpp index 539ad997a8..0741bc25af 100644 --- a/src/Gui/TaskElementColors.cpp +++ b/src/Gui/TaskElementColors.cpp @@ -190,13 +190,13 @@ public: void apply() { - std::map info; + std::map info; int count = ui->elementList->count(); for (int i = 0; i < count; ++i) { auto item = ui->elementList->item(i); auto col = item->data(Qt::UserRole).value(); std::string sub = qPrintable(item->data(Qt::UserRole + 1).value()); - info.emplace(sub, App::Color::fromValue(col)); + info.emplace(sub, Base::Color::fromValue(col)); } if (!App::GetApplication().getActiveTransaction()) { App::GetApplication().setActiveTransaction("Set colors"); diff --git a/src/Gui/TextEdit.cpp b/src/Gui/TextEdit.cpp index 68ae0efd99..998b1dd5b6 100644 --- a/src/Gui/TextEdit.cpp +++ b/src/Gui/TextEdit.cpp @@ -36,7 +36,7 @@ #include "TextEdit.h" #include "SyntaxHighlighter.h" #include "Tools.h" -#include +#include using namespace Gui; @@ -375,7 +375,7 @@ void TextEditor::highlightCurrentLine() if (!isReadOnly() && isEnabledHighlightCurrentLine()) { QTextEdit::ExtraSelection selection; QColor lineColor = d->colormap[QLatin1String("Current line highlight")]; - unsigned int col = App::Color::asPackedRGB(lineColor); + unsigned int col = Base::Color::asPackedRGB(lineColor); ParameterGrp::handle hPrefGrp = getWindowParameter(); auto value = static_cast(col); value = hPrefGrp->GetUnsigned( "Current line highlight", value); @@ -457,7 +457,7 @@ void TextEditor::OnChange(Base::Subject &rCaller,const char* sReaso QMap::Iterator it = d->colormap.find(QString::fromLatin1(sReason)); if (it != d->colormap.end()) { QColor color = it.value(); - unsigned int col = App::Color::asPackedRGB(color); + unsigned int col = Base::Color::asPackedRGB(color); auto value = static_cast(col); value = hPrefGrp->GetUnsigned(sReason, value); col = static_cast(value); diff --git a/src/Gui/Tools/color_traits.h b/src/Gui/Tools/color_traits.h index 6c46801165..94fe6f1336 100644 --- a/src/Gui/Tools/color_traits.h +++ b/src/Gui/Tools/color_traits.h @@ -24,12 +24,12 @@ #ifndef GUI_COLORTRAITS_H #define GUI_COLORTRAITS_H -#include +#include #include #include #include -namespace App +namespace Base { // Specialization for SbColor template<> @@ -201,91 +201,6 @@ private: color_type ct; }; -// Specialization for Color -template<> -struct color_traits -{ - using color_type = App::Color; - color_traits() = default; - explicit color_traits(const color_type& ct) - : ct(ct) - {} - float redF() const - { - return ct.r; - } - float greenF() const - { - return ct.g; - } - float blueF() const - { - return ct.b; - } - float alphaF() const - { - return ct.a; - } - void setRedF(float red) - { - ct.r = red; - } - void setGreenF(float green) - { - ct.g = green; - } - void setBlueF(float blue) - { - ct.b = blue; - } - void setAlphaF(float alpha) - { - ct.a = alpha; - } - int red() const - { - return int(std::lround(ct.r * 255.0F)); - } - int green() const - { - return int(std::lround(ct.g * 255.0F)); - } - int blue() const - { - return int(std::lround(ct.b * 255.0F)); - } - int alpha() const - { - return int(std::lround(ct.a * 255.0F)); - } - void setRed(int red) - { - ct.r = static_cast(red) / 255.0F; - } - void setGreen(int green) - { - ct.g = static_cast(green) / 255.0F; - } - void setBlue(int blue) - { - ct.b = static_cast(blue) / 255.0F; - } - void setAlpha(int alpha) - { - ct.a = static_cast(alpha) / 255.0F; - } - static color_type makeColor(int red, int green, int blue, int alpha = 255) - { - return color_type{static_cast(red) / 255.0F, - static_cast(green) / 255.0F, - static_cast(blue) / 255.0F, - static_cast(alpha) / 255.0F}; - } - -private: - color_type ct; -}; - // Specialization for QColor template<> struct color_traits diff --git a/src/Gui/Tree.cpp b/src/Gui/Tree.cpp index a989561eec..d66c28e00b 100644 --- a/src/Gui/Tree.cpp +++ b/src/Gui/Tree.cpp @@ -49,7 +49,7 @@ #include #include -#include +#include #include #include #include @@ -112,7 +112,7 @@ static bool isSelectionCheckBoxesEnabled() { void TreeParams::onItemBackgroundChanged() { if (getItemBackground()) { - App::Color color; + Base::Color color; color.setPackedValue(getItemBackground()); QColor col; col.setRedF(color.r); @@ -3861,7 +3861,7 @@ void DocumentItem::slotInEdit(const Gui::ViewProviderDocumentObject& v) ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( "User parameter:BaseApp/Preferences/TreeView"); unsigned long col = hGrp->GetUnsigned("TreeEditColor", 563609599); - QColor color(App::Color::fromPackedRGB(col)); + QColor color(Base::Color::fromPackedRGB(col)); if (!getTree()->editingItem) { auto doc = Application::Instance->editDocument(); @@ -5304,7 +5304,7 @@ void DocumentObjectItem::setHighlight(bool set, Gui::HighlightMode high) { f.setOverline(overlined); unsigned long col = hGrp->GetUnsigned("TreeActiveColor", 1538528255); - color = App::Color::fromPackedRGB(col); + color = Base::Color::fromPackedRGB(col); } else { f.setBold(false); diff --git a/src/Gui/Utilities.h b/src/Gui/Utilities.h index 3cc2333eca..cdb4a86523 100644 --- a/src/Gui/Utilities.h +++ b/src/Gui/Utilities.h @@ -94,8 +94,8 @@ private: // Specialization for Color template <> -struct vec_traits { - using vec_type = App::Color; +struct vec_traits { + using vec_type = Base::Color; using float_type = float; explicit vec_traits(const vec_type& v) : v(v){} inline std::tuple get() const { diff --git a/src/Gui/View3DInventor.cpp b/src/Gui/View3DInventor.cpp index 87e9615046..3238001f63 100644 --- a/src/Gui/View3DInventor.cpp +++ b/src/Gui/View3DInventor.cpp @@ -93,7 +93,7 @@ void GLOverlayWidget::paintEvent(QPaintEvent*) TYPESYSTEM_SOURCE_ABSTRACT(Gui::View3DInventor,Gui::MDIView) View3DInventor::View3DInventor(Gui::Document* pcDocument, QWidget* parent, - const QtGLWidget* sharewidget, Qt::WindowFlags wflags) + const QOpenGLWidget* sharewidget, Qt::WindowFlags wflags) : MDIView(pcDocument, parent, wflags), _viewerPy(nullptr) { stack = new QStackedWidget(this); @@ -106,7 +106,7 @@ View3DInventor::View3DInventor(Gui::Document* pcDocument, QWidget* parent, bool smoothing = false; bool glformat = false; int samples = View3DInventorViewer::getNumSamples(); - QtGLFormat f; + QSurfaceFormat f; if (samples > 1) { glformat = true; diff --git a/src/Gui/View3DInventor.h b/src/Gui/View3DInventor.h index e02d49a54b..efa6416844 100644 --- a/src/Gui/View3DInventor.h +++ b/src/Gui/View3DInventor.h @@ -26,7 +26,6 @@ #include #include #include -#include #include @@ -35,6 +34,7 @@ #include "Base/Vector3D.h" class QPrinter; +class QOpenGLWidget; class QStackedWidget; namespace Gui { @@ -82,7 +82,7 @@ class GuiExport View3DInventor : public MDIView TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: - View3DInventor(Gui::Document* pcDocument, QWidget* parent, const QtGLWidget* sharewidget = nullptr, Qt::WindowFlags wflags=Qt::WindowFlags()); + View3DInventor(Gui::Document* pcDocument, QWidget* parent, const QOpenGLWidget* sharewidget = nullptr, Qt::WindowFlags wflags=Qt::WindowFlags()); ~View3DInventor() override; /// Message handler diff --git a/src/Gui/View3DInventorViewer.cpp b/src/Gui/View3DInventorViewer.cpp index 2f6c0e60ae..078d9380b4 100644 --- a/src/Gui/View3DInventorViewer.cpp +++ b/src/Gui/View3DInventorViewer.cpp @@ -81,6 +81,9 @@ # include # include # include +# include +# include +# include # include # include # include @@ -365,7 +368,7 @@ public: // ************************************************************************* -View3DInventorViewer::View3DInventorViewer(QWidget* parent, const QtGLWidget* sharewidget) +View3DInventorViewer::View3DInventorViewer(QWidget* parent, const QOpenGLWidget* sharewidget) : Quarter::SoQTQuarterAdaptor(parent, sharewidget) , SelectionObserver(false, ResolveMode::NoResolve) , editViewProvider(nullptr) @@ -385,7 +388,7 @@ View3DInventorViewer::View3DInventorViewer(QWidget* parent, const QtGLWidget* sh init(); } -View3DInventorViewer::View3DInventorViewer(const QtGLFormat& format, QWidget* parent, const QtGLWidget* sharewidget) +View3DInventorViewer::View3DInventorViewer(const QSurfaceFormat& format, QWidget* parent, const QOpenGLWidget* sharewidget) : Quarter::SoQTQuarterAdaptor(format, parent, sharewidget) , SelectionObserver(false, ResolveMode::NoResolve) , editViewProvider(nullptr) @@ -739,7 +742,7 @@ void View3DInventorViewer::createStandardCursors(double dpr) void View3DInventorViewer::aboutToDestroyGLContext() { if (naviCube) { - if (auto gl = qobject_cast(this->viewport())) { + if (auto gl = qobject_cast(this->viewport())) { gl->makeCurrent(); } delete naviCube; @@ -1257,7 +1260,7 @@ void View3DInventorViewer::setGLWidgetCB(void* userdata, SoAction* action) // Separator (set envvar COIN_GLERROR_DEBUGGING=1 and re-run to get more information) if (action->isOfType(SoGLRenderAction::getClassTypeId())) { auto gl = static_cast(userdata); - SoGLWidgetElement::set(action->getState(), qobject_cast(gl)); + SoGLWidgetElement::set(action->getState(), qobject_cast(gl)); } } @@ -1267,7 +1270,7 @@ void View3DInventorViewer::handleEventCB(void* userdata, SoEventCallback* n) SoGLRenderAction* glra = that->getSoRenderManager()->getGLRenderAction(); SoAction* action = n->getAction(); SoGLRenderActionElement::set(action->getState(), glra); - SoGLWidgetElement::set(action->getState(), qobject_cast(that->getGLWidget())); + SoGLWidgetElement::set(action->getState(), qobject_cast(that->getGLWidget())); } void View3DInventorViewer::setGradientBackground(View3DInventorViewer::Background grad) @@ -1467,7 +1470,7 @@ void View3DInventorViewer::showRotationCenter(bool show) .GetParameterGroupByPath("User parameter:BaseApp/Preferences/View") ->GetUnsigned("RotationCenterColor", 4278190131); // NOLINT - QColor color = App::Color::fromPackedRGBA(rotationCenterColor); + QColor color = Base::Color::fromPackedRGBA(rotationCenterColor); rotationCenterGroup = new SoSkipBoundingGroup(); @@ -2124,15 +2127,15 @@ void View3DInventorViewer::setRenderType(RenderType type) int width = size[0]; int height = size[1]; - auto gl = static_cast(this->viewport()); // NOLINT + auto gl = static_cast(this->viewport()); // NOLINT gl->makeCurrent(); QOpenGLFramebufferObjectFormat fboFormat; fboFormat.setSamples(getNumSamples()); - fboFormat.setAttachment(QtGLFramebufferObject::Depth); - auto fbo = new QtGLFramebufferObject(width, height, fboFormat); + fboFormat.setAttachment(QOpenGLFramebufferObject::Depth); + auto fbo = new QOpenGLFramebufferObject(width, height, fboFormat); if (fbo->format().samples() > 0) { renderToFramebuffer(fbo); - framebuffer = new QtGLFramebufferObject(fbo->size()); + framebuffer = new QOpenGLFramebufferObject(fbo->size()); // this is needed to be able to render the texture later QOpenGLFramebufferObject::blitFramebuffer(framebuffer, fbo); delete fbo; @@ -2158,7 +2161,7 @@ View3DInventorViewer::RenderType View3DInventorViewer::getRenderType() const QImage View3DInventorViewer::grabFramebuffer() { - auto gl = static_cast(this->viewport()); // NOLINT + auto gl = static_cast(this->viewport()); // NOLINT gl->makeCurrent(); QImage res; @@ -2200,18 +2203,18 @@ QImage View3DInventorViewer::grabFramebuffer() void View3DInventorViewer::imageFromFramebuffer(int width, int height, int samples, const QColor& bgcolor, QImage& img) { - auto gl = static_cast(this->viewport()); // NOLINT + auto gl = static_cast(this->viewport()); // NOLINT gl->makeCurrent(); - const QtGLContext* context = QtGLContext::currentContext(); + const QOpenGLContext* context = QOpenGLContext::currentContext(); if (!context) { Base::Console().Warning("imageFromFramebuffer failed because no context is active\n"); return; } - QtGLFramebufferObjectFormat fboFormat; + QOpenGLFramebufferObjectFormat fboFormat; fboFormat.setSamples(samples); - fboFormat.setAttachment(QtGLFramebufferObject::Depth); + fboFormat.setAttachment(QOpenGLFramebufferObject::Depth); // With enabled alpha a transparent background is supported but // at the same time breaks semi-transparent models. A workaround // is to use a certain background color using GL_RGB as texture @@ -2219,7 +2222,7 @@ void View3DInventorViewer::imageFromFramebuffer(int width, int height, int sampl // replaces it with the color requested by the user. fboFormat.setInternalTextureFormat(getInternalTextureFormat()); - QtGLFramebufferObject fbo(width, height, fboFormat); + QOpenGLFramebufferObject fbo(width, height, fboFormat); const QColor col = backgroundColor(); auto grad = getGradientBackground(); @@ -2268,9 +2271,9 @@ void View3DInventorViewer::imageFromFramebuffer(int width, int height, int sampl } } -void View3DInventorViewer::renderToFramebuffer(QtGLFramebufferObject* fbo) +void View3DInventorViewer::renderToFramebuffer(QOpenGLFramebufferObject* fbo) { - static_cast(this->viewport())->makeCurrent(); // NOLINT + static_cast(this->viewport())->makeCurrent(); // NOLINT fbo->bind(); int width = fbo->size().width(); int height = fbo->size().height(); @@ -2435,7 +2438,7 @@ void View3DInventorViewer::renderScene() SoGLRenderAction* glra = this->getSoRenderManager()->getGLRenderAction(); SoState* state = glra->getState(); SoDevicePixelRatioElement::set(state, devicePixelRatio()); - SoGLWidgetElement::set(state, qobject_cast(this->getGLWidget())); + SoGLWidgetElement::set(state, qobject_cast(this->getGLWidget())); SoGLRenderActionElement::set(state, glra); SoGLVBOActivatedElement::set(state, this->vboEnabled); drawSingleBackground(col); @@ -2515,7 +2518,7 @@ void View3DInventorViewer::renderScene() draw2DString(stream.str().c_str(), SbVec2s(10, 10), SbVec2f((overlayLeftWidgets.empty() ? 0.1f : 1.1f), 0.1f), - App::Color(static_cast(axisLetterColor))); // NOLINT + Base::Color(static_cast(axisLetterColor))); // NOLINT } if (naviCubeEnabled) { @@ -3810,11 +3813,11 @@ void View3DInventorViewer::updateColors() unsigned long colorLong; colorLong = Gui::ViewParams::instance()->getAxisXColor(); - m_xColor = App::Color(static_cast(colorLong)); + m_xColor = Base::Color(static_cast(colorLong)); colorLong = Gui::ViewParams::instance()->getAxisYColor(); - m_yColor = App::Color(static_cast(colorLong)); + m_yColor = Base::Color(static_cast(colorLong)); colorLong = Gui::ViewParams::instance()->getAxisZColor(); - m_zColor = App::Color(static_cast(colorLong)); + m_zColor = Base::Color(static_cast(colorLong)); naviCube->updateColors(); diff --git a/src/Gui/View3DInventorViewer.h b/src/Gui/View3DInventorViewer.h index 0c53407303..47fa52d4e3 100644 --- a/src/Gui/View3DInventorViewer.h +++ b/src/Gui/View3DInventorViewer.h @@ -34,9 +34,20 @@ #include #include +#include #include +#include #include +#ifdef FC_OS_MACOSX +# include +#else +# ifdef FC_OS_WIN32 +# include +# endif // FC_OS_WIN32 +# include +#endif // FC_OS_MACOSX + #include #include "Namespace.h" @@ -46,9 +57,9 @@ #include "View3DInventorSelection.h" #include "Quarter/SoQTQuarterAdaptor.h" -#include -#include - +class QOpenGLFramebufferObject; +class QOpenGLWidget; +class QSurfaceFormat; class SoTranslation; class SoTransform; @@ -137,8 +148,8 @@ public: }; //@} - explicit View3DInventorViewer (QWidget *parent, const QtGLWidget* sharewidget = nullptr); - View3DInventorViewer (const QtGLFormat& format, QWidget *parent, const QtGLWidget* sharewidget = nullptr); + explicit View3DInventorViewer (QWidget *parent, const QOpenGLWidget* sharewidget = nullptr); + View3DInventorViewer (const QSurfaceFormat& format, QWidget *parent, const QOpenGLWidget* sharewidget = nullptr); ~View3DInventorViewer() override; void init(); @@ -183,7 +194,7 @@ public: static int getNumSamples(); void setRenderType(RenderType type); RenderType getRenderType() const; - void renderToFramebuffer(QtGLFramebufferObject*); + void renderToFramebuffer(QOpenGLFramebufferObject*); QImage grabFramebuffer(); void imageFromFramebuffer(int width, int height, int samples, const QColor& bgcolor, QImage& img); @@ -530,7 +541,7 @@ private: SoClipPlane *pcClipPlane; RenderType renderType; - QtGLFramebufferObject* framebuffer; + QOpenGLFramebufferObject* framebuffer; QImage glImage; bool shading; SoSwitch *dimensionRoot; @@ -549,9 +560,9 @@ private: bool vboEnabled; bool naviCubeEnabled; - App::Color m_xColor; - App::Color m_yColor; - App::Color m_zColor; + Base::Color m_xColor; + Base::Color m_yColor; + Base::Color m_zColor; bool editing; QCursor editCursor, zoomCursor, panCursor, spinCursor; diff --git a/src/Gui/View3DSettings.cpp b/src/Gui/View3DSettings.cpp index 287b4d6d77..1163436c53 100644 --- a/src/Gui/View3DSettings.cpp +++ b/src/Gui/View3DSettings.cpp @@ -30,7 +30,7 @@ #endif #include -#include +#include #include "NaviCube.h" #include "Navigation/NavigationStyle.h" @@ -599,19 +599,19 @@ void NaviCubeSettings::parameterChanged(const char* Name) } else if (strcmp(Name, "BaseColor") == 0) { unsigned long col = hGrp->GetUnsigned("BaseColor", 3806916544); - nc->setBaseColor(App::Color::fromPackedRGBA(col)); + nc->setBaseColor(Base::Color::fromPackedRGBA(col)); // update default contrast colors parameterChanged("EmphaseColor"); } else if (strcmp(Name, "EmphaseColor") == 0) { - App::Color bc((uint32_t)hGrp->GetUnsigned("BaseColor", 3806916544)); + Base::Color bc((uint32_t)hGrp->GetUnsigned("BaseColor", 3806916544)); unsigned long d = bc.r + bc.g + bc.b >= 1.5f ? 255 : 4294967295; unsigned long col = hGrp->GetUnsigned("EmphaseColor", d); - nc->setEmphaseColor(App::Color::fromPackedRGBA(col)); + nc->setEmphaseColor(Base::Color::fromPackedRGBA(col)); } else if (strcmp(Name, "HiliteColor") == 0) { unsigned long col = hGrp->GetUnsigned("HiliteColor", 2867003391); - nc->setHiliteColor(App::Color::fromPackedRGBA(col)); + nc->setHiliteColor(Base::Color::fromPackedRGBA(col)); } else if (strcmp(Name, "BorderWidth") == 0) { nc->setBorderWidth(hGrp->GetFloat("BorderWidth", 1.1)); diff --git a/src/Gui/ViewProvider.h b/src/Gui/ViewProvider.h index 7b199119a2..fd1aeb3d06 100644 --- a/src/Gui/ViewProvider.h +++ b/src/Gui/ViewProvider.h @@ -58,8 +58,6 @@ class QObject; namespace Base { class Matrix4D; -} -namespace App { class Color; } @@ -421,11 +419,11 @@ public: /** @name Color management methods */ //@{ - virtual std::map getElementColors(const char *element=nullptr) const { + virtual std::map getElementColors(const char *element=nullptr) const { (void)element; return {}; } - virtual void setElementColors(const std::map &colors) { + virtual void setElementColors(const std::map &colors) { (void)colors; } static const std::string &hiddenMarker(); diff --git a/src/Gui/ViewProviderAnnotation.cpp b/src/Gui/ViewProviderAnnotation.cpp index 4b554ec600..c1cb67e3ce 100644 --- a/src/Gui/ViewProviderAnnotation.cpp +++ b/src/Gui/ViewProviderAnnotation.cpp @@ -116,7 +116,7 @@ ViewProviderAnnotation::~ViewProviderAnnotation() void ViewProviderAnnotation::onChanged(const App::Property* prop) { if (prop == &TextColor) { - const App::Color& c = TextColor.getValue(); + const Base::Color& c = TextColor.getValue(); pColor->rgb.setValue(c.r,c.g,c.b); } else if (prop == &Justification) { @@ -315,7 +315,7 @@ ViewProviderAnnotationLabel::~ViewProviderAnnotationLabel() void ViewProviderAnnotationLabel::onChanged(const App::Property* prop) { if (prop == &BackgroundColor) { - const App::Color& c = BackgroundColor.getValue(); + const Base::Color& c = BackgroundColor.getValue(); pColor->rgb.setValue(c.r,c.g,c.b); } if (prop == &TextColor || prop == &BackgroundColor || @@ -454,10 +454,10 @@ void ViewProviderAnnotationLabel::drawImage(const std::vector& s) QFontMetrics fm(font); int w = 0; int h = fm.height() * s.size(); - const App::Color& b = this->BackgroundColor.getValue(); + const Base::Color& b = this->BackgroundColor.getValue(); QColor brush; brush.setRgbF(b.r,b.g,b.b); - const App::Color& t = this->TextColor.getValue(); + const Base::Color& t = this->TextColor.getValue(); QColor front; front.setRgbF(t.r,t.g,t.b); diff --git a/src/Gui/ViewProviderBuilder.cpp b/src/Gui/ViewProviderBuilder.cpp index c6bb1097e3..ee8c4b6cdf 100644 --- a/src/Gui/ViewProviderBuilder.cpp +++ b/src/Gui/ViewProviderBuilder.cpp @@ -97,7 +97,7 @@ ViewProviderColorBuilder::~ViewProviderColorBuilder() = default; void ViewProviderColorBuilder::buildNodes(const App::Property* prop, std::vector& node) const { const auto color = static_cast(prop); - const std::vector& val = color->getValues(); + const std::vector& val = color->getValues(); unsigned long i=0; auto material = new SoMaterial(); diff --git a/src/Gui/ViewProviderDragger.cpp b/src/Gui/ViewProviderDragger.cpp index 70caa50b6b..00b653e709 100644 --- a/src/Gui/ViewProviderDragger.cpp +++ b/src/Gui/ViewProviderDragger.cpp @@ -43,6 +43,7 @@ #include "Control.h" #include "Document.h" #include "SoFCCSysDragger.h" +#include "Inventor/SoFCPlacementIndicatorKit.h" #include "SoFCUnifiedSelection.h" #include "TaskCSysDragger.h" #include "View3DInventorViewer.h" @@ -60,6 +61,14 @@ PROPERTY_SOURCE(Gui::ViewProviderDragger, Gui::ViewProviderDocumentObject) ViewProviderDragger::ViewProviderDragger() { ADD_PROPERTY_TYPE(TransformOrigin, ({}), nullptr, App::Prop_Hidden, nullptr); + ADD_PROPERTY_TYPE(ShowPlacement, + (false), + "Display Options", + App::Prop_None, + "If true, placement of object is additionally rendered."); + + pcPlacement = new SoSwitch; + pcPlacement->whichChild = SO_SWITCH_NONE; }; ViewProviderDragger::~ViewProviderDragger() = default; @@ -98,6 +107,9 @@ void ViewProviderDragger::onChanged(const App::Property* property) if (property == &TransformOrigin) { updateDraggerPosition(); } + else if (property == &ShowPlacement) { + pcPlacement->whichChild = ShowPlacement.getValue() ? SO_SWITCH_ALL : SO_SWITCH_NONE; + } ViewProviderDocumentObject::onChanged(property); } @@ -322,6 +334,16 @@ void ViewProviderDragger::setDraggerPlacement(const Base::Placement& placement) csysDragger->clearIncrementCounts(); } +void ViewProviderDragger::attach(App::DocumentObject* pcObject) +{ + ViewProviderDocumentObject::attach(pcObject); + + getAnnotation()->addChild(pcPlacement); + + auto* pcAxisCrossKit = new Gui::SoFCPlacementIndicatorKit(); + pcPlacement->addChild(pcAxisCrossKit); +} + void ViewProviderDragger::updateDraggerPosition() { if (!csysDragger) { diff --git a/src/Gui/ViewProviderDragger.h b/src/Gui/ViewProviderDragger.h index 21808413a7..a0635ef2c6 100644 --- a/src/Gui/ViewProviderDragger.h +++ b/src/Gui/ViewProviderDragger.h @@ -56,11 +56,17 @@ public: /// destructor. ~ViewProviderDragger() override; + /// Property controlling visibility of the placement indicator, useful for displaying origin + /// position of attached Document Object. + App::PropertyBool ShowPlacement; + /// Origin used when object is transformed. It temporarily changes the origin of object. /// Dragger is normally placed at the transform origin, unless explicitly overridden via /// ViewProviderDragger#setDraggerPlacement() method. App::PropertyPlacement TransformOrigin; + void attach(App::DocumentObject* pcObject) override; + /// Convenience method to obtain the transform origin Base::Placement getTransformOrigin() const { return TransformOrigin.getValue(); } /// Convenience method to set the transform origin @@ -114,6 +120,7 @@ protected: CoinPtr csysDragger = nullptr; ViewProvider *forwardedViewProvider = nullptr; + CoinPtr pcPlacement; private: static void dragStartCallback(void *data, SoDragger *d); static void dragFinishCallback(void *data, SoDragger *d); diff --git a/src/Gui/ViewProviderFeature.cpp b/src/Gui/ViewProviderFeature.cpp index dd8b705b8c..30e92bee2d 100644 --- a/src/Gui/ViewProviderFeature.cpp +++ b/src/Gui/ViewProviderFeature.cpp @@ -34,7 +34,7 @@ PROPERTY_SOURCE(Gui::ViewProviderFeature, Gui::ViewProviderDocumentObject) ViewProviderFeature::ViewProviderFeature() { - App::Color c; + Base::Color c; ADD_PROPERTY(ColourList,(c)); } diff --git a/src/Gui/ViewProviderLink.cpp b/src/Gui/ViewProviderLink.cpp index b4531a9fe5..9f20fc9314 100644 --- a/src/Gui/ViewProviderLink.cpp +++ b/src/Gui/ViewProviderLink.cpp @@ -1006,7 +1006,7 @@ void LinkView::setMaterial(int index, const App::Material *material) { pcLinkRoot->removeColorOverride(); return; } - App::Color c = material->diffuseColor; + Base::Color c = material->diffuseColor; c.setTransparency(material->transparency); pcLinkRoot->setColorOverride(c); for(int i=0;iremoveColorOverride(); return; } - App::Color c = material->diffuseColor; + Base::Color c = material->diffuseColor; c.setTransparency(material->transparency); info.pcRoot->setColorOverride(c); } @@ -2942,7 +2942,7 @@ PyObject *ViewProviderLink::getPyLinkView() { return linkView->getPyObject(); } -std::map ViewProviderLink::getElementColors(const char *subname) const { +std::map ViewProviderLink::getElementColors(const char *subname) const { bool isPrefix = true; if(!subname) subname = ""; @@ -2950,7 +2950,7 @@ std::map ViewProviderLink::getElementColors(const char auto len = strlen(subname); isPrefix = !len || subname[len-1]=='.'; } - std::map colors; + std::map colors; auto ext = getLinkExtension(); if(!ext || ! ext->getColoredElementsProperty()) return colors; @@ -2960,7 +2960,7 @@ std::map ViewProviderLink::getElementColors(const char std::string wildcard(subname); if(wildcard == "Face" || wildcard == "Face*" || wildcard.empty()) { if(wildcard.size()==4 || OverrideMaterial.getValue()) { - App::Color c = ShapeMaterial.getValue().diffuseColor; + Base::Color c = ShapeMaterial.getValue().diffuseColor; c.setTransparency(ShapeMaterial.getValue().transparency); colors["Face"] = c; if(wildcard.size()==4) @@ -3081,9 +3081,9 @@ std::map ViewProviderLink::getElementColors(const char bool found = true; if(colors.empty()) { found = false; - colors.emplace(subname,App::Color()); + colors.emplace(subname,Base::Color()); } - std::map ret; + std::map ret; for(const auto &v : colors) { const char *pos = nullptr; auto sobj = getObject()->resolve(v.first.c_str(),nullptr,nullptr,&pos); @@ -3107,18 +3107,18 @@ std::map ViewProviderLink::getElementColors(const char return ret; } -void ViewProviderLink::setElementColors(const std::map &colorMap) { +void ViewProviderLink::setElementColors(const std::map &colorMap) { auto ext = getLinkExtension(); if(!ext || ! ext->getColoredElementsProperty()) return; // For checking and collapsing array element color - std::map > subMap; + std::map > subMap; int element_count = ext->getElementCountValue(); std::vector subs; - std::vector colors; - App::Color faceColor; + std::vector colors; + Base::Color faceColor; bool hasFaceColor = false; for(const auto &v : colorMap) { if(!hasFaceColor && v.first == "Face") { @@ -3142,7 +3142,7 @@ void ViewProviderLink::setElementColors(const std::map } for(auto &v : subMap) { if(element_count == (int)v.second.size()) { - App::Color firstColor = v.second.begin()->second; + Base::Color firstColor = v.second.begin()->second; subs.push_back(v.first); colors.push_back(firstColor); for(auto it=v.second.begin();it!=v.second.end();) { @@ -3188,7 +3188,7 @@ void ViewProviderLink::applyColors() { // reset color and visibility first action.apply(linkView->getLinkRoot()); - std::map > colorMap; + std::map > colorMap; std::set hideList; auto colors = getElementColors(); colors.erase("Face"); diff --git a/src/Gui/ViewProviderLink.h b/src/Gui/ViewProviderLink.h index c84d31c504..ab8c184990 100644 --- a/src/Gui/ViewProviderLink.h +++ b/src/Gui/ViewProviderLink.h @@ -253,8 +253,8 @@ public: static void updateLinks(ViewProvider *vp); - std::map getElementColors(const char *subname=nullptr) const override; - void setElementColors(const std::map &colors) override; + std::map getElementColors(const char *subname=nullptr) const override; + void setElementColors(const std::map &colors) override; void setOverrideMode(const std::string &mode) override; diff --git a/src/Gui/ViewProviderPyImp.cpp b/src/Gui/ViewProviderPyImp.cpp index 30178bf008..e3a9f5f5a0 100644 --- a/src/Gui/ViewProviderPyImp.cpp +++ b/src/Gui/ViewProviderPyImp.cpp @@ -484,7 +484,7 @@ PyObject* ViewProviderPy::setElementColors(PyObject* args) if(!PyDict_Check(pyObj)) throw Py::TypeError("Expect a dict"); - std::map colors; + std::map colors; Py::Dict dict(pyObj); for(auto it=dict.begin();it!=dict.end();++it) { const auto &value = *it; diff --git a/src/Gui/Widgets.cpp b/src/Gui/Widgets.cpp index 3d326ee782..5163741e68 100644 --- a/src/Gui/Widgets.cpp +++ b/src/Gui/Widgets.cpp @@ -671,7 +671,7 @@ QColor ColorButton::color() const */ void ColorButton::setPackedColor(uint32_t c) { - App::Color color; + Base::Color color; color.setPackedValue(c); d->col.setRedF(color.r); d->col.setGreenF(color.g); @@ -686,7 +686,7 @@ void ColorButton::setPackedColor(uint32_t c) */ uint32_t ColorButton::packedColor() const { - App::Color color(d->col.redF(), d->col.greenF(), d->col.blueF(), d->col.alphaF()); + Base::Color color(d->col.redF(), d->col.greenF(), d->col.blueF(), d->col.alphaF()); return color.getPackedValue(); } @@ -1009,7 +1009,7 @@ void StatefulLabel::setState(QString state) if (unsignedEntry.first == entry->second.preferenceString) { // Convert the stored Uint into usable color data: unsigned int col = unsignedEntry.second; - QColor qcolor(App::Color::fromPackedRGB(col)); + QColor qcolor(Base::Color::fromPackedRGB(col)); this->setStyleSheet(QStringLiteral("Gui--StatefulLabel{ color : rgba(%1,%2,%3,%4) ;}").arg(qcolor.red()).arg(qcolor.green()).arg(qcolor.blue()).arg(qcolor.alpha())); _styleCache[state] = this->styleSheet(); return; diff --git a/src/Gui/propertyeditor/PropertyItem.cpp b/src/Gui/propertyeditor/PropertyItem.cpp index 9769db88a8..d4aa272aae 100644 --- a/src/Gui/propertyeditor/PropertyItem.cpp +++ b/src/Gui/propertyeditor/PropertyItem.cpp @@ -3442,7 +3442,7 @@ QVariant PropertyColorItem::value(const App::Property* prop) const { assert(prop && prop->isDerivedFrom()); - App::Color value = static_cast(prop)->getValue(); + Base::Color value = static_cast(prop)->getValue(); return QVariant(value.asValue()); } @@ -3766,13 +3766,13 @@ void PropertyMaterialItem::setValue(const QVariant& value) } auto mat = value.value(); - App::Color dc; + Base::Color dc; dc.setValue(mat.diffuseColor); - App::Color ac; + Base::Color ac; ac.setValue(mat.ambientColor); - App::Color sc; + Base::Color sc; sc.setValue(mat.specularColor); - App::Color ec; + Base::Color ec; ec.setValue(mat.emissiveColor); float s = mat.shininess; float t = mat.transparency; @@ -4273,13 +4273,13 @@ void PropertyMaterialListItem::setValue(const QVariant& value) str << "("; auto mat = list[0].value(); - App::Color dc; + Base::Color dc; dc.setValue(mat.diffuseColor); - App::Color ac; + Base::Color ac; ac.setValue(mat.ambientColor); - App::Color sc; + Base::Color sc; sc.setValue(mat.specularColor); - App::Color ec; + Base::Color ec; ec.setValue(mat.emissiveColor); float s = mat.shininess; float t = mat.transparency; diff --git a/src/Main/CMakeLists.txt b/src/Main/CMakeLists.txt index 0661e6f1b9..6be6868503 100644 --- a/src/Main/CMakeLists.txt +++ b/src/Main/CMakeLists.txt @@ -5,6 +5,7 @@ file(COPY icon.ico DESTINATION ${CMAKE_CURRENT_BINARY_DIR}) if(BUILD_GUI) include_directories( + SYSTEM ${Boost_INCLUDE_DIRS} ${COIN3D_INCLUDE_DIRS} ${ZLIB_INCLUDE_DIR} @@ -16,6 +17,7 @@ if(BUILD_GUI) ) else(BUILD_GUI) include_directories( + SYSTEM ${Boost_INCLUDE_DIRS} ${ZLIB_INCLUDE_DIR} ${QT_INCLUDE_DIR} diff --git a/src/Mod/AddonManager/Addon.py b/src/Mod/AddonManager/Addon.py index d028429689..8ec60ce48e 100644 --- a/src/Mod/AddonManager/Addon.py +++ b/src/Mod/AddonManager/Addon.py @@ -489,23 +489,17 @@ class Addon: if self.repo_type == Addon.Kind.WORKBENCH: return True - if self.repo_type == Addon.Kind.PACKAGE: - if self.metadata is None: - fci.Console.PrintLog( - f"Addon Manager internal error: lost metadata for package {self.name}\n" - ) - return False - content = self.metadata.content - if not content: - return False - return "workbench" in content - return False + return self.contains_packaged_content("workbench") def contains_macro(self) -> bool: """Determine if this package contains (or is) a macro""" if self.repo_type == Addon.Kind.MACRO: return True + return self.contains_packaged_content("macro") + + def contains_packaged_content(self, content_type: str): + """Determine if the package contains content_type""" if self.repo_type == Addon.Kind.PACKAGE: if self.metadata is None: fci.Console.PrintLog( @@ -513,21 +507,20 @@ class Addon: ) return False content = self.metadata.content - return "macro" in content + return content_type in content return False def contains_preference_pack(self) -> bool: """Determine if this package contains a preference pack""" + return self.contains_packaged_content("preferencepack") - if self.repo_type == Addon.Kind.PACKAGE: - if self.metadata is None: - fci.Console.PrintLog( - f"Addon Manager internal error: lost metadata for package {self.name}\n" - ) - return False - content = self.metadata.content - return "preferencepack" in content - return False + def contains_bundle(self) -> bool: + """Determine if this package contains a bundle""" + return self.contains_packaged_content("bundle") + + def contains_other(self) -> bool: + """Determine if this package contains an "other" content item""" + return self.contains_packaged_content("other") def get_best_icon_relative_path(self) -> str: """Get the path within the repo the addon's icon. Usually specified by diff --git a/src/Mod/AddonManager/AddonManagerTest/app/test_addon.py b/src/Mod/AddonManager/AddonManagerTest/app/test_addon.py index e3a20d33d4..3872364739 100644 --- a/src/Mod/AddonManager/AddonManagerTest/app/test_addon.py +++ b/src/Mod/AddonManager/AddonManagerTest/app/test_addon.py @@ -93,6 +93,8 @@ class TestAddon(unittest.TestCase): self.assertTrue(addon_with_workbench.contains_workbench()) self.assertFalse(addon_with_workbench.contains_macro()) self.assertFalse(addon_with_workbench.contains_preference_pack()) + self.assertFalse(addon_with_workbench.contains_bundle()) + self.assertFalse(addon_with_workbench.contains_other()) # Macros addon_with_macro = Addon( @@ -105,6 +107,8 @@ class TestAddon(unittest.TestCase): self.assertFalse(addon_with_macro.contains_workbench()) self.assertTrue(addon_with_macro.contains_macro()) self.assertFalse(addon_with_macro.contains_preference_pack()) + self.assertFalse(addon_with_workbench.contains_bundle()) + self.assertFalse(addon_with_workbench.contains_other()) # Preference Packs addon_with_prefpack = Addon( @@ -117,6 +121,8 @@ class TestAddon(unittest.TestCase): self.assertFalse(addon_with_prefpack.contains_workbench()) self.assertFalse(addon_with_prefpack.contains_macro()) self.assertTrue(addon_with_prefpack.contains_preference_pack()) + self.assertFalse(addon_with_workbench.contains_bundle()) + self.assertFalse(addon_with_workbench.contains_other()) # Combination addon_with_all = Addon( @@ -129,6 +135,8 @@ class TestAddon(unittest.TestCase): self.assertTrue(addon_with_all.contains_workbench()) self.assertTrue(addon_with_all.contains_macro()) self.assertTrue(addon_with_all.contains_preference_pack()) + self.assertTrue(addon_with_all.contains_bundle()) + self.assertTrue(addon_with_all.contains_other()) # Now do the simple, explicitly-set cases addon_wb = Addon( diff --git a/src/Mod/AddonManager/AddonManagerTest/app/test_metadata.py b/src/Mod/AddonManager/AddonManagerTest/app/test_metadata.py index b572327d79..9f6f53cecf 100644 --- a/src/Mod/AddonManager/AddonManagerTest/app/test_metadata.py +++ b/src/Mod/AddonManager/AddonManagerTest/app/test_metadata.py @@ -616,6 +616,22 @@ class TestMetadataReaderIntegration(unittest.TestCase): expected_packs.remove(wb.name) self.assertEqual(len(expected_packs), 0) + def test_bundle(self): + from addonmanager_metadata import MetadataReader + + filename = os.path.join(self.test_data_dir, "bundle_only.xml") + metadata = MetadataReader.from_file(filename) + self.assertIn("bundle", metadata.content) + self.assertEqual(len(metadata.content["bundle"]), 1) + + def test_other(self): + from addonmanager_metadata import MetadataReader + + filename = os.path.join(self.test_data_dir, "other_only.xml") + metadata = MetadataReader.from_file(filename) + self.assertIn("other", metadata.content) + self.assertEqual(len(metadata.content["other"]), 1) + def test_content_combination(self): from addonmanager_metadata import MetadataReader diff --git a/src/Mod/AddonManager/AddonManagerTest/data/bundle_only.xml b/src/Mod/AddonManager/AddonManagerTest/data/bundle_only.xml new file mode 100644 index 0000000000..0cac57f292 --- /dev/null +++ b/src/Mod/AddonManager/AddonManagerTest/data/bundle_only.xml @@ -0,0 +1,23 @@ + + + Test Bundle + A package.xml file for unit testing. + 1.0.0 + 2025-02-22 + FreeCAD Developer + LGPL-2.1 + https://github.com/chennes/FreeCAD-Package + https://github.com/chennes/FreeCAD-Package/blob/main/README.md + + + + A bunch of great addons you should install + TestAddon1 + TestAddon2 + TestAddon3 + TestAddon4 + TestAddon5 + + + + diff --git a/src/Mod/AddonManager/AddonManagerTest/data/combination.xml b/src/Mod/AddonManager/AddonManagerTest/data/combination.xml index 8f095046f5..bc72470a0e 100644 --- a/src/Mod/AddonManager/AddonManagerTest/data/combination.xml +++ b/src/Mod/AddonManager/AddonManagerTest/data/combination.xml @@ -23,6 +23,12 @@ MyFirstPack + + A bundle that bundles nothing + + + Mysterious Object + diff --git a/src/Mod/AddonManager/AddonManagerTest/data/other_only.xml b/src/Mod/AddonManager/AddonManagerTest/data/other_only.xml new file mode 100644 index 0000000000..e4401f334d --- /dev/null +++ b/src/Mod/AddonManager/AddonManagerTest/data/other_only.xml @@ -0,0 +1,18 @@ + + + Test Other + A package.xml file for unit testing. + 1.0.0 + 2025-02-22 + FreeCAD Developer + LGPL-2.1 + https://github.com/chennes/FreeCAD-Package + https://github.com/chennes/FreeCAD-Package/blob/main/README.md + + + + A thing that's not a workbench, macro, preference pack, or bundle + + + + diff --git a/src/Mod/AddonManager/AddonManagerTest/gui/test_update_all_gui.py b/src/Mod/AddonManager/AddonManagerTest/gui/test_update_all_gui.py index c45d382d20..8cea9f327b 100644 --- a/src/Mod/AddonManager/AddonManagerTest/gui/test_update_all_gui.py +++ b/src/Mod/AddonManager/AddonManagerTest/gui/test_update_all_gui.py @@ -1,7 +1,7 @@ # SPDX-License-Identifier: LGPL-2.1-or-later # *************************************************************************** # * * -# * Copyright (c) 2022 FreeCAD Project Association * +# * Copyright (c) 2022-2025 FreeCAD project association AISBL * # * * # * This file is part of FreeCAD. * # * * @@ -73,6 +73,8 @@ class MockAddon: self.display_name = name self.name = name self.macro = None + self.metadata = None + self.installed_metadata = None def status(self): return Addon.Status.UPDATE_AVAILABLE @@ -144,29 +146,29 @@ class TestUpdateAllGui(unittest.TestCase): def test_add_addon_to_table(self): mock_addon = MockAddon("MockAddon") self.test_object.dialog.tableWidget.clear() - self.test_object._add_addon_to_table(mock_addon) + self.test_object._add_addon_to_table(mock_addon, 1) self.assertEqual(self.test_object.dialog.tableWidget.rowCount(), 1) def test_update_addon_status(self): self.test_object._setup_dialog() self.test_object._update_addon_status(0, AddonStatus.WAITING) self.assertEqual( - self.test_object.dialog.tableWidget.item(0, 1).text(), + self.test_object.dialog.tableWidget.item(0, 2).text(), AddonStatus.WAITING.ui_string(), ) self.test_object._update_addon_status(0, AddonStatus.INSTALLING) self.assertEqual( - self.test_object.dialog.tableWidget.item(0, 1).text(), + self.test_object.dialog.tableWidget.item(0, 2).text(), AddonStatus.INSTALLING.ui_string(), ) self.test_object._update_addon_status(0, AddonStatus.SUCCEEDED) self.assertEqual( - self.test_object.dialog.tableWidget.item(0, 1).text(), + self.test_object.dialog.tableWidget.item(0, 2).text(), AddonStatus.SUCCEEDED.ui_string(), ) self.test_object._update_addon_status(0, AddonStatus.FAILED) self.assertEqual( - self.test_object.dialog.tableWidget.item(0, 1).text(), + self.test_object.dialog.tableWidget.item(0, 2).text(), AddonStatus.FAILED.ui_string(), ) @@ -175,19 +177,19 @@ class TestUpdateAllGui(unittest.TestCase): self.test_object._launch_active_installer = lambda: None self.test_object._process_next_update() self.assertEqual( - self.test_object.dialog.tableWidget.item(0, 1).text(), + self.test_object.dialog.tableWidget.item(0, 2).text(), AddonStatus.INSTALLING.ui_string(), ) self.test_object._process_next_update() self.assertEqual( - self.test_object.dialog.tableWidget.item(1, 1).text(), + self.test_object.dialog.tableWidget.item(1, 2).text(), AddonStatus.INSTALLING.ui_string(), ) self.test_object._process_next_update() self.assertEqual( - self.test_object.dialog.tableWidget.item(2, 1).text(), + self.test_object.dialog.tableWidget.item(2, 2).text(), AddonStatus.INSTALLING.ui_string(), ) @@ -208,7 +210,7 @@ class TestUpdateAllGui(unittest.TestCase): self.test_object._setup_dialog() self.test_object._update_succeeded(self.addons[0]) self.assertEqual( - self.test_object.dialog.tableWidget.item(0, 1).text(), + self.test_object.dialog.tableWidget.item(0, 2).text(), AddonStatus.SUCCEEDED.ui_string(), ) @@ -216,7 +218,7 @@ class TestUpdateAllGui(unittest.TestCase): self.test_object._setup_dialog() self.test_object._update_failed(self.addons[0]) self.assertEqual( - self.test_object.dialog.tableWidget.item(0, 1).text(), + self.test_object.dialog.tableWidget.item(0, 2).text(), AddonStatus.FAILED.ui_string(), ) diff --git a/src/Mod/AddonManager/CMakeLists.txt b/src/Mod/AddonManager/CMakeLists.txt index 58b15d132b..8efcf67a0e 100644 --- a/src/Mod/AddonManager/CMakeLists.txt +++ b/src/Mod/AddonManager/CMakeLists.txt @@ -118,6 +118,7 @@ SET(AddonManagerTestsGui_SRCS SET(AddonManagerTestsFiles_SRCS AddonManagerTest/data/__init__.py AddonManagerTest/data/addon_update_stats.json + AddonManagerTest/data/bundle_only.xml AddonManagerTest/data/combination.xml AddonManagerTest/data/corrupted_metadata.zip AddonManagerTest/data/depends_on_all_workbenches.xml @@ -131,6 +132,7 @@ SET(AddonManagerTestsFiles_SRCS AddonManagerTest/data/MacrosRecipesWikiPage.zip AddonManagerTest/data/metadata.zip AddonManagerTest/data/missing_macro_metadata.FCStd + AddonManagerTest/data/other_only.xml AddonManagerTest/data/prefpack_only.xml AddonManagerTest/data/test_addon_with_fcmacro.zip AddonManagerTest/data/test_github_style_repo.zip diff --git a/src/Mod/AddonManager/Widgets/addonmanager_widget_filter_selector.py b/src/Mod/AddonManager/Widgets/addonmanager_widget_filter_selector.py index 308335e3c9..bb07ee3a28 100644 --- a/src/Mod/AddonManager/Widgets/addonmanager_widget_filter_selector.py +++ b/src/Mod/AddonManager/Widgets/addonmanager_widget_filter_selector.py @@ -69,6 +69,8 @@ class ContentFilter(IntEnum): WORKBENCH = 1 MACRO = 2 PREFERENCE_PACK = 3 + BUNDLE = 4 + OTHER = 5 class Filter: @@ -116,6 +118,14 @@ class WidgetFilterSelector(QtWidgets.QComboBox): translate("AddonsInstaller", "Preference Pack"), (FilterType.PACKAGE_CONTENTS, ContentFilter.PREFERENCE_PACK), ) + self.addItem( + translate("AddonsInstaller", "Bundle"), + (FilterType.PACKAGE_CONTENTS, ContentFilter.BUNDLE), + ) + self.addItem( + translate("AddonsInstaller", "Other"), + (FilterType.PACKAGE_CONTENTS, ContentFilter.OTHER), + ) self.insertSeparator(self.count()) self.addItem(translate("AddonsInstaller", "Installation Status")) self.installation_status_index = self.count() - 1 diff --git a/src/Mod/AddonManager/addonmanager_devmode_add_content.py b/src/Mod/AddonManager/addonmanager_devmode_add_content.py index f990f643ec..2907fbc8d4 100644 --- a/src/Mod/AddonManager/addonmanager_devmode_add_content.py +++ b/src/Mod/AddonManager/addonmanager_devmode_add_content.py @@ -71,6 +71,8 @@ class AddContent: self.dialog.addonKindComboBox.setItemData(0, "macro") self.dialog.addonKindComboBox.setItemData(1, "preferencepack") self.dialog.addonKindComboBox.setItemData(2, "workbench") + self.dialog.addonKindComboBox.setItemData(3, "bundle") + self.dialog.addonKindComboBox.setItemData(4, "other") self.people_table = PeopleTable() self.licenses_table = LicensesTable() @@ -148,6 +150,8 @@ class AddContent: self.dialog.macroFileLineEdit.setText(files[0]) elif addon_kind == "preferencepack": self.dialog.prefPackNameLineEdit.setText(self.metadata.Name) + elif addon_kind == "bundle" or addon_kind == "other": + pass else: raise RuntimeError("Invalid data found for selection") diff --git a/src/Mod/AddonManager/addonmanager_metadata.py b/src/Mod/AddonManager/addonmanager_metadata.py index debe1bac27..d72f2b92c1 100644 --- a/src/Mod/AddonManager/addonmanager_metadata.py +++ b/src/Mod/AddonManager/addonmanager_metadata.py @@ -367,7 +367,7 @@ class MetadataReader: def _parse_content(namespace: str, metadata: Metadata, root: ET.Element): """Given a content node, loop over its children, and if they are a recognized element type, recurse into each one to parse it.""" - known_content_types = ["workbench", "macro", "preferencepack"] + known_content_types = ["workbench", "macro", "preferencepack", "bundle", "other"] for child in root: content_type = child.tag[len(namespace) :] if content_type in known_content_types: diff --git a/src/Mod/AddonManager/addonmanager_update_all_gui.py b/src/Mod/AddonManager/addonmanager_update_all_gui.py index 9cfafbd0bf..89fd775ea7 100644 --- a/src/Mod/AddonManager/addonmanager_update_all_gui.py +++ b/src/Mod/AddonManager/addonmanager_update_all_gui.py @@ -1,7 +1,7 @@ # SPDX-License-Identifier: LGPL-2.1-or-later # *************************************************************************** # * * -# * Copyright (c) 2022 FreeCAD Project Association * +# * Copyright (c) 2022-2025 FreeCAD project association AISBL * # * * # * This file is part of FreeCAD. * # * * @@ -85,6 +85,8 @@ class UpdateAllGUI(QtCore.QObject): finished = QtCore.Signal() addon_updated = QtCore.Signal(object) + index_role = QtCore.Qt.UserRole + 1 + def __init__(self, addons: List[Addon]): super().__init__() self.addons = addons @@ -114,28 +116,58 @@ class UpdateAllGUI(QtCore.QObject): self.dialog.tableWidget.clear() self.in_process_row = None self.row_map = {} + self._setup_empty_table() + counter = 0 for addon in self.addons: if addon.status() == Addon.Status.UPDATE_AVAILABLE: - self._add_addon_to_table(addon) + self._add_addon_to_table(addon, counter) self.addons_with_update.append(addon) + counter += 1 def _cancel_installation(self): self.cancelled = True if self.worker_thread and self.worker_thread.isRunning(): self.worker_thread.requestInterruption() - def _add_addon_to_table(self, addon: Addon): - """Add the given addon to the list, with no icon in the first column""" + def _setup_empty_table(self): + self.dialog.tableWidget.setColumnCount(4) + self.dialog.tableWidget.horizontalHeader().setSectionResizeMode( + 0, QtWidgets.QHeaderView.ResizeMode.ResizeToContents + ) + self.dialog.tableWidget.horizontalHeader().setSectionResizeMode( + 1, QtWidgets.QHeaderView.ResizeMode.ResizeToContents + ) + self.dialog.tableWidget.horizontalHeader().setSectionResizeMode( + 2, QtWidgets.QHeaderView.ResizeMode.ResizeToContents + ) + self.dialog.tableWidget.horizontalHeader().setSectionResizeMode( + 3, QtWidgets.QHeaderView.ResizeMode.Stretch + ) + + def _add_addon_to_table(self, addon: Addon, index: int): + """Add the given addon to the list, storing its index as user data in the first column""" new_row = self.dialog.tableWidget.rowCount() - self.dialog.tableWidget.setColumnCount(2) self.dialog.tableWidget.setRowCount(new_row + 1) - self.dialog.tableWidget.setItem(new_row, 0, QtWidgets.QTableWidgetItem(addon.display_name)) - self.dialog.tableWidget.setItem(new_row, 1, QtWidgets.QTableWidgetItem("")) + new_item = QtWidgets.QTableWidgetItem(addon.display_name) + new_item.setData(UpdateAllGUI.index_role, index) # Only first item in each row needs data() + self.dialog.tableWidget.setItem(new_row, 0, new_item) + if addon.installed_metadata and addon.installed_metadata.version: + self.dialog.tableWidget.setItem( + new_row, 1, QtWidgets.QTableWidgetItem(str(addon.installed_metadata.version)) + ) + self.dialog.tableWidget.setItem(new_row, 2, QtWidgets.QTableWidgetItem("")) + self.dialog.tableWidget.setItem(new_row, 3, QtWidgets.QTableWidgetItem("")) self.row_map[addon.name] = new_row def _update_addon_status(self, row: int, status: AddonStatus): """Update the GUI to reflect this addon's new status.""" - self.dialog.tableWidget.item(row, 1).setText(status.ui_string()) + self.dialog.tableWidget.item(row, 2).setText(status.ui_string()) + if status == AddonStatus.SUCCEEDED and self.addons[row].metadata: + self.dialog.tableWidget.item(row, 2).setText(status.ui_string() + " →") + index = self.dialog.tableWidget.item(row, 0).data(UpdateAllGUI.index_role) + addon = self.addons[index] + if addon.metadata and addon.metadata.version: + self.dialog.tableWidget.item(row, 3).setText(str(addon.metadata.version)) def _process_next_update(self): """Grab the next addon in the list and start its updater.""" diff --git a/src/Mod/AddonManager/package_list.py b/src/Mod/AddonManager/package_list.py index b4590b776f..e946e14f12 100644 --- a/src/Mod/AddonManager/package_list.py +++ b/src/Mod/AddonManager/package_list.py @@ -569,7 +569,7 @@ class PackageListFilter(QtCore.QSortFilterProxyModel): def setPackageFilter( self, package_type: int - ) -> None: # 0=All, 1=Workbenches, 2=Macros, 3=Preference Packs + ) -> None: # 0=All, 1=Workbenches, 2=Macros, 3=Preference Packs, 4=Bundles, 5=Other """Set the package filter to package_type and refreshes.""" self.package_type = package_type self.invalidateFilter() @@ -634,6 +634,12 @@ class PackageListFilter(QtCore.QSortFilterProxyModel): elif self.package_type == 3: if not data.contains_preference_pack(): return False + elif self.package_type == 4: + if not data.contains_bundle(): + return False + elif self.package_type == 5: + if not data.contains_other(): + return False if self.status == StatusFilter.INSTALLED: if data.status() == Addon.Status.NOT_INSTALLED: diff --git a/src/Mod/AddonManager/update_all.ui b/src/Mod/AddonManager/update_all.ui index 94d2a19c81..266b779f9a 100644 --- a/src/Mod/AddonManager/update_all.ui +++ b/src/Mod/AddonManager/update_all.ui @@ -27,7 +27,7 @@ - QAbstractItemView::NoEditTriggers + QAbstractItemView::EditTrigger::NoEditTriggers false @@ -39,7 +39,10 @@ false - QAbstractItemView::NoSelection + QAbstractItemView::SelectionMode::NoSelection + + + QAbstractItemView::SelectionBehavior::SelectRows false @@ -58,10 +61,10 @@ - Qt::Horizontal + Qt::Orientation::Horizontal - QDialogButtonBox::Cancel + QDialogButtonBox::StandardButton::Cancel diff --git a/src/Mod/Assembly/App/CMakeLists.txt b/src/Mod/Assembly/App/CMakeLists.txt index 7cc8a1341f..34f6e7cf0a 100644 --- a/src/Mod/Assembly/App/CMakeLists.txt +++ b/src/Mod/Assembly/App/CMakeLists.txt @@ -4,6 +4,10 @@ include_directories( ${CMAKE_SOURCE_DIR}/src ${CMAKE_BINARY_DIR}/src ${CMAKE_CURRENT_BINARY_DIR} +) + +include_directories( + SYSTEM ${OCC_INCLUDE_DIR} ${PYCXX_INCLUDE_DIR} ${Python3_INCLUDE_DIRS} diff --git a/src/Mod/Assembly/Gui/CMakeLists.txt b/src/Mod/Assembly/Gui/CMakeLists.txt index 07b60c77cb..9d3ec1c17e 100644 --- a/src/Mod/Assembly/Gui/CMakeLists.txt +++ b/src/Mod/Assembly/Gui/CMakeLists.txt @@ -1,6 +1,10 @@ include_directories( ${CMAKE_BINARY_DIR} ${CMAKE_CURRENT_BINARY_DIR} +) + +include_directories( + SYSTEM ${COIN3D_INCLUDE_DIRS} ${OCC_INCLUDE_DIR} ${PYCXX_INCLUDE_DIR} diff --git a/src/Mod/BIM/ArchAxis.py b/src/Mod/BIM/ArchAxis.py index d110f749df..71cbaaa16c 100644 --- a/src/Mod/BIM/ArchAxis.py +++ b/src/Mod/BIM/ArchAxis.py @@ -344,14 +344,15 @@ class _ViewProviderAxis: pos = [] else: pos = [vobj.BubblePosition] - n = 0 - if hasattr(vobj.Object, "Distances"): - n = len(vobj.Object.Distances) - for i in range(n): + e = len(vobj.Object.Shape.Edges) + if getattr(vobj.Object,"Limit",0): + e //= 2 + n = len(getattr(vobj.Object,"Distances",[])) + for i in range(min(e,n)): for p in pos: - if hasattr(vobj.Object,"Limit") and vobj.Object.Limit.Value: - verts = [vobj.Object.Placement.inverse().multVec(vobj.Object.Shape.Edges[i].Vertexes[0].Point), - vobj.Object.Placement.inverse().multVec(vobj.Object.Shape.Edges[i+1].Vertexes[0].Point)] + if getattr(vobj.Object,"Limit",0): + verts = [vobj.Object.Placement.inverse().multVec(vobj.Object.Shape.Edges[i*2].Vertexes[0].Point), + vobj.Object.Placement.inverse().multVec(vobj.Object.Shape.Edges[i*2+1].Vertexes[0].Point)] else: verts = [vobj.Object.Placement.inverse().multVec(v.Point) for v in vobj.Object.Shape.Edges[i].Vertexes] arrow = None diff --git a/src/Mod/BIM/ArchComponent.py b/src/Mod/BIM/ArchComponent.py index 6a4927ef12..93a8d32d57 100644 --- a/src/Mod/BIM/ArchComponent.py +++ b/src/Mod/BIM/ArchComponent.py @@ -778,7 +778,7 @@ class Component(ArchIFC.IfcProduct): if (Draft.getType(o.getLinkedObject()) == "Window") or (Draft.isClone(o,"Window",True)): # windows can be additions or subtractions, treated the same way - subvolume = o.getLinkedObject().Proxy.getSubVolume(o) + subvolume = o.getLinkedObject().Proxy.getSubVolume(o,host=obj) # pass host obj (mostly Wall) elif (Draft.getType(o) == "Roof") or (Draft.isClone(o,"Roof")): # roofs define their own special subtraction volume subvolume = o.Proxy.getSubVolume(o) diff --git a/src/Mod/BIM/ArchWindow.py b/src/Mod/BIM/ArchWindow.py index 09321c48ea..93eea82a52 100644 --- a/src/Mod/BIM/ArchWindow.py +++ b/src/Mod/BIM/ArchWindow.py @@ -514,12 +514,25 @@ class _Window(ArchComponent.Component): # Execute features in the SketchArch External Add-on self.executeSketchArchFeatures(obj, linkObj) - def getSubVolume(self,obj,plac=None): + def getSubFace(self): + "returns a subface for creation of subvolume for cutting in a base object" + # creation of subface from HoleWire (getSubWire) + raise NotImplementedError + + def getSubVolume(self,obj,plac=None, host=None): "returns a subvolume for cutting in a base object" + # check if this is a clone or not, setup orig if positive + orig = None + if Draft.isClone(obj,"Window"): + if hasattr(obj,"CloneOf"): # TODO need to check this? + orig = obj.CloneOf + + # TODO Why always need tests e.g. hasattr(obj,"Subvolme"), hasattr(obj,"ClonOf") etc.? + # check if we have a custom subvolume - if hasattr(obj,"Subvolume"): + if hasattr(obj,"Subvolume"): # TODO To support Links if obj.Subvolume: if hasattr(obj.Subvolume,'Shape'): if not obj.Subvolume.Shape.isNull(): @@ -532,62 +545,62 @@ class _Window(ArchComponent.Component): return sh # getting extrusion depth - base = None - if obj.Base: - base = obj.Base width = 0 - if hasattr(obj,"HoleDepth"): # the code have not checked whether this is a clone and use the original's HoleDepth; if HoleDepth is set in this object, even it is a clone, the original's HoleDepth is overridden + if hasattr(obj,"HoleDepth"): # if this is a clone, the original's HoleDepth is overridden if HoleDepth is set in the clone # TODO To support Links if obj.HoleDepth.Value: width = obj.HoleDepth.Value if not width: - if base: - b = base.Shape.BoundBox - width = max(b.XLength,b.YLength,b.ZLength) - if not width: - if Draft.isClone(obj,"Window"): # check whether this is a clone and use the original's HoleDepth or Shape's Boundbox - if hasattr(obj,"CloneOf"): - orig = obj.CloneOf - else: - orig = obj.Objects[0] - if orig.Base: - base = orig.Base - - if hasattr(orig,"HoleDepth"): - if orig.HoleDepth.Value: - width = orig.HoleDepth.Value - if not width: - if base: - b = base.Shape.BoundBox - width = max(b.XLength,b.YLength,b.ZLength) + if orig and hasattr(orig,"HoleDepth"): + if orig.HoleDepth.Value: + width = orig.HoleDepth.Value if not width: + if host and Draft.getType(host) == "Wall": + # TODO More robust approach : With ArchSketch, on which wall segment an ArchObject is attached to is declared by user and saved. + # The extrusion of each wall segment could be done per segment, and punch hole in the exact wall segment before fusing them all. No need to care about each wall segment thickness. + # TODO Consider to turn below codes to getWidths/getSortedWidths() in ArchWall (below codes copied and modified from ArchWall) + propSetUuid = host.Proxy.ArchSkPropSetPickedUuid + widths = [] # [] or None are both False + if hasattr(host,"ArchSketchData") and host.ArchSketchData and Draft.getType(host.Base) == "ArchSketch": + if hasattr(host.Base, 'Proxy'): # TODO Any need to test ? + if hasattr(host.Base.Proxy, 'getWidths'): + # Return a list of Width corresponding to indexes + # of sorted edges of Sketch. + widths = host.Base.Proxy.getWidths(host.Base, + propSetUuid=propSetUuid) + if not widths: + if host.OverrideWidth: + # TODO No need to test as in ArchWall if host.Base is Sketch and sortSketchWidth(), just need the max value + widths = host.OverrideWidth + elif host.Width: + widths = [host.Width.Value] + if widths: + width = max(widths) + # +100mm to ensure subtract is through at the moment + width += 100 + elif obj.Base: # If host is not Wall + b = obj.Base.Shape.BoundBox + width = max(b.XLength,b.YLength,b.ZLength) # TODO Fix this, the width would be too much in many cases + if not width: # TODO Should not happen, it means there is no Base (Sketch or another FC object) in Clone either width = 1.1112 # some weird value to have little chance to overlap with an existing face - if not base: - if Draft.isClone(obj,"Window"): # if this object has not base, check whether this is a clone and use the original's base - if hasattr(obj,"CloneOf"): - orig = obj.CloneOf - else: - orig = obj.Objects[0] # not sure what is this exactly - if orig.Base: - base = orig.Base - else: - return None + # setup base + if orig: + base = orig.Base # always use original's base; clone's base should not be used to supersede original's base + else: + base = obj.Base # finding which wire to use to drill the hole - f = None - if hasattr(obj,"HoleWire"): # the code have not checked whether this is a clone and use the original's HoleWire; if HoleWire is set in this object, even it is a clone, the original's BoundBox/HoleWire is overridden + if hasattr(obj,"HoleWire"): # if this is a clone, the original's HoleWire is overridden if HoleWire is set in the clone # TODO To support Links if obj.HoleWire > 0: if obj.HoleWire <= len(base.Shape.Wires): f = base.Shape.Wires[obj.HoleWire-1] - if not f: - if Draft.isClone(obj,"Window"): - # check original HoleWire then + if orig and hasattr(orig,"HoleDepth"): + # check original's HoleWire if orig.HoleWire > 0: if orig.HoleWire <= len(base.Shape.Wires): f = base.Shape.Wires[obj.HoleWire-1] - if not f: # finding biggest wire in the base shape max_length = 0 diff --git a/src/Mod/BIM/bimcommands/BimShape2DView.py b/src/Mod/BIM/bimcommands/BimShape2DView.py index fecbee7e8c..3d69e95c34 100644 --- a/src/Mod/BIM/bimcommands/BimShape2DView.py +++ b/src/Mod/BIM/bimcommands/BimShape2DView.py @@ -43,6 +43,16 @@ class BIM_Shape2DView(gui_shape2dview.Shape2DView): return d def proceed(self): + """Proceed with the command if one object was selected.""" + self.proceed_BimShape2DView() # Common + if self.commitlist_BimShape2DView: + commitlist = self.commitlist_BimShape2DView + commitlist.append("FreeCAD.ActiveDocument.recompute()") + self.commit(translate("draft", "Create 2D view"), + self.commitlist_BimShape2DView) + self.finish() + + def proceed_BimShape2DView(self): # Common """Proceed with the command if one object was selected.""" # difference from Draft: it sets InPlace to False import DraftVecUtils @@ -59,6 +69,7 @@ class BIM_Shape2DView(gui_shape2dview.Shape2DView): if "Face" in e: faces.append(int(e[4:]) - 1) # print(objs, faces) + self.objs_BimShape2DView = objs commitlist = [] FreeCADGui.addModule("Draft") if len(objs) == 1 and faces: @@ -68,8 +79,10 @@ class BIM_Shape2DView(gui_shape2dview.Shape2DView): _cmd += DraftVecUtils.toString(vec) + ", " _cmd += "facenumbers=" + str(faces) _cmd += ")" - commitlist.append("sv = " + _cmd) - commitlist.append("sv.InPlace = False") + #commitlist.append("sv = " + _cmd) + #commitlist.append("sv.InPlace = False") + commitlist.append("sv0 = " + _cmd) + commitlist.append("sv0.InPlace = False") else: n = 0 for o in objs: @@ -82,10 +95,14 @@ class BIM_Shape2DView(gui_shape2dview.Shape2DView): commitlist.append("sv" + str(n) + ".InPlace = False") n += 1 if commitlist: - commitlist.append("FreeCAD.ActiveDocument.recompute()") - self.commit(translate("draft", "Create 2D view"), - commitlist) - self.finish() + #commitlist.append("FreeCAD.ActiveDocument.recompute()") + self.commitlist_BimShape2DView = commitlist + else: + self.commitlist_BimShape2DView = None + + # self.commit(translate("draft", "Create 2D view"), + # commitlist) + #self.finish() class BIM_Shape2DCut(BIM_Shape2DView): @@ -98,8 +115,26 @@ class BIM_Shape2DCut(BIM_Shape2DView): return d def proceed(self): - super().proceed() - FreeCADGui.doCommand("sv.ProjectionMode = \"Cutfaces\"") + #super().proceed() + #'sv' is not passed from BIM_Shape2DView() to BIM_Shape2DCut() + #FreeCADGui.doCommand("sv.ProjectionMode = \"Cutfaces\"") + + """Proceed with the command if one object was selected.""" + self.proceed_BimShape2DView() # Common + if self.commitlist_BimShape2DView: + commitlist = self.commitlist_BimShape2DView + + # BIM_Shape2DCut specific + #commitlist.append("sv.ProjectionMode = \"Cutfaces\"") + objs = self.objs_BimShape2DView + n = 0 + for o in objs: + commitlist.append("sv" + str(n) + ".ProjectionMode = \"Cutfaces\"") + n += 1 + commitlist.append("FreeCAD.ActiveDocument.recompute()") + self.commit(translate("draft", "Create 2D Cut"), + commitlist) + self.finish() FreeCADGui.addCommand("BIM_Shape2DView", BIM_Shape2DView()) diff --git a/src/Mod/BIM/nativeifc/ifc_classification.py b/src/Mod/BIM/nativeifc/ifc_classification.py index 0115ebe865..18de9a170f 100644 --- a/src/Mod/BIM/nativeifc/ifc_classification.py +++ b/src/Mod/BIM/nativeifc/ifc_classification.py @@ -21,7 +21,7 @@ # *************************************************************************** -from nativeifc import ifc_tools # lazy import +from . import ifc_tools # lazy import def edit_classification(obj): diff --git a/src/Mod/BIM/nativeifc/ifc_commands.py b/src/Mod/BIM/nativeifc/ifc_commands.py index 2fb24fcf30..25591cdc01 100644 --- a/src/Mod/BIM/nativeifc/ifc_commands.py +++ b/src/Mod/BIM/nativeifc/ifc_commands.py @@ -25,7 +25,7 @@ import FreeCAD import FreeCADGui -from nativeifc import ifc_openshell +from . import ifc_openshell translate = FreeCAD.Qt.translate QT_TRANSLATE_NOOP = FreeCAD.Qt.QT_TRANSLATE_NOOP @@ -34,7 +34,7 @@ QT_TRANSLATE_NOOP = FreeCAD.Qt.QT_TRANSLATE_NOOP def get_project(): """Gets the current project""" - from nativeifc import ifc_tools + from . import ifc_tools if FreeCADGui.Selection.getSelection(): return ifc_tools.get_project(FreeCADGui.Selection.getSelection()[0]) @@ -57,7 +57,7 @@ class IFC_Diff: } def Activated(self): - from nativeifc import ifc_diff + from . import ifc_diff proj = get_project() if proj: @@ -88,8 +88,8 @@ class IFC_Expand: no = obj.ViewObject.Proxy.expandChildren(obj) ns.extend(no) else: - from nativeifc import ifc_generator - from nativeifc import ifc_tools + from . import ifc_generator + from . import ifc_tools document = FreeCAD.ActiveDocument ifc_generator.delete_ghost(document) @@ -130,7 +130,7 @@ class IFC_ConvertDocument: translate("BIM", "The active document is already an IFC document") ) else: - from nativeifc import ifc_tools + from . import ifc_tools ifc_tools.convert_document(doc) @@ -154,7 +154,7 @@ class IFC_MakeProject: def Activated(self): from importers import exportIFC # lazy loading - from nativeifc import ifc_tools + from . import ifc_tools from PySide import QtCore, QtGui doc = FreeCAD.ActiveDocument @@ -196,7 +196,7 @@ class IFC_Save: return False def Activated(self): - from nativeifc import ifc_tools # lazy loading + from . import ifc_tools # lazy loading doc = FreeCAD.ActiveDocument if getattr(doc, "IfcFilePath", None): @@ -231,8 +231,8 @@ class IFC_SaveAs: return False def Activated(self): - from nativeifc import ifc_tools # lazy loading - from nativeifc import ifc_viewproviders + from . import ifc_tools # lazy loading + from . import ifc_viewproviders doc = FreeCAD.ActiveDocument if ifc_viewproviders.get_filepath(doc): diff --git a/src/Mod/BIM/nativeifc/ifc_diff.py b/src/Mod/BIM/nativeifc/ifc_diff.py index 2becf39d02..43cf4822be 100644 --- a/src/Mod/BIM/nativeifc/ifc_diff.py +++ b/src/Mod/BIM/nativeifc/ifc_diff.py @@ -26,7 +26,7 @@ import difflib import FreeCAD import FreeCADGui import ifcopenshell -from nativeifc import ifc_tools +from . import ifc_tools import Arch_rc translate = FreeCAD.Qt.translate diff --git a/src/Mod/BIM/nativeifc/ifc_export.py b/src/Mod/BIM/nativeifc/ifc_export.py index ba81c6d5fd..91001de2df 100644 --- a/src/Mod/BIM/nativeifc/ifc_export.py +++ b/src/Mod/BIM/nativeifc/ifc_export.py @@ -30,8 +30,8 @@ from importers import exportIFC from importers import exportIFCHelper from importers import importIFCHelper -from nativeifc import ifc_tools -from nativeifc import ifc_import +from . import ifc_tools +from . import ifc_import PARAMS = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/NativeIFC") diff --git a/src/Mod/BIM/nativeifc/ifc_generator.py b/src/Mod/BIM/nativeifc/ifc_generator.py index 15731ec650..4c01bf2501 100644 --- a/src/Mod/BIM/nativeifc/ifc_generator.py +++ b/src/Mod/BIM/nativeifc/ifc_generator.py @@ -25,20 +25,23 @@ The only entry point in this module is the generate_geometry() function which is used by the execute() method of ifc_objects""" -import time import re import FreeCAD from FreeCAD import Base import Part + import ifcopenshell -from ifcopenshell.util import element -from nativeifc import ifc_tools -from nativeifc import ifc_export +import ifcopenshell.util.element + import multiprocessing + import FreeCADGui + from pivy import coin from PySide import QtCore +from . import ifc_tools +from . import ifc_export def generate_geometry(obj, cached=False): """Sets the geometry of the given object from a corresponding IFC element. diff --git a/src/Mod/BIM/nativeifc/ifc_geometry.py b/src/Mod/BIM/nativeifc/ifc_geometry.py index 5257099c8c..1cdda68be9 100644 --- a/src/Mod/BIM/nativeifc/ifc_geometry.py +++ b/src/Mod/BIM/nativeifc/ifc_geometry.py @@ -22,11 +22,12 @@ """This module contains geometry editing and geometry properties-related tools""" - import FreeCAD + import ifcopenshell -from ifcopenshell.util import unit -from nativeifc import ifc_tools +import ifcopenshell.util.unit + +from . import ifc_tools def add_geom_properties(obj): diff --git a/src/Mod/BIM/nativeifc/ifc_import.py b/src/Mod/BIM/nativeifc/ifc_import.py index 007dfa3272..5a51801e28 100644 --- a/src/Mod/BIM/nativeifc/ifc_import.py +++ b/src/Mod/BIM/nativeifc/ifc_import.py @@ -20,20 +20,20 @@ # * * # *************************************************************************** -import importlib import os import time import FreeCAD -from nativeifc import ifc_tools -from nativeifc import ifc_psets -from nativeifc import ifc_materials -from nativeifc import ifc_layers -from nativeifc import ifc_status + +from . import ifc_tools +from . import ifc_psets +from . import ifc_materials +from . import ifc_layers +from . import ifc_status if FreeCAD.GuiUp: import FreeCADGui - import Arch_rc + import Arch_rc # needed to load the Arch icons, noqa: F401 PARAMS = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/NativeIFC") @@ -79,7 +79,7 @@ def insert( stime = time.time() try: document = FreeCAD.getDocument(docname) - except: + except NameError: document = FreeCAD.newDocument() if singledoc is None: singledoc = PARAMS.GetBool("SingleDoc", True) @@ -145,7 +145,6 @@ def get_options(strategy=None, shapemode=None, switchwb=None, silent=False): ask = PARAMS.GetBool("AskAgain", False) if ask and FreeCAD.GuiUp: import FreeCADGui - from PySide import QtGui dlg = FreeCADGui.PySideUic.loadUi(":/ui/dialogImport.ui") dlg.checkSwitchWB.hide() # TODO see what to do with this... @@ -188,7 +187,6 @@ def get_project_type(silent=False): return ptype if ask and FreeCAD.GuiUp: import FreeCADGui - from PySide import QtGui dlg = FreeCADGui.PySideUic.loadUi(":/ui/dialogCreateProject.ui") result = dlg.exec_() @@ -202,16 +200,15 @@ def get_project_type(silent=False): # convenience functions def toggle_lock_on(): - ifc_status.on_toggle_lock(True, noconvert=True, setchecked=True) -def toggle_lock_off(): +def toggle_lock_off(): ifc_status.on_toggle_lock(False, noconvert=True, setchecked=True) -def unset_modified(): +def unset_modified(): try: FreeCADGui.ActiveDocument.Modified = False - except: + except AttributeError: pass diff --git a/src/Mod/BIM/nativeifc/ifc_layers.py b/src/Mod/BIM/nativeifc/ifc_layers.py index 2ab4b5a82a..f4fa9ab0dc 100644 --- a/src/Mod/BIM/nativeifc/ifc_layers.py +++ b/src/Mod/BIM/nativeifc/ifc_layers.py @@ -23,11 +23,10 @@ """This NativeIFC module deals with layers""" -from nativeifc import ifc_tools import ifcopenshell -from ifcopenshell import util -from ifcopenshell.util import element +import ifcopenshell.util.element +from . import ifc_tools def load_layers(obj): """Loads all the layers of an IFC file""" diff --git a/src/Mod/BIM/nativeifc/ifc_materials.py b/src/Mod/BIM/nativeifc/ifc_materials.py index 2bffd72760..e925116a26 100644 --- a/src/Mod/BIM/nativeifc/ifc_materials.py +++ b/src/Mod/BIM/nativeifc/ifc_materials.py @@ -22,13 +22,12 @@ """This NativeIFC module deals with materials""" - import FreeCAD -from nativeifc import ifc_tools -import ifcopenshell -from ifcopenshell import util -from ifcopenshell.util import element +import ifcopenshell +import ifcopenshell.util.element + +from . import ifc_tools def create_material(element, parent, recursive=False): """Creates a material object in the given project or parent material""" diff --git a/src/Mod/BIM/nativeifc/ifc_objects.py b/src/Mod/BIM/nativeifc/ifc_objects.py index be202c7012..c3350dab3e 100644 --- a/src/Mod/BIM/nativeifc/ifc_objects.py +++ b/src/Mod/BIM/nativeifc/ifc_objects.py @@ -120,7 +120,7 @@ class ifc_object: def rebuild_classlist(self, obj, setprops=False): """rebuilds the list of Class enum property according to current class""" - from nativeifc import ifc_tools # lazy import + from . import ifc_tools # lazy import obj.Class = [obj.IfcClass] obj.Class = ifc_tools.get_ifc_classes(obj, obj.IfcClass) @@ -144,7 +144,7 @@ class ifc_object: return None def execute(self, obj): - from nativeifc import ifc_generator # lazy import + from . import ifc_generator # lazy import if obj.isDerivedFrom("Part::Feature"): cached = getattr(self, "cached", False) @@ -167,7 +167,7 @@ class ifc_object: def edit_attribute(self, obj, attribute, value=None): """Edits an attribute of an underlying IFC object""" - from nativeifc import ifc_tools # lazy import + from . import ifc_tools # lazy import if not value: value = obj.getPropertyByName(attribute) @@ -182,8 +182,8 @@ class ifc_object: def edit_annotation(self, obj, attribute, value=None): """Edits an attribute of an underlying IFC annotation""" - from nativeifc import ifc_tools # lazy import - from nativeifc import ifc_export + from . import ifc_tools # lazy import + from . import ifc_export if not value: if hasattr(obj, attribute): @@ -239,8 +239,8 @@ class ifc_object: def edit_geometry(self, obj, prop): """Edits a geometry property of an object""" - from nativeifc import ifc_geometry # lazy loading - from nativeifc import ifc_tools # lazy import + from . import ifc_geometry # lazy loading + from . import ifc_tools # lazy import result = ifc_geometry.set_geom_property(obj, prop) if result: @@ -249,7 +249,7 @@ class ifc_object: def edit_schema(self, obj, schema): """Changes the schema of an IFC document""" - from nativeifc import ifc_tools # lazy import + from . import ifc_tools # lazy import ifcfile = ifc_tools.get_ifcfile(obj) if not ifcfile: @@ -275,22 +275,22 @@ class ifc_object: def edit_placement(self, obj): """Syncs the internal IFC placement""" - from nativeifc import ifc_tools # lazy import + from . import ifc_tools # lazy import ifc_tools.set_placement(obj) def edit_pset(self, obj, prop): """Edits a Pset value""" - from nativeifc import ifc_psets # lazy import + from . import ifc_psets # lazy import ifc_psets.edit_pset(obj, prop) def edit_group(self, obj): """Edits the children list""" - from nativeifc import ifc_tools # lazy import - from nativeifc import ifc_layers + from . import ifc_tools # lazy import + from . import ifc_layers if obj.Class in [ "IfcPresentationLayerAssignment", @@ -321,7 +321,7 @@ class ifc_object: def edit_type(self, obj): """Edits the type of this object""" - from nativeifc import ifc_types # lazy import + from . import ifc_types # lazy import ifc_types.edit_type(obj) @@ -332,7 +332,7 @@ class ifc_object: def get_section_data(self, obj): """Returns two things: a list of objects and a cut plane""" - from nativeifc import ifc_tools # lazy import + from . import ifc_tools # lazy import import Part if not obj.IfcClass == "IfcAnnotation": @@ -375,7 +375,7 @@ class ifc_object: def edit_classification(self, obj): """Edits the classification of this object""" - from nativeifc import ifc_classification # lazy loading + from . import ifc_classification # lazy loading ifc_classification.edit_classification(obj) diff --git a/src/Mod/BIM/nativeifc/ifc_observer.py b/src/Mod/BIM/nativeifc/ifc_observer.py index 2aa933d905..f650c91101 100644 --- a/src/Mod/BIM/nativeifc/ifc_observer.py +++ b/src/Mod/BIM/nativeifc/ifc_observer.py @@ -23,7 +23,6 @@ """Document observer to act on documents containing NativeIFC objects""" -import os import FreeCAD params = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/NativeIFC") @@ -67,7 +66,7 @@ class ifc_observer: def slotDeletedObject(self, obj): """Deletes the corresponding object in the IFC document""" - from nativeifc import ifc_tools # lazy loading + from . import ifc_tools # lazy loading proj = ifc_tools.get_project(obj) if not proj: @@ -82,11 +81,10 @@ class ifc_observer: """Watch document IFC properties""" # only look at locked IFC documents - if not "IfcFilePath" in doc.PropertiesList: + if "IfcFilePath" not in doc.PropertiesList: return - from nativeifc import ifc_tools # lazy import - from nativeifc import ifc_status + from . import ifc_tools # lazy import if prop == "Schema": schema = doc.Schema @@ -126,13 +124,13 @@ class ifc_observer: def slotActivateDocument(self, doc): """Check if we need to lock""" - from nativeifc import ifc_status + from . import ifc_status ifc_status.on_activate() def slotRemoveDynamicProperty(self, obj, prop): - from nativeifc import ifc_psets + from . import ifc_psets ifc_psets.remove_property(obj, prop) # implementation methods @@ -164,8 +162,8 @@ class ifc_observer: if obj.Modified: projects.append(obj) if projects: - from nativeifc import ifc_tools # lazy loading - from nativeifc import ifc_viewproviders + from . import ifc_tools # lazy loading + from . import ifc_viewproviders ask = params.GetBool("AskBeforeSaving", True) if ask and FreeCAD.GuiUp: @@ -208,8 +206,8 @@ class ifc_observer: or "IfcType" in obj.PropertiesList \ or "CreateSpreadsheet" in obj.PropertiesList: FreeCAD.Console.PrintLog("Converting " + obj.Label + " to IFC\n") - from nativeifc import ifc_geometry # lazy loading - from nativeifc import ifc_tools # lazy loading + from . import ifc_geometry # lazy loading + from . import ifc_tools # lazy loading newobj = ifc_tools.aggregate(obj, doc) ifc_geometry.add_geom_properties(newobj) diff --git a/src/Mod/BIM/nativeifc/ifc_openshell.py b/src/Mod/BIM/nativeifc/ifc_openshell.py index c0553efb7d..f38b866ee4 100644 --- a/src/Mod/BIM/nativeifc/ifc_openshell.py +++ b/src/Mod/BIM/nativeifc/ifc_openshell.py @@ -26,6 +26,8 @@ import FreeCAD import FreeCADGui +from packaging.version import Version +from addonmanager_utilities import create_pip_call translate = FreeCAD.Qt.translate QT_TRANSLATE_NOOP = FreeCAD.Qt.QT_TRANSLATE_NOOP @@ -49,8 +51,7 @@ class IFC_UpdateIOS: avail = self.get_avail_version() if avail: if version: - comp = self.compare_versions(avail, version) - if comp > 0: + if Version(version) < Version(avail): self.show_dialog("update", avail) else: self.show_dialog("uptodate") @@ -92,6 +93,7 @@ class IFC_UpdateIOS: if mode in ["update", "install"]: result = self.install() if result: + FreeCAD.Console.PrintLog(f"{result.stdout}\n") text = translate("BIM", "IfcOpenShell update successfully installed.") buttons = QtGui.QMessageBox.Ok reply = QtGui.QMessageBox.information(None, title, text, buttons) @@ -104,7 +106,7 @@ class IFC_UpdateIOS: from PySide import QtCore, QtGui QtGui.QApplication.setOverrideCursor(QtCore.Qt.WaitCursor) vendor_path = utils.get_pip_target_directory() - args = ["install", "--disable-pip-version-check", "--target", vendor_path, "ifcopenshell"] + args = ["install", "--upgrade", "--disable-pip-version-check", "--target", vendor_path, "ifcopenshell"] result = self.run_pip(args) QtGui.QApplication.restoreOverrideCursor() return result @@ -115,14 +117,17 @@ class IFC_UpdateIOS: import addonmanager_utilities as utils import freecad.utils - cmd = [freecad.utils.get_python_exe(), "-m", "pip"] - cmd.extend(args) + from subprocess import CalledProcessError + + cmd = create_pip_call(args) result = None try: result = utils.run_interruptable_subprocess(cmd) - except: + except CalledProcessError as pe: + FreeCAD.Console.PrintError(pe.stderr) + except Exception as e: text = translate("BIM","Unable to run pip. Please ensure pip is installed on your system.") - FreeCAD.Console.PrintError(text + "\n") + FreeCAD.Console.PrintError(f"{text} {str(e)}\n") return result @@ -130,19 +135,19 @@ class IFC_UpdateIOS: """Retrieves the current ifcopenshell version""" import addonmanager_utilities as utils + from packaging.version import InvalidVersion + try: import ifcopenshell - version = ifcopenshell.version + version = ifcopenshell.version + try: + Version(version) + except InvalidVersion: + FreeCAD.Console.PrintWarning(f"Invalid IfcOpenShell version: {version}\n") + version = "" except: version = "" - if version.startswith("v"): - # this is a pip version - vendor_path = utils.get_pip_target_directory() - result = self.run_pip(["list", "--path", vendor_path]) - if result: - result = result.stdout.split() - if "ifcopenshell" in result: - version = result[result.index("ifcopenshell")+1] + return version @@ -159,31 +164,6 @@ class IFC_UpdateIOS: return None - def compare_versions(self, v1, v2): - """Compare two version strings in the form '0.7.0' or v0.7.0""" - - # code from https://www.geeksforgeeks.org/compare-two-version-numbers - - arr1 = v1.replace("v","").split(".") - arr2 = v2.replace("v","").split(".") - n = len(arr1) - m = len(arr2) - arr1 = [int(i) for i in arr1] - arr2 = [int(i) for i in arr2] - if n > m: - for i in range(m, n): - arr2.append(0) - elif m > n: - for i in range(n, m): - arr1.append(0) - for i in range(len(arr1)): - if arr1[i] > arr2[i]: - return 1 - elif arr2[i] > arr1[i]: - return -1 - return 0 - - FreeCADGui.addCommand("IFC_UpdateIOS", IFC_UpdateIOS()) diff --git a/src/Mod/BIM/nativeifc/ifc_performance_test.py b/src/Mod/BIM/nativeifc/ifc_performance_test.py index 0e0b6ec049..7fb7740cd1 100644 --- a/src/Mod/BIM/nativeifc/ifc_performance_test.py +++ b/src/Mod/BIM/nativeifc/ifc_performance_test.py @@ -24,7 +24,7 @@ import os import time import FreeCAD import unittest -from nativeifc import ifc_import +from . import ifc_import FILES = [ diff --git a/src/Mod/BIM/nativeifc/ifc_psets.py b/src/Mod/BIM/nativeifc/ifc_psets.py index 472a751e32..bc4d993690 100644 --- a/src/Mod/BIM/nativeifc/ifc_psets.py +++ b/src/Mod/BIM/nativeifc/ifc_psets.py @@ -25,8 +25,10 @@ import os import re + import FreeCAD -from nativeifc import ifc_tools + +from . import ifc_tools translate = FreeCAD.Qt.translate @@ -361,7 +363,7 @@ def read_properties_conversion(): def remove_property(obj, prop): """Removes a custom property""" - from nativeifc import ifc_tools + from . import ifc_tools ifcfile = ifc_tools.get_ifcfile(obj) if not ifcfile: return diff --git a/src/Mod/BIM/nativeifc/ifc_selftest.py b/src/Mod/BIM/nativeifc/ifc_selftest.py index bad6568d12..25300dd909 100644 --- a/src/Mod/BIM/nativeifc/ifc_selftest.py +++ b/src/Mod/BIM/nativeifc/ifc_selftest.py @@ -29,14 +29,14 @@ import FreeCAD import Draft import Arch import unittest -from nativeifc import ifc_import -from nativeifc import ifc_tools -from nativeifc import ifc_geometry -from nativeifc import ifc_materials -from nativeifc import ifc_layers -from nativeifc import ifc_psets -from nativeifc import ifc_objects -from nativeifc import ifc_generator +from . import ifc_import +from . import ifc_tools +from . import ifc_geometry +from . import ifc_materials +from . import ifc_layers +from . import ifc_psets +from . import ifc_objects +from . import ifc_generator import ifcopenshell from ifcopenshell.util import element import difflib @@ -301,7 +301,7 @@ class NativeIFCTest(unittest.TestCase): self.assertTrue(obj.Shape.Volume > 1500000, "ChangeGeometry failed") def test12_RemoveObject(self): - from nativeifc import ifc_observer + from . import ifc_observer ifc_observer.add_observer() FreeCAD.Console.PrintMessage("NativeIFC 12: Remove object...") clearObjects() diff --git a/src/Mod/BIM/nativeifc/ifc_status.py b/src/Mod/BIM/nativeifc/ifc_status.py index 14d36894e8..a75375b509 100644 --- a/src/Mod/BIM/nativeifc/ifc_status.py +++ b/src/Mod/BIM/nativeifc/ifc_status.py @@ -101,7 +101,7 @@ def on_add_property(): if not sel: return from PySide import QtCore, QtGui # lazy loading - from nativeifc import ifc_psets + from . import ifc_psets obj = sel[0] psets = list(set([obj.getGroupOfProperty(p) for p in obj.PropertiesList])) psets = [p for p in psets if p] @@ -180,7 +180,7 @@ def on_add_pset(): if not sel: return from PySide import QtCore, QtGui # lazy loading - from nativeifc import ifc_psets + from . import ifc_psets obj = sel[0] mw = FreeCADGui.getMainWindow() # read standard psets @@ -328,7 +328,7 @@ def set_button(checked=False, setchecked=False): def unlock_document(): """Unlocks the active document""" - from nativeifc import ifc_tools # lazy loading + from . import ifc_tools # lazy loading doc = FreeCAD.ActiveDocument if not doc: @@ -356,10 +356,10 @@ def unlock_document(): def lock_document(): """Locks the active document""" - from nativeifc import ifc_tools # lazy loading + from . import ifc_tools # lazy loading from importers import exportIFC - from nativeifc import ifc_geometry - from nativeifc import ifc_export + from . import ifc_geometry + from . import ifc_export from PySide import QtCore doc = FreeCAD.ActiveDocument diff --git a/src/Mod/BIM/nativeifc/ifc_tools.py b/src/Mod/BIM/nativeifc/ifc_tools.py index 27ac90e750..3330f6e007 100644 --- a/src/Mod/BIM/nativeifc/ifc_tools.py +++ b/src/Mod/BIM/nativeifc/ifc_tools.py @@ -33,14 +33,13 @@ translate = FreeCAD.Qt.translate try: import ifcopenshell - from ifcopenshell import geom - from ifcopenshell import api - from ifcopenshell import template - from ifcopenshell.util import element - from ifcopenshell.util import attribute - from ifcopenshell.util import schema - from ifcopenshell.util import placement - from ifcopenshell.util import unit + import ifcopenshell.api + import ifcopenshell.geom + import ifcopenshell.util.attribute + import ifcopenshell.util.element + import ifcopenshell.util.placement + import ifcopenshell.util.schema + import ifcopenshell.util.unit except ImportError as e: import FreeCAD FreeCAD.Console.PrintError( @@ -52,13 +51,13 @@ except ImportError as e: ) raise e -from nativeifc import ifc_objects -from nativeifc import ifc_viewproviders -from nativeifc import ifc_import -from nativeifc import ifc_layers -from nativeifc import ifc_status -from nativeifc import ifc_export -from nativeifc import ifc_psets +from . import ifc_objects +from . import ifc_viewproviders +from . import ifc_import +from . import ifc_layers +from . import ifc_status +from . import ifc_export +from . import ifc_psets from draftviewproviders import view_layer import ArchBuildingPart @@ -134,7 +133,7 @@ def convert_document(document, filename=None, shapemode=0, strategy=0, silent=Fa 3 = no children """ - if not "Proxy" in document.PropertiesList: + if "Proxy" not in document.PropertiesList: document.addProperty("App::PropertyPythonObject", "Proxy") document.setPropertyStatus("Proxy", "Transient") document.Proxy = ifc_objects.document_object() @@ -161,9 +160,9 @@ def setup_project(proj, filename, shapemode, silent): full = False d = "The path to the linked IFC file" - if not "IfcFilePath" in proj.PropertiesList: + if "IfcFilePath" not in proj.PropertiesList: proj.addProperty("App::PropertyFile", "IfcFilePath", "Base", d) - if not "Modified" in proj.PropertiesList: + if "Modified" not in proj.PropertiesList: proj.addProperty("App::PropertyBool", "Modified", "Base") proj.setPropertyStatus("Modified", "Hidden") if filename: @@ -181,7 +180,7 @@ def setup_project(proj, filename, shapemode, silent): # In IFC4, history is optional. What should we do here? proj.Proxy.ifcfile = ifcfile add_properties(proj, ifcfile, project, shapemode=shapemode) - if not "Schema" in proj.PropertiesList: + if "Schema" not in proj.PropertiesList: proj.addProperty("App::PropertyEnumeration", "Schema", "Base") # bug in FreeCAD - to avoid a crash, pre-populate the enum with one value proj.Schema = [ifcfile.wrapped_data.schema_name()] @@ -321,7 +320,7 @@ def create_children( def create_child(parent, element): subresult = [] # do not create if a child with same stepid already exists - if not element.id() in [ + if element.id() not in [ getattr(c, "StepId", 0) for c in get_parent_objects(parent) ]: doc = getattr(parent, "Document", parent) @@ -685,18 +684,12 @@ def add_properties( elif isinstance(value, ifcopenshell.entity_instance): if links: if attr not in obj.PropertiesList: - # value = create_object(value, obj.Document) obj.addProperty("App::PropertyLink", attr, "IFC") - # setattr(obj, attr, value) elif isinstance(value, (list, tuple)) and value: if isinstance(value[0], ifcopenshell.entity_instance): if links: if attr not in obj.PropertiesList: - # nvalue = [] - # for elt in value: - # nvalue.append(create_object(elt, obj.Document)) obj.addProperty("App::PropertyLinkList", attr, "IFC") - # setattr(obj, attr, nvalue) elif data_type == "enum": if attr not in obj.PropertiesList: obj.addProperty("App::PropertyEnumeration", attr, "IFC") @@ -1001,7 +994,6 @@ def set_colors(obj, colors): colors = [colors] # set the first color to opaque otherwise it spoils object transparency if len(colors) > 1: - #colors[0] = colors[0][:3] + (0.0,) # TEMP HACK: if multiple colors, set everything to opaque because it looks wrong colors = [color[:3] + (1.0,) for color in colors] sapp = [] @@ -1013,7 +1005,6 @@ def set_colors(obj, colors): sapp_mat.DiffuseColor = color[:3] + (1.0 - color[3],) sapp_mat.Transparency = 1.0 - color[3] if len(color) > 3 else 0.0 sapp.append(sapp_mat) - #print(vobj.Object.Label,[[m.DiffuseColor,m.Transparency] for m in sapp]) vobj.ShapeAppearance = sapp @@ -1252,7 +1243,6 @@ def aggregate(obj, parent, mode=None): if hasattr(child,"Host") and child.Host == obj: aggregate(child, newobj) elif hasattr(child,"Hosts") and obj in child.Hosts: - #op = create_product(child, newobj, ifcfile, ifcclass="IfcOpeningElement") aggregate(child, newobj) for child in getattr(obj, "Group", []): if newobj.IfcClass == "IfcGroup" and child in obj.Group: @@ -1519,7 +1509,6 @@ def get_elem_attribs(ifcentity): attr = ifcentity.attribute_name(anumber) except Exception: break - # print(attr) attribs.append(attr) # get attrib values @@ -1527,14 +1516,12 @@ def get_elem_attribs(ifcentity): try: value = getattr(ifcentity, attr) except Exception as e: - # print(e) value = "Error: {}".format(e) print( "DEBUG: The entity #{} has a problem on attribute {}: {}".format( ifcentity.id(), attr, e ) ) - # print(value) info_ifcentity[attr] = value return info_ifcentity @@ -1581,8 +1568,8 @@ def get_orphan_elements(ifcfile): ] # add control elements proj = ifcfile.by_type("IfcProject")[0] - for rel in proj.Declares: - for ctrl in getattr(rel,"RelatedDefinitions", []): + for rel in getattr(proj, "Declares", []): + for ctrl in getattr(rel, "RelatedDefinitions", []): if ctrl.is_a("IfcControl"): products.append(ctrl) groups = [] @@ -1617,8 +1604,6 @@ def get_group(project, name): doc = project group = add_object(doc, otype="group", oname=name) group.Label = name.strip("Ifc").strip("Group") - # if FreeCAD.GuiUp: - # group.ViewObject.ShowInTree = PARAMS.GetBool("ShowDataGroups", False) if hasattr(project.Proxy, "addObject"): project.Proxy.addObject(project, group) return group @@ -1662,7 +1647,7 @@ def remove_tree(objs): nobjs = objs for obj in objs: for child in obj.OutListRecursive: - if not child in nobjs: + if child not in nobjs: nobjs.append(child) deletelist = [] for obj in nobjs: @@ -1678,8 +1663,6 @@ def remove_tree(objs): def recompute(children): """Temporary function to recompute objects. Some objects don't get their shape correctly at creation""" - #import time - #stime = time.time() doc = None for c in children: if c: @@ -1687,5 +1670,3 @@ def recompute(children): doc = c.Document if doc: doc.recompute() - #endtime = "%02d:%02d" % (divmod(round(time.time() - stime, 1), 60)) - #print("DEBUG: Extra recomputing of",len(children),"objects took",endtime) diff --git a/src/Mod/BIM/nativeifc/ifc_tree.py b/src/Mod/BIM/nativeifc/ifc_tree.py index cbfa923c8b..334e3e1931 100644 --- a/src/Mod/BIM/nativeifc/ifc_tree.py +++ b/src/Mod/BIM/nativeifc/ifc_tree.py @@ -79,7 +79,7 @@ def show_geometry_tree(element): import Arch_rc import FreeCADGui # lazy import - from nativeifc import ifc_tools + from . import ifc_tools from PySide import QtGui, QtWidgets if isinstance(element, FreeCAD.DocumentObject): @@ -146,7 +146,7 @@ def show_properties(current, previous): """Displays object properties""" import FreeCADGui - from nativeifc import ifc_tools # lazy loading + from . import ifc_tools # lazy loading from PySide import QtCore, QtGui, QtWidgets ifcid = int(current.text(0).split("=", 1)[0].strip(" ").strip("#")) diff --git a/src/Mod/BIM/nativeifc/ifc_types.py b/src/Mod/BIM/nativeifc/ifc_types.py index 0a714fa6d5..295d3cc8dd 100644 --- a/src/Mod/BIM/nativeifc/ifc_types.py +++ b/src/Mod/BIM/nativeifc/ifc_types.py @@ -24,7 +24,7 @@ import FreeCAD -from nativeifc import ifc_tools +from . import ifc_tools translate = FreeCAD.Qt.translate diff --git a/src/Mod/BIM/nativeifc/ifc_viewproviders.py b/src/Mod/BIM/nativeifc/ifc_viewproviders.py index 3487c34460..13f0c6bd43 100644 --- a/src/Mod/BIM/nativeifc/ifc_viewproviders.py +++ b/src/Mod/BIM/nativeifc/ifc_viewproviders.py @@ -82,10 +82,10 @@ class ifc_vp_object: return [] def setupContextMenu(self, vobj, menu): - from nativeifc import ifc_tools # lazy import - from nativeifc import ifc_psets - from nativeifc import ifc_materials - from nativeifc import ifc_types + from . import ifc_tools # lazy import + from . import ifc_psets + from . import ifc_materials + from . import ifc_types from PySide import QtCore, QtGui # lazy import if FreeCADGui.activeWorkbench().name() != 'BIMWorkbench': @@ -164,7 +164,7 @@ class ifc_vp_object: def hasChildren(self, obj): """Returns True if this IFC object can be decomposed""" - from nativeifc import ifc_tools # lazy import + from . import ifc_tools # lazy import ifcfile = ifc_tools.get_ifcfile(obj) if ifcfile: @@ -174,7 +174,7 @@ class ifc_vp_object: def expandChildren(self, obj=None): """Creates children of this object""" - from nativeifc import ifc_tools # lazy import + from . import ifc_tools # lazy import from PySide import QtCore, QtGui if not obj: @@ -260,14 +260,14 @@ class ifc_vp_object: def addGeometryProperties(self): """Adds geometry properties to this object""" - from nativeifc import ifc_geometry # lazy loading + from . import ifc_geometry # lazy loading ifc_geometry.add_geom_properties(self.Object) def addMaterial(self): """Adds a material to this object""" - from nativeifc import ifc_materials # lazy loading + from . import ifc_materials # lazy loading ifc_materials.show_material(self.Object) self.Object.Document.recompute() @@ -275,8 +275,8 @@ class ifc_vp_object: def showTree(self): """Shows a dialog with a geometry tree for the object""" - from nativeifc import ifc_tools # lazy loading - from nativeifc import ifc_tree # lazy loading + from . import ifc_tools # lazy loading + from . import ifc_tree # lazy loading element = ifc_tools.get_ifc_element(self.Object) if element: @@ -285,7 +285,7 @@ class ifc_vp_object: def showProps(self): """Expands property sets""" - from nativeifc import ifc_psets # lazy loading + from . import ifc_psets # lazy loading ifc_psets.show_psets(self.Object) self.Object.Document.recompute() @@ -313,7 +313,7 @@ class ifc_vp_object: def dragObject(self, vobj, dragged_object): """Remove a child from the view provider by d&d""" - from nativeifc import ifc_tools # lazy import + from . import ifc_tools # lazy import parent = vobj.Object ifc_tools.deaggregate(dragged_object, parent) @@ -329,7 +329,7 @@ class ifc_vp_object: def onDrop(self, incoming_object): """Delayed action to be taken when dropping an object""" - from nativeifc import ifc_tools # lazy import + from . import ifc_tools # lazy import ifc_tools.aggregate(incoming_object, self.Object) if self.hasChildren(self.Object): self.expandChildren(self.Object) @@ -350,7 +350,7 @@ class ifc_vp_object: def createGroup(self): """Creates a group under this object""" - from nativeifc import ifc_tools # lazy import + from . import ifc_tools # lazy import group = self.Object.Document.addObject("App::DocumentObjectGroup", "Group") ifc_tools.aggregate(group, self.Object) @@ -364,13 +364,13 @@ class ifc_vp_object: def expandProperties(self, vobj): """Expands everything that needs to be expanded""" - from nativeifc import ifc_geometry # lazy import - from nativeifc import ifc_tools # lazy import - from nativeifc import ifc_psets # lazy import - from nativeifc import ifc_materials # lazy import - from nativeifc import ifc_layers # lazy import - from nativeifc import ifc_types # lazy import - from nativeifc import ifc_classification # lazy import + from . import ifc_geometry # lazy import + from . import ifc_tools # lazy import + from . import ifc_psets # lazy import + from . import ifc_materials # lazy import + from . import ifc_layers # lazy import + from . import ifc_types # lazy import + from . import ifc_classification # lazy import # generic data loading ifc_geometry.add_geom_properties(vobj.Object) @@ -399,7 +399,7 @@ class ifc_vp_object: if not hasattr(self, "Object"): return - from nativeifc import ifc_types + from . import ifc_types ifc_types.convert_to_type(self.Object) self.Object.Document.recompute() @@ -444,7 +444,7 @@ class ifc_vp_document(ifc_vp_object): def save(self): """Saves the associated IFC file""" - from nativeifc import ifc_tools # lazy import + from . import ifc_tools # lazy import ifc_tools.save(self.Object) self.Object.Document.recompute() @@ -452,7 +452,7 @@ class ifc_vp_document(ifc_vp_object): def saveas(self): """Saves the associated IFC file to another file""" - from nativeifc import ifc_tools # lazy import + from . import ifc_tools # lazy import sf = get_filepath(self.Object) if sf: @@ -503,7 +503,7 @@ class ifc_vp_document(ifc_vp_object): return False def diff(self): - from nativeifc import ifc_diff + from . import ifc_diff diff = ifc_diff.get_diff(self.Object) ifc_diff.show_diff(diff) @@ -600,8 +600,8 @@ class ifc_vp_material: return [] def setupContextMenu(self, vobj, menu): - from nativeifc import ifc_tools # lazy import - from nativeifc import ifc_psets + from . import ifc_tools # lazy import + from . import ifc_psets from PySide import QtCore, QtGui # lazy import if FreeCADGui.activeWorkbench().name() != 'BIMWorkbench': @@ -616,7 +616,7 @@ class ifc_vp_material: def showProps(self): """Expands property sets""" - from nativeifc import ifc_psets # lazy loading + from . import ifc_psets # lazy loading ifc_psets.show_psets(self.Object) self.Object.Document.recompute() @@ -659,7 +659,7 @@ def overlay(icon1, icon2): def get_filepath(project): """Saves the associated IFC file to another file""" - from nativeifc import ifc_tools # lazy import + from . import ifc_tools # lazy import from PySide import QtCore, QtGui # lazy import sf = QtGui.QFileDialog.getSaveFileName( diff --git a/src/Mod/CAM/App/CMakeLists.txt b/src/Mod/CAM/App/CMakeLists.txt index 97647fac0e..91ee10f7ea 100644 --- a/src/Mod/CAM/App/CMakeLists.txt +++ b/src/Mod/CAM/App/CMakeLists.txt @@ -7,6 +7,10 @@ include_directories( ${CMAKE_SOURCE_DIR}/src ${CMAKE_BINARY_DIR}/src ${CMAKE_CURRENT_BINARY_DIR} +) + +include_directories( + SYSTEM ${Boost_INCLUDE_DIRS} ${OCC_INCLUDE_DIR} ${EIGEN3_INCLUDE_DIR} diff --git a/src/Mod/CAM/Gui/CMakeLists.txt b/src/Mod/CAM/Gui/CMakeLists.txt index 32cb8b8f92..46a5eaafcd 100644 --- a/src/Mod/CAM/Gui/CMakeLists.txt +++ b/src/Mod/CAM/Gui/CMakeLists.txt @@ -2,6 +2,10 @@ include_directories( ${CMAKE_BINARY_DIR} ${CMAKE_SOURCE_DIR}/src ${CMAKE_CURRENT_BINARY_DIR} +) + +include_directories( + SYSTEM ${Boost_INCLUDE_DIRS} ${COIN3D_INCLUDE_DIRS} ${ZLIB_INCLUDE_DIR} diff --git a/src/Mod/CAM/Gui/ViewProviderPath.cpp b/src/Mod/CAM/Gui/ViewProviderPath.cpp index 87ab0829dd..25276bdacb 100644 --- a/src/Mod/CAM/Gui/ViewProviderPath.cpp +++ b/src/Mod/CAM/Gui/ViewProviderPath.cpp @@ -387,7 +387,7 @@ void ViewProviderPath::onChanged(const App::Property* prop) } else if (prop == &NormalColor) { if (!colorindex.empty() && coordStart >= 0 && coordStart < (int)colorindex.size()) { - const App::Color& c = NormalColor.getValue(); + const Base::Color& c = NormalColor.getValue(); ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( "User parameter:BaseApp/Preferences/Mod/CAM"); unsigned long rcol = @@ -429,7 +429,7 @@ void ViewProviderPath::onChanged(const App::Property* prop) } } else if (prop == &MarkerColor) { - const App::Color& c = MarkerColor.getValue(); + const Base::Color& c = MarkerColor.getValue(); pcMarkerColor->rgb.setValue(c.r, c.g, c.b); } else if (prop == &ShowNodes) { diff --git a/src/Mod/CAM/PathSimulator/App/CMakeLists.txt b/src/Mod/CAM/PathSimulator/App/CMakeLists.txt index 126a3ff219..1c01dff7fd 100644 --- a/src/Mod/CAM/PathSimulator/App/CMakeLists.txt +++ b/src/Mod/CAM/PathSimulator/App/CMakeLists.txt @@ -4,6 +4,10 @@ include_directories( ${CMAKE_SOURCE_DIR}/src ${CMAKE_BINARY_DIR}/src ${CMAKE_CURRENT_BINARY_DIR} +) + +include_directories( + SYSTEM ${Boost_INCLUDE_DIRS} ${OCC_INCLUDE_DIR} ${PYCXX_INCLUDE_DIR} diff --git a/src/Mod/CAM/PathSimulator/AppGL/CMakeLists.txt b/src/Mod/CAM/PathSimulator/AppGL/CMakeLists.txt index 121b3f8740..e1932e81a7 100644 --- a/src/Mod/CAM/PathSimulator/AppGL/CMakeLists.txt +++ b/src/Mod/CAM/PathSimulator/AppGL/CMakeLists.txt @@ -3,6 +3,10 @@ include_directories( ${CMAKE_SOURCE_DIR}/src ${CMAKE_BINARY_DIR}/src ${CMAKE_CURRENT_BINARY_DIR} +) + +include_directories( + SYSTEM ${Boost_INCLUDE_DIRS} ${COIN3D_INCLUDE_DIRS} ${ZLIB_INCLUDE_DIR} diff --git a/src/Mod/CAM/libarea/CMakeLists.txt b/src/Mod/CAM/libarea/CMakeLists.txt index ef7828b2d9..2dd9f3e0ec 100644 --- a/src/Mod/CAM/libarea/CMakeLists.txt +++ b/src/Mod/CAM/libarea/CMakeLists.txt @@ -9,9 +9,13 @@ if(MSVC) endif(MSVC) include_directories( + SYSTEM ${PYCXX_INCLUDE_DIR} ${Python3_INCLUDE_DIRS} ${OCC_INCLUDE_DIR} +) + +include_directories( ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_SOURCE_DIR}/src/Mod/Import/App/dxf ) @@ -39,7 +43,7 @@ if(NOT FREECAD_USE_PYBIND11) endif() if(Boost_FOUND) - include_directories(${Boost_INCLUDE_DIRS}) + include_directories(SYSTEM ${Boost_INCLUDE_DIRS}) MESSAGE(STATUS "found Boost: " ${Boost_LIB_VERSION}) MESSAGE(STATUS "boost-incude dirs are: " ${Boost_INCLUDE_DIRS}) MESSAGE(STATUS "boost-python lib is: " ${Boost_PYTHON_LIBRARY}) @@ -47,10 +51,10 @@ if(NOT FREECAD_USE_PYBIND11) MESSAGE(STATUS "Boost_LIBRARIES is: " ${Boost_LIBRARIES}) endif() else() - include_directories(${Boost_INCLUDE_DIRS}) + include_directories(SYSTEM ${Boost_INCLUDE_DIRS}) endif() else() - include_directories(${pybind11_INCLUDE_DIR}) + include_directories(SYSTEM ${pybind11_INCLUDE_DIR}) endif(NOT FREECAD_USE_PYBIND11) diff --git a/src/Mod/Cloud/App/CMakeLists.txt b/src/Mod/Cloud/App/CMakeLists.txt index f093f88fd1..bdb18ff345 100644 --- a/src/Mod/Cloud/App/CMakeLists.txt +++ b/src/Mod/Cloud/App/CMakeLists.txt @@ -3,6 +3,7 @@ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OPENSSL_CFLAGS}") endif() include_directories( + SYSTEM ${Boost_INCLUDE_DIRS} ${OCC_INCLUDE_DIR} ${PYCXX_INCLUDE_DIR} diff --git a/src/Mod/Cloud/Gui/CMakeLists.txt b/src/Mod/Cloud/Gui/CMakeLists.txt index c1495a4bed..c592cd523b 100644 --- a/src/Mod/Cloud/Gui/CMakeLists.txt +++ b/src/Mod/Cloud/Gui/CMakeLists.txt @@ -2,6 +2,10 @@ include_directories( ${CMAKE_SOURCE_DIR}/src ${CMAKE_CURRENT_BINARY_DIR} +) + +include_directories( + SYSTEM ${Boost_INCLUDE_DIRS} ${COIN3D_INCLUDE_DIRS} ${ZLIB_INCLUDE_DIR} diff --git a/src/Mod/Draft/App/CMakeLists.txt b/src/Mod/Draft/App/CMakeLists.txt index 373e31deb6..b01b3a13ba 100644 --- a/src/Mod/Draft/App/CMakeLists.txt +++ b/src/Mod/Draft/App/CMakeLists.txt @@ -8,6 +8,10 @@ include_directories( ${CMAKE_SOURCE_DIR}/src ${CMAKE_BINARY_DIR}/src ${CMAKE_CURRENT_BINARY_DIR} +) + +include_directories( + SYSTEM ${Boost_INCLUDE_DIRS} ${OCC_INCLUDE_DIR} ${PYCXX_INCLUDE_DIR} diff --git a/src/Mod/Draft/DraftGui.py b/src/Mod/Draft/DraftGui.py index 4eb01e311a..1a86ac0dec 100644 --- a/src/Mod/Draft/DraftGui.py +++ b/src/Mod/Draft/DraftGui.py @@ -1246,18 +1246,19 @@ class DraftToolBar: else: delta = plane.get_local_coords(point) + length, _, phi = DraftVecUtils.get_spherical_coords(*delta) + phi = math.degrees(phi) + self.x = delta.x self.y = delta.y self.z = delta.z + self.lvalue = length + self.avalue = phi + self.xValue.setText(display_external(delta.x,None,'Length')) self.yValue.setText(display_external(delta.y,None,'Length')) self.zValue.setText(display_external(delta.z,None,'Length')) - - length, theta, phi = DraftVecUtils.get_spherical_coords(*delta) - theta = math.degrees(theta) - phi = math.degrees(phi) self.lengthValue.setText(display_external(length,None,'Length')) - #if not self.angleLock.isChecked(): self.angleValue.setText(display_external(phi,None,'Angle')) # set masks diff --git a/src/Mod/Draft/draftguitools/gui_base_original.py b/src/Mod/Draft/draftguitools/gui_base_original.py index b2e4ffbf3c..b9f10c8eb2 100644 --- a/src/Mod/Draft/draftguitools/gui_base_original.py +++ b/src/Mod/Draft/draftguitools/gui_base_original.py @@ -236,7 +236,7 @@ class DraftTool: # Make face if self.ui: - make_face = str(bool(self.ui.makeFace)) + make_face = str(self.ui.makeFaceMode) else: make_face = "True" diff --git a/src/Mod/Draft/draftguitools/gui_edit.py b/src/Mod/Draft/draftguitools/gui_edit.py index ff48b19db6..307e3c18c8 100644 --- a/src/Mod/Draft/draftguitools/gui_edit.py +++ b/src/Mod/Draft/draftguitools/gui_edit.py @@ -679,7 +679,7 @@ class Edit(gui_base_original.Modifier): else: # try if user is over an edited object - pos = event.getPosition() + pos = event.getPosition().getValue() obj = self.get_selected_obj_at_position(pos) obj_gui_tools = self.get_obj_gui_tools(obj) @@ -825,8 +825,7 @@ class Edit(gui_base_original.Modifier): """Restore objects style during editing mode. """ for obj in objs: - if not obj.isAttachedToDocument(): - # Object has been deleted. + if utils.is_deleted(obj): continue obj_gui_tools = self.get_obj_gui_tools(obj) if obj_gui_tools: diff --git a/src/Mod/Draft/draftguitools/gui_rotate.py b/src/Mod/Draft/draftguitools/gui_rotate.py index 4a925479e6..dfa00ba4a4 100644 --- a/src/Mod/Draft/draftguitools/gui_rotate.py +++ b/src/Mod/Draft/draftguitools/gui_rotate.py @@ -36,6 +36,7 @@ from PySide.QtCore import QT_TRANSLATE_NOOP import FreeCAD as App import FreeCADGui as Gui import DraftVecUtils +from draftgeoutils import geometry from draftguitools import gui_base_original from draftguitools import gui_tool_utils from draftguitools import gui_trackers as trackers @@ -81,6 +82,8 @@ class Rotate(gui_base_original.Modifier): Gui.doCommand("selection = FreeCADGui.Selection.getSelectionEx(\"\", 0)") self.step = 0 self.center = None + self.point = None + self.firstangle = None self.ui.rotateSetCenterUi() self.arctrack = trackers.arcTracker() self.call = self.view.addEventCallback("SoEvent", self.action) @@ -106,17 +109,35 @@ class Rotate(gui_base_original.Modifier): and arg["Button"] == "BUTTON1"): self.handle_mouse_click_event(arg) + def _get_angle(self): + if self.center is None: + return 0 + if self.point is None: + return 0 + if DraftVecUtils.dist(self.point, self.center) < 1e-7: + return 0 + angle = DraftVecUtils.angle(self.wp.u, self.point.sub(self.center), self.wp.axis) + if self.firstangle is None: + return angle + if angle < self.firstangle: + return (2 * math.pi - self.firstangle) + angle + return angle - self.firstangle + def handle_mouse_move_event(self, arg): """Handle the mouse when moving.""" for ghost in self.ghosts: ghost.off() self.point, ctrlPoint, info = gui_tool_utils.getPoint(self, arg) - # this is to make sure radius is what you see on screen - if self.center and self.point and DraftVecUtils.dist(self.point, self.center): - viewdelta = DraftVecUtils.project(self.point.sub(self.center), - self.wp.axis) - if not DraftVecUtils.isNull(viewdelta): - self.point = self.point.add(viewdelta.negative()) + if self.center is not None: + # Project self.point on a plane that is parallel to the wp and that + # passes through self.center. + self.point = geometry.project_point_on_plane( + self.point, + self.center, + self.wp.axis, + direction=None, + force_projection=True + ) if self.extendedCopy: if not gui_tool_utils.hasMod(arg, gui_tool_utils.get_mod_alt_key()): self.step = 3 @@ -124,35 +145,17 @@ class Rotate(gui_base_original.Modifier): if self.step == 0: pass elif self.step == 1: - angle = 0 - if self.point: - currentrad = DraftVecUtils.dist(self.point, self.center) - if currentrad != 0: - angle = DraftVecUtils.angle(self.wp.u, - self.point.sub(self.center), - self.wp.axis) + angle = self._get_angle() self.ui.setRadiusValue(math.degrees(angle), unit="Angle") - self.firstangle = angle self.ui.radiusValue.setFocus() self.ui.radiusValue.selectAll() elif self.step == 2: - angle = 0 - if self.point: - currentrad = DraftVecUtils.dist(self.point, self.center) - if currentrad != 0: - angle = DraftVecUtils.angle(self.wp.u, - self.point.sub(self.center), - self.wp.axis) - if angle < self.firstangle: - sweep = (2 * math.pi - self.firstangle) + angle - else: - sweep = angle - self.firstangle - self.arctrack.setApertureAngle(sweep) + angle = self._get_angle() + self.arctrack.setApertureAngle(angle) for ghost in self.ghosts: - if sweep: - ghost.rotate(self.wp.axis, sweep) + ghost.rotate(self.wp.axis, angle) ghost.on() - self.ui.setRadiusValue(math.degrees(sweep), 'Angle') + self.ui.setRadiusValue(math.degrees(angle), unit="Angle") self.ui.radiusValue.setFocus() self.ui.radiusValue.selectAll() gui_tool_utils.redraw3DView() @@ -189,9 +192,9 @@ class Rotate(gui_base_original.Modifier): def set_start_point(self): """Set the starting point of the rotation.""" + self.firstangle = self._get_angle() self.ui.labelRadius.setText(translate("draft", "Rotation")) self.ui.radiusValue.setToolTip(translate("draft", "The amount of rotation you wish to perform.\nThe final angle will be the base angle plus this amount.")) - self.rad = DraftVecUtils.dist(self.point, self.center) self.arctrack.on() self.arctrack.setStartPoint(self.point) for ghost in self.ghosts: @@ -201,18 +204,10 @@ class Rotate(gui_base_original.Modifier): def set_rotation_angle(self, arg): """Set the rotation angle.""" - - # currentrad = DraftVecUtils.dist(self.point, self.center) - angle = self.point.sub(self.center).getAngle(self.wp.u) - _v = DraftVecUtils.project(self.point.sub(self.center), self.wp.v) - if _v.getAngle(self.wp.v) > 1: - angle = -angle - if angle < self.firstangle: - self.angle = (2 * math.pi - self.firstangle) + angle - else: - self.angle = angle - self.firstangle - self.rotate(self.ui.isCopy.isChecked() - or gui_tool_utils.hasMod(arg, gui_tool_utils.get_mod_alt_key())) + self.angle = self._get_angle() + if self.angle != 0: + self.rotate(self.ui.isCopy.isChecked() + or gui_tool_utils.hasMod(arg, gui_tool_utils.get_mod_alt_key())) if gui_tool_utils.hasMod(arg, gui_tool_utils.get_mod_alt_key()): self.extendedCopy = True else: diff --git a/src/Mod/Draft/draftguitools/gui_trimex.py b/src/Mod/Draft/draftguitools/gui_trimex.py index 27294ee696..4cfab71cac 100644 --- a/src/Mod/Draft/draftguitools/gui_trimex.py +++ b/src/Mod/Draft/draftguitools/gui_trimex.py @@ -158,7 +158,6 @@ class Trimex(gui_base_original.Modifier): self.finish() _err(translate("draft", "Trimex is not supported yet on this type of object.")) return - # self.obj.ViewObject.Visibility = False self.obj.ViewObject.LineColor = (0.5, 0.5, 0.5) self.obj.ViewObject.LineWidth = 1 self.extrudeMode = False @@ -323,10 +322,16 @@ class Trimex(gui_base_original.Modifier): # snapping if snapped: - snapped = self.doc.getObject(snapped['Object']) - if hasattr(snapped, "Shape"): + parent = snapped.get("ParentObject", None) + if parent: + subname = snapped["SubName"] + else: + parent = self.doc.getObject(snapped["Object"]) + subname = snapped["Component"] + shape = Part.getShape(parent, subname, needSubElement=True, noElementMap=True) + if shape.Edges: pts = [] - for e in snapped.Shape.Edges: + for e in shape.Edges: int = DraftGeomUtils.findIntersection(edge, e, True, True) if int: pts.extend(int) @@ -387,7 +392,7 @@ class Trimex(gui_base_original.Modifier): newedges.append(_sh) ghost.on() - # resetting the visible edges + # resetting the edges if not reverse: li = list(range(npoint + 1, len(self.edges))) else: @@ -578,7 +583,6 @@ class Trimex(gui_base_original.Modifier): for g in self.ghost: g.finalize() if self.obj: - self.obj.ViewObject.Visibility = True if self.color: self.obj.ViewObject.LineColor = self.color if self.width: diff --git a/src/Mod/Draft/importSVG.py b/src/Mod/Draft/importSVG.py index 5156e1e997..eb0749aaa4 100644 --- a/src/Mod/Draft/importSVG.py +++ b/src/Mod/Draft/importSVG.py @@ -636,7 +636,7 @@ def getrgb(color): Parameters ---------- - color : App::Color::Color + color : Base::Color::Color FreeCAD color. Returns @@ -1616,7 +1616,7 @@ class svgHandler(xml.sax.ContentHandler): _transf = _op + '\\s*?' + _val transformre = re.compile(_transf, re.DOTALL) m = FreeCAD.Matrix() - for transformation, arguments in transformre.findall(tr): + for transformation, arguments in reversed(transformre.findall(tr)): _args_rep = arguments.replace(',', ' ').split() argsplit = [float(arg) for arg in _args_rep] # m.multiply(FreeCAD.Matrix(1, 0, 0, 0, 0, -1)) diff --git a/src/Mod/Drawing/App/CMakeLists.txt b/src/Mod/Drawing/App/CMakeLists.txt index 9c4a90da2b..a2a83c674b 100644 --- a/src/Mod/Drawing/App/CMakeLists.txt +++ b/src/Mod/Drawing/App/CMakeLists.txt @@ -1,5 +1,9 @@ include_directories( ${CMAKE_BINARY_DIR} +) + +include_directories( + SYSTEM ${Boost_INCLUDE_DIRS} ${OCC_INCLUDE_DIR} ${ZLIB_INCLUDE_DIR} diff --git a/src/Mod/Drawing/App/FeatureViewAnnotation.cpp b/src/Mod/Drawing/App/FeatureViewAnnotation.cpp index 2281c9f899..0b93157b3e 100644 --- a/src/Mod/Drawing/App/FeatureViewAnnotation.cpp +++ b/src/Mod/Drawing/App/FeatureViewAnnotation.cpp @@ -58,7 +58,7 @@ FeatureViewAnnotation::~FeatureViewAnnotation() App::DocumentObjectExecReturn* FeatureViewAnnotation::execute(void) { stringstream result, hr, hg, hb; - const App::Color& c = TextColor.getValue(); + const Base::Color& c = TextColor.getValue(); hr << hex << setfill('0') << setw(2) << (int)(255.0 * c.r); hg << hex << setfill('0') << setw(2) << (int)(255.0 * c.g); hb << hex << setfill('0') << setw(2) << (int)(255.0 * c.b); diff --git a/src/Mod/Drawing/App/FeatureViewSpreadsheet.cpp b/src/Mod/Drawing/App/FeatureViewSpreadsheet.cpp index bf5b300e76..2aa53f3206 100644 --- a/src/Mod/Drawing/App/FeatureViewSpreadsheet.cpp +++ b/src/Mod/Drawing/App/FeatureViewSpreadsheet.cpp @@ -153,7 +153,7 @@ App::DocumentObjectExecReturn* FeatureViewSpreadsheet::execute(void) // create the containing group std::string ViewName = Label.getValue(); std::stringstream result, hr, hg, hb; - const App::Color& c = Color.getValue(); + const Base::Color& c = Color.getValue(); hr << std::hex << std::setfill('0') << std::setw(2) << (int)(255.0 * c.r); hg << std::hex << std::setfill('0') << std::setw(2) << (int)(255.0 * c.g); hb << std::hex << std::setfill('0') << std::setw(2) << (int)(255.0 * c.b); @@ -207,7 +207,7 @@ App::DocumentObjectExecReturn* FeatureViewSpreadsheet::execute(void) std::string textstyle = ""; Spreadsheet::Cell* cell = sheet->getCell(address); if (cell) { - App::Color f, b; + Base::Color f, b; std::set st; int colspan, rowspan; if (cell->getBackground(b)) { diff --git a/src/Mod/Drawing/Gui/CMakeLists.txt b/src/Mod/Drawing/Gui/CMakeLists.txt index b9c18d392a..45e5ed2fdb 100644 --- a/src/Mod/Drawing/Gui/CMakeLists.txt +++ b/src/Mod/Drawing/Gui/CMakeLists.txt @@ -2,6 +2,10 @@ include_directories( ${CMAKE_BINARY_DIR} ${CMAKE_SOURCE_DIR}/src ${CMAKE_CURRENT_BINARY_DIR} +) + +include_directories( + SYSTEM ${Boost_INCLUDE_DIRS} ${COIN3D_INCLUDE_DIRS} ${PYCXX_INCLUDE_DIR} diff --git a/src/Mod/Fem/App/CMakeLists.txt b/src/Mod/Fem/App/CMakeLists.txt index baa8abcc87..118493e062 100644 --- a/src/Mod/Fem/App/CMakeLists.txt +++ b/src/Mod/Fem/App/CMakeLists.txt @@ -20,6 +20,10 @@ include_directories( ${CMAKE_SOURCE_DIR}/src ${CMAKE_BINARY_DIR}/src ${CMAKE_CURRENT_BINARY_DIR} +) + +include_directories( + SYSTEM ${Boost_INCLUDE_DIRS} ${OCC_INCLUDE_DIR} ${PYCXX_INCLUDE_DIR} diff --git a/src/Mod/Fem/App/PreCompiled.h b/src/Mod/Fem/App/PreCompiled.h index c075ee3cb8..f679a40781 100644 --- a/src/Mod/Fem/App/PreCompiled.h +++ b/src/Mod/Fem/App/PreCompiled.h @@ -177,6 +177,9 @@ #include #include #include +#include +#include +#include #include #include #include diff --git a/src/Mod/Fem/CMakeLists.txt b/src/Mod/Fem/CMakeLists.txt index 56fb81cede..a8b9f378fe 100755 --- a/src/Mod/Fem/CMakeLists.txt +++ b/src/Mod/Fem/CMakeLists.txt @@ -285,6 +285,8 @@ SET(FemSolverElmerEquations_SRCS femsolver/elmer/equations/magnetodynamic2D.py femsolver/elmer/equations/magnetodynamic2D_writer.py femsolver/elmer/equations/nonlinear.py + femsolver/elmer/equations/staticcurrent.py + femsolver/elmer/equations/staticcurrent_writer.py ) SET(FemSolverFenics_SRCS diff --git a/src/Mod/Fem/Gui/CMakeLists.txt b/src/Mod/Fem/Gui/CMakeLists.txt index 2db0fdf104..8f343f3008 100755 --- a/src/Mod/Fem/Gui/CMakeLists.txt +++ b/src/Mod/Fem/Gui/CMakeLists.txt @@ -17,6 +17,10 @@ include_directories( ${CMAKE_BINARY_DIR} ${CMAKE_SOURCE_DIR}/src ${CMAKE_CURRENT_BINARY_DIR} +) + +include_directories( + SYSTEM ${Boost_INCLUDE_DIRS} ${COIN3D_INCLUDE_DIRS} ${ZLIB_INCLUDE_DIR} @@ -369,6 +373,7 @@ SET(FemGuiSymbol_IV Resources/symbols/ConstraintContact.iv Resources/symbols/ConstraintDisplacement.iv Resources/symbols/ConstraintElectrostaticPotential.iv + Resources/symbols/ConstraintCurrentDensity.iv Resources/symbols/ConstraintFixed.iv Resources/symbols/ConstraintForce.iv Resources/symbols/ConstraintHeatFlux.iv diff --git a/src/Mod/Fem/Gui/Command.cpp b/src/Mod/Fem/Gui/Command.cpp index 06fd5222a0..9032aa7b68 100644 --- a/src/Mod/Fem/Gui/Command.cpp +++ b/src/Mod/Fem/Gui/Command.cpp @@ -1542,6 +1542,9 @@ void CmdFemCompEmEquations::activated(int iMsg) else if (iMsg == 3) { rcCmdMgr.runCommandByName("FEM_EquationMagnetodynamic2D"); } + else if (iMsg == 4) { + rcCmdMgr.runCommandByName("FEM_EquationStaticCurrent"); + } else { return; } @@ -1569,6 +1572,8 @@ Gui::Action* CmdFemCompEmEquations::createAction() cmd2->setIcon(Gui::BitmapFactory().iconFromTheme("FEM_EquationMagnetodynamic")); QAction* cmd3 = pcAction->addAction(QString()); cmd3->setIcon(Gui::BitmapFactory().iconFromTheme("FEM_EquationMagnetodynamic2D")); + QAction* cmd4 = pcAction->addAction(QString()); + cmd4->setIcon(Gui::BitmapFactory().iconFromTheme("FEM_EquationStaticCurrent")); _pcAction = pcAction; languageChange(); @@ -1637,6 +1642,17 @@ void CmdFemCompEmEquations::languageChange() cmd3->setStatusTip(QApplication::translate("FEM_EquationMagnetodynamic2D", EquationMagnetodynamic2D->getStatusTip())); } + + Gui::Command* EquationStaticCurrent = rcCmdMgr.getCommandByName("FEM_EquationStaticCurrent"); + if (EquationStaticCurrent) { + QAction* cmd4 = a[4]; + cmd4->setText(QApplication::translate("FEM_EquationStaticCurrent", + EquationStaticCurrent->getMenuText())); + cmd4->setToolTip(QApplication::translate("FEM_EquationStaticCurrent", + EquationStaticCurrent->getToolTipText())); + cmd4->setStatusTip(QApplication::translate("FEM_EquationStaticCurrent", + EquationStaticCurrent->getStatusTip())); + } } bool CmdFemCompEmEquations::isActive() diff --git a/src/Mod/Fem/Gui/Resources/Fem.qrc b/src/Mod/Fem/Gui/Resources/Fem.qrc index db84762ef8..6342a0f9e5 100755 --- a/src/Mod/Fem/Gui/Resources/Fem.qrc +++ b/src/Mod/Fem/Gui/Resources/Fem.qrc @@ -51,6 +51,7 @@ icons/FEM_EquationHeat.svg icons/FEM_EquationMagnetodynamic.svg icons/FEM_EquationMagnetodynamic2D.svg + icons/FEM_EquationStaticCurrent.svg icons/FEM_CreateElementsSet.svg diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_EquationStaticCurrent.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_EquationStaticCurrent.svg new file mode 100644 index 0000000000..5a2ce5236d --- /dev/null +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_EquationStaticCurrent.svg @@ -0,0 +1,1066 @@ + + + + + + + image/svg+xml + + + + [vdwalts] + + + 2016-08-01 + https://www.freecad.org/wiki/index.php?title=Artwork + + + FreeCAD + + + FreeCAD/src/Mod/ + + + FreeCAD LGPL2+ + + + https://www.gnu.org/copyleft/lesser.html + + + [agryson] Alexander Gryson + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Mod/Fem/Gui/Resources/symbols/ConstraintCurrentDensity.iv b/src/Mod/Fem/Gui/Resources/symbols/ConstraintCurrentDensity.iv new file mode 100644 index 0000000000..d231f0b9de --- /dev/null +++ b/src/Mod/Fem/Gui/Resources/symbols/ConstraintCurrentDensity.iv @@ -0,0 +1,55 @@ +#Inventor V2.1 ascii + +# SPDX-License-Identifier: LGPL-2.1-or-later + +#/*************************************************************************** +# * Copyright (c) 2025 Mario Passaglia * +# * * +# * This file is part of FreeCAD. * +# * * +# * FreeCAD 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.1 of the * +# * License, or (at your option) any later version. * +# * * +# * FreeCAD 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 FreeCAD. If not, see * +# * . * +# * * +# ************************************************************************** + + +Separator { + + Separator { + + Switch { + + Separator { + + Translation { + translation 0 3.3333334 0 + } + Cone { + bottomRadius 0.66666669 + height 1.3333334 + + } + Translation { + translation 0 -2 0 + + } + Cylinder { + radius 0.26666668 + height 2.6666667 + + } + } + } + } +} diff --git a/src/Mod/Fem/Gui/Resources/ui/CurrentDensity.ui b/src/Mod/Fem/Gui/Resources/ui/CurrentDensity.ui index 3047b66c32..b3030d591b 100644 --- a/src/Mod/Fem/Gui/Resources/ui/CurrentDensity.ui +++ b/src/Mod/Fem/Gui/Resources/ui/CurrentDensity.ui @@ -13,336 +13,272 @@ Analysis feature properties - - - - - Current density: + + + + + + + Select Custom mode to enable vector current density + + + + + + Mode: + + + + + + + - - + + + + + true - - Real + + Imaginary part is only used for equations +with harmonic/oscillating driving current - - - - - - true - - - Imaginary + + false + + + + + true + + + Real + + + + + + + true + + + Imaginary + + + + + + + x + + + + + + + true + + + Real part of current density x-component + + + true + + + A/m^2 + + + 1.000000000000000 + + + 0.000000000000000 + + + + + + + true + + + Imaginary part of current density x-component + + + true + + + A/m^2 + + + 1.000000000000000 + + + 0.000000000000000 + + + + + + + y + + + + + + + true + + + Real part of current density y-component + + + true + + + A/m^2 + + + 1.000000000000000 + + + 0.000000000000000 + + + + + + + true + + + Imaginary part of current density y-component + + + true + + + A/m^2 + + + 1.000000000000000 + + + 0.000000000000000 + + + + + + + z + + + + + + + true + + + Real part of current density z-component + + + true + + + A/m^2 + + + 1.000000000000000 + + + 0.000000000000000 + + + + + + + true + + + Imaginary part of current density z-component + + + true + + + A/m^2 + + + 1.000000000000000 + + + 0.000000000000000 + + + + - - - true - - - x - - - - - - - true - - - - 100 - 20 - + + + - Real part of potential x-component -Note: if a face was selected this will be the value - in normal face direction - settings for y and z will be ignored - - - true - - - - - - -1000000000000000000000.000000000000000 - - - 1000000000000000000000.000000000000000 - - - 1.000000000000000 - - - 1.000000000000000 - - - - - - - unspecified - - - - - - - - - - true - - - - 100 - 20 - - - - Imaginary part of potential x-component -Note: if a face was selected this will be the value - in normal face direction - settings for y and z will be ignored - - - true - - - - - - -1000000000000000000000.000000000000000 - - - 1000000000000000000000.000000000000000 - - - 1.000000000000000 - - - 1.000000000000000 - - - - - - - unspecified - - - - - - - - - - true - - - y - - - - - - - true - - - - 100 - 20 - - - - Real part of potential y-component -Note: for 2D only setting for x is possible, - setting for y will be ignored - - - true - - - - - - -1000000000000000000000.000000000000000 - - - 1000000000000000000000.000000000000000 - - - 1.000000000000000 - - - 1.000000000000000 - - - - - - - unspecified - - - - - - - - - - true - - - - 100 - 20 - - - - Imaginary part of potential y-component -Note: for 2D only setting for x is possible, - setting for y will be ignored - - - true - - - - - - -1000000000000000000000.000000000000000 - - - 1000000000000000000000.000000000000000 - - - 1.000000000000000 - - - 1.000000000000000 - - - - - - - unspecified - - - - - - - - - - true - - - z - - - - - - - true - - - - 100 - 20 - - - - Real part of potential z-component - - - true - - - - - - -1000000000000000000000.000000000000000 - - - 1000000000000000000000.000000000000000 - - - 1.000000000000000 - - - 1.000000000000000 - - - - - - - unspecified - - - - - - - - - - true - - - - 100 - 20 - - - - Imaginary part of potential z-component - - - true - - - - - - -1000000000000000000000.000000000000000 - - - 1000000000000000000000.000000000000000 - - - 1.000000000000000 - - - 1.000000000000000 - - - - - - - unspecified - - - - + Current density normal to surface + + + + + + true + + + Real + + + + + + + true + + + Imaginary + + + + + + + Normal: + + + + + + + A/m^2 + + + + + + + A/m^2 + + + + @@ -355,102 +291,4 @@ Note: for 2D only setting for x is possible, - - - reXunspecBox - toggled(bool) - realXQSB - setDisabled(bool) - - - 152 - 61 - - - 80 - 61 - - - - - reYunspecBox - toggled(bool) - realYQSB - setDisabled(bool) - - - 152 - 87 - - - 80 - 87 - - - - - imZunspecBox - toggled(bool) - imagZQSB - setDisabled(bool) - - - 297 - 113 - - - 224 - 113 - - - - - imYunspecBox - toggled(bool) - imagYQSB - setDisabled(bool) - - - 297 - 87 - - - 224 - 87 - - - - - imXunspecBox - toggled(bool) - imagXQSB - setDisabled(bool) - - - 297 - 61 - - - 224 - 61 - - - - - reZunspecBox - toggled(bool) - realZQSB - setDisabled(bool) - - - 152 - 113 - - - 80 - 113 - - - - diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraint.cpp b/src/Mod/Fem/Gui/ViewProviderFemConstraint.cpp index 5c0576226d..040e9194cc 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraint.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraint.cpp @@ -200,9 +200,19 @@ void ViewProviderFemConstraint::handleChangedPropertyName(Base::XMLReader& reade } } +void ViewProviderFemConstraint::setRotateSymbol(bool rotate) +{ + rotateSymbol = rotate; + updateSymbol(); +} + void ViewProviderFemConstraint::updateSymbol() { auto obj = this->getObject(); + if (!obj) { + return; + } + const std::vector& points = obj->Points.getValue(); const std::vector& normals = obj->Normals.getValue(); if (points.size() != normals.size()) { diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraint.h b/src/Mod/Fem/Gui/ViewProviderFemConstraint.h index 6b7bdc0ff3..0f74e52488 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraint.h +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraint.h @@ -131,11 +131,6 @@ inline bool ViewProviderFemConstraint::getRotateSymbol() const return rotateSymbol; } -inline void ViewProviderFemConstraint::setRotateSymbol(bool rotate) -{ - rotateSymbol = rotate; -} - using ViewProviderFemConstraintPython = Gui::ViewProviderFeaturePythonT; diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraintOnBoundary.cpp b/src/Mod/Fem/Gui/ViewProviderFemConstraintOnBoundary.cpp index d0cd7415fc..07541b3b97 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraintOnBoundary.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraintOnBoundary.cpp @@ -67,7 +67,7 @@ void ViewProviderFemConstraintOnBoundary::highlightReferences(const bool on) if (originalPointColors[base].empty()) { originalPointColors[base] = vp->PointColorArray.getValues(); } - std::vector colors = originalPointColors[base]; + std::vector colors = originalPointColors[base]; // go through the subelements with constraint and recolor them // TODO: Replace `ShapeAppearance` with anything more appropriate @@ -82,7 +82,7 @@ void ViewProviderFemConstraintOnBoundary::highlightReferences(const bool on) if (originalLineColors[base].empty()) { originalLineColors[base] = vp->LineColorArray.getValues(); } - std::vector colors = originalLineColors[base]; + std::vector colors = originalLineColors[base]; // go through the subelements with constraint and recolor them // TODO: Replace `ShapeAppearance` with anything more appropriate @@ -97,7 +97,7 @@ void ViewProviderFemConstraintOnBoundary::highlightReferences(const bool on) if (originalFaceColors[base].empty()) { originalFaceColors[base] = vp->ShapeAppearance.getDiffuseColors(); } - std::vector colors = originalFaceColors[base]; + std::vector colors = originalFaceColors[base]; // go through the subelements with constraint and recolor them // TODO: Replace shape DiffuseColor with anything more appropriate diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraintOnBoundary.h b/src/Mod/Fem/Gui/ViewProviderFemConstraintOnBoundary.h index bca7164b1c..80e043d317 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraintOnBoundary.h +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraintOnBoundary.h @@ -46,9 +46,9 @@ public: void highlightReferences(const bool on) override; private: - std::map> originalPointColors; - std::map> originalLineColors; - std::map> originalFaceColors; + std::map> originalPointColors; + std::map> originalLineColors; + std::map> originalFaceColors; }; } // namespace FemGui diff --git a/src/Mod/Fem/Gui/ViewProviderFemMesh.cpp b/src/Mod/Fem/Gui/ViewProviderFemMesh.cpp index 6cbb27cd04..23f9c793c1 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemMesh.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemMesh.cpp @@ -192,13 +192,13 @@ ViewProviderFemMesh::ViewProviderFemMesh() { sPixmap = "fem-femmesh-from-shape"; - ADD_PROPERTY(PointColor, (App::Color(0.7f, 0.7f, 0.7f))); + ADD_PROPERTY(PointColor, (Base::Color(0.7f, 0.7f, 0.7f))); ADD_PROPERTY(PointSize, (5.0f)); PointSize.setConstraints(&floatRange); ADD_PROPERTY(LineWidth, (1.0f)); LineWidth.setConstraints(&floatRange); - ShapeAppearance.setDiffuseColor(App::Color(1.0f, 0.7f, 0.0f)); + ShapeAppearance.setDiffuseColor(Base::Color(1.0f, 0.7f, 0.0f)); Transparency.setValue(0); ADD_PROPERTY(BackfaceCulling, (true)); ADD_PROPERTY(ShowInner, (false)); @@ -412,7 +412,7 @@ void ViewProviderFemMesh::onChanged(const App::Property* prop) pcPointStyle->pointSize = PointSize.getValue(); } else if (prop == &PointColor) { - const App::Color& c = PointColor.getValue(); + const Base::Color& c = PointColor.getValue(); pcPointMaterial->diffuseColor.setValue(c.r, c.g, c.b); } else if (prop == &BackfaceCulling) { @@ -683,11 +683,11 @@ void ViewProviderFemMesh::applyDisplacementToNodes(double factor) } void ViewProviderFemMesh::setColorByNodeId(const std::vector& NodeIds, - const std::vector& NodeColors) + const std::vector& NodeColors) { long endId = *(std::max_element(NodeIds.begin(), NodeIds.end())); - std::vector colorVec(endId + 1, App::Color(0, 1, 0)); + std::vector colorVec(endId + 1, Base::Color(0, 1, 0)); long i = 0; for (std::vector::const_iterator it = NodeIds.begin(); it != NodeIds.end(); ++it, i++) { colorVec[*it] = NodeColors[i]; @@ -696,7 +696,7 @@ void ViewProviderFemMesh::setColorByNodeId(const std::vector& NodeIds, setColorByNodeIdHelper(colorVec); } -void ViewProviderFemMesh::setColorByNodeIdHelper(const std::vector& colorVec) +void ViewProviderFemMesh::setColorByNodeIdHelper(const std::vector& colorVec) { pcMatBinding->value = SoMaterialBinding::PER_VERTEX_INDEXED; @@ -716,43 +716,43 @@ void ViewProviderFemMesh::setColorByNodeIdHelper(const std::vector& void ViewProviderFemMesh::resetColorByNodeId() { - const App::Color& c = ShapeAppearance.getDiffuseColor(); + const Base::Color& c = ShapeAppearance.getDiffuseColor(); NodeColorArray.setValue(c); } void ViewProviderFemMesh::setColorByNodeId( - const std::map, App::Color>& elemColorMap) + const std::map, Base::Color>& elemColorMap) { setColorByIdHelper(elemColorMap, vNodeElementIdx, 0, NodeColorArray); } void ViewProviderFemMesh::setColorByElementId( - const std::map, App::Color>& elemColorMap) + const std::map, Base::Color>& elemColorMap) { setColorByIdHelper(elemColorMap, vFaceElementIdx, 3, ElementColorArray); } void ViewProviderFemMesh::setColorByIdHelper( - const std::map, App::Color>& elemColorMap, + const std::map, Base::Color>& elemColorMap, const std::vector& vElementIdx, int rShift, App::PropertyColorList& prop) { - std::vector vecColor(vElementIdx.size()); - std::map colorMap; + std::vector vecColor(vElementIdx.size()); + std::map colorMap; for (const auto& m : elemColorMap) { for (long i : m.first) { colorMap[i] = &m.second; } } - App::Color baseDif = ShapeAppearance.getDiffuseColor(); + Base::Color baseDif = ShapeAppearance.getDiffuseColor(); int i = 0; for (std::vector::const_iterator it = vElementIdx.begin(); it != vElementIdx.end(); ++it, i++) { unsigned long ElemIdx = ((*it) >> rShift); - const std::map::const_iterator pos = colorMap.find(ElemIdx); + const std::map::const_iterator pos = colorMap.find(ElemIdx); vecColor[i] = pos == colorMap.end() ? baseDif : *pos->second; } @@ -762,10 +762,10 @@ void ViewProviderFemMesh::setColorByIdHelper( void ViewProviderFemMesh::setMaterialOverall() const { const App::Material& mat = ShapeAppearance[0]; - App::Color baseDif = mat.diffuseColor; - App::Color baseAmb = mat.ambientColor; - App::Color baseSpe = mat.specularColor; - App::Color baseEmi = mat.emissiveColor; + Base::Color baseDif = mat.diffuseColor; + Base::Color baseAmb = mat.ambientColor; + Base::Color baseSpe = mat.specularColor; + Base::Color baseEmi = mat.emissiveColor; float baseShi = mat.shininess; float baseTra = mat.transparency; @@ -793,15 +793,15 @@ void ViewProviderFemMesh::setMaterialByColorArray( const std::vector& vElementIdx) const { const App::Material& baseMat = ShapeAppearance[0]; - App::Color baseDif = baseMat.diffuseColor; - App::Color baseAmb = baseMat.ambientColor; - App::Color baseSpe = baseMat.specularColor; - App::Color baseEmi = baseMat.emissiveColor; + Base::Color baseDif = baseMat.diffuseColor; + Base::Color baseAmb = baseMat.ambientColor; + Base::Color baseSpe = baseMat.specularColor; + Base::Color baseEmi = baseMat.emissiveColor; float baseShi = baseMat.shininess; float baseTra = baseMat.transparency; // resizing and writing the color vector: - std::vector vecColor = prop->getValue(); + std::vector vecColor = prop->getValue(); size_t elemSize = vElementIdx.size(); if (vecColor.size() == 1) { pcMatBinding->value = SoMaterialBinding::OVERALL; @@ -844,7 +844,7 @@ void ViewProviderFemMesh::setMaterialByColorArray( vecColor.resize(elemSize, baseDif); int i = 0; - for (const App::Color& c : vecColor) { + for (const Base::Color& c : vecColor) { diffuse[i] = SbColor(c.r, c.g, c.b); ambient[i] = SbColor(baseAmb.r, baseAmb.g, baseAmb.b); specular[i] = SbColor(baseSpe.r, baseSpe.g, baseSpe.b); @@ -866,7 +866,7 @@ void ViewProviderFemMesh::setMaterialByColorArray( void ViewProviderFemMesh::resetColorByElementId() { - const App::Color& c = ShapeAppearance.getDiffuseColor(); + const Base::Color& c = ShapeAppearance.getDiffuseColor(); ElementColorArray.setValue(c); } diff --git a/src/Mod/Fem/Gui/ViewProviderFemMesh.h b/src/Mod/Fem/Gui/ViewProviderFemMesh.h index 108afb5418..004c77317f 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemMesh.h +++ b/src/Mod/Fem/Gui/ViewProviderFemMesh.h @@ -114,9 +114,9 @@ public: //@{ /// set the color for each node - void setColorByNodeId(const std::map, App::Color>& NodeColorMap); + void setColorByNodeId(const std::map, Base::Color>& NodeColorMap); void setColorByNodeId(const std::vector& NodeIds, - const std::vector& NodeColors); + const std::vector& NodeColors); /// reset the view of the node colors void resetColorByNodeId(); @@ -129,7 +129,7 @@ public: /// reaply the node displacement with a certain factor and do a redraw void applyDisplacementToNodes(double factor); /// set the color for each element - void setColorByElementId(const std::map, App::Color>& ElementColorMap); + void setColorByElementId(const std::map, Base::Color>& ElementColorMap); /// reset the view of the element colors void resetColorByElementId(); void setMaterialByElement(); @@ -151,9 +151,9 @@ protected: /// get called by the container whenever a property has been changed void onChanged(const App::Property* prop) override; - void setColorByNodeIdHelper(const std::vector&); + void setColorByNodeIdHelper(const std::vector&); void setDisplacementByNodeIdHelper(const std::vector& DispVector, long startId); - void setColorByIdHelper(const std::map, App::Color>& elemColorMap, + void setColorByIdHelper(const std::map, Base::Color>& elemColorMap, const std::vector& vElementIdx, int rShift, App::PropertyColorList& prop); diff --git a/src/Mod/Fem/Gui/ViewProviderFemMeshPyImp.cpp b/src/Mod/Fem/Gui/ViewProviderFemMeshPyImp.cpp index b31278ba39..cd476e6a84 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemMeshPyImp.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemMeshPyImp.cpp @@ -41,7 +41,7 @@ PyObject* ViewProviderFemMeshPy::applyDisplacement(PyObject* args) } -App::Color calcColor(double value, double min, double max) +Base::Color calcColor(double value, double min, double max) { if (max < 0) { max = 0; @@ -51,27 +51,27 @@ App::Color calcColor(double value, double min, double max) } if (value < min) { - return App::Color(0.0, 0.0, 1.0); + return Base::Color(0.0, 0.0, 1.0); } if (value > max) { - return App::Color(1.0, 0.0, 0.0); + return Base::Color(1.0, 0.0, 0.0); } if (value == 0.0) { - return App::Color(0.0, 1.0, 0.0); + return Base::Color(0.0, 1.0, 0.0); } if (value > max / 2.0) { - return App::Color(1.0, 1 - ((value - (max / 2.0)) / (max / 2.0)), 0.0); + return Base::Color(1.0, 1 - ((value - (max / 2.0)) / (max / 2.0)), 0.0); } if (value > 0.0) { - return App::Color(value / (max / 2.0), 1.0, 0.0); + return Base::Color(value / (max / 2.0), 1.0, 0.0); } if (value < min / 2.0) { - return App::Color(0.0, 1 - ((value - (min / 2.0)) / (min / 2.0)), 1.0); + return Base::Color(0.0, 1 - ((value - (min / 2.0)) / (min / 2.0)), 1.0); } if (value < 0.0) { - return App::Color(0.0, 1.0, value / (min / 2.0)); + return Base::Color(0.0, 1.0, value / (min / 2.0)); } - return App::Color(0, 0, 0); + return Base::Color(0, 0, 0); } @@ -90,7 +90,7 @@ PyObject* ViewProviderFemMeshPy::setNodeColorByScalars(PyObject* args) PyErr_SetString(PyExc_ValueError, "PyList_Size < 0. That is not a valid list!"); Py_Return; } - std::vector node_colors(num_items); + std::vector node_colors(num_items); for (int i = 0; i < num_items; i++) { PyObject* id_py = PyList_GetItem(node_ids_py, i); long id = PyLong_AsLong(id_py); @@ -182,9 +182,9 @@ Py::Dict ViewProviderFemMeshPy::getNodeColor() const namespace { -std::map, App::Color> colorMapFromDict(Py::Dict& arg) +std::map, Base::Color> colorMapFromDict(Py::Dict& arg) { - std::map, App::Color> colorMap; + std::map, Base::Color> colorMap; for (Py::Dict::iterator it = arg.begin(); it != arg.end(); ++it) { std::vector vecId; const Py::Object& id = (*it).first; @@ -199,7 +199,7 @@ std::map, App::Color> colorMapFromDict(Py::Dict& arg) } const Py::Object& value = (*it).second; Py::Tuple color(value); - colorMap[vecId] = App::Color(Py::Float(color[0]), Py::Float(color[1]), Py::Float(color[2])); + colorMap[vecId] = Base::Color(Py::Float(color[0]), Py::Float(color[1]), Py::Float(color[2])); } return colorMap; diff --git a/src/Mod/Fem/Gui/ViewProviderFemPostObject.cpp b/src/Mod/Fem/Gui/ViewProviderFemPostObject.cpp index 2f76154c3b..32b68bf036 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemPostObject.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemPostObject.cpp @@ -703,8 +703,8 @@ void ViewProviderFemPostObject::WriteColorData(bool ResetColorBarRange) m_matPlainEdges->transparency.setNum(numPts); float* transp = m_material->transparency.startEditing(); float* edgeTransp = m_matPlainEdges->transparency.startEditing(); - App::Color c; - App::Color cEdge = EdgeColor.getValue(); + Base::Color c; + Base::Color cEdge = EdgeColor.getValue(); for (int i = 0; i < numPts; i++) { double value = 0; @@ -930,7 +930,7 @@ void ViewProviderFemPostObject::onChanged(const App::Property* prop) m_drawStyle->pointSize.setValue(PointSize.getValue()); } else if (prop == &EdgeColor && setupPipeline()) { - App::Color c = EdgeColor.getValue(); + Base::Color c = EdgeColor.getValue(); SbColor* edgeColor = m_matPlainEdges->diffuseColor.startEditing(); for (int i = 0; i < m_matPlainEdges->diffuseColor.getNum(); ++i) { edgeColor[i].setValue(c.r, c.g, c.b); diff --git a/src/Mod/Fem/ObjectsFem.py b/src/Mod/Fem/ObjectsFem.py index ad8963d760..d5bc8838f5 100644 --- a/src/Mod/Fem/ObjectsFem.py +++ b/src/Mod/Fem/ObjectsFem.py @@ -767,6 +767,17 @@ def makeEquationMagnetodynamic2D(doc, base_solver=None, name="Magnetodynamic2D") return obj +def makeEquationStaticCurrent(doc, base_solver=None, name="StaticCurrent"): + """makeEquationStaticCurrent(document, [base_solver], [name]): + creates a FEM static current equation for a solver""" + from femsolver.elmer.equations import staticcurrent + + obj = staticcurrent.create(doc, name) + if base_solver: + base_solver.addObject(obj) + return obj + + def makeSolverCalculiXCcxTools(doc, name="SolverCcxTools"): """makeSolverCalculiXCcxTools(document, [name]): makes a Calculix solver object for the ccx tools module""" diff --git a/src/Mod/Fem/femcommands/commands.py b/src/Mod/Fem/femcommands/commands.py index c7ad19a824..69bed9352f 100644 --- a/src/Mod/Fem/femcommands/commands.py +++ b/src/Mod/Fem/femcommands/commands.py @@ -502,6 +502,19 @@ class _EquationMagnetodynamic2D(CommandManager): self.do_activated = "add_obj_on_gui_selobj_expand_noset_edit" +class _EquationStaticCurrent(CommandManager): + "The FEM_EquationStaticCurrent command definition" + + def __init__(self): + super().__init__() + self.menutext = Qt.QT_TRANSLATE_NOOP("FEM_EquationStaticCurrent", "Static current equation") + self.tooltip = Qt.QT_TRANSLATE_NOOP( + "FEM_EquationStaticCurrent", "Creates a FEM equation for static current" + ) + self.is_active = "with_solver_elmer" + self.do_activated = "add_obj_on_gui_selobj_expand_noset_edit" + + class _Examples(CommandManager): "The FEM_Examples command definition" @@ -1179,6 +1192,7 @@ FreeCADGui.addCommand("FEM_EquationFlux", _EquationFlux()) FreeCADGui.addCommand("FEM_EquationHeat", _EquationHeat()) FreeCADGui.addCommand("FEM_EquationMagnetodynamic", _EquationMagnetodynamic()) FreeCADGui.addCommand("FEM_EquationMagnetodynamic2D", _EquationMagnetodynamic2D()) +FreeCADGui.addCommand("FEM_EquationStaticCurrent", _EquationStaticCurrent()) FreeCADGui.addCommand("FEM_Examples", _Examples()) FreeCADGui.addCommand("FEM_MaterialEditor", _MaterialEditor()) FreeCADGui.addCommand("FEM_MaterialFluid", _MaterialFluid()) diff --git a/src/Mod/Fem/femexamples/equation_magnetodynamics_2D_elmer.py b/src/Mod/Fem/femexamples/equation_magnetodynamics_2D_elmer.py index 6f99c1ff5a..1571d16a39 100644 --- a/src/Mod/Fem/femexamples/equation_magnetodynamics_2D_elmer.py +++ b/src/Mod/Fem/femexamples/equation_magnetodynamics_2D_elmer.py @@ -252,8 +252,8 @@ def setup(doc=None, solvertype="elmer"): # constraint current density CurrentDensity = ObjectsFem.makeConstraintCurrentDensity(doc, "CurrentDensity") CurrentDensity.References = [(BooleanFragments, "Face2")] - CurrentDensity.CurrentDensity_re_1 = "250000.000 A/m^2" - CurrentDensity.CurrentDensity_re_1_Disabled = False + CurrentDensity.NormalCurrentDensity_re = "250000.000 A/m^2" + CurrentDensity.Mode = "Normal" analysis.addObject(CurrentDensity) # mesh diff --git a/src/Mod/Fem/femobjects/constraint_currentdensity.py b/src/Mod/Fem/femobjects/constraint_currentdensity.py index 1c3f6499ff..c97a67d255 100644 --- a/src/Mod/Fem/femobjects/constraint_currentdensity.py +++ b/src/Mod/Fem/femobjects/constraint_currentdensity.py @@ -1,5 +1,6 @@ # *************************************************************************** # * Copyright (c) 2023 Uwe Stöhr * +# * Copyright (c) 2025 Mario Passaglia * # * * # * This file is part of the FreeCAD CAx development system. * # * * @@ -22,15 +23,19 @@ # *************************************************************************** __title__ = "FreeCAD FEM constraint current density document object" -__author__ = "Uwe Stöhr" +__author__ = "Uwe Stöhr, Mario Passaglia" __url__ = "https://www.freecad.org" ## @package constraint_currentdensity # \ingroup FEM # \brief constraint current density object +from FreeCAD import Base + from . import base_fempythonobject +_PropHelper = base_fempythonobject._PropHelper + class ConstraintCurrentDensity(base_fempythonobject.BaseFemPythonObject): @@ -38,101 +43,159 @@ class ConstraintCurrentDensity(base_fempythonobject.BaseFemPythonObject): def __init__(self, obj): super().__init__(obj) - self.add_properties(obj) + + for prop in self._get_properties(): + prop.add_to_object(obj) + + def _get_properties(self): + prop = [] + + prop.append( + _PropHelper( + type="App::PropertyCurrentDensity", + name="CurrentDensity_re_1", + group="Current Density", + doc="Real part of current density x-component", + value="0 A/m^2", + ) + ) + prop.append( + _PropHelper( + type="App::PropertyCurrentDensity", + name="CurrentDensity_re_2", + group="Current Density", + doc="Real part of current density y-component", + value="0 A/m^2", + ) + ) + prop.append( + _PropHelper( + type="App::PropertyCurrentDensity", + name="CurrentDensity_re_3", + group="Current Density", + doc="Real part of current density z-component", + value="0 A/m^2", + ) + ) + prop.append( + _PropHelper( + type="App::PropertyCurrentDensity", + name="CurrentDensity_im_1", + group="Current Density", + doc="Imaginary part of current density x-component", + value="0 A/m^2", + ) + ) + prop.append( + _PropHelper( + type="App::PropertyCurrentDensity", + name="CurrentDensity_im_2", + group="Current Density", + doc="Imaginary part of current density y-component", + value="0 A/m^2", + ) + ) + prop.append( + _PropHelper( + type="App::PropertyCurrentDensity", + name="CurrentDensity_im_3", + group="Current Density", + doc="Imaginary part of current density z-component", + value="0 A/m^2", + ) + ) + prop.append( + _PropHelper( + type="App::PropertyBool", + name="EnableCurrentDensity_1", + group="Current Density", + doc="Enable currenty density x component", + value=False, + ) + ) + prop.append( + _PropHelper( + type="App::PropertyBool", + name="EnableCurrentDensity_2", + group="Current Density", + doc="Enable currenty density y component", + value=False, + ) + ) + prop.append( + _PropHelper( + type="App::PropertyBool", + name="EnableCurrentDensity_3", + group="Current Density", + doc="Enable currenty density z component", + value=False, + ) + ) + prop.append( + _PropHelper( + type="App::PropertyCurrentDensity", + name="NormalCurrentDensity_re", + group="Current Density", + doc="Real part of current density normal to boundary", + value="0 A/m^2", + ) + ) + prop.append( + _PropHelper( + type="App::PropertyCurrentDensity", + name="NormalCurrentDensity_im", + group="Current Density", + doc="Imaginary part of current density normal to boundary", + value="0 A/m^2", + ) + ) + prop.append( + _PropHelper( + type="App::PropertyEnumeration", + name="Mode", + group="Current Density", + doc="Set current boundary condition direction mode", + value=["Custom", "Normal"], + ) + ) + + return prop def onDocumentRestored(self, obj): - self.add_properties(obj) + # update old project with new properties + for prop in self._get_properties(): + try: + obj.getPropertyByName(prop.name) + except Base.PropertyError: + prop.add_to_object(obj) - def add_properties(self, obj): - if not hasattr(obj, "CurrentDensity_re_1"): - obj.addProperty( - "App::PropertyCurrentDensity", - "CurrentDensity_re_1", - "Vector Potential", - "Real part of current density x-component", - ) - obj.setPropertyStatus("CurrentDensity_re_1", "LockDynamic") - obj.CurrentDensity_re_1 = "0 A/m^2" - if not hasattr(obj, "CurrentDensity_re_2"): - obj.addProperty( - "App::PropertyCurrentDensity", - "CurrentDensity_re_2", - "Vector Potential", - "Real part of current density y-component", - ) - obj.setPropertyStatus("CurrentDensity_re_2", "LockDynamic") - obj.CurrentDensity_re_2 = "0 A/m^2" - if not hasattr(obj, "CurrentDensity_re_3"): - obj.addProperty( - "App::PropertyCurrentDensity", - "CurrentDensity_re_3", - "Vector Potential", - "Real part of current density z-component", - ) - obj.setPropertyStatus("CurrentDensity_re_3", "LockDynamic") - obj.CurrentDensity_re_3 = "0 A/m^2" - if not hasattr(obj, "CurrentDensity_im_1"): - obj.addProperty( - "App::PropertyCurrentDensity", - "CurrentDensity_im_1", - "Vector Potential", - "Imaginary part of current density x-component", - ) - obj.setPropertyStatus("CurrentDensity_im_1", "LockDynamic") - obj.CurrentDensity_im_1 = "0 A/m^2" - if not hasattr(obj, "CurrentDensity_im_2"): - obj.addProperty( - "App::PropertyCurrentDensity", - "CurrentDensity_im_2", - "Vector Potential", - "Imaginary part of current density y-component", - ) - obj.setPropertyStatus("CurrentDensity_im_2", "LockDynamic") - obj.CurrentDensity_im_2 = "0 A/m^2" - if not hasattr(obj, "CurrentDensity_im_3"): - obj.addProperty( - "App::PropertyCurrentDensity", - "CurrentDensity_im_3", - "Vector Potential", - "Imaginary part of current density z-component", - ) - obj.setPropertyStatus("CurrentDensity_im_3", "LockDynamic") - obj.CurrentDensity_im_3 = "0 A/m^2" + # enable current density properties from old properties + try: + obj.EnableCurrentDensity_1 = not obj.getPropertyByName( + "CurrentDensity_re_1_Disabled" + ) or not obj.getPropertyByName("CurrentDensity_im_1_Disabled") - # now the enable bools - if not hasattr(obj, "CurrentDensity_re_1_Disabled"): - obj.addProperty( - "App::PropertyBool", "CurrentDensity_re_1_Disabled", "Vector Potential", "" - ) - obj.setPropertyStatus("CurrentDensity_re_1_Disabled", "LockDynamic") - obj.CurrentDensity_re_1_Disabled = True - if not hasattr(obj, "CurrentDensity_re_2_Disabled"): - obj.addProperty( - "App::PropertyBool", "CurrentDensity_re_2_Disabled", "Vector Potential", "" - ) - obj.setPropertyStatus("CurrentDensity_re_2_Disabled", "LockDynamic") - obj.CurrentDensity_re_2_Disabled = True - if not hasattr(obj, "CurrentDensity_re_3_Disabled"): - obj.addProperty( - "App::PropertyBool", "CurrentDensity_re_3_Disabled", "Vector Potential", "" - ) - obj.setPropertyStatus("CurrentDensity_re_3_Disabled", "LockDynamic") - obj.CurrentDensity_re_3_Disabled = True - if not hasattr(obj, "CurrentDensity_im_1_Disabled"): - obj.addProperty( - "App::PropertyBool", "CurrentDensity_im_1_Disabled", "Vector Potential", "" - ) - obj.setPropertyStatus("CurrentDensity_im_1_Disabled", "LockDynamic") - obj.CurrentDensity_im_1_Disabled = True - if not hasattr(obj, "CurrentDensity_im_2_Disabled"): - obj.addProperty( - "App::PropertyBool", "CurrentDensity_im_2_Disabled", "Vector Potential", "" - ) - obj.setPropertyStatus("CurrentDensity_im_2_Disabled", "LockDynamic") - obj.CurrentDensity_im_2_Disabled = True - if not hasattr(obj, "CurrentDensity_im_3_Disabled"): - obj.addProperty( - "App::PropertyBool", "CurrentDensity_im_3_Disabled", "Vector Potential", "" - ) - obj.setPropertyStatus("CurrentDensity_im_3_Disabled", "LockDynamic") - obj.CurrentDensity_im_3_Disabled = True + obj.EnableCurrentDensity_2 = not obj.getPropertyByName( + "CurrentDensity_re_2_Disabled" + ) or not obj.getPropertyByName("CurrentDensity_im_2_Disabled") + + obj.EnableCurrentDensity_3 = not obj.getPropertyByName( + "CurrentDensity_re_3_Disabled" + ) or not obj.getPropertyByName("CurrentDensity_im_3_Disabled") + + # remove old properties + obj.setPropertyStatus("CurrentDensity_re_1_Disabled", "-LockDynamic") + obj.removeProperty("CurrentDensity_re_1_Disabled") + obj.setPropertyStatus("CurrentDensity_re_2_Disabled", "-LockDynamic") + obj.removeProperty("CurrentDensity_re_2_Disabled") + obj.setPropertyStatus("CurrentDensity_re_3_Disabled", "-LockDynamic") + obj.removeProperty("CurrentDensity_re_3_Disabled") + obj.setPropertyStatus("CurrentDensity_im_1_Disabled", "-LockDynamic") + obj.removeProperty("CurrentDensity_im_1_Disabled") + obj.setPropertyStatus("CurrentDensity_im_2_Disabled", "-LockDynamic") + obj.removeProperty("CurrentDensity_im_2_Disabled") + obj.setPropertyStatus("CurrentDensity_im_3_Disabled", "-LockDynamic") + obj.removeProperty("CurrentDensity_im_3_Disabled") + + except Base.PropertyError: + pass diff --git a/src/Mod/Fem/femsolver/elmer/equations/magnetodynamic2D_writer.py b/src/Mod/Fem/femsolver/elmer/equations/magnetodynamic2D_writer.py index 8444a44325..6bc835060b 100644 --- a/src/Mod/Fem/femsolver/elmer/equations/magnetodynamic2D_writer.py +++ b/src/Mod/Fem/femsolver/elmer/equations/magnetodynamic2D_writer.py @@ -31,6 +31,7 @@ __url__ = "https://www.freecad.org" from FreeCAD import Console from FreeCAD import Units +from femtools import femutils from .. import sifio from .. import writer as general_writer @@ -135,16 +136,13 @@ class MgDyn2Dwriter: ) def _outputMagnetodynamic2DBodyForce(self, obj, name, equation): - if hasattr(obj, "CurrentDensity_re_1"): - # output only if current density is enabled and needed - if not obj.CurrentDensity_re_1_Disabled: - currentDensity = float(obj.CurrentDensity_re_1.getValueAs("A/m^2")) - self.write.bodyForce(name, "Current Density", round(currentDensity, 6)) + if femutils.is_derived_from(obj, "Fem::ConstraintCurrentDensity") and obj.Mode == "Normal": + currentDensity = obj.NormalCurrentDensity_re.getValueAs("A/m^2").Value + self.write.bodyForce(name, "Current Density", round(currentDensity, 6)) # imaginaries are only needed for harmonic equation if equation.IsHarmonic: - if not obj.CurrentDensity_im_1_Disabled: - currentDensity = float(obj.CurrentDensity_im_1.getValueAs("A/m^2")) - self.write.bodyForce(name, "Current Density Im", round(currentDensity, 6)) + currentDensity = obj.NormalCurrentDensity_im.getValueAs("A/m^2").Value + self.write.bodyForce(name, "Current Density Im", round(currentDensity, 6)) if hasattr(obj, "Magnetization_re_1"): # output only if magnetization is enabled and needed diff --git a/src/Mod/Fem/femsolver/elmer/equations/magnetodynamic_writer.py b/src/Mod/Fem/femsolver/elmer/equations/magnetodynamic_writer.py index d0a7e759fc..479cdfcfb9 100644 --- a/src/Mod/Fem/femsolver/elmer/equations/magnetodynamic_writer.py +++ b/src/Mod/Fem/femsolver/elmer/equations/magnetodynamic_writer.py @@ -162,26 +162,26 @@ class MgDynwriter: ) def _outputMagnetodynamicBodyForce(self, obj, name, equation): - if hasattr(obj, "CurrentDensity_re_1"): + if femutils.is_derived_from(obj, "Fem::ConstraintCurrentDensity") and obj.Mode == "Custom": # output only if current density is enabled and needed - if not obj.CurrentDensity_re_1_Disabled: + if obj.EnableCurrentDensity_re_1: currentDensity = float(obj.CurrentDensity_re_1.getValueAs("A/m^2")) self.write.bodyForce(name, "Current Density 1", round(currentDensity, 6)) - if not obj.CurrentDensity_re_2_Disabled: + if obj.EnableCurrentDensity_re_2: currentDensity = float(obj.CurrentDensity_re_2.getValueAs("A/m^2")) self.write.bodyForce(name, "Current Density 2", round(currentDensity, 6)) - if not obj.CurrentDensity_re_3_Disabled: + if obj.EnableCurrentDensity_re_3: currentDensity = float(obj.CurrentDensity_re_3.getValueAs("A/m^2")) self.write.bodyForce(name, "Current Density 3", round(currentDensity, 6)) # imaginaries are only needed for harmonic equation if equation.IsHarmonic: - if not obj.CurrentDensity_im_1_Disabled: + if obj.EnableCurrentDensity_im_1: currentDensity = float(obj.CurrentDensity_im_1.getValueAs("A/m^2")) self.write.bodyForce(name, "Current Density Im 1", round(currentDensity, 6)) - if not obj.CurrentDensity_im_2_Disabled: + if obj.EnableCurrentDensity_im_2: currentDensity = float(obj.CurrentDensity_im_2.getValueAs("A/m^2")) self.write.bodyForce(name, "Current Density Im 2", round(currentDensity, 6)) - if not obj.CurrentDensity_im_3_Disabled: + if obj.EnableCurrentDensity_im_3: currentDensity = float(obj.CurrentDensity_im_3.getValueAs("A/m^2")) self.write.bodyForce(name, "Current Density Im 3", round(currentDensity, 6)) @@ -276,16 +276,13 @@ class MgDynwriter: self.write.handled(obj) def _outputMagnetodynamicBndConditions(self, obj, name, equation): - if hasattr(obj, "CurrentDensity_re_1"): - # output only if current density is enabled and needed - if not obj.CurrentDensity_re_1_Disabled: - currentDensity = float(obj.CurrentDensity_re_1.getValueAs("A/m^2")) - self.write.boundary(name, "Current Density 1", round(currentDensity, 6)) + if femutils.is_derived_from(obj, "Fem::ConstraintCurrentDensity") and obj.Mode == "Normal": + currentDensity = float(obj.NormalCurrentDensity_re.getValueAs("A/m^2")) + self.write.boundary(name, "Electric Current Density", round(currentDensity, 6)) # imaginaries are only needed for harmonic equation if equation.IsHarmonic: - if not obj.CurrentDensity_im_1_Disabled: - currentDensity = float(obj.CurrentDensity_im_1.getValueAs("A/m^2")) - self.write.boundary(name, "Current Density Im 1", round(currentDensity, 6)) + currentDensity = float(obj.NormalCurrentDensity_im.getValueAs("A/m^2")) + self.write.boundary(name, "Electric Current Density Im", round(currentDensity, 6)) if femutils.is_derived_from(obj, "Fem::ConstraintElectrostaticPotential"): if obj.EnableAV: diff --git a/src/Mod/Fem/femsolver/elmer/equations/staticcurrent.py b/src/Mod/Fem/femsolver/elmer/equations/staticcurrent.py new file mode 100644 index 0000000000..79b9393c10 --- /dev/null +++ b/src/Mod/Fem/femsolver/elmer/equations/staticcurrent.py @@ -0,0 +1,90 @@ +# SPDX-License-Identifier: LGPL-2.1-or-later + +# *************************************************************************** +# * Copyright (c) 2025 Mario Passaglia * +# * * +# * This file is part of FreeCAD. * +# * * +# * FreeCAD 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.1 of the * +# * License, or (at your option) any later version. * +# * * +# * FreeCAD 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 FreeCAD. If not, see * +# * . * +# * * +# *************************************************************************** + +__title__ = "FreeCAD FEM solver Elmer equation object StaticCurrent" +__author__ = "Mario Passaglia" +__url__ = "https://www.freecad.org" + +## \addtogroup FEM +# @{ + +from femtools import femutils +from ... import equationbase +from . import linear + + +def create(doc, name="StaticCurrent"): + return femutils.createObject(doc, name, Proxy, ViewProxy) + + +class Proxy(linear.Proxy, equationbase.StaticCurrentProxy): + + Type = "Fem::EquationElmerStaticCurrent" + + def __init__(self, obj): + super().__init__(obj) + + obj.addProperty("App::PropertyBool", "CalculateVolumeCurrent", "StaticCurrent", "") + obj.CalculateVolumeCurrent = True + obj.addProperty("App::PropertyBool", "CalculateJouleHeating", "StaticCurrent", "") + obj.addProperty( + "App::PropertyBool", + "ConstantWeights", + "StaticCurrent", + "Used to turn constant weighting on for the results", + ) + obj.addProperty( + "App::PropertyBool", + "CalculateNodalHeating", + "StaticCurrent", + "Calculate nodal heating that may be used to couple the heat equation optimally when using conforming finite element meshes", + ) + obj.addProperty( + "App::PropertyBool", + "HeatSource", + "StaticCurrent", + "Use Joule heating as a heat source in combination with heat equation", + ) + obj.addProperty( + "App::PropertyBool", + "PowerControl", + "StaticCurrent", + "Apply power control with the desired heating power", + ) + obj.addProperty( + "App::PropertyBool", + "CurrentControl", + "StaticCurrent", + "Apply current control with the desired current", + ) + obj.addProperty( + "App::PropertyElectricCurrent", "Current", "StaticCurrent", "Current control value" + ) + obj.addProperty("App::PropertyPower", "Power", "StaticCurrent", "Power control value") + + +class ViewProxy(linear.ViewProxy, equationbase.StaticCurrentViewProxy): + pass + + +## @} diff --git a/src/Mod/Fem/femsolver/elmer/equations/staticcurrent_writer.py b/src/Mod/Fem/femsolver/elmer/equations/staticcurrent_writer.py new file mode 100644 index 0000000000..edb35d1fbb --- /dev/null +++ b/src/Mod/Fem/femsolver/elmer/equations/staticcurrent_writer.py @@ -0,0 +1,114 @@ +# SPDX-License-Identifier: LGPL-2.1-or-later + +# *************************************************************************** +# * Copyright (c) 2025 Mario Passaglia * +# * * +# * This file is part of FreeCAD. * +# * * +# * FreeCAD 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.1 of the * +# * License, or (at your option) any later version. * +# * * +# * FreeCAD 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 FreeCAD. If not, see * +# * . * +# * * +# *************************************************************************** + +__title__ = "FreeCAD FEM StaticCurrent Elmer writer" +__author__ = "Mario Passaglia" +__url__ = "https://www.freecad.org" + +## \addtogroup FEM +# @{ + +from FreeCAD import Units +from .. import sifio + + +class SCwriter: + + def __init__(self, writer, solver): + self.write = writer + self.solver = solver + + def getStaticCurrentSolver(self, equation): + # output the equation parameters + s = self.write.createLinearSolver(equation) + s["Equation"] = "Stat Current Solver" + s["Procedure"] = sifio.FileAttr("StatCurrentSolve/StatCurrentSolver") + s["Variable"] = self.write.getUniqueVarName("Potential") + s["Variable DOFs"] = 1 + s["Calculate Volume Current"] = equation.CalculateVolumeCurrent + s["Calculate Joule Heating"] = equation.CalculateJouleHeating + s["Constant Weights"] = equation.ConstantWeights + s["Calculate Nodal Heating"] = equation.CalculateNodalHeating + if equation.PowerControl: + s["Power Control"] = equation.Power.getValueAs("W").Value + if equation.CurrentControl: + s["Current Control"] = equation.Current.getValueAs("A").Value + s["Exec Solver"] = "Always" + s["Optimize Bandwidth"] = True + s["Stabilize"] = equation.Stabilize + + return s + + def handleStaticCurrentConstants(self): + pass + + def handleStaticCurrentMaterial(self, bodies): + for obj in self.write.getMember("App::MaterialObject"): + m = obj.Material + refs = obj.References[0][1] if obj.References else self.write.getAllBodies() + for name in (n for n in refs if n in bodies): + self.write.material(name, "Name", m["Name"]) + if "ElectricalConductivity" in m: + self.write.material( + name, + "Electric Conductivity", + Units.Quantity(m["ElectricalConductivity"]).getValueAs("S/m").Value, + ) + + def handleStaticCurrentBndConditions(self): + for obj in self.write.getMember("Fem::ConstraintElectrostaticPotential"): + if obj.References: + for name in obj.References[0][1]: + # output the FreeCAD label as comment + if obj.Label: + self.write.boundary(name, "! FreeCAD Name", obj.Label) + if obj.BoundaryCondition == "Dirichlet": + if obj.PotentialEnabled: + self.write.boundary(name, "Current Density BC", False) + self.write.boundary( + name, "Potential", obj.Potential.getValueAs("V").Value + ) + self.write.handled(obj) + + for obj in self.write.getMember("Fem::ConstraintCurrentDensity"): + if obj.References: + for name in obj.References[0][1]: + # output the FreeCAD label as comment + if obj.Label: + self.write.boundary(name, "! FreeCAD Name", obj.Label) + if obj.Mode == "Normal": + self.write.boundary(name, "Current Density BC", True) + self.write.boundary( + name, + "Current Density", + obj.NormalCurrentDensity_re.getValueAs("A/m^2").Value, + ) + + self.write.handled(obj) + + def handleStaticCurrentBodyForces(self, bodies, equation): + for name in bodies: + self.write.bodyForce(name, "Joule Heat", equation.HeatSource) + + +## @} diff --git a/src/Mod/Fem/femsolver/elmer/writer.py b/src/Mod/Fem/femsolver/elmer/writer.py index c08f701e35..6128280a05 100644 --- a/src/Mod/Fem/femsolver/elmer/writer.py +++ b/src/Mod/Fem/femsolver/elmer/writer.py @@ -57,6 +57,7 @@ from .equations import flux_writer from .equations import heat_writer from .equations import magnetodynamic_writer as MgDyn_writer from .equations import magnetodynamic2D_writer as MgDyn2D_writer +from .equations import staticcurrent_writer as SC_writer _STARTINFO_NAME = "ELMERSOLVER_STARTINFO" @@ -109,6 +110,7 @@ class Writer: self._handleFlux() self._handleMagnetodynamic() self._handleMagnetodynamic2D() + self._handleStaticCurrent() self._addOutputSolver() self._writeSif() @@ -614,6 +616,28 @@ class Writer: MgDyn2D.handleMagnetodynamic2DBodyForces(activeIn, equation) MgDyn2D.handleMagnetodynamic2DMaterial(activeIn) + # ------------------------------------------------------------------------------------------- + # StaticCurrent + + def _handleStaticCurrent(self): + SCW = SC_writer.SCwriter(self, self.solver) + activeIn = [] + for equation in self.solver.Group: + if femutils.is_of_type(equation, "Fem::EquationElmerStaticCurrent"): + if equation.References: + activeIn = equation.References[0][1] + else: + activeIn = self.getAllBodies() + solverSection = SCW.getStaticCurrentSolver(equation) + for body in activeIn: + self._addSolver(body, solverSection) + SCW.handleStaticCurrentBodyForces(activeIn, equation) + + if activeIn: + SCW.handleStaticCurrentConstants() + SCW.handleStaticCurrentBndConditions() + SCW.handleStaticCurrentMaterial(activeIn) + # ------------------------------------------------------------------------------------------- # Solver handling diff --git a/src/Mod/Fem/femsolver/equationbase.py b/src/Mod/Fem/femsolver/equationbase.py index 478a904708..6d405b2908 100644 --- a/src/Mod/Fem/femsolver/equationbase.py +++ b/src/Mod/Fem/femsolver/equationbase.py @@ -157,4 +157,14 @@ class Magnetodynamic2DViewProxy(BaseViewProxy): return ":/icons/FEM_EquationMagnetodynamic2D.svg" +class StaticCurrentProxy(BaseProxy): + pass + + +class StaticCurrentViewProxy(BaseViewProxy): + + def getIcon(self): + return ":/icons/FEM_EquationStaticCurrent.svg" + + ## @} diff --git a/src/Mod/Fem/femtaskpanels/task_constraint_currentdensity.py b/src/Mod/Fem/femtaskpanels/task_constraint_currentdensity.py index 8145263ebb..fcc2a761f0 100644 --- a/src/Mod/Fem/femtaskpanels/task_constraint_currentdensity.py +++ b/src/Mod/Fem/femtaskpanels/task_constraint_currentdensity.py @@ -1,5 +1,6 @@ # *************************************************************************** # * Copyright (c) 2023 Uwe Stöhr * +# * Copyright (c) 2025 Mario Passaglia * # * * # * This file is part of the FreeCAD CAx development system. * # * * @@ -22,13 +23,15 @@ # *************************************************************************** __title__ = "FreeCAD FEM constraint current density task panel for the document object" -__author__ = "Uwe Stöhr" +__author__ = "Uwe Stöhr, Mario Passaglia" __url__ = "https://www.freecad.org" ## @package task_constraint_currentdensity # \ingroup FEM # \brief task panel for constraint current density object +from PySide import QtCore + import FreeCAD import FreeCADGui @@ -43,10 +46,9 @@ class _TaskPanel(base_femtaskpanel._BaseTaskPanel): def __init__(self, obj): super().__init__(obj) - self._paramWidget = FreeCADGui.PySideUic.loadUi( + self.parameter_widget = FreeCADGui.PySideUic.loadUi( FreeCAD.getHomePath() + "Mod/Fem/Resources/ui/CurrentDensity.ui" ) - self._initParamWidget() # geometry selection widget # start with Solid in list! @@ -55,7 +57,7 @@ class _TaskPanel(base_femtaskpanel._BaseTaskPanel): ) # form made from param and selection widget - self.form = [self._paramWidget, self._selectionWidget] + self.form = [self.parameter_widget, self._selectionWidget] analysis = obj.getParentGroup() self._mesh = None @@ -67,6 +69,69 @@ class _TaskPanel(base_femtaskpanel._BaseTaskPanel): self._partVisible = None self._meshVisible = None + QtCore.QObject.connect( + self.parameter_widget.cb_mode, + QtCore.SIGNAL("currentIndexChanged(int)"), + self.mode_changed, + ) + QtCore.QObject.connect( + self.parameter_widget.ckb_current_density_1, + QtCore.SIGNAL("toggled(bool)"), + self.current_density_1_enabled_changed, + ) + QtCore.QObject.connect( + self.parameter_widget.qsb_current_density_re_1, + QtCore.SIGNAL("valueChanged(Base::Quantity)"), + self.current_density_re_1_changed, + ) + QtCore.QObject.connect( + self.parameter_widget.ckb_current_density_2, + QtCore.SIGNAL("toggled(bool)"), + self.current_density_2_enabled_changed, + ) + QtCore.QObject.connect( + self.parameter_widget.qsb_current_density_re_2, + QtCore.SIGNAL("valueChanged(Base::Quantity)"), + self.current_density_re_2_changed, + ) + QtCore.QObject.connect( + self.parameter_widget.ckb_current_density_3, + QtCore.SIGNAL("toggled(bool)"), + self.current_density_3_enabled_changed, + ) + QtCore.QObject.connect( + self.parameter_widget.qsb_current_density_re_3, + QtCore.SIGNAL("valueChanged(Base::Quantity)"), + self.current_density_re_3_changed, + ) + QtCore.QObject.connect( + self.parameter_widget.qsb_current_density_im_1, + QtCore.SIGNAL("valueChanged(Base::Quantity)"), + self.current_density_im_1_changed, + ) + QtCore.QObject.connect( + self.parameter_widget.qsb_current_density_im_2, + QtCore.SIGNAL("valueChanged(Base::Quantity)"), + self.current_density_im_2_changed, + ) + QtCore.QObject.connect( + self.parameter_widget.qsb_current_density_im_3, + QtCore.SIGNAL("valueChanged(Base::Quantity)"), + self.current_density_im_3_changed, + ) + QtCore.QObject.connect( + self.parameter_widget.qsb_normal_current_density_re, + QtCore.SIGNAL("valueChanged(Base::Quantity)"), + self.normal_current_density_re_changed, + ) + QtCore.QObject.connect( + self.parameter_widget.qsb_normal_current_density_im, + QtCore.SIGNAL("valueChanged(Base::Quantity)"), + self.normal_current_density_im_changed, + ) + + self.init_parameter_widget() + def open(self): if self._mesh is not None and self._part is not None: self._meshVisible = self._mesh.ViewObject.isVisible() @@ -82,7 +147,7 @@ class _TaskPanel(base_femtaskpanel._BaseTaskPanel): def accept(self): if self.obj.References != self._selectionWidget.references: self.obj.References = self._selectionWidget.references - self._applyWidgetChanges() + self._set_params() self._selectionWidget.finish_selection() self._restoreVisibility() return super().accept() @@ -98,81 +163,158 @@ class _TaskPanel(base_femtaskpanel._BaseTaskPanel): else: self._part.ViewObject.hide() - def _initParamWidget(self): - self._paramWidget.realXQSB.setProperty("value", self.obj.CurrentDensity_re_1) - FreeCADGui.ExpressionBinding(self._paramWidget.realXQSB).bind( + def _get_params(self): + self.mode = self.obj.Mode + + self.current_density_re_1 = self.obj.CurrentDensity_re_1 + self.current_density_re_2 = self.obj.CurrentDensity_re_2 + self.current_density_re_3 = self.obj.CurrentDensity_re_3 + self.current_density_im_1 = self.obj.CurrentDensity_im_1 + self.current_density_im_2 = self.obj.CurrentDensity_im_2 + self.current_density_im_3 = self.obj.CurrentDensity_im_3 + + self.current_density_1_enabled = self.obj.EnableCurrentDensity_1 + self.current_density_2_enabled = self.obj.EnableCurrentDensity_2 + self.current_density_3_enabled = self.obj.EnableCurrentDensity_3 + + self.normal_current_density_re = self.obj.NormalCurrentDensity_re + self.normal_current_density_im = self.obj.NormalCurrentDensity_im + + def _set_params(self): + self.obj.Mode = self.mode + + self.obj.CurrentDensity_re_1 = self.current_density_re_1 + self.obj.CurrentDensity_re_2 = self.current_density_re_2 + self.obj.CurrentDensity_re_3 = self.current_density_re_3 + self.obj.CurrentDensity_im_1 = self.current_density_im_1 + self.obj.CurrentDensity_im_2 = self.current_density_im_2 + self.obj.CurrentDensity_im_3 = self.current_density_im_3 + + self.obj.EnableCurrentDensity_1 = self.current_density_1_enabled + self.obj.EnableCurrentDensity_2 = self.current_density_2_enabled + self.obj.EnableCurrentDensity_3 = self.current_density_3_enabled + + self.obj.NormalCurrentDensity_re = self.normal_current_density_re + self.obj.NormalCurrentDensity_im = self.normal_current_density_im + + def init_parameter_widget(self): + self._get_params() + + # custom current density + self.parameter_widget.qsb_current_density_re_1.setProperty( + "value", self.current_density_re_1 + ) + self.parameter_widget.qsb_current_density_re_1.setEnabled(self.current_density_1_enabled) + FreeCADGui.ExpressionBinding(self.parameter_widget.qsb_current_density_re_1).bind( self.obj, "CurrentDensity_re_1" ) - self._paramWidget.realYQSB.setProperty("value", self.obj.CurrentDensity_re_2) - FreeCADGui.ExpressionBinding(self._paramWidget.realYQSB).bind( + + self.parameter_widget.qsb_current_density_re_2.setProperty( + "value", self.current_density_re_2 + ) + self.parameter_widget.qsb_current_density_re_2.setEnabled(self.current_density_2_enabled) + FreeCADGui.ExpressionBinding(self.parameter_widget.qsb_current_density_re_2).bind( self.obj, "CurrentDensity_re_2" ) - self._paramWidget.realZQSB.setProperty("value", self.obj.CurrentDensity_re_3) - FreeCADGui.ExpressionBinding(self._paramWidget.realZQSB).bind( + + self.parameter_widget.qsb_current_density_re_3.setProperty( + "value", self.current_density_re_3 + ) + self.parameter_widget.qsb_current_density_re_3.setEnabled(self.current_density_3_enabled) + FreeCADGui.ExpressionBinding(self.parameter_widget.qsb_current_density_re_3).bind( self.obj, "CurrentDensity_re_3" ) - self._paramWidget.imagXQSB.setProperty("value", self.obj.CurrentDensity_im_1) - FreeCADGui.ExpressionBinding(self._paramWidget.imagXQSB).bind( + + self.parameter_widget.qsb_current_density_im_1.setProperty( + "value", self.current_density_im_1 + ) + self.parameter_widget.qsb_current_density_im_1.setEnabled(self.current_density_1_enabled) + FreeCADGui.ExpressionBinding(self.parameter_widget.qsb_current_density_im_1).bind( self.obj, "CurrentDensity_im_1" ) - self._paramWidget.imagYQSB.setProperty("value", self.obj.CurrentDensity_im_2) - FreeCADGui.ExpressionBinding(self._paramWidget.imagYQSB).bind( + + self.parameter_widget.qsb_current_density_im_2.setProperty( + "value", self.current_density_im_2 + ) + self.parameter_widget.qsb_current_density_im_2.setEnabled(self.current_density_2_enabled) + FreeCADGui.ExpressionBinding(self.parameter_widget.qsb_current_density_im_2).bind( self.obj, "CurrentDensity_im_2" ) - self._paramWidget.imagZQSB.setProperty("value", self.obj.CurrentDensity_im_3) - FreeCADGui.ExpressionBinding(self._paramWidget.imagZQSB).bind( + + self.parameter_widget.qsb_current_density_im_3.setProperty( + "value", self.current_density_im_3 + ) + self.parameter_widget.qsb_current_density_im_3.setEnabled(self.current_density_3_enabled) + FreeCADGui.ExpressionBinding(self.parameter_widget.qsb_current_density_im_3).bind( self.obj, "CurrentDensity_im_3" ) - self._paramWidget.reXunspecBox.setChecked(self.obj.CurrentDensity_re_1_Disabled) - self._paramWidget.reYunspecBox.setChecked(self.obj.CurrentDensity_re_2_Disabled) - self._paramWidget.reZunspecBox.setChecked(self.obj.CurrentDensity_re_3_Disabled) - self._paramWidget.imXunspecBox.setChecked(self.obj.CurrentDensity_im_1_Disabled) - self._paramWidget.imYunspecBox.setChecked(self.obj.CurrentDensity_im_2_Disabled) - self._paramWidget.imZunspecBox.setChecked(self.obj.CurrentDensity_im_3_Disabled) + self.parameter_widget.ckb_current_density_1.setChecked(self.current_density_1_enabled) + self.parameter_widget.ckb_current_density_2.setChecked(self.current_density_2_enabled) + self.parameter_widget.ckb_current_density_3.setChecked(self.current_density_3_enabled) - def _applyCurrentDensityChanges(self, enabledBox, currentDensityQSB): - enabled = enabledBox.isChecked() - currentdensity = None - try: - currentdensity = currentDensityQSB.property("value") - except ValueError: - FreeCAD.Console.PrintMessage( - "Wrong input. Not recognised input: '{}' " - "Current density has not been set.\n".format(currentDensityQSB.text()) - ) - currentdensity = "0.0 A/m^2" - return enabled, currentdensity + self.parameter_widget.qsb_normal_current_density_re.setProperty( + "value", self.normal_current_density_re + ) + FreeCADGui.ExpressionBinding(self.parameter_widget.qsb_normal_current_density_re).bind( + self.obj, "NormalCurrentDensity_re" + ) + self.parameter_widget.qsb_normal_current_density_im.setProperty( + "value", self.normal_current_density_im + ) + FreeCADGui.ExpressionBinding(self.parameter_widget.qsb_normal_current_density_im).bind( + self.obj, "NormalCurrentDensity_im" + ) - def _applyWidgetChanges(self): - # apply the current densities and their enabled state - self.obj.CurrentDensity_re_1_Disabled, self.obj.CurrentDensity_re_1 = ( - self._applyCurrentDensityChanges( - self._paramWidget.reXunspecBox, self._paramWidget.realXQSB - ) - ) - self.obj.CurrentDensity_re_2_Disabled, self.obj.CurrentDensity_re_2 = ( - self._applyCurrentDensityChanges( - self._paramWidget.reYunspecBox, self._paramWidget.realYQSB - ) - ) - self.obj.CurrentDensity_re_3_Disabled, self.obj.CurrentDensity_re_3 = ( - self._applyCurrentDensityChanges( - self._paramWidget.reZunspecBox, self._paramWidget.realZQSB - ) - ) - self.obj.CurrentDensity_im_1_Disabled, self.obj.CurrentDensity_im_1 = ( - self._applyCurrentDensityChanges( - self._paramWidget.imXunspecBox, self._paramWidget.imagXQSB - ) - ) - self.obj.CurrentDensity_im_2_Disabled, self.obj.CurrentDensity_im_2 = ( - self._applyCurrentDensityChanges( - self._paramWidget.imYunspecBox, self._paramWidget.imagYQSB - ) - ) - self.obj.CurrentDensity_im_3_Disabled, self.obj.CurrentDensity_im_3 = ( - self._applyCurrentDensityChanges( - self._paramWidget.imZunspecBox, self._paramWidget.imagZQSB - ) - ) + self.mode_enum = self.obj.getEnumerationsOfProperty("Mode") + index = self.mode_enum.index(self.mode) + self.parameter_widget.cb_mode.addItems(self.mode_enum) + self.parameter_widget.cb_mode.setCurrentIndex(index) + + def current_density_1_enabled_changed(self, value): + self.current_density_1_enabled = value + self.parameter_widget.qsb_current_density_re_1.setEnabled(value) + self.parameter_widget.qsb_current_density_im_1.setEnabled(value) + + def current_density_2_enabled_changed(self, value): + self.current_density_2_enabled = value + self.parameter_widget.qsb_current_density_re_2.setEnabled(value) + self.parameter_widget.qsb_current_density_im_2.setEnabled(value) + + def current_density_3_enabled_changed(self, value): + self.current_density_3_enabled = value + self.parameter_widget.qsb_current_density_re_3.setEnabled(value) + self.parameter_widget.qsb_current_density_im_3.setEnabled(value) + + def current_density_re_1_changed(self, value): + self.current_density_re_1 = value + + def current_density_re_2_changed(self, value): + self.current_density_re_2 = value + + def current_density_re_3_changed(self, value): + self.current_density_re_3 = value + + def current_density_im_1_changed(self, value): + self.current_density_im_1 = value + + def current_density_im_2_changed(self, value): + self.current_density_im_2 = value + + def current_density_im_3_changed(self, value): + self.current_density_im_3 = value + + def normal_current_density_re_changed(self, value): + self.normal_current_density_re = value + + def normal_current_density_im_changed(self, value): + self.normal_current_density_im = value + + def mode_changed(self, index): + self.mode = self.mode_enum[index] + if self.mode == "Custom": + self.parameter_widget.gb_custom.setEnabled(True) + self.parameter_widget.gb_normal.setEnabled(False) + elif self.mode == "Normal": + self.parameter_widget.gb_custom.setEnabled(False) + self.parameter_widget.gb_normal.setEnabled(True) diff --git a/src/Mod/Fem/femtest/app/test_object.py b/src/Mod/Fem/femtest/app/test_object.py index ce4b47e9b0..44faa5125c 100644 --- a/src/Mod/Fem/femtest/app/test_object.py +++ b/src/Mod/Fem/femtest/app/test_object.py @@ -76,14 +76,14 @@ class TestObjectCreate(unittest.TestCase): # thus they are not added to the analysis group ATM # https://forum.freecad.org/viewtopic.php?t=25283 # thus they should not be counted - # solver children: equations --> 9 + # solver children: equations --> 10 # gmsh mesh children: group, region, boundary layer --> 3 # result children: mesh result --> 1 # post pipeline children: region, scalar, cut, wrap --> 5 # analysis itself is not in analysis group --> 1 - # thus: -19 + # thus: -20 - self.assertEqual(len(doc.Analysis.Group), count_defmake - 19) + self.assertEqual(len(doc.Analysis.Group), count_defmake - 20) self.assertEqual(len(doc.Objects), count_defmake) fcc_print( @@ -287,6 +287,10 @@ class TestObjectType(unittest.TestCase): "Fem::EquationElmerMagnetodynamic", type_of_obj(ObjectsFem.makeEquationMagnetodynamic(doc, solverelmer)), ) + self.assertEqual( + "Fem::EquationElmerStaticCurrent", + type_of_obj(ObjectsFem.makeEquationStaticCurrent(doc, solverelmer)), + ) fcc_print( "doc objects count: {}, method: {}".format( @@ -468,6 +472,12 @@ class TestObjectType(unittest.TestCase): "Fem::EquationElmerMagnetodynamic", ) ) + self.assertTrue( + is_of_type( + ObjectsFem.makeEquationStaticCurrent(doc, solverelmer), + "Fem::EquationElmerStaticCurrent", + ) + ) fcc_print( "doc objects count: {}, method: {}".format( @@ -859,6 +869,12 @@ class TestObjectType(unittest.TestCase): is_derived_from(equation_magnetodynamic, "Fem::EquationElmerMagnetodynamic") ) + # EquationElmerStaticCurrent + equation_staticcurrent = ObjectsFem.makeEquationStaticCurrent(doc, solver_elmer) + self.assertTrue(is_derived_from(equation_staticcurrent, "App::DocumentObject")) + self.assertTrue(is_derived_from(equation_staticcurrent, "App::FeaturePython")) + self.assertTrue(is_derived_from(equation_staticcurrent, "Fem::EquationElmerStaticCurrent")) + fcc_print( "doc objects count: {}, method: {}".format( len(doc.Objects), sys._getframe().f_code.co_name @@ -1035,6 +1051,11 @@ class TestObjectType(unittest.TestCase): "App::FeaturePython" ) ) + self.assertTrue( + ObjectsFem.makeEquationStaticCurrent(doc, solverelmer).isDerivedFrom( + "App::FeaturePython" + ) + ) fcc_print( "doc objects count: {}, method: {}".format( @@ -1121,6 +1142,7 @@ def create_all_fem_objects_doc(doc): ObjectsFem.makeEquationHeat(doc, sol) ObjectsFem.makeEquationMagnetodynamic2D(doc, sol) ObjectsFem.makeEquationMagnetodynamic(doc, sol) + ObjectsFem.makeEquationStaticCurrent(doc, sol) doc.recompute() diff --git a/src/Mod/Fem/femviewprovider/view_constraint_currentdensity.py b/src/Mod/Fem/femviewprovider/view_constraint_currentdensity.py index f747fa0ee9..e85602dd39 100644 --- a/src/Mod/Fem/femviewprovider/view_constraint_currentdensity.py +++ b/src/Mod/Fem/femviewprovider/view_constraint_currentdensity.py @@ -29,13 +29,35 @@ __url__ = "https://www.freecad.org" # \ingroup FEM # \brief view provider for the constraint current density object +from pivy import coin + from femtaskpanels import task_constraint_currentdensity from . import view_base_femconstraint class VPConstraintCurrentDensity(view_base_femconstraint.VPBaseFemConstraint): + def __init__(self, vobj): + super().__init__(vobj) + mat = vobj.ShapeAppearance[0] + mat.DiffuseColor = (0.71, 0.40, 0.11, 0.0) + vobj.ShapeAppearance = mat + def setEdit(self, vobj, mode=0): return view_base_femconstraint.VPBaseFemConstraint.setEdit( self, vobj, mode, task_constraint_currentdensity._TaskPanel ) + + def attach(self, vobj): + super().attach(vobj) + vobj.loadSymbol(self.resource_symbol_dir + "ConstraintCurrentDensity.iv") + + def updateData(self, obj, prop): + if prop == "Mode": + symb = obj.ViewObject.SymbolNode.getChild(0) + if obj.Mode == "Normal": + obj.ViewObject.RotateSymbol = True + symb.whichChild.setValue(0) + elif obj.Mode == "Custom": + obj.ViewObject.RotateSymbol = False + symb.whichChild.setValue(-1) diff --git a/src/Mod/Import/App/AppImportPy.cpp b/src/Mod/Import/App/AppImportPy.cpp index ce5919f4c7..56ef9a84ab 100644 --- a/src/Mod/Import/App/AppImportPy.cpp +++ b/src/Mod/Import/App/AppImportPy.cpp @@ -281,7 +281,7 @@ private: try { Py::Sequence list(object); std::vector objs; - std::map> partColor; + std::map> partColor; for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { PyObject* item = (*it).ptr(); if (PyObject_TypeCheck(item, &(App::DocumentObjectPy::Type))) { @@ -310,7 +310,7 @@ private: hApp->NewDocument(TCollection_ExtendedString("MDTV-CAF"), hDoc); auto getShapeColors = [partColor](App::DocumentObject* obj, const char* subname) { - std::map cols; + std::map cols; auto it = partColor.find(dynamic_cast(obj)); if (it != partColor.end() && boost::starts_with(subname, "Face")) { const auto& colors = it->second; diff --git a/src/Mod/Import/App/CMakeLists.txt b/src/Mod/Import/App/CMakeLists.txt index 305061094a..4dfae3961d 100644 --- a/src/Mod/Import/App/CMakeLists.txt +++ b/src/Mod/Import/App/CMakeLists.txt @@ -2,6 +2,10 @@ include_directories( ${CMAKE_BINARY_DIR} ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_CURRENT_SOURCE_DIR} +) + +include_directories( + SYSTEM ${Boost_INCLUDE_DIRS} ${OCC_INCLUDE_DIR} ${ZLIB_INCLUDE_DIR} diff --git a/src/Mod/Import/App/ExportOCAF.cpp b/src/Mod/Import/App/ExportOCAF.cpp index 392ff68619..1f5b8c4025 100644 --- a/src/Mod/Import/App/ExportOCAF.cpp +++ b/src/Mod/Import/App/ExportOCAF.cpp @@ -133,7 +133,7 @@ void ExportOCAF::exportObjects(std::vector& objs) std::vector part_id; getFreeLabels(hierarchical_label, FreeLabels, part_id); - std::vector> Colors; + std::vector> Colors; getPartColors(hierarchical_part, FreeLabels, part_id, Colors); reallocateFreeShape(hierarchical_part, FreeLabels, part_id, Colors); @@ -179,7 +179,7 @@ int ExportOCAF::exportObject(App::DocumentObject* obj, if (obj->isDerivedFrom()) { Part::Feature* part = static_cast(obj); - std::vector colors; + std::vector colors; findColors(part, colors); return_label = @@ -221,7 +221,7 @@ void ExportOCAF::createNode(App::Part* part, } int ExportOCAF::saveShape(Part::Feature* part, - const std::vector& colors, + const std::vector& colors, std::vector& hierarchical_label, std::vector& hierarchical_loc, std::vector& hierarchical_part) @@ -301,7 +301,7 @@ int ExportOCAF::saveShape(Part::Feature* part, } if (!faceLabel.IsNull()) { - const App::Color& color = colors[index - 1]; + const Base::Color& color = colors[index - 1]; col = Tools::convertColor(color); aColorTool->SetColor(faceLabel, col, XCAFDoc_ColorSurf); } @@ -310,7 +310,7 @@ int ExportOCAF::saveShape(Part::Feature* part, } } else if (!colors.empty()) { - App::Color color = colors.front(); + Base::Color color = colors.front(); col = Tools::convertColor(color); aColorTool->SetColor(shapeLabel, col, XCAFDoc_ColorGen); } @@ -347,12 +347,12 @@ void ExportOCAF::getFreeLabels(std::vector& hierarchical_label, void ExportOCAF::getPartColors(std::vector hierarchical_part, std::vector FreeLabels, std::vector part_id, - std::vector>& Colors) const + std::vector>& Colors) const { // I am seeking for the colors of each parts std::size_t n = FreeLabels.size(); for (std::size_t i = 0; i < n; i++) { - std::vector colors; + std::vector colors; Part::Feature* part = static_cast(hierarchical_part.at(part_id.at(i))); findColors(part, colors); Colors.push_back(colors); @@ -362,7 +362,7 @@ void ExportOCAF::getPartColors(std::vector hierarchical_pa void ExportOCAF::reallocateFreeShape(std::vector hierarchical_part, std::vector FreeLabels, std::vector part_id, - std::vector>& Colors) + std::vector>& Colors) { std::size_t n = FreeLabels.size(); for (std::size_t i = 0; i < n; i++) { @@ -372,7 +372,7 @@ void ExportOCAF::reallocateFreeShape(std::vector hierarchi Part::Feature* part = static_cast(hierarchical_part.at(part_id.at(i))); aShapeTool->SetShape(label, part->Shape.getValue()); // Add color information - std::vector colors; + std::vector colors; colors = Colors.at(i); TopoDS_Shape baseShape = part->Shape.getValue(); @@ -409,7 +409,7 @@ void ExportOCAF::reallocateFreeShape(std::vector hierarchi } if (!faceLabel.IsNull()) { - const App::Color& color = colors[index - 1]; + const Base::Color& color = colors[index - 1]; col = Tools::convertColor(color); aColorTool->SetColor(faceLabel, col, XCAFDoc_ColorSurf); } @@ -419,7 +419,7 @@ void ExportOCAF::reallocateFreeShape(std::vector hierarchi } } else if (!colors.empty()) { - App::Color color = colors.front(); + Base::Color color = colors.front(); col = Tools::convertColor(color); aColorTool->SetColor(label, col, XCAFDoc_ColorGen); } @@ -463,9 +463,9 @@ ExportOCAFCmd::ExportOCAFCmd(Handle(TDocStd_Document) h, bool explicitPlacement) : ExportOCAF(h, explicitPlacement) {} -void ExportOCAFCmd::findColors(Part::Feature* part, std::vector& colors) const +void ExportOCAFCmd::findColors(Part::Feature* part, std::vector& colors) const { - std::map>::const_iterator it = partColors.find(part); + std::map>::const_iterator it = partColors.find(part); if (it != partColors.end()) { colors = it->second; } diff --git a/src/Mod/Import/App/ExportOCAF.h b/src/Mod/Import/App/ExportOCAF.h index 3542f5169f..847b437cda 100644 --- a/src/Mod/Import/App/ExportOCAF.h +++ b/src/Mod/Import/App/ExportOCAF.h @@ -65,18 +65,18 @@ public: std::vector& hierarchical_loc, std::vector& hierarchical_part); int saveShape(Part::Feature* part, - const std::vector&, + const std::vector&, std::vector& hierarchical_label, std::vector& hierarchical_loc, std::vector& hierarchical_part); void getPartColors(std::vector hierarchical_part, std::vector FreeLabels, std::vector part_id, - std::vector>& Colors) const; + std::vector>& Colors) const; void reallocateFreeShape(std::vector hierarchical_part, std::vector FreeLabels, std::vector part_id, - std::vector>& Colors); + std::vector>& Colors); void getFreeLabels(std::vector& hierarchical_label, std::vector& labels, std::vector& label_part_id); @@ -91,7 +91,7 @@ public: std::vector& hierarchical_loc); private: - virtual void findColors(Part::Feature*, std::vector&) const + virtual void findColors(Part::Feature*, std::vector&) const {} std::vector filterPart(App::Part* part) const; @@ -108,16 +108,16 @@ class ImportExport ExportOCAFCmd: public ExportOCAF { public: ExportOCAFCmd(Handle(TDocStd_Document) h, bool explicitPlacement); - void setPartColorsMap(const std::map>& colors) + void setPartColorsMap(const std::map>& colors) { partColors = colors; } private: - void findColors(Part::Feature*, std::vector&) const override; + void findColors(Part::Feature*, std::vector&) const override; private: - std::map> partColors; + std::map> partColors; }; diff --git a/src/Mod/Import/App/ExportOCAF2.cpp b/src/Mod/Import/App/ExportOCAF2.cpp index 4940ccb228..4649c6a676 100644 --- a/src/Mod/Import/App/ExportOCAF2.cpp +++ b/src/Mod/Import/App/ExportOCAF2.cpp @@ -232,7 +232,7 @@ void ExportOCAF2::setupObject(TDF_Label label, return; } - std::map> colors; + std::map> colors; static std::string marker(App::DocumentObject::hiddenMarker() + "*"); static std::array keys = {"Face*", "Edge*", marker.c_str()}; std::string childName; @@ -280,7 +280,7 @@ void ExportOCAF2::setupObject(TDF_Label label, aColorTool->SetVisibility(nodeLabel, Standard_False); continue; } - const App::Color& c = vv.second; + const Base::Color& c = vv.second; Quantity_ColorRGBA color = Tools::convertColor(c); auto colorType = vv.first[0] == 'F' ? XCAFDoc_ColorSurf : XCAFDoc_ColorCurv; if (vv.first == "Face" || vv.first == "Edge") { diff --git a/src/Mod/Import/App/ExportOCAF2.h b/src/Mod/Import/App/ExportOCAF2.h index f33308987f..e5dda265b5 100644 --- a/src/Mod/Import/App/ExportOCAF2.h +++ b/src/Mod/Import/App/ExportOCAF2.h @@ -51,7 +51,7 @@ namespace Import struct ImportExport ExportOCAFOptions { ExportOCAFOptions(); - App::Color defaultColor; + Base::Color defaultColor; bool exportHidden = true; bool keepPlacement = false; }; @@ -60,7 +60,7 @@ class ImportExport ExportOCAF2 { public: using GetShapeColorsFunc = - std::function(App::DocumentObject*, const char*)>; + std::function(App::DocumentObject*, const char*)>; explicit ExportOCAF2(Handle(TDocStd_Document) hDoc, GetShapeColorsFunc func = GetShapeColorsFunc()); diff --git a/src/Mod/Import/App/ImportOCAF.cpp b/src/Mod/Import/App/ImportOCAF.cpp index 4db7eeba24..0d155d5201 100644 --- a/src/Mod/Import/App/ImportOCAF.cpp +++ b/src/Mod/Import/App/ImportOCAF.cpp @@ -394,12 +394,12 @@ void ImportOCAF::createShape(const TopoDS_Shape& aShape, void ImportOCAF::loadColors(Part::Feature* part, const TopoDS_Shape& aShape) { Quantity_ColorRGBA aColor; - App::Color color(0.8f, 0.8f, 0.8f); + Base::Color color(0.8f, 0.8f, 0.8f); if (aColorTool->GetColor(aShape, XCAFDoc_ColorGen, aColor) || aColorTool->GetColor(aShape, XCAFDoc_ColorSurf, aColor) || aColorTool->GetColor(aShape, XCAFDoc_ColorCurv, aColor)) { color = Tools::convertColor(aColor); - std::vector colors; + std::vector colors; colors.push_back(color); applyColors(part, colors); } @@ -412,7 +412,7 @@ void ImportOCAF::loadColors(Part::Feature* part, const TopoDS_Shape& aShape) } bool found_face_color = false; - std::vector faceColors; + std::vector faceColors; faceColors.resize(faces.Extent(), color); xp.Init(aShape, TopAbs_FACE); while (xp.More()) { @@ -438,7 +438,7 @@ ImportOCAFCmd::ImportOCAFCmd(Handle(TDocStd_Document) h, App::Document* d, const : ImportOCAF(h, d, name) {} -void ImportOCAFCmd::applyColors(Part::Feature* part, const std::vector& colors) +void ImportOCAFCmd::applyColors(Part::Feature* part, const std::vector& colors) { partColors[part] = colors; } @@ -503,7 +503,7 @@ void ImportXCAF::createShape(const TopoDS_Shape& shape, bool perface, bool setna std::map::const_iterator jt; jt = myColorMap.find(Part::ShapeMapHasher {}(shape)); - App::Color partColor(0.8f, 0.8f, 0.8f); + Base::Color partColor(0.8f, 0.8f, 0.8f); // set label name if defined @@ -524,7 +524,7 @@ void ImportXCAF::createShape(const TopoDS_Shape& shape, bool perface, bool setna xp.Next(); } - std::vector faceColors; + std::vector faceColors; faceColors.resize(faces.Extent(), partColor); xp.Init(shape, TopAbs_FACE); while (xp.More()) { diff --git a/src/Mod/Import/App/ImportOCAF.h b/src/Mod/Import/App/ImportOCAF.h index f933d17716..18ae55312a 100644 --- a/src/Mod/Import/App/ImportOCAF.h +++ b/src/Mod/Import/App/ImportOCAF.h @@ -81,7 +81,7 @@ private: const std::string&, std::vector&); void loadColors(Part::Feature* part, const TopoDS_Shape& aShape); - virtual void applyColors(Part::Feature*, const std::vector&) + virtual void applyColors(Part::Feature*, const std::vector&) {} static void tryPlacementFromLoc(App::GeoFeature*, const TopLoc_Location&); static void tryPlacementFromMatrix(App::GeoFeature*, const Base::Matrix4D&); @@ -100,16 +100,16 @@ class ImportExport ImportOCAFCmd: public ImportOCAF { public: ImportOCAFCmd(Handle(TDocStd_Document) h, App::Document* d, const std::string& name); - std::map> getPartColorsMap() const + std::map> getPartColorsMap() const { return partColors; } private: - void applyColors(Part::Feature* part, const std::vector& colors) override; + void applyColors(Part::Feature* part, const std::vector& colors) override; private: - std::map> partColors; + std::map> partColors; }; class ImportXCAF @@ -122,7 +122,7 @@ public: private: void createShape(const TopoDS_Shape& shape, bool perface = false, bool setname = false) const; void loadShapes(const TDF_Label& label); - virtual void applyColors(Part::Feature*, const std::vector&) + virtual void applyColors(Part::Feature*, const std::vector&) {} private: diff --git a/src/Mod/Import/App/ImportOCAF2.cpp b/src/Mod/Import/App/ImportOCAF2.cpp index feb927adfa..c0d7ec1fb1 100644 --- a/src/Mod/Import/App/ImportOCAF2.cpp +++ b/src/Mod/Import/App/ImportOCAF2.cpp @@ -204,7 +204,7 @@ bool ImportOCAF2::getColor(const TopoDS_Shape& shape, Info& info, bool check, bo bool ret = false; Quantity_ColorRGBA aColor; if (aColorTool->GetColor(shape, XCAFDoc_ColorSurf, aColor)) { - App::Color c = Tools::convertColor(aColor); + Base::Color c = Tools::convertColor(aColor); if (!check || info.faceColor != c) { info.faceColor = c; info.hasFaceColor = true; @@ -212,7 +212,7 @@ bool ImportOCAF2::getColor(const TopoDS_Shape& shape, Info& info, bool check, bo } } if (!noDefault && !info.hasFaceColor && aColorTool->GetColor(shape, XCAFDoc_ColorGen, aColor)) { - App::Color c = Tools::convertColor(aColor); + Base::Color c = Tools::convertColor(aColor); if (!check || info.faceColor != c) { info.faceColor = c; info.hasFaceColor = true; @@ -220,7 +220,7 @@ bool ImportOCAF2::getColor(const TopoDS_Shape& shape, Info& info, bool check, bo } } if (aColorTool->GetColor(shape, XCAFDoc_ColorCurv, aColor)) { - App::Color c = Tools::convertColor(aColor); + Base::Color c = Tools::convertColor(aColor); // Some STEP include a curve color with the same value of the face // color. And this will look weird in FC. So for shape with face // we'll ignore the curve color, if it is the same as the face color. @@ -296,8 +296,8 @@ bool ImportOCAF2::createObject(App::Document* doc, bool hasEdgeColors = false; Part::TopoShape tshape(shape); - std::vector faceColors; - std::vector edgeColors; + std::vector faceColors; + std::vector edgeColors; TDF_LabelSequence seq; if (!label.IsNull() && aShapeTool->GetSubShapes(label, seq)) { @@ -328,7 +328,7 @@ bool ImportOCAF2::createObject(App::Document* doc, } bool foundFaceColor = false, foundEdgeColor = false; - App::Color faceColor, edgeColor; + Base::Color faceColor, edgeColor; Quantity_ColorRGBA aColor; if (aColorTool->GetColor(l, XCAFDoc_ColorSurf, aColor) || aColorTool->GetColor(l, XCAFDoc_ColorGen, aColor)) { @@ -585,7 +585,7 @@ App::DocumentObject* ImportOCAF2::loadShapes() } void ImportOCAF2::getSHUOColors(TDF_Label label, - std::map& colors, + std::map& colors, bool appendFirst) { TDF_AttributeSequence seq; @@ -638,7 +638,7 @@ void ImportOCAF2::getSHUOColors(TDF_Label label, } if (!aColorTool->IsVisible(slabel)) { subname += App::DocumentObject::hiddenMarker(); - colors.emplace(subname, App::Color()); + colors.emplace(subname, Base::Color()); } else { Quantity_ColorRGBA aColor; @@ -685,7 +685,7 @@ App::DocumentObject* ImportOCAF2::loadShape(App::Document* doc, return it->second.obj; } - std::map shuoColors; + std::map shuoColors; if (!options.useLinkGroup) { getSHUOColors(label, shuoColors, false); } @@ -735,7 +735,7 @@ struct ChildInfo { std::vector plas; boost::dynamic_bitset<> vis; - std::map colors; + std::map colors; std::vector labels; TopoDS_Shape shape; }; @@ -751,7 +751,7 @@ bool ImportOCAF2::createAssembly(App::Document* _doc, std::vector children; std::map childrenMap; boost::dynamic_bitset<> visibilities; - std::map shuoColors; + std::map shuoColors; auto doc = _doc; if (newDoc) { @@ -877,7 +877,7 @@ ImportOCAFExt::ImportOCAFExt(Handle(TDocStd_Document) hStdDoc, : ImportOCAF2(hStdDoc, doc, name) {} -void ImportOCAFExt::applyFaceColors(Part::Feature* part, const std::vector& colors) +void ImportOCAFExt::applyFaceColors(Part::Feature* part, const std::vector& colors) { partColors[part] = colors; } diff --git a/src/Mod/Import/App/ImportOCAF2.h b/src/Mod/Import/App/ImportOCAF2.h index 8b79201e17..a850e3d583 100644 --- a/src/Mod/Import/App/ImportOCAF2.h +++ b/src/Mod/Import/App/ImportOCAF2.h @@ -62,8 +62,8 @@ namespace Import struct ImportExport ImportOCAFOptions { ImportOCAFOptions(); - App::Color defaultFaceColor; - App::Color defaultEdgeColor; + Base::Color defaultFaceColor; + Base::Color defaultEdgeColor; bool merge = false; bool useLinkGroup = false; bool useBaseName = true; @@ -130,8 +130,8 @@ private: std::string baseName; App::DocumentObject* obj = nullptr; App::PropertyPlacement* propPlacement = nullptr; - App::Color faceColor; - App::Color edgeColor; + Base::Color faceColor; + Base::Color edgeColor; bool hasFaceColor = false; bool hasEdgeColor = false; int free = true; @@ -162,19 +162,19 @@ private: bool getColor(const TopoDS_Shape& shape, Info& info, bool check = false, bool noDefault = false); void - getSHUOColors(TDF_Label label, std::map& colors, bool appendFirst); + getSHUOColors(TDF_Label label, std::map& colors, bool appendFirst); void setObjectName(Info& info, TDF_Label label); std::string getLabelName(TDF_Label label); App::DocumentObject* expandShape(App::Document* doc, TDF_Label label, const TopoDS_Shape& shape); - virtual void applyEdgeColors(Part::Feature*, const std::vector&) + virtual void applyEdgeColors(Part::Feature*, const std::vector&) {} - virtual void applyFaceColors(Part::Feature*, const std::vector&) + virtual void applyFaceColors(Part::Feature*, const std::vector&) {} - virtual void applyElementColors(App::DocumentObject*, const std::map&) + virtual void applyElementColors(App::DocumentObject*, const std::map&) {} - virtual void applyLinkColor(App::DocumentObject*, int /*index*/, App::Color) + virtual void applyLinkColor(App::DocumentObject*, int /*index*/, Base::Color) {} private: @@ -187,7 +187,7 @@ private: {} private: - void applyColors(Part::Feature* part, const std::vector& colors) override + void applyColors(Part::Feature* part, const std::vector& colors) override { myParent.applyFaceColors(part, colors); } @@ -217,16 +217,16 @@ class ImportExport ImportOCAFExt: public ImportOCAF2 public: ImportOCAFExt(Handle(TDocStd_Document) hStdDoc, App::Document* doc, const std::string& name); - std::map> partColors; + std::map> partColors; private: - void applyFaceColors(Part::Feature* part, const std::vector& colors) override; + void applyFaceColors(Part::Feature* part, const std::vector& colors) override; }; struct ImportExport ExportOCAFOptions { ExportOCAFOptions(); - App::Color defaultColor; + Base::Color defaultColor; bool exportHidden = true; bool keepPlacement = false; }; @@ -235,7 +235,7 @@ class ImportExport ExportOCAF2 { public: using GetShapeColorsFunc = - std::function(App::DocumentObject*, const char*)>; + std::function(App::DocumentObject*, const char*)>; explicit ExportOCAF2(Handle(TDocStd_Document) h, GetShapeColorsFunc func = GetShapeColorsFunc()); diff --git a/src/Mod/Import/App/ImportOCAFAssembly.cpp b/src/Mod/Import/App/ImportOCAFAssembly.cpp index 29ecb1d54e..4d60e779aa 100644 --- a/src/Mod/Import/App/ImportOCAFAssembly.cpp +++ b/src/Mod/Import/App/ImportOCAFAssembly.cpp @@ -251,14 +251,14 @@ void ImportOCAFAssembly::createShape(const TopoDS_Shape& aShape, part->Label.setValue(name); Quantity_Color aColor; - App::Color color(0.8f, 0.8f, 0.8f); + Base::Color color(0.8f, 0.8f, 0.8f); if (aColorTool->GetColor(aShape, XCAFDoc_ColorGen, aColor) || aColorTool->GetColor(aShape, XCAFDoc_ColorSurf, aColor) || aColorTool->GetColor(aShape, XCAFDoc_ColorCurv, aColor)) { color.r = (float)aColor.Red(); color.g = (float)aColor.Green(); color.b = (float)aColor.Blue(); - std::vector colors; + std::vector colors; colors.push_back(color); applyColors(part, colors); } @@ -270,7 +270,7 @@ void ImportOCAFAssembly::createShape(const TopoDS_Shape& aShape, xp.Next(); } bool found_face_color = false; - std::vector faceColors; + std::vector faceColors; faceColors.resize(faces.Extent(), color); xp.Init(aShape, TopAbs_FACE); while (xp.More()) { diff --git a/src/Mod/Import/App/ImportOCAFAssembly.h b/src/Mod/Import/App/ImportOCAFAssembly.h index fea051f30b..ee18ab30a2 100644 --- a/src/Mod/Import/App/ImportOCAFAssembly.h +++ b/src/Mod/Import/App/ImportOCAFAssembly.h @@ -76,7 +76,7 @@ private: int dep); void createShape(const TDF_Label& label, const TopLoc_Location&, const std::string&); void createShape(const TopoDS_Shape& label, const TopLoc_Location&, const std::string&); - virtual void applyColors(Part::Feature*, const std::vector&) + virtual void applyColors(Part::Feature*, const std::vector&) {} private: diff --git a/src/Mod/Import/App/Tools.cpp b/src/Mod/Import/App/Tools.cpp index 6d2cdaed90..5fe73d32c2 100644 --- a/src/Mod/Import/App/Tools.cpp +++ b/src/Mod/Import/App/Tools.cpp @@ -46,24 +46,24 @@ FC_LOG_LEVEL_INIT("Import", true, true) using namespace Import; -App::Color Tools::convertColor(const Quantity_ColorRGBA& rgba) +Base::Color Tools::convertColor(const Quantity_ColorRGBA& rgba) { Standard_Real red, green, blue; rgba.GetRGB().Values(red, green, blue, OCC_COLOR_SPACE); - return App::Color(static_cast(red), - static_cast(green), - static_cast(blue), - static_cast(rgba.Alpha())); + return Base::Color(static_cast(red), + static_cast(green), + static_cast(blue), + static_cast(rgba.Alpha())); } -Quantity_ColorRGBA Tools::convertColor(const App::Color& col) +Quantity_ColorRGBA Tools::convertColor(const Base::Color& col) { return Quantity_ColorRGBA(Quantity_Color(col.r, col.g, col.b, OCC_COLOR_SPACE), col.a); } static inline std::ostream& operator<<(std::ostream& os, const Quantity_ColorRGBA& rgba) { - App::Color color = Tools::convertColor(rgba); + Base::Color color = Tools::convertColor(rgba); auto toHex = [](float v) { return boost::format("%02X") % static_cast(v * 255); }; diff --git a/src/Mod/Import/App/Tools.h b/src/Mod/Import/App/Tools.h index aa05e3067e..9d99cf5dae 100644 --- a/src/Mod/Import/App/Tools.h +++ b/src/Mod/Import/App/Tools.h @@ -27,7 +27,7 @@ #include #include #include -#include +#include #include @@ -60,8 +60,8 @@ struct LabelHasher struct Tools { - static App::Color convertColor(const Quantity_ColorRGBA& rgba); - static Quantity_ColorRGBA convertColor(const App::Color& col); + static Base::Color convertColor(const Quantity_ColorRGBA& rgba); + static Quantity_ColorRGBA convertColor(const Base::Color& col); static std::string labelName(TDF_Label label); static void printLabel(TDF_Label label, Handle(XCAFDoc_ShapeTool) aShapeTool, diff --git a/src/Mod/Import/App/dxf/ImpExpDxf.cpp b/src/Mod/Import/App/dxf/ImpExpDxf.cpp index c51c1b620a..13f16b3ece 100644 --- a/src/Mod/Import/App/dxf/ImpExpDxf.cpp +++ b/src/Mod/Import/App/dxf/ImpExpDxf.cpp @@ -644,7 +644,7 @@ ImpExpDxfRead::MakeLayer(const std::string& name, ColorIndex_t color, std::strin { if (m_preserveLayers) { // Hidden layers are implemented in the wrapup code after the entire file has been read. - App::Color appColor = ObjectColor(color); + Base::Color appColor = ObjectColor(color); PyObject* draftModule = nullptr; PyObject* layer = nullptr; draftModule = getDraftModule(); diff --git a/src/Mod/Import/App/dxf/dxf.cpp b/src/Mod/Import/App/dxf/dxf.cpp index 2cd1f3b24a..54b40ad234 100644 --- a/src/Mod/Import/App/dxf/dxf.cpp +++ b/src/Mod/Import/App/dxf/dxf.cpp @@ -15,7 +15,7 @@ #include "dxf.h" #include -#include +#include #include #include #include @@ -3027,13 +3027,13 @@ inline static double level(int distance, double blackLevel) // 8 and beyond yield the black level return blackLevel; } -inline static App::Color wheel(int hue, double blackLevel, double multiplier = 1.0) +inline static Base::Color wheel(int hue, double blackLevel, double multiplier = 1.0) { - return App::Color((float)(level(hue - 0, blackLevel) * multiplier), - (float)(level(hue - 8, blackLevel) * multiplier), - (float)(level(hue - 16, blackLevel) * multiplier)); + return Base::Color((float)(level(hue - 0, blackLevel) * multiplier), + (float)(level(hue - 8, blackLevel) * multiplier), + (float)(level(hue - 16, blackLevel) * multiplier)); } -App::Color CDxfRead::ObjectColor(ColorIndex_t index) +Base::Color CDxfRead::ObjectColor(ColorIndex_t index) { // TODO: If it is ColorByBlock we need to use the color of the INSERT entity. // This is tricky because a block can itself contain INSERT entities and we don't currently @@ -3050,28 +3050,28 @@ App::Color CDxfRead::ObjectColor(ColorIndex_t index) // The AA fades as AA 7E 56 45 35 which is almost the exact same percentages. // For hue, (index-10)/10 : 0 is ff0000, and each step linearly adds green until 4 is pure // yellow ffff00, then red starts to fade... until but not including 24 which is back to ff0000. - App::Color result = App::Color(); + Base::Color result = Base::Color(); if (index == 0) { // Technically, 0 is BYBLOCK and not a real color, but all that means is that an object in a // block cannot specifically ask to be black. These colors are all contrasted to the // background so there is no objective black colour, through 255 is an objective white. - result = App::Color(); + result = Base::Color(); } else if (index < 7) { result = wheel((index - 1) * 4, 0x00); } else if (index == 7) { - result = App::Color(1, 1, 1); + result = Base::Color(1, 1, 1); } else if (index == 8) { - result = App::Color(0.5, 0.5, 0.5); + result = Base::Color(0.5, 0.5, 0.5); } else if (index == 9) { - result = App::Color(0.75, 0.75, 0.75); + result = Base::Color(0.75, 0.75, 0.75); } else if (index >= 250) { auto brightness = (float)((index - 250 + (255 - index) * 0.2) / 5); - result = App::Color(brightness, brightness, brightness); + result = Base::Color(brightness, brightness, brightness); } else { static const std::array fades = {1.00F, 0.74F, 0.50F, 0.40F, 0.30F}; diff --git a/src/Mod/Import/App/dxf/dxf.h b/src/Mod/Import/App/dxf/dxf.h index 411dd62fa0..2845d57bd0 100644 --- a/src/Mod/Import/App/dxf/dxf.h +++ b/src/Mod/Import/App/dxf/dxf.h @@ -25,7 +25,7 @@ #include #include #include -#include +#include #include // For some reason Cpplint complains about some of the categories used by Clang-tidy @@ -923,7 +923,7 @@ public: { return m_entityAttributes.m_LineType[0] == 'h' || m_entityAttributes.m_LineType[0] == 'H'; } - static App::Color ObjectColor(ColorIndex_t colorIndex); // as rgba value + static Base::Color ObjectColor(ColorIndex_t colorIndex); // as rgba value #ifdef DEBUG protected: diff --git a/src/Mod/Import/Gui/AppImportGuiPy.cpp b/src/Mod/Import/Gui/AppImportGuiPy.cpp index a65e1832ef..bfa4660732 100644 --- a/src/Mod/Import/Gui/AppImportGuiPy.cpp +++ b/src/Mod/Import/Gui/AppImportGuiPy.cpp @@ -341,8 +341,8 @@ private: return Py::None(); } - static std::map getShapeColors(App::DocumentObject* obj, - const char* subname) + static std::map getShapeColors(App::DocumentObject* obj, + const char* subname) { auto vp = Gui::Application::Instance->getViewProvider(obj); if (vp) { diff --git a/src/Mod/Import/Gui/CMakeLists.txt b/src/Mod/Import/Gui/CMakeLists.txt index ceff10359e..f3bd2e0d78 100644 --- a/src/Mod/Import/Gui/CMakeLists.txt +++ b/src/Mod/Import/Gui/CMakeLists.txt @@ -1,6 +1,10 @@ include_directories( ${CMAKE_BINARY_DIR} ${CMAKE_CURRENT_BINARY_DIR} +) + +include_directories( + SYSTEM ${Boost_INCLUDE_DIRS} ${OCC_INCLUDE_DIR} ${COIN3D_INCLUDE_DIRS} diff --git a/src/Mod/Import/Gui/ExportOCAFGui.cpp b/src/Mod/Import/Gui/ExportOCAFGui.cpp index 21f27560ee..e08ecc1544 100644 --- a/src/Mod/Import/Gui/ExportOCAFGui.cpp +++ b/src/Mod/Import/Gui/ExportOCAFGui.cpp @@ -35,7 +35,7 @@ ExportOCAFGui::ExportOCAFGui(Handle(TDocStd_Document) hDoc, bool explicitPlaceme : ExportOCAF(hDoc, explicitPlacement) {} -void ExportOCAFGui::findColors(Part::Feature* part, std::vector& colors) const +void ExportOCAFGui::findColors(Part::Feature* part, std::vector& colors) const { Gui::ViewProvider* vp = Gui::Application::Instance->getViewProvider(part); if (vp && vp->isDerivedFrom()) { diff --git a/src/Mod/Import/Gui/ExportOCAFGui.h b/src/Mod/Import/Gui/ExportOCAFGui.h index 6c31b7f48d..70585b2497 100644 --- a/src/Mod/Import/Gui/ExportOCAFGui.h +++ b/src/Mod/Import/Gui/ExportOCAFGui.h @@ -33,7 +33,7 @@ class ExportOCAFGui: public Import::ExportOCAF { public: ExportOCAFGui(Handle(TDocStd_Document) hDoc, bool explicitPlacement); - void findColors(Part::Feature* part, std::vector& colors) const override; + void findColors(Part::Feature* part, std::vector& colors) const override; }; } // namespace ImportGui diff --git a/src/Mod/Import/Gui/ImportOCAFGui.cpp b/src/Mod/Import/Gui/ImportOCAFGui.cpp index 0d0f2d3f94..a5cba4c2db 100644 --- a/src/Mod/Import/Gui/ImportOCAFGui.cpp +++ b/src/Mod/Import/Gui/ImportOCAFGui.cpp @@ -38,7 +38,7 @@ ImportOCAFGui::ImportOCAFGui(Handle(TDocStd_Document) hDoc, : ImportOCAF2(hDoc, pDoc, name) {} -void ImportOCAFGui::applyFaceColors(Part::Feature* part, const std::vector& colors) +void ImportOCAFGui::applyFaceColors(Part::Feature* part, const std::vector& colors) { auto vp = dynamic_cast( Gui::Application::Instance->getViewProvider(part)); @@ -58,7 +58,7 @@ void ImportOCAFGui::applyFaceColors(Part::Feature* part, const std::vector& colors) +void ImportOCAFGui::applyEdgeColors(Part::Feature* part, const std::vector& colors) { auto vp = dynamic_cast( Gui::Application::Instance->getViewProvider(part)); @@ -73,7 +73,7 @@ void ImportOCAFGui::applyEdgeColors(Part::Feature* part, const std::vector(Gui::Application::Instance->getViewProvider(obj)); @@ -98,7 +98,7 @@ void ImportOCAFGui::applyLinkColor(App::DocumentObject* obj, int index, App::Col } void ImportOCAFGui::applyElementColors(App::DocumentObject* obj, - const std::map& colors) + const std::map& colors) { auto vp = Gui::Application::Instance->getViewProvider(obj); if (!vp) { diff --git a/src/Mod/Import/Gui/ImportOCAFGui.h b/src/Mod/Import/Gui/ImportOCAFGui.h index 1b5c7d13c1..3d9ef56966 100644 --- a/src/Mod/Import/Gui/ImportOCAFGui.h +++ b/src/Mod/Import/Gui/ImportOCAFGui.h @@ -36,11 +36,11 @@ public: ImportOCAFGui(Handle(TDocStd_Document) hDoc, App::Document* pDoc, const std::string& name); private: - void applyFaceColors(Part::Feature* part, const std::vector& colors) override; - void applyEdgeColors(Part::Feature* part, const std::vector& colors) override; - void applyLinkColor(App::DocumentObject* obj, int index, App::Color color) override; + void applyFaceColors(Part::Feature* part, const std::vector& colors) override; + void applyEdgeColors(Part::Feature* part, const std::vector& colors) override; + void applyLinkColor(App::DocumentObject* obj, int index, Base::Color color) override; void applyElementColors(App::DocumentObject* obj, - const std::map& colors) override; + const std::map& colors) override; }; } // namespace ImportGui diff --git a/src/Mod/Import/Gui/dxf/ImpExpDxfGui.cpp b/src/Mod/Import/Gui/dxf/ImpExpDxfGui.cpp index 7c705d06e7..704e1bbb3b 100644 --- a/src/Mod/Import/Gui/dxf/ImpExpDxfGui.cpp +++ b/src/Mod/Import/Gui/dxf/ImpExpDxfGui.cpp @@ -69,7 +69,7 @@ ImpExpDxfReadGui::ImpExpDxfReadGui(const std::string& filepath, App::Document* p void ImpExpDxfReadGui::ApplyGuiStyles(Part::Feature* object) const { auto view = static_cast(GuiDocument->getViewProvider(object)); - App::Color color = ObjectColor(m_entityAttributes.m_Color); + Base::Color color = ObjectColor(m_entityAttributes.m_Color); view->LineColor.setValue(color); view->PointColor.setValue(color); view->ShapeAppearance.setDiffuseColor(color); @@ -82,7 +82,7 @@ void ImpExpDxfReadGui::ApplyGuiStyles(App::FeaturePython* object) const static Base::Type PropertyColorType = App::PropertyColor::getClassTypeId(); auto view = static_cast(GuiDocument->getViewProvider(object)); - App::Color color = ObjectColor(m_entityAttributes.m_Color); + Base::Color color = ObjectColor(m_entityAttributes.m_Color); // The properties on this object depend on which Python object is wrapped around it. // For now we look for the two colors we expect in text and dimensions, and check that they diff --git a/src/Mod/Inspection/App/CMakeLists.txt b/src/Mod/Inspection/App/CMakeLists.txt index 9ead7389f3..af4e123296 100644 --- a/src/Mod/Inspection/App/CMakeLists.txt +++ b/src/Mod/Inspection/App/CMakeLists.txt @@ -2,6 +2,10 @@ include_directories( ${CMAKE_BINARY_DIR} ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_CURRENT_SOURCE_DIR} +) + +include_directories( + SYSTEM ${Boost_INCLUDE_DIRS} ${OCC_INCLUDE_DIR} ${PYCXX_INCLUDE_DIR} diff --git a/src/Mod/Inspection/Gui/CMakeLists.txt b/src/Mod/Inspection/Gui/CMakeLists.txt index 22a7341e99..428d46aa99 100644 --- a/src/Mod/Inspection/Gui/CMakeLists.txt +++ b/src/Mod/Inspection/Gui/CMakeLists.txt @@ -1,6 +1,10 @@ include_directories( ${CMAKE_SOURCE_DIR}/src ${CMAKE_CURRENT_BINARY_DIR} +) + +include_directories( + SYSTEM ${Boost_INCLUDE_DIRS} ${COIN3D_INCLUDE_DIRS} ${PYCXX_INCLUDE_DIR} diff --git a/src/Mod/Inspection/Gui/ViewProviderInspection.cpp b/src/Mod/Inspection/Gui/ViewProviderInspection.cpp index b296fd94fa..0ef43ac35f 100644 --- a/src/Mod/Inspection/Gui/ViewProviderInspection.cpp +++ b/src/Mod/Inspection/Gui/ViewProviderInspection.cpp @@ -413,7 +413,7 @@ void ViewProviderInspection::setDistances() unsigned long j = 0; for (std::vector::const_iterator jt = fValues.begin(); jt != fValues.end(); ++jt, j++) { - App::Color col = pcColorBar->getColor(*jt); + Base::Color col = pcColorBar->getColor(*jt); cols[j] = SbColor(col.r, col.g, col.b); if (pcColorBar->isVisible(*jt)) { tran[j] = 0.0f; diff --git a/src/Mod/JtReader/App/CMakeLists.txt b/src/Mod/JtReader/App/CMakeLists.txt index 11ae24d8f6..027cdefc34 100644 --- a/src/Mod/JtReader/App/CMakeLists.txt +++ b/src/Mod/JtReader/App/CMakeLists.txt @@ -4,6 +4,10 @@ set(JTREADER_TKJT_LIBRARIES CACHE FILEPATH "File path to TKJT library") include_directories( ${CMAKE_BINARY_DIR} ${CMAKE_CURRENT_BINARY_DIR} +) + +include_directories( + SYSTEM ${Boost_INCLUDE_DIRS} ${OCC_INCLUDE_DIR} ${ZLIB_INCLUDE_DIR} @@ -33,7 +37,7 @@ SET(JtReader_SRCS if (EXISTS "${JTREADER_TKJT_INCLUDE_DIRS}/JtData_Object.hxx") add_definitions(-DJTREADER_HAVE_TKJT) - include_directories(${JTREADER_TKJT_INCLUDE_DIRS}) + include_directories(SYSTEM ${JTREADER_TKJT_INCLUDE_DIRS}) list (APPEND JtReader_LIBS ${JTREADER_TKJT_LIBRARIES} ) diff --git a/src/Mod/Material/App/CMakeLists.txt b/src/Mod/Material/App/CMakeLists.txt index f4c860a4e2..51a23400a4 100644 --- a/src/Mod/Material/App/CMakeLists.txt +++ b/src/Mod/Material/App/CMakeLists.txt @@ -12,6 +12,10 @@ include_directories( ${CMAKE_SOURCE_DIR}/src ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_CURRENT_SOURCE_DIR} +) + +include_directories( + SYSTEM ${Boost_INCLUDE_DIRS} ${PYCXX_INCLUDE_DIR} ${Python3_INCLUDE_DIRS} @@ -28,6 +32,7 @@ set(Materials_LIBS ) include_directories( + SYSTEM ${QtConcurrent_INCLUDE_DIRS} ) list(APPEND Materials_LIBS diff --git a/src/Mod/Material/App/MaterialManager.cpp b/src/Mod/Material/App/MaterialManager.cpp index 30c6cf4cce..5b23f288bb 100644 --- a/src/Mod/Material/App/MaterialManager.cpp +++ b/src/Mod/Material/App/MaterialManager.cpp @@ -145,7 +145,7 @@ std::shared_ptr MaterialManager::defaultAppearance() ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); - auto getColor = [hGrp](const char* parameter, App::Color& color) { + auto getColor = [hGrp](const char* parameter, Base::Color& color) { uint32_t packed = color.getPackedRGB(); packed = hGrp->GetUnsigned(parameter, packed); color.setPackedRGB(packed); @@ -164,7 +164,7 @@ std::shared_ptr MaterialManager::defaultAppearance() float red = static_cast(intRandom(0, 255)) / 255.0F; float green = static_cast(intRandom(0, 255)) / 255.0F; float blue = static_cast(intRandom(0, 255)) / 255.0F; - mat.diffuseColor = App::Color(red, green, blue, 1.0); + mat.diffuseColor = Base::Color(red, green, blue, 1.0); } else { getColor("DefaultShapeColor", mat.diffuseColor); diff --git a/src/Mod/Material/App/Materials.cpp b/src/Mod/Material/App/Materials.cpp index 0ad893c4a4..02ba167a30 100644 --- a/src/Mod/Material/App/Materials.cpp +++ b/src/Mod/Material/App/Materials.cpp @@ -142,7 +142,7 @@ QString MaterialProperty::getYAMLString() const return _valuePtr->getYAMLString(); } -App::Color MaterialProperty::getColor() const +Base::Color MaterialProperty::getColor() const { auto colorString = getValue().toString(); std::stringstream stream(colorString.toStdString()); @@ -163,7 +163,7 @@ App::Color MaterialProperty::getColor() const stream >> alpha; } - App::Color color(red, green, blue, alpha); + Base::Color color(red, green, blue, alpha); return color; } @@ -410,7 +410,7 @@ void MaterialProperty::setURL(const QString& value) _valuePtr->setValue(QVariant(value)); } -void MaterialProperty::setColor(const App::Color& value) +void MaterialProperty::setColor(const Base::Color& value) { std::stringstream ss; ss << "(" << value.r << ", " << value.g << ", " << value.b << ", " << value.a << ")"; diff --git a/src/Mod/Material/App/Materials.h b/src/Mod/Material/App/Materials.h index 845c9e831f..e94201dd22 100644 --- a/src/Mod/Material/App/Materials.h +++ b/src/Mod/Material/App/Materials.h @@ -31,7 +31,7 @@ #include #include -#include +#include #include #include @@ -102,7 +102,7 @@ public: { return getValue().toString(); } - App::Color getColor() const; + Base::Color getColor() const; MaterialProperty& getColumn(int column); const MaterialProperty& getColumn(int column) const; @@ -129,7 +129,7 @@ public: void setQuantity(const QString& value); void setList(const QList& value); void setURL(const QString& value); - void setColor(const App::Color& value); + void setColor(const Base::Color& value); MaterialProperty& operator=(const MaterialProperty& other); friend QTextStream& operator<<(QTextStream& output, const MaterialProperty& property); diff --git a/src/Mod/Material/Gui/CMakeLists.txt b/src/Mod/Material/Gui/CMakeLists.txt index 53b8f2a23f..3da7d37435 100644 --- a/src/Mod/Material/Gui/CMakeLists.txt +++ b/src/Mod/Material/Gui/CMakeLists.txt @@ -9,6 +9,10 @@ include_directories( ${CMAKE_SOURCE_DIR}/src ${CMAKE_BINARY_DIR}/src ${CMAKE_CURRENT_BINARY_DIR} +) + +include_directories( + SYSTEM ${Boost_INCLUDE_DIRS} ${COIN3D_INCLUDE_DIRS} ${OCC_INCLUDE_DIR} @@ -26,6 +30,7 @@ set(MatGui_LIBS ) include_directories( + SYSTEM ${QtConcurrent_INCLUDE_DIRS} ) list(APPEND MatGui_LIBS diff --git a/src/Mod/Material/Gui/DlgDisplayPropertiesImp.cpp b/src/Mod/Material/Gui/DlgDisplayPropertiesImp.cpp index 3d7289d6e6..7e4a3e419b 100644 --- a/src/Mod/Material/Gui/DlgDisplayPropertiesImp.cpp +++ b/src/Mod/Material/Gui/DlgDisplayPropertiesImp.cpp @@ -64,7 +64,7 @@ public: bool hasElementColor = false; for (const auto& view : views) { if (auto* prop = dynamic_cast(view->getPropertyByName(property))) { - App::Color color = prop->getValue(); + Base::Color color = prop->getValue(); QSignalBlocker block(buttonColor); buttonColor->setColor(color.asValue()); hasElementColor = true; @@ -83,7 +83,7 @@ public: for (const auto& view : views) { if (auto* prop = dynamic_cast(view->getPropertyByName(property))) { - App::Color color = prop->getDiffuseColor(); + Base::Color color = prop->getDiffuseColor(); QSignalBlocker block(buttonColor); buttonColor->setColor(color.asValue()); hasElementColor = true; @@ -310,7 +310,7 @@ void DlgDisplayPropertiesImp::slotChangedObject(const Gui::ViewProvider& obj, } std::string prop_name = name; if (prop.is()) { - App::Color value = static_cast(prop).getValue(); + Base::Color value = static_cast(prop).getValue(); if (prop_name == "LineColor") { bool blocked = d->ui.buttonLineColor->blockSignals(true); d->ui.buttonLineColor->setColor(value.asValue()); @@ -479,7 +479,7 @@ void DlgDisplayPropertiesImp::onButtonLineColorChanged() { std::vector Provider = getSelection(); QColor s = d->ui.buttonLineColor->color(); - App::Color c {}; + Base::Color c {}; c.setValue(s); for (auto it : Provider) { if (auto* prop = dynamic_cast(it->getPropertyByName("LineColor"))) { @@ -492,7 +492,7 @@ void DlgDisplayPropertiesImp::onButtonPointColorChanged() { std::vector Provider = getSelection(); QColor s = d->ui.buttonPointColor->color(); - App::Color c {}; + Base::Color c {}; c.setValue(s); for (auto it : Provider) { if (auto* prop = dynamic_cast(it->getPropertyByName("PointColor"))) { diff --git a/src/Mod/Material/Gui/DlgInspectAppearance.cpp b/src/Mod/Material/Gui/DlgInspectAppearance.cpp index c73ac260be..25c36cfa41 100644 --- a/src/Mod/Material/Gui/DlgInspectAppearance.cpp +++ b/src/Mod/Material/Gui/DlgInspectAppearance.cpp @@ -39,7 +39,7 @@ using namespace MatGui; -ColorWidget::ColorWidget(const App::Color& color, QWidget* parent) +ColorWidget::ColorWidget(const Base::Color& color, QWidget* parent) : QWidget(parent) { _color = color.asValue(); diff --git a/src/Mod/Material/Gui/DlgInspectAppearance.h b/src/Mod/Material/Gui/DlgInspectAppearance.h index fbcdb4855c..cdd16d5add 100644 --- a/src/Mod/Material/Gui/DlgInspectAppearance.h +++ b/src/Mod/Material/Gui/DlgInspectAppearance.h @@ -46,7 +46,7 @@ class ColorWidget : public QWidget Q_OBJECT public: - explicit ColorWidget(const App::Color& color, QWidget* parent = nullptr); + explicit ColorWidget(const Base::Color& color, QWidget* parent = nullptr); ~ColorWidget() override = default; QSize sizeHint() const override { return {75,23}; } diff --git a/src/Mod/Material/Gui/MaterialTreeWidget.cpp b/src/Mod/Material/Gui/MaterialTreeWidget.cpp index 079e779e2d..872547ac2d 100644 --- a/src/Mod/Material/Gui/MaterialTreeWidget.cpp +++ b/src/Mod/Material/Gui/MaterialTreeWidget.cpp @@ -31,7 +31,7 @@ #include #include -#include +#include #include #include #include diff --git a/src/Mod/Measure/App/CMakeLists.txt b/src/Mod/Measure/App/CMakeLists.txt index b9cf00edff..88f880a98e 100644 --- a/src/Mod/Measure/App/CMakeLists.txt +++ b/src/Mod/Measure/App/CMakeLists.txt @@ -3,6 +3,10 @@ include_directories( ${CMAKE_BINARY_DIR}/src ${CMAKE_SOURCE_DIR}/src ${CMAKE_CURRENT_BINARY_DIR} +) + +include_directories( + SYSTEM ${Boost_INCLUDE_DIRS} ${OCC_INCLUDE_DIR} ${ZLIB_INCLUDE_DIR} diff --git a/src/Mod/Measure/App/Preferences.cpp b/src/Mod/Measure/App/Preferences.cpp index dbc5e23baf..17972acdd2 100644 --- a/src/Mod/Measure/App/Preferences.cpp +++ b/src/Mod/Measure/App/Preferences.cpp @@ -46,25 +46,25 @@ Base::Reference Preferences::getPreferenceGroup(const char* Name) ->GetGroup(Name); } -App::Color Preferences::defaultLineColor() +Base::Color Preferences::defaultLineColor() { - App::Color fcColor; + Base::Color fcColor; fcColor.setPackedValue( getPreferenceGroup("Appearance")->GetUnsigned("DefaultLineColor", 0x3CF00000)); return fcColor; } -App::Color Preferences::defaultTextColor() +Base::Color Preferences::defaultTextColor() { - App::Color fcColor; + Base::Color fcColor; fcColor.setPackedValue( getPreferenceGroup("Appearance")->GetUnsigned("DefaultTextColor", 0x00000000)); return fcColor; } -App::Color Preferences::defaultTextBackgroundColor() +Base::Color Preferences::defaultTextBackgroundColor() { - App::Color fcColor; + Base::Color fcColor; fcColor.setPackedValue( getPreferenceGroup("Appearance")->GetUnsigned("DefaultTextBackgroundColor", 0x3CF00000)); return fcColor; diff --git a/src/Mod/Measure/App/Preferences.h b/src/Mod/Measure/App/Preferences.h index 63333f1b6a..ec7bc785c2 100644 --- a/src/Mod/Measure/App/Preferences.h +++ b/src/Mod/Measure/App/Preferences.h @@ -44,10 +44,10 @@ class MeasureExport Preferences public: static Base::Reference getPreferenceGroup(const char* Name); - static App::Color defaultLineColor(); - static App::Color defaultTextColor(); + static Base::Color defaultLineColor(); + static Base::Color defaultTextColor(); static int defaultFontSize(); - static App::Color defaultTextBackgroundColor(); + static Base::Color defaultTextBackgroundColor(); }; diff --git a/src/Mod/Measure/Gui/CMakeLists.txt b/src/Mod/Measure/Gui/CMakeLists.txt index e42f9ca8d6..679dae4139 100644 --- a/src/Mod/Measure/Gui/CMakeLists.txt +++ b/src/Mod/Measure/Gui/CMakeLists.txt @@ -3,6 +3,10 @@ include_directories( ${CMAKE_SOURCE_DIR}/src ${CMAKE_BINARY_DIR}/src ${CMAKE_CURRENT_BINARY_DIR} +) + +include_directories( + SYSTEM ${Boost_INCLUDE_DIRS} ${COIN3D_INCLUDE_DIRS} ${OCC_INCLUDE_DIR} diff --git a/src/Mod/Measure/Gui/ViewProviderMeasureBase.cpp b/src/Mod/Measure/Gui/ViewProviderMeasureBase.cpp index fd80b17488..cf3eb9a0ec 100644 --- a/src/Mod/Measure/Gui/ViewProviderMeasureBase.cpp +++ b/src/Mod/Measure/Gui/ViewProviderMeasureBase.cpp @@ -237,16 +237,16 @@ void ViewProviderMeasureBase::finishRestoring() void ViewProviderMeasureBase::onChanged(const App::Property* prop) { if (prop == &TextColor) { - const App::Color& color = TextColor.getValue(); + const Base::Color& color = TextColor.getValue(); pLabel->textColor.setValue(color.r, color.g, color.b); updateIcon(); } else if (prop == &TextBackgroundColor) { - const App::Color& color = TextBackgroundColor.getValue(); + const Base::Color& color = TextBackgroundColor.getValue(); pLabel->backgroundColor.setValue(color.r, color.g, color.b); } else if (prop == &LineColor) { - const App::Color& color = LineColor.getValue(); + const Base::Color& color = LineColor.getValue(); pColor->rgb.setValue(color.r, color.g, color.b); } else if (prop == &FontSize) { diff --git a/src/Mod/Mesh/App/CMakeLists.txt b/src/Mod/Mesh/App/CMakeLists.txt index 49825b1e24..e50866df11 100644 --- a/src/Mod/Mesh/App/CMakeLists.txt +++ b/src/Mod/Mesh/App/CMakeLists.txt @@ -6,6 +6,10 @@ include_directories( ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_SOURCE_DIR}/src/3rdParty/libkdtree +) + +include_directories( + SYSTEM ${Boost_INCLUDE_DIRS} ${PYCXX_INCLUDE_DIR} ${Python3_INCLUDE_DIRS} @@ -22,6 +26,7 @@ set(Mesh_LIBS ) include_directories( + SYSTEM ${QtConcurrent_INCLUDE_DIRS} ) list(APPEND Mesh_LIBS diff --git a/src/Mod/Mesh/App/Core/IO/ReaderOBJ.cpp b/src/Mod/Mesh/App/Core/IO/ReaderOBJ.cpp index ad7e9f9fa3..84c9606ed3 100644 --- a/src/Mod/Mesh/App/Core/IO/ReaderOBJ.cpp +++ b/src/Mod/Mesh/App/Core/IO/ReaderOBJ.cpp @@ -109,7 +109,7 @@ bool ReaderOBJ::Load(std::istream& str) float b = std::min(std::atof(what[12].first), 255) / 255.0F; meshPoints.push_back(MeshPoint(Base::Vector3f(fX, fY, fZ))); - App::Color c(r, g, b); + Base::Color c(r, g, b); unsigned long prop = static_cast(c.getPackedValue()); meshPoints.back().SetProperty(prop); rgb_value = MeshIO::PER_VERTEX; @@ -123,7 +123,7 @@ bool ReaderOBJ::Load(std::istream& str) float b = static_cast(std::atof(what[16].first)); meshPoints.push_back(MeshPoint(Base::Vector3f(fX, fY, fZ))); - App::Color c(r, g, b); + Base::Color c(r, g, b); unsigned long prop = static_cast(c.getPackedValue()); meshPoints.back().SetProperty(prop); rgb_value = MeshIO::PER_VERTEX; @@ -213,7 +213,7 @@ bool ReaderOBJ::Load(std::istream& str) for (const auto& it : meshPoints) { unsigned long prop = it._ulProp; - App::Color c; + Base::Color c; c.setPackedValue(static_cast(prop)); _material->diffuseColor.push_back(c); } @@ -224,7 +224,7 @@ bool ReaderOBJ::Load(std::istream& str) // calling instance but the color list is pre-filled with a default value if (_material) { _material->binding = MeshIO::PER_FACE; - _material->diffuseColor.resize(meshFacets.size(), App::Color(0.8F, 0.8F, 0.8F)); + _material->diffuseColor.resize(meshFacets.size(), Base::Color(0.8F, 0.8F, 0.8F)); } } @@ -259,27 +259,27 @@ bool ReaderOBJ::LoadMaterial(std::istream& str) return false; } - std::map materialAmbientColor; - std::map materialDiffuseColor; - std::map materialSpecularColor; + std::map materialAmbientColor; + std::map materialDiffuseColor; + std::map materialSpecularColor; std::map materialTransparency; std::string materialName; - std::vector ambientColor; - std::vector diffuseColor; - std::vector specularColor; + std::vector ambientColor; + std::vector diffuseColor; + std::vector specularColor; std::vector transparency; - auto readColor = [](const std::vector& tokens) -> App::Color { + auto readColor = [](const std::vector& tokens) -> Base::Color { if (tokens.size() == 2) { // If only R is given then G and B will be equal float r = boost::lexical_cast(tokens[1]); - return App::Color(r, r, r); + return Base::Color(r, r, r); } if (tokens.size() == 4) { float r = boost::lexical_cast(tokens[1]); float g = boost::lexical_cast(tokens[2]); float b = boost::lexical_cast(tokens[3]); - return App::Color(r, g, b); + return Base::Color(r, g, b); } throw std::length_error("Unexpected number of tokens"); @@ -322,21 +322,21 @@ bool ReaderOBJ::LoadMaterial(std::istream& str) { auto jt = materialAmbientColor.find(it.first); if (jt != materialAmbientColor.end()) { - std::vector mat(it.second, jt->second); + std::vector mat(it.second, jt->second); ambientColor.insert(ambientColor.end(), mat.begin(), mat.end()); } } { auto jt = materialDiffuseColor.find(it.first); if (jt != materialDiffuseColor.end()) { - std::vector mat(it.second, jt->second); + std::vector mat(it.second, jt->second); diffuseColor.insert(diffuseColor.end(), mat.begin(), mat.end()); } } { auto jt = materialSpecularColor.find(it.first); if (jt != materialSpecularColor.end()) { - std::vector mat(it.second, jt->second); + std::vector mat(it.second, jt->second); specularColor.insert(specularColor.end(), mat.begin(), mat.end()); } } diff --git a/src/Mod/Mesh/App/Core/IO/WriterInventor.cpp b/src/Mod/Mesh/App/Core/IO/WriterInventor.cpp index be89c3ed50..777940d45d 100644 --- a/src/Mod/Mesh/App/Core/IO/WriterInventor.cpp +++ b/src/Mod/Mesh/App/Core/IO/WriterInventor.cpp @@ -122,13 +122,13 @@ public: return; } - auto transformColors = [](const std::vector& input) { + auto transformColors = [](const std::vector& input) { std::vector output; output.reserve(input.size()); std::transform(input.cbegin(), input.cend(), std::back_inserter(output), - [](const App::Color& col) { + [](const Base::Color& col) { return Base::ColorRGB {col.r, col.g, col.b}; }); diff --git a/src/Mod/Mesh/App/Core/IO/WriterOBJ.cpp b/src/Mod/Mesh/App/Core/IO/WriterOBJ.cpp index dce64fd6de..ae02241cf0 100644 --- a/src/Mod/Mesh/App/Core/IO/WriterOBJ.cpp +++ b/src/Mod/Mesh/App/Core/IO/WriterOBJ.cpp @@ -34,7 +34,7 @@ using namespace MeshCore; struct WriterOBJ::Color_Less { - bool operator()(const App::Color& x, const App::Color& y) const + bool operator()(const Base::Color& x, const Base::Color& y) const { if (x.r != y.r) { return x.r < y.r; @@ -131,7 +131,7 @@ bool WriterOBJ::Save(std::ostream& out) } if (exportColorPerVertex) { - App::Color c; + Base::Color c; if (_material->binding == MeshIO::PER_VERTEX) { c = _material->diffuseColor[index]; } @@ -171,14 +171,14 @@ bool WriterOBJ::Save(std::ostream& out) // facet indices (no texture and normal indices) // make sure to use the 'usemtl' statement as less often as possible - std::vector colors = _material->diffuseColor; + std::vector colors = _material->diffuseColor; std::sort(colors.begin(), colors.end(), Color_Less()); colors.erase(std::unique(colors.begin(), colors.end()), colors.end()); std::size_t index = 0; - App::Color prev; + Base::Color prev; int faceIdx = 1; - const std::vector& Kd = _material->diffuseColor; + const std::vector& Kd = _material->diffuseColor; for (auto it = rFacets.begin(); it != rFacets.end(); ++it, index++) { if (index == 0 || prev != Kd[index]) { prev = Kd[index]; @@ -209,13 +209,13 @@ bool WriterOBJ::Save(std::ostream& out) else { if (exportColorPerFace) { // make sure to use the 'usemtl' statement as less often as possible - std::vector colors = _material->diffuseColor; + std::vector colors = _material->diffuseColor; std::sort(colors.begin(), colors.end(), Color_Less()); colors.erase(std::unique(colors.begin(), colors.end()), colors.end()); bool first = true; - App::Color prev; - const std::vector& Kd = _material->diffuseColor; + Base::Color prev; + const std::vector& Kd = _material->diffuseColor; for (const auto& gt : _groups) { out << "g " << Base::Tools::escapedUnicodeFromUtf8(gt.name.c_str()) << '\n'; @@ -263,7 +263,7 @@ bool WriterOBJ::SaveMaterial(std::ostream& out) if (_material) { if (_material->binding == MeshIO::PER_FACE) { - std::vector Kd = _material->diffuseColor; + std::vector Kd = _material->diffuseColor; std::sort(Kd.begin(), Kd.end(), Color_Less()); Kd.erase(std::unique(Kd.begin(), Kd.end()), Kd.end()); diff --git a/src/Mod/Mesh/App/Core/MeshIO.cpp b/src/Mod/Mesh/App/Core/MeshIO.cpp index 1279e1d6bd..096ccc0f14 100644 --- a/src/Mod/Mesh/App/Core/MeshIO.cpp +++ b/src/Mod/Mesh/App/Core/MeshIO.cpp @@ -481,7 +481,7 @@ bool MeshInput::LoadOFF(std::istream& input) boost::cmatch what; bool colorPerVertex = false; - std::vector diffuseColor; + std::vector diffuseColor; MeshPointArray meshPoints; MeshFacetArray meshFacets; @@ -1808,7 +1808,7 @@ bool MeshOutput::SaveAsymptote(std::ostream& out) const bool saveFaceColor = (_material && _material->binding == MeshIO::PER_FACE && _material->diffuseColor.size() == rFacets.size()); // global mesh color - App::Color mc(0.8F, 0.8F, 0.8F); + Base::Color mc(0.8F, 0.8F, 0.8F); if (_material && _material->binding == MeshIO::OVERALL && _material->diffuseColor.size() == 1) { mc = _material->diffuseColor[0]; } @@ -1831,7 +1831,7 @@ bool MeshOutput::SaveAsymptote(std::ostream& out) const const MeshFacet& face = rFacets[index]; out << ",\n new pen[] {"; for (int i = 0; i < 3; i++) { - const App::Color& c = _material->diffuseColor[face._aulPoints[i]]; + const Base::Color& c = _material->diffuseColor[face._aulPoints[i]]; out << "rgb(" << c.r << ", " << c.g << ", " << c.b << ")"; if (i < 2) { out << ", "; @@ -1840,7 +1840,7 @@ bool MeshOutput::SaveAsymptote(std::ostream& out) const out << "}));\n"; } else if (saveFaceColor) { - const App::Color& c = _material->diffuseColor[index]; + const Base::Color& c = _material->diffuseColor[index]; out << "),\n rgb(" << c.r << ", " << c.g << ", " << c.b << "));\n"; } else { @@ -1912,7 +1912,7 @@ bool MeshOutput::SaveOFF(std::ostream& out) const } if (exportColor) { - App::Color c; + Base::Color c; if (_material->binding == MeshIO::PER_VERTEX) { c = _material->diffuseColor[index]; } @@ -1984,7 +1984,7 @@ bool MeshOutput::SaveBinaryPLY(std::ostream& out) const os << p.x << p.y << p.z; } if (saveVertexColor) { - const App::Color& c = _material->diffuseColor[i]; + const Base::Color& c = _material->diffuseColor[i]; uint8_t r = uint8_t(255.0F * c.r); uint8_t g = uint8_t(255.0F * c.g); uint8_t b = uint8_t(255.0F * c.b); @@ -2046,7 +2046,7 @@ bool MeshOutput::SaveAsciiPLY(std::ostream& out) const out << p.x << " " << p.y << " " << p.z; } - const App::Color& c = _material->diffuseColor[i]; + const Base::Color& c = _material->diffuseColor[i]; int r = (int)(255.0F * c.r); int g = (int)(255.0F * c.g); int b = (int)(255.0F * c.b); @@ -2359,7 +2359,7 @@ bool MeshOutput::SaveX3DContent(std::ostream& out, bool exportViewpoints) const bbox = bbox.Transformed(_transform); } - App::Color mat(0.65F, 0.65F, 0.65F); + Base::Color mat(0.65F, 0.65F, 0.65F); if (_material && _material->binding == MeshIO::Binding::OVERALL) { if (!_material->diffuseColor.empty()) { mat = _material->diffuseColor.front(); @@ -2679,7 +2679,7 @@ bool MeshOutput::SaveVRML(std::ostream& output) const << " Material {\n"; if (_material && _material->binding == MeshIO::OVERALL) { if (!_material->diffuseColor.empty()) { - App::Color c = _material->diffuseColor.front(); + Base::Color c = _material->diffuseColor.front(); output << " diffuseColor " << c.r << " " << c.g << " " << c.b << "\n"; } else { @@ -2828,7 +2828,7 @@ void MeshCleanup::RemoveInvalidFacets() // adjust the material array if needed if (materialArray && materialArray->binding == MeshIO::PER_FACE && materialArray->diffuseColor.size() == facetArray.size()) { - std::vector colors; + std::vector colors; colors.reserve(facetArray.size() - countInvalidFacets); for (std::size_t index = 0; index < facetArray.size(); index++) { if (facetArray[index].IsValid()) { @@ -2887,7 +2887,7 @@ void MeshCleanup::RemoveInvalidPoints() // adjust the material array if needed if (materialArray && materialArray->binding == MeshIO::PER_VERTEX && materialArray->diffuseColor.size() == pointArray.size()) { - std::vector colors; + std::vector colors; colors.reserve(validPoints); for (std::size_t index = 0; index < pointArray.size(); index++) { if (pointArray[index].IsValid()) { diff --git a/src/Mod/Mesh/App/Core/MeshIO.h b/src/Mod/Mesh/App/Core/MeshIO.h index d005957a92..3cae90fe09 100644 --- a/src/Mod/Mesh/App/Core/MeshIO.h +++ b/src/Mod/Mesh/App/Core/MeshIO.h @@ -82,10 +82,10 @@ struct MeshExport Material MeshIO::Binding binding {MeshIO::OVERALL}; mutable std::string library; - std::vector ambientColor; /**< Defines the ambient color. */ - std::vector diffuseColor; /**< Defines the diffuse color. */ - std::vector specularColor; /**< Defines the specular color. */ - std::vector emissiveColor; /**< Defines the emissive color. */ + std::vector ambientColor; /**< Defines the ambient color. */ + std::vector diffuseColor; /**< Defines the diffuse color. */ + std::vector specularColor; /**< Defines the specular color. */ + std::vector emissiveColor; /**< Defines the emissive color. */ std::vector shininess; std::vector transparency; diff --git a/src/Mod/Mesh/App/Importer.cpp b/src/Mod/Mesh/App/Importer.cpp index 647a8fd116..8bfe187331 100644 --- a/src/Mod/Mesh/App/Importer.cpp +++ b/src/Mod/Mesh/App/Importer.cpp @@ -65,19 +65,19 @@ void Importer::load(const std::string& fileName) } } -void Importer::addVertexColors(Feature* feature, const std::vector& colors) +void Importer::addVertexColors(Feature* feature, const std::vector& colors) { addColors(feature, "VertexColors", colors); } -void Importer::addFaceColors(Feature* feature, const std::vector& colors) +void Importer::addFaceColors(Feature* feature, const std::vector& colors) { addColors(feature, "FaceColors", colors); } void Importer::addColors(Feature* feature, const std::string& property, - const std::vector& colors) + const std::vector& colors) { App::PropertyColorList* prop = static_cast( feature->addDynamicProperty("App::PropertyColorList", property.c_str())); @@ -105,7 +105,7 @@ void Importer::createMeshFromSegments(const std::string& name, if (mat.binding == MeshCore::MeshIO::PER_FACE && mat.diffuseColor.size() == mesh.countFacets()) { - std::vector diffuseColor; + std::vector diffuseColor; diffuseColor.reserve(group.getIndices().size()); for (const auto& it : group.getIndices()) { diffuseColor.push_back(mat.diffuseColor[it]); diff --git a/src/Mod/Mesh/App/Importer.h b/src/Mod/Mesh/App/Importer.h index 1000b19538..c5097f5961 100644 --- a/src/Mod/Mesh/App/Importer.h +++ b/src/Mod/Mesh/App/Importer.h @@ -48,9 +48,9 @@ public: void load(const std::string& fileName); private: - void addVertexColors(Feature*, const std::vector&); - void addFaceColors(Feature*, const std::vector&); - void addColors(Feature*, const std::string& property, const std::vector&); + void addVertexColors(Feature*, const std::vector&); + void addFaceColors(Feature*, const std::vector&); + void addColors(Feature*, const std::string& property, const std::vector&); Feature* createMesh(const std::string& name, MeshObject&); void createMeshFromSegments(const std::string& name, MeshCore::Material& mat, MeshObject& mesh); diff --git a/src/Mod/Mesh/App/MeshProperties.cpp b/src/Mod/Mesh/App/MeshProperties.cpp index a75969c3b6..e73ec88154 100644 --- a/src/Mod/Mesh/App/MeshProperties.cpp +++ b/src/Mod/Mesh/App/MeshProperties.cpp @@ -415,22 +415,22 @@ MeshCore::MeshIO::Binding PropertyMaterial::getBinding() const return _material.binding; } -const std::vector& PropertyMaterial::getAmbientColor() const +const std::vector& PropertyMaterial::getAmbientColor() const { return _material.ambientColor; } -const std::vector& PropertyMaterial::getDiffuseColor() const +const std::vector& PropertyMaterial::getDiffuseColor() const { return _material.diffuseColor; } -const std::vector& PropertyMaterial::getSpecularColor() const +const std::vector& PropertyMaterial::getSpecularColor() const { return _material.specularColor; } -const std::vector& PropertyMaterial::getEmissiveColor() const +const std::vector& PropertyMaterial::getEmissiveColor() const { return _material.emissiveColor; } @@ -452,28 +452,28 @@ void PropertyMaterial::setValue(const MeshCore::Material& value) hasSetValue(); } -void PropertyMaterial::setAmbientColor(const std::vector& value) +void PropertyMaterial::setAmbientColor(const std::vector& value) { aboutToSetValue(); _material.ambientColor = value; hasSetValue(); } -void PropertyMaterial::setDiffuseColor(const std::vector& value) +void PropertyMaterial::setDiffuseColor(const std::vector& value) { aboutToSetValue(); _material.diffuseColor = value; hasSetValue(); } -void PropertyMaterial::setSpecularColor(const std::vector& value) +void PropertyMaterial::setSpecularColor(const std::vector& value) { aboutToSetValue(); _material.specularColor = value; hasSetValue(); } -void PropertyMaterial::setEmissiveColor(const std::vector& value) +void PropertyMaterial::setEmissiveColor(const std::vector& value) { aboutToSetValue(); _material.emissiveColor = value; @@ -503,7 +503,7 @@ void PropertyMaterial::setBinding(MeshCore::MeshIO::Binding bind) PyObject* PropertyMaterial::getPyObject() { - auto getColorList = [](const std::vector& color) { + auto getColorList = [](const std::vector& color) { Py::List list; for (const auto& it : color) { list.append(Py::TupleN(Py::Float(it.r), Py::Float(it.g), Py::Float(it.b))); @@ -534,7 +534,7 @@ PyObject* PropertyMaterial::getPyObject() void PropertyMaterial::setPyObject(PyObject* obj) { auto getColorList = [](const Py::Dict& dict, const std::string& key) { - std::vector color; + std::vector color; if (dict.hasKey(key)) { Py::Sequence list(dict.getItem(key)); color.reserve(list.size()); @@ -610,7 +610,7 @@ void PropertyMaterial::Restore(Base::XMLReader& reader) void PropertyMaterial::SaveDocFile(Base::Writer& writer) const { Base::OutputStream str(writer.Stream()); - auto saveColor = [&str](const std::vector& color) { + auto saveColor = [&str](const std::vector& color) { uint32_t count = static_cast(color.size()); str << count; for (const auto& it : color) { @@ -640,7 +640,7 @@ void PropertyMaterial::SaveDocFile(Base::Writer& writer) const void PropertyMaterial::RestoreDocFile(Base::Reader& reader) { Base::InputStream str(reader); - auto restoreColor = [&str](std::vector& color) { + auto restoreColor = [&str](std::vector& color) { uint32_t count = 0; str >> count; color.resize(count); @@ -702,7 +702,7 @@ unsigned int PropertyMaterial::getMemSize() const { auto size = (_material.ambientColor.size() + _material.diffuseColor.size() + _material.emissiveColor.size() + _material.specularColor.size()) - * sizeof(App::Color) + * sizeof(Base::Color) + (_material.shininess.size() + _material.transparency.size()) * sizeof(float) + _material.library.size() + sizeof(_material); return static_cast(size); diff --git a/src/Mod/Mesh/App/MeshProperties.h b/src/Mod/Mesh/App/MeshProperties.h index d3be55dc46..65710824f4 100644 --- a/src/Mod/Mesh/App/MeshProperties.h +++ b/src/Mod/Mesh/App/MeshProperties.h @@ -189,19 +189,19 @@ public: /** Sets the property */ void setValue(const MeshCore::Material& value); - void setAmbientColor(const std::vector& value); - void setDiffuseColor(const std::vector& value); - void setSpecularColor(const std::vector& value); - void setEmissiveColor(const std::vector& value); + void setAmbientColor(const std::vector& value); + void setDiffuseColor(const std::vector& value); + void setSpecularColor(const std::vector& value); + void setEmissiveColor(const std::vector& value); void setShininess(const std::vector&); void setTransparency(const std::vector&); void setBinding(MeshCore::MeshIO::Binding); const MeshCore::Material& getValue() const; - const std::vector& getAmbientColor() const; - const std::vector& getDiffuseColor() const; - const std::vector& getSpecularColor() const; - const std::vector& getEmissiveColor() const; + const std::vector& getAmbientColor() const; + const std::vector& getDiffuseColor() const; + const std::vector& getSpecularColor() const; + const std::vector& getEmissiveColor() const; const std::vector& getShininess() const; const std::vector& getTransparency() const; MeshCore::MeshIO::Binding getBinding() const; diff --git a/src/Mod/Mesh/App/MeshTexture.cpp b/src/Mod/Mesh/App/MeshTexture.cpp index 90326148d4..16be349df7 100644 --- a/src/Mod/Mesh/App/MeshTexture.cpp +++ b/src/Mod/Mesh/App/MeshTexture.cpp @@ -47,14 +47,14 @@ MeshTexture::MeshTexture(const Mesh::MeshObject& mesh, const MeshCore::Material& } void MeshTexture::apply(const Mesh::MeshObject& mesh, - const App::Color& defaultColor, + const Base::Color& defaultColor, MeshCore::Material& material) { apply(mesh, true, defaultColor, -1.0F, material); } void MeshTexture::apply(const Mesh::MeshObject& mesh, - const App::Color& defaultColor, + const Base::Color& defaultColor, float max_dist, MeshCore::Material& material) { @@ -63,31 +63,31 @@ void MeshTexture::apply(const Mesh::MeshObject& mesh, void MeshTexture::apply(const Mesh::MeshObject& mesh, MeshCore::Material& material) { - App::Color defaultColor; + Base::Color defaultColor; apply(mesh, false, defaultColor, -1.0F, material); } void MeshTexture::apply(const Mesh::MeshObject& mesh, float max_dist, MeshCore::Material& material) { - App::Color defaultColor; + Base::Color defaultColor; apply(mesh, false, defaultColor, max_dist, material); } void MeshTexture::apply(const Mesh::MeshObject& mesh, bool addDefaultColor, - const App::Color& defaultColor, + const Base::Color& defaultColor, float max_dist, MeshCore::Material& material) { // copy the color values because the passed material could be the same instance as // 'materialRefMesh' - std::vector textureColor = materialRefMesh.diffuseColor; + std::vector textureColor = materialRefMesh.diffuseColor; material.diffuseColor.clear(); material.binding = MeshCore::MeshIO::OVERALL; if (kdTree) { // the points of the current mesh - std::vector diffuseColor; + std::vector diffuseColor; const MeshCore::MeshPointArray& points = mesh.getKernel().GetPoints(); const MeshCore::MeshFacetArray& facets = mesh.getKernel().GetFacets(); diff --git a/src/Mod/Mesh/App/MeshTexture.h b/src/Mod/Mesh/App/MeshTexture.h index 5251713b2d..83c198115a 100644 --- a/src/Mod/Mesh/App/MeshTexture.h +++ b/src/Mod/Mesh/App/MeshTexture.h @@ -53,7 +53,7 @@ public: original material is used. */ void apply(const Mesh::MeshObject& mesh, - const App::Color& defaultColor, + const Base::Color& defaultColor, MeshCore::Material& material); /*! Find common points or facets of this to the original mesh. For points or facets @@ -61,7 +61,7 @@ public: original material is used. */ void apply(const Mesh::MeshObject& mesh, - const App::Color& defaultColor, + const Base::Color& defaultColor, float max_dist, MeshCore::Material& material); /*! @@ -80,7 +80,7 @@ public: private: void apply(const Mesh::MeshObject& mesh, bool addDefaultColor, - const App::Color& defaultColor, + const Base::Color& defaultColor, float max_dist, MeshCore::Material& material); PointIndex findIndex(const Base::Vector3f& p, float max_dist) const diff --git a/src/Mod/Mesh/Gui/CMakeLists.txt b/src/Mod/Mesh/Gui/CMakeLists.txt index 15dbb22d95..c031c1f01e 100644 --- a/src/Mod/Mesh/Gui/CMakeLists.txt +++ b/src/Mod/Mesh/Gui/CMakeLists.txt @@ -1,5 +1,9 @@ include_directories( ${CMAKE_CURRENT_BINARY_DIR} +) + +include_directories( + SYSTEM ${Boost_INCLUDE_DIRS} ${COIN3D_INCLUDE_DIRS} ${COIN3D_INCLUDE_DIRS}/Inventor/annex diff --git a/src/Mod/Mesh/Gui/MeshEditor.cpp b/src/Mod/Mesh/Gui/MeshEditor.cpp index 1d9370a060..3270210c15 100644 --- a/src/Mod/Mesh/Gui/MeshEditor.cpp +++ b/src/Mod/Mesh/Gui/MeshEditor.cpp @@ -117,7 +117,7 @@ void ViewProviderFace::attach(App::DocumentObject* obj) SoBaseColor* basecol = new SoBaseColor; if (mesh) { - App::Color col = mesh->ShapeAppearance.getDiffuseColor(); + Base::Color col = mesh->ShapeAppearance.getDiffuseColor(); basecol->rgb.setValue(col.r, col.g, col.b); } else { diff --git a/src/Mod/Mesh/Gui/SoFCIndexedFaceSet.cpp b/src/Mod/Mesh/Gui/SoFCIndexedFaceSet.cpp index 82b3002259..080e0584b2 100644 --- a/src/Mod/Mesh/Gui/SoFCIndexedFaceSet.cpp +++ b/src/Mod/Mesh/Gui/SoFCIndexedFaceSet.cpp @@ -411,10 +411,9 @@ bool MeshRenderer::matchMaterial(SoState* state) const return p->pcolors == pcolors; } -bool MeshRenderer::shouldRenderDirectly(bool direct) +bool MeshRenderer::shouldRenderDirectly([[maybe_unused]] bool direct) { #ifdef RENDER_GL_VAO - Q_UNUSED(direct); return false; #else return direct; @@ -754,7 +753,7 @@ void SoFCIndexedFaceSet::generateGLArrays(SoGLRenderAction* action) numcolors = gl->getNumDiffuse(); transp = gl->getTransparencyPointer(); numtransp = gl->getNumTransparencies(); - Q_UNUSED(numtransp); + (void)numtransp; } std::vector face_vertices; diff --git a/src/Mod/Mesh/Gui/ViewProvider.cpp b/src/Mod/Mesh/Gui/ViewProvider.cpp index 033b0449de..41446b94f8 100644 --- a/src/Mod/Mesh/Gui/ViewProvider.cpp +++ b/src/Mod/Mesh/Gui/ViewProvider.cpp @@ -269,7 +269,7 @@ ViewProviderMesh::ViewProviderMesh() Gui::WindowParameter::getDefaultParameter()->GetGroup("Mod/Mesh"); // Mesh color - App::Color color = ShapeAppearance.getDiffuseColor(); + Base::Color color = ShapeAppearance.getDiffuseColor(); unsigned long current = color.getPackedValue(); unsigned long setting = hGrp->GetUnsigned("MeshColor", current); if (current != setting) { @@ -353,7 +353,7 @@ void ViewProviderMesh::onChanged(const App::Property* prop) } } else if (prop == &LineColor) { - const App::Color& c = LineColor.getValue(); + const Base::Color& c = LineColor.getValue(); pLineColor->diffuseColor.setValue(c.r, c.g, c.b); } else if (prop == &Coloring) { @@ -373,7 +373,7 @@ void ViewProviderMesh::onChanged(const App::Property* prop) ViewProviderGeometryObject::onChanged(prop); } -void ViewProviderMesh::setOpenEdgeColorFrom(const App::Color& c) +void ViewProviderMesh::setOpenEdgeColorFrom(const Base::Color& c) { float r = 1.0F - c.r; r = r < 0.5F ? 0.0F : 1.0F; @@ -588,7 +588,7 @@ void ViewProviderMesh::tryColorPerVertexOrFace(bool on) } else { pcMatBinding->value = SoMaterialBinding::OVERALL; - const App::Color& c = ShapeAppearance.getDiffuseColor(); + const Base::Color& c = ShapeAppearance.getDiffuseColor(); pcShapeMaterial->diffuseColor.setValue(c.r, c.g, c.b); pcShapeMaterial->transparency.setValue(Base::fromPercent(Transparency.getValue())); } @@ -606,7 +606,7 @@ void ViewProviderMesh::setColorPerFace(const App::PropertyColorList* prop) setDiffuseColor(prop->getValues()); } -void ViewProviderMesh::setColorField(const std::vector& val, SoMFColor& field) +void ViewProviderMesh::setColorField(const std::vector& val, SoMFColor& field) { field.setNum(val.size()); SbColor* col = field.startEditing(); @@ -619,22 +619,22 @@ void ViewProviderMesh::setColorField(const std::vector& val, SoMFCol field.finishEditing(); } -void ViewProviderMesh::setAmbientColor(const std::vector& val) +void ViewProviderMesh::setAmbientColor(const std::vector& val) { setColorField(val, pcShapeMaterial->ambientColor); } -void ViewProviderMesh::setDiffuseColor(const std::vector& val) +void ViewProviderMesh::setDiffuseColor(const std::vector& val) { setColorField(val, pcShapeMaterial->diffuseColor); } -void ViewProviderMesh::setSpecularColor(const std::vector& val) +void ViewProviderMesh::setSpecularColor(const std::vector& val) { setColorField(val, pcShapeMaterial->specularColor); } -void ViewProviderMesh::setEmissiveColor(const std::vector& val) +void ViewProviderMesh::setEmissiveColor(const std::vector& val) { setColorField(val, pcShapeMaterial->emissiveColor); } @@ -1982,7 +1982,7 @@ void ViewProviderMesh::fillHole(Mesh::FacetIndex uFacet) void ViewProviderMesh::setFacetTransparency(const std::vector& facetTransparency) { if (pcShapeMaterial->diffuseColor.getNum() != int(facetTransparency.size())) { - App::Color c = ShapeAppearance.getDiffuseColor(); + Base::Color c = ShapeAppearance.getDiffuseColor(); pcShapeMaterial->diffuseColor.setNum(facetTransparency.size()); SbColor* cols = pcShapeMaterial->diffuseColor.startEditing(); for (std::size_t index = 0; index < facetTransparency.size(); ++index) { @@ -2004,7 +2004,7 @@ void ViewProviderMesh::setFacetTransparency(const std::vector& facetTrans void ViewProviderMesh::resetFacetTransparency() { pcMatBinding->value = SoMaterialBinding::OVERALL; - App::Color c = ShapeAppearance.getDiffuseColor(); + Base::Color c = ShapeAppearance.getDiffuseColor(); pcShapeMaterial->diffuseColor.setValue(c.r, c.g, c.b); pcShapeMaterial->transparency.setValue(0); } @@ -2032,8 +2032,8 @@ void ViewProviderMesh::removeFacets(const std::vector& facets) // switch off coloring mode Coloring.setValue(false); - const std::vector& colors = prop->getValues(); - std::vector valid_colors; + const std::vector& colors = prop->getValues(); + std::vector valid_colors; valid_colors.reserve(kernel->countPoints() - invalid); std::size_t numPoints = pointDegree.size(); for (std::size_t index = 0; index < numPoints; index++) { @@ -2054,8 +2054,8 @@ void ViewProviderMesh::removeFacets(const std::vector& facets) validFacets[it] = false; } - const std::vector& colors = prop->getValues(); - std::vector valid_colors; + const std::vector& colors = prop->getValues(); + std::vector valid_colors; valid_colors.reserve(colors.size()); std::size_t numColors = colors.size(); for (std::size_t index = 0; index < numColors; index++) { @@ -2112,7 +2112,7 @@ void ViewProviderMesh::deselectFacet(Mesh::FacetIndex facet) highlightSelection(); } else { - App::Color c = ShapeAppearance.getDiffuseColor(); + Base::Color c = ShapeAppearance.getDiffuseColor(); pcShapeMaterial->diffuseColor.set1Value(facet, c.r, c.g, c.b); } } @@ -2280,7 +2280,7 @@ void ViewProviderMesh::highlightSelection() // Colorize the selection pcMatBinding->value = SoMaterialBinding::PER_FACE; - App::Color c = ShapeAppearance.getDiffuseColor(); + Base::Color c = ShapeAppearance.getDiffuseColor(); int uCtFacets = (int)rMesh.countFacets(); pcShapeMaterial->diffuseColor.setNum(uCtFacets); @@ -2296,7 +2296,7 @@ void ViewProviderMesh::highlightSelection() void ViewProviderMesh::unhighlightSelection() { - App::Color c = ShapeAppearance.getDiffuseColor(); + Base::Color c = ShapeAppearance.getDiffuseColor(); pcMatBinding->value = SoMaterialBinding::OVERALL; pcShapeMaterial->diffuseColor.setNum(1); pcShapeMaterial->diffuseColor.setValue(c.r, c.g, c.b); @@ -2358,13 +2358,13 @@ void ViewProviderMesh::setHighlightedSegments(bool on) void ViewProviderMesh::highlightSegments() { - std::vector colors; + std::vector colors; const Mesh::MeshObject& rMesh = getMeshObject(); unsigned long numSegm = rMesh.countSegments(); colors.resize(numSegm, this->ShapeAppearance.getDiffuseColor()); for (unsigned long i = 0; i < numSegm; i++) { - App::Color col; + Base::Color col; if (col.fromHexString(rMesh.getSegment(i).getColor())) { colors[i] = col; } @@ -2373,7 +2373,7 @@ void ViewProviderMesh::highlightSegments() highlightSegments(colors); } -void ViewProviderMesh::highlightSegments(const std::vector& colors) +void ViewProviderMesh::highlightSegments(const std::vector& colors) { const Mesh::MeshObject& rMesh = getMeshObject(); unsigned long numSegm = rMesh.countSegments(); diff --git a/src/Mod/Mesh/Gui/ViewProvider.h b/src/Mod/Mesh/Gui/ViewProvider.h index 8f0ab1e23d..b909e9150b 100644 --- a/src/Mod/Mesh/Gui/ViewProvider.h +++ b/src/Mod/Mesh/Gui/ViewProvider.h @@ -199,7 +199,7 @@ public: /*! The size of the array must be equal to the number of facets. */ void setFacetTransparency(const std::vector&); void resetFacetTransparency(); - void highlightSegments(const std::vector&); + void highlightSegments(const std::vector&); //@} /** @name Restoring view provider from document load */ @@ -215,7 +215,7 @@ protected: /// get called by the container whenever a property has been changed void onChanged(const App::Property* prop) override; virtual void showOpenEdges(bool); - void setOpenEdgeColorFrom(const App::Color& col); + void setOpenEdgeColorFrom(const Base::Color& col); virtual void splitMesh(const MeshCore::MeshKernel& toolMesh, const Base::Vector3f& normal, SbBool inner); virtual void @@ -241,11 +241,11 @@ protected: const Mesh::PropertyMeshKernel& getMeshProperty() const; Mesh::PropertyMeshKernel& getMeshProperty(); - void setColorField(const std::vector&, SoMFColor&); - void setAmbientColor(const std::vector&); - void setDiffuseColor(const std::vector&); - void setSpecularColor(const std::vector&); - void setEmissiveColor(const std::vector&); + void setColorField(const std::vector&, SoMFColor&); + void setAmbientColor(const std::vector&); + void setDiffuseColor(const std::vector&); + void setSpecularColor(const std::vector&); + void setEmissiveColor(const std::vector&); virtual SoShape* getShapeNode() const; virtual SoNode* getCoordNode() const; diff --git a/src/Mod/Mesh/Gui/ViewProviderCurvature.cpp b/src/Mod/Mesh/Gui/ViewProviderCurvature.cpp index db9768a15a..2fe95398b6 100644 --- a/src/Mod/Mesh/Gui/ViewProviderCurvature.cpp +++ b/src/Mod/Mesh/Gui/ViewProviderCurvature.cpp @@ -360,7 +360,7 @@ void ViewProviderMeshCurvature::setVertexCurvatureMode(int mode) float* transp = pcColorMat->transparency.startEditing(); for (auto const& value : fValues | boost::adaptors::indexed(0)) { - App::Color c = pcColorBar->getColor(value.value()); + Base::Color c = pcColorBar->getColor(value.value()); // NOLINTBEGIN diffcol[value.index()].setValue(c.r, c.g, c.b); transp[value.index()] = c.transparency(); diff --git a/src/Mod/MeshPart/App/AppMeshPartPy.cpp b/src/Mod/MeshPart/App/AppMeshPartPy.cpp index c8d05b9d5a..5b62b4216e 100644 --- a/src/Mod/MeshPart/App/AppMeshPartPy.cpp +++ b/src/Mod/MeshPart/App/AppMeshPartPy.cpp @@ -510,7 +510,7 @@ private: Py::Float r(t[0]); Py::Float g(t[1]); Py::Float b(t[2]); - App::Color c(static_cast(r), + Base::Color c(static_cast(r), static_cast(g), static_cast(b)); colors.push_back(c.getPackedValue()); diff --git a/src/Mod/MeshPart/App/CMakeLists.txt b/src/Mod/MeshPart/App/CMakeLists.txt index 4f337de023..8d52ddbafb 100644 --- a/src/Mod/MeshPart/App/CMakeLists.txt +++ b/src/Mod/MeshPart/App/CMakeLists.txt @@ -12,6 +12,10 @@ endif(BUILD_FEM_NETGEN) include_directories( ${CMAKE_BINARY_DIR} ${CMAKE_SOURCE_DIR}/src +) + +include_directories( + SYSTEM ${Boost_INCLUDE_DIRS} ${OCC_INCLUDE_DIR} ${ZLIB_INCLUDE_DIR} @@ -135,7 +139,7 @@ if (BUILD_FLAT_MESH) endif() if(Boost_FOUND) - include_directories(${Boost_INCLUDE_DIRS}) + include_directories(SYSTEM ${Boost_INCLUDE_DIRS}) SET(FLATMESH_SRCS MeshFlattening.cpp MeshFlattening.h diff --git a/src/Mod/MeshPart/App/Mesher.cpp b/src/Mod/MeshPart/App/Mesher.cpp index e5088b9141..0ba26fe51e 100644 --- a/src/Mod/MeshPart/App/Mesher.cpp +++ b/src/Mod/MeshPart/App/Mesher.cpp @@ -197,7 +197,7 @@ public: std::stringstream str; str << "patch" << index++; segm.setName(str.str()); - App::Color col; + Base::Color col; col.setPackedValue(it.first); segm.setColor(col.asHexString()); meshdata->addSegment(segm); diff --git a/src/Mod/MeshPart/Gui/CMakeLists.txt b/src/Mod/MeshPart/Gui/CMakeLists.txt index 2a05e71729..f5f2b4b963 100644 --- a/src/Mod/MeshPart/Gui/CMakeLists.txt +++ b/src/Mod/MeshPart/Gui/CMakeLists.txt @@ -13,6 +13,10 @@ include_directories( ${CMAKE_BINARY_DIR} ${CMAKE_SOURCE_DIR}/src ${CMAKE_CURRENT_BINARY_DIR} +) + +include_directories( + SYSTEM ${Boost_INCLUDE_DIRS} ${OCC_INCLUDE_DIR} ${COIN3D_INCLUDE_DIRS} diff --git a/src/Mod/MeshPart/Gui/Tessellation.cpp b/src/Mod/MeshPart/Gui/Tessellation.cpp index 6241ed1a0e..f063bd91be 100644 --- a/src/Mod/MeshPart/Gui/Tessellation.cpp +++ b/src/Mod/MeshPart/Gui/Tessellation.cpp @@ -377,7 +377,7 @@ void Tessellation::setFaceColors(int method, App::Document* doc, App::DocumentOb auto svp = Base::freecad_dynamic_cast( Gui::Application::Instance->getViewProvider(obj)); if (vpmesh && svp) { - std::vector diff_col = svp->ShapeAppearance.getDiffuseColors(); + std::vector diff_col = svp->ShapeAppearance.getDiffuseColors(); if (ui->groupsFaceColors->isChecked()) { diff_col = getUniqueColors(diff_col); } @@ -389,15 +389,15 @@ void Tessellation::setFaceColors(int method, App::Document* doc, App::DocumentOb } } -void Tessellation::addFaceColors(Mesh::Feature* mesh, const std::vector& colorPerSegm) +void Tessellation::addFaceColors(Mesh::Feature* mesh, const std::vector& colorPerSegm) { const Mesh::MeshObject& kernel = mesh->Mesh.getValue(); unsigned long numSegm = kernel.countSegments(); if (numSegm > 0 && numSegm == colorPerSegm.size()) { unsigned long uCtFacets = kernel.countFacets(); - std::vector colorPerFace(uCtFacets); + std::vector colorPerFace(uCtFacets); for (unsigned long i = 0; i < numSegm; i++) { - App::Color segmColor = colorPerSegm[i]; + Base::Color segmColor = colorPerSegm[i]; std::vector segm = kernel.getSegment(i).getIndices(); for (Mesh::FacetIndex it : segm) { colorPerFace[it] = segmColor; @@ -412,7 +412,7 @@ void Tessellation::addFaceColors(Mesh::Feature* mesh, const std::vector Tessellation::getUniqueColors(const std::vector& colors) const +std::vector Tessellation::getUniqueColors(const std::vector& colors) const { // unique colors std::set col_set; @@ -420,7 +420,7 @@ std::vector Tessellation::getUniqueColors(const std::vector unique; + std::vector unique; unique.reserve(col_set.size()); for (const auto& it : col_set) { unique.emplace_back(it); diff --git a/src/Mod/MeshPart/Gui/Tessellation.h b/src/Mod/MeshPart/Gui/Tessellation.h index c9361b0e3e..77d17d059d 100644 --- a/src/Mod/MeshPart/Gui/Tessellation.h +++ b/src/Mod/MeshPart/Gui/Tessellation.h @@ -97,12 +97,12 @@ protected: void process(int method, App::Document* doc, const std::list&); void saveParameters(int method); void setFaceColors(int method, App::Document* doc, App::DocumentObject* obj); - void addFaceColors(Mesh::Feature* mesh, const std::vector& colorPerSegm); + void addFaceColors(Mesh::Feature* mesh, const std::vector& colorPerSegm); QString getMeshingParameters(int method, App::DocumentObject* obj) const; QString getStandardParameters(App::DocumentObject* obj) const; QString getMefistoParameters() const; QString getNetgenParameters() const; - std::vector getUniqueColors(const std::vector& colors) const; + std::vector getUniqueColors(const std::vector& colors) const; private: void setupConnections(); diff --git a/src/Mod/Part/App/AppPartPy.cpp b/src/Mod/Part/App/AppPartPy.cpp index 7058f66d1e..f094479e61 100644 --- a/src/Mod/Part/App/AppPartPy.cpp +++ b/src/Mod/Part/App/AppPartPy.cpp @@ -720,7 +720,6 @@ private: std::string EncodedName = std::string(Name); PyMem_Free(Name); - //Base::Console().Log("Open in Part with %s",Name); Base::FileInfo file(EncodedName.c_str()); // extract ending @@ -2015,9 +2014,7 @@ private: } pysize = PyUnicode_GetLength(p); -#if PY_VERSION_HEX < 0x03090000 - unichars = PyUnicode_AS_UNICODE(p); -#else + #ifdef FC_OS_WIN32 //PyUNICODE is only 16 bits on Windows (wchar_t), so passing 32 bit UCS4 //will result in unknown glyph in even positions, and wrong characters in @@ -2025,15 +2022,12 @@ private: unichars = (Py_UNICODE*)PyUnicode_AsWideCharString(p, &pysize); #else unichars = (Py_UNICODE *)PyUnicode_AsUCS4Copy(p); -#endif #endif } else if (PyUnicode_Check(intext)) { pysize = PyUnicode_GetLength(intext); -#if PY_VERSION_HEX < 0x03090000 - unichars = PyUnicode_AS_UNICODE(intext); -#else + #ifdef FC_OS_WIN32 //PyUNICODE is only 16 bits on Windows (wchar_t), so passing 32 bit UCS4 //will result in unknown glyph in even positions, and wrong characters in @@ -2041,7 +2035,6 @@ private: unichars = (Py_UNICODE*)PyUnicode_AsWideCharString(intext, &pysize); #else unichars = (Py_UNICODE *)PyUnicode_AsUCS4Copy(intext); -#endif #endif } else { @@ -2055,11 +2048,9 @@ private: else { CharList = FT2FC(unichars,pysize,dir,fontfile,height,track); } -#if PY_VERSION_HEX >= 0x03090000 if (unichars) { PyMem_Free(unichars); } -#endif } catch (Standard_DomainError&) { // Standard_DomainError is OCC error. throw Py::Exception(PartExceptionOCCDomainError, "makeWireString failed - Standard_DomainError"); diff --git a/src/Mod/Part/App/CMakeLists.txt b/src/Mod/Part/App/CMakeLists.txt index 0c027cf6c4..9049ad51c2 100644 --- a/src/Mod/Part/App/CMakeLists.txt +++ b/src/Mod/Part/App/CMakeLists.txt @@ -7,6 +7,10 @@ include_directories( ${CMAKE_SOURCE_DIR}/src ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_CURRENT_SOURCE_DIR} +) + +include_directories( + SYSTEM ${Boost_INCLUDE_DIRS} ${OCC_INCLUDE_DIR} ${PYCXX_INCLUDE_DIR} diff --git a/src/Mod/Part/App/TopoShape.cpp b/src/Mod/Part/App/TopoShape.cpp index 8c01f76b64..b4425386b2 100644 --- a/src/Mod/Part/App/TopoShape.cpp +++ b/src/Mod/Part/App/TopoShape.cpp @@ -1007,7 +1007,7 @@ void TopoShape::exportStl(const char *filename, double deflection) const } void TopoShape::exportFaceSet(double dev, double ca, - const std::vector& colors, + const std::vector& colors, std::ostream& str) const { Base::InventorBuilder builder(str); @@ -1056,7 +1056,7 @@ void TopoShape::exportFaceSet(double dev, double ca, Base::ShapeHintsItem shapeHints{static_cast(ca)}; builder.addNode(shapeHints); if (supportFaceColors) { - App::Color c = colors[index]; + Base::Color c = colors[index]; Base::MaterialItem material; material.setDiffuseColor({Base::ColorRGB{c.r, c.g, c.b}}); material.setTransparency({c.a}); diff --git a/src/Mod/Part/App/TopoShape.h b/src/Mod/Part/App/TopoShape.h index 421d68cd4e..f402c08635 100644 --- a/src/Mod/Part/App/TopoShape.h +++ b/src/Mod/Part/App/TopoShape.h @@ -49,7 +49,7 @@ class gp_Ax2; class gp_Pln; class gp_Vec; -namespace App +namespace Base { class Color; } @@ -479,7 +479,7 @@ public: void exportBrep(std::ostream&) const; void exportBinary(std::ostream&) const; void exportStl(const char* FileName, double deflection) const; - void exportFaceSet(double, double, const std::vector&, std::ostream&) const; + void exportFaceSet(double, double, const std::vector&, std::ostream&) const; void exportLineSet(std::ostream&) const; //@} diff --git a/src/Mod/Part/App/TopoShapePyImp.cpp b/src/Mod/Part/App/TopoShapePyImp.cpp index d89d58b108..246c0c7e1a 100644 --- a/src/Mod/Part/App/TopoShapePyImp.cpp +++ b/src/Mod/Part/App/TopoShapePyImp.cpp @@ -312,7 +312,7 @@ PyObject* TopoShapePy::writeInventor(PyObject * args, PyObject * keywds) return nullptr; } - std::vector faceColors; + std::vector faceColors; if (pylist) { App::PropertyColorList prop; prop.setPyObject(pylist); diff --git a/src/Mod/Part/Gui/CMakeLists.txt b/src/Mod/Part/Gui/CMakeLists.txt index e878a62d51..ae9d47f00d 100644 --- a/src/Mod/Part/Gui/CMakeLists.txt +++ b/src/Mod/Part/Gui/CMakeLists.txt @@ -3,6 +3,10 @@ include_directories( ${CMAKE_SOURCE_DIR}/src ${CMAKE_BINARY_DIR}/src ${CMAKE_CURRENT_BINARY_DIR} +) + +include_directories( + SYSTEM ${Boost_INCLUDE_DIRS} ${COIN3D_INCLUDE_DIRS} ${OCC_INCLUDE_DIR} @@ -27,6 +31,7 @@ if(MSVC) endif(MSVC) include_directories( + SYSTEM ${QtConcurrent_INCLUDE_DIRS} ) list(APPEND PartGui_LIBS diff --git a/src/Mod/Part/Gui/DlgProjectionOnSurface.cpp b/src/Mod/Part/Gui/DlgProjectionOnSurface.cpp index 1a9d35660a..01fe09b9d0 100644 --- a/src/Mod/Part/Gui/DlgProjectionOnSurface.cpp +++ b/src/Mod/Part/Gui/DlgProjectionOnSurface.cpp @@ -656,7 +656,7 @@ void PartGui::DlgProjectionOnSurface::show_projected_shapes( if (vp) { const unsigned int color = 0x8ae23400; vp->LineColor.setValue(color); - vp->ShapeAppearance.setDiffuseColor(App::Color(color)); + vp->ShapeAppearance.setDiffuseColor(Base::Color(color)); vp->PointColor.setValue(color); vp->Transparency.setValue(0); } @@ -721,8 +721,8 @@ void PartGui::DlgProjectionOnSurface::higlight_object(Part::Feature* iCurrentObj auto vp = dynamic_cast( Gui::Application::Instance->getViewProvider(iCurrentObject)); if (vp) { - std::vector colors; - App::Color defaultColor; + std::vector colors; + Base::Color defaultColor; if (currentShapeType == TopAbs_FACE) { colors = vp->ShapeAppearance.getDiffuseColors(); defaultColor = colors.front(); @@ -737,7 +737,7 @@ void PartGui::DlgProjectionOnSurface::higlight_object(Part::Feature* iCurrentObj } if (iHighlight) { - App::Color aColor; + Base::Color aColor; aColor.setPackedValue(iColor); colors.at(index - 1) = aColor; } diff --git a/src/Mod/Part/Gui/ReferenceHighlighter.cpp b/src/Mod/Part/Gui/ReferenceHighlighter.cpp index 9d2692f9ce..fd64a10a4d 100644 --- a/src/Mod/Part/Gui/ReferenceHighlighter.cpp +++ b/src/Mod/Part/Gui/ReferenceHighlighter.cpp @@ -33,7 +33,7 @@ using namespace PartGui; -ReferenceHighlighter::ReferenceHighlighter(const TopoDS_Shape& shape, const App::Color& color) +ReferenceHighlighter::ReferenceHighlighter(const TopoDS_Shape& shape, const Base::Color& color) : defaultColor(color) , elementColor(1.0f,0.0f,1.0f) // magenta , objectColor(0.6f,0.0f,1.0f) // purple @@ -44,7 +44,7 @@ ReferenceHighlighter::ReferenceHighlighter(const TopoDS_Shape& shape, const App: TopExp::MapShapes(shape, TopAbs_FACE, fMap); } -void ReferenceHighlighter::getVertexColor(const std::string& element, std::vector& colors) const +void ReferenceHighlighter::getVertexColor(const std::string& element, std::vector& colors) const { int idx = std::stoi(element.substr(6)) - 1; assert ( idx >= 0 ); @@ -53,7 +53,7 @@ void ReferenceHighlighter::getVertexColor(const std::string& element, std::vecto colors[pos] = elementColor; } -void ReferenceHighlighter::getVertexColorsOfEdge(const std::string& element, std::vector& colors) const +void ReferenceHighlighter::getVertexColorsOfEdge(const std::string& element, std::vector& colors) const { int idx = std::stoi(element.substr(4)); assert ( idx > 0 ); @@ -71,7 +71,7 @@ void ReferenceHighlighter::getVertexColorsOfEdge(const std::string& element, std } } -void ReferenceHighlighter::getVertexColorsOfWire(const std::string& element, std::vector& colors) const +void ReferenceHighlighter::getVertexColorsOfWire(const std::string& element, std::vector& colors) const { int idx = std::stoi(element.substr(4)); assert ( idx > 0 ); @@ -89,7 +89,7 @@ void ReferenceHighlighter::getVertexColorsOfWire(const std::string& element, std } } -void ReferenceHighlighter::getVertexColorsOfFace(const std::string& element, std::vector& colors) const +void ReferenceHighlighter::getVertexColorsOfFace(const std::string& element, std::vector& colors) const { int idx = std::stoi(element.substr(4)); assert ( idx > 0 ); @@ -108,7 +108,7 @@ void ReferenceHighlighter::getVertexColorsOfFace(const std::string& element, std } void ReferenceHighlighter::getVertexColors(const std::vector& elements, - std::vector& colors) const + std::vector& colors) const { colors.resize(vMap.Extent(), defaultColor); @@ -133,7 +133,7 @@ void ReferenceHighlighter::getVertexColors(const std::vector& eleme } } -void ReferenceHighlighter::getEdgeColor(const std::string& element, std::vector& colors) const +void ReferenceHighlighter::getEdgeColor(const std::string& element, std::vector& colors) const { int idx = std::stoi(element.substr(4)) - 1; assert ( idx >= 0 ); @@ -142,7 +142,7 @@ void ReferenceHighlighter::getEdgeColor(const std::string& element, std::vector< colors[pos] = elementColor; } -void ReferenceHighlighter::getEdgeColorsOfWire(const std::string& element, std::vector& colors) const +void ReferenceHighlighter::getEdgeColorsOfWire(const std::string& element, std::vector& colors) const { int idx = std::stoi(element.substr(4)); assert ( idx > 0 ); @@ -160,7 +160,7 @@ void ReferenceHighlighter::getEdgeColorsOfWire(const std::string& element, std:: } } -void ReferenceHighlighter::getEdgeColorsOfFace(const std::string& element, std::vector& colors) const +void ReferenceHighlighter::getEdgeColorsOfFace(const std::string& element, std::vector& colors) const { int idx = std::stoi(element.substr(4)); assert ( idx > 0 ); @@ -179,7 +179,7 @@ void ReferenceHighlighter::getEdgeColorsOfFace(const std::string& element, std:: } void ReferenceHighlighter::getEdgeColors(const std::vector& elements, - std::vector& colors) const + std::vector& colors) const { colors.resize(eMap.Extent(), defaultColor); @@ -201,7 +201,7 @@ void ReferenceHighlighter::getEdgeColors(const std::vector& element } } -void ReferenceHighlighter::getFaceColor(const std::string& element, std::vector& colors) const +void ReferenceHighlighter::getFaceColor(const std::string& element, std::vector& colors) const { int idx = std::stoi(element.substr(4)) - 1; assert ( idx >= 0 ); @@ -222,7 +222,7 @@ void ReferenceHighlighter::getFaceColor(const std::string& element, } void ReferenceHighlighter::getFaceColors(const std::vector& elements, - std::vector& colors) const + std::vector& colors) const { colors.resize(fMap.Extent(), defaultColor); diff --git a/src/Mod/Part/Gui/ReferenceHighlighter.h b/src/Mod/Part/Gui/ReferenceHighlighter.h index 507e383776..8ea1468e57 100644 --- a/src/Mod/Part/Gui/ReferenceHighlighter.h +++ b/src/Mod/Part/Gui/ReferenceHighlighter.h @@ -46,15 +46,15 @@ public: * \param shape The input shape. * \param color The standard edge color. */ - ReferenceHighlighter(const TopoDS_Shape& shape, const App::Color& color); + ReferenceHighlighter(const TopoDS_Shape& shape, const Base::Color& color); - void setDefaultColor(const App::Color& c) { + void setDefaultColor(const Base::Color& c) { defaultColor = c; } - void setElementColor(const App::Color& c) { + void setElementColor(const Base::Color& c) { elementColor = c; } - void setObjectColor(const App::Color& c) { + void setObjectColor(const Base::Color& c) { objectColor = c; } @@ -64,21 +64,21 @@ public: * \param colors The size of the \a colors array is equal to the number of vertexes of the shape */ void getVertexColors(const std::vector& elements, - std::vector& colors) const; + std::vector& colors) const; /*! * \brief getEdgeColors * \param elements The sub-element names. If this list is empty \a colors will be filled with the default color. * \param colors The size of the \a colors array is equal to the number of edges of the shape */ void getEdgeColors(const std::vector& elements, - std::vector& colors) const; + std::vector& colors) const; /*! * \brief getFaceColors * \param elements The sub-element names. If this list is empty \a colors will be filled with the default color. * \param colors The size of the \a colors array is equal to the number of faces of the shape */ void getFaceColors(const std::vector& elements, - std::vector& colors) const; + std::vector& colors) const; /*! * \brief getFaceMaterials * \param elements The sub-element names. If this list is empty \a materials will be filled with @@ -89,20 +89,20 @@ public: std::vector& materials) const; private: - void getVertexColor(const std::string& element, std::vector& colors) const; - void getVertexColorsOfEdge(const std::string& element, std::vector& colors) const; - void getVertexColorsOfWire(const std::string& element, std::vector& colors) const; - void getVertexColorsOfFace(const std::string& element, std::vector& colors) const; - void getEdgeColor(const std::string& element, std::vector& colors) const; - void getEdgeColorsOfWire(const std::string& element, std::vector& colors) const; - void getEdgeColorsOfFace(const std::string& element, std::vector& colors) const; - void getFaceColor(const std::string& element, std::vector& colors) const; + void getVertexColor(const std::string& element, std::vector& colors) const; + void getVertexColorsOfEdge(const std::string& element, std::vector& colors) const; + void getVertexColorsOfWire(const std::string& element, std::vector& colors) const; + void getVertexColorsOfFace(const std::string& element, std::vector& colors) const; + void getEdgeColor(const std::string& element, std::vector& colors) const; + void getEdgeColorsOfWire(const std::string& element, std::vector& colors) const; + void getEdgeColorsOfFace(const std::string& element, std::vector& colors) const; + void getFaceColor(const std::string& element, std::vector& colors) const; void getFaceColor(const std::string& element, std::vector& materials) const; private: - App::Color defaultColor; - App::Color elementColor; - App::Color objectColor; + Base::Color defaultColor; + Base::Color elementColor; + Base::Color objectColor; TopTools_IndexedMapOfShape vMap; TopTools_IndexedMapOfShape eMap; TopTools_IndexedMapOfShape wMap; diff --git a/src/Mod/Part/Gui/SectionCutting.cpp b/src/Mod/Part/Gui/SectionCutting.cpp index b5dede0081..55043207c6 100644 --- a/src/Mod/Part/Gui/SectionCutting.cpp +++ b/src/Mod/Part/Gui/SectionCutting.cpp @@ -145,7 +145,7 @@ void SectionCut::initControls(const Base::BoundBox3d& BoundCompound) { // lambda function to set color and transparency auto setColorTransparency = [&](Part::Box* pcBox) { - App::Color cutColor; + Base::Color cutColor; long cutTransparency{}; auto vpBox = dynamic_cast( Gui::Application::Instance->getViewProvider(pcBox)); @@ -297,7 +297,7 @@ void SectionCut::initBooleanFragmentControls(Gui::ViewProviderGeometryObject* co ui->groupBoxIntersecting->setChecked(true); if (compoundBF) { - App::Color compoundColor = compoundBF->ShapeAppearance.getDiffuseColor(); + Base::Color compoundColor = compoundBF->ShapeAppearance.getDiffuseColor(); ui->BFragColor->setColor(compoundColor.asValue()); long compoundTransparency = compoundBF->Transparency.getValue(); ui->BFragTransparencyHS->setValue(int(compoundTransparency)); @@ -932,9 +932,9 @@ bool SectionCut::isCuttingEnabled() const } namespace { -App::Color getFirstColor(const std::vector& objects) +Base::Color getFirstColor(const std::vector& objects) { - App::Color cutColor; + Base::Color cutColor; auto vpFirstObject = dynamic_cast( Gui::Application::Instance->getViewProvider(objects.front())); if (vpFirstObject) { @@ -954,7 +954,7 @@ long getFirstTransparency(const std::vector& objects) return cutTransparency; } -bool isAutoColor(const App::Color& color, const std::vector& objects) +bool isAutoColor(const Base::Color& color, const std::vector& objects) { bool autoColor = true; for (auto itCuts : objects) { @@ -1278,7 +1278,7 @@ void SectionCut::processZBoxAndCut(const Args& args) void SectionCut::createAllObjects(const std::vector& ObjectsListCut) { // store color and transparency of first object - App::Color cutColor = getFirstColor(ObjectsListCut); + Base::Color cutColor = getFirstColor(ObjectsListCut); long cutTransparency = getFirstTransparency(ObjectsListCut); bool autoColor = true; bool autoTransparency = true; @@ -1325,7 +1325,7 @@ void SectionCut::createAllObjects(const std::vector& Objec } // read cutface color for the cut box - App::Color boxColor; + Base::Color boxColor; boxColor.setValue(ui->CutColor->color()); int boxTransparency = ui->CutTransparencyHS->value(); @@ -2052,7 +2052,7 @@ void SectionCut::changeCutBoxColors() auto boxVP = Gui::Application::Instance->getViewProvider(boxObject); auto boxVPGO = dynamic_cast(boxVP); if (boxVPGO) { - App::Color boxColor; + Base::Color boxColor; boxColor.setValue(ui->CutColor->color()); boxVPGO->ShapeAppearance.setDiffuseColor(boxColor); int boxTransparency = ui->CutTransparencyHS->value(); @@ -2160,7 +2160,7 @@ void SectionCut::setBooleanFragmentsColor() } auto CutCompoundBFGeom = dynamic_cast(CompoundBFVP); if (CutCompoundBFGeom) { - App::Color BFColor; + Base::Color BFColor; BFColor.setValue(ui->BFragColor->color()); CutCompoundBFGeom->ShapeAppearance.setDiffuseColor(BFColor); int BFTransparency = ui->BFragTransparencyHS->value(); diff --git a/src/Mod/Part/Gui/TaskFaceAppearances.cpp b/src/Mod/Part/Gui/TaskFaceAppearances.cpp index a1f2b5d6f3..bf0b89e467 100644 --- a/src/Mod/Part/Gui/TaskFaceAppearances.cpp +++ b/src/Mod/Part/Gui/TaskFaceAppearances.cpp @@ -369,9 +369,9 @@ void FaceAppearances::onSelectionChanged(const Gui::SelectionChanges& msg) if (docname == msg.pDocName && objname == msg.pObjectName) { int index = std::atoi(msg.pSubName + 4) - 1; d->index.insert(index); - const App::Color& faceColor = d->perface[index].diffuseColor; + const Base::Color& faceColor = d->perface[index].diffuseColor; QColor color; - // alpha of App::Color is contrary to the one of QColor + // alpha of Base::Color is contrary to the one of QColor color.setRgbF(faceColor.r, faceColor.g, faceColor.b, (1.0 - faceColor.a)); selection_changed = true; } diff --git a/src/Mod/Part/Gui/ViewProvider.cpp b/src/Mod/Part/Gui/ViewProvider.cpp index 9174a2526e..f0e34d685f 100644 --- a/src/Mod/Part/Gui/ViewProvider.cpp +++ b/src/Mod/Part/Gui/ViewProvider.cpp @@ -60,8 +60,8 @@ bool ViewProviderPart::doubleClicked() } void ViewProviderPart::applyColor(const Part::ShapeHistory& hist, - const std::vector& colBase, - std::vector& colBool) + const std::vector& colBase, + std::vector& colBool) { // apply color from modified faces for (const auto& jt : hist.shapeMap) { @@ -83,7 +83,7 @@ void ViewProviderPart::applyMaterial(const Part::ShapeHistory& hist, } } -void ViewProviderPart::applyTransparency(float transparency, std::vector& colors) +void ViewProviderPart::applyTransparency(float transparency, std::vector& colors) { if (transparency != 0.0) { // transparency has been set object-wide diff --git a/src/Mod/Part/Gui/ViewProvider.h b/src/Mod/Part/Gui/ViewProvider.h index 1286a9a53d..1c12497eea 100644 --- a/src/Mod/Part/Gui/ViewProvider.h +++ b/src/Mod/Part/Gui/ViewProvider.h @@ -55,12 +55,12 @@ public: protected: void applyColor(const Part::ShapeHistory& hist, - const std::vector& colBase, - std::vector& colBool); + const std::vector& colBase, + std::vector& colBool); void applyMaterial(const Part::ShapeHistory& hist, const std::vector& colBase, std::vector& colBool); - void applyTransparency(float transparency, std::vector& colors); + void applyTransparency(float transparency, std::vector& colors); void applyTransparency(float transparency, std::vector& colors); }; diff --git a/src/Mod/Part/Gui/ViewProvider2DObject.cpp b/src/Mod/Part/Gui/ViewProvider2DObject.cpp index e9b62513bf..50f8a20502 100644 --- a/src/Mod/Part/Gui/ViewProvider2DObject.cpp +++ b/src/Mod/Part/Gui/ViewProvider2DObject.cpp @@ -396,6 +396,12 @@ void ViewProvider2DObject::updatePlane() Base::ViewOrthoProjMatrix proj(place.inverse().toMatrix()); Base::BoundBox2d bb = bbox.ProjectBox(&proj); + // when projection of invalid it often results in infinite shapes + // if that happens we simply use some small bounding box to mark plane + if (bb.IsInfinite() || !bb.IsValid()) { + bb = Base::BoundBox2d(-1, -1, 1, 1); + } + SbVec3f verts[4] = { SbVec3f(bb.MinX - horizontalPlanePadding, bb.MinY - verticalPlanePadding, 0), SbVec3f(bb.MinX - horizontalPlanePadding, bb.MaxY + verticalPlanePadding, 0), diff --git a/src/Mod/Part/Gui/ViewProvider2DObject.h b/src/Mod/Part/Gui/ViewProvider2DObject.h index 47280be184..19d34b4f72 100644 --- a/src/Mod/Part/Gui/ViewProvider2DObject.h +++ b/src/Mod/Part/Gui/ViewProvider2DObject.h @@ -42,7 +42,7 @@ class PartGuiExport ViewProvider2DObject : public PartGui::ViewProviderPart PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProvider2DObject); static constexpr float horizontalPlanePadding = 8; - static constexpr float verticalPlanePadding = 5; + static constexpr float verticalPlanePadding = 6; public: /// constructor diff --git a/src/Mod/Part/Gui/ViewProviderExt.cpp b/src/Mod/Part/Gui/ViewProviderExt.cpp index df63366b1f..5e2a4cfa04 100644 --- a/src/Mod/Part/Gui/ViewProviderExt.cpp +++ b/src/Mod/Part/Gui/ViewProviderExt.cpp @@ -292,14 +292,14 @@ void ViewProviderPartExt::onChanged(const App::Property* prop) pcPointStyle->pointSize = PointSize.getValue(); } else if (prop == &LineColor) { - const App::Color& c = LineColor.getValue(); + const Base::Color& c = LineColor.getValue(); pcLineMaterial->diffuseColor.setValue(c.r,c.g,c.b); if (c != LineMaterial.getValue().diffuseColor) LineMaterial.setDiffuseColor(c); LineColorArray.setValue(LineColor.getValue()); } else if (prop == &PointColor) { - const App::Color& c = PointColor.getValue(); + const Base::Color& c = PointColor.getValue(); pcPointMaterial->diffuseColor.setValue(c.r,c.g,c.b); if (c != PointMaterial.getValue().diffuseColor) PointMaterial.setDiffuseColor(c); @@ -335,7 +335,7 @@ void ViewProviderPartExt::onChanged(const App::Property* prop) } else if (prop == &_diffuseColor) { // Used to load the old DiffuseColor values asynchronously - std::vector colors = _diffuseColor.getValues(); + std::vector colors = _diffuseColor.getValues(); std::vector transparencies; transparencies.resize(static_cast(colors.size())); for (int i = 0; i < static_cast(colors.size()); i++) { @@ -658,8 +658,8 @@ void ViewProviderPartExt::setHighlightedFaces(const App::PropertyMaterialList& a setHighlightedFaces(appearance.getValues()); } -std::map ViewProviderPartExt::getElementColors(const char *element) const { - std::map ret; +std::map ViewProviderPartExt::getElementColors(const char *element) const { + std::map ret; if(!element || !element[0]) { auto color = ShapeAppearance.getDiffuseColor(); @@ -753,7 +753,7 @@ void ViewProviderPartExt::unsetHighlightedFaces() Transparency.touch(); } -void ViewProviderPartExt::setHighlightedEdges(const std::vector& colors) +void ViewProviderPartExt::setHighlightedEdges(const std::vector& colors) { if (getObject() && getObject()->testStatus(App::ObjectStatus::TouchOnColorChange)) getObject()->touch(true); @@ -790,7 +790,7 @@ void ViewProviderPartExt::unsetHighlightedEdges() LineMaterial.touch(); } -void ViewProviderPartExt::setHighlightedPoints(const std::vector& colors) +void ViewProviderPartExt::setHighlightedPoints(const std::vector& colors) { if (getObject() && getObject()->testStatus(App::ObjectStatus::TouchOnColorChange)) getObject()->touch(true); diff --git a/src/Mod/Part/Gui/ViewProviderExt.h b/src/Mod/Part/Gui/ViewProviderExt.h index 2682835ff1..4234451d02 100644 --- a/src/Mod/Part/Gui/ViewProviderExt.h +++ b/src/Mod/Part/Gui/ViewProviderExt.h @@ -76,6 +76,7 @@ public: App::PropertyAngle AngularDeflection; App::PropertyEnumeration Lighting; App::PropertyEnumeration DrawStyle; + App::PropertyBool ShowPlacement; // Points App::PropertyFloatConstraint PointSize; App::PropertyColor PointColor; @@ -127,16 +128,16 @@ public: void setHighlightedFaces(const std::vector& materials); void setHighlightedFaces(const App::PropertyMaterialList& appearance); void unsetHighlightedFaces(); - void setHighlightedEdges(const std::vector& colors); + void setHighlightedEdges(const std::vector& colors); void unsetHighlightedEdges(); - void setHighlightedPoints(const std::vector& colors); + void setHighlightedPoints(const std::vector& colors); void unsetHighlightedPoints(); //@} /** @name Color management methods */ //@{ - std::map getElementColors(const char *element=nullptr) const override; + std::map getElementColors(const char *element=nullptr) const override; //@} bool isUpdateForced() const override { diff --git a/src/Mod/Part/Gui/ViewProviderGridExtension.cpp b/src/Mod/Part/Gui/ViewProviderGridExtension.cpp index 9b6130c7b6..d0d0a84eee 100644 --- a/src/Mod/Part/Gui/ViewProviderGridExtension.cpp +++ b/src/Mod/Part/Gui/ViewProviderGridExtension.cpp @@ -523,13 +523,13 @@ void ViewProviderGridExtension::setGridDivLineWidth(int width) drawGrid(false); } -void ViewProviderGridExtension::setGridLineColor(const App::Color & color) +void ViewProviderGridExtension::setGridLineColor(const Base::Color & color) { pImpl->GridLineColor = color.getPackedValue(); drawGrid(false); } -void ViewProviderGridExtension::setGridDivLineColor(const App::Color & color) +void ViewProviderGridExtension::setGridDivLineColor(const Base::Color & color) { pImpl->GridDivLineColor = color.getPackedValue(); drawGrid(false); diff --git a/src/Mod/Part/Gui/ViewProviderGridExtension.h b/src/Mod/Part/Gui/ViewProviderGridExtension.h index 872b62ac78..f480b0204d 100644 --- a/src/Mod/Part/Gui/ViewProviderGridExtension.h +++ b/src/Mod/Part/Gui/ViewProviderGridExtension.h @@ -76,8 +76,8 @@ protected: void setGridDivLinePattern(int pattern); void setGridLineWidth(int width); void setGridDivLineWidth(int width); - void setGridLineColor(const App::Color & color); - void setGridDivLineColor(const App::Color & color); + void setGridLineColor(const Base::Color & color); + void setGridDivLineColor(const Base::Color & color); bool extensionHandleChangedPropertyType(Base::XMLReader &reader, const char * TypeName, App::Property * prop) override; diff --git a/src/Mod/Part/Gui/ViewProviderPartExtPyImp.cpp b/src/Mod/Part/Gui/ViewProviderPartExtPyImp.cpp index d54580160a..301033a50c 100644 --- a/src/Mod/Part/Gui/ViewProviderPartExtPyImp.cpp +++ b/src/Mod/Part/Gui/ViewProviderPartExtPyImp.cpp @@ -52,7 +52,7 @@ PyObject* ViewProviderPartExtPy::getCustomAttributes(const char* attr) const // Get the color properties App::PropertyColorList prop; - std::vector colors = vp->ShapeAppearance.getDiffuseColors(); + std::vector colors = vp->ShapeAppearance.getDiffuseColors(); std::vector transparencies = vp->ShapeAppearance.getTransparencies(); for (int i = 0; i < static_cast(colors.size()); i++) { colors[i].setTransparency(transparencies[i]); @@ -72,7 +72,7 @@ int ViewProviderPartExtPy::setCustomAttributes(const char* attr, PyObject* obj) App::PropertyColorList prop; prop.setPyObject(obj); - std::vector colors = prop.getValues(); + std::vector colors = prop.getValues(); std::vector transparencies; transparencies.resize(static_cast(colors.size())); for (int i = 0; i < static_cast(colors.size()); i++) { diff --git a/src/Mod/Part/Gui/ViewProviderReference.cpp b/src/Mod/Part/Gui/ViewProviderReference.cpp index 14a45ffe4e..d6f272d076 100644 --- a/src/Mod/Part/Gui/ViewProviderReference.cpp +++ b/src/Mod/Part/Gui/ViewProviderReference.cpp @@ -122,13 +122,13 @@ void ViewProviderPartReference::onChanged(const App::Property* /*prop*/) // pcPointStyle->pointSize = PointSize.getValue(); //} //else if (prop == &LineColor) { - // const App::Color& c = LineColor.getValue(); + // const Base::Color& c = LineColor.getValue(); // pcLineMaterial->diffuseColor.setValue(c.r,c.g,c.b); // if (c != LineMaterial.getValue().diffuseColor) // LineMaterial.setDiffuseColor(c); //} //else if (prop == &PointColor) { - // const App::Color& c = PointColor.getValue(); + // const Base::Color& c = PointColor.getValue(); // pcPointMaterial->diffuseColor.setValue(c.r,c.g,c.b); // if (c != PointMaterial.getValue().diffuseColor) // PointMaterial.setDiffuseColor(c); diff --git a/src/Mod/PartDesign/App/CMakeLists.txt b/src/Mod/PartDesign/App/CMakeLists.txt index af96682011..9f08b749c4 100644 --- a/src/Mod/PartDesign/App/CMakeLists.txt +++ b/src/Mod/PartDesign/App/CMakeLists.txt @@ -3,6 +3,10 @@ include_directories( ${CMAKE_SOURCE_DIR}/src ${CMAKE_BINARY_DIR}/src ${CMAKE_CURRENT_BINARY_DIR} +) + +include_directories( + SYSTEM ${Boost_INCLUDE_DIRS} ${OCC_INCLUDE_DIR} ${QT_INCLUDE_DIR} diff --git a/src/Mod/PartDesign/Gui/CMakeLists.txt b/src/Mod/PartDesign/Gui/CMakeLists.txt index 7a77f03dfb..a485f8848d 100644 --- a/src/Mod/PartDesign/Gui/CMakeLists.txt +++ b/src/Mod/PartDesign/Gui/CMakeLists.txt @@ -2,6 +2,10 @@ include_directories( ${CMAKE_BINARY_DIR} ${CMAKE_SOURCE_DIR}/src ${CMAKE_CURRENT_BINARY_DIR} +) + +include_directories( + SYSTEM ${Boost_INCLUDE_DIRS} ${OCC_INCLUDE_DIR} ${COIN3D_INCLUDE_DIRS} diff --git a/src/Mod/PartDesign/Gui/ViewProviderDatum.cpp b/src/Mod/PartDesign/Gui/ViewProviderDatum.cpp index 2f6193fdfe..433935a5a5 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderDatum.cpp +++ b/src/Mod/PartDesign/Gui/ViewProviderDatum.cpp @@ -83,7 +83,7 @@ ViewProviderDatum::ViewProviderDatum() "User parameter:BaseApp/Preferences/Mod/PartDesign"); unsigned long shcol = hGrp->GetUnsigned ( "DefaultDatumColor", 0xFFD70099 ); - App::Color col ( (uint32_t) shcol ); + Base::Color col ( (uint32_t) shcol ); ShapeAppearance.setDiffuseColor(col); Transparency.setValue (col.a * 100); diff --git a/src/Mod/PartDesign/Gui/ViewProviderDressUp.cpp b/src/Mod/PartDesign/Gui/ViewProviderDressUp.cpp index 0dcf6afded..7046c0a418 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderDressUp.cpp +++ b/src/Mod/PartDesign/Gui/ViewProviderDressUp.cpp @@ -108,7 +108,7 @@ void ViewProviderDressUp::highlightReferences(const bool on) vp->setHighlightedFaces(materials); } if (!edges.empty()) { - std::vector colors = vp->LineColorArray.getValues(); + std::vector colors = vp->LineColorArray.getValues(); PartGui::ReferenceHighlighter highlighter(base->Shape.getValue(), LineColor.getValue()); highlighter.getEdgeColors(edges, colors); diff --git a/src/Mod/PartDesign/Gui/ViewProviderLoft.cpp b/src/Mod/PartDesign/Gui/ViewProviderLoft.cpp index 31ef046e36..6e11dbd4f3 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderLoft.cpp +++ b/src/Mod/PartDesign/Gui/ViewProviderLoft.cpp @@ -153,11 +153,11 @@ void ViewProviderLoft::highlightReferences(Part::Feature* base, const std::vecto if (!svp) return; - std::vector& edgeColors = originalLineColors[base->getID()]; + std::vector& edgeColors = originalLineColors[base->getID()]; if (on) { edgeColors = svp->LineColorArray.getValues(); - std::vector colors = edgeColors; + std::vector colors = edgeColors; PartGui::ReferenceHighlighter highlighter(base->Shape.getValue(), svp->LineColor.getValue()); highlighter.getEdgeColors(elements, colors); diff --git a/src/Mod/PartDesign/Gui/ViewProviderLoft.h b/src/Mod/PartDesign/Gui/ViewProviderLoft.h index 56dc3fb9e6..0f780d6f31 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderLoft.h +++ b/src/Mod/PartDesign/Gui/ViewProviderLoft.h @@ -63,7 +63,7 @@ private: void highlightReferences(Part::Feature*, const std::vector&, bool); private: - std::map> originalLineColors; + std::map> originalLineColors; }; diff --git a/src/Mod/PartDesign/Gui/ViewProviderPipe.cpp b/src/Mod/PartDesign/Gui/ViewProviderPipe.cpp index d0577253f8..044a52dd85 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderPipe.cpp +++ b/src/Mod/PartDesign/Gui/ViewProviderPipe.cpp @@ -151,12 +151,12 @@ void ViewProviderPipe::highlightReferences(Part::Feature* base, const std::vecto if (!svp) return; - std::vector& edgeColors = originalLineColors[base->getID()]; + std::vector& edgeColors = originalLineColors[base->getID()]; if (on) { if (edgeColors.empty()) { edgeColors = svp->LineColorArray.getValues(); - std::vector colors = edgeColors; + std::vector colors = edgeColors; PartGui::ReferenceHighlighter highlighter(base->Shape.getValue(), svp->LineColor.getValue()); highlighter.getEdgeColors(edges, colors); diff --git a/src/Mod/PartDesign/Gui/ViewProviderPipe.h b/src/Mod/PartDesign/Gui/ViewProviderPipe.h index cae4cf1219..3526668415 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderPipe.h +++ b/src/Mod/PartDesign/Gui/ViewProviderPipe.h @@ -64,7 +64,7 @@ private: void highlightReferences(Part::Feature*, const std::vector&, bool); private: - std::map> originalLineColors; + std::map> originalLineColors; }; diff --git a/src/Mod/PartDesign/Gui/ViewProviderShapeBinder.cpp b/src/Mod/PartDesign/Gui/ViewProviderShapeBinder.cpp index ceffb62a5a..ee07d3b742 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderShapeBinder.cpp +++ b/src/Mod/PartDesign/Gui/ViewProviderShapeBinder.cpp @@ -70,7 +70,7 @@ ViewProviderShapeBinder::ViewProviderShapeBinder() ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( "User parameter:BaseApp/Preferences/Mod/PartDesign"); unsigned long shcol = hGrp->GetUnsigned("DefaultDatumColor", 0xFFD70099); - App::Color col((uint32_t)shcol); + Base::Color col((uint32_t)shcol); ShapeAppearance.setDiffuseColor(col); LineColor.setValue(col); @@ -157,7 +157,7 @@ void ViewProviderShapeBinder::highlightReferences(bool on) TopTools_IndexedMapOfShape eMap; TopExp::MapShapes(static_cast(obj)->Shape.getValue(), TopAbs_EDGE, eMap); originalLineColors = svp->LineColorArray.getValues(); - std::vector lcolors = originalLineColors; + std::vector lcolors = originalLineColors; lcolors.resize(eMap.Extent(), svp->LineColor.getValue()); TopExp::MapShapes(static_cast(obj)->Shape.getValue(), TopAbs_FACE, eMap); @@ -171,13 +171,13 @@ void ViewProviderShapeBinder::highlightReferences(bool on) int idx = std::stoi(e.substr(4)) - 1; assert(idx >= 0); if (idx < static_cast(lcolors.size())) - lcolors[idx] = App::Color(1.0, 0.0, 1.0); // magenta + lcolors[idx] = Base::Color(1.0, 0.0, 1.0); // magenta } else if (e.compare(0, 4, "Face") == 0) { int idx = std::stoi(e.substr(4)) - 1; assert(idx >= 0); if (idx < static_cast(fcolors.size())) - fcolors[idx].diffuseColor = App::Color(1.0, 0.0, 1.0); // magenta + fcolors[idx].diffuseColor = Base::Color(1.0, 0.0, 1.0); // magenta } } svp->LineColorArray.setValues(lcolors); @@ -239,7 +239,7 @@ void ViewProviderSubShapeBinder::onChanged(const App::Property* prop) { if (prop == &UseBinderStyle && (!getObject() || !getObject()->isRestoring())) { - App::Color shapeColor, lineColor, pointColor; + Base::Color shapeColor, lineColor, pointColor; int transparency, linewidth; if (UseBinderStyle.getValue()) { //get the datum coloring scheme diff --git a/src/Mod/PartDesign/Gui/ViewProviderShapeBinder.h b/src/Mod/PartDesign/Gui/ViewProviderShapeBinder.h index cdaea2b2bc..6aa012472b 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderShapeBinder.h +++ b/src/Mod/PartDesign/Gui/ViewProviderShapeBinder.h @@ -47,7 +47,7 @@ protected: void attach(App::DocumentObject *obj) override; private: - std::vector originalLineColors; + std::vector originalLineColors; std::vector originalFaceAppearance; }; diff --git a/src/Mod/Points/App/CMakeLists.txt b/src/Mod/Points/App/CMakeLists.txt index 8914a44df2..48f9a8f6a6 100644 --- a/src/Mod/Points/App/CMakeLists.txt +++ b/src/Mod/Points/App/CMakeLists.txt @@ -5,6 +5,10 @@ endif(WIN32) include_directories( ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_CURRENT_SOURCE_DIR} +) + +include_directories( + SYSTEM ${Boost_INCLUDE_DIRS} ${EIGEN3_INCLUDE_DIR} ${PYCXX_INCLUDE_DIR} @@ -21,6 +25,7 @@ set(Points_LIBS ) include_directories( + SYSTEM ${QtConcurrent_INCLUDE_DIRS} ) list(APPEND Points_LIBS diff --git a/src/Mod/Points/App/PointsAlgos.cpp b/src/Mod/Points/App/PointsAlgos.cpp index 029e2f3a98..5f93ad0edc 100644 --- a/src/Mod/Points/App/PointsAlgos.cpp +++ b/src/Mod/Points/App/PointsAlgos.cpp @@ -155,7 +155,7 @@ bool Reader::hasIntensities() const return (!intensity.empty()); } -const std::vector& Reader::getColors() const +const std::vector& Reader::getColors() const { return colors; } @@ -1166,7 +1166,7 @@ void PcdReader::read(const std::string& filename) if (types[rgba] == "U") { for (Eigen::Index i = 0; i < numPoints; i++) { uint32_t packed = static_cast(data(i, rgba)); - App::Color col; + Base::Color col; col.setPackedARGB(packed); colors.emplace_back(col); } @@ -1178,7 +1178,7 @@ void PcdReader::read(const std::string& filename) float f = static_cast(data(i, rgba)); uint32_t packed {}; std::memcpy(&packed, &f, sizeof(packed)); - App::Color col; + Base::Color col; col.setPackedARGB(packed); colors.emplace_back(col); } @@ -1413,7 +1413,7 @@ public: } } - std::vector getColors() const + std::vector getColors() const { return colors; } @@ -1705,9 +1705,9 @@ private: return pt; } - App::Color getColor(const Proto& proto, size_t index) const + Base::Color getColor(const Proto& proto, size_t index) const { - App::Color c; + Base::Color c; c.r = static_cast(proto.redData[index]) / 255.0F; c.g = static_cast(proto.greenData[index]) / 255.0F; c.b = static_cast(proto.blueData[index]) / 255.0F; @@ -1769,7 +1769,7 @@ private: bool checkState; double minDistance; const size_t buf_size = 1024; - std::vector colors; + std::vector colors; std::vector intensity; PointKernel points; std::vector normals; @@ -1817,7 +1817,7 @@ void Writer::setIntensities(const std::vector& i) intensity = i; } -void Writer::setColors(const std::vector& c) +void Writer::setColors(const std::vector& c) { colors = c; } @@ -1972,7 +1972,7 @@ void PlyWriter::write(const std::string& filename) Eigen::Index col2 = col + 2; Eigen::Index col3 = col + 3; for (Eigen::Index i = 0; i < numPoints; i++) { - App::Color c = colors[i]; + Base::Color c = colors[i]; data(i, col0) = (c.r * 255.0F + 0.5F); data(i, col1) = (c.g * 255.0F + 0.5F); data(i, col2) = (c.b * 255.0F + 0.5F); diff --git a/src/Mod/Points/App/PointsAlgos.h b/src/Mod/Points/App/PointsAlgos.h index 5306500700..dba8373d6f 100644 --- a/src/Mod/Points/App/PointsAlgos.h +++ b/src/Mod/Points/App/PointsAlgos.h @@ -57,7 +57,7 @@ public: bool hasProperties() const; const std::vector& getIntensities() const; bool hasIntensities() const; - const std::vector& getColors() const; + const std::vector& getColors() const; bool hasColors() const; const std::vector& getNormals() const; bool hasNormals() const; @@ -74,7 +74,7 @@ protected: // NOLINTBEGIN PointKernel points; std::vector intensity; - std::vector colors; + std::vector colors; std::vector normals; int width {0}; int height {1}; @@ -149,7 +149,7 @@ public: virtual void write(const std::string& filename) = 0; void setIntensities(const std::vector&); - void setColors(const std::vector&); + void setColors(const std::vector&); void setNormals(const std::vector&); void setWidth(int); void setHeight(int); @@ -164,7 +164,7 @@ protected: // NOLINTBEGIN const PointKernel& points; std::vector intensity; - std::vector colors; + std::vector colors; std::vector normals; int width, height; Base::Placement placement; diff --git a/src/Mod/Points/Gui/CMakeLists.txt b/src/Mod/Points/Gui/CMakeLists.txt index 39de345442..e0e19fbbad 100644 --- a/src/Mod/Points/Gui/CMakeLists.txt +++ b/src/Mod/Points/Gui/CMakeLists.txt @@ -1,5 +1,9 @@ include_directories( ${CMAKE_CURRENT_BINARY_DIR} +) + +include_directories( + SYSTEM ${Boost_INCLUDE_DIRS} ${COIN3D_INCLUDE_DIRS} ${EIGEN3_INCLUDE_DIR} diff --git a/src/Mod/Points/Gui/ViewProvider.cpp b/src/Mod/Points/Gui/ViewProvider.cpp index 237ca9735a..95b8c85919 100644 --- a/src/Mod/Points/Gui/ViewProvider.cpp +++ b/src/Mod/Points/Gui/ViewProvider.cpp @@ -113,7 +113,7 @@ void ViewProviderPoints::onChanged(const App::Property* prop) void ViewProviderPoints::setVertexColorMode(App::PropertyColorList* pcProperty) { - const std::vector& val = pcProperty->getValues(); + const std::vector& val = pcProperty->getValues(); pcColorMat->diffuseColor.setNum(val.size()); SbColor* col = pcColorMat->diffuseColor.startEditing(); @@ -500,18 +500,18 @@ void ViewProviderScattered::cut(const std::vector& picked, } else if (type == App::PropertyColorList::getClassTypeId()) { // static_cast(it->second)->removeIndices(removeIndices); - const std::vector& colors = + const std::vector& colors = static_cast(it.second)->getValues(); if (removeIndices.size() > colors.size()) { break; } - std::vector remainValue; + std::vector remainValue; remainValue.reserve(colors.size() - removeIndices.size()); std::vector::iterator pos = removeIndices.begin(); - for (std::vector::const_iterator jt = colors.begin(); jt != colors.end(); + for (std::vector::const_iterator jt = colors.begin(); jt != colors.end(); ++jt) { unsigned long index = jt - colors.begin(); if (pos == removeIndices.end()) { diff --git a/src/Mod/ReverseEngineering/App/CMakeLists.txt b/src/Mod/ReverseEngineering/App/CMakeLists.txt index 221d71d379..1297c88eb7 100644 --- a/src/Mod/ReverseEngineering/App/CMakeLists.txt +++ b/src/Mod/ReverseEngineering/App/CMakeLists.txt @@ -20,6 +20,10 @@ endif () include_directories( ${CMAKE_SOURCE_DIR}/src +) + +include_directories( + SYSTEM ${Boost_INCLUDE_DIRS} ${OCC_INCLUDE_DIR} ${PYCXX_INCLUDE_DIR} diff --git a/src/Mod/ReverseEngineering/Gui/CMakeLists.txt b/src/Mod/ReverseEngineering/Gui/CMakeLists.txt index b36b05a4c0..bf3f2715c2 100644 --- a/src/Mod/ReverseEngineering/Gui/CMakeLists.txt +++ b/src/Mod/ReverseEngineering/Gui/CMakeLists.txt @@ -2,6 +2,10 @@ include_directories( ${CMAKE_BINARY_DIR} ${CMAKE_SOURCE_DIR}/src ${CMAKE_CURRENT_BINARY_DIR} +) + +include_directories( + SYSTEM ${Boost_INCLUDE_DIRS} ${OCC_INCLUDE_DIR} ${COIN3D_INCLUDE_DIRS} diff --git a/src/Mod/Robot/App/CMakeLists.txt b/src/Mod/Robot/App/CMakeLists.txt index 6d9f49c9c4..62161595ff 100644 --- a/src/Mod/Robot/App/CMakeLists.txt +++ b/src/Mod/Robot/App/CMakeLists.txt @@ -3,6 +3,10 @@ include_directories( ${CMAKE_SOURCE_DIR}/src ${CMAKE_BINARY_DIR}/src ${CMAKE_CURRENT_BINARY_DIR} +) + +include_directories( + SYSTEM ${Boost_INCLUDE_DIRS} ${OCC_INCLUDE_DIR} ${EIGEN3_INCLUDE_DIR} diff --git a/src/Mod/Robot/Gui/CMakeLists.txt b/src/Mod/Robot/Gui/CMakeLists.txt index 5858b7404f..6283f10e23 100644 --- a/src/Mod/Robot/Gui/CMakeLists.txt +++ b/src/Mod/Robot/Gui/CMakeLists.txt @@ -2,6 +2,10 @@ include_directories( ${CMAKE_BINARY_DIR} ${CMAKE_SOURCE_DIR}/src ${CMAKE_CURRENT_BINARY_DIR} +) + +include_directories( + SYSTEM ${Boost_INCLUDE_DIRS} ${COIN3D_INCLUDE_DIRS} ${ZLIB_INCLUDE_DIR} diff --git a/src/Mod/Sandbox/App/CMakeLists.txt b/src/Mod/Sandbox/App/CMakeLists.txt index af660d7b5b..2fe8ef802d 100644 --- a/src/Mod/Sandbox/App/CMakeLists.txt +++ b/src/Mod/Sandbox/App/CMakeLists.txt @@ -5,6 +5,10 @@ endif(WIN32) include_directories( ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_CURRENT_SOURCE_DIR} +) + +include_directories( + SYSTEM ${Boost_INCLUDE_DIRS} ${PYCXX_INCLUDE_DIR} ${Python3_INCLUDE_DIRS} @@ -14,10 +18,12 @@ include_directories( if (BUILD_QT5) include_directories( + SYSTEM ${Qt5Core_INCLUDE_DIRS} ) else() include_directories( + SYSTEM ${QT_INCLUDE_DIR} ) endif() diff --git a/src/Mod/Sandbox/Gui/CMakeLists.txt b/src/Mod/Sandbox/Gui/CMakeLists.txt index 1d8c8c6901..a352d0378e 100644 --- a/src/Mod/Sandbox/Gui/CMakeLists.txt +++ b/src/Mod/Sandbox/Gui/CMakeLists.txt @@ -1,6 +1,10 @@ include_directories( ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_SOURCE_DIR}/src/Gui +) + +include_directories( + SYSTEM ${Boost_INCLUDE_DIRS} ${COIN3D_INCLUDE_DIRS} ${OCC_INCLUDE_DIR} @@ -13,10 +17,13 @@ include_directories( if(BUILD_QT5) include_directories( + SYSTEM ${Qt5Core_INCLUDE_DIRS} ) else() + SYSTEM include_directories( + SYSTEM ${QT_INCLUDE_DIR} ) endif() diff --git a/src/Mod/Sandbox/Gui/Overlay.cpp b/src/Mod/Sandbox/Gui/Overlay.cpp index 2bf24b86b1..a41b128e61 100644 --- a/src/Mod/Sandbox/Gui/Overlay.cpp +++ b/src/Mod/Sandbox/Gui/Overlay.cpp @@ -30,8 +30,6 @@ # include #endif -#include - #include #include #include @@ -47,7 +45,7 @@ using namespace SandboxGui; class MyPaintable : public Gui::GLGraphicsItem { - QtGLFramebufferObject* fbo; + QOpenGLFramebufferObject* fbo; Gui::View3DInventorViewer* view; QImage img; public: @@ -63,7 +61,7 @@ public: p.drawText(200,200,QStringLiteral("Render to QImage")); } - fbo = new QtGLFramebufferObject(v->getGLWidget()->size()); + fbo = new QOpenGLFramebufferObject(v->getGLWidget()->size()); fbo->bind(); fbo->release(); @@ -92,7 +90,7 @@ public: class Teapots : public Gui::GLGraphicsItem { - QtGLFramebufferObject *fbObject; + QOpenGLFramebufferObject *fbObject; GLuint glTeapotObject; QPoint rubberBandCorner1; QPoint rubberBandCorner2; @@ -106,8 +104,8 @@ Teapots(Gui::View3DInventorViewer* v) :view(v) SbVec2s size = vp.getViewportSizePixels(); rubberBandIsShown = false; - fbObject = new QtGLFramebufferObject(size[0],size[1], - QtGLFramebufferObject::Depth); + fbObject = new QOpenGLFramebufferObject(size[0],size[1], + QOpenGLFramebufferObject::Depth); resizeGL(size[0],size[1]); rubberBandIsShown = true; @@ -332,7 +330,7 @@ DrawingPlane::~DrawingPlane() void DrawingPlane::initialize() { - fbo = new QtGLFramebufferObject(128, 128,QtGLFramebufferObject::Depth); + fbo = new QOpenGLFramebufferObject(128, 128,QOpenGLFramebufferObject::Depth); } void DrawingPlane::terminate() @@ -353,7 +351,7 @@ void DrawingPlane::draw () {return; if (1/*mustRedraw*/) { SbVec2s view = _pcView3D->getSoRenderManager()->getSize(); - static_cast(_pcView3D->getGLWidget())->makeCurrent(); + static_cast(_pcView3D->getGLWidget())->makeCurrent(); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); diff --git a/src/Mod/Sandbox/Gui/Overlay.h b/src/Mod/Sandbox/Gui/Overlay.h index b4342087df..814f0f3269 100644 --- a/src/Mod/Sandbox/Gui/Overlay.h +++ b/src/Mod/Sandbox/Gui/Overlay.h @@ -24,7 +24,6 @@ #ifndef SANDBOXGUI_OVERLAY_H #define SANDBOXGUI_OVERLAY_H -#include #include #include #include @@ -55,7 +54,7 @@ private: QPoint lastPoint; QList selection; - QtGLFramebufferObject* fbo; + QOpenGLFramebufferObject* fbo; }; } // SandboxGui diff --git a/src/Mod/Sandbox/Gui/Workbench.cpp b/src/Mod/Sandbox/Gui/Workbench.cpp index 2db48a096a..2041262465 100644 --- a/src/Mod/Sandbox/Gui/Workbench.cpp +++ b/src/Mod/Sandbox/Gui/Workbench.cpp @@ -34,8 +34,6 @@ # include #endif -#include - #include "Workbench.h" #include #include diff --git a/src/Mod/Sketcher/App/CMakeLists.txt b/src/Mod/Sketcher/App/CMakeLists.txt index 07581f3767..fec02c6214 100644 --- a/src/Mod/Sketcher/App/CMakeLists.txt +++ b/src/Mod/Sketcher/App/CMakeLists.txt @@ -14,6 +14,10 @@ include_directories( ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/.. ${CMAKE_CURRENT_BINARY_DIR}/.. +) + +include_directories( + SYSTEM ${Boost_INCLUDE_DIRS} ${OCC_INCLUDE_DIR} ${ZIPIOS_INCLUDES} diff --git a/src/Mod/Sketcher/App/SketchObject.cpp b/src/Mod/Sketcher/App/SketchObject.cpp index cfdceca3e6..776e1cc11e 100644 --- a/src/Mod/Sketcher/App/SketchObject.cpp +++ b/src/Mod/Sketcher/App/SketchObject.cpp @@ -113,6 +113,7 @@ #include "SolverGeometryExtension.h" #include "ExternalGeometryFacade.h" +#include #undef DEBUG @@ -8265,6 +8266,9 @@ void SketchObject::validateExternalLinks() const Part::Datum* datum = static_cast(Obj); refSubShape = datum->getShape(); } + else if (Obj->isDerivedFrom()) { + // do nothing - shape will be calculated later during rebuild + } else { const Part::Feature* refObj = static_cast(Obj); const Part::TopoShape& refShape = refObj->Shape.getShape(); @@ -9202,6 +9206,35 @@ void SketchObject::rebuildExternalGeometry(std::optional extToAdd TopoDS_Face f = TopoDS::Face(fBuilder.Shape()); refSubShape = f; } + else if (Obj->isDerivedFrom()) { + auto* line = static_cast(Obj); + Base::Placement plm = line->Placement.getValue(); + Base::Vector3d base = plm.getPosition(); + Base::Vector3d dir = line->getDirection(); + gp_Lin l(gp_Pnt(base.x, base.y, base.z), gp_Dir(dir.x, dir.y, dir.z)); + BRepBuilderAPI_MakeEdge eBuilder(l); + if (!eBuilder.IsDone()) { + throw Base::RuntimeError( + "Sketcher: addExternal(): Failed to build edge from Part::DatumLine"); + } + + TopoDS_Edge e = TopoDS::Edge(eBuilder.Shape()); + refSubShape = e; + } + else if (Obj->isDerivedFrom()) { + auto* point = static_cast(Obj); + Base::Placement plm = point->Placement.getValue(); + Base::Vector3d base = plm.getPosition(); + gp_Pnt p(base.x, base.y, base.z); + BRepBuilderAPI_MakeVertex eBuilder(p); + if (!eBuilder.IsDone()) { + throw Base::RuntimeError( + "Sketcher: addExternal(): Failed to build vertex from Part::DatumPoint"); + } + + TopoDS_Vertex v = TopoDS::Vertex(eBuilder.Shape()); + refSubShape = v; + } else { throw Base::TypeError( "Datum feature type is not yet supported as external geometry for a sketch"); diff --git a/src/Mod/Sketcher/Gui/CMakeLists.txt b/src/Mod/Sketcher/Gui/CMakeLists.txt index 0588699a22..12d0477e86 100644 --- a/src/Mod/Sketcher/Gui/CMakeLists.txt +++ b/src/Mod/Sketcher/Gui/CMakeLists.txt @@ -3,6 +3,10 @@ include_directories( ${CMAKE_SOURCE_DIR}/src ${CMAKE_BINARY_DIR}/src ${CMAKE_CURRENT_BINARY_DIR} +) + +include_directories( + SYSTEM ${Boost_INCLUDE_DIRS} ${OCC_INCLUDE_DIR} ${COIN3D_INCLUDE_DIRS} diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerExternal.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerExternal.h index 6623688796..697204f472 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerExternal.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerExternal.h @@ -40,6 +40,7 @@ #include "GeometryCreationMode.h" #include "Utils.h" #include "ViewProviderSketch.h" +#include namespace SketcherGui @@ -97,18 +98,25 @@ public: // return false; //} + if (pObj->isDerivedFrom() || pObj->isDerivedFrom()) { + return true; + } + + if (pObj->isDerivedFrom() || pObj->isDerivedFrom()) { + return true; + } + if (Base::Tools::isNullOrEmpty(sSubName)) { return false; } + std::string element(sSubName); if ((element.size() > 4 && element.substr(0, 4) == "Edge") || (element.size() > 6 && element.substr(0, 6) == "Vertex") || (element.size() > 4 && element.substr(0, 4) == "Face")) { return true; } - if (pObj->isDerivedFrom() || pObj->isDerivedFrom()) { - return true; - } + return false; } }; @@ -159,6 +167,7 @@ public: } std::string subName(msg.pSubName); if (obj->isDerivedFrom() || obj->isDerivedFrom() + || obj->isDerivedFrom() || obj->isDerivedFrom() || (subName.size() > 4 && subName.substr(0, 4) == "Edge") || (subName.size() > 6 && subName.substr(0, 6) == "Vertex") || (subName.size() > 4 && subName.substr(0, 4) == "Face")) { diff --git a/src/Mod/Sketcher/Gui/EditModeCoinManagerParameters.cpp b/src/Mod/Sketcher/Gui/EditModeCoinManagerParameters.cpp index 9710afacf6..9c90003eb8 100644 --- a/src/Mod/Sketcher/Gui/EditModeCoinManagerParameters.cpp +++ b/src/Mod/Sketcher/Gui/EditModeCoinManagerParameters.cpp @@ -24,7 +24,7 @@ #include "Mod/Sketcher/App/ExternalGeometryFacade.h" -#include +#include #include #include "EditModeCoinManagerParameters.h" @@ -59,10 +59,10 @@ SbColor DrawingParameters::CreateCurveColor(0.5f, 0.5f, 0.5f); // ##7f7f7f -> ( namespace { // Anonymous namespace to avoid making those variables global unsigned long HColorLong = Gui::ViewParams::instance()->getAxisXColor(); -App::Color Hcolor = App::Color(static_cast(HColorLong)); +Base::Color Hcolor = Base::Color(static_cast(HColorLong)); unsigned long VColorLong = Gui::ViewParams::instance()->getAxisYColor(); -App::Color Vcolor = App::Color(static_cast(VColorLong)); +Base::Color Vcolor = Base::Color(static_cast(VColorLong)); } // namespace SbColor DrawingParameters::CrossColorH(Hcolor.r, Hcolor.g, Hcolor.b); SbColor DrawingParameters::CrossColorV(Vcolor.r, Vcolor.g, Vcolor.b); diff --git a/src/Mod/Sketcher/Gui/EditModeCoinManagerParameters.h b/src/Mod/Sketcher/Gui/EditModeCoinManagerParameters.h index 0e1082f417..29e81b7261 100644 --- a/src/Mod/Sketcher/Gui/EditModeCoinManagerParameters.h +++ b/src/Mod/Sketcher/Gui/EditModeCoinManagerParameters.h @@ -40,7 +40,7 @@ #include #include -#include +#include #include #include #include @@ -153,14 +153,14 @@ struct DrawingParameters DrawingParameters() { unsigned long colorLong; - App::Color color; + Base::Color color; colorLong = Gui::ViewParams::instance()->getAxisXColor(); - color = App::Color(static_cast(colorLong)); + color = Base::Color(static_cast(colorLong)); CrossColorH = SbColor(color.r, color.g, color.b); colorLong = Gui::ViewParams::instance()->getAxisYColor(); - color = App::Color(static_cast(colorLong)); + color = Base::Color(static_cast(colorLong)); CrossColorV = SbColor(color.r, color.g, color.b); } }; diff --git a/src/Mod/Sketcher/Gui/ViewProviderSketch.cpp b/src/Mod/Sketcher/Gui/ViewProviderSketch.cpp index d7c1421a64..781a939522 100644 --- a/src/Mod/Sketcher/Gui/ViewProviderSketch.cpp +++ b/src/Mod/Sketcher/Gui/ViewProviderSketch.cpp @@ -141,7 +141,7 @@ void ViewProviderSketch::ParameterObserver::updateColorProperty(const std::strin colorprop->setValue(r, g, b); - App::Color elementAppColor = colorprop->getValue(); + Base::Color elementAppColor = colorprop->getValue(); unsigned long color = (unsigned long)(elementAppColor.getPackedValue()); color = hGrp->GetUnsigned(string.c_str(), color); elementAppColor.setPackedValue((uint32_t)color); @@ -345,7 +345,7 @@ void ViewProviderSketch::ParameterObserver::initParameters() {[this, packedDefaultGridColor](const std::string& string, [[maybe_unused]] App::Property* property) { auto v = getSketcherGeneralParameter(string, packedDefaultGridColor); - auto color = App::Color(v); + auto color = Base::Color(v); Client.setGridLineColor(color); }, nullptr}}, @@ -353,7 +353,7 @@ void ViewProviderSketch::ParameterObserver::initParameters() {[this, packedDefaultGridColor](const std::string& string, [[maybe_unused]] App::Property* property) { auto v = getSketcherGeneralParameter(string, packedDefaultGridColor); - auto color = App::Color(v); + auto color = Base::Color(v); Client.setGridDivLineColor(color); }, nullptr}}, @@ -2941,7 +2941,7 @@ void SketcherGui::ViewProviderSketch::finishRestoring() // that meaans that we need to run migration strategy and come up with a proper value if (!AutoColor.isTouched()) { // white is the normally provided default for FreeCAD sketch colors - auto white = App::Color(1.f, 1.f, 1.f, 1.f); + auto white = Base::Color(1.f, 1.f, 1.f, 1.f); auto colorWasNeverChanged = LineColor.getValue() == white && diff --git a/src/Mod/Spreadsheet/App/CMakeLists.txt b/src/Mod/Spreadsheet/App/CMakeLists.txt index 013747e784..fcbf9fe9a9 100644 --- a/src/Mod/Spreadsheet/App/CMakeLists.txt +++ b/src/Mod/Spreadsheet/App/CMakeLists.txt @@ -5,6 +5,10 @@ endif(WIN32) include_directories( ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR} +) + +include_directories( + SYSTEM ${PYCXX_INCLUDE_DIR} ${Python3_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS} diff --git a/src/Mod/Spreadsheet/App/Cell.cpp b/src/Mod/Spreadsheet/App/Cell.cpp index a5a1ee2c11..89414cd1de 100644 --- a/src/Mod/Spreadsheet/App/Cell.cpp +++ b/src/Mod/Spreadsheet/App/Cell.cpp @@ -467,13 +467,13 @@ bool Cell::getStyle(std::set& _style) const * */ -void Cell::setForeground(const App::Color& color) +void Cell::setForeground(const Base::Color& color) { if (color != foregroundColor) { PropertySheet::AtomicPropertyChange signaller(*owner); foregroundColor = color; - setUsed(FOREGROUND_COLOR_SET, foregroundColor != App::Color(0, 0, 0, 1)); + setUsed(FOREGROUND_COLOR_SET, foregroundColor != Base::Color(0, 0, 0, 1)); setDirty(); signaller.tryInvoke(); @@ -485,7 +485,7 @@ void Cell::setForeground(const App::Color& color) * */ -bool Cell::getForeground(App::Color& color) const +bool Cell::getForeground(Base::Color& color) const { color = foregroundColor; return isUsed(FOREGROUND_COLOR_SET); @@ -496,13 +496,13 @@ bool Cell::getForeground(App::Color& color) const * */ -void Cell::setBackground(const App::Color& color) +void Cell::setBackground(const Base::Color& color) { if (color != backgroundColor) { PropertySheet::AtomicPropertyChange signaller(*owner); backgroundColor = color; - setUsed(BACKGROUND_COLOR_SET, backgroundColor != App::Color(1, 1, 1, 0)); + setUsed(BACKGROUND_COLOR_SET, backgroundColor != Base::Color(1, 1, 1, 0)); setDirty(); signaller.tryInvoke(); @@ -516,7 +516,7 @@ void Cell::setBackground(const App::Color& color) * */ -bool Cell::getBackground(App::Color& color) const +bool Cell::getBackground(Base::Color& color) const { color = backgroundColor; return isUsed(BACKGROUND_COLOR_SET); @@ -543,7 +543,7 @@ void Cell::setDisplayUnit(const std::string& unit) if (newDisplayUnit != displayUnit) { PropertySheet::AtomicPropertyChange signaller(*owner); - displayUnit = newDisplayUnit; + displayUnit = std::move(newDisplayUnit); setUsed(DISPLAY_UNIT_SET, !displayUnit.isEmpty()); setDirty(); @@ -783,12 +783,12 @@ void Cell::restore(Base::XMLReader& reader, bool checkAlias) setAlignment(alignmentCode); } if (foregroundColor) { - App::Color color = decodeColor(foregroundColor, App::Color(0, 0, 0, 1)); + Base::Color color = decodeColor(foregroundColor, Base::Color(0, 0, 0, 1)); setForeground(color); } if (backgroundColor) { - App::Color color = decodeColor(backgroundColor, App::Color(1, 1, 1, 1)); + Base::Color color = decodeColor(backgroundColor, Base::Color(1, 1, 1, 1)); setBackground(color); } @@ -1016,7 +1016,7 @@ std::string Cell::encodeAlignment(int alignment) * */ -std::string Cell::encodeColor(const App::Color& color) +std::string Cell::encodeColor(const Base::Color& color) { std::stringstream tmp; @@ -1064,10 +1064,10 @@ std::string Cell::encodeStyle(const std::set& style) * */ -App::Color Cell::decodeColor(const std::string& color, const App::Color& defaultColor) +Base::Color Cell::decodeColor(const std::string& color, const Base::Color& defaultColor) { if (color.size() == 7 || color.size() == 9) { - App::Color c; + Base::Color c; if (color[0] != '#') { return defaultColor; diff --git a/src/Mod/Spreadsheet/App/Cell.h b/src/Mod/Spreadsheet/App/Cell.h index 5917908a37..97bf1c496d 100644 --- a/src/Mod/Spreadsheet/App/Cell.h +++ b/src/Mod/Spreadsheet/App/Cell.h @@ -72,11 +72,11 @@ public: void setStyle(const std::set& _style); bool getStyle(std::set& style) const; - void setForeground(const App::Color& color); - bool getForeground(App::Color& color) const; + void setForeground(const Base::Color& color); + bool getForeground(Base::Color& color) const; - void setBackground(const App::Color& color); - bool getBackground(App::Color& color) const; + void setBackground(const Base::Color& color); + bool getBackground(Base::Color& color) const; void setDisplayUnit(const std::string& unit); bool getDisplayUnit(DisplayUnit& unit) const; @@ -161,8 +161,8 @@ public: static std::string encodeStyle(const std::set& style); - static std::string encodeColor(const App::Color& color); - static App::Color decodeColor(const std::string& color, const App::Color& defaultColor); + static std::string encodeColor(const Base::Color& color); + static Base::Color decodeColor(const std::string& color, const Base::Color& defaultColor); private: void setParseException(const std::string& e); @@ -199,8 +199,8 @@ private: mutable App::ExpressionPtr expression; int alignment; std::set style; - App::Color foregroundColor; - App::Color backgroundColor; + Base::Color foregroundColor; + Base::Color backgroundColor; DisplayUnit displayUnit; std::string alias; Base::Unit computedUnit; diff --git a/src/Mod/Spreadsheet/App/DisplayUnit.h b/src/Mod/Spreadsheet/App/DisplayUnit.h index a5ec4011f6..d698f93deb 100644 --- a/src/Mod/Spreadsheet/App/DisplayUnit.h +++ b/src/Mod/Spreadsheet/App/DisplayUnit.h @@ -39,7 +39,7 @@ public: explicit DisplayUnit(const std::string _stringRep = "", const Base::Unit _unit = Base::Unit(), double _scaler = 0.0) - : stringRep(_stringRep) + : stringRep(std::move(_stringRep)) , unit(_unit) , scaler(_scaler) {} diff --git a/src/Mod/Spreadsheet/App/PropertySheet.cpp b/src/Mod/Spreadsheet/App/PropertySheet.cpp index 221a109788..d144c4652d 100644 --- a/src/Mod/Spreadsheet/App/PropertySheet.cpp +++ b/src/Mod/Spreadsheet/App/PropertySheet.cpp @@ -720,14 +720,14 @@ void PropertySheet::setStyle(CellAddress address, const std::set& _ cell->setStyle(_style); } -void PropertySheet::setForeground(CellAddress address, const App::Color& color) +void PropertySheet::setForeground(CellAddress address, const Base::Color& color) { Cell* cell = nonNullCellAt(address); assert(cell); cell->setForeground(color); } -void PropertySheet::setBackground(CellAddress address, const App::Color& color) +void PropertySheet::setBackground(CellAddress address, const Base::Color& color) { Cell* cell = nonNullCellAt(address); assert(cell); @@ -787,7 +787,7 @@ void PropertySheet::setAlias(CellAddress address, const std::string& alias) App::ObjectIdentifier key(owner, oldAlias); App::ObjectIdentifier value(owner, alias.empty() ? address.toString() : alias); - m[key] = value; + m[key] = std::move(value); owner->getDocument()->renameObjectIdentifiers(m); } @@ -1397,7 +1397,7 @@ void PropertySheet::addDependencies(CellAddress key) // Insert into maps propertyNameToCellMap[propName].insert(key); - cellToPropertyNameMap[key].insert(propName); + cellToPropertyNameMap[key].insert(std::move(propName)); } } } diff --git a/src/Mod/Spreadsheet/App/PropertySheet.h b/src/Mod/Spreadsheet/App/PropertySheet.h index 676818ce16..3123ec99c5 100644 --- a/src/Mod/Spreadsheet/App/PropertySheet.h +++ b/src/Mod/Spreadsheet/App/PropertySheet.h @@ -98,9 +98,9 @@ public: void setStyle(App::CellAddress address, const std::set& _style); - void setForeground(App::CellAddress address, const App::Color& color); + void setForeground(App::CellAddress address, const Base::Color& color); - void setBackground(App::CellAddress address, const App::Color& color); + void setBackground(App::CellAddress address, const Base::Color& color); void setDisplayUnit(App::CellAddress address, const std::string& unit); diff --git a/src/Mod/Spreadsheet/App/Sheet.cpp b/src/Mod/Spreadsheet/App/Sheet.cpp index 1e309c1bff..71da191938 100644 --- a/src/Mod/Spreadsheet/App/Sheet.cpp +++ b/src/Mod/Spreadsheet/App/Sheet.cpp @@ -24,6 +24,7 @@ #ifndef _PreComp_ #include +#include #include #include #include @@ -110,7 +111,15 @@ Sheet::Sheet() Sheet::~Sheet() { - clearAll(); + try { + clearAll(); + } + catch (...) { + // Don't let an exception propagate out of a destructor (calls terminate()) + Base::Console().Error( + "clearAll() resulted in an exception when deleting the spreadsheet : %s\n", + getNameInDocument()); + } } /** diff --git a/src/Mod/Spreadsheet/App/Sheet.h b/src/Mod/Spreadsheet/App/Sheet.h index 9c5a259c1f..a2b6d7ad3a 100644 --- a/src/Mod/Spreadsheet/App/Sheet.h +++ b/src/Mod/Spreadsheet/App/Sheet.h @@ -158,9 +158,9 @@ public: void setStyle(App::CellAddress address, const std::set& style); - void setForeground(App::CellAddress address, const App::Color& color); + void setForeground(App::CellAddress address, const Base::Color& color); - void setBackground(App::CellAddress address, const App::Color& color); + void setBackground(App::CellAddress address, const Base::Color& color); void setDisplayUnit(App::CellAddress address, const std::string& unit); diff --git a/src/Mod/Spreadsheet/App/SheetPyImp.cpp b/src/Mod/Spreadsheet/App/SheetPyImp.cpp index 0e37c5644b..79f9c6db6e 100644 --- a/src/Mod/Spreadsheet/App/SheetPyImp.cpp +++ b/src/Mod/Spreadsheet/App/SheetPyImp.cpp @@ -794,7 +794,7 @@ static float decodeFloat(const PyObject* obj) throw Base::TypeError("Float or integer expected"); } -static void decodeColor(PyObject* value, Color& c) +static void decodeColor(PyObject* value, Base::Color& c) { if (PyTuple_Check(value)) { if (PyTuple_Size(value) < 3 || PyTuple_Size(value) > 4) { @@ -822,7 +822,7 @@ PyObject* SheetPy::setForeground(PyObject* args) try { const char* range; PyObject* value; - Color c; + Base::Color c; if (!PyArg_ParseTuple(args, "sO:setForeground", &range, &value)) { return nullptr; @@ -863,7 +863,7 @@ PyObject* SheetPy::getForeground(PyObject* args) return nullptr; } - Color c; + Base::Color c; const Cell* cell = getSheetPtr()->getCell(address); if (cell && cell->getForeground(c)) { PyObject* t = PyTuple_New(4); @@ -886,7 +886,7 @@ PyObject* SheetPy::setBackground(PyObject* args) try { const char* strAddress; PyObject* value; - Color c; + Base::Color c; if (!PyArg_ParseTuple(args, "sO:setBackground", &strAddress, &value)) { return nullptr; @@ -927,7 +927,7 @@ PyObject* SheetPy::getBackground(PyObject* args) return nullptr; } - Color c; + Base::Color c; const Cell* cell = getSheetPtr()->getCell(address); if (cell && cell->getBackground(c)) { PyObject* t = PyTuple_New(4); diff --git a/src/Mod/Spreadsheet/Gui/CMakeLists.txt b/src/Mod/Spreadsheet/Gui/CMakeLists.txt index 595ce0c8d4..979399ccc6 100644 --- a/src/Mod/Spreadsheet/Gui/CMakeLists.txt +++ b/src/Mod/Spreadsheet/Gui/CMakeLists.txt @@ -1,6 +1,10 @@ include_directories( ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_CURRENT_SOURCE_DIR} +) + +include_directories( + SYSTEM ${Boost_INCLUDE_DIRS} ${COIN3D_INCLUDE_DIRS} ${ZIPIOS_INCLUDES} diff --git a/src/Mod/Spreadsheet/Gui/DlgBindSheet.cpp b/src/Mod/Spreadsheet/Gui/DlgBindSheet.cpp index 6e9463abd4..6df7a3a10c 100644 --- a/src/Mod/Spreadsheet/Gui/DlgBindSheet.cpp +++ b/src/Mod/Spreadsheet/Gui/DlgBindSheet.cpp @@ -191,7 +191,7 @@ void DlgBindSheet::accept() addr = std::string("<<") + copy + ">>"; } else { - addr = copy; + addr = std::move(copy); } }; diff --git a/src/Mod/Spreadsheet/Gui/PropertiesDialog.cpp b/src/Mod/Spreadsheet/Gui/PropertiesDialog.cpp index e732b5988f..3cecd1940a 100644 --- a/src/Mod/Spreadsheet/Gui/PropertiesDialog.cpp +++ b/src/Mod/Spreadsheet/Gui/PropertiesDialog.cpp @@ -153,12 +153,12 @@ PropertiesDialog::PropertiesDialog(Sheet* _sheet, void PropertiesDialog::foregroundColorChanged(const QColor& color) { - foregroundColor = App::Color(color.redF(), color.greenF(), color.blueF(), color.alphaF()); + foregroundColor = Base::Color(color.redF(), color.greenF(), color.blueF(), color.alphaF()); } void PropertiesDialog::backgroundColorChanged(const QColor& color) { - backgroundColor = App::Color(color.redF(), color.greenF(), color.blueF(), color.alphaF()); + backgroundColor = Base::Color(color.redF(), color.greenF(), color.blueF(), color.alphaF()); } void PropertiesDialog::alignmentChanged() diff --git a/src/Mod/Spreadsheet/Gui/PropertiesDialog.h b/src/Mod/Spreadsheet/Gui/PropertiesDialog.h index 5877218177..e44ab7e61a 100644 --- a/src/Mod/Spreadsheet/Gui/PropertiesDialog.h +++ b/src/Mod/Spreadsheet/Gui/PropertiesDialog.h @@ -59,15 +59,15 @@ private: Spreadsheet::Sheet* sheet; std::vector ranges; Ui::PropertiesDialog* ui; - App::Color foregroundColor; - App::Color backgroundColor; + Base::Color foregroundColor; + Base::Color backgroundColor; int alignment; std::set style; Spreadsheet::DisplayUnit displayUnit; std::string alias; - App::Color orgForegroundColor; - App::Color orgBackgroundColor; + Base::Color orgForegroundColor; + Base::Color orgBackgroundColor; int orgAlignment; std::set orgStyle; Spreadsheet::DisplayUnit orgDisplayUnit; diff --git a/src/Mod/Spreadsheet/Gui/SheetModel.cpp b/src/Mod/Spreadsheet/Gui/SheetModel.cpp index b5c4c856ac..8b6523230c 100644 --- a/src/Mod/Spreadsheet/Gui/SheetModel.cpp +++ b/src/Mod/Spreadsheet/Gui/SheetModel.cpp @@ -192,7 +192,7 @@ QVariant SheetModel::data(const QModelIndex& index, int role) const Property* prop = sheet->getPropertyByName(address.c_str()); if (role == Qt::BackgroundRole) { - Color color; + Base::Color color; if (cell->getBackground(color)) { return QVariant::fromValue( @@ -292,7 +292,7 @@ QVariant SheetModel::data(const QModelIndex& index, int role) const switch (role) { case Qt::ForegroundRole: { - Color color; + Base::Color color; if (cell->getForeground(color)) { return QVariant::fromValue( @@ -327,7 +327,7 @@ QVariant SheetModel::data(const QModelIndex& index, int role) const switch (role) { case Qt::ForegroundRole: { - Color color; + Base::Color color; if (cell->getForeground(color)) { return QVariant::fromValue( @@ -403,7 +403,7 @@ QVariant SheetModel::data(const QModelIndex& index, int role) const switch (role) { case Qt::ForegroundRole: { - Color color; + Base::Color color; if (cell->getForeground(color)) { return QVariant::fromValue( @@ -459,7 +459,7 @@ QVariant SheetModel::data(const QModelIndex& index, int role) const switch (role) { case Qt::ForegroundRole: { - Color color; + Base::Color color; if (cell->getForeground(color)) { return QVariant::fromValue( diff --git a/src/Mod/Spreadsheet/Gui/SheetTableView.cpp b/src/Mod/Spreadsheet/Gui/SheetTableView.cpp index 732e714bdd..f8a35e3287 100644 --- a/src/Mod/Spreadsheet/Gui/SheetTableView.cpp +++ b/src/Mod/Spreadsheet/Gui/SheetTableView.cpp @@ -714,6 +714,10 @@ void SheetTableView::_copySelection(const std::vector& ranges, bool for (int j = minCol; j <= maxCol; j++) { QModelIndex index = model()->index(i, j); QString cell = index.data(Qt::EditRole).toString(); + if (!cell.isEmpty() && cell.at(0) == QLatin1Char('\'')) { + cell.remove(0, 1); + } + if (j < maxCol) { cell.append(QChar::fromLatin1('\t')); } diff --git a/src/Mod/Spreadsheet/Gui/ZoomableView.h b/src/Mod/Spreadsheet/Gui/ZoomableView.h index a95e34e156..0992690288 100644 --- a/src/Mod/Spreadsheet/Gui/ZoomableView.h +++ b/src/Mod/Spreadsheet/Gui/ZoomableView.h @@ -68,9 +68,9 @@ private: QPointer stv; QGraphicsScene m_scene; - QGraphicsProxyWidget* qpw; + QGraphicsProxyWidget* qpw {nullptr}; - int m_zoomLevel; + int m_zoomLevel {0}; protected: void focusOutEvent(QFocusEvent* event) override; diff --git a/src/Mod/Spreadsheet/TestSpreadsheet.py b/src/Mod/Spreadsheet/TestSpreadsheet.py index a5d78a9810..98b5e27e8d 100644 --- a/src/Mod/Spreadsheet/TestSpreadsheet.py +++ b/src/Mod/Spreadsheet/TestSpreadsheet.py @@ -33,354 +33,530 @@ from FreeCAD import Units v = Base.Vector + # ---------------------------------------------------------------------------------- -# define the functions to test the FreeCAD Spreadsheet module and expression engine +# Test Spreadsheet module and expression engine # ---------------------------------------------------------------------------------- -class SpreadsheetCases(unittest.TestCase): +############################################################################################# +class SpreadsheetAggregates(unittest.TestCase): def setUp(self): self.doc = FreeCAD.newDocument() - self.TempPath = tempfile.gettempdir() - FreeCAD.Console.PrintLog(" Using temp path: " + self.TempPath + "\n") + self.sheet = self.doc.addObject("Spreadsheet::Sheet", "Spreadsheet") - def testAggregates(self): - """Test all aggregate functions""" - sheet = self.doc.addObject("Spreadsheet::Sheet", "Spreadsheet") - sheet.set("B13", "4") - sheet.set("B14", "5") - sheet.set("B15", "6") - sheet.set("C13", "4mm") - sheet.set("C14", "5mm") - sheet.set("C15", "6mm") - sheet.set("C16", "6") + def tearDown(self): + FreeCAD.closeDocument(self.doc.Name) - sheet.set("A1", "=sum(1)") - sheet.set("A2", "=sum(1;2)") - sheet.set("A3", "=sum(1;2;3)") - sheet.set("A4", "=sum(1;2;3;B13)") - sheet.set("A5", "=sum(1;2;3;B13:B15)") - - sheet.set("B1", "=min(1)") - sheet.set("B2", "=min(1;2)") - sheet.set("B3", "=min(1;2;3)") - sheet.set("B4", "=min(1;2;3;B13)") - sheet.set("B5", "=min(1;2;3;B13:B15)") - - sheet.set("C1", "=max(1)") - sheet.set("C2", "=max(1;2)") - sheet.set("C3", "=max(1;2;3)") - sheet.set("C4", "=max(1;2;3;B13)") - sheet.set("C5", "=max(1;2;3;B13:B15)") - - sheet.set("D1", "=stddev(1)") - sheet.set("D2", "=stddev(1;2)") - sheet.set("D3", "=stddev(1;2;3)") - sheet.set("D4", "=stddev(1;2;3;B13)") - sheet.set("D5", "=stddev(1;2;3;B13:B15)") - - sheet.set("E1", "=count(1)") - sheet.set("E2", "=count(1;2)") - sheet.set("E3", "=count(1;2;3)") - sheet.set("E4", "=count(1;2;3;B13)") - sheet.set("E5", "=count(1;2;3;B13:B15)") - - sheet.set("F1", "=average(1)") - sheet.set("F2", "=average(1;2)") - sheet.set("F3", "=average(1;2;3)") - sheet.set("F4", "=average(1;2;3;B13)") - sheet.set("F5", "=average(1;2;3;B13:B15)") - - sheet.set("G1", "=average(C13:C15)") - sheet.set("G2", "=min(C13:C15)") - sheet.set("G3", "=max(C13:C15)") - sheet.set("G4", "=count(C13:C15)") - sheet.set("G5", "=stddev(C13:C15)") - sheet.set("G6", "=sum(C13:C15)") - - sheet.set("H1", "=average(C13:C16)") - sheet.set("H2", "=min(C13:C16)") - sheet.set("H3", "=max(C13:C16)") - sheet.set("H4", "=count(C13:C16)") - sheet.set("H5", "=stddev(C13:C16)") - sheet.set("H6", "=sum(C13:C16)") + def test_sum(self): + self.sheet.set("B13", "4") + self.sheet.set("B14", "5") + self.sheet.set("B15", "6") + self.sheet.set("A1", "=sum(1)") + self.sheet.set("A2", "=sum(1;2)") + self.sheet.set("A3", "=sum(1;2;3)") + self.sheet.set("A4", "=sum(1;2;3;B13)") + self.sheet.set("A5", "=sum(1;2;3;B13:B15)") self.doc.recompute() - self.assertEqual(sheet.A1, 1) - self.assertEqual(sheet.A2, 3) - self.assertEqual(sheet.A3, 6) - self.assertEqual(sheet.A4, 10) - self.assertEqual(sheet.A5, 21) - self.assertEqual(sheet.B1, 1) - self.assertEqual(sheet.B2, 1) - self.assertEqual(sheet.B3, 1) - self.assertEqual(sheet.B4, 1) - self.assertEqual(sheet.B5, 1) + self.assertEqual(self.sheet.A1, 1) + self.assertEqual(self.sheet.A2, 3) + self.assertEqual(self.sheet.A3, 6) + self.assertEqual(self.sheet.A4, 10) + self.assertEqual(self.sheet.A5, 21) - self.assertEqual(sheet.C1, 1) - self.assertEqual(sheet.C2, 2) - self.assertEqual(sheet.C3, 3) - self.assertEqual(sheet.C4, 4) - self.assertEqual(sheet.C5, 6) + def test_min(self): + self.sheet.set("B13", "4") + self.sheet.set("B14", "5") + self.sheet.set("B15", "6") + self.sheet.set("B1", "=min(1)") + self.sheet.set("B2", "=min(1;2)") + self.sheet.set("B3", "=min(1;2;3)") + self.sheet.set("B4", "=min(1;2;3;B13)") + self.sheet.set("B5", "=min(1;2;3;B13:B15)") + + self.doc.recompute() + + self.assertEqual(self.sheet.B1, 1) + self.assertEqual(self.sheet.B2, 1) + self.assertEqual(self.sheet.B3, 1) + self.assertEqual(self.sheet.B4, 1) + self.assertEqual(self.sheet.B5, 1) + + def test_max(self): + self.sheet.set("B13", "4") + self.sheet.set("B14", "5") + self.sheet.set("B15", "6") + self.sheet.set("C1", "=max(1)") + self.sheet.set("C2", "=max(1;2)") + self.sheet.set("C3", "=max(1;2;3)") + self.sheet.set("C4", "=max(1;2;3;B13)") + self.sheet.set("C5", "=max(1;2;3;B13:B15)") + + self.doc.recompute() + + self.assertEqual(self.sheet.C1, 1) + self.assertEqual(self.sheet.C2, 2) + self.assertEqual(self.sheet.C3, 3) + self.assertEqual(self.sheet.C4, 4) + self.assertEqual(self.sheet.C5, 6) + + def test_stddev(self): + self.sheet.set("B13", "4") + self.sheet.set("B14", "5") + self.sheet.set("B15", "6") + self.sheet.set("D1", "=stddev(1)") + self.sheet.set("D2", "=stddev(1;2)") + self.sheet.set("D3", "=stddev(1;2;3)") + self.sheet.set("D4", "=stddev(1;2;3;B13)") + self.sheet.set("D5", "=stddev(1;2;3;B13:B15)") + + self.doc.recompute() self.assertTrue( - sheet.D1.startswith("ERR: Invalid number of entries: at least two required.") + self.sheet.D1.startswith("ERR: Invalid number of entries: at least two required.") ) - self.assertEqual(sheet.D2, 0.7071067811865476) - self.assertEqual(sheet.D3, 1.0) - self.assertEqual(sheet.D4, 1.2909944487358056) - self.assertEqual(sheet.D5, 1.8708286933869707) + self.assertEqual(self.sheet.D2, 0.7071067811865476) + self.assertEqual(self.sheet.D3, 1.0) + self.assertEqual(self.sheet.D4, 1.2909944487358056) + self.assertEqual(self.sheet.D5, 1.8708286933869707) - self.assertEqual(sheet.E1, 1) - self.assertEqual(sheet.E2, 2) - self.assertEqual(sheet.E3, 3) - self.assertEqual(sheet.E4, 4) - self.assertEqual(sheet.E5, 6) + def test_count(self): + self.sheet.set("B13", "4") + self.sheet.set("B14", "5") + self.sheet.set("B15", "6") + self.sheet.set("E1", "=count(1)") + self.sheet.set("E2", "=count(1;2)") + self.sheet.set("E3", "=count(1;2;3)") + self.sheet.set("E4", "=count(1;2;3;B13)") + self.sheet.set("E5", "=count(1;2;3;B13:B15)") - self.assertEqual(sheet.F1, 1) - self.assertEqual(sheet.F2, (1.0 + 2.0) / 2.0) - self.assertEqual(sheet.F3, (1.0 + 2 + 3) / 3) - self.assertEqual(sheet.F4, (1.0 + 2 + 3 + 4) / 4) - self.assertEqual(sheet.F5, (1.0 + 2 + 3 + 4 + 5 + 6) / 6) + self.doc.recompute() - self.assertEqual(sheet.G1, Units.Quantity("5 mm")) - self.assertEqual(sheet.G2, Units.Quantity("4 mm")) - self.assertEqual(sheet.G3, Units.Quantity("6 mm")) - self.assertEqual(sheet.G4, 3) - self.assertEqual(sheet.G5, Units.Quantity("1 mm")) - self.assertEqual(sheet.G6, Units.Quantity("15 mm")) + self.assertEqual(self.sheet.E1, 1) + self.assertEqual(self.sheet.E2, 2) + self.assertEqual(self.sheet.E3, 3) + self.assertEqual(self.sheet.E4, 4) + self.assertEqual(self.sheet.E5, 6) + + def test_average(self): + self.sheet.set("B13", "4") + self.sheet.set("B14", "5") + self.sheet.set("B15", "6") + self.sheet.set("F1", "=average(1)") + self.sheet.set("F2", "=average(1;2)") + self.sheet.set("F3", "=average(1;2;3)") + self.sheet.set("F4", "=average(1;2;3;B13)") + self.sheet.set("F5", "=average(1;2;3;B13:B15)") + + self.doc.recompute() + + self.assertEqual(self.sheet.F1, 1) + self.assertEqual(self.sheet.F2, (1.0 + 2.0) / 2.0) + self.assertEqual(self.sheet.F3, (1.0 + 2 + 3) / 3) + self.assertEqual(self.sheet.F4, (1.0 + 2 + 3 + 4) / 4) + self.assertEqual(self.sheet.F5, (1.0 + 2 + 3 + 4 + 5 + 6) / 6) + + def test_range(self): + self.sheet.set("C13", "4mm") + self.sheet.set("C14", "5mm") + self.sheet.set("C15", "6mm") + self.sheet.set("G1", "=average(C13:C15)") + self.sheet.set("G2", "=min(C13:C15)") + self.sheet.set("G3", "=max(C13:C15)") + self.sheet.set("G4", "=count(C13:C15)") + self.sheet.set("G5", "=stddev(C13:C15)") + self.sheet.set("G6", "=sum(C13:C15)") + + self.doc.recompute() + + self.assertEqual(self.sheet.G1, Units.Quantity("5 mm")) + self.assertEqual(self.sheet.G2, Units.Quantity("4 mm")) + self.assertEqual(self.sheet.G3, Units.Quantity("6 mm")) + self.assertEqual(self.sheet.G4, 3) + self.assertEqual(self.sheet.G5, Units.Quantity("1 mm")) + self.assertEqual(self.sheet.G6, Units.Quantity("15 mm")) + + def test_range_invalid(self): + self.sheet.set("C13", "4mm") + self.sheet.set("C14", "5mm") + self.sheet.set("C15", "6mm") + self.sheet.set("C16", "6") + self.sheet.set("H1", "=average(C13:C16)") + self.sheet.set("H2", "=min(C13:C16)") + self.sheet.set("H3", "=max(C13:C16)") + self.sheet.set("H4", "=count(C13:C16)") + self.sheet.set("H5", "=stddev(C13:C16)") + self.sheet.set("H6", "=sum(C13:C16)") + + self.doc.recompute() self.assertTrue( - sheet.H1.startswith("ERR: Quantity::operator +=(): Unit mismatch in plus operation") + self.sheet.H1.startswith( + "ERR: Quantity::operator +=(): Unit mismatch in plus operation" + ) ) self.assertTrue( - sheet.H2.startswith( + self.sheet.H2.startswith( "ERR: Quantity::operator <(): quantities need to have same unit to compare" ) ) self.assertTrue( - sheet.H3.startswith( + self.sheet.H3.startswith( "ERR: Quantity::operator >(): quantities need to have same unit to compare" ) ) - self.assertEqual(sheet.H4, 4) + self.assertEqual(self.sheet.H4, 4) self.assertTrue( - sheet.H5.startswith("ERR: Quantity::operator -(): Unit mismatch in minus operation") + self.sheet.H5.startswith( + "ERR: Quantity::operator -(): Unit mismatch in minus operation" + ) ) self.assertTrue( - sheet.H6.startswith("ERR: Quantity::operator +=(): Unit mismatch in plus operation") + self.sheet.H6.startswith( + "ERR: Quantity::operator +=(): Unit mismatch in plus operation" + ) ) + +############################################################################################# +class SpreadsheetFunction(unittest.TestCase): + def setUp(self): + self.doc = FreeCAD.newDocument() + self.sheet = self.doc.addObject("Spreadsheet::Sheet", "Spreadsheet") + + def tearDown(self): + FreeCAD.closeDocument(self.doc.Name) + def assertMostlyEqual(self, a, b): if type(a) is Units.Quantity: self.assertTrue(math.fabs(a.Value - b.Value) < 1e-14) self.assertTrue(a.Unit == b.Unit) else: - self.assertTrue(math.fabs(a - b) < 1e-14) + self.assertNotIsInstance(a, str) + self.assertNotIsInstance(b, str) + self.assertTrue( + math.fabs(a - b) < 1e-14, + "Values are not 'Mostly Equal': %s != %s" % (a, b), + ) - def testFunctions(self): - """Test all built-in simple functions""" - sheet = self.doc.addObject("Spreadsheet::Sheet", "Spreadsheet") - sheet.set("A1", "=cos(60)") # Cos - sheet.set("B1", "=cos(60deg)") - sheet.set("C1", "=cos(pi / 2 * 1rad)") - sheet.set("A2", "=sin(30)") # Sin - sheet.set("B2", "=sin(30deg)") - sheet.set("C2", "=sin(pi / 6 * 1rad)") - sheet.set("A3", "=tan(45)") # Tan - sheet.set("B3", "=tan(45deg)") - sheet.set("C3", "=tan(pi / 4 * 1rad)") - sheet.set("A4", "=abs(3)") # Abs - sheet.set("B4", "=abs(-3)") - sheet.set("C4", "=abs(-3mm)") - sheet.set("A5", "=exp(3)") # Exp - sheet.set("B5", "=exp(-3)") - sheet.set("C5", "=exp(-3mm)") - sheet.set("A6", "=log(3)") # Log - sheet.set("B6", "=log(-3)") - sheet.set("C6", "=log(-3mm)") - sheet.set("A7", "=log10(10)") # Log10 - sheet.set("B7", "=log10(-3)") - sheet.set("C7", "=log10(-3mm)") - sheet.set("A8", "=round(3.4)") # Round - sheet.set("B8", "=round(3.6)") - sheet.set("C8", "=round(-3.4)") - sheet.set("D8", "=round(-3.6)") - sheet.set("E8", "=round(3.4mm)") - sheet.set("F8", "=round(3.6mm)") - sheet.set("G8", "=round(-3.4mm)") - sheet.set("H8", "=round(-3.6mm)") - sheet.set("A9", "=trunc(3.4)") # Trunc - sheet.set("B9", "=trunc(3.6)") - sheet.set("C9", "=trunc(-3.4)") - sheet.set("D9", "=trunc(-3.6)") - sheet.set("E9", "=trunc(3.4mm)") - sheet.set("F9", "=trunc(3.6mm)") - sheet.set("G9", "=trunc(-3.4mm)") - sheet.set("H9", "=trunc(-3.6mm)") - sheet.set("A10", "=ceil(3.4)") # Ceil - sheet.set("B10", "=ceil(3.6)") - sheet.set("C10", "=ceil(-3.4)") - sheet.set("D10", "=ceil(-3.6)") - sheet.set("E10", "=ceil(3.4mm)") - sheet.set("F10", "=ceil(3.6mm)") - sheet.set("G10", "=ceil(-3.4mm)") - sheet.set("H10", "=ceil(-3.6mm)") - sheet.set("A11", "=floor(3.4)") # Floor - sheet.set("B11", "=floor(3.6)") - sheet.set("C11", "=floor(-3.4)") - sheet.set("D11", "=floor(-3.6)") - sheet.set("E11", "=floor(3.4mm)") - sheet.set("F11", "=floor(3.6mm)") - sheet.set("G11", "=floor(-3.4mm)") - sheet.set("H11", "=floor(-3.6mm)") - sheet.set("A12", "=asin(0.5)") # Asin - sheet.set("B12", "=asin(0.5mm)") - sheet.set("A13", "=acos(0.5)") # Acos - sheet.set("B13", "=acos(0.5mm)") - sheet.set("A14", "=atan(sqrt(3))") # Atan - sheet.set("B14", "=atan(0.5mm)") - sheet.set("A15", "=sinh(0.5)") # Sinh - sheet.set("B15", "=sinh(0.5mm)") - sheet.set("A16", "=cosh(0.5)") # Cosh - sheet.set("B16", "=cosh(0.5mm)") - sheet.set("A17", "=tanh(0.5)") # Tanh - sheet.set("B17", "=tanh(0.5mm)") - sheet.set("A18", "=sqrt(4)") # Sqrt - sheet.set("B18", "=sqrt(4mm^2)") - sheet.set("A19", "=mod(7; 4)") # Mod - sheet.set("B19", "=mod(-7; 4)") - sheet.set("C19", "=mod(7mm; 4)") - sheet.set("D19", "=mod(7mm; 4mm)") - sheet.set("A20", "=atan2(3; 3)") # Atan2 - sheet.set("B20", "=atan2(-3; 3)") - sheet.set("C20", "=atan2(3mm; 3)") - sheet.set("D20", "=atan2(3mm; 3mm)") - sheet.set("A21", "=pow(7; 4)") # Pow - sheet.set("B21", "=pow(-7; 4)") - sheet.set("C21", "=pow(7mm; 4)") - sheet.set("D21", "=pow(7mm; 4mm)") - sheet.set("A23", "=hypot(3; 4)") # Hypot - sheet.set("B23", "=hypot(-3; 4)") - sheet.set("C23", "=hypot(3mm; 4)") - sheet.set("D23", "=hypot(3mm; 4mm)") - sheet.set("A24", "=hypot(3; 4; 5)") # Hypot - sheet.set("B24", "=hypot(-3; 4; 5)") - sheet.set("C24", "=hypot(3mm; 4; 5)") - sheet.set("D24", "=hypot(3mm; 4mm; 5mm)") - sheet.set("A26", "=cath(5; 3)") # Cath - sheet.set("B26", "=cath(-5; 3)") - sheet.set("C26", "=cath(5mm; 3)") - sheet.set("D26", "=cath(5mm; 3mm)") - - l = math.sqrt(5 * 5 + 4 * 4 + 3 * 3) - sheet.set("A27", "=cath(%0.15f; 5; 4)" % l) # Cath - sheet.set("B27", "=cath(%0.15f; -5; 4)" % l) - sheet.set("C27", "=cath(%0.15f mm; 5mm; 4)" % l) - sheet.set("D27", "=cath(%0.15f mm; 5mm; 4mm)" % l) + def test_cos(self): + self.sheet.set("A1", "=cos(60)") + self.sheet.set("B1", "=cos(60deg)") + self.sheet.set("C1", "=cos(pi / 2 * 1rad)") self.doc.recompute() - self.assertMostlyEqual(sheet.A1, 0.5) # Cos - self.assertMostlyEqual(sheet.B1, 0.5) - self.assertMostlyEqual(sheet.C1, 0) - self.assertMostlyEqual(sheet.A2, 0.5) # Sin - self.assertMostlyEqual(sheet.B2, 0.5) - self.assertMostlyEqual(sheet.C2, 0.5) - self.assertMostlyEqual(sheet.A3, 1) # Tan - self.assertMostlyEqual(sheet.B3, 1) - self.assertMostlyEqual(sheet.C3, 1) - self.assertMostlyEqual(sheet.A4, 3) # Abs - self.assertMostlyEqual(sheet.B4, 3) - self.assertMostlyEqual(sheet.C4, Units.Quantity("3 mm")) - self.assertMostlyEqual(sheet.A5, math.exp(3)) # Exp - self.assertMostlyEqual(sheet.B5, math.exp(-3)) - self.assertTrue(sheet.C5.startswith("ERR: Unit must be empty.")) - self.assertMostlyEqual(sheet.A6, math.log(3)) # Log - self.assertTrue(math.isnan(sheet.B6)) - self.assertTrue(sheet.C6.startswith("ERR: Unit must be empty.")) - self.assertMostlyEqual(sheet.A7, math.log10(10)) # Log10 - self.assertTrue(math.isnan(sheet.B7)) - self.assertTrue(sheet.C7.startswith("ERR: Unit must be empty.")) - self.assertMostlyEqual(sheet.A8, 3) # Round - self.assertMostlyEqual(sheet.B8, 4) - self.assertMostlyEqual(sheet.C8, -3) - self.assertMostlyEqual(sheet.D8, -4) - self.assertEqual(sheet.E8, Units.Quantity("3 mm")) - self.assertEqual(sheet.F8, Units.Quantity("4 mm")) - self.assertEqual(sheet.G8, Units.Quantity("-3 mm")) - self.assertEqual(sheet.H8, Units.Quantity("-4 mm")) - self.assertMostlyEqual(sheet.A9, 3) # Trunc - self.assertMostlyEqual(sheet.B9, 3) - self.assertMostlyEqual(sheet.C9, -3) - self.assertMostlyEqual(sheet.D9, -3) - self.assertEqual(sheet.E9, Units.Quantity("3 mm")) - self.assertEqual(sheet.F9, Units.Quantity("3 mm")) - self.assertEqual(sheet.G9, Units.Quantity("-3 mm")) - self.assertEqual(sheet.H9, Units.Quantity("-3 mm")) - self.assertMostlyEqual(sheet.A10, 4) # Ceil - self.assertMostlyEqual(sheet.B10, 4) - self.assertMostlyEqual(sheet.C10, -3) - self.assertMostlyEqual(sheet.D10, -3) - self.assertMostlyEqual(sheet.E10, Units.Quantity("4 mm")) - self.assertMostlyEqual(sheet.F10, Units.Quantity("4 mm")) - self.assertMostlyEqual(sheet.G10, Units.Quantity("-3 mm")) - self.assertMostlyEqual(sheet.H10, Units.Quantity("-3 mm")) - self.assertMostlyEqual(sheet.A11, 3) # Floor - self.assertMostlyEqual(sheet.B11, 3) - self.assertMostlyEqual(sheet.C11, -4) - self.assertMostlyEqual(sheet.D11, -4) - self.assertMostlyEqual(sheet.E11, Units.Quantity("3 mm")) - self.assertMostlyEqual(sheet.F11, Units.Quantity("3 mm")) - self.assertMostlyEqual(sheet.G11, Units.Quantity("-4 mm")) - self.assertMostlyEqual(sheet.H11, Units.Quantity("-4 mm")) - self.assertMostlyEqual(sheet.A12, Units.Quantity("30 deg")) # Asin - self.assertTrue(sheet.B12.startswith("ERR: Unit must be empty.")) - self.assertMostlyEqual(sheet.A13, Units.Quantity("60 deg")) # Acos - self.assertTrue(sheet.B13.startswith("ERR: Unit must be empty.")) - self.assertMostlyEqual(sheet.A14, Units.Quantity("60 deg")) # Atan - self.assertTrue(sheet.B14.startswith("ERR: Unit must be empty.")) - self.assertMostlyEqual(sheet.A15, math.sinh(0.5)) # Sinh - self.assertTrue(sheet.B15.startswith("ERR: Unit must be empty.")) - self.assertMostlyEqual(sheet.A16, math.cosh(0.5)) # Cosh - self.assertTrue(sheet.B16.startswith("ERR: Unit must be empty.")) - self.assertMostlyEqual(sheet.A17, math.tanh(0.5)) # Tanh - self.assertTrue(sheet.B17.startswith("ERR: Unit must be empty.")) - self.assertMostlyEqual(sheet.A18, 2) # Sqrt - self.assertMostlyEqual(sheet.B18, Units.Quantity("2 mm")) - self.assertMostlyEqual(sheet.A19, 3) # Mod - self.assertMostlyEqual(sheet.B19, -3) - self.assertMostlyEqual(sheet.C19, Units.Quantity("3 mm")) - self.assertEqual(sheet.D19, 3) - self.assertMostlyEqual(sheet.A20, Units.Quantity("45 deg")) # Atan2 - self.assertMostlyEqual(sheet.B20, Units.Quantity("-45 deg")) - self.assertTrue(sheet.C20.startswith("ERR: Units must be equal")) - self.assertMostlyEqual(sheet.D20, Units.Quantity("45 deg")) - self.assertMostlyEqual(sheet.A21, 2401) # Pow - self.assertMostlyEqual(sheet.B21, 2401) - self.assertMostlyEqual(sheet.C21, Units.Quantity("2401mm^4")) - self.assertTrue(sheet.D21.startswith("ERR: Exponent is not allowed to have a unit.")) - self.assertMostlyEqual(sheet.A23, 5) # Hypot - self.assertMostlyEqual(sheet.B23, 5) - self.assertTrue(sheet.C23.startswith("ERR: Units must be equal")) - self.assertMostlyEqual(sheet.D23, Units.Quantity("5mm")) - l = math.sqrt(3 * 3 + 4 * 4 + 5 * 5) - self.assertMostlyEqual(sheet.A24, l) # Hypot - self.assertMostlyEqual(sheet.B24, l) - self.assertTrue(sheet.C24.startswith("ERR: Units must be equal")) - self.assertMostlyEqual(sheet.D24, Units.Quantity("7.07106781186548 mm")) - self.assertMostlyEqual(sheet.A26, 4) # Cath - self.assertMostlyEqual(sheet.B26, 4) - self.assertTrue(sheet.C26.startswith("ERR: Units must be equal")) - self.assertMostlyEqual(sheet.D26, Units.Quantity("4mm")) + self.assertMostlyEqual(self.sheet.A1, 0.5) + self.assertMostlyEqual(self.sheet.B1, 0.5) + self.assertMostlyEqual(self.sheet.C1, 0) + def test_sin(self): + self.sheet.set("A2", "=sin(30)") + self.sheet.set("B2", "=sin(30deg)") + self.sheet.set("C2", "=sin(pi / 6 * 1rad)") + + self.doc.recompute() + + self.assertMostlyEqual(self.sheet.A2, 0.5) + self.assertMostlyEqual(self.sheet.B2, 0.5) + self.assertMostlyEqual(self.sheet.C2, 0.5) + + def test_tan(self): + self.sheet.set("A3", "=tan(45)") + self.sheet.set("B3", "=tan(45deg)") + self.sheet.set("C3", "=tan(pi / 4 * 1rad)") + + self.doc.recompute() + + self.assertMostlyEqual(self.sheet.A3, 1) + self.assertMostlyEqual(self.sheet.B3, 1) + self.assertMostlyEqual(self.sheet.C3, 1) + + def test_abs(self): + self.sheet.set("A4", "=abs(3)") + self.sheet.set("B4", "=abs(-3)") + self.sheet.set("C4", "=abs(-3mm)") + + self.doc.recompute() + + self.assertMostlyEqual(self.sheet.A4, 3) + self.assertMostlyEqual(self.sheet.B4, 3) + self.assertMostlyEqual(self.sheet.C4, Units.Quantity("3 mm")) + + def test_exp(self): + self.sheet.set("A5", "=exp(3)") + self.sheet.set("B5", "=exp(-3)") + self.sheet.set("C5", "=exp(-3mm)") + + self.doc.recompute() + + self.assertMostlyEqual(self.sheet.A5, math.exp(3)) + self.assertMostlyEqual(self.sheet.B5, math.exp(-3)) + self.assertTrue(self.sheet.C5.startswith("ERR: Unit must be empty.")) + + def test_log(self): + self.sheet.set("A6", "=log(3)") + self.sheet.set("B6", "=log(-3)") + self.sheet.set("C6", "=log(-3mm)") + + self.doc.recompute() + + self.assertMostlyEqual(self.sheet.A6, math.log(3)) + self.assertTrue(math.isnan(self.sheet.B6)) + self.assertTrue(self.sheet.C6.startswith("ERR: Unit must be empty.")) + + def test_log10(self): + self.sheet.set("A7", "=log10(10)") + self.sheet.set("B7", "=log10(-3)") + self.sheet.set("C7", "=log10(-3mm)") + + self.doc.recompute() + + self.assertMostlyEqual(self.sheet.A7, math.log10(10)) + self.assertTrue(math.isnan(self.sheet.B7)) + self.assertTrue(self.sheet.C7.startswith("ERR: Unit must be empty.")) + + def test_round(self): + self.sheet.set("A8", "=round(3.4)") + self.sheet.set("B8", "=round(3.6)") + self.sheet.set("C8", "=round(-3.4)") + self.sheet.set("D8", "=round(-3.6)") + self.sheet.set("E8", "=round(3.4mm)") + self.sheet.set("F8", "=round(3.6mm)") + self.sheet.set("G8", "=round(-3.4mm)") + self.sheet.set("H8", "=round(-3.6mm)") + + self.doc.recompute() + + self.assertMostlyEqual(self.sheet.A8, 3) + self.assertMostlyEqual(self.sheet.B8, 4) + self.assertMostlyEqual(self.sheet.C8, -3) + self.assertMostlyEqual(self.sheet.D8, -4) + self.assertEqual(self.sheet.E8, Units.Quantity("3 mm")) + self.assertEqual(self.sheet.F8, Units.Quantity("4 mm")) + self.assertEqual(self.sheet.G8, Units.Quantity("-3 mm")) + self.assertEqual(self.sheet.H8, Units.Quantity("-4 mm")) + + def test_trunc(self): + self.sheet.set("A9", "=trunc(3.4)") + self.sheet.set("B9", "=trunc(3.6)") + self.sheet.set("C9", "=trunc(-3.4)") + self.sheet.set("D9", "=trunc(-3.6)") + self.sheet.set("E9", "=trunc(3.4mm)") + self.sheet.set("F9", "=trunc(3.6mm)") + self.sheet.set("G9", "=trunc(-3.4mm)") + self.sheet.set("H9", "=trunc(-3.6mm)") + + self.doc.recompute() + + self.assertMostlyEqual(self.sheet.A9, 3) + self.assertMostlyEqual(self.sheet.B9, 3) + self.assertMostlyEqual(self.sheet.C9, -3) + self.assertMostlyEqual(self.sheet.D9, -3) + self.assertEqual(self.sheet.E9, Units.Quantity("3 mm")) + self.assertEqual(self.sheet.F9, Units.Quantity("3 mm")) + self.assertEqual(self.sheet.G9, Units.Quantity("-3 mm")) + self.assertEqual(self.sheet.H9, Units.Quantity("-3 mm")) + + def test_ceil(self): + self.sheet.set("A10", "=ceil(3.4)") + self.sheet.set("B10", "=ceil(3.6)") + self.sheet.set("C10", "=ceil(-3.4)") + self.sheet.set("D10", "=ceil(-3.6)") + self.sheet.set("E10", "=ceil(3.4mm)") + self.sheet.set("F10", "=ceil(3.6mm)") + self.sheet.set("G10", "=ceil(-3.4mm)") + self.sheet.set("H10", "=ceil(-3.6mm)") + + self.doc.recompute() + + self.assertMostlyEqual(self.sheet.A10, 4) + self.assertMostlyEqual(self.sheet.B10, 4) + self.assertMostlyEqual(self.sheet.C10, -3) + self.assertMostlyEqual(self.sheet.D10, -3) + self.assertMostlyEqual(self.sheet.E10, Units.Quantity("4 mm")) + self.assertMostlyEqual(self.sheet.F10, Units.Quantity("4 mm")) + self.assertMostlyEqual(self.sheet.G10, Units.Quantity("-3 mm")) + self.assertMostlyEqual(self.sheet.H10, Units.Quantity("-3 mm")) + + def test_floor(self): + self.sheet.set("A11", "=floor(3.4)") + self.sheet.set("B11", "=floor(3.6)") + self.sheet.set("C11", "=floor(-3.4)") + self.sheet.set("D11", "=floor(-3.6)") + self.sheet.set("E11", "=floor(3.4mm)") + self.sheet.set("F11", "=floor(3.6mm)") + self.sheet.set("G11", "=floor(-3.4mm)") + self.sheet.set("H11", "=floor(-3.6mm)") + + self.doc.recompute() + + self.assertMostlyEqual(self.sheet.A11, 3) + self.assertMostlyEqual(self.sheet.B11, 3) + self.assertMostlyEqual(self.sheet.C11, -4) + self.assertMostlyEqual(self.sheet.D11, -4) + self.assertMostlyEqual(self.sheet.E11, Units.Quantity("3 mm")) + self.assertMostlyEqual(self.sheet.F11, Units.Quantity("3 mm")) + self.assertMostlyEqual(self.sheet.G11, Units.Quantity("-4 mm")) + self.assertMostlyEqual(self.sheet.H11, Units.Quantity("-4 mm")) + + def test_asin(self): + self.sheet.set("A12", "=asin(0.5)") + self.sheet.set("B12", "=asin(0.5mm)") + + self.doc.recompute() + + self.assertMostlyEqual(self.sheet.A12, Units.Quantity("30 deg")) + self.assertTrue(self.sheet.B12.startswith("ERR: Unit must be empty.")) + + def test_acos(self): + self.sheet.set("A13", "=acos(0.5)") + self.sheet.set("B13", "=acos(0.5mm)") + + self.doc.recompute() + + self.assertMostlyEqual(self.sheet.A13, Units.Quantity("60 deg")) + self.assertTrue(self.sheet.B13.startswith("ERR: Unit must be empty.")) + + def test_atan(self): + self.sheet.set("A14", "=atan(sqrt(3))") + self.sheet.set("B14", "=atan(0.5mm)") + + self.doc.recompute() + + self.assertMostlyEqual(self.sheet.A14, Units.Quantity("60 deg")) + self.assertTrue(self.sheet.B14.startswith("ERR: Unit must be empty.")) + + def test_asinh(self): + self.sheet.set("A15", "=sinh(0.5)") + self.sheet.set("B15", "=sinh(0.5mm)") + + self.doc.recompute() + + self.assertMostlyEqual(self.sheet.A15, math.sinh(0.5)) + self.assertTrue(self.sheet.B15.startswith("ERR: Unit must be empty.")) + + def test_cosh(self): + self.sheet.set("A16", "=cosh(0.5)") + self.sheet.set("B16", "=cosh(0.5mm)") + + self.doc.recompute() + + self.assertMostlyEqual(self.sheet.A16, math.cosh(0.5)) + self.assertTrue(self.sheet.B16.startswith("ERR: Unit must be empty.")) + + def test_tanh(self): + self.sheet.set("A17", "=tanh(0.5)") + self.sheet.set("B17", "=tanh(0.5mm)") + + self.doc.recompute() + + self.assertMostlyEqual(self.sheet.A17, math.tanh(0.5)) + self.assertTrue(self.sheet.B17.startswith("ERR: Unit must be empty.")) + + def test_sqrt(self): + self.sheet.set("A18", "=sqrt(4)") + self.sheet.set("B18", "=sqrt(4mm^2)") + + self.doc.recompute() + + self.assertMostlyEqual(self.sheet.A18, 2) + self.assertMostlyEqual(self.sheet.B18, Units.Quantity("2 mm")) + + def test_mod(self): + self.sheet.set("A19", "=mod(7; 4)") + self.sheet.set("B19", "=mod(-7; 4)") + self.sheet.set("C19", "=mod(7mm; 4)") + self.sheet.set("D19", "=mod(7mm; 4mm)") + + self.doc.recompute() + + self.assertMostlyEqual(self.sheet.A19, 3) + self.assertMostlyEqual(self.sheet.B19, -3) + self.assertMostlyEqual(self.sheet.C19, Units.Quantity("3 mm")) + self.assertEqual(self.sheet.D19, 3) + + def test_atan2(self): + self.sheet.set("A20", "=atan2(3; 3)") + self.sheet.set("B20", "=atan2(-3; 3)") + self.sheet.set("C20", "=atan2(3mm; 3)") + self.sheet.set("D20", "=atan2(3mm; 3mm)") + + self.doc.recompute() + + self.assertMostlyEqual(self.sheet.A20, Units.Quantity("45 deg")) + self.assertMostlyEqual(self.sheet.B20, Units.Quantity("-45 deg")) + self.assertTrue(self.sheet.C20.startswith("ERR: Units must be equal")) + self.assertMostlyEqual(self.sheet.D20, Units.Quantity("45 deg")) + + def test_pow(self): + self.sheet.set("A21", "=pow(7; 4)") + self.sheet.set("B21", "=pow(-7; 4)") + self.sheet.set("C21", "=pow(7mm; 4)") + self.sheet.set("D21", "=pow(7mm; 4mm)") + + self.doc.recompute() + + self.assertMostlyEqual(self.sheet.A21, 2401) + self.assertMostlyEqual(self.sheet.B21, 2401) + self.assertMostlyEqual(self.sheet.C21, Units.Quantity("2401mm^4")) + self.assertTrue(self.sheet.D21.startswith("ERR: Exponent is not allowed to have a unit.")) + + def test_hypot(self): + self.sheet.set("A23", "=hypot(3; 4)") + self.sheet.set("B23", "=hypot(-3; 4)") + self.sheet.set("C23", "=hypot(3mm; 4)") + self.sheet.set("D23", "=hypot(3mm; 4mm)") + self.sheet.set("A24", "=hypot(3; 4; 5)") + self.sheet.set("B24", "=hypot(-3; 4; 5)") + self.sheet.set("C24", "=hypot(3mm; 4; 5)") + self.sheet.set("D24", "=hypot(3mm; 4mm; 5mm)") + + self.doc.recompute() + + self.assertMostlyEqual(self.sheet.A23, 5) + self.assertMostlyEqual(self.sheet.B23, 5) + self.assertTrue(self.sheet.C23.startswith("ERR: Units must be equal")) + self.assertMostlyEqual(self.sheet.D23, Units.Quantity("5mm")) + self.assertMostlyEqual(self.sheet.A24, math.sqrt(3 * 3 + 4 * 4 + 5 * 5)) + self.assertMostlyEqual(self.sheet.B24, math.sqrt(3 * 3 + 4 * 4 + 5 * 5)) + self.assertTrue(self.sheet.C24.startswith("ERR: Units must be equal")) + self.assertMostlyEqual(self.sheet.D24, Units.Quantity("7.07106781186548 mm")) + + def test_cath(self): + self.sheet.set("A26", "=cath(5; 3)") + self.sheet.set("B26", "=cath(-5; 3)") + self.sheet.set("C26", "=cath(5mm; 3)") + self.sheet.set("D26", "=cath(5mm; 3mm)") l = math.sqrt(5 * 5 + 4 * 4 + 3 * 3) - l = math.sqrt(l * l - 5 * 5 - 4 * 4) - self.assertMostlyEqual(sheet.A27, l) # Cath - self.assertMostlyEqual(sheet.B27, l) - self.assertTrue(sheet.C27.startswith("ERR: Units must be equal")) - self.assertMostlyEqual(sheet.D27, Units.Quantity("3 mm")) + self.sheet.set("A27", "=cath(%0.15f; 5; 4)" % l) + self.sheet.set("B27", "=cath(%0.15f; -5; 4)" % l) + self.sheet.set("C27", "=cath(%0.15f mm; 5mm; 4)" % l) + self.sheet.set("D27", "=cath(%0.15f mm; 5mm; 4mm)" % l) + + self.doc.recompute() + + self.assertMostlyEqual(self.sheet.A26, 4) + self.assertMostlyEqual(self.sheet.B26, 4) + self.assertTrue(self.sheet.C26.startswith("ERR: Units must be equal")) + self.assertMostlyEqual(self.sheet.D26, Units.Quantity("4mm")) + self.assertMostlyEqual(self.sheet.A27, math.sqrt(l * l - 5 * 5 - 4 * 4)) + self.assertMostlyEqual(self.sheet.B27, math.sqrt(l * l - 5 * 5 - 4 * 4)) + self.assertTrue(self.sheet.C27.startswith("ERR: Units must be equal")) + self.assertMostlyEqual(self.sheet.D27, Units.Quantity("3 mm")) + + +############################################################################################# +class SpreadsheetCases(unittest.TestCase): + def setUp(self): + self.doc = FreeCAD.newDocument() + self.TempPath = tempfile.gettempdir() + FreeCAD.Console.PrintLog(" Using temp path: " + self.TempPath + "\n") + + def tearDown(self): + FreeCAD.closeDocument(self.doc.Name) def testRelationalOperators(self): """Test relational operators""" @@ -412,6 +588,7 @@ class SpreadsheetCases(unittest.TestCase): sheet.set("A24", "=1 != 1.0000000000000001 ? 0 : 1") self.doc.recompute() + self.assertEqual(sheet.A1, 1) self.assertEqual(sheet.A2, 1) self.assertEqual(sheet.A3, 1) @@ -446,13 +623,15 @@ class SpreadsheetCases(unittest.TestCase): sheet.set("A4", "=4mm / 2mm") sheet.set("A5", "=(4mm)^2") sheet.set("A6", "=5(mm^2)") - sheet.set("A7", "=5mm^2") # ^2 operates on whole number + sheet.set("A7", "=5mm^2") # ^2 operates on whole number sheet.set("A8", "=5") sheet.set("A9", "=5*1/K") # Currently fails sheet.set("A10", "=5 K^-1") # Currently fails sheet.set("A11", "=9.8 m/s^2") # Currently fails sheet.setDisplayUnit("A8", "1/K") + self.doc.recompute() + self.assertEqual(sheet.A1, Units.Quantity("5mm")) self.assertEqual(sheet.A2, Units.Quantity("-1 mm")) self.assertEqual(sheet.A3, Units.Quantity("6 mm^2")) @@ -538,6 +717,7 @@ class SpreadsheetCases(unittest.TestCase): sheet.set("A54", '=-(Cylinder.Radius + Box.Length - 1"/2)') self.doc.recompute() + self.assertEqual(sheet.getContents("A1"), "=1 < 2 ? 3 : 4") self.assertEqual(sheet.getContents("A2"), "=1 + 2 < 3 + 4 ? 5 + 6 : 7 + 8") self.assertEqual( @@ -670,7 +850,9 @@ class SpreadsheetCases(unittest.TestCase): sheet.set("A16", "1/1") sheet.set("A17", "1/2") sheet.set("A18", "2/4") + self.doc.recompute() + self.assertEqual(sheet.A1, 1) self.assertEqual(sheet.A2, 1.5) self.assertEqual(sheet.A3, 0.5) @@ -699,7 +881,9 @@ class SpreadsheetCases(unittest.TestCase): sheet.set("A4", "2/mm") sheet.set("A5", "4/2mm") sheet.set("A6", "6mm/3s") + self.doc.recompute() + self.assertEqual(sheet.A1, Units.Quantity("1 mm")) self.assertEqual(sheet.A2, 0.5) self.assertEqual(sheet.A3, Units.Quantity("2 mm")) @@ -902,7 +1086,7 @@ class SpreadsheetCases(unittest.TestCase): qpair = zip(plm1.Rotation.Q, plm2.Rotation.Q) qdiff1 = sqrt(sum([(v1 - v2) ** 2 for v1, v2 in qpair])) qdiff2 = sqrt(sum([(v1 + v2) ** 2 for v1, v2 in qpair])) - return (plm1.Base - plm2.Base).Length < 1e-7 and (qdiff1 < 1e-12 or dqiff2 < 1e-12) + return (plm1.Base - plm2.Base).Length < 1e-7 and (qdiff1 < 1e-12 or qdiff2 < 1e-12) sheet = self.doc.addObject("Spreadsheet::Sheet", "Spreadsheet") @@ -1221,7 +1405,7 @@ class SpreadsheetCases(unittest.TestCase): self.doc.recompute() sheet.setAlias("C3", "test") - def testCrossLinkEmptyPropertyName(self): + def test_cross_link_empty_property_name(self): # https://forum.freecad.org/viewtopic.php?f=3&t=58603 base = FreeCAD.newDocument("base") sheet = base.addObject("Spreadsheet::Sheet", "Spreadsheet") @@ -1238,10 +1422,10 @@ class SpreadsheetCases(unittest.TestCase): box.Height = 10.00 square.recompute() - basePath = self.TempPath + os.sep + "base.FCStd" - base.saveAs(basePath) - squarePath = self.TempPath + os.sep + "square.FCStd" - square.saveAs(squarePath) + base_path = self.TempPath + os.sep + "base.FCStd" + base.saveAs(base_path) + square_path = self.TempPath + os.sep + "square.FCStd" + square.saveAs(square_path) base.save() square.save() @@ -1251,8 +1435,8 @@ class SpreadsheetCases(unittest.TestCase): ## ## preparation done - base = FreeCAD.openDocument(basePath) - square = FreeCAD.openDocument(squarePath) + base = FreeCAD.openDocument(base_path) + square = FreeCAD.openDocument(square_path) square.Box.setExpression("Length", "base#Spreadsheet.x") square.recompute() @@ -1262,7 +1446,7 @@ class SpreadsheetCases(unittest.TestCase): FreeCAD.closeDocument(square.Name) FreeCAD.closeDocument(base.Name) - def testExpressionWithAlias(self): + def test_expression_with_alias(self): # https://forum.freecad.org/viewtopic.php?p=564502#p564502 ss1 = self.doc.addObject("Spreadsheet::Sheet", "Input") ss1.setAlias("A1", "one") @@ -1575,7 +1759,3 @@ class SpreadsheetCases(unittest.TestCase): self.assertLess(sheet.F3.distanceToPoint(FreeCAD.Vector(0.28, 0.04, -0.2)), tolerance) self.assertLess(abs(sheet.F4.Value - -1.6971), 0.0001) self.assertEqual(sheet.F5, FreeCAD.Vector(1.72, 2.96, 4.2)) - - def tearDown(self): - # closing doc - FreeCAD.closeDocument(self.doc.Name) diff --git a/src/Mod/Start/App/CMakeLists.txt b/src/Mod/Start/App/CMakeLists.txt index 93600938a9..387f5ea827 100644 --- a/src/Mod/Start/App/CMakeLists.txt +++ b/src/Mod/Start/App/CMakeLists.txt @@ -22,6 +22,7 @@ # ***************************************************************************/ include_directories( + SYSTEM ${PYCXX_INCLUDE_DIR} ${Python3_INCLUDE_DIRS} ${QtCore_INCLUDE_DIRS} diff --git a/src/Mod/Start/Gui/AppStartGui.cpp b/src/Mod/Start/Gui/AppStartGui.cpp index 561485d147..5750b1baab 100644 --- a/src/Mod/Start/Gui/AppStartGui.cpp +++ b/src/Mod/Start/Gui/AppStartGui.cpp @@ -33,6 +33,8 @@ #include #include #include +#include +#include "DlgStartPreferencesImp.h" #include @@ -124,5 +126,9 @@ PyMOD_INIT_FUNC(StartGui) loadStartResource(); Base::Console().Log("done\n"); + // register preferences pages + new Gui::PrefPageProducer( + QT_TRANSLATE_NOOP("QObject", "Start")); + PyMOD_Return(mod); } diff --git a/src/Mod/Start/Gui/CMakeLists.txt b/src/Mod/Start/Gui/CMakeLists.txt index 5d3447b284..98706d562c 100644 --- a/src/Mod/Start/Gui/CMakeLists.txt +++ b/src/Mod/Start/Gui/CMakeLists.txt @@ -23,6 +23,10 @@ include_directories( ${CMAKE_CURRENT_BINARY_DIR} +) + +include_directories( + SYSTEM ${Boost_INCLUDE_DIRS} ${COIN3D_INCLUDE_DIRS} ${PYCXX_INCLUDE_DIR} @@ -40,6 +44,10 @@ set(StartGui_LIBS FreeCADGui ) +set(StartGui_UIC_SRCS + DlgStartPreferences.ui + ) + set(Start_TR_QRC ${CMAKE_CURRENT_BINARY_DIR}/Resources/Start_translation.qrc) qt_find_and_add_translation(QM_SRCS "Resources/translations/*_*.ts" ${CMAKE_CURRENT_BINARY_DIR}/Resources/translations) @@ -50,6 +58,8 @@ qt_add_resources(Start_QRC_SRCS Resources/Start.qrc ${Start_TR_QRC}) SET(StartGui_SRCS ${Start_QRC_SRCS} ${StartGui_UIC_SRCS} + DlgStartPreferencesImp.cpp + DlgStartPreferencesImp.h AppStartGui.cpp FileCardDelegate.cpp FileCardDelegate.h diff --git a/src/Mod/Start/Gui/DlgStartPreferences.ui b/src/Mod/Start/Gui/DlgStartPreferences.ui new file mode 100644 index 0000000000..2dcf6df394 --- /dev/null +++ b/src/Mod/Start/Gui/DlgStartPreferences.ui @@ -0,0 +1,147 @@ + + + DlgStartPreferences + + + + 0 + 0 + 537 + 766 + + + + General + + + + + + Contents + + + + + + Show additional folder contents + + + + + + + If you want the examples to show on the first page + + + Qt::RightToLeft + + + + + + true + + + ShowExamples + + + Mod/Start + + + + + + + An optional custom folder to be displayed on the Start page. + + + Gui::FileChooser::Directory + + + CustomFolder + + + Mod/Start + + + + + + + Show examples folder contents + + + + + + + + + + Options + + + + + + If checked, will automatically close the Start page when FreeCAD launches + + + Qt::RightToLeft + + + + + + closeStart + + + Mod/Start + + + + + + + Close start page after loading + + + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + Gui::FileChooser + QWidget +
Gui/FileDialog.h
+
+ + Gui::PrefFileChooser + Gui::FileChooser +
Gui/PrefWidgets.h
+
+ + Gui::PrefCheckBox + QCheckBox +
Gui/PrefWidgets.h
+
+
+ + +
diff --git a/src/Mod/Start/Gui/DlgStartPreferencesImp.cpp b/src/Mod/Start/Gui/DlgStartPreferencesImp.cpp new file mode 100644 index 0000000000..0d842d1b23 --- /dev/null +++ b/src/Mod/Start/Gui/DlgStartPreferencesImp.cpp @@ -0,0 +1,78 @@ +/*************************************************************************** + * Copyright (c) 2018 Yorik van Havre * + * * + * This file is part of the FreeCAD CAx development system. * + * * + * This library is free software; you can redistribute it and/or * + * modify it under the terms of the GNU Library General Public * + * License as published by the Free Software Foundation; either * + * version 2 of the License, or (at your option) any later version. * + * * + * This library 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 Library General Public License for more details. * + * * + * You should have received a copy of the GNU Library General Public * + * License along with this library; see the file COPYING.LIB. If not, * + * write to the Free Software Foundation, Inc., 59 Temple Place, * + * Suite 330, Boston, MA 02111-1307, USA * + * * + ***************************************************************************/ + +#include "PreCompiled.h" + +#include + +#include "DlgStartPreferencesImp.h" +#include "ui_DlgStartPreferences.h" + + +using namespace StartGui; + +/** + * Constructs a DlgStartPreferencesImp which is a child of 'parent' + */ +DlgStartPreferencesImp::DlgStartPreferencesImp(QWidget* parent) + : PreferencePage(parent) + , ui(new Ui_DlgStartPreferences) +{ + ui->setupUi(this); +} + +/** + * Destroys the object and frees any allocated resources + */ +DlgStartPreferencesImp::~DlgStartPreferencesImp() +{ + // no need to delete child widgets, Qt does it all for us +} + +void DlgStartPreferencesImp::saveSettings() +{ + ui->fileChooserCustomFolder->onSave(); + ui->checkBoxShowExamples->onSave(); + ui->checkBoxCloseAfterLoading->onSave(); +} + +void DlgStartPreferencesImp::loadSettings() +{ + ui->fileChooserCustomFolder->onRestore(); + ui->checkBoxShowExamples->onRestore(); + ui->checkBoxCloseAfterLoading->onRestore(); +} + +/** + * Sets the strings of the subwidgets using the current language. + */ +void DlgStartPreferencesImp::changeEvent(QEvent* e) +{ + if (e->type() == QEvent::LanguageChange) { + ui->retranslateUi(this); + } + else { + QWidget::changeEvent(e); + } +} + +#include "moc_DlgStartPreferencesImp.cpp" diff --git a/src/QtOpenGL.h.cmake b/src/Mod/Start/Gui/DlgStartPreferencesImp.h similarity index 67% rename from src/QtOpenGL.h.cmake rename to src/Mod/Start/Gui/DlgStartPreferencesImp.h index a871f0bb50..61696ad39f 100644 --- a/src/QtOpenGL.h.cmake +++ b/src/Mod/Start/Gui/DlgStartPreferencesImp.h @@ -1,42 +1,52 @@ -/*************************************************************************** - * Copyright (c) 2017 Werner Mayer * - * * - * This file is part of the FreeCAD CAx development system. * - * * - * This library is free software; you can redistribute it and/or * - * modify it under the terms of the GNU Library General Public * - * License as published by the Free Software Foundation; either * - * version 2 of the License, or (at your option) any later version. * - * * - * This library 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 Library General Public License for more details. * - * * - * You should have received a copy of the GNU Library General Public * - * License along with this library; see the file COPYING.LIB. If not, * - * write to the Free Software Foundation, Inc., 59 Temple Place, * - * Suite 330, Boston, MA 02111-1307, USA * - * * - ***************************************************************************/ - - -#ifndef QUARTER_QTOPENGL_H -#define QUARTER_QTOPENGL_H - -/* QtOpenGL.h. Generated from QtOpenGL.h.cmake by cmake. */ - -#include -#include -#include -#include -#include -#include - -using QtGLContext = QOpenGLContext; -using QtGLFormat = QSurfaceFormat; -using QtGLWidget = QOpenGLWidget; -using QtGLFramebufferObject = QOpenGLFramebufferObject; -using QtGLFramebufferObjectFormat = QOpenGLFramebufferObjectFormat; - -#endif //QUARTER_QTOPENGL_H +/*************************************************************************** + * Copyright (c) 2018 Yorik van Havre * + * * + * This file is part of the FreeCAD CAx development system. * + * * + * This library is free software; you can redistribute it and/or * + * modify it under the terms of the GNU Library General Public * + * License as published by the Free Software Foundation; either * + * version 2 of the License, or (at your option) any later version. * + * * + * This library 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 Library General Public License for more details. * + * * + * You should have received a copy of the GNU Library General Public * + * License along with this library; see the file COPYING.LIB. If not, * + * write to the Free Software Foundation, Inc., 59 Temple Place, * + * Suite 330, Boston, MA 02111-1307, USA * + * * + ***************************************************************************/ + +#ifndef STARTGUI_DLGSTARTPREFERENCESIMP_H +#define STARTGUI_DLGSTARTPREFERENCESIMP_H + +#include +#include + + +class Ui_DlgStartPreferences; +namespace StartGui +{ +class DlgStartPreferencesImp: public Gui::Dialog::PreferencePage +{ + Q_OBJECT + +public: + explicit DlgStartPreferencesImp(QWidget* parent = nullptr); + ~DlgStartPreferencesImp() override; + +protected: + void saveSettings() override; + void loadSettings() override; + void changeEvent(QEvent* e) override; + +private: + std::unique_ptr ui; +}; + +} // namespace StartGui + +#endif // STARTGUI_DLGSTARTPREFERENCESIMP_H diff --git a/src/Mod/Start/Gui/FileCardDelegate.cpp b/src/Mod/Start/Gui/FileCardDelegate.cpp index 50df409286..9fef0b800d 100644 --- a/src/Mod/Start/Gui/FileCardDelegate.cpp +++ b/src/Mod/Start/Gui/FileCardDelegate.cpp @@ -38,7 +38,7 @@ #include "FileCardDelegate.h" #include "../App/DisplayedFilesModel.h" #include "App/Application.h" -#include +#include #include using namespace Start; @@ -58,27 +58,27 @@ FileCardDelegate::FileCardDelegate(QObject* parent) QColor FileCardDelegate::getBorderColor() const { QColor color(98, 160, 234); // NOLINT - uint32_t packed = App::Color::asPackedRGB(color); + uint32_t packed = Base::Color::asPackedRGB(color); packed = _parameterGroup->GetUnsigned("FileThumbnailBorderColor", packed); - color = App::Color::fromPackedRGB(packed); + color = Base::Color::fromPackedRGB(packed); return color; } QColor FileCardDelegate::getBackgroundColor() const { QColor color(221, 221, 221); // NOLINT - uint32_t packed = App::Color::asPackedRGB(color); + uint32_t packed = Base::Color::asPackedRGB(color); packed = _parameterGroup->GetUnsigned("FileThumbnailBackgroundColor", packed); - color = App::Color::fromPackedRGB(packed); + color = Base::Color::fromPackedRGB(packed); return color; } QColor FileCardDelegate::getSelectionColor() const { QColor color(38, 162, 105); // NOLINT - uint32_t packed = App::Color::asPackedRGB(color); + uint32_t packed = Base::Color::asPackedRGB(color); packed = _parameterGroup->GetUnsigned("FileThumbnailSelectionColor", packed); - color = App::Color::fromPackedRGB(packed); + color = Base::Color::fromPackedRGB(packed); return color; } diff --git a/src/Mod/Start/Gui/Resources/Start.qrc b/src/Mod/Start/Gui/Resources/Start.qrc index e02454d61d..ce6754ea91 100644 --- a/src/Mod/Start/Gui/Resources/Start.qrc +++ b/src/Mod/Start/Gui/Resources/Start.qrc @@ -1,6 +1,7 @@ icons/StartCommandIcon.svg + icons/preferences-start.svg icons/PartDesignWorkbench.svg thumbnails/Theme_thumbnail_classic.png thumbnails/Theme_thumbnail_light.png diff --git a/src/Mod/Start/Gui/Resources/icons/preferences-start.svg b/src/Mod/Start/Gui/Resources/icons/preferences-start.svg new file mode 100644 index 0000000000..2e09d1511c --- /dev/null +++ b/src/Mod/Start/Gui/Resources/icons/preferences-start.svg @@ -0,0 +1,182 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + [triplus] + + + StartWorkbench + 2016-02-26 + http://www.freecad.org/wiki/index.php?title=Artwork + + + FreeCAD + + + FreeCAD/src/Mod/Start/Gui/Resources/icons/StartWorkbench.svg + + + FreeCAD LGPL2+ + + + https://www.gnu.org/copyleft/lesser.html + + + [agryson] Alexander Gryson + + + + + arrow + right + + + Arrow pointing towards the right + + + + + + + + diff --git a/src/Mod/Start/Gui/StartView.cpp b/src/Mod/Start/Gui/StartView.cpp index e398c142ae..bcc51ba28a 100644 --- a/src/Mod/Start/Gui/StartView.cpp +++ b/src/Mod/Start/Gui/StartView.cpp @@ -136,9 +136,9 @@ public: "User parameter:BaseApp/Preferences/Mod/Start"); auto getUserColor = [&hGrp](QColor color, const char* parameter) { - uint32_t packed = App::Color::asPackedRGB(color); + uint32_t packed = Base::Color::asPackedRGB(color); packed = hGrp->GetUnsigned(parameter, packed); - color = App::Color::fromPackedRGB(packed); + color = Base::Color::fromPackedRGB(packed); return color; }; @@ -194,15 +194,6 @@ StartView::StartView(QWidget* parent) auto cardSpacing = hGrp->GetInt("FileCardSpacing", 15); // NOLINT auto showExamples = hGrp->GetBool("ShowExamples", true); // NOLINT - // Migrate legacy property, can be removed in later releases - std::string legacyCustomFolder(hGrp->GetASCII("ShowCustomFolder", "")); - if (!legacyCustomFolder.empty()) { - hGrp->SetASCII("CustomFolder", legacyCustomFolder); - hGrp->RemoveASCII("ShowCustomFolder"); - Base::Console().Message("v1.1: renamed ShowCustomFolder parameter to CustomFolder\n"); - } - // End of migration code - // Verify that the folder specified in preferences is available before showing it std::string customFolder(hGrp->GetASCII("CustomFolder", "")); bool showCustomFolder = false; diff --git a/src/Mod/Start/StartMigrator.py b/src/Mod/Start/StartMigrator.py index 18c1476341..2b5480fe8f 100644 --- a/src/Mod/Start/StartMigrator.py +++ b/src/Mod/Start/StartMigrator.py @@ -57,6 +57,7 @@ class StartMigrator2024: self._remove_toolbars() self._remove_deprecated_parameters() self._mark_complete() + self._migrate_custom_folder() FreeCAD.Console.PrintMessage("done.\n") # If the old Start workbench was set as the Autoload Module, reconfigure it so the Start command is run at startup, @@ -99,19 +100,26 @@ class StartMigrator2024: if "WebWorkbench" in groups: tux_prefs.RemGroup("WebWorkbench") + # In FreeCAD 1.1, the custom folder parameter was renamed from "ShowCustomFolder" + # to "CustomFolder". The new parameter does not yet support multiple locations. + def _migrate_custom_folder(self): + custom_folder = self.start_prefs.GetString("ShowCustomFolder", "") + + # Note: multiple locations separated by ";;" are not supported at this time + # Use the first listed location and discard the rest + return custom_folder.split(";;")[0] + # Delete old Start preferences def _remove_deprecated_parameters(self): show_on_startup = self.start_prefs.GetBool("ShowOnStartup", True) show_examples = self.start_prefs.GetBool("ShowExamples", True) close_start = self.start_prefs.GetBool("closeStart", False) - custom_folder = self.start_prefs.GetString( - "ShowCustomFolder", "" - ) # Note: allow multiple locations separated by ";;" + custom_folder = self._migrate_custom_folder() self.start_prefs.Clear() self.start_prefs.SetBool("ShowOnStartup", show_on_startup) self.start_prefs.SetBool("ShowExamples", show_examples) self.start_prefs.SetBool("CloseStart", close_start) - self.start_prefs.SetString("ShowCustomFolder", custom_folder) + self.start_prefs.SetString("CustomFolder", custom_folder) # Indicate that this migration has been run def _mark_complete(self): diff --git a/src/Mod/Surface/App/CMakeLists.txt b/src/Mod/Surface/App/CMakeLists.txt index 9fcade5f03..be9e676005 100644 --- a/src/Mod/Surface/App/CMakeLists.txt +++ b/src/Mod/Surface/App/CMakeLists.txt @@ -4,6 +4,10 @@ include_directories( ${CMAKE_SOURCE_DIR}/src ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_CURRENT_SOURCE_DIR} +) + +include_directories( + SYSTEM ${Boost_INCLUDE_DIRS} ${OCC_INCLUDE_DIR} ${PYCXX_INCLUDE_DIR} diff --git a/src/Mod/Surface/Gui/CMakeLists.txt b/src/Mod/Surface/Gui/CMakeLists.txt index 635e54a4e3..3ab45e6793 100644 --- a/src/Mod/Surface/Gui/CMakeLists.txt +++ b/src/Mod/Surface/Gui/CMakeLists.txt @@ -4,6 +4,10 @@ include_directories( ${CMAKE_BINARY_DIR}/src ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_CURRENT_SOURCE_DIR} +) + +include_directories( + SYSTEM ${Boost_INCLUDE_DIRS} ${COIN3D_INCLUDE_DIRS} ${OCC_INCLUDE_DIR} diff --git a/src/Mod/Surface/Gui/TaskFilling.cpp b/src/Mod/Surface/Gui/TaskFilling.cpp index 8e1dfbb34e..23f3dc315d 100644 --- a/src/Mod/Surface/Gui/TaskFilling.cpp +++ b/src/Mod/Surface/Gui/TaskFilling.cpp @@ -117,7 +117,7 @@ void ViewProviderFilling::highlightReferences(ShapeType type, const References& switch (type) { case ViewProviderFilling::Vertex: if (on) { - std::vector colors; + std::vector colors; TopTools_IndexedMapOfShape vMap; TopExp::MapShapes(base->Shape.getValue(), TopAbs_VERTEX, vMap); colors.resize(vMap.Extent(), svp->PointColor.getValue()); @@ -128,7 +128,7 @@ void ViewProviderFilling::highlightReferences(ShapeType type, const References& std::size_t idx = static_cast(std::stoi(jt.substr(6)) - 1); if (idx < colors.size()) { - colors[idx] = App::Color(1.0, 0.0, 1.0); // magenta + colors[idx] = Base::Color(1.0, 0.0, 1.0); // magenta } } @@ -140,7 +140,7 @@ void ViewProviderFilling::highlightReferences(ShapeType type, const References& break; case ViewProviderFilling::Edge: if (on) { - std::vector colors; + std::vector colors; TopTools_IndexedMapOfShape eMap; TopExp::MapShapes(base->Shape.getValue(), TopAbs_EDGE, eMap); colors.resize(eMap.Extent(), svp->LineColor.getValue()); @@ -151,7 +151,7 @@ void ViewProviderFilling::highlightReferences(ShapeType type, const References& // check again that the index is in range because it's possible that // the sub-names are invalid if (idx < colors.size()) { - colors[idx] = App::Color(1.0, 0.0, 1.0); // magenta + colors[idx] = Base::Color(1.0, 0.0, 1.0); // magenta } } @@ -175,7 +175,7 @@ void ViewProviderFilling::highlightReferences(ShapeType type, const References& // the sub-names are invalid if (idx < materials.size()) { materials[idx].diffuseColor = - App::Color(1.0, 0.0, 1.0); // magenta + Base::Color(1.0, 0.0, 1.0); // magenta } } diff --git a/src/Mod/Surface/Gui/TaskGeomFillSurface.cpp b/src/Mod/Surface/Gui/TaskGeomFillSurface.cpp index c862e533fd..06fd928d5d 100644 --- a/src/Mod/Surface/Gui/TaskGeomFillSurface.cpp +++ b/src/Mod/Surface/Gui/TaskGeomFillSurface.cpp @@ -121,7 +121,7 @@ void ViewProviderGeomFillSurface::highlightReferences(bool on) Gui::Application::Instance->getViewProvider(base)); if (svp) { if (on) { - std::vector colors; + std::vector colors; TopTools_IndexedMapOfShape eMap; TopExp::MapShapes(base->Shape.getValue(), TopAbs_EDGE, eMap); colors.resize(eMap.Extent(), svp->LineColor.getValue()); @@ -129,7 +129,7 @@ void ViewProviderGeomFillSurface::highlightReferences(bool on) for (const auto& jt : it.second) { std::size_t idx = static_cast(std::stoi(jt.substr(4)) - 1); assert(idx < colors.size()); - colors[idx] = App::Color(1.0, 0.0, 1.0); // magenta + colors[idx] = Base::Color(1.0, 0.0, 1.0); // magenta } svp->setHighlightedEdges(colors); diff --git a/src/Mod/Surface/Gui/TaskSections.cpp b/src/Mod/Surface/Gui/TaskSections.cpp index 519b93690b..955831a0d3 100644 --- a/src/Mod/Surface/Gui/TaskSections.cpp +++ b/src/Mod/Surface/Gui/TaskSections.cpp @@ -117,7 +117,7 @@ void ViewProviderSections::highlightReferences(ShapeType type, const References& switch (type) { case ViewProviderSections::Vertex: if (on) { - std::vector colors; + std::vector colors; TopTools_IndexedMapOfShape vMap; TopExp::MapShapes(base->Shape.getValue(), TopAbs_VERTEX, vMap); colors.resize(vMap.Extent(), svp->PointColor.getValue()); @@ -128,7 +128,7 @@ void ViewProviderSections::highlightReferences(ShapeType type, const References& std::size_t idx = static_cast(std::stoi(jt.substr(6)) - 1); if (idx < colors.size()) { - colors[idx] = App::Color(1.0, 0.0, 1.0); // magenta + colors[idx] = Base::Color(1.0, 0.0, 1.0); // magenta } } @@ -140,7 +140,7 @@ void ViewProviderSections::highlightReferences(ShapeType type, const References& break; case ViewProviderSections::Edge: if (on) { - std::vector colors; + std::vector colors; TopTools_IndexedMapOfShape eMap; TopExp::MapShapes(base->Shape.getValue(), TopAbs_EDGE, eMap); colors.resize(eMap.Extent(), svp->LineColor.getValue()); @@ -151,7 +151,7 @@ void ViewProviderSections::highlightReferences(ShapeType type, const References& // check again that the index is in range because it's possible that // the sub-names are invalid if (idx < colors.size()) { - colors[idx] = App::Color(1.0, 0.0, 1.0); // magenta + colors[idx] = Base::Color(1.0, 0.0, 1.0); // magenta } } @@ -175,7 +175,7 @@ void ViewProviderSections::highlightReferences(ShapeType type, const References& // the sub-names are invalid if (idx < materials.size()) { // magenta - materials[idx].diffuseColor = App::Color(1.0, 0.0, 1.0); + materials[idx].diffuseColor = Base::Color(1.0, 0.0, 1.0); } } diff --git a/src/Mod/TechDraw/App/ArrowPropEnum.h b/src/Mod/TechDraw/App/ArrowPropEnum.h index 383f3866d4..7048f5bad7 100644 --- a/src/Mod/TechDraw/App/ArrowPropEnum.h +++ b/src/Mod/TechDraw/App/ArrowPropEnum.h @@ -34,14 +34,16 @@ namespace TechDraw { //common definitions for line ends / arrows -enum ArrowType { FILLED_ARROW = 0, - OPEN_ARROW, - TICK, - DOT, - OPEN_CIRCLE, - FORK, - FILLED_TRIANGLE, - NONE}; +enum class ArrowType : int { + FILLED_ARROW = 0, + OPEN_ARROW, + TICK, + DOT, + OPEN_CIRCLE, + FORK, + FILLED_TRIANGLE, + NONE +}; class TechDrawExport ArrowPropEnum { Q_DECLARE_TR_FUNCTIONS(TechDraw::ArrowPropEnum) diff --git a/src/Mod/TechDraw/App/BalloonPropEnum.h b/src/Mod/TechDraw/App/BalloonPropEnum.h index d2ce78a760..f60ddb014d 100644 --- a/src/Mod/TechDraw/App/BalloonPropEnum.h +++ b/src/Mod/TechDraw/App/BalloonPropEnum.h @@ -33,14 +33,16 @@ namespace TechDraw { -enum BalloonType { Circular = 0, - None, - Triangle, - Inspection, - Hexagon, - Square, - Rectangle, - Line}; +enum class BalloonType { + Circular = 0, + None, + Triangle, + Inspection, + Hexagon, + Square, + Rectangle, + Line +}; class TechDrawExport BalloonPropEnum { Q_DECLARE_TR_FUNCTIONS(TechDraw::BalloonPropEnum) diff --git a/src/Mod/TechDraw/App/CMakeLists.txt b/src/Mod/TechDraw/App/CMakeLists.txt index e4aaa5c823..9968f333cd 100644 --- a/src/Mod/TechDraw/App/CMakeLists.txt +++ b/src/Mod/TechDraw/App/CMakeLists.txt @@ -5,6 +5,10 @@ include_directories( ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR} +) + +include_directories( + SYSTEM ${Boost_INCLUDE_DIRS} ${OCC_INCLUDE_DIR} ${ZIPIOS_INCLUDES} @@ -26,6 +30,7 @@ if (BUILD_IMPORT) endif () include_directories( + SYSTEM ${QtConcurrent_INCLUDE_DIRS} ${QtCore_INCLUDE_DIR} ${QtGui_INCLUDE_DIR} @@ -175,6 +180,8 @@ SET(TechDraw_SRCS MattingPropEnum.h Preferences.cpp Preferences.h + Tag.cpp + Tag.h TechDrawExport.cpp TechDrawExport.h ProjectionAlgos.cpp diff --git a/src/Mod/TechDraw/App/CenterLine.cpp b/src/Mod/TechDraw/App/CenterLine.cpp index 5f3f48627b..1043d1386c 100644 --- a/src/Mod/TechDraw/App/CenterLine.cpp +++ b/src/Mod/TechDraw/App/CenterLine.cpp @@ -23,9 +23,6 @@ #include "PreCompiled.h" #ifndef _PreComp_ - #include - #include - #include #include #include #include @@ -35,8 +32,6 @@ #include #include -#include -#include #include "CenterLine.h" #include "DrawUtil.h" @@ -140,8 +135,6 @@ void CenterLine::initialize() m_geometry->setHlrVisible( true); m_geometry->setCosmetic(true); m_geometry->source(SourceType::CENTERLINE); - - createNewTag(); m_geometry->setCosmeticTag(getTagAsString()); } @@ -992,7 +985,7 @@ void CenterLine::Restore(Base::XMLReader &reader) m_format.setWidth(reader.getAttributeAsFloat("value")); reader.readElement("Color"); std::string tempHex = reader.getAttribute("value"); - App::Color tempColor; + Base::Color tempColor; tempColor.fromHexString(tempHex); m_format.setColor(tempColor); reader.readElement("Visible"); @@ -1062,49 +1055,10 @@ CenterLine* CenterLine::copy() const return newCL; } -boost::uuids::uuid CenterLine::getTag() const -{ - return tag; -} - -std::string CenterLine::getTagAsString() const -{ - return boost::uuids::to_string(getTag()); -} - -void CenterLine::createNewTag() -{ - // Initialize a random number generator, to avoid Valgrind false positives. - // The random number generator is not threadsafe so we guard it. See - // https://www.boost.org/doc/libs/1_62_0/libs/uuid/uuid.html#Design%20notes - static boost::mt19937 ran; - static bool seeded = false; - static boost::mutex random_number_mutex; - - boost::lock_guard guard(random_number_mutex); - - if (!seeded) { - ran.seed(static_cast(std::time(nullptr))); - seeded = true; - } - static boost::uuids::basic_random_generator gen(&ran); - - - tag = gen(); -} - -void CenterLine::assignTag(const TechDraw::CenterLine* ce) -{ - if(ce->getTypeId() == this->getTypeId()) - this->tag = ce->tag; - else - throw Base::TypeError("CenterLine tag can not be assigned as types do not match."); -} - CenterLine *CenterLine::clone() const { CenterLine* cpy = this->copy(); - cpy->tag = this->tag; + cpy->setTag(this->getTag()); return cpy; } diff --git a/src/Mod/TechDraw/App/CenterLine.h b/src/Mod/TechDraw/App/CenterLine.h index 2c54fb8b19..efdd9b6e0f 100644 --- a/src/Mod/TechDraw/App/CenterLine.h +++ b/src/Mod/TechDraw/App/CenterLine.h @@ -28,6 +28,7 @@ #include #include +#include "Tag.h" #include "Cosmetic.h" #include "Geometry.h" @@ -35,7 +36,7 @@ namespace TechDraw { class DrawViewPart; -class TechDrawExport CenterLine: public Base::Persistence +class TechDrawExport CenterLine: public Base::Persistence, public TechDraw::Tag { TYPESYSTEM_HEADER_WITH_OVERRIDE(); @@ -175,20 +176,10 @@ public: TechDraw::BaseGeomPtr m_geometry; - //Uniqueness - boost::uuids::uuid getTag() const; - virtual std::string getTagAsString() const; - protected: void initialize(); - void createNewTag(); - void assignTag(const TechDraw::CenterLine* cl); - - boost::uuids::uuid tag; - Py::Object PythonObject; - }; } // namespace TechDraw diff --git a/src/Mod/TechDraw/App/CenterLinePyImp.cpp b/src/Mod/TechDraw/App/CenterLinePyImp.cpp index 6904e77c5e..9dda832c46 100644 --- a/src/Mod/TechDraw/App/CenterLinePyImp.cpp +++ b/src/Mod/TechDraw/App/CenterLinePyImp.cpp @@ -21,9 +21,6 @@ ***************************************************************************/ #include "PreCompiled.h" -#ifndef _PreComp_ -# include -#endif #include #include @@ -146,7 +143,7 @@ void CenterLinePy::setFormat(Py::Dict arg) Py::String CenterLinePy::getTag() const { - std::string tmp = boost::uuids::to_string(getCenterLinePtr()->getTag()); + std::string tmp = getCenterLinePtr()->getTagAsString(); return Py::String(tmp); } diff --git a/src/Mod/TechDraw/App/Cosmetic.cpp b/src/Mod/TechDraw/App/Cosmetic.cpp index 7ff83c29c6..5ebde9f936 100644 --- a/src/Mod/TechDraw/App/Cosmetic.cpp +++ b/src/Mod/TechDraw/App/Cosmetic.cpp @@ -24,12 +24,7 @@ #include "PreCompiled.h" #ifndef _PreComp_ # include -# include -# include -# include #endif -#include -#include #include #include @@ -115,8 +110,6 @@ void CosmeticEdge::initialize() m_geometry->setHlrVisible( true); m_geometry->setCosmetic(true); m_geometry->source(SourceType::COSMETICEDGE); - - createNewTag(); m_geometry->setCosmeticTag(getTagAsString()); } @@ -248,7 +241,7 @@ void CosmeticEdge::Restore(Base::XMLReader &reader) m_format.setWidth(reader.getAttributeAsFloat("value")); reader.readElement("Color"); std::string tempHex = reader.getAttribute("value"); - App::Color tempColor; + Base::Color tempColor; tempColor.fromHexString(tempHex); m_format.setColor(tempColor); reader.readElement("Visible"); @@ -298,51 +291,13 @@ void CosmeticEdge::Restore(Base::XMLReader &reader) } } -boost::uuids::uuid CosmeticEdge::getTag() const -{ - return tag; -} - -std::string CosmeticEdge::getTagAsString() const -{ - return boost::uuids::to_string(getTag()); -} - -void CosmeticEdge::createNewTag() -{ - // Initialize a random number generator, to avoid Valgrind false positives. - // The random number generator is not threadsafe so we guard it. See - // https://www.boost.org/doc/libs/1_62_0/libs/uuid/uuid.html#Design%20notes - static boost::mt19937 ran; - static bool seeded = false; - static boost::mutex random_number_mutex; - - boost::lock_guard guard(random_number_mutex); - - if (!seeded) { - ran.seed(static_cast(std::time(nullptr))); - seeded = true; - } - static boost::uuids::basic_random_generator gen(&ran); - - tag = gen(); -} - -void CosmeticEdge::assignTag(const TechDraw::CosmeticEdge* ce) -{ - if(ce->getTypeId() == this->getTypeId()) - this->tag = ce->tag; - else - throw Base::TypeError("CosmeticEdge tag can not be assigned as types do not match."); -} - CosmeticEdge* CosmeticEdge::clone() const { Base::Console().Message("CE::clone()\n"); CosmeticEdge* cpy = new CosmeticEdge(); cpy->m_geometry = m_geometry->copy(); cpy->m_format = m_format; - cpy->tag = this->tag; + cpy->setTag(this->getTag()); return cpy; } @@ -367,8 +322,6 @@ GeomFormat::GeomFormat() : m_format.setColor(LineFormat::getDefEdgeColor()); m_format.setVisible(true); m_format.setLineNumber(LineFormat::InvalidLine); - - createNewTag(); } GeomFormat::GeomFormat(const GeomFormat* gf) @@ -379,8 +332,6 @@ GeomFormat::GeomFormat(const GeomFormat* gf) m_format.setColor(gf->m_format.getColor()); m_format.setVisible(gf->m_format.getVisible()); m_format.setLineNumber(gf->m_format.getLineNumber()); - - createNewTag(); } GeomFormat::GeomFormat(const int idx, @@ -392,8 +343,6 @@ GeomFormat::GeomFormat(const int idx, m_format.setColor(fmt.getColor()); m_format.setVisible(fmt.getVisible()); m_format.setLineNumber(fmt.getLineNumber()); - - createNewTag(); } GeomFormat::~GeomFormat() @@ -451,7 +400,7 @@ void GeomFormat::Restore(Base::XMLReader &reader) m_format.setWidth(reader.getAttributeAsFloat("value")); reader.readElement("Color"); std::string tempHex = reader.getAttribute("value"); - App::Color tempColor; + Base::Color tempColor; tempColor.fromHexString(tempHex); m_format.setColor(tempColor); reader.readElement("Visible"); @@ -474,48 +423,10 @@ void GeomFormat::Restore(Base::XMLReader &reader) } } -boost::uuids::uuid GeomFormat::getTag() const -{ - return tag; -} - -std::string GeomFormat::getTagAsString() const -{ - return boost::uuids::to_string(getTag()); -} - -void GeomFormat::createNewTag() -{ - // Initialize a random number generator, to avoid Valgrind false positives. - // The random number generator is not threadsafe so we guard it. See - // https://www.boost.org/doc/libs/1_62_0/libs/uuid/uuid.html#Design%20notes - static boost::mt19937 ran; - static bool seeded = false; - static boost::mutex random_number_mutex; - - boost::lock_guard guard(random_number_mutex); - - if (!seeded) { - ran.seed(static_cast(std::time(nullptr))); - seeded = true; - } - static boost::uuids::basic_random_generator gen(&ran); - - tag = gen(); -} - -void GeomFormat::assignTag(const TechDraw::GeomFormat* ce) -{ - if(ce->getTypeId() == this->getTypeId()) - this->tag = ce->tag; - else - throw Base::TypeError("GeomFormat tag can not be assigned as types do not match."); -} - GeomFormat *GeomFormat::clone() const { GeomFormat* cpy = this->copy(); - cpy->tag = this->tag; + cpy->setTag(this->getTag()); return cpy; } diff --git a/src/Mod/TechDraw/App/Cosmetic.h b/src/Mod/TechDraw/App/Cosmetic.h index 2a8085fbca..7dca90306a 100644 --- a/src/Mod/TechDraw/App/Cosmetic.h +++ b/src/Mod/TechDraw/App/Cosmetic.h @@ -26,7 +26,7 @@ #include #include -#include +#include #include #include @@ -81,23 +81,14 @@ public: TechDraw::BaseGeomPtr m_geometry; LineFormat m_format; - boost::uuids::uuid getTag() const; - std::string getTagAsString() const override; - protected: - //Uniqueness - void createNewTag(); - void assignTag(const TechDraw::CosmeticEdge* ce); - boost::uuids::uuid tag; - Py::Object PythonObject; - }; //********** GeomFormat ******************************************************** // format specifier for geometric edges (Edge5) -class TechDrawExport GeomFormat: public Base::Persistence +class TechDrawExport GeomFormat: public Base::Persistence, public TechDraw::Tag { TYPESYSTEM_HEADER_WITH_OVERRIDE(); @@ -124,15 +115,7 @@ public: int m_geomIndex; //connection to edgeGeom LineFormat m_format; - //Uniqueness - boost::uuids::uuid getTag() const; - virtual std::string getTagAsString() const; - protected: - void createNewTag(); - void assignTag(const TechDraw::GeomFormat* gf); - - boost::uuids::uuid tag; Py::Object PythonObject; }; diff --git a/src/Mod/TechDraw/App/CosmeticEdgePyImp.cpp b/src/Mod/TechDraw/App/CosmeticEdgePyImp.cpp index 5cab4be262..c989ec3881 100644 --- a/src/Mod/TechDraw/App/CosmeticEdgePyImp.cpp +++ b/src/Mod/TechDraw/App/CosmeticEdgePyImp.cpp @@ -24,7 +24,6 @@ #ifndef _PreComp_ # include -# include #endif #include @@ -152,7 +151,7 @@ Py::Dict CosmeticEdgePy::getFormat() const Py::String CosmeticEdgePy::getTag() const { - std::string tmp = boost::uuids::to_string(getCosmeticEdgePtr()->getTag()); + std::string tmp = getCosmeticEdgePtr()->getTagAsString(); return Py::String(tmp); } diff --git a/src/Mod/TechDraw/App/CosmeticVertex.cpp b/src/Mod/TechDraw/App/CosmeticVertex.cpp index e2ffe27b47..a33e6c2dd8 100644 --- a/src/Mod/TechDraw/App/CosmeticVertex.cpp +++ b/src/Mod/TechDraw/App/CosmeticVertex.cpp @@ -24,17 +24,10 @@ //! CosmeticVertex point is stored in unscaled, unrotated form #include "PreCompiled.h" -#ifndef _PreComp_ - #include - #include - #include -#endif // _PreComp_ #include #include #include -#include -#include #include "CosmeticVertex.h" #include "CosmeticVertexPy.h" @@ -56,8 +49,6 @@ CosmeticVertex::CosmeticVertex() : TechDraw::Vertex() LineGroup::getDefaultWidth("Thin"); hlrVisible = true; cosmetic = true; - - createNewTag(); } CosmeticVertex::CosmeticVertex(const TechDraw::CosmeticVertex* cv) : TechDraw::Vertex(cv) @@ -70,8 +61,6 @@ CosmeticVertex::CosmeticVertex(const TechDraw::CosmeticVertex* cv) : TechDraw::V visible = cv->visible; hlrVisible = true; cosmetic = true; - - createNewTag(); } CosmeticVertex::CosmeticVertex(const Base::Vector3d& loc) : TechDraw::Vertex(loc) @@ -85,9 +74,6 @@ CosmeticVertex::CosmeticVertex(const Base::Vector3d& loc) : TechDraw::Vertex(loc visible = true; hlrVisible = true; cosmetic = true; - - createNewTag(); - } void CosmeticVertex::move(const Base::Vector3d& newPos) @@ -140,7 +126,7 @@ void CosmeticVertex::Save(Base::Writer &writer) const writer.Stream() << writer.ind() << "\n\n\n

"; diff --git a/src/Mod/TechDraw/Gui/QGIViewBalloon.cpp b/src/Mod/TechDraw/Gui/QGIViewBalloon.cpp index 19fc1133b3..bd8a9d3898 100644 --- a/src/Mod/TechDraw/Gui/QGIViewBalloon.cpp +++ b/src/Mod/TechDraw/Gui/QGIViewBalloon.cpp @@ -785,7 +785,7 @@ void QGIViewBalloon::drawBalloon(bool originDrag) double xAdj = 0.0; double yAdj = 0.0; - int endType = balloon->EndType.getValue(); + ArrowType endType = static_cast(balloon->EndType.getValue()); double arrowAdj = QGIArrow::getOverlapAdjust( endType, balloon->EndTypeScale.getValue() * QGIArrow::getPrefArrowSize()); @@ -948,15 +948,16 @@ QColor QGIViewBalloon::prefNormalColor() if (vp) { vpBalloon = dynamic_cast(vp); if (vpBalloon) { - App::Color fcColor = Preferences::getAccessibleColor(vpBalloon->Color.getValue()); + Base::Color fcColor = Preferences::getAccessibleColor(vpBalloon->Color.getValue()); setNormalColor(fcColor.asValue()); } } return getNormalColor(); } -int QGIViewBalloon::prefDefaultArrow() const { return Preferences::balloonArrow(); } - +ArrowType QGIViewBalloon::prefDefaultArrow() const { + return Preferences::balloonArrow(); +} //should this be an object property or global preference? //when would you want a crooked pyramid? diff --git a/src/Mod/TechDraw/Gui/QGIViewBalloon.h b/src/Mod/TechDraw/Gui/QGIViewBalloon.h index 990dccf3b8..5b46525db8 100644 --- a/src/Mod/TechDraw/Gui/QGIViewBalloon.h +++ b/src/Mod/TechDraw/Gui/QGIViewBalloon.h @@ -42,6 +42,7 @@ namespace TechDraw { class DrawViewBalloon; class DrawView; +enum class ArrowType : int; }// namespace TechDraw namespace TechDraw @@ -203,7 +204,7 @@ public: void setNormalColorAll(); QColor prefNormalColor(); - int prefDefaultArrow() const; + TechDraw::ArrowType prefDefaultArrow() const; bool prefOrthoPyramid() const; TechDraw::DrawViewBalloon* getBalloonFeat() diff --git a/src/Mod/TechDraw/Gui/QGIViewDimension.cpp b/src/Mod/TechDraw/Gui/QGIViewDimension.cpp index c4eff8be7f..60040fbbba 100644 --- a/src/Mod/TechDraw/Gui/QGIViewDimension.cpp +++ b/src/Mod/TechDraw/Gui/QGIViewDimension.cpp @@ -54,6 +54,7 @@ #include "QGIViewDimension.h" #include "PreferencesGui.h" #include "QGIArrow.h" +#include "QGIDatumLabel.h" #include "QGIDimLines.h" #include "QGIVertex.h" #include "QGCustomSvg.h" @@ -81,544 +82,6 @@ enum class SnapMode }; -QGIDatumLabel::QGIDatumLabel() : m_dragState(DragState::NoDrag) -{ - verticalSep = false; - posX = 0; - posY = 0; - - parent = nullptr; - - setCacheMode(QGraphicsItem::NoCache); - setFlag(ItemSendsGeometryChanges, true); - setFlag(ItemIsMovable, true); - setSelectability(true); - setFiltersChildEvents(true); - - m_textItems = new QGraphicsItemGroup(); - m_textItems->setParentItem(this); - m_dimText = new QGCustomText(); - m_dimText->setTightBounding(true); - m_dimText->setParentItem(m_textItems); - m_tolTextOver = new QGCustomText(); - m_tolTextOver->setTightBounding(true); - m_tolTextOver->setParentItem(m_textItems); - m_tolTextUnder = new QGCustomText(); - m_tolTextUnder->setTightBounding(true); - m_tolTextUnder->setParentItem(m_textItems); - m_unitText = new QGCustomText(); - m_unitText->setTightBounding(true); - m_unitText->setParentItem(m_textItems); - - m_frame = new QGraphicsRectItem(); - QPen framePen; - framePen.setWidthF(Rez::guiX(0.5)); - framePen.setColor(m_dimText->defaultTextColor()); - framePen.setJoinStyle(Qt::MiterJoin); - m_frame->setPen(framePen); - - m_ctrl = false; -} - -void QGIDatumLabel::setFramed(bool framed) -{ - if(framed) { - m_frame->setVisible(true); - m_frame->setParentItem(this); - } - else { - m_frame->setVisible(false); - m_frame->setParentItem(nullptr); - } -} - -QVariant QGIDatumLabel::itemChange(GraphicsItemChange change, const QVariant& value) -{ - if (change == ItemSelectedHasChanged && scene()) { - if (isSelected()) { - setPrettySel(); - } - else { - setPrettyNormal(); - if (m_dragState == DragState::Dragging) { - //stop the drag if we are no longer selected. - m_dragState = DragState::NoDrag; - Q_EMIT dragFinished(); - } - } - } - else if (change == ItemPositionHasChanged && scene()) { - if (!(QApplication::keyboardModifiers() & Qt::AltModifier)) { - QPointF newPos = value.toPointF(); //position within parent! - snapPosition(newPos); - } - - setLabelCenter(); - m_dragState = DragState::Dragging; - Q_EMIT dragging(m_ctrl); - } - - return QGraphicsItem::itemChange(change, value); -} - -void QGIDatumLabel::snapPosition(QPointF& pos) -{ - qreal snapPercent = 0.4; - double dimSpacing = Rez::guiX(activeDimAttributes.getCascadeSpacing()); - - auto* qgivd = dynamic_cast(parentItem()); - if (!qgivd) { - return; - } - auto* dim(dynamic_cast(qgivd->getViewObject())); - if (!dim) { - return; - } - - // We only have snap for distances constraints - std::string type = dim->Type.getValueAsString(); - if(type != "Distance" && type != "DistanceX" && type != "DistanceY") { - return; - } - - // 1 - We try to snap the label to its center position. - pointPair pp = dim->getLinearPoints(); - Base::Vector3d p1_3d = Rez::guiX(pp.first()); - Base::Vector3d p2_3d = Rez::guiX(pp.second()); - Base::Vector2d p1 = Base::Vector2d(p1_3d.x, p1_3d.y); - Base::Vector2d p2 = Base::Vector2d(p2_3d.x, p2_3d.y); - if (type == "DistanceX") { - p2 = Base::Vector2d(p2.x, p1.y); - } - else if (type == "DistanceY") { - p2 = Base::Vector2d(p1.x, p2.y); - } - Base::Vector2d mid = (p1 + p2) * 0.5; - Base::Vector2d dir = p2 - p1; - Base::Vector2d normal = Base::Vector2d(-dir.y, dir.x); - - Base::Vector2d toCenter = getPosToCenterVec(); - - Base::Vector2d posV = Base::Vector2d(pos.x(), pos.y()) + toCenter; - - Base::Vector2d projPnt; - projPnt.ProjectToLine(posV - mid, normal); - projPnt = projPnt + mid; - - if ((projPnt - posV).Length() < dimSpacing * snapPercent) { - posV = projPnt; - pos.setX(posV.x - toCenter.x); - pos.setY(posV.y - toCenter.y); - } - - // 2 - We check for coord/chain dimensions to offer proper snapping - auto* qgiv = dynamic_cast(qgivd->parentItem()); - if (qgiv) { - auto* dvp = dynamic_cast(qgiv->getViewObject()); - if (dvp) { - snapPercent = 0.2; - std::vector dims = dvp->getDimensions(); - for (auto& d : dims) { - if (d == dim) { continue; } - - std::string typei = d->Type.getValueAsString(); - if (typei != "Distance" && typei != "DistanceX" && typei != "DistanceY") { - continue; - } - - pp = d->getLinearPoints(); - Base::Vector3d ip1_3d = Rez::guiX(pp.first()); - Base::Vector3d ip2_3d = Rez::guiX(pp.second()); - - Base::Vector2d ip1 = Base::Vector2d(ip1_3d.x, ip1_3d.y); - Base::Vector2d ip2 = Base::Vector2d(ip2_3d.x, ip2_3d.y); - if (typei == "DistanceX") { - ip2 = Base::Vector2d(ip2.x, ip1.y); - } - else if (typei == "DistanceY") { - ip2 = Base::Vector2d(ip1.x, ip2.y); - } - - Base::Vector2d idir = ip2 - ip1; - - if (fabs(dir.x * idir.y - dir.y * idir.x) > Precision::Confusion()) { - //dimensions not parallel - continue; - } - - auto* vp = dynamic_cast(Gui::Application::Instance->getViewProvider(d)); - if (!vp) { continue; } - auto* qgivDi(dynamic_cast(vp->getQView())); - if (!qgivDi) { continue; } - auto labeli = qgivDi->getDatumLabel(); - if (!labeli) { continue; } - QPointF posi = labeli->pos(); - Base::Vector2d toCenteri = labeli->getPosToCenterVec(); - Base::Vector2d posVi = Base::Vector2d(posi.x(), posi.y()) + toCenteri; - - Base::Vector2d projPnt2; - projPnt2.ProjectToLine(posV - posVi, idir); - projPnt2 = projPnt2 + posVi; - - if ((projPnt2 - posV).Length() < dimSpacing * snapPercent) { - posV = projPnt2; - pos.setX(posV.x - toCenter.x); - pos.setY(posV.y - toCenter.y); - break; - } - else if (fabs((projPnt2 - posV).Length() - fabs(dimSpacing)) < dimSpacing * snapPercent) { - posV = projPnt2 + (posV - projPnt2).Normalize() * dimSpacing; - pos.setX(posV.x - toCenter.x); - pos.setY(posV.y - toCenter.y); - break; - } - } - } - } - - - setPos(pos); // no infinite loop because if pos doesn't change then itemChanged is not triggered. -} - -void QGIDatumLabel::mousePressEvent(QGraphicsSceneMouseEvent* event) -{ - if (event->modifiers() & Qt::ControlModifier) { - m_ctrl = true; - } - - QGraphicsItem::mousePressEvent(event); -} - -void QGIDatumLabel::mouseReleaseEvent(QGraphicsSceneMouseEvent* event) -{ - // Base::Console().Message("QGIDL::mouseReleaseEvent()\n"); - m_ctrl = false; - if (m_dragState == DragState::Dragging) { - m_dragState = DragState::NoDrag; - Q_EMIT dragFinished(); - } - - QGraphicsItem::mouseReleaseEvent(event); -} - -void QGIDatumLabel::mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event) -{ - QGIViewDimension* qgivDimension = dynamic_cast(parentItem()); - if (!qgivDimension) { - qWarning() << "QGIDatumLabel::mouseDoubleClickEvent: No parent item"; - return; - } - - auto ViewProvider = dynamic_cast( - qgivDimension->getViewProvider(qgivDimension->getViewObject())); - if (!ViewProvider) { - qWarning() << "QGIDatumLabel::mouseDoubleClickEvent: No valid view provider"; - return; - } - - ViewProvider->startDefaultEditMode(); - QGraphicsItem::mouseDoubleClickEvent(event); -} - -void QGIDatumLabel::hoverEnterEvent(QGraphicsSceneHoverEvent* event) -{ - Q_EMIT hover(true); - if (!isSelected()) { - setPrettyPre(); - } - else { - setPrettySel(); - } - QGraphicsItem::hoverEnterEvent(event); -} - -void QGIDatumLabel::hoverLeaveEvent(QGraphicsSceneHoverEvent* event) -{ - Q_EMIT hover(false); - if (!isSelected()) { - setPrettyNormal(); - } - else { - setPrettySel(); - } - - QGraphicsItem::hoverLeaveEvent(event); -} - -QRectF QGIDatumLabel::boundingRect() const -{ - return childrenBoundingRect(); -} - -QRectF QGIDatumLabel::tightBoundingRect() const -{ - QRectF totalRect; - for (QGraphicsItem* item : m_textItems->childItems()) { - auto* customText = dynamic_cast(item); - if (customText && !customText->toPlainText().isEmpty()) { - QRectF itemRect = customText->alignmentRect(); - QPointF pos = customText->pos(); - itemRect.translate(pos.x(), pos.y()); - totalRect = totalRect.isNull() ? itemRect : totalRect.united(itemRect); - } - } - int fontSize = m_dimText->font().pixelSize(); - int paddingLeft = fontSize * 0.2; - int paddingTop = fontSize * 0.1; - int paddingRight = fontSize * 0.2; - int paddingBottom = fontSize * 0.1; - return totalRect.adjusted(-paddingLeft, -paddingTop, paddingRight, paddingBottom); -} - -void QGIDatumLabel::updateFrameRect() { - prepareGeometryChange(); - m_frame->setRect(tightBoundingRect()); -} - -void QGIDatumLabel::setLineWidth(double lineWidth) -{ - QPen pen = m_frame->pen(); - pen.setWidthF(lineWidth); - m_frame->setPen(pen); -} - -void QGIDatumLabel::setFrameColor(QColor color) -{ - QPen pen = m_frame->pen(); - pen.setColor(color); - m_frame->setPen(pen); -} - -void QGIDatumLabel::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, - QWidget* widget) -{ - Q_UNUSED(widget); - Q_UNUSED(painter); - QStyleOptionGraphicsItem myOption(*option); - myOption.state &= ~QStyle::State_Selected; - - // painter->setPen(Qt::blue); - // painter->drawRect(boundingRect()); //good for debugging -} - -void QGIDatumLabel::setPosFromCenter(const double& xCenter, const double& yCenter) -{ - prepareGeometryChange(); - auto* qgivd = dynamic_cast(parentItem()); - if (!qgivd) { - return; - } - const auto dim(dynamic_cast(qgivd->getViewObject())); - if (!dim) { - return; - } - - //set label's Qt position(top, left) given boundingRect center point - Base::Vector2d vec = getPosToCenterVec(); - setPos(xCenter - vec.x, yCenter - vec.y); - - QString uText = m_unitText->toPlainText(); - if ((uText.size() > 0) && (uText.at(0) != QChar::fromLatin1(' '))) { - QString vText = m_dimText->toPlainText(); - vText = vText + uText; - m_dimText->setPlainText(vText); - m_unitText->setPlainText(QString()); - } - - QRectF labelBox = m_dimText->alignmentRect(); - double right = labelBox.right(); - double middle = labelBox.center().y(); - - //set unit position - QRectF unitBox = m_unitText->alignmentRect(); - double unitWidth = unitBox.width(); - double unitRight = right + unitWidth; - // Set the m_unitText font *baseline* at same height as the m_dimText font baseline - m_unitText->setPos(right, 0.0); - - //set tolerance position - QRectF overBox = m_tolTextOver->alignmentRect(); - double tolLeft = unitRight; - - // Adjust for difference in tight and original bounding box sizes, note the y-coord down system - QPointF tol_adj = m_tolTextOver->tightBoundingAdjust(); - m_tolTextOver->justifyLeftAt(tolLeft + tol_adj.x(), middle + tol_adj.y()/2.0, false); - tol_adj = m_tolTextUnder->tightBoundingAdjust(); - m_tolTextUnder->justifyLeftAt(tolLeft + tol_adj.x(), middle + overBox.height() + tol_adj.y()/2.0, false); -} - -void QGIDatumLabel::setLabelCenter() -{ - //save label's bRect center (posX, posY) given Qt position (top, left) - Base::Vector2d vec = getPosToCenterVec(); - posX = x() + vec.x; - posY = y() + vec.y; -} - -Base::Vector2d QGIDatumLabel::getPosToCenterVec() -{ - QPointF center = tightBoundingRect().center(); - - return Base::Vector2d(center.x(), center.y()); -} - -void QGIDatumLabel::setFont(QFont font) -{ - prepareGeometryChange(); - m_dimText->setFont(font); - m_unitText->setFont(font); - QFont tFont(font); - double fontSize = font.pixelSize(); - double tolAdj = getTolAdjust(); - tFont.setPixelSize(std::max(1, (int)(fontSize * tolAdj))); - m_tolTextOver->setFont(tFont); - m_tolTextUnder->setFont(tFont); - updateFrameRect(); -} - -void QGIDatumLabel::setDimString(QString text) -{ - prepareGeometryChange(); - m_dimText->setPlainText(text); - updateFrameRect(); -} - -void QGIDatumLabel::setDimString(QString text, qreal maxWidth) -{ - prepareGeometryChange(); - m_dimText->setPlainText(text); - m_dimText->setTextWidth(maxWidth); - updateFrameRect(); -} - -void QGIDatumLabel::setToleranceString() -{ - prepareGeometryChange(); - QGIViewDimension* qgivd = dynamic_cast(parentItem()); - if (!qgivd) { - return; - } - const auto dim(dynamic_cast(qgivd->getViewObject())); - if (!dim) { - return; - // don't show if both are zero or if EqualTolerance is true - } - else if (!dim->hasOverUnderTolerance() || dim->EqualTolerance.getValue() - || dim->TheoreticalExact.getValue()) { - m_tolTextOver->hide(); - m_tolTextUnder->hide(); - // we must explicitly empty the text otherwise the frame drawn for - // TheoreticalExact would be as wide as necessary for the text - m_tolTextOver->setPlainText(QString()); - m_tolTextUnder->setPlainText(QString()); - updateFrameRect(); - return; - } - - std::pair labelTexts, unitTexts; - - if (dim->ArbitraryTolerances.getValue()) { - labelTexts = dim->getFormattedToleranceValues(Format::FORMATTED);//copy tolerance spec - unitTexts.first = ""; - unitTexts.second = ""; - } - else { - if (dim->isMultiValueSchema()) { - labelTexts = dim->getFormattedToleranceValues(Format::UNALTERED);//don't format multis - unitTexts.first = ""; - unitTexts.second = ""; - } - else { - labelTexts = dim->getFormattedToleranceValues(Format::FORMATTED);// prefix value [unit] postfix - unitTexts = dim->getFormattedToleranceValues(Format::UNIT); //just the unit - } - } - - if (labelTexts.first.empty()) { - m_tolTextUnder->hide(); - } - else { - m_tolTextUnder->setPlainText(QString::fromUtf8(labelTexts.first.c_str())); - m_tolTextUnder->show(); - } - if (labelTexts.second.empty()) { - m_tolTextOver->hide(); - } - else { - m_tolTextOver->setPlainText(QString::fromUtf8(labelTexts.second.c_str())); - m_tolTextOver->show(); - } - - updateFrameRect(); -} - - -int QGIDatumLabel::getPrecision() -{ - if (Preferences::useGlobalDecimals()) { - return Base::UnitsApi::getDecimals(); - } - return Preferences::getPreferenceGroup("Dimensions")->GetInt("AltDecimals", 2); -} - -double QGIDatumLabel::getTolAdjust() -{ - return Preferences::getPreferenceGroup("Dimensions")->GetFloat("TolSizeAdjust", 0.50); -} - - -void QGIDatumLabel::setPrettySel() -{ - // Base::Console().Message("QGIDL::setPrettySel()\n"); - m_dimText->setPrettySel(); - m_tolTextOver->setPrettySel(); - m_tolTextUnder->setPrettySel(); - m_unitText->setPrettySel(); - setFrameColor(PreferencesGui::selectQColor()); - Q_EMIT setPretty(SEL); -} - -void QGIDatumLabel::setPrettyPre() -{ - // Base::Console().Message("QGIDL::setPrettyPre()\n"); - m_dimText->setPrettyPre(); - m_tolTextOver->setPrettyPre(); - m_tolTextUnder->setPrettyPre(); - m_unitText->setPrettyPre(); - setFrameColor(PreferencesGui::preselectQColor()); - Q_EMIT setPretty(PRE); -} - -void QGIDatumLabel::setPrettyNormal() -{ - // Base::Console().Message("QGIDL::setPrettyNormal()\n"); - m_dimText->setPrettyNormal(); - m_tolTextOver->setPrettyNormal(); - m_tolTextUnder->setPrettyNormal(); - m_unitText->setPrettyNormal(); - setFrameColor(PreferencesGui::normalQColor()); - Q_EMIT setPretty(NORMAL); -} - -void QGIDatumLabel::setColor(QColor color) -{ - // Base::Console().Message("QGIDL::setColor(%s)\n", qPrintable(c.name())); - m_colNormal = color; - m_dimText->setColor(m_colNormal); - m_tolTextOver->setColor(m_colNormal); - m_tolTextUnder->setColor(m_colNormal); - m_unitText->setColor(m_colNormal); - setFrameColor(m_colNormal); -} - -void QGIDatumLabel::setSelectability(bool val) -{ - setFlag(ItemIsSelectable, val); - setAcceptHoverEvents(val); - setAcceptedMouseButtons(val ? Qt::AllButtons : Qt::NoButton); -} - -//************************************************************** QGIViewDimension::QGIViewDimension() : dvDimension(nullptr), hasHover(false), m_lineWidth(0.0) { setHandlesChildEvents(false); @@ -1464,7 +927,7 @@ void QGIViewDimension::drawArrows(int count, const Base::Vector2d positions[], d arrow->setSize(arrowSize); arrow->setFlipped(flipped); - if (vp->ArrowStyle.getValue() != ArrowType::NONE) { + if (vp->ArrowStyle.getValue() != static_cast(ArrowType::NONE)) { arrow->draw(); arrow->show(); } @@ -2786,7 +2249,7 @@ QColor QGIViewDimension::prefNormalColor() if (vp) { vpDim = dynamic_cast(vp); if (vpDim) { - App::Color fcColor = vpDim->Color.getValue(); + Base::Color fcColor = vpDim->Color.getValue(); fcColor = Preferences::getAccessibleColor(fcColor); setNormalColor(fcColor.asValue()); } diff --git a/src/Mod/TechDraw/Gui/QGIViewDimension.h b/src/Mod/TechDraw/Gui/QGIViewDimension.h index 23179b8dd2..1546bfcaaf 100644 --- a/src/Mod/TechDraw/Gui/QGIViewDimension.h +++ b/src/Mod/TechDraw/Gui/QGIViewDimension.h @@ -52,111 +52,13 @@ namespace TechDrawGui { class QGCustomText; class QGIArrow; +class QGIDatumLabel; class QGIDimLines; class QGIViewDimension; class QGCustomSvg; class ViewProviderDimension; enum class DragState; -class QGIDatumLabel : public QGraphicsObject -{ -Q_OBJECT - -public: - QGIDatumLabel(); - ~QGIDatumLabel() override = default; - - enum {Type = QGraphicsItem::UserType + 107}; - int type() const override { return Type;} - - QRectF boundingRect() const override; - QRectF tightBoundingRect() const; - void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override; - void paint( QPainter *painter, - const QStyleOptionGraphicsItem *option, - QWidget *widget = nullptr ) override; - void setLabelCenter(); - void setPosFromCenter(const double &xCenter, const double &yCenter); - double X() const { return posX; } - double Y() const { return posY; } //minus posY? - Base::Vector2d getPosToCenterVec(); - - void setFont(QFont font); - QFont getFont() const { return m_dimText->font(); } - void setDimString(QString text); - void setDimString(QString text, qreal maxWidth); - void setToleranceString(); - void setPrettySel(); - void setPrettyPre(); - void setPrettyNormal(); - void setColor(QColor color); - void setSelectability(bool val); - void setFrameColor(QColor color); - - QGCustomText* getDimText() { return m_dimText; } - void setDimText(QGCustomText* newText) { m_dimText = newText; } - QGCustomText* getTolTextOver() { return m_tolTextOver; } - void setTolTextOver(QGCustomText* newTol) { m_tolTextOver = newTol; } - QGCustomText* getTolTextUnder() { return m_tolTextUnder; } - void setTolTextUnder(QGCustomText* newTol) { m_tolTextOver = newTol; } - - double getTolAdjust(); - - bool isFramed() const { return m_frame->parentItem(); } // If empty pointer, then no frame - void setFramed(bool framed); - - double getLineWidth() const { return m_frame->pen().widthF(); } - void setLineWidth(double lineWidth); - void setQDim(QGIViewDimension* qDim) { parent = qDim;} - -Q_SIGNALS: - void setPretty(int state); - void dragging(bool); - void hover(bool state); - void selected(bool state); - void dragFinished(); - -protected: - QVariant itemChange(GraphicsItemChange change, const QVariant &value) override; - void mousePressEvent(QGraphicsSceneMouseEvent *event) override; - void hoverEnterEvent(QGraphicsSceneHoverEvent *event) override; - void hoverLeaveEvent(QGraphicsSceneHoverEvent *event) override; - void mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event) override; - void updateFrameRect(); - - int getPrecision(); - - void snapPosition(QPointF& position); - - bool getVerticalSep() const { return verticalSep; } - void setVerticalSep(bool sep) { verticalSep = sep; } - std::vector getSeps() const { return seps; } - void setSeps(std::vector newSeps) { seps = newSeps; } - -private: - bool verticalSep; - std::vector seps; - - QGIViewDimension* parent; - - QGCustomText* m_dimText; - QGCustomText* m_tolTextOver; - QGCustomText* m_tolTextUnder; - QGCustomText* m_unitText; - QGraphicsItemGroup* m_textItems; - QGraphicsRectItem* m_frame; - QColor m_colNormal; - bool m_ctrl; - - double posX; - double posY; - - DragState m_dragState; - -private: -}; - -//******************************************************************* class TechDrawGuiExport QGIViewDimension : public QGIView { diff --git a/src/Mod/TechDraw/Gui/QGIViewPart.cpp b/src/Mod/TechDraw/Gui/QGIViewPart.cpp index b287351d4a..e3c691f987 100644 --- a/src/Mod/TechDraw/Gui/QGIViewPart.cpp +++ b/src/Mod/TechDraw/Gui/QGIViewPart.cpp @@ -379,7 +379,7 @@ void QGIViewPart::drawAllEdges() // geometry edge - apply format if applicable TechDraw::GeomFormat* gf = dvp->getGeomFormatBySelection(iEdge); if (gf) { - App::Color color = Preferences::getAccessibleColor(gf->m_format.getColor()); + Base::Color color = Preferences::getAccessibleColor(gf->m_format.getColor()); item->setNormalColor(color.asValue()); int lineNumber = gf->m_format.getLineNumber(); int qtStyle = gf->m_format.getStyle(); @@ -543,7 +543,7 @@ bool QGIViewPart::formatGeomFromCosmetic(std::string cTag, QGIEdge* item) auto partFeat(dynamic_cast(getViewObject())); TechDraw::CosmeticEdge* ce = partFeat ? partFeat->getCosmeticEdge(cTag) : nullptr; if (ce) { - App::Color color = Preferences::getAccessibleColor(ce->m_format.getColor()); + Base::Color color = Preferences::getAccessibleColor(ce->m_format.getColor()); item->setNormalColor(color.asValue()); item->setLinePen(m_dashedLineGenerator->getBestPen(ce->m_format.getLineNumber(), (Qt::PenStyle)ce->m_format.getStyle(), @@ -562,7 +562,7 @@ bool QGIViewPart::formatGeomFromCenterLine(std::string cTag, QGIEdge* item) auto partFeat(dynamic_cast(getViewObject())); TechDraw::CenterLine* cl = partFeat ? partFeat->getCenterLine(cTag) : nullptr; if (cl) { - App::Color color = Preferences::getAccessibleColor(cl->m_format.getColor()); + Base::Color color = Preferences::getAccessibleColor(cl->m_format.getColor()); item->setNormalColor(color.asValue()); item->setLinePen(m_dashedLineGenerator->getBestPen(cl->m_format.getLineNumber(), (Qt::PenStyle)cl->m_format.getStyle(), @@ -723,7 +723,7 @@ void QGIViewPart::drawSectionLine(TechDraw::DrawViewSection* viewSection, bool b QGISectionLine* sectionLine = new QGISectionLine(); addToGroup(sectionLine); sectionLine->setSymbol(const_cast(viewSection->SectionSymbol.getValue())); - App::Color color = Preferences::getAccessibleColor(vp->SectionLineColor.getValue()); + Base::Color color = Preferences::getAccessibleColor(vp->SectionLineColor.getValue()); sectionLine->setSectionColor(color.asValue()); sectionLine->setPathMode(false); @@ -818,7 +818,7 @@ void QGIViewPart::drawComplexSectionLine(TechDraw::DrawViewSection* viewSection, QGISectionLine* sectionLine = new QGISectionLine(); addToGroup(sectionLine); sectionLine->setSymbol(const_cast(viewSection->SectionSymbol.getValue())); - App::Color color = Preferences::getAccessibleColor(vp->SectionLineColor.getValue()); + Base::Color color = Preferences::getAccessibleColor(vp->SectionLineColor.getValue()); sectionLine->setSectionColor(color.asValue()); sectionLine->setPathMode(true); sectionLine->setPath(wirePath); @@ -957,7 +957,7 @@ void QGIViewPart::drawHighlight(TechDraw::DrawViewDetail* viewDetail, bool b) scene()->addItem(highlight); highlight->setReference(viewDetail->Reference.getValue()); - App::Color color = Preferences::getAccessibleColor(vp->HighlightLineColor.getValue()); + Base::Color color = Preferences::getAccessibleColor(vp->HighlightLineColor.getValue()); highlight->setColor(color.asValue()); highlight->setFeatureName(viewDetail->getNameInDocument()); highlight->setInteractive(true); @@ -1064,7 +1064,7 @@ void QGIViewPart::drawBreakLines() breakLine->setWidth(Rez::guiX(vp->HiddenWidth.getValue())); breakLine->setBreakType(breakType); breakLine->setZValue(ZVALUE::SECTIONLINE); - App::Color color = prefBreaklineColor(); + Base::Color color = prefBreaklineColor(); breakLine->setBreakColor(color.asValue()); breakLine->setRotation(-dbv->Rotation.getValue()); breakLine->draw(); @@ -1198,7 +1198,7 @@ bool QGIViewPart::prefPrintCenters() return printCenters; } -App::Color QGIViewPart::prefBreaklineColor() +Base::Color QGIViewPart::prefBreaklineColor() { return Preferences::getAccessibleColor(PreferencesGui::breaklineColor()); } diff --git a/src/Mod/TechDraw/Gui/QGIViewPart.h b/src/Mod/TechDraw/Gui/QGIViewPart.h index bfb7098faf..963de0610d 100644 --- a/src/Mod/TechDraw/Gui/QGIViewPart.h +++ b/src/Mod/TechDraw/Gui/QGIViewPart.h @@ -138,7 +138,7 @@ protected: void removeDecorations(); bool prefFaceEdges(); bool prefPrintCenters(); - App::Color prefBreaklineColor(); + Base::Color prefBreaklineColor(); bool formatGeomFromCosmetic(std::string cTag, QGIEdge* item); bool formatGeomFromCenterLine(std::string cTag, QGIEdge* item); diff --git a/src/Mod/TechDraw/Gui/QGSPage.cpp b/src/Mod/TechDraw/Gui/QGSPage.cpp index 7c17a30bc9..2be8bcab13 100644 --- a/src/Mod/TechDraw/Gui/QGSPage.cpp +++ b/src/Mod/TechDraw/Gui/QGSPage.cpp @@ -1250,7 +1250,7 @@ TechDraw::DrawPage* QGSPage::getDrawPage() { return m_vpPage->getDrawPage(); } QColor QGSPage::getBackgroundColor() { - App::Color fcColor; + Base::Color fcColor; fcColor.setPackedValue(Preferences::getPreferenceGroup("Colors")->GetUnsigned("Background", 0x70707000)); return fcColor.asValue(); } diff --git a/src/Mod/TechDraw/Gui/QGTracker.cpp b/src/Mod/TechDraw/Gui/QGTracker.cpp index c32eb66884..f188090297 100644 --- a/src/Mod/TechDraw/Gui/QGTracker.cpp +++ b/src/Mod/TechDraw/Gui/QGTracker.cpp @@ -477,7 +477,7 @@ void QGTracker::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QColor QGTracker::getTrackerColor() { - App::Color trackColor = App::Color((uint32_t) Preferences::getPreferenceGroup("Tracker")->GetUnsigned("TrackerColor", 0xFF000000)); + Base::Color trackColor = Base::Color((uint32_t) Preferences::getPreferenceGroup("Tracker")->GetUnsigned("TrackerColor", 0xFF000000)); return PreferencesGui::getAccessibleQColor(trackColor.asValue()); } diff --git a/src/Mod/TechDraw/Gui/QGVPage.cpp b/src/Mod/TechDraw/Gui/QGVPage.cpp index 840deaa174..bd1516ccaf 100644 --- a/src/Mod/TechDraw/Gui/QGVPage.cpp +++ b/src/Mod/TechDraw/Gui/QGVPage.cpp @@ -29,6 +29,7 @@ #include #include #include +#include #include #include #include @@ -558,7 +559,7 @@ TechDraw::DrawPage* QGVPage::getDrawPage() { return m_vpPage->getDrawPage(); } QColor QGVPage::getBackgroundColor() { - App::Color fcColor; + Base::Color fcColor; fcColor.setPackedValue(Preferences::getPreferenceGroup("Colors")->GetUnsigned("Background", 0x70707000)); return fcColor.asValue(); } diff --git a/src/Mod/TechDraw/Gui/TaskBalloon.cpp b/src/Mod/TechDraw/Gui/TaskBalloon.cpp index 2b0e37f0d7..b4cde3dc2d 100644 --- a/src/Mod/TechDraw/Gui/TaskBalloon.cpp +++ b/src/Mod/TechDraw/Gui/TaskBalloon.cpp @@ -168,7 +168,7 @@ void TaskBalloon::onTextChanged() void TaskBalloon::onColorChanged() { - App::Color ac; + Base::Color ac; ac.setValue(ui->textColor->color()); m_balloonVP->Color.setValue(ac); recomputeFeature(); diff --git a/src/Mod/TechDraw/Gui/TaskCenterLine.cpp b/src/Mod/TechDraw/Gui/TaskCenterLine.cpp index 6f20181c83..c6591ee96a 100644 --- a/src/Mod/TechDraw/Gui/TaskCenterLine.cpp +++ b/src/Mod/TechDraw/Gui/TaskCenterLine.cpp @@ -317,7 +317,7 @@ void TaskCenterLine::onColorChanged() return; } - App::Color ac; + Base::Color ac; ac.setValue(ui->cpLineColor->color()); m_cl->m_format.getColor().setValue(ui->cpLineColor->color()); m_partFeat->recomputeFeature(); @@ -430,7 +430,7 @@ void TaskCenterLine::createCenterLine() cl->setExtend(extendBy); cl->setRotate(rotate); cl->m_flip2Line = false; - App::Color ac; + Base::Color ac; ac.setValue(ui->cpLineColor->color()); cl->m_format.setColor(ac); cl->m_format.setWidth(ui->dsbWeight->value().getValue()); diff --git a/src/Mod/TechDraw/Gui/TaskDimRepair.cpp b/src/Mod/TechDraw/Gui/TaskDimRepair.cpp index b34bd98c7e..aaa73f94e8 100644 --- a/src/Mod/TechDraw/Gui/TaskDimRepair.cpp +++ b/src/Mod/TechDraw/Gui/TaskDimRepair.cpp @@ -128,21 +128,21 @@ void TaskDimRepair::slotUseSelection() StringVector acceptableGeometry({ "Edge", "Vertex", "Face" }); std::vector minimumCounts({1, 1, 1}); - std::vector acceptableDimensionGeometrys;//accept anything - DimensionGeometryType geometryRefs2d = validateDimSelection( + std::vector acceptableDimensionGeometrys;//accept anything + DimensionGeometry geometryRefs2d = validateDimSelection( references2d, acceptableGeometry, minimumCounts, acceptableDimensionGeometrys); - if (geometryRefs2d == isInvalid) { + if (geometryRefs2d == DimensionGeometry::isInvalid) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Incorrect Selection"), QObject::tr("Can not make dimension from selection")); return; } //what 3d geometry configuration did we receive? - DimensionGeometryType geometryRefs3d(isInvalid); - if (geometryRefs2d == TechDraw::isViewReference && !references3d.empty()) { + DimensionGeometry geometryRefs3d(DimensionGeometry::isInvalid); + if (geometryRefs2d == DimensionGeometry::isViewReference && !references3d.empty()) { geometryRefs3d = validateDimSelection3d( dvp, references3d, acceptableGeometry, minimumCounts, acceptableDimensionGeometrys); - if (geometryRefs3d == isInvalid) { + if (geometryRefs3d == DimensionGeometry::isInvalid) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Incorrect Selection"), QObject::tr("Can not make dimension from selection")); diff --git a/src/Mod/TechDraw/Gui/TaskDimension.cpp b/src/Mod/TechDraw/Gui/TaskDimension.cpp index 7f83ed375a..ad9b4777d0 100644 --- a/src/Mod/TechDraw/Gui/TaskDimension.cpp +++ b/src/Mod/TechDraw/Gui/TaskDimension.cpp @@ -322,7 +322,7 @@ void TaskDimension::onColorChanged() if (m_dimensionVP.expired()) { return; } - App::Color ac; + Base::Color ac; ac.setValue(ui->dimensionColor->color()); m_dimensionVP->Color.setValue(ac); recomputeFeature(); diff --git a/src/Mod/TechDraw/Gui/TaskGeomHatch.h b/src/Mod/TechDraw/Gui/TaskGeomHatch.h index c191c53a5e..32b5b3e343 100644 --- a/src/Mod/TechDraw/Gui/TaskGeomHatch.h +++ b/src/Mod/TechDraw/Gui/TaskGeomHatch.h @@ -76,12 +76,12 @@ private: std::string m_name; double m_scale; double m_weight; - App::Color m_color; + Base::Color m_color; std::string m_origFile; std::string m_origName; double m_origScale; double m_origWeight; - App::Color m_origColor; + Base::Color m_origColor; double m_rotation; double m_origRotation; Base::Vector3d m_offset; diff --git a/src/Mod/TechDraw/Gui/TaskHatch.cpp b/src/Mod/TechDraw/Gui/TaskHatch.cpp index 7a41c74779..78f84ed89f 100644 --- a/src/Mod/TechDraw/Gui/TaskHatch.cpp +++ b/src/Mod/TechDraw/Gui/TaskHatch.cpp @@ -218,7 +218,7 @@ void TaskHatch::createHatch() Gui::ViewProvider* vp = Gui::Application::Instance->getDocument(doc)->getViewProvider(m_hatch); m_vp = dynamic_cast(vp); if (m_vp) { - App::Color ac; + Base::Color ac; ac.setValue(ui->ccColor->color()); m_vp->HatchColor.setValue(ac); m_vp->HatchScale.setValue(ui->sbScale->value().getValue()); @@ -244,7 +244,7 @@ void TaskHatch::updateHatch() FeatName.c_str(), filespec.c_str()); - App::Color ac; + Base::Color ac; ac.setValue(ui->ccColor->color()); m_vp->HatchColor.setValue(ac); m_vp->HatchScale.setValue(ui->sbScale->value().getValue()); diff --git a/src/Mod/TechDraw/Gui/TaskHatch.h b/src/Mod/TechDraw/Gui/TaskHatch.h index b72d3c5dbe..4d4144c1a9 100644 --- a/src/Mod/TechDraw/Gui/TaskHatch.h +++ b/src/Mod/TechDraw/Gui/TaskHatch.h @@ -84,13 +84,13 @@ private: std::vector m_subs; std::string m_file; double m_scale; - App::Color m_color; + Base::Color m_color; double m_rotation; Base::Vector3d m_offset; std::string m_saveFile; double m_saveScale; - App::Color m_saveColor; + Base::Color m_saveColor; std::vector m_saveSubs; double m_saveRotation; Base::Vector3d m_saveOffset; diff --git a/src/Mod/TechDraw/Gui/TaskLeaderLine.cpp b/src/Mod/TechDraw/Gui/TaskLeaderLine.cpp index cebae32948..3c2593cb96 100644 --- a/src/Mod/TechDraw/Gui/TaskLeaderLine.cpp +++ b/src/Mod/TechDraw/Gui/TaskLeaderLine.cpp @@ -233,11 +233,11 @@ void TaskLeaderLine::setUiPrimary() } DrawGuiUtil::loadArrowBox(ui->cboxStartSym); - int aStyle = PreferencesGui::dimArrowStyle(); - ui->cboxStartSym->setCurrentIndex(aStyle); + ArrowType aStyle = PreferencesGui::dimArrowStyle(); + ui->cboxStartSym->setCurrentIndex(static_cast(aStyle)); DrawGuiUtil::loadArrowBox(ui->cboxEndSym); - ui->cboxEndSym->setCurrentIndex(TechDraw::ArrowType::NONE); + ui->cboxEndSym->setCurrentIndex(static_cast(TechDraw::ArrowType::NONE)); ui->dsbWeight->setUnit(Base::Unit::Length); ui->dsbWeight->setMinimum(0); @@ -313,7 +313,7 @@ void TaskLeaderLine::onEndSymbolChanged() void TaskLeaderLine::onColorChanged() { - App::Color ac; + Base::Color ac; ac.setValue(ui->cpLineColor->color()); m_lineVP->Color.setValue(ac); recomputeFeature(); @@ -395,7 +395,7 @@ void TaskLeaderLine::createLeaderFeature(std::vector sceneDeltas Gui::ViewProvider* vp = QGIView::getViewProvider(m_lineFeat); auto leadVP = dynamic_cast(vp); if (leadVP) { - App::Color ac; + Base::Color ac; ac.setValue(ui->cpLineColor->color()); leadVP->Color.setValue(ac); leadVP->LineWidth.setValue(ui->dsbWeight->rawValue()); @@ -433,7 +433,7 @@ void TaskLeaderLine::updateLeaderFeature() Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Edit Leader")); //waypoints & x, y are updated by QGILeaderLine (for edits only!) commonFeatureUpdate(); - App::Color ac; + Base::Color ac; ac.setValue(ui->cpLineColor->color()); m_lineVP->Color.setValue(ac); m_lineVP->LineWidth.setValue(ui->dsbWeight->rawValue()); diff --git a/src/Mod/TechDraw/Gui/TaskLineDecor.h b/src/Mod/TechDraw/Gui/TaskLineDecor.h index de7763d02e..75cfc50393 100644 --- a/src/Mod/TechDraw/Gui/TaskLineDecor.h +++ b/src/Mod/TechDraw/Gui/TaskLineDecor.h @@ -84,7 +84,7 @@ private: std::vector m_createdFormatTags; int m_style; - App::Color m_color; + Base::Color m_color; double m_weight; bool m_visible; bool m_apply; diff --git a/src/Mod/TechDraw/Gui/TaskLinkDim.cpp b/src/Mod/TechDraw/Gui/TaskLinkDim.cpp index 78a4553b0f..6f3aede92a 100644 --- a/src/Mod/TechDraw/Gui/TaskLinkDim.cpp +++ b/src/Mod/TechDraw/Gui/TaskLinkDim.cpp @@ -90,12 +90,12 @@ void TaskLinkDim::loadAvailDims() return; std::string result; - int selRefType = TechDraw::DrawViewDimension::getRefTypeSubElements(m_subs); + TechDraw::DrawViewDimension::RefType selRefType = TechDraw::DrawViewDimension::getRefTypeSubElements(m_subs); //int found = 0; for (auto* view : m_page->getViews()) { if (view->isDerivedFrom()) { auto* dim = static_cast(view); - int dimRefType = dim->getRefType(); + TechDraw::DrawViewDimension::RefType dimRefType = dim->getRefType(); if (dimRefType == selRefType) { //potential matches // found++; if (dim->has3DReferences()) { diff --git a/src/Mod/TechDraw/Gui/TaskProjGroup.cpp b/src/Mod/TechDraw/Gui/TaskProjGroup.cpp index fd1e7d9873..21d60f6dac 100644 --- a/src/Mod/TechDraw/Gui/TaskProjGroup.cpp +++ b/src/Mod/TechDraw/Gui/TaskProjGroup.cpp @@ -444,12 +444,12 @@ void TaskProjGroup::rotateButtonClicked() if (multiView) { //change Front View Dir by 90 - if (clicked == ui->butTopRotate) multiView->rotate("Up"); - else if (clicked == ui->butDownRotate) multiView->rotate("Down"); - else if (clicked == ui->butRightRotate) multiView->rotate("Right"); - else if (clicked == ui->butLeftRotate) multiView->rotate("Left"); - else if (clicked == ui->butCWRotate) multiView->spin("CW"); - else if (clicked == ui->butCCWRotate) multiView->spin("CCW"); + if (clicked == ui->butTopRotate) multiView->rotate(RotationMotion::Up); + else if (clicked == ui->butDownRotate) multiView->rotate(RotationMotion::Down); + else if (clicked == ui->butRightRotate) multiView->rotate(RotationMotion::Right); + else if (clicked == ui->butLeftRotate) multiView->rotate(RotationMotion::Left); + else if (clicked == ui->butCWRotate) multiView->spin(SpinDirection::CW); + else if (clicked == ui->butCCWRotate) multiView->spin(SpinDirection::CCW); else if (clicked == ui->butFront) { multiView->getAnchor()->Direction.setValue(Base::Vector3d(0.0, -1.0, 0.0)); multiView->getAnchor()->RotationVector.setValue(Base::Vector3d(1.0, 0.0, 0.0)); @@ -466,12 +466,12 @@ void TaskProjGroup::rotateButtonClicked() } else { auto* viewPart = static_cast(view); - if (clicked == ui->butTopRotate) viewPart->rotate("Up"); - else if (clicked == ui->butDownRotate) viewPart->rotate("Down"); - else if (clicked == ui->butRightRotate) viewPart->rotate("Right"); - else if (clicked == ui->butLeftRotate) viewPart->rotate("Left"); - else if (clicked == ui->butCWRotate) viewPart->spin("CW"); - else if (clicked == ui->butCCWRotate) viewPart->spin("CCW"); + if (clicked == ui->butTopRotate) viewPart->rotate(RotationMotion::Up); + else if (clicked == ui->butDownRotate) viewPart->rotate(RotationMotion::Down); + else if (clicked == ui->butRightRotate) viewPart->rotate(RotationMotion::Right); + else if (clicked == ui->butLeftRotate) viewPart->rotate(RotationMotion::Left); + else if (clicked == ui->butCWRotate) viewPart->spin(SpinDirection::CW); + else if (clicked == ui->butCCWRotate) viewPart->spin(SpinDirection::CCW); else if (clicked == ui->butFront) { viewPart->Direction.setValue(Base::Vector3d(0.0,-1.0,0.0)); viewPart->XDirection.setValue(Base::Vector3d(1.0, 0.0, 0.0)); diff --git a/src/Mod/TechDraw/Gui/TaskRichAnno.cpp b/src/Mod/TechDraw/Gui/TaskRichAnno.cpp index c580adc939..e8189af1a5 100644 --- a/src/Mod/TechDraw/Gui/TaskRichAnno.cpp +++ b/src/Mod/TechDraw/Gui/TaskRichAnno.cpp @@ -269,7 +269,7 @@ double TaskRichAnno::prefWeight() const return TechDraw::LineGroup::getDefaultWidth("Graphic"); } -App::Color TaskRichAnno::prefLineColor() +Base::Color TaskRichAnno::prefLineColor() { return PreferencesGui::leaderColor(); } @@ -319,7 +319,7 @@ void TaskRichAnno::createAnnoFeature() Gui::ViewProvider* vp = QGIView::getViewProvider(m_annoFeat); auto annoVP = dynamic_cast(vp); if (annoVP) { - App::Color ac; + Base::Color ac; ac.setValue(ui->cpFrameColor->color()); annoVP->LineColor.setValue(ac); annoVP->LineWidth.setValue(ui->dsbWidth->rawValue()); @@ -350,7 +350,7 @@ void TaskRichAnno::updateAnnoFeature() // Base::Console().Message("TRA::updateAnnoFeature()\n"); Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Edit Anno")); commonFeatureUpdate(); - App::Color ac; + Base::Color ac; ac.setValue(ui->cpFrameColor->color()); m_annoVP->LineColor.setValue(ac); m_annoVP->LineWidth.setValue(ui->dsbWidth->rawValue()); diff --git a/src/Mod/TechDraw/Gui/TaskRichAnno.h b/src/Mod/TechDraw/Gui/TaskRichAnno.h index 51799e05d1..d881a2b90a 100644 --- a/src/Mod/TechDraw/Gui/TaskRichAnno.h +++ b/src/Mod/TechDraw/Gui/TaskRichAnno.h @@ -87,7 +87,7 @@ protected: void enableTextUi(bool enable); void enableVPUi(bool enable); double prefWeight() const; - App::Color prefLineColor(); + Base::Color prefLineColor(); protected Q_SLOTS: void onSaveAndExit(QString); diff --git a/src/Mod/TechDraw/Gui/TaskSelectLineAttributes.cpp b/src/Mod/TechDraw/Gui/TaskSelectLineAttributes.cpp index 52e1247a6c..0c5782c654 100644 --- a/src/Mod/TechDraw/Gui/TaskSelectLineAttributes.cpp +++ b/src/Mod/TechDraw/Gui/TaskSelectLineAttributes.cpp @@ -165,7 +165,7 @@ bool TaskSelectLineAttributes::accept() } QColor qTemp = ui->cbColor->color(); - App::Color temp; + Base::Color temp; temp.set(qTemp.redF(), qTemp.greenF(), qTemp.blueF(), 1.0 - qTemp.alphaF()); LineFormat::getCurrentLineFormat().setColor(temp); diff --git a/src/Mod/TechDraw/Gui/TaskSelectLineAttributes.h b/src/Mod/TechDraw/Gui/TaskSelectLineAttributes.h index d353d10222..adf89cbf99 100644 --- a/src/Mod/TechDraw/Gui/TaskSelectLineAttributes.h +++ b/src/Mod/TechDraw/Gui/TaskSelectLineAttributes.h @@ -85,7 +85,7 @@ class Ui_TaskSelectLineAttributes; // float getWidthValue(); // void setColor(int); // int getColor() const {return color;} -// App::Color getColorValue(); +// Base::Color getColorValue(); // }; // class lineAttributes diff --git a/src/Mod/TechDraw/Gui/ViewProviderDimension.cpp b/src/Mod/TechDraw/Gui/ViewProviderDimension.cpp index 23682f4243..32a1813d9a 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderDimension.cpp +++ b/src/Mod/TechDraw/Gui/ViewProviderDimension.cpp @@ -85,7 +85,7 @@ ViewProviderDimension::ViewProviderDimension() "Arrow size in units"); ArrowStyle.setEnums(ArrowPropEnum::ArrowTypeEnums); // NOLINT - ADD_PROPERTY_TYPE(ArrowStyle, (PreferencesGui::dimArrowStyle()), + ADD_PROPERTY_TYPE(ArrowStyle, (static_cast(PreferencesGui::dimArrowStyle())), group, (App::PropertyType)(App::Prop_None), "Arrow end symbol - point, filled arrow, etc"); @@ -248,7 +248,7 @@ TechDraw::DrawViewDimension* ViewProviderDimension::getViewObject() const return dynamic_cast(pcObject); } -App::Color ViewProviderDimension::prefColor() const +Base::Color ViewProviderDimension::prefColor() const { return PreferencesGui::dimColor(); } diff --git a/src/Mod/TechDraw/Gui/ViewProviderDimension.h b/src/Mod/TechDraw/Gui/ViewProviderDimension.h index 962890e25f..f5a6b6c38c 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderDimension.h +++ b/src/Mod/TechDraw/Gui/ViewProviderDimension.h @@ -82,7 +82,7 @@ public: TechDraw::DrawViewDimension* getViewObject() const override; - App::Color prefColor() const; + Base::Color prefColor() const; std::string prefFont() const; double prefFontSize() const; double prefArrowSize() const; diff --git a/src/Mod/TechDraw/Gui/ViewProviderLeader.cpp b/src/Mod/TechDraw/Gui/ViewProviderLeader.cpp index 54ab2a34ef..f604b4eabb 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderLeader.cpp +++ b/src/Mod/TechDraw/Gui/ViewProviderLeader.cpp @@ -157,7 +157,7 @@ double ViewProviderLeader::getDefLineWeight() return TechDraw::LineGroup::getDefaultWidth("Thin"); } -App::Color ViewProviderLeader::getDefLineColor() +Base::Color ViewProviderLeader::getDefLineColor() { return PreferencesGui::leaderColor(); } diff --git a/src/Mod/TechDraw/Gui/ViewProviderLeader.h b/src/Mod/TechDraw/Gui/ViewProviderLeader.h index e07a5d8654..f7d5305073 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderLeader.h +++ b/src/Mod/TechDraw/Gui/ViewProviderLeader.h @@ -71,7 +71,7 @@ public: protected: double getDefLineWeight(); - App::Color getDefLineColor(); + Base::Color getDefLineColor(); void handleChangedPropertyType(Base::XMLReader &reader, const char *TypeName, App::Property * prop) override; private: diff --git a/src/Mod/TechDraw/Gui/ViewProviderRichAnno.cpp b/src/Mod/TechDraw/Gui/ViewProviderRichAnno.cpp index 5c8da54999..d6db537377 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderRichAnno.cpp +++ b/src/Mod/TechDraw/Gui/ViewProviderRichAnno.cpp @@ -121,7 +121,7 @@ TechDraw::DrawRichAnno* ViewProviderRichAnno::getFeature() const return dynamic_cast(pcObject); } -App::Color ViewProviderRichAnno::getDefLineColor() +Base::Color ViewProviderRichAnno::getDefLineColor() { return PreferencesGui::leaderColor(); } diff --git a/src/Mod/TechDraw/Gui/ViewProviderRichAnno.h b/src/Mod/TechDraw/Gui/ViewProviderRichAnno.h index ebff4129f1..10ce1aac57 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderRichAnno.h +++ b/src/Mod/TechDraw/Gui/ViewProviderRichAnno.h @@ -68,7 +68,7 @@ public: protected: - App::Color getDefLineColor(); + Base::Color getDefLineColor(); std::string getDefFont(); double getDefFontSize(); double getDefLineWeight(); diff --git a/src/Mod/TechDraw/Gui/ViewProviderSymbol.cpp b/src/Mod/TechDraw/Gui/ViewProviderSymbol.cpp index d41d311588..4dadf03991 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderSymbol.cpp +++ b/src/Mod/TechDraw/Gui/ViewProviderSymbol.cpp @@ -49,10 +49,6 @@ ViewProviderSymbol::ViewProviderSymbol() } -ViewProviderSymbol::~ViewProviderSymbol() -{ -} - void ViewProviderSymbol::updateData(const App::Property* prop) { TechDraw::DrawViewSymbol *obj = getViewObject(); @@ -92,11 +88,10 @@ PROPERTY_SOURCE(TechDrawGui::ViewProviderDraft, TechDrawGui::ViewProviderSymbol) ViewProviderDraft::ViewProviderDraft() { sPixmap = "actions/TechDraw_DraftView.svg"; + // svg files from Draft/BIM arrive in old scale + LegacyScaling.setValue(true); } -ViewProviderDraft::~ViewProviderDraft() -{ -} //************************************************************************** // Arch view @@ -107,8 +102,7 @@ PROPERTY_SOURCE(TechDrawGui::ViewProviderArch, TechDrawGui::ViewProviderSymbol) ViewProviderArch::ViewProviderArch() { sPixmap = "actions/TechDraw_ArchView.svg"; + // svg files from Draft/BIM arrive in old scale + LegacyScaling.setValue(true); } -ViewProviderArch::~ViewProviderArch() -{ -} diff --git a/src/Mod/TechDraw/Gui/ViewProviderSymbol.h b/src/Mod/TechDraw/Gui/ViewProviderSymbol.h index 67e31603ab..fa16bd498e 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderSymbol.h +++ b/src/Mod/TechDraw/Gui/ViewProviderSymbol.h @@ -33,45 +33,52 @@ namespace TechDrawGui { +//NOLINTBEGIN class TechDrawGuiExport ViewProviderSymbol : public ViewProviderDrawingView { PROPERTY_HEADER_WITH_OVERRIDE(TechDrawGui::ViewProviderSymbol); +//NOLINTEND public: /// constructor ViewProviderSymbol(); /// destructor - ~ViewProviderSymbol() override; + ~ViewProviderSymbol() override = default ; App::PropertyBool LegacyScaling; bool useNewSelectionModel() const override {return false;} - void updateData(const App::Property*) override; + void updateData(const App::Property* prop) override; void onChanged(const App::Property* prop) override; TechDraw::DrawViewSymbol* getViewObject() const override; }; +//NOLINTBEGIN class TechDrawGuiExport ViewProviderDraft : public ViewProviderSymbol { PROPERTY_HEADER_WITH_OVERRIDE(TechDrawGui::ViewProviderDraft); +//NOLINTEND public: /// constructor ViewProviderDraft(); /// destructor - ~ViewProviderDraft() override; + ~ViewProviderDraft() override = default ; }; + +//NOLINTBEGIN class TechDrawGuiExport ViewProviderArch : public ViewProviderSymbol { PROPERTY_HEADER_WITH_OVERRIDE(TechDrawGui::ViewProviderArch); +//NOLINTEND public: /// constructor ViewProviderArch(); /// destructor - ~ViewProviderArch() override; + ~ViewProviderArch() override = default ; }; } // namespace TechDrawGui diff --git a/src/Mod/TechDraw/Gui/ViewProviderViewPart.cpp b/src/Mod/TechDraw/Gui/ViewProviderViewPart.cpp index 0b19e1d9cd..15290a29d9 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderViewPart.cpp +++ b/src/Mod/TechDraw/Gui/ViewProviderViewPart.cpp @@ -386,14 +386,14 @@ bool ViewProviderViewPart::canDelete(App::DocumentObject *obj) const return true; } -App::Color ViewProviderViewPart::prefSectionColor() +Base::Color ViewProviderViewPart::prefSectionColor() { return PreferencesGui::sectionLineColor(); } -App::Color ViewProviderViewPart::prefHighlightColor() +Base::Color ViewProviderViewPart::prefHighlightColor() { - App::Color fcColor; + Base::Color fcColor; fcColor.setPackedValue(Preferences::getPreferenceGroup("Decorations")->GetUnsigned("HighlightColor", 0x00000000)); return fcColor; } diff --git a/src/Mod/TechDraw/Gui/ViewProviderViewPart.h b/src/Mod/TechDraw/Gui/ViewProviderViewPart.h index 65cc67ddf9..d19137e349 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderViewPart.h +++ b/src/Mod/TechDraw/Gui/ViewProviderViewPart.h @@ -74,8 +74,8 @@ public: bool doubleClicked(void) override; void onChanged(const App::Property *prop) override; void handleChangedPropertyType(Base::XMLReader &reader, const char *TypeName, App::Property * prop) override; - App::Color prefSectionColor(void); - App::Color prefHighlightColor(void); + Base::Color prefSectionColor(void); + Base::Color prefHighlightColor(void); int prefHighlightStyle(void); std::vector claimChildren(void) const override; diff --git a/src/Mod/TechDraw/Gui/ViewProviderViewSection.cpp b/src/Mod/TechDraw/Gui/ViewProviderViewSection.cpp index bedc15c6b3..a63ab53b15 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderViewSection.cpp +++ b/src/Mod/TechDraw/Gui/ViewProviderViewSection.cpp @@ -152,7 +152,7 @@ bool ViewProviderViewSection::doubleClicked() void ViewProviderViewSection::getParameters() { - App::Color cutColor = App::Color((uint32_t) Preferences::getPreferenceGroup("Colors")->GetUnsigned("CutSurfaceColor", 0xD3D3D3FF)); + Base::Color cutColor = Base::Color((uint32_t) Preferences::getPreferenceGroup("Colors")->GetUnsigned("CutSurfaceColor", 0xD3D3D3FF)); CutSurfaceColor.setValue(cutColor); double lineWeight = Preferences::getPreferenceGroup("PAT")->GetFloat("GeomWeight", 0.1); diff --git a/src/Mod/Test/Gui/CMakeLists.txt b/src/Mod/Test/Gui/CMakeLists.txt index 70e5d57181..1d44e0abd6 100644 --- a/src/Mod/Test/Gui/CMakeLists.txt +++ b/src/Mod/Test/Gui/CMakeLists.txt @@ -1,6 +1,10 @@ include_directories( ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_SOURCE_DIR}/src +) + +include_directories( + SYSTEM ${Boost_INCLUDE_DIRS} ${PYCXX_INCLUDE_DIR} ${Python3_INCLUDE_DIRS} diff --git a/src/Mod/Tux/NavigationIndicatorGui.py b/src/Mod/Tux/NavigationIndicatorGui.py index f2c8b8d81a..b76ea9afd5 100644 --- a/src/Mod/Tux/NavigationIndicatorGui.py +++ b/src/Mod/Tux/NavigationIndicatorGui.py @@ -74,9 +74,9 @@ def RePopulateIcons(): a6.setIcon(QtGui.QIcon(":/icons/NavigationOpenInventor_" + StyleSheetType + ".svg")) a7.setIcon(QtGui.QIcon(":/icons/NavigationOpenSCAD_" + StyleSheetType + ".svg")) a8.setIcon(QtGui.QIcon(":/icons/NavigationRevit_" + StyleSheetType + ".svg")) - a9.setIcon(QtGui.QIcon(":/icons/NavigationTinkerCAD_" + StyleSheetType + ".svg")) - a10.setIcon(QtGui.QIcon(":/icons/NavigationTouchpad_" + StyleSheetType + ".svg")) - a11.setIcon(QtGui.QIcon(":/icons/NavigationSolidWorks_" + StyleSheetType + ".svg")) + a9.setIcon(QtGui.QIcon(":/icons/NavigationSolidWorks_" + StyleSheetType + ".svg")) + a10.setIcon(QtGui.QIcon(":/icons/NavigationTinkerCAD_" + StyleSheetType + ".svg")) + a11.setIcon(QtGui.QIcon(":/icons/NavigationTouchpad_" + StyleSheetType + ".svg")) def retranslateUi(): @@ -474,6 +474,44 @@ def retranslateUi(): global t9 t9 = ( + "

SolidWorks " + + text06 + + """

+ + + + + + + + + + + + + + + +
""" + + text01 + + """""" + + text02 + + """""" + + text02 + + """""" + + text03 + + """""" + + text04 + + """
+ """ + + text08 + + ": " + + text10 + + "

" + ) + + global t10 + t10 = ( "

TinkerCAD " + text06 + """

@@ -501,8 +539,8 @@ def retranslateUi(): """ ) - global t10 - t10 = ( + global t11 + t11 = ( "

Touchpad " + text06 + """

@@ -567,44 +605,6 @@ def retranslateUi(): + "

" ) - global t11 - t11 = ( - "

SolidWorks " - + text06 - + """

- - - - - - - - - - - - - - - -
""" - + text01 - + """""" - + text02 - + """""" - + text02 - + """""" - + text03 - + """""" - + text04 - + """
- """ - + text08 - + ": " - + text10 - + "

" - ) - menuSettings.setTitle(translate("NavigationIndicator", "Settings")) menuOrbit.setTitle(translate("NavigationIndicator", "Orbit style")) aCompact.setText(translate("NavigationIndicator", "Compact")) @@ -700,19 +700,19 @@ a8.setData("Gui::RevitNavigationStyle") a8.setObjectName("Indicator_NavigationRevit") a9 = QtGui.QAction(gStyle) -a9.setText("TinkerCAD ") -a9.setData("Gui::TinkerCADNavigationStyle") -a9.setObjectName("Indicator_NavigationTinkerCAD") +a9.setText("SolidWorks ") +a9.setData("Gui::SolidWorksNavigationStyle") +a9.setObjectName("Indicator_NavigationSolidWorks") a10 = QtGui.QAction(gStyle) -a10.setText("Touchpad ") -a10.setData("Gui::TouchpadNavigationStyle") -a10.setObjectName("Indicator_NavigationTouchpad") +a10.setText("TinkerCAD ") +a10.setData("Gui::TinkerCADNavigationStyle") +a10.setObjectName("Indicator_NavigationTinkerCAD") a11 = QtGui.QAction(gStyle) -a11.setText("SolidWorks ") -a11.setData("Gui::SolidWorksNavigationStyle") -a11.setObjectName("Indicator_NavigationSolidWorks") +a11.setText("Touchpad ") +a11.setData("Gui::TouchpadNavigationStyle") +a11.setObjectName("Indicator_NavigationTouchpad") RePopulateIcons() diff --git a/src/Mod/Web/App/CMakeLists.txt b/src/Mod/Web/App/CMakeLists.txt index 33aa54b8de..390596168c 100644 --- a/src/Mod/Web/App/CMakeLists.txt +++ b/src/Mod/Web/App/CMakeLists.txt @@ -1,6 +1,10 @@ include_directories( ${CMAKE_CURRENT_BINARY_DIR} +) + +include_directories( + SYSTEM ${Boost_INCLUDE_DIRS} ${OCC_INCLUDE_DIR} ${PYCXX_INCLUDE_DIR} @@ -9,6 +13,7 @@ include_directories( ) include_directories( + SYSTEM ${QtNetwork_INCLUDE_DIRS} ) set(Web_LIBS diff --git a/src/Tools/ThumbnailProvider/CMakeLists.txt b/src/Tools/ThumbnailProvider/CMakeLists.txt index 7ed1ffde7a..09ce8be1a9 100644 --- a/src/Tools/ThumbnailProvider/CMakeLists.txt +++ b/src/Tools/ThumbnailProvider/CMakeLists.txt @@ -18,6 +18,10 @@ find_package(ZLIB REQUIRED) include_directories( . ../../../ +) + +include_directories( + SYSTEM ${ZLIB_INCLUDE_DIR} ) diff --git a/src/Tools/_TEMPLATE_/App/CMakeLists.txt b/src/Tools/_TEMPLATE_/App/CMakeLists.txt index 2230b37637..fc40ab2b67 100644 --- a/src/Tools/_TEMPLATE_/App/CMakeLists.txt +++ b/src/Tools/_TEMPLATE_/App/CMakeLists.txt @@ -1,5 +1,6 @@ include_directories( + SYSTEM ${Boost_INCLUDE_DIRS} ${OCC_INCLUDE_DIR} ${PYCXX_INCLUDE_DIR} diff --git a/src/Tools/_TEMPLATE_/Gui/CMakeLists.txt b/src/Tools/_TEMPLATE_/Gui/CMakeLists.txt index be41ef33f0..fc8fa5710f 100644 --- a/src/Tools/_TEMPLATE_/Gui/CMakeLists.txt +++ b/src/Tools/_TEMPLATE_/Gui/CMakeLists.txt @@ -2,6 +2,10 @@ include_directories( ${CMAKE_SOURCE_DIR}/src ${CMAKE_CURRENT_BINARY_DIR} +) + +include_directories( + SYSTEM ${Boost_INCLUDE_DIRS} ${COIN3D_INCLUDE_DIRS} ${ZLIB_INCLUDE_DIR} diff --git a/src/Tools/bindings/generate.py b/src/Tools/bindings/generate.py index b399b17a0c..62d6f2b896 100644 --- a/src/Tools/bindings/generate.py +++ b/src/Tools/bindings/generate.py @@ -57,10 +57,8 @@ def generate(filename, outputPath): Export.outputDir = outputPath + "/" Export.inputDir = os.path.dirname(filename) + "/" Export.export = GenerateModelInst.PythonExport[0] - Export.is_python = filename.endswith(".py") + Export.is_python = filename.endswith(".pyi") Export.Generate() - if Export.is_python: - Export.Compare() print("Done generating: " + GenerateModelInst.PythonExport[0].Name) diff --git a/src/Tools/bindings/model/generateModel_Python.py b/src/Tools/bindings/model/generateModel_Python.py index 5ebcb9d088..de97c1015a 100644 --- a/src/Tools/bindings/model/generateModel_Python.py +++ b/src/Tools/bindings/model/generateModel_Python.py @@ -210,10 +210,17 @@ def _parse_methods(class_node: ast.ClassDef) -> List[Methode]: """ methods = [] - for stmt in class_node.body: - if not isinstance(stmt, ast.FunctionDef): - continue + def collect_function_defs(nodes): + funcs = [] + for node in nodes: + if isinstance(node, ast.FunctionDef): + funcs.append(node) + elif isinstance(node, ast.If): + funcs.extend(collect_function_defs(node.body)) + funcs.extend(collect_function_defs(node.orelse)) + return funcs + for stmt in collect_function_defs(class_node.body): # Skip methods decorated with @overload skip_method = False for deco in stmt.decorator_list: @@ -542,28 +549,42 @@ def _parse_class(class_node, source_code: str, path: str, imports_mapping: dict) def parse_python_code(path: str) -> GenerateModel: """ Parse the given Python source code and build a GenerateModel containing - PythonExport entries for each class that inherits from a relevant binding class. + PythonExport entries. If any class is explicitly exported using @export, + only those classes are used. If no classes have the @export decorator, + then a single non-exported class is assumed to be the export. If there + are multiple non-exported classes, an exception is raised. """ - - source_code = None with open(path, "r") as file: source_code = file.read() tree = ast.parse(source_code) imports_mapping = _parse_imports(tree) - model = GenerateModel() + + explicit_exports = [] + non_explicit_exports = [] for node in tree.body: if isinstance(node, ast.ClassDef): py_export = _parse_class(node, source_code, path, imports_mapping) - model.PythonExport.append(py_export) + if py_export.IsExplicitlyExported: + explicit_exports.append(py_export) + else: + non_explicit_exports.append(py_export) - # Check for multiple non explicitly exported classes - non_exported_classes = [ - item for item in model.PythonExport if not getattr(item, "IsExplicitlyExported", False) - ] - if len(non_exported_classes) > 1: - raise Exception("Multiple non explicitly-exported classes were found, please use @export.") + model = GenerateModel() + if explicit_exports: + # Use only explicitly exported classes. + model.PythonExport.extend(explicit_exports) + else: + # No explicit exports; allow only one non-exported class. + if len(non_explicit_exports) == 1: + model.PythonExport.append(non_explicit_exports[0]) + elif len(non_explicit_exports) > 1: + raise Exception( + "Multiple non explicitly-exported classes were found, please use @export." + ) + else: + raise Exception("No classes found for export.") return model diff --git a/src/Tools/bindings/templates/templateClassPyExport.py b/src/Tools/bindings/templates/templateClassPyExport.py index 7fc9298fdf..1fa4582caa 100644 --- a/src/Tools/bindings/templates/templateClassPyExport.py +++ b/src/Tools/bindings/templates/templateClassPyExport.py @@ -15,7 +15,7 @@ def compareFiles(file1, file2): # Check if files exist for file in (file1, file2): if not os.path.exists(file): - raise FileNotFoundError(f"File not found: {file1} {file2}") + raise FileNotFoundError(f"File not found: {file}") # Read file contents with open(file1, "r", encoding="utf-8") as f1, open(file2, "r", encoding="utf-8") as f2: diff --git a/src/Tools/embedded/Qt/cxx/CMakeLists.txt b/src/Tools/embedded/Qt/cxx/CMakeLists.txt index 06455cda07..8640751f85 100644 --- a/src/Tools/embedded/Qt/cxx/CMakeLists.txt +++ b/src/Tools/embedded/Qt/cxx/CMakeLists.txt @@ -30,6 +30,11 @@ set(FREECAD_LIBPACK_DIR ${CMAKE_SOURCE_DIR} CACHE PATH "Directory of the FreeCA add_definitions(-DBOOST_ALL_DYN_LINK) include_directories( + ${FREECAD_SRC_DIR} +) + +include_directories( + SYSTEM ${Boost_INCLUDE_DIRS} #${COIN3D_INCLUDE_DIRS} ${PYCXX_INCLUDE_DIR} @@ -37,7 +42,6 @@ include_directories( ${Qt5Core_INCLUDE_DIRS} ${Qt5Gui_INCLUDE_DIRS} ${Qt5Widgets_INCLUDE_DIRS} - ${FREECAD_SRC_DIR} "${FREECAD_LIBPACK_DIR}/include" ) diff --git a/src/Tools/plugins/widget/CMakeLists.txt b/src/Tools/plugins/widget/CMakeLists.txt index 9052694f28..933caeea29 100644 --- a/src/Tools/plugins/widget/CMakeLists.txt +++ b/src/Tools/plugins/widget/CMakeLists.txt @@ -13,6 +13,7 @@ if (NOT IS_SUB_PROJECT) endif() include_directories( + SYSTEM ${Qt${FREECAD_QT_MAJOR_VERSION}Core_INCLUDE_DIRS} ${Qt${FREECAD_QT_MAJOR_VERSION}Widgets_INCLUDE_DIRS} ${Qt${FREECAD_QT_MAJOR_VERSION}Designer_INCLUDE_DIRS} diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 6ab8e40678..dd306ce4ee 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -68,6 +68,7 @@ function(setup_qt_test) endif() target_include_directories(${_testname}_Tests_run PUBLIC + SYSTEM ${PYCXX_INCLUDE_DIR} ${Python3_INCLUDE_DIRS} ${XercesC_INCLUDE_DIRS} @@ -134,7 +135,7 @@ if ( EXISTS "${CMAKE_SOURCE_DIR}/tests/lib/googletest" ) endif() add_subdirectory(src) -target_include_directories(Tests_run PUBLIC +target_include_directories(Tests_run SYSTEM PUBLIC ${PYCXX_INCLUDE_DIR} ${Python3_INCLUDE_DIRS} ${XercesC_INCLUDE_DIRS} diff --git a/tests/src/App/Color.cpp b/tests/src/App/Color.cpp index 32a262058e..73445c450a 100644 --- a/tests/src/App/Color.cpp +++ b/tests/src/App/Color.cpp @@ -1,6 +1,6 @@ #include #include -#include "App/Color.h" +#include "Base/Color.h" // NOLINTBEGIN TEST(TestColor, equal) @@ -9,10 +9,10 @@ TEST(TestColor, equal) int green = 170; int blue = 255; - App::Color color(red / 255.0F, green / 255.0F, blue / 255.0F); + Base::Color color(red / 255.0F, green / 255.0F, blue / 255.0F); uint32_t packed = color.getPackedValue(); - App::Color color2 {packed}; + Base::Color color2 {packed}; EXPECT_EQ(color, color2); } @@ -30,9 +30,9 @@ TEST(TestColor, packedValue) int green = 170; int blue = 255; - App::Color color(red / 255.0F, green / 255.0F, blue / 255.0F); + Base::Color color(red / 255.0F, green / 255.0F, blue / 255.0F); uint32_t packed = color.getPackedValue(); - App::Color color2 {packed}; + Base::Color color2 {packed}; EXPECT_EQ(std::lround(color2.r * 255.0F), 85); EXPECT_EQ(std::lround(color2.g * 255.0F), 170); @@ -45,9 +45,9 @@ TEST(TestColor, packedRGB) int green = 170; int blue = 255; - App::Color color(red / 255.0F, green / 255.0F, blue / 255.0F); + Base::Color color(red / 255.0F, green / 255.0F, blue / 255.0F); uint32_t packed = color.getPackedRGB(); - App::Color color2; + Base::Color color2; color2.setPackedRGB(packed); EXPECT_EQ(std::lround(color2.r * 255.0F), 85); @@ -62,9 +62,9 @@ TEST(TestColor, packedARGB) int blue = 255; int alpha = 127; - App::Color color(red / 255.0F, green / 255.0F, blue / 255.0F, alpha / 255.0F); + Base::Color color(red / 255.0F, green / 255.0F, blue / 255.0F, alpha / 255.0F); uint32_t packed = color.getPackedARGB(); - App::Color color2; + Base::Color color2; color2.setPackedARGB(packed); EXPECT_EQ(std::lround(color2.r * 255.0F), 85); @@ -136,7 +136,7 @@ TEST(TestColor, asPackedRGB) int blue = 255; IntColor intColor {red, green, blue}; - uint32_t packed = App::Color::asPackedRGB(intColor); + uint32_t packed = Base::Color::asPackedRGB(intColor); EXPECT_EQ(packed, 1437269760); @@ -148,9 +148,9 @@ TEST(TestColor, fromPackedRGB) int green = 170; int blue = 255; - App::Color color(red / 255.0F, green / 255.0F, blue / 255.0F); + Base::Color color(red / 255.0F, green / 255.0F, blue / 255.0F); - IntColor intColor = App::Color::fromPackedRGB(color.getPackedRGB()); + IntColor intColor = Base::Color::fromPackedRGB(color.getPackedRGB()); EXPECT_EQ(intColor.red(), red); EXPECT_EQ(intColor.green(), green); @@ -165,7 +165,7 @@ TEST(TestColor, asPackedRGBA) int alpha = 127; IntColor intColor {red, green, blue, alpha}; - uint32_t packed = App::Color::asPackedRGBA(intColor); + uint32_t packed = Base::Color::asPackedRGBA(intColor); EXPECT_EQ(packed, 1437269887); @@ -178,9 +178,9 @@ TEST(TestColor, fromPackedRGBA) int blue = 255; int alpha = 127; - App::Color color(red / 255.0F, green / 255.0F, blue / 255.0F, alpha / 255.0F); + Base::Color color(red / 255.0F, green / 255.0F, blue / 255.0F, alpha / 255.0F); - IntColor intColor = App::Color::fromPackedRGBA(color.getPackedValue()); + IntColor intColor = Base::Color::fromPackedRGBA(color.getPackedValue()); EXPECT_EQ(intColor.red(), red); EXPECT_EQ(intColor.green(), green); @@ -195,7 +195,7 @@ TEST(TestColor, setValue) int blue = 255; IntColor intColor {red, green, blue}; - App::Color color {}; + Base::Color color {}; color.setValue(intColor); EXPECT_FLOAT_EQ(color.r, 85.0F / 255.0F); @@ -209,7 +209,7 @@ TEST(TestColor, asValue) int green = 170; int blue = 255; - App::Color color(red / 255.0F, green / 255.0F, blue / 255.0F); + Base::Color color(red / 255.0F, green / 255.0F, blue / 255.0F); IntColor intColor = color.asValue(); @@ -224,14 +224,14 @@ TEST(TestColor, asHexString) int green = 170; int blue = 255; - App::Color color(red / 255.0F, green / 255.0F, blue / 255.0F); + Base::Color color(red / 255.0F, green / 255.0F, blue / 255.0F); EXPECT_EQ(color.asHexString(), "#55AAFF"); } TEST(TestColor, fromHexString) { - App::Color color; + Base::Color color; EXPECT_FALSE(color.fromHexString(std::string(""))); EXPECT_FALSE(color.fromHexString(std::string("abcdef"))); EXPECT_TRUE(color.fromHexString(std::string("#abcdef"))); diff --git a/tests/src/Mod/Assembly/CMakeLists.txt b/tests/src/Mod/Assembly/CMakeLists.txt index e8422f1c60..3d4314f551 100644 --- a/tests/src/Mod/Assembly/CMakeLists.txt +++ b/tests/src/Mod/Assembly/CMakeLists.txt @@ -1,5 +1,5 @@ -target_include_directories(Assembly_tests_run PUBLIC +target_include_directories(Assembly_tests_run SYSTEM PUBLIC ${EIGEN3_INCLUDE_DIR} ${OCC_INCLUDE_DIR} ${PYCXX_INCLUDE_DIR} diff --git a/tests/src/Mod/Material/App/CMakeLists.txt b/tests/src/Mod/Material/App/CMakeLists.txt index 1d72f944b2..b6b4cd949a 100644 --- a/tests/src/Mod/Material/App/CMakeLists.txt +++ b/tests/src/Mod/Material/App/CMakeLists.txt @@ -8,7 +8,7 @@ target_sources(Material_tests_run PRIVATE TestModelProperties.cpp ) -target_include_directories(Material_tests_run PUBLIC +target_include_directories(Material_tests_run SYSTEM PUBLIC ${QtCore_INCLUDE_DIRS} ) diff --git a/tests/src/Mod/Material/CMakeLists.txt b/tests/src/Mod/Material/CMakeLists.txt index 1b778ffaa5..a9ad17f7b7 100644 --- a/tests/src/Mod/Material/CMakeLists.txt +++ b/tests/src/Mod/Material/CMakeLists.txt @@ -1,5 +1,5 @@ -target_include_directories(Material_tests_run PUBLIC +target_include_directories(Material_tests_run SYSTEM PUBLIC ${EIGEN3_INCLUDE_DIR} ${OCC_INCLUDE_DIR} ${PYCXX_INCLUDE_DIR} diff --git a/tests/src/Mod/Measure/CMakeLists.txt b/tests/src/Mod/Measure/CMakeLists.txt index d6ad356ded..cb17c1de25 100644 --- a/tests/src/Mod/Measure/CMakeLists.txt +++ b/tests/src/Mod/Measure/CMakeLists.txt @@ -1,5 +1,5 @@ -target_include_directories(Measure_tests_run PUBLIC +target_include_directories(Measure_tests_run SYSTEM PUBLIC ${EIGEN3_INCLUDE_DIR} ${OCC_INCLUDE_DIR} ${PYCXX_INCLUDE_DIR} diff --git a/tests/src/Mod/Mesh/CMakeLists.txt b/tests/src/Mod/Mesh/CMakeLists.txt index 94d7d4ab86..e044f94020 100644 --- a/tests/src/Mod/Mesh/CMakeLists.txt +++ b/tests/src/Mod/Mesh/CMakeLists.txt @@ -1,5 +1,5 @@ -target_include_directories(Mesh_tests_run PUBLIC +target_include_directories(Mesh_tests_run SYSTEM PUBLIC ${EIGEN3_INCLUDE_DIR} ${OCC_INCLUDE_DIR} ${PYCXX_INCLUDE_DIR} diff --git a/tests/src/Mod/MeshPart/CMakeLists.txt b/tests/src/Mod/MeshPart/CMakeLists.txt index dd73d83243..47602eec6b 100644 --- a/tests/src/Mod/MeshPart/CMakeLists.txt +++ b/tests/src/Mod/MeshPart/CMakeLists.txt @@ -1,5 +1,5 @@ -target_include_directories(MeshPart_tests_run PUBLIC +target_include_directories(MeshPart_tests_run SYSTEM PUBLIC ${EIGEN3_INCLUDE_DIR} ${OCC_INCLUDE_DIR} ${PYCXX_INCLUDE_DIR} diff --git a/tests/src/Mod/Part/CMakeLists.txt b/tests/src/Mod/Part/CMakeLists.txt index d0e0ad606b..4e6a35b52b 100644 --- a/tests/src/Mod/Part/CMakeLists.txt +++ b/tests/src/Mod/Part/CMakeLists.txt @@ -1,5 +1,5 @@ -target_include_directories(Part_tests_run PUBLIC +target_include_directories(Part_tests_run SYSTEM PUBLIC ${EIGEN3_INCLUDE_DIR} ${OCC_INCLUDE_DIR} ${PYCXX_INCLUDE_DIR} diff --git a/tests/src/Mod/PartDesign/CMakeLists.txt b/tests/src/Mod/PartDesign/CMakeLists.txt index ded38dbda2..bf21365c0a 100644 --- a/tests/src/Mod/PartDesign/CMakeLists.txt +++ b/tests/src/Mod/PartDesign/CMakeLists.txt @@ -1,5 +1,5 @@ -target_include_directories(PartDesign_tests_run PUBLIC +target_include_directories(PartDesign_tests_run SYSTEM PUBLIC ${EIGEN3_INCLUDE_DIR} ${OCC_INCLUDE_DIR} ${PYCXX_INCLUDE_DIR} diff --git a/tests/src/Mod/Points/App/Points.cpp b/tests/src/Mod/Points/App/Points.cpp index 452e160ae2..cf82496747 100644 --- a/tests/src/Mod/Points/App/Points.cpp +++ b/tests/src/Mod/Points/App/Points.cpp @@ -46,9 +46,9 @@ protected: std::vector vec(8, Base::Vector3f(0, 0, 1)); return vec; } - std::vector getColors() const + std::vector getColors() const { - std::vector col(8); + std::vector col(8); col[0].set(0, 0, 0); col[1].set(0, 0, 1); col[2].set(0, 1, 0); diff --git a/tests/src/Mod/Points/CMakeLists.txt b/tests/src/Mod/Points/CMakeLists.txt index 650b2afb86..9d3a3fbee0 100644 --- a/tests/src/Mod/Points/CMakeLists.txt +++ b/tests/src/Mod/Points/CMakeLists.txt @@ -1,5 +1,5 @@ -target_include_directories(Points_tests_run PUBLIC +target_include_directories(Points_tests_run SYSTEM PUBLIC ${EIGEN3_INCLUDE_DIR} ${OCC_INCLUDE_DIR} ${PYCXX_INCLUDE_DIR} diff --git a/tests/src/Mod/Sketcher/App/SketchObject.cpp b/tests/src/Mod/Sketcher/App/SketchObject.cpp index 603ec299e9..954308353c 100644 --- a/tests/src/Mod/Sketcher/App/SketchObject.cpp +++ b/tests/src/Mod/Sketcher/App/SketchObject.cpp @@ -134,7 +134,8 @@ TEST_F(SketchObjectTest, testGetPointFromGeomPoint) auto ptMid = Sketcher::SketchObject::getPoint(&point, Sketcher::PointPos::mid); auto ptEnd = Sketcher::SketchObject::getPoint(&point, Sketcher::PointPos::end); // TODO: Maybe we want this to give an error instead of some default value - auto ptNone = Sketcher::SketchObject::getPoint(&point, Sketcher::PointPos::none); + [[maybe_unused]] auto ptNone = + Sketcher::SketchObject::getPoint(&point, Sketcher::PointPos::none); // Assert EXPECT_DOUBLE_EQ(ptStart[0], 1.0); @@ -156,10 +157,12 @@ TEST_F(SketchObjectTest, testGetPointFromGeomLineSegment) // Act auto ptStart = Sketcher::SketchObject::getPoint(&lineSeg, Sketcher::PointPos::start); // TODO: Maybe we want this to give an error instead of some default value - auto ptMid = Sketcher::SketchObject::getPoint(&lineSeg, Sketcher::PointPos::mid); + [[maybe_unused]] auto ptMid = + Sketcher::SketchObject::getPoint(&lineSeg, Sketcher::PointPos::mid); auto ptEnd = Sketcher::SketchObject::getPoint(&lineSeg, Sketcher::PointPos::end); // TODO: Maybe we want this to give an error instead of some default value - auto ptNone = Sketcher::SketchObject::getPoint(&lineSeg, Sketcher::PointPos::none); + [[maybe_unused]] auto ptNone = + Sketcher::SketchObject::getPoint(&lineSeg, Sketcher::PointPos::none); // Assert EXPECT_DOUBLE_EQ(ptStart[0], 1.0); @@ -184,7 +187,8 @@ TEST_F(SketchObjectTest, testGetPointFromGeomCircle) // TODO: Maybe we want this to give an error instead of some default value auto ptEnd = Sketcher::SketchObject::getPoint(&circle, Sketcher::PointPos::end); // TODO: Maybe we want this to give an error instead of some default value - auto ptNone = Sketcher::SketchObject::getPoint(&circle, Sketcher::PointPos::none); + [[maybe_unused]] auto ptNone = + Sketcher::SketchObject::getPoint(&circle, Sketcher::PointPos::none); // Assert // NOTE: Presently, start/end points of a circle are defined as the point on circle right of the @@ -215,7 +219,8 @@ TEST_F(SketchObjectTest, testGetPointFromGeomEllipse) // TODO: Maybe we want this to give an error instead of some default value auto ptEnd = Sketcher::SketchObject::getPoint(&ellipse, Sketcher::PointPos::end); // TODO: Maybe we want this to give an error instead of some default value - auto ptNone = Sketcher::SketchObject::getPoint(&ellipse, Sketcher::PointPos::none); + [[maybe_unused]] auto ptNone = + Sketcher::SketchObject::getPoint(&ellipse, Sketcher::PointPos::none); // Assert // NOTE: Presently, start/end points of an ellipse are defined as the point on the major axis in @@ -243,7 +248,8 @@ TEST_F(SketchObjectTest, testGetPointFromGeomArcOfCircle) auto ptMid = Sketcher::SketchObject::getPoint(&arcOfCircle, Sketcher::PointPos::mid); auto ptEnd = Sketcher::SketchObject::getPoint(&arcOfCircle, Sketcher::PointPos::end); // TODO: Maybe we want this to give an error instead of some default value - auto ptNone = Sketcher::SketchObject::getPoint(&arcOfCircle, Sketcher::PointPos::none); + [[maybe_unused]] auto ptNone = + Sketcher::SketchObject::getPoint(&arcOfCircle, Sketcher::PointPos::none); // Assert // NOTE: parameters for arc of circle are CCW angles from positive x-axis @@ -273,7 +279,8 @@ TEST_F(SketchObjectTest, testGetPointFromGeomArcOfEllipse) auto ptMid = Sketcher::SketchObject::getPoint(&arcOfEllipse, Sketcher::PointPos::mid); auto ptEnd = Sketcher::SketchObject::getPoint(&arcOfEllipse, Sketcher::PointPos::end); // TODO: Maybe we want this to give an error instead of some default value - auto ptNone = Sketcher::SketchObject::getPoint(&arcOfEllipse, Sketcher::PointPos::none); + [[maybe_unused]] auto ptNone = + Sketcher::SketchObject::getPoint(&arcOfEllipse, Sketcher::PointPos::none); // Assert // NOTE: parameters for arc of ellipse are CCW angles from positive x-axis @@ -299,11 +306,14 @@ TEST_F(SketchObjectTest, testGetPointFromGeomArcOfHyperbola) arcOfHyperbola.setRange(startParam, endParam, true); // Act - auto ptStart = Sketcher::SketchObject::getPoint(&arcOfHyperbola, Sketcher::PointPos::start); + [[maybe_unused]] auto ptStart = + Sketcher::SketchObject::getPoint(&arcOfHyperbola, Sketcher::PointPos::start); auto ptMid = Sketcher::SketchObject::getPoint(&arcOfHyperbola, Sketcher::PointPos::mid); - auto ptEnd = Sketcher::SketchObject::getPoint(&arcOfHyperbola, Sketcher::PointPos::end); + [[maybe_unused]] auto ptEnd = + Sketcher::SketchObject::getPoint(&arcOfHyperbola, Sketcher::PointPos::end); // TODO: Maybe we want this to give an error instead of some default value - auto ptNone = Sketcher::SketchObject::getPoint(&arcOfHyperbola, Sketcher::PointPos::none); + [[maybe_unused]] auto ptNone = + Sketcher::SketchObject::getPoint(&arcOfHyperbola, Sketcher::PointPos::none); // Assert // FIXME: Figure out how this is defined @@ -327,11 +337,14 @@ TEST_F(SketchObjectTest, testGetPointFromGeomArcOfParabola) arcOfParabola.setRange(startParam, endParam, true); // Act - auto ptStart = Sketcher::SketchObject::getPoint(&arcOfParabola, Sketcher::PointPos::start); + [[maybe_unused]] auto ptStart = + Sketcher::SketchObject::getPoint(&arcOfParabola, Sketcher::PointPos::start); auto ptMid = Sketcher::SketchObject::getPoint(&arcOfParabola, Sketcher::PointPos::mid); - auto ptEnd = Sketcher::SketchObject::getPoint(&arcOfParabola, Sketcher::PointPos::end); + [[maybe_unused]] auto ptEnd = + Sketcher::SketchObject::getPoint(&arcOfParabola, Sketcher::PointPos::end); // TODO: Maybe we want this to give an error instead of some default value - auto ptNone = Sketcher::SketchObject::getPoint(&arcOfParabola, Sketcher::PointPos::none); + [[maybe_unused]] auto ptNone = + Sketcher::SketchObject::getPoint(&arcOfParabola, Sketcher::PointPos::none); // Assert // FIXME: Figure out how this is defined @@ -366,10 +379,12 @@ TEST_F(SketchObjectTest, testGetPointFromGeomBSplineCurveNonPeriodic) // Act auto ptStart = Sketcher::SketchObject::getPoint(&nonPeriodicBSpline, Sketcher::PointPos::start); // TODO: Maybe we want this to give an error instead of some default value - auto ptMid = Sketcher::SketchObject::getPoint(&nonPeriodicBSpline, Sketcher::PointPos::mid); + [[maybe_unused]] auto ptMid = + Sketcher::SketchObject::getPoint(&nonPeriodicBSpline, Sketcher::PointPos::mid); auto ptEnd = Sketcher::SketchObject::getPoint(&nonPeriodicBSpline, Sketcher::PointPos::end); // TODO: Maybe we want this to give an error instead of some default value - auto ptNone = Sketcher::SketchObject::getPoint(&nonPeriodicBSpline, Sketcher::PointPos::none); + [[maybe_unused]] auto ptNone = + Sketcher::SketchObject::getPoint(&nonPeriodicBSpline, Sketcher::PointPos::none); // Assert EXPECT_DOUBLE_EQ(ptStart[0], poles.front()[0]); @@ -402,11 +417,13 @@ TEST_F(SketchObjectTest, testGetPointFromGeomBSplineCurvePeriodic) // TODO: Maybe we want this to give an error instead of some default value auto ptStart = Sketcher::SketchObject::getPoint(&periodicBSpline, Sketcher::PointPos::start); // TODO: Maybe we want this to give an error instead of some default value - auto ptMid = Sketcher::SketchObject::getPoint(&periodicBSpline, Sketcher::PointPos::mid); + [[maybe_unused]] auto ptMid = + Sketcher::SketchObject::getPoint(&periodicBSpline, Sketcher::PointPos::mid); // TODO: Maybe we want this to give an error instead of some default value auto ptEnd = Sketcher::SketchObject::getPoint(&periodicBSpline, Sketcher::PointPos::end); // TODO: Maybe we want this to give an error instead of some default value - auto ptNone = Sketcher::SketchObject::getPoint(&periodicBSpline, Sketcher::PointPos::none); + [[maybe_unused]] auto ptNone = + Sketcher::SketchObject::getPoint(&periodicBSpline, Sketcher::PointPos::none); // Assert // With non-trivial values for weights, knots, mults, etc, getting the coordinates is diff --git a/tests/src/Mod/Sketcher/CMakeLists.txt b/tests/src/Mod/Sketcher/CMakeLists.txt index ce025bcc90..201ee118f8 100644 --- a/tests/src/Mod/Sketcher/CMakeLists.txt +++ b/tests/src/Mod/Sketcher/CMakeLists.txt @@ -1,5 +1,5 @@ -target_include_directories(Sketcher_tests_run PUBLIC +target_include_directories(Sketcher_tests_run SYSTEM PUBLIC ${EIGEN3_INCLUDE_DIR} ${OCC_INCLUDE_DIR} ${PYCXX_INCLUDE_DIR} diff --git a/tests/src/Mod/Spreadsheet/CMakeLists.txt b/tests/src/Mod/Spreadsheet/CMakeLists.txt index 306c5a3ee9..ec78e021b7 100644 --- a/tests/src/Mod/Spreadsheet/CMakeLists.txt +++ b/tests/src/Mod/Spreadsheet/CMakeLists.txt @@ -1,5 +1,5 @@ -target_include_directories(Spreadsheet_tests_run PUBLIC +target_include_directories(Spreadsheet_tests_run SYSTEM PUBLIC ${EIGEN3_INCLUDE_DIR} ${OCC_INCLUDE_DIR} ${PYCXX_INCLUDE_DIR}