From: Mathieu Westphal Date: Thu, 10 Oct 2019 08:51:29 +0000 (+0000) Subject: Porting to ParaView 5.8 X-Git-Tag: V9_5_0a2~2 X-Git-Url: http://git.salome-platform.org/gitweb/?a=commitdiff_plain;h=1b88bf920850aabea9625aa061fd4ec8d4bd5210;p=modules%2Fparavis.git Porting to ParaView 5.8 --- diff --git a/CMakeLists.txt b/CMakeLists.txt index d69f6db0..a0c2ce45 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -25,6 +25,9 @@ IF(WIN32) SET( CMAKE_SHARED_LINKER_FLAGS_DEBUG "${replacementFlags}" ) ENDIF(WIN32) +# For correct Qt 5 detection procedure +CMAKE_POLICY(SET CMP0053 NEW) + # Ensure a proper linker behavior: CMAKE_POLICY(SET CMP0003 NEW) IF(WIN32) diff --git a/src/.gitignore b/src/.gitignore new file mode 100644 index 00000000..c18dd8d8 --- /dev/null +++ b/src/.gitignore @@ -0,0 +1 @@ +__pycache__/ diff --git a/src/Insitu/VisualizationLibrary/CMakeLists.txt b/src/Insitu/VisualizationLibrary/CMakeLists.txt index 880976cf..41547dd7 100644 --- a/src/Insitu/VisualizationLibrary/CMakeLists.txt +++ b/src/Insitu/VisualizationLibrary/CMakeLists.txt @@ -15,7 +15,6 @@ SET(_link_LIBRARIES ${MEDCoupling_medcoupling} ${MEDCoupling_interpkernel} ${MPI_LIBRARIES} - ${VTK_LIBRARIES} ${PARAVIS_MEDLoaderForPV} ${MEDCoupling_medloader} ${MEDFILE_C_LIBRARIES} diff --git a/src/PVGUI/CMakeLists.txt b/src/PVGUI/CMakeLists.txt index fa183e08..bf2396b2 100644 --- a/src/PVGUI/CMakeLists.txt +++ b/src/PVGUI/CMakeLists.txt @@ -35,9 +35,6 @@ INCLUDE_DIRECTORIES( ADD_DEFINITIONS(${KERNEL_DEFINITIONS}) # libraries to link to -SET(_PARAVIEW_APP_COMPO_LIB - pqApplicationComponents - ) SET(_link_LIBRARIES ${QT_LIBRARIES} @@ -45,9 +42,8 @@ SET(_link_LIBRARIES ${KERNEL_LDFLAGS} ${GUI_LDFLAGS} ${GUI_LightApp} ${GUI_CAM} ${GUI_qtx} ${GUI_suit} ${GUI_SalomeObject} - ${_PARAVIEW_APP_COMPO_LIB} + ParaView::pqApplicationComponents ${GUI_PVViewer} - ${VTK_LIBRARIES} ) # --- headers --- @@ -88,7 +84,7 @@ IF(SALOME_BUILD_DOC) # Check ParaView documentation file existence # if it exists add it to the resources (compile into binary form) # otherwise print warning message - SET(PV_DOC_FILE ${VTK_INSTALL_PREFIX}/share/doc/paraview-${PARAVIEW_VERSION_MAJOR}.${PARAVIEW_VERSION_MINOR}/paraview.qch) + SET(PV_DOC_FILE ${ParaView_PREFIX_PATH}/share/doc/ParaView/paraview.qch) IF (EXISTS ${PV_DOC_FILE}) SET(RC_SOURCE ${CMAKE_CURRENT_SOURCE_DIR}/PVGUI.qrc.in) SET(RC_GENERATED ${CMAKE_CURRENT_BINARY_DIR}/PVGUI.qrc) diff --git a/src/Plugins/ArrayRenamer/ArrayRenamer.xml b/src/Plugins/ArrayRenamer/ArrayRenamer.xml deleted file mode 100644 index 11240fbb..00000000 --- a/src/Plugins/ArrayRenamer/ArrayRenamer.xml +++ /dev/null @@ -1,59 +0,0 @@ - - - - - - - - - - - - - - - - - - This property specifies the input to Array Renamer filter. - - - - - Set the arrays information (new name and way how to process array: copy origin array with new name or keep existing array and set new name). - - - - Set the compoenents information for the array. - - - - - - - - - - - - - - diff --git a/src/Plugins/ArrayRenamer/CMakeLists.txt b/src/Plugins/ArrayRenamer/CMakeLists.txt index ad351acd..a37cb906 100644 --- a/src/Plugins/ArrayRenamer/CMakeLists.txt +++ b/src/Plugins/ArrayRenamer/CMakeLists.txt @@ -1,48 +1,30 @@ -# Copyright (C) 2014-2019 CEA/DEN, EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# -# Author : Roman NIKOLAEV - -PROJECT(ArrayRenamer) - -cmake_minimum_required(VERSION 2.8) - -INCLUDE(UseQtExt) -FIND_PACKAGE(ParaView REQUIRED) -INCLUDE(${PARAVIEW_USE_FILE}) - -SET (outifaces) -SET (outsrcs) - -QT_WRAP_MOC(moc_srcs pqArraysEditorPropertyWidget.h pqEditComponents.h) - - ADD_PARAVIEW_PROPERTY_GROUP_WIDGET(outifaces outsrcs - TYPE "custom_arrays_editor" - CLASS_NAME pqArraysEditorPropertyWidget) - -ADD_PARAVIEW_PLUGIN(ArrayRenamer "1.0" - SERVER_MANAGER_XML ArrayRenamer.xml - SERVER_MANAGER_SOURCES vtkArrayRenamerFilter.cxx - GUI_INTERFACES ${outifaces} - GUI_RESOURCES pqArrayRenamer.qrc - SOURCES ${outsrcs} ${moc_srcs} pqArraysEditorPropertyWidget.cxx - ) - -INSTALL(TARGETS ArrayRenamer - DESTINATION lib/paraview -) +cmake_minimum_required(VERSION 3.8) +project(ArrayRenamer) +find_package(ParaView REQUIRED) + +include(GNUInstallDirs) +set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_BINDIR}") +set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_LIBDIR}") +set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_LIBDIR}") + +set("_paraview_plugin_default_${CMAKE_PROJECT_NAME}" ON) +paraview_plugin_scan( + ENABLE_BY_DEFAULT YES + PLUGIN_FILES "${CMAKE_CURRENT_SOURCE_DIR}/plugin/paraview.plugin" + PROVIDES_PLUGINS plugins + REQUIRES_MODULES required_modules) + +foreach(module IN LISTS required_modules) + if(NOT TARGET "${module}") + message("Missing required module: ${module}") + return() + endif() +endforeach() + +set(BUILD_SHARED_LIBS ON) +paraview_plugin_build( + RUNTIME_DESTINATION "${CMAKE_INSTALL_BINDIR}" + LIBRARY_DESTINATION "${CMAKE_INSTALL_LIBDIR}" + LIBRARY_SUBDIRECTORY "${PARAVIEW_PLUGIN_SUBDIR}" + PLUGINS ${plugins} + AUTOLOAD ${plugins}) diff --git a/src/Plugins/ArrayRenamer/plugin.cmake b/src/Plugins/ArrayRenamer/plugin.cmake deleted file mode 100644 index 311942d1..00000000 --- a/src/Plugins/ArrayRenamer/plugin.cmake +++ /dev/null @@ -1,3 +0,0 @@ -pv_plugin(ArrayRenamer - DESCRIPTION "Renames data arrays and array's components" - DEFAULT_ENABLED) diff --git a/src/Plugins/ArrayRenamer/plugin/ArrayRenamerModule/CMakeLists.txt b/src/Plugins/ArrayRenamer/plugin/ArrayRenamerModule/CMakeLists.txt new file mode 100644 index 00000000..43cd0118 --- /dev/null +++ b/src/Plugins/ArrayRenamer/plugin/ArrayRenamerModule/CMakeLists.txt @@ -0,0 +1,8 @@ +set(classes + vtkArrayRenamerFilter +) + +vtk_module_add_module(ArrayRenamerModule + FORCE_STATIC + CLASSES ${classes} +) diff --git a/src/Plugins/ArrayRenamer/plugin/ArrayRenamerModule/vtk.module b/src/Plugins/ArrayRenamer/plugin/ArrayRenamerModule/vtk.module new file mode 100644 index 00000000..74412069 --- /dev/null +++ b/src/Plugins/ArrayRenamer/plugin/ArrayRenamerModule/vtk.module @@ -0,0 +1,11 @@ +NAME + ArrayRenamerModule +DEPENDS + VTK::CommonCore + VTK::CommonDataModel + VTK::CommonExecutionModel + VTK::FiltersCore +PRIVATE_DEPENDS + VTK::CommonMisc + VTK::CommonSystem + VTK::FiltersGeneral diff --git a/src/Plugins/ArrayRenamer/plugin/ArrayRenamerModule/vtkArrayRenamerFilter.cxx b/src/Plugins/ArrayRenamer/plugin/ArrayRenamerModule/vtkArrayRenamerFilter.cxx new file mode 100644 index 00000000..e496254d --- /dev/null +++ b/src/Plugins/ArrayRenamer/plugin/ArrayRenamerModule/vtkArrayRenamerFilter.cxx @@ -0,0 +1,217 @@ +// Copyright (C) 2014-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Roman NIKOLAEV + +#include "vtkArrayRenamerFilter.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +// For debug +//#include + +class vtkArrayRenamerFilter::vtkInternals +{ +public: + // Vector which contains information about array's components : origin_component_name <-> new_name + typedef std::vector > ComponentsInfo; + + struct ArrayInfo + { + std::string NewName; // New name of the array + bool CopyArray; // Make copy of the array or keep origin array, but change the name + ComponentsInfo ComponentVector; // Components of the array + ArrayInfo() + : NewName("") + , CopyArray(false) + { + } + }; + typedef std::map + ArraysType; // Map : origin_aray_name <-> ArrayInfo struct + ArraysType Arrays; +}; + +//------------------------------------------------------------------------------ +vtkStandardNewMacro(vtkArrayRenamerFilter); + +//-------------------------------------------------------------------------------------------------- +vtkArrayRenamerFilter::vtkArrayRenamerFilter() +{ + this->Internals = new vtkInternals(); +} + +//-------------------------------------------------------------------------------------------------- +vtkArrayRenamerFilter::~vtkArrayRenamerFilter() +{ + delete this->Internals; +} + +//-------------------------------------------------------------------------------------------------- +int vtkArrayRenamerFilter::RequestData(vtkInformation* theRequest, + vtkInformationVector** theInputVector, vtkInformationVector* theOutputVector) +{ + // std::cout<<"vtkArrayRenamerFilter::RequestData !!! "<GetInformationObject(0); + vtkInformation* anOutputInfo = theOutputVector->GetInformationObject(0); + + vtkDataSet* anInput = vtkDataSet::GetData(theInputVector[0], 0); + vtkDataSet* anOutput = vtkDataSet::GetData(theOutputVector, 0); + anOutput->DeepCopy(anInput); + vtkFieldData* data = 0; + + vtkInternals::ArraysType::iterator it = this->Internals->Arrays.begin(); + for (; it != this->Internals->Arrays.end(); it++) + { + vtkDataArray* array = anOutput->GetPointData()->GetArray(it->first.c_str()); + data = anOutput->GetPointData(); + if (!array) + { + array = anOutput->GetCellData()->GetArray(it->first.c_str()); + data = anOutput->GetCellData(); + } + + if (array && !it->second.NewName.empty()) + { + + if (it->second.CopyArray) + { + vtkDataArray* new_array = array->NewInstance(); + new_array->DeepCopy(array); + data->AddArray(new_array); + array = new_array; + } + array->SetName(it->second.NewName.c_str()); + } + + if (array) + { + vtkInternals::ComponentsInfo::iterator vect_it = it->second.ComponentVector.begin(); + for (; vect_it != it->second.ComponentVector.end(); vect_it++) + { + array->SetComponentName(vect_it->first, vect_it->second.c_str()); + } + } + } + + return Superclass::RequestData(theRequest, theInputVector, theOutputVector); +} + +void vtkArrayRenamerFilter::SetComponentInfo( + const char* arrayname, const int compid, const char* newcompname) +{ + // std::cout<<"vtkArrayRenamerFilter::SetComponentArrayInfo : "<Internals->Arrays.clear(); + this->Modified(); +} + +void vtkArrayRenamerFilter::ClearComponentsInfo() +{ + // std::cout<<"vtkArrayRenamerFilter::ClearComponentsInfo"<Internals->Arrays.begin(); + for (; it != this->Internals->Arrays.end(); it++) + { + it->second.ComponentVector.clear(); + } + this->Modified(); +} diff --git a/src/Plugins/ArrayRenamer/plugin/ArrayRenamerModule/vtkArrayRenamerFilter.h b/src/Plugins/ArrayRenamer/plugin/ArrayRenamerModule/vtkArrayRenamerFilter.h new file mode 100644 index 00000000..df69eefa --- /dev/null +++ b/src/Plugins/ArrayRenamer/plugin/ArrayRenamerModule/vtkArrayRenamerFilter.h @@ -0,0 +1,62 @@ +// Copyright (C) 2014-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Roman NIKOLAEV + +#ifndef __ArrayRenamerFilter_h_ +#define __ArrayRenamerFilter_h_ + +#include + +/** + * Description of class: + * Class allows to rename data arrays and array's components. + */ +class VTK_EXPORT vtkArrayRenamerFilter : public vtkDataSetAlgorithm +{ +public: + /// Returns pointer on a new instance of the class + static vtkArrayRenamerFilter* New(); + + vtkTypeMacro(vtkArrayRenamerFilter, vtkDataSetAlgorithm); + + void SetArrayInfo(const char* originarrayname, const char* newarrayname, bool copy); + void ClearArrayInfo(); + + void SetComponentInfo(const char* arrayname, const int compid, const char* newarrayname); + void ClearComponentsInfo(); + +protected: + /// Constructor & destructor + vtkArrayRenamerFilter(); + ~vtkArrayRenamerFilter() override; + + int RequestData(vtkInformation*, vtkInformationVector**, vtkInformationVector*) override; + +private: + vtkArrayRenamerFilter(const vtkArrayRenamerFilter&) = delete; + void operator=(const vtkArrayRenamerFilter&) = delete; + + void FillListOfArrays(vtkDataObject*); + + class vtkInternals; + friend class vtkInternals; + vtkInternals* Internals; +}; + +#endif // __ArrayRenamerFilter_h_ diff --git a/src/Plugins/ArrayRenamer/plugin/CMakeLists.txt b/src/Plugins/ArrayRenamer/plugin/CMakeLists.txt new file mode 100644 index 00000000..de6bb36d --- /dev/null +++ b/src/Plugins/ArrayRenamer/plugin/CMakeLists.txt @@ -0,0 +1,54 @@ +# Copyright (C) 2014-2019 CEA/DEN, EDF R&D +# +# This library 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. +# +# 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 +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +# +# Author : Roman NIKOLAEV + +set(interfaces) +set(sources) +set(qrc_files) +if(PARAVIEW_USE_QT) + paraview_plugin_add_property_widget( + KIND GROUP_WIDGET + TYPE custom_arrays_editor + CLASS_NAME pqArraysEditorPropertyWidget + INTERFACES interfaces + SOURCES sources + ) + list(APPEND sources + pqArraysEditorPropertyWidget.cxx + pqArraysEditorPropertyWidget.h + pqEditComponents.h + ) + list(APPEND qrc_files pqArrayRenamer.qrc) +endif() + +paraview_add_plugin(ArrayRenamer + VERSION "1.0" + UI_RESOURCES ${qrc_files} + UI_INTERFACES ${interfaces} + SOURCES ${sources} + MODULES ArrayRenamerModule + MODULE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/ArrayRenamerModule/vtk.module" + SERVER_MANAGER_XML filters.xml +) + +install(TARGETS ArrayRenamer + RUNTIME DESTINATION lib/paraview + LIBRARY DESTINATION lib/paraview + ARCHIVE DESTINATION lib/paraview +) \ No newline at end of file diff --git a/src/Plugins/ArrayRenamer/plugin/filters.xml b/src/Plugins/ArrayRenamer/plugin/filters.xml new file mode 100644 index 00000000..3d5b8215 --- /dev/null +++ b/src/Plugins/ArrayRenamer/plugin/filters.xml @@ -0,0 +1,59 @@ + + + + + + + + + + + + + + + + + + This property specifies the input to Array Renamer filter. + + + + + Set the arrays information (new name and way how to process array: copy origin array with new name or keep existing array and set new name). + + + + Set the compoenents information for the array. + + + + + + + + + + + + + + diff --git a/src/Plugins/ArrayRenamer/plugin/paraview.plugin b/src/Plugins/ArrayRenamer/plugin/paraview.plugin new file mode 100644 index 00000000..fcbfa0df --- /dev/null +++ b/src/Plugins/ArrayRenamer/plugin/paraview.plugin @@ -0,0 +1,13 @@ +NAME + ArrayRenamer +DESCRIPTION + Renames data arrays and array's components. +CONDITION + PARAVIEW_USE_QT +REQUIRES_MODULES + VTK::CommonCore + VTK::IOCore + VTK::FiltersCore + ParaView::pqApplicationComponents + ParaView::RemotingCore + ParaView::RemotingServerManager diff --git a/src/Plugins/ArrayRenamer/plugin/pqArrayRenamer.qrc b/src/Plugins/ArrayRenamer/plugin/pqArrayRenamer.qrc new file mode 100644 index 00000000..d82c446d --- /dev/null +++ b/src/Plugins/ArrayRenamer/plugin/pqArrayRenamer.qrc @@ -0,0 +1,7 @@ + + + resources/rename_ico_24x24.png + resources/copy_ico_16x16.png + resources/edit_ico_16x16.png + + diff --git a/src/Plugins/ArrayRenamer/plugin/pqArraysEditorPropertyWidget.cxx b/src/Plugins/ArrayRenamer/plugin/pqArraysEditorPropertyWidget.cxx new file mode 100644 index 00000000..26be2760 --- /dev/null +++ b/src/Plugins/ArrayRenamer/plugin/pqArraysEditorPropertyWidget.cxx @@ -0,0 +1,882 @@ +// Copyright (C) 2014-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Roman NIKOLAEV + +// Local includes +#include "pqArraysEditorPropertyWidget.h" +#include "pqEditComponents.h" + +// ParaView includes +#include +#include +#include +#include +#include +#include + +// Qt Includes +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// STD includes +#include + +/// Table model for the components table +class pqComponentsModel : public QAbstractTableModel +{ + typedef QAbstractTableModel Superclass; + +public: + typedef QPair SingleComponentInfoType; + typedef QVector ComponentsInfoType; + +private: + ComponentsInfoType myComponentsInfoVector; + bool myRenameSimilar; + +public: + enum ColumnRoles + { + COMPONENT_NAME = 0, + NEW_COMPONENT_NAME = 1, + }; + + //------------------------------------------------------------------ + pqComponentsModel(QObject* parentObject = 0) + : Superclass(parentObject) + , myRenameSimilar(false) + { + } + + //------------------------------------------------------------------ + virtual ~pqComponentsModel() {} + + void setRenameSimilar(bool IsRenameSimilar) + { + myRenameSimilar = IsRenameSimilar; + if (myRenameSimilar) + { + QHash anUnique; + foreach (SingleComponentInfoType item, myComponentsInfoVector) + { + if (!anUnique.contains(item.first)) + { + anUnique.insert(item.first, item.second); + } + } + bool modified = false; + int min = std::numeric_limits::max(); + int max = std::numeric_limits::min(); + for (int i = 0; i < myComponentsInfoVector.size(); i++) + { + if (anUnique.contains(myComponentsInfoVector[i].first) && + anUnique.value(myComponentsInfoVector[i].first) != myComponentsInfoVector[i].second) + { + myComponentsInfoVector[i].second = anUnique.value(myComponentsInfoVector[i].first); + min = qMin(min, i); + max = qMax(max, i); + modified = true; + } + } + if (modified) + { + emit dataChanged(index(1, min), index(1, max)); + } + } + } + + //------------------------------------------------------------------ + virtual Qt::ItemFlags flags(const QModelIndex& idx) const + { + Qt::ItemFlags value = Superclass::flags(idx); + if (idx.isValid()) + { + switch (idx.column()) + { + case NEW_COMPONENT_NAME: + return value | Qt::ItemIsEditable; + default: + break; + } + } + return value; + } + + //------------------------------------------------------------------ + virtual int rowCount(const QModelIndex& idx = QModelIndex()) const + { + return idx.isValid() ? 0 : myComponentsInfoVector.size(); + } + + //------------------------------------------------------------------ + virtual int columnCount(const QModelIndex& idx = QModelIndex()) const + { + Q_UNUSED(idx); + return 2; + } + + //------------------------------------------------------------------ + virtual QVariant data(const QModelIndex& idx, int role = Qt::DisplayRole) const + { + if (idx.column() == COMPONENT_NAME) + { + switch (role) + { + case Qt::DisplayRole: + case Qt::ToolTipRole: + case Qt::StatusTipRole: + return myComponentsInfoVector[idx.row()].first; + default: + break; + } + } + else if (idx.column() == NEW_COMPONENT_NAME) + { + switch (role) + { + case Qt::DisplayRole: + case Qt::EditRole: + case Qt::ToolTipRole: + case Qt::StatusTipRole: + return myComponentsInfoVector[idx.row()].second; + case Qt::ForegroundRole: + { + if (myComponentsInfoVector[idx.row()].second == myComponentsInfoVector[idx.row()].first) + return QApplication::palette().color(QPalette::Disabled, QPalette::Text); + } + case Qt::FontRole: + { + if (myComponentsInfoVector[idx.row()].second == myComponentsInfoVector[idx.row()].first) + { + QFont f = QApplication::font(); + f.setItalic(true); + return f; + } + } + default: + break; + } + } + return QVariant(); + } + + //------------------------------------------------------------------ + virtual bool setData(const QModelIndex& idx, const QVariant& value, int role = Qt::EditRole) + { + if (idx.column() == NEW_COMPONENT_NAME && role == Qt::EditRole) + { + QString new_name = value.toString(); + Q_ASSERT(idx.row() < myComponentsInfoVector.size()); + myComponentsInfoVector[idx.row()].second = new_name; + int min = idx.row(); + int max = idx.row(); + if (myRenameSimilar) + { + QString ref_name = myComponentsInfoVector[idx.row()].first; + for (int i = 0; i < myComponentsInfoVector.size(); i++) + { + if (myComponentsInfoVector[i].first == ref_name) + { + min = qMin(min, i); + max = qMax(max, i); + myComponentsInfoVector[i].second = new_name; + } + } + } + emit dataChanged(index(1, min), index(1, max)); + return true; + } + return Superclass::setData(idx, value, role); + } + + //------------------------------------------------------------------ + QVariant headerData(int section, Qt::Orientation orientation, int role) const + { + if (orientation == Qt::Horizontal) + { + if (role == Qt::DisplayRole || role == Qt::ToolTipRole) + { + switch (section) + { + case COMPONENT_NAME: + return role == Qt::DisplayRole ? "Origin Name" : "Origin Names of components"; + case NEW_COMPONENT_NAME: + return role == Qt::DisplayRole ? "New Name" : "New Names of components"; + default: + break; + } + } + } + return this->Superclass::headerData(section, orientation, role); + } + + //------------------------------------------------------------------ + void setComponentsInfo(const ComponentsInfoType& data) + { + emit this->beginResetModel(); + myComponentsInfoVector = data; + emit this->endResetModel(); + } + + //------------------------------------------------------------------ + const ComponentsInfoType& componentsInfo() const { return myComponentsInfoVector; } + +private: + Q_DISABLE_COPY(pqComponentsModel); +}; + +/// Table model for the array's table +class pqArraysModel : public QAbstractTableModel +{ + typedef QAbstractTableModel Superclass; + +public: + struct ArrayInfo + { + bool copyArray; // How to porocess arrays: remane origin array or keep origin and make copy with + // the new name + QString newName; + pqComponentsModel::ComponentsInfoType myComponentsInfo; + + public: + //------------------------------------------------------------------ + const int nbComps() const { return myComponentsInfo.size(); } + + //------------------------------------------------------------------ + const bool isCompomentsModified() const + { + foreach (pqComponentsModel::SingleComponentInfoType item, myComponentsInfo) + { + if (item.first != item.second) + return true; + } + return false; + } + }; + +public: + typedef QPair ArraysInfoItemType; + typedef QVector ArraysInfoType; + +private: + ArraysInfoType myArraysInfo; + +public: + //------------------------------------------------------------------ + enum ColumnRoles + { + PROCESSING = 0, + NAME = 1, + NEW_NAME = 2, + COMPONENTS = 3, + }; + + //------------------------------------------------------------------ + pqArraysModel(QObject* parentObject = 0) + : Superclass(parentObject) + { + } + + //------------------------------------------------------------------ + virtual ~pqArraysModel() {} + + //------------------------------------------------------------------ + virtual Qt::ItemFlags flags(const QModelIndex& idx) const + { + Qt::ItemFlags value = Superclass::flags(idx); + if (idx.isValid()) + { + switch (idx.column()) + { + case PROCESSING: + return value | Qt::ItemIsUserCheckable; + case NEW_NAME: + return value | Qt::ItemIsEditable; + default: + break; + } + } + return value; + } + + //------------------------------------------------------------------ + virtual int rowCount(const QModelIndex& idx = QModelIndex()) const + { + return idx.isValid() ? 0 : myArraysInfo.size(); + } + + //------------------------------------------------------------------ + virtual int columnCount(const QModelIndex& idx = QModelIndex()) const + { + Q_UNUSED(idx); + return 4; + } + + //------------------------------------------------------------------ + virtual QVariant data(const QModelIndex& idx, int role = Qt::DisplayRole) const + { + Q_ASSERT(idx.row() < myArraysInfo.size()); + if (idx.column() == PROCESSING) + { + switch (role) + { + case Qt::CheckStateRole: + return myArraysInfo[idx.row()].second.copyArray ? Qt::Checked : Qt::Unchecked; + default: + break; + } + } + else if (idx.column() == NAME) + { + switch (role) + { + case Qt::DisplayRole: + case Qt::ToolTipRole: + case Qt::StatusTipRole: + return myArraysInfo[idx.row()].first; + default: + break; + } + } + else if (idx.column() == NEW_NAME) + { + switch (role) + { + case Qt::DisplayRole: + case Qt::EditRole: + case Qt::ToolTipRole: + case Qt::StatusTipRole: + return myArraysInfo[idx.row()].second.newName; + case Qt::ForegroundRole: + { + if (myArraysInfo[idx.row()].second.newName == myArraysInfo[idx.row()].first) + return QApplication::palette().color(QPalette::Disabled, QPalette::Text); + } + case Qt::FontRole: + { + if (myArraysInfo[idx.row()].second.newName == myArraysInfo[idx.row()].first) + { + QFont f = QApplication::font(); + f.setItalic(true); + return f; + } + } + default: + break; + } + } + return QVariant(); + } + + //------------------------------------------------------------------ + virtual bool setData(const QModelIndex& idx, const QVariant& value, int role = Qt::EditRole) + { + + if (idx.column() == PROCESSING && role == Qt::CheckStateRole) + { + bool checkState = (value.toInt() == Qt::Checked); + Q_ASSERT(idx.row() < myArraysInfo.size()); + myArraysInfo[idx.row()].second.copyArray = (bool)checkState; + emit dataChanged(idx, idx); + return true; + } + + if (idx.column() == NEW_NAME && role == Qt::EditRole) + { + QString new_name = value.toString(); + if (!new_name.isEmpty()) + { + Q_ASSERT(idx.row() < myArraysInfo.size()); + myArraysInfo[idx.row()].second.newName = new_name; + emit dataChanged(idx, idx); + return true; + } + } + return Superclass::setData(idx, value, role); + } + + //------------------------------------------------------------------ + QVariant headerData(int section, Qt::Orientation orientation, int role) const + { + if (orientation == Qt::Horizontal) + { + if (role == Qt::DisplayRole || role == Qt::ToolTipRole) + { + switch (section) + { + case PROCESSING: + return role == Qt::DisplayRole ? "" : "Toggle to copy arrays"; + case NAME: + return role == Qt::DisplayRole ? "Origin Name" : "Origin Names of arrays"; + case NEW_NAME: + return role == Qt::DisplayRole ? "New Name" : "New Names of arrays"; + case COMPONENTS: + return role == Qt::DisplayRole ? "Components" : "Click item to edit components"; + default: + break; + } + } + else if (role == Qt::DecorationRole) + { + switch (section) + { + case PROCESSING: + return QIcon(":/ArrayRenamerIcons/resources/copy_ico_16x16.png"); + default: + break; + } + } + } + return Superclass::headerData(section, orientation, role); + } + + //------------------------------------------------------------------ + QString arrayName(const QModelIndex& idx) const + { + if (idx.isValid() && idx.row() < myArraysInfo.size()) + { + return myArraysInfo[idx.row()].first; + } + return QString(); + } + + //------------------------------------------------------------------ + void setArraysInfo(const QVector >& data) + { + emit beginResetModel(); + myArraysInfo = data; + emit endResetModel(); + } + + //------------------------------------------------------------------ + const ArraysInfoType& arraysInfo() const { return myArraysInfo; } + + //------------------------------------------------------------------ + ArraysInfoType& editArraysInfo() { return myArraysInfo; } + +private: + Q_DISABLE_COPY(pqArraysModel); +}; + +//----------------------------------------------------------------------------- +pqEditComponents::pqEditComponents(pqComponentsModel* model, QWidget* parent) +{ + + myComponentsModel = model; + setWindowTitle("Edit Components"); + + // Layout + QVBoxLayout* mainLayout = new QVBoxLayout(this); + QGroupBox* aComps = new QGroupBox("Components", this); + QGroupBox* aParams = new QGroupBox("Parameters", this); + QGroupBox* aBtns = new QGroupBox(this); + mainLayout->addWidget(aComps); + mainLayout->addWidget(aParams); + mainLayout->addWidget(aBtns); + + /// Table + QVBoxLayout* aCompsLayout = new QVBoxLayout(aComps); + QTableView* componentsTable = new QTableView(this); + componentsTable->setModel(model); + aCompsLayout->addWidget(componentsTable); + componentsTable->horizontalHeader()->setSectionResizeMode( + pqComponentsModel::COMPONENT_NAME, QHeaderView::Stretch); + componentsTable->horizontalHeader()->setSectionResizeMode( + pqComponentsModel::NEW_COMPONENT_NAME, QHeaderView::Stretch); + + /// Parameters + QVBoxLayout* aParamsLayout = new QVBoxLayout(aParams); + myRenameAllComps = new QCheckBox("Rename all similar Components", aParams); + aParamsLayout->addWidget(myRenameAllComps); + + /// Buttons + QPushButton* anOk = new QPushButton("OK", this); + QPushButton* aCancel = new QPushButton("Cancel", this); + QSpacerItem* space = new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Minimum); + QHBoxLayout* aBtnsLayout = new QHBoxLayout(aBtns); + aBtnsLayout->addWidget(anOk); + aBtnsLayout->addItem(space); + aBtnsLayout->addWidget(aCancel); + + // Connections + connect(anOk, SIGNAL(clicked()), this, SLOT(accept())); + connect(myRenameAllComps, SIGNAL(toggled(bool)), this, SLOT(onRenameAll(bool))); + connect(aCancel, SIGNAL(clicked()), this, SLOT(reject())); +} + +//----------------------------------------------------------------------------- +pqEditComponents::~pqEditComponents() {} + +//----------------------------------------------------------------------------- +bool pqEditComponents::renameAllComps() +{ + return myRenameAllComps->checkState() == Qt::Checked; +} + +//----------------------------------------------------------------------------- +void pqEditComponents::onRenameAll(bool val) +{ + myComponentsModel->setRenameSimilar(val); +} + +//----------------------------------------------------------------------------- +pqArraysEditorPropertyWidget::pqArraysEditorPropertyWidget( + vtkSMProxy* smproxy, vtkSMPropertyGroup* smgroup, QWidget* parentObject) + : Superclass(smproxy, parentObject) +{ + + myPropertyGroup = smgroup; + myConnection = vtkEventQtSlotConnect::New(); + + // Table + myArraysTable = new QTableView(this); + myArraysModel = new pqArraysModel(this); + myArraysTable->setModel(myArraysModel); + + // Layout + QVBoxLayout* lay = new QVBoxLayout(this); + lay->addWidget(myArraysTable); + myArraysTable->horizontalHeader()->setSectionResizeMode( + pqArraysModel::PROCESSING, QHeaderView::ResizeToContents); + myArraysTable->horizontalHeader()->setSectionResizeMode( + pqArraysModel::NAME, QHeaderView::Stretch); + myArraysTable->horizontalHeader()->setSectionResizeMode( + pqArraysModel::NEW_NAME, QHeaderView::Stretch); + myArraysTable->horizontalHeader()->setSectionResizeMode( + pqArraysModel::COMPONENTS, QHeaderView::ResizeToContents); + myArraysTable->resizeColumnsToContents(); + + // Connections + /// Client < - > Server + addPropertyLink( + this, "arrayInfo", SIGNAL(arraysInfoChanged()), smgroup->GetProperty("ArrayInfo")); + addPropertyLink( + this, "componentsInfo", SIGNAL(componentsInfoChanged()), smgroup->GetProperty("ComponentInfo")); + myConnection->Connect(smproxy, vtkCommand::UpdateDataEvent, this, SLOT(onInputDataChanged())); + + /// Qt + QObject::connect(myArraysModel, SIGNAL(dataChanged(const QModelIndex&, const QModelIndex&)), this, + SLOT(onDataChanged(const QModelIndex&, const QModelIndex&))); + + // Obtains list of the data arrays + updateArraysList(); +} + +pqArraysEditorPropertyWidget::~pqArraysEditorPropertyWidget() +{ + delete myArraysModel; + myConnection->Delete(); +} + +//----------------------------------------------------------------------------- +void pqArraysEditorPropertyWidget::setArraysInfo(const QList& values) +{ + pqArraysModel::ArraysInfoType vdata; + vdata.resize(values.size() / 3); + for (int cc = 0; (cc + 1) < values.size(); cc += 3) + { + vdata[cc / 3].first = values[cc].toString(); + vdata[cc / 3].second.newName = values[cc + 1].toString(); + vdata[cc / 3].second.copyArray = values[cc + 2].toBool(); + } + myArraysModel->setArraysInfo(vdata); +} + +//----------------------------------------------------------------------------- +QList pqArraysEditorPropertyWidget::arraysInfo() const +{ + const pqArraysModel::ArraysInfoType& vdata = myArraysModel->arraysInfo(); + QList reply; + for (int cc = 0; cc < vdata.size(); cc++) + { + if (vdata[cc].first != vdata[cc].second.newName) + { + reply.push_back(vdata[cc].first); + reply.push_back(vdata[cc].second.newName); + reply.push_back(vdata[cc].second.copyArray ? 1 : 0); + } + } + return reply; +} + +//----------------------------------------------------------------------------- +void pqArraysEditorPropertyWidget::setComponentsInfo(const QList& values) +{ + pqArraysModel::ArraysInfoType& vdata = myArraysModel->editArraysInfo(); + for (int i = 0; i < vdata.size(); i++) + { + vdata.resize(values.size() / 3); + QString anArrayName = "", aNewCompName = ""; + int aCompId = 0; + for (int cc = 0; (cc + 1) < values.size(); cc += 3) + { + anArrayName = values[cc].toString(); + aCompId = values[cc + 1].toInt(); + aNewCompName = values[cc + 2].toString(); + } + if (vdata[i].first == anArrayName && aCompId < vdata[i].second.myComponentsInfo.size()) + { + vdata[i].second.myComponentsInfo[i].second = aNewCompName; + } + } +} + +//----------------------------------------------------------------------------- +QList pqArraysEditorPropertyWidget::componentsInfo() const +{ + pqArraysModel::ArraysInfoType& vdata = myArraysModel->editArraysInfo(); + QList reply; + for (int cc = 0; cc < vdata.size(); cc++) + { + for (int ll = 0; ll < vdata[cc].second.myComponentsInfo.size(); ll++) + { + if (vdata[cc].second.myComponentsInfo[ll].second != + vdata[cc].second.myComponentsInfo[ll].first) + { + QString aArrayName = + (vdata[cc].first != vdata[cc].second.newName && !vdata[cc].second.newName.isEmpty()) + ? vdata[cc].second.newName + : vdata[cc].first; + reply.push_back(aArrayName); + reply.push_back(ll); + reply.push_back(vdata[cc].second.myComponentsInfo[ll].second); + } + } + } + return reply; +} + +//----------------------------------------------------------------------------- +void pqArraysEditorPropertyWidget::onDataChanged( + const QModelIndex& topleft, const QModelIndex& btmright) +{ + if (topleft.column() == pqArraysModel::PROCESSING || topleft.column() == pqArraysModel::NEW_NAME) + { + if (topleft.column() == pqArraysModel::PROCESSING) + { + const pqArraysModel::ArraysInfoType& vdata = myArraysModel->arraysInfo(); + Q_ASSERT(topleft.row() < vdata.size()); + if (vdata[topleft.row()].second.isCompomentsModified()) + { + myPropertyGroup->GetProperty("ComponentInfo")->Modified(); + } + } + emit arraysInfoChanged(); + } +} + +//----------------------------------------------------------------------------- +void pqArraysEditorPropertyWidget::updateArraysList() +{ + vtkPVDataSetAttributesInformation *cdi = NULL, *pdi = NULL; + + vtkSMSourceProxy* input = + vtkSMSourceProxy::SafeDownCast(vtkSMUncheckedPropertyHelper(proxy(), "Input").GetAsProxy(0)); + + // Null input + if (!input) + return; + + const QVector >& oldModelData = + myArraysModel->arraysInfo(); + + QStringList oldNames; + QPair oldArrayInfo; + foreach (oldArrayInfo, oldModelData) + { + oldNames.append(oldArrayInfo.first); + } + + myDataTime = input->GetDataInformation(0)->GetMTime(); + + pdi = input->GetDataInformation(0)->GetPointDataInformation(); + cdi = input->GetDataInformation(0)->GetCellDataInformation(); + QVector > myModelArraysInfo; + + if (pdi) + { + for (int i = 0; i < pdi->GetNumberOfArrays(); i++) + { + vtkPVArrayInformation* pvArrayInformation = pdi->GetArrayInformation(i); + QString anArrayName = QString(pvArrayInformation->GetName()); + int numComponents = pvArrayInformation->GetNumberOfComponents(); + int index = oldNames.indexOf(anArrayName); + if (index < 0) + { + + myModelArraysInfo.push_back(qMakePair(anArrayName, pqArraysModel::ArrayInfo())); + myModelArraysInfo.last().second.newName = anArrayName; + for (int j = 0; j < numComponents; j++) + { + QString compName = pvArrayInformation->GetComponentName(j); + myModelArraysInfo.last().second.myComponentsInfo.insert(j, qMakePair(compName, compName)); + } + } + else + { + + myModelArraysInfo.push_back(qMakePair(anArrayName, oldModelData[index].second)); + if (oldModelData[index].second.nbComps() != numComponents) + { + for (int j = 0; j < numComponents; j++) + { + QString compName = pvArrayInformation->GetComponentName(j); + myModelArraysInfo.last().second.myComponentsInfo.insert( + j, qMakePair(compName, compName)); + } + } + } + } + } + if (cdi) + { + for (int i = 0; i < cdi->GetNumberOfArrays(); i++) + { + + vtkPVArrayInformation* pvArrayInformation = cdi->GetArrayInformation(i); + QString anArrayName = QString(pvArrayInformation->GetName()); + int numComponents = pvArrayInformation->GetNumberOfComponents(); + int index = oldNames.indexOf(anArrayName); + if (index < 0) + { + myModelArraysInfo.push_back(qMakePair(anArrayName, pqArraysModel::ArrayInfo())); + myModelArraysInfo.last().second.newName = anArrayName; + for (int j = 0; j < numComponents; j++) + { + QString compName = pvArrayInformation->GetComponentName(j); + myModelArraysInfo.last().second.myComponentsInfo.insert(j, qMakePair(compName, compName)); + } + } + else + { + + myModelArraysInfo.push_back(qMakePair(anArrayName, oldModelData[index].second)); + if (oldModelData[index].second.nbComps() != numComponents) + { + for (int j = 0; j < numComponents; j++) + { + QString compName = pvArrayInformation->GetComponentName(j); + myModelArraysInfo.last().second.myComponentsInfo.insert( + j, qMakePair(compName, compName)); + } + } + } + } + } + + myArraysModel->setArraysInfo(myModelArraysInfo); + + for (int i = 0; i < myModelArraysInfo.size(); i++) + { + if (myModelArraysInfo[i].second.nbComps() > 1) + { + QPushButton* aBtn = new QPushButton(myArraysTable); + aBtn->setProperty("arrayName", myModelArraysInfo[i].first); + aBtn->setIcon(QIcon(":/ArrayRenamerIcons/resources/edit_ico_16x16.png")); + myArraysTable->setIndexWidget(myArraysModel->index(i, 3), aBtn); + connect(aBtn, SIGNAL(clicked()), this, SLOT(onComponentsEdit())); + } + } +} + +//----------------------------------------------------------------------------- +void pqArraysEditorPropertyWidget::onInputDataChanged() +{ + vtkSMSourceProxy* input = + vtkSMSourceProxy::SafeDownCast(vtkSMUncheckedPropertyHelper(proxy(), "Input").GetAsProxy(0)); + if (myDataTime < input->GetDataInformation(0)->GetMTime()) + { + updateArraysList(); + } +} + +//----------------------------------------------------------------------------- +void pqArraysEditorPropertyWidget::onComponentsEdit() +{ + QObject* snd = sender(); + QVariant v = snd->property("arrayName"); + int index = -1; + + if (v.isValid()) + { + QString anArrayName = v.toString(); + pqComponentsModel::ComponentsInfoType* aComponents = NULL; + pqArraysModel::ArraysInfoType& aModelData = myArraysModel->editArraysInfo(); + for (int i = 0; i < aModelData.size(); i++) + { + pqArraysModel::ArraysInfoItemType& item = aModelData[i]; + if (item.first == anArrayName) + { + aComponents = &item.second.myComponentsInfo; + index = i; + break; + } + } + + if (aComponents) + { + pqComponentsModel* aCompsModel = new pqComponentsModel(); + aCompsModel->setComponentsInfo(*aComponents); + pqEditComponents* dlg = new pqEditComponents(aCompsModel, this); + if (dlg->exec() == QDialog::Accepted) + { + const pqComponentsModel::ComponentsInfoType& aRenamedComponents = + aCompsModel->componentsInfo(); + if (dlg->renameAllComps()) + { + /// Rename all components in all arrays + for (int i = 0; i < aModelData.size(); i++) + { + pqArraysModel::ArraysInfoItemType& item = aModelData[i]; + for (int j = 0; j < item.second.myComponentsInfo.size(); j++) + { + pqComponentsModel::ComponentsInfoType& aComps = item.second.myComponentsInfo; + for (int k = 0; k < aRenamedComponents.size(); k++) + { + if (aComps[j].first == aRenamedComponents[k].first) + { + aComps[j].second = aRenamedComponents[k].second; + } + } + } + } + } + else + { + if (index >= 0) + { + aModelData[index].second.myComponentsInfo = aRenamedComponents; + } + } + emit componentsInfoChanged(); + } + delete dlg; + delete aCompsModel; + } + } +} diff --git a/src/Plugins/ArrayRenamer/plugin/pqArraysEditorPropertyWidget.h b/src/Plugins/ArrayRenamer/plugin/pqArraysEditorPropertyWidget.h new file mode 100644 index 00000000..4cdb8cf2 --- /dev/null +++ b/src/Plugins/ArrayRenamer/plugin/pqArraysEditorPropertyWidget.h @@ -0,0 +1,89 @@ +// Copyright (C) 2014-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Roman NIKOLAEV + +/*========================================================================*/ +#ifndef __pqArraysEditorPropertyWidget_h +#define __pqArraysEditorPropertyWidget_h + +#include +#include + +// ParaView classes +class vtkSMPropertyGroup; +class vtkEventQtSlotConnect; + +// Qt Classes +class QTableView; +class QModelIndex; + +class pqArraysModel; + +/// pqArraysEditorPropertyWidget is the pqPropertyWidget used to edit +/// arrays and array's components. +class VTK_EXPORT pqArraysEditorPropertyWidget : public pqPropertyWidget +{ + Q_OBJECT + + Q_PROPERTY(QList arrayInfo READ arraysInfo WRITE setArraysInfo NOTIFY arraysInfoChanged) + + Q_PROPERTY(QList componentsInfo READ componentsInfo WRITE setComponentsInfo NOTIFY + componentsInfoChanged) + + typedef pqPropertyWidget Superclass; + +public: + pqArraysEditorPropertyWidget(vtkSMProxy* proxy, vtkSMPropertyGroup* smgroup, QWidget* parent = nullptr); + virtual ~pqArraysEditorPropertyWidget(); + + /// Get/Set the arrays Info + QList arraysInfo() const; + void setArraysInfo(const QList&); + + /// Get/Set the arrays Info + QList componentsInfo() const; + void setComponentsInfo(const QList&); + +signals: + /// Fired when the arrays Info is changes. + void arraysInfoChanged(); + void componentsInfoChanged(); + +private slots: + /// called whenever the internal model's data changes. + void onDataChanged(const QModelIndex& topleft, const QModelIndex& btmright); + void onComponentsEdit(); + + /// called whenever the input changed. + void onInputDataChanged(); + +private: // Methods + void updateArraysList(); + +private: // Fields + vtkSmartPointer myPropertyGroup; + vtkEventQtSlotConnect* myConnection; + unsigned long myDataTime; + + // Array's table + pqArraysModel* myArraysModel; + QTableView* myArraysTable; +}; + +#endif // __pqArraysEditorPropertyWidget_h diff --git a/src/Plugins/ArrayRenamer/plugin/pqEditComponents.h b/src/Plugins/ArrayRenamer/plugin/pqEditComponents.h new file mode 100644 index 00000000..c5ca3940 --- /dev/null +++ b/src/Plugins/ArrayRenamer/plugin/pqEditComponents.h @@ -0,0 +1,41 @@ +// Copyright (C) 2014-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Roman NIKOLAEV + +#include + +class pqComponentsModel; +class QCheckBox; + +class pqEditComponents : public QDialog +{ + Q_OBJECT +public: + pqEditComponents(pqComponentsModel* model, QWidget* parent); + ~pqEditComponents(); + + bool renameAllComps(); + +private slots: + void onRenameAll(bool val); + +private: + QCheckBox* myRenameAllComps; + pqComponentsModel* myComponentsModel; +}; diff --git a/src/Plugins/ArrayRenamer/plugin/resources/copy_ico_16x16.png b/src/Plugins/ArrayRenamer/plugin/resources/copy_ico_16x16.png new file mode 100644 index 00000000..8969c406 Binary files /dev/null and b/src/Plugins/ArrayRenamer/plugin/resources/copy_ico_16x16.png differ diff --git a/src/Plugins/ArrayRenamer/plugin/resources/edit_ico_16x16.png b/src/Plugins/ArrayRenamer/plugin/resources/edit_ico_16x16.png new file mode 100644 index 00000000..b73a4a3e Binary files /dev/null and b/src/Plugins/ArrayRenamer/plugin/resources/edit_ico_16x16.png differ diff --git a/src/Plugins/ArrayRenamer/plugin/resources/rename_ico_24x24.png b/src/Plugins/ArrayRenamer/plugin/resources/rename_ico_24x24.png new file mode 100644 index 00000000..9066ff59 Binary files /dev/null and b/src/Plugins/ArrayRenamer/plugin/resources/rename_ico_24x24.png differ diff --git a/src/Plugins/ArrayRenamer/pqArrayRenamer.qrc b/src/Plugins/ArrayRenamer/pqArrayRenamer.qrc deleted file mode 100644 index d82c446d..00000000 --- a/src/Plugins/ArrayRenamer/pqArrayRenamer.qrc +++ /dev/null @@ -1,7 +0,0 @@ - - - resources/rename_ico_24x24.png - resources/copy_ico_16x16.png - resources/edit_ico_16x16.png - - diff --git a/src/Plugins/ArrayRenamer/pqArraysEditorPropertyWidget.cxx b/src/Plugins/ArrayRenamer/pqArraysEditorPropertyWidget.cxx deleted file mode 100644 index 2fac7fca..00000000 --- a/src/Plugins/ArrayRenamer/pqArraysEditorPropertyWidget.cxx +++ /dev/null @@ -1,744 +0,0 @@ -// Copyright (C) 2014-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Roman NIKOLAEV - -// Local includes -#include "pqArraysEditorPropertyWidget.h" -#include "pqEditComponents.h" - -//ParaView includes -#include -#include -#include -#include -#include -#include - -// Qt Includes -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -// STD includes -#include - - -/// Table model for the components table -class pqComponentsModel : public QAbstractTableModel { - typedef QAbstractTableModel Superclass; -public: - typedef QPair SingleComponentInfoType; - typedef QVector ComponentsInfoType; -private: - ComponentsInfoType myComponentsInfoVector; - bool myRenameSimilar; - -public: - enum ColumnRoles { - COMPONENT_NAME = 0, - NEW_COMPONENT_NAME = 1, - }; - - //------------------------------------------------------------------ - pqComponentsModel( QObject* parentObject=0 ): - Superclass(parentObject), - myRenameSimilar(false) {} - - //------------------------------------------------------------------ - virtual ~pqComponentsModel() {} - - void setRenameSimilar( bool IsRenameSimilar ) { - myRenameSimilar = IsRenameSimilar; - if ( myRenameSimilar ) { - QHash anUnique; - foreach( SingleComponentInfoType item, myComponentsInfoVector ) { - if( !anUnique.contains( item.first ) ) { - anUnique.insert( item.first,item.second ); - } - } - bool modified = false; - int min = std::numeric_limits::max(); - int max = std::numeric_limits::min(); - for( int i = 0; i < myComponentsInfoVector.size(); i++ ) { - if( anUnique.contains( myComponentsInfoVector[i].first) && - anUnique.value( myComponentsInfoVector[i].first ) != myComponentsInfoVector[i].second ) { - myComponentsInfoVector[i].second = anUnique.value( myComponentsInfoVector[i].first ); - min = qMin( min, i ); - max = qMax( max, i ); - modified = true; - } - } - if( modified ) { - emit dataChanged( index( 1, min ) , index( 1, max ) ); - } - } - } - - //------------------------------------------------------------------ - virtual Qt::ItemFlags flags( const QModelIndex &idx ) const { - Qt::ItemFlags value = Superclass::flags( idx ); - if ( idx.isValid() ) { - switch ( idx.column() ) { - case NEW_COMPONENT_NAME: return value | Qt::ItemIsEditable; - default: - break; - } - } - return value; - } - - //------------------------------------------------------------------ - virtual int rowCount( const QModelIndex& idx=QModelIndex() ) const { - return idx.isValid() ? 0 : myComponentsInfoVector.size(); - } - - //------------------------------------------------------------------ - virtual int columnCount( const QModelIndex& idx=QModelIndex() ) const { - Q_UNUSED( idx ); - return 2; - } - - //------------------------------------------------------------------ - virtual QVariant data(const QModelIndex& idx, int role=Qt::DisplayRole) const { - if ( idx.column() == COMPONENT_NAME ) { - switch ( role ) { - case Qt::DisplayRole: - case Qt::ToolTipRole: - case Qt::StatusTipRole: - return myComponentsInfoVector[idx.row()].first; - default: - break; - } - } - else if (idx.column() == NEW_COMPONENT_NAME) { - switch (role) { - case Qt::DisplayRole: - case Qt::EditRole: - case Qt::ToolTipRole: - case Qt::StatusTipRole: - return myComponentsInfoVector[idx.row()].second; - case Qt::ForegroundRole: { - if ( myComponentsInfoVector[idx.row()].second == myComponentsInfoVector[idx.row()].first ) - return QApplication::palette().color(QPalette::Disabled, QPalette::Text); - } - case Qt::FontRole: { - if ( myComponentsInfoVector[idx.row()].second == myComponentsInfoVector[idx.row()].first ) { - QFont f = QApplication::font(); - f.setItalic(true); - return f; - } - } - default: - break; - } - } - return QVariant(); - } - - //------------------------------------------------------------------ - virtual bool setData(const QModelIndex &idx, const QVariant &value, int role=Qt::EditRole) { - if (idx.column() == NEW_COMPONENT_NAME && role == Qt::EditRole ) { - QString new_name = value.toString(); - Q_ASSERT(idx.row() < myComponentsInfoVector.size()); - myComponentsInfoVector[idx.row()].second = new_name; - int min = idx.row(); - int max = idx.row(); - if( myRenameSimilar ) { - QString ref_name = myComponentsInfoVector[idx.row()].first; - for( int i = 0; i < myComponentsInfoVector.size(); i++ ) { - if(myComponentsInfoVector[i].first == ref_name) { - min = qMin( min, i ); - max = qMax( max, i ); - myComponentsInfoVector[i].second = new_name; - } - } - } - emit dataChanged( index( 1, min ) , index( 1, max ) ); - return true; - } - return Superclass::setData(idx,value,role); - } - - //------------------------------------------------------------------ - QVariant headerData( int section, Qt::Orientation orientation, int role ) const { - if ( orientation == Qt::Horizontal ) { - if ( role == Qt::DisplayRole || role == Qt::ToolTipRole ) { - switch (section) { - case COMPONENT_NAME: - return role == Qt::DisplayRole? "Origin Name": "Origin Names of components"; - case NEW_COMPONENT_NAME: - return role == Qt::DisplayRole? "New Name": "New Names of components"; - default: - break; - } - } - } - return this->Superclass::headerData(section, orientation, role); - } - - //------------------------------------------------------------------ - void setComponentsInfo( const ComponentsInfoType& data ) { - emit this->beginResetModel(); - myComponentsInfoVector = data; - emit this->endResetModel(); - } - - //------------------------------------------------------------------ - const ComponentsInfoType& componentsInfo() const { - return myComponentsInfoVector; - } -private: - Q_DISABLE_COPY(pqComponentsModel); -}; - -/// Table model for the array's table -class pqArraysModel : public QAbstractTableModel -{ - typedef QAbstractTableModel Superclass; -public: - struct ArrayInfo { - bool copyArray; // How to porocess arrays: remane origin array or keep origin and make copy with the new name - QString newName; - pqComponentsModel::ComponentsInfoType myComponentsInfo; - - public: - - //------------------------------------------------------------------ - const int nbComps() const { - return myComponentsInfo.size(); - } - - //------------------------------------------------------------------ - const bool isCompomentsModified() const { - foreach(pqComponentsModel::SingleComponentInfoType item , myComponentsInfo) { - if(item.first != item.second) - return true; - } - return false; - } - }; - -public: - typedef QPair ArraysInfoItemType; - typedef QVector ArraysInfoType; - -private: - ArraysInfoType myArraysInfo; - -public: - - //------------------------------------------------------------------ - enum ColumnRoles { - PROCESSING = 0, - NAME = 1, - NEW_NAME = 2, - COMPONENTS = 3, - }; - - //------------------------------------------------------------------ - pqArraysModel( QObject* parentObject=0 ) : - Superclass( parentObject ) { } - - //------------------------------------------------------------------ - virtual ~pqArraysModel() { } - - //------------------------------------------------------------------ - virtual Qt::ItemFlags flags( const QModelIndex &idx ) const { - Qt::ItemFlags value = Superclass::flags( idx ); - if (idx.isValid()) { - switch ( idx.column() ) { - case PROCESSING: - return value | Qt::ItemIsUserCheckable; - case NEW_NAME: - return value | Qt::ItemIsEditable; - default: - break; - } - } - return value; - } - - //------------------------------------------------------------------ - virtual int rowCount( const QModelIndex& idx=QModelIndex() ) const { - return idx.isValid() ? 0 : myArraysInfo.size(); - } - - //------------------------------------------------------------------ - virtual int columnCount( const QModelIndex& idx=QModelIndex() ) const { - Q_UNUSED(idx); - return 4; - } - - //------------------------------------------------------------------ - virtual QVariant data(const QModelIndex& idx, int role=Qt::DisplayRole) const { - Q_ASSERT( idx.row() < myArraysInfo.size() ); - if ( idx.column() == PROCESSING ) { - switch (role) { - case Qt::CheckStateRole: - return myArraysInfo[idx.row()].second.copyArray ? Qt::Checked : Qt::Unchecked; - default: - break; - } - } else if ( idx.column() == NAME ) { - switch ( role ) { - case Qt::DisplayRole: - case Qt::ToolTipRole: - case Qt::StatusTipRole: - return myArraysInfo[idx.row()].first; - default: - break; - } - } else if ( idx.column() == NEW_NAME ) { - switch (role) { - case Qt::DisplayRole: - case Qt::EditRole: - case Qt::ToolTipRole: - case Qt::StatusTipRole: - return myArraysInfo[idx.row()].second.newName; - case Qt::ForegroundRole: { - if ( myArraysInfo[idx.row()].second.newName == myArraysInfo[idx.row()].first ) - return QApplication::palette().color(QPalette::Disabled, QPalette::Text); - } - case Qt::FontRole: { - if ( myArraysInfo[idx.row()].second.newName == myArraysInfo[idx.row()].first ) { - QFont f = QApplication::font(); - f.setItalic(true); - return f; - } - } - default: - break; - } - } - return QVariant(); - } - - //------------------------------------------------------------------ - virtual bool setData(const QModelIndex &idx, const QVariant &value, int role=Qt::EditRole) { - - if (idx.column() == PROCESSING && role == Qt::CheckStateRole) { - bool checkState = (value.toInt() == Qt::Checked); - Q_ASSERT(idx.row() < myArraysInfo.size()); - myArraysInfo[idx.row()].second.copyArray = (bool)checkState; - emit dataChanged(idx, idx); - return true; - } - - if (idx.column() == NEW_NAME && role == Qt::EditRole) { - QString new_name = value.toString(); - if ( !new_name.isEmpty() ) { - Q_ASSERT(idx.row() < myArraysInfo.size()); - myArraysInfo[idx.row()].second.newName = new_name; - emit dataChanged(idx, idx); - return true; - } - } - return Superclass::setData(idx,value,role); - } - - //------------------------------------------------------------------ - QVariant headerData(int section, Qt::Orientation orientation, int role) const { - if ( orientation == Qt::Horizontal ) { - if ( role == Qt::DisplayRole || role == Qt::ToolTipRole ) { - switch ( section ) { - case PROCESSING: - return role == Qt::DisplayRole? "": "Toggle to copy arrays"; - case NAME: - return role == Qt::DisplayRole? "Origin Name": "Origin Names of arrays"; - case NEW_NAME: - return role == Qt::DisplayRole? "New Name": "New Names of arrays"; - case COMPONENTS: - return role == Qt::DisplayRole? "Components" : "Click item to edit components"; - default: - break; - } - } else if ( role == Qt::DecorationRole ) { - switch ( section ) { - case PROCESSING: return QIcon( ":/ArrayRenamerIcons/resources/copy_ico_16x16.png" ); - default: - break; - } - } - } - return Superclass::headerData( section, orientation, role ); - } - - //------------------------------------------------------------------ - QString arrayName( const QModelIndex& idx ) const { - if ( idx.isValid() && idx.row() < myArraysInfo.size() ) { - return myArraysInfo[idx.row()].first; - } - return QString(); - } - - //------------------------------------------------------------------ - void setArraysInfo( const QVector >& data ) { - emit beginResetModel(); - myArraysInfo = data; - emit endResetModel(); - } - - //------------------------------------------------------------------ - const ArraysInfoType& arraysInfo() const { - return myArraysInfo; - } - - //------------------------------------------------------------------ - ArraysInfoType& editArraysInfo() { - return myArraysInfo; - } - -private: - Q_DISABLE_COPY(pqArraysModel); -}; - -//----------------------------------------------------------------------------- -pqEditComponents::pqEditComponents( pqComponentsModel* model, QWidget* parent ) { - - myComponentsModel = model; - setWindowTitle( "Edit Components" ); - - //Layout - QVBoxLayout *mainLayout = new QVBoxLayout( this ); - QGroupBox* aComps = new QGroupBox( "Components", this ); - QGroupBox* aParams = new QGroupBox( "Parameters", this ); - QGroupBox* aBtns = new QGroupBox( this ); - mainLayout->addWidget( aComps ); - mainLayout->addWidget( aParams ); - mainLayout->addWidget( aBtns ); - - /// Table - QVBoxLayout *aCompsLayout = new QVBoxLayout( aComps ); - QTableView* componentsTable = new QTableView( this ); - componentsTable->setModel( model ); - aCompsLayout->addWidget( componentsTable ); - componentsTable->horizontalHeader()->setSectionResizeMode( pqComponentsModel::COMPONENT_NAME, QHeaderView::Stretch ); - componentsTable->horizontalHeader()->setSectionResizeMode( pqComponentsModel::NEW_COMPONENT_NAME, QHeaderView::Stretch ); - - /// Parameters - QVBoxLayout *aParamsLayout = new QVBoxLayout( aParams ); - myRenameAllComps = new QCheckBox( "Rename all similar Components", aParams ); - aParamsLayout->addWidget( myRenameAllComps ); - - /// Buttons - QPushButton* anOk = new QPushButton( "OK", this ); - QPushButton* aCancel = new QPushButton( "Cancel", this ); - QSpacerItem* space = new QSpacerItem( 0, 0, QSizePolicy::Expanding, QSizePolicy::Minimum ); - QHBoxLayout* aBtnsLayout = new QHBoxLayout( aBtns ); - aBtnsLayout->addWidget( anOk ); - aBtnsLayout->addItem( space ); - aBtnsLayout->addWidget( aCancel ); - - //Connections - connect( anOk, SIGNAL( clicked() ), this, SLOT( accept() ) ); - connect( myRenameAllComps, SIGNAL( toggled(bool) ), this, SLOT( onRenameAll(bool) ) ); - connect( aCancel, SIGNAL( clicked() ), this, SLOT( reject() ) ); -} - -//----------------------------------------------------------------------------- -pqEditComponents::~pqEditComponents() { } - -//----------------------------------------------------------------------------- -bool pqEditComponents::renameAllComps() { - return myRenameAllComps->checkState() == Qt::Checked; -} - -//----------------------------------------------------------------------------- -void pqEditComponents::onRenameAll( bool val ) { - myComponentsModel->setRenameSimilar( val ); -} - -//----------------------------------------------------------------------------- -pqArraysEditorPropertyWidget::pqArraysEditorPropertyWidget( vtkSMProxy* smproxy, vtkSMPropertyGroup* smgroup, QWidget* parentObject ) : - Superclass(smproxy, parentObject) { - - myPropertyGroup = smgroup; - myConnection = vtkEventQtSlotConnect::New(); - - // Table - myArraysTable = new QTableView(this); - myArraysModel = new pqArraysModel(this); - myArraysTable->setModel(myArraysModel); - - // Layout - QVBoxLayout* lay = new QVBoxLayout(this); - lay->addWidget(myArraysTable); - myArraysTable->horizontalHeader()->setSectionResizeMode( pqArraysModel::PROCESSING, QHeaderView::ResizeToContents ); - myArraysTable->horizontalHeader()->setSectionResizeMode( pqArraysModel::NAME, QHeaderView::Stretch); - myArraysTable->horizontalHeader()->setSectionResizeMode( pqArraysModel::NEW_NAME, QHeaderView::Stretch ); - myArraysTable->horizontalHeader()->setSectionResizeMode( pqArraysModel::COMPONENTS, QHeaderView::ResizeToContents ); - myArraysTable->resizeColumnsToContents(); - - // Connections - /// Clien < - > Server - addPropertyLink( this, "arrayInfo", SIGNAL( arraysInfoChanged() ), smgroup->GetProperty( "ArrayInfo" ) ); - addPropertyLink( this, "componentsInfo", SIGNAL( componentsInfoChanged() ), smgroup->GetProperty( "ComponentInfo" ) ); - myConnection->Connect( smproxy, vtkCommand::UpdateDataEvent, this, SLOT( onInputDataChanged() ) ); - - /// Qt - QObject::connect( myArraysModel, - SIGNAL( dataChanged( const QModelIndex &, const QModelIndex& ) ), - this, SLOT( onDataChanged( const QModelIndex&, const QModelIndex& ) ) ); - - // Obtains list of the data arrays - updateArraysList(); -} - -pqArraysEditorPropertyWidget::~pqArraysEditorPropertyWidget() { - delete myArraysModel; - myConnection->Delete(); -} - -//----------------------------------------------------------------------------- -void pqArraysEditorPropertyWidget::setArraysInfo( const QList & values ){ - pqArraysModel::ArraysInfoType vdata; - vdata.resize( values.size()/3 ); - for ( int cc=0; ( cc + 1 ) < values.size(); cc+=3 ) { - vdata[cc/3].first = values[cc].toString(); - vdata[cc/3].second.newName = values[cc+1].toString(); - vdata[cc/3].second.copyArray = values[cc+2].toBool(); - } - myArraysModel->setArraysInfo( vdata ); -} - -//----------------------------------------------------------------------------- -QList pqArraysEditorPropertyWidget::arraysInfo() const { - const pqArraysModel::ArraysInfoType &vdata = myArraysModel->arraysInfo(); - QList reply; - for ( int cc=0; cc < vdata.size(); cc++ ) { - if(vdata[cc].first != vdata[cc].second.newName ) { - reply.push_back( vdata[cc].first ); - reply.push_back( vdata[cc].second.newName ); - reply.push_back( vdata[cc].second.copyArray ? 1 : 0 ); - } - } - return reply; -} - -//----------------------------------------------------------------------------- -void pqArraysEditorPropertyWidget::setComponentsInfo( const QList & values ) { - - pqArraysModel::ArraysInfoType &vdata = myArraysModel->editArraysInfo(); - for(int i = 0; i < vdata.size(); i++) { - vdata.resize( values.size()/3 ); - QString anArrayName = "", aNewCompName = ""; - int aCompId = 0; - for ( int cc=0; ( cc + 1 ) < values.size(); cc+=3 ) { - anArrayName = values[cc].toString(); - aCompId = values[cc+1].toInt(); - aNewCompName = values[cc+2].toString(); - } - if( vdata[i].first == anArrayName && aCompId < vdata[i].second.myComponentsInfo.size() ) { - vdata[i].second.myComponentsInfo[i].second = aNewCompName; - } - } -} - -//----------------------------------------------------------------------------- -QList pqArraysEditorPropertyWidget::componentsInfo() const { - - pqArraysModel::ArraysInfoType &vdata = myArraysModel->editArraysInfo(); - QList reply; - for ( int cc=0; cc < vdata.size(); cc++ ) { - for ( int ll = 0; ll < vdata[cc].second.myComponentsInfo.size(); ll++ ) { - if ( vdata[cc].second.myComponentsInfo[ll].second != vdata[cc].second.myComponentsInfo[ll].first) { - QString aArrayName = - (vdata[cc].first != vdata[cc].second.newName && !vdata[cc].second.newName.isEmpty()) ? vdata[cc].second.newName : vdata[cc].first; - reply.push_back( aArrayName ); - reply.push_back( ll ); - reply.push_back( vdata[cc].second.myComponentsInfo[ll].second ); - } - } - } - - return reply; -} - -//----------------------------------------------------------------------------- -void pqArraysEditorPropertyWidget::onDataChanged( const QModelIndex& topleft, const QModelIndex& btmright ) { - if ( topleft.column() == pqArraysModel::PROCESSING || topleft.column() == pqArraysModel::NEW_NAME ) { - if ( topleft.column() == pqArraysModel::PROCESSING ) { - const pqArraysModel::ArraysInfoType &vdata = myArraysModel->arraysInfo(); - Q_ASSERT(topleft.row() < vdata.size()); - if( vdata[topleft.row()].second.isCompomentsModified() ) { - myPropertyGroup->GetProperty( "ComponentInfo" )->Modified(); - } - } - emit arraysInfoChanged(); - } -} - -//----------------------------------------------------------------------------- -void pqArraysEditorPropertyWidget::updateArraysList() { - vtkPVDataSetAttributesInformation *cdi = NULL, *pdi = NULL; - - vtkSMSourceProxy* input = vtkSMSourceProxy::SafeDownCast( vtkSMUncheckedPropertyHelper( proxy(), "Input" ).GetAsProxy( 0 ) ); - - // Null insput - if ( !input ) - return; - - const QVector > &oldModelData = myArraysModel->arraysInfo(); - - QStringList oldNames; - QPair oldArrayInfo; - foreach ( oldArrayInfo, oldModelData ) { - oldNames.append(oldArrayInfo.first); - } - - myDataTime = input->GetDataInformation( 0 )->GetMTime(); - - pdi = input->GetDataInformation( 0 )->GetPointDataInformation(); - cdi = input->GetDataInformation( 0 )->GetCellDataInformation(); - QVector > myModelArraysInfo; - - if ( pdi ) { - for ( int i=0; iGetNumberOfArrays(); i++ ) { - vtkPVArrayInformation* pvArrayInformation = pdi->GetArrayInformation( i ); - QString anArrayName = QString( pvArrayInformation->GetName() ); - int numComponents = pvArrayInformation->GetNumberOfComponents(); - int index = oldNames.indexOf(anArrayName); - if ( index < 0 ) { - - myModelArraysInfo.push_back( qMakePair( anArrayName , pqArraysModel::ArrayInfo() ) ); - myModelArraysInfo.last().second.newName = anArrayName; - for ( int j=0; jGetComponentName( j ); - myModelArraysInfo.last().second.myComponentsInfo.insert(j, qMakePair( compName, compName ) ); - } - } else { - - myModelArraysInfo.push_back( qMakePair(anArrayName, oldModelData[index].second ) ); - if ( oldModelData[index].second.nbComps() != numComponents ) { - for ( int j=0; jGetComponentName( j ); - myModelArraysInfo.last().second.myComponentsInfo.insert( j, qMakePair( compName, compName ) ); - } - } - } - } - } - if ( cdi ) { - for ( int i=0; iGetNumberOfArrays(); i++ ) { - - vtkPVArrayInformation* pvArrayInformation = cdi->GetArrayInformation( i ); - QString anArrayName = QString( pvArrayInformation->GetName() ); - int numComponents = pvArrayInformation->GetNumberOfComponents(); - int index = oldNames.indexOf(anArrayName); - if ( index < 0 ) { - myModelArraysInfo.push_back( qMakePair( anArrayName , pqArraysModel::ArrayInfo() ) ); - myModelArraysInfo.last().second.newName = anArrayName; - for ( int j=0; jGetComponentName( j ); - myModelArraysInfo.last().second.myComponentsInfo.insert( j, qMakePair( compName, compName ) ); - } - } else { - - myModelArraysInfo.push_back( qMakePair(anArrayName, oldModelData[index].second ) ); - if ( oldModelData[index].second.nbComps() != numComponents ) { - for ( int j=0; jGetComponentName( j ); - myModelArraysInfo.last().second.myComponentsInfo.insert( j, qMakePair( compName, compName ) ); - } - } - } - } - } - - myArraysModel->setArraysInfo(myModelArraysInfo); - - for ( int i = 0; i < myModelArraysInfo.size(); i++ ) { - if ( myModelArraysInfo[i].second.nbComps() > 1 ) { - QPushButton* aBtn = new QPushButton(myArraysTable); - aBtn->setProperty("arrayName",myModelArraysInfo[i].first); - aBtn->setIcon( QIcon( ":/ArrayRenamerIcons/resources/edit_ico_16x16.png" ) ); - myArraysTable->setIndexWidget( myArraysModel->index( i, 3 ), aBtn ); - connect(aBtn, SIGNAL( clicked() ) , this, SLOT( onComponentsEdit() ) ); - } - } -} - -//----------------------------------------------------------------------------- -void pqArraysEditorPropertyWidget::onInputDataChanged() { - - vtkSMSourceProxy* input = vtkSMSourceProxy::SafeDownCast( vtkSMUncheckedPropertyHelper( proxy(), "Input" ).GetAsProxy( 0 ) ); - if ( myDataTime < input->GetDataInformation( 0 )->GetMTime() ) { - updateArraysList(); - } -} - -//----------------------------------------------------------------------------- -void pqArraysEditorPropertyWidget::onComponentsEdit() { - QObject* snd = sender(); - QVariant v = snd->property("arrayName"); - int index = -1; - - if( v.isValid() ) { - QString anArrayName = v.toString(); - pqComponentsModel::ComponentsInfoType* aComponents = NULL; - pqArraysModel::ArraysInfoType &aModelData = myArraysModel->editArraysInfo(); - for ( int i = 0 ; i < aModelData.size() ; i++ ) { - pqArraysModel::ArraysInfoItemType& item = aModelData[i]; - if( item.first == anArrayName ) { - aComponents = &item.second.myComponentsInfo; - index = i; - break; - } - } - - if( aComponents ) { - pqComponentsModel* aCompsModel = new pqComponentsModel(); - aCompsModel->setComponentsInfo(*aComponents); - pqEditComponents* dlg = new pqEditComponents(aCompsModel, this); - if ( dlg->exec() == QDialog::Accepted ) { - const pqComponentsModel::ComponentsInfoType& aRenamedComponents = aCompsModel->componentsInfo(); - if( dlg->renameAllComps() ) { - /// Rename all components in all arrays - for ( int i = 0 ; i < aModelData.size() ; i++ ) { - pqArraysModel::ArraysInfoItemType& item = aModelData[i]; - for (int j = 0; j < item.second.myComponentsInfo.size(); j++ ) { - pqComponentsModel::ComponentsInfoType &aComps = item.second.myComponentsInfo; - for (int k = 0; k < aRenamedComponents.size(); k++ ) { - if( aComps[j].first == aRenamedComponents[k].first ) { - aComps[j].second = aRenamedComponents[k].second; - } - } - } - } - } else { - if( index >= 0 ) { - aModelData[index].second.myComponentsInfo = aRenamedComponents; - } - } - emit componentsInfoChanged(); - } - delete dlg; - delete aCompsModel; - } - } -} diff --git a/src/Plugins/ArrayRenamer/pqArraysEditorPropertyWidget.h b/src/Plugins/ArrayRenamer/pqArraysEditorPropertyWidget.h deleted file mode 100644 index 2641e320..00000000 --- a/src/Plugins/ArrayRenamer/pqArraysEditorPropertyWidget.h +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright (C) 2014-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Roman NIKOLAEV - -/*========================================================================*/ -#ifndef __pqArraysEditorPropertyWidget_h -#define __pqArraysEditorPropertyWidget_h - -#include -#include - -// ParaView classes -class vtkSMPropertyGroup; -class vtkEventQtSlotConnect; - -// Qt Classes -class QTableView; -class QModelIndex; - -class pqArraysModel; - -/// pqArraysEditorPropertyWidget is the pqPropertyWidget used to edit -/// arrays and array's components. -class VTK_EXPORT pqArraysEditorPropertyWidget : public pqPropertyWidget { - - Q_OBJECT - - Q_PROPERTY(QList arrayInfo - READ arraysInfo - WRITE setArraysInfo - NOTIFY arraysInfoChanged) - - Q_PROPERTY(QList componentsInfo - READ componentsInfo - WRITE setComponentsInfo - NOTIFY componentsInfoChanged) - - - typedef pqPropertyWidget Superclass; - public: - pqArraysEditorPropertyWidget(vtkSMProxy* proxy, vtkSMPropertyGroup* smgroup, QWidget* parent=0); - virtual ~pqArraysEditorPropertyWidget(); - - /// Get/Set the arrays Info - QList arraysInfo() const; - void setArraysInfo(const QList&); - - /// Get/Set the arrays Info - QList componentsInfo() const; - void setComponentsInfo(const QList&); - - - signals: - /// Fired when the arrays Info is changes. - void arraysInfoChanged(); - void componentsInfoChanged(); - -private slots: - /// called whenever the internal model's data changes. - void onDataChanged(const QModelIndex& topleft, const QModelIndex& btmright); - void onComponentsEdit(); - - /// called whenever the input changed. - void onInputDataChanged(); - - private: // Methods - void updateArraysList(); - - private: // Fields - - vtkSmartPointer myPropertyGroup; - vtkEventQtSlotConnect* myConnection; - unsigned long myDataTime; - - //Array's table - pqArraysModel* myArraysModel; - QTableView* myArraysTable; -}; - -#endif // __pqArraysEditorPropertyWidget_h diff --git a/src/Plugins/ArrayRenamer/pqEditComponents.h b/src/Plugins/ArrayRenamer/pqEditComponents.h deleted file mode 100644 index 85babdb9..00000000 --- a/src/Plugins/ArrayRenamer/pqEditComponents.h +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright (C) 2014-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Roman NIKOLAEV - - -#include - -class pqComponentsModel; -class QCheckBox; - -class pqEditComponents : public QDialog { - Q_OBJECT -public: - pqEditComponents( pqComponentsModel* model, QWidget* parent ); - ~pqEditComponents(); - - bool renameAllComps(); - -private slots: - void onRenameAll(bool val); - private: - QCheckBox* myRenameAllComps; - pqComponentsModel* myComponentsModel; - -}; diff --git a/src/Plugins/ArrayRenamer/resources/copy_ico_16x16.png b/src/Plugins/ArrayRenamer/resources/copy_ico_16x16.png deleted file mode 100644 index 8969c406..00000000 Binary files a/src/Plugins/ArrayRenamer/resources/copy_ico_16x16.png and /dev/null differ diff --git a/src/Plugins/ArrayRenamer/resources/edit_ico_16x16.png b/src/Plugins/ArrayRenamer/resources/edit_ico_16x16.png deleted file mode 100644 index b73a4a3e..00000000 Binary files a/src/Plugins/ArrayRenamer/resources/edit_ico_16x16.png and /dev/null differ diff --git a/src/Plugins/ArrayRenamer/resources/rename_ico_24x24.png b/src/Plugins/ArrayRenamer/resources/rename_ico_24x24.png deleted file mode 100644 index 9066ff59..00000000 Binary files a/src/Plugins/ArrayRenamer/resources/rename_ico_24x24.png and /dev/null differ diff --git a/src/Plugins/ArrayRenamer/vtkArrayRenamerFilter.cxx b/src/Plugins/ArrayRenamer/vtkArrayRenamerFilter.cxx deleted file mode 100644 index b1cb58e0..00000000 --- a/src/Plugins/ArrayRenamer/vtkArrayRenamerFilter.cxx +++ /dev/null @@ -1,195 +0,0 @@ -// Copyright (C) 2014-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Roman NIKOLAEV - -#include "vtkArrayRenamerFilter.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -//For debug -//#include - -class vtkArrayRenamerFilter::vtkInternals -{ -public: - //Vector which contains information about array's components : origin_component_name <-> new_name - typedef std::vector< std::pair > ComponentsInfo; - - struct ArrayInfo - { - std::string NewName; // New name of the array - bool CopyArray; // Make copy of the array or keep origin array, but change the name - ComponentsInfo ComponentVector; // Components of the array - ArrayInfo(): - NewName( "" ), - CopyArray( false ) - { - } - }; - typedef std::map ArraysType; // Map : origin_aray_name <-> ArrayInfo struct - ArraysType Arrays; -}; - - -//------------------------------------------------------------------------------ -vtkStandardNewMacro(vtkArrayRenamerFilter); -//-------------------------------------------------------------------------------------------------- -vtkArrayRenamerFilter::vtkArrayRenamerFilter() -{ - this->Internals = new vtkInternals(); -} - -//-------------------------------------------------------------------------------------------------- -vtkArrayRenamerFilter::~vtkArrayRenamerFilter() -{ - delete this->Internals; -} - - - -//-------------------------------------------------------------------------------------------------- -int vtkArrayRenamerFilter::RequestData( vtkInformation* theRequest, - vtkInformationVector** theInputVector, - vtkInformationVector* theOutputVector ) -{ - - //std::cout<<"vtkArrayRenamerFilter::RequestData !!! "<GetInformationObject( 0 ); - vtkInformation *anOutputInfo = theOutputVector->GetInformationObject( 0 ); - - vtkDataSet* anInput = vtkDataSet::GetData(theInputVector[0], 0); - vtkDataSet* anOutput = vtkDataSet::GetData(theOutputVector, 0); - anOutput->DeepCopy(anInput); - vtkFieldData* data = 0; - - vtkInternals::ArraysType::iterator it = this->Internals->Arrays.begin(); - for( ; it != this->Internals->Arrays.end(); it ++ ) { - vtkDataArray* array = anOutput->GetPointData()->GetArray( it->first.c_str() ); - data = anOutput->GetPointData(); - if( !array ) { - array = anOutput->GetCellData()->GetArray( it->first.c_str() ); - data = anOutput->GetCellData(); - } - - if( array && !it->second.NewName.empty() ) { - - if ( it->second.CopyArray ) { - vtkDataArray* new_array = array->NewInstance(); - new_array->DeepCopy(array); - data->AddArray(new_array); - array = new_array; - } - array->SetName(it->second.NewName.c_str()); - } - - if ( array ) { - vtkInternals::ComponentsInfo::iterator vect_it = it->second.ComponentVector.begin(); - for( ; vect_it != it->second.ComponentVector.end(); vect_it++ ) { - array->SetComponentName( vect_it->first, vect_it->second.c_str() ); - } - } - } - - return Superclass::RequestData( theRequest, theInputVector, theOutputVector ); -} - - -void vtkArrayRenamerFilter::SetComponentInfo( const char* arrayname, const int compid, const char* newcompname ) { - //std::cout<<"vtkArrayRenamerFilter::SetComponentArrayInfo : "<Internals->Arrays.clear(); - this->Modified(); -} - -void vtkArrayRenamerFilter::ClearComponentsInfo() { - //std::cout<<"vtkArrayRenamerFilter::ClearComponentsInfo"<Internals->Arrays.begin(); - for( ; it != this->Internals->Arrays.end(); it ++ ){ - it->second.ComponentVector.clear(); - } - this->Modified(); -} diff --git a/src/Plugins/ArrayRenamer/vtkArrayRenamerFilter.h b/src/Plugins/ArrayRenamer/vtkArrayRenamerFilter.h deleted file mode 100644 index 8798199e..00000000 --- a/src/Plugins/ArrayRenamer/vtkArrayRenamerFilter.h +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright (C) 2014-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Roman NIKOLAEV - -#ifndef __ArrayRenamerFilter_h_ -#define __ArrayRenamerFilter_h_ - -#include - -/** - * Description of class: - * Class allows to rename data arrays and array's components. -*/ -class VTK_EXPORT vtkArrayRenamerFilter : public vtkDataSetAlgorithm -{ -public: - /// Returns pointer on a new instance of the class - static vtkArrayRenamerFilter* New(); - - vtkTypeMacro( vtkArrayRenamerFilter, vtkDataSetAlgorithm ); - - void SetArrayInfo( const char* originarrayname, const char* newarrayname, bool copy ); - void ClearArrayInfo(); - - void SetComponentInfo( const char* arrayname, const int compid, const char* newarrayname ); - void ClearComponentsInfo(); -protected: - /// Constructor & destructor - vtkArrayRenamerFilter(); - virtual ~vtkArrayRenamerFilter(); - - virtual int RequestData( vtkInformation *, - vtkInformationVector **, - vtkInformationVector * ); -private: - vtkArrayRenamerFilter( const vtkArrayRenamerFilter & ); // Not implemented yet - void operator=( const vtkArrayRenamerFilter & ); // Not implemented yet - - void FillListOfArrays( vtkDataObject* ); - - class vtkInternals; - friend class vtkInternals; - vtkInternals* Internals; - -}; - -#endif // __ArrayRenamerFilter_h_ diff --git a/src/Plugins/CMakeLists.txt b/src/Plugins/CMakeLists.txt index f97e6aed..787639a9 100644 --- a/src/Plugins/CMakeLists.txt +++ b/src/Plugins/CMakeLists.txt @@ -17,8 +17,6 @@ # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com # -INCLUDE(${PARAVIEW_USE_FILE}) - SET(_subdirs MEDReader MEDWriter @@ -38,9 +36,7 @@ SET(_subdirs IF(NOT SALOME_LIGHT_ONLY) IF(SALOME_PARAVIS_BUILD_CORBA_PLUGINS) - LIST(APPEND _subdirs - ParaMEDCorba - ) + LIST(APPEND _subdirs ParaMEDCorba) ENDIF() ENDIF() diff --git a/src/Plugins/DevelopedSurface/CMakeLists.txt b/src/Plugins/DevelopedSurface/CMakeLists.txt index 3a592742..69224e42 100644 --- a/src/Plugins/DevelopedSurface/CMakeLists.txt +++ b/src/Plugins/DevelopedSurface/CMakeLists.txt @@ -1,76 +1,30 @@ -# Copyright (C) 2017-2019 EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# -# Author : Anthony Geay (EDF R&D) - -PROJECT(DevelopedSurface) -CMAKE_MINIMUM_REQUIRED(VERSION 2.8) - -CMAKE_POLICY(SET CMP0003 NEW) -IF(${CMAKE_VERSION} VERSION_GREATER "3.0.0") - CMAKE_POLICY(SET CMP0022 OLD) - CMAKE_POLICY(SET CMP0023 OLD) -ENDIF() - - -ENABLE_TESTING() - -# Common CMake macros -# =================== -SET(CONFIGURATION_ROOT_DIR $ENV{CONFIGURATION_ROOT_DIR} CACHE PATH "Path to the Salome CMake configuration files") -IF(EXISTS ${CONFIGURATION_ROOT_DIR}) - LIST(APPEND CMAKE_MODULE_PATH "${CONFIGURATION_ROOT_DIR}/cmake") - INCLUDE(SalomeMacros) -ELSE() - MESSAGE(FATAL_ERROR "We absolutely need the Salome CMake configuration files, please define CONFIGURATION_ROOT_DIR !") -ENDIF() -FIND_PACKAGE(SalomePythonInterp REQUIRED) -FIND_PACKAGE(SalomePythonLibs REQUIRED) -FIND_PACKAGE(SalomeMEDFile REQUIRED) - -FIND_PACKAGE(ParaView REQUIRED) -IF(NOT ParaView_FOUND) - MESSAGE(FATAL_ERROR "Please locate ParaView." ) -ENDIF(NOT ParaView_FOUND) -INCLUDE(${PARAVIEW_USE_FILE}) - -SET(MEDCOUPLING_ROOT_DIR $ENV{MEDCOUPLING_ROOT_DIR} CACHE PATH "MEDCOUPLING_ROOT_DIR") -LIST(APPEND CMAKE_MODULE_PATH "${MEDCOUPLING_ROOT_DIR}/cmake_files") - -## -FIND_PACKAGE(SalomeMEDCoupling REQUIRED) - -IF(MEDCOUPLING_USE_64BIT_IDS) - ADD_DEFINITIONS("-DMEDCOUPLING_USE_64BIT_IDS") -ENDIF(MEDCOUPLING_USE_64BIT_IDS) - - -OPTION(BUILD_SHARED_LIBS "Build with shared libraries." ${VTK_BUILD_SHARED_LIBS}) - -SET(VTK_INSTALL_RUNTIME_DIR lib) -SET(VTK_INSTALL_LIBRARY_DIR lib) -SET(VTK_INSTALL_ARCHIVE_DIR lib) - -PV_PROCESS_MODULES() -INCLUDE_DIRECTORIES( ${MEDCOUPLING_INCLUDE_DIRS} ${MEDFILE_INCLUDE_DIRS}) -INCLUDE_DIRECTORIES( "${PROJECT_SOURCE_DIR}/../MEDWriter/IO" ) -#INCLUDE_DIRECTORIES( "${PARAVIS_ROOT_DIR}/include/salome" ) -ADD_SUBDIRECTORY(ParaViewPlugin) - - -ADD_SUBDIRECTORY(Test) +cmake_minimum_required(VERSION 3.8) +project(DevelopedSurfacePlugin) +find_package(ParaView REQUIRED) + +include(GNUInstallDirs) +set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_BINDIR}") +set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_LIBDIR}") +set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_LIBDIR}") + +set("_paraview_plugin_default_${CMAKE_PROJECT_NAME}" ON) +paraview_plugin_scan( + ENABLE_BY_DEFAULT YES + PLUGIN_FILES "${CMAKE_CURRENT_SOURCE_DIR}/plugin/paraview.plugin" + PROVIDES_PLUGINS plugins + REQUIRES_MODULES required_modules) + +foreach(module IN LISTS required_modules) + if(NOT TARGET "${module}") + message("Missing required module: ${module}") + return() + endif() +endforeach() + +set(BUILD_SHARED_LIBS ON) +paraview_plugin_build( + RUNTIME_DESTINATION "${CMAKE_INSTALL_BINDIR}" + LIBRARY_DESTINATION "${CMAKE_INSTALL_LIBDIR}" + LIBRARY_SUBDIRECTORY "${PARAVIEW_PLUGIN_SUBDIR}" + PLUGINS ${plugins} + AUTOLOAD ${plugins}) diff --git a/src/Plugins/DevelopedSurface/IO/vtkDevelopedSurface.h b/src/Plugins/DevelopedSurface/IO/vtkDevelopedSurface.h deleted file mode 100644 index a5138454..00000000 --- a/src/Plugins/DevelopedSurface/IO/vtkDevelopedSurface.h +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright (C) 2017-2019 EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Anthony Geay (EDF R&D) - -#ifndef vtkDevelopedSurface_h__ -#define vtkDevelopedSurface_h__ - -#include "vtkDataSetAlgorithm.h" - -class vtkMutableDirectedGraph; -class vtkImplicitFunction; -class vtkCylinder; - -class VTK_EXPORT vtkDevelopedSurface : public vtkDataSetAlgorithm -{ -public: - static vtkDevelopedSurface* New(); - vtkTypeMacro(vtkDevelopedSurface, vtkDataSetAlgorithm) - void PrintSelf(ostream& os, vtkIndent indent); - void SetCutFunction(vtkImplicitFunction* func); - vtkMTimeType GetMTime(); - void SetInvertWay(bool invertStatus); - void SetThetaOffset(double offsetInDegrees); -protected: - vtkDevelopedSurface(); - ~vtkDevelopedSurface(); - int FillOutputPortInformation( int vtkNotUsed(port), vtkInformation* info); - int RequestInformation(vtkInformation *request, - vtkInformationVector **inputVector, vtkInformationVector *outputVector); - - int RequestData(vtkInformation *request, vtkInformationVector **inputVector, - vtkInformationVector *outputVector); -private: - vtkDevelopedSurface(const vtkDevelopedSurface&); - void operator=(const vtkDevelopedSurface&); // Not implemented. - private: - //BTX - vtkCylinder *_cyl; - //ETX - - class vtkInternals; - vtkInternals *Internal; - bool InvertStatus; - double OffsetInRad; -}; - -#endif diff --git a/src/Plugins/DevelopedSurface/ParaViewPlugin/CMakeLists.txt b/src/Plugins/DevelopedSurface/ParaViewPlugin/CMakeLists.txt deleted file mode 100644 index f9e37380..00000000 --- a/src/Plugins/DevelopedSurface/ParaViewPlugin/CMakeLists.txt +++ /dev/null @@ -1,26 +0,0 @@ -# Copyright (C) 2017-2019 EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# -# Author : Anthony Geay (EDF R&D) - -INCLUDE_DIRECTORIES( ${CMAKE_CURRENT_SOURCE_DIR}/../IO ) -ADD_PARAVIEW_PLUGIN(DevelopedSurfacePlugin "4.0" - SERVER_MANAGER_SOURCES ${SM_SRCS} ${PROJECT_SOURCE_DIR}/IO/vtkDevelopedSurface.cxx - SERVER_MANAGER_XML Resources/DevelopedSurfaceServer.xml) -TARGET_LINK_LIBRARIES(DevelopedSurfacePlugin VTKToMEDMem) -INSTALL(TARGETS DevelopedSurfacePlugin RUNTIME DESTINATION lib/paraview LIBRARY DESTINATION lib/paraview ARCHIVE DESTINATION lib/paraview) diff --git a/src/Plugins/DevelopedSurface/ParaViewPlugin/Resources/DevelopedSurfaceServer.xml b/src/Plugins/DevelopedSurface/ParaViewPlugin/Resources/DevelopedSurfaceServer.xml deleted file mode 100644 index 15570245..00000000 --- a/src/Plugins/DevelopedSurface/ParaViewPlugin/Resources/DevelopedSurfaceServer.xml +++ /dev/null @@ -1,47 +0,0 @@ - - - - - - - - - - - - - This property specifies the input to the Level Scalars filter. - - - - - - - - - - This property sets the parameters of cylinder used for slice. - - - - Specify if way used to develop theta is inverted or not relative to the reference one. By default no. The reference way used is those defined by the first cell sharing node 0. - - - - By default, node 0 theta parameter is used as starting point. This property allows to change this reference by applying an offset on it. Offset is expressed in degrees. - - - - - - - diff --git a/src/Plugins/DevelopedSurface/Test/CMakeLists.txt b/src/Plugins/DevelopedSurface/Test/CMakeLists.txt deleted file mode 100644 index ccd6d186..00000000 --- a/src/Plugins/DevelopedSurface/Test/CMakeLists.txt +++ /dev/null @@ -1,33 +0,0 @@ -# Copyright (C) 2017-2019 EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# - -SET(TEMP_DIR "${CMAKE_CURRENT_BINARY_DIR}/Testing/Temporary") - -IF(NOT EXISTS ${TEMP_DIR}) - FILE(MAKE_DIRECTORY ${TEMP_DIR}) -ENDIF(NOT EXISTS ${TEMP_DIR}) - -SET(DEV_SURFACE_TESTS test_dev_surface2 test_dev_surface3) - -IF(NOT SALOME_PARAVIS_NO_VISU_TESTS) - FOREACH(tfile ${DEV_SURFACE_TESTS}) - ADD_TEST(${tfile} ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/${tfile}.py ) - SET_TESTS_PROPERTIES(${tfile} PROPERTIES LABELS "PVS_ADD_ONS") - ENDFOREACH(tfile ${DEV_SURFACE_TESTS}) -ENDIF() diff --git a/src/Plugins/DevelopedSurface/Test/test_dev_surface.py b/src/Plugins/DevelopedSurface/Test/test_dev_surface.py deleted file mode 100644 index 0b3f2b05..00000000 --- a/src/Plugins/DevelopedSurface/Test/test_dev_surface.py +++ /dev/null @@ -1,162 +0,0 @@ -# Copyright (C) 2017-2019 EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# -# Author : Anthony Geay (EDF R&D) - -#### import the simple module from the paraview -from paraview.simple import * -#### disable automatic camera reset on 'Show' -paraview.simple._DisableFirstRenderCameraReset() - -# create a new 'MED Reader' -multiTSmed = MEDReader(FileName='multiTS.med') -multiTSmed.AllArrays = ['TS0/Mesh/ComSup0/Pressure@@][@@P0'] -multiTSmed.AllTimeSteps = ['0000', '0001', '0002', '0003', '0004', '0005', '0006', '0007', '0008', '0009'] - -# get animation scene -animationScene1 = GetAnimationScene() - -# update animation scene based on data timesteps -animationScene1.UpdateAnimationUsingDataTimeSteps() - -# get active view -renderView1 = GetActiveViewOrCreate('RenderView') -# uncomment following to set a specific view size -# renderView1.ViewSize = [1499, 582] - -# show data in view -multiTSmedDisplay = Show(multiTSmed, renderView1) - -# trace defaults for the display properties. -multiTSmedDisplay.Representation = 'Surface' -multiTSmedDisplay.ColorArrayName = [None, ''] -multiTSmedDisplay.OSPRayScaleArray = 'FamilyIdNode' -multiTSmedDisplay.OSPRayScaleFunction = 'PiecewiseFunction' -multiTSmedDisplay.SelectOrientationVectors = 'FamilyIdNode' -multiTSmedDisplay.ScaleFactor = 0.07399989366531372 -multiTSmedDisplay.SelectScaleArray = 'FamilyIdNode' -multiTSmedDisplay.GlyphType = 'Arrow' -multiTSmedDisplay.GlyphTableIndexArray = 'FamilyIdNode' -multiTSmedDisplay.DataAxesGrid = 'GridAxesRepresentation' -multiTSmedDisplay.PolarAxes = 'PolarAxesRepresentation' -multiTSmedDisplay.ScalarOpacityUnitDistance = 0.017316274962626298 -multiTSmedDisplay.GaussianRadius = 0.03699994683265686 -multiTSmedDisplay.SetScaleArray = ['POINTS', 'FamilyIdNode'] -multiTSmedDisplay.ScaleTransferFunction = 'PiecewiseFunction' -multiTSmedDisplay.OpacityArray = ['POINTS', 'FamilyIdNode'] -multiTSmedDisplay.OpacityTransferFunction = 'PiecewiseFunction' -multiTSmedDisplay.InputVectors = [None, ''] -multiTSmedDisplay.SelectInputVectors = [None, ''] -multiTSmedDisplay.WriteLog = '' - -# init the 'PiecewiseFunction' selected for 'ScaleTransferFunction' -multiTSmedDisplay.ScaleTransferFunction.Points = [0.0, 0.0, 0.5, 0.0, 1.1757813367477812e-38, 1.0, 0.5, 0.0] - -# init the 'PiecewiseFunction' selected for 'OpacityTransferFunction' -multiTSmedDisplay.OpacityTransferFunction.Points = [0.0, 0.0, 0.5, 0.0, 1.1757813367477812e-38, 1.0, 0.5, 0.0] - -# reset view to fit data -renderView1.ResetCamera() - -# update the view to ensure updated data information -renderView1.Update() - -# create a new 'Developed Surface' -developedSurface1 = DevelopedSurface(Input=multiTSmed) -developedSurface1.SliceType = 'Cylinder' - -# init the 'Cylinder' selected for 'SliceType' -developedSurface1.SliceType.Center = [0.0, 0.0, 0.05000000074505806] -developedSurface1.SliceType.Radius = 0.3699994683265686 - -# Properties modified on developedSurface1.SliceType -developedSurface1.SliceType.Center = [0.0, 0.0, 0.05] -developedSurface1.SliceType.Axis = [0.0, 0.0, 1.0] -developedSurface1.SliceType.Radius = 0.07 - -# Properties modified on developedSurface1.SliceType -developedSurface1.SliceType.Center = [0.0, 0.0, 0.05] -developedSurface1.SliceType.Axis = [0.0, 0.0, 1.0] -developedSurface1.SliceType.Radius = 0.07 - -# show data in view -developedSurface1Display = Show(developedSurface1, renderView1) - -# trace defaults for the display properties. -developedSurface1Display.Representation = 'Surface' -developedSurface1Display.ColorArrayName = [None, ''] -developedSurface1Display.OSPRayScaleArray = 'FamilyIdNode' -developedSurface1Display.OSPRayScaleFunction = 'PiecewiseFunction' -developedSurface1Display.SelectOrientationVectors = 'FamilyIdNode' -developedSurface1Display.ScaleFactor = 0.043982297150257116 -developedSurface1Display.SelectScaleArray = 'FamilyIdNode' -developedSurface1Display.GlyphType = 'Arrow' -developedSurface1Display.GlyphTableIndexArray = 'FamilyIdNode' -developedSurface1Display.DataAxesGrid = 'GridAxesRepresentation' -developedSurface1Display.PolarAxes = 'PolarAxesRepresentation' -developedSurface1Display.GaussianRadius = 0.021991148575128558 -developedSurface1Display.SetScaleArray = ['POINTS', 'FamilyIdNode'] -developedSurface1Display.ScaleTransferFunction = 'PiecewiseFunction' -developedSurface1Display.OpacityArray = ['POINTS', 'FamilyIdNode'] -developedSurface1Display.OpacityTransferFunction = 'PiecewiseFunction' -developedSurface1Display.InputVectors = [None, ''] -developedSurface1Display.SelectInputVectors = [None, ''] -developedSurface1Display.WriteLog = '' - -# init the 'PiecewiseFunction' selected for 'ScaleTransferFunction' -developedSurface1Display.ScaleTransferFunction.Points = [0.0, 0.0, 0.5, 0.0, 1.1757813367477812e-38, 1.0, 0.5, 0.0] - -# init the 'PiecewiseFunction' selected for 'OpacityTransferFunction' -developedSurface1Display.OpacityTransferFunction.Points = [0.0, 0.0, 0.5, 0.0, 1.1757813367477812e-38, 1.0, 0.5, 0.0] - -# hide data in view -Hide(multiTSmed, renderView1) - -# update the view to ensure updated data information -renderView1.Update() - -#change interaction mode for render view -renderView1.InteractionMode = '2D' - -# toggle 3D widget visibility (only when running from the GUI) -Hide3DWidgets(proxy=developedSurface1.SliceType) - -# set scalar coloring -ColorBy(developedSurface1Display, ('CELLS', 'Pressure')) - -# rescale color and/or opacity maps used to include current data range -developedSurface1Display.RescaleTransferFunctionToDataRange(True, False) - -# show color bar/color legend -developedSurface1Display.SetScalarBarVisibility(renderView1, True) - -# get color transfer function/color map for 'Pressure' -pressureLUT = GetColorTransferFunction('Pressure') - -#### saving camera placements for all active views - -# current camera placement for renderView1 -renderView1.InteractionMode = '2D' -renderView1.CameraPosition = [0.18935662797765695, 0.01726656182167085, 2.08092363470839] -renderView1.CameraFocalPoint = [0.18935662797765695, 0.01726656182167085, 0.05000000074505806] -renderView1.CameraParallelScale = 0.16748564967020724 - -#### uncomment the following to render all views -# RenderAllViews() -# alternatively, if you want to write images, you can use SaveScreenshot(...). -Render() diff --git a/src/Plugins/DevelopedSurface/Test/test_dev_surface2.py b/src/Plugins/DevelopedSurface/Test/test_dev_surface2.py deleted file mode 100644 index d52406b8..00000000 --- a/src/Plugins/DevelopedSurface/Test/test_dev_surface2.py +++ /dev/null @@ -1,170 +0,0 @@ -# Copyright (C) 2017-2019 EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# -# Author : Anthony Geay (EDF R&D) - -#### import the simple module from the paraview -from paraview.simple import * -from math import pi -TMPFileName="test2.med" - -#### disable automatic camera reset on 'Show' -paraview.simple._DisableFirstRenderCameraReset() - -# create a new 'Mandelbrot' -mandelbrot1 = Mandelbrot() - -# Properties modified on mandelbrot1 -mandelbrot1.WholeExtent = [0, 50, 0, 50, 0, 50] - -# get active view -renderView1 = GetActiveViewOrCreate('RenderView') -# uncomment following to set a specific view size -# renderView1.ViewSize = [1017, 317] - -# show data in view -mandelbrot1Display = Show(mandelbrot1, renderView1) - -# trace defaults for the display properties. -mandelbrot1Display.Representation = 'Outline' -mandelbrot1Display.ColorArrayName = ['POINTS', ''] -mandelbrot1Display.OSPRayScaleArray = 'Iterations' -mandelbrot1Display.OSPRayScaleFunction = 'PiecewiseFunction' -mandelbrot1Display.SelectOrientationVectors = 'Iterations' -mandelbrot1Display.ScaleFactor = 0.25 -mandelbrot1Display.SelectScaleArray = 'Iterations' -mandelbrot1Display.GlyphType = 'Arrow' -mandelbrot1Display.GlyphTableIndexArray = 'Iterations' -mandelbrot1Display.DataAxesGrid = 'GridAxesRepresentation' -mandelbrot1Display.PolarAxes = 'PolarAxesRepresentation' -mandelbrot1Display.ScalarOpacityUnitDistance = 0.08124038404635964 -mandelbrot1Display.Slice = 25 -mandelbrot1Display.GaussianRadius = 0.125 -mandelbrot1Display.SetScaleArray = ['POINTS', 'Iterations'] -mandelbrot1Display.ScaleTransferFunction = 'PiecewiseFunction' -mandelbrot1Display.OpacityArray = ['POINTS', 'Iterations'] -mandelbrot1Display.OpacityTransferFunction = 'PiecewiseFunction' -mandelbrot1Display.InputVectors = [None, ''] -mandelbrot1Display.SelectInputVectors = [None, ''] -mandelbrot1Display.WriteLog = '' - -# init the 'PiecewiseFunction' selected for 'ScaleTransferFunction' -mandelbrot1Display.ScaleTransferFunction.Points = [1.0, 0.0, 0.5, 0.0, 100.0, 1.0, 0.5, 0.0] - -# init the 'PiecewiseFunction' selected for 'OpacityTransferFunction' -mandelbrot1Display.OpacityTransferFunction.Points = [1.0, 0.0, 0.5, 0.0, 100.0, 1.0, 0.5, 0.0] - -# reset view to fit data -renderView1.ResetCamera() - -# update the view to ensure updated data information -renderView1.Update() - -# create a new 'Developed Surface' -developedSurface1 = DevelopedSurface(Input=mandelbrot1) -developedSurface1.SliceType = 'Cylinder' - -# init the 'Cylinder' selected for 'SliceType' -developedSurface1.SliceType.Center = [-0.5, 0.0, 1.0] -developedSurface1.SliceType.Radius = 0.5 #1.25 - -# show data in view -developedSurface1Display = Show(developedSurface1, renderView1) - -# get color transfer function/color map for 'Iterations' -iterationsLUT = GetColorTransferFunction('Iterations') - -# trace defaults for the display properties. -developedSurface1Display.Representation = 'Surface' -developedSurface1Display.ColorArrayName = ['POINTS', 'Iterations'] -developedSurface1Display.LookupTable = iterationsLUT -developedSurface1Display.OSPRayScaleArray = 'Iterations' -developedSurface1Display.OSPRayScaleFunction = 'PiecewiseFunction' -developedSurface1Display.SelectOrientationVectors = 'Iterations' -developedSurface1Display.ScaleFactor = 0.7853981633974483 -developedSurface1Display.SelectScaleArray = 'Iterations' -developedSurface1Display.GlyphType = 'Arrow' -developedSurface1Display.GlyphTableIndexArray = 'Iterations' -developedSurface1Display.DataAxesGrid = 'GridAxesRepresentation' -developedSurface1Display.PolarAxes = 'PolarAxesRepresentation' -developedSurface1Display.GaussianRadius = 0.39269908169872414 -developedSurface1Display.SetScaleArray = ['POINTS', 'Iterations'] -developedSurface1Display.ScaleTransferFunction = 'PiecewiseFunction' -developedSurface1Display.OpacityArray = ['POINTS', 'Iterations'] -developedSurface1Display.OpacityTransferFunction = 'PiecewiseFunction' -developedSurface1Display.InputVectors = [None, ''] -developedSurface1Display.SelectInputVectors = [None, ''] -developedSurface1Display.WriteLog = '' - -# init the 'PiecewiseFunction' selected for 'ScaleTransferFunction' -developedSurface1Display.ScaleTransferFunction.Points = [1.0, 0.0, 0.5, 0.0, 100.0, 1.0, 0.5, 0.0] - -# init the 'PiecewiseFunction' selected for 'OpacityTransferFunction' -developedSurface1Display.OpacityTransferFunction.Points = [1.0, 0.0, 0.5, 0.0, 100.0, 1.0, 0.5, 0.0] - -# hide data in view -Hide(mandelbrot1, renderView1) - -# show color bar/color legend -developedSurface1Display.SetScalarBarVisibility(renderView1, True) - -# update the view to ensure updated data information -renderView1.Update() - -# toggle 3D widget visibility (only when running from the GUI) -Hide3DWidgets(proxy=developedSurface1.SliceType) - -#### saving camera placements for all active views - -# current camera placement for renderView1 -renderView1.CameraPosition = [4.090024784500779, -0.15919161102314858, 7.485304552729019] -renderView1.CameraFocalPoint = [4.090024784500779, -0.15919161102314858, 1.0] -renderView1.CameraParallelScale = 2.03100960115899 - -#### uncomment the following to render all views -# RenderAllViews() -# alternatively, if you want to write images, you can use SaveScreenshot(...). - -mand=servermanager.Fetch(mandelbrot1) -axisId=1 -high_out=mand.GetSpacing()[axisId]*(mand.GetExtent()[2*axisId+1]-mand.GetExtent()[2*axisId+0]) - -vtp=servermanager.Fetch(developedSurface1) -arr=vtp.GetPointData().GetArray(0) -assert(arr.GetName()=="Iterations") -a,b=arr.GetRange() -assert(a>=1 and a<=2) -assert(b==100.) -SaveData(TMPFileName, proxy=developedSurface1) -from MEDLoader import * - -mm=MEDFileMesh.New(TMPFileName) -m0=mm[0] -area=m0.getMeasureField(True).getArray().accumulate()[0] - -zeResu0=area/high_out/developedSurface1.SliceType.Radius -assert(abs(zeResu0-2*pi)<1e-5) - -fs=MEDFileFields(TMPFileName) -f=fs["Iterations"][0].field(mm) -nodeIds=f.getArray().convertToDblArr().findIdsInRange(99.,101.) -cellIds=m0.getCellIdsLyingOnNodes(nodeIds,True) -zeResu1=m0[cellIds].getMeasureField(True).getArray().accumulate()[0] - -assert(abs(zeResu1-1.1427)<1e-2) - diff --git a/src/Plugins/DevelopedSurface/Test/test_dev_surface3.py b/src/Plugins/DevelopedSurface/Test/test_dev_surface3.py deleted file mode 100644 index ba748b88..00000000 --- a/src/Plugins/DevelopedSurface/Test/test_dev_surface3.py +++ /dev/null @@ -1,166 +0,0 @@ -# Copyright (C) 2017-2019 EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# -# Author : Anthony Geay (EDF R&D) - -#### import the simple module from the paraview -from paraview.simple import * -from math import pi -TMPFileName="test3.med" - -#### disable automatic camera reset on 'Show' -paraview.simple._DisableFirstRenderCameraReset() - -# create a new 'Mandelbrot' -mandelbrot1 = Mandelbrot() - -# Properties modified on mandelbrot1 -mandelbrot1.WholeExtent = [0, 50, 0, 50, 0, 50] - -# get active view -renderView1 = GetActiveViewOrCreate('RenderView') -# uncomment following to set a specific view size -# renderView1.ViewSize = [1017, 317] - -# show data in view -mandelbrot1Display = Show(mandelbrot1, renderView1) - -# trace defaults for the display properties. -mandelbrot1Display.Representation = 'Outline' -mandelbrot1Display.ColorArrayName = ['POINTS', ''] -mandelbrot1Display.OSPRayScaleArray = 'Iterations' -mandelbrot1Display.OSPRayScaleFunction = 'PiecewiseFunction' -mandelbrot1Display.SelectOrientationVectors = 'Iterations' -mandelbrot1Display.ScaleFactor = 0.25 -mandelbrot1Display.SelectScaleArray = 'Iterations' -mandelbrot1Display.GlyphType = 'Arrow' -mandelbrot1Display.GlyphTableIndexArray = 'Iterations' -mandelbrot1Display.DataAxesGrid = 'GridAxesRepresentation' -mandelbrot1Display.PolarAxes = 'PolarAxesRepresentation' -mandelbrot1Display.ScalarOpacityUnitDistance = 0.08124038404635964 -mandelbrot1Display.Slice = 25 -mandelbrot1Display.GaussianRadius = 0.125 -mandelbrot1Display.SetScaleArray = ['POINTS', 'Iterations'] -mandelbrot1Display.ScaleTransferFunction = 'PiecewiseFunction' -mandelbrot1Display.OpacityArray = ['POINTS', 'Iterations'] -mandelbrot1Display.OpacityTransferFunction = 'PiecewiseFunction' -mandelbrot1Display.InputVectors = [None, ''] -mandelbrot1Display.SelectInputVectors = [None, ''] -mandelbrot1Display.WriteLog = '' - -# init the 'PiecewiseFunction' selected for 'ScaleTransferFunction' -mandelbrot1Display.ScaleTransferFunction.Points = [1.0, 0.0, 0.5, 0.0, 100.0, 1.0, 0.5, 0.0] - -# init the 'PiecewiseFunction' selected for 'OpacityTransferFunction' -mandelbrot1Display.OpacityTransferFunction.Points = [1.0, 0.0, 0.5, 0.0, 100.0, 1.0, 0.5, 0.0] - -# reset view to fit data -renderView1.ResetCamera() - -# update the view to ensure updated data information -renderView1.Update() - -# create a new 'Developed Surface' -developedSurface1 = DevelopedSurface(Input=mandelbrot1) -developedSurface1.SliceType = 'Cylinder' - -# init the 'Cylinder' selected for 'SliceType' -developedSurface1.SliceType.Center = [-0.5, 0.0, 1.0] -developedSurface1.SliceType.Radius = 0.5 #1.25 -developedSurface1.SliceType.Axis = [-0.5065630563269753, -0.6288876685363318, -0.5898255422814533] - -# show data in view -developedSurface1Display = Show(developedSurface1, renderView1) - -# get color transfer function/color map for 'Iterations' -iterationsLUT = GetColorTransferFunction('Iterations') - -# trace defaults for the display properties. -developedSurface1Display.Representation = 'Surface' -developedSurface1Display.ColorArrayName = ['POINTS', 'Iterations'] -developedSurface1Display.LookupTable = iterationsLUT -developedSurface1Display.OSPRayScaleArray = 'Iterations' -developedSurface1Display.OSPRayScaleFunction = 'PiecewiseFunction' -developedSurface1Display.SelectOrientationVectors = 'Iterations' -developedSurface1Display.ScaleFactor = 0.7853981633974483 -developedSurface1Display.SelectScaleArray = 'Iterations' -developedSurface1Display.GlyphType = 'Arrow' -developedSurface1Display.GlyphTableIndexArray = 'Iterations' -developedSurface1Display.DataAxesGrid = 'GridAxesRepresentation' -developedSurface1Display.PolarAxes = 'PolarAxesRepresentation' -developedSurface1Display.GaussianRadius = 0.39269908169872414 -developedSurface1Display.SetScaleArray = ['POINTS', 'Iterations'] -developedSurface1Display.ScaleTransferFunction = 'PiecewiseFunction' -developedSurface1Display.OpacityArray = ['POINTS', 'Iterations'] -developedSurface1Display.OpacityTransferFunction = 'PiecewiseFunction' -developedSurface1Display.InputVectors = [None, ''] -developedSurface1Display.SelectInputVectors = [None, ''] -developedSurface1Display.WriteLog = '' - -# init the 'PiecewiseFunction' selected for 'ScaleTransferFunction' -developedSurface1Display.ScaleTransferFunction.Points = [1.0, 0.0, 0.5, 0.0, 100.0, 1.0, 0.5, 0.0] - -# init the 'PiecewiseFunction' selected for 'OpacityTransferFunction' -developedSurface1Display.OpacityTransferFunction.Points = [1.0, 0.0, 0.5, 0.0, 100.0, 1.0, 0.5, 0.0] - -# hide data in view -Hide(mandelbrot1, renderView1) - -# show color bar/color legend -developedSurface1Display.SetScalarBarVisibility(renderView1, True) - -# update the view to ensure updated data information -renderView1.Update() - -# toggle 3D widget visibility (only when running from the GUI) -Hide3DWidgets(proxy=developedSurface1.SliceType) - -#### saving camera placements for all active views - -# current camera placement for renderView1 -renderView1.CameraPosition = [4.090024784500779, -0.15919161102314858, 7.485304552729019] -renderView1.CameraFocalPoint = [4.090024784500779, -0.15919161102314858, 1.0] -renderView1.CameraParallelScale = 2.03100960115899 - -#### uncomment the following to render all views -# RenderAllViews() -# alternatively, if you want to write images, you can use SaveScreenshot(...). - - -vtp=servermanager.Fetch(developedSurface1) -arr=vtp.GetPointData().GetArray(0) -assert(arr.GetName()=="Iterations") -a,b=arr.GetRange() -assert(a>=1 and a<=2) -assert(b==100.) -SaveData(TMPFileName, proxy=developedSurface1) -from MEDLoader import * - -mm=MEDFileMesh.New(TMPFileName) -m0=mm[0] -area=m0.getMeasureField(True).getArray().accumulate()[0] - - -fs=MEDFileFields(TMPFileName) -f=fs["Iterations"][0].field(mm) -nodeIds=f.getArray().convertToDblArr().findIdsInRange(99.,101.) -cellIds=m0.getCellIdsLyingOnNodes(nodeIds,True) -zeResu1=m0[cellIds].getMeasureField(True).getArray().accumulate()[0] - -assert(abs(zeResu1-1.3564)<1e-2) - diff --git a/src/Plugins/DevelopedSurface/plugin/CMakeLists.txt b/src/Plugins/DevelopedSurface/plugin/CMakeLists.txt new file mode 100644 index 00000000..2fc9c0aa --- /dev/null +++ b/src/Plugins/DevelopedSurface/plugin/CMakeLists.txt @@ -0,0 +1,46 @@ +# Common CMake macros +# =================== +set(TMP_CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH}) +unset(CMAKE_MODULE_PATH) +set(CONFIGURATION_ROOT_DIR $ENV{CONFIGURATION_ROOT_DIR} CACHE PATH "Path to the Salome CMake configuration files") +if(EXISTS ${CONFIGURATION_ROOT_DIR}) + list(APPEND CMAKE_MODULE_PATH "${CONFIGURATION_ROOT_DIR}/cmake") + include(SalomeMacros) +else() + message(FATAL_ERROR "We absolutely need the Salome CMake configuration files, please define CONFIGURATION_ROOT_DIR !") +endif() + +set(MEDCOUPLING_ROOT_DIR $ENV{MEDCOUPLING_ROOT_DIR} CACHE PATH "Path to the MEDCoupling tool") +if(EXISTS ${MEDCOUPLING_ROOT_DIR}) + list(APPEND CMAKE_MODULE_PATH "${MEDCOUPLING_ROOT_DIR}/cmake_files") +endif() +list(APPEND CMAKE_MODULE_PATH "${CMAKE_ROOT}/Modules") +list(APPEND CMAKE_MODULE_PATH ${TMP_CMAKE_MODULE_PATH}) + +include(SalomeSetupPlatform) +set(BUILD_SHARED_LIBS TRUE) + +find_package(SalomeHDF5 REQUIRED) +find_package(SalomeMEDCoupling REQUIRED) + +if(MEDCOUPLING_USE_64BIT_IDS) + add_definitions("-DMEDCOUPLING_USE_64BIT_IDS") +endif(MEDCOUPLING_USE_64BIT_IDS) + +SALOME_ACCUMULATE_ENVIRONMENT(PYTHONPATH NOCHECK ${CMAKE_INSTALL_PREFIX}/${SALOME_INSTALL_BINS} + ${CMAKE_INSTALL_PREFIX}/${SALOME_INSTALL_PYTHON}) +SALOME_ACCUMULATE_ENVIRONMENT(LD_LIBRARY_PATH NOCHECK ${CMAKE_INSTALL_PREFIX}/${SALOME_INSTALL_LIBS}) +SALOME_ACCUMULATE_ENVIRONMENT(PV_PLUGIN_PATH NOCHECK ${CMAKE_INSTALL_PREFIX}/lib/paraview) + +paraview_add_plugin(DevelopedSurfacePlugin + VERSION "1.0" + MODULES DevelopedSurfaceModule + MODULE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/DevelopedSurfaceModule/vtk.module" + SERVER_MANAGER_XML filters.xml + ) + +install(TARGETS DevelopedSurfacePlugin + RUNTIME DESTINATION lib/paraview + LIBRARY DESTINATION lib/paraview + ARCHIVE DESTINATION lib/paraview + ) diff --git a/src/Plugins/DevelopedSurface/plugin/DevelopedSurfaceModule/CMakeLists.txt b/src/Plugins/DevelopedSurface/plugin/DevelopedSurfaceModule/CMakeLists.txt new file mode 100644 index 00000000..0afb641a --- /dev/null +++ b/src/Plugins/DevelopedSurface/plugin/DevelopedSurfaceModule/CMakeLists.txt @@ -0,0 +1,17 @@ +set(classes + vtkDevelopedSurface + VTKToMEDMem +) + +vtk_module_add_module(DevelopedSurfaceModule + FORCE_STATIC + CLASSES ${classes} +) + +target_include_directories(DevelopedSurfaceModule PRIVATE ${MEDCOUPLING_INCLUDE_DIRS}) + +if(HDF5_IS_PARALLEL) + target_link_libraries(DevelopedSurfaceModule PRIVATE ${MEDCoupling_paramedloader}) +else() + target_link_libraries(DevelopedSurfaceModule PRIVATE ${MEDCoupling_medloader}) +endif() diff --git a/src/Plugins/DevelopedSurface/plugin/DevelopedSurfaceModule/VTKMEDTraits.hxx b/src/Plugins/DevelopedSurface/plugin/DevelopedSurfaceModule/VTKMEDTraits.hxx new file mode 100644 index 00000000..4efcdc24 --- /dev/null +++ b/src/Plugins/DevelopedSurface/plugin/DevelopedSurfaceModule/VTKMEDTraits.hxx @@ -0,0 +1,81 @@ +// Copyright (C) 2017-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay (EDF R&D) + +#ifndef __VTKMEDTRAITS_HXX__ +#define __VTKMEDTRAITS_HXX__ + +class vtkIntArray; +class vtkLongArray; +#ifdef WIN32 +class vtkLongLongArray; +#endif +class vtkFloatArray; +class vtkDoubleArray; + +template +class MEDFileVTKTraits +{ +public: + typedef void VtkType; + typedef void MCType; +}; + +template<> +class MEDFileVTKTraits +{ +public: + typedef vtkIntArray VtkType; + typedef MEDCoupling::DataArrayInt32 MCType; +}; + +template<> +#ifdef WIN32 +class MEDFileVTKTraits +#else +class MEDFileVTKTraits +#endif +# +{ +public: +#ifdef WIN32 + typedef vtkLongLongArray VtkType; +#else + typedef vtkLongArray VtkType; +#endif + typedef MEDCoupling::DataArrayInt64 MCType; +}; + +template<> +class MEDFileVTKTraits +{ +public: + typedef vtkFloatArray VtkType; + typedef MEDCoupling::DataArrayFloat MCType; +}; + +template<> +class MEDFileVTKTraits +{ +public: + typedef vtkDoubleArray VtkType; + typedef MEDCoupling::DataArrayDouble MCType; +}; + +#endif diff --git a/src/Plugins/DevelopedSurface/plugin/DevelopedSurfaceModule/VTKToMEDMem.cxx b/src/Plugins/DevelopedSurface/plugin/DevelopedSurfaceModule/VTKToMEDMem.cxx new file mode 100644 index 00000000..3a0cb639 --- /dev/null +++ b/src/Plugins/DevelopedSurface/plugin/DevelopedSurfaceModule/VTKToMEDMem.cxx @@ -0,0 +1,950 @@ +// Copyright (C) 2017-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay (EDF R&D) + +#include "VTKToMEDMem.h" + +#include "vtkAdjacentVertexIterator.h" +#include "vtkIntArray.h" +#include "vtkLongArray.h" +#include "vtkCellData.h" +#include "vtkPointData.h" +#include "vtkFloatArray.h" +#include "vtkCellArray.h" + +#include "vtkStreamingDemandDrivenPipeline.h" +#include "vtkInformationDataObjectMetaDataKey.h" +#include "vtkUnstructuredGrid.h" +#include "vtkMultiBlockDataSet.h" +#include "vtkRectilinearGrid.h" +#include "vtkInformationStringKey.h" +#include "vtkAlgorithmOutput.h" +#include "vtkObjectFactory.h" +#include "vtkMutableDirectedGraph.h" +#include "vtkMultiBlockDataSet.h" +#include "vtkPolyData.h" +#include "vtkDataSet.h" +#include "vtkInformationVector.h" +#include "vtkInformation.h" +#include "vtkDataArraySelection.h" +#include "vtkTimeStamp.h" +#include "vtkInEdgeIterator.h" +#include "vtkInformationDataObjectKey.h" +#include "vtkExecutive.h" +#include "vtkVariantArray.h" +#include "vtkStringArray.h" +#include "vtkDoubleArray.h" +#include "vtkCharArray.h" +#include "vtkUnsignedCharArray.h" +#include "vtkDataSetAttributes.h" +#include "vtkDemandDrivenPipeline.h" +#include "vtkDataObjectTreeIterator.h" +#include "vtkWarpScalar.h" + +#include +#include +#include +#include + +using VTKToMEDMem::Grp; +using VTKToMEDMem::Fam; + +using MEDCoupling::MEDFileData; +using MEDCoupling::MEDFileMesh; +using MEDCoupling::MEDFileCMesh; +using MEDCoupling::MEDFileUMesh; +using MEDCoupling::MEDFileFields; +using MEDCoupling::MEDFileMeshes; + +using MEDCoupling::MEDFileIntField1TS; +using MEDCoupling::MEDFileField1TS; +using MEDCoupling::MEDFileIntFieldMultiTS; +using MEDCoupling::MEDFileFieldMultiTS; +using MEDCoupling::MEDFileAnyTypeFieldMultiTS; +using MEDCoupling::DataArray; +using MEDCoupling::DataArrayInt32; +using MEDCoupling::DataArrayInt64; +using MEDCoupling::DataArrayFloat; +using MEDCoupling::DataArrayDouble; +using MEDCoupling::MEDCouplingMesh; +using MEDCoupling::MEDCouplingUMesh; +using MEDCoupling::MEDCouplingCMesh; +using MEDCoupling::MEDCouplingFieldDouble; +using MEDCoupling::MEDCouplingFieldFloat; +using MEDCoupling::MEDCouplingFieldInt; +using MEDCoupling::MCAuto; +using MEDCoupling::Traits; +using MEDCoupling::MLFieldTraits; + +/////////////////// + +Fam::Fam(const std::string& name) +{ + static const char ZE_SEP[]="@@][@@"; + std::size_t pos(name.find(ZE_SEP)); + std::string name0(name.substr(0,pos)),name1(name.substr(pos+strlen(ZE_SEP))); + std::istringstream iss(name1); + iss >> _id; + _name=name0; +} + +/////////////////// + +#include "VTKMEDTraits.hxx" + +std::map ComputeMapOfType() +{ + std::map ret; + int nbOfTypesInMC(sizeof(MEDCOUPLING2VTKTYPETRADUCER)/sizeof( decltype(MEDCOUPLING2VTKTYPETRADUCER[0]) )); + for(int i=0;i& context) +{ + static const char DFT_MESH_NAME[]="Mesh"; + if(context.empty()) + return DFT_MESH_NAME; + std::ostringstream oss; oss << DFT_MESH_NAME; + for(std::vector::const_iterator it=context.begin();it!=context.end();it++) + oss << "_" << *it; + return oss.str(); +} + +DataArrayIdType *ConvertVTKArrayToMCArrayInt(vtkDataArray *data) +{ + if(!data) + throw MZCException("ConvertVTKArrayToMCArrayInt : internal error !"); + int nbTuples(data->GetNumberOfTuples()),nbComp(data->GetNumberOfComponents()); + std::size_t nbElts(nbTuples*nbComp); + MCAuto ret(DataArrayIdType::New()); + ret->alloc(nbTuples,nbComp); + for(int i=0;iGetComponentName(i)); + if(comp) + ret->setInfoOnComponent(i,comp); + } + mcIdType *ptOut(ret->getPointer()); + vtkIntArray *d0(vtkIntArray::SafeDownCast(data)); + if(d0) + { + const int *pt(d0->GetPointer(0)); + std::copy(pt,pt+nbElts,ptOut); + return ret.retn(); + } + vtkLongArray *d1(vtkLongArray::SafeDownCast(data)); + if(d1) + { + const long *pt(d1->GetPointer(0)); + std::copy(pt,pt+nbElts,ptOut); + return ret.retn(); + } + vtkUnsignedCharArray *d2(vtkUnsignedCharArray::SafeDownCast(data)); + if(d2) + { + const unsigned char *pt(d2->GetPointer(0)); + std::copy(pt,pt+nbElts,ptOut); + return ret.retn(); + } + std::ostringstream oss; + oss << "ConvertVTKArrayToMCArrayInt : unrecognized array \"" << typeid(*data).name() << "\" type !"; + throw MZCException(oss.str()); +} + +template +typename Traits::ArrayType *ConvertVTKArrayToMCArrayDouble(vtkDataArray *data) +{ + if(!data) + throw MZCException("ConvertVTKArrayToMCArrayDouble : internal error !"); + int nbTuples(data->GetNumberOfTuples()),nbComp(data->GetNumberOfComponents()); + std::size_t nbElts(nbTuples*nbComp); + MCAuto< typename Traits::ArrayType > ret(Traits::ArrayType::New()); + ret->alloc(nbTuples,nbComp); + for(int i=0;iGetComponentName(i)); + if(comp) + ret->setInfoOnComponent(i,comp); + else + { + if(nbComp>1 && nbComp<=3) + { + char tmp[2]; + tmp[0]=(char)('X'+i); tmp[1]='\0'; + ret->setInfoOnComponent(i,tmp); + } + } + } + T *ptOut(ret->getPointer()); + typename MEDFileVTKTraits::VtkType *d0(MEDFileVTKTraits::VtkType::SafeDownCast(data)); + if(d0) + { + const T *pt(d0->GetPointer(0)); + for(std::size_t i=0;iGetClassName() << "\" type !"; + throw MZCException(oss.str()); +} + +DataArrayDouble *ConvertVTKArrayToMCArrayDoubleForced(vtkDataArray *data) +{ + if(!data) + throw MZCException("ConvertVTKArrayToMCArrayDoubleForced : internal error 0 !"); + vtkFloatArray *d0(vtkFloatArray::SafeDownCast(data)); + if(d0) + { + MCAuto ret(ConvertVTKArrayToMCArrayDouble(data)); + MCAuto ret2(ret->convertToDblArr()); + return ret2.retn(); + } + vtkDoubleArray *d1(vtkDoubleArray::SafeDownCast(data)); + if(d1) + return ConvertVTKArrayToMCArrayDouble(data); + throw MZCException("ConvertVTKArrayToMCArrayDoubleForced : unrecognized type of data for double !"); +} + +DataArray *ConvertVTKArrayToMCArray(vtkDataArray *data) +{ + if(!data) + throw MZCException("ConvertVTKArrayToMCArray : internal error !"); + vtkFloatArray *d0(vtkFloatArray::SafeDownCast(data)); + if(d0) + return ConvertVTKArrayToMCArrayDouble(data); + vtkDoubleArray *d1(vtkDoubleArray::SafeDownCast(data)); + if(d1) + return ConvertVTKArrayToMCArrayDouble(data); + vtkIntArray *d2(vtkIntArray::SafeDownCast(data)); + vtkLongArray *d3(vtkLongArray::SafeDownCast(data)); + vtkUnsignedCharArray *d4(vtkUnsignedCharArray::SafeDownCast(data)); + if(d2 || d3 || d4) + return ConvertVTKArrayToMCArrayInt(data); + std::ostringstream oss; + oss << "ConvertVTKArrayToMCArray : unrecognized array \"" << typeid(*data).name() << "\" type !"; + throw MZCException(oss.str()); +} + +MEDCouplingUMesh *BuildMeshFromCellArray(vtkCellArray *ca, DataArrayDouble *coords, int meshDim, INTERP_KERNEL::NormalizedCellType type) +{ + MCAuto subMesh(MEDCouplingUMesh::New("",meshDim)); + subMesh->setCoords(coords); subMesh->allocateCells(); + int nbCells(ca->GetNumberOfCells()); + if(nbCells==0) + return 0; + vtkIdType nbEntries(ca->GetNumberOfConnectivityEntries()); + const vtkIdType *conn(ca->GetData()->GetPointer(0)); + for(int i=0;i conn2(sz); + for(int jj=0;jjinsertNextCell(type,sz,&conn2[0]); + conn+=sz; + } + return subMesh.retn(); +} + +MEDCouplingUMesh *BuildMeshFromCellArrayTriangleStrip(vtkCellArray *ca, DataArrayDouble *coords, MCAuto& ids) +{ + MCAuto subMesh(MEDCouplingUMesh::New("",2)); + subMesh->setCoords(coords); subMesh->allocateCells(); + int nbCells(ca->GetNumberOfCells()); + if(nbCells==0) + return 0; + vtkIdType nbEntries(ca->GetNumberOfConnectivityEntries()); + const vtkIdType *conn(ca->GetData()->GetPointer(0)); + ids=DataArrayIdType::New() ; ids->alloc(0,1); + for(int i=0;i0) + { + for(int j=0;jinsertNextCell(INTERP_KERNEL::NORM_TRI3,3,conn2); + ids->pushBackSilent(i); + } + } + else + { + std::ostringstream oss; oss << "BuildMeshFromCellArrayTriangleStrip : on cell #" << i << " the triangle stip looks bab !"; + throw MZCException(oss.str()); + } + conn+=sz; + } + return subMesh.retn(); +} + +class MicroField +{ +public: + MicroField(const MCAuto& m, const std::vector >& cellFs):_m(m),_cellFs(cellFs) { } + MicroField(const std::vector< MicroField >& vs); + void setNodeFields(const std::vector >& nf) { _nodeFs=nf; } + MCAuto getMesh() const { return _m; } + std::vector > getCellFields() const { return _cellFs; } +private: + MCAuto _m; + std::vector > _cellFs; + std::vector > _nodeFs; +}; + +MicroField::MicroField(const std::vector< MicroField >& vs) +{ + std::size_t sz(vs.size()); + std::vector vs2(sz); + std::vector< std::vector< MCAuto > > arrs2(sz); + int nbElts(-1); + for(std::size_t ii=0;ii arrsTmp(sz); + for(std::size_t jj=0;jj +void AppendToFields(MEDCoupling::TypeOfField tf, MEDCouplingMesh *mesh, const DataArrayIdType *n2oPtr, typename MEDFileVTKTraits::MCType *dadPtr, MEDFileFields *fs, double timeStep, int tsId) +{ + std::string fieldName(dadPtr->getName()); + MCAuto< typename Traits::FieldType > f(Traits::FieldType::New(tf)); + f->setTime(timeStep,tsId,0); + { + std::string fieldNameForChuckNorris(MEDCoupling::MEDFileAnyTypeField1TSWithoutSDA::FieldNameToMEDFileConvention(fieldName)); + f->setName(fieldNameForChuckNorris); + } + if(!n2oPtr) + f->setArray(dadPtr); + else + { + MCAuto< typename Traits::ArrayType > dad2(dadPtr->selectByTupleId(n2oPtr->begin(),n2oPtr->end())); + f->setArray(dad2); + } + f->setMesh(mesh); + MCAuto< typename MLFieldTraits::FMTSType > fmts(MLFieldTraits::FMTSType::New()); + MCAuto< typename MLFieldTraits::F1TSType > f1ts(MLFieldTraits::F1TSType::New()); + f1ts->setFieldNoProfileSBT(f); + fmts->pushBackTimeStep(f1ts); + fs->pushField(fmts); +} + +void AppendMCFieldFrom(MEDCoupling::TypeOfField tf, MEDCouplingMesh *mesh, MEDFileData *mfd, MCAuto da, const DataArrayIdType *n2oPtr, double timeStep, int tsId) +{ + static const char FAMFIELD_FOR_CELLS[]="FamilyIdCell"; + static const char FAMFIELD_FOR_NODES[]="FamilyIdNode"; + if(!da || !mesh || !mfd) + throw MZCException("AppendMCFieldFrom : internal error !"); + MEDFileFields *fs(mfd->getFields()); + MEDFileMeshes *ms(mfd->getMeshes()); + if(!fs || !ms) + throw MZCException("AppendMCFieldFrom : internal error 2 !"); + MCAuto dad(MEDCoupling::DynamicCast(da)); + if(dad.isNotNull()) + { + AppendToFields(tf,mesh,n2oPtr,dad,fs,timeStep,tsId); + return ; + } + MCAuto daf(MEDCoupling::DynamicCast(da)); + if(daf.isNotNull()) + { + AppendToFields(tf,mesh,n2oPtr,daf,fs,timeStep,tsId); + return ; + } + MCAuto dai(MEDCoupling::DynamicCast(da)); + MCAuto daId(MEDCoupling::DynamicCast(da)); + if(dai.isNotNull() || daId.isNotNull()) + { + std::string fieldName(dai->getName()); + if((fieldName!=FAMFIELD_FOR_CELLS || tf!=MEDCoupling::ON_CELLS) && (fieldName!=FAMFIELD_FOR_NODES || tf!=MEDCoupling::ON_NODES)) + { + if(!dai) + throw MZCException("AppendMCFieldFrom : internal error 3 (not int32) !"); + AppendToFields(tf,mesh,n2oPtr,dai,fs,timeStep,tsId); + return ; + } + else if(fieldName==FAMFIELD_FOR_CELLS && tf==MEDCoupling::ON_CELLS) + { + MEDFileMesh *mm(ms->getMeshWithName(mesh->getName())); + if(!mm) + throw MZCException("AppendMCFieldFrom : internal error 3 !"); + if(!daId) + throw MZCException("AppendMCFieldFrom : internal error 3 (not mcIdType) !"); + if(!n2oPtr) + mm->setFamilyFieldArr(mesh->getMeshDimension()-mm->getMeshDimension(),daId); + else + { + MCAuto dai2(daId->selectByTupleId(n2oPtr->begin(),n2oPtr->end())); + mm->setFamilyFieldArr(mesh->getMeshDimension()-mm->getMeshDimension(),dai2); + } + } + else if(fieldName==FAMFIELD_FOR_NODES || tf==MEDCoupling::ON_NODES) + { + MEDFileMesh *mm(ms->getMeshWithName(mesh->getName())); + if(!mm) + throw MZCException("AppendMCFieldFrom : internal error 4 !"); + if(!daId) + throw MZCException("AppendMCFieldFrom : internal error 4 (not mcIdType) !"); + if(!n2oPtr) + mm->setFamilyFieldArr(1,daId); + else + { + MCAuto dai2(daId->selectByTupleId(n2oPtr->begin(),n2oPtr->end())); + mm->setFamilyFieldArr(1,dai2); + } + } + } +} + +void PutAtLevelDealOrder(MEDFileData *mfd, int meshDimRel, const MicroField& mf, double timeStep, int tsId) +{ + if(!mfd) + throw MZCException("PutAtLevelDealOrder : internal error !"); + MEDFileMesh *mm(mfd->getMeshes()->getMeshAtPos(0)); + MEDFileUMesh *mmu(dynamic_cast(mm)); + if(!mmu) + throw MZCException("PutAtLevelDealOrder : internal error 2 !"); + MCAuto mesh(mf.getMesh()); + mesh->setName(mfd->getMeshes()->getMeshAtPos(0)->getName()); + MCAuto o2n(mesh->sortCellsInMEDFileFrmt()); + const DataArrayIdType *o2nPtr(o2n); + MCAuto n2o; + mmu->setMeshAtLevel(meshDimRel,mesh); + const DataArrayIdType *n2oPtr(0); + if(o2n) + { + n2o=o2n->invertArrayO2N2N2O(mesh->getNumberOfCells()); + n2oPtr=n2o; + if(n2oPtr && n2oPtr->isIota(mesh->getNumberOfCells())) + n2oPtr=0; + if(n2oPtr) + mm->setRenumFieldArr(meshDimRel,n2o); + } + // + std::vector > cells(mf.getCellFields()); + for(std::vector >::const_iterator it=cells.begin();it!=cells.end();it++) + { + MCAuto da(*it); + AppendMCFieldFrom(MEDCoupling::ON_CELLS,mesh,mfd,da,n2oPtr,timeStep,tsId); + } +} + +void AssignSingleGTMeshes(MEDFileData *mfd, const std::vector< MicroField >& ms, double timeStep, int tsId) +{ + if(!mfd) + throw MZCException("AssignSingleGTMeshes : internal error !"); + MEDFileMesh *mm0(mfd->getMeshes()->getMeshAtPos(0)); + MEDFileUMesh *mm(dynamic_cast(mm0)); + if(!mm) + throw MZCException("AssignSingleGTMeshes : internal error 2 !"); + int meshDim(-std::numeric_limits::max()); + std::map > ms2; + for(std::vector< MicroField >::const_iterator it=ms.begin();it!=ms.end();it++) + { + const MEDCouplingUMesh *elt((*it).getMesh()); + if(elt) + { + int myMeshDim(elt->getMeshDimension()); + meshDim=std::max(meshDim,myMeshDim); + ms2[myMeshDim].push_back(*it); + } + } + if(ms2.empty()) + return ; + for(std::map >::const_iterator it=ms2.begin();it!=ms2.end();it++) + { + const std::vector< MicroField >& vs((*it).second); + if(vs.size()==1) + { + PutAtLevelDealOrder(mfd,(*it).first-meshDim,vs[0],timeStep,tsId); + } + else + { + MicroField merge(vs); + PutAtLevelDealOrder(mfd,(*it).first-meshDim,merge,timeStep,tsId); + } + } +} + +DataArrayDouble *BuildCoordsFrom(vtkPointSet *ds) +{ + if(!ds) + throw MZCException("BuildCoordsFrom : internal error !"); + vtkPoints *pts(ds->GetPoints()); + if(!pts) + throw MZCException("BuildCoordsFrom : internal error 2 !"); + vtkDataArray *data(pts->GetData()); + if(!data) + throw MZCException("BuildCoordsFrom : internal error 3 !"); + return ConvertVTKArrayToMCArrayDoubleForced(data); +} + +void AddNodeFields(MEDFileData *mfd, vtkDataSetAttributes *dsa, double timeStep, int tsId) +{ + if(!mfd || !dsa) + throw MZCException("AddNodeFields : internal error !"); + MEDFileMesh *mm(mfd->getMeshes()->getMeshAtPos(0)); + MEDFileUMesh *mmu(dynamic_cast(mm)); + if(!mmu) + throw MZCException("AddNodeFields : internal error 2 !"); + MCAuto mesh; + if(!mmu->getNonEmptyLevels().empty()) + mesh=mmu->getMeshAtLevel(0); + else + { + mesh=MEDCouplingUMesh::Build0DMeshFromCoords(mmu->getCoords()); + mesh->setName(mmu->getName()); + } + int nba(dsa->GetNumberOfArrays()); + for(int i=0;iGetArray(i)); + const char *name(arr->GetName()); + if(!arr) + continue; + MCAuto da(ConvertVTKArrayToMCArray(arr)); + da->setName(name); + AppendMCFieldFrom(MEDCoupling::ON_NODES,mesh,mfd,da,NULL,timeStep,tsId); + } +} + +std::vector > AddPartFields(const DataArrayIdType *part, vtkDataSetAttributes *dsa) +{ + std::vector< MCAuto > ret; + if(!dsa) + return ret; + int nba(dsa->GetNumberOfArrays()); + for(int i=0;iGetArray(i)); + if(!arr) + continue; + const char *name(arr->GetName()); + int nbCompo(arr->GetNumberOfComponents()); + vtkIdType nbTuples(arr->GetNumberOfTuples()); + MCAuto mcarr(ConvertVTKArrayToMCArray(arr)); + if(part) + mcarr=mcarr->selectByTupleId(part->begin(),part->end()); + mcarr->setName(name); + ret.push_back(mcarr); + } + return ret; +} + +std::vector > AddPartFields2(int bg, int end, vtkDataSetAttributes *dsa) +{ + std::vector< MCAuto > ret; + if(!dsa) + return ret; + int nba(dsa->GetNumberOfArrays()); + for(int i=0;iGetArray(i)); + if(!arr) + continue; + const char *name(arr->GetName()); + int nbCompo(arr->GetNumberOfComponents()); + vtkIdType nbTuples(arr->GetNumberOfTuples()); + MCAuto mcarr(ConvertVTKArrayToMCArray(arr)); + mcarr=mcarr->selectByTupleIdSafeSlice(bg,end,1); + mcarr->setName(name); + ret.push_back(mcarr); + } + return ret; +} + +void ConvertFromRectilinearGrid(MEDFileData *ret, vtkRectilinearGrid *ds, const std::vector& context, double timeStep, int tsId) +{ + if(!ds || !ret) + throw MZCException("ConvertFromRectilinearGrid : internal error !"); + // + MCAuto meshes(MEDFileMeshes::New()); + ret->setMeshes(meshes); + MCAuto fields(MEDFileFields::New()); + ret->setFields(fields); + // + MCAuto cmesh(MEDFileCMesh::New()); + meshes->pushMesh(cmesh); + MCAuto cmeshmc(MEDCouplingCMesh::New()); + vtkDataArray *cx(ds->GetXCoordinates()),*cy(ds->GetYCoordinates()),*cz(ds->GetZCoordinates()); + if(cx) + { + MCAuto arr(ConvertVTKArrayToMCArrayDoubleForced(cx)); + cmeshmc->setCoordsAt(0,arr); + } + if(cy) + { + MCAuto arr(ConvertVTKArrayToMCArrayDoubleForced(cy)); + cmeshmc->setCoordsAt(1,arr); + } + if(cz) + { + MCAuto arr(ConvertVTKArrayToMCArrayDoubleForced(cz)); + cmeshmc->setCoordsAt(2,arr); + } + std::string meshName(GetMeshNameWithContext(context)); + cmeshmc->setName(meshName); + cmesh->setMesh(cmeshmc); + std::vector > cellFs(AddPartFields(0,ds->GetCellData())); + for(std::vector >::const_iterator it=cellFs.begin();it!=cellFs.end();it++) + { + MCAuto da(*it); + AppendMCFieldFrom(MEDCoupling::ON_CELLS,cmeshmc,ret,da,NULL,timeStep,tsId); + } + std::vector > nodeFs(AddPartFields(0,ds->GetPointData())); + for(std::vector >::const_iterator it=nodeFs.begin();it!=nodeFs.end();it++) + { + MCAuto da(*it); + AppendMCFieldFrom(MEDCoupling::ON_NODES,cmeshmc,ret,da,NULL,timeStep,tsId); + } +} + +void ConvertFromPolyData(MEDFileData *ret, vtkPolyData *ds, const std::vector& context, double timeStep, int tsId) +{ + if(!ds || !ret) + throw MZCException("ConvertFromPolyData : internal error !"); + // + MCAuto meshes(MEDFileMeshes::New()); + ret->setMeshes(meshes); + MCAuto fields(MEDFileFields::New()); + ret->setFields(fields); + // + MCAuto umesh(MEDFileUMesh::New()); + meshes->pushMesh(umesh); + MCAuto coords(BuildCoordsFrom(ds)); + umesh->setCoords(coords); + umesh->setName(GetMeshNameWithContext(context)); + // + int offset(0); + std::vector< MicroField > ms; + vtkCellArray *cd(ds->GetVerts()); + if(cd) + { + MCAuto subMesh(BuildMeshFromCellArray(cd,coords,0,INTERP_KERNEL::NORM_POINT1)); + if((const MEDCouplingUMesh *)subMesh) + { + std::vector > cellFs(AddPartFields2(offset,offset+subMesh->getNumberOfCells(),ds->GetCellData())); + offset+=subMesh->getNumberOfCells(); + ms.push_back(MicroField(subMesh,cellFs)); + } + } + vtkCellArray *cc(ds->GetLines()); + if(cc) + { + MCAuto subMesh; + try + { + subMesh=BuildMeshFromCellArray(cc,coords,1,INTERP_KERNEL::NORM_SEG2); + } + catch(INTERP_KERNEL::Exception& e) + { + std::ostringstream oss; oss << "MEDWriter does not manage polyline cell type because MED file format does not support it ! Maybe it is the source of the problem ? The cause of this exception was " << e.what() << std::endl; + throw INTERP_KERNEL::Exception(oss.str()); + } + if((const MEDCouplingUMesh *)subMesh) + { + std::vector > cellFs(AddPartFields2(offset,offset+subMesh->getNumberOfCells(),ds->GetCellData())); + offset+=subMesh->getNumberOfCells(); + ms.push_back(MicroField(subMesh,cellFs)); + } + } + vtkCellArray *cb(ds->GetPolys()); + if(cb) + { + MCAuto subMesh(BuildMeshFromCellArray(cb,coords,2,INTERP_KERNEL::NORM_POLYGON)); + if((const MEDCouplingUMesh *)subMesh) + { + std::vector > cellFs(AddPartFields2(offset,offset+subMesh->getNumberOfCells(),ds->GetCellData())); + offset+=subMesh->getNumberOfCells(); + ms.push_back(MicroField(subMesh,cellFs)); + } + } + vtkCellArray *ca(ds->GetStrips()); + if(ca) + { + MCAuto ids; + MCAuto subMesh(BuildMeshFromCellArrayTriangleStrip(ca,coords,ids)); + if((const MEDCouplingUMesh *)subMesh) + { + std::vector > cellFs(AddPartFields(ids,ds->GetCellData())); + offset+=subMesh->getNumberOfCells(); + ms.push_back(MicroField(subMesh,cellFs)); + } + } + AssignSingleGTMeshes(ret,ms,timeStep,tsId); + AddNodeFields(ret,ds->GetPointData(),timeStep,tsId); +} + +void ConvertFromUnstructuredGrid(MEDFileData *ret, vtkUnstructuredGrid *ds, const std::vector& context, double timeStep, int tsId) +{ + if(!ds || !ret) + throw MZCException("ConvertFromUnstructuredGrid : internal error !"); + // + MCAuto meshes(MEDFileMeshes::New()); + ret->setMeshes(meshes); + MCAuto fields(MEDFileFields::New()); + ret->setFields(fields); + // + MCAuto umesh(MEDFileUMesh::New()); + meshes->pushMesh(umesh); + MCAuto coords(BuildCoordsFrom(ds)); + umesh->setCoords(coords); + umesh->setName(GetMeshNameWithContext(context)); + vtkIdType nbCells(ds->GetNumberOfCells()); + vtkCellArray *ca(ds->GetCells()); + if(!ca) + return ; + vtkIdType nbEnt(ca->GetNumberOfConnectivityEntries()); + vtkIdType *caPtr(ca->GetData()->GetPointer(0)); + vtkUnsignedCharArray *ct(ds->GetCellTypesArray()); + if(!ct) + throw MZCException("ConvertFromUnstructuredGrid : internal error"); + vtkIdTypeArray *cla(ds->GetCellLocationsArray()); + const vtkIdType *claPtr(cla->GetPointer(0)); + if(!cla) + throw MZCException("ConvertFromUnstructuredGrid : internal error 2"); + const unsigned char *ctPtr(ct->GetPointer(0)); + std::map m(ComputeMapOfType()); + MCAuto lev(DataArrayInt::New()) ; lev->alloc(nbCells,1); + int *levPtr(lev->getPointer()); + for(vtkIdType i=0;i::iterator it(m.find(ctPtr[i])); + if(it!=m.end()) + { + const INTERP_KERNEL::CellModel& cm(INTERP_KERNEL::CellModel::GetCellModel((INTERP_KERNEL::NormalizedCellType)(*it).second)); + levPtr[i]=cm.getDimension(); + } + else + { + if(ctPtr[i]==VTK_POLY_VERTEX) + { + const INTERP_KERNEL::CellModel& cm(INTERP_KERNEL::CellModel::GetCellModel(INTERP_KERNEL::NORM_POINT1)); + levPtr[i]=cm.getDimension(); + } + else + { + std::ostringstream oss; oss << "ConvertFromUnstructuredGrid : at pos #" << i << " unrecognized VTK cell with type =" << ctPtr[i]; + throw MZCException(oss.str()); + } + } + } + int dummy(0); + MCAuto levs(lev->getDifferentValues()); + std::vector< MicroField > ms; + vtkIdTypeArray *faces(ds->GetFaces()),*faceLoc(ds->GetFaceLocations()); + for(const int *curLev=levs->begin();curLev!=levs->end();curLev++) + { + MCAuto m0(MEDCouplingUMesh::New("",*curLev)); + m0->setCoords(coords); m0->allocateCells(); + MCAuto cellIdsCurLev(lev->findIdsEqual(*curLev)); + for(const mcIdType *cellId=cellIdsCurLev->begin();cellId!=cellIdsCurLev->end();cellId++) + { + int vtkType(ctPtr[*cellId]); + std::map::iterator it(m.find(vtkType)); + vtkIdType offset(claPtr[*cellId]); + vtkIdType sz(caPtr[offset]); + INTERP_KERNEL::NormalizedCellType ct=it!=m.end()?(INTERP_KERNEL::NormalizedCellType)((*it).second):INTERP_KERNEL::NORM_POINT1; + if(ct!=INTERP_KERNEL::NORM_POLYHED && vtkType!=VTK_POLY_VERTEX) + { + std::vector conn2(sz); + for(int kk=0;kkinsertNextCell(ct,sz,&conn2[0]); + } + else if(ct==INTERP_KERNEL::NORM_POLYHED) + { + if(!faces || !faceLoc) + throw MZCException("ConvertFromUnstructuredGrid : faces are expected when there are polyhedra !"); + const vtkIdType *facPtr(faces->GetPointer(0)),*facLocPtr(faceLoc->GetPointer(0)); + std::vector conn; + int off0(facLocPtr[*cellId]); + int nbOfFaces(facPtr[off0++]); + for(int k=0;kinsertNextCell(ct,ToIdType(conn.size()),&conn[0]); + } + else + { + if(sz!=1) + throw MZCException("ConvertFromUnstructuredGrid : non single poly vertex not managed by MED !"); + m0->insertNextCell(ct,1,(const mcIdType*)(caPtr+offset+1)); + } + } + std::vector > cellFs(AddPartFields(cellIdsCurLev,ds->GetCellData())); + ms.push_back(MicroField(m0,cellFs)); + } + AssignSingleGTMeshes(ret,ms,timeStep,tsId); + AddNodeFields(ret,ds->GetPointData(),timeStep,tsId); +} + +/////////////////// + +void WriteMEDFileFromVTKDataSet(MEDFileData *mfd, vtkDataSet *ds, const std::vector& context, double timeStep, int tsId) +{ + if(!ds || !mfd) + throw MZCException("Internal error in WriteMEDFileFromVTKDataSet."); + vtkPolyData *ds2(vtkPolyData::SafeDownCast(ds)); + vtkUnstructuredGrid *ds3(vtkUnstructuredGrid::SafeDownCast(ds)); + vtkRectilinearGrid *ds4(vtkRectilinearGrid::SafeDownCast(ds)); + if(ds2) + { + ConvertFromPolyData(mfd,ds2,context,timeStep,tsId); + } + else if(ds3) + { + ConvertFromUnstructuredGrid(mfd,ds3,context,timeStep,tsId); + } + else if(ds4) + { + ConvertFromRectilinearGrid(mfd,ds4,context,timeStep,tsId); + } + else + throw MZCException("Unrecognized vtkDataSet ! Sorry ! Try to convert it to UnstructuredGrid to be able to write it !"); +} + +void WriteMEDFileFromVTKMultiBlock(MEDFileData *mfd, vtkMultiBlockDataSet *ds, const std::vector& context, double timeStep, int tsId) +{ + if(!ds || !mfd) + throw MZCException("Internal error in WriteMEDFileFromVTKMultiBlock."); + int nbBlocks(ds->GetNumberOfBlocks()); + if(nbBlocks==1 && context.empty()) + { + vtkDataObject *uniqueElt(ds->GetBlock(0)); + if(!uniqueElt) + throw MZCException("Unique elt in multiblock is NULL !"); + vtkDataSet *uniqueEltc(vtkDataSet::SafeDownCast(uniqueElt)); + if(uniqueEltc) + { + WriteMEDFileFromVTKDataSet(mfd,uniqueEltc,context,timeStep,tsId); + return ; + } + } + for(int i=0;iGetBlock(i)); + std::vector context2; + context2.push_back(i); + if(!elt) + { + std::ostringstream oss; oss << "In context "; + std::copy(context.begin(),context.end(),std::ostream_iterator(oss," ")); + oss << " at pos #" << i << " elt is NULL !"; + throw MZCException(oss.str()); + } + vtkDataSet *elt1(vtkDataSet::SafeDownCast(elt)); + if(elt1) + { + WriteMEDFileFromVTKDataSet(mfd,elt1,context,timeStep,tsId); + continue; + } + vtkMultiBlockDataSet *elt2(vtkMultiBlockDataSet::SafeDownCast(elt)); + if(elt2) + { + WriteMEDFileFromVTKMultiBlock(mfd,elt2,context,timeStep,tsId); + continue; + } + std::ostringstream oss; oss << "In context "; + std::copy(context.begin(),context.end(),std::ostream_iterator(oss," ")); + oss << " at pos #" << i << " elt not recognized data type !"; + throw MZCException(oss.str()); + } +} + +void WriteMEDFileFromVTKGDS(MEDFileData *mfd, vtkDataObject *input, double timeStep, int tsId) +{ + if(!input || !mfd) + throw MZCException("WriteMEDFileFromVTKGDS : internal error !"); + std::vector context; + vtkDataSet *input1(vtkDataSet::SafeDownCast(input)); + if(input1) + { + WriteMEDFileFromVTKDataSet(mfd,input1,context,timeStep,tsId); + return ; + } + vtkMultiBlockDataSet *input2(vtkMultiBlockDataSet::SafeDownCast(input)); + if(input2) + { + WriteMEDFileFromVTKMultiBlock(mfd,input2,context,timeStep,tsId); + return ; + } + throw MZCException("WriteMEDFileFromVTKGDS : not recognized data type !"); +} + +void PutFamGrpInfoIfAny(MEDFileData *mfd, const std::string& meshName, const std::vector& groups, const std::vector& fams) +{ + if(!mfd) + return ; + if(meshName.empty()) + return ; + MEDFileMeshes *meshes(mfd->getMeshes()); + if(!meshes) + return ; + if(meshes->getNumberOfMeshes()!=1) + return ; + MEDFileMesh *mm(meshes->getMeshAtPos(0)); + if(!mm) + return ; + mm->setName(meshName); + for(std::vector::const_iterator it=fams.begin();it!=fams.end();it++) + mm->setFamilyId((*it).getName(),(*it).getID()); + for(std::vector::const_iterator it=groups.begin();it!=groups.end();it++) + mm->setFamiliesOnGroup((*it).getName(),(*it).getFamilies()); + MEDFileFields *fields(mfd->getFields()); + if(!fields) + return ; + for(int i=0;igetNumberOfFields();i++) + { + MEDFileAnyTypeFieldMultiTS *fmts(fields->getFieldAtPos(i)); + if(!fmts) + continue; + fmts->setMeshName(meshName); + } +} diff --git a/src/Plugins/DevelopedSurface/plugin/DevelopedSurfaceModule/VTKToMEDMem.h b/src/Plugins/DevelopedSurface/plugin/DevelopedSurfaceModule/VTKToMEDMem.h new file mode 100644 index 00000000..6f36d77f --- /dev/null +++ b/src/Plugins/DevelopedSurface/plugin/DevelopedSurfaceModule/VTKToMEDMem.h @@ -0,0 +1,88 @@ +// Copyright (C) 2017-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay (EDF R&D) + +#ifndef __VTKTOMEDMEM_HXX__ +#define __VTKTOMEDMEM_HXX__ + +#include "vtkSystemIncludes.h" //needed for exports + +#include "MEDCouplingRefCountObject.hxx" +#include "MEDCouplingMemArray.hxx" +#include "MEDCouplingFieldDouble.hxx" +#include "MEDCouplingFieldFloat.hxx" +#include "MEDCouplingFieldInt.hxx" +#include "MEDFileData.hxx" +#include "MEDFileField.hxx" +#include "MEDFileMesh.hxx" +#include "MEDLoaderTraits.hxx" + +#include +#include + +/////////////////// + +class vtkDataSet; + +class VTK_EXPORT MZCException : public std::exception +{ +public: + MZCException(const std::string& s):_reason(s) { } + virtual const char *what() const throw() { return _reason.c_str(); } + virtual ~MZCException() throw() { } +private: + std::string _reason; +}; + +namespace VTKToMEDMem +{ + class VTK_EXPORT Grp + { + public: + Grp(const std::string& name):_name(name) { } + void setFamilies(const std::vector& fams) { _fams=fams; } + std::string getName() const { return _name; } + std::vector getFamilies() const { return _fams; } + private: + std::string _name; + std::vector _fams; + }; + + class VTK_EXPORT Fam + { + public: + Fam(const std::string& name); + std::string getName() const { return _name; } + int getID() const { return _id; } + private: + std::string _name; + int _id; + }; +} + +class vtkDataObject; + +void VTK_EXPORT WriteMEDFileFromVTKDataSet(MEDCoupling::MEDFileData *mfd, vtkDataSet *ds, const std::vector& context, double timeStep, int tsId); + +void VTK_EXPORT WriteMEDFileFromVTKGDS(MEDCoupling::MEDFileData *mfd, vtkDataObject *input, double timeStep, int tsId); + +void VTK_EXPORT PutFamGrpInfoIfAny(MEDCoupling::MEDFileData *mfd, const std::string& meshName, const std::vector& groups, const std::vector& fams); + +#endif + diff --git a/src/Plugins/DevelopedSurface/plugin/DevelopedSurfaceModule/vtk.module b/src/Plugins/DevelopedSurface/plugin/DevelopedSurfaceModule/vtk.module new file mode 100644 index 00000000..26116c11 --- /dev/null +++ b/src/Plugins/DevelopedSurface/plugin/DevelopedSurfaceModule/vtk.module @@ -0,0 +1,12 @@ +NAME + DevelopedSurfaceModule +DEPENDS + VTK::CommonCore + VTK::CommonDataModel + VTK::CommonExecutionModel + VTK::FiltersCore + VTK::FiltersModeling +PRIVATE_DEPENDS + VTK::CommonMisc + VTK::CommonSystem + VTK::FiltersGeneral diff --git a/src/Plugins/DevelopedSurface/plugin/DevelopedSurfaceModule/vtkDevelopedSurface.cxx b/src/Plugins/DevelopedSurface/plugin/DevelopedSurfaceModule/vtkDevelopedSurface.cxx new file mode 100644 index 00000000..1ae36be5 --- /dev/null +++ b/src/Plugins/DevelopedSurface/plugin/DevelopedSurfaceModule/vtkDevelopedSurface.cxx @@ -0,0 +1,526 @@ +// Copyright (C) 2017-2019 EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay (EDF R&D) + +#include "vtkDevelopedSurface.h" +#include "VTKToMEDMem.h" + +#include "vtkAdjacentVertexIterator.h" +#include "vtkIntArray.h" +#include "vtkLongArray.h" +#include "vtkCellData.h" +#include "vtkPointData.h" +#include "vtkCylinder.h" +#include "vtkNew.h" +#include "vtkCutter.h" +#include "vtkTransform.h" + +#include "vtkStreamingDemandDrivenPipeline.h" +#include "vtkUnstructuredGrid.h" +#include "vtkMultiBlockDataSet.h" + +#include "vtkInformationStringKey.h" +#include "vtkAlgorithmOutput.h" +#include "vtkObjectFactory.h" +#include "vtkMutableDirectedGraph.h" +#include "vtkMultiBlockDataSet.h" +#include "vtkDataSet.h" +#include "vtkInformationVector.h" +#include "vtkInformation.h" +#include "vtkDataArraySelection.h" +#include "vtkTimeStamp.h" +#include "vtkInEdgeIterator.h" +#include "vtkInformationDataObjectKey.h" +#include "vtkExecutive.h" +#include "vtkVariantArray.h" +#include "vtkStringArray.h" +#include "vtkDoubleArray.h" +#include "vtkFloatArray.h" +#include "vtkCharArray.h" +#include "vtkUnsignedCharArray.h" +#include "vtkDataSetAttributes.h" +#include "vtkDemandDrivenPipeline.h" +#include "vtkDataObjectTreeIterator.h" +#include "vtkWarpScalar.h" + +#include "MEDCouplingMemArray.hxx" + +#include "VTKMEDTraits.hxx" + +#ifdef WIN32 +#define _USE_MATH_DEFINES +#endif +#include + +#include +#include +#include +#include + +vtkStandardNewMacro(vtkDevelopedSurface); + +/////////////////// + +template +struct VTKTraits +{ +}; + +template<> +struct VTKTraits +{ + typedef vtkDoubleArray ArrayType; +}; + +template<> +struct VTKTraits +{ + typedef vtkFloatArray ArrayType; +}; + +void ExtractInfo(vtkInformationVector *inputVector, vtkDataSet *& usgIn) +{ + vtkInformation *inputInfo(inputVector->GetInformationObject(0)); + vtkDataSet *input(0); + vtkDataSet *input0(vtkDataSet::SafeDownCast(inputInfo->Get(vtkDataObject::DATA_OBJECT()))); + vtkMultiBlockDataSet *input1(vtkMultiBlockDataSet::SafeDownCast(inputInfo->Get(vtkDataObject::DATA_OBJECT()))); + if(input0) + input=input0; + else + { + if(!input1) + throw MZCException("Input dataSet must be a DataSet or single elt multi block dataset expected !"); + if(input1->GetNumberOfBlocks()!=1) + throw MZCException("Input dataSet is a multiblock dataset with not exactly one block ! Use MergeBlocks or ExtractBlocks filter before calling this filter !"); + vtkDataObject *input2(input1->GetBlock(0)); + if(!input2) + throw MZCException("Input dataSet is a multiblock dataset with exactly one block but this single element is NULL !"); + vtkDataSet *input2c(vtkDataSet::SafeDownCast(input2)); + if(!input2c) + throw MZCException("Input dataSet is a multiblock dataset with exactly one block but this single element is not a dataset ! Use MergeBlocks or ExtractBlocks filter before calling this filter !"); + input=input2c; + } + if(!input) + throw MZCException("Input data set is NULL !"); + vtkPointData *att(input->GetPointData()); + if(!att) + throw MZCException("Input dataset has no point data attribute ! Impossible to deduce a developed surface on it !"); + usgIn=input; +} + +class vtkDevelopedSurface::vtkInternals +{ +public: + vtkNew Cutter; +}; + +//////////////////// + +vtkDevelopedSurface::vtkDevelopedSurface():_cyl(nullptr),Internal(new vtkInternals),InvertStatus(false),OffsetInRad(0.) +{ + //this->RegisterFilter(this->Internal->Cutter.GetPointer()); +} + +vtkDevelopedSurface::~vtkDevelopedSurface() +{ + delete this->Internal; +} + +void vtkDevelopedSurface::SetInvertWay(bool invertStatus) +{ + this->InvertStatus=invertStatus; + this->Modified(); +} + +void vtkDevelopedSurface::SetThetaOffset(double offsetInDegrees) +{ + double tmp(std::min(offsetInDegrees,180.)); + tmp=std::max(tmp,-180.); + this->OffsetInRad=tmp/180.*M_PI; + this->Modified(); +} + +int vtkDevelopedSurface::RequestInformation(vtkInformation *request, vtkInformationVector **inputVector, vtkInformationVector *outputVector) +{ + //std::cerr << "########################################## vtkDevelopedSurface::RequestInformation ##########################################" << std::endl; + try + { + vtkDataSet *usgIn(0); + ExtractInfo(inputVector[0],usgIn); + } + catch(MZCException& e) + { + std::ostringstream oss; + oss << "Exception has been thrown in vtkDevelopedSurface::RequestInformation : " << e.what() << std::endl; + if(this->HasObserver("ErrorEvent") ) + this->InvokeEvent("ErrorEvent",const_cast(oss.str().c_str())); + else + vtkOutputWindowDisplayErrorText(const_cast(oss.str().c_str())); + vtkObject::BreakOnError(); + return 0; + } + return 1; +} + +std::vector UnWrapByDuplicatingNodes(vtkCellArray *ca, vtkIdType& offset, const MEDCoupling::DataArrayDouble *thetas) +{ + std::vector ret; + vtkIdType nbCells(ca->GetNumberOfCells()); + vtkIdType *conn(ca->GetData()->GetPointer(0)); + const double *tptr(thetas->begin()); + for(vtkIdType i=0;i::max()),mi(std::numeric_limits::max()); + for(vtkIdType j=0;jM_PI) + { + for(vtkIdType j=0;j +void DealArray(vtkDataSetAttributes *pd, int pos, typename MEDFileVTKTraits::VtkType *arr, std::vector& nodeSel) +{ + int nbc(arr->GetNumberOfComponents()); + std::size_t nbt(nodeSel.size()); + vtkSmartPointer< typename MEDFileVTKTraits::VtkType > newArr; + newArr.TakeReference(MEDFileVTKTraits::VtkType::New()); + newArr->SetNumberOfComponents(nbc); + newArr->SetNumberOfTuples(nbt); + T *ptr(newArr->GetPointer(0)); + const T *inPtr(arr->GetPointer(0)); + for(std::size_t i=0;iSetName(arr->GetName()); + arr->DeepCopy(newArr); +} + +void ToDouble(vtkDataArray *coords, vtkSmartPointer& coordsOut) +{ + vtkDoubleArray *coords2(vtkDoubleArray::SafeDownCast(coords)); + vtkFloatArray *coords3(vtkFloatArray::SafeDownCast(coords)); + if(!coords2 && !coords3) + throw MZCException("Input coordinates are neither float64 or float32 !"); + // + if(coords2) + { + coordsOut.TakeReference(coords2); + coords2->Register(0); + } + else + { + coordsOut.TakeReference(vtkDoubleArray::New()); + coordsOut->SetNumberOfComponents(3); + vtkIdType nbTuples(coords3->GetNumberOfTuples()); + coordsOut->SetNumberOfTuples(nbTuples); + std::copy(coords3->GetPointer(0),coords3->GetPointer(0)+3*nbTuples,coordsOut->GetPointer(0)); + } +} + +void dealWith(vtkPolyData *outdata, const double center[3], const double axis[3], double radius, double eps, bool invertThetaInc, double offsetInRad) +{ + vtkDataArray *coords(outdata->GetPoints()->GetData()); + if(coords->GetNumberOfComponents()!=3) + throw MZCException("Input coordinates are expected to have 3 components !"); + // + vtkIdType nbNodes(coords->GetNumberOfTuples()); + if(nbNodes==0) + throw MZCException("No points -> impossible to develop anything !"); + // + vtkSmartPointer zeCoords; + ToDouble(coords,zeCoords); + // + double axis_cross_Z[3]={axis[1],-axis[0],0.}; + double n_axis(sqrt(axis_cross_Z[0]*axis_cross_Z[0]+axis_cross_Z[1]*axis_cross_Z[1])); + if(n_axis>eps) + { + double ang(asin(n_axis)); + if(axis[2]<0.) + ang=M_PI-ang; + MEDCoupling::DataArrayDouble::Rotate3DAlg(center,axis_cross_Z,ang,nbNodes,zeCoords->GetPointer(0),zeCoords->GetPointer(0)); + } + // + MEDCoupling::MCAuto c_cyl; + { + MEDCoupling::MCAuto cc(MEDCoupling::DataArrayDouble::New()); cc->alloc(nbNodes,3); + double *ccPtr(cc->getPointer()); + const double *zeCoordsPtr(zeCoords->GetPointer(0)); + for(vtkIdType i=0;i()); + } + c_cyl=cc->fromCartToCyl(); + } + MEDCoupling::MCAuto mfd(MEDCoupling::MEDFileData::New()); + WriteMEDFileFromVTKDataSet(mfd,outdata,{},0.,0); + bool a; + { + MEDCoupling::MEDFileMeshes *ms(mfd->getMeshes()); + if(ms->getNumberOfMeshes()!=1) + throw MZCException("Unexpected number of meshes !"); + MEDCoupling::MEDFileMesh *mm(ms->getMeshAtPos(0)); + MEDCoupling::MEDFileUMesh *mmu(dynamic_cast(mm)); + if(!mmu) + throw MZCException("Expecting unstructured one !"); + MEDCoupling::MCAuto m0(mmu->getMeshAtLevel(0)); + { + mcIdType v(0); + MEDCoupling::MCAuto c0s(m0->getCellIdsLyingOnNodes(&v,&v+1,false)); + if(c0s->empty()) + throw MZCException("Orphan node 0 !"); + std::vector nodes0; + m0->getNodeIdsOfCell(c0s->getIJ(0,0),nodes0); + MEDCoupling::MCAuto tmp0(c_cyl->selectByTupleIdSafe(nodes0.data(),nodes0.data()+nodes0.size())); + tmp0=tmp0->keepSelectedComponents({1}); + double tmp(tmp0->getMaxAbsValueInArray()); + a=tmp>0.; + } + } + // + constexpr double EPS_FOR_RADIUS=1e-2; + MEDCoupling::MCAuto rs(c_cyl->keepSelectedComponents({0})); + if(!rs->isUniform(radius,radius*EPS_FOR_RADIUS)) + { + double mi(rs->getMinValueInArray()),ma(rs->getMaxValueInArray()); + std::ostringstream oss; oss << "Looks not really a cylinder within given precision ! Range is [" << mi << "," << ma << "] expecting " << radius << " within precision of " << radius*EPS_FOR_RADIUS << " !"; + throw MZCException(oss.str()); + } + double tetha0(c_cyl->getIJ(0,1)); + { + double *ccylptr(c_cyl->getPointer()+1); + double mi02(std::numeric_limits::max()); + for(vtkIdType i=0;i0.) + { + ccylptr=c_cyl->getPointer()+1; + for(vtkIdType i=0;i=2*M_PI) + { + *ccylptr+=-2*M_PI; + } + } + } + } + { + MEDCoupling::MCAuto c_cyl_2(c_cyl->keepSelectedComponents({1})); + c_cyl_2->abs(); + MEDCoupling::MCAuto poses(c_cyl_2->findIdsInRange(0.,eps)); + c_cyl->setPartOfValuesSimple3(0.,poses->begin(),poses->end(),1,2,1); + } + // + if(a ^ (!invertThetaInc)) + { + MEDCoupling::MCAuto tmp(c_cyl->keepSelectedComponents({1})); + tmp=tmp->negate(); + std::for_each(tmp->getPointer(),tmp->getPointer()+tmp->getNumberOfTuples(),[](double& v) { if(v==-0.) v=0.; }); + c_cyl->setPartOfValues1(tmp,0,nbNodes,1,1,2,1); + } + MEDCoupling::MCAuto c_cyl_post(c_cyl->keepSelectedComponents({1})); + { + double *c_cyl_post_ptr(c_cyl_post->getPointer()); + for(vtkIdType i=0;iGetPolys()); + vtkIdType offset(nbNodes); + std::vector dupNodes(UnWrapByDuplicatingNodes(cb,offset,c_cyl_post)); + // + MEDCoupling::MCAuto c_cyl_post2(c_cyl_post->selectByTupleId(dupNodes.data(),dupNodes.data()+dupNodes.size())); + c_cyl_post2->applyLin(1.,2*M_PI); + c_cyl_post=MEDCoupling::DataArrayDouble::Aggregate(c_cyl_post,c_cyl_post2); + MEDCoupling::MCAuto z0(c_cyl->keepSelectedComponents({2})); + MEDCoupling::MCAuto z1(z0->selectByTupleId(dupNodes.data(),dupNodes.data()+dupNodes.size())); + z0=MEDCoupling::DataArrayDouble::Aggregate(z0,z1); + // + std::size_t outNbNodes(z0->getNumberOfTuples()); + vtkSmartPointer zeCoords2; + zeCoords2.TakeReference(vtkDoubleArray::New()); + zeCoords2->SetNumberOfComponents(3); + zeCoords2->SetNumberOfTuples(outNbNodes); + { + const double *tptr(c_cyl_post->begin()),*zptr(z0->begin()); + double *outPtr(zeCoords2->GetPointer(0)); + for(std::size_t i=0;iGetPoints()->SetData(zeCoords2); + // now post process nodes + std::vector nodeSel(nbNodes+dupNodes.size()); + { + int cnt(0); + std::for_each(nodeSel.begin(),nodeSel.begin()+nbNodes,[&cnt](int& v){ v=cnt++; }); + std::copy(dupNodes.begin(),dupNodes.end(),nodeSel.begin()+nbNodes); + } + vtkDataSetAttributes *pd(outdata->GetPointData()); + int nba(pd->GetNumberOfArrays()); + for(int i=0;iGetArray(i)); + { + vtkIntArray *arr0(vtkIntArray::SafeDownCast(arr)); + if(arr0) + { + DealArray(pd,i,arr0,nodeSel); + continue; + } + } + { + vtkFloatArray *arr0(vtkFloatArray::SafeDownCast(arr)); + if(arr0) + { + DealArray(pd,i,arr0,nodeSel); + continue; + } + } + { + vtkDoubleArray *arr0(vtkDoubleArray::SafeDownCast(arr)); + if(arr0) + { + DealArray(pd,i,arr0,nodeSel); + continue; + } + } + } +} + +int vtkDevelopedSurface::RequestData(vtkInformation *request, vtkInformationVector **inputVector, vtkInformationVector *outputVector) +{ + //std::cerr << "########################################## vtkDevelopedSurface::RequestData ##########################################" << std::endl; + try + { + if(!_cyl) + throw MZCException("No cylinder object as cut function !"); + double center[3],axis[3],radius; + vtkAbstractTransform* trf(_cyl->GetTransform()); + { + _cyl->GetCenter(center); + _cyl->GetAxis(axis[0],axis[1],axis[2]); + radius=_cyl->GetRadius(); + } + if(trf) + { + double axis3[3]={center[0]+0.,center[1]+1.,center[2]+0.},axis4[3]; + trf->TransformPoint(axis3,axis4); + std::transform(axis4,axis4+3,center,axis,[](double a, double b) { return b-a; }); + axis[1]=-axis[1]; + if(std::isnan(axis[0]) && std::isnan(axis[1]) && std::isnan(axis[2])) + { axis[0]=0.; axis[1]=-1.; axis[2]=0.; } + } + //std::cerr << trf << " jjj " << axis[0] << " " << axis[1] << " " << axis[2] << " : " << center[0] << " " << center[1] << " " << center[2] << " " " " << " -> " << radius << std::endl; + vtkDataSet *usgIn(0); + ExtractInfo(inputVector[0],usgIn); + vtkSmartPointer outData; + { + vtkNew Cutter; + Cutter->SetInputData(usgIn); + Cutter->SetCutFunction(_cyl); + Cutter->Update(); + vtkDataSet *zeComputedOutput(Cutter->GetOutput()); + vtkPolyData *zeComputedOutput2(vtkPolyData::SafeDownCast(zeComputedOutput)); + if(!zeComputedOutput2) + throw MZCException("Unexpected output of cutter !"); + outData.TakeReference(zeComputedOutput2); + zeComputedOutput2->Register(0); + } + if(outData->GetNumberOfCells()==0) + return 1;// no cells -> nothing to do + // + dealWith(outData,center,axis,radius,1e-7,this->InvertStatus,this->OffsetInRad); + //finish + vtkInformation *outInfo(outputVector->GetInformationObject(0)); + vtkPolyData *output(vtkPolyData::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT()))); + output->ShallowCopy(outData); + } + catch(MZCException& e) + { + std::ostringstream oss; + oss << "Exception has been thrown in vtkDevelopedSurface::RequestInformation : " << e.what() << std::endl; + if(this->HasObserver("ErrorEvent") ) + this->InvokeEvent("ErrorEvent",const_cast(oss.str().c_str())); + else + vtkOutputWindowDisplayErrorText(const_cast(oss.str().c_str())); + vtkObject::BreakOnError(); + return 0; + } + return 1; +} + +int vtkDevelopedSurface::FillOutputPortInformation( int vtkNotUsed(port), vtkInformation* info) +{ + info->Set(vtkDataObject::DATA_TYPE_NAME(), "vtkPolyData"); + return 1; +} + + +void vtkDevelopedSurface::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os, indent); +} + +void vtkDevelopedSurface::SetCutFunction(vtkImplicitFunction* func) +{ + vtkCylinder *cyl(vtkCylinder::SafeDownCast(func)); + if(cyl) + { + _cyl=cyl; + this->Modified(); + } +} + +vtkMTimeType vtkDevelopedSurface::GetMTime() +{ + vtkMTimeType maxMTime = this->Superclass::GetMTime(); // My MTime + if(_cyl) + { + maxMTime=std::max(maxMTime,_cyl->GetMTime()); + } + return maxMTime; +} diff --git a/src/Plugins/DevelopedSurface/plugin/DevelopedSurfaceModule/vtkDevelopedSurface.h b/src/Plugins/DevelopedSurface/plugin/DevelopedSurfaceModule/vtkDevelopedSurface.h new file mode 100644 index 00000000..d3bf7348 --- /dev/null +++ b/src/Plugins/DevelopedSurface/plugin/DevelopedSurfaceModule/vtkDevelopedSurface.h @@ -0,0 +1,65 @@ +// Copyright (C) 2017-2019 EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay (EDF R&D) + +#ifndef vtkDevelopedSurface_h__ +#define vtkDevelopedSurface_h__ + +#include + +class vtkMutableDirectedGraph; +class vtkImplicitFunction; +class vtkCylinder; + +class vtkDevelopedSurface : public vtkDataSetAlgorithm +{ +public: + static vtkDevelopedSurface* New(); + vtkTypeMacro(vtkDevelopedSurface, vtkDataSetAlgorithm); + void PrintSelf(ostream& os, vtkIndent indent) override; + + void SetCutFunction(vtkImplicitFunction* func); + + void SetInvertWay(bool invertStatus); + + void SetThetaOffset(double offsetInDegrees); + + vtkMTimeType GetMTime(); + +protected: + vtkDevelopedSurface(); + ~vtkDevelopedSurface(); + + int FillOutputPortInformation(int, vtkInformation*) override; + + int RequestInformation(vtkInformation*, vtkInformationVector**, vtkInformationVector*) override; + int RequestData(vtkInformation*, vtkInformationVector**, vtkInformationVector*) override; + + vtkCylinder* _cyl; + class vtkInternals; + vtkInternals* Internal; + bool InvertStatus; + double OffsetInRad; + +private: + vtkDevelopedSurface(const vtkDevelopedSurface&) = delete; + void operator=(const vtkDevelopedSurface&) = delete; +}; + +#endif diff --git a/src/Plugins/DevelopedSurface/plugin/Test/CMakeLists.txt b/src/Plugins/DevelopedSurface/plugin/Test/CMakeLists.txt new file mode 100644 index 00000000..ccd6d186 --- /dev/null +++ b/src/Plugins/DevelopedSurface/plugin/Test/CMakeLists.txt @@ -0,0 +1,33 @@ +# Copyright (C) 2017-2019 EDF R&D +# +# This library 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. +# +# 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 +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +# + +SET(TEMP_DIR "${CMAKE_CURRENT_BINARY_DIR}/Testing/Temporary") + +IF(NOT EXISTS ${TEMP_DIR}) + FILE(MAKE_DIRECTORY ${TEMP_DIR}) +ENDIF(NOT EXISTS ${TEMP_DIR}) + +SET(DEV_SURFACE_TESTS test_dev_surface2 test_dev_surface3) + +IF(NOT SALOME_PARAVIS_NO_VISU_TESTS) + FOREACH(tfile ${DEV_SURFACE_TESTS}) + ADD_TEST(${tfile} ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/${tfile}.py ) + SET_TESTS_PROPERTIES(${tfile} PROPERTIES LABELS "PVS_ADD_ONS") + ENDFOREACH(tfile ${DEV_SURFACE_TESTS}) +ENDIF() diff --git a/src/Plugins/DevelopedSurface/plugin/Test/test_dev_surface.py b/src/Plugins/DevelopedSurface/plugin/Test/test_dev_surface.py new file mode 100644 index 00000000..0b3f2b05 --- /dev/null +++ b/src/Plugins/DevelopedSurface/plugin/Test/test_dev_surface.py @@ -0,0 +1,162 @@ +# Copyright (C) 2017-2019 EDF R&D +# +# This library 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. +# +# 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 +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +# +# Author : Anthony Geay (EDF R&D) + +#### import the simple module from the paraview +from paraview.simple import * +#### disable automatic camera reset on 'Show' +paraview.simple._DisableFirstRenderCameraReset() + +# create a new 'MED Reader' +multiTSmed = MEDReader(FileName='multiTS.med') +multiTSmed.AllArrays = ['TS0/Mesh/ComSup0/Pressure@@][@@P0'] +multiTSmed.AllTimeSteps = ['0000', '0001', '0002', '0003', '0004', '0005', '0006', '0007', '0008', '0009'] + +# get animation scene +animationScene1 = GetAnimationScene() + +# update animation scene based on data timesteps +animationScene1.UpdateAnimationUsingDataTimeSteps() + +# get active view +renderView1 = GetActiveViewOrCreate('RenderView') +# uncomment following to set a specific view size +# renderView1.ViewSize = [1499, 582] + +# show data in view +multiTSmedDisplay = Show(multiTSmed, renderView1) + +# trace defaults for the display properties. +multiTSmedDisplay.Representation = 'Surface' +multiTSmedDisplay.ColorArrayName = [None, ''] +multiTSmedDisplay.OSPRayScaleArray = 'FamilyIdNode' +multiTSmedDisplay.OSPRayScaleFunction = 'PiecewiseFunction' +multiTSmedDisplay.SelectOrientationVectors = 'FamilyIdNode' +multiTSmedDisplay.ScaleFactor = 0.07399989366531372 +multiTSmedDisplay.SelectScaleArray = 'FamilyIdNode' +multiTSmedDisplay.GlyphType = 'Arrow' +multiTSmedDisplay.GlyphTableIndexArray = 'FamilyIdNode' +multiTSmedDisplay.DataAxesGrid = 'GridAxesRepresentation' +multiTSmedDisplay.PolarAxes = 'PolarAxesRepresentation' +multiTSmedDisplay.ScalarOpacityUnitDistance = 0.017316274962626298 +multiTSmedDisplay.GaussianRadius = 0.03699994683265686 +multiTSmedDisplay.SetScaleArray = ['POINTS', 'FamilyIdNode'] +multiTSmedDisplay.ScaleTransferFunction = 'PiecewiseFunction' +multiTSmedDisplay.OpacityArray = ['POINTS', 'FamilyIdNode'] +multiTSmedDisplay.OpacityTransferFunction = 'PiecewiseFunction' +multiTSmedDisplay.InputVectors = [None, ''] +multiTSmedDisplay.SelectInputVectors = [None, ''] +multiTSmedDisplay.WriteLog = '' + +# init the 'PiecewiseFunction' selected for 'ScaleTransferFunction' +multiTSmedDisplay.ScaleTransferFunction.Points = [0.0, 0.0, 0.5, 0.0, 1.1757813367477812e-38, 1.0, 0.5, 0.0] + +# init the 'PiecewiseFunction' selected for 'OpacityTransferFunction' +multiTSmedDisplay.OpacityTransferFunction.Points = [0.0, 0.0, 0.5, 0.0, 1.1757813367477812e-38, 1.0, 0.5, 0.0] + +# reset view to fit data +renderView1.ResetCamera() + +# update the view to ensure updated data information +renderView1.Update() + +# create a new 'Developed Surface' +developedSurface1 = DevelopedSurface(Input=multiTSmed) +developedSurface1.SliceType = 'Cylinder' + +# init the 'Cylinder' selected for 'SliceType' +developedSurface1.SliceType.Center = [0.0, 0.0, 0.05000000074505806] +developedSurface1.SliceType.Radius = 0.3699994683265686 + +# Properties modified on developedSurface1.SliceType +developedSurface1.SliceType.Center = [0.0, 0.0, 0.05] +developedSurface1.SliceType.Axis = [0.0, 0.0, 1.0] +developedSurface1.SliceType.Radius = 0.07 + +# Properties modified on developedSurface1.SliceType +developedSurface1.SliceType.Center = [0.0, 0.0, 0.05] +developedSurface1.SliceType.Axis = [0.0, 0.0, 1.0] +developedSurface1.SliceType.Radius = 0.07 + +# show data in view +developedSurface1Display = Show(developedSurface1, renderView1) + +# trace defaults for the display properties. +developedSurface1Display.Representation = 'Surface' +developedSurface1Display.ColorArrayName = [None, ''] +developedSurface1Display.OSPRayScaleArray = 'FamilyIdNode' +developedSurface1Display.OSPRayScaleFunction = 'PiecewiseFunction' +developedSurface1Display.SelectOrientationVectors = 'FamilyIdNode' +developedSurface1Display.ScaleFactor = 0.043982297150257116 +developedSurface1Display.SelectScaleArray = 'FamilyIdNode' +developedSurface1Display.GlyphType = 'Arrow' +developedSurface1Display.GlyphTableIndexArray = 'FamilyIdNode' +developedSurface1Display.DataAxesGrid = 'GridAxesRepresentation' +developedSurface1Display.PolarAxes = 'PolarAxesRepresentation' +developedSurface1Display.GaussianRadius = 0.021991148575128558 +developedSurface1Display.SetScaleArray = ['POINTS', 'FamilyIdNode'] +developedSurface1Display.ScaleTransferFunction = 'PiecewiseFunction' +developedSurface1Display.OpacityArray = ['POINTS', 'FamilyIdNode'] +developedSurface1Display.OpacityTransferFunction = 'PiecewiseFunction' +developedSurface1Display.InputVectors = [None, ''] +developedSurface1Display.SelectInputVectors = [None, ''] +developedSurface1Display.WriteLog = '' + +# init the 'PiecewiseFunction' selected for 'ScaleTransferFunction' +developedSurface1Display.ScaleTransferFunction.Points = [0.0, 0.0, 0.5, 0.0, 1.1757813367477812e-38, 1.0, 0.5, 0.0] + +# init the 'PiecewiseFunction' selected for 'OpacityTransferFunction' +developedSurface1Display.OpacityTransferFunction.Points = [0.0, 0.0, 0.5, 0.0, 1.1757813367477812e-38, 1.0, 0.5, 0.0] + +# hide data in view +Hide(multiTSmed, renderView1) + +# update the view to ensure updated data information +renderView1.Update() + +#change interaction mode for render view +renderView1.InteractionMode = '2D' + +# toggle 3D widget visibility (only when running from the GUI) +Hide3DWidgets(proxy=developedSurface1.SliceType) + +# set scalar coloring +ColorBy(developedSurface1Display, ('CELLS', 'Pressure')) + +# rescale color and/or opacity maps used to include current data range +developedSurface1Display.RescaleTransferFunctionToDataRange(True, False) + +# show color bar/color legend +developedSurface1Display.SetScalarBarVisibility(renderView1, True) + +# get color transfer function/color map for 'Pressure' +pressureLUT = GetColorTransferFunction('Pressure') + +#### saving camera placements for all active views + +# current camera placement for renderView1 +renderView1.InteractionMode = '2D' +renderView1.CameraPosition = [0.18935662797765695, 0.01726656182167085, 2.08092363470839] +renderView1.CameraFocalPoint = [0.18935662797765695, 0.01726656182167085, 0.05000000074505806] +renderView1.CameraParallelScale = 0.16748564967020724 + +#### uncomment the following to render all views +# RenderAllViews() +# alternatively, if you want to write images, you can use SaveScreenshot(...). +Render() diff --git a/src/Plugins/DevelopedSurface/plugin/Test/test_dev_surface2.py b/src/Plugins/DevelopedSurface/plugin/Test/test_dev_surface2.py new file mode 100644 index 00000000..d52406b8 --- /dev/null +++ b/src/Plugins/DevelopedSurface/plugin/Test/test_dev_surface2.py @@ -0,0 +1,170 @@ +# Copyright (C) 2017-2019 EDF R&D +# +# This library 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. +# +# 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 +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +# +# Author : Anthony Geay (EDF R&D) + +#### import the simple module from the paraview +from paraview.simple import * +from math import pi +TMPFileName="test2.med" + +#### disable automatic camera reset on 'Show' +paraview.simple._DisableFirstRenderCameraReset() + +# create a new 'Mandelbrot' +mandelbrot1 = Mandelbrot() + +# Properties modified on mandelbrot1 +mandelbrot1.WholeExtent = [0, 50, 0, 50, 0, 50] + +# get active view +renderView1 = GetActiveViewOrCreate('RenderView') +# uncomment following to set a specific view size +# renderView1.ViewSize = [1017, 317] + +# show data in view +mandelbrot1Display = Show(mandelbrot1, renderView1) + +# trace defaults for the display properties. +mandelbrot1Display.Representation = 'Outline' +mandelbrot1Display.ColorArrayName = ['POINTS', ''] +mandelbrot1Display.OSPRayScaleArray = 'Iterations' +mandelbrot1Display.OSPRayScaleFunction = 'PiecewiseFunction' +mandelbrot1Display.SelectOrientationVectors = 'Iterations' +mandelbrot1Display.ScaleFactor = 0.25 +mandelbrot1Display.SelectScaleArray = 'Iterations' +mandelbrot1Display.GlyphType = 'Arrow' +mandelbrot1Display.GlyphTableIndexArray = 'Iterations' +mandelbrot1Display.DataAxesGrid = 'GridAxesRepresentation' +mandelbrot1Display.PolarAxes = 'PolarAxesRepresentation' +mandelbrot1Display.ScalarOpacityUnitDistance = 0.08124038404635964 +mandelbrot1Display.Slice = 25 +mandelbrot1Display.GaussianRadius = 0.125 +mandelbrot1Display.SetScaleArray = ['POINTS', 'Iterations'] +mandelbrot1Display.ScaleTransferFunction = 'PiecewiseFunction' +mandelbrot1Display.OpacityArray = ['POINTS', 'Iterations'] +mandelbrot1Display.OpacityTransferFunction = 'PiecewiseFunction' +mandelbrot1Display.InputVectors = [None, ''] +mandelbrot1Display.SelectInputVectors = [None, ''] +mandelbrot1Display.WriteLog = '' + +# init the 'PiecewiseFunction' selected for 'ScaleTransferFunction' +mandelbrot1Display.ScaleTransferFunction.Points = [1.0, 0.0, 0.5, 0.0, 100.0, 1.0, 0.5, 0.0] + +# init the 'PiecewiseFunction' selected for 'OpacityTransferFunction' +mandelbrot1Display.OpacityTransferFunction.Points = [1.0, 0.0, 0.5, 0.0, 100.0, 1.0, 0.5, 0.0] + +# reset view to fit data +renderView1.ResetCamera() + +# update the view to ensure updated data information +renderView1.Update() + +# create a new 'Developed Surface' +developedSurface1 = DevelopedSurface(Input=mandelbrot1) +developedSurface1.SliceType = 'Cylinder' + +# init the 'Cylinder' selected for 'SliceType' +developedSurface1.SliceType.Center = [-0.5, 0.0, 1.0] +developedSurface1.SliceType.Radius = 0.5 #1.25 + +# show data in view +developedSurface1Display = Show(developedSurface1, renderView1) + +# get color transfer function/color map for 'Iterations' +iterationsLUT = GetColorTransferFunction('Iterations') + +# trace defaults for the display properties. +developedSurface1Display.Representation = 'Surface' +developedSurface1Display.ColorArrayName = ['POINTS', 'Iterations'] +developedSurface1Display.LookupTable = iterationsLUT +developedSurface1Display.OSPRayScaleArray = 'Iterations' +developedSurface1Display.OSPRayScaleFunction = 'PiecewiseFunction' +developedSurface1Display.SelectOrientationVectors = 'Iterations' +developedSurface1Display.ScaleFactor = 0.7853981633974483 +developedSurface1Display.SelectScaleArray = 'Iterations' +developedSurface1Display.GlyphType = 'Arrow' +developedSurface1Display.GlyphTableIndexArray = 'Iterations' +developedSurface1Display.DataAxesGrid = 'GridAxesRepresentation' +developedSurface1Display.PolarAxes = 'PolarAxesRepresentation' +developedSurface1Display.GaussianRadius = 0.39269908169872414 +developedSurface1Display.SetScaleArray = ['POINTS', 'Iterations'] +developedSurface1Display.ScaleTransferFunction = 'PiecewiseFunction' +developedSurface1Display.OpacityArray = ['POINTS', 'Iterations'] +developedSurface1Display.OpacityTransferFunction = 'PiecewiseFunction' +developedSurface1Display.InputVectors = [None, ''] +developedSurface1Display.SelectInputVectors = [None, ''] +developedSurface1Display.WriteLog = '' + +# init the 'PiecewiseFunction' selected for 'ScaleTransferFunction' +developedSurface1Display.ScaleTransferFunction.Points = [1.0, 0.0, 0.5, 0.0, 100.0, 1.0, 0.5, 0.0] + +# init the 'PiecewiseFunction' selected for 'OpacityTransferFunction' +developedSurface1Display.OpacityTransferFunction.Points = [1.0, 0.0, 0.5, 0.0, 100.0, 1.0, 0.5, 0.0] + +# hide data in view +Hide(mandelbrot1, renderView1) + +# show color bar/color legend +developedSurface1Display.SetScalarBarVisibility(renderView1, True) + +# update the view to ensure updated data information +renderView1.Update() + +# toggle 3D widget visibility (only when running from the GUI) +Hide3DWidgets(proxy=developedSurface1.SliceType) + +#### saving camera placements for all active views + +# current camera placement for renderView1 +renderView1.CameraPosition = [4.090024784500779, -0.15919161102314858, 7.485304552729019] +renderView1.CameraFocalPoint = [4.090024784500779, -0.15919161102314858, 1.0] +renderView1.CameraParallelScale = 2.03100960115899 + +#### uncomment the following to render all views +# RenderAllViews() +# alternatively, if you want to write images, you can use SaveScreenshot(...). + +mand=servermanager.Fetch(mandelbrot1) +axisId=1 +high_out=mand.GetSpacing()[axisId]*(mand.GetExtent()[2*axisId+1]-mand.GetExtent()[2*axisId+0]) + +vtp=servermanager.Fetch(developedSurface1) +arr=vtp.GetPointData().GetArray(0) +assert(arr.GetName()=="Iterations") +a,b=arr.GetRange() +assert(a>=1 and a<=2) +assert(b==100.) +SaveData(TMPFileName, proxy=developedSurface1) +from MEDLoader import * + +mm=MEDFileMesh.New(TMPFileName) +m0=mm[0] +area=m0.getMeasureField(True).getArray().accumulate()[0] + +zeResu0=area/high_out/developedSurface1.SliceType.Radius +assert(abs(zeResu0-2*pi)<1e-5) + +fs=MEDFileFields(TMPFileName) +f=fs["Iterations"][0].field(mm) +nodeIds=f.getArray().convertToDblArr().findIdsInRange(99.,101.) +cellIds=m0.getCellIdsLyingOnNodes(nodeIds,True) +zeResu1=m0[cellIds].getMeasureField(True).getArray().accumulate()[0] + +assert(abs(zeResu1-1.1427)<1e-2) + diff --git a/src/Plugins/DevelopedSurface/plugin/Test/test_dev_surface3.py b/src/Plugins/DevelopedSurface/plugin/Test/test_dev_surface3.py new file mode 100644 index 00000000..ba748b88 --- /dev/null +++ b/src/Plugins/DevelopedSurface/plugin/Test/test_dev_surface3.py @@ -0,0 +1,166 @@ +# Copyright (C) 2017-2019 EDF R&D +# +# This library 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. +# +# 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 +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +# +# Author : Anthony Geay (EDF R&D) + +#### import the simple module from the paraview +from paraview.simple import * +from math import pi +TMPFileName="test3.med" + +#### disable automatic camera reset on 'Show' +paraview.simple._DisableFirstRenderCameraReset() + +# create a new 'Mandelbrot' +mandelbrot1 = Mandelbrot() + +# Properties modified on mandelbrot1 +mandelbrot1.WholeExtent = [0, 50, 0, 50, 0, 50] + +# get active view +renderView1 = GetActiveViewOrCreate('RenderView') +# uncomment following to set a specific view size +# renderView1.ViewSize = [1017, 317] + +# show data in view +mandelbrot1Display = Show(mandelbrot1, renderView1) + +# trace defaults for the display properties. +mandelbrot1Display.Representation = 'Outline' +mandelbrot1Display.ColorArrayName = ['POINTS', ''] +mandelbrot1Display.OSPRayScaleArray = 'Iterations' +mandelbrot1Display.OSPRayScaleFunction = 'PiecewiseFunction' +mandelbrot1Display.SelectOrientationVectors = 'Iterations' +mandelbrot1Display.ScaleFactor = 0.25 +mandelbrot1Display.SelectScaleArray = 'Iterations' +mandelbrot1Display.GlyphType = 'Arrow' +mandelbrot1Display.GlyphTableIndexArray = 'Iterations' +mandelbrot1Display.DataAxesGrid = 'GridAxesRepresentation' +mandelbrot1Display.PolarAxes = 'PolarAxesRepresentation' +mandelbrot1Display.ScalarOpacityUnitDistance = 0.08124038404635964 +mandelbrot1Display.Slice = 25 +mandelbrot1Display.GaussianRadius = 0.125 +mandelbrot1Display.SetScaleArray = ['POINTS', 'Iterations'] +mandelbrot1Display.ScaleTransferFunction = 'PiecewiseFunction' +mandelbrot1Display.OpacityArray = ['POINTS', 'Iterations'] +mandelbrot1Display.OpacityTransferFunction = 'PiecewiseFunction' +mandelbrot1Display.InputVectors = [None, ''] +mandelbrot1Display.SelectInputVectors = [None, ''] +mandelbrot1Display.WriteLog = '' + +# init the 'PiecewiseFunction' selected for 'ScaleTransferFunction' +mandelbrot1Display.ScaleTransferFunction.Points = [1.0, 0.0, 0.5, 0.0, 100.0, 1.0, 0.5, 0.0] + +# init the 'PiecewiseFunction' selected for 'OpacityTransferFunction' +mandelbrot1Display.OpacityTransferFunction.Points = [1.0, 0.0, 0.5, 0.0, 100.0, 1.0, 0.5, 0.0] + +# reset view to fit data +renderView1.ResetCamera() + +# update the view to ensure updated data information +renderView1.Update() + +# create a new 'Developed Surface' +developedSurface1 = DevelopedSurface(Input=mandelbrot1) +developedSurface1.SliceType = 'Cylinder' + +# init the 'Cylinder' selected for 'SliceType' +developedSurface1.SliceType.Center = [-0.5, 0.0, 1.0] +developedSurface1.SliceType.Radius = 0.5 #1.25 +developedSurface1.SliceType.Axis = [-0.5065630563269753, -0.6288876685363318, -0.5898255422814533] + +# show data in view +developedSurface1Display = Show(developedSurface1, renderView1) + +# get color transfer function/color map for 'Iterations' +iterationsLUT = GetColorTransferFunction('Iterations') + +# trace defaults for the display properties. +developedSurface1Display.Representation = 'Surface' +developedSurface1Display.ColorArrayName = ['POINTS', 'Iterations'] +developedSurface1Display.LookupTable = iterationsLUT +developedSurface1Display.OSPRayScaleArray = 'Iterations' +developedSurface1Display.OSPRayScaleFunction = 'PiecewiseFunction' +developedSurface1Display.SelectOrientationVectors = 'Iterations' +developedSurface1Display.ScaleFactor = 0.7853981633974483 +developedSurface1Display.SelectScaleArray = 'Iterations' +developedSurface1Display.GlyphType = 'Arrow' +developedSurface1Display.GlyphTableIndexArray = 'Iterations' +developedSurface1Display.DataAxesGrid = 'GridAxesRepresentation' +developedSurface1Display.PolarAxes = 'PolarAxesRepresentation' +developedSurface1Display.GaussianRadius = 0.39269908169872414 +developedSurface1Display.SetScaleArray = ['POINTS', 'Iterations'] +developedSurface1Display.ScaleTransferFunction = 'PiecewiseFunction' +developedSurface1Display.OpacityArray = ['POINTS', 'Iterations'] +developedSurface1Display.OpacityTransferFunction = 'PiecewiseFunction' +developedSurface1Display.InputVectors = [None, ''] +developedSurface1Display.SelectInputVectors = [None, ''] +developedSurface1Display.WriteLog = '' + +# init the 'PiecewiseFunction' selected for 'ScaleTransferFunction' +developedSurface1Display.ScaleTransferFunction.Points = [1.0, 0.0, 0.5, 0.0, 100.0, 1.0, 0.5, 0.0] + +# init the 'PiecewiseFunction' selected for 'OpacityTransferFunction' +developedSurface1Display.OpacityTransferFunction.Points = [1.0, 0.0, 0.5, 0.0, 100.0, 1.0, 0.5, 0.0] + +# hide data in view +Hide(mandelbrot1, renderView1) + +# show color bar/color legend +developedSurface1Display.SetScalarBarVisibility(renderView1, True) + +# update the view to ensure updated data information +renderView1.Update() + +# toggle 3D widget visibility (only when running from the GUI) +Hide3DWidgets(proxy=developedSurface1.SliceType) + +#### saving camera placements for all active views + +# current camera placement for renderView1 +renderView1.CameraPosition = [4.090024784500779, -0.15919161102314858, 7.485304552729019] +renderView1.CameraFocalPoint = [4.090024784500779, -0.15919161102314858, 1.0] +renderView1.CameraParallelScale = 2.03100960115899 + +#### uncomment the following to render all views +# RenderAllViews() +# alternatively, if you want to write images, you can use SaveScreenshot(...). + + +vtp=servermanager.Fetch(developedSurface1) +arr=vtp.GetPointData().GetArray(0) +assert(arr.GetName()=="Iterations") +a,b=arr.GetRange() +assert(a>=1 and a<=2) +assert(b==100.) +SaveData(TMPFileName, proxy=developedSurface1) +from MEDLoader import * + +mm=MEDFileMesh.New(TMPFileName) +m0=mm[0] +area=m0.getMeasureField(True).getArray().accumulate()[0] + + +fs=MEDFileFields(TMPFileName) +f=fs["Iterations"][0].field(mm) +nodeIds=f.getArray().convertToDblArr().findIdsInRange(99.,101.) +cellIds=m0.getCellIdsLyingOnNodes(nodeIds,True) +zeResu1=m0[cellIds].getMeasureField(True).getArray().accumulate()[0] + +assert(abs(zeResu1-1.3564)<1e-2) + diff --git a/src/Plugins/DevelopedSurface/plugin/filters.xml b/src/Plugins/DevelopedSurface/plugin/filters.xml new file mode 100644 index 00000000..737871ba --- /dev/null +++ b/src/Plugins/DevelopedSurface/plugin/filters.xml @@ -0,0 +1,60 @@ + + + + + + + + + + + + + This property specifies the input to the Level Scalars filter. + + + + + + + + + + + This property sets the parameters of cylinder used for slice. + + + + + + Specify if way used to develop theta is inverted or not relative to the + reference one. By default no. The reference way used is those defined + by the first cell sharing node 0. + + + + + + By default, node 0 theta parameter is used as starting point. This + property allows to change this reference by applying an offset on it. + Offset is expressed in degrees. + + + + + + + + diff --git a/src/Plugins/DevelopedSurface/plugin/paraview.plugin b/src/Plugins/DevelopedSurface/plugin/paraview.plugin new file mode 100644 index 00000000..bbe047da --- /dev/null +++ b/src/Plugins/DevelopedSurface/plugin/paraview.plugin @@ -0,0 +1,8 @@ +NAME + DevelopedSurfacePlugin +DESCRIPTION + This plugin provides the DevelopedSurface filter. +REQUIRES_MODULES + VTK::CommonCore + VTK::IOCore + VTK::FiltersCore diff --git a/src/Plugins/DevelopedSurface/pp.py b/src/Plugins/DevelopedSurface/pp.py deleted file mode 100644 index bf5d413b..00000000 --- a/src/Plugins/DevelopedSurface/pp.py +++ /dev/null @@ -1,107 +0,0 @@ -# Copyright (C) 2017-2019 EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# -# Author : Anthony Geay (EDF R&D) - -from MEDLoader import * -from math import sqrt -import numpy as np -import scipy -import scipy.sparse.linalg - -def f0(sample,p,v,r): - d=sample-p - return d.magnitude()[0]-r - -def f(sample,p,v,r): - d=sample-p - l=d-DataArrayDouble.Dot(d,v)[0]*v - return l.magnitude()[0]-r - -def f2(sample,zev,ff): - p=zev[0,:3] ; v=zev[0,3:6] ; r=zev[0,6] - return ff(sample,p,v,r) - -def df(sample,zev,varid,ff): - eps=0.0001 - zev=zev[:] - zev2=zev[:] - zev[0,varid]+=eps ; zev2[0,varid]-=eps - return (f2(sample,zev,ff)-f2(sample,zev2,ff))/(2*eps) - -#def df2(sample,p,v,r,varid): -# zev=DataArrayDouble.Meld([p_s,v_s,DataArrayDouble([r_s])]) -# return df(sample,zev,varid) - -def jacob(sample,p,v,r,ff): - zev=DataArrayDouble.Meld([p_s,v_s,DataArrayDouble([r_s])]) - return DataArrayDouble([df(sample,zev,i,ff) for i in range(7)],1,7) - -def jacob0(sample,p,v,r): - zev=DataArrayDouble.Meld([p_s,v_s,DataArrayDouble([r_s])]) - return DataArrayDouble([df0(sample,zev,i) for i in range(7)],1,7) - -mm=MEDFileMesh.New("example2.med") -c=mm.getCoords() -p_s=DataArrayDouble(c.accumulate(),1,3)/float(len(c)) -v_s=DataArrayDouble([1,0,0],1,3) -o=DataArrayDouble(c.getMinMaxPerComponent(),3,2) -o0,o1=o.explodeComponents() -o=o1-o0 -o.abs() -r_s=o.getMaxValue()[0]/2. -# -r_s=0.215598 -p_s=DataArrayDouble([0.,0.,0.],1,3) -v_s=DataArrayDouble([0.,0.,1.],1,3) -# -r_s=0.2 -p_s=DataArrayDouble([1.,1.,1.],1,3) -v_s=DataArrayDouble([1.,1.,1.],1,3) -#probes=[0,979,1167,2467,2862,3706,3819] -probes=[1000]+[c[:,i].getMaxValue()[1] for i in range(3)]+[c[:,i].getMinValue()[1] for i in range(3)] - -p=p_s ; v=v_s ; r=r_s -for ii in range(1): - mat=DataArrayDouble.Aggregate([jacob(c[probes[0]],p,v,r,f0)]+[jacob(c[probe],p,v,r,f) for probe in probes[1:]])#+[DataArrayDouble([0,0,0,2*v[0,0],2*v[0,1],2*v[0,2],0],1,7)] - y=DataArrayDouble([f0(c[probes[0]],p,v,r)]+[f(c[probe],p,v,r) for probe in probes[1:]]) - #y.pushBackSilent(v.magnitude()[0]-1.) - delta2=y[:] ; delta2.abs() - if delta2.getMaxValueInArray()<1e-5: - print("finished") - break; - mat=scipy.matrix(mat.toNumPyArray()) - print ii,np.linalg.cond(mat) - y=scipy.matrix(y.toNumPyArray()) - y=y.transpose() - delta=np.linalg.solve(mat,-y) - #delta=scipy.sparse.linalg.gmres(mat,-y)[0] # cg - delta=DataArrayDouble(delta) ; delta.rearrange(7) - #p+=delta[0,:3] - #v+=delta[0,3:6] - #v/=v.magnitude()[0] - #r+=delta[0,6] - print ii,delta.getValues()#,yy.transpose().tolist() - - pass - -mat1=mat[[0,1,2,6]] -mat1=mat1.transpose() -mat1=mat1[[0,1,2,6]] -mat1=mat1.transpose() -mm=np.linalg.solve(mat1,y[[0,1,2,6]]) diff --git a/src/Plugins/DevelopedSurface/pp1.py b/src/Plugins/DevelopedSurface/pp1.py deleted file mode 100644 index 2eaf059a..00000000 --- a/src/Plugins/DevelopedSurface/pp1.py +++ /dev/null @@ -1,27 +0,0 @@ -# Copyright (C) 2017-2019 EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# -# Author : Anthony Geay (EDF R&D) - -from MEDLoader import * -from math import pi -mm=MEDFileMesh.New("example2.med") -c=mm.getCoords() -MEDCouplingUMesh.Rotate3DAlg([0,0,0],[1,1,0],pi/4,c) -c+=[3,2,0] -mm.write("example2_2.med",2) diff --git a/src/Plugins/DevelopedSurface/pp2.py b/src/Plugins/DevelopedSurface/pp2.py deleted file mode 100644 index 65783346..00000000 --- a/src/Plugins/DevelopedSurface/pp2.py +++ /dev/null @@ -1,121 +0,0 @@ -# Copyright (C) 2017-2019 EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# -# Author : Anthony Geay (EDF R&D) - -from MEDLoader import * -from math import pi,asin,acos,atan2 -import numpy as np - -invertThetaInc=False - -mm=MEDFileMesh.New("example2_2.med") -c=mm.getCoords() - -v=DataArrayDouble([0.70710678118617443,-0.70710678118572623,1],1,3) -v/=v.magnitude()[0] -vRef=DataArrayDouble([0,0,1],1,3) -vRot=DataArrayDouble.CrossProduct(v,vRef) -ang=asin(vRot.magnitude()[0]) -MEDCouplingUMesh.Rotate3DAlg([0,0,0],vRot.getValues(),ang,c) - -c2=c[:,[0,1]] -# -a,b=c2.findCommonTuples(1e-5) -pool=c2[a[b[:-1]]] -probes=[pool[:,0].getMaxValue()[1],pool[:,1].getMaxValue()[1],pool[:,0].getMinValue()[1]] -center,radius,_=pool[probes].asArcOfCircle() -assert(((c2-center).magnitude()).isUniform(radius,1e-5)) -theta=((c2-center)/radius) -theta=DataArrayDouble([atan2(y,x) for x,y in theta]) -zeTheta=theta-theta[0] - -mm.write("tmp.med",2) -########### -c_cyl=DataArrayDouble.fromCartToCyl(c-(center+[0.])) -assert(c_cyl[:,0].isUniform(radius,1e-5)) -tetha0=c_cyl[0,1] -c_cyl[:,1]-=tetha0 -c_cyl_2=c_cyl[:,1] ; c_cyl_2.abs() -c_cyl[c_cyl_2.findIdsInRange(0.,1e-6),1]=0. -######## -m0=mm[0] -c0s=m0.getCellIdsLyingOnNodes([0],False) -assert(len(c0s)!=0) -tmp=c_cyl[m0.getNodeIdsOfCell(c0s[0]),1].getMaxAbsValueInArray() -a=tmp>0. -if a^(not invertThetaInc): - c_cyl[:,1]=-c_cyl[:,1] - pass -# -c_cyl_post=c_cyl[:,1] -m0.convertAllToPoly() -tmp=MEDCoupling1DGTUMesh(m0) ; c=tmp.getNodalConnectivity() ; ci=tmp.getNodalConnectivityIndex() -for elt in c_cyl_post: - if float(elt)<0: - elt[:]=float(elt)+2*pi - -nbCells=m0.getNumberOfCells() -nbNodes=m0.getNumberOfNodes() -newCoo=DataArrayInt(0,1) -cellsWithPb=[] -newConn=[] -for i in xrange(nbCells): - tmp=c_cyl_post[c[ci[i]:ci[i+1]]] - if tmp.getMaxValueInArray()-tmp.getMinValueInArray()>pi: - cellsWithPb.append(i) - # dup of low val - newLocConn=[] - for elt in c[ci[i]:ci[i+1]]: - if float(c_cyl_post[elt])<=pi: - newLocConn.append(nbNodes+len(newCoo)) - newCoo.pushBackSilent(int(elt)) - pass - else: - newLocConn.append(int(elt)) - pass - pass - newConn.append(newLocConn[:]) - pass - - -c_cyl_post=DataArrayDouble.Aggregate([c_cyl_post,c_cyl_post[newCoo]+2*pi]) -z_post=DataArrayDouble.Aggregate([c_cyl[:,2],c_cyl[newCoo,2]]) -newCoords=DataArrayDouble.Meld(radius*c_cyl_post,z_post) - -z=DataArrayInt([len(elt) for elt in newConn]) -z.computeOffsetsFull() -# -cellsWithPbMesh=MEDCoupling1DGTUMesh("",NORM_POLYGON) -cellsWithPbMesh.setNodalConnectivity(DataArrayInt(sum(newConn,[])),z) -cellsWithPbMesh.setCoords(newCoords) -# -ko_part_ids=DataArrayInt(cellsWithPb) -part_ids=ko_part_ids.buildComplement(nbCells) -part=m0[part_ids] -part.setCoords(newCoords) -whole=MEDCouplingUMesh.MergeUMeshesOnSameCoords([part,cellsWithPbMesh.buildUnstructured()]) - -o2n=DataArrayInt.Aggregate([part_ids,ko_part_ids]) -whole=whole[o2n.invertArrayO2N2N2O(len(o2n))] -whole.setName("mesh") -WriteMesh("tmp3.med",whole,True) - -#sk=m0.computeSkin().computeFetchedNodeIds() -#sk_part=part.computeSkin().computeFetchedNodeIds() -#m0[DataArrayInt(cellsWithPb)].computeFetchedNodeIds() diff --git a/src/Plugins/DevelopedSurface/scripts/pp.py b/src/Plugins/DevelopedSurface/scripts/pp.py new file mode 100644 index 00000000..bf5d413b --- /dev/null +++ b/src/Plugins/DevelopedSurface/scripts/pp.py @@ -0,0 +1,107 @@ +# Copyright (C) 2017-2019 EDF R&D +# +# This library 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. +# +# 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 +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +# +# Author : Anthony Geay (EDF R&D) + +from MEDLoader import * +from math import sqrt +import numpy as np +import scipy +import scipy.sparse.linalg + +def f0(sample,p,v,r): + d=sample-p + return d.magnitude()[0]-r + +def f(sample,p,v,r): + d=sample-p + l=d-DataArrayDouble.Dot(d,v)[0]*v + return l.magnitude()[0]-r + +def f2(sample,zev,ff): + p=zev[0,:3] ; v=zev[0,3:6] ; r=zev[0,6] + return ff(sample,p,v,r) + +def df(sample,zev,varid,ff): + eps=0.0001 + zev=zev[:] + zev2=zev[:] + zev[0,varid]+=eps ; zev2[0,varid]-=eps + return (f2(sample,zev,ff)-f2(sample,zev2,ff))/(2*eps) + +#def df2(sample,p,v,r,varid): +# zev=DataArrayDouble.Meld([p_s,v_s,DataArrayDouble([r_s])]) +# return df(sample,zev,varid) + +def jacob(sample,p,v,r,ff): + zev=DataArrayDouble.Meld([p_s,v_s,DataArrayDouble([r_s])]) + return DataArrayDouble([df(sample,zev,i,ff) for i in range(7)],1,7) + +def jacob0(sample,p,v,r): + zev=DataArrayDouble.Meld([p_s,v_s,DataArrayDouble([r_s])]) + return DataArrayDouble([df0(sample,zev,i) for i in range(7)],1,7) + +mm=MEDFileMesh.New("example2.med") +c=mm.getCoords() +p_s=DataArrayDouble(c.accumulate(),1,3)/float(len(c)) +v_s=DataArrayDouble([1,0,0],1,3) +o=DataArrayDouble(c.getMinMaxPerComponent(),3,2) +o0,o1=o.explodeComponents() +o=o1-o0 +o.abs() +r_s=o.getMaxValue()[0]/2. +# +r_s=0.215598 +p_s=DataArrayDouble([0.,0.,0.],1,3) +v_s=DataArrayDouble([0.,0.,1.],1,3) +# +r_s=0.2 +p_s=DataArrayDouble([1.,1.,1.],1,3) +v_s=DataArrayDouble([1.,1.,1.],1,3) +#probes=[0,979,1167,2467,2862,3706,3819] +probes=[1000]+[c[:,i].getMaxValue()[1] for i in range(3)]+[c[:,i].getMinValue()[1] for i in range(3)] + +p=p_s ; v=v_s ; r=r_s +for ii in range(1): + mat=DataArrayDouble.Aggregate([jacob(c[probes[0]],p,v,r,f0)]+[jacob(c[probe],p,v,r,f) for probe in probes[1:]])#+[DataArrayDouble([0,0,0,2*v[0,0],2*v[0,1],2*v[0,2],0],1,7)] + y=DataArrayDouble([f0(c[probes[0]],p,v,r)]+[f(c[probe],p,v,r) for probe in probes[1:]]) + #y.pushBackSilent(v.magnitude()[0]-1.) + delta2=y[:] ; delta2.abs() + if delta2.getMaxValueInArray()<1e-5: + print("finished") + break; + mat=scipy.matrix(mat.toNumPyArray()) + print ii,np.linalg.cond(mat) + y=scipy.matrix(y.toNumPyArray()) + y=y.transpose() + delta=np.linalg.solve(mat,-y) + #delta=scipy.sparse.linalg.gmres(mat,-y)[0] # cg + delta=DataArrayDouble(delta) ; delta.rearrange(7) + #p+=delta[0,:3] + #v+=delta[0,3:6] + #v/=v.magnitude()[0] + #r+=delta[0,6] + print ii,delta.getValues()#,yy.transpose().tolist() + + pass + +mat1=mat[[0,1,2,6]] +mat1=mat1.transpose() +mat1=mat1[[0,1,2,6]] +mat1=mat1.transpose() +mm=np.linalg.solve(mat1,y[[0,1,2,6]]) diff --git a/src/Plugins/DevelopedSurface/scripts/pp1.py b/src/Plugins/DevelopedSurface/scripts/pp1.py new file mode 100644 index 00000000..2eaf059a --- /dev/null +++ b/src/Plugins/DevelopedSurface/scripts/pp1.py @@ -0,0 +1,27 @@ +# Copyright (C) 2017-2019 EDF R&D +# +# This library 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. +# +# 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 +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +# +# Author : Anthony Geay (EDF R&D) + +from MEDLoader import * +from math import pi +mm=MEDFileMesh.New("example2.med") +c=mm.getCoords() +MEDCouplingUMesh.Rotate3DAlg([0,0,0],[1,1,0],pi/4,c) +c+=[3,2,0] +mm.write("example2_2.med",2) diff --git a/src/Plugins/DevelopedSurface/scripts/pp2.py b/src/Plugins/DevelopedSurface/scripts/pp2.py new file mode 100644 index 00000000..65783346 --- /dev/null +++ b/src/Plugins/DevelopedSurface/scripts/pp2.py @@ -0,0 +1,121 @@ +# Copyright (C) 2017-2019 EDF R&D +# +# This library 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. +# +# 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 +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +# +# Author : Anthony Geay (EDF R&D) + +from MEDLoader import * +from math import pi,asin,acos,atan2 +import numpy as np + +invertThetaInc=False + +mm=MEDFileMesh.New("example2_2.med") +c=mm.getCoords() + +v=DataArrayDouble([0.70710678118617443,-0.70710678118572623,1],1,3) +v/=v.magnitude()[0] +vRef=DataArrayDouble([0,0,1],1,3) +vRot=DataArrayDouble.CrossProduct(v,vRef) +ang=asin(vRot.magnitude()[0]) +MEDCouplingUMesh.Rotate3DAlg([0,0,0],vRot.getValues(),ang,c) + +c2=c[:,[0,1]] +# +a,b=c2.findCommonTuples(1e-5) +pool=c2[a[b[:-1]]] +probes=[pool[:,0].getMaxValue()[1],pool[:,1].getMaxValue()[1],pool[:,0].getMinValue()[1]] +center,radius,_=pool[probes].asArcOfCircle() +assert(((c2-center).magnitude()).isUniform(radius,1e-5)) +theta=((c2-center)/radius) +theta=DataArrayDouble([atan2(y,x) for x,y in theta]) +zeTheta=theta-theta[0] + +mm.write("tmp.med",2) +########### +c_cyl=DataArrayDouble.fromCartToCyl(c-(center+[0.])) +assert(c_cyl[:,0].isUniform(radius,1e-5)) +tetha0=c_cyl[0,1] +c_cyl[:,1]-=tetha0 +c_cyl_2=c_cyl[:,1] ; c_cyl_2.abs() +c_cyl[c_cyl_2.findIdsInRange(0.,1e-6),1]=0. +######## +m0=mm[0] +c0s=m0.getCellIdsLyingOnNodes([0],False) +assert(len(c0s)!=0) +tmp=c_cyl[m0.getNodeIdsOfCell(c0s[0]),1].getMaxAbsValueInArray() +a=tmp>0. +if a^(not invertThetaInc): + c_cyl[:,1]=-c_cyl[:,1] + pass +# +c_cyl_post=c_cyl[:,1] +m0.convertAllToPoly() +tmp=MEDCoupling1DGTUMesh(m0) ; c=tmp.getNodalConnectivity() ; ci=tmp.getNodalConnectivityIndex() +for elt in c_cyl_post: + if float(elt)<0: + elt[:]=float(elt)+2*pi + +nbCells=m0.getNumberOfCells() +nbNodes=m0.getNumberOfNodes() +newCoo=DataArrayInt(0,1) +cellsWithPb=[] +newConn=[] +for i in xrange(nbCells): + tmp=c_cyl_post[c[ci[i]:ci[i+1]]] + if tmp.getMaxValueInArray()-tmp.getMinValueInArray()>pi: + cellsWithPb.append(i) + # dup of low val + newLocConn=[] + for elt in c[ci[i]:ci[i+1]]: + if float(c_cyl_post[elt])<=pi: + newLocConn.append(nbNodes+len(newCoo)) + newCoo.pushBackSilent(int(elt)) + pass + else: + newLocConn.append(int(elt)) + pass + pass + newConn.append(newLocConn[:]) + pass + + +c_cyl_post=DataArrayDouble.Aggregate([c_cyl_post,c_cyl_post[newCoo]+2*pi]) +z_post=DataArrayDouble.Aggregate([c_cyl[:,2],c_cyl[newCoo,2]]) +newCoords=DataArrayDouble.Meld(radius*c_cyl_post,z_post) + +z=DataArrayInt([len(elt) for elt in newConn]) +z.computeOffsetsFull() +# +cellsWithPbMesh=MEDCoupling1DGTUMesh("",NORM_POLYGON) +cellsWithPbMesh.setNodalConnectivity(DataArrayInt(sum(newConn,[])),z) +cellsWithPbMesh.setCoords(newCoords) +# +ko_part_ids=DataArrayInt(cellsWithPb) +part_ids=ko_part_ids.buildComplement(nbCells) +part=m0[part_ids] +part.setCoords(newCoords) +whole=MEDCouplingUMesh.MergeUMeshesOnSameCoords([part,cellsWithPbMesh.buildUnstructured()]) + +o2n=DataArrayInt.Aggregate([part_ids,ko_part_ids]) +whole=whole[o2n.invertArrayO2N2N2O(len(o2n))] +whole.setName("mesh") +WriteMesh("tmp3.med",whole,True) + +#sk=m0.computeSkin().computeFetchedNodeIds() +#sk_part=part.computeSkin().computeFetchedNodeIds() +#m0[DataArrayInt(cellsWithPb)].computeFetchedNodeIds() diff --git a/src/Plugins/DevelopedSurface/scripts/test.py b/src/Plugins/DevelopedSurface/scripts/test.py new file mode 100644 index 00000000..f456fa47 --- /dev/null +++ b/src/Plugins/DevelopedSurface/scripts/test.py @@ -0,0 +1,139 @@ +# Copyright (C) 2017-2019 EDF R&D +# +# This library 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. +# +# 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 +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +# +# Author : Anthony Geay (EDF R&D) + +#### import the simple module from the paraview +from paraview.simple import * +#### disable automatic camera reset on 'Show' +paraview.simple._DisableFirstRenderCameraReset() + +# create a new 'Wavelet' +wavelet1 = Wavelet() + +# Properties modified on wavelet1 +wavelet1.WholeExtent = [0, 10, 0, 10, 0, 10] + +# get active view +renderView1 = GetActiveViewOrCreate('RenderView') +# uncomment following to set a specific view size +# renderView1.ViewSize = [1168, 582] + +# show data in view +wavelet1Display = Show(wavelet1, renderView1) + +# trace defaults for the display properties. +wavelet1Display.Representation = 'Outline' +wavelet1Display.ColorArrayName = ['POINTS', ''] +wavelet1Display.OSPRayScaleArray = 'RTData' +wavelet1Display.OSPRayScaleFunction = 'PiecewiseFunction' +wavelet1Display.SelectOrientationVectors = 'None' +wavelet1Display.SelectScaleArray = 'RTData' +wavelet1Display.GlyphType = 'Arrow' +wavelet1Display.GlyphTableIndexArray = 'RTData' +wavelet1Display.DataAxesGrid = 'GridAxesRepresentation' +wavelet1Display.PolarAxes = 'PolarAxesRepresentation' +wavelet1Display.ScalarOpacityUnitDistance = 1.7320508075688779 +wavelet1Display.Slice = 5 +wavelet1Display.GaussianRadius = 0.5 +wavelet1Display.SetScaleArray = ['POINTS', 'RTData'] +wavelet1Display.ScaleTransferFunction = 'PiecewiseFunction' +wavelet1Display.OpacityArray = ['POINTS', 'RTData'] +wavelet1Display.OpacityTransferFunction = 'PiecewiseFunction' +wavelet1Display.InputVectors = [None, ''] +wavelet1Display.SelectInputVectors = [None, ''] +wavelet1Display.WriteLog = '' + +# init the 'PiecewiseFunction' selected for 'ScaleTransferFunction' +wavelet1Display.ScaleTransferFunction.Points = [-16.577068328857422, 0.0, 0.5, 0.0, 260.0, 1.0, 0.5, 0.0] + +# init the 'PiecewiseFunction' selected for 'OpacityTransferFunction' +wavelet1Display.OpacityTransferFunction.Points = [-16.577068328857422, 0.0, 0.5, 0.0, 260.0, 1.0, 0.5, 0.0] + +# reset view to fit data +renderView1.ResetCamera() + +# update the view to ensure updated data information +renderView1.Update() + +# create a new 'Slice' +slice1 = Slice(Input=wavelet1) +slice1.SliceType = 'Plane' +slice1.SliceOffsetValues = [0.0] + +# init the 'Plane' selected for 'SliceType' +slice1.SliceType.Origin = [5.0, 5.0, 5.0] + +# toggle 3D widget visibility (only when running from the GUI) +Show3DWidgets(proxy=slice1.SliceType) + +# Properties modified on slice1 +slice1.SliceType = 'Cylinder' + +# show data in view +slice1Display = Show(slice1, renderView1) + +# get color transfer function/color map for 'RTData' +rTDataLUT = GetColorTransferFunction('RTData') + +# trace defaults for the display properties. +slice1Display.Representation = 'Surface' +slice1Display.ColorArrayName = ['POINTS', 'RTData'] +slice1Display.LookupTable = rTDataLUT +slice1Display.OSPRayScaleArray = 'RTData' +slice1Display.OSPRayScaleFunction = 'PiecewiseFunction' +slice1Display.SelectOrientationVectors = 'None' +slice1Display.SelectScaleArray = 'RTData' +slice1Display.GlyphType = 'Arrow' +slice1Display.GlyphTableIndexArray = 'RTData' +slice1Display.DataAxesGrid = 'GridAxesRepresentation' +slice1Display.PolarAxes = 'PolarAxesRepresentation' +slice1Display.GaussianRadius = 0.5 +slice1Display.SetScaleArray = ['POINTS', 'RTData'] +slice1Display.ScaleTransferFunction = 'PiecewiseFunction' +slice1Display.OpacityArray = ['POINTS', 'RTData'] +slice1Display.OpacityTransferFunction = 'PiecewiseFunction' +slice1Display.InputVectors = [None, ''] +slice1Display.SelectInputVectors = [None, ''] +slice1Display.WriteLog = '' + +# init the 'PiecewiseFunction' selected for 'ScaleTransferFunction' +slice1Display.ScaleTransferFunction.Points = [-14.761041641235352, 0.0, 0.5, 0.0, 232.8310546875, 1.0, 0.5, 0.0] + +# init the 'PiecewiseFunction' selected for 'OpacityTransferFunction' +slice1Display.OpacityTransferFunction.Points = [-14.761041641235352, 0.0, 0.5, 0.0, 232.8310546875, 1.0, 0.5, 0.0] + +# show color bar/color legend +slice1Display.SetScalarBarVisibility(renderView1, True) + +# update the view to ensure updated data information +renderView1.Update() + +# create a new 'Developed Surface' +developedSurface1 = DevelopedSurface(Input=slice1) + +#### saving camera placements for all active views + +# current camera placement for renderView1 +renderView1.CameraPosition = [5.0, 5.0, 38.46065214951232] +renderView1.CameraFocalPoint = [5.0, 5.0, 5.0] +renderView1.CameraParallelScale = 8.660254037844387 + +#### uncomment the following to render all views +# RenderAllViews() +# alternatively, if you want to write images, you can use SaveScreenshot(...). diff --git a/src/Plugins/DevelopedSurface/test.py b/src/Plugins/DevelopedSurface/test.py deleted file mode 100644 index f456fa47..00000000 --- a/src/Plugins/DevelopedSurface/test.py +++ /dev/null @@ -1,139 +0,0 @@ -# Copyright (C) 2017-2019 EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# -# Author : Anthony Geay (EDF R&D) - -#### import the simple module from the paraview -from paraview.simple import * -#### disable automatic camera reset on 'Show' -paraview.simple._DisableFirstRenderCameraReset() - -# create a new 'Wavelet' -wavelet1 = Wavelet() - -# Properties modified on wavelet1 -wavelet1.WholeExtent = [0, 10, 0, 10, 0, 10] - -# get active view -renderView1 = GetActiveViewOrCreate('RenderView') -# uncomment following to set a specific view size -# renderView1.ViewSize = [1168, 582] - -# show data in view -wavelet1Display = Show(wavelet1, renderView1) - -# trace defaults for the display properties. -wavelet1Display.Representation = 'Outline' -wavelet1Display.ColorArrayName = ['POINTS', ''] -wavelet1Display.OSPRayScaleArray = 'RTData' -wavelet1Display.OSPRayScaleFunction = 'PiecewiseFunction' -wavelet1Display.SelectOrientationVectors = 'None' -wavelet1Display.SelectScaleArray = 'RTData' -wavelet1Display.GlyphType = 'Arrow' -wavelet1Display.GlyphTableIndexArray = 'RTData' -wavelet1Display.DataAxesGrid = 'GridAxesRepresentation' -wavelet1Display.PolarAxes = 'PolarAxesRepresentation' -wavelet1Display.ScalarOpacityUnitDistance = 1.7320508075688779 -wavelet1Display.Slice = 5 -wavelet1Display.GaussianRadius = 0.5 -wavelet1Display.SetScaleArray = ['POINTS', 'RTData'] -wavelet1Display.ScaleTransferFunction = 'PiecewiseFunction' -wavelet1Display.OpacityArray = ['POINTS', 'RTData'] -wavelet1Display.OpacityTransferFunction = 'PiecewiseFunction' -wavelet1Display.InputVectors = [None, ''] -wavelet1Display.SelectInputVectors = [None, ''] -wavelet1Display.WriteLog = '' - -# init the 'PiecewiseFunction' selected for 'ScaleTransferFunction' -wavelet1Display.ScaleTransferFunction.Points = [-16.577068328857422, 0.0, 0.5, 0.0, 260.0, 1.0, 0.5, 0.0] - -# init the 'PiecewiseFunction' selected for 'OpacityTransferFunction' -wavelet1Display.OpacityTransferFunction.Points = [-16.577068328857422, 0.0, 0.5, 0.0, 260.0, 1.0, 0.5, 0.0] - -# reset view to fit data -renderView1.ResetCamera() - -# update the view to ensure updated data information -renderView1.Update() - -# create a new 'Slice' -slice1 = Slice(Input=wavelet1) -slice1.SliceType = 'Plane' -slice1.SliceOffsetValues = [0.0] - -# init the 'Plane' selected for 'SliceType' -slice1.SliceType.Origin = [5.0, 5.0, 5.0] - -# toggle 3D widget visibility (only when running from the GUI) -Show3DWidgets(proxy=slice1.SliceType) - -# Properties modified on slice1 -slice1.SliceType = 'Cylinder' - -# show data in view -slice1Display = Show(slice1, renderView1) - -# get color transfer function/color map for 'RTData' -rTDataLUT = GetColorTransferFunction('RTData') - -# trace defaults for the display properties. -slice1Display.Representation = 'Surface' -slice1Display.ColorArrayName = ['POINTS', 'RTData'] -slice1Display.LookupTable = rTDataLUT -slice1Display.OSPRayScaleArray = 'RTData' -slice1Display.OSPRayScaleFunction = 'PiecewiseFunction' -slice1Display.SelectOrientationVectors = 'None' -slice1Display.SelectScaleArray = 'RTData' -slice1Display.GlyphType = 'Arrow' -slice1Display.GlyphTableIndexArray = 'RTData' -slice1Display.DataAxesGrid = 'GridAxesRepresentation' -slice1Display.PolarAxes = 'PolarAxesRepresentation' -slice1Display.GaussianRadius = 0.5 -slice1Display.SetScaleArray = ['POINTS', 'RTData'] -slice1Display.ScaleTransferFunction = 'PiecewiseFunction' -slice1Display.OpacityArray = ['POINTS', 'RTData'] -slice1Display.OpacityTransferFunction = 'PiecewiseFunction' -slice1Display.InputVectors = [None, ''] -slice1Display.SelectInputVectors = [None, ''] -slice1Display.WriteLog = '' - -# init the 'PiecewiseFunction' selected for 'ScaleTransferFunction' -slice1Display.ScaleTransferFunction.Points = [-14.761041641235352, 0.0, 0.5, 0.0, 232.8310546875, 1.0, 0.5, 0.0] - -# init the 'PiecewiseFunction' selected for 'OpacityTransferFunction' -slice1Display.OpacityTransferFunction.Points = [-14.761041641235352, 0.0, 0.5, 0.0, 232.8310546875, 1.0, 0.5, 0.0] - -# show color bar/color legend -slice1Display.SetScalarBarVisibility(renderView1, True) - -# update the view to ensure updated data information -renderView1.Update() - -# create a new 'Developed Surface' -developedSurface1 = DevelopedSurface(Input=slice1) - -#### saving camera placements for all active views - -# current camera placement for renderView1 -renderView1.CameraPosition = [5.0, 5.0, 38.46065214951232] -renderView1.CameraFocalPoint = [5.0, 5.0, 5.0] -renderView1.CameraParallelScale = 8.660254037844387 - -#### uncomment the following to render all views -# RenderAllViews() -# alternatively, if you want to write images, you can use SaveScreenshot(...). diff --git a/src/Plugins/DifferenceTimesteps/CMakeLists.txt b/src/Plugins/DifferenceTimesteps/CMakeLists.txt index 9e849248..f851e446 100644 --- a/src/Plugins/DifferenceTimesteps/CMakeLists.txt +++ b/src/Plugins/DifferenceTimesteps/CMakeLists.txt @@ -1,36 +1,30 @@ -# Copyright (C) 2014-2019 CEA/DEN, EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# -# Author : Maxim Glibin +cmake_minimum_required(VERSION 3.8) +project(DifferenceTimesteps) +find_package(ParaView REQUIRED) -PROJECT(DifferenceTimesteps) +include(GNUInstallDirs) +set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_BINDIR}") +set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_LIBDIR}") +set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_LIBDIR}") -cmake_minimum_required(VERSION 2.8) +set("_paraview_plugin_default_${CMAKE_PROJECT_NAME}" ON) +paraview_plugin_scan( + ENABLE_BY_DEFAULT YES + PLUGIN_FILES "${CMAKE_CURRENT_SOURCE_DIR}/plugin/paraview.plugin" + PROVIDES_PLUGINS plugins + REQUIRES_MODULES required_modules) -FIND_PACKAGE(ParaView REQUIRED) -INCLUDE(${PARAVIEW_USE_FILE}) +foreach(module IN LISTS required_modules) + if(NOT TARGET "${module}") + message("Missing required module: ${module}") + return() + endif() +endforeach() -ADD_PARAVIEW_PLUGIN(DifferenceTimesteps "1.0" - SERVER_MANAGER_XML DifferenceTimesteps.xml - SERVER_MANAGER_SOURCES vtkDifferenceTimestepsFilter.cxx - GUI_RESOURCES pqDifferenceTimesteps.qrc - ) - -INSTALL(TARGETS DifferenceTimesteps - DESTINATION lib/paraview -) +set(BUILD_SHARED_LIBS ON) +paraview_plugin_build( + RUNTIME_DESTINATION "${CMAKE_INSTALL_BINDIR}" + LIBRARY_DESTINATION "${CMAKE_INSTALL_LIBDIR}" + LIBRARY_SUBDIRECTORY "${PARAVIEW_PLUGIN_SUBDIR}" + PLUGINS ${plugins} + AUTOLOAD ${plugins}) diff --git a/src/Plugins/DifferenceTimesteps/DifferenceTimesteps.xml b/src/Plugins/DifferenceTimesteps/DifferenceTimesteps.xml deleted file mode 100644 index 6acb5525..00000000 --- a/src/Plugins/DifferenceTimesteps/DifferenceTimesteps.xml +++ /dev/null @@ -1,131 +0,0 @@ - - - - - - - - - - - - - - - - - - This property specifies the input to DifferenceTimesteps filter. - - - - - - - - - - - This property indicates the scalar array name to compute difference. - - - - - - - Available timestep values. - - - - - - - - - - - - - - - Define a first time step. - - - - - - - - - - - Define a second time step. - - - - - - Prefix to a new array name. - - - - - - - - - - - - - - - - - - diff --git a/src/Plugins/DifferenceTimesteps/plugin.cmake b/src/Plugins/DifferenceTimesteps/plugin.cmake deleted file mode 100644 index 686ebde6..00000000 --- a/src/Plugins/DifferenceTimesteps/plugin.cmake +++ /dev/null @@ -1,3 +0,0 @@ -pv_plugin(DifferenceTimesteps - DESCRIPTION "Compute difference between two time steps" - DEFAULT_ENABLED) diff --git a/src/Plugins/DifferenceTimesteps/plugin/CMakeLists.txt b/src/Plugins/DifferenceTimesteps/plugin/CMakeLists.txt new file mode 100644 index 00000000..8d73d9b3 --- /dev/null +++ b/src/Plugins/DifferenceTimesteps/plugin/CMakeLists.txt @@ -0,0 +1,18 @@ +set(qrc_files) +if(PARAVIEW_USE_QT) + list(APPEND qrc_files pqDifferenceTimesteps.qrc) +endif() + +paraview_add_plugin(DifferenceTimesteps + VERSION "1.0" + UI_RESOURCES ${qrc_files} + MODULES DifferenceTimestepsModule + MODULE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/DifferenceTimestepsModule/vtk.module" + SERVER_MANAGER_XML filters.xml +) + +install(TARGETS DifferenceTimesteps + RUNTIME DESTINATION lib/paraview + LIBRARY DESTINATION lib/paraview + ARCHIVE DESTINATION lib/paraview + ) diff --git a/src/Plugins/DifferenceTimesteps/plugin/DifferenceTimestepsModule/CMakeLists.txt b/src/Plugins/DifferenceTimesteps/plugin/DifferenceTimestepsModule/CMakeLists.txt new file mode 100644 index 00000000..09bffebe --- /dev/null +++ b/src/Plugins/DifferenceTimesteps/plugin/DifferenceTimestepsModule/CMakeLists.txt @@ -0,0 +1,8 @@ +set(classes + vtkDifferenceTimestepsFilter +) + +vtk_module_add_module(DifferenceTimestepsModule + FORCE_STATIC + CLASSES ${classes} +) diff --git a/src/Plugins/DifferenceTimesteps/plugin/DifferenceTimestepsModule/vtk.module b/src/Plugins/DifferenceTimesteps/plugin/DifferenceTimestepsModule/vtk.module new file mode 100644 index 00000000..6deb4721 --- /dev/null +++ b/src/Plugins/DifferenceTimesteps/plugin/DifferenceTimestepsModule/vtk.module @@ -0,0 +1,11 @@ +NAME + DifferenceTimestepsModule +DEPENDS + VTK::CommonCore + VTK::CommonDataModel + VTK::CommonExecutionModel + VTK::FiltersCore +PRIVATE_DEPENDS + VTK::CommonMisc + VTK::CommonSystem + VTK::FiltersGeneral diff --git a/src/Plugins/DifferenceTimesteps/plugin/DifferenceTimestepsModule/vtkDifferenceTimestepsFilter.cxx b/src/Plugins/DifferenceTimesteps/plugin/DifferenceTimestepsModule/vtkDifferenceTimestepsFilter.cxx new file mode 100644 index 00000000..6953fbbd --- /dev/null +++ b/src/Plugins/DifferenceTimesteps/plugin/DifferenceTimestepsModule/vtkDifferenceTimestepsFilter.cxx @@ -0,0 +1,499 @@ +// Copyright (C) 2014-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Maxim Glibin + +#include "vtkDifferenceTimestepsFilter.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// Temporal difference of data array +vtkDataArray* DataTempDiffArray( + vtkDataArray* theDataArray, vtkIdType theNumComp, vtkIdType theNumTuple, const char* thePrefix) +{ + // Create the new array + vtkAbstractArray* anAbstractArray = theDataArray->CreateArray(theDataArray->GetDataType()); + vtkDataArray* anOutput = vtkDataArray::SafeDownCast(anAbstractArray); + + // Initialize and appoint a new name + anOutput->SetNumberOfComponents(theNumComp); + anOutput->SetNumberOfTuples(theNumTuple); + std::string aNewName = std::string(thePrefix) + theDataArray->GetName(); + anOutput->SetName(aNewName.c_str()); + + return anOutput; +} + +// Templated difference function +template +void vtkTemporalDataDifference(vtkDifferenceTimestepsFilter* theDTF, vtkDataArray* theOutput, + vtkDataArray** theArrays, vtkIdType theNumComp, T*) +{ + T* anOutputData = static_cast(theOutput->GetVoidPointer(0)); + T* anInputData0 = static_cast(theArrays[0]->GetVoidPointer(0)); + T* anInputData1 = static_cast(theArrays[1]->GetVoidPointer(0)); + + vtkIdType N = theArrays[0]->GetNumberOfTuples(); + for (vtkIdType t = 0; t < N; ++t) + { + T* x0 = &anInputData0[t * theNumComp]; + T* x1 = &anInputData1[t * theNumComp]; + for (int c = 0; c < theNumComp; ++c) + { + // Compute the difference + *anOutputData++ = static_cast(x1[c] - x0[c]); + } + } + // Copy component name + for (int c = 0; c < theNumComp; ++c) + { + theOutput->SetComponentName(c, theArrays[0]->GetComponentName(c)); + } + theOutput->SetNumberOfTuples(N); +} + +vtkStandardNewMacro(vtkDifferenceTimestepsFilter); + +//-------------------------------------------------------------------------------------------------- +vtkDifferenceTimestepsFilter::vtkDifferenceTimestepsFilter() +{ + this->NumberTimeSteps = 0; + this->RangeIndicesTimeSteps[0] = 0; + this->RangeIndicesTimeSteps[1] = 0; + this->FirstTimeStepIndex = 0.0; + this->SecondTimeStepIndex = 0.0; + this->TimeStepValues.clear(); + this->ArrayNamePrefix = nullptr; + + this->SetNumberOfInputPorts(1); + this->SetNumberOfOutputPorts(1); + + // Set the input data array that the algorithm will process + this->SetInputArrayToProcess( + 0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_POINTS, vtkDataSetAttributes::SCALARS); +} + +//-------------------------------------------------------------------------------------------------- +vtkDifferenceTimestepsFilter::~vtkDifferenceTimestepsFilter() +{ + this->TimeStepValues.clear(); + this->SetArrayNamePrefix(nullptr); +} + +//-------------------------------------------------------------------------------------------------- +void vtkDifferenceTimestepsFilter::PrintSelf(ostream& theOS, vtkIndent theIndent) +{ + this->Superclass::PrintSelf(theOS, theIndent); + theOS << theIndent << "Number of time steps : " << this->NumberTimeSteps << endl; + theOS << theIndent << "First time step : " << this->FirstTimeStepIndex << endl; + theOS << theIndent << "Second time step : " << this->SecondTimeStepIndex << endl; + theOS << theIndent << "Field association : " + << vtkDataObject::GetAssociationTypeAsString(this->GetInputFieldAssociation()) << endl; +} + +//-------------------------------------------------------------------------------------------------- +int vtkDifferenceTimestepsFilter::FillInputPortInformation(int thePort, vtkInformation* theInfo) +{ + if (thePort == 0) + theInfo->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkDataObject"); + + return 1; +} + +//-------------------------------------------------------------------------------------------------- +int vtkDifferenceTimestepsFilter::FillOutputPortInformation( + int vtkNotUsed(thePort), vtkInformation* theInfo) +{ + theInfo->Set(vtkDataObject::DATA_TYPE_NAME(), "vtkDataObject"); + return 1; +} + +//-------------------------------------------------------------------------------------------------- +int vtkDifferenceTimestepsFilter::RequestDataObject(vtkInformation* vtkNotUsed(theRequest), + vtkInformationVector** theInputVector, vtkInformationVector* theOutputVector) +{ + if (this->GetNumberOfInputPorts() == 0 || this->GetNumberOfOutputPorts() == 0) + return 1; + + vtkInformation* anInputInfo = theInputVector[0]->GetInformationObject(0); + if (anInputInfo == nullptr) + { + vtkErrorMacro(<< "Input information vector is missed."); + return 0; + } + + vtkDataObject* anInputObj = anInputInfo->Get(vtkDataObject::DATA_OBJECT()); + if (anInputObj != nullptr) + { + // For each output + for (int i = 0; i < this->GetNumberOfOutputPorts(); ++i) + { + vtkInformation* anOutputInfo = theOutputVector->GetInformationObject(i); + vtkDataObject* anOutputObj = anOutputInfo->Get(vtkDataObject::DATA_OBJECT()); + if (!anOutputObj || !anOutputObj->IsA(anInputObj->GetClassName())) + { + vtkDataObject* aNewOutput = anInputObj->NewInstance(); + anOutputInfo->Set(vtkDataObject::DATA_OBJECT(), aNewOutput); + aNewOutput->Delete(); + } + } + return 1; + } + return 0; +} + +//-------------------------------------------------------------------------------------------------- +int vtkDifferenceTimestepsFilter::RequestInformation(vtkInformation* vtkNotUsed(theRequest), + vtkInformationVector** theInputVector, vtkInformationVector* theOutputVector) +{ + // Get input and output information objects + vtkInformation* anInInfo = theInputVector[0]->GetInformationObject(0); + vtkInformation* anOutInfo = theOutputVector->GetInformationObject(0); + + // Check for presence more than one time step + if (anInInfo->Has(vtkStreamingDemandDrivenPipeline::TIME_STEPS())) + { + // Find time on input + this->NumberTimeSteps = anInInfo->Length(vtkStreamingDemandDrivenPipeline::TIME_STEPS()); + if (this->NumberTimeSteps < 2) + { + vtkErrorMacro(<< "Not enough numbers of time steps: " << this->NumberTimeSteps); + return 0; + } + // Get time step values + this->TimeStepValues.resize(this->NumberTimeSteps); + anInInfo->Get(vtkStreamingDemandDrivenPipeline::TIME_STEPS(), &this->TimeStepValues[0]); + if (this->TimeStepValues.size() == 0) + { + vtkErrorMacro(<< "Array of time steps is empty."); + return 0; + } + } + else + { + vtkErrorMacro(<< "No time steps in input data."); + return 0; + } + + // Update range of indices of the time steps + this->RangeIndicesTimeSteps[0] = 0; + this->RangeIndicesTimeSteps[1] = this->NumberTimeSteps - 1; + + /* + * RNV: Temporary commented: + * This piece of the code removes all time steps from the output object, + * but this leads to the strange side effect in the ParaView: time steps also disappears + * from the animation scene of the input (parent) object of this filter. + * Seems it is a bug of the ParaView, to be investigated ... + * + // The output data of this filter has no time associated with it. + // It is the result of computation difference between two time steps. + // Unset the time steps + if (anOutInfo->Has(vtkStreamingDemandDrivenPipeline::TIME_STEPS())) + anOutInfo->Remove(vtkStreamingDemandDrivenPipeline::TIME_STEPS()); + + // Unset the time range + if(anOutInfo->Has(vtkStreamingDemandDrivenPipeline::TIME_RANGE())) + anOutInfo->Remove(vtkStreamingDemandDrivenPipeline::TIME_RANGE()); + */ + return 1; +} + +//-------------------------------------------------------------------------------------------------- +int vtkDifferenceTimestepsFilter::RequestUpdateExtent(vtkInformation* theRequest, + vtkInformationVector** theInputVector, vtkInformationVector* theOutputVector) +{ + // Get the information objects + vtkInformation* anInputInfo = theInputVector[0]->GetInformationObject(0); + vtkInformation* anOutputInfo = theOutputVector->GetInformationObject(0); + + // Indices must not go beyond the range of indices of the time steps + if (this->FirstTimeStepIndex >= this->NumberTimeSteps || this->FirstTimeStepIndex < 0) + { + vtkErrorMacro(<< "Specified index of the first time step [" << this->FirstTimeStepIndex + << "] is outside the range of indices."); + return 0; + } + if (this->SecondTimeStepIndex >= this->NumberTimeSteps || this->SecondTimeStepIndex < 0) + { + vtkErrorMacro(<< "Specified index of the second time step [" << this->SecondTimeStepIndex + << "] is outside the range of indices."); + return 0; + } + + // Warn if the selected time steps are equal + if (this->FirstTimeStepIndex == this->SecondTimeStepIndex) + { + vtkWarningMacro(<< "First and second indices [" << this->FirstTimeStepIndex << " = " + << this->SecondTimeStepIndex << "] are the same."); + } + + // Find the required input time steps and request them + if (anOutputInfo->Has(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP())) + { + // Get the available input times + double* anInputTimes = anInputInfo->Get(vtkStreamingDemandDrivenPipeline::TIME_STEPS()); + if (anInputTimes != nullptr) + { + // Compute the requested times + double anInputUpdateTimes[2]; + int aNumberInputUpdateTimes(0); + + // For each the requested time mark the required input times + anInputUpdateTimes[aNumberInputUpdateTimes++] = anInputTimes[this->FirstTimeStepIndex]; + anInputUpdateTimes[aNumberInputUpdateTimes++] = anInputTimes[this->SecondTimeStepIndex]; + + // Make the multiple time requests upstream and use set of time-stamped data + // objects are stored in time order in a vtkMultiBlockDataSet object + anInputInfo->Set(vtkMultiTimeStepAlgorithm::UPDATE_TIME_STEPS(), anInputUpdateTimes, + aNumberInputUpdateTimes); + } + } + return 1; +} + +//-------------------------------------------------------------------------------------------------- +int vtkDifferenceTimestepsFilter::RequestData(vtkInformation* vtkNotUsed(theRequest), + vtkInformationVector** theInputVector, vtkInformationVector* theOutputVector) +{ + // Get the information objects + vtkInformation* anInputInfo = theInputVector[0]->GetInformationObject(0); + vtkInformation* anOutputInfo = theOutputVector->GetInformationObject(0); + + vtkDataObject* anOutputDataObj = nullptr; + + vtkMultiBlockDataSet* anInputData = + vtkMultiBlockDataSet::SafeDownCast(anInputInfo->Get(vtkDataObject::DATA_OBJECT())); + + int aNumberTimeSteps = anInputData->GetNumberOfBlocks(); + if (aNumberTimeSteps == 2) + { + // Get data objects + vtkDataObject* aData0 = anInputData->GetBlock(0); + vtkDataObject* aData1 = anInputData->GetBlock(1); + if (aData0 == nullptr && aData1 == nullptr) + { + vtkErrorMacro(<< "Null data set."); + return 0; + } + + // Compute difference between two objects + anOutputDataObj = this->DifferenceDataObject(aData0, aData1); + anOutputInfo->Set(vtkDataObject::DATA_OBJECT(), anOutputDataObj); + if (anOutputDataObj != nullptr) + anOutputDataObj->Delete(); + } + else + { + vtkErrorMacro(<< "The amount of time blocks is not correct: " << aNumberTimeSteps); + return 0; + } + + return 1; +} + +//-------------------------------------------------------------------------------------------------- +vtkDataObject* vtkDifferenceTimestepsFilter::DifferenceDataObject( + vtkDataObject* theInput1, vtkDataObject* theInput2) +{ + // Determine the input object type + if (theInput1->IsA("vtkDataSet")) + { + vtkDataSet* anInDataSet1 = vtkDataSet::SafeDownCast(theInput1); + vtkDataSet* anInDataSet2 = vtkDataSet::SafeDownCast(theInput2); + return this->DifferenceDataSet(anInDataSet1, anInDataSet2); + } + else if (theInput1->IsA("vtkCompositeDataSet")) + { + // It is essential that aMGDataSet[0] an aMGDataSet[1] has the same structure. + vtkCompositeDataSet* aMGDataSet[2]; + aMGDataSet[0] = vtkCompositeDataSet::SafeDownCast(theInput1); + aMGDataSet[1] = vtkCompositeDataSet::SafeDownCast(theInput2); + + vtkCompositeDataSet* anOutput = aMGDataSet[0]->NewInstance(); + anOutput->CopyStructure(aMGDataSet[0]); + + vtkSmartPointer anIter; + anIter.TakeReference(aMGDataSet[0]->NewIterator()); + for (anIter->InitTraversal(); !anIter->IsDoneWithTraversal(); anIter->GoToNextItem()) + { + vtkDataObject* aDataObj1 = anIter->GetCurrentDataObject(); + vtkDataObject* aDataObj2 = aMGDataSet[1]->GetDataSet(anIter); + if (aDataObj1 == nullptr || aDataObj2 == nullptr) + { + vtkWarningMacro("The composite datasets were not identical in structure."); + continue; + } + + vtkDataObject* aResultDObj = this->DifferenceDataObject(aDataObj1, aDataObj2); + if (aResultDObj != nullptr) + { + anOutput->SetDataSet(anIter, aResultDObj); + aResultDObj->Delete(); + } + else + { + vtkErrorMacro(<< "Unexpected error during computation of the difference."); + return nullptr; + } + } + return anOutput; + } + else + { + vtkErrorMacro("We cannot yet compute difference of this type of dataset."); + return nullptr; + } +} + +//-------------------------------------------------------------------------------------------------- +vtkDataSet* vtkDifferenceTimestepsFilter::DifferenceDataSet( + vtkDataSet* theInput1, vtkDataSet* theInput2) +{ + vtkDataSet* anInput[2]; + anInput[0] = theInput1; + anInput[1] = theInput2; + + // Copy input structure into output + vtkDataSet* anOutput = anInput[0]->NewInstance(); + anOutput->CopyStructure(anInput[0]); + + std::vector anArrays; + vtkDataArray* anOutputArray; + + // Compute the difference of the the specified point or cell data array + vtkDataArray* aDataArray0 = this->GetInputArrayToProcess(0, anInput[0]); + vtkDataArray* aDataArray1 = this->GetInputArrayToProcess(0, anInput[1]); + if (aDataArray0 == nullptr || aDataArray1 == nullptr) + { + vtkErrorMacro(<< "Input array to process is empty."); + return nullptr; + } + anArrays.push_back(aDataArray0); + anArrays.push_back(aDataArray1); + + if (anArrays.size() > 1) + { + if (!this->VerifyArrays(&anArrays[0], 2)) + { + vtkErrorMacro(<< "Verification of data arrays has failed."); + return nullptr; + } + + anOutputArray = this->DifferenceDataArray(&anArrays[0], anArrays[0]->GetNumberOfTuples()); + // Determine a field association + int aTypeFieldAssociation = this->GetInputFieldAssociation(); + if (aTypeFieldAssociation == vtkDataObject::FIELD_ASSOCIATION_POINTS) + { + // For point data + anOutput->GetPointData()->AddArray(anOutputArray); + } + else if (aTypeFieldAssociation == vtkDataObject::FIELD_ASSOCIATION_CELLS) + { + // For cell data + anOutput->GetCellData()->AddArray(anOutputArray); + } + else + { + vtkErrorMacro(<< "Solution is not implemeted yet."); + return nullptr; + } + anOutputArray->Delete(); + anArrays.clear(); + } + + return anOutput; +} + +//-------------------------------------------------------------------------------------------------- +vtkDataArray* vtkDifferenceTimestepsFilter::DifferenceDataArray( + vtkDataArray** theArrays, vtkIdType theNumTuple) +{ + // Create the output array based on the number of tuple and components + // with a new name containing the specified prefix + int aNumComp = theArrays[0]->GetNumberOfComponents(); + vtkDataArray* anOutput = + DataTempDiffArray(theArrays[0], aNumComp, theNumTuple, this->ArrayNamePrefix); + + // Now do the computation of the difference + switch (theArrays[0]->GetDataType()) + { + vtkTemplateMacro( + vtkTemporalDataDifference(this, anOutput, theArrays, aNumComp, static_cast(0))); + default: + vtkErrorMacro(<< "Execute: unknown scalar type."); + return nullptr; + } + + return anOutput; +} + +//-------------------------------------------------------------------------------------------------- +int vtkDifferenceTimestepsFilter::GetInputFieldAssociation() +{ + vtkInformationVector* anInputArrayVec = this->GetInformation()->Get(INPUT_ARRAYS_TO_PROCESS()); + vtkInformation* anInputArrayInfo = anInputArrayVec->GetInformationObject(0); + return anInputArrayInfo->Get(vtkDataObject::FIELD_ASSOCIATION()); +} + +//-------------------------------------------------------------------------------------------------- +bool vtkDifferenceTimestepsFilter::VerifyArrays(vtkDataArray** theArrays, int theNumArrays) +{ + // Get all required data to compare with other + const char* anArrayName = theArrays[0]->GetName(); + vtkIdType aNumTuples = theArrays[0]->GetNumberOfTuples(); + vtkIdType aNumComponents = theArrays[0]->GetNumberOfComponents(); + + for (int i = 1; i < theNumArrays; ++i) + { + if (strcmp(theArrays[i]->GetName(), anArrayName) != 0) + { + vtkWarningMacro(<< "Computation of difference aborted for dataset because " + << "the array name in each time step are different."); + return false; + } + + if (theArrays[i]->GetNumberOfTuples() != aNumTuples) + { + vtkWarningMacro(<< "Computation of difference aborted for dataset because " + << "the number of tuples in each time step are different."); + return false; + } + + if (theArrays[i]->GetNumberOfComponents() != aNumComponents) + { + vtkWarningMacro(<< "Computation of difference aborted for dataset because " + << "the number of components in each time step are different."); + return false; + } + } + + return true; +} diff --git a/src/Plugins/DifferenceTimesteps/plugin/DifferenceTimestepsModule/vtkDifferenceTimestepsFilter.h b/src/Plugins/DifferenceTimesteps/plugin/DifferenceTimestepsModule/vtkDifferenceTimestepsFilter.h new file mode 100644 index 00000000..79fd79b4 --- /dev/null +++ b/src/Plugins/DifferenceTimesteps/plugin/DifferenceTimestepsModule/vtkDifferenceTimestepsFilter.h @@ -0,0 +1,137 @@ +// Copyright (C) 2014-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Maxim Glibin + +#ifndef __DifferenceTimestepsFilter_h_ +#define __DifferenceTimestepsFilter_h_ + +#include + +#include + +class vtkDataSet; +class vtkStringArray; + +/** + * Description of class: + * Class allows to compute difference between two time steps of one data array (field). + */ +class VTK_EXPORT vtkDifferenceTimestepsFilter : public vtkMultiTimeStepAlgorithm +{ +public: + /// Returns pointer on a new instance of the class + static vtkDifferenceTimestepsFilter* New(); + + vtkTypeMacro(vtkDifferenceTimestepsFilter, vtkMultiTimeStepAlgorithm); + + /// Prints current state of the objects + void PrintSelf(ostream&, vtkIndent) override; + + // Description: + // Set/Get methods for first time step. + vtkSetMacro(FirstTimeStepIndex, int); + vtkGetMacro(FirstTimeStepIndex, int); + + // Description: + // Set/Get methods for first time step. + vtkSetMacro(SecondTimeStepIndex, int); + vtkGetMacro(SecondTimeStepIndex, int); + + // Description: + // Get methods for range of indices of time steps. + vtkGetVector2Macro(RangeIndicesTimeSteps, int); + + // Description: + // Set/Get methods for prefix of array name. + vtkSetStringMacro(ArrayNamePrefix); + vtkGetStringMacro(ArrayNamePrefix); + +protected: + /// Constructor & destructor + vtkDifferenceTimestepsFilter(); + ~vtkDifferenceTimestepsFilter() override; + + /// The methods which is called on filtering data + int FillInputPortInformation(int, vtkInformation*) override; + + int FillOutputPortInformation(int, vtkInformation*) override; + + int RequestDataObject(vtkInformation*, vtkInformationVector**, vtkInformationVector*) override; + + int RequestInformation(vtkInformation*, vtkInformationVector**, vtkInformationVector*) override; + + int RequestUpdateExtent(vtkInformation*, vtkInformationVector**, vtkInformationVector*) override; + + int RequestData(vtkInformation*, vtkInformationVector**, vtkInformationVector*) override; + + // Description: + // General computation differences routine for any type on input data. This + // is called recursively when heirarchical/multiblock data is encountered. + vtkDataObject* DifferenceDataObject(vtkDataObject* theInput1, vtkDataObject* theInput2); + + // Description: + // Root level interpolation for a concrete dataset object. + // Point/Cell data and points are different. + // Needs improving if connectivity is to be handled. + virtual vtkDataSet* DifferenceDataSet(vtkDataSet* theInput1, vtkDataSet* theInput2); + + // Description: + // Compute difference a single vtkDataArray. Called from computation + // of the difference routine on pointdata or celldata. + virtual vtkDataArray* DifferenceDataArray(vtkDataArray** theArrays, vtkIdType theN); + + // Description: + // Range of indices of the time steps. + int RangeIndicesTimeSteps[2]; + + // Description: + // First time step index. + int FirstTimeStepIndex; + + // Description: + // Second time step index. + int SecondTimeStepIndex; + + // Description: + // Length of time steps array + int NumberTimeSteps; + + // Description: + // Array of time step values. + std::vector TimeStepValues; + + // Description: + // Prefix of array name. + char* ArrayNamePrefix; + +private: + vtkDifferenceTimestepsFilter(const vtkDifferenceTimestepsFilter&) = delete; + void operator=(const vtkDifferenceTimestepsFilter&) = delete; + + // Description: + // Get field association type. + int GetInputFieldAssociation(); + + // Description: + // Called just before computation of the difference of the dataset to ensure that + // each data array has the same array name, number of tuples or components and etc. + bool VerifyArrays(vtkDataArray** theArrays, int theNumArrays); +}; + +#endif // __DifferenceTimestepsFilter_h_ diff --git a/src/Plugins/DifferenceTimesteps/plugin/filters.xml b/src/Plugins/DifferenceTimesteps/plugin/filters.xml new file mode 100644 index 00000000..6acb5525 --- /dev/null +++ b/src/Plugins/DifferenceTimesteps/plugin/filters.xml @@ -0,0 +1,131 @@ + + + + + + + + + + + + + + + + + + This property specifies the input to DifferenceTimesteps filter. + + + + + + + + + + + This property indicates the scalar array name to compute difference. + + + + + + + Available timestep values. + + + + + + + + + + + + + + + Define a first time step. + + + + + + + + + + + Define a second time step. + + + + + + Prefix to a new array name. + + + + + + + + + + + + + + + + + + diff --git a/src/Plugins/DifferenceTimesteps/plugin/paraview.plugin b/src/Plugins/DifferenceTimesteps/plugin/paraview.plugin new file mode 100644 index 00000000..e4267d7d --- /dev/null +++ b/src/Plugins/DifferenceTimesteps/plugin/paraview.plugin @@ -0,0 +1,8 @@ +NAME + DifferenceTimesteps +DESCRIPTION + Compute difference between two time steps +REQUIRES_MODULES + VTK::CommonCore + VTK::IOCore + VTK::FiltersCore diff --git a/src/Plugins/DifferenceTimesteps/plugin/pqDifferenceTimesteps.qrc b/src/Plugins/DifferenceTimesteps/plugin/pqDifferenceTimesteps.qrc new file mode 100644 index 00000000..85fa5c3e --- /dev/null +++ b/src/Plugins/DifferenceTimesteps/plugin/pqDifferenceTimesteps.qrc @@ -0,0 +1,5 @@ + + + resources/timesteps-icon.png + + diff --git a/src/Plugins/DifferenceTimesteps/plugin/resources/timesteps-icon.png b/src/Plugins/DifferenceTimesteps/plugin/resources/timesteps-icon.png new file mode 100644 index 00000000..28feea5c Binary files /dev/null and b/src/Plugins/DifferenceTimesteps/plugin/resources/timesteps-icon.png differ diff --git a/src/Plugins/DifferenceTimesteps/pqDifferenceTimesteps.qrc b/src/Plugins/DifferenceTimesteps/pqDifferenceTimesteps.qrc deleted file mode 100644 index 85fa5c3e..00000000 --- a/src/Plugins/DifferenceTimesteps/pqDifferenceTimesteps.qrc +++ /dev/null @@ -1,5 +0,0 @@ - - - resources/timesteps-icon.png - - diff --git a/src/Plugins/DifferenceTimesteps/resources/timesteps-icon.png b/src/Plugins/DifferenceTimesteps/resources/timesteps-icon.png deleted file mode 100644 index 28feea5c..00000000 Binary files a/src/Plugins/DifferenceTimesteps/resources/timesteps-icon.png and /dev/null differ diff --git a/src/Plugins/DifferenceTimesteps/vtkDifferenceTimestepsFilter.cxx b/src/Plugins/DifferenceTimesteps/vtkDifferenceTimestepsFilter.cxx deleted file mode 100644 index f1e8a18c..00000000 --- a/src/Plugins/DifferenceTimesteps/vtkDifferenceTimestepsFilter.cxx +++ /dev/null @@ -1,520 +0,0 @@ -// Copyright (C) 2014-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Maxim Glibin - -#include "vtkDifferenceTimestepsFilter.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -// Temporal difference of data array -vtkDataArray* DataTempDiffArray(vtkDataArray* theDataArray, - vtkIdType theNumComp, - vtkIdType theNumTuple, - const char* thePrefix) -{ - // Create the new array - vtkAbstractArray *anAbstractArray = theDataArray->CreateArray(theDataArray->GetDataType()); - vtkDataArray *anOutput = vtkDataArray::SafeDownCast(anAbstractArray); - - // Initialize and appoint a new name - anOutput->SetNumberOfComponents(theNumComp); - anOutput->SetNumberOfTuples(theNumTuple); - std::string aNewName = std::string(thePrefix) + theDataArray->GetName(); - anOutput->SetName(aNewName.c_str()); - - return anOutput; -} - -// Templated difference function -template -void vtkTemporalDataDifference( - vtkDifferenceTimestepsFilter* theDTF, - vtkDataArray* theOutput, - vtkDataArray** theArrays, - vtkIdType theNumComp, - T *) -{ - T* anOutputData = static_cast(theOutput->GetVoidPointer(0)); - T* anInputData0 = static_cast(theArrays[0]->GetVoidPointer(0)); - T* anInputData1 = static_cast(theArrays[1]->GetVoidPointer(0)); - - vtkIdType N = theArrays[0]->GetNumberOfTuples(); - for (vtkIdType t = 0; t < N; ++t) - { - T* x0 = &anInputData0[t*theNumComp]; - T* x1 = &anInputData1[t*theNumComp]; - for (int c = 0; c < theNumComp; ++c) - { - // Compute the difference - *anOutputData++ = static_cast(x1[c]-x0[c]); - } - } - // Copy component name - for (int c = 0; c < theNumComp; ++c) - { - theOutput->SetComponentName(c,theArrays[0]->GetComponentName(c)); - } - theOutput->SetNumberOfTuples(N); -} - -vtkStandardNewMacro(vtkDifferenceTimestepsFilter); - -//-------------------------------------------------------------------------------------------------- -vtkDifferenceTimestepsFilter::vtkDifferenceTimestepsFilter() -{ - this->NumberTimeSteps = 0; - this->RangeIndicesTimeSteps[0] = 0; - this->RangeIndicesTimeSteps[1] = 0; - this->FirstTimeStepIndex = 0.0; - this->SecondTimeStepIndex = 0.0; - this->TimeStepValues.clear(); - this->ArrayNamePrefix = NULL; - - this->SetNumberOfInputPorts(1); - this->SetNumberOfOutputPorts(1); - - // Set the input data array that the algorithm will process - this->SetInputArrayToProcess( - 0, - 0, - 0, - vtkDataObject::FIELD_ASSOCIATION_POINTS, - vtkDataSetAttributes::SCALARS); -} - -//-------------------------------------------------------------------------------------------------- -vtkDifferenceTimestepsFilter::~vtkDifferenceTimestepsFilter() -{ - this->TimeStepValues.clear(); - this->SetArrayNamePrefix(NULL); -} - -//-------------------------------------------------------------------------------------------------- -void vtkDifferenceTimestepsFilter::PrintSelf(ostream& theOS, vtkIndent theIndent) -{ - this->Superclass::PrintSelf(theOS, theIndent); - theOS << theIndent << "Number of time steps : " << this->NumberTimeSteps << endl; - theOS << theIndent << "First time step : " << this->FirstTimeStepIndex << endl; - theOS << theIndent << "Second time step : " << this->SecondTimeStepIndex << endl; - theOS << theIndent << "Field association : " - << vtkDataObject::GetAssociationTypeAsString(this->GetInputFieldAssociation()) << endl; -} - -//-------------------------------------------------------------------------------------------------- -int vtkDifferenceTimestepsFilter::FillInputPortInformation( - int thePort, vtkInformation* theInfo) -{ - if (thePort == 0) - theInfo->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkDataObject"); - - return 1; -} - -//-------------------------------------------------------------------------------------------------- -int vtkDifferenceTimestepsFilter::FillOutputPortInformation( - int vtkNotUsed(thePort), vtkInformation* theInfo) -{ - theInfo->Set(vtkDataObject::DATA_TYPE_NAME(), "vtkDataObject"); - return 1; -} - -//-------------------------------------------------------------------------------------------------- -int vtkDifferenceTimestepsFilter::RequestDataObject( - vtkInformation* vtkNotUsed(theRequest), - vtkInformationVector** theInputVector, - vtkInformationVector* theOutputVector) -{ - if (this->GetNumberOfInputPorts() == 0 || this->GetNumberOfOutputPorts() == 0) - return 1; - - vtkInformation* anInputInfo = theInputVector[0]->GetInformationObject(0); - if (anInputInfo == NULL) - { - vtkErrorMacro(<< "Input information vector is missed."); - return 0; - } - - vtkDataObject *anInputObj = anInputInfo->Get(vtkDataObject::DATA_OBJECT()); - if (anInputObj != NULL) - { - // For each output - for (int i = 0; i < this->GetNumberOfOutputPorts(); ++i) - { - vtkInformation* anOutputInfo = theOutputVector->GetInformationObject(i); - vtkDataObject *anOutputObj = anOutputInfo->Get(vtkDataObject::DATA_OBJECT()); - if (!anOutputObj || !anOutputObj->IsA(anInputObj->GetClassName())) - { - vtkDataObject* aNewOutput = anInputObj->NewInstance(); - anOutputInfo->Set(vtkDataObject::DATA_OBJECT(), aNewOutput); - aNewOutput->Delete(); - } - } - return 1; - } - return 0; -} - -//-------------------------------------------------------------------------------------------------- -int vtkDifferenceTimestepsFilter::RequestInformation( - vtkInformation* vtkNotUsed(theRequest), - vtkInformationVector** theInputVector, - vtkInformationVector* theOutputVector) -{ - // Get input and output information objects - vtkInformation *anInInfo = theInputVector[0]->GetInformationObject(0); - vtkInformation *anOutInfo = theOutputVector->GetInformationObject(0); - - // Check for presence more than one time step - if (anInInfo->Has(vtkStreamingDemandDrivenPipeline::TIME_STEPS())) - { - // Find time on input - this->NumberTimeSteps = anInInfo->Length(vtkStreamingDemandDrivenPipeline::TIME_STEPS()); - if (this->NumberTimeSteps < 2) - { - vtkErrorMacro(<< "Not enough numbers of time steps: " << this->NumberTimeSteps); - return 0; - } - // Get time step values - this->TimeStepValues.resize(this->NumberTimeSteps); - anInInfo->Get(vtkStreamingDemandDrivenPipeline::TIME_STEPS(), &this->TimeStepValues[0]); - if (this->TimeStepValues.size() == 0) - { - vtkErrorMacro(<<"Array of time steps is empty."); - return 0; - } - } - else - { - vtkErrorMacro(<< "No time steps in input data."); - return 0; - } - - // Update range of indices of the time steps - this->RangeIndicesTimeSteps[0] = 0; - this->RangeIndicesTimeSteps[1] = this->NumberTimeSteps - 1; - - /* - * RNV: Temporary commented: - * This piece of the code removes all time steps from the output object, - * but this leads to the strange side effect in the ParaView: time steps also disappears - * from the animation scene of the input (parent) object of this filter. - * Seems it is a bug of the ParaView, to be investigated ... - * - // The output data of this filter has no time associated with it. - // It is the result of computation difference between two time steps. - // Unset the time steps - if (anOutInfo->Has(vtkStreamingDemandDrivenPipeline::TIME_STEPS())) - anOutInfo->Remove(vtkStreamingDemandDrivenPipeline::TIME_STEPS()); - - // Unset the time range - if(anOutInfo->Has(vtkStreamingDemandDrivenPipeline::TIME_RANGE())) - anOutInfo->Remove(vtkStreamingDemandDrivenPipeline::TIME_RANGE()); - */ - return 1; -} - -//-------------------------------------------------------------------------------------------------- -int vtkDifferenceTimestepsFilter::RequestUpdateExtent(vtkInformation* theRequest, - vtkInformationVector** theInputVector, - vtkInformationVector* theOutputVector) -{ - // Get the information objects - vtkInformation* anInputInfo = theInputVector[0]->GetInformationObject(0); - vtkInformation* anOutputInfo = theOutputVector->GetInformationObject(0); - - // Indices must not go beyond the range of indices of the time steps - if (this->FirstTimeStepIndex >= this->NumberTimeSteps || this->FirstTimeStepIndex < 0) - { - vtkErrorMacro(<< "Specified index of the first time step [" - << this->FirstTimeStepIndex - << "] is outside the range of indices."); - return 0; - } - if (this->SecondTimeStepIndex >= this->NumberTimeSteps || this->SecondTimeStepIndex < 0) - { - vtkErrorMacro(<< "Specified index of the second time step [" - << this->SecondTimeStepIndex - << "] is outside the range of indices."); - return 0; - } - - // Warn if the selected time steps are equal - if (this->FirstTimeStepIndex == this->SecondTimeStepIndex) - { - vtkWarningMacro(<< "First and second indices [" - << this->FirstTimeStepIndex - << " = " << this->SecondTimeStepIndex - << "] are the same."); - } - - // Find the required input time steps and request them - if (anOutputInfo->Has(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP())) - { - // Get the available input times - double *anInputTimes = anInputInfo->Get(vtkStreamingDemandDrivenPipeline::TIME_STEPS()); - if (anInputTimes != NULL) - { - // Compute the requested times - double anInputUpdateTimes[2]; - int aNumberInputUpdateTimes(0); - - // For each the requested time mark the required input times - anInputUpdateTimes[aNumberInputUpdateTimes++] = anInputTimes[this->FirstTimeStepIndex]; - anInputUpdateTimes[aNumberInputUpdateTimes++] = anInputTimes[this->SecondTimeStepIndex]; - - // Make the multiple time requests upstream and use set of time-stamped data - // objects are stored in time order in a vtkMultiBlockDataSet object - anInputInfo->Set(vtkMultiTimeStepAlgorithm::UPDATE_TIME_STEPS(), - anInputUpdateTimes, aNumberInputUpdateTimes); - } - } - return 1; -} - -//-------------------------------------------------------------------------------------------------- -int vtkDifferenceTimestepsFilter::RequestData(vtkInformation* vtkNotUsed(theRequest), - vtkInformationVector** theInputVector, - vtkInformationVector* theOutputVector) -{ - // Get the information objects - vtkInformation *anInputInfo = theInputVector[0]->GetInformationObject(0); - vtkInformation *anOutputInfo = theOutputVector->GetInformationObject(0); - - vtkDataObject *anOutputDataObj = NULL; - - vtkMultiBlockDataSet *anInputData = - vtkMultiBlockDataSet::SafeDownCast(anInputInfo->Get(vtkDataObject::DATA_OBJECT())); - - int aNumberTimeSteps = anInputData->GetNumberOfBlocks(); - if (aNumberTimeSteps == 2) - { - // Get data objects - vtkDataObject* aData0 = anInputData->GetBlock(0); - vtkDataObject* aData1 = anInputData->GetBlock(1); - if (aData0 == NULL && aData1 == NULL) - { - vtkErrorMacro(<< "Null data set."); - return 0; - } - - // Compute difference between two objects - anOutputDataObj = this->DifferenceDataObject(aData0, aData1); - anOutputInfo->Set(vtkDataObject::DATA_OBJECT(), anOutputDataObj); - if (anOutputDataObj != NULL) - anOutputDataObj->Delete(); - } - else - { - vtkErrorMacro(<< "The amount of time blocks is not correct: " << aNumberTimeSteps); - return 0; - } - - return 1; -} - -//-------------------------------------------------------------------------------------------------- -vtkDataObject* vtkDifferenceTimestepsFilter::DifferenceDataObject(vtkDataObject* theInput1, - vtkDataObject* theInput2) -{ - // Determine the input object type - if (theInput1->IsA("vtkDataSet")) - { - vtkDataSet *anInDataSet1 = vtkDataSet::SafeDownCast(theInput1); - vtkDataSet *anInDataSet2 = vtkDataSet::SafeDownCast(theInput2); - return this->DifferenceDataSet(anInDataSet1, anInDataSet2); - } - else if (theInput1->IsA("vtkCompositeDataSet")) - { - // It is essential that aMGDataSet[0] an aMGDataSet[1] has the same structure. - vtkCompositeDataSet* aMGDataSet[2]; - aMGDataSet[0] = vtkCompositeDataSet::SafeDownCast(theInput1); - aMGDataSet[1] = vtkCompositeDataSet::SafeDownCast(theInput2); - - vtkCompositeDataSet *anOutput = aMGDataSet[0]->NewInstance(); - anOutput->CopyStructure(aMGDataSet[0]); - - vtkSmartPointer anIter; - anIter.TakeReference(aMGDataSet[0]->NewIterator()); - for (anIter->InitTraversal(); !anIter->IsDoneWithTraversal(); anIter->GoToNextItem()) - { - vtkDataObject* aDataObj1 = anIter->GetCurrentDataObject(); - vtkDataObject* aDataObj2 = aMGDataSet[1]->GetDataSet(anIter); - if (aDataObj1 == NULL || aDataObj2 == NULL) - { - vtkWarningMacro("The composite datasets were not identical in structure."); - continue; - } - - vtkDataObject *aResultDObj = this->DifferenceDataObject(aDataObj1, aDataObj2); - if (aResultDObj != NULL) - { - anOutput->SetDataSet(anIter, aResultDObj); - aResultDObj->Delete(); - } - else - { - vtkErrorMacro(<< "Unexpected error during computation of the difference."); - return NULL; - } - } - return anOutput; - } - else - { - vtkErrorMacro("We cannot yet compute difference of this type of dataset."); - return NULL; - } -} - -//-------------------------------------------------------------------------------------------------- -vtkDataSet* vtkDifferenceTimestepsFilter::DifferenceDataSet(vtkDataSet* theInput1, - vtkDataSet* theInput2) -{ - vtkDataSet *anInput[2]; - anInput[0] = theInput1; - anInput[1] = theInput2; - - // Copy input structure into output - vtkDataSet *anOutput = anInput[0]->NewInstance(); - anOutput->CopyStructure(anInput[0]); - - std::vector anArrays; - vtkDataArray *anOutputArray; - - // Compute the difference of the the specified point or cell data array - vtkDataArray* aDataArray0 = this->GetInputArrayToProcess(0, anInput[0]); - vtkDataArray* aDataArray1 = this->GetInputArrayToProcess(0, anInput[1]); - if (aDataArray0 == NULL || aDataArray1 == NULL) - { - vtkErrorMacro(<< "Input array to process is empty."); - return NULL; - } - anArrays.push_back(aDataArray0); - anArrays.push_back(aDataArray1); - - if (anArrays.size() > 1) - { - if (!this->VerifyArrays(&anArrays[0], 2)) - { - vtkErrorMacro(<< "Verification of data arrays has failed."); - return NULL; - } - - anOutputArray = this->DifferenceDataArray(&anArrays[0], anArrays[0]->GetNumberOfTuples()); - // Determine a field association - int aTypeFieldAssociation = this->GetInputFieldAssociation(); - if (aTypeFieldAssociation == vtkDataObject::FIELD_ASSOCIATION_POINTS) - { - // For point data - anOutput->GetPointData()->AddArray(anOutputArray); - } - else if (aTypeFieldAssociation == vtkDataObject::FIELD_ASSOCIATION_CELLS) - { - // For cell data - anOutput->GetCellData()->AddArray(anOutputArray); - } - else - { - vtkErrorMacro(<< "Solution is not implemeted yet."); - return NULL; - } - anOutputArray->Delete(); - anArrays.clear(); - } - - return anOutput; -} - -//-------------------------------------------------------------------------------------------------- -vtkDataArray* vtkDifferenceTimestepsFilter::DifferenceDataArray(vtkDataArray** theArrays, - vtkIdType theNumTuple) -{ - // Create the output array based on the number of tuple and components - // with a new name containing the specified prefix - int aNumComp = theArrays[0]->GetNumberOfComponents(); - vtkDataArray *anOutput = - DataTempDiffArray(theArrays[0], aNumComp, theNumTuple, this->ArrayNamePrefix); - - // Now do the computation of the difference - switch (theArrays[0]->GetDataType()) - { - vtkTemplateMacro( - vtkTemporalDataDifference(this, anOutput, theArrays, aNumComp, static_cast(0))); - default: - vtkErrorMacro(<< "Execute: unknown scalar type."); - return NULL; - } - - return anOutput; -} - -//-------------------------------------------------------------------------------------------------- -int vtkDifferenceTimestepsFilter::GetInputFieldAssociation() -{ - vtkInformationVector *anInputArrayVec = this->GetInformation()->Get(INPUT_ARRAYS_TO_PROCESS()); - vtkInformation *anInputArrayInfo = anInputArrayVec->GetInformationObject(0); - return anInputArrayInfo->Get(vtkDataObject::FIELD_ASSOCIATION()); -} - -//-------------------------------------------------------------------------------------------------- -bool vtkDifferenceTimestepsFilter::VerifyArrays(vtkDataArray **theArrays, int theNumArrays) -{ - // Get all required data to compare with other - const char* anArrayName = theArrays[0]->GetName(); - vtkIdType aNumTuples = theArrays[0]->GetNumberOfTuples(); - vtkIdType aNumComponents = theArrays[0]->GetNumberOfComponents(); - - for (int i = 1; i < theNumArrays; ++i) - { - if (strcmp(theArrays[i]->GetName(), anArrayName) != 0) - { - vtkWarningMacro(<< "Computation of difference aborted for dataset because " - << "the array name in each time step are different.") - return false; - } - - if (theArrays[i]->GetNumberOfTuples() != aNumTuples) - { - vtkWarningMacro(<< "Computation of difference aborted for dataset because " - << "the number of tuples in each time step are different.") - return false; - } - - if (theArrays[i]->GetNumberOfComponents() != aNumComponents) - { - vtkWarningMacro(<< "Computation of difference aborted for dataset because " - << "the number of components in each time step are different.") - return false; - } - } - - return true; -} diff --git a/src/Plugins/DifferenceTimesteps/vtkDifferenceTimestepsFilter.h b/src/Plugins/DifferenceTimesteps/vtkDifferenceTimestepsFilter.h deleted file mode 100644 index e7ae9b0f..00000000 --- a/src/Plugins/DifferenceTimesteps/vtkDifferenceTimestepsFilter.h +++ /dev/null @@ -1,148 +0,0 @@ -// Copyright (C) 2014-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Maxim Glibin - -#ifndef __DifferenceTimestepsFilter_h_ -#define __DifferenceTimestepsFilter_h_ - -#include - -#include - -class vtkDataSet; -class vtkStringArray; - -/** - * Description of class: - * Class allows to compute difference between two time steps of one data array (field). -*/ -class VTK_EXPORT vtkDifferenceTimestepsFilter : public vtkMultiTimeStepAlgorithm -{ -public: - /// Returns pointer on a new instance of the class - static vtkDifferenceTimestepsFilter* New(); - - vtkTypeMacro(vtkDifferenceTimestepsFilter, vtkMultiTimeStepAlgorithm); - - /// Prints current state of the objects - virtual void PrintSelf(ostream &, vtkIndent); - - // Description: - // Set/Get methods for first time step. - vtkSetMacro(FirstTimeStepIndex, int); - vtkGetMacro(FirstTimeStepIndex, int); - - // Description: - // Set/Get methods for first time step. - vtkSetMacro(SecondTimeStepIndex, int); - vtkGetMacro(SecondTimeStepIndex, int); - - // Description: - // Get methods for range of indices of time steps. - vtkGetVector2Macro(RangeIndicesTimeSteps, int); - - // Description: - // Set/Get methods for prefix of array name. - vtkSetStringMacro(ArrayNamePrefix); - vtkGetStringMacro(ArrayNamePrefix); - -protected: - /// Constructor & destructor - vtkDifferenceTimestepsFilter(); - virtual ~vtkDifferenceTimestepsFilter(); - - /// The methods which is called on filtering data - virtual int FillInputPortInformation(int, vtkInformation *); - - virtual int FillOutputPortInformation(int, vtkInformation *); - - virtual int RequestDataObject(vtkInformation *, - vtkInformationVector **, - vtkInformationVector *); - - virtual int RequestInformation(vtkInformation *, - vtkInformationVector **, - vtkInformationVector *); - - virtual int RequestUpdateExtent(vtkInformation *, - vtkInformationVector **, - vtkInformationVector *); - - virtual int RequestData(vtkInformation *, - vtkInformationVector **, - vtkInformationVector *); - - // Description: - // General computation differences routine for any type on input data. This - // is called recursively when heirarchical/multiblock data is encountered. - vtkDataObject *DifferenceDataObject(vtkDataObject* theInput1, - vtkDataObject* theInput2); - - // Description: - // Root level interpolation for a concrete dataset object. - // Point/Cell data and points are different. - // Needs improving if connectivity is to be handled. - virtual vtkDataSet *DifferenceDataSet(vtkDataSet* theInput1, - vtkDataSet* theInput2); - - // Description: - // Compute difference a single vtkDataArray. Called from computation - // of the difference routine on pointdata or celldata. - virtual vtkDataArray *DifferenceDataArray(vtkDataArray** theArrays, - vtkIdType theN); - - // Description: - // Range of indices of the time steps. - int RangeIndicesTimeSteps[2]; - - // Description: - // First time step index. - int FirstTimeStepIndex; - - // Description: - // Second time step index. - int SecondTimeStepIndex; - - // Description: - // Length of time steps array - int NumberTimeSteps; - - // Description: - // Array of time step values. - std::vector TimeStepValues; - - // Description: - // Prefix of array name. - char *ArrayNamePrefix; - -private: - vtkDifferenceTimestepsFilter(const vtkDifferenceTimestepsFilter &); // Not implemented yet - void operator=(const vtkDifferenceTimestepsFilter &); // Not implemented yet - - // Description: - // Get field association type. - int GetInputFieldAssociation(); - - // Description: - // Called just before computation of the difference of the dataset to ensure that - // each data array has the same array name, number of tuples or components and etc. - bool VerifyArrays(vtkDataArray **theArrays, int theNumArrays); -}; - -#endif // __DifferenceTimestepsFilter_h_ diff --git a/src/Plugins/ElevationSurface/CMakeLists.txt b/src/Plugins/ElevationSurface/CMakeLists.txt index 6bae5c9d..4760549d 100644 --- a/src/Plugins/ElevationSurface/CMakeLists.txt +++ b/src/Plugins/ElevationSurface/CMakeLists.txt @@ -1,41 +1,30 @@ -# Copyright (C) 2010-2019 CEA/DEN, EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# +cmake_minimum_required(VERSION 3.8) +project(ElevationSurface) +find_package(ParaView REQUIRED) -PROJECT(ElevationSurface) -cmake_minimum_required(VERSION 2.6) +include(GNUInstallDirs) +set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_BINDIR}") +set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_LIBDIR}") +set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_LIBDIR}") -cmake_policy(SET CMP0003 NEW) +set("_paraview_plugin_default_${CMAKE_PROJECT_NAME}" ON) +paraview_plugin_scan( + ENABLE_BY_DEFAULT YES + PLUGIN_FILES "${CMAKE_CURRENT_SOURCE_DIR}/plugin/paraview.plugin" + PROVIDES_PLUGINS plugins + REQUIRES_MODULES required_modules) -FIND_PACKAGE(ParaView REQUIRED) -INCLUDE(${PARAVIEW_USE_FILE}) - -SET(SRCS - vtkElevationSurfaceFilter.cxx - ) - -ADD_PARAVIEW_PLUGIN(ElevationSurface "1.0" - SERVER_MANAGER_XML ElevationSurface.xml - SERVER_MANAGER_SOURCES ${SRCS}) - -install(TARGETS ${PROJECT_NAME} - RUNTIME DESTINATION lib/paraview - LIBRARY DESTINATION lib/paraview - ARCHIVE DESTINATION lib/paraview - ) +foreach(module IN LISTS required_modules) + if(NOT TARGET "${module}") + message("Missing required module: ${module}") + return() + endif() +endforeach() +set(BUILD_SHARED_LIBS ON) +paraview_plugin_build( + RUNTIME_DESTINATION "${CMAKE_INSTALL_BINDIR}" + LIBRARY_DESTINATION "${CMAKE_INSTALL_LIBDIR}" + LIBRARY_SUBDIRECTORY "${PARAVIEW_PLUGIN_SUBDIR}" + PLUGINS ${plugins} + AUTOLOAD ${plugins}) diff --git a/src/Plugins/ElevationSurface/ElevationSurface.xml b/src/Plugins/ElevationSurface/ElevationSurface.xml deleted file mode 100644 index ab36cca4..00000000 --- a/src/Plugins/ElevationSurface/ElevationSurface.xml +++ /dev/null @@ -1,95 +0,0 @@ - - - - - - - "Create a point set with data at quadrature points." - - - - - - - - - - - - - - - - - - - Specifies the cell field used for the elevation surface. - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/Plugins/ElevationSurface/plugin/CMakeLists.txt b/src/Plugins/ElevationSurface/plugin/CMakeLists.txt new file mode 100644 index 00000000..28519fcd --- /dev/null +++ b/src/Plugins/ElevationSurface/plugin/CMakeLists.txt @@ -0,0 +1,13 @@ + +paraview_add_plugin(ElevationSurface + VERSION "1.0" + MODULES ElevationSurfaceModule + MODULE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/ElevationSurfaceModule/vtk.module" + SERVER_MANAGER_XML filters.xml + ) + +install(TARGETS ElevationSurface + RUNTIME DESTINATION lib/paraview + LIBRARY DESTINATION lib/paraview + ARCHIVE DESTINATION lib/paraview + ) diff --git a/src/Plugins/ElevationSurface/plugin/ElevationSurfaceModule/CMakeLists.txt b/src/Plugins/ElevationSurface/plugin/ElevationSurfaceModule/CMakeLists.txt new file mode 100644 index 00000000..a2304025 --- /dev/null +++ b/src/Plugins/ElevationSurface/plugin/ElevationSurfaceModule/CMakeLists.txt @@ -0,0 +1,8 @@ +set(classes + vtkElevationSurfaceFilter +) + +vtk_module_add_module(ElevationSurfaceModule + FORCE_STATIC + CLASSES ${classes} +) diff --git a/src/Plugins/ElevationSurface/plugin/ElevationSurfaceModule/vtk.module b/src/Plugins/ElevationSurface/plugin/ElevationSurfaceModule/vtk.module new file mode 100644 index 00000000..4cc8a645 --- /dev/null +++ b/src/Plugins/ElevationSurface/plugin/ElevationSurfaceModule/vtk.module @@ -0,0 +1,11 @@ +NAME + ElevationSurfaceModule +DEPENDS + VTK::CommonCore + VTK::CommonDataModel + VTK::CommonExecutionModel + VTK::FiltersCore +PRIVATE_DEPENDS + VTK::CommonMisc + VTK::CommonSystem + VTK::FiltersGeneral diff --git a/src/Plugins/ElevationSurface/plugin/ElevationSurfaceModule/vtkElevationSurfaceFilter.cxx b/src/Plugins/ElevationSurface/plugin/ElevationSurfaceModule/vtkElevationSurfaceFilter.cxx new file mode 100644 index 00000000..e102b351 --- /dev/null +++ b/src/Plugins/ElevationSurface/plugin/ElevationSurfaceModule/vtkElevationSurfaceFilter.cxx @@ -0,0 +1,315 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// + +#include "vtkElevationSurfaceFilter.h" +#include "vtkInformation.h" +#include "vtkInformationVector.h" +#include "vtkObjectFactory.h" +#include "vtkElevationSurfaceFilter.h" +#include "vtkPolyData.h" +#include "vtkIdTypeArray.h" +#include "vtkPolyData.h" +#include "vtkUnstructuredGrid.h" +#include "vtkDemandDrivenPipeline.h" +#include "vtkStreamingDemandDrivenPipeline.h" +#include "vtkGenericCell.h" +#include "vtkSmartPointer.h" +#include "vtkPoints.h" +#include "vtkCellArray.h" +#include "vtkPointData.h" +#include "vtkCellData.h" + +#include + +//vtkCxxRevisionMacro(vtkElevationSurfaceFilter, "$Revision$"); +vtkStandardNewMacro(vtkElevationSurfaceFilter); + +vtkElevationSurfaceFilter::vtkElevationSurfaceFilter() +{ + this->SetNumberOfInputPorts(1); + this->SetNumberOfOutputPorts(1); + + this->ScaleFactor = 0.5; + this->Direction[0] = 0.0; + this->Direction[1] = 0.0; + this->Direction[2] = 1.0; + this->AutoDetectDirection = 1; +} + +vtkElevationSurfaceFilter::~vtkElevationSurfaceFilter() +{ +} + +//---------------------------------------------------------------------------- +int vtkElevationSurfaceFilter::ProcessRequest(vtkInformation* request, + vtkInformationVector** inputVector, + vtkInformationVector* outputVector) +{ + // generate the data + if(request->Has(vtkDemandDrivenPipeline::REQUEST_DATA())) + { + return this->RequestData(request, inputVector, outputVector); + } + + if(request->Has(vtkStreamingDemandDrivenPipeline::REQUEST_UPDATE_EXTENT())) + { + return this->RequestUpdateExtent(request, inputVector, outputVector); + } + + // execute information + if(request->Has(vtkDemandDrivenPipeline::REQUEST_INFORMATION())) + { + return this->RequestInformation(request, inputVector, outputVector); + } + + return this->Superclass::ProcessRequest(request, inputVector, outputVector); +} + +//---------------------------------------------------------------------------- +int vtkElevationSurfaceFilter::FillOutputPortInformation( + int vtkNotUsed(port), vtkInformation* info) +{ + // now add our info + info->Set(vtkDataObject::DATA_TYPE_NAME(), "vtkUnstructuredGrid"); + return 1; +} + +//---------------------------------------------------------------------------- +int vtkElevationSurfaceFilter::FillInputPortInformation( + int vtkNotUsed(port), vtkInformation* info) +{ + info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkPolyData"); + return 1; +} + +//---------------------------------------------------------------------------- +int vtkElevationSurfaceFilter::RequestUpdateExtent( + vtkInformation* vtkNotUsed(request), + vtkInformationVector** inputVector, + vtkInformationVector* vtkNotUsed(outputVector)) +{ + int numInputPorts = this->GetNumberOfInputPorts(); + for (int i=0; iGetNumberOfInputConnections(i); + for (int j=0; jGetInformationObject(j); + inputInfo->Set(vtkStreamingDemandDrivenPipeline::EXACT_EXTENT(), 1); + } + } + return 1; +} + +int vtkElevationSurfaceFilter::RequestInformation(vtkInformation *request, + vtkInformationVector **input, vtkInformationVector *output) +{ + return 1; +} + +int vtkElevationSurfaceFilter::RequestData(vtkInformation *request, + vtkInformationVector **input, vtkInformationVector *output) +{ + vtkPolyData *pdIn = vtkPolyData::SafeDownCast( + input[0]->GetInformationObject(0)->Get(vtkDataObject::DATA_OBJECT())); + + vtkUnstructuredGrid *usgOut = vtkUnstructuredGrid::SafeDownCast( + output->GetInformationObject(0)->Get(vtkDataObject::DATA_OBJECT())); + + vtkDataArray* array = this->GetInputArrayToProcess(0, input); + + if(pdIn == NULL || array == NULL || usgOut == NULL + || array->GetNumberOfComponents() != 1) + { + vtkDebugMacro("vtkElevationSurfaceFilter no correctly configured"); + return 1; + } + + double dir[3]; + if(this->AutoDetectDirection) + { + this->ComputeDirection(pdIn, dir); + } + else + { + dir[0] = this->Direction[0]; + dir[1] = this->Direction[1]; + dir[2] = this->Direction[2]; + } + + double len = dir[0]*dir[0] + dir[1]*dir[1] + dir[2]*dir[2]; + + if(len == 0) + { + dir[2] = 1; + len = 1.0; + } + + len = sqrt(len); + + dir[0] /= len; + dir[1] /= len; + dir[2] /= len; + + dir[0] *= this->GetScaleFactor(); + dir[1] *= this->GetScaleFactor(); + dir[2] *= this->GetScaleFactor(); + + usgOut->Allocate(pdIn->GetNumberOfCells()); + + vtkSmartPointer newPts = vtkSmartPointer::New(); + usgOut->SetPoints(newPts); + + usgOut->GetPointData()->CopyAllocate(pdIn->GetPointData(), + 2*pdIn->GetNumberOfPoints()); + usgOut->GetCellData()->CopyAllocate(pdIn->GetCellData(), + pdIn->GetNumberOfCells()); + + vtkIdType ncell = pdIn->GetNumberOfCells(); + vtkSmartPointer newIds = vtkSmartPointer::New(); + vtkSmartPointer polyhedronIds = vtkSmartPointer::New(); + for(vtkIdType cellId=0; cellId < ncell; cellId++) + { + vtkCell* cell = pdIn->GetCell(cellId); + if(cell->GetCellDimension() != 2) + continue; + + unsigned char newCellType = VTK_EMPTY_CELL; + unsigned char oldCellType = (unsigned char)cell->GetCellType(); + switch(oldCellType) + { + case VTK_TRIANGLE : + newCellType = VTK_WEDGE; + break; + case VTK_QUAD : + newCellType = VTK_HEXAHEDRON; + break; + case VTK_POLYGON : + newCellType = VTK_POLYHEDRON; + // default : add new cell types to extrude here + } + if(newCellType == VTK_EMPTY_CELL) + continue; + + double cellScalar = array->GetTuple1(cellId); + + vtkIdList* oldIds = cell->GetPointIds(); + int oldPtsNumber = oldIds->GetNumberOfIds(); + int newPtsNumber = oldPtsNumber * 2; + newIds->SetNumberOfIds(newPtsNumber); + double coords[VTK_CELL_SIZE*3]; + for(int ptid = 0; ptid < oldPtsNumber; ptid++) + { + pdIn->GetPoint(oldIds->GetId(ptid), coords + 3*ptid); + } + for(int ptid = 0; ptid < oldPtsNumber; ptid++) + { + coords[(ptid+oldPtsNumber)*3+0] = coords[ptid*3+0] + cellScalar*dir[0]; + coords[(ptid+oldPtsNumber)*3+1] = coords[ptid*3+1] + cellScalar*dir[1]; + coords[(ptid+oldPtsNumber)*3+2] = coords[ptid*3+2] + cellScalar*dir[2]; + } + for(int ptid=0; ptidInsertNextPoint(coords + 3*ptid); + newIds->SetId(ptid, newId); + usgOut->GetPointData()->CopyData(pdIn->GetPointData(), + oldIds->GetId(ptid % oldPtsNumber), + newIds->GetId(ptid)); + } + vtkIdType newCellId; + if(newCellType == VTK_POLYHEDRON) + { + polyhedronIds->Initialize(); + // in the polyhedron case, I will generate a quad for each edge + // of the input, and two capping faces + polyhedronIds->InsertNextId(2+oldPtsNumber); + // insert the bottom face + polyhedronIds->InsertNextId(oldPtsNumber); + for(int ptid = 0; ptid < oldPtsNumber; ptid++) + { + polyhedronIds->InsertNextId(newIds->GetId(ptid)); + } + // insert the top face + polyhedronIds->InsertNextId(oldPtsNumber); + for(int ptid = oldPtsNumber; ptid < 2*oldPtsNumber; ptid++) + { + polyhedronIds->InsertNextId(newIds->GetId(ptid)); + } + // insert the bording quads + for(int qid = 0; qid < oldPtsNumber; qid++) + { + polyhedronIds->InsertNextId(4); + polyhedronIds->InsertNextId(newIds->GetId(qid)); + polyhedronIds->InsertNextId(newIds->GetId(qid+oldPtsNumber)); + polyhedronIds->InsertNextId(newIds->GetId(qid+((oldPtsNumber+1)%oldPtsNumber))); + polyhedronIds->InsertNextId(newIds->GetId((qid+1)%oldPtsNumber)); + } + newIds->Initialize(); + for(int jj=0; jjGetNumberOfIds(); jj++) + { + newIds->InsertNextId(polyhedronIds->GetId(jj)); + } + } + newCellId = usgOut->InsertNextCell(newCellType, newIds); + usgOut->GetCellData()->CopyData(pdIn->GetCellData(), + cellId, + newCellId); + } + + usgOut->GetFieldData()->ShallowCopy(pdIn->GetFieldData()); + + usgOut->Squeeze(); + + return 1; +} + +void vtkElevationSurfaceFilter::ComputeDirection(vtkPolyData* pdIn, double *outDir) +{ + double tmp[2][3] = {{0, 0, 0}, {0, 0, 0}}; + outDir[0] = outDir[1] = outDir[2] = 0; + + vtkPoints* pts = pdIn->GetPoints(); + vtkSmartPointer cell = vtkSmartPointer::New(); + + for(vtkIdType cellId = 0; cellId < pdIn->GetNumberOfCells(); cellId++) + { + pdIn->GetCell(cellId, cell); + if(cell->GetCellDimension() != 2) + continue; + + vtkIdList* ptIds = cell->GetPointIds(); + for(int i=0; iGetNumberOfIds(); i++) + { + vtkIdType firstId = ptIds->GetId(i); + vtkIdType secondId = ptIds->GetId((i+1)%ptIds->GetNumberOfIds()); + pts->GetPoint(firstId, tmp[0]); + pts->GetPoint(secondId, tmp[1]); + outDir[0] += tmp[0][1]*tmp[1][2] - tmp[0][2]*tmp[1][1]; + outDir[1] += tmp[0][2]*tmp[1][0] - tmp[0][0]*tmp[1][2]; + outDir[2] += tmp[0][0]*tmp[1][1] - tmp[0][1]*tmp[1][0]; + } + } +} + +void vtkElevationSurfaceFilter::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os, indent); + + os << indent << "ScaleFactor : " << this->ScaleFactor << endl; +} diff --git a/src/Plugins/ElevationSurface/plugin/ElevationSurfaceModule/vtkElevationSurfaceFilter.h b/src/Plugins/ElevationSurface/plugin/ElevationSurfaceModule/vtkElevationSurfaceFilter.h new file mode 100644 index 00000000..2dbf1a01 --- /dev/null +++ b/src/Plugins/ElevationSurface/plugin/ElevationSurfaceModule/vtkElevationSurfaceFilter.h @@ -0,0 +1,83 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// + +#ifndef _vtkElevationSurfaceFilter_h +#define _vtkElevationSurfaceFilter_h + +#include + +class vtkPolyData; + +class VTK_EXPORT vtkElevationSurfaceFilter : public vtkAlgorithm +{ +public: + static vtkElevationSurfaceFilter* New(); + vtkTypeMacro(vtkElevationSurfaceFilter, vtkAlgorithm); + void PrintSelf(ostream& os, vtkIndent indent) override; + + // Description : + // This is the factor applied to shrink the cell before extracting + // the Elevation points. + // A value of 0 shrinks the cells to their center, and a value of 1 + // do not shrink the cell at all. + // default value 0.5 + vtkSetMacro(ScaleFactor, double); + vtkGetMacro(ScaleFactor, double); + + // Description: + // Set the direction of the deformation + vtkSetVector3Macro(Direction, double); + vtkGetVector3Macro(Direction, double); + + // Description: + // If this flag is != 0, the filter will attempt detect automatically the + // direction of the normal of the input. + // The direction is given by the sum of the normals of all input polygons. + // If there is no input poly, or if the sum is 0, it will revert to the + // Direction ivar + vtkBooleanMacro(AutoDetectDirection, int); + vtkSetMacro(AutoDetectDirection, int); + vtkGetMacro(AutoDetectDirection, int); + +protected: + vtkElevationSurfaceFilter(); + ~vtkElevationSurfaceFilter() override; + + int FillInputPortInformation(int, vtkInformation*) override; + int FillOutputPortInformation(int, vtkInformation*) override; + + int ProcessRequest(vtkInformation*, vtkInformationVector**, vtkInformationVector*) override; + + virtual int RequestData(vtkInformation*, vtkInformationVector**, vtkInformationVector*); + + virtual int RequestInformation(vtkInformation*, vtkInformationVector**, vtkInformationVector*); + + virtual int RequestUpdateExtent(vtkInformation*, vtkInformationVector**, vtkInformationVector*); + + virtual void ComputeDirection(vtkPolyData*, double* outDir); + + double ScaleFactor; + double Direction[3]; + int AutoDetectDirection; + +private: + vtkElevationSurfaceFilter(const vtkElevationSurfaceFilter&) = delete; + void operator=(const vtkElevationSurfaceFilter&) = delete; +}; +#endif diff --git a/src/Plugins/ElevationSurface/plugin/filters.xml b/src/Plugins/ElevationSurface/plugin/filters.xml new file mode 100644 index 00000000..c07a2cc6 --- /dev/null +++ b/src/Plugins/ElevationSurface/plugin/filters.xml @@ -0,0 +1,77 @@ + + + + + + "Create a point set with data at quadrature points." + + + + + + + + + + + + + + + + + + + Specifies the cell field used for the elevation surface. + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Plugins/ElevationSurface/plugin/paraview.plugin b/src/Plugins/ElevationSurface/plugin/paraview.plugin new file mode 100644 index 00000000..2f097666 --- /dev/null +++ b/src/Plugins/ElevationSurface/plugin/paraview.plugin @@ -0,0 +1,8 @@ +NAME + ElevationSurface +DESCRIPTION + This plugin provides the ElevationSurface filter. +REQUIRES_MODULES + VTK::CommonCore + VTK::IOCore + VTK::FiltersCore diff --git a/src/Plugins/ElevationSurface/vtkElevationSurfaceFilter.cxx b/src/Plugins/ElevationSurface/vtkElevationSurfaceFilter.cxx deleted file mode 100644 index e102b351..00000000 --- a/src/Plugins/ElevationSurface/vtkElevationSurfaceFilter.cxx +++ /dev/null @@ -1,315 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// - -#include "vtkElevationSurfaceFilter.h" -#include "vtkInformation.h" -#include "vtkInformationVector.h" -#include "vtkObjectFactory.h" -#include "vtkElevationSurfaceFilter.h" -#include "vtkPolyData.h" -#include "vtkIdTypeArray.h" -#include "vtkPolyData.h" -#include "vtkUnstructuredGrid.h" -#include "vtkDemandDrivenPipeline.h" -#include "vtkStreamingDemandDrivenPipeline.h" -#include "vtkGenericCell.h" -#include "vtkSmartPointer.h" -#include "vtkPoints.h" -#include "vtkCellArray.h" -#include "vtkPointData.h" -#include "vtkCellData.h" - -#include - -//vtkCxxRevisionMacro(vtkElevationSurfaceFilter, "$Revision$"); -vtkStandardNewMacro(vtkElevationSurfaceFilter); - -vtkElevationSurfaceFilter::vtkElevationSurfaceFilter() -{ - this->SetNumberOfInputPorts(1); - this->SetNumberOfOutputPorts(1); - - this->ScaleFactor = 0.5; - this->Direction[0] = 0.0; - this->Direction[1] = 0.0; - this->Direction[2] = 1.0; - this->AutoDetectDirection = 1; -} - -vtkElevationSurfaceFilter::~vtkElevationSurfaceFilter() -{ -} - -//---------------------------------------------------------------------------- -int vtkElevationSurfaceFilter::ProcessRequest(vtkInformation* request, - vtkInformationVector** inputVector, - vtkInformationVector* outputVector) -{ - // generate the data - if(request->Has(vtkDemandDrivenPipeline::REQUEST_DATA())) - { - return this->RequestData(request, inputVector, outputVector); - } - - if(request->Has(vtkStreamingDemandDrivenPipeline::REQUEST_UPDATE_EXTENT())) - { - return this->RequestUpdateExtent(request, inputVector, outputVector); - } - - // execute information - if(request->Has(vtkDemandDrivenPipeline::REQUEST_INFORMATION())) - { - return this->RequestInformation(request, inputVector, outputVector); - } - - return this->Superclass::ProcessRequest(request, inputVector, outputVector); -} - -//---------------------------------------------------------------------------- -int vtkElevationSurfaceFilter::FillOutputPortInformation( - int vtkNotUsed(port), vtkInformation* info) -{ - // now add our info - info->Set(vtkDataObject::DATA_TYPE_NAME(), "vtkUnstructuredGrid"); - return 1; -} - -//---------------------------------------------------------------------------- -int vtkElevationSurfaceFilter::FillInputPortInformation( - int vtkNotUsed(port), vtkInformation* info) -{ - info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkPolyData"); - return 1; -} - -//---------------------------------------------------------------------------- -int vtkElevationSurfaceFilter::RequestUpdateExtent( - vtkInformation* vtkNotUsed(request), - vtkInformationVector** inputVector, - vtkInformationVector* vtkNotUsed(outputVector)) -{ - int numInputPorts = this->GetNumberOfInputPorts(); - for (int i=0; iGetNumberOfInputConnections(i); - for (int j=0; jGetInformationObject(j); - inputInfo->Set(vtkStreamingDemandDrivenPipeline::EXACT_EXTENT(), 1); - } - } - return 1; -} - -int vtkElevationSurfaceFilter::RequestInformation(vtkInformation *request, - vtkInformationVector **input, vtkInformationVector *output) -{ - return 1; -} - -int vtkElevationSurfaceFilter::RequestData(vtkInformation *request, - vtkInformationVector **input, vtkInformationVector *output) -{ - vtkPolyData *pdIn = vtkPolyData::SafeDownCast( - input[0]->GetInformationObject(0)->Get(vtkDataObject::DATA_OBJECT())); - - vtkUnstructuredGrid *usgOut = vtkUnstructuredGrid::SafeDownCast( - output->GetInformationObject(0)->Get(vtkDataObject::DATA_OBJECT())); - - vtkDataArray* array = this->GetInputArrayToProcess(0, input); - - if(pdIn == NULL || array == NULL || usgOut == NULL - || array->GetNumberOfComponents() != 1) - { - vtkDebugMacro("vtkElevationSurfaceFilter no correctly configured"); - return 1; - } - - double dir[3]; - if(this->AutoDetectDirection) - { - this->ComputeDirection(pdIn, dir); - } - else - { - dir[0] = this->Direction[0]; - dir[1] = this->Direction[1]; - dir[2] = this->Direction[2]; - } - - double len = dir[0]*dir[0] + dir[1]*dir[1] + dir[2]*dir[2]; - - if(len == 0) - { - dir[2] = 1; - len = 1.0; - } - - len = sqrt(len); - - dir[0] /= len; - dir[1] /= len; - dir[2] /= len; - - dir[0] *= this->GetScaleFactor(); - dir[1] *= this->GetScaleFactor(); - dir[2] *= this->GetScaleFactor(); - - usgOut->Allocate(pdIn->GetNumberOfCells()); - - vtkSmartPointer newPts = vtkSmartPointer::New(); - usgOut->SetPoints(newPts); - - usgOut->GetPointData()->CopyAllocate(pdIn->GetPointData(), - 2*pdIn->GetNumberOfPoints()); - usgOut->GetCellData()->CopyAllocate(pdIn->GetCellData(), - pdIn->GetNumberOfCells()); - - vtkIdType ncell = pdIn->GetNumberOfCells(); - vtkSmartPointer newIds = vtkSmartPointer::New(); - vtkSmartPointer polyhedronIds = vtkSmartPointer::New(); - for(vtkIdType cellId=0; cellId < ncell; cellId++) - { - vtkCell* cell = pdIn->GetCell(cellId); - if(cell->GetCellDimension() != 2) - continue; - - unsigned char newCellType = VTK_EMPTY_CELL; - unsigned char oldCellType = (unsigned char)cell->GetCellType(); - switch(oldCellType) - { - case VTK_TRIANGLE : - newCellType = VTK_WEDGE; - break; - case VTK_QUAD : - newCellType = VTK_HEXAHEDRON; - break; - case VTK_POLYGON : - newCellType = VTK_POLYHEDRON; - // default : add new cell types to extrude here - } - if(newCellType == VTK_EMPTY_CELL) - continue; - - double cellScalar = array->GetTuple1(cellId); - - vtkIdList* oldIds = cell->GetPointIds(); - int oldPtsNumber = oldIds->GetNumberOfIds(); - int newPtsNumber = oldPtsNumber * 2; - newIds->SetNumberOfIds(newPtsNumber); - double coords[VTK_CELL_SIZE*3]; - for(int ptid = 0; ptid < oldPtsNumber; ptid++) - { - pdIn->GetPoint(oldIds->GetId(ptid), coords + 3*ptid); - } - for(int ptid = 0; ptid < oldPtsNumber; ptid++) - { - coords[(ptid+oldPtsNumber)*3+0] = coords[ptid*3+0] + cellScalar*dir[0]; - coords[(ptid+oldPtsNumber)*3+1] = coords[ptid*3+1] + cellScalar*dir[1]; - coords[(ptid+oldPtsNumber)*3+2] = coords[ptid*3+2] + cellScalar*dir[2]; - } - for(int ptid=0; ptidInsertNextPoint(coords + 3*ptid); - newIds->SetId(ptid, newId); - usgOut->GetPointData()->CopyData(pdIn->GetPointData(), - oldIds->GetId(ptid % oldPtsNumber), - newIds->GetId(ptid)); - } - vtkIdType newCellId; - if(newCellType == VTK_POLYHEDRON) - { - polyhedronIds->Initialize(); - // in the polyhedron case, I will generate a quad for each edge - // of the input, and two capping faces - polyhedronIds->InsertNextId(2+oldPtsNumber); - // insert the bottom face - polyhedronIds->InsertNextId(oldPtsNumber); - for(int ptid = 0; ptid < oldPtsNumber; ptid++) - { - polyhedronIds->InsertNextId(newIds->GetId(ptid)); - } - // insert the top face - polyhedronIds->InsertNextId(oldPtsNumber); - for(int ptid = oldPtsNumber; ptid < 2*oldPtsNumber; ptid++) - { - polyhedronIds->InsertNextId(newIds->GetId(ptid)); - } - // insert the bording quads - for(int qid = 0; qid < oldPtsNumber; qid++) - { - polyhedronIds->InsertNextId(4); - polyhedronIds->InsertNextId(newIds->GetId(qid)); - polyhedronIds->InsertNextId(newIds->GetId(qid+oldPtsNumber)); - polyhedronIds->InsertNextId(newIds->GetId(qid+((oldPtsNumber+1)%oldPtsNumber))); - polyhedronIds->InsertNextId(newIds->GetId((qid+1)%oldPtsNumber)); - } - newIds->Initialize(); - for(int jj=0; jjGetNumberOfIds(); jj++) - { - newIds->InsertNextId(polyhedronIds->GetId(jj)); - } - } - newCellId = usgOut->InsertNextCell(newCellType, newIds); - usgOut->GetCellData()->CopyData(pdIn->GetCellData(), - cellId, - newCellId); - } - - usgOut->GetFieldData()->ShallowCopy(pdIn->GetFieldData()); - - usgOut->Squeeze(); - - return 1; -} - -void vtkElevationSurfaceFilter::ComputeDirection(vtkPolyData* pdIn, double *outDir) -{ - double tmp[2][3] = {{0, 0, 0}, {0, 0, 0}}; - outDir[0] = outDir[1] = outDir[2] = 0; - - vtkPoints* pts = pdIn->GetPoints(); - vtkSmartPointer cell = vtkSmartPointer::New(); - - for(vtkIdType cellId = 0; cellId < pdIn->GetNumberOfCells(); cellId++) - { - pdIn->GetCell(cellId, cell); - if(cell->GetCellDimension() != 2) - continue; - - vtkIdList* ptIds = cell->GetPointIds(); - for(int i=0; iGetNumberOfIds(); i++) - { - vtkIdType firstId = ptIds->GetId(i); - vtkIdType secondId = ptIds->GetId((i+1)%ptIds->GetNumberOfIds()); - pts->GetPoint(firstId, tmp[0]); - pts->GetPoint(secondId, tmp[1]); - outDir[0] += tmp[0][1]*tmp[1][2] - tmp[0][2]*tmp[1][1]; - outDir[1] += tmp[0][2]*tmp[1][0] - tmp[0][0]*tmp[1][2]; - outDir[2] += tmp[0][0]*tmp[1][1] - tmp[0][1]*tmp[1][0]; - } - } -} - -void vtkElevationSurfaceFilter::PrintSelf(ostream& os, vtkIndent indent) -{ - this->Superclass::PrintSelf(os, indent); - - os << indent << "ScaleFactor : " << this->ScaleFactor << endl; -} diff --git a/src/Plugins/ElevationSurface/vtkElevationSurfaceFilter.h b/src/Plugins/ElevationSurface/vtkElevationSurfaceFilter.h deleted file mode 100644 index 3fd4019a..00000000 --- a/src/Plugins/ElevationSurface/vtkElevationSurfaceFilter.h +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// - -#ifndef _vtkElevationSurfaceFilter_h -#define _vtkElevationSurfaceFilter_h - -#include "vtkAlgorithm.h" - -class vtkPolyData; - -class VTK_EXPORT vtkElevationSurfaceFilter: public vtkAlgorithm -{ -public: - static vtkElevationSurfaceFilter *New(); - vtkTypeMacro(vtkElevationSurfaceFilter,vtkAlgorithm); - void PrintSelf(ostream& os, vtkIndent indent); - - // Description : - // This is the factor applied to shrink the cell before extracting - // the Elevation points. - // A value of 0 shrinks the cells to their center, and a value of 1 - // do not shrink the cell at all. - // default value 0.5 - vtkSetMacro(ScaleFactor,double); - vtkGetMacro(ScaleFactor,double); - - // Description: - // Set the direction of the deformation - vtkSetVector3Macro(Direction, double); - vtkGetVector3Macro(Direction, double); - - // Description: - // If this flag is != 0, the filter will attempt detect automatically the - // direction of the normal of the input. - // The direction is given by the sum of the normals of all input polygons. - // If there is no input poly, or if the sum is 0, it will revert to the - // Direction ivar - vtkBooleanMacro(AutoDetectDirection, int); - vtkSetMacro(AutoDetectDirection, int); - vtkGetMacro(AutoDetectDirection, int); - -protected: - vtkElevationSurfaceFilter(); - ~vtkElevationSurfaceFilter(); - - int FillInputPortInformation(int , vtkInformation* ); - int FillOutputPortInformation(int , vtkInformation* ); - - int ProcessRequest(vtkInformation* , - vtkInformationVector** , - vtkInformationVector* ); - - - int RequestData(vtkInformation *, - vtkInformationVector **, - vtkInformationVector *); - - int RequestInformation(vtkInformation *, - vtkInformationVector **, - vtkInformationVector *); - - int RequestUpdateExtent(vtkInformation* , - vtkInformationVector**, - vtkInformationVector*); - - virtual void ComputeDirection(vtkPolyData*, double *outDir); - - double ScaleFactor; - double Direction[3]; - int AutoDetectDirection; - -private: - vtkElevationSurfaceFilter(const vtkElevationSurfaceFilter&); - void operator =(const vtkElevationSurfaceFilter&); -}; -#endif diff --git a/src/Plugins/EllipseBuilder/CMakeLists.txt b/src/Plugins/EllipseBuilder/CMakeLists.txt index 8a8f06a9..bf4ec51f 100644 --- a/src/Plugins/EllipseBuilder/CMakeLists.txt +++ b/src/Plugins/EllipseBuilder/CMakeLists.txt @@ -1,36 +1,30 @@ -# Copyright (C) 2014-2019 CEA/DEN, EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# +cmake_minimum_required(VERSION 3.8) +project(EllipseBuilderFilter) +find_package(ParaView REQUIRED) -PROJECT(EllipseBuilder) +include(GNUInstallDirs) +set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_BINDIR}") +set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_LIBDIR}") +set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_LIBDIR}") -cmake_minimum_required(VERSION 2.8) +set("_paraview_plugin_default_${CMAKE_PROJECT_NAME}" ON) +paraview_plugin_scan( + ENABLE_BY_DEFAULT YES + PLUGIN_FILES "${CMAKE_CURRENT_SOURCE_DIR}/plugin/paraview.plugin" + PROVIDES_PLUGINS plugins + REQUIRES_MODULES required_modules) -FIND_PACKAGE(ParaView REQUIRED) -INCLUDE(${PARAVIEW_USE_FILE}) +foreach(module IN LISTS required_modules) + if(NOT TARGET "${module}") + message("Missing required module: ${module}") + return() + endif() +endforeach() -ADD_PARAVIEW_PLUGIN(EllipseBuilderFilter "1.0" - SERVER_MANAGER_XML EllipseBuilderFilter.xml - SERVER_MANAGER_SOURCES vtkEllipseBuilderFilter.cxx - GUI_RESOURCES pqEllipseBuilder.qrc - ) - -INSTALL( - TARGETS EllipseBuilderFilter - DESTINATION lib/paraview -) +set(BUILD_SHARED_LIBS ON) +paraview_plugin_build( + RUNTIME_DESTINATION "${CMAKE_INSTALL_BINDIR}" + LIBRARY_DESTINATION "${CMAKE_INSTALL_LIBDIR}" + LIBRARY_SUBDIRECTORY "${PARAVIEW_PLUGIN_SUBDIR}" + PLUGINS ${plugins} + AUTOLOAD ${plugins}) diff --git a/src/Plugins/EllipseBuilder/EllipseBuilderFilter.xml b/src/Plugins/EllipseBuilder/EllipseBuilderFilter.xml deleted file mode 100644 index 1bd5f0c1..00000000 --- a/src/Plugins/EllipseBuilder/EllipseBuilderFilter.xml +++ /dev/null @@ -1,118 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - This property specifies the name of the real field. - - - - - - - - - - - This property specifies the name of the image field. - - - - - - - - - - - - - - This property specifies the scale factor to scale every ellipse by. - - - - - - - This property sets the number of the points for every ellipse. - - - - - - - This property sets the start angle for every ellipse. - - - - - - - This property sets the end angle for every ellipse. - - - - - - - - diff --git a/src/Plugins/EllipseBuilder/plugin/CMakeLists.txt b/src/Plugins/EllipseBuilder/plugin/CMakeLists.txt new file mode 100644 index 00000000..92990fd9 --- /dev/null +++ b/src/Plugins/EllipseBuilder/plugin/CMakeLists.txt @@ -0,0 +1,18 @@ +set(qrc_files) +if(PARAVIEW_USE_QT) + list(APPEND qrc_files pqEllipseBuilder.qrc) +endif() + +paraview_add_plugin(EllipseBuilderFilter + VERSION "1.0" + UI_RESOURCES ${qrc_files} + MODULES EllipseBuilderModule + MODULE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/EllipseBuilderModule/vtk.module" + SERVER_MANAGER_XML filters.xml +) + +install(TARGETS EllipseBuilderFilter + RUNTIME DESTINATION lib/paraview + LIBRARY DESTINATION lib/paraview + ARCHIVE DESTINATION lib/paraview + ) diff --git a/src/Plugins/EllipseBuilder/plugin/EllipseBuilderModule/CMakeLists.txt b/src/Plugins/EllipseBuilder/plugin/EllipseBuilderModule/CMakeLists.txt new file mode 100644 index 00000000..7379275c --- /dev/null +++ b/src/Plugins/EllipseBuilder/plugin/EllipseBuilderModule/CMakeLists.txt @@ -0,0 +1,8 @@ +set(classes + vtkEllipseBuilderFilter +) + +vtk_module_add_module(EllipseBuilderModule + FORCE_STATIC + CLASSES ${classes} +) diff --git a/src/Plugins/EllipseBuilder/plugin/EllipseBuilderModule/vtk.module b/src/Plugins/EllipseBuilder/plugin/EllipseBuilderModule/vtk.module new file mode 100644 index 00000000..c5e50d35 --- /dev/null +++ b/src/Plugins/EllipseBuilder/plugin/EllipseBuilderModule/vtk.module @@ -0,0 +1,11 @@ +NAME + EllipseBuilderModule +DEPENDS + VTK::CommonCore + VTK::CommonDataModel + VTK::CommonExecutionModel + VTK::FiltersCore +PRIVATE_DEPENDS + VTK::CommonMisc + VTK::CommonSystem + VTK::FiltersGeneral diff --git a/src/Plugins/EllipseBuilder/plugin/EllipseBuilderModule/vtkEllipseBuilderFilter.cxx b/src/Plugins/EllipseBuilder/plugin/EllipseBuilderModule/vtkEllipseBuilderFilter.cxx new file mode 100644 index 00000000..f8f1020f --- /dev/null +++ b/src/Plugins/EllipseBuilder/plugin/EllipseBuilderModule/vtkEllipseBuilderFilter.cxx @@ -0,0 +1,319 @@ +// Copyright (C) 2014-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// + +#include "vtkEllipseBuilderFilter.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +using namespace std; + +//------------------------------------------------------------------------------ +bool isStringInList(const list& aList, const string& theName) +{ + list::const_iterator anIter; + for (anIter = aList.begin(); anIter != aList.end(); anIter++) + { + // Compares the values of the string. + if ( (*anIter).compare(theName) == 0) + return true; + } + return false; +} + +//------------------------------------------------------------------------------ +void add2List(const list& theSource, list& theDestination) +{ + list::const_iterator anIter; + for (anIter = theSource.begin(); anIter != theSource.end(); anIter++) + { + // Add the item to the list if it does not exist + if (!isStringInList(theDestination, *anIter)) + theDestination.push_back(*anIter); + } +} + +//------------------------------------------------------------------------------ +double maximumElement(vector< complex >& theList) +{ + double aMaximum; + vector tmpList; + vector< complex >::iterator it; + for (it = theList.begin(); it != theList.end(); ++it) + { + tmpList.push_back(((*it)*conj(*it)).real()); + } + aMaximum = *max_element(tmpList.begin(), tmpList.end()); + return aMaximum; +} + +//------------------------------------------------------------------------------ +list GetListOfFields(vtkDataObject* theObject) +{ + list aList; + + if (theObject->IsA("vtkDataSet")) + { + vtkDataSet* aDataSet = vtkDataSet::SafeDownCast(theObject); + vtkPointData* aPntData = aDataSet->GetPointData(); + + // Add fields name on points + int aNbArrays = aPntData->GetNumberOfArrays(); + for (int i = 0; iGetArray(i) ) { + //Data array should contains at least 3 components (1 - DX, 2 - DY, 3 - DZ) + if( anArray->GetNumberOfComponents() >= 3 ) { + const char* aName = aPntData->GetArrayName(i); + aList.push_back(aName); + } + } + } + } + return aList; +} + +//------------------------------------------------------------------------------ +vtkStandardNewMacro(vtkEllipseBuilderFilter); + +//------------------------------------------------------------------------------ +vtkEllipseBuilderFilter::vtkEllipseBuilderFilter() : vtkMultiBlockDataSetAlgorithm() +{ + this->RealField = NULL; + this->ImagField = NULL; + this->FieldList = vtkStringArray::New(); +} + +//------------------------------------------------------------------------------ +vtkEllipseBuilderFilter::~vtkEllipseBuilderFilter() +{ + this->SetRealField(NULL); + this->SetRealField(NULL); + this->FieldList->Delete(); +} + +//------------------------------------------------------------------------------ +int vtkEllipseBuilderFilter::RequestData(vtkInformation* vtkNotUsed(request), + vtkInformationVector** theInputVector, + vtkInformationVector* theOutputVector) +{ + int aResolution = this->Resolution; + if(aResolution <=0 ) + return 0; + if( this->ScaleFactor == 0.0 ) + return 0; + + int anAxis = this->Axis; + + // Get the info objects + vtkMultiBlockDataSet* anInputMDSet = vtkMultiBlockDataSet::GetData(theInputVector[0], 0); + vtkMultiBlockDataSet* anOutputMDSet = vtkMultiBlockDataSet::GetData(theOutputVector, 0); + + double a, b, z_point; + vector< complex > circle; + + // Points Ellipses + double range, min, max, delta; + if(this->EndAngle > this->StartAngle) { + min = this->StartAngle; + max = this->EndAngle; + } else { + min = this->StartAngle; + max = this->EndAngle + 360.; + } + range = max-min; + delta = range/(double)aResolution; + for (double iter = min; iter < max; iter+=delta) + { + a = cos(vtkMath::RadiansFromDegrees(iter)); + b = sin(vtkMath::RadiansFromDegrees(iter)); + complex aVal(a, b); + circle.push_back(aVal); + } + + //Scale Factor + double aScaleFactor; + aScaleFactor = 1./this->ScaleFactor; + + vtkDataObjectTreeIterator* anIter = anInputMDSet->NewTreeIterator(); + anIter->VisitOnlyLeavesOff(); + bool created = false; + for (anIter->InitTraversal(); !anIter->IsDoneWithTraversal(); anIter->GoToNextItem()) + { + vtkDataObject* anInputNode = anInputMDSet->GetDataSet(anIter); + if (anInputNode->IsA("vtkDataSet")) + { + vtkUnstructuredGrid* aSourceDS = vtkUnstructuredGrid::SafeDownCast(anInputNode); + if(!aSourceDS) continue; + + vtkPointData* aPointData = aSourceDS->GetPointData(); + if(!aPointData) continue; + + int aNumberPoints = aSourceDS->GetNumberOfPoints(); + + vtkDataArray* aRealArray = vtkDataArray::SafeDownCast(aPointData->GetArray(this->RealField)); + vtkDataArray* anImagArray = vtkDataArray::SafeDownCast(aPointData->GetArray(this->ImagField)); + + if(!aRealArray || !anImagArray) continue; + + int aNumberOfRealComponents = aRealArray->GetNumberOfComponents(); + int aNumberOfImagComponents = anImagArray->GetNumberOfComponents(); + if (aNumberOfRealComponents >= 3 && aNumberOfImagComponents >= 3) + { + anOutputMDSet->CopyStructure(anInputMDSet); + vtkUnstructuredGrid* aCloneDS = aSourceDS->NewInstance(); + vtkPoints* aClonePoints = vtkPoints::New(); + aCloneDS->SetPoints(aClonePoints); + aClonePoints->Delete(); + anOutputMDSet->SetDataSet(anIter, aCloneDS); + aCloneDS->Delete(); + double rx, ry, ix, iy; + created = true; + for (int j = 0; j < aNumberPoints; j++) + { + z_point = aSourceDS->GetPoint(j)[2]; + + if (anAxis == 2) // Z : DX and DY + { + rx = aRealArray->GetTuple(j)[0]; + ry = aRealArray->GetTuple(j)[1]; + ix = anImagArray->GetTuple(j)[0]; + iy = anImagArray->GetTuple(j)[1]; + } + else if (anAxis == 1) // Y : DX and DZ + { + rx = aRealArray->GetTuple(j)[0]; + ry = aRealArray->GetTuple(j)[2]; + ix = anImagArray->GetTuple(j)[0]; + iy = anImagArray->GetTuple(j)[2]; + } + else // X : DY and DZ + { + rx = aRealArray->GetTuple(j)[1]; + ry = aRealArray->GetTuple(j)[2]; + ix = anImagArray->GetTuple(j)[1]; + iy = anImagArray->GetTuple(j)[2]; + } + + complex x(rx, ix); + complex y(ry, iy); + + x = x / aScaleFactor; + y = y / aScaleFactor; + + double x_point, y_point; + for (std::size_t r = 0; r < circle.size(); r++) + { + x_point = (x*circle[r]).real(); + y_point = (y*circle[r]).real(); + vtkIdType anId[1]; + if (anAxis == 2) + anId[0] = aClonePoints->InsertNextPoint(x_point, y_point, z_point); + else if (anAxis == 1) + anId[0] = aClonePoints->InsertNextPoint(x_point, z_point, y_point); + else + anId[0] = aClonePoints->InsertNextPoint(z_point, x_point, y_point); + aCloneDS->InsertNextCell(VTK_VERTEX, 1, anId); + } + } + } + else + { + continue; + } + } + } + anIter->Delete(); + if(!created) + return 0; + return 1; +} + +//------------------------------------------------------------------------------ +int vtkEllipseBuilderFilter::RequestInformation(vtkInformation* request, + vtkInformationVector **theInputVector, + vtkInformationVector *theOutputVector) +{ + // Retrieve an instance of vtkMultiBlockDataSet class from an information object. + vtkMultiBlockDataSet* anInputMDataSet = vtkMultiBlockDataSet::GetData(theInputVector[0], 0); + + list aList; + vtkDataObjectTreeIterator* anIter = anInputMDataSet->NewTreeIterator(); + anIter->VisitOnlyLeavesOff(); + for (anIter->InitTraversal(); !anIter->IsDoneWithTraversal(); anIter->GoToNextItem()) + { + vtkDataObject* anInputNode = anInputMDataSet->GetDataSet(anIter); + if (anInputNode->IsA("vtkDataSet")) + { + list aSubList = GetListOfFields(anInputNode); + add2List(aSubList, aList); + } + } + anIter->Delete(); + + this->FieldList->Reset(); + this->FieldList->SetNumberOfValues((vtkIdType)aList.size()); + list::const_iterator anIterName; + int i = 0; + for (anIterName = aList.begin(); anIterName != aList.end(); anIterName++) + { + this->FieldList->SetValue(i, *anIterName); + i++; + } + + return this->Superclass::RequestInformation(request, theInputVector, theOutputVector); +} + + +//------------------------------------------------------------------------------ +vtkStringArray* vtkEllipseBuilderFilter::GetFieldList() +{ + return this->FieldList; +} + +//------------------------------------------------------------------------------ +void vtkEllipseBuilderFilter::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os, indent); + os << indent << "Real Field : " << this->RealField << endl; + os << indent << "Imag Field : " << this->ImagField << endl; + os << indent << "Start Angle : " << this->StartAngle << endl; + os << indent << "End Angle : " << this->EndAngle << endl; + os << indent << "Scale Factor : " << this->ScaleFactor << endl; + os << indent << "Scale Resolution : " << this->Resolution << endl; + os << indent << "Axis : " << this->Axis << endl; +} + diff --git a/src/Plugins/EllipseBuilder/plugin/EllipseBuilderModule/vtkEllipseBuilderFilter.h b/src/Plugins/EllipseBuilder/plugin/EllipseBuilderModule/vtkEllipseBuilderFilter.h new file mode 100644 index 00000000..c6ded89e --- /dev/null +++ b/src/Plugins/EllipseBuilder/plugin/EllipseBuilderModule/vtkEllipseBuilderFilter.h @@ -0,0 +1,99 @@ +// Copyright (C) 2014-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// + +#ifndef __ElliplseBuilderFilter_h +#define __ElliplseBuilderFilter_h + +#include + +class vtkDataObjectTreeIterator; +class vtkStringArray; + +/** + * Description of class: TODO + */ +class vtkEllipseBuilderFilter : public vtkMultiBlockDataSetAlgorithm +{ +public: + /// Returns pointer on a new instance of the class + static vtkEllipseBuilderFilter* New(); + + vtkTypeMacro(vtkEllipseBuilderFilter, vtkMultiBlockDataSetAlgorithm); + + /// Prints current state of the objects + void PrintSelf(ostream& os, vtkIndent indent) override; + + /// Set and Get methods for scale factor + vtkSetMacro(ScaleFactor, double); + vtkGetMacro(ScaleFactor, double); + + virtual vtkStringArray* GetFieldList(); + + /// Set and Get methods for field of real part + vtkSetStringMacro(RealField); + vtkGetStringMacro(RealField); + + /// Set and Get methods for field of imag part + vtkSetStringMacro(ImagField); + vtkGetStringMacro(ImagField); + + /// Set and Get methods for start angle + vtkSetMacro(StartAngle, double); + vtkGetMacro(StartAngle, double); + + /// Set and Get methods for end angle + vtkSetMacro(EndAngle, double); + vtkGetMacro(EndAngle, double); + + /// Set and Get methods for resolution + vtkSetMacro(Resolution, int); + vtkGetMacro(Resolution, int); + + /// Set and Get methods for axis + vtkSetMacro(Axis, int); + vtkGetMacro(Axis, int); + +protected: + /// Constructor + vtkEllipseBuilderFilter(); + + /// Destructor + ~vtkEllipseBuilderFilter() override; + + /// A method which is called on filtering data + int RequestData(vtkInformation*, vtkInformationVector**, vtkInformationVector*) override; + int RequestInformation(vtkInformation*, vtkInformationVector**, vtkInformationVector*) override; + + vtkStringArray* FieldList; + + double ScaleFactor; + double StartAngle; + double EndAngle; + int Resolution; + int Axis; + char* RealField; + char* ImagField; + +private: + /// Methods for copy of the filter: Not implemented + vtkEllipseBuilderFilter(const vtkEllipseBuilderFilter&) = delete; + void operator=(const vtkEllipseBuilderFilter&) = delete; +}; + +#endif diff --git a/src/Plugins/EllipseBuilder/plugin/filters.xml b/src/Plugins/EllipseBuilder/plugin/filters.xml new file mode 100644 index 00000000..f7d66736 --- /dev/null +++ b/src/Plugins/EllipseBuilder/plugin/filters.xml @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + This property specifies the name of the real field. + + + + + + + + + + + This property specifies the name of the image field. + + + + + + + + + + + + + + This property specifies the scale factor to scale every ellipse by. + + + + + + + This property sets the number of the points for every ellipse. + + + + + + + This property sets the start angle for every ellipse. + + + + + + + This property sets the end angle for every ellipse. + + + + + + + + diff --git a/src/Plugins/EllipseBuilder/plugin/paraview.plugin b/src/Plugins/EllipseBuilder/plugin/paraview.plugin new file mode 100644 index 00000000..519c16a0 --- /dev/null +++ b/src/Plugins/EllipseBuilder/plugin/paraview.plugin @@ -0,0 +1,8 @@ +NAME + EllipseBuilderFilter +DESCRIPTION + This plugin provides the Ellipse Builder filter. +REQUIRES_MODULES + VTK::CommonCore + VTK::IOCore + VTK::FiltersCore diff --git a/src/Plugins/EllipseBuilder/plugin/pqEllipseBuilder.qrc b/src/Plugins/EllipseBuilder/plugin/pqEllipseBuilder.qrc new file mode 100644 index 00000000..677e155b --- /dev/null +++ b/src/Plugins/EllipseBuilder/plugin/pqEllipseBuilder.qrc @@ -0,0 +1,5 @@ + + + resources/ellipse-icon.png + + \ No newline at end of file diff --git a/src/Plugins/EllipseBuilder/plugin/resources/ellipse-icon.png b/src/Plugins/EllipseBuilder/plugin/resources/ellipse-icon.png new file mode 100644 index 00000000..9b0c3a8d Binary files /dev/null and b/src/Plugins/EllipseBuilder/plugin/resources/ellipse-icon.png differ diff --git a/src/Plugins/EllipseBuilder/pqEllipseBuilder.qrc b/src/Plugins/EllipseBuilder/pqEllipseBuilder.qrc deleted file mode 100644 index 677e155b..00000000 --- a/src/Plugins/EllipseBuilder/pqEllipseBuilder.qrc +++ /dev/null @@ -1,5 +0,0 @@ - - - resources/ellipse-icon.png - - \ No newline at end of file diff --git a/src/Plugins/EllipseBuilder/resources/ellipse-icon.png b/src/Plugins/EllipseBuilder/resources/ellipse-icon.png deleted file mode 100644 index 9b0c3a8d..00000000 Binary files a/src/Plugins/EllipseBuilder/resources/ellipse-icon.png and /dev/null differ diff --git a/src/Plugins/EllipseBuilder/vtkEllipseBuilderFilter.cxx b/src/Plugins/EllipseBuilder/vtkEllipseBuilderFilter.cxx deleted file mode 100644 index dbeb7ac5..00000000 --- a/src/Plugins/EllipseBuilder/vtkEllipseBuilderFilter.cxx +++ /dev/null @@ -1,318 +0,0 @@ -// Copyright (C) 2014-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// - -#include "vtkEllipseBuilderFilter.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -using namespace std; - -//------------------------------------------------------------------------------ -bool isStringInList(const list& aList, const string& theName) -{ - list::const_iterator anIter; - for (anIter = aList.begin(); anIter != aList.end(); anIter++) - { - // Compares the values of the string. - if ( (*anIter).compare(theName) == 0) - return true; - } - return false; -} - -//------------------------------------------------------------------------------ -void add2List(const list& theSource, list& theDestination) -{ - list::const_iterator anIter; - for (anIter = theSource.begin(); anIter != theSource.end(); anIter++) - { - // Add the item to the list if it does not exist - if (!isStringInList(theDestination, *anIter)) - theDestination.push_back(*anIter); - } -} - -//------------------------------------------------------------------------------ -double maximumElement(vector< complex >& theList) -{ - double aMaximum; - vector tmpList; - vector< complex >::iterator it; - for (it = theList.begin(); it != theList.end(); ++it) - { - tmpList.push_back(((*it)*conj(*it)).real()); - } - aMaximum = *max_element(tmpList.begin(), tmpList.end()); - return aMaximum; -} - -//------------------------------------------------------------------------------ -list GetListOfFields(vtkDataObject* theObject) -{ - list aList; - - if (theObject->IsA("vtkDataSet")) - { - vtkDataSet* aDataSet = vtkDataSet::SafeDownCast(theObject); - vtkPointData* aPntData = aDataSet->GetPointData(); - - // Add fields name on points - int aNbArrays = aPntData->GetNumberOfArrays(); - for (int i = 0; iGetArray(i) ) { - //Data array should contains at least 3 components (1 - DX, 2 - DY, 3 - DZ) - if( anArray->GetNumberOfComponents() >= 3 ) { - const char* aName = aPntData->GetArrayName(i); - aList.push_back(aName); - } - } - } - } - return aList; -} - -//------------------------------------------------------------------------------ -vtkStandardNewMacro(vtkEllipseBuilderFilter); - -//------------------------------------------------------------------------------ -vtkEllipseBuilderFilter::vtkEllipseBuilderFilter() : vtkMultiBlockDataSetAlgorithm() -{ - this->RealField = NULL; - this->ImagField = NULL; - this->FieldList = vtkStringArray::New(); -} - -//------------------------------------------------------------------------------ -vtkEllipseBuilderFilter::~vtkEllipseBuilderFilter() -{ - this->SetRealField(NULL); - this->SetRealField(NULL); - this->FieldList->Delete(); -} - -//------------------------------------------------------------------------------ -int vtkEllipseBuilderFilter::RequestData(vtkInformation* vtkNotUsed(request), - vtkInformationVector** theInputVector, - vtkInformationVector* theOutputVector) -{ - int aResolution = this->Resolution; - if(aResolution <=0 ) - return 0; - if( this->ScaleFactor == 0.0 ) - return 0; - - int anAxis = this->Axis; - - // Get the info objects - vtkMultiBlockDataSet* anInputMDSet = vtkMultiBlockDataSet::GetData(theInputVector[0], 0); - vtkMultiBlockDataSet* anOutputMDSet = vtkMultiBlockDataSet::GetData(theOutputVector, 0); - - double a, b, z_point; - vector< complex > circle; - - // Points Ellipses - double range, min, max, delta; - if(this->EndAngle > this->StartAngle) { - min = this->StartAngle; - max = this->EndAngle; - } else { - min = this->StartAngle; - max = this->EndAngle + 360.; - } - range = max-min; - delta = range/(double)aResolution; - for (double iter = min; iter < max; iter+=delta) - { - a = cos(vtkMath::RadiansFromDegrees(iter)); - b = sin(vtkMath::RadiansFromDegrees(iter)); - complex aVal(a, b); - circle.push_back(aVal); - } - - //Scale Factor - double aScaleFactor; - aScaleFactor = 1./this->ScaleFactor; - - vtkDataObjectTreeIterator* anIter = anInputMDSet->NewTreeIterator(); - anIter->VisitOnlyLeavesOff(); - bool created = false; - for (anIter->InitTraversal(); !anIter->IsDoneWithTraversal(); anIter->GoToNextItem()) - { - vtkDataObject* anInputNode = anInputMDSet->GetDataSet(anIter); - if (anInputNode->IsA("vtkDataSet")) - { - vtkUnstructuredGrid* aSourceDS = vtkUnstructuredGrid::SafeDownCast(anInputNode); - if(!aSourceDS) continue; - - vtkPointData* aPointData = aSourceDS->GetPointData(); - if(!aPointData) continue; - - int aNumberPoints = aSourceDS->GetNumberOfPoints(); - - vtkDataArray* aRealArray = vtkDataArray::SafeDownCast(aPointData->GetArray(this->RealField)); - vtkDataArray* anImagArray = vtkDataArray::SafeDownCast(aPointData->GetArray(this->ImagField)); - - if(!aRealArray || !anImagArray) continue; - - int aNumberOfRealComponents = aRealArray->GetNumberOfComponents(); - int aNumberOfImagComponents = anImagArray->GetNumberOfComponents(); - if (aNumberOfRealComponents >= 3 && aNumberOfImagComponents >= 3) - { - anOutputMDSet->CopyStructure(anInputMDSet); - vtkUnstructuredGrid* aCloneDS = aSourceDS->NewInstance(); - vtkPoints* aClonePoints = vtkPoints::New(); - aCloneDS->SetPoints(aClonePoints); - aClonePoints->Delete(); - anOutputMDSet->SetDataSet(anIter, aCloneDS); - aCloneDS->Delete(); - double rx, ry, ix, iy; - created = true; - for (int j = 0; j < aNumberPoints; j++) - { - z_point = aSourceDS->GetPoint(j)[2]; - - if (anAxis == 2) // Z : DX and DY - { - rx = aRealArray->GetTuple(j)[0]; - ry = aRealArray->GetTuple(j)[1]; - ix = anImagArray->GetTuple(j)[0]; - iy = anImagArray->GetTuple(j)[1]; - } - else if (anAxis == 1) // Y : DX and DZ - { - rx = aRealArray->GetTuple(j)[0]; - ry = aRealArray->GetTuple(j)[2]; - ix = anImagArray->GetTuple(j)[0]; - iy = anImagArray->GetTuple(j)[2]; - } - else // X : DY and DZ - { - rx = aRealArray->GetTuple(j)[1]; - ry = aRealArray->GetTuple(j)[2]; - ix = anImagArray->GetTuple(j)[1]; - iy = anImagArray->GetTuple(j)[2]; - } - - complex x(rx, ix); - complex y(ry, iy); - - x = x / aScaleFactor; - y = y / aScaleFactor; - - double x_point, y_point; - for (std::size_t r = 0; r < circle.size(); r++) - { - x_point = (x*circle[r]).real(); - y_point = (y*circle[r]).real(); - vtkIdType anId[1]; - if (anAxis == 2) - anId[0] = aClonePoints->InsertNextPoint(x_point, y_point, z_point); - else if (anAxis == 1) - anId[0] = aClonePoints->InsertNextPoint(x_point, z_point, y_point); - else - anId[0] = aClonePoints->InsertNextPoint(z_point, x_point, y_point); - aCloneDS->InsertNextCell(VTK_VERTEX, 1, anId); - } - } - } - else - { - continue; - } - } - } - anIter->Delete(); - if(!created) - return 0; - return 1; -} - -//------------------------------------------------------------------------------ -int vtkEllipseBuilderFilter::RequestInformation(vtkInformation* request, - vtkInformationVector **theInputVector, - vtkInformationVector *theOutputVector) -{ - // Retrieve an instance of vtkMultiBlockDataSet class from an information object. - vtkMultiBlockDataSet* anInputMDataSet = vtkMultiBlockDataSet::GetData(theInputVector[0], 0); - - list aList; - vtkDataObjectTreeIterator* anIter = anInputMDataSet->NewTreeIterator(); - anIter->VisitOnlyLeavesOff(); - for (anIter->InitTraversal(); !anIter->IsDoneWithTraversal(); anIter->GoToNextItem()) - { - vtkDataObject* anInputNode = anInputMDataSet->GetDataSet(anIter); - if (anInputNode->IsA("vtkDataSet")) - { - list aSubList = GetListOfFields(anInputNode); - add2List(aSubList, aList); - } - } - anIter->Delete(); - - this->FieldList->Reset(); - this->FieldList->SetNumberOfValues((vtkIdType)aList.size()); - list::const_iterator anIterName; - int i = 0; - for (anIterName = aList.begin(); anIterName != aList.end(); anIterName++) - { - this->FieldList->SetValue(i, *anIterName); - i++; - } - - return this->Superclass::RequestInformation(request, theInputVector, theOutputVector); -} - - -//------------------------------------------------------------------------------ -vtkStringArray* vtkEllipseBuilderFilter::GetFieldList() -{ - return this->FieldList; -} - -//------------------------------------------------------------------------------ -void vtkEllipseBuilderFilter::PrintSelf(ostream& os, vtkIndent indent) -{ - this->Superclass::PrintSelf(os, indent); - os << indent << "Real Field : " << this->RealField << endl; - os << indent << "Imag Field : " << this->ImagField << endl; - os << indent << "Start Angle : " << this->StartAngle << endl; - os << indent << "End Angle : " << this->EndAngle << endl; - os << indent << "Scale Factor : " << this->ScaleFactor << endl; - os << indent << "Scale Resolution : " << this->Resolution << endl; - os << indent << "Axis : " << this->Axis << endl; -} - diff --git a/src/Plugins/EllipseBuilder/vtkEllipseBuilderFilter.h b/src/Plugins/EllipseBuilder/vtkEllipseBuilderFilter.h deleted file mode 100644 index 630fd9e0..00000000 --- a/src/Plugins/EllipseBuilder/vtkEllipseBuilderFilter.h +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright (C) 2014-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// - -#ifndef __ElliplseBuilderFilter_h -#define __ElliplseBuilderFilter_h - -#include -#include - -class vtkDataObjectTreeIterator; -class vtkStringArray; - -/** - * Description of class: TODO -*/ -class vtkEllipseBuilderFilter : public vtkMultiBlockDataSetAlgorithm -{ -public: - /// Returns pointer on a new instance of the class - static vtkEllipseBuilderFilter* New(); - - vtkTypeMacro(vtkEllipseBuilderFilter, vtkMultiBlockDataSetAlgorithm); - - /// Prints current state of the objects - virtual void PrintSelf(ostream& os, vtkIndent indent); - - /// Set and Get methods for scale factor - vtkSetMacro(ScaleFactor, double); - vtkGetMacro(ScaleFactor, double); - - virtual vtkStringArray* GetFieldList(); - - /// Set and Get methods for field of real part - vtkSetStringMacro(RealField); - vtkGetStringMacro(RealField); - - /// Set and Get methods for field of imag part - vtkSetStringMacro(ImagField); - vtkGetStringMacro(ImagField); - - /// Set and Get methods for start angle - vtkSetMacro(StartAngle, double); - vtkGetMacro(StartAngle, double); - - /// Set and Get methods for end angle - vtkSetMacro(EndAngle, double); - vtkGetMacro(EndAngle, double); - - /// Set and Get methods for resolution - vtkSetMacro(Resolution, int); - vtkGetMacro(Resolution, int); - - /// Set and Get methods for axis - vtkSetMacro(Axis, int); - vtkGetMacro(Axis, int); - -protected: - /// Constructor - vtkEllipseBuilderFilter(); - - /// Destructor - virtual ~vtkEllipseBuilderFilter(); - - /// A method which is called on filtering data - virtual int RequestData(vtkInformation *, vtkInformationVector **, vtkInformationVector *); - virtual int RequestInformation(vtkInformation *, vtkInformationVector **, vtkInformationVector *); - - vtkStringArray* FieldList; - - double ScaleFactor; - double StartAngle; - double EndAngle; - int Resolution; - int Axis; - char* RealField; - char* ImagField; - -private: - /// Methods for copy of the filter: Not implemented - vtkEllipseBuilderFilter(const vtkEllipseBuilderFilter&); // Not implemented - void operator=(const vtkEllipseBuilderFilter&); // Not implemented -}; - -#endif diff --git a/src/Plugins/GaussToCell/CMakeLists.txt b/src/Plugins/GaussToCell/CMakeLists.txt index 347a9bc5..18938fe5 100644 --- a/src/Plugins/GaussToCell/CMakeLists.txt +++ b/src/Plugins/GaussToCell/CMakeLists.txt @@ -1,74 +1,30 @@ -# Copyright (C) 2018-2019 EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# -# Author : Anthony Geay (EDF R&D) - -PROJECT(VoroGauss) -CMAKE_MINIMUM_REQUIRED(VERSION 2.8) - -CMAKE_POLICY(SET CMP0003 NEW) -IF(${CMAKE_VERSION} VERSION_GREATER "3.0.0") - CMAKE_POLICY(SET CMP0022 OLD) - CMAKE_POLICY(SET CMP0023 OLD) -ENDIF() - -SET(MED_READER_VERSION "0.0.0") - -# Common CMake macros -# =================== -SET(CONFIGURATION_ROOT_DIR $ENV{CONFIGURATION_ROOT_DIR} CACHE PATH "Path to the Salome CMake configuration files") -IF(EXISTS ${CONFIGURATION_ROOT_DIR}) - LIST(APPEND CMAKE_MODULE_PATH "${CONFIGURATION_ROOT_DIR}/cmake") - INCLUDE(SalomeMacros) -ELSE() - MESSAGE(FATAL_ERROR "We absolutely need the Salome CMake configuration files, please define CONFIGURATION_ROOT_DIR !") -ENDIF() -FIND_PACKAGE(SalomePythonInterp REQUIRED) -FIND_PACKAGE(SalomePythonLibs REQUIRED) - -FIND_PACKAGE(ParaView REQUIRED) -IF(NOT ParaView_FOUND) - MESSAGE(FATAL_ERROR "Please locate ParaView." ) -ENDIF(NOT ParaView_FOUND) -INCLUDE(${PARAVIEW_USE_FILE}) - -SET(MEDCOUPLING_ROOT_DIR $ENV{MEDCOUPLING_ROOT_DIR} CACHE PATH "MEDCOUPLING_ROOT_DIR") -LIST(APPEND CMAKE_MODULE_PATH "${MEDCOUPLING_ROOT_DIR}/cmake_files") -FIND_PACKAGE(SalomeMEDCoupling REQUIRED) - -IF(MEDCOUPLING_USE_64BIT_IDS) - ADD_DEFINITIONS("-DMEDCOUPLING_USE_64BIT_IDS") -ENDIF(MEDCOUPLING_USE_64BIT_IDS) - -OPTION(BUILD_SHARED_LIBS "Build with shared libraries." ${VTK_BUILD_SHARED_LIBS}) - -SET(VTK_INSTALL_RUNTIME_DIR lib) -SET(VTK_INSTALL_LIBRARY_DIR lib) -SET(VTK_INSTALL_ARCHIVE_DIR lib) - -PV_PROCESS_MODULES() - -INCLUDE_DIRECTORIES( - ${MEDCOUPLING_INCLUDE_DIRS} -) - -ADD_PARAVIEW_PLUGIN(GaussToCellPlugin "1.0" - SERVER_MANAGER_SOURCES ${SM_SRCS} vtkGaussToCell.cxx - SERVER_MANAGER_XML GaussToCellServer.xml) -TARGET_LINK_LIBRARIES(GaussToCellPlugin ${MEDCoupling_medcoupling}) -INSTALL(TARGETS GaussToCellPlugin RUNTIME DESTINATION lib/paraview LIBRARY DESTINATION lib/paraview ARCHIVE DESTINATION lib/paraview) +cmake_minimum_required(VERSION 3.8) +project(GaussToCellPlugin) +find_package(ParaView REQUIRED) + +include(GNUInstallDirs) +set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_BINDIR}") +set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_LIBDIR}") +set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_LIBDIR}") + +set("_paraview_plugin_default_${CMAKE_PROJECT_NAME}" ON) +paraview_plugin_scan( + ENABLE_BY_DEFAULT YES + PLUGIN_FILES "${CMAKE_CURRENT_SOURCE_DIR}/plugin/paraview.plugin" + PROVIDES_PLUGINS plugins + REQUIRES_MODULES required_modules) + +foreach(module IN LISTS required_modules) + if(NOT TARGET "${module}") + message("Missing required module: ${module}") + return() + endif() +endforeach() + +set(BUILD_SHARED_LIBS ON) +paraview_plugin_build( + RUNTIME_DESTINATION "${CMAKE_INSTALL_BINDIR}" + LIBRARY_DESTINATION "${CMAKE_INSTALL_LIBDIR}" + LIBRARY_SUBDIRECTORY "${PARAVIEW_PLUGIN_SUBDIR}" + PLUGINS ${plugins} + AUTOLOAD ${plugins}) diff --git a/src/Plugins/GaussToCell/GaussToCellServer.xml b/src/Plugins/GaussToCell/GaussToCellServer.xml deleted file mode 100644 index 162081fb..00000000 --- a/src/Plugins/GaussToCell/GaussToCellServer.xml +++ /dev/null @@ -1,42 +0,0 @@ - - - - - - - - - - - - - This property specifies the input to the Level Scalars filter. - - - - - Foreach field on Gauss Points : computes a cell field lying of input mesh that is the average of the values associated to the set of Gauss points for each cell. - - - - Foreach field on Gauss Points : computes a cell field lying of input mesh that is the max of the values associated to the set of Gauss points for each cell. - - - - Foreach field on Gauss Points : computes a cell field lying of input mesh that is the min of the values associated to the set of Gauss points for each cell. - - - - - - - diff --git a/src/Plugins/GaussToCell/PG_3D.med b/src/Plugins/GaussToCell/PG_3D.med deleted file mode 100644 index 9c7e51e7..00000000 Binary files a/src/Plugins/GaussToCell/PG_3D.med and /dev/null differ diff --git a/src/Plugins/GaussToCell/TestCase.py b/src/Plugins/GaussToCell/TestCase.py deleted file mode 100644 index 35f68723..00000000 --- a/src/Plugins/GaussToCell/TestCase.py +++ /dev/null @@ -1,73 +0,0 @@ -# Copyright (C) 2018-2019 CEA/DEN, EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# - -from MEDLoader import * - -fname="VoroGauss1.med" -meshName="mesh" -mm=MEDFileUMesh() -coords=DataArrayDouble([0,0, 1,0, 2,0, 3,0, 4,0, 5,0, 0,1, 1,1, 2,1, 0,2, 1,2, 3,1, 4,1],13,2) -m0=MEDCouplingUMesh(meshName,2) -m0.setCoords(coords) -m0.allocateCells() -m0.insertNextCell(NORM_TRI3,[2,3,8]) -m0.insertNextCell(NORM_TRI3,[3,4,11]) -m0.insertNextCell(NORM_TRI3,[4,5,12]) -m0.insertNextCell(NORM_TRI3,[6,7,9]) -m0.insertNextCell(NORM_TRI3,[7,8,10]) -m0.insertNextCell(NORM_QUAD4,[0,1,7,6]) -m0.insertNextCell(NORM_QUAD4,[1,2,8,7]) -mm[0]=m0 -m1=MEDCouplingUMesh(meshName,1) -m1.setCoords(coords) -m1.allocateCells() -m1.insertNextCell(NORM_SEG2,[0,1]) -m1.insertNextCell(NORM_SEG2,[1,2]) -m1.insertNextCell(NORM_SEG2,[2,3]) -m1.insertNextCell(NORM_SEG2,[3,4]) -m1.insertNextCell(NORM_SEG2,[4,5]) -mm[-1]=m1 -mm.setFamilyFieldArr(0,DataArrayInt([-1,-1,-2,-3,-3,-1,-3])) -mm.setFamilyFieldArr(-1,DataArrayInt([-1,-4,-4,-4,-1])) -for i in [-1,-2,-3,-4]: - mm.setFamilyId("Fam_%d"%i,i) - mm.setFamiliesOnGroup("G%d"%(abs(i)),["Fam_%d"%i]) - pass -mm.write(fname,2) -# -f0=MEDCouplingFieldDouble(ON_GAUSS_PT) -f0.setMesh(m0) -f0.setName("MyFieldPG") ; f0.setMesh(m0) -f0.setGaussLocalizationOnType(NORM_TRI3,[0,0, 1,0, 0,1],[0.1,0.1, 0.8,0.1, 0.1,0.8],[0.3,0.3,0.4]) -f0.setGaussLocalizationOnType(NORM_QUAD4,[-1,-1, 1,-1, 1,1, -1,1],[-0.57735,-0.57735,0.57735,-0.57735,0.57735,0.57735,-0.57735,0.57735],[0.25,0.25,0.25,0.25]) -arr=DataArrayDouble(f0.getNumberOfTuplesExpected()) ; arr.iota() -arr=DataArrayDouble.Meld(arr,arr) -arr.setInfoOnComponents(["comp0","comp1"]) -f0.setArray(arr) -WriteFieldUsingAlreadyWrittenMesh(fname,f0) -# -f1=MEDCouplingFieldDouble(ON_CELLS) -f1.setMesh(m0) -f1.setName("MyFieldCell") ; f1.setMesh(m0) -arr=DataArrayDouble(f1.getNumberOfTuplesExpected()) ; arr.iota() -arr=DataArrayDouble.Meld(arr,arr) -arr.setInfoOnComponents(["comp2","comp3"]) -f1.setArray(arr) -WriteFieldUsingAlreadyWrittenMesh(fname,f1) - diff --git a/src/Plugins/GaussToCell/plugin/CMakeLists.txt b/src/Plugins/GaussToCell/plugin/CMakeLists.txt new file mode 100644 index 00000000..32593afb --- /dev/null +++ b/src/Plugins/GaussToCell/plugin/CMakeLists.txt @@ -0,0 +1,46 @@ +# Common CMake macros +# =================== +set(TMP_CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH}) +unset(CMAKE_MODULE_PATH) +set(CONFIGURATION_ROOT_DIR $ENV{CONFIGURATION_ROOT_DIR} CACHE PATH "Path to the Salome CMake configuration files") +if(EXISTS ${CONFIGURATION_ROOT_DIR}) + list(APPEND CMAKE_MODULE_PATH "${CONFIGURATION_ROOT_DIR}/cmake") + include(SalomeMacros) +else() + message(FATAL_ERROR "We absolutely need the Salome CMake configuration files, please define CONFIGURATION_ROOT_DIR !") +endif() + +set(MEDCOUPLING_ROOT_DIR $ENV{MEDCOUPLING_ROOT_DIR} CACHE PATH "Path to the MEDCoupling tool") +if(EXISTS ${MEDCOUPLING_ROOT_DIR}) + list(APPEND CMAKE_MODULE_PATH "${MEDCOUPLING_ROOT_DIR}/cmake_files") +endif() +list(APPEND CMAKE_MODULE_PATH "${CMAKE_ROOT}/Modules") +list(APPEND CMAKE_MODULE_PATH ${TMP_CMAKE_MODULE_PATH}) + +include(SalomeSetupPlatform) +set(BUILD_SHARED_LIBS TRUE) + +find_package(SalomeHDF5 REQUIRED) +find_package(SalomeMEDCoupling REQUIRED) + +if(MEDCOUPLING_USE_64BIT_IDS) + add_definitions("-DMEDCOUPLING_USE_64BIT_IDS") +endif(MEDCOUPLING_USE_64BIT_IDS) + +SALOME_ACCUMULATE_ENVIRONMENT(PYTHONPATH NOCHECK ${CMAKE_INSTALL_PREFIX}/${SALOME_INSTALL_BINS} + ${CMAKE_INSTALL_PREFIX}/${SALOME_INSTALL_PYTHON}) +SALOME_ACCUMULATE_ENVIRONMENT(LD_LIBRARY_PATH NOCHECK ${CMAKE_INSTALL_PREFIX}/${SALOME_INSTALL_LIBS}) +SALOME_ACCUMULATE_ENVIRONMENT(PV_PLUGIN_PATH NOCHECK ${CMAKE_INSTALL_PREFIX}/lib/paraview) + +paraview_add_plugin(GaussToCellPlugin + VERSION "1.0" + MODULES GaussToCellModule + MODULE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/GaussToCellModule/vtk.module" + SERVER_MANAGER_XML filters.xml +) + +install(TARGETS GaussToCellPlugin + RUNTIME DESTINATION lib/paraview + LIBRARY DESTINATION lib/paraview + ARCHIVE DESTINATION lib/paraview + ) diff --git a/src/Plugins/GaussToCell/plugin/GaussToCellModule/CMakeLists.txt b/src/Plugins/GaussToCell/plugin/GaussToCellModule/CMakeLists.txt new file mode 100644 index 00000000..25ced302 --- /dev/null +++ b/src/Plugins/GaussToCell/plugin/GaussToCellModule/CMakeLists.txt @@ -0,0 +1,17 @@ +set(classes + vtkGaussToCell +) + +vtk_module_add_module(GaussToCellModule + FORCE_STATIC + CLASSES ${classes} +) + +target_include_directories(GaussToCellModule PRIVATE ${MEDCOUPLING_INCLUDE_DIRS}) + +if(HDF5_IS_PARALLEL) + target_link_libraries(GaussToCellModule PRIVATE ${MEDCoupling_paramedloader}) +else() + target_link_libraries(GaussToCellModule PRIVATE ${MEDCoupling_medloader}) +endif() + diff --git a/src/Plugins/GaussToCell/plugin/GaussToCellModule/vtk.module b/src/Plugins/GaussToCell/plugin/GaussToCellModule/vtk.module new file mode 100644 index 00000000..72789698 --- /dev/null +++ b/src/Plugins/GaussToCell/plugin/GaussToCellModule/vtk.module @@ -0,0 +1,8 @@ +NAME + GaussToCellModule +DEPENDS + VTK::CommonCore + VTK::CommonExecutionModel + VTK::FiltersGeneral +PRIVATE_DEPENDS + ParaView::VTKExtensionsMisc diff --git a/src/Plugins/GaussToCell/plugin/GaussToCellModule/vtkGaussToCell.cxx b/src/Plugins/GaussToCell/plugin/GaussToCellModule/vtkGaussToCell.cxx new file mode 100644 index 00000000..d3873c9d --- /dev/null +++ b/src/Plugins/GaussToCell/plugin/GaussToCellModule/vtkGaussToCell.cxx @@ -0,0 +1,389 @@ +// Copyright (C) 2018-2019 EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay (EDF R&D) + +#include "vtkGaussToCell.h" + +#include "vtkAdjacentVertexIterator.h" +#include "vtkIntArray.h" +#include "vtkCellData.h" +#include "vtkPointData.h" +#include "vtkCellType.h" +#include "vtkCell.h" +#include "vtkCellArray.h" +#include "vtkIdTypeArray.h" + +#include "vtkStreamingDemandDrivenPipeline.h" +#include "vtkUnstructuredGrid.h" +#include "vtkMultiBlockDataSet.h" + +#include "vtkInformationStringKey.h" +#include "vtkAlgorithmOutput.h" +#include "vtkObjectFactory.h" +#include "vtkMutableDirectedGraph.h" +#include "vtkMultiBlockDataSet.h" +#include "vtkDataSet.h" +#include "vtkInformationVector.h" +#include "vtkInformation.h" +#include "vtkDataArraySelection.h" +#include "vtkTimeStamp.h" +#include "vtkInEdgeIterator.h" +#include "vtkInformationDataObjectKey.h" +#include "vtkInformationDataObjectMetaDataKey.h" +#include "vtkInformationDoubleVectorKey.h" +#include "vtkExecutive.h" +#include "vtkVariantArray.h" +#include "vtkStringArray.h" +#include "vtkDoubleArray.h" +#include "vtkFloatArray.h" +#include "vtkCharArray.h" +#include "vtkLongArray.h" +#include "vtkUnsignedCharArray.h" +#include "vtkDataSetAttributes.h" +#include "vtkDemandDrivenPipeline.h" +#include "vtkDataObjectTreeIterator.h" +#include "vtkWarpScalar.h" +#include "vtkQuadratureSchemeDefinition.h" +#include "vtkInformationQuadratureSchemeDefinitionVectorKey.h" +#include "vtkCompositeDataToUnstructuredGridFilter.h" +#include "vtkMultiBlockDataGroupFilter.h" + +#include "MEDCouplingMemArray.hxx" +#include "MEDCouplingUMesh.hxx" +#include "MEDCouplingFieldDouble.hxx" +#include "InterpKernelAutoPtr.hxx" +#include "InterpKernelGaussCoords.hxx" + +#include +#include +#include +#include + +using MEDCoupling::DataArray; +using MEDCoupling::DataArrayInt32; +using MEDCoupling::DataArrayInt64; +using MEDCoupling::DataArrayDouble; +using MEDCoupling::MEDCouplingMesh; +using MEDCoupling::MEDCouplingUMesh; +using MEDCoupling::DynamicCastSafe; +using MEDCoupling::MEDCouplingFieldDouble; +using MEDCoupling::ON_GAUSS_PT; +using MEDCoupling::MCAuto; + +vtkStandardNewMacro(vtkGaussToCell); + +vtkInformationDoubleVectorKey *GetMEDReaderMetaDataIfAny() +{ + static const char ZE_KEY[]="vtkMEDReader::GAUSS_DATA"; + MEDCoupling::GlobalDict *gd(MEDCoupling::GlobalDict::GetInstance()); + if(!gd->hasKey(ZE_KEY)) + return 0; + std::string ptSt(gd->value(ZE_KEY)); + void *pt(0); + std::istringstream iss(ptSt); iss >> pt; + return reinterpret_cast(pt); +} + +bool IsInformationOK(vtkInformation *info, std::vector& data) +{ + vtkInformationDoubleVectorKey *key(GetMEDReaderMetaDataIfAny()); + if(!key) + return false; + // Check the information contain meta data key + if(!info->Has(key)) + return false; + int lgth(key->Length(info)); + const double *data2(info->Get(key)); + data.insert(data.end(),data2,data2+lgth); + return true; +} + +void ExtractInfo(vtkInformationVector *inputVector, vtkUnstructuredGrid *& usgIn) +{ + vtkInformation *inputInfo(inputVector->GetInformationObject(0)); + vtkDataSet *input(0); + vtkDataSet *input0(vtkDataSet::SafeDownCast(inputInfo->Get(vtkDataObject::DATA_OBJECT()))); + vtkMultiBlockDataSet *input1(vtkMultiBlockDataSet::SafeDownCast(inputInfo->Get(vtkDataObject::DATA_OBJECT()))); + if(input0) + input=input0; + else + { + if(!input1) + throw INTERP_KERNEL::Exception("Input dataSet must be a DataSet or single elt multi block dataset expected !"); + if(input1->GetNumberOfBlocks()!=1) + throw INTERP_KERNEL::Exception("Input dataSet is a multiblock dataset with not exactly one block ! Use MergeBlocks or ExtractBlocks filter before calling this filter !"); + vtkDataObject *input2(input1->GetBlock(0)); + if(!input2) + throw INTERP_KERNEL::Exception("Input dataSet is a multiblock dataset with exactly one block but this single element is NULL !"); + vtkDataSet *input2c(vtkDataSet::SafeDownCast(input2)); + if(!input2c) + throw INTERP_KERNEL::Exception("Input dataSet is a multiblock dataset with exactly one block but this single element is not a dataset ! Use MergeBlocks or ExtractBlocks filter before calling this filter !"); + input=input2c; + } + if(!input) + throw INTERP_KERNEL::Exception("Input data set is NULL !"); + usgIn=vtkUnstructuredGrid::SafeDownCast(input); + if(!usgIn) + throw INTERP_KERNEL::Exception("Input data set is not an unstructured mesh ! This filter works only on unstructured meshes !"); +} + +vtkGaussToCell::vtkGaussToCell():avgStatus(true),maxStatus(false),minStatus(false) +{ + this->SetNumberOfInputPorts(1); + this->SetNumberOfOutputPorts(1); +} + +vtkGaussToCell::~vtkGaussToCell() +{ +} + +void vtkGaussToCell::SetAvgFlag(bool avgStatus) +{ + if(this->avgStatus!=avgStatus) + { + this->avgStatus=avgStatus; + this->Modified(); + } +} + +void vtkGaussToCell::SetMaxFlag(bool maxStatus) +{ + if(this->maxStatus!=maxStatus) + { + this->maxStatus=maxStatus; + this->Modified(); + } +} + +void vtkGaussToCell::SetMinFlag(bool minStatus) +{ + if(this->minStatus!=minStatus) + { + this->minStatus=minStatus; + this->Modified(); + } +} + +int vtkGaussToCell::RequestInformation(vtkInformation *request, vtkInformationVector **inputVector, vtkInformationVector *outputVector) +{ + //std::cerr << "########################################## vtkGaussToCell::RequestInformation ##########################################" << std::endl; + try + { + vtkUnstructuredGrid *usgIn(0); + ExtractInfo(inputVector[0],usgIn); + } + catch(INTERP_KERNEL::Exception& e) + { + std::ostringstream oss; + oss << "Exception has been thrown in vtkGaussToCell::RequestInformation : " << e.what() << std::endl; + if(this->HasObserver("ErrorEvent") ) + this->InvokeEvent("ErrorEvent",const_cast(oss.str().c_str())); + else + vtkOutputWindowDisplayErrorText(const_cast(oss.str().c_str())); + vtkObject::BreakOnError(); + return 0; + } + return 1; +} + +typedef void (*DataComputer) (const double *inData, const vtkIdType *offData, const std::vector *nbgPerCell, int zeNbCompo, vtkIdType outNbCells, double *outData); + +void ComputeAvg(const double *inData, const vtkIdType *offData, const std::vector *nbgPerCell, int zeNbCompo, vtkIdType outNbCells, double *outData) +{ + std::fill(outData,outData+outNbCells*zeNbCompo,0.); + for(auto i=0;i *nbgPerCell, int zeNbCompo, vtkIdType outNbCells, double *outData) +{ + std::fill(outData,outData+outNbCells*zeNbCompo,-std::numeric_limits::max()); + for(auto i=0;i *nbgPerCell, int zeNbCompo, vtkIdType outNbCells, double *outData) +{ + std::fill(outData,outData+outNbCells*zeNbCompo,std::numeric_limits::max()); + for(auto i=0;i *nbgPerCell, vtkIdType outNbCells, vtkDoubleArray *zeOutArray, DataComputer dc) +{ + std::ostringstream oss; + oss << zearray->GetName() << '_' << postName; + int zeNbCompo(zearray->GetNumberOfComponents()); + { + std::string st(oss.str()); + zeOutArray->SetName(st.c_str()); + } + zeOutArray->SetNumberOfComponents(zeNbCompo); + zeOutArray->SetNumberOfTuples(outNbCells); + double *outData(zeOutArray->GetPointer(0)); + const double *inData(zearray->GetPointer(0)); + const auto *offData(offsets->GetPointer(0)); + for(auto i=0;iGetComponentName(i)); + if(comp) + zeOutArray->SetComponentName(i,comp); + } + dc(inData,offData,nbgPerCell,zeNbCompo,outNbCells,outData); +} + +int vtkGaussToCell::RequestData(vtkInformation *request, vtkInformationVector **inputVector, vtkInformationVector *outputVector) +{ + //std::cerr << "########################################## vtkGaussToCell::RequestData ##########################################" << std::endl; + try + { + std::vector GaussAdvData; + bool isOK(IsInformationOK(inputVector[0]->GetInformationObject(0),GaussAdvData)); + if(!isOK) + throw INTERP_KERNEL::Exception("Sorry but no advanced gauss info found ! Expect to be called right after a MEDReader containing Gauss Points !"); + vtkUnstructuredGrid *usgIn(0); + ExtractInfo(inputVector[0],usgIn); + vtkInformation *outInfo(outputVector->GetInformationObject(0)); + vtkUnstructuredGrid *output(vtkUnstructuredGrid::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT()))); + output->ShallowCopy(usgIn); + // + std::string zeArrOffset; + int nArrays(usgIn->GetFieldData()->GetNumberOfArrays()); + std::map > offsetKeyMap;//Map storing for each offsets array the corresponding nb of Gauss Points per cell + for(int i=0;iGetFieldData()->GetArray(i)); + if(!array) + continue; + const char* arrayOffsetName(array->GetInformation()->Get(vtkQuadratureSchemeDefinition::QUADRATURE_OFFSET_ARRAY_NAME())); + if(!arrayOffsetName) + continue; + std::string arrOffsetNameCpp(arrayOffsetName); + if(arrOffsetNameCpp.find("ELGA@")==std::string::npos) + continue; + if(zeArrOffset.empty()) + zeArrOffset=arrOffsetNameCpp; + else + if(zeArrOffset!=arrOffsetNameCpp) + { + throw INTERP_KERNEL::Exception("ComputeGaussToCell : error in QUADRATURE_OFFSET_ARRAY_NAME for Gauss fields array !"); + } + vtkDataArray *offTmp(usgIn->GetCellData()->GetArray(zeArrOffset.c_str())); + if(!offTmp) + { + std::ostringstream oss; oss << "ComputeGaussToCell : cell field " << zeArrOffset << " not found !"; + throw INTERP_KERNEL::Exception(oss.str()); + } + vtkIdTypeArray *offsets(vtkIdTypeArray::SafeDownCast(offTmp)); + if(!offsets) + { + std::ostringstream oss; oss << "ComputeGaussToCell : cell field " << zeArrOffset << " exists but not with the right type of data !"; + throw INTERP_KERNEL::Exception(oss.str()); + } + vtkDoubleArray *zearray(vtkDoubleArray::SafeDownCast(array)); + if(!zearray) + continue ; + // + std::map >::iterator nbgPerCellPt(offsetKeyMap.find(offsets)); + const std::vector *nbgPerCell(nullptr); + if(nbgPerCellPt==offsetKeyMap.end()) + { + // fini la parlote + vtkInformation *info(offsets->GetInformation()); + if(!info) + throw INTERP_KERNEL::Exception("info is null ! Internal error ! Looks bad !"); + vtkInformationQuadratureSchemeDefinitionVectorKey *key(vtkQuadratureSchemeDefinition::DICTIONARY()); + if(!key->Has(info)) + throw INTERP_KERNEL::Exception("No quadrature key in info included in offets array ! Internal error ! Looks bad !"); + int dictSize(key->Size(info)); + INTERP_KERNEL::AutoPtr dict(new vtkQuadratureSchemeDefinition *[dictSize]); + key->GetRange(info,dict,0,0,dictSize); + auto nbOfCells(output->GetNumberOfCells()); + std::vector nbg(nbOfCells); + for(auto cellId=0;cellIdGetCellType(cellId)); + vtkQuadratureSchemeDefinition *gaussLoc(dict[ct]); + if(!gaussLoc) + { + std::ostringstream oss; oss << "For cell " << cellId << " no Gauss info attached !"; + throw INTERP_KERNEL::Exception(oss.str()); + } + int np(gaussLoc->GetNumberOfQuadraturePoints()); + nbg[cellId]=np; + } + nbgPerCell=&((*(offsetKeyMap.emplace(offsets,std::move(nbg)).first)).second); + } + else + { + nbgPerCell=&((*nbgPerCellPt).second); + } + auto outNbCells(nbgPerCell->size()); + if(this->avgStatus) + { + vtkNew zeOutArray; + DealWith("avg",zearray,offsets,nbgPerCell,outNbCells,zeOutArray,ComputeAvg); + output->GetCellData()->AddArray(zeOutArray); + } + if(this->maxStatus) + { + vtkNew zeOutArray; + DealWith("max",zearray,offsets,nbgPerCell,outNbCells,zeOutArray,ComputeMax); + output->GetCellData()->AddArray(zeOutArray); + } + if(this->minStatus) + { + vtkNew zeOutArray; + DealWith("min",zearray,offsets,nbgPerCell,outNbCells,zeOutArray,ComputeMin); + output->GetCellData()->AddArray(zeOutArray); + } + } + } + catch(INTERP_KERNEL::Exception& e) + { + std::ostringstream oss; + oss << "Exception has been thrown in vtkGaussToCell::RequestData : " << e.what() << std::endl; + if(this->HasObserver("ErrorEvent") ) + this->InvokeEvent("ErrorEvent",const_cast(oss.str().c_str())); + else + vtkOutputWindowDisplayErrorText(const_cast(oss.str().c_str())); + vtkObject::BreakOnError(); + return 0; + } + return 1; +} + +void vtkGaussToCell::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os, indent); +} diff --git a/src/Plugins/GaussToCell/plugin/GaussToCellModule/vtkGaussToCell.h b/src/Plugins/GaussToCell/plugin/GaussToCellModule/vtkGaussToCell.h new file mode 100644 index 00000000..da91fce9 --- /dev/null +++ b/src/Plugins/GaussToCell/plugin/GaussToCellModule/vtkGaussToCell.h @@ -0,0 +1,58 @@ +// Copyright (C) 2018-2019 EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay (EDF R&D) + +#ifndef vtkGaussToCell_h__ +#define vtkGaussToCell_h__ + +#include + +class vtkMutableDirectedGraph; + +class VTK_EXPORT vtkGaussToCell : public vtkUnstructuredGridAlgorithm +{ +public: + static vtkGaussToCell* New(); + vtkTypeMacro(vtkGaussToCell, vtkUnstructuredGridAlgorithm); + void PrintSelf(ostream& os, vtkIndent indent) override; + + void SetAvgFlag(bool avgStatus); + + void SetMaxFlag(bool maxStatus); + + void SetMinFlag(bool minStatus); + +protected: + vtkGaussToCell(); + ~vtkGaussToCell() override; + + int RequestInformation(vtkInformation*, vtkInformationVector**, vtkInformationVector*) override; + + int RequestData(vtkInformation*, vtkInformationVector**, vtkInformationVector*) override; + + bool avgStatus; + bool maxStatus; + bool minStatus; + +private: + vtkGaussToCell(const vtkGaussToCell&); + void operator=(const vtkGaussToCell&); // Not implemented. +}; + +#endif diff --git a/src/Plugins/GaussToCell/plugin/filters.xml b/src/Plugins/GaussToCell/plugin/filters.xml new file mode 100644 index 00000000..728f5d22 --- /dev/null +++ b/src/Plugins/GaussToCell/plugin/filters.xml @@ -0,0 +1,45 @@ + + + + + + + + + + + + + This property specifies the input to the Level Scalars filter. + + + + + Foreach field on Gauss Points : computes a cell field lying of input mesh that is the average of the values associated to the set of Gauss points for each cell. + + + + Foreach field on Gauss Points : computes a cell field lying of input mesh that is the max of the values associated to the set of Gauss points for each cell. + + + + Foreach field on Gauss Points : computes a cell field lying of input mesh that is the min of the values associated to the set of Gauss points for each cell. + + + + + + + diff --git a/src/Plugins/GaussToCell/plugin/paraview.plugin b/src/Plugins/GaussToCell/plugin/paraview.plugin new file mode 100644 index 00000000..9ac8af7a --- /dev/null +++ b/src/Plugins/GaussToCell/plugin/paraview.plugin @@ -0,0 +1,6 @@ +NAME + GaussToCellPlugin +DESCRIPTION + This plugin provides the GaussToCell filter. +REQUIRES_MODULES + VTK::CommonCore diff --git a/src/Plugins/GaussToCell/script/PG_3D.med b/src/Plugins/GaussToCell/script/PG_3D.med new file mode 100644 index 00000000..9c7e51e7 Binary files /dev/null and b/src/Plugins/GaussToCell/script/PG_3D.med differ diff --git a/src/Plugins/GaussToCell/script/TestCase.py b/src/Plugins/GaussToCell/script/TestCase.py new file mode 100644 index 00000000..35f68723 --- /dev/null +++ b/src/Plugins/GaussToCell/script/TestCase.py @@ -0,0 +1,73 @@ +# Copyright (C) 2018-2019 CEA/DEN, EDF R&D +# +# This library 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. +# +# 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 +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +# + +from MEDLoader import * + +fname="VoroGauss1.med" +meshName="mesh" +mm=MEDFileUMesh() +coords=DataArrayDouble([0,0, 1,0, 2,0, 3,0, 4,0, 5,0, 0,1, 1,1, 2,1, 0,2, 1,2, 3,1, 4,1],13,2) +m0=MEDCouplingUMesh(meshName,2) +m0.setCoords(coords) +m0.allocateCells() +m0.insertNextCell(NORM_TRI3,[2,3,8]) +m0.insertNextCell(NORM_TRI3,[3,4,11]) +m0.insertNextCell(NORM_TRI3,[4,5,12]) +m0.insertNextCell(NORM_TRI3,[6,7,9]) +m0.insertNextCell(NORM_TRI3,[7,8,10]) +m0.insertNextCell(NORM_QUAD4,[0,1,7,6]) +m0.insertNextCell(NORM_QUAD4,[1,2,8,7]) +mm[0]=m0 +m1=MEDCouplingUMesh(meshName,1) +m1.setCoords(coords) +m1.allocateCells() +m1.insertNextCell(NORM_SEG2,[0,1]) +m1.insertNextCell(NORM_SEG2,[1,2]) +m1.insertNextCell(NORM_SEG2,[2,3]) +m1.insertNextCell(NORM_SEG2,[3,4]) +m1.insertNextCell(NORM_SEG2,[4,5]) +mm[-1]=m1 +mm.setFamilyFieldArr(0,DataArrayInt([-1,-1,-2,-3,-3,-1,-3])) +mm.setFamilyFieldArr(-1,DataArrayInt([-1,-4,-4,-4,-1])) +for i in [-1,-2,-3,-4]: + mm.setFamilyId("Fam_%d"%i,i) + mm.setFamiliesOnGroup("G%d"%(abs(i)),["Fam_%d"%i]) + pass +mm.write(fname,2) +# +f0=MEDCouplingFieldDouble(ON_GAUSS_PT) +f0.setMesh(m0) +f0.setName("MyFieldPG") ; f0.setMesh(m0) +f0.setGaussLocalizationOnType(NORM_TRI3,[0,0, 1,0, 0,1],[0.1,0.1, 0.8,0.1, 0.1,0.8],[0.3,0.3,0.4]) +f0.setGaussLocalizationOnType(NORM_QUAD4,[-1,-1, 1,-1, 1,1, -1,1],[-0.57735,-0.57735,0.57735,-0.57735,0.57735,0.57735,-0.57735,0.57735],[0.25,0.25,0.25,0.25]) +arr=DataArrayDouble(f0.getNumberOfTuplesExpected()) ; arr.iota() +arr=DataArrayDouble.Meld(arr,arr) +arr.setInfoOnComponents(["comp0","comp1"]) +f0.setArray(arr) +WriteFieldUsingAlreadyWrittenMesh(fname,f0) +# +f1=MEDCouplingFieldDouble(ON_CELLS) +f1.setMesh(m0) +f1.setName("MyFieldCell") ; f1.setMesh(m0) +arr=DataArrayDouble(f1.getNumberOfTuplesExpected()) ; arr.iota() +arr=DataArrayDouble.Meld(arr,arr) +arr.setInfoOnComponents(["comp2","comp3"]) +f1.setArray(arr) +WriteFieldUsingAlreadyWrittenMesh(fname,f1) + diff --git a/src/Plugins/GaussToCell/script/testMEDReader14.med b/src/Plugins/GaussToCell/script/testMEDReader14.med new file mode 100644 index 00000000..c7ff867f Binary files /dev/null and b/src/Plugins/GaussToCell/script/testMEDReader14.med differ diff --git a/src/Plugins/GaussToCell/testMEDReader14.med b/src/Plugins/GaussToCell/testMEDReader14.med deleted file mode 100644 index c7ff867f..00000000 Binary files a/src/Plugins/GaussToCell/testMEDReader14.med and /dev/null differ diff --git a/src/Plugins/GaussToCell/vtkGaussToCell.cxx b/src/Plugins/GaussToCell/vtkGaussToCell.cxx deleted file mode 100644 index d3873c9d..00000000 --- a/src/Plugins/GaussToCell/vtkGaussToCell.cxx +++ /dev/null @@ -1,389 +0,0 @@ -// Copyright (C) 2018-2019 EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Anthony Geay (EDF R&D) - -#include "vtkGaussToCell.h" - -#include "vtkAdjacentVertexIterator.h" -#include "vtkIntArray.h" -#include "vtkCellData.h" -#include "vtkPointData.h" -#include "vtkCellType.h" -#include "vtkCell.h" -#include "vtkCellArray.h" -#include "vtkIdTypeArray.h" - -#include "vtkStreamingDemandDrivenPipeline.h" -#include "vtkUnstructuredGrid.h" -#include "vtkMultiBlockDataSet.h" - -#include "vtkInformationStringKey.h" -#include "vtkAlgorithmOutput.h" -#include "vtkObjectFactory.h" -#include "vtkMutableDirectedGraph.h" -#include "vtkMultiBlockDataSet.h" -#include "vtkDataSet.h" -#include "vtkInformationVector.h" -#include "vtkInformation.h" -#include "vtkDataArraySelection.h" -#include "vtkTimeStamp.h" -#include "vtkInEdgeIterator.h" -#include "vtkInformationDataObjectKey.h" -#include "vtkInformationDataObjectMetaDataKey.h" -#include "vtkInformationDoubleVectorKey.h" -#include "vtkExecutive.h" -#include "vtkVariantArray.h" -#include "vtkStringArray.h" -#include "vtkDoubleArray.h" -#include "vtkFloatArray.h" -#include "vtkCharArray.h" -#include "vtkLongArray.h" -#include "vtkUnsignedCharArray.h" -#include "vtkDataSetAttributes.h" -#include "vtkDemandDrivenPipeline.h" -#include "vtkDataObjectTreeIterator.h" -#include "vtkWarpScalar.h" -#include "vtkQuadratureSchemeDefinition.h" -#include "vtkInformationQuadratureSchemeDefinitionVectorKey.h" -#include "vtkCompositeDataToUnstructuredGridFilter.h" -#include "vtkMultiBlockDataGroupFilter.h" - -#include "MEDCouplingMemArray.hxx" -#include "MEDCouplingUMesh.hxx" -#include "MEDCouplingFieldDouble.hxx" -#include "InterpKernelAutoPtr.hxx" -#include "InterpKernelGaussCoords.hxx" - -#include -#include -#include -#include - -using MEDCoupling::DataArray; -using MEDCoupling::DataArrayInt32; -using MEDCoupling::DataArrayInt64; -using MEDCoupling::DataArrayDouble; -using MEDCoupling::MEDCouplingMesh; -using MEDCoupling::MEDCouplingUMesh; -using MEDCoupling::DynamicCastSafe; -using MEDCoupling::MEDCouplingFieldDouble; -using MEDCoupling::ON_GAUSS_PT; -using MEDCoupling::MCAuto; - -vtkStandardNewMacro(vtkGaussToCell); - -vtkInformationDoubleVectorKey *GetMEDReaderMetaDataIfAny() -{ - static const char ZE_KEY[]="vtkMEDReader::GAUSS_DATA"; - MEDCoupling::GlobalDict *gd(MEDCoupling::GlobalDict::GetInstance()); - if(!gd->hasKey(ZE_KEY)) - return 0; - std::string ptSt(gd->value(ZE_KEY)); - void *pt(0); - std::istringstream iss(ptSt); iss >> pt; - return reinterpret_cast(pt); -} - -bool IsInformationOK(vtkInformation *info, std::vector& data) -{ - vtkInformationDoubleVectorKey *key(GetMEDReaderMetaDataIfAny()); - if(!key) - return false; - // Check the information contain meta data key - if(!info->Has(key)) - return false; - int lgth(key->Length(info)); - const double *data2(info->Get(key)); - data.insert(data.end(),data2,data2+lgth); - return true; -} - -void ExtractInfo(vtkInformationVector *inputVector, vtkUnstructuredGrid *& usgIn) -{ - vtkInformation *inputInfo(inputVector->GetInformationObject(0)); - vtkDataSet *input(0); - vtkDataSet *input0(vtkDataSet::SafeDownCast(inputInfo->Get(vtkDataObject::DATA_OBJECT()))); - vtkMultiBlockDataSet *input1(vtkMultiBlockDataSet::SafeDownCast(inputInfo->Get(vtkDataObject::DATA_OBJECT()))); - if(input0) - input=input0; - else - { - if(!input1) - throw INTERP_KERNEL::Exception("Input dataSet must be a DataSet or single elt multi block dataset expected !"); - if(input1->GetNumberOfBlocks()!=1) - throw INTERP_KERNEL::Exception("Input dataSet is a multiblock dataset with not exactly one block ! Use MergeBlocks or ExtractBlocks filter before calling this filter !"); - vtkDataObject *input2(input1->GetBlock(0)); - if(!input2) - throw INTERP_KERNEL::Exception("Input dataSet is a multiblock dataset with exactly one block but this single element is NULL !"); - vtkDataSet *input2c(vtkDataSet::SafeDownCast(input2)); - if(!input2c) - throw INTERP_KERNEL::Exception("Input dataSet is a multiblock dataset with exactly one block but this single element is not a dataset ! Use MergeBlocks or ExtractBlocks filter before calling this filter !"); - input=input2c; - } - if(!input) - throw INTERP_KERNEL::Exception("Input data set is NULL !"); - usgIn=vtkUnstructuredGrid::SafeDownCast(input); - if(!usgIn) - throw INTERP_KERNEL::Exception("Input data set is not an unstructured mesh ! This filter works only on unstructured meshes !"); -} - -vtkGaussToCell::vtkGaussToCell():avgStatus(true),maxStatus(false),minStatus(false) -{ - this->SetNumberOfInputPorts(1); - this->SetNumberOfOutputPorts(1); -} - -vtkGaussToCell::~vtkGaussToCell() -{ -} - -void vtkGaussToCell::SetAvgFlag(bool avgStatus) -{ - if(this->avgStatus!=avgStatus) - { - this->avgStatus=avgStatus; - this->Modified(); - } -} - -void vtkGaussToCell::SetMaxFlag(bool maxStatus) -{ - if(this->maxStatus!=maxStatus) - { - this->maxStatus=maxStatus; - this->Modified(); - } -} - -void vtkGaussToCell::SetMinFlag(bool minStatus) -{ - if(this->minStatus!=minStatus) - { - this->minStatus=minStatus; - this->Modified(); - } -} - -int vtkGaussToCell::RequestInformation(vtkInformation *request, vtkInformationVector **inputVector, vtkInformationVector *outputVector) -{ - //std::cerr << "########################################## vtkGaussToCell::RequestInformation ##########################################" << std::endl; - try - { - vtkUnstructuredGrid *usgIn(0); - ExtractInfo(inputVector[0],usgIn); - } - catch(INTERP_KERNEL::Exception& e) - { - std::ostringstream oss; - oss << "Exception has been thrown in vtkGaussToCell::RequestInformation : " << e.what() << std::endl; - if(this->HasObserver("ErrorEvent") ) - this->InvokeEvent("ErrorEvent",const_cast(oss.str().c_str())); - else - vtkOutputWindowDisplayErrorText(const_cast(oss.str().c_str())); - vtkObject::BreakOnError(); - return 0; - } - return 1; -} - -typedef void (*DataComputer) (const double *inData, const vtkIdType *offData, const std::vector *nbgPerCell, int zeNbCompo, vtkIdType outNbCells, double *outData); - -void ComputeAvg(const double *inData, const vtkIdType *offData, const std::vector *nbgPerCell, int zeNbCompo, vtkIdType outNbCells, double *outData) -{ - std::fill(outData,outData+outNbCells*zeNbCompo,0.); - for(auto i=0;i *nbgPerCell, int zeNbCompo, vtkIdType outNbCells, double *outData) -{ - std::fill(outData,outData+outNbCells*zeNbCompo,-std::numeric_limits::max()); - for(auto i=0;i *nbgPerCell, int zeNbCompo, vtkIdType outNbCells, double *outData) -{ - std::fill(outData,outData+outNbCells*zeNbCompo,std::numeric_limits::max()); - for(auto i=0;i *nbgPerCell, vtkIdType outNbCells, vtkDoubleArray *zeOutArray, DataComputer dc) -{ - std::ostringstream oss; - oss << zearray->GetName() << '_' << postName; - int zeNbCompo(zearray->GetNumberOfComponents()); - { - std::string st(oss.str()); - zeOutArray->SetName(st.c_str()); - } - zeOutArray->SetNumberOfComponents(zeNbCompo); - zeOutArray->SetNumberOfTuples(outNbCells); - double *outData(zeOutArray->GetPointer(0)); - const double *inData(zearray->GetPointer(0)); - const auto *offData(offsets->GetPointer(0)); - for(auto i=0;iGetComponentName(i)); - if(comp) - zeOutArray->SetComponentName(i,comp); - } - dc(inData,offData,nbgPerCell,zeNbCompo,outNbCells,outData); -} - -int vtkGaussToCell::RequestData(vtkInformation *request, vtkInformationVector **inputVector, vtkInformationVector *outputVector) -{ - //std::cerr << "########################################## vtkGaussToCell::RequestData ##########################################" << std::endl; - try - { - std::vector GaussAdvData; - bool isOK(IsInformationOK(inputVector[0]->GetInformationObject(0),GaussAdvData)); - if(!isOK) - throw INTERP_KERNEL::Exception("Sorry but no advanced gauss info found ! Expect to be called right after a MEDReader containing Gauss Points !"); - vtkUnstructuredGrid *usgIn(0); - ExtractInfo(inputVector[0],usgIn); - vtkInformation *outInfo(outputVector->GetInformationObject(0)); - vtkUnstructuredGrid *output(vtkUnstructuredGrid::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT()))); - output->ShallowCopy(usgIn); - // - std::string zeArrOffset; - int nArrays(usgIn->GetFieldData()->GetNumberOfArrays()); - std::map > offsetKeyMap;//Map storing for each offsets array the corresponding nb of Gauss Points per cell - for(int i=0;iGetFieldData()->GetArray(i)); - if(!array) - continue; - const char* arrayOffsetName(array->GetInformation()->Get(vtkQuadratureSchemeDefinition::QUADRATURE_OFFSET_ARRAY_NAME())); - if(!arrayOffsetName) - continue; - std::string arrOffsetNameCpp(arrayOffsetName); - if(arrOffsetNameCpp.find("ELGA@")==std::string::npos) - continue; - if(zeArrOffset.empty()) - zeArrOffset=arrOffsetNameCpp; - else - if(zeArrOffset!=arrOffsetNameCpp) - { - throw INTERP_KERNEL::Exception("ComputeGaussToCell : error in QUADRATURE_OFFSET_ARRAY_NAME for Gauss fields array !"); - } - vtkDataArray *offTmp(usgIn->GetCellData()->GetArray(zeArrOffset.c_str())); - if(!offTmp) - { - std::ostringstream oss; oss << "ComputeGaussToCell : cell field " << zeArrOffset << " not found !"; - throw INTERP_KERNEL::Exception(oss.str()); - } - vtkIdTypeArray *offsets(vtkIdTypeArray::SafeDownCast(offTmp)); - if(!offsets) - { - std::ostringstream oss; oss << "ComputeGaussToCell : cell field " << zeArrOffset << " exists but not with the right type of data !"; - throw INTERP_KERNEL::Exception(oss.str()); - } - vtkDoubleArray *zearray(vtkDoubleArray::SafeDownCast(array)); - if(!zearray) - continue ; - // - std::map >::iterator nbgPerCellPt(offsetKeyMap.find(offsets)); - const std::vector *nbgPerCell(nullptr); - if(nbgPerCellPt==offsetKeyMap.end()) - { - // fini la parlote - vtkInformation *info(offsets->GetInformation()); - if(!info) - throw INTERP_KERNEL::Exception("info is null ! Internal error ! Looks bad !"); - vtkInformationQuadratureSchemeDefinitionVectorKey *key(vtkQuadratureSchemeDefinition::DICTIONARY()); - if(!key->Has(info)) - throw INTERP_KERNEL::Exception("No quadrature key in info included in offets array ! Internal error ! Looks bad !"); - int dictSize(key->Size(info)); - INTERP_KERNEL::AutoPtr dict(new vtkQuadratureSchemeDefinition *[dictSize]); - key->GetRange(info,dict,0,0,dictSize); - auto nbOfCells(output->GetNumberOfCells()); - std::vector nbg(nbOfCells); - for(auto cellId=0;cellIdGetCellType(cellId)); - vtkQuadratureSchemeDefinition *gaussLoc(dict[ct]); - if(!gaussLoc) - { - std::ostringstream oss; oss << "For cell " << cellId << " no Gauss info attached !"; - throw INTERP_KERNEL::Exception(oss.str()); - } - int np(gaussLoc->GetNumberOfQuadraturePoints()); - nbg[cellId]=np; - } - nbgPerCell=&((*(offsetKeyMap.emplace(offsets,std::move(nbg)).first)).second); - } - else - { - nbgPerCell=&((*nbgPerCellPt).second); - } - auto outNbCells(nbgPerCell->size()); - if(this->avgStatus) - { - vtkNew zeOutArray; - DealWith("avg",zearray,offsets,nbgPerCell,outNbCells,zeOutArray,ComputeAvg); - output->GetCellData()->AddArray(zeOutArray); - } - if(this->maxStatus) - { - vtkNew zeOutArray; - DealWith("max",zearray,offsets,nbgPerCell,outNbCells,zeOutArray,ComputeMax); - output->GetCellData()->AddArray(zeOutArray); - } - if(this->minStatus) - { - vtkNew zeOutArray; - DealWith("min",zearray,offsets,nbgPerCell,outNbCells,zeOutArray,ComputeMin); - output->GetCellData()->AddArray(zeOutArray); - } - } - } - catch(INTERP_KERNEL::Exception& e) - { - std::ostringstream oss; - oss << "Exception has been thrown in vtkGaussToCell::RequestData : " << e.what() << std::endl; - if(this->HasObserver("ErrorEvent") ) - this->InvokeEvent("ErrorEvent",const_cast(oss.str().c_str())); - else - vtkOutputWindowDisplayErrorText(const_cast(oss.str().c_str())); - vtkObject::BreakOnError(); - return 0; - } - return 1; -} - -void vtkGaussToCell::PrintSelf(ostream& os, vtkIndent indent) -{ - this->Superclass::PrintSelf(os, indent); -} diff --git a/src/Plugins/GaussToCell/vtkGaussToCell.h b/src/Plugins/GaussToCell/vtkGaussToCell.h deleted file mode 100644 index 4d70e128..00000000 --- a/src/Plugins/GaussToCell/vtkGaussToCell.h +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright (C) 2018-2019 EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Anthony Geay (EDF R&D) - -#ifndef vtkGaussToCell_h__ -#define vtkGaussToCell_h__ - -#include "vtkUnstructuredGridAlgorithm.h" - -class vtkMutableDirectedGraph; - -class VTK_EXPORT vtkGaussToCell : public vtkUnstructuredGridAlgorithm -{ -public: - static vtkGaussToCell* New(); - vtkTypeMacro(vtkGaussToCell, vtkUnstructuredGridAlgorithm) - void PrintSelf(ostream& os, vtkIndent indent); - - void SetAvgFlag(bool avgStatus); - - void SetMaxFlag(bool maxStatus); - - void SetMinFlag(bool minStatus); - -protected: - vtkGaussToCell(); - ~vtkGaussToCell(); - - int RequestInformation(vtkInformation *request, - vtkInformationVector **inputVector, vtkInformationVector *outputVector); - - int RequestData(vtkInformation *request, vtkInformationVector **inputVector, - vtkInformationVector *outputVector); - -private: - vtkGaussToCell(const vtkGaussToCell&); - void operator=(const vtkGaussToCell&); // Not implemented. - private: - //BTX - //ETX - bool avgStatus; - bool maxStatus; - bool minStatus; -}; - -#endif diff --git a/src/Plugins/JSONReader/CMakeLists.txt b/src/Plugins/JSONReader/CMakeLists.txt index 7ec6b207..63ccaf4e 100644 --- a/src/Plugins/JSONReader/CMakeLists.txt +++ b/src/Plugins/JSONReader/CMakeLists.txt @@ -1,40 +1,30 @@ -# Copyright (C) 2015-2019 CEA/DEN, EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# +cmake_minimum_required(VERSION 3.8) +project(JSONReader) +find_package(ParaView REQUIRED) -# Author : Roman NIKOLAEV +include(GNUInstallDirs) +set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_BINDIR}") +set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_LIBDIR}") +set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_LIBDIR}") -PROJECT(JSONReader) +set("_paraview_plugin_default_${CMAKE_PROJECT_NAME}" ON) +paraview_plugin_scan( + ENABLE_BY_DEFAULT YES + PLUGIN_FILES "${CMAKE_CURRENT_SOURCE_DIR}/plugin/paraview.plugin" + PROVIDES_PLUGINS plugins + REQUIRES_MODULES required_modules) -cmake_minimum_required(VERSION 2.8) +foreach(module IN LISTS required_modules) + if(NOT TARGET "${module}") + message("Missing required module: ${module}") + return() + endif() +endforeach() -# Find ParaView -FIND_PACKAGE(ParaView REQUIRED) -INCLUDE(${PARAVIEW_USE_FILE}) - -# Standard CMake option for building libraries shared or static by default. -OPTION(BUILD_SHARED_LIBS "Build with shared libraries" ${VTK_BUILD_SHARED_LIBS}) - -# Add subdirectories -# ADD_SUBDIRECTORY(JSONParser) -#IF(SALOME_BUILD_TESTS) -# ENABLE_TESTING() -# ADD_SUBDIRECTORY(Test) -#ENDIF() - -ADD_SUBDIRECTORY(ParaViewPlugin) +set(BUILD_SHARED_LIBS ON) +paraview_plugin_build( + RUNTIME_DESTINATION "${CMAKE_INSTALL_BINDIR}" + LIBRARY_DESTINATION "${CMAKE_INSTALL_LIBDIR}" + LIBRARY_SUBDIRECTORY "${PARAVIEW_PLUGIN_SUBDIR}" + PLUGINS ${plugins} + AUTOLOAD ${plugins}) diff --git a/src/Plugins/JSONReader/JSONParser/CMakeLists.txt b/src/Plugins/JSONReader/JSONParser/CMakeLists.txt deleted file mode 100644 index 3535691e..00000000 --- a/src/Plugins/JSONReader/JSONParser/CMakeLists.txt +++ /dev/null @@ -1,30 +0,0 @@ -# Copyright (C) 2015-2019 CEA/DEN, EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# -# Author: Roman NIKOLAEV - -SET(PARCER_SRCS - vtkJSONParser.cxx) - -ADD_LIBRARY(vtkJSONParser ${PARCER_SRCS}) - -TARGET_LINK_LIBRARIES(vtkJSONParser ${VTK_LIBRARIES}) - -INSTALL( - TARGETS vtkJSONParser - DESTINATION lib/salome) diff --git a/src/Plugins/JSONReader/JSONParser/vtkJSONParser.cxx b/src/Plugins/JSONReader/JSONParser/vtkJSONParser.cxx deleted file mode 100644 index 19f6ee0c..00000000 --- a/src/Plugins/JSONReader/JSONParser/vtkJSONParser.cxx +++ /dev/null @@ -1,845 +0,0 @@ -// Copyright (C) 2015-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author: Roman NIKOLAEV - -#include "vtkJSONParser.h" - -#include -#include -#include -#include - -#include -#include -#include -#include - -//DEBUG macro -//#define __DEBUG - -#ifdef WIN32 -#include -#define NAN std::numeric_limits::quiet_NaN() -#define isnan _isnan -#endif - -// Key words -#define MD "_metadata" -#define CMT "_comment" -#define TBN "table_name" -#define TBD "table_description" -#define SHT "short_names" -#define LNG "long_names" -#define UNT "units" -#define DT "date" - -// Separators -#define COMMA ',' - -#define COLON ':' - -#define OSB '[' -#define CSB ']' - -#define OCB '{' -#define CCB '}' -#define ENDL '\n' -#define QTS '"' -#define SPS ' ' -#define TAB '\t' - -#define NA "n/a" - - -#define addInfo(info) \ - Info I; \ - I.type = info; \ - I.ln = this->LineNumber; \ - I.cn = this->ColumnNumber; \ - I.pos = ftell(this->File); \ - this->CInfoVector.push_back(I); - -//--------------------------------------------------- -bool isBlankOrEnd(const char c) { - return c == SPS || c == ENDL || c == TAB || c == EOF; -} - -bool isDigitOrDot(const char c) { - return (c >= '.' && c <='9') || c == '+' || c == '-' || c == 'e'; -} - -// Exception -//--------------------------------------------------- -vtkJSONException::vtkJSONException(const char *reason) : Reason(reason) { -} - -//--------------------------------------------------- -vtkJSONException::~vtkJSONException() throw () { -} - -//--------------------------------------------------- -const char* vtkJSONException::what() const throw() { - return Reason.c_str(); -} - -// Containers to store information about nodes: - -// Base node -//--------------------------------------------------- -class vtkJSONNode { -public: - vtkJSONNode() { Name = 0; } - virtual ~vtkJSONNode() { } - const char* GetName() { return this->Name ; } - void SetName(const char* name) { this->Name = name; } -private: - const char* Name; -}; - -class vtkJSONMetaNode : public vtkJSONNode { -public: - vtkJSONMetaNode() : vtkJSONNode() { - this->SetName(MD); - this->Comment = 0; - this->TableName = 0; - this->TableDescription = 0; - this->Date = 0; - } - - virtual ~vtkJSONMetaNode() { - delete this->Comment; this->Comment = 0; - delete this->TableName; this->TableName = 0; - delete this->Date; this->Date= 0; - delete this->TableDescription; this->TableDescription = 0; - for(int i = 0; i < this->ShortNames.size(); i++) { - delete this->ShortNames[i]; this->ShortNames[i] = 0; - } - for(int i = 0; i < this->LongNames.size(); i++) { - delete this->LongNames[i]; this->LongNames[i] = 0; - } - for(int i = 0; i < this->Units.size(); i++) { - delete this->Units[i]; this->Units[i] = 0; - } - } - - void SetComment(const char* comment) { this->Comment = comment; } - const char* GetComment() { return this->Comment; } - - void SetTableName(const char* name) { this->TableName = name; } - const char* GetTableName() { return this->TableName; } - - void SetDate(const char* name) { this->Date = name; } - const char* GetDate() { return this->Date; } - - void SetTableDescription(const char* description) { this->TableDescription = description; } - const char* GetDescription() { return this->TableDescription; } - - void SetShortNames(std::vector names) { this->ShortNames = names; } - std::vector GetShortNames() { return this->ShortNames; } - - void SetLongNames(std::vector names) { this->LongNames = names; } - std::vector GetLongNames() { return this->LongNames; } - - void SetUnits(std::vector units) { this->Units = units; } - std::vector GetUnits() { return this->Units; } - -private: - const char* Comment; - const char* TableName; - const char* TableDescription; - const char* Date; - std::vector ShortNames; - std::vector LongNames; - std::vector Units; -}; - -struct char_cmp { - bool operator () (const char *a, const char *b) const - { - return strcmp(a,b)<0; - } -}; - -typedef std::map vtkJSONMap; - -class vtkJSONInfoNode : public vtkJSONNode { -public: - vtkJSONInfoNode(const char* name) : vtkJSONNode() { - this->SetName(name); - } - virtual ~vtkJSONInfoNode() { - vtkJSONMap::iterator it = this->Values.begin(); - for( ;it != this->Values.end(); it++) { - delete it->first; - const char* c = it->first; - c = 0; - } - } - void AddValue(const char* key, const double value) { - this->Values.insert(std::pair(key,value)); - } - vtkJSONMap& GetValues() { return this->Values; } -private: - vtkJSONMap Values; -}; - - -//--------------------------------------------------- -vtkStandardNewMacro(vtkJSONParser); - -//--------------------------------------------------- -vtkJSONParser::vtkJSONParser() -{ - this->FileName = NULL; - this->LineNumber = 1; - this->ColumnNumber = 0; - this->File = 0; - this->InsideQuotes = false; - this->LastString = 0; - this->CurrentNode = 0; - this->ParseList = false; - this->ParseObjectList = false; - this->LastValue = NAN; - this->ShortNamesFilled = false; -} - -//--------------------------------------------------- -vtkJSONParser::~vtkJSONParser() -{ - delete this->FileName; - this->FileName = 0; -} - - -//--------------------------------------------------- -int vtkJSONParser::Parse(vtkTable* theTable) -{ - if(!this->FileName) { - vtkErrorMacro("The name of the file is not defined"); - return 1; - } - this->File = fopen( this->FileName, "r" ); - - if( !this->File ) { - std::string message = std::string("Can't open file: ") + std::string(this->FileName); - throwSimpleException(message.c_str()); - return 1; - } - char ch = 0; - - this->ExpectedCharacters.push_back(OCB); - - while( ch != EOF ) { - ch = fgetc(this->File); - processCharacter(ch); - if(isDigitsAllowed() && isDigitOrDot(ch)) { - readDoubleValue(); - } - int nb = 1; - switch(ch) { - case OCB: processOCB(); break; - case CCB: processCCB(); break; - - case OSB: processOSB(); break; - case CSB: processCSB(); break; - - case ENDL: processENDL(); nb = 0; break; - - case QTS: processQTS(); break; - - case COLON: processCOLON(); break; - - case COMMA: processCOMMA(); break; - } - this->ColumnNumber+=nb; - } - fclose(this->File); - - if(this->CInfoVector.size() > 0 ) { - throwException("braket is not closed ", - this->CInfoVector.back().ln, - this->CInfoVector.back().cn); - } - - finalize(theTable); - clean(); - return 1; -} - -//--------------------------------------------------- -void vtkJSONParser::finalize( vtkTable *t ) { - std::vector::iterator it = this->Nodes.begin(); - vtkJSONMetaNode* mn = 0; - for( ; it != this->Nodes.end(); it++ ) { - mn = dynamic_cast(*it); - if (mn) - break; - } - std::vector units; - if(mn) { - if(!mn->GetShortNames().empty()) { - this->ShortNames.clear(); - this->ShortNames = mn->GetShortNames(); - } - t->GetInformation()->Set(vtkDataObject::FIELD_NAME(), mn->GetTableName() ? mn->GetTableName() : ""); - units = mn->GetUnits(); - } - - long nbRow = mn ? (this->Nodes.size() - 1 ) : this->Nodes.size(); - for (long col=0; col < this->ShortNames.size(); col++) { - vtkDoubleArray* newCol = vtkDoubleArray::New(); - newCol->SetNumberOfValues(nbRow); - vtkJSONInfoNode* in = 0; - std::string name = this->ShortNames[col]; - name += "["; - if(col < units.size()){ - name += units[col]; - } else { - name += NA; - } - name += "]"; - newCol->SetName(name.c_str()); - it = this->Nodes.begin(); - long row = 0; - for( ; it != this->Nodes.end(); it++ ) { - in = dynamic_cast(*it); - if (in) { - vtkJSONMap& vl = in->GetValues(); - vtkJSONMap::iterator mit = vl.find(this->ShortNames[col]); - if(mit != vl.end()) { - newCol->SetValue(row, mit->second); - const char* c = mit->first; - vl.erase(mit); - delete c; - c = 0; - row++; - } else { - std::string s("Item with name '"); - s+=in->GetName(); - s+="' has no key (or not a numerical value for key) '"; - s+=this->ShortNames[col]; - s+="'! Value set to 0.0."; - //throwSimpleException(s.c_str()); - std::ostringstream oss; - oss << "vtkJSONParser::finalize(): " << s << std::endl; - if(this->HasObserver("ErrorEvent") ) - this->InvokeEvent("ErrorEvent",const_cast(oss.str().c_str())); - else - vtkOutputWindowDisplayErrorText(const_cast(oss.str().c_str())); - vtkObject::BreakOnError(); - - newCol->SetValue(row, 0.0); - } - } - } - t->AddColumn(newCol); - } - it = this->Nodes.begin(); - vtkJSONInfoNode* in = 0; - for( ; it != this->Nodes.end(); it++ ) { - in = dynamic_cast(*it); - if (in) { - vtkJSONMap& vl = in->GetValues(); - if(vl.size() > 0 ) { - std::string s("Item with name '"); - s+=in->GetName(); - s+="' has unexpected key '"; - s+=vl.begin()->first; - s+="' !"; - throwSimpleException(s.c_str()); - } - } - } -} - -//--------------------------------------------------- -void vtkJSONParser::processQTS() { - this->InsideQuotes = !this->InsideQuotes; - if(this->InsideQuotes) { - addInfo(QTS); - } else { - // Quotes is closed, get content - Info i = this->CInfoVector.back(); - this->CInfoVector.pop_back(); - if(i.type == QTS) { - long begin = i.pos; - long end = ftell(this->File) - 1; - this->LastString = getString(begin, end); - bool parse_list = (this->CInfoVector.size() >= 1 && this->CInfoVector.back().type == OSB); - if(parse_list) { - this->CurrentList.push_back(this->LastString); - } else { - this->Strings.push_back(this->LastString); - processMetaNode(); - } -#ifdef __DEBUG - std::cout<<"String : "<LastString<ExpectedCharacters.clear(); - this->ExpectedCharacters.push_back(COLON); - this->ExpectedCharacters.push_back(COMMA); - this->ExpectedCharacters.push_back(CCB); - this->ExpectedCharacters.push_back(CSB); - } - } -} - -//--------------------------------------------------- -void vtkJSONParser::processCOLON() { - if (this->InsideQuotes) - return; - this->ExpectedCharacters.clear(); - this->ExpectedCharacters.push_back(OCB); - this->ExpectedCharacters.push_back(QTS); - this->ExpectedCharacters.push_back(OSB); - if(GetInfoNode() && Strings.size() == 1 ) { - allowsDigits(); - } -} - -//--------------------------------------------------- -void vtkJSONParser::processOCB() { - if (this->InsideQuotes) - return; - this->ExpectedCharacters.clear(); - this->ExpectedCharacters.push_back(QTS); - this->ExpectedCharacters.push_back(CCB); - - // Create node - if(this->CInfoVector.size() >= 1) { - if ( !GetMetaNode() && this->Strings.size() > 0 && - this->Strings.back() && - strcmp(this->Strings.back(), MD) == 0 ) { -#ifdef __DEBUG - std::cout<<"Create new Meta Node !!!"<CurrentNode = new vtkJSONMetaNode(); - delete this->Strings.back(); - this->Strings.back() = 0; - this->Strings.pop_back(); - } else { - if(this->CInfoVector.back().type == OSB ) { - this->ParseObjectList = true; - } -#ifdef __DEBUG - std::cout<<"Create new Node with name '"<<(this->Strings.size() == 0 ? "" : this->Strings.back())<<"' !!!"<CurrentNode = new vtkJSONInfoNode(this->Strings.size() == 0 ? "" : this->Strings.back()); - if(!this->ParseObjectList && this->Strings.size() == 1) { - this->Strings.pop_back(); - } - } - } - addInfo(OCB); -} - -//--------------------------------------------------- -vtkJSONMetaNode* vtkJSONParser::GetMetaNode() { - vtkJSONMetaNode *mnode = 0; - if( this->CurrentNode ) { - mnode = dynamic_cast(this->CurrentNode); - } - return mnode; -} - -//--------------------------------------------------- -vtkJSONInfoNode* vtkJSONParser::GetInfoNode() { - vtkJSONInfoNode *mnode = 0; - if( this->CurrentNode ) { - mnode = dynamic_cast(this->CurrentNode); - } - return mnode; -} - -//--------------------------------------------------- -void vtkJSONParser::processENDL() { - if(this->InsideQuotes) { - - throwException("quote is not closed !"); - } - this->LineNumber++; - this->ColumnNumber=0; -} - - -//--------------------------------------------------- -void vtkJSONParser::processCSB() { - if (this->InsideQuotes) - return; - - if(this->CInfoVector.back().type == OSB) { - if(this->ParseList) { - this->ParseList = false; - } - if(this->ParseObjectList) { - this->ParseObjectList = false; - } - this->CInfoVector.pop_back(); - } - - this->ExpectedCharacters.clear(); - this->ExpectedCharacters.push_back(COMMA); - this->ExpectedCharacters.push_back(OCB); - this->ExpectedCharacters.push_back(CCB); -} - -//--------------------------------------------------- -void vtkJSONParser::processOSB() { - if (this->InsideQuotes) - return; - - if(this->ParseList) { - Info i = CInfoVector.back(); - if(i.type == OSB) { - throwException("list, which has been opened in this place, has not been closed !", i.ln, i.cn); - } - } - if(GetMetaNode()) { - this->ParseList = true; - } else { - if( this->Strings.size() > 0 ) { - delete this->Strings[Strings.size()-1]; - this->Strings[Strings.size()-1] = 0; - this->Strings.pop_back(); - } - } - addInfo(OSB); - this->ExpectedCharacters.clear(); - this->ExpectedCharacters.push_back(QTS); - this->ExpectedCharacters.push_back(OCB); -} - -//--------------------------------------------------- -void vtkJSONParser::processCCB() { - if (this->InsideQuotes) - return; - - this->ExpectedCharacters.clear(); - this->ExpectedCharacters.push_back(COMMA); - this->ExpectedCharacters.push_back(CCB); - if(this->ParseObjectList) { - this->ExpectedCharacters.push_back(CSB); - } - - processMetaNode(); - processInfoNode(); - - if(this->CurrentNode) - this->Nodes.push_back(this->CurrentNode); - if( !this->ShortNamesFilled ){ - vtkJSONInfoNode* n = dynamic_cast(this->CurrentNode); - if(n){ - this->ShortNamesFilled = true; - } - } - -#ifdef __DEBUG - if(this->CurrentNode) - std::cout<<"End parsing node with name '"<CurrentNode->GetName()<<"' !!!!"<CInfoVector.size() > 0 && this->CInfoVector.back().type == OCB ) { - this->CInfoVector.pop_back(); - } else{ - throwException ("unexpected closed braket '}' !"); - } - - this->CurrentNode = 0; -} - -//--------------------------------------------------- -void vtkJSONParser::processCOMMA() { - if (this->InsideQuotes) - return; - this->ExpectedCharacters.clear(); - this->ExpectedCharacters.push_back(QTS); - this->ExpectedCharacters.push_back(OCB); - processMetaNode(); - processInfoNode(); -} - -void vtkJSONParser::processMetaNode() { - vtkJSONMetaNode* mn = GetMetaNode(); - if(mn) { - bool strings = this->Strings.size() == 2 && !this->ParseList; - bool str_and_list = (this->Strings.size() == 1 && this->CurrentList.size() > 0 && !this->ParseList); - - if( strings ) { - if ( strcmp(this->Strings[0], CMT) == 0 ) { - mn->SetComment(this->Strings[1]); -#ifdef __DEBUG - std::cout<<"Table Comment : "<Strings[1]<Strings[0], TBN) == 0 ) { - mn->SetTableName(this->Strings[1]); -#ifdef __DEBUG - std::cout<<"Table Name : "<Strings[1]<Strings[0], TBD) == 0 ) { - mn->SetTableDescription(this->Strings[1]); -#ifdef __DEBUG - std::cout<<"Table Description : "<Strings[1]<Strings[0], DT) == 0 ) { - mn->SetDate(this->Strings[1]); -#ifdef __DEBUG - std::cout<<"Date : "<Strings[1]<FileName; - s << ", line "<LineNumber; - s << " unexpected key word: '"<Strings[0]<<"'"; - } - delete this->Strings[0]; - this->Strings[0] = 0; - Strings.pop_back(); - Strings.pop_back(); - - } else if(str_and_list) { - if ( strcmp(this->Strings[0], SHT) == 0 ) { - std::vector::const_iterator it = this->CurrentList.begin(); - for( ;it != this->CurrentList.end(); it++) { - checkShortName(*it); - } - mn->SetShortNames(this->CurrentList); -#ifdef __DEBUG - std::cout<<"Short Names : "<Strings[0], LNG) == 0 ) { - mn->SetLongNames(this->CurrentList); -#ifdef __DEBUG - std::cout<<"Long Names : "<Strings[0], UNT) == 0 ) { - mn->SetUnits(this->CurrentList); -#ifdef __DEBUG - std::cout<<"Units : "; -#endif - } else { - std::stringstream s; - s << "File : "<< this->FileName; - s << ", line "<LineNumber; - s << " unexpected key word: '"<Strings[0]<<"'"; - } - delete this->Strings[0]; - this->Strings[0] = 0; - Strings.pop_back(); -#ifdef __DEBUG - std::vector::const_iterator it = this->CurrentList.begin(); - std::cout<<"[ "; - for( ;it != this->CurrentList.end(); it++) { - std::cout<<"'"<<*it<<"'"; - if ( it+1 != this->CurrentList.end() ) - std::cout<<", "; - } - std::cout<<" ]"<CurrentList.clear(); - } - } -} -//--------------------------------------------------- -void vtkJSONParser::processInfoNode() { - vtkJSONInfoNode* in = GetInfoNode(); - if(in) { - if(this->Strings.size() == 1 && !isnan(this->LastValue)) { - in->AddValue(this->Strings[0],this->LastValue); - if(!ShortNamesFilled) { - char* name = new char[strlen(Strings[0])]; - strcpy(name, Strings[0]); - this->ShortNames.push_back(name); - } - this->Strings.pop_back(); - this->LastValue = NAN; - } - if(this->Strings.size() == 2) { - std::string s("Item with name '"); - s+=in->GetName(); - s+="' has not a numerical value for key '"; - s+=Strings[0]; - s+="'! Value set to 0.0."; - //throwSimpleException(s.c_str()); - std::ostringstream oss; - oss << "vtkJSONParser::processInfoNode(): " << s << std::endl; - if(this->HasObserver("ErrorEvent") ) - this->InvokeEvent("ErrorEvent",const_cast(oss.str().c_str())); - else - vtkOutputWindowDisplayErrorText(const_cast(oss.str().c_str())); - vtkObject::BreakOnError(); - - in->AddValue(this->Strings[0],0.0); - if(!ShortNamesFilled) { - char* name = new char[strlen(Strings[0])]; - strcpy(name, Strings[0]); - this->ShortNames.push_back(name); - } - this->Strings.clear(); - this->LastValue = NAN; - } - } -} - -//--------------------------------------------------- -void vtkJSONParser::processCharacter(const char ch) { - if (this->InsideQuotes) - return; - if(isBlankOrEnd(ch)) - return; - - if(this->ExpectedCharacters.empty()) - return; - - std::vector::const_iterator it = std::find(this->ExpectedCharacters.begin(), - this->ExpectedCharacters.end(), - ch); - - // Unexpected character is found - if(it == this->ExpectedCharacters.end()) { - std::string s("unexpected character '"); - s+=ch; - s+="' !"; - throwException(s.c_str()); - - } -} - -//--------------------------------------------------- -char* vtkJSONParser::getString(long b, long e) { - char* result = 0; - - long old_pos = ftell(this->File); - fseek(this->File, b, SEEK_SET); - long data_s = e - b; - result = new char[data_s + 1]; // + 1 for the '\0' symbol - result[0] = 0; - size_t nb_read = fread(result, sizeof(char), data_s, this->File); - result[nb_read] = '\0'; - fseek(this->File, old_pos, SEEK_SET); - return result; -} - -//--------------------------------------------------- -void vtkJSONParser::allowsDigits() { - for(char c = '.'; c <= '9'; c++) { - ExpectedCharacters.push_back(c); - } - ExpectedCharacters.push_back('-'); - ExpectedCharacters.push_back('+'); - ExpectedCharacters.push_back('e'); -} - -//--------------------------------------------------- -bool vtkJSONParser::isDigitsAllowed() { - std::vector::const_iterator it = std::find(this->ExpectedCharacters.begin(), - this->ExpectedCharacters.end(), - '0'); - return (it != this->ExpectedCharacters.end()); -} - -//--------------------------------------------------- -void vtkJSONParser::readDoubleValue() { - long b = ftell(this->File); - - while(1) { - char ch = fgetc(this->File); - if(!isDigitOrDot(ch)) { - break; - } - } - - long e = ftell(this->File); - fseek(this->File, b-1, SEEK_SET); - long data_s = e - b; - char* result = new char[data_s]; - result[0] = 0; - size_t nb_read = fread(result, sizeof(char), data_s, this->File); - result[nb_read] = '\0'; - this->ExpectedCharacters.clear(); - this->ExpectedCharacters.push_back(COMMA); - this->ExpectedCharacters.push_back(CCB); - this->LastValue = atof(result); -#ifdef __DEBUG - std::cout<<"Read number : "<LastValue< 0 ){ - for( size_t i = 0; i < ln; i++ ) { - // a - z - if(!(name[i] >= 'a' && name[i] <= 'z') && - // A - Z - !(name[i] >= 'A' && name[i] <= 'Z') ) { - std::string s("wrong short name '"); - s += name; - s += "' !"; - throwException(s.c_str(), this->LineNumber); - } - } - } -} - -void vtkJSONParser::clean() { - std::vector::iterator it = this->Nodes.begin(); - for( ; it != this->Nodes.end(); it++ ) { - delete *(it); - *it = 0; - } -} - -//--------------------------------------------------- -void vtkJSONParser::throwException(const char* message) { - std::stringstream s; - s << "File : "<< this->FileName; - s << ", line "<LineNumber; - s << ", column " << this->ColumnNumber<<" : "; - s << message; - clean(); - throw vtkJSONException(s.str().c_str()); -} - -//--------------------------------------------------- -void vtkJSONParser::throwException(const char* message, int ln, int cn) { - std::stringstream s; - s << "File : "<< this->FileName; - s << ", line "<FileName; - s << ", line "< -#include -#include -#include -#include - - -class vtkTable; -class vtkJSONNode; -class vtkJSONMetaNode; -class vtkJSONInfoNode; - -//--------------------------------------------------- -class VTK_EXPORT vtkJSONException : public std::exception { - public: - vtkJSONException(const char *reason); - ~vtkJSONException() throw (); - const char* what() const throw(); - protected: - std::string Reason; -}; - -class VTK_EXPORT vtkJSONParser : public vtkObject -{ -public: - static vtkJSONParser* New(); - - // Description: - // Specifies the name of the file - vtkGetStringMacro(FileName); - vtkSetStringMacro(FileName); - - virtual int Parse(vtkTable* theTable); - -protected: - - //Struct to store cursor information - //---------------------------------- - struct Info { - public: - char type; - long ln; - long cn; - long pos; - - Info() { - type = 0; - ln = -1; - cn = -1; - pos = -1; - } - }; - - vtkJSONParser(); - ~vtkJSONParser(); - - // name of the file to read from - //---------------------------------- - char* FileName; - - // current line and column - //---------------------------------- - int LineNumber; - int ColumnNumber; - - // markup information - //---------------------------------- - std::vector CInfoVector; - - // file - //---------------------------------- - FILE* File; - - // Nodes - //---------------------------------- - std::vector Nodes; - vtkJSONNode* CurrentNode; - vtkJSONMetaNode* MetaNode; - - // Nodes - //---------------------------------- - std::vector ExpectedCharacters; - - // Flags - //---------------------------------- - bool InsideQuotes; - bool ParseList; - bool ParseObjectList; - bool ShortNamesFilled; - - // Last parced string - //---------------------------------- - char* LastString; - std::vector Strings; - std::vector CurrentList; - std::vector ShortNames; - - // Last parced values - //---------------------------------- - double LastValue; - -private: - vtkJSONParser(const vtkJSONParser&); // Not implemented. - void operator=(const vtkJSONParser&); // Not implemented. - - vtkJSONMetaNode* GetMetaNode(); - vtkJSONInfoNode* GetInfoNode(); - - void processOCB(); - void processCCB(); - - void processOSB(); - void processCSB(); - - void processCOMMA(); - - void processCOLON(); - - void processENDL(); - - void processQTS(); - - void processCharacter(const char ch); - - void processMetaNode(); - void processInfoNode(); - - void readDoubleValue(); - - char* getString(long b, long e); - - void allowsDigits(); - - bool isDigitsAllowed(); - - void checkShortName(const char* unit); - - void finalize(vtkTable *t); - - void clean(); - - void throwSimpleException(const char* message); - - void throwException(const char* message); - - void throwException(const char* message, int ln, int cn); - - void throwException(const char* message, int ln); -}; -#endif //__vtkJSONParser_h_ diff --git a/src/Plugins/JSONReader/ParaViewPlugin/CMakeLists.txt b/src/Plugins/JSONReader/ParaViewPlugin/CMakeLists.txt deleted file mode 100644 index c97d3525..00000000 --- a/src/Plugins/JSONReader/ParaViewPlugin/CMakeLists.txt +++ /dev/null @@ -1,36 +0,0 @@ -# Copyright (C) 2015-2019 CEA/DEN, EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# -# Author : Roman NIKOLAEV - -INCLUDE_DIRECTORIES( ${PROJECT_SOURCE_DIR}/JSONParser ) - -ADD_PARAVIEW_PLUGIN(JSONReader "1.0" - SERVER_MANAGER_XML JSONReader.xml - SERVER_MANAGER_SOURCES vtkJSONReader.cxx - REQUIRED_ON_SERVER) - -TARGET_LINK_LIBRARIES(JSONReader vtkjsoncpp) - -IF(WIN32) - ADD_DEFINITIONS(-DJSON_DLL) -ENDIF() - -INSTALL(TARGETS JSONReader - DESTINATION lib/paraview -) diff --git a/src/Plugins/JSONReader/ParaViewPlugin/JSONReader.xml b/src/Plugins/JSONReader/ParaViewPlugin/JSONReader.xml deleted file mode 100644 index 5b35ddd0..00000000 --- a/src/Plugins/JSONReader/ParaViewPlugin/JSONReader.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - - - - - - - This property specifies the file name for the JSON reader - - - - - diff --git a/src/Plugins/JSONReader/ParaViewPlugin/plugin.cmake b/src/Plugins/JSONReader/ParaViewPlugin/plugin.cmake deleted file mode 100644 index 4a646baa..00000000 --- a/src/Plugins/JSONReader/ParaViewPlugin/plugin.cmake +++ /dev/null @@ -1,3 +0,0 @@ -pv_plugin(JSONReader - DESCRIPTION "Reads the JSON file and converts it to the VTK table" - DEFAULT_ENABLED) diff --git a/src/Plugins/JSONReader/ParaViewPlugin/vtkJSONReader.cxx b/src/Plugins/JSONReader/ParaViewPlugin/vtkJSONReader.cxx deleted file mode 100644 index 6160f29d..00000000 --- a/src/Plugins/JSONReader/ParaViewPlugin/vtkJSONReader.cxx +++ /dev/null @@ -1,394 +0,0 @@ -// Copyright (C) 2015-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author: Roman NIKOLAEV - -#include "vtkJSONReader.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -// Key words -#define MD "_metadata" -#define CMT "_comment" -#define TBN "table_name" -#define TBD "table_description" -#define SHT "short_names" -#define LNG "long_names" -#define UNT "units" -#define DT "date" - -#define NA "n/a" - -// Exception -//--------------------------------------------------- -vtkJSONException::vtkJSONException(const char *reason) : Reason(reason) { - -} - -//--------------------------------------------------- -vtkJSONException::~vtkJSONException() throw () { -} - -//--------------------------------------------------- -const char* vtkJSONException::what() const throw() { - return Reason.c_str(); -} - - -//--------------------------------------------------- -class Container { -public: - typedef std::vector > > DataType; - Container(){} - void initKeys(std::vector &keys, std::string &err) { - for(int i = 0; i < keys.size(); i++) { - if( !checkVar(keys[i].c_str()) ) { - std::ostringstream oss; - oss<<"Bad key value '"<())); - } - } - - void addValue(std::string key, double value, std::string& err) { - if( !checkVar(key.c_str()) ) { - std::ostringstream oss; - oss<<"Bad key value '"<SetNumberOfInputPorts(0); - this->SetNumberOfOutputPorts(1); - this->FileName = NULL; -} - -//--------------------------------------------------- -vtkJSONReader::~vtkJSONReader() -{ - this->SetFileName(NULL); -} - -//--------------------------------------------------- -void vtkJSONReader::PrintSelf(ostream& os, vtkIndent indent) -{ - this->Superclass::PrintSelf(os, indent); - os << indent << "FileName: " - << (this->FileName ? this->FileName : "(none)") << endl; -} - -//--------------------------------------------------- -int vtkJSONReader::RequestData(vtkInformation*, - vtkInformationVector**, - vtkInformationVector* outputVector) { - vtkTable* const output_table = vtkTable::GetData(outputVector); - - vtkInformation* const outInfo = outputVector->GetInformationObject(0); - if(outInfo->Has(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()) && - outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()) > 0) { - return 0; - } - - Json::Value root; - int parseResult = 0; - parseResult = this->CanParseFile(this->FileName, root); - if(!parseResult) - return 0; - - try { - this->Parse(root, output_table); - return 1; - } - catch(vtkJSONException e) { - std::ostringstream oss; - oss<HasObserver("ErrorEvent") ) - { - this->InvokeEvent("ErrorEvent",const_cast(oss.str().c_str())); - } - else - { - vtkOutputWindowDisplayErrorText(const_cast(oss.str().c_str())); - vtkObject::BreakOnError(); - } - return 0; - } -} - -//--------------------------------------------------- -int vtkJSONReader::CanParseFile(const char *fname, Json::Value &root) -{ - if ( !fname) { - vtkErrorMacro(<< "Input file name is not specified !!! "); - return 0; - } - - ifstream file; - std::ostringstream oss; - bool parsedSuccess = true; - Json::Reader reader; - - file.open(fname); - if ( !file.is_open() ) { - oss<< "Unable to open file: " << this->FileName; - parsedSuccess = false; - } else { - parsedSuccess = reader.parse(file, root, false); - file.close(); - } - if ( !parsedSuccess ) { - if(oss.str().empty()) { - oss<<"Failed to parse JSON file: " << "\n" << reader.getFormattedErrorMessages(); - } - if(this->HasObserver("ErrorEvent") ) { - this->InvokeEvent("ErrorEvent",const_cast(oss.str().c_str())); - } - else { - vtkOutputWindowDisplayErrorText(const_cast(oss.str().c_str())); - vtkObject::BreakOnError(); - } - return 0; - } - return 1; -} - -//--------------------------------------------------- -void vtkJSONReader::Parse(Json::Value& root, vtkTable *table) { - bool hasShortNames = false; - bool hasUnits = false; - Container container; - - - Json::Value jSONListOfNames; - Json::Value jSONListOfUnits; - Json::Value jSONTableName; - std::vector short_names; - - if ( root.isMember(MD) ) { - Json::Value jSONMetaData = root.get(MD, Json::Value::null); - - if ( jSONMetaData.isMember(CMT) ) { - Json::Value jSONComment = jSONMetaData.get(CMT, Json::Value::null); - vtkDebugMacro(<<"Table Comment : " << jSONComment.asString()); - } - if ( jSONMetaData.isMember(TBN) ) { - jSONTableName = jSONMetaData.get(TBN, Json::Value::null); - vtkDebugMacro(<<"Table Name : " << jSONTableName.asString()); - } - - if ( jSONMetaData.isMember(TBD) ) { - Json::Value jSONTableDescription = jSONMetaData.get(TBD, Json::Value::null); - vtkDebugMacro(<<"Table Description : " << jSONTableDescription.asString()); - } - - if ( jSONMetaData.isMember(DT) ) { - Json::Value jSONDate = jSONMetaData.get("date", Json::Value::null); - vtkDebugMacro(<<"Date : " << jSONDate.asString()); - } - - if ( jSONMetaData.isMember(SHT) ) { - hasShortNames = true; - jSONListOfNames = jSONMetaData.get(SHT, Json::Value::null); - std::ostringstream oss; - oss<< "Short Names : [ "; - for (int i = 0; i < jSONListOfNames.size(); i++) { - oss << "'" << jSONListOfNames[i].asString() << "'"; - short_names.push_back(jSONListOfNames[i].asString()); - if ( i != jSONListOfNames.size() - 1 ) { - oss << ", "; - } - } - oss << " ]"; - vtkDebugMacro(< 1) { - throw vtkJSONException("Wrong JSON file: it contains array and others elements"); - } - - if(newRoot == Json::Value::null) { - newRoot = root; - } - - it = newRoot.begin(); - bool initContainer = false; - for( ; it != newRoot.end(); it++) { - if((*it).type() != Json::objectValue) { - std::ostringstream oss; - oss<<"Wrong JSON file: unexpected element, named '"<<(it.name())<<"'"; - throw vtkJSONException(oss.str().c_str()); - } - Json::Value::Members members = (*it).getMemberNames(); - if(!initContainer) { - if(!hasShortNames) { - short_names = members; - } - std::string err; - container.initKeys(short_names,err); - if(!err.empty()){ - throw vtkJSONException(err.c_str()); - } - initContainer = true; - } - for(int i=0; i < members.size(); i++) { - Json::Value val = (*it).get(members[i],Json::Value::null); - double value = 0.0; - switch (val.type()) { - case Json::stringValue: { - std::string s("Item with name '"); - s += it.name(); - s += "' has key '"; - s += members[i]; - s += "' with string value '"; - s += val.asString(); - s += "' ! Value set to 0.0"; - if(this->HasObserver("WarningEvent") ) { - this->InvokeEvent("WarningEvent",const_cast(s.c_str())); - } - else { - vtkOutputWindowDisplayWarningText(const_cast(s.c_str())); - } - break; - } - default: - value = val.asDouble(); - } - std::string err; - container.addValue(members[i],value,err); - if(!err.empty()){ - throw vtkJSONException(err.c_str()); - } - } - } - - table->GetInformation()->Set(vtkDataObject::FIELD_NAME(), jSONTableName.asString().c_str()); - Container::DataType data = container.getData(); - if(hasUnits && data.size() != jSONListOfUnits.size()) { - throw vtkJSONException("W"); - } - - int nbRows = 0; - if(data.size() > 0) - nbRows = data[0].second.size(); - - for(int i = 0; i < data.size(); i++) { - vtkDoubleArray* newCol = vtkDoubleArray::New(); - newCol->SetNumberOfValues(nbRows); - std::string name = data[i].first; - name += "["; - if(!jSONListOfUnits[i].asString().empty()){ - name += jSONListOfUnits[i].asString(); - } else { - name += NA; - } - name += "]"; - newCol->SetName(name.c_str()); - for(int j = 0; j < data[i].second.size(); j++) { - newCol->SetValue(j, data[i].second[j]); - } - table->AddColumn(newCol); - } -} diff --git a/src/Plugins/JSONReader/ParaViewPlugin/vtkJSONReader.h b/src/Plugins/JSONReader/ParaViewPlugin/vtkJSONReader.h deleted file mode 100644 index 8f905a1e..00000000 --- a/src/Plugins/JSONReader/ParaViewPlugin/vtkJSONReader.h +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright (C) 2015-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author: Roman NIKOLAEV (roman.nikolaev@opencascade.com) - -#ifndef __vtkJSONReader_h_ -#define __vtkJSONReader_h_ - -#include "vtk_jsoncpp.h" // For json parser -#include "vtkTableAlgorithm.h" - - -//--------------------------------------------------- -class VTK_EXPORT vtkJSONException : public std::exception { - public: - vtkJSONException(const char *reason); - ~vtkJSONException() throw (); - const char* what() const throw(); - protected: - std::string Reason; -}; - -class vtkStringArray; - -class VTK_EXPORT vtkJSONReader: public vtkTableAlgorithm -{ -public: - static vtkJSONReader* New(); - vtkTypeMacro(vtkJSONReader, vtkTableAlgorithm) - void PrintSelf(ostream& os, vtkIndent indent); - - // Description: - // Specifies the name of the file - vtkGetStringMacro(FileName); - vtkSetStringMacro(FileName); - - - // Description: - // Request Data - virtual int RequestData(vtkInformation*, - vtkInformationVector**, - vtkInformationVector*); - -protected: - // Decription: - // Parse the Json Value corresponding to the root data from the file - virtual void Parse(Json::Value& root, vtkTable *theTable); - - // Decription: - // Verify if file exists and can be read by the parser - // If exists, parse into Jsoncpp data structure - int CanParseFile(const char *fname, Json::Value &root); - -protected: - vtkJSONReader(); - ~vtkJSONReader(); - // name of the file to read from - char* FileName; - -private: - vtkJSONReader(const vtkJSONReader&); // Not implemented. - void operator=(const vtkJSONReader&); // Not implemented. -}; - -#endif //__vtkJSONReader_h_ diff --git a/src/Plugins/JSONReader/plugin/CMakeLists.txt b/src/Plugins/JSONReader/plugin/CMakeLists.txt new file mode 100644 index 00000000..b3440dac --- /dev/null +++ b/src/Plugins/JSONReader/plugin/CMakeLists.txt @@ -0,0 +1,15 @@ + +paraview_add_plugin(JSONReader + VERSION "1.0" + MODULES JSONReaderModule + MODULE_FILES + "${CMAKE_CURRENT_SOURCE_DIR}/JSONParserModule/vtk.module" + "${CMAKE_CURRENT_SOURCE_DIR}/JSONReaderModule/vtk.module" + SERVER_MANAGER_XML sources.xml + ) + +install(TARGETS JSONReader + RUNTIME DESTINATION lib/paraview + LIBRARY DESTINATION lib/paraview + ARCHIVE DESTINATION lib/paraview + ) diff --git a/src/Plugins/JSONReader/plugin/JSONParserModule/CMakeLists.txt b/src/Plugins/JSONReader/plugin/JSONParserModule/CMakeLists.txt new file mode 100644 index 00000000..d05b267b --- /dev/null +++ b/src/Plugins/JSONReader/plugin/JSONParserModule/CMakeLists.txt @@ -0,0 +1,8 @@ +set(classes + vtkJSONParser +) + +vtk_module_add_module(JSONParserModule + FORCE_STATIC + CLASSES ${classes} +) diff --git a/src/Plugins/JSONReader/plugin/JSONParserModule/vtk.module b/src/Plugins/JSONReader/plugin/JSONParserModule/vtk.module new file mode 100644 index 00000000..e54683c3 --- /dev/null +++ b/src/Plugins/JSONReader/plugin/JSONParserModule/vtk.module @@ -0,0 +1,11 @@ +NAME + JSONParserModule +DEPENDS + VTK::CommonCore + VTK::CommonDataModel + VTK::CommonExecutionModel + VTK::IOCore +PRIVATE_DEPENDS + VTK::CommonMisc + VTK::CommonSystem + VTK::vtksys diff --git a/src/Plugins/JSONReader/plugin/JSONParserModule/vtkJSONParser.cxx b/src/Plugins/JSONReader/plugin/JSONParserModule/vtkJSONParser.cxx new file mode 100644 index 00000000..13fce7ed --- /dev/null +++ b/src/Plugins/JSONReader/plugin/JSONParserModule/vtkJSONParser.cxx @@ -0,0 +1,997 @@ +// Copyright (C) 2015-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author: Roman NIKOLAEV + +#include "vtkJSONParser.h" + +#include +#include +#include +#include + +#include +#include +#include +#include + +// DEBUG macro +//#define __DEBUG + +#ifdef WIN32 +#include +#define NAN std::numeric_limits::quiet_NaN() +#define isnan _isnan +#endif + +// Key words +#define MD "_metadata" +#define CMT "_comment" +#define TBN "table_name" +#define TBD "table_description" +#define SHT "short_names" +#define LNG "long_names" +#define UNT "units" +#define DT "date" + +// Separators +#define COMMA ',' + +#define COLON ':' + +#define OSB '[' +#define CSB ']' + +#define OCB '{' +#define CCB '}' +#define ENDL '\n' +#define QTS '"' +#define SPS ' ' +#define TAB '\t' + +#define NA "n/a" + +#define addInfo(info) \ + Info I; \ + I.type = info; \ + I.ln = this->LineNumber; \ + I.cn = this->ColumnNumber; \ + I.pos = ftell(this->File); \ + this->CInfoVector.push_back(I); + +//--------------------------------------------------- +bool isBlankOrEnd(const char c) +{ + return c == SPS || c == ENDL || c == TAB || c == EOF; +} + +bool isDigitOrDot(const char c) +{ + return (c >= '.' && c <= '9') || c == '+' || c == '-' || c == 'e'; +} + +// Exception +//--------------------------------------------------- +vtkJSONException::vtkJSONException(const char* reason) + : Reason(reason) +{ +} + +//--------------------------------------------------- +vtkJSONException::~vtkJSONException() throw() +{ +} + +//--------------------------------------------------- +const char* vtkJSONException::what() const throw() +{ + return Reason.c_str(); +} + +// Containers to store information about nodes: + +// Base node +//--------------------------------------------------- +class vtkJSONNode +{ +public: + vtkJSONNode() { Name = 0; } + virtual ~vtkJSONNode() {} + const char* GetName() { return this->Name; } + void SetName(const char* name) { this->Name = name; } + +private: + const char* Name; +}; + +class vtkJSONMetaNode : public vtkJSONNode +{ +public: + vtkJSONMetaNode() + : vtkJSONNode() + { + this->SetName(MD); + this->Comment = 0; + this->TableName = 0; + this->TableDescription = 0; + this->Date = 0; + } + + virtual ~vtkJSONMetaNode() + { + delete this->Comment; + this->Comment = 0; + delete this->TableName; + this->TableName = 0; + delete this->Date; + this->Date = 0; + delete this->TableDescription; + this->TableDescription = 0; + for (int i = 0; i < this->ShortNames.size(); i++) + { + delete this->ShortNames[i]; + this->ShortNames[i] = 0; + } + for (int i = 0; i < this->LongNames.size(); i++) + { + delete this->LongNames[i]; + this->LongNames[i] = 0; + } + for (int i = 0; i < this->Units.size(); i++) + { + delete this->Units[i]; + this->Units[i] = 0; + } + } + + void SetComment(const char* comment) { this->Comment = comment; } + const char* GetComment() { return this->Comment; } + + void SetTableName(const char* name) { this->TableName = name; } + const char* GetTableName() { return this->TableName; } + + void SetDate(const char* name) { this->Date = name; } + const char* GetDate() { return this->Date; } + + void SetTableDescription(const char* description) { this->TableDescription = description; } + const char* GetDescription() { return this->TableDescription; } + + void SetShortNames(std::vector names) { this->ShortNames = names; } + std::vector GetShortNames() { return this->ShortNames; } + + void SetLongNames(std::vector names) { this->LongNames = names; } + std::vector GetLongNames() { return this->LongNames; } + + void SetUnits(std::vector units) { this->Units = units; } + std::vector GetUnits() { return this->Units; } + +private: + const char* Comment; + const char* TableName; + const char* TableDescription; + const char* Date; + std::vector ShortNames; + std::vector LongNames; + std::vector Units; +}; + +struct char_cmp +{ + bool operator()(const char* a, const char* b) const { return strcmp(a, b) < 0; } +}; + +typedef std::map vtkJSONMap; + +class vtkJSONInfoNode : public vtkJSONNode +{ +public: + vtkJSONInfoNode(const char* name) + : vtkJSONNode() + { + this->SetName(name); + } + virtual ~vtkJSONInfoNode() + { + vtkJSONMap::iterator it = this->Values.begin(); + for (; it != this->Values.end(); it++) + { + delete it->first; + const char* c = it->first; + c = 0; + } + } + void AddValue(const char* key, const double value) + { + this->Values.insert(std::pair(key, value)); + } + vtkJSONMap& GetValues() { return this->Values; } + +private: + vtkJSONMap Values; +}; + +//--------------------------------------------------- +vtkStandardNewMacro(vtkJSONParser); + +//--------------------------------------------------- +vtkJSONParser::vtkJSONParser() +{ + this->FileName = nullptr; + this->LineNumber = 1; + this->ColumnNumber = 0; + this->File = 0; + this->InsideQuotes = false; + this->LastString = 0; + this->CurrentNode = 0; + this->ParseList = false; + this->ParseObjectList = false; + this->LastValue = NAN; + this->ShortNamesFilled = false; +} + +//--------------------------------------------------- +vtkJSONParser::~vtkJSONParser() +{ + delete this->FileName; + this->FileName = nullptr; +} + +//--------------------------------------------------- +int vtkJSONParser::Parse(vtkTable* theTable) +{ + if (!this->FileName) + { + vtkErrorMacro("The name of the file is not defined"); + return 1; + } + this->File = fopen(this->FileName, "r"); + + if (!this->File) + { + std::string message = std::string("Can't open file: ") + std::string(this->FileName); + throwSimpleException(message.c_str()); + return 1; + } + char ch = 0; + + this->ExpectedCharacters.push_back(OCB); + + while (ch != EOF) + { + ch = fgetc(this->File); + processCharacter(ch); + if (isDigitsAllowed() && isDigitOrDot(ch)) + { + readDoubleValue(); + } + int nb = 1; + switch (ch) + { + case OCB: + processOCB(); + break; + case CCB: + processCCB(); + break; + + case OSB: + processOSB(); + break; + case CSB: + processCSB(); + break; + + case ENDL: + processENDL(); + nb = 0; + break; + + case QTS: + processQTS(); + break; + + case COLON: + processCOLON(); + break; + + case COMMA: + processCOMMA(); + break; + } + this->ColumnNumber += nb; + } + fclose(this->File); + + if (this->CInfoVector.size() > 0) + { + throwException( + "braket is not closed ", this->CInfoVector.back().ln, this->CInfoVector.back().cn); + } + + finalize(theTable); + clean(); + return 1; +} + +//--------------------------------------------------- +void vtkJSONParser::finalize(vtkTable* t) +{ + std::vector::iterator it = this->Nodes.begin(); + vtkJSONMetaNode* mn = 0; + for (; it != this->Nodes.end(); it++) + { + mn = dynamic_cast(*it); + if (mn) + break; + } + std::vector units; + if (mn) + { + if (!mn->GetShortNames().empty()) + { + this->ShortNames.clear(); + this->ShortNames = mn->GetShortNames(); + } + t->GetInformation()->Set( + vtkDataObject::FIELD_NAME(), mn->GetTableName() ? mn->GetTableName() : ""); + units = mn->GetUnits(); + } + + long nbRow = mn ? (this->Nodes.size() - 1) : this->Nodes.size(); + for (long col = 0; col < this->ShortNames.size(); col++) + { + vtkDoubleArray* newCol = vtkDoubleArray::New(); + newCol->SetNumberOfValues(nbRow); + vtkJSONInfoNode* in = 0; + std::string name = this->ShortNames[col]; + name += "["; + if (col < units.size()) + { + name += units[col]; + } + else + { + name += NA; + } + name += "]"; + newCol->SetName(name.c_str()); + it = this->Nodes.begin(); + long row = 0; + for (; it != this->Nodes.end(); it++) + { + in = dynamic_cast(*it); + if (in) + { + vtkJSONMap& vl = in->GetValues(); + vtkJSONMap::iterator mit = vl.find(this->ShortNames[col]); + if (mit != vl.end()) + { + newCol->SetValue(row, mit->second); + const char* c = mit->first; + vl.erase(mit); + delete c; + c = 0; + row++; + } + else + { + std::string s("Item with name '"); + s += in->GetName(); + s += "' has no key (or not a numerical value for key) '"; + s += this->ShortNames[col]; + s += "'! Value set to 0.0."; + // throwSimpleException(s.c_str()); + std::ostringstream oss; + oss << "vtkJSONParser::finalize(): " << s << std::endl; + if (this->HasObserver("ErrorEvent")) + this->InvokeEvent("ErrorEvent", const_cast(oss.str().c_str())); + else + vtkOutputWindowDisplayErrorText(const_cast(oss.str().c_str())); + vtkObject::BreakOnError(); + + newCol->SetValue(row, 0.0); + } + } + } + t->AddColumn(newCol); + } + it = this->Nodes.begin(); + vtkJSONInfoNode* in = 0; + for (; it != this->Nodes.end(); it++) + { + in = dynamic_cast(*it); + if (in) + { + vtkJSONMap& vl = in->GetValues(); + if (vl.size() > 0) + { + std::string s("Item with name '"); + s += in->GetName(); + s += "' has unexpected key '"; + s += vl.begin()->first; + s += "' !"; + throwSimpleException(s.c_str()); + } + } + } +} + +//--------------------------------------------------- +void vtkJSONParser::processQTS() +{ + this->InsideQuotes = !this->InsideQuotes; + if (this->InsideQuotes) + { + addInfo(QTS); + } + else + { + // Quotes is closed, get content + Info i = this->CInfoVector.back(); + this->CInfoVector.pop_back(); + if (i.type == QTS) + { + long begin = i.pos; + long end = ftell(this->File) - 1; + this->LastString = getString(begin, end); + bool parse_list = (this->CInfoVector.size() >= 1 && this->CInfoVector.back().type == OSB); + if (parse_list) + { + this->CurrentList.push_back(this->LastString); + } + else + { + this->Strings.push_back(this->LastString); + processMetaNode(); + } +#ifdef __DEBUG + std::cout << "String : " << this->LastString << std::endl; +#endif + + this->ExpectedCharacters.clear(); + this->ExpectedCharacters.push_back(COLON); + this->ExpectedCharacters.push_back(COMMA); + this->ExpectedCharacters.push_back(CCB); + this->ExpectedCharacters.push_back(CSB); + } + } +} + +//--------------------------------------------------- +void vtkJSONParser::processCOLON() +{ + if (this->InsideQuotes) + return; + this->ExpectedCharacters.clear(); + this->ExpectedCharacters.push_back(OCB); + this->ExpectedCharacters.push_back(QTS); + this->ExpectedCharacters.push_back(OSB); + if (GetInfoNode() && Strings.size() == 1) + { + allowsDigits(); + } +} + +//--------------------------------------------------- +void vtkJSONParser::processOCB() +{ + if (this->InsideQuotes) + return; + this->ExpectedCharacters.clear(); + this->ExpectedCharacters.push_back(QTS); + this->ExpectedCharacters.push_back(CCB); + + // Create node + if (this->CInfoVector.size() >= 1) + { + if (!GetMetaNode() && this->Strings.size() > 0 && this->Strings.back() && + strcmp(this->Strings.back(), MD) == 0) + { +#ifdef __DEBUG + std::cout << "Create new Meta Node !!!" << std::endl; +#endif + this->CurrentNode = new vtkJSONMetaNode(); + delete this->Strings.back(); + this->Strings.back() = 0; + this->Strings.pop_back(); + } + else + { + if (this->CInfoVector.back().type == OSB) + { + this->ParseObjectList = true; + } +#ifdef __DEBUG + std::cout << "Create new Node with name '" + << (this->Strings.size() == 0 ? "" : this->Strings.back()) << "' !!!" << std::endl; +#endif + this->CurrentNode = + new vtkJSONInfoNode(this->Strings.size() == 0 ? "" : this->Strings.back()); + if (!this->ParseObjectList && this->Strings.size() == 1) + { + this->Strings.pop_back(); + } + } + } + addInfo(OCB); +} + +//--------------------------------------------------- +vtkJSONMetaNode* vtkJSONParser::GetMetaNode() +{ + vtkJSONMetaNode* mnode = 0; + if (this->CurrentNode) + { + mnode = dynamic_cast(this->CurrentNode); + } + return mnode; +} + +//--------------------------------------------------- +vtkJSONInfoNode* vtkJSONParser::GetInfoNode() +{ + vtkJSONInfoNode* mnode = 0; + if (this->CurrentNode) + { + mnode = dynamic_cast(this->CurrentNode); + } + return mnode; +} + +//--------------------------------------------------- +void vtkJSONParser::processENDL() +{ + if (this->InsideQuotes) + { + + throwException("quote is not closed !"); + } + this->LineNumber++; + this->ColumnNumber = 0; +} + +//--------------------------------------------------- +void vtkJSONParser::processCSB() +{ + if (this->InsideQuotes) + return; + + if (this->CInfoVector.back().type == OSB) + { + if (this->ParseList) + { + this->ParseList = false; + } + if (this->ParseObjectList) + { + this->ParseObjectList = false; + } + this->CInfoVector.pop_back(); + } + + this->ExpectedCharacters.clear(); + this->ExpectedCharacters.push_back(COMMA); + this->ExpectedCharacters.push_back(OCB); + this->ExpectedCharacters.push_back(CCB); +} + +//--------------------------------------------------- +void vtkJSONParser::processOSB() +{ + if (this->InsideQuotes) + return; + + if (this->ParseList) + { + Info i = CInfoVector.back(); + if (i.type == OSB) + { + throwException( + "list, which has been opened in this place, has not been closed !", i.ln, i.cn); + } + } + if (GetMetaNode()) + { + this->ParseList = true; + } + else + { + if (this->Strings.size() > 0) + { + delete this->Strings[Strings.size() - 1]; + this->Strings[Strings.size() - 1] = 0; + this->Strings.pop_back(); + } + } + addInfo(OSB); + this->ExpectedCharacters.clear(); + this->ExpectedCharacters.push_back(QTS); + this->ExpectedCharacters.push_back(OCB); +} + +//--------------------------------------------------- +void vtkJSONParser::processCCB() +{ + if (this->InsideQuotes) + return; + + this->ExpectedCharacters.clear(); + this->ExpectedCharacters.push_back(COMMA); + this->ExpectedCharacters.push_back(CCB); + if (this->ParseObjectList) + { + this->ExpectedCharacters.push_back(CSB); + } + + processMetaNode(); + processInfoNode(); + + if (this->CurrentNode) + this->Nodes.push_back(this->CurrentNode); + if (!this->ShortNamesFilled) + { + vtkJSONInfoNode* n = dynamic_cast(this->CurrentNode); + if (n) + { + this->ShortNamesFilled = true; + } + } + +#ifdef __DEBUG + if (this->CurrentNode) + std::cout << "End parsing node with name '" << this->CurrentNode->GetName() << "' !!!!" + << std::endl; +#endif + + if (this->CInfoVector.size() > 0 && this->CInfoVector.back().type == OCB) + { + this->CInfoVector.pop_back(); + } + else + { + throwException("unexpected closed braket '}' !"); + } + + this->CurrentNode = 0; +} + +//--------------------------------------------------- +void vtkJSONParser::processCOMMA() +{ + if (this->InsideQuotes) + return; + this->ExpectedCharacters.clear(); + this->ExpectedCharacters.push_back(QTS); + this->ExpectedCharacters.push_back(OCB); + processMetaNode(); + processInfoNode(); +} + +void vtkJSONParser::processMetaNode() +{ + vtkJSONMetaNode* mn = GetMetaNode(); + if (mn) + { + bool strings = this->Strings.size() == 2 && !this->ParseList; + bool str_and_list = + (this->Strings.size() == 1 && this->CurrentList.size() > 0 && !this->ParseList); + + if (strings) + { + if (strcmp(this->Strings[0], CMT) == 0) + { + mn->SetComment(this->Strings[1]); +#ifdef __DEBUG + std::cout << "Table Comment : " << this->Strings[1] << std::endl; +#endif + } + else if (strcmp(this->Strings[0], TBN) == 0) + { + mn->SetTableName(this->Strings[1]); +#ifdef __DEBUG + std::cout << "Table Name : " << this->Strings[1] << std::endl; +#endif + } + else if (strcmp(this->Strings[0], TBD) == 0) + { + mn->SetTableDescription(this->Strings[1]); +#ifdef __DEBUG + std::cout << "Table Description : " << this->Strings[1] << std::endl; +#endif + } + else if (strcmp(this->Strings[0], DT) == 0) + { + mn->SetDate(this->Strings[1]); +#ifdef __DEBUG + std::cout << "Date : " << this->Strings[1] << std::endl; +#endif + } + else + { + std::stringstream s; + s << "File : " << this->FileName; + s << ", line " << this->LineNumber; + s << " unexpected key word: '" << this->Strings[0] << "'"; + } + delete this->Strings[0]; + this->Strings[0] = 0; + Strings.pop_back(); + Strings.pop_back(); + } + else if (str_and_list) + { + if (strcmp(this->Strings[0], SHT) == 0) + { + std::vector::const_iterator it = this->CurrentList.begin(); + for (; it != this->CurrentList.end(); it++) + { + checkShortName(*it); + } + mn->SetShortNames(this->CurrentList); +#ifdef __DEBUG + std::cout << "Short Names : " << std::endl; +#endif + } + else if (strcmp(this->Strings[0], LNG) == 0) + { + mn->SetLongNames(this->CurrentList); +#ifdef __DEBUG + std::cout << "Long Names : " << std::endl; +#endif + } + else if (strcmp(this->Strings[0], UNT) == 0) + { + mn->SetUnits(this->CurrentList); +#ifdef __DEBUG + std::cout << "Units : "; +#endif + } + else + { + std::stringstream s; + s << "File : " << this->FileName; + s << ", line " << this->LineNumber; + s << " unexpected key word: '" << this->Strings[0] << "'"; + } + delete this->Strings[0]; + this->Strings[0] = 0; + Strings.pop_back(); +#ifdef __DEBUG + std::vector::const_iterator it = this->CurrentList.begin(); + std::cout << "[ "; + for (; it != this->CurrentList.end(); it++) + { + std::cout << "'" << *it << "'"; + if (it + 1 != this->CurrentList.end()) + std::cout << ", "; + } + std::cout << " ]" << std::endl; +#endif + this->CurrentList.clear(); + } + } +} +//--------------------------------------------------- +void vtkJSONParser::processInfoNode() +{ + vtkJSONInfoNode* in = GetInfoNode(); + if (in) + { + if (this->Strings.size() == 1 && !isnan(this->LastValue)) + { + in->AddValue(this->Strings[0], this->LastValue); + if (!ShortNamesFilled) + { + char* name = new char[strlen(Strings[0])]; + strcpy(name, Strings[0]); + this->ShortNames.push_back(name); + } + this->Strings.pop_back(); + this->LastValue = NAN; + } + if (this->Strings.size() == 2) + { + std::string s("Item with name '"); + s += in->GetName(); + s += "' has not a numerical value for key '"; + s += Strings[0]; + s += "'! Value set to 0.0."; + // throwSimpleException(s.c_str()); + std::ostringstream oss; + oss << "vtkJSONParser::processInfoNode(): " << s << std::endl; + if (this->HasObserver("ErrorEvent")) + this->InvokeEvent("ErrorEvent", const_cast(oss.str().c_str())); + else + vtkOutputWindowDisplayErrorText(const_cast(oss.str().c_str())); + vtkObject::BreakOnError(); + + in->AddValue(this->Strings[0], 0.0); + if (!ShortNamesFilled) + { + char* name = new char[strlen(Strings[0])]; + strcpy(name, Strings[0]); + this->ShortNames.push_back(name); + } + this->Strings.clear(); + this->LastValue = NAN; + } + } +} + +//--------------------------------------------------- +void vtkJSONParser::processCharacter(const char ch) +{ + if (this->InsideQuotes) + return; + if (isBlankOrEnd(ch)) + return; + + if (this->ExpectedCharacters.empty()) + return; + + std::vector::const_iterator it = + std::find(this->ExpectedCharacters.begin(), this->ExpectedCharacters.end(), ch); + + // Unexpected character is found + if (it == this->ExpectedCharacters.end()) + { + std::string s("unexpected character '"); + s += ch; + s += "' !"; + throwException(s.c_str()); + } +} + +//--------------------------------------------------- +char* vtkJSONParser::getString(long b, long e) +{ + char* result = 0; + + long old_pos = ftell(this->File); + fseek(this->File, b, SEEK_SET); + long data_s = e - b; + result = new char[data_s + 1]; // + 1 for the '\0' symbol + result[0] = 0; + size_t nb_read = fread(result, sizeof(char), data_s, this->File); + result[nb_read] = '\0'; + fseek(this->File, old_pos, SEEK_SET); + return result; +} + +//--------------------------------------------------- +void vtkJSONParser::allowsDigits() +{ + for (char c = '.'; c <= '9'; c++) + { + ExpectedCharacters.push_back(c); + } + ExpectedCharacters.push_back('-'); + ExpectedCharacters.push_back('+'); + ExpectedCharacters.push_back('e'); +} + +//--------------------------------------------------- +bool vtkJSONParser::isDigitsAllowed() +{ + std::vector::const_iterator it = + std::find(this->ExpectedCharacters.begin(), this->ExpectedCharacters.end(), '0'); + return (it != this->ExpectedCharacters.end()); +} + +//--------------------------------------------------- +void vtkJSONParser::readDoubleValue() +{ + long b = ftell(this->File); + + while (1) + { + char ch = fgetc(this->File); + if (!isDigitOrDot(ch)) + { + break; + } + } + + long e = ftell(this->File); + fseek(this->File, b - 1, SEEK_SET); + long data_s = e - b; + char* result = new char[data_s]; + result[0] = 0; + size_t nb_read = fread(result, sizeof(char), data_s, this->File); + result[nb_read] = '\0'; + this->ExpectedCharacters.clear(); + this->ExpectedCharacters.push_back(COMMA); + this->ExpectedCharacters.push_back(CCB); + this->LastValue = atof(result); +#ifdef __DEBUG + std::cout << "Read number : " << this->LastValue << std::endl; +#endif +} + +//--------------------------------------------------- +void vtkJSONParser::checkShortName(const char* name) +{ + size_t ln = strlen(name); + if (ln > 0) + { + for (size_t i = 0; i < ln; i++) + { + // a - z + if (!(name[i] >= 'a' && name[i] <= 'z') && + // A - Z + !(name[i] >= 'A' && name[i] <= 'Z')) + { + std::string s("wrong short name '"); + s += name; + s += "' !"; + throwException(s.c_str(), this->LineNumber); + } + } + } +} + +void vtkJSONParser::clean() +{ + std::vector::iterator it = this->Nodes.begin(); + for (; it != this->Nodes.end(); it++) + { + delete *(it); + *it = 0; + } +} + +//--------------------------------------------------- +void vtkJSONParser::throwException(const char* message) +{ + std::stringstream s; + s << "File : " << this->FileName; + s << ", line " << this->LineNumber; + s << ", column " << this->ColumnNumber << " : "; + s << message; + clean(); + throw vtkJSONException(s.str().c_str()); +} + +//--------------------------------------------------- +void vtkJSONParser::throwException(const char* message, int ln, int cn) +{ + std::stringstream s; + s << "File : " << this->FileName; + s << ", line " << ln; + s << ", column :" << cn << " "; + s << message; + clean(); + throw vtkJSONException(s.str().c_str()); +} +//--------------------------------------------------- +void vtkJSONParser::throwException(const char* message, int ln) +{ + std::stringstream s; + s << "File " << this->FileName; + s << ", line " << ln << " : "; + s << message; + clean(); + throw vtkJSONException(s.str().c_str()); +} + +//--------------------------------------------------- +void vtkJSONParser::throwSimpleException(const char* message) +{ + clean(); + throw vtkJSONException(message); +} diff --git a/src/Plugins/JSONReader/plugin/JSONParserModule/vtkJSONParser.h b/src/Plugins/JSONReader/plugin/JSONParserModule/vtkJSONParser.h new file mode 100644 index 00000000..324cd5a7 --- /dev/null +++ b/src/Plugins/JSONReader/plugin/JSONParserModule/vtkJSONParser.h @@ -0,0 +1,175 @@ +// Copyright (C) 2015-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author: Roman NIKOLAEV (roman.nikolaev@opencascade.com) + +#ifndef __vtkJSONParser_h_ +#define __vtkJSONParser_h_ + +#include +#include +#include +#include +#include + +class vtkTable; +class vtkJSONNode; +class vtkJSONMetaNode; +class vtkJSONInfoNode; + +//--------------------------------------------------- +class VTK_EXPORT vtkJSONException : public std::exception +{ +public: + vtkJSONException(const char* reason); + ~vtkJSONException() throw(); + const char* what() const throw(); + +protected: + std::string Reason; +}; + +class VTK_EXPORT vtkJSONParser : public vtkObject +{ +public: + static vtkJSONParser* New(); + + // Description: + // Specifies the name of the file + vtkGetStringMacro(FileName); + vtkSetStringMacro(FileName); + + virtual int Parse(vtkTable* theTable); + +protected: + // Struct to store cursor information + //---------------------------------- + struct Info + { + public: + char type; + long ln; + long cn; + long pos; + + Info() + { + type = 0; + ln = -1; + cn = -1; + pos = -1; + } + }; + + vtkJSONParser(); + ~vtkJSONParser(); + + // name of the file to read from + //---------------------------------- + char* FileName; + + // current line and column + //---------------------------------- + int LineNumber; + int ColumnNumber; + + // markup information + //---------------------------------- + std::vector CInfoVector; + + // file + //---------------------------------- + FILE* File; + + // Nodes + //---------------------------------- + std::vector Nodes; + vtkJSONNode* CurrentNode; + vtkJSONMetaNode* MetaNode; + + // Nodes + //---------------------------------- + std::vector ExpectedCharacters; + + // Flags + //---------------------------------- + bool InsideQuotes; + bool ParseList; + bool ParseObjectList; + bool ShortNamesFilled; + + // Last parced string + //---------------------------------- + char* LastString; + std::vector Strings; + std::vector CurrentList; + std::vector ShortNames; + + // Last parced values + //---------------------------------- + double LastValue; + +private: + vtkJSONParser(const vtkJSONParser&) = delete; + void operator=(const vtkJSONParser&) = delete; + + vtkJSONMetaNode* GetMetaNode(); + vtkJSONInfoNode* GetInfoNode(); + + void processOCB(); + void processCCB(); + + void processOSB(); + void processCSB(); + + void processCOMMA(); + + void processCOLON(); + + void processENDL(); + + void processQTS(); + + void processCharacter(const char ch); + + void processMetaNode(); + void processInfoNode(); + + void readDoubleValue(); + + char* getString(long b, long e); + + void allowsDigits(); + + bool isDigitsAllowed(); + + void checkShortName(const char* unit); + + void finalize(vtkTable* t); + + void clean(); + + void throwSimpleException(const char* message); + + void throwException(const char* message); + + void throwException(const char* message, int ln, int cn); + + void throwException(const char* message, int ln); +}; +#endif //__vtkJSONParser_h_ diff --git a/src/Plugins/JSONReader/plugin/JSONReaderModule/CMakeLists.txt b/src/Plugins/JSONReader/plugin/JSONReaderModule/CMakeLists.txt new file mode 100644 index 00000000..8da5aab2 --- /dev/null +++ b/src/Plugins/JSONReader/plugin/JSONReaderModule/CMakeLists.txt @@ -0,0 +1,8 @@ +set(classes + vtkJSONReader +) + +vtk_module_add_module(JSONReaderModule + FORCE_STATIC + CLASSES ${classes} +) diff --git a/src/Plugins/JSONReader/plugin/JSONReaderModule/vtk.module b/src/Plugins/JSONReader/plugin/JSONReaderModule/vtk.module new file mode 100644 index 00000000..22d9a0b7 --- /dev/null +++ b/src/Plugins/JSONReader/plugin/JSONReaderModule/vtk.module @@ -0,0 +1,15 @@ +NAME + JSONReaderModule +DEPENDS + VTK::CommonCore + VTK::CommonDataModel + VTK::CommonExecutionModel + VTK::FiltersCore + VTK::IOCore + VTK::jsoncpp +PRIVATE_DEPENDS + VTK::CommonMisc + VTK::CommonSystem + VTK::InfovisCore + VTK::vtksys + VTK::zlib diff --git a/src/Plugins/JSONReader/plugin/JSONReaderModule/vtkJSONReader.cxx b/src/Plugins/JSONReader/plugin/JSONReaderModule/vtkJSONReader.cxx new file mode 100644 index 00000000..6160f29d --- /dev/null +++ b/src/Plugins/JSONReader/plugin/JSONReaderModule/vtkJSONReader.cxx @@ -0,0 +1,394 @@ +// Copyright (C) 2015-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author: Roman NIKOLAEV + +#include "vtkJSONReader.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +// Key words +#define MD "_metadata" +#define CMT "_comment" +#define TBN "table_name" +#define TBD "table_description" +#define SHT "short_names" +#define LNG "long_names" +#define UNT "units" +#define DT "date" + +#define NA "n/a" + +// Exception +//--------------------------------------------------- +vtkJSONException::vtkJSONException(const char *reason) : Reason(reason) { + +} + +//--------------------------------------------------- +vtkJSONException::~vtkJSONException() throw () { +} + +//--------------------------------------------------- +const char* vtkJSONException::what() const throw() { + return Reason.c_str(); +} + + +//--------------------------------------------------- +class Container { +public: + typedef std::vector > > DataType; + Container(){} + void initKeys(std::vector &keys, std::string &err) { + for(int i = 0; i < keys.size(); i++) { + if( !checkVar(keys[i].c_str()) ) { + std::ostringstream oss; + oss<<"Bad key value '"<())); + } + } + + void addValue(std::string key, double value, std::string& err) { + if( !checkVar(key.c_str()) ) { + std::ostringstream oss; + oss<<"Bad key value '"<SetNumberOfInputPorts(0); + this->SetNumberOfOutputPorts(1); + this->FileName = NULL; +} + +//--------------------------------------------------- +vtkJSONReader::~vtkJSONReader() +{ + this->SetFileName(NULL); +} + +//--------------------------------------------------- +void vtkJSONReader::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os, indent); + os << indent << "FileName: " + << (this->FileName ? this->FileName : "(none)") << endl; +} + +//--------------------------------------------------- +int vtkJSONReader::RequestData(vtkInformation*, + vtkInformationVector**, + vtkInformationVector* outputVector) { + vtkTable* const output_table = vtkTable::GetData(outputVector); + + vtkInformation* const outInfo = outputVector->GetInformationObject(0); + if(outInfo->Has(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()) && + outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()) > 0) { + return 0; + } + + Json::Value root; + int parseResult = 0; + parseResult = this->CanParseFile(this->FileName, root); + if(!parseResult) + return 0; + + try { + this->Parse(root, output_table); + return 1; + } + catch(vtkJSONException e) { + std::ostringstream oss; + oss<HasObserver("ErrorEvent") ) + { + this->InvokeEvent("ErrorEvent",const_cast(oss.str().c_str())); + } + else + { + vtkOutputWindowDisplayErrorText(const_cast(oss.str().c_str())); + vtkObject::BreakOnError(); + } + return 0; + } +} + +//--------------------------------------------------- +int vtkJSONReader::CanParseFile(const char *fname, Json::Value &root) +{ + if ( !fname) { + vtkErrorMacro(<< "Input file name is not specified !!! "); + return 0; + } + + ifstream file; + std::ostringstream oss; + bool parsedSuccess = true; + Json::Reader reader; + + file.open(fname); + if ( !file.is_open() ) { + oss<< "Unable to open file: " << this->FileName; + parsedSuccess = false; + } else { + parsedSuccess = reader.parse(file, root, false); + file.close(); + } + if ( !parsedSuccess ) { + if(oss.str().empty()) { + oss<<"Failed to parse JSON file: " << "\n" << reader.getFormattedErrorMessages(); + } + if(this->HasObserver("ErrorEvent") ) { + this->InvokeEvent("ErrorEvent",const_cast(oss.str().c_str())); + } + else { + vtkOutputWindowDisplayErrorText(const_cast(oss.str().c_str())); + vtkObject::BreakOnError(); + } + return 0; + } + return 1; +} + +//--------------------------------------------------- +void vtkJSONReader::Parse(Json::Value& root, vtkTable *table) { + bool hasShortNames = false; + bool hasUnits = false; + Container container; + + + Json::Value jSONListOfNames; + Json::Value jSONListOfUnits; + Json::Value jSONTableName; + std::vector short_names; + + if ( root.isMember(MD) ) { + Json::Value jSONMetaData = root.get(MD, Json::Value::null); + + if ( jSONMetaData.isMember(CMT) ) { + Json::Value jSONComment = jSONMetaData.get(CMT, Json::Value::null); + vtkDebugMacro(<<"Table Comment : " << jSONComment.asString()); + } + if ( jSONMetaData.isMember(TBN) ) { + jSONTableName = jSONMetaData.get(TBN, Json::Value::null); + vtkDebugMacro(<<"Table Name : " << jSONTableName.asString()); + } + + if ( jSONMetaData.isMember(TBD) ) { + Json::Value jSONTableDescription = jSONMetaData.get(TBD, Json::Value::null); + vtkDebugMacro(<<"Table Description : " << jSONTableDescription.asString()); + } + + if ( jSONMetaData.isMember(DT) ) { + Json::Value jSONDate = jSONMetaData.get("date", Json::Value::null); + vtkDebugMacro(<<"Date : " << jSONDate.asString()); + } + + if ( jSONMetaData.isMember(SHT) ) { + hasShortNames = true; + jSONListOfNames = jSONMetaData.get(SHT, Json::Value::null); + std::ostringstream oss; + oss<< "Short Names : [ "; + for (int i = 0; i < jSONListOfNames.size(); i++) { + oss << "'" << jSONListOfNames[i].asString() << "'"; + short_names.push_back(jSONListOfNames[i].asString()); + if ( i != jSONListOfNames.size() - 1 ) { + oss << ", "; + } + } + oss << " ]"; + vtkDebugMacro(< 1) { + throw vtkJSONException("Wrong JSON file: it contains array and others elements"); + } + + if(newRoot == Json::Value::null) { + newRoot = root; + } + + it = newRoot.begin(); + bool initContainer = false; + for( ; it != newRoot.end(); it++) { + if((*it).type() != Json::objectValue) { + std::ostringstream oss; + oss<<"Wrong JSON file: unexpected element, named '"<<(it.name())<<"'"; + throw vtkJSONException(oss.str().c_str()); + } + Json::Value::Members members = (*it).getMemberNames(); + if(!initContainer) { + if(!hasShortNames) { + short_names = members; + } + std::string err; + container.initKeys(short_names,err); + if(!err.empty()){ + throw vtkJSONException(err.c_str()); + } + initContainer = true; + } + for(int i=0; i < members.size(); i++) { + Json::Value val = (*it).get(members[i],Json::Value::null); + double value = 0.0; + switch (val.type()) { + case Json::stringValue: { + std::string s("Item with name '"); + s += it.name(); + s += "' has key '"; + s += members[i]; + s += "' with string value '"; + s += val.asString(); + s += "' ! Value set to 0.0"; + if(this->HasObserver("WarningEvent") ) { + this->InvokeEvent("WarningEvent",const_cast(s.c_str())); + } + else { + vtkOutputWindowDisplayWarningText(const_cast(s.c_str())); + } + break; + } + default: + value = val.asDouble(); + } + std::string err; + container.addValue(members[i],value,err); + if(!err.empty()){ + throw vtkJSONException(err.c_str()); + } + } + } + + table->GetInformation()->Set(vtkDataObject::FIELD_NAME(), jSONTableName.asString().c_str()); + Container::DataType data = container.getData(); + if(hasUnits && data.size() != jSONListOfUnits.size()) { + throw vtkJSONException("W"); + } + + int nbRows = 0; + if(data.size() > 0) + nbRows = data[0].second.size(); + + for(int i = 0; i < data.size(); i++) { + vtkDoubleArray* newCol = vtkDoubleArray::New(); + newCol->SetNumberOfValues(nbRows); + std::string name = data[i].first; + name += "["; + if(!jSONListOfUnits[i].asString().empty()){ + name += jSONListOfUnits[i].asString(); + } else { + name += NA; + } + name += "]"; + newCol->SetName(name.c_str()); + for(int j = 0; j < data[i].second.size(); j++) { + newCol->SetValue(j, data[i].second[j]); + } + table->AddColumn(newCol); + } +} diff --git a/src/Plugins/JSONReader/plugin/JSONReaderModule/vtkJSONReader.h b/src/Plugins/JSONReader/plugin/JSONReaderModule/vtkJSONReader.h new file mode 100644 index 00000000..4ab5c9cd --- /dev/null +++ b/src/Plugins/JSONReader/plugin/JSONReaderModule/vtkJSONReader.h @@ -0,0 +1,74 @@ +// Copyright (C) 2015-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author: Roman NIKOLAEV (roman.nikolaev@opencascade.com) + +#ifndef __vtkJSONReader_h_ +#define __vtkJSONReader_h_ + +#include +#include // For json parser + +//--------------------------------------------------- +class VTK_EXPORT vtkJSONException : public std::exception +{ +public: + vtkJSONException(const char* reason); + ~vtkJSONException() throw(); + const char* what() const throw(); + +protected: + std::string Reason; +}; + +class vtkStringArray; + +class VTK_EXPORT vtkJSONReader : public vtkTableAlgorithm +{ +public: + static vtkJSONReader* New(); + vtkTypeMacro(vtkJSONReader, vtkTableAlgorithm); + void PrintSelf(ostream& os, vtkIndent indent) override; + + // Specifies the name of the file + vtkGetStringMacro(FileName); + vtkSetStringMacro(FileName); + + // Request Data + int RequestData(vtkInformation*, vtkInformationVector**, vtkInformationVector*) override; + +protected: + vtkJSONReader(); + ~vtkJSONReader() override; + + // Parse the Json Value corresponding to the root data from the file + virtual void Parse(Json::Value& root, vtkTable* theTable); + + // Verify if file exists and can be read by the parser + // If exists, parse into Jsoncpp data structure + int CanParseFile(const char* fname, Json::Value& root); + + // name of the file to read from + char* FileName; + +private: + vtkJSONReader(const vtkJSONReader&) = delete; + void operator=(const vtkJSONReader&) = delete; +}; + +#endif //__vtkJSONReader_h_ diff --git a/src/Plugins/JSONReader/plugin/paraview.plugin b/src/Plugins/JSONReader/plugin/paraview.plugin new file mode 100644 index 00000000..c2535eb9 --- /dev/null +++ b/src/Plugins/JSONReader/plugin/paraview.plugin @@ -0,0 +1,8 @@ +NAME + JSONReader +DESCRIPTION + Reads the JSON file and converts it to the VTK table. +REQUIRES_MODULES + VTK::CommonCore + VTK::IOCore + VTK::FiltersCore diff --git a/src/Plugins/JSONReader/plugin/sources.xml b/src/Plugins/JSONReader/plugin/sources.xml new file mode 100644 index 00000000..c6fdf7e0 --- /dev/null +++ b/src/Plugins/JSONReader/plugin/sources.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + This property specifies the file name for the JSON reader + + + + + diff --git a/src/Plugins/MEDReader/CMake/CTestCustom.ctest.in b/src/Plugins/MEDReader/CMake/CTestCustom.ctest.in deleted file mode 100644 index c49f242c..00000000 --- a/src/Plugins/MEDReader/CMake/CTestCustom.ctest.in +++ /dev/null @@ -1,103 +0,0 @@ -# Copyright (C) 2010-2019 CEA/DEN, EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# - -SET(CTEST_CUSTOM_WARNING_MATCH - ${CTEST_CUSTOM_WARNING_MATCH} - "{standard input}:[0-9][0-9]*: Warning: " - ) - -# Removing this because it somehow matches normal build output lines -# on several platforms. Perhaps there is a bug in the custom match -# support. -# -# SET(CTEST_CUSTOM_ERROR_MATCH -# ${CTEST_CUSTOM_ERROR_MATCH} -# "\\", line [0-9]+, in " -# ) - -IF("@CMAKE_SYSTEM@" MATCHES "OSF") - SET(CTEST_CUSTOM_WARNING_EXCEPTION - ${CTEST_CUSTOM_WARNING_EXCEPTION} - "vtkKWApplication" - "vtkKWObject" - ) -ENDIF("@CMAKE_SYSTEM@" MATCHES "OSF") - -SET(CTEST_CUSTOM_WARNING_EXCEPTION - ${CTEST_CUSTOM_WARNING_EXCEPTION} - "Utilities/vtktiff/" - "xtree.[0-9]+. : warning C4702: unreachable code" - "warning LNK4221" - "variable .var_args[2]*. is used before its value is set" - "jobserver unavailable" - "warning: \\(Long double usage is reported only once for each file" - "warning: To disable this warning use" - "warning: .+ might be clobbered by .longjmp. or .vfork." - "(ranlib|libtool):.*file: .+ has no symbols" - "could not be inlined" - "ld: warning prebinding disabled because \\((__TEXT|__DATA|__LINKEDIT) segment \\(address = 0x[a-f0-9]+ size = 0x[a-f0-9]+\\) of (.*) overlaps with (__LINKEDIT|__TEXT|__DATA) segment \\(address = 0x[a-f0-9]+ size = 0x[a-f0-9]+\\) of (.*)" - "ld: warning prebinding disabled because dependent library: (.*).dylib is not prebound" - - # MPI uses c++ but may have been built with a different c++ compiler. - # It seems to work anyway so let's ignore it to make it easier to - # test more compilers. - "ld: warning: libstdc.*, needed by .*, may conflict with libstdc.*" - - # Does *anyone* have an STL implementation that compiles without warnings...? - "cc-1116 CC: WARNING File = /usr/include/CC/stl_alloc.h, Line = 175" - - # vtkfreetype needs to be updated to get rid of warnings that occur during - # 64-bit compiles... for now, mask them out of dashboard results: - "vtkfreetype.*warning C4" - "vtkfreetype.*warning: dereferencing type-punned pointer" - - # vtknetcdf occasionally has warnings for things that are not a problem. - "vtknetcdf.*warning: dereferencing type-punned pointer" - - # Some VTK dashboards include building bits of Qt which produce lots of - # the following warnings when built with the MS compilers. Qt guys should - # fix their code. Until they do, keep the Qt chatter off the VTK dashboard - # results: - "include.Qt(Core|Gui).*warning C4127: conditional expression is constant" - - # Specifically for HP compiler, mask out - "Utilities.(vtkjpeg|vtksqlite).*warning.*more strictly aligned type" - "Filtering.vtkImageMultiple(Input|InputOutput)Filter.cxx.*warning.*more strictly aligned type" - "IO.vtkJPEGReader.cxx.*warning.*more strictly aligned type" - ) - -IF(APPLE) -SET(CTEST_CUSTOM_WARNING_EXCEPTION - ${CTEST_CUSTOM_WARNING_EXCEPTION} - "warning -.: directory name .* does not exist" - "OpenTransport.*warning.*is deprecated" - - # Somebody will have to get rid of these calls eventually (bug 4001) to - # eliminate these warnings. For now, mask them out of dashboard results: - "vtkCarbonRenderWindow.cxx.*warning: .(New|Diff|Equal|Dispose)Rgn. is deprecated" - ) -ENDIF(APPLE) - -SET(CTEST_CUSTOM_COVERAGE_EXCLUDE - ${CTEST_CUSTOM_COVERAGE_EXCLUDE} - "vtk.*TCLInit.cxx" - "vtk[^\\.]+(Java|Python|Tcl).cxx" - "Utilities.kwsys" - "Utilities.vtksys" - ) diff --git a/src/Plugins/MEDReader/CMake/FindMED.cmake b/src/Plugins/MEDReader/CMake/FindMED.cmake deleted file mode 100644 index 70fbc933..00000000 --- a/src/Plugins/MEDReader/CMake/FindMED.cmake +++ /dev/null @@ -1,96 +0,0 @@ -# Copyright (C) 2010-2019 CEA/DEN, EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# - -# - Find MED library -# Find the MED includes and library -# This module defines -# MED3HOME, a directory where MED was installed. This directory is used to help find trhe other values. -# MED_INCLUDE_DIR, where to find med.h -# MED_INCLUDE_DIRS, where to find med.h file, concatenated with other include dirs from HDF5 and MPI (if parallel) -# MED_LIBRARIES, libraries to link against to use MED. (including HDF5 and MPI if parallel) -# MED_FOUND, If false, do not try to use MED. -# also defined, but not for general use are -# MED_LIBRARY, the med library. -# MEDC_LIBRARY, the medC library - -SET(MED3HOME $ENV{MED3HOME} CACHE PATH "Path to the med install dir") - -IF(NOT MED3HOME) - FIND_PROGRAM(MDUMP mdump) - IF(MDUMP) - SET(MED3HOME ${MDUMP}) - GET_FILENAME_COMPONENT(MED3HOME ${MED3HOME} PATH) - GET_FILENAME_COMPONENT(MED3HOME ${MED3HOME} PATH) - ENDIF(MDUMP) -ENDIF(NOT MED3HOME) - -FIND_PATH(MED_INCLUDE_DIR med.h - HINTS - ${MED3HOME}/include - PATHS - /usr/local/include - /usr/include -) - -FIND_LIBRARY(MED_LIBRARY med - HINTS - ${MED_INCLUDE_DIR}/../lib - ${MED3HOME}/lib - PATHS - /usr/local/lib - /usr/lib -) - -get_filename_component(MED_LIBRARY_DIR ${MED_LIBRARY} PATH) - -FIND_LIBRARY(MEDC_LIBRARY medC - HINTS - ${MED_LIBRARY_DIR} - ${MED3HOME}/lib - PATHS - /usr/local/lib - /usr/lib -) - -IF(MED_INCLUDE_DIR) - IF(MED_LIBRARY) - IF(MEDC_LIBRARY) - SET(MED_LIBRARIES ${MED_LIBRARY} ${MEDC_LIBRARY} ) - SET( MED_FOUND "YES" ) - ENDIF(MEDC_LIBRARY) - ENDIF(MED_LIBRARY) -ENDIF(MED_INCLUDE_DIR) - -IF(${MED_FOUND}) - IF(WINDOWS) - SET(MED_LIBRARIES ${MED_LIBRARIES} ${HDF5_LIBS}) - SET(MED_INCLUDE_DIRS ${MED_INCLUDE_DIR} ${HDF5_INCLUDE_DIR}) - ELSE(WINDOWS) - FIND_PACKAGE(SalomeHDF5 REQUIRED) - SET(MED_LIBRARIES ${MED_LIBRARIES} ${HDF5_LIBRARIES}) - SET(MED_INCLUDE_DIRS ${MED_INCLUDE_DIR} ${HDF5_INCLUDE_DIRS}) - IF(${HDF5_IS_PARALLEL}) - FIND_PACKAGE(SalomeMPI REQUIRED) - SET(MED_LIBRARIES ${MED_LIBRARIES} ${MPI_LIBRARY} ${MPI_EXTRA_LIBRARY}) - SET(MED_INCLUDE_DIRS ${MED_INCLUDE_DIRS} ${MPI_INCLUDE_PATH}) - ENDIF(${HDF5_IS_PARALLEL}) - ENDIF(WINDOWS) -ENDIF(${MED_FOUND}) - -SET(MED_INCLUDE_DIR ${MED_INCLUDE_DIRS}) diff --git a/src/Plugins/MEDReader/CMakeLists.txt b/src/Plugins/MEDReader/CMakeLists.txt index e53cbece..050c1bdd 100644 --- a/src/Plugins/MEDReader/CMakeLists.txt +++ b/src/Plugins/MEDReader/CMakeLists.txt @@ -1,154 +1,32 @@ -# Copyright (C) 2010-2019 CEA/DEN, EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# - -# (cd /home/H87074/salome/DEV/modules/build/MEDReader ; export CURRENT_SOFTWARE_SRC_DIR=/home/H87074/salome/DEV/modules/src/PARAVIS ; export CURRENT_SOFTWARE_BUILD_DIR=/home/H87074/salome/DEV/modules/build/PARAVIS_master ; export CURRENT_SOFTWARE_INSTALL_DIR=/home/H87074/salome/DEV/modules/install/PARAVIS_master ; export PYTHON_VERSION="2.7" ; . /home/H87074/salome/DEV/modules/build/PARAVIS_master/.yamm/env_build.sh >/dev/null 2>&1 ; . /home/H87074/salome/DEV/salome_modules.sh >/dev/null 2>&1 ; . /home/H87074/salome/DEV/salome_prerequisites.sh >/dev/null 2>&1 ; export PARAVIEW_INSTALL_DIR="/home/H87074/salome/prerequisites/install/Paraview-v512_EDF-cm362-dox1831-gl2ps139-gr2380-hd1814-xml2290-py2710-qt561" ; cmake -DCMAKE_INSTALL_PREFIX=/home/H87074/salome/DEV/modules/install/PARAVIS_master -DPYTHON_ROOT_DIR=${PYTHONHOME} -DSALOME_PARAVIS_MINIMAL_CORBA=ON -DCMAKE_BUILD_TYPE=Debug -DSALOME_PARAVIS_MINIMAL_CORBA=ON -DMEDCOUPLING_ROOT_DIR=/home/H87074/salome/DEV/tools/install/Medcoupling-master /home/H87074/salome/DEV/modules/src/PARAVIS/src/Plugins/MEDReader) - -IF(NOT KW_TESTING_PLATFORM) -PROJECT(MEDReader C CXX) -CMAKE_MINIMUM_REQUIRED(VERSION 2.8) -INCLUDE(CMakeDependentOption) -ENDIF(NOT KW_TESTING_PLATFORM) - -IF(COMMAND cmake_policy) - cmake_policy(SET CMP0003 NEW) -ENDIF(COMMAND cmake_policy) - -SET(MED_READER_MAJOR_VERSION 0) -SET(MED_READER_MINOR_VERSION 0) -SET(MED_READER_BUILD_VERSION 0) -SET(MED_READER_VERSION "${MED_READER_MAJOR_VERSION}.${MED_READER_MINOR_VERSION}.${MED_READER_BUILD_VERSION}") - -# -# Load the ParaView/VTK packages -# -SET(MEDReader_BUILD_ParaView_Plugin ON CACHE BOOL "Build the ParaView plugin") - - -# Ensure a proper linker behavior: -CMAKE_POLICY(SET CMP0003 NEW) -CMAKE_POLICY(SET CMP0045 OLD) -CMAKE_POLICY(SET CMP0023 OLD) -CMAKE_POLICY(SET CMP0022 OLD) -IF(WIN32) - CMAKE_POLICY(SET CMP0020 OLD) # disable automatic linking to qtmain.lib -ENDIF(WIN32) - -# Common CMake macros -# =================== -SET(TMP_CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH}) -unset(CMAKE_MODULE_PATH) -SET(CONFIGURATION_ROOT_DIR $ENV{CONFIGURATION_ROOT_DIR} CACHE PATH "Path to the Salome CMake configuration files") -IF(EXISTS ${CONFIGURATION_ROOT_DIR}) - LIST(APPEND CMAKE_MODULE_PATH "${CONFIGURATION_ROOT_DIR}/cmake") - INCLUDE(SalomeMacros) -ELSE() - MESSAGE(FATAL_ERROR "We absolutely need the Salome CMake configuration files, please define CONFIGURATION_ROOT_DIR !") -ENDIF() - -SET(MEDCOUPLING_ROOT_DIR $ENV{MEDCOUPLING_ROOT_DIR} CACHE PATH "Path to the MEDCoupling tool") -IF(EXISTS ${MEDCOUPLING_ROOT_DIR}) - LIST(APPEND CMAKE_MODULE_PATH "${MEDCOUPLING_ROOT_DIR}/cmake_files") -ENDIF() -LIST(APPEND CMAKE_MODULE_PATH "${CMAKE_ROOT}/Modules") -LIST(APPEND CMAKE_MODULE_PATH ${TMP_CMAKE_MODULE_PATH}) - - - -# Platform setup -# ============== -INCLUDE(SalomeSetupPlatform) -SET(BUILD_SHARED_LIBS TRUE) - -FIND_PACKAGE(SalomePythonInterp REQUIRED) -FIND_PACKAGE(SalomePythonLibs REQUIRED) -FIND_PACKAGE(SalomeHDF5 REQUIRED) -FIND_PACKAGE(SalomeMEDCoupling REQUIRED) -FIND_PACKAGE(SalomeMEDFile REQUIRED) - -IF(MEDCOUPLING_USE_64BIT_IDS) - ADD_DEFINITIONS("-DMEDCOUPLING_USE_64BIT_IDS") -ENDIF(MEDCOUPLING_USE_64BIT_IDS) - -SALOME_ACCUMULATE_ENVIRONMENT(PYTHONPATH NOCHECK ${CMAKE_INSTALL_PREFIX}/${SALOME_INSTALL_BINS} - ${CMAKE_INSTALL_PREFIX}/${SALOME_INSTALL_PYTHON}) -SALOME_ACCUMULATE_ENVIRONMENT(LD_LIBRARY_PATH NOCHECK ${CMAKE_INSTALL_PREFIX}/${SALOME_INSTALL_LIBS}) -SALOME_ACCUMULATE_ENVIRONMENT(PV_PLUGIN_PATH NOCHECK ${CMAKE_INSTALL_PREFIX}/lib/paraview) - -IF(MEDReader_BUILD_ParaView_Plugin) - FIND_PACKAGE(ParaView REQUIRED) - IF(NOT ParaView_FOUND) - MESSAGE(FATAL_ERROR "Please locate ParaView." ) - ENDIF(NOT ParaView_FOUND) - INCLUDE(${PARAVIEW_USE_FILE}) - # Load information about VTK/ParaView modules loaded/available. -ELSE(MEDReader_BUILD_ParaView_Plugin) - FIND_PACKAGE(VTK REQUIRED) - if(NOT VTK_FOUND) - MESSAGE(FATAL_ERROR "Please locate VTK." ) - ENDIF(NOT VTK_FOUND) - INCLUDE(${VTK_USE_FILE}) -ENDIF(MEDReader_BUILD_ParaView_Plugin) - -FIND_PACKAGE(SalomeQt5 REQUIRED) -INCLUDE(UseQtExt) - -# Accumulate environment variables for PARAVIS module -SALOME_ACCUMULATE_ENVIRONMENT(PYTHONPATH NOCHECK ${CMAKE_INSTALL_PREFIX}/${SALOME_INSTALL_BINS} - ${CMAKE_INSTALL_PREFIX}/${SALOME_INSTALL_PYTHON}) -SALOME_ACCUMULATE_ENVIRONMENT(LD_LIBRARY_PATH NOCHECK ${CMAKE_INSTALL_PREFIX}/${SALOME_INSTALL_LIBS}) -SALOME_ACCUMULATE_ENVIRONMENT(PV_PLUGIN_PATH NOCHECK ${CMAKE_INSTALL_PREFIX}/lib/paraview) - -# -# process all vtk-modules defined in this plugin. This generates the necessary -# wrappings for all these modules as well. -# -SET(VTK_INSTALL_RUNTIME_DIR lib/salome) -SET(VTK_INSTALL_LIBRARY_DIR lib/salome) -SET(VTK_INSTALL_ARCHIVE_DIR lib/salome) -PV_PROCESS_MODULES() - -INCLUDE_DIRECTORIES( - ${MEDCOUPLING_INCLUDE_DIRS} - ${MEDFILE_INCLUDE_DIRS} - ${HDF5_INCLUDE_DIRS} - ${FIELDS_ROOT_DIR}/include/salome - ) - -IF(HDF5_IS_PARALLEL) - ADD_DEFINITIONS("-DMEDREADER_USE_MPI") -ENDIF(HDF5_IS_PARALLEL) - -# -# Build the parallel vtkPMEDReader -# -SET(MEDReader_BUILD_PARALLEL ${VTK_USE_PARALLEL} CACHE BOOL "Build the Med Reader with parallel support.") - -ADD_SUBDIRECTORY(IO) -# -# Build the ParaView Plugin -# -IF(MEDReader_BUILD_ParaView_Plugin) - ADD_SUBDIRECTORY(ParaViewPlugin) -ENDIF(MEDReader_BUILD_ParaView_Plugin) - -SET(SALOME_BUILD_TESTS ON CACHE BOOL "Build Salome Test") -IF(SALOME_BUILD_TESTS) - ENABLE_TESTING() - ADD_SUBDIRECTORY(Test) -ENDIF() +cmake_minimum_required(VERSION 3.8) +project(MEDReader) + +find_package(ParaView REQUIRED) + +option(BUILD_SHARED_LIBS "Build shared libraries" ON) +enable_testing() + +include(GNUInstallDirs) +set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/${CMAKE_INSTALL_BINDIR}") +set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/${CMAKE_INSTALL_LIBDIR}") +set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/${CMAKE_INSTALL_LIBDIR}") + +set("_paraview_plugin_default_${CMAKE_PROJECT_NAME}" ON) +paraview_plugin_scan( + ENABLE_BY_DEFAULT YES + PLUGIN_FILES "${CMAKE_CURRENT_SOURCE_DIR}/plugin/paraview.plugin" + PROVIDES_PLUGINS plugins + REQUIRES_MODULES required_modules) + +foreach (module IN LISTS required_modules) + if (NOT TARGET "${module}") + message("Missing required module: ${module}") + return () + endif () +endforeach () + +paraview_plugin_build( + RUNTIME_DESTINATION "${CMAKE_INSTALL_BINDIR}" + LIBRARY_DESTINATION "${CMAKE_INSTALL_LIBDIR}" + LIBRARY_SUBDIRECTORY "${PARAVIEW_PLUGIN_SUBDIR}" + PLUGINS ${plugins}) diff --git a/src/Plugins/MEDReader/CTestConfig.cmake b/src/Plugins/MEDReader/CTestConfig.cmake new file mode 100644 index 00000000..72307349 --- /dev/null +++ b/src/Plugins/MEDReader/CTestConfig.cmake @@ -0,0 +1,15 @@ +## This file should be placed in the root directory of your project. +## Then modify the CMakeLists.txt file in the root directory of your +## project to incorporate the testing dashboard. +## +## # The following are required to submit to the CDash dashboard: +## ENABLE_TESTING() +## INCLUDE(CTest) + +set(CTEST_PROJECT_NAME "MOVIDO") +set(CTEST_NIGHTLY_START_TIME "00:00:00 EST") + +set(CTEST_DROP_METHOD "http") +set(CTEST_DROP_SITE "open.cdash.org") +set(CTEST_DROP_LOCATION "/submit.php?project=movido") +set(CTEST_DROP_SITE_CDASH TRUE) diff --git a/src/Plugins/MEDReader/Doc/ELNO.txt b/src/Plugins/MEDReader/Doc/ELNO.txt deleted file mode 100644 index 456a2ea8..00000000 --- a/src/Plugins/MEDReader/Doc/ELNO.txt +++ /dev/null @@ -1,3 +0,0 @@ -1- ELNO Points: creates points on the vertices of the cells, with a shrink factor which allows you to make the distinction between the vertices of the adjacent cells -2- ELNO Surface: this filters starts by extracting the surface of the object, then project the ELNO field on it, slightly separating the cells one from the others (10-5 shrink factor compared to cell initial size) -3- ELNO Mesh: all the cells of the initial mesh are separated one from the others to be able to project the ELNO fields on them. Beware not to use this filter on big calculation cases as the memory used and the graphical performances are degraded. This filter allows to make operations such as Cut Planes keeping the ELNO fields correct. diff --git a/src/Plugins/MEDReader/Doc/HowTo0.py b/src/Plugins/MEDReader/Doc/HowTo0.py deleted file mode 100644 index b5213bf1..00000000 --- a/src/Plugins/MEDReader/Doc/HowTo0.py +++ /dev/null @@ -1,16 +0,0 @@ -from paraview.simple import * - -myMedReader=MEDReader(FileName="/home/H87074/WORK/TESTS_AMA/TESTS0/ssll117a/ssll117a.med") - -# list of all keys - -keys=myMedReader.GetProperty("FieldsTreeInfo")[::2] - -# list all the names of arrays that can be seen (including their spatial discretization) - -arr_name_with_dis=[elt.split("/")[-1] for elt in keys] - -# list all the names of arrays (Equal to those in the MED File) - -arr_name=[elt.split(myMedReader.GetProperty("Separator").GetData())[0] for elt in arr_name_with_dis] - diff --git a/src/Plugins/MEDReader/IO/CMakeLists.txt b/src/Plugins/MEDReader/IO/CMakeLists.txt deleted file mode 100644 index a33db2a7..00000000 --- a/src/Plugins/MEDReader/IO/CMakeLists.txt +++ /dev/null @@ -1,48 +0,0 @@ -# Copyright (C) 2010-2019 CEA/DEN, EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# - -SET(MEDReader_CLASSES vtkMEDReader vtkExtractGroup vtkELNOMeshFilter vtkELNOSurfaceFilter vtkELNOFilter - vtkExtractCellType vtkMEDQuadraturePointsGenerator) - -SET(MEDReader_SRCS) -SET(MEDReader_HDRS) - -FOREACH(class ${MEDReader_CLASSES}) - SET(MEDReader_SRCS ${MEDReader_SRCS} ${class}.cxx) - SET(MEDReader_HDRS ${MEDReader_HDRS} ${class}.h) -ENDFOREACH(class) - -SET(MEDReader_HDRS ${MEDReader_HDRS} MEDFileFieldRepresentationTree.hxx MEDTimeReq.hxx MEDUtilities.hxx MEDLoaderForPV.h vtkInformationGaussDoubleVectorKey.h) - -ADD_LIBRARY(MEDLoaderForPV SHARED MEDFileFieldRepresentationTree.cxx MEDTimeReq.cxx MEDUtilities.cxx vtkGenerateVectors.cxx) - -IF(HDF5_IS_PARALLEL) - TARGET_LINK_LIBRARIES(MEDLoaderForPV vtkCommonCore vtkCommonDataModel ${MEDCoupling_paramedloader} ${MEDFILE_C_LIBRARIES}) -ELSE(HDF5_IS_PARALLEL) - TARGET_LINK_LIBRARIES(MEDLoaderForPV vtkCommonCore vtkCommonDataModel ${MEDCoupling_medloader} ${MEDFILE_C_LIBRARIES}) -ENDIF(HDF5_IS_PARALLEL) - -INSTALL( - TARGETS MEDLoaderForPV - RUNTIME DESTINATION lib/salome - LIBRARY DESTINATION lib/salome - ARCHIVE DESTINATION lib/salome - ) - -INSTALL(FILES ${MEDReader_HDRS} DESTINATION include) diff --git a/src/Plugins/MEDReader/IO/MEDFileFieldRepresentationTree.cxx b/src/Plugins/MEDReader/IO/MEDFileFieldRepresentationTree.cxx deleted file mode 100644 index 3a67b540..00000000 --- a/src/Plugins/MEDReader/IO/MEDFileFieldRepresentationTree.cxx +++ /dev/null @@ -1,1782 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Anthony Geay - -#include "MEDTimeReq.hxx" -#include "MEDUtilities.hxx" - -#include "MEDFileFieldRepresentationTree.hxx" -#include "MEDCouplingFieldDiscretization.hxx" -#include "MEDCouplingFieldDouble.hxx" -#include "InterpKernelGaussCoords.hxx" -#include "MEDFileData.hxx" -#include "SauvReader.hxx" -#include "MEDCouplingMemArray.txx" - -#ifdef MEDREADER_USE_MPI - #include "ParaMEDFileMesh.hxx" -#endif - -#include "vtkXMLUnstructuredGridWriter.h"// - -#include "vtkUnstructuredGrid.h" -#include "vtkRectilinearGrid.h" -#include "vtkStructuredGrid.h" -#include "vtkUnsignedCharArray.h" -#include "vtkQuadratureSchemeDefinition.h" -#include "vtkInformationQuadratureSchemeDefinitionVectorKey.h" -#include "vtkInformationIntegerKey.h" -#include "vtkInformation.h" -#include "vtkDataArrayTemplate.h" -#include "vtkIdTypeArray.h" -#include "vtkDoubleArray.h" -#include "vtkIntArray.h" -#include "vtkLongArray.h" -#ifdef WIN32 -#include "vtkLongLongArray.h" -#endif -#include "vtkFloatArray.h" -#include "vtkCellArray.h" -#include "vtkPointData.h" -#include "vtkFieldData.h" -#include "vtkCellData.h" - -#include "vtkMutableDirectedGraph.h" - -using namespace MEDCoupling; - -const char MEDFileFieldRepresentationLeavesArrays::ZE_SEP[]="@@][@@"; - -const char MEDFileFieldRepresentationLeavesArrays::TS_STR[]="TS"; - -const char MEDFileFieldRepresentationLeavesArrays::COM_SUP_STR[]="ComSup"; - -const char MEDFileFieldRepresentationLeavesArrays::FAMILY_ID_CELL_NAME[]="FamilyIdCell"; - -const char MEDFileFieldRepresentationLeavesArrays::NUM_ID_CELL_NAME[]="NumIdCell"; - -const char MEDFileFieldRepresentationLeavesArrays::FAMILY_ID_NODE_NAME[]="FamilyIdNode"; - -const char MEDFileFieldRepresentationLeavesArrays::NUM_ID_NODE_NAME[]="NumIdNode"; - -const char MEDFileFieldRepresentationLeavesArrays::GLOBAL_NODE_ID_NAME[]="GlobalNodeIds";// WARNING DO NOT CHANGE IT BEFORE HAVING CHECKED IN PV SOURCES ! - -const char MEDFileFieldRepresentationTree::ROOT_OF_GRPS_IN_TREE[]="zeGrps"; - -const char MEDFileFieldRepresentationTree::ROOT_OF_FAM_IDS_IN_TREE[]="zeFamIds"; - -const char MEDFileFieldRepresentationTree::COMPO_STR_TO_LOCATE_MESH_DA[]="-@?|*_"; - -template -vtkIdTypeArray *ELGACmp::findOrCreate(const MEDCoupling::MEDFileFieldGlobsReal *globs, const std::vector& locsReallyUsed, vtkDataArray *vtkd, vtkDataSet *ds, bool& isNew, ExportedTinyInfo *internalInfo) const -{ - vtkIdTypeArray *try0(isExisting(locsReallyUsed,vtkd)); - if(try0) - { - isNew=false; - return try0; - } - else - { - isNew=true; - return createNew(globs,locsReallyUsed,vtkd,ds,internalInfo); - } -} - -vtkIdTypeArray *ELGACmp::isExisting(const std::vector& locsReallyUsed, vtkDataArray *vtkd) const -{ - std::vector< std::vector >::iterator it(std::find(_loc_names.begin(),_loc_names.end(),locsReallyUsed)); - if(it==_loc_names.end()) - return 0; - std::size_t pos(std::distance(_loc_names.begin(),it)); - vtkIdTypeArray *ret(_elgas[pos]); - vtkInformationQuadratureSchemeDefinitionVectorKey *key(vtkQuadratureSchemeDefinition::DICTIONARY()); - for(std::vector >::const_iterator it=_defs[pos].begin();it!=_defs[pos].end();it++) - { - key->Set(vtkd->GetInformation(),(*it).first,(*it).second); - } - vtkd->GetInformation()->Set(vtkQuadratureSchemeDefinition::QUADRATURE_OFFSET_ARRAY_NAME(),ret->GetName()); - return ret; -} - -template -vtkIdTypeArray *ELGACmp::createNew(const MEDCoupling::MEDFileFieldGlobsReal *globs, const std::vector& locsReallyUsed, vtkDataArray *vtkd, vtkDataSet *ds, ExportedTinyInfo *internalInfo) const -{ - const int VTK_DATA_ARRAY_DELETE=vtkDataArrayTemplate::VTK_DATA_ARRAY_DELETE; - std::vector< std::vector > locNames(_loc_names); - std::vector elgas(_elgas); - std::vector< std::pair< vtkQuadratureSchemeDefinition *, unsigned char > > defs; - // - std::vector< std::vector >::const_iterator it(std::find(locNames.begin(),locNames.end(),locsReallyUsed)); - if(it!=locNames.end()) - throw INTERP_KERNEL::Exception("ELGACmp::createNew : Method is expected to be called after isExisting call ! Entry already exists !"); - locNames.push_back(locsReallyUsed); - vtkIdTypeArray *elga(vtkIdTypeArray::New()); - elga->SetNumberOfComponents(1); - vtkInformationQuadratureSchemeDefinitionVectorKey *key(vtkQuadratureSchemeDefinition::DICTIONARY()); - std::map m; - for(std::vector::const_iterator it=locsReallyUsed.begin();it!=locsReallyUsed.end();it++) - { - vtkQuadratureSchemeDefinition *def(vtkQuadratureSchemeDefinition::New()); - const MEDFileFieldLoc& loc(globs->getLocalization((*it).c_str())); - INTERP_KERNEL::NormalizedCellType ct(loc.getGeoType()); - unsigned char vtkType(MEDMeshMultiLev::PARAMEDMEM_2_VTKTYPE[ct]); - const INTERP_KERNEL::CellModel& cm(INTERP_KERNEL::CellModel::GetCellModel(ct)); - int nbGaussPt(loc.getNbOfGaussPtPerCell()),nbPtsPerCell((int)cm.getNumberOfNodes()),dimLoc(loc.getDimension()); - // WARNING : these 2 lines are a workaround, due to users that write a ref element with dimension not equal to dimension of the geometric element. - std::vector gsCoods2(INTERP_KERNEL::GaussInfo::NormalizeCoordinatesIfNecessary(ct,dimLoc,loc.getGaussCoords())); - std::vector refCoods2(INTERP_KERNEL::GaussInfo::NormalizeCoordinatesIfNecessary(ct,dimLoc,loc.getRefCoords())); - if(internalInfo) - internalInfo->pushGaussAdditionnalInfo(vtkType,dimLoc,refCoods2,gsCoods2); - double *shape(new double[nbPtsPerCell*nbGaussPt]); - INTERP_KERNEL::GaussInfo calculator(ct,gsCoods2,nbGaussPt,refCoods2,nbPtsPerCell); - calculator.initLocalInfo(); - const std::vector& wgths(loc.getGaussWeights()); - for(int i=0;iInitialize(vtkType,nbPtsPerCell,nbGaussPt,shape,const_cast(&wgths[0])); - delete [] shape; - key->Set(elga->GetInformation(),def,vtkType); - key->Set(vtkd->GetInformation(),def,vtkType); - defs.push_back(std::pair< vtkQuadratureSchemeDefinition *, unsigned char >(def,vtkType)); - } - // - vtkIdType ncell(ds->GetNumberOfCells()); - vtkIdType *pt(new vtkIdType[ncell]),offset(0); - for(vtkIdType cellId=0;cellIdGetCell(cellId)); - vtkIdType delta(m[(unsigned char)cell->GetCellType()]); - pt[cellId]=offset; - offset+=delta; - } - elga->GetInformation()->Set(MEDUtilities::ELGA(),1); - elga->SetVoidArray(pt,ncell,0,VTK_DATA_ARRAY_DELETE); - std::ostringstream oss; oss << "ELGA" << "@" << _loc_names.size(); - std::string ossStr(oss.str()); - elga->SetName(ossStr.c_str()); - elga->GetInformation()->Set(vtkAbstractArray::GUI_HIDE(),1); - vtkd->GetInformation()->Set(vtkQuadratureSchemeDefinition::QUADRATURE_OFFSET_ARRAY_NAME(),elga->GetName()); - elgas.push_back(elga); - // - _loc_names=locNames; - _elgas=elgas; - _defs.push_back(defs); - return elga; -} - -void ELGACmp::appendELGAIfAny(vtkDataSet *ds) const -{ - for(std::vector::const_iterator it=_elgas.begin();it!=_elgas.end();it++) - ds->GetCellData()->AddArray(*it); -} - -ELGACmp::~ELGACmp() -{ - for(std::vector::const_iterator it=_elgas.begin();it!=_elgas.end();it++) - (*it)->Delete(); - for(std::vector< std::vector< std::pair< vtkQuadratureSchemeDefinition *, unsigned char > > >::const_iterator it0=_defs.begin();it0!=_defs.end();it0++) - for(std::vector< std::pair< vtkQuadratureSchemeDefinition *, unsigned char > >::const_iterator it1=(*it0).begin();it1!=(*it0).end();it1++) - (*it1).first->Delete(); -} - -//= - -template -class MEDFileVTKTraits -{ -public: - typedef void VtkType; - typedef void MCType; -}; - -template<> -class MEDFileVTKTraits -{ -public: - typedef vtkIntArray VtkType; - typedef MEDCoupling::DataArrayInt MCType; -}; - -template<> -#ifdef WIN32 -class MEDFileVTKTraits -#else -class MEDFileVTKTraits -#endif -{ -public: -#ifdef WIN32 - typedef vtkLongLongArray VtkType; -#else - typedef vtkLongArray VtkType; -#endif - typedef MEDCoupling::DataArrayInt64 MCType; -}; - -template<> -class MEDFileVTKTraits -{ -public: - typedef vtkFloatArray VtkType; - typedef MEDCoupling::DataArrayFloat MCType; -}; - -template<> -class MEDFileVTKTraits -{ -public: - typedef vtkDoubleArray VtkType; - typedef MEDCoupling::DataArrayDouble MCType; -}; - -typedef typename MEDFileVTKTraits::VtkType vtkMCIdTypeArray; - - -template -void AssignDataPointerToVTK(typename MEDFileVTKTraits::VtkType *vtkTab, typename MEDFileVTKTraits::MCType *mcTab, bool noCpyNumNodes) -{ - if(noCpyNumNodes) - vtkTab->SetArray(mcTab->getPointer(),mcTab->getNbOfElems(),1,vtkDataArrayTemplate::VTK_DATA_ARRAY_FREE); - else - { vtkTab->SetArray(mcTab->getPointer(),mcTab->getNbOfElems(),0,vtkDataArrayTemplate::VTK_DATA_ARRAY_FREE); mcTab->accessToMemArray().setSpecificDeallocator(0); } -} - -// here copy is always assumed. -template -void AssignDataPointerOther(VTKT *vtkTab, MCT *mcTab, int nbElems) -{ - typedef typename VTKT::ValueType VTKType; - if ( sizeof( VTKType ) == sizeof( typename MCT::Type )) - { - vtkTab->SetVoidArray(reinterpret_cast(mcTab->getPointer()),nbElems,0,VTKT::VTK_DATA_ARRAY_FREE); - mcTab->accessToMemArray().setSpecificDeallocator(0); - } - else - { - VTKType* newArray = new VTKType[ nbElems ]; - std::copy( mcTab->begin(), mcTab->begin() + nbElems, newArray ); - vtkTab->SetVoidArray(reinterpret_cast(newArray),nbElems,0,VTKT::VTK_DATA_ARRAY_DELETE); - } -} - -template -void AssignToFieldData(DataArray *vPtr, const MEDTimeReq *tr, vtkFieldData *att, const std::string& crudeName, bool noCpyNumNodes, - const std::vector& discs, const ELGACmp& elgaCmp, const MEDCoupling::MEDFileFieldGlobsReal *globs, - MEDFileAnyTypeField1TS *f1ts, vtkDataSet *ds, ExportedTinyInfo *internalInfo) -{ - const int VTK_DATA_ARRAY_DELETE=vtkDataArrayTemplate::VTK_DATA_ARRAY_DELETE; - typename MEDFileVTKTraits::MCType *vi(static_cast::MCType *>(vPtr)); - typename MEDFileVTKTraits::VtkType *vtkd(MEDFileVTKTraits::VtkType::New()); - vtkd->SetNumberOfComponents((int)vi->getNumberOfComponents()); - for(unsigned int i=0;igetNumberOfComponents();i++) - vtkd->SetComponentName(i,vi->getVarOnComponent(i).c_str()); - AssignDataPointerToVTK(vtkd,vi,noCpyNumNodes); - std::string name(tr->buildName(crudeName)); - vtkd->SetName(name.c_str()); - att->AddArray(vtkd); - vtkd->Delete(); - if(discs[0]==ON_GAUSS_PT) - { - bool tmp; - elgaCmp.findOrCreate(globs,f1ts->getLocsReallyUsed(),vtkd,ds,tmp,internalInfo); - } - if(discs[0]==ON_GAUSS_NE) - { - vtkIdTypeArray *elno(vtkIdTypeArray::New()); - elno->SetNumberOfComponents(1); - vtkIdType ncell(ds->GetNumberOfCells()); - vtkIdType *pt(new vtkIdType[ncell]),offset(0); - std::set cellTypes; - for(vtkIdType cellId=0;cellIdGetCell(cellId)); - vtkIdType delta(cell->GetNumberOfPoints()); - cellTypes.insert(cell->GetCellType()); - pt[cellId]=offset; - offset+=delta; - } - elno->GetInformation()->Set(MEDUtilities::ELNO(),1); - elno->SetVoidArray(pt,ncell,0,VTK_DATA_ARRAY_DELETE); - std::string nameElno("ELNO"); nameElno+="@"; nameElno+=name; - elno->SetName(nameElno.c_str()); - ds->GetCellData()->AddArray(elno); - vtkd->GetInformation()->Set(vtkQuadratureSchemeDefinition::QUADRATURE_OFFSET_ARRAY_NAME(),elno->GetName()); - elno->GetInformation()->Set(vtkAbstractArray::GUI_HIDE(),1); - // - vtkInformationQuadratureSchemeDefinitionVectorKey *key(vtkQuadratureSchemeDefinition::DICTIONARY()); - for(std::set::const_iterator it=cellTypes.begin();it!=cellTypes.end();it++) - { - const unsigned char *pos(std::find(MEDMeshMultiLev::PARAMEDMEM_2_VTKTYPE,MEDMeshMultiLev::PARAMEDMEM_2_VTKTYPE+MEDMeshMultiLev::PARAMEDMEM_2_VTKTYPE_LGTH,*it)); - if(pos==MEDMeshMultiLev::PARAMEDMEM_2_VTKTYPE+MEDMeshMultiLev::PARAMEDMEM_2_VTKTYPE_LGTH) - continue; - INTERP_KERNEL::NormalizedCellType ct((INTERP_KERNEL::NormalizedCellType)std::distance(MEDMeshMultiLev::PARAMEDMEM_2_VTKTYPE,pos)); - const INTERP_KERNEL::CellModel& cm(INTERP_KERNEL::CellModel::GetCellModel(ct)); - int nbGaussPt(cm.getNumberOfNodes()),dim(cm.getDimension()); - vtkQuadratureSchemeDefinition *def(vtkQuadratureSchemeDefinition::New()); - double *shape(new double[nbGaussPt*nbGaussPt]); - std::size_t dummy; - const double *gsCoords(MEDCouplingFieldDiscretizationGaussNE::GetRefCoordsFromGeometricType(ct,dummy));//GetLocsFromGeometricType - const double *refCoords(MEDCouplingFieldDiscretizationGaussNE::GetRefCoordsFromGeometricType(ct,dummy)); - const double *weights(MEDCouplingFieldDiscretizationGaussNE::GetWeightArrayFromGeometricType(ct,dummy)); - std::vector gsCoords2(gsCoords,gsCoords+nbGaussPt*dim),refCoords2(refCoords,refCoords+nbGaussPt*dim); - INTERP_KERNEL::GaussInfo calculator(ct,gsCoords2,nbGaussPt,refCoords2,nbGaussPt); - calculator.initLocalInfo(); - for(int i=0;iInitialize(*it,nbGaussPt,nbGaussPt,shape,const_cast(weights)); - delete [] shape; - key->Set(elno->GetInformation(),def,*it); - key->Set(vtkd->GetInformation(),def,*it); - def->Delete(); - } - // - elno->Delete(); - } -} - -//= - -MEDFileFieldRepresentationLeavesArrays::MEDFileFieldRepresentationLeavesArrays():_id(-1) -{ -} - -MEDFileFieldRepresentationLeavesArrays::MEDFileFieldRepresentationLeavesArrays(const MEDCoupling::MCAuto& arr):MEDCoupling::MCAuto(arr),_activated(false),_id(-1) -{ - std::vector< std::vector > typs((operator->())->getTypesOfFieldAvailable()); - if(typs.size()<1) - throw INTERP_KERNEL::Exception("There is a big internal problem in MEDLoader ! The field time spitting has failed ! A CRASH will occur soon !"); - if(typs[0].size()!=1) - throw INTERP_KERNEL::Exception("There is a big internal problem in MEDLoader ! The field spitting by spatial discretization has failed ! A CRASH will occur soon !"); - MEDCoupling::MCAuto fd(MEDCouplingFieldDiscretization::New(typs[0][0])); - std::ostringstream oss2; oss2 << (operator->())->getName() << ZE_SEP << fd->getRepr(); - _ze_name=oss2.str(); -} - -MEDFileFieldRepresentationLeavesArrays& MEDFileFieldRepresentationLeavesArrays::operator=(const MEDFileFieldRepresentationLeavesArrays& other) -{ - MEDCoupling::MCAuto::operator=(other); - _id=-1; - _activated=false; - _ze_name=other._ze_name; - _ze_full_name.clear(); - return *this; -} - -void MEDFileFieldRepresentationLeavesArrays::setId(int& id) const -{ - _id=id++; -} - -int MEDFileFieldRepresentationLeavesArrays::getId() const -{ - return _id; -} - -std::string MEDFileFieldRepresentationLeavesArrays::getZeName() const -{ - return _ze_full_name; -} - -const char *MEDFileFieldRepresentationLeavesArrays::getZeNameC() const -{ - return _ze_full_name.c_str(); -} - -void MEDFileFieldRepresentationLeavesArrays::feedSIL(vtkMutableDirectedGraph* sil, vtkIdType root, vtkVariantArray *edge, std::vector& names) const -{ - vtkIdType refId(sil->AddChild(root,edge)); - names.push_back(_ze_name); - // - if(MEDFileFieldRepresentationTree::IsFieldMeshRegardingInfo(((operator->())->getInfo()))) - { - sil->AddChild(refId,edge); - names.push_back(std::string()); - } -} - -void MEDFileFieldRepresentationLeavesArrays::computeFullNameInLeaves(const std::string& tsName, const std::string& meshName, const std::string& comSupStr) const -{ - std::ostringstream oss3; oss3 << tsName << "/" << meshName << "/" << comSupStr << "/" << _ze_name; - _ze_full_name=oss3.str(); -} - -bool MEDFileFieldRepresentationLeavesArrays::getStatus() const -{ - return _activated; -} - -bool MEDFileFieldRepresentationLeavesArrays::setStatus(bool status) const -{ - bool ret(_activated!=status); - _activated=status; - return ret; -} - -void MEDFileFieldRepresentationLeavesArrays::appendFields(const MEDTimeReq *tr, const MEDCoupling::MEDFileFieldGlobsReal *globs, const MEDCoupling::MEDMeshMultiLev *mml, const MEDCoupling::MEDFileMeshStruct *mst, vtkDataSet *ds, ExportedTinyInfo *internalInfo) const -{ - const int VTK_DATA_ARRAY_DELETE=vtkDataArrayTemplate::VTK_DATA_ARRAY_DELETE; - tr->setNumberOfTS((operator->())->getNumberOfTS()); - tr->initIterator(); - for(int timeStepId=0;timeStepIdsize();timeStepId++,++(*tr)) - { - MCAuto f1ts((operator->())->getTimeStepAtPos(tr->getCurrent())); - MEDFileAnyTypeField1TS *f1tsPtr(f1ts); - MEDFileField1TS *f1tsPtrDbl(dynamic_cast(f1tsPtr)); - MEDFileIntField1TS *f1tsPtrInt(dynamic_cast(f1tsPtr)); - MEDFileFloatField1TS *f1tsPtrFloat(dynamic_cast(f1tsPtr)); - DataArray *crudeArr(0),*postProcessedArr(0); - if(f1tsPtrDbl) - crudeArr=f1tsPtrDbl->getUndergroundDataArray(); - else if(f1tsPtrInt) - crudeArr=f1tsPtrInt->getUndergroundDataArray(); - else if(f1tsPtrFloat) - crudeArr=f1tsPtrFloat->getUndergroundDataArray(); - else - throw INTERP_KERNEL::Exception("MEDFileFieldRepresentationLeavesArrays::appendFields : only FLOAT64, FLOAT32 and INT32 fields are dealt for the moment !"); - MEDFileField1TSStructItem fsst(MEDFileField1TSStructItem::BuildItemFrom(f1ts,mst)); - f1ts->loadArraysIfNecessary(); - MCAuto v(mml->buildDataArray(fsst,globs,crudeArr)); - postProcessedArr=v; - // - std::vector discs(f1ts->getTypesOfFieldAvailable()); - if(discs.size()!=1) - throw INTERP_KERNEL::Exception("MEDFileFieldRepresentationLeavesArrays::appendFields : internal error ! Number of spatial discretizations must be equal to one !"); - vtkFieldData *att(0); - switch(discs[0]) - { - case ON_CELLS: - { - att=ds->GetCellData(); - break; - } - case ON_NODES: - { - att=ds->GetPointData(); - break; - } - case ON_GAUSS_NE: - { - att=ds->GetFieldData(); - break; - } - case ON_GAUSS_PT: - { - att=ds->GetFieldData(); - break; - } - default: - throw INTERP_KERNEL::Exception("MEDFileFieldRepresentationLeavesArrays::appendFields : only CELL and NODE, GAUSS_NE and GAUSS fields are available for the moment !"); - } - if(f1tsPtrDbl) - { - AssignToFieldData(v,tr,att,f1ts->getName(),postProcessedArr==crudeArr,discs,_elga_cmp,globs,f1ts,ds,internalInfo); - } - else if(f1tsPtrInt) - { - AssignToFieldData(v,tr,att,f1ts->getName(),postProcessedArr==crudeArr,discs,_elga_cmp,globs,f1ts,ds,internalInfo); - } - else if(f1tsPtrFloat) - { - AssignToFieldData(v,tr,att,f1ts->getName(),postProcessedArr==crudeArr,discs,_elga_cmp,globs,f1ts,ds,internalInfo); - } - else - throw INTERP_KERNEL::Exception("MEDFileFieldRepresentationLeavesArrays::appendFields : only FLOAT64 and INT32 fields are dealt for the moment ! Internal Error !"); - } -} - -void MEDFileFieldRepresentationLeavesArrays::appendELGAIfAny(vtkDataSet *ds) const -{ - _elga_cmp.appendELGAIfAny(ds); -} - -//////////////////// - -MEDFileFieldRepresentationLeaves::MEDFileFieldRepresentationLeaves():_cached_ds(0) -{ -} - -MEDFileFieldRepresentationLeaves::MEDFileFieldRepresentationLeaves(const std::vector< MEDCoupling::MCAuto >& arr, - const MEDCoupling::MCAuto& fsp):_arrays(arr.size()),_fsp(fsp),_cached_ds(0) -{ - for(std::size_t i=0;iDelete(); -} - -bool MEDFileFieldRepresentationLeaves::empty() const -{ - const MEDFileFastCellSupportComparator *fcscp(_fsp); - return fcscp==0 || _arrays.empty(); -} - -void MEDFileFieldRepresentationLeaves::setId(int& id) const -{ - for(std::vector::const_iterator it=_arrays.begin();it!=_arrays.end();it++) - (*it).setId(id); -} - -std::string MEDFileFieldRepresentationLeaves::getMeshName() const -{ - return _arrays[0]->getMeshName(); -} - -int MEDFileFieldRepresentationLeaves::getNumberOfArrays() const -{ - return (int)_arrays.size(); -} - -int MEDFileFieldRepresentationLeaves::getNumberOfTS() const -{ - return _arrays[0]->getNumberOfTS(); -} - -void MEDFileFieldRepresentationLeaves::computeFullNameInLeaves(const std::string& tsName, const std::string& meshName, const std::string& comSupStr) const -{ - for(std::vector::const_iterator it=_arrays.begin();it!=_arrays.end();it++) - (*it).computeFullNameInLeaves(tsName,meshName,comSupStr); -} - -/*! - * \param [in] ms is the meshes pointer. It can be used only for information of geometric types. No special processing will be requested on ms. - */ -void MEDFileFieldRepresentationLeaves::feedSIL(const MEDCoupling::MEDFileMeshes *ms, const std::string& meshName, vtkMutableDirectedGraph* sil, vtkIdType root, vtkVariantArray *edge, std::vector& names) const -{ - vtkIdType root2(sil->AddChild(root,edge)); - names.push_back(std::string("Arrs")); - for(std::vector::const_iterator it=_arrays.begin();it!=_arrays.end();it++) - (*it).feedSIL(sil,root2,edge,names); - // - vtkIdType root3(sil->AddChild(root,edge)); - names.push_back(std::string("InfoOnGeoType")); - const MEDCoupling::MEDFileMesh *m(0); - if(ms) - m=ms->getMeshWithName(meshName); - const MEDCoupling::MEDFileFastCellSupportComparator *fsp(_fsp); - if(!fsp || fsp->getNumberOfTS()==0) - return ; - std::vector< INTERP_KERNEL::NormalizedCellType > gts(fsp->getGeoTypesAt(0,m)); - for(std::vector< INTERP_KERNEL::NormalizedCellType >::const_iterator it2=gts.begin();it2!=gts.end();it2++) - { - const INTERP_KERNEL::CellModel& cm(INTERP_KERNEL::CellModel::GetCellModel(*it2)); - std::string cmStr(cm.getRepr()); cmStr=cmStr.substr(5);//skip "NORM_" - sil->AddChild(root3,edge); - names.push_back(cmStr); - } -} - -bool MEDFileFieldRepresentationLeaves::containId(int id) const -{ - for(std::vector::const_iterator it=_arrays.begin();it!=_arrays.end();it++) - if((*it).getId()==id) - return true; - return false; -} - -bool MEDFileFieldRepresentationLeaves::containZeName(const char *name, int& id) const -{ - for(std::vector::const_iterator it=_arrays.begin();it!=_arrays.end();it++) - if((*it).getZeName()==name) - { - id=(*it).getId(); - return true; - } - return false; -} - -void MEDFileFieldRepresentationLeaves::dumpState(std::map& status) const -{ - for(std::vector::const_iterator it=_arrays.begin();it!=_arrays.end();it++) - status[(*it).getZeName()]=(*it).getStatus(); -} - -bool MEDFileFieldRepresentationLeaves::isActivated() const -{ - for(std::vector::const_iterator it=_arrays.begin();it!=_arrays.end();it++) - if((*it).getStatus()) - return true; - return false; -} - -void MEDFileFieldRepresentationLeaves::printMySelf(std::ostream& os) const -{ - for(std::vector::const_iterator it0=_arrays.begin();it0!=_arrays.end();it0++) - { - os << " - " << (*it0).getZeName() << " ("; - if((*it0).getStatus()) - os << "X"; - else - os << " "; - os << ")" << std::endl; - } -} - -void MEDFileFieldRepresentationLeaves::activateAllArrays() const -{ - for(std::vector::const_iterator it=_arrays.begin();it!=_arrays.end();it++) - (*it).setStatus(true); -} - -const MEDFileFieldRepresentationLeavesArrays& MEDFileFieldRepresentationLeaves::getLeafArr(int id) const -{ - for(std::vector::const_iterator it=_arrays.begin();it!=_arrays.end();it++) - if((*it).getId()==id) - return *it; - throw INTERP_KERNEL::Exception("MEDFileFieldRepresentationLeaves::getLeafArr ! No such id !"); -} - -std::vector MEDFileFieldRepresentationLeaves::getTimeSteps(const TimeKeeper& tk) const -{ - if(_arrays.size()<1) - throw INTERP_KERNEL::Exception("MEDFileFieldRepresentationLeaves::getTimeSteps : the array size must be at least of size one !"); - std::vector ret; - std::vector< std::pair > dtits(_arrays[0]->getTimeSteps(ret)); - return tk.getTimeStepsRegardingPolicy(dtits,ret); -} - -std::vector< std::pair > MEDFileFieldRepresentationLeaves::getTimeStepsInCoarseMEDFileFormat(std::vector& ts) const -{ - if(!_arrays.empty()) - return _arrays[0]->getTimeSteps(ts); - else - { - ts.clear(); - return std::vector< std::pair >(); - } -} - -std::string MEDFileFieldRepresentationLeaves::getHumanReadableOverviewOfTS() const -{ - std::ostringstream oss; - oss << _arrays[0]->getNumberOfTS() << " time steps [" << _arrays[0]->getDtUnit() << "]\n("; - std::vector ret1; - std::vector< std::pair > ret2(getTimeStepsInCoarseMEDFileFormat(ret1)); - std::size_t sz(ret1.size()); - for(std::size_t i=0;i200 && i!=sz-1) - { - oss << "..."; - break; - } - } - oss << ")"; - return oss.str(); -} - -void MEDFileFieldRepresentationLeaves::appendFields(const MEDTimeReq *tr, const MEDCoupling::MEDFileFieldGlobsReal *globs, const MEDCoupling::MEDMeshMultiLev *mml, const MEDCoupling::MEDFileMeshes *meshes, vtkDataSet *ds, ExportedTinyInfo *internalInfo) const -{ - if(_arrays.size()<1) - throw INTERP_KERNEL::Exception("MEDFileFieldRepresentationLeaves::appendFields : internal error !"); - MCAuto mst(MEDFileMeshStruct::New(meshes->getMeshWithName(_arrays[0]->getMeshName().c_str()))); - for(std::vector::const_iterator it=_arrays.begin();it!=_arrays.end();it++) - if((*it).getStatus()) - { - (*it).appendFields(tr,globs,mml,mst,ds,internalInfo); - (*it).appendELGAIfAny(ds); - } -} - -vtkUnstructuredGrid *MEDFileFieldRepresentationLeaves::buildVTKInstanceNoTimeInterpolationUnstructured(MEDUMeshMultiLev *mm) const -{ - DataArrayDouble *coordsMC(0); - DataArrayByte *typesMC(0); - DataArrayIdType *cellLocationsMC(0),*cellsMC(0),*faceLocationsMC(0),*facesMC(0); - bool statusOfCoords(mm->buildVTUArrays(coordsMC,typesMC,cellLocationsMC,cellsMC,faceLocationsMC,facesMC)); - MCAuto coordsSafe(coordsMC); - MCAuto typesSafe(typesMC); - MCAuto cellLocationsSafe(cellLocationsMC),cellsSafe(cellsMC),faceLocationsSafe(faceLocationsMC),facesSafe(facesMC); - // - int nbOfCells(typesSafe->getNbOfElems()); - vtkUnstructuredGrid *ret(vtkUnstructuredGrid::New()); - vtkUnsignedCharArray *cellTypes(vtkUnsignedCharArray::New()); - AssignDataPointerOther(cellTypes,typesSafe,nbOfCells); - vtkIdTypeArray *cellLocations(vtkIdTypeArray::New()); - AssignDataPointerOther(cellLocations,cellLocationsSafe,nbOfCells); - vtkCellArray *cells(vtkCellArray::New()); - vtkIdTypeArray *cells2(vtkIdTypeArray::New()); - AssignDataPointerOther(cells2,cellsSafe,cellsSafe->getNbOfElems()); - cells->SetCells(nbOfCells,cells2); - cells2->Delete(); - if(faceLocationsMC!=0 && facesMC!=0) - { - vtkIdTypeArray *faces(vtkIdTypeArray::New()); - AssignDataPointerOther(faces,facesSafe,facesSafe->getNbOfElems()); - vtkIdTypeArray *faceLocations(vtkIdTypeArray::New()); - AssignDataPointerOther(faceLocations,faceLocationsSafe,faceLocationsSafe->getNbOfElems()); - ret->SetCells(cellTypes,cellLocations,cells,faceLocations,faces); - faceLocations->Delete(); - faces->Delete(); - } - else - ret->SetCells(cellTypes,cellLocations,cells); - cellTypes->Delete(); - cellLocations->Delete(); - cells->Delete(); - vtkPoints *pts(vtkPoints::New()); - vtkDoubleArray *pts2(vtkDoubleArray::New()); - pts2->SetNumberOfComponents(3); - AssignDataPointerToVTK(pts2,coordsSafe,statusOfCoords); - pts->SetData(pts2); - pts2->Delete(); - ret->SetPoints(pts); - pts->Delete(); - // - return ret; -} - -vtkRectilinearGrid *MEDFileFieldRepresentationLeaves::buildVTKInstanceNoTimeInterpolationCartesian(MEDCoupling::MEDCMeshMultiLev *mm) const -{ - bool isInternal; - std::vector< DataArrayDouble * > arrs(mm->buildVTUArrays(isInternal)); - vtkDoubleArray *vtkTmp(0); - vtkRectilinearGrid *ret(vtkRectilinearGrid::New()); - std::size_t dim(arrs.size()); - if(dim<1 || dim>3) - throw INTERP_KERNEL::Exception("buildVTKInstanceNoTimeInterpolationCartesian : dimension must be in [1,3] !"); - int sizePerAxe[3]={1,1,1}; - sizePerAxe[0]=arrs[0]->getNbOfElems(); - if(dim>=2) - sizePerAxe[1]=arrs[1]->getNbOfElems(); - if(dim==3) - sizePerAxe[2]=arrs[2]->getNbOfElems(); - ret->SetDimensions(sizePerAxe[0],sizePerAxe[1],sizePerAxe[2]); - vtkTmp=vtkDoubleArray::New(); - vtkTmp->SetNumberOfComponents(1); - AssignDataPointerToVTK(vtkTmp,arrs[0],isInternal); - ret->SetXCoordinates(vtkTmp); - vtkTmp->Delete(); - arrs[0]->decrRef(); - if(dim>=2) - { - vtkTmp=vtkDoubleArray::New(); - vtkTmp->SetNumberOfComponents(1); - AssignDataPointerToVTK(vtkTmp,arrs[1],isInternal); - ret->SetYCoordinates(vtkTmp); - vtkTmp->Delete(); - arrs[1]->decrRef(); - } - if(dim==3) - { - vtkTmp=vtkDoubleArray::New(); - vtkTmp->SetNumberOfComponents(1); - AssignDataPointerToVTK(vtkTmp,arrs[2],isInternal); - ret->SetZCoordinates(vtkTmp); - vtkTmp->Delete(); - arrs[2]->decrRef(); - } - return ret; -} - -vtkStructuredGrid *MEDFileFieldRepresentationLeaves::buildVTKInstanceNoTimeInterpolationCurveLinear(MEDCoupling::MEDCurveLinearMeshMultiLev *mm) const -{ - int meshStr[3]={1,1,1}; - DataArrayDouble *coords(0); - std::vector nodeStrct; - bool isInternal; - mm->buildVTUArrays(coords,nodeStrct,isInternal); - std::size_t dim(nodeStrct.size()); - if(dim<1 || dim>3) - throw INTERP_KERNEL::Exception("buildVTKInstanceNoTimeInterpolationCurveLinear : dimension must be in [1,3] !"); - meshStr[0]=nodeStrct[0]; - if(dim>=2) - meshStr[1]=nodeStrct[1]; - if(dim==3) - meshStr[2]=nodeStrct[2]; - vtkStructuredGrid *ret(vtkStructuredGrid::New()); - ret->SetDimensions(meshStr[0],meshStr[1],meshStr[2]); - vtkDoubleArray *da(vtkDoubleArray::New()); - da->SetNumberOfComponents(3); - if(coords->getNumberOfComponents()==3) - AssignDataPointerToVTK(da,coords,isInternal);//if isIntenal==True VTK has not the ownership of double * because MEDLoader main struct has it ! - else - { - MCAuto coords2(coords->changeNbOfComponents(3,0.)); - AssignDataPointerToVTK(da,coords2,false);//let VTK deal with double * - } - coords->decrRef(); - vtkPoints *points=vtkPoints::New(); - ret->SetPoints(points); - points->SetData(da); - points->Delete(); - da->Delete(); - return ret; -} - -vtkDataSet *MEDFileFieldRepresentationLeaves::buildVTKInstanceNoTimeInterpolation(const MEDTimeReq *tr, const MEDFileFieldGlobsReal *globs, const MEDCoupling::MEDFileMeshes *meshes, ExportedTinyInfo *internalInfo) const -{ - vtkDataSet *ret(0); - //_fsp->isDataSetSupportEqualToThePreviousOne(i,globs); - MCAuto mml(_fsp->buildFromScratchDataSetSupport(0,globs));//0=timestep Id. Make the hypothesis that support does not change - MCAuto mml2(mml->prepare()); - MEDMeshMultiLev *ptMML2(mml2); - if(!_cached_ds) - { - MEDUMeshMultiLev *ptUMML2(dynamic_cast(ptMML2)); - MEDCMeshMultiLev *ptCMML2(dynamic_cast(ptMML2)); - MEDCurveLinearMeshMultiLev *ptCLMML2(dynamic_cast(ptMML2)); - - if(ptUMML2) - { - ret=buildVTKInstanceNoTimeInterpolationUnstructured(ptUMML2); - } - else if(ptCMML2) - { - ret=buildVTKInstanceNoTimeInterpolationCartesian(ptCMML2); - } - else if(ptCLMML2) - { - ret=buildVTKInstanceNoTimeInterpolationCurveLinear(ptCLMML2); - } - else - throw INTERP_KERNEL::Exception("MEDFileFieldRepresentationLeaves::buildVTKInstanceNoTimeInterpolation : unrecognized mesh ! Supported for the moment unstructured, cartesian, curvelinear !"); - _cached_ds=ret->NewInstance(); - _cached_ds->ShallowCopy(ret); - } - else - { - ret=_cached_ds->NewInstance(); - ret->ShallowCopy(_cached_ds); - } - // - appendFields(tr,globs,mml,meshes,ret,internalInfo); - // The arrays links to mesh - DataArrayIdType *famCells(0),*numCells(0); - bool noCpyFamCells(false),noCpyNumCells(false); - ptMML2->retrieveFamilyIdsOnCells(famCells,noCpyFamCells); - if(famCells) - { - vtkMCIdTypeArray *vtkTab(vtkMCIdTypeArray::New()); - vtkTab->SetNumberOfComponents(1); - vtkTab->SetName(MEDFileFieldRepresentationLeavesArrays::FAMILY_ID_CELL_NAME); - AssignDataPointerToVTK(vtkTab,famCells,noCpyFamCells); - ret->GetCellData()->AddArray(vtkTab); - vtkTab->Delete(); - famCells->decrRef(); - } - ptMML2->retrieveNumberIdsOnCells(numCells,noCpyNumCells); - if(numCells) - { - vtkMCIdTypeArray *vtkTab(vtkMCIdTypeArray::New()); - vtkTab->SetNumberOfComponents(1); - vtkTab->SetName(MEDFileFieldRepresentationLeavesArrays::NUM_ID_CELL_NAME); - AssignDataPointerToVTK(vtkTab,numCells,noCpyNumCells); - ret->GetCellData()->AddArray(vtkTab); - vtkTab->Delete(); - numCells->decrRef(); - } - // The arrays links to mesh - DataArrayIdType *famNodes(0),*numNodes(0); - bool noCpyFamNodes(false),noCpyNumNodes(false); - ptMML2->retrieveFamilyIdsOnNodes(famNodes,noCpyFamNodes); - if(famNodes) - { - vtkMCIdTypeArray *vtkTab(vtkMCIdTypeArray::New()); - vtkTab->SetNumberOfComponents(1); - vtkTab->SetName(MEDFileFieldRepresentationLeavesArrays::FAMILY_ID_NODE_NAME); - AssignDataPointerToVTK(vtkTab,famNodes,noCpyFamNodes); - ret->GetPointData()->AddArray(vtkTab); - vtkTab->Delete(); - famNodes->decrRef(); - } - ptMML2->retrieveNumberIdsOnNodes(numNodes,noCpyNumNodes); - if(numNodes) - { - vtkMCIdTypeArray *vtkTab(vtkMCIdTypeArray::New()); - vtkTab->SetNumberOfComponents(1); - vtkTab->SetName(MEDFileFieldRepresentationLeavesArrays::NUM_ID_NODE_NAME); - AssignDataPointerToVTK(vtkTab,numNodes,noCpyNumNodes); - ret->GetPointData()->AddArray(vtkTab); - vtkTab->Delete(); - numNodes->decrRef(); - } - // Global Node Ids if any ! (In // mode) - DataArrayIdType *gni(ptMML2->retrieveGlobalNodeIdsIfAny()); - if(gni) - { - vtkMCIdTypeArray *vtkTab(vtkMCIdTypeArray::New()); - vtkTab->SetNumberOfComponents(1); - vtkTab->SetName(MEDFileFieldRepresentationLeavesArrays::GLOBAL_NODE_ID_NAME); - AssignDataPointerToVTK(vtkTab,gni,false); - ret->GetPointData()->AddArray(vtkTab); - vtkTab->Delete(); - gni->decrRef(); - } - return ret; -} - -////////////////////// - -MEDFileFieldRepresentationTree::MEDFileFieldRepresentationTree() -{ -} - -int MEDFileFieldRepresentationTree::getNumberOfLeavesArrays() const -{ - int ret(0); - for(std::vector< std::vector< std::vector< MEDFileFieldRepresentationLeaves > > >::const_iterator it0=_data_structure.begin();it0!=_data_structure.end();it0++) - for(std::vector< std::vector< MEDFileFieldRepresentationLeaves > >::const_iterator it1=(*it0).begin();it1!=(*it0).end();it1++) - for(std::vector< MEDFileFieldRepresentationLeaves >::const_iterator it2=(*it1).begin();it2!=(*it1).end();it2++) - ret+=(*it2).getNumberOfArrays(); - return ret; -} - -void MEDFileFieldRepresentationTree::assignIds() const -{ - int zeId(0); - for(std::vector< std::vector< std::vector< MEDFileFieldRepresentationLeaves > > >::const_iterator it0=_data_structure.begin();it0!=_data_structure.end();it0++) - for(std::vector< std::vector< MEDFileFieldRepresentationLeaves > >::const_iterator it1=(*it0).begin();it1!=(*it0).end();it1++) - for(std::vector< MEDFileFieldRepresentationLeaves >::const_iterator it2=(*it1).begin();it2!=(*it1).end();it2++) - (*it2).setId(zeId); -} - -void MEDFileFieldRepresentationTree::computeFullNameInLeaves() const -{ - std::size_t it0Cnt(0); - for(std::vector< std::vector< std::vector< MEDFileFieldRepresentationLeaves > > >::const_iterator it0=_data_structure.begin();it0!=_data_structure.end();it0++,it0Cnt++) - { - std::ostringstream oss; oss << MEDFileFieldRepresentationLeavesArrays::TS_STR << it0Cnt; - std::string tsName(oss.str()); - for(std::vector< std::vector< MEDFileFieldRepresentationLeaves > >::const_iterator it1=(*it0).begin();it1!=(*it0).end();it1++) - { - std::string meshName((*it1)[0].getMeshName()); - std::size_t it2Cnt(0); - for(std::vector< MEDFileFieldRepresentationLeaves >::const_iterator it2=(*it1).begin();it2!=(*it1).end();it2++,it2Cnt++) - { - std::ostringstream oss2; oss2 << MEDFileFieldRepresentationLeavesArrays::COM_SUP_STR << it2Cnt; - std::string comSupStr(oss2.str()); - (*it2).computeFullNameInLeaves(tsName,meshName,comSupStr); - } - } - } -} - -void MEDFileFieldRepresentationTree::activateTheFirst() const -{ - for(std::vector< std::vector< std::vector< MEDFileFieldRepresentationLeaves > > >::const_iterator it0=_data_structure.begin();it0!=_data_structure.end();it0++) - for(std::vector< std::vector< MEDFileFieldRepresentationLeaves > >::const_iterator it1=(*it0).begin();it1!=(*it0).end();it1++) - for(std::vector< MEDFileFieldRepresentationLeaves >::const_iterator it2=(*it1).begin();it2!=(*it1).end();it2++) - { - (*it2).activateAllArrays(); - return ; - } -} - -void MEDFileFieldRepresentationTree::feedSIL(vtkMutableDirectedGraph* sil, vtkIdType root, vtkVariantArray *edge, std::vector& names) const -{ - std::size_t it0Cnt(0); - for(std::vector< std::vector< std::vector< MEDFileFieldRepresentationLeaves > > >::const_iterator it0=_data_structure.begin();it0!=_data_structure.end();it0++,it0Cnt++) - { - vtkIdType InfoOnTSId(sil->AddChild(root,edge)); - names.push_back((*it0)[0][0].getHumanReadableOverviewOfTS()); - // - vtkIdType NbOfTSId(sil->AddChild(InfoOnTSId,edge)); - std::vector ts; - std::vector< std::pair > dtits((*it0)[0][0].getTimeStepsInCoarseMEDFileFormat(ts)); - std::size_t nbOfTS(dtits.size()); - std::ostringstream oss3; oss3 << nbOfTS; - names.push_back(oss3.str()); - for(std::size_t i=0;iAddChild(NbOfTSId,edge)); - names.push_back(oss4.str()); - std::ostringstream oss5; oss5 << dtits[i].second; - vtkIdType ItId(sil->AddChild(DtId,edge)); - names.push_back(oss5.str()); - std::ostringstream oss6; oss6 << ts[i]; - sil->AddChild(ItId,edge); - names.push_back(oss6.str()); - } - // - std::ostringstream oss; oss << MEDFileFieldRepresentationLeavesArrays::TS_STR << it0Cnt; - std::string tsName(oss.str()); - vtkIdType typeId0(sil->AddChild(root,edge)); - names.push_back(tsName); - for(std::vector< std::vector< MEDFileFieldRepresentationLeaves > >::const_iterator it1=(*it0).begin();it1!=(*it0).end();it1++) - { - std::string meshName((*it1)[0].getMeshName()); - vtkIdType typeId1(sil->AddChild(typeId0,edge)); - names.push_back(meshName); - std::size_t it2Cnt(0); - for(std::vector< MEDFileFieldRepresentationLeaves >::const_iterator it2=(*it1).begin();it2!=(*it1).end();it2++,it2Cnt++) - { - std::ostringstream oss2; oss2 << MEDFileFieldRepresentationLeavesArrays::COM_SUP_STR << it2Cnt; - std::string comSupStr(oss2.str()); - vtkIdType typeId2(sil->AddChild(typeId1,edge)); - names.push_back(comSupStr); - (*it2).feedSIL(_ms,meshName,sil,typeId2,edge,names); - } - } - } -} - -std::string MEDFileFieldRepresentationTree::getActiveMeshName() const -{ - int dummy0(0),dummy1(0),dummy2(0); - const MEDFileFieldRepresentationLeaves& leaf(getTheSingleActivated(dummy0,dummy1,dummy2)); - return leaf.getMeshName(); -} - -std::string MEDFileFieldRepresentationTree::feedSILForFamsAndGrps(vtkMutableDirectedGraph* sil, vtkIdType root, vtkVariantArray *edge, std::vector& names) const -{ - int dummy0(0),dummy1(0),dummy2(0); - const MEDFileFieldRepresentationLeaves& leaf(getTheSingleActivated(dummy0,dummy1,dummy2)); - std::string ret(leaf.getMeshName()); - int i(0); - MEDFileMesh *m(0); - for(;i<_ms->getNumberOfMeshes();i++) - { - m=_ms->getMeshAtPos(i); - if(m->getName()==ret) - break; - } - if(i==_ms->getNumberOfMeshes()) - throw INTERP_KERNEL::Exception("MEDFileFieldRepresentationTree::feedSILForFamsAndGrps : internal error #0 !"); - vtkIdType typeId0(sil->AddChild(root,edge)); - names.push_back(m->getName()); - // - vtkIdType typeId1(sil->AddChild(typeId0,edge)); - names.push_back(std::string(ROOT_OF_GRPS_IN_TREE)); - std::vector grps(m->getGroupsNames()); - for(std::vector::const_iterator it0=grps.begin();it0!=grps.end();it0++) - { - vtkIdType typeId2(sil->AddChild(typeId1,edge)); - names.push_back(*it0); - std::vector famsOnGrp(m->getFamiliesOnGroup((*it0).c_str())); - for(std::vector::const_iterator it1=famsOnGrp.begin();it1!=famsOnGrp.end();it1++) - { - sil->AddChild(typeId2,edge); - names.push_back((*it1).c_str()); - } - } - // - vtkIdType typeId11(sil->AddChild(typeId0,edge)); - names.push_back(std::string(ROOT_OF_FAM_IDS_IN_TREE)); - std::vector fams(m->getFamiliesNames()); - for(std::vector::const_iterator it00=fams.begin();it00!=fams.end();it00++) - { - sil->AddChild(typeId11,edge); - int famId(m->getFamilyId((*it00).c_str())); - std::ostringstream oss; oss << (*it00) << MEDFileFieldRepresentationLeavesArrays::ZE_SEP << famId; - names.push_back(oss.str()); - } - return ret; -} - -const MEDFileFieldRepresentationLeavesArrays& MEDFileFieldRepresentationTree::getLeafArr(int id) const -{ - for(std::vector< std::vector< std::vector< MEDFileFieldRepresentationLeaves > > >::const_iterator it0=_data_structure.begin();it0!=_data_structure.end();it0++) - for(std::vector< std::vector< MEDFileFieldRepresentationLeaves > >::const_iterator it1=(*it0).begin();it1!=(*it0).end();it1++) - for(std::vector< MEDFileFieldRepresentationLeaves >::const_iterator it2=(*it1).begin();it2!=(*it1).end();it2++) - if((*it2).containId(id)) - return (*it2).getLeafArr(id); - throw INTERP_KERNEL::Exception("Internal error in MEDFileFieldRepresentationTree::getLeafArr !"); -} - -std::string MEDFileFieldRepresentationTree::getNameOf(int id) const -{ - const MEDFileFieldRepresentationLeavesArrays& elt(getLeafArr(id)); - return elt.getZeName(); -} - -const char *MEDFileFieldRepresentationTree::getNameOfC(int id) const -{ - const MEDFileFieldRepresentationLeavesArrays& elt(getLeafArr(id)); - return elt.getZeNameC(); -} - -bool MEDFileFieldRepresentationTree::getStatusOf(int id) const -{ - const MEDFileFieldRepresentationLeavesArrays& elt(getLeafArr(id)); - return elt.getStatus(); -} - -int MEDFileFieldRepresentationTree::getIdHavingZeName(const char *name) const -{ - int ret(-1); - for(std::vector< std::vector< std::vector< MEDFileFieldRepresentationLeaves > > >::const_iterator it0=_data_structure.begin();it0!=_data_structure.end();it0++) - for(std::vector< std::vector< MEDFileFieldRepresentationLeaves > >::const_iterator it1=(*it0).begin();it1!=(*it0).end();it1++) - for(std::vector< MEDFileFieldRepresentationLeaves >::const_iterator it2=(*it1).begin();it2!=(*it1).end();it2++) - if((*it2).containZeName(name,ret)) - return ret; - std::ostringstream msg; msg << "MEDFileFieldRepresentationTree::getIdHavingZeName : No such a name \"" << name << "\" !"; - throw INTERP_KERNEL::Exception(msg.str().c_str()); -} - -bool MEDFileFieldRepresentationTree::changeStatusOfAndUpdateToHaveCoherentVTKDataSet(int id, bool status) const -{ - const MEDFileFieldRepresentationLeavesArrays& elt(getLeafArr(id)); - bool ret(elt.setStatus(status));//to be implemented - return ret; -} - -int MEDFileFieldRepresentationTree::getMaxNumberOfTimeSteps() const -{ - int ret(0); - for(std::vector< std::vector< std::vector< MEDFileFieldRepresentationLeaves > > >::const_iterator it0=_data_structure.begin();it0!=_data_structure.end();it0++) - for(std::vector< std::vector< MEDFileFieldRepresentationLeaves > >::const_iterator it1=(*it0).begin();it1!=(*it0).end();it1++) - for(std::vector< MEDFileFieldRepresentationLeaves >::const_iterator it2=(*it1).begin();it2!=(*it1).end();it2++) - ret=std::max(ret,(*it2).getNumberOfTS()); - return ret; -} - -/*! - * - */ -void MEDFileFieldRepresentationTree::loadInMemory(MEDCoupling::MEDFileFields *fields, MEDCoupling::MEDFileMeshes *meshes) -{ - _fields=fields; _ms=meshes; - if(_fields.isNotNull()) - _fields->incrRef(); - if(_ms.isNotNull()) - _ms->incrRef(); - // - if(_fields.isNull()) - { - _fields=BuildFieldFromMeshes(_ms); - } - else - { - AppendFieldFromMeshes(_ms,_fields); - } - _ms->cartesianizeMe(); - _fields->removeFieldsWithoutAnyTimeStep(); - std::vector meshNames(_ms->getMeshesNames()); - std::vector< MCAuto > fields_per_mesh(meshNames.size()); - for(std::size_t i=0;ipartOfThisLyingOnSpecifiedMeshName(meshNames[i].c_str()); - } - std::vector< MCAuto > allFMTSLeavesToDisplaySafe; - std::size_t k(0); - for(std::vector< MCAuto >::const_iterator fields=fields_per_mesh.begin();fields!=fields_per_mesh.end();fields++) - { - for(int j=0;j<(*fields)->getNumberOfFields();j++) - { - MCAuto fmts((*fields)->getFieldAtPos((int)j)); - std::vector< MCAuto< MEDFileAnyTypeFieldMultiTS > > tmp(fmts->splitDiscretizations()); - // EDF 8655 - for(std::vector< MCAuto< MEDFileAnyTypeFieldMultiTS > >::const_iterator it=tmp.begin();it!=tmp.end();it++) - { - if(!(*it)->presenceOfMultiDiscPerGeoType()) - allFMTSLeavesToDisplaySafe.push_back(*it); - else - {// The case of some parts of field have more than one discretization per geo type. - std::vector< MCAuto< MEDFileAnyTypeFieldMultiTS > > subTmp((*it)->splitMultiDiscrPerGeoTypes()); - std::size_t it0Cnt(0); - for(std::vector< MCAuto< MEDFileAnyTypeFieldMultiTS > >::iterator it0=subTmp.begin();it0!=subTmp.end();it0++,it0Cnt++)//not const because setName - { - std::ostringstream oss; oss << (*it0)->getName() << "_" << std::setfill('M') << std::setw(3) << it0Cnt; - (*it0)->setName(oss.str()); - allFMTSLeavesToDisplaySafe.push_back(*it0); - } - } - } - // end EDF 8655 - } - } - std::vector< MEDFileAnyTypeFieldMultiTS *> allFMTSLeavesToDisplay(allFMTSLeavesToDisplaySafe.size()); - for(std::size_t i=0;i > allFMTSLeavesPerTimeSeries(MEDFileAnyTypeFieldMultiTS::SplitIntoCommonTimeSeries(allFMTSLeavesToDisplay)); - // memory safety part - std::vector< std::vector< MCAuto > > allFMTSLeavesPerTimeSeriesSafe(allFMTSLeavesPerTimeSeries.size()); - for(std::size_t j=0;jincrRef();//because MEDFileAnyTypeFieldMultiTS::SplitIntoCommonTimeSeries do not increments the counter - allFMTSLeavesPerTimeSeriesSafe[j][k]=allFMTSLeavesPerTimeSeries[j][k]; - } - } - // end of memory safety part - // 1st : timesteps, 2nd : meshName, 3rd : common support - this->_data_structure.resize(allFMTSLeavesPerTimeSeriesSafe.size()); - for(std::size_t i=0;i meshNamesLoc; - std::vector< std::vector< MCAuto > > splitByMeshName; - for(std::size_t j=0;jgetMeshName()); - std::vector< std::string >::iterator it(std::find(meshNamesLoc.begin(),meshNamesLoc.end(),meshName)); - if(it==meshNamesLoc.end()) - { - meshNamesLoc.push_back(meshName); - splitByMeshName.resize(splitByMeshName.size()+1); - splitByMeshName.back().push_back(allFMTSLeavesPerTimeSeriesSafe[i][j]); - } - else - splitByMeshName[std::distance(meshNamesLoc.begin(),it)].push_back(allFMTSLeavesPerTimeSeriesSafe[i][j]); - } - _data_structure[i].resize(meshNamesLoc.size()); - for(std::size_t j=0;j > fsp; - std::vector< MEDFileAnyTypeFieldMultiTS *> sbmn(splitByMeshName[j].size()); - for(std::size_t k=0;k > commonSupSplit(MEDFileAnyTypeFieldMultiTS::SplitPerCommonSupport(sbmn,_ms->getMeshWithName(meshNamesLoc[j].c_str()),fsp)); - std::vector< std::vector< MCAuto > > commonSupSplitSafe(commonSupSplit.size()); - this->_data_structure[i][j].resize(commonSupSplit.size()); - for(std::size_t k=0;kincrRef();//because MEDFileAnyTypeFieldMultiTS::SplitPerCommonSupport does not increment pointers ! - commonSupSplitSafe[k][l]=commonSupSplit[k][l]; - } - } - for(std::size_t k=0;k_data_structure[i][j][k]=MEDFileFieldRepresentationLeaves(commonSupSplitSafe[k],fsp[k]); - } - } - this->removeEmptyLeaves(); - this->assignIds(); - this->computeFullNameInLeaves(); -} - -void MEDFileFieldRepresentationTree::loadMainStructureOfFile(const char *fileName, bool isMEDOrSauv, int iPart, int nbOfParts) -{ - MCAuto ms; - MCAuto fields; - if(isMEDOrSauv) - { - if((iPart==-1 && nbOfParts==-1) || (iPart==0 && nbOfParts==1)) - { - MCAuto msups(MEDFileMeshSupports::New(fileName)); - MCAuto mse(MEDFileStructureElements::New(fileName,msups)); - ms=MEDFileMeshes::New(fileName); - fields=MEDFileFields::NewWithDynGT(fileName,mse,false);//false is important to not read the values - if(ms->presenceOfStructureElements()) - {// pre traitement - fields->loadArrays(); - fields->blowUpSE(ms,mse); - } - int nbMeshes(ms->getNumberOfMeshes()); - for(int i=0;igetMeshAtPos(i)); - MEDCoupling::MEDFileUMesh *tmp2(dynamic_cast(tmp)); - if(tmp2) - tmp2->forceComputationOfParts(); - } - } - else - { -#ifdef MEDREADER_USE_MPI - ms=ParaMEDFileMeshes::New(iPart,nbOfParts,fileName); - int nbMeshes(ms->getNumberOfMeshes()); - for(int i=0;igetMeshAtPos(i)); - MEDCoupling::MEDFileUMesh *tmp2(dynamic_cast(tmp)); - if(tmp2) - MCAuto tmp3(tmp2->zipCoords()); - } - fields=MEDFileFields::LoadPartOf(fileName,false,ms);//false is important to not read the values -#else - std::ostringstream oss; oss << "MEDFileFieldRepresentationTree::loadMainStructureOfFile : request for iPart/nbOfParts=" << iPart << "/" << nbOfParts << " whereas Plugin not compiled with MPI !"; - throw INTERP_KERNEL::Exception(oss.str().c_str()); -#endif - } - } - else - { - MCAuto sr(MEDCoupling::SauvReader::New(fileName)); - MCAuto mfd(sr->loadInMEDFileDS()); - ms=mfd->getMeshes(); ms->incrRef(); - int nbMeshes(ms->getNumberOfMeshes()); - for(int i=0;igetMeshAtPos(i)); - MEDCoupling::MEDFileUMesh *tmp2(dynamic_cast(tmp)); - if(tmp2) - tmp2->forceComputationOfParts(); - } - fields=mfd->getFields(); - if(fields.isNotNull()) - fields->incrRef(); - } - loadInMemory(fields,ms); -} - -void MEDFileFieldRepresentationTree::removeEmptyLeaves() -{ - std::vector< std::vector< std::vector< MEDFileFieldRepresentationLeaves > > > newSD; - for(std::vector< std::vector< std::vector< MEDFileFieldRepresentationLeaves > > >::const_iterator it0=_data_structure.begin();it0!=_data_structure.end();it0++) - { - std::vector< std::vector< MEDFileFieldRepresentationLeaves > > newSD0; - for(std::vector< std::vector< MEDFileFieldRepresentationLeaves > >::const_iterator it1=(*it0).begin();it1!=(*it0).end();it1++) - { - std::vector< MEDFileFieldRepresentationLeaves > newSD1; - for(std::vector< MEDFileFieldRepresentationLeaves >::const_iterator it2=(*it1).begin();it2!=(*it1).end();it2++) - if(!(*it2).empty()) - newSD1.push_back(*it2); - if(!newSD1.empty()) - newSD0.push_back(newSD1); - } - if(!newSD0.empty()) - newSD.push_back(newSD0); - } -} - -bool MEDFileFieldRepresentationTree::IsFieldMeshRegardingInfo(const std::vector& compInfos) -{ - if(compInfos.size()!=1) - return false; - return compInfos[0]==COMPO_STR_TO_LOCATE_MESH_DA; -} - -std::string MEDFileFieldRepresentationTree::getDftMeshName() const -{ - return _data_structure[0][0][0].getMeshName(); -} - -std::vector MEDFileFieldRepresentationTree::getTimeSteps(int& lev0, const TimeKeeper& tk) const -{ - int lev1,lev2; - const MEDFileFieldRepresentationLeaves& leaf(getTheSingleActivated(lev0,lev1,lev2)); - return leaf.getTimeSteps(tk); -} - -vtkDataSet *MEDFileFieldRepresentationTree::buildVTKInstance(bool isStdOrMode, double timeReq, std::string& meshName, const TimeKeeper& tk, ExportedTinyInfo *internalInfo) const -{ - int lev0,lev1,lev2; - const MEDFileFieldRepresentationLeaves& leaf(getTheSingleActivated(lev0,lev1,lev2)); - meshName=leaf.getMeshName(); - std::vector ts(leaf.getTimeSteps(tk)); - std::size_t zeTimeId(0); - if(ts.size()!=1) - { - std::vector ts2(ts.size()); - std::transform(ts.begin(),ts.end(),ts2.begin(),std::bind2nd(std::plus(),-timeReq)); - std::transform(ts2.begin(),ts2.end(),ts2.begin(),std::ptr_fun(fabs)); - zeTimeId=std::distance(ts2.begin(),std::find_if(ts2.begin(),ts2.end(),std::bind2nd(std::less(),1e-14))); - } - //2nd chance - if(zeTimeId==ts.size()) - zeTimeId=std::distance(ts.begin(),std::find(ts.begin(),ts.end(),timeReq)); - if(zeTimeId==ts.size()) - {//OK the time requested does not fit time series given to ParaView. It is typically the case if more than one MEDReader instance are created or TimeInspector in real time mode. - //In this case the default behaviour is taken. Keep the highest time step in this lower than timeReq. - int pos(-1); - double valAttachedToPos(-std::numeric_limits::max()); - for(std::size_t i=0;ivalAttachedToPos) - { - pos=(int)i; - valAttachedToPos=ts[i]; - } - } - } - if(pos==-1) - {// timeReq is lower than all time steps (ts). So let's keep the lowest time step greater than timeReq. - valAttachedToPos=std::numeric_limits::max(); - for(std::size_t i=0;i(oss,",")); - oss << " ! Keep time " << valAttachedToPos << " at pos #" << zeTimeId; - std::cerr << oss.str() << std::endl; - } - MEDTimeReq *tr(0); - if(!isStdOrMode) - tr=new MEDStdTimeReq((int)zeTimeId); - else - tr=new MEDModeTimeReq(tk.getTheVectOfBool(),tk.getPostProcessedTime()); - vtkDataSet *ret(leaf.buildVTKInstanceNoTimeInterpolation(tr,_fields,_ms,internalInfo)); - delete tr; - return ret; -} - -const MEDFileFieldRepresentationLeaves& MEDFileFieldRepresentationTree::getTheSingleActivated(int& lev0, int& lev1, int& lev2) const -{ - int nbOfActivated(0); - for(std::vector< std::vector< std::vector< MEDFileFieldRepresentationLeaves > > >::const_iterator it0=_data_structure.begin();it0!=_data_structure.end();it0++) - for(std::vector< std::vector< MEDFileFieldRepresentationLeaves > >::const_iterator it1=(*it0).begin();it1!=(*it0).end();it1++) - for(std::vector< MEDFileFieldRepresentationLeaves >::const_iterator it2=(*it1).begin();it2!=(*it1).end();it2++) - if((*it2).isActivated()) - nbOfActivated++; - if(nbOfActivated!=1) - { - std::ostringstream oss; oss << "MEDFileFieldRepresentationTree::getTheSingleActivated : Only one leaf must be activated ! Having " << nbOfActivated << " !"; - throw INTERP_KERNEL::Exception(oss.str().c_str()); - } - int i0(0),i1(0),i2(0); - for(std::vector< std::vector< std::vector< MEDFileFieldRepresentationLeaves > > >::const_iterator it0=_data_structure.begin();it0!=_data_structure.end();it0++,i0++) - for(std::vector< std::vector< MEDFileFieldRepresentationLeaves > >::const_iterator it1=(*it0).begin();it1!=(*it0).end();it1++,i1++) - for(std::vector< MEDFileFieldRepresentationLeaves >::const_iterator it2=(*it1).begin();it2!=(*it1).end();it2++,i2++) - if((*it2).isActivated()) - { - lev0=i0; lev1=i1; lev2=i2; - return *it2; - } - throw INTERP_KERNEL::Exception("MEDFileFieldRepresentationTree::getTheSingleActivated : Internal error !"); -} - -void MEDFileFieldRepresentationTree::printMySelf(std::ostream& os) const -{ - int i(0); - os << "#############################################" << std::endl; - for(std::vector< std::vector< std::vector< MEDFileFieldRepresentationLeaves > > >::const_iterator it0=_data_structure.begin();it0!=_data_structure.end();it0++,i++) - { - int j(0); - os << "TS" << i << std::endl; - for(std::vector< std::vector< MEDFileFieldRepresentationLeaves > >::const_iterator it1=(*it0).begin();it1!=(*it0).end();it1++,j++) - { - int k(0); - for(std::vector< MEDFileFieldRepresentationLeaves >::const_iterator it2=(*it1).begin();it2!=(*it1).end();it2++,k++) - { - if(k==0) - os << " " << (*it2).getMeshName() << std::endl; - os << " Comp" << k << std::endl; - (*it2).printMySelf(os); - } - } - } - os << "$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$" << std::endl; -} - -std::map MEDFileFieldRepresentationTree::dumpState() const -{ - std::map ret; - for(std::vector< std::vector< std::vector< MEDFileFieldRepresentationLeaves > > >::const_iterator it0=_data_structure.begin();it0!=_data_structure.end();it0++) - for(std::vector< std::vector< MEDFileFieldRepresentationLeaves > >::const_iterator it1=(*it0).begin();it1!=(*it0).end();it1++) - for(std::vector< MEDFileFieldRepresentationLeaves >::const_iterator it2=(*it1).begin();it2!=(*it1).end();it2++) - (*it2).dumpState(ret); - return ret; -} - -void MEDFileFieldRepresentationTree::AppendFieldFromMeshes(const MEDCoupling::MEDFileMeshes *ms, MEDCoupling::MEDFileFields *ret) -{ - if(!ret) - throw INTERP_KERNEL::Exception("MEDFileFieldRepresentationTree::AppendFieldFromMeshes : internal error ! NULL ret !"); - for(int i=0;igetNumberOfMeshes();i++) - { - MEDFileMesh *mm(ms->getMeshAtPos(i)); - std::vector levs(mm->getNonEmptyLevels()); - MEDCoupling::MCAuto f1tsMultiLev(MEDCoupling::MEDFileField1TS::New()); - MEDFileUMesh *mmu(dynamic_cast(mm)); - if(mmu) - { - for(std::vector::const_iterator it=levs.begin();it!=levs.end();it++) - { - std::vector gts(mmu->getGeoTypesAtLevel(*it)); - for(std::vector::const_iterator gt=gts.begin();gt!=gts.end();gt++) - { - MEDCoupling::MEDCouplingMesh *m(mmu->getDirectUndergroundSingleGeoTypeMesh(*gt)); - MEDCoupling::MCAuto f(MEDCoupling::MEDCouplingFieldDouble::New(MEDCoupling::ON_CELLS)); - f->setMesh(m); - MEDCoupling::MCAuto arr(MEDCoupling::DataArrayDouble::New()); arr->alloc(f->getNumberOfTuplesExpected()); - arr->setInfoOnComponent(0,std::string(COMPO_STR_TO_LOCATE_MESH_DA)); - arr->iota(); - f->setArray(arr); - f->setName(BuildAUniqueArrayNameForMesh(mm->getName(),ret)); - f1tsMultiLev->setFieldNoProfileSBT(f); - } - } - if(levs.empty()) - { - std::vector levsExt(mm->getNonEmptyLevelsExt()); - if(levsExt.size()==levs.size()+1) - { - MEDCoupling::MCAuto m(mm->getMeshAtLevel(1)); - MEDCoupling::MCAuto f(MEDCoupling::MEDCouplingFieldDouble::New(MEDCoupling::ON_NODES)); - f->setMesh(m); - MEDCoupling::MCAuto arr(MEDCoupling::DataArrayDouble::New()); arr->alloc(m->getNumberOfNodes()); - arr->setInfoOnComponent(0,std::string(COMPO_STR_TO_LOCATE_MESH_DA)); - arr->iota(); f->setArray(arr); - f->setName(BuildAUniqueArrayNameForMesh(mm->getName(),ret)); - f1tsMultiLev->setFieldNoProfileSBT(f); - } - else - continue; - } - } - else - { - MEDCoupling::MCAuto m(mm->getMeshAtLevel(0)); - MEDCoupling::MCAuto f(MEDCoupling::MEDCouplingFieldDouble::New(MEDCoupling::ON_CELLS)); - f->setMesh(m); - MEDCoupling::MCAuto arr(MEDCoupling::DataArrayDouble::New()); arr->alloc(f->getNumberOfTuplesExpected()); - arr->setInfoOnComponent(0,std::string(COMPO_STR_TO_LOCATE_MESH_DA)); - arr->iota(); - f->setArray(arr); - f->setName(BuildAUniqueArrayNameForMesh(mm->getName(),ret)); - f1tsMultiLev->setFieldNoProfileSBT(f); - } - // - MEDCoupling::MCAuto fmtsMultiLev(MEDCoupling::MEDFileFieldMultiTS::New()); - fmtsMultiLev->pushBackTimeStep(f1tsMultiLev); - ret->pushField(fmtsMultiLev); - } -} - -std::string MEDFileFieldRepresentationTree::BuildAUniqueArrayNameForMesh(const std::string& meshName, const MEDCoupling::MEDFileFields *ret) -{ - const char KEY_STR_TO_AVOID_COLLIDE[]="MESH@"; - if(!ret) - throw INTERP_KERNEL::Exception("MEDFileFieldRepresentationTree::BuildAUniqueArrayNameForMesh : internal error ! NULL ret !"); - std::vector fieldNamesAlreadyExisting(ret->getFieldsNames()); - if(std::find(fieldNamesAlreadyExisting.begin(),fieldNamesAlreadyExisting.end(),meshName)==fieldNamesAlreadyExisting.end()) - return meshName; - std::string tmpName(KEY_STR_TO_AVOID_COLLIDE); tmpName+=meshName; - while(std::find(fieldNamesAlreadyExisting.begin(),fieldNamesAlreadyExisting.end(),tmpName)!=fieldNamesAlreadyExisting.end()) - tmpName=std::string(KEY_STR_TO_AVOID_COLLIDE)+tmpName; - return tmpName; -} - -MEDCoupling::MEDFileFields *MEDFileFieldRepresentationTree::BuildFieldFromMeshes(const MEDCoupling::MEDFileMeshes *ms) -{ - MEDCoupling::MCAuto ret(MEDCoupling::MEDFileFields::New()); - AppendFieldFromMeshes(ms,ret); - return ret.retn(); -} - -std::vector MEDFileFieldRepresentationTree::SplitFieldNameIntoParts(const std::string& fullFieldName, char sep) -{ - std::vector ret; - std::size_t pos(0); - while(pos!=std::string::npos) - { - std::size_t curPos(fullFieldName.find_first_of(sep,pos)); - std::string elt(fullFieldName.substr(pos,curPos!=std::string::npos?curPos-pos:std::string::npos)); - ret.push_back(elt); - pos=fullFieldName.find_first_not_of(sep,curPos); - } - return ret; -} - -/*! - * Here the non regression tests. - * const char inp0[]=""; - * const char exp0[]=""; - * const char inp1[]="field"; - * const char exp1[]="field"; - * const char inp2[]="_________"; - * const char exp2[]="_________"; - * const char inp3[]="field_p"; - * const char exp3[]="field_p"; - * const char inp4[]="field__p"; - * const char exp4[]="field_p"; - * const char inp5[]="field_p__"; - * const char exp5[]="field_p"; - * const char inp6[]="field_p_"; - * const char exp6[]="field_p"; - * const char inp7[]="field_____EDFGEG//sdkjf_____PP_______________"; - * const char exp7[]="field_EDFGEG//sdkjf_PP"; - * const char inp8[]="field_____EDFGEG//sdkjf_____PP"; - * const char exp8[]="field_EDFGEG//sdkjf_PP"; - * const char inp9[]="_field_____EDFGEG//sdkjf_____PP_______________"; - * const char exp9[]="field_EDFGEG//sdkjf_PP"; - * const char inp10[]="___field_____EDFGEG//sdkjf_____PP_______________"; - * const char exp10[]="field_EDFGEG//sdkjf_PP"; -*/ -std::string MEDFileFieldRepresentationTree::PostProcessFieldName(const std::string& fullFieldName) -{ - const char SEP('_'); - std::vector v(SplitFieldNameIntoParts(fullFieldName,SEP)); - if(v.empty()) - return fullFieldName;//should never happen - if(v.size()==1) - { - if(v[0].empty()) - return fullFieldName; - else - return v[0]; - } - std::string ret(v[0]); - for(std::size_t i=1;i TimeKeeper::getTimeStepsRegardingPolicy(const std::vector< std::pair >& tsPairs, const std::vector& ts) const -{ - switch(_policy) - { - case 0: - return getTimeStepsRegardingPolicy0(tsPairs,ts); - case 1: - return getTimeStepsRegardingPolicy0(tsPairs,ts); - default: - throw INTERP_KERNEL::Exception("TimeKeeper::getTimeStepsRegardingPolicy : only policy 0 and 1 supported presently !"); - } -} - -/*! - * policy = 0 : - * if all of ts are in -1e299,1e299 and different each other pairs are ignored ts taken directly. - * if all of ts are in -1e299,1e299 but some are not different each other ts are ignored pairs used - * if some of ts are out of -1e299,1e299 ts are ignored pairs used - */ -std::vector TimeKeeper::getTimeStepsRegardingPolicy0(const std::vector< std::pair >& tsPairs, const std::vector& ts) const -{ - std::size_t sz(ts.size()); - bool isInHumanRange(true); - std::set s; - for(std::size_t i=0;i=1e299) - isInHumanRange=false; - } - if(!isInHumanRange) - return processedUsingPairOfIds(tsPairs); - if(s.size()!=sz) - return processedUsingPairOfIds(tsPairs); - _postprocessed_time=ts; - return getPostProcessedTime(); -} - -/*! - * policy = 1 : - * idem than 0, except that ts is preaccumulated before invoking policy 0. - */ -std::vector TimeKeeper::getTimeStepsRegardingPolicy1(const std::vector< std::pair >& tsPairs, const std::vector& ts) const -{ - std::size_t sz(ts.size()); - std::vector ts2(sz); - double acc(0.); - for(std::size_t i=0;i TimeKeeper::getTheVectOfBool() const -{ - std::size_t sz(_activated_ts.size()); - std::vector ret(sz); - for(std::size_t i=0;i TimeKeeper::processedUsingPairOfIds(const std::vector< std::pair >& tsPairs) const -{ - std::size_t sz(tsPairs.size()); - std::set s0,s1; - for(std::size_t i=0;i(true,oss.str()); - } -} diff --git a/src/Plugins/MEDReader/IO/MEDFileFieldRepresentationTree.hxx b/src/Plugins/MEDReader/IO/MEDFileFieldRepresentationTree.hxx deleted file mode 100644 index 36a1adf5..00000000 --- a/src/Plugins/MEDReader/IO/MEDFileFieldRepresentationTree.hxx +++ /dev/null @@ -1,208 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Anthony Geay - -#ifndef __MEDFILEFIELDREPRESENTATIONTREE_HXX__ -#define __MEDFILEFIELDREPRESENTATIONTREE_HXX__ - -#include "MEDFileMesh.hxx" -#include "MEDFileField.hxx" -#include "MEDLoaderForPV.h" - -#include "vtkType.h" - -#include -#include - -class vtkQuadratureSchemeDefinition; -class vtkMutableDirectedGraph; -class vtkUnstructuredGrid; -class vtkRectilinearGrid; -class vtkStructuredGrid; -class vtkVariantArray; -class vtkIdTypeArray; -class vtkDoubleArray; -class vtkDataArray; -class vtkDataSet; - -class TimeKeeper; -class MEDTimeReq; -class ExportedTinyInfo; - -class ELGACmp -{ -public: - template - vtkIdTypeArray *findOrCreate(const MEDCoupling::MEDFileFieldGlobsReal *globs, const std::vector& locsReallyUsed, vtkDataArray *vtkd, vtkDataSet *ds, bool& isNew, ExportedTinyInfo *internalInfo) const; - void appendELGAIfAny(vtkDataSet *ds) const; - ~ELGACmp(); -private: - vtkIdTypeArray *isExisting(const std::vector& locsReallyUsed, vtkDataArray *vtkd) const; - template - vtkIdTypeArray *createNew(const MEDCoupling::MEDFileFieldGlobsReal *globs, const std::vector& locsReallyUsed, vtkDataArray *vtkd, vtkDataSet *ds, ExportedTinyInfo *internalInfo) const; -private: - //! size of _loc_names is equal to _elgas. - mutable std::vector< std::vector > _loc_names; - //! size of _elgas is equal to _loc_names. All instances in _elgas are \b not null. - mutable std::vector _elgas; - //! same size than _loc_names and _elgas. - mutable std::vector< std::vector< std::pair< vtkQuadratureSchemeDefinition *, unsigned char > > > _defs; -}; - -class MEDLOADERFORPV_EXPORT MEDFileFieldRepresentationLeavesArrays : public MEDCoupling::MCAuto -{ -public: - MEDFileFieldRepresentationLeavesArrays(); - MEDFileFieldRepresentationLeavesArrays(const MEDCoupling::MCAuto& arr); - MEDFileFieldRepresentationLeavesArrays& operator=(const MEDFileFieldRepresentationLeavesArrays& other); - int getId() const; - void setId(int& id) const; - void feedSIL(vtkMutableDirectedGraph* sil, vtkIdType root, vtkVariantArray *edge, std::vector& names) const; - void computeFullNameInLeaves(const std::string& tsName, const std::string& meshName, const std::string& comSupStr) const; - bool getStatus() const; - bool setStatus(bool status) const; - std::string getZeName() const; - const char *getZeNameC() const; - void appendFields(const MEDTimeReq *tr, const MEDCoupling::MEDFileFieldGlobsReal *globs, const MEDCoupling::MEDMeshMultiLev *mml, const MEDCoupling::MEDFileMeshStruct *mst, vtkDataSet *ds, ExportedTinyInfo *internalInfo) const; - void appendELGAIfAny(vtkDataSet *ds) const; -public: - static const char ZE_SEP[]; - static const char TS_STR[]; - static const char COM_SUP_STR[]; - static const char FAMILY_ID_CELL_NAME[]; - static const char NUM_ID_CELL_NAME[]; - static const char FAMILY_ID_NODE_NAME[]; - static const char NUM_ID_NODE_NAME[]; - static const char GLOBAL_NODE_ID_NAME[]; -private: - mutable bool _activated; - mutable int _id; - mutable std::string _ze_name; - mutable std::string _ze_full_name; - ELGACmp _elga_cmp; -}; - -class MEDLOADERFORPV_EXPORT MEDFileFieldRepresentationLeaves -{ -public: - MEDFileFieldRepresentationLeaves(); - MEDFileFieldRepresentationLeaves(const std::vector< MEDCoupling::MCAuto >& arr, - const MEDCoupling::MCAuto& fsp); - ~MEDFileFieldRepresentationLeaves(); - bool empty() const; - void setId(int& id) const; - std::string getMeshName() const; - int getNumberOfArrays() const; - int getNumberOfTS() const; - void feedSIL(const MEDCoupling::MEDFileMeshes *ms, const std::string& meshName, vtkMutableDirectedGraph* sil, vtkIdType root, vtkVariantArray *edge, std::vector& names) const; - void computeFullNameInLeaves(const std::string& tsName, const std::string& meshName, const std::string& comSupStr) const; - bool containId(int id) const; - bool containZeName(const char *name, int& id) const; - void dumpState(std::map& status) const; - bool isActivated() const; - void printMySelf(std::ostream& os) const; - void activateAllArrays() const; - const MEDFileFieldRepresentationLeavesArrays& getLeafArr(int id) const; - std::vector getTimeSteps(const TimeKeeper& tk) const; - std::vector< std::pair > getTimeStepsInCoarseMEDFileFormat(std::vector& ts) const; - std::string getHumanReadableOverviewOfTS() const; - vtkDataSet *buildVTKInstanceNoTimeInterpolation(const MEDTimeReq *tr, const MEDCoupling::MEDFileFieldGlobsReal *globs, const MEDCoupling::MEDFileMeshes *meshes, ExportedTinyInfo *internalInfo=0) const; -private: - vtkUnstructuredGrid *buildVTKInstanceNoTimeInterpolationUnstructured(MEDCoupling::MEDUMeshMultiLev *mm) const; - vtkRectilinearGrid *buildVTKInstanceNoTimeInterpolationCartesian(MEDCoupling::MEDCMeshMultiLev *mm) const; - vtkStructuredGrid *buildVTKInstanceNoTimeInterpolationCurveLinear(MEDCoupling::MEDCurveLinearMeshMultiLev *mm) const; - void appendFields(const MEDTimeReq *tr, const MEDCoupling::MEDFileFieldGlobsReal *globs, const MEDCoupling::MEDMeshMultiLev *mml, const MEDCoupling::MEDFileMeshes *meshes, vtkDataSet *ds, ExportedTinyInfo *internalInfo=0) const; -private: - std::vector _arrays; - MEDCoupling::MCAuto _fsp; - mutable vtkDataSet *_cached_ds; -}; - -class MEDLOADERFORPV_EXPORT MEDFileFieldRepresentationTree -{ -public: - MEDFileFieldRepresentationTree(); - int getNumberOfLeavesArrays() const; - void assignIds() const; - void activateTheFirst() const; - void computeFullNameInLeaves() const; - void feedSIL(vtkMutableDirectedGraph* sil, vtkIdType root, vtkVariantArray *edge, std::vector& names) const; - std::string getActiveMeshName() const; - std::string feedSILForFamsAndGrps(vtkMutableDirectedGraph* sil, vtkIdType root, vtkVariantArray *edge, std::vector& names) const; - std::string getNameOf(int id) const; - const char *getNameOfC(int id) const; - bool getStatusOf(int id) const; - int getIdHavingZeName(const char *name) const; - bool changeStatusOfAndUpdateToHaveCoherentVTKDataSet(int id, bool status) const; - int getMaxNumberOfTimeSteps() const; - // - std::string getDftMeshName() const; - std::vector getTimeSteps(int& lev0, const TimeKeeper& tk) const; - vtkDataSet *buildVTKInstance(bool isStdOrMode, double timeReq, std::string& meshName, const TimeKeeper& tk, ExportedTinyInfo *internalInfo=0) const; - void printMySelf(std::ostream& os) const; - std::map dumpState() const; - //non const methods - void loadMainStructureOfFile(const char *fileName, bool isMEDOrSauv, int iPart, int nbOfParts); - void loadInMemory(MEDCoupling::MEDFileFields *fields, MEDCoupling::MEDFileMeshes *meshes); - void removeEmptyLeaves(); - // static methods - static bool IsFieldMeshRegardingInfo(const std::vector& compInfos); - static std::string PostProcessFieldName(const std::string& fullFieldName); -public: - static const char ROOT_OF_GRPS_IN_TREE[]; - static const char ROOT_OF_FAM_IDS_IN_TREE[]; - static const char COMPO_STR_TO_LOCATE_MESH_DA[]; -private: - const MEDFileFieldRepresentationLeavesArrays& getLeafArr(int id) const; - const MEDFileFieldRepresentationLeaves& getTheSingleActivated(int& lev0, int& lev1, int& lev2) const; - static MEDCoupling::MEDFileFields *BuildFieldFromMeshes(const MEDCoupling::MEDFileMeshes *ms); - static void AppendFieldFromMeshes(const MEDCoupling::MEDFileMeshes *ms, MEDCoupling::MEDFileFields *ret); - static std::string BuildAUniqueArrayNameForMesh(const std::string& meshName, const MEDCoupling::MEDFileFields *ret); - static std::vector SplitFieldNameIntoParts(const std::string& fullFieldName, char sep); -private: - // 1st : timesteps, 2nd : meshName, 3rd : common support - std::vector< std::vector< std::vector< MEDFileFieldRepresentationLeaves > > > _data_structure; - MEDCoupling::MCAuto _ms; - MEDCoupling::MCAuto _fields; -}; - -class MEDLOADERFORPV_EXPORT TimeKeeper -{ -public: - TimeKeeper(int policy); - int getPolicy() const { return _policy; } - void setPolicy(int policy) { _policy=policy; } - std::vector getTimeStepsRegardingPolicy(const std::vector< std::pair >& tsPairs, const std::vector& ts) const; - int getTimeStepIdFrom(double timeReq) const; - std::vector getPostProcessedTime() const { return _postprocessed_time; } - void printSelf(std::ostream& oss) const; - std::vector getTheVectOfBool() const; - std::vector< std::pair >& getTimesFlagArray() { return _activated_ts; } - void setMaxNumberOfTimeSteps(int maxNumberOfTS); -private: - std::vector getTimeStepsRegardingPolicy0(const std::vector< std::pair >& tsPairs, const std::vector& ts) const; - std::vector getTimeStepsRegardingPolicy1(const std::vector< std::pair >& tsPairs, const std::vector& ts) const; - std::vector processedUsingPairOfIds(const std::vector< std::pair >& tsPairs) const; -private: - int _policy; - mutable std::vector _postprocessed_time; - std::vector< std::pair > _activated_ts; -}; - -#endif diff --git a/src/Plugins/MEDReader/IO/MEDLoaderForPV.h b/src/Plugins/MEDReader/IO/MEDLoaderForPV.h deleted file mode 100644 index f60b5c73..00000000 --- a/src/Plugins/MEDReader/IO/MEDLoaderForPV.h +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// - -#ifndef __MEDLOADERFORPV_HXX__ -#define __MEDLOADERFORPV_HXX__ - -#ifdef WIN32 -# if defined MEDLoaderForPV_EXPORTS || defined MEDLOADERFORPV_EXPORTS -# define MEDLOADERFORPV_EXPORT __declspec( dllexport ) -# else -# define MEDLOADERFORPV_EXPORT __declspec( dllimport ) -# endif -#else - #define MEDLOADERFORPV_EXPORT -#endif - -#endif diff --git a/src/Plugins/MEDReader/IO/MEDTimeReq.cxx b/src/Plugins/MEDReader/IO/MEDTimeReq.cxx deleted file mode 100644 index fa104990..00000000 --- a/src/Plugins/MEDReader/IO/MEDTimeReq.cxx +++ /dev/null @@ -1,135 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Anthony Geay - -#include "MEDTimeReq.hxx" - -#include - -MEDTimeReq::~MEDTimeReq() -{ -} - -/////////// - -MEDStdTimeReq::~MEDStdTimeReq() -{ -} - -MEDStdTimeReq::MEDStdTimeReq(int timeReq):_time_req(timeReq) -{ -} - -/*! - * Does nothing ! It is not a bug - */ -void MEDStdTimeReq::setNumberOfTS(int nbOfTS) const -{ -} - -int MEDStdTimeReq::size() const -{ - return 1; -} - -int MEDStdTimeReq::getCurrent() const -{ - return _time_req; -} - -/*! - * Does nothing ! It is not a bug - */ -void MEDStdTimeReq::initIterator() const -{ -} - -std::string MEDStdTimeReq::buildName(const std::string& name) const -{ - return std::string(name); -} - -/*! - * Does nothing ! It is not a bug - */ -void MEDStdTimeReq::operator++() const -{ -} - -/////////// - -MEDModeTimeReq::MEDModeTimeReq(const std::vector& v, const std::vector& ts):_v(v),_ts(ts),_it(0),_sz(0) -{ -} - -MEDModeTimeReq::~MEDModeTimeReq() -{ -} - -int MEDModeTimeReq::size() const -{ - int ret(0); - for(int i=0;i<_sz;i++) - { - if(_v[i]) - ret++; - } - return ret; -} - -int MEDModeTimeReq::getCurrent() const -{ - return _it; -} - -void MEDModeTimeReq::setNumberOfTS(int nbOfTS) const -{ - _sz=nbOfTS; -} - -void MEDModeTimeReq::initIterator() const -{ - for(_it=0;_it<_sz;_it++) - if(_v[_it]) - return; -} - -std::string MEDModeTimeReq::buildName(const std::string& name) const -{ - std::ostringstream oss,oss2,oss3; - oss << name << " ["; - // - oss3 << _sz-1; - std::size_t len(oss3.str().length()); - oss2.width(len); - oss2.fill('0'); oss2 << _it; - // - oss << oss2.str() << "]"; - if(_it<(int)_ts.size()) - oss << " - " << _ts[_it]; - return oss.str(); -} - -void MEDModeTimeReq::operator++() const -{ - _it++; - for(;_it<_sz;_it++) - if(_v[_it]) - return; -} diff --git a/src/Plugins/MEDReader/IO/MEDTimeReq.hxx b/src/Plugins/MEDReader/IO/MEDTimeReq.hxx deleted file mode 100644 index 49546196..00000000 --- a/src/Plugins/MEDReader/IO/MEDTimeReq.hxx +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Anthony Geay - -#ifndef __MEDTIMEREQ_HXX__ -#define __MEDTIMEREQ_HXX__ - -#include -#include - -#include "MEDLoaderForPV.h" - -class MEDLOADERFORPV_EXPORT MEDTimeReq -{ -public: - virtual int size() const = 0; - virtual void setNumberOfTS(int nbOfTS) const = 0; - virtual std::string buildName(const std::string& name) const = 0; - virtual void initIterator() const = 0; - virtual int getCurrent() const = 0; - virtual void operator++() const = 0; - virtual ~MEDTimeReq(); -}; - -class MEDLOADERFORPV_EXPORT MEDStdTimeReq : public MEDTimeReq -{ -public: - MEDStdTimeReq(int timeReq); - int size() const; - int getCurrent() const; - void initIterator() const; - void setNumberOfTS(int nbOfTS) const; - std::string buildName(const std::string& name) const; - void operator++() const; -public: - ~MEDStdTimeReq(); -private: - int _time_req; -}; - -class MEDLOADERFORPV_EXPORT MEDModeTimeReq : public MEDTimeReq -{ -public: - MEDModeTimeReq(const std::vector& v, const std::vector& ts); - ~MEDModeTimeReq(); - int size() const; - int getCurrent() const; - void initIterator() const; - void setNumberOfTS(int nbOfTS) const; - std::string buildName(const std::string& name) const; - void operator++() const; -private: - std::vector _v; - std::vector _ts; - mutable int _it; - mutable int _sz; -}; - -#endif diff --git a/src/Plugins/MEDReader/IO/MEDUtilities.cxx b/src/Plugins/MEDReader/IO/MEDUtilities.cxx deleted file mode 100644 index 0150a4e2..00000000 --- a/src/Plugins/MEDReader/IO/MEDUtilities.cxx +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Anthony Geay - -#include "MEDUtilities.hxx" - -#include "vtkInformationIntegerKey.h" -#include "vtkInformationQuadratureSchemeDefinitionVectorKey.h" - -#include - -vtkInformationKeyMacro(MEDUtilities,ELGA,Integer); -vtkInformationKeyMacro(MEDUtilities,ELNO,Integer); - -void ExportedTinyInfo::pushGaussAdditionnalInfo(int ct, int dim, const std::vector& refCoo, const std::vector& posInRefCoo) -{ - prepareForAppend(); - std::vector tmp(1,(double)ct); - tmp.push_back((double)dim); - tmp.insert(tmp.end(),refCoo.begin(),refCoo.end()); - tmp.insert(tmp.end(),posInRefCoo.begin(),posInRefCoo.end()); - _data.push_back((double)tmp.size()); - _data.insert(_data.end(),tmp.begin(),tmp.end()); -} - -void ExportedTinyInfo::prepareForAppend() -{ - if(_data.empty()) - _data.push_back(1.); - else - { - double val(_data[0]); - int val2((int) val); - _data[0]=++val2; - } -} diff --git a/src/Plugins/MEDReader/IO/MEDUtilities.hxx b/src/Plugins/MEDReader/IO/MEDUtilities.hxx deleted file mode 100644 index 25a04600..00000000 --- a/src/Plugins/MEDReader/IO/MEDUtilities.hxx +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Anthony Geay - -#ifndef __MEDUTILITIES_HXX__ -#define __MEDUTILITIES_HXX__ - -#include "MEDLoaderForPV.h" -#include "vtkCellType.h" - -#include - -class vtkInformationIntegerKey; - -class MEDLOADERFORPV_EXPORT MEDUtilities -{ -public: - static vtkInformationIntegerKey *ELGA(); - static vtkInformationIntegerKey *ELNO(); -}; - -class ExportedTinyInfo -{ -public: - void pushGaussAdditionnalInfo(int ct, int dim, const std::vector& refCoo, const std::vector& posInRefCoo); - const std::vector& getData() const { return _data; } - bool empty() const { return _data.empty(); } -private: - void prepareForAppend(); -private: - // first place is nb of ct - // 2nd place is the size of first ct def (this 2nd place included) - // 3rd place is the VTK cell type of first ct def - // 4th place is the dimension of first ct def - // 5th->n th : ref Coo - // nth -> n+p th : posInRefCoo - // n+p+1 -> size of second ct def (this n+p+1 place included) - // n+p+2 -> VTK cell type of second ct def - // ... - std::vector _data; -}; - -#endif diff --git a/src/Plugins/MEDReader/IO/Testing/CMakeLists.txt b/src/Plugins/MEDReader/IO/Testing/CMakeLists.txt deleted file mode 100644 index 189879cd..00000000 --- a/src/Plugins/MEDReader/IO/Testing/CMakeLists.txt +++ /dev/null @@ -1,20 +0,0 @@ -# Copyright (C) 2010-2019 CEA/DEN, EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# - -ADD_SUBDIRECTORY(Cxx) \ No newline at end of file diff --git a/src/Plugins/MEDReader/IO/Testing/Cxx/CMakeLists.txt b/src/Plugins/MEDReader/IO/Testing/Cxx/CMakeLists.txt deleted file mode 100644 index a84bd054..00000000 --- a/src/Plugins/MEDReader/IO/Testing/Cxx/CMakeLists.txt +++ /dev/null @@ -1,67 +0,0 @@ -# Copyright (C) 2010-2019 CEA/DEN, EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# - -INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}/../..) -INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR}/../..) -INCLUDE_DIRECTORIES(${MEDCOUPLING_INCLUDE_DIRS} ${MEDFILE_INCLUDE_DIRS} ${HDF5_INCLUDE_DIRS}) -INCLUDE_DIRECTORIES(${FIELDS_ROOT_DIR}/include/salome) - -SET( TestMedReader_SRCS TestMedReader.cxx ) - -SET( TestMedPolyhedron_SRCS TestMedPolyhedron.cxx ) - -SET( TestMedReadPolyhedron_SRCS TestMedReadPolyhedron.cxx ) - -SET( TestMedDescendingPolyhedron_SRCS TestMedDescendingPolyhedron.cxx ) - -SET( TestMedReadDescendingPolyhedron_SRCS TestMedReadDescendingPolyhedron.cxx ) - -SET( TestMedWriteOcta12_SRCS TestMedWriteOcta12.cxx ) - -SET( TestMedParallelRead_SRCS TestMedParallelRead.cxx ) - -SET( TestMedParallelWrite_SRCS TestMedParallelWrite.cxx ) - -ADD_EXECUTABLE(TestReading0 TestReading0.cxx) -TARGET_LINK_LIBRARIES(TestReading0 MEDLoaderForPV vtkCommonDataModel) - -#ADD_EXECUTABLE(TestMedReader ${TestMedReader_SRCS}) -#ADD_EXECUTABLE(TestMedPolyhedron ${TestMedPolyhedron_SRCS}) -#ADD_EXECUTABLE(TestMedReadPolyhedron ${TestMedReadPolyhedron_SRCS}) -#ADD_EXECUTABLE(TestMedDescendingPolyhedron ${TestMedDescendingPolyhedron_SRCS}) -#ADD_EXECUTABLE(TestMedReadDescendingPolyhedron ${TestMedReadDescendingPolyhedron_SRCS}) -#ADD_EXECUTABLE(TestMedWriteOcta12 ${TestMedWriteOcta12_SRCS}) - -#IF(${HDF5_IS_PARALLEL}) -# ADD_EXECUTABLE(TestMedParallelRead ${TestMedParallelRead_SRCS}) -# ADD_EXECUTABLE(TestMedParallelWrite ${TestMedParallelWrite_SRCS}) -# TARGET_LINK_LIBRARIES(TestMedParallelRead vtkParallelCore ${MED_LIBRARIES}) -# TARGET_LINK_LIBRARIES(TestMedParallelWrite vtkParallelCore ${MED_LIBRARIES}) -#ENDIF(${HDF5_IS_PARALLEL}) - -INCLUDE(${CMAKE_CURRENT_SOURCE_DIR}/../../module.cmake) - -#vtkIOMPIImage -#TARGET_LINK_LIBRARIES(TestMedReader ${${vtk-module-test}_DEPENDS} ${MEDFILE_C_LIBRARIES}) -#TARGET_LINK_LIBRARIES(TestMedPolyhedron ${MEDFILE_C_LIBRARIES}) -#TARGET_LINK_LIBRARIES(TestMedReadPolyhedron ${MEDFILE_C_LIBRARIES}) -#TARGET_LINK_LIBRARIES(TestMedDescendingPolyhedron ${MEDFILE_C_LIBRARIES}) -#TARGET_LINK_LIBRARIES(TestMedReadDescendingPolyhedron ${MEDFILE_C_LIBRARIES}) -#TARGET_LINK_LIBRARIES(TestMedWriteOcta12 ${MEDFILE_C_LIBRARIES}) - diff --git a/src/Plugins/MEDReader/IO/Testing/Cxx/TestMedDescendingPolyhedron.cxx b/src/Plugins/MEDReader/IO/Testing/Cxx/TestMedDescendingPolyhedron.cxx deleted file mode 100644 index c1690ad6..00000000 --- a/src/Plugins/MEDReader/IO/Testing/Cxx/TestMedDescendingPolyhedron.cxx +++ /dev/null @@ -1,189 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// - -/* - * TestMedDescendingPolyhedron.cxx - * - * Created on: 3 mars 2011 - * Author: alejandro - */ - -#include -#define MESGERR 1 -#include - -#include - -int main (int argc, char **argv) { - med_idt fid; - const char meshname[MED_NAME_SIZE+1] = "3D unstructured mesh"; - const med_int spacedim = 3; - const med_int meshdim = 3; - /* 12345678901234561234567890123456 */ - const char axisname[3*MED_SNAME_SIZE+1] = "x y z "; - const char unitname[3*MED_SNAME_SIZE+1] = "cm cm cm "; - const med_int nnodes = 12; - const med_float coordinates[3 * 12] = - { 1.618, 1., 0., - -1.618, 1., 0., - 1.618, -1., 0., - -1.618, -1., 0., - 1., 0., 1.618, - 1., 0., -1.618, - -1., 0., 1.618, - -1., 0., -1.618, - 0., 1.618, 1., - 0., -1.618, 1., - 0., 1.618, -1., - 0., -1.618, -1. }; - const med_int nodeIndexSize = 20; - const med_int nodeindex[20] = { - MED_TRIA3, MED_TRIA3, MED_TRIA3, MED_TRIA3, MED_TRIA3, - MED_TRIA3, MED_TRIA3, MED_TRIA3, MED_TRIA3, MED_TRIA3, - MED_TRIA3, MED_TRIA3, MED_TRIA3, MED_TRIA3, MED_TRIA3, - MED_TRIA3, MED_TRIA3, MED_TRIA3, MED_TRIA3, MED_TRIA3 }; - const med_int faceIndexSize = 2; - /* connectivity : 1 icosahedron */ - const med_int faceindex[2] = { 1, 21 }; - - const med_int connectivity[20] = { 1, 2, 3, 4, 5, 6, 7, 8, 9,10, - 11,12,13,14,15,16,17,18,19,20 }; - - const med_int ntria3 = 20; - const med_int triaConnectivity[60] = { 1, 9, 5, - 1, 6, 11, - 3, 5, 10, - 3, 12, 6, - 2, 7, 9, - 2, 11, 8, - 4, 10, 7, - 4, 8, 12, - 1, 11, 9, - 2, 9, 11, - 3, 10, 12, - 4, 10, 12, - 5, 3, 1, - 6, 1, 3, - 7, 2, 4, - 8, 4, 2, - 9, 7, 5, - 10, 5, 7, - 11, 6, 8, - 12, 8, 6 }; - - /* open MED file */ - fid = MEDfileOpen("UsesCase_MEDmesh_17.med", - MED_ACC_CREAT); - if (fid < 0) { - MESSAGE("ERROR : file creation ..."); - return -1; - } - - /* write a comment in the file */ - if (MEDfileCommentWr(fid, - "A 3D unstructured mesh : 1 icosahedron") < 0) { - MESSAGE("ERROR : write file description ..."); - return -1; - } - - /* mesh creation : a 3D unstructured mesh */ - if (MEDmeshCr(fid, - meshname, - spacedim, - meshdim, - MED_UNSTRUCTURED_MESH, - "A 3D mesh with 1 icosahedron in DESCENDING connectivity", - "", - MED_SORT_DTIT, - MED_CARTESIAN, - axisname, - unitname) < 0) { - MESSAGE("ERROR : mesh creation ..."); - return -1; - } - - /* nodes coordinates in a cartesian axis in full interlace mode - (X1,Y1, X2,Y2, X3,Y3, ...) with no iteration and computation step - */ - if (MEDmeshNodeCoordinateWr(fid, - meshname, - MED_NO_DT, - MED_NO_IT, - MED_UNDEF_DT, - MED_FULL_INTERLACE, - nnodes, - coordinates) < 0) { - MESSAGE("ERROR : nodes coordinates ..."); - return -1; - } - - // cells connectiviy is defined in nodal mode - // it is later in the polyhedron thet the connectivity is descending - if (MEDmeshElementConnectivityWr(fid, - meshname, - MED_NO_DT, - MED_NO_IT, - 0.0, - MED_DESCENDING_FACE, - MED_TRIA3, - MED_NODAL, - MED_FULL_INTERLACE, - ntria3, - triaConnectivity) < 0) { - MESSAGE("ERROR : triangular cells connectivity ..."); - return -1; - } - - // cells connectiviy is defined in descending mode - // 1 icosahedron - if (MEDmeshPolyhedronWr(fid, - meshname, - MED_NO_DT, - MED_NO_IT, - MED_UNDEF_DT, - MED_CELL, - MED_DESCENDING, - faceIndexSize, - faceindex, - nodeIndexSize, - nodeindex, - connectivity) < 0) { - MESSAGE("ERROR : polyhedron connectivity ..."); - return -1; - } - - /* create family 0 : by default, all mesh entities family number is 0 */ - if (MEDfamilyCr(fid, - meshname, - "", - 0, - 0, - "") < 0) { - MESSAGE("ERROR : quadrangular cells connectivity ..."); - return -1; - } - - /* close MED file */ - if (MEDfileClose(fid) < 0) { - MESSAGE("ERROR : close file ..."); - return -1; - } - - return 0; -} diff --git a/src/Plugins/MEDReader/IO/Testing/Cxx/TestMedParallelRead.cxx b/src/Plugins/MEDReader/IO/Testing/Cxx/TestMedParallelRead.cxx deleted file mode 100644 index a5269ed1..00000000 --- a/src/Plugins/MEDReader/IO/Testing/Cxx/TestMedParallelRead.cxx +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// - -/* - * TestMedParallelRead.cxx - * - * Created on: 20 avr. 2011 - * Author: alejandro - */ - -#define MAX(a,b) ((a) > (b) ? (a) : (b)) - -#define MED_HAVE_MPI - -#include -#define MESGERR 1 -#include "med_utils.h" - -#include -#include -#include - -#if TIME_WITH_SYS_TIME -# include -# include -#else -# if HAVE_SYS_TIME_H -# include -# else -# include -# endif -#endif - -int main (int argc, char **argv) -{ - med_err _ret=0; - med_idt _fid; - - int mpi_size, mpi_rank; - MPI_Comm comm = MPI_COMM_WORLD; - MPI_Info info = MPI_INFO_NULL; - - med_int _nbofentitiesfiltered=0; - med_int *_filterarray=NULL; - - MPI_Init(&argc, &argv); - MPI_Comm_size(MPI_COMM_WORLD, &mpi_size); - MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank); - - med_size _nbblocksperproc = 0; - int _nbofentities = 0; - int _nbofvaluesperentity = 0; - int _nbofconstituentpervalue = 0; - - printf("mpi_size = %03d\n", mpi_size); - - if (mpi_rank == 0 ) { - - struct tm *_tm ; - time_t _tt=time(0); - _tm = localtime(&_tt); - - srandom((*_tm).tm_sec * (*_tm).tm_min ); - _nbblocksperproc = 1 + (int) (mpi_size * (random() / (RAND_MAX + 1.0))); - _nbofentities = 1 + (int) (1000.0 * (random() / (RAND_MAX + 1.0))); - _nbofvaluesperentity = 1 + (int) (11.0 * (random() / (RAND_MAX + 1.0))); - _nbofconstituentpervalue = 1 + (int) (7.0 * (random() / (RAND_MAX + 1.0))); - } - - MPI_Bcast(&_nbblocksperproc , 1, MPI_LONG, 0, MPI_COMM_WORLD); - MPI_Bcast(&_nbofentities , 1, MPI_LONG, 0, MPI_COMM_WORLD); - MPI_Bcast(&_nbofvaluesperentity , 1, MPI_LONG, 0, MPI_COMM_WORLD); - MPI_Bcast(&_nbofconstituentpervalue , 1, MPI_LONG, 0, MPI_COMM_WORLD); - - printf( "NENT-%03d_NVAL-%03d_NCST-%03d_NBL-%03llu\n",_nbofentities,_nbofvaluesperentity, - _nbofconstituentpervalue,_nbblocksperproc); - - char _filename [255]=""; - sprintf(_filename,"/home/alejandro/work/Data-test-Med/tmp/depl.resu.med"); - /* SSCRUTE(_filename); */ - - /* Ouverture du fichier en mode parallel */ - if ((_fid = MEDparFileOpen(_filename, MED_ACC_RDONLY ,comm, info)) < 0){ - MED_ERR_(_ret,MED_ERR_OPEN,MED_ERR_FILE,_filename); - } - - if ( MEDfileClose( _fid ) < 0) { - MED_ERR_(_ret,MED_ERR_CLOSE,MED_ERR_FILE,""); _ret = -1; - } - - /* MPI_Finalize must be called AFTER MEDclose which may use MPI calls */ - MPI_Finalize(); - -} diff --git a/src/Plugins/MEDReader/IO/Testing/Cxx/TestMedParallelWrite.cxx b/src/Plugins/MEDReader/IO/Testing/Cxx/TestMedParallelWrite.cxx deleted file mode 100644 index dba7130b..00000000 --- a/src/Plugins/MEDReader/IO/Testing/Cxx/TestMedParallelWrite.cxx +++ /dev/null @@ -1,343 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// - -/* - * TestMedParallelWrite.cxx - * - * Created on: 11 mai 2011 - * Author: alejandro - */ - -#define MED_HAVE_MPI - -#include -#define MESGERR 1 -#include "med_utils.h" - -#include -#include -#include - -int main (int argc, char **argv) -{ - const char meshname[MED_NAME_SIZE+1] = "2D unstructured mesh"; - const med_int spacedim = 2; - const med_int meshdim = 2; - /* 12345678901234561234567890123456 */ - const char axisname[2*MED_SNAME_SIZE+1] = "x y "; - const char unitname[2*MED_SNAME_SIZE+1] = "cm cm "; - med_float coordinates[2222]; - const med_int nnodes = 1111; - - med_int* quadconnectivity; - const med_int nquad4 = 1000; - - med_err _ret=-1; - - int mpi_size, mpi_rank; - MPI_Comm comm = MPI_COMM_WORLD; - MPI_Info info = MPI_INFO_NULL; - - MPI_Init(&argc, &argv); - MPI_Comm_size(MPI_COMM_WORLD, &mpi_size); - MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank); - - med_idt fid; - char filename[255]="UsesCase_MEDmesh_parallel.med"; - /* SSCRUTE(_filename); */ - - if (mpi_rank == 0 ) { - printf("mpi_size = %03d\n", mpi_size); - - /* Ouverture du fichier en mode non-parallel */ - if ((fid = MEDfileOpen(filename, MED_ACC_CREAT)) < 0){ - MED_ERR_(_ret, MED_ERR_OPEN,MED_ERR_FILE, filename); - } - - /* write a comment in the file */ - if (MEDfileCommentWr(fid,"A 2D unstructured mesh : 15 nodes, 12 cells") < 0) { - MESSAGE("ERROR : write file description ..."); - } - - /* mesh creation : a 2D unstructured mesh */ - if (MEDmeshCr(fid, meshname, spacedim, meshdim, MED_UNSTRUCTURED_MESH, - "A 2D unstructured mesh","",MED_SORT_DTIT,MED_CARTESIAN, axisname, unitname) < 0) { - MESSAGE("ERROR : mesh creation ..."); - } - - /* - * Building the coordinates of a rectangle of 101 points in the Y-axis, - * and 11 in the X-axis - */ - for (int j=0; j<11; j++ ) - for (int i=0; i<101; i++ ) - { - coordinates[j*202+i*2] = j+1; - coordinates[j*202+i*2+1] = i+1; - } - - /* nodes coordinates in a Cartesian axis in full interlace mode - (X1,Y1, X2,Y2, X3,Y3, ...) with no iteration and computation step - */ - if (MEDmeshNodeCoordinateWr(fid, meshname, MED_NO_DT, MED_NO_IT, 0.0, - MED_FULL_INTERLACE, nnodes, coordinates) < 0) { - MESSAGE("ERROR : nodes coordinates ..."); - } - - if ( MEDfileClose( fid ) < 0) { - MED_ERR_(_ret,MED_ERR_CLOSE,MED_ERR_FILE,"");; - } - - MPI_Barrier(comm); - } /* End of process ZERO */ - else - { - MPI_Barrier(comm); - } - - /* Ouverture du fichier en mode parallel */ - if ((fid = MEDparFileOpen(filename, MED_ACC_RDWR ,comm, info)) < 0){ - MED_ERR_(_ret, MED_ERR_OPEN,MED_ERR_FILE, filename); - } - - med_int nbofentity = nquad4; - med_int nbofvaluesperentity = 1; - med_int nbofconstituentpervalue = 4; - med_int constituentselect = MED_ALL_CONSTITUENT; - med_switch_mode switchmode = MED_FULL_INTERLACE; - med_storage_mode storagemode = MED_COMPACT_STMODE; - const char *const profilename = MED_NO_PROFILE; - - /* - * Calculating block sizes - */ - - int block_size = (100/mpi_size)*10; - med_size start = block_size * mpi_rank + 1; - med_size stride = block_size; - med_size count = 1; - med_size blocksize = block_size; - med_size lastblocksize = (100 % mpi_size)*10; - if ((mpi_size == mpi_rank+1) && (lastblocksize != 0)) - { - blocksize += lastblocksize; - stride += lastblocksize; - } - lastblocksize = 0; - - printf("%03d: block_size = %03d\n", mpi_rank, block_size); - printf("%03d: start = %03d\n", mpi_rank, start); - printf("%03d: stride = %03d\n", mpi_rank, stride); - printf("%03d: count = %03d\n", mpi_rank, count); - printf("%03d: blocksize = %03d\n", mpi_rank, blocksize); - printf("%03d: lastblocksize = %03d\n", mpi_rank, lastblocksize); - med_filter filter = MED_FILTER_INIT; - - if ( MEDfilterBlockOfEntityCr( fid, - nbofentity, - nbofvaluesperentity, - nbofconstituentpervalue, - constituentselect, - switchmode, - storagemode, - profilename, - start, - stride, - count, - blocksize, - lastblocksize, - &filter ) < 0 ) - { - MESSAGE("ERROR : filter creation ..."); - } - - // Attention: there is blocksize and block_size and it does not - // represent the same quantity, in case we are in the last - // block they are different, if not it is the same - quadconnectivity = new med_int[blocksize*4]; - int shift = mpi_rank*block_size; - printf("%03d: mpi_rank*block_size = %03d\n", mpi_rank, shift); - printf("%03d: block_size = %03d\n", mpi_rank, block_size); - int base = shift + shift / 101; - int c = 0; - for (int i=0; i block_size * l - 1) && (l < mpi_size)) - { - l++; - } - familynumbers[i] = -l; - } - - if (MEDmeshEntityFamilyNumberWr(fid, meshname, MED_NO_DT, MED_NO_IT, - MED_CELL, MED_QUAD4, nquad4, familynumbers) < 0) { - MESSAGE("ERROR : nodes family numbers ..."); - } - - /* Write a Profile */ - const char profileName[MED_NAME_SIZE+1] = "QUAD4_PROFILE"; - const med_int profilesize = 9; - med_int profilearray[9] = {1, 3, 5, 7, 9, 11, 13, 15, 17}; - if (MEDprofileWr(fid, profileName, profilesize, profilearray ) < 0) { - MESSAGE("ERROR : nodes family numbers ..."); - } - - /* write localization for integration points */ - const char localizationName[MED_NAME_SIZE+1] = "QUAD4_INTEGRATION_POINTS_4"; - const med_float elementcoordinate[6] = {0.0, 0.0, 1.0, 0.0, 0.0,1.0}; - const med_float iPointCoordinate[8] = {1.0/5, 1.0/5, 3.0/5, 1.0/5, 1.0/5, 3.0/5, 1.0/3, 1.0/3}; - const med_float weight[4] = {1.0/8, 1.0/8, 1.0/8, 1.0/8}; - med_int spacedim = 2; - med_int nipoint = 4; - if (MEDlocalizationWr(fid, localizationName, MED_QUAD4, spacedim, - elementcoordinate, MED_FULL_INTERLACE, - nipoint, iPointCoordinate, weight, - MED_NO_INTERPOLATION, MED_NO_MESH_SUPPORT) < 0) { - MESSAGE("ERROR : create family of integration points ..."); - } - - /* Writing a scalar Field on the Quads right here */ - const char fieldname[MED_NAME_SIZE+1] = "TEMPERATURE_FIELD"; - const med_int ncomponent = 1; - const char componentname[MED_SNAME_SIZE+1] = "TEMPERATURE"; - const char componentunit[MED_SNAME_SIZE+1] = "C"; - - if (MEDfieldCr(fid, fieldname, MED_FLOAT64, - ncomponent, componentname, componentunit,"", - meshname) < 0) { - MESSAGE("ERROR : create field"); - } - - /* write values at cell (QUADS) centers */ - med_float quad4values[nquad4]; - for (int i=0; i -#define MESGERR 1 -#include - -#include - -int main (int argc, char **argv) { - med_idt fid; - const char meshname[MED_NAME_SIZE+1] = "3D unstructured mesh"; - const med_int spacedim = 3; - const med_int meshdim = 3; - /* 12345678901234561234567890123456 */ - const char axisname[3*MED_SNAME_SIZE+1] = "x y z "; - const char unitname[3*MED_SNAME_SIZE+1] = "cm cm cm "; - const med_int nnodes = 12; - const med_float coordinates[3 * 12] = - { 1.618, 1., 0., - -1.618, 1., 0., - 1.618, -1., 0., - -1.618, -1., 0., - 1., 0., 1.618, - 1., 0., -1.618, - -1., 0., 1.618, - -1., 0., -1.618, - 0., 1.618, 1., - 0., -1.618, 1., - 0., 0, 0., -// 0., 1.618, -1., - 0., -1.618, -1. }; - const med_int faceIndexSize = 2; - const med_int faceindex[2] = {1,22}; - const med_int nodeIndexSize = 21; - /* connectivity : 1 icosahedron */ - const med_int nodeindex[21] = { 1, 4, 7,10,13,16,19,22,25,28, - 31,34,37,40,43,46,49,52,55,58,61 }; - const med_int connectivity[60] = { 1, 9, 5, - 1, 6, 11, - 3, 5, 10, - 3, 12, 6, - 2, 7, 9, - 2, 11, 8, - 4, 10, 7, - 4, 8, 12, - 1, 11, 9, - 2, 9, 11, - 3, 10, 12, - 4, 10, 12, - 5, 3, 1, - 6, 1, 3, - 7, 2, 4, - 8, 4, 2, - 9, 7, 5, - 10, 5, 7, - 11, 6, 8, - 12, 8, 6 }; - - /* open MED file */ - fid = MEDfileOpen("UsesCase_MEDmesh_15.med", - MED_ACC_CREAT); - if (fid < 0) { - MESSAGE("ERROR : file creation ..."); - return -1; - } - - /* write a comment in the file */ - if (MEDfileCommentWr(fid, - "A 3D unstructured mesh : 1 icosahedron") < 0) { - MESSAGE("ERROR : write file description ..."); - return -1; - } - - /* mesh creation : a 3D unstructured mesh */ - if (MEDmeshCr(fid, - meshname, - spacedim, - meshdim, - MED_UNSTRUCTURED_MESH, - "A 3D mesh with 1 icosahedron", - "", - MED_SORT_DTIT, - MED_CARTESIAN, - axisname, - unitname) < 0) { - MESSAGE("ERROR : mesh creation ..."); - return -1; - } - - /* nodes coordinates in a cartesian axis in full interlace mode - (X1,Y1, X2,Y2, X3,Y3, ...) with no iteration and computation step - */ - if (MEDmeshNodeCoordinateWr(fid, - meshname, - MED_NO_DT, - MED_NO_IT, - MED_UNDEF_DT, - MED_FULL_INTERLACE, - nnodes, - coordinates) < 0) { - MESSAGE("ERROR : nodes coordinates ..."); - return -1; - } - - /* cells connectiviy is defined in nodal mode */ - /* 1 icosahedron */ - if (MEDmeshPolyhedronWr(fid, - meshname, - MED_NO_DT, - MED_NO_IT, - MED_UNDEF_DT, - MED_CELL, - MED_NODAL, - faceIndexSize, - faceindex, - nodeIndexSize, - nodeindex, - connectivity) < 0) { - MESSAGE("ERROR : polyhedron connectivity ..."); - return -1; - } - - /* create family 0 : by default, all mesh entities family number is 0 */ - if (MEDfamilyCr(fid, - meshname, - "", - 0, - 0, - "") < 0) { - MESSAGE("ERROR : quadrangular cells connectivity ..."); - return -1; - } - - /* close MED file */ - if (MEDfileClose(fid) < 0) { - MESSAGE("ERROR : close file ..."); - return -1; - } - - return 0; -} diff --git a/src/Plugins/MEDReader/IO/Testing/Cxx/TestMedReadDescendingPolyhedron.cxx b/src/Plugins/MEDReader/IO/Testing/Cxx/TestMedReadDescendingPolyhedron.cxx deleted file mode 100644 index 1c2aa175..00000000 --- a/src/Plugins/MEDReader/IO/Testing/Cxx/TestMedReadDescendingPolyhedron.cxx +++ /dev/null @@ -1,234 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// - -/* - * TestMedReadDescendingPolyhedron.cxx - * - * Created on: 3 mars 2011 - * Author: alejandro - */ - -#include -#define MESGERR 1 -#include - -#include - -int main (int argc, char **argv) { - med_idt fid; - const char meshname[MED_NAME_SIZE+1] = "3D unstructured mesh"; - char meshdescription[MED_COMMENT_SIZE+1]; - med_int meshdim; - med_int spacedim; - med_sorting_type sortingtype; - med_int nstep; - med_mesh_type meshtype; - med_axis_type axistype; - char axisname[3*MED_SNAME_SIZE+1]; - char unitname[3*MED_SNAME_SIZE+1]; - char dtunit[MED_SNAME_SIZE+1]; - med_float *coordinates = NULL; - med_int nnodes = 0; - med_int npoly = 0; - med_int indexsize; - med_int faceIndexSize; - med_int *index = NULL; - med_int *faceindex = NULL; - med_int *connectivity = NULL; - med_int connectivitysize; - med_int *triaconnectivity = NULL; - med_int ntria3 = 0; - med_bool coordinatechangement; - med_bool geotransformation; - int i; - int k,ind1,ind2; - int j,jind1,jind2; - - /* open MED file with READ ONLY access mode */ - fid = MEDfileOpen("./UsesCase_MEDmesh_17.med",MED_ACC_RDONLY); - if (fid < 0) { - MESSAGE("ERROR : open file in READ ONLY ACCESS mode ..."); - return -1; - } - - /* - * ... we know that the MED file has only one mesh, - * a real code working would check ... - */ - - /* read mesh informations : mesh dimension, space dimension ... */ - if (MEDmeshInfoByName(fid, meshname, &spacedim, &meshdim, &meshtype, meshdescription, - dtunit, &sortingtype, &nstep, &axistype, axisname, unitname) < 0) { - MESSAGE("ERROR : mesh info ..."); - return -1; - } - - /* read how many nodes in the mesh */ - if ((nnodes = MEDmeshnEntity(fid, meshname, MED_NO_DT, MED_NO_IT, MED_NODE, MED_POINT1, - MED_COORDINATE, MED_NO_CMODE,&coordinatechangement, - &geotransformation)) < 0) { - MESSAGE("ERROR : number of nodes ..."); - return -1; - } - - /* read how many triangular cells in the mesh */ - if ((ntria3 = MEDmeshnEntity(fid, meshname, MED_NO_DT, MED_NO_IT, MED_DESCENDING_FACE,MED_TRIA3, - MED_CONNECTIVITY, MED_NODAL,&coordinatechangement, - &geotransformation)) < 0) { - MESSAGE("ERROR : number of MED_TRIA3 ..."); - return -1; - } - ISCRUTE(ntria3); - - /* read cells connectivity in the mesh */ - if ((triaconnectivity = (med_int *) malloc(sizeof(med_int)*ntria3*3)) == NULL) { - MESSAGE("ERROR : memory allocation ..."); - return -1; - } - if (MEDmeshElementConnectivityRd(fid, meshname, MED_NO_DT, MED_NO_IT, MED_DESCENDING_FACE, - MED_TRIA3, MED_NODAL, MED_FULL_INTERLACE, triaconnectivity) < 0) { - MESSAGE("ERROR : MED_TRIA3 connectivity ..."); - return -1; - } - for (i=0;i> MED_POLYHEDRON "IFORMAT" : \n",i+1); - printf("---- Face Index ----- : [ "); - ind1 = *(index+i)-1; - ind2 = *(index+i+1)-1; - for (k=ind1;k -#define MESGERR 1 -#include - -#include - -int main (int argc, char **argv) { - med_idt fid; - const char meshname[MED_NAME_SIZE+1] = "3D unstructured mesh"; - char meshdescription[MED_COMMENT_SIZE+1]; - med_int meshdim; - med_int spacedim; - med_sorting_type sortingtype; - med_int nstep; - med_mesh_type meshtype; - med_axis_type axistype; - char axisname[3*MED_SNAME_SIZE+1]; - char unitname[3*MED_SNAME_SIZE+1]; - char dtunit[MED_SNAME_SIZE+1]; - med_float *coordinates = NULL; - med_int nnodes = 0; - med_int npoly = 0; - med_int indexsize; - med_int faceIndexSize; - med_int *index = NULL; - med_int *faceindex = NULL; - med_int *connectivity = NULL; - med_int connectivitysize; - med_bool coordinatechangement; - med_bool geotransformation; - int i; - int k,ind1,ind2; - int j, jind1,jind2; - - /* open MED file with READ ONLY access mode */ - fid = MEDfileOpen("./UsesCase_MEDmesh_15.med",MED_ACC_RDONLY); - if (fid < 0) { - MESSAGE("ERROR : open file in READ ONLY ACCESS mode ..."); - return -1; - } - - /* - * ... we know that the MED file has only one mesh, - * a real code working would check ... - */ - - /* read mesh informations : mesh dimension, space dimension ... */ - if (MEDmeshInfoByName(fid, meshname, &spacedim, &meshdim, &meshtype, meshdescription, - dtunit, &sortingtype, &nstep, &axistype, axisname, unitname) < 0) { - MESSAGE("ERROR : mesh info ..."); - return -1; - } - - /* read how many nodes in the mesh */ - if ((nnodes = MEDmeshnEntity(fid, meshname, MED_NO_DT, MED_NO_IT, MED_NODE, MED_POINT1, - MED_COORDINATE, MED_NO_CMODE,&coordinatechangement, - &geotransformation)) < 0) { - MESSAGE("ERROR : number of nodes ..."); - return -1; - } - - /* - * ... we know that we only have MED_POLYHEDRON cells in the mesh, - * a real code working would check all MED geometry cell types ... - */ - - /* How many polygon in the mesh in nodal connectivity mode */ - /* For the polygons, we get the size of array index */ - if ((indexsize = MEDmeshnEntity(fid,meshname,MED_NO_DT,MED_NO_IT, - MED_CELL,MED_POLYHEDRON,MED_INDEX_FACE,MED_NODAL, - &coordinatechangement, - &geotransformation)) < 0) { - MESSAGE("ERROR : read number of polyedron ..."); - return -1; - } - npoly = indexsize-1; - ISCRUTE(npoly); - - if ((faceIndexSize = MEDmeshnEntity(fid,meshname,MED_NO_DT,MED_NO_IT, - MED_CELL,MED_POLYHEDRON,MED_INDEX_NODE,MED_NODAL, - &coordinatechangement, - &geotransformation)) < 0) { - MESSAGE("ERROR : read number of polyedron ..."); - return -1; - } - ISCRUTE(faceIndexSize); - - /* how many nodes for the polyhedron connectivity ? */ - if ((connectivitysize = MEDmeshnEntity(fid,meshname,MED_NO_DT,MED_NO_IT, - MED_CELL,MED_POLYHEDRON,MED_CONNECTIVITY,MED_NODAL, - &coordinatechangement, - &geotransformation)) < 0) { - MESSAGE("ERROR : read connevity size ..."); - return -1; - } - ISCRUTE(connectivitysize); - - /* read mesh nodes coordinates */ - if ((coordinates = (med_float*) malloc(sizeof(med_float)*nnodes*spacedim)) == NULL) { - MESSAGE("ERROR : memory allocation ..."); - return -1; - } - - if (MEDmeshNodeCoordinateRd(fid, meshname, MED_NO_DT, MED_NO_IT, MED_FULL_INTERLACE, - coordinates) < 0) { - MESSAGE("ERROR : nodes coordinates ..."); - return -1; - } - for (i=0;i> MED_POLYHEDRON "IFORMAT" : \n",i+1); - printf("---- Face Index ----- : [ "); - ind1 = *(index+i)-1; - ind2 = *(index+i+1)-1; - for (k=ind1;kSetFileName(argv[1]); - reader->Update(); - - vtkCompositePolyDataMapper *mapper = vtkCompositePolyDataMapper::New(); - mapper->SetInputConnection(reader->GetOutputPort()); - - vtkActor *actor = vtkActor::New(); - actor->SetMapper(mapper); - - vtkRenderer *renderer = vtkRenderer::New(); - renderer->AddActor(actor); - renderer->SetBackground(0.5, 0.5, 0.5); - - vtkRenderWindow *renWin = vtkRenderWindow::New(); - renWin->AddRenderer(renderer); - - vtkRenderWindowInteractor *interactor = vtkRenderWindowInteractor::New(); - interactor->SetRenderWindow(renWin); - - renWin->SetSize(400,400); - renWin->Render(); - interactor->Initialize(); - renderer->ResetCamera(); - renWin->Render(); - renderer->ResetCamera(); - - int retVal = vtkRegressionTestImageThreshold(renWin,18); - if( retVal == vtkRegressionTester::DO_INTERACTOR) - { - interactor->Start(); - } - - reader->Delete(); - mapper->Delete(); - actor->Delete(); - renderer->Delete(); - renWin->Delete(); - interactor->Delete(); - - return !retVal; -} diff --git a/src/Plugins/MEDReader/IO/Testing/Cxx/TestMedWriteOcta12.cxx b/src/Plugins/MEDReader/IO/Testing/Cxx/TestMedWriteOcta12.cxx deleted file mode 100644 index 434f66f1..00000000 --- a/src/Plugins/MEDReader/IO/Testing/Cxx/TestMedWriteOcta12.cxx +++ /dev/null @@ -1,149 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// - -/* - * TestMedWriteOcta12.cxx - * - * Created on: 17 mars 2011 - * Author: alejandro - */ - -#include -#define MESGERR 1 -#include - -#include - -int main (int argc, char **argv) { - med_idt fid; - const char meshname[MED_NAME_SIZE+1] = "3D unstructured mesh"; - const med_int spacedim = 3; - const med_int meshdim = 3; - /* 12345678901234561234567890123456 */ - const char axisname[3*MED_SNAME_SIZE+1] = "x y z "; - const char unitname[3*MED_SNAME_SIZE+1] = "cm cm cm "; - const med_int nnodes = 20; - const med_float coordinates[3 * 20] = - { 0., 0., 1., - 1., 0., 1., - 1.5, 1., 1., - 1., 2., 1., - 0., 2., 1., - -0.5, 1., 1., - 0., 0., 0., - 1., 0., 0., - 1.5, 1., 0., - 1., 2., 0., - 0., 2., 0., - -0.5, 1., 0., - 2.5, 1., 1., - 3., 2., 1., - 2.5, 2.5, 1., - 1.5, 2.5, 1., - 2.5, 1., 0., - 3., 2., 0., - 2.5, 2.5, 0., - 1.5, 2.5, 0. }; - - const med_int nOcta = 2; - const med_int octa12Connectivity[12*2] = - { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, - 13, 14, 15, 16, 4, 3, 17, 18, 19, 20, 10, 9 }; - - /* open MED file */ - fid = MEDfileOpen("UsesCase_MEDmesh_19.med", - MED_ACC_CREAT); - if (fid < 0) { - MESSAGE("ERROR : file creation ..."); - return -1; - } - - /* write a comment in the file */ - if (MEDfileCommentWr(fid, - "A 3D unstructured mesh : 2 Hexagonal Prisms") < 0) { - MESSAGE("ERROR : write file description ..."); - return -1; - } - - /* mesh creation : a 3D unstructured mesh */ - if (MEDmeshCr(fid, - meshname, - spacedim, - meshdim, - MED_UNSTRUCTURED_MESH, - "A 3D mesh with 1 hexagonal in NODAL connectivity", - "", - MED_SORT_DTIT, - MED_CARTESIAN, - axisname, - unitname) < 0) { - MESSAGE("ERROR : mesh creation ..."); - return -1; - } - - /* nodes coordinates in a cartesian axis in full interlace mode - (X1,Y1, X2,Y2, X3,Y3, ...) with no iteration and computation step - */ - if (MEDmeshNodeCoordinateWr(fid, - meshname, - MED_NO_DT, - MED_NO_IT, - MED_UNDEF_DT, - MED_FULL_INTERLACE, - nnodes, - coordinates) < 0) { - MESSAGE("ERROR : nodes coordinates ..."); - return -1; - } - - // cells connectiviy is defined in nodal mode - if (MEDmeshElementConnectivityWr(fid, - meshname, - MED_NO_DT, - MED_NO_IT, - 0.0, - MED_CELL, - MED_OCTA12, - MED_NODAL, - MED_FULL_INTERLACE, - nOcta, - octa12Connectivity) < 0) { - MESSAGE("ERROR : triangular cells connectivity ..."); - return -1; - } - - /* create family 0 : by default, all mesh entities family number is 0 */ - if (MEDfamilyCr(fid, - meshname, - "", - 0, - 0, - "") < 0) { - MESSAGE("ERROR : quadrangular cells connectivity ..."); - return -1; - } - - /* close MED file */ - if (MEDfileClose(fid) < 0) { - MESSAGE("ERROR : close file ..."); - return -1; - } - - return 0; -} diff --git a/src/Plugins/MEDReader/IO/Testing/Cxx/TestReading0.cxx b/src/Plugins/MEDReader/IO/Testing/Cxx/TestReading0.cxx deleted file mode 100644 index ee45875d..00000000 --- a/src/Plugins/MEDReader/IO/Testing/Cxx/TestReading0.cxx +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Anthony Geay - -int main(int argc, char *argv[]) -{ - return 0; -} diff --git a/src/Plugins/MEDReader/IO/config.h.cmake b/src/Plugins/MEDReader/IO/config.h.cmake deleted file mode 100644 index 138b4918..00000000 --- a/src/Plugins/MEDReader/IO/config.h.cmake +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// - - #ifndef __CONFIG_H__ - #define __CONFIG_H__ - - #cmakedefine MedReader_BUILD_PARALLEL - - #endif // __CONFIG_H__ diff --git a/src/Plugins/MEDReader/IO/vtkELNOFilter.cxx b/src/Plugins/MEDReader/IO/vtkELNOFilter.cxx deleted file mode 100644 index dc756b8b..00000000 --- a/src/Plugins/MEDReader/IO/vtkELNOFilter.cxx +++ /dev/null @@ -1,205 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// - -#include "vtkELNOFilter.h" -#include "vtkInformation.h" -#include "vtkInformationVector.h" -#include "vtkObjectFactory.h" -#include "vtkPolyDataAlgorithm.h" -#include "vtkPolyData.h" -#include "vtkIdTypeArray.h" -#include "vtkFieldData.h" -#include "vtkCellData.h" -#include "vtkPointData.h" -#include "vtkCell.h" -#include "vtkInformationQuadratureSchemeDefinitionVectorKey.h" -#include "vtkQuadratureSchemeDefinition.h" -#include "vtkUnstructuredGrid.h" - -#include "MEDUtilities.hxx" -#include "InterpKernelAutoPtr.hxx" - -//vtkCxxRevisionMacro(vtkELNOFilter, "$Revision: 1.2.2.2 $"); -vtkStandardNewMacro(vtkELNOFilter); - -vtkELNOFilter::vtkELNOFilter() -{ - this->ShrinkFactor = 0.5; -} - -vtkELNOFilter::~vtkELNOFilter() -{ -} - -int vtkELNOFilter::RequestData(vtkInformation *request, vtkInformationVector **input, vtkInformationVector *output) -{ - vtkUnstructuredGrid *usgIn(vtkUnstructuredGrid::SafeDownCast( input[0]->GetInformationObject(0)->Get(vtkDataObject::DATA_OBJECT()))); - vtkPolyData *pdOut(vtkPolyData::SafeDownCast(output->GetInformationObject(0)->Get(vtkDataObject::DATA_OBJECT()))); - - vtkDataArray *array(this->GetInputArrayToProcess(0, input)); - vtkIdTypeArray* offsets(vtkIdTypeArray::SafeDownCast(this->GetInputArrayToProcess(0, input))); - - if(usgIn == NULL || offsets == NULL || pdOut == NULL) - { - vtkDebugMacro("vtkELNOFilter no correctly configured : offsets = " << offsets); - return 1; - } - - vtkInformation *info(offsets->GetInformation()); - vtkInformationQuadratureSchemeDefinitionVectorKey *key(vtkQuadratureSchemeDefinition::DICTIONARY()); - if(!key->Has(info)) - { - vtkDebugMacro("Dictionary is not present in array " << offsets->GetName() << " " << offsets << " Aborting." ); - return 1; - } - - int res(this->Superclass::RequestData(request, input, output)); - if(res == 0) - return 0; - - int dictSize(key->Size(info)); - vtkQuadratureSchemeDefinition **dict = new vtkQuadratureSchemeDefinition *[dictSize]; - key->GetRange(info, dict, 0, 0, dictSize); - - vtkIdType ncell(usgIn->GetNumberOfCells()); - vtkPoints *points(pdOut->GetPoints()); - vtkIdType start(0); - for(vtkIdType cellId = 0; cellId < ncell; cellId++) - { - vtkIdType offset(offsets->GetValue(cellId)); - int cellType(usgIn->GetCellType(cellId)); - // a simple check to see if a scheme really exists for this cell type. - // should not happen if the cell type has not been modified. - if(dict[cellType] == NULL) - continue; - int np = dict[cellType]->GetNumberOfQuadraturePoints(); - double center[3] = {0, 0, 0}; - for(int id = start; id < start + np; id++) - { - double *position = points->GetPoint(id); - center[0] += position[0]; - center[1] += position[1]; - center[2] += position[2]; - } - center[0] /= np; - center[1] /= np; - center[2] /= np; - for(int id = start; id < start + np; id++) - { - double *position = points->GetPoint(id); - double newpos[3]; - newpos[0] = position[0] * this->ShrinkFactor + center[0] * (1 - this->ShrinkFactor); - newpos[1] = position[1] * this->ShrinkFactor + center[1] * (1 - this->ShrinkFactor); - newpos[2] = position[2] * this->ShrinkFactor + center[2] * (1 - this->ShrinkFactor); - points->SetPoint(id, newpos); - } - start += np; - } - //// bug EDF 8407 PARAVIS - mantis 22610 - vtkFieldData *fielddata(usgIn->GetFieldData()); - for(int index=0;indexGetNumberOfArrays();index++) - { - vtkDataArray *data(fielddata->GetArray(index)); - vtkInformation *info(data->GetInformation()); - const char *arrayOffsetName(info->Get(vtkQuadratureSchemeDefinition::QUADRATURE_OFFSET_ARRAY_NAME())); - vtkIdTypeArray *offData(0); - bool isELNO(false); - if(arrayOffsetName) - { - vtkCellData *cellData(usgIn->GetCellData()); - vtkDataArray *offDataTmp(cellData->GetArray(arrayOffsetName)); - isELNO=offDataTmp->GetInformation()->Get(MEDUtilities::ELNO())==1; - offData=dynamic_cast(offDataTmp); - } - if(isELNO && offData) - { - vtkIdType nbCellsInput(usgIn->GetNumberOfCells()); - if(nbCellsInput==0) - continue ;//no cells -> no fields - // First trying to detected if we are in the special case where data can be used directly. To detect that look at offData. If offData.front()==0 && offData->back()+NbOfNodesInLastCell==data->GetNumberOfTuples() OK. - vtkCell *cell(usgIn->GetCell(nbCellsInput-1)); - bool statement0(offData->GetTuple1(0)==0); - bool statement1(offData->GetTuple1(nbCellsInput-1)+cell->GetNumberOfPoints()==data->GetNumberOfTuples()); - if(statement0 && statement1) - pdOut->GetPointData()->AddArray(data);//We are lucky ! No extraction needed. - else - {//not lucky ! Extract values from data. A previous threshold has been done... Bug EDF8662 - vtkDataArray *newArray(data->NewInstance()); - newArray->SetName(data->GetName()); - pdOut->GetPointData()->AddArray(newArray); - newArray->SetNumberOfComponents(data->GetNumberOfComponents()); - newArray->SetNumberOfTuples(pdOut->GetNumberOfPoints()); - newArray->CopyComponentNames(data); - newArray->Delete(); - vtkIdType *offsetPtr(offData->GetPointer(0)); - vtkIdType zeId(0); - for(vtkIdType cellId=0;cellIdGetCell(cellId)); - vtkIdType nbPoints(cell->GetNumberOfPoints()),offset(offsetPtr[cellId]); - for(vtkIdType j=0;jSetTuple(zeId,offsetPtr[cellId]+j,data); - } - } - } - } - AttachCellFieldsOn(usgIn,pdOut->GetCellData(),pdOut->GetNumberOfCells()); - return 1; -} - -void vtkELNOFilter::PrintSelf(ostream& os, vtkIndent indent) -{ - this->Superclass::PrintSelf(os, indent); - os << indent << "ShrinkFactor : " << this->ShrinkFactor << endl; -} - -/*! - * This method attach fields on cell of \a inGrid and add it as a point data in \a outData. - */ -void vtkELNOFilter::AttachCellFieldsOn(vtkUnstructuredGrid *inGrid, vtkCellData *outData, int nbCellsOut) -{ - vtkCellData *cd(inGrid->GetCellData()); - int nbOfArrays(cd->GetNumberOfArrays()); - vtkIdType nbCells(inGrid->GetNumberOfCells()); - if(nbOfArrays==0) - return ; - INTERP_KERNEL::AutoPtr tmpPtr(new vtkIdType[nbCells]); - for(vtkIdType cellId=0;cellIdGetCell(cellId)); - tmpPtr[cellId]=cell->GetNumberOfPoints(); - } - for(int index=0;indexGetArray(index)); - vtkDataArray *newArray(data->NewInstance()); - newArray->SetName(data->GetName()); - outData->AddArray(newArray); - newArray->SetNumberOfComponents(data->GetNumberOfComponents()); - newArray->SetNumberOfTuples(nbCellsOut); - newArray->CopyComponentNames(data); - newArray->Delete(); - vtkIdType offset(0); - for(vtkIdType cellId=0;cellIdSetTuple(offset,cellId,data); - } - } -} diff --git a/src/Plugins/MEDReader/IO/vtkELNOFilter.h b/src/Plugins/MEDReader/IO/vtkELNOFilter.h deleted file mode 100644 index 01138027..00000000 --- a/src/Plugins/MEDReader/IO/vtkELNOFilter.h +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// - -#ifndef _vtkELNOFilter_h -#define _vtkELNOFilter_h - -#include "vtkQuadraturePointsGenerator.h" - -class VTK_EXPORT vtkELNOFilter: public vtkQuadraturePointsGenerator -{ -public: - static vtkELNOFilter *New(); - vtkTypeMacro(vtkELNOFilter,vtkQuadraturePointsGenerator); - void PrintSelf(ostream& os, vtkIndent indent); - - // Description : - // This is the factor applied to shrink the cell before extracting - // the ELNO points. - // A value of 0 shrinks the cells to their center, and a value of 1 - // do not shrink the cell at all. - // default value 0.5 - vtkSetMacro(ShrinkFactor,double); - vtkGetMacro(ShrinkFactor,double); - -protected: - vtkELNOFilter(); - ~vtkELNOFilter(); - - int RequestData(vtkInformation *, vtkInformationVector **, vtkInformationVector *); - void AttachCellFieldsOn(vtkUnstructuredGrid *, vtkCellData *, int); - double ShrinkFactor; - -private: - vtkELNOFilter(const vtkELNOFilter&); - void operator =(const vtkELNOFilter&); -}; -#endif diff --git a/src/Plugins/MEDReader/IO/vtkELNOMeshFilter.cxx b/src/Plugins/MEDReader/IO/vtkELNOMeshFilter.cxx deleted file mode 100644 index c7d3798e..00000000 --- a/src/Plugins/MEDReader/IO/vtkELNOMeshFilter.cxx +++ /dev/null @@ -1,212 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// - -#include "vtkELNOMeshFilter.h" -#include "vtkInformation.h" -#include "vtkInformationVector.h" -#include "vtkInformationIntegerKey.h" -#include "vtkObjectFactory.h" -#include "vtkPolyDataAlgorithm.h" -#include "vtkPolyData.h" -#include "vtkIdTypeArray.h" -#include "vtkQuadratureSchemeDefinition.h" -#include "vtkInformationQuadratureSchemeDefinitionVectorKey.h" -#include "vtkUnstructuredGrid.h" -#include "vtkShrinkFilter.h" -#include "vtkSmartPointer.h" -#include "vtkPointData.h" -#include "vtkCellData.h" -#include "vtkIdList.h" -#include "vtkCell.h" - -#include "MEDUtilities.hxx" - -#include - -vtkStandardNewMacro(vtkELNOMeshFilter); - -vtkELNOMeshFilter::vtkELNOMeshFilter():ShrinkFactor(0.9999) -{ -} - -vtkELNOMeshFilter::~vtkELNOMeshFilter() -{ -} - -int vtkELNOMeshFilter::RequestData(vtkInformation *request, - vtkInformationVector **input, vtkInformationVector *output) -{ - vtkUnstructuredGrid *usgIn = vtkUnstructuredGrid::SafeDownCast( - input[0]->GetInformationObject(0)->Get(vtkDataObject::DATA_OBJECT())); - - vtkUnstructuredGrid *usgOut = vtkUnstructuredGrid::SafeDownCast( - output->GetInformationObject(0)->Get(vtkDataObject::DATA_OBJECT())); - - if(usgIn == NULL || usgOut == NULL) - { - vtkDebugMacro("vtkELNOMeshFilter not correctly configured : Invalid input or output !"); - return 0; - } - - // creates offsets array - - // first shrink the input - vtkUnstructuredGrid* usgInClone = usgIn->NewInstance(); - usgInClone->ShallowCopy(usgIn); - vtkSmartPointer shrink(vtkSmartPointer::New()); - shrink->SetInputData(usgInClone); - shrink->SetShrinkFactor(this->ShrinkFactor); - shrink->Update(); - vtkUnstructuredGrid *shrinked(shrink->GetOutput()); - usgInClone->Delete(); - usgOut->ShallowCopy(shrinked); - // OK for the output - - // now copy ELNO data. Start by verifying if it is possible to - // shallow copy the array. - vtkInformation *info(usgIn->GetInformation()); - // - vtkIdType nVerts(shrinked->GetNumberOfPoints()),ncell(usgIn->GetNumberOfCells()); - // first loop through all cells to check if a shallow copy is possible - bool shallowok(true);// Anthony : checks that shrink works well. Really necessary ? - vtkIdType previous(0),offset(0); - - for(vtkIdType cellId = 0; cellId < ncell; cellId++) - { - if(offset != previous) - { - shallowok = false; - break; - } - vtkCell *cell(usgIn->GetCell(cellId)); - vtkIdType nbptsInCell(cell->GetNumberOfPoints()); - previous = offset + nbptsInCell; - // - offset += nbptsInCell ; - } - // - if(shallowok) - shallowok = (previous == nVerts); - - vtkFieldData *fielddata(usgIn->GetFieldData()); - for(int index = 0; index < fielddata->GetNumberOfArrays(); index++) - { - vtkDataArray *data(fielddata->GetArray(index)); - vtkQuadratureSchemeDefinition **dict = 0; - vtkInformationQuadratureSchemeDefinitionVectorKey *key(vtkQuadratureSchemeDefinition::DICTIONARY()); - if(key->Has(data->GetInformation())) - { - int dictSize(key->Size(data->GetInformation())); - dict=new vtkQuadratureSchemeDefinition *[dictSize]; - key->GetRange(data->GetInformation(),dict,0,0,dictSize); - } - if(data == NULL) - { - delete [] dict; - continue; - } - - vtkInformation *info(data->GetInformation()); - const char *arrayOffsetName(info->Get(vtkQuadratureSchemeDefinition::QUADRATURE_OFFSET_ARRAY_NAME())); - vtkIdTypeArray *offData(0); - bool isELGA(false),isELNO(false); - - if(arrayOffsetName) - { - vtkFieldData *cellData(usgIn->GetCellData()); - vtkDataArray *offDataTmp(cellData->GetArray(arrayOffsetName)); - isELGA=offDataTmp->GetInformation()->Get(MEDUtilities::ELGA())==1; - isELNO=offDataTmp->GetInformation()->Get(MEDUtilities::ELNO())==1; - offData=dynamic_cast(offDataTmp); - } - - if(arrayOffsetName == NULL || isELGA) - { - if(shallowok && data->GetNumberOfTuples()==nVerts )// Anthony : is it not a little confusing to assign a FieldData on Points because the number of tuples fits the number of nodes of shrinked mesh ? - usgOut->GetPointData()->AddArray(data); - else - shrinked->GetFieldData()->AddArray(data); - delete [] dict; - continue; - } - else - { - vtkDataArray *newArray(data->NewInstance()); - newArray->SetName(data->GetName()); - usgOut->GetPointData()->AddArray(newArray); - newArray->SetNumberOfComponents(data->GetNumberOfComponents()); - newArray->SetNumberOfTuples(usgOut->GetNumberOfPoints()); - newArray->CopyComponentNames(data); - newArray->Delete(); - if(isELGA) - { - vtkIdList *ids(vtkIdList::New()); - vtkIdType offset(0); - for(vtkIdType cellId=0;cellIdGetCellType(cellId)); - shrinked->GetCellPoints(cellId, ids); - for(int id = 0; id < dict[cellType]->GetNumberOfQuadraturePoints(); id++) - { - const double * w = dict[cellType]->GetShapeFunctionWeights(id); - int j; - for(j = 0; j < dict[cellType]->GetNumberOfNodes(); j++) - { - if(w[j] == 1.0) - break; - } - if(j == dict[cellType]->GetNumberOfNodes()) - { - j = id; - } - newArray->SetTuple(ids->GetId(id), offset + j, data); - } - vtkCell *cell(usgIn->GetCell(cellId)); - vtkIdType nbptsInCell(cell->GetNumberOfPoints()); - offset+=nbptsInCell; - } - ids->FastDelete(); - } - else if(offData && isELNO) - { - vtkIdType *offsetPtr(offData->GetPointer(0)); - vtkIdType zeId(0); - for(vtkIdType cellId=0;cellIdGetCell(cellId)); - vtkIdType nbPoints(cell->GetNumberOfPoints()),offset(offsetPtr[cellId]); - for(vtkIdType j=0;jSetTuple(zeId,offsetPtr[cellId]+j,data); - } - } - else - { - delete [] dict; - continue ; - } - } - delete [] dict; - } - return 1; -} - -void vtkELNOMeshFilter::PrintSelf(ostream& os, vtkIndent indent) -{ - this->Superclass::PrintSelf(os, indent); -} diff --git a/src/Plugins/MEDReader/IO/vtkELNOMeshFilter.h b/src/Plugins/MEDReader/IO/vtkELNOMeshFilter.h deleted file mode 100644 index f0045c3a..00000000 --- a/src/Plugins/MEDReader/IO/vtkELNOMeshFilter.h +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// - -#ifndef _vtkELNOMeshFilter_h -#define _vtkELNOMeshFilter_h - -#include "vtkUnstructuredGridAlgorithm.h" - -class VTK_EXPORT vtkELNOMeshFilter: public vtkUnstructuredGridAlgorithm -{ -public: - static vtkELNOMeshFilter *New(); - vtkTypeMacro(vtkELNOMeshFilter,vtkUnstructuredGridAlgorithm); - void PrintSelf(ostream& os, vtkIndent indent); - - vtkGetMacro(ShrinkFactor, double); - vtkSetMacro(ShrinkFactor, double); -protected: - vtkELNOMeshFilter(); - ~vtkELNOMeshFilter(); - - int RequestData(vtkInformation *, vtkInformationVector **, - vtkInformationVector *); -private: - vtkELNOMeshFilter(const vtkELNOMeshFilter&); - void operator =(const vtkELNOMeshFilter&); -private: - double ShrinkFactor; -}; -#endif diff --git a/src/Plugins/MEDReader/IO/vtkELNOSurfaceFilter.cxx b/src/Plugins/MEDReader/IO/vtkELNOSurfaceFilter.cxx deleted file mode 100644 index c5c92516..00000000 --- a/src/Plugins/MEDReader/IO/vtkELNOSurfaceFilter.cxx +++ /dev/null @@ -1,222 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// - -#include "vtkELNOSurfaceFilter.h" -#include "vtkInformation.h" -#include "vtkInformationVector.h" -#include "vtkObjectFactory.h" -#include "vtkPolyDataAlgorithm.h" -#include "vtkPolyData.h" -#include "vtkIdTypeArray.h" -#include "vtkInformationQuadratureSchemeDefinitionVectorKey.h" -#include "vtkQuadratureSchemeDefinition.h" -#include "vtkUnstructuredGrid.h" -#include "vtkPVGeometryFilter.h" -#include "vtkShrinkFilter.h" -#include "vtkSmartPointer.h" -#include "vtkPointData.h" -#include "vtkCellData.h" -#include "vtkIdList.h" - -//vtkCxxRevisionMacro(vtkELNOSurfaceFilter, "$Revision$") -//; -vtkStandardNewMacro(vtkELNOSurfaceFilter) -; - -vtkELNOSurfaceFilter::vtkELNOSurfaceFilter() -{ -} - -vtkELNOSurfaceFilter::~vtkELNOSurfaceFilter() -{ -} - -int vtkELNOSurfaceFilter::RequestData(vtkInformation *request, vtkInformationVector **input, vtkInformationVector *output) -{ - vtkUnstructuredGrid *usgIn=vtkUnstructuredGrid::SafeDownCast( - input[0]->GetInformationObject(0)->Get(vtkDataObject::DATA_OBJECT())); - - vtkUnstructuredGrid *usgOut=vtkUnstructuredGrid::SafeDownCast( - output->GetInformationObject(0)->Get(vtkDataObject::DATA_OBJECT())); - - vtkIdTypeArray* usg_offsets=vtkIdTypeArray::SafeDownCast( - this->GetInputArrayToProcess(0, input)); - - if(usgIn==NULL||usg_offsets==NULL||usgOut==NULL) - { - vtkDebugMacro("vtkELNOSurfaceFilter no correctly configured : offsets = " << usg_offsets); - return 1; - } - - // first shrink the input - vtkUnstructuredGrid* usgInClone=usgIn->NewInstance(); - - usgInClone->ShallowCopy(usgIn); - - vtkSmartPointer geomFilter=vtkSmartPointer< - vtkPVGeometryFilter>::New(); - geomFilter->SetInputData(usgInClone); - geomFilter->SetPassThroughCellIds(1); - geomFilter->SetPassThroughPointIds(1); - geomFilter->SetUseOutline(0); - geomFilter->Update(); - - vtkPolyData* surface=vtkPolyData::SafeDownCast(geomFilter->GetOutput()); - vtkIdTypeArray* originalCellIds=vtkIdTypeArray::SafeDownCast( - surface->GetCellData()->GetArray("vtkOriginalCellIds")); - vtkIdTypeArray* originalPointIds=vtkIdTypeArray::SafeDownCast( - surface->GetPointData()->GetArray("vtkOriginalPointIds")); - - if( originalCellIds == NULL ) - { - vtkErrorMacro("vtkPVGeometryFilter return NULL 'vtkOriginalCellIds' array"); - return 0; - } - - if(originalPointIds==NULL) - { - vtkErrorMacro("It appears that your dataset is not reduced using vtkPVGeometryFilter (NULL 'vtkOriginalPointIds).\n==================================================================================================\nProbably your dataset is not 3D.\nIf it is not a 3D dataset you are expected to use ELNO Mesh filter instead of ELNO Surface filter.\n==================================================================================================\n"); - return 0; - } - - vtkSmartPointer shrink= - vtkSmartPointer::New(); - shrink->SetInputConnection(geomFilter->GetOutputPort(0)); - shrink->SetShrinkFactor(0.9999); - shrink->Update(); - - vtkUnstructuredGrid* shrinked=shrink->GetOutput(); - - usgInClone->Delete(); - - usgOut->ShallowCopy(shrinked); - - vtkIdTypeArray* offsets=vtkIdTypeArray::SafeDownCast( - shrinked->GetCellData()->GetArray(usg_offsets->GetName())); - - // now copy ELNO data. Start by verifying if it is possible to - // shallow copy the array. - vtkInformation *info=offsets->GetInformation(); - vtkInformationQuadratureSchemeDefinitionVectorKey *key= - vtkQuadratureSchemeDefinition::DICTIONARY(); - if(!key->Has(info)) - { - vtkDebugMacro("Dictionary is not present in array " << offsets->GetName() - << " " << offsets << " Aborting." ); - return 0; - } - int dictSize=key->Size(info); - vtkQuadratureSchemeDefinition **dict= - new vtkQuadratureSchemeDefinition *[dictSize]; - key->GetRange(info, dict, 0, 0, dictSize); - - vtkIdType ncell=shrinked->GetNumberOfCells(); - - vtkFieldData* fielddata=usgIn->GetFieldData(); - vtkIdList *ids=vtkIdList::New(); - vtkIdList *surfaceIds=vtkIdList::New(); - vtkIdList *originalIds=vtkIdList::New(); - for(int index=0; indexGetNumberOfArrays(); index++) - { - vtkDataArray* data=fielddata->GetArray(index); - if(data==NULL) - continue; - - vtkInformation* info=data->GetInformation(); - const char* arrayOffsetName=info->Get( - vtkQuadratureSchemeDefinition::QUADRATURE_OFFSET_ARRAY_NAME()); - - if(arrayOffsetName == NULL || - strcmp(arrayOffsetName, offsets->GetName())!=0) - { - usgOut->GetFieldData()->AddArray(data); - - continue; - } - - vtkDataArray* newArray=data->NewInstance(); - newArray->SetName(data->GetName()); - usgOut->GetPointData()->AddArray(newArray); - newArray->SetNumberOfComponents(data->GetNumberOfComponents()); - newArray->SetNumberOfTuples(usgOut->GetNumberOfPoints()); - newArray->CopyComponentNames(data); - newArray->Delete(); - - for(vtkIdType cellId=0; cellIdGetValue(cellId); - - vtkIdType originalCellId=originalCellIds->GetValue(cellId); - int originalCellType=usgIn->GetCellType(originalCellId); - - shrinked->GetCellPoints(cellId, ids); - surface->GetCellPoints(cellId, surfaceIds); - - for(int id=0; idGetNumberOfIds(); id++) - { - vtkIdType surfaceId=surfaceIds->GetId(id); - vtkIdType shrinkedId=ids->GetId(id); - vtkIdType originalPointId = originalPointIds->GetValue(surfaceId); - - usgIn->GetCellPoints(originalCellId, originalIds); - int originalLocalId=-1; - for(int li=0; liGetNumberOfIds(); li++) - { - if(originalPointId==originalIds->GetId(li)) - { - originalLocalId=li; - break; - } - } - if(originalLocalId==-1) - { - originalLocalId=0; - vtkErrorMacro("cannot find original id"); - } - - const double * w=dict[originalCellType]->GetShapeFunctionWeights( - originalLocalId); - int j; - for(j=0; jGetNumberOfNodes(); j++) - { - if(w[j]==1.0) - break; - } - if(j==dict[originalCellType]->GetNumberOfNodes()) - { - //vtkErrorMacro("cannot find elno weigth."); - j=id; - } - newArray->SetTuple(shrinkedId, offset+j, data); - } - } - } - - ids->FastDelete(); - surfaceIds->FastDelete(); - originalIds->FastDelete(); - delete[] dict; - - return 1; -} - -void vtkELNOSurfaceFilter::PrintSelf(ostream& os, vtkIndent indent) -{ - this->Superclass::PrintSelf(os, indent); -} diff --git a/src/Plugins/MEDReader/IO/vtkELNOSurfaceFilter.h b/src/Plugins/MEDReader/IO/vtkELNOSurfaceFilter.h deleted file mode 100644 index 99de2d47..00000000 --- a/src/Plugins/MEDReader/IO/vtkELNOSurfaceFilter.h +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// - -#ifndef _vtkELNOSurfaceFilter_h -#define _vtkELNOSurfaceFilter_h - -#include "vtkUnstructuredGridAlgorithm.h" - -class VTK_EXPORT vtkELNOSurfaceFilter: public vtkUnstructuredGridAlgorithm -{ -public: - static vtkELNOSurfaceFilter *New(); - vtkTypeMacro(vtkELNOSurfaceFilter,vtkUnstructuredGridAlgorithm); - void PrintSelf(ostream& os, vtkIndent indent); - -protected: - vtkELNOSurfaceFilter(); - ~vtkELNOSurfaceFilter(); - - int RequestData(vtkInformation *, vtkInformationVector **, - vtkInformationVector *); - -private: - vtkELNOSurfaceFilter(const vtkELNOSurfaceFilter&); - void operator =(const vtkELNOSurfaceFilter&); -}; -#endif diff --git a/src/Plugins/MEDReader/IO/vtkExtractCellType.cxx b/src/Plugins/MEDReader/IO/vtkExtractCellType.cxx deleted file mode 100644 index af4d2465..00000000 --- a/src/Plugins/MEDReader/IO/vtkExtractCellType.cxx +++ /dev/null @@ -1,483 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Anthony Geay - -#include "vtkExtractCellType.h" -#include "MEDFileFieldRepresentationTree.hxx" -#include "MEDFileFieldOverView.hxx" - -#include "vtkAdjacentVertexIterator.h" -#include "vtkDataArrayTemplate.h" -#include "vtkIntArray.h" -#include "vtkCellData.h" -#include "vtkPointData.h" - -#include "vtkStreamingDemandDrivenPipeline.h" -#include "vtkUnstructuredGrid.h" -#include "vtkMultiBlockDataSet.h" - -#include "vtkInformationStringKey.h" -#include "vtkAlgorithmOutput.h" -#include "vtkObjectFactory.h" -#include "vtkMutableDirectedGraph.h" -#include "vtkMultiBlockDataSet.h" -#include "vtkDataSet.h" -#include "vtkInformationVector.h" -#include "vtkInformation.h" -#include "vtkDataArraySelection.h" -#include "vtkTimeStamp.h" -#include "vtkInEdgeIterator.h" -#include "vtkInformationDataObjectKey.h" -#include "vtkExecutive.h" -#include "vtkVariantArray.h" -#include "vtkStringArray.h" -#include "vtkDoubleArray.h" -#include "vtkCharArray.h" -#include "vtkUnsignedCharArray.h" -#include "vtkDataSetAttributes.h" -#include "vtkDemandDrivenPipeline.h" -#include "vtkDataObjectTreeIterator.h" -#include "vtkThreshold.h" - -#include -#include - -vtkStandardNewMacro(vtkExtractCellType); - -vtkCxxSetObjectMacro(vtkExtractCellType, SIL, vtkMutableDirectedGraph); - -/////////////////// - -class ExtractCellTypeStatus -{ -public: - ExtractCellTypeStatus():_status(false),_vtkt(-1),_mct(INTERP_KERNEL::NORM_ERROR) { } - ExtractCellTypeStatus(int vtkt, INTERP_KERNEL::NormalizedCellType mct); - bool isSame(int vtkt, INTERP_KERNEL::NormalizedCellType mct) const { return _vtkt==vtkt && _mct==mct; } - bool getStatus() const { return _status; } - void setStatus(bool status) const { _status=status; } - void cpyStatusFrom(const ExtractCellTypeStatus& other) { _status=other._status; } - std::string getKey() const { return _type_str; } - const char *getKeyOfEntry() const { return _type_str.c_str(); } - int getVTKCellType() const { return _vtkt; } - void printMySelf(std::ostream& os) const; - bool isSameAs(const ExtractCellTypeStatus& other) const; - void feedSIL(vtkMutableDirectedGraph *sil, vtkIdType root, vtkVariantArray *childEdge, std::vector& names) const; -protected: - mutable bool _status; - int _vtkt; - INTERP_KERNEL::NormalizedCellType _mct; - std::string _type_str; -}; - -class vtkExtractCellType::vtkExtractCellTypeInternal -{ -public: - vtkExtractCellTypeInternal():_ref_mtime(0) { } - int getNumberOfEntries() const; - const char *getKeyOfEntry(int i) const; - bool getStatusOfEntryStr(const char *entry) const; - void setStatusOfEntryStr(const char *entry, bool status) const; - void feedSIL(vtkMutableDirectedGraph *sil) const; - std::vector getIdsToKeep() const; - void printMySelf(std::ostream& os) const; - bool setRefTime(vtkObject *input) const; - // non const methods - void loadFrom(const std::map& m); -private: - const ExtractCellTypeStatus& getEntry(const char *entry) const; - bool checkSame(const std::map& m) const; -private: - std::vector _types; - mutable unsigned long _ref_mtime; -}; - -bool vtkExtractCellType::vtkExtractCellTypeInternal::setRefTime(vtkObject *input) const -{ - unsigned long mtime(input->GetMTime()); - if(mtime>_ref_mtime) - { - _ref_mtime=mtime; - return true; - } - else - return false; -} - -std::vector vtkExtractCellType::vtkExtractCellTypeInternal::getIdsToKeep() const -{ - std::vector ret; - for(std::vector::const_iterator it=_types.begin();it!=_types.end();it++) - { - if((*it).getStatus()) - ret.push_back((*it).getVTKCellType()); - } - return ret; -} - -void vtkExtractCellType::vtkExtractCellTypeInternal::feedSIL(vtkMutableDirectedGraph *sil) const -{ - vtkSmartPointer childEdge(vtkSmartPointer::New()); - childEdge->InsertNextValue(0); - vtkSmartPointer crossEdge(vtkSmartPointer::New()); - crossEdge->InsertNextValue(1); - // CrossEdge is an edge linking hierarchies. - vtkUnsignedCharArray* crossEdgesArray=vtkUnsignedCharArray::New(); - crossEdgesArray->SetName("CrossEdges"); - sil->GetEdgeData()->AddArray(crossEdgesArray); - crossEdgesArray->Delete(); - std::vector names; - // Add global fields root - vtkIdType root(sil->AddVertex()); - names.push_back("CellTypesTree"); - // - for(std::vector::const_iterator it=_types.begin();it!=_types.end();it++) - { - (*it).feedSIL(sil,root,childEdge,names); - } - // This array is used to assign names to nodes. - vtkStringArray *namesArray(vtkStringArray::New()); - namesArray->SetName("Names"); - namesArray->SetNumberOfTuples(sil->GetNumberOfVertices()); - sil->GetVertexData()->AddArray(namesArray); - namesArray->Delete(); - std::vector::const_iterator iter; - vtkIdType cc; - for(cc=0, iter=names.begin(); iter!=names.end(); ++iter, ++cc) - namesArray->SetValue(cc,(*iter).c_str()); -} - -void vtkExtractCellType::vtkExtractCellTypeInternal::loadFrom(const std::map& m) -{ - if(checkSame(m)) - return; - // - std::size_t sz(m.size()),ii(0); - _types.resize(sz); - for(std::map::const_iterator it=m.begin();it!=m.end();it++,ii++) - { - ExtractCellTypeStatus elt((*it).first,(*it).second); - _types[ii]=elt; - } -} - -int vtkExtractCellType::vtkExtractCellTypeInternal::getNumberOfEntries() const -{ - return (int) _types.size(); -} - -const char *vtkExtractCellType::vtkExtractCellTypeInternal::getKeyOfEntry(int i) const -{ - return _types[i].getKeyOfEntry(); -} - -bool vtkExtractCellType::vtkExtractCellTypeInternal::checkSame(const std::map& m) const -{ - std::size_t sz(m.size()); - if(sz!=_types.size()) - return false; - bool ret(true); - std::map::const_iterator it(m.begin()); - for(std::size_t i=0;i::const_iterator it0=_types.begin();it0!=_types.end();it0++) - if(entryCpp==(*it0).getKey()) - return *it0; - std::ostringstream oss; oss << "vtkExtractCellTypeInternal::getEntry : no such entry \"" << entry << "\"!"; - throw INTERP_KERNEL::Exception(oss.str().c_str()); -} - -bool vtkExtractCellType::vtkExtractCellTypeInternal::getStatusOfEntryStr(const char *entry) const -{ - try - { - const ExtractCellTypeStatus& elt(getEntry(entry)); - return elt.getStatus(); - } - catch (INTERP_KERNEL::Exception e) - { - //std::cerr << vtkDebugMacro"Exception has been thrown in vtkExtractCellType::vtkExtractCellTypeInternal::getStatusOfEntryStr : " << e.what() << std::endl; - return false; - } -} - -void vtkExtractCellType::vtkExtractCellTypeInternal::setStatusOfEntryStr(const char *entry, bool status) const -{ - try - { - const ExtractCellTypeStatus& elt(getEntry(entry)); - elt.setStatus(status); - } - catch (INTERP_KERNEL::Exception e) - { - //std::cerr << "Exception has been thrown in vtkExtractCellType::vtkExtractCellTypeInternal::setStatusOfEntryStr : " << e.what() << std::endl; - } -} - -void vtkExtractCellType::vtkExtractCellTypeInternal::printMySelf(std::ostream& os) const -{ - for(std::vector::const_iterator it0=_types.begin();it0!=_types.end();it0++) - (*it0).printMySelf(os); -} - -ExtractCellTypeStatus::ExtractCellTypeStatus(int vtkt, INTERP_KERNEL::NormalizedCellType mct):_status(false),_vtkt(vtkt),_mct(mct) -{ - std::string name(INTERP_KERNEL::CellModel::GetCellModel(mct).getRepr()); - _type_str=name.substr(5);//skip "NORM_" -} - -void ExtractCellTypeStatus::printMySelf(std::ostream& os) const -{ - os << " -" << _type_str << "("; - if(_status) - os << "X"; - else - os << " "; - os << ")" << std::endl; -} - -bool ExtractCellTypeStatus::isSameAs(const ExtractCellTypeStatus& other) const -{ - return _vtkt==other._vtkt && _mct==other._mct; -} - -void ExtractCellTypeStatus::feedSIL(vtkMutableDirectedGraph *sil, vtkIdType root, vtkVariantArray *childEdge, std::vector& names) const -{ - vtkIdType InfoGeoType(sil->AddChild(root,childEdge)); - names.push_back(_type_str); - vtkIdType InfoVTKID(sil->AddChild(InfoGeoType,childEdge)); - std::ostringstream oss; oss << _vtkt; - names.push_back(oss.str()); -} - -//////////////////// - -vtkExtractCellType::vtkExtractCellType():SIL(NULL),Internal(new vtkExtractCellTypeInternal),InsideOut(0) -{ -} - -vtkExtractCellType::~vtkExtractCellType() -{ - if(this->SIL) - this->SIL->Delete(); - delete this->Internal; -} - -void vtkExtractCellType::SetInsideOut(int val) -{ - if(this->InsideOut!=val) - { - this->InsideOut=val; - this->Modified(); - } -} - -int vtkExtractCellType::RequestInformation(vtkInformation *request, vtkInformationVector **inputVector, vtkInformationVector *outputVector) -{ - try - { - //std::cerr << "########################################## vtkExtractCellType::RequestInformation ##########################################" << std::endl; - vtkInformation *outInfo(outputVector->GetInformationObject(0)); - vtkInformation *inputInfo(inputVector[0]->GetInformationObject(0)); - vtkDataSet *input(0); - { - vtkDataObject *inp(inputInfo->Get(vtkDataObject::DATA_OBJECT())); - if(vtkDataSet::SafeDownCast(inp)) - input=vtkDataSet::SafeDownCast(inp); - else - { - vtkMultiBlockDataSet *inputTmp(vtkMultiBlockDataSet::SafeDownCast(inp)); - if(inputTmp) - { - if(inputTmp->GetNumberOfBlocks()!=1) - { - vtkDebugMacro("vtkExtractCellType::RequestInformation : input vtkMultiBlockDataSet must contain exactly 1 block !"); - return 0; - } - vtkDataSet *blk0(vtkDataSet::SafeDownCast(inputTmp->GetBlock(0))); - if(!blk0) - { - vtkDebugMacro("vtkExtractCellType::RequestInformation : the single block in input vtkMultiBlockDataSet must be a vtkDataSet instance !"); - return 0; - } - input=blk0; - } - else - { - vtkDebugMacro("vtkExtractCellType::RequestInformation : supported input are vtkDataSet or vtkMultiBlockDataSet !"); - return 0; - } - } - } - if(this->Internal->setRefTime(input)) - { - vtkIdType nbOfCells(input->GetNumberOfCells()); - std::map m; - for(vtkIdType cellId=0;cellIdGetCellType(cellId)); - const std::map::const_iterator it(m.find(vtkCt)); - if(it==m.end()) - { - const unsigned char *pos(std::find(MEDCoupling::MEDMeshMultiLev::PARAMEDMEM_2_VTKTYPE,MEDCoupling::MEDMeshMultiLev::PARAMEDMEM_2_VTKTYPE+MEDCoupling::MEDMeshMultiLev::PARAMEDMEM_2_VTKTYPE_LGTH,vtkCt)); - if(pos==MEDCoupling::MEDMeshMultiLev::PARAMEDMEM_2_VTKTYPE+MEDCoupling::MEDMeshMultiLev::PARAMEDMEM_2_VTKTYPE_LGTH) - { - vtkDebugMacro("vtkExtractCellType::RequestInformation : cell #" << cellId << " has unrecognized type !"); - return 0; - } - m[vtkCt]=(INTERP_KERNEL::NormalizedCellType)std::distance(MEDCoupling::MEDMeshMultiLev::PARAMEDMEM_2_VTKTYPE,pos); - } - } - this->Internal->loadFrom(m); - if(this->SIL) - this->SIL->Delete(); - this->SIL=vtkMutableDirectedGraph::New(); - this->Internal->feedSIL(this->SIL); - // - outInfo->Set(vtkDataObject::SIL(),this->SIL); - } - } - catch(INTERP_KERNEL::Exception& e) - { - std::cerr << "Exception has been thrown in vtkExtractCellType::RequestInformation : " << e.what() << std::endl; - return 0; - } - return 1; -} - -vtkDataSet *FilterFamilies(vtkDataSet *input, const std::vector& idsToKeep, bool insideOut) -{ - const int VTK_DATA_ARRAY_DELETE=vtkDataArrayTemplate::VTK_DATA_ARRAY_DELETE; - const char ZE_SELECTION_ARR_NAME[]="@@ZeSelection@@"; - vtkDataSet *output(input->NewInstance()); - output->ShallowCopy(input); - vtkSmartPointer thres(vtkSmartPointer::New()); - thres->SetInputData(output); - vtkDataSetAttributes *dscIn(input->GetCellData()),*dscIn2(input->GetPointData()); - vtkDataSetAttributes *dscOut(output->GetCellData()),*dscOut2(output->GetPointData()); - // - double vMin(insideOut==0?1.:0.),vMax(insideOut==0?2.:1.); - thres->ThresholdBetween(vMin,vMax); - // OK for the output - vtkIdType nbOfCells(input->GetNumberOfCells()); - vtkCharArray *zeSelection(vtkCharArray::New()); - zeSelection->SetName(ZE_SELECTION_ARR_NAME); - zeSelection->SetNumberOfComponents(1); - char *pt(new char[nbOfCells]); - zeSelection->SetArray(pt,nbOfCells,0,VTK_DATA_ARRAY_DELETE); - std::fill(pt,pt+nbOfCells,0); - std::vector pt2(nbOfCells,false); - for(std::vector::const_iterator it=idsToKeep.begin();it!=idsToKeep.end();it++) - { - for(vtkIdType ii=0;iiGetCellType(ii)==*it) - pt2[ii]=true; - } - } - for(int ii=0;iiGetCellData()->AddArray(zeSelection)); - output->GetCellData()->SetActiveAttribute(idx,vtkDataSetAttributes::SCALARS); - output->GetCellData()->CopyScalarsOff(); - zeSelection->Delete(); - // - thres->SetInputArrayToProcess(idx,0,0,"vtkDataObject::FIELD_ASSOCIATION_CELLS",ZE_SELECTION_ARR_NAME); - thres->Update(); - vtkUnstructuredGrid *zeComputedOutput(thres->GetOutput()); - zeComputedOutput->GetCellData()->RemoveArray(idx); - output->Delete(); - zeComputedOutput->Register(0); - return zeComputedOutput; -} - -int vtkExtractCellType::RequestData(vtkInformation *request, vtkInformationVector **inputVector, vtkInformationVector *outputVector) -{ - try - { - //std::cerr << "########################################## vtkExtractCellType::RequestData ##########################################" << std::endl; - vtkInformation* inputInfo=inputVector[0]->GetInformationObject(0); - vtkDataSet *input(vtkDataSet::SafeDownCast(inputInfo->Get(vtkDataObject::DATA_OBJECT()))); - vtkInformation *info(input->GetInformation()); - vtkInformation *outInfo(outputVector->GetInformationObject(0)); - vtkDataSet *output(vtkDataSet::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT()))); - std::vector idsToKeep(this->Internal->getIdsToKeep()); - vtkDataSet *tryOnCell(FilterFamilies(input,idsToKeep,this->InsideOut)); - // first shrink the input - output->ShallowCopy(tryOnCell); - tryOnCell->Delete(); - } - catch(INTERP_KERNEL::Exception& e) - { - std::cerr << "Exception has been thrown in vtkExtractCellType::RequestData : " << e.what() << std::endl; - return 0; - } - return 1; -} - -int vtkExtractCellType::GetSILUpdateStamp() -{ - return (int)this->SILTime; -} - -void vtkExtractCellType::PrintSelf(ostream& os, vtkIndent indent) -{ - this->Superclass::PrintSelf(os, indent); -} - -int vtkExtractCellType::GetNumberOfGeoTypesArrays() -{ - int ret(this->Internal->getNumberOfEntries()); - //std::cerr << "vtkExtractCellType::GetNumberOfGeoTypesArrays() -> " << ret << std::endl; - return ret; -} - -const char *vtkExtractCellType::GetGeoTypesArrayName(int index) -{ - const char *ret(this->Internal->getKeyOfEntry(index)); - //std::cerr << "vtkExtractCellType::GetGeoTypesArrayName(" << index << ") -> " << ret << std::endl; - return ret; -} - -int vtkExtractCellType::GetGeoTypesArrayStatus(const char *name) -{ - int ret((int)this->Internal->getStatusOfEntryStr(name)); - //std::cerr << "vtkExtractCellType::GetGeoTypesArrayStatus(" << name << ") -> " << ret << std::endl; - return ret; -} - -void vtkExtractCellType::SetGeoTypesStatus(const char *name, int status) -{ - //std::cerr << "vtkExtractCellType::SetGeoTypesStatus(" << name << "," << status << ")" << std::endl; - if (GetNumberOfGeoTypesArrays()<1) - return; - this->Internal->setStatusOfEntryStr(name,(bool)status); - if(std::string(name)==GetGeoTypesArrayName(GetNumberOfGeoTypesArrays()-1)) - { - this->Modified(); - //this->Internal->printMySelf(std::cerr); - } -} diff --git a/src/Plugins/MEDReader/IO/vtkExtractCellType.h b/src/Plugins/MEDReader/IO/vtkExtractCellType.h deleted file mode 100644 index 560c0cdb..00000000 --- a/src/Plugins/MEDReader/IO/vtkExtractCellType.h +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Anthony Geay - -#ifndef vtkExtractCellType_h__ -#define vtkExtractCellType_h__ - -#include "vtkDataSetAlgorithm.h" - -class vtkMutableDirectedGraph; - -class VTK_EXPORT vtkExtractCellType : public vtkDataSetAlgorithm -{ -public: - static vtkExtractCellType* New(); - vtkTypeMacro(vtkExtractCellType, vtkDataSetAlgorithm) - void PrintSelf(ostream& os, vtkIndent indent); - virtual int GetNumberOfGeoTypesArrays(); - const char *GetGeoTypesArrayName(int index); - int GetGeoTypesArrayStatus(const char *name); - virtual void SetGeoTypesStatus(const char *name, int status); - void SetInsideOut(int val); - // Description: - // Every time the SIL is updated a this will return a different value. - virtual int GetSILUpdateStamp(); - -protected: - vtkExtractCellType(); - ~vtkExtractCellType(); - - int RequestInformation(vtkInformation *request, - vtkInformationVector **inputVector, vtkInformationVector *outputVector); - - int RequestData(vtkInformation *request, vtkInformationVector **inputVector, - vtkInformationVector *outputVector); - // Description: - // This SIL stores the structure of the mesh/groups/cell types - // that can be selected. - virtual void SetSIL(vtkMutableDirectedGraph*); - vtkGetObjectMacro(SIL, vtkMutableDirectedGraph); -protected: - vtkMutableDirectedGraph *SIL; - vtkTimeStamp SILTime; -private: - vtkExtractCellType(const vtkExtractCellType&); - void operator=(const vtkExtractCellType&); // Not implemented. - private: - //BTX - //ETX - class vtkExtractCellTypeInternal; - vtkExtractCellTypeInternal *Internal; - int InsideOut; -}; - -#endif diff --git a/src/Plugins/MEDReader/IO/vtkExtractGroup.cxx b/src/Plugins/MEDReader/IO/vtkExtractGroup.cxx deleted file mode 100644 index 7bf32f5d..00000000 --- a/src/Plugins/MEDReader/IO/vtkExtractGroup.cxx +++ /dev/null @@ -1,739 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Anthony Geay - -#include "vtkExtractGroup.h" -#include "MEDFileFieldRepresentationTree.hxx" -#include "vtkMEDReader.h" -#include "VTKMEDTraits.hxx" - -#include "vtkAdjacentVertexIterator.h" -#include "vtkDataArrayTemplate.h" -#include "vtkIntArray.h" -#include "vtkLongArray.h" -#ifdef WIN32 -#include "vtkLongLongArray.h" -#endif -#include "vtkCellData.h" -#include "vtkPointData.h" - -#include "vtkStreamingDemandDrivenPipeline.h" -#include "vtkUnstructuredGrid.h" -#include "vtkMultiBlockDataSet.h" - -#include "vtkInformationStringKey.h" -#include "vtkAlgorithmOutput.h" -#include "vtkObjectFactory.h" -#include "vtkMutableDirectedGraph.h" -#include "vtkMultiBlockDataSet.h" -#include "vtkDataSet.h" -#include "vtkInformationVector.h" -#include "vtkInformation.h" -#include "vtkDataArraySelection.h" -#include "vtkTimeStamp.h" -#include "vtkInEdgeIterator.h" -#include "vtkInformationDataObjectKey.h" -#include "vtkExecutive.h" -#include "vtkVariantArray.h" -#include "vtkStringArray.h" -#include "vtkDoubleArray.h" -#include "vtkCharArray.h" -#include "vtkUnsignedCharArray.h" -#include "vtkDataSetAttributes.h" -#include "vtkDemandDrivenPipeline.h" -#include "vtkDataObjectTreeIterator.h" -#include "vtkThreshold.h" -#include "vtkMultiBlockDataGroupFilter.h" -#include "vtkCompositeDataToUnstructuredGridFilter.h" -#include "vtkInformationDataObjectMetaDataKey.h" - -#include -#include - -vtkStandardNewMacro(vtkExtractGroup); - -/////////////////// - -class ExtractGroupStatus -{ -public: - ExtractGroupStatus():_status(false) { } - ExtractGroupStatus(const char *name); - bool getStatus() const { return _status; } - void setStatus(bool status) const { _status=status; } - void cpyStatusFrom(const ExtractGroupStatus& other) { _status=other._status; } - std::string getName() const { return _name; } - void resetStatus() const { _status=false; } - const char *getKeyOfEntry() const { return _ze_key_name.c_str(); } - virtual void printMySelf(std::ostream& os) const; - virtual bool isSameAs(const ExtractGroupStatus& other) const; -protected: -mutable bool _status; -std::string _name; -std::string _ze_key_name; -}; - -class ExtractGroupGrp : public ExtractGroupStatus -{ -public: - ExtractGroupGrp(const char *name):ExtractGroupStatus(name) { std::ostringstream oss; oss << START << name; _ze_key_name=oss.str(); } - void setFamilies(const std::vector& fams) { _fams=fams; } - const std::vector& getFamiliesLyingOn() const { return _fams; } - bool isSameAs(const ExtractGroupGrp& other) const; -public: - static const char START[]; - std::vector _fams; -}; - -class ExtractGroupFam : public ExtractGroupStatus -{ -public: - ExtractGroupFam(const char *name); - void printMySelf(std::ostream& os) const; - void fillIdsToKeep(std::set& s) const; - int getId() const { return _id; } - bool isSameAs(const ExtractGroupFam& other) const; -public: - static const char START[]; -private: - int _id; -}; - -class vtkExtractGroup::vtkExtractGroupInternal -{ -public: - void loadFrom(vtkMutableDirectedGraph *sil); - int getNumberOfEntries() const; - const char *getMeshName() const; - const char *getKeyOfEntry(int i) const; - bool getStatusOfEntryStr(const char *entry) const; - void setStatusOfEntryStr(const char *entry, bool status); - void printMySelf(std::ostream& os) const; - std::set getIdsToKeep() const; - void clearSelection() const; - int getIdOfFamily(const std::string& famName) const; - static bool IsInformationOK(vtkInformation *info); -private: - std::map computeFamStrIdMap() const; - const ExtractGroupStatus& getEntry(const char *entry) const; - ExtractGroupStatus& getEntry(const char *entry); -private: - std::vector _groups; - std::vector _fams; - mutable std::vector< std::pair > _selection; - std::string _mesh_name; -}; - -const char ExtractGroupGrp::START[]="GRP_"; - -const char ExtractGroupFam::START[]="FAM_"; - -ExtractGroupStatus::ExtractGroupStatus(const char *name):_status(false),_name(name) -{ -} - -void ExtractGroupStatus::printMySelf(std::ostream& os) const -{ - os << " -" << _ze_key_name << "("; - if(_status) - os << "X"; - else - os << " "; - os << ")" << std::endl; -} - -bool ExtractGroupStatus::isSameAs(const ExtractGroupStatus& other) const -{ - return _name==other._name && _ze_key_name==other._ze_key_name; -} - -bool ExtractGroupGrp::isSameAs(const ExtractGroupGrp& other) const -{ - bool ret(ExtractGroupStatus::isSameAs(other)); - if(ret) - return _fams==other._fams; - else - return false; -} - -bool vtkExtractGroup::vtkExtractGroupInternal::IsInformationOK(vtkInformation *info) -{ - // Check the information contain meta data key - if(!info->Has(vtkMEDReader::META_DATA())) - return false; - - // Recover Meta Data - vtkMutableDirectedGraph *sil(vtkMutableDirectedGraph::SafeDownCast(info->Get(vtkMEDReader::META_DATA()))); - if(!sil) - return false; - int idNames(0); - vtkAbstractArray *verticesNames(sil->GetVertexData()->GetAbstractArray("Names",idNames)); - vtkStringArray *verticesNames2(vtkStringArray::SafeDownCast(verticesNames)); - if(!verticesNames2) - return false; - for(int i=0;iGetNumberOfValues();i++) - { - vtkStdString &st(verticesNames2->GetValue(i)); - if(st=="MeshesFamsGrps") - return true; - } - return false; -} - -const char* vtkExtractGroup::GetGrpStart() -{ - return ExtractGroupGrp::START; -} - -const char* vtkExtractGroup::GetFamStart() -{ - return ExtractGroupFam::START; -} - -const char *vtkExtractGroup::vtkExtractGroupInternal::getMeshName() const -{ - return this->_mesh_name.c_str(); -} - -void vtkExtractGroup::vtkExtractGroupInternal::loadFrom(vtkMutableDirectedGraph *sil) -{ - std::vector oldGrps(_groups); _groups.clear(); - std::vector oldFams(_fams); _fams.clear(); - int idNames(0); - vtkAbstractArray *verticesNames(sil->GetVertexData()->GetAbstractArray("Names",idNames)); - vtkStringArray *verticesNames2(vtkStringArray::SafeDownCast(verticesNames)); - vtkIdType id0; - bool found(false); - for(int i=0;iGetNumberOfValues();i++) - { - vtkStdString &st(verticesNames2->GetValue(i)); - if(st=="MeshesFamsGrps") - { - id0=i; - found=true; - } - } - if(!found) - throw INTERP_KERNEL::Exception("There is an internal error ! The tree on server side has not the expected look !"); - vtkAdjacentVertexIterator *it0(vtkAdjacentVertexIterator::New()); - sil->GetAdjacentVertices(id0,it0); - int kk(0),ll(0); - while(it0->HasNext()) - { - vtkIdType id1(it0->Next()); - std::string meshName((const char *)verticesNames2->GetValue(id1)); - this->_mesh_name=meshName; - vtkAdjacentVertexIterator *it1(vtkAdjacentVertexIterator::New()); - sil->GetAdjacentVertices(id1,it1); - vtkIdType idZeGrps(it1->Next());//zeGroups - vtkAdjacentVertexIterator *itGrps(vtkAdjacentVertexIterator::New()); - sil->GetAdjacentVertices(idZeGrps,itGrps); - while(itGrps->HasNext()) - { - vtkIdType idg(itGrps->Next()); - ExtractGroupGrp grp((const char *)verticesNames2->GetValue(idg)); - vtkAdjacentVertexIterator *itGrps2(vtkAdjacentVertexIterator::New()); - sil->GetAdjacentVertices(idg,itGrps2); - std::vector famsOnGroup; - while(itGrps2->HasNext()) - { - vtkIdType idgf(itGrps2->Next()); - famsOnGroup.push_back(std::string((const char *)verticesNames2->GetValue(idgf))); - } - grp.setFamilies(famsOnGroup); - itGrps2->Delete(); - _groups.push_back(grp); - } - itGrps->Delete(); - vtkIdType idZeFams(it1->Next());//zeFams - it1->Delete(); - vtkAdjacentVertexIterator *itFams(vtkAdjacentVertexIterator::New()); - sil->GetAdjacentVertices(idZeFams,itFams); - while(itFams->HasNext()) - { - vtkIdType idf(itFams->Next()); - ExtractGroupFam fam((const char *)verticesNames2->GetValue(idf)); - _fams.push_back(fam); - } - itFams->Delete(); - } - it0->Delete(); - // - std::size_t szg(_groups.size()),szf(_fams.size()); - if(szg==oldGrps.size() && szf==oldFams.size()) - { - bool isSame(true); - for(std::size_t i=0;i=0 && i::const_iterator it0=_groups.begin();it0!=_groups.end();it0++) - if(entryCpp==(*it0).getKeyOfEntry()) - return *it0; - for(std::vector::const_iterator it0=_fams.begin();it0!=_fams.end();it0++) - if(entryCpp==(*it0).getKeyOfEntry()) - return *it0; - std::ostringstream oss; oss << "vtkExtractGroupInternal::getEntry : no such entry \"" << entry << "\"!"; - throw INTERP_KERNEL::Exception(oss.str().c_str()); -} - -ExtractGroupStatus& vtkExtractGroup::vtkExtractGroupInternal::getEntry(const char *entry) -{ - std::string entryCpp(entry); - for(std::vector::iterator it0=_groups.begin();it0!=_groups.end();it0++) - if(entryCpp==(*it0).getKeyOfEntry()) - return *it0; - for(std::vector::iterator it0=_fams.begin();it0!=_fams.end();it0++) - if(entryCpp==(*it0).getKeyOfEntry()) - return *it0; - std::ostringstream oss; oss << "vtkExtractGroupInternal::getEntry : no such entry \"" << entry << "\"!"; - throw INTERP_KERNEL::Exception(oss.str().c_str()); -} - -void vtkExtractGroup::vtkExtractGroupInternal::printMySelf(std::ostream& os) const -{ - os << "Groups :" << std::endl; - for(std::vector::const_iterator it0=_groups.begin();it0!=_groups.end();it0++) - (*it0).printMySelf(os); - os << "Families :" << std::endl; - for(std::vector::const_iterator it0=_fams.begin();it0!=_fams.end();it0++) - (*it0).printMySelf(os); -} - -int vtkExtractGroup::vtkExtractGroupInternal::getIdOfFamily(const std::string& famName) const -{ - for(std::vector::const_iterator it=_fams.begin();it!=_fams.end();it++) - { - if((*it).getName()==famName) - return (*it).getId(); - } - return std::numeric_limits::max(); -} - -ExtractGroupFam::ExtractGroupFam(const char *name):ExtractGroupStatus(name),_id(0) -{ - std::size_t pos(_name.find(MEDFileFieldRepresentationLeavesArrays::ZE_SEP)); - std::string name0(_name.substr(0,pos)),name1(_name.substr(pos+strlen(MEDFileFieldRepresentationLeavesArrays::ZE_SEP))); - std::istringstream iss(name1); - iss >> _id; - std::ostringstream oss; oss << START << name; _ze_key_name=oss.str(); _name=name0; -} - -bool ExtractGroupFam::isSameAs(const ExtractGroupFam& other) const -{ - bool ret(ExtractGroupStatus::isSameAs(other)); - if(ret) - return _id==other._id; - else - return false; -} - -void ExtractGroupFam::printMySelf(std::ostream& os) const -{ - os << " -" << _ze_key_name << " famName : \"" << _name << "\" id : " << _id << " ("; - if(_status) - os << "X"; - else - os << " "; - os << ")" << std::endl; -} - -void ExtractGroupFam::fillIdsToKeep(std::set& s) const -{ - s.insert(_id); -} - -std::set vtkExtractGroup::vtkExtractGroupInternal::getIdsToKeep() const -{ - for(auto it: _selection) - { - const ExtractGroupStatus& elt(getEntry(it.first.c_str())); - elt.setStatus(it.second); - } - std::map m(this->computeFamStrIdMap()); - std::set s; - for(std::vector::const_iterator it0=_groups.begin();it0!=_groups.end();it0++) - { - if((*it0).getStatus()) - { - const std::vector& fams((*it0).getFamiliesLyingOn()); - for(std::vector::const_iterator it1=fams.begin();it1!=fams.end();it1++) - { - std::map::iterator it2(m.find((*it1))); - if(it2!=m.end()) - s.insert((*it2).second); - } - } - } - for(std::vector::const_iterator it0=_fams.begin();it0!=_fams.end();it0++) - if((*it0).getStatus()) - (*it0).fillIdsToKeep(s); - return s; -} - -void vtkExtractGroup::vtkExtractGroupInternal::clearSelection() const -{ - _selection.clear(); - for(auto it : _groups) - it.resetStatus(); - for(auto it : _fams) - it.resetStatus(); -} - -std::map vtkExtractGroup::vtkExtractGroupInternal::computeFamStrIdMap() const -{ - std::map ret; - for(std::vector::const_iterator it0=_fams.begin();it0!=_fams.end();it0++) - ret[(*it0).getName()]=(*it0).getId(); - return ret; -} - -//////////////////// - -vtkExtractGroup::vtkExtractGroup():SIL(NULL),Internal(new vtkExtractGroupInternal),InsideOut(0) -{ -} - -vtkExtractGroup::~vtkExtractGroup() -{ - delete this->Internal; -} - -void vtkExtractGroup::SetInsideOut(int val) -{ - if(this->InsideOut!=val) - { - this->InsideOut=val; - this->Modified(); - } -} - -int vtkExtractGroup::RequestInformation(vtkInformation *request, vtkInformationVector **inputVector, vtkInformationVector *outputVector) -{ -// vtkUnstructuredGridAlgorithm::RequestInformation(request,inputVector,outputVector); - try - { -// std::cerr << "########################################## vtkExtractGroup::RequestInformation ##########################################" << std::endl; -// request->Print(cout); - vtkInformation *outInfo(outputVector->GetInformationObject(0)); - vtkInformation *inputInfo(inputVector[0]->GetInformationObject(0)); - if(!vtkExtractGroup::vtkExtractGroupInternal::IsInformationOK(inputInfo)) - { - vtkErrorMacro("No SIL Data available ! The source of this filter must be MEDReader !"); - return 0; - } - - this->SetSIL(vtkMutableDirectedGraph::SafeDownCast(inputInfo->Get(vtkMEDReader::META_DATA()))); - this->Internal->loadFrom(this->SIL); - //this->Internal->printMySelf(std::cerr); - } - catch(INTERP_KERNEL::Exception& e) - { - std::cerr << "Exception has been thrown in vtkExtractGroup::RequestInformation : " << e.what() << std::endl; - return 0; - } - return 1; -} - -/*! - * Do not use vtkCxxSetObjectMacro macro because input mdg comes from an already managed in the pipeline just a ref on it. - */ -void vtkExtractGroup::SetSIL(vtkMutableDirectedGraph *mdg) -{ - if(this->SIL==mdg) - return ; - this->SIL=mdg; -} - -template -vtkDataSet *FilterFamilies(vtkSmartPointer& thres, - vtkDataSet *input, const std::set& idsToKeep, bool insideOut, const char *arrNameOfFamilyField, - const char *associationForThreshold, bool& catchAll, bool& catchSmth) -{ - const int VTK_DATA_ARRAY_DELETE=vtkDataArrayTemplate::VTK_DATA_ARRAY_DELETE; - const char ZE_SELECTION_ARR_NAME[]="@@ZeSelection@@"; - vtkDataSet *output(input->NewInstance()); - output->ShallowCopy(input); - thres->SetInputData(output); - vtkDataSetAttributes *dscIn(input->GetCellData()),*dscIn2(input->GetPointData()); - vtkDataSetAttributes *dscOut(output->GetCellData()),*dscOut2(output->GetPointData()); - // - double vMin(insideOut==0?1.:0.),vMax(insideOut==0?2.:1.); - thres->ThresholdBetween(vMin,vMax); - // OK for the output - // - CellPointExtractor cpe2(input); - vtkDataArray *da(cpe2.Get()->GetScalars(arrNameOfFamilyField)); - if(!da) - return 0; - std::string daName(da->GetName()); - typedef MEDFileVTKTraits::VtkType vtkMCIdTypeArray; - vtkMCIdTypeArray *dai(vtkMCIdTypeArray::SafeDownCast(da)); - if(daName!=arrNameOfFamilyField || !dai) - return 0; - // - int nbOfTuples(dai->GetNumberOfTuples()); - vtkCharArray *zeSelection(vtkCharArray::New()); - zeSelection->SetName(ZE_SELECTION_ARR_NAME); - zeSelection->SetNumberOfComponents(1); - char *pt(new char[nbOfTuples]); - zeSelection->SetArray(pt,nbOfTuples,0,VTK_DATA_ARRAY_DELETE); - const mcIdType *inPtr(dai->GetPointer(0)); - std::fill(pt,pt+nbOfTuples,0); - catchAll=true; catchSmth=false; - std::vector pt2(nbOfTuples,false); - for(std::set::const_iterator it=idsToKeep.begin();it!=idsToKeep.end();it++) - { - bool catchFid(false); - for(int i=0;iAddArray(zeSelection)); - cpe3.Get()->SetActiveAttribute(idx,vtkDataSetAttributes::SCALARS); - cpe3.Get()->CopyScalarsOff(); - zeSelection->Delete(); - // - thres->SetInputArrayToProcess(idx,0,0,associationForThreshold,ZE_SELECTION_ARR_NAME); - thres->Update(); - vtkUnstructuredGrid *zeComputedOutput(thres->GetOutput()); - CellPointExtractor cpe(zeComputedOutput); - cpe.Get()->RemoveArray(idx); - output->Delete(); - zeComputedOutput->Register(0); - return zeComputedOutput; -} - -class CellExtractor -{ -public: - CellExtractor(vtkDataSet *ds):_ds(ds) { } - vtkDataSetAttributes *Get() { return _ds->GetCellData(); } -private: - vtkDataSet *_ds; -}; - -class PointExtractor -{ -public: - PointExtractor(vtkDataSet *ds):_ds(ds) { } - vtkDataSetAttributes *Get() { return _ds->GetPointData(); } -private: - vtkDataSet *_ds; -}; -int vtkExtractGroup::RequestData(vtkInformation *request, vtkInformationVector **inputVector, vtkInformationVector *outputVector) -{ - try - { - // std::cerr << "########################################## vtkExtractGroup::RequestData ##########################################" << std::endl; - // request->Print(cout); - vtkInformation* inputInfo=inputVector[0]->GetInformationObject(0); - vtkMultiBlockDataSet *inputMB(vtkMultiBlockDataSet::SafeDownCast(inputInfo->Get(vtkDataObject::DATA_OBJECT()))); - if(inputMB->GetNumberOfBlocks()!=1) - { - std::ostringstream oss; oss << "vtkExtractGroup::RequestData : input has not the right number of parts ! Expected 1 !"; - if(this->HasObserver("ErrorEvent") ) - this->InvokeEvent("ErrorEvent",const_cast(oss.str().c_str())); - else - vtkOutputWindowDisplayErrorText(const_cast(oss.str().c_str())); - vtkObject::BreakOnError(); - return 0; - } - vtkDataSet *input(vtkDataSet::SafeDownCast(inputMB->GetBlock(0))); - vtkInformation *info(input->GetInformation()); - vtkInformation *outInfo(outputVector->GetInformationObject(0)); - vtkMultiBlockDataSet *output(vtkMultiBlockDataSet::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT()))); - std::set idsToKeep(this->Internal->getIdsToKeep()); - this->Internal->clearSelection(); - // first shrink the input - bool catchAll,catchSmth; - vtkSmartPointer thres1(vtkSmartPointer::New()),thres2(vtkSmartPointer::New()); - vtkDataSet *tryOnCell(FilterFamilies(thres1,input,idsToKeep,this->InsideOut, - MEDFileFieldRepresentationLeavesArrays::FAMILY_ID_CELL_NAME,"vtkDataObject::FIELD_ASSOCIATION_CELLS",catchAll,catchSmth)); - if(tryOnCell) - { - if(catchAll) - { - output->SetBlock(0,tryOnCell); - tryOnCell->Delete();// - return 1; - } - else - { - if(catchSmth) - { - vtkDataSet *tryOnNode(FilterFamilies(thres2,input,idsToKeep,this->InsideOut, - MEDFileFieldRepresentationLeavesArrays::FAMILY_ID_NODE_NAME,"vtkDataObject::FIELD_ASSOCIATION_POINTS",catchAll,catchSmth)); - if(tryOnNode && catchSmth) - { - output->SetBlock(0,tryOnCell); - output->SetBlock(1,tryOnNode); - tryOnCell->Delete(); - tryOnNode->Delete(); - return 1; - } - else - { - if(tryOnNode) - tryOnNode->Delete(); - output->SetBlock(0,tryOnCell); - tryOnCell->Delete(); - return 1; - } - } - else - { - vtkDataSet *tryOnNode(FilterFamilies(thres1,input,idsToKeep,this->InsideOut, - MEDFileFieldRepresentationLeavesArrays::FAMILY_ID_NODE_NAME,"vtkDataObject::FIELD_ASSOCIATION_POINTS",catchAll,catchSmth)); - if(tryOnNode) - { - tryOnCell->Delete(); - output->SetBlock(0,tryOnNode); - tryOnNode->Delete(); - return 1; - } - else - { - output->SetBlock(0,tryOnNode); - tryOnCell->Delete(); - return 0; - } - } - } - } - else - { - vtkDataSet *tryOnNode(FilterFamilies(thres1,input,idsToKeep,this->InsideOut, - MEDFileFieldRepresentationLeavesArrays::FAMILY_ID_NODE_NAME,"vtkDataObject::FIELD_ASSOCIATION_POINTS",catchAll,catchSmth)); - if(tryOnNode) - { - output->ShallowCopy(tryOnNode); - tryOnNode->Delete();// - return 1; - } - else - { - std::ostringstream oss; oss << "vtkExtractGroup::RequestData : The integer array with name \""<< MEDFileFieldRepresentationLeavesArrays::FAMILY_ID_CELL_NAME; - oss << "\" or \"" << MEDFileFieldRepresentationLeavesArrays::FAMILY_ID_NODE_NAME << "\" does not exist ! The extraction of group and/or family is not possible !"; - if(this->HasObserver("ErrorEvent") ) - this->InvokeEvent("ErrorEvent",const_cast(oss.str().c_str())); - else - vtkOutputWindowDisplayErrorText(const_cast(oss.str().c_str())); - vtkObject::BreakOnError(); - return 0; - } - } - } - catch(INTERP_KERNEL::Exception& e) - { - std::cerr << "Exception has been thrown in vtkExtractGroup::RequestData : " << e.what() << std::endl; - return 0; - } -} - -int vtkExtractGroup::GetSILUpdateStamp() -{ - return (int)this->SILTime; -} - -void vtkExtractGroup::PrintSelf(ostream& os, vtkIndent indent) -{ - this->Superclass::PrintSelf(os, indent); -} - -int vtkExtractGroup::GetNumberOfGroupsFlagsArrays() -{ - int ret(this->Internal->getNumberOfEntries()); - //std::cerr << "vtkExtractGroup::GetNumberOfFieldsTreeArrays() -> " << ret << std::endl; - return ret; -} - -const char *vtkExtractGroup::GetGroupsFlagsArrayName(int index) -{ - const char *ret(this->Internal->getKeyOfEntry(index)); -// std::cerr << "vtkExtractGroup::GetFieldsTreeArrayName(" << index << ") -> " << ret << std::endl; - return ret; -} - -int vtkExtractGroup::GetGroupsFlagsArrayStatus(const char *name) -{ - int ret((int)this->Internal->getStatusOfEntryStr(name)); -// std::cerr << "vtkExtractGroup::GetGroupsFlagsArrayStatus(" << name << ") -> " << ret << std::endl; - return ret; -} - -void vtkExtractGroup::SetGroupsFlagsStatus(const char *name, int status) -{ - //std::cerr << "vtkExtractGroup::SetFieldsStatus(" << name << "," << status << ")" << std::endl; - this->Internal->setStatusOfEntryStr(name,(bool)status); - this->Modified(); - //this->Internal->printMySelf(std::cerr); -} - -const char *vtkExtractGroup::GetMeshName() -{ - return this->Internal->getMeshName(); -} diff --git a/src/Plugins/MEDReader/IO/vtkExtractGroup.h b/src/Plugins/MEDReader/IO/vtkExtractGroup.h deleted file mode 100644 index bea981ea..00000000 --- a/src/Plugins/MEDReader/IO/vtkExtractGroup.h +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Anthony Geay - -#ifndef vtkExtractGroup_h__ -#define vtkExtractGroup_h__ - -#include "vtkMultiBlockDataSetAlgorithm.h" - -class vtkMutableDirectedGraph; - -class VTK_EXPORT vtkExtractGroup: public vtkMultiBlockDataSetAlgorithm -{ -public: - static vtkExtractGroup* New(); - vtkTypeMacro(vtkExtractGroup, vtkMultiBlockDataSetAlgorithm) - void PrintSelf(ostream& os, vtkIndent indent); - virtual int GetNumberOfGroupsFlagsArrays(); - const char *GetGroupsFlagsArrayName(int index); - int GetGroupsFlagsArrayStatus(const char *name); - virtual void SetGroupsFlagsStatus(const char *name, int status); - void SetInsideOut(int val); - // Description: - // Every time the SIL is updated a this will return a different value. - virtual int GetSILUpdateStamp(); - const char *GetMeshName(); - static const char* GetGrpStart(); - static const char* GetFamStart(); -protected: - vtkExtractGroup(); - ~vtkExtractGroup(); - - int RequestInformation(vtkInformation *request, - vtkInformationVector **inputVector, vtkInformationVector *outputVector); - - int RequestData(vtkInformation *request, vtkInformationVector **inputVector, - vtkInformationVector *outputVector); - - // Description: - // This SIL stores the structure of the mesh/groups/cell types - // that can be selected. - virtual void SetSIL(vtkMutableDirectedGraph*); - vtkGetObjectMacro(SIL, vtkMutableDirectedGraph); -protected: - vtkMutableDirectedGraph *SIL; - vtkTimeStamp SILTime; -private: - vtkExtractGroup(const vtkExtractGroup&); - void operator=(const vtkExtractGroup&); // Not implemented. - private: - //BTX - //ETX - class vtkExtractGroupInternal; - vtkExtractGroupInternal *Internal; - int InsideOut; -}; - -#endif diff --git a/src/Plugins/MEDReader/IO/vtkGenerateVectors.cxx b/src/Plugins/MEDReader/IO/vtkGenerateVectors.cxx deleted file mode 100644 index 36bc6bea..00000000 --- a/src/Plugins/MEDReader/IO/vtkGenerateVectors.cxx +++ /dev/null @@ -1,151 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Anthony Geay - -#include "vtkGenerateVectors.h" -#include "vtkDataArrayTemplate.h" -#include "vtkDoubleArray.h" -#include "vtkInformation.h" -#include "vtkUnstructuredGrid.h" -#include "vtkQuadratureSchemeDefinition.h" -#include "vtkInformationQuadratureSchemeDefinitionVectorKey.h" -#include "MEDUtilities.hxx" -#include "vtkFieldData.h" - -#include - -const char vtkGenerateVectors::VECTOR_SUFFIX[]="_Vector"; - -std::string vtkGenerateVectors::SuffixFieldName(const std::string& name) -{ - std::ostringstream oss; oss << name << VECTOR_SUFFIX; - return oss.str(); -} - -/*! - * This method forces MeshMTime modification. To do so, points are declared as modified. - */ -void vtkGenerateVectors::ChangeMeshTimeToUpdateCache(vtkDataSet *dataset) -{ - vtkUnstructuredGrid *ug(vtkUnstructuredGrid::SafeDownCast(dataset)); - if(!ug) - return ; - ug->GetPoints()->Modified(); -} - -void vtkGenerateVectors::Operate(vtkFieldData *fd) -{ - if(!fd) - return ; - const int nbOfArrs(fd->GetNumberOfArrays()); - std::vector daToAppend; - for(int i=0;iGetArray(i)); - if(!arr) - continue; - vtkDoubleArray *arrc(vtkDoubleArray::SafeDownCast(arr)); - if(!arrc) - continue; - int nbOfCompo(arrc->GetNumberOfComponents()); - if(nbOfCompo<=1 || nbOfCompo==3) - continue; - if(nbOfCompo==2) - daToAppend.push_back(Operate2Compo(arrc)); - else - daToAppend.push_back(OperateMoreThan3Compo(arrc)); - } - for(std::vector::const_iterator it=daToAppend.begin();it!=daToAppend.end();it++) - { - vtkDoubleArray *elt(*it); - if(!elt) - continue; - fd->AddArray(elt); - elt->Delete(); - } -} - -vtkDoubleArray *vtkGenerateVectors::Operate2Compo(vtkDoubleArray *oldArr) -{ - const int VTK_DATA_ARRAY_FREE=vtkDataArrayTemplate::VTK_DATA_ARRAY_FREE; - vtkDoubleArray *ret(vtkDoubleArray::New()); - vtkIdType nbOfTuples(oldArr->GetNumberOfTuples()); - const double *inPt(oldArr->GetPointer(0)); - double *pt((double *)malloc(nbOfTuples*3*sizeof(double))); - for(vtkIdType i=0;iSetNumberOfComponents(3); - std::string newName(SuffixFieldName(oldArr->GetName())); - ret->SetName(newName.c_str()); - ret->SetComponentName(0,oldArr->GetComponentName(0)); - ret->SetComponentName(1,oldArr->GetComponentName(1)); - ret->SetArray(pt,3*nbOfTuples,0,VTK_DATA_ARRAY_FREE); - UpdateInformationOfArray(oldArr,ret); - return ret; -} - -vtkDoubleArray *vtkGenerateVectors::OperateMoreThan3Compo(vtkDoubleArray *oldArr) -{ - const int VTK_DATA_ARRAY_FREE=vtkDataArrayTemplate::VTK_DATA_ARRAY_FREE; - vtkDoubleArray *ret(vtkDoubleArray::New()); - int nbOfCompo(oldArr->GetNumberOfComponents()); - vtkIdType nbOfTuples(oldArr->GetNumberOfTuples()); - const double *inPt(oldArr->GetPointer(0)); - double *pt((double *)malloc(nbOfTuples*3*sizeof(double))); - for(vtkIdType i=0;iSetNumberOfComponents(3); - std::string newName(SuffixFieldName(oldArr->GetName())); - ret->SetName(newName.c_str()); - ret->SetComponentName(0,oldArr->GetComponentName(0)); - ret->SetComponentName(1,oldArr->GetComponentName(1)); - ret->SetComponentName(2,oldArr->GetComponentName(2)); - ret->SetArray(pt,3*nbOfTuples,0,VTK_DATA_ARRAY_FREE); - UpdateInformationOfArray(oldArr,ret); - return ret; -} - -void vtkGenerateVectors::UpdateInformationOfArray(vtkDoubleArray *oldArr, vtkDoubleArray *arr) -{ - if(oldArr->GetInformation()->Has(vtkQuadratureSchemeDefinition::QUADRATURE_OFFSET_ARRAY_NAME())) - { - arr->GetInformation()->Set(vtkQuadratureSchemeDefinition::QUADRATURE_OFFSET_ARRAY_NAME(),oldArr->GetInformation()->Get((vtkQuadratureSchemeDefinition::QUADRATURE_OFFSET_ARRAY_NAME()))); - } - if(oldArr->GetInformation()->Get(MEDUtilities::ELGA())) - arr->GetInformation()->Set(MEDUtilities::ELGA(),1); - vtkInformationQuadratureSchemeDefinitionVectorKey *key(vtkQuadratureSchemeDefinition::DICTIONARY()); - if(key->Has(oldArr->GetInformation())) - { - int dictSize(key->Size(oldArr->GetInformation())); - vtkQuadratureSchemeDefinition **dict = new vtkQuadratureSchemeDefinition *[dictSize]; - key->GetRange(oldArr->GetInformation(),dict,0,0,dictSize); - key->SetRange(arr->GetInformation(),dict,0,0,dictSize); - delete [] dict; - } - if(oldArr->GetInformation()->Get(MEDUtilities::ELNO())) - arr->GetInformation()->Set(MEDUtilities::ELNO(),1); -} diff --git a/src/Plugins/MEDReader/IO/vtkGenerateVectors.h b/src/Plugins/MEDReader/IO/vtkGenerateVectors.h deleted file mode 100644 index e7a45d53..00000000 --- a/src/Plugins/MEDReader/IO/vtkGenerateVectors.h +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Anthony Geay - -#ifndef vtkGenerateVectors_h__ -#define vtkGenerateVectors_h__ - -#include "vtkDataSetAlgorithm.h" - -class vtkFieldData; -class vtkDoubleArray; - -class VTK_EXPORT vtkGenerateVectors -{ -public: - static void ChangeMeshTimeToUpdateCache(vtkDataSet *dataset); - static void Operate(vtkFieldData *fd); - static vtkDoubleArray *Operate2Compo(vtkDoubleArray *oldArr); - static vtkDoubleArray *OperateMoreThan3Compo(vtkDoubleArray *oldArr); - static std::string SuffixFieldName(const std::string& name); -public: - static const char VECTOR_SUFFIX[]; -protected: - static void UpdateInformationOfArray(vtkDoubleArray *oldArr, vtkDoubleArray *arr); -}; - -#endif diff --git a/src/Plugins/MEDReader/IO/vtkInformationGaussDoubleVectorKey.h b/src/Plugins/MEDReader/IO/vtkInformationGaussDoubleVectorKey.h deleted file mode 100644 index 9c0d5288..00000000 --- a/src/Plugins/MEDReader/IO/vtkInformationGaussDoubleVectorKey.h +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// - -#ifndef __vtkInformationGaussDoubleVectorKey_h_ -#define __vtkInformationGaussDoubleVectorKey_h_ - -#include "vtkInformationDoubleVectorKey.h" - -class VTK_EXPORT vtkInformationGaussDoubleVectorKey : public vtkInformationDoubleVectorKey -{ -public: - vtkTypeMacro(vtkInformationGaussDoubleVectorKey, vtkInformationDoubleVectorKey); - void PrintSelf(ostream& os, vtkIndent indent) VTK_OVERRIDE{} - - vtkInformationGaussDoubleVectorKey(const char* name, const char* location, - int length = -1) : vtkInformationDoubleVectorKey(name, location, length) { } - - /** - * This method simply returns a new vtkInformationDoubleVectorKey, given a - * name, a location and a required length. This method is provided for - * wrappers. Use the constructor directly from C++ instead. - */ - static vtkInformationGaussDoubleVectorKey* MakeKey(const char* name, const char* location, - int length = -1) - { - return new vtkInformationGaussDoubleVectorKey(name, location, length); - } - - /** - * Simply shallow copies the key from fromInfo to toInfo. - * This is used by the pipeline to propagate this key downstream. - */ - void CopyDefaultInformation(vtkInformation* request, - vtkInformation* fromInfo, - vtkInformation* toInfo) VTK_OVERRIDE - { - this->ShallowCopy(fromInfo, toInfo); - } - - /*private: - vtkInformationGaussDoubleVectorKey(const vtkInformationGaussDoubleVectorKey&) VTK_DELETE_FUNCTION; - void operator=(const vtkInformationGaussDoubleVectorKey&) VTK_DELETE_FUNCTION;*/ -}; - -#endif diff --git a/src/Plugins/MEDReader/IO/vtkMEDQuadraturePointsGenerator.cxx b/src/Plugins/MEDReader/IO/vtkMEDQuadraturePointsGenerator.cxx deleted file mode 100644 index bfc25d59..00000000 --- a/src/Plugins/MEDReader/IO/vtkMEDQuadraturePointsGenerator.cxx +++ /dev/null @@ -1,134 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Roman NIKOLAEV - -//Local includes -#include "vtkMEDQuadraturePointsGenerator.h" -#include "MEDFileFieldRepresentationTree.hxx" - -//VTK includes -#include -#include -#include -#include -#include -#include -#include -#include - -//----------------------------------------------------------------------------- -vtkStandardNewMacro(vtkMEDQuadraturePointsGenerator); - -//----------------------------------------------------------------------------- -vtkMEDQuadraturePointsGenerator::vtkMEDQuadraturePointsGenerator() -{ -} - -//----------------------------------------------------------------------------- -vtkMEDQuadraturePointsGenerator::~vtkMEDQuadraturePointsGenerator() -{} - - -//----------------------------------------------------------------------------- -int vtkMEDQuadraturePointsGenerator::RequestData( - vtkInformation* request, - vtkInformationVector **input, - vtkInformationVector *output) -{ - if (this->Superclass::RequestData(request, input, output) == 0 ) - { - return 0; - } - - //Fill MED internal array - vtkDataObject *tmpDataObj; - - // Get the input. - tmpDataObj = input[0]->GetInformationObject(0)->Get(vtkDataObject::DATA_OBJECT()); - vtkUnstructuredGrid *usgIn = vtkUnstructuredGrid::SafeDownCast(tmpDataObj); - // Get the output. - tmpDataObj = output->GetInformationObject(0)->Get(vtkDataObject::DATA_OBJECT()); - vtkPolyData *pdOut = vtkPolyData::SafeDownCast(tmpDataObj); - vtkDataArray* offsets = this->GetInputArrayToProcess(0, input); - - if (usgIn == NULL || pdOut == NULL || offsets == NULL ) - { - vtkErrorMacro("Filter data has not been configured correctly. Aborting."); - return 1; - } - - vtkInformation *info = offsets->GetInformation(); - vtkInformationQuadratureSchemeDefinitionVectorKey *key - = vtkQuadratureSchemeDefinition::DICTIONARY(); - if (!key->Has(info)) - { - vtkErrorMacro( - << "Dictionary is not present in array " - << offsets->GetName() << " " << offsets - << " Aborting."); - return 0; - } - - vtkIdType nCells = usgIn->GetNumberOfCells(); - int dictSize = key->Size(info); - vtkQuadratureSchemeDefinition **dict - = new vtkQuadratureSchemeDefinition *[dictSize]; - key->GetRange(info, dict, 0, 0, dictSize); - - // Loop over all fields to map the internal MED cell array to the points array - int nCArrays = usgIn->GetCellData()->GetNumberOfArrays(); - for (int i = 0; iGetCellData()->GetArray(i); - if ( !array ) - { - continue; - } - std::string arrName = array->GetName(); - if ( arrName == MEDFileFieldRepresentationLeavesArrays::FAMILY_ID_CELL_NAME ) - { - vtkDataArray *out_id_cells = array->NewInstance(); - out_id_cells->SetName(MEDFileFieldRepresentationLeavesArrays::FAMILY_ID_NODE_NAME); - out_id_cells->SetNumberOfComponents(array->GetNumberOfComponents()); - out_id_cells->CopyComponentNames( array ); - for (int cellId = 0; cellId < nCells; cellId++) - { - int cellType = usgIn->GetCellType(cellId); - - // a simple check to see if a scheme really exists for this cell type. - // should not happen if the cell type has not been modified. - if (dict[cellType] == NULL) - { - continue; - } - - int np = dict[cellType]->GetNumberOfQuadraturePoints(); - for (int id = 0; id < np; id++) - { - out_id_cells->InsertNextTuple(cellId, array); - } - } - out_id_cells->Squeeze(); - pdOut->GetPointData()->AddArray(out_id_cells); - out_id_cells->Delete(); - } - } - delete[] dict; - return 1; -} diff --git a/src/Plugins/MEDReader/IO/vtkMEDQuadraturePointsGenerator.h b/src/Plugins/MEDReader/IO/vtkMEDQuadraturePointsGenerator.h deleted file mode 100644 index 4578aa2e..00000000 --- a/src/Plugins/MEDReader/IO/vtkMEDQuadraturePointsGenerator.h +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Roman NIKOLAEV - -#ifndef vtkMEDQuadraturePointsGenerator_h -#define vtkMEDQuadraturePointsGenerator_h - -#include // For export macro -#include - -class vtkInformation; -class vtkInformationVector; - -class VTK_EXPORT vtkMEDQuadraturePointsGenerator : public vtkQuadraturePointsGenerator -{ -public: - vtkTypeMacro(vtkMEDQuadraturePointsGenerator,vtkQuadraturePointsGenerator); - static vtkMEDQuadraturePointsGenerator *New(); - -protected: - - int RequestData(vtkInformation *req, vtkInformationVector **input, vtkInformationVector *output); - vtkMEDQuadraturePointsGenerator(); - virtual ~vtkMEDQuadraturePointsGenerator(); -private: - vtkMEDQuadraturePointsGenerator(const vtkMEDQuadraturePointsGenerator &); // Not implemented - void operator=(const vtkMEDQuadraturePointsGenerator &); // Not implemented -}; - -#endif diff --git a/src/Plugins/MEDReader/IO/vtkMEDReader.cxx b/src/Plugins/MEDReader/IO/vtkMEDReader.cxx deleted file mode 100644 index 129ec3b3..00000000 --- a/src/Plugins/MEDReader/IO/vtkMEDReader.cxx +++ /dev/null @@ -1,697 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Anthony Geay - -#include "vtkMEDReader.h" -#include "vtkGenerateVectors.h" -#include "MEDUtilities.hxx" - -#include "vtkMultiBlockDataSet.h" -#include "vtkInformation.h" -#include "vtkDataSetAttributes.h" -#include "vtkStringArray.h" -#include "vtkMutableDirectedGraph.h" -#include "vtkInformationStringKey.h" -// -#include "vtkUnsignedCharArray.h" -#include "vtkInformationVector.h" -#include "vtkSmartPointer.h" -#include "vtkVariantArray.h" -#include "vtkExecutive.h" -#include "vtkStreamingDemandDrivenPipeline.h" -#include "vtkMultiTimeStepAlgorithm.h" -#include "vtkUnstructuredGrid.h" -#include "vtkInformationQuadratureSchemeDefinitionVectorKey.h" -#include "vtkInformationDoubleVectorKey.h" -#include "vtkQuadratureSchemeDefinition.h" -#include "vtkPointData.h" -#include "vtkCellData.h" -#include "vtkCellType.h" -#include "vtkCellArray.h" -#include "vtkDoubleArray.h" -#include "vtkObjectFactory.h" -#include "vtkInformationDataObjectMetaDataKey.h" - -#ifdef MEDREADER_USE_MPI -#include "vtkMultiProcessController.h" -#include "vtkPUnstructuredGridGhostCellsGenerator.h" -#endif - -#include "MEDFileFieldRepresentationTree.hxx" - -#include -#include -#include -#include -#include - -/*! - * This class stores properties in loading state mode (pvsm) when the MED file has not been read yet. - * The file is not read beacause FileName has not been informed yet ! So this class stores properties of vtkMEDReader instance that - * owns it and wait the vtkMEDReader::SetFileName to apply properties afterwards. - */ -class PropertyKeeper -{ -public: - PropertyKeeper(vtkMEDReader *master):IsGVActivated(false),GVValue(0),IsCMActivated(false),CMValue(0),IsGhostActivated(false),GCGCP(1),_master(master) { } - void assignPropertiesIfNeeded(); - bool arePropertiesOnTreeToSetAfter() const; - // - void pushFieldStatusEntry(const char* name, int status); - void pushGenerateVectorsValue(int value); - void pushChangeModeValue(int value); - void pushTimesFlagsStatusEntry(const char* name, int status); - void pushGhost(int value); -protected: - // pool of pairs to assign in SetFieldsStatus if needed. The use case is the load using pvsm. - std::vector< std::pair > SetFieldsStatusPairs; - // generate vector - bool IsGVActivated; - int GVValue; - // change mode - bool IsCMActivated; - int CMValue; - // ghost cells - bool IsGhostActivated; - int GCGCP; - // - std::vector< std::pair > TimesFlagsStatusPairs; - vtkMEDReader *_master; -}; - -void PropertyKeeper::assignPropertiesIfNeeded() -{ - if(!this->SetFieldsStatusPairs.empty()) - { - for(std::vector< std::pair >::const_iterator it=this->SetFieldsStatusPairs.begin();it!=this->SetFieldsStatusPairs.end();it++) - _master->SetFieldsStatus((*it).first.c_str(),(*it).second); - this->SetFieldsStatusPairs.clear(); - } - if(!this->TimesFlagsStatusPairs.empty()) - { - for(std::vector< std::pair >::const_iterator it=this->TimesFlagsStatusPairs.begin();it!=this->TimesFlagsStatusPairs.end();it++) - _master->SetTimesFlagsStatus((*it).first.c_str(),(*it).second); - this->TimesFlagsStatusPairs.clear(); - } - if(this->IsGVActivated) - { - _master->GenerateVectors(this->GVValue); - this->IsGVActivated=false; - } - if(this->IsCMActivated) - { - _master->ChangeMode(this->CMValue); - this->IsCMActivated=false; - } - if(this->IsGhostActivated) - { - _master->GhostCellGeneratorCallForPara(this->GCGCP); - this->IsGhostActivated=false; - } -} - -void PropertyKeeper::pushFieldStatusEntry(const char* name, int status) -{ - bool found(false); - for(std::vector< std::pair >::const_iterator it=this->SetFieldsStatusPairs.begin();it!=this->SetFieldsStatusPairs.end() && !found;it++) - found=(*it).first==name; - if(!found) - this->SetFieldsStatusPairs.push_back(std::pair(name,status)); -} - -void PropertyKeeper::pushTimesFlagsStatusEntry(const char* name, int status) -{ - bool found(false); - for(std::vector< std::pair >::const_iterator it=this->TimesFlagsStatusPairs.begin();it!=this->TimesFlagsStatusPairs.end() && !found;it++) - found=(*it).first==name; - if(!found) - this->TimesFlagsStatusPairs.push_back(std::pair(name,status)); -} - -void PropertyKeeper::pushGenerateVectorsValue(int value) -{ - this->IsGVActivated=true; - this->GVValue=value; -} - -void PropertyKeeper::pushChangeModeValue(int value) -{ - this->IsCMActivated=true; - this->CMValue=value; -} - -void PropertyKeeper::pushGhost(int value) -{ - this->IsGhostActivated=true; - this->GCGCP=value; -} - -bool PropertyKeeper::arePropertiesOnTreeToSetAfter() const -{ - return !SetFieldsStatusPairs.empty(); -} - -class vtkMEDReader::vtkMEDReaderInternal -{ - -public: - vtkMEDReaderInternal(vtkMEDReader *master):TK(0),IsMEDOrSauv(true),IsStdOrMode(false),GenerateVect(false),SIL(0),LastLev0(-1),PK(master),MyMTime(0),GCGCP(true),FirstCall0(2) - { - } - - bool PluginStart0() - { - return false; // TODO Useless and buggy - if(FirstCall0==0) - return false; - FirstCall0--; - return true; - } - - ~vtkMEDReaderInternal() - { - if(this->SIL) - this->SIL->Delete(); - } -public: - MEDFileFieldRepresentationTree Tree; - TimeKeeper TK; - std::string FileName; - //when true the file is MED file. when false it is a Sauv file - bool IsMEDOrSauv; - //when false -> std, true -> mode. By default std (false). - bool IsStdOrMode; - //when false -> do nothing. When true cut off or extend to nbOfCompo=3 vector arrays. - bool GenerateVect; - std::string DftMeshName; - // Store the vtkMutableDirectedGraph that represents links between family, groups and cell types - vtkMutableDirectedGraph* SIL; - // store the lev0 id in Tree corresponding to the TIME_STEPS in the pipeline. - int LastLev0; - // The property keeper is usable only in pvsm mode. - PropertyKeeper PK; - int MyMTime; - std::set _wonderful_set;// this set is used by SetFieldsStatus method to detect the fact that SetFieldsStatus has been called for all items ! Great Items are not sorted ! Why ? - std::map _wonderful_ref;// this map stores the state before a SetFieldsStatus status. - bool GCGCP; - -private: - unsigned char FirstCall0; -}; - -vtkStandardNewMacro(vtkMEDReader); - -// vtkInformationKeyMacro(vtkMEDReader, META_DATA, DataObjectMetaData); // Here we need to customize vtkMEDReader::META_DATA method -// start of overload of vtkInformationKeyMacro -static vtkInformationDataObjectMetaDataKey *vtkMEDReader_META_DATA=new vtkInformationDataObjectMetaDataKey("META_DATA","vtkMEDReader"); - -vtkInformationDataObjectMetaDataKey *vtkMEDReader::META_DATA() -{ - static const char ZE_KEY[]="vtkMEDReader::META_DATA"; - vtkInformationDataObjectMetaDataKey *ret(vtkMEDReader_META_DATA); - MEDCoupling::GlobalDict *gd(MEDCoupling::GlobalDict::GetInstance()); - if(!gd->hasKey(ZE_KEY)) - {// here META_DATA is put on global var to be exchanged with other filters without dependancy of MEDReader. Please do not change ZE_KEY ! - std::ostringstream oss; oss << ret; - gd->setKeyValue(ZE_KEY,oss.str()); - } - return ret; -} - -static vtkInformationGaussDoubleVectorKey *vtkMEDReader_GAUSS_DATA=new vtkInformationGaussDoubleVectorKey("GAUSS_DATA","vtkMEDReader"); - -vtkInformationGaussDoubleVectorKey *vtkMEDReader::GAUSS_DATA() -{ - static const char ZE_KEY[]="vtkMEDReader::GAUSS_DATA"; - vtkInformationGaussDoubleVectorKey *ret(vtkMEDReader_GAUSS_DATA); - MEDCoupling::GlobalDict *gd(MEDCoupling::GlobalDict::GetInstance()); - if(!gd->hasKey(ZE_KEY)) - {// here META_DATA is put on global var to be exchanged with other filters without dependancy of MEDReader. Please do not change ZE_KEY ! - vtkInformationDoubleVectorKey *ret2(ret); - std::ostringstream oss; oss << ret2; - gd->setKeyValue(ZE_KEY,oss.str()); - } - return ret; -} -// end of overload of vtkInformationKeyMacro - -vtkMEDReader::vtkMEDReader():Internal(new vtkMEDReaderInternal(this)) -{ - this->SetNumberOfInputPorts(0); - this->SetNumberOfOutputPorts(1); -} - -vtkMEDReader::~vtkMEDReader() -{ - delete this->Internal; - this->Internal = 0; -} - -void vtkMEDReader::Reload() -{ - std::string fName((const char *)this->GetFileName()); - delete this->Internal; - this->Internal=new vtkMEDReaderInternal(this); - this->SetFileName(fName.c_str()); -} - -int vtkMEDReader::GetServerModifTime() -{ - if( !this->Internal ) - return -1; - return this->Internal->MyMTime; -} - -void vtkMEDReader::GenerateVectors(int val) -{ - if ( !this->Internal ) - return; - - if(this->Internal->FileName.empty()) - {//pvsm mode - this->Internal->PK.pushGenerateVectorsValue(val); - return ; - } - //not pvsm mode (general case) - bool val2((bool)val); - if(val2!=this->Internal->GenerateVect) - { - this->Internal->GenerateVect=val2; - this->Modified(); - } -} - -void vtkMEDReader::ChangeMode(int newMode) -{ - if ( !this->Internal ) - return; - - if(this->Internal->FileName.empty()) - {//pvsm mode - this->Internal->PK.pushChangeModeValue(newMode); - return ; - } - //not pvsm mode (general case) - this->Internal->IsStdOrMode=newMode!=0; - this->Modified(); -} - -void vtkMEDReader::GhostCellGeneratorCallForPara(int gcgcp) -{ - if ( !this->Internal ) - return; - - if(this->Internal->FileName.empty()) - {//pvsm mode - this->Internal->PK.pushGhost(gcgcp); - return ; - } - bool newVal(gcgcp!=0); - if(newVal!=this->Internal->GCGCP) - { - this->Internal->GCGCP=newVal; - this->Modified(); - } -} - -const char *vtkMEDReader::GetSeparator() -{ - return MEDFileFieldRepresentationLeavesArrays::ZE_SEP; -} - -void vtkMEDReader::SetFileName(const char *fname) -{ - if(!this->Internal) - return; - try - { - this->Internal->FileName=fname; - std::size_t pos(this->Internal->FileName.find_last_of('.')); - if(pos!=std::string::npos) - { - std::string ext(this->Internal->FileName.substr(pos)); - if(ext.find("sauv")!=std::string::npos) - this->Internal->IsMEDOrSauv=false; - } - if(this->Internal->Tree.getNumberOfLeavesArrays()==0) - { - int iPart(-1),nbOfParts(-1); -#ifdef MEDREADER_USE_MPI - vtkMultiProcessController *vmpc(vtkMultiProcessController::GetGlobalController()); - if(vmpc) - { - iPart=vmpc->GetLocalProcessId(); - nbOfParts=vmpc->GetNumberOfProcesses(); - } -#endif - this->Internal->Tree.loadMainStructureOfFile(this->Internal->FileName.c_str(),this->Internal->IsMEDOrSauv,iPart,nbOfParts); - if(!this->Internal->PK.arePropertiesOnTreeToSetAfter()) - this->Internal->Tree.activateTheFirst();//This line manually initialize the status of server (this) with the remote client. - this->Internal->TK.setMaxNumberOfTimeSteps(this->Internal->Tree.getMaxNumberOfTimeSteps()); - } - this->Modified(); - this->Internal->PK.assignPropertiesIfNeeded(); - } - catch(INTERP_KERNEL::Exception& e) - { - delete this->Internal; - this->Internal=0; - std::ostringstream oss; - oss << "Exception has been thrown in vtkMEDReader::SetFileName : " << e.what() << std::endl; - if(this->HasObserver("ErrorEvent") ) - this->InvokeEvent("ErrorEvent",const_cast(oss.str().c_str())); - else - vtkOutputWindowDisplayErrorText(const_cast(oss.str().c_str())); - vtkObject::BreakOnError(); - } -} - -char *vtkMEDReader::GetFileName() -{ - if (!this->Internal) - return 0; - return const_cast(this->Internal->FileName.c_str()); -} - -int vtkMEDReader::RequestInformation(vtkInformation *request, vtkInformationVector **inputVector, vtkInformationVector *outputVector) -{ -// std::cout << "########################################## vtkMEDReader::RequestInformation ##########################################" << std::endl; - if(!this->Internal) - return 0; - try - { -// request->Print(cout); - vtkInformation *outInfo(outputVector->GetInformationObject(0)); - outInfo->Set(vtkDataObject::DATA_TYPE_NAME(),"vtkMultiBlockDataSet"); - this->UpdateSIL(request, outInfo); - - // Set the meta data graph as a meta data key in the information - // That's all that is needed to transfer it along the pipeline - outInfo->Set(vtkMEDReader::META_DATA(),this->Internal->SIL); - - bool dummy(false); - this->PublishTimeStepsIfNeeded(outInfo,dummy); - } - catch(INTERP_KERNEL::Exception& e) - { - std::ostringstream oss; - oss << "Exception has been thrown in vtkMEDReader::RequestInformation : " << e.what() << std::endl; - if(this->HasObserver("ErrorEvent") ) - this->InvokeEvent("ErrorEvent",const_cast(oss.str().c_str())); - else - vtkOutputWindowDisplayErrorText(const_cast(oss.str().c_str())); - vtkObject::BreakOnError(); - return 0; - } - return 1; -} - -int vtkMEDReader::RequestData(vtkInformation *request, vtkInformationVector **inputVector, vtkInformationVector *outputVector) -{ -// std::cout << "########################################## vtkMEDReader::RequestData ##########################################" << std::endl; - if(!this->Internal) - return 0; - try - { -// request->Print(cout); - vtkInformation *outInfo(outputVector->GetInformationObject(0)); - vtkMultiBlockDataSet *output(vtkMultiBlockDataSet::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT()))); - bool isUpdated(false); - double reqTS(0.); - if(outInfo->Has(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP())) - reqTS=outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP()); - ExportedTinyInfo ti; -#ifndef MEDREADER_USE_MPI - this->FillMultiBlockDataSetInstance(output,reqTS,&ti); -#else - if(this->Internal->GCGCP) - { - vtkSmartPointer gcg(vtkSmartPointer::New()); - { - vtkDataSet *ret(RetrieveDataSetAtTime(reqTS,&ti)); - gcg->SetInputData(ret); - ret->Delete(); - } - gcg->SetUseGlobalPointIds(true); - gcg->SetBuildIfRequired(false); - gcg->Update(); - output->SetBlock(0,gcg->GetOutput()); - } - else - this->FillMultiBlockDataSetInstance(output,reqTS,&ti); -#endif - if(!ti.empty()) - { - const std::vector& data(ti.getData()); - outInfo->Set(vtkMEDReader::GAUSS_DATA(),&data[0],(int)data.size()); - request->Append(vtkExecutive::KEYS_TO_COPY(),vtkMEDReader::GAUSS_DATA());// Thank you to SciberQuest and DIPOLE_CENTER ! Don't understand why ! In RequestInformation it does not work ! - } - output->GetInformation()->Set(vtkDataObject::DATA_TIME_STEP(),reqTS); - // Is it really needed ? TODO - this->UpdateSIL(request, outInfo); - } - catch(INTERP_KERNEL::Exception& e) - { - std::cerr << "Exception has been thrown in vtkMEDReader::RequestData : " << e.what() << std::endl; - return 0; - } - return 1; -} - -void vtkMEDReader::SetFieldsStatus(const char* name, int status) -{ - if( !this->Internal ) - return; - - //this->Internal->_wonderful_set.insert(name); - if(this->Internal->FileName.empty()) - {//pvsm mode - this->Internal->PK.pushFieldStatusEntry(name,status); - return ; - } - if(this->Internal->_wonderful_set.empty()) - this->Internal->_wonderful_ref=this->Internal->Tree.dumpState();// start of SetFieldsStatus serie -> store ref to compare at the end of the SetFieldsStatus serie. - this->Internal->_wonderful_set.insert(name); - //not pvsm mode (general case) - try - { - this->Internal->Tree.changeStatusOfAndUpdateToHaveCoherentVTKDataSet(this->Internal->Tree.getIdHavingZeName(name),status); - if((int)this->Internal->_wonderful_set.size()==GetNumberOfFieldsTreeArrays()) - { - if(this->Internal->_wonderful_ref!=this->Internal->Tree.dumpState()) - { - if(!this->Internal->PluginStart0()) - { - this->Modified(); - } - this->Internal->MyMTime++; - } - this->Internal->_wonderful_set.clear(); - } - } - catch(INTERP_KERNEL::Exception& e) - { - if(!this->Internal->FileName.empty()) - { - std::cerr << "vtkMEDReader::SetFieldsStatus error : " << e.what() << " *** WITH STATUS=" << status << endl; - return ; - } - } -} - -int vtkMEDReader::GetNumberOfFieldsTreeArrays() -{ - if(!this->Internal) - return 0; - return this->Internal->Tree.getNumberOfLeavesArrays(); -} - -const char *vtkMEDReader::GetFieldsTreeArrayName(int index) -{ - if(!this->Internal) - return 0; - return this->Internal->Tree.getNameOfC(index); -} - -int vtkMEDReader::GetFieldsTreeArrayStatus(const char *name) -{ - if(!this->Internal) - return -1; - - int zeId(this->Internal->Tree.getIdHavingZeName(name)); - int ret(this->Internal->Tree.getStatusOf(zeId)); - return ret; -} - -void vtkMEDReader::SetTimesFlagsStatus(const char *name, int status) -{ - if (!this->Internal) - return; - - if(this->Internal->FileName.empty()) - {//pvsm mode - this->Internal->PK.pushTimesFlagsStatusEntry(name,status); - return ; - } - //not pvsm mode (general case) - int pos(0); - std::istringstream iss(name); iss >> pos; - this->Internal->TK.getTimesFlagArray()[pos].first=(bool)status; - if(pos==(int)this->Internal->TK.getTimesFlagArray().size()-1) - if(!this->Internal->PluginStart0()) - { - this->Modified(); - //this->Internal->TK.printSelf(std::cerr); - } -} - -int vtkMEDReader::GetNumberOfTimesFlagsArrays() -{ - if(!this->Internal) - return 0; - return (int)this->Internal->TK.getTimesFlagArray().size(); -} - -const char *vtkMEDReader::GetTimesFlagsArrayName(int index) -{ - return this->Internal->TK.getTimesFlagArray()[index].second.c_str(); -} - -int vtkMEDReader::GetTimesFlagsArrayStatus(const char *name) -{ - if(!this->Internal) - return -1; - int pos(0); - std::istringstream iss(name); iss >> pos; - return (int)this->Internal->TK.getTimesFlagArray()[pos].first; -} - -void vtkMEDReader::UpdateSIL(vtkInformation* request, vtkInformation *info) -{ - if(!this->Internal) - return; - std::string meshName(this->Internal->Tree.getActiveMeshName()); - if(!this->Internal->SIL || meshName!=this->Internal->DftMeshName) - { - vtkMutableDirectedGraph *sil(vtkMutableDirectedGraph::New()); - this->BuildSIL(sil); - if(this->Internal->SIL) - this->Internal->SIL->Delete(); - this->Internal->SIL=sil; - this->Internal->DftMeshName=meshName; - } -} - -/*! - * The returned string is the name of the mesh activated which groups and families are in \a sil. - */ -std::string vtkMEDReader::BuildSIL(vtkMutableDirectedGraph* sil) -{ - if (!this->Internal) - return std::string(); - sil->Initialize(); - vtkSmartPointer childEdge(vtkSmartPointer::New()); - childEdge->InsertNextValue(0); - vtkSmartPointer crossEdge(vtkSmartPointer::New()); - crossEdge->InsertNextValue(1); - // CrossEdge is an edge linking hierarchies. - vtkUnsignedCharArray* crossEdgesArray=vtkUnsignedCharArray::New(); - crossEdgesArray->SetName("CrossEdges"); - sil->GetEdgeData()->AddArray(crossEdgesArray); - crossEdgesArray->Delete(); - std::vector names; - // Now build the hierarchy. - vtkIdType rootId=sil->AddVertex(); - names.push_back("SIL"); - // Add global fields root - vtkIdType fieldsRoot(sil->AddChild(rootId,childEdge)); - names.push_back("FieldsStatusTree"); - this->Internal->Tree.feedSIL(sil,fieldsRoot,childEdge,names); - vtkIdType meshesFamsGrpsRoot(sil->AddChild(rootId,childEdge)); - names.push_back("MeshesFamsGrps"); - std::string dftMeshName(this->Internal->Tree.feedSILForFamsAndGrps(sil,meshesFamsGrpsRoot,childEdge,names)); - // This array is used to assign names to nodes. - vtkStringArray *namesArray(vtkStringArray::New()); - namesArray->SetName("Names"); - namesArray->SetNumberOfTuples(sil->GetNumberOfVertices()); - sil->GetVertexData()->AddArray(namesArray); - namesArray->Delete(); - std::vector::const_iterator iter; - vtkIdType cc; - for(cc=0, iter=names.begin(); iter!=names.end(); ++iter, ++cc) - namesArray->SetValue(cc,(*iter).c_str()); - return dftMeshName; -} - -double vtkMEDReader::PublishTimeStepsIfNeeded(vtkInformation *outInfo, bool& isUpdated) -{ - if(!this->Internal) - return 0.0; - - int lev0(-1); - std::vector tsteps; - if(!this->Internal->IsStdOrMode) - tsteps=this->Internal->Tree.getTimeSteps(lev0,this->Internal->TK); - else - { tsteps.resize(1); tsteps[0]=0.; } - isUpdated=false; - if(lev0!=this->Internal->LastLev0) - { - isUpdated=true; - double timeRange[2]; - timeRange[0]=tsteps.front(); - timeRange[1]=tsteps.back(); - outInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_STEPS(),&tsteps[0],(int)tsteps.size()); - outInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_RANGE(),timeRange,2); - this->Internal->LastLev0=lev0; - } - return tsteps.front(); -} - -void vtkMEDReader::FillMultiBlockDataSetInstance(vtkMultiBlockDataSet *output, double reqTS, ExportedTinyInfo *internalInfo) -{ - if( !this->Internal ) - return; - vtkDataSet *ret(RetrieveDataSetAtTime(reqTS,internalInfo)); - output->SetBlock(0,ret); - ret->Delete(); -} - -vtkDataSet *vtkMEDReader::RetrieveDataSetAtTime(double reqTS, ExportedTinyInfo *internalInfo) -{ - if( !this->Internal ) - return 0; - std::string meshName; - vtkDataSet *ret(this->Internal->Tree.buildVTKInstance(this->Internal->IsStdOrMode,reqTS,meshName,this->Internal->TK,internalInfo)); - if(this->Internal->GenerateVect) - { - vtkGenerateVectors::Operate(ret->GetPointData()); - vtkGenerateVectors::Operate(ret->GetCellData()); - vtkGenerateVectors::Operate(ret->GetFieldData()); - // The operations above have potentially created new arrays -> This breaks the optimization of StaticMesh that expects the same field arrays over time. - // To enforce the cache recomputation declare modification of mesh. - //vtkGenerateVectors::ChangeMeshTimeToUpdateCache(ret); - } - return ret; -} - -void vtkMEDReader::PrintSelf(ostream& os, vtkIndent indent) -{ - this->Superclass::PrintSelf(os, indent); -} diff --git a/src/Plugins/MEDReader/IO/vtkMEDReader.h b/src/Plugins/MEDReader/IO/vtkMEDReader.h deleted file mode 100644 index b5301817..00000000 --- a/src/Plugins/MEDReader/IO/vtkMEDReader.h +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Anthony Geay - -#ifndef __vtkMEDReader_h_ -#define __vtkMEDReader_h_ - -#include - -#include "vtkMultiBlockDataSetAlgorithm.h" -#include "vtkInformationGaussDoubleVectorKey.h" - -class vtkDataSet; -class vtkMutableDirectedGraph; -class vtkInformationDataObjectMetaDataKey; -class vtkInformationDoubleVectorKey; -class ExportedTinyInfo; - -class VTK_EXPORT vtkMEDReader : public vtkMultiBlockDataSetAlgorithm -{ - private: - vtkMEDReader(const vtkMEDReader&); // Not implemented. - void operator=(const vtkMEDReader&); // Not implemented. - public: - static vtkMEDReader *New(); - vtkTypeMacro(vtkMEDReader, vtkMultiBlockDataSetAlgorithm); - void PrintSelf(ostream& os, vtkIndent indent); - virtual void SetFileName(const char*); - virtual char *GetFileName(); - virtual const char *GetFileExtensions() { return ".med .rmed .sauv .sauve"; } - virtual const char *GetDescriptiveName() { return "MED file (Data Exchange Model)"; } - // - virtual void SetFieldsStatus(const char *name, int status); - virtual int GetNumberOfFieldsTreeArrays(); - virtual const char *GetFieldsTreeArrayName(int index); - virtual int GetFieldsTreeArrayStatus(const char *name); - // - virtual int GetTimesFlagsArrayStatus(const char *name); - virtual void SetTimesFlagsStatus(const char *name, int status); - virtual int GetNumberOfTimesFlagsArrays(); - virtual const char *GetTimesFlagsArrayName(int index); - //! Build the graph used to pass information to the client on the supports - virtual std::string BuildSIL(vtkMutableDirectedGraph*); - - // Description - // Reload will delete the internal reader and recreate it with default properties - virtual void Reload(); - - virtual int GetServerModifTime(); - // - virtual void GenerateVectors(int); - virtual void ChangeMode(int); - virtual void GhostCellGeneratorCallForPara(int); - static const char *GetSeparator(); - - // Description - // Static information key used to transfer the meta data graph along the pipeline - static vtkInformationDataObjectMetaDataKey* META_DATA(); - static vtkInformationGaussDoubleVectorKey* GAUSS_DATA(); - - protected: - vtkMEDReader(); - virtual ~vtkMEDReader(); - virtual int RequestInformation(vtkInformation*, vtkInformationVector**, vtkInformationVector*); - virtual int RequestData(vtkInformation*, vtkInformationVector**, vtkInformationVector*); - private: - void UpdateSIL(vtkInformation *request, vtkInformation *info); - virtual double PublishTimeStepsIfNeeded(vtkInformation*, bool& isUpdated); - virtual void FillMultiBlockDataSetInstance(vtkMultiBlockDataSet *output, double reqTS, ExportedTinyInfo *internalInfo=0); - vtkDataSet *RetrieveDataSetAtTime(double reqTS, ExportedTinyInfo *internalInfo); - private: - //BTX - //ETX - - class vtkMEDReaderInternal; - vtkMEDReaderInternal* Internal; -}; - -#endif //__vtkMEDReader_h_ diff --git a/src/Plugins/MEDReader/IO/vtkMEDReader2.cxx b/src/Plugins/MEDReader/IO/vtkMEDReader2.cxx deleted file mode 100644 index f4fdf8f3..00000000 --- a/src/Plugins/MEDReader/IO/vtkMEDReader2.cxx +++ /dev/null @@ -1,573 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Anthony Geay - -#include "vtkMEDReader.h" -#include "vtkGenerateVectors.h" - -#include "vtkMultiBlockDataSet.h" -#include "vtkInformation.h" -#include "vtkDataSetAttributes.h" -#include "vtkStringArray.h" -#include "vtkMutableDirectedGraph.h" -#include "vtkInformationStringKey.h" -// -#include "vtkUnsignedCharArray.h" -#include "vtkInformationVector.h" -#include "vtkSmartPointer.h" -#include "vtkVariantArray.h" -#include "vtkExecutive.h" -#include "vtkStreamingDemandDrivenPipeline.h" -#include "vtkMultiTimeStepAlgorithm.h" -#include "vtkUnstructuredGrid.h" -#include "vtkInformationQuadratureSchemeDefinitionVectorKey.h" -#include "vtkQuadratureSchemeDefinition.h" -#include "vtkPointData.h" -#include "vtkCellData.h" -#include "vtkCellType.h" -#include "vtkCellArray.h" -#include "vtkDoubleArray.h" -#include "vtkObjectFactory.h" -#ifdef MEDREADER_USE_MPI -#include "vtkMultiProcessController.h" -#endif - -#include "MEDFileFieldRepresentationTree.hxx" - -#include -#include -#include -#include -#include - -/*! - * This class stores properties in loading state mode (pvsm) when the MED file has not been read yet. - * The file is not read beacause FileName has not been informed yet ! So this class stores properties of vtkMEDReader instance that - * owns it and wait the vtkMEDReader::SetFileName to apply properties afterwards. - */ -class PropertyKeeper -{ -public: - PropertyKeeper(vtkMEDReader *master):_master(master),IsGVActivated(false),GVValue(0),IsCMActivated(false),CMValue(0) { } - void assignPropertiesIfNeeded(); - bool arePropertiesOnTreeToSetAfter() const; - // - void pushFieldStatusEntry(const char* name, int status); - void pushGenerateVectorsValue(int value); - void pushChangeModeValue(int value); - void pushTimesFlagsStatusEntry(const char* name, int status); -protected: - // pool of pairs to assign in SetFieldsStatus if needed. The use case is the load using pvsm. - std::vector< std::pair > SetFieldsStatusPairs; - // generate vector - bool IsGVActivated; - int GVValue; - // change mode - bool IsCMActivated; - int CMValue; - // - std::vector< std::pair > TimesFlagsStatusPairs; - vtkMEDReader *_master; -}; - -void PropertyKeeper::assignPropertiesIfNeeded() -{ - if(!this->SetFieldsStatusPairs.empty()) - { - for(std::vector< std::pair >::const_iterator it=this->SetFieldsStatusPairs.begin();it!=this->SetFieldsStatusPairs.end();it++) - _master->SetFieldsStatus((*it).first.c_str(),(*it).second); - this->SetFieldsStatusPairs.clear(); - } - if(!this->TimesFlagsStatusPairs.empty()) - { - for(std::vector< std::pair >::const_iterator it=this->TimesFlagsStatusPairs.begin();it!=this->TimesFlagsStatusPairs.end();it++) - _master->SetTimesFlagsStatus((*it).first.c_str(),(*it).second); - this->TimesFlagsStatusPairs.clear(); - } - if(this->IsGVActivated) - { - _master->GenerateVectors(this->GVValue); - this->IsGVActivated=false; - } - if(this->IsCMActivated) - { - _master->ChangeMode(this->CMValue); - this->IsCMActivated=false; - } -} - -void PropertyKeeper::pushFieldStatusEntry(const char* name, int status) -{ - bool found(false); - for(std::vector< std::pair >::const_iterator it=this->SetFieldsStatusPairs.begin();it!=this->SetFieldsStatusPairs.end() && !found;it++) - found=(*it).first==name; - if(!found) - this->SetFieldsStatusPairs.push_back(std::pair(name,status)); -} - -void PropertyKeeper::pushTimesFlagsStatusEntry(const char* name, int status) -{ - bool found(false); - for(std::vector< std::pair >::const_iterator it=this->TimesFlagsStatusPairs.begin();it!=this->TimesFlagsStatusPairs.end() && !found;it++) - found=(*it).first==name; - if(!found) - this->TimesFlagsStatusPairs.push_back(std::pair(name,status)); -} - -void PropertyKeeper::pushGenerateVectorsValue(int value) -{ - this->IsGVActivated=true; - this->GVValue=value; -} - -void PropertyKeeper::pushChangeModeValue(int value) -{ - this->IsCMActivated=true; - this->CMValue=value; -} - -bool PropertyKeeper::arePropertiesOnTreeToSetAfter() const -{ - return !SetFieldsStatusPairs.empty(); -} - -class vtkMEDReader::vtkMEDReaderInternal -{ - -public: - vtkMEDReaderInternal(vtkMEDReader *master):TK(0),IsMEDOrSauv(true),IsStdOrMode(false),GenerateVect(false),SIL(0),LastLev0(-1),FirstCall0(2),PK(master),MyMTime(0), ReloadReq(0) - { - } - - bool PluginStart0() - { - if(FirstCall0==0) - return false; - FirstCall0--; - return true; - } - - ~vtkMEDReaderInternal() - { - if(this->SIL) - this->SIL->Delete(); - } -public: - MEDFileFieldRepresentationTree Tree; - TimeKeeper TK; - std::string FileName; - //when true the file is MED file. when false it is a Sauv file - bool IsMEDOrSauv; - //when false -> std, true -> mode. By default std (false). - bool IsStdOrMode; - //when false -> do nothing. When true cut off or extend to nbOfCompo=3 vector arrays. - bool GenerateVect; - std::string DftMeshName; - // Store the vtkMutableDirectedGraph that represents links between family, groups and cell types - vtkMutableDirectedGraph* SIL; - // store the lev0 id in Tree corresponding to the TIME_STEPS in the pipeline. - int LastLev0; - // The property keeper is usable only in pvsm mode. - PropertyKeeper PK; - int MyMTime; - std::set _wonderful_set;// this set is used by SetFieldsStatus method to detect the fact that SetFieldsStatus has been called for all items ! Great Items are not sorted ! Why ? - std::map _wonderful_ref;// this map stores the state before a SetFieldsStatus status. - - int ReloadReq; -private: - unsigned char FirstCall0; -}; - -vtkStandardNewMacro(vtkMEDReader); - -vtkMEDReader::vtkMEDReader():Internal(new vtkMEDReaderInternal(this)) -{ - this->SetNumberOfInputPorts(0); - this->SetNumberOfOutputPorts(1); -} - -vtkMEDReader::~vtkMEDReader() -{ - delete this->Internal; -} - -void vtkMEDReader::Reload() -{ - this->Internal->ReloadReq = this->Internal->ReloadReq++; - std::cerr << "vtkMEDReader::Reload" << std::endl; - std::string fName((const char *)this->GetFileName()); - delete this->Internal; - this->Internal=new vtkMEDReaderInternal(this); - this->SetFileName(fName.c_str()); -} - -int vtkMEDReader::GetReloadReq() -{ - cout<<"Get Reload Req Null" <Internal->ReloadReq; - // this->Internal->ReloadReq = 0; - return ret;*/ -} -int vtkMEDReader::GetReloadReq(int a) -{ - cout<<"Get Reload Req:"<< a <Internal->ReloadReq; - // this->Internal->ReloadReq = 0; - return ret;*/ -} - -int vtkMEDReader::GetServerModifTime() -{ - return this->Internal->MyMTime; -} - -void vtkMEDReader::GenerateVectors(int val) -{ - if(this->Internal->FileName.empty()) - {//pvsm mode - this->Internal->PK.pushGenerateVectorsValue(val); - return ; - } - //not pvsm mode (general case) - bool val2((bool)val); - if(val2!=this->Internal->GenerateVect) - { - this->Internal->GenerateVect=val2; - this->Modified(); - } -} - -void vtkMEDReader::ChangeMode(int newMode) -{ - if(this->Internal->FileName.empty()) - {//pvsm mode - this->Internal->PK.pushChangeModeValue(newMode); - return ; - } - //not pvsm mode (general case) - this->Internal->IsStdOrMode=newMode!=0; - this->Modified(); -} - -const char *vtkMEDReader::GetSeparator() -{ - return MEDFileFieldRepresentationLeavesArrays::ZE_SEP; -} - -void vtkMEDReader::SetFileName(const char *fname) -{ - try - { - this->Internal->FileName=fname; - std::size_t pos(this->Internal->FileName.find_last_of('.')); - if(pos!=std::string::npos) - { - std::string ext(this->Internal->FileName.substr(pos)); - if(ext.find("sauv")!=std::string::npos) - this->Internal->IsMEDOrSauv=false; - } - if(this->Internal->Tree.getNumberOfLeavesArrays()==0) - { - int iPart(-1),nbOfParts(-1); -#ifdef MEDREADER_USE_MPI - vtkMultiProcessController *vmpc(vtkMultiProcessController::GetGlobalController()); - if(vmpc) - { - iPart=vmpc->GetLocalProcessId(); - nbOfParts=vmpc->GetNumberOfProcesses(); - } -#endif - this->Internal->Tree.loadMainStructureOfFile(this->Internal->FileName.c_str(),this->Internal->IsMEDOrSauv,iPart,nbOfParts); - if(!this->Internal->PK.arePropertiesOnTreeToSetAfter()) - this->Internal->Tree.activateTheFirst();//This line manually initialize the status of server (this) with the remote client. - this->Internal->TK.setMaxNumberOfTimeSteps(this->Internal->Tree.getMaxNumberOfTimeSteps()); - } - this->Modified(); - this->Internal->PK.assignPropertiesIfNeeded(); - } - catch(INTERP_KERNEL::Exception& e) - { - delete this->Internal; - this->Internal=0; - std::ostringstream oss; - oss << "Exception has been thrown in vtkMEDReader::SetFileName : " << e.what() << std::endl; - if(this->HasObserver("ErrorEvent") ) - this->InvokeEvent("ErrorEvent",const_cast(oss.str().c_str())); - else - vtkOutputWindowDisplayErrorText(const_cast(oss.str().c_str())); - vtkObject::BreakOnError(); - } -} - -char *vtkMEDReader::GetFileName() -{ - return const_cast(this->Internal->FileName.c_str()); -} - -int vtkMEDReader::RequestInformation(vtkInformation *request, vtkInformationVector **inputVector, vtkInformationVector *outputVector) -{ - std::cout << "########################################## RequestInformation ##########################################" << std::endl; - if(!this->Internal) - return 0; - try - { - vtkInformation *outInfo(outputVector->GetInformationObject(0)); - outInfo->Set(vtkDataObject::DATA_TYPE_NAME(),"vtkMultiBlockDataSet"); - this->UpdateSIL(outInfo); - // - bool dummy(false); - this->PublishTimeStepsIfNeeded(outInfo,dummy); - } - catch(INTERP_KERNEL::Exception& e) - { - std::ostringstream oss; - oss << "Exception has been thrown in vtkMEDReader::RequestInformation : " << e.what() << std::endl; - if(this->HasObserver("ErrorEvent") ) - this->InvokeEvent("ErrorEvent",const_cast(oss.str().c_str())); - else - vtkOutputWindowDisplayErrorText(const_cast(oss.str().c_str())); - vtkObject::BreakOnError(); - return 0; - } - return 1; -} - -int vtkMEDReader::RequestData(vtkInformation *request, vtkInformationVector **inputVector, vtkInformationVector *outputVector) -{ - std::cout << "########################################## RequestData ##########################################" << std::endl; - if(!this->Internal) - return 0; - try - { - vtkInformation *outInfo(outputVector->GetInformationObject(0)); - vtkMultiBlockDataSet *output(vtkMultiBlockDataSet::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT()))); - bool isUpdated(false); - double reqTS(0.); - if(outInfo->Has(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP())) - reqTS=outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP()); - this->FillMultiBlockDataSetInstance(output,reqTS); - output->GetInformation()->Set(vtkDataObject::DATA_TIME_STEP(),reqTS); - this->UpdateSIL(outInfo); - //this->UpdateProgress((float) progress/((float) maxprogress-1)); - } - catch(INTERP_KERNEL::Exception& e) - { - std::cerr << "Exception has been thrown in vtkMEDReader::RequestData : " << e.what() << std::endl; - return 0; - } - return 1; -} - -void vtkMEDReader::SetFieldsStatus(const char* name, int status) -{ - //this->Internal->_wonderful_set.insert(name); - if(this->Internal->FileName.empty()) - {//pvsm mode - this->Internal->PK.pushFieldStatusEntry(name,status); - return ; - } - if(this->Internal->_wonderful_set.empty()) - this->Internal->_wonderful_ref=this->Internal->Tree.dumpState();// start of SetFieldsStatus serie -> store ref to compare at the end of the SetFieldsStatus serie. - this->Internal->_wonderful_set.insert(name); - //not pvsm mode (general case) - try - { - this->Internal->Tree.changeStatusOfAndUpdateToHaveCoherentVTKDataSet(this->Internal->Tree.getIdHavingZeName(name),status); - if(this->Internal->_wonderful_set.size()==GetNumberOfFieldsTreeArrays()) - { - if(this->Internal->_wonderful_ref!=this->Internal->Tree.dumpState()) - { - if(!this->Internal->PluginStart0()) - { - this->Modified(); - } - this->Internal->MyMTime++; - } - this->Internal->_wonderful_set.clear(); - } - } - catch(INTERP_KERNEL::Exception& e) - { - if(!this->Internal->FileName.empty()) - { - std::cerr << "vtkMEDReader::SetFieldsStatus error : " << e.what() << " *** WITH STATUS=" << status << endl; - return ; - } - } -} - -int vtkMEDReader::GetNumberOfFieldsTreeArrays() -{ - if(!this->Internal) - return 0; -// std::cout << "vtkMEDReader::GetNumberOfFieldsTreeArrays called ! " << std::endl; - return this->Internal->Tree.getNumberOfLeavesArrays(); -} - -const char *vtkMEDReader::GetFieldsTreeArrayName(int index) -{ -// std::cout << "vtkMEDReader::GetFieldsTreeArrayName(" << index << ") called ! " << std::endl; - return this->Internal->Tree.getNameOfC(index); -} - -int vtkMEDReader::GetFieldsTreeArrayStatus(const char *name) -{ - int zeId(this->Internal->Tree.getIdHavingZeName(name)); - int ret(this->Internal->Tree.getStatusOf(zeId)); - return ret; -} - -void vtkMEDReader::SetTimesFlagsStatus(const char *name, int status) -{ - if(this->Internal->FileName.empty()) - {//pvsm mode - this->Internal->PK.pushTimesFlagsStatusEntry(name,status); - return ; - } - //not pvsm mode (general case) - int pos(0); - std::istringstream iss(name); iss >> pos; - this->Internal->TK.getTimesFlagArray()[pos].first=(bool)status; - if(pos==this->Internal->TK.getTimesFlagArray().size()-1) - if(!this->Internal->PluginStart0()) - { - this->Modified(); - //this->Internal->TK.printSelf(std::cerr); - } -} - -int vtkMEDReader::GetNumberOfTimesFlagsArrays() -{ - if(!this->Internal) - return 0; - return (int)this->Internal->TK.getTimesFlagArray().size(); -} - -const char *vtkMEDReader::GetTimesFlagsArrayName(int index) -{ - return this->Internal->TK.getTimesFlagArray()[index].second.c_str(); -} - -int vtkMEDReader::GetTimesFlagsArrayStatus(const char *name) -{ - int pos(0); - std::istringstream iss(name); iss >> pos; - return (int)this->Internal->TK.getTimesFlagArray()[pos].first; -} - -void vtkMEDReader::UpdateSIL(vtkInformation *info) -{ - if(!this->Internal) - return ; - vtkMutableDirectedGraph *sil(vtkMutableDirectedGraph::New()); - std::string meshName(this->BuildSIL(sil)); - if(meshName!=this->Internal->DftMeshName) - { - if(this->Internal->SIL) - this->Internal->SIL->Delete(); - this->Internal->SIL=sil; - this->Internal->DftMeshName=meshName; - info->Set(vtkDataObject::SIL(),this->Internal->SIL); - //request->AppendUnique(vtkExecutive::KEYS_TO_COPY(),vtkDataObject::SIL()); - } - else - { - sil->Delete(); - } -} - -/*! - * The returned string is the name of the mesh activated which groups and families are in \a sil. - */ -std::string vtkMEDReader::BuildSIL(vtkMutableDirectedGraph* sil) -{ - sil->Initialize(); - vtkSmartPointer childEdge(vtkSmartPointer::New()); - childEdge->InsertNextValue(0); - vtkSmartPointer crossEdge(vtkSmartPointer::New()); - crossEdge->InsertNextValue(1); - // CrossEdge is an edge linking hierarchies. - vtkUnsignedCharArray* crossEdgesArray=vtkUnsignedCharArray::New(); - crossEdgesArray->SetName("CrossEdges"); - sil->GetEdgeData()->AddArray(crossEdgesArray); - crossEdgesArray->Delete(); - std::vector names; - // Now build the hierarchy. - vtkIdType rootId=sil->AddVertex(); - names.push_back("SIL"); - // Add global fields root - vtkIdType fieldsRoot(sil->AddChild(rootId,childEdge)); - names.push_back("FieldsStatusTree"); - this->Internal->Tree.feedSIL(sil,fieldsRoot,childEdge,names); - vtkIdType meshesFamsGrpsRoot(sil->AddChild(rootId,childEdge)); - names.push_back("MeshesFamsGrps"); - std::string dftMeshName(this->Internal->Tree.feedSILForFamsAndGrps(sil,meshesFamsGrpsRoot,childEdge,names)); - // This array is used to assign names to nodes. - vtkStringArray *namesArray(vtkStringArray::New()); - namesArray->SetName("Names"); - namesArray->SetNumberOfTuples(sil->GetNumberOfVertices()); - sil->GetVertexData()->AddArray(namesArray); - namesArray->Delete(); - std::vector::const_iterator iter; - vtkIdType cc; - for(cc=0, iter=names.begin(); iter!=names.end(); ++iter, ++cc) - namesArray->SetValue(cc,(*iter).c_str()); - return dftMeshName; -} - -double vtkMEDReader::PublishTimeStepsIfNeeded(vtkInformation *outInfo, bool& isUpdated) -{ - int lev0(-1); - std::vector tsteps; - if(!this->Internal->IsStdOrMode) - tsteps=this->Internal->Tree.getTimeSteps(lev0,this->Internal->TK); - else - { tsteps.resize(1); tsteps[0]=0.; } - isUpdated=false; - if(lev0!=this->Internal->LastLev0) - { - isUpdated=true; - double timeRange[2]; - timeRange[0]=tsteps.front(); - timeRange[1]=tsteps.back(); - outInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_STEPS(),&tsteps[0],tsteps.size()); - outInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_RANGE(),timeRange,2); - this->Internal->LastLev0=lev0; - } - return tsteps.front(); -} - -void vtkMEDReader::FillMultiBlockDataSetInstance(vtkMultiBlockDataSet *output, double reqTS) -{ - std::string meshName; - vtkDataSet *ret(this->Internal->Tree.buildVTKInstance(this->Internal->IsStdOrMode,reqTS,meshName,this->Internal->TK)); - if(this->Internal->GenerateVect) - { - vtkGenerateVectors::Operate(ret->GetPointData()); - vtkGenerateVectors::Operate(ret->GetCellData()); - vtkGenerateVectors::Operate(ret->GetFieldData()); - } - output->SetBlock(0,ret); - ret->Delete(); -} - -void vtkMEDReader::PrintSelf(ostream& os, vtkIndent indent) -{ - this->Superclass::PrintSelf(os, indent); -} diff --git a/src/Plugins/MEDReader/IO/vtkMEDReader2.h b/src/Plugins/MEDReader/IO/vtkMEDReader2.h deleted file mode 100644 index e5d29013..00000000 --- a/src/Plugins/MEDReader/IO/vtkMEDReader2.h +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Anthony Geay - -#ifndef __vtkMEDReader_h_ -#define __vtkMEDReader_h_ - -#include - -#include "vtkMultiBlockDataSetAlgorithm.h" - -class vtkMutableDirectedGraph; - -class VTK_EXPORT vtkMEDReader : public vtkMultiBlockDataSetAlgorithm -{ - private: - vtkMEDReader(const vtkMEDReader&); // Not implemented. - void operator=(const vtkMEDReader&); // Not implemented. - public: - static vtkMEDReader *New(); - vtkTypeMacro(vtkMEDReader, vtkMultiBlockDataSetAlgorithm); - void PrintSelf(ostream& os, vtkIndent indent); - virtual void SetFileName(const char*); - virtual char *GetFileName(); - virtual const char *GetFileExtensions() { return ".med .rmed .sauv .sauve"; } - virtual const char *GetDescriptiveName() { return "MED file (Data Exchange Model)"; } - // - virtual void SetFieldsStatus(const char *name, int status); - virtual int GetNumberOfFieldsTreeArrays(); - virtual const char *GetFieldsTreeArrayName(int index); - virtual int GetFieldsTreeArrayStatus(const char *name); - // - virtual int GetTimesFlagsArrayStatus(const char *name); - virtual void SetTimesFlagsStatus(const char *name, int status); - virtual int GetNumberOfTimesFlagsArrays(); - virtual const char *GetTimesFlagsArrayName(int index); - //! Build the graph used to pass information to the client on the supports - virtual std::string BuildSIL(vtkMutableDirectedGraph*); - virtual void Reload(); - virtual int GetReloadReq(int a); - virtual int GetReloadReq(); - virtual int GetServerModifTime(); - // - virtual void GenerateVectors(int); - virtual void ChangeMode(int); - static const char *GetSeparator(); - - protected: - vtkMEDReader(); - virtual ~vtkMEDReader(); - virtual int RequestInformation(vtkInformation*, vtkInformationVector**, vtkInformationVector*); - virtual int RequestData(vtkInformation*, vtkInformationVector**, vtkInformationVector*); - private: - void UpdateSIL(vtkInformation *info); - virtual double PublishTimeStepsIfNeeded(vtkInformation*, bool& isUpdated); - virtual void FillMultiBlockDataSetInstance(vtkMultiBlockDataSet *output, double reqTS); - private: - //BTX - //ETX - class vtkMEDReaderInternal; - vtkMEDReaderInternal* Internal; -}; - -#endif //__vtkMEDReader_h_ diff --git a/src/Plugins/MEDReader/ParaViewPlugin/CMakeLists.txt b/src/Plugins/MEDReader/ParaViewPlugin/CMakeLists.txt deleted file mode 100644 index 5541c527..00000000 --- a/src/Plugins/MEDReader/ParaViewPlugin/CMakeLists.txt +++ /dev/null @@ -1,138 +0,0 @@ -# Copyright (C) 2010-2019 CEA/DEN, EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# - -INCLUDE_DIRECTORIES( - ${CMAKE_CURRENT_SOURCE_DIR}/../IO - ${CMAKE_CURRENT_SOURCE_DIR}/../../MEDWriter/IO - ) - -IF(PARAVIEW_BUILD_QT_GUI) - - QT_WRAP_UIC(CLIENT_UI_SRCS - Resources/UI/MEDReaderVectorsWidget.ui - Resources/UI/MEDReaderTimeModeWidget.ui) - - # create a plugin that implements an object panel for the reader - SET(SM_SRCS - vtkPVMetaDataInformation.cxx - ${PROJECT_SOURCE_DIR}/IO/vtkMEDReader.cxx - ${PROJECT_SOURCE_DIR}/IO/vtkExtractGroup.cxx - ${PROJECT_SOURCE_DIR}/IO/vtkELNOMeshFilter.cxx - ${PROJECT_SOURCE_DIR}/IO/vtkELNOSurfaceFilter.cxx - ${PROJECT_SOURCE_DIR}/IO/vtkELNOFilter.cxx - ${PROJECT_SOURCE_DIR}/IO/vtkExtractCellType.cxx - ${PROJECT_SOURCE_DIR}/IO/vtkMEDQuadraturePointsGenerator.cxx - ) - - SET(CLIENT_SRCS - pqExtractGroupFieldsWidget.cxx - pqAbstractFieldsWidget.cxx - VectBoolSpreadSheet.cxx - VectBoolWidget.cxx - pqMEDReaderGraphUtils.cxx - pqMEDReaderVectorsWidget.cxx - pqMEDReaderTimeModeWidget.cxx - pqMEDReaderReloadWidget.cxx - pqMEDReaderTimesFlagsWidget.cxx - pqMEDReaderFieldsWidget.cxx) - - QT_WRAP_MOC(MOC_SRCS - pqExtractGroupFieldsWidget.h - pqAbstractFieldsWidget.h - VectBoolSpreadSheet.h - VectBoolWidget.h - pqMEDReaderVectorsWidget.h - pqMEDReaderTimeModeWidget.h - pqMEDReaderReloadWidget.h - pqMEDReaderTimesFlagsWidget.h - pqMEDReaderFieldsWidget.h) - - ADD_PARAVIEW_PROPERTY_WIDGET(MEDREADER_TIMEMODE_IFACES MEDREADER_TIMEMODE_IFACE_SRCS - TYPE "MEDReaderTimeModeWidgetType" - CLASS_NAME pqMEDReaderTimeModeWidget) - - ADD_PARAVIEW_PROPERTY_WIDGET(MEDREADER_RELOAD_IFACES MEDREADER_RELOAD_IFACE_SRCS - TYPE "MEDReaderReloadWidgetType" - CLASS_NAME pqMEDReaderReloadWidget) - - ADD_PARAVIEW_PROPERTY_WIDGET(MEDREADER_VECTORS_IFACES MEDREADER_VECTORS_IFACE_SRCS - TYPE "MEDReaderVectorsWidgetType" - CLASS_NAME pqMEDReaderVectorsWidget) - - ADD_PARAVIEW_PROPERTY_WIDGET(MEDREADER_TIMESFLAGS_IFACES MEDREADER_TIMESFLAGS_IFACE_SRCS - TYPE "MEDReaderTimesFlagsWidgetType" - CLASS_NAME pqMEDReaderTimesFlagsWidget) - - ADD_PARAVIEW_PROPERTY_WIDGET(MEDREADER_FIELDS_IFACES MEDREADER_FIELDS_IFACE_SRCS - TYPE "MEDReaderFieldsWidgetType" - CLASS_NAME pqMEDReaderFieldsWidget) - - ADD_PARAVIEW_PROPERTY_WIDGET(EXTRACTGROUP_FIELDS_IFACES EXTRACTGROUP_FIELDS_IFACES_SRCS - TYPE "ExtractGroupFieldsWidgetType" - CLASS_NAME pqExtractGroupFieldsWidget) - - # create the med reader plugin itself - ADD_PARAVIEW_PLUGIN(MEDReaderPlugin "4.0" - SERVER_MANAGER_SOURCES ${SM_SRCS} - SERVER_MANAGER_XML Resources/MEDReaderServer.xml - GUI_INTERFACES - ${MEDREADER_TIMEMODE_IFACES} - ${MEDREADER_RELOAD_IFACES} - ${MEDREADER_TIMESFLAGS_IFACES} - ${MEDREADER_FIELDS_IFACES} - ${MEDREADER_VECTORS_IFACES} - ${EXTRACTGROUP_FIELDS_IFACES} - GUI_RESOURCES Resources/pqMEDReader.qrc - SOURCES - ${CLIENT_SRCS} - ${CLIENT_UI_SRCS} - ${MOC_SRCS} - ${MEDREADER_TIMEMODE_IFACE_SRCS} - ${MEDREADER_RELOAD_IFACE_SRCS} - ${MEDREADER_TIMESFLAGS_IFACE_SRCS} - ${MEDREADER_FIELDS_IFACE_SRCS} - ${MEDREADER_VECTORS_IFACE_SRCS} - ${EXTRACTGROUP_FIELDS_IFACES_SRCS} - ) - -ELSE(PARAVIEW_BUILD_QT_GUI) - - # create the med reader plugin itself - ADD_PARAVIEW_PLUGIN(MEDReaderPlugin "4.0" - SERVER_MANAGER_SOURCES ${SM_SRCS} - SERVER_MANAGER_XML Resources/MEDReaderServer.xml - CS_KITS - # this is the same name as the name in module.cmake file IO - # directory. - vtkMEDReader - ) - -ENDIF(PARAVIEW_BUILD_QT_GUI) - -TARGET_LINK_LIBRARIES(MEDReaderPlugin MEDLoaderForPV) - -# Install -INSTALL( - TARGETS MEDReaderPlugin - RUNTIME DESTINATION lib/paraview - LIBRARY DESTINATION lib/paraview - ARCHIVE DESTINATION lib/paraview - ) - - diff --git a/src/Plugins/MEDReader/ParaViewPlugin/Resources/Icons/pqCellData16.png b/src/Plugins/MEDReader/ParaViewPlugin/Resources/Icons/pqCellData16.png deleted file mode 100644 index 8a6f2a6c..00000000 Binary files a/src/Plugins/MEDReader/ParaViewPlugin/Resources/Icons/pqCellData16.png and /dev/null differ diff --git a/src/Plugins/MEDReader/ParaViewPlugin/Resources/Icons/pqCellDataForWholeMesh16.png b/src/Plugins/MEDReader/ParaViewPlugin/Resources/Icons/pqCellDataForWholeMesh16.png deleted file mode 100644 index 93401f4c..00000000 Binary files a/src/Plugins/MEDReader/ParaViewPlugin/Resources/Icons/pqCellDataForWholeMesh16.png and /dev/null differ diff --git a/src/Plugins/MEDReader/ParaViewPlugin/Resources/Icons/pqElnoData16.png b/src/Plugins/MEDReader/ParaViewPlugin/Resources/Icons/pqElnoData16.png deleted file mode 100644 index e4618100..00000000 Binary files a/src/Plugins/MEDReader/ParaViewPlugin/Resources/Icons/pqElnoData16.png and /dev/null differ diff --git a/src/Plugins/MEDReader/ParaViewPlugin/Resources/Icons/pqPointData16.png b/src/Plugins/MEDReader/ParaViewPlugin/Resources/Icons/pqPointData16.png deleted file mode 100644 index 50367eaa..00000000 Binary files a/src/Plugins/MEDReader/ParaViewPlugin/Resources/Icons/pqPointData16.png and /dev/null differ diff --git a/src/Plugins/MEDReader/ParaViewPlugin/Resources/Icons/pqQuadratureData16.png b/src/Plugins/MEDReader/ParaViewPlugin/Resources/Icons/pqQuadratureData16.png deleted file mode 100644 index ff6e1995..00000000 Binary files a/src/Plugins/MEDReader/ParaViewPlugin/Resources/Icons/pqQuadratureData16.png and /dev/null differ diff --git a/src/Plugins/MEDReader/ParaViewPlugin/Resources/Icons/pqReloadFile16.png b/src/Plugins/MEDReader/ParaViewPlugin/Resources/Icons/pqReloadFile16.png deleted file mode 100644 index cc13970b..00000000 Binary files a/src/Plugins/MEDReader/ParaViewPlugin/Resources/Icons/pqReloadFile16.png and /dev/null differ diff --git a/src/Plugins/MEDReader/ParaViewPlugin/Resources/MEDReaderServer.xml b/src/Plugins/MEDReader/ParaViewPlugin/Resources/MEDReaderServer.xml deleted file mode 100644 index 807df538..00000000 --- a/src/Plugins/MEDReader/ParaViewPlugin/Resources/MEDReaderServer.xml +++ /dev/null @@ -1,464 +0,0 @@ - - - - - - - - - - - - - - - This property specifies the file name for the MED reader. - - - - - - - - - - - - - - - - - - - - This property lists all the fields sorted by time steps then by mesh then by common support. - - - - - - This property define if the reader generate vectors. - - - - - - This property define if the reader read time steps as modes or not. - - - - - - - This property specifies the file name for the MED reader. - - - - - - - Available timestep values. - - - - - - - - - - - - - - - This property define which time steps the reader should read. - - - - - - - - - - - This property tells if ghost cell generator is applied in parallel mode right after MED file read. This call has a CPU cost but it avoids viz artefacts (interfaces inside dataset on domain borders) you can experiment during usage of filters sensitive to ghost cells in // mode (Ex transparency, contour...). - - - - - - - - - - - - - - - - - - - This property specifies the input to the Level Scalars filter. - - - - - - - - - - - - - - - This property lists all groups and families to select. - - - - - - Choose which part of the dataset to keep regarding the selected Groups/Families. When 0 (default) the direct selection - is kept. When 1 the complementary part is selected. - - - - - - This property returns the name of the mesh. - - - - - - - - - - - - - - - - - - This property specifies the input to the Level Scalars filter. - - - - - - - - - - - - - - - This property lists all the geometric types to select. - - - - - Choose which part of the dataset to keep regarding the selected geometric types. When 0 (default) the direct selection - is kept. When 1 the complementary part is selected. - - - - - - - "Create a Mesh with ELNO values mapped at each vertex." - - - - - - - - - - - - - - - - The value of this property determines how far the points - will move in the mesh before to be colored using ELNO fields on it. A value of 0 positions the points at the centroid of the cell; a value of 1 leaves them at their original positions. - - - - - - - - - "Extract the surface of a dataset with ELNO values." - - - - - - - - - - - - - - - - - Specifies the offset array from which we generate ELNO points. - - - - - - - - - - - - - - - - - "Create a point set with data at quadrature points." - - - - - - - - - - - - - - - - - - - Specifies the offset array from which we generate Gauss points. - - - - - - - - - - - - - - - - - - - "Create a point set with data at quadrature points." - - - - - - - - - - - - - - - - - - - Specifies the offset array from which we generate ELNO points. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - This property specifies the input to the Generate Structural Element filter. - - - - - - diff --git a/src/Plugins/MEDReader/ParaViewPlugin/Resources/UI/MEDReaderTimeModeWidget.ui b/src/Plugins/MEDReader/ParaViewPlugin/Resources/UI/MEDReaderTimeModeWidget.ui deleted file mode 100644 index 419d1e7b..00000000 --- a/src/Plugins/MEDReader/ParaViewPlugin/Resources/UI/MEDReaderTimeModeWidget.ui +++ /dev/null @@ -1,37 +0,0 @@ - - - MEDReaderTimeModeWidget - - - - - - true - - - - - - - - - Time - - - true - - - - - - - Mode - - - - - - - - - diff --git a/src/Plugins/MEDReader/ParaViewPlugin/Resources/UI/MEDReaderVectorsWidget.ui b/src/Plugins/MEDReader/ParaViewPlugin/Resources/UI/MEDReaderVectorsWidget.ui deleted file mode 100644 index c9424273..00000000 --- a/src/Plugins/MEDReader/ParaViewPlugin/Resources/UI/MEDReaderVectorsWidget.ui +++ /dev/null @@ -1,39 +0,0 @@ - - - MEDReaderVectorsWidget - - - - 0 - - - 0 - - - - - true - - - - - - - 0 - - - 0 - - - - - GenerateVectors - - - - - - - - - diff --git a/src/Plugins/MEDReader/ParaViewPlugin/Resources/pqMEDReader.qrc b/src/Plugins/MEDReader/ParaViewPlugin/Resources/pqMEDReader.qrc deleted file mode 100644 index 1006ebf7..00000000 --- a/src/Plugins/MEDReader/ParaViewPlugin/Resources/pqMEDReader.qrc +++ /dev/null @@ -1,10 +0,0 @@ - - - Icons/pqCellData16.png - Icons/pqPointData16.png - Icons/pqQuadratureData16.png - Icons/pqElnoData16.png - Icons/pqReloadFile16.png - Icons/pqCellDataForWholeMesh16.png - - diff --git a/src/Plugins/MEDReader/ParaViewPlugin/VectBoolSpreadSheet.cxx b/src/Plugins/MEDReader/ParaViewPlugin/VectBoolSpreadSheet.cxx deleted file mode 100644 index 4bd937fc..00000000 --- a/src/Plugins/MEDReader/ParaViewPlugin/VectBoolSpreadSheet.cxx +++ /dev/null @@ -1,300 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Anthony Geay - -#include "VectBoolSpreadSheet.h" -#include -#include -#include -#include -#include - -VectBoolModel::VectBoolModel(int maxSize, int nbRows):_activated(maxSize,false),_nb_rows(nbRows) -{ - setCurSize(maxSize); -} - -int VectBoolModel::rowCount(const QModelIndex &) const -{ - return _nb_rows; -} - -int VectBoolModel::columnCount (const QModelIndex &) const -{ - int sz(curSize()); - if(sz%_nb_rows==0) - return sz/_nb_rows; - else - return sz/_nb_rows+1; -} - -QVariant VectBoolModel::headerData(int section, Qt::Orientation orientation, int role) const -{ - if(role==Qt::FontRole) - { - QFont serifFont("Arial",6, QFont::Bold); - return QVariant(serifFont); - } - else if(role==Qt::DisplayRole) - { - return QVariant(section); - } - else - return QAbstractTableModel::headerData(section,orientation,role); -} - -bool VectBoolModel::setData(const QModelIndex& index, const QVariant& value, int role) -{ - if(role==Qt::UserRole) - { - int pos(index.column()*_nb_rows+index.row()); - bool v(_activated[pos]); - _activated[pos]=!v; - emit nbOfTimeStepsOnChanged((int)getNbOfActivatedTimeSteps(),_dts.size()); - return true; - } - else - return QAbstractTableModel::setData(index,value,role); -} - -QVariant VectBoolModel::data(const QModelIndex &index, int role) const -{ - if(role==Qt::FontRole) - { - QFont serifFont("Arial",8);//, QFont::Bold); - return QVariant(serifFont); - } - else if(role==Qt::UserRole) - { - int pos(index.column()*_nb_rows+index.row()); - return QVariant(_activated[pos]); - } - else if(role==Qt::DisplayRole) - { - int pos(index.column()*_nb_rows+index.row()); - if(pos=curSize()) - return QVariant(); - if(_activated[pos]) - { - QBrush b(QColor(0,255,0)); - return QVariant(b); - } - else - { - QBrush b(QColor(255,0,0)); - return QVariant(b); - } - } - else - return QVariant(); -} - -bool VectBoolModel::setCurrentItems(const QStringList& dts, const QStringList& its, const QStringList& tts) -{ - int oldSize(curSize()); - if(oldSize!=dts.size()) - { - emit layoutAboutToBeChanged(); - _dts=dts; _its=its; _tts=tts; - emit layoutChanged(); - return true; - } - else - { - _dts=dts; _its=its; _tts=tts; - return false; - } - -} - -void VectBoolModel::setNumberOfRows(int newNbOfRows) -{ - if(newNbOfRows!=_nb_rows) - { - emit beginResetModel(); - _nb_rows=newNbOfRows; - emit endResetModel(); - } -} - -void VectBoolModel::selectUnselectAll() -{ - int nbOn(getNbOfActivatedTimeSteps()),sz(curSize()),signalVal(0); - emit layoutAboutToBeChanged(); - if(nbOn>sz/2) - { - for(int ii=0;iihorizontalHeader()->setMinimumSectionSize(2); - this->horizontalHeader()->setDefaultSectionSize(2); - this->verticalHeader()->setMinimumSectionSize(2); - this->verticalHeader()->setDefaultSectionSize(2); - this->setItemDelegate(_delegate); - this->verticalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); - this->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); - - this->resizeColumnsToContents(); - this->resizeRowsToContents(); - //this->verticalHeader()->hide(); - //this->horizontalHeader()->hide(); -} - -void VectBoolSpreadSheet::selectionChanged(const QItemSelection & selected, const QItemSelection & deselected) -{ - QAbstractItemModel * m(model()); - foreach(const QModelIndex& ind,selected.indexes()) - { - m->setData(ind,QVariant(true),Qt::UserRole); - } - QTableView::selectionChanged(selected,deselected); - this->clearSelection(); -} - -void VectBoolSpreadSheet::nbOfRowsHasChanged(int newNbOfRows) -{ - VectBoolModel *zeModel(qobject_cast(model())); - if(!zeModel) - return ; - zeModel->setNumberOfRows(newNbOfRows); - this->verticalHeader()->setUpdatesEnabled(true);//please let this line. If not a refresh problem appear at EDF configuration. -} - -void VectBoolSpreadSheet::selectUnselectAllFired() -{ - VectBoolModel *zeModel(qobject_cast(model())); - if(!zeModel) - return ; - zeModel->selectUnselectAll(); -} - -/////////////// - -OnOffDelegate::OnOffDelegate(QObject *parent):QStyledItemDelegate(parent) -{ -} - -void OnOffDelegate::paint(QPainter *painter, const QStyleOptionViewItem & option, const QModelIndex& index) const -{ - painter->save(); - const QAbstractItemModel *zeModel(index.model()); - QString cont(zeModel->data(index,Qt::DisplayRole).toString()); - bool checked(zeModel->data(index,Qt::UserRole).toBool()); - QFont font; - if(checked) - { - QFont zeFont(zeModel->data(index,Qt::FontRole).value()); - zeFont.setBold(true); - font=zeFont; - } - else - { - font=QFont("Arial",7); - font.setItalic(true); - } - painter->setFont(font); - Qt::Alignment al((Qt::Alignment)zeModel->data(index,Qt::TextAlignmentRole).toInt()); - if(checked) - {//sizeHint - //painter->drawEllipse(option.rect); - //painter->setBrush(QBrush(Qt::lightGray,Qt::Dense6Pattern)); - painter->setBrush(QBrush(QColor(230,230,255))); - painter->drawRect(option.rect); - //painter->drawLine(option.rect.topLeft(),option.rect.bottomRight()); - //painter->drawLine(option.rect.topRight(),option.rect.bottomLeft()); - } - else - { - painter->setBrush(QBrush(QColor(255,255,255))); - painter->drawRect(option.rect); - painter->setPen(Qt::lightGray); - } - painter->drawText(option.rect,cont,QTextOption(al)); - painter->restore(); -} diff --git a/src/Plugins/MEDReader/ParaViewPlugin/VectBoolSpreadSheet.h b/src/Plugins/MEDReader/ParaViewPlugin/VectBoolSpreadSheet.h deleted file mode 100644 index 82d06b9e..00000000 --- a/src/Plugins/MEDReader/ParaViewPlugin/VectBoolSpreadSheet.h +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Anthony Geay - -#include -#include -#include -#include -#include -#include - -class OnOffDelegate : public QStyledItemDelegate//QItemDelegate -{ - Q_OBJECT - public: - OnOffDelegate(QObject *parent=0); - void paint(QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index) const; -}; - -class VectBoolSpreadSheet : public QTableView -{ - Q_OBJECT -public: - VectBoolSpreadSheet(QWidget *parent); - ~VectBoolSpreadSheet(); - void init(); - void selectionChanged(const QItemSelection & selected, const QItemSelection & deselected); -public slots: - void nbOfRowsHasChanged(int newNbOfRows); - void selectUnselectAllFired(); -private: - OnOffDelegate *_delegate; -}; - -class VectBoolModel : public QAbstractTableModel -{ - Q_OBJECT -public: - VectBoolModel(int maxSize, int nbRows); - std::size_t getSize() const { return _activated.size(); } - bool getStatusAt(int pos) const { return _activated[pos]; } - void setStatusAt(int pos, bool val) { _activated[pos]=val; } - int rowCount( const QModelIndex & parent = QModelIndex() ) const; - int columnCount ( const QModelIndex & parent = QModelIndex() ) const; - bool setData(const QModelIndex & index, const QVariant & value, int role = Qt::EditRole ); - QVariant data(const QModelIndex &index, int role) const; - QVariant headerData ( int section, Qt::Orientation orientation, int role = Qt::DisplayRole ) const; - // non const methods. - bool setCurrentItems(const QStringList& dts, const QStringList& its, const QStringList& tts); - int getNbOfActivatedTimeSteps() const; -public: - void setNumberOfRows(int newNbOfRows); - void selectUnselectAll(); -signals: - void nbOfTimeStepsOnChanged(int newNbOfTimeStepsOn, int totalNbOfTS); -private: - void setCurSize(int sz); - int curSize() const; -private: - std::vector _activated; - QStringList _dts,_its,_tts; - int _cur_size; - int _nb_rows; -}; diff --git a/src/Plugins/MEDReader/ParaViewPlugin/VectBoolWidget.cxx b/src/Plugins/MEDReader/ParaViewPlugin/VectBoolWidget.cxx deleted file mode 100644 index 24c7aead..00000000 --- a/src/Plugins/MEDReader/ParaViewPlugin/VectBoolWidget.cxx +++ /dev/null @@ -1,197 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Anthony Geay - -#include "VectBoolWidget.h" -#include "VectBoolSpreadSheet.h" - -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -NbOfActiveTSDisplay::NbOfActiveTSDisplay(QWidget *parent):QLabel(parent),_nb_of_items_on(0),_total_nb_of_items(0) -{ - setFont(QFont("Arial",8,QFont::Bold)); - setTextFormat(Qt::AutoText); -} - - void NbOfActiveTSDisplay::display(int nbOfItemsOn, int totalNbOfItems) -{ - _nb_of_items_on=nbOfItemsOn; - _total_nb_of_items=totalNbOfItems; - setText(QString("%1/%2").arg(_nb_of_items_on).arg(_total_nb_of_items)); -} - -void NbOfActiveTSDisplay::totalNbOfItemsChanged(int totalNbOfItems) -{ - _total_nb_of_items=totalNbOfItems; - setText(QString("%1/%2").arg(_nb_of_items_on).arg(_total_nb_of_items)); -} - -VectBoolItem::VectBoolItem(QObject *parent, int pos, VectBoolModel *model):QObject(parent),_pos(pos),_old_status(true),_model(model) -{ -} - -bool VectBoolItem::isActivated() const -{ - return _model->getStatusAt(_pos); -} - -void VectBoolItem::activated(bool val) -{ - _model->setStatusAt(_pos,val); - _old_status=val; -} - -void VectBoolItem::theModelHasChanged() -{ - bool val(isActivated()); - if(val!=_old_status) - { - _old_status=val; - emit changed(); - } -} - -VectBoolWidget::VectBoolWidget(QWidget *parent, int nbOfItems):QFrame(parent) -{ - QSizePolicy sizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding); - sizePolicy.setHorizontalStretch(0); - sizePolicy.setVerticalStretch(0); - sizePolicy.setHeightForWidth(this->sizePolicy().hasHeightForWidth()); - this->setSizePolicy(sizePolicy); - this->setFrameShape(QFrame::StyledPanel); - this->setFrameShadow(QFrame::Raised); - _horizontal_layout=new QHBoxLayout(this); - _horizontal_layout->setSpacing(6); - _horizontal_layout->setContentsMargins(11,11,11,11); - _spreadsheet_container=new QFrame(this); - QSizePolicy sizePolicy1(QSizePolicy::Expanding,QSizePolicy::Expanding); - sizePolicy1.setHorizontalStretch(0); - sizePolicy1.setVerticalStretch(0); - sizePolicy1.setHeightForWidth(_spreadsheet_container->sizePolicy().hasHeightForWidth()); - _spreadsheet_container->setSizePolicy(sizePolicy1); - _grid_layout=new QGridLayout(_spreadsheet_container); - _grid_layout->setSpacing(6); - _grid_layout->setContentsMargins(11,11,11,11); - _horizontal_layout->addWidget(_spreadsheet_container); - _group_box=new QGroupBox(this); - QSizePolicy sizePolicy2(QSizePolicy::Minimum, QSizePolicy::Expanding); - sizePolicy2.setHorizontalStretch(0); - sizePolicy2.setVerticalStretch(0); - sizePolicy2.setHeightForWidth(_group_box->sizePolicy().hasHeightForWidth()); - _group_box->setSizePolicy(sizePolicy2); - // - _vertical_layout=new QVBoxLayout(_group_box); - _vertical_layout->setSpacing(6); - _vertical_layout->setContentsMargins(11,11,11,11); - _nb_of_time_steps_on=new NbOfActiveTSDisplay(_group_box); - _nb_of_time_steps_on->setMaximumSize(QSize(40,16777215)); - _vertical_layout->addWidget(_nb_of_time_steps_on); - _nb_of_rows_selecter=new QSlider(_group_box); - QSizePolicy sizePolicy3(QSizePolicy::Expanding,QSizePolicy::Expanding); - sizePolicy3.setHorizontalStretch(0); - sizePolicy3.setVerticalStretch(0); - sizePolicy3.setHeightForWidth(_nb_of_rows_selecter->sizePolicy().hasHeightForWidth()); - _nb_of_rows_selecter->setSizePolicy(sizePolicy3); - _nb_of_rows_selecter->setOrientation(Qt::Vertical); - _vertical_layout->addWidget(_nb_of_rows_selecter); - _sel_unsel_all=new QPushButton(_group_box); - _sel_unsel_all->setMaximumSize(QSize(40,16777215)); - _sel_unsel_all->setText(QString("Sel All")); - QFont font("Andale Mono"); - font.setPointSize(5); - _sel_unsel_all->setFont(font); - _vertical_layout->addWidget(_sel_unsel_all); - // - _horizontal_layout->addWidget(_group_box); - // - _vbw=new VectBoolSpreadSheet(_spreadsheet_container); - QSizePolicy sizePolicy4(QSizePolicy::Expanding,QSizePolicy::Expanding); - sizePolicy4.setHorizontalStretch(0); - sizePolicy4.setVerticalStretch(0); - sizePolicy4.setHeightForWidth(_vbw->sizePolicy().hasHeightForWidth()); - _vbw->setSizePolicy(sizePolicy4); - _nb_of_rows_selecter->setSizePolicy(sizePolicy3); - _nb_of_rows_selecter->setMinimum(1); - _nb_of_rows_selecter->setMaximum(GetMaxTickValueOfSlider(nbOfItems)); - _nb_of_rows_selecter->setTickInterval(1); - _nb_of_rows_selecter->setTickPosition(QSlider::TicksRight); - connect(_nb_of_rows_selecter,SIGNAL(valueChanged(int)),_vbw,SLOT(nbOfRowsHasChanged(int))); - connect(_sel_unsel_all,SIGNAL(clicked()),_vbw,SLOT(selectUnselectAllFired())); - _grid_layout->addWidget(_vbw); - _vbw->init(); - _vbm=new VectBoolModel(nbOfItems,1); - _vbw->setModel(_vbm); - connect(this->_vbm,SIGNAL(nbOfTimeStepsOnChanged(int,int)),_nb_of_time_steps_on,SLOT(display(int,int))); - _vbm->selectUnselectAll(); - _nb_of_rows_selecter->setValue(_nb_of_rows_selecter->maximum()); - // - for(int i=0;igetNumberOfBoolItems()) - { - std::cerr << "ERROR ! Internal Error in VectBoolWidget::setItems ! Current number of items is bigger than the current one !" << std::endl; - std::cerr << curNbOfItems << " "<setCurrentItems(dts,its,tts)) - { - _nb_of_rows_selecter->setMaximum(GetMaxTickValueOfSlider(curNbOfItems)); - _nb_of_rows_selecter->setValue(_nb_of_rows_selecter->maximum()); - _nb_of_time_steps_on->display(_vbm->getNbOfActivatedTimeSteps(),dts.size()); - } -} - -int VectBoolWidget::getNumberOfBoolItems() const -{ - return (int)_vbm->getSize(); -} - -int VectBoolWidget::GetMaxTickValueOfSlider(int val) -{ - double valf((double)val); - double ret(sqrt(valf)); - int reti((int)ret); - if(reti*reti==val) - return reti; - else - return reti+1; -} - -VectBoolWidget::~VectBoolWidget() -{ - delete _vbm; -} diff --git a/src/Plugins/MEDReader/ParaViewPlugin/VectBoolWidget.h b/src/Plugins/MEDReader/ParaViewPlugin/VectBoolWidget.h deleted file mode 100644 index b0cc0567..00000000 --- a/src/Plugins/MEDReader/ParaViewPlugin/VectBoolWidget.h +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Anthony Geay - -#ifndef __VECTBOOLWIDGET_H__ -#define __VECTBOOLWIDGET_H__ - -#include -#include -#include - -class QSlider; -class QGroupBox; -class QHBoxLayout; -class QVBoxLayout; -class QGridLayout; -class QPushButton; -class VectBoolModel; -class VectBoolSpreadSheet; - -class NbOfActiveTSDisplay : public QLabel -{ -Q_OBJECT -public: - NbOfActiveTSDisplay(QWidget *parent=0); -public slots: - void display(int nbOfItemsOn, int totalNbOfItems); - void totalNbOfItemsChanged(int totalNbOfItems); -private: - int _nb_of_items_on; - int _total_nb_of_items; -}; - -class VectBoolItem : public QObject -{ -Q_OBJECT -Q_PROPERTY(bool activated READ isActivated WRITE activated) -public: - VectBoolItem(QObject *parent, int pos, VectBoolModel *model); - bool isActivated() const; - void activated(bool val); -public slots: - void theModelHasChanged(); -signals: - void changed(); -private: - int _pos; - mutable bool _old_status; - VectBoolModel *_model; -}; - -class VectBoolWidget : public QFrame -{ -public: - VectBoolWidget(QWidget *parent, int nbOfItems); - ~VectBoolWidget(); - int getNumberOfBoolItems() const; - void setItems(const QStringList& dts, const QStringList& its, const QStringList& tts); - const QMap& getItems() const { return _items; } -private: - static int GetMaxTickValueOfSlider(int val); -private: - QMap _items; - QHBoxLayout *_horizontal_layout; - QFrame *_spreadsheet_container; - QGridLayout *_grid_layout; - QGroupBox *_group_box; - QVBoxLayout *_vertical_layout; - NbOfActiveTSDisplay *_nb_of_time_steps_on; - QSlider *_nb_of_rows_selecter; - QPushButton *_sel_unsel_all; - VectBoolSpreadSheet *_vbw; - VectBoolModel *_vbm; -}; - -#endif diff --git a/src/Plugins/MEDReader/ParaViewPlugin/pqAbstractFieldsWidget.cxx b/src/Plugins/MEDReader/ParaViewPlugin/pqAbstractFieldsWidget.cxx deleted file mode 100644 index cdaae619..00000000 --- a/src/Plugins/MEDReader/ParaViewPlugin/pqAbstractFieldsWidget.cxx +++ /dev/null @@ -1,147 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Anthony Geay - -#include "pqAbstractFieldsWidget.h" - -#include "pqArrayListDomain.h" -#include "pqTreeWidget.h" -#include "pqTreeWidgetItemObject.h" - -#include -#include -//----------------------------------------------------------------------------- -pqAbstractFieldsWidget::pqAbstractFieldsWidget( - vtkSMProxy *smproxy, vtkSMProperty *smproperty, QWidget *parentObject) -: Superclass(smproxy, parentObject) -{ - this->NItems = 0; - this->visibleHeader = true; - this->setShowLabel(false); - - // Grid Layout - QGridLayout* gridLayout = new QGridLayout(this); - - // Tree widget - this->TreeWidget = new pqTreeWidget(this); - gridLayout->addWidget(this->TreeWidget); -} - -//----------------------------------------------------------------------------- -pqAbstractFieldsWidget::~pqAbstractFieldsWidget() -{ - delete this->TreeWidget; -} - -void pqAbstractFieldsWidget::initializeTreeWidget(vtkSMProxy *smproxy, vtkSMProperty *smproperty) -{ - // Load Tree Widget Items - this->loadTreeWidgetItems(); - - // Connect Property Domain to the fieldDomain property, - // so setFieldDomain is called when the domain changes. - vtkSMDomain* arraySelectionDomain = smproperty->GetDomain("array_list"); - new pqArrayListDomain(this,"fieldsDomain", smproxy, smproperty, arraySelectionDomain); - - // Connect property to field QProperty using a biderectionnal property link - this->addPropertyLink(this, "fields", SIGNAL(fieldsChanged()), - smproxy, smproperty); - - // Call slot when the tree is changed - QObject::connect(this->TreeWidget, SIGNAL(itemChanged(QTreeWidgetItem*, int)), - this, SLOT(onItemChanged(QTreeWidgetItem*, int))); - -} - -//----------------------------------------------------------------------------- -QSize pqAbstractFieldsWidget::sizeHint() const -{ - // TreeWidget sizeHintForRow is too low, correcting to +3. - int pix = (this->TreeWidget->sizeHintForRow(0) + 3) * this->NItems; - int margin[4]; - this->TreeWidget->getContentsMargins(margin, margin + 1, margin + 2, margin + 3); - int h = pix + margin[1] + margin[3]; - if (this->visibleHeader) - { - h += this->TreeWidget->header()->frameSize().height(); - } - h = std::min(300, h); - return QSize(156, h); -} - -//----------------------------------------------------------------------------- -void pqAbstractFieldsWidget::onItemChanged(QTreeWidgetItem* item, int column) const -{ - if (column != 0) - { - return; - } - emit fieldsChanged(); -} - -//----------------------------------------------------------------------------- -QList< QList< QVariant> > pqAbstractFieldsWidget::getFields() const -{ - // Put together a Field list, using ItemMap - QList< QList< QVariant> > ret; - QList< QVariant > field; - QMap::const_iterator it; - for (it = this->ItemMap.begin(); it != this->ItemMap.end(); it++) - { - field.clear(); - field.append(it.key()); - field.append(it.value()->isChecked()); - ret.append(field); - } - return ret; -} - -//----------------------------------------------------------------------------- -void pqAbstractFieldsWidget::setFields(QList< QList< QVariant> > fields) -{ - // Update each item checkboxes, using fields names and ItemMap - QMap::iterator it; - foreach (QList< QVariant> field, fields) - { - it = this->ItemMap.find(field[0].toString()); - if (it == this->ItemMap.end()) - { - qDebug("Found an unknow Field in pqAbstractFieldsWidget::setFields, ignoring"); - continue; - } - it.value()->setChecked(field[1].toBool()); - } -} - -//----------------------------------------------------------------------------- -void pqAbstractFieldsWidget::setFieldsDomain(QList< QList< QVariant> > fields) -{ - // Block signals so the reloading does not trigger - // UncheckPropertyModified event - this->blockSignals(true); - - // Load the tree widget - this->loadTreeWidgetItems(); - - // Set fields checkboxes - this->setFields(fields); - - // Restore signals - this->blockSignals(false); -} diff --git a/src/Plugins/MEDReader/ParaViewPlugin/pqAbstractFieldsWidget.h b/src/Plugins/MEDReader/ParaViewPlugin/pqAbstractFieldsWidget.h deleted file mode 100644 index 10d01984..00000000 --- a/src/Plugins/MEDReader/ParaViewPlugin/pqAbstractFieldsWidget.h +++ /dev/null @@ -1,103 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Anthony Geay - -#ifndef __pqAbstractFieldsWidget_h -#define __pqAbstractFieldsWidget_h - -#include "pqPropertyWidget.h" - -class pqTreeWidget; -class pqTreeWidgetItemObject; -class QTreeWidgetItem; -class vtkSMProxy; -class vtkSMProperty; - -class pqAbstractFieldsWidget : public pqPropertyWidget -{ - typedef pqPropertyWidget Superclass; - Q_OBJECT - - // Description - // Property Qt used to set/get the fields with the property link - Q_PROPERTY(QList< QList< QVariant> > fields READ getFields WRITE setFields) - - // Description - // Property Qt used to set the gorup fields domain with the property link - Q_PROPERTY(QList< QList< QVariant> > fieldsDomain READ getFields WRITE setFieldsDomain) -public: - pqAbstractFieldsWidget( - vtkSMProxy *smproxy, vtkSMProperty *smproperty, QWidget *parentObject = 0); - virtual ~pqAbstractFieldsWidget(); - - // Description - // Corrected size hint, +3 pixel on each line - virtual QSize sizeHint() const; - -signals: - // Description - // Signal emited when selected field changed - void fieldsChanged() const; - -protected: - // Description - // bidrectionnal property link setter/getter - virtual QList< QList< QVariant> > getFields() const; - virtual void setFields(QList< QList< QVariant> > fields); - - // Description - // Update the domain, eg: reload - virtual void setFieldsDomain(QList< QList< QVariant> > fields); - - - // Description - // Initialize the widget items and connect it to property - // To be called by subclasses in constructor - virtual void initializeTreeWidget(vtkSMProxy *smproxy, vtkSMProperty *smproperty); - - // Description - // (Re)Load the tree widget items using recovered meta data graph - virtual void loadTreeWidgetItems() = 0; - - // Description - // Tree widget - pqTreeWidget* TreeWidget; - - // Description - // Number of items, for graphic purpose - int NItems; - - // Description - // Map of ItemPropertyName -> Item Pointer, contains only leaf. - QMap< QString, pqTreeWidgetItemObject*> ItemMap; - - // Description - // Bug in qt, header->isVisible always return false, storing this info here - // https://bugreports.qt.io/browse/QTBUG-12939 - bool visibleHeader; -protected slots: - // Description - // Slot called when the tree widget changed - virtual void onItemChanged(QTreeWidgetItem* itemOrig, int column) const; - -private: - Q_DISABLE_COPY(pqAbstractFieldsWidget); -}; - -#endif diff --git a/src/Plugins/MEDReader/ParaViewPlugin/pqExtractGroupFieldsWidget.cxx b/src/Plugins/MEDReader/ParaViewPlugin/pqExtractGroupFieldsWidget.cxx deleted file mode 100644 index 3dd3d2ef..00000000 --- a/src/Plugins/MEDReader/ParaViewPlugin/pqExtractGroupFieldsWidget.cxx +++ /dev/null @@ -1,202 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Anthony Geay - -#include "pqExtractGroupFieldsWidget.h" - -#include "vtkMEDReader.h" -#include "vtkExtractGroup.h" -#include "vtkPVMetaDataInformation.h" - -#include "pqTreeWidget.h" -#include "pqTreeWidgetItemObject.h" -#include "vtkGraph.h" -#include "vtkNew.h" -#include "vtkStringArray.h" -#include "vtkDataSetAttributes.h" -#include "vtkTree.h" - -#include - -//----------------------------------------------------------------------------- -pqExtractGroupFieldsWidget::pqExtractGroupFieldsWidget( - vtkSMProxy *smproxy, vtkSMProperty *smproperty, QWidget *parentObject) -: Superclass(smproxy, smproperty, parentObject) -{ - this->TreeWidget->setHeaderLabel("Groups And Families"); - this->initializeTreeWidget(smproxy, smproperty); -} - -//----------------------------------------------------------------------------- -pqExtractGroupFieldsWidget::~pqExtractGroupFieldsWidget() -{ -} - -//----------------------------------------------------------------------------- -void pqExtractGroupFieldsWidget::loadTreeWidgetItems() -{ - // Recover Graph - vtkPVMetaDataInformation *info(vtkPVMetaDataInformation::New()); - this->proxy()->GatherInformation(info); - vtkGraph* graph = vtkGraph::SafeDownCast(info->GetInformationData()); - if(!graph) - { - return; - } - - // Clear Tree Widget - this->TreeWidget->clear(); - - // Clear Item Map - this->ItemMap.clear(); - - // Create a tree - vtkNew tree; - tree->CheckedShallowCopy(graph); - vtkStringArray* names = vtkStringArray::SafeDownCast(tree->GetVertexData()->GetAbstractArray("Names")); - - vtkIdType root = tree->GetRoot(); - vtkIdType mfg = tree->GetChild(root, 1); // MeshesFamsGrps - - vtkIdType mesh = tree->GetChild(mfg, 0); // mesh - QString meshName = QString(names->GetValue(mesh)); - - this->NItems = 0; - - vtkIdType grps = tree->GetChild(mesh, 0); // grps - pqTreeWidgetItemObject* grpsItem = new pqTreeWidgetItemObject(this->TreeWidget, QStringList()); - this->NItems++; - grpsItem->setText(0, QString("Groups of \"" + meshName + "\"")); - - vtkIdType fams = tree->GetChild(mesh, 1); // fams - pqTreeWidgetItemObject* famsItem = new pqTreeWidgetItemObject(this->TreeWidget, QStringList()); - this->NItems++; - famsItem->setText(0, QString("Families of \"" + meshName + "\"")); - - std::map famDataTypeMap; - - for (int i = 0; i < tree->GetNumberOfChildren(fams); i++) - { - // Familly Item - vtkIdType fam = tree->GetChild(fams, i); - pqTreeWidgetItemObject *famItem = new pqTreeWidgetItemObject(famsItem, QStringList()); - this->NItems++; - - // Familly name - std::string str = names->GetValue(fam); - const char* separator = vtkMEDReader::GetSeparator(); - size_t pos = str.find(separator); - std::string name = str.substr(0, pos); - famItem->setText(0, QString(name.c_str())); - - // Property Name - QString propertyName = QString(vtkExtractGroup::GetFamStart()) + QString(str.c_str()); - this->ItemMap[propertyName] = famItem; - - // Datatype flag - int dataTypeFlag = atoi(str.substr(pos + strlen(separator)).c_str()); - famDataTypeMap[name] = dataTypeFlag; - - // Checkbox - famItem->setFlags(famItem->flags() | Qt::ItemIsUserCheckable | Qt::ItemIsSelectable); - famItem->setChecked(true); - - // Tooltip - QString famToolTip(QString("%1 (%2)").arg(QString(name.c_str())).arg(dataTypeFlag)); - famItem->setData(0, Qt::ToolTipRole, famToolTip); - - // Pixmap - if (dataTypeFlag<0) - { - famItem->setData(0, Qt::DecorationRole, - QPixmap(":/ParaViewResources/Icons/pqCellData16.png")); - } - if (dataTypeFlag>0) - { - famItem->setData(0, Qt::DecorationRole, - QPixmap(":/ParaViewResources/Icons/pqPointData16.png")); - } - } - - for (int i = 0; i < tree->GetNumberOfChildren(grps); i++) - { - // Grp Item - vtkIdType grp = tree->GetChild(grps, i); - pqTreeWidgetItemObject *grpItem = new pqTreeWidgetItemObject(grpsItem, QStringList()); - this->NItems++; - - // Group name - QString name = QString(names->GetValue(grp)); - grpItem->setText(0, name); - - // Property Name - QString propertyName = QString(vtkExtractGroup::GetGrpStart()) + name; - this->ItemMap[propertyName] = grpItem; - - // Datatype flag - bool hasPoint = false; - bool hasCell = false; - int dataTypeFlag = 0; - for (int j = 0; j < tree->GetNumberOfChildren(grp); j++) - { - dataTypeFlag = famDataTypeMap[names->GetValue(tree->GetChild(grp, j))]; - if (dataTypeFlag > 0) - { - hasPoint = true; - } - else if (dataTypeFlag < 0) - { - hasCell = true; - } - else - { - dataTypeFlag = 0; - break; - } - - if (hasPoint && hasCell) - { - dataTypeFlag = 0; - break; - } - } - - // Checkbox - grpItem->setFlags(grpItem->flags() | Qt::ItemIsUserCheckable | Qt::ItemIsSelectable); - grpItem->setChecked(true); - - // Tooltip - grpItem->setData(0, Qt::ToolTipRole, name); - - // Pixmap - if (dataTypeFlag<0) - { - grpItem->setData(0, Qt::DecorationRole, - QPixmap(":/ParaViewResources/Icons/pqCellData16.png")); - } - if (dataTypeFlag>0) - { - grpItem->setData(0, Qt::DecorationRole, - QPixmap(":/ParaViewResources/Icons/pqPointData16.png")); - } - } - - // Expand Widget - this->TreeWidget->expandAll(); -} diff --git a/src/Plugins/MEDReader/ParaViewPlugin/pqExtractGroupFieldsWidget.h b/src/Plugins/MEDReader/ParaViewPlugin/pqExtractGroupFieldsWidget.h deleted file mode 100644 index 34add9bb..00000000 --- a/src/Plugins/MEDReader/ParaViewPlugin/pqExtractGroupFieldsWidget.h +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Anthony Geay - -#ifndef __pqExtractGroupFieldsWidget_h -#define __pqExtractGroupFieldsWidget_h - -#include "pqAbstractFieldsWidget.h" - -class vtkSMProxy; -class vtkSMProperty; - -class pqExtractGroupFieldsWidget : public pqAbstractFieldsWidget -{ - typedef pqAbstractFieldsWidget Superclass; - Q_OBJECT - -public: - pqExtractGroupFieldsWidget( - vtkSMProxy *smproxy, vtkSMProperty *smproperty, QWidget *parentObject = 0); - virtual ~pqExtractGroupFieldsWidget(); - -protected: - // Description - // Load the tree widget using recovered meta data graph - void loadTreeWidgetItems(); - -private: - Q_DISABLE_COPY(pqExtractGroupFieldsWidget); -}; - -#endif diff --git a/src/Plugins/MEDReader/ParaViewPlugin/pqMEDReaderFieldsWidget.cxx b/src/Plugins/MEDReader/ParaViewPlugin/pqMEDReaderFieldsWidget.cxx deleted file mode 100644 index 29151f03..00000000 --- a/src/Plugins/MEDReader/ParaViewPlugin/pqMEDReaderFieldsWidget.cxx +++ /dev/null @@ -1,278 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Anthony Geay - -#include "pqMEDReaderFieldsWidget.h" - -#include "vtkMEDReader.h" -#include "vtkPVMetaDataInformation.h" - -#include "pqTreeWidget.h" -#include "pqTreeWidgetItemObject.h" -#include "vtkDataSetAttributes.h" -#include "vtkGraph.h" -#include "vtkNew.h" -#include "vtkStringArray.h" -#include "vtkTree.h" - -#include -#include - -//----------------------------------------------------------------------------- -pqMEDReaderFieldsWidget::pqMEDReaderFieldsWidget( - vtkSMProxy *smproxy, vtkSMProperty *smproperty, QWidget *parentObject) -: Superclass(smproxy, smproperty, parentObject) -{ - this->TreeWidget->header()->hide(); - this->visibleHeader = false; - this->TransmitToParent = true; - this->initializeTreeWidget(smproxy, smproperty); -} - -//----------------------------------------------------------------------------- -pqMEDReaderFieldsWidget::~pqMEDReaderFieldsWidget() -{ -} - -//----------------------------------------------------------------------------- -void pqMEDReaderFieldsWidget::loadTreeWidgetItems() -{ - //Clear Item Map - this->ItemMap.clear(); - - // Clear tree - this->TreeWidget->clear(); - - // Clear unique checked item vector - this->UniqueCheckedItems.clear(); - - // Recover meta data graph - vtkPVMetaDataInformation *info(vtkPVMetaDataInformation::New()); - this->proxy()->GatherInformation(info); - vtkGraph* graph = vtkGraph::SafeDownCast(info->GetInformationData()); - - // Create a tree - vtkNew tree; - tree->CheckedShallowCopy(graph); - vtkStringArray* names = - vtkStringArray::SafeDownCast(tree->GetVertexData()->GetAbstractArray("Names")); - - if(!names)// In case of error right at the begining of loading process (empty MED file) - return ; - - vtkIdType root = tree->GetRoot(); - vtkIdType fst = tree->GetChild(root, 0); // FieldsStatusTree - - this->NItems = 0; - int nLeaves = 0; - for (int i = 1; i < tree->GetNumberOfChildren(fst); i += 2) - { - // Browse all interessting tree node - - // TSX Node - vtkIdType tsxId = tree->GetChild(fst, i); - vtkIdType tsId = tree->GetChild(fst, i - 1); - pqTreeWidgetItemObject *ts = new pqTreeWidgetItemObject(this->TreeWidget, QStringList()); - this->NItems++; - QString tsxName = QString(names->GetValue(tsxId)); - ts->setText(0, tsxName); - ts->setData(0, Qt::ToolTipRole, QString(names->GetValue(tsId))); - - // MAIL Node - for (int maili = 0; maili < tree->GetNumberOfChildren(tsxId); maili++) - { - vtkIdType mailId = tree->GetChild(tsxId, maili); - pqTreeWidgetItemObject *mail = new pqTreeWidgetItemObject(ts, QStringList()); - this->NItems++; - QString mailName = QString(names->GetValue(mailId)); - mail->setText(0, mailName); - mail->setData(0, Qt::ToolTipRole, QString(names->GetValue(mailId))); - - QString propertyBaseName = tsxName + "/" + mailName + "/"; - - // ComsupX node - for (int comsupi = 0; comsupi < tree->GetNumberOfChildren(mailId); comsupi++) - { - vtkIdType comSupId = tree->GetChild(mailId, comsupi); - pqTreeWidgetItemObject *comsup = new pqTreeWidgetItemObject(mail, QStringList()); - this->NItems++; - QString comsupName = QString(names->GetValue(comSupId)); - comsup->setText(0, comsupName); - - // ComSup tooltip - vtkIdType geoTypeId = tree->GetChild(comSupId, 1); - QString comSupToolTipName(names->GetValue(comSupId)); - for (int geoi = 0; geoi < tree->GetNumberOfChildren(geoTypeId); geoi++) - { - comSupToolTipName += QString("\n- %1").arg( - QString(names->GetValue(tree->GetChild(geoTypeId, geoi)))); - } - comsup->setData(0, Qt::ToolTipRole, comSupToolTipName); - - comsup->setFlags(comsup->flags() | Qt::ItemIsUserCheckable | Qt::ItemIsSelectable); - comsup->setChecked(true); - QObject::connect(comsup, SIGNAL(checkedStateChanged(bool)), this, SLOT(updateChecks())); - this->UniqueCheckedItems.push_back(comsup); - - QString fullComsupName = propertyBaseName + comsupName + "/"; - // Arrs node - vtkIdType arrId = tree->GetChild(comSupId, 0); - for (int arri = 0; arri < tree->GetNumberOfChildren(arrId); arri++) - { - pqTreeWidgetItemObject *array = new pqTreeWidgetItemObject(comsup, QStringList()); - this->NItems++; - - vtkIdType arrayId = tree->GetChild(arrId, arri); - std::string str = names->GetValue(arrayId); - this->ItemMap[fullComsupName + QString(str.c_str())] = array; - - const char* separator = vtkMEDReader::GetSeparator(); - size_t pos = str.find(separator); - std::string name = str.substr(0, pos); - - array->setText(0, QString(name.c_str())); - array->setFlags(array->flags() | Qt::ItemIsUserCheckable); - array->setChecked(true); - - // Special Field - if (tree->GetNumberOfChildren(arrayId) != 0) - { - QFont font; - font.setItalic(true); - font.setUnderline(true); - array->setData(0, Qt::FontRole, QVariant(font)); - - array->setData(0, Qt::ToolTipRole, - QString("Whole \" %1\" mesh").arg(name.c_str())); - array->setData(0, Qt::DecorationRole, - QPixmap(":/ParaViewResources/Icons/pqCellDataForWholeMesh16.png")); - } - // Standard Field - else - { - std::string spatialDiscr = str.substr(pos + strlen(separator)); - QString tooltip = QString(name.c_str() + QString(" (") + - spatialDiscr.c_str() + QString(")")); - array->setData(0, Qt::ToolTipRole, tooltip); - - QPixmap pix; - if (spatialDiscr == "P0") - { - pix.load(":/ParaViewResources/Icons/pqCellData16.png"); - } - else if (spatialDiscr == "P1") - { - pix.load(":/ParaViewResources/Icons/pqPointData16.png"); - } - else if (spatialDiscr == "GAUSS") - { - pix.load(":/ParaViewResources/Icons/pqQuadratureData16.png"); - } - else if (spatialDiscr == "GSSNE") - { - pix.load(":/ParaViewResources/Icons/pqElnoData16.png"); - } - array->setData(0, Qt::DecorationRole, pix); - } - - // Connection and updating checks for each item - QObject::connect(array, SIGNAL(checkedStateChanged(bool)), this, SLOT(updateChecks())); - nLeaves++; - } - } - } - } - // Expand tree - this->TreeWidget->expandAll(); -} - -//----------------------------------------------------------------------------- -void pqMEDReaderFieldsWidget::uncheckOtherUniqueItems(pqTreeWidgetItemObject* item) -{ - // Uncheck all other items in vector - foreach (pqTreeWidgetItemObject* otherItems, this->UniqueCheckedItems) - { - if (otherItems != item) - { - otherItems->setCheckState(0, Qt::Unchecked); - } - } -} - -//----------------------------------------------------------------------------- -void pqMEDReaderFieldsWidget::updateChecks() -{ - // Call updateCheck on the sender - pqTreeWidgetItemObject* item = qobject_cast(QObject::sender()); - this->updateChecks(item); -} - -//----------------------------------------------------------------------------- -void pqMEDReaderFieldsWidget::updateChecks(pqTreeWidgetItemObject* item) -{ - // When a Leaf item is checked, the parent will be checked (partially or not). - // Then other parents will be unchecked using uncheckOtherUniqueItems - // Then other parent leaf will be unchecked using updateChecks(parent) - // - // When a Parent item is checked, the leaf will be checked - // Then other parents will be unchecked using uncheckOtherUniqueItems - // Then other parent leaf will be unchecked using updateChecks(parent) - - if (item->childCount() == 0) - { - // Only first level leaf will transmit checks to parent - if (this->TransmitToParent) - { - // Recover correct parent state - Qt::CheckState state = item->checkState(0); - pqTreeWidgetItemObject* parent = - dynamic_cast(item->QTreeWidgetItem::parent()); - for (int i = 0; i < parent->childCount(); i++) - { - if (parent->child(i)->checkState(0) != state) - { - state = Qt::PartiallyChecked; - } - } - // Set Parent State - parent->setCheckState(0, state); - } - } - else - { - // Check/Uncheck childs, blocking looped call to slot - if (item->checkState(0) != Qt::PartiallyChecked) - { - this->TransmitToParent = false; - for (int i = 0; i < item->childCount(); i++) - { - pqTreeWidgetItemObject* leaf = - dynamic_cast(item->child(i)); - leaf->setCheckState(0, item->checkState(0)); - } - this->TransmitToParent = true; - } - - // Uncheck other unique checked items - if (item->checkState(0) != Qt::Unchecked) - { - this->uncheckOtherUniqueItems(item); - } - } -} diff --git a/src/Plugins/MEDReader/ParaViewPlugin/pqMEDReaderFieldsWidget.h b/src/Plugins/MEDReader/ParaViewPlugin/pqMEDReaderFieldsWidget.h deleted file mode 100644 index a11dc1f9..00000000 --- a/src/Plugins/MEDReader/ParaViewPlugin/pqMEDReaderFieldsWidget.h +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Anthony Geay - -#ifndef __pqMEDReaderFieldsWidget_h -#define __pqMEDReaderFieldsWidget_h - -#include "pqAbstractFieldsWidget.h" - -class vtkSMProxy; -class vtkSMProperty; -class pqMEDReaderFieldsWidget : public pqAbstractFieldsWidget -{ - typedef pqAbstractFieldsWidget Superclass; - Q_OBJECT - -public: - pqMEDReaderFieldsWidget( - vtkSMProxy *smproxy, vtkSMProperty *smproperty, QWidget *parentObject = 0); - virtual ~pqMEDReaderFieldsWidget(); - -protected: - // Descritpion - // Load the tree widget using recovered meta data graph - // and connect each item to indexed property - void loadTreeWidgetItems(); - - // Description - // Uncheck other unique checked item - void uncheckOtherUniqueItems(pqTreeWidgetItemObject* item); - - // Description - // Update check state of other items using provided item - void updateChecks(pqTreeWidgetItemObject* item); - - // Description - // Vector of unique checked items - std::vector UniqueCheckedItems; - - // Description - // Flag indicating if updateCheck method is recursivelly called, - // to avoid infinite loop - bool TransmitToParent; - -protected slots: - // Description - // Update check state of other items using the sender object - void updateChecks(); - -private: - Q_DISABLE_COPY(pqMEDReaderFieldsWidget); -}; - -#endif diff --git a/src/Plugins/MEDReader/ParaViewPlugin/pqMEDReaderGraphUtils.cxx b/src/Plugins/MEDReader/ParaViewPlugin/pqMEDReaderGraphUtils.cxx deleted file mode 100644 index c347ce68..00000000 --- a/src/Plugins/MEDReader/ParaViewPlugin/pqMEDReaderGraphUtils.cxx +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Anthony Geay - -#include "pqMEDReaderGraphUtils.h" - -#include "vtkGraph.h" -#include "vtkTree.h" -#include "vtkNew.h" -#include "vtkStringArray.h" -#include "vtkDataSetAttributes.h" - -namespace pqMedReaderGraphUtils -{ -void getCurrentTS(vtkGraph* graph, vtkIdType id, QStringList& dts, QStringList& its, - QStringList& tts) -{ - vtkNew tree; - tree->CheckedShallowCopy(graph); - vtkStringArray* names = vtkStringArray::SafeDownCast( - tree->GetVertexData()->GetAbstractArray("Names")); - vtkIdType root = tree->GetRoot(); - vtkIdType fst = tree->GetChild(root, 0); // FieldsStatusTree - vtkIdType tsr = tree->GetChild(tree->GetChild(fst, id*2), 0); //Time Step root node - vtkIdType tmp; - for (int i = 0; i < tree->GetNumberOfChildren(tsr); i++) - { - // Each Time Step - // Recover step - tmp = tree->GetChild(tsr, i); - dts << QString(names->GetValue(tmp)); - - // Recover mode - tmp = tree->GetChild(tmp, 0); - its << QString(names->GetValue(tmp)); - - // Recover value - tmp = tree->GetChild(tmp, 0); - tts << QString(names->GetValue(tmp)); - } -} - -int getMaxNumberOfTS(vtkGraph* graph) -{ - vtkNew tree; - tree->CheckedShallowCopy(graph); - vtkStringArray* names = vtkStringArray::SafeDownCast( - tree->GetVertexData()->GetAbstractArray("Names")); - vtkIdType root = tree->GetRoot(); - vtkIdType fst = tree->GetChild(root, 0); // FieldsStatusTree - vtkIdType tmp; - int nbTS = 0; - for (int i = 0; i < tree->GetNumberOfChildren(fst); i += 2) - { - // Look for max time steps - tmp = tree->GetChild(tree->GetChild(fst, i), 0); - nbTS = std::max(nbTS, names->GetVariantValue(tmp).ToInt()); - } - return nbTS; -} -} diff --git a/src/Plugins/MEDReader/ParaViewPlugin/pqMEDReaderGraphUtils.h b/src/Plugins/MEDReader/ParaViewPlugin/pqMEDReaderGraphUtils.h deleted file mode 100644 index cb91d537..00000000 --- a/src/Plugins/MEDReader/ParaViewPlugin/pqMEDReaderGraphUtils.h +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Anthony Geay - -#ifndef _pqMEDReaderGraphUtils_h -#define _pqMEDReaderGraphUtils_h - -#include "vtkType.h" - -#include - -class vtkGraph; -class pqTreeWidget; - -namespace pqMedReaderGraphUtils -{ - // Description - // Extract Current Time Step from a meta data graph - void getCurrentTS(vtkGraph* graph, vtkIdType id, QStringList& dts, - QStringList& its, QStringList& tts); - - // Description - // Extract the maximum number of timestep from a meta data graph - int getMaxNumberOfTS(vtkGraph* graph); -} - -#endif diff --git a/src/Plugins/MEDReader/ParaViewPlugin/pqMEDReaderReloadWidget.cxx b/src/Plugins/MEDReader/ParaViewPlugin/pqMEDReaderReloadWidget.cxx deleted file mode 100644 index 82323c9f..00000000 --- a/src/Plugins/MEDReader/ParaViewPlugin/pqMEDReaderReloadWidget.cxx +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Anthony Geay - -#include "pqMEDReaderReloadWidget.h" - -#include "vtkSMProxy.h" -#include "vtkSMSourceProxy.h" -#include "vtkSMProperty.h" - -#include "pqPropertiesPanel.h" - -#include -#include - -pqMEDReaderReloadWidget::pqMEDReaderReloadWidget(vtkSMProxy *smProxy, - vtkSMProperty *proxyProperty, - QWidget *pWidget) -: pqPropertyWidget(smProxy, pWidget), - Property(proxyProperty) -{ - this->setShowLabel(false); - - // Grid Layout - QGridLayout* gridLayout = new QGridLayout(this); - gridLayout->setAlignment(Qt::AlignRight); - - // Reload Button - QPushButton *button = new QPushButton(); - button->setIcon(QIcon(":/ParaViewResources/Icons/pqReloadFile16.png")); - button->setFixedSize(button->sizeHint()); - gridLayout->addWidget(button); - - // Connection - connect(button, SIGNAL(clicked()), this, SLOT(buttonClicked())); -} - -pqMEDReaderReloadWidget::~pqMEDReaderReloadWidget() -{ -} - -void pqMEDReaderReloadWidget::buttonClicked() -{ - // Recovering Property Panel - pqPropertiesPanel* panel = NULL; - QObject* tmp = this; - while (panel == NULL) - { - tmp = tmp->parent(); - if (!tmp) - { - break; - } - panel = qobject_cast(tmp); - } - - if (!panel) - { - qDebug() << "Cannot find pqPropertiesPanel, reload may not work"; - } - else - { - // Restoring property to defaults, necessary when unchecked property are not applied - panel->propertiesRestoreDefaults(); - } - - // Reloading the data and associated properties - this->Property->Modified(); - this->proxy()->UpdateProperty(this->proxy()->GetPropertyName(this->Property)); - vtkSMSourceProxy::SafeDownCast(this->proxy())->UpdatePipelineInformation(); - - // Restting properties to dufault using domains and XML values - this->proxy()->ResetPropertiesToDefault(); - - if (panel) - { - // Disabled apply button inderectly - panel->propertiesRestoreDefaults(); - } -} diff --git a/src/Plugins/MEDReader/ParaViewPlugin/pqMEDReaderReloadWidget.h b/src/Plugins/MEDReader/ParaViewPlugin/pqMEDReaderReloadWidget.h deleted file mode 100644 index 1dd3ff17..00000000 --- a/src/Plugins/MEDReader/ParaViewPlugin/pqMEDReaderReloadWidget.h +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Anthony Geay - -#ifndef _pqMEDReaderReloadWidget_h -#define _pqMEDReaderReloadWidget_h - -#include "pqPropertyWidget.h" - -class pqMEDReaderReloadWidget : public pqPropertyWidget -{ - Q_OBJECT - -public: - explicit pqMEDReaderReloadWidget(vtkSMProxy *proxy, - vtkSMProperty *property, - QWidget *parent = 0); - ~pqMEDReaderReloadWidget(); - -private slots: - // Description - // Called when button is clicked - // Reload the med reader - void buttonClicked(); - -private: - vtkSMProperty* Property; -}; - -#endif // _pqMEDReaderReloadWidget_h diff --git a/src/Plugins/MEDReader/ParaViewPlugin/pqMEDReaderTimeModeWidget.cxx b/src/Plugins/MEDReader/ParaViewPlugin/pqMEDReaderTimeModeWidget.cxx deleted file mode 100644 index bf5f8e8f..00000000 --- a/src/Plugins/MEDReader/ParaViewPlugin/pqMEDReaderTimeModeWidget.cxx +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Anthony Geay - -#include "ui_MEDReaderTimeModeWidget.h" -#include "pqMEDReaderTimeModeWidget.h" - -#include "pqCoreUtilities.h" -//----------------------------------------------------------------------------- -// Internals -class pqMEDReaderTimeModeWidget::pqInternals : public Ui::MEDReaderTimeModeWidget -{ -public: - pqInternals(pqMEDReaderTimeModeWidget* self) - { - this->setupUi(self); - } -}; - -//----------------------------------------------------------------------------- -pqMEDReaderTimeModeWidget::pqMEDReaderTimeModeWidget( - vtkSMProxy *smproxy, vtkSMProperty *smproperty, QWidget *parentObject) -: Superclass(smproxy, parentObject), Internals(new pqMEDReaderTimeModeWidget::pqInternals(this)) -{ - this->setShowLabel(false); - this->ModeEnabled = false; - - this->addPropertyLink(this, "ModeEnabled" , SIGNAL(modeEnabled(bool)), smproperty); - QObject::connect(this->Internals->modeMode, SIGNAL(toggled(bool)), - this, SLOT(setModeEnabled(bool))); -} - -//----------------------------------------------------------------------------- -pqMEDReaderTimeModeWidget::~pqMEDReaderTimeModeWidget() -{ -} - -//----------------------------------------------------------------------------- -bool pqMEDReaderTimeModeWidget::isModeEnabled() const -{ - return this->ModeEnabled; -} - -//----------------------------------------------------------------------------- -void pqMEDReaderTimeModeWidget::setModeEnabled(bool enable) -{ - this->ModeEnabled = enable; - this->Internals->modeMode->setChecked(enable); - this->Internals->stdMode->setChecked(!enable); - emit modeEnabled(enable); -} diff --git a/src/Plugins/MEDReader/ParaViewPlugin/pqMEDReaderTimeModeWidget.h b/src/Plugins/MEDReader/ParaViewPlugin/pqMEDReaderTimeModeWidget.h deleted file mode 100644 index 437de291..00000000 --- a/src/Plugins/MEDReader/ParaViewPlugin/pqMEDReaderTimeModeWidget.h +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Anthony Geay - -#ifndef __pqMEDReaderTimeModeWidget_h -#define __pqMEDReaderTimeModeWidget_h - -#include "pqPropertyWidget.h" - -class pqMEDReaderTimeModeWidget : public pqPropertyWidget -{ - Q_OBJECT - - // Qt property to link to vtk property - Q_PROPERTY(bool ModeEnabled READ isModeEnabled WRITE setModeEnabled) - - typedef pqPropertyWidget Superclass; -public: - pqMEDReaderTimeModeWidget( - vtkSMProxy *smproxy, vtkSMProperty *smproperty, QWidget *parentObject = 0); - virtual ~pqMEDReaderTimeModeWidget(); - - // Description - // Qt property getter - bool isModeEnabled() const; - -public slots: - // Description - // Qt Property setter - void setModeEnabled(bool enable); - -signals: - // Description - // Qt Property signal - void modeEnabled(bool enable); - -private: - Q_DISABLE_COPY(pqMEDReaderTimeModeWidget); - - // Description - // Qt property value - bool ModeEnabled; - - // Description - // UI Internals - class pqInternals; - pqInternals* Internals; -}; - -#endif diff --git a/src/Plugins/MEDReader/ParaViewPlugin/pqMEDReaderTimesFlagsWidget.cxx b/src/Plugins/MEDReader/ParaViewPlugin/pqMEDReaderTimesFlagsWidget.cxx deleted file mode 100644 index 23d840b5..00000000 --- a/src/Plugins/MEDReader/ParaViewPlugin/pqMEDReaderTimesFlagsWidget.cxx +++ /dev/null @@ -1,224 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Anthony Geay - -#include "pqMEDReaderTimesFlagsWidget.h" - -#include "VectBoolWidget.h" -#include "pqMEDReaderGraphUtils.h" -#include "vtkMEDReader.h" -#include "vtkPVMetaDataInformation.h" - -#include "pqCoreUtilities.h" -#include "pqArrayListDomain.h" -#include "pqPropertiesPanel.h" -#include "vtkGraph.h" -#include "vtkGraphWriter.h" -#include "vtkInformationDataObjectMetaDataKey.h" -#include "vtkNew.h" -#include "vtkSMDoubleVectorProperty.h" -#include "vtkSMStringVectorProperty.h" -#include "vtkTree.h" - -#include -#include - -//----------------------------------------------------------------------------- -pqMEDReaderTimesFlagsWidget::pqMEDReaderTimesFlagsWidget( - vtkSMProxy *smproxy, vtkSMProperty *smproperty, QWidget *parentObject) -: Superclass(smproxy, parentObject) -{ - this->CachedTsId = -1; - this->TimesVectWidget = NULL; - this->setShowLabel(false); - - // Grid Layout - this->TimesVectLayout = new QGridLayout(this); - - // VectBoolWidget - this->CreateTimesVectWidget(); - this->UpdateTimeSteps(); - - // Connect timeStepStatus property to update time steps method - vtkSMProperty* prop = smproxy? smproxy->GetProperty("FieldsStatus") : NULL; - if (!prop) - { - qDebug("Could not locate property named 'FieldsStatus'. " - "pqMEDReaderTimesFlagsWidget will have no updated labels."); - } - else - { - pqCoreUtilities::connect(prop, vtkCommand::UncheckedPropertyModifiedEvent, - this, SLOT(UpdateTimeSteps())); - } - - // Connect Property Domain to the timeStepDomain property, - // so setTimeStepDomain is called when the domain changes. - vtkSMDomain* arraySelectionDomain = smproperty->GetDomain("array_list"); - new pqArrayListDomain(this,"timeStepsDomain", smproxy, smproperty, arraySelectionDomain); - - // Connect property to timeStep QProperty using a biderectionnal property link - this->addPropertyLink(this, "timeSteps", SIGNAL(timeStepsChanged()), - smproxy, smproperty); - - if(!this->TimesVectWidget) // In case of error right at the begining of loading process (empty MED file) - return ; - - const QMap& items(this->TimesVectWidget->getItems()); - QMap::const_iterator it; - for (it = items.begin(); it != items.end(); it++) - { - QObject::connect(it.value(), SIGNAL(changed()), this, SLOT(onItemChanged())); - } -} - -//----------------------------------------------------------------------------- -pqMEDReaderTimesFlagsWidget::~pqMEDReaderTimesFlagsWidget() -{ - delete this->TimesVectWidget; -} - -//----------------------------------------------------------------------------- -void pqMEDReaderTimesFlagsWidget::onItemChanged() const -{ - emit timeStepsChanged(); -} - -//----------------------------------------------------------------------------- -QList< QList< QVariant> > pqMEDReaderTimesFlagsWidget::getTimeSteps() const -{ - // Put together a TimeStep list, using ItemMap - QList< QList< QVariant> > ret; - QList< QVariant > timeStep; - if(!this->TimesVectWidget) // In case of error right at the begining of loading process (empty MED file) - return ret; - const QMap& items(this->TimesVectWidget->getItems()); - QMap::const_iterator it; - for (it = items.begin(); it != items.end(); it++) - { - timeStep.clear(); - timeStep.append(it.key()); - timeStep.append(it.value()->isActivated()); - ret.append(timeStep); - } - return ret; -} - -//----------------------------------------------------------------------------- -void pqMEDReaderTimesFlagsWidget::setTimeSteps(QList< QList< QVariant> > timeSteps) -{ - // Update each item checkboxes, using timeSteps names and ItemMap - const QMap& items(this->TimesVectWidget->getItems()); - QMap::const_iterator it; - foreach (QList< QVariant> timeStep, timeSteps) - { - it = items.find(timeStep[0].toString()); - if (it == items.end()) - { - qDebug("Found an unknow TimeStep in pqMEDReaderTimesFlagsWidget::setTimeSteps, ignoring"); - continue; - } - it.value()->activated(timeStep[1].toBool()); - } -} - -//----------------------------------------------------------------------------- -void pqMEDReaderTimesFlagsWidget::setTimeStepsDomain(QList< QList< QVariant> > timeSteps) -{ - cout<<"TimeStepsDomai"<blockSignals(true); - - // Load the tree widget - this->CreateTimesVectWidget(); - - // Set timeSteps checkboxes - this->setTimeSteps(timeSteps); - - // Restore signals - this->blockSignals(false); -} - -//----------------------------------------------------------------------------- -void pqMEDReaderTimesFlagsWidget::CreateTimesVectWidget() -{ - // Recover Graph - vtkPVMetaDataInformation *info(vtkPVMetaDataInformation::New()); - this->proxy()->GatherInformation(info); - vtkGraph* graph = vtkGraph::SafeDownCast(info->GetInformationData()); - - // Delete the widget - if (this->TimesVectWidget != NULL) - { - delete this->TimesVectWidget; - } - - if(!graph) - return ;// In case of error right at the begining of loading process (empty MED file) - - // (Re)cretate widget - this->TimesVectWidget = new VectBoolWidget(this, - pqMedReaderGraphUtils::getMaxNumberOfTS(graph)); - this->TimesVectLayout->addWidget(this->TimesVectWidget); -} - -//----------------------------------------------------------------------------- -void pqMEDReaderTimesFlagsWidget::UpdateTimeSteps() -{ - // Recover property - vtkSMStringVectorProperty* prop = this->proxy()? - vtkSMStringVectorProperty::SafeDownCast(this->proxy()->GetProperty("FieldsStatus")) : NULL; - vtkIdType tsId = -1; - if (prop) - { - // Searching first activated leaf id - for (unsigned int i = 1; i < prop->GetNumberOfElements(); i += 2) - { - if (prop->GetElement(i)[0] == '1') - { - const char* leafString = prop->GetElement(i - 1); - const char* tmp = strchr(leafString, '/'); - size_t num = tmp - leafString; - char* dest = new char[num+1]; - strncpy(dest, leafString, num); - dest[num] = '\0'; - tsId = (vtkIdType)strtol(dest + 2, NULL, 10); - delete [] dest; - break; - } - } - } - - if (tsId != -1 && tsId != this->CachedTsId) - { - // Recovering graph - this->CachedTsId = tsId; - vtkPVMetaDataInformation *info(vtkPVMetaDataInformation::New()); - this->proxy()->GatherInformation(info); - vtkGraph* g = vtkGraph::SafeDownCast(info->GetInformationData()); - - // Updating times steps using leaf id - QStringList dts, its, tts; - if(g) - pqMedReaderGraphUtils::getCurrentTS(g, tsId, dts, its, tts); - if(this->TimesVectWidget) - this->TimesVectWidget->setItems(dts, its, tts); - } -} diff --git a/src/Plugins/MEDReader/ParaViewPlugin/pqMEDReaderTimesFlagsWidget.h b/src/Plugins/MEDReader/ParaViewPlugin/pqMEDReaderTimesFlagsWidget.h deleted file mode 100644 index 742d13d9..00000000 --- a/src/Plugins/MEDReader/ParaViewPlugin/pqMEDReaderTimesFlagsWidget.h +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Anthony Geay - -#ifndef __pqMEDReaderTimesFlagsWidget_h -#define __pqMEDReaderTimesFlagsWidget_h - -#include "pqPropertyWidget.h" - -class VectBoolWidget; -class QGridLayout; - -class pqMEDReaderTimesFlagsWidget : public pqPropertyWidget -{ - - typedef pqPropertyWidget Superclass; - Q_OBJECT - // Description - // Property Qt used to set/get the times steps with the property link - Q_PROPERTY(QList< QList< QVariant> > timeSteps READ getTimeSteps WRITE setTimeSteps) - // Description - // Property Qt used to set the gorup time steps domain with the property link - Q_PROPERTY(QList< QList< QVariant> > timeStepsDomain READ getTimeSteps WRITE setTimeStepsDomain) -public: - pqMEDReaderTimesFlagsWidget( - vtkSMProxy *smproxy, vtkSMProperty *smproperty, QWidget *parentObject = 0); - virtual ~pqMEDReaderTimesFlagsWidget(); - -signals: - // Description - // Signal emited when selected field changed - void timeStepsChanged() const; - -protected slots: - // Description - // Slot called when item is changed - virtual void onItemChanged() const; - -protected slots: - // Description - // bidrectionnal property link setter/getter - virtual QList< QList< QVariant> > getTimeSteps() const; - virtual void setTimeSteps(QList< QList< QVariant> > timeSteps); - - // Description - // Update the domain, eg: reload - virtual void setTimeStepsDomain(QList< QList< QVariant> > timeSteps); - - - // Description - // Called when field status changed and reload the time steps - void UpdateTimeSteps(); - - // Description - // Called to create the vect widget, on creation or for a reload - void CreateTimesVectWidget(); - -protected: - // Description - // The Vect time widget - VectBoolWidget* TimesVectWidget; - - // Description - // The grid layout contian the vect times widget - QGridLayout* TimesVectLayout; - - // Description - // Id of current time step, for caching purpose - vtkIdType CachedTsId; - -private: - Q_DISABLE_COPY(pqMEDReaderTimesFlagsWidget); -}; - -#endif diff --git a/src/Plugins/MEDReader/ParaViewPlugin/pqMEDReaderVectorsWidget.cxx b/src/Plugins/MEDReader/ParaViewPlugin/pqMEDReaderVectorsWidget.cxx deleted file mode 100644 index cede7b73..00000000 --- a/src/Plugins/MEDReader/ParaViewPlugin/pqMEDReaderVectorsWidget.cxx +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Anthony Geay - -#include "pqMEDReaderVectorsWidget.h" -#include "ui_MEDReaderVectorsWidget.h" - -//----------------------------------------------------------------------------- -// Internals -class pqMEDReaderVectorsWidget::pqInternals : public Ui::MEDReaderVectorsWidget -{ -public: - pqInternals(pqMEDReaderVectorsWidget* self) - { - this->setupUi(self); - } -}; - -//----------------------------------------------------------------------------- -pqMEDReaderVectorsWidget::pqMEDReaderVectorsWidget( - vtkSMProxy *smproxy, vtkSMProperty *smproperty, QWidget *parentObject) -: Superclass(smproxy, parentObject), Internals(new pqMEDReaderVectorsWidget::pqInternals(this)) -{ - this->setShowLabel(false); - this->addPropertyLink(this->Internals->GenerateVects, "checked" , - SIGNAL(toggled(bool)), smproperty); -} - -//----------------------------------------------------------------------------- -pqMEDReaderVectorsWidget::~pqMEDReaderVectorsWidget() -{ -} diff --git a/src/Plugins/MEDReader/ParaViewPlugin/pqMEDReaderVectorsWidget.h b/src/Plugins/MEDReader/ParaViewPlugin/pqMEDReaderVectorsWidget.h deleted file mode 100644 index dd2e34a8..00000000 --- a/src/Plugins/MEDReader/ParaViewPlugin/pqMEDReaderVectorsWidget.h +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Anthony Geay - -#ifndef __pqMEDReaderVectorsWidget_h -#define __pqMEDReaderVectorsWidget_h - -#include "pqPropertyWidget.h" - -class pqMEDReaderVectorsWidget : public pqPropertyWidget -{ - Q_OBJECT - typedef pqPropertyWidget Superclass; -public: - pqMEDReaderVectorsWidget( - vtkSMProxy *smproxy, vtkSMProperty *smproperty, QWidget *parentObject = 0); - virtual ~pqMEDReaderVectorsWidget(); - -private: - Q_DISABLE_COPY(pqMEDReaderVectorsWidget); - - class pqInternals; - pqInternals* Internals; -}; - -#endif diff --git a/src/Plugins/MEDReader/ParaViewPlugin/vtkPVMetaDataInformation.cxx b/src/Plugins/MEDReader/ParaViewPlugin/vtkPVMetaDataInformation.cxx deleted file mode 100644 index 9d6754e0..00000000 --- a/src/Plugins/MEDReader/ParaViewPlugin/vtkPVMetaDataInformation.cxx +++ /dev/null @@ -1,142 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Anthony Geay - -#include "vtkPVMetaDataInformation.h" - -#include "vtkAlgorithm.h" -#include "vtkAlgorithmOutput.h" -#include "vtkClientServerStream.h" -#include "vtkExecutive.h" -#include "vtkDataObject.h" -#include "vtkGenericDataObjectReader.h" -#include "vtkGenericDataObjectWriter.h" -#include "vtkInformationDataObjectMetaDataKey.h" -#include "vtkInformation.h" -#include "vtkObjectFactory.h" - -#include "vtkMEDReader.h" - -vtkStandardNewMacro(vtkPVMetaDataInformation); -vtkCxxSetObjectMacro(vtkPVMetaDataInformation, InformationData, vtkDataObject); - -//---------------------------------------------------------------------------- -vtkPVMetaDataInformation::vtkPVMetaDataInformation() -{ - this->InformationData = NULL; -} - -//---------------------------------------------------------------------------- -vtkPVMetaDataInformation::~vtkPVMetaDataInformation() -{ - this->SetInformationData(NULL); -} - -//---------------------------------------------------------------------------- -void vtkPVMetaDataInformation::CopyFromObject(vtkObject* obj) -{ - this->SetInformationData(NULL); - - vtkAlgorithmOutput* algOutput = vtkAlgorithmOutput::SafeDownCast(obj); - if (!algOutput) - { - vtkAlgorithm* alg = vtkAlgorithm::SafeDownCast(obj); - if (alg) - { - algOutput = alg->GetOutputPort(0); - } - - } - if (!algOutput) - { - vtkErrorMacro("Information can only be gathered from a vtkAlgorithmOutput."); - return; - } - - vtkAlgorithm* reader = algOutput->GetProducer(); - vtkInformation* info = reader->GetExecutive()->GetOutputInformation( - algOutput->GetIndex()); - - if (info && info->Has(vtkMEDReader::META_DATA())) - { - this->SetInformationData(vtkDataObject::SafeDownCast(info->Get(vtkMEDReader::META_DATA()))); - } -} - -//---------------------------------------------------------------------------- -void vtkPVMetaDataInformation::CopyToStream(vtkClientServerStream* css) -{ - css->Reset(); - if (!this->InformationData) - { - *css << vtkClientServerStream::Reply - << vtkClientServerStream::InsertArray( - static_cast(NULL), 0) - << vtkClientServerStream::End; - return; - } - - vtkDataObject* clone = this->InformationData->NewInstance(); - clone->ShallowCopy(this->InformationData); - - vtkGenericDataObjectWriter* writer = vtkGenericDataObjectWriter::New(); - writer->SetFileTypeToBinary(); - writer->WriteToOutputStringOn(); - writer->SetInputData(clone); - writer->Write(); - - *css << vtkClientServerStream::Reply - << vtkClientServerStream::InsertArray( - writer->GetBinaryOutputString(), - writer->GetOutputStringLength()) - << vtkClientServerStream::End; - writer->RemoveAllInputs(); - writer->Delete(); - clone->Delete(); -} - -//---------------------------------------------------------------------------- -void vtkPVMetaDataInformation::CopyFromStream(const vtkClientServerStream* css) -{ - this->SetInformationData(0); - vtkTypeUInt32 length; - if (css->GetArgumentLength(0, 0, &length) && length > 0) - { - unsigned char* raw_data = new unsigned char[length]; - css->GetArgument(0, 0, raw_data, length); - vtkGenericDataObjectReader* reader = vtkGenericDataObjectReader::New(); - reader->SetBinaryInputString(reinterpret_cast(raw_data), length); - reader->ReadFromInputStringOn(); - delete []raw_data; - reader->Update(); - this->SetInformationData(reader->GetOutput()); - reader->Delete(); - } -} - -void vtkPVMetaDataInformation::AddInformation(vtkPVInformation*) -{ -} - -//---------------------------------------------------------------------------- -void vtkPVMetaDataInformation::PrintSelf(ostream& os, vtkIndent indent) -{ - this->Superclass::PrintSelf(os, indent); - os << indent << "InformationData: " << this->InformationData << endl; -} diff --git a/src/Plugins/MEDReader/ParaViewPlugin/vtkPVMetaDataInformation.h b/src/Plugins/MEDReader/ParaViewPlugin/vtkPVMetaDataInformation.h deleted file mode 100644 index fbf7bfe3..00000000 --- a/src/Plugins/MEDReader/ParaViewPlugin/vtkPVMetaDataInformation.h +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Anthony Geay - -#ifndef __vtkPVMetaDataInformation_h -#define __vtkPVMetaDataInformation_h - -#include "vtkPVInformation.h" - -class vtkDataObject; -class vtkInformationDataObjectKey; - -class vtkPVMetaDataInformation : public vtkPVInformation -{ -public: - static vtkPVMetaDataInformation* New(); - vtkTypeMacro(vtkPVMetaDataInformation, vtkPVInformation); - void PrintSelf(ostream& os, vtkIndent indent); - - // Description: - // Transfer information about a single object into this object. - virtual void CopyFromObject(vtkObject*); - - //BTX - // Description: - // Manage a serialized version of the information. - virtual void CopyToStream(vtkClientServerStream*); - virtual void CopyFromStream(const vtkClientServerStream*); - virtual void AddInformation(vtkPVInformation*); - //ETX - - // Description: - // Returns the Information Data. - vtkGetObjectMacro(InformationData, vtkDataObject); - -//BTX -protected: - vtkPVMetaDataInformation(); - ~vtkPVMetaDataInformation(); - void SetInformationData(vtkDataObject*); - vtkDataObject* InformationData; - -private: - vtkPVMetaDataInformation(const vtkPVMetaDataInformation&); // Not implemented - void operator=(const vtkPVMetaDataInformation&); // Not implemented -//ETX -}; - -#endif diff --git a/src/Plugins/MEDReader/Plugin/ParaViewPlugin/CMakeLists.txt.old b/src/Plugins/MEDReader/Plugin/ParaViewPlugin/CMakeLists.txt.old new file mode 100644 index 00000000..605b7fe3 --- /dev/null +++ b/src/Plugins/MEDReader/Plugin/ParaViewPlugin/CMakeLists.txt.old @@ -0,0 +1,138 @@ +# Copyright (C) 2010-2019 CEA/DEN, EDF R&D +# +# This library 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. +# +# 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 +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +# + +INCLUDE_DIRECTORIES( + ${CMAKE_CURRENT_SOURCE_DIR}/../IO + ${CMAKE_CURRENT_SOURCE_DIR}/../../MEDWriter/IO + ) + +IF(PARAVIEW_BUILD_QT_GUI) + + QT_WRAP_UIC(CLIENT_UI_SRCS + Resources/UI/MEDReaderVectorsWidget.ui + Resources/UI/MEDReaderTimeModeWidget.ui) + + # create a plugin that implements an object panel for the reader + SET(SM_SRCS + vtkPVMetaDataInformation.cxx + ../IO/vtkMEDReader.cxx + ../IO/vtkExtractGroup.cxx + ../IO/vtkELNOMeshFilter.cxx + ../IO/vtkELNOSurfaceFilter.cxx + ../IO/vtkELNOFilter.cxx + ../IO/vtkExtractCellType.cxx + ../IO/vtkMEDQuadraturePointsGenerator.cxx + ) + + SET(CLIENT_SRCS + pqExtractGroupFieldsWidget.cxx + pqAbstractFieldsWidget.cxx + VectBoolSpreadSheet.cxx + VectBoolWidget.cxx + pqMEDReaderGraphUtils.cxx + pqMEDReaderVectorsWidget.cxx + pqMEDReaderTimeModeWidget.cxx + pqMEDReaderReloadWidget.cxx + pqMEDReaderTimesFlagsWidget.cxx + pqMEDReaderFieldsWidget.cxx) + + QT_WRAP_MOC(MOC_SRCS + pqExtractGroupFieldsWidget.h + pqAbstractFieldsWidget.h + VectBoolSpreadSheet.h + VectBoolWidget.h + pqMEDReaderVectorsWidget.h + pqMEDReaderTimeModeWidget.h + pqMEDReaderReloadWidget.h + pqMEDReaderTimesFlagsWidget.h + pqMEDReaderFieldsWidget.h) + + ADD_PARAVIEW_PROPERTY_WIDGET(MEDREADER_TIMEMODE_IFACES MEDREADER_TIMEMODE_IFACE_SRCS + TYPE "MEDReaderTimeModeWidgetType" + CLASS_NAME pqMEDReaderTimeModeWidget) + + ADD_PARAVIEW_PROPERTY_WIDGET(MEDREADER_RELOAD_IFACES MEDREADER_RELOAD_IFACE_SRCS + TYPE "MEDReaderReloadWidgetType" + CLASS_NAME pqMEDReaderReloadWidget) + + ADD_PARAVIEW_PROPERTY_WIDGET(MEDREADER_VECTORS_IFACES MEDREADER_VECTORS_IFACE_SRCS + TYPE "MEDReaderVectorsWidgetType" + CLASS_NAME pqMEDReaderVectorsWidget) + + ADD_PARAVIEW_PROPERTY_WIDGET(MEDREADER_TIMESFLAGS_IFACES MEDREADER_TIMESFLAGS_IFACE_SRCS + TYPE "MEDReaderTimesFlagsWidgetType" + CLASS_NAME pqMEDReaderTimesFlagsWidget) + + ADD_PARAVIEW_PROPERTY_WIDGET(MEDREADER_FIELDS_IFACES MEDREADER_FIELDS_IFACE_SRCS + TYPE "MEDReaderFieldsWidgetType" + CLASS_NAME pqMEDReaderFieldsWidget) + + ADD_PARAVIEW_PROPERTY_WIDGET(EXTRACTGROUP_FIELDS_IFACES EXTRACTGROUP_FIELDS_IFACES_SRCS + TYPE "ExtractGroupFieldsWidgetType" + CLASS_NAME pqExtractGroupFieldsWidget) + + # create the med reader plugin itself + ADD_PARAVIEW_PLUGIN(MEDReaderPlugin "4.0" + SERVER_MANAGER_SOURCES ${SM_SRCS} + SERVER_MANAGER_XML Resources/MEDReaderServer.xml + GUI_INTERFACES + ${MEDREADER_TIMEMODE_IFACES} + ${MEDREADER_RELOAD_IFACES} + ${MEDREADER_TIMESFLAGS_IFACES} + ${MEDREADER_FIELDS_IFACES} + ${MEDREADER_VECTORS_IFACES} + ${EXTRACTGROUP_FIELDS_IFACES} + GUI_RESOURCES Resources/pqMEDReader.qrc + SOURCES + ${CLIENT_SRCS} + ${CLIENT_UI_SRCS} + ${MOC_SRCS} + ${MEDREADER_TIMEMODE_IFACE_SRCS} + ${MEDREADER_RELOAD_IFACE_SRCS} + ${MEDREADER_TIMESFLAGS_IFACE_SRCS} + ${MEDREADER_FIELDS_IFACE_SRCS} + ${MEDREADER_VECTORS_IFACE_SRCS} + ${EXTRACTGROUP_FIELDS_IFACES_SRCS} + ) + +ELSE(PARAVIEW_BUILD_QT_GUI) + + # create the med reader plugin itself + ADD_PARAVIEW_PLUGIN(MEDReaderPlugin "4.0" + SERVER_MANAGER_SOURCES ${SM_SRCS} + SERVER_MANAGER_XML Resources/MEDReaderServer.xml + CS_KITS + # this is the same name as the name in module.cmake file IO + # directory. + vtkMEDReader + ) + +ENDIF(PARAVIEW_BUILD_QT_GUI) + +TARGET_LINK_LIBRARIES(MEDReaderPlugin MEDLoaderForPV) + +# Install +INSTALL( + TARGETS MEDReaderPlugin + RUNTIME DESTINATION lib/paraview + LIBRARY DESTINATION lib/paraview + ARCHIVE DESTINATION lib/paraview + ) + + diff --git a/src/Plugins/MEDReader/TODO.txt b/src/Plugins/MEDReader/TODO.txt deleted file mode 100644 index 7c598555..00000000 --- a/src/Plugins/MEDReader/TODO.txt +++ /dev/null @@ -1,68 +0,0 @@ - - - -TODO : ------- - - - -3 - propagate the update of filters connected directly or not (typically ExtractGroup) to the MEDReader when the groups have been updated. -UC : ForMEDReader16.med, then extractgroup, then return to MEDReader properties and select zeField3_1 & zeField4_1 -> ExtractGroup filter is out of date and "Apply" button not green. - - -Known bug : ------------ - - -Warning for users : -------------------- - -Try to avoid to change the localization along time on a same field -because it leads to an unfriendly behavior when playing. (bug seen in EDF2420 in ssnp121.rmed when applying GaussPoint filter and running different time steps. - - -TODO in MED: ------------- - -- Manage degenerated cases. - -DONE ----- - -0- Sur le time quand tout a echouer prendre le plus grand < (07/01/2014) - -1 - Load ForMEDReader8.med, Load ForMEDReader17.med --> throw because of missynchronization of time. -> Alejandro (07/01/2014) - -1 - ELNO to be added only once not for each GAUSS_NE -> To test a file having > 1 field with GAUSS_NE - -1 - Keep tracks of built support to accelerate rendering in MEDFileFieldRepresentation. - -2 - in branch EDF1 : adm_local_without_kernel to put in install of MED_SRC -when in STANDALONE mode. - -0 - test22 doit etre sur les seg2 et tri3 - -1 - When Reload Applied it is possible with gui to unselect all ! - -0 - protect ExtractGroup against throw - -0 - protect ExctractCellType against throw - -0 - Extract cell type + Extract Group - -0 - bug client side when the field having the max number of TS is not first. - -0 - ELGA arrays choice of GaussPoints filter - -0 - Manage file containing only cartesian meshes. - -0 - Bug on vtkExtractGroup when attempting to extract on empty group. Previously, it led to SIGSEGV. - -0 - Add the frequency information in mode mode in the name of arrays in DataSet. - -0 - Addition of MeshName property in ExtractGroup (see testMEDReader9.py) - -0 - Bug when fields contains @ - -1 - Bug on reload the first leaf is not systematically activated. \ No newline at end of file diff --git a/src/Plugins/MEDReader/Test/Baselines/testMEDReader0.png b/src/Plugins/MEDReader/Test/Baselines/testMEDReader0.png deleted file mode 100644 index 86ef73da..00000000 Binary files a/src/Plugins/MEDReader/Test/Baselines/testMEDReader0.png and /dev/null differ diff --git a/src/Plugins/MEDReader/Test/Baselines/testMEDReader10.png b/src/Plugins/MEDReader/Test/Baselines/testMEDReader10.png deleted file mode 100644 index 4f0907df..00000000 Binary files a/src/Plugins/MEDReader/Test/Baselines/testMEDReader10.png and /dev/null differ diff --git a/src/Plugins/MEDReader/Test/Baselines/testMEDReader13.png b/src/Plugins/MEDReader/Test/Baselines/testMEDReader13.png deleted file mode 100644 index ea4ebe98..00000000 Binary files a/src/Plugins/MEDReader/Test/Baselines/testMEDReader13.png and /dev/null differ diff --git a/src/Plugins/MEDReader/Test/Baselines/testMEDReader14.png b/src/Plugins/MEDReader/Test/Baselines/testMEDReader14.png deleted file mode 100644 index dea5f2d7..00000000 Binary files a/src/Plugins/MEDReader/Test/Baselines/testMEDReader14.png and /dev/null differ diff --git a/src/Plugins/MEDReader/Test/Baselines/testMEDReader15.png b/src/Plugins/MEDReader/Test/Baselines/testMEDReader15.png deleted file mode 100644 index 4af9e7ea..00000000 Binary files a/src/Plugins/MEDReader/Test/Baselines/testMEDReader15.png and /dev/null differ diff --git a/src/Plugins/MEDReader/Test/Baselines/testMEDReader19.png b/src/Plugins/MEDReader/Test/Baselines/testMEDReader19.png deleted file mode 100644 index f05519f4..00000000 Binary files a/src/Plugins/MEDReader/Test/Baselines/testMEDReader19.png and /dev/null differ diff --git a/src/Plugins/MEDReader/Test/Baselines/testMEDReader2.png b/src/Plugins/MEDReader/Test/Baselines/testMEDReader2.png deleted file mode 100644 index 3489d127..00000000 Binary files a/src/Plugins/MEDReader/Test/Baselines/testMEDReader2.png and /dev/null differ diff --git a/src/Plugins/MEDReader/Test/Baselines/testMEDReader20.png b/src/Plugins/MEDReader/Test/Baselines/testMEDReader20.png deleted file mode 100644 index 71cbf867..00000000 Binary files a/src/Plugins/MEDReader/Test/Baselines/testMEDReader20.png and /dev/null differ diff --git a/src/Plugins/MEDReader/Test/Baselines/testMEDReader21.png b/src/Plugins/MEDReader/Test/Baselines/testMEDReader21.png deleted file mode 100644 index 6421dbc3..00000000 Binary files a/src/Plugins/MEDReader/Test/Baselines/testMEDReader21.png and /dev/null differ diff --git a/src/Plugins/MEDReader/Test/Baselines/testMEDReader3.png b/src/Plugins/MEDReader/Test/Baselines/testMEDReader3.png deleted file mode 100644 index 8b6031de..00000000 Binary files a/src/Plugins/MEDReader/Test/Baselines/testMEDReader3.png and /dev/null differ diff --git a/src/Plugins/MEDReader/Test/Baselines/testMEDReader4.png b/src/Plugins/MEDReader/Test/Baselines/testMEDReader4.png deleted file mode 100644 index 17c6a9b6..00000000 Binary files a/src/Plugins/MEDReader/Test/Baselines/testMEDReader4.png and /dev/null differ diff --git a/src/Plugins/MEDReader/Test/Baselines/testMEDReader5.png b/src/Plugins/MEDReader/Test/Baselines/testMEDReader5.png deleted file mode 100644 index 5b3d99b6..00000000 Binary files a/src/Plugins/MEDReader/Test/Baselines/testMEDReader5.png and /dev/null differ diff --git a/src/Plugins/MEDReader/Test/Baselines/testMEDReader6.png b/src/Plugins/MEDReader/Test/Baselines/testMEDReader6.png deleted file mode 100644 index 64b8247f..00000000 Binary files a/src/Plugins/MEDReader/Test/Baselines/testMEDReader6.png and /dev/null differ diff --git a/src/Plugins/MEDReader/Test/Baselines/testMEDReader7.png b/src/Plugins/MEDReader/Test/Baselines/testMEDReader7.png deleted file mode 100644 index a6df19ec..00000000 Binary files a/src/Plugins/MEDReader/Test/Baselines/testMEDReader7.png and /dev/null differ diff --git a/src/Plugins/MEDReader/Test/Baselines/testMEDReader8.png b/src/Plugins/MEDReader/Test/Baselines/testMEDReader8.png deleted file mode 100644 index ebbd4f77..00000000 Binary files a/src/Plugins/MEDReader/Test/Baselines/testMEDReader8.png and /dev/null differ diff --git a/src/Plugins/MEDReader/Test/CMakeLists.txt b/src/Plugins/MEDReader/Test/CMakeLists.txt deleted file mode 100644 index 1b1426a0..00000000 --- a/src/Plugins/MEDReader/Test/CMakeLists.txt +++ /dev/null @@ -1,119 +0,0 @@ -# Copyright (C) 2010-2019 CEA/DEN, EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# - -INCLUDE(tests.set) - -IF(NOT SALOME_INSTALL_SCRIPT_SCRIPTS) - SET(SALOME_INSTALL_SCRIPT_SCRIPTS "bin/salome") -ENDIF(NOT SALOME_INSTALL_SCRIPT_SCRIPTS) - -SET(TEST_INSTALL_DIRECTORY ${SALOME_INSTALL_SCRIPT_SCRIPTS}/test/MEDReader) -SET(BASELINES_DIR "${CMAKE_CURRENT_SOURCE_DIR}/Baselines") - -IF(KW_TESTING_PLATFORM) - -cmake_minimum_required(VERSION 2.7) - -find_package(ParaView REQUIRED) -include(${PARAVIEW_USE_FILE}) - -include(ParaViewTestingMacros) -include(FindPythonModules) - -include(${PROJECT_SOURCE_DIR}/testing/testFunctions.cmake) -set(PV_PLUGIN_PATH "${CMAKE_BINARY_DIR}/lib/") - -include(CTest) - -enable_testing() - -set(PARAVIEW_BIN_DIR "${ParaView_DIR}/bin" CACHE PATH "ParaView binary path") - -set(PVTEST_DRIVER "${PARAVIEW_BIN_DIR}/smTestDriver") -set(PARAVIEW_CLIENT "${PARAVIEW_BIN_DIR}/paraview") -set(PARAVIEW_SERVER "${PARAVIEW_BIN_DIR}/pvserver") -set(PVPYTHON "${PARAVIEW_BIN_DIR}/pvpython") - -set(PYTHON_SCRIPTS_DIR "${CMAKE_CURRENT_SOURCE_DIR}") -set(TEMP_DIR "${CMAKE_CURRENT_BINARY_DIR}/Testing/Temporary") - -if(NOT EXISTS ${TEMP_DIR}) - file(MAKE_DIRECTORY ${TEMP_DIR}) -endif() - -# Override vtk_add_test_* variables for use with ParaView. -macro (_myy_override_vtk_dirs) - set(VTK_TEST_DATA_DIR ${PYTHON_SCRIPTS_DIR}) - set(VTK_BASELINE_DIR ${BASELINES_DIR}) - set(VTK_TEST_OUTPUT_DIR ${TEMP_DIR}) - set(VTK_TEST_DATA_TARGET ParaViewData) -endmacro () - -function (myy_add_python_test) - message(STATUS "Add Python test for ${ARGV2}") - set(VTK_PYTHON_EXE "${PVPYTHON}") - list(APPEND VTK_PYTHON_ARGS -dr - ${PARAVIEW_PYTHON_ARGS}) - _myy_override_vtk_dirs() - myvtk_add_test_python(${ARGN}) -endfunction () - -# Test all python scripts -file(GLOB scripts "${PYTHON_SCRIPTS_DIR}/*py") -foreach(file ${scripts}) - get_filename_component(fname ${file} NAME) - myy_add_python_test( - NO_DATA NO_RT - ${fname}) - INSTALL(FILES ${file} - DESTINATION ${TEST_INSTALL_DIRECTORY}) -endforeach() - -ELSE(KW_TESTING_PLATFORM) - -SALOME_GENERATE_TESTS_ENVIRONMENT(tests_env) - -SET(OTHER_OPTIONS) -IF(SALOME_PARAVIS_NO_VISU_TESTS) - LIST(APPEND OTHER_OPTIONS "-D") -ENDIF() - -FOREACH(tfile ${TEST_NUMBERS}) - ADD_TEST(testMEDReader${tfile} ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/testMEDReader${tfile}.py -B ${BASELINES_DIR} ${OTHER_OPTIONS}) - SET_TESTS_PROPERTIES(testMEDReader${tfile} PROPERTIES ENVIRONMENT "${tests_env}") -ENDFOREACH() - -ENDIF(KW_TESTING_PLATFORM) - - -# Application tests -FOREACH(tfile ${TEST_NUMBERS}) - INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/testMEDReader${tfile}.py - DESTINATION ${TEST_INSTALL_DIRECTORY}) -ENDFOREACH() - -FILE(GLOB BASELINE_FILES "${BASELINES_DIR}/*") -FOREACH(baseline_file ${BASELINE_FILES}) - INSTALL(FILES ${baseline_file} DESTINATION ${TEST_INSTALL_DIRECTORY}/Baselines) -ENDFOREACH() - -INSTALL(FILES CTestTestfileInstall.cmake - DESTINATION ${TEST_INSTALL_DIRECTORY} - RENAME CTestTestfile.cmake) -INSTALL(FILES tests.set MEDReaderHelper.py DESTINATION ${TEST_INSTALL_DIRECTORY}) diff --git a/src/Plugins/MEDReader/Test/CTestTestfileInstall.cmake b/src/Plugins/MEDReader/Test/CTestTestfileInstall.cmake deleted file mode 100644 index cb0329e0..00000000 --- a/src/Plugins/MEDReader/Test/CTestTestfileInstall.cmake +++ /dev/null @@ -1,31 +0,0 @@ -# Copyright (C) 2015-2019 CEA/DEN, EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# - -INCLUDE(tests.set) - -SET(COMPONENT_NAME MEDREADER) -SET(TIMEOUT 60) - -set(BASELINES_DIR "Baselines") - -FOREACH(tfile ${TEST_NUMBERS}) - SET(TEST_NAME MEDREADER_${tfile}) - ADD_TEST(${TEST_NAME} python testMEDReader${tfile}.py -B ${BASELINES_DIR}) - SET_TESTS_PROPERTIES(${TEST_NAME} PROPERTIES LABELS "${COMPONENT_NAME};REQUIRE_X_SERVER" TIMEOUT ${TIMEOUT}) -ENDFOREACH() diff --git a/src/Plugins/MEDReader/Test/MEDReaderHelper.py b/src/Plugins/MEDReader/Test/MEDReaderHelper.py deleted file mode 100644 index 7d970f0f..00000000 --- a/src/Plugins/MEDReader/Test/MEDReaderHelper.py +++ /dev/null @@ -1,43 +0,0 @@ -# -*- coding: iso-8859-1 -*- -# Copyright (C) 2019 CEA/DEN, EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# -# Author : Anthony Geay (EDF R&D) - -def WriteInTmpDir(func): - def decoratedFunc(*args,**kwargs): - import tempfile,os - ret = None - with tempfile.TemporaryDirectory() as tmpdirname: - os.chdir(tmpdirname) - ret = func(*args,**kwargs) - pass - return ret - return decoratedFunc - -def RetriveBaseLine(imgFile): - import os,sys - try: - baselineIndex = sys.argv.index('-B')+1 - baselinePath = sys.argv[baselineIndex] - except: - print("Could not get baseline directory. Test failed.") - exit(1) - baseline_file = os.path.join(baselinePath, imgFile) - return os.path.abspath(baseline_file) - diff --git a/src/Plugins/MEDReader/Test/testMEDReader0.py b/src/Plugins/MEDReader/Test/testMEDReader0.py deleted file mode 100644 index a8af4345..00000000 --- a/src/Plugins/MEDReader/Test/testMEDReader0.py +++ /dev/null @@ -1,146 +0,0 @@ -# -*- coding: iso-8859-1 -*- -# Copyright (C) 2007-2019 CEA/DEN, EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# -# Author : Anthony Geay - -import os -import sys - -from medcoupling import * -from paraview.simple import * -from MEDReaderHelper import WriteInTmpDir,RetriveBaseLine - -def GenerateCase(): - fname="testMEDReader0.med" - ######### - mz=MEDCoupling1SGTUMesh("mesh",NORM_QUAD9) - mz.setNodalConnectivity(DataArrayInt([0,6,37,12,76,112,113,82,205,12,37,38,13,113,114,115,83,206,13,38,9,1,115,116,79,84,207,6,7,39,37,77,117,118,112,208,37,39,40,38,118,119,120,114,209,38,40,10,9,120,121,80,116,210,7,8,41,39,78,122,123,117,211,39,41,42,40,123,124,125,119,212,40,42,11,10,125,126,81,121,213,1,9,43,17,79,127,128,88,214,17,43,44,18,128,129,130,89,215,18,44,14,2,130,131,85,90,216,9,10,45,43,80,132,133,127,217,43,45,46,44,133,134,135,129,218,44,46,15,14,135,136,86,131,219,10,11,47,45,81,137,138,132,220,45,47,48,46,138,139,140,134,221,46,48,16,15,140,141,87,136,222,1,9,49,22,79,142,143,94,223,22,49,50,23,143,144,145,95,224,23,50,51,24,145,146,147,96,225,24,51,52,25,147,148,149,97,226,25,52,53,26,149,150,151,98,227,26,53,19,3,151,152,91,99,228,9,10,54,49,80,153,154,142,229,49,54,55,50,154,155,156,144,230,50,55,56,51,156,157,158,146,231,51,56,57,52,158,159,160,148,232,52,57,58,53,160,161,162,150,233,53,58,20,19,162,163,92,152,234,10,11,59,54,81,164,165,153,235,54,59,60,55,165,166,167,155,236,55,60,61,56,167,168,169,157,237,56,61,62,57,169,170,171,159,238,57,62,63,58,171,172,173,161,239,58,63,21,20,173,174,93,163,240,4,27,64,30,100,175,176,103,241,30,64,65,31,176,177,178,104,242,31,65,19,3,178,179,91,105,243,27,28,66,64,101,180,181,175,244,64,66,67,65,181,182,183,177,245,65,67,20,19,183,184,92,179,246,28,29,68,66,102,185,186,180,247,66,68,69,67,186,187,188,182,248,67,69,21,20,188,189,93,184,249,3,19,70,35,91,190,191,109,250,35,70,71,36,191,192,193,110,251,36,71,32,5,193,194,106,111,252,19,20,72,70,92,195,196,190,253,70,72,73,71,196,197,198,192,254,71,73,33,32,198,199,107,194,255,20,21,74,72,93,200,201,195,256,72,74,75,73,201,202,203,197,257,73,75,34,33,203,204,108,199,258])) - coords=DataArrayDouble([-0.04,0.015,0.,0.,0.015,0.,0.04,0.015,0.,0.,0.105,0.,-0.04,0.105,0.,0.04,0.105,0.,-0.04,0.015,0.015,-0.04,0.015,0.03,-0.04,0.015,0.045,0.,0.015,0.015,0.,0.015,0.03,0.,0.015,0.045,-0.026666666666666665,0.015,0.,-0.013333333333333329,0.015,0.,0.04,0.015,0.015,0.04,0.015,0.03,0.04,0.015,0.045,0.013333333333333336,0.015,0.,0.026666666666666672,0.015,0.,0.,0.105,0.015,0.,0.105,0.03,0.,0.105,0.045,0.,0.03,0.,0.,0.045,0.,0.,0.06,0.,0.,0.075,0.,0.,0.09,0.,-0.04,0.105,0.015,-0.04,0.105,0.03,-0.04,0.105,0.045,-0.026666666666666665,0.105,0.,-0.013333333333333329,0.105,0.,0.04,0.105,0.015,0.04,0.105,0.03,0.04,0.105,0.045,0.013333333333333336,0.105,0.,0.026666666666666672,0.105,0.,-0.026666666666666665,0.015,0.015,-0.013333333333333326,0.015,0.015,-0.026666666666666665,0.015,0.03,-0.013333333333333326,0.015,0.03,-0.026666666666666665,0.015,0.045,-0.013333333333333329,0.015,0.045,0.013333333333333338,0.015,0.015,0.026666666666666675,0.015,0.015,0.013333333333333338,0.015,0.03,0.026666666666666675,0.015,0.03,0.013333333333333336,0.015,0.045,0.026666666666666672,0.015,0.045,0.,0.03,0.015,0.,0.045,0.015,0.,0.06,0.015,0.,0.07500000000000001,0.015,0.,0.09,0.015,0.,0.03,0.03,0.,0.045,0.03,0.,0.06,0.03,0.,0.075,0.03,0.,0.09,0.03,0.,0.03,0.045,0.,0.045,0.045,0.,0.06,0.045,0.,0.075,0.045,0.,0.09,0.045,-0.026666666666666665,0.105,0.015,-0.013333333333333326,0.105,0.015,-0.026666666666666665,0.105,0.03,-0.013333333333333326,0.105,0.03,-0.026666666666666665,0.105,0.045,-0.013333333333333329,0.105,0.045,0.013333333333333338,0.105,0.015,0.026666666666666675,0.105,0.015,0.013333333333333338,0.105,0.03,0.026666666666666675,0.105,0.03,0.013333333333333336,0.105,0.045,0.026666666666666672,0.105,0.045,-0.04,0.015,0.0075,-0.04,0.015,0.0225,-0.04,0.015,0.0375,0.,0.015,0.0075,0.,0.015,0.0225,0.,0.015,0.0375,-0.03333333333333333,0.015,0.,-0.02,0.015,0.,-0.0066666666666666645,0.015,0.,0.04,0.015,0.0075,0.04,0.015,0.0225,0.04,0.015,0.0375,0.006666666666666668,0.015,0.,0.02,0.015,0.,0.03333333333333334,0.015,0.,0.,0.105,0.0075,0.,0.105,0.0225,0.,0.105,0.0375,0.,0.0225,0.,0.,0.0375,0.,0.,0.0525,0.,0.,0.0675,0.,0.,0.0825,0.,0.,0.0975,0.,-0.04,0.105,0.0075,-0.04,0.105,0.0225,-0.04,0.105,0.0375,-0.03333333333333333,0.105,0.,-0.02,0.105,0.,-0.0066666666666666645,0.105,0.,0.04,0.105,0.0075,0.04,0.105,0.0225,0.04,0.105,0.0375,0.006666666666666668,0.105,0.,0.02,0.105,0.,0.03333333333333334,0.105,0.,-0.03333333333333333,0.015,0.015,-0.026666666666666665,0.015,0.0075,-0.02,0.015,0.015,-0.013333333333333327,0.015,0.0075,-0.006666666666666663,0.015,0.015,-0.03333333333333333,0.015,0.03,-0.026666666666666665,0.015,0.0225,-0.02,0.015,0.03,-0.013333333333333326,0.015,0.0225,-0.006666666666666663,0.015,0.03,-0.03333333333333333,0.015,0.045,-0.026666666666666665,0.015,0.0375,-0.02,0.015,0.045,-0.013333333333333327,0.015,0.0375,-0.0066666666666666645,0.015,0.045,0.006666666666666669,0.015,0.015,0.013333333333333336,0.015,0.0075,0.020000000000000007,0.015,0.015,0.026666666666666672,0.015,0.0075,0.03333333333333334,0.015,0.015,0.006666666666666669,0.015,0.03,0.013333333333333338,0.015,0.0225,0.02,0.015,0.03,0.026666666666666675,0.015,0.0225,0.03333333333333334,0.015,0.03,0.006666666666666668,0.015,0.045,0.013333333333333336,0.015,0.0375,0.02,0.015,0.045,0.026666666666666672,0.015,0.0375,0.03333333333333334,0.015,0.045,0.,0.0225,0.015,0.,0.03,0.0075,0.,0.0375,0.015,0.,0.045,0.0075,0.,0.0525,0.015,0.,0.06,0.0075,0.,0.0675,0.015,0.,0.07500000000000001,0.0075,0.,0.0825,0.015,0.,0.09,0.0075,0.,0.0975,0.015,0.,0.0225,0.03,0.,0.03,0.0225,0.,0.0375,0.03,0.,0.045,0.0225,0.,0.0525,0.03,0.,0.06,0.0225,0.,0.0675,0.03,0.,0.07500000000000001,0.0225,0.,0.08249999999999999,0.03,0.,0.09,0.0225,0.,0.0975,0.03,0.,0.0225,0.045,0.,0.03,0.0375,0.,0.0375,0.045,0.,0.045,0.0375,0.,0.0525,0.045,0.,0.06,0.0375,0.,0.0675,0.045,0.,0.075,0.0375,0.,0.08249999999999999,0.045,0.,0.09,0.0375,0.,0.0975,0.045,-0.03333333333333333,0.105,0.015,-0.026666666666666665,0.105,0.0075,-0.02,0.105,0.015,-0.013333333333333327,0.105,0.0075,-0.006666666666666663,0.105,0.015,-0.03333333333333333,0.105,0.03,-0.026666666666666665,0.105,0.0225,-0.02,0.105,0.03,-0.013333333333333326,0.105,0.0225,-0.006666666666666663,0.105,0.03,-0.03333333333333333,0.105,0.045,-0.026666666666666665,0.105,0.0375,-0.02,0.105,0.045,-0.013333333333333327,0.105,0.0375,-0.0066666666666666645,0.105,0.045,0.006666666666666669,0.105,0.015,0.013333333333333336,0.105,0.0075,0.020000000000000007,0.105,0.015,0.026666666666666672,0.105,0.0075,0.03333333333333334,0.105,0.015,0.006666666666666669,0.105,0.03,0.013333333333333338,0.105,0.0225,0.020000000000000007,0.105,0.03,0.026666666666666675,0.105,0.0225,0.03333333333333334,0.105,0.03,0.006666666666666668,0.105,0.045,0.013333333333333336,0.105,0.0375,0.02,0.105,0.045,0.026666666666666672,0.105,0.0375,0.03333333333333334,0.105,0.045,-0.03333333333333333,0.015,0.0075,-0.02,0.015,0.0075,-0.006666666666666664,0.015,0.0075,-0.03333333333333333,0.015,0.0225,-0.02,0.015,0.0225,-0.006666666666666663,0.015,0.0225,-0.03333333333333333,0.015,0.0375,-0.02,0.015,0.0375,-0.006666666666666662,0.015,0.0375,0.006666666666666668,0.015,0.0075,0.02,0.015,0.0075,0.03333333333333334,0.015,0.0075,0.006666666666666669,0.015,0.0225,0.020000000000000007,0.015,0.0225,0.03333333333333334,0.015,0.0225,0.006666666666666668,0.015,0.0375,0.02,0.015,0.0375,0.03333333333333334,0.015,0.0375,0.,0.0225,0.0075,0.,0.0375,0.0075,0.,0.0525,0.0075,0.,0.0675,0.0075,0.,0.0825,0.0075,0.,0.0975,0.0075,0.,0.0225,0.0225,0.,0.0375,0.0225,0.,0.0525,0.0225,0.,0.0675,0.0225,0.,0.0825,0.0225,0.,0.0975,0.0225,0.,0.0225,0.0375,0.,0.0375,0.0375,0.,0.0525,0.0375,0.,0.0675,0.0375,0.,0.08249999999999999,0.0375,0.,0.0975,0.0375,-0.03333333333333333,0.105,0.0075,-0.02,0.105,0.0075,-0.006666666666666664,0.105,0.0075,-0.03333333333333333,0.105,0.0225,-0.02,0.105,0.0225,-0.006666666666666663,0.105,0.0225,-0.03333333333333333,0.105,0.0375,-0.02,0.105,0.0375,-0.006666666666666662,0.105,0.0375,0.006666666666666668,0.105,0.0075,0.02,0.105,0.0075,0.03333333333333334,0.105,0.0075,0.006666666666666669,0.105,0.0225,0.020000000000000007,0.105,0.0225,0.03333333333333334,0.105,0.0225,0.006666666666666668,0.105,0.0375,0.02,0.105,0.0375,0.03333333333333334,0.105,0.0375],259,3) - coords.setInfoOnComponents(['X [INCONNUE]','Y [INCONNUE]','Z [INCONNUE]']) - mz.setCoords(coords) - mz=mz.buildUnstructured() - # - arr0=DataArrayDouble() - vals0=9*[-3593.,85220.,-15343.,-438.,11985.,-15343.,2716.,-61248.,-15343.,5488.,101072.,-16250.,549.,13186.,-16250.,-4389.,-74699.,-16250.,9988.,101646.,-17156.,1537.,14386.,-17156.,-6913.,-72874.,-17156.,22178.,120238.,-19521.,2342.,14222.,-19521.,-17493.,-91793.,-19521.,37737.,139840.,-21887.,3147.,14059.,-21887.,-31443.,-111722.,-21887.,34350.,140668.,-18690.,3714.,16214.,-18690.,-26922.,-108238.,-18690.,34563.,153494.,-15493.,4281.,18370.,-15493.,-26000.,-116753.,-15493.,2147.,115356.,-15418.,1921.,15178.,-15418.,1695.,-84999.,-15418.,12408.,118616.,-17470.,2131.,14700.,-17470.,-8144.,-89215.,-17470.,15624.,100983.,-16718.,2286.,15441.,-16718.,-11050.,-70101.,-16718.,19381.,102680.,-17191.,2505.,16813.,-17191.,-14370.,-69054.,-17191.,22911.,103615.,-17665.,2725.,18184.,-17665.,-17461.,-67245.,-17665.,32377.,125140.,-20005.,4011.,17741.,-20005.,-24353.,-89657.,-20005.,43183.,147067.,-22345.,5298.,17297.,-22345.,-32586.,-112472.,-22345.,41570.,144664.,-22105.,4896.,15874.,-22105.,-31778.,-112915.,-22105.,40070.,142637.,-21866.,4493.,14451.,-21866.,-31083.,-113734.,-21866.,25367.,121066.,-19292.,3390.,14946.,-19292.,-18587.,-91173.,-19292.,28901.,123199.,-19648.,3701.,16343.,-19648.,-21499.,-90512.,-19648.,23716.,103481.,-17470.,2234.,18509.,-17470.,-19247.,-66463.,-17470.,22561.,104808.,-17142.,1238.,20732.,-17142.,-20084.,-63343.,-17142.,21499.,106443.,-16813.,242.,22956.,-16813.,-21014.,-60531.,-16813.,32906.,133441.,-20775.,3873.,26633.,-20775.,-25158.,-80173.,-20775.,45801.,160885.,-24737.,7505.,30311.,-24737.,-30791.,-100262.,-24737.,44184.,154705.,-23601.,5922.,24329.,-23601.,-32340.,-106046.,-23601.,42566.,148521.,-22465.,4338.,18347.,-22465.,-33888.,-111825.,-22465.,32545.,125822.,-19968.,3286.,18428.,-19968.,-25972.,-88965.,-19968.,32703.,129556.,-20371.,3580.,22531.,-20371.,-25542.,-84493.,-20371.,-580.,50781.,-14878.,-188.,10419.,-14878.,203.,-29941.,-14878.,974.,53486.,-13087.,-197.,11696.,-13087.,-1370.,-30094.,-13087.,2154.,54941.,-11297.,-206.,12972.,-11297.,-2567.,-28996.,-11297.,4921.,72039.,-13221.,709.,13770.,-13221.,-3503.,-44499.,-13221.,6472.,88772.,-15144.,1624.,14567.,-15144.,-3223.,-59637.,-15144.,4104.,85353.,-15580.,600.,13047.,-15580.,-2903.,-59258.,-15580.,1258.,80341.,-16016.,-423.,11526.,-16016.,-2105.,-57288.,-16016.,-822.,65212.,-15447.,-306.,10973.,-15447.,210.,-43266.,-15447.,2262.,69336.,-14334.,201.,12371.,-14334.,-1859.,-44593.,-14334.,4047.,55415.,-11562.,137.,13264.,-11562.,-3772.,-28887.,-11562.,6455.,56737.,-11164.,80.,14219.,-11164.,-6294.,-28298.,-11164.,8701.,57516.,-10766.,23.,15175.,-10766.,-8653.,-27166.,-10766.,12843.,74210.,-13196.,662.,16118.,-13196.,-11519.,-41972.,-13196.,17837.,91160.,-15627.,1300.,17062.,-15627.,-15237.,-57034.,-15627.,14573.,90279.,-15674.,1166.,15841.,-15674.,-12240.,-58596.,-15674.,11497.,90026.,-15722.,1033.,14619.,-15722.,-9431.,-60786.,-15722.,7014.,72493.,-13642.,585.,13941.,-13642.,-5844.,-44609.,-13642.,9922.,73330.,-13419.,623.,15030.,-13419.,-8675.,-43270.,-13419.,9608.,58062.,-10666.,-408.,15882.,-10666.,-10425.,-26297.,-10666.,10622.,58358.,-9978.,-497.,16431.,-9978.,-11617.,-25496.,-9978.,11722.,58941.,-9290.,-587.,16979.,-9290.,-12896.,-24981.,-9290.,14386.,76411.,-12130.,-417.,19190.,-12130.,-15221.,-38029.,-12130.,18009.,94168.,-14969.,-248.,21401.,-14969.,-18505.,-51365.,-14969.,19049.,93091.,-15325.,999.,19998.,-15325.,-17050.,-53095.,-15325.,20242.,92527.,-15681.,2246.,18594.,-15681.,-15748.,-55338.,-15681.,14435.,75147.,-13174.,919.,17238.,-13174.,-12597.,-40670.,-13174.,14351.,75579.,-12652.,250.,18214.,-12652.,-13849.,-39150.,-12652.0] - arr0.setValues(vals0,1458,3) - arr0.setInfoOnComponents(['SIXX','SIYY','SIYZ']) - f0z=MEDCouplingFieldDouble(ON_GAUSS_PT) - f0z.setMesh(mz) - f0z.setArray(arr0) - f0z.setGaussLocalizationOnType(NORM_QUAD9,[-1,-1,1,-1,1,1,-1,1,0,-1,1,0,0,1,-1,0,0,0],[-0.774597,-0.774597,0.774597,-0.774597,0.774597,0.774597,-0.774597,0.774597,0,-0.774597,0.774597,0,0,0.774597,-0.774597,0,0,0,-0.774597,-0.774597,0.774597,-0.774597,0.774597,0.774597,-0.774597,0.774597,0,-0.774597,0.774597,0,0,0.774597,-0.774597,0,0,0,-0.774597,-0.774597,0.774597,-0.774597,0.774597,0.774597,-0.774597,0.774597,0,-0.774597,0.774597,0,0,0.774597,-0.774597,0,0,0],[0.308642,0.308642,0.308642,0.308642,0.493827,0.493827,0.493827,0.493827,0.790123,0.308642,0.308642,0.308642,0.308642,0.493827,0.493827,0.493827,0.493827,0.790123,0.308642,0.308642,0.308642,0.308642,0.493827,0.493827,0.493827,0.493827,0.790123]) - f0z.setName("SolutionSIEF_ELGA") - f0z.checkConsistencyLight() - ff0z=MEDFileField1TS() - ff0z.setFieldNoProfileSBT(f0z) - # - arr1=DataArrayDouble([158663.,171562.,32597.,37341.,118998.,128979.,88846.,94935.,28786.,32250.,67038.,71287.,102742.,108939.,32907.,37716.,0.,0.,138922.,155768.,41391.,47731.,114491.,128395.,94101.,100197.,31445.,35939.,67322.,71913.,94031.,103701.,34833.,39475.,0.,0.,142412.,160086.,42700.,49041.,113826.,128551.,92705.,102386.,34032.,38580.,61698.,69417.,96177.,104283.,38223.,40570.,0.,0.,87935.,89674.,30482.,34419.,66325.,69150.,53964.,55380.,28306.,32157.,37909.,40395.,53662.,55355.,22264.,24611.,0.,0.,94013.,100457.,31768.,36134.,68065.,73681.,53358.,55305.,23341.,26188.,32996.,35203.,52496.,56792.,23849.,26556.,0.,0.,92797.,102692.,33656.,38268.,61244.,68735.,52594.,56740.,24539.,27146.,29157.,33011.,52853.,57683.,25671.,28315.,0.,0.,53581.,55745.,27972.,31820.,37174.,39935.,29236.,31416.,22475.,25354.,20531.,23672.,25557.,26298.,15741.,17492.,0.,0.,53385.,55725.,23224.,25998.,32556.,35093.,25809.,26619.,16518.,18338.,18447.,21219.,23343.,26173.,16948.,19353.,0.,0.,52384.,56725.,24293.,26951.,29491.,33373.,23510.,26382.,17117.,19543.,19649.,22252.,26670.,30680.,19554.,22512.,0.,0.,158781.,178651.,54413.,62227.,103151.,116693.,96177.,104283.,38223.,40570.,56254.,64331.,92705.,102386.,34032.,38580.,0.,0.,142873.,161033.,43285.,49854.,113088.,127440.,94031.,103701.,34833.,39475.,61888.,69552.,94101.,100197.,31445.,35939.,0.,0.,132908.,149284.,42933.,49391.,109280.,123481.,102742.,108939.,32907.,37716.,75662.,80547.,88846.,94935.,28786.,32250.,0.,0.,96505.,105010.,37990.,40710.,56669.,64741.,52853.,57683.,25671.,28315.,26824.,30727.,52594.,56740.,24539.,27146.,0.,0.,92360.,101577.,33582.,37900.,61559.,69237.,52496.,56792.,23849.,26556.,29094.,32746.,53358.,55305.,23341.,26188.,0.,0.,95615.,101326.,31440.,36083.,69356.,73116.,53662.,55355.,22264.,24611.,31957.,34376.,53964.,55380.,28306.,32157.,0.,0.,53029.,58077.,25636.,28363.,27182.,31122.,26670.,30680.,19554.,22512.,20758.,22139.,23510.,26382.,17117.,19543.,0.,0.,52348.,56723.,23922.,26648.,29286.,32993.,23343.,26173.,16948.,19353.,19615.,22178.,25809.,26619.,16518.,18338.,0.,0.,53623.,55229.,22321.,24800.,32700.,34971.,25557.,26298.,15741.,17492.,18986.,21836.,29236.,31416.,22475.,25354.,0.,0.,64897.,69997.,64897.,69997.,64897.,69997.,81086.,90448.,81086.,90448.,81086.,90448.,85289.,98323.,85289.,98323.,0.,0.,71712.,82585.,71712.,82585.,71712.,82585.,83868.,96651.,83868.,96651.,83868.,96651.,86266.,99505.,86266.,99505.,0.,0.,77671.,89574.,77671.,89574.,77671.,89574.,86057.,99277.,86057.,99277.,86057.,99277.,86664.,99373.,86664.,99373.,0.,0.,80105.,91799.,80105.,91799.,80105.,91799.,86589.,99313.,86589.,99313.,86589.,99313.,85997.,97609.,85997.,97609.,0.,0.,79826.,90350.,79826.,90350.,79826.,90350.,86438.,98180.,86438.,98180.,86438.,98180.,85995.,95152.,85995.,95152.,0.,0.,75137.,82756.,75137.,82756.,75137.,82756.,88617.,98610.,88617.,98610.,88617.,98610.,79961.,83623.,79961.,83623.,0.,0.,79241.,88756.,79241.,88756.,79241.,88756.,84552.,97374.,84552.,97374.,84552.,97374.,93024.,107413.,93024.,107413.,0.,0.,85301.,98315.,85301.,98315.,85301.,98315.,92453.,106752.,92453.,106752.,92453.,106752.,93783.,108035.,93783.,108035.,0.,0.,86813.,100152.,86813.,100152.,86813.,100152.,93530.,107737.,93530.,107737.,93530.,107737.,92512.,106099.,92512.,106099.,0.,0.,87195.,100044.,87195.,100044.,87195.,100044.,92527.,106109.,92527.,106109.,92527.,106109.,90156.,102760.,90156.,102760.,0.,0.,87342.,99233.,87342.,99233.,87342.,99233.,90384.,103001.,90384.,103001.,90384.,103001.,85458.,96494.,85458.,96494.,0.,0.,90428.,100728.,90428.,100728.,90428.,100728.,85454.,96396.,85454.,96396.,85454.,96396.,70692.,78323.,70692.,78323.,0.,0.,84617.,97440.,84617.,97440.,84617.,97440.,83973.,96607.,83973.,96607.,83973.,96607.,92886.,106795.,92886.,106795.,0.,0.,92294.,106564.,92294.,106564.,92294.,106564.,92515.,106364.,92515.,106364.,92515.,106364.,94158.,108033.,94158.,108033.,0.,0.,93639.,107861.,93639.,107861.,93639.,107861.,93950.,107796.,93950.,107796.,93950.,107796.,91874.,105168.,91874.,105168.,0.,0.,92701.,106313.,92701.,106313.,92701.,106313.,91869.,105167.,91869.,105167.,91869.,105167.,87044.,99369.,87044.,99369.,0.,0.,90450.,103104.,90450.,103104.,90450.,103104.,87236.,99605.,87236.,99605.,87236.,99605.,78375.,89211.,78375.,89211.,0.,0.,84833.,95787.,84833.,95787.,84833.,95787.,78665.,89521.,78665.,89521.,78665.,89521.,63448.,71985.,63448.,71985.,0.,0.,9194.,10306.,41521.,44441.,79431.,85178.,8946.,9792.,22335.,23886.,51736.,54740.,7726.,8300.,30477.,32533.,0.,0.,25028.,27404.,28235.,31471.,75379.,84132.,7236.,8309.,29539.,31536.,54052.,58395.,22577.,23370.,39152.,41429.,0.,0.,37235.,42691.,35353.,38183.,100490.,111738.,23433.,25843.,36759.,39109.,53411.,59694.,57437.,65025.,61345.,68878.,0.,0.,6377.,6683.,22457.,23448.,49503.,50751.,10380.,10835.,19266.,19610.,28417.,28750.,20732.,22044.,26521.,27276.,0.,0.,10131.,11681.,28482.,29670.,52601.,56753.,20722.,21728.,25680.,25959.,30780.,31657.,32161.,33290.,33096.,34633.,0.,0.,21380.,22651.,37121.,39923.,54598.,60751.,34744.,36379.,35111.,37417.,35939.,39080.,46708.,51426.,44384.,48624.,0.,0.,10952.,11418.,19643.,20167.,28488.,29118.,20182.,20242.,18359.,18431.,16718.,16900.,24621.,25169.,20737.,21234.,0.,0.,20251.,21309.,25725.,26026.,31355.,32256.,24539.,25102.,20991.,21593.,17889.,18639.,31588.,32417.,27170.,29235.,0.,0.,33431.,35174.,34427.,36736.,35916.,38926.,31741.,32451.,27148.,29040.,23993.,27214.,38993.,40689.,36596.,40772.,0.,0.,41907.,48128.,77947.,87844.,152033.,169876.,57437.,65025.,61345.,68878.,74154.,85533.,23433.,25843.,36759.,39109.,0.,0.,33932.,38310.,36200.,40713.,99297.,111743.,22577.,23370.,39152.,41429.,57432.,62292.,7236.,8309.,29539.,31536.,0.,0.,22968.,26297.,27645.,30092.,72463.,80413.,7726.,8300.,30477.,32533.,57469.,61055.,8946.,9792.,22335.,23886.,0.,0.,48710.,53918.,59260.,65402.,77350.,87781.,46708.,51426.,44384.,48624.,50354.,58143.,34744.,36379.,35111.,37417.,0.,0.,20908.,22670.,38133.,39669.,56332.,59453.,32161.,33290.,33096.,34633.,34367.,36793.,20722.,21728.,25680.,25959.,0.,0.,7404.,8010.,30073.,32272.,55210.,58955.,20732.,22044.,26521.,27276.,32434.,32943.,10380.,10835.,19266.,19610.,0.,0.,45425.,49667.,44460.,48383.,51014.,58851.,38993.,40689.,36596.,40772.,38865.,44837.,31741.,32451.,27148.,29040.,0.,0.,31595.,32602.,33322.,34837.,35379.,37698.,31588.,32417.,27170.,29235.,24035.,27311.,24539.,25102.,20991.,21593.,0.,0.,19475.,20577.,25384.,25965.,31447.,32050.,24621.,25169.,20737.,21234.,17759.,18414.,20182.,20242.,18359.,18431.,0.,0.],486,2) - arr1.setInfoOnComponents(['VMIS','TRESCA']) - f1z=MEDCouplingFieldDouble(ON_GAUSS_NE) ; f1z.setName("SolutionSIEQ_ELNO") - f1z.setArray(arr1) - f1z.setMesh(mz) - f1z.checkConsistencyLight() - ff1z=MEDFileField1TS() - ff1z.setFieldNoProfileSBT(f1z) - # - arr2=DataArrayDouble([4.938269266683534e-28,-6.232001151245993e-28,1.0602290566170399e-27,4.029857051193646e-29,-1.1103217240985741e-27,-1.5536615528327828e-27,1.5241233363338648e-28,-3.015674201798923e-30,-1.02980203874559e-30,2.72351596604712e-29,-1.1888246600739933e-29,-2.69937196846485e-29,-4.7437993223547586e-07,1.3496193329105202e-07,-7.295395086913946e-07,7.054959528904149e-08,-8.433644218153947e-07,-1.3140517414252605e-08,-4.6699282590396373e-07,-4.307881601165781e-21,-7.181557182928824e-07,-8.028640214851634e-21,-8.231757491716489e-07,-1.2311604671716488e-20,6.500213859021137e-28,-5.36425415550288e-29,2.082592789783471e-28,1.3252863207712998e-28,-4.743799322354692e-07,-1.3496193329105909e-07,-7.295395086913853e-07,-7.054959528905818e-08,-8.433644218153849e-07,1.3140517414226876e-08,6.058451752097371e-28,5.632466863278024e-28,2.208810534618833e-28,2.2876966251409342e-28,-6.120655339318954e-07,1.623023866978208e-20,-7.136250920460284e-07,4.359903572644498e-20,-6.995066975751433e-07,7.373674095935513e-20,0.0,1.4598897976731362e-43,0.0,5.997557427310217e-43,0.0,1.156071233067974e-43,0.0,6.726232628759122e-44,0.0,1.0089348943138683e-43,-4.76082153061813e-07,1.7635130038063272e-07,-7.252650834474581e-07,1.797684522608815e-07,-7.726301925249592e-07,1.3593814652780474e-07,1.28713440720985e-28,8.66262871593868e-30,-1.7918024758329104e-28,1.9633850833341234e-29,-4.7608215306193535e-07,-1.7635130038060178e-07,-7.252650834476241e-07,-1.797684522607695e-07,-7.726301925251186e-07,-1.3593814652760442e-07,-3.0106055763582786e-29,-3.568658720396775e-29,-2.2739766223848432e-29,-1.6603258665331888e-29,-4.741010514018535e-07,5.448590612379579e-08,-4.701818411901992e-07,1.6663000490694165e-08,-7.453102534678627e-07,2.7357217239441644e-08,-7.279540615613018e-07,3.4371113890668217e-09,-8.579330208754989e-07,-2.6008405171390205e-08,-8.357526525453042e-07,-2.5729239758795502e-08,-4.701818411901952e-07,-1.6663000490702818e-08,-4.741010514018457e-07,-5.448590612380402e-08,-7.279540615612966e-07,-3.4371113890835274e-09,-7.45310253467852e-07,-2.7357217239458564e-08,-8.357526525452993e-07,2.572923975877074e-08,-8.579330208754882e-07,2.6008405171364682e-08,0.0,-3.689838846534034e-21,0.0,-3.4057248282497575e-21,0.0,-2.389474304570763e-21,0.0,1.1849907150798524e-21,0.0,7.728930340233592e-21,0.0,-9.409753747161713e-21,0.0,-9.27355993916331e-21,0.0,-5.9005465375222355e-21,0.0,3.45820724462685e-21,0.0,2.0021147143626658e-20,0.0,-1.6042705688202718e-20,0.0,-1.541762360721681e-20,0.0,-8.827856096357078e-21,0.0,6.3984676397065826e-21,0.0,3.396409774956617e-20,-5.21059344905059e-07,1.0785416831218214e-07,-5.942832234061152e-07,1.1284412735292002e-07,-7.291198556954883e-07,1.5975182005082218e-07,-7.29419534669376e-07,1.4146009988497262e-07,-7.536819640264805e-07,1.388363757438669e-07,-7.212688685979149e-07,1.1197909398607218e-07,-5.94283223406162e-07,-1.1284412735287996e-07,-5.210593449051535e-07,-1.0785416831213956e-07,-7.294195346694393e-07,-1.4146009988486582e-07,-7.291198556956173e-07,-1.5975182005070884e-07,-7.212688685979762e-07,-1.1197909398589052e-07,-7.536819640266044e-07,-1.3883637574367513e-07,-2.8576578578864835e-07,1.301140611795876e-07,-6.228581335977658e-07,1.1144407150470386e-07,-8.014360278229913e-07,2.882237382538957e-08,-2.6588034168431343e-07,-2.345549761149889e-21,-6.148909793824232e-07,-5.981322827533954e-21,-7.85277352863385e-07,-1.0225807644204478e-20,3.1049565229499025e-27,-4.196740015775783e-28,-2.887230913108903e-28,-4.403551231441193e-28,4.812051521848172e-29,3.851635443793833e-28,-2.857657857886445e-07,-1.301140611795897e-07,-6.228581335977572e-07,-1.1144407150471579e-07,-8.01436027822981e-07,-2.8822373825410947e-08,-1.5635223141480454e-27,-9.802651538976083e-29,3.278505922098525e-27,-6.797558254135845e-28,4.1020767071492614e-27,5.932234007262009e-28,-4.410314084022777e-07,7.268022452197178e-21,-6.915240267186082e-07,2.9979998916103056e-20,-7.135613152026231e-07,5.968769864060137e-20,0.0,1.793662034335766e-43,0.0,1.793662034335766e-43,0.0,8.96831017167883e-43,0.0,-5.6519283938616335e-43,0.0,1.0761972206014595e-42,0.0,9.269247757898544e-43,-2.627131752301911e-07,1.3274214899302934e-07,-6.329945799890571e-07,1.9265484727832687e-07,-7.677771910976133e-07,1.6184720841148966e-07,1.5146129380243427e-28,-5.494056542378401e-29,1.0988346067719275e-50,3.891714187734575e-29,2.524354896707238e-28,1.6407579324035087e-28,-2.62713175230267e-07,-1.3274214899303003e-07,-6.329945799892127e-07,-1.9265484727825895e-07,-7.677771910977852e-07,-1.6184720841133102e-07,-1.5146129380243427e-28,6.686637000472881e-29,-1.5146129380243427e-28,5.412840523535707e-29,5.048709949123486e-29,-1.0255191767873153e-29,-4.801584184334589e-07,9.447106112382042e-08,-2.646155245804423e-07,4.165624981437424e-08,-4.7283844479037397e-07,3.112099903692373e-08,-2.656912190102633e-07,1.2633757629192664e-08,-4.6803908104000066e-07,8.091752496288301e-09,-7.484767456103177e-07,4.8063930505815753e-08,-6.342336387597463e-07,4.783223809223803e-08,-7.371756425756432e-07,1.2491484933343017e-08,-6.217198644652372e-07,1.3160740615455145e-08,-7.210619794360716e-07,-6.140998451021678e-11,-8.616398069136549e-07,-2.0279767975595878e-08,-8.174867338143947e-07,1.761743718501197e-09,-8.474965025861739e-07,-2.8360688201075687e-08,-7.969390370704656e-07,-1.0156396041453297e-08,-8.26809188564297e-07,-1.6608029814857525e-08,-4.6803908103999843e-07,-8.091752496296909e-09,-2.6569121901026077e-07,-1.2633757629197396e-08,-4.72838444790368e-07,-3.112099903693232e-08,-2.6461552458043755e-07,-4.165624981437841e-08,-4.801584184334501e-07,-9.447106112382803e-08,-7.210619794360687e-07,6.140998449395655e-11,-6.217198644652322e-07,-1.3160740615467643e-08,-7.37175642575635e-07,-1.2491484933360037e-08,-6.342336387597367e-07,-4.783223809225061e-08,-7.484767456103061e-07,-4.8063930505832595e-08,-8.268091885642944e-07,1.6608029814832955e-08,-7.969390370704601e-07,1.015639604143253e-08,-8.474965025861654e-07,2.836068820105083e-08,-8.174867338143834e-07,-1.7617437185225845e-09,-8.616398069136434e-07,2.02797679755703e-08,0.0,-3.435877556189529e-21,0.0,-1.3776771401529971e-21,0.0,-3.403994495899553e-21,0.0,-1.3185754926235634e-21,0.0,-2.7680254878980847e-21,0.0,-1.1103673324958778e-21,0.0,-9.900107724251277e-22,0.0,4.77602156134974e-22,0.0,3.959146546409973e-21,0.0,3.776411006916986e-21,0.0,1.2124392797414627e-20,0.0,-8.731709783191639e-21,0.0,-6.144329300702704e-21,0.0,-8.89968038381516e-21,0.0,-5.404653063609732e-21,0.0,-7.547524363424233e-21,0.0,-3.3206893791145496e-21,0.0,-1.6246546029348425e-21,0.0,1.9854969588545943e-21,0.0,1.1317236337409485e-20,0.0,1.3983874347413824e-20,0.0,3.098996503833694e-20,0.0,-1.407865292807831e-20,0.0,-1.1626000835692668e-20,0.0,-1.533412146384094e-20,0.0,-1.1018823571603408e-20,0.0,-1.2512374860235445e-20,0.0,-6.514267779823197e-21,0.0,-2.4719015385819347e-21,0.0,4.858859984935085e-21,0.0,1.881348220188166e-20,0.0,2.740874292245713e-20,0.0,5.211376231395407e-20,-4.864225626157067e-07,1.3296728230814142e-07,-3.076586015279749e-07,6.740802636874205e-08,-5.594534933091086e-07,1.1066583698276748e-07,-3.841186138586638e-07,7.559745482599735e-08,-6.098267681100678e-07,9.875238991849593e-08,-7.2970765755297e-07,1.669225383108583e-07,-6.573316628421653e-07,1.465581454371536e-07,-7.316181481946474e-07,1.5542337568784254e-07,-6.912676702186072e-07,1.3829023572925456e-07,-7.20589385417476e-07,9.666451163676767e-08,-7.723884127434406e-07,1.3857930563622999e-07,-7.569169347428396e-07,1.547516335925935e-07,-7.383025429990218e-07,1.3271074092312e-07,-7.350854918831709e-07,1.2994146610617741e-07,-7.0646090437235e-07,6.938656131041383e-08,-6.098267681100908e-07,-9.875238991845998e-08,-3.841186138586908e-07,-7.559745482597872e-08,-5.594534933091803e-07,-1.1066583698272561e-07,-3.0765860152803245e-07,-6.740802636872275e-08,-4.864225626158294e-07,-1.329672823081032e-07,-7.20589385417508e-07,-9.666451163666813e-08,-6.912676702186662e-07,-1.3829023572918171e-07,-7.316181481947439e-07,-1.5542337568773118e-07,-6.573316628422832e-07,-1.4655814543707692e-07,-7.297076575531353e-07,-1.6692253831074535e-07,-7.064609043723808e-07,-6.938656131024667e-08,-7.350854918832338e-07,-1.2994146610603196e-07,-7.383025429991161e-07,-1.3271074092293177e-07,-7.56916934742969e-07,-1.5475163359243975e-07,-7.723884127435972e-07,-1.3857930563603445e-07,-2.6225523866596743e-07,7.368618860781533e-08,-2.6483901297419715e-07,2.3043552983380804e-08,-2.6569368384400127e-07,6.351605004005378e-09,-6.372294401265312e-07,7.723333950374213e-08,-6.279151194946851e-07,2.6473214771574048e-08,-6.169026138715963e-07,5.559932643680484e-09,-8.206671947434617e-07,1.419786412636469e-08,-8.077626999789484e-07,-6.830966026358984e-09,-7.886512424652054e-07,-7.805683188152915e-09,-2.6569368384400005e-07,-6.351605004010108e-09,-2.648390129741935e-07,-2.3043552983385364e-08,-2.622552386659623e-07,-7.36861886078186e-08,-6.169026138715935e-07,-5.559932643692688e-09,-6.279151194946777e-07,-2.647321477158676e-08,-6.372294401265209e-07,-7.723333950375434e-08,-7.886512424652024e-07,7.805683188132495e-09,-8.077626999789395e-07,6.830966026337777e-09,-8.2066719474345e-07,-1.4197864126386033e-08,0.0,-1.528080794868089e-21,0.0,-1.5426894495622164e-21,0.0,-1.1495211961775125e-21,0.0,-4.441807280413718e-22,0.0,1.9784166326767865e-21,0.0,5.420802477152069e-21,0.0,-6.12858914756041e-21,0.0,-6.197208509921192e-21,0.0,-4.895012827081806e-21,0.0,-1.2104071985400557e-21,0.0,7.207223659623184e-21,0.0,2.1139789648778443e-20,0.0,-1.178112680978544e-20,0.0,-1.2361618534325795e-20,0.0,-9.332953007651742e-21,0.0,-2.4549106998298197e-21,0.0,1.5192320364423287e-20,0.0,4.128606459003346e-20,-2.6179012371741095e-07,8.492155525093568e-08,-3.431936650750607e-07,6.526689580555302e-08,-4.206987870183037e-07,7.275786337707596e-08,-6.39565352471141e-07,1.6214246375922057e-07,-6.76924119958337e-07,1.4588367240696607e-07,-6.94035042843604e-07,1.042901908413762e-07,-7.689004953903582e-07,1.574343097081281e-07,-7.476782438785353e-07,1.489103868358007e-07,-7.209785981316606e-07,8.394206942691553e-08,-4.2069878701831687e-07,-7.275786337705938e-08,-3.431936650751034e-07,-6.52668958055331e-08,-2.617901237174839e-07,-8.492155525092188e-08,-6.940350428436335e-07,-1.0429019084130907e-07,-6.769241199584262e-07,-1.458836724068901e-07,-6.39565352471292e-07,-1.6214246375914686e-07,-7.209785981316918e-07,-8.394206942678136e-08,-7.476782438786325e-07,-1.4891038683565012e-07,-7.68900495390525e-07,-1.574343097079712e-07],259,2) - arr2.setInfoOnComponents(['DRX','DRZ']) - f2z=MEDCouplingFieldDouble(ON_NODES) ; f2z.setName("SolutionDEPL") ; f2z.setArray(arr2) - f2z.setMesh(mz) - f2z.checkConsistencyLight() - ff2z=MEDFileField1TS() - ff2z.setFieldNoProfileSBT(f2z) - # - mm2=MEDFileUMesh() - mm2.setMeshAtLevel(0,mz) - mm2.setFamilyFieldArr(0,DataArrayInt([-1,-1,-1,-1,-1,-1,-1,-1,-1,-2,-2,-2,-2,-2,-2,-2,-2,-2,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-4,-4,-4,-4,-4,-4,-4,-4,-4,-5,-5,-5,-5,-5,-5,-5,-5,-5])) - mm2.setFamilyFieldArr(1,DataArrayInt([1,2,3,4,5,6,0,0,0,0,0,0,1,1,0,0,0,3,3,0,0,0,7,7,7,7,7,0,0,0,5,5,0,0,0,6,6,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,3,3,3,0,0,0,7,7,7,7,7,7,0,0,0,5,5,5,0,0,0,6,6,6,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0])) - for famName,famId in [('FAMILLE_ZERO',0),('ba1_beam',-1),('ba2_beam',-2),('h1',6),('h1_h2_h3',4),('h2',5),('h3',7),('h3_h4_h5',2),('h4',3),('h5',1),('to1_beam',-4),('to2_beam',-5),('web_beam',-3)]: - mm2.setFamilyId(famName,famId) - pass - for grName,famsOnGrp in [('ba1',['ba1_beam']),('ba2',['ba2_beam']),('beam',['ba1_beam','ba2_beam','to1_beam','to2_beam','web_beam']),('h1',['h1','h1_h2_h3']),('h2',['h1_h2_h3','h2']),('h3',['h1_h2_h3','h3','h3_h4_h5']),('h4',['h3_h4_h5','h4']),('h5',['h3_h4_h5','h5']),('to1',['to1_beam']),('to2',['to2_beam']),('web',['web_beam'])]: - mm2.setFamiliesOnGroup(grName,famsOnGrp) - pass - # - mm2.write(fname,2) - ff0z.write(fname,0) - ff1z.write(fname,0) - ff2z.write(fname,0) - return fname - -@WriteInTmpDir -def test0(baseline_file): - fname = GenerateCase() - ################### MED write is done -> Go to MEDReader - - myMedReader=MEDReader(FileName=fname) - keys=myMedReader.GetProperty("FieldsTreeInfo")[::2] - # list all the names of arrays that can be seen (including their spatial discretization) - arr_name_with_dis=[elt.split("/")[-1] for elt in keys] - # list all the names of arrays (Equal to those in the MED File) - arr_name=[elt.split(myMedReader.GetProperty("Separator").GetData())[0] for elt in arr_name_with_dis] - myMedReader.AllArrays=keys - - if '-D' not in sys.argv: - RenderView1 = GetRenderView() - ELNOfieldToSurface1=ELNOfieldToSurface(Input=myMedReader) - ExtractGroup1=ExtractGroup(Input=ELNOfieldToSurface1) - #ExtractGroup1.UpdatePipelineInformation() - ExtractGroup1.AllGroups=['GRP_ba2','GRP_to1','GRP_web'] - assert(isinstance(ExtractGroup1.GetProperty("MeshName")[0],str)) - assert(ExtractGroup1.GetProperty("MeshName")[0]=="mesh") - # - DataRepresentation3 = Show() - DataRepresentation3.ScaleFactor = 0.008999999705702066 - DataRepresentation3.EdgeColor = [0.0, 0.0, 0.5000076295109483] - DataRepresentation3.SelectionPointFieldDataArrayName = 'SolutionSIEF_ELNO' - a2_SolutionSIEQ_ELNO_PiecewiseFunction = CreatePiecewiseFunction(Points=[0.0, 0.0, 0.5, 0.0, 1.0, 1.0, 0.5, 0.0]) - #VectorMode='Magnitude' or VectorMode='Component' - a2_SolutionSIEQ_ELNO_PVLookupTable = GetLookupTableForArray("SolutionSIEQ_ELNO",2,RGBPoints=[0.0, 0.23, 0.299, 0.754, 239013.7773476667, 0.706, 0.016, 0.15], VectorMode='Component', VectorComponent=1, NanColor=[0.25, 0.0, 0.0], ColorSpace='Diverging', ScalarRangeInitialized=1.0, AllowDuplicateScalars=1 ) - DataRepresentation3.ScalarOpacityFunction = a2_SolutionSIEQ_ELNO_PiecewiseFunction - DataRepresentation3.ColorArrayName = 'SolutionSIEQ_ELNO' - DataRepresentation3.LookupTable = a2_SolutionSIEQ_ELNO_PVLookupTable - DataRepresentation3.Visibility = 1 - # - ELGAfieldToPointGaussian1=ELGAfieldToPointGaussian(Input=ELNOfieldToSurface1) - ELGAfieldToPointGaussian1.SelectSourceArray=['CELLS','ELGA@0'] - DataRepresentation4 = Show() - DataRepresentation4.ScaleFactor = 0.008999999705702066 - DataRepresentation4.EdgeColor = [0.0, 0.0, 0.5000076295109483] - DataRepresentation4.SelectionPointFieldDataArrayName = 'SolutionSIEF_ELGA' - DataRepresentation4.ColorArrayName = 'SolutionSIEF_ELGA' - ######## - RenderView1.CameraViewUp = [-0.19545466285945437, 0.837274140321886, -0.5106559396646081] - RenderView1.CameraPosition = [0.11797550069274401, 0.20119836056342144, 0.20885419432082736] - RenderView1.CameraFocalPoint = [1.0170565790969026e-18, 0.0599999981932342, 0.022500000894069675] - RenderView1.ViewSize =[300,300] - Render() - - # compare with baseline image - import vtk.test.Testing - from vtk.util.misc import vtkGetTempDir - vtk.test.Testing.VTK_TEMP_DIR = vtk.util.misc.vtkGetTempDir() - vtk.test.Testing.compareImage(GetActiveView().GetRenderWindow(), baseline_file, - threshold=1) - vtk.test.Testing.interact() - -if __name__ == "__main__": - outImgName="testMEDReader0.png" - baseline_file = RetriveBaseLine(outImgName) - test0(baseline_file) - pass diff --git a/src/Plugins/MEDReader/Test/testMEDReader1.py b/src/Plugins/MEDReader/Test/testMEDReader1.py deleted file mode 100644 index 6c730c2c..00000000 --- a/src/Plugins/MEDReader/Test/testMEDReader1.py +++ /dev/null @@ -1,65 +0,0 @@ -# -*- coding: iso-8859-1 -*- -# Copyright (C) 2007-2019 CEA/DEN, EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# -# Author : Anthony Geay - -from medcoupling import * -from MEDReaderHelper import WriteInTmpDir,RetriveBaseLine - -@WriteInTmpDir -def GenerateCase(): - """ - This test focused on ELNO. Here a 2 QUAD4 cells and a single ELNO field - is defined. - """ - fname="testMEDReader1.med" - coords=DataArrayDouble([(0,0,0),(2,1,0),(1,0,0),(1,1,0),(2,0,0),(0,1,0)]) - m=MEDCouplingUMesh("mesh",2) ; m.setCoords(coords) - m.allocateCells() - m.insertNextCell(NORM_QUAD4,[0,5,3,2]) - m.insertNextCell(NORM_QUAD4,[4,2,3,1]) - m.finishInsertingCells() - WriteMesh(fname,m,True) - # - f0=MEDCouplingFieldDouble(ON_GAUSS_NE) ; f0.setMesh(m) ; f0.setTimeUnit("ms") - f0.setTime(1.1,1,1) - f0.setName("myELNOField") - arr=DataArrayDouble([7,5,3,1,5,3,1,7]) ; arr.setInfoOnComponent(0,"Comp0") - f0.setArray(arr) - WriteFieldUsingAlreadyWrittenMesh(fname,f0) - # - f0.setTime(2.2,2,1) - arr=DataArrayDouble([1,7,5,3,7,5,3,1]) ; arr.setInfoOnComponent(0,"Comp0") - f0.setArray(arr) - WriteFieldUsingAlreadyWrittenMesh(fname,f0) - # - f0.setTime(3.3,3,1) - arr=DataArrayDouble([3,1,7,5,1,7,5,3]) ; arr.setInfoOnComponent(0,"Comp0") - f0.setArray(arr) - WriteFieldUsingAlreadyWrittenMesh(fname,f0) - # - f0.setTime(4.4,4,1) - arr=DataArrayDouble([5,3,1,7,3,1,7,5]) ; arr.setInfoOnComponent(0,"Comp0") - f0.setArray(arr) - WriteFieldUsingAlreadyWrittenMesh(fname,f0) - - -if __name__ == "__main__": - GenerateCase() - pass diff --git a/src/Plugins/MEDReader/Test/testMEDReader10.py b/src/Plugins/MEDReader/Test/testMEDReader10.py deleted file mode 100644 index 6cd5dc55..00000000 --- a/src/Plugins/MEDReader/Test/testMEDReader10.py +++ /dev/null @@ -1,131 +0,0 @@ -# -*- coding: iso-8859-1 -*- -# Copyright (C) 2007-2019 CEA/DEN, EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# -# Author : Anthony Geay - -import os -import sys - -from medcoupling import * -from paraview.simple import * -from MEDReaderHelper import WriteInTmpDir,RetriveBaseLine - -def GenerateCase(): - """ This test focuses on GenerateVector part. - """ - fname="testMEDReader10.med" - ############## - coo=DataArrayDouble([(0.,0.,0.),(1.,0.,0.),(2.,0.,0.),(3.,0.,0.),(0.,1.,0.),(1.,1.,0.),(2.,1.,0.),(3.,1.,0.),(0.,0.,1.),(1.,0.,1.),(2.,0.,1.),(3.,0.,1.),(0.,1.,1.),(1.,1.,1.),(2.,1.,1.),(3.,1.,1.)]) - m=MEDCouplingUMesh("myMesh",3) ; m.setCoords(coo) - m.allocateCells() - m.insertNextCell(NORM_HEXA8,[0,4,5,1,8,12,13,9]) ; m.insertNextCell(NORM_HEXA8,[1,5,6,2,9,13,14,10]) ; m.insertNextCell(NORM_HEXA8,[2,6,7,3,10,14,15,11]) - f0=MEDCouplingFieldDouble(ON_NODES) ; f0.setName("f0NbComp1") ; f0.setMesh(m) ; - arr=DataArrayDouble(8) ; arr.iota() ; arr=DataArrayDouble.Aggregate(arr,arr+8) ; arr.setInfoOnComponents(["1st"]) - f0.setArray(arr) - f1=MEDCouplingFieldDouble(ON_NODES) ; f1.setName("f1NbComp2") ; f1.setMesh(m) ; - arr=DataArrayDouble([(-1.,-1.),(0.,0.5),(0.,0.5),(1.,-1.),(-1.,1.),(0.,-0.5),(0.,-0.5),(1.,1.)]) ; arr=DataArrayDouble.Aggregate(arr,arr) ; arr.setInfoOnComponents(["1st","2nd"]) - f1.setArray(arr) - f2=MEDCouplingFieldDouble(ON_NODES) ; f2.setName("f2NbComp3") ; f2.setMesh(m) ; - arr=DataArrayDouble([(-1.,-1.,-1.),(0.,0.5,0.),(0.,0.5,0.),(1.,-1.,-1.),(-1.,1.,-1.),(0.,-0.5,0.),(0.,-0.5,0.),(1.,1.,-1)]) ; arr2=arr[:] ; arr2[[0,3,4,7],2]=1. - arr=DataArrayDouble.Aggregate(arr,arr2) ; arr.setInfoOnComponents(["1st","2nd","3rd"]) - f2.setArray(arr) - f3=MEDCouplingFieldDouble(ON_NODES) ; f3.setName("f3NbComp4") ; f3.setMesh(m) ; - arr=DataArrayDouble([(-1.,-1.,-1.),(0.,0.5,0.),(0.,0.5,0.),(1.,-1.,-1.),(-1.,1.,-1.),(0.,-0.5,0.),(0.,-0.5,0.),(1.,1.,-1)]) ; arr2=arr[:] ; arr2[[0,3,4,7],2]=1. - arr=DataArrayDouble.Aggregate(arr,arr2) ; arr3=DataArrayDouble(16) ; arr3.iota() ; arr=DataArrayDouble.Meld([arr,arr3]) - arr.setInfoOnComponents(["1st","2nd","3rd","4th"]) - f3.setArray(arr) - # - WriteMesh(fname,m,True) - WriteFieldUsingAlreadyWrittenMesh(fname,f0) - WriteFieldUsingAlreadyWrittenMesh(fname,f1) - WriteFieldUsingAlreadyWrittenMesh(fname,f2) - WriteFieldUsingAlreadyWrittenMesh(fname,f3) - return fname - - -@WriteInTmpDir -def test(baseline_file): - fname = GenerateCase() - ################### MED write is done -> Go to MEDReader - myMedReader=MEDReader(FileName=fname) - keys=myMedReader.GetProperty("FieldsTreeInfo")[::2] - # list all the names of arrays that can be seen (including their spatial discretization) - arr_name_with_dis=[elt.split("/")[-1] for elt in keys] - # list all the names of arrays (Equal to those in the MED File) - arr_name=[elt.split(myMedReader.GetProperty("Separator").GetData())[0] for elt in arr_name_with_dis] - myMedReader.AllArrays=keys - myMedReader.GenerateVectors=1 - - if '-D' not in sys.argv: - RenderView1=GetRenderView() - DataRepresentation1 = Show() - DataRepresentation1.EdgeColor = [0.0, 0.0, 0.5] - DataRepresentation1.SelectionPointFieldDataArrayName='f0NbComp1' - DataRepresentation1.ScalarOpacityUnitDistance = 2.299619191183727 - #DataRepresentation1.ExtractedBlockIndex = 1 - DataRepresentation1.ScaleFactor = 0.3 - RenderView1.CenterOfRotation = [1.5, 0.5, 0.5] - RenderView1.CameraPosition = [1.5, 0.5, 6.907227082229696] - RenderView1.CameraFocalPoint = [1.5, 0.5, 0.5] - RenderView1.CameraParallelScale = 1.6583123951777 - DataRepresentation1.Representation = 'Wireframe' - # - wbv=WarpByVector(Input=myMedReader) - wbv.ScaleFactor=0.1 - wbv.Vectors=['POINTS','f3NbComp4_Vector'] - assert(list(wbv.PointData.keys())==['f0NbComp1','f1NbComp2','f1NbComp2_Vector','f2NbComp3','f3NbComp4','f3NbComp4_Vector']) - # - DataRepresentation2 = Show() - DataRepresentation2.EdgeColor = [0.0, 0.0, 0.5000076295109483] - DataRepresentation2.SelectionPointFieldDataArrayName = 'f0NbComp1' - DataRepresentation2.SelectionCellFieldDataArrayName = 'FamilyIdCell' - DataRepresentation2.ScalarOpacityUnitDistance = 4.546673931685981 - #DataRepresentation2.ExtractedBlockIndex = 1 - DataRepresentation2.ScaleFactor = 0.5 - DataRepresentation1.Visibility = 0 - DataRepresentation1.ColorArrayName = ('POINT_DATA', '') - DataRepresentation1.Visibility = 1 - a4_f3NbComp4_PVLookupTable = GetLookupTableForArray( "f3NbComp4", 4, RGBPoints=[1.118033988749895, 0.23, 0.299, 0.754, 8.108851429645696, 0.865, 0.865, 0.865, 15.0996688705415, 0.706, 0.016, 0.15], VectorMode='Magnitude', NanColor=[0.25, 0.0, 0.0], ColorSpace='Diverging', ScalarRangeInitialized=1.0 ) - a4_f3NbComp4_PiecewiseFunction = CreatePiecewiseFunction( Points=[1.118033988749895, 0.0, 0.5, 0.0, 15.0996688705415, 1.0, 0.5, 0.0] ) - DataRepresentation1.ScalarOpacityFunction = a4_f3NbComp4_PiecewiseFunction - DataRepresentation1.LookupTable = a4_f3NbComp4_PVLookupTable - a4_f3NbComp4_PVLookupTable.ScalarOpacityFunction = a4_f3NbComp4_PiecewiseFunction - DataRepresentation2.ScalarOpacityFunction = a4_f3NbComp4_PiecewiseFunction - DataRepresentation2.ColorArrayName = ('POINT_DATA', 'f3NbComp4') - DataRepresentation2.LookupTable = a4_f3NbComp4_PVLookupTable - RenderView1.CameraViewUp = [0.32310237626907823, -0.28721735329781684, -0.901726702728644] - RenderView1.CameraPosition = [0.17151044563787257, 6.31903262423349, -1.8294921560963984] - RenderView1.CameraFocalPoint = [1.4999999999999996, 0.49999999999999944, 0.4999999999999996] - # - RenderView1.ViewSize =[300,300] - Render() - - # compare with baseline image - import vtk.test.Testing - from vtk.util.misc import vtkGetTempDir - vtk.test.Testing.VTK_TEMP_DIR = vtk.util.misc.vtkGetTempDir() - vtk.test.Testing.compareImage(GetActiveView().GetRenderWindow(), baseline_file, - threshold=1) - vtk.test.Testing.interact() - -if __name__ == "__main__": - outImgName="testMEDReader10.png" - baseline_file = RetriveBaseLine(outImgName) - test(baseline_file) - pass diff --git a/src/Plugins/MEDReader/Test/testMEDReader13.py b/src/Plugins/MEDReader/Test/testMEDReader13.py deleted file mode 100644 index 84925fd5..00000000 --- a/src/Plugins/MEDReader/Test/testMEDReader13.py +++ /dev/null @@ -1,98 +0,0 @@ -# -*- coding: iso-8859-1 -*- -# Copyright (C) 2007-2019 CEA/DEN, EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# -# Author : Anthony Geay - -import os -import sys - -from medcoupling import * -from paraview.simple import * -from MEDReaderHelper import WriteInTmpDir,RetriveBaseLine - -def GenerateCase(): - """ This test is non regression test to check non regression of EDF 8761. ELNO Mesh filter on vector field with 4 comps cut of using GenerateVectors""" - - fname="testMEDReader13.med" - # - - m=MEDCouplingUMesh("mesh",2) - m.setCoords(DataArrayDouble([0.,0.,0.,1.,0.,0.,2.,0.,0.,1.,1.,0.],4,3)) - m.allocateCells() - m.insertNextCell(NORM_TRI3,[0,1,3]) ; m.insertNextCell(NORM_TRI3,[1,2,3]) - f=MEDCouplingFieldDouble(ON_GAUSS_NE) ; f.setName("fieldELNO") ; f.setMesh(m) - arr=DataArrayDouble([0.2,1.1,0.7,0.5,-0.3,0.4]) - f.setArray(DataArrayDouble.Meld(4*[arr])) - f.checkConsistencyLight() - WriteField(fname,f,True) - return fname - -@WriteInTmpDir -def test(baseline_file): - fname = GenerateCase() - ################### MED write is done -> Go to MEDReader - testMEDReader13_med = MEDReader( FileName=fname ) - - testMEDReader13_med.GenerateVectors = 1 - testMEDReader13_med.AllArrays = ['TS0/mesh/ComSup0/fieldELNO@@][@@GSSNE'] - - if '-D' not in sys.argv: - RenderView1 = GetRenderView() - RenderView1.CameraPosition = [1.0, 0.5, 10000.0] - - RenderView1.CameraPosition = [1.0, 0.5, 4.319751617610021] - - ELNOfieldToSurface3 = ELNOfieldToSurface(Input=testMEDReader13_med) - - DataRepresentation2 = Show() - #DataRepresentation2.ConstantRadius = 1.9999333620071411 - DataRepresentation2.EdgeColor = [0.0, 0.0, 0.5000076295109483] - #DataRepresentation2.PointGaussianDefaultsInitialized = 1 - DataRepresentation2.SelectionPointFieldDataArrayName = 'fieldELNO' - DataRepresentation2.SelectionCellFieldDataArrayName = 'FamilyIdCell' - #DataRepresentation2.SelectInputVectors = ['POINTS', 'fieldELNO_Vector'] - DataRepresentation2.ScalarOpacityUnitDistance = 1.7746382108908556 - DataRepresentation2.Texture = [] - DataRepresentation2.ExtractedBlockIndex = 1 - #DataRepresentation2.RadiusRange = [6.666666740784422e-05, 1.9999333620071411] - DataRepresentation2.ScaleFactor = 0.19998666953397334 - - #DataRepresentation2.RadiusRange = [6.66667e-05, 1.99993] - DataRepresentation2.ColorArrayName = ('POINT_DATA', 'fieldELNO_Vector') - - a3_fieldELNO_Vector_PVLookupTable = GetLookupTableForArray( "fieldELNO_Vector", 3, RGBPoints=[0.3464101615137755, 0.23, 0.299, 0.754, 1.1258330249197703, 0.865, 0.865, 0.865, 1.9052558883257653, 0.706, 0.016, 0.15], VectorMode='Magnitude', NanColor=[0.25, 0.0, 0.0], ColorSpace='Diverging', ScalarRangeInitialized=1.0 ) - - a3_fieldELNO_Vector_PiecewiseFunction = CreatePiecewiseFunction( Points=[0.3464101615137755, 0.0, 0.5, 0.0, 1.9052558883257653, 1.0, 0.5, 0.0] ) - - RenderView1.ViewSize =[300,300] - Render() - - # compare with baseline image - import vtk.test.Testing - from vtk.util.misc import vtkGetTempDir - vtk.test.Testing.VTK_TEMP_DIR = vtk.util.misc.vtkGetTempDir() - vtk.test.Testing.compareImage(GetActiveView().GetRenderWindow(), baseline_file, - threshold=1) - vtk.test.Testing.interact() - -if __name__ == "__main__": - outImgName="testMEDReader13.png" - baseline_file = RetriveBaseLine(outImgName) - test(baseline_file) - pass diff --git a/src/Plugins/MEDReader/Test/testMEDReader14.py b/src/Plugins/MEDReader/Test/testMEDReader14.py deleted file mode 100644 index e8eca2c1..00000000 --- a/src/Plugins/MEDReader/Test/testMEDReader14.py +++ /dev/null @@ -1,181 +0,0 @@ -# -*- coding: iso-8859-1 -*- -# Copyright (C) 2007-2019 CEA/DEN, EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# -# Author : Anthony Geay (EDF R&D) - -import os -import sys - -from medcoupling import * -from paraview.simple import * -from MEDReaderHelper import WriteInTmpDir,RetriveBaseLine -paraview.simple._DisableFirstRenderCameraReset() - -def GenerateCase(): - """ This test reproduces precisely the bug EDF8655 (PAL 22677) by cheking that multi loc per geo type in a field is correctly managed. - """ - - fname="testMEDReader14.med" - - arr0=DataArrayDouble(7) ; arr0.iota() - arr1=DataArrayDouble(5) ; arr1.iota() - c=MEDCouplingCMesh() - c.setCoords(arr0,arr1) - m=c.build1SGTUnstructured() - pfl=DataArrayInt([5,10,11,16,17,23]) - m0=m[pfl.buildComplement(24)] - m1=m[pfl] ; m1.simplexize(0) - m=MEDCouplingUMesh.MergeUMeshesOnSameCoords(m1.buildUnstructured(),m0.buildUnstructured()) - m.setName("Mesh") - m1=MEDCoupling1SGTUMesh(m.getName(),NORM_SEG2) - m1.setCoords(m.getCoords()) - m1.allocateCells() - for i in [[28,21],[21,14],[14,7],[7,0]]: - m1.insertNextCell(i) - pass - for i in range(6): - m1.insertNextCell([i,i+1]) - pass - for i in [[6,13],[13,20],[20,27],[27,34]]: - m1.insertNextCell(i) - pass - for i in range(6,0,-1): - m1.insertNextCell([28+i,28+i-1]) - pass - # - mm=MEDFileUMesh() - mm.setMeshAtLevel(0,m) - mm.setMeshAtLevel(-1,m1) - mm.write(fname,2) - # - pfl0=DataArrayInt([0,1,2,3]) ; pfl0.setName("PFL000") - pfl1=DataArrayInt([4,5,6,7,8,9]) ; pfl1.setName("PFL001") - pfl2=DataArrayInt([10,11,12,13]) ; pfl2.setName("PFL002") - pfl3=DataArrayInt([13,14,15,16,19,20,23,24,26,27,28,29]) ; pfl3.setName("PFL003") - # - fieldName0="zeField0" - fieldName1="zeField1" - fieldName2="zeField2" - fs0=MEDFileFieldMultiTS() - fs1=MEDFileFieldMultiTS() - fs2=MEDFileFieldMultiTS() - for i in range(5): - f=MEDFileField1TS() - zePfl0=DataArrayInt.Aggregate(DataArrayInt.Range(0,12,1),pfl3,0) ; zePfl0.setName("PFL") - fNode=MEDCouplingFieldDouble(ON_GAUSS_PT) ; fNode.setTime(float(i),i,0) - tmp=m[zePfl0] - fNode.setName(fieldName0) ; fNode.setMesh(tmp) - fNode.setGaussLocalizationOnCells(DataArrayInt.Range(0,12,1),[0.,0.,1.,0.,0.,1.],[0.1,0.1,0.8,0.1,0.1,0.8],3*[0.16666666666666666]) - fNode.setGaussLocalizationOnCells(DataArrayInt.Range(12,24,1),[-1.,-1.,1.,-1.,1.,1.,-1.,1.],[-0.577350,-0.577350,0.577350,-0.577350,0.577350,0.577350,-0.577350,0.577350],4*[1.]) - arr=DataArrayDouble(2*(12*3+12*4)) ; arr.iota(0+1000*i) ; arr.rearrange(2) - fNode.setArray(arr) ; arr.setInfoOnComponents(["Comp1_2 [m]","Com2_2 [s^2]"]) ; fNode.checkConsistencyLight() - fNode.setName(fieldName0) - f.setFieldProfile(fNode,mm,0,zePfl0) - # - zePfl1=DataArrayInt.Range(0,14,1) ; zePfl1.setName("PFL") - fNode=MEDCouplingFieldDouble(ON_GAUSS_PT) ; fNode.setTime(float(i),i,0) - tmp=m1[zePfl1] - # - fNode.setName(fieldName0) ; fNode.setMesh(tmp) - fNode.setGaussLocalizationOnCells(DataArrayInt.Range(0,4,1),[-1.,1.],[-0.33333333333333337,0.33333333333333337],[1.,1.]) - fNode.setGaussLocalizationOnCells(DataArrayInt.Range(4,10,1),[-1.,1.],[-0.5,0.,0.5],[1.,1.,1.]) - fNode.setGaussLocalizationOnCells(DataArrayInt.Range(10,14,1),[-1.,1.],[-0.6,-0.2,0.2,0.6],[1.,1.,1.,1.]) - arr=DataArrayDouble(2*(4*2+6*3+4*4)) ; arr.iota(100+1000*i) ; arr.rearrange(2) - fNode.setArray(arr) ; arr.setInfoOnComponents(["Comp1_2 [m]","Com2_2 [s^2]"]) ; fNode.checkConsistencyLight() - fNode.setName(fieldName0) - f.setFieldProfile(fNode,mm,-1,zePfl1) - fs0.pushBackTimeStep(f) - # - f=MEDFileField1TS() - zePfl2=DataArrayInt.Range(10,20,1) ; zePfl2.setName("PFL2") - fNode=MEDCouplingFieldDouble(ON_GAUSS_PT) ; fNode.setTime(float(i),i,0) - tmp=m1[zePfl2] - fNode.setName(fieldName1) ; fNode.setMesh(tmp) - fNode.setGaussLocalizationOnCells(DataArrayInt.Range(0,4,1),[-1.,1.],[-0.6,-0.2,0.2,0.6],[1.,1.,1.,1.]) - fNode.setGaussLocalizationOnCells(DataArrayInt.Range(4,10,1),[-1.,1.],[-0.6666666666666667,-0.33333333333333337,0.,0.33333333333333337,0.6666666666666667],[1.,1.,1.,1.,1.]) - arr=DataArrayDouble(2*(4*4+6*5)) ; arr.iota(500+1000*i) ; arr.rearrange(2) - fNode.setArray(arr) ; arr.setInfoOnComponents(["C1 [m]","C2 [s^2]"]) ; fNode.checkConsistencyLight() - f.setFieldProfile(fNode,mm,-1,zePfl2) - fs1.pushBackTimeStep(f) - # - f=MEDFileField1TS() - zePfl3=DataArrayInt([6,10,11,12,13,17,18,19,20,24,25,26,27,34]) ; zePfl3.setName("PFL3") - fNode=MEDCouplingFieldDouble(ON_NODES) ; fNode.setTime(float(i),i,0) - fNode.setName(fieldName2) - arr=DataArrayDouble(2*14) ; arr.iota(700+1000*i) ; arr.rearrange(2) - fNode.setArray(arr) ; arr.setInfoOnComponents(["C3 [kg]","C4 [m^2]"]) - f.setFieldProfile(fNode,mm,0,zePfl3) - fs2.pushBackTimeStep(f) - pass - fs0.write(fname,0) - fs1.write(fname,0) - fs2.write(fname,0) - return fname - -@WriteInTmpDir -def test(baseline_file): - fname = GenerateCase() - reader=MEDReader(FileName=fname) - ExpectedEntries=['TS0/Mesh/ComSup0/zeField0_MM0@@][@@GAUSS', 'TS0/Mesh/ComSup1/zeField0_MM1@@][@@GAUSS', 'TS0/Mesh/ComSup2/zeField0_MM2@@][@@GAUSS', 'TS0/Mesh/ComSup2/zeField1_MM0@@][@@GAUSS', 'TS0/Mesh/ComSup3/zeField1_MM1@@][@@GAUSS', 'TS0/Mesh/ComSup4/zeField2@@][@@P1', 'TS1/Mesh/ComSup0/Mesh@@][@@P0'] - assert(reader.GetProperty("FieldsTreeInfo")[::2]==ExpectedEntries) - - if '-D' not in sys.argv: - renderView1=GetActiveViewOrCreate('RenderView') - for entry in [[ExpectedEntries[0]],[ExpectedEntries[1]],[ExpectedEntries[2],ExpectedEntries[3]],[ExpectedEntries[4]]]: - reader=MEDReader(FileName=fname) - reader.AllArrays=entry - gaussPoints=ELGAfieldToPointGaussian(Input=reader) - gaussPoints.SelectSourceArray="ELGA@0" - Show(gaussPoints,renderView1) - pass - - # - - readerNodeField=MEDReader(FileName=fname) - readerNodeField.AllArrays=[ExpectedEntries[5]] - nodeFieldDisplay=Show(readerNodeField,renderView1) - ColorBy(nodeFieldDisplay,('POINTS','zeField2')) - nodeFieldDisplay.RescaleTransferFunctionToDataRange(True) - zeField2LUT=GetColorTransferFunction('zeField2') - zeField2LUT.RGBPoints=[990.6568528002015, 0.231373, 0.298039, 0.752941, 1009.0416245953584, 0.865003, 0.865003, 0.865003, 1027.4263963905153, 0.705882, 0.0156863, 0.14902] - zeField2LUT.ScalarRangeInitialized=1. - # - renderView1.ResetCamera() - renderView1.InteractionMode = '2D' - renderView1.CameraPosition = [3.0, 2.0, 10000.0] - renderView1.CameraFocalPoint = [3.0, 2.0, 0.0] - renderView1.ViewSize =[300,300] - renderView1.GetRenderWindow().DoubleBufferOff() - # - - Render() - - # compare with baseline image - import vtk.test.Testing - from vtk.util.misc import vtkGetTempDir - vtk.test.Testing.VTK_TEMP_DIR = vtk.util.misc.vtkGetTempDir() - vtk.test.Testing.compareImage(renderView1.GetRenderWindow(), baseline_file, - threshold=1) - vtk.test.Testing.interact() - -if __name__ == "__main__": - outImgName="testMEDReader14.png" - baseline_file = RetriveBaseLine(outImgName) - test(baseline_file) - pass diff --git a/src/Plugins/MEDReader/Test/testMEDReader15.py b/src/Plugins/MEDReader/Test/testMEDReader15.py deleted file mode 100644 index f3ea0e24..00000000 --- a/src/Plugins/MEDReader/Test/testMEDReader15.py +++ /dev/null @@ -1,95 +0,0 @@ -# -*- coding: iso-8859-1 -*- -# Copyright (C) 2007-2019 CEA/DEN, EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# -# Author : Anthony Geay (EDF R&D) - -import os -import sys - -from medcoupling import * -from paraview.simple import * -from MEDReaderHelper import WriteInTmpDir,RetriveBaseLine - -paraview.simple._DisableFirstRenderCameraReset() - -def GenerateCase(): - """ This test is a non regression test that checks the behaviour of MEDReader when a mesh has the same name than a field. - """ - - fname="testMEDReader15.med" - - zeName="zeName" - c=DataArrayDouble([(0.,0.,0.),(1.,0.,0.),(0.,1.,0.)]) - m=MEDFileUMesh() - m.setCoords(c) - m.setName(zeName) - m.write(fname,2) - f=MEDCouplingFieldDouble(ON_NODES) - f.setName(zeName) - f.setArray(DataArrayDouble([(-1.,1.,0.),(0.,1.,0.),(1.,1.,0.)])) - tmp=MEDCouplingUMesh.Build0DMeshFromCoords(m.getCoords()) ; tmp.setName(zeName) - f.setMesh(tmp) - WriteFieldUsingAlreadyWrittenMesh(fname,f) - return fname - -@WriteInTmpDir -def test(baseline_file): - fname = GenerateCase() - reader=MEDReader(FileName=fname) - ExpectedEntries=['TS0/zeName/ComSup0/zeName@@][@@P1','TS0/zeName/ComSup0/MESH@zeName@@][@@P1'] - assert(reader.GetProperty("FieldsTreeInfo")[::2]==ExpectedEntries) - - # - glyph1=Glyph(Input=reader,GlyphType='Arrow',ScaleArray='FamilyIdNode',OrientationArray='zeName',GlyphMode='All Points',ScaleFactor=0.1,GlyphTransform='Transform2') - - if '-D' not in sys.argv: - renderView1=GetActiveViewOrCreate('RenderView') - renderView1.InteractionMode='3D' - zeNameLUT = GetColorTransferFunction('zeName') - zeNameLUT.RGBPoints = [1.0, 0.231373, 0.298039, 0.752941, 1.2071067811865475, 0.865003, 0.865003, 0.865003, 1.4142135623730951, 0.705882, 0.0156863, 0.14902] - zeNameLUT.ScalarRangeInitialized = 1. - zeNameLUT.VectorMode = 'Component' - - glyph1Display=Show(glyph1,renderView1) - glyph1Display.ColorArrayName = ['POINTS', 'FamilyIdNode'] - glyph1Display.LookupTable = zeNameLUT - # set scalar coloring - ColorBy(glyph1Display, ('POINTS', 'zeName')) - # rescale color and/or opacity maps used to include current data range - glyph1Display.RescaleTransferFunctionToDataRange(True) - # do not show color bar/color legend - glyph1Display.SetScalarBarVisibility(renderView1, False) - # - renderView1.ViewSize =[300,300] - renderView1.GetRenderWindow().DoubleBufferOff() - Render() - - # compare with baseline image - import vtk.test.Testing - from vtk.util.misc import vtkGetTempDir - vtk.test.Testing.VTK_TEMP_DIR = vtk.util.misc.vtkGetTempDir() - vtk.test.Testing.compareImage(GetActiveView().GetRenderWindow(), baseline_file, - threshold=1) - vtk.test.Testing.interact() - -if __name__ == "__main__": - outImgName="testMEDReader15.png" - baseline_file = RetriveBaseLine(outImgName) - test(baseline_file) - pass diff --git a/src/Plugins/MEDReader/Test/testMEDReader16.py b/src/Plugins/MEDReader/Test/testMEDReader16.py deleted file mode 100644 index cc31f6c7..00000000 --- a/src/Plugins/MEDReader/Test/testMEDReader16.py +++ /dev/null @@ -1,114 +0,0 @@ -# -*- coding: iso-8859-1 -*- -# Copyright (C) 2007-2019 CEA/DEN, EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# -# Author : Anthony Geay (EDF R&D) - -from medcoupling import * -from paraview.simple import * -from paraview import servermanager -from MEDReaderHelper import WriteInTmpDir,RetriveBaseLine - -paraview.simple._DisableFirstRenderCameraReset() - -def GenerateCase(): - """ This test is a non regression test of EDF8662 : This bug revealed that ELNOfieldToSurface and ELNOfieldToPointGaussian do not behave correctly after the call of ExtractGroup""" - - fname="testMEDReader16.med" - - arr=DataArrayDouble([0,1,2]) - m=MEDCouplingCMesh() ; m.setCoords(arr,arr) ; m=m.buildUnstructured() ; m.setName("Mesh") - mm=MEDFileUMesh() ; mm.setMeshAtLevel(0,m) - grp0=DataArrayInt([0,1]) ; grp0.setName("grp0") - grp1=DataArrayInt([2,3]) ; grp1.setName("grp1") - grp2=DataArrayInt([1,2]) ; grp2.setName("grp2") - grp3=DataArrayInt([0,1,2,3]) ; grp3.setName("grp3") - mm.setGroupsAtLevel(0,[grp0,grp1,grp2,grp3]) - f=MEDCouplingFieldDouble(ON_GAUSS_NE) ; f.setMesh(m) ; f.setName("MyField") ; f.setTime(0.,0,0) - arr2=DataArrayDouble(4*4*2) ; arr2.iota() ; arr2.rearrange(2) ; arr2.setInfoOnComponents(["aa","bbb"]) - f.setArray(arr2) ; arr2+=0.1 ; f.checkConsistencyLight() - mm.write(fname,2) - WriteFieldUsingAlreadyWrittenMesh(fname,f) - return fname, arr2 - - -@WriteInTmpDir -def test(): - fname,arr2 = GenerateCase() - # - reader=MEDReader(FileName=fname) - ExpectedEntries=['TS0/Mesh/ComSup0/MyField@@][@@GSSNE','TS1/Mesh/ComSup0/Mesh@@][@@P0'] - assert(reader.GetProperty("FieldsTreeInfo")[::2]==ExpectedEntries) - reader.AllArrays=['TS0/Mesh/ComSup0/MyField@@][@@GSSNE'] - ExtractGroup1 = ExtractGroup(Input=reader) - #ExtractGroup1.UpdatePipelineInformation() - ExtractGroup1.AllGroups=["GRP_grp1"] - ELNOfieldToSurface1=ELNOfieldToSurface(Input=ExtractGroup1) - ELNOfieldToPointGaussian1=ELNOfieldToPointGaussian(Input=ExtractGroup1) - ELNOfieldToPointGaussian1.SelectSourceArray=['ELNO@MyField'] - for elt in [ELNOfieldToSurface1,ELNOfieldToPointGaussian1]: - elnoMesh=servermanager.Fetch(ELNOfieldToPointGaussian1,0) - vtkArrToTest=elnoMesh.GetBlock(0).GetPointData().GetArray("MyField") - assert(vtkArrToTest.GetNumberOfTuples()==8) - assert(vtkArrToTest.GetNumberOfComponents()==2) - assert(vtkArrToTest.GetComponentName(0)==arr2.getInfoOnComponent(0)) - assert(vtkArrToTest.GetComponentName(1)==arr2.getInfoOnComponent(1)) - vals=[vtkArrToTest.GetValue(i) for i in range(16)] - assert(arr2[8:].isEqualWithoutConsideringStr(DataArrayDouble(vals,8,2),1e-12)) - pass - # - ExtractGroup1.AllGroups=["GRP_grp2"] - for elt in [ELNOfieldToSurface1,ELNOfieldToPointGaussian1]: - elnoMesh=servermanager.Fetch(ELNOfieldToSurface1) - vtkArrToTest=elnoMesh.GetBlock(0).GetPointData().GetArray("MyField") - assert(vtkArrToTest.GetNumberOfTuples()==8) - assert(vtkArrToTest.GetNumberOfComponents()==2) - assert(vtkArrToTest.GetComponentName(0)==arr2.getInfoOnComponent(0)) - assert(vtkArrToTest.GetComponentName(1)==arr2.getInfoOnComponent(1)) - vals=[vtkArrToTest.GetValue(i) for i in range(16)] - assert(arr2[4:12].isEqualWithoutConsideringStr(DataArrayDouble(vals,8,2),1e-12)) - pass - # important to check that if all the field is present that it is OK (check of the optimization) - ExtractGroup1.AllGroups=["GRP_grp3"] - for elt in [ELNOfieldToSurface1,ELNOfieldToPointGaussian1]: - elnoMesh=servermanager.Fetch(ELNOfieldToSurface1) - vtkArrToTest=elnoMesh.GetBlock(0).GetPointData().GetArray("MyField") - assert(vtkArrToTest.GetNumberOfTuples()==16) - assert(vtkArrToTest.GetNumberOfComponents()==2) - assert(vtkArrToTest.GetComponentName(0)==arr2.getInfoOnComponent(0)) - assert(vtkArrToTest.GetComponentName(1)==arr2.getInfoOnComponent(1)) - vals=[vtkArrToTest.GetValue(i) for i in range(32)] - assert(arr2.isEqualWithoutConsideringStr(DataArrayDouble(vals,16,2),1e-12)) - pass - ELNOfieldToSurface1=ELNOfieldToSurface(Input=reader) - ELNOfieldToPointGaussian1=ELNOfieldToPointGaussian(Input=reader) - ELNOfieldToPointGaussian1.SelectSourceArray=['ELNO@MyField'] - for elt in [ELNOfieldToSurface1,ELNOfieldToPointGaussian1]: - elnoMesh=servermanager.Fetch(ELNOfieldToSurface1) - vtkArrToTest=elnoMesh.GetBlock(0).GetPointData().GetArray("MyField") - assert(vtkArrToTest.GetNumberOfTuples()==16) - assert(vtkArrToTest.GetNumberOfComponents()==2) - assert(vtkArrToTest.GetComponentName(0)==arr2.getInfoOnComponent(0)) - assert(vtkArrToTest.GetComponentName(1)==arr2.getInfoOnComponent(1)) - vals=[vtkArrToTest.GetValue(i) for i in range(32)] - assert(arr2.isEqualWithoutConsideringStr(DataArrayDouble(vals,16,2),1e-12)) - pass - -if __name__ == "__main__": - test() - pass diff --git a/src/Plugins/MEDReader/Test/testMEDReader17.py b/src/Plugins/MEDReader/Test/testMEDReader17.py deleted file mode 100644 index 893ff4e1..00000000 --- a/src/Plugins/MEDReader/Test/testMEDReader17.py +++ /dev/null @@ -1,78 +0,0 @@ -# -*- coding: iso-8859-1 -*- -# Copyright (C) 2007-2019 CEA/DEN, EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# -# Author : Anthony Geay (EDF R&D) - -from medcoupling import * -from paraview.simple import * -from paraview import servermanager -from MEDReaderHelper import WriteInTmpDir,RetriveBaseLine - -paraview.simple._DisableFirstRenderCameraReset() - -def GenerateCase(): - """ This test is a non regression test of EDF9622.""" - - fname="testMEDReader17.med" - - arr=DataArrayDouble([0,1,2]) - m=MEDCouplingCMesh() ; m.setCoords(arr,arr) ; m=m.buildUnstructured() ; m.setName("Mesh") - mm=MEDFileUMesh() ; mm.setMeshAtLevel(0,m) - grp0=DataArrayInt([0,1]) ; grp0.setName("grp0") - grp1=DataArrayInt([2,3]) ; grp1.setName("grp1") - grp2=DataArrayInt([1,2]) ; grp2.setName("grp2") - grp3=DataArrayInt([0,1,2,3]) ; grp3.setName("grp3") - mm.setGroupsAtLevel(0,[grp0,grp1,grp2,grp3]) - f=MEDCouplingFieldDouble(ON_GAUSS_NE) ; f.setMesh(m) ; f.setName("MyField") ; f.setTime(0.,0,0) - arr2=DataArrayDouble(4*4*2) ; arr2.iota() ; arr2.rearrange(2) ; arr2.setInfoOnComponents(["aa","bbb"]) - f.setArray(arr2) ; arr2+=0.1 ; f.checkConsistencyLight() - mm.write(fname,2) - WriteFieldUsingAlreadyWrittenMesh(fname,f) - return fname - -@WriteInTmpDir -def test(): - fname = GenerateCase() - # - reader=MEDReader(FileName=fname) - ExpectedEntries=['TS0/Mesh/ComSup0/MyField@@][@@GSSNE','TS1/Mesh/ComSup0/Mesh@@][@@P0'] - assert(reader.GetProperty("FieldsTreeInfo")[::2]==ExpectedEntries) - reader.AllArrays=['TS0/Mesh/ComSup0/MyField@@][@@GSSNE'] - ExtractGroup1 = ExtractGroup(Input=reader) - #ExtractGroup1.UpdatePipelineInformation() - ExtractGroup1.AllGroups=["GRP_grp1"] - ELNOfieldToPointGaussian1=ELNOfieldToPointGaussian(Input=ExtractGroup1) - ELNOfieldToPointGaussian1.SelectSourceArray=['ELNO@MyField'] - # - ELNOfieldToPointGaussian1=ELNOfieldToPointGaussian(Input=reader) - ELNOfieldToPointGaussian1.SelectSourceArray=['ELNO@MyField'] - ExtractGroup1 = ExtractGroup(Input=ELNOfieldToPointGaussian1) - #ExtractGroup1.UpdatePipelineInformation() - ExtractGroup1.AllGroups=["GRP_grp1"] - #ExtractGroup1.UpdatePipeline() - res=servermanager.Fetch(ExtractGroup1,0) - assert(res.GetBlock(0).GetNumberOfCells()==8) - vtkArrToTest=res.GetBlock(0).GetPointData().GetArray("MyField") - assert(vtkArrToTest.GetNumberOfComponents()==2) - assert(vtkArrToTest.GetNumberOfTuples()==8) - vals=[vtkArrToTest.GetValue(i) for i in range(16)] - assert(DataArrayDouble([(16.1,17.1),(18.1,19.1),(20.1,21.1),(22.1,23.1),(24.1,25.1),(26.1,27.1),(28.1,29.1),(30.1,31.1)]).isEqual(DataArrayDouble(vals,8,2),1e-12)) - -if __name__ == "__main__": - test() diff --git a/src/Plugins/MEDReader/Test/testMEDReader18.py b/src/Plugins/MEDReader/Test/testMEDReader18.py deleted file mode 100644 index fc668781..00000000 --- a/src/Plugins/MEDReader/Test/testMEDReader18.py +++ /dev/null @@ -1,66 +0,0 @@ -# -*- coding: iso-8859-1 -*- -# Copyright (C) 2015-2019 CEA/DEN, EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# -# Author : Anthony Geay (EDF R&D) - - -from medcoupling import * -from paraview.simple import * -from MEDReaderHelper import WriteInTmpDir,RetriveBaseLine - -def GenerateCase(): - """Non regression test for bug EDF11343. Extract group on groups mixing cells entities and node entities.""" - fname="testMEDReader18.med" - arr1=DataArrayDouble(5) ; arr1.iota() - arr2=DataArrayDouble([0,1]) - m=MEDCouplingCMesh() ; m.setCoords(arr1,arr2) - m.setName("mesh") - m=m.buildUnstructured() - # - mm=MEDFileUMesh() - mm[0]=m - # - grp0=DataArrayInt([1,2]) ; grp0.setName("grp0") - grp1=DataArrayInt([3,4,8,9]) ; grp1.setName("grp1") - # - mm.addGroup(0,grp0) - mm.addGroup(1,grp1) - # - mm.write(fname,2) - return fname - -@WriteInTmpDir -def test(): - fname = GenerateCase() - reader=MEDReader(FileName=fname) - reader.AllArrays=['TS0/mesh/ComSup0/mesh@@][@@P0'] - ExtractGroup1 = ExtractGroup(Input=reader) - ExtractGroup1.AllGroups=["GRP_grp0","GRP_grp1"] - #ExtractGroup1.UpdatePipelineInformation() - res=servermanager.Fetch(ExtractGroup1,0) - assert(res.GetNumberOfBlocks()==2) - assert(res.GetBlock(1).GetNumberOfCells()==1) - assert(res.GetBlock(0).GetNumberOfCells()==2) - pass - -if __name__ == "__main__": - test() - pass - - diff --git a/src/Plugins/MEDReader/Test/testMEDReader19.py b/src/Plugins/MEDReader/Test/testMEDReader19.py deleted file mode 100644 index 0b476e1f..00000000 --- a/src/Plugins/MEDReader/Test/testMEDReader19.py +++ /dev/null @@ -1,107 +0,0 @@ -# -*- coding: iso-8859-1 -*- -# Copyright (C) 2015-2019 CEA/DEN, EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# -# Author : Anthony Geay - -import os -import sys - -from medcoupling import * -from paraview.simple import * -from MEDReaderHelper import WriteInTmpDir,RetriveBaseLine -#### import the simple module from the paraview -#### disable automatic camera reset on 'Show' -paraview.simple._DisableFirstRenderCameraReset() -import vtk.test.Testing # this line must be here. If not SIGSEGV ! KW10658 - -def GenerateCase(): - """ This is a non regression bug revealed during training session. The bug is linked to the native Threshold VTK filter. Corrected with PV version >= 4.4. (KW10658) - There is still a problem when both image comparison and Fetch are enable together.""" - fname="testMEDReader19.med" - meshName="mesh" - mm=MEDFileUMesh() - coo=DataArrayDouble([(-0.3,-0.3),(0.2,-0.3),(0.7,-0.3),(-0.3,0.2),(0.2,0.2),(0.7,0.2),(-0.3,0.7),(0.2,0.7),(0.7,0.7)]) - conn0=[[NORM_TRI3,1,4,2],[NORM_TRI3,4,5,2],[NORM_QUAD4,0,3,4,1],[NORM_QUAD4,6,7,4,3],[NORM_QUAD4,7,8,5,4]] - conn1=[[NORM_SEG2,4,5],[NORM_SEG2,5,2],[NORM_SEG2,1,0],[NORM_SEG2,6,7]] - m0=MEDCouplingUMesh() ; m0.setCoords(coo) ; m0.setMeshDimension(2) ; m0.allocateCells(0) - for c in conn0: - m0.insertNextCell(c[0],c[1:]) - mm[0]=m0 - m1=MEDCouplingUMesh() ; m1.setCoords(coo) ; m1.setMeshDimension(1) ; m1.allocateCells(0) - for c in conn1: - m1.insertNextCell(c[0],c[1:]) - mm[-1]=m1 - mm.setName(meshName) - mm.write(fname,2) - return fname - -@WriteInTmpDir -def test(baseline_file): - fname = GenerateCase() - # create a new 'MED Reader' - testMEDReader19med = MEDReader(FileName=fname) - testMEDReader19med.AllArrays = ['TS0/mesh/ComSup0/mesh@@][@@P0'] - testMEDReader19med.AllTimeSteps = ['0000'] - # Properties modified on testMEDReader19med - testMEDReader19med.AllArrays = ['TS0/mesh/ComSup0/mesh@@][@@P0'] - - if '-D' not in sys.argv: - # get active view - renderView1 = GetActiveViewOrCreate('RenderView') - - # reset view to fit data - renderView1.ResetCamera() - - #changing interaction mode based on data extents - renderView1.InteractionMode = '2D' - renderView1.CameraPosition = [0.2, 0.2, 10000.0] - renderView1.CameraFocalPoint = [0.2, 0.2, 0.0] - testMEDReader19med.UpdatePipeline() - # create a new 'Extract Cell Type' - extractCellType1 = ExtractCellType(Input=testMEDReader19med) - extractCellType1.AllGeoTypes = [] - - # Properties modified on extractCellType1 - extractCellType1.AllGeoTypes = ['TRI3'] - - # show data in view - extractCellType1Display = Show(extractCellType1, renderView1) - # trace defaults for the display properties. - extractCellType1Display.ColorArrayName = [None, ''] - extractCellType1Display.ScalarOpacityUnitDistance = 0.5 - - renderView1.InteractionMode = '2D' - renderView1.CameraPosition = [0.2, 0.2, 10000.0] - renderView1.CameraFocalPoint = [0.2, 0.2, 0.0] - renderView1.CameraParallelScale = 0.7071067811865476 - - res=servermanager.Fetch(extractCellType1,0) - assert(res.GetBlock(0).GetNumberOfCells()==2) # problem was here in PV4.3.1 - - # compare with baseline image # Waiting KW return to uncomment this part because SIGSEGV in PV5. - import vtk.test.Testing - from vtk.util.misc import vtkGetTempDir - vtk.test.Testing.VTK_TEMP_DIR = vtk.util.misc.vtkGetTempDir() - vtk.test.Testing.compareImage(GetActiveView().GetRenderWindow(), baseline_file, threshold=1) - vtk.test.Testing.interact() - -if __name__ == "__main__": - imgName="testMEDReader19.png" - baseline_file = RetriveBaseLine(imgName) - test(baseline_file) diff --git a/src/Plugins/MEDReader/Test/testMEDReader2.py b/src/Plugins/MEDReader/Test/testMEDReader2.py deleted file mode 100644 index 5374a13d..00000000 --- a/src/Plugins/MEDReader/Test/testMEDReader2.py +++ /dev/null @@ -1,125 +0,0 @@ -# -*- coding: iso-8859-1 -*- -# Copyright (C) 2007-2019 CEA/DEN, EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# -# Author : Anthony Geay - -import os -import sys - -from medcoupling import * -from paraview.simple import * -from MEDReaderHelper import WriteInTmpDir,RetriveBaseLine - -def GenerateCase(): - """ This use case is a mesh containing a large number of orphan cells (cells having no field lying on them) - """ - fname="testMEDReader2.med" - ######### - arrX=DataArrayDouble(7) ; arrX.iota() - arrY=DataArrayDouble(7) ; arrY.iota() - arrZ=DataArrayDouble(7) ; arrZ.iota() - m=MEDCouplingCMesh() - m.setCoords(arrX,arrY,arrZ) - m=m.buildUnstructured() ; m.setName("mesh") - tmp=m[3*36:4*36] - tmp=tmp.buildDescendingConnectivity()[0] - nodeIds=tmp.findNodesOnPlane([0.,0.,3.],[0.,0.,1.],1e-12) - cellIds=tmp.getCellIdsLyingOnNodes(nodeIds,True) - m1=tmp[cellIds] - mm=MEDFileUMesh() - mm.setMeshAtLevel(0,m) - mm.setMeshAtLevel(-1,m1) - mm.write(fname,2) - # - pfl=DataArrayInt([7,8,9,10,13,14,15,16,19,20,21,22,25,26,27,28]) ; pfl.setName("pfl") - f=MEDCouplingFieldDouble(ON_CELLS) ; f.setName("ACellField") - arr=DataArrayDouble(16) ; arr.iota() - arr2=arr.deepCopy() ; arr2.reverse() - arr=DataArrayDouble.Meld(arr,arr2) ; arr.setInfoOnComponents(["aa","bbb"]) - f.setArray(arr) - f1ts=MEDFileField1TS() - f1ts.setFieldProfile(f,mm,-1,pfl) - f1ts.write(fname,0) - return fname - -@WriteInTmpDir -def test(baseline_file): - fname = GenerateCase() - ################### MED write is done -> Go to MEDReader - testMEDReader1=MEDReader(FileName=fname) - testMEDReader1.AllArrays=['TS0/mesh/ComSup0/ACellField@@][@@P0'] - testMEDReader2=MEDReader(FileName=fname) - testMEDReader2.AllArrays=['TS0/mesh/ComSup1/mesh@@][@@P0'] - GroupDatasets1=GroupDatasets(Input=[testMEDReader1,testMEDReader2]) - - Clip1 = Clip(ClipType="Plane",Input=GroupDatasets1) - Clip1.Scalars=['FamilyIdCell'] - Clip1.ClipType.Origin=[3.0, 3.0, 3.0] - Clip1.Invert=1 - Clip1.ClipType.Normal=[0.9255623174457069, 0.0027407477590518157, 0.378585373233375] - Clip1.Scalars=['CELLS'] - - DataRepresentation4 = Show() - DataRepresentation4.EdgeColor = [0.0, 0.0, 0.5000076295109483] - DataRepresentation4.SelectionCellFieldDataArrayName = 'ACellField' - DataRepresentation4.ScalarOpacityUnitDistance = 1.61104723630366 - DataRepresentation4.ExtractedBlockIndex = 2 - DataRepresentation4.ScaleFactor = 0.6000000000000001 - DataRepresentation4.Visibility = 1 - DataRepresentation4.Representation = 'Wireframe' - - ExtractBlock1 = ExtractBlock(Input=Clip1) - ExtractBlock1.BlockIndices=[1, 2] - - DataRepresentation5 = Show() - DataRepresentation5.EdgeColor = [0.0, 0.0, 0.5000076295109483] - DataRepresentation5.SelectionCellFieldDataArrayName = 'FamilyIdCell' - DataRepresentation5.ScaleFactor = 0.6 - a2_ACellField_PVLookupTable=GetLookupTableForArray( "ACellField", 2, RGBPoints=[10.63014581273465, 0.23, 0.299, 0.754, 15.0, 0.706, 0.016, 0.15], VectorMode='Magnitude', NanColor=[0.25, 0.0, 0.0], ColorSpace='Diverging', ScalarRangeInitialized=1.0, AllowDuplicateScalars=1 ) - a2_ACellField_PiecewiseFunction=CreatePiecewiseFunction( Points=[0.0, 0.0, 0.5, 0.0, 1.0, 1.0, 0.5, 0.0] ) - a2_ACellField_PVLookupTable.ScalarOpacityFunction = a2_ACellField_PiecewiseFunction - DataRepresentation5.ScalarOpacityFunction = a2_ACellField_PiecewiseFunction - DataRepresentation5.LookupTable = a2_ACellField_PVLookupTable - DataRepresentation5.ColorArrayName = ("CELLS", "ACellField") - - if '-D' not in sys.argv: - RenderView1 = GetRenderView() - RenderView1.CenterOfRotation = [3.0, 3.0, 3.0] - RenderView1.CameraViewUp = [-0.03886073885859842, 0.48373409998193495, 0.8743518533691291] - RenderView1.CameraPosition = [7.351939549758929, -5.688193007926853, 8.000155023042788] - RenderView1.CameraFocalPoint = [2.9999999999999996, 2.9999999999999987, 2.9999999999999982] - - RenderView1.ViewSize =[300,300] - Render() - - #WriteImage(outImgName) - - # compare with baseline image - import vtk.test.Testing - from vtk.util.misc import vtkGetTempDir - vtk.test.Testing.VTK_TEMP_DIR = vtk.util.misc.vtkGetTempDir() - vtk.test.Testing.compareImage(GetActiveView().GetRenderWindow(), baseline_file, - threshold=1) - vtk.test.Testing.interact() - -if __name__ == "__main__": - outImgName="testMEDReader2.png" - baseline_file = RetriveBaseLine(outImgName) - test(baseline_file) - pass diff --git a/src/Plugins/MEDReader/Test/testMEDReader20.py b/src/Plugins/MEDReader/Test/testMEDReader20.py deleted file mode 100644 index b8447ce1..00000000 --- a/src/Plugins/MEDReader/Test/testMEDReader20.py +++ /dev/null @@ -1,162 +0,0 @@ -# -*- coding: iso-8859-1 -*- -# Copyright (C) 2016-2019 CEA/DEN, EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# -# Author : Anthony Geay (EDF R&D) - -# non regression test that emulates https://ageay@git.salome-platform.org/gitpub/samples/datafiles.git Med/ResOK_0000.med -# This test point error during commit efd9331a9455785d0f04b75 in PARAVIS -# Commit of the correction : a4e89b15c2faff6341ab9c3d78abc in PARAVIS -# Due to mistake in MEDReader, the family field array on nodes was deleted twice when changing time step - -import os -import sys - -from medcoupling import * -from paraview.simple import * -from MEDReaderHelper import WriteInTmpDir,RetriveBaseLine - -#### disable automatic camera reset on 'Show' -paraview.simple._DisableFirstRenderCameraReset() - -def GenerateCase(): - fname="testMEDReader20.med" - nb=10 - arrX=DataArrayDouble(nb+1) ; arrX.iota() - arrY=DataArrayDouble([0.,1.]) - m=MEDCouplingCMesh() ; m.setCoords(arrX,arrY) ; m=m.buildUnstructured(); m.setName("mesh") ; m.simplexize(0) - mm=MEDFileUMesh() ; mm[0]=m - m1=m.computeSkin() ; mm[-1]=m1 - # - f0=DataArrayInt(m1.getNumberOfCells()) ; f0.iota() ; mm.setFamilyFieldArr(-1,f0) - f1=DataArrayInt(m1.getNumberOfNodes()) ; f1.iota() ; mm.setFamilyFieldArr(1,f1) # <- very important the bug can be shown here - # - nbCells=m1.getNumberOfCells() ; nbNodes=m.getNumberOfNodes() - mm.write(fname,2) - for i in range(5): - f=MEDCouplingFieldDouble(ON_CELLS) ; f.setMesh(m) - f.setName("Field") - arr=DataArrayInt(2*nb) ; arr.iota(i) ; arr%=nb ; arr=arr.convertToDblArr() - f.setArray(arr) ; f.setTime(float(i),i,0) - WriteFieldUsingAlreadyWrittenMesh(fname,f) - # - f=MEDCouplingFieldDouble(ON_CELLS) ; f.setMesh(m1) - f.setName("Field") - arr=DataArrayInt(nbCells) ; arr.iota(i) ; arr%=nbCells ; arr=arr.convertToDblArr() - f.setArray(arr) ; f.setTime(float(i),i,0) - WriteFieldUsingAlreadyWrittenMesh(fname,f) - # - f=MEDCouplingFieldDouble(ON_NODES) ; f.setMesh(m) - f.setName("FieldNode") - arr=DataArrayDouble(nbNodes) ; arr[:]=float(i) - f.setArray(arr) ; f.setTime(float(i),i,0) - WriteFieldUsingAlreadyWrittenMesh(fname,f) - pass - return fname - -@WriteInTmpDir -def test(baseline_file): - fname = GenerateCase() - ##################### - # create a new 'MED Reader' - testMEDReader20med = MEDReader(FileName=fname) - testMEDReader20med.AllArrays = ['TS0/mesh/ComSup0/Field@@][@@P0'] - testMEDReader20med.AllTimeSteps = ['0000', '0001', '0002', '0003', '0004'] - - # get animation scene - animationScene1 = GetAnimationScene() - - # update animation scene based on data timesteps - animationScene1.UpdateAnimationUsingDataTimeSteps() - - if '-D' not in sys.argv: - # get active view - renderView1 = GetActiveViewOrCreate('RenderView') - # uncomment following to set a specific view size - # renderView1.ViewSize = [610, 477] - - # show data in view - testMEDReader20medDisplay = Show(testMEDReader20med, renderView1) - # trace defaults for the display properties. - testMEDReader20medDisplay.ColorArrayName = [None, ''] - testMEDReader20medDisplay.GlyphType = 'Arrow' - testMEDReader20medDisplay.ScalarOpacityUnitDistance = 4.664739046219201 - - # reset view to fit data - renderView1.ResetCamera() - - #changing interaction mode based on data extents - renderView1.InteractionMode = '2D' - renderView1.CameraPosition = [5.0, 0.5, 10000.0] - renderView1.CameraFocalPoint = [5.0, 0.5, 0.0] - - # set scalar coloring - ColorBy(testMEDReader20medDisplay, ('CELLS', 'Field')) - - # rescale color and/or opacity maps used to include current data range - testMEDReader20medDisplay.RescaleTransferFunctionToDataRange(True) - - # do not show color bar/color legend - testMEDReader20medDisplay.SetScalarBarVisibility(renderView1, False) - - # get color transfer function/color map for 'Field' - fieldLUT = GetColorTransferFunction('Field') - - # get opacity transfer function/opacity map for 'Field' - fieldPWF = GetOpacityTransferFunction('Field') - - animationScene1.GoToNext() # <- very important to see the bug play with time steps... - animationScene1.GoToNext() - animationScene1.GoToNext() - animationScene1.GoToNext() - animationScene1.GoToPrevious() - animationScene1.GoToPrevious() - - # current camera placement for renderView1 - renderView1.InteractionMode = '2D' - renderView1.CameraPosition = [5.0, 0.5, 10000.0] - renderView1.CameraFocalPoint = [5.0, 0.5, 0.0] - renderView1.CameraParallelScale = 5.024937810560445 - - # - - renderView1.ViewSize =[300,300] - Render() - #WriteImage(png) - - #### saving camera placements for all active views - - # current camera placement for renderView1 - renderView1.InteractionMode = '2D' - renderView1.CameraPosition = [5.0, 0.5, 10000.0] - renderView1.CameraFocalPoint = [5.0, 0.5, 0.0] - renderView1.CameraParallelScale = 5.024937810560445 - - # compare with baseline image - import vtk.test.Testing - from vtk.util.misc import vtkGetTempDir - vtk.test.Testing.VTK_TEMP_DIR = vtk.util.misc.vtkGetTempDir() - vtk.test.Testing.compareImage(GetActiveView().GetRenderWindow(), baseline_file, threshold=1) - vtk.test.Testing.interact() - pass - -if __name__ == "__main__": - outImgName="testMEDReader20.png" - baseline_file = RetriveBaseLine(outImgName) - test(baseline_file) - pass diff --git a/src/Plugins/MEDReader/Test/testMEDReader21.py b/src/Plugins/MEDReader/Test/testMEDReader21.py deleted file mode 100644 index 133fee3d..00000000 --- a/src/Plugins/MEDReader/Test/testMEDReader21.py +++ /dev/null @@ -1,171 +0,0 @@ -# -*- coding: iso-8859-1 -*- -# Copyright (C) 2015-2019 CEA/DEN, EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# -# Author : Anthony Geay (EDF R&D) - -import os -import sys - -from medcoupling import * -from paraview.simple import * -from MEDReaderHelper import WriteInTmpDir,RetriveBaseLine - -def GenerateCase(): - """ This is a non regression EDF12599""" - fname="testMEDReader21.med" - fieldName="MyField" - meshName="mesh" - m=MEDFileUMesh() - m0=MEDCouplingUMesh(meshName,1) - m0.setCoords(DataArrayDouble([(0.,0.,0),(1.,0.,0.),(2.,0.,0.)])) - m0.allocateCells() - m0.insertNextCell(NORM_SEG2,[0,1]) - m0.insertNextCell(NORM_SEG2,[1,2]) - m[0]=m0 - # - f=MEDCouplingFieldDouble(ON_GAUSS_NE) ; f.setName(fieldName) - f.setMesh(m0) ; f.setArray(DataArrayDouble([1.,7.,3.,2.])) - WriteField(fname,f,True) - return fname, meshName, fieldName - -@WriteInTmpDir -def test(baseline_file): - fname, meshName, fieldName = GenerateCase() - ######## - testTotomed = MEDReader(FileName=fname) - testTotomed.AllArrays = ['TS0/%s/ComSup0/%s@@][@@GSSNE'%(meshName,fieldName)] - testTotomed.AllTimeSteps = ['0000'] - - if '-D' not in sys.argv: - # get active view - renderView1 = GetActiveViewOrCreate('RenderView') - # uncomment following to set a specific view size - # renderView1.ViewSize = [739, 503] - - # show data in view - testTotomedDisplay = Show(testTotomed, renderView1) - # trace defaults for the display properties. - testTotomedDisplay.ColorArrayName = [None, ''] - testTotomedDisplay.GlyphType = 'Arrow' - testTotomedDisplay.ScalarOpacityUnitDistance = 1.5874010519681994 - - # reset view to fit data - renderView1.ResetCamera() - - #changing interaction mode based on data extents - renderView1.InteractionMode = '2D' - renderView1.CameraPosition = [1.0, 10000.0, 10000.0] - renderView1.CameraFocalPoint = [1.0, 0.0, 0.0] - renderView1.CameraViewUp = [1.0, 1.0, 0.0] - - # set scalar coloring - ColorBy(testTotomedDisplay, ('FIELD', 'vtkBlockColors')) - - # hide color bar/color legend - testTotomedDisplay.SetScalarBarVisibility(renderView1, False) - - # get color transfer function/color map for 'vtkBlockColors' - vtkBlockColorsLUT = GetColorTransferFunction('vtkBlockColors') - - # get opacity transfer function/opacity map for 'vtkBlockColors' - vtkBlockColorsPWF = GetOpacityTransferFunction('vtkBlockColors') - - # create a new 'ELNO Mesh' - eLNOMesh1 = ELNOfieldToSurface(Input=testTotomed) - - # Properties modified on eLNOMesh1 - eLNOMesh1.ShrinkFactor = 0.5 # <- test is here !!!!!!!! - - # show data in view - eLNOMesh1Display = Show(eLNOMesh1, renderView1) - # trace defaults for the display properties. - eLNOMesh1Display.ColorArrayName = [None, ''] - eLNOMesh1Display.GlyphType = 'Arrow' - eLNOMesh1Display.ScalarOpacityUnitDistance = 1.1905507889761495 - - # hide data in view - Hide(testTotomed, renderView1) - - # set scalar coloring - ColorBy(eLNOMesh1Display, ('FIELD', 'vtkBlockColors')) - - # show color bar/color legend - eLNOMesh1Display.SetScalarBarVisibility(renderView1, False) - - # set scalar coloring - ColorBy(eLNOMesh1Display, ('POINTS', 'MyField')) - - # rescale color and/or opacity maps used to include current data range - eLNOMesh1Display.RescaleTransferFunctionToDataRange(True) - - # show color bar/color legend - eLNOMesh1Display.SetScalarBarVisibility(renderView1, False) - - # get color transfer function/color map for 'MyField' - myFieldLUT = GetColorTransferFunction('MyField') - - # get opacity transfer function/opacity map for 'MyField' - myFieldPWF = GetOpacityTransferFunction('MyField') - - # hide color bar/color legend - eLNOMesh1Display.SetScalarBarVisibility(renderView1, False) - - # create a new 'Glyph' - glyph1 = Glyph(Input=eLNOMesh1, - GlyphType='Arrow') - glyph1.ScaleArray = [] - glyph1.OrientationArray = ['POINTS', 'No orientation array'] - glyph1.ScaleFactor = 0.15000000000000002 - glyph1.GlyphTransform = 'Transform2' - - # Properties modified on glyph1 - glyph1.GlyphType = 'Sphere' - glyph1.ScaleFactor = 0.15 - - # show data in view - glyph1Display = Show(glyph1, renderView1) - # trace defaults for the display properties. - glyph1Display.ColorArrayName = ['POINTS', 'MyField'] - glyph1Display.LookupTable = myFieldLUT - glyph1Display.GlyphType = 'Arrow' - - # hide color bar/color legend - glyph1Display.SetScalarBarVisibility(renderView1, False) - - #### saving camera placements for all active views - - # current camera placement for renderView1 - renderView1.InteractionMode = '2D' - renderView1.CameraPosition = [0.9999999999999908, 9999.999999999995, 9999.999999999993] - renderView1.CameraFocalPoint = [1.0, 0.0, 0.0] - renderView1.CameraViewUp = [0.6331899945158901, 0.547298104713038, -0.5472981047130381] - renderView1.CameraParallelScale = 0.6930835077290218 - renderView1.ViewSize = [739,503] - - import vtk.test.Testing - from vtk.util.misc import vtkGetTempDir - vtk.test.Testing.VTK_TEMP_DIR = vtk.util.misc.vtkGetTempDir() - vtk.test.Testing.compareImage(GetActiveView().GetRenderWindow(), baseline_file, threshold=1) - vtk.test.Testing.interact() - -if __name__ == "__main__": - imgName="testMEDReader21.png" - baseline_file = RetriveBaseLine(imgName) - test(baseline_file) - pass diff --git a/src/Plugins/MEDReader/Test/testMEDReader3.py b/src/Plugins/MEDReader/Test/testMEDReader3.py deleted file mode 100644 index a3ffac6e..00000000 --- a/src/Plugins/MEDReader/Test/testMEDReader3.py +++ /dev/null @@ -1,148 +0,0 @@ -# -*- coding: iso-8859-1 -*- -# Copyright (C) 2007-2019 CEA/DEN, EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# -# Author : Anthony Geay - -import os -import sys - -from medcoupling import * -from paraview.simple import * -from MEDReaderHelper import WriteInTmpDir,RetriveBaseLine - -outImgName="testMEDReader3.png" - -def GenerateCase(): - """ This test checks that invalid double time (not in [-1e299:1e299]) - leads MEDReader to takes iteration numbers instead of double time to discriminate timesteps each other - See EDF 1956. - """ - fname="testMEDReader3.med" - ######### - m=MEDCouplingUMesh("mesh",2) - coords=DataArrayDouble([(0.,0.,0.),(1.,0.,0.),(1.,1.,0.),(0.,1.,0.)],4,3) - m.setCoords(coords) - m.allocateCells() - m.insertNextCell(NORM_QUAD4,[0,3,2,1]) - mm=MEDFileUMesh() - mm.setMeshAtLevel(0,m) - mm.write(fname,2) - fmts=MEDFileFieldMultiTS() - # - f=MEDCouplingFieldDouble(ON_NODES) ; f.setName("ANodeField") - f.setTime(1.7976931348623157e+308,1,1) ; f.setMesh(m) - arr=DataArrayDouble([0.,4.,4.,4.]) ; arr.setInfoOnComponent(0,"aaa") - f.setArray(arr) - f1ts=MEDFileField1TS() - f1ts.setFieldNoProfileSBT(f) - fmts.pushBackTimeStep(f1ts) - # - f.setTime(1.7976931348623157e+308,2,2) - arr=DataArrayDouble([1.,4.,4.,4.]) ; arr.setInfoOnComponent(0,"aaa") - f.setArray(arr) - f1ts=MEDFileField1TS() - f1ts.setFieldNoProfileSBT(f) - fmts.pushBackTimeStep(f1ts) - # - f.setTime(1.7976931348623157e+308,3,3) - arr=DataArrayDouble([2.,4.,4.,4.]) ; arr.setInfoOnComponent(0,"aaa") - f.setArray(arr) - f1ts=MEDFileField1TS() - f1ts.setFieldNoProfileSBT(f) - fmts.pushBackTimeStep(f1ts) - # - f.setTime(1.7976931348623157e+308,4,6) - arr=DataArrayDouble([3.,4.,4.,4.]) ; arr.setInfoOnComponent(0,"aaa") - f.setArray(arr) - f1ts=MEDFileField1TS() - f1ts.setFieldNoProfileSBT(f) - fmts.pushBackTimeStep(f1ts) - # - f.setTime(1.7976931348623157e+308,5,7) - arr=DataArrayDouble([4.,4.,4.,4.]) ; arr.setInfoOnComponent(0,"aaa") - f.setArray(arr) - f1ts=MEDFileField1TS() - f1ts.setFieldNoProfileSBT(f) - fmts.pushBackTimeStep(f1ts) - # - fmts.write(fname,0) - return fname - -@WriteInTmpDir -def test(baseline_file): - fname = GenerateCase() - ################### MED write is done -> Go to MEDReader - AnimationScene1=GetAnimationScene() - AnimationScene1.PlayMode='Snap To TimeSteps' - AnimationScene1.EndTime = 2.0 - AnimationScene1.AnimationTime = 1.0 - AnimationScene1.StartTime = 1.0 - - testMEDReader3=MEDReader(FileName=fname) - testMEDReader3.AllArrays=['TS0/mesh/ComSup0/ANodeField@@][@@P1'] - - assert(list(testMEDReader3.TimestepValues)==[1.,2.,3.,4.,5.]) ## <- the test is here - double time steps are too big use dt. - - if '-D' not in sys.argv: - RenderView1=GetRenderView() - RenderView1.ViewTime=3.0 - RenderView1.CameraPosition=[0.5,0.5,5.7320508075688776] - RenderView1.ViewSize=[300,300] - - DataRepresentation2=Show() - DataRepresentation2.EdgeColor=[0.0, 0.0, 0.5000076295109483] - DataRepresentation2.SelectionPointFieldDataArrayName='ANodeField' - DataRepresentation2.SelectionCellFieldDataArrayName='FamilyIdCell' - DataRepresentation2.ScalarOpacityUnitDistance=1.4142135623730951 - DataRepresentation2.ExtractedBlockIndex=1 - DataRepresentation2.ScaleFactor=0.1 - - a1_ANodeField_PVLookupTable=GetLookupTableForArray("ANodeField",1,RGBPoints=[0.0,0.23,0.299,0.754,4.0,0.706,0.016,0.15],VectorMode='Magnitude',NanColor=[0.25,0.0,0.0], - ColorSpace='Diverging',ScalarRangeInitialized=1.0,AllowDuplicateScalars=1) - a1_ANodeField_PiecewiseFunction=CreatePiecewiseFunction(Points=[0.0,0.0,0.5,0.0,1.0,1.0,0.5,0.0]) - a1_ANodeField_PVLookupTable.ScalarOpacityFunction=a1_ANodeField_PiecewiseFunction - - DataRepresentation2.ScalarOpacityFunction=a1_ANodeField_PiecewiseFunction - DataRepresentation2.ColorArrayName='ANodeField' - DataRepresentation2.LookupTable=a1_ANodeField_PVLookupTable - - # Triangulate so rendring always the same with different gpu or graphic backend. - extSurf = ExtractSurface(Input=testMEDReader3) - triangulate = Triangulate(Input=extSurf) - Hide(testMEDReader3, RenderView1) - Show(triangulate, RenderView1) - triangulate1Display = GetDisplayProperties(triangulate, view=RenderView1) - ColorBy(triangulate1Display, ('POINTS', 'ANodeField')) - - Render() - ### - - # compare with baseline image - import vtk.test.Testing - from vtk.util.misc import vtkGetTempDir - vtk.test.Testing.VTK_TEMP_DIR = vtk.util.misc.vtkGetTempDir() - vtk.test.Testing.compareImage(GetActiveView().GetRenderWindow(), baseline_file, - threshold=1) - vtk.test.Testing.interact() - -if __name__ == "__main__": - outImgName="testMEDReader3.png" - baseline_file = RetriveBaseLine(outImgName) - test(baseline_file) - pass diff --git a/src/Plugins/MEDReader/Test/testMEDReader4.py b/src/Plugins/MEDReader/Test/testMEDReader4.py deleted file mode 100644 index 4253bb39..00000000 --- a/src/Plugins/MEDReader/Test/testMEDReader4.py +++ /dev/null @@ -1,118 +0,0 @@ -# -*- coding: iso-8859-1 -*- -# Copyright (C) 2007-2019 CEA/DEN, EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# -# Author : Anthony Geay - -import os -import sys - -from medcoupling import * -from paraview.simple import * -from MEDReaderHelper import WriteInTmpDir,RetriveBaseLine - -def GenerateCase(): - """ This test checks that umeshes with no names work properly. - """ - - fname="testMEDReader4.med" - ######### - coords=DataArrayDouble([(0.,0.,0.),(1.,0.,0.),(2.,0.,0.),(3.,0.,0.),(0.,1.,0.),(1.,1.,0.),(2.,1.,0.),(3.,1.,0.),(0.,2.,0.),(1.,2.,0.),(2.,2.,0.),(3.,2.,0.),(0.,3.,0.),(1.,3.,0.),(2.,3.,0.),(3.,3.,0.)]) - m0=MEDCouplingUMesh("mesh",2) - m0.allocateCells() - m0.setCoords(coords) - ## - mm=MEDFileUMesh() - mm.setMeshAtLevel(0,m0) - mm.setFamilyFieldArr(1,DataArrayInt([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])) - # - f1ts0=MEDFileField1TS() - f1ts1=MEDFileField1TS() - # - f0=MEDCouplingFieldDouble(ON_NODES) ; f0.setMesh(m0) ; f0.setName("f0NoPfl") - arr0=DataArrayDouble([0.,1.,2.,3.,1.,1.5,2.2,3.1,2.,2.2,3.,3.1,3.,3.1,3.5,4.]) - f0.setArray(arr0) - f0.checkConsistencyLight() - f1ts0.setFieldNoProfileSBT(f0) - # - pfl1=DataArrayInt([0,1,2,3,4,5,6,8,9,12]) ; pfl1.setName("pfl1") - f1=MEDCouplingFieldDouble(ON_NODES) ; f1.setName("f1Pfl") - arr1=DataArrayDouble([3.,2.,1.,0.,2.,1.5,0.,1.,0.,0.2]) - f1.setArray(arr1) - f1ts1.setFieldProfile(f1,mm,0,pfl1) - # - fs=MEDFileFields() - fmts0=MEDFileFieldMultiTS() - fmts0.pushBackTimeStep(f1ts0) - fmts1=MEDFileFieldMultiTS() - fmts1.pushBackTimeStep(f1ts1) - fs.pushField(fmts0) ; fs.pushField(fmts1) - mm.write(fname,2) - fs.write(fname,0) - return fname - -@WriteInTmpDir -def test(baseline_file): -################### MED write is done -> Go to MEDReader - fname = GenerateCase() - - testMEDReader4_med=MEDReader(FileName=fname) - - testMEDReader4_med.AllArrays=['TS0/mesh/ComSup0/f0NoPfl@@][@@P1','TS0/mesh/ComSup0/mesh@@][@@P1'] - #testMEDReader4_med.AllTimeSteps=['0000'] - - Glyph1=Glyph(Input=testMEDReader4_med,GlyphType='Sphere') - Glyph1.ScaleArray=['POINTS','No scale array']#f0NoPflN - Glyph1.ScaleFactor=0.3 - Glyph1.OrientationArray = ['POINTS', 'No orientation array'] - Glyph1.GlyphTransform="Transform2" - Glyph1.GlyphMode = 'All Points' - - DataRepresentation1 = Show() - DataRepresentation1.EdgeColor = [0.0, 0.0, 0.5000076295109483] - DataRepresentation1.SelectionPointFieldDataArrayName = 'f0NoPfl' - DataRepresentation1.ScaleFactor = 0.3 - DataRepresentation1.ColorArrayName = 'f0NoPfl' - lookupTable = GetLookupTableForArray( "f0NoPfl", 1, RGBPoints=[0.0, 0.23, 0.299, 0.754, 4.0, 0.706, 0.016, 0.15], VectorMode='Magnitude', NanColor=[0.25, 0.0, 0.0], ColorSpace='Diverging', ScalarRangeInitialized=1.0, AllowDuplicateScalars=1 ) - function=CreatePiecewiseFunction(Points=[0.0,0.0,0.5,0.0,1.0,1.0,0.5,0.0] ) - lookupTable.ScalarOpacityFunction = function - DataRepresentation1.LookupTable = lookupTable - - if '-D' not in sys.argv: - RenderView1 = GetRenderView() - RenderView1.CameraViewUp = [0.06254683966704512, 0.9980420295997885, 0.0] - RenderView1.CameraPosition = [0.8087292125440382, 1.3325993334207897, 12.692130429902462] - RenderView1.CameraFocalPoint = [0.8087292125440382, 1.3325993334207897, 0.0] - RenderView1.CameraParallelScale = 3.712804729456109 - - RenderView1.ViewSize =[300,300] - Render() - - # compare with baseline image - import vtk.test.Testing - from vtk.util.misc import vtkGetTempDir - vtk.test.Testing.VTK_TEMP_DIR = vtk.util.misc.vtkGetTempDir() - vtk.test.Testing.compareImage(GetActiveView().GetRenderWindow(), baseline_file, - threshold=1) - vtk.test.Testing.interact() - -if __name__ == "__main__": - outImgName="testMEDReader4.png" - baseline_file = RetriveBaseLine(outImgName) - test(baseline_file) - pass diff --git a/src/Plugins/MEDReader/Test/testMEDReader5.py b/src/Plugins/MEDReader/Test/testMEDReader5.py deleted file mode 100644 index f278a8e2..00000000 --- a/src/Plugins/MEDReader/Test/testMEDReader5.py +++ /dev/null @@ -1,134 +0,0 @@ -# -*- coding: iso-8859-1 -*- -# Copyright (C) 2007-2019 CEA/DEN, EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# -# Author : Anthony Geay - -import os -import sys - -from medcoupling import * -from paraview.simple import * -from MEDReaderHelper import WriteInTmpDir,RetriveBaseLine - -def GenerateCase(): - """ This test is CEA specific one. It generates a .sauv file - that is then read by MEDReader - """ - fname="testMEDReader5.sauv" - ######### - arr=DataArrayDouble(5) ; arr.iota() - c=MEDCouplingCMesh("mesh") - c.setCoords(arr,arr,arr) - m=c.buildUnstructured() - mbis=m.deepCopy() ; mbis.translate([5,0,0]) ; mbis.tetrahedrize(PLANAR_FACE_5) - m=MEDCouplingUMesh.MergeUMeshes([mbis,m]) ; m.setName(c.getName()) - mm=MEDFileUMesh() - mm.setMeshAtLevel(0,m) - grp0=DataArrayInt.Range(0,m.getNumberOfCells(),2) ; grp0.setName("grp0") - grp1=DataArrayInt.Range(1,m.getNumberOfCells(),2) ; grp1.setName("grp1") - grp2=DataArrayInt.Range(0,m.getNumberOfNodes(),7) ; grp2.setName("grp2") - mm.setGroupsAtLevel(0,[grp0,grp1]) - mm.setGroupsAtLevel(1,[grp2]) - ms=MEDFileMeshes() - ms.pushMesh(mm) - f=MEDCouplingFieldDouble(ON_CELLS) ; f.setName("fCell") ; f.setMesh(m[:10]) - arr=DataArrayDouble(f.getNumberOfTuplesExpected()) ; arr.iota() ; f.setArray(arr) - f2=MEDCouplingFieldDouble(ON_NODES) ; f2.setName("fNode") ; f2.setMesh(m) - arr=DataArrayDouble(f2.getNumberOfTuplesExpected()) ; arr.iota() ; f2.setArray(arr) - - fs=MEDFileFields() - f1ts=MEDFileField1TS() - #f1ts.setFieldNoProfileSBT(f) - pfl=DataArrayInt(10); pfl.iota() ; pfl.setName("pfl") ; f1ts.setFieldProfile(f,mm,0,pfl) - fmts=MEDFileFieldMultiTS() - fmts.pushBackTimeStep(f1ts) - fs.pushField(fmts) - f1ts=MEDFileField1TS() - f1ts.setFieldNoProfileSBT(f2) - fmts=MEDFileFieldMultiTS() - fmts.pushBackTimeStep(f1ts) - fs.pushField(fmts) - - mfd=MEDFileData() - mfd.setMeshes(ms) - mfd.setFields(fs) - #mfd.write(fname,2) not activated because useless - # - sw=SauvWriter(); - sw.setMEDFileDS(mfd); - sw.write(fname); - del mm,m,c,f,arr - del f1ts - return fname - - -@WriteInTmpDir -def test(baseline_file): - fname = GenerateCase() - ################### MED write is done -> Go to MEDReader - myMedReader=MEDReader(FileName=fname) - myMedReader.AllArrays = ['TS0/mesh/ComSup1/fNode@@][@@P1'] - myMedReader.AllTimeSteps = ['0000'] - - Clip1=Clip(ClipType="Plane",Input=myMedReader) - Clip1.Scalars = ['POINTS', 'FamilyIdNode'] - Clip1.ClipType.Origin = [2.0, 2.0, 2.0] - Clip1.ClipType = "Plane" - Clip1.ClipType.Normal = [0.04207410474474753, 0.9319448861971525, 0.3601506612529047] - Clip1.Invert = 1 - - DataRepresentation2 = Show() - DataRepresentation2.EdgeColor = [0.0, 0.0, 0.5000076295109483] - DataRepresentation2.ScalarOpacityUnitDistance = 1.5768745057161244 - DataRepresentation2.ExtractedBlockIndex = 1 - DataRepresentation2.ScaleFactor = 0.4 - - if '-D' not in sys.argv: - RenderView1=GetRenderView() - RenderView1.CenterOfRotation=[2.,2.,2.] - RenderView1.CameraViewUp=[0.24562884954787187,0.6907950752417243,-0.680050463047831] - RenderView1.CameraPosition=[-2.5085697461776486,11.6185941755061,10.14210560568201] - RenderView1.CameraFocalPoint=[2.,2.,2.] - RenderView1.CameraParallelScale=5.071791174723188 - - LookupTable=GetLookupTableForArray("fNode",1,RGBPoints=[0.0,0.23,0.299,0.754,55.0,0.706,0.016,0.15],VectorMode='Magnitude',NanColor=[0.25,0.0,0.0],ColorSpace='Diverging',ScalarRangeInitialized=1.0,AllowDuplicateScalars=1) - DataRepresentation2 = Show() - DataRepresentation2.EdgeColor = [0.0, 0.0, 0.5000076295109483] - DataRepresentation2.ScalarOpacityUnitDistance = 1.5768745057161244 - DataRepresentation2.ExtractedBlockIndex = 1 - DataRepresentation2.ScaleFactor = 0.4 - DataRepresentation2.ColorArrayName=('POINTS','fNode') - DataRepresentation2.LookupTable=LookupTable - - RenderView1.ViewSize=[300,300] - Render() - - # compare with baseline image - import vtk.test.Testing - from vtk.util.misc import vtkGetTempDir - vtk.test.Testing.VTK_TEMP_DIR = vtk.util.misc.vtkGetTempDir() - vtk.test.Testing.compareImage(GetActiveView().GetRenderWindow(), baseline_file, - threshold=1) - vtk.test.Testing.interact() - -if __name__ == "__main__": - outImgName="testMEDReader5.png" - baseline_file = RetriveBaseLine(outImgName) - test(baseline_file) - pass diff --git a/src/Plugins/MEDReader/Test/testMEDReader6.py b/src/Plugins/MEDReader/Test/testMEDReader6.py deleted file mode 100644 index 159121f4..00000000 --- a/src/Plugins/MEDReader/Test/testMEDReader6.py +++ /dev/null @@ -1,119 +0,0 @@ -# -*- coding: iso-8859-1 -*- -# Copyright (C) 2007-2019 CEA/DEN, EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# -# Author : Anthony Geay - -import os -import sys - -from medcoupling import * -from paraview.simple import * -from MEDReaderHelper import WriteInTmpDir,RetriveBaseLine - -def GenerateCase(): - """ This test generate a GaussPoint field on a mesh with groups. - The aim of this test is to check that the ExtractGroup works well for ELGAfieldToPointGaussian - """ - fname="testMEDReader6.med" - ######### - arr=DataArrayDouble([(0,0,0),(1,0,0),(2,0,0),(3,0,0),(0,1,0),(1,1,0),(2,1,0),(3,1,0),(0,2,0),(1,2,0),(2,2,0),(3,2,0),(0,3,0),(1,3,0),(2,3,0),(3,3,0)]) - m0=MEDCouplingUMesh("mesh",2) ; m0.setCoords(arr) ; m0.allocateCells() - for elt in [[2,3,6],[3,7,6],[6,9,5],[6,10,9]]: - m0.insertNextCell(NORM_TRI3,elt) - pass - for elt in [[0,4,5,1],[5,6,2,1],[4,8,9,5],[6,10,11,7],[8,12,13,9],[9,13,14,10],[10,14,15,11]]: - m0.insertNextCell(NORM_QUAD4,elt) - pass - mm=MEDFileUMesh() - mm.setMeshAtLevel(0,m0) - grp0=DataArrayInt([0,1,4,5,7,10]) ; grp0.setName("grp0") - mm.setGroupsAtLevel(0,[grp0]) - # - fGauss=MEDCouplingFieldDouble(ON_GAUSS_PT) ; fGauss.setName("fGauss") - fGauss.setMesh(m0) - fGauss.setGaussLocalizationOnType(NORM_TRI3,[0.,0.,1.,0.,0.,1.],[0.1,0.1,0.05,0.9],[0.4,0.6]) - fGauss.setGaussLocalizationOnType(NORM_QUAD4,[-1.,-1.,1.,-1.,1.,1.,-1.,1.],[-0.9,-0.9,0.,0.,0.9,0.9],[0.2,0.3,0.5]) - fGauss.setArray(DataArrayDouble([0.9,1.3,0.22,1.3,1.62,2.21,1.62,2.72,2.95,2.54,2.25,2.16,1.58,1.05,3.13,2.91,2.82,1.41,1.58,1.95,3.59,3.53,3.59,2.82,2.91,3.13,2.25,2.54,2.95])) - fGauss.getArray().setInfoOnComponent(0,"C0") - fGauss.checkConsistencyLight() - # - f1ts=MEDFileField1TS() - f1ts.setFieldNoProfileSBT(fGauss) - # - mm.write(fname,2) - f1ts.write(fname,0) - return fname - -@WriteInTmpDir -def test(baseline_file): - fname = GenerateCase() - ################### MED write is done -> Go to MEDReader - - myMedReader=MEDReader(FileName=fname) - myMedReader.AllArrays = ['TS0/mesh/ComSup0/fGauss@@][@@GAUSS'] - myMedReader.AllTimeSteps = ['0000'] - - ExtractGroup1 = ExtractGroup(Input=myMedReader) - ExtractGroup1.UpdatePipelineInformation() - ExtractGroup1.AllGroups = ['GRP_grp0'] - - ELGAfieldToPointGaussian1 = ELGAfieldToPointGaussian(Input=ExtractGroup1) - ELGAfieldToPointGaussian1.SelectSourceArray = ['CELLS','ELGA@0'] - - Glyph1 = Glyph( Input=ELGAfieldToPointGaussian1, GlyphType="Sphere", GlyphTransform="Transform2" ) - Glyph1.GlyphType = "Sphere" - Glyph1.OrientationArray = ['POINTS', 'No orientation array'] - Glyph1.ScaleFactor = 0.29 - - if '-D' not in sys.argv: - RenderView1 = GetRenderView() - RenderView1.CameraFocalPoint = [1.5, 1.5, 0.0] - RenderView1.CameraPosition = [1.5, 1.5, 10000.0] - RenderView1.InteractionMode = '3D' - RenderView1.CameraPosition = [1.5, 1.5, 8.196152422706632] - RenderView1.CameraParallelScale = 2.1213203435596424 - RenderView1.CenterOfRotation = [1.5, 1.5, 0.0] - - DataRepresentation4 = Show() - DataRepresentation4.EdgeColor = [0.0, 0.0, 0.5000076295109483] - DataRepresentation4.SelectionPointFieldDataArrayName = 'fGauss' - DataRepresentation4.ScaleFactor = 0.3182729169726372 - - a1_fGauss_PVLookupTable = GetLookupTableForArray( "fGauss", 1, RGBPoints=[0.22, 0.23, 0.299, 0.754, 2.95, 0.706, 0.016, 0.15], VectorMode='Magnitude', NanColor=[0.25, 0.0, 0.0], ColorSpace='Diverging', ScalarRangeInitialized=1.0, AllowDuplicateScalars=1 ) - a1_fGauss_PiecewiseFunction = CreatePiecewiseFunction( Points=[0.0, 0.0, 0.5, 0.0, 1.0, 1.0, 0.5, 0.0] ) - DataRepresentation4.ColorArrayName = 'fGauss' - DataRepresentation4.LookupTable = a1_fGauss_PVLookupTable - a1_fGauss_PVLookupTable.ScalarOpacityFunction = a1_fGauss_PiecewiseFunction - - RenderView1.ViewSize=[300,300] - Render() - - # compare with baseline image - import vtk.test.Testing - from vtk.util.misc import vtkGetTempDir - vtk.test.Testing.VTK_TEMP_DIR = vtk.util.misc.vtkGetTempDir() - vtk.test.Testing.compareImage(GetActiveView().GetRenderWindow(), baseline_file, - threshold=1) - vtk.test.Testing.interact() - -if __name__ == "__main__": - outImgName="testMEDReader6.png" - baseline_file = RetriveBaseLine(outImgName) - test(baseline_file) - pass diff --git a/src/Plugins/MEDReader/Test/testMEDReader7.py b/src/Plugins/MEDReader/Test/testMEDReader7.py deleted file mode 100644 index d7f40b13..00000000 --- a/src/Plugins/MEDReader/Test/testMEDReader7.py +++ /dev/null @@ -1,120 +0,0 @@ -# -*- coding: iso-8859-1 -*- -# Copyright (C) 2007-2019 CEA/DEN, EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# -# Author : Anthony Geay - -import os -import sys - - -from medcoupling import * -from paraview.simple import * -from MEDReaderHelper import WriteInTmpDir,RetriveBaseLine - -def GenerateCase(): - """ This test generate a simple multi time field with a very aggressive time steps triplets. Neither dt, nor iteration nor order is considered. - In this case only the rank is considered. - """ - fname="testMEDReader7.med" - ######### - arr=DataArrayDouble([(0,0,0),(1,0,0),(2,0,0),(3,0,0),(0,1,0),(1,1,0),(2,1,0),(3,1,0),(0,2,0),(1,2,0),(2,2,0),(3,2,0),(0,3,0),(1,3,0),(2,3,0),(3,3,0)]) - m0=MEDCouplingUMesh("mesh",2) ; m0.setCoords(arr) ; m0.allocateCells() - for elt in [[2,3,6],[3,7,6],[6,9,5],[6,10,9]]: - m0.insertNextCell(NORM_TRI3,elt) - pass - for elt in [[0,4,5,1],[5,6,2,1],[4,8,9,5],[6,10,11,7],[8,12,13,9],[9,13,14,10],[10,14,15,11]]: - m0.insertNextCell(NORM_QUAD4,elt) - pass - mm=MEDFileUMesh() - mm.setMeshAtLevel(0,m0) - grp0=DataArrayInt([0,1,4,5,7,10]) ; grp0.setName("grp0") - mm.setGroupsAtLevel(0,[grp0]) - fmts=MEDFileFieldMultiTS() - # - fNode=MEDCouplingFieldDouble(ON_NODES) ; fNode.setName("fNode") - fNode.setMesh(m0) - fNode.setArray(DataArrayDouble([3,2,1,0,3.16,2.23,1.41,1,3.6,2.82,2.23,2,4.24,3.6,3.16,3])) - fNode.getArray().setInfoOnComponent(0,"C0") - fNode.setTime(0.5,1,1) - f1ts=MEDFileField1TS() ; f1ts.setFieldNoProfileSBT(fNode) ; fmts.pushBackTimeStep(f1ts) - # - fNode.getArray().reverse() - fNode.setTime(0.5,1,2) - f1ts=MEDFileField1TS() ; f1ts.setFieldNoProfileSBT(fNode) ; fmts.pushBackTimeStep(f1ts) - # - fNode.getArray().reverse() - fNode.setTime(0.5,2,1) - f1ts=MEDFileField1TS() ; f1ts.setFieldNoProfileSBT(fNode) ; fmts.pushBackTimeStep(f1ts) - # - fNode.getArray().reverse() - fNode.setTime(0.5,2,2) - f1ts=MEDFileField1TS() ; f1ts.setFieldNoProfileSBT(fNode) ; fmts.pushBackTimeStep(f1ts) - # - mm.write(fname,2) - fmts.write(fname,0) - return fname - - -@WriteInTmpDir -def test(baseline_file): - fname = GenerateCase() - ################### MED write is done -> Go to MEDReader - myMedReader=MEDReader(FileName=fname) - myMedReader.AllArrays = ['TS0/mesh/ComSup0/fNode@@][@@P1'] - assert(list(myMedReader.TimestepValues)==[0.,1.,2.,3.]) - - if '-D' not in sys.argv: - RenderView1 = GetRenderView() - RenderView1.CameraFocalPoint = [1.5, 1.5, 0.0] - RenderView1.CameraPosition = [1.5, 1.5, 10000.0] - RenderView1.InteractionMode = '3D' - RenderView1.CameraPosition = [1.5, 1.5, 8.196152422706632] - RenderView1.CameraParallelScale = 2.1213203435596424 - RenderView1.CenterOfRotation = [1.5, 1.5, 0.0] - - DataRepresentation4 = Show() - DataRepresentation4.EdgeColor = [0.0, 0.0, 0.5000076295109483] - DataRepresentation4.SelectionPointFieldDataArrayName = 'fNode' - DataRepresentation4.ScaleFactor = 0.3182729169726372 - - a1_fGauss_PVLookupTable = GetLookupTableForArray( "fNode", 1, RGBPoints=[0.22, 0.23, 0.299, 0.754, 2.95, 0.706, 0.016, 0.15], VectorMode='Magnitude', NanColor=[0.25, 0.0, 0.0], ColorSpace='Diverging', ScalarRangeInitialized=1.0, AllowDuplicateScalars=1 ) - a1_fGauss_PiecewiseFunction = CreatePiecewiseFunction( Points=[0.0, 0.0, 0.5, 0.0, 1.0, 1.0, 0.5, 0.0] ) - DataRepresentation4.ColorArrayName = 'fNode' - DataRepresentation4.LookupTable = a1_fGauss_PVLookupTable - a1_fGauss_PVLookupTable.ScalarOpacityFunction = a1_fGauss_PiecewiseFunction - - RenderView1.ViewTime = 1.0 #### Important # red is in right bottom - RenderView1.CacheKey = 1.0 - RenderView1.UseCache = 1 - RenderView1.ViewSize=[300,300] - Render() - - # compare with baseline image - import vtk.test.Testing - from vtk.util.misc import vtkGetTempDir - vtk.test.Testing.VTK_TEMP_DIR = vtk.util.misc.vtkGetTempDir() - vtk.test.Testing.compareImage(GetActiveView().GetRenderWindow(), baseline_file, - threshold=6) - vtk.test.Testing.interact() - -if __name__ == "__main__": - outImgName="testMEDReader7.png" - baseline_file = RetriveBaseLine(outImgName) - test(baseline_file) - pass diff --git a/src/Plugins/MEDReader/Test/testMEDReader8.py b/src/Plugins/MEDReader/Test/testMEDReader8.py deleted file mode 100644 index 85814275..00000000 --- a/src/Plugins/MEDReader/Test/testMEDReader8.py +++ /dev/null @@ -1,131 +0,0 @@ -# -*- coding: iso-8859-1 -*- -# Copyright (C) 2007-2019 CEA/DEN, EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# -# Author : Anthony Geay - -import os -import sys - -from medcoupling import * -from paraview.simple import * -from MEDReaderHelper import WriteInTmpDir,RetriveBaseLine - -def GenerateCase(): - """ This test is a non regression test. ExtractCellType then ExtractGroup. - """ - fname="testMEDReader8.med" - ######### - arr=DataArrayDouble([(0,0,0),(1,0,0),(2,0,0),(3,0,0),(0,1,0),(1,1,0),(2,1,0),(3,1,0),(0,2,0),(1,2,0),(2,2,0),(3,2,0),(0,3,0),(1,3,0),(2,3,0),(3,3,0)]) - m0=MEDCouplingUMesh("mesh",2) ; m0.setCoords(arr) ; m0.allocateCells() - for elt in [[2,3,6],[3,7,6],[6,9,5],[6,10,9]]: - m0.insertNextCell(NORM_TRI3,elt) - pass - for elt in [[0,4,5,1],[5,6,2,1],[4,8,9,5],[6,10,11,7],[8,12,13,9],[9,13,14,10],[10,14,15,11]]: - m0.insertNextCell(NORM_QUAD4,elt) - pass - mm=MEDFileUMesh() - mm.setMeshAtLevel(0,m0) - grp0=DataArrayInt([0,1,2,5]) ; grp0.setName("grp0") - mm.setGroupsAtLevel(0,[grp0]) - fmts=MEDFileFieldMultiTS() - # - fNode=MEDCouplingFieldDouble(ON_NODES) ; fNode.setName("fNode") - fNode.setMesh(m0) - fNode.setArray(DataArrayDouble([3,2,1,0,3.16,2.23,1.41,1,3.6,2.82,2.23,2,4.24,3.6,3.16,3])) - fNode.getArray().setInfoOnComponent(0,"C0") - fNode.setTime(0.5,1,1) - f1ts=MEDFileField1TS() ; f1ts.setFieldNoProfileSBT(fNode) ; fmts.pushBackTimeStep(f1ts) - # - fNode.getArray().reverse() - fNode.setTime(0.5,1,2) - f1ts=MEDFileField1TS() ; f1ts.setFieldNoProfileSBT(fNode) ; fmts.pushBackTimeStep(f1ts) - # - fNode.getArray().reverse() - fNode.setTime(0.5,2,1) - f1ts=MEDFileField1TS() ; f1ts.setFieldNoProfileSBT(fNode) ; fmts.pushBackTimeStep(f1ts) - # - fNode.getArray().reverse() - fNode.setTime(0.5,2,2) - f1ts=MEDFileField1TS() ; f1ts.setFieldNoProfileSBT(fNode) ; fmts.pushBackTimeStep(f1ts) - # - mm.write(fname,2) - fmts.write(fname,0) - return fname - - -@WriteInTmpDir -def test(baseline_file): - fname = GenerateCase() - ################### MED write is done -> Go to MEDReader - - myMedReader=MEDReader(FileName=fname) - myMedReader.AllArrays = ['TS0/mesh/ComSup0/fNode@@][@@P1'] - assert(list(myMedReader.TimestepValues)==[0.,1.,2.,3.]) - myMedReader.UpdatePipeline() - - extractCT=ExtractCellType(Input=myMedReader) - extractCT.UpdatePipelineInformation() - assert(list(extractCT.GetProperty("GeoTypesInfo"))==['TRI3','0','QUAD4','0']) - extractCT.AllGeoTypes=['TRI3'] - - extGrp=ExtractGroup(Input=extractCT) - #extGrp.UpdatePipelineInformation() - assert([x for x in list(extGrp.GetProperty("GroupsFlagsInfo")[::2]) if x[:4]=="GRP_"]==['GRP_grp0']) - extGrp.AllGroups="GRP_grp0" - - if '-D' not in sys.argv: - RenderView1 = GetRenderView() - RenderView1.CameraFocalPoint = [1.5, 1.5, 0.0] - RenderView1.CameraPosition = [1.5, 1.5, 10000.0] - RenderView1.InteractionMode = '3D' - RenderView1.CameraPosition = [1.5, 1.5, 8.196152422706632] - RenderView1.CameraParallelScale = 2.1213203435596424 - RenderView1.CenterOfRotation = [1.5, 1.5, 0.0] - - DataRepresentation4 = Show() - DataRepresentation4.EdgeColor = [0.0, 0.0, 0.5000076295109483] - DataRepresentation4.SelectionPointFieldDataArrayName = 'fNode' - DataRepresentation4.ScaleFactor = 0.3182729169726372 - - a1_fGauss_PVLookupTable = GetLookupTableForArray( "fNode", 1, RGBPoints=[0.22, 0.23, 0.299, 0.754, 2.95, 0.706, 0.016, 0.15], VectorMode='Magnitude', NanColor=[0.25, 0.0, 0.0], ColorSpace='Diverging', ScalarRangeInitialized=1.0, AllowDuplicateScalars=1 ) - a1_fGauss_PiecewiseFunction = CreatePiecewiseFunction( Points=[0.0, 0.0, 0.5, 0.0, 1.0, 1.0, 0.5, 0.0] ) - DataRepresentation4.ColorArrayName = 'fNode' - DataRepresentation4.LookupTable = a1_fGauss_PVLookupTable - a1_fGauss_PVLookupTable.ScalarOpacityFunction = a1_fGauss_PiecewiseFunction - - RenderView1.ViewTime = 1.0 #### Important # red is in right bottom - RenderView1.CacheKey = 1.0 - RenderView1.UseCache = 1 - RenderView1.ViewSize=[300,300] - Render() - - # compare with baseline image - - import vtk.test.Testing - from vtk.util.misc import vtkGetTempDir - vtk.test.Testing.VTK_TEMP_DIR = vtk.util.misc.vtkGetTempDir() - vtk.test.Testing.compareImage(GetActiveView().GetRenderWindow(), baseline_file, - threshold=1) - vtk.test.Testing.interact() - -if __name__ == "__main__": - outImgName="testMEDReader8.png" - baseline_file = RetriveBaseLine(outImgName) - test(baseline_file) - pass diff --git a/src/Plugins/MEDReader/Test/testMEDReader9.py b/src/Plugins/MEDReader/Test/testMEDReader9.py deleted file mode 100644 index 4945528f..00000000 --- a/src/Plugins/MEDReader/Test/testMEDReader9.py +++ /dev/null @@ -1,63 +0,0 @@ -# -*- coding: iso-8859-1 -*- -# Copyright (C) 2007-2019 CEA/DEN, EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# -# Author : Anthony Geay - -from medcoupling import * -from paraview.simple import * -from MEDReaderHelper import WriteInTmpDir,RetriveBaseLine - -def GenerateCase(): - """ This test is a non regression test. Test that ExtractGroup adapt to the current mesh of MEDReader. A MED file containing 2 fields on a 2 different meshes. - This test checks that the MeshName follows. - """ - fname="testMEDReader9.med" - ######### - m1=MEDCouplingUMesh("m1",2) ; m1.setCoords(DataArrayDouble([(0.,0.),(1.,0.),(0.,1.)])) ; m1.allocateCells() ; m1.insertNextCell(NORM_TRI3,[0,1,2]) - m2=MEDCouplingUMesh("m2",2) ; m2.setCoords(DataArrayDouble([(0.,0.),(1.,0.),(0.,1.),(1.,1.)])) ; m2.allocateCells() ; m2.insertNextCell(NORM_QUAD4,[0,1,3,2]) - mm1=MEDFileUMesh() ; mm2=MEDFileUMesh() - mm1.setMeshAtLevel(0,m1) ; mm2.setMeshAtLevel(0,m2) - ms=MEDFileMeshes() ; ms.pushMesh(mm1) ; ms.pushMesh(mm2) - f1=MEDCouplingFieldDouble(ON_CELLS) ; f1.setName("f1") ; f1.setMesh(m1) ; f1.setArray(DataArrayDouble([1.111])) - f2=MEDCouplingFieldDouble(ON_CELLS) ; f2.setName("f2") ; f2.setMesh(m2) ; f2.setArray(DataArrayDouble([2.2222])) - ff1=MEDFileField1TS() ; ff2=MEDFileField1TS() - ff1.setFieldNoProfileSBT(f1) ; ff2.setFieldNoProfileSBT(f2) - ms.write(fname,2) - ff1.write(fname,0) - ff2.write(fname,0) - return fname - -@WriteInTmpDir -def test(): - fname = GenerateCase() - ################### MED write is done -> Go to MEDReader - myMedReader=MEDReader(FileName=fname) - myMedReader.AllArrays=['TS0/m1/ComSup0/f1@@][@@P0'] - #myMedReader.UpdatePipelineInformation() - ExtractGroup1=ExtractGroup(Input=myMedReader) - #ExtractGroup1.UpdatePipelineInformation() - assert(ExtractGroup1.GetProperty("MeshName")[0]=="m1") - myMedReader.AllArrays=['TS0/m2/ComSup0/f2@@][@@P0'] - #myMedReader.UpdatePipeline() - ExtractGroup2=ExtractGroup(Input=myMedReader) - #ExtractGroup2.UpdatePipelineInformation() - assert(ExtractGroup2.GetProperty("MeshName")[0]=="m2") - -if __name__ == "__main__": - test() diff --git a/src/Plugins/MEDReader/Test/tests.set b/src/Plugins/MEDReader/Test/tests.set deleted file mode 100644 index a8cb3e7c..00000000 --- a/src/Plugins/MEDReader/Test/tests.set +++ /dev/null @@ -1,32 +0,0 @@ -# Copyright (C) 2017-2019 CEA/DEN, EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# - -# This file declares a shared set of MEDREADER tests, used by two test -# approaches: "make test" and "salome test". The former is used just after -# MEDREADER build step, the latter is used from an installed SALOME application. -# -# We here initialize a cmake variable that is used, by file inclusion, in -# CMakeLists.txt (for make test) and CTestTestfileInstall.cmake (for salome -# test). -# This variables is: TEST_NUMBERS. -# Additional variables might be defined if necessary. - -# 11 and 12 have been willingly removed due to problem in image comparisons - -SET(TEST_NUMBERS 0 1 2 3 4 5 6 7 8 9 10 13 14 15 16 17 18 19 20 21) diff --git a/src/Plugins/MEDReader/plugin.cmake b/src/Plugins/MEDReader/plugin.cmake deleted file mode 100644 index db151042..00000000 --- a/src/Plugins/MEDReader/plugin.cmake +++ /dev/null @@ -1,5 +0,0 @@ -pv_plugin(MEDReader - # provide a description for the plugin. - DESCRIPTION "Reads the MED data format from Electricite de France" - PLUGIN_NAMES MEDReader - DEFAULT_ENABLED) diff --git a/src/Plugins/MEDReader/plugin/CMakeLists.txt b/src/Plugins/MEDReader/plugin/CMakeLists.txt new file mode 100644 index 00000000..ad1f1027 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/CMakeLists.txt @@ -0,0 +1,44 @@ +# Common CMake macros +# =================== +set(TMP_CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH}) +unset(CMAKE_MODULE_PATH) +set(CONFIGURATION_ROOT_DIR $ENV{CONFIGURATION_ROOT_DIR} CACHE PATH "Path to the Salome CMake configuration files") +if(EXISTS ${CONFIGURATION_ROOT_DIR}) + list(APPEND CMAKE_MODULE_PATH "${CONFIGURATION_ROOT_DIR}/cmake") + include(SalomeMacros) +else() + message(FATAL_ERROR "We absolutely need the Salome CMake configuration files, please define CONFIGURATION_ROOT_DIR !") +endif() + +set(MEDCOUPLING_ROOT_DIR $ENV{MEDCOUPLING_ROOT_DIR} CACHE PATH "Path to the MEDCoupling tool") +if(EXISTS ${MEDCOUPLING_ROOT_DIR}) + list(APPEND CMAKE_MODULE_PATH "${MEDCOUPLING_ROOT_DIR}/cmake_files") +endif() +list(APPEND CMAKE_MODULE_PATH "${CMAKE_ROOT}/Modules") +list(APPEND CMAKE_MODULE_PATH ${TMP_CMAKE_MODULE_PATH}) + +include(SalomeSetupPlatform) +set(BUILD_SHARED_LIBS TRUE) + +find_package(SalomePythonInterp REQUIRED) +find_package(SalomePythonLibs REQUIRED) +find_package(SalomeHDF5 REQUIRED) +find_package(SalomeMEDCoupling REQUIRED) +find_package(SalomeMEDFile REQUIRED) + +if(MEDCOUPLING_USE_64BIT_IDS) + add_definitions("-DMEDCOUPLING_USE_64BIT_IDS") +endif(MEDCOUPLING_USE_64BIT_IDS) + +SALOME_ACCUMULATE_ENVIRONMENT(PYTHONPATH NOCHECK ${CMAKE_INSTALL_PREFIX}/${SALOME_INSTALL_BINS} + ${CMAKE_INSTALL_PREFIX}/${SALOME_INSTALL_PYTHON}) +SALOME_ACCUMULATE_ENVIRONMENT(LD_LIBRARY_PATH NOCHECK ${CMAKE_INSTALL_PREFIX}/${SALOME_INSTALL_LIBS}) +SALOME_ACCUMULATE_ENVIRONMENT(PV_PLUGIN_PATH NOCHECK ${CMAKE_INSTALL_PREFIX}/lib/paraview) + +add_subdirectory(MEDLoaderForPV) +add_subdirectory(ParaViewPlugin) + +option(BUILD_TESTING "Build Plugin Testing" OFF) +if (BUILD_TESTING) + add_subdirectory(Test) +endif() diff --git a/src/Plugins/MEDReader/plugin/Doc/ELNO.txt b/src/Plugins/MEDReader/plugin/Doc/ELNO.txt new file mode 100644 index 00000000..456a2ea8 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/Doc/ELNO.txt @@ -0,0 +1,3 @@ +1- ELNO Points: creates points on the vertices of the cells, with a shrink factor which allows you to make the distinction between the vertices of the adjacent cells +2- ELNO Surface: this filters starts by extracting the surface of the object, then project the ELNO field on it, slightly separating the cells one from the others (10-5 shrink factor compared to cell initial size) +3- ELNO Mesh: all the cells of the initial mesh are separated one from the others to be able to project the ELNO fields on them. Beware not to use this filter on big calculation cases as the memory used and the graphical performances are degraded. This filter allows to make operations such as Cut Planes keeping the ELNO fields correct. diff --git a/src/Plugins/MEDReader/plugin/Doc/HowTo0.py b/src/Plugins/MEDReader/plugin/Doc/HowTo0.py new file mode 100644 index 00000000..b5213bf1 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/Doc/HowTo0.py @@ -0,0 +1,16 @@ +from paraview.simple import * + +myMedReader=MEDReader(FileName="/home/H87074/WORK/TESTS_AMA/TESTS0/ssll117a/ssll117a.med") + +# list of all keys + +keys=myMedReader.GetProperty("FieldsTreeInfo")[::2] + +# list all the names of arrays that can be seen (including their spatial discretization) + +arr_name_with_dis=[elt.split("/")[-1] for elt in keys] + +# list all the names of arrays (Equal to those in the MED File) + +arr_name=[elt.split(myMedReader.GetProperty("Separator").GetData())[0] for elt in arr_name_with_dis] + diff --git a/src/Plugins/MEDReader/plugin/MEDLoaderForPV/CMakeLists.txt b/src/Plugins/MEDReader/plugin/MEDLoaderForPV/CMakeLists.txt new file mode 100644 index 00000000..54dc38b7 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/MEDLoaderForPV/CMakeLists.txt @@ -0,0 +1,13 @@ +add_library(MEDLoaderForPV SHARED MEDFileFieldRepresentationTree.cxx MEDTimeReq.cxx MEDUtilities.cxx vtkGenerateVectors.cxx) +target_include_directories(MEDLoaderForPV PRIVATE . ${MEDCOUPLING_INCLUDE_DIRS}) + +target_link_libraries(MEDLoaderForPV VTK::CommonCore VTK::CommonDataModel VTK::IOXML ${MEDFILE_C_LIBRARIES}) + +IF(HDF5_IS_PARALLEL) + target_link_libraries(MEDLoaderForPV ${MEDCoupling_paramedloader}) +ELSE(HDF5_IS_PARALLEL) + TARGET_LINK_LIBRARIES(MEDLoaderForPV ${MEDCoupling_medloader}) +ENDIF(HDF5_IS_PARALLEL) + +install(TARGETS MEDLoaderForPV + DESTINATION lib/salome)#${CMAKE_INSTALL_LIBDIR} diff --git a/src/Plugins/MEDReader/plugin/MEDLoaderForPV/MEDFileFieldRepresentationTree.cxx b/src/Plugins/MEDReader/plugin/MEDLoaderForPV/MEDFileFieldRepresentationTree.cxx new file mode 100644 index 00000000..3a67b540 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/MEDLoaderForPV/MEDFileFieldRepresentationTree.cxx @@ -0,0 +1,1782 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay + +#include "MEDTimeReq.hxx" +#include "MEDUtilities.hxx" + +#include "MEDFileFieldRepresentationTree.hxx" +#include "MEDCouplingFieldDiscretization.hxx" +#include "MEDCouplingFieldDouble.hxx" +#include "InterpKernelGaussCoords.hxx" +#include "MEDFileData.hxx" +#include "SauvReader.hxx" +#include "MEDCouplingMemArray.txx" + +#ifdef MEDREADER_USE_MPI + #include "ParaMEDFileMesh.hxx" +#endif + +#include "vtkXMLUnstructuredGridWriter.h"// + +#include "vtkUnstructuredGrid.h" +#include "vtkRectilinearGrid.h" +#include "vtkStructuredGrid.h" +#include "vtkUnsignedCharArray.h" +#include "vtkQuadratureSchemeDefinition.h" +#include "vtkInformationQuadratureSchemeDefinitionVectorKey.h" +#include "vtkInformationIntegerKey.h" +#include "vtkInformation.h" +#include "vtkDataArrayTemplate.h" +#include "vtkIdTypeArray.h" +#include "vtkDoubleArray.h" +#include "vtkIntArray.h" +#include "vtkLongArray.h" +#ifdef WIN32 +#include "vtkLongLongArray.h" +#endif +#include "vtkFloatArray.h" +#include "vtkCellArray.h" +#include "vtkPointData.h" +#include "vtkFieldData.h" +#include "vtkCellData.h" + +#include "vtkMutableDirectedGraph.h" + +using namespace MEDCoupling; + +const char MEDFileFieldRepresentationLeavesArrays::ZE_SEP[]="@@][@@"; + +const char MEDFileFieldRepresentationLeavesArrays::TS_STR[]="TS"; + +const char MEDFileFieldRepresentationLeavesArrays::COM_SUP_STR[]="ComSup"; + +const char MEDFileFieldRepresentationLeavesArrays::FAMILY_ID_CELL_NAME[]="FamilyIdCell"; + +const char MEDFileFieldRepresentationLeavesArrays::NUM_ID_CELL_NAME[]="NumIdCell"; + +const char MEDFileFieldRepresentationLeavesArrays::FAMILY_ID_NODE_NAME[]="FamilyIdNode"; + +const char MEDFileFieldRepresentationLeavesArrays::NUM_ID_NODE_NAME[]="NumIdNode"; + +const char MEDFileFieldRepresentationLeavesArrays::GLOBAL_NODE_ID_NAME[]="GlobalNodeIds";// WARNING DO NOT CHANGE IT BEFORE HAVING CHECKED IN PV SOURCES ! + +const char MEDFileFieldRepresentationTree::ROOT_OF_GRPS_IN_TREE[]="zeGrps"; + +const char MEDFileFieldRepresentationTree::ROOT_OF_FAM_IDS_IN_TREE[]="zeFamIds"; + +const char MEDFileFieldRepresentationTree::COMPO_STR_TO_LOCATE_MESH_DA[]="-@?|*_"; + +template +vtkIdTypeArray *ELGACmp::findOrCreate(const MEDCoupling::MEDFileFieldGlobsReal *globs, const std::vector& locsReallyUsed, vtkDataArray *vtkd, vtkDataSet *ds, bool& isNew, ExportedTinyInfo *internalInfo) const +{ + vtkIdTypeArray *try0(isExisting(locsReallyUsed,vtkd)); + if(try0) + { + isNew=false; + return try0; + } + else + { + isNew=true; + return createNew(globs,locsReallyUsed,vtkd,ds,internalInfo); + } +} + +vtkIdTypeArray *ELGACmp::isExisting(const std::vector& locsReallyUsed, vtkDataArray *vtkd) const +{ + std::vector< std::vector >::iterator it(std::find(_loc_names.begin(),_loc_names.end(),locsReallyUsed)); + if(it==_loc_names.end()) + return 0; + std::size_t pos(std::distance(_loc_names.begin(),it)); + vtkIdTypeArray *ret(_elgas[pos]); + vtkInformationQuadratureSchemeDefinitionVectorKey *key(vtkQuadratureSchemeDefinition::DICTIONARY()); + for(std::vector >::const_iterator it=_defs[pos].begin();it!=_defs[pos].end();it++) + { + key->Set(vtkd->GetInformation(),(*it).first,(*it).second); + } + vtkd->GetInformation()->Set(vtkQuadratureSchemeDefinition::QUADRATURE_OFFSET_ARRAY_NAME(),ret->GetName()); + return ret; +} + +template +vtkIdTypeArray *ELGACmp::createNew(const MEDCoupling::MEDFileFieldGlobsReal *globs, const std::vector& locsReallyUsed, vtkDataArray *vtkd, vtkDataSet *ds, ExportedTinyInfo *internalInfo) const +{ + const int VTK_DATA_ARRAY_DELETE=vtkDataArrayTemplate::VTK_DATA_ARRAY_DELETE; + std::vector< std::vector > locNames(_loc_names); + std::vector elgas(_elgas); + std::vector< std::pair< vtkQuadratureSchemeDefinition *, unsigned char > > defs; + // + std::vector< std::vector >::const_iterator it(std::find(locNames.begin(),locNames.end(),locsReallyUsed)); + if(it!=locNames.end()) + throw INTERP_KERNEL::Exception("ELGACmp::createNew : Method is expected to be called after isExisting call ! Entry already exists !"); + locNames.push_back(locsReallyUsed); + vtkIdTypeArray *elga(vtkIdTypeArray::New()); + elga->SetNumberOfComponents(1); + vtkInformationQuadratureSchemeDefinitionVectorKey *key(vtkQuadratureSchemeDefinition::DICTIONARY()); + std::map m; + for(std::vector::const_iterator it=locsReallyUsed.begin();it!=locsReallyUsed.end();it++) + { + vtkQuadratureSchemeDefinition *def(vtkQuadratureSchemeDefinition::New()); + const MEDFileFieldLoc& loc(globs->getLocalization((*it).c_str())); + INTERP_KERNEL::NormalizedCellType ct(loc.getGeoType()); + unsigned char vtkType(MEDMeshMultiLev::PARAMEDMEM_2_VTKTYPE[ct]); + const INTERP_KERNEL::CellModel& cm(INTERP_KERNEL::CellModel::GetCellModel(ct)); + int nbGaussPt(loc.getNbOfGaussPtPerCell()),nbPtsPerCell((int)cm.getNumberOfNodes()),dimLoc(loc.getDimension()); + // WARNING : these 2 lines are a workaround, due to users that write a ref element with dimension not equal to dimension of the geometric element. + std::vector gsCoods2(INTERP_KERNEL::GaussInfo::NormalizeCoordinatesIfNecessary(ct,dimLoc,loc.getGaussCoords())); + std::vector refCoods2(INTERP_KERNEL::GaussInfo::NormalizeCoordinatesIfNecessary(ct,dimLoc,loc.getRefCoords())); + if(internalInfo) + internalInfo->pushGaussAdditionnalInfo(vtkType,dimLoc,refCoods2,gsCoods2); + double *shape(new double[nbPtsPerCell*nbGaussPt]); + INTERP_KERNEL::GaussInfo calculator(ct,gsCoods2,nbGaussPt,refCoods2,nbPtsPerCell); + calculator.initLocalInfo(); + const std::vector& wgths(loc.getGaussWeights()); + for(int i=0;iInitialize(vtkType,nbPtsPerCell,nbGaussPt,shape,const_cast(&wgths[0])); + delete [] shape; + key->Set(elga->GetInformation(),def,vtkType); + key->Set(vtkd->GetInformation(),def,vtkType); + defs.push_back(std::pair< vtkQuadratureSchemeDefinition *, unsigned char >(def,vtkType)); + } + // + vtkIdType ncell(ds->GetNumberOfCells()); + vtkIdType *pt(new vtkIdType[ncell]),offset(0); + for(vtkIdType cellId=0;cellIdGetCell(cellId)); + vtkIdType delta(m[(unsigned char)cell->GetCellType()]); + pt[cellId]=offset; + offset+=delta; + } + elga->GetInformation()->Set(MEDUtilities::ELGA(),1); + elga->SetVoidArray(pt,ncell,0,VTK_DATA_ARRAY_DELETE); + std::ostringstream oss; oss << "ELGA" << "@" << _loc_names.size(); + std::string ossStr(oss.str()); + elga->SetName(ossStr.c_str()); + elga->GetInformation()->Set(vtkAbstractArray::GUI_HIDE(),1); + vtkd->GetInformation()->Set(vtkQuadratureSchemeDefinition::QUADRATURE_OFFSET_ARRAY_NAME(),elga->GetName()); + elgas.push_back(elga); + // + _loc_names=locNames; + _elgas=elgas; + _defs.push_back(defs); + return elga; +} + +void ELGACmp::appendELGAIfAny(vtkDataSet *ds) const +{ + for(std::vector::const_iterator it=_elgas.begin();it!=_elgas.end();it++) + ds->GetCellData()->AddArray(*it); +} + +ELGACmp::~ELGACmp() +{ + for(std::vector::const_iterator it=_elgas.begin();it!=_elgas.end();it++) + (*it)->Delete(); + for(std::vector< std::vector< std::pair< vtkQuadratureSchemeDefinition *, unsigned char > > >::const_iterator it0=_defs.begin();it0!=_defs.end();it0++) + for(std::vector< std::pair< vtkQuadratureSchemeDefinition *, unsigned char > >::const_iterator it1=(*it0).begin();it1!=(*it0).end();it1++) + (*it1).first->Delete(); +} + +//= + +template +class MEDFileVTKTraits +{ +public: + typedef void VtkType; + typedef void MCType; +}; + +template<> +class MEDFileVTKTraits +{ +public: + typedef vtkIntArray VtkType; + typedef MEDCoupling::DataArrayInt MCType; +}; + +template<> +#ifdef WIN32 +class MEDFileVTKTraits +#else +class MEDFileVTKTraits +#endif +{ +public: +#ifdef WIN32 + typedef vtkLongLongArray VtkType; +#else + typedef vtkLongArray VtkType; +#endif + typedef MEDCoupling::DataArrayInt64 MCType; +}; + +template<> +class MEDFileVTKTraits +{ +public: + typedef vtkFloatArray VtkType; + typedef MEDCoupling::DataArrayFloat MCType; +}; + +template<> +class MEDFileVTKTraits +{ +public: + typedef vtkDoubleArray VtkType; + typedef MEDCoupling::DataArrayDouble MCType; +}; + +typedef typename MEDFileVTKTraits::VtkType vtkMCIdTypeArray; + + +template +void AssignDataPointerToVTK(typename MEDFileVTKTraits::VtkType *vtkTab, typename MEDFileVTKTraits::MCType *mcTab, bool noCpyNumNodes) +{ + if(noCpyNumNodes) + vtkTab->SetArray(mcTab->getPointer(),mcTab->getNbOfElems(),1,vtkDataArrayTemplate::VTK_DATA_ARRAY_FREE); + else + { vtkTab->SetArray(mcTab->getPointer(),mcTab->getNbOfElems(),0,vtkDataArrayTemplate::VTK_DATA_ARRAY_FREE); mcTab->accessToMemArray().setSpecificDeallocator(0); } +} + +// here copy is always assumed. +template +void AssignDataPointerOther(VTKT *vtkTab, MCT *mcTab, int nbElems) +{ + typedef typename VTKT::ValueType VTKType; + if ( sizeof( VTKType ) == sizeof( typename MCT::Type )) + { + vtkTab->SetVoidArray(reinterpret_cast(mcTab->getPointer()),nbElems,0,VTKT::VTK_DATA_ARRAY_FREE); + mcTab->accessToMemArray().setSpecificDeallocator(0); + } + else + { + VTKType* newArray = new VTKType[ nbElems ]; + std::copy( mcTab->begin(), mcTab->begin() + nbElems, newArray ); + vtkTab->SetVoidArray(reinterpret_cast(newArray),nbElems,0,VTKT::VTK_DATA_ARRAY_DELETE); + } +} + +template +void AssignToFieldData(DataArray *vPtr, const MEDTimeReq *tr, vtkFieldData *att, const std::string& crudeName, bool noCpyNumNodes, + const std::vector& discs, const ELGACmp& elgaCmp, const MEDCoupling::MEDFileFieldGlobsReal *globs, + MEDFileAnyTypeField1TS *f1ts, vtkDataSet *ds, ExportedTinyInfo *internalInfo) +{ + const int VTK_DATA_ARRAY_DELETE=vtkDataArrayTemplate::VTK_DATA_ARRAY_DELETE; + typename MEDFileVTKTraits::MCType *vi(static_cast::MCType *>(vPtr)); + typename MEDFileVTKTraits::VtkType *vtkd(MEDFileVTKTraits::VtkType::New()); + vtkd->SetNumberOfComponents((int)vi->getNumberOfComponents()); + for(unsigned int i=0;igetNumberOfComponents();i++) + vtkd->SetComponentName(i,vi->getVarOnComponent(i).c_str()); + AssignDataPointerToVTK(vtkd,vi,noCpyNumNodes); + std::string name(tr->buildName(crudeName)); + vtkd->SetName(name.c_str()); + att->AddArray(vtkd); + vtkd->Delete(); + if(discs[0]==ON_GAUSS_PT) + { + bool tmp; + elgaCmp.findOrCreate(globs,f1ts->getLocsReallyUsed(),vtkd,ds,tmp,internalInfo); + } + if(discs[0]==ON_GAUSS_NE) + { + vtkIdTypeArray *elno(vtkIdTypeArray::New()); + elno->SetNumberOfComponents(1); + vtkIdType ncell(ds->GetNumberOfCells()); + vtkIdType *pt(new vtkIdType[ncell]),offset(0); + std::set cellTypes; + for(vtkIdType cellId=0;cellIdGetCell(cellId)); + vtkIdType delta(cell->GetNumberOfPoints()); + cellTypes.insert(cell->GetCellType()); + pt[cellId]=offset; + offset+=delta; + } + elno->GetInformation()->Set(MEDUtilities::ELNO(),1); + elno->SetVoidArray(pt,ncell,0,VTK_DATA_ARRAY_DELETE); + std::string nameElno("ELNO"); nameElno+="@"; nameElno+=name; + elno->SetName(nameElno.c_str()); + ds->GetCellData()->AddArray(elno); + vtkd->GetInformation()->Set(vtkQuadratureSchemeDefinition::QUADRATURE_OFFSET_ARRAY_NAME(),elno->GetName()); + elno->GetInformation()->Set(vtkAbstractArray::GUI_HIDE(),1); + // + vtkInformationQuadratureSchemeDefinitionVectorKey *key(vtkQuadratureSchemeDefinition::DICTIONARY()); + for(std::set::const_iterator it=cellTypes.begin();it!=cellTypes.end();it++) + { + const unsigned char *pos(std::find(MEDMeshMultiLev::PARAMEDMEM_2_VTKTYPE,MEDMeshMultiLev::PARAMEDMEM_2_VTKTYPE+MEDMeshMultiLev::PARAMEDMEM_2_VTKTYPE_LGTH,*it)); + if(pos==MEDMeshMultiLev::PARAMEDMEM_2_VTKTYPE+MEDMeshMultiLev::PARAMEDMEM_2_VTKTYPE_LGTH) + continue; + INTERP_KERNEL::NormalizedCellType ct((INTERP_KERNEL::NormalizedCellType)std::distance(MEDMeshMultiLev::PARAMEDMEM_2_VTKTYPE,pos)); + const INTERP_KERNEL::CellModel& cm(INTERP_KERNEL::CellModel::GetCellModel(ct)); + int nbGaussPt(cm.getNumberOfNodes()),dim(cm.getDimension()); + vtkQuadratureSchemeDefinition *def(vtkQuadratureSchemeDefinition::New()); + double *shape(new double[nbGaussPt*nbGaussPt]); + std::size_t dummy; + const double *gsCoords(MEDCouplingFieldDiscretizationGaussNE::GetRefCoordsFromGeometricType(ct,dummy));//GetLocsFromGeometricType + const double *refCoords(MEDCouplingFieldDiscretizationGaussNE::GetRefCoordsFromGeometricType(ct,dummy)); + const double *weights(MEDCouplingFieldDiscretizationGaussNE::GetWeightArrayFromGeometricType(ct,dummy)); + std::vector gsCoords2(gsCoords,gsCoords+nbGaussPt*dim),refCoords2(refCoords,refCoords+nbGaussPt*dim); + INTERP_KERNEL::GaussInfo calculator(ct,gsCoords2,nbGaussPt,refCoords2,nbGaussPt); + calculator.initLocalInfo(); + for(int i=0;iInitialize(*it,nbGaussPt,nbGaussPt,shape,const_cast(weights)); + delete [] shape; + key->Set(elno->GetInformation(),def,*it); + key->Set(vtkd->GetInformation(),def,*it); + def->Delete(); + } + // + elno->Delete(); + } +} + +//= + +MEDFileFieldRepresentationLeavesArrays::MEDFileFieldRepresentationLeavesArrays():_id(-1) +{ +} + +MEDFileFieldRepresentationLeavesArrays::MEDFileFieldRepresentationLeavesArrays(const MEDCoupling::MCAuto& arr):MEDCoupling::MCAuto(arr),_activated(false),_id(-1) +{ + std::vector< std::vector > typs((operator->())->getTypesOfFieldAvailable()); + if(typs.size()<1) + throw INTERP_KERNEL::Exception("There is a big internal problem in MEDLoader ! The field time spitting has failed ! A CRASH will occur soon !"); + if(typs[0].size()!=1) + throw INTERP_KERNEL::Exception("There is a big internal problem in MEDLoader ! The field spitting by spatial discretization has failed ! A CRASH will occur soon !"); + MEDCoupling::MCAuto fd(MEDCouplingFieldDiscretization::New(typs[0][0])); + std::ostringstream oss2; oss2 << (operator->())->getName() << ZE_SEP << fd->getRepr(); + _ze_name=oss2.str(); +} + +MEDFileFieldRepresentationLeavesArrays& MEDFileFieldRepresentationLeavesArrays::operator=(const MEDFileFieldRepresentationLeavesArrays& other) +{ + MEDCoupling::MCAuto::operator=(other); + _id=-1; + _activated=false; + _ze_name=other._ze_name; + _ze_full_name.clear(); + return *this; +} + +void MEDFileFieldRepresentationLeavesArrays::setId(int& id) const +{ + _id=id++; +} + +int MEDFileFieldRepresentationLeavesArrays::getId() const +{ + return _id; +} + +std::string MEDFileFieldRepresentationLeavesArrays::getZeName() const +{ + return _ze_full_name; +} + +const char *MEDFileFieldRepresentationLeavesArrays::getZeNameC() const +{ + return _ze_full_name.c_str(); +} + +void MEDFileFieldRepresentationLeavesArrays::feedSIL(vtkMutableDirectedGraph* sil, vtkIdType root, vtkVariantArray *edge, std::vector& names) const +{ + vtkIdType refId(sil->AddChild(root,edge)); + names.push_back(_ze_name); + // + if(MEDFileFieldRepresentationTree::IsFieldMeshRegardingInfo(((operator->())->getInfo()))) + { + sil->AddChild(refId,edge); + names.push_back(std::string()); + } +} + +void MEDFileFieldRepresentationLeavesArrays::computeFullNameInLeaves(const std::string& tsName, const std::string& meshName, const std::string& comSupStr) const +{ + std::ostringstream oss3; oss3 << tsName << "/" << meshName << "/" << comSupStr << "/" << _ze_name; + _ze_full_name=oss3.str(); +} + +bool MEDFileFieldRepresentationLeavesArrays::getStatus() const +{ + return _activated; +} + +bool MEDFileFieldRepresentationLeavesArrays::setStatus(bool status) const +{ + bool ret(_activated!=status); + _activated=status; + return ret; +} + +void MEDFileFieldRepresentationLeavesArrays::appendFields(const MEDTimeReq *tr, const MEDCoupling::MEDFileFieldGlobsReal *globs, const MEDCoupling::MEDMeshMultiLev *mml, const MEDCoupling::MEDFileMeshStruct *mst, vtkDataSet *ds, ExportedTinyInfo *internalInfo) const +{ + const int VTK_DATA_ARRAY_DELETE=vtkDataArrayTemplate::VTK_DATA_ARRAY_DELETE; + tr->setNumberOfTS((operator->())->getNumberOfTS()); + tr->initIterator(); + for(int timeStepId=0;timeStepIdsize();timeStepId++,++(*tr)) + { + MCAuto f1ts((operator->())->getTimeStepAtPos(tr->getCurrent())); + MEDFileAnyTypeField1TS *f1tsPtr(f1ts); + MEDFileField1TS *f1tsPtrDbl(dynamic_cast(f1tsPtr)); + MEDFileIntField1TS *f1tsPtrInt(dynamic_cast(f1tsPtr)); + MEDFileFloatField1TS *f1tsPtrFloat(dynamic_cast(f1tsPtr)); + DataArray *crudeArr(0),*postProcessedArr(0); + if(f1tsPtrDbl) + crudeArr=f1tsPtrDbl->getUndergroundDataArray(); + else if(f1tsPtrInt) + crudeArr=f1tsPtrInt->getUndergroundDataArray(); + else if(f1tsPtrFloat) + crudeArr=f1tsPtrFloat->getUndergroundDataArray(); + else + throw INTERP_KERNEL::Exception("MEDFileFieldRepresentationLeavesArrays::appendFields : only FLOAT64, FLOAT32 and INT32 fields are dealt for the moment !"); + MEDFileField1TSStructItem fsst(MEDFileField1TSStructItem::BuildItemFrom(f1ts,mst)); + f1ts->loadArraysIfNecessary(); + MCAuto v(mml->buildDataArray(fsst,globs,crudeArr)); + postProcessedArr=v; + // + std::vector discs(f1ts->getTypesOfFieldAvailable()); + if(discs.size()!=1) + throw INTERP_KERNEL::Exception("MEDFileFieldRepresentationLeavesArrays::appendFields : internal error ! Number of spatial discretizations must be equal to one !"); + vtkFieldData *att(0); + switch(discs[0]) + { + case ON_CELLS: + { + att=ds->GetCellData(); + break; + } + case ON_NODES: + { + att=ds->GetPointData(); + break; + } + case ON_GAUSS_NE: + { + att=ds->GetFieldData(); + break; + } + case ON_GAUSS_PT: + { + att=ds->GetFieldData(); + break; + } + default: + throw INTERP_KERNEL::Exception("MEDFileFieldRepresentationLeavesArrays::appendFields : only CELL and NODE, GAUSS_NE and GAUSS fields are available for the moment !"); + } + if(f1tsPtrDbl) + { + AssignToFieldData(v,tr,att,f1ts->getName(),postProcessedArr==crudeArr,discs,_elga_cmp,globs,f1ts,ds,internalInfo); + } + else if(f1tsPtrInt) + { + AssignToFieldData(v,tr,att,f1ts->getName(),postProcessedArr==crudeArr,discs,_elga_cmp,globs,f1ts,ds,internalInfo); + } + else if(f1tsPtrFloat) + { + AssignToFieldData(v,tr,att,f1ts->getName(),postProcessedArr==crudeArr,discs,_elga_cmp,globs,f1ts,ds,internalInfo); + } + else + throw INTERP_KERNEL::Exception("MEDFileFieldRepresentationLeavesArrays::appendFields : only FLOAT64 and INT32 fields are dealt for the moment ! Internal Error !"); + } +} + +void MEDFileFieldRepresentationLeavesArrays::appendELGAIfAny(vtkDataSet *ds) const +{ + _elga_cmp.appendELGAIfAny(ds); +} + +//////////////////// + +MEDFileFieldRepresentationLeaves::MEDFileFieldRepresentationLeaves():_cached_ds(0) +{ +} + +MEDFileFieldRepresentationLeaves::MEDFileFieldRepresentationLeaves(const std::vector< MEDCoupling::MCAuto >& arr, + const MEDCoupling::MCAuto& fsp):_arrays(arr.size()),_fsp(fsp),_cached_ds(0) +{ + for(std::size_t i=0;iDelete(); +} + +bool MEDFileFieldRepresentationLeaves::empty() const +{ + const MEDFileFastCellSupportComparator *fcscp(_fsp); + return fcscp==0 || _arrays.empty(); +} + +void MEDFileFieldRepresentationLeaves::setId(int& id) const +{ + for(std::vector::const_iterator it=_arrays.begin();it!=_arrays.end();it++) + (*it).setId(id); +} + +std::string MEDFileFieldRepresentationLeaves::getMeshName() const +{ + return _arrays[0]->getMeshName(); +} + +int MEDFileFieldRepresentationLeaves::getNumberOfArrays() const +{ + return (int)_arrays.size(); +} + +int MEDFileFieldRepresentationLeaves::getNumberOfTS() const +{ + return _arrays[0]->getNumberOfTS(); +} + +void MEDFileFieldRepresentationLeaves::computeFullNameInLeaves(const std::string& tsName, const std::string& meshName, const std::string& comSupStr) const +{ + for(std::vector::const_iterator it=_arrays.begin();it!=_arrays.end();it++) + (*it).computeFullNameInLeaves(tsName,meshName,comSupStr); +} + +/*! + * \param [in] ms is the meshes pointer. It can be used only for information of geometric types. No special processing will be requested on ms. + */ +void MEDFileFieldRepresentationLeaves::feedSIL(const MEDCoupling::MEDFileMeshes *ms, const std::string& meshName, vtkMutableDirectedGraph* sil, vtkIdType root, vtkVariantArray *edge, std::vector& names) const +{ + vtkIdType root2(sil->AddChild(root,edge)); + names.push_back(std::string("Arrs")); + for(std::vector::const_iterator it=_arrays.begin();it!=_arrays.end();it++) + (*it).feedSIL(sil,root2,edge,names); + // + vtkIdType root3(sil->AddChild(root,edge)); + names.push_back(std::string("InfoOnGeoType")); + const MEDCoupling::MEDFileMesh *m(0); + if(ms) + m=ms->getMeshWithName(meshName); + const MEDCoupling::MEDFileFastCellSupportComparator *fsp(_fsp); + if(!fsp || fsp->getNumberOfTS()==0) + return ; + std::vector< INTERP_KERNEL::NormalizedCellType > gts(fsp->getGeoTypesAt(0,m)); + for(std::vector< INTERP_KERNEL::NormalizedCellType >::const_iterator it2=gts.begin();it2!=gts.end();it2++) + { + const INTERP_KERNEL::CellModel& cm(INTERP_KERNEL::CellModel::GetCellModel(*it2)); + std::string cmStr(cm.getRepr()); cmStr=cmStr.substr(5);//skip "NORM_" + sil->AddChild(root3,edge); + names.push_back(cmStr); + } +} + +bool MEDFileFieldRepresentationLeaves::containId(int id) const +{ + for(std::vector::const_iterator it=_arrays.begin();it!=_arrays.end();it++) + if((*it).getId()==id) + return true; + return false; +} + +bool MEDFileFieldRepresentationLeaves::containZeName(const char *name, int& id) const +{ + for(std::vector::const_iterator it=_arrays.begin();it!=_arrays.end();it++) + if((*it).getZeName()==name) + { + id=(*it).getId(); + return true; + } + return false; +} + +void MEDFileFieldRepresentationLeaves::dumpState(std::map& status) const +{ + for(std::vector::const_iterator it=_arrays.begin();it!=_arrays.end();it++) + status[(*it).getZeName()]=(*it).getStatus(); +} + +bool MEDFileFieldRepresentationLeaves::isActivated() const +{ + for(std::vector::const_iterator it=_arrays.begin();it!=_arrays.end();it++) + if((*it).getStatus()) + return true; + return false; +} + +void MEDFileFieldRepresentationLeaves::printMySelf(std::ostream& os) const +{ + for(std::vector::const_iterator it0=_arrays.begin();it0!=_arrays.end();it0++) + { + os << " - " << (*it0).getZeName() << " ("; + if((*it0).getStatus()) + os << "X"; + else + os << " "; + os << ")" << std::endl; + } +} + +void MEDFileFieldRepresentationLeaves::activateAllArrays() const +{ + for(std::vector::const_iterator it=_arrays.begin();it!=_arrays.end();it++) + (*it).setStatus(true); +} + +const MEDFileFieldRepresentationLeavesArrays& MEDFileFieldRepresentationLeaves::getLeafArr(int id) const +{ + for(std::vector::const_iterator it=_arrays.begin();it!=_arrays.end();it++) + if((*it).getId()==id) + return *it; + throw INTERP_KERNEL::Exception("MEDFileFieldRepresentationLeaves::getLeafArr ! No such id !"); +} + +std::vector MEDFileFieldRepresentationLeaves::getTimeSteps(const TimeKeeper& tk) const +{ + if(_arrays.size()<1) + throw INTERP_KERNEL::Exception("MEDFileFieldRepresentationLeaves::getTimeSteps : the array size must be at least of size one !"); + std::vector ret; + std::vector< std::pair > dtits(_arrays[0]->getTimeSteps(ret)); + return tk.getTimeStepsRegardingPolicy(dtits,ret); +} + +std::vector< std::pair > MEDFileFieldRepresentationLeaves::getTimeStepsInCoarseMEDFileFormat(std::vector& ts) const +{ + if(!_arrays.empty()) + return _arrays[0]->getTimeSteps(ts); + else + { + ts.clear(); + return std::vector< std::pair >(); + } +} + +std::string MEDFileFieldRepresentationLeaves::getHumanReadableOverviewOfTS() const +{ + std::ostringstream oss; + oss << _arrays[0]->getNumberOfTS() << " time steps [" << _arrays[0]->getDtUnit() << "]\n("; + std::vector ret1; + std::vector< std::pair > ret2(getTimeStepsInCoarseMEDFileFormat(ret1)); + std::size_t sz(ret1.size()); + for(std::size_t i=0;i200 && i!=sz-1) + { + oss << "..."; + break; + } + } + oss << ")"; + return oss.str(); +} + +void MEDFileFieldRepresentationLeaves::appendFields(const MEDTimeReq *tr, const MEDCoupling::MEDFileFieldGlobsReal *globs, const MEDCoupling::MEDMeshMultiLev *mml, const MEDCoupling::MEDFileMeshes *meshes, vtkDataSet *ds, ExportedTinyInfo *internalInfo) const +{ + if(_arrays.size()<1) + throw INTERP_KERNEL::Exception("MEDFileFieldRepresentationLeaves::appendFields : internal error !"); + MCAuto mst(MEDFileMeshStruct::New(meshes->getMeshWithName(_arrays[0]->getMeshName().c_str()))); + for(std::vector::const_iterator it=_arrays.begin();it!=_arrays.end();it++) + if((*it).getStatus()) + { + (*it).appendFields(tr,globs,mml,mst,ds,internalInfo); + (*it).appendELGAIfAny(ds); + } +} + +vtkUnstructuredGrid *MEDFileFieldRepresentationLeaves::buildVTKInstanceNoTimeInterpolationUnstructured(MEDUMeshMultiLev *mm) const +{ + DataArrayDouble *coordsMC(0); + DataArrayByte *typesMC(0); + DataArrayIdType *cellLocationsMC(0),*cellsMC(0),*faceLocationsMC(0),*facesMC(0); + bool statusOfCoords(mm->buildVTUArrays(coordsMC,typesMC,cellLocationsMC,cellsMC,faceLocationsMC,facesMC)); + MCAuto coordsSafe(coordsMC); + MCAuto typesSafe(typesMC); + MCAuto cellLocationsSafe(cellLocationsMC),cellsSafe(cellsMC),faceLocationsSafe(faceLocationsMC),facesSafe(facesMC); + // + int nbOfCells(typesSafe->getNbOfElems()); + vtkUnstructuredGrid *ret(vtkUnstructuredGrid::New()); + vtkUnsignedCharArray *cellTypes(vtkUnsignedCharArray::New()); + AssignDataPointerOther(cellTypes,typesSafe,nbOfCells); + vtkIdTypeArray *cellLocations(vtkIdTypeArray::New()); + AssignDataPointerOther(cellLocations,cellLocationsSafe,nbOfCells); + vtkCellArray *cells(vtkCellArray::New()); + vtkIdTypeArray *cells2(vtkIdTypeArray::New()); + AssignDataPointerOther(cells2,cellsSafe,cellsSafe->getNbOfElems()); + cells->SetCells(nbOfCells,cells2); + cells2->Delete(); + if(faceLocationsMC!=0 && facesMC!=0) + { + vtkIdTypeArray *faces(vtkIdTypeArray::New()); + AssignDataPointerOther(faces,facesSafe,facesSafe->getNbOfElems()); + vtkIdTypeArray *faceLocations(vtkIdTypeArray::New()); + AssignDataPointerOther(faceLocations,faceLocationsSafe,faceLocationsSafe->getNbOfElems()); + ret->SetCells(cellTypes,cellLocations,cells,faceLocations,faces); + faceLocations->Delete(); + faces->Delete(); + } + else + ret->SetCells(cellTypes,cellLocations,cells); + cellTypes->Delete(); + cellLocations->Delete(); + cells->Delete(); + vtkPoints *pts(vtkPoints::New()); + vtkDoubleArray *pts2(vtkDoubleArray::New()); + pts2->SetNumberOfComponents(3); + AssignDataPointerToVTK(pts2,coordsSafe,statusOfCoords); + pts->SetData(pts2); + pts2->Delete(); + ret->SetPoints(pts); + pts->Delete(); + // + return ret; +} + +vtkRectilinearGrid *MEDFileFieldRepresentationLeaves::buildVTKInstanceNoTimeInterpolationCartesian(MEDCoupling::MEDCMeshMultiLev *mm) const +{ + bool isInternal; + std::vector< DataArrayDouble * > arrs(mm->buildVTUArrays(isInternal)); + vtkDoubleArray *vtkTmp(0); + vtkRectilinearGrid *ret(vtkRectilinearGrid::New()); + std::size_t dim(arrs.size()); + if(dim<1 || dim>3) + throw INTERP_KERNEL::Exception("buildVTKInstanceNoTimeInterpolationCartesian : dimension must be in [1,3] !"); + int sizePerAxe[3]={1,1,1}; + sizePerAxe[0]=arrs[0]->getNbOfElems(); + if(dim>=2) + sizePerAxe[1]=arrs[1]->getNbOfElems(); + if(dim==3) + sizePerAxe[2]=arrs[2]->getNbOfElems(); + ret->SetDimensions(sizePerAxe[0],sizePerAxe[1],sizePerAxe[2]); + vtkTmp=vtkDoubleArray::New(); + vtkTmp->SetNumberOfComponents(1); + AssignDataPointerToVTK(vtkTmp,arrs[0],isInternal); + ret->SetXCoordinates(vtkTmp); + vtkTmp->Delete(); + arrs[0]->decrRef(); + if(dim>=2) + { + vtkTmp=vtkDoubleArray::New(); + vtkTmp->SetNumberOfComponents(1); + AssignDataPointerToVTK(vtkTmp,arrs[1],isInternal); + ret->SetYCoordinates(vtkTmp); + vtkTmp->Delete(); + arrs[1]->decrRef(); + } + if(dim==3) + { + vtkTmp=vtkDoubleArray::New(); + vtkTmp->SetNumberOfComponents(1); + AssignDataPointerToVTK(vtkTmp,arrs[2],isInternal); + ret->SetZCoordinates(vtkTmp); + vtkTmp->Delete(); + arrs[2]->decrRef(); + } + return ret; +} + +vtkStructuredGrid *MEDFileFieldRepresentationLeaves::buildVTKInstanceNoTimeInterpolationCurveLinear(MEDCoupling::MEDCurveLinearMeshMultiLev *mm) const +{ + int meshStr[3]={1,1,1}; + DataArrayDouble *coords(0); + std::vector nodeStrct; + bool isInternal; + mm->buildVTUArrays(coords,nodeStrct,isInternal); + std::size_t dim(nodeStrct.size()); + if(dim<1 || dim>3) + throw INTERP_KERNEL::Exception("buildVTKInstanceNoTimeInterpolationCurveLinear : dimension must be in [1,3] !"); + meshStr[0]=nodeStrct[0]; + if(dim>=2) + meshStr[1]=nodeStrct[1]; + if(dim==3) + meshStr[2]=nodeStrct[2]; + vtkStructuredGrid *ret(vtkStructuredGrid::New()); + ret->SetDimensions(meshStr[0],meshStr[1],meshStr[2]); + vtkDoubleArray *da(vtkDoubleArray::New()); + da->SetNumberOfComponents(3); + if(coords->getNumberOfComponents()==3) + AssignDataPointerToVTK(da,coords,isInternal);//if isIntenal==True VTK has not the ownership of double * because MEDLoader main struct has it ! + else + { + MCAuto coords2(coords->changeNbOfComponents(3,0.)); + AssignDataPointerToVTK(da,coords2,false);//let VTK deal with double * + } + coords->decrRef(); + vtkPoints *points=vtkPoints::New(); + ret->SetPoints(points); + points->SetData(da); + points->Delete(); + da->Delete(); + return ret; +} + +vtkDataSet *MEDFileFieldRepresentationLeaves::buildVTKInstanceNoTimeInterpolation(const MEDTimeReq *tr, const MEDFileFieldGlobsReal *globs, const MEDCoupling::MEDFileMeshes *meshes, ExportedTinyInfo *internalInfo) const +{ + vtkDataSet *ret(0); + //_fsp->isDataSetSupportEqualToThePreviousOne(i,globs); + MCAuto mml(_fsp->buildFromScratchDataSetSupport(0,globs));//0=timestep Id. Make the hypothesis that support does not change + MCAuto mml2(mml->prepare()); + MEDMeshMultiLev *ptMML2(mml2); + if(!_cached_ds) + { + MEDUMeshMultiLev *ptUMML2(dynamic_cast(ptMML2)); + MEDCMeshMultiLev *ptCMML2(dynamic_cast(ptMML2)); + MEDCurveLinearMeshMultiLev *ptCLMML2(dynamic_cast(ptMML2)); + + if(ptUMML2) + { + ret=buildVTKInstanceNoTimeInterpolationUnstructured(ptUMML2); + } + else if(ptCMML2) + { + ret=buildVTKInstanceNoTimeInterpolationCartesian(ptCMML2); + } + else if(ptCLMML2) + { + ret=buildVTKInstanceNoTimeInterpolationCurveLinear(ptCLMML2); + } + else + throw INTERP_KERNEL::Exception("MEDFileFieldRepresentationLeaves::buildVTKInstanceNoTimeInterpolation : unrecognized mesh ! Supported for the moment unstructured, cartesian, curvelinear !"); + _cached_ds=ret->NewInstance(); + _cached_ds->ShallowCopy(ret); + } + else + { + ret=_cached_ds->NewInstance(); + ret->ShallowCopy(_cached_ds); + } + // + appendFields(tr,globs,mml,meshes,ret,internalInfo); + // The arrays links to mesh + DataArrayIdType *famCells(0),*numCells(0); + bool noCpyFamCells(false),noCpyNumCells(false); + ptMML2->retrieveFamilyIdsOnCells(famCells,noCpyFamCells); + if(famCells) + { + vtkMCIdTypeArray *vtkTab(vtkMCIdTypeArray::New()); + vtkTab->SetNumberOfComponents(1); + vtkTab->SetName(MEDFileFieldRepresentationLeavesArrays::FAMILY_ID_CELL_NAME); + AssignDataPointerToVTK(vtkTab,famCells,noCpyFamCells); + ret->GetCellData()->AddArray(vtkTab); + vtkTab->Delete(); + famCells->decrRef(); + } + ptMML2->retrieveNumberIdsOnCells(numCells,noCpyNumCells); + if(numCells) + { + vtkMCIdTypeArray *vtkTab(vtkMCIdTypeArray::New()); + vtkTab->SetNumberOfComponents(1); + vtkTab->SetName(MEDFileFieldRepresentationLeavesArrays::NUM_ID_CELL_NAME); + AssignDataPointerToVTK(vtkTab,numCells,noCpyNumCells); + ret->GetCellData()->AddArray(vtkTab); + vtkTab->Delete(); + numCells->decrRef(); + } + // The arrays links to mesh + DataArrayIdType *famNodes(0),*numNodes(0); + bool noCpyFamNodes(false),noCpyNumNodes(false); + ptMML2->retrieveFamilyIdsOnNodes(famNodes,noCpyFamNodes); + if(famNodes) + { + vtkMCIdTypeArray *vtkTab(vtkMCIdTypeArray::New()); + vtkTab->SetNumberOfComponents(1); + vtkTab->SetName(MEDFileFieldRepresentationLeavesArrays::FAMILY_ID_NODE_NAME); + AssignDataPointerToVTK(vtkTab,famNodes,noCpyFamNodes); + ret->GetPointData()->AddArray(vtkTab); + vtkTab->Delete(); + famNodes->decrRef(); + } + ptMML2->retrieveNumberIdsOnNodes(numNodes,noCpyNumNodes); + if(numNodes) + { + vtkMCIdTypeArray *vtkTab(vtkMCIdTypeArray::New()); + vtkTab->SetNumberOfComponents(1); + vtkTab->SetName(MEDFileFieldRepresentationLeavesArrays::NUM_ID_NODE_NAME); + AssignDataPointerToVTK(vtkTab,numNodes,noCpyNumNodes); + ret->GetPointData()->AddArray(vtkTab); + vtkTab->Delete(); + numNodes->decrRef(); + } + // Global Node Ids if any ! (In // mode) + DataArrayIdType *gni(ptMML2->retrieveGlobalNodeIdsIfAny()); + if(gni) + { + vtkMCIdTypeArray *vtkTab(vtkMCIdTypeArray::New()); + vtkTab->SetNumberOfComponents(1); + vtkTab->SetName(MEDFileFieldRepresentationLeavesArrays::GLOBAL_NODE_ID_NAME); + AssignDataPointerToVTK(vtkTab,gni,false); + ret->GetPointData()->AddArray(vtkTab); + vtkTab->Delete(); + gni->decrRef(); + } + return ret; +} + +////////////////////// + +MEDFileFieldRepresentationTree::MEDFileFieldRepresentationTree() +{ +} + +int MEDFileFieldRepresentationTree::getNumberOfLeavesArrays() const +{ + int ret(0); + for(std::vector< std::vector< std::vector< MEDFileFieldRepresentationLeaves > > >::const_iterator it0=_data_structure.begin();it0!=_data_structure.end();it0++) + for(std::vector< std::vector< MEDFileFieldRepresentationLeaves > >::const_iterator it1=(*it0).begin();it1!=(*it0).end();it1++) + for(std::vector< MEDFileFieldRepresentationLeaves >::const_iterator it2=(*it1).begin();it2!=(*it1).end();it2++) + ret+=(*it2).getNumberOfArrays(); + return ret; +} + +void MEDFileFieldRepresentationTree::assignIds() const +{ + int zeId(0); + for(std::vector< std::vector< std::vector< MEDFileFieldRepresentationLeaves > > >::const_iterator it0=_data_structure.begin();it0!=_data_structure.end();it0++) + for(std::vector< std::vector< MEDFileFieldRepresentationLeaves > >::const_iterator it1=(*it0).begin();it1!=(*it0).end();it1++) + for(std::vector< MEDFileFieldRepresentationLeaves >::const_iterator it2=(*it1).begin();it2!=(*it1).end();it2++) + (*it2).setId(zeId); +} + +void MEDFileFieldRepresentationTree::computeFullNameInLeaves() const +{ + std::size_t it0Cnt(0); + for(std::vector< std::vector< std::vector< MEDFileFieldRepresentationLeaves > > >::const_iterator it0=_data_structure.begin();it0!=_data_structure.end();it0++,it0Cnt++) + { + std::ostringstream oss; oss << MEDFileFieldRepresentationLeavesArrays::TS_STR << it0Cnt; + std::string tsName(oss.str()); + for(std::vector< std::vector< MEDFileFieldRepresentationLeaves > >::const_iterator it1=(*it0).begin();it1!=(*it0).end();it1++) + { + std::string meshName((*it1)[0].getMeshName()); + std::size_t it2Cnt(0); + for(std::vector< MEDFileFieldRepresentationLeaves >::const_iterator it2=(*it1).begin();it2!=(*it1).end();it2++,it2Cnt++) + { + std::ostringstream oss2; oss2 << MEDFileFieldRepresentationLeavesArrays::COM_SUP_STR << it2Cnt; + std::string comSupStr(oss2.str()); + (*it2).computeFullNameInLeaves(tsName,meshName,comSupStr); + } + } + } +} + +void MEDFileFieldRepresentationTree::activateTheFirst() const +{ + for(std::vector< std::vector< std::vector< MEDFileFieldRepresentationLeaves > > >::const_iterator it0=_data_structure.begin();it0!=_data_structure.end();it0++) + for(std::vector< std::vector< MEDFileFieldRepresentationLeaves > >::const_iterator it1=(*it0).begin();it1!=(*it0).end();it1++) + for(std::vector< MEDFileFieldRepresentationLeaves >::const_iterator it2=(*it1).begin();it2!=(*it1).end();it2++) + { + (*it2).activateAllArrays(); + return ; + } +} + +void MEDFileFieldRepresentationTree::feedSIL(vtkMutableDirectedGraph* sil, vtkIdType root, vtkVariantArray *edge, std::vector& names) const +{ + std::size_t it0Cnt(0); + for(std::vector< std::vector< std::vector< MEDFileFieldRepresentationLeaves > > >::const_iterator it0=_data_structure.begin();it0!=_data_structure.end();it0++,it0Cnt++) + { + vtkIdType InfoOnTSId(sil->AddChild(root,edge)); + names.push_back((*it0)[0][0].getHumanReadableOverviewOfTS()); + // + vtkIdType NbOfTSId(sil->AddChild(InfoOnTSId,edge)); + std::vector ts; + std::vector< std::pair > dtits((*it0)[0][0].getTimeStepsInCoarseMEDFileFormat(ts)); + std::size_t nbOfTS(dtits.size()); + std::ostringstream oss3; oss3 << nbOfTS; + names.push_back(oss3.str()); + for(std::size_t i=0;iAddChild(NbOfTSId,edge)); + names.push_back(oss4.str()); + std::ostringstream oss5; oss5 << dtits[i].second; + vtkIdType ItId(sil->AddChild(DtId,edge)); + names.push_back(oss5.str()); + std::ostringstream oss6; oss6 << ts[i]; + sil->AddChild(ItId,edge); + names.push_back(oss6.str()); + } + // + std::ostringstream oss; oss << MEDFileFieldRepresentationLeavesArrays::TS_STR << it0Cnt; + std::string tsName(oss.str()); + vtkIdType typeId0(sil->AddChild(root,edge)); + names.push_back(tsName); + for(std::vector< std::vector< MEDFileFieldRepresentationLeaves > >::const_iterator it1=(*it0).begin();it1!=(*it0).end();it1++) + { + std::string meshName((*it1)[0].getMeshName()); + vtkIdType typeId1(sil->AddChild(typeId0,edge)); + names.push_back(meshName); + std::size_t it2Cnt(0); + for(std::vector< MEDFileFieldRepresentationLeaves >::const_iterator it2=(*it1).begin();it2!=(*it1).end();it2++,it2Cnt++) + { + std::ostringstream oss2; oss2 << MEDFileFieldRepresentationLeavesArrays::COM_SUP_STR << it2Cnt; + std::string comSupStr(oss2.str()); + vtkIdType typeId2(sil->AddChild(typeId1,edge)); + names.push_back(comSupStr); + (*it2).feedSIL(_ms,meshName,sil,typeId2,edge,names); + } + } + } +} + +std::string MEDFileFieldRepresentationTree::getActiveMeshName() const +{ + int dummy0(0),dummy1(0),dummy2(0); + const MEDFileFieldRepresentationLeaves& leaf(getTheSingleActivated(dummy0,dummy1,dummy2)); + return leaf.getMeshName(); +} + +std::string MEDFileFieldRepresentationTree::feedSILForFamsAndGrps(vtkMutableDirectedGraph* sil, vtkIdType root, vtkVariantArray *edge, std::vector& names) const +{ + int dummy0(0),dummy1(0),dummy2(0); + const MEDFileFieldRepresentationLeaves& leaf(getTheSingleActivated(dummy0,dummy1,dummy2)); + std::string ret(leaf.getMeshName()); + int i(0); + MEDFileMesh *m(0); + for(;i<_ms->getNumberOfMeshes();i++) + { + m=_ms->getMeshAtPos(i); + if(m->getName()==ret) + break; + } + if(i==_ms->getNumberOfMeshes()) + throw INTERP_KERNEL::Exception("MEDFileFieldRepresentationTree::feedSILForFamsAndGrps : internal error #0 !"); + vtkIdType typeId0(sil->AddChild(root,edge)); + names.push_back(m->getName()); + // + vtkIdType typeId1(sil->AddChild(typeId0,edge)); + names.push_back(std::string(ROOT_OF_GRPS_IN_TREE)); + std::vector grps(m->getGroupsNames()); + for(std::vector::const_iterator it0=grps.begin();it0!=grps.end();it0++) + { + vtkIdType typeId2(sil->AddChild(typeId1,edge)); + names.push_back(*it0); + std::vector famsOnGrp(m->getFamiliesOnGroup((*it0).c_str())); + for(std::vector::const_iterator it1=famsOnGrp.begin();it1!=famsOnGrp.end();it1++) + { + sil->AddChild(typeId2,edge); + names.push_back((*it1).c_str()); + } + } + // + vtkIdType typeId11(sil->AddChild(typeId0,edge)); + names.push_back(std::string(ROOT_OF_FAM_IDS_IN_TREE)); + std::vector fams(m->getFamiliesNames()); + for(std::vector::const_iterator it00=fams.begin();it00!=fams.end();it00++) + { + sil->AddChild(typeId11,edge); + int famId(m->getFamilyId((*it00).c_str())); + std::ostringstream oss; oss << (*it00) << MEDFileFieldRepresentationLeavesArrays::ZE_SEP << famId; + names.push_back(oss.str()); + } + return ret; +} + +const MEDFileFieldRepresentationLeavesArrays& MEDFileFieldRepresentationTree::getLeafArr(int id) const +{ + for(std::vector< std::vector< std::vector< MEDFileFieldRepresentationLeaves > > >::const_iterator it0=_data_structure.begin();it0!=_data_structure.end();it0++) + for(std::vector< std::vector< MEDFileFieldRepresentationLeaves > >::const_iterator it1=(*it0).begin();it1!=(*it0).end();it1++) + for(std::vector< MEDFileFieldRepresentationLeaves >::const_iterator it2=(*it1).begin();it2!=(*it1).end();it2++) + if((*it2).containId(id)) + return (*it2).getLeafArr(id); + throw INTERP_KERNEL::Exception("Internal error in MEDFileFieldRepresentationTree::getLeafArr !"); +} + +std::string MEDFileFieldRepresentationTree::getNameOf(int id) const +{ + const MEDFileFieldRepresentationLeavesArrays& elt(getLeafArr(id)); + return elt.getZeName(); +} + +const char *MEDFileFieldRepresentationTree::getNameOfC(int id) const +{ + const MEDFileFieldRepresentationLeavesArrays& elt(getLeafArr(id)); + return elt.getZeNameC(); +} + +bool MEDFileFieldRepresentationTree::getStatusOf(int id) const +{ + const MEDFileFieldRepresentationLeavesArrays& elt(getLeafArr(id)); + return elt.getStatus(); +} + +int MEDFileFieldRepresentationTree::getIdHavingZeName(const char *name) const +{ + int ret(-1); + for(std::vector< std::vector< std::vector< MEDFileFieldRepresentationLeaves > > >::const_iterator it0=_data_structure.begin();it0!=_data_structure.end();it0++) + for(std::vector< std::vector< MEDFileFieldRepresentationLeaves > >::const_iterator it1=(*it0).begin();it1!=(*it0).end();it1++) + for(std::vector< MEDFileFieldRepresentationLeaves >::const_iterator it2=(*it1).begin();it2!=(*it1).end();it2++) + if((*it2).containZeName(name,ret)) + return ret; + std::ostringstream msg; msg << "MEDFileFieldRepresentationTree::getIdHavingZeName : No such a name \"" << name << "\" !"; + throw INTERP_KERNEL::Exception(msg.str().c_str()); +} + +bool MEDFileFieldRepresentationTree::changeStatusOfAndUpdateToHaveCoherentVTKDataSet(int id, bool status) const +{ + const MEDFileFieldRepresentationLeavesArrays& elt(getLeafArr(id)); + bool ret(elt.setStatus(status));//to be implemented + return ret; +} + +int MEDFileFieldRepresentationTree::getMaxNumberOfTimeSteps() const +{ + int ret(0); + for(std::vector< std::vector< std::vector< MEDFileFieldRepresentationLeaves > > >::const_iterator it0=_data_structure.begin();it0!=_data_structure.end();it0++) + for(std::vector< std::vector< MEDFileFieldRepresentationLeaves > >::const_iterator it1=(*it0).begin();it1!=(*it0).end();it1++) + for(std::vector< MEDFileFieldRepresentationLeaves >::const_iterator it2=(*it1).begin();it2!=(*it1).end();it2++) + ret=std::max(ret,(*it2).getNumberOfTS()); + return ret; +} + +/*! + * + */ +void MEDFileFieldRepresentationTree::loadInMemory(MEDCoupling::MEDFileFields *fields, MEDCoupling::MEDFileMeshes *meshes) +{ + _fields=fields; _ms=meshes; + if(_fields.isNotNull()) + _fields->incrRef(); + if(_ms.isNotNull()) + _ms->incrRef(); + // + if(_fields.isNull()) + { + _fields=BuildFieldFromMeshes(_ms); + } + else + { + AppendFieldFromMeshes(_ms,_fields); + } + _ms->cartesianizeMe(); + _fields->removeFieldsWithoutAnyTimeStep(); + std::vector meshNames(_ms->getMeshesNames()); + std::vector< MCAuto > fields_per_mesh(meshNames.size()); + for(std::size_t i=0;ipartOfThisLyingOnSpecifiedMeshName(meshNames[i].c_str()); + } + std::vector< MCAuto > allFMTSLeavesToDisplaySafe; + std::size_t k(0); + for(std::vector< MCAuto >::const_iterator fields=fields_per_mesh.begin();fields!=fields_per_mesh.end();fields++) + { + for(int j=0;j<(*fields)->getNumberOfFields();j++) + { + MCAuto fmts((*fields)->getFieldAtPos((int)j)); + std::vector< MCAuto< MEDFileAnyTypeFieldMultiTS > > tmp(fmts->splitDiscretizations()); + // EDF 8655 + for(std::vector< MCAuto< MEDFileAnyTypeFieldMultiTS > >::const_iterator it=tmp.begin();it!=tmp.end();it++) + { + if(!(*it)->presenceOfMultiDiscPerGeoType()) + allFMTSLeavesToDisplaySafe.push_back(*it); + else + {// The case of some parts of field have more than one discretization per geo type. + std::vector< MCAuto< MEDFileAnyTypeFieldMultiTS > > subTmp((*it)->splitMultiDiscrPerGeoTypes()); + std::size_t it0Cnt(0); + for(std::vector< MCAuto< MEDFileAnyTypeFieldMultiTS > >::iterator it0=subTmp.begin();it0!=subTmp.end();it0++,it0Cnt++)//not const because setName + { + std::ostringstream oss; oss << (*it0)->getName() << "_" << std::setfill('M') << std::setw(3) << it0Cnt; + (*it0)->setName(oss.str()); + allFMTSLeavesToDisplaySafe.push_back(*it0); + } + } + } + // end EDF 8655 + } + } + std::vector< MEDFileAnyTypeFieldMultiTS *> allFMTSLeavesToDisplay(allFMTSLeavesToDisplaySafe.size()); + for(std::size_t i=0;i > allFMTSLeavesPerTimeSeries(MEDFileAnyTypeFieldMultiTS::SplitIntoCommonTimeSeries(allFMTSLeavesToDisplay)); + // memory safety part + std::vector< std::vector< MCAuto > > allFMTSLeavesPerTimeSeriesSafe(allFMTSLeavesPerTimeSeries.size()); + for(std::size_t j=0;jincrRef();//because MEDFileAnyTypeFieldMultiTS::SplitIntoCommonTimeSeries do not increments the counter + allFMTSLeavesPerTimeSeriesSafe[j][k]=allFMTSLeavesPerTimeSeries[j][k]; + } + } + // end of memory safety part + // 1st : timesteps, 2nd : meshName, 3rd : common support + this->_data_structure.resize(allFMTSLeavesPerTimeSeriesSafe.size()); + for(std::size_t i=0;i meshNamesLoc; + std::vector< std::vector< MCAuto > > splitByMeshName; + for(std::size_t j=0;jgetMeshName()); + std::vector< std::string >::iterator it(std::find(meshNamesLoc.begin(),meshNamesLoc.end(),meshName)); + if(it==meshNamesLoc.end()) + { + meshNamesLoc.push_back(meshName); + splitByMeshName.resize(splitByMeshName.size()+1); + splitByMeshName.back().push_back(allFMTSLeavesPerTimeSeriesSafe[i][j]); + } + else + splitByMeshName[std::distance(meshNamesLoc.begin(),it)].push_back(allFMTSLeavesPerTimeSeriesSafe[i][j]); + } + _data_structure[i].resize(meshNamesLoc.size()); + for(std::size_t j=0;j > fsp; + std::vector< MEDFileAnyTypeFieldMultiTS *> sbmn(splitByMeshName[j].size()); + for(std::size_t k=0;k > commonSupSplit(MEDFileAnyTypeFieldMultiTS::SplitPerCommonSupport(sbmn,_ms->getMeshWithName(meshNamesLoc[j].c_str()),fsp)); + std::vector< std::vector< MCAuto > > commonSupSplitSafe(commonSupSplit.size()); + this->_data_structure[i][j].resize(commonSupSplit.size()); + for(std::size_t k=0;kincrRef();//because MEDFileAnyTypeFieldMultiTS::SplitPerCommonSupport does not increment pointers ! + commonSupSplitSafe[k][l]=commonSupSplit[k][l]; + } + } + for(std::size_t k=0;k_data_structure[i][j][k]=MEDFileFieldRepresentationLeaves(commonSupSplitSafe[k],fsp[k]); + } + } + this->removeEmptyLeaves(); + this->assignIds(); + this->computeFullNameInLeaves(); +} + +void MEDFileFieldRepresentationTree::loadMainStructureOfFile(const char *fileName, bool isMEDOrSauv, int iPart, int nbOfParts) +{ + MCAuto ms; + MCAuto fields; + if(isMEDOrSauv) + { + if((iPart==-1 && nbOfParts==-1) || (iPart==0 && nbOfParts==1)) + { + MCAuto msups(MEDFileMeshSupports::New(fileName)); + MCAuto mse(MEDFileStructureElements::New(fileName,msups)); + ms=MEDFileMeshes::New(fileName); + fields=MEDFileFields::NewWithDynGT(fileName,mse,false);//false is important to not read the values + if(ms->presenceOfStructureElements()) + {// pre traitement + fields->loadArrays(); + fields->blowUpSE(ms,mse); + } + int nbMeshes(ms->getNumberOfMeshes()); + for(int i=0;igetMeshAtPos(i)); + MEDCoupling::MEDFileUMesh *tmp2(dynamic_cast(tmp)); + if(tmp2) + tmp2->forceComputationOfParts(); + } + } + else + { +#ifdef MEDREADER_USE_MPI + ms=ParaMEDFileMeshes::New(iPart,nbOfParts,fileName); + int nbMeshes(ms->getNumberOfMeshes()); + for(int i=0;igetMeshAtPos(i)); + MEDCoupling::MEDFileUMesh *tmp2(dynamic_cast(tmp)); + if(tmp2) + MCAuto tmp3(tmp2->zipCoords()); + } + fields=MEDFileFields::LoadPartOf(fileName,false,ms);//false is important to not read the values +#else + std::ostringstream oss; oss << "MEDFileFieldRepresentationTree::loadMainStructureOfFile : request for iPart/nbOfParts=" << iPart << "/" << nbOfParts << " whereas Plugin not compiled with MPI !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); +#endif + } + } + else + { + MCAuto sr(MEDCoupling::SauvReader::New(fileName)); + MCAuto mfd(sr->loadInMEDFileDS()); + ms=mfd->getMeshes(); ms->incrRef(); + int nbMeshes(ms->getNumberOfMeshes()); + for(int i=0;igetMeshAtPos(i)); + MEDCoupling::MEDFileUMesh *tmp2(dynamic_cast(tmp)); + if(tmp2) + tmp2->forceComputationOfParts(); + } + fields=mfd->getFields(); + if(fields.isNotNull()) + fields->incrRef(); + } + loadInMemory(fields,ms); +} + +void MEDFileFieldRepresentationTree::removeEmptyLeaves() +{ + std::vector< std::vector< std::vector< MEDFileFieldRepresentationLeaves > > > newSD; + for(std::vector< std::vector< std::vector< MEDFileFieldRepresentationLeaves > > >::const_iterator it0=_data_structure.begin();it0!=_data_structure.end();it0++) + { + std::vector< std::vector< MEDFileFieldRepresentationLeaves > > newSD0; + for(std::vector< std::vector< MEDFileFieldRepresentationLeaves > >::const_iterator it1=(*it0).begin();it1!=(*it0).end();it1++) + { + std::vector< MEDFileFieldRepresentationLeaves > newSD1; + for(std::vector< MEDFileFieldRepresentationLeaves >::const_iterator it2=(*it1).begin();it2!=(*it1).end();it2++) + if(!(*it2).empty()) + newSD1.push_back(*it2); + if(!newSD1.empty()) + newSD0.push_back(newSD1); + } + if(!newSD0.empty()) + newSD.push_back(newSD0); + } +} + +bool MEDFileFieldRepresentationTree::IsFieldMeshRegardingInfo(const std::vector& compInfos) +{ + if(compInfos.size()!=1) + return false; + return compInfos[0]==COMPO_STR_TO_LOCATE_MESH_DA; +} + +std::string MEDFileFieldRepresentationTree::getDftMeshName() const +{ + return _data_structure[0][0][0].getMeshName(); +} + +std::vector MEDFileFieldRepresentationTree::getTimeSteps(int& lev0, const TimeKeeper& tk) const +{ + int lev1,lev2; + const MEDFileFieldRepresentationLeaves& leaf(getTheSingleActivated(lev0,lev1,lev2)); + return leaf.getTimeSteps(tk); +} + +vtkDataSet *MEDFileFieldRepresentationTree::buildVTKInstance(bool isStdOrMode, double timeReq, std::string& meshName, const TimeKeeper& tk, ExportedTinyInfo *internalInfo) const +{ + int lev0,lev1,lev2; + const MEDFileFieldRepresentationLeaves& leaf(getTheSingleActivated(lev0,lev1,lev2)); + meshName=leaf.getMeshName(); + std::vector ts(leaf.getTimeSteps(tk)); + std::size_t zeTimeId(0); + if(ts.size()!=1) + { + std::vector ts2(ts.size()); + std::transform(ts.begin(),ts.end(),ts2.begin(),std::bind2nd(std::plus(),-timeReq)); + std::transform(ts2.begin(),ts2.end(),ts2.begin(),std::ptr_fun(fabs)); + zeTimeId=std::distance(ts2.begin(),std::find_if(ts2.begin(),ts2.end(),std::bind2nd(std::less(),1e-14))); + } + //2nd chance + if(zeTimeId==ts.size()) + zeTimeId=std::distance(ts.begin(),std::find(ts.begin(),ts.end(),timeReq)); + if(zeTimeId==ts.size()) + {//OK the time requested does not fit time series given to ParaView. It is typically the case if more than one MEDReader instance are created or TimeInspector in real time mode. + //In this case the default behaviour is taken. Keep the highest time step in this lower than timeReq. + int pos(-1); + double valAttachedToPos(-std::numeric_limits::max()); + for(std::size_t i=0;ivalAttachedToPos) + { + pos=(int)i; + valAttachedToPos=ts[i]; + } + } + } + if(pos==-1) + {// timeReq is lower than all time steps (ts). So let's keep the lowest time step greater than timeReq. + valAttachedToPos=std::numeric_limits::max(); + for(std::size_t i=0;i(oss,",")); + oss << " ! Keep time " << valAttachedToPos << " at pos #" << zeTimeId; + std::cerr << oss.str() << std::endl; + } + MEDTimeReq *tr(0); + if(!isStdOrMode) + tr=new MEDStdTimeReq((int)zeTimeId); + else + tr=new MEDModeTimeReq(tk.getTheVectOfBool(),tk.getPostProcessedTime()); + vtkDataSet *ret(leaf.buildVTKInstanceNoTimeInterpolation(tr,_fields,_ms,internalInfo)); + delete tr; + return ret; +} + +const MEDFileFieldRepresentationLeaves& MEDFileFieldRepresentationTree::getTheSingleActivated(int& lev0, int& lev1, int& lev2) const +{ + int nbOfActivated(0); + for(std::vector< std::vector< std::vector< MEDFileFieldRepresentationLeaves > > >::const_iterator it0=_data_structure.begin();it0!=_data_structure.end();it0++) + for(std::vector< std::vector< MEDFileFieldRepresentationLeaves > >::const_iterator it1=(*it0).begin();it1!=(*it0).end();it1++) + for(std::vector< MEDFileFieldRepresentationLeaves >::const_iterator it2=(*it1).begin();it2!=(*it1).end();it2++) + if((*it2).isActivated()) + nbOfActivated++; + if(nbOfActivated!=1) + { + std::ostringstream oss; oss << "MEDFileFieldRepresentationTree::getTheSingleActivated : Only one leaf must be activated ! Having " << nbOfActivated << " !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + int i0(0),i1(0),i2(0); + for(std::vector< std::vector< std::vector< MEDFileFieldRepresentationLeaves > > >::const_iterator it0=_data_structure.begin();it0!=_data_structure.end();it0++,i0++) + for(std::vector< std::vector< MEDFileFieldRepresentationLeaves > >::const_iterator it1=(*it0).begin();it1!=(*it0).end();it1++,i1++) + for(std::vector< MEDFileFieldRepresentationLeaves >::const_iterator it2=(*it1).begin();it2!=(*it1).end();it2++,i2++) + if((*it2).isActivated()) + { + lev0=i0; lev1=i1; lev2=i2; + return *it2; + } + throw INTERP_KERNEL::Exception("MEDFileFieldRepresentationTree::getTheSingleActivated : Internal error !"); +} + +void MEDFileFieldRepresentationTree::printMySelf(std::ostream& os) const +{ + int i(0); + os << "#############################################" << std::endl; + for(std::vector< std::vector< std::vector< MEDFileFieldRepresentationLeaves > > >::const_iterator it0=_data_structure.begin();it0!=_data_structure.end();it0++,i++) + { + int j(0); + os << "TS" << i << std::endl; + for(std::vector< std::vector< MEDFileFieldRepresentationLeaves > >::const_iterator it1=(*it0).begin();it1!=(*it0).end();it1++,j++) + { + int k(0); + for(std::vector< MEDFileFieldRepresentationLeaves >::const_iterator it2=(*it1).begin();it2!=(*it1).end();it2++,k++) + { + if(k==0) + os << " " << (*it2).getMeshName() << std::endl; + os << " Comp" << k << std::endl; + (*it2).printMySelf(os); + } + } + } + os << "$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$" << std::endl; +} + +std::map MEDFileFieldRepresentationTree::dumpState() const +{ + std::map ret; + for(std::vector< std::vector< std::vector< MEDFileFieldRepresentationLeaves > > >::const_iterator it0=_data_structure.begin();it0!=_data_structure.end();it0++) + for(std::vector< std::vector< MEDFileFieldRepresentationLeaves > >::const_iterator it1=(*it0).begin();it1!=(*it0).end();it1++) + for(std::vector< MEDFileFieldRepresentationLeaves >::const_iterator it2=(*it1).begin();it2!=(*it1).end();it2++) + (*it2).dumpState(ret); + return ret; +} + +void MEDFileFieldRepresentationTree::AppendFieldFromMeshes(const MEDCoupling::MEDFileMeshes *ms, MEDCoupling::MEDFileFields *ret) +{ + if(!ret) + throw INTERP_KERNEL::Exception("MEDFileFieldRepresentationTree::AppendFieldFromMeshes : internal error ! NULL ret !"); + for(int i=0;igetNumberOfMeshes();i++) + { + MEDFileMesh *mm(ms->getMeshAtPos(i)); + std::vector levs(mm->getNonEmptyLevels()); + MEDCoupling::MCAuto f1tsMultiLev(MEDCoupling::MEDFileField1TS::New()); + MEDFileUMesh *mmu(dynamic_cast(mm)); + if(mmu) + { + for(std::vector::const_iterator it=levs.begin();it!=levs.end();it++) + { + std::vector gts(mmu->getGeoTypesAtLevel(*it)); + for(std::vector::const_iterator gt=gts.begin();gt!=gts.end();gt++) + { + MEDCoupling::MEDCouplingMesh *m(mmu->getDirectUndergroundSingleGeoTypeMesh(*gt)); + MEDCoupling::MCAuto f(MEDCoupling::MEDCouplingFieldDouble::New(MEDCoupling::ON_CELLS)); + f->setMesh(m); + MEDCoupling::MCAuto arr(MEDCoupling::DataArrayDouble::New()); arr->alloc(f->getNumberOfTuplesExpected()); + arr->setInfoOnComponent(0,std::string(COMPO_STR_TO_LOCATE_MESH_DA)); + arr->iota(); + f->setArray(arr); + f->setName(BuildAUniqueArrayNameForMesh(mm->getName(),ret)); + f1tsMultiLev->setFieldNoProfileSBT(f); + } + } + if(levs.empty()) + { + std::vector levsExt(mm->getNonEmptyLevelsExt()); + if(levsExt.size()==levs.size()+1) + { + MEDCoupling::MCAuto m(mm->getMeshAtLevel(1)); + MEDCoupling::MCAuto f(MEDCoupling::MEDCouplingFieldDouble::New(MEDCoupling::ON_NODES)); + f->setMesh(m); + MEDCoupling::MCAuto arr(MEDCoupling::DataArrayDouble::New()); arr->alloc(m->getNumberOfNodes()); + arr->setInfoOnComponent(0,std::string(COMPO_STR_TO_LOCATE_MESH_DA)); + arr->iota(); f->setArray(arr); + f->setName(BuildAUniqueArrayNameForMesh(mm->getName(),ret)); + f1tsMultiLev->setFieldNoProfileSBT(f); + } + else + continue; + } + } + else + { + MEDCoupling::MCAuto m(mm->getMeshAtLevel(0)); + MEDCoupling::MCAuto f(MEDCoupling::MEDCouplingFieldDouble::New(MEDCoupling::ON_CELLS)); + f->setMesh(m); + MEDCoupling::MCAuto arr(MEDCoupling::DataArrayDouble::New()); arr->alloc(f->getNumberOfTuplesExpected()); + arr->setInfoOnComponent(0,std::string(COMPO_STR_TO_LOCATE_MESH_DA)); + arr->iota(); + f->setArray(arr); + f->setName(BuildAUniqueArrayNameForMesh(mm->getName(),ret)); + f1tsMultiLev->setFieldNoProfileSBT(f); + } + // + MEDCoupling::MCAuto fmtsMultiLev(MEDCoupling::MEDFileFieldMultiTS::New()); + fmtsMultiLev->pushBackTimeStep(f1tsMultiLev); + ret->pushField(fmtsMultiLev); + } +} + +std::string MEDFileFieldRepresentationTree::BuildAUniqueArrayNameForMesh(const std::string& meshName, const MEDCoupling::MEDFileFields *ret) +{ + const char KEY_STR_TO_AVOID_COLLIDE[]="MESH@"; + if(!ret) + throw INTERP_KERNEL::Exception("MEDFileFieldRepresentationTree::BuildAUniqueArrayNameForMesh : internal error ! NULL ret !"); + std::vector fieldNamesAlreadyExisting(ret->getFieldsNames()); + if(std::find(fieldNamesAlreadyExisting.begin(),fieldNamesAlreadyExisting.end(),meshName)==fieldNamesAlreadyExisting.end()) + return meshName; + std::string tmpName(KEY_STR_TO_AVOID_COLLIDE); tmpName+=meshName; + while(std::find(fieldNamesAlreadyExisting.begin(),fieldNamesAlreadyExisting.end(),tmpName)!=fieldNamesAlreadyExisting.end()) + tmpName=std::string(KEY_STR_TO_AVOID_COLLIDE)+tmpName; + return tmpName; +} + +MEDCoupling::MEDFileFields *MEDFileFieldRepresentationTree::BuildFieldFromMeshes(const MEDCoupling::MEDFileMeshes *ms) +{ + MEDCoupling::MCAuto ret(MEDCoupling::MEDFileFields::New()); + AppendFieldFromMeshes(ms,ret); + return ret.retn(); +} + +std::vector MEDFileFieldRepresentationTree::SplitFieldNameIntoParts(const std::string& fullFieldName, char sep) +{ + std::vector ret; + std::size_t pos(0); + while(pos!=std::string::npos) + { + std::size_t curPos(fullFieldName.find_first_of(sep,pos)); + std::string elt(fullFieldName.substr(pos,curPos!=std::string::npos?curPos-pos:std::string::npos)); + ret.push_back(elt); + pos=fullFieldName.find_first_not_of(sep,curPos); + } + return ret; +} + +/*! + * Here the non regression tests. + * const char inp0[]=""; + * const char exp0[]=""; + * const char inp1[]="field"; + * const char exp1[]="field"; + * const char inp2[]="_________"; + * const char exp2[]="_________"; + * const char inp3[]="field_p"; + * const char exp3[]="field_p"; + * const char inp4[]="field__p"; + * const char exp4[]="field_p"; + * const char inp5[]="field_p__"; + * const char exp5[]="field_p"; + * const char inp6[]="field_p_"; + * const char exp6[]="field_p"; + * const char inp7[]="field_____EDFGEG//sdkjf_____PP_______________"; + * const char exp7[]="field_EDFGEG//sdkjf_PP"; + * const char inp8[]="field_____EDFGEG//sdkjf_____PP"; + * const char exp8[]="field_EDFGEG//sdkjf_PP"; + * const char inp9[]="_field_____EDFGEG//sdkjf_____PP_______________"; + * const char exp9[]="field_EDFGEG//sdkjf_PP"; + * const char inp10[]="___field_____EDFGEG//sdkjf_____PP_______________"; + * const char exp10[]="field_EDFGEG//sdkjf_PP"; +*/ +std::string MEDFileFieldRepresentationTree::PostProcessFieldName(const std::string& fullFieldName) +{ + const char SEP('_'); + std::vector v(SplitFieldNameIntoParts(fullFieldName,SEP)); + if(v.empty()) + return fullFieldName;//should never happen + if(v.size()==1) + { + if(v[0].empty()) + return fullFieldName; + else + return v[0]; + } + std::string ret(v[0]); + for(std::size_t i=1;i TimeKeeper::getTimeStepsRegardingPolicy(const std::vector< std::pair >& tsPairs, const std::vector& ts) const +{ + switch(_policy) + { + case 0: + return getTimeStepsRegardingPolicy0(tsPairs,ts); + case 1: + return getTimeStepsRegardingPolicy0(tsPairs,ts); + default: + throw INTERP_KERNEL::Exception("TimeKeeper::getTimeStepsRegardingPolicy : only policy 0 and 1 supported presently !"); + } +} + +/*! + * policy = 0 : + * if all of ts are in -1e299,1e299 and different each other pairs are ignored ts taken directly. + * if all of ts are in -1e299,1e299 but some are not different each other ts are ignored pairs used + * if some of ts are out of -1e299,1e299 ts are ignored pairs used + */ +std::vector TimeKeeper::getTimeStepsRegardingPolicy0(const std::vector< std::pair >& tsPairs, const std::vector& ts) const +{ + std::size_t sz(ts.size()); + bool isInHumanRange(true); + std::set s; + for(std::size_t i=0;i=1e299) + isInHumanRange=false; + } + if(!isInHumanRange) + return processedUsingPairOfIds(tsPairs); + if(s.size()!=sz) + return processedUsingPairOfIds(tsPairs); + _postprocessed_time=ts; + return getPostProcessedTime(); +} + +/*! + * policy = 1 : + * idem than 0, except that ts is preaccumulated before invoking policy 0. + */ +std::vector TimeKeeper::getTimeStepsRegardingPolicy1(const std::vector< std::pair >& tsPairs, const std::vector& ts) const +{ + std::size_t sz(ts.size()); + std::vector ts2(sz); + double acc(0.); + for(std::size_t i=0;i TimeKeeper::getTheVectOfBool() const +{ + std::size_t sz(_activated_ts.size()); + std::vector ret(sz); + for(std::size_t i=0;i TimeKeeper::processedUsingPairOfIds(const std::vector< std::pair >& tsPairs) const +{ + std::size_t sz(tsPairs.size()); + std::set s0,s1; + for(std::size_t i=0;i(true,oss.str()); + } +} diff --git a/src/Plugins/MEDReader/plugin/MEDLoaderForPV/MEDFileFieldRepresentationTree.hxx b/src/Plugins/MEDReader/plugin/MEDLoaderForPV/MEDFileFieldRepresentationTree.hxx new file mode 100644 index 00000000..36a1adf5 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/MEDLoaderForPV/MEDFileFieldRepresentationTree.hxx @@ -0,0 +1,208 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay + +#ifndef __MEDFILEFIELDREPRESENTATIONTREE_HXX__ +#define __MEDFILEFIELDREPRESENTATIONTREE_HXX__ + +#include "MEDFileMesh.hxx" +#include "MEDFileField.hxx" +#include "MEDLoaderForPV.h" + +#include "vtkType.h" + +#include +#include + +class vtkQuadratureSchemeDefinition; +class vtkMutableDirectedGraph; +class vtkUnstructuredGrid; +class vtkRectilinearGrid; +class vtkStructuredGrid; +class vtkVariantArray; +class vtkIdTypeArray; +class vtkDoubleArray; +class vtkDataArray; +class vtkDataSet; + +class TimeKeeper; +class MEDTimeReq; +class ExportedTinyInfo; + +class ELGACmp +{ +public: + template + vtkIdTypeArray *findOrCreate(const MEDCoupling::MEDFileFieldGlobsReal *globs, const std::vector& locsReallyUsed, vtkDataArray *vtkd, vtkDataSet *ds, bool& isNew, ExportedTinyInfo *internalInfo) const; + void appendELGAIfAny(vtkDataSet *ds) const; + ~ELGACmp(); +private: + vtkIdTypeArray *isExisting(const std::vector& locsReallyUsed, vtkDataArray *vtkd) const; + template + vtkIdTypeArray *createNew(const MEDCoupling::MEDFileFieldGlobsReal *globs, const std::vector& locsReallyUsed, vtkDataArray *vtkd, vtkDataSet *ds, ExportedTinyInfo *internalInfo) const; +private: + //! size of _loc_names is equal to _elgas. + mutable std::vector< std::vector > _loc_names; + //! size of _elgas is equal to _loc_names. All instances in _elgas are \b not null. + mutable std::vector _elgas; + //! same size than _loc_names and _elgas. + mutable std::vector< std::vector< std::pair< vtkQuadratureSchemeDefinition *, unsigned char > > > _defs; +}; + +class MEDLOADERFORPV_EXPORT MEDFileFieldRepresentationLeavesArrays : public MEDCoupling::MCAuto +{ +public: + MEDFileFieldRepresentationLeavesArrays(); + MEDFileFieldRepresentationLeavesArrays(const MEDCoupling::MCAuto& arr); + MEDFileFieldRepresentationLeavesArrays& operator=(const MEDFileFieldRepresentationLeavesArrays& other); + int getId() const; + void setId(int& id) const; + void feedSIL(vtkMutableDirectedGraph* sil, vtkIdType root, vtkVariantArray *edge, std::vector& names) const; + void computeFullNameInLeaves(const std::string& tsName, const std::string& meshName, const std::string& comSupStr) const; + bool getStatus() const; + bool setStatus(bool status) const; + std::string getZeName() const; + const char *getZeNameC() const; + void appendFields(const MEDTimeReq *tr, const MEDCoupling::MEDFileFieldGlobsReal *globs, const MEDCoupling::MEDMeshMultiLev *mml, const MEDCoupling::MEDFileMeshStruct *mst, vtkDataSet *ds, ExportedTinyInfo *internalInfo) const; + void appendELGAIfAny(vtkDataSet *ds) const; +public: + static const char ZE_SEP[]; + static const char TS_STR[]; + static const char COM_SUP_STR[]; + static const char FAMILY_ID_CELL_NAME[]; + static const char NUM_ID_CELL_NAME[]; + static const char FAMILY_ID_NODE_NAME[]; + static const char NUM_ID_NODE_NAME[]; + static const char GLOBAL_NODE_ID_NAME[]; +private: + mutable bool _activated; + mutable int _id; + mutable std::string _ze_name; + mutable std::string _ze_full_name; + ELGACmp _elga_cmp; +}; + +class MEDLOADERFORPV_EXPORT MEDFileFieldRepresentationLeaves +{ +public: + MEDFileFieldRepresentationLeaves(); + MEDFileFieldRepresentationLeaves(const std::vector< MEDCoupling::MCAuto >& arr, + const MEDCoupling::MCAuto& fsp); + ~MEDFileFieldRepresentationLeaves(); + bool empty() const; + void setId(int& id) const; + std::string getMeshName() const; + int getNumberOfArrays() const; + int getNumberOfTS() const; + void feedSIL(const MEDCoupling::MEDFileMeshes *ms, const std::string& meshName, vtkMutableDirectedGraph* sil, vtkIdType root, vtkVariantArray *edge, std::vector& names) const; + void computeFullNameInLeaves(const std::string& tsName, const std::string& meshName, const std::string& comSupStr) const; + bool containId(int id) const; + bool containZeName(const char *name, int& id) const; + void dumpState(std::map& status) const; + bool isActivated() const; + void printMySelf(std::ostream& os) const; + void activateAllArrays() const; + const MEDFileFieldRepresentationLeavesArrays& getLeafArr(int id) const; + std::vector getTimeSteps(const TimeKeeper& tk) const; + std::vector< std::pair > getTimeStepsInCoarseMEDFileFormat(std::vector& ts) const; + std::string getHumanReadableOverviewOfTS() const; + vtkDataSet *buildVTKInstanceNoTimeInterpolation(const MEDTimeReq *tr, const MEDCoupling::MEDFileFieldGlobsReal *globs, const MEDCoupling::MEDFileMeshes *meshes, ExportedTinyInfo *internalInfo=0) const; +private: + vtkUnstructuredGrid *buildVTKInstanceNoTimeInterpolationUnstructured(MEDCoupling::MEDUMeshMultiLev *mm) const; + vtkRectilinearGrid *buildVTKInstanceNoTimeInterpolationCartesian(MEDCoupling::MEDCMeshMultiLev *mm) const; + vtkStructuredGrid *buildVTKInstanceNoTimeInterpolationCurveLinear(MEDCoupling::MEDCurveLinearMeshMultiLev *mm) const; + void appendFields(const MEDTimeReq *tr, const MEDCoupling::MEDFileFieldGlobsReal *globs, const MEDCoupling::MEDMeshMultiLev *mml, const MEDCoupling::MEDFileMeshes *meshes, vtkDataSet *ds, ExportedTinyInfo *internalInfo=0) const; +private: + std::vector _arrays; + MEDCoupling::MCAuto _fsp; + mutable vtkDataSet *_cached_ds; +}; + +class MEDLOADERFORPV_EXPORT MEDFileFieldRepresentationTree +{ +public: + MEDFileFieldRepresentationTree(); + int getNumberOfLeavesArrays() const; + void assignIds() const; + void activateTheFirst() const; + void computeFullNameInLeaves() const; + void feedSIL(vtkMutableDirectedGraph* sil, vtkIdType root, vtkVariantArray *edge, std::vector& names) const; + std::string getActiveMeshName() const; + std::string feedSILForFamsAndGrps(vtkMutableDirectedGraph* sil, vtkIdType root, vtkVariantArray *edge, std::vector& names) const; + std::string getNameOf(int id) const; + const char *getNameOfC(int id) const; + bool getStatusOf(int id) const; + int getIdHavingZeName(const char *name) const; + bool changeStatusOfAndUpdateToHaveCoherentVTKDataSet(int id, bool status) const; + int getMaxNumberOfTimeSteps() const; + // + std::string getDftMeshName() const; + std::vector getTimeSteps(int& lev0, const TimeKeeper& tk) const; + vtkDataSet *buildVTKInstance(bool isStdOrMode, double timeReq, std::string& meshName, const TimeKeeper& tk, ExportedTinyInfo *internalInfo=0) const; + void printMySelf(std::ostream& os) const; + std::map dumpState() const; + //non const methods + void loadMainStructureOfFile(const char *fileName, bool isMEDOrSauv, int iPart, int nbOfParts); + void loadInMemory(MEDCoupling::MEDFileFields *fields, MEDCoupling::MEDFileMeshes *meshes); + void removeEmptyLeaves(); + // static methods + static bool IsFieldMeshRegardingInfo(const std::vector& compInfos); + static std::string PostProcessFieldName(const std::string& fullFieldName); +public: + static const char ROOT_OF_GRPS_IN_TREE[]; + static const char ROOT_OF_FAM_IDS_IN_TREE[]; + static const char COMPO_STR_TO_LOCATE_MESH_DA[]; +private: + const MEDFileFieldRepresentationLeavesArrays& getLeafArr(int id) const; + const MEDFileFieldRepresentationLeaves& getTheSingleActivated(int& lev0, int& lev1, int& lev2) const; + static MEDCoupling::MEDFileFields *BuildFieldFromMeshes(const MEDCoupling::MEDFileMeshes *ms); + static void AppendFieldFromMeshes(const MEDCoupling::MEDFileMeshes *ms, MEDCoupling::MEDFileFields *ret); + static std::string BuildAUniqueArrayNameForMesh(const std::string& meshName, const MEDCoupling::MEDFileFields *ret); + static std::vector SplitFieldNameIntoParts(const std::string& fullFieldName, char sep); +private: + // 1st : timesteps, 2nd : meshName, 3rd : common support + std::vector< std::vector< std::vector< MEDFileFieldRepresentationLeaves > > > _data_structure; + MEDCoupling::MCAuto _ms; + MEDCoupling::MCAuto _fields; +}; + +class MEDLOADERFORPV_EXPORT TimeKeeper +{ +public: + TimeKeeper(int policy); + int getPolicy() const { return _policy; } + void setPolicy(int policy) { _policy=policy; } + std::vector getTimeStepsRegardingPolicy(const std::vector< std::pair >& tsPairs, const std::vector& ts) const; + int getTimeStepIdFrom(double timeReq) const; + std::vector getPostProcessedTime() const { return _postprocessed_time; } + void printSelf(std::ostream& oss) const; + std::vector getTheVectOfBool() const; + std::vector< std::pair >& getTimesFlagArray() { return _activated_ts; } + void setMaxNumberOfTimeSteps(int maxNumberOfTS); +private: + std::vector getTimeStepsRegardingPolicy0(const std::vector< std::pair >& tsPairs, const std::vector& ts) const; + std::vector getTimeStepsRegardingPolicy1(const std::vector< std::pair >& tsPairs, const std::vector& ts) const; + std::vector processedUsingPairOfIds(const std::vector< std::pair >& tsPairs) const; +private: + int _policy; + mutable std::vector _postprocessed_time; + std::vector< std::pair > _activated_ts; +}; + +#endif diff --git a/src/Plugins/MEDReader/plugin/MEDLoaderForPV/MEDLoaderForPV.h b/src/Plugins/MEDReader/plugin/MEDLoaderForPV/MEDLoaderForPV.h new file mode 100644 index 00000000..f60b5c73 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/MEDLoaderForPV/MEDLoaderForPV.h @@ -0,0 +1,33 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// + +#ifndef __MEDLOADERFORPV_HXX__ +#define __MEDLOADERFORPV_HXX__ + +#ifdef WIN32 +# if defined MEDLoaderForPV_EXPORTS || defined MEDLOADERFORPV_EXPORTS +# define MEDLOADERFORPV_EXPORT __declspec( dllexport ) +# else +# define MEDLOADERFORPV_EXPORT __declspec( dllimport ) +# endif +#else + #define MEDLOADERFORPV_EXPORT +#endif + +#endif diff --git a/src/Plugins/MEDReader/plugin/MEDLoaderForPV/MEDTimeReq.cxx b/src/Plugins/MEDReader/plugin/MEDLoaderForPV/MEDTimeReq.cxx new file mode 100644 index 00000000..fa104990 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/MEDLoaderForPV/MEDTimeReq.cxx @@ -0,0 +1,135 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay + +#include "MEDTimeReq.hxx" + +#include + +MEDTimeReq::~MEDTimeReq() +{ +} + +/////////// + +MEDStdTimeReq::~MEDStdTimeReq() +{ +} + +MEDStdTimeReq::MEDStdTimeReq(int timeReq):_time_req(timeReq) +{ +} + +/*! + * Does nothing ! It is not a bug + */ +void MEDStdTimeReq::setNumberOfTS(int nbOfTS) const +{ +} + +int MEDStdTimeReq::size() const +{ + return 1; +} + +int MEDStdTimeReq::getCurrent() const +{ + return _time_req; +} + +/*! + * Does nothing ! It is not a bug + */ +void MEDStdTimeReq::initIterator() const +{ +} + +std::string MEDStdTimeReq::buildName(const std::string& name) const +{ + return std::string(name); +} + +/*! + * Does nothing ! It is not a bug + */ +void MEDStdTimeReq::operator++() const +{ +} + +/////////// + +MEDModeTimeReq::MEDModeTimeReq(const std::vector& v, const std::vector& ts):_v(v),_ts(ts),_it(0),_sz(0) +{ +} + +MEDModeTimeReq::~MEDModeTimeReq() +{ +} + +int MEDModeTimeReq::size() const +{ + int ret(0); + for(int i=0;i<_sz;i++) + { + if(_v[i]) + ret++; + } + return ret; +} + +int MEDModeTimeReq::getCurrent() const +{ + return _it; +} + +void MEDModeTimeReq::setNumberOfTS(int nbOfTS) const +{ + _sz=nbOfTS; +} + +void MEDModeTimeReq::initIterator() const +{ + for(_it=0;_it<_sz;_it++) + if(_v[_it]) + return; +} + +std::string MEDModeTimeReq::buildName(const std::string& name) const +{ + std::ostringstream oss,oss2,oss3; + oss << name << " ["; + // + oss3 << _sz-1; + std::size_t len(oss3.str().length()); + oss2.width(len); + oss2.fill('0'); oss2 << _it; + // + oss << oss2.str() << "]"; + if(_it<(int)_ts.size()) + oss << " - " << _ts[_it]; + return oss.str(); +} + +void MEDModeTimeReq::operator++() const +{ + _it++; + for(;_it<_sz;_it++) + if(_v[_it]) + return; +} diff --git a/src/Plugins/MEDReader/plugin/MEDLoaderForPV/MEDTimeReq.hxx b/src/Plugins/MEDReader/plugin/MEDLoaderForPV/MEDTimeReq.hxx new file mode 100644 index 00000000..49546196 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/MEDLoaderForPV/MEDTimeReq.hxx @@ -0,0 +1,75 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay + +#ifndef __MEDTIMEREQ_HXX__ +#define __MEDTIMEREQ_HXX__ + +#include +#include + +#include "MEDLoaderForPV.h" + +class MEDLOADERFORPV_EXPORT MEDTimeReq +{ +public: + virtual int size() const = 0; + virtual void setNumberOfTS(int nbOfTS) const = 0; + virtual std::string buildName(const std::string& name) const = 0; + virtual void initIterator() const = 0; + virtual int getCurrent() const = 0; + virtual void operator++() const = 0; + virtual ~MEDTimeReq(); +}; + +class MEDLOADERFORPV_EXPORT MEDStdTimeReq : public MEDTimeReq +{ +public: + MEDStdTimeReq(int timeReq); + int size() const; + int getCurrent() const; + void initIterator() const; + void setNumberOfTS(int nbOfTS) const; + std::string buildName(const std::string& name) const; + void operator++() const; +public: + ~MEDStdTimeReq(); +private: + int _time_req; +}; + +class MEDLOADERFORPV_EXPORT MEDModeTimeReq : public MEDTimeReq +{ +public: + MEDModeTimeReq(const std::vector& v, const std::vector& ts); + ~MEDModeTimeReq(); + int size() const; + int getCurrent() const; + void initIterator() const; + void setNumberOfTS(int nbOfTS) const; + std::string buildName(const std::string& name) const; + void operator++() const; +private: + std::vector _v; + std::vector _ts; + mutable int _it; + mutable int _sz; +}; + +#endif diff --git a/src/Plugins/MEDReader/plugin/MEDLoaderForPV/MEDUtilities.cxx b/src/Plugins/MEDReader/plugin/MEDLoaderForPV/MEDUtilities.cxx new file mode 100644 index 00000000..0150a4e2 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/MEDLoaderForPV/MEDUtilities.cxx @@ -0,0 +1,52 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay + +#include "MEDUtilities.hxx" + +#include "vtkInformationIntegerKey.h" +#include "vtkInformationQuadratureSchemeDefinitionVectorKey.h" + +#include + +vtkInformationKeyMacro(MEDUtilities,ELGA,Integer); +vtkInformationKeyMacro(MEDUtilities,ELNO,Integer); + +void ExportedTinyInfo::pushGaussAdditionnalInfo(int ct, int dim, const std::vector& refCoo, const std::vector& posInRefCoo) +{ + prepareForAppend(); + std::vector tmp(1,(double)ct); + tmp.push_back((double)dim); + tmp.insert(tmp.end(),refCoo.begin(),refCoo.end()); + tmp.insert(tmp.end(),posInRefCoo.begin(),posInRefCoo.end()); + _data.push_back((double)tmp.size()); + _data.insert(_data.end(),tmp.begin(),tmp.end()); +} + +void ExportedTinyInfo::prepareForAppend() +{ + if(_data.empty()) + _data.push_back(1.); + else + { + double val(_data[0]); + int val2((int) val); + _data[0]=++val2; + } +} diff --git a/src/Plugins/MEDReader/plugin/MEDLoaderForPV/MEDUtilities.hxx b/src/Plugins/MEDReader/plugin/MEDLoaderForPV/MEDUtilities.hxx new file mode 100644 index 00000000..25a04600 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/MEDLoaderForPV/MEDUtilities.hxx @@ -0,0 +1,59 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay + +#ifndef __MEDUTILITIES_HXX__ +#define __MEDUTILITIES_HXX__ + +#include "MEDLoaderForPV.h" +#include "vtkCellType.h" + +#include + +class vtkInformationIntegerKey; + +class MEDLOADERFORPV_EXPORT MEDUtilities +{ +public: + static vtkInformationIntegerKey *ELGA(); + static vtkInformationIntegerKey *ELNO(); +}; + +class ExportedTinyInfo +{ +public: + void pushGaussAdditionnalInfo(int ct, int dim, const std::vector& refCoo, const std::vector& posInRefCoo); + const std::vector& getData() const { return _data; } + bool empty() const { return _data.empty(); } +private: + void prepareForAppend(); +private: + // first place is nb of ct + // 2nd place is the size of first ct def (this 2nd place included) + // 3rd place is the VTK cell type of first ct def + // 4th place is the dimension of first ct def + // 5th->n th : ref Coo + // nth -> n+p th : posInRefCoo + // n+p+1 -> size of second ct def (this n+p+1 place included) + // n+p+2 -> VTK cell type of second ct def + // ... + std::vector _data; +}; + +#endif diff --git a/src/Plugins/MEDReader/plugin/MEDLoaderForPV/vtkGenerateVectors.cxx b/src/Plugins/MEDReader/plugin/MEDLoaderForPV/vtkGenerateVectors.cxx new file mode 100644 index 00000000..36bc6bea --- /dev/null +++ b/src/Plugins/MEDReader/plugin/MEDLoaderForPV/vtkGenerateVectors.cxx @@ -0,0 +1,151 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay + +#include "vtkGenerateVectors.h" +#include "vtkDataArrayTemplate.h" +#include "vtkDoubleArray.h" +#include "vtkInformation.h" +#include "vtkUnstructuredGrid.h" +#include "vtkQuadratureSchemeDefinition.h" +#include "vtkInformationQuadratureSchemeDefinitionVectorKey.h" +#include "MEDUtilities.hxx" +#include "vtkFieldData.h" + +#include + +const char vtkGenerateVectors::VECTOR_SUFFIX[]="_Vector"; + +std::string vtkGenerateVectors::SuffixFieldName(const std::string& name) +{ + std::ostringstream oss; oss << name << VECTOR_SUFFIX; + return oss.str(); +} + +/*! + * This method forces MeshMTime modification. To do so, points are declared as modified. + */ +void vtkGenerateVectors::ChangeMeshTimeToUpdateCache(vtkDataSet *dataset) +{ + vtkUnstructuredGrid *ug(vtkUnstructuredGrid::SafeDownCast(dataset)); + if(!ug) + return ; + ug->GetPoints()->Modified(); +} + +void vtkGenerateVectors::Operate(vtkFieldData *fd) +{ + if(!fd) + return ; + const int nbOfArrs(fd->GetNumberOfArrays()); + std::vector daToAppend; + for(int i=0;iGetArray(i)); + if(!arr) + continue; + vtkDoubleArray *arrc(vtkDoubleArray::SafeDownCast(arr)); + if(!arrc) + continue; + int nbOfCompo(arrc->GetNumberOfComponents()); + if(nbOfCompo<=1 || nbOfCompo==3) + continue; + if(nbOfCompo==2) + daToAppend.push_back(Operate2Compo(arrc)); + else + daToAppend.push_back(OperateMoreThan3Compo(arrc)); + } + for(std::vector::const_iterator it=daToAppend.begin();it!=daToAppend.end();it++) + { + vtkDoubleArray *elt(*it); + if(!elt) + continue; + fd->AddArray(elt); + elt->Delete(); + } +} + +vtkDoubleArray *vtkGenerateVectors::Operate2Compo(vtkDoubleArray *oldArr) +{ + const int VTK_DATA_ARRAY_FREE=vtkDataArrayTemplate::VTK_DATA_ARRAY_FREE; + vtkDoubleArray *ret(vtkDoubleArray::New()); + vtkIdType nbOfTuples(oldArr->GetNumberOfTuples()); + const double *inPt(oldArr->GetPointer(0)); + double *pt((double *)malloc(nbOfTuples*3*sizeof(double))); + for(vtkIdType i=0;iSetNumberOfComponents(3); + std::string newName(SuffixFieldName(oldArr->GetName())); + ret->SetName(newName.c_str()); + ret->SetComponentName(0,oldArr->GetComponentName(0)); + ret->SetComponentName(1,oldArr->GetComponentName(1)); + ret->SetArray(pt,3*nbOfTuples,0,VTK_DATA_ARRAY_FREE); + UpdateInformationOfArray(oldArr,ret); + return ret; +} + +vtkDoubleArray *vtkGenerateVectors::OperateMoreThan3Compo(vtkDoubleArray *oldArr) +{ + const int VTK_DATA_ARRAY_FREE=vtkDataArrayTemplate::VTK_DATA_ARRAY_FREE; + vtkDoubleArray *ret(vtkDoubleArray::New()); + int nbOfCompo(oldArr->GetNumberOfComponents()); + vtkIdType nbOfTuples(oldArr->GetNumberOfTuples()); + const double *inPt(oldArr->GetPointer(0)); + double *pt((double *)malloc(nbOfTuples*3*sizeof(double))); + for(vtkIdType i=0;iSetNumberOfComponents(3); + std::string newName(SuffixFieldName(oldArr->GetName())); + ret->SetName(newName.c_str()); + ret->SetComponentName(0,oldArr->GetComponentName(0)); + ret->SetComponentName(1,oldArr->GetComponentName(1)); + ret->SetComponentName(2,oldArr->GetComponentName(2)); + ret->SetArray(pt,3*nbOfTuples,0,VTK_DATA_ARRAY_FREE); + UpdateInformationOfArray(oldArr,ret); + return ret; +} + +void vtkGenerateVectors::UpdateInformationOfArray(vtkDoubleArray *oldArr, vtkDoubleArray *arr) +{ + if(oldArr->GetInformation()->Has(vtkQuadratureSchemeDefinition::QUADRATURE_OFFSET_ARRAY_NAME())) + { + arr->GetInformation()->Set(vtkQuadratureSchemeDefinition::QUADRATURE_OFFSET_ARRAY_NAME(),oldArr->GetInformation()->Get((vtkQuadratureSchemeDefinition::QUADRATURE_OFFSET_ARRAY_NAME()))); + } + if(oldArr->GetInformation()->Get(MEDUtilities::ELGA())) + arr->GetInformation()->Set(MEDUtilities::ELGA(),1); + vtkInformationQuadratureSchemeDefinitionVectorKey *key(vtkQuadratureSchemeDefinition::DICTIONARY()); + if(key->Has(oldArr->GetInformation())) + { + int dictSize(key->Size(oldArr->GetInformation())); + vtkQuadratureSchemeDefinition **dict = new vtkQuadratureSchemeDefinition *[dictSize]; + key->GetRange(oldArr->GetInformation(),dict,0,0,dictSize); + key->SetRange(arr->GetInformation(),dict,0,0,dictSize); + delete [] dict; + } + if(oldArr->GetInformation()->Get(MEDUtilities::ELNO())) + arr->GetInformation()->Set(MEDUtilities::ELNO(),1); +} diff --git a/src/Plugins/MEDReader/plugin/MEDLoaderForPV/vtkGenerateVectors.h b/src/Plugins/MEDReader/plugin/MEDLoaderForPV/vtkGenerateVectors.h new file mode 100644 index 00000000..e7a45d53 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/MEDLoaderForPV/vtkGenerateVectors.h @@ -0,0 +1,43 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay + +#ifndef vtkGenerateVectors_h__ +#define vtkGenerateVectors_h__ + +#include "vtkDataSetAlgorithm.h" + +class vtkFieldData; +class vtkDoubleArray; + +class VTK_EXPORT vtkGenerateVectors +{ +public: + static void ChangeMeshTimeToUpdateCache(vtkDataSet *dataset); + static void Operate(vtkFieldData *fd); + static vtkDoubleArray *Operate2Compo(vtkDoubleArray *oldArr); + static vtkDoubleArray *OperateMoreThan3Compo(vtkDoubleArray *oldArr); + static std::string SuffixFieldName(const std::string& name); +public: + static const char VECTOR_SUFFIX[]; +protected: + static void UpdateInformationOfArray(vtkDoubleArray *oldArr, vtkDoubleArray *arr); +}; + +#endif diff --git a/src/Plugins/MEDReader/plugin/MEDReaderIO/CMakeLists.txt b/src/Plugins/MEDReader/plugin/MEDReaderIO/CMakeLists.txt new file mode 100644 index 00000000..2c69c54f --- /dev/null +++ b/src/Plugins/MEDReader/plugin/MEDReaderIO/CMakeLists.txt @@ -0,0 +1,21 @@ +set(classes + vtkELNOFilter + vtkELNOMeshFilter + vtkELNOSurfaceFilter + vtkExtractGroup + vtkExtractCellType + vtkMEDQuadraturePointsGenerator + vtkMEDReader + vtkPVMetaDataInformation +) + +vtk_module_add_module(MEDReaderIO + FORCE_STATIC + CLASSES ${classes} +) + +target_include_directories(MEDReaderIO PRIVATE + "${CMAKE_CURRENT_SOURCE_DIR}/../MEDLoaderForPV" + ${MEDCOUPLING_INCLUDE_DIRS}) + +target_link_libraries(MEDReaderIO PUBLIC MEDLoaderForPV) diff --git a/src/Plugins/MEDReader/plugin/MEDReaderIO/VTKMEDTraits.hxx b/src/Plugins/MEDReader/plugin/MEDReaderIO/VTKMEDTraits.hxx new file mode 100644 index 00000000..4efcdc24 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/MEDReaderIO/VTKMEDTraits.hxx @@ -0,0 +1,81 @@ +// Copyright (C) 2017-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay (EDF R&D) + +#ifndef __VTKMEDTRAITS_HXX__ +#define __VTKMEDTRAITS_HXX__ + +class vtkIntArray; +class vtkLongArray; +#ifdef WIN32 +class vtkLongLongArray; +#endif +class vtkFloatArray; +class vtkDoubleArray; + +template +class MEDFileVTKTraits +{ +public: + typedef void VtkType; + typedef void MCType; +}; + +template<> +class MEDFileVTKTraits +{ +public: + typedef vtkIntArray VtkType; + typedef MEDCoupling::DataArrayInt32 MCType; +}; + +template<> +#ifdef WIN32 +class MEDFileVTKTraits +#else +class MEDFileVTKTraits +#endif +# +{ +public: +#ifdef WIN32 + typedef vtkLongLongArray VtkType; +#else + typedef vtkLongArray VtkType; +#endif + typedef MEDCoupling::DataArrayInt64 MCType; +}; + +template<> +class MEDFileVTKTraits +{ +public: + typedef vtkFloatArray VtkType; + typedef MEDCoupling::DataArrayFloat MCType; +}; + +template<> +class MEDFileVTKTraits +{ +public: + typedef vtkDoubleArray VtkType; + typedef MEDCoupling::DataArrayDouble MCType; +}; + +#endif diff --git a/src/Plugins/MEDReader/plugin/MEDReaderIO/vtk.module b/src/Plugins/MEDReader/plugin/MEDReaderIO/vtk.module new file mode 100644 index 00000000..af3c0825 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/MEDReaderIO/vtk.module @@ -0,0 +1,10 @@ +NAME + MEDReaderIO +DEPENDS + VTK::FiltersGeneral + VTK::IOLegacy + ParaView::RemotingCore +PRIVATE_DEPENDS + VTK::IOLegacy + ParaView::VTKExtensionsFiltersRendering + ParaView::VTKExtensionsMisc diff --git a/src/Plugins/MEDReader/plugin/MEDReaderIO/vtkELNOFilter.cxx b/src/Plugins/MEDReader/plugin/MEDReaderIO/vtkELNOFilter.cxx new file mode 100644 index 00000000..dc756b8b --- /dev/null +++ b/src/Plugins/MEDReader/plugin/MEDReaderIO/vtkELNOFilter.cxx @@ -0,0 +1,205 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// + +#include "vtkELNOFilter.h" +#include "vtkInformation.h" +#include "vtkInformationVector.h" +#include "vtkObjectFactory.h" +#include "vtkPolyDataAlgorithm.h" +#include "vtkPolyData.h" +#include "vtkIdTypeArray.h" +#include "vtkFieldData.h" +#include "vtkCellData.h" +#include "vtkPointData.h" +#include "vtkCell.h" +#include "vtkInformationQuadratureSchemeDefinitionVectorKey.h" +#include "vtkQuadratureSchemeDefinition.h" +#include "vtkUnstructuredGrid.h" + +#include "MEDUtilities.hxx" +#include "InterpKernelAutoPtr.hxx" + +//vtkCxxRevisionMacro(vtkELNOFilter, "$Revision: 1.2.2.2 $"); +vtkStandardNewMacro(vtkELNOFilter); + +vtkELNOFilter::vtkELNOFilter() +{ + this->ShrinkFactor = 0.5; +} + +vtkELNOFilter::~vtkELNOFilter() +{ +} + +int vtkELNOFilter::RequestData(vtkInformation *request, vtkInformationVector **input, vtkInformationVector *output) +{ + vtkUnstructuredGrid *usgIn(vtkUnstructuredGrid::SafeDownCast( input[0]->GetInformationObject(0)->Get(vtkDataObject::DATA_OBJECT()))); + vtkPolyData *pdOut(vtkPolyData::SafeDownCast(output->GetInformationObject(0)->Get(vtkDataObject::DATA_OBJECT()))); + + vtkDataArray *array(this->GetInputArrayToProcess(0, input)); + vtkIdTypeArray* offsets(vtkIdTypeArray::SafeDownCast(this->GetInputArrayToProcess(0, input))); + + if(usgIn == NULL || offsets == NULL || pdOut == NULL) + { + vtkDebugMacro("vtkELNOFilter no correctly configured : offsets = " << offsets); + return 1; + } + + vtkInformation *info(offsets->GetInformation()); + vtkInformationQuadratureSchemeDefinitionVectorKey *key(vtkQuadratureSchemeDefinition::DICTIONARY()); + if(!key->Has(info)) + { + vtkDebugMacro("Dictionary is not present in array " << offsets->GetName() << " " << offsets << " Aborting." ); + return 1; + } + + int res(this->Superclass::RequestData(request, input, output)); + if(res == 0) + return 0; + + int dictSize(key->Size(info)); + vtkQuadratureSchemeDefinition **dict = new vtkQuadratureSchemeDefinition *[dictSize]; + key->GetRange(info, dict, 0, 0, dictSize); + + vtkIdType ncell(usgIn->GetNumberOfCells()); + vtkPoints *points(pdOut->GetPoints()); + vtkIdType start(0); + for(vtkIdType cellId = 0; cellId < ncell; cellId++) + { + vtkIdType offset(offsets->GetValue(cellId)); + int cellType(usgIn->GetCellType(cellId)); + // a simple check to see if a scheme really exists for this cell type. + // should not happen if the cell type has not been modified. + if(dict[cellType] == NULL) + continue; + int np = dict[cellType]->GetNumberOfQuadraturePoints(); + double center[3] = {0, 0, 0}; + for(int id = start; id < start + np; id++) + { + double *position = points->GetPoint(id); + center[0] += position[0]; + center[1] += position[1]; + center[2] += position[2]; + } + center[0] /= np; + center[1] /= np; + center[2] /= np; + for(int id = start; id < start + np; id++) + { + double *position = points->GetPoint(id); + double newpos[3]; + newpos[0] = position[0] * this->ShrinkFactor + center[0] * (1 - this->ShrinkFactor); + newpos[1] = position[1] * this->ShrinkFactor + center[1] * (1 - this->ShrinkFactor); + newpos[2] = position[2] * this->ShrinkFactor + center[2] * (1 - this->ShrinkFactor); + points->SetPoint(id, newpos); + } + start += np; + } + //// bug EDF 8407 PARAVIS - mantis 22610 + vtkFieldData *fielddata(usgIn->GetFieldData()); + for(int index=0;indexGetNumberOfArrays();index++) + { + vtkDataArray *data(fielddata->GetArray(index)); + vtkInformation *info(data->GetInformation()); + const char *arrayOffsetName(info->Get(vtkQuadratureSchemeDefinition::QUADRATURE_OFFSET_ARRAY_NAME())); + vtkIdTypeArray *offData(0); + bool isELNO(false); + if(arrayOffsetName) + { + vtkCellData *cellData(usgIn->GetCellData()); + vtkDataArray *offDataTmp(cellData->GetArray(arrayOffsetName)); + isELNO=offDataTmp->GetInformation()->Get(MEDUtilities::ELNO())==1; + offData=dynamic_cast(offDataTmp); + } + if(isELNO && offData) + { + vtkIdType nbCellsInput(usgIn->GetNumberOfCells()); + if(nbCellsInput==0) + continue ;//no cells -> no fields + // First trying to detected if we are in the special case where data can be used directly. To detect that look at offData. If offData.front()==0 && offData->back()+NbOfNodesInLastCell==data->GetNumberOfTuples() OK. + vtkCell *cell(usgIn->GetCell(nbCellsInput-1)); + bool statement0(offData->GetTuple1(0)==0); + bool statement1(offData->GetTuple1(nbCellsInput-1)+cell->GetNumberOfPoints()==data->GetNumberOfTuples()); + if(statement0 && statement1) + pdOut->GetPointData()->AddArray(data);//We are lucky ! No extraction needed. + else + {//not lucky ! Extract values from data. A previous threshold has been done... Bug EDF8662 + vtkDataArray *newArray(data->NewInstance()); + newArray->SetName(data->GetName()); + pdOut->GetPointData()->AddArray(newArray); + newArray->SetNumberOfComponents(data->GetNumberOfComponents()); + newArray->SetNumberOfTuples(pdOut->GetNumberOfPoints()); + newArray->CopyComponentNames(data); + newArray->Delete(); + vtkIdType *offsetPtr(offData->GetPointer(0)); + vtkIdType zeId(0); + for(vtkIdType cellId=0;cellIdGetCell(cellId)); + vtkIdType nbPoints(cell->GetNumberOfPoints()),offset(offsetPtr[cellId]); + for(vtkIdType j=0;jSetTuple(zeId,offsetPtr[cellId]+j,data); + } + } + } + } + AttachCellFieldsOn(usgIn,pdOut->GetCellData(),pdOut->GetNumberOfCells()); + return 1; +} + +void vtkELNOFilter::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os, indent); + os << indent << "ShrinkFactor : " << this->ShrinkFactor << endl; +} + +/*! + * This method attach fields on cell of \a inGrid and add it as a point data in \a outData. + */ +void vtkELNOFilter::AttachCellFieldsOn(vtkUnstructuredGrid *inGrid, vtkCellData *outData, int nbCellsOut) +{ + vtkCellData *cd(inGrid->GetCellData()); + int nbOfArrays(cd->GetNumberOfArrays()); + vtkIdType nbCells(inGrid->GetNumberOfCells()); + if(nbOfArrays==0) + return ; + INTERP_KERNEL::AutoPtr tmpPtr(new vtkIdType[nbCells]); + for(vtkIdType cellId=0;cellIdGetCell(cellId)); + tmpPtr[cellId]=cell->GetNumberOfPoints(); + } + for(int index=0;indexGetArray(index)); + vtkDataArray *newArray(data->NewInstance()); + newArray->SetName(data->GetName()); + outData->AddArray(newArray); + newArray->SetNumberOfComponents(data->GetNumberOfComponents()); + newArray->SetNumberOfTuples(nbCellsOut); + newArray->CopyComponentNames(data); + newArray->Delete(); + vtkIdType offset(0); + for(vtkIdType cellId=0;cellIdSetTuple(offset,cellId,data); + } + } +} diff --git a/src/Plugins/MEDReader/plugin/MEDReaderIO/vtkELNOFilter.h b/src/Plugins/MEDReader/plugin/MEDReaderIO/vtkELNOFilter.h new file mode 100644 index 00000000..01138027 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/MEDReaderIO/vtkELNOFilter.h @@ -0,0 +1,53 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// + +#ifndef _vtkELNOFilter_h +#define _vtkELNOFilter_h + +#include "vtkQuadraturePointsGenerator.h" + +class VTK_EXPORT vtkELNOFilter: public vtkQuadraturePointsGenerator +{ +public: + static vtkELNOFilter *New(); + vtkTypeMacro(vtkELNOFilter,vtkQuadraturePointsGenerator); + void PrintSelf(ostream& os, vtkIndent indent); + + // Description : + // This is the factor applied to shrink the cell before extracting + // the ELNO points. + // A value of 0 shrinks the cells to their center, and a value of 1 + // do not shrink the cell at all. + // default value 0.5 + vtkSetMacro(ShrinkFactor,double); + vtkGetMacro(ShrinkFactor,double); + +protected: + vtkELNOFilter(); + ~vtkELNOFilter(); + + int RequestData(vtkInformation *, vtkInformationVector **, vtkInformationVector *); + void AttachCellFieldsOn(vtkUnstructuredGrid *, vtkCellData *, int); + double ShrinkFactor; + +private: + vtkELNOFilter(const vtkELNOFilter&); + void operator =(const vtkELNOFilter&); +}; +#endif diff --git a/src/Plugins/MEDReader/plugin/MEDReaderIO/vtkELNOMeshFilter.cxx b/src/Plugins/MEDReader/plugin/MEDReaderIO/vtkELNOMeshFilter.cxx new file mode 100644 index 00000000..c7d3798e --- /dev/null +++ b/src/Plugins/MEDReader/plugin/MEDReaderIO/vtkELNOMeshFilter.cxx @@ -0,0 +1,212 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// + +#include "vtkELNOMeshFilter.h" +#include "vtkInformation.h" +#include "vtkInformationVector.h" +#include "vtkInformationIntegerKey.h" +#include "vtkObjectFactory.h" +#include "vtkPolyDataAlgorithm.h" +#include "vtkPolyData.h" +#include "vtkIdTypeArray.h" +#include "vtkQuadratureSchemeDefinition.h" +#include "vtkInformationQuadratureSchemeDefinitionVectorKey.h" +#include "vtkUnstructuredGrid.h" +#include "vtkShrinkFilter.h" +#include "vtkSmartPointer.h" +#include "vtkPointData.h" +#include "vtkCellData.h" +#include "vtkIdList.h" +#include "vtkCell.h" + +#include "MEDUtilities.hxx" + +#include + +vtkStandardNewMacro(vtkELNOMeshFilter); + +vtkELNOMeshFilter::vtkELNOMeshFilter():ShrinkFactor(0.9999) +{ +} + +vtkELNOMeshFilter::~vtkELNOMeshFilter() +{ +} + +int vtkELNOMeshFilter::RequestData(vtkInformation *request, + vtkInformationVector **input, vtkInformationVector *output) +{ + vtkUnstructuredGrid *usgIn = vtkUnstructuredGrid::SafeDownCast( + input[0]->GetInformationObject(0)->Get(vtkDataObject::DATA_OBJECT())); + + vtkUnstructuredGrid *usgOut = vtkUnstructuredGrid::SafeDownCast( + output->GetInformationObject(0)->Get(vtkDataObject::DATA_OBJECT())); + + if(usgIn == NULL || usgOut == NULL) + { + vtkDebugMacro("vtkELNOMeshFilter not correctly configured : Invalid input or output !"); + return 0; + } + + // creates offsets array + + // first shrink the input + vtkUnstructuredGrid* usgInClone = usgIn->NewInstance(); + usgInClone->ShallowCopy(usgIn); + vtkSmartPointer shrink(vtkSmartPointer::New()); + shrink->SetInputData(usgInClone); + shrink->SetShrinkFactor(this->ShrinkFactor); + shrink->Update(); + vtkUnstructuredGrid *shrinked(shrink->GetOutput()); + usgInClone->Delete(); + usgOut->ShallowCopy(shrinked); + // OK for the output + + // now copy ELNO data. Start by verifying if it is possible to + // shallow copy the array. + vtkInformation *info(usgIn->GetInformation()); + // + vtkIdType nVerts(shrinked->GetNumberOfPoints()),ncell(usgIn->GetNumberOfCells()); + // first loop through all cells to check if a shallow copy is possible + bool shallowok(true);// Anthony : checks that shrink works well. Really necessary ? + vtkIdType previous(0),offset(0); + + for(vtkIdType cellId = 0; cellId < ncell; cellId++) + { + if(offset != previous) + { + shallowok = false; + break; + } + vtkCell *cell(usgIn->GetCell(cellId)); + vtkIdType nbptsInCell(cell->GetNumberOfPoints()); + previous = offset + nbptsInCell; + // + offset += nbptsInCell ; + } + // + if(shallowok) + shallowok = (previous == nVerts); + + vtkFieldData *fielddata(usgIn->GetFieldData()); + for(int index = 0; index < fielddata->GetNumberOfArrays(); index++) + { + vtkDataArray *data(fielddata->GetArray(index)); + vtkQuadratureSchemeDefinition **dict = 0; + vtkInformationQuadratureSchemeDefinitionVectorKey *key(vtkQuadratureSchemeDefinition::DICTIONARY()); + if(key->Has(data->GetInformation())) + { + int dictSize(key->Size(data->GetInformation())); + dict=new vtkQuadratureSchemeDefinition *[dictSize]; + key->GetRange(data->GetInformation(),dict,0,0,dictSize); + } + if(data == NULL) + { + delete [] dict; + continue; + } + + vtkInformation *info(data->GetInformation()); + const char *arrayOffsetName(info->Get(vtkQuadratureSchemeDefinition::QUADRATURE_OFFSET_ARRAY_NAME())); + vtkIdTypeArray *offData(0); + bool isELGA(false),isELNO(false); + + if(arrayOffsetName) + { + vtkFieldData *cellData(usgIn->GetCellData()); + vtkDataArray *offDataTmp(cellData->GetArray(arrayOffsetName)); + isELGA=offDataTmp->GetInformation()->Get(MEDUtilities::ELGA())==1; + isELNO=offDataTmp->GetInformation()->Get(MEDUtilities::ELNO())==1; + offData=dynamic_cast(offDataTmp); + } + + if(arrayOffsetName == NULL || isELGA) + { + if(shallowok && data->GetNumberOfTuples()==nVerts )// Anthony : is it not a little confusing to assign a FieldData on Points because the number of tuples fits the number of nodes of shrinked mesh ? + usgOut->GetPointData()->AddArray(data); + else + shrinked->GetFieldData()->AddArray(data); + delete [] dict; + continue; + } + else + { + vtkDataArray *newArray(data->NewInstance()); + newArray->SetName(data->GetName()); + usgOut->GetPointData()->AddArray(newArray); + newArray->SetNumberOfComponents(data->GetNumberOfComponents()); + newArray->SetNumberOfTuples(usgOut->GetNumberOfPoints()); + newArray->CopyComponentNames(data); + newArray->Delete(); + if(isELGA) + { + vtkIdList *ids(vtkIdList::New()); + vtkIdType offset(0); + for(vtkIdType cellId=0;cellIdGetCellType(cellId)); + shrinked->GetCellPoints(cellId, ids); + for(int id = 0; id < dict[cellType]->GetNumberOfQuadraturePoints(); id++) + { + const double * w = dict[cellType]->GetShapeFunctionWeights(id); + int j; + for(j = 0; j < dict[cellType]->GetNumberOfNodes(); j++) + { + if(w[j] == 1.0) + break; + } + if(j == dict[cellType]->GetNumberOfNodes()) + { + j = id; + } + newArray->SetTuple(ids->GetId(id), offset + j, data); + } + vtkCell *cell(usgIn->GetCell(cellId)); + vtkIdType nbptsInCell(cell->GetNumberOfPoints()); + offset+=nbptsInCell; + } + ids->FastDelete(); + } + else if(offData && isELNO) + { + vtkIdType *offsetPtr(offData->GetPointer(0)); + vtkIdType zeId(0); + for(vtkIdType cellId=0;cellIdGetCell(cellId)); + vtkIdType nbPoints(cell->GetNumberOfPoints()),offset(offsetPtr[cellId]); + for(vtkIdType j=0;jSetTuple(zeId,offsetPtr[cellId]+j,data); + } + } + else + { + delete [] dict; + continue ; + } + } + delete [] dict; + } + return 1; +} + +void vtkELNOMeshFilter::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os, indent); +} diff --git a/src/Plugins/MEDReader/plugin/MEDReaderIO/vtkELNOMeshFilter.h b/src/Plugins/MEDReader/plugin/MEDReaderIO/vtkELNOMeshFilter.h new file mode 100644 index 00000000..f0045c3a --- /dev/null +++ b/src/Plugins/MEDReader/plugin/MEDReaderIO/vtkELNOMeshFilter.h @@ -0,0 +1,46 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// + +#ifndef _vtkELNOMeshFilter_h +#define _vtkELNOMeshFilter_h + +#include "vtkUnstructuredGridAlgorithm.h" + +class VTK_EXPORT vtkELNOMeshFilter: public vtkUnstructuredGridAlgorithm +{ +public: + static vtkELNOMeshFilter *New(); + vtkTypeMacro(vtkELNOMeshFilter,vtkUnstructuredGridAlgorithm); + void PrintSelf(ostream& os, vtkIndent indent); + + vtkGetMacro(ShrinkFactor, double); + vtkSetMacro(ShrinkFactor, double); +protected: + vtkELNOMeshFilter(); + ~vtkELNOMeshFilter(); + + int RequestData(vtkInformation *, vtkInformationVector **, + vtkInformationVector *); +private: + vtkELNOMeshFilter(const vtkELNOMeshFilter&); + void operator =(const vtkELNOMeshFilter&); +private: + double ShrinkFactor; +}; +#endif diff --git a/src/Plugins/MEDReader/plugin/MEDReaderIO/vtkELNOSurfaceFilter.cxx b/src/Plugins/MEDReader/plugin/MEDReaderIO/vtkELNOSurfaceFilter.cxx new file mode 100644 index 00000000..c5c92516 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/MEDReaderIO/vtkELNOSurfaceFilter.cxx @@ -0,0 +1,222 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// + +#include "vtkELNOSurfaceFilter.h" +#include "vtkInformation.h" +#include "vtkInformationVector.h" +#include "vtkObjectFactory.h" +#include "vtkPolyDataAlgorithm.h" +#include "vtkPolyData.h" +#include "vtkIdTypeArray.h" +#include "vtkInformationQuadratureSchemeDefinitionVectorKey.h" +#include "vtkQuadratureSchemeDefinition.h" +#include "vtkUnstructuredGrid.h" +#include "vtkPVGeometryFilter.h" +#include "vtkShrinkFilter.h" +#include "vtkSmartPointer.h" +#include "vtkPointData.h" +#include "vtkCellData.h" +#include "vtkIdList.h" + +//vtkCxxRevisionMacro(vtkELNOSurfaceFilter, "$Revision$") +//; +vtkStandardNewMacro(vtkELNOSurfaceFilter) +; + +vtkELNOSurfaceFilter::vtkELNOSurfaceFilter() +{ +} + +vtkELNOSurfaceFilter::~vtkELNOSurfaceFilter() +{ +} + +int vtkELNOSurfaceFilter::RequestData(vtkInformation *request, vtkInformationVector **input, vtkInformationVector *output) +{ + vtkUnstructuredGrid *usgIn=vtkUnstructuredGrid::SafeDownCast( + input[0]->GetInformationObject(0)->Get(vtkDataObject::DATA_OBJECT())); + + vtkUnstructuredGrid *usgOut=vtkUnstructuredGrid::SafeDownCast( + output->GetInformationObject(0)->Get(vtkDataObject::DATA_OBJECT())); + + vtkIdTypeArray* usg_offsets=vtkIdTypeArray::SafeDownCast( + this->GetInputArrayToProcess(0, input)); + + if(usgIn==NULL||usg_offsets==NULL||usgOut==NULL) + { + vtkDebugMacro("vtkELNOSurfaceFilter no correctly configured : offsets = " << usg_offsets); + return 1; + } + + // first shrink the input + vtkUnstructuredGrid* usgInClone=usgIn->NewInstance(); + + usgInClone->ShallowCopy(usgIn); + + vtkSmartPointer geomFilter=vtkSmartPointer< + vtkPVGeometryFilter>::New(); + geomFilter->SetInputData(usgInClone); + geomFilter->SetPassThroughCellIds(1); + geomFilter->SetPassThroughPointIds(1); + geomFilter->SetUseOutline(0); + geomFilter->Update(); + + vtkPolyData* surface=vtkPolyData::SafeDownCast(geomFilter->GetOutput()); + vtkIdTypeArray* originalCellIds=vtkIdTypeArray::SafeDownCast( + surface->GetCellData()->GetArray("vtkOriginalCellIds")); + vtkIdTypeArray* originalPointIds=vtkIdTypeArray::SafeDownCast( + surface->GetPointData()->GetArray("vtkOriginalPointIds")); + + if( originalCellIds == NULL ) + { + vtkErrorMacro("vtkPVGeometryFilter return NULL 'vtkOriginalCellIds' array"); + return 0; + } + + if(originalPointIds==NULL) + { + vtkErrorMacro("It appears that your dataset is not reduced using vtkPVGeometryFilter (NULL 'vtkOriginalPointIds).\n==================================================================================================\nProbably your dataset is not 3D.\nIf it is not a 3D dataset you are expected to use ELNO Mesh filter instead of ELNO Surface filter.\n==================================================================================================\n"); + return 0; + } + + vtkSmartPointer shrink= + vtkSmartPointer::New(); + shrink->SetInputConnection(geomFilter->GetOutputPort(0)); + shrink->SetShrinkFactor(0.9999); + shrink->Update(); + + vtkUnstructuredGrid* shrinked=shrink->GetOutput(); + + usgInClone->Delete(); + + usgOut->ShallowCopy(shrinked); + + vtkIdTypeArray* offsets=vtkIdTypeArray::SafeDownCast( + shrinked->GetCellData()->GetArray(usg_offsets->GetName())); + + // now copy ELNO data. Start by verifying if it is possible to + // shallow copy the array. + vtkInformation *info=offsets->GetInformation(); + vtkInformationQuadratureSchemeDefinitionVectorKey *key= + vtkQuadratureSchemeDefinition::DICTIONARY(); + if(!key->Has(info)) + { + vtkDebugMacro("Dictionary is not present in array " << offsets->GetName() + << " " << offsets << " Aborting." ); + return 0; + } + int dictSize=key->Size(info); + vtkQuadratureSchemeDefinition **dict= + new vtkQuadratureSchemeDefinition *[dictSize]; + key->GetRange(info, dict, 0, 0, dictSize); + + vtkIdType ncell=shrinked->GetNumberOfCells(); + + vtkFieldData* fielddata=usgIn->GetFieldData(); + vtkIdList *ids=vtkIdList::New(); + vtkIdList *surfaceIds=vtkIdList::New(); + vtkIdList *originalIds=vtkIdList::New(); + for(int index=0; indexGetNumberOfArrays(); index++) + { + vtkDataArray* data=fielddata->GetArray(index); + if(data==NULL) + continue; + + vtkInformation* info=data->GetInformation(); + const char* arrayOffsetName=info->Get( + vtkQuadratureSchemeDefinition::QUADRATURE_OFFSET_ARRAY_NAME()); + + if(arrayOffsetName == NULL || + strcmp(arrayOffsetName, offsets->GetName())!=0) + { + usgOut->GetFieldData()->AddArray(data); + + continue; + } + + vtkDataArray* newArray=data->NewInstance(); + newArray->SetName(data->GetName()); + usgOut->GetPointData()->AddArray(newArray); + newArray->SetNumberOfComponents(data->GetNumberOfComponents()); + newArray->SetNumberOfTuples(usgOut->GetNumberOfPoints()); + newArray->CopyComponentNames(data); + newArray->Delete(); + + for(vtkIdType cellId=0; cellIdGetValue(cellId); + + vtkIdType originalCellId=originalCellIds->GetValue(cellId); + int originalCellType=usgIn->GetCellType(originalCellId); + + shrinked->GetCellPoints(cellId, ids); + surface->GetCellPoints(cellId, surfaceIds); + + for(int id=0; idGetNumberOfIds(); id++) + { + vtkIdType surfaceId=surfaceIds->GetId(id); + vtkIdType shrinkedId=ids->GetId(id); + vtkIdType originalPointId = originalPointIds->GetValue(surfaceId); + + usgIn->GetCellPoints(originalCellId, originalIds); + int originalLocalId=-1; + for(int li=0; liGetNumberOfIds(); li++) + { + if(originalPointId==originalIds->GetId(li)) + { + originalLocalId=li; + break; + } + } + if(originalLocalId==-1) + { + originalLocalId=0; + vtkErrorMacro("cannot find original id"); + } + + const double * w=dict[originalCellType]->GetShapeFunctionWeights( + originalLocalId); + int j; + for(j=0; jGetNumberOfNodes(); j++) + { + if(w[j]==1.0) + break; + } + if(j==dict[originalCellType]->GetNumberOfNodes()) + { + //vtkErrorMacro("cannot find elno weigth."); + j=id; + } + newArray->SetTuple(shrinkedId, offset+j, data); + } + } + } + + ids->FastDelete(); + surfaceIds->FastDelete(); + originalIds->FastDelete(); + delete[] dict; + + return 1; +} + +void vtkELNOSurfaceFilter::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os, indent); +} diff --git a/src/Plugins/MEDReader/plugin/MEDReaderIO/vtkELNOSurfaceFilter.h b/src/Plugins/MEDReader/plugin/MEDReaderIO/vtkELNOSurfaceFilter.h new file mode 100644 index 00000000..99de2d47 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/MEDReaderIO/vtkELNOSurfaceFilter.h @@ -0,0 +1,43 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// + +#ifndef _vtkELNOSurfaceFilter_h +#define _vtkELNOSurfaceFilter_h + +#include "vtkUnstructuredGridAlgorithm.h" + +class VTK_EXPORT vtkELNOSurfaceFilter: public vtkUnstructuredGridAlgorithm +{ +public: + static vtkELNOSurfaceFilter *New(); + vtkTypeMacro(vtkELNOSurfaceFilter,vtkUnstructuredGridAlgorithm); + void PrintSelf(ostream& os, vtkIndent indent); + +protected: + vtkELNOSurfaceFilter(); + ~vtkELNOSurfaceFilter(); + + int RequestData(vtkInformation *, vtkInformationVector **, + vtkInformationVector *); + +private: + vtkELNOSurfaceFilter(const vtkELNOSurfaceFilter&); + void operator =(const vtkELNOSurfaceFilter&); +}; +#endif diff --git a/src/Plugins/MEDReader/plugin/MEDReaderIO/vtkExtractCellType.cxx b/src/Plugins/MEDReader/plugin/MEDReaderIO/vtkExtractCellType.cxx new file mode 100644 index 00000000..af4d2465 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/MEDReaderIO/vtkExtractCellType.cxx @@ -0,0 +1,483 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay + +#include "vtkExtractCellType.h" +#include "MEDFileFieldRepresentationTree.hxx" +#include "MEDFileFieldOverView.hxx" + +#include "vtkAdjacentVertexIterator.h" +#include "vtkDataArrayTemplate.h" +#include "vtkIntArray.h" +#include "vtkCellData.h" +#include "vtkPointData.h" + +#include "vtkStreamingDemandDrivenPipeline.h" +#include "vtkUnstructuredGrid.h" +#include "vtkMultiBlockDataSet.h" + +#include "vtkInformationStringKey.h" +#include "vtkAlgorithmOutput.h" +#include "vtkObjectFactory.h" +#include "vtkMutableDirectedGraph.h" +#include "vtkMultiBlockDataSet.h" +#include "vtkDataSet.h" +#include "vtkInformationVector.h" +#include "vtkInformation.h" +#include "vtkDataArraySelection.h" +#include "vtkTimeStamp.h" +#include "vtkInEdgeIterator.h" +#include "vtkInformationDataObjectKey.h" +#include "vtkExecutive.h" +#include "vtkVariantArray.h" +#include "vtkStringArray.h" +#include "vtkDoubleArray.h" +#include "vtkCharArray.h" +#include "vtkUnsignedCharArray.h" +#include "vtkDataSetAttributes.h" +#include "vtkDemandDrivenPipeline.h" +#include "vtkDataObjectTreeIterator.h" +#include "vtkThreshold.h" + +#include +#include + +vtkStandardNewMacro(vtkExtractCellType); + +vtkCxxSetObjectMacro(vtkExtractCellType, SIL, vtkMutableDirectedGraph); + +/////////////////// + +class ExtractCellTypeStatus +{ +public: + ExtractCellTypeStatus():_status(false),_vtkt(-1),_mct(INTERP_KERNEL::NORM_ERROR) { } + ExtractCellTypeStatus(int vtkt, INTERP_KERNEL::NormalizedCellType mct); + bool isSame(int vtkt, INTERP_KERNEL::NormalizedCellType mct) const { return _vtkt==vtkt && _mct==mct; } + bool getStatus() const { return _status; } + void setStatus(bool status) const { _status=status; } + void cpyStatusFrom(const ExtractCellTypeStatus& other) { _status=other._status; } + std::string getKey() const { return _type_str; } + const char *getKeyOfEntry() const { return _type_str.c_str(); } + int getVTKCellType() const { return _vtkt; } + void printMySelf(std::ostream& os) const; + bool isSameAs(const ExtractCellTypeStatus& other) const; + void feedSIL(vtkMutableDirectedGraph *sil, vtkIdType root, vtkVariantArray *childEdge, std::vector& names) const; +protected: + mutable bool _status; + int _vtkt; + INTERP_KERNEL::NormalizedCellType _mct; + std::string _type_str; +}; + +class vtkExtractCellType::vtkExtractCellTypeInternal +{ +public: + vtkExtractCellTypeInternal():_ref_mtime(0) { } + int getNumberOfEntries() const; + const char *getKeyOfEntry(int i) const; + bool getStatusOfEntryStr(const char *entry) const; + void setStatusOfEntryStr(const char *entry, bool status) const; + void feedSIL(vtkMutableDirectedGraph *sil) const; + std::vector getIdsToKeep() const; + void printMySelf(std::ostream& os) const; + bool setRefTime(vtkObject *input) const; + // non const methods + void loadFrom(const std::map& m); +private: + const ExtractCellTypeStatus& getEntry(const char *entry) const; + bool checkSame(const std::map& m) const; +private: + std::vector _types; + mutable unsigned long _ref_mtime; +}; + +bool vtkExtractCellType::vtkExtractCellTypeInternal::setRefTime(vtkObject *input) const +{ + unsigned long mtime(input->GetMTime()); + if(mtime>_ref_mtime) + { + _ref_mtime=mtime; + return true; + } + else + return false; +} + +std::vector vtkExtractCellType::vtkExtractCellTypeInternal::getIdsToKeep() const +{ + std::vector ret; + for(std::vector::const_iterator it=_types.begin();it!=_types.end();it++) + { + if((*it).getStatus()) + ret.push_back((*it).getVTKCellType()); + } + return ret; +} + +void vtkExtractCellType::vtkExtractCellTypeInternal::feedSIL(vtkMutableDirectedGraph *sil) const +{ + vtkSmartPointer childEdge(vtkSmartPointer::New()); + childEdge->InsertNextValue(0); + vtkSmartPointer crossEdge(vtkSmartPointer::New()); + crossEdge->InsertNextValue(1); + // CrossEdge is an edge linking hierarchies. + vtkUnsignedCharArray* crossEdgesArray=vtkUnsignedCharArray::New(); + crossEdgesArray->SetName("CrossEdges"); + sil->GetEdgeData()->AddArray(crossEdgesArray); + crossEdgesArray->Delete(); + std::vector names; + // Add global fields root + vtkIdType root(sil->AddVertex()); + names.push_back("CellTypesTree"); + // + for(std::vector::const_iterator it=_types.begin();it!=_types.end();it++) + { + (*it).feedSIL(sil,root,childEdge,names); + } + // This array is used to assign names to nodes. + vtkStringArray *namesArray(vtkStringArray::New()); + namesArray->SetName("Names"); + namesArray->SetNumberOfTuples(sil->GetNumberOfVertices()); + sil->GetVertexData()->AddArray(namesArray); + namesArray->Delete(); + std::vector::const_iterator iter; + vtkIdType cc; + for(cc=0, iter=names.begin(); iter!=names.end(); ++iter, ++cc) + namesArray->SetValue(cc,(*iter).c_str()); +} + +void vtkExtractCellType::vtkExtractCellTypeInternal::loadFrom(const std::map& m) +{ + if(checkSame(m)) + return; + // + std::size_t sz(m.size()),ii(0); + _types.resize(sz); + for(std::map::const_iterator it=m.begin();it!=m.end();it++,ii++) + { + ExtractCellTypeStatus elt((*it).first,(*it).second); + _types[ii]=elt; + } +} + +int vtkExtractCellType::vtkExtractCellTypeInternal::getNumberOfEntries() const +{ + return (int) _types.size(); +} + +const char *vtkExtractCellType::vtkExtractCellTypeInternal::getKeyOfEntry(int i) const +{ + return _types[i].getKeyOfEntry(); +} + +bool vtkExtractCellType::vtkExtractCellTypeInternal::checkSame(const std::map& m) const +{ + std::size_t sz(m.size()); + if(sz!=_types.size()) + return false; + bool ret(true); + std::map::const_iterator it(m.begin()); + for(std::size_t i=0;i::const_iterator it0=_types.begin();it0!=_types.end();it0++) + if(entryCpp==(*it0).getKey()) + return *it0; + std::ostringstream oss; oss << "vtkExtractCellTypeInternal::getEntry : no such entry \"" << entry << "\"!"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); +} + +bool vtkExtractCellType::vtkExtractCellTypeInternal::getStatusOfEntryStr(const char *entry) const +{ + try + { + const ExtractCellTypeStatus& elt(getEntry(entry)); + return elt.getStatus(); + } + catch (INTERP_KERNEL::Exception e) + { + //std::cerr << vtkDebugMacro"Exception has been thrown in vtkExtractCellType::vtkExtractCellTypeInternal::getStatusOfEntryStr : " << e.what() << std::endl; + return false; + } +} + +void vtkExtractCellType::vtkExtractCellTypeInternal::setStatusOfEntryStr(const char *entry, bool status) const +{ + try + { + const ExtractCellTypeStatus& elt(getEntry(entry)); + elt.setStatus(status); + } + catch (INTERP_KERNEL::Exception e) + { + //std::cerr << "Exception has been thrown in vtkExtractCellType::vtkExtractCellTypeInternal::setStatusOfEntryStr : " << e.what() << std::endl; + } +} + +void vtkExtractCellType::vtkExtractCellTypeInternal::printMySelf(std::ostream& os) const +{ + for(std::vector::const_iterator it0=_types.begin();it0!=_types.end();it0++) + (*it0).printMySelf(os); +} + +ExtractCellTypeStatus::ExtractCellTypeStatus(int vtkt, INTERP_KERNEL::NormalizedCellType mct):_status(false),_vtkt(vtkt),_mct(mct) +{ + std::string name(INTERP_KERNEL::CellModel::GetCellModel(mct).getRepr()); + _type_str=name.substr(5);//skip "NORM_" +} + +void ExtractCellTypeStatus::printMySelf(std::ostream& os) const +{ + os << " -" << _type_str << "("; + if(_status) + os << "X"; + else + os << " "; + os << ")" << std::endl; +} + +bool ExtractCellTypeStatus::isSameAs(const ExtractCellTypeStatus& other) const +{ + return _vtkt==other._vtkt && _mct==other._mct; +} + +void ExtractCellTypeStatus::feedSIL(vtkMutableDirectedGraph *sil, vtkIdType root, vtkVariantArray *childEdge, std::vector& names) const +{ + vtkIdType InfoGeoType(sil->AddChild(root,childEdge)); + names.push_back(_type_str); + vtkIdType InfoVTKID(sil->AddChild(InfoGeoType,childEdge)); + std::ostringstream oss; oss << _vtkt; + names.push_back(oss.str()); +} + +//////////////////// + +vtkExtractCellType::vtkExtractCellType():SIL(NULL),Internal(new vtkExtractCellTypeInternal),InsideOut(0) +{ +} + +vtkExtractCellType::~vtkExtractCellType() +{ + if(this->SIL) + this->SIL->Delete(); + delete this->Internal; +} + +void vtkExtractCellType::SetInsideOut(int val) +{ + if(this->InsideOut!=val) + { + this->InsideOut=val; + this->Modified(); + } +} + +int vtkExtractCellType::RequestInformation(vtkInformation *request, vtkInformationVector **inputVector, vtkInformationVector *outputVector) +{ + try + { + //std::cerr << "########################################## vtkExtractCellType::RequestInformation ##########################################" << std::endl; + vtkInformation *outInfo(outputVector->GetInformationObject(0)); + vtkInformation *inputInfo(inputVector[0]->GetInformationObject(0)); + vtkDataSet *input(0); + { + vtkDataObject *inp(inputInfo->Get(vtkDataObject::DATA_OBJECT())); + if(vtkDataSet::SafeDownCast(inp)) + input=vtkDataSet::SafeDownCast(inp); + else + { + vtkMultiBlockDataSet *inputTmp(vtkMultiBlockDataSet::SafeDownCast(inp)); + if(inputTmp) + { + if(inputTmp->GetNumberOfBlocks()!=1) + { + vtkDebugMacro("vtkExtractCellType::RequestInformation : input vtkMultiBlockDataSet must contain exactly 1 block !"); + return 0; + } + vtkDataSet *blk0(vtkDataSet::SafeDownCast(inputTmp->GetBlock(0))); + if(!blk0) + { + vtkDebugMacro("vtkExtractCellType::RequestInformation : the single block in input vtkMultiBlockDataSet must be a vtkDataSet instance !"); + return 0; + } + input=blk0; + } + else + { + vtkDebugMacro("vtkExtractCellType::RequestInformation : supported input are vtkDataSet or vtkMultiBlockDataSet !"); + return 0; + } + } + } + if(this->Internal->setRefTime(input)) + { + vtkIdType nbOfCells(input->GetNumberOfCells()); + std::map m; + for(vtkIdType cellId=0;cellIdGetCellType(cellId)); + const std::map::const_iterator it(m.find(vtkCt)); + if(it==m.end()) + { + const unsigned char *pos(std::find(MEDCoupling::MEDMeshMultiLev::PARAMEDMEM_2_VTKTYPE,MEDCoupling::MEDMeshMultiLev::PARAMEDMEM_2_VTKTYPE+MEDCoupling::MEDMeshMultiLev::PARAMEDMEM_2_VTKTYPE_LGTH,vtkCt)); + if(pos==MEDCoupling::MEDMeshMultiLev::PARAMEDMEM_2_VTKTYPE+MEDCoupling::MEDMeshMultiLev::PARAMEDMEM_2_VTKTYPE_LGTH) + { + vtkDebugMacro("vtkExtractCellType::RequestInformation : cell #" << cellId << " has unrecognized type !"); + return 0; + } + m[vtkCt]=(INTERP_KERNEL::NormalizedCellType)std::distance(MEDCoupling::MEDMeshMultiLev::PARAMEDMEM_2_VTKTYPE,pos); + } + } + this->Internal->loadFrom(m); + if(this->SIL) + this->SIL->Delete(); + this->SIL=vtkMutableDirectedGraph::New(); + this->Internal->feedSIL(this->SIL); + // + outInfo->Set(vtkDataObject::SIL(),this->SIL); + } + } + catch(INTERP_KERNEL::Exception& e) + { + std::cerr << "Exception has been thrown in vtkExtractCellType::RequestInformation : " << e.what() << std::endl; + return 0; + } + return 1; +} + +vtkDataSet *FilterFamilies(vtkDataSet *input, const std::vector& idsToKeep, bool insideOut) +{ + const int VTK_DATA_ARRAY_DELETE=vtkDataArrayTemplate::VTK_DATA_ARRAY_DELETE; + const char ZE_SELECTION_ARR_NAME[]="@@ZeSelection@@"; + vtkDataSet *output(input->NewInstance()); + output->ShallowCopy(input); + vtkSmartPointer thres(vtkSmartPointer::New()); + thres->SetInputData(output); + vtkDataSetAttributes *dscIn(input->GetCellData()),*dscIn2(input->GetPointData()); + vtkDataSetAttributes *dscOut(output->GetCellData()),*dscOut2(output->GetPointData()); + // + double vMin(insideOut==0?1.:0.),vMax(insideOut==0?2.:1.); + thres->ThresholdBetween(vMin,vMax); + // OK for the output + vtkIdType nbOfCells(input->GetNumberOfCells()); + vtkCharArray *zeSelection(vtkCharArray::New()); + zeSelection->SetName(ZE_SELECTION_ARR_NAME); + zeSelection->SetNumberOfComponents(1); + char *pt(new char[nbOfCells]); + zeSelection->SetArray(pt,nbOfCells,0,VTK_DATA_ARRAY_DELETE); + std::fill(pt,pt+nbOfCells,0); + std::vector pt2(nbOfCells,false); + for(std::vector::const_iterator it=idsToKeep.begin();it!=idsToKeep.end();it++) + { + for(vtkIdType ii=0;iiGetCellType(ii)==*it) + pt2[ii]=true; + } + } + for(int ii=0;iiGetCellData()->AddArray(zeSelection)); + output->GetCellData()->SetActiveAttribute(idx,vtkDataSetAttributes::SCALARS); + output->GetCellData()->CopyScalarsOff(); + zeSelection->Delete(); + // + thres->SetInputArrayToProcess(idx,0,0,"vtkDataObject::FIELD_ASSOCIATION_CELLS",ZE_SELECTION_ARR_NAME); + thres->Update(); + vtkUnstructuredGrid *zeComputedOutput(thres->GetOutput()); + zeComputedOutput->GetCellData()->RemoveArray(idx); + output->Delete(); + zeComputedOutput->Register(0); + return zeComputedOutput; +} + +int vtkExtractCellType::RequestData(vtkInformation *request, vtkInformationVector **inputVector, vtkInformationVector *outputVector) +{ + try + { + //std::cerr << "########################################## vtkExtractCellType::RequestData ##########################################" << std::endl; + vtkInformation* inputInfo=inputVector[0]->GetInformationObject(0); + vtkDataSet *input(vtkDataSet::SafeDownCast(inputInfo->Get(vtkDataObject::DATA_OBJECT()))); + vtkInformation *info(input->GetInformation()); + vtkInformation *outInfo(outputVector->GetInformationObject(0)); + vtkDataSet *output(vtkDataSet::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT()))); + std::vector idsToKeep(this->Internal->getIdsToKeep()); + vtkDataSet *tryOnCell(FilterFamilies(input,idsToKeep,this->InsideOut)); + // first shrink the input + output->ShallowCopy(tryOnCell); + tryOnCell->Delete(); + } + catch(INTERP_KERNEL::Exception& e) + { + std::cerr << "Exception has been thrown in vtkExtractCellType::RequestData : " << e.what() << std::endl; + return 0; + } + return 1; +} + +int vtkExtractCellType::GetSILUpdateStamp() +{ + return (int)this->SILTime; +} + +void vtkExtractCellType::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os, indent); +} + +int vtkExtractCellType::GetNumberOfGeoTypesArrays() +{ + int ret(this->Internal->getNumberOfEntries()); + //std::cerr << "vtkExtractCellType::GetNumberOfGeoTypesArrays() -> " << ret << std::endl; + return ret; +} + +const char *vtkExtractCellType::GetGeoTypesArrayName(int index) +{ + const char *ret(this->Internal->getKeyOfEntry(index)); + //std::cerr << "vtkExtractCellType::GetGeoTypesArrayName(" << index << ") -> " << ret << std::endl; + return ret; +} + +int vtkExtractCellType::GetGeoTypesArrayStatus(const char *name) +{ + int ret((int)this->Internal->getStatusOfEntryStr(name)); + //std::cerr << "vtkExtractCellType::GetGeoTypesArrayStatus(" << name << ") -> " << ret << std::endl; + return ret; +} + +void vtkExtractCellType::SetGeoTypesStatus(const char *name, int status) +{ + //std::cerr << "vtkExtractCellType::SetGeoTypesStatus(" << name << "," << status << ")" << std::endl; + if (GetNumberOfGeoTypesArrays()<1) + return; + this->Internal->setStatusOfEntryStr(name,(bool)status); + if(std::string(name)==GetGeoTypesArrayName(GetNumberOfGeoTypesArrays()-1)) + { + this->Modified(); + //this->Internal->printMySelf(std::cerr); + } +} diff --git a/src/Plugins/MEDReader/plugin/MEDReaderIO/vtkExtractCellType.h b/src/Plugins/MEDReader/plugin/MEDReaderIO/vtkExtractCellType.h new file mode 100644 index 00000000..560c0cdb --- /dev/null +++ b/src/Plugins/MEDReader/plugin/MEDReaderIO/vtkExtractCellType.h @@ -0,0 +1,71 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay + +#ifndef vtkExtractCellType_h__ +#define vtkExtractCellType_h__ + +#include "vtkDataSetAlgorithm.h" + +class vtkMutableDirectedGraph; + +class VTK_EXPORT vtkExtractCellType : public vtkDataSetAlgorithm +{ +public: + static vtkExtractCellType* New(); + vtkTypeMacro(vtkExtractCellType, vtkDataSetAlgorithm) + void PrintSelf(ostream& os, vtkIndent indent); + virtual int GetNumberOfGeoTypesArrays(); + const char *GetGeoTypesArrayName(int index); + int GetGeoTypesArrayStatus(const char *name); + virtual void SetGeoTypesStatus(const char *name, int status); + void SetInsideOut(int val); + // Description: + // Every time the SIL is updated a this will return a different value. + virtual int GetSILUpdateStamp(); + +protected: + vtkExtractCellType(); + ~vtkExtractCellType(); + + int RequestInformation(vtkInformation *request, + vtkInformationVector **inputVector, vtkInformationVector *outputVector); + + int RequestData(vtkInformation *request, vtkInformationVector **inputVector, + vtkInformationVector *outputVector); + // Description: + // This SIL stores the structure of the mesh/groups/cell types + // that can be selected. + virtual void SetSIL(vtkMutableDirectedGraph*); + vtkGetObjectMacro(SIL, vtkMutableDirectedGraph); +protected: + vtkMutableDirectedGraph *SIL; + vtkTimeStamp SILTime; +private: + vtkExtractCellType(const vtkExtractCellType&); + void operator=(const vtkExtractCellType&); // Not implemented. + private: + //BTX + //ETX + class vtkExtractCellTypeInternal; + vtkExtractCellTypeInternal *Internal; + int InsideOut; +}; + +#endif diff --git a/src/Plugins/MEDReader/plugin/MEDReaderIO/vtkExtractGroup.cxx b/src/Plugins/MEDReader/plugin/MEDReaderIO/vtkExtractGroup.cxx new file mode 100644 index 00000000..7bf32f5d --- /dev/null +++ b/src/Plugins/MEDReader/plugin/MEDReaderIO/vtkExtractGroup.cxx @@ -0,0 +1,739 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay + +#include "vtkExtractGroup.h" +#include "MEDFileFieldRepresentationTree.hxx" +#include "vtkMEDReader.h" +#include "VTKMEDTraits.hxx" + +#include "vtkAdjacentVertexIterator.h" +#include "vtkDataArrayTemplate.h" +#include "vtkIntArray.h" +#include "vtkLongArray.h" +#ifdef WIN32 +#include "vtkLongLongArray.h" +#endif +#include "vtkCellData.h" +#include "vtkPointData.h" + +#include "vtkStreamingDemandDrivenPipeline.h" +#include "vtkUnstructuredGrid.h" +#include "vtkMultiBlockDataSet.h" + +#include "vtkInformationStringKey.h" +#include "vtkAlgorithmOutput.h" +#include "vtkObjectFactory.h" +#include "vtkMutableDirectedGraph.h" +#include "vtkMultiBlockDataSet.h" +#include "vtkDataSet.h" +#include "vtkInformationVector.h" +#include "vtkInformation.h" +#include "vtkDataArraySelection.h" +#include "vtkTimeStamp.h" +#include "vtkInEdgeIterator.h" +#include "vtkInformationDataObjectKey.h" +#include "vtkExecutive.h" +#include "vtkVariantArray.h" +#include "vtkStringArray.h" +#include "vtkDoubleArray.h" +#include "vtkCharArray.h" +#include "vtkUnsignedCharArray.h" +#include "vtkDataSetAttributes.h" +#include "vtkDemandDrivenPipeline.h" +#include "vtkDataObjectTreeIterator.h" +#include "vtkThreshold.h" +#include "vtkMultiBlockDataGroupFilter.h" +#include "vtkCompositeDataToUnstructuredGridFilter.h" +#include "vtkInformationDataObjectMetaDataKey.h" + +#include +#include + +vtkStandardNewMacro(vtkExtractGroup); + +/////////////////// + +class ExtractGroupStatus +{ +public: + ExtractGroupStatus():_status(false) { } + ExtractGroupStatus(const char *name); + bool getStatus() const { return _status; } + void setStatus(bool status) const { _status=status; } + void cpyStatusFrom(const ExtractGroupStatus& other) { _status=other._status; } + std::string getName() const { return _name; } + void resetStatus() const { _status=false; } + const char *getKeyOfEntry() const { return _ze_key_name.c_str(); } + virtual void printMySelf(std::ostream& os) const; + virtual bool isSameAs(const ExtractGroupStatus& other) const; +protected: +mutable bool _status; +std::string _name; +std::string _ze_key_name; +}; + +class ExtractGroupGrp : public ExtractGroupStatus +{ +public: + ExtractGroupGrp(const char *name):ExtractGroupStatus(name) { std::ostringstream oss; oss << START << name; _ze_key_name=oss.str(); } + void setFamilies(const std::vector& fams) { _fams=fams; } + const std::vector& getFamiliesLyingOn() const { return _fams; } + bool isSameAs(const ExtractGroupGrp& other) const; +public: + static const char START[]; + std::vector _fams; +}; + +class ExtractGroupFam : public ExtractGroupStatus +{ +public: + ExtractGroupFam(const char *name); + void printMySelf(std::ostream& os) const; + void fillIdsToKeep(std::set& s) const; + int getId() const { return _id; } + bool isSameAs(const ExtractGroupFam& other) const; +public: + static const char START[]; +private: + int _id; +}; + +class vtkExtractGroup::vtkExtractGroupInternal +{ +public: + void loadFrom(vtkMutableDirectedGraph *sil); + int getNumberOfEntries() const; + const char *getMeshName() const; + const char *getKeyOfEntry(int i) const; + bool getStatusOfEntryStr(const char *entry) const; + void setStatusOfEntryStr(const char *entry, bool status); + void printMySelf(std::ostream& os) const; + std::set getIdsToKeep() const; + void clearSelection() const; + int getIdOfFamily(const std::string& famName) const; + static bool IsInformationOK(vtkInformation *info); +private: + std::map computeFamStrIdMap() const; + const ExtractGroupStatus& getEntry(const char *entry) const; + ExtractGroupStatus& getEntry(const char *entry); +private: + std::vector _groups; + std::vector _fams; + mutable std::vector< std::pair > _selection; + std::string _mesh_name; +}; + +const char ExtractGroupGrp::START[]="GRP_"; + +const char ExtractGroupFam::START[]="FAM_"; + +ExtractGroupStatus::ExtractGroupStatus(const char *name):_status(false),_name(name) +{ +} + +void ExtractGroupStatus::printMySelf(std::ostream& os) const +{ + os << " -" << _ze_key_name << "("; + if(_status) + os << "X"; + else + os << " "; + os << ")" << std::endl; +} + +bool ExtractGroupStatus::isSameAs(const ExtractGroupStatus& other) const +{ + return _name==other._name && _ze_key_name==other._ze_key_name; +} + +bool ExtractGroupGrp::isSameAs(const ExtractGroupGrp& other) const +{ + bool ret(ExtractGroupStatus::isSameAs(other)); + if(ret) + return _fams==other._fams; + else + return false; +} + +bool vtkExtractGroup::vtkExtractGroupInternal::IsInformationOK(vtkInformation *info) +{ + // Check the information contain meta data key + if(!info->Has(vtkMEDReader::META_DATA())) + return false; + + // Recover Meta Data + vtkMutableDirectedGraph *sil(vtkMutableDirectedGraph::SafeDownCast(info->Get(vtkMEDReader::META_DATA()))); + if(!sil) + return false; + int idNames(0); + vtkAbstractArray *verticesNames(sil->GetVertexData()->GetAbstractArray("Names",idNames)); + vtkStringArray *verticesNames2(vtkStringArray::SafeDownCast(verticesNames)); + if(!verticesNames2) + return false; + for(int i=0;iGetNumberOfValues();i++) + { + vtkStdString &st(verticesNames2->GetValue(i)); + if(st=="MeshesFamsGrps") + return true; + } + return false; +} + +const char* vtkExtractGroup::GetGrpStart() +{ + return ExtractGroupGrp::START; +} + +const char* vtkExtractGroup::GetFamStart() +{ + return ExtractGroupFam::START; +} + +const char *vtkExtractGroup::vtkExtractGroupInternal::getMeshName() const +{ + return this->_mesh_name.c_str(); +} + +void vtkExtractGroup::vtkExtractGroupInternal::loadFrom(vtkMutableDirectedGraph *sil) +{ + std::vector oldGrps(_groups); _groups.clear(); + std::vector oldFams(_fams); _fams.clear(); + int idNames(0); + vtkAbstractArray *verticesNames(sil->GetVertexData()->GetAbstractArray("Names",idNames)); + vtkStringArray *verticesNames2(vtkStringArray::SafeDownCast(verticesNames)); + vtkIdType id0; + bool found(false); + for(int i=0;iGetNumberOfValues();i++) + { + vtkStdString &st(verticesNames2->GetValue(i)); + if(st=="MeshesFamsGrps") + { + id0=i; + found=true; + } + } + if(!found) + throw INTERP_KERNEL::Exception("There is an internal error ! The tree on server side has not the expected look !"); + vtkAdjacentVertexIterator *it0(vtkAdjacentVertexIterator::New()); + sil->GetAdjacentVertices(id0,it0); + int kk(0),ll(0); + while(it0->HasNext()) + { + vtkIdType id1(it0->Next()); + std::string meshName((const char *)verticesNames2->GetValue(id1)); + this->_mesh_name=meshName; + vtkAdjacentVertexIterator *it1(vtkAdjacentVertexIterator::New()); + sil->GetAdjacentVertices(id1,it1); + vtkIdType idZeGrps(it1->Next());//zeGroups + vtkAdjacentVertexIterator *itGrps(vtkAdjacentVertexIterator::New()); + sil->GetAdjacentVertices(idZeGrps,itGrps); + while(itGrps->HasNext()) + { + vtkIdType idg(itGrps->Next()); + ExtractGroupGrp grp((const char *)verticesNames2->GetValue(idg)); + vtkAdjacentVertexIterator *itGrps2(vtkAdjacentVertexIterator::New()); + sil->GetAdjacentVertices(idg,itGrps2); + std::vector famsOnGroup; + while(itGrps2->HasNext()) + { + vtkIdType idgf(itGrps2->Next()); + famsOnGroup.push_back(std::string((const char *)verticesNames2->GetValue(idgf))); + } + grp.setFamilies(famsOnGroup); + itGrps2->Delete(); + _groups.push_back(grp); + } + itGrps->Delete(); + vtkIdType idZeFams(it1->Next());//zeFams + it1->Delete(); + vtkAdjacentVertexIterator *itFams(vtkAdjacentVertexIterator::New()); + sil->GetAdjacentVertices(idZeFams,itFams); + while(itFams->HasNext()) + { + vtkIdType idf(itFams->Next()); + ExtractGroupFam fam((const char *)verticesNames2->GetValue(idf)); + _fams.push_back(fam); + } + itFams->Delete(); + } + it0->Delete(); + // + std::size_t szg(_groups.size()),szf(_fams.size()); + if(szg==oldGrps.size() && szf==oldFams.size()) + { + bool isSame(true); + for(std::size_t i=0;i=0 && i::const_iterator it0=_groups.begin();it0!=_groups.end();it0++) + if(entryCpp==(*it0).getKeyOfEntry()) + return *it0; + for(std::vector::const_iterator it0=_fams.begin();it0!=_fams.end();it0++) + if(entryCpp==(*it0).getKeyOfEntry()) + return *it0; + std::ostringstream oss; oss << "vtkExtractGroupInternal::getEntry : no such entry \"" << entry << "\"!"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); +} + +ExtractGroupStatus& vtkExtractGroup::vtkExtractGroupInternal::getEntry(const char *entry) +{ + std::string entryCpp(entry); + for(std::vector::iterator it0=_groups.begin();it0!=_groups.end();it0++) + if(entryCpp==(*it0).getKeyOfEntry()) + return *it0; + for(std::vector::iterator it0=_fams.begin();it0!=_fams.end();it0++) + if(entryCpp==(*it0).getKeyOfEntry()) + return *it0; + std::ostringstream oss; oss << "vtkExtractGroupInternal::getEntry : no such entry \"" << entry << "\"!"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); +} + +void vtkExtractGroup::vtkExtractGroupInternal::printMySelf(std::ostream& os) const +{ + os << "Groups :" << std::endl; + for(std::vector::const_iterator it0=_groups.begin();it0!=_groups.end();it0++) + (*it0).printMySelf(os); + os << "Families :" << std::endl; + for(std::vector::const_iterator it0=_fams.begin();it0!=_fams.end();it0++) + (*it0).printMySelf(os); +} + +int vtkExtractGroup::vtkExtractGroupInternal::getIdOfFamily(const std::string& famName) const +{ + for(std::vector::const_iterator it=_fams.begin();it!=_fams.end();it++) + { + if((*it).getName()==famName) + return (*it).getId(); + } + return std::numeric_limits::max(); +} + +ExtractGroupFam::ExtractGroupFam(const char *name):ExtractGroupStatus(name),_id(0) +{ + std::size_t pos(_name.find(MEDFileFieldRepresentationLeavesArrays::ZE_SEP)); + std::string name0(_name.substr(0,pos)),name1(_name.substr(pos+strlen(MEDFileFieldRepresentationLeavesArrays::ZE_SEP))); + std::istringstream iss(name1); + iss >> _id; + std::ostringstream oss; oss << START << name; _ze_key_name=oss.str(); _name=name0; +} + +bool ExtractGroupFam::isSameAs(const ExtractGroupFam& other) const +{ + bool ret(ExtractGroupStatus::isSameAs(other)); + if(ret) + return _id==other._id; + else + return false; +} + +void ExtractGroupFam::printMySelf(std::ostream& os) const +{ + os << " -" << _ze_key_name << " famName : \"" << _name << "\" id : " << _id << " ("; + if(_status) + os << "X"; + else + os << " "; + os << ")" << std::endl; +} + +void ExtractGroupFam::fillIdsToKeep(std::set& s) const +{ + s.insert(_id); +} + +std::set vtkExtractGroup::vtkExtractGroupInternal::getIdsToKeep() const +{ + for(auto it: _selection) + { + const ExtractGroupStatus& elt(getEntry(it.first.c_str())); + elt.setStatus(it.second); + } + std::map m(this->computeFamStrIdMap()); + std::set s; + for(std::vector::const_iterator it0=_groups.begin();it0!=_groups.end();it0++) + { + if((*it0).getStatus()) + { + const std::vector& fams((*it0).getFamiliesLyingOn()); + for(std::vector::const_iterator it1=fams.begin();it1!=fams.end();it1++) + { + std::map::iterator it2(m.find((*it1))); + if(it2!=m.end()) + s.insert((*it2).second); + } + } + } + for(std::vector::const_iterator it0=_fams.begin();it0!=_fams.end();it0++) + if((*it0).getStatus()) + (*it0).fillIdsToKeep(s); + return s; +} + +void vtkExtractGroup::vtkExtractGroupInternal::clearSelection() const +{ + _selection.clear(); + for(auto it : _groups) + it.resetStatus(); + for(auto it : _fams) + it.resetStatus(); +} + +std::map vtkExtractGroup::vtkExtractGroupInternal::computeFamStrIdMap() const +{ + std::map ret; + for(std::vector::const_iterator it0=_fams.begin();it0!=_fams.end();it0++) + ret[(*it0).getName()]=(*it0).getId(); + return ret; +} + +//////////////////// + +vtkExtractGroup::vtkExtractGroup():SIL(NULL),Internal(new vtkExtractGroupInternal),InsideOut(0) +{ +} + +vtkExtractGroup::~vtkExtractGroup() +{ + delete this->Internal; +} + +void vtkExtractGroup::SetInsideOut(int val) +{ + if(this->InsideOut!=val) + { + this->InsideOut=val; + this->Modified(); + } +} + +int vtkExtractGroup::RequestInformation(vtkInformation *request, vtkInformationVector **inputVector, vtkInformationVector *outputVector) +{ +// vtkUnstructuredGridAlgorithm::RequestInformation(request,inputVector,outputVector); + try + { +// std::cerr << "########################################## vtkExtractGroup::RequestInformation ##########################################" << std::endl; +// request->Print(cout); + vtkInformation *outInfo(outputVector->GetInformationObject(0)); + vtkInformation *inputInfo(inputVector[0]->GetInformationObject(0)); + if(!vtkExtractGroup::vtkExtractGroupInternal::IsInformationOK(inputInfo)) + { + vtkErrorMacro("No SIL Data available ! The source of this filter must be MEDReader !"); + return 0; + } + + this->SetSIL(vtkMutableDirectedGraph::SafeDownCast(inputInfo->Get(vtkMEDReader::META_DATA()))); + this->Internal->loadFrom(this->SIL); + //this->Internal->printMySelf(std::cerr); + } + catch(INTERP_KERNEL::Exception& e) + { + std::cerr << "Exception has been thrown in vtkExtractGroup::RequestInformation : " << e.what() << std::endl; + return 0; + } + return 1; +} + +/*! + * Do not use vtkCxxSetObjectMacro macro because input mdg comes from an already managed in the pipeline just a ref on it. + */ +void vtkExtractGroup::SetSIL(vtkMutableDirectedGraph *mdg) +{ + if(this->SIL==mdg) + return ; + this->SIL=mdg; +} + +template +vtkDataSet *FilterFamilies(vtkSmartPointer& thres, + vtkDataSet *input, const std::set& idsToKeep, bool insideOut, const char *arrNameOfFamilyField, + const char *associationForThreshold, bool& catchAll, bool& catchSmth) +{ + const int VTK_DATA_ARRAY_DELETE=vtkDataArrayTemplate::VTK_DATA_ARRAY_DELETE; + const char ZE_SELECTION_ARR_NAME[]="@@ZeSelection@@"; + vtkDataSet *output(input->NewInstance()); + output->ShallowCopy(input); + thres->SetInputData(output); + vtkDataSetAttributes *dscIn(input->GetCellData()),*dscIn2(input->GetPointData()); + vtkDataSetAttributes *dscOut(output->GetCellData()),*dscOut2(output->GetPointData()); + // + double vMin(insideOut==0?1.:0.),vMax(insideOut==0?2.:1.); + thres->ThresholdBetween(vMin,vMax); + // OK for the output + // + CellPointExtractor cpe2(input); + vtkDataArray *da(cpe2.Get()->GetScalars(arrNameOfFamilyField)); + if(!da) + return 0; + std::string daName(da->GetName()); + typedef MEDFileVTKTraits::VtkType vtkMCIdTypeArray; + vtkMCIdTypeArray *dai(vtkMCIdTypeArray::SafeDownCast(da)); + if(daName!=arrNameOfFamilyField || !dai) + return 0; + // + int nbOfTuples(dai->GetNumberOfTuples()); + vtkCharArray *zeSelection(vtkCharArray::New()); + zeSelection->SetName(ZE_SELECTION_ARR_NAME); + zeSelection->SetNumberOfComponents(1); + char *pt(new char[nbOfTuples]); + zeSelection->SetArray(pt,nbOfTuples,0,VTK_DATA_ARRAY_DELETE); + const mcIdType *inPtr(dai->GetPointer(0)); + std::fill(pt,pt+nbOfTuples,0); + catchAll=true; catchSmth=false; + std::vector pt2(nbOfTuples,false); + for(std::set::const_iterator it=idsToKeep.begin();it!=idsToKeep.end();it++) + { + bool catchFid(false); + for(int i=0;iAddArray(zeSelection)); + cpe3.Get()->SetActiveAttribute(idx,vtkDataSetAttributes::SCALARS); + cpe3.Get()->CopyScalarsOff(); + zeSelection->Delete(); + // + thres->SetInputArrayToProcess(idx,0,0,associationForThreshold,ZE_SELECTION_ARR_NAME); + thres->Update(); + vtkUnstructuredGrid *zeComputedOutput(thres->GetOutput()); + CellPointExtractor cpe(zeComputedOutput); + cpe.Get()->RemoveArray(idx); + output->Delete(); + zeComputedOutput->Register(0); + return zeComputedOutput; +} + +class CellExtractor +{ +public: + CellExtractor(vtkDataSet *ds):_ds(ds) { } + vtkDataSetAttributes *Get() { return _ds->GetCellData(); } +private: + vtkDataSet *_ds; +}; + +class PointExtractor +{ +public: + PointExtractor(vtkDataSet *ds):_ds(ds) { } + vtkDataSetAttributes *Get() { return _ds->GetPointData(); } +private: + vtkDataSet *_ds; +}; +int vtkExtractGroup::RequestData(vtkInformation *request, vtkInformationVector **inputVector, vtkInformationVector *outputVector) +{ + try + { + // std::cerr << "########################################## vtkExtractGroup::RequestData ##########################################" << std::endl; + // request->Print(cout); + vtkInformation* inputInfo=inputVector[0]->GetInformationObject(0); + vtkMultiBlockDataSet *inputMB(vtkMultiBlockDataSet::SafeDownCast(inputInfo->Get(vtkDataObject::DATA_OBJECT()))); + if(inputMB->GetNumberOfBlocks()!=1) + { + std::ostringstream oss; oss << "vtkExtractGroup::RequestData : input has not the right number of parts ! Expected 1 !"; + if(this->HasObserver("ErrorEvent") ) + this->InvokeEvent("ErrorEvent",const_cast(oss.str().c_str())); + else + vtkOutputWindowDisplayErrorText(const_cast(oss.str().c_str())); + vtkObject::BreakOnError(); + return 0; + } + vtkDataSet *input(vtkDataSet::SafeDownCast(inputMB->GetBlock(0))); + vtkInformation *info(input->GetInformation()); + vtkInformation *outInfo(outputVector->GetInformationObject(0)); + vtkMultiBlockDataSet *output(vtkMultiBlockDataSet::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT()))); + std::set idsToKeep(this->Internal->getIdsToKeep()); + this->Internal->clearSelection(); + // first shrink the input + bool catchAll,catchSmth; + vtkSmartPointer thres1(vtkSmartPointer::New()),thres2(vtkSmartPointer::New()); + vtkDataSet *tryOnCell(FilterFamilies(thres1,input,idsToKeep,this->InsideOut, + MEDFileFieldRepresentationLeavesArrays::FAMILY_ID_CELL_NAME,"vtkDataObject::FIELD_ASSOCIATION_CELLS",catchAll,catchSmth)); + if(tryOnCell) + { + if(catchAll) + { + output->SetBlock(0,tryOnCell); + tryOnCell->Delete();// + return 1; + } + else + { + if(catchSmth) + { + vtkDataSet *tryOnNode(FilterFamilies(thres2,input,idsToKeep,this->InsideOut, + MEDFileFieldRepresentationLeavesArrays::FAMILY_ID_NODE_NAME,"vtkDataObject::FIELD_ASSOCIATION_POINTS",catchAll,catchSmth)); + if(tryOnNode && catchSmth) + { + output->SetBlock(0,tryOnCell); + output->SetBlock(1,tryOnNode); + tryOnCell->Delete(); + tryOnNode->Delete(); + return 1; + } + else + { + if(tryOnNode) + tryOnNode->Delete(); + output->SetBlock(0,tryOnCell); + tryOnCell->Delete(); + return 1; + } + } + else + { + vtkDataSet *tryOnNode(FilterFamilies(thres1,input,idsToKeep,this->InsideOut, + MEDFileFieldRepresentationLeavesArrays::FAMILY_ID_NODE_NAME,"vtkDataObject::FIELD_ASSOCIATION_POINTS",catchAll,catchSmth)); + if(tryOnNode) + { + tryOnCell->Delete(); + output->SetBlock(0,tryOnNode); + tryOnNode->Delete(); + return 1; + } + else + { + output->SetBlock(0,tryOnNode); + tryOnCell->Delete(); + return 0; + } + } + } + } + else + { + vtkDataSet *tryOnNode(FilterFamilies(thres1,input,idsToKeep,this->InsideOut, + MEDFileFieldRepresentationLeavesArrays::FAMILY_ID_NODE_NAME,"vtkDataObject::FIELD_ASSOCIATION_POINTS",catchAll,catchSmth)); + if(tryOnNode) + { + output->ShallowCopy(tryOnNode); + tryOnNode->Delete();// + return 1; + } + else + { + std::ostringstream oss; oss << "vtkExtractGroup::RequestData : The integer array with name \""<< MEDFileFieldRepresentationLeavesArrays::FAMILY_ID_CELL_NAME; + oss << "\" or \"" << MEDFileFieldRepresentationLeavesArrays::FAMILY_ID_NODE_NAME << "\" does not exist ! The extraction of group and/or family is not possible !"; + if(this->HasObserver("ErrorEvent") ) + this->InvokeEvent("ErrorEvent",const_cast(oss.str().c_str())); + else + vtkOutputWindowDisplayErrorText(const_cast(oss.str().c_str())); + vtkObject::BreakOnError(); + return 0; + } + } + } + catch(INTERP_KERNEL::Exception& e) + { + std::cerr << "Exception has been thrown in vtkExtractGroup::RequestData : " << e.what() << std::endl; + return 0; + } +} + +int vtkExtractGroup::GetSILUpdateStamp() +{ + return (int)this->SILTime; +} + +void vtkExtractGroup::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os, indent); +} + +int vtkExtractGroup::GetNumberOfGroupsFlagsArrays() +{ + int ret(this->Internal->getNumberOfEntries()); + //std::cerr << "vtkExtractGroup::GetNumberOfFieldsTreeArrays() -> " << ret << std::endl; + return ret; +} + +const char *vtkExtractGroup::GetGroupsFlagsArrayName(int index) +{ + const char *ret(this->Internal->getKeyOfEntry(index)); +// std::cerr << "vtkExtractGroup::GetFieldsTreeArrayName(" << index << ") -> " << ret << std::endl; + return ret; +} + +int vtkExtractGroup::GetGroupsFlagsArrayStatus(const char *name) +{ + int ret((int)this->Internal->getStatusOfEntryStr(name)); +// std::cerr << "vtkExtractGroup::GetGroupsFlagsArrayStatus(" << name << ") -> " << ret << std::endl; + return ret; +} + +void vtkExtractGroup::SetGroupsFlagsStatus(const char *name, int status) +{ + //std::cerr << "vtkExtractGroup::SetFieldsStatus(" << name << "," << status << ")" << std::endl; + this->Internal->setStatusOfEntryStr(name,(bool)status); + this->Modified(); + //this->Internal->printMySelf(std::cerr); +} + +const char *vtkExtractGroup::GetMeshName() +{ + return this->Internal->getMeshName(); +} diff --git a/src/Plugins/MEDReader/plugin/MEDReaderIO/vtkExtractGroup.h b/src/Plugins/MEDReader/plugin/MEDReaderIO/vtkExtractGroup.h new file mode 100644 index 00000000..bea981ea --- /dev/null +++ b/src/Plugins/MEDReader/plugin/MEDReaderIO/vtkExtractGroup.h @@ -0,0 +1,74 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay + +#ifndef vtkExtractGroup_h__ +#define vtkExtractGroup_h__ + +#include "vtkMultiBlockDataSetAlgorithm.h" + +class vtkMutableDirectedGraph; + +class VTK_EXPORT vtkExtractGroup: public vtkMultiBlockDataSetAlgorithm +{ +public: + static vtkExtractGroup* New(); + vtkTypeMacro(vtkExtractGroup, vtkMultiBlockDataSetAlgorithm) + void PrintSelf(ostream& os, vtkIndent indent); + virtual int GetNumberOfGroupsFlagsArrays(); + const char *GetGroupsFlagsArrayName(int index); + int GetGroupsFlagsArrayStatus(const char *name); + virtual void SetGroupsFlagsStatus(const char *name, int status); + void SetInsideOut(int val); + // Description: + // Every time the SIL is updated a this will return a different value. + virtual int GetSILUpdateStamp(); + const char *GetMeshName(); + static const char* GetGrpStart(); + static const char* GetFamStart(); +protected: + vtkExtractGroup(); + ~vtkExtractGroup(); + + int RequestInformation(vtkInformation *request, + vtkInformationVector **inputVector, vtkInformationVector *outputVector); + + int RequestData(vtkInformation *request, vtkInformationVector **inputVector, + vtkInformationVector *outputVector); + + // Description: + // This SIL stores the structure of the mesh/groups/cell types + // that can be selected. + virtual void SetSIL(vtkMutableDirectedGraph*); + vtkGetObjectMacro(SIL, vtkMutableDirectedGraph); +protected: + vtkMutableDirectedGraph *SIL; + vtkTimeStamp SILTime; +private: + vtkExtractGroup(const vtkExtractGroup&); + void operator=(const vtkExtractGroup&); // Not implemented. + private: + //BTX + //ETX + class vtkExtractGroupInternal; + vtkExtractGroupInternal *Internal; + int InsideOut; +}; + +#endif diff --git a/src/Plugins/MEDReader/plugin/MEDReaderIO/vtkInformationGaussDoubleVectorKey.h b/src/Plugins/MEDReader/plugin/MEDReaderIO/vtkInformationGaussDoubleVectorKey.h new file mode 100644 index 00000000..9c0d5288 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/MEDReaderIO/vtkInformationGaussDoubleVectorKey.h @@ -0,0 +1,61 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// + +#ifndef __vtkInformationGaussDoubleVectorKey_h_ +#define __vtkInformationGaussDoubleVectorKey_h_ + +#include "vtkInformationDoubleVectorKey.h" + +class VTK_EXPORT vtkInformationGaussDoubleVectorKey : public vtkInformationDoubleVectorKey +{ +public: + vtkTypeMacro(vtkInformationGaussDoubleVectorKey, vtkInformationDoubleVectorKey); + void PrintSelf(ostream& os, vtkIndent indent) VTK_OVERRIDE{} + + vtkInformationGaussDoubleVectorKey(const char* name, const char* location, + int length = -1) : vtkInformationDoubleVectorKey(name, location, length) { } + + /** + * This method simply returns a new vtkInformationDoubleVectorKey, given a + * name, a location and a required length. This method is provided for + * wrappers. Use the constructor directly from C++ instead. + */ + static vtkInformationGaussDoubleVectorKey* MakeKey(const char* name, const char* location, + int length = -1) + { + return new vtkInformationGaussDoubleVectorKey(name, location, length); + } + + /** + * Simply shallow copies the key from fromInfo to toInfo. + * This is used by the pipeline to propagate this key downstream. + */ + void CopyDefaultInformation(vtkInformation* request, + vtkInformation* fromInfo, + vtkInformation* toInfo) VTK_OVERRIDE + { + this->ShallowCopy(fromInfo, toInfo); + } + + /*private: + vtkInformationGaussDoubleVectorKey(const vtkInformationGaussDoubleVectorKey&) VTK_DELETE_FUNCTION; + void operator=(const vtkInformationGaussDoubleVectorKey&) VTK_DELETE_FUNCTION;*/ +}; + +#endif diff --git a/src/Plugins/MEDReader/plugin/MEDReaderIO/vtkMEDQuadraturePointsGenerator.cxx b/src/Plugins/MEDReader/plugin/MEDReaderIO/vtkMEDQuadraturePointsGenerator.cxx new file mode 100644 index 00000000..bfc25d59 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/MEDReaderIO/vtkMEDQuadraturePointsGenerator.cxx @@ -0,0 +1,134 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Roman NIKOLAEV + +//Local includes +#include "vtkMEDQuadraturePointsGenerator.h" +#include "MEDFileFieldRepresentationTree.hxx" + +//VTK includes +#include +#include +#include +#include +#include +#include +#include +#include + +//----------------------------------------------------------------------------- +vtkStandardNewMacro(vtkMEDQuadraturePointsGenerator); + +//----------------------------------------------------------------------------- +vtkMEDQuadraturePointsGenerator::vtkMEDQuadraturePointsGenerator() +{ +} + +//----------------------------------------------------------------------------- +vtkMEDQuadraturePointsGenerator::~vtkMEDQuadraturePointsGenerator() +{} + + +//----------------------------------------------------------------------------- +int vtkMEDQuadraturePointsGenerator::RequestData( + vtkInformation* request, + vtkInformationVector **input, + vtkInformationVector *output) +{ + if (this->Superclass::RequestData(request, input, output) == 0 ) + { + return 0; + } + + //Fill MED internal array + vtkDataObject *tmpDataObj; + + // Get the input. + tmpDataObj = input[0]->GetInformationObject(0)->Get(vtkDataObject::DATA_OBJECT()); + vtkUnstructuredGrid *usgIn = vtkUnstructuredGrid::SafeDownCast(tmpDataObj); + // Get the output. + tmpDataObj = output->GetInformationObject(0)->Get(vtkDataObject::DATA_OBJECT()); + vtkPolyData *pdOut = vtkPolyData::SafeDownCast(tmpDataObj); + vtkDataArray* offsets = this->GetInputArrayToProcess(0, input); + + if (usgIn == NULL || pdOut == NULL || offsets == NULL ) + { + vtkErrorMacro("Filter data has not been configured correctly. Aborting."); + return 1; + } + + vtkInformation *info = offsets->GetInformation(); + vtkInformationQuadratureSchemeDefinitionVectorKey *key + = vtkQuadratureSchemeDefinition::DICTIONARY(); + if (!key->Has(info)) + { + vtkErrorMacro( + << "Dictionary is not present in array " + << offsets->GetName() << " " << offsets + << " Aborting."); + return 0; + } + + vtkIdType nCells = usgIn->GetNumberOfCells(); + int dictSize = key->Size(info); + vtkQuadratureSchemeDefinition **dict + = new vtkQuadratureSchemeDefinition *[dictSize]; + key->GetRange(info, dict, 0, 0, dictSize); + + // Loop over all fields to map the internal MED cell array to the points array + int nCArrays = usgIn->GetCellData()->GetNumberOfArrays(); + for (int i = 0; iGetCellData()->GetArray(i); + if ( !array ) + { + continue; + } + std::string arrName = array->GetName(); + if ( arrName == MEDFileFieldRepresentationLeavesArrays::FAMILY_ID_CELL_NAME ) + { + vtkDataArray *out_id_cells = array->NewInstance(); + out_id_cells->SetName(MEDFileFieldRepresentationLeavesArrays::FAMILY_ID_NODE_NAME); + out_id_cells->SetNumberOfComponents(array->GetNumberOfComponents()); + out_id_cells->CopyComponentNames( array ); + for (int cellId = 0; cellId < nCells; cellId++) + { + int cellType = usgIn->GetCellType(cellId); + + // a simple check to see if a scheme really exists for this cell type. + // should not happen if the cell type has not been modified. + if (dict[cellType] == NULL) + { + continue; + } + + int np = dict[cellType]->GetNumberOfQuadraturePoints(); + for (int id = 0; id < np; id++) + { + out_id_cells->InsertNextTuple(cellId, array); + } + } + out_id_cells->Squeeze(); + pdOut->GetPointData()->AddArray(out_id_cells); + out_id_cells->Delete(); + } + } + delete[] dict; + return 1; +} diff --git a/src/Plugins/MEDReader/plugin/MEDReaderIO/vtkMEDQuadraturePointsGenerator.h b/src/Plugins/MEDReader/plugin/MEDReaderIO/vtkMEDQuadraturePointsGenerator.h new file mode 100644 index 00000000..4578aa2e --- /dev/null +++ b/src/Plugins/MEDReader/plugin/MEDReaderIO/vtkMEDQuadraturePointsGenerator.h @@ -0,0 +1,46 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Roman NIKOLAEV + +#ifndef vtkMEDQuadraturePointsGenerator_h +#define vtkMEDQuadraturePointsGenerator_h + +#include // For export macro +#include + +class vtkInformation; +class vtkInformationVector; + +class VTK_EXPORT vtkMEDQuadraturePointsGenerator : public vtkQuadraturePointsGenerator +{ +public: + vtkTypeMacro(vtkMEDQuadraturePointsGenerator,vtkQuadraturePointsGenerator); + static vtkMEDQuadraturePointsGenerator *New(); + +protected: + + int RequestData(vtkInformation *req, vtkInformationVector **input, vtkInformationVector *output); + vtkMEDQuadraturePointsGenerator(); + virtual ~vtkMEDQuadraturePointsGenerator(); +private: + vtkMEDQuadraturePointsGenerator(const vtkMEDQuadraturePointsGenerator &); // Not implemented + void operator=(const vtkMEDQuadraturePointsGenerator &); // Not implemented +}; + +#endif diff --git a/src/Plugins/MEDReader/plugin/MEDReaderIO/vtkMEDReader.cxx b/src/Plugins/MEDReader/plugin/MEDReaderIO/vtkMEDReader.cxx new file mode 100644 index 00000000..129ec3b3 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/MEDReaderIO/vtkMEDReader.cxx @@ -0,0 +1,697 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay + +#include "vtkMEDReader.h" +#include "vtkGenerateVectors.h" +#include "MEDUtilities.hxx" + +#include "vtkMultiBlockDataSet.h" +#include "vtkInformation.h" +#include "vtkDataSetAttributes.h" +#include "vtkStringArray.h" +#include "vtkMutableDirectedGraph.h" +#include "vtkInformationStringKey.h" +// +#include "vtkUnsignedCharArray.h" +#include "vtkInformationVector.h" +#include "vtkSmartPointer.h" +#include "vtkVariantArray.h" +#include "vtkExecutive.h" +#include "vtkStreamingDemandDrivenPipeline.h" +#include "vtkMultiTimeStepAlgorithm.h" +#include "vtkUnstructuredGrid.h" +#include "vtkInformationQuadratureSchemeDefinitionVectorKey.h" +#include "vtkInformationDoubleVectorKey.h" +#include "vtkQuadratureSchemeDefinition.h" +#include "vtkPointData.h" +#include "vtkCellData.h" +#include "vtkCellType.h" +#include "vtkCellArray.h" +#include "vtkDoubleArray.h" +#include "vtkObjectFactory.h" +#include "vtkInformationDataObjectMetaDataKey.h" + +#ifdef MEDREADER_USE_MPI +#include "vtkMultiProcessController.h" +#include "vtkPUnstructuredGridGhostCellsGenerator.h" +#endif + +#include "MEDFileFieldRepresentationTree.hxx" + +#include +#include +#include +#include +#include + +/*! + * This class stores properties in loading state mode (pvsm) when the MED file has not been read yet. + * The file is not read beacause FileName has not been informed yet ! So this class stores properties of vtkMEDReader instance that + * owns it and wait the vtkMEDReader::SetFileName to apply properties afterwards. + */ +class PropertyKeeper +{ +public: + PropertyKeeper(vtkMEDReader *master):IsGVActivated(false),GVValue(0),IsCMActivated(false),CMValue(0),IsGhostActivated(false),GCGCP(1),_master(master) { } + void assignPropertiesIfNeeded(); + bool arePropertiesOnTreeToSetAfter() const; + // + void pushFieldStatusEntry(const char* name, int status); + void pushGenerateVectorsValue(int value); + void pushChangeModeValue(int value); + void pushTimesFlagsStatusEntry(const char* name, int status); + void pushGhost(int value); +protected: + // pool of pairs to assign in SetFieldsStatus if needed. The use case is the load using pvsm. + std::vector< std::pair > SetFieldsStatusPairs; + // generate vector + bool IsGVActivated; + int GVValue; + // change mode + bool IsCMActivated; + int CMValue; + // ghost cells + bool IsGhostActivated; + int GCGCP; + // + std::vector< std::pair > TimesFlagsStatusPairs; + vtkMEDReader *_master; +}; + +void PropertyKeeper::assignPropertiesIfNeeded() +{ + if(!this->SetFieldsStatusPairs.empty()) + { + for(std::vector< std::pair >::const_iterator it=this->SetFieldsStatusPairs.begin();it!=this->SetFieldsStatusPairs.end();it++) + _master->SetFieldsStatus((*it).first.c_str(),(*it).second); + this->SetFieldsStatusPairs.clear(); + } + if(!this->TimesFlagsStatusPairs.empty()) + { + for(std::vector< std::pair >::const_iterator it=this->TimesFlagsStatusPairs.begin();it!=this->TimesFlagsStatusPairs.end();it++) + _master->SetTimesFlagsStatus((*it).first.c_str(),(*it).second); + this->TimesFlagsStatusPairs.clear(); + } + if(this->IsGVActivated) + { + _master->GenerateVectors(this->GVValue); + this->IsGVActivated=false; + } + if(this->IsCMActivated) + { + _master->ChangeMode(this->CMValue); + this->IsCMActivated=false; + } + if(this->IsGhostActivated) + { + _master->GhostCellGeneratorCallForPara(this->GCGCP); + this->IsGhostActivated=false; + } +} + +void PropertyKeeper::pushFieldStatusEntry(const char* name, int status) +{ + bool found(false); + for(std::vector< std::pair >::const_iterator it=this->SetFieldsStatusPairs.begin();it!=this->SetFieldsStatusPairs.end() && !found;it++) + found=(*it).first==name; + if(!found) + this->SetFieldsStatusPairs.push_back(std::pair(name,status)); +} + +void PropertyKeeper::pushTimesFlagsStatusEntry(const char* name, int status) +{ + bool found(false); + for(std::vector< std::pair >::const_iterator it=this->TimesFlagsStatusPairs.begin();it!=this->TimesFlagsStatusPairs.end() && !found;it++) + found=(*it).first==name; + if(!found) + this->TimesFlagsStatusPairs.push_back(std::pair(name,status)); +} + +void PropertyKeeper::pushGenerateVectorsValue(int value) +{ + this->IsGVActivated=true; + this->GVValue=value; +} + +void PropertyKeeper::pushChangeModeValue(int value) +{ + this->IsCMActivated=true; + this->CMValue=value; +} + +void PropertyKeeper::pushGhost(int value) +{ + this->IsGhostActivated=true; + this->GCGCP=value; +} + +bool PropertyKeeper::arePropertiesOnTreeToSetAfter() const +{ + return !SetFieldsStatusPairs.empty(); +} + +class vtkMEDReader::vtkMEDReaderInternal +{ + +public: + vtkMEDReaderInternal(vtkMEDReader *master):TK(0),IsMEDOrSauv(true),IsStdOrMode(false),GenerateVect(false),SIL(0),LastLev0(-1),PK(master),MyMTime(0),GCGCP(true),FirstCall0(2) + { + } + + bool PluginStart0() + { + return false; // TODO Useless and buggy + if(FirstCall0==0) + return false; + FirstCall0--; + return true; + } + + ~vtkMEDReaderInternal() + { + if(this->SIL) + this->SIL->Delete(); + } +public: + MEDFileFieldRepresentationTree Tree; + TimeKeeper TK; + std::string FileName; + //when true the file is MED file. when false it is a Sauv file + bool IsMEDOrSauv; + //when false -> std, true -> mode. By default std (false). + bool IsStdOrMode; + //when false -> do nothing. When true cut off or extend to nbOfCompo=3 vector arrays. + bool GenerateVect; + std::string DftMeshName; + // Store the vtkMutableDirectedGraph that represents links between family, groups and cell types + vtkMutableDirectedGraph* SIL; + // store the lev0 id in Tree corresponding to the TIME_STEPS in the pipeline. + int LastLev0; + // The property keeper is usable only in pvsm mode. + PropertyKeeper PK; + int MyMTime; + std::set _wonderful_set;// this set is used by SetFieldsStatus method to detect the fact that SetFieldsStatus has been called for all items ! Great Items are not sorted ! Why ? + std::map _wonderful_ref;// this map stores the state before a SetFieldsStatus status. + bool GCGCP; + +private: + unsigned char FirstCall0; +}; + +vtkStandardNewMacro(vtkMEDReader); + +// vtkInformationKeyMacro(vtkMEDReader, META_DATA, DataObjectMetaData); // Here we need to customize vtkMEDReader::META_DATA method +// start of overload of vtkInformationKeyMacro +static vtkInformationDataObjectMetaDataKey *vtkMEDReader_META_DATA=new vtkInformationDataObjectMetaDataKey("META_DATA","vtkMEDReader"); + +vtkInformationDataObjectMetaDataKey *vtkMEDReader::META_DATA() +{ + static const char ZE_KEY[]="vtkMEDReader::META_DATA"; + vtkInformationDataObjectMetaDataKey *ret(vtkMEDReader_META_DATA); + MEDCoupling::GlobalDict *gd(MEDCoupling::GlobalDict::GetInstance()); + if(!gd->hasKey(ZE_KEY)) + {// here META_DATA is put on global var to be exchanged with other filters without dependancy of MEDReader. Please do not change ZE_KEY ! + std::ostringstream oss; oss << ret; + gd->setKeyValue(ZE_KEY,oss.str()); + } + return ret; +} + +static vtkInformationGaussDoubleVectorKey *vtkMEDReader_GAUSS_DATA=new vtkInformationGaussDoubleVectorKey("GAUSS_DATA","vtkMEDReader"); + +vtkInformationGaussDoubleVectorKey *vtkMEDReader::GAUSS_DATA() +{ + static const char ZE_KEY[]="vtkMEDReader::GAUSS_DATA"; + vtkInformationGaussDoubleVectorKey *ret(vtkMEDReader_GAUSS_DATA); + MEDCoupling::GlobalDict *gd(MEDCoupling::GlobalDict::GetInstance()); + if(!gd->hasKey(ZE_KEY)) + {// here META_DATA is put on global var to be exchanged with other filters without dependancy of MEDReader. Please do not change ZE_KEY ! + vtkInformationDoubleVectorKey *ret2(ret); + std::ostringstream oss; oss << ret2; + gd->setKeyValue(ZE_KEY,oss.str()); + } + return ret; +} +// end of overload of vtkInformationKeyMacro + +vtkMEDReader::vtkMEDReader():Internal(new vtkMEDReaderInternal(this)) +{ + this->SetNumberOfInputPorts(0); + this->SetNumberOfOutputPorts(1); +} + +vtkMEDReader::~vtkMEDReader() +{ + delete this->Internal; + this->Internal = 0; +} + +void vtkMEDReader::Reload() +{ + std::string fName((const char *)this->GetFileName()); + delete this->Internal; + this->Internal=new vtkMEDReaderInternal(this); + this->SetFileName(fName.c_str()); +} + +int vtkMEDReader::GetServerModifTime() +{ + if( !this->Internal ) + return -1; + return this->Internal->MyMTime; +} + +void vtkMEDReader::GenerateVectors(int val) +{ + if ( !this->Internal ) + return; + + if(this->Internal->FileName.empty()) + {//pvsm mode + this->Internal->PK.pushGenerateVectorsValue(val); + return ; + } + //not pvsm mode (general case) + bool val2((bool)val); + if(val2!=this->Internal->GenerateVect) + { + this->Internal->GenerateVect=val2; + this->Modified(); + } +} + +void vtkMEDReader::ChangeMode(int newMode) +{ + if ( !this->Internal ) + return; + + if(this->Internal->FileName.empty()) + {//pvsm mode + this->Internal->PK.pushChangeModeValue(newMode); + return ; + } + //not pvsm mode (general case) + this->Internal->IsStdOrMode=newMode!=0; + this->Modified(); +} + +void vtkMEDReader::GhostCellGeneratorCallForPara(int gcgcp) +{ + if ( !this->Internal ) + return; + + if(this->Internal->FileName.empty()) + {//pvsm mode + this->Internal->PK.pushGhost(gcgcp); + return ; + } + bool newVal(gcgcp!=0); + if(newVal!=this->Internal->GCGCP) + { + this->Internal->GCGCP=newVal; + this->Modified(); + } +} + +const char *vtkMEDReader::GetSeparator() +{ + return MEDFileFieldRepresentationLeavesArrays::ZE_SEP; +} + +void vtkMEDReader::SetFileName(const char *fname) +{ + if(!this->Internal) + return; + try + { + this->Internal->FileName=fname; + std::size_t pos(this->Internal->FileName.find_last_of('.')); + if(pos!=std::string::npos) + { + std::string ext(this->Internal->FileName.substr(pos)); + if(ext.find("sauv")!=std::string::npos) + this->Internal->IsMEDOrSauv=false; + } + if(this->Internal->Tree.getNumberOfLeavesArrays()==0) + { + int iPart(-1),nbOfParts(-1); +#ifdef MEDREADER_USE_MPI + vtkMultiProcessController *vmpc(vtkMultiProcessController::GetGlobalController()); + if(vmpc) + { + iPart=vmpc->GetLocalProcessId(); + nbOfParts=vmpc->GetNumberOfProcesses(); + } +#endif + this->Internal->Tree.loadMainStructureOfFile(this->Internal->FileName.c_str(),this->Internal->IsMEDOrSauv,iPart,nbOfParts); + if(!this->Internal->PK.arePropertiesOnTreeToSetAfter()) + this->Internal->Tree.activateTheFirst();//This line manually initialize the status of server (this) with the remote client. + this->Internal->TK.setMaxNumberOfTimeSteps(this->Internal->Tree.getMaxNumberOfTimeSteps()); + } + this->Modified(); + this->Internal->PK.assignPropertiesIfNeeded(); + } + catch(INTERP_KERNEL::Exception& e) + { + delete this->Internal; + this->Internal=0; + std::ostringstream oss; + oss << "Exception has been thrown in vtkMEDReader::SetFileName : " << e.what() << std::endl; + if(this->HasObserver("ErrorEvent") ) + this->InvokeEvent("ErrorEvent",const_cast(oss.str().c_str())); + else + vtkOutputWindowDisplayErrorText(const_cast(oss.str().c_str())); + vtkObject::BreakOnError(); + } +} + +char *vtkMEDReader::GetFileName() +{ + if (!this->Internal) + return 0; + return const_cast(this->Internal->FileName.c_str()); +} + +int vtkMEDReader::RequestInformation(vtkInformation *request, vtkInformationVector **inputVector, vtkInformationVector *outputVector) +{ +// std::cout << "########################################## vtkMEDReader::RequestInformation ##########################################" << std::endl; + if(!this->Internal) + return 0; + try + { +// request->Print(cout); + vtkInformation *outInfo(outputVector->GetInformationObject(0)); + outInfo->Set(vtkDataObject::DATA_TYPE_NAME(),"vtkMultiBlockDataSet"); + this->UpdateSIL(request, outInfo); + + // Set the meta data graph as a meta data key in the information + // That's all that is needed to transfer it along the pipeline + outInfo->Set(vtkMEDReader::META_DATA(),this->Internal->SIL); + + bool dummy(false); + this->PublishTimeStepsIfNeeded(outInfo,dummy); + } + catch(INTERP_KERNEL::Exception& e) + { + std::ostringstream oss; + oss << "Exception has been thrown in vtkMEDReader::RequestInformation : " << e.what() << std::endl; + if(this->HasObserver("ErrorEvent") ) + this->InvokeEvent("ErrorEvent",const_cast(oss.str().c_str())); + else + vtkOutputWindowDisplayErrorText(const_cast(oss.str().c_str())); + vtkObject::BreakOnError(); + return 0; + } + return 1; +} + +int vtkMEDReader::RequestData(vtkInformation *request, vtkInformationVector **inputVector, vtkInformationVector *outputVector) +{ +// std::cout << "########################################## vtkMEDReader::RequestData ##########################################" << std::endl; + if(!this->Internal) + return 0; + try + { +// request->Print(cout); + vtkInformation *outInfo(outputVector->GetInformationObject(0)); + vtkMultiBlockDataSet *output(vtkMultiBlockDataSet::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT()))); + bool isUpdated(false); + double reqTS(0.); + if(outInfo->Has(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP())) + reqTS=outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP()); + ExportedTinyInfo ti; +#ifndef MEDREADER_USE_MPI + this->FillMultiBlockDataSetInstance(output,reqTS,&ti); +#else + if(this->Internal->GCGCP) + { + vtkSmartPointer gcg(vtkSmartPointer::New()); + { + vtkDataSet *ret(RetrieveDataSetAtTime(reqTS,&ti)); + gcg->SetInputData(ret); + ret->Delete(); + } + gcg->SetUseGlobalPointIds(true); + gcg->SetBuildIfRequired(false); + gcg->Update(); + output->SetBlock(0,gcg->GetOutput()); + } + else + this->FillMultiBlockDataSetInstance(output,reqTS,&ti); +#endif + if(!ti.empty()) + { + const std::vector& data(ti.getData()); + outInfo->Set(vtkMEDReader::GAUSS_DATA(),&data[0],(int)data.size()); + request->Append(vtkExecutive::KEYS_TO_COPY(),vtkMEDReader::GAUSS_DATA());// Thank you to SciberQuest and DIPOLE_CENTER ! Don't understand why ! In RequestInformation it does not work ! + } + output->GetInformation()->Set(vtkDataObject::DATA_TIME_STEP(),reqTS); + // Is it really needed ? TODO + this->UpdateSIL(request, outInfo); + } + catch(INTERP_KERNEL::Exception& e) + { + std::cerr << "Exception has been thrown in vtkMEDReader::RequestData : " << e.what() << std::endl; + return 0; + } + return 1; +} + +void vtkMEDReader::SetFieldsStatus(const char* name, int status) +{ + if( !this->Internal ) + return; + + //this->Internal->_wonderful_set.insert(name); + if(this->Internal->FileName.empty()) + {//pvsm mode + this->Internal->PK.pushFieldStatusEntry(name,status); + return ; + } + if(this->Internal->_wonderful_set.empty()) + this->Internal->_wonderful_ref=this->Internal->Tree.dumpState();// start of SetFieldsStatus serie -> store ref to compare at the end of the SetFieldsStatus serie. + this->Internal->_wonderful_set.insert(name); + //not pvsm mode (general case) + try + { + this->Internal->Tree.changeStatusOfAndUpdateToHaveCoherentVTKDataSet(this->Internal->Tree.getIdHavingZeName(name),status); + if((int)this->Internal->_wonderful_set.size()==GetNumberOfFieldsTreeArrays()) + { + if(this->Internal->_wonderful_ref!=this->Internal->Tree.dumpState()) + { + if(!this->Internal->PluginStart0()) + { + this->Modified(); + } + this->Internal->MyMTime++; + } + this->Internal->_wonderful_set.clear(); + } + } + catch(INTERP_KERNEL::Exception& e) + { + if(!this->Internal->FileName.empty()) + { + std::cerr << "vtkMEDReader::SetFieldsStatus error : " << e.what() << " *** WITH STATUS=" << status << endl; + return ; + } + } +} + +int vtkMEDReader::GetNumberOfFieldsTreeArrays() +{ + if(!this->Internal) + return 0; + return this->Internal->Tree.getNumberOfLeavesArrays(); +} + +const char *vtkMEDReader::GetFieldsTreeArrayName(int index) +{ + if(!this->Internal) + return 0; + return this->Internal->Tree.getNameOfC(index); +} + +int vtkMEDReader::GetFieldsTreeArrayStatus(const char *name) +{ + if(!this->Internal) + return -1; + + int zeId(this->Internal->Tree.getIdHavingZeName(name)); + int ret(this->Internal->Tree.getStatusOf(zeId)); + return ret; +} + +void vtkMEDReader::SetTimesFlagsStatus(const char *name, int status) +{ + if (!this->Internal) + return; + + if(this->Internal->FileName.empty()) + {//pvsm mode + this->Internal->PK.pushTimesFlagsStatusEntry(name,status); + return ; + } + //not pvsm mode (general case) + int pos(0); + std::istringstream iss(name); iss >> pos; + this->Internal->TK.getTimesFlagArray()[pos].first=(bool)status; + if(pos==(int)this->Internal->TK.getTimesFlagArray().size()-1) + if(!this->Internal->PluginStart0()) + { + this->Modified(); + //this->Internal->TK.printSelf(std::cerr); + } +} + +int vtkMEDReader::GetNumberOfTimesFlagsArrays() +{ + if(!this->Internal) + return 0; + return (int)this->Internal->TK.getTimesFlagArray().size(); +} + +const char *vtkMEDReader::GetTimesFlagsArrayName(int index) +{ + return this->Internal->TK.getTimesFlagArray()[index].second.c_str(); +} + +int vtkMEDReader::GetTimesFlagsArrayStatus(const char *name) +{ + if(!this->Internal) + return -1; + int pos(0); + std::istringstream iss(name); iss >> pos; + return (int)this->Internal->TK.getTimesFlagArray()[pos].first; +} + +void vtkMEDReader::UpdateSIL(vtkInformation* request, vtkInformation *info) +{ + if(!this->Internal) + return; + std::string meshName(this->Internal->Tree.getActiveMeshName()); + if(!this->Internal->SIL || meshName!=this->Internal->DftMeshName) + { + vtkMutableDirectedGraph *sil(vtkMutableDirectedGraph::New()); + this->BuildSIL(sil); + if(this->Internal->SIL) + this->Internal->SIL->Delete(); + this->Internal->SIL=sil; + this->Internal->DftMeshName=meshName; + } +} + +/*! + * The returned string is the name of the mesh activated which groups and families are in \a sil. + */ +std::string vtkMEDReader::BuildSIL(vtkMutableDirectedGraph* sil) +{ + if (!this->Internal) + return std::string(); + sil->Initialize(); + vtkSmartPointer childEdge(vtkSmartPointer::New()); + childEdge->InsertNextValue(0); + vtkSmartPointer crossEdge(vtkSmartPointer::New()); + crossEdge->InsertNextValue(1); + // CrossEdge is an edge linking hierarchies. + vtkUnsignedCharArray* crossEdgesArray=vtkUnsignedCharArray::New(); + crossEdgesArray->SetName("CrossEdges"); + sil->GetEdgeData()->AddArray(crossEdgesArray); + crossEdgesArray->Delete(); + std::vector names; + // Now build the hierarchy. + vtkIdType rootId=sil->AddVertex(); + names.push_back("SIL"); + // Add global fields root + vtkIdType fieldsRoot(sil->AddChild(rootId,childEdge)); + names.push_back("FieldsStatusTree"); + this->Internal->Tree.feedSIL(sil,fieldsRoot,childEdge,names); + vtkIdType meshesFamsGrpsRoot(sil->AddChild(rootId,childEdge)); + names.push_back("MeshesFamsGrps"); + std::string dftMeshName(this->Internal->Tree.feedSILForFamsAndGrps(sil,meshesFamsGrpsRoot,childEdge,names)); + // This array is used to assign names to nodes. + vtkStringArray *namesArray(vtkStringArray::New()); + namesArray->SetName("Names"); + namesArray->SetNumberOfTuples(sil->GetNumberOfVertices()); + sil->GetVertexData()->AddArray(namesArray); + namesArray->Delete(); + std::vector::const_iterator iter; + vtkIdType cc; + for(cc=0, iter=names.begin(); iter!=names.end(); ++iter, ++cc) + namesArray->SetValue(cc,(*iter).c_str()); + return dftMeshName; +} + +double vtkMEDReader::PublishTimeStepsIfNeeded(vtkInformation *outInfo, bool& isUpdated) +{ + if(!this->Internal) + return 0.0; + + int lev0(-1); + std::vector tsteps; + if(!this->Internal->IsStdOrMode) + tsteps=this->Internal->Tree.getTimeSteps(lev0,this->Internal->TK); + else + { tsteps.resize(1); tsteps[0]=0.; } + isUpdated=false; + if(lev0!=this->Internal->LastLev0) + { + isUpdated=true; + double timeRange[2]; + timeRange[0]=tsteps.front(); + timeRange[1]=tsteps.back(); + outInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_STEPS(),&tsteps[0],(int)tsteps.size()); + outInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_RANGE(),timeRange,2); + this->Internal->LastLev0=lev0; + } + return tsteps.front(); +} + +void vtkMEDReader::FillMultiBlockDataSetInstance(vtkMultiBlockDataSet *output, double reqTS, ExportedTinyInfo *internalInfo) +{ + if( !this->Internal ) + return; + vtkDataSet *ret(RetrieveDataSetAtTime(reqTS,internalInfo)); + output->SetBlock(0,ret); + ret->Delete(); +} + +vtkDataSet *vtkMEDReader::RetrieveDataSetAtTime(double reqTS, ExportedTinyInfo *internalInfo) +{ + if( !this->Internal ) + return 0; + std::string meshName; + vtkDataSet *ret(this->Internal->Tree.buildVTKInstance(this->Internal->IsStdOrMode,reqTS,meshName,this->Internal->TK,internalInfo)); + if(this->Internal->GenerateVect) + { + vtkGenerateVectors::Operate(ret->GetPointData()); + vtkGenerateVectors::Operate(ret->GetCellData()); + vtkGenerateVectors::Operate(ret->GetFieldData()); + // The operations above have potentially created new arrays -> This breaks the optimization of StaticMesh that expects the same field arrays over time. + // To enforce the cache recomputation declare modification of mesh. + //vtkGenerateVectors::ChangeMeshTimeToUpdateCache(ret); + } + return ret; +} + +void vtkMEDReader::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os, indent); +} diff --git a/src/Plugins/MEDReader/plugin/MEDReaderIO/vtkMEDReader.h b/src/Plugins/MEDReader/plugin/MEDReaderIO/vtkMEDReader.h new file mode 100644 index 00000000..b5301817 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/MEDReaderIO/vtkMEDReader.h @@ -0,0 +1,95 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay + +#ifndef __vtkMEDReader_h_ +#define __vtkMEDReader_h_ + +#include + +#include "vtkMultiBlockDataSetAlgorithm.h" +#include "vtkInformationGaussDoubleVectorKey.h" + +class vtkDataSet; +class vtkMutableDirectedGraph; +class vtkInformationDataObjectMetaDataKey; +class vtkInformationDoubleVectorKey; +class ExportedTinyInfo; + +class VTK_EXPORT vtkMEDReader : public vtkMultiBlockDataSetAlgorithm +{ + private: + vtkMEDReader(const vtkMEDReader&); // Not implemented. + void operator=(const vtkMEDReader&); // Not implemented. + public: + static vtkMEDReader *New(); + vtkTypeMacro(vtkMEDReader, vtkMultiBlockDataSetAlgorithm); + void PrintSelf(ostream& os, vtkIndent indent); + virtual void SetFileName(const char*); + virtual char *GetFileName(); + virtual const char *GetFileExtensions() { return ".med .rmed .sauv .sauve"; } + virtual const char *GetDescriptiveName() { return "MED file (Data Exchange Model)"; } + // + virtual void SetFieldsStatus(const char *name, int status); + virtual int GetNumberOfFieldsTreeArrays(); + virtual const char *GetFieldsTreeArrayName(int index); + virtual int GetFieldsTreeArrayStatus(const char *name); + // + virtual int GetTimesFlagsArrayStatus(const char *name); + virtual void SetTimesFlagsStatus(const char *name, int status); + virtual int GetNumberOfTimesFlagsArrays(); + virtual const char *GetTimesFlagsArrayName(int index); + //! Build the graph used to pass information to the client on the supports + virtual std::string BuildSIL(vtkMutableDirectedGraph*); + + // Description + // Reload will delete the internal reader and recreate it with default properties + virtual void Reload(); + + virtual int GetServerModifTime(); + // + virtual void GenerateVectors(int); + virtual void ChangeMode(int); + virtual void GhostCellGeneratorCallForPara(int); + static const char *GetSeparator(); + + // Description + // Static information key used to transfer the meta data graph along the pipeline + static vtkInformationDataObjectMetaDataKey* META_DATA(); + static vtkInformationGaussDoubleVectorKey* GAUSS_DATA(); + + protected: + vtkMEDReader(); + virtual ~vtkMEDReader(); + virtual int RequestInformation(vtkInformation*, vtkInformationVector**, vtkInformationVector*); + virtual int RequestData(vtkInformation*, vtkInformationVector**, vtkInformationVector*); + private: + void UpdateSIL(vtkInformation *request, vtkInformation *info); + virtual double PublishTimeStepsIfNeeded(vtkInformation*, bool& isUpdated); + virtual void FillMultiBlockDataSetInstance(vtkMultiBlockDataSet *output, double reqTS, ExportedTinyInfo *internalInfo=0); + vtkDataSet *RetrieveDataSetAtTime(double reqTS, ExportedTinyInfo *internalInfo); + private: + //BTX + //ETX + + class vtkMEDReaderInternal; + vtkMEDReaderInternal* Internal; +}; + +#endif //__vtkMEDReader_h_ diff --git a/src/Plugins/MEDReader/plugin/MEDReaderIO/vtkPVMetaDataInformation.cxx b/src/Plugins/MEDReader/plugin/MEDReaderIO/vtkPVMetaDataInformation.cxx new file mode 100644 index 00000000..9d6754e0 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/MEDReaderIO/vtkPVMetaDataInformation.cxx @@ -0,0 +1,142 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay + +#include "vtkPVMetaDataInformation.h" + +#include "vtkAlgorithm.h" +#include "vtkAlgorithmOutput.h" +#include "vtkClientServerStream.h" +#include "vtkExecutive.h" +#include "vtkDataObject.h" +#include "vtkGenericDataObjectReader.h" +#include "vtkGenericDataObjectWriter.h" +#include "vtkInformationDataObjectMetaDataKey.h" +#include "vtkInformation.h" +#include "vtkObjectFactory.h" + +#include "vtkMEDReader.h" + +vtkStandardNewMacro(vtkPVMetaDataInformation); +vtkCxxSetObjectMacro(vtkPVMetaDataInformation, InformationData, vtkDataObject); + +//---------------------------------------------------------------------------- +vtkPVMetaDataInformation::vtkPVMetaDataInformation() +{ + this->InformationData = NULL; +} + +//---------------------------------------------------------------------------- +vtkPVMetaDataInformation::~vtkPVMetaDataInformation() +{ + this->SetInformationData(NULL); +} + +//---------------------------------------------------------------------------- +void vtkPVMetaDataInformation::CopyFromObject(vtkObject* obj) +{ + this->SetInformationData(NULL); + + vtkAlgorithmOutput* algOutput = vtkAlgorithmOutput::SafeDownCast(obj); + if (!algOutput) + { + vtkAlgorithm* alg = vtkAlgorithm::SafeDownCast(obj); + if (alg) + { + algOutput = alg->GetOutputPort(0); + } + + } + if (!algOutput) + { + vtkErrorMacro("Information can only be gathered from a vtkAlgorithmOutput."); + return; + } + + vtkAlgorithm* reader = algOutput->GetProducer(); + vtkInformation* info = reader->GetExecutive()->GetOutputInformation( + algOutput->GetIndex()); + + if (info && info->Has(vtkMEDReader::META_DATA())) + { + this->SetInformationData(vtkDataObject::SafeDownCast(info->Get(vtkMEDReader::META_DATA()))); + } +} + +//---------------------------------------------------------------------------- +void vtkPVMetaDataInformation::CopyToStream(vtkClientServerStream* css) +{ + css->Reset(); + if (!this->InformationData) + { + *css << vtkClientServerStream::Reply + << vtkClientServerStream::InsertArray( + static_cast(NULL), 0) + << vtkClientServerStream::End; + return; + } + + vtkDataObject* clone = this->InformationData->NewInstance(); + clone->ShallowCopy(this->InformationData); + + vtkGenericDataObjectWriter* writer = vtkGenericDataObjectWriter::New(); + writer->SetFileTypeToBinary(); + writer->WriteToOutputStringOn(); + writer->SetInputData(clone); + writer->Write(); + + *css << vtkClientServerStream::Reply + << vtkClientServerStream::InsertArray( + writer->GetBinaryOutputString(), + writer->GetOutputStringLength()) + << vtkClientServerStream::End; + writer->RemoveAllInputs(); + writer->Delete(); + clone->Delete(); +} + +//---------------------------------------------------------------------------- +void vtkPVMetaDataInformation::CopyFromStream(const vtkClientServerStream* css) +{ + this->SetInformationData(0); + vtkTypeUInt32 length; + if (css->GetArgumentLength(0, 0, &length) && length > 0) + { + unsigned char* raw_data = new unsigned char[length]; + css->GetArgument(0, 0, raw_data, length); + vtkGenericDataObjectReader* reader = vtkGenericDataObjectReader::New(); + reader->SetBinaryInputString(reinterpret_cast(raw_data), length); + reader->ReadFromInputStringOn(); + delete []raw_data; + reader->Update(); + this->SetInformationData(reader->GetOutput()); + reader->Delete(); + } +} + +void vtkPVMetaDataInformation::AddInformation(vtkPVInformation*) +{ +} + +//---------------------------------------------------------------------------- +void vtkPVMetaDataInformation::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os, indent); + os << indent << "InformationData: " << this->InformationData << endl; +} diff --git a/src/Plugins/MEDReader/plugin/MEDReaderIO/vtkPVMetaDataInformation.h b/src/Plugins/MEDReader/plugin/MEDReaderIO/vtkPVMetaDataInformation.h new file mode 100644 index 00000000..fbf7bfe3 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/MEDReaderIO/vtkPVMetaDataInformation.h @@ -0,0 +1,65 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay + +#ifndef __vtkPVMetaDataInformation_h +#define __vtkPVMetaDataInformation_h + +#include "vtkPVInformation.h" + +class vtkDataObject; +class vtkInformationDataObjectKey; + +class vtkPVMetaDataInformation : public vtkPVInformation +{ +public: + static vtkPVMetaDataInformation* New(); + vtkTypeMacro(vtkPVMetaDataInformation, vtkPVInformation); + void PrintSelf(ostream& os, vtkIndent indent); + + // Description: + // Transfer information about a single object into this object. + virtual void CopyFromObject(vtkObject*); + + //BTX + // Description: + // Manage a serialized version of the information. + virtual void CopyToStream(vtkClientServerStream*); + virtual void CopyFromStream(const vtkClientServerStream*); + virtual void AddInformation(vtkPVInformation*); + //ETX + + // Description: + // Returns the Information Data. + vtkGetObjectMacro(InformationData, vtkDataObject); + +//BTX +protected: + vtkPVMetaDataInformation(); + ~vtkPVMetaDataInformation(); + void SetInformationData(vtkDataObject*); + vtkDataObject* InformationData; + +private: + vtkPVMetaDataInformation(const vtkPVMetaDataInformation&); // Not implemented + void operator=(const vtkPVMetaDataInformation&); // Not implemented +//ETX +}; + +#endif diff --git a/src/Plugins/MEDReader/plugin/ParaViewPlugin/CMakeLists.txt b/src/Plugins/MEDReader/plugin/ParaViewPlugin/CMakeLists.txt new file mode 100644 index 00000000..15a5c803 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/ParaViewPlugin/CMakeLists.txt @@ -0,0 +1,105 @@ +set(interfaces) +set(ui_files) +set(sources) + +if(PARAVIEW_USE_QT) + set(ui_files + MEDReaderVectorsWidget.ui + MEDReaderTimeModeWidget.ui) + + set(sources + pqAbstractFieldsWidget.cxx + VectBoolSpreadSheet.cxx + VectBoolWidget.cxx + pqExtractGroupFieldsWidget.cxx + pqMEDReaderGraphUtils.cxx + pqMEDReaderVectorsWidget.cxx + pqMEDReaderTimeModeWidget.cxx + pqMEDReaderReloadWidget.cxx + pqMEDReaderTimesFlagsWidget.cxx + pqMEDReaderFieldsWidget.cxx) + + paraview_plugin_add_property_widget( + KIND WIDGET + TYPE "MEDReaderTimeModeWidgetType" + CLASS_NAME pqMEDReaderTimeModeWidget + INTERFACES property_interfaces + SOURCES property_sources) + list(APPEND interfaces + ${property_interfaces}) + list(APPEND sources + ${property_sources}) + + paraview_plugin_add_property_widget( + KIND WIDGET + TYPE "MEDReaderReloadWidgetType" + CLASS_NAME pqMEDReaderReloadWidget + INTERFACES property_interfaces + SOURCES property_sources) + list(APPEND interfaces + ${property_interfaces}) + list(APPEND sources + ${property_sources}) + + paraview_plugin_add_property_widget( + KIND WIDGET + TYPE "MEDReaderVectorsWidgetType" + CLASS_NAME pqMEDReaderVectorsWidget + INTERFACES property_interfaces + SOURCES property_sources) + list(APPEND interfaces + ${property_interfaces}) + list(APPEND sources + ${property_sources}) + + paraview_plugin_add_property_widget( + KIND WIDGET + TYPE "MEDReaderTimesFlagsWidgetType" + CLASS_NAME pqMEDReaderTimesFlagsWidget + INTERFACES property_interfaces + SOURCES property_sources) + list(APPEND interfaces + ${property_interfaces}) + list(APPEND sources + ${property_sources}) + + paraview_plugin_add_property_widget( + KIND WIDGET + TYPE "MEDReaderFieldsWidgetType" + CLASS_NAME pqMEDReaderFieldsWidget + INTERFACES property_interfaces + SOURCES property_sources) + list(APPEND interfaces + ${property_interfaces}) + list(APPEND sources + ${property_sources}) + + paraview_plugin_add_property_widget( + KIND WIDGET + TYPE "ExtractGroupFieldsWidgetType" + CLASS_NAME pqExtractGroupFieldsWidget + INTERFACES property_interfaces + SOURCES property_sources) + list(APPEND interfaces + ${property_interfaces}) + list(APPEND sources + ${property_sources}) + +endif(PARAVIEW_USE_QT) + +paraview_add_plugin(MEDReader + VERSION "5.0" + UI_INTERFACES ${interfaces} + UI_FILES ${ui_files} + SOURCES ${sources} + UI_RESOURCES Resources/pqMEDReader.qrc + SERVER_MANAGER_XML Resources/MEDReaderServer.xml + MODULES MEDReaderIO + MODULE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/../MEDReaderIO/vtk.module" + ) + +install(TARGETS MEDReader + RUNTIME DESTINATION lib/paraview + LIBRARY DESTINATION lib/paraview + ARCHIVE DESTINATION lib/paraview + ) diff --git a/src/Plugins/MEDReader/plugin/ParaViewPlugin/MEDReaderTimeModeWidget.ui b/src/Plugins/MEDReader/plugin/ParaViewPlugin/MEDReaderTimeModeWidget.ui new file mode 100644 index 00000000..419d1e7b --- /dev/null +++ b/src/Plugins/MEDReader/plugin/ParaViewPlugin/MEDReaderTimeModeWidget.ui @@ -0,0 +1,37 @@ + + + MEDReaderTimeModeWidget + + + + + + true + + + + + + + + + Time + + + true + + + + + + + Mode + + + + + + + + + diff --git a/src/Plugins/MEDReader/plugin/ParaViewPlugin/MEDReaderVectorsWidget.ui b/src/Plugins/MEDReader/plugin/ParaViewPlugin/MEDReaderVectorsWidget.ui new file mode 100644 index 00000000..c9424273 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/ParaViewPlugin/MEDReaderVectorsWidget.ui @@ -0,0 +1,39 @@ + + + MEDReaderVectorsWidget + + + + 0 + + + 0 + + + + + true + + + + + + + 0 + + + 0 + + + + + GenerateVectors + + + + + + + + + diff --git a/src/Plugins/MEDReader/plugin/ParaViewPlugin/Resources/Icons/pqCellData16.png b/src/Plugins/MEDReader/plugin/ParaViewPlugin/Resources/Icons/pqCellData16.png new file mode 100644 index 00000000..8a6f2a6c Binary files /dev/null and b/src/Plugins/MEDReader/plugin/ParaViewPlugin/Resources/Icons/pqCellData16.png differ diff --git a/src/Plugins/MEDReader/plugin/ParaViewPlugin/Resources/Icons/pqCellDataForWholeMesh16.png b/src/Plugins/MEDReader/plugin/ParaViewPlugin/Resources/Icons/pqCellDataForWholeMesh16.png new file mode 100644 index 00000000..93401f4c Binary files /dev/null and b/src/Plugins/MEDReader/plugin/ParaViewPlugin/Resources/Icons/pqCellDataForWholeMesh16.png differ diff --git a/src/Plugins/MEDReader/plugin/ParaViewPlugin/Resources/Icons/pqElnoData16.png b/src/Plugins/MEDReader/plugin/ParaViewPlugin/Resources/Icons/pqElnoData16.png new file mode 100644 index 00000000..e4618100 Binary files /dev/null and b/src/Plugins/MEDReader/plugin/ParaViewPlugin/Resources/Icons/pqElnoData16.png differ diff --git a/src/Plugins/MEDReader/plugin/ParaViewPlugin/Resources/Icons/pqPointData16.png b/src/Plugins/MEDReader/plugin/ParaViewPlugin/Resources/Icons/pqPointData16.png new file mode 100644 index 00000000..50367eaa Binary files /dev/null and b/src/Plugins/MEDReader/plugin/ParaViewPlugin/Resources/Icons/pqPointData16.png differ diff --git a/src/Plugins/MEDReader/plugin/ParaViewPlugin/Resources/Icons/pqQuadratureData16.png b/src/Plugins/MEDReader/plugin/ParaViewPlugin/Resources/Icons/pqQuadratureData16.png new file mode 100644 index 00000000..ff6e1995 Binary files /dev/null and b/src/Plugins/MEDReader/plugin/ParaViewPlugin/Resources/Icons/pqQuadratureData16.png differ diff --git a/src/Plugins/MEDReader/plugin/ParaViewPlugin/Resources/Icons/pqReloadFile16.png b/src/Plugins/MEDReader/plugin/ParaViewPlugin/Resources/Icons/pqReloadFile16.png new file mode 100644 index 00000000..cc13970b Binary files /dev/null and b/src/Plugins/MEDReader/plugin/ParaViewPlugin/Resources/Icons/pqReloadFile16.png differ diff --git a/src/Plugins/MEDReader/plugin/ParaViewPlugin/Resources/MEDReaderServer.xml b/src/Plugins/MEDReader/plugin/ParaViewPlugin/Resources/MEDReaderServer.xml new file mode 100644 index 00000000..807df538 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/ParaViewPlugin/Resources/MEDReaderServer.xml @@ -0,0 +1,464 @@ + + + + + + + + + + + + + + + This property specifies the file name for the MED reader. + + + + + + + + + + + + + + + + + + + + This property lists all the fields sorted by time steps then by mesh then by common support. + + + + + + This property define if the reader generate vectors. + + + + + + This property define if the reader read time steps as modes or not. + + + + + + + This property specifies the file name for the MED reader. + + + + + + + Available timestep values. + + + + + + + + + + + + + + + This property define which time steps the reader should read. + + + + + + + + + + + This property tells if ghost cell generator is applied in parallel mode right after MED file read. This call has a CPU cost but it avoids viz artefacts (interfaces inside dataset on domain borders) you can experiment during usage of filters sensitive to ghost cells in // mode (Ex transparency, contour...). + + + + + + + + + + + + + + + + + + + This property specifies the input to the Level Scalars filter. + + + + + + + + + + + + + + + This property lists all groups and families to select. + + + + + + Choose which part of the dataset to keep regarding the selected Groups/Families. When 0 (default) the direct selection + is kept. When 1 the complementary part is selected. + + + + + + This property returns the name of the mesh. + + + + + + + + + + + + + + + + + + This property specifies the input to the Level Scalars filter. + + + + + + + + + + + + + + + This property lists all the geometric types to select. + + + + + Choose which part of the dataset to keep regarding the selected geometric types. When 0 (default) the direct selection + is kept. When 1 the complementary part is selected. + + + + + + + "Create a Mesh with ELNO values mapped at each vertex." + + + + + + + + + + + + + + + + The value of this property determines how far the points + will move in the mesh before to be colored using ELNO fields on it. A value of 0 positions the points at the centroid of the cell; a value of 1 leaves them at their original positions. + + + + + + + + + "Extract the surface of a dataset with ELNO values." + + + + + + + + + + + + + + + + + Specifies the offset array from which we generate ELNO points. + + + + + + + + + + + + + + + + + "Create a point set with data at quadrature points." + + + + + + + + + + + + + + + + + + + Specifies the offset array from which we generate Gauss points. + + + + + + + + + + + + + + + + + + + "Create a point set with data at quadrature points." + + + + + + + + + + + + + + + + + + + Specifies the offset array from which we generate ELNO points. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + This property specifies the input to the Generate Structural Element filter. + + + + + + diff --git a/src/Plugins/MEDReader/plugin/ParaViewPlugin/Resources/UI/MEDReaderTimeModeWidget.ui b/src/Plugins/MEDReader/plugin/ParaViewPlugin/Resources/UI/MEDReaderTimeModeWidget.ui new file mode 100644 index 00000000..419d1e7b --- /dev/null +++ b/src/Plugins/MEDReader/plugin/ParaViewPlugin/Resources/UI/MEDReaderTimeModeWidget.ui @@ -0,0 +1,37 @@ + + + MEDReaderTimeModeWidget + + + + + + true + + + + + + + + + Time + + + true + + + + + + + Mode + + + + + + + + + diff --git a/src/Plugins/MEDReader/plugin/ParaViewPlugin/Resources/UI/MEDReaderVectorsWidget.ui b/src/Plugins/MEDReader/plugin/ParaViewPlugin/Resources/UI/MEDReaderVectorsWidget.ui new file mode 100644 index 00000000..c9424273 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/ParaViewPlugin/Resources/UI/MEDReaderVectorsWidget.ui @@ -0,0 +1,39 @@ + + + MEDReaderVectorsWidget + + + + 0 + + + 0 + + + + + true + + + + + + + 0 + + + 0 + + + + + GenerateVectors + + + + + + + + + diff --git a/src/Plugins/MEDReader/plugin/ParaViewPlugin/Resources/pqMEDReader.qrc b/src/Plugins/MEDReader/plugin/ParaViewPlugin/Resources/pqMEDReader.qrc new file mode 100644 index 00000000..1006ebf7 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/ParaViewPlugin/Resources/pqMEDReader.qrc @@ -0,0 +1,10 @@ + + + Icons/pqCellData16.png + Icons/pqPointData16.png + Icons/pqQuadratureData16.png + Icons/pqElnoData16.png + Icons/pqReloadFile16.png + Icons/pqCellDataForWholeMesh16.png + + diff --git a/src/Plugins/MEDReader/plugin/ParaViewPlugin/VectBoolSpreadSheet.cxx b/src/Plugins/MEDReader/plugin/ParaViewPlugin/VectBoolSpreadSheet.cxx new file mode 100644 index 00000000..4bd937fc --- /dev/null +++ b/src/Plugins/MEDReader/plugin/ParaViewPlugin/VectBoolSpreadSheet.cxx @@ -0,0 +1,300 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay + +#include "VectBoolSpreadSheet.h" +#include +#include +#include +#include +#include + +VectBoolModel::VectBoolModel(int maxSize, int nbRows):_activated(maxSize,false),_nb_rows(nbRows) +{ + setCurSize(maxSize); +} + +int VectBoolModel::rowCount(const QModelIndex &) const +{ + return _nb_rows; +} + +int VectBoolModel::columnCount (const QModelIndex &) const +{ + int sz(curSize()); + if(sz%_nb_rows==0) + return sz/_nb_rows; + else + return sz/_nb_rows+1; +} + +QVariant VectBoolModel::headerData(int section, Qt::Orientation orientation, int role) const +{ + if(role==Qt::FontRole) + { + QFont serifFont("Arial",6, QFont::Bold); + return QVariant(serifFont); + } + else if(role==Qt::DisplayRole) + { + return QVariant(section); + } + else + return QAbstractTableModel::headerData(section,orientation,role); +} + +bool VectBoolModel::setData(const QModelIndex& index, const QVariant& value, int role) +{ + if(role==Qt::UserRole) + { + int pos(index.column()*_nb_rows+index.row()); + bool v(_activated[pos]); + _activated[pos]=!v; + emit nbOfTimeStepsOnChanged((int)getNbOfActivatedTimeSteps(),_dts.size()); + return true; + } + else + return QAbstractTableModel::setData(index,value,role); +} + +QVariant VectBoolModel::data(const QModelIndex &index, int role) const +{ + if(role==Qt::FontRole) + { + QFont serifFont("Arial",8);//, QFont::Bold); + return QVariant(serifFont); + } + else if(role==Qt::UserRole) + { + int pos(index.column()*_nb_rows+index.row()); + return QVariant(_activated[pos]); + } + else if(role==Qt::DisplayRole) + { + int pos(index.column()*_nb_rows+index.row()); + if(pos=curSize()) + return QVariant(); + if(_activated[pos]) + { + QBrush b(QColor(0,255,0)); + return QVariant(b); + } + else + { + QBrush b(QColor(255,0,0)); + return QVariant(b); + } + } + else + return QVariant(); +} + +bool VectBoolModel::setCurrentItems(const QStringList& dts, const QStringList& its, const QStringList& tts) +{ + int oldSize(curSize()); + if(oldSize!=dts.size()) + { + emit layoutAboutToBeChanged(); + _dts=dts; _its=its; _tts=tts; + emit layoutChanged(); + return true; + } + else + { + _dts=dts; _its=its; _tts=tts; + return false; + } + +} + +void VectBoolModel::setNumberOfRows(int newNbOfRows) +{ + if(newNbOfRows!=_nb_rows) + { + emit beginResetModel(); + _nb_rows=newNbOfRows; + emit endResetModel(); + } +} + +void VectBoolModel::selectUnselectAll() +{ + int nbOn(getNbOfActivatedTimeSteps()),sz(curSize()),signalVal(0); + emit layoutAboutToBeChanged(); + if(nbOn>sz/2) + { + for(int ii=0;iihorizontalHeader()->setMinimumSectionSize(2); + this->horizontalHeader()->setDefaultSectionSize(2); + this->verticalHeader()->setMinimumSectionSize(2); + this->verticalHeader()->setDefaultSectionSize(2); + this->setItemDelegate(_delegate); + this->verticalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); + this->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); + + this->resizeColumnsToContents(); + this->resizeRowsToContents(); + //this->verticalHeader()->hide(); + //this->horizontalHeader()->hide(); +} + +void VectBoolSpreadSheet::selectionChanged(const QItemSelection & selected, const QItemSelection & deselected) +{ + QAbstractItemModel * m(model()); + foreach(const QModelIndex& ind,selected.indexes()) + { + m->setData(ind,QVariant(true),Qt::UserRole); + } + QTableView::selectionChanged(selected,deselected); + this->clearSelection(); +} + +void VectBoolSpreadSheet::nbOfRowsHasChanged(int newNbOfRows) +{ + VectBoolModel *zeModel(qobject_cast(model())); + if(!zeModel) + return ; + zeModel->setNumberOfRows(newNbOfRows); + this->verticalHeader()->setUpdatesEnabled(true);//please let this line. If not a refresh problem appear at EDF configuration. +} + +void VectBoolSpreadSheet::selectUnselectAllFired() +{ + VectBoolModel *zeModel(qobject_cast(model())); + if(!zeModel) + return ; + zeModel->selectUnselectAll(); +} + +/////////////// + +OnOffDelegate::OnOffDelegate(QObject *parent):QStyledItemDelegate(parent) +{ +} + +void OnOffDelegate::paint(QPainter *painter, const QStyleOptionViewItem & option, const QModelIndex& index) const +{ + painter->save(); + const QAbstractItemModel *zeModel(index.model()); + QString cont(zeModel->data(index,Qt::DisplayRole).toString()); + bool checked(zeModel->data(index,Qt::UserRole).toBool()); + QFont font; + if(checked) + { + QFont zeFont(zeModel->data(index,Qt::FontRole).value()); + zeFont.setBold(true); + font=zeFont; + } + else + { + font=QFont("Arial",7); + font.setItalic(true); + } + painter->setFont(font); + Qt::Alignment al((Qt::Alignment)zeModel->data(index,Qt::TextAlignmentRole).toInt()); + if(checked) + {//sizeHint + //painter->drawEllipse(option.rect); + //painter->setBrush(QBrush(Qt::lightGray,Qt::Dense6Pattern)); + painter->setBrush(QBrush(QColor(230,230,255))); + painter->drawRect(option.rect); + //painter->drawLine(option.rect.topLeft(),option.rect.bottomRight()); + //painter->drawLine(option.rect.topRight(),option.rect.bottomLeft()); + } + else + { + painter->setBrush(QBrush(QColor(255,255,255))); + painter->drawRect(option.rect); + painter->setPen(Qt::lightGray); + } + painter->drawText(option.rect,cont,QTextOption(al)); + painter->restore(); +} diff --git a/src/Plugins/MEDReader/plugin/ParaViewPlugin/VectBoolSpreadSheet.h b/src/Plugins/MEDReader/plugin/ParaViewPlugin/VectBoolSpreadSheet.h new file mode 100644 index 00000000..82d06b9e --- /dev/null +++ b/src/Plugins/MEDReader/plugin/ParaViewPlugin/VectBoolSpreadSheet.h @@ -0,0 +1,80 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay + +#include +#include +#include +#include +#include +#include + +class OnOffDelegate : public QStyledItemDelegate//QItemDelegate +{ + Q_OBJECT + public: + OnOffDelegate(QObject *parent=0); + void paint(QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index) const; +}; + +class VectBoolSpreadSheet : public QTableView +{ + Q_OBJECT +public: + VectBoolSpreadSheet(QWidget *parent); + ~VectBoolSpreadSheet(); + void init(); + void selectionChanged(const QItemSelection & selected, const QItemSelection & deselected); +public slots: + void nbOfRowsHasChanged(int newNbOfRows); + void selectUnselectAllFired(); +private: + OnOffDelegate *_delegate; +}; + +class VectBoolModel : public QAbstractTableModel +{ + Q_OBJECT +public: + VectBoolModel(int maxSize, int nbRows); + std::size_t getSize() const { return _activated.size(); } + bool getStatusAt(int pos) const { return _activated[pos]; } + void setStatusAt(int pos, bool val) { _activated[pos]=val; } + int rowCount( const QModelIndex & parent = QModelIndex() ) const; + int columnCount ( const QModelIndex & parent = QModelIndex() ) const; + bool setData(const QModelIndex & index, const QVariant & value, int role = Qt::EditRole ); + QVariant data(const QModelIndex &index, int role) const; + QVariant headerData ( int section, Qt::Orientation orientation, int role = Qt::DisplayRole ) const; + // non const methods. + bool setCurrentItems(const QStringList& dts, const QStringList& its, const QStringList& tts); + int getNbOfActivatedTimeSteps() const; +public: + void setNumberOfRows(int newNbOfRows); + void selectUnselectAll(); +signals: + void nbOfTimeStepsOnChanged(int newNbOfTimeStepsOn, int totalNbOfTS); +private: + void setCurSize(int sz); + int curSize() const; +private: + std::vector _activated; + QStringList _dts,_its,_tts; + int _cur_size; + int _nb_rows; +}; diff --git a/src/Plugins/MEDReader/plugin/ParaViewPlugin/VectBoolWidget.cxx b/src/Plugins/MEDReader/plugin/ParaViewPlugin/VectBoolWidget.cxx new file mode 100644 index 00000000..24c7aead --- /dev/null +++ b/src/Plugins/MEDReader/plugin/ParaViewPlugin/VectBoolWidget.cxx @@ -0,0 +1,197 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay + +#include "VectBoolWidget.h" +#include "VectBoolSpreadSheet.h" + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +NbOfActiveTSDisplay::NbOfActiveTSDisplay(QWidget *parent):QLabel(parent),_nb_of_items_on(0),_total_nb_of_items(0) +{ + setFont(QFont("Arial",8,QFont::Bold)); + setTextFormat(Qt::AutoText); +} + + void NbOfActiveTSDisplay::display(int nbOfItemsOn, int totalNbOfItems) +{ + _nb_of_items_on=nbOfItemsOn; + _total_nb_of_items=totalNbOfItems; + setText(QString("%1/%2").arg(_nb_of_items_on).arg(_total_nb_of_items)); +} + +void NbOfActiveTSDisplay::totalNbOfItemsChanged(int totalNbOfItems) +{ + _total_nb_of_items=totalNbOfItems; + setText(QString("%1/%2").arg(_nb_of_items_on).arg(_total_nb_of_items)); +} + +VectBoolItem::VectBoolItem(QObject *parent, int pos, VectBoolModel *model):QObject(parent),_pos(pos),_old_status(true),_model(model) +{ +} + +bool VectBoolItem::isActivated() const +{ + return _model->getStatusAt(_pos); +} + +void VectBoolItem::activated(bool val) +{ + _model->setStatusAt(_pos,val); + _old_status=val; +} + +void VectBoolItem::theModelHasChanged() +{ + bool val(isActivated()); + if(val!=_old_status) + { + _old_status=val; + emit changed(); + } +} + +VectBoolWidget::VectBoolWidget(QWidget *parent, int nbOfItems):QFrame(parent) +{ + QSizePolicy sizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding); + sizePolicy.setHorizontalStretch(0); + sizePolicy.setVerticalStretch(0); + sizePolicy.setHeightForWidth(this->sizePolicy().hasHeightForWidth()); + this->setSizePolicy(sizePolicy); + this->setFrameShape(QFrame::StyledPanel); + this->setFrameShadow(QFrame::Raised); + _horizontal_layout=new QHBoxLayout(this); + _horizontal_layout->setSpacing(6); + _horizontal_layout->setContentsMargins(11,11,11,11); + _spreadsheet_container=new QFrame(this); + QSizePolicy sizePolicy1(QSizePolicy::Expanding,QSizePolicy::Expanding); + sizePolicy1.setHorizontalStretch(0); + sizePolicy1.setVerticalStretch(0); + sizePolicy1.setHeightForWidth(_spreadsheet_container->sizePolicy().hasHeightForWidth()); + _spreadsheet_container->setSizePolicy(sizePolicy1); + _grid_layout=new QGridLayout(_spreadsheet_container); + _grid_layout->setSpacing(6); + _grid_layout->setContentsMargins(11,11,11,11); + _horizontal_layout->addWidget(_spreadsheet_container); + _group_box=new QGroupBox(this); + QSizePolicy sizePolicy2(QSizePolicy::Minimum, QSizePolicy::Expanding); + sizePolicy2.setHorizontalStretch(0); + sizePolicy2.setVerticalStretch(0); + sizePolicy2.setHeightForWidth(_group_box->sizePolicy().hasHeightForWidth()); + _group_box->setSizePolicy(sizePolicy2); + // + _vertical_layout=new QVBoxLayout(_group_box); + _vertical_layout->setSpacing(6); + _vertical_layout->setContentsMargins(11,11,11,11); + _nb_of_time_steps_on=new NbOfActiveTSDisplay(_group_box); + _nb_of_time_steps_on->setMaximumSize(QSize(40,16777215)); + _vertical_layout->addWidget(_nb_of_time_steps_on); + _nb_of_rows_selecter=new QSlider(_group_box); + QSizePolicy sizePolicy3(QSizePolicy::Expanding,QSizePolicy::Expanding); + sizePolicy3.setHorizontalStretch(0); + sizePolicy3.setVerticalStretch(0); + sizePolicy3.setHeightForWidth(_nb_of_rows_selecter->sizePolicy().hasHeightForWidth()); + _nb_of_rows_selecter->setSizePolicy(sizePolicy3); + _nb_of_rows_selecter->setOrientation(Qt::Vertical); + _vertical_layout->addWidget(_nb_of_rows_selecter); + _sel_unsel_all=new QPushButton(_group_box); + _sel_unsel_all->setMaximumSize(QSize(40,16777215)); + _sel_unsel_all->setText(QString("Sel All")); + QFont font("Andale Mono"); + font.setPointSize(5); + _sel_unsel_all->setFont(font); + _vertical_layout->addWidget(_sel_unsel_all); + // + _horizontal_layout->addWidget(_group_box); + // + _vbw=new VectBoolSpreadSheet(_spreadsheet_container); + QSizePolicy sizePolicy4(QSizePolicy::Expanding,QSizePolicy::Expanding); + sizePolicy4.setHorizontalStretch(0); + sizePolicy4.setVerticalStretch(0); + sizePolicy4.setHeightForWidth(_vbw->sizePolicy().hasHeightForWidth()); + _vbw->setSizePolicy(sizePolicy4); + _nb_of_rows_selecter->setSizePolicy(sizePolicy3); + _nb_of_rows_selecter->setMinimum(1); + _nb_of_rows_selecter->setMaximum(GetMaxTickValueOfSlider(nbOfItems)); + _nb_of_rows_selecter->setTickInterval(1); + _nb_of_rows_selecter->setTickPosition(QSlider::TicksRight); + connect(_nb_of_rows_selecter,SIGNAL(valueChanged(int)),_vbw,SLOT(nbOfRowsHasChanged(int))); + connect(_sel_unsel_all,SIGNAL(clicked()),_vbw,SLOT(selectUnselectAllFired())); + _grid_layout->addWidget(_vbw); + _vbw->init(); + _vbm=new VectBoolModel(nbOfItems,1); + _vbw->setModel(_vbm); + connect(this->_vbm,SIGNAL(nbOfTimeStepsOnChanged(int,int)),_nb_of_time_steps_on,SLOT(display(int,int))); + _vbm->selectUnselectAll(); + _nb_of_rows_selecter->setValue(_nb_of_rows_selecter->maximum()); + // + for(int i=0;igetNumberOfBoolItems()) + { + std::cerr << "ERROR ! Internal Error in VectBoolWidget::setItems ! Current number of items is bigger than the current one !" << std::endl; + std::cerr << curNbOfItems << " "<setCurrentItems(dts,its,tts)) + { + _nb_of_rows_selecter->setMaximum(GetMaxTickValueOfSlider(curNbOfItems)); + _nb_of_rows_selecter->setValue(_nb_of_rows_selecter->maximum()); + _nb_of_time_steps_on->display(_vbm->getNbOfActivatedTimeSteps(),dts.size()); + } +} + +int VectBoolWidget::getNumberOfBoolItems() const +{ + return (int)_vbm->getSize(); +} + +int VectBoolWidget::GetMaxTickValueOfSlider(int val) +{ + double valf((double)val); + double ret(sqrt(valf)); + int reti((int)ret); + if(reti*reti==val) + return reti; + else + return reti+1; +} + +VectBoolWidget::~VectBoolWidget() +{ + delete _vbm; +} diff --git a/src/Plugins/MEDReader/plugin/ParaViewPlugin/VectBoolWidget.h b/src/Plugins/MEDReader/plugin/ParaViewPlugin/VectBoolWidget.h new file mode 100644 index 00000000..b0cc0567 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/ParaViewPlugin/VectBoolWidget.h @@ -0,0 +1,92 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay + +#ifndef __VECTBOOLWIDGET_H__ +#define __VECTBOOLWIDGET_H__ + +#include +#include +#include + +class QSlider; +class QGroupBox; +class QHBoxLayout; +class QVBoxLayout; +class QGridLayout; +class QPushButton; +class VectBoolModel; +class VectBoolSpreadSheet; + +class NbOfActiveTSDisplay : public QLabel +{ +Q_OBJECT +public: + NbOfActiveTSDisplay(QWidget *parent=0); +public slots: + void display(int nbOfItemsOn, int totalNbOfItems); + void totalNbOfItemsChanged(int totalNbOfItems); +private: + int _nb_of_items_on; + int _total_nb_of_items; +}; + +class VectBoolItem : public QObject +{ +Q_OBJECT +Q_PROPERTY(bool activated READ isActivated WRITE activated) +public: + VectBoolItem(QObject *parent, int pos, VectBoolModel *model); + bool isActivated() const; + void activated(bool val); +public slots: + void theModelHasChanged(); +signals: + void changed(); +private: + int _pos; + mutable bool _old_status; + VectBoolModel *_model; +}; + +class VectBoolWidget : public QFrame +{ +public: + VectBoolWidget(QWidget *parent, int nbOfItems); + ~VectBoolWidget(); + int getNumberOfBoolItems() const; + void setItems(const QStringList& dts, const QStringList& its, const QStringList& tts); + const QMap& getItems() const { return _items; } +private: + static int GetMaxTickValueOfSlider(int val); +private: + QMap _items; + QHBoxLayout *_horizontal_layout; + QFrame *_spreadsheet_container; + QGridLayout *_grid_layout; + QGroupBox *_group_box; + QVBoxLayout *_vertical_layout; + NbOfActiveTSDisplay *_nb_of_time_steps_on; + QSlider *_nb_of_rows_selecter; + QPushButton *_sel_unsel_all; + VectBoolSpreadSheet *_vbw; + VectBoolModel *_vbm; +}; + +#endif diff --git a/src/Plugins/MEDReader/plugin/ParaViewPlugin/pqAbstractFieldsWidget.cxx b/src/Plugins/MEDReader/plugin/ParaViewPlugin/pqAbstractFieldsWidget.cxx new file mode 100644 index 00000000..cdaae619 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/ParaViewPlugin/pqAbstractFieldsWidget.cxx @@ -0,0 +1,147 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay + +#include "pqAbstractFieldsWidget.h" + +#include "pqArrayListDomain.h" +#include "pqTreeWidget.h" +#include "pqTreeWidgetItemObject.h" + +#include +#include +//----------------------------------------------------------------------------- +pqAbstractFieldsWidget::pqAbstractFieldsWidget( + vtkSMProxy *smproxy, vtkSMProperty *smproperty, QWidget *parentObject) +: Superclass(smproxy, parentObject) +{ + this->NItems = 0; + this->visibleHeader = true; + this->setShowLabel(false); + + // Grid Layout + QGridLayout* gridLayout = new QGridLayout(this); + + // Tree widget + this->TreeWidget = new pqTreeWidget(this); + gridLayout->addWidget(this->TreeWidget); +} + +//----------------------------------------------------------------------------- +pqAbstractFieldsWidget::~pqAbstractFieldsWidget() +{ + delete this->TreeWidget; +} + +void pqAbstractFieldsWidget::initializeTreeWidget(vtkSMProxy *smproxy, vtkSMProperty *smproperty) +{ + // Load Tree Widget Items + this->loadTreeWidgetItems(); + + // Connect Property Domain to the fieldDomain property, + // so setFieldDomain is called when the domain changes. + vtkSMDomain* arraySelectionDomain = smproperty->GetDomain("array_list"); + new pqArrayListDomain(this,"fieldsDomain", smproxy, smproperty, arraySelectionDomain); + + // Connect property to field QProperty using a biderectionnal property link + this->addPropertyLink(this, "fields", SIGNAL(fieldsChanged()), + smproxy, smproperty); + + // Call slot when the tree is changed + QObject::connect(this->TreeWidget, SIGNAL(itemChanged(QTreeWidgetItem*, int)), + this, SLOT(onItemChanged(QTreeWidgetItem*, int))); + +} + +//----------------------------------------------------------------------------- +QSize pqAbstractFieldsWidget::sizeHint() const +{ + // TreeWidget sizeHintForRow is too low, correcting to +3. + int pix = (this->TreeWidget->sizeHintForRow(0) + 3) * this->NItems; + int margin[4]; + this->TreeWidget->getContentsMargins(margin, margin + 1, margin + 2, margin + 3); + int h = pix + margin[1] + margin[3]; + if (this->visibleHeader) + { + h += this->TreeWidget->header()->frameSize().height(); + } + h = std::min(300, h); + return QSize(156, h); +} + +//----------------------------------------------------------------------------- +void pqAbstractFieldsWidget::onItemChanged(QTreeWidgetItem* item, int column) const +{ + if (column != 0) + { + return; + } + emit fieldsChanged(); +} + +//----------------------------------------------------------------------------- +QList< QList< QVariant> > pqAbstractFieldsWidget::getFields() const +{ + // Put together a Field list, using ItemMap + QList< QList< QVariant> > ret; + QList< QVariant > field; + QMap::const_iterator it; + for (it = this->ItemMap.begin(); it != this->ItemMap.end(); it++) + { + field.clear(); + field.append(it.key()); + field.append(it.value()->isChecked()); + ret.append(field); + } + return ret; +} + +//----------------------------------------------------------------------------- +void pqAbstractFieldsWidget::setFields(QList< QList< QVariant> > fields) +{ + // Update each item checkboxes, using fields names and ItemMap + QMap::iterator it; + foreach (QList< QVariant> field, fields) + { + it = this->ItemMap.find(field[0].toString()); + if (it == this->ItemMap.end()) + { + qDebug("Found an unknow Field in pqAbstractFieldsWidget::setFields, ignoring"); + continue; + } + it.value()->setChecked(field[1].toBool()); + } +} + +//----------------------------------------------------------------------------- +void pqAbstractFieldsWidget::setFieldsDomain(QList< QList< QVariant> > fields) +{ + // Block signals so the reloading does not trigger + // UncheckPropertyModified event + this->blockSignals(true); + + // Load the tree widget + this->loadTreeWidgetItems(); + + // Set fields checkboxes + this->setFields(fields); + + // Restore signals + this->blockSignals(false); +} diff --git a/src/Plugins/MEDReader/plugin/ParaViewPlugin/pqAbstractFieldsWidget.h b/src/Plugins/MEDReader/plugin/ParaViewPlugin/pqAbstractFieldsWidget.h new file mode 100644 index 00000000..10d01984 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/ParaViewPlugin/pqAbstractFieldsWidget.h @@ -0,0 +1,103 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay + +#ifndef __pqAbstractFieldsWidget_h +#define __pqAbstractFieldsWidget_h + +#include "pqPropertyWidget.h" + +class pqTreeWidget; +class pqTreeWidgetItemObject; +class QTreeWidgetItem; +class vtkSMProxy; +class vtkSMProperty; + +class pqAbstractFieldsWidget : public pqPropertyWidget +{ + typedef pqPropertyWidget Superclass; + Q_OBJECT + + // Description + // Property Qt used to set/get the fields with the property link + Q_PROPERTY(QList< QList< QVariant> > fields READ getFields WRITE setFields) + + // Description + // Property Qt used to set the gorup fields domain with the property link + Q_PROPERTY(QList< QList< QVariant> > fieldsDomain READ getFields WRITE setFieldsDomain) +public: + pqAbstractFieldsWidget( + vtkSMProxy *smproxy, vtkSMProperty *smproperty, QWidget *parentObject = 0); + virtual ~pqAbstractFieldsWidget(); + + // Description + // Corrected size hint, +3 pixel on each line + virtual QSize sizeHint() const; + +signals: + // Description + // Signal emited when selected field changed + void fieldsChanged() const; + +protected: + // Description + // bidrectionnal property link setter/getter + virtual QList< QList< QVariant> > getFields() const; + virtual void setFields(QList< QList< QVariant> > fields); + + // Description + // Update the domain, eg: reload + virtual void setFieldsDomain(QList< QList< QVariant> > fields); + + + // Description + // Initialize the widget items and connect it to property + // To be called by subclasses in constructor + virtual void initializeTreeWidget(vtkSMProxy *smproxy, vtkSMProperty *smproperty); + + // Description + // (Re)Load the tree widget items using recovered meta data graph + virtual void loadTreeWidgetItems() = 0; + + // Description + // Tree widget + pqTreeWidget* TreeWidget; + + // Description + // Number of items, for graphic purpose + int NItems; + + // Description + // Map of ItemPropertyName -> Item Pointer, contains only leaf. + QMap< QString, pqTreeWidgetItemObject*> ItemMap; + + // Description + // Bug in qt, header->isVisible always return false, storing this info here + // https://bugreports.qt.io/browse/QTBUG-12939 + bool visibleHeader; +protected slots: + // Description + // Slot called when the tree widget changed + virtual void onItemChanged(QTreeWidgetItem* itemOrig, int column) const; + +private: + Q_DISABLE_COPY(pqAbstractFieldsWidget); +}; + +#endif diff --git a/src/Plugins/MEDReader/plugin/ParaViewPlugin/pqExtractGroupFieldsWidget.cxx b/src/Plugins/MEDReader/plugin/ParaViewPlugin/pqExtractGroupFieldsWidget.cxx new file mode 100644 index 00000000..3dd3d2ef --- /dev/null +++ b/src/Plugins/MEDReader/plugin/ParaViewPlugin/pqExtractGroupFieldsWidget.cxx @@ -0,0 +1,202 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay + +#include "pqExtractGroupFieldsWidget.h" + +#include "vtkMEDReader.h" +#include "vtkExtractGroup.h" +#include "vtkPVMetaDataInformation.h" + +#include "pqTreeWidget.h" +#include "pqTreeWidgetItemObject.h" +#include "vtkGraph.h" +#include "vtkNew.h" +#include "vtkStringArray.h" +#include "vtkDataSetAttributes.h" +#include "vtkTree.h" + +#include + +//----------------------------------------------------------------------------- +pqExtractGroupFieldsWidget::pqExtractGroupFieldsWidget( + vtkSMProxy *smproxy, vtkSMProperty *smproperty, QWidget *parentObject) +: Superclass(smproxy, smproperty, parentObject) +{ + this->TreeWidget->setHeaderLabel("Groups And Families"); + this->initializeTreeWidget(smproxy, smproperty); +} + +//----------------------------------------------------------------------------- +pqExtractGroupFieldsWidget::~pqExtractGroupFieldsWidget() +{ +} + +//----------------------------------------------------------------------------- +void pqExtractGroupFieldsWidget::loadTreeWidgetItems() +{ + // Recover Graph + vtkPVMetaDataInformation *info(vtkPVMetaDataInformation::New()); + this->proxy()->GatherInformation(info); + vtkGraph* graph = vtkGraph::SafeDownCast(info->GetInformationData()); + if(!graph) + { + return; + } + + // Clear Tree Widget + this->TreeWidget->clear(); + + // Clear Item Map + this->ItemMap.clear(); + + // Create a tree + vtkNew tree; + tree->CheckedShallowCopy(graph); + vtkStringArray* names = vtkStringArray::SafeDownCast(tree->GetVertexData()->GetAbstractArray("Names")); + + vtkIdType root = tree->GetRoot(); + vtkIdType mfg = tree->GetChild(root, 1); // MeshesFamsGrps + + vtkIdType mesh = tree->GetChild(mfg, 0); // mesh + QString meshName = QString(names->GetValue(mesh)); + + this->NItems = 0; + + vtkIdType grps = tree->GetChild(mesh, 0); // grps + pqTreeWidgetItemObject* grpsItem = new pqTreeWidgetItemObject(this->TreeWidget, QStringList()); + this->NItems++; + grpsItem->setText(0, QString("Groups of \"" + meshName + "\"")); + + vtkIdType fams = tree->GetChild(mesh, 1); // fams + pqTreeWidgetItemObject* famsItem = new pqTreeWidgetItemObject(this->TreeWidget, QStringList()); + this->NItems++; + famsItem->setText(0, QString("Families of \"" + meshName + "\"")); + + std::map famDataTypeMap; + + for (int i = 0; i < tree->GetNumberOfChildren(fams); i++) + { + // Familly Item + vtkIdType fam = tree->GetChild(fams, i); + pqTreeWidgetItemObject *famItem = new pqTreeWidgetItemObject(famsItem, QStringList()); + this->NItems++; + + // Familly name + std::string str = names->GetValue(fam); + const char* separator = vtkMEDReader::GetSeparator(); + size_t pos = str.find(separator); + std::string name = str.substr(0, pos); + famItem->setText(0, QString(name.c_str())); + + // Property Name + QString propertyName = QString(vtkExtractGroup::GetFamStart()) + QString(str.c_str()); + this->ItemMap[propertyName] = famItem; + + // Datatype flag + int dataTypeFlag = atoi(str.substr(pos + strlen(separator)).c_str()); + famDataTypeMap[name] = dataTypeFlag; + + // Checkbox + famItem->setFlags(famItem->flags() | Qt::ItemIsUserCheckable | Qt::ItemIsSelectable); + famItem->setChecked(true); + + // Tooltip + QString famToolTip(QString("%1 (%2)").arg(QString(name.c_str())).arg(dataTypeFlag)); + famItem->setData(0, Qt::ToolTipRole, famToolTip); + + // Pixmap + if (dataTypeFlag<0) + { + famItem->setData(0, Qt::DecorationRole, + QPixmap(":/ParaViewResources/Icons/pqCellData16.png")); + } + if (dataTypeFlag>0) + { + famItem->setData(0, Qt::DecorationRole, + QPixmap(":/ParaViewResources/Icons/pqPointData16.png")); + } + } + + for (int i = 0; i < tree->GetNumberOfChildren(grps); i++) + { + // Grp Item + vtkIdType grp = tree->GetChild(grps, i); + pqTreeWidgetItemObject *grpItem = new pqTreeWidgetItemObject(grpsItem, QStringList()); + this->NItems++; + + // Group name + QString name = QString(names->GetValue(grp)); + grpItem->setText(0, name); + + // Property Name + QString propertyName = QString(vtkExtractGroup::GetGrpStart()) + name; + this->ItemMap[propertyName] = grpItem; + + // Datatype flag + bool hasPoint = false; + bool hasCell = false; + int dataTypeFlag = 0; + for (int j = 0; j < tree->GetNumberOfChildren(grp); j++) + { + dataTypeFlag = famDataTypeMap[names->GetValue(tree->GetChild(grp, j))]; + if (dataTypeFlag > 0) + { + hasPoint = true; + } + else if (dataTypeFlag < 0) + { + hasCell = true; + } + else + { + dataTypeFlag = 0; + break; + } + + if (hasPoint && hasCell) + { + dataTypeFlag = 0; + break; + } + } + + // Checkbox + grpItem->setFlags(grpItem->flags() | Qt::ItemIsUserCheckable | Qt::ItemIsSelectable); + grpItem->setChecked(true); + + // Tooltip + grpItem->setData(0, Qt::ToolTipRole, name); + + // Pixmap + if (dataTypeFlag<0) + { + grpItem->setData(0, Qt::DecorationRole, + QPixmap(":/ParaViewResources/Icons/pqCellData16.png")); + } + if (dataTypeFlag>0) + { + grpItem->setData(0, Qt::DecorationRole, + QPixmap(":/ParaViewResources/Icons/pqPointData16.png")); + } + } + + // Expand Widget + this->TreeWidget->expandAll(); +} diff --git a/src/Plugins/MEDReader/plugin/ParaViewPlugin/pqExtractGroupFieldsWidget.h b/src/Plugins/MEDReader/plugin/ParaViewPlugin/pqExtractGroupFieldsWidget.h new file mode 100644 index 00000000..34add9bb --- /dev/null +++ b/src/Plugins/MEDReader/plugin/ParaViewPlugin/pqExtractGroupFieldsWidget.h @@ -0,0 +1,48 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay + +#ifndef __pqExtractGroupFieldsWidget_h +#define __pqExtractGroupFieldsWidget_h + +#include "pqAbstractFieldsWidget.h" + +class vtkSMProxy; +class vtkSMProperty; + +class pqExtractGroupFieldsWidget : public pqAbstractFieldsWidget +{ + typedef pqAbstractFieldsWidget Superclass; + Q_OBJECT + +public: + pqExtractGroupFieldsWidget( + vtkSMProxy *smproxy, vtkSMProperty *smproperty, QWidget *parentObject = 0); + virtual ~pqExtractGroupFieldsWidget(); + +protected: + // Description + // Load the tree widget using recovered meta data graph + void loadTreeWidgetItems(); + +private: + Q_DISABLE_COPY(pqExtractGroupFieldsWidget); +}; + +#endif diff --git a/src/Plugins/MEDReader/plugin/ParaViewPlugin/pqMEDReaderFieldsWidget.cxx b/src/Plugins/MEDReader/plugin/ParaViewPlugin/pqMEDReaderFieldsWidget.cxx new file mode 100644 index 00000000..29151f03 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/ParaViewPlugin/pqMEDReaderFieldsWidget.cxx @@ -0,0 +1,278 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay + +#include "pqMEDReaderFieldsWidget.h" + +#include "vtkMEDReader.h" +#include "vtkPVMetaDataInformation.h" + +#include "pqTreeWidget.h" +#include "pqTreeWidgetItemObject.h" +#include "vtkDataSetAttributes.h" +#include "vtkGraph.h" +#include "vtkNew.h" +#include "vtkStringArray.h" +#include "vtkTree.h" + +#include +#include + +//----------------------------------------------------------------------------- +pqMEDReaderFieldsWidget::pqMEDReaderFieldsWidget( + vtkSMProxy *smproxy, vtkSMProperty *smproperty, QWidget *parentObject) +: Superclass(smproxy, smproperty, parentObject) +{ + this->TreeWidget->header()->hide(); + this->visibleHeader = false; + this->TransmitToParent = true; + this->initializeTreeWidget(smproxy, smproperty); +} + +//----------------------------------------------------------------------------- +pqMEDReaderFieldsWidget::~pqMEDReaderFieldsWidget() +{ +} + +//----------------------------------------------------------------------------- +void pqMEDReaderFieldsWidget::loadTreeWidgetItems() +{ + //Clear Item Map + this->ItemMap.clear(); + + // Clear tree + this->TreeWidget->clear(); + + // Clear unique checked item vector + this->UniqueCheckedItems.clear(); + + // Recover meta data graph + vtkPVMetaDataInformation *info(vtkPVMetaDataInformation::New()); + this->proxy()->GatherInformation(info); + vtkGraph* graph = vtkGraph::SafeDownCast(info->GetInformationData()); + + // Create a tree + vtkNew tree; + tree->CheckedShallowCopy(graph); + vtkStringArray* names = + vtkStringArray::SafeDownCast(tree->GetVertexData()->GetAbstractArray("Names")); + + if(!names)// In case of error right at the begining of loading process (empty MED file) + return ; + + vtkIdType root = tree->GetRoot(); + vtkIdType fst = tree->GetChild(root, 0); // FieldsStatusTree + + this->NItems = 0; + int nLeaves = 0; + for (int i = 1; i < tree->GetNumberOfChildren(fst); i += 2) + { + // Browse all interessting tree node + + // TSX Node + vtkIdType tsxId = tree->GetChild(fst, i); + vtkIdType tsId = tree->GetChild(fst, i - 1); + pqTreeWidgetItemObject *ts = new pqTreeWidgetItemObject(this->TreeWidget, QStringList()); + this->NItems++; + QString tsxName = QString(names->GetValue(tsxId)); + ts->setText(0, tsxName); + ts->setData(0, Qt::ToolTipRole, QString(names->GetValue(tsId))); + + // MAIL Node + for (int maili = 0; maili < tree->GetNumberOfChildren(tsxId); maili++) + { + vtkIdType mailId = tree->GetChild(tsxId, maili); + pqTreeWidgetItemObject *mail = new pqTreeWidgetItemObject(ts, QStringList()); + this->NItems++; + QString mailName = QString(names->GetValue(mailId)); + mail->setText(0, mailName); + mail->setData(0, Qt::ToolTipRole, QString(names->GetValue(mailId))); + + QString propertyBaseName = tsxName + "/" + mailName + "/"; + + // ComsupX node + for (int comsupi = 0; comsupi < tree->GetNumberOfChildren(mailId); comsupi++) + { + vtkIdType comSupId = tree->GetChild(mailId, comsupi); + pqTreeWidgetItemObject *comsup = new pqTreeWidgetItemObject(mail, QStringList()); + this->NItems++; + QString comsupName = QString(names->GetValue(comSupId)); + comsup->setText(0, comsupName); + + // ComSup tooltip + vtkIdType geoTypeId = tree->GetChild(comSupId, 1); + QString comSupToolTipName(names->GetValue(comSupId)); + for (int geoi = 0; geoi < tree->GetNumberOfChildren(geoTypeId); geoi++) + { + comSupToolTipName += QString("\n- %1").arg( + QString(names->GetValue(tree->GetChild(geoTypeId, geoi)))); + } + comsup->setData(0, Qt::ToolTipRole, comSupToolTipName); + + comsup->setFlags(comsup->flags() | Qt::ItemIsUserCheckable | Qt::ItemIsSelectable); + comsup->setChecked(true); + QObject::connect(comsup, SIGNAL(checkedStateChanged(bool)), this, SLOT(updateChecks())); + this->UniqueCheckedItems.push_back(comsup); + + QString fullComsupName = propertyBaseName + comsupName + "/"; + // Arrs node + vtkIdType arrId = tree->GetChild(comSupId, 0); + for (int arri = 0; arri < tree->GetNumberOfChildren(arrId); arri++) + { + pqTreeWidgetItemObject *array = new pqTreeWidgetItemObject(comsup, QStringList()); + this->NItems++; + + vtkIdType arrayId = tree->GetChild(arrId, arri); + std::string str = names->GetValue(arrayId); + this->ItemMap[fullComsupName + QString(str.c_str())] = array; + + const char* separator = vtkMEDReader::GetSeparator(); + size_t pos = str.find(separator); + std::string name = str.substr(0, pos); + + array->setText(0, QString(name.c_str())); + array->setFlags(array->flags() | Qt::ItemIsUserCheckable); + array->setChecked(true); + + // Special Field + if (tree->GetNumberOfChildren(arrayId) != 0) + { + QFont font; + font.setItalic(true); + font.setUnderline(true); + array->setData(0, Qt::FontRole, QVariant(font)); + + array->setData(0, Qt::ToolTipRole, + QString("Whole \" %1\" mesh").arg(name.c_str())); + array->setData(0, Qt::DecorationRole, + QPixmap(":/ParaViewResources/Icons/pqCellDataForWholeMesh16.png")); + } + // Standard Field + else + { + std::string spatialDiscr = str.substr(pos + strlen(separator)); + QString tooltip = QString(name.c_str() + QString(" (") + + spatialDiscr.c_str() + QString(")")); + array->setData(0, Qt::ToolTipRole, tooltip); + + QPixmap pix; + if (spatialDiscr == "P0") + { + pix.load(":/ParaViewResources/Icons/pqCellData16.png"); + } + else if (spatialDiscr == "P1") + { + pix.load(":/ParaViewResources/Icons/pqPointData16.png"); + } + else if (spatialDiscr == "GAUSS") + { + pix.load(":/ParaViewResources/Icons/pqQuadratureData16.png"); + } + else if (spatialDiscr == "GSSNE") + { + pix.load(":/ParaViewResources/Icons/pqElnoData16.png"); + } + array->setData(0, Qt::DecorationRole, pix); + } + + // Connection and updating checks for each item + QObject::connect(array, SIGNAL(checkedStateChanged(bool)), this, SLOT(updateChecks())); + nLeaves++; + } + } + } + } + // Expand tree + this->TreeWidget->expandAll(); +} + +//----------------------------------------------------------------------------- +void pqMEDReaderFieldsWidget::uncheckOtherUniqueItems(pqTreeWidgetItemObject* item) +{ + // Uncheck all other items in vector + foreach (pqTreeWidgetItemObject* otherItems, this->UniqueCheckedItems) + { + if (otherItems != item) + { + otherItems->setCheckState(0, Qt::Unchecked); + } + } +} + +//----------------------------------------------------------------------------- +void pqMEDReaderFieldsWidget::updateChecks() +{ + // Call updateCheck on the sender + pqTreeWidgetItemObject* item = qobject_cast(QObject::sender()); + this->updateChecks(item); +} + +//----------------------------------------------------------------------------- +void pqMEDReaderFieldsWidget::updateChecks(pqTreeWidgetItemObject* item) +{ + // When a Leaf item is checked, the parent will be checked (partially or not). + // Then other parents will be unchecked using uncheckOtherUniqueItems + // Then other parent leaf will be unchecked using updateChecks(parent) + // + // When a Parent item is checked, the leaf will be checked + // Then other parents will be unchecked using uncheckOtherUniqueItems + // Then other parent leaf will be unchecked using updateChecks(parent) + + if (item->childCount() == 0) + { + // Only first level leaf will transmit checks to parent + if (this->TransmitToParent) + { + // Recover correct parent state + Qt::CheckState state = item->checkState(0); + pqTreeWidgetItemObject* parent = + dynamic_cast(item->QTreeWidgetItem::parent()); + for (int i = 0; i < parent->childCount(); i++) + { + if (parent->child(i)->checkState(0) != state) + { + state = Qt::PartiallyChecked; + } + } + // Set Parent State + parent->setCheckState(0, state); + } + } + else + { + // Check/Uncheck childs, blocking looped call to slot + if (item->checkState(0) != Qt::PartiallyChecked) + { + this->TransmitToParent = false; + for (int i = 0; i < item->childCount(); i++) + { + pqTreeWidgetItemObject* leaf = + dynamic_cast(item->child(i)); + leaf->setCheckState(0, item->checkState(0)); + } + this->TransmitToParent = true; + } + + // Uncheck other unique checked items + if (item->checkState(0) != Qt::Unchecked) + { + this->uncheckOtherUniqueItems(item); + } + } +} diff --git a/src/Plugins/MEDReader/plugin/ParaViewPlugin/pqMEDReaderFieldsWidget.h b/src/Plugins/MEDReader/plugin/ParaViewPlugin/pqMEDReaderFieldsWidget.h new file mode 100644 index 00000000..a11dc1f9 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/ParaViewPlugin/pqMEDReaderFieldsWidget.h @@ -0,0 +1,70 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay + +#ifndef __pqMEDReaderFieldsWidget_h +#define __pqMEDReaderFieldsWidget_h + +#include "pqAbstractFieldsWidget.h" + +class vtkSMProxy; +class vtkSMProperty; +class pqMEDReaderFieldsWidget : public pqAbstractFieldsWidget +{ + typedef pqAbstractFieldsWidget Superclass; + Q_OBJECT + +public: + pqMEDReaderFieldsWidget( + vtkSMProxy *smproxy, vtkSMProperty *smproperty, QWidget *parentObject = 0); + virtual ~pqMEDReaderFieldsWidget(); + +protected: + // Descritpion + // Load the tree widget using recovered meta data graph + // and connect each item to indexed property + void loadTreeWidgetItems(); + + // Description + // Uncheck other unique checked item + void uncheckOtherUniqueItems(pqTreeWidgetItemObject* item); + + // Description + // Update check state of other items using provided item + void updateChecks(pqTreeWidgetItemObject* item); + + // Description + // Vector of unique checked items + std::vector UniqueCheckedItems; + + // Description + // Flag indicating if updateCheck method is recursivelly called, + // to avoid infinite loop + bool TransmitToParent; + +protected slots: + // Description + // Update check state of other items using the sender object + void updateChecks(); + +private: + Q_DISABLE_COPY(pqMEDReaderFieldsWidget); +}; + +#endif diff --git a/src/Plugins/MEDReader/plugin/ParaViewPlugin/pqMEDReaderGraphUtils.cxx b/src/Plugins/MEDReader/plugin/ParaViewPlugin/pqMEDReaderGraphUtils.cxx new file mode 100644 index 00000000..c347ce68 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/ParaViewPlugin/pqMEDReaderGraphUtils.cxx @@ -0,0 +1,77 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay + +#include "pqMEDReaderGraphUtils.h" + +#include "vtkGraph.h" +#include "vtkTree.h" +#include "vtkNew.h" +#include "vtkStringArray.h" +#include "vtkDataSetAttributes.h" + +namespace pqMedReaderGraphUtils +{ +void getCurrentTS(vtkGraph* graph, vtkIdType id, QStringList& dts, QStringList& its, + QStringList& tts) +{ + vtkNew tree; + tree->CheckedShallowCopy(graph); + vtkStringArray* names = vtkStringArray::SafeDownCast( + tree->GetVertexData()->GetAbstractArray("Names")); + vtkIdType root = tree->GetRoot(); + vtkIdType fst = tree->GetChild(root, 0); // FieldsStatusTree + vtkIdType tsr = tree->GetChild(tree->GetChild(fst, id*2), 0); //Time Step root node + vtkIdType tmp; + for (int i = 0; i < tree->GetNumberOfChildren(tsr); i++) + { + // Each Time Step + // Recover step + tmp = tree->GetChild(tsr, i); + dts << QString(names->GetValue(tmp)); + + // Recover mode + tmp = tree->GetChild(tmp, 0); + its << QString(names->GetValue(tmp)); + + // Recover value + tmp = tree->GetChild(tmp, 0); + tts << QString(names->GetValue(tmp)); + } +} + +int getMaxNumberOfTS(vtkGraph* graph) +{ + vtkNew tree; + tree->CheckedShallowCopy(graph); + vtkStringArray* names = vtkStringArray::SafeDownCast( + tree->GetVertexData()->GetAbstractArray("Names")); + vtkIdType root = tree->GetRoot(); + vtkIdType fst = tree->GetChild(root, 0); // FieldsStatusTree + vtkIdType tmp; + int nbTS = 0; + for (int i = 0; i < tree->GetNumberOfChildren(fst); i += 2) + { + // Look for max time steps + tmp = tree->GetChild(tree->GetChild(fst, i), 0); + nbTS = std::max(nbTS, names->GetVariantValue(tmp).ToInt()); + } + return nbTS; +} +} diff --git a/src/Plugins/MEDReader/plugin/ParaViewPlugin/pqMEDReaderGraphUtils.h b/src/Plugins/MEDReader/plugin/ParaViewPlugin/pqMEDReaderGraphUtils.h new file mode 100644 index 00000000..cb91d537 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/ParaViewPlugin/pqMEDReaderGraphUtils.h @@ -0,0 +1,43 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay + +#ifndef _pqMEDReaderGraphUtils_h +#define _pqMEDReaderGraphUtils_h + +#include "vtkType.h" + +#include + +class vtkGraph; +class pqTreeWidget; + +namespace pqMedReaderGraphUtils +{ + // Description + // Extract Current Time Step from a meta data graph + void getCurrentTS(vtkGraph* graph, vtkIdType id, QStringList& dts, + QStringList& its, QStringList& tts); + + // Description + // Extract the maximum number of timestep from a meta data graph + int getMaxNumberOfTS(vtkGraph* graph); +} + +#endif diff --git a/src/Plugins/MEDReader/plugin/ParaViewPlugin/pqMEDReaderReloadWidget.cxx b/src/Plugins/MEDReader/plugin/ParaViewPlugin/pqMEDReaderReloadWidget.cxx new file mode 100644 index 00000000..82323c9f --- /dev/null +++ b/src/Plugins/MEDReader/plugin/ParaViewPlugin/pqMEDReaderReloadWidget.cxx @@ -0,0 +1,96 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay + +#include "pqMEDReaderReloadWidget.h" + +#include "vtkSMProxy.h" +#include "vtkSMSourceProxy.h" +#include "vtkSMProperty.h" + +#include "pqPropertiesPanel.h" + +#include +#include + +pqMEDReaderReloadWidget::pqMEDReaderReloadWidget(vtkSMProxy *smProxy, + vtkSMProperty *proxyProperty, + QWidget *pWidget) +: pqPropertyWidget(smProxy, pWidget), + Property(proxyProperty) +{ + this->setShowLabel(false); + + // Grid Layout + QGridLayout* gridLayout = new QGridLayout(this); + gridLayout->setAlignment(Qt::AlignRight); + + // Reload Button + QPushButton *button = new QPushButton(); + button->setIcon(QIcon(":/ParaViewResources/Icons/pqReloadFile16.png")); + button->setFixedSize(button->sizeHint()); + gridLayout->addWidget(button); + + // Connection + connect(button, SIGNAL(clicked()), this, SLOT(buttonClicked())); +} + +pqMEDReaderReloadWidget::~pqMEDReaderReloadWidget() +{ +} + +void pqMEDReaderReloadWidget::buttonClicked() +{ + // Recovering Property Panel + pqPropertiesPanel* panel = NULL; + QObject* tmp = this; + while (panel == NULL) + { + tmp = tmp->parent(); + if (!tmp) + { + break; + } + panel = qobject_cast(tmp); + } + + if (!panel) + { + qDebug() << "Cannot find pqPropertiesPanel, reload may not work"; + } + else + { + // Restoring property to defaults, necessary when unchecked property are not applied + panel->propertiesRestoreDefaults(); + } + + // Reloading the data and associated properties + this->Property->Modified(); + this->proxy()->UpdateProperty(this->proxy()->GetPropertyName(this->Property)); + vtkSMSourceProxy::SafeDownCast(this->proxy())->UpdatePipelineInformation(); + + // Restting properties to dufault using domains and XML values + this->proxy()->ResetPropertiesToDefault(); + + if (panel) + { + // Disabled apply button inderectly + panel->propertiesRestoreDefaults(); + } +} diff --git a/src/Plugins/MEDReader/plugin/ParaViewPlugin/pqMEDReaderReloadWidget.h b/src/Plugins/MEDReader/plugin/ParaViewPlugin/pqMEDReaderReloadWidget.h new file mode 100644 index 00000000..1dd3ff17 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/ParaViewPlugin/pqMEDReaderReloadWidget.h @@ -0,0 +1,46 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay + +#ifndef _pqMEDReaderReloadWidget_h +#define _pqMEDReaderReloadWidget_h + +#include "pqPropertyWidget.h" + +class pqMEDReaderReloadWidget : public pqPropertyWidget +{ + Q_OBJECT + +public: + explicit pqMEDReaderReloadWidget(vtkSMProxy *proxy, + vtkSMProperty *property, + QWidget *parent = 0); + ~pqMEDReaderReloadWidget(); + +private slots: + // Description + // Called when button is clicked + // Reload the med reader + void buttonClicked(); + +private: + vtkSMProperty* Property; +}; + +#endif // _pqMEDReaderReloadWidget_h diff --git a/src/Plugins/MEDReader/plugin/ParaViewPlugin/pqMEDReaderTimeModeWidget.cxx b/src/Plugins/MEDReader/plugin/ParaViewPlugin/pqMEDReaderTimeModeWidget.cxx new file mode 100644 index 00000000..bf5f8e8f --- /dev/null +++ b/src/Plugins/MEDReader/plugin/ParaViewPlugin/pqMEDReaderTimeModeWidget.cxx @@ -0,0 +1,67 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay + +#include "ui_MEDReaderTimeModeWidget.h" +#include "pqMEDReaderTimeModeWidget.h" + +#include "pqCoreUtilities.h" +//----------------------------------------------------------------------------- +// Internals +class pqMEDReaderTimeModeWidget::pqInternals : public Ui::MEDReaderTimeModeWidget +{ +public: + pqInternals(pqMEDReaderTimeModeWidget* self) + { + this->setupUi(self); + } +}; + +//----------------------------------------------------------------------------- +pqMEDReaderTimeModeWidget::pqMEDReaderTimeModeWidget( + vtkSMProxy *smproxy, vtkSMProperty *smproperty, QWidget *parentObject) +: Superclass(smproxy, parentObject), Internals(new pqMEDReaderTimeModeWidget::pqInternals(this)) +{ + this->setShowLabel(false); + this->ModeEnabled = false; + + this->addPropertyLink(this, "ModeEnabled" , SIGNAL(modeEnabled(bool)), smproperty); + QObject::connect(this->Internals->modeMode, SIGNAL(toggled(bool)), + this, SLOT(setModeEnabled(bool))); +} + +//----------------------------------------------------------------------------- +pqMEDReaderTimeModeWidget::~pqMEDReaderTimeModeWidget() +{ +} + +//----------------------------------------------------------------------------- +bool pqMEDReaderTimeModeWidget::isModeEnabled() const +{ + return this->ModeEnabled; +} + +//----------------------------------------------------------------------------- +void pqMEDReaderTimeModeWidget::setModeEnabled(bool enable) +{ + this->ModeEnabled = enable; + this->Internals->modeMode->setChecked(enable); + this->Internals->stdMode->setChecked(!enable); + emit modeEnabled(enable); +} diff --git a/src/Plugins/MEDReader/plugin/ParaViewPlugin/pqMEDReaderTimeModeWidget.h b/src/Plugins/MEDReader/plugin/ParaViewPlugin/pqMEDReaderTimeModeWidget.h new file mode 100644 index 00000000..437de291 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/ParaViewPlugin/pqMEDReaderTimeModeWidget.h @@ -0,0 +1,66 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay + +#ifndef __pqMEDReaderTimeModeWidget_h +#define __pqMEDReaderTimeModeWidget_h + +#include "pqPropertyWidget.h" + +class pqMEDReaderTimeModeWidget : public pqPropertyWidget +{ + Q_OBJECT + + // Qt property to link to vtk property + Q_PROPERTY(bool ModeEnabled READ isModeEnabled WRITE setModeEnabled) + + typedef pqPropertyWidget Superclass; +public: + pqMEDReaderTimeModeWidget( + vtkSMProxy *smproxy, vtkSMProperty *smproperty, QWidget *parentObject = 0); + virtual ~pqMEDReaderTimeModeWidget(); + + // Description + // Qt property getter + bool isModeEnabled() const; + +public slots: + // Description + // Qt Property setter + void setModeEnabled(bool enable); + +signals: + // Description + // Qt Property signal + void modeEnabled(bool enable); + +private: + Q_DISABLE_COPY(pqMEDReaderTimeModeWidget); + + // Description + // Qt property value + bool ModeEnabled; + + // Description + // UI Internals + class pqInternals; + pqInternals* Internals; +}; + +#endif diff --git a/src/Plugins/MEDReader/plugin/ParaViewPlugin/pqMEDReaderTimesFlagsWidget.cxx b/src/Plugins/MEDReader/plugin/ParaViewPlugin/pqMEDReaderTimesFlagsWidget.cxx new file mode 100644 index 00000000..23d840b5 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/ParaViewPlugin/pqMEDReaderTimesFlagsWidget.cxx @@ -0,0 +1,224 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay + +#include "pqMEDReaderTimesFlagsWidget.h" + +#include "VectBoolWidget.h" +#include "pqMEDReaderGraphUtils.h" +#include "vtkMEDReader.h" +#include "vtkPVMetaDataInformation.h" + +#include "pqCoreUtilities.h" +#include "pqArrayListDomain.h" +#include "pqPropertiesPanel.h" +#include "vtkGraph.h" +#include "vtkGraphWriter.h" +#include "vtkInformationDataObjectMetaDataKey.h" +#include "vtkNew.h" +#include "vtkSMDoubleVectorProperty.h" +#include "vtkSMStringVectorProperty.h" +#include "vtkTree.h" + +#include +#include + +//----------------------------------------------------------------------------- +pqMEDReaderTimesFlagsWidget::pqMEDReaderTimesFlagsWidget( + vtkSMProxy *smproxy, vtkSMProperty *smproperty, QWidget *parentObject) +: Superclass(smproxy, parentObject) +{ + this->CachedTsId = -1; + this->TimesVectWidget = NULL; + this->setShowLabel(false); + + // Grid Layout + this->TimesVectLayout = new QGridLayout(this); + + // VectBoolWidget + this->CreateTimesVectWidget(); + this->UpdateTimeSteps(); + + // Connect timeStepStatus property to update time steps method + vtkSMProperty* prop = smproxy? smproxy->GetProperty("FieldsStatus") : NULL; + if (!prop) + { + qDebug("Could not locate property named 'FieldsStatus'. " + "pqMEDReaderTimesFlagsWidget will have no updated labels."); + } + else + { + pqCoreUtilities::connect(prop, vtkCommand::UncheckedPropertyModifiedEvent, + this, SLOT(UpdateTimeSteps())); + } + + // Connect Property Domain to the timeStepDomain property, + // so setTimeStepDomain is called when the domain changes. + vtkSMDomain* arraySelectionDomain = smproperty->GetDomain("array_list"); + new pqArrayListDomain(this,"timeStepsDomain", smproxy, smproperty, arraySelectionDomain); + + // Connect property to timeStep QProperty using a biderectionnal property link + this->addPropertyLink(this, "timeSteps", SIGNAL(timeStepsChanged()), + smproxy, smproperty); + + if(!this->TimesVectWidget) // In case of error right at the begining of loading process (empty MED file) + return ; + + const QMap& items(this->TimesVectWidget->getItems()); + QMap::const_iterator it; + for (it = items.begin(); it != items.end(); it++) + { + QObject::connect(it.value(), SIGNAL(changed()), this, SLOT(onItemChanged())); + } +} + +//----------------------------------------------------------------------------- +pqMEDReaderTimesFlagsWidget::~pqMEDReaderTimesFlagsWidget() +{ + delete this->TimesVectWidget; +} + +//----------------------------------------------------------------------------- +void pqMEDReaderTimesFlagsWidget::onItemChanged() const +{ + emit timeStepsChanged(); +} + +//----------------------------------------------------------------------------- +QList< QList< QVariant> > pqMEDReaderTimesFlagsWidget::getTimeSteps() const +{ + // Put together a TimeStep list, using ItemMap + QList< QList< QVariant> > ret; + QList< QVariant > timeStep; + if(!this->TimesVectWidget) // In case of error right at the begining of loading process (empty MED file) + return ret; + const QMap& items(this->TimesVectWidget->getItems()); + QMap::const_iterator it; + for (it = items.begin(); it != items.end(); it++) + { + timeStep.clear(); + timeStep.append(it.key()); + timeStep.append(it.value()->isActivated()); + ret.append(timeStep); + } + return ret; +} + +//----------------------------------------------------------------------------- +void pqMEDReaderTimesFlagsWidget::setTimeSteps(QList< QList< QVariant> > timeSteps) +{ + // Update each item checkboxes, using timeSteps names and ItemMap + const QMap& items(this->TimesVectWidget->getItems()); + QMap::const_iterator it; + foreach (QList< QVariant> timeStep, timeSteps) + { + it = items.find(timeStep[0].toString()); + if (it == items.end()) + { + qDebug("Found an unknow TimeStep in pqMEDReaderTimesFlagsWidget::setTimeSteps, ignoring"); + continue; + } + it.value()->activated(timeStep[1].toBool()); + } +} + +//----------------------------------------------------------------------------- +void pqMEDReaderTimesFlagsWidget::setTimeStepsDomain(QList< QList< QVariant> > timeSteps) +{ + cout<<"TimeStepsDomai"<blockSignals(true); + + // Load the tree widget + this->CreateTimesVectWidget(); + + // Set timeSteps checkboxes + this->setTimeSteps(timeSteps); + + // Restore signals + this->blockSignals(false); +} + +//----------------------------------------------------------------------------- +void pqMEDReaderTimesFlagsWidget::CreateTimesVectWidget() +{ + // Recover Graph + vtkPVMetaDataInformation *info(vtkPVMetaDataInformation::New()); + this->proxy()->GatherInformation(info); + vtkGraph* graph = vtkGraph::SafeDownCast(info->GetInformationData()); + + // Delete the widget + if (this->TimesVectWidget != NULL) + { + delete this->TimesVectWidget; + } + + if(!graph) + return ;// In case of error right at the begining of loading process (empty MED file) + + // (Re)cretate widget + this->TimesVectWidget = new VectBoolWidget(this, + pqMedReaderGraphUtils::getMaxNumberOfTS(graph)); + this->TimesVectLayout->addWidget(this->TimesVectWidget); +} + +//----------------------------------------------------------------------------- +void pqMEDReaderTimesFlagsWidget::UpdateTimeSteps() +{ + // Recover property + vtkSMStringVectorProperty* prop = this->proxy()? + vtkSMStringVectorProperty::SafeDownCast(this->proxy()->GetProperty("FieldsStatus")) : NULL; + vtkIdType tsId = -1; + if (prop) + { + // Searching first activated leaf id + for (unsigned int i = 1; i < prop->GetNumberOfElements(); i += 2) + { + if (prop->GetElement(i)[0] == '1') + { + const char* leafString = prop->GetElement(i - 1); + const char* tmp = strchr(leafString, '/'); + size_t num = tmp - leafString; + char* dest = new char[num+1]; + strncpy(dest, leafString, num); + dest[num] = '\0'; + tsId = (vtkIdType)strtol(dest + 2, NULL, 10); + delete [] dest; + break; + } + } + } + + if (tsId != -1 && tsId != this->CachedTsId) + { + // Recovering graph + this->CachedTsId = tsId; + vtkPVMetaDataInformation *info(vtkPVMetaDataInformation::New()); + this->proxy()->GatherInformation(info); + vtkGraph* g = vtkGraph::SafeDownCast(info->GetInformationData()); + + // Updating times steps using leaf id + QStringList dts, its, tts; + if(g) + pqMedReaderGraphUtils::getCurrentTS(g, tsId, dts, its, tts); + if(this->TimesVectWidget) + this->TimesVectWidget->setItems(dts, its, tts); + } +} diff --git a/src/Plugins/MEDReader/plugin/ParaViewPlugin/pqMEDReaderTimesFlagsWidget.h b/src/Plugins/MEDReader/plugin/ParaViewPlugin/pqMEDReaderTimesFlagsWidget.h new file mode 100644 index 00000000..742d13d9 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/ParaViewPlugin/pqMEDReaderTimesFlagsWidget.h @@ -0,0 +1,91 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay + +#ifndef __pqMEDReaderTimesFlagsWidget_h +#define __pqMEDReaderTimesFlagsWidget_h + +#include "pqPropertyWidget.h" + +class VectBoolWidget; +class QGridLayout; + +class pqMEDReaderTimesFlagsWidget : public pqPropertyWidget +{ + + typedef pqPropertyWidget Superclass; + Q_OBJECT + // Description + // Property Qt used to set/get the times steps with the property link + Q_PROPERTY(QList< QList< QVariant> > timeSteps READ getTimeSteps WRITE setTimeSteps) + // Description + // Property Qt used to set the gorup time steps domain with the property link + Q_PROPERTY(QList< QList< QVariant> > timeStepsDomain READ getTimeSteps WRITE setTimeStepsDomain) +public: + pqMEDReaderTimesFlagsWidget( + vtkSMProxy *smproxy, vtkSMProperty *smproperty, QWidget *parentObject = 0); + virtual ~pqMEDReaderTimesFlagsWidget(); + +signals: + // Description + // Signal emited when selected field changed + void timeStepsChanged() const; + +protected slots: + // Description + // Slot called when item is changed + virtual void onItemChanged() const; + +protected slots: + // Description + // bidrectionnal property link setter/getter + virtual QList< QList< QVariant> > getTimeSteps() const; + virtual void setTimeSteps(QList< QList< QVariant> > timeSteps); + + // Description + // Update the domain, eg: reload + virtual void setTimeStepsDomain(QList< QList< QVariant> > timeSteps); + + + // Description + // Called when field status changed and reload the time steps + void UpdateTimeSteps(); + + // Description + // Called to create the vect widget, on creation or for a reload + void CreateTimesVectWidget(); + +protected: + // Description + // The Vect time widget + VectBoolWidget* TimesVectWidget; + + // Description + // The grid layout contian the vect times widget + QGridLayout* TimesVectLayout; + + // Description + // Id of current time step, for caching purpose + vtkIdType CachedTsId; + +private: + Q_DISABLE_COPY(pqMEDReaderTimesFlagsWidget); +}; + +#endif diff --git a/src/Plugins/MEDReader/plugin/ParaViewPlugin/pqMEDReaderVectorsWidget.cxx b/src/Plugins/MEDReader/plugin/ParaViewPlugin/pqMEDReaderVectorsWidget.cxx new file mode 100644 index 00000000..cede7b73 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/ParaViewPlugin/pqMEDReaderVectorsWidget.cxx @@ -0,0 +1,48 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay + +#include "pqMEDReaderVectorsWidget.h" +#include "ui_MEDReaderVectorsWidget.h" + +//----------------------------------------------------------------------------- +// Internals +class pqMEDReaderVectorsWidget::pqInternals : public Ui::MEDReaderVectorsWidget +{ +public: + pqInternals(pqMEDReaderVectorsWidget* self) + { + this->setupUi(self); + } +}; + +//----------------------------------------------------------------------------- +pqMEDReaderVectorsWidget::pqMEDReaderVectorsWidget( + vtkSMProxy *smproxy, vtkSMProperty *smproperty, QWidget *parentObject) +: Superclass(smproxy, parentObject), Internals(new pqMEDReaderVectorsWidget::pqInternals(this)) +{ + this->setShowLabel(false); + this->addPropertyLink(this->Internals->GenerateVects, "checked" , + SIGNAL(toggled(bool)), smproperty); +} + +//----------------------------------------------------------------------------- +pqMEDReaderVectorsWidget::~pqMEDReaderVectorsWidget() +{ +} diff --git a/src/Plugins/MEDReader/plugin/ParaViewPlugin/pqMEDReaderVectorsWidget.h b/src/Plugins/MEDReader/plugin/ParaViewPlugin/pqMEDReaderVectorsWidget.h new file mode 100644 index 00000000..dd2e34a8 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/ParaViewPlugin/pqMEDReaderVectorsWidget.h @@ -0,0 +1,42 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay + +#ifndef __pqMEDReaderVectorsWidget_h +#define __pqMEDReaderVectorsWidget_h + +#include "pqPropertyWidget.h" + +class pqMEDReaderVectorsWidget : public pqPropertyWidget +{ + Q_OBJECT + typedef pqPropertyWidget Superclass; +public: + pqMEDReaderVectorsWidget( + vtkSMProxy *smproxy, vtkSMProperty *smproperty, QWidget *parentObject = 0); + virtual ~pqMEDReaderVectorsWidget(); + +private: + Q_DISABLE_COPY(pqMEDReaderVectorsWidget); + + class pqInternals; + pqInternals* Internals; +}; + +#endif diff --git a/src/Plugins/MEDReader/plugin/TODO.txt b/src/Plugins/MEDReader/plugin/TODO.txt new file mode 100644 index 00000000..7c598555 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/TODO.txt @@ -0,0 +1,68 @@ + + + +TODO : +------ + + + +3 - propagate the update of filters connected directly or not (typically ExtractGroup) to the MEDReader when the groups have been updated. +UC : ForMEDReader16.med, then extractgroup, then return to MEDReader properties and select zeField3_1 & zeField4_1 -> ExtractGroup filter is out of date and "Apply" button not green. + + +Known bug : +----------- + + +Warning for users : +------------------- + +Try to avoid to change the localization along time on a same field +because it leads to an unfriendly behavior when playing. (bug seen in EDF2420 in ssnp121.rmed when applying GaussPoint filter and running different time steps. + + +TODO in MED: +------------ + +- Manage degenerated cases. + +DONE +---- + +0- Sur le time quand tout a echouer prendre le plus grand < (07/01/2014) + +1 - Load ForMEDReader8.med, Load ForMEDReader17.med +-> throw because of missynchronization of time. -> Alejandro (07/01/2014) + +1 - ELNO to be added only once not for each GAUSS_NE -> To test a file having > 1 field with GAUSS_NE + +1 - Keep tracks of built support to accelerate rendering in MEDFileFieldRepresentation. + +2 - in branch EDF1 : adm_local_without_kernel to put in install of MED_SRC +when in STANDALONE mode. + +0 - test22 doit etre sur les seg2 et tri3 + +1 - When Reload Applied it is possible with gui to unselect all ! + +0 - protect ExtractGroup against throw + +0 - protect ExctractCellType against throw + +0 - Extract cell type + Extract Group + +0 - bug client side when the field having the max number of TS is not first. + +0 - ELGA arrays choice of GaussPoints filter + +0 - Manage file containing only cartesian meshes. + +0 - Bug on vtkExtractGroup when attempting to extract on empty group. Previously, it led to SIGSEGV. + +0 - Add the frequency information in mode mode in the name of arrays in DataSet. + +0 - Addition of MeshName property in ExtractGroup (see testMEDReader9.py) + +0 - Bug when fields contains @ + +1 - Bug on reload the first leaf is not systematically activated. \ No newline at end of file diff --git a/src/Plugins/MEDReader/plugin/Test/CMakeLists.txt b/src/Plugins/MEDReader/plugin/Test/CMakeLists.txt new file mode 100644 index 00000000..e949f80d --- /dev/null +++ b/src/Plugins/MEDReader/plugin/Test/CMakeLists.txt @@ -0,0 +1,25 @@ +if (PARAVIEW_ENABLE_PYTHON) + file(GLOB pythonTests *.py) + list(FILTER pythonTests EXCLUDE REGEX ".*MEDReaderHelper.py$") + foreach(testFullPath ${pythonTests}) + get_filename_component(testFile ${testFullPath} NAME) + paraview_add_test_python(NO_RT DIRECT_DATA ${testFile}) + get_filename_component(testName ${testFile} NAME_WE) + set_tests_properties(Python-${testName} PROPERTIES ENVIRONMENT "PARAVIEW_DATA_ROOT=${CMAKE_CURRENT_SOURCE_DIR}/Data;LD_LIBRARY_PATH=${QT5_ROOT_DIR}/lib/:${MEDCOUPLING_ROOT_DIR}/lib/:${MEDFILE_ROOT_DIR}/lib/:${HDF5_ROOT_DIR}/lib:${PYTHON_ROOT_DIR}/lib;PYTHONPATH=${MEDCOUPLING_ROOT_DIR}/lib/python3.6/site-packages/;PV_PLUGIN_PATH=${CMAKE_BINARY_DIR}/lib/paraview-5.7/plugins/MEDReader;PARAVIEW_BIN_DIR=${ParaView_DIR}/bin/") + endforeach() +endif() + +if (PARAVIEW_USE_QT) + file(GLOB xmlTests *.xml) + foreach(testFullPath ${xmlTests}) + get_filename_component(testFile ${testFullPath} NAME) + get_filename_component(testName ${testFile} NAME_WE) + set (${testName}_USES_DIRECT_DATA ON) + paraview_add_client_tests( + LOAD_PLUGIN MEDReader + PLUGIN_PATH $ + BASELINE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/Data/Baseline + TEST_SCRIPTS ${testFile}) + set_tests_properties(pv.${testName} PROPERTIES ENVIRONMENT "PARAVIEW_DATA_ROOT=${CMAKE_CURRENT_SOURCE_DIR}/Data;LD_LIBRARY_PATH=${QT5_ROOT_DIR}/lib/:${MEDCOUPLING_ROOT_DIR}/lib/:${MEDFILE_ROOT_DIR}/lib/:${HDF5_ROOT_DIR}/lib:${PYTHON_ROOT_DIR}/lib") + endforeach() +endif() diff --git a/src/Plugins/MEDReader/plugin/Test/Data/Barreau_Elga_V11.rmed b/src/Plugins/MEDReader/plugin/Test/Data/Barreau_Elga_V11.rmed new file mode 100755 index 00000000..3bc86495 Binary files /dev/null and b/src/Plugins/MEDReader/plugin/Test/Data/Barreau_Elga_V11.rmed differ diff --git a/src/Plugins/MEDReader/plugin/Test/Data/Baseline/TestDataAnalysis.png b/src/Plugins/MEDReader/plugin/Test/Data/Baseline/TestDataAnalysis.png new file mode 100644 index 00000000..bcc29eeb Binary files /dev/null and b/src/Plugins/MEDReader/plugin/Test/Data/Baseline/TestDataAnalysis.png differ diff --git a/src/Plugins/MEDReader/plugin/Test/Data/Baseline/TestExtractCell.png b/src/Plugins/MEDReader/plugin/Test/Data/Baseline/TestExtractCell.png new file mode 100644 index 00000000..3819c627 Binary files /dev/null and b/src/Plugins/MEDReader/plugin/Test/Data/Baseline/TestExtractCell.png differ diff --git a/src/Plugins/MEDReader/plugin/Test/Data/Baseline/TestExtractGroup.png b/src/Plugins/MEDReader/plugin/Test/Data/Baseline/TestExtractGroup.png new file mode 100644 index 00000000..6fefac41 Binary files /dev/null and b/src/Plugins/MEDReader/plugin/Test/Data/Baseline/TestExtractGroup.png differ diff --git a/src/Plugins/MEDReader/plugin/Test/Data/Baseline/TestGUIPerf.png b/src/Plugins/MEDReader/plugin/Test/Data/Baseline/TestGUIPerf.png new file mode 100644 index 00000000..8531a9d2 Binary files /dev/null and b/src/Plugins/MEDReader/plugin/Test/Data/Baseline/TestGUIPerf.png differ diff --git a/src/Plugins/MEDReader/plugin/Test/Data/Baseline/TestGaussPoints.png b/src/Plugins/MEDReader/plugin/Test/Data/Baseline/TestGaussPoints.png new file mode 100644 index 00000000..f8c12eb6 Binary files /dev/null and b/src/Plugins/MEDReader/plugin/Test/Data/Baseline/TestGaussPoints.png differ diff --git a/src/Plugins/MEDReader/plugin/Test/Data/Baseline/TestMultiMesh.png b/src/Plugins/MEDReader/plugin/Test/Data/Baseline/TestMultiMesh.png new file mode 100644 index 00000000..c8202d16 Binary files /dev/null and b/src/Plugins/MEDReader/plugin/Test/Data/Baseline/TestMultiMesh.png differ diff --git a/src/Plugins/MEDReader/plugin/Test/Data/Baseline/TestPythonTrace.png b/src/Plugins/MEDReader/plugin/Test/Data/Baseline/TestPythonTrace.png new file mode 100644 index 00000000..3eebe44f Binary files /dev/null and b/src/Plugins/MEDReader/plugin/Test/Data/Baseline/TestPythonTrace.png differ diff --git a/src/Plugins/MEDReader/plugin/Test/Data/Baseline/TestScalarBar.png b/src/Plugins/MEDReader/plugin/Test/Data/Baseline/TestScalarBar.png new file mode 100644 index 00000000..7307b7c7 Binary files /dev/null and b/src/Plugins/MEDReader/plugin/Test/Data/Baseline/TestScalarBar.png differ diff --git a/src/Plugins/MEDReader/plugin/Test/Data/Baseline/TestWarpColorBar.png b/src/Plugins/MEDReader/plugin/Test/Data/Baseline/TestWarpColorBar.png new file mode 100644 index 00000000..2a969e53 Binary files /dev/null and b/src/Plugins/MEDReader/plugin/Test/Data/Baseline/TestWarpColorBar.png differ diff --git a/src/Plugins/MEDReader/plugin/Test/Data/Baseline/TestWidgetsPropertySynchronisation.png b/src/Plugins/MEDReader/plugin/Test/Data/Baseline/TestWidgetsPropertySynchronisation.png new file mode 100644 index 00000000..dab81320 Binary files /dev/null and b/src/Plugins/MEDReader/plugin/Test/Data/Baseline/TestWidgetsPropertySynchronisation.png differ diff --git a/src/Plugins/MEDReader/plugin/Test/Data/Baseline/TestWidgetsPropertySynchronisationBiDir.png b/src/Plugins/MEDReader/plugin/Test/Data/Baseline/TestWidgetsPropertySynchronisationBiDir.png new file mode 100644 index 00000000..6250869c Binary files /dev/null and b/src/Plugins/MEDReader/plugin/Test/Data/Baseline/TestWidgetsPropertySynchronisationBiDir.png differ diff --git a/src/Plugins/MEDReader/plugin/Test/Data/Baseline/testMEDReader0.png b/src/Plugins/MEDReader/plugin/Test/Data/Baseline/testMEDReader0.png new file mode 100644 index 00000000..86ef73da Binary files /dev/null and b/src/Plugins/MEDReader/plugin/Test/Data/Baseline/testMEDReader0.png differ diff --git a/src/Plugins/MEDReader/plugin/Test/Data/Baseline/testMEDReader10.png b/src/Plugins/MEDReader/plugin/Test/Data/Baseline/testMEDReader10.png new file mode 100644 index 00000000..4f0907df Binary files /dev/null and b/src/Plugins/MEDReader/plugin/Test/Data/Baseline/testMEDReader10.png differ diff --git a/src/Plugins/MEDReader/plugin/Test/Data/Baseline/testMEDReader13.png b/src/Plugins/MEDReader/plugin/Test/Data/Baseline/testMEDReader13.png new file mode 100644 index 00000000..ea4ebe98 Binary files /dev/null and b/src/Plugins/MEDReader/plugin/Test/Data/Baseline/testMEDReader13.png differ diff --git a/src/Plugins/MEDReader/plugin/Test/Data/Baseline/testMEDReader14.png b/src/Plugins/MEDReader/plugin/Test/Data/Baseline/testMEDReader14.png new file mode 100644 index 00000000..dea5f2d7 Binary files /dev/null and b/src/Plugins/MEDReader/plugin/Test/Data/Baseline/testMEDReader14.png differ diff --git a/src/Plugins/MEDReader/plugin/Test/Data/Baseline/testMEDReader15.png b/src/Plugins/MEDReader/plugin/Test/Data/Baseline/testMEDReader15.png new file mode 100644 index 00000000..4af9e7ea Binary files /dev/null and b/src/Plugins/MEDReader/plugin/Test/Data/Baseline/testMEDReader15.png differ diff --git a/src/Plugins/MEDReader/plugin/Test/Data/Baseline/testMEDReader19.png b/src/Plugins/MEDReader/plugin/Test/Data/Baseline/testMEDReader19.png new file mode 100644 index 00000000..f05519f4 Binary files /dev/null and b/src/Plugins/MEDReader/plugin/Test/Data/Baseline/testMEDReader19.png differ diff --git a/src/Plugins/MEDReader/plugin/Test/Data/Baseline/testMEDReader2.png b/src/Plugins/MEDReader/plugin/Test/Data/Baseline/testMEDReader2.png new file mode 100644 index 00000000..3489d127 Binary files /dev/null and b/src/Plugins/MEDReader/plugin/Test/Data/Baseline/testMEDReader2.png differ diff --git a/src/Plugins/MEDReader/plugin/Test/Data/Baseline/testMEDReader20.png b/src/Plugins/MEDReader/plugin/Test/Data/Baseline/testMEDReader20.png new file mode 100644 index 00000000..71cbf867 Binary files /dev/null and b/src/Plugins/MEDReader/plugin/Test/Data/Baseline/testMEDReader20.png differ diff --git a/src/Plugins/MEDReader/plugin/Test/Data/Baseline/testMEDReader21.png b/src/Plugins/MEDReader/plugin/Test/Data/Baseline/testMEDReader21.png new file mode 100644 index 00000000..6421dbc3 Binary files /dev/null and b/src/Plugins/MEDReader/plugin/Test/Data/Baseline/testMEDReader21.png differ diff --git a/src/Plugins/MEDReader/plugin/Test/Data/Baseline/testMEDReader3.png b/src/Plugins/MEDReader/plugin/Test/Data/Baseline/testMEDReader3.png new file mode 100644 index 00000000..8b6031de Binary files /dev/null and b/src/Plugins/MEDReader/plugin/Test/Data/Baseline/testMEDReader3.png differ diff --git a/src/Plugins/MEDReader/plugin/Test/Data/Baseline/testMEDReader4.png b/src/Plugins/MEDReader/plugin/Test/Data/Baseline/testMEDReader4.png new file mode 100644 index 00000000..17c6a9b6 Binary files /dev/null and b/src/Plugins/MEDReader/plugin/Test/Data/Baseline/testMEDReader4.png differ diff --git a/src/Plugins/MEDReader/plugin/Test/Data/Baseline/testMEDReader5.png b/src/Plugins/MEDReader/plugin/Test/Data/Baseline/testMEDReader5.png new file mode 100644 index 00000000..5b3d99b6 Binary files /dev/null and b/src/Plugins/MEDReader/plugin/Test/Data/Baseline/testMEDReader5.png differ diff --git a/src/Plugins/MEDReader/plugin/Test/Data/Baseline/testMEDReader6.png b/src/Plugins/MEDReader/plugin/Test/Data/Baseline/testMEDReader6.png new file mode 100644 index 00000000..64b8247f Binary files /dev/null and b/src/Plugins/MEDReader/plugin/Test/Data/Baseline/testMEDReader6.png differ diff --git a/src/Plugins/MEDReader/plugin/Test/Data/Baseline/testMEDReader7.png b/src/Plugins/MEDReader/plugin/Test/Data/Baseline/testMEDReader7.png new file mode 100644 index 00000000..a6df19ec Binary files /dev/null and b/src/Plugins/MEDReader/plugin/Test/Data/Baseline/testMEDReader7.png differ diff --git a/src/Plugins/MEDReader/plugin/Test/Data/Baseline/testMEDReader8.png b/src/Plugins/MEDReader/plugin/Test/Data/Baseline/testMEDReader8.png new file mode 100644 index 00000000..ebbd4f77 Binary files /dev/null and b/src/Plugins/MEDReader/plugin/Test/Data/Baseline/testMEDReader8.png differ diff --git a/src/Plugins/MEDReader/plugin/Test/Data/L15_R2_Temp.med b/src/Plugins/MEDReader/plugin/Test/Data/L15_R2_Temp.med new file mode 100644 index 00000000..8777711f Binary files /dev/null and b/src/Plugins/MEDReader/plugin/Test/Data/L15_R2_Temp.med differ diff --git a/src/Plugins/MEDReader/plugin/Test/Data/MultiTS.med b/src/Plugins/MEDReader/plugin/Test/Data/MultiTS.med new file mode 100644 index 00000000..96eba168 Binary files /dev/null and b/src/Plugins/MEDReader/plugin/Test/Data/MultiTS.med differ diff --git a/src/Plugins/MEDReader/plugin/Test/Data/barreau2.med b/src/Plugins/MEDReader/plugin/Test/Data/barreau2.med new file mode 100644 index 00000000..e6aa0003 Binary files /dev/null and b/src/Plugins/MEDReader/plugin/Test/Data/barreau2.med differ diff --git a/src/Plugins/MEDReader/plugin/Test/Data/japonlight.med b/src/Plugins/MEDReader/plugin/Test/Data/japonlight.med new file mode 100644 index 00000000..6964a1ae Binary files /dev/null and b/src/Plugins/MEDReader/plugin/Test/Data/japonlight.med differ diff --git a/src/Plugins/MEDReader/plugin/Test/Data/rosette_am.med b/src/Plugins/MEDReader/plugin/Test/Data/rosette_am.med new file mode 100644 index 00000000..55141dde Binary files /dev/null and b/src/Plugins/MEDReader/plugin/Test/Data/rosette_am.med differ diff --git a/src/Plugins/MEDReader/plugin/Test/Data/testGUIPerf.med b/src/Plugins/MEDReader/plugin/Test/Data/testGUIPerf.med new file mode 100644 index 00000000..e2b2bf5d Binary files /dev/null and b/src/Plugins/MEDReader/plugin/Test/Data/testGUIPerf.med differ diff --git a/src/Plugins/MEDReader/plugin/Test/Data/testWidgetSync.med b/src/Plugins/MEDReader/plugin/Test/Data/testWidgetSync.med new file mode 100644 index 00000000..5260d26a Binary files /dev/null and b/src/Plugins/MEDReader/plugin/Test/Data/testWidgetSync.med differ diff --git a/src/Plugins/MEDReader/plugin/Test/MEDReaderHelper.py b/src/Plugins/MEDReader/plugin/Test/MEDReaderHelper.py new file mode 100644 index 00000000..7d970f0f --- /dev/null +++ b/src/Plugins/MEDReader/plugin/Test/MEDReaderHelper.py @@ -0,0 +1,43 @@ +# -*- coding: iso-8859-1 -*- +# Copyright (C) 2019 CEA/DEN, EDF R&D +# +# This library 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. +# +# 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 +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +# +# Author : Anthony Geay (EDF R&D) + +def WriteInTmpDir(func): + def decoratedFunc(*args,**kwargs): + import tempfile,os + ret = None + with tempfile.TemporaryDirectory() as tmpdirname: + os.chdir(tmpdirname) + ret = func(*args,**kwargs) + pass + return ret + return decoratedFunc + +def RetriveBaseLine(imgFile): + import os,sys + try: + baselineIndex = sys.argv.index('-B')+1 + baselinePath = sys.argv[baselineIndex] + except: + print("Could not get baseline directory. Test failed.") + exit(1) + baseline_file = os.path.join(baselinePath, imgFile) + return os.path.abspath(baseline_file) + diff --git a/src/Plugins/MEDReader/plugin/Test/TestDataAnalysis.py b/src/Plugins/MEDReader/plugin/Test/TestDataAnalysis.py new file mode 100644 index 00000000..88778869 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/Test/TestDataAnalysis.py @@ -0,0 +1,180 @@ +# -*- coding: iso-8859-1 -*- +# Script de visualisation rosette et contrainte normale/tangeantielle + +# Donnees utilisateur +# +# MEDFILE : Fichier de resultat MED +# MAILLAGE : Nom du maillage +# GROUPE_FACE : Liste groupes de face de post-traitement +# COEFF_T1T2 : facteur scale rosette +# COEFF_TN : facteur scale normale/cisaillement +# +# T1 : Nom du champ SIRO_ELEM_T1 +# T2 : Nom du champ SIRO_ELEM_T2 +# T : Nom du champ SIRO_ELEM_SIGT +# N : Nom du champ SIRO_ELEM_SIGN +# +# ROSETTE : True/False + +from paraview.simple import * + +import os +dataRoot = os.getenv('PARAVIEW_DATA_ROOT', "") +MEDFILE = dataRoot+'/rosette_am.med' +MAILLAGE='mail' +GROUPE_FACE = ['SURF_AM',] +COEFF_T1T2 = 0.00003 +COEFF_TN = 0.003 + +T='RESUNL__SIRO_ELEM_TANGENT_Vector' +N='RESUNL__SIRO_ELEM_NORMAL_Vector' +T1 = 'RESUNL__SIRO_ELEM_T1_Vector' +T2 = 'RESUNL__SIRO_ELEM_T2_Vector' + +ROSETTE = True + +# Fin données utilisateurs + + + +#%==================== Importing MED file====================% + +print ("**** Importing MED file") + +myResult0 = MEDReader(FileName=MEDFILE) +if myResult0 is None : raise "Erreur de fichier MED" + +# Imposition GenerateVectors à faire +myResult0.GenerateVectors=1 + +NB_ORDRE = myResult0.GetPropertyValue('TimestepValues') + +#extraction groupes et visualisation du maillage +listeg=[] +for g in GROUPE_FACE : + listeg.append('GRP_'+g) + +myResult = ExtractGroup() +myResult.AllGroups=listeg +#myResult.Groups = listeg + + +CellCenters1 = CellCenters() +if len(NB_ORDRE) > 1 : + animation = GetAnimationScene() + #animation.AnimationTime = NB_ORDRE[2] +view2 = GetRenderView() + + +#%====================Displaying rosette====================% + +if ROSETTE : + CMAX = 0.0 + T_MAX = 0.0 + print ("**** Displaying rosette") + + view2.Background=[1.0,1.0,1.0] + SetActiveSource(myResult) + Display0 = Show() + Display0.Texture=[] + Display0.Representation = 'Wireframe' + Display0.AmbientColor=[0.0,0.0,0.0] + + SetActiveSource(CellCenters1) + Glyph1 = Glyph() + Glyph1.OrientationArray = ['POINTS', T1] + Glyph1.GlyphType ='Line' + Glyph1.GlyphMode = 'All Points' + + pd1 = Glyph1.PointData + + for i in range(len(pd1)): + if pd1.values()[i-1].GetName()== T1 : + NUM = i-1 + NB_CMP = pd1.values()[i-1].GetNumberOfComponents() + NOM_CMP = pd1.values()[i-1].GetComponentName(NB_CMP) + RANGE_CMP = pd1.values()[i-1].GetRange(NB_CMP-1) + MAX_CMP = max(abs(RANGE_CMP[0]),abs(RANGE_CMP[1])) + if RANGE_CMP[0] < 0.0 : + C_MAX = -RANGE_CMP[0] + else : + C_MAX = 0. + if RANGE_CMP[1] > 0.0 : + T_MAX = RANGE_CMP[1] + else : + T_MAX = 0. + + Render() + + Glyph1.ScaleArray = ['POINTS', T1] + Glyph1.VectorScaleMode = 'Scale by Magnitude' + Glyph1.ScaleFactor = COEFF_T1T2 + + Display1=Show() + + PVLookupTable1 = GetLookupTableForArray( T1, NB_CMP, VectorMode = 'Component',VectorComponent=NB_CMP-1, NumberOfTableValues=2, RGBPoints=[-MAX_CMP, 0.0, 0.0, 1.0, MAX_CMP, 1.0, 0.0, 0.0], AutomaticRescaleRangeMode=-1, ScalarRangeInitialized = 1.0) + + scalarbar1 = CreateScalarBar(Title =T1, ComponentTitle = NOM_CMP, LookupTable=PVLookupTable1, TitleFontSize=12 , LabelFontSize=12, TitleColor=[0.0,0.0,0.0],LabelColor=[0.0,0.0,0.0]) + + view2.Representations.append(scalarbar1) + Display1.ColorArrayName = T1 + Display1.LookupTable = PVLookupTable1 + Display1.Representation = 'Surface' + + SetActiveSource(CellCenters1) + Glyph2 = Glyph() + Glyph2.OrientationArray = ['POINTS', T2] + Glyph2.GlyphType ='Line' + Glyph2.ScaleArray = ['POINTS', T2] + Glyph2.VectorScaleMode = 'Scale by Magnitude' + Glyph2.ScaleFactor = COEFF_T1T2 + + Glyph2.GlyphMode = 'All Points' + + pd2 = Glyph2.PointData + + for i in range(len(pd2)): + if pd2.values()[i-1].GetName()== T2 : + NB_CMP = pd2.values()[i-1].GetNumberOfComponents() + NOM_CMP = pd2.values()[i-1].GetComponentName(NB_CMP-1) + RANGE_CMP = pd2.values()[i-1].GetRange(NB_CMP-1) + MAX_CMP = max(abs(RANGE_CMP[0]),abs(RANGE_CMP[1])) + if RANGE_CMP[0] < 0.0 : + C_MAX = max(C_MAX,-RANGE_CMP[0]) + if RANGE_CMP[1] > 0.0 : + T_MAX = max(T_MAX,RANGE_CMP[1]) + + Display2=Show() + + PVLookupTable2 = GetLookupTableForArray( T2, NB_CMP, VectorMode = 'Component',VectorComponent=NB_CMP-1, NumberOfTableValues=2, RGBPoints=[-MAX_CMP, 0.0, 0.0, 1.0, MAX_CMP, 1.0, 0.0, 0.0], AutomaticRescaleRangeMode=-1) + scalarbar2 = CreateScalarBar(Title =T2, ComponentTitle = NOM_CMP, LookupTable=PVLookupTable2, TitleFontSize=12 , LabelFontSize=12,TitleColor=[0.0,0.0,0.0],LabelColor=[0.0,0.0,0.0]) + #view2.Representations.append(scalarbar2) + Display2.ColorArrayName = T2 + Display2.LookupTable = PVLookupTable2 + Display2.Representation = 'Surface' + + Text2 = Text() + Texte = 'COMPRESSION MAX = '+str(C_MAX)+' MPa \nTRACTION MAX = '+str(T_MAX)+' Mpa' + Text2.Text = Texte + DisplayT = Show() + DisplayT.FontSize = 12 + DisplayT.Color=[0.0, 0.0, 0.0] + + Render() + view2.CameraPosition = [-524.450475200065, -34.2470779418945, 572.968383789062] + view2.CameraFocalPoint = [9.7492516040802, -34.2470779418945, 572.968383789062] + view2.CameraViewUp = [0.0, 0.0, 1.0] + ResetCamera() + + import sys + try: + baselineIndex = sys.argv.index('-B')+1 + baselinePath = sys.argv[baselineIndex] + except: + print ("Could not get baseline directory. Test failed.") + baseline_file = os.path.join(baselinePath, "TestDataAnalysis.png") + from paraview.vtk.test import Testing + from paraview.vtk.util.misc import vtkGetTempDir + Testing.VTK_TEMP_DIR = vtkGetTempDir() + Testing.compareImage(view2.GetRenderWindow(), baseline_file, threshold=10) + Testing.interact() diff --git a/src/Plugins/MEDReader/plugin/Test/TestExtractCell.xml b/src/Plugins/MEDReader/plugin/Test/TestExtractCell.xml new file mode 100644 index 00000000..1957b42f --- /dev/null +++ b/src/Plugins/MEDReader/plugin/Test/TestExtractCell.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + diff --git a/src/Plugins/MEDReader/plugin/Test/TestExtractGroup.xml b/src/Plugins/MEDReader/plugin/Test/TestExtractGroup.xml new file mode 100644 index 00000000..2c8cfe67 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/Test/TestExtractGroup.xml @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/src/Plugins/MEDReader/plugin/Test/TestGUIPerf.xml b/src/Plugins/MEDReader/plugin/Test/TestGUIPerf.xml new file mode 100644 index 00000000..cb87885a --- /dev/null +++ b/src/Plugins/MEDReader/plugin/Test/TestGUIPerf.xml @@ -0,0 +1,50 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Plugins/MEDReader/plugin/Test/TestGaussPoints.xml b/src/Plugins/MEDReader/plugin/Test/TestGaussPoints.xml new file mode 100644 index 00000000..aeff14b7 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/Test/TestGaussPoints.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + diff --git a/src/Plugins/MEDReader/plugin/Test/TestMultiMesh.xml b/src/Plugins/MEDReader/plugin/Test/TestMultiMesh.xml new file mode 100644 index 00000000..6d4b9857 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/Test/TestMultiMesh.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + diff --git a/src/Plugins/MEDReader/plugin/Test/TestPythonTrace.xml b/src/Plugins/MEDReader/plugin/Test/TestPythonTrace.xml new file mode 100644 index 00000000..e6e33c54 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/Test/TestPythonTrace.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Plugins/MEDReader/plugin/Test/TestScalarBar.xml b/src/Plugins/MEDReader/plugin/Test/TestScalarBar.xml new file mode 100644 index 00000000..e4e3f260 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/Test/TestScalarBar.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Plugins/MEDReader/plugin/Test/TestWarpColorBar.xml b/src/Plugins/MEDReader/plugin/Test/TestWarpColorBar.xml new file mode 100644 index 00000000..e7faac6c --- /dev/null +++ b/src/Plugins/MEDReader/plugin/Test/TestWarpColorBar.xml @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Plugins/MEDReader/plugin/Test/TestWidgetsPropertySynchronisation.xml b/src/Plugins/MEDReader/plugin/Test/TestWidgetsPropertySynchronisation.xml new file mode 100644 index 00000000..71766d70 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/Test/TestWidgetsPropertySynchronisation.xml @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/src/Plugins/MEDReader/plugin/Test/TestWidgetsPropertySynchronisationBiDir.xml b/src/Plugins/MEDReader/plugin/Test/TestWidgetsPropertySynchronisationBiDir.xml new file mode 100644 index 00000000..7b5a5ccf --- /dev/null +++ b/src/Plugins/MEDReader/plugin/Test/TestWidgetsPropertySynchronisationBiDir.xml @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/src/Plugins/MEDReader/plugin/Test/checkParaview.py b/src/Plugins/MEDReader/plugin/Test/checkParaview.py new file mode 100644 index 00000000..4457d45b --- /dev/null +++ b/src/Plugins/MEDReader/plugin/Test/checkParaview.py @@ -0,0 +1,7 @@ +import os +import os.path +paraviewBinDir = os.getenv('PARAVIEW_BIN_DIR', "") +paraviewFile = paraviewBinDir + "/paraview" +pvserverFile = paraviewBinDir + "/pvserver" +assert(os.access(paraviewFile, os.X_OK)) +assert(os.access(pvserverFile, os.X_OK)) diff --git a/src/Plugins/MEDReader/plugin/Test/testMEDReader0.py b/src/Plugins/MEDReader/plugin/Test/testMEDReader0.py new file mode 100644 index 00000000..a8af4345 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/Test/testMEDReader0.py @@ -0,0 +1,146 @@ +# -*- coding: iso-8859-1 -*- +# Copyright (C) 2007-2019 CEA/DEN, EDF R&D +# +# This library 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. +# +# 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 +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +# +# Author : Anthony Geay + +import os +import sys + +from medcoupling import * +from paraview.simple import * +from MEDReaderHelper import WriteInTmpDir,RetriveBaseLine + +def GenerateCase(): + fname="testMEDReader0.med" + ######### + mz=MEDCoupling1SGTUMesh("mesh",NORM_QUAD9) + mz.setNodalConnectivity(DataArrayInt([0,6,37,12,76,112,113,82,205,12,37,38,13,113,114,115,83,206,13,38,9,1,115,116,79,84,207,6,7,39,37,77,117,118,112,208,37,39,40,38,118,119,120,114,209,38,40,10,9,120,121,80,116,210,7,8,41,39,78,122,123,117,211,39,41,42,40,123,124,125,119,212,40,42,11,10,125,126,81,121,213,1,9,43,17,79,127,128,88,214,17,43,44,18,128,129,130,89,215,18,44,14,2,130,131,85,90,216,9,10,45,43,80,132,133,127,217,43,45,46,44,133,134,135,129,218,44,46,15,14,135,136,86,131,219,10,11,47,45,81,137,138,132,220,45,47,48,46,138,139,140,134,221,46,48,16,15,140,141,87,136,222,1,9,49,22,79,142,143,94,223,22,49,50,23,143,144,145,95,224,23,50,51,24,145,146,147,96,225,24,51,52,25,147,148,149,97,226,25,52,53,26,149,150,151,98,227,26,53,19,3,151,152,91,99,228,9,10,54,49,80,153,154,142,229,49,54,55,50,154,155,156,144,230,50,55,56,51,156,157,158,146,231,51,56,57,52,158,159,160,148,232,52,57,58,53,160,161,162,150,233,53,58,20,19,162,163,92,152,234,10,11,59,54,81,164,165,153,235,54,59,60,55,165,166,167,155,236,55,60,61,56,167,168,169,157,237,56,61,62,57,169,170,171,159,238,57,62,63,58,171,172,173,161,239,58,63,21,20,173,174,93,163,240,4,27,64,30,100,175,176,103,241,30,64,65,31,176,177,178,104,242,31,65,19,3,178,179,91,105,243,27,28,66,64,101,180,181,175,244,64,66,67,65,181,182,183,177,245,65,67,20,19,183,184,92,179,246,28,29,68,66,102,185,186,180,247,66,68,69,67,186,187,188,182,248,67,69,21,20,188,189,93,184,249,3,19,70,35,91,190,191,109,250,35,70,71,36,191,192,193,110,251,36,71,32,5,193,194,106,111,252,19,20,72,70,92,195,196,190,253,70,72,73,71,196,197,198,192,254,71,73,33,32,198,199,107,194,255,20,21,74,72,93,200,201,195,256,72,74,75,73,201,202,203,197,257,73,75,34,33,203,204,108,199,258])) + coords=DataArrayDouble([-0.04,0.015,0.,0.,0.015,0.,0.04,0.015,0.,0.,0.105,0.,-0.04,0.105,0.,0.04,0.105,0.,-0.04,0.015,0.015,-0.04,0.015,0.03,-0.04,0.015,0.045,0.,0.015,0.015,0.,0.015,0.03,0.,0.015,0.045,-0.026666666666666665,0.015,0.,-0.013333333333333329,0.015,0.,0.04,0.015,0.015,0.04,0.015,0.03,0.04,0.015,0.045,0.013333333333333336,0.015,0.,0.026666666666666672,0.015,0.,0.,0.105,0.015,0.,0.105,0.03,0.,0.105,0.045,0.,0.03,0.,0.,0.045,0.,0.,0.06,0.,0.,0.075,0.,0.,0.09,0.,-0.04,0.105,0.015,-0.04,0.105,0.03,-0.04,0.105,0.045,-0.026666666666666665,0.105,0.,-0.013333333333333329,0.105,0.,0.04,0.105,0.015,0.04,0.105,0.03,0.04,0.105,0.045,0.013333333333333336,0.105,0.,0.026666666666666672,0.105,0.,-0.026666666666666665,0.015,0.015,-0.013333333333333326,0.015,0.015,-0.026666666666666665,0.015,0.03,-0.013333333333333326,0.015,0.03,-0.026666666666666665,0.015,0.045,-0.013333333333333329,0.015,0.045,0.013333333333333338,0.015,0.015,0.026666666666666675,0.015,0.015,0.013333333333333338,0.015,0.03,0.026666666666666675,0.015,0.03,0.013333333333333336,0.015,0.045,0.026666666666666672,0.015,0.045,0.,0.03,0.015,0.,0.045,0.015,0.,0.06,0.015,0.,0.07500000000000001,0.015,0.,0.09,0.015,0.,0.03,0.03,0.,0.045,0.03,0.,0.06,0.03,0.,0.075,0.03,0.,0.09,0.03,0.,0.03,0.045,0.,0.045,0.045,0.,0.06,0.045,0.,0.075,0.045,0.,0.09,0.045,-0.026666666666666665,0.105,0.015,-0.013333333333333326,0.105,0.015,-0.026666666666666665,0.105,0.03,-0.013333333333333326,0.105,0.03,-0.026666666666666665,0.105,0.045,-0.013333333333333329,0.105,0.045,0.013333333333333338,0.105,0.015,0.026666666666666675,0.105,0.015,0.013333333333333338,0.105,0.03,0.026666666666666675,0.105,0.03,0.013333333333333336,0.105,0.045,0.026666666666666672,0.105,0.045,-0.04,0.015,0.0075,-0.04,0.015,0.0225,-0.04,0.015,0.0375,0.,0.015,0.0075,0.,0.015,0.0225,0.,0.015,0.0375,-0.03333333333333333,0.015,0.,-0.02,0.015,0.,-0.0066666666666666645,0.015,0.,0.04,0.015,0.0075,0.04,0.015,0.0225,0.04,0.015,0.0375,0.006666666666666668,0.015,0.,0.02,0.015,0.,0.03333333333333334,0.015,0.,0.,0.105,0.0075,0.,0.105,0.0225,0.,0.105,0.0375,0.,0.0225,0.,0.,0.0375,0.,0.,0.0525,0.,0.,0.0675,0.,0.,0.0825,0.,0.,0.0975,0.,-0.04,0.105,0.0075,-0.04,0.105,0.0225,-0.04,0.105,0.0375,-0.03333333333333333,0.105,0.,-0.02,0.105,0.,-0.0066666666666666645,0.105,0.,0.04,0.105,0.0075,0.04,0.105,0.0225,0.04,0.105,0.0375,0.006666666666666668,0.105,0.,0.02,0.105,0.,0.03333333333333334,0.105,0.,-0.03333333333333333,0.015,0.015,-0.026666666666666665,0.015,0.0075,-0.02,0.015,0.015,-0.013333333333333327,0.015,0.0075,-0.006666666666666663,0.015,0.015,-0.03333333333333333,0.015,0.03,-0.026666666666666665,0.015,0.0225,-0.02,0.015,0.03,-0.013333333333333326,0.015,0.0225,-0.006666666666666663,0.015,0.03,-0.03333333333333333,0.015,0.045,-0.026666666666666665,0.015,0.0375,-0.02,0.015,0.045,-0.013333333333333327,0.015,0.0375,-0.0066666666666666645,0.015,0.045,0.006666666666666669,0.015,0.015,0.013333333333333336,0.015,0.0075,0.020000000000000007,0.015,0.015,0.026666666666666672,0.015,0.0075,0.03333333333333334,0.015,0.015,0.006666666666666669,0.015,0.03,0.013333333333333338,0.015,0.0225,0.02,0.015,0.03,0.026666666666666675,0.015,0.0225,0.03333333333333334,0.015,0.03,0.006666666666666668,0.015,0.045,0.013333333333333336,0.015,0.0375,0.02,0.015,0.045,0.026666666666666672,0.015,0.0375,0.03333333333333334,0.015,0.045,0.,0.0225,0.015,0.,0.03,0.0075,0.,0.0375,0.015,0.,0.045,0.0075,0.,0.0525,0.015,0.,0.06,0.0075,0.,0.0675,0.015,0.,0.07500000000000001,0.0075,0.,0.0825,0.015,0.,0.09,0.0075,0.,0.0975,0.015,0.,0.0225,0.03,0.,0.03,0.0225,0.,0.0375,0.03,0.,0.045,0.0225,0.,0.0525,0.03,0.,0.06,0.0225,0.,0.0675,0.03,0.,0.07500000000000001,0.0225,0.,0.08249999999999999,0.03,0.,0.09,0.0225,0.,0.0975,0.03,0.,0.0225,0.045,0.,0.03,0.0375,0.,0.0375,0.045,0.,0.045,0.0375,0.,0.0525,0.045,0.,0.06,0.0375,0.,0.0675,0.045,0.,0.075,0.0375,0.,0.08249999999999999,0.045,0.,0.09,0.0375,0.,0.0975,0.045,-0.03333333333333333,0.105,0.015,-0.026666666666666665,0.105,0.0075,-0.02,0.105,0.015,-0.013333333333333327,0.105,0.0075,-0.006666666666666663,0.105,0.015,-0.03333333333333333,0.105,0.03,-0.026666666666666665,0.105,0.0225,-0.02,0.105,0.03,-0.013333333333333326,0.105,0.0225,-0.006666666666666663,0.105,0.03,-0.03333333333333333,0.105,0.045,-0.026666666666666665,0.105,0.0375,-0.02,0.105,0.045,-0.013333333333333327,0.105,0.0375,-0.0066666666666666645,0.105,0.045,0.006666666666666669,0.105,0.015,0.013333333333333336,0.105,0.0075,0.020000000000000007,0.105,0.015,0.026666666666666672,0.105,0.0075,0.03333333333333334,0.105,0.015,0.006666666666666669,0.105,0.03,0.013333333333333338,0.105,0.0225,0.020000000000000007,0.105,0.03,0.026666666666666675,0.105,0.0225,0.03333333333333334,0.105,0.03,0.006666666666666668,0.105,0.045,0.013333333333333336,0.105,0.0375,0.02,0.105,0.045,0.026666666666666672,0.105,0.0375,0.03333333333333334,0.105,0.045,-0.03333333333333333,0.015,0.0075,-0.02,0.015,0.0075,-0.006666666666666664,0.015,0.0075,-0.03333333333333333,0.015,0.0225,-0.02,0.015,0.0225,-0.006666666666666663,0.015,0.0225,-0.03333333333333333,0.015,0.0375,-0.02,0.015,0.0375,-0.006666666666666662,0.015,0.0375,0.006666666666666668,0.015,0.0075,0.02,0.015,0.0075,0.03333333333333334,0.015,0.0075,0.006666666666666669,0.015,0.0225,0.020000000000000007,0.015,0.0225,0.03333333333333334,0.015,0.0225,0.006666666666666668,0.015,0.0375,0.02,0.015,0.0375,0.03333333333333334,0.015,0.0375,0.,0.0225,0.0075,0.,0.0375,0.0075,0.,0.0525,0.0075,0.,0.0675,0.0075,0.,0.0825,0.0075,0.,0.0975,0.0075,0.,0.0225,0.0225,0.,0.0375,0.0225,0.,0.0525,0.0225,0.,0.0675,0.0225,0.,0.0825,0.0225,0.,0.0975,0.0225,0.,0.0225,0.0375,0.,0.0375,0.0375,0.,0.0525,0.0375,0.,0.0675,0.0375,0.,0.08249999999999999,0.0375,0.,0.0975,0.0375,-0.03333333333333333,0.105,0.0075,-0.02,0.105,0.0075,-0.006666666666666664,0.105,0.0075,-0.03333333333333333,0.105,0.0225,-0.02,0.105,0.0225,-0.006666666666666663,0.105,0.0225,-0.03333333333333333,0.105,0.0375,-0.02,0.105,0.0375,-0.006666666666666662,0.105,0.0375,0.006666666666666668,0.105,0.0075,0.02,0.105,0.0075,0.03333333333333334,0.105,0.0075,0.006666666666666669,0.105,0.0225,0.020000000000000007,0.105,0.0225,0.03333333333333334,0.105,0.0225,0.006666666666666668,0.105,0.0375,0.02,0.105,0.0375,0.03333333333333334,0.105,0.0375],259,3) + coords.setInfoOnComponents(['X [INCONNUE]','Y [INCONNUE]','Z [INCONNUE]']) + mz.setCoords(coords) + mz=mz.buildUnstructured() + # + arr0=DataArrayDouble() + vals0=9*[-3593.,85220.,-15343.,-438.,11985.,-15343.,2716.,-61248.,-15343.,5488.,101072.,-16250.,549.,13186.,-16250.,-4389.,-74699.,-16250.,9988.,101646.,-17156.,1537.,14386.,-17156.,-6913.,-72874.,-17156.,22178.,120238.,-19521.,2342.,14222.,-19521.,-17493.,-91793.,-19521.,37737.,139840.,-21887.,3147.,14059.,-21887.,-31443.,-111722.,-21887.,34350.,140668.,-18690.,3714.,16214.,-18690.,-26922.,-108238.,-18690.,34563.,153494.,-15493.,4281.,18370.,-15493.,-26000.,-116753.,-15493.,2147.,115356.,-15418.,1921.,15178.,-15418.,1695.,-84999.,-15418.,12408.,118616.,-17470.,2131.,14700.,-17470.,-8144.,-89215.,-17470.,15624.,100983.,-16718.,2286.,15441.,-16718.,-11050.,-70101.,-16718.,19381.,102680.,-17191.,2505.,16813.,-17191.,-14370.,-69054.,-17191.,22911.,103615.,-17665.,2725.,18184.,-17665.,-17461.,-67245.,-17665.,32377.,125140.,-20005.,4011.,17741.,-20005.,-24353.,-89657.,-20005.,43183.,147067.,-22345.,5298.,17297.,-22345.,-32586.,-112472.,-22345.,41570.,144664.,-22105.,4896.,15874.,-22105.,-31778.,-112915.,-22105.,40070.,142637.,-21866.,4493.,14451.,-21866.,-31083.,-113734.,-21866.,25367.,121066.,-19292.,3390.,14946.,-19292.,-18587.,-91173.,-19292.,28901.,123199.,-19648.,3701.,16343.,-19648.,-21499.,-90512.,-19648.,23716.,103481.,-17470.,2234.,18509.,-17470.,-19247.,-66463.,-17470.,22561.,104808.,-17142.,1238.,20732.,-17142.,-20084.,-63343.,-17142.,21499.,106443.,-16813.,242.,22956.,-16813.,-21014.,-60531.,-16813.,32906.,133441.,-20775.,3873.,26633.,-20775.,-25158.,-80173.,-20775.,45801.,160885.,-24737.,7505.,30311.,-24737.,-30791.,-100262.,-24737.,44184.,154705.,-23601.,5922.,24329.,-23601.,-32340.,-106046.,-23601.,42566.,148521.,-22465.,4338.,18347.,-22465.,-33888.,-111825.,-22465.,32545.,125822.,-19968.,3286.,18428.,-19968.,-25972.,-88965.,-19968.,32703.,129556.,-20371.,3580.,22531.,-20371.,-25542.,-84493.,-20371.,-580.,50781.,-14878.,-188.,10419.,-14878.,203.,-29941.,-14878.,974.,53486.,-13087.,-197.,11696.,-13087.,-1370.,-30094.,-13087.,2154.,54941.,-11297.,-206.,12972.,-11297.,-2567.,-28996.,-11297.,4921.,72039.,-13221.,709.,13770.,-13221.,-3503.,-44499.,-13221.,6472.,88772.,-15144.,1624.,14567.,-15144.,-3223.,-59637.,-15144.,4104.,85353.,-15580.,600.,13047.,-15580.,-2903.,-59258.,-15580.,1258.,80341.,-16016.,-423.,11526.,-16016.,-2105.,-57288.,-16016.,-822.,65212.,-15447.,-306.,10973.,-15447.,210.,-43266.,-15447.,2262.,69336.,-14334.,201.,12371.,-14334.,-1859.,-44593.,-14334.,4047.,55415.,-11562.,137.,13264.,-11562.,-3772.,-28887.,-11562.,6455.,56737.,-11164.,80.,14219.,-11164.,-6294.,-28298.,-11164.,8701.,57516.,-10766.,23.,15175.,-10766.,-8653.,-27166.,-10766.,12843.,74210.,-13196.,662.,16118.,-13196.,-11519.,-41972.,-13196.,17837.,91160.,-15627.,1300.,17062.,-15627.,-15237.,-57034.,-15627.,14573.,90279.,-15674.,1166.,15841.,-15674.,-12240.,-58596.,-15674.,11497.,90026.,-15722.,1033.,14619.,-15722.,-9431.,-60786.,-15722.,7014.,72493.,-13642.,585.,13941.,-13642.,-5844.,-44609.,-13642.,9922.,73330.,-13419.,623.,15030.,-13419.,-8675.,-43270.,-13419.,9608.,58062.,-10666.,-408.,15882.,-10666.,-10425.,-26297.,-10666.,10622.,58358.,-9978.,-497.,16431.,-9978.,-11617.,-25496.,-9978.,11722.,58941.,-9290.,-587.,16979.,-9290.,-12896.,-24981.,-9290.,14386.,76411.,-12130.,-417.,19190.,-12130.,-15221.,-38029.,-12130.,18009.,94168.,-14969.,-248.,21401.,-14969.,-18505.,-51365.,-14969.,19049.,93091.,-15325.,999.,19998.,-15325.,-17050.,-53095.,-15325.,20242.,92527.,-15681.,2246.,18594.,-15681.,-15748.,-55338.,-15681.,14435.,75147.,-13174.,919.,17238.,-13174.,-12597.,-40670.,-13174.,14351.,75579.,-12652.,250.,18214.,-12652.,-13849.,-39150.,-12652.0] + arr0.setValues(vals0,1458,3) + arr0.setInfoOnComponents(['SIXX','SIYY','SIYZ']) + f0z=MEDCouplingFieldDouble(ON_GAUSS_PT) + f0z.setMesh(mz) + f0z.setArray(arr0) + f0z.setGaussLocalizationOnType(NORM_QUAD9,[-1,-1,1,-1,1,1,-1,1,0,-1,1,0,0,1,-1,0,0,0],[-0.774597,-0.774597,0.774597,-0.774597,0.774597,0.774597,-0.774597,0.774597,0,-0.774597,0.774597,0,0,0.774597,-0.774597,0,0,0,-0.774597,-0.774597,0.774597,-0.774597,0.774597,0.774597,-0.774597,0.774597,0,-0.774597,0.774597,0,0,0.774597,-0.774597,0,0,0,-0.774597,-0.774597,0.774597,-0.774597,0.774597,0.774597,-0.774597,0.774597,0,-0.774597,0.774597,0,0,0.774597,-0.774597,0,0,0],[0.308642,0.308642,0.308642,0.308642,0.493827,0.493827,0.493827,0.493827,0.790123,0.308642,0.308642,0.308642,0.308642,0.493827,0.493827,0.493827,0.493827,0.790123,0.308642,0.308642,0.308642,0.308642,0.493827,0.493827,0.493827,0.493827,0.790123]) + f0z.setName("SolutionSIEF_ELGA") + f0z.checkConsistencyLight() + ff0z=MEDFileField1TS() + ff0z.setFieldNoProfileSBT(f0z) + # + arr1=DataArrayDouble([158663.,171562.,32597.,37341.,118998.,128979.,88846.,94935.,28786.,32250.,67038.,71287.,102742.,108939.,32907.,37716.,0.,0.,138922.,155768.,41391.,47731.,114491.,128395.,94101.,100197.,31445.,35939.,67322.,71913.,94031.,103701.,34833.,39475.,0.,0.,142412.,160086.,42700.,49041.,113826.,128551.,92705.,102386.,34032.,38580.,61698.,69417.,96177.,104283.,38223.,40570.,0.,0.,87935.,89674.,30482.,34419.,66325.,69150.,53964.,55380.,28306.,32157.,37909.,40395.,53662.,55355.,22264.,24611.,0.,0.,94013.,100457.,31768.,36134.,68065.,73681.,53358.,55305.,23341.,26188.,32996.,35203.,52496.,56792.,23849.,26556.,0.,0.,92797.,102692.,33656.,38268.,61244.,68735.,52594.,56740.,24539.,27146.,29157.,33011.,52853.,57683.,25671.,28315.,0.,0.,53581.,55745.,27972.,31820.,37174.,39935.,29236.,31416.,22475.,25354.,20531.,23672.,25557.,26298.,15741.,17492.,0.,0.,53385.,55725.,23224.,25998.,32556.,35093.,25809.,26619.,16518.,18338.,18447.,21219.,23343.,26173.,16948.,19353.,0.,0.,52384.,56725.,24293.,26951.,29491.,33373.,23510.,26382.,17117.,19543.,19649.,22252.,26670.,30680.,19554.,22512.,0.,0.,158781.,178651.,54413.,62227.,103151.,116693.,96177.,104283.,38223.,40570.,56254.,64331.,92705.,102386.,34032.,38580.,0.,0.,142873.,161033.,43285.,49854.,113088.,127440.,94031.,103701.,34833.,39475.,61888.,69552.,94101.,100197.,31445.,35939.,0.,0.,132908.,149284.,42933.,49391.,109280.,123481.,102742.,108939.,32907.,37716.,75662.,80547.,88846.,94935.,28786.,32250.,0.,0.,96505.,105010.,37990.,40710.,56669.,64741.,52853.,57683.,25671.,28315.,26824.,30727.,52594.,56740.,24539.,27146.,0.,0.,92360.,101577.,33582.,37900.,61559.,69237.,52496.,56792.,23849.,26556.,29094.,32746.,53358.,55305.,23341.,26188.,0.,0.,95615.,101326.,31440.,36083.,69356.,73116.,53662.,55355.,22264.,24611.,31957.,34376.,53964.,55380.,28306.,32157.,0.,0.,53029.,58077.,25636.,28363.,27182.,31122.,26670.,30680.,19554.,22512.,20758.,22139.,23510.,26382.,17117.,19543.,0.,0.,52348.,56723.,23922.,26648.,29286.,32993.,23343.,26173.,16948.,19353.,19615.,22178.,25809.,26619.,16518.,18338.,0.,0.,53623.,55229.,22321.,24800.,32700.,34971.,25557.,26298.,15741.,17492.,18986.,21836.,29236.,31416.,22475.,25354.,0.,0.,64897.,69997.,64897.,69997.,64897.,69997.,81086.,90448.,81086.,90448.,81086.,90448.,85289.,98323.,85289.,98323.,0.,0.,71712.,82585.,71712.,82585.,71712.,82585.,83868.,96651.,83868.,96651.,83868.,96651.,86266.,99505.,86266.,99505.,0.,0.,77671.,89574.,77671.,89574.,77671.,89574.,86057.,99277.,86057.,99277.,86057.,99277.,86664.,99373.,86664.,99373.,0.,0.,80105.,91799.,80105.,91799.,80105.,91799.,86589.,99313.,86589.,99313.,86589.,99313.,85997.,97609.,85997.,97609.,0.,0.,79826.,90350.,79826.,90350.,79826.,90350.,86438.,98180.,86438.,98180.,86438.,98180.,85995.,95152.,85995.,95152.,0.,0.,75137.,82756.,75137.,82756.,75137.,82756.,88617.,98610.,88617.,98610.,88617.,98610.,79961.,83623.,79961.,83623.,0.,0.,79241.,88756.,79241.,88756.,79241.,88756.,84552.,97374.,84552.,97374.,84552.,97374.,93024.,107413.,93024.,107413.,0.,0.,85301.,98315.,85301.,98315.,85301.,98315.,92453.,106752.,92453.,106752.,92453.,106752.,93783.,108035.,93783.,108035.,0.,0.,86813.,100152.,86813.,100152.,86813.,100152.,93530.,107737.,93530.,107737.,93530.,107737.,92512.,106099.,92512.,106099.,0.,0.,87195.,100044.,87195.,100044.,87195.,100044.,92527.,106109.,92527.,106109.,92527.,106109.,90156.,102760.,90156.,102760.,0.,0.,87342.,99233.,87342.,99233.,87342.,99233.,90384.,103001.,90384.,103001.,90384.,103001.,85458.,96494.,85458.,96494.,0.,0.,90428.,100728.,90428.,100728.,90428.,100728.,85454.,96396.,85454.,96396.,85454.,96396.,70692.,78323.,70692.,78323.,0.,0.,84617.,97440.,84617.,97440.,84617.,97440.,83973.,96607.,83973.,96607.,83973.,96607.,92886.,106795.,92886.,106795.,0.,0.,92294.,106564.,92294.,106564.,92294.,106564.,92515.,106364.,92515.,106364.,92515.,106364.,94158.,108033.,94158.,108033.,0.,0.,93639.,107861.,93639.,107861.,93639.,107861.,93950.,107796.,93950.,107796.,93950.,107796.,91874.,105168.,91874.,105168.,0.,0.,92701.,106313.,92701.,106313.,92701.,106313.,91869.,105167.,91869.,105167.,91869.,105167.,87044.,99369.,87044.,99369.,0.,0.,90450.,103104.,90450.,103104.,90450.,103104.,87236.,99605.,87236.,99605.,87236.,99605.,78375.,89211.,78375.,89211.,0.,0.,84833.,95787.,84833.,95787.,84833.,95787.,78665.,89521.,78665.,89521.,78665.,89521.,63448.,71985.,63448.,71985.,0.,0.,9194.,10306.,41521.,44441.,79431.,85178.,8946.,9792.,22335.,23886.,51736.,54740.,7726.,8300.,30477.,32533.,0.,0.,25028.,27404.,28235.,31471.,75379.,84132.,7236.,8309.,29539.,31536.,54052.,58395.,22577.,23370.,39152.,41429.,0.,0.,37235.,42691.,35353.,38183.,100490.,111738.,23433.,25843.,36759.,39109.,53411.,59694.,57437.,65025.,61345.,68878.,0.,0.,6377.,6683.,22457.,23448.,49503.,50751.,10380.,10835.,19266.,19610.,28417.,28750.,20732.,22044.,26521.,27276.,0.,0.,10131.,11681.,28482.,29670.,52601.,56753.,20722.,21728.,25680.,25959.,30780.,31657.,32161.,33290.,33096.,34633.,0.,0.,21380.,22651.,37121.,39923.,54598.,60751.,34744.,36379.,35111.,37417.,35939.,39080.,46708.,51426.,44384.,48624.,0.,0.,10952.,11418.,19643.,20167.,28488.,29118.,20182.,20242.,18359.,18431.,16718.,16900.,24621.,25169.,20737.,21234.,0.,0.,20251.,21309.,25725.,26026.,31355.,32256.,24539.,25102.,20991.,21593.,17889.,18639.,31588.,32417.,27170.,29235.,0.,0.,33431.,35174.,34427.,36736.,35916.,38926.,31741.,32451.,27148.,29040.,23993.,27214.,38993.,40689.,36596.,40772.,0.,0.,41907.,48128.,77947.,87844.,152033.,169876.,57437.,65025.,61345.,68878.,74154.,85533.,23433.,25843.,36759.,39109.,0.,0.,33932.,38310.,36200.,40713.,99297.,111743.,22577.,23370.,39152.,41429.,57432.,62292.,7236.,8309.,29539.,31536.,0.,0.,22968.,26297.,27645.,30092.,72463.,80413.,7726.,8300.,30477.,32533.,57469.,61055.,8946.,9792.,22335.,23886.,0.,0.,48710.,53918.,59260.,65402.,77350.,87781.,46708.,51426.,44384.,48624.,50354.,58143.,34744.,36379.,35111.,37417.,0.,0.,20908.,22670.,38133.,39669.,56332.,59453.,32161.,33290.,33096.,34633.,34367.,36793.,20722.,21728.,25680.,25959.,0.,0.,7404.,8010.,30073.,32272.,55210.,58955.,20732.,22044.,26521.,27276.,32434.,32943.,10380.,10835.,19266.,19610.,0.,0.,45425.,49667.,44460.,48383.,51014.,58851.,38993.,40689.,36596.,40772.,38865.,44837.,31741.,32451.,27148.,29040.,0.,0.,31595.,32602.,33322.,34837.,35379.,37698.,31588.,32417.,27170.,29235.,24035.,27311.,24539.,25102.,20991.,21593.,0.,0.,19475.,20577.,25384.,25965.,31447.,32050.,24621.,25169.,20737.,21234.,17759.,18414.,20182.,20242.,18359.,18431.,0.,0.],486,2) + arr1.setInfoOnComponents(['VMIS','TRESCA']) + f1z=MEDCouplingFieldDouble(ON_GAUSS_NE) ; f1z.setName("SolutionSIEQ_ELNO") + f1z.setArray(arr1) + f1z.setMesh(mz) + f1z.checkConsistencyLight() + ff1z=MEDFileField1TS() + ff1z.setFieldNoProfileSBT(f1z) + # + arr2=DataArrayDouble([4.938269266683534e-28,-6.232001151245993e-28,1.0602290566170399e-27,4.029857051193646e-29,-1.1103217240985741e-27,-1.5536615528327828e-27,1.5241233363338648e-28,-3.015674201798923e-30,-1.02980203874559e-30,2.72351596604712e-29,-1.1888246600739933e-29,-2.69937196846485e-29,-4.7437993223547586e-07,1.3496193329105202e-07,-7.295395086913946e-07,7.054959528904149e-08,-8.433644218153947e-07,-1.3140517414252605e-08,-4.6699282590396373e-07,-4.307881601165781e-21,-7.181557182928824e-07,-8.028640214851634e-21,-8.231757491716489e-07,-1.2311604671716488e-20,6.500213859021137e-28,-5.36425415550288e-29,2.082592789783471e-28,1.3252863207712998e-28,-4.743799322354692e-07,-1.3496193329105909e-07,-7.295395086913853e-07,-7.054959528905818e-08,-8.433644218153849e-07,1.3140517414226876e-08,6.058451752097371e-28,5.632466863278024e-28,2.208810534618833e-28,2.2876966251409342e-28,-6.120655339318954e-07,1.623023866978208e-20,-7.136250920460284e-07,4.359903572644498e-20,-6.995066975751433e-07,7.373674095935513e-20,0.0,1.4598897976731362e-43,0.0,5.997557427310217e-43,0.0,1.156071233067974e-43,0.0,6.726232628759122e-44,0.0,1.0089348943138683e-43,-4.76082153061813e-07,1.7635130038063272e-07,-7.252650834474581e-07,1.797684522608815e-07,-7.726301925249592e-07,1.3593814652780474e-07,1.28713440720985e-28,8.66262871593868e-30,-1.7918024758329104e-28,1.9633850833341234e-29,-4.7608215306193535e-07,-1.7635130038060178e-07,-7.252650834476241e-07,-1.797684522607695e-07,-7.726301925251186e-07,-1.3593814652760442e-07,-3.0106055763582786e-29,-3.568658720396775e-29,-2.2739766223848432e-29,-1.6603258665331888e-29,-4.741010514018535e-07,5.448590612379579e-08,-4.701818411901992e-07,1.6663000490694165e-08,-7.453102534678627e-07,2.7357217239441644e-08,-7.279540615613018e-07,3.4371113890668217e-09,-8.579330208754989e-07,-2.6008405171390205e-08,-8.357526525453042e-07,-2.5729239758795502e-08,-4.701818411901952e-07,-1.6663000490702818e-08,-4.741010514018457e-07,-5.448590612380402e-08,-7.279540615612966e-07,-3.4371113890835274e-09,-7.45310253467852e-07,-2.7357217239458564e-08,-8.357526525452993e-07,2.572923975877074e-08,-8.579330208754882e-07,2.6008405171364682e-08,0.0,-3.689838846534034e-21,0.0,-3.4057248282497575e-21,0.0,-2.389474304570763e-21,0.0,1.1849907150798524e-21,0.0,7.728930340233592e-21,0.0,-9.409753747161713e-21,0.0,-9.27355993916331e-21,0.0,-5.9005465375222355e-21,0.0,3.45820724462685e-21,0.0,2.0021147143626658e-20,0.0,-1.6042705688202718e-20,0.0,-1.541762360721681e-20,0.0,-8.827856096357078e-21,0.0,6.3984676397065826e-21,0.0,3.396409774956617e-20,-5.21059344905059e-07,1.0785416831218214e-07,-5.942832234061152e-07,1.1284412735292002e-07,-7.291198556954883e-07,1.5975182005082218e-07,-7.29419534669376e-07,1.4146009988497262e-07,-7.536819640264805e-07,1.388363757438669e-07,-7.212688685979149e-07,1.1197909398607218e-07,-5.94283223406162e-07,-1.1284412735287996e-07,-5.210593449051535e-07,-1.0785416831213956e-07,-7.294195346694393e-07,-1.4146009988486582e-07,-7.291198556956173e-07,-1.5975182005070884e-07,-7.212688685979762e-07,-1.1197909398589052e-07,-7.536819640266044e-07,-1.3883637574367513e-07,-2.8576578578864835e-07,1.301140611795876e-07,-6.228581335977658e-07,1.1144407150470386e-07,-8.014360278229913e-07,2.882237382538957e-08,-2.6588034168431343e-07,-2.345549761149889e-21,-6.148909793824232e-07,-5.981322827533954e-21,-7.85277352863385e-07,-1.0225807644204478e-20,3.1049565229499025e-27,-4.196740015775783e-28,-2.887230913108903e-28,-4.403551231441193e-28,4.812051521848172e-29,3.851635443793833e-28,-2.857657857886445e-07,-1.301140611795897e-07,-6.228581335977572e-07,-1.1144407150471579e-07,-8.01436027822981e-07,-2.8822373825410947e-08,-1.5635223141480454e-27,-9.802651538976083e-29,3.278505922098525e-27,-6.797558254135845e-28,4.1020767071492614e-27,5.932234007262009e-28,-4.410314084022777e-07,7.268022452197178e-21,-6.915240267186082e-07,2.9979998916103056e-20,-7.135613152026231e-07,5.968769864060137e-20,0.0,1.793662034335766e-43,0.0,1.793662034335766e-43,0.0,8.96831017167883e-43,0.0,-5.6519283938616335e-43,0.0,1.0761972206014595e-42,0.0,9.269247757898544e-43,-2.627131752301911e-07,1.3274214899302934e-07,-6.329945799890571e-07,1.9265484727832687e-07,-7.677771910976133e-07,1.6184720841148966e-07,1.5146129380243427e-28,-5.494056542378401e-29,1.0988346067719275e-50,3.891714187734575e-29,2.524354896707238e-28,1.6407579324035087e-28,-2.62713175230267e-07,-1.3274214899303003e-07,-6.329945799892127e-07,-1.9265484727825895e-07,-7.677771910977852e-07,-1.6184720841133102e-07,-1.5146129380243427e-28,6.686637000472881e-29,-1.5146129380243427e-28,5.412840523535707e-29,5.048709949123486e-29,-1.0255191767873153e-29,-4.801584184334589e-07,9.447106112382042e-08,-2.646155245804423e-07,4.165624981437424e-08,-4.7283844479037397e-07,3.112099903692373e-08,-2.656912190102633e-07,1.2633757629192664e-08,-4.6803908104000066e-07,8.091752496288301e-09,-7.484767456103177e-07,4.8063930505815753e-08,-6.342336387597463e-07,4.783223809223803e-08,-7.371756425756432e-07,1.2491484933343017e-08,-6.217198644652372e-07,1.3160740615455145e-08,-7.210619794360716e-07,-6.140998451021678e-11,-8.616398069136549e-07,-2.0279767975595878e-08,-8.174867338143947e-07,1.761743718501197e-09,-8.474965025861739e-07,-2.8360688201075687e-08,-7.969390370704656e-07,-1.0156396041453297e-08,-8.26809188564297e-07,-1.6608029814857525e-08,-4.6803908103999843e-07,-8.091752496296909e-09,-2.6569121901026077e-07,-1.2633757629197396e-08,-4.72838444790368e-07,-3.112099903693232e-08,-2.6461552458043755e-07,-4.165624981437841e-08,-4.801584184334501e-07,-9.447106112382803e-08,-7.210619794360687e-07,6.140998449395655e-11,-6.217198644652322e-07,-1.3160740615467643e-08,-7.37175642575635e-07,-1.2491484933360037e-08,-6.342336387597367e-07,-4.783223809225061e-08,-7.484767456103061e-07,-4.8063930505832595e-08,-8.268091885642944e-07,1.6608029814832955e-08,-7.969390370704601e-07,1.015639604143253e-08,-8.474965025861654e-07,2.836068820105083e-08,-8.174867338143834e-07,-1.7617437185225845e-09,-8.616398069136434e-07,2.02797679755703e-08,0.0,-3.435877556189529e-21,0.0,-1.3776771401529971e-21,0.0,-3.403994495899553e-21,0.0,-1.3185754926235634e-21,0.0,-2.7680254878980847e-21,0.0,-1.1103673324958778e-21,0.0,-9.900107724251277e-22,0.0,4.77602156134974e-22,0.0,3.959146546409973e-21,0.0,3.776411006916986e-21,0.0,1.2124392797414627e-20,0.0,-8.731709783191639e-21,0.0,-6.144329300702704e-21,0.0,-8.89968038381516e-21,0.0,-5.404653063609732e-21,0.0,-7.547524363424233e-21,0.0,-3.3206893791145496e-21,0.0,-1.6246546029348425e-21,0.0,1.9854969588545943e-21,0.0,1.1317236337409485e-20,0.0,1.3983874347413824e-20,0.0,3.098996503833694e-20,0.0,-1.407865292807831e-20,0.0,-1.1626000835692668e-20,0.0,-1.533412146384094e-20,0.0,-1.1018823571603408e-20,0.0,-1.2512374860235445e-20,0.0,-6.514267779823197e-21,0.0,-2.4719015385819347e-21,0.0,4.858859984935085e-21,0.0,1.881348220188166e-20,0.0,2.740874292245713e-20,0.0,5.211376231395407e-20,-4.864225626157067e-07,1.3296728230814142e-07,-3.076586015279749e-07,6.740802636874205e-08,-5.594534933091086e-07,1.1066583698276748e-07,-3.841186138586638e-07,7.559745482599735e-08,-6.098267681100678e-07,9.875238991849593e-08,-7.2970765755297e-07,1.669225383108583e-07,-6.573316628421653e-07,1.465581454371536e-07,-7.316181481946474e-07,1.5542337568784254e-07,-6.912676702186072e-07,1.3829023572925456e-07,-7.20589385417476e-07,9.666451163676767e-08,-7.723884127434406e-07,1.3857930563622999e-07,-7.569169347428396e-07,1.547516335925935e-07,-7.383025429990218e-07,1.3271074092312e-07,-7.350854918831709e-07,1.2994146610617741e-07,-7.0646090437235e-07,6.938656131041383e-08,-6.098267681100908e-07,-9.875238991845998e-08,-3.841186138586908e-07,-7.559745482597872e-08,-5.594534933091803e-07,-1.1066583698272561e-07,-3.0765860152803245e-07,-6.740802636872275e-08,-4.864225626158294e-07,-1.329672823081032e-07,-7.20589385417508e-07,-9.666451163666813e-08,-6.912676702186662e-07,-1.3829023572918171e-07,-7.316181481947439e-07,-1.5542337568773118e-07,-6.573316628422832e-07,-1.4655814543707692e-07,-7.297076575531353e-07,-1.6692253831074535e-07,-7.064609043723808e-07,-6.938656131024667e-08,-7.350854918832338e-07,-1.2994146610603196e-07,-7.383025429991161e-07,-1.3271074092293177e-07,-7.56916934742969e-07,-1.5475163359243975e-07,-7.723884127435972e-07,-1.3857930563603445e-07,-2.6225523866596743e-07,7.368618860781533e-08,-2.6483901297419715e-07,2.3043552983380804e-08,-2.6569368384400127e-07,6.351605004005378e-09,-6.372294401265312e-07,7.723333950374213e-08,-6.279151194946851e-07,2.6473214771574048e-08,-6.169026138715963e-07,5.559932643680484e-09,-8.206671947434617e-07,1.419786412636469e-08,-8.077626999789484e-07,-6.830966026358984e-09,-7.886512424652054e-07,-7.805683188152915e-09,-2.6569368384400005e-07,-6.351605004010108e-09,-2.648390129741935e-07,-2.3043552983385364e-08,-2.622552386659623e-07,-7.36861886078186e-08,-6.169026138715935e-07,-5.559932643692688e-09,-6.279151194946777e-07,-2.647321477158676e-08,-6.372294401265209e-07,-7.723333950375434e-08,-7.886512424652024e-07,7.805683188132495e-09,-8.077626999789395e-07,6.830966026337777e-09,-8.2066719474345e-07,-1.4197864126386033e-08,0.0,-1.528080794868089e-21,0.0,-1.5426894495622164e-21,0.0,-1.1495211961775125e-21,0.0,-4.441807280413718e-22,0.0,1.9784166326767865e-21,0.0,5.420802477152069e-21,0.0,-6.12858914756041e-21,0.0,-6.197208509921192e-21,0.0,-4.895012827081806e-21,0.0,-1.2104071985400557e-21,0.0,7.207223659623184e-21,0.0,2.1139789648778443e-20,0.0,-1.178112680978544e-20,0.0,-1.2361618534325795e-20,0.0,-9.332953007651742e-21,0.0,-2.4549106998298197e-21,0.0,1.5192320364423287e-20,0.0,4.128606459003346e-20,-2.6179012371741095e-07,8.492155525093568e-08,-3.431936650750607e-07,6.526689580555302e-08,-4.206987870183037e-07,7.275786337707596e-08,-6.39565352471141e-07,1.6214246375922057e-07,-6.76924119958337e-07,1.4588367240696607e-07,-6.94035042843604e-07,1.042901908413762e-07,-7.689004953903582e-07,1.574343097081281e-07,-7.476782438785353e-07,1.489103868358007e-07,-7.209785981316606e-07,8.394206942691553e-08,-4.2069878701831687e-07,-7.275786337705938e-08,-3.431936650751034e-07,-6.52668958055331e-08,-2.617901237174839e-07,-8.492155525092188e-08,-6.940350428436335e-07,-1.0429019084130907e-07,-6.769241199584262e-07,-1.458836724068901e-07,-6.39565352471292e-07,-1.6214246375914686e-07,-7.209785981316918e-07,-8.394206942678136e-08,-7.476782438786325e-07,-1.4891038683565012e-07,-7.68900495390525e-07,-1.574343097079712e-07],259,2) + arr2.setInfoOnComponents(['DRX','DRZ']) + f2z=MEDCouplingFieldDouble(ON_NODES) ; f2z.setName("SolutionDEPL") ; f2z.setArray(arr2) + f2z.setMesh(mz) + f2z.checkConsistencyLight() + ff2z=MEDFileField1TS() + ff2z.setFieldNoProfileSBT(f2z) + # + mm2=MEDFileUMesh() + mm2.setMeshAtLevel(0,mz) + mm2.setFamilyFieldArr(0,DataArrayInt([-1,-1,-1,-1,-1,-1,-1,-1,-1,-2,-2,-2,-2,-2,-2,-2,-2,-2,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-4,-4,-4,-4,-4,-4,-4,-4,-4,-5,-5,-5,-5,-5,-5,-5,-5,-5])) + mm2.setFamilyFieldArr(1,DataArrayInt([1,2,3,4,5,6,0,0,0,0,0,0,1,1,0,0,0,3,3,0,0,0,7,7,7,7,7,0,0,0,5,5,0,0,0,6,6,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,3,3,3,0,0,0,7,7,7,7,7,7,0,0,0,5,5,5,0,0,0,6,6,6,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0])) + for famName,famId in [('FAMILLE_ZERO',0),('ba1_beam',-1),('ba2_beam',-2),('h1',6),('h1_h2_h3',4),('h2',5),('h3',7),('h3_h4_h5',2),('h4',3),('h5',1),('to1_beam',-4),('to2_beam',-5),('web_beam',-3)]: + mm2.setFamilyId(famName,famId) + pass + for grName,famsOnGrp in [('ba1',['ba1_beam']),('ba2',['ba2_beam']),('beam',['ba1_beam','ba2_beam','to1_beam','to2_beam','web_beam']),('h1',['h1','h1_h2_h3']),('h2',['h1_h2_h3','h2']),('h3',['h1_h2_h3','h3','h3_h4_h5']),('h4',['h3_h4_h5','h4']),('h5',['h3_h4_h5','h5']),('to1',['to1_beam']),('to2',['to2_beam']),('web',['web_beam'])]: + mm2.setFamiliesOnGroup(grName,famsOnGrp) + pass + # + mm2.write(fname,2) + ff0z.write(fname,0) + ff1z.write(fname,0) + ff2z.write(fname,0) + return fname + +@WriteInTmpDir +def test0(baseline_file): + fname = GenerateCase() + ################### MED write is done -> Go to MEDReader + + myMedReader=MEDReader(FileName=fname) + keys=myMedReader.GetProperty("FieldsTreeInfo")[::2] + # list all the names of arrays that can be seen (including their spatial discretization) + arr_name_with_dis=[elt.split("/")[-1] for elt in keys] + # list all the names of arrays (Equal to those in the MED File) + arr_name=[elt.split(myMedReader.GetProperty("Separator").GetData())[0] for elt in arr_name_with_dis] + myMedReader.AllArrays=keys + + if '-D' not in sys.argv: + RenderView1 = GetRenderView() + ELNOfieldToSurface1=ELNOfieldToSurface(Input=myMedReader) + ExtractGroup1=ExtractGroup(Input=ELNOfieldToSurface1) + #ExtractGroup1.UpdatePipelineInformation() + ExtractGroup1.AllGroups=['GRP_ba2','GRP_to1','GRP_web'] + assert(isinstance(ExtractGroup1.GetProperty("MeshName")[0],str)) + assert(ExtractGroup1.GetProperty("MeshName")[0]=="mesh") + # + DataRepresentation3 = Show() + DataRepresentation3.ScaleFactor = 0.008999999705702066 + DataRepresentation3.EdgeColor = [0.0, 0.0, 0.5000076295109483] + DataRepresentation3.SelectionPointFieldDataArrayName = 'SolutionSIEF_ELNO' + a2_SolutionSIEQ_ELNO_PiecewiseFunction = CreatePiecewiseFunction(Points=[0.0, 0.0, 0.5, 0.0, 1.0, 1.0, 0.5, 0.0]) + #VectorMode='Magnitude' or VectorMode='Component' + a2_SolutionSIEQ_ELNO_PVLookupTable = GetLookupTableForArray("SolutionSIEQ_ELNO",2,RGBPoints=[0.0, 0.23, 0.299, 0.754, 239013.7773476667, 0.706, 0.016, 0.15], VectorMode='Component', VectorComponent=1, NanColor=[0.25, 0.0, 0.0], ColorSpace='Diverging', ScalarRangeInitialized=1.0, AllowDuplicateScalars=1 ) + DataRepresentation3.ScalarOpacityFunction = a2_SolutionSIEQ_ELNO_PiecewiseFunction + DataRepresentation3.ColorArrayName = 'SolutionSIEQ_ELNO' + DataRepresentation3.LookupTable = a2_SolutionSIEQ_ELNO_PVLookupTable + DataRepresentation3.Visibility = 1 + # + ELGAfieldToPointGaussian1=ELGAfieldToPointGaussian(Input=ELNOfieldToSurface1) + ELGAfieldToPointGaussian1.SelectSourceArray=['CELLS','ELGA@0'] + DataRepresentation4 = Show() + DataRepresentation4.ScaleFactor = 0.008999999705702066 + DataRepresentation4.EdgeColor = [0.0, 0.0, 0.5000076295109483] + DataRepresentation4.SelectionPointFieldDataArrayName = 'SolutionSIEF_ELGA' + DataRepresentation4.ColorArrayName = 'SolutionSIEF_ELGA' + ######## + RenderView1.CameraViewUp = [-0.19545466285945437, 0.837274140321886, -0.5106559396646081] + RenderView1.CameraPosition = [0.11797550069274401, 0.20119836056342144, 0.20885419432082736] + RenderView1.CameraFocalPoint = [1.0170565790969026e-18, 0.0599999981932342, 0.022500000894069675] + RenderView1.ViewSize =[300,300] + Render() + + # compare with baseline image + import vtk.test.Testing + from vtk.util.misc import vtkGetTempDir + vtk.test.Testing.VTK_TEMP_DIR = vtk.util.misc.vtkGetTempDir() + vtk.test.Testing.compareImage(GetActiveView().GetRenderWindow(), baseline_file, + threshold=1) + vtk.test.Testing.interact() + +if __name__ == "__main__": + outImgName="testMEDReader0.png" + baseline_file = RetriveBaseLine(outImgName) + test0(baseline_file) + pass diff --git a/src/Plugins/MEDReader/plugin/Test/testMEDReader1.py b/src/Plugins/MEDReader/plugin/Test/testMEDReader1.py new file mode 100644 index 00000000..6c730c2c --- /dev/null +++ b/src/Plugins/MEDReader/plugin/Test/testMEDReader1.py @@ -0,0 +1,65 @@ +# -*- coding: iso-8859-1 -*- +# Copyright (C) 2007-2019 CEA/DEN, EDF R&D +# +# This library 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. +# +# 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 +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +# +# Author : Anthony Geay + +from medcoupling import * +from MEDReaderHelper import WriteInTmpDir,RetriveBaseLine + +@WriteInTmpDir +def GenerateCase(): + """ + This test focused on ELNO. Here a 2 QUAD4 cells and a single ELNO field + is defined. + """ + fname="testMEDReader1.med" + coords=DataArrayDouble([(0,0,0),(2,1,0),(1,0,0),(1,1,0),(2,0,0),(0,1,0)]) + m=MEDCouplingUMesh("mesh",2) ; m.setCoords(coords) + m.allocateCells() + m.insertNextCell(NORM_QUAD4,[0,5,3,2]) + m.insertNextCell(NORM_QUAD4,[4,2,3,1]) + m.finishInsertingCells() + WriteMesh(fname,m,True) + # + f0=MEDCouplingFieldDouble(ON_GAUSS_NE) ; f0.setMesh(m) ; f0.setTimeUnit("ms") + f0.setTime(1.1,1,1) + f0.setName("myELNOField") + arr=DataArrayDouble([7,5,3,1,5,3,1,7]) ; arr.setInfoOnComponent(0,"Comp0") + f0.setArray(arr) + WriteFieldUsingAlreadyWrittenMesh(fname,f0) + # + f0.setTime(2.2,2,1) + arr=DataArrayDouble([1,7,5,3,7,5,3,1]) ; arr.setInfoOnComponent(0,"Comp0") + f0.setArray(arr) + WriteFieldUsingAlreadyWrittenMesh(fname,f0) + # + f0.setTime(3.3,3,1) + arr=DataArrayDouble([3,1,7,5,1,7,5,3]) ; arr.setInfoOnComponent(0,"Comp0") + f0.setArray(arr) + WriteFieldUsingAlreadyWrittenMesh(fname,f0) + # + f0.setTime(4.4,4,1) + arr=DataArrayDouble([5,3,1,7,3,1,7,5]) ; arr.setInfoOnComponent(0,"Comp0") + f0.setArray(arr) + WriteFieldUsingAlreadyWrittenMesh(fname,f0) + + +if __name__ == "__main__": + GenerateCase() + pass diff --git a/src/Plugins/MEDReader/plugin/Test/testMEDReader10.py b/src/Plugins/MEDReader/plugin/Test/testMEDReader10.py new file mode 100644 index 00000000..6cd5dc55 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/Test/testMEDReader10.py @@ -0,0 +1,131 @@ +# -*- coding: iso-8859-1 -*- +# Copyright (C) 2007-2019 CEA/DEN, EDF R&D +# +# This library 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. +# +# 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 +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +# +# Author : Anthony Geay + +import os +import sys + +from medcoupling import * +from paraview.simple import * +from MEDReaderHelper import WriteInTmpDir,RetriveBaseLine + +def GenerateCase(): + """ This test focuses on GenerateVector part. + """ + fname="testMEDReader10.med" + ############## + coo=DataArrayDouble([(0.,0.,0.),(1.,0.,0.),(2.,0.,0.),(3.,0.,0.),(0.,1.,0.),(1.,1.,0.),(2.,1.,0.),(3.,1.,0.),(0.,0.,1.),(1.,0.,1.),(2.,0.,1.),(3.,0.,1.),(0.,1.,1.),(1.,1.,1.),(2.,1.,1.),(3.,1.,1.)]) + m=MEDCouplingUMesh("myMesh",3) ; m.setCoords(coo) + m.allocateCells() + m.insertNextCell(NORM_HEXA8,[0,4,5,1,8,12,13,9]) ; m.insertNextCell(NORM_HEXA8,[1,5,6,2,9,13,14,10]) ; m.insertNextCell(NORM_HEXA8,[2,6,7,3,10,14,15,11]) + f0=MEDCouplingFieldDouble(ON_NODES) ; f0.setName("f0NbComp1") ; f0.setMesh(m) ; + arr=DataArrayDouble(8) ; arr.iota() ; arr=DataArrayDouble.Aggregate(arr,arr+8) ; arr.setInfoOnComponents(["1st"]) + f0.setArray(arr) + f1=MEDCouplingFieldDouble(ON_NODES) ; f1.setName("f1NbComp2") ; f1.setMesh(m) ; + arr=DataArrayDouble([(-1.,-1.),(0.,0.5),(0.,0.5),(1.,-1.),(-1.,1.),(0.,-0.5),(0.,-0.5),(1.,1.)]) ; arr=DataArrayDouble.Aggregate(arr,arr) ; arr.setInfoOnComponents(["1st","2nd"]) + f1.setArray(arr) + f2=MEDCouplingFieldDouble(ON_NODES) ; f2.setName("f2NbComp3") ; f2.setMesh(m) ; + arr=DataArrayDouble([(-1.,-1.,-1.),(0.,0.5,0.),(0.,0.5,0.),(1.,-1.,-1.),(-1.,1.,-1.),(0.,-0.5,0.),(0.,-0.5,0.),(1.,1.,-1)]) ; arr2=arr[:] ; arr2[[0,3,4,7],2]=1. + arr=DataArrayDouble.Aggregate(arr,arr2) ; arr.setInfoOnComponents(["1st","2nd","3rd"]) + f2.setArray(arr) + f3=MEDCouplingFieldDouble(ON_NODES) ; f3.setName("f3NbComp4") ; f3.setMesh(m) ; + arr=DataArrayDouble([(-1.,-1.,-1.),(0.,0.5,0.),(0.,0.5,0.),(1.,-1.,-1.),(-1.,1.,-1.),(0.,-0.5,0.),(0.,-0.5,0.),(1.,1.,-1)]) ; arr2=arr[:] ; arr2[[0,3,4,7],2]=1. + arr=DataArrayDouble.Aggregate(arr,arr2) ; arr3=DataArrayDouble(16) ; arr3.iota() ; arr=DataArrayDouble.Meld([arr,arr3]) + arr.setInfoOnComponents(["1st","2nd","3rd","4th"]) + f3.setArray(arr) + # + WriteMesh(fname,m,True) + WriteFieldUsingAlreadyWrittenMesh(fname,f0) + WriteFieldUsingAlreadyWrittenMesh(fname,f1) + WriteFieldUsingAlreadyWrittenMesh(fname,f2) + WriteFieldUsingAlreadyWrittenMesh(fname,f3) + return fname + + +@WriteInTmpDir +def test(baseline_file): + fname = GenerateCase() + ################### MED write is done -> Go to MEDReader + myMedReader=MEDReader(FileName=fname) + keys=myMedReader.GetProperty("FieldsTreeInfo")[::2] + # list all the names of arrays that can be seen (including their spatial discretization) + arr_name_with_dis=[elt.split("/")[-1] for elt in keys] + # list all the names of arrays (Equal to those in the MED File) + arr_name=[elt.split(myMedReader.GetProperty("Separator").GetData())[0] for elt in arr_name_with_dis] + myMedReader.AllArrays=keys + myMedReader.GenerateVectors=1 + + if '-D' not in sys.argv: + RenderView1=GetRenderView() + DataRepresentation1 = Show() + DataRepresentation1.EdgeColor = [0.0, 0.0, 0.5] + DataRepresentation1.SelectionPointFieldDataArrayName='f0NbComp1' + DataRepresentation1.ScalarOpacityUnitDistance = 2.299619191183727 + #DataRepresentation1.ExtractedBlockIndex = 1 + DataRepresentation1.ScaleFactor = 0.3 + RenderView1.CenterOfRotation = [1.5, 0.5, 0.5] + RenderView1.CameraPosition = [1.5, 0.5, 6.907227082229696] + RenderView1.CameraFocalPoint = [1.5, 0.5, 0.5] + RenderView1.CameraParallelScale = 1.6583123951777 + DataRepresentation1.Representation = 'Wireframe' + # + wbv=WarpByVector(Input=myMedReader) + wbv.ScaleFactor=0.1 + wbv.Vectors=['POINTS','f3NbComp4_Vector'] + assert(list(wbv.PointData.keys())==['f0NbComp1','f1NbComp2','f1NbComp2_Vector','f2NbComp3','f3NbComp4','f3NbComp4_Vector']) + # + DataRepresentation2 = Show() + DataRepresentation2.EdgeColor = [0.0, 0.0, 0.5000076295109483] + DataRepresentation2.SelectionPointFieldDataArrayName = 'f0NbComp1' + DataRepresentation2.SelectionCellFieldDataArrayName = 'FamilyIdCell' + DataRepresentation2.ScalarOpacityUnitDistance = 4.546673931685981 + #DataRepresentation2.ExtractedBlockIndex = 1 + DataRepresentation2.ScaleFactor = 0.5 + DataRepresentation1.Visibility = 0 + DataRepresentation1.ColorArrayName = ('POINT_DATA', '') + DataRepresentation1.Visibility = 1 + a4_f3NbComp4_PVLookupTable = GetLookupTableForArray( "f3NbComp4", 4, RGBPoints=[1.118033988749895, 0.23, 0.299, 0.754, 8.108851429645696, 0.865, 0.865, 0.865, 15.0996688705415, 0.706, 0.016, 0.15], VectorMode='Magnitude', NanColor=[0.25, 0.0, 0.0], ColorSpace='Diverging', ScalarRangeInitialized=1.0 ) + a4_f3NbComp4_PiecewiseFunction = CreatePiecewiseFunction( Points=[1.118033988749895, 0.0, 0.5, 0.0, 15.0996688705415, 1.0, 0.5, 0.0] ) + DataRepresentation1.ScalarOpacityFunction = a4_f3NbComp4_PiecewiseFunction + DataRepresentation1.LookupTable = a4_f3NbComp4_PVLookupTable + a4_f3NbComp4_PVLookupTable.ScalarOpacityFunction = a4_f3NbComp4_PiecewiseFunction + DataRepresentation2.ScalarOpacityFunction = a4_f3NbComp4_PiecewiseFunction + DataRepresentation2.ColorArrayName = ('POINT_DATA', 'f3NbComp4') + DataRepresentation2.LookupTable = a4_f3NbComp4_PVLookupTable + RenderView1.CameraViewUp = [0.32310237626907823, -0.28721735329781684, -0.901726702728644] + RenderView1.CameraPosition = [0.17151044563787257, 6.31903262423349, -1.8294921560963984] + RenderView1.CameraFocalPoint = [1.4999999999999996, 0.49999999999999944, 0.4999999999999996] + # + RenderView1.ViewSize =[300,300] + Render() + + # compare with baseline image + import vtk.test.Testing + from vtk.util.misc import vtkGetTempDir + vtk.test.Testing.VTK_TEMP_DIR = vtk.util.misc.vtkGetTempDir() + vtk.test.Testing.compareImage(GetActiveView().GetRenderWindow(), baseline_file, + threshold=1) + vtk.test.Testing.interact() + +if __name__ == "__main__": + outImgName="testMEDReader10.png" + baseline_file = RetriveBaseLine(outImgName) + test(baseline_file) + pass diff --git a/src/Plugins/MEDReader/plugin/Test/testMEDReader13.py b/src/Plugins/MEDReader/plugin/Test/testMEDReader13.py new file mode 100644 index 00000000..84925fd5 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/Test/testMEDReader13.py @@ -0,0 +1,98 @@ +# -*- coding: iso-8859-1 -*- +# Copyright (C) 2007-2019 CEA/DEN, EDF R&D +# +# This library 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. +# +# 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 +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +# +# Author : Anthony Geay + +import os +import sys + +from medcoupling import * +from paraview.simple import * +from MEDReaderHelper import WriteInTmpDir,RetriveBaseLine + +def GenerateCase(): + """ This test is non regression test to check non regression of EDF 8761. ELNO Mesh filter on vector field with 4 comps cut of using GenerateVectors""" + + fname="testMEDReader13.med" + # + + m=MEDCouplingUMesh("mesh",2) + m.setCoords(DataArrayDouble([0.,0.,0.,1.,0.,0.,2.,0.,0.,1.,1.,0.],4,3)) + m.allocateCells() + m.insertNextCell(NORM_TRI3,[0,1,3]) ; m.insertNextCell(NORM_TRI3,[1,2,3]) + f=MEDCouplingFieldDouble(ON_GAUSS_NE) ; f.setName("fieldELNO") ; f.setMesh(m) + arr=DataArrayDouble([0.2,1.1,0.7,0.5,-0.3,0.4]) + f.setArray(DataArrayDouble.Meld(4*[arr])) + f.checkConsistencyLight() + WriteField(fname,f,True) + return fname + +@WriteInTmpDir +def test(baseline_file): + fname = GenerateCase() + ################### MED write is done -> Go to MEDReader + testMEDReader13_med = MEDReader( FileName=fname ) + + testMEDReader13_med.GenerateVectors = 1 + testMEDReader13_med.AllArrays = ['TS0/mesh/ComSup0/fieldELNO@@][@@GSSNE'] + + if '-D' not in sys.argv: + RenderView1 = GetRenderView() + RenderView1.CameraPosition = [1.0, 0.5, 10000.0] + + RenderView1.CameraPosition = [1.0, 0.5, 4.319751617610021] + + ELNOfieldToSurface3 = ELNOfieldToSurface(Input=testMEDReader13_med) + + DataRepresentation2 = Show() + #DataRepresentation2.ConstantRadius = 1.9999333620071411 + DataRepresentation2.EdgeColor = [0.0, 0.0, 0.5000076295109483] + #DataRepresentation2.PointGaussianDefaultsInitialized = 1 + DataRepresentation2.SelectionPointFieldDataArrayName = 'fieldELNO' + DataRepresentation2.SelectionCellFieldDataArrayName = 'FamilyIdCell' + #DataRepresentation2.SelectInputVectors = ['POINTS', 'fieldELNO_Vector'] + DataRepresentation2.ScalarOpacityUnitDistance = 1.7746382108908556 + DataRepresentation2.Texture = [] + DataRepresentation2.ExtractedBlockIndex = 1 + #DataRepresentation2.RadiusRange = [6.666666740784422e-05, 1.9999333620071411] + DataRepresentation2.ScaleFactor = 0.19998666953397334 + + #DataRepresentation2.RadiusRange = [6.66667e-05, 1.99993] + DataRepresentation2.ColorArrayName = ('POINT_DATA', 'fieldELNO_Vector') + + a3_fieldELNO_Vector_PVLookupTable = GetLookupTableForArray( "fieldELNO_Vector", 3, RGBPoints=[0.3464101615137755, 0.23, 0.299, 0.754, 1.1258330249197703, 0.865, 0.865, 0.865, 1.9052558883257653, 0.706, 0.016, 0.15], VectorMode='Magnitude', NanColor=[0.25, 0.0, 0.0], ColorSpace='Diverging', ScalarRangeInitialized=1.0 ) + + a3_fieldELNO_Vector_PiecewiseFunction = CreatePiecewiseFunction( Points=[0.3464101615137755, 0.0, 0.5, 0.0, 1.9052558883257653, 1.0, 0.5, 0.0] ) + + RenderView1.ViewSize =[300,300] + Render() + + # compare with baseline image + import vtk.test.Testing + from vtk.util.misc import vtkGetTempDir + vtk.test.Testing.VTK_TEMP_DIR = vtk.util.misc.vtkGetTempDir() + vtk.test.Testing.compareImage(GetActiveView().GetRenderWindow(), baseline_file, + threshold=1) + vtk.test.Testing.interact() + +if __name__ == "__main__": + outImgName="testMEDReader13.png" + baseline_file = RetriveBaseLine(outImgName) + test(baseline_file) + pass diff --git a/src/Plugins/MEDReader/plugin/Test/testMEDReader14.py b/src/Plugins/MEDReader/plugin/Test/testMEDReader14.py new file mode 100644 index 00000000..e8eca2c1 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/Test/testMEDReader14.py @@ -0,0 +1,181 @@ +# -*- coding: iso-8859-1 -*- +# Copyright (C) 2007-2019 CEA/DEN, EDF R&D +# +# This library 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. +# +# 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 +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +# +# Author : Anthony Geay (EDF R&D) + +import os +import sys + +from medcoupling import * +from paraview.simple import * +from MEDReaderHelper import WriteInTmpDir,RetriveBaseLine +paraview.simple._DisableFirstRenderCameraReset() + +def GenerateCase(): + """ This test reproduces precisely the bug EDF8655 (PAL 22677) by cheking that multi loc per geo type in a field is correctly managed. + """ + + fname="testMEDReader14.med" + + arr0=DataArrayDouble(7) ; arr0.iota() + arr1=DataArrayDouble(5) ; arr1.iota() + c=MEDCouplingCMesh() + c.setCoords(arr0,arr1) + m=c.build1SGTUnstructured() + pfl=DataArrayInt([5,10,11,16,17,23]) + m0=m[pfl.buildComplement(24)] + m1=m[pfl] ; m1.simplexize(0) + m=MEDCouplingUMesh.MergeUMeshesOnSameCoords(m1.buildUnstructured(),m0.buildUnstructured()) + m.setName("Mesh") + m1=MEDCoupling1SGTUMesh(m.getName(),NORM_SEG2) + m1.setCoords(m.getCoords()) + m1.allocateCells() + for i in [[28,21],[21,14],[14,7],[7,0]]: + m1.insertNextCell(i) + pass + for i in range(6): + m1.insertNextCell([i,i+1]) + pass + for i in [[6,13],[13,20],[20,27],[27,34]]: + m1.insertNextCell(i) + pass + for i in range(6,0,-1): + m1.insertNextCell([28+i,28+i-1]) + pass + # + mm=MEDFileUMesh() + mm.setMeshAtLevel(0,m) + mm.setMeshAtLevel(-1,m1) + mm.write(fname,2) + # + pfl0=DataArrayInt([0,1,2,3]) ; pfl0.setName("PFL000") + pfl1=DataArrayInt([4,5,6,7,8,9]) ; pfl1.setName("PFL001") + pfl2=DataArrayInt([10,11,12,13]) ; pfl2.setName("PFL002") + pfl3=DataArrayInt([13,14,15,16,19,20,23,24,26,27,28,29]) ; pfl3.setName("PFL003") + # + fieldName0="zeField0" + fieldName1="zeField1" + fieldName2="zeField2" + fs0=MEDFileFieldMultiTS() + fs1=MEDFileFieldMultiTS() + fs2=MEDFileFieldMultiTS() + for i in range(5): + f=MEDFileField1TS() + zePfl0=DataArrayInt.Aggregate(DataArrayInt.Range(0,12,1),pfl3,0) ; zePfl0.setName("PFL") + fNode=MEDCouplingFieldDouble(ON_GAUSS_PT) ; fNode.setTime(float(i),i,0) + tmp=m[zePfl0] + fNode.setName(fieldName0) ; fNode.setMesh(tmp) + fNode.setGaussLocalizationOnCells(DataArrayInt.Range(0,12,1),[0.,0.,1.,0.,0.,1.],[0.1,0.1,0.8,0.1,0.1,0.8],3*[0.16666666666666666]) + fNode.setGaussLocalizationOnCells(DataArrayInt.Range(12,24,1),[-1.,-1.,1.,-1.,1.,1.,-1.,1.],[-0.577350,-0.577350,0.577350,-0.577350,0.577350,0.577350,-0.577350,0.577350],4*[1.]) + arr=DataArrayDouble(2*(12*3+12*4)) ; arr.iota(0+1000*i) ; arr.rearrange(2) + fNode.setArray(arr) ; arr.setInfoOnComponents(["Comp1_2 [m]","Com2_2 [s^2]"]) ; fNode.checkConsistencyLight() + fNode.setName(fieldName0) + f.setFieldProfile(fNode,mm,0,zePfl0) + # + zePfl1=DataArrayInt.Range(0,14,1) ; zePfl1.setName("PFL") + fNode=MEDCouplingFieldDouble(ON_GAUSS_PT) ; fNode.setTime(float(i),i,0) + tmp=m1[zePfl1] + # + fNode.setName(fieldName0) ; fNode.setMesh(tmp) + fNode.setGaussLocalizationOnCells(DataArrayInt.Range(0,4,1),[-1.,1.],[-0.33333333333333337,0.33333333333333337],[1.,1.]) + fNode.setGaussLocalizationOnCells(DataArrayInt.Range(4,10,1),[-1.,1.],[-0.5,0.,0.5],[1.,1.,1.]) + fNode.setGaussLocalizationOnCells(DataArrayInt.Range(10,14,1),[-1.,1.],[-0.6,-0.2,0.2,0.6],[1.,1.,1.,1.]) + arr=DataArrayDouble(2*(4*2+6*3+4*4)) ; arr.iota(100+1000*i) ; arr.rearrange(2) + fNode.setArray(arr) ; arr.setInfoOnComponents(["Comp1_2 [m]","Com2_2 [s^2]"]) ; fNode.checkConsistencyLight() + fNode.setName(fieldName0) + f.setFieldProfile(fNode,mm,-1,zePfl1) + fs0.pushBackTimeStep(f) + # + f=MEDFileField1TS() + zePfl2=DataArrayInt.Range(10,20,1) ; zePfl2.setName("PFL2") + fNode=MEDCouplingFieldDouble(ON_GAUSS_PT) ; fNode.setTime(float(i),i,0) + tmp=m1[zePfl2] + fNode.setName(fieldName1) ; fNode.setMesh(tmp) + fNode.setGaussLocalizationOnCells(DataArrayInt.Range(0,4,1),[-1.,1.],[-0.6,-0.2,0.2,0.6],[1.,1.,1.,1.]) + fNode.setGaussLocalizationOnCells(DataArrayInt.Range(4,10,1),[-1.,1.],[-0.6666666666666667,-0.33333333333333337,0.,0.33333333333333337,0.6666666666666667],[1.,1.,1.,1.,1.]) + arr=DataArrayDouble(2*(4*4+6*5)) ; arr.iota(500+1000*i) ; arr.rearrange(2) + fNode.setArray(arr) ; arr.setInfoOnComponents(["C1 [m]","C2 [s^2]"]) ; fNode.checkConsistencyLight() + f.setFieldProfile(fNode,mm,-1,zePfl2) + fs1.pushBackTimeStep(f) + # + f=MEDFileField1TS() + zePfl3=DataArrayInt([6,10,11,12,13,17,18,19,20,24,25,26,27,34]) ; zePfl3.setName("PFL3") + fNode=MEDCouplingFieldDouble(ON_NODES) ; fNode.setTime(float(i),i,0) + fNode.setName(fieldName2) + arr=DataArrayDouble(2*14) ; arr.iota(700+1000*i) ; arr.rearrange(2) + fNode.setArray(arr) ; arr.setInfoOnComponents(["C3 [kg]","C4 [m^2]"]) + f.setFieldProfile(fNode,mm,0,zePfl3) + fs2.pushBackTimeStep(f) + pass + fs0.write(fname,0) + fs1.write(fname,0) + fs2.write(fname,0) + return fname + +@WriteInTmpDir +def test(baseline_file): + fname = GenerateCase() + reader=MEDReader(FileName=fname) + ExpectedEntries=['TS0/Mesh/ComSup0/zeField0_MM0@@][@@GAUSS', 'TS0/Mesh/ComSup1/zeField0_MM1@@][@@GAUSS', 'TS0/Mesh/ComSup2/zeField0_MM2@@][@@GAUSS', 'TS0/Mesh/ComSup2/zeField1_MM0@@][@@GAUSS', 'TS0/Mesh/ComSup3/zeField1_MM1@@][@@GAUSS', 'TS0/Mesh/ComSup4/zeField2@@][@@P1', 'TS1/Mesh/ComSup0/Mesh@@][@@P0'] + assert(reader.GetProperty("FieldsTreeInfo")[::2]==ExpectedEntries) + + if '-D' not in sys.argv: + renderView1=GetActiveViewOrCreate('RenderView') + for entry in [[ExpectedEntries[0]],[ExpectedEntries[1]],[ExpectedEntries[2],ExpectedEntries[3]],[ExpectedEntries[4]]]: + reader=MEDReader(FileName=fname) + reader.AllArrays=entry + gaussPoints=ELGAfieldToPointGaussian(Input=reader) + gaussPoints.SelectSourceArray="ELGA@0" + Show(gaussPoints,renderView1) + pass + + # + + readerNodeField=MEDReader(FileName=fname) + readerNodeField.AllArrays=[ExpectedEntries[5]] + nodeFieldDisplay=Show(readerNodeField,renderView1) + ColorBy(nodeFieldDisplay,('POINTS','zeField2')) + nodeFieldDisplay.RescaleTransferFunctionToDataRange(True) + zeField2LUT=GetColorTransferFunction('zeField2') + zeField2LUT.RGBPoints=[990.6568528002015, 0.231373, 0.298039, 0.752941, 1009.0416245953584, 0.865003, 0.865003, 0.865003, 1027.4263963905153, 0.705882, 0.0156863, 0.14902] + zeField2LUT.ScalarRangeInitialized=1. + # + renderView1.ResetCamera() + renderView1.InteractionMode = '2D' + renderView1.CameraPosition = [3.0, 2.0, 10000.0] + renderView1.CameraFocalPoint = [3.0, 2.0, 0.0] + renderView1.ViewSize =[300,300] + renderView1.GetRenderWindow().DoubleBufferOff() + # + + Render() + + # compare with baseline image + import vtk.test.Testing + from vtk.util.misc import vtkGetTempDir + vtk.test.Testing.VTK_TEMP_DIR = vtk.util.misc.vtkGetTempDir() + vtk.test.Testing.compareImage(renderView1.GetRenderWindow(), baseline_file, + threshold=1) + vtk.test.Testing.interact() + +if __name__ == "__main__": + outImgName="testMEDReader14.png" + baseline_file = RetriveBaseLine(outImgName) + test(baseline_file) + pass diff --git a/src/Plugins/MEDReader/plugin/Test/testMEDReader15.py b/src/Plugins/MEDReader/plugin/Test/testMEDReader15.py new file mode 100644 index 00000000..f3ea0e24 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/Test/testMEDReader15.py @@ -0,0 +1,95 @@ +# -*- coding: iso-8859-1 -*- +# Copyright (C) 2007-2019 CEA/DEN, EDF R&D +# +# This library 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. +# +# 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 +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +# +# Author : Anthony Geay (EDF R&D) + +import os +import sys + +from medcoupling import * +from paraview.simple import * +from MEDReaderHelper import WriteInTmpDir,RetriveBaseLine + +paraview.simple._DisableFirstRenderCameraReset() + +def GenerateCase(): + """ This test is a non regression test that checks the behaviour of MEDReader when a mesh has the same name than a field. + """ + + fname="testMEDReader15.med" + + zeName="zeName" + c=DataArrayDouble([(0.,0.,0.),(1.,0.,0.),(0.,1.,0.)]) + m=MEDFileUMesh() + m.setCoords(c) + m.setName(zeName) + m.write(fname,2) + f=MEDCouplingFieldDouble(ON_NODES) + f.setName(zeName) + f.setArray(DataArrayDouble([(-1.,1.,0.),(0.,1.,0.),(1.,1.,0.)])) + tmp=MEDCouplingUMesh.Build0DMeshFromCoords(m.getCoords()) ; tmp.setName(zeName) + f.setMesh(tmp) + WriteFieldUsingAlreadyWrittenMesh(fname,f) + return fname + +@WriteInTmpDir +def test(baseline_file): + fname = GenerateCase() + reader=MEDReader(FileName=fname) + ExpectedEntries=['TS0/zeName/ComSup0/zeName@@][@@P1','TS0/zeName/ComSup0/MESH@zeName@@][@@P1'] + assert(reader.GetProperty("FieldsTreeInfo")[::2]==ExpectedEntries) + + # + glyph1=Glyph(Input=reader,GlyphType='Arrow',ScaleArray='FamilyIdNode',OrientationArray='zeName',GlyphMode='All Points',ScaleFactor=0.1,GlyphTransform='Transform2') + + if '-D' not in sys.argv: + renderView1=GetActiveViewOrCreate('RenderView') + renderView1.InteractionMode='3D' + zeNameLUT = GetColorTransferFunction('zeName') + zeNameLUT.RGBPoints = [1.0, 0.231373, 0.298039, 0.752941, 1.2071067811865475, 0.865003, 0.865003, 0.865003, 1.4142135623730951, 0.705882, 0.0156863, 0.14902] + zeNameLUT.ScalarRangeInitialized = 1. + zeNameLUT.VectorMode = 'Component' + + glyph1Display=Show(glyph1,renderView1) + glyph1Display.ColorArrayName = ['POINTS', 'FamilyIdNode'] + glyph1Display.LookupTable = zeNameLUT + # set scalar coloring + ColorBy(glyph1Display, ('POINTS', 'zeName')) + # rescale color and/or opacity maps used to include current data range + glyph1Display.RescaleTransferFunctionToDataRange(True) + # do not show color bar/color legend + glyph1Display.SetScalarBarVisibility(renderView1, False) + # + renderView1.ViewSize =[300,300] + renderView1.GetRenderWindow().DoubleBufferOff() + Render() + + # compare with baseline image + import vtk.test.Testing + from vtk.util.misc import vtkGetTempDir + vtk.test.Testing.VTK_TEMP_DIR = vtk.util.misc.vtkGetTempDir() + vtk.test.Testing.compareImage(GetActiveView().GetRenderWindow(), baseline_file, + threshold=1) + vtk.test.Testing.interact() + +if __name__ == "__main__": + outImgName="testMEDReader15.png" + baseline_file = RetriveBaseLine(outImgName) + test(baseline_file) + pass diff --git a/src/Plugins/MEDReader/plugin/Test/testMEDReader16.py b/src/Plugins/MEDReader/plugin/Test/testMEDReader16.py new file mode 100644 index 00000000..cc31f6c7 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/Test/testMEDReader16.py @@ -0,0 +1,114 @@ +# -*- coding: iso-8859-1 -*- +# Copyright (C) 2007-2019 CEA/DEN, EDF R&D +# +# This library 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. +# +# 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 +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +# +# Author : Anthony Geay (EDF R&D) + +from medcoupling import * +from paraview.simple import * +from paraview import servermanager +from MEDReaderHelper import WriteInTmpDir,RetriveBaseLine + +paraview.simple._DisableFirstRenderCameraReset() + +def GenerateCase(): + """ This test is a non regression test of EDF8662 : This bug revealed that ELNOfieldToSurface and ELNOfieldToPointGaussian do not behave correctly after the call of ExtractGroup""" + + fname="testMEDReader16.med" + + arr=DataArrayDouble([0,1,2]) + m=MEDCouplingCMesh() ; m.setCoords(arr,arr) ; m=m.buildUnstructured() ; m.setName("Mesh") + mm=MEDFileUMesh() ; mm.setMeshAtLevel(0,m) + grp0=DataArrayInt([0,1]) ; grp0.setName("grp0") + grp1=DataArrayInt([2,3]) ; grp1.setName("grp1") + grp2=DataArrayInt([1,2]) ; grp2.setName("grp2") + grp3=DataArrayInt([0,1,2,3]) ; grp3.setName("grp3") + mm.setGroupsAtLevel(0,[grp0,grp1,grp2,grp3]) + f=MEDCouplingFieldDouble(ON_GAUSS_NE) ; f.setMesh(m) ; f.setName("MyField") ; f.setTime(0.,0,0) + arr2=DataArrayDouble(4*4*2) ; arr2.iota() ; arr2.rearrange(2) ; arr2.setInfoOnComponents(["aa","bbb"]) + f.setArray(arr2) ; arr2+=0.1 ; f.checkConsistencyLight() + mm.write(fname,2) + WriteFieldUsingAlreadyWrittenMesh(fname,f) + return fname, arr2 + + +@WriteInTmpDir +def test(): + fname,arr2 = GenerateCase() + # + reader=MEDReader(FileName=fname) + ExpectedEntries=['TS0/Mesh/ComSup0/MyField@@][@@GSSNE','TS1/Mesh/ComSup0/Mesh@@][@@P0'] + assert(reader.GetProperty("FieldsTreeInfo")[::2]==ExpectedEntries) + reader.AllArrays=['TS0/Mesh/ComSup0/MyField@@][@@GSSNE'] + ExtractGroup1 = ExtractGroup(Input=reader) + #ExtractGroup1.UpdatePipelineInformation() + ExtractGroup1.AllGroups=["GRP_grp1"] + ELNOfieldToSurface1=ELNOfieldToSurface(Input=ExtractGroup1) + ELNOfieldToPointGaussian1=ELNOfieldToPointGaussian(Input=ExtractGroup1) + ELNOfieldToPointGaussian1.SelectSourceArray=['ELNO@MyField'] + for elt in [ELNOfieldToSurface1,ELNOfieldToPointGaussian1]: + elnoMesh=servermanager.Fetch(ELNOfieldToPointGaussian1,0) + vtkArrToTest=elnoMesh.GetBlock(0).GetPointData().GetArray("MyField") + assert(vtkArrToTest.GetNumberOfTuples()==8) + assert(vtkArrToTest.GetNumberOfComponents()==2) + assert(vtkArrToTest.GetComponentName(0)==arr2.getInfoOnComponent(0)) + assert(vtkArrToTest.GetComponentName(1)==arr2.getInfoOnComponent(1)) + vals=[vtkArrToTest.GetValue(i) for i in range(16)] + assert(arr2[8:].isEqualWithoutConsideringStr(DataArrayDouble(vals,8,2),1e-12)) + pass + # + ExtractGroup1.AllGroups=["GRP_grp2"] + for elt in [ELNOfieldToSurface1,ELNOfieldToPointGaussian1]: + elnoMesh=servermanager.Fetch(ELNOfieldToSurface1) + vtkArrToTest=elnoMesh.GetBlock(0).GetPointData().GetArray("MyField") + assert(vtkArrToTest.GetNumberOfTuples()==8) + assert(vtkArrToTest.GetNumberOfComponents()==2) + assert(vtkArrToTest.GetComponentName(0)==arr2.getInfoOnComponent(0)) + assert(vtkArrToTest.GetComponentName(1)==arr2.getInfoOnComponent(1)) + vals=[vtkArrToTest.GetValue(i) for i in range(16)] + assert(arr2[4:12].isEqualWithoutConsideringStr(DataArrayDouble(vals,8,2),1e-12)) + pass + # important to check that if all the field is present that it is OK (check of the optimization) + ExtractGroup1.AllGroups=["GRP_grp3"] + for elt in [ELNOfieldToSurface1,ELNOfieldToPointGaussian1]: + elnoMesh=servermanager.Fetch(ELNOfieldToSurface1) + vtkArrToTest=elnoMesh.GetBlock(0).GetPointData().GetArray("MyField") + assert(vtkArrToTest.GetNumberOfTuples()==16) + assert(vtkArrToTest.GetNumberOfComponents()==2) + assert(vtkArrToTest.GetComponentName(0)==arr2.getInfoOnComponent(0)) + assert(vtkArrToTest.GetComponentName(1)==arr2.getInfoOnComponent(1)) + vals=[vtkArrToTest.GetValue(i) for i in range(32)] + assert(arr2.isEqualWithoutConsideringStr(DataArrayDouble(vals,16,2),1e-12)) + pass + ELNOfieldToSurface1=ELNOfieldToSurface(Input=reader) + ELNOfieldToPointGaussian1=ELNOfieldToPointGaussian(Input=reader) + ELNOfieldToPointGaussian1.SelectSourceArray=['ELNO@MyField'] + for elt in [ELNOfieldToSurface1,ELNOfieldToPointGaussian1]: + elnoMesh=servermanager.Fetch(ELNOfieldToSurface1) + vtkArrToTest=elnoMesh.GetBlock(0).GetPointData().GetArray("MyField") + assert(vtkArrToTest.GetNumberOfTuples()==16) + assert(vtkArrToTest.GetNumberOfComponents()==2) + assert(vtkArrToTest.GetComponentName(0)==arr2.getInfoOnComponent(0)) + assert(vtkArrToTest.GetComponentName(1)==arr2.getInfoOnComponent(1)) + vals=[vtkArrToTest.GetValue(i) for i in range(32)] + assert(arr2.isEqualWithoutConsideringStr(DataArrayDouble(vals,16,2),1e-12)) + pass + +if __name__ == "__main__": + test() + pass diff --git a/src/Plugins/MEDReader/plugin/Test/testMEDReader17.py b/src/Plugins/MEDReader/plugin/Test/testMEDReader17.py new file mode 100644 index 00000000..893ff4e1 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/Test/testMEDReader17.py @@ -0,0 +1,78 @@ +# -*- coding: iso-8859-1 -*- +# Copyright (C) 2007-2019 CEA/DEN, EDF R&D +# +# This library 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. +# +# 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 +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +# +# Author : Anthony Geay (EDF R&D) + +from medcoupling import * +from paraview.simple import * +from paraview import servermanager +from MEDReaderHelper import WriteInTmpDir,RetriveBaseLine + +paraview.simple._DisableFirstRenderCameraReset() + +def GenerateCase(): + """ This test is a non regression test of EDF9622.""" + + fname="testMEDReader17.med" + + arr=DataArrayDouble([0,1,2]) + m=MEDCouplingCMesh() ; m.setCoords(arr,arr) ; m=m.buildUnstructured() ; m.setName("Mesh") + mm=MEDFileUMesh() ; mm.setMeshAtLevel(0,m) + grp0=DataArrayInt([0,1]) ; grp0.setName("grp0") + grp1=DataArrayInt([2,3]) ; grp1.setName("grp1") + grp2=DataArrayInt([1,2]) ; grp2.setName("grp2") + grp3=DataArrayInt([0,1,2,3]) ; grp3.setName("grp3") + mm.setGroupsAtLevel(0,[grp0,grp1,grp2,grp3]) + f=MEDCouplingFieldDouble(ON_GAUSS_NE) ; f.setMesh(m) ; f.setName("MyField") ; f.setTime(0.,0,0) + arr2=DataArrayDouble(4*4*2) ; arr2.iota() ; arr2.rearrange(2) ; arr2.setInfoOnComponents(["aa","bbb"]) + f.setArray(arr2) ; arr2+=0.1 ; f.checkConsistencyLight() + mm.write(fname,2) + WriteFieldUsingAlreadyWrittenMesh(fname,f) + return fname + +@WriteInTmpDir +def test(): + fname = GenerateCase() + # + reader=MEDReader(FileName=fname) + ExpectedEntries=['TS0/Mesh/ComSup0/MyField@@][@@GSSNE','TS1/Mesh/ComSup0/Mesh@@][@@P0'] + assert(reader.GetProperty("FieldsTreeInfo")[::2]==ExpectedEntries) + reader.AllArrays=['TS0/Mesh/ComSup0/MyField@@][@@GSSNE'] + ExtractGroup1 = ExtractGroup(Input=reader) + #ExtractGroup1.UpdatePipelineInformation() + ExtractGroup1.AllGroups=["GRP_grp1"] + ELNOfieldToPointGaussian1=ELNOfieldToPointGaussian(Input=ExtractGroup1) + ELNOfieldToPointGaussian1.SelectSourceArray=['ELNO@MyField'] + # + ELNOfieldToPointGaussian1=ELNOfieldToPointGaussian(Input=reader) + ELNOfieldToPointGaussian1.SelectSourceArray=['ELNO@MyField'] + ExtractGroup1 = ExtractGroup(Input=ELNOfieldToPointGaussian1) + #ExtractGroup1.UpdatePipelineInformation() + ExtractGroup1.AllGroups=["GRP_grp1"] + #ExtractGroup1.UpdatePipeline() + res=servermanager.Fetch(ExtractGroup1,0) + assert(res.GetBlock(0).GetNumberOfCells()==8) + vtkArrToTest=res.GetBlock(0).GetPointData().GetArray("MyField") + assert(vtkArrToTest.GetNumberOfComponents()==2) + assert(vtkArrToTest.GetNumberOfTuples()==8) + vals=[vtkArrToTest.GetValue(i) for i in range(16)] + assert(DataArrayDouble([(16.1,17.1),(18.1,19.1),(20.1,21.1),(22.1,23.1),(24.1,25.1),(26.1,27.1),(28.1,29.1),(30.1,31.1)]).isEqual(DataArrayDouble(vals,8,2),1e-12)) + +if __name__ == "__main__": + test() diff --git a/src/Plugins/MEDReader/plugin/Test/testMEDReader18.py b/src/Plugins/MEDReader/plugin/Test/testMEDReader18.py new file mode 100644 index 00000000..fc668781 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/Test/testMEDReader18.py @@ -0,0 +1,66 @@ +# -*- coding: iso-8859-1 -*- +# Copyright (C) 2015-2019 CEA/DEN, EDF R&D +# +# This library 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. +# +# 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 +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +# +# Author : Anthony Geay (EDF R&D) + + +from medcoupling import * +from paraview.simple import * +from MEDReaderHelper import WriteInTmpDir,RetriveBaseLine + +def GenerateCase(): + """Non regression test for bug EDF11343. Extract group on groups mixing cells entities and node entities.""" + fname="testMEDReader18.med" + arr1=DataArrayDouble(5) ; arr1.iota() + arr2=DataArrayDouble([0,1]) + m=MEDCouplingCMesh() ; m.setCoords(arr1,arr2) + m.setName("mesh") + m=m.buildUnstructured() + # + mm=MEDFileUMesh() + mm[0]=m + # + grp0=DataArrayInt([1,2]) ; grp0.setName("grp0") + grp1=DataArrayInt([3,4,8,9]) ; grp1.setName("grp1") + # + mm.addGroup(0,grp0) + mm.addGroup(1,grp1) + # + mm.write(fname,2) + return fname + +@WriteInTmpDir +def test(): + fname = GenerateCase() + reader=MEDReader(FileName=fname) + reader.AllArrays=['TS0/mesh/ComSup0/mesh@@][@@P0'] + ExtractGroup1 = ExtractGroup(Input=reader) + ExtractGroup1.AllGroups=["GRP_grp0","GRP_grp1"] + #ExtractGroup1.UpdatePipelineInformation() + res=servermanager.Fetch(ExtractGroup1,0) + assert(res.GetNumberOfBlocks()==2) + assert(res.GetBlock(1).GetNumberOfCells()==1) + assert(res.GetBlock(0).GetNumberOfCells()==2) + pass + +if __name__ == "__main__": + test() + pass + + diff --git a/src/Plugins/MEDReader/plugin/Test/testMEDReader19.py b/src/Plugins/MEDReader/plugin/Test/testMEDReader19.py new file mode 100644 index 00000000..0b476e1f --- /dev/null +++ b/src/Plugins/MEDReader/plugin/Test/testMEDReader19.py @@ -0,0 +1,107 @@ +# -*- coding: iso-8859-1 -*- +# Copyright (C) 2015-2019 CEA/DEN, EDF R&D +# +# This library 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. +# +# 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 +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +# +# Author : Anthony Geay + +import os +import sys + +from medcoupling import * +from paraview.simple import * +from MEDReaderHelper import WriteInTmpDir,RetriveBaseLine +#### import the simple module from the paraview +#### disable automatic camera reset on 'Show' +paraview.simple._DisableFirstRenderCameraReset() +import vtk.test.Testing # this line must be here. If not SIGSEGV ! KW10658 + +def GenerateCase(): + """ This is a non regression bug revealed during training session. The bug is linked to the native Threshold VTK filter. Corrected with PV version >= 4.4. (KW10658) + There is still a problem when both image comparison and Fetch are enable together.""" + fname="testMEDReader19.med" + meshName="mesh" + mm=MEDFileUMesh() + coo=DataArrayDouble([(-0.3,-0.3),(0.2,-0.3),(0.7,-0.3),(-0.3,0.2),(0.2,0.2),(0.7,0.2),(-0.3,0.7),(0.2,0.7),(0.7,0.7)]) + conn0=[[NORM_TRI3,1,4,2],[NORM_TRI3,4,5,2],[NORM_QUAD4,0,3,4,1],[NORM_QUAD4,6,7,4,3],[NORM_QUAD4,7,8,5,4]] + conn1=[[NORM_SEG2,4,5],[NORM_SEG2,5,2],[NORM_SEG2,1,0],[NORM_SEG2,6,7]] + m0=MEDCouplingUMesh() ; m0.setCoords(coo) ; m0.setMeshDimension(2) ; m0.allocateCells(0) + for c in conn0: + m0.insertNextCell(c[0],c[1:]) + mm[0]=m0 + m1=MEDCouplingUMesh() ; m1.setCoords(coo) ; m1.setMeshDimension(1) ; m1.allocateCells(0) + for c in conn1: + m1.insertNextCell(c[0],c[1:]) + mm[-1]=m1 + mm.setName(meshName) + mm.write(fname,2) + return fname + +@WriteInTmpDir +def test(baseline_file): + fname = GenerateCase() + # create a new 'MED Reader' + testMEDReader19med = MEDReader(FileName=fname) + testMEDReader19med.AllArrays = ['TS0/mesh/ComSup0/mesh@@][@@P0'] + testMEDReader19med.AllTimeSteps = ['0000'] + # Properties modified on testMEDReader19med + testMEDReader19med.AllArrays = ['TS0/mesh/ComSup0/mesh@@][@@P0'] + + if '-D' not in sys.argv: + # get active view + renderView1 = GetActiveViewOrCreate('RenderView') + + # reset view to fit data + renderView1.ResetCamera() + + #changing interaction mode based on data extents + renderView1.InteractionMode = '2D' + renderView1.CameraPosition = [0.2, 0.2, 10000.0] + renderView1.CameraFocalPoint = [0.2, 0.2, 0.0] + testMEDReader19med.UpdatePipeline() + # create a new 'Extract Cell Type' + extractCellType1 = ExtractCellType(Input=testMEDReader19med) + extractCellType1.AllGeoTypes = [] + + # Properties modified on extractCellType1 + extractCellType1.AllGeoTypes = ['TRI3'] + + # show data in view + extractCellType1Display = Show(extractCellType1, renderView1) + # trace defaults for the display properties. + extractCellType1Display.ColorArrayName = [None, ''] + extractCellType1Display.ScalarOpacityUnitDistance = 0.5 + + renderView1.InteractionMode = '2D' + renderView1.CameraPosition = [0.2, 0.2, 10000.0] + renderView1.CameraFocalPoint = [0.2, 0.2, 0.0] + renderView1.CameraParallelScale = 0.7071067811865476 + + res=servermanager.Fetch(extractCellType1,0) + assert(res.GetBlock(0).GetNumberOfCells()==2) # problem was here in PV4.3.1 + + # compare with baseline image # Waiting KW return to uncomment this part because SIGSEGV in PV5. + import vtk.test.Testing + from vtk.util.misc import vtkGetTempDir + vtk.test.Testing.VTK_TEMP_DIR = vtk.util.misc.vtkGetTempDir() + vtk.test.Testing.compareImage(GetActiveView().GetRenderWindow(), baseline_file, threshold=1) + vtk.test.Testing.interact() + +if __name__ == "__main__": + imgName="testMEDReader19.png" + baseline_file = RetriveBaseLine(imgName) + test(baseline_file) diff --git a/src/Plugins/MEDReader/plugin/Test/testMEDReader2.py b/src/Plugins/MEDReader/plugin/Test/testMEDReader2.py new file mode 100644 index 00000000..5374a13d --- /dev/null +++ b/src/Plugins/MEDReader/plugin/Test/testMEDReader2.py @@ -0,0 +1,125 @@ +# -*- coding: iso-8859-1 -*- +# Copyright (C) 2007-2019 CEA/DEN, EDF R&D +# +# This library 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. +# +# 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 +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +# +# Author : Anthony Geay + +import os +import sys + +from medcoupling import * +from paraview.simple import * +from MEDReaderHelper import WriteInTmpDir,RetriveBaseLine + +def GenerateCase(): + """ This use case is a mesh containing a large number of orphan cells (cells having no field lying on them) + """ + fname="testMEDReader2.med" + ######### + arrX=DataArrayDouble(7) ; arrX.iota() + arrY=DataArrayDouble(7) ; arrY.iota() + arrZ=DataArrayDouble(7) ; arrZ.iota() + m=MEDCouplingCMesh() + m.setCoords(arrX,arrY,arrZ) + m=m.buildUnstructured() ; m.setName("mesh") + tmp=m[3*36:4*36] + tmp=tmp.buildDescendingConnectivity()[0] + nodeIds=tmp.findNodesOnPlane([0.,0.,3.],[0.,0.,1.],1e-12) + cellIds=tmp.getCellIdsLyingOnNodes(nodeIds,True) + m1=tmp[cellIds] + mm=MEDFileUMesh() + mm.setMeshAtLevel(0,m) + mm.setMeshAtLevel(-1,m1) + mm.write(fname,2) + # + pfl=DataArrayInt([7,8,9,10,13,14,15,16,19,20,21,22,25,26,27,28]) ; pfl.setName("pfl") + f=MEDCouplingFieldDouble(ON_CELLS) ; f.setName("ACellField") + arr=DataArrayDouble(16) ; arr.iota() + arr2=arr.deepCopy() ; arr2.reverse() + arr=DataArrayDouble.Meld(arr,arr2) ; arr.setInfoOnComponents(["aa","bbb"]) + f.setArray(arr) + f1ts=MEDFileField1TS() + f1ts.setFieldProfile(f,mm,-1,pfl) + f1ts.write(fname,0) + return fname + +@WriteInTmpDir +def test(baseline_file): + fname = GenerateCase() + ################### MED write is done -> Go to MEDReader + testMEDReader1=MEDReader(FileName=fname) + testMEDReader1.AllArrays=['TS0/mesh/ComSup0/ACellField@@][@@P0'] + testMEDReader2=MEDReader(FileName=fname) + testMEDReader2.AllArrays=['TS0/mesh/ComSup1/mesh@@][@@P0'] + GroupDatasets1=GroupDatasets(Input=[testMEDReader1,testMEDReader2]) + + Clip1 = Clip(ClipType="Plane",Input=GroupDatasets1) + Clip1.Scalars=['FamilyIdCell'] + Clip1.ClipType.Origin=[3.0, 3.0, 3.0] + Clip1.Invert=1 + Clip1.ClipType.Normal=[0.9255623174457069, 0.0027407477590518157, 0.378585373233375] + Clip1.Scalars=['CELLS'] + + DataRepresentation4 = Show() + DataRepresentation4.EdgeColor = [0.0, 0.0, 0.5000076295109483] + DataRepresentation4.SelectionCellFieldDataArrayName = 'ACellField' + DataRepresentation4.ScalarOpacityUnitDistance = 1.61104723630366 + DataRepresentation4.ExtractedBlockIndex = 2 + DataRepresentation4.ScaleFactor = 0.6000000000000001 + DataRepresentation4.Visibility = 1 + DataRepresentation4.Representation = 'Wireframe' + + ExtractBlock1 = ExtractBlock(Input=Clip1) + ExtractBlock1.BlockIndices=[1, 2] + + DataRepresentation5 = Show() + DataRepresentation5.EdgeColor = [0.0, 0.0, 0.5000076295109483] + DataRepresentation5.SelectionCellFieldDataArrayName = 'FamilyIdCell' + DataRepresentation5.ScaleFactor = 0.6 + a2_ACellField_PVLookupTable=GetLookupTableForArray( "ACellField", 2, RGBPoints=[10.63014581273465, 0.23, 0.299, 0.754, 15.0, 0.706, 0.016, 0.15], VectorMode='Magnitude', NanColor=[0.25, 0.0, 0.0], ColorSpace='Diverging', ScalarRangeInitialized=1.0, AllowDuplicateScalars=1 ) + a2_ACellField_PiecewiseFunction=CreatePiecewiseFunction( Points=[0.0, 0.0, 0.5, 0.0, 1.0, 1.0, 0.5, 0.0] ) + a2_ACellField_PVLookupTable.ScalarOpacityFunction = a2_ACellField_PiecewiseFunction + DataRepresentation5.ScalarOpacityFunction = a2_ACellField_PiecewiseFunction + DataRepresentation5.LookupTable = a2_ACellField_PVLookupTable + DataRepresentation5.ColorArrayName = ("CELLS", "ACellField") + + if '-D' not in sys.argv: + RenderView1 = GetRenderView() + RenderView1.CenterOfRotation = [3.0, 3.0, 3.0] + RenderView1.CameraViewUp = [-0.03886073885859842, 0.48373409998193495, 0.8743518533691291] + RenderView1.CameraPosition = [7.351939549758929, -5.688193007926853, 8.000155023042788] + RenderView1.CameraFocalPoint = [2.9999999999999996, 2.9999999999999987, 2.9999999999999982] + + RenderView1.ViewSize =[300,300] + Render() + + #WriteImage(outImgName) + + # compare with baseline image + import vtk.test.Testing + from vtk.util.misc import vtkGetTempDir + vtk.test.Testing.VTK_TEMP_DIR = vtk.util.misc.vtkGetTempDir() + vtk.test.Testing.compareImage(GetActiveView().GetRenderWindow(), baseline_file, + threshold=1) + vtk.test.Testing.interact() + +if __name__ == "__main__": + outImgName="testMEDReader2.png" + baseline_file = RetriveBaseLine(outImgName) + test(baseline_file) + pass diff --git a/src/Plugins/MEDReader/plugin/Test/testMEDReader20.py b/src/Plugins/MEDReader/plugin/Test/testMEDReader20.py new file mode 100644 index 00000000..b8447ce1 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/Test/testMEDReader20.py @@ -0,0 +1,162 @@ +# -*- coding: iso-8859-1 -*- +# Copyright (C) 2016-2019 CEA/DEN, EDF R&D +# +# This library 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. +# +# 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 +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +# +# Author : Anthony Geay (EDF R&D) + +# non regression test that emulates https://ageay@git.salome-platform.org/gitpub/samples/datafiles.git Med/ResOK_0000.med +# This test point error during commit efd9331a9455785d0f04b75 in PARAVIS +# Commit of the correction : a4e89b15c2faff6341ab9c3d78abc in PARAVIS +# Due to mistake in MEDReader, the family field array on nodes was deleted twice when changing time step + +import os +import sys + +from medcoupling import * +from paraview.simple import * +from MEDReaderHelper import WriteInTmpDir,RetriveBaseLine + +#### disable automatic camera reset on 'Show' +paraview.simple._DisableFirstRenderCameraReset() + +def GenerateCase(): + fname="testMEDReader20.med" + nb=10 + arrX=DataArrayDouble(nb+1) ; arrX.iota() + arrY=DataArrayDouble([0.,1.]) + m=MEDCouplingCMesh() ; m.setCoords(arrX,arrY) ; m=m.buildUnstructured(); m.setName("mesh") ; m.simplexize(0) + mm=MEDFileUMesh() ; mm[0]=m + m1=m.computeSkin() ; mm[-1]=m1 + # + f0=DataArrayInt(m1.getNumberOfCells()) ; f0.iota() ; mm.setFamilyFieldArr(-1,f0) + f1=DataArrayInt(m1.getNumberOfNodes()) ; f1.iota() ; mm.setFamilyFieldArr(1,f1) # <- very important the bug can be shown here + # + nbCells=m1.getNumberOfCells() ; nbNodes=m.getNumberOfNodes() + mm.write(fname,2) + for i in range(5): + f=MEDCouplingFieldDouble(ON_CELLS) ; f.setMesh(m) + f.setName("Field") + arr=DataArrayInt(2*nb) ; arr.iota(i) ; arr%=nb ; arr=arr.convertToDblArr() + f.setArray(arr) ; f.setTime(float(i),i,0) + WriteFieldUsingAlreadyWrittenMesh(fname,f) + # + f=MEDCouplingFieldDouble(ON_CELLS) ; f.setMesh(m1) + f.setName("Field") + arr=DataArrayInt(nbCells) ; arr.iota(i) ; arr%=nbCells ; arr=arr.convertToDblArr() + f.setArray(arr) ; f.setTime(float(i),i,0) + WriteFieldUsingAlreadyWrittenMesh(fname,f) + # + f=MEDCouplingFieldDouble(ON_NODES) ; f.setMesh(m) + f.setName("FieldNode") + arr=DataArrayDouble(nbNodes) ; arr[:]=float(i) + f.setArray(arr) ; f.setTime(float(i),i,0) + WriteFieldUsingAlreadyWrittenMesh(fname,f) + pass + return fname + +@WriteInTmpDir +def test(baseline_file): + fname = GenerateCase() + ##################### + # create a new 'MED Reader' + testMEDReader20med = MEDReader(FileName=fname) + testMEDReader20med.AllArrays = ['TS0/mesh/ComSup0/Field@@][@@P0'] + testMEDReader20med.AllTimeSteps = ['0000', '0001', '0002', '0003', '0004'] + + # get animation scene + animationScene1 = GetAnimationScene() + + # update animation scene based on data timesteps + animationScene1.UpdateAnimationUsingDataTimeSteps() + + if '-D' not in sys.argv: + # get active view + renderView1 = GetActiveViewOrCreate('RenderView') + # uncomment following to set a specific view size + # renderView1.ViewSize = [610, 477] + + # show data in view + testMEDReader20medDisplay = Show(testMEDReader20med, renderView1) + # trace defaults for the display properties. + testMEDReader20medDisplay.ColorArrayName = [None, ''] + testMEDReader20medDisplay.GlyphType = 'Arrow' + testMEDReader20medDisplay.ScalarOpacityUnitDistance = 4.664739046219201 + + # reset view to fit data + renderView1.ResetCamera() + + #changing interaction mode based on data extents + renderView1.InteractionMode = '2D' + renderView1.CameraPosition = [5.0, 0.5, 10000.0] + renderView1.CameraFocalPoint = [5.0, 0.5, 0.0] + + # set scalar coloring + ColorBy(testMEDReader20medDisplay, ('CELLS', 'Field')) + + # rescale color and/or opacity maps used to include current data range + testMEDReader20medDisplay.RescaleTransferFunctionToDataRange(True) + + # do not show color bar/color legend + testMEDReader20medDisplay.SetScalarBarVisibility(renderView1, False) + + # get color transfer function/color map for 'Field' + fieldLUT = GetColorTransferFunction('Field') + + # get opacity transfer function/opacity map for 'Field' + fieldPWF = GetOpacityTransferFunction('Field') + + animationScene1.GoToNext() # <- very important to see the bug play with time steps... + animationScene1.GoToNext() + animationScene1.GoToNext() + animationScene1.GoToNext() + animationScene1.GoToPrevious() + animationScene1.GoToPrevious() + + # current camera placement for renderView1 + renderView1.InteractionMode = '2D' + renderView1.CameraPosition = [5.0, 0.5, 10000.0] + renderView1.CameraFocalPoint = [5.0, 0.5, 0.0] + renderView1.CameraParallelScale = 5.024937810560445 + + # + + renderView1.ViewSize =[300,300] + Render() + #WriteImage(png) + + #### saving camera placements for all active views + + # current camera placement for renderView1 + renderView1.InteractionMode = '2D' + renderView1.CameraPosition = [5.0, 0.5, 10000.0] + renderView1.CameraFocalPoint = [5.0, 0.5, 0.0] + renderView1.CameraParallelScale = 5.024937810560445 + + # compare with baseline image + import vtk.test.Testing + from vtk.util.misc import vtkGetTempDir + vtk.test.Testing.VTK_TEMP_DIR = vtk.util.misc.vtkGetTempDir() + vtk.test.Testing.compareImage(GetActiveView().GetRenderWindow(), baseline_file, threshold=1) + vtk.test.Testing.interact() + pass + +if __name__ == "__main__": + outImgName="testMEDReader20.png" + baseline_file = RetriveBaseLine(outImgName) + test(baseline_file) + pass diff --git a/src/Plugins/MEDReader/plugin/Test/testMEDReader21.py b/src/Plugins/MEDReader/plugin/Test/testMEDReader21.py new file mode 100644 index 00000000..133fee3d --- /dev/null +++ b/src/Plugins/MEDReader/plugin/Test/testMEDReader21.py @@ -0,0 +1,171 @@ +# -*- coding: iso-8859-1 -*- +# Copyright (C) 2015-2019 CEA/DEN, EDF R&D +# +# This library 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. +# +# 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 +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +# +# Author : Anthony Geay (EDF R&D) + +import os +import sys + +from medcoupling import * +from paraview.simple import * +from MEDReaderHelper import WriteInTmpDir,RetriveBaseLine + +def GenerateCase(): + """ This is a non regression EDF12599""" + fname="testMEDReader21.med" + fieldName="MyField" + meshName="mesh" + m=MEDFileUMesh() + m0=MEDCouplingUMesh(meshName,1) + m0.setCoords(DataArrayDouble([(0.,0.,0),(1.,0.,0.),(2.,0.,0.)])) + m0.allocateCells() + m0.insertNextCell(NORM_SEG2,[0,1]) + m0.insertNextCell(NORM_SEG2,[1,2]) + m[0]=m0 + # + f=MEDCouplingFieldDouble(ON_GAUSS_NE) ; f.setName(fieldName) + f.setMesh(m0) ; f.setArray(DataArrayDouble([1.,7.,3.,2.])) + WriteField(fname,f,True) + return fname, meshName, fieldName + +@WriteInTmpDir +def test(baseline_file): + fname, meshName, fieldName = GenerateCase() + ######## + testTotomed = MEDReader(FileName=fname) + testTotomed.AllArrays = ['TS0/%s/ComSup0/%s@@][@@GSSNE'%(meshName,fieldName)] + testTotomed.AllTimeSteps = ['0000'] + + if '-D' not in sys.argv: + # get active view + renderView1 = GetActiveViewOrCreate('RenderView') + # uncomment following to set a specific view size + # renderView1.ViewSize = [739, 503] + + # show data in view + testTotomedDisplay = Show(testTotomed, renderView1) + # trace defaults for the display properties. + testTotomedDisplay.ColorArrayName = [None, ''] + testTotomedDisplay.GlyphType = 'Arrow' + testTotomedDisplay.ScalarOpacityUnitDistance = 1.5874010519681994 + + # reset view to fit data + renderView1.ResetCamera() + + #changing interaction mode based on data extents + renderView1.InteractionMode = '2D' + renderView1.CameraPosition = [1.0, 10000.0, 10000.0] + renderView1.CameraFocalPoint = [1.0, 0.0, 0.0] + renderView1.CameraViewUp = [1.0, 1.0, 0.0] + + # set scalar coloring + ColorBy(testTotomedDisplay, ('FIELD', 'vtkBlockColors')) + + # hide color bar/color legend + testTotomedDisplay.SetScalarBarVisibility(renderView1, False) + + # get color transfer function/color map for 'vtkBlockColors' + vtkBlockColorsLUT = GetColorTransferFunction('vtkBlockColors') + + # get opacity transfer function/opacity map for 'vtkBlockColors' + vtkBlockColorsPWF = GetOpacityTransferFunction('vtkBlockColors') + + # create a new 'ELNO Mesh' + eLNOMesh1 = ELNOfieldToSurface(Input=testTotomed) + + # Properties modified on eLNOMesh1 + eLNOMesh1.ShrinkFactor = 0.5 # <- test is here !!!!!!!! + + # show data in view + eLNOMesh1Display = Show(eLNOMesh1, renderView1) + # trace defaults for the display properties. + eLNOMesh1Display.ColorArrayName = [None, ''] + eLNOMesh1Display.GlyphType = 'Arrow' + eLNOMesh1Display.ScalarOpacityUnitDistance = 1.1905507889761495 + + # hide data in view + Hide(testTotomed, renderView1) + + # set scalar coloring + ColorBy(eLNOMesh1Display, ('FIELD', 'vtkBlockColors')) + + # show color bar/color legend + eLNOMesh1Display.SetScalarBarVisibility(renderView1, False) + + # set scalar coloring + ColorBy(eLNOMesh1Display, ('POINTS', 'MyField')) + + # rescale color and/or opacity maps used to include current data range + eLNOMesh1Display.RescaleTransferFunctionToDataRange(True) + + # show color bar/color legend + eLNOMesh1Display.SetScalarBarVisibility(renderView1, False) + + # get color transfer function/color map for 'MyField' + myFieldLUT = GetColorTransferFunction('MyField') + + # get opacity transfer function/opacity map for 'MyField' + myFieldPWF = GetOpacityTransferFunction('MyField') + + # hide color bar/color legend + eLNOMesh1Display.SetScalarBarVisibility(renderView1, False) + + # create a new 'Glyph' + glyph1 = Glyph(Input=eLNOMesh1, + GlyphType='Arrow') + glyph1.ScaleArray = [] + glyph1.OrientationArray = ['POINTS', 'No orientation array'] + glyph1.ScaleFactor = 0.15000000000000002 + glyph1.GlyphTransform = 'Transform2' + + # Properties modified on glyph1 + glyph1.GlyphType = 'Sphere' + glyph1.ScaleFactor = 0.15 + + # show data in view + glyph1Display = Show(glyph1, renderView1) + # trace defaults for the display properties. + glyph1Display.ColorArrayName = ['POINTS', 'MyField'] + glyph1Display.LookupTable = myFieldLUT + glyph1Display.GlyphType = 'Arrow' + + # hide color bar/color legend + glyph1Display.SetScalarBarVisibility(renderView1, False) + + #### saving camera placements for all active views + + # current camera placement for renderView1 + renderView1.InteractionMode = '2D' + renderView1.CameraPosition = [0.9999999999999908, 9999.999999999995, 9999.999999999993] + renderView1.CameraFocalPoint = [1.0, 0.0, 0.0] + renderView1.CameraViewUp = [0.6331899945158901, 0.547298104713038, -0.5472981047130381] + renderView1.CameraParallelScale = 0.6930835077290218 + renderView1.ViewSize = [739,503] + + import vtk.test.Testing + from vtk.util.misc import vtkGetTempDir + vtk.test.Testing.VTK_TEMP_DIR = vtk.util.misc.vtkGetTempDir() + vtk.test.Testing.compareImage(GetActiveView().GetRenderWindow(), baseline_file, threshold=1) + vtk.test.Testing.interact() + +if __name__ == "__main__": + imgName="testMEDReader21.png" + baseline_file = RetriveBaseLine(imgName) + test(baseline_file) + pass diff --git a/src/Plugins/MEDReader/plugin/Test/testMEDReader3.py b/src/Plugins/MEDReader/plugin/Test/testMEDReader3.py new file mode 100644 index 00000000..a3ffac6e --- /dev/null +++ b/src/Plugins/MEDReader/plugin/Test/testMEDReader3.py @@ -0,0 +1,148 @@ +# -*- coding: iso-8859-1 -*- +# Copyright (C) 2007-2019 CEA/DEN, EDF R&D +# +# This library 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. +# +# 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 +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +# +# Author : Anthony Geay + +import os +import sys + +from medcoupling import * +from paraview.simple import * +from MEDReaderHelper import WriteInTmpDir,RetriveBaseLine + +outImgName="testMEDReader3.png" + +def GenerateCase(): + """ This test checks that invalid double time (not in [-1e299:1e299]) + leads MEDReader to takes iteration numbers instead of double time to discriminate timesteps each other + See EDF 1956. + """ + fname="testMEDReader3.med" + ######### + m=MEDCouplingUMesh("mesh",2) + coords=DataArrayDouble([(0.,0.,0.),(1.,0.,0.),(1.,1.,0.),(0.,1.,0.)],4,3) + m.setCoords(coords) + m.allocateCells() + m.insertNextCell(NORM_QUAD4,[0,3,2,1]) + mm=MEDFileUMesh() + mm.setMeshAtLevel(0,m) + mm.write(fname,2) + fmts=MEDFileFieldMultiTS() + # + f=MEDCouplingFieldDouble(ON_NODES) ; f.setName("ANodeField") + f.setTime(1.7976931348623157e+308,1,1) ; f.setMesh(m) + arr=DataArrayDouble([0.,4.,4.,4.]) ; arr.setInfoOnComponent(0,"aaa") + f.setArray(arr) + f1ts=MEDFileField1TS() + f1ts.setFieldNoProfileSBT(f) + fmts.pushBackTimeStep(f1ts) + # + f.setTime(1.7976931348623157e+308,2,2) + arr=DataArrayDouble([1.,4.,4.,4.]) ; arr.setInfoOnComponent(0,"aaa") + f.setArray(arr) + f1ts=MEDFileField1TS() + f1ts.setFieldNoProfileSBT(f) + fmts.pushBackTimeStep(f1ts) + # + f.setTime(1.7976931348623157e+308,3,3) + arr=DataArrayDouble([2.,4.,4.,4.]) ; arr.setInfoOnComponent(0,"aaa") + f.setArray(arr) + f1ts=MEDFileField1TS() + f1ts.setFieldNoProfileSBT(f) + fmts.pushBackTimeStep(f1ts) + # + f.setTime(1.7976931348623157e+308,4,6) + arr=DataArrayDouble([3.,4.,4.,4.]) ; arr.setInfoOnComponent(0,"aaa") + f.setArray(arr) + f1ts=MEDFileField1TS() + f1ts.setFieldNoProfileSBT(f) + fmts.pushBackTimeStep(f1ts) + # + f.setTime(1.7976931348623157e+308,5,7) + arr=DataArrayDouble([4.,4.,4.,4.]) ; arr.setInfoOnComponent(0,"aaa") + f.setArray(arr) + f1ts=MEDFileField1TS() + f1ts.setFieldNoProfileSBT(f) + fmts.pushBackTimeStep(f1ts) + # + fmts.write(fname,0) + return fname + +@WriteInTmpDir +def test(baseline_file): + fname = GenerateCase() + ################### MED write is done -> Go to MEDReader + AnimationScene1=GetAnimationScene() + AnimationScene1.PlayMode='Snap To TimeSteps' + AnimationScene1.EndTime = 2.0 + AnimationScene1.AnimationTime = 1.0 + AnimationScene1.StartTime = 1.0 + + testMEDReader3=MEDReader(FileName=fname) + testMEDReader3.AllArrays=['TS0/mesh/ComSup0/ANodeField@@][@@P1'] + + assert(list(testMEDReader3.TimestepValues)==[1.,2.,3.,4.,5.]) ## <- the test is here - double time steps are too big use dt. + + if '-D' not in sys.argv: + RenderView1=GetRenderView() + RenderView1.ViewTime=3.0 + RenderView1.CameraPosition=[0.5,0.5,5.7320508075688776] + RenderView1.ViewSize=[300,300] + + DataRepresentation2=Show() + DataRepresentation2.EdgeColor=[0.0, 0.0, 0.5000076295109483] + DataRepresentation2.SelectionPointFieldDataArrayName='ANodeField' + DataRepresentation2.SelectionCellFieldDataArrayName='FamilyIdCell' + DataRepresentation2.ScalarOpacityUnitDistance=1.4142135623730951 + DataRepresentation2.ExtractedBlockIndex=1 + DataRepresentation2.ScaleFactor=0.1 + + a1_ANodeField_PVLookupTable=GetLookupTableForArray("ANodeField",1,RGBPoints=[0.0,0.23,0.299,0.754,4.0,0.706,0.016,0.15],VectorMode='Magnitude',NanColor=[0.25,0.0,0.0], + ColorSpace='Diverging',ScalarRangeInitialized=1.0,AllowDuplicateScalars=1) + a1_ANodeField_PiecewiseFunction=CreatePiecewiseFunction(Points=[0.0,0.0,0.5,0.0,1.0,1.0,0.5,0.0]) + a1_ANodeField_PVLookupTable.ScalarOpacityFunction=a1_ANodeField_PiecewiseFunction + + DataRepresentation2.ScalarOpacityFunction=a1_ANodeField_PiecewiseFunction + DataRepresentation2.ColorArrayName='ANodeField' + DataRepresentation2.LookupTable=a1_ANodeField_PVLookupTable + + # Triangulate so rendring always the same with different gpu or graphic backend. + extSurf = ExtractSurface(Input=testMEDReader3) + triangulate = Triangulate(Input=extSurf) + Hide(testMEDReader3, RenderView1) + Show(triangulate, RenderView1) + triangulate1Display = GetDisplayProperties(triangulate, view=RenderView1) + ColorBy(triangulate1Display, ('POINTS', 'ANodeField')) + + Render() + ### + + # compare with baseline image + import vtk.test.Testing + from vtk.util.misc import vtkGetTempDir + vtk.test.Testing.VTK_TEMP_DIR = vtk.util.misc.vtkGetTempDir() + vtk.test.Testing.compareImage(GetActiveView().GetRenderWindow(), baseline_file, + threshold=1) + vtk.test.Testing.interact() + +if __name__ == "__main__": + outImgName="testMEDReader3.png" + baseline_file = RetriveBaseLine(outImgName) + test(baseline_file) + pass diff --git a/src/Plugins/MEDReader/plugin/Test/testMEDReader4.py b/src/Plugins/MEDReader/plugin/Test/testMEDReader4.py new file mode 100644 index 00000000..4253bb39 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/Test/testMEDReader4.py @@ -0,0 +1,118 @@ +# -*- coding: iso-8859-1 -*- +# Copyright (C) 2007-2019 CEA/DEN, EDF R&D +# +# This library 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. +# +# 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 +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +# +# Author : Anthony Geay + +import os +import sys + +from medcoupling import * +from paraview.simple import * +from MEDReaderHelper import WriteInTmpDir,RetriveBaseLine + +def GenerateCase(): + """ This test checks that umeshes with no names work properly. + """ + + fname="testMEDReader4.med" + ######### + coords=DataArrayDouble([(0.,0.,0.),(1.,0.,0.),(2.,0.,0.),(3.,0.,0.),(0.,1.,0.),(1.,1.,0.),(2.,1.,0.),(3.,1.,0.),(0.,2.,0.),(1.,2.,0.),(2.,2.,0.),(3.,2.,0.),(0.,3.,0.),(1.,3.,0.),(2.,3.,0.),(3.,3.,0.)]) + m0=MEDCouplingUMesh("mesh",2) + m0.allocateCells() + m0.setCoords(coords) + ## + mm=MEDFileUMesh() + mm.setMeshAtLevel(0,m0) + mm.setFamilyFieldArr(1,DataArrayInt([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])) + # + f1ts0=MEDFileField1TS() + f1ts1=MEDFileField1TS() + # + f0=MEDCouplingFieldDouble(ON_NODES) ; f0.setMesh(m0) ; f0.setName("f0NoPfl") + arr0=DataArrayDouble([0.,1.,2.,3.,1.,1.5,2.2,3.1,2.,2.2,3.,3.1,3.,3.1,3.5,4.]) + f0.setArray(arr0) + f0.checkConsistencyLight() + f1ts0.setFieldNoProfileSBT(f0) + # + pfl1=DataArrayInt([0,1,2,3,4,5,6,8,9,12]) ; pfl1.setName("pfl1") + f1=MEDCouplingFieldDouble(ON_NODES) ; f1.setName("f1Pfl") + arr1=DataArrayDouble([3.,2.,1.,0.,2.,1.5,0.,1.,0.,0.2]) + f1.setArray(arr1) + f1ts1.setFieldProfile(f1,mm,0,pfl1) + # + fs=MEDFileFields() + fmts0=MEDFileFieldMultiTS() + fmts0.pushBackTimeStep(f1ts0) + fmts1=MEDFileFieldMultiTS() + fmts1.pushBackTimeStep(f1ts1) + fs.pushField(fmts0) ; fs.pushField(fmts1) + mm.write(fname,2) + fs.write(fname,0) + return fname + +@WriteInTmpDir +def test(baseline_file): +################### MED write is done -> Go to MEDReader + fname = GenerateCase() + + testMEDReader4_med=MEDReader(FileName=fname) + + testMEDReader4_med.AllArrays=['TS0/mesh/ComSup0/f0NoPfl@@][@@P1','TS0/mesh/ComSup0/mesh@@][@@P1'] + #testMEDReader4_med.AllTimeSteps=['0000'] + + Glyph1=Glyph(Input=testMEDReader4_med,GlyphType='Sphere') + Glyph1.ScaleArray=['POINTS','No scale array']#f0NoPflN + Glyph1.ScaleFactor=0.3 + Glyph1.OrientationArray = ['POINTS', 'No orientation array'] + Glyph1.GlyphTransform="Transform2" + Glyph1.GlyphMode = 'All Points' + + DataRepresentation1 = Show() + DataRepresentation1.EdgeColor = [0.0, 0.0, 0.5000076295109483] + DataRepresentation1.SelectionPointFieldDataArrayName = 'f0NoPfl' + DataRepresentation1.ScaleFactor = 0.3 + DataRepresentation1.ColorArrayName = 'f0NoPfl' + lookupTable = GetLookupTableForArray( "f0NoPfl", 1, RGBPoints=[0.0, 0.23, 0.299, 0.754, 4.0, 0.706, 0.016, 0.15], VectorMode='Magnitude', NanColor=[0.25, 0.0, 0.0], ColorSpace='Diverging', ScalarRangeInitialized=1.0, AllowDuplicateScalars=1 ) + function=CreatePiecewiseFunction(Points=[0.0,0.0,0.5,0.0,1.0,1.0,0.5,0.0] ) + lookupTable.ScalarOpacityFunction = function + DataRepresentation1.LookupTable = lookupTable + + if '-D' not in sys.argv: + RenderView1 = GetRenderView() + RenderView1.CameraViewUp = [0.06254683966704512, 0.9980420295997885, 0.0] + RenderView1.CameraPosition = [0.8087292125440382, 1.3325993334207897, 12.692130429902462] + RenderView1.CameraFocalPoint = [0.8087292125440382, 1.3325993334207897, 0.0] + RenderView1.CameraParallelScale = 3.712804729456109 + + RenderView1.ViewSize =[300,300] + Render() + + # compare with baseline image + import vtk.test.Testing + from vtk.util.misc import vtkGetTempDir + vtk.test.Testing.VTK_TEMP_DIR = vtk.util.misc.vtkGetTempDir() + vtk.test.Testing.compareImage(GetActiveView().GetRenderWindow(), baseline_file, + threshold=1) + vtk.test.Testing.interact() + +if __name__ == "__main__": + outImgName="testMEDReader4.png" + baseline_file = RetriveBaseLine(outImgName) + test(baseline_file) + pass diff --git a/src/Plugins/MEDReader/plugin/Test/testMEDReader5.py b/src/Plugins/MEDReader/plugin/Test/testMEDReader5.py new file mode 100644 index 00000000..f278a8e2 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/Test/testMEDReader5.py @@ -0,0 +1,134 @@ +# -*- coding: iso-8859-1 -*- +# Copyright (C) 2007-2019 CEA/DEN, EDF R&D +# +# This library 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. +# +# 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 +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +# +# Author : Anthony Geay + +import os +import sys + +from medcoupling import * +from paraview.simple import * +from MEDReaderHelper import WriteInTmpDir,RetriveBaseLine + +def GenerateCase(): + """ This test is CEA specific one. It generates a .sauv file + that is then read by MEDReader + """ + fname="testMEDReader5.sauv" + ######### + arr=DataArrayDouble(5) ; arr.iota() + c=MEDCouplingCMesh("mesh") + c.setCoords(arr,arr,arr) + m=c.buildUnstructured() + mbis=m.deepCopy() ; mbis.translate([5,0,0]) ; mbis.tetrahedrize(PLANAR_FACE_5) + m=MEDCouplingUMesh.MergeUMeshes([mbis,m]) ; m.setName(c.getName()) + mm=MEDFileUMesh() + mm.setMeshAtLevel(0,m) + grp0=DataArrayInt.Range(0,m.getNumberOfCells(),2) ; grp0.setName("grp0") + grp1=DataArrayInt.Range(1,m.getNumberOfCells(),2) ; grp1.setName("grp1") + grp2=DataArrayInt.Range(0,m.getNumberOfNodes(),7) ; grp2.setName("grp2") + mm.setGroupsAtLevel(0,[grp0,grp1]) + mm.setGroupsAtLevel(1,[grp2]) + ms=MEDFileMeshes() + ms.pushMesh(mm) + f=MEDCouplingFieldDouble(ON_CELLS) ; f.setName("fCell") ; f.setMesh(m[:10]) + arr=DataArrayDouble(f.getNumberOfTuplesExpected()) ; arr.iota() ; f.setArray(arr) + f2=MEDCouplingFieldDouble(ON_NODES) ; f2.setName("fNode") ; f2.setMesh(m) + arr=DataArrayDouble(f2.getNumberOfTuplesExpected()) ; arr.iota() ; f2.setArray(arr) + + fs=MEDFileFields() + f1ts=MEDFileField1TS() + #f1ts.setFieldNoProfileSBT(f) + pfl=DataArrayInt(10); pfl.iota() ; pfl.setName("pfl") ; f1ts.setFieldProfile(f,mm,0,pfl) + fmts=MEDFileFieldMultiTS() + fmts.pushBackTimeStep(f1ts) + fs.pushField(fmts) + f1ts=MEDFileField1TS() + f1ts.setFieldNoProfileSBT(f2) + fmts=MEDFileFieldMultiTS() + fmts.pushBackTimeStep(f1ts) + fs.pushField(fmts) + + mfd=MEDFileData() + mfd.setMeshes(ms) + mfd.setFields(fs) + #mfd.write(fname,2) not activated because useless + # + sw=SauvWriter(); + sw.setMEDFileDS(mfd); + sw.write(fname); + del mm,m,c,f,arr + del f1ts + return fname + + +@WriteInTmpDir +def test(baseline_file): + fname = GenerateCase() + ################### MED write is done -> Go to MEDReader + myMedReader=MEDReader(FileName=fname) + myMedReader.AllArrays = ['TS0/mesh/ComSup1/fNode@@][@@P1'] + myMedReader.AllTimeSteps = ['0000'] + + Clip1=Clip(ClipType="Plane",Input=myMedReader) + Clip1.Scalars = ['POINTS', 'FamilyIdNode'] + Clip1.ClipType.Origin = [2.0, 2.0, 2.0] + Clip1.ClipType = "Plane" + Clip1.ClipType.Normal = [0.04207410474474753, 0.9319448861971525, 0.3601506612529047] + Clip1.Invert = 1 + + DataRepresentation2 = Show() + DataRepresentation2.EdgeColor = [0.0, 0.0, 0.5000076295109483] + DataRepresentation2.ScalarOpacityUnitDistance = 1.5768745057161244 + DataRepresentation2.ExtractedBlockIndex = 1 + DataRepresentation2.ScaleFactor = 0.4 + + if '-D' not in sys.argv: + RenderView1=GetRenderView() + RenderView1.CenterOfRotation=[2.,2.,2.] + RenderView1.CameraViewUp=[0.24562884954787187,0.6907950752417243,-0.680050463047831] + RenderView1.CameraPosition=[-2.5085697461776486,11.6185941755061,10.14210560568201] + RenderView1.CameraFocalPoint=[2.,2.,2.] + RenderView1.CameraParallelScale=5.071791174723188 + + LookupTable=GetLookupTableForArray("fNode",1,RGBPoints=[0.0,0.23,0.299,0.754,55.0,0.706,0.016,0.15],VectorMode='Magnitude',NanColor=[0.25,0.0,0.0],ColorSpace='Diverging',ScalarRangeInitialized=1.0,AllowDuplicateScalars=1) + DataRepresentation2 = Show() + DataRepresentation2.EdgeColor = [0.0, 0.0, 0.5000076295109483] + DataRepresentation2.ScalarOpacityUnitDistance = 1.5768745057161244 + DataRepresentation2.ExtractedBlockIndex = 1 + DataRepresentation2.ScaleFactor = 0.4 + DataRepresentation2.ColorArrayName=('POINTS','fNode') + DataRepresentation2.LookupTable=LookupTable + + RenderView1.ViewSize=[300,300] + Render() + + # compare with baseline image + import vtk.test.Testing + from vtk.util.misc import vtkGetTempDir + vtk.test.Testing.VTK_TEMP_DIR = vtk.util.misc.vtkGetTempDir() + vtk.test.Testing.compareImage(GetActiveView().GetRenderWindow(), baseline_file, + threshold=1) + vtk.test.Testing.interact() + +if __name__ == "__main__": + outImgName="testMEDReader5.png" + baseline_file = RetriveBaseLine(outImgName) + test(baseline_file) + pass diff --git a/src/Plugins/MEDReader/plugin/Test/testMEDReader6.py b/src/Plugins/MEDReader/plugin/Test/testMEDReader6.py new file mode 100644 index 00000000..159121f4 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/Test/testMEDReader6.py @@ -0,0 +1,119 @@ +# -*- coding: iso-8859-1 -*- +# Copyright (C) 2007-2019 CEA/DEN, EDF R&D +# +# This library 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. +# +# 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 +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +# +# Author : Anthony Geay + +import os +import sys + +from medcoupling import * +from paraview.simple import * +from MEDReaderHelper import WriteInTmpDir,RetriveBaseLine + +def GenerateCase(): + """ This test generate a GaussPoint field on a mesh with groups. + The aim of this test is to check that the ExtractGroup works well for ELGAfieldToPointGaussian + """ + fname="testMEDReader6.med" + ######### + arr=DataArrayDouble([(0,0,0),(1,0,0),(2,0,0),(3,0,0),(0,1,0),(1,1,0),(2,1,0),(3,1,0),(0,2,0),(1,2,0),(2,2,0),(3,2,0),(0,3,0),(1,3,0),(2,3,0),(3,3,0)]) + m0=MEDCouplingUMesh("mesh",2) ; m0.setCoords(arr) ; m0.allocateCells() + for elt in [[2,3,6],[3,7,6],[6,9,5],[6,10,9]]: + m0.insertNextCell(NORM_TRI3,elt) + pass + for elt in [[0,4,5,1],[5,6,2,1],[4,8,9,5],[6,10,11,7],[8,12,13,9],[9,13,14,10],[10,14,15,11]]: + m0.insertNextCell(NORM_QUAD4,elt) + pass + mm=MEDFileUMesh() + mm.setMeshAtLevel(0,m0) + grp0=DataArrayInt([0,1,4,5,7,10]) ; grp0.setName("grp0") + mm.setGroupsAtLevel(0,[grp0]) + # + fGauss=MEDCouplingFieldDouble(ON_GAUSS_PT) ; fGauss.setName("fGauss") + fGauss.setMesh(m0) + fGauss.setGaussLocalizationOnType(NORM_TRI3,[0.,0.,1.,0.,0.,1.],[0.1,0.1,0.05,0.9],[0.4,0.6]) + fGauss.setGaussLocalizationOnType(NORM_QUAD4,[-1.,-1.,1.,-1.,1.,1.,-1.,1.],[-0.9,-0.9,0.,0.,0.9,0.9],[0.2,0.3,0.5]) + fGauss.setArray(DataArrayDouble([0.9,1.3,0.22,1.3,1.62,2.21,1.62,2.72,2.95,2.54,2.25,2.16,1.58,1.05,3.13,2.91,2.82,1.41,1.58,1.95,3.59,3.53,3.59,2.82,2.91,3.13,2.25,2.54,2.95])) + fGauss.getArray().setInfoOnComponent(0,"C0") + fGauss.checkConsistencyLight() + # + f1ts=MEDFileField1TS() + f1ts.setFieldNoProfileSBT(fGauss) + # + mm.write(fname,2) + f1ts.write(fname,0) + return fname + +@WriteInTmpDir +def test(baseline_file): + fname = GenerateCase() + ################### MED write is done -> Go to MEDReader + + myMedReader=MEDReader(FileName=fname) + myMedReader.AllArrays = ['TS0/mesh/ComSup0/fGauss@@][@@GAUSS'] + myMedReader.AllTimeSteps = ['0000'] + + ExtractGroup1 = ExtractGroup(Input=myMedReader) + ExtractGroup1.UpdatePipelineInformation() + ExtractGroup1.AllGroups = ['GRP_grp0'] + + ELGAfieldToPointGaussian1 = ELGAfieldToPointGaussian(Input=ExtractGroup1) + ELGAfieldToPointGaussian1.SelectSourceArray = ['CELLS','ELGA@0'] + + Glyph1 = Glyph( Input=ELGAfieldToPointGaussian1, GlyphType="Sphere", GlyphTransform="Transform2" ) + Glyph1.GlyphType = "Sphere" + Glyph1.OrientationArray = ['POINTS', 'No orientation array'] + Glyph1.ScaleFactor = 0.29 + + if '-D' not in sys.argv: + RenderView1 = GetRenderView() + RenderView1.CameraFocalPoint = [1.5, 1.5, 0.0] + RenderView1.CameraPosition = [1.5, 1.5, 10000.0] + RenderView1.InteractionMode = '3D' + RenderView1.CameraPosition = [1.5, 1.5, 8.196152422706632] + RenderView1.CameraParallelScale = 2.1213203435596424 + RenderView1.CenterOfRotation = [1.5, 1.5, 0.0] + + DataRepresentation4 = Show() + DataRepresentation4.EdgeColor = [0.0, 0.0, 0.5000076295109483] + DataRepresentation4.SelectionPointFieldDataArrayName = 'fGauss' + DataRepresentation4.ScaleFactor = 0.3182729169726372 + + a1_fGauss_PVLookupTable = GetLookupTableForArray( "fGauss", 1, RGBPoints=[0.22, 0.23, 0.299, 0.754, 2.95, 0.706, 0.016, 0.15], VectorMode='Magnitude', NanColor=[0.25, 0.0, 0.0], ColorSpace='Diverging', ScalarRangeInitialized=1.0, AllowDuplicateScalars=1 ) + a1_fGauss_PiecewiseFunction = CreatePiecewiseFunction( Points=[0.0, 0.0, 0.5, 0.0, 1.0, 1.0, 0.5, 0.0] ) + DataRepresentation4.ColorArrayName = 'fGauss' + DataRepresentation4.LookupTable = a1_fGauss_PVLookupTable + a1_fGauss_PVLookupTable.ScalarOpacityFunction = a1_fGauss_PiecewiseFunction + + RenderView1.ViewSize=[300,300] + Render() + + # compare with baseline image + import vtk.test.Testing + from vtk.util.misc import vtkGetTempDir + vtk.test.Testing.VTK_TEMP_DIR = vtk.util.misc.vtkGetTempDir() + vtk.test.Testing.compareImage(GetActiveView().GetRenderWindow(), baseline_file, + threshold=1) + vtk.test.Testing.interact() + +if __name__ == "__main__": + outImgName="testMEDReader6.png" + baseline_file = RetriveBaseLine(outImgName) + test(baseline_file) + pass diff --git a/src/Plugins/MEDReader/plugin/Test/testMEDReader7.py b/src/Plugins/MEDReader/plugin/Test/testMEDReader7.py new file mode 100644 index 00000000..d7f40b13 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/Test/testMEDReader7.py @@ -0,0 +1,120 @@ +# -*- coding: iso-8859-1 -*- +# Copyright (C) 2007-2019 CEA/DEN, EDF R&D +# +# This library 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. +# +# 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 +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +# +# Author : Anthony Geay + +import os +import sys + + +from medcoupling import * +from paraview.simple import * +from MEDReaderHelper import WriteInTmpDir,RetriveBaseLine + +def GenerateCase(): + """ This test generate a simple multi time field with a very aggressive time steps triplets. Neither dt, nor iteration nor order is considered. + In this case only the rank is considered. + """ + fname="testMEDReader7.med" + ######### + arr=DataArrayDouble([(0,0,0),(1,0,0),(2,0,0),(3,0,0),(0,1,0),(1,1,0),(2,1,0),(3,1,0),(0,2,0),(1,2,0),(2,2,0),(3,2,0),(0,3,0),(1,3,0),(2,3,0),(3,3,0)]) + m0=MEDCouplingUMesh("mesh",2) ; m0.setCoords(arr) ; m0.allocateCells() + for elt in [[2,3,6],[3,7,6],[6,9,5],[6,10,9]]: + m0.insertNextCell(NORM_TRI3,elt) + pass + for elt in [[0,4,5,1],[5,6,2,1],[4,8,9,5],[6,10,11,7],[8,12,13,9],[9,13,14,10],[10,14,15,11]]: + m0.insertNextCell(NORM_QUAD4,elt) + pass + mm=MEDFileUMesh() + mm.setMeshAtLevel(0,m0) + grp0=DataArrayInt([0,1,4,5,7,10]) ; grp0.setName("grp0") + mm.setGroupsAtLevel(0,[grp0]) + fmts=MEDFileFieldMultiTS() + # + fNode=MEDCouplingFieldDouble(ON_NODES) ; fNode.setName("fNode") + fNode.setMesh(m0) + fNode.setArray(DataArrayDouble([3,2,1,0,3.16,2.23,1.41,1,3.6,2.82,2.23,2,4.24,3.6,3.16,3])) + fNode.getArray().setInfoOnComponent(0,"C0") + fNode.setTime(0.5,1,1) + f1ts=MEDFileField1TS() ; f1ts.setFieldNoProfileSBT(fNode) ; fmts.pushBackTimeStep(f1ts) + # + fNode.getArray().reverse() + fNode.setTime(0.5,1,2) + f1ts=MEDFileField1TS() ; f1ts.setFieldNoProfileSBT(fNode) ; fmts.pushBackTimeStep(f1ts) + # + fNode.getArray().reverse() + fNode.setTime(0.5,2,1) + f1ts=MEDFileField1TS() ; f1ts.setFieldNoProfileSBT(fNode) ; fmts.pushBackTimeStep(f1ts) + # + fNode.getArray().reverse() + fNode.setTime(0.5,2,2) + f1ts=MEDFileField1TS() ; f1ts.setFieldNoProfileSBT(fNode) ; fmts.pushBackTimeStep(f1ts) + # + mm.write(fname,2) + fmts.write(fname,0) + return fname + + +@WriteInTmpDir +def test(baseline_file): + fname = GenerateCase() + ################### MED write is done -> Go to MEDReader + myMedReader=MEDReader(FileName=fname) + myMedReader.AllArrays = ['TS0/mesh/ComSup0/fNode@@][@@P1'] + assert(list(myMedReader.TimestepValues)==[0.,1.,2.,3.]) + + if '-D' not in sys.argv: + RenderView1 = GetRenderView() + RenderView1.CameraFocalPoint = [1.5, 1.5, 0.0] + RenderView1.CameraPosition = [1.5, 1.5, 10000.0] + RenderView1.InteractionMode = '3D' + RenderView1.CameraPosition = [1.5, 1.5, 8.196152422706632] + RenderView1.CameraParallelScale = 2.1213203435596424 + RenderView1.CenterOfRotation = [1.5, 1.5, 0.0] + + DataRepresentation4 = Show() + DataRepresentation4.EdgeColor = [0.0, 0.0, 0.5000076295109483] + DataRepresentation4.SelectionPointFieldDataArrayName = 'fNode' + DataRepresentation4.ScaleFactor = 0.3182729169726372 + + a1_fGauss_PVLookupTable = GetLookupTableForArray( "fNode", 1, RGBPoints=[0.22, 0.23, 0.299, 0.754, 2.95, 0.706, 0.016, 0.15], VectorMode='Magnitude', NanColor=[0.25, 0.0, 0.0], ColorSpace='Diverging', ScalarRangeInitialized=1.0, AllowDuplicateScalars=1 ) + a1_fGauss_PiecewiseFunction = CreatePiecewiseFunction( Points=[0.0, 0.0, 0.5, 0.0, 1.0, 1.0, 0.5, 0.0] ) + DataRepresentation4.ColorArrayName = 'fNode' + DataRepresentation4.LookupTable = a1_fGauss_PVLookupTable + a1_fGauss_PVLookupTable.ScalarOpacityFunction = a1_fGauss_PiecewiseFunction + + RenderView1.ViewTime = 1.0 #### Important # red is in right bottom + RenderView1.CacheKey = 1.0 + RenderView1.UseCache = 1 + RenderView1.ViewSize=[300,300] + Render() + + # compare with baseline image + import vtk.test.Testing + from vtk.util.misc import vtkGetTempDir + vtk.test.Testing.VTK_TEMP_DIR = vtk.util.misc.vtkGetTempDir() + vtk.test.Testing.compareImage(GetActiveView().GetRenderWindow(), baseline_file, + threshold=6) + vtk.test.Testing.interact() + +if __name__ == "__main__": + outImgName="testMEDReader7.png" + baseline_file = RetriveBaseLine(outImgName) + test(baseline_file) + pass diff --git a/src/Plugins/MEDReader/plugin/Test/testMEDReader8.py b/src/Plugins/MEDReader/plugin/Test/testMEDReader8.py new file mode 100644 index 00000000..85814275 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/Test/testMEDReader8.py @@ -0,0 +1,131 @@ +# -*- coding: iso-8859-1 -*- +# Copyright (C) 2007-2019 CEA/DEN, EDF R&D +# +# This library 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. +# +# 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 +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +# +# Author : Anthony Geay + +import os +import sys + +from medcoupling import * +from paraview.simple import * +from MEDReaderHelper import WriteInTmpDir,RetriveBaseLine + +def GenerateCase(): + """ This test is a non regression test. ExtractCellType then ExtractGroup. + """ + fname="testMEDReader8.med" + ######### + arr=DataArrayDouble([(0,0,0),(1,0,0),(2,0,0),(3,0,0),(0,1,0),(1,1,0),(2,1,0),(3,1,0),(0,2,0),(1,2,0),(2,2,0),(3,2,0),(0,3,0),(1,3,0),(2,3,0),(3,3,0)]) + m0=MEDCouplingUMesh("mesh",2) ; m0.setCoords(arr) ; m0.allocateCells() + for elt in [[2,3,6],[3,7,6],[6,9,5],[6,10,9]]: + m0.insertNextCell(NORM_TRI3,elt) + pass + for elt in [[0,4,5,1],[5,6,2,1],[4,8,9,5],[6,10,11,7],[8,12,13,9],[9,13,14,10],[10,14,15,11]]: + m0.insertNextCell(NORM_QUAD4,elt) + pass + mm=MEDFileUMesh() + mm.setMeshAtLevel(0,m0) + grp0=DataArrayInt([0,1,2,5]) ; grp0.setName("grp0") + mm.setGroupsAtLevel(0,[grp0]) + fmts=MEDFileFieldMultiTS() + # + fNode=MEDCouplingFieldDouble(ON_NODES) ; fNode.setName("fNode") + fNode.setMesh(m0) + fNode.setArray(DataArrayDouble([3,2,1,0,3.16,2.23,1.41,1,3.6,2.82,2.23,2,4.24,3.6,3.16,3])) + fNode.getArray().setInfoOnComponent(0,"C0") + fNode.setTime(0.5,1,1) + f1ts=MEDFileField1TS() ; f1ts.setFieldNoProfileSBT(fNode) ; fmts.pushBackTimeStep(f1ts) + # + fNode.getArray().reverse() + fNode.setTime(0.5,1,2) + f1ts=MEDFileField1TS() ; f1ts.setFieldNoProfileSBT(fNode) ; fmts.pushBackTimeStep(f1ts) + # + fNode.getArray().reverse() + fNode.setTime(0.5,2,1) + f1ts=MEDFileField1TS() ; f1ts.setFieldNoProfileSBT(fNode) ; fmts.pushBackTimeStep(f1ts) + # + fNode.getArray().reverse() + fNode.setTime(0.5,2,2) + f1ts=MEDFileField1TS() ; f1ts.setFieldNoProfileSBT(fNode) ; fmts.pushBackTimeStep(f1ts) + # + mm.write(fname,2) + fmts.write(fname,0) + return fname + + +@WriteInTmpDir +def test(baseline_file): + fname = GenerateCase() + ################### MED write is done -> Go to MEDReader + + myMedReader=MEDReader(FileName=fname) + myMedReader.AllArrays = ['TS0/mesh/ComSup0/fNode@@][@@P1'] + assert(list(myMedReader.TimestepValues)==[0.,1.,2.,3.]) + myMedReader.UpdatePipeline() + + extractCT=ExtractCellType(Input=myMedReader) + extractCT.UpdatePipelineInformation() + assert(list(extractCT.GetProperty("GeoTypesInfo"))==['TRI3','0','QUAD4','0']) + extractCT.AllGeoTypes=['TRI3'] + + extGrp=ExtractGroup(Input=extractCT) + #extGrp.UpdatePipelineInformation() + assert([x for x in list(extGrp.GetProperty("GroupsFlagsInfo")[::2]) if x[:4]=="GRP_"]==['GRP_grp0']) + extGrp.AllGroups="GRP_grp0" + + if '-D' not in sys.argv: + RenderView1 = GetRenderView() + RenderView1.CameraFocalPoint = [1.5, 1.5, 0.0] + RenderView1.CameraPosition = [1.5, 1.5, 10000.0] + RenderView1.InteractionMode = '3D' + RenderView1.CameraPosition = [1.5, 1.5, 8.196152422706632] + RenderView1.CameraParallelScale = 2.1213203435596424 + RenderView1.CenterOfRotation = [1.5, 1.5, 0.0] + + DataRepresentation4 = Show() + DataRepresentation4.EdgeColor = [0.0, 0.0, 0.5000076295109483] + DataRepresentation4.SelectionPointFieldDataArrayName = 'fNode' + DataRepresentation4.ScaleFactor = 0.3182729169726372 + + a1_fGauss_PVLookupTable = GetLookupTableForArray( "fNode", 1, RGBPoints=[0.22, 0.23, 0.299, 0.754, 2.95, 0.706, 0.016, 0.15], VectorMode='Magnitude', NanColor=[0.25, 0.0, 0.0], ColorSpace='Diverging', ScalarRangeInitialized=1.0, AllowDuplicateScalars=1 ) + a1_fGauss_PiecewiseFunction = CreatePiecewiseFunction( Points=[0.0, 0.0, 0.5, 0.0, 1.0, 1.0, 0.5, 0.0] ) + DataRepresentation4.ColorArrayName = 'fNode' + DataRepresentation4.LookupTable = a1_fGauss_PVLookupTable + a1_fGauss_PVLookupTable.ScalarOpacityFunction = a1_fGauss_PiecewiseFunction + + RenderView1.ViewTime = 1.0 #### Important # red is in right bottom + RenderView1.CacheKey = 1.0 + RenderView1.UseCache = 1 + RenderView1.ViewSize=[300,300] + Render() + + # compare with baseline image + + import vtk.test.Testing + from vtk.util.misc import vtkGetTempDir + vtk.test.Testing.VTK_TEMP_DIR = vtk.util.misc.vtkGetTempDir() + vtk.test.Testing.compareImage(GetActiveView().GetRenderWindow(), baseline_file, + threshold=1) + vtk.test.Testing.interact() + +if __name__ == "__main__": + outImgName="testMEDReader8.png" + baseline_file = RetriveBaseLine(outImgName) + test(baseline_file) + pass diff --git a/src/Plugins/MEDReader/plugin/Test/testMEDReader9.py b/src/Plugins/MEDReader/plugin/Test/testMEDReader9.py new file mode 100644 index 00000000..4945528f --- /dev/null +++ b/src/Plugins/MEDReader/plugin/Test/testMEDReader9.py @@ -0,0 +1,63 @@ +# -*- coding: iso-8859-1 -*- +# Copyright (C) 2007-2019 CEA/DEN, EDF R&D +# +# This library 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. +# +# 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 +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +# +# Author : Anthony Geay + +from medcoupling import * +from paraview.simple import * +from MEDReaderHelper import WriteInTmpDir,RetriveBaseLine + +def GenerateCase(): + """ This test is a non regression test. Test that ExtractGroup adapt to the current mesh of MEDReader. A MED file containing 2 fields on a 2 different meshes. + This test checks that the MeshName follows. + """ + fname="testMEDReader9.med" + ######### + m1=MEDCouplingUMesh("m1",2) ; m1.setCoords(DataArrayDouble([(0.,0.),(1.,0.),(0.,1.)])) ; m1.allocateCells() ; m1.insertNextCell(NORM_TRI3,[0,1,2]) + m2=MEDCouplingUMesh("m2",2) ; m2.setCoords(DataArrayDouble([(0.,0.),(1.,0.),(0.,1.),(1.,1.)])) ; m2.allocateCells() ; m2.insertNextCell(NORM_QUAD4,[0,1,3,2]) + mm1=MEDFileUMesh() ; mm2=MEDFileUMesh() + mm1.setMeshAtLevel(0,m1) ; mm2.setMeshAtLevel(0,m2) + ms=MEDFileMeshes() ; ms.pushMesh(mm1) ; ms.pushMesh(mm2) + f1=MEDCouplingFieldDouble(ON_CELLS) ; f1.setName("f1") ; f1.setMesh(m1) ; f1.setArray(DataArrayDouble([1.111])) + f2=MEDCouplingFieldDouble(ON_CELLS) ; f2.setName("f2") ; f2.setMesh(m2) ; f2.setArray(DataArrayDouble([2.2222])) + ff1=MEDFileField1TS() ; ff2=MEDFileField1TS() + ff1.setFieldNoProfileSBT(f1) ; ff2.setFieldNoProfileSBT(f2) + ms.write(fname,2) + ff1.write(fname,0) + ff2.write(fname,0) + return fname + +@WriteInTmpDir +def test(): + fname = GenerateCase() + ################### MED write is done -> Go to MEDReader + myMedReader=MEDReader(FileName=fname) + myMedReader.AllArrays=['TS0/m1/ComSup0/f1@@][@@P0'] + #myMedReader.UpdatePipelineInformation() + ExtractGroup1=ExtractGroup(Input=myMedReader) + #ExtractGroup1.UpdatePipelineInformation() + assert(ExtractGroup1.GetProperty("MeshName")[0]=="m1") + myMedReader.AllArrays=['TS0/m2/ComSup0/f2@@][@@P0'] + #myMedReader.UpdatePipeline() + ExtractGroup2=ExtractGroup(Input=myMedReader) + #ExtractGroup2.UpdatePipelineInformation() + assert(ExtractGroup2.GetProperty("MeshName")[0]=="m2") + +if __name__ == "__main__": + test() diff --git a/src/Plugins/MEDReader/plugin/paraview.plugin b/src/Plugins/MEDReader/plugin/paraview.plugin new file mode 100644 index 00000000..47bc39b7 --- /dev/null +++ b/src/Plugins/MEDReader/plugin/paraview.plugin @@ -0,0 +1,5 @@ +NAME + MEDReader +DESCRIPTION + Reads the MED data format from Electricite de France +REQUIRES_MODULES diff --git a/src/Plugins/MEDWriter/CMakeLists.txt b/src/Plugins/MEDWriter/CMakeLists.txt index 6b2af517..eee16d45 100644 --- a/src/Plugins/MEDWriter/CMakeLists.txt +++ b/src/Plugins/MEDWriter/CMakeLists.txt @@ -1,77 +1,30 @@ -# Copyright (C) 2016-2019 CEA/DEN, EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# -# Author : Anthony Geay (EDF R&D) - -PROJECT(MEDWriter) -CMAKE_MINIMUM_REQUIRED(VERSION 2.8) - -IF(COMMAND cmake_policy) - CMAKE_POLICY(SET CMP0003 NEW) - #CMAKE_POLICY(SET CMP0022 OLD) - #CMAKE_POLICY(SET CMP0023 OLD) -ENDIF(COMMAND cmake_policy) - -SET(MED_WRITER_VERSION "0.0.0") - -FIND_PACKAGE(ParaView REQUIRED) -IF(NOT ParaView_FOUND) - MESSAGE(FATAL_ERROR "Please locate ParaView." ) -ENDIF(NOT ParaView_FOUND) -INCLUDE(${PARAVIEW_USE_FILE}) - -OPTION(BUILD_SHARED_LIBS "Build with shared libraries." ${VTK_BUILD_SHARED_LIBS}) - -SET(VTK_INSTALL_RUNTIME_DIR lib/salome) -SET(VTK_INSTALL_LIBRARY_DIR lib/salome) -SET(VTK_INSTALL_ARCHIVE_DIR lib/salome) -SET(MEDWRITER_INSTALL_CMAKE_LOCAL adm_local/cmake_files CACHE PATH "Install path: local SALOME CMake files") -SET(MEDWRITER_INSTALL_HEADERS include/salome CACHE PATH "Install path: local include files") - - -SET(MEDCOUPLING_ROOT_DIR $ENV{MEDCOUPLING_ROOT_DIR} CACHE PATH "MEDCOUPLING_ROOT_DIR") -LIST(APPEND CMAKE_MODULE_PATH "${MEDCOUPLING_ROOT_DIR}/cmake_files") -INCLUDE(SalomeMacros) -FIND_PACKAGE(SalomeHDF5 REQUIRED) -FIND_PACKAGE(SalomeMEDCoupling REQUIRED) -FIND_PACKAGE(SalomeMEDFile REQUIRED) - -IF(MEDCOUPLING_USE_64BIT_IDS) - ADD_DEFINITIONS("-DMEDCOUPLING_USE_64BIT_IDS") -ENDIF(MEDCOUPLING_USE_64BIT_IDS) - -PV_PROCESS_MODULES() - -INCLUDE_DIRECTORIES( - ${MEDCOUPLING_INCLUDE_DIRS} - ${MEDFILE_INCLUDE_DIRS} - ${HDF5_INCLUDE_DIRS}) - -ADD_SUBDIRECTORY(IO) -ADD_SUBDIRECTORY(ParaViewPlugin) - -INCLUDE(CMakePackageConfigHelpers) - -SALOME_CONFIGURE_PREPARE(MEDCOUPLING MEDFILE HDF5) -CONFIGURE_PACKAGE_CONFIG_FILE(${PROJECT_NAME}Config.cmake.in - ${PROJECT_BINARY_DIR}/${PROJECT_NAME}Config.cmake - INSTALL_DESTINATION "${MEDWRITER_INSTALL_CMAKE_LOCAL}" - PATH_VARS CMAKE_INSTALL_PREFIX MEDWRITER_INSTALL_HEADERS) - -INSTALL(FILES "${PROJECT_BINARY_DIR}/${PROJECT_NAME}Config.cmake" DESTINATION "${MEDWRITER_INSTALL_CMAKE_LOCAL}") -INSTALL(EXPORT ${PROJECT_NAME}TargetGroup DESTINATION "${MEDWRITER_INSTALL_CMAKE_LOCAL}" FILE ${PROJECT_NAME}Targets.cmake) +cmake_minimum_required(VERSION 3.8) +project(MEDWriterPlugin) +find_package(ParaView REQUIRED) + +include(GNUInstallDirs) +set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_BINDIR}") +set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_LIBDIR}") +set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_LIBDIR}") + +set("_paraview_plugin_default_${CMAKE_PROJECT_NAME}" ON) +paraview_plugin_scan( + ENABLE_BY_DEFAULT YES + PLUGIN_FILES "${CMAKE_CURRENT_SOURCE_DIR}/plugin/paraview.plugin" + PROVIDES_PLUGINS plugins + REQUIRES_MODULES required_modules) + +foreach(module IN LISTS required_modules) + if(NOT TARGET "${module}") + message("Missing required module: ${module}") + return() + endif() +endforeach() + +set(BUILD_SHARED_LIBS ON) +paraview_plugin_build( + RUNTIME_DESTINATION "${CMAKE_INSTALL_BINDIR}" + LIBRARY_DESTINATION "${CMAKE_INSTALL_LIBDIR}" + LIBRARY_SUBDIRECTORY "${PARAVIEW_PLUGIN_SUBDIR}" + PLUGINS ${plugins} + AUTOLOAD ${plugins}) diff --git a/src/Plugins/MEDWriter/IO/CMakeLists.txt b/src/Plugins/MEDWriter/IO/CMakeLists.txt deleted file mode 100644 index d3674c31..00000000 --- a/src/Plugins/MEDWriter/IO/CMakeLists.txt +++ /dev/null @@ -1,28 +0,0 @@ -# Copyright (C) 2016-2019 CEA/DEN, EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# -# Author : Anthony Geay (EDF R&D) - -ADD_LIBRARY(VTKToMEDMem SHARED VTKToMEDMem.cxx) -TARGET_LINK_LIBRARIES(VTKToMEDMem vtkPVVTKExtensionsRendering vtkFiltersGeneral vtkFiltersCore ${PARAVIEW_LIBRARIES} ${MEDCoupling_medloader} ${MEDFILE_C_LIBRARIES}) -INSTALL(TARGETS VTKToMEDMem EXPORT ${PROJECT_NAME}TargetGroup RUNTIME DESTINATION ${VTK_INSTALL_RUNTIME_DIR} LIBRARY DESTINATION ${VTK_INSTALL_LIBRARY_DIR} ARCHIVE DESTINATION ${VTK_INSTALL_ARCHIVE_DIR} ) - -INSTALL(FILES VTKToMEDMem.hxx VTKMEDTraits.hxx DESTINATION ${MEDWRITER_INSTALL_HEADERS}) - -SET(_${PROJECT_NAME}_exposed_targets VTKToMEDMem) -EXPORT(TARGETS ${_${PROJECT_NAME}_exposed_targets} FILE ${PROJECT_BINARY_DIR}/${PROJECT_NAME}Targets.cmake) diff --git a/src/Plugins/MEDWriter/IO/VTKMEDTraits.hxx b/src/Plugins/MEDWriter/IO/VTKMEDTraits.hxx deleted file mode 100644 index 4efcdc24..00000000 --- a/src/Plugins/MEDWriter/IO/VTKMEDTraits.hxx +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (C) 2017-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Anthony Geay (EDF R&D) - -#ifndef __VTKMEDTRAITS_HXX__ -#define __VTKMEDTRAITS_HXX__ - -class vtkIntArray; -class vtkLongArray; -#ifdef WIN32 -class vtkLongLongArray; -#endif -class vtkFloatArray; -class vtkDoubleArray; - -template -class MEDFileVTKTraits -{ -public: - typedef void VtkType; - typedef void MCType; -}; - -template<> -class MEDFileVTKTraits -{ -public: - typedef vtkIntArray VtkType; - typedef MEDCoupling::DataArrayInt32 MCType; -}; - -template<> -#ifdef WIN32 -class MEDFileVTKTraits -#else -class MEDFileVTKTraits -#endif -# -{ -public: -#ifdef WIN32 - typedef vtkLongLongArray VtkType; -#else - typedef vtkLongArray VtkType; -#endif - typedef MEDCoupling::DataArrayInt64 MCType; -}; - -template<> -class MEDFileVTKTraits -{ -public: - typedef vtkFloatArray VtkType; - typedef MEDCoupling::DataArrayFloat MCType; -}; - -template<> -class MEDFileVTKTraits -{ -public: - typedef vtkDoubleArray VtkType; - typedef MEDCoupling::DataArrayDouble MCType; -}; - -#endif diff --git a/src/Plugins/MEDWriter/IO/VTKToMEDMem.cxx b/src/Plugins/MEDWriter/IO/VTKToMEDMem.cxx deleted file mode 100644 index 80a2bc03..00000000 --- a/src/Plugins/MEDWriter/IO/VTKToMEDMem.cxx +++ /dev/null @@ -1,950 +0,0 @@ -// Copyright (C) 2017-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Anthony Geay (EDF R&D) - -#include "VTKToMEDMem.hxx" - -#include "vtkAdjacentVertexIterator.h" -#include "vtkIntArray.h" -#include "vtkLongArray.h" -#include "vtkCellData.h" -#include "vtkPointData.h" -#include "vtkFloatArray.h" -#include "vtkCellArray.h" - -#include "vtkStreamingDemandDrivenPipeline.h" -#include "vtkInformationDataObjectMetaDataKey.h" -#include "vtkUnstructuredGrid.h" -#include "vtkMultiBlockDataSet.h" -#include "vtkRectilinearGrid.h" -#include "vtkInformationStringKey.h" -#include "vtkAlgorithmOutput.h" -#include "vtkObjectFactory.h" -#include "vtkMutableDirectedGraph.h" -#include "vtkMultiBlockDataSet.h" -#include "vtkPolyData.h" -#include "vtkDataSet.h" -#include "vtkInformationVector.h" -#include "vtkInformation.h" -#include "vtkDataArraySelection.h" -#include "vtkTimeStamp.h" -#include "vtkInEdgeIterator.h" -#include "vtkInformationDataObjectKey.h" -#include "vtkExecutive.h" -#include "vtkVariantArray.h" -#include "vtkStringArray.h" -#include "vtkDoubleArray.h" -#include "vtkCharArray.h" -#include "vtkUnsignedCharArray.h" -#include "vtkDataSetAttributes.h" -#include "vtkDemandDrivenPipeline.h" -#include "vtkDataObjectTreeIterator.h" -#include "vtkWarpScalar.h" - -#include -#include -#include -#include - -using VTKToMEDMem::Grp; -using VTKToMEDMem::Fam; - -using MEDCoupling::MEDFileData; -using MEDCoupling::MEDFileMesh; -using MEDCoupling::MEDFileCMesh; -using MEDCoupling::MEDFileUMesh; -using MEDCoupling::MEDFileFields; -using MEDCoupling::MEDFileMeshes; - -using MEDCoupling::MEDFileIntField1TS; -using MEDCoupling::MEDFileField1TS; -using MEDCoupling::MEDFileIntFieldMultiTS; -using MEDCoupling::MEDFileFieldMultiTS; -using MEDCoupling::MEDFileAnyTypeFieldMultiTS; -using MEDCoupling::DataArray; -using MEDCoupling::DataArrayInt32; -using MEDCoupling::DataArrayInt64; -using MEDCoupling::DataArrayFloat; -using MEDCoupling::DataArrayDouble; -using MEDCoupling::MEDCouplingMesh; -using MEDCoupling::MEDCouplingUMesh; -using MEDCoupling::MEDCouplingCMesh; -using MEDCoupling::MEDCouplingFieldDouble; -using MEDCoupling::MEDCouplingFieldFloat; -using MEDCoupling::MEDCouplingFieldInt; -using MEDCoupling::MCAuto; -using MEDCoupling::Traits; -using MEDCoupling::MLFieldTraits; - -/////////////////// - -Fam::Fam(const std::string& name) -{ - static const char ZE_SEP[]="@@][@@"; - std::size_t pos(name.find(ZE_SEP)); - std::string name0(name.substr(0,pos)),name1(name.substr(pos+strlen(ZE_SEP))); - std::istringstream iss(name1); - iss >> _id; - _name=name0; -} - -/////////////////// - -#include "VTKMEDTraits.hxx" - -std::map ComputeMapOfType() -{ - std::map ret; - int nbOfTypesInMC(sizeof(MEDCOUPLING2VTKTYPETRADUCER)/sizeof( decltype(MEDCOUPLING2VTKTYPETRADUCER[0]) )); - for(int i=0;i& context) -{ - static const char DFT_MESH_NAME[]="Mesh"; - if(context.empty()) - return DFT_MESH_NAME; - std::ostringstream oss; oss << DFT_MESH_NAME; - for(std::vector::const_iterator it=context.begin();it!=context.end();it++) - oss << "_" << *it; - return oss.str(); -} - -DataArrayIdType *ConvertVTKArrayToMCArrayInt(vtkDataArray *data) -{ - if(!data) - throw MZCException("ConvertVTKArrayToMCArrayInt : internal error !"); - int nbTuples(data->GetNumberOfTuples()),nbComp(data->GetNumberOfComponents()); - std::size_t nbElts(nbTuples*nbComp); - MCAuto ret(DataArrayIdType::New()); - ret->alloc(nbTuples,nbComp); - for(int i=0;iGetComponentName(i)); - if(comp) - ret->setInfoOnComponent(i,comp); - } - mcIdType *ptOut(ret->getPointer()); - vtkIntArray *d0(vtkIntArray::SafeDownCast(data)); - if(d0) - { - const int *pt(d0->GetPointer(0)); - std::copy(pt,pt+nbElts,ptOut); - return ret.retn(); - } - vtkLongArray *d1(vtkLongArray::SafeDownCast(data)); - if(d1) - { - const long *pt(d1->GetPointer(0)); - std::copy(pt,pt+nbElts,ptOut); - return ret.retn(); - } - vtkUnsignedCharArray *d2(vtkUnsignedCharArray::SafeDownCast(data)); - if(d2) - { - const unsigned char *pt(d2->GetPointer(0)); - std::copy(pt,pt+nbElts,ptOut); - return ret.retn(); - } - std::ostringstream oss; - oss << "ConvertVTKArrayToMCArrayInt : unrecognized array \"" << typeid(*data).name() << "\" type !"; - throw MZCException(oss.str()); -} - -template -typename Traits::ArrayType *ConvertVTKArrayToMCArrayDouble(vtkDataArray *data) -{ - if(!data) - throw MZCException("ConvertVTKArrayToMCArrayDouble : internal error !"); - int nbTuples(data->GetNumberOfTuples()),nbComp(data->GetNumberOfComponents()); - std::size_t nbElts(nbTuples*nbComp); - MCAuto< typename Traits::ArrayType > ret(Traits::ArrayType::New()); - ret->alloc(nbTuples,nbComp); - for(int i=0;iGetComponentName(i)); - if(comp) - ret->setInfoOnComponent(i,comp); - else - { - if(nbComp>1 && nbComp<=3) - { - char tmp[2]; - tmp[0]=(char)('X'+i); tmp[1]='\0'; - ret->setInfoOnComponent(i,tmp); - } - } - } - T *ptOut(ret->getPointer()); - typename MEDFileVTKTraits::VtkType *d0(MEDFileVTKTraits::VtkType::SafeDownCast(data)); - if(d0) - { - const T *pt(d0->GetPointer(0)); - for(std::size_t i=0;iGetClassName() << "\" type !"; - throw MZCException(oss.str()); -} - -DataArrayDouble *ConvertVTKArrayToMCArrayDoubleForced(vtkDataArray *data) -{ - if(!data) - throw MZCException("ConvertVTKArrayToMCArrayDoubleForced : internal error 0 !"); - vtkFloatArray *d0(vtkFloatArray::SafeDownCast(data)); - if(d0) - { - MCAuto ret(ConvertVTKArrayToMCArrayDouble(data)); - MCAuto ret2(ret->convertToDblArr()); - return ret2.retn(); - } - vtkDoubleArray *d1(vtkDoubleArray::SafeDownCast(data)); - if(d1) - return ConvertVTKArrayToMCArrayDouble(data); - throw MZCException("ConvertVTKArrayToMCArrayDoubleForced : unrecognized type of data for double !"); -} - -DataArray *ConvertVTKArrayToMCArray(vtkDataArray *data) -{ - if(!data) - throw MZCException("ConvertVTKArrayToMCArray : internal error !"); - vtkFloatArray *d0(vtkFloatArray::SafeDownCast(data)); - if(d0) - return ConvertVTKArrayToMCArrayDouble(data); - vtkDoubleArray *d1(vtkDoubleArray::SafeDownCast(data)); - if(d1) - return ConvertVTKArrayToMCArrayDouble(data); - vtkIntArray *d2(vtkIntArray::SafeDownCast(data)); - vtkLongArray *d3(vtkLongArray::SafeDownCast(data)); - vtkUnsignedCharArray *d4(vtkUnsignedCharArray::SafeDownCast(data)); - if(d2 || d3 || d4) - return ConvertVTKArrayToMCArrayInt(data); - std::ostringstream oss; - oss << "ConvertVTKArrayToMCArray : unrecognized array \"" << typeid(*data).name() << "\" type !"; - throw MZCException(oss.str()); -} - -MEDCouplingUMesh *BuildMeshFromCellArray(vtkCellArray *ca, DataArrayDouble *coords, int meshDim, INTERP_KERNEL::NormalizedCellType type) -{ - MCAuto subMesh(MEDCouplingUMesh::New("",meshDim)); - subMesh->setCoords(coords); subMesh->allocateCells(); - int nbCells(ca->GetNumberOfCells()); - if(nbCells==0) - return 0; - vtkIdType nbEntries(ca->GetNumberOfConnectivityEntries()); - const vtkIdType *conn(ca->GetPointer()); - for(int i=0;i conn2(sz); - for(int jj=0;jjinsertNextCell(type,sz,&conn2[0]); - conn+=sz; - } - return subMesh.retn(); -} - -MEDCouplingUMesh *BuildMeshFromCellArrayTriangleStrip(vtkCellArray *ca, DataArrayDouble *coords, MCAuto& ids) -{ - MCAuto subMesh(MEDCouplingUMesh::New("",2)); - subMesh->setCoords(coords); subMesh->allocateCells(); - int nbCells(ca->GetNumberOfCells()); - if(nbCells==0) - return 0; - vtkIdType nbEntries(ca->GetNumberOfConnectivityEntries()); - const vtkIdType *conn(ca->GetPointer()); - ids=DataArrayIdType::New() ; ids->alloc(0,1); - for(int i=0;i0) - { - for(int j=0;jinsertNextCell(INTERP_KERNEL::NORM_TRI3,3,conn2); - ids->pushBackSilent(i); - } - } - else - { - std::ostringstream oss; oss << "BuildMeshFromCellArrayTriangleStrip : on cell #" << i << " the triangle stip looks bab !"; - throw MZCException(oss.str()); - } - conn+=sz; - } - return subMesh.retn(); -} - -class MicroField -{ -public: - MicroField(const MCAuto& m, const std::vector >& cellFs):_m(m),_cellFs(cellFs) { } - MicroField(const std::vector< MicroField >& vs); - void setNodeFields(const std::vector >& nf) { _nodeFs=nf; } - MCAuto getMesh() const { return _m; } - std::vector > getCellFields() const { return _cellFs; } -private: - MCAuto _m; - std::vector > _cellFs; - std::vector > _nodeFs; -}; - -MicroField::MicroField(const std::vector< MicroField >& vs) -{ - std::size_t sz(vs.size()); - std::vector vs2(sz); - std::vector< std::vector< MCAuto > > arrs2(sz); - int nbElts(-1); - for(std::size_t ii=0;ii arrsTmp(sz); - for(std::size_t jj=0;jj -void AppendToFields(MEDCoupling::TypeOfField tf, MEDCouplingMesh *mesh, const DataArrayIdType *n2oPtr, typename MEDFileVTKTraits::MCType *dadPtr, MEDFileFields *fs, double timeStep, int tsId) -{ - std::string fieldName(dadPtr->getName()); - MCAuto< typename Traits::FieldType > f(Traits::FieldType::New(tf)); - f->setTime(timeStep,tsId,0); - { - std::string fieldNameForChuckNorris(MEDCoupling::MEDFileAnyTypeField1TSWithoutSDA::FieldNameToMEDFileConvention(fieldName)); - f->setName(fieldNameForChuckNorris); - } - if(!n2oPtr) - f->setArray(dadPtr); - else - { - MCAuto< typename Traits::ArrayType > dad2(dadPtr->selectByTupleId(n2oPtr->begin(),n2oPtr->end())); - f->setArray(dad2); - } - f->setMesh(mesh); - MCAuto< typename MLFieldTraits::FMTSType > fmts(MLFieldTraits::FMTSType::New()); - MCAuto< typename MLFieldTraits::F1TSType > f1ts(MLFieldTraits::F1TSType::New()); - f1ts->setFieldNoProfileSBT(f); - fmts->pushBackTimeStep(f1ts); - fs->pushField(fmts); -} - -void AppendMCFieldFrom(MEDCoupling::TypeOfField tf, MEDCouplingMesh *mesh, MEDFileData *mfd, MCAuto da, const DataArrayIdType *n2oPtr, double timeStep, int tsId) -{ - static const char FAMFIELD_FOR_CELLS[]="FamilyIdCell"; - static const char FAMFIELD_FOR_NODES[]="FamilyIdNode"; - if(!da || !mesh || !mfd) - throw MZCException("AppendMCFieldFrom : internal error !"); - MEDFileFields *fs(mfd->getFields()); - MEDFileMeshes *ms(mfd->getMeshes()); - if(!fs || !ms) - throw MZCException("AppendMCFieldFrom : internal error 2 !"); - MCAuto dad(MEDCoupling::DynamicCast(da)); - if(dad.isNotNull()) - { - AppendToFields(tf,mesh,n2oPtr,dad,fs,timeStep,tsId); - return ; - } - MCAuto daf(MEDCoupling::DynamicCast(da)); - if(daf.isNotNull()) - { - AppendToFields(tf,mesh,n2oPtr,daf,fs,timeStep,tsId); - return ; - } - MCAuto dai(MEDCoupling::DynamicCast(da)); - MCAuto daId(MEDCoupling::DynamicCast(da)); - if(dai.isNotNull() || daId.isNotNull()) - { - std::string fieldName(dai->getName()); - if((fieldName!=FAMFIELD_FOR_CELLS || tf!=MEDCoupling::ON_CELLS) && (fieldName!=FAMFIELD_FOR_NODES || tf!=MEDCoupling::ON_NODES)) - { - if(!dai) - throw MZCException("AppendMCFieldFrom : internal error 3 (not int32) !"); - AppendToFields(tf,mesh,n2oPtr,dai,fs,timeStep,tsId); - return ; - } - else if(fieldName==FAMFIELD_FOR_CELLS && tf==MEDCoupling::ON_CELLS) - { - MEDFileMesh *mm(ms->getMeshWithName(mesh->getName())); - if(!mm) - throw MZCException("AppendMCFieldFrom : internal error 3 !"); - if(!daId) - throw MZCException("AppendMCFieldFrom : internal error 3 (not mcIdType) !"); - if(!n2oPtr) - mm->setFamilyFieldArr(mesh->getMeshDimension()-mm->getMeshDimension(),daId); - else - { - MCAuto dai2(daId->selectByTupleId(n2oPtr->begin(),n2oPtr->end())); - mm->setFamilyFieldArr(mesh->getMeshDimension()-mm->getMeshDimension(),dai2); - } - } - else if(fieldName==FAMFIELD_FOR_NODES || tf==MEDCoupling::ON_NODES) - { - MEDFileMesh *mm(ms->getMeshWithName(mesh->getName())); - if(!mm) - throw MZCException("AppendMCFieldFrom : internal error 4 !"); - if(!daId) - throw MZCException("AppendMCFieldFrom : internal error 4 (not mcIdType) !"); - if(!n2oPtr) - mm->setFamilyFieldArr(1,daId); - else - { - MCAuto dai2(daId->selectByTupleId(n2oPtr->begin(),n2oPtr->end())); - mm->setFamilyFieldArr(1,dai2); - } - } - } -} - -void PutAtLevelDealOrder(MEDFileData *mfd, int meshDimRel, const MicroField& mf, double timeStep, int tsId) -{ - if(!mfd) - throw MZCException("PutAtLevelDealOrder : internal error !"); - MEDFileMesh *mm(mfd->getMeshes()->getMeshAtPos(0)); - MEDFileUMesh *mmu(dynamic_cast(mm)); - if(!mmu) - throw MZCException("PutAtLevelDealOrder : internal error 2 !"); - MCAuto mesh(mf.getMesh()); - mesh->setName(mfd->getMeshes()->getMeshAtPos(0)->getName()); - MCAuto o2n(mesh->sortCellsInMEDFileFrmt()); - const DataArrayIdType *o2nPtr(o2n); - MCAuto n2o; - mmu->setMeshAtLevel(meshDimRel,mesh); - const DataArrayIdType *n2oPtr(0); - if(o2n) - { - n2o=o2n->invertArrayO2N2N2O(mesh->getNumberOfCells()); - n2oPtr=n2o; - if(n2oPtr && n2oPtr->isIota(mesh->getNumberOfCells())) - n2oPtr=0; - if(n2oPtr) - mm->setRenumFieldArr(meshDimRel,n2o); - } - // - std::vector > cells(mf.getCellFields()); - for(std::vector >::const_iterator it=cells.begin();it!=cells.end();it++) - { - MCAuto da(*it); - AppendMCFieldFrom(MEDCoupling::ON_CELLS,mesh,mfd,da,n2oPtr,timeStep,tsId); - } -} - -void AssignSingleGTMeshes(MEDFileData *mfd, const std::vector< MicroField >& ms, double timeStep, int tsId) -{ - if(!mfd) - throw MZCException("AssignSingleGTMeshes : internal error !"); - MEDFileMesh *mm0(mfd->getMeshes()->getMeshAtPos(0)); - MEDFileUMesh *mm(dynamic_cast(mm0)); - if(!mm) - throw MZCException("AssignSingleGTMeshes : internal error 2 !"); - int meshDim(-std::numeric_limits::max()); - std::map > ms2; - for(std::vector< MicroField >::const_iterator it=ms.begin();it!=ms.end();it++) - { - const MEDCouplingUMesh *elt((*it).getMesh()); - if(elt) - { - int myMeshDim(elt->getMeshDimension()); - meshDim=std::max(meshDim,myMeshDim); - ms2[myMeshDim].push_back(*it); - } - } - if(ms2.empty()) - return ; - for(std::map >::const_iterator it=ms2.begin();it!=ms2.end();it++) - { - const std::vector< MicroField >& vs((*it).second); - if(vs.size()==1) - { - PutAtLevelDealOrder(mfd,(*it).first-meshDim,vs[0],timeStep,tsId); - } - else - { - MicroField merge(vs); - PutAtLevelDealOrder(mfd,(*it).first-meshDim,merge,timeStep,tsId); - } - } -} - -DataArrayDouble *BuildCoordsFrom(vtkPointSet *ds) -{ - if(!ds) - throw MZCException("BuildCoordsFrom : internal error !"); - vtkPoints *pts(ds->GetPoints()); - if(!pts) - throw MZCException("BuildCoordsFrom : internal error 2 !"); - vtkDataArray *data(pts->GetData()); - if(!data) - throw MZCException("BuildCoordsFrom : internal error 3 !"); - return ConvertVTKArrayToMCArrayDoubleForced(data); -} - -void AddNodeFields(MEDFileData *mfd, vtkDataSetAttributes *dsa, double timeStep, int tsId) -{ - if(!mfd || !dsa) - throw MZCException("AddNodeFields : internal error !"); - MEDFileMesh *mm(mfd->getMeshes()->getMeshAtPos(0)); - MEDFileUMesh *mmu(dynamic_cast(mm)); - if(!mmu) - throw MZCException("AddNodeFields : internal error 2 !"); - MCAuto mesh; - if(!mmu->getNonEmptyLevels().empty()) - mesh=mmu->getMeshAtLevel(0); - else - { - mesh=MEDCouplingUMesh::Build0DMeshFromCoords(mmu->getCoords()); - mesh->setName(mmu->getName()); - } - int nba(dsa->GetNumberOfArrays()); - for(int i=0;iGetArray(i)); - const char *name(arr->GetName()); - if(!arr) - continue; - MCAuto da(ConvertVTKArrayToMCArray(arr)); - da->setName(name); - AppendMCFieldFrom(MEDCoupling::ON_NODES,mesh,mfd,da,NULL,timeStep,tsId); - } -} - -std::vector > AddPartFields(const DataArrayIdType *part, vtkDataSetAttributes *dsa) -{ - std::vector< MCAuto > ret; - if(!dsa) - return ret; - int nba(dsa->GetNumberOfArrays()); - for(int i=0;iGetArray(i)); - if(!arr) - continue; - const char *name(arr->GetName()); - int nbCompo(arr->GetNumberOfComponents()); - vtkIdType nbTuples(arr->GetNumberOfTuples()); - MCAuto mcarr(ConvertVTKArrayToMCArray(arr)); - if(part) - mcarr=mcarr->selectByTupleId(part->begin(),part->end()); - mcarr->setName(name); - ret.push_back(mcarr); - } - return ret; -} - -std::vector > AddPartFields2(int bg, int end, vtkDataSetAttributes *dsa) -{ - std::vector< MCAuto > ret; - if(!dsa) - return ret; - int nba(dsa->GetNumberOfArrays()); - for(int i=0;iGetArray(i)); - if(!arr) - continue; - const char *name(arr->GetName()); - int nbCompo(arr->GetNumberOfComponents()); - vtkIdType nbTuples(arr->GetNumberOfTuples()); - MCAuto mcarr(ConvertVTKArrayToMCArray(arr)); - mcarr=mcarr->selectByTupleIdSafeSlice(bg,end,1); - mcarr->setName(name); - ret.push_back(mcarr); - } - return ret; -} - -void ConvertFromRectilinearGrid(MEDFileData *ret, vtkRectilinearGrid *ds, const std::vector& context, double timeStep, int tsId) -{ - if(!ds || !ret) - throw MZCException("ConvertFromRectilinearGrid : internal error !"); - // - MCAuto meshes(MEDFileMeshes::New()); - ret->setMeshes(meshes); - MCAuto fields(MEDFileFields::New()); - ret->setFields(fields); - // - MCAuto cmesh(MEDFileCMesh::New()); - meshes->pushMesh(cmesh); - MCAuto cmeshmc(MEDCouplingCMesh::New()); - vtkDataArray *cx(ds->GetXCoordinates()),*cy(ds->GetYCoordinates()),*cz(ds->GetZCoordinates()); - if(cx) - { - MCAuto arr(ConvertVTKArrayToMCArrayDoubleForced(cx)); - cmeshmc->setCoordsAt(0,arr); - } - if(cy) - { - MCAuto arr(ConvertVTKArrayToMCArrayDoubleForced(cy)); - cmeshmc->setCoordsAt(1,arr); - } - if(cz) - { - MCAuto arr(ConvertVTKArrayToMCArrayDoubleForced(cz)); - cmeshmc->setCoordsAt(2,arr); - } - std::string meshName(GetMeshNameWithContext(context)); - cmeshmc->setName(meshName); - cmesh->setMesh(cmeshmc); - std::vector > cellFs(AddPartFields(0,ds->GetCellData())); - for(std::vector >::const_iterator it=cellFs.begin();it!=cellFs.end();it++) - { - MCAuto da(*it); - AppendMCFieldFrom(MEDCoupling::ON_CELLS,cmeshmc,ret,da,NULL,timeStep,tsId); - } - std::vector > nodeFs(AddPartFields(0,ds->GetPointData())); - for(std::vector >::const_iterator it=nodeFs.begin();it!=nodeFs.end();it++) - { - MCAuto da(*it); - AppendMCFieldFrom(MEDCoupling::ON_NODES,cmeshmc,ret,da,NULL,timeStep,tsId); - } -} - -void ConvertFromPolyData(MEDFileData *ret, vtkPolyData *ds, const std::vector& context, double timeStep, int tsId) -{ - if(!ds || !ret) - throw MZCException("ConvertFromPolyData : internal error !"); - // - MCAuto meshes(MEDFileMeshes::New()); - ret->setMeshes(meshes); - MCAuto fields(MEDFileFields::New()); - ret->setFields(fields); - // - MCAuto umesh(MEDFileUMesh::New()); - meshes->pushMesh(umesh); - MCAuto coords(BuildCoordsFrom(ds)); - umesh->setCoords(coords); - umesh->setName(GetMeshNameWithContext(context)); - // - int offset(0); - std::vector< MicroField > ms; - vtkCellArray *cd(ds->GetVerts()); - if(cd) - { - MCAuto subMesh(BuildMeshFromCellArray(cd,coords,0,INTERP_KERNEL::NORM_POINT1)); - if((const MEDCouplingUMesh *)subMesh) - { - std::vector > cellFs(AddPartFields2(offset,offset+subMesh->getNumberOfCells(),ds->GetCellData())); - offset+=subMesh->getNumberOfCells(); - ms.push_back(MicroField(subMesh,cellFs)); - } - } - vtkCellArray *cc(ds->GetLines()); - if(cc) - { - MCAuto subMesh; - try - { - subMesh=BuildMeshFromCellArray(cc,coords,1,INTERP_KERNEL::NORM_SEG2); - } - catch(INTERP_KERNEL::Exception& e) - { - std::ostringstream oss; oss << "MEDWriter does not manage polyline cell type because MED file format does not support it ! Maybe it is the source of the problem ? The cause of this exception was " << e.what() << std::endl; - throw INTERP_KERNEL::Exception(oss.str()); - } - if((const MEDCouplingUMesh *)subMesh) - { - std::vector > cellFs(AddPartFields2(offset,offset+subMesh->getNumberOfCells(),ds->GetCellData())); - offset+=subMesh->getNumberOfCells(); - ms.push_back(MicroField(subMesh,cellFs)); - } - } - vtkCellArray *cb(ds->GetPolys()); - if(cb) - { - MCAuto subMesh(BuildMeshFromCellArray(cb,coords,2,INTERP_KERNEL::NORM_POLYGON)); - if((const MEDCouplingUMesh *)subMesh) - { - std::vector > cellFs(AddPartFields2(offset,offset+subMesh->getNumberOfCells(),ds->GetCellData())); - offset+=subMesh->getNumberOfCells(); - ms.push_back(MicroField(subMesh,cellFs)); - } - } - vtkCellArray *ca(ds->GetStrips()); - if(ca) - { - MCAuto ids; - MCAuto subMesh(BuildMeshFromCellArrayTriangleStrip(ca,coords,ids)); - if((const MEDCouplingUMesh *)subMesh) - { - std::vector > cellFs(AddPartFields(ids,ds->GetCellData())); - offset+=subMesh->getNumberOfCells(); - ms.push_back(MicroField(subMesh,cellFs)); - } - } - AssignSingleGTMeshes(ret,ms,timeStep,tsId); - AddNodeFields(ret,ds->GetPointData(),timeStep,tsId); -} - -void ConvertFromUnstructuredGrid(MEDFileData *ret, vtkUnstructuredGrid *ds, const std::vector& context, double timeStep, int tsId) -{ - if(!ds || !ret) - throw MZCException("ConvertFromUnstructuredGrid : internal error !"); - // - MCAuto meshes(MEDFileMeshes::New()); - ret->setMeshes(meshes); - MCAuto fields(MEDFileFields::New()); - ret->setFields(fields); - // - MCAuto umesh(MEDFileUMesh::New()); - meshes->pushMesh(umesh); - MCAuto coords(BuildCoordsFrom(ds)); - umesh->setCoords(coords); - umesh->setName(GetMeshNameWithContext(context)); - vtkIdType nbCells(ds->GetNumberOfCells()); - vtkCellArray *ca(ds->GetCells()); - if(!ca) - return ; - vtkIdType nbEnt(ca->GetNumberOfConnectivityEntries()); - vtkIdType *caPtr(ca->GetPointer()); - vtkUnsignedCharArray *ct(ds->GetCellTypesArray()); - if(!ct) - throw MZCException("ConvertFromUnstructuredGrid : internal error"); - vtkIdTypeArray *cla(ds->GetCellLocationsArray()); - const vtkIdType *claPtr(cla->GetPointer(0)); - if(!cla) - throw MZCException("ConvertFromUnstructuredGrid : internal error 2"); - const unsigned char *ctPtr(ct->GetPointer(0)); - std::map m(ComputeMapOfType()); - MCAuto lev(DataArrayInt::New()) ; lev->alloc(nbCells,1); - int *levPtr(lev->getPointer()); - for(vtkIdType i=0;i::iterator it(m.find(ctPtr[i])); - if(it!=m.end()) - { - const INTERP_KERNEL::CellModel& cm(INTERP_KERNEL::CellModel::GetCellModel((INTERP_KERNEL::NormalizedCellType)(*it).second)); - levPtr[i]=cm.getDimension(); - } - else - { - if(ctPtr[i]==VTK_POLY_VERTEX) - { - const INTERP_KERNEL::CellModel& cm(INTERP_KERNEL::CellModel::GetCellModel(INTERP_KERNEL::NORM_POINT1)); - levPtr[i]=cm.getDimension(); - } - else - { - std::ostringstream oss; oss << "ConvertFromUnstructuredGrid : at pos #" << i << " unrecognized VTK cell with type =" << ctPtr[i]; - throw MZCException(oss.str()); - } - } - } - int dummy(0); - MCAuto levs(lev->getDifferentValues()); - std::vector< MicroField > ms; - vtkIdTypeArray *faces(ds->GetFaces()),*faceLoc(ds->GetFaceLocations()); - for(const int *curLev=levs->begin();curLev!=levs->end();curLev++) - { - MCAuto m0(MEDCouplingUMesh::New("",*curLev)); - m0->setCoords(coords); m0->allocateCells(); - MCAuto cellIdsCurLev(lev->findIdsEqual(*curLev)); - for(const mcIdType *cellId=cellIdsCurLev->begin();cellId!=cellIdsCurLev->end();cellId++) - { - int vtkType(ctPtr[*cellId]); - std::map::iterator it(m.find(vtkType)); - vtkIdType offset(claPtr[*cellId]); - vtkIdType sz(caPtr[offset]); - INTERP_KERNEL::NormalizedCellType ct=it!=m.end()?(INTERP_KERNEL::NormalizedCellType)((*it).second):INTERP_KERNEL::NORM_POINT1; - if(ct!=INTERP_KERNEL::NORM_POLYHED && vtkType!=VTK_POLY_VERTEX) - { - std::vector conn2(sz); - for(int kk=0;kkinsertNextCell(ct,sz,&conn2[0]); - } - else if(ct==INTERP_KERNEL::NORM_POLYHED) - { - if(!faces || !faceLoc) - throw MZCException("ConvertFromUnstructuredGrid : faces are expected when there are polyhedra !"); - const vtkIdType *facPtr(faces->GetPointer(0)),*facLocPtr(faceLoc->GetPointer(0)); - std::vector conn; - int off0(facLocPtr[*cellId]); - int nbOfFaces(facPtr[off0++]); - for(int k=0;kinsertNextCell(ct,ToIdType(conn.size()),&conn[0]); - } - else - { - if(sz!=1) - throw MZCException("ConvertFromUnstructuredGrid : non single poly vertex not managed by MED !"); - m0->insertNextCell(ct,1,(const mcIdType*)(caPtr+offset+1)); - } - } - std::vector > cellFs(AddPartFields(cellIdsCurLev,ds->GetCellData())); - ms.push_back(MicroField(m0,cellFs)); - } - AssignSingleGTMeshes(ret,ms,timeStep,tsId); - AddNodeFields(ret,ds->GetPointData(),timeStep,tsId); -} - -/////////////////// - -void WriteMEDFileFromVTKDataSet(MEDFileData *mfd, vtkDataSet *ds, const std::vector& context, double timeStep, int tsId) -{ - if(!ds || !mfd) - throw MZCException("Internal error in WriteMEDFileFromVTKDataSet."); - vtkPolyData *ds2(vtkPolyData::SafeDownCast(ds)); - vtkUnstructuredGrid *ds3(vtkUnstructuredGrid::SafeDownCast(ds)); - vtkRectilinearGrid *ds4(vtkRectilinearGrid::SafeDownCast(ds)); - if(ds2) - { - ConvertFromPolyData(mfd,ds2,context,timeStep,tsId); - } - else if(ds3) - { - ConvertFromUnstructuredGrid(mfd,ds3,context,timeStep,tsId); - } - else if(ds4) - { - ConvertFromRectilinearGrid(mfd,ds4,context,timeStep,tsId); - } - else - throw MZCException("Unrecognized vtkDataSet ! Sorry ! Try to convert it to UnstructuredGrid to be able to write it !"); -} - -void WriteMEDFileFromVTKMultiBlock(MEDFileData *mfd, vtkMultiBlockDataSet *ds, const std::vector& context, double timeStep, int tsId) -{ - if(!ds || !mfd) - throw MZCException("Internal error in WriteMEDFileFromVTKMultiBlock."); - int nbBlocks(ds->GetNumberOfBlocks()); - if(nbBlocks==1 && context.empty()) - { - vtkDataObject *uniqueElt(ds->GetBlock(0)); - if(!uniqueElt) - throw MZCException("Unique elt in multiblock is NULL !"); - vtkDataSet *uniqueEltc(vtkDataSet::SafeDownCast(uniqueElt)); - if(uniqueEltc) - { - WriteMEDFileFromVTKDataSet(mfd,uniqueEltc,context,timeStep,tsId); - return ; - } - } - for(int i=0;iGetBlock(i)); - std::vector context2; - context2.push_back(i); - if(!elt) - { - std::ostringstream oss; oss << "In context "; - std::copy(context.begin(),context.end(),std::ostream_iterator(oss," ")); - oss << " at pos #" << i << " elt is NULL !"; - throw MZCException(oss.str()); - } - vtkDataSet *elt1(vtkDataSet::SafeDownCast(elt)); - if(elt1) - { - WriteMEDFileFromVTKDataSet(mfd,elt1,context,timeStep,tsId); - continue; - } - vtkMultiBlockDataSet *elt2(vtkMultiBlockDataSet::SafeDownCast(elt)); - if(elt2) - { - WriteMEDFileFromVTKMultiBlock(mfd,elt2,context,timeStep,tsId); - continue; - } - std::ostringstream oss; oss << "In context "; - std::copy(context.begin(),context.end(),std::ostream_iterator(oss," ")); - oss << " at pos #" << i << " elt not recognized data type !"; - throw MZCException(oss.str()); - } -} - -void WriteMEDFileFromVTKGDS(MEDFileData *mfd, vtkDataObject *input, double timeStep, int tsId) -{ - if(!input || !mfd) - throw MZCException("WriteMEDFileFromVTKGDS : internal error !"); - std::vector context; - vtkDataSet *input1(vtkDataSet::SafeDownCast(input)); - if(input1) - { - WriteMEDFileFromVTKDataSet(mfd,input1,context,timeStep,tsId); - return ; - } - vtkMultiBlockDataSet *input2(vtkMultiBlockDataSet::SafeDownCast(input)); - if(input2) - { - WriteMEDFileFromVTKMultiBlock(mfd,input2,context,timeStep,tsId); - return ; - } - throw MZCException("WriteMEDFileFromVTKGDS : not recognized data type !"); -} - -void PutFamGrpInfoIfAny(MEDFileData *mfd, const std::string& meshName, const std::vector& groups, const std::vector& fams) -{ - if(!mfd) - return ; - if(meshName.empty()) - return ; - MEDFileMeshes *meshes(mfd->getMeshes()); - if(!meshes) - return ; - if(meshes->getNumberOfMeshes()!=1) - return ; - MEDFileMesh *mm(meshes->getMeshAtPos(0)); - if(!mm) - return ; - mm->setName(meshName); - for(std::vector::const_iterator it=fams.begin();it!=fams.end();it++) - mm->setFamilyId((*it).getName(),(*it).getID()); - for(std::vector::const_iterator it=groups.begin();it!=groups.end();it++) - mm->setFamiliesOnGroup((*it).getName(),(*it).getFamilies()); - MEDFileFields *fields(mfd->getFields()); - if(!fields) - return ; - for(int i=0;igetNumberOfFields();i++) - { - MEDFileAnyTypeFieldMultiTS *fmts(fields->getFieldAtPos(i)); - if(!fmts) - continue; - fmts->setMeshName(meshName); - } -} diff --git a/src/Plugins/MEDWriter/IO/VTKToMEDMem.hxx b/src/Plugins/MEDWriter/IO/VTKToMEDMem.hxx deleted file mode 100644 index 6f36d77f..00000000 --- a/src/Plugins/MEDWriter/IO/VTKToMEDMem.hxx +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright (C) 2017-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Anthony Geay (EDF R&D) - -#ifndef __VTKTOMEDMEM_HXX__ -#define __VTKTOMEDMEM_HXX__ - -#include "vtkSystemIncludes.h" //needed for exports - -#include "MEDCouplingRefCountObject.hxx" -#include "MEDCouplingMemArray.hxx" -#include "MEDCouplingFieldDouble.hxx" -#include "MEDCouplingFieldFloat.hxx" -#include "MEDCouplingFieldInt.hxx" -#include "MEDFileData.hxx" -#include "MEDFileField.hxx" -#include "MEDFileMesh.hxx" -#include "MEDLoaderTraits.hxx" - -#include -#include - -/////////////////// - -class vtkDataSet; - -class VTK_EXPORT MZCException : public std::exception -{ -public: - MZCException(const std::string& s):_reason(s) { } - virtual const char *what() const throw() { return _reason.c_str(); } - virtual ~MZCException() throw() { } -private: - std::string _reason; -}; - -namespace VTKToMEDMem -{ - class VTK_EXPORT Grp - { - public: - Grp(const std::string& name):_name(name) { } - void setFamilies(const std::vector& fams) { _fams=fams; } - std::string getName() const { return _name; } - std::vector getFamilies() const { return _fams; } - private: - std::string _name; - std::vector _fams; - }; - - class VTK_EXPORT Fam - { - public: - Fam(const std::string& name); - std::string getName() const { return _name; } - int getID() const { return _id; } - private: - std::string _name; - int _id; - }; -} - -class vtkDataObject; - -void VTK_EXPORT WriteMEDFileFromVTKDataSet(MEDCoupling::MEDFileData *mfd, vtkDataSet *ds, const std::vector& context, double timeStep, int tsId); - -void VTK_EXPORT WriteMEDFileFromVTKGDS(MEDCoupling::MEDFileData *mfd, vtkDataObject *input, double timeStep, int tsId); - -void VTK_EXPORT PutFamGrpInfoIfAny(MEDCoupling::MEDFileData *mfd, const std::string& meshName, const std::vector& groups, const std::vector& fams); - -#endif - diff --git a/src/Plugins/MEDWriter/IO/vtkMEDWriter.cxx b/src/Plugins/MEDWriter/IO/vtkMEDWriter.cxx deleted file mode 100644 index e25bb47e..00000000 --- a/src/Plugins/MEDWriter/IO/vtkMEDWriter.cxx +++ /dev/null @@ -1,305 +0,0 @@ -// Copyright (C) 2016-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Anthony Geay (EDF R&D) - -#include "vtkMEDWriter.h" -#include "VTKToMEDMem.hxx" - -#include "vtkAdjacentVertexIterator.h" -#include "vtkIntArray.h" -#include "vtkLongArray.h" -#include "vtkCellData.h" -#include "vtkPointData.h" -#include "vtkFloatArray.h" -#include "vtkCellArray.h" - -#include "vtkStreamingDemandDrivenPipeline.h" -#include "vtkInformationDataObjectMetaDataKey.h" -#include "vtkUnstructuredGrid.h" -#include "vtkMultiBlockDataSet.h" -#include "vtkRectilinearGrid.h" -#include "vtkInformationStringKey.h" -#include "vtkAlgorithmOutput.h" -#include "vtkObjectFactory.h" -#include "vtkMutableDirectedGraph.h" -#include "vtkMultiBlockDataSet.h" -#include "vtkPolyData.h" -#include "vtkDataSet.h" -#include "vtkInformationVector.h" -#include "vtkInformation.h" -#include "vtkDataArraySelection.h" -#include "vtkTimeStamp.h" -#include "vtkInEdgeIterator.h" -#include "vtkInformationDataObjectKey.h" -#include "vtkExecutive.h" -#include "vtkVariantArray.h" -#include "vtkStringArray.h" -#include "vtkDoubleArray.h" -#include "vtkCharArray.h" -#include "vtkUnsignedCharArray.h" -#include "vtkDataSetAttributes.h" -#include "vtkDemandDrivenPipeline.h" -#include "vtkDataObjectTreeIterator.h" -#include "vtkWarpScalar.h" - -#include "MEDFileMesh.hxx" -#include "MEDFileField.hxx" -#include "MEDFileData.hxx" -#include "MEDCouplingMemArray.hxx" -#include "MEDCouplingFieldInt.hxx" -#include "MEDCouplingFieldFloat.hxx" -#include "MEDCouplingFieldDouble.hxx" -#include "MEDCouplingRefCountObject.hxx" -#include "MEDLoaderTraits.hxx" - -#include -#include -#include - -vtkStandardNewMacro(vtkMEDWriter); - -using MEDCoupling::MEDFileData; -using MEDCoupling::MCAuto; -using VTKToMEDMem::Grp; -using VTKToMEDMem::Fam; - -vtkInformationDataObjectMetaDataKey *GetMEDReaderMetaDataIfAny() -{ - static const char ZE_KEY[]="vtkMEDReader::META_DATA"; - MEDCoupling::GlobalDict *gd(MEDCoupling::GlobalDict::GetInstance()); - if(!gd->hasKey(ZE_KEY)) - return 0; - std::string ptSt(gd->value(ZE_KEY)); - void *pt(0); - std::istringstream iss(ptSt); iss >> pt; - return reinterpret_cast(pt); -} - -bool IsInformationOK(vtkInformation *info) -{ - vtkInformationDataObjectMetaDataKey *key(GetMEDReaderMetaDataIfAny()); - if(!key) - return false; - // Check the information contain meta data key - if(!info->Has(key)) - return false; - // Recover Meta Data - vtkMutableDirectedGraph *sil(vtkMutableDirectedGraph::SafeDownCast(info->Get(key))); - if(!sil) - return false; - int idNames(0); - vtkAbstractArray *verticesNames(sil->GetVertexData()->GetAbstractArray("Names",idNames)); - vtkStringArray *verticesNames2(vtkStringArray::SafeDownCast(verticesNames)); - if(!verticesNames2) - return false; - for(int i=0;iGetNumberOfValues();i++) - { - vtkStdString &st(verticesNames2->GetValue(i)); - if(st=="MeshesFamsGrps") - return true; - } - return false; -} - -void LoadFamGrpMapInfo(vtkMutableDirectedGraph *sil, std::string& meshName, std::vector& groups, std::vector& fams) -{ - if(!sil) - throw MZCException("LoadFamGrpMapInfo : internal error !"); - int idNames(0); - vtkAbstractArray *verticesNames(sil->GetVertexData()->GetAbstractArray("Names",idNames)); - vtkStringArray *verticesNames2(vtkStringArray::SafeDownCast(verticesNames)); - vtkIdType id0; - bool found(false); - for(int i=0;iGetNumberOfValues();i++) - { - vtkStdString &st(verticesNames2->GetValue(i)); - if(st=="MeshesFamsGrps") - { - id0=i; - found=true; - } - } - if(!found) - throw INTERP_KERNEL::Exception("There is an internal error ! The tree on server side has not the expected look !"); - vtkAdjacentVertexIterator *it0(vtkAdjacentVertexIterator::New()); - sil->GetAdjacentVertices(id0,it0); - int kk(0),ll(0); - while(it0->HasNext()) - { - vtkIdType id1(it0->Next()); - std::string mName((const char *)verticesNames2->GetValue(id1)); - meshName=mName; - vtkAdjacentVertexIterator *it1(vtkAdjacentVertexIterator::New()); - sil->GetAdjacentVertices(id1,it1); - vtkIdType idZeGrps(it1->Next());//zeGroups - vtkAdjacentVertexIterator *itGrps(vtkAdjacentVertexIterator::New()); - sil->GetAdjacentVertices(idZeGrps,itGrps); - while(itGrps->HasNext()) - { - vtkIdType idg(itGrps->Next()); - Grp grp((const char *)verticesNames2->GetValue(idg)); - vtkAdjacentVertexIterator *itGrps2(vtkAdjacentVertexIterator::New()); - sil->GetAdjacentVertices(idg,itGrps2); - std::vector famsOnGroup; - while(itGrps2->HasNext()) - { - vtkIdType idgf(itGrps2->Next()); - famsOnGroup.push_back(std::string((const char *)verticesNames2->GetValue(idgf))); - } - grp.setFamilies(famsOnGroup); - itGrps2->Delete(); - groups.push_back(grp); - } - itGrps->Delete(); - vtkIdType idZeFams(it1->Next());//zeFams - it1->Delete(); - vtkAdjacentVertexIterator *itFams(vtkAdjacentVertexIterator::New()); - sil->GetAdjacentVertices(idZeFams,itFams); - while(itFams->HasNext()) - { - vtkIdType idf(itFams->Next()); - Fam fam((const char *)verticesNames2->GetValue(idf)); - fams.push_back(fam); - } - itFams->Delete(); - } - it0->Delete(); -} - -vtkMEDWriter::vtkMEDWriter():WriteAllTimeSteps(0),NumberOfTimeSteps(0),CurrentTimeIndex(0),FileName(0) -{ -} - -vtkMEDWriter::~vtkMEDWriter() -{ -} - -int vtkMEDWriter::RequestInformation(vtkInformation *request, vtkInformationVector **inputVector, vtkInformationVector *outputVector) -{ - //std::cerr << "########################################## vtkMEDWriter::RequestInformation ########################################## " << (const char *) this->FileName << std::endl; - vtkInformation *inInfo(inputVector[0]->GetInformationObject(0)); - if(inInfo->Has(vtkStreamingDemandDrivenPipeline::TIME_STEPS())) - this->NumberOfTimeSteps=inInfo->Length(vtkStreamingDemandDrivenPipeline::TIME_STEPS()); - else - this->NumberOfTimeSteps=0; - return 1; -} - -int vtkMEDWriter::RequestUpdateExtent(vtkInformation* vtkNotUsed(request), vtkInformationVector** inputVector, vtkInformationVector* vtkNotUsed(outputVector)) -{ - double *inTimes(inputVector[0]->GetInformationObject(0)->Get(vtkStreamingDemandDrivenPipeline::TIME_STEPS())); - if(inTimes && this->WriteAllTimeSteps) - { - double timeReq(inTimes[this->CurrentTimeIndex]); - inputVector[0]->GetInformationObject(0)->Set(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP(),timeReq); - } - return 1; -} - -void ExceptionDisplayer(vtkMEDWriter *self, const std::string& fileName, std::exception& e) -{ - std::ostringstream oss; - oss << "Exception has been thrown in vtkMEDWriter::RequestData : During writing of \"" << fileName << "\", the following exception has been thrown : "<< e.what() << std::endl; - if(self->HasObserver("ErrorEvent") ) - self->InvokeEvent("ErrorEvent",const_cast(oss.str().c_str())); - else - vtkOutputWindowDisplayErrorText(const_cast(oss.str().c_str())); - vtkObject::BreakOnError(); -} - -int vtkMEDWriter::RequestData(vtkInformation *request, vtkInformationVector **inputVector, vtkInformationVector *outputVector) -{ - //std::cerr << "########################################## vtkMEDWriter::RequestData ########################################## " << (const char *) this->FileName << std::endl; - try - { - bool writeAll((this->WriteAllTimeSteps!=0 && this->NumberOfTimeSteps>0)); - if(writeAll) - { - if(this->CurrentTimeIndex==0) - request->Set(vtkStreamingDemandDrivenPipeline::CONTINUE_EXECUTING(),1); - } - else - { - request->Remove(vtkStreamingDemandDrivenPipeline::CONTINUE_EXECUTING()); - this->CurrentTimeIndex=0; - } - ////////////// - vtkInformation *inputInfo(inputVector[0]->GetInformationObject(0)); - std::string meshName; - std::vector groups; std::vector fams; - if(IsInformationOK(inputInfo)) - { - vtkMutableDirectedGraph *famGrpGraph(vtkMutableDirectedGraph::SafeDownCast(inputInfo->Get(GetMEDReaderMetaDataIfAny()))); - LoadFamGrpMapInfo(famGrpGraph,meshName,groups,fams); - } - vtkInformation *outInfo(outputVector->GetInformationObject(0)); - vtkDataObject *input(vtkDataObject::SafeDownCast(inputInfo->Get(vtkDataObject::DATA_OBJECT()))); - if(!input) - throw MZCException("Not recognized data object in input of the MEDWriter ! Maybe not implemented yet !"); - double timeStep; - { - vtkInformation *inInfo(inputVector[0]->GetInformationObject(0)); - vtkDataObject* input(vtkDataObject::GetData(inInfo)); - timeStep=input->GetInformation()->Get(vtkDataObject::DATA_TIME_STEP()); - } - //////////// - MCAuto mfd(MEDFileData::New()); - WriteMEDFileFromVTKGDS(mfd,input,timeStep,this->CurrentTimeIndex); - PutFamGrpInfoIfAny(mfd,meshName,groups,fams); - if(this->WriteAllTimeSteps==0 || (this->WriteAllTimeSteps!=0 && this->CurrentTimeIndex==0)) - mfd->write(this->FileName,2); - else - { - mfd->getFields()->write(this->FileName,0); - } - outInfo->Set(vtkDataObject::DATA_OBJECT(),input); - /////////// - if(writeAll) - { - this->CurrentTimeIndex++; - if(this->CurrentTimeIndex>=this->NumberOfTimeSteps) - { - request->Remove(vtkStreamingDemandDrivenPipeline::CONTINUE_EXECUTING()); - this->CurrentTimeIndex=0; - } - } - } - catch(INTERP_KERNEL::Exception& e) - { - ExceptionDisplayer(this,(const char *) this->FileName,e); - return 0; - } - catch(MZCException& e) - { - ExceptionDisplayer(this,(const char *) this->FileName,e); - return 0; - } - return 1; -} - -void vtkMEDWriter::PrintSelf(ostream& os, vtkIndent indent) -{ - this->Superclass::PrintSelf(os, indent); -} - -int vtkMEDWriter::Write() -{ - this->Update(); - return 0; -} diff --git a/src/Plugins/MEDWriter/IO/vtkMEDWriter.h b/src/Plugins/MEDWriter/IO/vtkMEDWriter.h deleted file mode 100644 index e99badf2..00000000 --- a/src/Plugins/MEDWriter/IO/vtkMEDWriter.h +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (C) 2016-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Anthony Geay (EDF R&D) - -#ifndef vtkMEDWriter_h__ -#define vtkMEDWriter_h__ - -#include "vtkDataObjectAlgorithm.h" - -class vtkMutableDirectedGraph; - -class VTK_EXPORT vtkMEDWriter : public vtkDataObjectAlgorithm -{ -public: - static vtkMEDWriter* New(); - vtkTypeMacro(vtkMEDWriter, vtkDataObjectAlgorithm) - void PrintSelf(ostream& os, vtkIndent indent); - - vtkSetStringMacro(FileName); - vtkGetStringMacro(FileName); - int Write(); - vtkGetMacro(WriteAllTimeSteps, int); - vtkSetMacro(WriteAllTimeSteps, int); - vtkBooleanMacro(WriteAllTimeSteps, int); -protected: - vtkMEDWriter(); - ~vtkMEDWriter(); - - int RequestInformation(vtkInformation *request, vtkInformationVector **inputVector, vtkInformationVector *outputVector); - int RequestData(vtkInformation *request, vtkInformationVector **inputVector, vtkInformationVector *outputVector); - int RequestUpdateExtent(vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector); -private: - vtkMEDWriter(const vtkMEDWriter&); - void operator=(const vtkMEDWriter&); // Not implemented. - private: - int WriteAllTimeSteps; - int NumberOfTimeSteps; - int CurrentTimeIndex; - char *FileName; - //BTX - //ETX -}; - -#endif diff --git a/src/Plugins/MEDWriter/MEDWriterConfig.cmake.in b/src/Plugins/MEDWriter/MEDWriterConfig.cmake.in deleted file mode 100644 index 588af97d..00000000 --- a/src/Plugins/MEDWriter/MEDWriterConfig.cmake.in +++ /dev/null @@ -1,65 +0,0 @@ -############################################################### -# Copyright (C) 2017-2019 CEA/DEN, EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# - -@PACKAGE_INIT@ - -# Load the dependencies for the libraries of @PROJECT_NAME@ -# (contains definitions for IMPORTED targets). This is only -# imported if we are not built as a subproject (in this case targets are already there) -INCLUDE("@PROJECT_NAME@Targets") - -# Package root dir: -SET_AND_CHECK(MEDWRITER_ROOT_DIR_EXP "@PACKAGE_CMAKE_INSTALL_PREFIX@") - -# Include directories and definitions -SET_AND_CHECK(MEDWRITER_INCLUDE_DIRS "${MEDWRITER_ROOT_DIR_EXP}/@MEDWRITER_INSTALL_HEADERS@") - - -# For all prerequisites, load the corresponding targets if the package was used -# in CONFIG mode. This ensures dependent projects link correctly -# without having to set LD_LIBRARY_PATH: -SET(_PREREQ_@PROJECT_NAME@ @_PREREQ_LIST@) -SET(_PREREQ_@PROJECT_NAME@_CONFIG_DIR @_PREREQ_DIR_LIST@) -SET(_PREREQ_@PROJECT_NAME@_COMPONENTS "@_PREREQ_COMPO_LIST@") -LIST(LENGTH _PREREQ_@PROJECT_NAME@_CONFIG_DIR _list_len_@PROJECT_NAME@) -IF(NOT _list_len_@PROJECT_NAME@ EQUAL 0) - # Another CMake stupidity - FOREACH(... RANGE r) generates r+1 numbers ... - MATH(EXPR _range_@PROJECT_NAME@ "${_list_len_@PROJECT_NAME@}-1") - FOREACH(_p_@PROJECT_NAME@ RANGE ${_range_@PROJECT_NAME@}) - LIST(GET _PREREQ_@PROJECT_NAME@ ${_p_@PROJECT_NAME@} _pkg_@PROJECT_NAME@ ) - LIST(GET _PREREQ_@PROJECT_NAME@_CONFIG_DIR ${_p_@PROJECT_NAME@} _pkg_dir_@PROJECT_NAME@) - LIST(GET _PREREQ_@PROJECT_NAME@_COMPONENTS ${_p_@PROJECT_NAME@} _pkg_compo_@PROJECT_NAME@) - IF(NOT OMIT_DETECT_PACKAGE_${_pkg_@PROJECT_NAME@}) - MESSAGE(STATUS "===> Reloading targets from ${_pkg_@PROJECT_NAME@} ...") - IF(NOT _pkg_compo_@PROJECT_NAME@) - FIND_PACKAGE(${_pkg_@PROJECT_NAME@} REQUIRED NO_MODULE - PATHS "${_pkg_dir_@PROJECT_NAME@}" - NO_DEFAULT_PATH) - ELSE() - STRING(REPLACE "," ";" _compo_lst_@PROJECT_NAME@ "${_pkg_compo_@PROJECT_NAME@}") - MESSAGE(STATUS "===> (components: ${_pkg_compo_@PROJECT_NAME@})") - FIND_PACKAGE(${_pkg_@PROJECT_NAME@} REQUIRED NO_MODULE - COMPONENTS ${_compo_lst_@PROJECT_NAME@} - PATHS "${_pkg_dir_@PROJECT_NAME@}" - NO_DEFAULT_PATH) - ENDIF() - ENDIF() - ENDFOREACH() -ENDIF() \ No newline at end of file diff --git a/src/Plugins/MEDWriter/ParaViewPlugin/CMakeLists.txt b/src/Plugins/MEDWriter/ParaViewPlugin/CMakeLists.txt deleted file mode 100644 index 4536b481..00000000 --- a/src/Plugins/MEDWriter/ParaViewPlugin/CMakeLists.txt +++ /dev/null @@ -1,26 +0,0 @@ -# Copyright (C) 2016-2019 CEA/DEN, EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# -# Author : Anthony Geay (EDF R&D) - -INCLUDE_DIRECTORIES( ${CMAKE_CURRENT_SOURCE_DIR}/../IO ) -ADD_PARAVIEW_PLUGIN(MEDWriterPlugin "4.0" - SERVER_MANAGER_SOURCES ${SM_SRCS} ${PROJECT_SOURCE_DIR}/IO/vtkMEDWriter.cxx - SERVER_MANAGER_XML Resources/MEDWriterServer.xml) -TARGET_LINK_LIBRARIES(MEDWriterPlugin VTKToMEDMem) -INSTALL(TARGETS MEDWriterPlugin RUNTIME DESTINATION lib/paraview LIBRARY DESTINATION lib/paraview ARCHIVE DESTINATION lib/paraview) diff --git a/src/Plugins/MEDWriter/ParaViewPlugin/Resources/MEDWriterServer.xml b/src/Plugins/MEDWriter/ParaViewPlugin/Resources/MEDWriterServer.xml deleted file mode 100644 index 29239b8a..00000000 --- a/src/Plugins/MEDWriter/ParaViewPlugin/Resources/MEDWriterServer.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - - - The input filter/source whose output dataset is written to the MED file. - - - - The name of the MED file to be written. - - - - When WriteAllTimeSteps is turned ON, the writer is executed once for each timestep available from the reader. - - - - - - - - - diff --git a/src/Plugins/MEDWriter/Test/TestMEDWriter0.py b/src/Plugins/MEDWriter/Test/TestMEDWriter0.py deleted file mode 100644 index 8cf8cb79..00000000 --- a/src/Plugins/MEDWriter/Test/TestMEDWriter0.py +++ /dev/null @@ -1,242 +0,0 @@ -# Copyright (C) 2016-2019 CEA/DEN, EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# -# Author : Anthony Geay (EDF R&D) - -#### import the simple module from the paraview -from paraview.simple import * -import MEDLoader as ml -import os -from math import pi,sqrt - -#### disable automatic camera reset on 'Show' -paraview.simple._DisableFirstRenderCameraReset() - -pat='testMEDWriter_%i.med' -fname0=pat%0 -fname1=pat%1 -fname2=pat%2 -fname3=pat%3 -fname4=pat%4 -fname4_vtp=os.path.splitext(pat%4)[0]+".vtp" -fname5=pat%5 -fname6_vtu=os.path.splitext(pat%6)[0]+".vtu" -fname6=pat%6 -fname7_vtu=os.path.splitext(pat%7)[0]+".vtu" -fname7=pat%7 -fname8_vtr=os.path.splitext(pat%8)[0]+".vtr" -fname8=pat%8 - -##### First test with a simple sphere - -plane1 = Sphere() -SaveData(fname0,proxy=plane1,WriteAllTimeSteps=1) -# -totomed=MEDReader(FileName=fname0) -totomed.AllArrays=['TS0/Mesh/ComSup0/Mesh@@][@@P0'] -totomed.AllTimeSteps=['0000'] -SaveData(fname1,proxy=totomed,WriteAllTimeSteps=1) -# Sphere has been written. Try to check to write it in MED file ! -mfd=ml.MEDFileData(fname0) -mm=mfd.getMeshes()[0] ; m0=mm[0] -area=m0.getMeasureField(ml.ON_CELLS).accumulate()[0] -assert(abs(sqrt(area/(4*pi))-0.975/2.)<0.01) # 4*pi*radius**2 -f=mfd.getFields()[0][0].getFieldOnMeshAtLevel(ml.ON_NODES,0,mm) -assert(abs(ml.DataArrayDouble(f.accumulate(),1,3).magnitude()[0])<1e-12) # sum of all normal vector should be 0 - - -##### Build a MED file from scratch - -fieldName0="F0" -fieldName1="F1" -c=ml.DataArrayDouble([0.,0.,1.,1.,2.,2.,1.,0.,2.,0.,0.,2.,1.,2.,0.,1.,2.,1.],9,2) -c.setInfoOnComponents(["X abc","Y defg"]) -# -mName="mesh" -m0=ml.MEDCouplingUMesh(mName,2) ; m0.allocateCells() ; m0.setCoords(c) -m0.insertNextCell(ml.NORM_TRI3,[3,1,4]) -m0.insertNextCell(ml.NORM_TRI3,[1,8,4]) -m0.insertNextCell(ml.NORM_QUAD4,[0,7,1,3]) -m0.insertNextCell(ml.NORM_QUAD4,[1,6,2,4]) -m0.insertNextCell(ml.NORM_QUAD4,[7,5,6,1]) -m1=ml.MEDCouplingUMesh(mName,1) ; m1.allocateCells() ; m1.setCoords(c) -m1.insertNextCell(ml.NORM_SEG2,[0,7]) -m1.insertNextCell(ml.NORM_SEG2,[7,5]) -m1.insertNextCell(ml.NORM_SEG2,[5,6]) -mm=ml.MEDFileUMesh() ; mm[0]=m0 ; mm[-1]=m1 -mm.setFamilyFieldArr(1,ml.DataArrayInt([200,201,202,203,204,205,206,207,208])) -mm.setFamilyFieldArr(0,ml.DataArrayInt([100,101,102,103,104])) -mm.setFamilyFieldArr(-1,ml.DataArrayInt([105,106,107])) -mm.setFamilyId("Fam3",3) ; mm.setFamilyId("Fam5",7) -mm.setFamiliesOnGroup("gr0",["Fam3"]) -mm.setFamiliesOnGroup("gr1",["Fam5"]) -mm.setFamiliesOnGroup("gr2",["Fam3","Fam5"]) -mm.write(fname2,2) -# -f1ts0=ml.MEDFileField1TS() -f0=ml.MEDCouplingFieldDouble(ml.ON_CELLS) ; f0.setName(fieldName0) -f0.setMesh(m0) ; f0.setArray(ml.DataArrayDouble([8,7,6,5,4])) -f1ts0.setFieldNoProfileSBT(f0) -f0=ml.MEDCouplingFieldDouble(ml.ON_CELLS) ; f0.setName(fieldName0) -f0.setMesh(m1) ; f0.setArray(ml.DataArrayDouble([3,2,1])) -f1ts0.setFieldNoProfileSBT(f0) -f1ts0.write(fname2,0) -# -f1ts1=ml.MEDFileField1TS() -f0=ml.MEDCouplingFieldDouble(ml.ON_NODES) ; f0.setName(fieldName1) -arr=ml.DataArrayDouble([9,109,8,108,7,107,6,106,5,105,4,104,3,103,2,102,1,101],9,2) -arr.setInfoOnComponents(["aa","bbb"]) -f0.setMesh(m0) ; f0.setArray(arr) -f1ts1.setFieldNoProfileSBT(f0) -f1ts1.write(fname2,0) -# -test3=MEDReader(FileName=fname2) -test3.AllArrays=['TS0/%s/ComSup0/%s@@][@@P0'%(mName,fieldName0),'TS0/%s/ComSup0/%s@@][@@P1'%(mName,fieldName1)] -test3.AllTimeSteps = ['0000'] -SaveData(fname3,proxy=test3,WriteAllTimeSteps=1) -### test content of fname3 -mfd2=ml.MEDFileData(fname3) -mm2=mfd2.getMeshes()[0] -c1=mm2.getCoords() -assert(c.isEqualWithoutConsideringStr(c1[:,:2],1e-12)) -fs2=ml.MEDFileFields(fname3) -assert(len(fs2)==2) -assert(mm2.getSpaceDimension()==3) ; assert(mm2.getCoords()[:,2].isUniform(0.,0.)) -m2_0=mm2[0].deepCopy() ; m2_0.changeSpaceDimension(2,0.) ; m2_0.getCoords().setInfoOnComponents(mm[0].getCoords().getInfoOnComponents()) -assert(m2_0.isEqual(mm[0],1e-12)) -m2_1=mm2[-1].deepCopy() ; m2_1.changeSpaceDimension(2,0.) ; m2_1.getCoords().setInfoOnComponents(mm[0].getCoords().getInfoOnComponents()) -assert(m2_1.isEqual(mm[-1],1e-12)) -f2_0=mfd2.getFields()[fieldName0][0].getFieldOnMeshAtLevel(ml.ON_CELLS,0,mm2) ; f2_0.setMesh(m2_0) -assert(f1ts0.getFieldOnMeshAtLevel(ml.ON_CELLS,0,mm).isEqual(f2_0,1e-12,1e-12)) -f2_1=mfd2.getFields()[fieldName1][0].getFieldOnMeshAtLevel(ml.ON_NODES,0,mm2) ; f2_1.setMesh(m2_0) -assert(f1ts1.getFieldOnMeshAtLevel(ml.ON_NODES,0,mm).isEqual(f2_1,1e-12,1e-12)) -assert(mm2.getGroupsNames()==('gr0','gr1','gr2')) -assert(mm2.getFamiliesOnGroup("gr0")==("Fam3",)) -assert(mm2.getFamiliesOnGroup("gr1")==("Fam5",)) -assert(mm2.getFamiliesOnGroup("gr2")==("Fam3","Fam5")) -assert(mm2.getFamiliesNames()==('FAMILLE_ZERO','Fam3','Fam5')) -assert([mm2.getFamilyId(elt) for elt in ['FAMILLE_ZERO','Fam3','Fam5']]==[0,3,7]) -assert(mm2.getFamilyFieldAtLevel(0).isEqual(mm.getFamilyFieldAtLevel(0))) -assert(mm2.getFamilyFieldAtLevel(-1).isEqual(mm.getFamilyFieldAtLevel(-1))) -assert(mm2.getFamilyFieldAtLevel(1).isEqual(mm.getFamilyFieldAtLevel(1))) -# Write a polydata mesh -mergeBlocks1 = MergeBlocks(Input=test3) -extractSurface1 = ExtractSurface(Input=mergeBlocks1) -SaveData(fname4_vtp,proxy=extractSurface1) -test4vtp = XMLPolyDataReader(FileName=[fname4_vtp]) -test4vtp.CellArrayStatus = ['F0', 'FamilyIdCell'] -SaveData(fname5,proxy=test4vtp,WriteAllTimeSteps=1) -### test content of fname5 -mfd5=ml.MEDFileData(fname5) -m5=mfd5.getMeshes()[0][0].deepCopy() -assert(m5.getSpaceDimension()==3) # -m5.setName(mm.getName()) ; m5.changeSpaceDimension(2,0.) ; m5.getCoords().setInfoOnComponents(mm[0].getCoords().getInfoOnComponents()) -bary5=m5.computeCellCenterOfMass() -bary=mm[0].computeCellCenterOfMass() -a,b=bary5.areIncludedInMe(bary,1e-12) ; assert(a) -a,c=mm[0].getCoords().areIncludedInMe(m5.getCoords(),1e-12) ; assert(a) -m5.renumberNodes(c,len(c))#c.invertArrayO2N2N2O(len(c))) -assert(m5.unPolyze()) -assert(m5.getCoords().isEqual(mm[0].getCoords(),1e-12)) -assert(m5.isEqual(mm[0],1e-12)) -f5_0=mfd5.getFields()[fieldName0][0].getFieldOnMeshAtLevel(ml.ON_CELLS,0,mfd5.getMeshes()[0]) ; f5_0.setMesh(m5) -assert(f1ts0.getFieldOnMeshAtLevel(ml.ON_CELLS,0,mm).isEqual(f5_0,1e-12,1e-12)) -f5_1=mfd5.getFields()[fieldName1][0].getFieldOnMeshAtLevel(ml.ON_NODES,0,mfd5.getMeshes()[0]) ; f5_1.setMesh(m5) -f5_1.setArray(f5_1.getArray()[c.invertArrayO2N2N2O(len(c))]) -assert(f1ts1.getFieldOnMeshAtLevel(ml.ON_NODES,0,mm).isEqual(f5_1,1e-12,1e-12)) - -### test with a non geo types non sorted - -c=ml.DataArrayDouble([0.,0.,1.,1.,2.,2.,1.,0.,2.,0.,0.,2.,1.,2.,0.,1.,2.,1.],9,2) -c.setInfoOnComponents(["X abc","Y defg"]) -m6=ml.MEDCouplingUMesh(mName,2) ; m6.allocateCells() ; m6.setCoords(c) -m6.insertNextCell(ml.NORM_TRI3,[3,1,4]) -m6.insertNextCell(ml.NORM_QUAD4,[0,7,1,3]) -m6.insertNextCell(ml.NORM_TRI3,[1,8,4]) -m6.insertNextCell(ml.NORM_QUAD4,[1,6,2,4]) -m6.insertNextCell(ml.NORM_QUAD4,[7,5,6,1]) -fieldName6="F6" -f6=ml.MEDCouplingFieldDouble(ml.ON_CELLS) ; f6.setMesh(m6) ; f6.setName(fieldName6) -f6.setArray(ml.DataArrayDouble([20,21,22,23,24])) -f6.writeVTK(fname6_vtu) -test6vtu=XMLUnstructuredGridReader(FileName=[fname6_vtu]) -SaveData(fname6,proxy=test6vtu,WriteAllTimeSteps=1) -mfd7=ml.MEDFileData(fname6) -assert(len(mfd7.getMeshes())==1) -m7=mfd7.getMeshes()[0][0] -assert(len(mfd7.getFields())==1) -f7=mfd7.getFields()[0][0].getFieldOnMeshAtLevel(ml.ON_CELLS,0,mfd7.getMeshes()[0]) -assert(f7.getMesh().isEqual(m7,1e-12)) -assert(m7.getCoords()[:,:2].isEqualWithoutConsideringStr(m6.getCoords(),1e-12)) -assert(m7.getNodalConnectivity().isEqual(ml.DataArrayInt([3,3,1,4,3,1,8,4,4,0,7,1,3,4,1,6,2,4,4,7,5,6,1]))) # there is a permutation of cells -assert(m7.getNodalConnectivityIndex().isEqual(ml.DataArrayInt([0,4,8,13,18,23]))) # there is a permutation of cells -assert(f7.getArray().isEqual(ml.DataArrayDouble([20,22,21,23,24]),1e-12)) # there is a permutation of cells - -### test with polyhedron - -m8=ml.MEDCouplingCMesh() ; m8.setCoords(ml.DataArrayDouble([0,1,2,3]),ml.DataArrayDouble([0,1]),ml.DataArrayDouble([0,1])) -m8=m8.buildUnstructured() -m8_0=m8[0] ; m8_0.simplexize(ml.PLANAR_FACE_5) -m8_1=m8[1:] -m8_1.convertAllToPoly() -m8=ml.MEDCouplingUMesh.MergeUMeshesOnSameCoords([m8_0,m8_1]) -m8=m8[[0,5,1,2,6,3,4]] -fieldName8="F8" -f8=ml.MEDCouplingFieldDouble(ml.ON_CELLS) ; f8.setMesh(m8) ; f8.setName(fieldName8) -f8.setArray(ml.DataArrayDouble([20,21,22,23,24,25,26])) -f8.writeVTK(fname7_vtu) -test8vtu=XMLUnstructuredGridReader(FileName=[fname7_vtu]) -SaveData(fname7,proxy=test8vtu,WriteAllTimeSteps=1) -mfd9=ml.MEDFileData(fname7) -assert(len(mfd9.getMeshes())==1) -m9=mfd9.getMeshes()[0][0] -assert(len(mfd9.getFields())==1) -assert(m9.getCoords().isEqual(m8.getCoords(),1e-12)) -c9=ml.DataArrayInt([0,2,3,5,6,1,4]) -assert(m8[c9].isEqualWithoutConsideringStr(m9,1e-12)) -f9=mfd9.getFields()[0][0].getFieldOnMeshAtLevel(ml.ON_CELLS,0,mfd9.getMeshes()[0]) -assert(f9.getArray().isEqual(f8.getArray()[c9],1e-12)) - -### test with cartesian - -FieldName10="F10" -FieldName10_n="F10_n" -m10=ml.MEDCouplingCMesh() -m10.setCoordsAt(0,ml.DataArrayDouble([0,1,2])) -m10.setCoordsAt(1,ml.DataArrayDouble([1,2,3,4])) -m10.setCoordsAt(2,ml.DataArrayDouble([3,5,6,7,8])) -f10=ml.MEDCouplingFieldDouble(ml.ON_CELLS) ; f10.setMesh(m10) -f10.setName(FieldName10) -f10.setArray(ml.DataArrayInt.Range(0,m10.getNumberOfCells(),1).convertToDblArr()) ; f10.checkConsistencyLight() -f10_n=ml.MEDCouplingFieldDouble(ml.ON_NODES) ; f10_n.setMesh(m10) -f10_n.setName(FieldName10_n) -f10_n.setArray(ml.DataArrayInt.Range(0,m10.getNumberOfNodes(),1).convertToDblArr()) ; f10_n.checkConsistencyLight() -ml.MEDCouplingFieldDouble.WriteVTK(fname8_vtr,[f10,f10_n]) -test10vtr=XMLRectilinearGridReader(FileName=[fname8_vtr]) -SaveData(fname8,proxy=test10vtr,WriteAllTimeSteps=1) -mfd11=ml.MEDFileData(fname8) -assert(len(mfd11.getMeshes())==1) -assert(len(mfd11.getFields())==2) -mfd11=ml.MEDFileData(fname8) -m11=mfd11.getMeshes()[0] -assert(isinstance(m11,ml.MEDFileCMesh)) -f11=mfd11.getFields()[FieldName10][0].getFieldOnMeshAtLevel(ml.ON_CELLS,0,m11) -f11_n=mfd11.getFields()[FieldName10_n][0].getFieldOnMeshAtLevel(ml.ON_NODES,0,m11) -assert(f11.isEqualWithoutConsideringStr(f10,1e-12,1e-12)) -assert(f11_n.isEqualWithoutConsideringStr(f10_n,1e-12,1e-12)) - diff --git a/src/Plugins/MEDWriter/plugin/CMakeLists.txt b/src/Plugins/MEDWriter/plugin/CMakeLists.txt new file mode 100644 index 00000000..7577343b --- /dev/null +++ b/src/Plugins/MEDWriter/plugin/CMakeLists.txt @@ -0,0 +1,46 @@ +# Common CMake macros +# =================== +set(TMP_CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH}) +unset(CMAKE_MODULE_PATH) +set(CONFIGURATION_ROOT_DIR $ENV{CONFIGURATION_ROOT_DIR} CACHE PATH "Path to the Salome CMake configuration files") +if(EXISTS ${CONFIGURATION_ROOT_DIR}) + list(APPEND CMAKE_MODULE_PATH "${CONFIGURATION_ROOT_DIR}/cmake") + include(SalomeMacros) +else() + message(FATAL_ERROR "We absolutely need the Salome CMake configuration files, please define CONFIGURATION_ROOT_DIR !") +endif() + +set(MEDCOUPLING_ROOT_DIR $ENV{MEDCOUPLING_ROOT_DIR} CACHE PATH "Path to the MEDCoupling tool") +if(EXISTS ${MEDCOUPLING_ROOT_DIR}) + list(APPEND CMAKE_MODULE_PATH "${MEDCOUPLING_ROOT_DIR}/cmake_files") +endif() +list(APPEND CMAKE_MODULE_PATH "${CMAKE_ROOT}/Modules") +list(APPEND CMAKE_MODULE_PATH ${TMP_CMAKE_MODULE_PATH}) + +include(SalomeSetupPlatform) +set(BUILD_SHARED_LIBS TRUE) + +find_package(SalomeHDF5 REQUIRED) +find_package(SalomeMEDCoupling REQUIRED) + +if(MEDCOUPLING_USE_64BIT_IDS) + add_definitions("-DMEDCOUPLING_USE_64BIT_IDS") +endif(MEDCOUPLING_USE_64BIT_IDS) + +SALOME_ACCUMULATE_ENVIRONMENT(PYTHONPATH NOCHECK ${CMAKE_INSTALL_PREFIX}/${SALOME_INSTALL_BINS} + ${CMAKE_INSTALL_PREFIX}/${SALOME_INSTALL_PYTHON}) +SALOME_ACCUMULATE_ENVIRONMENT(LD_LIBRARY_PATH NOCHECK ${CMAKE_INSTALL_PREFIX}/${SALOME_INSTALL_LIBS}) +SALOME_ACCUMULATE_ENVIRONMENT(PV_PLUGIN_PATH NOCHECK ${CMAKE_INSTALL_PREFIX}/lib/paraview) + +paraview_add_plugin(MEDWriterPlugin + VERSION "1.0" + MODULES MEDWriterIO + MODULE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/MEDWriterIO/vtk.module" + SERVER_MANAGER_XML writers.xml +) + +install(TARGETS MEDWriterPlugin + RUNTIME DESTINATION lib/paraview + LIBRARY DESTINATION lib/paraview + ARCHIVE DESTINATION lib/paraview + ) diff --git a/src/Plugins/MEDWriter/plugin/MEDWriterIO/CMakeLists.txt b/src/Plugins/MEDWriter/plugin/MEDWriterIO/CMakeLists.txt new file mode 100644 index 00000000..62652928 --- /dev/null +++ b/src/Plugins/MEDWriter/plugin/MEDWriterIO/CMakeLists.txt @@ -0,0 +1,18 @@ +set(classes + VTKToMEDMem + vtkMEDWriter +) + +vtk_module_add_module(MEDWriterIO + FORCE_STATIC + CLASSES ${classes} +) + +target_include_directories(MEDWriterIO PRIVATE ${MEDCOUPLING_INCLUDE_DIRS}) + +if(HDF5_IS_PARALLEL) + target_link_libraries(MEDWriterIO PRIVATE ${MEDCoupling_paramedloader}) +else() + target_link_libraries(MEDWriterIO PRIVATE ${MEDCoupling_medloader}) +endif() + diff --git a/src/Plugins/MEDWriter/plugin/MEDWriterIO/VTKMEDTraits.hxx b/src/Plugins/MEDWriter/plugin/MEDWriterIO/VTKMEDTraits.hxx new file mode 100644 index 00000000..4efcdc24 --- /dev/null +++ b/src/Plugins/MEDWriter/plugin/MEDWriterIO/VTKMEDTraits.hxx @@ -0,0 +1,81 @@ +// Copyright (C) 2017-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay (EDF R&D) + +#ifndef __VTKMEDTRAITS_HXX__ +#define __VTKMEDTRAITS_HXX__ + +class vtkIntArray; +class vtkLongArray; +#ifdef WIN32 +class vtkLongLongArray; +#endif +class vtkFloatArray; +class vtkDoubleArray; + +template +class MEDFileVTKTraits +{ +public: + typedef void VtkType; + typedef void MCType; +}; + +template<> +class MEDFileVTKTraits +{ +public: + typedef vtkIntArray VtkType; + typedef MEDCoupling::DataArrayInt32 MCType; +}; + +template<> +#ifdef WIN32 +class MEDFileVTKTraits +#else +class MEDFileVTKTraits +#endif +# +{ +public: +#ifdef WIN32 + typedef vtkLongLongArray VtkType; +#else + typedef vtkLongArray VtkType; +#endif + typedef MEDCoupling::DataArrayInt64 MCType; +}; + +template<> +class MEDFileVTKTraits +{ +public: + typedef vtkFloatArray VtkType; + typedef MEDCoupling::DataArrayFloat MCType; +}; + +template<> +class MEDFileVTKTraits +{ +public: + typedef vtkDoubleArray VtkType; + typedef MEDCoupling::DataArrayDouble MCType; +}; + +#endif diff --git a/src/Plugins/MEDWriter/plugin/MEDWriterIO/VTKToMEDMem.cxx b/src/Plugins/MEDWriter/plugin/MEDWriterIO/VTKToMEDMem.cxx new file mode 100644 index 00000000..3a0cb639 --- /dev/null +++ b/src/Plugins/MEDWriter/plugin/MEDWriterIO/VTKToMEDMem.cxx @@ -0,0 +1,950 @@ +// Copyright (C) 2017-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay (EDF R&D) + +#include "VTKToMEDMem.h" + +#include "vtkAdjacentVertexIterator.h" +#include "vtkIntArray.h" +#include "vtkLongArray.h" +#include "vtkCellData.h" +#include "vtkPointData.h" +#include "vtkFloatArray.h" +#include "vtkCellArray.h" + +#include "vtkStreamingDemandDrivenPipeline.h" +#include "vtkInformationDataObjectMetaDataKey.h" +#include "vtkUnstructuredGrid.h" +#include "vtkMultiBlockDataSet.h" +#include "vtkRectilinearGrid.h" +#include "vtkInformationStringKey.h" +#include "vtkAlgorithmOutput.h" +#include "vtkObjectFactory.h" +#include "vtkMutableDirectedGraph.h" +#include "vtkMultiBlockDataSet.h" +#include "vtkPolyData.h" +#include "vtkDataSet.h" +#include "vtkInformationVector.h" +#include "vtkInformation.h" +#include "vtkDataArraySelection.h" +#include "vtkTimeStamp.h" +#include "vtkInEdgeIterator.h" +#include "vtkInformationDataObjectKey.h" +#include "vtkExecutive.h" +#include "vtkVariantArray.h" +#include "vtkStringArray.h" +#include "vtkDoubleArray.h" +#include "vtkCharArray.h" +#include "vtkUnsignedCharArray.h" +#include "vtkDataSetAttributes.h" +#include "vtkDemandDrivenPipeline.h" +#include "vtkDataObjectTreeIterator.h" +#include "vtkWarpScalar.h" + +#include +#include +#include +#include + +using VTKToMEDMem::Grp; +using VTKToMEDMem::Fam; + +using MEDCoupling::MEDFileData; +using MEDCoupling::MEDFileMesh; +using MEDCoupling::MEDFileCMesh; +using MEDCoupling::MEDFileUMesh; +using MEDCoupling::MEDFileFields; +using MEDCoupling::MEDFileMeshes; + +using MEDCoupling::MEDFileIntField1TS; +using MEDCoupling::MEDFileField1TS; +using MEDCoupling::MEDFileIntFieldMultiTS; +using MEDCoupling::MEDFileFieldMultiTS; +using MEDCoupling::MEDFileAnyTypeFieldMultiTS; +using MEDCoupling::DataArray; +using MEDCoupling::DataArrayInt32; +using MEDCoupling::DataArrayInt64; +using MEDCoupling::DataArrayFloat; +using MEDCoupling::DataArrayDouble; +using MEDCoupling::MEDCouplingMesh; +using MEDCoupling::MEDCouplingUMesh; +using MEDCoupling::MEDCouplingCMesh; +using MEDCoupling::MEDCouplingFieldDouble; +using MEDCoupling::MEDCouplingFieldFloat; +using MEDCoupling::MEDCouplingFieldInt; +using MEDCoupling::MCAuto; +using MEDCoupling::Traits; +using MEDCoupling::MLFieldTraits; + +/////////////////// + +Fam::Fam(const std::string& name) +{ + static const char ZE_SEP[]="@@][@@"; + std::size_t pos(name.find(ZE_SEP)); + std::string name0(name.substr(0,pos)),name1(name.substr(pos+strlen(ZE_SEP))); + std::istringstream iss(name1); + iss >> _id; + _name=name0; +} + +/////////////////// + +#include "VTKMEDTraits.hxx" + +std::map ComputeMapOfType() +{ + std::map ret; + int nbOfTypesInMC(sizeof(MEDCOUPLING2VTKTYPETRADUCER)/sizeof( decltype(MEDCOUPLING2VTKTYPETRADUCER[0]) )); + for(int i=0;i& context) +{ + static const char DFT_MESH_NAME[]="Mesh"; + if(context.empty()) + return DFT_MESH_NAME; + std::ostringstream oss; oss << DFT_MESH_NAME; + for(std::vector::const_iterator it=context.begin();it!=context.end();it++) + oss << "_" << *it; + return oss.str(); +} + +DataArrayIdType *ConvertVTKArrayToMCArrayInt(vtkDataArray *data) +{ + if(!data) + throw MZCException("ConvertVTKArrayToMCArrayInt : internal error !"); + int nbTuples(data->GetNumberOfTuples()),nbComp(data->GetNumberOfComponents()); + std::size_t nbElts(nbTuples*nbComp); + MCAuto ret(DataArrayIdType::New()); + ret->alloc(nbTuples,nbComp); + for(int i=0;iGetComponentName(i)); + if(comp) + ret->setInfoOnComponent(i,comp); + } + mcIdType *ptOut(ret->getPointer()); + vtkIntArray *d0(vtkIntArray::SafeDownCast(data)); + if(d0) + { + const int *pt(d0->GetPointer(0)); + std::copy(pt,pt+nbElts,ptOut); + return ret.retn(); + } + vtkLongArray *d1(vtkLongArray::SafeDownCast(data)); + if(d1) + { + const long *pt(d1->GetPointer(0)); + std::copy(pt,pt+nbElts,ptOut); + return ret.retn(); + } + vtkUnsignedCharArray *d2(vtkUnsignedCharArray::SafeDownCast(data)); + if(d2) + { + const unsigned char *pt(d2->GetPointer(0)); + std::copy(pt,pt+nbElts,ptOut); + return ret.retn(); + } + std::ostringstream oss; + oss << "ConvertVTKArrayToMCArrayInt : unrecognized array \"" << typeid(*data).name() << "\" type !"; + throw MZCException(oss.str()); +} + +template +typename Traits::ArrayType *ConvertVTKArrayToMCArrayDouble(vtkDataArray *data) +{ + if(!data) + throw MZCException("ConvertVTKArrayToMCArrayDouble : internal error !"); + int nbTuples(data->GetNumberOfTuples()),nbComp(data->GetNumberOfComponents()); + std::size_t nbElts(nbTuples*nbComp); + MCAuto< typename Traits::ArrayType > ret(Traits::ArrayType::New()); + ret->alloc(nbTuples,nbComp); + for(int i=0;iGetComponentName(i)); + if(comp) + ret->setInfoOnComponent(i,comp); + else + { + if(nbComp>1 && nbComp<=3) + { + char tmp[2]; + tmp[0]=(char)('X'+i); tmp[1]='\0'; + ret->setInfoOnComponent(i,tmp); + } + } + } + T *ptOut(ret->getPointer()); + typename MEDFileVTKTraits::VtkType *d0(MEDFileVTKTraits::VtkType::SafeDownCast(data)); + if(d0) + { + const T *pt(d0->GetPointer(0)); + for(std::size_t i=0;iGetClassName() << "\" type !"; + throw MZCException(oss.str()); +} + +DataArrayDouble *ConvertVTKArrayToMCArrayDoubleForced(vtkDataArray *data) +{ + if(!data) + throw MZCException("ConvertVTKArrayToMCArrayDoubleForced : internal error 0 !"); + vtkFloatArray *d0(vtkFloatArray::SafeDownCast(data)); + if(d0) + { + MCAuto ret(ConvertVTKArrayToMCArrayDouble(data)); + MCAuto ret2(ret->convertToDblArr()); + return ret2.retn(); + } + vtkDoubleArray *d1(vtkDoubleArray::SafeDownCast(data)); + if(d1) + return ConvertVTKArrayToMCArrayDouble(data); + throw MZCException("ConvertVTKArrayToMCArrayDoubleForced : unrecognized type of data for double !"); +} + +DataArray *ConvertVTKArrayToMCArray(vtkDataArray *data) +{ + if(!data) + throw MZCException("ConvertVTKArrayToMCArray : internal error !"); + vtkFloatArray *d0(vtkFloatArray::SafeDownCast(data)); + if(d0) + return ConvertVTKArrayToMCArrayDouble(data); + vtkDoubleArray *d1(vtkDoubleArray::SafeDownCast(data)); + if(d1) + return ConvertVTKArrayToMCArrayDouble(data); + vtkIntArray *d2(vtkIntArray::SafeDownCast(data)); + vtkLongArray *d3(vtkLongArray::SafeDownCast(data)); + vtkUnsignedCharArray *d4(vtkUnsignedCharArray::SafeDownCast(data)); + if(d2 || d3 || d4) + return ConvertVTKArrayToMCArrayInt(data); + std::ostringstream oss; + oss << "ConvertVTKArrayToMCArray : unrecognized array \"" << typeid(*data).name() << "\" type !"; + throw MZCException(oss.str()); +} + +MEDCouplingUMesh *BuildMeshFromCellArray(vtkCellArray *ca, DataArrayDouble *coords, int meshDim, INTERP_KERNEL::NormalizedCellType type) +{ + MCAuto subMesh(MEDCouplingUMesh::New("",meshDim)); + subMesh->setCoords(coords); subMesh->allocateCells(); + int nbCells(ca->GetNumberOfCells()); + if(nbCells==0) + return 0; + vtkIdType nbEntries(ca->GetNumberOfConnectivityEntries()); + const vtkIdType *conn(ca->GetData()->GetPointer(0)); + for(int i=0;i conn2(sz); + for(int jj=0;jjinsertNextCell(type,sz,&conn2[0]); + conn+=sz; + } + return subMesh.retn(); +} + +MEDCouplingUMesh *BuildMeshFromCellArrayTriangleStrip(vtkCellArray *ca, DataArrayDouble *coords, MCAuto& ids) +{ + MCAuto subMesh(MEDCouplingUMesh::New("",2)); + subMesh->setCoords(coords); subMesh->allocateCells(); + int nbCells(ca->GetNumberOfCells()); + if(nbCells==0) + return 0; + vtkIdType nbEntries(ca->GetNumberOfConnectivityEntries()); + const vtkIdType *conn(ca->GetData()->GetPointer(0)); + ids=DataArrayIdType::New() ; ids->alloc(0,1); + for(int i=0;i0) + { + for(int j=0;jinsertNextCell(INTERP_KERNEL::NORM_TRI3,3,conn2); + ids->pushBackSilent(i); + } + } + else + { + std::ostringstream oss; oss << "BuildMeshFromCellArrayTriangleStrip : on cell #" << i << " the triangle stip looks bab !"; + throw MZCException(oss.str()); + } + conn+=sz; + } + return subMesh.retn(); +} + +class MicroField +{ +public: + MicroField(const MCAuto& m, const std::vector >& cellFs):_m(m),_cellFs(cellFs) { } + MicroField(const std::vector< MicroField >& vs); + void setNodeFields(const std::vector >& nf) { _nodeFs=nf; } + MCAuto getMesh() const { return _m; } + std::vector > getCellFields() const { return _cellFs; } +private: + MCAuto _m; + std::vector > _cellFs; + std::vector > _nodeFs; +}; + +MicroField::MicroField(const std::vector< MicroField >& vs) +{ + std::size_t sz(vs.size()); + std::vector vs2(sz); + std::vector< std::vector< MCAuto > > arrs2(sz); + int nbElts(-1); + for(std::size_t ii=0;ii arrsTmp(sz); + for(std::size_t jj=0;jj +void AppendToFields(MEDCoupling::TypeOfField tf, MEDCouplingMesh *mesh, const DataArrayIdType *n2oPtr, typename MEDFileVTKTraits::MCType *dadPtr, MEDFileFields *fs, double timeStep, int tsId) +{ + std::string fieldName(dadPtr->getName()); + MCAuto< typename Traits::FieldType > f(Traits::FieldType::New(tf)); + f->setTime(timeStep,tsId,0); + { + std::string fieldNameForChuckNorris(MEDCoupling::MEDFileAnyTypeField1TSWithoutSDA::FieldNameToMEDFileConvention(fieldName)); + f->setName(fieldNameForChuckNorris); + } + if(!n2oPtr) + f->setArray(dadPtr); + else + { + MCAuto< typename Traits::ArrayType > dad2(dadPtr->selectByTupleId(n2oPtr->begin(),n2oPtr->end())); + f->setArray(dad2); + } + f->setMesh(mesh); + MCAuto< typename MLFieldTraits::FMTSType > fmts(MLFieldTraits::FMTSType::New()); + MCAuto< typename MLFieldTraits::F1TSType > f1ts(MLFieldTraits::F1TSType::New()); + f1ts->setFieldNoProfileSBT(f); + fmts->pushBackTimeStep(f1ts); + fs->pushField(fmts); +} + +void AppendMCFieldFrom(MEDCoupling::TypeOfField tf, MEDCouplingMesh *mesh, MEDFileData *mfd, MCAuto da, const DataArrayIdType *n2oPtr, double timeStep, int tsId) +{ + static const char FAMFIELD_FOR_CELLS[]="FamilyIdCell"; + static const char FAMFIELD_FOR_NODES[]="FamilyIdNode"; + if(!da || !mesh || !mfd) + throw MZCException("AppendMCFieldFrom : internal error !"); + MEDFileFields *fs(mfd->getFields()); + MEDFileMeshes *ms(mfd->getMeshes()); + if(!fs || !ms) + throw MZCException("AppendMCFieldFrom : internal error 2 !"); + MCAuto dad(MEDCoupling::DynamicCast(da)); + if(dad.isNotNull()) + { + AppendToFields(tf,mesh,n2oPtr,dad,fs,timeStep,tsId); + return ; + } + MCAuto daf(MEDCoupling::DynamicCast(da)); + if(daf.isNotNull()) + { + AppendToFields(tf,mesh,n2oPtr,daf,fs,timeStep,tsId); + return ; + } + MCAuto dai(MEDCoupling::DynamicCast(da)); + MCAuto daId(MEDCoupling::DynamicCast(da)); + if(dai.isNotNull() || daId.isNotNull()) + { + std::string fieldName(dai->getName()); + if((fieldName!=FAMFIELD_FOR_CELLS || tf!=MEDCoupling::ON_CELLS) && (fieldName!=FAMFIELD_FOR_NODES || tf!=MEDCoupling::ON_NODES)) + { + if(!dai) + throw MZCException("AppendMCFieldFrom : internal error 3 (not int32) !"); + AppendToFields(tf,mesh,n2oPtr,dai,fs,timeStep,tsId); + return ; + } + else if(fieldName==FAMFIELD_FOR_CELLS && tf==MEDCoupling::ON_CELLS) + { + MEDFileMesh *mm(ms->getMeshWithName(mesh->getName())); + if(!mm) + throw MZCException("AppendMCFieldFrom : internal error 3 !"); + if(!daId) + throw MZCException("AppendMCFieldFrom : internal error 3 (not mcIdType) !"); + if(!n2oPtr) + mm->setFamilyFieldArr(mesh->getMeshDimension()-mm->getMeshDimension(),daId); + else + { + MCAuto dai2(daId->selectByTupleId(n2oPtr->begin(),n2oPtr->end())); + mm->setFamilyFieldArr(mesh->getMeshDimension()-mm->getMeshDimension(),dai2); + } + } + else if(fieldName==FAMFIELD_FOR_NODES || tf==MEDCoupling::ON_NODES) + { + MEDFileMesh *mm(ms->getMeshWithName(mesh->getName())); + if(!mm) + throw MZCException("AppendMCFieldFrom : internal error 4 !"); + if(!daId) + throw MZCException("AppendMCFieldFrom : internal error 4 (not mcIdType) !"); + if(!n2oPtr) + mm->setFamilyFieldArr(1,daId); + else + { + MCAuto dai2(daId->selectByTupleId(n2oPtr->begin(),n2oPtr->end())); + mm->setFamilyFieldArr(1,dai2); + } + } + } +} + +void PutAtLevelDealOrder(MEDFileData *mfd, int meshDimRel, const MicroField& mf, double timeStep, int tsId) +{ + if(!mfd) + throw MZCException("PutAtLevelDealOrder : internal error !"); + MEDFileMesh *mm(mfd->getMeshes()->getMeshAtPos(0)); + MEDFileUMesh *mmu(dynamic_cast(mm)); + if(!mmu) + throw MZCException("PutAtLevelDealOrder : internal error 2 !"); + MCAuto mesh(mf.getMesh()); + mesh->setName(mfd->getMeshes()->getMeshAtPos(0)->getName()); + MCAuto o2n(mesh->sortCellsInMEDFileFrmt()); + const DataArrayIdType *o2nPtr(o2n); + MCAuto n2o; + mmu->setMeshAtLevel(meshDimRel,mesh); + const DataArrayIdType *n2oPtr(0); + if(o2n) + { + n2o=o2n->invertArrayO2N2N2O(mesh->getNumberOfCells()); + n2oPtr=n2o; + if(n2oPtr && n2oPtr->isIota(mesh->getNumberOfCells())) + n2oPtr=0; + if(n2oPtr) + mm->setRenumFieldArr(meshDimRel,n2o); + } + // + std::vector > cells(mf.getCellFields()); + for(std::vector >::const_iterator it=cells.begin();it!=cells.end();it++) + { + MCAuto da(*it); + AppendMCFieldFrom(MEDCoupling::ON_CELLS,mesh,mfd,da,n2oPtr,timeStep,tsId); + } +} + +void AssignSingleGTMeshes(MEDFileData *mfd, const std::vector< MicroField >& ms, double timeStep, int tsId) +{ + if(!mfd) + throw MZCException("AssignSingleGTMeshes : internal error !"); + MEDFileMesh *mm0(mfd->getMeshes()->getMeshAtPos(0)); + MEDFileUMesh *mm(dynamic_cast(mm0)); + if(!mm) + throw MZCException("AssignSingleGTMeshes : internal error 2 !"); + int meshDim(-std::numeric_limits::max()); + std::map > ms2; + for(std::vector< MicroField >::const_iterator it=ms.begin();it!=ms.end();it++) + { + const MEDCouplingUMesh *elt((*it).getMesh()); + if(elt) + { + int myMeshDim(elt->getMeshDimension()); + meshDim=std::max(meshDim,myMeshDim); + ms2[myMeshDim].push_back(*it); + } + } + if(ms2.empty()) + return ; + for(std::map >::const_iterator it=ms2.begin();it!=ms2.end();it++) + { + const std::vector< MicroField >& vs((*it).second); + if(vs.size()==1) + { + PutAtLevelDealOrder(mfd,(*it).first-meshDim,vs[0],timeStep,tsId); + } + else + { + MicroField merge(vs); + PutAtLevelDealOrder(mfd,(*it).first-meshDim,merge,timeStep,tsId); + } + } +} + +DataArrayDouble *BuildCoordsFrom(vtkPointSet *ds) +{ + if(!ds) + throw MZCException("BuildCoordsFrom : internal error !"); + vtkPoints *pts(ds->GetPoints()); + if(!pts) + throw MZCException("BuildCoordsFrom : internal error 2 !"); + vtkDataArray *data(pts->GetData()); + if(!data) + throw MZCException("BuildCoordsFrom : internal error 3 !"); + return ConvertVTKArrayToMCArrayDoubleForced(data); +} + +void AddNodeFields(MEDFileData *mfd, vtkDataSetAttributes *dsa, double timeStep, int tsId) +{ + if(!mfd || !dsa) + throw MZCException("AddNodeFields : internal error !"); + MEDFileMesh *mm(mfd->getMeshes()->getMeshAtPos(0)); + MEDFileUMesh *mmu(dynamic_cast(mm)); + if(!mmu) + throw MZCException("AddNodeFields : internal error 2 !"); + MCAuto mesh; + if(!mmu->getNonEmptyLevels().empty()) + mesh=mmu->getMeshAtLevel(0); + else + { + mesh=MEDCouplingUMesh::Build0DMeshFromCoords(mmu->getCoords()); + mesh->setName(mmu->getName()); + } + int nba(dsa->GetNumberOfArrays()); + for(int i=0;iGetArray(i)); + const char *name(arr->GetName()); + if(!arr) + continue; + MCAuto da(ConvertVTKArrayToMCArray(arr)); + da->setName(name); + AppendMCFieldFrom(MEDCoupling::ON_NODES,mesh,mfd,da,NULL,timeStep,tsId); + } +} + +std::vector > AddPartFields(const DataArrayIdType *part, vtkDataSetAttributes *dsa) +{ + std::vector< MCAuto > ret; + if(!dsa) + return ret; + int nba(dsa->GetNumberOfArrays()); + for(int i=0;iGetArray(i)); + if(!arr) + continue; + const char *name(arr->GetName()); + int nbCompo(arr->GetNumberOfComponents()); + vtkIdType nbTuples(arr->GetNumberOfTuples()); + MCAuto mcarr(ConvertVTKArrayToMCArray(arr)); + if(part) + mcarr=mcarr->selectByTupleId(part->begin(),part->end()); + mcarr->setName(name); + ret.push_back(mcarr); + } + return ret; +} + +std::vector > AddPartFields2(int bg, int end, vtkDataSetAttributes *dsa) +{ + std::vector< MCAuto > ret; + if(!dsa) + return ret; + int nba(dsa->GetNumberOfArrays()); + for(int i=0;iGetArray(i)); + if(!arr) + continue; + const char *name(arr->GetName()); + int nbCompo(arr->GetNumberOfComponents()); + vtkIdType nbTuples(arr->GetNumberOfTuples()); + MCAuto mcarr(ConvertVTKArrayToMCArray(arr)); + mcarr=mcarr->selectByTupleIdSafeSlice(bg,end,1); + mcarr->setName(name); + ret.push_back(mcarr); + } + return ret; +} + +void ConvertFromRectilinearGrid(MEDFileData *ret, vtkRectilinearGrid *ds, const std::vector& context, double timeStep, int tsId) +{ + if(!ds || !ret) + throw MZCException("ConvertFromRectilinearGrid : internal error !"); + // + MCAuto meshes(MEDFileMeshes::New()); + ret->setMeshes(meshes); + MCAuto fields(MEDFileFields::New()); + ret->setFields(fields); + // + MCAuto cmesh(MEDFileCMesh::New()); + meshes->pushMesh(cmesh); + MCAuto cmeshmc(MEDCouplingCMesh::New()); + vtkDataArray *cx(ds->GetXCoordinates()),*cy(ds->GetYCoordinates()),*cz(ds->GetZCoordinates()); + if(cx) + { + MCAuto arr(ConvertVTKArrayToMCArrayDoubleForced(cx)); + cmeshmc->setCoordsAt(0,arr); + } + if(cy) + { + MCAuto arr(ConvertVTKArrayToMCArrayDoubleForced(cy)); + cmeshmc->setCoordsAt(1,arr); + } + if(cz) + { + MCAuto arr(ConvertVTKArrayToMCArrayDoubleForced(cz)); + cmeshmc->setCoordsAt(2,arr); + } + std::string meshName(GetMeshNameWithContext(context)); + cmeshmc->setName(meshName); + cmesh->setMesh(cmeshmc); + std::vector > cellFs(AddPartFields(0,ds->GetCellData())); + for(std::vector >::const_iterator it=cellFs.begin();it!=cellFs.end();it++) + { + MCAuto da(*it); + AppendMCFieldFrom(MEDCoupling::ON_CELLS,cmeshmc,ret,da,NULL,timeStep,tsId); + } + std::vector > nodeFs(AddPartFields(0,ds->GetPointData())); + for(std::vector >::const_iterator it=nodeFs.begin();it!=nodeFs.end();it++) + { + MCAuto da(*it); + AppendMCFieldFrom(MEDCoupling::ON_NODES,cmeshmc,ret,da,NULL,timeStep,tsId); + } +} + +void ConvertFromPolyData(MEDFileData *ret, vtkPolyData *ds, const std::vector& context, double timeStep, int tsId) +{ + if(!ds || !ret) + throw MZCException("ConvertFromPolyData : internal error !"); + // + MCAuto meshes(MEDFileMeshes::New()); + ret->setMeshes(meshes); + MCAuto fields(MEDFileFields::New()); + ret->setFields(fields); + // + MCAuto umesh(MEDFileUMesh::New()); + meshes->pushMesh(umesh); + MCAuto coords(BuildCoordsFrom(ds)); + umesh->setCoords(coords); + umesh->setName(GetMeshNameWithContext(context)); + // + int offset(0); + std::vector< MicroField > ms; + vtkCellArray *cd(ds->GetVerts()); + if(cd) + { + MCAuto subMesh(BuildMeshFromCellArray(cd,coords,0,INTERP_KERNEL::NORM_POINT1)); + if((const MEDCouplingUMesh *)subMesh) + { + std::vector > cellFs(AddPartFields2(offset,offset+subMesh->getNumberOfCells(),ds->GetCellData())); + offset+=subMesh->getNumberOfCells(); + ms.push_back(MicroField(subMesh,cellFs)); + } + } + vtkCellArray *cc(ds->GetLines()); + if(cc) + { + MCAuto subMesh; + try + { + subMesh=BuildMeshFromCellArray(cc,coords,1,INTERP_KERNEL::NORM_SEG2); + } + catch(INTERP_KERNEL::Exception& e) + { + std::ostringstream oss; oss << "MEDWriter does not manage polyline cell type because MED file format does not support it ! Maybe it is the source of the problem ? The cause of this exception was " << e.what() << std::endl; + throw INTERP_KERNEL::Exception(oss.str()); + } + if((const MEDCouplingUMesh *)subMesh) + { + std::vector > cellFs(AddPartFields2(offset,offset+subMesh->getNumberOfCells(),ds->GetCellData())); + offset+=subMesh->getNumberOfCells(); + ms.push_back(MicroField(subMesh,cellFs)); + } + } + vtkCellArray *cb(ds->GetPolys()); + if(cb) + { + MCAuto subMesh(BuildMeshFromCellArray(cb,coords,2,INTERP_KERNEL::NORM_POLYGON)); + if((const MEDCouplingUMesh *)subMesh) + { + std::vector > cellFs(AddPartFields2(offset,offset+subMesh->getNumberOfCells(),ds->GetCellData())); + offset+=subMesh->getNumberOfCells(); + ms.push_back(MicroField(subMesh,cellFs)); + } + } + vtkCellArray *ca(ds->GetStrips()); + if(ca) + { + MCAuto ids; + MCAuto subMesh(BuildMeshFromCellArrayTriangleStrip(ca,coords,ids)); + if((const MEDCouplingUMesh *)subMesh) + { + std::vector > cellFs(AddPartFields(ids,ds->GetCellData())); + offset+=subMesh->getNumberOfCells(); + ms.push_back(MicroField(subMesh,cellFs)); + } + } + AssignSingleGTMeshes(ret,ms,timeStep,tsId); + AddNodeFields(ret,ds->GetPointData(),timeStep,tsId); +} + +void ConvertFromUnstructuredGrid(MEDFileData *ret, vtkUnstructuredGrid *ds, const std::vector& context, double timeStep, int tsId) +{ + if(!ds || !ret) + throw MZCException("ConvertFromUnstructuredGrid : internal error !"); + // + MCAuto meshes(MEDFileMeshes::New()); + ret->setMeshes(meshes); + MCAuto fields(MEDFileFields::New()); + ret->setFields(fields); + // + MCAuto umesh(MEDFileUMesh::New()); + meshes->pushMesh(umesh); + MCAuto coords(BuildCoordsFrom(ds)); + umesh->setCoords(coords); + umesh->setName(GetMeshNameWithContext(context)); + vtkIdType nbCells(ds->GetNumberOfCells()); + vtkCellArray *ca(ds->GetCells()); + if(!ca) + return ; + vtkIdType nbEnt(ca->GetNumberOfConnectivityEntries()); + vtkIdType *caPtr(ca->GetData()->GetPointer(0)); + vtkUnsignedCharArray *ct(ds->GetCellTypesArray()); + if(!ct) + throw MZCException("ConvertFromUnstructuredGrid : internal error"); + vtkIdTypeArray *cla(ds->GetCellLocationsArray()); + const vtkIdType *claPtr(cla->GetPointer(0)); + if(!cla) + throw MZCException("ConvertFromUnstructuredGrid : internal error 2"); + const unsigned char *ctPtr(ct->GetPointer(0)); + std::map m(ComputeMapOfType()); + MCAuto lev(DataArrayInt::New()) ; lev->alloc(nbCells,1); + int *levPtr(lev->getPointer()); + for(vtkIdType i=0;i::iterator it(m.find(ctPtr[i])); + if(it!=m.end()) + { + const INTERP_KERNEL::CellModel& cm(INTERP_KERNEL::CellModel::GetCellModel((INTERP_KERNEL::NormalizedCellType)(*it).second)); + levPtr[i]=cm.getDimension(); + } + else + { + if(ctPtr[i]==VTK_POLY_VERTEX) + { + const INTERP_KERNEL::CellModel& cm(INTERP_KERNEL::CellModel::GetCellModel(INTERP_KERNEL::NORM_POINT1)); + levPtr[i]=cm.getDimension(); + } + else + { + std::ostringstream oss; oss << "ConvertFromUnstructuredGrid : at pos #" << i << " unrecognized VTK cell with type =" << ctPtr[i]; + throw MZCException(oss.str()); + } + } + } + int dummy(0); + MCAuto levs(lev->getDifferentValues()); + std::vector< MicroField > ms; + vtkIdTypeArray *faces(ds->GetFaces()),*faceLoc(ds->GetFaceLocations()); + for(const int *curLev=levs->begin();curLev!=levs->end();curLev++) + { + MCAuto m0(MEDCouplingUMesh::New("",*curLev)); + m0->setCoords(coords); m0->allocateCells(); + MCAuto cellIdsCurLev(lev->findIdsEqual(*curLev)); + for(const mcIdType *cellId=cellIdsCurLev->begin();cellId!=cellIdsCurLev->end();cellId++) + { + int vtkType(ctPtr[*cellId]); + std::map::iterator it(m.find(vtkType)); + vtkIdType offset(claPtr[*cellId]); + vtkIdType sz(caPtr[offset]); + INTERP_KERNEL::NormalizedCellType ct=it!=m.end()?(INTERP_KERNEL::NormalizedCellType)((*it).second):INTERP_KERNEL::NORM_POINT1; + if(ct!=INTERP_KERNEL::NORM_POLYHED && vtkType!=VTK_POLY_VERTEX) + { + std::vector conn2(sz); + for(int kk=0;kkinsertNextCell(ct,sz,&conn2[0]); + } + else if(ct==INTERP_KERNEL::NORM_POLYHED) + { + if(!faces || !faceLoc) + throw MZCException("ConvertFromUnstructuredGrid : faces are expected when there are polyhedra !"); + const vtkIdType *facPtr(faces->GetPointer(0)),*facLocPtr(faceLoc->GetPointer(0)); + std::vector conn; + int off0(facLocPtr[*cellId]); + int nbOfFaces(facPtr[off0++]); + for(int k=0;kinsertNextCell(ct,ToIdType(conn.size()),&conn[0]); + } + else + { + if(sz!=1) + throw MZCException("ConvertFromUnstructuredGrid : non single poly vertex not managed by MED !"); + m0->insertNextCell(ct,1,(const mcIdType*)(caPtr+offset+1)); + } + } + std::vector > cellFs(AddPartFields(cellIdsCurLev,ds->GetCellData())); + ms.push_back(MicroField(m0,cellFs)); + } + AssignSingleGTMeshes(ret,ms,timeStep,tsId); + AddNodeFields(ret,ds->GetPointData(),timeStep,tsId); +} + +/////////////////// + +void WriteMEDFileFromVTKDataSet(MEDFileData *mfd, vtkDataSet *ds, const std::vector& context, double timeStep, int tsId) +{ + if(!ds || !mfd) + throw MZCException("Internal error in WriteMEDFileFromVTKDataSet."); + vtkPolyData *ds2(vtkPolyData::SafeDownCast(ds)); + vtkUnstructuredGrid *ds3(vtkUnstructuredGrid::SafeDownCast(ds)); + vtkRectilinearGrid *ds4(vtkRectilinearGrid::SafeDownCast(ds)); + if(ds2) + { + ConvertFromPolyData(mfd,ds2,context,timeStep,tsId); + } + else if(ds3) + { + ConvertFromUnstructuredGrid(mfd,ds3,context,timeStep,tsId); + } + else if(ds4) + { + ConvertFromRectilinearGrid(mfd,ds4,context,timeStep,tsId); + } + else + throw MZCException("Unrecognized vtkDataSet ! Sorry ! Try to convert it to UnstructuredGrid to be able to write it !"); +} + +void WriteMEDFileFromVTKMultiBlock(MEDFileData *mfd, vtkMultiBlockDataSet *ds, const std::vector& context, double timeStep, int tsId) +{ + if(!ds || !mfd) + throw MZCException("Internal error in WriteMEDFileFromVTKMultiBlock."); + int nbBlocks(ds->GetNumberOfBlocks()); + if(nbBlocks==1 && context.empty()) + { + vtkDataObject *uniqueElt(ds->GetBlock(0)); + if(!uniqueElt) + throw MZCException("Unique elt in multiblock is NULL !"); + vtkDataSet *uniqueEltc(vtkDataSet::SafeDownCast(uniqueElt)); + if(uniqueEltc) + { + WriteMEDFileFromVTKDataSet(mfd,uniqueEltc,context,timeStep,tsId); + return ; + } + } + for(int i=0;iGetBlock(i)); + std::vector context2; + context2.push_back(i); + if(!elt) + { + std::ostringstream oss; oss << "In context "; + std::copy(context.begin(),context.end(),std::ostream_iterator(oss," ")); + oss << " at pos #" << i << " elt is NULL !"; + throw MZCException(oss.str()); + } + vtkDataSet *elt1(vtkDataSet::SafeDownCast(elt)); + if(elt1) + { + WriteMEDFileFromVTKDataSet(mfd,elt1,context,timeStep,tsId); + continue; + } + vtkMultiBlockDataSet *elt2(vtkMultiBlockDataSet::SafeDownCast(elt)); + if(elt2) + { + WriteMEDFileFromVTKMultiBlock(mfd,elt2,context,timeStep,tsId); + continue; + } + std::ostringstream oss; oss << "In context "; + std::copy(context.begin(),context.end(),std::ostream_iterator(oss," ")); + oss << " at pos #" << i << " elt not recognized data type !"; + throw MZCException(oss.str()); + } +} + +void WriteMEDFileFromVTKGDS(MEDFileData *mfd, vtkDataObject *input, double timeStep, int tsId) +{ + if(!input || !mfd) + throw MZCException("WriteMEDFileFromVTKGDS : internal error !"); + std::vector context; + vtkDataSet *input1(vtkDataSet::SafeDownCast(input)); + if(input1) + { + WriteMEDFileFromVTKDataSet(mfd,input1,context,timeStep,tsId); + return ; + } + vtkMultiBlockDataSet *input2(vtkMultiBlockDataSet::SafeDownCast(input)); + if(input2) + { + WriteMEDFileFromVTKMultiBlock(mfd,input2,context,timeStep,tsId); + return ; + } + throw MZCException("WriteMEDFileFromVTKGDS : not recognized data type !"); +} + +void PutFamGrpInfoIfAny(MEDFileData *mfd, const std::string& meshName, const std::vector& groups, const std::vector& fams) +{ + if(!mfd) + return ; + if(meshName.empty()) + return ; + MEDFileMeshes *meshes(mfd->getMeshes()); + if(!meshes) + return ; + if(meshes->getNumberOfMeshes()!=1) + return ; + MEDFileMesh *mm(meshes->getMeshAtPos(0)); + if(!mm) + return ; + mm->setName(meshName); + for(std::vector::const_iterator it=fams.begin();it!=fams.end();it++) + mm->setFamilyId((*it).getName(),(*it).getID()); + for(std::vector::const_iterator it=groups.begin();it!=groups.end();it++) + mm->setFamiliesOnGroup((*it).getName(),(*it).getFamilies()); + MEDFileFields *fields(mfd->getFields()); + if(!fields) + return ; + for(int i=0;igetNumberOfFields();i++) + { + MEDFileAnyTypeFieldMultiTS *fmts(fields->getFieldAtPos(i)); + if(!fmts) + continue; + fmts->setMeshName(meshName); + } +} diff --git a/src/Plugins/MEDWriter/plugin/MEDWriterIO/VTKToMEDMem.h b/src/Plugins/MEDWriter/plugin/MEDWriterIO/VTKToMEDMem.h new file mode 100644 index 00000000..6f36d77f --- /dev/null +++ b/src/Plugins/MEDWriter/plugin/MEDWriterIO/VTKToMEDMem.h @@ -0,0 +1,88 @@ +// Copyright (C) 2017-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay (EDF R&D) + +#ifndef __VTKTOMEDMEM_HXX__ +#define __VTKTOMEDMEM_HXX__ + +#include "vtkSystemIncludes.h" //needed for exports + +#include "MEDCouplingRefCountObject.hxx" +#include "MEDCouplingMemArray.hxx" +#include "MEDCouplingFieldDouble.hxx" +#include "MEDCouplingFieldFloat.hxx" +#include "MEDCouplingFieldInt.hxx" +#include "MEDFileData.hxx" +#include "MEDFileField.hxx" +#include "MEDFileMesh.hxx" +#include "MEDLoaderTraits.hxx" + +#include +#include + +/////////////////// + +class vtkDataSet; + +class VTK_EXPORT MZCException : public std::exception +{ +public: + MZCException(const std::string& s):_reason(s) { } + virtual const char *what() const throw() { return _reason.c_str(); } + virtual ~MZCException() throw() { } +private: + std::string _reason; +}; + +namespace VTKToMEDMem +{ + class VTK_EXPORT Grp + { + public: + Grp(const std::string& name):_name(name) { } + void setFamilies(const std::vector& fams) { _fams=fams; } + std::string getName() const { return _name; } + std::vector getFamilies() const { return _fams; } + private: + std::string _name; + std::vector _fams; + }; + + class VTK_EXPORT Fam + { + public: + Fam(const std::string& name); + std::string getName() const { return _name; } + int getID() const { return _id; } + private: + std::string _name; + int _id; + }; +} + +class vtkDataObject; + +void VTK_EXPORT WriteMEDFileFromVTKDataSet(MEDCoupling::MEDFileData *mfd, vtkDataSet *ds, const std::vector& context, double timeStep, int tsId); + +void VTK_EXPORT WriteMEDFileFromVTKGDS(MEDCoupling::MEDFileData *mfd, vtkDataObject *input, double timeStep, int tsId); + +void VTK_EXPORT PutFamGrpInfoIfAny(MEDCoupling::MEDFileData *mfd, const std::string& meshName, const std::vector& groups, const std::vector& fams); + +#endif + diff --git a/src/Plugins/MEDWriter/plugin/MEDWriterIO/vtk.module b/src/Plugins/MEDWriter/plugin/MEDWriterIO/vtk.module new file mode 100644 index 00000000..091d107c --- /dev/null +++ b/src/Plugins/MEDWriter/plugin/MEDWriterIO/vtk.module @@ -0,0 +1,7 @@ +NAME + MEDWriterIO +DEPENDS + VTK::FiltersCore + VTK::CommonCore +PRIVATE_DEPENDS + VTK::FiltersGeneral diff --git a/src/Plugins/MEDWriter/plugin/MEDWriterIO/vtkMEDWriter.cxx b/src/Plugins/MEDWriter/plugin/MEDWriterIO/vtkMEDWriter.cxx new file mode 100644 index 00000000..1dfa3708 --- /dev/null +++ b/src/Plugins/MEDWriter/plugin/MEDWriterIO/vtkMEDWriter.cxx @@ -0,0 +1,320 @@ +// Copyright (C) 2016 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay (EDF R&D) + +#include "vtkMEDWriter.h" +#include "VTKToMEDMem.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "MEDCouplingFieldDouble.hxx" +#include "MEDCouplingFieldFloat.hxx" +#include "MEDCouplingFieldInt.hxx" +#include "MEDCouplingMemArray.hxx" +#include "MEDCouplingRefCountObject.hxx" +#include "MEDFileData.hxx" +#include "MEDFileField.hxx" +#include "MEDFileMesh.hxx" +#include "MEDLoaderTraits.hxx" + +#include +#include +#include + +vtkStandardNewMacro(vtkMEDWriter); + +using MEDCoupling::MCAuto; +using MEDCoupling::MEDFileData; +using VTKToMEDMem::Fam; +using VTKToMEDMem::Grp; + +vtkInformationDataObjectMetaDataKey* GetMEDReaderMetaDataIfAny() +{ + static const char ZE_KEY[] = "vtkMEDReader::META_DATA"; + MEDCoupling::GlobalDict* gd(MEDCoupling::GlobalDict::GetInstance()); + if (!gd->hasKey(ZE_KEY)) + return 0; + std::string ptSt(gd->value(ZE_KEY)); + void* pt(0); + std::istringstream iss(ptSt); + iss >> pt; + return reinterpret_cast(pt); +} + +bool IsInformationOK(vtkInformation* info) +{ + vtkInformationDataObjectMetaDataKey* key(GetMEDReaderMetaDataIfAny()); + if (!key) + return false; + // Check the information contain meta data key + if (!info->Has(key)) + return false; + // Recover Meta Data + vtkMutableDirectedGraph* sil(vtkMutableDirectedGraph::SafeDownCast(info->Get(key))); + if (!sil) + return false; + int idNames(0); + vtkAbstractArray* verticesNames(sil->GetVertexData()->GetAbstractArray("Names", idNames)); + vtkStringArray* verticesNames2(vtkStringArray::SafeDownCast(verticesNames)); + if (!verticesNames2) + return false; + for (int i = 0; i < verticesNames2->GetNumberOfValues(); i++) + { + vtkStdString& st(verticesNames2->GetValue(i)); + if (st == "MeshesFamsGrps") + return true; + } + return false; +} + +void LoadFamGrpMapInfo(vtkMutableDirectedGraph* sil, std::string& meshName, + std::vector& groups, std::vector& fams) +{ + if (!sil) + throw MZCException("LoadFamGrpMapInfo : internal error !"); + int idNames(0); + vtkAbstractArray* verticesNames(sil->GetVertexData()->GetAbstractArray("Names", idNames)); + vtkStringArray* verticesNames2(vtkStringArray::SafeDownCast(verticesNames)); + vtkIdType id0; + bool found(false); + for (int i = 0; i < verticesNames2->GetNumberOfValues(); i++) + { + vtkStdString& st(verticesNames2->GetValue(i)); + if (st == "MeshesFamsGrps") + { + id0 = i; + found = true; + } + } + if (!found) + throw INTERP_KERNEL::Exception( + "There is an internal error ! The tree on server side has not the expected look !"); + vtkAdjacentVertexIterator* it0(vtkAdjacentVertexIterator::New()); + sil->GetAdjacentVertices(id0, it0); + int kk(0), ll(0); + while (it0->HasNext()) + { + vtkIdType id1(it0->Next()); + std::string mName((const char*)verticesNames2->GetValue(id1)); + meshName = mName; + vtkAdjacentVertexIterator* it1(vtkAdjacentVertexIterator::New()); + sil->GetAdjacentVertices(id1, it1); + vtkIdType idZeGrps(it1->Next()); // zeGroups + vtkAdjacentVertexIterator* itGrps(vtkAdjacentVertexIterator::New()); + sil->GetAdjacentVertices(idZeGrps, itGrps); + while (itGrps->HasNext()) + { + vtkIdType idg(itGrps->Next()); + Grp grp((const char*)verticesNames2->GetValue(idg)); + vtkAdjacentVertexIterator* itGrps2(vtkAdjacentVertexIterator::New()); + sil->GetAdjacentVertices(idg, itGrps2); + std::vector famsOnGroup; + while (itGrps2->HasNext()) + { + vtkIdType idgf(itGrps2->Next()); + famsOnGroup.push_back(std::string((const char*)verticesNames2->GetValue(idgf))); + } + grp.setFamilies(famsOnGroup); + itGrps2->Delete(); + groups.push_back(grp); + } + itGrps->Delete(); + vtkIdType idZeFams(it1->Next()); // zeFams + it1->Delete(); + vtkAdjacentVertexIterator* itFams(vtkAdjacentVertexIterator::New()); + sil->GetAdjacentVertices(idZeFams, itFams); + while (itFams->HasNext()) + { + vtkIdType idf(itFams->Next()); + Fam fam((const char*)verticesNames2->GetValue(idf)); + fams.push_back(fam); + } + itFams->Delete(); + } + it0->Delete(); +} + +vtkMEDWriter::vtkMEDWriter() + : WriteAllTimeSteps(0) + , NumberOfTimeSteps(0) + , CurrentTimeIndex(0) + , FileName(0) +{ +} + +vtkMEDWriter::~vtkMEDWriter() {} + +int vtkMEDWriter::RequestInformation( + vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector) +{ + // std::cerr << "########################################## vtkMEDWriter::RequestInformation + // ########################################## " << (const char *) this->FileName << std::endl; + vtkInformation* inInfo(inputVector[0]->GetInformationObject(0)); + if (inInfo->Has(vtkStreamingDemandDrivenPipeline::TIME_STEPS())) + this->NumberOfTimeSteps = inInfo->Length(vtkStreamingDemandDrivenPipeline::TIME_STEPS()); + else + this->NumberOfTimeSteps = 0; + return 1; +} + +int vtkMEDWriter::RequestUpdateExtent(vtkInformation* vtkNotUsed(request), + vtkInformationVector** inputVector, vtkInformationVector* vtkNotUsed(outputVector)) +{ + double* inTimes( + inputVector[0]->GetInformationObject(0)->Get(vtkStreamingDemandDrivenPipeline::TIME_STEPS())); + if (inTimes && this->WriteAllTimeSteps) + { + double timeReq(inTimes[this->CurrentTimeIndex]); + inputVector[0]->GetInformationObject(0)->Set( + vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP(), timeReq); + } + return 1; +} + +void ExceptionDisplayer(vtkMEDWriter* self, const std::string& fileName, std::exception& e) +{ + std::ostringstream oss; + oss << "Exception has been thrown in vtkMEDWriter::RequestData : During writing of \"" << fileName + << "\", the following exception has been thrown : " << e.what() << std::endl; + if (self->HasObserver("ErrorEvent")) + self->InvokeEvent("ErrorEvent", const_cast(oss.str().c_str())); + else + vtkOutputWindowDisplayErrorText(const_cast(oss.str().c_str())); + vtkObject::BreakOnError(); +} + +int vtkMEDWriter::RequestData( + vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector) +{ + // std::cerr << "########################################## vtkMEDWriter::RequestData + // ########################################## " << (const char *) this->FileName << std::endl; + try + { + bool writeAll((this->WriteAllTimeSteps != 0 && this->NumberOfTimeSteps > 0)); + if (writeAll) + { + if (this->CurrentTimeIndex == 0) + request->Set(vtkStreamingDemandDrivenPipeline::CONTINUE_EXECUTING(), 1); + } + else + { + request->Remove(vtkStreamingDemandDrivenPipeline::CONTINUE_EXECUTING()); + this->CurrentTimeIndex = 0; + } + ////////////// + vtkInformation* inputInfo(inputVector[0]->GetInformationObject(0)); + std::string meshName; + std::vector groups; + std::vector fams; + if (IsInformationOK(inputInfo)) + { + vtkMutableDirectedGraph* famGrpGraph( + vtkMutableDirectedGraph::SafeDownCast(inputInfo->Get(GetMEDReaderMetaDataIfAny()))); + LoadFamGrpMapInfo(famGrpGraph, meshName, groups, fams); + } + vtkInformation* outInfo(outputVector->GetInformationObject(0)); + vtkDataObject* input(vtkDataObject::SafeDownCast(inputInfo->Get(vtkDataObject::DATA_OBJECT()))); + if (!input) + throw MZCException( + "Not recognized data object in input of the MEDWriter ! Maybe not implemented yet !"); + double timeStep; + { + vtkInformation* inInfo(inputVector[0]->GetInformationObject(0)); + vtkDataObject* input(vtkDataObject::GetData(inInfo)); + timeStep = input->GetInformation()->Get(vtkDataObject::DATA_TIME_STEP()); + } + //////////// + MCAuto mfd(MEDFileData::New()); + WriteMEDFileFromVTKGDS(mfd, input, timeStep, this->CurrentTimeIndex); + PutFamGrpInfoIfAny(mfd, meshName, groups, fams); + if (this->WriteAllTimeSteps == 0 || + (this->WriteAllTimeSteps != 0 && this->CurrentTimeIndex == 0)) + mfd->write(this->FileName, 2); + else + { + mfd->getFields()->write(this->FileName, 0); + } + outInfo->Set(vtkDataObject::DATA_OBJECT(), input); + /////////// + if (writeAll) + { + this->CurrentTimeIndex++; + if (this->CurrentTimeIndex >= this->NumberOfTimeSteps) + { + request->Remove(vtkStreamingDemandDrivenPipeline::CONTINUE_EXECUTING()); + this->CurrentTimeIndex = 0; + } + } + } + catch (INTERP_KERNEL::Exception& e) + { + ExceptionDisplayer(this, (const char*)this->FileName, e); + return 0; + } + catch (MZCException& e) + { + ExceptionDisplayer(this, (const char*)this->FileName, e); + return 0; + } + return 1; +} + +void vtkMEDWriter::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os, indent); +} + +int vtkMEDWriter::Write() +{ + this->Update(); + return 0; +} diff --git a/src/Plugins/MEDWriter/plugin/MEDWriterIO/vtkMEDWriter.h b/src/Plugins/MEDWriter/plugin/MEDWriterIO/vtkMEDWriter.h new file mode 100644 index 00000000..8cc663c2 --- /dev/null +++ b/src/Plugins/MEDWriter/plugin/MEDWriterIO/vtkMEDWriter.h @@ -0,0 +1,60 @@ +// Copyright (C) 2016 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay (EDF R&D) + +#ifndef vtkMEDWriter_h__ +#define vtkMEDWriter_h__ + +#include "vtkDataObjectAlgorithm.h" + +class vtkMutableDirectedGraph; + +class VTK_EXPORT vtkMEDWriter : public vtkDataObjectAlgorithm +{ +public: + static vtkMEDWriter* New(); + vtkTypeMacro(vtkMEDWriter, vtkDataObjectAlgorithm) + void PrintSelf(ostream& os, vtkIndent indent); + + vtkSetStringMacro(FileName); + vtkGetStringMacro(FileName); + int Write(); + vtkGetMacro(WriteAllTimeSteps, int); + vtkSetMacro(WriteAllTimeSteps, int); + vtkBooleanMacro(WriteAllTimeSteps, int); +protected: + vtkMEDWriter(); + ~vtkMEDWriter(); + + int RequestInformation(vtkInformation *request, vtkInformationVector **inputVector, vtkInformationVector *outputVector); + int RequestData(vtkInformation *request, vtkInformationVector **inputVector, vtkInformationVector *outputVector); + int RequestUpdateExtent(vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector); +private: + vtkMEDWriter(const vtkMEDWriter&); + void operator=(const vtkMEDWriter&); // Not implemented. + private: + int WriteAllTimeSteps; + int NumberOfTimeSteps; + int CurrentTimeIndex; + char *FileName; + //BTX + //ETX +}; + +#endif diff --git a/src/Plugins/MEDWriter/plugin/Test/TestMEDWriter0.py b/src/Plugins/MEDWriter/plugin/Test/TestMEDWriter0.py new file mode 100644 index 00000000..8cf8cb79 --- /dev/null +++ b/src/Plugins/MEDWriter/plugin/Test/TestMEDWriter0.py @@ -0,0 +1,242 @@ +# Copyright (C) 2016-2019 CEA/DEN, EDF R&D +# +# This library 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. +# +# 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 +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +# +# Author : Anthony Geay (EDF R&D) + +#### import the simple module from the paraview +from paraview.simple import * +import MEDLoader as ml +import os +from math import pi,sqrt + +#### disable automatic camera reset on 'Show' +paraview.simple._DisableFirstRenderCameraReset() + +pat='testMEDWriter_%i.med' +fname0=pat%0 +fname1=pat%1 +fname2=pat%2 +fname3=pat%3 +fname4=pat%4 +fname4_vtp=os.path.splitext(pat%4)[0]+".vtp" +fname5=pat%5 +fname6_vtu=os.path.splitext(pat%6)[0]+".vtu" +fname6=pat%6 +fname7_vtu=os.path.splitext(pat%7)[0]+".vtu" +fname7=pat%7 +fname8_vtr=os.path.splitext(pat%8)[0]+".vtr" +fname8=pat%8 + +##### First test with a simple sphere + +plane1 = Sphere() +SaveData(fname0,proxy=plane1,WriteAllTimeSteps=1) +# +totomed=MEDReader(FileName=fname0) +totomed.AllArrays=['TS0/Mesh/ComSup0/Mesh@@][@@P0'] +totomed.AllTimeSteps=['0000'] +SaveData(fname1,proxy=totomed,WriteAllTimeSteps=1) +# Sphere has been written. Try to check to write it in MED file ! +mfd=ml.MEDFileData(fname0) +mm=mfd.getMeshes()[0] ; m0=mm[0] +area=m0.getMeasureField(ml.ON_CELLS).accumulate()[0] +assert(abs(sqrt(area/(4*pi))-0.975/2.)<0.01) # 4*pi*radius**2 +f=mfd.getFields()[0][0].getFieldOnMeshAtLevel(ml.ON_NODES,0,mm) +assert(abs(ml.DataArrayDouble(f.accumulate(),1,3).magnitude()[0])<1e-12) # sum of all normal vector should be 0 + + +##### Build a MED file from scratch + +fieldName0="F0" +fieldName1="F1" +c=ml.DataArrayDouble([0.,0.,1.,1.,2.,2.,1.,0.,2.,0.,0.,2.,1.,2.,0.,1.,2.,1.],9,2) +c.setInfoOnComponents(["X abc","Y defg"]) +# +mName="mesh" +m0=ml.MEDCouplingUMesh(mName,2) ; m0.allocateCells() ; m0.setCoords(c) +m0.insertNextCell(ml.NORM_TRI3,[3,1,4]) +m0.insertNextCell(ml.NORM_TRI3,[1,8,4]) +m0.insertNextCell(ml.NORM_QUAD4,[0,7,1,3]) +m0.insertNextCell(ml.NORM_QUAD4,[1,6,2,4]) +m0.insertNextCell(ml.NORM_QUAD4,[7,5,6,1]) +m1=ml.MEDCouplingUMesh(mName,1) ; m1.allocateCells() ; m1.setCoords(c) +m1.insertNextCell(ml.NORM_SEG2,[0,7]) +m1.insertNextCell(ml.NORM_SEG2,[7,5]) +m1.insertNextCell(ml.NORM_SEG2,[5,6]) +mm=ml.MEDFileUMesh() ; mm[0]=m0 ; mm[-1]=m1 +mm.setFamilyFieldArr(1,ml.DataArrayInt([200,201,202,203,204,205,206,207,208])) +mm.setFamilyFieldArr(0,ml.DataArrayInt([100,101,102,103,104])) +mm.setFamilyFieldArr(-1,ml.DataArrayInt([105,106,107])) +mm.setFamilyId("Fam3",3) ; mm.setFamilyId("Fam5",7) +mm.setFamiliesOnGroup("gr0",["Fam3"]) +mm.setFamiliesOnGroup("gr1",["Fam5"]) +mm.setFamiliesOnGroup("gr2",["Fam3","Fam5"]) +mm.write(fname2,2) +# +f1ts0=ml.MEDFileField1TS() +f0=ml.MEDCouplingFieldDouble(ml.ON_CELLS) ; f0.setName(fieldName0) +f0.setMesh(m0) ; f0.setArray(ml.DataArrayDouble([8,7,6,5,4])) +f1ts0.setFieldNoProfileSBT(f0) +f0=ml.MEDCouplingFieldDouble(ml.ON_CELLS) ; f0.setName(fieldName0) +f0.setMesh(m1) ; f0.setArray(ml.DataArrayDouble([3,2,1])) +f1ts0.setFieldNoProfileSBT(f0) +f1ts0.write(fname2,0) +# +f1ts1=ml.MEDFileField1TS() +f0=ml.MEDCouplingFieldDouble(ml.ON_NODES) ; f0.setName(fieldName1) +arr=ml.DataArrayDouble([9,109,8,108,7,107,6,106,5,105,4,104,3,103,2,102,1,101],9,2) +arr.setInfoOnComponents(["aa","bbb"]) +f0.setMesh(m0) ; f0.setArray(arr) +f1ts1.setFieldNoProfileSBT(f0) +f1ts1.write(fname2,0) +# +test3=MEDReader(FileName=fname2) +test3.AllArrays=['TS0/%s/ComSup0/%s@@][@@P0'%(mName,fieldName0),'TS0/%s/ComSup0/%s@@][@@P1'%(mName,fieldName1)] +test3.AllTimeSteps = ['0000'] +SaveData(fname3,proxy=test3,WriteAllTimeSteps=1) +### test content of fname3 +mfd2=ml.MEDFileData(fname3) +mm2=mfd2.getMeshes()[0] +c1=mm2.getCoords() +assert(c.isEqualWithoutConsideringStr(c1[:,:2],1e-12)) +fs2=ml.MEDFileFields(fname3) +assert(len(fs2)==2) +assert(mm2.getSpaceDimension()==3) ; assert(mm2.getCoords()[:,2].isUniform(0.,0.)) +m2_0=mm2[0].deepCopy() ; m2_0.changeSpaceDimension(2,0.) ; m2_0.getCoords().setInfoOnComponents(mm[0].getCoords().getInfoOnComponents()) +assert(m2_0.isEqual(mm[0],1e-12)) +m2_1=mm2[-1].deepCopy() ; m2_1.changeSpaceDimension(2,0.) ; m2_1.getCoords().setInfoOnComponents(mm[0].getCoords().getInfoOnComponents()) +assert(m2_1.isEqual(mm[-1],1e-12)) +f2_0=mfd2.getFields()[fieldName0][0].getFieldOnMeshAtLevel(ml.ON_CELLS,0,mm2) ; f2_0.setMesh(m2_0) +assert(f1ts0.getFieldOnMeshAtLevel(ml.ON_CELLS,0,mm).isEqual(f2_0,1e-12,1e-12)) +f2_1=mfd2.getFields()[fieldName1][0].getFieldOnMeshAtLevel(ml.ON_NODES,0,mm2) ; f2_1.setMesh(m2_0) +assert(f1ts1.getFieldOnMeshAtLevel(ml.ON_NODES,0,mm).isEqual(f2_1,1e-12,1e-12)) +assert(mm2.getGroupsNames()==('gr0','gr1','gr2')) +assert(mm2.getFamiliesOnGroup("gr0")==("Fam3",)) +assert(mm2.getFamiliesOnGroup("gr1")==("Fam5",)) +assert(mm2.getFamiliesOnGroup("gr2")==("Fam3","Fam5")) +assert(mm2.getFamiliesNames()==('FAMILLE_ZERO','Fam3','Fam5')) +assert([mm2.getFamilyId(elt) for elt in ['FAMILLE_ZERO','Fam3','Fam5']]==[0,3,7]) +assert(mm2.getFamilyFieldAtLevel(0).isEqual(mm.getFamilyFieldAtLevel(0))) +assert(mm2.getFamilyFieldAtLevel(-1).isEqual(mm.getFamilyFieldAtLevel(-1))) +assert(mm2.getFamilyFieldAtLevel(1).isEqual(mm.getFamilyFieldAtLevel(1))) +# Write a polydata mesh +mergeBlocks1 = MergeBlocks(Input=test3) +extractSurface1 = ExtractSurface(Input=mergeBlocks1) +SaveData(fname4_vtp,proxy=extractSurface1) +test4vtp = XMLPolyDataReader(FileName=[fname4_vtp]) +test4vtp.CellArrayStatus = ['F0', 'FamilyIdCell'] +SaveData(fname5,proxy=test4vtp,WriteAllTimeSteps=1) +### test content of fname5 +mfd5=ml.MEDFileData(fname5) +m5=mfd5.getMeshes()[0][0].deepCopy() +assert(m5.getSpaceDimension()==3) # +m5.setName(mm.getName()) ; m5.changeSpaceDimension(2,0.) ; m5.getCoords().setInfoOnComponents(mm[0].getCoords().getInfoOnComponents()) +bary5=m5.computeCellCenterOfMass() +bary=mm[0].computeCellCenterOfMass() +a,b=bary5.areIncludedInMe(bary,1e-12) ; assert(a) +a,c=mm[0].getCoords().areIncludedInMe(m5.getCoords(),1e-12) ; assert(a) +m5.renumberNodes(c,len(c))#c.invertArrayO2N2N2O(len(c))) +assert(m5.unPolyze()) +assert(m5.getCoords().isEqual(mm[0].getCoords(),1e-12)) +assert(m5.isEqual(mm[0],1e-12)) +f5_0=mfd5.getFields()[fieldName0][0].getFieldOnMeshAtLevel(ml.ON_CELLS,0,mfd5.getMeshes()[0]) ; f5_0.setMesh(m5) +assert(f1ts0.getFieldOnMeshAtLevel(ml.ON_CELLS,0,mm).isEqual(f5_0,1e-12,1e-12)) +f5_1=mfd5.getFields()[fieldName1][0].getFieldOnMeshAtLevel(ml.ON_NODES,0,mfd5.getMeshes()[0]) ; f5_1.setMesh(m5) +f5_1.setArray(f5_1.getArray()[c.invertArrayO2N2N2O(len(c))]) +assert(f1ts1.getFieldOnMeshAtLevel(ml.ON_NODES,0,mm).isEqual(f5_1,1e-12,1e-12)) + +### test with a non geo types non sorted + +c=ml.DataArrayDouble([0.,0.,1.,1.,2.,2.,1.,0.,2.,0.,0.,2.,1.,2.,0.,1.,2.,1.],9,2) +c.setInfoOnComponents(["X abc","Y defg"]) +m6=ml.MEDCouplingUMesh(mName,2) ; m6.allocateCells() ; m6.setCoords(c) +m6.insertNextCell(ml.NORM_TRI3,[3,1,4]) +m6.insertNextCell(ml.NORM_QUAD4,[0,7,1,3]) +m6.insertNextCell(ml.NORM_TRI3,[1,8,4]) +m6.insertNextCell(ml.NORM_QUAD4,[1,6,2,4]) +m6.insertNextCell(ml.NORM_QUAD4,[7,5,6,1]) +fieldName6="F6" +f6=ml.MEDCouplingFieldDouble(ml.ON_CELLS) ; f6.setMesh(m6) ; f6.setName(fieldName6) +f6.setArray(ml.DataArrayDouble([20,21,22,23,24])) +f6.writeVTK(fname6_vtu) +test6vtu=XMLUnstructuredGridReader(FileName=[fname6_vtu]) +SaveData(fname6,proxy=test6vtu,WriteAllTimeSteps=1) +mfd7=ml.MEDFileData(fname6) +assert(len(mfd7.getMeshes())==1) +m7=mfd7.getMeshes()[0][0] +assert(len(mfd7.getFields())==1) +f7=mfd7.getFields()[0][0].getFieldOnMeshAtLevel(ml.ON_CELLS,0,mfd7.getMeshes()[0]) +assert(f7.getMesh().isEqual(m7,1e-12)) +assert(m7.getCoords()[:,:2].isEqualWithoutConsideringStr(m6.getCoords(),1e-12)) +assert(m7.getNodalConnectivity().isEqual(ml.DataArrayInt([3,3,1,4,3,1,8,4,4,0,7,1,3,4,1,6,2,4,4,7,5,6,1]))) # there is a permutation of cells +assert(m7.getNodalConnectivityIndex().isEqual(ml.DataArrayInt([0,4,8,13,18,23]))) # there is a permutation of cells +assert(f7.getArray().isEqual(ml.DataArrayDouble([20,22,21,23,24]),1e-12)) # there is a permutation of cells + +### test with polyhedron + +m8=ml.MEDCouplingCMesh() ; m8.setCoords(ml.DataArrayDouble([0,1,2,3]),ml.DataArrayDouble([0,1]),ml.DataArrayDouble([0,1])) +m8=m8.buildUnstructured() +m8_0=m8[0] ; m8_0.simplexize(ml.PLANAR_FACE_5) +m8_1=m8[1:] +m8_1.convertAllToPoly() +m8=ml.MEDCouplingUMesh.MergeUMeshesOnSameCoords([m8_0,m8_1]) +m8=m8[[0,5,1,2,6,3,4]] +fieldName8="F8" +f8=ml.MEDCouplingFieldDouble(ml.ON_CELLS) ; f8.setMesh(m8) ; f8.setName(fieldName8) +f8.setArray(ml.DataArrayDouble([20,21,22,23,24,25,26])) +f8.writeVTK(fname7_vtu) +test8vtu=XMLUnstructuredGridReader(FileName=[fname7_vtu]) +SaveData(fname7,proxy=test8vtu,WriteAllTimeSteps=1) +mfd9=ml.MEDFileData(fname7) +assert(len(mfd9.getMeshes())==1) +m9=mfd9.getMeshes()[0][0] +assert(len(mfd9.getFields())==1) +assert(m9.getCoords().isEqual(m8.getCoords(),1e-12)) +c9=ml.DataArrayInt([0,2,3,5,6,1,4]) +assert(m8[c9].isEqualWithoutConsideringStr(m9,1e-12)) +f9=mfd9.getFields()[0][0].getFieldOnMeshAtLevel(ml.ON_CELLS,0,mfd9.getMeshes()[0]) +assert(f9.getArray().isEqual(f8.getArray()[c9],1e-12)) + +### test with cartesian + +FieldName10="F10" +FieldName10_n="F10_n" +m10=ml.MEDCouplingCMesh() +m10.setCoordsAt(0,ml.DataArrayDouble([0,1,2])) +m10.setCoordsAt(1,ml.DataArrayDouble([1,2,3,4])) +m10.setCoordsAt(2,ml.DataArrayDouble([3,5,6,7,8])) +f10=ml.MEDCouplingFieldDouble(ml.ON_CELLS) ; f10.setMesh(m10) +f10.setName(FieldName10) +f10.setArray(ml.DataArrayInt.Range(0,m10.getNumberOfCells(),1).convertToDblArr()) ; f10.checkConsistencyLight() +f10_n=ml.MEDCouplingFieldDouble(ml.ON_NODES) ; f10_n.setMesh(m10) +f10_n.setName(FieldName10_n) +f10_n.setArray(ml.DataArrayInt.Range(0,m10.getNumberOfNodes(),1).convertToDblArr()) ; f10_n.checkConsistencyLight() +ml.MEDCouplingFieldDouble.WriteVTK(fname8_vtr,[f10,f10_n]) +test10vtr=XMLRectilinearGridReader(FileName=[fname8_vtr]) +SaveData(fname8,proxy=test10vtr,WriteAllTimeSteps=1) +mfd11=ml.MEDFileData(fname8) +assert(len(mfd11.getMeshes())==1) +assert(len(mfd11.getFields())==2) +mfd11=ml.MEDFileData(fname8) +m11=mfd11.getMeshes()[0] +assert(isinstance(m11,ml.MEDFileCMesh)) +f11=mfd11.getFields()[FieldName10][0].getFieldOnMeshAtLevel(ml.ON_CELLS,0,m11) +f11_n=mfd11.getFields()[FieldName10_n][0].getFieldOnMeshAtLevel(ml.ON_NODES,0,m11) +assert(f11.isEqualWithoutConsideringStr(f10,1e-12,1e-12)) +assert(f11_n.isEqualWithoutConsideringStr(f10_n,1e-12,1e-12)) + diff --git a/src/Plugins/MEDWriter/plugin/paraview.plugin b/src/Plugins/MEDWriter/plugin/paraview.plugin new file mode 100644 index 00000000..2f596e55 --- /dev/null +++ b/src/Plugins/MEDWriter/plugin/paraview.plugin @@ -0,0 +1,6 @@ +NAME + MEDWriterPlugin +DESCRIPTION + This plugin provides the MED Writer. +REQUIRES_MODULES + VTK::CommonCore diff --git a/src/Plugins/MEDWriter/plugin/writers.xml b/src/Plugins/MEDWriter/plugin/writers.xml new file mode 100644 index 00000000..29239b8a --- /dev/null +++ b/src/Plugins/MEDWriter/plugin/writers.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + + + The input filter/source whose output dataset is written to the MED file. + + + + The name of the MED file to be written. + + + + When WriteAllTimeSteps is turned ON, the writer is executed once for each timestep available from the reader. + + + + + + + + + diff --git a/src/Plugins/ParaGEOMCorba/CMakeLists.txt b/src/Plugins/ParaGEOMCorba/CMakeLists.txt index 8f706e2f..c4dd0315 100644 --- a/src/Plugins/ParaGEOMCorba/CMakeLists.txt +++ b/src/Plugins/ParaGEOMCorba/CMakeLists.txt @@ -17,33 +17,67 @@ # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com # -PROJECT( ParaGEOMCorba ) - - CMAKE_MINIMUM_REQUIRED( VERSION 2.8.7 ) - FIND_PACKAGE(ParaView REQUIRED) - INCLUDE( ${PARAVIEW_USE_FILE} ) - SET( PARA_GEOM_CORBA_SRCS - ${ParaGEOMCorba_SOURCE_DIR}/vtkParaGEOMCorbaSource.cxx - ) - ADD_PARAVIEW_PLUGIN( ParaGEOMCorbaPlugin "1.0" - SERVER_MANAGER_XML ParaGEOMCorbaServerManager.xml - SERVER_MANAGER_SOURCES ${PARA_GEOM_CORBA_SRCS} ) +cmake_minimum_required(VERSION 3.8) +project(ParaGEOMCorba) + +include(GNUInstallDirs) +set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_BINDIR}") +set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_LIBDIR}") +set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_LIBDIR}") + +find_package(SalomeGEOM) + +include_directories( ${CMAKE_CURRENT_SOURCE_DIR}/plugin/ParaGEOMCorbaModule ) + +set("_paraview_plugin_default_${CMAKE_PROJECT_NAME}" ON) +paraview_plugin_scan( + ENABLE_BY_DEFAULT YES + PLUGIN_FILES "${CMAKE_CURRENT_SOURCE_DIR}/plugin/paraview.plugin" + PROVIDES_PLUGINS plugins + REQUIRES_MODULES required_modules) + +foreach(module IN LISTS required_modules) + if(NOT TARGET "${module}") + message("Missing required module: ${module}") + return() + endif() +endforeach() + +set(BUILD_SHARED_LIBS ON) +paraview_plugin_build( + RUNTIME_DESTINATION "${CMAKE_INSTALL_BINDIR}" + LIBRARY_DESTINATION "${CMAKE_INSTALL_LIBDIR}" + LIBRARY_SUBDIRECTORY "${PARAVIEW_PLUGIN_SUBDIR}" + PLUGINS ${plugins} + AUTOLOAD ${plugins}) + +# PROJECT( ParaGEOMCorba ) + +# CMAKE_MINIMUM_REQUIRED( VERSION 2.8.7 ) +# FIND_PACKAGE(ParaView REQUIRED) +# INCLUDE( ${PARAVIEW_USE_FILE} ) +# SET( PARA_GEOM_CORBA_SRCS +# ${ParaGEOMCorba_SOURCE_DIR}/vtkParaGEOMCorbaSource.cxx +# ) +# ADD_PARAVIEW_PLUGIN( ParaGEOMCorbaPlugin "1.0" +# SERVER_MANAGER_XML ParaGEOMCorbaServerManager.xml +# SERVER_MANAGER_SOURCES ${PARA_GEOM_CORBA_SRCS} ) - INCLUDE_DIRECTORIES( - ${OMNIORB_INCLUDE_DIR} - ${GEOM_ROOT_DIR}/include/salome - ${KERNEL_ROOT_DIR}/include/salome ) - - ADD_DEFINITIONS(${OMNIORB_DEFINITIONS}) - TARGET_LINK_LIBRARIES(ParaGEOMCorbaPlugin - ${OMNIORB_LIBRARIES} - ${KERNEL_SalomeIDLKernel} - ${KERNEL_SalomeLifeCycleCORBA} - ${KERNEL_SalomeNS} - ${GEOM_GEOMClient} - ${GEOM_SalomeIDLGEOM} - ${GEOM_OCC2VTK} - ) +# INCLUDE_DIRECTORIES( +# ${OMNIORB_INCLUDE_DIR} +# ${GEOM_ROOT_DIR}/include/salome +# ${KERNEL_ROOT_DIR}/include/salome ) +# +# ADD_DEFINITIONS(${OMNIORB_DEFINITIONS}) +# TARGET_LINK_LIBRARIES(ParaGEOMCorbaPlugin +# ${OMNIORB_LIBRARIES} +# ${KERNEL_SalomeIDLKernel} +# ${KERNEL_SalomeLifeCycleCORBA} +# ${KERNEL_SalomeNS} +# ${GEOM_GEOMClient} +# ${GEOM_SalomeIDLGEOM} +# ${GEOM_OCC2VTK} +# ) - INSTALL(TARGETS ParaGEOMCorbaPlugin DESTINATION lib/paraview) - INSTALL(FILES ParaGEOMCorbaServerManager.xml DESTINATION share) +# INSTALL(TARGETS ParaGEOMCorbaPlugin DESTINATION lib/paraview) +# INSTALL(FILES ParaGEOMCorbaServerManager.xml DESTINATION share) diff --git a/src/Plugins/ParaGEOMCorba/ParaGEOMCorbaServerManager.xml b/src/Plugins/ParaGEOMCorba/ParaGEOMCorbaServerManager.xml deleted file mode 100644 index 3f3085b7..00000000 --- a/src/Plugins/ParaGEOMCorba/ParaGEOMCorbaServerManager.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - - - - - Source of a remote Geometry Corba reference. - - - - This property specifies the IOR of a Geometry object in memory. - - - - - This property specifies the Deflection coefficient. - - - - - - - - - diff --git a/src/Plugins/ParaGEOMCorba/plugin/CMakeLists.txt b/src/Plugins/ParaGEOMCorba/plugin/CMakeLists.txt new file mode 100644 index 00000000..fe34202e --- /dev/null +++ b/src/Plugins/ParaGEOMCorba/plugin/CMakeLists.txt @@ -0,0 +1,31 @@ +# Copyright (C) 2010-2019 CEA/DEN, EDF R&D +# +# This library 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. +# +# 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 +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +# + +paraview_add_plugin(ParaGEOMCorbaPlugin + VERSION "1.0" + MODULES ParaGEOMCorbaModule + MODULE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/ParaGEOMCorbaModule/vtk.module" + SERVER_MANAGER_XML filters.xml +) + +install(TARGETS ParaGEOMCorbaPlugin + RUNTIME DESTINATION lib/paraview + LIBRARY DESTINATION lib/paraview + ARCHIVE DESTINATION lib/paraview + ) diff --git a/src/Plugins/ParaGEOMCorba/plugin/ParaGEOMCorbaModule/CMakeLists.txt b/src/Plugins/ParaGEOMCorba/plugin/ParaGEOMCorbaModule/CMakeLists.txt new file mode 100644 index 00000000..ef396ec2 --- /dev/null +++ b/src/Plugins/ParaGEOMCorba/plugin/ParaGEOMCorbaModule/CMakeLists.txt @@ -0,0 +1,43 @@ +# Copyright (C) 2010-2019 CEA/DEN, EDF R&D +# +# This library 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. +# +# 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 +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +# + +include_directories( + ${GEOM_ROOT_DIR}/include/salome + ) + +add_definitions(${OMNIORB_DEFINITIONS}) + +set(classes + vtkParaGEOMCorbaSource +) + +vtk_module_add_module(ParaGEOMCorbaModule + FORCE_STATIC + CLASSES ${classes} +) + +target_link_libraries(ParaGEOMCorbaModule PRIVATE + ${OMNIORB_LIBRARIES} + ${KERNEL_SalomeIDLKernel} + ${KERNEL_SalomeLifeCycleCORBA} + ${KERNEL_SalomeNS} + ${GEOM_GEOMClient} + ${GEOM_SalomeIDLGEOM} + ${GEOM_OCC2VTK} +) \ No newline at end of file diff --git a/src/Plugins/ParaGEOMCorba/plugin/ParaGEOMCorbaModule/vtk.module b/src/Plugins/ParaGEOMCorba/plugin/ParaGEOMCorbaModule/vtk.module new file mode 100644 index 00000000..97d633b2 --- /dev/null +++ b/src/Plugins/ParaGEOMCorba/plugin/ParaGEOMCorbaModule/vtk.module @@ -0,0 +1,14 @@ +NAME + ParaGEOMCorbaModule +DEPENDS + VTK::CommonCore + VTK::CommonDataModel + VTK::CommonExecutionModel + VTK::FiltersCore + VTK::FiltersModeling +PRIVATE_DEPENDS + VTK::CommonMisc + VTK::CommonSystem + VTK::FiltersGeneral + VTK::FiltersGeometry + \ No newline at end of file diff --git a/src/Plugins/ParaGEOMCorba/plugin/ParaGEOMCorbaModule/vtkParaGEOMCorbaSource.cxx b/src/Plugins/ParaGEOMCorba/plugin/ParaGEOMCorbaModule/vtkParaGEOMCorbaSource.cxx new file mode 100644 index 00000000..dbc204d9 --- /dev/null +++ b/src/Plugins/ParaGEOMCorba/plugin/ParaGEOMCorbaModule/vtkParaGEOMCorbaSource.cxx @@ -0,0 +1,143 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// + +#include "vtkParaGEOMCorbaSource.h" + +#include "vtkMultiBlockDataSet.h" +#include "vtkUnstructuredGrid.h" +// +#include "vtkStreamingDemandDrivenPipeline.h" +#include "vtkInformationVector.h" +#include "vtkObjectFactory.h" +#include "vtkInformation.h" + +#include +#include +#include +#include "vtkPolyData.h" +#include "GEOM_Gen.hh" +#include "GEOM_Client.hxx" +#include "OCC2VTK_Tools.h" + +#include + +//---------------------------------------------- +vtkStandardNewMacro(vtkParaGEOMCorbaSource); + +void *vtkParaGEOMCorbaSource::Orb=0; + +//---------------------------------------------- +vtkParaGEOMCorbaSource::vtkParaGEOMCorbaSource():Deflection(0.0) +{ + if(!Orb) { + CORBA::ORB_var *OrbC=new CORBA::ORB_var; + int argc=0; + *OrbC=CORBA::ORB_init(argc,0); + this->Orb=OrbC; + } + this->SetNumberOfInputPorts(0); + this->SetNumberOfOutputPorts(1); +} + +//---------------------------------------------- +vtkParaGEOMCorbaSource::~vtkParaGEOMCorbaSource() { +} + +//---------------------------------------------- +const char* vtkParaGEOMCorbaSource::GetIORCorba() +{ + return &IOR[0]; +} + +//---------------------------------------------- +void vtkParaGEOMCorbaSource::SetIORCorba(char *ior) { + if(!ior) + return; + if(ior[0]=='\0') + return; + int length=strlen(ior); + IOR.resize(length+1); + std::copy(ior,ior+length+1,&IOR[0]); + this->Modified(); +} + +//---------------------------------------------- +int vtkParaGEOMCorbaSource::ProcessRequest(vtkInformation* request, + vtkInformationVector** inputVector, + vtkInformationVector* outputVector) { + // generate the data + if(request->Has(vtkDemandDrivenPipeline::REQUEST_DATA())) { + return this->RequestData(request, inputVector, outputVector); + } + return this->Superclass::ProcessRequest(request, inputVector, outputVector); +} + +//---------------------------------------------- +int vtkParaGEOMCorbaSource::FillOutputPortInformation(int vtkNotUsed(port), vtkInformation* info) { + info->Set(vtkDataObject::DATA_TYPE_NAME(), "vtkMultiBlockDataSet"); + return 1; +} + +//---------------------------------------------- +int vtkParaGEOMCorbaSource::RequestData(vtkInformation* request, vtkInformationVector** inInfo, vtkInformationVector* outputVector) { + vtkInformation *outInfo=outputVector->GetInformationObject(0); + vtkMultiBlockDataSet *ret0=vtkMultiBlockDataSet::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); + double reqTS = 0; + if(outInfo->Has(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP())) + reqTS = outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP()); + try { + //Client request on ORB. + CORBA::ORB_var *OrbC=(CORBA::ORB_var *)this->Orb; + CORBA::Object_var obj=(*OrbC)->string_to_object(&IOR[0]); + GEOM::GEOM_Object_var geomObj = GEOM::GEOM_Object::_narrow(obj); + + if(!CORBA::is_nil(geomObj)) { + SALOME_NamingService ns(*OrbC); + SALOME_LifeCycleCORBA aLCC(&ns); + Engines::EngineComponent_var aComponent = aLCC.FindOrLoad_Component("FactoryServer","GEOM"); + GEOM::GEOM_Gen_var geomGen = GEOM::GEOM_Gen::_narrow(aComponent); + if ( !CORBA::is_nil( geomGen ) ) { + TopoDS_Shape aTopoDSShape = GEOM_Client::get_client().GetShape( geomGen, geomObj ); + + if ( !aTopoDSShape.IsNull() ) { + vtkPolyData *ret=GEOM::GetVTKData(aTopoDSShape, this->Deflection); + if(!ret) { + vtkErrorMacro("On geom object CORBA fetching an error occurs !"); + return 0; + } + ret0->SetBlock(0,ret); + ret->Delete(); + return 1; + } + } + } + vtkErrorMacro("Unrecognized CORBA reference!"); + } + catch(CORBA::Exception& ex) { + vtkErrorMacro("On fetching object error occurs"); + } + return 0; +} + +//---------------------------------------------- +void vtkParaGEOMCorbaSource::PrintSelf(ostream& os, vtkIndent indent) { + this->Superclass::PrintSelf( os, indent ); + os << "Deflection: " << this->Deflection << "\n"; +} + diff --git a/src/Plugins/ParaGEOMCorba/plugin/ParaGEOMCorbaModule/vtkParaGEOMCorbaSource.h b/src/Plugins/ParaGEOMCorba/plugin/ParaGEOMCorbaModule/vtkParaGEOMCorbaSource.h new file mode 100644 index 00000000..176f358e --- /dev/null +++ b/src/Plugins/ParaGEOMCorba/plugin/ParaGEOMCorbaModule/vtkParaGEOMCorbaSource.h @@ -0,0 +1,54 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// + + +#ifndef __vtkParaGEOMCorbaSource_h +#define __vtkParaGEOMCorbaSource_h + +#include "vtkUnstructuredGridAlgorithm.h" +#include + +class vtkParaGEOMCorbaSource : public vtkAlgorithm { + public: + static vtkParaGEOMCorbaSource* New(); + vtkTypeMacro(vtkParaGEOMCorbaSource, vtkAlgorithm); + virtual void PrintSelf( ostream& os, vtkIndent indent ); + const char *GetIORCorba(); + void SetIORCorba(char *ior); + + vtkSetMacro(Deflection,double); + + protected: + vtkParaGEOMCorbaSource(); + virtual ~vtkParaGEOMCorbaSource(); + int FillOutputPortInformation(int vtkNotUsed(port), vtkInformation* info); + int ProcessRequest(vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector); + virtual int RequestData( vtkInformation* request, vtkInformationVector** inInfo, vtkInformationVector* outInfo ); + + std::vector IOR; + static void *Orb; + double Deflection; + + private: + vtkParaGEOMCorbaSource( const vtkParaGEOMCorbaSource& ); // Not implemented. + void operator = ( const vtkParaGEOMCorbaSource& ); // Not implemented. +}; + +#endif // __vtkParaGEOMCorbaSource_h + diff --git a/src/Plugins/ParaGEOMCorba/plugin/filters.xml b/src/Plugins/ParaGEOMCorba/plugin/filters.xml new file mode 100644 index 00000000..3f3085b7 --- /dev/null +++ b/src/Plugins/ParaGEOMCorba/plugin/filters.xml @@ -0,0 +1,39 @@ + + + + + + + Source of a remote Geometry Corba reference. + + + + This property specifies the IOR of a Geometry object in memory. + + + + + This property specifies the Deflection coefficient. + + + + + + + + + diff --git a/src/Plugins/ParaGEOMCorba/plugin/paraview.plugin b/src/Plugins/ParaGEOMCorba/plugin/paraview.plugin new file mode 100644 index 00000000..4dcfb859 --- /dev/null +++ b/src/Plugins/ParaGEOMCorba/plugin/paraview.plugin @@ -0,0 +1,8 @@ +NAME + ParaGEOMCorbaPlugin +DESCRIPTION + This plugin provides the ParaGEOMCorba filter. +REQUIRES_MODULES + VTK::CommonCore + VTK::IOCore + VTK::FiltersCore diff --git a/src/Plugins/ParaGEOMCorba/vtkParaGEOMCorbaSource.cxx b/src/Plugins/ParaGEOMCorba/vtkParaGEOMCorbaSource.cxx deleted file mode 100644 index dbc204d9..00000000 --- a/src/Plugins/ParaGEOMCorba/vtkParaGEOMCorbaSource.cxx +++ /dev/null @@ -1,143 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// - -#include "vtkParaGEOMCorbaSource.h" - -#include "vtkMultiBlockDataSet.h" -#include "vtkUnstructuredGrid.h" -// -#include "vtkStreamingDemandDrivenPipeline.h" -#include "vtkInformationVector.h" -#include "vtkObjectFactory.h" -#include "vtkInformation.h" - -#include -#include -#include -#include "vtkPolyData.h" -#include "GEOM_Gen.hh" -#include "GEOM_Client.hxx" -#include "OCC2VTK_Tools.h" - -#include - -//---------------------------------------------- -vtkStandardNewMacro(vtkParaGEOMCorbaSource); - -void *vtkParaGEOMCorbaSource::Orb=0; - -//---------------------------------------------- -vtkParaGEOMCorbaSource::vtkParaGEOMCorbaSource():Deflection(0.0) -{ - if(!Orb) { - CORBA::ORB_var *OrbC=new CORBA::ORB_var; - int argc=0; - *OrbC=CORBA::ORB_init(argc,0); - this->Orb=OrbC; - } - this->SetNumberOfInputPorts(0); - this->SetNumberOfOutputPorts(1); -} - -//---------------------------------------------- -vtkParaGEOMCorbaSource::~vtkParaGEOMCorbaSource() { -} - -//---------------------------------------------- -const char* vtkParaGEOMCorbaSource::GetIORCorba() -{ - return &IOR[0]; -} - -//---------------------------------------------- -void vtkParaGEOMCorbaSource::SetIORCorba(char *ior) { - if(!ior) - return; - if(ior[0]=='\0') - return; - int length=strlen(ior); - IOR.resize(length+1); - std::copy(ior,ior+length+1,&IOR[0]); - this->Modified(); -} - -//---------------------------------------------- -int vtkParaGEOMCorbaSource::ProcessRequest(vtkInformation* request, - vtkInformationVector** inputVector, - vtkInformationVector* outputVector) { - // generate the data - if(request->Has(vtkDemandDrivenPipeline::REQUEST_DATA())) { - return this->RequestData(request, inputVector, outputVector); - } - return this->Superclass::ProcessRequest(request, inputVector, outputVector); -} - -//---------------------------------------------- -int vtkParaGEOMCorbaSource::FillOutputPortInformation(int vtkNotUsed(port), vtkInformation* info) { - info->Set(vtkDataObject::DATA_TYPE_NAME(), "vtkMultiBlockDataSet"); - return 1; -} - -//---------------------------------------------- -int vtkParaGEOMCorbaSource::RequestData(vtkInformation* request, vtkInformationVector** inInfo, vtkInformationVector* outputVector) { - vtkInformation *outInfo=outputVector->GetInformationObject(0); - vtkMultiBlockDataSet *ret0=vtkMultiBlockDataSet::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); - double reqTS = 0; - if(outInfo->Has(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP())) - reqTS = outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP()); - try { - //Client request on ORB. - CORBA::ORB_var *OrbC=(CORBA::ORB_var *)this->Orb; - CORBA::Object_var obj=(*OrbC)->string_to_object(&IOR[0]); - GEOM::GEOM_Object_var geomObj = GEOM::GEOM_Object::_narrow(obj); - - if(!CORBA::is_nil(geomObj)) { - SALOME_NamingService ns(*OrbC); - SALOME_LifeCycleCORBA aLCC(&ns); - Engines::EngineComponent_var aComponent = aLCC.FindOrLoad_Component("FactoryServer","GEOM"); - GEOM::GEOM_Gen_var geomGen = GEOM::GEOM_Gen::_narrow(aComponent); - if ( !CORBA::is_nil( geomGen ) ) { - TopoDS_Shape aTopoDSShape = GEOM_Client::get_client().GetShape( geomGen, geomObj ); - - if ( !aTopoDSShape.IsNull() ) { - vtkPolyData *ret=GEOM::GetVTKData(aTopoDSShape, this->Deflection); - if(!ret) { - vtkErrorMacro("On geom object CORBA fetching an error occurs !"); - return 0; - } - ret0->SetBlock(0,ret); - ret->Delete(); - return 1; - } - } - } - vtkErrorMacro("Unrecognized CORBA reference!"); - } - catch(CORBA::Exception& ex) { - vtkErrorMacro("On fetching object error occurs"); - } - return 0; -} - -//---------------------------------------------- -void vtkParaGEOMCorbaSource::PrintSelf(ostream& os, vtkIndent indent) { - this->Superclass::PrintSelf( os, indent ); - os << "Deflection: " << this->Deflection << "\n"; -} - diff --git a/src/Plugins/ParaGEOMCorba/vtkParaGEOMCorbaSource.h b/src/Plugins/ParaGEOMCorba/vtkParaGEOMCorbaSource.h deleted file mode 100644 index 176f358e..00000000 --- a/src/Plugins/ParaGEOMCorba/vtkParaGEOMCorbaSource.h +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// - - -#ifndef __vtkParaGEOMCorbaSource_h -#define __vtkParaGEOMCorbaSource_h - -#include "vtkUnstructuredGridAlgorithm.h" -#include - -class vtkParaGEOMCorbaSource : public vtkAlgorithm { - public: - static vtkParaGEOMCorbaSource* New(); - vtkTypeMacro(vtkParaGEOMCorbaSource, vtkAlgorithm); - virtual void PrintSelf( ostream& os, vtkIndent indent ); - const char *GetIORCorba(); - void SetIORCorba(char *ior); - - vtkSetMacro(Deflection,double); - - protected: - vtkParaGEOMCorbaSource(); - virtual ~vtkParaGEOMCorbaSource(); - int FillOutputPortInformation(int vtkNotUsed(port), vtkInformation* info); - int ProcessRequest(vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector); - virtual int RequestData( vtkInformation* request, vtkInformationVector** inInfo, vtkInformationVector* outInfo ); - - std::vector IOR; - static void *Orb; - double Deflection; - - private: - vtkParaGEOMCorbaSource( const vtkParaGEOMCorbaSource& ); // Not implemented. - void operator = ( const vtkParaGEOMCorbaSource& ); // Not implemented. -}; - -#endif // __vtkParaGEOMCorbaSource_h - diff --git a/src/Plugins/ParaMEDCorba/CMakeLists.txt b/src/Plugins/ParaMEDCorba/CMakeLists.txt index 1fedca98..686c02ef 100644 --- a/src/Plugins/ParaMEDCorba/CMakeLists.txt +++ b/src/Plugins/ParaMEDCorba/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (C) 2010-2019 CEA/DEN, EDF R&D +# Copyright (C) 2020 CEA/DEN, EDF R&D # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public @@ -17,87 +17,122 @@ # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com # -PROJECT( ParaMEDCorba ) +cmake_minimum_required(VERSION 3.8) +project(ParaMEDCorba) - CMAKE_MINIMUM_REQUIRED( VERSION 2.8.7 ) - IF(WIN32) - CMAKE_POLICY(SET CMP0020 OLD) # disable automatic linking to qtmain.lib - ENDIF(WIN32) +include(GNUInstallDirs) +set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_BINDIR}") +set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_LIBDIR}") +set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_LIBDIR}") - ## !!! This definition corrupts wrapping process - #SET( LIBRARY_OUTPUT_PATH ${ParaMEDCorba_BINARY_DIR}/bin CACHE INTERNAL "Single place for output" ) - #SET( EXECUTABLE_OUTPUT_PATH ${ParaMEDCorba_BINARY_DIR}/bin CACHE INTERNAL "Single place for output" ) - MARK_AS_ADVANCED( - LIBRARY_OUTPUT_PATH - EXECUTABLE_OUTPUT_PATH - ) +find_package(SalomeFIELDS) - FIND_PACKAGE( ParaView COMPONENTS pqCore NO_MODULE) +include_directories( ${CMAKE_CURRENT_SOURCE_DIR}/plugin/ParaMEDCorbaModule ) - IF( ParaView_FOUND ) +set("_paraview_plugin_default_${CMAKE_PROJECT_NAME}" ON) +paraview_plugin_scan( + ENABLE_BY_DEFAULT YES + PLUGIN_FILES "${CMAKE_CURRENT_SOURCE_DIR}/plugin/paraview.plugin" + PROVIDES_PLUGINS plugins + REQUIRES_MODULES required_modules) + +foreach(module IN LISTS required_modules) + if(NOT TARGET "${module}") + message("Missing required module: ${module}") + return() + endif() +endforeach() + +set(BUILD_SHARED_LIBS ON) +paraview_plugin_build( + RUNTIME_DESTINATION "${CMAKE_INSTALL_BINDIR}" + LIBRARY_DESTINATION "${CMAKE_INSTALL_LIBDIR}" + LIBRARY_SUBDIRECTORY "${PARAVIEW_PLUGIN_SUBDIR}" + PLUGINS ${plugins} + AUTOLOAD ${plugins}) + + +######################## + + # CMAKE_MINIMUM_REQUIRED( VERSION 2.8.7 ) + # IF(WIN32) + # CMAKE_POLICY(SET CMP0020 OLD) # disable automatic linking to qtmain.lib + # ENDIF(WIN32) + + # ## !!! This definition corrupts wrapping process + # #SET( LIBRARY_OUTPUT_PATH ${ParaMEDCorba_BINARY_DIR}/bin CACHE INTERNAL "Single place for output" ) + # #SET( EXECUTABLE_OUTPUT_PATH ${ParaMEDCorba_BINARY_DIR}/bin CACHE INTERNAL "Single place for output" ) + # MARK_AS_ADVANCED( + # LIBRARY_OUTPUT_PATH + # EXECUTABLE_OUTPUT_PATH + # ) + + # FIND_PACKAGE( ParaView COMPONENTS pqCore NO_MODULE) + + # IF( ParaView_FOUND ) - INCLUDE( ${PARAVIEW_USE_FILE} ) + # INCLUDE( ${PARAVIEW_USE_FILE} ) - FIND_PACKAGE( VTK COMPONENTS vtkClientServer NO_MODULE NO_DEFAULT_PATH) - INCLUDE( ${VTK_USE_FILE} ) + # FIND_PACKAGE( VTK COMPONENTS vtkClientServer NO_MODULE NO_DEFAULT_PATH) + # INCLUDE( ${VTK_USE_FILE} ) - SET( PARACORBAPLUG_SRCS - ${ParaMEDCorba_SOURCE_DIR}/vtkParaMEDCorbaSource.cxx - ) + # SET( PARACORBAPLUG_SRCS + # ${ParaMEDCorba_SOURCE_DIR}/vtkParaMEDCorbaSource.cxx + # ) - ADD_LIBRARY (ParaMEDMEM2VTK SHARED VTKMEDCouplingMeshClient.cxx VTKMEDCouplingUMeshClient.cxx VTKMEDCouplingCMeshClient.cxx - VTKMEDCouplingFieldClient.cxx VTKParaMEDFieldClient.cxx VTKMEDCouplingMultiFieldsClient.cxx VTKMEDCouplingCurveLinearMeshClient.cxx) + # ADD_LIBRARY (ParaMEDMEM2VTK SHARED VTKMEDCouplingMeshClient.cxx VTKMEDCouplingUMeshClient.cxx VTKMEDCouplingCMeshClient.cxx + # VTKMEDCouplingFieldClient.cxx VTKParaMEDFieldClient.cxx VTKMEDCouplingMultiFieldsClient.cxx VTKMEDCouplingCurveLinearMeshClient.cxx) - ADD_PARAVIEW_PLUGIN( ParaMEDCorbaPlugin "1.0" - SERVER_MANAGER_XML ParaMEDCorbaServerManager.xml - SERVER_MANAGER_SOURCES ${PARACORBAPLUG_SRCS} ) + # ADD_PARAVIEW_PLUGIN( ParaMEDCorbaPlugin "1.0" + # SERVER_MANAGER_XML ParaMEDCorbaServerManager.xml + # SERVER_MANAGER_SOURCES ${PARACORBAPLUG_SRCS} ) - INCLUDE_DIRECTORIES(${OMNIORB_INCLUDE_DIR} ${FIELDS_ROOT_DIR}/include/salome ${KERNEL_ROOT_DIR}/include/salome) - ADD_DEFINITIONS(${OMNIORB_DEFINITIONS}) - - TARGET_LINK_LIBRARIES(ParaMEDMEM2VTK - #vtkCommon - #vtkFiltering - #vtkGraphics - vtkClientServer - vtkPVVTKExtensionsRendering - pqCore - ${OMNIORB_LIBRARIES} - ${FIELDS_SalomeIDLMED} - ${KERNEL_SalomeIDLKernel} - ) - TARGET_LINK_LIBRARIES(ParaMEDCorbaPlugin - ParaMEDMEM2VTK - ) + # INCLUDE_DIRECTORIES(${OMNIORB_INCLUDE_DIR} ${FIELDS_ROOT_DIR}/include/salome ${KERNEL_ROOT_DIR}/include/salome) + # ADD_DEFINITIONS(${OMNIORB_DEFINITIONS}) + + # TARGET_LINK_LIBRARIES(ParaMEDMEM2VTK + # #vtkCommon + # #vtkFiltering + # #vtkGraphics + # vtkClientServer + # vtkPVVTKExtensionsRendering + # pqCore + # ${OMNIORB_LIBRARIES} + # ${FIELDS_SalomeIDLMED} + # ${KERNEL_SalomeIDLKernel} + # ) + # TARGET_LINK_LIBRARIES(ParaMEDCorbaPlugin + # ParaMEDMEM2VTK + # ) - #Build library with a static runtime and ignore MSVCRT.lib on WINDOWS - IF(WIN32) - IF(CMAKE_BUILD_TYPE STREQUAL Debug) - SET_TARGET_PROPERTIES(ParaMEDMEM2VTK PROPERTIES LINK_FLAGS "/NODEFAULTLIB:MSVCRTD") - SET_TARGET_PROPERTIES(ParaMEDMEM2VTK PROPERTIES COMPILE_FLAGS "/MTd") - ELSE() - SET_TARGET_PROPERTIES(ParaMEDMEM2VTK PROPERTIES LINK_FLAGS "/NODEFAULTLIB:MSVCRT") - SET_TARGET_PROPERTIES(ParaMEDMEM2VTK PROPERTIES COMPILE_FLAGS "/MT") - ENDIF() - ENDIF(WIN32) - - INSTALL(TARGETS ParaMEDCorbaPlugin DESTINATION lib/paraview) - - INSTALL(TARGETS ParaMEDMEM2VTK DESTINATION lib/salome) + # #Build library with a static runtime and ignore MSVCRT.lib on WINDOWS + # IF(WIN32) + # IF(CMAKE_BUILD_TYPE STREQUAL Debug) + # SET_TARGET_PROPERTIES(ParaMEDMEM2VTK PROPERTIES LINK_FLAGS "/NODEFAULTLIB:MSVCRTD") + # SET_TARGET_PROPERTIES(ParaMEDMEM2VTK PROPERTIES COMPILE_FLAGS "/MTd") + # ELSE() + # SET_TARGET_PROPERTIES(ParaMEDMEM2VTK PROPERTIES LINK_FLAGS "/NODEFAULTLIB:MSVCRT") + # SET_TARGET_PROPERTIES(ParaMEDMEM2VTK PROPERTIES COMPILE_FLAGS "/MT") + # ENDIF() + # ENDIF(WIN32) + + # INSTALL(TARGETS ParaMEDCorbaPlugin DESTINATION lib/paraview) + + # INSTALL(TARGETS ParaMEDMEM2VTK DESTINATION lib/salome) - ADD_EXECUTABLE( testParaMEDCorba - ${ParaMEDCorba_SOURCE_DIR}/testParaMEDCorba.cxx - ) - # SET_TARGET_PROPERTIES(testCorbaPlugin PROPERTIES COMPILE_FLAGS "${OMNIORB_DEFINITIONS}") - - # RNV: ${vtkgl2ps_LIBRARIES} was added for Fedora 26 OS - TARGET_LINK_LIBRARIES( testParaMEDCorba - ParaMEDCorbaPlugin - ${vtkgl2ps_LIBRARIES} - ) + # ADD_EXECUTABLE( testParaMEDCorba + # ${ParaMEDCorba_SOURCE_DIR}/testParaMEDCorba.cxx + # ) + # # SET_TARGET_PROPERTIES(testCorbaPlugin PROPERTIES COMPILE_FLAGS "${OMNIORB_DEFINITIONS}") + + # # RNV: ${vtkgl2ps_LIBRARIES} was added for Fedora 26 OS + # TARGET_LINK_LIBRARIES( testParaMEDCorba + # ParaMEDCorbaPlugin + # ${vtkgl2ps_LIBRARIES} + # ) - INSTALL(FILES ParaMEDCorbaServerManager.xml DESTINATION share) + # INSTALL(FILES ParaMEDCorbaServerManager.xml DESTINATION share) - ENDIF( ParaView_FOUND ) + # ENDIF( ParaView_FOUND ) diff --git a/src/Plugins/ParaMEDCorba/ParaMEDCorbaServerManager.xml b/src/Plugins/ParaMEDCorba/ParaMEDCorbaServerManager.xml deleted file mode 100644 index e2c51aeb..00000000 --- a/src/Plugins/ParaMEDCorba/ParaMEDCorbaServerManager.xml +++ /dev/null @@ -1,67 +0,0 @@ - - - - - - - Source of a remote ParaMED Corba reference. - - - - This property specifies the IOR of a ParaFIELD MED in memory. - - - - - - This property specifies the buffering policy. - 0 means no buffering, that is to say Corba fetching is done - every times needed to get field at a time step. Remote Corba - object is NOT Released. - 10 means full buffering, that is to say a full Corba fetching - is performed on begin and remote Corba object is - released. But memory consumtion could be huge. - Between 0,and 10 a partial buffering is done. - - - - - - - Available timestep values. - - - - - - - Available time range. - - - - - - - - - - diff --git a/src/Plugins/ParaMEDCorba/ParaMEDMEM2VTK_defines.hxx b/src/Plugins/ParaMEDCorba/ParaMEDMEM2VTK_defines.hxx deleted file mode 100644 index f67126ae..00000000 --- a/src/Plugins/ParaMEDCorba/ParaMEDMEM2VTK_defines.hxx +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// - -#ifndef __ParaMEDMEM2VTK_defines_h__ -#define __ParaMEDMEM2VTK_defines_h__ - -#ifdef WIN32 -# if defined ParaMEDMEM2VTK_EXPORTS -# define ParaMEDMEM2VTK_EXPORT __declspec( dllexport ) -# else -# define ParaMEDMEM2VTK_EXPORT __declspec( dllimport ) -# endif -#else -# define ParaMEDMEM2VTK_EXPORT -#endif - -#endif // __ParaMEDMEM2VTK_defines_h__ diff --git a/src/Plugins/ParaMEDCorba/VTKMEDCouplingCMeshClient.cxx b/src/Plugins/ParaMEDCorba/VTKMEDCouplingCMeshClient.cxx deleted file mode 100644 index 67fbb5e5..00000000 --- a/src/Plugins/ParaMEDCorba/VTKMEDCouplingCMeshClient.cxx +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// - -#include "VTKMEDCouplingCMeshClient.hxx" - -#include "vtkErrorCode.h" -#include "vtkDoubleArray.h" -#include "vtkRectilinearGrid.h" - -#include -#include - -void ParaMEDMEM2VTK::FillMEDCouplingCMeshInstanceFrom(SALOME_MED::MEDCouplingCMeshCorbaInterface_ptr meshPtr, vtkRectilinearGrid *ret) -{ - meshPtr->Register(); - SALOME_TYPES::ListOfDouble *tinyD; - SALOME_TYPES::ListOfLong *tinyI; - SALOME_TYPES::ListOfString *tinyS; - meshPtr->getTinyInfo(tinyD,tinyI,tinyS); - int sizePerAxe[3]={1,1,1}; - bool isOK[3]={false,false,false}; - if((*tinyI)[0]>0) - { sizePerAxe[0]=(*tinyI)[0]; isOK[0]=true; } - if((*tinyI)[1]>0) - { sizePerAxe[1]=(*tinyI)[1]; isOK[1]=true; } - if((*tinyI)[2]>0) - { sizePerAxe[2]=(*tinyI)[2]; isOK[2]=true; } - ret->SetDimensions(sizePerAxe[0],sizePerAxe[1],sizePerAxe[2]); - delete tinyI; - delete tinyS; - delete tinyD; - SALOME_TYPES::ListOfDouble *bigD; - meshPtr->getSerialisationData(tinyI,bigD); - delete tinyI; - int offset=0; - vtkDoubleArray *da=0; - if(isOK[0]) - { - da=vtkDoubleArray::New(); - da->SetNumberOfTuples(sizePerAxe[0]); - da->SetNumberOfComponents(1); - double *pt=da->GetPointer(0); - for(int i=0;iSetXCoordinates(da); - da->Delete(); - offset+=sizePerAxe[0]; - } - if(isOK[1]) - { - da=vtkDoubleArray::New(); - da->SetNumberOfTuples(sizePerAxe[1]); - da->SetNumberOfComponents(1); - double *pt=da->GetPointer(0); - for(int i=0;iSetYCoordinates(da); - da->Delete(); - offset+=sizePerAxe[1]; - } - else - { - da=vtkDoubleArray::New(); da->SetNumberOfTuples(1); da->SetNumberOfComponents(1); - double *pt=da->GetPointer(0); *pt=0.; ret->SetYCoordinates(da); da->Delete(); - } - if(isOK[2]) - { - da=vtkDoubleArray::New(); - da->SetNumberOfTuples(sizePerAxe[2]); - da->SetNumberOfComponents(1); - double *pt=da->GetPointer(0); - for(int i=0;iSetZCoordinates(da); - da->Delete(); - } - else - { - da=vtkDoubleArray::New(); da->SetNumberOfTuples(1); da->SetNumberOfComponents(1); - double *pt=da->GetPointer(0); *pt=0.; ret->SetZCoordinates(da); da->Delete(); - } - delete bigD; - meshPtr->UnRegister(); -} diff --git a/src/Plugins/ParaMEDCorba/VTKMEDCouplingCMeshClient.hxx b/src/Plugins/ParaMEDCorba/VTKMEDCouplingCMeshClient.hxx deleted file mode 100644 index 07117236..00000000 --- a/src/Plugins/ParaMEDCorba/VTKMEDCouplingCMeshClient.hxx +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// - -#ifndef __VTKMEDCOUPLINGCMESHCLIENT_HXX__ -#define __VTKMEDCOUPLINGCMESHCLIENT_HXX__ - -#include "ParaMEDCouplingCorbaServant.hh" - -class vtkRectilinearGrid; - -namespace ParaMEDMEM2VTK -{ - void FillMEDCouplingCMeshInstanceFrom(SALOME_MED::MEDCouplingCMeshCorbaInterface_ptr meshPtr, vtkRectilinearGrid *ret); -} - -#endif diff --git a/src/Plugins/ParaMEDCorba/VTKMEDCouplingCurveLinearMeshClient.cxx b/src/Plugins/ParaMEDCorba/VTKMEDCouplingCurveLinearMeshClient.cxx deleted file mode 100644 index 54b73a3e..00000000 --- a/src/Plugins/ParaMEDCorba/VTKMEDCouplingCurveLinearMeshClient.cxx +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// - -#include "VTKMEDCouplingCurveLinearMeshClient.hxx" - -#include "vtkPoints.h" -#include "vtkErrorCode.h" -#include "vtkDoubleArray.h" -#include "vtkStructuredGrid.h" - -#include -#include - -void ParaMEDMEM2VTK::FillMEDCouplingCurveLinearMeshInstanceFrom(SALOME_MED::MEDCouplingCurveLinearMeshCorbaInterface_ptr meshPtr, vtkStructuredGrid *ret) -{ - meshPtr->Register(); - SALOME_TYPES::ListOfDouble *tinyD; - SALOME_TYPES::ListOfLong *tinyI; - SALOME_TYPES::ListOfString *tinyS; - meshPtr->getTinyInfo(tinyD,tinyI,tinyS); - int meshStr[3]={1,1,1}; - int meshDim=(*tinyI)[2]; - if(meshDim<0 || meshDim>3) - vtkErrorWithObjectMacro(ret,"Internal error in ParaMEDCorba plugin : distant curvilinear mesh has a mesh dimension not in [0,3] !"); - for(int i=0;iSetDimensions(meshStr); - int nbOfNodes=(*tinyI)[3+meshDim]; - int spaceDim=(*tinyI)[3+meshDim+1]; - delete tinyD; - delete tinyI; - delete tinyS; - // - vtkDoubleArray *da=vtkDoubleArray::New(); - da->SetNumberOfComponents(3); - da->SetNumberOfTuples(nbOfNodes); - double *pt=da->GetPointer(0); - SALOME_TYPES::ListOfDouble *bigD; - meshPtr->getSerialisationData(tinyI,bigD); - delete tinyI; - if(bigD->length()!=nbOfNodes*spaceDim) - vtkErrorWithObjectMacro(ret,"Internal error in ParaMEDCorba plugin : distant curvilinear mesh, mismatch between informations ! Internal error !"); - for(int i=0;iSetPoints(points); - points->SetData(da); - points->Delete(); - da->Delete(); - meshPtr->UnRegister(); -} diff --git a/src/Plugins/ParaMEDCorba/VTKMEDCouplingCurveLinearMeshClient.hxx b/src/Plugins/ParaMEDCorba/VTKMEDCouplingCurveLinearMeshClient.hxx deleted file mode 100644 index 25385ea5..00000000 --- a/src/Plugins/ParaMEDCorba/VTKMEDCouplingCurveLinearMeshClient.hxx +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// - -#ifndef __VTKMEDCOUPLINGCURVELINEARMESHCLIENT_HXX__ -#define __VTKMEDCOUPLINGCURVELINEARMESHCLIENT_HXX__ - -#include "ParaMEDCouplingCorbaServant.hh" - -class vtkStructuredGrid; - -namespace ParaMEDMEM2VTK -{ - void FillMEDCouplingCurveLinearMeshInstanceFrom(SALOME_MED::MEDCouplingCurveLinearMeshCorbaInterface_ptr meshPtr, vtkStructuredGrid *ret); -} - -#endif diff --git a/src/Plugins/ParaMEDCorba/VTKMEDCouplingFieldClient.cxx b/src/Plugins/ParaMEDCorba/VTKMEDCouplingFieldClient.cxx deleted file mode 100644 index 2bbb6298..00000000 --- a/src/Plugins/ParaMEDCorba/VTKMEDCouplingFieldClient.cxx +++ /dev/null @@ -1,212 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// - -#include "VTKMEDCouplingFieldClient.hxx" -#include "VTKMEDCouplingMeshClient.hxx" - -#include "vtkErrorCode.h" -#include "vtkCellData.h" -#include "vtkPointData.h" -#include "vtkDoubleArray.h" -#include "vtkUnstructuredGrid.h" - -#include -#include - -std::vector ParaMEDMEM2VTK::FillMEDCouplingFieldDoubleInstanceFrom(SALOME_MED::MEDCouplingFieldDoubleCorbaInterface_ptr fieldPtr, vtkDataSet *ret) -{ - fieldPtr->Register(); - // - SALOME_MED::MEDCouplingMeshCorbaInterface_var meshPtr=fieldPtr->getMesh(); - ParaMEDMEM2VTK::FillMEDCouplingMeshInstanceFrom(meshPtr,ret); - meshPtr->UnRegister(); - // - std::vector ret2=FillMEDCouplingFieldDoublePartOnly(fieldPtr,ret); - fieldPtr->UnRegister(); - // - return ret2; -} - -std::vector ParaMEDMEM2VTK::FillMEDCouplingFieldDoublePartOnly(SALOME_MED::MEDCouplingFieldDoubleCorbaInterface_ptr fieldPtr, vtkDataSet *ret) -{ - std::vector ret2; - // - SALOME_TYPES::ListOfLong *tinyL; - SALOME_TYPES::ListOfDouble *tinyD; - SALOME_TYPES::ListOfString *tinyS; - fieldPtr->getTinyInfo(tinyL,tinyD,tinyS); - // - int typeOfField=(*tinyL)[0];// 0:ON_CELLS, 1:ON_NODES, 2:ON_GAUSS_PT, 3:ON_GAUSS_NE - int timeDiscr=(*tinyL)[1]; - int nbOfTuples=(*tinyL)[3]; - int nbOfComponents=(*tinyL)[4]; - std::vector comps(nbOfComponents); - for(int i=0;iSetName(name.c_str()); - var0->SetNumberOfComponents(nbOfComponents); - var0->SetNumberOfTuples(nbOfTuples); - for(int i=0;iSetComponentName(i,comps[i].c_str()); - var0Ptr=var0->GetPointer(0); - if(timeDiscr==7) - { - var1->SetNumberOfComponents(nbOfComponents); - var1->SetNumberOfTuples(nbOfTuples); - var1Ptr=var1->GetPointer(0); - std::ostringstream oss; oss << name << "_end_array"; - var1->SetName(oss.str().c_str()); - } - // - SALOME_TYPES::ListOfLong *bigDataI; - SALOME_TYPES::ListOfDouble2 *bigArr; - fieldPtr->getSerialisationData(bigDataI,bigArr); - delete bigDataI;//for the moment gauss points are not dealt - SALOME_TYPES::ListOfDouble& oneArr=(*bigArr)[0]; - int nbVals=oneArr.length(); - for(int i=0;iGetCellData()->AddArray(var0); - if(timeDiscr==7) - ret->GetCellData()->AddArray(var1); - break; - case 1://ON_NODES - ret->GetPointData()->AddArray(var0); - if(timeDiscr==7) - ret->GetCellData()->AddArray(var1); - break; - default: - vtkErrorWithObjectMacro(ret,"Not implemented yet for gauss fields and gauss on elements fields !"); - } - var0->Delete(); - if(timeDiscr==7) - var1->Delete(); - // - return ret2; -} - -vtkDataSet *ParaMEDMEM2VTK::BuildFullyFilledFromMEDCouplingFieldDoubleInstance(SALOME_MED::MEDCouplingFieldDoubleCorbaInterface_ptr fieldPtr, - std::vector& times) -{ - fieldPtr->Register(); - SALOME_MED::MEDCouplingMeshCorbaInterface_var meshPtr=fieldPtr->getMesh(); - bool dummy;//VTK bug - vtkDataSet *ret=ParaMEDMEM2VTK::BuildFromMEDCouplingMeshInstance(meshPtr,dummy);//VTK bug - meshPtr->UnRegister(); - // - std::vector ret2=FillMEDCouplingFieldDoublePartOnly(fieldPtr,ret); - times=ret2; - // - fieldPtr->UnRegister(); - return ret; -} - -vtkDoubleArray *ParaMEDMEM2VTK::BuildFromMEDCouplingFieldDoubleArr(SALOME_MED::DataArrayDoubleCorbaInterface_ptr dadPtr) -{ - vtkDoubleArray *ret=vtkDoubleArray::New(); - // - SALOME_TYPES::ListOfLong *tinyL=0; - SALOME_TYPES::ListOfDouble *bigD=0; - SALOME_TYPES::ListOfString *tinyS=0; - // - dadPtr->getTinyInfo(tinyL,tinyS); - int nbOfTuples=(*tinyL)[0]; - int nbOfCompo=(*tinyL)[1]; - std::string name((*tinyS)[0]); - std::vector comps(nbOfCompo); - for(int i=0;iSetName(name.c_str()); - ret->SetNumberOfComponents(nbOfCompo); - ret->SetNumberOfTuples(nbOfTuples); - for(int i=0;iSetComponentName(i,comps[i].c_str()); - else - { - std::ostringstream oss; oss << "Comp" << i; - ret->SetComponentName(i,oss.str().c_str()); - } - } - int nbElems=nbOfCompo*nbOfTuples; - double *pt=ret->GetPointer(0); - dadPtr->getSerialisationData(bigD); - for(int i=0;i - -class vtkDataSet; -class vtkDoubleArray; - -namespace ParaMEDMEM2VTK -{ - std::vector FillMEDCouplingFieldDoubleInstanceFrom(SALOME_MED::MEDCouplingFieldDoubleCorbaInterface_ptr fieldPtr, vtkDataSet *ret); - std::vector FillMEDCouplingFieldDoublePartOnly(SALOME_MED::MEDCouplingFieldDoubleCorbaInterface_ptr fieldPtr, vtkDataSet *ret); - ParaMEDMEM2VTK_EXPORT vtkDataSet *BuildFullyFilledFromMEDCouplingFieldDoubleInstance(SALOME_MED::MEDCouplingFieldDoubleCorbaInterface_ptr fieldPtr, - std::vector& times); - ParaMEDMEM2VTK_EXPORT vtkDoubleArray *BuildFromMEDCouplingFieldDoubleArr(SALOME_MED::DataArrayDoubleCorbaInterface_ptr dadPtr); -} - -#endif diff --git a/src/Plugins/ParaMEDCorba/VTKMEDCouplingMeshClient.cxx b/src/Plugins/ParaMEDCorba/VTKMEDCouplingMeshClient.cxx deleted file mode 100644 index 114df1bd..00000000 --- a/src/Plugins/ParaMEDCorba/VTKMEDCouplingMeshClient.cxx +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// - -#include "VTKMEDCouplingMeshClient.hxx" -#include "VTKMEDCouplingUMeshClient.hxx" -#include "VTKMEDCouplingCMeshClient.hxx" -#include "VTKMEDCouplingCurveLinearMeshClient.hxx" - -#include "vtkErrorCode.h" -#include "vtkUnstructuredGrid.h" -#include "vtkRectilinearGrid.h" -#include "vtkStructuredGrid.h" - -#include -#include - -//vtkErrorMacro("Cannot call Start() twice before calling Finish()."); -void ParaMEDMEM2VTK::FillMEDCouplingMeshInstanceFrom(SALOME_MED::MEDCouplingMeshCorbaInterface_ptr meshPtr, vtkDataSet *ret) -{ - SALOME_MED::MEDCouplingUMeshCorbaInterface_var umeshPtr=SALOME_MED::MEDCouplingUMeshCorbaInterface::_narrow(meshPtr); - if(!CORBA::is_nil(umeshPtr)) - { - vtkUnstructuredGrid *ret1=vtkUnstructuredGrid::SafeDownCast(ret); - if(!ret1) - { - vtkErrorWithObjectMacro(ret,"Internal error in ParaMEDCorba plugin : mismatch between VTK type and CORBA type UMesh !"); - return ; - } - bool dummy;//VTK bug - ParaMEDMEM2VTK::FillMEDCouplingUMeshInstanceFrom(umeshPtr,ret1,dummy);//VTK bug - return ; - } - SALOME_MED::MEDCouplingCMeshCorbaInterface_var cmeshPtr=SALOME_MED::MEDCouplingCMeshCorbaInterface::_narrow(meshPtr); - if(!CORBA::is_nil(cmeshPtr)) - { - vtkRectilinearGrid *ret1=vtkRectilinearGrid::SafeDownCast(ret); - if(!ret1) - { - vtkErrorWithObjectMacro(ret,"Internal error in ParaMEDCorba plugin : mismatch between VTK type and CORBA type CMesh !"); - return ; - } - ParaMEDMEM2VTK::FillMEDCouplingCMeshInstanceFrom(cmeshPtr,ret1); - return ; - } - SALOME_MED::MEDCouplingCurveLinearMeshCorbaInterface_var clmeshPtr=SALOME_MED::MEDCouplingCurveLinearMeshCorbaInterface::_narrow(meshPtr); - if(!CORBA::is_nil(clmeshPtr)) - { - vtkStructuredGrid *ret1=vtkStructuredGrid::SafeDownCast(ret); - if(!ret1) - { - vtkErrorWithObjectMacro(ret,"Internal error in ParaMEDCorba plugin : mismatch between VTK type and CORBA type CurveLinearMesh !"); - return ; - } - ParaMEDMEM2VTK::FillMEDCouplingCurveLinearMeshInstanceFrom(clmeshPtr,ret1); - return ; - } - vtkErrorWithObjectMacro(ret,"Error : CORBA mesh type ! Mesh type not managed !"); -} - -vtkDataSet *ParaMEDMEM2VTK::BuildFromMEDCouplingMeshInstance(SALOME_MED::MEDCouplingMeshCorbaInterface_ptr meshPtr, bool& isPolyh) -{ - SALOME_MED::MEDCouplingUMeshCorbaInterface_var umeshPtr=SALOME_MED::MEDCouplingUMeshCorbaInterface::_narrow(meshPtr); - if(!CORBA::is_nil(umeshPtr)) - { - vtkUnstructuredGrid *ret1=vtkUnstructuredGrid::New(); - ParaMEDMEM2VTK::FillMEDCouplingUMeshInstanceFrom(umeshPtr,ret1,isPolyh); - return ret1; - } - SALOME_MED::MEDCouplingCMeshCorbaInterface_var cmeshPtr=SALOME_MED::MEDCouplingCMeshCorbaInterface::_narrow(meshPtr); - if(!CORBA::is_nil(cmeshPtr)) - { - vtkRectilinearGrid *ret1=vtkRectilinearGrid::New(); - ParaMEDMEM2VTK::FillMEDCouplingCMeshInstanceFrom(cmeshPtr,ret1); - return ret1; - } - SALOME_MED::MEDCouplingCurveLinearMeshCorbaInterface_var clmeshPtr=SALOME_MED::MEDCouplingCurveLinearMeshCorbaInterface::_narrow(meshPtr); - if(!CORBA::is_nil(clmeshPtr)) - { - vtkStructuredGrid *ret1=vtkStructuredGrid::New(); - ParaMEDMEM2VTK::FillMEDCouplingCurveLinearMeshInstanceFrom(clmeshPtr,ret1); - return ret1; - } - vtkOutputWindowDisplayErrorText("Error : CORBA mesh type ! Mesh type not managed #2 !"); - return 0; -} diff --git a/src/Plugins/ParaMEDCorba/VTKMEDCouplingMeshClient.hxx b/src/Plugins/ParaMEDCorba/VTKMEDCouplingMeshClient.hxx deleted file mode 100644 index 39d504cd..00000000 --- a/src/Plugins/ParaMEDCorba/VTKMEDCouplingMeshClient.hxx +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// - -#ifndef __VTKMEDCOUPLINGMESHCLIENT_HXX__ -#define __VTKMEDCOUPLINGMESHCLIENT_HXX__ - -#include "ParaMEDMEM2VTK_defines.hxx" -#include "ParaMEDCouplingCorbaServant.hh" - -class vtkDataSet; - -namespace ParaMEDMEM2VTK -{ - void FillMEDCouplingMeshInstanceFrom(SALOME_MED::MEDCouplingMeshCorbaInterface_ptr meshPtr, vtkDataSet *ret); - ParaMEDMEM2VTK_EXPORT vtkDataSet *BuildFromMEDCouplingMeshInstance(SALOME_MED::MEDCouplingMeshCorbaInterface_ptr meshPtr, bool& isPolyh);//isPolyh bug VTK -} - -#endif diff --git a/src/Plugins/ParaMEDCorba/VTKMEDCouplingMultiFieldsClient.cxx b/src/Plugins/ParaMEDCorba/VTKMEDCouplingMultiFieldsClient.cxx deleted file mode 100644 index c3c080a0..00000000 --- a/src/Plugins/ParaMEDCorba/VTKMEDCouplingMultiFieldsClient.cxx +++ /dev/null @@ -1,340 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// - -// To access to vtkUnstructuredGrid::Faces and FaceLocations -#ifdef WIN32 -#define _ALLOW_KEYWORD_MACROS -#endif -#define protected public - -#include "VTKMEDCouplingMultiFieldsClient.hxx" -#include "VTKMEDCouplingMeshClient.hxx" -#include "VTKMEDCouplingFieldClient.hxx" - -#include "vtkUnstructuredGrid.h" -#include "vtkRectilinearGrid.h" -#include "vtkDoubleArray.h" -#include "vtkErrorCode.h" -#include "vtkCellData.h" -#include "vtkIdTypeArray.h" -#include "vtkPointData.h" - -#include -#include -#include -#include - -const double ParaMEDMEM2VTK::MEDCouplingMultiFieldsFetcher::EPS_TIME=1e-7; - -ParaMEDMEM2VTK::MEDCouplingMultiFieldsFetcher::MEDCouplingMultiFieldsFetcher(int bufferingPolicy, - SALOME_MED::MEDCouplingMultiFieldsCorbaInterface_ptr mfieldsPtr):_effective_pol(bufferingPolicy),_mfields_ptr_released(false) -{ - _mfields_ptr=SALOME_MED::MEDCouplingMultiFieldsCorbaInterface::_duplicate(mfieldsPtr); - _mfields_ptr->Register(); -} - -ParaMEDMEM2VTK::MEDCouplingMultiFieldsFetcher::~MEDCouplingMultiFieldsFetcher() -{ - for(std::vector::iterator it=_meshes.begin();it!=_meshes.end();it++) - { - if(*it) - (*it)->Delete(); - } - for(std::vector::iterator it2=_arrays.begin();it2!=_arrays.end();it2++) - { - if(*it2) - (*it2)->Delete(); - } - if(!_mfields_ptr_released) - _mfields_ptr->UnRegister(); -} - -std::vector ParaMEDMEM2VTK::MEDCouplingMultiFieldsFetcher::getTimeStepsForPV() -{ - retrievesMainTinyInfo(); - int nbOfFields=_mesh_id_per_field.size(); - // - _time_label_per_field.resize(nbOfFields); - SALOME_MED::MEDCouplingFieldOverTimeCorbaInterface_var fotPtr=SALOME_MED::MEDCouplingFieldOverTimeCorbaInterface::_narrow(_mfields_ptr); - if(CORBA::is_nil(fotPtr)) - { - for(CORBA::Long i=0;i=10) - { - fetchAll(); - return ; - } - if(_effective_pol>=1 && _effective_pol<=9) - { - fetchMeshes(); - return ; - } -} - -vtkDataSet *ParaMEDMEM2VTK::MEDCouplingMultiFieldsFetcher::buildDataSetOnTime(double time) -{ - int fieldId=getPosGivenTimeLabel(time); - if(fieldId<0) - return 0; - fetchDataIfNeeded(fieldId); - int meshId=_mesh_id_per_field[fieldId]; - vtkDataSet *ret0=_meshes[meshId]; - std::string clsName=ret0->GetClassName(); - if(clsName=="vtkUnstructuredGrid") - { - vtkUnstructuredGrid *ret1=vtkUnstructuredGrid::New(); - ret1->DeepCopy(ret0); - if(_is_meshes_polyhedron[meshId])//bug VTK polyhedron - {//bug VTK polyhedron part - ret1->Faces->UnRegister(ret1); - ret1->Faces=vtkIdTypeArray::New(); - ret1->Faces->DeepCopy(((vtkUnstructuredGrid *)ret0)->GetFaces()); - ret1->Faces->Register(ret1); - ret1->Faces->Delete(); - ret1->FaceLocations->UnRegister(ret1); - ret1->FaceLocations=vtkIdTypeArray::New(); - ret1->FaceLocations->DeepCopy(((vtkUnstructuredGrid *)ret0)->GetFaceLocations()); - ret1->FaceLocations->Register(ret1); - ret1->FaceLocations->Delete(); - }//end bug VTK polyhedron part - appendFieldValueOnAlreadyFetchedData(ret1,fieldId); - applyBufferingPolicy(); - return ret1; - } - if(clsName=="vtkRectilinearGrid") - { - vtkRectilinearGrid *ret1=vtkRectilinearGrid::New(); - ret1->DeepCopy(ret0); - appendFieldValueOnAlreadyFetchedData(ret1,fieldId); - applyBufferingPolicy(); - return ret1; - } - return 0; -} - -void ParaMEDMEM2VTK::MEDCouplingMultiFieldsFetcher::retrievesMainTinyInfo() -{ - SALOME_TYPES::ListOfLong *tinyL=0; - SALOME_TYPES::ListOfDouble *tinyD=0; - SALOME_TYPES::ListOfString *tinyS=0; - // - CORBA::Long nbOfArrays; - CORBA::Long nbOfFields; - CORBA::Long nbOfMeshes=_mfields_ptr->getMainTinyInfo(tinyL,tinyD,nbOfArrays,nbOfFields); - int sz=(*tinyL)[0];//nbOfFields - //int sz2=(*tinyL)[1];//sigma(nbOfArraysPerField) - _time_discr_per_field.resize(sz);//4 : NO_TIME 5:ONE_TIME 6:LINEAR_TIME 7:CONST_ON_TIME_INTERVAL - _mesh_id_per_field.resize(sz); - _array_ids_per_field.resize(sz); - _time_def_per_field.resize(sz); - int offsetTime=0; - int offsetArrays=0; - for(int i=0;igetTinyInfo(i,tinyL,tinyD,tinyS); - _info_per_field[i]._type=(*tinyL)[0]; - _info_per_field[i]._name=(*tinyS)[0]; - delete tinyL; - delete tinyD; - delete tinyS; - } -} - -void ParaMEDMEM2VTK::MEDCouplingMultiFieldsFetcher::fetchAll() -{ - fetchMeshes(); - int nbOfArrays=_arrays.size(); - for(int i=0;igetArray(i); - if(_arrays[i]) - _arrays[i]->Delete(); - _arrays[i]=ParaMEDMEM2VTK::BuildFromMEDCouplingFieldDoubleArr(daPtr); - daPtr->UnRegister(); - } - unregisterRemoteServantIfAllFetched(); -} - -/*! - * Fetches meshes without regarding if already fetched - */ -void ParaMEDMEM2VTK::MEDCouplingMultiFieldsFetcher::fetchMeshes() -{ - int nbOfMeshes=_meshes.size(); - for(int i=0;igetMeshWithId(i); - if(_meshes[i]) - _meshes[i]->Delete(); - bool polyh=false;//bug VTK - _meshes[i]=ParaMEDMEM2VTK::BuildFromMEDCouplingMeshInstance(mPtr,polyh);//bug VTK - _is_meshes_polyhedron[i]=polyh;//bug VTK - mPtr->UnRegister(); - } - unregisterRemoteServantIfAllFetched(); -} - -/*! - * For a field with id 'fieldId' this method CORBA fetch, if needed, basic data. - * 'fieldId' should be correct no check of that is done ! - */ -void ParaMEDMEM2VTK::MEDCouplingMultiFieldsFetcher::fetchDataIfNeeded(int fieldId) -{ - std::vector arrayIds=_array_ids_per_field[fieldId]; - int meshId=_mesh_id_per_field[fieldId]; - if(!_meshes[meshId]) - { - SALOME_MED::MEDCouplingMeshCorbaInterface_var mPtr=_mfields_ptr->getMeshWithId(meshId); - bool polyh=false;//bug VTK - _meshes[meshId]=ParaMEDMEM2VTK::BuildFromMEDCouplingMeshInstance(mPtr,polyh);//bug VTK - _is_meshes_polyhedron[meshId]=polyh;//bug VTK - mPtr->UnRegister(); - } - for(std::vector::const_iterator it=arrayIds.begin();it!=arrayIds.end();it++) - { - if(!_arrays[*it]) - { - SALOME_MED::DataArrayDoubleCorbaInterface_var daPtr=_mfields_ptr->getArray(*it); - _arrays[*it]=ParaMEDMEM2VTK::BuildFromMEDCouplingFieldDoubleArr(daPtr); - daPtr->UnRegister(); - } - } - unregisterRemoteServantIfAllFetched(); -} - -void ParaMEDMEM2VTK::MEDCouplingMultiFieldsFetcher::unregisterRemoteServantIfAllFetched() -{ - for(std::vector::iterator it=_meshes.begin();it!=_meshes.end();it++) - { - if((*it)==0) - return ; - } - for(std::vector::iterator it2=_arrays.begin();it2!=_arrays.end();it2++) - { - if((*it2)==0) - return ; - } - if(!_mfields_ptr_released) - { - _mfields_ptr_released=true; - _mfields_ptr->UnRegister(); - } -} - -void ParaMEDMEM2VTK::MEDCouplingMultiFieldsFetcher::applyBufferingPolicy() -{ - if(_effective_pol==0) - {// - for(std::vector::iterator it=_meshes.begin();it!=_meshes.end();it++) - { - if(*it) - { - (*it)->Delete(); - *it=0; - } - } - for(std::vector::iterator it2=_arrays.begin();it2!=_arrays.end();it2++) - { - if(*it2) - { - (*it2)->Delete(); - *it2=0; - } - } - } - //else nothing to do let the plugin bufferize -} - -void ParaMEDMEM2VTK::MEDCouplingMultiFieldsFetcher::appendFieldValueOnAlreadyFetchedData(vtkDataSet *ds, int fieldId) -{ - const TinyInfoOnField& info=_info_per_field[fieldId]; - vtkDoubleArray *arr=_arrays[_array_ids_per_field[fieldId].front()]; - arr->SetName(info._name.c_str()); - if(info._type==0)//ON_CELLS - { - ds->GetCellData()->AddArray(arr); - return ; - } - if(info._type==1)//ON_NODES - { - ds->GetPointData()->AddArray(arr); - return ; - } -} - -int ParaMEDMEM2VTK::MEDCouplingMultiFieldsFetcher::getPosGivenTimeLabel(double t) -{ - int nbOfFields=_time_label_per_field.size(); - for(int i=0;i::iterator it=std::find_if(_time_label_per_field.begin(),_time_label_per_field.end(), - std::bind2nd(std::greater(),t)); - if(it!=_time_label_per_field.end() && it!=_time_label_per_field.end()) - return std::distance(_time_label_per_field.begin(),it); - // - std::ostringstream oss; - oss << "Unexisting time : " << t << " Not in "; - std::copy(_time_label_per_field.begin(),_time_label_per_field.end(),std::ostream_iterator(oss," ")); - oss << " !"; - vtkOutputWindowDisplayErrorText(oss.str().c_str()); - return -1; -} diff --git a/src/Plugins/ParaMEDCorba/VTKMEDCouplingMultiFieldsClient.hxx b/src/Plugins/ParaMEDCorba/VTKMEDCouplingMultiFieldsClient.hxx deleted file mode 100644 index e2206879..00000000 --- a/src/Plugins/ParaMEDCorba/VTKMEDCouplingMultiFieldsClient.hxx +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// - -#ifndef __VTKMEDCOUPLINGMULTIFIELDSCLIENT_HXX__ -#define __VTKMEDCOUPLINGMULTIFIELDSCLIENT_HXX__ - -#include "ParaMEDMEM2VTK_defines.hxx" -#include "ParaMEDCouplingCorbaServant.hh" - -#include -#include - -class vtkDataSet; -class vtkDoubleArray; - -namespace ParaMEDMEM2VTK -{ - /*! - * Stores all info on field without consideration of time - */ - class TinyInfoOnField - { - public: - int _type;//ON_CELLS = 0, ON_NODES = 1, ON_GAUSS_PT = 2, ON_GAUSS_NE = 3 - std::string _name; - }; - - class ParaMEDMEM2VTK_EXPORT MEDCouplingMultiFieldsFetcher - { - public: - MEDCouplingMultiFieldsFetcher(int bufferingPolicy, SALOME_MED::MEDCouplingMultiFieldsCorbaInterface_ptr mfieldsPtr); - ~MEDCouplingMultiFieldsFetcher(); - std::vector getTimeStepsForPV(); - void fetchRegardingPolicy(); - vtkDataSet *buildDataSetOnTime(double time); - private: - void appendFieldValueOnAlreadyFetchedData(vtkDataSet *ds, int fieldId); - int getPosGivenTimeLabel(double t); - private://CORBA Fetching - void retrievesMainTinyInfo(); - void fetchAll(); - void fetchMeshes(); - void fetchDataIfNeeded(int fieldId); - void unregisterRemoteServantIfAllFetched(); - void applyBufferingPolicy(); - private: - int _effective_pol; - SALOME_MED::MEDCouplingMultiFieldsCorbaInterface_var _mfields_ptr; - bool _mfields_ptr_released; - private: - std::vector _info_per_field; - std::vector _time_label_per_field; - std::vector _time_discr_per_field; - std::vector _mesh_id_per_field; - std::vector< std::vector > _array_ids_per_field; - std::vector< std::vector > _time_def_per_field; - private: - int _field_id_previous; - int _arr_pos_previous; - double _time_field_id_previous; - int _arr_id_previous; - int _mesh_id_previous; - private: - std::vector _meshes; - std::vector _is_meshes_polyhedron;//to correct bug of polyhedrons in VTK on DeepCopy. BUG id :0011860 - std::vector _arrays; - private: - static const double EPS_TIME; - }; -} - -#endif diff --git a/src/Plugins/ParaMEDCorba/VTKMEDCouplingUMeshClient.cxx b/src/Plugins/ParaMEDCorba/VTKMEDCouplingUMeshClient.cxx deleted file mode 100644 index 1f664ce5..00000000 --- a/src/Plugins/ParaMEDCorba/VTKMEDCouplingUMeshClient.cxx +++ /dev/null @@ -1,129 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// - -#include "VTKMEDCouplingUMeshClient.hxx" - -#include "vtkPoints.h" -#include "vtkCellArray.h" -#include "vtkDoubleArray.h" -#include "vtkSmartPointer.h" -#include "vtkUnstructuredGrid.h" - -#include -#include -#include -#include - -static const int ParaMEDMEM2VTKTypeTraducer[34]={1,3,21,5,9,7,22,34,23,28,-1,-1,-1,-1,10,14,13,-1,12,-1,24,-1,16,27,-1,26,-1,29,-1,-1,25,42,-1,4}; - -void ParaMEDMEM2VTK::FillMEDCouplingUMeshInstanceFrom(SALOME_MED::MEDCouplingUMeshCorbaInterface_ptr meshPtr, vtkUnstructuredGrid *ret, bool& isPolyh) -{ - meshPtr->Register(); - // - SALOME_TYPES::ListOfDouble *tinyD; - SALOME_TYPES::ListOfLong *tinyI; - SALOME_TYPES::ListOfString *tinyS; - meshPtr->getTinyInfo(tinyD,tinyI,tinyS); - // - int spaceDim=(*tinyI)[1]; - int nbOfNodes=(*tinyI)[2]; - int meshDim=(*tinyI)[5]; - int nbOfCells=(*tinyI)[6]; - int meshLength=(*tinyI)[7]; - std::string name((*tinyS)[0]); - //std::vector compoNames(spaceDim); - //for(int i=0;iInitialize(); - ret->Allocate(nbOfCells); - vtkPoints *points=vtkPoints::New(); - vtkDoubleArray *da=vtkDoubleArray::New(); - da->SetNumberOfComponents(3); - da->SetNumberOfTuples(nbOfNodes); - double *pts=da->GetPointer(0); - // - SALOME_TYPES::ListOfLong *a1Corba; - SALOME_TYPES::ListOfDouble *a2Corba; - meshPtr->getSerialisationData(a1Corba,a2Corba); - if(spaceDim==3) - { - int myLgth=a2Corba->length(); - for(int i=0;iInsertNextCell(vtkType,nbOfNodeInCurCell,tmp); - else - {//polyhedron - isPolyh=true; - std::set s(tmp,tmp+nbOfNodeInCurCell); - vtkSmartPointer faces=vtkSmartPointer::New(); - std::size_t nbOfFaces=std::count(tmp,tmp+nbOfNodeInCurCell,-1)+1; - vtkIdType *work=tmp; - for(std::size_t i=0;iInsertNextCell(nbOfNodesInFace,work); - work=work2+1; - } - s.erase(-1); - std::vector v(s.begin(),s.end()); - ret->InsertNextCell(VTK_POLYHEDRON,(vtkIdType)v.size(),&v[0],(vtkIdType)nbOfFaces,faces->GetPointer()); - } - } - delete [] tmp; - // - delete a1Corba; - delete a2Corba; - // - ret->SetPoints(points); - points->Delete(); - points->SetData(da); - da->Delete(); - // - meshPtr->UnRegister(); -} diff --git a/src/Plugins/ParaMEDCorba/VTKMEDCouplingUMeshClient.hxx b/src/Plugins/ParaMEDCorba/VTKMEDCouplingUMeshClient.hxx deleted file mode 100644 index 5c25c1dc..00000000 --- a/src/Plugins/ParaMEDCorba/VTKMEDCouplingUMeshClient.hxx +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// - -#ifndef __VTKMEDCOUPLINGUMESHCLIENT_HXX__ -#define __VTKMEDCOUPLINGUMESHCLIENT_HXX__ - -#include "ParaMEDCouplingCorbaServant.hh" - -class vtkUnstructuredGrid; - -namespace ParaMEDMEM2VTK -{ - void FillMEDCouplingUMeshInstanceFrom(SALOME_MED::MEDCouplingUMeshCorbaInterface_ptr meshPtr, vtkUnstructuredGrid *ret, bool& isPolyh);//isPolyh bug VTK -} - -#endif diff --git a/src/Plugins/ParaMEDCorba/VTKParaMEDFieldClient.cxx b/src/Plugins/ParaMEDCorba/VTKParaMEDFieldClient.cxx deleted file mode 100644 index c66ed3ac..00000000 --- a/src/Plugins/ParaMEDCorba/VTKParaMEDFieldClient.cxx +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// - -#include "VTKParaMEDFieldClient.hxx" -#include "VTKMEDCouplingFieldClient.hxx" - -#include "vtkDataSet.h" -#include "vtkUnstructuredGrid.h" -#include "vtkMultiBlockDataSet.h" -#include "vtkMultiBlockDataGroupFilter.h" -#include "vtkCompositeDataToUnstructuredGridFilter.h" - -std::vector ParaMEDMEM2VTK::FillMEDCouplingParaFieldDoubleInstanceFrom(SALOME_MED::ParaMEDCouplingFieldDoubleCorbaInterface_ptr fieldPtr, int begin, int end, - vtkMultiBlockDataSet *ret) -{ - std::vector ret2; - int nbOfParts=end-begin; - Engines::IORTab *allSlices=fieldPtr->tior(); - vtkMultiBlockDataGroupFilter *tmp=vtkMultiBlockDataGroupFilter::New(); - for(int i=0;i times; - vtkDataSet *part=ParaMEDMEM2VTK::BuildFullyFilledFromMEDCouplingFieldDoubleInstance(fieldCorba,times); - tmp->AddInputData(part); - part->Delete(); - } - tmp->Update(); - vtkCompositeDataToUnstructuredGridFilter *tmp2=vtkCompositeDataToUnstructuredGridFilter::New(); - tmp2->SetInputData(tmp->GetOutput()); - tmp2->Update(); - // - vtkUnstructuredGrid *ret3=tmp2->GetOutput(); - ret->SetBlock(0,ret3); - // - tmp->Delete(); - tmp2->Delete(); - delete allSlices; - return ret2; -} diff --git a/src/Plugins/ParaMEDCorba/VTKParaMEDFieldClient.hxx b/src/Plugins/ParaMEDCorba/VTKParaMEDFieldClient.hxx deleted file mode 100644 index d174160c..00000000 --- a/src/Plugins/ParaMEDCorba/VTKParaMEDFieldClient.hxx +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// - -#ifndef __VTKPARAMEDFIELDCLIENT_HXX__ -#define __VTKPARAMEDFIELDCLIENT_HXX__ - -#include "ParaMEDMEM2VTK_defines.hxx" -#include "ParaMEDCouplingCorbaServant.hh" - -#include - -class vtkMultiBlockDataSet; - -namespace ParaMEDMEM2VTK -{ - ParaMEDMEM2VTK_EXPORT std::vector FillMEDCouplingParaFieldDoubleInstanceFrom(SALOME_MED::ParaMEDCouplingFieldDoubleCorbaInterface_ptr fieldPtr, int begin, int end, - vtkMultiBlockDataSet *ret); -} - -#endif diff --git a/src/Plugins/ParaMEDCorba/plugin/CMakeLists.txt b/src/Plugins/ParaMEDCorba/plugin/CMakeLists.txt new file mode 100644 index 00000000..b55a755f --- /dev/null +++ b/src/Plugins/ParaMEDCorba/plugin/CMakeLists.txt @@ -0,0 +1,16 @@ +include_directories( ${CMAKE_CURRENT_SOURCE_DIR}/ParaMEDMEM2VTK ) + +paraview_add_plugin(ParaMEDCorbaPlugin + VERSION "1.0" + MODULES ParaMEDCorbaModule + MODULE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/ParaMEDCorbaModule/vtk.module" + SERVER_MANAGER_XML filters.xml +) + +add_subdirectory(ParaMEDMEM2VTK) + +install(TARGETS ParaMEDCorbaPlugin + RUNTIME DESTINATION lib/paraview + LIBRARY DESTINATION lib/paraview + ARCHIVE DESTINATION lib/paraview + ) diff --git a/src/Plugins/ParaMEDCorba/plugin/ParaMEDCorbaModule/CMakeLists.txt b/src/Plugins/ParaMEDCorba/plugin/ParaMEDCorbaModule/CMakeLists.txt new file mode 100644 index 00000000..f2257e29 --- /dev/null +++ b/src/Plugins/ParaMEDCorba/plugin/ParaMEDCorbaModule/CMakeLists.txt @@ -0,0 +1,16 @@ +include_directories( + ${FIELDS_ROOT_DIR}/include/salome + ) + +add_definitions(${OMNIORB_DEFINITIONS}) + +set(classes + vtkParaMEDCorbaSource +) + +vtk_module_add_module(ParaMEDCorbaModule + FORCE_STATIC + CLASSES ${classes} +) + +target_link_libraries(ParaMEDCorbaModule PRIVATE ParaMEDMEM2VTK ${OMNIORB_LIBRARIES} ${FIELDS_SalomeIDLMED}) \ No newline at end of file diff --git a/src/Plugins/ParaMEDCorba/plugin/ParaMEDCorbaModule/ParaMEDMEM2VTK_defines.hxx b/src/Plugins/ParaMEDCorba/plugin/ParaMEDCorbaModule/ParaMEDMEM2VTK_defines.hxx new file mode 100644 index 00000000..f67126ae --- /dev/null +++ b/src/Plugins/ParaMEDCorba/plugin/ParaMEDCorbaModule/ParaMEDMEM2VTK_defines.hxx @@ -0,0 +1,33 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// + +#ifndef __ParaMEDMEM2VTK_defines_h__ +#define __ParaMEDMEM2VTK_defines_h__ + +#ifdef WIN32 +# if defined ParaMEDMEM2VTK_EXPORTS +# define ParaMEDMEM2VTK_EXPORT __declspec( dllexport ) +# else +# define ParaMEDMEM2VTK_EXPORT __declspec( dllimport ) +# endif +#else +# define ParaMEDMEM2VTK_EXPORT +#endif + +#endif // __ParaMEDMEM2VTK_defines_h__ diff --git a/src/Plugins/ParaMEDCorba/plugin/ParaMEDCorbaModule/vtk.module b/src/Plugins/ParaMEDCorba/plugin/ParaMEDCorbaModule/vtk.module new file mode 100644 index 00000000..bf03b2b6 --- /dev/null +++ b/src/Plugins/ParaMEDCorba/plugin/ParaMEDCorbaModule/vtk.module @@ -0,0 +1,15 @@ +NAME + ParaMEDCorbaModule +DEPENDS + VTK::CommonCore + VTK::CommonDataModel + VTK::CommonExecutionModel + VTK::FiltersCore + VTK::FiltersModeling +PRIVATE_DEPENDS + VTK::CommonMisc + VTK::CommonSystem + VTK::FiltersGeneral + VTK::FiltersGeometry + ParaView::VTKExtensionsMisc + \ No newline at end of file diff --git a/src/Plugins/ParaMEDCorba/plugin/ParaMEDCorbaModule/vtkParaMEDCorbaSource.cxx b/src/Plugins/ParaMEDCorba/plugin/ParaMEDCorbaModule/vtkParaMEDCorbaSource.cxx new file mode 100644 index 00000000..5aa24839 --- /dev/null +++ b/src/Plugins/ParaMEDCorba/plugin/ParaMEDCorbaModule/vtkParaMEDCorbaSource.cxx @@ -0,0 +1,283 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// + +#include "vtkParaMEDCorbaSource.h" + +#include "vtkPoints.h" +#include "vtkIntArray.h" +#include "vtkCellData.h" +#include "vtkCellTypes.h" +#include "vtkCharArray.h" +#include "vtkPointData.h" +#include "vtkDoubleArray.h" +#include "vtkMultiBlockDataSet.h" +#include "vtkUnstructuredGrid.h" +// +#include "vtkStreamingDemandDrivenPipeline.h" +#include "vtkGenericAttributeCollection.h" +#include "vtkInformationVector.h" +#include "vtkObjectFactory.h" +#include "vtkInformation.h" +// +#include "string" +#include "fstream" +#include "algorithm" + +#include "VTKMEDCouplingMeshClient.hxx" +#include "VTKMEDCouplingFieldClient.hxx" +#include "VTKMEDCouplingMultiFieldsClient.hxx" +#include "VTKParaMEDFieldClient.hxx" + +//Work with IOR. +#include "ParaMEDCouplingCorbaServant.hh" +// + +vtkStandardNewMacro(vtkParaMEDCorbaSource); +//vtkCxxRevisionMacro(vtkParaMEDCorbaSource,"$Revision$"); + +void *vtkParaMEDCorbaSource::Orb=0; + +vtkParaMEDCorbaSource::vtkParaMEDCorbaSource():mfieldsFetcher(0) +{ + this->MyDataSet=0; + if(!Orb) + { + CORBA::ORB_var *OrbC=new CORBA::ORB_var; + int argc=0; + *OrbC=CORBA::ORB_init(argc,0); + this->Orb=OrbC; + } + this->SetNumberOfInputPorts(0); + this->SetNumberOfOutputPorts(1); +} + +vtkParaMEDCorbaSource::~vtkParaMEDCorbaSource() +{ + delete mfieldsFetcher; +} + +const char *vtkParaMEDCorbaSource::GetIORCorba() +{ + return &IOR[0]; +} + +void vtkParaMEDCorbaSource::SetIORCorba(char *ior) +{ + if(!ior) + return; + if(ior[0]=='\0') + return; + std::size_t length=strlen(ior); + IOR.resize(length+1); + std::copy(ior,ior+length+1,&IOR[0]); + this->Modified(); +} + +void vtkParaMEDCorbaSource::SetBufferingPolicy(int pol) +{ + BufferingPolicy=pol; +} + +int vtkParaMEDCorbaSource::GetBufferingPolicy() +{ + return BufferingPolicy; +} + +//int vtkParaMEDCorbaSource::RequestUpdateExtent( vtkInformation* request, vtkInformationVector** inInfo, vtkInformationVector* outInfo ) +//{ +//return this->Superclass::RequestUpdateExtent(request,inInfo,outInfo); + +/*vtkParaMEDCorbaDataSet* output = vtkParaMEDCorbaDataSet::SafeDownCast( info->Get( vtkDataObject::DATA_OBJECT() ) ); + if ( ! output ) + { + output = vtkParaMEDCorbaDataSet::New(); + output->SetPipelineInformation( info ); + output->Delete(); + this->GetOutputPortInformation( 0 )->Set( vtkDataObject::DATA_EXTENT_TYPE(), output->GetExtentType() ); + }*/ + +// return 1; +//} + +int vtkParaMEDCorbaSource::ProcessRequest(vtkInformation* request, + vtkInformationVector** inputVector, + vtkInformationVector* outputVector) +{ + // generate the data + if(request->Has(vtkDemandDrivenPipeline::REQUEST_DATA())) + { + return this->RequestData(request, inputVector, outputVector); + } + if(request->Has(vtkDemandDrivenPipeline::REQUEST_INFORMATION())) + { + return this->RequestInformation(request, inputVector, outputVector); + } + return this->Superclass::ProcessRequest(request, inputVector, outputVector); +} + +int vtkParaMEDCorbaSource::FillOutputPortInformation(int vtkNotUsed(port), vtkInformation* info) +{ + info->Set(vtkDataObject::DATA_TYPE_NAME(), "vtkMultiBlockDataSet"); + return 1; +} + +int vtkParaMEDCorbaSource::RequestInformation(vtkInformation* request, vtkInformationVector** inInfo, vtkInformationVector* outInfo) +{ + vtkInformation* myInfo=outInfo->GetInformationObject(0); + //myInfo->Set(vtkDataObject::DATA_TYPE_NAME(),"vtkUnstructuredGrid"); + if(!IOR.empty()) + { + //myInfo->Remove(vtkDataObject::DATA_TYPE_NAME()); + //myInfo->Remove(PORT_REQUIREMENTS_FILLED()); + //myInfo->Set(vtkDataObject::DATA_TYPE_NAME(),"vtkUnstructuredGrid"); + //myInfo->Set(PORT_REQUIREMENTS_FILLED(),1); + //vtkUnstructuredGrid *tony=vtkUnstructuredGrid::New(); + //tony->SetInformation(myInfo); + //myInfo->Set(vtkDataObject::DATA_OBJECT(),tony); + // + try { + CORBA::ORB_var *OrbC=(CORBA::ORB_var *)this->Orb; + CORBA::Object_var obj=(*OrbC)->string_to_object(&IOR[0]); + // + Engines::MPIObject_ptr objPara=Engines::MPIObject::_narrow(obj); + if(CORBA::is_nil(objPara)) + {//sequential + this->TotalNumberOfPieces=1; + SALOME_MED::MEDCouplingMultiFieldsCorbaInterface_var multiPtr=SALOME_MED::MEDCouplingMultiFieldsCorbaInterface::_narrow(obj); + if(!CORBA::is_nil(multiPtr)) + {//Request for multiFields + delete mfieldsFetcher; + mfieldsFetcher=new ParaMEDMEM2VTK::MEDCouplingMultiFieldsFetcher(BufferingPolicy,multiPtr); + std::vector tsteps=mfieldsFetcher->getTimeStepsForPV(); + double timeRange[2]; + timeRange[0]=tsteps.front(); + timeRange[1]=tsteps.back(); + myInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_STEPS(),&tsteps[0],(vtkIdType)tsteps.size()); + myInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_RANGE(),timeRange,2); + } + } + else + { + Engines::IORTab *iorTab=objPara->tior(); + this->TotalNumberOfPieces=iorTab->length(); + delete iorTab; + CORBA::release(objPara); + } + myInfo->Set(CAN_HANDLE_PIECE_REQUEST(), 1); + } + catch(CORBA::Exception&) { + vtkErrorMacro("On fetching object error occurs"); + } + } + return 1; +} + +int vtkParaMEDCorbaSource::RequestData(vtkInformation* request, vtkInformationVector** inInfo, vtkInformationVector* outputVector) +{ + vtkInformation *outInfo=outputVector->GetInformationObject(0); + // + this->UpdatePiece = vtkStreamingDemandDrivenPipeline::GetUpdatePiece(outInfo); + this->NumberOfPieces = vtkStreamingDemandDrivenPipeline::GetUpdateNumberOfPieces(outInfo); + this->GhostLevel = vtkStreamingDemandDrivenPipeline::GetUpdateGhostLevel(outInfo); + this->StartPiece=((this->UpdatePiece*this->TotalNumberOfPieces)/this->NumberOfPieces); + this->EndPiece=(((this->UpdatePiece+1)*this->TotalNumberOfPieces)/this->NumberOfPieces); + vtkMultiBlockDataSet *ret0=vtkMultiBlockDataSet::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); + double reqTS = 0; + if(outInfo->Has(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP())) + reqTS = outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP()); + try { + //Client request on ORB. + CORBA::ORB_var *OrbC=(CORBA::ORB_var *)this->Orb; + CORBA::Object_var obj=(*OrbC)->string_to_object(&IOR[0]); + // + Engines::MPIObject_var objPara=Engines::MPIObject::_narrow(obj); + if(CORBA::is_nil(objPara)) + {//sequential + SALOME_MED::MEDCouplingMeshCorbaInterface_var meshPtr=SALOME_MED::MEDCouplingMeshCorbaInterface::_narrow(obj); + if(!CORBA::is_nil(meshPtr)) + { + bool dummy;//bug VTK + vtkDataSet *ret=ParaMEDMEM2VTK::BuildFromMEDCouplingMeshInstance(meshPtr,dummy);//bug VTK + if(!ret) + return 0; + ret0->SetBlock(0,ret); + ret->Delete(); + return 1; + } + SALOME_MED::MEDCouplingFieldDoubleCorbaInterface_var fieldPtr=SALOME_MED::MEDCouplingFieldDoubleCorbaInterface::_narrow(obj); + if(!CORBA::is_nil(fieldPtr)) + { + std::vector ret2; + vtkDataSet *ret=ParaMEDMEM2VTK::BuildFullyFilledFromMEDCouplingFieldDoubleInstance(fieldPtr,ret2); + if(!ret) + { + vtkErrorMacro("On single field CORBA fetching an error occurs !"); + return 0; + } + ret0->SetBlock(0,ret); + ret->Delete(); + // + double timeRange[2]; + timeRange[0]=ret2[0]; + timeRange[1]=ret2[0]; + outInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_STEPS(),&ret2[0],1); + outInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_RANGE(),timeRange,2); + ret0->GetInformation()->Set(vtkDataObject::DATA_TIME_STEP(),ret2[0]); + return 1; + } + SALOME_MED::MEDCouplingMultiFieldsCorbaInterface_var multiPtr=SALOME_MED::MEDCouplingMultiFieldsCorbaInterface::_narrow(obj); + if(!CORBA::is_nil(multiPtr)) + { + vtkDataSet *ret=mfieldsFetcher->buildDataSetOnTime(reqTS); + if(!ret) + { + vtkErrorMacro("On multi fields CORBA fetching an error occurs !"); + return 0; + } + ret0->SetBlock(0,ret); + ret->Delete(); + ret0->GetInformation()->Set(vtkDataObject::DATA_TIME_STEP(),reqTS); + return 1; + } + vtkErrorMacro("Unrecognized sequential CORBA reference !"); + return 0; + } + else + { + SALOME_MED::ParaMEDCouplingFieldDoubleCorbaInterface_var paraFieldCorba=SALOME_MED::ParaMEDCouplingFieldDoubleCorbaInterface::_narrow(obj); + if(!CORBA::is_nil(paraFieldCorba)) + { + ParaMEDMEM2VTK::FillMEDCouplingParaFieldDoubleInstanceFrom(paraFieldCorba,this->StartPiece,this->EndPiece,ret0); + return 1; + } + vtkErrorMacro("Unrecognized parallel CORBA reference !"); + return 0; + } + } + catch(CORBA::Exception&) { + vtkErrorMacro("On fetching object error occurs"); + } +} + +void vtkParaMEDCorbaSource::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf( os, indent ); + os << "Data: " << this->MyDataSet << "\n"; +} + diff --git a/src/Plugins/ParaMEDCorba/plugin/ParaMEDCorbaModule/vtkParaMEDCorbaSource.h b/src/Plugins/ParaMEDCorba/plugin/ParaMEDCorbaModule/vtkParaMEDCorbaSource.h new file mode 100644 index 00000000..4fce88ba --- /dev/null +++ b/src/Plugins/ParaMEDCorba/plugin/ParaMEDCorbaModule/vtkParaMEDCorbaSource.h @@ -0,0 +1,81 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// + + +#ifndef __vtkParaMEDCorbaSource_h +#define __vtkParaMEDCorbaSource_h + +#include "ParaMEDMEM2VTK_defines.hxx" +#include "vtkUnstructuredGridAlgorithm.h" +#include + +class vtkDoubleArray; +class vtkUnstructuredGrid; + +namespace ParaMEDMEM2VTK +{ + class MEDCouplingMultiFieldsFetcher; +} + +class vtkParaMEDCorbaSource : public vtkAlgorithm // +{ +public: + vtkTypeMacro(vtkParaMEDCorbaSource, vtkAlgorithm) + ParaMEDMEM2VTK_EXPORT static vtkParaMEDCorbaSource* New(); + virtual void PrintSelf( ostream& os, vtkIndent indent ); + const char *GetIORCorba(); + void SetIORCorba(char *ior); + void SetBufferingPolicy(int pol); + int GetBufferingPolicy(); +protected: + vtkParaMEDCorbaSource(); + virtual ~vtkParaMEDCorbaSource(); + int FillOutputPortInformation(int vtkNotUsed(port), vtkInformation* info); + int ProcessRequest(vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector); + //virtual int RequestUpdateExtent( vtkInformation* request, vtkInformationVector** inInfo, vtkInformationVector* outInfo ); + virtual int RequestInformation( vtkInformation* request, vtkInformationVector** inInfo, vtkInformationVector* outInfo ); + virtual int RequestData( vtkInformation* request, vtkInformationVector** inInfo, vtkInformationVector* outInfo ); + //BTX + int TotalNumberOfPieces; + int NumberOfPieces; + int UpdatePiece; + int GhostLevel; + int StartPiece; + int EndPiece; + int BufferingPolicy; + vtkUnstructuredGrid *MyDataSet; + std::vector IOR; + ParaMEDMEM2VTK::MEDCouplingMultiFieldsFetcher *mfieldsFetcher; + //not clean but to avoid to include CORBA.h in this *.h + static void *Orb; + //ETX +private: + /*void traduceMedMeshToUnstructuredDataset(vtkUnstructuredGrid *ret, int nbOfCells, int nbOfNodes, + int nbOfTypes, const int *types, const int *nbOfEltsPerTypes, const int *nodalConnectivity, + const double *coords, int spaceDim); + vtkDoubleArray *buildDataArrayFromMedCoords(const double *coords, int nbOfNodes, int spaceDim); + void reorganizeCellConnectivity(int vtkType, int nbOfNodes, const int *medConn, int *vtkConn); + int transformMedGeomEltType2VtkType(int typeMed, int *nbOfNodesPerCell);*/ + // + vtkParaMEDCorbaSource( const vtkParaMEDCorbaSource& ); // Not implemented. + void operator = ( const vtkParaMEDCorbaSource& ); // Not implemented. +}; + +#endif // __vtkParaMEDCorbaSource_h + diff --git a/src/Plugins/ParaMEDCorba/plugin/ParaMEDMEM2VTK/CMakeLists.txt b/src/Plugins/ParaMEDCorba/plugin/ParaMEDMEM2VTK/CMakeLists.txt new file mode 100644 index 00000000..7005a614 --- /dev/null +++ b/src/Plugins/ParaMEDCorba/plugin/ParaMEDMEM2VTK/CMakeLists.txt @@ -0,0 +1,34 @@ +include_directories( + ${OMNIORB_INCLUDE_DIR} + ${FIELDS_ROOT_DIR}/include/salome + ${KERNEL_ROOT_DIR}/include/salome + ${CMAKE_CURRENT_SOURCE_DIR}/../ParaMEDCorbaModule + ) + +add_definitions(${OMNIORB_DEFINITIONS}) + +add_library(ParaMEDMEM2VTK SHARED VTKMEDCouplingMeshClient.cxx VTKMEDCouplingUMeshClient.cxx VTKMEDCouplingCMeshClient.cxx VTKMEDCouplingFieldClient.cxx VTKParaMEDFieldClient.cxx VTKMEDCouplingMultiFieldsClient.cxx VTKMEDCouplingCurveLinearMeshClient.cxx) + +target_link_libraries(ParaMEDMEM2VTK + VTK::CommonCore + VTK::CommonDataModel + VTK::CommonExecutionModel + VTK::FiltersGeneral + ParaView::VTKExtensionsMisc + ${OMNIORB_LIBRARIES} + ${FIELDS_SalomeIDLMED} + ${KERNEL_SalomeIDLKernel} + ) + +#Build library with a static runtime and ignore MSVCRT.lib on WINDOWS +if(WIN32) + if(CMAKE_BUILD_TYPE STREQUAL Debug) + set_target_properties(ParaMEDMEM2VTK PROPERTIES LINK_FLAGS "/NODEFAULTLIB:MSVCRTD") + set_target_properties(ParaMEDMEM2VTK PROPERTIES COMPILE_FLAGS "/MTd") + else() + set_target_properties(ParaMEDMEM2VTK PROPERTIES LINK_FLAGS "/NODEFAULTLIB:MSVCRT") + set_target_properties(ParaMEDMEM2VTK PROPERTIES COMPILE_FLAGS "/MT") + endif() +endif(WIN32) + +install(TARGETS ParaMEDMEM2VTK EXPORT DESTINATION ${SALOME_INSTALL_LIBS}) diff --git a/src/Plugins/ParaMEDCorba/plugin/ParaMEDMEM2VTK/VTKMEDCouplingCMeshClient.cxx b/src/Plugins/ParaMEDCorba/plugin/ParaMEDMEM2VTK/VTKMEDCouplingCMeshClient.cxx new file mode 100644 index 00000000..67fbb5e5 --- /dev/null +++ b/src/Plugins/ParaMEDCorba/plugin/ParaMEDMEM2VTK/VTKMEDCouplingCMeshClient.cxx @@ -0,0 +1,100 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// + +#include "VTKMEDCouplingCMeshClient.hxx" + +#include "vtkErrorCode.h" +#include "vtkDoubleArray.h" +#include "vtkRectilinearGrid.h" + +#include +#include + +void ParaMEDMEM2VTK::FillMEDCouplingCMeshInstanceFrom(SALOME_MED::MEDCouplingCMeshCorbaInterface_ptr meshPtr, vtkRectilinearGrid *ret) +{ + meshPtr->Register(); + SALOME_TYPES::ListOfDouble *tinyD; + SALOME_TYPES::ListOfLong *tinyI; + SALOME_TYPES::ListOfString *tinyS; + meshPtr->getTinyInfo(tinyD,tinyI,tinyS); + int sizePerAxe[3]={1,1,1}; + bool isOK[3]={false,false,false}; + if((*tinyI)[0]>0) + { sizePerAxe[0]=(*tinyI)[0]; isOK[0]=true; } + if((*tinyI)[1]>0) + { sizePerAxe[1]=(*tinyI)[1]; isOK[1]=true; } + if((*tinyI)[2]>0) + { sizePerAxe[2]=(*tinyI)[2]; isOK[2]=true; } + ret->SetDimensions(sizePerAxe[0],sizePerAxe[1],sizePerAxe[2]); + delete tinyI; + delete tinyS; + delete tinyD; + SALOME_TYPES::ListOfDouble *bigD; + meshPtr->getSerialisationData(tinyI,bigD); + delete tinyI; + int offset=0; + vtkDoubleArray *da=0; + if(isOK[0]) + { + da=vtkDoubleArray::New(); + da->SetNumberOfTuples(sizePerAxe[0]); + da->SetNumberOfComponents(1); + double *pt=da->GetPointer(0); + for(int i=0;iSetXCoordinates(da); + da->Delete(); + offset+=sizePerAxe[0]; + } + if(isOK[1]) + { + da=vtkDoubleArray::New(); + da->SetNumberOfTuples(sizePerAxe[1]); + da->SetNumberOfComponents(1); + double *pt=da->GetPointer(0); + for(int i=0;iSetYCoordinates(da); + da->Delete(); + offset+=sizePerAxe[1]; + } + else + { + da=vtkDoubleArray::New(); da->SetNumberOfTuples(1); da->SetNumberOfComponents(1); + double *pt=da->GetPointer(0); *pt=0.; ret->SetYCoordinates(da); da->Delete(); + } + if(isOK[2]) + { + da=vtkDoubleArray::New(); + da->SetNumberOfTuples(sizePerAxe[2]); + da->SetNumberOfComponents(1); + double *pt=da->GetPointer(0); + for(int i=0;iSetZCoordinates(da); + da->Delete(); + } + else + { + da=vtkDoubleArray::New(); da->SetNumberOfTuples(1); da->SetNumberOfComponents(1); + double *pt=da->GetPointer(0); *pt=0.; ret->SetZCoordinates(da); da->Delete(); + } + delete bigD; + meshPtr->UnRegister(); +} diff --git a/src/Plugins/ParaMEDCorba/plugin/ParaMEDMEM2VTK/VTKMEDCouplingCMeshClient.hxx b/src/Plugins/ParaMEDCorba/plugin/ParaMEDMEM2VTK/VTKMEDCouplingCMeshClient.hxx new file mode 100644 index 00000000..07117236 --- /dev/null +++ b/src/Plugins/ParaMEDCorba/plugin/ParaMEDMEM2VTK/VTKMEDCouplingCMeshClient.hxx @@ -0,0 +1,32 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// + +#ifndef __VTKMEDCOUPLINGCMESHCLIENT_HXX__ +#define __VTKMEDCOUPLINGCMESHCLIENT_HXX__ + +#include "ParaMEDCouplingCorbaServant.hh" + +class vtkRectilinearGrid; + +namespace ParaMEDMEM2VTK +{ + void FillMEDCouplingCMeshInstanceFrom(SALOME_MED::MEDCouplingCMeshCorbaInterface_ptr meshPtr, vtkRectilinearGrid *ret); +} + +#endif diff --git a/src/Plugins/ParaMEDCorba/plugin/ParaMEDMEM2VTK/VTKMEDCouplingCurveLinearMeshClient.cxx b/src/Plugins/ParaMEDCorba/plugin/ParaMEDMEM2VTK/VTKMEDCouplingCurveLinearMeshClient.cxx new file mode 100644 index 00000000..54b73a3e --- /dev/null +++ b/src/Plugins/ParaMEDCorba/plugin/ParaMEDMEM2VTK/VTKMEDCouplingCurveLinearMeshClient.cxx @@ -0,0 +1,73 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// + +#include "VTKMEDCouplingCurveLinearMeshClient.hxx" + +#include "vtkPoints.h" +#include "vtkErrorCode.h" +#include "vtkDoubleArray.h" +#include "vtkStructuredGrid.h" + +#include +#include + +void ParaMEDMEM2VTK::FillMEDCouplingCurveLinearMeshInstanceFrom(SALOME_MED::MEDCouplingCurveLinearMeshCorbaInterface_ptr meshPtr, vtkStructuredGrid *ret) +{ + meshPtr->Register(); + SALOME_TYPES::ListOfDouble *tinyD; + SALOME_TYPES::ListOfLong *tinyI; + SALOME_TYPES::ListOfString *tinyS; + meshPtr->getTinyInfo(tinyD,tinyI,tinyS); + int meshStr[3]={1,1,1}; + int meshDim=(*tinyI)[2]; + if(meshDim<0 || meshDim>3) + vtkErrorWithObjectMacro(ret,"Internal error in ParaMEDCorba plugin : distant curvilinear mesh has a mesh dimension not in [0,3] !"); + for(int i=0;iSetDimensions(meshStr); + int nbOfNodes=(*tinyI)[3+meshDim]; + int spaceDim=(*tinyI)[3+meshDim+1]; + delete tinyD; + delete tinyI; + delete tinyS; + // + vtkDoubleArray *da=vtkDoubleArray::New(); + da->SetNumberOfComponents(3); + da->SetNumberOfTuples(nbOfNodes); + double *pt=da->GetPointer(0); + SALOME_TYPES::ListOfDouble *bigD; + meshPtr->getSerialisationData(tinyI,bigD); + delete tinyI; + if(bigD->length()!=nbOfNodes*spaceDim) + vtkErrorWithObjectMacro(ret,"Internal error in ParaMEDCorba plugin : distant curvilinear mesh, mismatch between informations ! Internal error !"); + for(int i=0;iSetPoints(points); + points->SetData(da); + points->Delete(); + da->Delete(); + meshPtr->UnRegister(); +} diff --git a/src/Plugins/ParaMEDCorba/plugin/ParaMEDMEM2VTK/VTKMEDCouplingCurveLinearMeshClient.hxx b/src/Plugins/ParaMEDCorba/plugin/ParaMEDMEM2VTK/VTKMEDCouplingCurveLinearMeshClient.hxx new file mode 100644 index 00000000..25385ea5 --- /dev/null +++ b/src/Plugins/ParaMEDCorba/plugin/ParaMEDMEM2VTK/VTKMEDCouplingCurveLinearMeshClient.hxx @@ -0,0 +1,32 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// + +#ifndef __VTKMEDCOUPLINGCURVELINEARMESHCLIENT_HXX__ +#define __VTKMEDCOUPLINGCURVELINEARMESHCLIENT_HXX__ + +#include "ParaMEDCouplingCorbaServant.hh" + +class vtkStructuredGrid; + +namespace ParaMEDMEM2VTK +{ + void FillMEDCouplingCurveLinearMeshInstanceFrom(SALOME_MED::MEDCouplingCurveLinearMeshCorbaInterface_ptr meshPtr, vtkStructuredGrid *ret); +} + +#endif diff --git a/src/Plugins/ParaMEDCorba/plugin/ParaMEDMEM2VTK/VTKMEDCouplingFieldClient.cxx b/src/Plugins/ParaMEDCorba/plugin/ParaMEDMEM2VTK/VTKMEDCouplingFieldClient.cxx new file mode 100644 index 00000000..2bbb6298 --- /dev/null +++ b/src/Plugins/ParaMEDCorba/plugin/ParaMEDMEM2VTK/VTKMEDCouplingFieldClient.cxx @@ -0,0 +1,212 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// + +#include "VTKMEDCouplingFieldClient.hxx" +#include "VTKMEDCouplingMeshClient.hxx" + +#include "vtkErrorCode.h" +#include "vtkCellData.h" +#include "vtkPointData.h" +#include "vtkDoubleArray.h" +#include "vtkUnstructuredGrid.h" + +#include +#include + +std::vector ParaMEDMEM2VTK::FillMEDCouplingFieldDoubleInstanceFrom(SALOME_MED::MEDCouplingFieldDoubleCorbaInterface_ptr fieldPtr, vtkDataSet *ret) +{ + fieldPtr->Register(); + // + SALOME_MED::MEDCouplingMeshCorbaInterface_var meshPtr=fieldPtr->getMesh(); + ParaMEDMEM2VTK::FillMEDCouplingMeshInstanceFrom(meshPtr,ret); + meshPtr->UnRegister(); + // + std::vector ret2=FillMEDCouplingFieldDoublePartOnly(fieldPtr,ret); + fieldPtr->UnRegister(); + // + return ret2; +} + +std::vector ParaMEDMEM2VTK::FillMEDCouplingFieldDoublePartOnly(SALOME_MED::MEDCouplingFieldDoubleCorbaInterface_ptr fieldPtr, vtkDataSet *ret) +{ + std::vector ret2; + // + SALOME_TYPES::ListOfLong *tinyL; + SALOME_TYPES::ListOfDouble *tinyD; + SALOME_TYPES::ListOfString *tinyS; + fieldPtr->getTinyInfo(tinyL,tinyD,tinyS); + // + int typeOfField=(*tinyL)[0];// 0:ON_CELLS, 1:ON_NODES, 2:ON_GAUSS_PT, 3:ON_GAUSS_NE + int timeDiscr=(*tinyL)[1]; + int nbOfTuples=(*tinyL)[3]; + int nbOfComponents=(*tinyL)[4]; + std::vector comps(nbOfComponents); + for(int i=0;iSetName(name.c_str()); + var0->SetNumberOfComponents(nbOfComponents); + var0->SetNumberOfTuples(nbOfTuples); + for(int i=0;iSetComponentName(i,comps[i].c_str()); + var0Ptr=var0->GetPointer(0); + if(timeDiscr==7) + { + var1->SetNumberOfComponents(nbOfComponents); + var1->SetNumberOfTuples(nbOfTuples); + var1Ptr=var1->GetPointer(0); + std::ostringstream oss; oss << name << "_end_array"; + var1->SetName(oss.str().c_str()); + } + // + SALOME_TYPES::ListOfLong *bigDataI; + SALOME_TYPES::ListOfDouble2 *bigArr; + fieldPtr->getSerialisationData(bigDataI,bigArr); + delete bigDataI;//for the moment gauss points are not dealt + SALOME_TYPES::ListOfDouble& oneArr=(*bigArr)[0]; + int nbVals=oneArr.length(); + for(int i=0;iGetCellData()->AddArray(var0); + if(timeDiscr==7) + ret->GetCellData()->AddArray(var1); + break; + case 1://ON_NODES + ret->GetPointData()->AddArray(var0); + if(timeDiscr==7) + ret->GetCellData()->AddArray(var1); + break; + default: + vtkErrorWithObjectMacro(ret,"Not implemented yet for gauss fields and gauss on elements fields !"); + } + var0->Delete(); + if(timeDiscr==7) + var1->Delete(); + // + return ret2; +} + +vtkDataSet *ParaMEDMEM2VTK::BuildFullyFilledFromMEDCouplingFieldDoubleInstance(SALOME_MED::MEDCouplingFieldDoubleCorbaInterface_ptr fieldPtr, + std::vector& times) +{ + fieldPtr->Register(); + SALOME_MED::MEDCouplingMeshCorbaInterface_var meshPtr=fieldPtr->getMesh(); + bool dummy;//VTK bug + vtkDataSet *ret=ParaMEDMEM2VTK::BuildFromMEDCouplingMeshInstance(meshPtr,dummy);//VTK bug + meshPtr->UnRegister(); + // + std::vector ret2=FillMEDCouplingFieldDoublePartOnly(fieldPtr,ret); + times=ret2; + // + fieldPtr->UnRegister(); + return ret; +} + +vtkDoubleArray *ParaMEDMEM2VTK::BuildFromMEDCouplingFieldDoubleArr(SALOME_MED::DataArrayDoubleCorbaInterface_ptr dadPtr) +{ + vtkDoubleArray *ret=vtkDoubleArray::New(); + // + SALOME_TYPES::ListOfLong *tinyL=0; + SALOME_TYPES::ListOfDouble *bigD=0; + SALOME_TYPES::ListOfString *tinyS=0; + // + dadPtr->getTinyInfo(tinyL,tinyS); + int nbOfTuples=(*tinyL)[0]; + int nbOfCompo=(*tinyL)[1]; + std::string name((*tinyS)[0]); + std::vector comps(nbOfCompo); + for(int i=0;iSetName(name.c_str()); + ret->SetNumberOfComponents(nbOfCompo); + ret->SetNumberOfTuples(nbOfTuples); + for(int i=0;iSetComponentName(i,comps[i].c_str()); + else + { + std::ostringstream oss; oss << "Comp" << i; + ret->SetComponentName(i,oss.str().c_str()); + } + } + int nbElems=nbOfCompo*nbOfTuples; + double *pt=ret->GetPointer(0); + dadPtr->getSerialisationData(bigD); + for(int i=0;i + +class vtkDataSet; +class vtkDoubleArray; + +namespace ParaMEDMEM2VTK +{ + std::vector FillMEDCouplingFieldDoubleInstanceFrom(SALOME_MED::MEDCouplingFieldDoubleCorbaInterface_ptr fieldPtr, vtkDataSet *ret); + std::vector FillMEDCouplingFieldDoublePartOnly(SALOME_MED::MEDCouplingFieldDoubleCorbaInterface_ptr fieldPtr, vtkDataSet *ret); + ParaMEDMEM2VTK_EXPORT vtkDataSet *BuildFullyFilledFromMEDCouplingFieldDoubleInstance(SALOME_MED::MEDCouplingFieldDoubleCorbaInterface_ptr fieldPtr, + std::vector& times); + ParaMEDMEM2VTK_EXPORT vtkDoubleArray *BuildFromMEDCouplingFieldDoubleArr(SALOME_MED::DataArrayDoubleCorbaInterface_ptr dadPtr); +} + +#endif diff --git a/src/Plugins/ParaMEDCorba/plugin/ParaMEDMEM2VTK/VTKMEDCouplingMeshClient.cxx b/src/Plugins/ParaMEDCorba/plugin/ParaMEDMEM2VTK/VTKMEDCouplingMeshClient.cxx new file mode 100644 index 00000000..114df1bd --- /dev/null +++ b/src/Plugins/ParaMEDCorba/plugin/ParaMEDMEM2VTK/VTKMEDCouplingMeshClient.cxx @@ -0,0 +1,101 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// + +#include "VTKMEDCouplingMeshClient.hxx" +#include "VTKMEDCouplingUMeshClient.hxx" +#include "VTKMEDCouplingCMeshClient.hxx" +#include "VTKMEDCouplingCurveLinearMeshClient.hxx" + +#include "vtkErrorCode.h" +#include "vtkUnstructuredGrid.h" +#include "vtkRectilinearGrid.h" +#include "vtkStructuredGrid.h" + +#include +#include + +//vtkErrorMacro("Cannot call Start() twice before calling Finish()."); +void ParaMEDMEM2VTK::FillMEDCouplingMeshInstanceFrom(SALOME_MED::MEDCouplingMeshCorbaInterface_ptr meshPtr, vtkDataSet *ret) +{ + SALOME_MED::MEDCouplingUMeshCorbaInterface_var umeshPtr=SALOME_MED::MEDCouplingUMeshCorbaInterface::_narrow(meshPtr); + if(!CORBA::is_nil(umeshPtr)) + { + vtkUnstructuredGrid *ret1=vtkUnstructuredGrid::SafeDownCast(ret); + if(!ret1) + { + vtkErrorWithObjectMacro(ret,"Internal error in ParaMEDCorba plugin : mismatch between VTK type and CORBA type UMesh !"); + return ; + } + bool dummy;//VTK bug + ParaMEDMEM2VTK::FillMEDCouplingUMeshInstanceFrom(umeshPtr,ret1,dummy);//VTK bug + return ; + } + SALOME_MED::MEDCouplingCMeshCorbaInterface_var cmeshPtr=SALOME_MED::MEDCouplingCMeshCorbaInterface::_narrow(meshPtr); + if(!CORBA::is_nil(cmeshPtr)) + { + vtkRectilinearGrid *ret1=vtkRectilinearGrid::SafeDownCast(ret); + if(!ret1) + { + vtkErrorWithObjectMacro(ret,"Internal error in ParaMEDCorba plugin : mismatch between VTK type and CORBA type CMesh !"); + return ; + } + ParaMEDMEM2VTK::FillMEDCouplingCMeshInstanceFrom(cmeshPtr,ret1); + return ; + } + SALOME_MED::MEDCouplingCurveLinearMeshCorbaInterface_var clmeshPtr=SALOME_MED::MEDCouplingCurveLinearMeshCorbaInterface::_narrow(meshPtr); + if(!CORBA::is_nil(clmeshPtr)) + { + vtkStructuredGrid *ret1=vtkStructuredGrid::SafeDownCast(ret); + if(!ret1) + { + vtkErrorWithObjectMacro(ret,"Internal error in ParaMEDCorba plugin : mismatch between VTK type and CORBA type CurveLinearMesh !"); + return ; + } + ParaMEDMEM2VTK::FillMEDCouplingCurveLinearMeshInstanceFrom(clmeshPtr,ret1); + return ; + } + vtkErrorWithObjectMacro(ret,"Error : CORBA mesh type ! Mesh type not managed !"); +} + +vtkDataSet *ParaMEDMEM2VTK::BuildFromMEDCouplingMeshInstance(SALOME_MED::MEDCouplingMeshCorbaInterface_ptr meshPtr, bool& isPolyh) +{ + SALOME_MED::MEDCouplingUMeshCorbaInterface_var umeshPtr=SALOME_MED::MEDCouplingUMeshCorbaInterface::_narrow(meshPtr); + if(!CORBA::is_nil(umeshPtr)) + { + vtkUnstructuredGrid *ret1=vtkUnstructuredGrid::New(); + ParaMEDMEM2VTK::FillMEDCouplingUMeshInstanceFrom(umeshPtr,ret1,isPolyh); + return ret1; + } + SALOME_MED::MEDCouplingCMeshCorbaInterface_var cmeshPtr=SALOME_MED::MEDCouplingCMeshCorbaInterface::_narrow(meshPtr); + if(!CORBA::is_nil(cmeshPtr)) + { + vtkRectilinearGrid *ret1=vtkRectilinearGrid::New(); + ParaMEDMEM2VTK::FillMEDCouplingCMeshInstanceFrom(cmeshPtr,ret1); + return ret1; + } + SALOME_MED::MEDCouplingCurveLinearMeshCorbaInterface_var clmeshPtr=SALOME_MED::MEDCouplingCurveLinearMeshCorbaInterface::_narrow(meshPtr); + if(!CORBA::is_nil(clmeshPtr)) + { + vtkStructuredGrid *ret1=vtkStructuredGrid::New(); + ParaMEDMEM2VTK::FillMEDCouplingCurveLinearMeshInstanceFrom(clmeshPtr,ret1); + return ret1; + } + vtkOutputWindowDisplayErrorText("Error : CORBA mesh type ! Mesh type not managed #2 !"); + return 0; +} diff --git a/src/Plugins/ParaMEDCorba/plugin/ParaMEDMEM2VTK/VTKMEDCouplingMeshClient.hxx b/src/Plugins/ParaMEDCorba/plugin/ParaMEDMEM2VTK/VTKMEDCouplingMeshClient.hxx new file mode 100644 index 00000000..39d504cd --- /dev/null +++ b/src/Plugins/ParaMEDCorba/plugin/ParaMEDMEM2VTK/VTKMEDCouplingMeshClient.hxx @@ -0,0 +1,34 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// + +#ifndef __VTKMEDCOUPLINGMESHCLIENT_HXX__ +#define __VTKMEDCOUPLINGMESHCLIENT_HXX__ + +#include "ParaMEDMEM2VTK_defines.hxx" +#include "ParaMEDCouplingCorbaServant.hh" + +class vtkDataSet; + +namespace ParaMEDMEM2VTK +{ + void FillMEDCouplingMeshInstanceFrom(SALOME_MED::MEDCouplingMeshCorbaInterface_ptr meshPtr, vtkDataSet *ret); + ParaMEDMEM2VTK_EXPORT vtkDataSet *BuildFromMEDCouplingMeshInstance(SALOME_MED::MEDCouplingMeshCorbaInterface_ptr meshPtr, bool& isPolyh);//isPolyh bug VTK +} + +#endif diff --git a/src/Plugins/ParaMEDCorba/plugin/ParaMEDMEM2VTK/VTKMEDCouplingMultiFieldsClient.cxx b/src/Plugins/ParaMEDCorba/plugin/ParaMEDMEM2VTK/VTKMEDCouplingMultiFieldsClient.cxx new file mode 100644 index 00000000..c3c080a0 --- /dev/null +++ b/src/Plugins/ParaMEDCorba/plugin/ParaMEDMEM2VTK/VTKMEDCouplingMultiFieldsClient.cxx @@ -0,0 +1,340 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// + +// To access to vtkUnstructuredGrid::Faces and FaceLocations +#ifdef WIN32 +#define _ALLOW_KEYWORD_MACROS +#endif +#define protected public + +#include "VTKMEDCouplingMultiFieldsClient.hxx" +#include "VTKMEDCouplingMeshClient.hxx" +#include "VTKMEDCouplingFieldClient.hxx" + +#include "vtkUnstructuredGrid.h" +#include "vtkRectilinearGrid.h" +#include "vtkDoubleArray.h" +#include "vtkErrorCode.h" +#include "vtkCellData.h" +#include "vtkIdTypeArray.h" +#include "vtkPointData.h" + +#include +#include +#include +#include + +const double ParaMEDMEM2VTK::MEDCouplingMultiFieldsFetcher::EPS_TIME=1e-7; + +ParaMEDMEM2VTK::MEDCouplingMultiFieldsFetcher::MEDCouplingMultiFieldsFetcher(int bufferingPolicy, + SALOME_MED::MEDCouplingMultiFieldsCorbaInterface_ptr mfieldsPtr):_effective_pol(bufferingPolicy),_mfields_ptr_released(false) +{ + _mfields_ptr=SALOME_MED::MEDCouplingMultiFieldsCorbaInterface::_duplicate(mfieldsPtr); + _mfields_ptr->Register(); +} + +ParaMEDMEM2VTK::MEDCouplingMultiFieldsFetcher::~MEDCouplingMultiFieldsFetcher() +{ + for(std::vector::iterator it=_meshes.begin();it!=_meshes.end();it++) + { + if(*it) + (*it)->Delete(); + } + for(std::vector::iterator it2=_arrays.begin();it2!=_arrays.end();it2++) + { + if(*it2) + (*it2)->Delete(); + } + if(!_mfields_ptr_released) + _mfields_ptr->UnRegister(); +} + +std::vector ParaMEDMEM2VTK::MEDCouplingMultiFieldsFetcher::getTimeStepsForPV() +{ + retrievesMainTinyInfo(); + int nbOfFields=_mesh_id_per_field.size(); + // + _time_label_per_field.resize(nbOfFields); + SALOME_MED::MEDCouplingFieldOverTimeCorbaInterface_var fotPtr=SALOME_MED::MEDCouplingFieldOverTimeCorbaInterface::_narrow(_mfields_ptr); + if(CORBA::is_nil(fotPtr)) + { + for(CORBA::Long i=0;i=10) + { + fetchAll(); + return ; + } + if(_effective_pol>=1 && _effective_pol<=9) + { + fetchMeshes(); + return ; + } +} + +vtkDataSet *ParaMEDMEM2VTK::MEDCouplingMultiFieldsFetcher::buildDataSetOnTime(double time) +{ + int fieldId=getPosGivenTimeLabel(time); + if(fieldId<0) + return 0; + fetchDataIfNeeded(fieldId); + int meshId=_mesh_id_per_field[fieldId]; + vtkDataSet *ret0=_meshes[meshId]; + std::string clsName=ret0->GetClassName(); + if(clsName=="vtkUnstructuredGrid") + { + vtkUnstructuredGrid *ret1=vtkUnstructuredGrid::New(); + ret1->DeepCopy(ret0); + if(_is_meshes_polyhedron[meshId])//bug VTK polyhedron + {//bug VTK polyhedron part + ret1->Faces->UnRegister(ret1); + ret1->Faces=vtkIdTypeArray::New(); + ret1->Faces->DeepCopy(((vtkUnstructuredGrid *)ret0)->GetFaces()); + ret1->Faces->Register(ret1); + ret1->Faces->Delete(); + ret1->FaceLocations->UnRegister(ret1); + ret1->FaceLocations=vtkIdTypeArray::New(); + ret1->FaceLocations->DeepCopy(((vtkUnstructuredGrid *)ret0)->GetFaceLocations()); + ret1->FaceLocations->Register(ret1); + ret1->FaceLocations->Delete(); + }//end bug VTK polyhedron part + appendFieldValueOnAlreadyFetchedData(ret1,fieldId); + applyBufferingPolicy(); + return ret1; + } + if(clsName=="vtkRectilinearGrid") + { + vtkRectilinearGrid *ret1=vtkRectilinearGrid::New(); + ret1->DeepCopy(ret0); + appendFieldValueOnAlreadyFetchedData(ret1,fieldId); + applyBufferingPolicy(); + return ret1; + } + return 0; +} + +void ParaMEDMEM2VTK::MEDCouplingMultiFieldsFetcher::retrievesMainTinyInfo() +{ + SALOME_TYPES::ListOfLong *tinyL=0; + SALOME_TYPES::ListOfDouble *tinyD=0; + SALOME_TYPES::ListOfString *tinyS=0; + // + CORBA::Long nbOfArrays; + CORBA::Long nbOfFields; + CORBA::Long nbOfMeshes=_mfields_ptr->getMainTinyInfo(tinyL,tinyD,nbOfArrays,nbOfFields); + int sz=(*tinyL)[0];//nbOfFields + //int sz2=(*tinyL)[1];//sigma(nbOfArraysPerField) + _time_discr_per_field.resize(sz);//4 : NO_TIME 5:ONE_TIME 6:LINEAR_TIME 7:CONST_ON_TIME_INTERVAL + _mesh_id_per_field.resize(sz); + _array_ids_per_field.resize(sz); + _time_def_per_field.resize(sz); + int offsetTime=0; + int offsetArrays=0; + for(int i=0;igetTinyInfo(i,tinyL,tinyD,tinyS); + _info_per_field[i]._type=(*tinyL)[0]; + _info_per_field[i]._name=(*tinyS)[0]; + delete tinyL; + delete tinyD; + delete tinyS; + } +} + +void ParaMEDMEM2VTK::MEDCouplingMultiFieldsFetcher::fetchAll() +{ + fetchMeshes(); + int nbOfArrays=_arrays.size(); + for(int i=0;igetArray(i); + if(_arrays[i]) + _arrays[i]->Delete(); + _arrays[i]=ParaMEDMEM2VTK::BuildFromMEDCouplingFieldDoubleArr(daPtr); + daPtr->UnRegister(); + } + unregisterRemoteServantIfAllFetched(); +} + +/*! + * Fetches meshes without regarding if already fetched + */ +void ParaMEDMEM2VTK::MEDCouplingMultiFieldsFetcher::fetchMeshes() +{ + int nbOfMeshes=_meshes.size(); + for(int i=0;igetMeshWithId(i); + if(_meshes[i]) + _meshes[i]->Delete(); + bool polyh=false;//bug VTK + _meshes[i]=ParaMEDMEM2VTK::BuildFromMEDCouplingMeshInstance(mPtr,polyh);//bug VTK + _is_meshes_polyhedron[i]=polyh;//bug VTK + mPtr->UnRegister(); + } + unregisterRemoteServantIfAllFetched(); +} + +/*! + * For a field with id 'fieldId' this method CORBA fetch, if needed, basic data. + * 'fieldId' should be correct no check of that is done ! + */ +void ParaMEDMEM2VTK::MEDCouplingMultiFieldsFetcher::fetchDataIfNeeded(int fieldId) +{ + std::vector arrayIds=_array_ids_per_field[fieldId]; + int meshId=_mesh_id_per_field[fieldId]; + if(!_meshes[meshId]) + { + SALOME_MED::MEDCouplingMeshCorbaInterface_var mPtr=_mfields_ptr->getMeshWithId(meshId); + bool polyh=false;//bug VTK + _meshes[meshId]=ParaMEDMEM2VTK::BuildFromMEDCouplingMeshInstance(mPtr,polyh);//bug VTK + _is_meshes_polyhedron[meshId]=polyh;//bug VTK + mPtr->UnRegister(); + } + for(std::vector::const_iterator it=arrayIds.begin();it!=arrayIds.end();it++) + { + if(!_arrays[*it]) + { + SALOME_MED::DataArrayDoubleCorbaInterface_var daPtr=_mfields_ptr->getArray(*it); + _arrays[*it]=ParaMEDMEM2VTK::BuildFromMEDCouplingFieldDoubleArr(daPtr); + daPtr->UnRegister(); + } + } + unregisterRemoteServantIfAllFetched(); +} + +void ParaMEDMEM2VTK::MEDCouplingMultiFieldsFetcher::unregisterRemoteServantIfAllFetched() +{ + for(std::vector::iterator it=_meshes.begin();it!=_meshes.end();it++) + { + if((*it)==0) + return ; + } + for(std::vector::iterator it2=_arrays.begin();it2!=_arrays.end();it2++) + { + if((*it2)==0) + return ; + } + if(!_mfields_ptr_released) + { + _mfields_ptr_released=true; + _mfields_ptr->UnRegister(); + } +} + +void ParaMEDMEM2VTK::MEDCouplingMultiFieldsFetcher::applyBufferingPolicy() +{ + if(_effective_pol==0) + {// + for(std::vector::iterator it=_meshes.begin();it!=_meshes.end();it++) + { + if(*it) + { + (*it)->Delete(); + *it=0; + } + } + for(std::vector::iterator it2=_arrays.begin();it2!=_arrays.end();it2++) + { + if(*it2) + { + (*it2)->Delete(); + *it2=0; + } + } + } + //else nothing to do let the plugin bufferize +} + +void ParaMEDMEM2VTK::MEDCouplingMultiFieldsFetcher::appendFieldValueOnAlreadyFetchedData(vtkDataSet *ds, int fieldId) +{ + const TinyInfoOnField& info=_info_per_field[fieldId]; + vtkDoubleArray *arr=_arrays[_array_ids_per_field[fieldId].front()]; + arr->SetName(info._name.c_str()); + if(info._type==0)//ON_CELLS + { + ds->GetCellData()->AddArray(arr); + return ; + } + if(info._type==1)//ON_NODES + { + ds->GetPointData()->AddArray(arr); + return ; + } +} + +int ParaMEDMEM2VTK::MEDCouplingMultiFieldsFetcher::getPosGivenTimeLabel(double t) +{ + int nbOfFields=_time_label_per_field.size(); + for(int i=0;i::iterator it=std::find_if(_time_label_per_field.begin(),_time_label_per_field.end(), + std::bind2nd(std::greater(),t)); + if(it!=_time_label_per_field.end() && it!=_time_label_per_field.end()) + return std::distance(_time_label_per_field.begin(),it); + // + std::ostringstream oss; + oss << "Unexisting time : " << t << " Not in "; + std::copy(_time_label_per_field.begin(),_time_label_per_field.end(),std::ostream_iterator(oss," ")); + oss << " !"; + vtkOutputWindowDisplayErrorText(oss.str().c_str()); + return -1; +} diff --git a/src/Plugins/ParaMEDCorba/plugin/ParaMEDMEM2VTK/VTKMEDCouplingMultiFieldsClient.hxx b/src/Plugins/ParaMEDCorba/plugin/ParaMEDMEM2VTK/VTKMEDCouplingMultiFieldsClient.hxx new file mode 100644 index 00000000..e2206879 --- /dev/null +++ b/src/Plugins/ParaMEDCorba/plugin/ParaMEDMEM2VTK/VTKMEDCouplingMultiFieldsClient.hxx @@ -0,0 +1,88 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// + +#ifndef __VTKMEDCOUPLINGMULTIFIELDSCLIENT_HXX__ +#define __VTKMEDCOUPLINGMULTIFIELDSCLIENT_HXX__ + +#include "ParaMEDMEM2VTK_defines.hxx" +#include "ParaMEDCouplingCorbaServant.hh" + +#include +#include + +class vtkDataSet; +class vtkDoubleArray; + +namespace ParaMEDMEM2VTK +{ + /*! + * Stores all info on field without consideration of time + */ + class TinyInfoOnField + { + public: + int _type;//ON_CELLS = 0, ON_NODES = 1, ON_GAUSS_PT = 2, ON_GAUSS_NE = 3 + std::string _name; + }; + + class ParaMEDMEM2VTK_EXPORT MEDCouplingMultiFieldsFetcher + { + public: + MEDCouplingMultiFieldsFetcher(int bufferingPolicy, SALOME_MED::MEDCouplingMultiFieldsCorbaInterface_ptr mfieldsPtr); + ~MEDCouplingMultiFieldsFetcher(); + std::vector getTimeStepsForPV(); + void fetchRegardingPolicy(); + vtkDataSet *buildDataSetOnTime(double time); + private: + void appendFieldValueOnAlreadyFetchedData(vtkDataSet *ds, int fieldId); + int getPosGivenTimeLabel(double t); + private://CORBA Fetching + void retrievesMainTinyInfo(); + void fetchAll(); + void fetchMeshes(); + void fetchDataIfNeeded(int fieldId); + void unregisterRemoteServantIfAllFetched(); + void applyBufferingPolicy(); + private: + int _effective_pol; + SALOME_MED::MEDCouplingMultiFieldsCorbaInterface_var _mfields_ptr; + bool _mfields_ptr_released; + private: + std::vector _info_per_field; + std::vector _time_label_per_field; + std::vector _time_discr_per_field; + std::vector _mesh_id_per_field; + std::vector< std::vector > _array_ids_per_field; + std::vector< std::vector > _time_def_per_field; + private: + int _field_id_previous; + int _arr_pos_previous; + double _time_field_id_previous; + int _arr_id_previous; + int _mesh_id_previous; + private: + std::vector _meshes; + std::vector _is_meshes_polyhedron;//to correct bug of polyhedrons in VTK on DeepCopy. BUG id :0011860 + std::vector _arrays; + private: + static const double EPS_TIME; + }; +} + +#endif diff --git a/src/Plugins/ParaMEDCorba/plugin/ParaMEDMEM2VTK/VTKMEDCouplingUMeshClient.cxx b/src/Plugins/ParaMEDCorba/plugin/ParaMEDMEM2VTK/VTKMEDCouplingUMeshClient.cxx new file mode 100644 index 00000000..69af2c16 --- /dev/null +++ b/src/Plugins/ParaMEDCorba/plugin/ParaMEDMEM2VTK/VTKMEDCouplingUMeshClient.cxx @@ -0,0 +1,129 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// + +#include "VTKMEDCouplingUMeshClient.hxx" + +#include "vtkPoints.h" +#include "vtkCellArray.h" +#include "vtkDoubleArray.h" +#include "vtkSmartPointer.h" +#include "vtkUnstructuredGrid.h" + +#include +#include +#include +#include + +static const int ParaMEDMEM2VTKTypeTraducer[34]={1,3,21,5,9,7,22,34,23,28,-1,-1,-1,-1,10,14,13,-1,12,-1,24,-1,16,27,-1,26,-1,29,-1,-1,25,42,-1,4}; + +void ParaMEDMEM2VTK::FillMEDCouplingUMeshInstanceFrom(SALOME_MED::MEDCouplingUMeshCorbaInterface_ptr meshPtr, vtkUnstructuredGrid *ret, bool& isPolyh) +{ + meshPtr->Register(); + // + SALOME_TYPES::ListOfDouble *tinyD; + SALOME_TYPES::ListOfLong *tinyI; + SALOME_TYPES::ListOfString *tinyS; + meshPtr->getTinyInfo(tinyD,tinyI,tinyS); + // + int spaceDim=(*tinyI)[1]; + int nbOfNodes=(*tinyI)[2]; + int meshDim=(*tinyI)[5]; + int nbOfCells=(*tinyI)[6]; + int meshLength=(*tinyI)[7]; + std::string name((*tinyS)[0]); + //std::vector compoNames(spaceDim); + //for(int i=0;iInitialize(); + ret->Allocate(nbOfCells); + vtkPoints *points=vtkPoints::New(); + vtkDoubleArray *da=vtkDoubleArray::New(); + da->SetNumberOfComponents(3); + da->SetNumberOfTuples(nbOfNodes); + double *pts=da->GetPointer(0); + // + SALOME_TYPES::ListOfLong *a1Corba; + SALOME_TYPES::ListOfDouble *a2Corba; + meshPtr->getSerialisationData(a1Corba,a2Corba); + if(spaceDim==3) + { + int myLgth=a2Corba->length(); + for(int i=0;iInsertNextCell(vtkType,nbOfNodeInCurCell,tmp); + else + {//polyhedron + isPolyh=true; + std::set s(tmp,tmp+nbOfNodeInCurCell); + vtkSmartPointer faces=vtkSmartPointer::New(); + std::size_t nbOfFaces=std::count(tmp,tmp+nbOfNodeInCurCell,-1)+1; + vtkIdType *work=tmp; + for(std::size_t i=0;iInsertNextCell(nbOfNodesInFace,work); + work=work2+1; + } + s.erase(-1); + std::vector v(s.begin(),s.end()); + ret->InsertNextCell(VTK_POLYHEDRON,(vtkIdType)v.size(),&v[0],(vtkIdType)nbOfFaces,faces->GetData()->GetPointer(0)); + } + } + delete [] tmp; + // + delete a1Corba; + delete a2Corba; + // + ret->SetPoints(points); + points->Delete(); + points->SetData(da); + da->Delete(); + // + meshPtr->UnRegister(); +} diff --git a/src/Plugins/ParaMEDCorba/plugin/ParaMEDMEM2VTK/VTKMEDCouplingUMeshClient.hxx b/src/Plugins/ParaMEDCorba/plugin/ParaMEDMEM2VTK/VTKMEDCouplingUMeshClient.hxx new file mode 100644 index 00000000..5c25c1dc --- /dev/null +++ b/src/Plugins/ParaMEDCorba/plugin/ParaMEDMEM2VTK/VTKMEDCouplingUMeshClient.hxx @@ -0,0 +1,32 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// + +#ifndef __VTKMEDCOUPLINGUMESHCLIENT_HXX__ +#define __VTKMEDCOUPLINGUMESHCLIENT_HXX__ + +#include "ParaMEDCouplingCorbaServant.hh" + +class vtkUnstructuredGrid; + +namespace ParaMEDMEM2VTK +{ + void FillMEDCouplingUMeshInstanceFrom(SALOME_MED::MEDCouplingUMeshCorbaInterface_ptr meshPtr, vtkUnstructuredGrid *ret, bool& isPolyh);//isPolyh bug VTK +} + +#endif diff --git a/src/Plugins/ParaMEDCorba/plugin/ParaMEDMEM2VTK/VTKParaMEDFieldClient.cxx b/src/Plugins/ParaMEDCorba/plugin/ParaMEDMEM2VTK/VTKParaMEDFieldClient.cxx new file mode 100644 index 00000000..c66ed3ac --- /dev/null +++ b/src/Plugins/ParaMEDCorba/plugin/ParaMEDMEM2VTK/VTKParaMEDFieldClient.cxx @@ -0,0 +1,57 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// + +#include "VTKParaMEDFieldClient.hxx" +#include "VTKMEDCouplingFieldClient.hxx" + +#include "vtkDataSet.h" +#include "vtkUnstructuredGrid.h" +#include "vtkMultiBlockDataSet.h" +#include "vtkMultiBlockDataGroupFilter.h" +#include "vtkCompositeDataToUnstructuredGridFilter.h" + +std::vector ParaMEDMEM2VTK::FillMEDCouplingParaFieldDoubleInstanceFrom(SALOME_MED::ParaMEDCouplingFieldDoubleCorbaInterface_ptr fieldPtr, int begin, int end, + vtkMultiBlockDataSet *ret) +{ + std::vector ret2; + int nbOfParts=end-begin; + Engines::IORTab *allSlices=fieldPtr->tior(); + vtkMultiBlockDataGroupFilter *tmp=vtkMultiBlockDataGroupFilter::New(); + for(int i=0;i times; + vtkDataSet *part=ParaMEDMEM2VTK::BuildFullyFilledFromMEDCouplingFieldDoubleInstance(fieldCorba,times); + tmp->AddInputData(part); + part->Delete(); + } + tmp->Update(); + vtkCompositeDataToUnstructuredGridFilter *tmp2=vtkCompositeDataToUnstructuredGridFilter::New(); + tmp2->SetInputData(tmp->GetOutput()); + tmp2->Update(); + // + vtkUnstructuredGrid *ret3=tmp2->GetOutput(); + ret->SetBlock(0,ret3); + // + tmp->Delete(); + tmp2->Delete(); + delete allSlices; + return ret2; +} diff --git a/src/Plugins/ParaMEDCorba/plugin/ParaMEDMEM2VTK/VTKParaMEDFieldClient.hxx b/src/Plugins/ParaMEDCorba/plugin/ParaMEDMEM2VTK/VTKParaMEDFieldClient.hxx new file mode 100644 index 00000000..d174160c --- /dev/null +++ b/src/Plugins/ParaMEDCorba/plugin/ParaMEDMEM2VTK/VTKParaMEDFieldClient.hxx @@ -0,0 +1,36 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// + +#ifndef __VTKPARAMEDFIELDCLIENT_HXX__ +#define __VTKPARAMEDFIELDCLIENT_HXX__ + +#include "ParaMEDMEM2VTK_defines.hxx" +#include "ParaMEDCouplingCorbaServant.hh" + +#include + +class vtkMultiBlockDataSet; + +namespace ParaMEDMEM2VTK +{ + ParaMEDMEM2VTK_EXPORT std::vector FillMEDCouplingParaFieldDoubleInstanceFrom(SALOME_MED::ParaMEDCouplingFieldDoubleCorbaInterface_ptr fieldPtr, int begin, int end, + vtkMultiBlockDataSet *ret); +} + +#endif diff --git a/src/Plugins/ParaMEDCorba/plugin/filters.xml b/src/Plugins/ParaMEDCorba/plugin/filters.xml new file mode 100644 index 00000000..e2c51aeb --- /dev/null +++ b/src/Plugins/ParaMEDCorba/plugin/filters.xml @@ -0,0 +1,67 @@ + + + + + + + Source of a remote ParaMED Corba reference. + + + + This property specifies the IOR of a ParaFIELD MED in memory. + + + + + + This property specifies the buffering policy. + 0 means no buffering, that is to say Corba fetching is done + every times needed to get field at a time step. Remote Corba + object is NOT Released. + 10 means full buffering, that is to say a full Corba fetching + is performed on begin and remote Corba object is + released. But memory consumtion could be huge. + Between 0,and 10 a partial buffering is done. + + + + + + + Available timestep values. + + + + + + + Available time range. + + + + + + + + + + diff --git a/src/Plugins/ParaMEDCorba/plugin/paraview.plugin b/src/Plugins/ParaMEDCorba/plugin/paraview.plugin new file mode 100644 index 00000000..c9acb389 --- /dev/null +++ b/src/Plugins/ParaMEDCorba/plugin/paraview.plugin @@ -0,0 +1,9 @@ +NAME + ParaMEDCorbaPlugin +DESCRIPTION + This plugin provides the ParaMEDCorba filter. +REQUIRES_MODULES + VTK::CommonCore + VTK::IOCore + VTK::FiltersCore + \ No newline at end of file diff --git a/src/Plugins/ParaMEDCorba/plugin/testParaMEDCorba.cxx b/src/Plugins/ParaMEDCorba/plugin/testParaMEDCorba.cxx new file mode 100644 index 00000000..fef277aa --- /dev/null +++ b/src/Plugins/ParaMEDCorba/plugin/testParaMEDCorba.cxx @@ -0,0 +1,35 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// + +#include "vtkUnstructuredGrid.h" +#include "vtkParaMEDCorbaSource.h" + +int main( int argc, char* argv[] ) +{ + const char* fname = argc > 1 ? argv[1] : "data.iorp"; + + vtkParaMEDCorbaSource* efr = vtkParaMEDCorbaSource::New(); + //efr->SetFileName( (char *)fname ); + efr->Update(); + // + vtkDataObject* ef = efr->GetOutputDataObject(0); + // + efr->Delete(); + return 0; +} diff --git a/src/Plugins/ParaMEDCorba/testParaMEDCorba.cxx b/src/Plugins/ParaMEDCorba/testParaMEDCorba.cxx deleted file mode 100644 index fef277aa..00000000 --- a/src/Plugins/ParaMEDCorba/testParaMEDCorba.cxx +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// - -#include "vtkUnstructuredGrid.h" -#include "vtkParaMEDCorbaSource.h" - -int main( int argc, char* argv[] ) -{ - const char* fname = argc > 1 ? argv[1] : "data.iorp"; - - vtkParaMEDCorbaSource* efr = vtkParaMEDCorbaSource::New(); - //efr->SetFileName( (char *)fname ); - efr->Update(); - // - vtkDataObject* ef = efr->GetOutputDataObject(0); - // - efr->Delete(); - return 0; -} diff --git a/src/Plugins/ParaMEDCorba/vtkParaMEDCorbaSource.cxx b/src/Plugins/ParaMEDCorba/vtkParaMEDCorbaSource.cxx deleted file mode 100644 index 5aa24839..00000000 --- a/src/Plugins/ParaMEDCorba/vtkParaMEDCorbaSource.cxx +++ /dev/null @@ -1,283 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// - -#include "vtkParaMEDCorbaSource.h" - -#include "vtkPoints.h" -#include "vtkIntArray.h" -#include "vtkCellData.h" -#include "vtkCellTypes.h" -#include "vtkCharArray.h" -#include "vtkPointData.h" -#include "vtkDoubleArray.h" -#include "vtkMultiBlockDataSet.h" -#include "vtkUnstructuredGrid.h" -// -#include "vtkStreamingDemandDrivenPipeline.h" -#include "vtkGenericAttributeCollection.h" -#include "vtkInformationVector.h" -#include "vtkObjectFactory.h" -#include "vtkInformation.h" -// -#include "string" -#include "fstream" -#include "algorithm" - -#include "VTKMEDCouplingMeshClient.hxx" -#include "VTKMEDCouplingFieldClient.hxx" -#include "VTKMEDCouplingMultiFieldsClient.hxx" -#include "VTKParaMEDFieldClient.hxx" - -//Work with IOR. -#include "ParaMEDCouplingCorbaServant.hh" -// - -vtkStandardNewMacro(vtkParaMEDCorbaSource); -//vtkCxxRevisionMacro(vtkParaMEDCorbaSource,"$Revision$"); - -void *vtkParaMEDCorbaSource::Orb=0; - -vtkParaMEDCorbaSource::vtkParaMEDCorbaSource():mfieldsFetcher(0) -{ - this->MyDataSet=0; - if(!Orb) - { - CORBA::ORB_var *OrbC=new CORBA::ORB_var; - int argc=0; - *OrbC=CORBA::ORB_init(argc,0); - this->Orb=OrbC; - } - this->SetNumberOfInputPorts(0); - this->SetNumberOfOutputPorts(1); -} - -vtkParaMEDCorbaSource::~vtkParaMEDCorbaSource() -{ - delete mfieldsFetcher; -} - -const char *vtkParaMEDCorbaSource::GetIORCorba() -{ - return &IOR[0]; -} - -void vtkParaMEDCorbaSource::SetIORCorba(char *ior) -{ - if(!ior) - return; - if(ior[0]=='\0') - return; - std::size_t length=strlen(ior); - IOR.resize(length+1); - std::copy(ior,ior+length+1,&IOR[0]); - this->Modified(); -} - -void vtkParaMEDCorbaSource::SetBufferingPolicy(int pol) -{ - BufferingPolicy=pol; -} - -int vtkParaMEDCorbaSource::GetBufferingPolicy() -{ - return BufferingPolicy; -} - -//int vtkParaMEDCorbaSource::RequestUpdateExtent( vtkInformation* request, vtkInformationVector** inInfo, vtkInformationVector* outInfo ) -//{ -//return this->Superclass::RequestUpdateExtent(request,inInfo,outInfo); - -/*vtkParaMEDCorbaDataSet* output = vtkParaMEDCorbaDataSet::SafeDownCast( info->Get( vtkDataObject::DATA_OBJECT() ) ); - if ( ! output ) - { - output = vtkParaMEDCorbaDataSet::New(); - output->SetPipelineInformation( info ); - output->Delete(); - this->GetOutputPortInformation( 0 )->Set( vtkDataObject::DATA_EXTENT_TYPE(), output->GetExtentType() ); - }*/ - -// return 1; -//} - -int vtkParaMEDCorbaSource::ProcessRequest(vtkInformation* request, - vtkInformationVector** inputVector, - vtkInformationVector* outputVector) -{ - // generate the data - if(request->Has(vtkDemandDrivenPipeline::REQUEST_DATA())) - { - return this->RequestData(request, inputVector, outputVector); - } - if(request->Has(vtkDemandDrivenPipeline::REQUEST_INFORMATION())) - { - return this->RequestInformation(request, inputVector, outputVector); - } - return this->Superclass::ProcessRequest(request, inputVector, outputVector); -} - -int vtkParaMEDCorbaSource::FillOutputPortInformation(int vtkNotUsed(port), vtkInformation* info) -{ - info->Set(vtkDataObject::DATA_TYPE_NAME(), "vtkMultiBlockDataSet"); - return 1; -} - -int vtkParaMEDCorbaSource::RequestInformation(vtkInformation* request, vtkInformationVector** inInfo, vtkInformationVector* outInfo) -{ - vtkInformation* myInfo=outInfo->GetInformationObject(0); - //myInfo->Set(vtkDataObject::DATA_TYPE_NAME(),"vtkUnstructuredGrid"); - if(!IOR.empty()) - { - //myInfo->Remove(vtkDataObject::DATA_TYPE_NAME()); - //myInfo->Remove(PORT_REQUIREMENTS_FILLED()); - //myInfo->Set(vtkDataObject::DATA_TYPE_NAME(),"vtkUnstructuredGrid"); - //myInfo->Set(PORT_REQUIREMENTS_FILLED(),1); - //vtkUnstructuredGrid *tony=vtkUnstructuredGrid::New(); - //tony->SetInformation(myInfo); - //myInfo->Set(vtkDataObject::DATA_OBJECT(),tony); - // - try { - CORBA::ORB_var *OrbC=(CORBA::ORB_var *)this->Orb; - CORBA::Object_var obj=(*OrbC)->string_to_object(&IOR[0]); - // - Engines::MPIObject_ptr objPara=Engines::MPIObject::_narrow(obj); - if(CORBA::is_nil(objPara)) - {//sequential - this->TotalNumberOfPieces=1; - SALOME_MED::MEDCouplingMultiFieldsCorbaInterface_var multiPtr=SALOME_MED::MEDCouplingMultiFieldsCorbaInterface::_narrow(obj); - if(!CORBA::is_nil(multiPtr)) - {//Request for multiFields - delete mfieldsFetcher; - mfieldsFetcher=new ParaMEDMEM2VTK::MEDCouplingMultiFieldsFetcher(BufferingPolicy,multiPtr); - std::vector tsteps=mfieldsFetcher->getTimeStepsForPV(); - double timeRange[2]; - timeRange[0]=tsteps.front(); - timeRange[1]=tsteps.back(); - myInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_STEPS(),&tsteps[0],(vtkIdType)tsteps.size()); - myInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_RANGE(),timeRange,2); - } - } - else - { - Engines::IORTab *iorTab=objPara->tior(); - this->TotalNumberOfPieces=iorTab->length(); - delete iorTab; - CORBA::release(objPara); - } - myInfo->Set(CAN_HANDLE_PIECE_REQUEST(), 1); - } - catch(CORBA::Exception&) { - vtkErrorMacro("On fetching object error occurs"); - } - } - return 1; -} - -int vtkParaMEDCorbaSource::RequestData(vtkInformation* request, vtkInformationVector** inInfo, vtkInformationVector* outputVector) -{ - vtkInformation *outInfo=outputVector->GetInformationObject(0); - // - this->UpdatePiece = vtkStreamingDemandDrivenPipeline::GetUpdatePiece(outInfo); - this->NumberOfPieces = vtkStreamingDemandDrivenPipeline::GetUpdateNumberOfPieces(outInfo); - this->GhostLevel = vtkStreamingDemandDrivenPipeline::GetUpdateGhostLevel(outInfo); - this->StartPiece=((this->UpdatePiece*this->TotalNumberOfPieces)/this->NumberOfPieces); - this->EndPiece=(((this->UpdatePiece+1)*this->TotalNumberOfPieces)/this->NumberOfPieces); - vtkMultiBlockDataSet *ret0=vtkMultiBlockDataSet::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); - double reqTS = 0; - if(outInfo->Has(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP())) - reqTS = outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP()); - try { - //Client request on ORB. - CORBA::ORB_var *OrbC=(CORBA::ORB_var *)this->Orb; - CORBA::Object_var obj=(*OrbC)->string_to_object(&IOR[0]); - // - Engines::MPIObject_var objPara=Engines::MPIObject::_narrow(obj); - if(CORBA::is_nil(objPara)) - {//sequential - SALOME_MED::MEDCouplingMeshCorbaInterface_var meshPtr=SALOME_MED::MEDCouplingMeshCorbaInterface::_narrow(obj); - if(!CORBA::is_nil(meshPtr)) - { - bool dummy;//bug VTK - vtkDataSet *ret=ParaMEDMEM2VTK::BuildFromMEDCouplingMeshInstance(meshPtr,dummy);//bug VTK - if(!ret) - return 0; - ret0->SetBlock(0,ret); - ret->Delete(); - return 1; - } - SALOME_MED::MEDCouplingFieldDoubleCorbaInterface_var fieldPtr=SALOME_MED::MEDCouplingFieldDoubleCorbaInterface::_narrow(obj); - if(!CORBA::is_nil(fieldPtr)) - { - std::vector ret2; - vtkDataSet *ret=ParaMEDMEM2VTK::BuildFullyFilledFromMEDCouplingFieldDoubleInstance(fieldPtr,ret2); - if(!ret) - { - vtkErrorMacro("On single field CORBA fetching an error occurs !"); - return 0; - } - ret0->SetBlock(0,ret); - ret->Delete(); - // - double timeRange[2]; - timeRange[0]=ret2[0]; - timeRange[1]=ret2[0]; - outInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_STEPS(),&ret2[0],1); - outInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_RANGE(),timeRange,2); - ret0->GetInformation()->Set(vtkDataObject::DATA_TIME_STEP(),ret2[0]); - return 1; - } - SALOME_MED::MEDCouplingMultiFieldsCorbaInterface_var multiPtr=SALOME_MED::MEDCouplingMultiFieldsCorbaInterface::_narrow(obj); - if(!CORBA::is_nil(multiPtr)) - { - vtkDataSet *ret=mfieldsFetcher->buildDataSetOnTime(reqTS); - if(!ret) - { - vtkErrorMacro("On multi fields CORBA fetching an error occurs !"); - return 0; - } - ret0->SetBlock(0,ret); - ret->Delete(); - ret0->GetInformation()->Set(vtkDataObject::DATA_TIME_STEP(),reqTS); - return 1; - } - vtkErrorMacro("Unrecognized sequential CORBA reference !"); - return 0; - } - else - { - SALOME_MED::ParaMEDCouplingFieldDoubleCorbaInterface_var paraFieldCorba=SALOME_MED::ParaMEDCouplingFieldDoubleCorbaInterface::_narrow(obj); - if(!CORBA::is_nil(paraFieldCorba)) - { - ParaMEDMEM2VTK::FillMEDCouplingParaFieldDoubleInstanceFrom(paraFieldCorba,this->StartPiece,this->EndPiece,ret0); - return 1; - } - vtkErrorMacro("Unrecognized parallel CORBA reference !"); - return 0; - } - } - catch(CORBA::Exception&) { - vtkErrorMacro("On fetching object error occurs"); - } -} - -void vtkParaMEDCorbaSource::PrintSelf(ostream& os, vtkIndent indent) -{ - this->Superclass::PrintSelf( os, indent ); - os << "Data: " << this->MyDataSet << "\n"; -} - diff --git a/src/Plugins/ParaMEDCorba/vtkParaMEDCorbaSource.h b/src/Plugins/ParaMEDCorba/vtkParaMEDCorbaSource.h deleted file mode 100644 index 4fce88ba..00000000 --- a/src/Plugins/ParaMEDCorba/vtkParaMEDCorbaSource.h +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// - - -#ifndef __vtkParaMEDCorbaSource_h -#define __vtkParaMEDCorbaSource_h - -#include "ParaMEDMEM2VTK_defines.hxx" -#include "vtkUnstructuredGridAlgorithm.h" -#include - -class vtkDoubleArray; -class vtkUnstructuredGrid; - -namespace ParaMEDMEM2VTK -{ - class MEDCouplingMultiFieldsFetcher; -} - -class vtkParaMEDCorbaSource : public vtkAlgorithm // -{ -public: - vtkTypeMacro(vtkParaMEDCorbaSource, vtkAlgorithm) - ParaMEDMEM2VTK_EXPORT static vtkParaMEDCorbaSource* New(); - virtual void PrintSelf( ostream& os, vtkIndent indent ); - const char *GetIORCorba(); - void SetIORCorba(char *ior); - void SetBufferingPolicy(int pol); - int GetBufferingPolicy(); -protected: - vtkParaMEDCorbaSource(); - virtual ~vtkParaMEDCorbaSource(); - int FillOutputPortInformation(int vtkNotUsed(port), vtkInformation* info); - int ProcessRequest(vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector); - //virtual int RequestUpdateExtent( vtkInformation* request, vtkInformationVector** inInfo, vtkInformationVector* outInfo ); - virtual int RequestInformation( vtkInformation* request, vtkInformationVector** inInfo, vtkInformationVector* outInfo ); - virtual int RequestData( vtkInformation* request, vtkInformationVector** inInfo, vtkInformationVector* outInfo ); - //BTX - int TotalNumberOfPieces; - int NumberOfPieces; - int UpdatePiece; - int GhostLevel; - int StartPiece; - int EndPiece; - int BufferingPolicy; - vtkUnstructuredGrid *MyDataSet; - std::vector IOR; - ParaMEDMEM2VTK::MEDCouplingMultiFieldsFetcher *mfieldsFetcher; - //not clean but to avoid to include CORBA.h in this *.h - static void *Orb; - //ETX -private: - /*void traduceMedMeshToUnstructuredDataset(vtkUnstructuredGrid *ret, int nbOfCells, int nbOfNodes, - int nbOfTypes, const int *types, const int *nbOfEltsPerTypes, const int *nodalConnectivity, - const double *coords, int spaceDim); - vtkDoubleArray *buildDataArrayFromMedCoords(const double *coords, int nbOfNodes, int spaceDim); - void reorganizeCellConnectivity(int vtkType, int nbOfNodes, const int *medConn, int *vtkConn); - int transformMedGeomEltType2VtkType(int typeMed, int *nbOfNodesPerCell);*/ - // - vtkParaMEDCorbaSource( const vtkParaMEDCorbaSource& ); // Not implemented. - void operator = ( const vtkParaMEDCorbaSource& ); // Not implemented. -}; - -#endif // __vtkParaMEDCorbaSource_h - diff --git a/src/Plugins/ParaSMESHCorba/CMakeLists.txt b/src/Plugins/ParaSMESHCorba/CMakeLists.txt index f519de95..f759f825 100644 --- a/src/Plugins/ParaSMESHCorba/CMakeLists.txt +++ b/src/Plugins/ParaSMESHCorba/CMakeLists.txt @@ -16,35 +16,68 @@ # # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com # +cmake_minimum_required(VERSION 3.8) +project(ParaSMESHCorba) - PROJECT(ParaSMESHCorba) - CMAKE_MINIMUM_REQUIRED( VERSION 2.8.7 ) +include(GNUInstallDirs) +set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_BINDIR}") +set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_LIBDIR}") +set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_LIBDIR}") - FIND_PACKAGE(ParaView REQUIRED) - INCLUDE(${PARAVIEW_USE_FILE}) +find_package(SalomeSMESH) - SET(PARA_SMESH_CORBA_SRC - ${ParaSMESHCorba_SOURCE_DIR}/vtkParaSMESHCorbaSource.cxx - ) +include_directories( ${CMAKE_CURRENT_SOURCE_DIR}/plugin/ParaSMESHCorbaModule ) - ADD_PARAVIEW_PLUGIN( ParaSMESHCorbaPlugin "1.0" - SERVER_MANAGER_XML ParaSMESHCorbaServerManager.xml - SERVER_MANAGER_SOURCES ${PARA_SMESH_CORBA_SRC} ) +set("_paraview_plugin_default_${CMAKE_PROJECT_NAME}" ON) +paraview_plugin_scan( + ENABLE_BY_DEFAULT YES + PLUGIN_FILES "${CMAKE_CURRENT_SOURCE_DIR}/plugin/paraview.plugin" + PROVIDES_PLUGINS plugins + REQUIRES_MODULES required_modules) - INCLUDE_DIRECTORIES( - ${OMNIORB_INCLUDE_DIR} - ${SMESH_ROOT_DIR}/include/salome - ${GEOM_ROOT_DIR}/include/salome - ${KERNEL_ROOT_DIR}/include/salome ) +foreach(module IN LISTS required_modules) + if(NOT TARGET "${module}") + message("Missing required module: ${module}") + return() + endif() +endforeach() + +set(BUILD_SHARED_LIBS ON) +paraview_plugin_build( + RUNTIME_DESTINATION "${CMAKE_INSTALL_BINDIR}" + LIBRARY_DESTINATION "${CMAKE_INSTALL_LIBDIR}" + LIBRARY_SUBDIRECTORY "${PARAVIEW_PLUGIN_SUBDIR}" + PLUGINS ${plugins} + AUTOLOAD ${plugins}) + +# PROJECT(ParaSMESHCorba) +# CMAKE_MINIMUM_REQUIRED( VERSION 2.8.7 ) +# +# FIND_PACKAGE(ParaView REQUIRED) +# INCLUDE(${PARAVIEW_USE_FILE}) +# +# SET(PARA_SMESH_CORBA_SRC +# ${ParaSMESHCorba_SOURCE_DIR}/vtkParaSMESHCorbaSource.cxx +# ) + +# ADD_PARAVIEW_PLUGIN( ParaSMESHCorbaPlugin "1.0" +# SERVER_MANAGER_XML ParaSMESHCorbaServerManager.xml +# SERVER_MANAGER_SOURCES ${PARA_SMESH_CORBA_SRC} ) + +# INCLUDE_DIRECTORIES( +# ${OMNIORB_INCLUDE_DIR} +# ${SMESH_ROOT_DIR}/include/salome +# ${GEOM_ROOT_DIR}/include/salome +# ${KERNEL_ROOT_DIR}/include/salome ) - ADD_DEFINITIONS(${OMNIORB_DEFINITIONS}) - TARGET_LINK_LIBRARIES(ParaSMESHCorbaPlugin - ${OMNIORB_LIBRARIES} - ${KERNEL_SalomeIDLKernel} - ${SMESH_SalomeIDLSMESH} - ${SMESH_SMESHClient} - ${GEOM_SalomeIDLGEOM} - ) - - INSTALL(TARGETS ParaSMESHCorbaPlugin DESTINATION lib/paraview) - INSTALL(FILES ParaSMESHCorbaServerManager.xml DESTINATION share) +# ADD_DEFINITIONS(${OMNIORB_DEFINITIONS}) +# TARGET_LINK_LIBRARIES(ParaSMESHCorbaPlugin +# ${OMNIORB_LIBRARIES} +# ${KERNEL_SalomeIDLKernel} +# ${SMESH_SalomeIDLSMESH} +# ${SMESH_SMESHClient} +# ${GEOM_SalomeIDLGEOM} +# ) + +# INSTALL(TARGETS ParaSMESHCorbaPlugin DESTINATION lib/paraview) +# INSTALL(FILES ParaSMESHCorbaServerManager.xml DESTINATION share) diff --git a/src/Plugins/ParaSMESHCorba/ParaSMESHCorbaServerManager.xml b/src/Plugins/ParaSMESHCorba/ParaSMESHCorbaServerManager.xml deleted file mode 100644 index f547c556..00000000 --- a/src/Plugins/ParaSMESHCorba/ParaSMESHCorbaServerManager.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - Source of a remote Mesh Corba reference. - - - - This property specifies the IOR of a Mesh object in memory. - - - - - - - - - diff --git a/src/Plugins/ParaSMESHCorba/plugin/CMakeLists.txt b/src/Plugins/ParaSMESHCorba/plugin/CMakeLists.txt new file mode 100644 index 00000000..806bff19 --- /dev/null +++ b/src/Plugins/ParaSMESHCorba/plugin/CMakeLists.txt @@ -0,0 +1,31 @@ +# Copyright (C) 2010-2019 CEA/DEN, EDF R&D +# +# This library 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. +# +# 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 +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +# + +paraview_add_plugin(ParaSMESHCorbaPlugin + VERSION "1.0" + MODULES ParaSMESHCorbaModule + MODULE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/ParaSMESHCorbaModule/vtk.module" + SERVER_MANAGER_XML filters.xml +) + +install(TARGETS ParaSMESHCorbaPlugin + RUNTIME DESTINATION lib/paraview + LIBRARY DESTINATION lib/paraview + ARCHIVE DESTINATION lib/paraview + ) diff --git a/src/Plugins/ParaSMESHCorba/plugin/ParaSMESHCorbaModule/CMakeLists.txt b/src/Plugins/ParaSMESHCorba/plugin/ParaSMESHCorbaModule/CMakeLists.txt new file mode 100644 index 00000000..7372964b --- /dev/null +++ b/src/Plugins/ParaSMESHCorba/plugin/ParaSMESHCorbaModule/CMakeLists.txt @@ -0,0 +1,42 @@ +# Copyright (C) 2010-2019 CEA/DEN, EDF R&D +# +# This library 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. +# +# 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 +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +# + +include_directories( + ${GEOM_ROOT_DIR}/include/salome + ${SMESH_ROOT_DIR}/include/salome + ) + +add_definitions(${OMNIORB_DEFINITIONS}) + +set(classes + vtkParaSMESHCorbaSource +) + +vtk_module_add_module(ParaSMESHCorbaModule + FORCE_STATIC + CLASSES ${classes} +) + +target_link_libraries(ParaSMESHCorbaModule PRIVATE + ${OMNIORB_LIBRARIES} + ${KERNEL_SalomeIDLKernel} + ${SMESH_SalomeIDLSMESH} + ${SMESH_SMESHClient} + ${GEOM_SalomeIDLGEOM} +) \ No newline at end of file diff --git a/src/Plugins/ParaSMESHCorba/plugin/ParaSMESHCorbaModule/vtk.module b/src/Plugins/ParaSMESHCorba/plugin/ParaSMESHCorbaModule/vtk.module new file mode 100644 index 00000000..680cde0e --- /dev/null +++ b/src/Plugins/ParaSMESHCorba/plugin/ParaSMESHCorbaModule/vtk.module @@ -0,0 +1,15 @@ +NAME + ParaSMESHCorbaModule +DEPENDS + VTK::CommonCore + VTK::CommonDataModel + VTK::CommonExecutionModel + VTK::FiltersCore + VTK::FiltersModeling + VTK::IOLegacy +PRIVATE_DEPENDS + VTK::CommonMisc + VTK::CommonSystem + VTK::FiltersGeneral + VTK::FiltersGeometry + \ No newline at end of file diff --git a/src/Plugins/ParaSMESHCorba/plugin/ParaSMESHCorbaModule/vtkParaSMESHCorbaSource.cxx b/src/Plugins/ParaSMESHCorba/plugin/ParaSMESHCorbaModule/vtkParaSMESHCorbaSource.cxx new file mode 100644 index 00000000..d03c5917 --- /dev/null +++ b/src/Plugins/ParaSMESHCorba/plugin/ParaSMESHCorbaModule/vtkParaSMESHCorbaSource.cxx @@ -0,0 +1,134 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// + +#include "vtkParaSMESHCorbaSource.h" + +#include + +#include "vtkStreamingDemandDrivenPipeline.h" +#include "vtkInformationVector.h" +#include "vtkInformation.h" +#include "vtkMultiBlockDataSet.h" +#include "vtkObjectFactory.h" +#include "vtkUnstructuredGridReader.h" + +#include "SMDS_UnstructuredGrid.hxx" +#include "SMESH_Mesh.hh" + +#include + +vtkStandardNewMacro(vtkParaSMESHCorbaSource); + +void *vtkParaSMESHCorbaSource::Orb=0; + +//---------------------------------------------- +vtkParaSMESHCorbaSource::vtkParaSMESHCorbaSource() { + if(!Orb) { + CORBA::ORB_var *OrbC=new CORBA::ORB_var; + int argc=0; + *OrbC=CORBA::ORB_init(argc,0); + this->Orb=OrbC; + } + this->SetNumberOfInputPorts(0); + this->SetNumberOfOutputPorts(1); +} + +//---------------------------------------------- +vtkParaSMESHCorbaSource::~vtkParaSMESHCorbaSource() { + +} + +//---------------------------------------------- +const char* vtkParaSMESHCorbaSource::GetIORCorba() +{ + return &IOR[0]; +} + +//---------------------------------------------- +void vtkParaSMESHCorbaSource::SetIORCorba(char *ior) { + if(!ior) + return; + if(ior[0]=='\0') + return; + int length=strlen(ior); + IOR.resize(length+1); + std::copy(ior,ior+length+1,&IOR[0]); + this->Modified(); +} + +//---------------------------------------------- +int vtkParaSMESHCorbaSource::ProcessRequest(vtkInformation* request, + vtkInformationVector** inputVector, + vtkInformationVector* outputVector) { + // generate the data + if(request->Has(vtkDemandDrivenPipeline::REQUEST_DATA())) { + return this->RequestData(request, inputVector, outputVector); + } + return this->Superclass::ProcessRequest(request, inputVector, outputVector); +} + +//---------------------------------------------- +int vtkParaSMESHCorbaSource::FillOutputPortInformation(int vtkNotUsed(port), vtkInformation* info) { + info->Set(vtkDataObject::DATA_TYPE_NAME(), "vtkMultiBlockDataSet"); + return 1; +} + +//---------------------------------------------- +int vtkParaSMESHCorbaSource::RequestData(vtkInformation* request, vtkInformationVector** inInfo, vtkInformationVector* outputVector) { + vtkInformation *outInfo=outputVector->GetInformationObject(0); + vtkMultiBlockDataSet *ret0=vtkMultiBlockDataSet::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); + double reqTS = 0; + if(outInfo->Has(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP())) + reqTS = outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP()); + + try { + CORBA::ORB_var *OrbC=(CORBA::ORB_var *)this->Orb; + CORBA::Object_var obj=(*OrbC)->string_to_object(&IOR[0]); + SMESH::SMESH_Mesh_var meshObj = SMESH::SMESH_Mesh::_narrow(obj); + if(!CORBA::is_nil(meshObj)) { + SALOMEDS::TMPFile* SeqFile = meshObj->GetVtkUgStream(); + int aSize = SeqFile->length(); + char* buf = (char*)SeqFile->NP_data(); + vtkUnstructuredGridReader* aReader = vtkUnstructuredGridReader::New(); + aReader->ReadFromInputStringOn(); + aReader->SetBinaryInputString(buf, aSize); + aReader->Update(); + vtkUnstructuredGrid* ret = vtkUnstructuredGrid::New(); + ret->ShallowCopy(aReader->GetOutput()); + aReader->Delete(); + if(!ret) { + vtkErrorMacro("On smesh object CORBA fetching an error occurs !"); + return 0; + } + + ret0->SetBlock(0, ret); + ret->Delete(); + return 1; + } + + vtkErrorMacro("Unrecognized CORBA reference!"); + } + catch(CORBA::Exception&) { + vtkErrorMacro("On fetching object error occurs"); + } + return 0; +} + + + diff --git a/src/Plugins/ParaSMESHCorba/plugin/ParaSMESHCorbaModule/vtkParaSMESHCorbaSource.h b/src/Plugins/ParaSMESHCorba/plugin/ParaSMESHCorbaModule/vtkParaSMESHCorbaSource.h new file mode 100644 index 00000000..2dc1fa18 --- /dev/null +++ b/src/Plugins/ParaSMESHCorba/plugin/ParaSMESHCorbaModule/vtkParaSMESHCorbaSource.h @@ -0,0 +1,50 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// + + +#ifndef __vtkParaSMESHCorbaSource_h +#define __vtkParaSMESHCorbaSource_h + +#include "vtkUnstructuredGridAlgorithm.h" +#include + +class vtkParaSMESHCorbaSource: public vtkAlgorithm { + public: + static vtkParaSMESHCorbaSource* New(); + vtkTypeMacro(vtkParaSMESHCorbaSource, vtkAlgorithm); + + + const char *GetIORCorba(); + void SetIORCorba(char *ior); + +protected: + vtkParaSMESHCorbaSource(); + virtual ~vtkParaSMESHCorbaSource(); + int FillOutputPortInformation(int vtkNotUsed(port), vtkInformation* info); + int ProcessRequest(vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector); + virtual int RequestData( vtkInformation* request, vtkInformationVector** inInfo, vtkInformationVector* outInfo ); + std::vector IOR; + static void *Orb; + private: + vtkParaSMESHCorbaSource( const vtkParaSMESHCorbaSource& ); // Not implemented. + void operator = ( const vtkParaSMESHCorbaSource& ); // Not implemented. +}; + +#endif // __vtkParaSMESHCorbaSource_h + diff --git a/src/Plugins/ParaSMESHCorba/plugin/filters.xml b/src/Plugins/ParaSMESHCorba/plugin/filters.xml new file mode 100644 index 00000000..3c195de5 --- /dev/null +++ b/src/Plugins/ParaSMESHCorba/plugin/filters.xml @@ -0,0 +1,29 @@ + + + + + + + Source of a remote Mesh Corba reference. + + + + This property specifies the IOR of a Mesh object in memory. + + + + + + + + + diff --git a/src/Plugins/ParaSMESHCorba/plugin/paraview.plugin b/src/Plugins/ParaSMESHCorba/plugin/paraview.plugin new file mode 100644 index 00000000..f5627ec3 --- /dev/null +++ b/src/Plugins/ParaSMESHCorba/plugin/paraview.plugin @@ -0,0 +1,8 @@ +NAME + ParaSMESHCorbaPlugin +DESCRIPTION + This plugin provides the ParaSMESHCorba filter. +REQUIRES_MODULES + VTK::CommonCore + VTK::IOCore + VTK::FiltersCore diff --git a/src/Plugins/ParaSMESHCorba/vtkParaSMESHCorbaSource.cxx b/src/Plugins/ParaSMESHCorba/vtkParaSMESHCorbaSource.cxx deleted file mode 100644 index d03c5917..00000000 --- a/src/Plugins/ParaSMESHCorba/vtkParaSMESHCorbaSource.cxx +++ /dev/null @@ -1,134 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// - -#include "vtkParaSMESHCorbaSource.h" - -#include - -#include "vtkStreamingDemandDrivenPipeline.h" -#include "vtkInformationVector.h" -#include "vtkInformation.h" -#include "vtkMultiBlockDataSet.h" -#include "vtkObjectFactory.h" -#include "vtkUnstructuredGridReader.h" - -#include "SMDS_UnstructuredGrid.hxx" -#include "SMESH_Mesh.hh" - -#include - -vtkStandardNewMacro(vtkParaSMESHCorbaSource); - -void *vtkParaSMESHCorbaSource::Orb=0; - -//---------------------------------------------- -vtkParaSMESHCorbaSource::vtkParaSMESHCorbaSource() { - if(!Orb) { - CORBA::ORB_var *OrbC=new CORBA::ORB_var; - int argc=0; - *OrbC=CORBA::ORB_init(argc,0); - this->Orb=OrbC; - } - this->SetNumberOfInputPorts(0); - this->SetNumberOfOutputPorts(1); -} - -//---------------------------------------------- -vtkParaSMESHCorbaSource::~vtkParaSMESHCorbaSource() { - -} - -//---------------------------------------------- -const char* vtkParaSMESHCorbaSource::GetIORCorba() -{ - return &IOR[0]; -} - -//---------------------------------------------- -void vtkParaSMESHCorbaSource::SetIORCorba(char *ior) { - if(!ior) - return; - if(ior[0]=='\0') - return; - int length=strlen(ior); - IOR.resize(length+1); - std::copy(ior,ior+length+1,&IOR[0]); - this->Modified(); -} - -//---------------------------------------------- -int vtkParaSMESHCorbaSource::ProcessRequest(vtkInformation* request, - vtkInformationVector** inputVector, - vtkInformationVector* outputVector) { - // generate the data - if(request->Has(vtkDemandDrivenPipeline::REQUEST_DATA())) { - return this->RequestData(request, inputVector, outputVector); - } - return this->Superclass::ProcessRequest(request, inputVector, outputVector); -} - -//---------------------------------------------- -int vtkParaSMESHCorbaSource::FillOutputPortInformation(int vtkNotUsed(port), vtkInformation* info) { - info->Set(vtkDataObject::DATA_TYPE_NAME(), "vtkMultiBlockDataSet"); - return 1; -} - -//---------------------------------------------- -int vtkParaSMESHCorbaSource::RequestData(vtkInformation* request, vtkInformationVector** inInfo, vtkInformationVector* outputVector) { - vtkInformation *outInfo=outputVector->GetInformationObject(0); - vtkMultiBlockDataSet *ret0=vtkMultiBlockDataSet::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); - double reqTS = 0; - if(outInfo->Has(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP())) - reqTS = outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP()); - - try { - CORBA::ORB_var *OrbC=(CORBA::ORB_var *)this->Orb; - CORBA::Object_var obj=(*OrbC)->string_to_object(&IOR[0]); - SMESH::SMESH_Mesh_var meshObj = SMESH::SMESH_Mesh::_narrow(obj); - if(!CORBA::is_nil(meshObj)) { - SALOMEDS::TMPFile* SeqFile = meshObj->GetVtkUgStream(); - int aSize = SeqFile->length(); - char* buf = (char*)SeqFile->NP_data(); - vtkUnstructuredGridReader* aReader = vtkUnstructuredGridReader::New(); - aReader->ReadFromInputStringOn(); - aReader->SetBinaryInputString(buf, aSize); - aReader->Update(); - vtkUnstructuredGrid* ret = vtkUnstructuredGrid::New(); - ret->ShallowCopy(aReader->GetOutput()); - aReader->Delete(); - if(!ret) { - vtkErrorMacro("On smesh object CORBA fetching an error occurs !"); - return 0; - } - - ret0->SetBlock(0, ret); - ret->Delete(); - return 1; - } - - vtkErrorMacro("Unrecognized CORBA reference!"); - } - catch(CORBA::Exception&) { - vtkErrorMacro("On fetching object error occurs"); - } - return 0; -} - - - diff --git a/src/Plugins/ParaSMESHCorba/vtkParaSMESHCorbaSource.h b/src/Plugins/ParaSMESHCorba/vtkParaSMESHCorbaSource.h deleted file mode 100644 index 2dc1fa18..00000000 --- a/src/Plugins/ParaSMESHCorba/vtkParaSMESHCorbaSource.h +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// - - -#ifndef __vtkParaSMESHCorbaSource_h -#define __vtkParaSMESHCorbaSource_h - -#include "vtkUnstructuredGridAlgorithm.h" -#include - -class vtkParaSMESHCorbaSource: public vtkAlgorithm { - public: - static vtkParaSMESHCorbaSource* New(); - vtkTypeMacro(vtkParaSMESHCorbaSource, vtkAlgorithm); - - - const char *GetIORCorba(); - void SetIORCorba(char *ior); - -protected: - vtkParaSMESHCorbaSource(); - virtual ~vtkParaSMESHCorbaSource(); - int FillOutputPortInformation(int vtkNotUsed(port), vtkInformation* info); - int ProcessRequest(vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector); - virtual int RequestData( vtkInformation* request, vtkInformationVector** inInfo, vtkInformationVector* outInfo ); - std::vector IOR; - static void *Orb; - private: - vtkParaSMESHCorbaSource( const vtkParaSMESHCorbaSource& ); // Not implemented. - void operator = ( const vtkParaSMESHCorbaSource& ); // Not implemented. -}; - -#endif // __vtkParaSMESHCorbaSource_h - diff --git a/src/Plugins/ScaleVector/CMakeLists.txt b/src/Plugins/ScaleVector/CMakeLists.txt index dbf5678f..5b8091ba 100644 --- a/src/Plugins/ScaleVector/CMakeLists.txt +++ b/src/Plugins/ScaleVector/CMakeLists.txt @@ -1,41 +1,30 @@ -# Copyright (C) 2010-2019 CEA/DEN, EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# +cmake_minimum_required(VERSION 3.8) +project(ScaleVector) +find_package(ParaView REQUIRED) -PROJECT(ScaleVector) -cmake_minimum_required(VERSION 2.6) +include(GNUInstallDirs) +set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_BINDIR}") +set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_LIBDIR}") +set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_LIBDIR}") -cmake_policy(SET CMP0003 NEW) +set("_paraview_plugin_default_${CMAKE_PROJECT_NAME}" ON) +paraview_plugin_scan( + ENABLE_BY_DEFAULT YES + PLUGIN_FILES "${CMAKE_CURRENT_SOURCE_DIR}/plugin/paraview.plugin" + PROVIDES_PLUGINS plugins + REQUIRES_MODULES required_modules) -FIND_PACKAGE(ParaView REQUIRED) -INCLUDE(${PARAVIEW_USE_FILE}) - -SET(SRCS - vtkScaleVectorFilter.cxx - ) - -ADD_PARAVIEW_PLUGIN(ScaleVector "1.0" - SERVER_MANAGER_XML ScaleVector.xml - SERVER_MANAGER_SOURCES ${SRCS}) - -install(TARGETS ${PROJECT_NAME} - RUNTIME DESTINATION lib/paraview - LIBRARY DESTINATION lib/paraview - ARCHIVE DESTINATION lib/paraview - ) +foreach(module IN LISTS required_modules) + if(NOT TARGET "${module}") + message("Missing required module: ${module}") + return() + endif() +endforeach() +set(BUILD_SHARED_LIBS ON) +paraview_plugin_build( + RUNTIME_DESTINATION "${CMAKE_INSTALL_BINDIR}" + LIBRARY_DESTINATION "${CMAKE_INSTALL_LIBDIR}" + LIBRARY_SUBDIRECTORY "${PARAVIEW_PLUGIN_SUBDIR}" + PLUGINS ${plugins} + AUTOLOAD ${plugins}) diff --git a/src/Plugins/ScaleVector/ScaleVector.xml b/src/Plugins/ScaleVector/ScaleVector.xml deleted file mode 100644 index 3ec3519e..00000000 --- a/src/Plugins/ScaleVector/ScaleVector.xml +++ /dev/null @@ -1,77 +0,0 @@ - - - - - - - "Multiply a vector by a scale factor." - - - - - - - - - - - - - - - - - - - Specifies the cell field used for the elevation surface. - - - - - - - - - - - - - - - - - diff --git a/src/Plugins/ScaleVector/plugin/CMakeLists.txt b/src/Plugins/ScaleVector/plugin/CMakeLists.txt new file mode 100644 index 00000000..783f761a --- /dev/null +++ b/src/Plugins/ScaleVector/plugin/CMakeLists.txt @@ -0,0 +1,13 @@ + +paraview_add_plugin(ScaleVector + VERSION "1.0" + MODULES ScaleVectorModule + MODULE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/ScaleVectorModule/vtk.module" + SERVER_MANAGER_XML filters.xml +) + +install(TARGETS ScaleVector + RUNTIME DESTINATION lib/paraview + LIBRARY DESTINATION lib/paraview + ARCHIVE DESTINATION lib/paraview + ) diff --git a/src/Plugins/ScaleVector/plugin/ScaleVectorModule/CMakeLists.txt b/src/Plugins/ScaleVector/plugin/ScaleVectorModule/CMakeLists.txt new file mode 100644 index 00000000..7dd8e550 --- /dev/null +++ b/src/Plugins/ScaleVector/plugin/ScaleVectorModule/CMakeLists.txt @@ -0,0 +1,8 @@ +set(classes + vtkScaleVectorFilter +) + +vtk_module_add_module(ScaleVectorModule + FORCE_STATIC + CLASSES ${classes} +) diff --git a/src/Plugins/ScaleVector/plugin/ScaleVectorModule/vtk.module b/src/Plugins/ScaleVector/plugin/ScaleVectorModule/vtk.module new file mode 100644 index 00000000..c43eba0a --- /dev/null +++ b/src/Plugins/ScaleVector/plugin/ScaleVectorModule/vtk.module @@ -0,0 +1,11 @@ +NAME + ScaleVectorModule +DEPENDS + VTK::CommonCore + VTK::CommonDataModel + VTK::CommonExecutionModel + VTK::FiltersCore +PRIVATE_DEPENDS + VTK::CommonMisc + VTK::CommonSystem + VTK::FiltersGeneral diff --git a/src/Plugins/ScaleVector/plugin/ScaleVectorModule/vtkScaleVectorFilter.cxx b/src/Plugins/ScaleVector/plugin/ScaleVectorModule/vtkScaleVectorFilter.cxx new file mode 100644 index 00000000..8ed96b1c --- /dev/null +++ b/src/Plugins/ScaleVector/plugin/ScaleVectorModule/vtkScaleVectorFilter.cxx @@ -0,0 +1,167 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// + +#include "vtkScaleVectorFilter.h" + +#include +#include +#include +#include +#include +#include + +#include + +using namespace std; + +// vtkCxxRevisionMacro(vtkScaleVectorFilter, "$Revision$"); +vtkStandardNewMacro(vtkScaleVectorFilter); + +vtkScaleVectorFilter::vtkScaleVectorFilter() +{ + this->ScaleFactor = 0.5; +} + +vtkScaleVectorFilter::~vtkScaleVectorFilter() +{ +} + +//---------------------------------------------------------------------------- +int vtkScaleVectorFilter::FillInputPortInformation(int vtkNotUsed(port), vtkInformation* info) +{ + // now add our info + info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkDataSet"); + return 1; +} + +int vtkScaleVectorFilter::RequestData( + vtkInformation* vtkNotUsed(request), vtkInformationVector** input, vtkInformationVector* output) +{ + vtkDataSet* dsIn = + vtkDataSet::SafeDownCast(input[0]->GetInformationObject(0)->Get(vtkDataObject::DATA_OBJECT())); + + vtkDataSet* dsOut = + vtkDataSet::SafeDownCast(output->GetInformationObject(0)->Get(vtkDataObject::DATA_OBJECT())); + + vtkDataArray* array = this->GetInputArrayToProcess(0, input); + + if (dsIn == NULL || array == NULL || dsOut == NULL || array->GetNumberOfComponents() != 3 || + this->GetInputArrayAssociation(0, input) != vtkDataObject::FIELD_ASSOCIATION_POINTS) + { + vtkDebugMacro("vtkScaleVectorFilter no correctly configured"); + return 1; + } + + dsOut->ShallowCopy(dsIn); + + vtkPointData* inPD = dsIn->GetPointData(); + vtkPointData* outPD = dsOut->GetPointData(); + + outPD->RemoveArray(array->GetName()); + + vtkDataArray* outArray = array->NewInstance(); + outArray->SetName(array->GetName()); + + string name = array->GetName(); + size_t pos1 = name.find_last_of("["); + if (pos1 != string::npos) + { + string name1 = name.substr(0, pos1); + size_t noblankpos = name1.find_last_not_of(" "); + name1 = name1.substr(0, noblankpos + 1); + + outArray->SetName(name1.c_str()); + + for (int arrayId = 0; arrayId < inPD->GetNumberOfArrays(); arrayId++) + { + vtkDataArray* thearray = inPD->GetArray(arrayId); + if (thearray == NULL) + continue; + + if (strncmp(name1.c_str(), thearray->GetName(), name1.size()) == 0) + { + outPD->RemoveArray(thearray->GetName()); + } + } + } + + outPD->AddArray(outArray); + outArray->Delete(); + + outArray->SetNumberOfComponents(array->GetNumberOfComponents()); + outArray->SetNumberOfTuples(array->GetNumberOfTuples()); + + if (array->HasAComponentName()) + { + outArray->CopyComponentNames(array); + } + + if (array->HasInformation()) + { + outArray->CopyInformation(array->GetInformation()); + } + + for (vtkIdType id = 0; id < outArray->GetNumberOfTuples(); id++) + { + double tuple[3]; + array->GetTuple(id, tuple); + tuple[0] *= this->ScaleFactor; + tuple[1] *= this->ScaleFactor; + tuple[2] *= this->ScaleFactor; + outArray->SetTuple(id, tuple); + } + // fix the range keys to match the full range, so that the + // gui automatically sets the range. + double range[2]; + vtkInformation* info = outArray->GetInformation(); + + array->GetRange(range, -1); + range[0] = 0; + info->Set(vtkDataArray::L2_NORM_RANGE(), range, 2); + + if (!outArray->GetInformation()->Has(vtkDataArray::PER_COMPONENT())) + { + vtkInformationVector* infoVec = vtkInformationVector::New(); + info->Set(vtkDataArray::PER_COMPONENT(), infoVec); + infoVec->FastDelete(); + } + vtkInformationVector* per_comp = info->Get(vtkDataArray::PER_COMPONENT()); + per_comp->SetNumberOfInformationObjects(outArray->GetNumberOfComponents()); + for (int comp = 0; comp < outArray->GetNumberOfComponents(); comp++) + { + array->GetRange(range, comp); + range[0] = fabs(range[0]); + range[1] = fabs(range[1]); + double r = (range[0] > range[1] ? range[0] : range[1]); + range[0] = -r; + range[1] = r; + per_comp->GetInformationObject(comp)->Set(vtkDataArray::COMPONENT_RANGE(), range, 2); + } + + outPD->SetActiveVectors(outArray->GetName()); + + return 1; +} + +void vtkScaleVectorFilter::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os, indent); + + os << indent << "ScaleFactor : " << this->ScaleFactor << endl; +} diff --git a/src/Plugins/ScaleVector/plugin/ScaleVectorModule/vtkScaleVectorFilter.h b/src/Plugins/ScaleVector/plugin/ScaleVectorModule/vtkScaleVectorFilter.h new file mode 100644 index 00000000..db6c62c5 --- /dev/null +++ b/src/Plugins/ScaleVector/plugin/ScaleVectorModule/vtkScaleVectorFilter.h @@ -0,0 +1,51 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// + +#ifndef _vtkScaleVectorFilter_h +#define _vtkScaleVectorFilter_h + +#include + +class VTK_EXPORT vtkScaleVectorFilter : public vtkPassInputTypeAlgorithm +{ +public: + static vtkScaleVectorFilter* New(); + vtkTypeMacro(vtkScaleVectorFilter, vtkPassInputTypeAlgorithm); + void PrintSelf(ostream& os, vtkIndent indent) override; + + // Description : + // This is the factor applied to the vector field. + vtkSetClampMacro(ScaleFactor, double, -1, 1); + vtkGetMacro(ScaleFactor, double); + +protected: + vtkScaleVectorFilter(); + ~vtkScaleVectorFilter() override; + + int RequestData(vtkInformation*, vtkInformationVector**, vtkInformationVector*) override; + + int FillInputPortInformation(int port, vtkInformation* info) override; + + double ScaleFactor; + +private: + vtkScaleVectorFilter(const vtkScaleVectorFilter&) = delete; + void operator=(const vtkScaleVectorFilter&) = delete; +}; +#endif diff --git a/src/Plugins/ScaleVector/plugin/filters.xml b/src/Plugins/ScaleVector/plugin/filters.xml new file mode 100644 index 00000000..ffcaaa6a --- /dev/null +++ b/src/Plugins/ScaleVector/plugin/filters.xml @@ -0,0 +1,63 @@ + + + + + + "Multiply a vector by a scale factor." + + + + + + + + + + + + + + + + + + + Specifies the cell field used for the elevation surface. + + + + + + + + + + + + + + + + diff --git a/src/Plugins/ScaleVector/plugin/paraview.plugin b/src/Plugins/ScaleVector/plugin/paraview.plugin new file mode 100644 index 00000000..7905f119 --- /dev/null +++ b/src/Plugins/ScaleVector/plugin/paraview.plugin @@ -0,0 +1,8 @@ +NAME + ScaleVector +DESCRIPTION + This plugin provides the ScaleVector filter +REQUIRES_MODULES + VTK::CommonCore + VTK::IOCore + VTK::FiltersCore diff --git a/src/Plugins/ScaleVector/vtkScaleVectorFilter.cxx b/src/Plugins/ScaleVector/vtkScaleVectorFilter.cxx deleted file mode 100644 index 2b2e4f39..00000000 --- a/src/Plugins/ScaleVector/vtkScaleVectorFilter.cxx +++ /dev/null @@ -1,170 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// - -#include "vtkScaleVectorFilter.h" -#include "vtkInformation.h" -#include "vtkInformationVector.h" -#include "vtkObjectFactory.h" -#include "vtkCellArray.h" -#include "vtkPointData.h" -#include "vtkDataSet.h" - -#include - -using namespace std; - -//vtkCxxRevisionMacro(vtkScaleVectorFilter, "$Revision$"); -vtkStandardNewMacro(vtkScaleVectorFilter); - -vtkScaleVectorFilter::vtkScaleVectorFilter() -{ - this->ScaleFactor = 0.5; -} - -vtkScaleVectorFilter::~vtkScaleVectorFilter() -{ -} - -//---------------------------------------------------------------------------- -int vtkScaleVectorFilter::FillInputPortInformation( - int vtkNotUsed(port), vtkInformation* info) -{ - // now add our info - info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkDataSet"); - return 1; -} - - -int vtkScaleVectorFilter::RequestData(vtkInformation *vtkNotUsed(request), - vtkInformationVector **input, vtkInformationVector *output) -{ - vtkDataSet *dsIn = vtkDataSet::SafeDownCast( - input[0]->GetInformationObject(0)->Get(vtkDataObject::DATA_OBJECT())); - - vtkDataSet *dsOut = vtkDataSet::SafeDownCast( - output->GetInformationObject(0)->Get(vtkDataObject::DATA_OBJECT())); - - vtkDataArray* array = this->GetInputArrayToProcess(0, input); - - if(dsIn == NULL || array == NULL || dsOut == NULL - || array->GetNumberOfComponents() != 3 || - this->GetInputArrayAssociation(0, input) != vtkDataObject::FIELD_ASSOCIATION_POINTS) - { - vtkDebugMacro("vtkScaleVectorFilter no correctly configured"); - return 1; - } - - dsOut->ShallowCopy(dsIn); - - vtkPointData* inPD = dsIn->GetPointData(); - vtkPointData* outPD = dsOut->GetPointData(); - - outPD->RemoveArray(array->GetName()); - - vtkDataArray* outArray = array->NewInstance(); - outArray->SetName(array->GetName()); - - string name = array->GetName(); - size_t pos1 = name.find_last_of("["); - if(pos1 != string::npos) - { - string name1 = name.substr(0, pos1); - size_t noblankpos = name1.find_last_not_of(" "); - name1 = name1.substr(0, noblankpos+1); - - outArray->SetName(name1.c_str()); - - for(int arrayId = 0; arrayId < inPD->GetNumberOfArrays(); arrayId++) - { - vtkDataArray* thearray = inPD->GetArray(arrayId); - if(thearray == NULL) - continue; - - if(strncmp(name1.c_str(), thearray->GetName(), name1.size()) == 0) - { - outPD->RemoveArray(thearray->GetName()); - } - } - } - - outPD->AddArray(outArray); - outArray->Delete(); - - outArray->SetNumberOfComponents(array->GetNumberOfComponents()); - outArray->SetNumberOfTuples(array->GetNumberOfTuples()); - - if(array->HasAComponentName()) - { - outArray->CopyComponentNames(array); - } - - if(array->HasInformation()) - { - outArray->CopyInformation(array->GetInformation()); - } - - for(vtkIdType id=0; id < outArray->GetNumberOfTuples(); id++) - { - double tuple[3]; - array->GetTuple(id, tuple); - tuple[0] *= this->ScaleFactor; - tuple[1] *= this->ScaleFactor; - tuple[2] *= this->ScaleFactor; - outArray->SetTuple(id, tuple); - } - // fix the range keys to match the full range, so that the - // gui automatically sets the range. - double range[2]; - vtkInformation* info = outArray->GetInformation(); - - array->GetRange(range, -1); - range[0] = 0; - info->Set(vtkDataArray::L2_NORM_RANGE(), range, 2); - - if(!outArray->GetInformation()->Has(vtkDataArray::PER_COMPONENT())) - { - vtkInformationVector* infoVec = vtkInformationVector::New(); - info->Set( vtkDataArray::PER_COMPONENT(), infoVec ); - infoVec->FastDelete(); - } - vtkInformationVector* per_comp = info->Get(vtkDataArray::PER_COMPONENT()); - per_comp->SetNumberOfInformationObjects(outArray->GetNumberOfComponents()); - for(int comp = 0; comp < outArray->GetNumberOfComponents(); comp++) - { - array->GetRange(range, comp); - range[0] = fabs(range[0]); - range[1] = fabs(range[1]); - double r = (range[0] > range[1] ? range[0] : range[1]); - range[0] = -r; - range[1] = r; - per_comp->GetInformationObject(comp)->Set( - vtkDataArray::COMPONENT_RANGE(), range, 2 ); - } - - outPD->SetActiveVectors(outArray->GetName()); - - return 1; -} - -void vtkScaleVectorFilter::PrintSelf(ostream& os, vtkIndent indent) -{ - this->Superclass::PrintSelf(os, indent); - - os << indent << "ScaleFactor : " << this->ScaleFactor << endl; -} diff --git a/src/Plugins/ScaleVector/vtkScaleVectorFilter.h b/src/Plugins/ScaleVector/vtkScaleVectorFilter.h deleted file mode 100644 index 34129116..00000000 --- a/src/Plugins/ScaleVector/vtkScaleVectorFilter.h +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// - -#ifndef _vtkScaleVectorFilter_h -#define _vtkScaleVectorFilter_h - -#include "vtkPassInputTypeAlgorithm.h" - -class VTK_EXPORT vtkScaleVectorFilter: public vtkPassInputTypeAlgorithm -{ -public: - static vtkScaleVectorFilter *New(); - vtkTypeMacro(vtkScaleVectorFilter,vtkPassInputTypeAlgorithm); - void PrintSelf(ostream& os, vtkIndent indent); - - // Description : - // This is the factor applied to the vector field. - vtkSetClampMacro(ScaleFactor,double, -1, 1); - vtkGetMacro(ScaleFactor,double); - -protected: - vtkScaleVectorFilter(); - ~vtkScaleVectorFilter(); - - int RequestData(vtkInformation *, - vtkInformationVector **, - vtkInformationVector *); - - int FillInputPortInformation(int port, - vtkInformation* info); - - double ScaleFactor; - -private: - vtkScaleVectorFilter(const vtkScaleVectorFilter&); - void operator =(const vtkScaleVectorFilter&); -}; -#endif diff --git a/src/Plugins/SimpleMode/CMakeLists.txt b/src/Plugins/SimpleMode/CMakeLists.txt index fcfae85c..4fbf2cb9 100644 --- a/src/Plugins/SimpleMode/CMakeLists.txt +++ b/src/Plugins/SimpleMode/CMakeLists.txt @@ -1,58 +1,30 @@ -# Copyright (C) 2017-2019 CEA/DEN, EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# -# Author : Anthony Geay (EDF R&D) - -PROJECT(SimpleMode) -CMAKE_MINIMUM_REQUIRED(VERSION 2.8) - -CMAKE_POLICY(SET CMP0003 NEW) -IF(${CMAKE_VERSION} VERSION_GREATER "3.0.0") - CMAKE_POLICY(SET CMP0022 OLD) - CMAKE_POLICY(SET CMP0023 OLD) -ENDIF() - -SET(MED_READER_VERSION "0.0.0") - -# Common CMake macros -# =================== -SET(CONFIGURATION_ROOT_DIR $ENV{CONFIGURATION_ROOT_DIR} CACHE PATH "Path to the Salome CMake configuration files") -IF(EXISTS ${CONFIGURATION_ROOT_DIR}) - LIST(APPEND CMAKE_MODULE_PATH "${CONFIGURATION_ROOT_DIR}/cmake") - INCLUDE(SalomeMacros) -ELSE() - MESSAGE(FATAL_ERROR "We absolutely need the Salome CMake configuration files, please define CONFIGURATION_ROOT_DIR !") -ENDIF() -FIND_PACKAGE(SalomePythonInterp REQUIRED) -FIND_PACKAGE(SalomePythonLibs REQUIRED) - -FIND_PACKAGE(ParaView REQUIRED) -IF(NOT ParaView_FOUND) - MESSAGE(FATAL_ERROR "Please locate ParaView." ) -ENDIF(NOT ParaView_FOUND) -INCLUDE(${PARAVIEW_USE_FILE}) - -OPTION(BUILD_SHARED_LIBS "Build with shared libraries." ${VTK_BUILD_SHARED_LIBS}) - -SET(VTK_INSTALL_RUNTIME_DIR lib/salome) -SET(VTK_INSTALL_LIBRARY_DIR lib/salome) -SET(VTK_INSTALL_ARCHIVE_DIR lib/salome) - -PV_PROCESS_MODULES() - -ADD_SUBDIRECTORY(ParaViewPlugin) +cmake_minimum_required(VERSION 3.8) +project(SimpleModePlugin) +find_package(ParaView REQUIRED) + +include(GNUInstallDirs) +set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_BINDIR}") +set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_LIBDIR}") +set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_LIBDIR}") + +set("_paraview_plugin_default_${CMAKE_PROJECT_NAME}" ON) +paraview_plugin_scan( + ENABLE_BY_DEFAULT YES + PLUGIN_FILES "${CMAKE_CURRENT_SOURCE_DIR}/plugin/paraview.plugin" + PROVIDES_PLUGINS plugins + REQUIRES_MODULES required_modules) + +foreach(module IN LISTS required_modules) + if(NOT TARGET "${module}") + message("Missing required module: ${module}") + return() + endif() +endforeach() + +set(BUILD_SHARED_LIBS ON) +paraview_plugin_build( + RUNTIME_DESTINATION "${CMAKE_INSTALL_BINDIR}" + LIBRARY_DESTINATION "${CMAKE_INSTALL_LIBDIR}" + LIBRARY_SUBDIRECTORY "${PARAVIEW_PLUGIN_SUBDIR}" + PLUGINS ${plugins} + AUTOLOAD ${plugins}) diff --git a/src/Plugins/SimpleMode/IO/vtkSimpleMode.cxx b/src/Plugins/SimpleMode/IO/vtkSimpleMode.cxx deleted file mode 100644 index 2626e79d..00000000 --- a/src/Plugins/SimpleMode/IO/vtkSimpleMode.cxx +++ /dev/null @@ -1,496 +0,0 @@ -// Copyright (C) 2017-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Anthony Geay (EDF R&D) - -#include "vtkSimpleMode.h" - -#include "vtkAdjacentVertexIterator.h" -#include "vtkDataSetSurfaceFilter.h" -#include "vtkIntArray.h" -#include "vtkCellData.h" -#include "vtkPointData.h" - -#include "vtkStreamingDemandDrivenPipeline.h" -#include "vtkUnstructuredGrid.h" -#include "vtkDataSet.h" -#include "vtkMultiBlockDataSet.h" - -#include "vtkInformationStringKey.h" -#include "vtkAlgorithmOutput.h" -#include "vtkObjectFactory.h" -#include "vtkMutableDirectedGraph.h" -#include "vtkMultiBlockDataSet.h" -#include "vtkDataSet.h" -#include "vtkInformationVector.h" -#include "vtkInformation.h" -#include "vtkDataArraySelection.h" -#include "vtkTimeStamp.h" -#include "vtkInEdgeIterator.h" -#include "vtkInformationDataObjectKey.h" -#include "vtkExecutive.h" -#include "vtkVariantArray.h" -#include "vtkStringArray.h" -#include "vtkDoubleArray.h" -#include "vtkFloatArray.h" -#include "vtkCharArray.h" -#include "vtkUnsignedCharArray.h" -#include "vtkDataSetAttributes.h" -#include "vtkDemandDrivenPipeline.h" -#include "vtkDataObjectTreeIterator.h" -#include "vtkWarpScalar.h" -#include "vtkWarpVector.h" -#include "vtkMultiBlockDataGroupFilter.h" -#include "vtkCompositeDataToUnstructuredGridFilter.h" - -#ifdef WIN32 -#define _USE_MATH_DEFINES -#include -#include -#endif - -#include -#include -#include - -vtkStandardNewMacro(vtkSimpleMode); - -static const char ZE_DISPLACEMENT_NAME1[]="@@ForReal?@@"; - -static const char ZE_DISPLACEMENT_NAME2[]="@@ForImag?@@"; - -static const char ZE_DISPLACEMENT_NAME3[]="MagnitudeOfCpxDisp"; - -static const double EPS=1e-12; - -/////////////////// - -class MZCException : public std::exception -{ -public: - MZCException(const std::string& s):_reason(s) { } - virtual const char *what() const throw() { return _reason.c_str(); } - virtual ~MZCException() throw() { } -private: - std::string _reason; -}; - -//ValueTypeT - -/*template -struct ArrayTraits -{ - typedef T EltType; - };*/ - -template -vtkSmartPointer ForceTo3CompoImpl(VTK_ARRAY_T *arr) -{ - using ELT_TYPE = typename VTK_ARRAY_T::ValueType; - if(!arr) - return vtkSmartPointer(); - vtkIdType nbCompo(arr->GetNumberOfComponents()),nbTuples(arr->GetNumberOfTuples()); - if(nbCompo==3) - { - vtkSmartPointer ret(arr); - return ret; - } - if(nbCompo==6) - { - vtkSmartPointer ret(vtkSmartPointer::New()); - ret->SetNumberOfComponents(3); - ret->SetNumberOfTuples(nbTuples); - const ELT_TYPE *srcPt(arr->Begin()); - ELT_TYPE *destPt(ret->Begin()); - for(vtkIdType i=0;i ForceTo3Compo(vtkDataArray *arr) -{ - vtkDoubleArray *arr0(vtkDoubleArray::SafeDownCast(arr)); - if(arr0) - return ForceTo3CompoImpl(arr0); - vtkFloatArray *arr1(vtkFloatArray::SafeDownCast(arr)); - if(arr1) - return ForceTo3CompoImpl(arr1); - throw MZCException("ForceTo3Compo : array is NEITHER float64 NOR float32 array !"); -} - -template -void FeedDataInternal(VTK_ARRAY_T *arrReal, double cst1, double *ptToFeed1) -{ - vtkIdType nbTuples(arrReal->GetNumberOfTuples()); - using ELT_TYPE = typename VTK_ARRAY_T::ValueType; - const ELT_TYPE *srcPt1(arrReal->Begin()); - std::for_each(srcPt1,srcPt1+3*nbTuples,[&ptToFeed1,cst1](const ELT_TYPE& elt) { *ptToFeed1 = (double)elt * cst1; ptToFeed1++; }); -} - -void FeedData(vtkDataArray *arr, double cst1, double *ptToFeed1) -{ - vtkDoubleArray *arr0(vtkDoubleArray::SafeDownCast(arr)); - if(arr0) - return FeedDataInternal(arr0,cst1,ptToFeed1); - vtkFloatArray *arr1(vtkFloatArray::SafeDownCast(arr)); - if(arr1) - return FeedDataInternal(arr1,cst1,ptToFeed1); - throw MZCException("FeedData : array is NEITHER float64 NOR float32 array !"); -} - -std::vector< std::string > GetPossibleArrayNames(vtkDataSet *dataset) -{ - if(!dataset) - throw MZCException("The input dataset is null !"); - std::vector< std::string > ret; - vtkPointData *att(dataset->GetPointData()); - for(int i=0;iGetNumberOfArrays();i++) - { - vtkDataArray *locArr(att->GetArray(i)); - int nbComp(locArr->GetNumberOfComponents()); - if(nbComp!=3 && nbComp!=6) - continue; - std::string s(locArr->GetName()); - ret.push_back(s); - } - return ret; -} - -std::string FindTheBest(const std::vector& arrNames, const std::string& key0, const std::string& key1) -{ - std::string ret; - char points(0); - if(arrNames.empty()) - return ret; - for(std::vector::const_iterator it=arrNames.begin();it!=arrNames.end();it++) - { - char curNbPts(1); - if((*it).find(key0,0)!=std::string::npos) - curNbPts++; - if((*it).find(key1,0)!=std::string::npos) - curNbPts++; - if(curNbPts>points) - { - points=curNbPts; - ret=*it; - } - } - return ret; -} - -std::string FindBestRealAmong(const std::vector& arrNames) -{ - static const char KEY1[]="DEPL"; - static const char KEY2[]="REEL"; - return FindTheBest(arrNames,KEY1,KEY2); -} - -std::string FindBestImagAmong(const std::vector& arrNames) -{ - static const char KEY1[]="DEPL"; - static const char KEY2[]="IMAG"; - return FindTheBest(arrNames,KEY1,KEY2); -} - -vtkUnstructuredGrid *ExtractInfo1(vtkInformationVector *inputVector) -{ - vtkInformation *inputInfo(inputVector->GetInformationObject(0)); - vtkDataSet *input(0); - vtkDataSet *input0(vtkDataSet::SafeDownCast(inputInfo->Get(vtkDataObject::DATA_OBJECT()))); - vtkMultiBlockDataSet *input1(vtkMultiBlockDataSet::SafeDownCast(inputInfo->Get(vtkDataObject::DATA_OBJECT()))); - if(input0) - input=input0; - else - { - if(!input1) - throw MZCException("Input dataSet must be a DataSet or single elt multi block dataset expected !"); - if(input1->GetNumberOfBlocks()!=1) - throw MZCException("Input dataSet is a multiblock dataset with not exactly one block ! Use MergeBlocks or ExtractBlocks filter before calling this filter !"); - vtkDataObject *input2(input1->GetBlock(0)); - if(!input2) - throw MZCException("Input dataSet is a multiblock dataset with exactly one block but this single element is NULL !"); - vtkDataSet *input2c(vtkDataSet::SafeDownCast(input2)); - if(!input2c) - throw MZCException("Input dataSet is a multiblock dataset with exactly one block but this single element is not a dataset ! Use MergeBlocks or ExtractBlocks filter before calling this filter !"); - input=input2c; - } - if(!input) - throw MZCException("Input data set is NULL !"); - vtkUnstructuredGrid *usgIn(vtkUnstructuredGrid::SafeDownCast(input)); - if(!usgIn) - throw MZCException("Input data set is not an unstructured mesh ! This filter works only on unstructured meshes !"); - return usgIn; -} - -void ExtractInfo3(vtkDataSet *ds, const std::string& arrName, vtkDataArray *& arr, int& idx) -{ - vtkPointData *att(ds->GetPointData()); - if(!att) - throw MZCException("Input dataset has no point data attribute ! Impossible to move mesh !"); - vtkDataArray *zeArr(0); - int i(0); - for(;iGetNumberOfArrays();i++) - { - vtkDataArray *locArr(att->GetArray(i)); - std::string s(locArr->GetName()); - if(s==arrName) - { - zeArr=locArr; - break; - } - } - if(!zeArr) - { - std::ostringstream oss; - oss << "Impossible to locate the array called \"" << arrName << "\" used to move mesh !"; - throw MZCException(oss.str()); - } - arr=zeArr; - idx=i; -} - - -void ExtractInfo2(vtkDataSet *ds, const std::string& arrName, vtkDataArray *&arr) -{ - int dummy; - ExtractInfo3(ds,arrName,arr,dummy); - vtkDoubleArray *arr1(vtkDoubleArray::SafeDownCast(arr)); - vtkFloatArray *arr2(vtkFloatArray::SafeDownCast(arr)); - if(!arr1 && !arr2) - { - std::ostringstream oss; - oss << "Array called \"" << arrName << "\" has been located but this is NEITHER float64 NOR float32 array !"; - throw MZCException(oss.str()); - } - if(arr->GetNumberOfComponents()!=3 && arr->GetNumberOfComponents()!=6) - { - std::ostringstream oss; - oss << "Float64 array called \"" << arrName << "\" has been located but this array has not exactly 3 or 6 components as it should !"; - throw MZCException(oss.str()); - } - if(arr->GetNumberOfTuples()!=ds->GetNumberOfPoints()) - { - std::ostringstream oss; - oss << "Float64-1 components array called \"" << arrName << "\" has been located but the number of tuples is invalid ! Should be " << ds->GetNumberOfPoints() << " instead of " << arr->GetNumberOfTuples() << " !"; - throw MZCException(oss.str()); - } -} - -//////////////////// - -class vtkSimpleMode::vtkSimpleModeInternal -{ -public: - vtkSimpleModeInternal():_surface(0) { } - vtkPolyData *performConnection(vtkDataSet *ds); - void setFieldForReal(const std::string& st) { _real=st; } - std::string getFieldForReal() const { return _real; } - ~vtkSimpleModeInternal(); -private: - vtkDataSetSurfaceFilter *_surface; -private: - std::string _real; -}; - -vtkPolyData *vtkSimpleMode::vtkSimpleModeInternal::performConnection(vtkDataSet *ds) -{ - if(!_surface) - { - _surface=vtkDataSetSurfaceFilter::New(); - _surface->SetInputData(ds); - } - _surface->Update(); - return _surface->GetOutput(); -} - -vtkSimpleMode::vtkSimpleModeInternal::~vtkSimpleModeInternal() -{ - if(_surface) - _surface->Delete(); -} - -vtkSimpleMode::vtkSimpleMode():Factor(1.),AnimationTime(0.),Internal(new vtkSimpleMode::vtkSimpleModeInternal) -{ - //this->SetInputArrayToProcess(0,0,0,vtkDataObject::FIELD_ASSOCIATION_POINTS,vtkDataSetAttributes::VECTORS); -} - -vtkSimpleMode::~vtkSimpleMode() -{ - delete this->Internal; -} - -void vtkSimpleMode::SetInputArrayToProcess(int idx, int port, int connection, int ff, const char *name) -{ - if(idx==0) - this->Internal->setFieldForReal(name); - vtkDataSetAlgorithm::SetInputArrayToProcess(idx,port,connection,ff,name); -} - -double GetOptimalRatioFrom(vtkUnstructuredGrid *dataset, vtkDoubleArray *array) -{ - if(!dataset || !array) - throw MZCException("The input dataset and or array is null !"); - vtkDataArray *coords(dataset->GetPoints()->GetData()); - vtkDoubleArray *coords2(vtkDoubleArray::SafeDownCast(coords)); - if(!coords2) - throw MZCException("Input coordinates are not float64 !"); - int nbCompo(array->GetNumberOfComponents()); - if(coords2->GetNumberOfComponents()!=3 || (nbCompo!=3 && nbCompo!=6)) - throw MZCException("Input coordinates do not have 3 components as it should !"); - int nbPts(dataset->GetNumberOfPoints()); - const double *srcPt1(array->Begin()); - dataset->ComputeBounds(); - double *minmax1(dataset->GetBounds()); - double minmax2[3]={0.,0.,0.}; - for(int i=0;iSet(vtkDataObject::DATA_TYPE_NAME(), "vtkPolyData"); - return 1; -} - -int vtkSimpleMode::RequestInformation(vtkInformation *request, vtkInformationVector **inputVector, vtkInformationVector *outputVector) -{ - //std::cerr << "########################################## vtkSimpleMode::RequestInformation ##########################################" << std::endl; - try - { - if(this->Internal->getFieldForReal().empty()) - return 1; - /*vtkUnstructuredGrid *usgIn(0); - vtkDoubleArray *arr(0); - ExtractInfo(inputVector[0],usgIn,this->Internal->getFieldForReal(),arr); - std::vector candidatesArrName(GetPossibleArrayNames(usgIn)); - // - double ratio(GetOptimalRatioFrom(usgIn,arr)); - std::string optArrNameForReal(FindBestRealAmong(candidatesArrName)); - std::string optArrNameForImag(FindBestImagAmong(candidatesArrName));*/ - //std::cerr << ratio << std::endl; - //std::cerr << optArrNameForReal << " * " << optArrNameForImag << std::endl; - } - catch(MZCException& e) - { - std::ostringstream oss; - oss << "Exception has been thrown in vtkSimpleMode::RequestInformation : " << e.what() << std::endl; - if(this->HasObserver("ErrorEvent") ) - this->InvokeEvent("ErrorEvent",const_cast(oss.str().c_str())); - else - vtkOutputWindowDisplayErrorText(const_cast(oss.str().c_str())); - vtkObject::BreakOnError(); - return 0; - } - return 1; -} - -int vtkSimpleMode::RequestData(vtkInformation *request, vtkInformationVector **inputVector, vtkInformationVector *outputVector) -{ - //std::cerr << "########################################## vtkSimpleMode::RequestData ##########################################" << std::endl; - try - { - vtkUnstructuredGrid *usgIn(0); - usgIn=ExtractInfo1(inputVector[0]); - // - int nbPts(usgIn->GetNumberOfPoints()); - vtkPolyData *outSurface(this->Internal->performConnection(usgIn)); - vtkDataArray *arrRealBase(nullptr); - ExtractInfo2(outSurface,this->Internal->getFieldForReal(),arrRealBase); - vtkSmartPointer arrReal(ForceTo3Compo(arrRealBase)); - vtkSmartPointer arr1(vtkSmartPointer::New()); - arr1->SetName(ZE_DISPLACEMENT_NAME1); - arr1->SetNumberOfComponents(3); - arr1->SetNumberOfTuples(nbPts); - double *ptToFeed1(arr1->Begin()); - double cst1(Factor*cos(AnimationTime*2*M_PI)); - FeedData(arrReal,cst1,ptToFeed1); - int idx1(outSurface->GetPointData()->AddArray(arr1)); - outSurface->GetPointData()->SetActiveAttribute(idx1,vtkDataSetAttributes::VECTORS); - // - // - vtkSmartPointer ws(vtkSmartPointer::New());//vtkNew - ws->SetInputData(outSurface); - ws->SetScaleFactor(1.); - ws->SetInputArrayToProcess(idx1,0,0,"vtkDataObject::FIELD_ASSOCIATION_POINTS",ZE_DISPLACEMENT_NAME1); - ws->Update(); - vtkSmartPointer ds(ws->GetOutput()); - ds->GetPointData()->RemoveArray(idx1); - // - int idx2(0); - { - vtkDataArray *dummy(0); - ExtractInfo3(ds,this->Internal->getFieldForReal(),dummy,idx2); - } - // - vtkInformation *outInfo(outputVector->GetInformationObject(0)); - vtkPolyData *output(vtkPolyData::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT()))); - output->ShallowCopy(ds); - output->GetPointData()->DeepCopy(ds->GetPointData()); - // - for(int i=0;iGetPointData()->GetNumberOfArrays();i++) - { - vtkDataArray *arr(output->GetPointData()->GetArray(i)); - vtkDoubleArray *arr2(vtkDoubleArray::SafeDownCast(arr)); - if(!arr2) - continue; - vtkIdType nbCompo(arr2->GetNumberOfComponents()),nbTuples(arr2->GetNumberOfTuples()); - if(nbCompo!=3 && nbCompo!=2) - continue; - double *arrPtr(arr2->GetPointer(0)); - std::transform(arrPtr,arrPtr+nbCompo*nbTuples,arrPtr,std::bind2nd(std::multiplies(),cos(AnimationTime*2*M_PI))); - } - // - vtkDataArray* array = output->GetPointData()->GetArray(idx2); - vtkSmartPointer result = vtkSmartPointer::Take(vtkDataArray::CreateDataArray(array->GetDataType())); - result->ShallowCopy(array); - result->SetName("__NormalModesAnimation__"); - output->GetPointData()->SetScalars(result); - } - catch(MZCException& e) - { - std::ostringstream oss; - oss << "Exception has been thrown in vtkSimpleMode::RequestInformation : " << e.what() << std::endl; - if(this->HasObserver("ErrorEvent") ) - this->InvokeEvent("ErrorEvent",const_cast(oss.str().c_str())); - else - vtkOutputWindowDisplayErrorText(const_cast(oss.str().c_str())); - vtkObject::BreakOnError(); - return 0; - } - return 1; -} - -void vtkSimpleMode::PrintSelf(ostream& os, vtkIndent indent) -{ - this->Superclass::PrintSelf(os, indent); -} diff --git a/src/Plugins/SimpleMode/IO/vtkSimpleMode.h b/src/Plugins/SimpleMode/IO/vtkSimpleMode.h deleted file mode 100644 index 8476d6f4..00000000 --- a/src/Plugins/SimpleMode/IO/vtkSimpleMode.h +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (C) 2017-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Anthony Geay (EDF R&D) - -#ifndef vtkSimpleMode_h__ -#define vtkSimpleMode_h__ - -#include "vtkDataSetAlgorithm.h" - -class vtkMutableDirectedGraph; - -class VTK_EXPORT vtkSimpleMode : public vtkDataSetAlgorithm -{ -public: - static vtkSimpleMode* New(); - vtkTypeMacro(vtkSimpleMode, vtkDataSetAlgorithm) - void PrintSelf(ostream& os, vtkIndent indent); - void SetInputArrayToProcess(int idx, int port, int connection, int fieldAssociation, const char *name); - vtkGetMacro(Factor,double); - vtkSetClampMacro(Factor,double,0.,VTK_DOUBLE_MAX); - vtkGetMacro(AnimationTime,double); - vtkSetClampMacro(AnimationTime,double,0.,1.); -protected: - vtkSimpleMode(); - ~vtkSimpleMode(); - int FillOutputPortInformation( int vtkNotUsed(port), vtkInformation* info); - int RequestInformation(vtkInformation *request, - vtkInformationVector **inputVector, vtkInformationVector *outputVector); - - int RequestData(vtkInformation *request, vtkInformationVector **inputVector, - vtkInformationVector *outputVector); -private: - vtkSimpleMode(const vtkSimpleMode&); - void operator=(const vtkSimpleMode&); // Not implemented. - private: - //BTX - //ETX - double Factor; - double AnimationTime; - class vtkSimpleModeInternal; - vtkSimpleModeInternal* Internal; -}; - -#endif diff --git a/src/Plugins/SimpleMode/ParaViewPlugin/CMakeLists.txt b/src/Plugins/SimpleMode/ParaViewPlugin/CMakeLists.txt deleted file mode 100644 index 0e3c512c..00000000 --- a/src/Plugins/SimpleMode/ParaViewPlugin/CMakeLists.txt +++ /dev/null @@ -1,25 +0,0 @@ -# Copyright (C) 2017-2019 CEA/DEN, EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# -# Author : Anthony Geay (EDF R&D) - -INCLUDE_DIRECTORIES( ${CMAKE_CURRENT_SOURCE_DIR}/../IO ) -ADD_PARAVIEW_PLUGIN(SimpleModePlugin "4.0" - SERVER_MANAGER_SOURCES ${SM_SRCS} ${PROJECT_SOURCE_DIR}/IO/vtkSimpleMode.cxx - SERVER_MANAGER_XML Resources/SimpleModeServer.xml) -INSTALL(TARGETS SimpleModePlugin RUNTIME DESTINATION lib/paraview LIBRARY DESTINATION lib/paraview ARCHIVE DESTINATION lib/paraview) diff --git a/src/Plugins/SimpleMode/ParaViewPlugin/Resources/SimpleModeServer.xml b/src/Plugins/SimpleMode/ParaViewPlugin/Resources/SimpleModeServer.xml deleted file mode 100644 index 82a393c2..00000000 --- a/src/Plugins/SimpleMode/ParaViewPlugin/Resources/SimpleModeServer.xml +++ /dev/null @@ -1,67 +0,0 @@ - - - - - - - - - - - - - This property specifies the input to the Level Scalars filter. - - - - - - - - - - - - -Select the array that represents the requested mode. - - - - - - - - - - - The value of this property sets the scale factor applied for all nodes displacement. - - - - - The value of this property sets the scale factor applied for all nodes displacement. - - - - - - - diff --git a/src/Plugins/SimpleMode/plugin/CMakeLists.txt b/src/Plugins/SimpleMode/plugin/CMakeLists.txt new file mode 100644 index 00000000..9daa2c66 --- /dev/null +++ b/src/Plugins/SimpleMode/plugin/CMakeLists.txt @@ -0,0 +1,13 @@ + +paraview_add_plugin(SimpleModePlugin + VERSION "1.0" + MODULES SimpleModeModule + MODULE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/SimpleModeModule/vtk.module" + SERVER_MANAGER_XML filters.xml +) + +install(TARGETS SimpleModePlugin + RUNTIME DESTINATION lib/paraview + LIBRARY DESTINATION lib/paraview + ARCHIVE DESTINATION lib/paraview + ) diff --git a/src/Plugins/SimpleMode/plugin/SimpleModeModule/CMakeLists.txt b/src/Plugins/SimpleMode/plugin/SimpleModeModule/CMakeLists.txt new file mode 100644 index 00000000..51a29e9f --- /dev/null +++ b/src/Plugins/SimpleMode/plugin/SimpleModeModule/CMakeLists.txt @@ -0,0 +1,8 @@ +set(classes + vtkSimpleMode +) + +vtk_module_add_module(SimpleModeModule + FORCE_STATIC + CLASSES ${classes} +) diff --git a/src/Plugins/SimpleMode/plugin/SimpleModeModule/vtk.module b/src/Plugins/SimpleMode/plugin/SimpleModeModule/vtk.module new file mode 100644 index 00000000..9f430537 --- /dev/null +++ b/src/Plugins/SimpleMode/plugin/SimpleModeModule/vtk.module @@ -0,0 +1,14 @@ +NAME + SimpleModeModule +DEPENDS + VTK::CommonCore + VTK::CommonDataModel + VTK::CommonExecutionModel + VTK::FiltersCore + VTK::FiltersModeling +PRIVATE_DEPENDS + VTK::CommonMisc + VTK::CommonSystem + VTK::FiltersGeneral + VTK::FiltersGeometry + ParaView::VTKExtensionsMisc diff --git a/src/Plugins/SimpleMode/plugin/SimpleModeModule/vtkSimpleMode.cxx b/src/Plugins/SimpleMode/plugin/SimpleModeModule/vtkSimpleMode.cxx new file mode 100644 index 00000000..a7262c36 --- /dev/null +++ b/src/Plugins/SimpleMode/plugin/SimpleModeModule/vtkSimpleMode.cxx @@ -0,0 +1,528 @@ +// Copyright (C) 2017-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay (EDF R&D) + +#include "vtkSimpleMode.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef WIN32 +#define _USE_MATH_DEFINES +#include +#include +#endif + +#include +#include +#include + +vtkStandardNewMacro(vtkSimpleMode); + +static const char ZE_DISPLACEMENT_NAME1[] = "@@ForReal?@@"; + +static const char ZE_DISPLACEMENT_NAME2[] = "@@ForImag?@@"; + +static const char ZE_DISPLACEMENT_NAME3[] = "MagnitudeOfCpxDisp"; + +static const double EPS = 1e-12; + +/////////////////// + +class MZCException : public std::exception +{ +public: + MZCException(const std::string& s) + : _reason(s) + { + } + virtual const char* what() const throw() { return _reason.c_str(); } + virtual ~MZCException() throw() {} + +private: + std::string _reason; +}; + +// ValueTypeT + +/*template +struct ArrayTraits +{ + typedef T EltType; + };*/ + +template +vtkSmartPointer ForceTo3CompoImpl(VTK_ARRAY_T* arr) +{ + using ELT_TYPE = typename VTK_ARRAY_T::ValueType; + if (!arr) + return vtkSmartPointer(); + vtkIdType nbCompo(arr->GetNumberOfComponents()), nbTuples(arr->GetNumberOfTuples()); + if (nbCompo == 3) + { + vtkSmartPointer ret(arr); + return ret; + } + if (nbCompo == 6) + { + vtkSmartPointer ret(vtkSmartPointer::New()); + ret->SetNumberOfComponents(3); + ret->SetNumberOfTuples(nbTuples); + const ELT_TYPE* srcPt(arr->Begin()); + ELT_TYPE* destPt(ret->Begin()); + for (vtkIdType i = 0; i < nbTuples; i++, destPt += 3, srcPt += 6) + std::copy(srcPt, srcPt + 3, destPt); + return ret; + } + throw MZCException("ForceTo3CompoImpl : internal error ! 6 or 3 compo arrays expected !"); +} + +vtkSmartPointer ForceTo3Compo(vtkDataArray* arr) +{ + vtkDoubleArray* arr0(vtkDoubleArray::SafeDownCast(arr)); + if (arr0) + return ForceTo3CompoImpl(arr0); + vtkFloatArray* arr1(vtkFloatArray::SafeDownCast(arr)); + if (arr1) + return ForceTo3CompoImpl(arr1); + throw MZCException("ForceTo3Compo : array is NEITHER float64 NOR float32 array !"); +} + +template +void FeedDataInternal(VTK_ARRAY_T* arrReal, double cst1, double* ptToFeed1) +{ + vtkIdType nbTuples(arrReal->GetNumberOfTuples()); + using ELT_TYPE = typename VTK_ARRAY_T::ValueType; + const ELT_TYPE* srcPt1(arrReal->Begin()); + std::for_each(srcPt1, srcPt1 + 3 * nbTuples, [&ptToFeed1, cst1](const ELT_TYPE& elt) { + *ptToFeed1 = (double)elt * cst1; + ptToFeed1++; + }); +} + +void FeedData(vtkDataArray* arr, double cst1, double* ptToFeed1) +{ + vtkDoubleArray* arr0(vtkDoubleArray::SafeDownCast(arr)); + if (arr0) + return FeedDataInternal(arr0, cst1, ptToFeed1); + vtkFloatArray* arr1(vtkFloatArray::SafeDownCast(arr)); + if (arr1) + return FeedDataInternal(arr1, cst1, ptToFeed1); + throw MZCException("FeedData : array is NEITHER float64 NOR float32 array !"); +} + +std::vector GetPossibleArrayNames(vtkDataSet* dataset) +{ + if (!dataset) + throw MZCException("The input dataset is null !"); + std::vector ret; + vtkPointData* att(dataset->GetPointData()); + for (int i = 0; i < att->GetNumberOfArrays(); i++) + { + vtkDataArray* locArr(att->GetArray(i)); + int nbComp(locArr->GetNumberOfComponents()); + if (nbComp != 3 && nbComp != 6) + continue; + std::string s(locArr->GetName()); + ret.push_back(s); + } + return ret; +} + +std::string FindTheBest( + const std::vector& arrNames, const std::string& key0, const std::string& key1) +{ + std::string ret; + char points(0); + if (arrNames.empty()) + return ret; + for (std::vector::const_iterator it = arrNames.begin(); it != arrNames.end(); it++) + { + char curNbPts(1); + if ((*it).find(key0, 0) != std::string::npos) + curNbPts++; + if ((*it).find(key1, 0) != std::string::npos) + curNbPts++; + if (curNbPts > points) + { + points = curNbPts; + ret = *it; + } + } + return ret; +} + +std::string FindBestRealAmong(const std::vector& arrNames) +{ + static const char KEY1[] = "DEPL"; + static const char KEY2[] = "REEL"; + return FindTheBest(arrNames, KEY1, KEY2); +} + +std::string FindBestImagAmong(const std::vector& arrNames) +{ + static const char KEY1[] = "DEPL"; + static const char KEY2[] = "IMAG"; + return FindTheBest(arrNames, KEY1, KEY2); +} + +vtkUnstructuredGrid* ExtractInfo1(vtkInformationVector* inputVector) +{ + vtkInformation* inputInfo(inputVector->GetInformationObject(0)); + vtkDataSet* input(0); + vtkDataSet* input0(vtkDataSet::SafeDownCast(inputInfo->Get(vtkDataObject::DATA_OBJECT()))); + vtkMultiBlockDataSet* input1( + vtkMultiBlockDataSet::SafeDownCast(inputInfo->Get(vtkDataObject::DATA_OBJECT()))); + if (input0) + input = input0; + else + { + if (!input1) + throw MZCException( + "Input dataSet must be a DataSet or single elt multi block dataset expected !"); + if (input1->GetNumberOfBlocks() != 1) + throw MZCException("Input dataSet is a multiblock dataset with not exactly one block ! Use " + "MergeBlocks or ExtractBlocks filter before calling this filter !"); + vtkDataObject* input2(input1->GetBlock(0)); + if (!input2) + throw MZCException("Input dataSet is a multiblock dataset with exactly one block but this " + "single element is NULL !"); + vtkDataSet* input2c(vtkDataSet::SafeDownCast(input2)); + if (!input2c) + throw MZCException( + "Input dataSet is a multiblock dataset with exactly one block but this single element is " + "not a dataset ! Use MergeBlocks or ExtractBlocks filter before calling this filter !"); + input = input2c; + } + if (!input) + throw MZCException("Input data set is NULL !"); + vtkUnstructuredGrid* usgIn(vtkUnstructuredGrid::SafeDownCast(input)); + if (!usgIn) + throw MZCException("Input data set is not an unstructured mesh ! This filter works only on " + "unstructured meshes !"); + return usgIn; +} + +void ExtractInfo3(vtkDataSet* ds, const std::string& arrName, vtkDataArray*& arr, int& idx) +{ + vtkPointData* att(ds->GetPointData()); + if (!att) + throw MZCException("Input dataset has no point data attribute ! Impossible to move mesh !"); + vtkDataArray* zeArr(0); + int i(0); + for (; i < att->GetNumberOfArrays(); i++) + { + vtkDataArray* locArr(att->GetArray(i)); + std::string s(locArr->GetName()); + if (s == arrName) + { + zeArr = locArr; + break; + } + } + if (!zeArr) + { + std::ostringstream oss; + oss << "Impossible to locate the array called \"" << arrName << "\" used to move mesh !"; + throw MZCException(oss.str()); + } + arr = zeArr; + idx = i; +} + +void ExtractInfo2(vtkDataSet* ds, const std::string& arrName, vtkDataArray*& arr) +{ + int dummy; + ExtractInfo3(ds, arrName, arr, dummy); + vtkDoubleArray* arr1(vtkDoubleArray::SafeDownCast(arr)); + vtkFloatArray* arr2(vtkFloatArray::SafeDownCast(arr)); + if (!arr1 && !arr2) + { + std::ostringstream oss; + oss << "Array called \"" << arrName + << "\" has been located but this is NEITHER float64 NOR float32 array !"; + throw MZCException(oss.str()); + } + if (arr->GetNumberOfComponents() != 3 && arr->GetNumberOfComponents() != 6) + { + std::ostringstream oss; + oss << "Float64 array called \"" << arrName + << "\" has been located but this array has not exactly 3 or 6 components as it should !"; + throw MZCException(oss.str()); + } + if (arr->GetNumberOfTuples() != ds->GetNumberOfPoints()) + { + std::ostringstream oss; + oss << "Float64-1 components array called \"" << arrName + << "\" has been located but the number of tuples is invalid ! Should be " + << ds->GetNumberOfPoints() << " instead of " << arr->GetNumberOfTuples() << " !"; + throw MZCException(oss.str()); + } +} + +//////////////////// + +class vtkSimpleMode::vtkSimpleModeInternal +{ +public: + vtkSimpleModeInternal() + : _surface(0) + { + } + vtkPolyData* performConnection(vtkDataSet* ds); + void setFieldForReal(const std::string& st) { _real = st; } + std::string getFieldForReal() const { return _real; } + ~vtkSimpleModeInternal(); + +private: + vtkDataSetSurfaceFilter* _surface; + +private: + std::string _real; +}; + +vtkPolyData* vtkSimpleMode::vtkSimpleModeInternal::performConnection(vtkDataSet* ds) +{ + if (!_surface) + { + _surface = vtkDataSetSurfaceFilter::New(); + _surface->SetInputData(ds); + } + _surface->Update(); + return _surface->GetOutput(); +} + +vtkSimpleMode::vtkSimpleModeInternal::~vtkSimpleModeInternal() +{ + if (_surface) + _surface->Delete(); +} + +vtkSimpleMode::vtkSimpleMode() + : Factor(1.) + , AnimationTime(0.) + , Internal(new vtkSimpleMode::vtkSimpleModeInternal) +{ + // this->SetInputArrayToProcess(0,0,0,vtkDataObject::FIELD_ASSOCIATION_POINTS,vtkDataSetAttributes::VECTORS); +} + +vtkSimpleMode::~vtkSimpleMode() +{ + delete this->Internal; +} + +void vtkSimpleMode::SetInputArrayToProcess( + int idx, int port, int connection, int ff, const char* name) +{ + if (idx == 0) + this->Internal->setFieldForReal(name); + vtkDataSetAlgorithm::SetInputArrayToProcess(idx, port, connection, ff, name); +} + +double GetOptimalRatioFrom(vtkUnstructuredGrid* dataset, vtkDoubleArray* array) +{ + if (!dataset || !array) + throw MZCException("The input dataset and or array is null !"); + vtkDataArray* coords(dataset->GetPoints()->GetData()); + vtkDoubleArray* coords2(vtkDoubleArray::SafeDownCast(coords)); + if (!coords2) + throw MZCException("Input coordinates are not float64 !"); + int nbCompo(array->GetNumberOfComponents()); + if (coords2->GetNumberOfComponents() != 3 || (nbCompo != 3 && nbCompo != 6)) + throw MZCException("Input coordinates do not have 3 components as it should !"); + int nbPts(dataset->GetNumberOfPoints()); + const double* srcPt1(array->Begin()); + dataset->ComputeBounds(); + double* minmax1(dataset->GetBounds()); + double minmax2[3] = { 0., 0., 0. }; + for (int i = 0; i < nbPts; i++, srcPt1 += nbCompo) + { + minmax2[0] = std::max(fabs(srcPt1[0]), minmax2[0]); + minmax2[1] = std::max(fabs(srcPt1[1]), minmax2[1]); + minmax2[2] = std::max(fabs(srcPt1[2]), minmax2[2]); + } + double maxDispDelta(*std::max_element(minmax2, minmax2 + 3)); + if (maxDispDelta < EPS) + maxDispDelta = 1.; + for (int i = 0; i < 3; i++) + minmax2[i] = minmax1[2 * i + 1] - minmax1[2 * i]; + double maxGeoDelta(*std::max_element(minmax2, minmax2 + 3)); + if (maxDispDelta < EPS) + maxDispDelta = 1.; + return maxGeoDelta / maxDispDelta; +} + +int vtkSimpleMode::FillOutputPortInformation(int vtkNotUsed(port), vtkInformation* info) +{ + info->Set(vtkDataObject::DATA_TYPE_NAME(), "vtkPolyData"); + return 1; +} + +int vtkSimpleMode::RequestInformation( + vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector) +{ + // std::cerr << "########################################## vtkSimpleMode::RequestInformation + // ##########################################" << std::endl; + try + { + if (this->Internal->getFieldForReal().empty()) + return 1; + /*vtkUnstructuredGrid *usgIn(0); + vtkDoubleArray *arr(0); + ExtractInfo(inputVector[0],usgIn,this->Internal->getFieldForReal(),arr); + std::vector candidatesArrName(GetPossibleArrayNames(usgIn)); + // + double ratio(GetOptimalRatioFrom(usgIn,arr)); + std::string optArrNameForReal(FindBestRealAmong(candidatesArrName)); + std::string optArrNameForImag(FindBestImagAmong(candidatesArrName));*/ + // std::cerr << ratio << std::endl; + // std::cerr << optArrNameForReal << " * " << optArrNameForImag << std::endl; + } + catch (MZCException& e) + { + std::ostringstream oss; + oss << "Exception has been thrown in vtkSimpleMode::RequestInformation : " << e.what() + << std::endl; + if (this->HasObserver("ErrorEvent")) + this->InvokeEvent("ErrorEvent", const_cast(oss.str().c_str())); + else + vtkOutputWindowDisplayErrorText(const_cast(oss.str().c_str())); + vtkObject::BreakOnError(); + return 0; + } + return 1; +} + +int vtkSimpleMode::RequestData( + vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector) +{ + // std::cerr << "########################################## vtkSimpleMode::RequestData + // ##########################################" << std::endl; + try + { + vtkUnstructuredGrid* usgIn(0); + usgIn = ExtractInfo1(inputVector[0]); + // + int nbPts(usgIn->GetNumberOfPoints()); + vtkPolyData* outSurface(this->Internal->performConnection(usgIn)); + vtkDataArray* arrRealBase(nullptr); + ExtractInfo2(outSurface, this->Internal->getFieldForReal(), arrRealBase); + vtkSmartPointer arrReal(ForceTo3Compo(arrRealBase)); + vtkSmartPointer arr1(vtkSmartPointer::New()); + arr1->SetName(ZE_DISPLACEMENT_NAME1); + arr1->SetNumberOfComponents(3); + arr1->SetNumberOfTuples(nbPts); + double* ptToFeed1(arr1->Begin()); + double cst1(Factor * cos(AnimationTime * 2 * M_PI)); + FeedData(arrReal, cst1, ptToFeed1); + int idx1(outSurface->GetPointData()->AddArray(arr1)); + outSurface->GetPointData()->SetActiveAttribute(idx1, vtkDataSetAttributes::VECTORS); + // + // + vtkSmartPointer ws(vtkSmartPointer::New()); // vtkNew + ws->SetInputData(outSurface); + ws->SetScaleFactor(1.); + ws->SetInputArrayToProcess( + idx1, 0, 0, "vtkDataObject::FIELD_ASSOCIATION_POINTS", ZE_DISPLACEMENT_NAME1); + ws->Update(); + vtkSmartPointer ds(ws->GetOutput()); + ds->GetPointData()->RemoveArray(idx1); + // + int idx2(0); + { + vtkDataArray* dummy(0); + ExtractInfo3(ds, this->Internal->getFieldForReal(), dummy, idx2); + } + // + vtkInformation* outInfo(outputVector->GetInformationObject(0)); + vtkPolyData* output(vtkPolyData::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT()))); + output->ShallowCopy(ds); + output->GetPointData()->DeepCopy(ds->GetPointData()); + // + for (int i = 0; i < output->GetPointData()->GetNumberOfArrays(); i++) + { + vtkDataArray* arr(output->GetPointData()->GetArray(i)); + vtkDoubleArray* arr2(vtkDoubleArray::SafeDownCast(arr)); + if (!arr2) + continue; + vtkIdType nbCompo(arr2->GetNumberOfComponents()), nbTuples(arr2->GetNumberOfTuples()); + if (nbCompo != 3 && nbCompo != 2) + continue; + double* arrPtr(arr2->GetPointer(0)); + std::transform(arrPtr, arrPtr + nbCompo * nbTuples, arrPtr, + std::bind2nd(std::multiplies(), cos(AnimationTime * 2 * M_PI))); + } + // + vtkDataArray* array = output->GetPointData()->GetArray(idx2); + vtkSmartPointer result = + vtkSmartPointer::Take(vtkDataArray::CreateDataArray(array->GetDataType())); + result->ShallowCopy(array); + result->SetName("__NormalModesAnimation__"); + output->GetPointData()->SetScalars(result); + } + catch (MZCException& e) + { + std::ostringstream oss; + oss << "Exception has been thrown in vtkSimpleMode::RequestInformation : " << e.what() + << std::endl; + if (this->HasObserver("ErrorEvent")) + this->InvokeEvent("ErrorEvent", const_cast(oss.str().c_str())); + else + vtkOutputWindowDisplayErrorText(const_cast(oss.str().c_str())); + vtkObject::BreakOnError(); + return 0; + } + return 1; +} + +void vtkSimpleMode::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os, indent); +} diff --git a/src/Plugins/SimpleMode/plugin/SimpleModeModule/vtkSimpleMode.h b/src/Plugins/SimpleMode/plugin/SimpleModeModule/vtkSimpleMode.h new file mode 100644 index 00000000..dd2a2a7c --- /dev/null +++ b/src/Plugins/SimpleMode/plugin/SimpleModeModule/vtkSimpleMode.h @@ -0,0 +1,62 @@ +// Copyright (C) 2017-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay (EDF R&D) + +#ifndef vtkSimpleMode_h__ +#define vtkSimpleMode_h__ + +#include + +class vtkMutableDirectedGraph; + +class VTK_EXPORT vtkSimpleMode : public vtkDataSetAlgorithm +{ +public: + static vtkSimpleMode* New(); + vtkTypeMacro(vtkSimpleMode, vtkDataSetAlgorithm); + void PrintSelf(ostream& os, vtkIndent indent) override; + + void SetInputArrayToProcess( + int idx, int port, int connection, int fieldAssociation, const char* name) override; + + vtkGetMacro(Factor, double); + vtkSetClampMacro(Factor, double, 0., VTK_DOUBLE_MAX); + + vtkGetMacro(AnimationTime, double); + vtkSetClampMacro(AnimationTime, double, 0., 1.); + +protected: + vtkSimpleMode(); + ~vtkSimpleMode() override; + + int FillOutputPortInformation(int, vtkInformation*) override; + int RequestInformation(vtkInformation*, vtkInformationVector**, vtkInformationVector*) override; + int RequestData(vtkInformation*, vtkInformationVector**, vtkInformationVector*) override; + +private: + vtkSimpleMode(const vtkSimpleMode&) = delete; + void operator=(const vtkSimpleMode&) = delete; + + double Factor; + double AnimationTime; + class vtkSimpleModeInternal; + vtkSimpleModeInternal* Internal; +}; + +#endif diff --git a/src/Plugins/SimpleMode/plugin/filters.xml b/src/Plugins/SimpleMode/plugin/filters.xml new file mode 100644 index 00000000..2b8a1bf3 --- /dev/null +++ b/src/Plugins/SimpleMode/plugin/filters.xml @@ -0,0 +1,72 @@ + + + + + + + + + + + + + This property specifies the input to the Level Scalars filter. + + + + + + + + + + + + + Select the array that represents the requested mode. + + + + + + + + + + + The value of this property sets the scale factor applied for all nodes displacement. + + + + + The value of this property sets the scale factor applied for all nodes displacement. + + + + + + + diff --git a/src/Plugins/SimpleMode/plugin/paraview.plugin b/src/Plugins/SimpleMode/plugin/paraview.plugin new file mode 100644 index 00000000..771e40bf --- /dev/null +++ b/src/Plugins/SimpleMode/plugin/paraview.plugin @@ -0,0 +1,8 @@ +NAME + SimpleModePlugin +DESCRIPTION + This plugin provides the SimpleMode filter. +REQUIRES_MODULES + VTK::CommonCore + VTK::IOCore + VTK::FiltersCore diff --git a/src/Plugins/StaticMesh/CMakeLists.txt b/src/Plugins/StaticMesh/CMakeLists.txt index 7ab25fd3..527c65fa 100644 --- a/src/Plugins/StaticMesh/CMakeLists.txt +++ b/src/Plugins/StaticMesh/CMakeLists.txt @@ -1,58 +1,30 @@ -# Copyright (C) 2018-2019 EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# +cmake_minimum_required(VERSION 3.8) +project(StaticMesh) +find_package(ParaView REQUIRED) -if (NOT ParaView_BINARY_DIR) - cmake_minimum_required(VERSION 3.3) - find_package(ParaView REQUIRED) - include(${PARAVIEW_USE_FILE}) -endif() +include(GNUInstallDirs) +set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_BINDIR}") +set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_LIBDIR}") +set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_LIBDIR}") -include_directories( - ${VTK_INCLUDE_DIRS} - ${CMAKE_CURRENT_SOURCE_DIR} - ${CMAKE_CURRENT_BINARY_DIR} - ) +set("_paraview_plugin_default_${CMAKE_PROJECT_NAME}" ON) +paraview_plugin_scan( + ENABLE_BY_DEFAULT YES + PLUGIN_FILES "${CMAKE_CURRENT_SOURCE_DIR}/plugin/paraview.plugin" + PROVIDES_PLUGINS plugins + REQUIRES_MODULES required_modules) -set(Module_SRCS - vtkStaticDataSetSurfaceFilter.cxx - vtkStaticEnSight6BinaryReader.cxx - vtkStaticEnSight6Reader.cxx - vtkStaticEnSightGoldBinaryReader.cxx - vtkStaticEnSightGoldReader.cxx - vtkStaticMeshObjectFactory.cxx - vtkStaticPlaneCutter.cxx -) -if (PARAVIEW_USE_MPI) - list(APPEND Module_SRCS vtkStaticPUnstructuredGridGhostCellsGenerator.cxx) -endif() +foreach(module IN LISTS required_modules) + if(NOT TARGET "${module}") + message("Missing required module: ${module}") + return() + endif() +endforeach() -add_paraview_plugin( - StaticMesh "0.1" - SERVER_MANAGER_XML - StaticMeshSM.xml - SERVER_MANAGER_SOURCES - vtkTemporalUGWavelet.cxx - SOURCES - ${Module_SRCS} - ) - -if (BUILD_TESTING) - add_subdirectory(Testing) -endif() -INSTALL(TARGETS StaticMesh RUNTIME DESTINATION lib/paraview LIBRARY DESTINATION lib/paraview ARCHIVE DESTINATION lib/paraview) +set(BUILD_SHARED_LIBS ON) +paraview_plugin_build( + RUNTIME_DESTINATION "${CMAKE_INSTALL_BINDIR}" + LIBRARY_DESTINATION "${CMAKE_INSTALL_LIBDIR}" + LIBRARY_SUBDIRECTORY "${PARAVIEW_PLUGIN_SUBDIR}" + PLUGINS ${plugins} + AUTOLOAD ${plugins}) diff --git a/src/Plugins/StaticMesh/StaticMeshSM.xml b/src/Plugins/StaticMesh/StaticMeshSM.xml deleted file mode 100644 index bf089f3b..00000000 --- a/src/Plugins/StaticMesh/StaticMeshSM.xml +++ /dev/null @@ -1,154 +0,0 @@ - - - - - - See Wavelet documentation. - This is a wavelet converted into an unstructured grid. - It contains timesteps yet the mesh is statis over time. - It also contains tPoint and tCell wich are scalar array varying over time. - - - - - - This property specifies the number of time steps - - - - - The six values in this property indicate the X, Y, and Z - extent of the output data. The first two values represent the minimum - and maximum X indices, the next two are the minimum and maximum Y - indices, and the last two are the minimum and maximum Z - indices. - - - - This property specifies the 3D coordinates of the center of - the periodic function (x, y and z in the equation). - - - - This parameter specifies the maximum value (M) of the - function. - - - - This property specifies the natural frequency in X (XF - in the equation). - - - - This property specifies the natural frequency in Y (YF - in the equation). - - - - This property specifies the natural frequency in Z (ZF - in the equation). - - - - This property specifies the wave amplitude in X (XM in - the equation). - - - - This property specifies the wave amplitude in Y (YM in - the equation). - - - - This property specifies the wave amplitude in Z (ZM in - the equation). - - - - This property specifies the standard deviation of the - Gaussian used in computing this function. - - - - This property specifies the rate at which to subsample - the volume. The extent of the dataset in each dimension will be divided - by this value. (See the Whole Extent property.) - - - - - - - - - - - - - - - - - - diff --git a/src/Plugins/StaticMesh/Testing/CMakeLists.txt b/src/Plugins/StaticMesh/Testing/CMakeLists.txt deleted file mode 100644 index 936f7ae1..00000000 --- a/src/Plugins/StaticMesh/Testing/CMakeLists.txt +++ /dev/null @@ -1,39 +0,0 @@ -include(ParaViewTestingMacros) - -if (PARAVIEW_BUILD_QT_GUI) - add_client_tests("pv" - LOAD_PLUGIN "StaticMesh" - BASELINE_DIR ${PARAVIEW_TEST_BASELINE_DIR} - TEST_SCRIPTS ${CMAKE_CURRENT_SOURCE_DIR}/StaticDataSetSurfaceFilter.xml) - add_client_tests("pv" - LOAD_PLUGIN "StaticMesh" - BASELINE_DIR ${PARAVIEW_TEST_BASELINE_DIR} - TEST_SCRIPTS ${CMAKE_CURRENT_SOURCE_DIR}/StaticPlaneCutter.xml) - add_client_tests("pvcs" - LOAD_PLUGIN "StaticMesh" - BASELINE_DIR ${PARAVIEW_TEST_BASELINE_DIR} - TEST_SCRIPTS ${CMAKE_CURRENT_SOURCE_DIR}/StaticDataSetSurfaceFilter.xml) - add_client_tests("pvcs" - LOAD_PLUGIN "StaticMesh" - BASELINE_DIR ${PARAVIEW_TEST_BASELINE_DIR} - TEST_SCRIPTS ${CMAKE_CURRENT_SOURCE_DIR}/StaticPlaneCutter.xml) - add_client_tests("pvcrs" - LOAD_PLUGIN "StaticMesh" - BASELINE_DIR ${PARAVIEW_TEST_BASELINE_DIR} - TEST_SCRIPTS ${CMAKE_CURRENT_SOURCE_DIR}/StaticDataSetSurfaceFilter.xml) - add_client_tests("pvcrs" - LOAD_PLUGIN "StaticMesh" - BASELINE_DIR ${PARAVIEW_TEST_BASELINE_DIR} - TEST_SCRIPTS ${CMAKE_CURRENT_SOURCE_DIR}/StaticPlaneCutter.xml) - - if (PARAVIEW_USE_MPI) - add_client_server_tests("pvcs" - LOAD_PLUGIN "StaticMesh" - BASELINE_DIR ${PARAVIEW_TEST_BASELINE_DIR} - TEST_SCRIPTS ${CMAKE_CURRENT_SOURCE_DIR}/StaticGhostCellGenerator.xml) - add_client_render_server_tests("pvcrs" - LOAD_PLUGIN "StaticMesh" - BASELINE_DIR ${PARAVIEW_TEST_BASELINE_DIR} - TEST_SCRIPTS ${CMAKE_CURRENT_SOURCE_DIR}/StaticGhostCellGenerator.xml) - endif() -endif() diff --git a/src/Plugins/StaticMesh/Testing/StaticDataSetSurfaceFilter.xml b/src/Plugins/StaticMesh/Testing/StaticDataSetSurfaceFilter.xml deleted file mode 100644 index 16baa350..00000000 --- a/src/Plugins/StaticMesh/Testing/StaticDataSetSurfaceFilter.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - diff --git a/src/Plugins/StaticMesh/Testing/StaticGhostCellGenerator.xml b/src/Plugins/StaticMesh/Testing/StaticGhostCellGenerator.xml deleted file mode 100644 index 655ea949..00000000 --- a/src/Plugins/StaticMesh/Testing/StaticGhostCellGenerator.xml +++ /dev/null @@ -1,41 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/Plugins/StaticMesh/Testing/StaticPlaneCutter.xml b/src/Plugins/StaticMesh/Testing/StaticPlaneCutter.xml deleted file mode 100644 index 37198c3f..00000000 --- a/src/Plugins/StaticMesh/Testing/StaticPlaneCutter.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/Plugins/StaticMesh/plugin.cmake b/src/Plugins/StaticMesh/plugin.cmake deleted file mode 100644 index fb8142ac..00000000 --- a/src/Plugins/StaticMesh/plugin.cmake +++ /dev/null @@ -1,3 +0,0 @@ -pv_plugin(StaticMesh - DESCRIPTION "Extend unstructured dataset and selected filters to take benefit of static meshes in transient data" - DEFAULT_ENABLED) diff --git a/src/Plugins/StaticMesh/plugin/CMakeLists.txt b/src/Plugins/StaticMesh/plugin/CMakeLists.txt new file mode 100644 index 00000000..940edc2f --- /dev/null +++ b/src/Plugins/StaticMesh/plugin/CMakeLists.txt @@ -0,0 +1,13 @@ + +paraview_add_plugin(StaticMesh + VERSION "1.0" + MODULES StaticMeshModule + MODULE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/StaticMeshModule/vtk.module" + SERVER_MANAGER_XML sources.xml +) + +install(TARGETS StaticMesh + RUNTIME DESTINATION lib/paraview + LIBRARY DESTINATION lib/paraview + ARCHIVE DESTINATION lib/paraview + ) diff --git a/src/Plugins/StaticMesh/plugin/StaticMeshModule/CMakeLists.txt b/src/Plugins/StaticMesh/plugin/StaticMeshModule/CMakeLists.txt new file mode 100644 index 00000000..3069c470 --- /dev/null +++ b/src/Plugins/StaticMesh/plugin/StaticMeshModule/CMakeLists.txt @@ -0,0 +1,23 @@ +set(private_classes + vtkStaticDataSetSurfaceFilter + vtkStaticEnSight6BinaryReader + vtkStaticEnSight6Reader + vtkStaticEnSightGoldBinaryReader + vtkStaticEnSightGoldReader + vtkStaticMeshObjectFactory + vtkStaticPlaneCutter +) + +set(classes + vtkTemporalUGWavelet +) + +if (PARAVIEW_USE_MPI) + list(APPEND private_classes vtkStaticPUnstructuredGridGhostCellsGenerator) +endif() + +vtk_module_add_module(StaticMeshModule + FORCE_STATIC + CLASSES ${classes} + PRIVATE_CLASSES ${private_classes} +) diff --git a/src/Plugins/StaticMesh/plugin/StaticMeshModule/vtk.module b/src/Plugins/StaticMesh/plugin/StaticMeshModule/vtk.module new file mode 100644 index 00000000..d6165617 --- /dev/null +++ b/src/Plugins/StaticMesh/plugin/StaticMeshModule/vtk.module @@ -0,0 +1,18 @@ +NAME + StaticMeshModule +DEPENDS + VTK::CommonCore + VTK::CommonDataModel + VTK::CommonExecutionModel + VTK::FiltersCore + VTK::FiltersModeling + VTK::FiltersGeometry + VTK::FiltersParallelGeometry + VTK::ImagingCore + VTK::IOCore + VTK::IOGeometry + VTK::IOEnSight +PRIVATE_DEPENDS + VTK::CommonMisc + VTK::CommonSystem + VTK::FiltersGeneral diff --git a/src/Plugins/StaticMesh/plugin/StaticMeshModule/vtkStaticDataSetSurfaceFilter.cxx b/src/Plugins/StaticMesh/plugin/StaticMeshModule/vtkStaticDataSetSurfaceFilter.cxx new file mode 100644 index 00000000..429e8905 --- /dev/null +++ b/src/Plugins/StaticMesh/plugin/StaticMeshModule/vtkStaticDataSetSurfaceFilter.cxx @@ -0,0 +1,172 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkStaticDataSetSurfaceFilter.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +#include "vtkStaticDataSetSurfaceFilter.h" + +#include +#include +#include +#include +#include +#include + +vtkStandardNewMacro(vtkStaticDataSetSurfaceFilter); + +//---------------------------------------------------------------------------- +vtkStaticDataSetSurfaceFilter::vtkStaticDataSetSurfaceFilter() +{ + this->InputMeshTime = 0; + this->FilterMTime = 0; +} + +//---------------------------------------------------------------------------- +vtkStaticDataSetSurfaceFilter::~vtkStaticDataSetSurfaceFilter() +{ +} + +//----------------------------------------------------------------------------- +int vtkStaticDataSetSurfaceFilter::UnstructuredGridExecute(vtkDataSet* input, vtkPolyData* output) +{ + vtkUnstructuredGrid* inputUG = vtkUnstructuredGrid::SafeDownCast(input); + if (!inputUG) + { + // Rely on superclass for any input which is not a vtkUnstructuredGrid + return this->Superclass::UnstructuredGridExecute(input, output); + } + + // Check is cache is still valid + if (this->InputMeshTime == inputUG->GetMeshMTime() && this->FilterMTime == this->GetMTime()) + { + // Use cache as base + output->ShallowCopy(this->Cache.Get()); + + // Recover original ids + vtkPointData* outPD = output->GetPointData(); + vtkCellData* outCD = output->GetCellData(); + vtkIdTypeArray* origPointArray = + vtkIdTypeArray::SafeDownCast(outPD->GetArray(this->GetOriginalPointIdsName())); + vtkIdTypeArray* origCellArray = + vtkIdTypeArray::SafeDownCast(outCD->GetArray(this->GetOriginalCellIdsName())); + if (!origPointArray || !origCellArray) + { + vtkErrorMacro( + "OriginalPointIds or OriginalCellIds are missing, cannot use static mesh cache"); + return this->Superclass::UnstructuredGridExecute(input, output); + } + + // Recover input point and cell data + vtkPointData* inPD = input->GetPointData(); + vtkCellData* inCD = input->GetCellData(); + + // Update output point data + vtkIdType* tmpIds = new vtkIdType[origPointArray->GetNumberOfTuples()]; + memcpy(tmpIds, reinterpret_cast(origPointArray->GetVoidPointer(0)), + sizeof(vtkIdType) * origPointArray->GetNumberOfTuples()); + vtkNew pointIds; + pointIds->SetArray(tmpIds, origPointArray->GetNumberOfTuples()); + + // Remove array that have disappeared from input + for (int iArr = outPD->GetNumberOfArrays() - 1; iArr >= 0; iArr--) + { + vtkAbstractArray* inArr = inPD->GetAbstractArray(outPD->GetArrayName(iArr)); + if (!inArr) + { + outPD->RemoveArray(iArr); + } + } + + // Update or create arrays present in input + for (int iArr = 0; iArr < inPD->GetNumberOfArrays(); iArr++) + { + vtkAbstractArray* outArr = outPD->GetAbstractArray(inPD->GetArrayName(iArr)); + if (outArr) + { + inPD->GetAbstractArray(iArr)->GetTuples(pointIds.Get(), outArr); + } + else + { + // New array in input, create it in output + vtkAbstractArray* inArr = inPD->GetAbstractArray(iArr); + outArr = inArr->NewInstance(); + outArr->SetName(inArr->GetName()); + outArr->SetNumberOfComponents(inArr->GetNumberOfComponents()); + outArr->SetNumberOfTuples(output->GetNumberOfPoints()); + inArr->GetTuples(pointIds.Get(), outArr); + outPD->AddArray(outArr); + } + } + + // Update output cell data + tmpIds = new vtkIdType[origCellArray->GetNumberOfTuples()]; + memcpy(tmpIds, reinterpret_cast(origCellArray->GetVoidPointer(0)), + sizeof(vtkIdType) * origCellArray->GetNumberOfTuples()); + vtkNew cellIds; + cellIds->SetArray(tmpIds, origCellArray->GetNumberOfTuples()); + + // Remove array that have disappeared from input + for (int iArr = outCD->GetNumberOfArrays() - 1; iArr >= 0; iArr--) + { + vtkAbstractArray* inArr = inCD->GetAbstractArray(outCD->GetArrayName(iArr)); + if (!inArr) + { + outCD->RemoveArray(iArr); + } + } + + for (int iArr = 0; iArr < inCD->GetNumberOfArrays(); iArr++) + { + vtkAbstractArray* outArr = outCD->GetAbstractArray(inCD->GetArrayName(iArr)); + if (outArr) + { + inCD->GetAbstractArray(iArr)->GetTuples(cellIds.Get(), outArr); + } + else + { + // New array in input, create it in output + vtkAbstractArray* inArr = inCD->GetAbstractArray(iArr); + outArr = inArr->NewInstance(); + outArr->SetName(inArr->GetName()); + outArr->SetNumberOfComponents(inArr->GetNumberOfComponents()); + outArr->SetNumberOfTuples(output->GetNumberOfCells()); + inArr->GetTuples(cellIds.Get(), outArr); + outCD->AddArray(outArr); + } + + } + + // Update output field data + output->GetFieldData()->ShallowCopy(input->GetFieldData()); + return 1; + } + else + { + // Cache is not valid, Execute supercall algorithm + int ret = this->Superclass::UnstructuredGridExecute(input, output); + + // Update the cache with superclass output + this->Cache->ShallowCopy(output); + this->InputMeshTime = inputUG->GetMeshMTime(); + this->FilterMTime = this->GetMTime(); + return ret; + } +} + +//---------------------------------------------------------------------------- +void vtkStaticDataSetSurfaceFilter::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os, indent); + os << indent << "Cache: " << this->Cache << endl; + os << indent << "Input Mesh Time: " << this->InputMeshTime << endl; + os << indent << "Filter mTime: " << this->FilterMTime << endl; +} diff --git a/src/Plugins/StaticMesh/plugin/StaticMeshModule/vtkStaticDataSetSurfaceFilter.h b/src/Plugins/StaticMesh/plugin/StaticMeshModule/vtkStaticDataSetSurfaceFilter.h new file mode 100644 index 00000000..ec885829 --- /dev/null +++ b/src/Plugins/StaticMesh/plugin/StaticMeshModule/vtkStaticDataSetSurfaceFilter.h @@ -0,0 +1,62 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkStaticDataSetSurfaceFilter.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +/** + * @class vtkStaticDataSetSurfaceFilter + * @brief Extract the surface of a dataset, optimized for static unstructured grid + * + * vtkStaticDataSetSurfaceFilter is a specialization of vtkDataSetSurfaceFilter + * that uses a cache to store the surface output and reuses it when associated data + * changes over the time, but the geometry of a unstructured grid is static. + * It is to be noted that, since ParaView use the same surface filter + * for each block of a MultiBlock, this filter is not effective with multiblock + * dataset. + * + * @sa + * vtkStaticMeshObjectFactory +*/ + +#ifndef vtkStaticDataSetSurfaceFilter_h +#define vtkStaticDataSetSurfaceFilter_h + +#include +#include + +class vtkPolyData; + +class vtkStaticDataSetSurfaceFilter : public vtkDataSetSurfaceFilter +{ +public: + static vtkStaticDataSetSurfaceFilter* New(); + typedef vtkDataSetSurfaceFilter + Superclass; // vtkTypeMacro can't be used with a factory built object + void PrintSelf(ostream& os, vtkIndent indent) override; + + int UnstructuredGridExecute(vtkDataSet* input, vtkPolyData* output) override; + +protected: + vtkStaticDataSetSurfaceFilter(); + ~vtkStaticDataSetSurfaceFilter() override; + + vtkNew Cache; + vtkMTimeType InputMeshTime; + vtkMTimeType FilterMTime; + +private: + // Hide these from the user and the compiler. + vtkStaticDataSetSurfaceFilter(const vtkStaticDataSetSurfaceFilter&) = delete; + void operator=(const vtkStaticDataSetSurfaceFilter&) = delete; +}; + +#endif diff --git a/src/Plugins/StaticMesh/plugin/StaticMeshModule/vtkStaticEnSight6BinaryReader.cxx b/src/Plugins/StaticMesh/plugin/StaticMeshModule/vtkStaticEnSight6BinaryReader.cxx new file mode 100644 index 00000000..aef35889 --- /dev/null +++ b/src/Plugins/StaticMesh/plugin/StaticMeshModule/vtkStaticEnSight6BinaryReader.cxx @@ -0,0 +1,275 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkStaticEnSight6BinaryReader.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +#include "vtkStaticEnSight6BinaryReader.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +vtkStandardNewMacro(vtkStaticEnSight6BinaryReader); + +//---------------------------------------------------------------------------- +int vtkStaticEnSight6BinaryReader::RequestData( + vtkInformation *vtkNotUsed(request), + vtkInformationVector **vtkNotUsed(inputVector), + vtkInformationVector *outputVector) +{ + vtkDebugMacro("In execute "); + + vtkInformation *outInfo = outputVector->GetInformationObject(0); + vtkMultiBlockDataSet *output = vtkMultiBlockDataSet::SafeDownCast( + outInfo->Get(vtkDataObject::DATA_OBJECT())); + + int tsLength = + outInfo->Length(vtkStreamingDemandDrivenPipeline::TIME_STEPS()); + double* steps = + outInfo->Get(vtkStreamingDemandDrivenPipeline::TIME_STEPS()); + + this->ActualTimeValue = this->TimeValue; + + // Check if a particular time was requested by the pipeline. + // This overrides the ivar. + if(outInfo->Has(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP()) && tsLength>0) + { + // Get the requested time step. We only support requests of a single time + // step in this reader right now + double requestedTimeStep = + outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP()); + + // find the first time value larger than requested time value + // this logic could be improved + int cnt = 0; + while (cnt < tsLength-1 && steps[cnt] < requestedTimeStep) + { + cnt++; + } + this->ActualTimeValue = steps[cnt]; + } + + vtkDebugMacro("Executing with: " << this->ActualTimeValue); + + if (this->CacheMTime < this->GetMTime()) + { + int i, timeSet, fileSet, timeStep, timeStepInFile, fileNum; + vtkDataArray *times; + vtkIdList *numStepsList, *filenameNumbers; + float newTime; + int numSteps; + char* fileName; + int filenameNum; + + if ( ! this->CaseFileRead) + { + vtkErrorMacro("error reading case file"); + return 0; + } + + this->NumberOfNewOutputs = 0; + this->NumberOfGeometryParts = 0; + if (this->GeometryFileName) + { + timeStep = timeStepInFile = 1; + fileNum = 1; + fileName = new char[strlen(this->GeometryFileName) + 10]; + strcpy(fileName, this->GeometryFileName); + + if (this->UseTimeSets) + { + timeSet = this->TimeSetIds->IsId(this->GeometryTimeSet); + if (timeSet >= 0) + { + times = this->TimeSets->GetItem(timeSet); + this->GeometryTimeValue = times->GetComponent(0, 0); + for (i = 1; i < times->GetNumberOfTuples(); i++) + { + newTime = times->GetComponent(i, 0); + if (newTime <= this->ActualTimeValue && + newTime > this->GeometryTimeValue) + { + this->GeometryTimeValue = newTime; + timeStep++; + timeStepInFile++; + } + } + if (this->TimeSetFileNameNumbers->GetNumberOfItems() > 0) + { + int collectionNum = this->TimeSetsWithFilenameNumbers-> + IsId(this->GeometryTimeSet); + if (collectionNum > -1) + { + filenameNumbers = + this->TimeSetFileNameNumbers->GetItem(collectionNum); + filenameNum = filenameNumbers->GetId(timeStep-1); + if (! this->UseFileSets) + { + this->ReplaceWildcards(fileName, filenameNum); + } + } + } + + // There can only be file sets if there are also time sets. + if (this->UseFileSets) + { + fileSet = this->FileSets->IsId(this->GeometryFileSet); + numStepsList = static_cast(this->FileSetNumberOfSteps-> + GetItemAsObject(fileSet)); + + if (timeStep > numStepsList->GetId(0)) + { + numSteps = numStepsList->GetId(0); + timeStepInFile -= numSteps; + fileNum = 2; + for (i = 1; i < numStepsList->GetNumberOfIds(); i++) + { + numSteps += numStepsList->GetId(i); + if (timeStep > numSteps) + { + fileNum++; + timeStepInFile -= numStepsList->GetId(i); + } + } + } + if (this->FileSetFileNameNumbers->GetNumberOfItems() > 0) + { + int collectionNum = this->FileSetsWithFilenameNumbers-> + IsId(this->GeometryFileSet); + if (collectionNum > -1) + { + filenameNumbers = this->FileSetFileNameNumbers-> + GetItem(collectionNum); + filenameNum = filenameNumbers->GetId(fileNum-1); + this->ReplaceWildcards(fileName, filenameNum); + } + } + } + } + } + + if (!this->ReadGeometryFile(fileName, timeStepInFile, this->Cache)) + { + vtkErrorMacro("error reading geometry file"); + delete [] fileName; + return 0; + } + + delete [] fileName; + } + if (this->MeasuredFileName) + { + timeStep = timeStepInFile = 1; + fileNum = 1; + fileName = new char[strlen(this->MeasuredFileName) + 10]; + strcpy(fileName, this->MeasuredFileName); + + if (this->UseTimeSets) + { + timeSet = this->TimeSetIds->IsId(this->MeasuredTimeSet); + if (timeSet >= 0) + { + times = this->TimeSets->GetItem(timeSet); + this->MeasuredTimeValue = times->GetComponent(0, 0); + for (i = 1; i < times->GetNumberOfTuples(); i++) + { + newTime = times->GetComponent(i, 0); + if (newTime <= this->ActualTimeValue && + newTime > this->MeasuredTimeValue) + { + this->MeasuredTimeValue = newTime; + timeStep++; + timeStepInFile++; + } + } + if (this->TimeSetFileNameNumbers->GetNumberOfItems() > 0) + { + int collectionNum = this->TimeSetsWithFilenameNumbers-> + IsId(this->MeasuredTimeSet); + if (collectionNum > -1) + { + filenameNumbers = this->TimeSetFileNameNumbers-> + GetItem(collectionNum); + filenameNum = filenameNumbers->GetId(timeStep-1); + if (! this->UseFileSets) + { + this->ReplaceWildcards(fileName, filenameNum); + } + } + } + + // There can only be file sets if there are also time sets. + if (this->UseFileSets) + { + fileSet = this->FileSets->IsId(this->MeasuredFileSet); + numStepsList = static_cast(this->FileSetNumberOfSteps-> + GetItemAsObject(fileSet)); + + if (timeStep > numStepsList->GetId(0)) + { + numSteps = numStepsList->GetId(0); + timeStepInFile -= numSteps; + fileNum = 2; + for (i = 1; i < numStepsList->GetNumberOfIds(); i++) + { + numSteps += numStepsList->GetId(i); + if (timeStep > numSteps) + { + fileNum++; + timeStepInFile -= numStepsList->GetId(i); + } + } + } + if (this->FileSetFileNameNumbers->GetNumberOfItems() > 0) + { + int collectionNum = this->FileSetsWithFilenameNumbers-> + IsId(this->MeasuredFileSet); + if (collectionNum > -1) + { + filenameNumbers = this->FileSetFileNameNumbers-> + GetItem(fileSet); + filenameNum = filenameNumbers->GetId(fileNum-1); + this->ReplaceWildcards(fileName, filenameNum); + } + } + } + } + } + if (!this->ReadMeasuredGeometryFile(fileName, timeStepInFile, this->Cache)) + { + vtkErrorMacro("error reading measured geometry file"); + delete [] fileName; + return 0; + } + delete [] fileName; + } + this->CacheMTime.Modified(); + } + output->ShallowCopy(this->Cache); + + if ((this->NumberOfVariables + this->NumberOfComplexVariables) > 0) + { + if (!this->ReadVariableFiles(output)) + { + vtkErrorMacro("error reading variable files"); + return 0; + } + } + + return 1; +} diff --git a/src/Plugins/StaticMesh/plugin/StaticMeshModule/vtkStaticEnSight6BinaryReader.h b/src/Plugins/StaticMesh/plugin/StaticMeshModule/vtkStaticEnSight6BinaryReader.h new file mode 100644 index 00000000..eadf1726 --- /dev/null +++ b/src/Plugins/StaticMesh/plugin/StaticMeshModule/vtkStaticEnSight6BinaryReader.h @@ -0,0 +1,69 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkStaticEnSight6BinaryReader.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +/** + * @class vtkStaticEnSight6BinaryReader + * @brief class to read binary EnSight6 files + * + * vtkStaticEnSight6BinaryReader is a class to read binary EnSight6 files into vtk. + * Because the different parts of the EnSight data can be of various data + * types, this reader produces multiple outputs, one per part in the input + * file. + * All variable information is being stored in field data. The descriptions + * listed in the case file are used as the array names in the field data. + * For complex vector variables, the description is appended with _r (for the + * array of real values) and _i (for the array if imaginary values). Complex + * scalar variables are stored as a single array with 2 components, real and + * imaginary, listed in that order. + * @warning + * You must manually call Update on this reader and then connect the rest + * of the pipeline because (due to the nature of the file format) it is + * not possible to know ahead of time how many outputs you will have or + * what types they will be. + * This reader can only handle static EnSight datasets (both static geometry + * and variables). +*/ + +#ifndef vtkStaticEnSight6BinaryReader_h +#define vtkStaticEnSight6BinaryReader_h + +#include +#include + +class vtkMultiBlockDataSet; + +class vtkStaticEnSight6BinaryReader : public vtkEnSight6BinaryReader +{ +public: + static vtkStaticEnSight6BinaryReader *New(); + vtkTypeMacro(vtkStaticEnSight6BinaryReader, vtkEnSight6BinaryReader); + +protected: + vtkStaticEnSight6BinaryReader() = default; + ~vtkStaticEnSight6BinaryReader() override = default; + + int RequestData(vtkInformation*, + vtkInformationVector**, + vtkInformationVector*) override; + + vtkNew Cache; + vtkTimeStamp CacheMTime; + +private: + vtkStaticEnSight6BinaryReader(const vtkStaticEnSight6BinaryReader&) = delete; + void operator=(const vtkStaticEnSight6BinaryReader&) = delete; +}; + +#endif + diff --git a/src/Plugins/StaticMesh/plugin/StaticMeshModule/vtkStaticEnSight6Reader.cxx b/src/Plugins/StaticMesh/plugin/StaticMeshModule/vtkStaticEnSight6Reader.cxx new file mode 100644 index 00000000..8ad68cd4 --- /dev/null +++ b/src/Plugins/StaticMesh/plugin/StaticMeshModule/vtkStaticEnSight6Reader.cxx @@ -0,0 +1,275 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkStaticEnSight6Reader.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +#include "vtkStaticEnSight6Reader.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +vtkStandardNewMacro(vtkStaticEnSight6Reader); + +//---------------------------------------------------------------------------- +int vtkStaticEnSight6Reader::RequestData( + vtkInformation *vtkNotUsed(request), + vtkInformationVector **vtkNotUsed(inputVector), + vtkInformationVector *outputVector) +{ + vtkDebugMacro("In execute "); + + vtkInformation *outInfo = outputVector->GetInformationObject(0); + vtkMultiBlockDataSet *output = vtkMultiBlockDataSet::SafeDownCast( + outInfo->Get(vtkDataObject::DATA_OBJECT())); + + int tsLength = + outInfo->Length(vtkStreamingDemandDrivenPipeline::TIME_STEPS()); + double* steps = + outInfo->Get(vtkStreamingDemandDrivenPipeline::TIME_STEPS()); + + this->ActualTimeValue = this->TimeValue; + + // Check if a particular time was requested by the pipeline. + // This overrides the ivar. + if(outInfo->Has(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP()) && tsLength>0) + { + // Get the requested time step. We only support requests of a single time + // step in this reader right now + double requestedTimeStep = + outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP()); + + // find the first time value larger than requested time value + // this logic could be improved + int cnt = 0; + while (cnt < tsLength-1 && steps[cnt] < requestedTimeStep) + { + cnt++; + } + this->ActualTimeValue = steps[cnt]; + } + + vtkDebugMacro("Executing with: " << this->ActualTimeValue); + + if (this->CacheMTime < this->GetMTime()) + { + int i, timeSet, fileSet, timeStep, timeStepInFile, fileNum; + vtkDataArray *times; + vtkIdList *numStepsList, *filenameNumbers; + float newTime; + int numSteps; + char* fileName; + int filenameNum; + + if ( ! this->CaseFileRead) + { + vtkErrorMacro("error reading case file"); + return 0; + } + + this->NumberOfNewOutputs = 0; + this->NumberOfGeometryParts = 0; + if (this->GeometryFileName) + { + timeStep = timeStepInFile = 1; + fileNum = 1; + fileName = new char[strlen(this->GeometryFileName) + 10]; + strcpy(fileName, this->GeometryFileName); + + if (this->UseTimeSets) + { + timeSet = this->TimeSetIds->IsId(this->GeometryTimeSet); + if (timeSet >= 0) + { + times = this->TimeSets->GetItem(timeSet); + this->GeometryTimeValue = times->GetComponent(0, 0); + for (i = 1; i < times->GetNumberOfTuples(); i++) + { + newTime = times->GetComponent(i, 0); + if (newTime <= this->ActualTimeValue && + newTime > this->GeometryTimeValue) + { + this->GeometryTimeValue = newTime; + timeStep++; + timeStepInFile++; + } + } + if (this->TimeSetFileNameNumbers->GetNumberOfItems() > 0) + { + int collectionNum = this->TimeSetsWithFilenameNumbers-> + IsId(this->GeometryTimeSet); + if (collectionNum > -1) + { + filenameNumbers = + this->TimeSetFileNameNumbers->GetItem(collectionNum); + filenameNum = filenameNumbers->GetId(timeStep-1); + if (! this->UseFileSets) + { + this->ReplaceWildcards(fileName, filenameNum); + } + } + } + + // There can only be file sets if there are also time sets. + if (this->UseFileSets) + { + fileSet = this->FileSets->IsId(this->GeometryFileSet); + numStepsList = static_cast(this->FileSetNumberOfSteps-> + GetItemAsObject(fileSet)); + + if (timeStep > numStepsList->GetId(0)) + { + numSteps = numStepsList->GetId(0); + timeStepInFile -= numSteps; + fileNum = 2; + for (i = 1; i < numStepsList->GetNumberOfIds(); i++) + { + numSteps += numStepsList->GetId(i); + if (timeStep > numSteps) + { + fileNum++; + timeStepInFile -= numStepsList->GetId(i); + } + } + } + if (this->FileSetFileNameNumbers->GetNumberOfItems() > 0) + { + int collectionNum = this->FileSetsWithFilenameNumbers-> + IsId(this->GeometryFileSet); + if (collectionNum > -1) + { + filenameNumbers = this->FileSetFileNameNumbers-> + GetItem(collectionNum); + filenameNum = filenameNumbers->GetId(fileNum-1); + this->ReplaceWildcards(fileName, filenameNum); + } + } + } + } + } + + if (!this->ReadGeometryFile(fileName, timeStepInFile, this->Cache)) + { + vtkErrorMacro("error reading geometry file"); + delete [] fileName; + return 0; + } + + delete [] fileName; + } + if (this->MeasuredFileName) + { + timeStep = timeStepInFile = 1; + fileNum = 1; + fileName = new char[strlen(this->MeasuredFileName) + 10]; + strcpy(fileName, this->MeasuredFileName); + + if (this->UseTimeSets) + { + timeSet = this->TimeSetIds->IsId(this->MeasuredTimeSet); + if (timeSet >= 0) + { + times = this->TimeSets->GetItem(timeSet); + this->MeasuredTimeValue = times->GetComponent(0, 0); + for (i = 1; i < times->GetNumberOfTuples(); i++) + { + newTime = times->GetComponent(i, 0); + if (newTime <= this->ActualTimeValue && + newTime > this->MeasuredTimeValue) + { + this->MeasuredTimeValue = newTime; + timeStep++; + timeStepInFile++; + } + } + if (this->TimeSetFileNameNumbers->GetNumberOfItems() > 0) + { + int collectionNum = this->TimeSetsWithFilenameNumbers-> + IsId(this->MeasuredTimeSet); + if (collectionNum > -1) + { + filenameNumbers = this->TimeSetFileNameNumbers-> + GetItem(collectionNum); + filenameNum = filenameNumbers->GetId(timeStep-1); + if (! this->UseFileSets) + { + this->ReplaceWildcards(fileName, filenameNum); + } + } + } + + // There can only be file sets if there are also time sets. + if (this->UseFileSets) + { + fileSet = this->FileSets->IsId(this->MeasuredFileSet); + numStepsList = static_cast(this->FileSetNumberOfSteps-> + GetItemAsObject(fileSet)); + + if (timeStep > numStepsList->GetId(0)) + { + numSteps = numStepsList->GetId(0); + timeStepInFile -= numSteps; + fileNum = 2; + for (i = 1; i < numStepsList->GetNumberOfIds(); i++) + { + numSteps += numStepsList->GetId(i); + if (timeStep > numSteps) + { + fileNum++; + timeStepInFile -= numStepsList->GetId(i); + } + } + } + if (this->FileSetFileNameNumbers->GetNumberOfItems() > 0) + { + int collectionNum = this->FileSetsWithFilenameNumbers-> + IsId(this->MeasuredFileSet); + if (collectionNum > -1) + { + filenameNumbers = this->FileSetFileNameNumbers-> + GetItem(fileSet); + filenameNum = filenameNumbers->GetId(fileNum-1); + this->ReplaceWildcards(fileName, filenameNum); + } + } + } + } + } + if (!this->ReadMeasuredGeometryFile(fileName, timeStepInFile, this->Cache)) + { + vtkErrorMacro("error reading measured geometry file"); + delete [] fileName; + return 0; + } + delete [] fileName; + } + this->CacheMTime.Modified(); + } + output->ShallowCopy(this->Cache); + + if ((this->NumberOfVariables + this->NumberOfComplexVariables) > 0) + { + if (!this->ReadVariableFiles(output)) + { + vtkErrorMacro("error reading variable files"); + return 0; + } + } + + return 1; +} diff --git a/src/Plugins/StaticMesh/plugin/StaticMeshModule/vtkStaticEnSight6Reader.h b/src/Plugins/StaticMesh/plugin/StaticMeshModule/vtkStaticEnSight6Reader.h new file mode 100644 index 00000000..30fe1484 --- /dev/null +++ b/src/Plugins/StaticMesh/plugin/StaticMeshModule/vtkStaticEnSight6Reader.h @@ -0,0 +1,69 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkStaticEnSight6Reader.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +/** + * @class vtkStaticEnSight6Reader + * @brief class to read binary EnSight6 files + * + * vtkStaticEnSight6Reader is a class to read binary EnSight6 files into vtk. + * Because the different parts of the EnSight data can be of various data + * types, this reader produces multiple outputs, one per part in the input + * file. + * All variable information is being stored in field data. The descriptions + * listed in the case file are used as the array names in the field data. + * For complex vector variables, the description is appended with _r (for the + * array of real values) and _i (for the array if imaginary values). Complex + * scalar variables are stored as a single array with 2 components, real and + * imaginary, listed in that order. + * @warning + * You must manually call Update on this reader and then connect the rest + * of the pipeline because (due to the nature of the file format) it is + * not possible to know ahead of time how many outputs you will have or + * what types they will be. + * This reader can only handle static EnSight datasets (both static geometry + * and variables). +*/ + +#ifndef vtkStaticEnSight6Reader_h +#define vtkStaticEnSight6Reader_h + +#include +#include + +class vtkMultiBlockDataSet; + +class vtkStaticEnSight6Reader : public vtkEnSight6Reader +{ +public: + static vtkStaticEnSight6Reader *New(); + vtkTypeMacro(vtkStaticEnSight6Reader, vtkEnSight6Reader); + +protected: + vtkStaticEnSight6Reader() = default; + ~vtkStaticEnSight6Reader() override = default; + + int RequestData(vtkInformation*, + vtkInformationVector**, + vtkInformationVector*) override; + + vtkNew Cache; + vtkTimeStamp CacheMTime; + +private: + vtkStaticEnSight6Reader(const vtkStaticEnSight6Reader&) = delete; + void operator=(const vtkStaticEnSight6Reader&) = delete; +}; + +#endif + diff --git a/src/Plugins/StaticMesh/plugin/StaticMeshModule/vtkStaticEnSightGoldBinaryReader.cxx b/src/Plugins/StaticMesh/plugin/StaticMeshModule/vtkStaticEnSightGoldBinaryReader.cxx new file mode 100644 index 00000000..6d336de8 --- /dev/null +++ b/src/Plugins/StaticMesh/plugin/StaticMeshModule/vtkStaticEnSightGoldBinaryReader.cxx @@ -0,0 +1,275 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkStaticEnSightGoldBinaryReader.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +#include "vtkStaticEnSightGoldBinaryReader.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +vtkStandardNewMacro(vtkStaticEnSightGoldBinaryReader); + +//---------------------------------------------------------------------------- +int vtkStaticEnSightGoldBinaryReader::RequestData( + vtkInformation *vtkNotUsed(request), + vtkInformationVector **vtkNotUsed(inputVector), + vtkInformationVector *outputVector) +{ + vtkDebugMacro("In execute "); + + vtkInformation *outInfo = outputVector->GetInformationObject(0); + vtkMultiBlockDataSet *output = vtkMultiBlockDataSet::SafeDownCast( + outInfo->Get(vtkDataObject::DATA_OBJECT())); + + int tsLength = + outInfo->Length(vtkStreamingDemandDrivenPipeline::TIME_STEPS()); + double* steps = + outInfo->Get(vtkStreamingDemandDrivenPipeline::TIME_STEPS()); + + this->ActualTimeValue = this->TimeValue; + + // Check if a particular time was requested by the pipeline. + // This overrides the ivar. + if(outInfo->Has(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP()) && tsLength>0) + { + // Get the requested time step. We only support requests of a single time + // step in this reader right now + double requestedTimeStep = + outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP()); + + // find the first time value larger than requested time value + // this logic could be improved + int cnt = 0; + while (cnt < tsLength-1 && steps[cnt] < requestedTimeStep) + { + cnt++; + } + this->ActualTimeValue = steps[cnt]; + } + + vtkDebugMacro("Executing with: " << this->ActualTimeValue); + + if (this->CacheMTime < this->GetMTime()) + { + int i, timeSet, fileSet, timeStep, timeStepInFile, fileNum; + vtkDataArray *times; + vtkIdList *numStepsList, *filenameNumbers; + float newTime; + int numSteps; + char* fileName; + int filenameNum; + + if ( ! this->CaseFileRead) + { + vtkErrorMacro("error reading case file"); + return 0; + } + + this->NumberOfNewOutputs = 0; + this->NumberOfGeometryParts = 0; + if (this->GeometryFileName) + { + timeStep = timeStepInFile = 1; + fileNum = 1; + fileName = new char[strlen(this->GeometryFileName) + 10]; + strcpy(fileName, this->GeometryFileName); + + if (this->UseTimeSets) + { + timeSet = this->TimeSetIds->IsId(this->GeometryTimeSet); + if (timeSet >= 0) + { + times = this->TimeSets->GetItem(timeSet); + this->GeometryTimeValue = times->GetComponent(0, 0); + for (i = 1; i < times->GetNumberOfTuples(); i++) + { + newTime = times->GetComponent(i, 0); + if (newTime <= this->ActualTimeValue && + newTime > this->GeometryTimeValue) + { + this->GeometryTimeValue = newTime; + timeStep++; + timeStepInFile++; + } + } + if (this->TimeSetFileNameNumbers->GetNumberOfItems() > 0) + { + int collectionNum = this->TimeSetsWithFilenameNumbers-> + IsId(this->GeometryTimeSet); + if (collectionNum > -1) + { + filenameNumbers = + this->TimeSetFileNameNumbers->GetItem(collectionNum); + filenameNum = filenameNumbers->GetId(timeStep-1); + if (! this->UseFileSets) + { + this->ReplaceWildcards(fileName, filenameNum); + } + } + } + + // There can only be file sets if there are also time sets. + if (this->UseFileSets) + { + fileSet = this->FileSets->IsId(this->GeometryFileSet); + numStepsList = static_cast(this->FileSetNumberOfSteps-> + GetItemAsObject(fileSet)); + + if (timeStep > numStepsList->GetId(0)) + { + numSteps = numStepsList->GetId(0); + timeStepInFile -= numSteps; + fileNum = 2; + for (i = 1; i < numStepsList->GetNumberOfIds(); i++) + { + numSteps += numStepsList->GetId(i); + if (timeStep > numSteps) + { + fileNum++; + timeStepInFile -= numStepsList->GetId(i); + } + } + } + if (this->FileSetFileNameNumbers->GetNumberOfItems() > 0) + { + int collectionNum = this->FileSetsWithFilenameNumbers-> + IsId(this->GeometryFileSet); + if (collectionNum > -1) + { + filenameNumbers = this->FileSetFileNameNumbers-> + GetItem(collectionNum); + filenameNum = filenameNumbers->GetId(fileNum-1); + this->ReplaceWildcards(fileName, filenameNum); + } + } + } + } + } + + if (!this->ReadGeometryFile(fileName, timeStepInFile, this->Cache)) + { + vtkErrorMacro("error reading geometry file"); + delete [] fileName; + return 0; + } + + delete [] fileName; + } + if (this->MeasuredFileName) + { + timeStep = timeStepInFile = 1; + fileNum = 1; + fileName = new char[strlen(this->MeasuredFileName) + 10]; + strcpy(fileName, this->MeasuredFileName); + + if (this->UseTimeSets) + { + timeSet = this->TimeSetIds->IsId(this->MeasuredTimeSet); + if (timeSet >= 0) + { + times = this->TimeSets->GetItem(timeSet); + this->MeasuredTimeValue = times->GetComponent(0, 0); + for (i = 1; i < times->GetNumberOfTuples(); i++) + { + newTime = times->GetComponent(i, 0); + if (newTime <= this->ActualTimeValue && + newTime > this->MeasuredTimeValue) + { + this->MeasuredTimeValue = newTime; + timeStep++; + timeStepInFile++; + } + } + if (this->TimeSetFileNameNumbers->GetNumberOfItems() > 0) + { + int collectionNum = this->TimeSetsWithFilenameNumbers-> + IsId(this->MeasuredTimeSet); + if (collectionNum > -1) + { + filenameNumbers = this->TimeSetFileNameNumbers-> + GetItem(collectionNum); + filenameNum = filenameNumbers->GetId(timeStep-1); + if (! this->UseFileSets) + { + this->ReplaceWildcards(fileName, filenameNum); + } + } + } + + // There can only be file sets if there are also time sets. + if (this->UseFileSets) + { + fileSet = this->FileSets->IsId(this->MeasuredFileSet); + numStepsList = static_cast(this->FileSetNumberOfSteps-> + GetItemAsObject(fileSet)); + + if (timeStep > numStepsList->GetId(0)) + { + numSteps = numStepsList->GetId(0); + timeStepInFile -= numSteps; + fileNum = 2; + for (i = 1; i < numStepsList->GetNumberOfIds(); i++) + { + numSteps += numStepsList->GetId(i); + if (timeStep > numSteps) + { + fileNum++; + timeStepInFile -= numStepsList->GetId(i); + } + } + } + if (this->FileSetFileNameNumbers->GetNumberOfItems() > 0) + { + int collectionNum = this->FileSetsWithFilenameNumbers-> + IsId(this->MeasuredFileSet); + if (collectionNum > -1) + { + filenameNumbers = this->FileSetFileNameNumbers-> + GetItem(fileSet); + filenameNum = filenameNumbers->GetId(fileNum-1); + this->ReplaceWildcards(fileName, filenameNum); + } + } + } + } + } + if (!this->ReadMeasuredGeometryFile(fileName, timeStepInFile, this->Cache)) + { + vtkErrorMacro("error reading measured geometry file"); + delete [] fileName; + return 0; + } + delete [] fileName; + } + this->CacheMTime.Modified(); + } + output->ShallowCopy(this->Cache); + + if ((this->NumberOfVariables + this->NumberOfComplexVariables) > 0) + { + if (!this->ReadVariableFiles(output)) + { + vtkErrorMacro("error reading variable files"); + return 0; + } + } + + return 1; +} diff --git a/src/Plugins/StaticMesh/plugin/StaticMeshModule/vtkStaticEnSightGoldBinaryReader.h b/src/Plugins/StaticMesh/plugin/StaticMeshModule/vtkStaticEnSightGoldBinaryReader.h new file mode 100644 index 00000000..e246509a --- /dev/null +++ b/src/Plugins/StaticMesh/plugin/StaticMeshModule/vtkStaticEnSightGoldBinaryReader.h @@ -0,0 +1,69 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkStaticEnSightGoldBinaryReader.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +/** + * @class vtkStaticEnSightGoldBinaryReader + * @brief class to read binary EnSight6 files + * + * vtkStaticEnSightGoldBinaryReader is a class to read binary EnSight6 files into vtk. + * Because the different parts of the EnSight data can be of various data + * types, this reader produces multiple outputs, one per part in the input + * file. + * All variable information is being stored in field data. The descriptions + * listed in the case file are used as the array names in the field data. + * For complex vector variables, the description is appended with _r (for the + * array of real values) and _i (for the array if imaginary values). Complex + * scalar variables are stored as a single array with 2 components, real and + * imaginary, listed in that order. + * @warning + * You must manually call Update on this reader and then connect the rest + * of the pipeline because (due to the nature of the file format) it is + * not possible to know ahead of time how many outputs you will have or + * what types they will be. + * This reader can only handle static EnSight datasets (both static geometry + * and variables). +*/ + +#ifndef vtkStaticEnSightGoldBinaryReader_h +#define vtkStaticEnSightGoldBinaryReader_h + +#include +#include + +class vtkMultiBlockDataSet; + +class vtkStaticEnSightGoldBinaryReader : public vtkEnSightGoldBinaryReader +{ +public: + static vtkStaticEnSightGoldBinaryReader *New(); + vtkTypeMacro(vtkStaticEnSightGoldBinaryReader, vtkEnSightGoldBinaryReader); + +protected: + vtkStaticEnSightGoldBinaryReader() = default; + ~vtkStaticEnSightGoldBinaryReader() override = default; + + int RequestData(vtkInformation*, + vtkInformationVector**, + vtkInformationVector*) override; + + vtkNew Cache; + vtkTimeStamp CacheMTime; + +private: + vtkStaticEnSightGoldBinaryReader(const vtkStaticEnSightGoldBinaryReader&) = delete; + void operator=(const vtkStaticEnSightGoldBinaryReader&) = delete; +}; + +#endif + diff --git a/src/Plugins/StaticMesh/plugin/StaticMeshModule/vtkStaticEnSightGoldReader.cxx b/src/Plugins/StaticMesh/plugin/StaticMeshModule/vtkStaticEnSightGoldReader.cxx new file mode 100644 index 00000000..11a62154 --- /dev/null +++ b/src/Plugins/StaticMesh/plugin/StaticMeshModule/vtkStaticEnSightGoldReader.cxx @@ -0,0 +1,275 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkStaticEnSightGoldReader.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +#include "vtkStaticEnSightGoldReader.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +vtkStandardNewMacro(vtkStaticEnSightGoldReader); + +//---------------------------------------------------------------------------- +int vtkStaticEnSightGoldReader::RequestData( + vtkInformation *vtkNotUsed(request), + vtkInformationVector **vtkNotUsed(inputVector), + vtkInformationVector *outputVector) +{ + vtkDebugMacro("In execute "); + + vtkInformation *outInfo = outputVector->GetInformationObject(0); + vtkMultiBlockDataSet *output = vtkMultiBlockDataSet::SafeDownCast( + outInfo->Get(vtkDataObject::DATA_OBJECT())); + + int tsLength = + outInfo->Length(vtkStreamingDemandDrivenPipeline::TIME_STEPS()); + double* steps = + outInfo->Get(vtkStreamingDemandDrivenPipeline::TIME_STEPS()); + + this->ActualTimeValue = this->TimeValue; + + // Check if a particular time was requested by the pipeline. + // This overrides the ivar. + if(outInfo->Has(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP()) && tsLength>0) + { + // Get the requested time step. We only support requests of a single time + // step in this reader right now + double requestedTimeStep = + outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP()); + + // find the first time value larger than requested time value + // this logic could be improved + int cnt = 0; + while (cnt < tsLength-1 && steps[cnt] < requestedTimeStep) + { + cnt++; + } + this->ActualTimeValue = steps[cnt]; + } + + vtkDebugMacro("Executing with: " << this->ActualTimeValue); + + if (this->CacheMTime < this->GetMTime()) + { + int i, timeSet, fileSet, timeStep, timeStepInFile, fileNum; + vtkDataArray *times; + vtkIdList *numStepsList, *filenameNumbers; + float newTime; + int numSteps; + char* fileName; + int filenameNum; + + if ( ! this->CaseFileRead) + { + vtkErrorMacro("error reading case file"); + return 0; + } + + this->NumberOfNewOutputs = 0; + this->NumberOfGeometryParts = 0; + if (this->GeometryFileName) + { + timeStep = timeStepInFile = 1; + fileNum = 1; + fileName = new char[strlen(this->GeometryFileName) + 10]; + strcpy(fileName, this->GeometryFileName); + + if (this->UseTimeSets) + { + timeSet = this->TimeSetIds->IsId(this->GeometryTimeSet); + if (timeSet >= 0) + { + times = this->TimeSets->GetItem(timeSet); + this->GeometryTimeValue = times->GetComponent(0, 0); + for (i = 1; i < times->GetNumberOfTuples(); i++) + { + newTime = times->GetComponent(i, 0); + if (newTime <= this->ActualTimeValue && + newTime > this->GeometryTimeValue) + { + this->GeometryTimeValue = newTime; + timeStep++; + timeStepInFile++; + } + } + if (this->TimeSetFileNameNumbers->GetNumberOfItems() > 0) + { + int collectionNum = this->TimeSetsWithFilenameNumbers-> + IsId(this->GeometryTimeSet); + if (collectionNum > -1) + { + filenameNumbers = + this->TimeSetFileNameNumbers->GetItem(collectionNum); + filenameNum = filenameNumbers->GetId(timeStep-1); + if (! this->UseFileSets) + { + this->ReplaceWildcards(fileName, filenameNum); + } + } + } + + // There can only be file sets if there are also time sets. + if (this->UseFileSets) + { + fileSet = this->FileSets->IsId(this->GeometryFileSet); + numStepsList = static_cast(this->FileSetNumberOfSteps-> + GetItemAsObject(fileSet)); + + if (timeStep > numStepsList->GetId(0)) + { + numSteps = numStepsList->GetId(0); + timeStepInFile -= numSteps; + fileNum = 2; + for (i = 1; i < numStepsList->GetNumberOfIds(); i++) + { + numSteps += numStepsList->GetId(i); + if (timeStep > numSteps) + { + fileNum++; + timeStepInFile -= numStepsList->GetId(i); + } + } + } + if (this->FileSetFileNameNumbers->GetNumberOfItems() > 0) + { + int collectionNum = this->FileSetsWithFilenameNumbers-> + IsId(this->GeometryFileSet); + if (collectionNum > -1) + { + filenameNumbers = this->FileSetFileNameNumbers-> + GetItem(collectionNum); + filenameNum = filenameNumbers->GetId(fileNum-1); + this->ReplaceWildcards(fileName, filenameNum); + } + } + } + } + } + + if (!this->ReadGeometryFile(fileName, timeStepInFile, this->Cache)) + { + vtkErrorMacro("error reading geometry file"); + delete [] fileName; + return 0; + } + + delete [] fileName; + } + if (this->MeasuredFileName) + { + timeStep = timeStepInFile = 1; + fileNum = 1; + fileName = new char[strlen(this->MeasuredFileName) + 10]; + strcpy(fileName, this->MeasuredFileName); + + if (this->UseTimeSets) + { + timeSet = this->TimeSetIds->IsId(this->MeasuredTimeSet); + if (timeSet >= 0) + { + times = this->TimeSets->GetItem(timeSet); + this->MeasuredTimeValue = times->GetComponent(0, 0); + for (i = 1; i < times->GetNumberOfTuples(); i++) + { + newTime = times->GetComponent(i, 0); + if (newTime <= this->ActualTimeValue && + newTime > this->MeasuredTimeValue) + { + this->MeasuredTimeValue = newTime; + timeStep++; + timeStepInFile++; + } + } + if (this->TimeSetFileNameNumbers->GetNumberOfItems() > 0) + { + int collectionNum = this->TimeSetsWithFilenameNumbers-> + IsId(this->MeasuredTimeSet); + if (collectionNum > -1) + { + filenameNumbers = this->TimeSetFileNameNumbers-> + GetItem(collectionNum); + filenameNum = filenameNumbers->GetId(timeStep-1); + if (! this->UseFileSets) + { + this->ReplaceWildcards(fileName, filenameNum); + } + } + } + + // There can only be file sets if there are also time sets. + if (this->UseFileSets) + { + fileSet = this->FileSets->IsId(this->MeasuredFileSet); + numStepsList = static_cast(this->FileSetNumberOfSteps-> + GetItemAsObject(fileSet)); + + if (timeStep > numStepsList->GetId(0)) + { + numSteps = numStepsList->GetId(0); + timeStepInFile -= numSteps; + fileNum = 2; + for (i = 1; i < numStepsList->GetNumberOfIds(); i++) + { + numSteps += numStepsList->GetId(i); + if (timeStep > numSteps) + { + fileNum++; + timeStepInFile -= numStepsList->GetId(i); + } + } + } + if (this->FileSetFileNameNumbers->GetNumberOfItems() > 0) + { + int collectionNum = this->FileSetsWithFilenameNumbers-> + IsId(this->MeasuredFileSet); + if (collectionNum > -1) + { + filenameNumbers = this->FileSetFileNameNumbers-> + GetItem(fileSet); + filenameNum = filenameNumbers->GetId(fileNum-1); + this->ReplaceWildcards(fileName, filenameNum); + } + } + } + } + } + if (!this->ReadMeasuredGeometryFile(fileName, timeStepInFile, this->Cache)) + { + vtkErrorMacro("error reading measured geometry file"); + delete [] fileName; + return 0; + } + delete [] fileName; + } + this->CacheMTime.Modified(); + } + output->ShallowCopy(this->Cache); + + if ((this->NumberOfVariables + this->NumberOfComplexVariables) > 0) + { + if (!this->ReadVariableFiles(output)) + { + vtkErrorMacro("error reading variable files"); + return 0; + } + } + + return 1; +} diff --git a/src/Plugins/StaticMesh/plugin/StaticMeshModule/vtkStaticEnSightGoldReader.h b/src/Plugins/StaticMesh/plugin/StaticMeshModule/vtkStaticEnSightGoldReader.h new file mode 100644 index 00000000..2be1a028 --- /dev/null +++ b/src/Plugins/StaticMesh/plugin/StaticMeshModule/vtkStaticEnSightGoldReader.h @@ -0,0 +1,69 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkStaticEnSightGoldReader.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +/** + * @class vtkStaticEnSightGoldReader + * @brief class to read binary EnSight6 files + * + * vtkStaticEnSightGoldReader is a class to read binary EnSight6 files into vtk. + * Because the different parts of the EnSight data can be of various data + * types, this reader produces multiple outputs, one per part in the input + * file. + * All variable information is being stored in field data. The descriptions + * listed in the case file are used as the array names in the field data. + * For complex vector variables, the description is appended with _r (for the + * array of real values) and _i (for the array if imaginary values). Complex + * scalar variables are stored as a single array with 2 components, real and + * imaginary, listed in that order. + * @warning + * You must manually call Update on this reader and then connect the rest + * of the pipeline because (due to the nature of the file format) it is + * not possible to know ahead of time how many outputs you will have or + * what types they will be. + * This reader can only handle static EnSight datasets (both static geometry + * and variables). +*/ + +#ifndef vtkStaticEnSightGoldReader_h +#define vtkStaticEnSightGoldReader_h + +#include +#include + +class vtkMultiBlockDataSet; + +class vtkStaticEnSightGoldReader : public vtkEnSightGoldReader +{ +public: + static vtkStaticEnSightGoldReader *New(); + vtkTypeMacro(vtkStaticEnSightGoldReader, vtkEnSightGoldReader); + +protected: + vtkStaticEnSightGoldReader() = default; + ~vtkStaticEnSightGoldReader() override = default; + + int RequestData(vtkInformation*, + vtkInformationVector**, + vtkInformationVector*) override; + + vtkNew Cache; + vtkTimeStamp CacheMTime; + +private: + vtkStaticEnSightGoldReader(const vtkStaticEnSightGoldReader&) = delete; + void operator=(const vtkStaticEnSightGoldReader&) = delete; +}; + +#endif + diff --git a/src/Plugins/StaticMesh/plugin/StaticMeshModule/vtkStaticMeshObjectFactory.cxx b/src/Plugins/StaticMesh/plugin/StaticMeshModule/vtkStaticMeshObjectFactory.cxx new file mode 100644 index 00000000..4c6f1e6e --- /dev/null +++ b/src/Plugins/StaticMesh/plugin/StaticMeshModule/vtkStaticMeshObjectFactory.cxx @@ -0,0 +1,132 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkStaticDataSetSurfaceFilter.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +#include "vtkStaticMeshObjectFactory.h" + +#include +#include +#include +#include + +#include "vtkStaticDataSetSurfaceFilter.h" +#include "vtkStaticEnSight6BinaryReader.h" +#include "vtkStaticEnSight6Reader.h" +#include "vtkStaticEnSightGoldBinaryReader.h" +#include "vtkStaticEnSightGoldReader.h" +#include "vtkStaticPlaneCutter.h" + +#ifdef PARAVIEW_USE_MPI +#include "vtkStaticPUnstructuredGridGhostCellsGenerator.h" +#endif + +vtkStandardNewMacro(vtkStaticMeshObjectFactory); + +VTK_CREATE_CREATE_FUNCTION(vtkStaticDataSetSurfaceFilter); +VTK_CREATE_CREATE_FUNCTION(vtkStaticPlaneCutter); +VTK_CREATE_CREATE_FUNCTION(vtkStaticEnSight6BinaryReader); +VTK_CREATE_CREATE_FUNCTION(vtkStaticEnSight6Reader); +VTK_CREATE_CREATE_FUNCTION(vtkStaticEnSightGoldReader); +VTK_CREATE_CREATE_FUNCTION(vtkStaticEnSightGoldBinaryReader); + +#ifdef PARAVIEW_USE_MPI +VTK_CREATE_CREATE_FUNCTION(vtkStaticPUnstructuredGridGhostCellsGenerator); +#endif + +vtkStaticMeshObjectFactory::vtkStaticMeshObjectFactory() +{ + vtkDebugMacro("Create vtkStaticMeshObjectFactory"); + + this->RegisterOverride("vtkDataSetSurfaceFilter", "vtkStaticDataSetSurfaceFilter", + "StaticDataSetSurfaceFilter", 1, vtkObjectFactoryCreatevtkStaticDataSetSurfaceFilter); + this->RegisterOverride("vtkPlaneCutter", "vtkStaticPlaneCutter", "StaticPlaneCutter", 1, + vtkObjectFactoryCreatevtkStaticPlaneCutter); + this->RegisterOverride("vtkEnSight6BinaryReader", "vtkStaticEnSight6BinaryReader", "StaticEnSight6BinaryReader", 1, + vtkObjectFactoryCreatevtkStaticEnSight6BinaryReader); + this->RegisterOverride("vtkEnSight6Reader", "vtkStaticEnSight6Reader", "StaticEnSight6Reader", 1, + vtkObjectFactoryCreatevtkStaticEnSight6Reader); + this->RegisterOverride("vtkEnSightGoldReader", "vtkStaticEnSight6BinaryReader", "StaticEnSight6BinaryReader", 1, + vtkObjectFactoryCreatevtkStaticEnSightGoldReader); + this->RegisterOverride("vtkEnSightGoldBinaryReader", "vtkStaticEnSightGoldBinaryReader", "StaticEnSightGoldBinaryReader", 1, + vtkObjectFactoryCreatevtkStaticEnSightGoldBinaryReader); + +#ifdef PARAVIEW_USE_MPI + this->RegisterOverride("vtkPUnstructuredGridGhostCellsGenerator", + "vtkStaticPUnstructuredGridGhostCellsGenerator", "StaticPUnstructuredGridGhostCellsGenerator", + 1, vtkObjectFactoryCreatevtkStaticPUnstructuredGridGhostCellsGenerator); +#endif +} + +vtkStaticMeshObjectFactory::~vtkStaticMeshObjectFactory() +{ + vtkDebugMacro("Delete vtkStaticMeshObjectFactory"); +} + +void vtkStaticMeshObjectFactory::PrintSelf(ostream& os, vtkIndent indent) +{ + os << indent << "VTK Static Mesh Extension Factory" << endl; +} + +const char* vtkStaticMeshObjectFactory::GetVTKSourceVersion() +{ + return VTK_SOURCE_VERSION; +} + +const char* vtkStaticMeshObjectFactory::GetDescription() +{ + return "VTK Static Mesh Extension Factory"; +} + +class StaticFactoryInitialize +{ +public: + StaticFactoryInitialize() + { + bool hasStaticPluginFactory = false; + vtkObjectFactoryCollection* collection = vtkObjectFactory::GetRegisteredFactories(); + collection->InitTraversal(); + vtkObjectFactory* f = collection->GetNextItem(); + while (f) + { + if (f->IsA("vtkStaticMeshObjectFactory")) + { + hasStaticPluginFactory = true; + break; + } + f = collection->GetNextItem(); + } + if (!hasStaticPluginFactory) + { + vtkStaticMeshObjectFactory* instance = vtkStaticMeshObjectFactory::New(); + vtkObjectFactory::RegisterFactory(instance); + instance->Delete(); + } + } + + virtual ~StaticFactoryInitialize() + { + vtkObjectFactoryCollection* collection = vtkObjectFactory::GetRegisteredFactories(); + collection->InitTraversal(); + vtkObjectFactory* f; + while ((f = collection->GetNextItem())) + { + if (f->IsA("vtkStaticMeshObjectFactory")) + { + vtkObjectFactory::UnRegisterFactory(f); + break; + } + } + } +}; + +static StaticFactoryInitialize StaticFactory; diff --git a/src/Plugins/StaticMesh/plugin/StaticMeshModule/vtkStaticMeshObjectFactory.h b/src/Plugins/StaticMesh/plugin/StaticMeshModule/vtkStaticMeshObjectFactory.h new file mode 100644 index 00000000..316b9fab --- /dev/null +++ b/src/Plugins/StaticMesh/plugin/StaticMeshModule/vtkStaticMeshObjectFactory.h @@ -0,0 +1,58 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkStaticDataSetSurfaceFilter.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +/** + * @class vtkStaticMeshObjectFactory + * @brief Generate static version of dataset and filter for statix mesh plugin + * + * vtkStaticMeshObjectFactory is a vtk object factory, instantiating static version + * of some dataset and filters. +*/ + +#ifndef vtkStaticMeshObjectFactory_h +#define vtkStaticMeshObjectFactory_h + +#include // Must be included before singletons + +class vtkStaticMeshObjectFactory : public vtkObjectFactory +{ +public: + vtkTypeMacro(vtkStaticMeshObjectFactory, vtkObjectFactory); + static vtkStaticMeshObjectFactory* New(); + void PrintSelf(ostream& os, vtkIndent indent) override; + + /** + * All sub-classes of vtkObjectFactory must return the version of + * VTK they were built with. This should be implemented with the macro + * VTK_SOURCE_VERSION and NOT a call to vtkVersion::GetVTKSourceVersion. + * As the version needs to be compiled into the file as a string constant. + * This is critical to determine possible incompatible dynamic factory loads. + */ + const char* GetVTKSourceVersion() override; + + /** + * Return a descriptive string describing the factory. + */ + const char* GetDescription() override; + +protected: + vtkStaticMeshObjectFactory(); + ~vtkStaticMeshObjectFactory() override; + +private: + vtkStaticMeshObjectFactory(const vtkStaticMeshObjectFactory&) = delete; + void operator=(const vtkStaticMeshObjectFactory&) = delete; +}; + +#endif diff --git a/src/Plugins/StaticMesh/plugin/StaticMeshModule/vtkStaticPUnstructuredGridGhostCellsGenerator.cxx b/src/Plugins/StaticMesh/plugin/StaticMeshModule/vtkStaticPUnstructuredGridGhostCellsGenerator.cxx new file mode 100644 index 00000000..b4ab07c9 --- /dev/null +++ b/src/Plugins/StaticMesh/plugin/StaticMeshModule/vtkStaticPUnstructuredGridGhostCellsGenerator.cxx @@ -0,0 +1,517 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkStaticPUnstructuredGridGhostCellsGenerator.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +#include "vtkStaticPUnstructuredGridGhostCellsGenerator.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static const int SUGGCG_SIZE_EXCHANGE_TAG = 9002; +static const int SUGGCG_DATA_EXCHANGE_TAG = 9003; + +vtkStandardNewMacro(vtkStaticPUnstructuredGridGhostCellsGenerator); + +//---------------------------------------------------------------------------- +vtkStaticPUnstructuredGridGhostCellsGenerator::vtkStaticPUnstructuredGridGhostCellsGenerator() +{ + this->InputMeshTime = 0; + this->FilterMTime = 0; + + vtkMPIController* controller = + vtkMPIController::SafeDownCast(vtkMultiProcessController::GetGlobalController()); + if (controller) + { + // Initialise vtkIdList vectors + this->GhostPointsToReceive.resize(controller->GetNumberOfProcesses()); + this->GhostPointsToSend.resize(controller->GetNumberOfProcesses()); + this->GhostCellsToReceive.resize(controller->GetNumberOfProcesses()); + this->GhostCellsToSend.resize(controller->GetNumberOfProcesses()); + + int nProc = controller->GetNumberOfProcesses(); + + for (int i = 0; i < nProc; i++) + { + this->GhostCellsToReceive[i] = vtkSmartPointer::New(); + this->GhostCellsToSend[i] = vtkSmartPointer::New(); + this->GhostPointsToReceive[i] = vtkSmartPointer::New(); + this->GhostPointsToSend[i] = vtkSmartPointer::New(); + } + } +} + +//---------------------------------------------------------------------------- +vtkStaticPUnstructuredGridGhostCellsGenerator::~vtkStaticPUnstructuredGridGhostCellsGenerator() +{ +} + +//----------------------------------------------------------------------------- +int vtkStaticPUnstructuredGridGhostCellsGenerator::RequestData( + vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector) +{ + // get the inputs and outputs + vtkInformation* inInfo = inputVector[0]->GetInformationObject(0); + vtkInformation* outInfo = outputVector->GetInformationObject(0); + vtkUnstructuredGridBase* input = + vtkUnstructuredGridBase::SafeDownCast(inInfo->Get(vtkDataObject::DATA_OBJECT())); + vtkUnstructuredGrid* output = + vtkUnstructuredGrid::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); + + // Recover the static unstructured grid + vtkUnstructuredGrid* inputUG = vtkUnstructuredGrid::SafeDownCast(input); + if (!inputUG) + { + // For any other types of input, fall back to superclass implementation + return this->Superclass::RequestData(request, inputVector, outputVector); + } + + // Check cache validity + if (this->InputMeshTime == inputUG->GetMeshMTime() && this->FilterMTime == this->GetMTime()) + { + // Cache mesh is up to date, use it to generate data + // Update the cache data + this->UpdateCacheData(input); + + // Copy the updated cache into the output + output->ShallowCopy(this->Cache.Get()); + return 1; + } + else + { + // Add Arrays Ids needed + vtkNew tmpInput; + this->AddIdsArrays(input, tmpInput.Get()); + + // Create an input vector to pass the completed input to the superclass + // RequestData method + vtkNew tmpInputVec; + tmpInputVec->Copy(inputVector[0], 1); + vtkInformation* tmpInInfo = tmpInputVec->GetInformationObject(0); + tmpInInfo->Set(vtkDataObject::DATA_OBJECT(), tmpInput.Get()); + vtkInformationVector* tmpInputVecPt = tmpInputVec.Get(); + int ret = this->Superclass::RequestData(request, &tmpInputVecPt, outputVector); + + // Update the cache with superclass output + this->Cache->ShallowCopy(output); + this->InputMeshTime = inputUG->GetMeshMTime(); + this->FilterMTime = this->GetMTime(); + + this->ProcessGhostIds(); + + return ret; + } +} + +//----------------------------------------------------------------------------- +void vtkStaticPUnstructuredGridGhostCellsGenerator::ProcessGhostIds() +{ + vtkMPIController* controller = + vtkMPIController::SafeDownCast(vtkMultiProcessController::GetGlobalController()); + if (controller) + { + int nProc = controller->GetNumberOfProcesses(); + int rank = controller->GetLocalProcessId(); + + // Clear ghost vectors + for (int i = 0; i < nProc; i++) + { + this->GhostCellsToReceive[i]->SetNumberOfIds(0); + this->GhostCellsToSend[i]->SetNumberOfIds(0); + this->GhostPointsToReceive[i]->SetNumberOfIds(0); + this->GhostPointsToSend[i]->SetNumberOfIds(0); + } + + // Recover all needed data arrays + vtkPointData* cachePD = this->Cache->GetPointData(); + vtkCellData* cacheCD = this->Cache->GetCellData(); + vtkUnsignedCharArray* pointGhostArray = this->Cache->GetPointGhostArray(); + vtkUnsignedCharArray* cellGhostArray = this->Cache->GetCellGhostArray(); + vtkIdTypeArray* pointIds = vtkIdTypeArray::SafeDownCast(cachePD->GetAbstractArray("Ids")); + vtkIdTypeArray* cellIds = vtkIdTypeArray::SafeDownCast(cacheCD->GetAbstractArray("Ids")); + vtkIntArray* pointProcIds = vtkIntArray::SafeDownCast(cachePD->GetAbstractArray("ProcessId")); + vtkIntArray* cellProcIds = vtkIntArray::SafeDownCast(cacheCD->GetAbstractArray("ProcessId")); + if (!pointGhostArray || !pointIds || !pointProcIds || !cellGhostArray || !cellIds || + !cellProcIds) + { + // Sanity check + vtkWarningMacro("Arrays are missing from cache, cache is discarded"); + this->InputMeshTime = 0; + this->FilterMTime = 0; + } + else + { + // Compute list of remote ghost point ids + // and corresponding local point ids. + std::vector > remoteGhostPoints; + remoteGhostPoints.resize(nProc); + for (vtkIdType i = 0; i < pointGhostArray->GetNumberOfTuples(); i++) + { + if (pointGhostArray->GetValue(i) != 0) + { + this->GhostPointsToReceive[pointProcIds->GetValue(i)]->InsertNextId(i); + remoteGhostPoints[pointProcIds->GetValue(i)].push_back(pointIds->GetValue(i)); + } + } + + // Compute list of remote ghost cell ids + // and corresponding local cell ids. + std::vector > remoteGhostCells; + remoteGhostCells.resize(nProc); + for (vtkIdType i = 0; i < cellGhostArray->GetNumberOfTuples(); i++) + { + if (cellGhostArray->GetValue(i) != 0) + { + this->GhostCellsToReceive[cellProcIds->GetValue(i)]->InsertNextId(i); + remoteGhostCells[cellProcIds->GetValue(i)].push_back(cellIds->GetValue(i)); + } + } + + // Send requested ghost point ids to their own rank + vtkMPICommunicator::Request pointSizeReqs[nProc]; + vtkMPICommunicator::Request pointIdsReqs[nProc]; + vtkIdType lengths[nProc]; + for (int i = 0; i < nProc; i++) + { + if (i != rank) + { + lengths[i] = remoteGhostPoints[i].size(); + controller->NoBlockSend(&lengths[i], 1, i, SUGGCG_SIZE_EXCHANGE_TAG, pointSizeReqs[i]); + controller->NoBlockSend(&remoteGhostPoints[i][0], remoteGhostPoints[i].size(), i, + SUGGCG_DATA_EXCHANGE_TAG, pointIdsReqs[i]); + } + } + + // Receive and store requested ghost point ids. + for (int i = 0; i < nProc; i++) + { + if (i != rank) + { + vtkIdType length; + controller->Receive(&length, 1, i, SUGGCG_SIZE_EXCHANGE_TAG); + this->GhostPointsToSend[i]->SetNumberOfIds(length); + controller->Receive( + this->GhostPointsToSend[i]->GetPointer(0), length, i, SUGGCG_DATA_EXCHANGE_TAG); + } + } + controller->Barrier(); + + // Send requested ghost cell ids to their own rank + vtkMPICommunicator::Request cellSizeReqs[nProc]; + vtkMPICommunicator::Request cellIdsReqs[nProc]; + for (int i = 0; i < nProc; i++) + { + if (i != rank) + { + lengths[i] = remoteGhostCells[i].size(); + controller->NoBlockSend(&lengths[i], 1, i, SUGGCG_SIZE_EXCHANGE_TAG, cellSizeReqs[i]); + controller->NoBlockSend( + &remoteGhostCells[i][0], lengths[i], i, SUGGCG_DATA_EXCHANGE_TAG, cellIdsReqs[i]); + } + } + // Receive and store requested ghost cell ids. + for (int i = 0; i < nProc; i++) + { + if (i != rank) + { + vtkIdType length; + controller->Receive(&length, 1, i, SUGGCG_SIZE_EXCHANGE_TAG); + this->GhostCellsToSend[i]->SetNumberOfIds(length); + controller->Receive( + this->GhostCellsToSend[i]->GetPointer(0), length, i, SUGGCG_DATA_EXCHANGE_TAG); + } + } + controller->Barrier(); + } + } +} + +//----------------------------------------------------------------------------- +void vtkStaticPUnstructuredGridGhostCellsGenerator::AddIdsArrays( + vtkDataSet* input, vtkDataSet* output) +{ + vtkDataSet* tmpInput; + tmpInput = input; + vtkNew generateIdScalars; + vtkNew processPointIdScalars; + vtkNew processCellIdScalars; + + // Check for Ids array + vtkAbstractArray* pointIdsTmp = input->GetPointData()->GetAbstractArray("Ids"); + vtkAbstractArray* cellIdsTmp = input->GetCellData()->GetAbstractArray("Ids"); + if (!pointIdsTmp || !cellIdsTmp) + { + // Create Ids array + generateIdScalars->SetInputData(tmpInput); + generateIdScalars->SetIdsArrayName("Ids"); + generateIdScalars->Update(); + tmpInput = generateIdScalars->GetOutput(); + } + + // Check for ProcessId point array + vtkAbstractArray* procIdsTmp = input->GetPointData()->GetAbstractArray("ProcessId"); + if (!procIdsTmp) + { + // Create ProcessId point Array + processPointIdScalars->SetInputData(tmpInput); + processPointIdScalars->SetScalarModeToPointData(); + processPointIdScalars->Update(); + tmpInput = processPointIdScalars->GetOutput(); + } + + // Check for ProcessId Cell Array + procIdsTmp = input->GetCellData()->GetAbstractArray("ProcessId"); + if (!procIdsTmp) + { + // Create ProcessId Cell array + vtkNew processIdScalars; + processCellIdScalars->SetInputData(tmpInput); + processCellIdScalars->SetScalarModeToCellData(); + processCellIdScalars->Update(); + tmpInput = processCellIdScalars->GetOutput(); + } + output->ShallowCopy(tmpInput); +} + +//----------------------------------------------------------------------------- +void vtkStaticPUnstructuredGridGhostCellsGenerator::UpdateCacheData(vtkDataSet* input) +{ + this->UpdateCacheDataWithInput(input); + this->UpdateCacheGhostCellAndPointData(input); +} + +//----------------------------------------------------------------------------- +void vtkStaticPUnstructuredGridGhostCellsGenerator::UpdateCacheDataWithInput(vtkDataSet* input) +{ + // Recover point and cell data + vtkPointData* cachePD = this->Cache->GetPointData(); + vtkCellData* cacheCD = this->Cache->GetCellData(); + vtkPointData* inPD = input->GetPointData(); + vtkCellData* inCD = input->GetCellData(); + + // Update cache point data using input point data + // Of course this concerns only non-ghost points + for (int i = 0; i < inPD->GetNumberOfArrays(); i++) + { + vtkAbstractArray* cacheArray = cachePD->GetAbstractArray(inPD->GetArrayName(i)); + if (cacheArray) + { + cacheArray->InsertTuples(0, input->GetNumberOfPoints(), 0, inPD->GetAbstractArray(i)); + } + } + + // Update cache cell data using input cell data + // Of course this concerns only non-ghost cells + for (int i = 0; i < inCD->GetNumberOfArrays(); i++) + { + vtkAbstractArray* cacheArray = cacheCD->GetAbstractArray(inCD->GetArrayName(i)); + if (cacheArray) + { + cacheArray->InsertTuples(0, input->GetNumberOfCells(), 0, inCD->GetAbstractArray(i)); + } + } + + // Update field data + this->Cache->GetFieldData()->ShallowCopy(input->GetFieldData()); +} + +//----------------------------------------------------------------------------- +void vtkStaticPUnstructuredGridGhostCellsGenerator::UpdateCacheGhostCellAndPointData( + vtkDataSet* input) +{ + vtkMPIController* controller = + vtkMPIController::SafeDownCast(vtkMultiProcessController::GetGlobalController()); + if (controller) + { + vtkPointData* cachePD = this->Cache->GetPointData(); + vtkCellData* cacheCD = this->Cache->GetCellData(); + vtkPointData* inPD = input->GetPointData(); + vtkCellData* inCD = input->GetCellData(); + + int nProc = controller->GetNumberOfProcesses(); + int rank = controller->GetLocalProcessId(); + + vtkNew buffers[nProc]; + vtkIdType lengths[nProc]; + vtkMPICommunicator::Request sizeReqs[nProc]; + vtkMPICommunicator::Request dataReqs[nProc]; + + // For each rank + for (int i = 0; i < nProc; i++) + { + if (i != rank && this->GhostPointsToSend[i]->GetNumberOfIds() > 0) + { + // Prepare ghost points point data to send it as a table + vtkNew ghostPointData; + ghostPointData->CopyAllocate(inPD); + + // Prepare a list of iterating ids and copy all ghost point ids + // for this rank into the ghostPointData + vtkNew dumStaticPointIds; + dumStaticPointIds->SetNumberOfIds(this->GhostPointsToSend[i]->GetNumberOfIds()); + for (vtkIdType id = 0; id < this->GhostPointsToSend[i]->GetNumberOfIds(); id++) + { + dumStaticPointIds->SetId(id, id); + } + ghostPointData->CopyData(inPD, this->GhostPointsToSend[i].Get(), dumStaticPointIds.Get()); + + // Add each point data array to a dumStatic table + vtkNew pointDataTable; + for (int iArr = 0; iArr < ghostPointData->GetNumberOfArrays(); iArr++) + { + pointDataTable->AddColumn(ghostPointData->GetArray(iArr)); + } + + // Marshall the table and transfer it to rank + vtkCommunicator::MarshalDataObject(pointDataTable.Get(), buffers[i].Get()); + lengths[i] = buffers[i]->GetNumberOfTuples(); + controller->NoBlockSend(&lengths[i], 1, i, SUGGCG_SIZE_EXCHANGE_TAG, sizeReqs[i]); + controller->NoBlockSend((char*)(buffers[i]->GetVoidPointer(0)), lengths[i], i, + SUGGCG_DATA_EXCHANGE_TAG, dataReqs[i]); + } + } + // Foe each rank + for (int i = 0; i < nProc; i++) + { + if (i != rank && this->GhostPointsToReceive[i]->GetNumberOfIds() > 0) + { + // Receive dumStatic table to unmarshall + vtkIdType length; + controller->Receive(&length, 1, i, SUGGCG_SIZE_EXCHANGE_TAG); + + vtkNew recvBuffer; + recvBuffer->SetNumberOfValues(length); + controller->Receive( + (char*)(recvBuffer->GetVoidPointer(0)), length, i, SUGGCG_DATA_EXCHANGE_TAG); + vtkNew pointDataTable; + vtkCommunicator::UnMarshalDataObject(recvBuffer.Get(), pointDataTable.Get()); + + // Create a dumStatic iterating point ids + vtkNew dumStaticPointIds; + dumStaticPointIds->SetNumberOfIds(this->GhostPointsToReceive[i]->GetNumberOfIds()); + for (vtkIdType id = 0; id < this->GhostPointsToReceive[i]->GetNumberOfIds(); id++) + { + dumStaticPointIds->SetId(id, id); + } + + // Copy the tuples of each array from the dumStatic table + // into the ghost point data + for (int iArr = 0; iArr < pointDataTable->GetNumberOfColumns(); iArr++) + { + vtkAbstractArray* arrayToCopyIn = + cachePD->GetAbstractArray(pointDataTable->GetColumnName(iArr)); + if (arrayToCopyIn) + { + arrayToCopyIn->InsertTuples(this->GhostPointsToReceive[i].Get(), + dumStaticPointIds.Get(), pointDataTable->GetColumn(iArr)); + } + } + } + } + // Make sure all rank finished + controller->Barrier(); + + for (int i = 0; i < nProc; i++) + { + if (i != rank && this->GhostCellsToSend[i]->GetNumberOfIds() > 0) + { + // Prepare ghost cells data to send it as a table + vtkNew ghostCellData; + ghostCellData->CopyAllocate(inCD); + + // Prepare a list of iterating ids and copy all ghost point ids + // for this rank into the ghostPointData + vtkNew dumStaticCellIds; + dumStaticCellIds->SetNumberOfIds(this->GhostCellsToSend[i]->GetNumberOfIds()); + for (vtkIdType id = 0; id < this->GhostCellsToSend[i]->GetNumberOfIds(); id++) + { + dumStaticCellIds->SetId(id, id); + } + ghostCellData->CopyData(inCD, this->GhostCellsToSend[i].Get(), dumStaticCellIds.Get()); + + // Add each point data array to a dumStatic table + vtkNew cellDataTable; + for (int iArr = 0; iArr < ghostCellData->GetNumberOfArrays(); iArr++) + { + cellDataTable->AddColumn(ghostCellData->GetArray(iArr)); + } + + // Marshall the table and transfer it to rank + vtkCommunicator::MarshalDataObject(cellDataTable.Get(), buffers[i].Get()); + lengths[i] = buffers[i]->GetNumberOfTuples(); + controller->NoBlockSend(&lengths[i], 1, i, SUGGCG_SIZE_EXCHANGE_TAG, sizeReqs[i]); + controller->NoBlockSend((char*)(buffers[i]->GetVoidPointer(0)), lengths[i], i, + SUGGCG_DATA_EXCHANGE_TAG, dataReqs[i]); + } + } + for (int i = 0; i < nProc; i++) + { + if (i != rank && this->GhostCellsToReceive[i]->GetNumberOfIds() > 0) + { + // Receive dumStatic table to unmarshall + vtkIdType length; + controller->Receive(&length, 1, i, SUGGCG_SIZE_EXCHANGE_TAG); + + vtkNew recvBuffer; + recvBuffer->SetNumberOfValues(length); + controller->Receive( + (char*)(recvBuffer->GetVoidPointer(0)), length, i, SUGGCG_DATA_EXCHANGE_TAG); + vtkNew cellDataTable; + vtkCommunicator::UnMarshalDataObject(recvBuffer.Get(), cellDataTable.Get()); + + // Create a dumStatic iterating point ids + vtkNew dumStaticCellIds; + dumStaticCellIds->SetNumberOfIds(this->GhostCellsToReceive[i]->GetNumberOfIds()); + for (vtkIdType id = 0; id < this->GhostCellsToReceive[i]->GetNumberOfIds(); id++) + { + dumStaticCellIds->SetId(id, id); + } + + // Copy the tuples of each array from the dumStatic table + // into the ghost point data + for (int iArr = 0; iArr < cellDataTable->GetNumberOfColumns(); iArr++) + { + vtkAbstractArray* arrayToCopyIn = + cacheCD->GetAbstractArray(cellDataTable->GetColumnName(iArr)); + if (arrayToCopyIn) + { + arrayToCopyIn->InsertTuples(this->GhostCellsToReceive[i].Get(), dumStaticCellIds.Get(), + cellDataTable->GetColumn(iArr)); + } + } + } + } + // Make sure all rank finished + controller->Barrier(); + } +} + +//---------------------------------------------------------------------------- +void vtkStaticPUnstructuredGridGhostCellsGenerator::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os, indent); + os << indent << "Cache: " << this->Cache << endl; + os << indent << "Input Mesh Time: " << this->InputMeshTime << endl; + os << indent << "Filter mTime: " << this->FilterMTime << endl; +} diff --git a/src/Plugins/StaticMesh/plugin/StaticMeshModule/vtkStaticPUnstructuredGridGhostCellsGenerator.h b/src/Plugins/StaticMesh/plugin/StaticMeshModule/vtkStaticPUnstructuredGridGhostCellsGenerator.h new file mode 100644 index 00000000..ecfadfec --- /dev/null +++ b/src/Plugins/StaticMesh/plugin/StaticMeshModule/vtkStaticPUnstructuredGridGhostCellsGenerator.h @@ -0,0 +1,102 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkStaticPUnstructuredGridGhostCellsGenerator.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +/** + * @class vtkStaticPUnstructuredGridGhostCellsGenerator + * @brief StaticMesh aware GhostCellGenerator implementation + * + * This class specialize vtkPUnstructuredGridGhostCellGenerator + * This class improves it by making it static mesh aware. + * The first time this filter is executed it will store its output + * in a cache as well as a list of ghost and point ids to request from other rank + * On next execution, if the mesh is static, it will uses the list of ids to request + * only point and cell data for the ghost point and cell from other + * allowing to update the output without needing to recompute everything + * + * @sa + * vtkPUnstructuredGridGhostCellsGenerator +*/ + +#ifndef vtkStaticPUnstructuredGridGhostCellsGenerator_h +#define vtkStaticPUnstructuredGridGhostCellsGenerator_h + +#include +#include +#include +#include + +#include + +class vtkUnstructuredGrid; + +class vtkStaticPUnstructuredGridGhostCellsGenerator : public vtkPUnstructuredGridGhostCellsGenerator +{ +public: + static vtkStaticPUnstructuredGridGhostCellsGenerator* New(); + typedef vtkPUnstructuredGridGhostCellsGenerator + Superclass; // vtkTypeMacro can't be used with a factory built object + void PrintSelf(ostream& os, vtkIndent indent) override; + + int RequestData(vtkInformation*, vtkInformationVector**, vtkInformationVector*) override; + +protected: + vtkStaticPUnstructuredGridGhostCellsGenerator(); + ~vtkStaticPUnstructuredGridGhostCellsGenerator() override; + + /** + * Check input for "ProcessId" and "Ids" point and cell array, + * If absent, compute and add them. + */ + static void AddIdsArrays(vtkDataSet* input, vtkDataSet* output); + + /** + * Using the Cache, exchange and update ghost point and cell + * ids between ranks + */ + virtual void ProcessGhostIds(); + + /** + * Update cache with input and with ghost cells info + */ + virtual void UpdateCacheData(vtkDataSet* input); + + /** + * Copy input point, cell and field data into cache + */ + virtual void UpdateCacheDataWithInput(vtkDataSet* input); + + /** + * Using Cached ghost cell and points info + * Update ghost cell and point data in cache + * by sending input point and cell data to other ranks + */ + virtual void UpdateCacheGhostCellAndPointData(vtkDataSet* input); + + vtkNew Cache; + vtkMTimeType InputMeshTime; + vtkMTimeType FilterMTime; + + std::vector > GhostCellsToReceive; + std::vector > GhostCellsToSend; + std::vector > GhostPointsToReceive; + std::vector > GhostPointsToSend; + +private: + // Hide these from the user and the compiler. + vtkStaticPUnstructuredGridGhostCellsGenerator( + const vtkStaticPUnstructuredGridGhostCellsGenerator&) = delete; + void operator=(const vtkStaticPUnstructuredGridGhostCellsGenerator&) = delete; +}; + +#endif diff --git a/src/Plugins/StaticMesh/plugin/StaticMeshModule/vtkStaticPlaneCutter.cxx b/src/Plugins/StaticMesh/plugin/StaticMeshModule/vtkStaticPlaneCutter.cxx new file mode 100644 index 00000000..393bddcf --- /dev/null +++ b/src/Plugins/StaticMesh/plugin/StaticMeshModule/vtkStaticPlaneCutter.cxx @@ -0,0 +1,300 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkStaticPlaneCutter.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +#include "vtkStaticPlaneCutter.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +vtkStandardNewMacro(vtkStaticPlaneCutter); + +static const char* IdsArrayName = "__vtkSPC_Ids"; + +//---------------------------------------------------------------------------- +vtkStaticPlaneCutter::vtkStaticPlaneCutter() +{ + this->InputMeshTime = 0; + this->FilterMTime = 0; +} + +//---------------------------------------------------------------------------- +vtkStaticPlaneCutter::~vtkStaticPlaneCutter() +{ + this->ClearWeightsVector(); +} + +//----------------------------------------------------------------------------- +int vtkStaticPlaneCutter::RequestData( + vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector) +{ + // get the inputs and outputs + vtkInformation* inInfo = inputVector[0]->GetInformationObject(0); + vtkInformation* outInfo = outputVector->GetInformationObject(0); + vtkUnstructuredGrid* input = vtkUnstructuredGrid::SafeDownCast(inInfo->Get(vtkDataObject::DATA_OBJECT())); + vtkMultiBlockDataSet* inputMB = vtkMultiBlockDataSet::SafeDownCast(inInfo->Get(vtkDataObject::DATA_OBJECT())); + vtkMultiBlockDataSet* mb = + vtkMultiBlockDataSet::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); + if (!mb) + { + vtkErrorMacro("Ouput information does not contain expected type of data object"); + return 0; + } + + // Recover the first and only block so this works with single block mb + if (inputMB && inputMB->GetNumberOfBlocks() == 1) + { + input = vtkUnstructuredGrid::SafeDownCast(inputMB->GetBlock(0)); + } + + // Recover the static unstructured grid + if (!input) + { + // For any other type of input, fall back to superclass implementation + return this->Superclass::RequestData(request, inputVector, outputVector); + } + + // Check cache validity + if (this->InputMeshTime == input->GetMeshMTime() && this->FilterMTime == this->GetMTime()) + { + // Cache mesh is up to date, use it to generate data + if (this->InterpolateAttributes) + { + // Update the cache data + this->UpdateCacheData(input); + } + + // Copy the updated cache into the output + mb->SetBlock(0, this->Cache.Get()); + return 1; + } + else + { + // Cache is invalid + // Add needed Arrays + vtkNew tmpInput; + this->AddIdsArray(input, tmpInput.Get()); + + // Create an input vector to pass the completed input to the superclass + // RequestData method + vtkNew tmpInputVec; + tmpInputVec->Copy(inputVector[0], 1); + vtkInformation* tmpInInfo = tmpInputVec->GetInformationObject(0); + tmpInInfo->Set(vtkDataObject::DATA_OBJECT(), tmpInput.Get()); + vtkInformationVector* tmpInputVecPt = tmpInputVec.Get(); + int ret = this->Superclass::RequestData(request, &tmpInputVecPt, outputVector); + + // Update the cache with superclass output + vtkMultiPieceDataSet* output = vtkMultiPieceDataSet::SafeDownCast(mb->GetBlock(0)); + if (!output) + { + vtkErrorMacro("Output is not of expected type"); + return 0; + } + + this->Cache->ShallowCopy(output); + this->InputMeshTime = input->GetMeshMTime(); + this->FilterMTime = this->GetMTime(); + + // Compute the ids to be passed from the input to the cache + this->ComputeIds(input); + this->RemoveIdsArray(this->Cache); + return ret; + } +} + +//----------------------------------------------------------------------------- +void vtkStaticPlaneCutter::AddIdsArray(vtkDataSet* input, vtkDataSet* output) +{ + vtkDataSet* tmpInput = input; + vtkNew generateIdScalars; + + // Check for Ids array + vtkIdTypeArray *cellIdsTmp = vtkIdTypeArray::SafeDownCast(input->GetCellData()->GetAbstractArray(IdsArrayName)); + if (!cellIdsTmp) + { + // Create Ids array + generateIdScalars->SetInputData(tmpInput); + generateIdScalars->SetIdsArrayName(IdsArrayName); + generateIdScalars->FieldDataOn(); + generateIdScalars->Update(); + tmpInput = generateIdScalars->GetOutput(); + } + output->ShallowCopy(tmpInput); +} + +//----------------------------------------------------------------------------- +void vtkStaticPlaneCutter::RemoveIdsArray(vtkMultiPieceDataSet* output) +{ + vtkSmartPointer iter; + iter.TakeReference(output->NewIterator()); + iter->SkipEmptyNodesOn(); + for (iter->GoToFirstItem(); !iter->IsDoneWithTraversal(); iter->GoToNextItem()) + { + vtkPolyData* slice = vtkPolyData::SafeDownCast(iter->GetCurrentDataObject()); + if (slice) + { + slice->GetCellData()->RemoveArray(IdsArrayName); + } + } +} + +//----------------------------------------------------------------------------- +void vtkStaticPlaneCutter::ClearWeightsVector() +{ + for(auto& weightsVector : this->WeightsVectorCompo) + { + delete[] weightsVector[0].second; + } + this->WeightsVectorCompo.clear(); +} + +//----------------------------------------------------------------------------- +void vtkStaticPlaneCutter::ComputeIds(vtkUnstructuredGrid* input) +{ + this->CellToCopyFrom.clear(); + this->CellToCopyTo.clear(); + this->ClearWeightsVector(); + + // Iterate over each piece of the multipiece output + vtkNew tmpCell; + vtkSmartPointer iter; + iter.TakeReference(this->Cache->NewIterator()); + iter->SkipEmptyNodesOn(); + for (iter->GoToFirstItem(); !iter->IsDoneWithTraversal(); iter->GoToNextItem()) + { + vtkPolyData* slice = vtkPolyData::SafeDownCast(iter->GetCurrentDataObject()); + vtkIdType sliceNbPoints = slice ? slice->GetNumberOfPoints() : 0; + if (sliceNbPoints > 0) + { + // For each piece, recover the Ids of the cells sliced and the corresponding + // cellId in the slice + vtkSmartPointer cellIdsFrom = vtkSmartPointer::New(); + vtkSmartPointer cellIdsTo = vtkSmartPointer::New(); + this->CellToCopyFrom.push_back(cellIdsFrom); + this->CellToCopyTo.push_back(cellIdsTo); + + vtkIdTypeArray* ids = vtkIdTypeArray::SafeDownCast(slice->GetCellData()->GetArray(IdsArrayName)); + assert(ids); + cellIdsFrom->SetNumberOfIds(ids->GetNumberOfValues()); + cellIdsTo->SetNumberOfIds(ids->GetNumberOfValues()); + for (vtkIdType i = 0; i < ids->GetNumberOfValues(); i++) + { + cellIdsFrom->SetId(i, ids->GetValue(i)); + cellIdsTo->SetId(i, i); + } + if (input->GetPointData()->GetNumberOfArrays() > 0) + { + slice->BuildLinks(); + vtkIdType maxCellSize = input->GetMaxCellSize(); + std::vector, double*>> weightsVector; + weightsVector.resize(sliceNbPoints); + double *allWeights = new double[maxCellSize * sliceNbPoints]; + for (vtkIdType i = 0; i < sliceNbPoints; i++) + { + vtkNew ptIds; + double *weights = &allWeights[maxCellSize * i]; + unsigned short ncells; + vtkIdType *cells; + slice->GetPointCells(i, ncells, cells); + vtkIdType cellId = cellIdsFrom->GetId(cells[0]); + assert(cellId < input->GetNumberOfCells()); + input->GetCell(cellId, tmpCell); + input->GetCellPoints(cellId, ptIds); + double dist, pcoords[3], x[3], p[3]; + int subId = 0; + slice->GetPoint(i, p); + tmpCell->EvaluatePosition(p, x, subId, pcoords, dist, weights); + weightsVector[i] = { ptIds, weights }; + } + this->WeightsVectorCompo.push_back(weightsVector); + } + } + } +} + +//----------------------------------------------------------------------------- +void vtkStaticPlaneCutter::UpdateCacheData(vtkDataSet* input) +{ + // Remove useless FieldData Array from multipiece + // Created by automatic pass data in pipeline + vtkFieldData* mpFieldData = this->Cache->GetFieldData(); + for (int i = mpFieldData->GetNumberOfArrays() - 1; i >= 0; i--) + { + mpFieldData->RemoveArray(i); + } + + // Recover cell/point data + vtkCellData* inCD = input->GetCellData(); + vtkPointData* inPD = input->GetPointData(); + + vtkSmartPointer iter; + iter.TakeReference(this->Cache->NewIterator()); + iter->SkipEmptyNodesOn(); + int blockId = 0; + for (iter->GoToFirstItem(); !iter->IsDoneWithTraversal(); iter->GoToNextItem()) + { + vtkPolyData* slice = vtkPolyData::SafeDownCast(iter->GetCurrentDataObject()); + if (slice && slice->GetNumberOfPoints() > 0) + { + vtkCellData* sliceCD = slice->GetCellData(); + for (int iArr = 0; iArr < inCD->GetNumberOfArrays(); iArr++) + { + // For each array of the cell data of each slice + vtkAbstractArray* arrayToCopyIn = sliceCD->GetAbstractArray(inCD->GetArrayName(iArr)); + if (arrayToCopyIn) + { + // Copy the tuples from the input cell ids to the slice cell ids + arrayToCopyIn->InsertTuples(this->CellToCopyTo[blockId].Get(), this->CellToCopyFrom[blockId].Get(), + inCD->GetAbstractArray(iArr)); + } + } + + if (input->GetPointData()->GetNumberOfArrays() > 0) + { + vtkPointData* slicePD = slice->GetPointData(); + vtkIdType sliceNbPoints = slice->GetNumberOfPoints(); + slicePD->InterpolateAllocate(inPD, sliceNbPoints); + auto& weightsVector = this->WeightsVectorCompo[blockId]; + for (vtkIdType ptIdx = 0; ptIdx < sliceNbPoints; ptIdx++) + { + slicePD->InterpolatePoint(inPD, ptIdx, weightsVector[ptIdx].first, weightsVector[ptIdx].second); + } + } + + // Update field data + slice->GetFieldData()->PassData(input->GetFieldData()); + blockId++; + } + } +} + +//---------------------------------------------------------------------------- +void vtkStaticPlaneCutter::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os, indent); + os << indent << "Cache: " << this->Cache << endl; + os << indent << "Input Mesh Time: " << this->InputMeshTime << endl; + os << indent << "Filter mTime: " << this->FilterMTime << endl; +} diff --git a/src/Plugins/StaticMesh/plugin/StaticMeshModule/vtkStaticPlaneCutter.h b/src/Plugins/StaticMesh/plugin/StaticMeshModule/vtkStaticPlaneCutter.h new file mode 100644 index 00000000..ab473e7c --- /dev/null +++ b/src/Plugins/StaticMesh/plugin/StaticMeshModule/vtkStaticPlaneCutter.h @@ -0,0 +1,91 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkStaticPlaneCutter.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +/** + * @class vtkStaticPlaneCutter + * @brief StaticMesh aware implementation of vtkPlaneCutter vtk vtkUnstructuredGrid + * + * This class specialize vtkPlaneCutter for vtkUnstructuredGrid input. + * It uses a cache when the associated data chage over time but not the geometry. + * In order to be able to update the cache, we keep track of cells ids + * when the cache is computed. + * Contrary to its parent, this class does not interpolate point data, + * only transmit cell data. + * + * + * @sa + * vtkPlaneCutter +*/ + +#ifndef vtkStaticPlaneCutter_h +#define vtkStaticPlaneCutter_h + +#include +#include +#include +#include + +#include + +class vtkMultiPieceDataSet; + +class vtkStaticPlaneCutter : public vtkPlaneCutter +{ +public: + static vtkStaticPlaneCutter* New(); + typedef vtkPlaneCutter Superclass; // vtkTypeMacro can't be used with a factory built object + void PrintSelf(ostream &os, vtkIndent indent) override; + + int RequestData(vtkInformation*, vtkInformationVector**, vtkInformationVector*) override; + +protected: + vtkStaticPlaneCutter(); + ~vtkStaticPlaneCutter() override; + + /** + * Check input for Ids cell array, if absent, compute and add them. + */ + static void AddIdsArray(vtkDataSet* input, vtkDataSet* output); + + /** + * Remove an Ids cell array in all polydata pieces of output + */ + static void RemoveIdsArray(vtkMultiPieceDataSet* output); + + /** + * Update cache point, cell and field data using input + */ + void UpdateCacheData(vtkDataSet* input); + + /** + * Compute the ids and weights to be used when updating the cache later + */ + void ComputeIds(vtkUnstructuredGrid* input); + + void ClearWeightsVector(); + + vtkNew Cache; + std::vector > CellToCopyFrom; + std::vector > CellToCopyTo; + std::vector, double*>>> WeightsVectorCompo; + vtkMTimeType InputMeshTime; + vtkMTimeType FilterMTime; + +private: + // Hide these from the user and the compiler. + vtkStaticPlaneCutter(const vtkStaticPlaneCutter&) = delete; + void operator=(const vtkStaticPlaneCutter&) = delete; +}; + +#endif diff --git a/src/Plugins/StaticMesh/plugin/StaticMeshModule/vtkTemporalUGWavelet.cxx b/src/Plugins/StaticMesh/plugin/StaticMeshModule/vtkTemporalUGWavelet.cxx new file mode 100644 index 00000000..f1f2a007 --- /dev/null +++ b/src/Plugins/StaticMesh/plugin/StaticMeshModule/vtkTemporalUGWavelet.cxx @@ -0,0 +1,140 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkRTAnalyticSource.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +#include "vtkTemporalUGWavelet.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +vtkStandardNewMacro(vtkTemporalUGWavelet); + +// ---------------------------------------------------------------------------- +vtkTemporalUGWavelet::vtkTemporalUGWavelet() +{ + this->Cache = vtkUnstructuredGrid::New(); + this->NumberOfTimeSteps = 10; +} + +// ---------------------------------------------------------------------------- +vtkTemporalUGWavelet::~vtkTemporalUGWavelet() +{ + this->Cache->Delete(); +} + +//---------------------------------------------------------------------------- +int vtkTemporalUGWavelet::FillOutputPortInformation(int vtkNotUsed(port), vtkInformation* info) +{ + info->Set(vtkDataObject::DATA_TYPE_NAME(), "vtkUnstructuredGrid"); + return 1; +} + +// ---------------------------------------------------------------------------- +int vtkTemporalUGWavelet::RequestInformation( + vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector) +{ + vtkInformation* outInfo = outputVector->GetInformationObject(0); + double range[2] = { 0, static_cast(this->NumberOfTimeSteps - 1) }; + outInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_RANGE(), range, 2); + double* outTimes = new double[this->NumberOfTimeSteps]; + for (int i = 0; i < this->NumberOfTimeSteps; i++) + { + outTimes[i] = i; + } + outInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_STEPS(), outTimes, this->NumberOfTimeSteps); + outInfo->Set(CAN_HANDLE_PIECE_REQUEST(), 1); + return Superclass::RequestInformation(request, inputVector, outputVector); +} + +// ---------------------------------------------------------------------------- +int vtkTemporalUGWavelet::RequestData( + vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector) +{ + vtkInformation* outInfo = outputVector->GetInformationObject(0); + vtkUnstructuredGrid* data = vtkUnstructuredGrid::GetData(outInfo); + if (this->CacheMTime < this->GetMTime()) + { + // Create an output vector to recover the output image data + // RequestData method + vtkNew tmpOutputVec; + vtkNew image; + tmpOutputVec->Copy(outputVector, 1); + vtkInformation* tmpOutInfo = tmpOutputVec->GetInformationObject(0); + tmpOutInfo->Set(vtkDataObject::DATA_OBJECT(), image.Get()); + + // Generate wavelet + int ret = this->Superclass::RequestData(request, inputVector, tmpOutputVec.Get()); + if (ret == 0) + { + return ret; + } + + // Transform it to unstructured grid + vtkNew tetra; + tetra->SetInputData(image.Get()); + tetra->Update(); + + // Create the cache + this->Cache->ShallowCopy(tetra->GetOutput()); + this->CacheMTime.Modified(); + } + + // Use the cache + data->ShallowCopy(this->Cache); + + double t = outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP()); + + // Generate tPoint array + vtkIdType nbPoints = data->GetNumberOfPoints(); + vtkNew pointArray; + pointArray->SetName("tPoint"); + pointArray->SetNumberOfValues(nbPoints); + data->GetPointData()->AddArray(pointArray.Get()); + for (vtkIdType i = 0; i < nbPoints; i++) + { + pointArray->SetValue( + i, static_cast(i + t * (nbPoints / this->NumberOfTimeSteps)) % nbPoints); + } + + // Generate tCell array + vtkIdType nbCells = data->GetNumberOfCells(); + vtkNew cellArray; + cellArray->SetName("tCell"); + cellArray->SetNumberOfValues(nbCells); + data->GetCellData()->AddArray(cellArray.Get()); + + for (vtkIdType i = 0; i < nbCells; i++) + { + cellArray->SetValue(i, static_cast(i + t * (nbCells / this->NumberOfTimeSteps)) % nbCells); + } + + return 1; +} + +// ---------------------------------------------------------------------------- +void vtkTemporalUGWavelet::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os, indent); + os << indent << "NumberOfTimeSteps: " << this->NumberOfTimeSteps << endl; +} diff --git a/src/Plugins/StaticMesh/plugin/StaticMeshModule/vtkTemporalUGWavelet.h b/src/Plugins/StaticMesh/plugin/StaticMeshModule/vtkTemporalUGWavelet.h new file mode 100644 index 00000000..2758debd --- /dev/null +++ b/src/Plugins/StaticMesh/plugin/StaticMeshModule/vtkTemporalUGWavelet.h @@ -0,0 +1,67 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkTemporalUGWavelet.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +/** + * @class vtkTemporalUGWavelet + * @brief Create a Temporal Unstructured Grid Wavelet with a static mesh + * + * vtkTemporalUGWavelet specialize vtkRTAnalyticSource to create + * a wavelet converted to vtkUnstructuredGrid, with timesteps. + * The "tPoint" and "tCell" arrays are the only data actually changing over time + * make the output a static mesh with data evolving over time. +*/ + +#ifndef vtkTemporalUGWavelet_h +#define vtkTemporalUGWavelet_h + +#include + +class vtkUnstructuredGrid; + +class vtkTemporalUGWavelet : public vtkRTAnalyticSource +{ +public: + static vtkTemporalUGWavelet* New(); + vtkTypeMacro(vtkTemporalUGWavelet, vtkRTAnalyticSource); + void PrintSelf(ostream& os, vtkIndent indent) override; + + //@{ + /** + * Set/Get the number of time steps. Initial value is 10. + */ + vtkSetMacro(NumberOfTimeSteps, int); + vtkGetMacro(NumberOfTimeSteps, int); + //@} + +protected: + vtkTemporalUGWavelet(); + ~vtkTemporalUGWavelet(); + + int FillOutputPortInformation(int vtkNotUsed(port), vtkInformation* info) override; + + int RequestInformation(vtkInformation* request, vtkInformationVector** inputVector, + vtkInformationVector* outputVector) override; + + int RequestData(vtkInformation*, vtkInformationVector**, vtkInformationVector*) override; + + int NumberOfTimeSteps; + vtkUnstructuredGrid* Cache; + vtkTimeStamp CacheMTime; + +private: + vtkTemporalUGWavelet(const vtkTemporalUGWavelet&) = delete; + void operator=(const vtkTemporalUGWavelet&) = delete; +}; + +#endif diff --git a/src/Plugins/StaticMesh/plugin/paraview.plugin b/src/Plugins/StaticMesh/plugin/paraview.plugin new file mode 100644 index 00000000..cb2645ed --- /dev/null +++ b/src/Plugins/StaticMesh/plugin/paraview.plugin @@ -0,0 +1,11 @@ +NAME + StaticMesh +DESCRIPTION + Extend unstructured dataset and selected filters to take benefit of static meshes in transient data. +REQUIRES_MODULES + VTK::CommonCore + VTK::IOCore + VTK::FiltersCore + VTK::FiltersGeometry + VTK::FiltersParallelGeometry + VTK::IOEnSight diff --git a/src/Plugins/StaticMesh/plugin/sources.xml b/src/Plugins/StaticMesh/plugin/sources.xml new file mode 100644 index 00000000..bf089f3b --- /dev/null +++ b/src/Plugins/StaticMesh/plugin/sources.xml @@ -0,0 +1,154 @@ + + + + + + See Wavelet documentation. + This is a wavelet converted into an unstructured grid. + It contains timesteps yet the mesh is statis over time. + It also contains tPoint and tCell wich are scalar array varying over time. + + + + + + This property specifies the number of time steps + + + + + The six values in this property indicate the X, Y, and Z + extent of the output data. The first two values represent the minimum + and maximum X indices, the next two are the minimum and maximum Y + indices, and the last two are the minimum and maximum Z + indices. + + + + This property specifies the 3D coordinates of the center of + the periodic function (x, y and z in the equation). + + + + This parameter specifies the maximum value (M) of the + function. + + + + This property specifies the natural frequency in X (XF + in the equation). + + + + This property specifies the natural frequency in Y (YF + in the equation). + + + + This property specifies the natural frequency in Z (ZF + in the equation). + + + + This property specifies the wave amplitude in X (XM in + the equation). + + + + This property specifies the wave amplitude in Y (YM in + the equation). + + + + This property specifies the wave amplitude in Z (ZM in + the equation). + + + + This property specifies the standard deviation of the + Gaussian used in computing this function. + + + + This property specifies the rate at which to subsample + the volume. The extent of the dataset in each dimension will be divided + by this value. (See the Whole Extent property.) + + + + + + + + + + + + + + + + + + diff --git a/src/Plugins/StaticMesh/vtkStaticDataSetSurfaceFilter.cxx b/src/Plugins/StaticMesh/vtkStaticDataSetSurfaceFilter.cxx deleted file mode 100644 index 429e8905..00000000 --- a/src/Plugins/StaticMesh/vtkStaticDataSetSurfaceFilter.cxx +++ /dev/null @@ -1,172 +0,0 @@ -/*========================================================================= - - Program: Visualization Toolkit - Module: vtkStaticDataSetSurfaceFilter.cxx - - Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen - All rights reserved. - See Copyright.txt or http://www.kitware.com/Copyright.htm for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notice for more information. - -=========================================================================*/ -#include "vtkStaticDataSetSurfaceFilter.h" - -#include -#include -#include -#include -#include -#include - -vtkStandardNewMacro(vtkStaticDataSetSurfaceFilter); - -//---------------------------------------------------------------------------- -vtkStaticDataSetSurfaceFilter::vtkStaticDataSetSurfaceFilter() -{ - this->InputMeshTime = 0; - this->FilterMTime = 0; -} - -//---------------------------------------------------------------------------- -vtkStaticDataSetSurfaceFilter::~vtkStaticDataSetSurfaceFilter() -{ -} - -//----------------------------------------------------------------------------- -int vtkStaticDataSetSurfaceFilter::UnstructuredGridExecute(vtkDataSet* input, vtkPolyData* output) -{ - vtkUnstructuredGrid* inputUG = vtkUnstructuredGrid::SafeDownCast(input); - if (!inputUG) - { - // Rely on superclass for any input which is not a vtkUnstructuredGrid - return this->Superclass::UnstructuredGridExecute(input, output); - } - - // Check is cache is still valid - if (this->InputMeshTime == inputUG->GetMeshMTime() && this->FilterMTime == this->GetMTime()) - { - // Use cache as base - output->ShallowCopy(this->Cache.Get()); - - // Recover original ids - vtkPointData* outPD = output->GetPointData(); - vtkCellData* outCD = output->GetCellData(); - vtkIdTypeArray* origPointArray = - vtkIdTypeArray::SafeDownCast(outPD->GetArray(this->GetOriginalPointIdsName())); - vtkIdTypeArray* origCellArray = - vtkIdTypeArray::SafeDownCast(outCD->GetArray(this->GetOriginalCellIdsName())); - if (!origPointArray || !origCellArray) - { - vtkErrorMacro( - "OriginalPointIds or OriginalCellIds are missing, cannot use static mesh cache"); - return this->Superclass::UnstructuredGridExecute(input, output); - } - - // Recover input point and cell data - vtkPointData* inPD = input->GetPointData(); - vtkCellData* inCD = input->GetCellData(); - - // Update output point data - vtkIdType* tmpIds = new vtkIdType[origPointArray->GetNumberOfTuples()]; - memcpy(tmpIds, reinterpret_cast(origPointArray->GetVoidPointer(0)), - sizeof(vtkIdType) * origPointArray->GetNumberOfTuples()); - vtkNew pointIds; - pointIds->SetArray(tmpIds, origPointArray->GetNumberOfTuples()); - - // Remove array that have disappeared from input - for (int iArr = outPD->GetNumberOfArrays() - 1; iArr >= 0; iArr--) - { - vtkAbstractArray* inArr = inPD->GetAbstractArray(outPD->GetArrayName(iArr)); - if (!inArr) - { - outPD->RemoveArray(iArr); - } - } - - // Update or create arrays present in input - for (int iArr = 0; iArr < inPD->GetNumberOfArrays(); iArr++) - { - vtkAbstractArray* outArr = outPD->GetAbstractArray(inPD->GetArrayName(iArr)); - if (outArr) - { - inPD->GetAbstractArray(iArr)->GetTuples(pointIds.Get(), outArr); - } - else - { - // New array in input, create it in output - vtkAbstractArray* inArr = inPD->GetAbstractArray(iArr); - outArr = inArr->NewInstance(); - outArr->SetName(inArr->GetName()); - outArr->SetNumberOfComponents(inArr->GetNumberOfComponents()); - outArr->SetNumberOfTuples(output->GetNumberOfPoints()); - inArr->GetTuples(pointIds.Get(), outArr); - outPD->AddArray(outArr); - } - } - - // Update output cell data - tmpIds = new vtkIdType[origCellArray->GetNumberOfTuples()]; - memcpy(tmpIds, reinterpret_cast(origCellArray->GetVoidPointer(0)), - sizeof(vtkIdType) * origCellArray->GetNumberOfTuples()); - vtkNew cellIds; - cellIds->SetArray(tmpIds, origCellArray->GetNumberOfTuples()); - - // Remove array that have disappeared from input - for (int iArr = outCD->GetNumberOfArrays() - 1; iArr >= 0; iArr--) - { - vtkAbstractArray* inArr = inCD->GetAbstractArray(outCD->GetArrayName(iArr)); - if (!inArr) - { - outCD->RemoveArray(iArr); - } - } - - for (int iArr = 0; iArr < inCD->GetNumberOfArrays(); iArr++) - { - vtkAbstractArray* outArr = outCD->GetAbstractArray(inCD->GetArrayName(iArr)); - if (outArr) - { - inCD->GetAbstractArray(iArr)->GetTuples(cellIds.Get(), outArr); - } - else - { - // New array in input, create it in output - vtkAbstractArray* inArr = inCD->GetAbstractArray(iArr); - outArr = inArr->NewInstance(); - outArr->SetName(inArr->GetName()); - outArr->SetNumberOfComponents(inArr->GetNumberOfComponents()); - outArr->SetNumberOfTuples(output->GetNumberOfCells()); - inArr->GetTuples(cellIds.Get(), outArr); - outCD->AddArray(outArr); - } - - } - - // Update output field data - output->GetFieldData()->ShallowCopy(input->GetFieldData()); - return 1; - } - else - { - // Cache is not valid, Execute supercall algorithm - int ret = this->Superclass::UnstructuredGridExecute(input, output); - - // Update the cache with superclass output - this->Cache->ShallowCopy(output); - this->InputMeshTime = inputUG->GetMeshMTime(); - this->FilterMTime = this->GetMTime(); - return ret; - } -} - -//---------------------------------------------------------------------------- -void vtkStaticDataSetSurfaceFilter::PrintSelf(ostream& os, vtkIndent indent) -{ - this->Superclass::PrintSelf(os, indent); - os << indent << "Cache: " << this->Cache << endl; - os << indent << "Input Mesh Time: " << this->InputMeshTime << endl; - os << indent << "Filter mTime: " << this->FilterMTime << endl; -} diff --git a/src/Plugins/StaticMesh/vtkStaticDataSetSurfaceFilter.h b/src/Plugins/StaticMesh/vtkStaticDataSetSurfaceFilter.h deleted file mode 100644 index ec885829..00000000 --- a/src/Plugins/StaticMesh/vtkStaticDataSetSurfaceFilter.h +++ /dev/null @@ -1,62 +0,0 @@ -/*========================================================================= - - Program: Visualization Toolkit - Module: vtkStaticDataSetSurfaceFilter.h - - Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen - All rights reserved. - See Copyright.txt or http://www.kitware.com/Copyright.htm for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notice for more information. - -=========================================================================*/ -/** - * @class vtkStaticDataSetSurfaceFilter - * @brief Extract the surface of a dataset, optimized for static unstructured grid - * - * vtkStaticDataSetSurfaceFilter is a specialization of vtkDataSetSurfaceFilter - * that uses a cache to store the surface output and reuses it when associated data - * changes over the time, but the geometry of a unstructured grid is static. - * It is to be noted that, since ParaView use the same surface filter - * for each block of a MultiBlock, this filter is not effective with multiblock - * dataset. - * - * @sa - * vtkStaticMeshObjectFactory -*/ - -#ifndef vtkStaticDataSetSurfaceFilter_h -#define vtkStaticDataSetSurfaceFilter_h - -#include -#include - -class vtkPolyData; - -class vtkStaticDataSetSurfaceFilter : public vtkDataSetSurfaceFilter -{ -public: - static vtkStaticDataSetSurfaceFilter* New(); - typedef vtkDataSetSurfaceFilter - Superclass; // vtkTypeMacro can't be used with a factory built object - void PrintSelf(ostream& os, vtkIndent indent) override; - - int UnstructuredGridExecute(vtkDataSet* input, vtkPolyData* output) override; - -protected: - vtkStaticDataSetSurfaceFilter(); - ~vtkStaticDataSetSurfaceFilter() override; - - vtkNew Cache; - vtkMTimeType InputMeshTime; - vtkMTimeType FilterMTime; - -private: - // Hide these from the user and the compiler. - vtkStaticDataSetSurfaceFilter(const vtkStaticDataSetSurfaceFilter&) = delete; - void operator=(const vtkStaticDataSetSurfaceFilter&) = delete; -}; - -#endif diff --git a/src/Plugins/StaticMesh/vtkStaticEnSight6BinaryReader.cxx b/src/Plugins/StaticMesh/vtkStaticEnSight6BinaryReader.cxx deleted file mode 100644 index aef35889..00000000 --- a/src/Plugins/StaticMesh/vtkStaticEnSight6BinaryReader.cxx +++ /dev/null @@ -1,275 +0,0 @@ -/*========================================================================= - - Program: Visualization Toolkit - Module: vtkStaticEnSight6BinaryReader.cxx - - Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen - All rights reserved. - See Copyright.txt or http://www.kitware.com/Copyright.htm for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notice for more information. - -=========================================================================*/ -#include "vtkStaticEnSight6BinaryReader.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -vtkStandardNewMacro(vtkStaticEnSight6BinaryReader); - -//---------------------------------------------------------------------------- -int vtkStaticEnSight6BinaryReader::RequestData( - vtkInformation *vtkNotUsed(request), - vtkInformationVector **vtkNotUsed(inputVector), - vtkInformationVector *outputVector) -{ - vtkDebugMacro("In execute "); - - vtkInformation *outInfo = outputVector->GetInformationObject(0); - vtkMultiBlockDataSet *output = vtkMultiBlockDataSet::SafeDownCast( - outInfo->Get(vtkDataObject::DATA_OBJECT())); - - int tsLength = - outInfo->Length(vtkStreamingDemandDrivenPipeline::TIME_STEPS()); - double* steps = - outInfo->Get(vtkStreamingDemandDrivenPipeline::TIME_STEPS()); - - this->ActualTimeValue = this->TimeValue; - - // Check if a particular time was requested by the pipeline. - // This overrides the ivar. - if(outInfo->Has(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP()) && tsLength>0) - { - // Get the requested time step. We only support requests of a single time - // step in this reader right now - double requestedTimeStep = - outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP()); - - // find the first time value larger than requested time value - // this logic could be improved - int cnt = 0; - while (cnt < tsLength-1 && steps[cnt] < requestedTimeStep) - { - cnt++; - } - this->ActualTimeValue = steps[cnt]; - } - - vtkDebugMacro("Executing with: " << this->ActualTimeValue); - - if (this->CacheMTime < this->GetMTime()) - { - int i, timeSet, fileSet, timeStep, timeStepInFile, fileNum; - vtkDataArray *times; - vtkIdList *numStepsList, *filenameNumbers; - float newTime; - int numSteps; - char* fileName; - int filenameNum; - - if ( ! this->CaseFileRead) - { - vtkErrorMacro("error reading case file"); - return 0; - } - - this->NumberOfNewOutputs = 0; - this->NumberOfGeometryParts = 0; - if (this->GeometryFileName) - { - timeStep = timeStepInFile = 1; - fileNum = 1; - fileName = new char[strlen(this->GeometryFileName) + 10]; - strcpy(fileName, this->GeometryFileName); - - if (this->UseTimeSets) - { - timeSet = this->TimeSetIds->IsId(this->GeometryTimeSet); - if (timeSet >= 0) - { - times = this->TimeSets->GetItem(timeSet); - this->GeometryTimeValue = times->GetComponent(0, 0); - for (i = 1; i < times->GetNumberOfTuples(); i++) - { - newTime = times->GetComponent(i, 0); - if (newTime <= this->ActualTimeValue && - newTime > this->GeometryTimeValue) - { - this->GeometryTimeValue = newTime; - timeStep++; - timeStepInFile++; - } - } - if (this->TimeSetFileNameNumbers->GetNumberOfItems() > 0) - { - int collectionNum = this->TimeSetsWithFilenameNumbers-> - IsId(this->GeometryTimeSet); - if (collectionNum > -1) - { - filenameNumbers = - this->TimeSetFileNameNumbers->GetItem(collectionNum); - filenameNum = filenameNumbers->GetId(timeStep-1); - if (! this->UseFileSets) - { - this->ReplaceWildcards(fileName, filenameNum); - } - } - } - - // There can only be file sets if there are also time sets. - if (this->UseFileSets) - { - fileSet = this->FileSets->IsId(this->GeometryFileSet); - numStepsList = static_cast(this->FileSetNumberOfSteps-> - GetItemAsObject(fileSet)); - - if (timeStep > numStepsList->GetId(0)) - { - numSteps = numStepsList->GetId(0); - timeStepInFile -= numSteps; - fileNum = 2; - for (i = 1; i < numStepsList->GetNumberOfIds(); i++) - { - numSteps += numStepsList->GetId(i); - if (timeStep > numSteps) - { - fileNum++; - timeStepInFile -= numStepsList->GetId(i); - } - } - } - if (this->FileSetFileNameNumbers->GetNumberOfItems() > 0) - { - int collectionNum = this->FileSetsWithFilenameNumbers-> - IsId(this->GeometryFileSet); - if (collectionNum > -1) - { - filenameNumbers = this->FileSetFileNameNumbers-> - GetItem(collectionNum); - filenameNum = filenameNumbers->GetId(fileNum-1); - this->ReplaceWildcards(fileName, filenameNum); - } - } - } - } - } - - if (!this->ReadGeometryFile(fileName, timeStepInFile, this->Cache)) - { - vtkErrorMacro("error reading geometry file"); - delete [] fileName; - return 0; - } - - delete [] fileName; - } - if (this->MeasuredFileName) - { - timeStep = timeStepInFile = 1; - fileNum = 1; - fileName = new char[strlen(this->MeasuredFileName) + 10]; - strcpy(fileName, this->MeasuredFileName); - - if (this->UseTimeSets) - { - timeSet = this->TimeSetIds->IsId(this->MeasuredTimeSet); - if (timeSet >= 0) - { - times = this->TimeSets->GetItem(timeSet); - this->MeasuredTimeValue = times->GetComponent(0, 0); - for (i = 1; i < times->GetNumberOfTuples(); i++) - { - newTime = times->GetComponent(i, 0); - if (newTime <= this->ActualTimeValue && - newTime > this->MeasuredTimeValue) - { - this->MeasuredTimeValue = newTime; - timeStep++; - timeStepInFile++; - } - } - if (this->TimeSetFileNameNumbers->GetNumberOfItems() > 0) - { - int collectionNum = this->TimeSetsWithFilenameNumbers-> - IsId(this->MeasuredTimeSet); - if (collectionNum > -1) - { - filenameNumbers = this->TimeSetFileNameNumbers-> - GetItem(collectionNum); - filenameNum = filenameNumbers->GetId(timeStep-1); - if (! this->UseFileSets) - { - this->ReplaceWildcards(fileName, filenameNum); - } - } - } - - // There can only be file sets if there are also time sets. - if (this->UseFileSets) - { - fileSet = this->FileSets->IsId(this->MeasuredFileSet); - numStepsList = static_cast(this->FileSetNumberOfSteps-> - GetItemAsObject(fileSet)); - - if (timeStep > numStepsList->GetId(0)) - { - numSteps = numStepsList->GetId(0); - timeStepInFile -= numSteps; - fileNum = 2; - for (i = 1; i < numStepsList->GetNumberOfIds(); i++) - { - numSteps += numStepsList->GetId(i); - if (timeStep > numSteps) - { - fileNum++; - timeStepInFile -= numStepsList->GetId(i); - } - } - } - if (this->FileSetFileNameNumbers->GetNumberOfItems() > 0) - { - int collectionNum = this->FileSetsWithFilenameNumbers-> - IsId(this->MeasuredFileSet); - if (collectionNum > -1) - { - filenameNumbers = this->FileSetFileNameNumbers-> - GetItem(fileSet); - filenameNum = filenameNumbers->GetId(fileNum-1); - this->ReplaceWildcards(fileName, filenameNum); - } - } - } - } - } - if (!this->ReadMeasuredGeometryFile(fileName, timeStepInFile, this->Cache)) - { - vtkErrorMacro("error reading measured geometry file"); - delete [] fileName; - return 0; - } - delete [] fileName; - } - this->CacheMTime.Modified(); - } - output->ShallowCopy(this->Cache); - - if ((this->NumberOfVariables + this->NumberOfComplexVariables) > 0) - { - if (!this->ReadVariableFiles(output)) - { - vtkErrorMacro("error reading variable files"); - return 0; - } - } - - return 1; -} diff --git a/src/Plugins/StaticMesh/vtkStaticEnSight6BinaryReader.h b/src/Plugins/StaticMesh/vtkStaticEnSight6BinaryReader.h deleted file mode 100644 index eadf1726..00000000 --- a/src/Plugins/StaticMesh/vtkStaticEnSight6BinaryReader.h +++ /dev/null @@ -1,69 +0,0 @@ -/*========================================================================= - - Program: Visualization Toolkit - Module: vtkStaticEnSight6BinaryReader.h - - Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen - All rights reserved. - See Copyright.txt or http://www.kitware.com/Copyright.htm for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notice for more information. - -=========================================================================*/ -/** - * @class vtkStaticEnSight6BinaryReader - * @brief class to read binary EnSight6 files - * - * vtkStaticEnSight6BinaryReader is a class to read binary EnSight6 files into vtk. - * Because the different parts of the EnSight data can be of various data - * types, this reader produces multiple outputs, one per part in the input - * file. - * All variable information is being stored in field data. The descriptions - * listed in the case file are used as the array names in the field data. - * For complex vector variables, the description is appended with _r (for the - * array of real values) and _i (for the array if imaginary values). Complex - * scalar variables are stored as a single array with 2 components, real and - * imaginary, listed in that order. - * @warning - * You must manually call Update on this reader and then connect the rest - * of the pipeline because (due to the nature of the file format) it is - * not possible to know ahead of time how many outputs you will have or - * what types they will be. - * This reader can only handle static EnSight datasets (both static geometry - * and variables). -*/ - -#ifndef vtkStaticEnSight6BinaryReader_h -#define vtkStaticEnSight6BinaryReader_h - -#include -#include - -class vtkMultiBlockDataSet; - -class vtkStaticEnSight6BinaryReader : public vtkEnSight6BinaryReader -{ -public: - static vtkStaticEnSight6BinaryReader *New(); - vtkTypeMacro(vtkStaticEnSight6BinaryReader, vtkEnSight6BinaryReader); - -protected: - vtkStaticEnSight6BinaryReader() = default; - ~vtkStaticEnSight6BinaryReader() override = default; - - int RequestData(vtkInformation*, - vtkInformationVector**, - vtkInformationVector*) override; - - vtkNew Cache; - vtkTimeStamp CacheMTime; - -private: - vtkStaticEnSight6BinaryReader(const vtkStaticEnSight6BinaryReader&) = delete; - void operator=(const vtkStaticEnSight6BinaryReader&) = delete; -}; - -#endif - diff --git a/src/Plugins/StaticMesh/vtkStaticEnSight6Reader.cxx b/src/Plugins/StaticMesh/vtkStaticEnSight6Reader.cxx deleted file mode 100644 index 8ad68cd4..00000000 --- a/src/Plugins/StaticMesh/vtkStaticEnSight6Reader.cxx +++ /dev/null @@ -1,275 +0,0 @@ -/*========================================================================= - - Program: Visualization Toolkit - Module: vtkStaticEnSight6Reader.cxx - - Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen - All rights reserved. - See Copyright.txt or http://www.kitware.com/Copyright.htm for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notice for more information. - -=========================================================================*/ -#include "vtkStaticEnSight6Reader.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -vtkStandardNewMacro(vtkStaticEnSight6Reader); - -//---------------------------------------------------------------------------- -int vtkStaticEnSight6Reader::RequestData( - vtkInformation *vtkNotUsed(request), - vtkInformationVector **vtkNotUsed(inputVector), - vtkInformationVector *outputVector) -{ - vtkDebugMacro("In execute "); - - vtkInformation *outInfo = outputVector->GetInformationObject(0); - vtkMultiBlockDataSet *output = vtkMultiBlockDataSet::SafeDownCast( - outInfo->Get(vtkDataObject::DATA_OBJECT())); - - int tsLength = - outInfo->Length(vtkStreamingDemandDrivenPipeline::TIME_STEPS()); - double* steps = - outInfo->Get(vtkStreamingDemandDrivenPipeline::TIME_STEPS()); - - this->ActualTimeValue = this->TimeValue; - - // Check if a particular time was requested by the pipeline. - // This overrides the ivar. - if(outInfo->Has(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP()) && tsLength>0) - { - // Get the requested time step. We only support requests of a single time - // step in this reader right now - double requestedTimeStep = - outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP()); - - // find the first time value larger than requested time value - // this logic could be improved - int cnt = 0; - while (cnt < tsLength-1 && steps[cnt] < requestedTimeStep) - { - cnt++; - } - this->ActualTimeValue = steps[cnt]; - } - - vtkDebugMacro("Executing with: " << this->ActualTimeValue); - - if (this->CacheMTime < this->GetMTime()) - { - int i, timeSet, fileSet, timeStep, timeStepInFile, fileNum; - vtkDataArray *times; - vtkIdList *numStepsList, *filenameNumbers; - float newTime; - int numSteps; - char* fileName; - int filenameNum; - - if ( ! this->CaseFileRead) - { - vtkErrorMacro("error reading case file"); - return 0; - } - - this->NumberOfNewOutputs = 0; - this->NumberOfGeometryParts = 0; - if (this->GeometryFileName) - { - timeStep = timeStepInFile = 1; - fileNum = 1; - fileName = new char[strlen(this->GeometryFileName) + 10]; - strcpy(fileName, this->GeometryFileName); - - if (this->UseTimeSets) - { - timeSet = this->TimeSetIds->IsId(this->GeometryTimeSet); - if (timeSet >= 0) - { - times = this->TimeSets->GetItem(timeSet); - this->GeometryTimeValue = times->GetComponent(0, 0); - for (i = 1; i < times->GetNumberOfTuples(); i++) - { - newTime = times->GetComponent(i, 0); - if (newTime <= this->ActualTimeValue && - newTime > this->GeometryTimeValue) - { - this->GeometryTimeValue = newTime; - timeStep++; - timeStepInFile++; - } - } - if (this->TimeSetFileNameNumbers->GetNumberOfItems() > 0) - { - int collectionNum = this->TimeSetsWithFilenameNumbers-> - IsId(this->GeometryTimeSet); - if (collectionNum > -1) - { - filenameNumbers = - this->TimeSetFileNameNumbers->GetItem(collectionNum); - filenameNum = filenameNumbers->GetId(timeStep-1); - if (! this->UseFileSets) - { - this->ReplaceWildcards(fileName, filenameNum); - } - } - } - - // There can only be file sets if there are also time sets. - if (this->UseFileSets) - { - fileSet = this->FileSets->IsId(this->GeometryFileSet); - numStepsList = static_cast(this->FileSetNumberOfSteps-> - GetItemAsObject(fileSet)); - - if (timeStep > numStepsList->GetId(0)) - { - numSteps = numStepsList->GetId(0); - timeStepInFile -= numSteps; - fileNum = 2; - for (i = 1; i < numStepsList->GetNumberOfIds(); i++) - { - numSteps += numStepsList->GetId(i); - if (timeStep > numSteps) - { - fileNum++; - timeStepInFile -= numStepsList->GetId(i); - } - } - } - if (this->FileSetFileNameNumbers->GetNumberOfItems() > 0) - { - int collectionNum = this->FileSetsWithFilenameNumbers-> - IsId(this->GeometryFileSet); - if (collectionNum > -1) - { - filenameNumbers = this->FileSetFileNameNumbers-> - GetItem(collectionNum); - filenameNum = filenameNumbers->GetId(fileNum-1); - this->ReplaceWildcards(fileName, filenameNum); - } - } - } - } - } - - if (!this->ReadGeometryFile(fileName, timeStepInFile, this->Cache)) - { - vtkErrorMacro("error reading geometry file"); - delete [] fileName; - return 0; - } - - delete [] fileName; - } - if (this->MeasuredFileName) - { - timeStep = timeStepInFile = 1; - fileNum = 1; - fileName = new char[strlen(this->MeasuredFileName) + 10]; - strcpy(fileName, this->MeasuredFileName); - - if (this->UseTimeSets) - { - timeSet = this->TimeSetIds->IsId(this->MeasuredTimeSet); - if (timeSet >= 0) - { - times = this->TimeSets->GetItem(timeSet); - this->MeasuredTimeValue = times->GetComponent(0, 0); - for (i = 1; i < times->GetNumberOfTuples(); i++) - { - newTime = times->GetComponent(i, 0); - if (newTime <= this->ActualTimeValue && - newTime > this->MeasuredTimeValue) - { - this->MeasuredTimeValue = newTime; - timeStep++; - timeStepInFile++; - } - } - if (this->TimeSetFileNameNumbers->GetNumberOfItems() > 0) - { - int collectionNum = this->TimeSetsWithFilenameNumbers-> - IsId(this->MeasuredTimeSet); - if (collectionNum > -1) - { - filenameNumbers = this->TimeSetFileNameNumbers-> - GetItem(collectionNum); - filenameNum = filenameNumbers->GetId(timeStep-1); - if (! this->UseFileSets) - { - this->ReplaceWildcards(fileName, filenameNum); - } - } - } - - // There can only be file sets if there are also time sets. - if (this->UseFileSets) - { - fileSet = this->FileSets->IsId(this->MeasuredFileSet); - numStepsList = static_cast(this->FileSetNumberOfSteps-> - GetItemAsObject(fileSet)); - - if (timeStep > numStepsList->GetId(0)) - { - numSteps = numStepsList->GetId(0); - timeStepInFile -= numSteps; - fileNum = 2; - for (i = 1; i < numStepsList->GetNumberOfIds(); i++) - { - numSteps += numStepsList->GetId(i); - if (timeStep > numSteps) - { - fileNum++; - timeStepInFile -= numStepsList->GetId(i); - } - } - } - if (this->FileSetFileNameNumbers->GetNumberOfItems() > 0) - { - int collectionNum = this->FileSetsWithFilenameNumbers-> - IsId(this->MeasuredFileSet); - if (collectionNum > -1) - { - filenameNumbers = this->FileSetFileNameNumbers-> - GetItem(fileSet); - filenameNum = filenameNumbers->GetId(fileNum-1); - this->ReplaceWildcards(fileName, filenameNum); - } - } - } - } - } - if (!this->ReadMeasuredGeometryFile(fileName, timeStepInFile, this->Cache)) - { - vtkErrorMacro("error reading measured geometry file"); - delete [] fileName; - return 0; - } - delete [] fileName; - } - this->CacheMTime.Modified(); - } - output->ShallowCopy(this->Cache); - - if ((this->NumberOfVariables + this->NumberOfComplexVariables) > 0) - { - if (!this->ReadVariableFiles(output)) - { - vtkErrorMacro("error reading variable files"); - return 0; - } - } - - return 1; -} diff --git a/src/Plugins/StaticMesh/vtkStaticEnSight6Reader.h b/src/Plugins/StaticMesh/vtkStaticEnSight6Reader.h deleted file mode 100644 index 30fe1484..00000000 --- a/src/Plugins/StaticMesh/vtkStaticEnSight6Reader.h +++ /dev/null @@ -1,69 +0,0 @@ -/*========================================================================= - - Program: Visualization Toolkit - Module: vtkStaticEnSight6Reader.h - - Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen - All rights reserved. - See Copyright.txt or http://www.kitware.com/Copyright.htm for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notice for more information. - -=========================================================================*/ -/** - * @class vtkStaticEnSight6Reader - * @brief class to read binary EnSight6 files - * - * vtkStaticEnSight6Reader is a class to read binary EnSight6 files into vtk. - * Because the different parts of the EnSight data can be of various data - * types, this reader produces multiple outputs, one per part in the input - * file. - * All variable information is being stored in field data. The descriptions - * listed in the case file are used as the array names in the field data. - * For complex vector variables, the description is appended with _r (for the - * array of real values) and _i (for the array if imaginary values). Complex - * scalar variables are stored as a single array with 2 components, real and - * imaginary, listed in that order. - * @warning - * You must manually call Update on this reader and then connect the rest - * of the pipeline because (due to the nature of the file format) it is - * not possible to know ahead of time how many outputs you will have or - * what types they will be. - * This reader can only handle static EnSight datasets (both static geometry - * and variables). -*/ - -#ifndef vtkStaticEnSight6Reader_h -#define vtkStaticEnSight6Reader_h - -#include -#include - -class vtkMultiBlockDataSet; - -class vtkStaticEnSight6Reader : public vtkEnSight6Reader -{ -public: - static vtkStaticEnSight6Reader *New(); - vtkTypeMacro(vtkStaticEnSight6Reader, vtkEnSight6Reader); - -protected: - vtkStaticEnSight6Reader() = default; - ~vtkStaticEnSight6Reader() override = default; - - int RequestData(vtkInformation*, - vtkInformationVector**, - vtkInformationVector*) override; - - vtkNew Cache; - vtkTimeStamp CacheMTime; - -private: - vtkStaticEnSight6Reader(const vtkStaticEnSight6Reader&) = delete; - void operator=(const vtkStaticEnSight6Reader&) = delete; -}; - -#endif - diff --git a/src/Plugins/StaticMesh/vtkStaticEnSightGoldBinaryReader.cxx b/src/Plugins/StaticMesh/vtkStaticEnSightGoldBinaryReader.cxx deleted file mode 100644 index 6d336de8..00000000 --- a/src/Plugins/StaticMesh/vtkStaticEnSightGoldBinaryReader.cxx +++ /dev/null @@ -1,275 +0,0 @@ -/*========================================================================= - - Program: Visualization Toolkit - Module: vtkStaticEnSightGoldBinaryReader.cxx - - Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen - All rights reserved. - See Copyright.txt or http://www.kitware.com/Copyright.htm for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notice for more information. - -=========================================================================*/ -#include "vtkStaticEnSightGoldBinaryReader.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -vtkStandardNewMacro(vtkStaticEnSightGoldBinaryReader); - -//---------------------------------------------------------------------------- -int vtkStaticEnSightGoldBinaryReader::RequestData( - vtkInformation *vtkNotUsed(request), - vtkInformationVector **vtkNotUsed(inputVector), - vtkInformationVector *outputVector) -{ - vtkDebugMacro("In execute "); - - vtkInformation *outInfo = outputVector->GetInformationObject(0); - vtkMultiBlockDataSet *output = vtkMultiBlockDataSet::SafeDownCast( - outInfo->Get(vtkDataObject::DATA_OBJECT())); - - int tsLength = - outInfo->Length(vtkStreamingDemandDrivenPipeline::TIME_STEPS()); - double* steps = - outInfo->Get(vtkStreamingDemandDrivenPipeline::TIME_STEPS()); - - this->ActualTimeValue = this->TimeValue; - - // Check if a particular time was requested by the pipeline. - // This overrides the ivar. - if(outInfo->Has(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP()) && tsLength>0) - { - // Get the requested time step. We only support requests of a single time - // step in this reader right now - double requestedTimeStep = - outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP()); - - // find the first time value larger than requested time value - // this logic could be improved - int cnt = 0; - while (cnt < tsLength-1 && steps[cnt] < requestedTimeStep) - { - cnt++; - } - this->ActualTimeValue = steps[cnt]; - } - - vtkDebugMacro("Executing with: " << this->ActualTimeValue); - - if (this->CacheMTime < this->GetMTime()) - { - int i, timeSet, fileSet, timeStep, timeStepInFile, fileNum; - vtkDataArray *times; - vtkIdList *numStepsList, *filenameNumbers; - float newTime; - int numSteps; - char* fileName; - int filenameNum; - - if ( ! this->CaseFileRead) - { - vtkErrorMacro("error reading case file"); - return 0; - } - - this->NumberOfNewOutputs = 0; - this->NumberOfGeometryParts = 0; - if (this->GeometryFileName) - { - timeStep = timeStepInFile = 1; - fileNum = 1; - fileName = new char[strlen(this->GeometryFileName) + 10]; - strcpy(fileName, this->GeometryFileName); - - if (this->UseTimeSets) - { - timeSet = this->TimeSetIds->IsId(this->GeometryTimeSet); - if (timeSet >= 0) - { - times = this->TimeSets->GetItem(timeSet); - this->GeometryTimeValue = times->GetComponent(0, 0); - for (i = 1; i < times->GetNumberOfTuples(); i++) - { - newTime = times->GetComponent(i, 0); - if (newTime <= this->ActualTimeValue && - newTime > this->GeometryTimeValue) - { - this->GeometryTimeValue = newTime; - timeStep++; - timeStepInFile++; - } - } - if (this->TimeSetFileNameNumbers->GetNumberOfItems() > 0) - { - int collectionNum = this->TimeSetsWithFilenameNumbers-> - IsId(this->GeometryTimeSet); - if (collectionNum > -1) - { - filenameNumbers = - this->TimeSetFileNameNumbers->GetItem(collectionNum); - filenameNum = filenameNumbers->GetId(timeStep-1); - if (! this->UseFileSets) - { - this->ReplaceWildcards(fileName, filenameNum); - } - } - } - - // There can only be file sets if there are also time sets. - if (this->UseFileSets) - { - fileSet = this->FileSets->IsId(this->GeometryFileSet); - numStepsList = static_cast(this->FileSetNumberOfSteps-> - GetItemAsObject(fileSet)); - - if (timeStep > numStepsList->GetId(0)) - { - numSteps = numStepsList->GetId(0); - timeStepInFile -= numSteps; - fileNum = 2; - for (i = 1; i < numStepsList->GetNumberOfIds(); i++) - { - numSteps += numStepsList->GetId(i); - if (timeStep > numSteps) - { - fileNum++; - timeStepInFile -= numStepsList->GetId(i); - } - } - } - if (this->FileSetFileNameNumbers->GetNumberOfItems() > 0) - { - int collectionNum = this->FileSetsWithFilenameNumbers-> - IsId(this->GeometryFileSet); - if (collectionNum > -1) - { - filenameNumbers = this->FileSetFileNameNumbers-> - GetItem(collectionNum); - filenameNum = filenameNumbers->GetId(fileNum-1); - this->ReplaceWildcards(fileName, filenameNum); - } - } - } - } - } - - if (!this->ReadGeometryFile(fileName, timeStepInFile, this->Cache)) - { - vtkErrorMacro("error reading geometry file"); - delete [] fileName; - return 0; - } - - delete [] fileName; - } - if (this->MeasuredFileName) - { - timeStep = timeStepInFile = 1; - fileNum = 1; - fileName = new char[strlen(this->MeasuredFileName) + 10]; - strcpy(fileName, this->MeasuredFileName); - - if (this->UseTimeSets) - { - timeSet = this->TimeSetIds->IsId(this->MeasuredTimeSet); - if (timeSet >= 0) - { - times = this->TimeSets->GetItem(timeSet); - this->MeasuredTimeValue = times->GetComponent(0, 0); - for (i = 1; i < times->GetNumberOfTuples(); i++) - { - newTime = times->GetComponent(i, 0); - if (newTime <= this->ActualTimeValue && - newTime > this->MeasuredTimeValue) - { - this->MeasuredTimeValue = newTime; - timeStep++; - timeStepInFile++; - } - } - if (this->TimeSetFileNameNumbers->GetNumberOfItems() > 0) - { - int collectionNum = this->TimeSetsWithFilenameNumbers-> - IsId(this->MeasuredTimeSet); - if (collectionNum > -1) - { - filenameNumbers = this->TimeSetFileNameNumbers-> - GetItem(collectionNum); - filenameNum = filenameNumbers->GetId(timeStep-1); - if (! this->UseFileSets) - { - this->ReplaceWildcards(fileName, filenameNum); - } - } - } - - // There can only be file sets if there are also time sets. - if (this->UseFileSets) - { - fileSet = this->FileSets->IsId(this->MeasuredFileSet); - numStepsList = static_cast(this->FileSetNumberOfSteps-> - GetItemAsObject(fileSet)); - - if (timeStep > numStepsList->GetId(0)) - { - numSteps = numStepsList->GetId(0); - timeStepInFile -= numSteps; - fileNum = 2; - for (i = 1; i < numStepsList->GetNumberOfIds(); i++) - { - numSteps += numStepsList->GetId(i); - if (timeStep > numSteps) - { - fileNum++; - timeStepInFile -= numStepsList->GetId(i); - } - } - } - if (this->FileSetFileNameNumbers->GetNumberOfItems() > 0) - { - int collectionNum = this->FileSetsWithFilenameNumbers-> - IsId(this->MeasuredFileSet); - if (collectionNum > -1) - { - filenameNumbers = this->FileSetFileNameNumbers-> - GetItem(fileSet); - filenameNum = filenameNumbers->GetId(fileNum-1); - this->ReplaceWildcards(fileName, filenameNum); - } - } - } - } - } - if (!this->ReadMeasuredGeometryFile(fileName, timeStepInFile, this->Cache)) - { - vtkErrorMacro("error reading measured geometry file"); - delete [] fileName; - return 0; - } - delete [] fileName; - } - this->CacheMTime.Modified(); - } - output->ShallowCopy(this->Cache); - - if ((this->NumberOfVariables + this->NumberOfComplexVariables) > 0) - { - if (!this->ReadVariableFiles(output)) - { - vtkErrorMacro("error reading variable files"); - return 0; - } - } - - return 1; -} diff --git a/src/Plugins/StaticMesh/vtkStaticEnSightGoldBinaryReader.h b/src/Plugins/StaticMesh/vtkStaticEnSightGoldBinaryReader.h deleted file mode 100644 index e246509a..00000000 --- a/src/Plugins/StaticMesh/vtkStaticEnSightGoldBinaryReader.h +++ /dev/null @@ -1,69 +0,0 @@ -/*========================================================================= - - Program: Visualization Toolkit - Module: vtkStaticEnSightGoldBinaryReader.h - - Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen - All rights reserved. - See Copyright.txt or http://www.kitware.com/Copyright.htm for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notice for more information. - -=========================================================================*/ -/** - * @class vtkStaticEnSightGoldBinaryReader - * @brief class to read binary EnSight6 files - * - * vtkStaticEnSightGoldBinaryReader is a class to read binary EnSight6 files into vtk. - * Because the different parts of the EnSight data can be of various data - * types, this reader produces multiple outputs, one per part in the input - * file. - * All variable information is being stored in field data. The descriptions - * listed in the case file are used as the array names in the field data. - * For complex vector variables, the description is appended with _r (for the - * array of real values) and _i (for the array if imaginary values). Complex - * scalar variables are stored as a single array with 2 components, real and - * imaginary, listed in that order. - * @warning - * You must manually call Update on this reader and then connect the rest - * of the pipeline because (due to the nature of the file format) it is - * not possible to know ahead of time how many outputs you will have or - * what types they will be. - * This reader can only handle static EnSight datasets (both static geometry - * and variables). -*/ - -#ifndef vtkStaticEnSightGoldBinaryReader_h -#define vtkStaticEnSightGoldBinaryReader_h - -#include -#include - -class vtkMultiBlockDataSet; - -class vtkStaticEnSightGoldBinaryReader : public vtkEnSightGoldBinaryReader -{ -public: - static vtkStaticEnSightGoldBinaryReader *New(); - vtkTypeMacro(vtkStaticEnSightGoldBinaryReader, vtkEnSightGoldBinaryReader); - -protected: - vtkStaticEnSightGoldBinaryReader() = default; - ~vtkStaticEnSightGoldBinaryReader() override = default; - - int RequestData(vtkInformation*, - vtkInformationVector**, - vtkInformationVector*) override; - - vtkNew Cache; - vtkTimeStamp CacheMTime; - -private: - vtkStaticEnSightGoldBinaryReader(const vtkStaticEnSightGoldBinaryReader&) = delete; - void operator=(const vtkStaticEnSightGoldBinaryReader&) = delete; -}; - -#endif - diff --git a/src/Plugins/StaticMesh/vtkStaticEnSightGoldReader.cxx b/src/Plugins/StaticMesh/vtkStaticEnSightGoldReader.cxx deleted file mode 100644 index 11a62154..00000000 --- a/src/Plugins/StaticMesh/vtkStaticEnSightGoldReader.cxx +++ /dev/null @@ -1,275 +0,0 @@ -/*========================================================================= - - Program: Visualization Toolkit - Module: vtkStaticEnSightGoldReader.cxx - - Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen - All rights reserved. - See Copyright.txt or http://www.kitware.com/Copyright.htm for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notice for more information. - -=========================================================================*/ -#include "vtkStaticEnSightGoldReader.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -vtkStandardNewMacro(vtkStaticEnSightGoldReader); - -//---------------------------------------------------------------------------- -int vtkStaticEnSightGoldReader::RequestData( - vtkInformation *vtkNotUsed(request), - vtkInformationVector **vtkNotUsed(inputVector), - vtkInformationVector *outputVector) -{ - vtkDebugMacro("In execute "); - - vtkInformation *outInfo = outputVector->GetInformationObject(0); - vtkMultiBlockDataSet *output = vtkMultiBlockDataSet::SafeDownCast( - outInfo->Get(vtkDataObject::DATA_OBJECT())); - - int tsLength = - outInfo->Length(vtkStreamingDemandDrivenPipeline::TIME_STEPS()); - double* steps = - outInfo->Get(vtkStreamingDemandDrivenPipeline::TIME_STEPS()); - - this->ActualTimeValue = this->TimeValue; - - // Check if a particular time was requested by the pipeline. - // This overrides the ivar. - if(outInfo->Has(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP()) && tsLength>0) - { - // Get the requested time step. We only support requests of a single time - // step in this reader right now - double requestedTimeStep = - outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP()); - - // find the first time value larger than requested time value - // this logic could be improved - int cnt = 0; - while (cnt < tsLength-1 && steps[cnt] < requestedTimeStep) - { - cnt++; - } - this->ActualTimeValue = steps[cnt]; - } - - vtkDebugMacro("Executing with: " << this->ActualTimeValue); - - if (this->CacheMTime < this->GetMTime()) - { - int i, timeSet, fileSet, timeStep, timeStepInFile, fileNum; - vtkDataArray *times; - vtkIdList *numStepsList, *filenameNumbers; - float newTime; - int numSteps; - char* fileName; - int filenameNum; - - if ( ! this->CaseFileRead) - { - vtkErrorMacro("error reading case file"); - return 0; - } - - this->NumberOfNewOutputs = 0; - this->NumberOfGeometryParts = 0; - if (this->GeometryFileName) - { - timeStep = timeStepInFile = 1; - fileNum = 1; - fileName = new char[strlen(this->GeometryFileName) + 10]; - strcpy(fileName, this->GeometryFileName); - - if (this->UseTimeSets) - { - timeSet = this->TimeSetIds->IsId(this->GeometryTimeSet); - if (timeSet >= 0) - { - times = this->TimeSets->GetItem(timeSet); - this->GeometryTimeValue = times->GetComponent(0, 0); - for (i = 1; i < times->GetNumberOfTuples(); i++) - { - newTime = times->GetComponent(i, 0); - if (newTime <= this->ActualTimeValue && - newTime > this->GeometryTimeValue) - { - this->GeometryTimeValue = newTime; - timeStep++; - timeStepInFile++; - } - } - if (this->TimeSetFileNameNumbers->GetNumberOfItems() > 0) - { - int collectionNum = this->TimeSetsWithFilenameNumbers-> - IsId(this->GeometryTimeSet); - if (collectionNum > -1) - { - filenameNumbers = - this->TimeSetFileNameNumbers->GetItem(collectionNum); - filenameNum = filenameNumbers->GetId(timeStep-1); - if (! this->UseFileSets) - { - this->ReplaceWildcards(fileName, filenameNum); - } - } - } - - // There can only be file sets if there are also time sets. - if (this->UseFileSets) - { - fileSet = this->FileSets->IsId(this->GeometryFileSet); - numStepsList = static_cast(this->FileSetNumberOfSteps-> - GetItemAsObject(fileSet)); - - if (timeStep > numStepsList->GetId(0)) - { - numSteps = numStepsList->GetId(0); - timeStepInFile -= numSteps; - fileNum = 2; - for (i = 1; i < numStepsList->GetNumberOfIds(); i++) - { - numSteps += numStepsList->GetId(i); - if (timeStep > numSteps) - { - fileNum++; - timeStepInFile -= numStepsList->GetId(i); - } - } - } - if (this->FileSetFileNameNumbers->GetNumberOfItems() > 0) - { - int collectionNum = this->FileSetsWithFilenameNumbers-> - IsId(this->GeometryFileSet); - if (collectionNum > -1) - { - filenameNumbers = this->FileSetFileNameNumbers-> - GetItem(collectionNum); - filenameNum = filenameNumbers->GetId(fileNum-1); - this->ReplaceWildcards(fileName, filenameNum); - } - } - } - } - } - - if (!this->ReadGeometryFile(fileName, timeStepInFile, this->Cache)) - { - vtkErrorMacro("error reading geometry file"); - delete [] fileName; - return 0; - } - - delete [] fileName; - } - if (this->MeasuredFileName) - { - timeStep = timeStepInFile = 1; - fileNum = 1; - fileName = new char[strlen(this->MeasuredFileName) + 10]; - strcpy(fileName, this->MeasuredFileName); - - if (this->UseTimeSets) - { - timeSet = this->TimeSetIds->IsId(this->MeasuredTimeSet); - if (timeSet >= 0) - { - times = this->TimeSets->GetItem(timeSet); - this->MeasuredTimeValue = times->GetComponent(0, 0); - for (i = 1; i < times->GetNumberOfTuples(); i++) - { - newTime = times->GetComponent(i, 0); - if (newTime <= this->ActualTimeValue && - newTime > this->MeasuredTimeValue) - { - this->MeasuredTimeValue = newTime; - timeStep++; - timeStepInFile++; - } - } - if (this->TimeSetFileNameNumbers->GetNumberOfItems() > 0) - { - int collectionNum = this->TimeSetsWithFilenameNumbers-> - IsId(this->MeasuredTimeSet); - if (collectionNum > -1) - { - filenameNumbers = this->TimeSetFileNameNumbers-> - GetItem(collectionNum); - filenameNum = filenameNumbers->GetId(timeStep-1); - if (! this->UseFileSets) - { - this->ReplaceWildcards(fileName, filenameNum); - } - } - } - - // There can only be file sets if there are also time sets. - if (this->UseFileSets) - { - fileSet = this->FileSets->IsId(this->MeasuredFileSet); - numStepsList = static_cast(this->FileSetNumberOfSteps-> - GetItemAsObject(fileSet)); - - if (timeStep > numStepsList->GetId(0)) - { - numSteps = numStepsList->GetId(0); - timeStepInFile -= numSteps; - fileNum = 2; - for (i = 1; i < numStepsList->GetNumberOfIds(); i++) - { - numSteps += numStepsList->GetId(i); - if (timeStep > numSteps) - { - fileNum++; - timeStepInFile -= numStepsList->GetId(i); - } - } - } - if (this->FileSetFileNameNumbers->GetNumberOfItems() > 0) - { - int collectionNum = this->FileSetsWithFilenameNumbers-> - IsId(this->MeasuredFileSet); - if (collectionNum > -1) - { - filenameNumbers = this->FileSetFileNameNumbers-> - GetItem(fileSet); - filenameNum = filenameNumbers->GetId(fileNum-1); - this->ReplaceWildcards(fileName, filenameNum); - } - } - } - } - } - if (!this->ReadMeasuredGeometryFile(fileName, timeStepInFile, this->Cache)) - { - vtkErrorMacro("error reading measured geometry file"); - delete [] fileName; - return 0; - } - delete [] fileName; - } - this->CacheMTime.Modified(); - } - output->ShallowCopy(this->Cache); - - if ((this->NumberOfVariables + this->NumberOfComplexVariables) > 0) - { - if (!this->ReadVariableFiles(output)) - { - vtkErrorMacro("error reading variable files"); - return 0; - } - } - - return 1; -} diff --git a/src/Plugins/StaticMesh/vtkStaticEnSightGoldReader.h b/src/Plugins/StaticMesh/vtkStaticEnSightGoldReader.h deleted file mode 100644 index 2be1a028..00000000 --- a/src/Plugins/StaticMesh/vtkStaticEnSightGoldReader.h +++ /dev/null @@ -1,69 +0,0 @@ -/*========================================================================= - - Program: Visualization Toolkit - Module: vtkStaticEnSightGoldReader.h - - Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen - All rights reserved. - See Copyright.txt or http://www.kitware.com/Copyright.htm for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notice for more information. - -=========================================================================*/ -/** - * @class vtkStaticEnSightGoldReader - * @brief class to read binary EnSight6 files - * - * vtkStaticEnSightGoldReader is a class to read binary EnSight6 files into vtk. - * Because the different parts of the EnSight data can be of various data - * types, this reader produces multiple outputs, one per part in the input - * file. - * All variable information is being stored in field data. The descriptions - * listed in the case file are used as the array names in the field data. - * For complex vector variables, the description is appended with _r (for the - * array of real values) and _i (for the array if imaginary values). Complex - * scalar variables are stored as a single array with 2 components, real and - * imaginary, listed in that order. - * @warning - * You must manually call Update on this reader and then connect the rest - * of the pipeline because (due to the nature of the file format) it is - * not possible to know ahead of time how many outputs you will have or - * what types they will be. - * This reader can only handle static EnSight datasets (both static geometry - * and variables). -*/ - -#ifndef vtkStaticEnSightGoldReader_h -#define vtkStaticEnSightGoldReader_h - -#include -#include - -class vtkMultiBlockDataSet; - -class vtkStaticEnSightGoldReader : public vtkEnSightGoldReader -{ -public: - static vtkStaticEnSightGoldReader *New(); - vtkTypeMacro(vtkStaticEnSightGoldReader, vtkEnSightGoldReader); - -protected: - vtkStaticEnSightGoldReader() = default; - ~vtkStaticEnSightGoldReader() override = default; - - int RequestData(vtkInformation*, - vtkInformationVector**, - vtkInformationVector*) override; - - vtkNew Cache; - vtkTimeStamp CacheMTime; - -private: - vtkStaticEnSightGoldReader(const vtkStaticEnSightGoldReader&) = delete; - void operator=(const vtkStaticEnSightGoldReader&) = delete; -}; - -#endif - diff --git a/src/Plugins/StaticMesh/vtkStaticMeshObjectFactory.cxx b/src/Plugins/StaticMesh/vtkStaticMeshObjectFactory.cxx deleted file mode 100644 index 4c6f1e6e..00000000 --- a/src/Plugins/StaticMesh/vtkStaticMeshObjectFactory.cxx +++ /dev/null @@ -1,132 +0,0 @@ -/*========================================================================= - - Program: Visualization Toolkit - Module: vtkStaticDataSetSurfaceFilter.cxx - - Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen - All rights reserved. - See Copyright.txt or http://www.kitware.com/Copyright.htm for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notice for more information. - -=========================================================================*/ -#include "vtkStaticMeshObjectFactory.h" - -#include -#include -#include -#include - -#include "vtkStaticDataSetSurfaceFilter.h" -#include "vtkStaticEnSight6BinaryReader.h" -#include "vtkStaticEnSight6Reader.h" -#include "vtkStaticEnSightGoldBinaryReader.h" -#include "vtkStaticEnSightGoldReader.h" -#include "vtkStaticPlaneCutter.h" - -#ifdef PARAVIEW_USE_MPI -#include "vtkStaticPUnstructuredGridGhostCellsGenerator.h" -#endif - -vtkStandardNewMacro(vtkStaticMeshObjectFactory); - -VTK_CREATE_CREATE_FUNCTION(vtkStaticDataSetSurfaceFilter); -VTK_CREATE_CREATE_FUNCTION(vtkStaticPlaneCutter); -VTK_CREATE_CREATE_FUNCTION(vtkStaticEnSight6BinaryReader); -VTK_CREATE_CREATE_FUNCTION(vtkStaticEnSight6Reader); -VTK_CREATE_CREATE_FUNCTION(vtkStaticEnSightGoldReader); -VTK_CREATE_CREATE_FUNCTION(vtkStaticEnSightGoldBinaryReader); - -#ifdef PARAVIEW_USE_MPI -VTK_CREATE_CREATE_FUNCTION(vtkStaticPUnstructuredGridGhostCellsGenerator); -#endif - -vtkStaticMeshObjectFactory::vtkStaticMeshObjectFactory() -{ - vtkDebugMacro("Create vtkStaticMeshObjectFactory"); - - this->RegisterOverride("vtkDataSetSurfaceFilter", "vtkStaticDataSetSurfaceFilter", - "StaticDataSetSurfaceFilter", 1, vtkObjectFactoryCreatevtkStaticDataSetSurfaceFilter); - this->RegisterOverride("vtkPlaneCutter", "vtkStaticPlaneCutter", "StaticPlaneCutter", 1, - vtkObjectFactoryCreatevtkStaticPlaneCutter); - this->RegisterOverride("vtkEnSight6BinaryReader", "vtkStaticEnSight6BinaryReader", "StaticEnSight6BinaryReader", 1, - vtkObjectFactoryCreatevtkStaticEnSight6BinaryReader); - this->RegisterOverride("vtkEnSight6Reader", "vtkStaticEnSight6Reader", "StaticEnSight6Reader", 1, - vtkObjectFactoryCreatevtkStaticEnSight6Reader); - this->RegisterOverride("vtkEnSightGoldReader", "vtkStaticEnSight6BinaryReader", "StaticEnSight6BinaryReader", 1, - vtkObjectFactoryCreatevtkStaticEnSightGoldReader); - this->RegisterOverride("vtkEnSightGoldBinaryReader", "vtkStaticEnSightGoldBinaryReader", "StaticEnSightGoldBinaryReader", 1, - vtkObjectFactoryCreatevtkStaticEnSightGoldBinaryReader); - -#ifdef PARAVIEW_USE_MPI - this->RegisterOverride("vtkPUnstructuredGridGhostCellsGenerator", - "vtkStaticPUnstructuredGridGhostCellsGenerator", "StaticPUnstructuredGridGhostCellsGenerator", - 1, vtkObjectFactoryCreatevtkStaticPUnstructuredGridGhostCellsGenerator); -#endif -} - -vtkStaticMeshObjectFactory::~vtkStaticMeshObjectFactory() -{ - vtkDebugMacro("Delete vtkStaticMeshObjectFactory"); -} - -void vtkStaticMeshObjectFactory::PrintSelf(ostream& os, vtkIndent indent) -{ - os << indent << "VTK Static Mesh Extension Factory" << endl; -} - -const char* vtkStaticMeshObjectFactory::GetVTKSourceVersion() -{ - return VTK_SOURCE_VERSION; -} - -const char* vtkStaticMeshObjectFactory::GetDescription() -{ - return "VTK Static Mesh Extension Factory"; -} - -class StaticFactoryInitialize -{ -public: - StaticFactoryInitialize() - { - bool hasStaticPluginFactory = false; - vtkObjectFactoryCollection* collection = vtkObjectFactory::GetRegisteredFactories(); - collection->InitTraversal(); - vtkObjectFactory* f = collection->GetNextItem(); - while (f) - { - if (f->IsA("vtkStaticMeshObjectFactory")) - { - hasStaticPluginFactory = true; - break; - } - f = collection->GetNextItem(); - } - if (!hasStaticPluginFactory) - { - vtkStaticMeshObjectFactory* instance = vtkStaticMeshObjectFactory::New(); - vtkObjectFactory::RegisterFactory(instance); - instance->Delete(); - } - } - - virtual ~StaticFactoryInitialize() - { - vtkObjectFactoryCollection* collection = vtkObjectFactory::GetRegisteredFactories(); - collection->InitTraversal(); - vtkObjectFactory* f; - while ((f = collection->GetNextItem())) - { - if (f->IsA("vtkStaticMeshObjectFactory")) - { - vtkObjectFactory::UnRegisterFactory(f); - break; - } - } - } -}; - -static StaticFactoryInitialize StaticFactory; diff --git a/src/Plugins/StaticMesh/vtkStaticMeshObjectFactory.h b/src/Plugins/StaticMesh/vtkStaticMeshObjectFactory.h deleted file mode 100644 index 316b9fab..00000000 --- a/src/Plugins/StaticMesh/vtkStaticMeshObjectFactory.h +++ /dev/null @@ -1,58 +0,0 @@ -/*========================================================================= - - Program: Visualization Toolkit - Module: vtkStaticDataSetSurfaceFilter.h - - Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen - All rights reserved. - See Copyright.txt or http://www.kitware.com/Copyright.htm for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notice for more information. - -=========================================================================*/ -/** - * @class vtkStaticMeshObjectFactory - * @brief Generate static version of dataset and filter for statix mesh plugin - * - * vtkStaticMeshObjectFactory is a vtk object factory, instantiating static version - * of some dataset and filters. -*/ - -#ifndef vtkStaticMeshObjectFactory_h -#define vtkStaticMeshObjectFactory_h - -#include // Must be included before singletons - -class vtkStaticMeshObjectFactory : public vtkObjectFactory -{ -public: - vtkTypeMacro(vtkStaticMeshObjectFactory, vtkObjectFactory); - static vtkStaticMeshObjectFactory* New(); - void PrintSelf(ostream& os, vtkIndent indent) override; - - /** - * All sub-classes of vtkObjectFactory must return the version of - * VTK they were built with. This should be implemented with the macro - * VTK_SOURCE_VERSION and NOT a call to vtkVersion::GetVTKSourceVersion. - * As the version needs to be compiled into the file as a string constant. - * This is critical to determine possible incompatible dynamic factory loads. - */ - const char* GetVTKSourceVersion() override; - - /** - * Return a descriptive string describing the factory. - */ - const char* GetDescription() override; - -protected: - vtkStaticMeshObjectFactory(); - ~vtkStaticMeshObjectFactory() override; - -private: - vtkStaticMeshObjectFactory(const vtkStaticMeshObjectFactory&) = delete; - void operator=(const vtkStaticMeshObjectFactory&) = delete; -}; - -#endif diff --git a/src/Plugins/StaticMesh/vtkStaticPUnstructuredGridGhostCellsGenerator.cxx b/src/Plugins/StaticMesh/vtkStaticPUnstructuredGridGhostCellsGenerator.cxx deleted file mode 100644 index b4ab07c9..00000000 --- a/src/Plugins/StaticMesh/vtkStaticPUnstructuredGridGhostCellsGenerator.cxx +++ /dev/null @@ -1,517 +0,0 @@ -/*========================================================================= - - Program: Visualization Toolkit - Module: vtkStaticPUnstructuredGridGhostCellsGenerator.cxx - - Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen - All rights reserved. - See Copyright.txt or http://www.kitware.com/Copyright.htm for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notice for more information. - -=========================================================================*/ -#include "vtkStaticPUnstructuredGridGhostCellsGenerator.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -static const int SUGGCG_SIZE_EXCHANGE_TAG = 9002; -static const int SUGGCG_DATA_EXCHANGE_TAG = 9003; - -vtkStandardNewMacro(vtkStaticPUnstructuredGridGhostCellsGenerator); - -//---------------------------------------------------------------------------- -vtkStaticPUnstructuredGridGhostCellsGenerator::vtkStaticPUnstructuredGridGhostCellsGenerator() -{ - this->InputMeshTime = 0; - this->FilterMTime = 0; - - vtkMPIController* controller = - vtkMPIController::SafeDownCast(vtkMultiProcessController::GetGlobalController()); - if (controller) - { - // Initialise vtkIdList vectors - this->GhostPointsToReceive.resize(controller->GetNumberOfProcesses()); - this->GhostPointsToSend.resize(controller->GetNumberOfProcesses()); - this->GhostCellsToReceive.resize(controller->GetNumberOfProcesses()); - this->GhostCellsToSend.resize(controller->GetNumberOfProcesses()); - - int nProc = controller->GetNumberOfProcesses(); - - for (int i = 0; i < nProc; i++) - { - this->GhostCellsToReceive[i] = vtkSmartPointer::New(); - this->GhostCellsToSend[i] = vtkSmartPointer::New(); - this->GhostPointsToReceive[i] = vtkSmartPointer::New(); - this->GhostPointsToSend[i] = vtkSmartPointer::New(); - } - } -} - -//---------------------------------------------------------------------------- -vtkStaticPUnstructuredGridGhostCellsGenerator::~vtkStaticPUnstructuredGridGhostCellsGenerator() -{ -} - -//----------------------------------------------------------------------------- -int vtkStaticPUnstructuredGridGhostCellsGenerator::RequestData( - vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector) -{ - // get the inputs and outputs - vtkInformation* inInfo = inputVector[0]->GetInformationObject(0); - vtkInformation* outInfo = outputVector->GetInformationObject(0); - vtkUnstructuredGridBase* input = - vtkUnstructuredGridBase::SafeDownCast(inInfo->Get(vtkDataObject::DATA_OBJECT())); - vtkUnstructuredGrid* output = - vtkUnstructuredGrid::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); - - // Recover the static unstructured grid - vtkUnstructuredGrid* inputUG = vtkUnstructuredGrid::SafeDownCast(input); - if (!inputUG) - { - // For any other types of input, fall back to superclass implementation - return this->Superclass::RequestData(request, inputVector, outputVector); - } - - // Check cache validity - if (this->InputMeshTime == inputUG->GetMeshMTime() && this->FilterMTime == this->GetMTime()) - { - // Cache mesh is up to date, use it to generate data - // Update the cache data - this->UpdateCacheData(input); - - // Copy the updated cache into the output - output->ShallowCopy(this->Cache.Get()); - return 1; - } - else - { - // Add Arrays Ids needed - vtkNew tmpInput; - this->AddIdsArrays(input, tmpInput.Get()); - - // Create an input vector to pass the completed input to the superclass - // RequestData method - vtkNew tmpInputVec; - tmpInputVec->Copy(inputVector[0], 1); - vtkInformation* tmpInInfo = tmpInputVec->GetInformationObject(0); - tmpInInfo->Set(vtkDataObject::DATA_OBJECT(), tmpInput.Get()); - vtkInformationVector* tmpInputVecPt = tmpInputVec.Get(); - int ret = this->Superclass::RequestData(request, &tmpInputVecPt, outputVector); - - // Update the cache with superclass output - this->Cache->ShallowCopy(output); - this->InputMeshTime = inputUG->GetMeshMTime(); - this->FilterMTime = this->GetMTime(); - - this->ProcessGhostIds(); - - return ret; - } -} - -//----------------------------------------------------------------------------- -void vtkStaticPUnstructuredGridGhostCellsGenerator::ProcessGhostIds() -{ - vtkMPIController* controller = - vtkMPIController::SafeDownCast(vtkMultiProcessController::GetGlobalController()); - if (controller) - { - int nProc = controller->GetNumberOfProcesses(); - int rank = controller->GetLocalProcessId(); - - // Clear ghost vectors - for (int i = 0; i < nProc; i++) - { - this->GhostCellsToReceive[i]->SetNumberOfIds(0); - this->GhostCellsToSend[i]->SetNumberOfIds(0); - this->GhostPointsToReceive[i]->SetNumberOfIds(0); - this->GhostPointsToSend[i]->SetNumberOfIds(0); - } - - // Recover all needed data arrays - vtkPointData* cachePD = this->Cache->GetPointData(); - vtkCellData* cacheCD = this->Cache->GetCellData(); - vtkUnsignedCharArray* pointGhostArray = this->Cache->GetPointGhostArray(); - vtkUnsignedCharArray* cellGhostArray = this->Cache->GetCellGhostArray(); - vtkIdTypeArray* pointIds = vtkIdTypeArray::SafeDownCast(cachePD->GetAbstractArray("Ids")); - vtkIdTypeArray* cellIds = vtkIdTypeArray::SafeDownCast(cacheCD->GetAbstractArray("Ids")); - vtkIntArray* pointProcIds = vtkIntArray::SafeDownCast(cachePD->GetAbstractArray("ProcessId")); - vtkIntArray* cellProcIds = vtkIntArray::SafeDownCast(cacheCD->GetAbstractArray("ProcessId")); - if (!pointGhostArray || !pointIds || !pointProcIds || !cellGhostArray || !cellIds || - !cellProcIds) - { - // Sanity check - vtkWarningMacro("Arrays are missing from cache, cache is discarded"); - this->InputMeshTime = 0; - this->FilterMTime = 0; - } - else - { - // Compute list of remote ghost point ids - // and corresponding local point ids. - std::vector > remoteGhostPoints; - remoteGhostPoints.resize(nProc); - for (vtkIdType i = 0; i < pointGhostArray->GetNumberOfTuples(); i++) - { - if (pointGhostArray->GetValue(i) != 0) - { - this->GhostPointsToReceive[pointProcIds->GetValue(i)]->InsertNextId(i); - remoteGhostPoints[pointProcIds->GetValue(i)].push_back(pointIds->GetValue(i)); - } - } - - // Compute list of remote ghost cell ids - // and corresponding local cell ids. - std::vector > remoteGhostCells; - remoteGhostCells.resize(nProc); - for (vtkIdType i = 0; i < cellGhostArray->GetNumberOfTuples(); i++) - { - if (cellGhostArray->GetValue(i) != 0) - { - this->GhostCellsToReceive[cellProcIds->GetValue(i)]->InsertNextId(i); - remoteGhostCells[cellProcIds->GetValue(i)].push_back(cellIds->GetValue(i)); - } - } - - // Send requested ghost point ids to their own rank - vtkMPICommunicator::Request pointSizeReqs[nProc]; - vtkMPICommunicator::Request pointIdsReqs[nProc]; - vtkIdType lengths[nProc]; - for (int i = 0; i < nProc; i++) - { - if (i != rank) - { - lengths[i] = remoteGhostPoints[i].size(); - controller->NoBlockSend(&lengths[i], 1, i, SUGGCG_SIZE_EXCHANGE_TAG, pointSizeReqs[i]); - controller->NoBlockSend(&remoteGhostPoints[i][0], remoteGhostPoints[i].size(), i, - SUGGCG_DATA_EXCHANGE_TAG, pointIdsReqs[i]); - } - } - - // Receive and store requested ghost point ids. - for (int i = 0; i < nProc; i++) - { - if (i != rank) - { - vtkIdType length; - controller->Receive(&length, 1, i, SUGGCG_SIZE_EXCHANGE_TAG); - this->GhostPointsToSend[i]->SetNumberOfIds(length); - controller->Receive( - this->GhostPointsToSend[i]->GetPointer(0), length, i, SUGGCG_DATA_EXCHANGE_TAG); - } - } - controller->Barrier(); - - // Send requested ghost cell ids to their own rank - vtkMPICommunicator::Request cellSizeReqs[nProc]; - vtkMPICommunicator::Request cellIdsReqs[nProc]; - for (int i = 0; i < nProc; i++) - { - if (i != rank) - { - lengths[i] = remoteGhostCells[i].size(); - controller->NoBlockSend(&lengths[i], 1, i, SUGGCG_SIZE_EXCHANGE_TAG, cellSizeReqs[i]); - controller->NoBlockSend( - &remoteGhostCells[i][0], lengths[i], i, SUGGCG_DATA_EXCHANGE_TAG, cellIdsReqs[i]); - } - } - // Receive and store requested ghost cell ids. - for (int i = 0; i < nProc; i++) - { - if (i != rank) - { - vtkIdType length; - controller->Receive(&length, 1, i, SUGGCG_SIZE_EXCHANGE_TAG); - this->GhostCellsToSend[i]->SetNumberOfIds(length); - controller->Receive( - this->GhostCellsToSend[i]->GetPointer(0), length, i, SUGGCG_DATA_EXCHANGE_TAG); - } - } - controller->Barrier(); - } - } -} - -//----------------------------------------------------------------------------- -void vtkStaticPUnstructuredGridGhostCellsGenerator::AddIdsArrays( - vtkDataSet* input, vtkDataSet* output) -{ - vtkDataSet* tmpInput; - tmpInput = input; - vtkNew generateIdScalars; - vtkNew processPointIdScalars; - vtkNew processCellIdScalars; - - // Check for Ids array - vtkAbstractArray* pointIdsTmp = input->GetPointData()->GetAbstractArray("Ids"); - vtkAbstractArray* cellIdsTmp = input->GetCellData()->GetAbstractArray("Ids"); - if (!pointIdsTmp || !cellIdsTmp) - { - // Create Ids array - generateIdScalars->SetInputData(tmpInput); - generateIdScalars->SetIdsArrayName("Ids"); - generateIdScalars->Update(); - tmpInput = generateIdScalars->GetOutput(); - } - - // Check for ProcessId point array - vtkAbstractArray* procIdsTmp = input->GetPointData()->GetAbstractArray("ProcessId"); - if (!procIdsTmp) - { - // Create ProcessId point Array - processPointIdScalars->SetInputData(tmpInput); - processPointIdScalars->SetScalarModeToPointData(); - processPointIdScalars->Update(); - tmpInput = processPointIdScalars->GetOutput(); - } - - // Check for ProcessId Cell Array - procIdsTmp = input->GetCellData()->GetAbstractArray("ProcessId"); - if (!procIdsTmp) - { - // Create ProcessId Cell array - vtkNew processIdScalars; - processCellIdScalars->SetInputData(tmpInput); - processCellIdScalars->SetScalarModeToCellData(); - processCellIdScalars->Update(); - tmpInput = processCellIdScalars->GetOutput(); - } - output->ShallowCopy(tmpInput); -} - -//----------------------------------------------------------------------------- -void vtkStaticPUnstructuredGridGhostCellsGenerator::UpdateCacheData(vtkDataSet* input) -{ - this->UpdateCacheDataWithInput(input); - this->UpdateCacheGhostCellAndPointData(input); -} - -//----------------------------------------------------------------------------- -void vtkStaticPUnstructuredGridGhostCellsGenerator::UpdateCacheDataWithInput(vtkDataSet* input) -{ - // Recover point and cell data - vtkPointData* cachePD = this->Cache->GetPointData(); - vtkCellData* cacheCD = this->Cache->GetCellData(); - vtkPointData* inPD = input->GetPointData(); - vtkCellData* inCD = input->GetCellData(); - - // Update cache point data using input point data - // Of course this concerns only non-ghost points - for (int i = 0; i < inPD->GetNumberOfArrays(); i++) - { - vtkAbstractArray* cacheArray = cachePD->GetAbstractArray(inPD->GetArrayName(i)); - if (cacheArray) - { - cacheArray->InsertTuples(0, input->GetNumberOfPoints(), 0, inPD->GetAbstractArray(i)); - } - } - - // Update cache cell data using input cell data - // Of course this concerns only non-ghost cells - for (int i = 0; i < inCD->GetNumberOfArrays(); i++) - { - vtkAbstractArray* cacheArray = cacheCD->GetAbstractArray(inCD->GetArrayName(i)); - if (cacheArray) - { - cacheArray->InsertTuples(0, input->GetNumberOfCells(), 0, inCD->GetAbstractArray(i)); - } - } - - // Update field data - this->Cache->GetFieldData()->ShallowCopy(input->GetFieldData()); -} - -//----------------------------------------------------------------------------- -void vtkStaticPUnstructuredGridGhostCellsGenerator::UpdateCacheGhostCellAndPointData( - vtkDataSet* input) -{ - vtkMPIController* controller = - vtkMPIController::SafeDownCast(vtkMultiProcessController::GetGlobalController()); - if (controller) - { - vtkPointData* cachePD = this->Cache->GetPointData(); - vtkCellData* cacheCD = this->Cache->GetCellData(); - vtkPointData* inPD = input->GetPointData(); - vtkCellData* inCD = input->GetCellData(); - - int nProc = controller->GetNumberOfProcesses(); - int rank = controller->GetLocalProcessId(); - - vtkNew buffers[nProc]; - vtkIdType lengths[nProc]; - vtkMPICommunicator::Request sizeReqs[nProc]; - vtkMPICommunicator::Request dataReqs[nProc]; - - // For each rank - for (int i = 0; i < nProc; i++) - { - if (i != rank && this->GhostPointsToSend[i]->GetNumberOfIds() > 0) - { - // Prepare ghost points point data to send it as a table - vtkNew ghostPointData; - ghostPointData->CopyAllocate(inPD); - - // Prepare a list of iterating ids and copy all ghost point ids - // for this rank into the ghostPointData - vtkNew dumStaticPointIds; - dumStaticPointIds->SetNumberOfIds(this->GhostPointsToSend[i]->GetNumberOfIds()); - for (vtkIdType id = 0; id < this->GhostPointsToSend[i]->GetNumberOfIds(); id++) - { - dumStaticPointIds->SetId(id, id); - } - ghostPointData->CopyData(inPD, this->GhostPointsToSend[i].Get(), dumStaticPointIds.Get()); - - // Add each point data array to a dumStatic table - vtkNew pointDataTable; - for (int iArr = 0; iArr < ghostPointData->GetNumberOfArrays(); iArr++) - { - pointDataTable->AddColumn(ghostPointData->GetArray(iArr)); - } - - // Marshall the table and transfer it to rank - vtkCommunicator::MarshalDataObject(pointDataTable.Get(), buffers[i].Get()); - lengths[i] = buffers[i]->GetNumberOfTuples(); - controller->NoBlockSend(&lengths[i], 1, i, SUGGCG_SIZE_EXCHANGE_TAG, sizeReqs[i]); - controller->NoBlockSend((char*)(buffers[i]->GetVoidPointer(0)), lengths[i], i, - SUGGCG_DATA_EXCHANGE_TAG, dataReqs[i]); - } - } - // Foe each rank - for (int i = 0; i < nProc; i++) - { - if (i != rank && this->GhostPointsToReceive[i]->GetNumberOfIds() > 0) - { - // Receive dumStatic table to unmarshall - vtkIdType length; - controller->Receive(&length, 1, i, SUGGCG_SIZE_EXCHANGE_TAG); - - vtkNew recvBuffer; - recvBuffer->SetNumberOfValues(length); - controller->Receive( - (char*)(recvBuffer->GetVoidPointer(0)), length, i, SUGGCG_DATA_EXCHANGE_TAG); - vtkNew pointDataTable; - vtkCommunicator::UnMarshalDataObject(recvBuffer.Get(), pointDataTable.Get()); - - // Create a dumStatic iterating point ids - vtkNew dumStaticPointIds; - dumStaticPointIds->SetNumberOfIds(this->GhostPointsToReceive[i]->GetNumberOfIds()); - for (vtkIdType id = 0; id < this->GhostPointsToReceive[i]->GetNumberOfIds(); id++) - { - dumStaticPointIds->SetId(id, id); - } - - // Copy the tuples of each array from the dumStatic table - // into the ghost point data - for (int iArr = 0; iArr < pointDataTable->GetNumberOfColumns(); iArr++) - { - vtkAbstractArray* arrayToCopyIn = - cachePD->GetAbstractArray(pointDataTable->GetColumnName(iArr)); - if (arrayToCopyIn) - { - arrayToCopyIn->InsertTuples(this->GhostPointsToReceive[i].Get(), - dumStaticPointIds.Get(), pointDataTable->GetColumn(iArr)); - } - } - } - } - // Make sure all rank finished - controller->Barrier(); - - for (int i = 0; i < nProc; i++) - { - if (i != rank && this->GhostCellsToSend[i]->GetNumberOfIds() > 0) - { - // Prepare ghost cells data to send it as a table - vtkNew ghostCellData; - ghostCellData->CopyAllocate(inCD); - - // Prepare a list of iterating ids and copy all ghost point ids - // for this rank into the ghostPointData - vtkNew dumStaticCellIds; - dumStaticCellIds->SetNumberOfIds(this->GhostCellsToSend[i]->GetNumberOfIds()); - for (vtkIdType id = 0; id < this->GhostCellsToSend[i]->GetNumberOfIds(); id++) - { - dumStaticCellIds->SetId(id, id); - } - ghostCellData->CopyData(inCD, this->GhostCellsToSend[i].Get(), dumStaticCellIds.Get()); - - // Add each point data array to a dumStatic table - vtkNew cellDataTable; - for (int iArr = 0; iArr < ghostCellData->GetNumberOfArrays(); iArr++) - { - cellDataTable->AddColumn(ghostCellData->GetArray(iArr)); - } - - // Marshall the table and transfer it to rank - vtkCommunicator::MarshalDataObject(cellDataTable.Get(), buffers[i].Get()); - lengths[i] = buffers[i]->GetNumberOfTuples(); - controller->NoBlockSend(&lengths[i], 1, i, SUGGCG_SIZE_EXCHANGE_TAG, sizeReqs[i]); - controller->NoBlockSend((char*)(buffers[i]->GetVoidPointer(0)), lengths[i], i, - SUGGCG_DATA_EXCHANGE_TAG, dataReqs[i]); - } - } - for (int i = 0; i < nProc; i++) - { - if (i != rank && this->GhostCellsToReceive[i]->GetNumberOfIds() > 0) - { - // Receive dumStatic table to unmarshall - vtkIdType length; - controller->Receive(&length, 1, i, SUGGCG_SIZE_EXCHANGE_TAG); - - vtkNew recvBuffer; - recvBuffer->SetNumberOfValues(length); - controller->Receive( - (char*)(recvBuffer->GetVoidPointer(0)), length, i, SUGGCG_DATA_EXCHANGE_TAG); - vtkNew cellDataTable; - vtkCommunicator::UnMarshalDataObject(recvBuffer.Get(), cellDataTable.Get()); - - // Create a dumStatic iterating point ids - vtkNew dumStaticCellIds; - dumStaticCellIds->SetNumberOfIds(this->GhostCellsToReceive[i]->GetNumberOfIds()); - for (vtkIdType id = 0; id < this->GhostCellsToReceive[i]->GetNumberOfIds(); id++) - { - dumStaticCellIds->SetId(id, id); - } - - // Copy the tuples of each array from the dumStatic table - // into the ghost point data - for (int iArr = 0; iArr < cellDataTable->GetNumberOfColumns(); iArr++) - { - vtkAbstractArray* arrayToCopyIn = - cacheCD->GetAbstractArray(cellDataTable->GetColumnName(iArr)); - if (arrayToCopyIn) - { - arrayToCopyIn->InsertTuples(this->GhostCellsToReceive[i].Get(), dumStaticCellIds.Get(), - cellDataTable->GetColumn(iArr)); - } - } - } - } - // Make sure all rank finished - controller->Barrier(); - } -} - -//---------------------------------------------------------------------------- -void vtkStaticPUnstructuredGridGhostCellsGenerator::PrintSelf(ostream& os, vtkIndent indent) -{ - this->Superclass::PrintSelf(os, indent); - os << indent << "Cache: " << this->Cache << endl; - os << indent << "Input Mesh Time: " << this->InputMeshTime << endl; - os << indent << "Filter mTime: " << this->FilterMTime << endl; -} diff --git a/src/Plugins/StaticMesh/vtkStaticPUnstructuredGridGhostCellsGenerator.h b/src/Plugins/StaticMesh/vtkStaticPUnstructuredGridGhostCellsGenerator.h deleted file mode 100644 index ecfadfec..00000000 --- a/src/Plugins/StaticMesh/vtkStaticPUnstructuredGridGhostCellsGenerator.h +++ /dev/null @@ -1,102 +0,0 @@ -/*========================================================================= - - Program: Visualization Toolkit - Module: vtkStaticPUnstructuredGridGhostCellsGenerator.h - - Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen - All rights reserved. - See Copyright.txt or http://www.kitware.com/Copyright.htm for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notice for more information. - -=========================================================================*/ -/** - * @class vtkStaticPUnstructuredGridGhostCellsGenerator - * @brief StaticMesh aware GhostCellGenerator implementation - * - * This class specialize vtkPUnstructuredGridGhostCellGenerator - * This class improves it by making it static mesh aware. - * The first time this filter is executed it will store its output - * in a cache as well as a list of ghost and point ids to request from other rank - * On next execution, if the mesh is static, it will uses the list of ids to request - * only point and cell data for the ghost point and cell from other - * allowing to update the output without needing to recompute everything - * - * @sa - * vtkPUnstructuredGridGhostCellsGenerator -*/ - -#ifndef vtkStaticPUnstructuredGridGhostCellsGenerator_h -#define vtkStaticPUnstructuredGridGhostCellsGenerator_h - -#include -#include -#include -#include - -#include - -class vtkUnstructuredGrid; - -class vtkStaticPUnstructuredGridGhostCellsGenerator : public vtkPUnstructuredGridGhostCellsGenerator -{ -public: - static vtkStaticPUnstructuredGridGhostCellsGenerator* New(); - typedef vtkPUnstructuredGridGhostCellsGenerator - Superclass; // vtkTypeMacro can't be used with a factory built object - void PrintSelf(ostream& os, vtkIndent indent) override; - - int RequestData(vtkInformation*, vtkInformationVector**, vtkInformationVector*) override; - -protected: - vtkStaticPUnstructuredGridGhostCellsGenerator(); - ~vtkStaticPUnstructuredGridGhostCellsGenerator() override; - - /** - * Check input for "ProcessId" and "Ids" point and cell array, - * If absent, compute and add them. - */ - static void AddIdsArrays(vtkDataSet* input, vtkDataSet* output); - - /** - * Using the Cache, exchange and update ghost point and cell - * ids between ranks - */ - virtual void ProcessGhostIds(); - - /** - * Update cache with input and with ghost cells info - */ - virtual void UpdateCacheData(vtkDataSet* input); - - /** - * Copy input point, cell and field data into cache - */ - virtual void UpdateCacheDataWithInput(vtkDataSet* input); - - /** - * Using Cached ghost cell and points info - * Update ghost cell and point data in cache - * by sending input point and cell data to other ranks - */ - virtual void UpdateCacheGhostCellAndPointData(vtkDataSet* input); - - vtkNew Cache; - vtkMTimeType InputMeshTime; - vtkMTimeType FilterMTime; - - std::vector > GhostCellsToReceive; - std::vector > GhostCellsToSend; - std::vector > GhostPointsToReceive; - std::vector > GhostPointsToSend; - -private: - // Hide these from the user and the compiler. - vtkStaticPUnstructuredGridGhostCellsGenerator( - const vtkStaticPUnstructuredGridGhostCellsGenerator&) = delete; - void operator=(const vtkStaticPUnstructuredGridGhostCellsGenerator&) = delete; -}; - -#endif diff --git a/src/Plugins/StaticMesh/vtkStaticPlaneCutter.cxx b/src/Plugins/StaticMesh/vtkStaticPlaneCutter.cxx deleted file mode 100644 index 393bddcf..00000000 --- a/src/Plugins/StaticMesh/vtkStaticPlaneCutter.cxx +++ /dev/null @@ -1,300 +0,0 @@ -/*========================================================================= - - Program: Visualization Toolkit - Module: vtkStaticPlaneCutter.cxx - - Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen - All rights reserved. - See Copyright.txt or http://www.kitware.com/Copyright.htm for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notice for more information. - -=========================================================================*/ -#include "vtkStaticPlaneCutter.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -vtkStandardNewMacro(vtkStaticPlaneCutter); - -static const char* IdsArrayName = "__vtkSPC_Ids"; - -//---------------------------------------------------------------------------- -vtkStaticPlaneCutter::vtkStaticPlaneCutter() -{ - this->InputMeshTime = 0; - this->FilterMTime = 0; -} - -//---------------------------------------------------------------------------- -vtkStaticPlaneCutter::~vtkStaticPlaneCutter() -{ - this->ClearWeightsVector(); -} - -//----------------------------------------------------------------------------- -int vtkStaticPlaneCutter::RequestData( - vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector) -{ - // get the inputs and outputs - vtkInformation* inInfo = inputVector[0]->GetInformationObject(0); - vtkInformation* outInfo = outputVector->GetInformationObject(0); - vtkUnstructuredGrid* input = vtkUnstructuredGrid::SafeDownCast(inInfo->Get(vtkDataObject::DATA_OBJECT())); - vtkMultiBlockDataSet* inputMB = vtkMultiBlockDataSet::SafeDownCast(inInfo->Get(vtkDataObject::DATA_OBJECT())); - vtkMultiBlockDataSet* mb = - vtkMultiBlockDataSet::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); - if (!mb) - { - vtkErrorMacro("Ouput information does not contain expected type of data object"); - return 0; - } - - // Recover the first and only block so this works with single block mb - if (inputMB && inputMB->GetNumberOfBlocks() == 1) - { - input = vtkUnstructuredGrid::SafeDownCast(inputMB->GetBlock(0)); - } - - // Recover the static unstructured grid - if (!input) - { - // For any other type of input, fall back to superclass implementation - return this->Superclass::RequestData(request, inputVector, outputVector); - } - - // Check cache validity - if (this->InputMeshTime == input->GetMeshMTime() && this->FilterMTime == this->GetMTime()) - { - // Cache mesh is up to date, use it to generate data - if (this->InterpolateAttributes) - { - // Update the cache data - this->UpdateCacheData(input); - } - - // Copy the updated cache into the output - mb->SetBlock(0, this->Cache.Get()); - return 1; - } - else - { - // Cache is invalid - // Add needed Arrays - vtkNew tmpInput; - this->AddIdsArray(input, tmpInput.Get()); - - // Create an input vector to pass the completed input to the superclass - // RequestData method - vtkNew tmpInputVec; - tmpInputVec->Copy(inputVector[0], 1); - vtkInformation* tmpInInfo = tmpInputVec->GetInformationObject(0); - tmpInInfo->Set(vtkDataObject::DATA_OBJECT(), tmpInput.Get()); - vtkInformationVector* tmpInputVecPt = tmpInputVec.Get(); - int ret = this->Superclass::RequestData(request, &tmpInputVecPt, outputVector); - - // Update the cache with superclass output - vtkMultiPieceDataSet* output = vtkMultiPieceDataSet::SafeDownCast(mb->GetBlock(0)); - if (!output) - { - vtkErrorMacro("Output is not of expected type"); - return 0; - } - - this->Cache->ShallowCopy(output); - this->InputMeshTime = input->GetMeshMTime(); - this->FilterMTime = this->GetMTime(); - - // Compute the ids to be passed from the input to the cache - this->ComputeIds(input); - this->RemoveIdsArray(this->Cache); - return ret; - } -} - -//----------------------------------------------------------------------------- -void vtkStaticPlaneCutter::AddIdsArray(vtkDataSet* input, vtkDataSet* output) -{ - vtkDataSet* tmpInput = input; - vtkNew generateIdScalars; - - // Check for Ids array - vtkIdTypeArray *cellIdsTmp = vtkIdTypeArray::SafeDownCast(input->GetCellData()->GetAbstractArray(IdsArrayName)); - if (!cellIdsTmp) - { - // Create Ids array - generateIdScalars->SetInputData(tmpInput); - generateIdScalars->SetIdsArrayName(IdsArrayName); - generateIdScalars->FieldDataOn(); - generateIdScalars->Update(); - tmpInput = generateIdScalars->GetOutput(); - } - output->ShallowCopy(tmpInput); -} - -//----------------------------------------------------------------------------- -void vtkStaticPlaneCutter::RemoveIdsArray(vtkMultiPieceDataSet* output) -{ - vtkSmartPointer iter; - iter.TakeReference(output->NewIterator()); - iter->SkipEmptyNodesOn(); - for (iter->GoToFirstItem(); !iter->IsDoneWithTraversal(); iter->GoToNextItem()) - { - vtkPolyData* slice = vtkPolyData::SafeDownCast(iter->GetCurrentDataObject()); - if (slice) - { - slice->GetCellData()->RemoveArray(IdsArrayName); - } - } -} - -//----------------------------------------------------------------------------- -void vtkStaticPlaneCutter::ClearWeightsVector() -{ - for(auto& weightsVector : this->WeightsVectorCompo) - { - delete[] weightsVector[0].second; - } - this->WeightsVectorCompo.clear(); -} - -//----------------------------------------------------------------------------- -void vtkStaticPlaneCutter::ComputeIds(vtkUnstructuredGrid* input) -{ - this->CellToCopyFrom.clear(); - this->CellToCopyTo.clear(); - this->ClearWeightsVector(); - - // Iterate over each piece of the multipiece output - vtkNew tmpCell; - vtkSmartPointer iter; - iter.TakeReference(this->Cache->NewIterator()); - iter->SkipEmptyNodesOn(); - for (iter->GoToFirstItem(); !iter->IsDoneWithTraversal(); iter->GoToNextItem()) - { - vtkPolyData* slice = vtkPolyData::SafeDownCast(iter->GetCurrentDataObject()); - vtkIdType sliceNbPoints = slice ? slice->GetNumberOfPoints() : 0; - if (sliceNbPoints > 0) - { - // For each piece, recover the Ids of the cells sliced and the corresponding - // cellId in the slice - vtkSmartPointer cellIdsFrom = vtkSmartPointer::New(); - vtkSmartPointer cellIdsTo = vtkSmartPointer::New(); - this->CellToCopyFrom.push_back(cellIdsFrom); - this->CellToCopyTo.push_back(cellIdsTo); - - vtkIdTypeArray* ids = vtkIdTypeArray::SafeDownCast(slice->GetCellData()->GetArray(IdsArrayName)); - assert(ids); - cellIdsFrom->SetNumberOfIds(ids->GetNumberOfValues()); - cellIdsTo->SetNumberOfIds(ids->GetNumberOfValues()); - for (vtkIdType i = 0; i < ids->GetNumberOfValues(); i++) - { - cellIdsFrom->SetId(i, ids->GetValue(i)); - cellIdsTo->SetId(i, i); - } - if (input->GetPointData()->GetNumberOfArrays() > 0) - { - slice->BuildLinks(); - vtkIdType maxCellSize = input->GetMaxCellSize(); - std::vector, double*>> weightsVector; - weightsVector.resize(sliceNbPoints); - double *allWeights = new double[maxCellSize * sliceNbPoints]; - for (vtkIdType i = 0; i < sliceNbPoints; i++) - { - vtkNew ptIds; - double *weights = &allWeights[maxCellSize * i]; - unsigned short ncells; - vtkIdType *cells; - slice->GetPointCells(i, ncells, cells); - vtkIdType cellId = cellIdsFrom->GetId(cells[0]); - assert(cellId < input->GetNumberOfCells()); - input->GetCell(cellId, tmpCell); - input->GetCellPoints(cellId, ptIds); - double dist, pcoords[3], x[3], p[3]; - int subId = 0; - slice->GetPoint(i, p); - tmpCell->EvaluatePosition(p, x, subId, pcoords, dist, weights); - weightsVector[i] = { ptIds, weights }; - } - this->WeightsVectorCompo.push_back(weightsVector); - } - } - } -} - -//----------------------------------------------------------------------------- -void vtkStaticPlaneCutter::UpdateCacheData(vtkDataSet* input) -{ - // Remove useless FieldData Array from multipiece - // Created by automatic pass data in pipeline - vtkFieldData* mpFieldData = this->Cache->GetFieldData(); - for (int i = mpFieldData->GetNumberOfArrays() - 1; i >= 0; i--) - { - mpFieldData->RemoveArray(i); - } - - // Recover cell/point data - vtkCellData* inCD = input->GetCellData(); - vtkPointData* inPD = input->GetPointData(); - - vtkSmartPointer iter; - iter.TakeReference(this->Cache->NewIterator()); - iter->SkipEmptyNodesOn(); - int blockId = 0; - for (iter->GoToFirstItem(); !iter->IsDoneWithTraversal(); iter->GoToNextItem()) - { - vtkPolyData* slice = vtkPolyData::SafeDownCast(iter->GetCurrentDataObject()); - if (slice && slice->GetNumberOfPoints() > 0) - { - vtkCellData* sliceCD = slice->GetCellData(); - for (int iArr = 0; iArr < inCD->GetNumberOfArrays(); iArr++) - { - // For each array of the cell data of each slice - vtkAbstractArray* arrayToCopyIn = sliceCD->GetAbstractArray(inCD->GetArrayName(iArr)); - if (arrayToCopyIn) - { - // Copy the tuples from the input cell ids to the slice cell ids - arrayToCopyIn->InsertTuples(this->CellToCopyTo[blockId].Get(), this->CellToCopyFrom[blockId].Get(), - inCD->GetAbstractArray(iArr)); - } - } - - if (input->GetPointData()->GetNumberOfArrays() > 0) - { - vtkPointData* slicePD = slice->GetPointData(); - vtkIdType sliceNbPoints = slice->GetNumberOfPoints(); - slicePD->InterpolateAllocate(inPD, sliceNbPoints); - auto& weightsVector = this->WeightsVectorCompo[blockId]; - for (vtkIdType ptIdx = 0; ptIdx < sliceNbPoints; ptIdx++) - { - slicePD->InterpolatePoint(inPD, ptIdx, weightsVector[ptIdx].first, weightsVector[ptIdx].second); - } - } - - // Update field data - slice->GetFieldData()->PassData(input->GetFieldData()); - blockId++; - } - } -} - -//---------------------------------------------------------------------------- -void vtkStaticPlaneCutter::PrintSelf(ostream& os, vtkIndent indent) -{ - this->Superclass::PrintSelf(os, indent); - os << indent << "Cache: " << this->Cache << endl; - os << indent << "Input Mesh Time: " << this->InputMeshTime << endl; - os << indent << "Filter mTime: " << this->FilterMTime << endl; -} diff --git a/src/Plugins/StaticMesh/vtkStaticPlaneCutter.h b/src/Plugins/StaticMesh/vtkStaticPlaneCutter.h deleted file mode 100644 index ab473e7c..00000000 --- a/src/Plugins/StaticMesh/vtkStaticPlaneCutter.h +++ /dev/null @@ -1,91 +0,0 @@ -/*========================================================================= - - Program: Visualization Toolkit - Module: vtkStaticPlaneCutter.h - - Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen - All rights reserved. - See Copyright.txt or http://www.kitware.com/Copyright.htm for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notice for more information. - -=========================================================================*/ -/** - * @class vtkStaticPlaneCutter - * @brief StaticMesh aware implementation of vtkPlaneCutter vtk vtkUnstructuredGrid - * - * This class specialize vtkPlaneCutter for vtkUnstructuredGrid input. - * It uses a cache when the associated data chage over time but not the geometry. - * In order to be able to update the cache, we keep track of cells ids - * when the cache is computed. - * Contrary to its parent, this class does not interpolate point data, - * only transmit cell data. - * - * - * @sa - * vtkPlaneCutter -*/ - -#ifndef vtkStaticPlaneCutter_h -#define vtkStaticPlaneCutter_h - -#include -#include -#include -#include - -#include - -class vtkMultiPieceDataSet; - -class vtkStaticPlaneCutter : public vtkPlaneCutter -{ -public: - static vtkStaticPlaneCutter* New(); - typedef vtkPlaneCutter Superclass; // vtkTypeMacro can't be used with a factory built object - void PrintSelf(ostream &os, vtkIndent indent) override; - - int RequestData(vtkInformation*, vtkInformationVector**, vtkInformationVector*) override; - -protected: - vtkStaticPlaneCutter(); - ~vtkStaticPlaneCutter() override; - - /** - * Check input for Ids cell array, if absent, compute and add them. - */ - static void AddIdsArray(vtkDataSet* input, vtkDataSet* output); - - /** - * Remove an Ids cell array in all polydata pieces of output - */ - static void RemoveIdsArray(vtkMultiPieceDataSet* output); - - /** - * Update cache point, cell and field data using input - */ - void UpdateCacheData(vtkDataSet* input); - - /** - * Compute the ids and weights to be used when updating the cache later - */ - void ComputeIds(vtkUnstructuredGrid* input); - - void ClearWeightsVector(); - - vtkNew Cache; - std::vector > CellToCopyFrom; - std::vector > CellToCopyTo; - std::vector, double*>>> WeightsVectorCompo; - vtkMTimeType InputMeshTime; - vtkMTimeType FilterMTime; - -private: - // Hide these from the user and the compiler. - vtkStaticPlaneCutter(const vtkStaticPlaneCutter&) = delete; - void operator=(const vtkStaticPlaneCutter&) = delete; -}; - -#endif diff --git a/src/Plugins/StaticMesh/vtkTemporalUGWavelet.cxx b/src/Plugins/StaticMesh/vtkTemporalUGWavelet.cxx deleted file mode 100644 index f1f2a007..00000000 --- a/src/Plugins/StaticMesh/vtkTemporalUGWavelet.cxx +++ /dev/null @@ -1,140 +0,0 @@ -/*========================================================================= - - Program: Visualization Toolkit - Module: vtkRTAnalyticSource.cxx - - Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen - All rights reserved. - See Copyright.txt or http://www.kitware.com/Copyright.htm for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notice for more information. - -=========================================================================*/ -#include "vtkTemporalUGWavelet.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -vtkStandardNewMacro(vtkTemporalUGWavelet); - -// ---------------------------------------------------------------------------- -vtkTemporalUGWavelet::vtkTemporalUGWavelet() -{ - this->Cache = vtkUnstructuredGrid::New(); - this->NumberOfTimeSteps = 10; -} - -// ---------------------------------------------------------------------------- -vtkTemporalUGWavelet::~vtkTemporalUGWavelet() -{ - this->Cache->Delete(); -} - -//---------------------------------------------------------------------------- -int vtkTemporalUGWavelet::FillOutputPortInformation(int vtkNotUsed(port), vtkInformation* info) -{ - info->Set(vtkDataObject::DATA_TYPE_NAME(), "vtkUnstructuredGrid"); - return 1; -} - -// ---------------------------------------------------------------------------- -int vtkTemporalUGWavelet::RequestInformation( - vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector) -{ - vtkInformation* outInfo = outputVector->GetInformationObject(0); - double range[2] = { 0, static_cast(this->NumberOfTimeSteps - 1) }; - outInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_RANGE(), range, 2); - double* outTimes = new double[this->NumberOfTimeSteps]; - for (int i = 0; i < this->NumberOfTimeSteps; i++) - { - outTimes[i] = i; - } - outInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_STEPS(), outTimes, this->NumberOfTimeSteps); - outInfo->Set(CAN_HANDLE_PIECE_REQUEST(), 1); - return Superclass::RequestInformation(request, inputVector, outputVector); -} - -// ---------------------------------------------------------------------------- -int vtkTemporalUGWavelet::RequestData( - vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector) -{ - vtkInformation* outInfo = outputVector->GetInformationObject(0); - vtkUnstructuredGrid* data = vtkUnstructuredGrid::GetData(outInfo); - if (this->CacheMTime < this->GetMTime()) - { - // Create an output vector to recover the output image data - // RequestData method - vtkNew tmpOutputVec; - vtkNew image; - tmpOutputVec->Copy(outputVector, 1); - vtkInformation* tmpOutInfo = tmpOutputVec->GetInformationObject(0); - tmpOutInfo->Set(vtkDataObject::DATA_OBJECT(), image.Get()); - - // Generate wavelet - int ret = this->Superclass::RequestData(request, inputVector, tmpOutputVec.Get()); - if (ret == 0) - { - return ret; - } - - // Transform it to unstructured grid - vtkNew tetra; - tetra->SetInputData(image.Get()); - tetra->Update(); - - // Create the cache - this->Cache->ShallowCopy(tetra->GetOutput()); - this->CacheMTime.Modified(); - } - - // Use the cache - data->ShallowCopy(this->Cache); - - double t = outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP()); - - // Generate tPoint array - vtkIdType nbPoints = data->GetNumberOfPoints(); - vtkNew pointArray; - pointArray->SetName("tPoint"); - pointArray->SetNumberOfValues(nbPoints); - data->GetPointData()->AddArray(pointArray.Get()); - for (vtkIdType i = 0; i < nbPoints; i++) - { - pointArray->SetValue( - i, static_cast(i + t * (nbPoints / this->NumberOfTimeSteps)) % nbPoints); - } - - // Generate tCell array - vtkIdType nbCells = data->GetNumberOfCells(); - vtkNew cellArray; - cellArray->SetName("tCell"); - cellArray->SetNumberOfValues(nbCells); - data->GetCellData()->AddArray(cellArray.Get()); - - for (vtkIdType i = 0; i < nbCells; i++) - { - cellArray->SetValue(i, static_cast(i + t * (nbCells / this->NumberOfTimeSteps)) % nbCells); - } - - return 1; -} - -// ---------------------------------------------------------------------------- -void vtkTemporalUGWavelet::PrintSelf(ostream& os, vtkIndent indent) -{ - this->Superclass::PrintSelf(os, indent); - os << indent << "NumberOfTimeSteps: " << this->NumberOfTimeSteps << endl; -} diff --git a/src/Plugins/StaticMesh/vtkTemporalUGWavelet.h b/src/Plugins/StaticMesh/vtkTemporalUGWavelet.h deleted file mode 100644 index 2758debd..00000000 --- a/src/Plugins/StaticMesh/vtkTemporalUGWavelet.h +++ /dev/null @@ -1,67 +0,0 @@ -/*========================================================================= - - Program: Visualization Toolkit - Module: vtkTemporalUGWavelet.h - - Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen - All rights reserved. - See Copyright.txt or http://www.kitware.com/Copyright.htm for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notice for more information. - -=========================================================================*/ -/** - * @class vtkTemporalUGWavelet - * @brief Create a Temporal Unstructured Grid Wavelet with a static mesh - * - * vtkTemporalUGWavelet specialize vtkRTAnalyticSource to create - * a wavelet converted to vtkUnstructuredGrid, with timesteps. - * The "tPoint" and "tCell" arrays are the only data actually changing over time - * make the output a static mesh with data evolving over time. -*/ - -#ifndef vtkTemporalUGWavelet_h -#define vtkTemporalUGWavelet_h - -#include - -class vtkUnstructuredGrid; - -class vtkTemporalUGWavelet : public vtkRTAnalyticSource -{ -public: - static vtkTemporalUGWavelet* New(); - vtkTypeMacro(vtkTemporalUGWavelet, vtkRTAnalyticSource); - void PrintSelf(ostream& os, vtkIndent indent) override; - - //@{ - /** - * Set/Get the number of time steps. Initial value is 10. - */ - vtkSetMacro(NumberOfTimeSteps, int); - vtkGetMacro(NumberOfTimeSteps, int); - //@} - -protected: - vtkTemporalUGWavelet(); - ~vtkTemporalUGWavelet(); - - int FillOutputPortInformation(int vtkNotUsed(port), vtkInformation* info) override; - - int RequestInformation(vtkInformation* request, vtkInformationVector** inputVector, - vtkInformationVector* outputVector) override; - - int RequestData(vtkInformation*, vtkInformationVector**, vtkInformationVector*) override; - - int NumberOfTimeSteps; - vtkUnstructuredGrid* Cache; - vtkTimeStamp CacheMTime; - -private: - vtkTemporalUGWavelet(const vtkTemporalUGWavelet&) = delete; - void operator=(const vtkTemporalUGWavelet&) = delete; -}; - -#endif diff --git a/src/Plugins/TableReader/CMakeLists.txt b/src/Plugins/TableReader/CMakeLists.txt index 1ed1789c..ec7566b5 100644 --- a/src/Plugins/TableReader/CMakeLists.txt +++ b/src/Plugins/TableReader/CMakeLists.txt @@ -1,47 +1,30 @@ -# Copyright (C) 2010-2019 CEA/DEN, EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# +cmake_minimum_required(VERSION 3.8) +project(TableReaderPlugin) +find_package(ParaView REQUIRED) -# TableReader plugin consists of two parts: -# 1. Table reader - reads tables in Post-Pro specific format -# 2. "Table To 3D" filter - creates 3D representation of a table +include(GNUInstallDirs) +set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_BINDIR}") +set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_LIBDIR}") +set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_LIBDIR}") -cmake_minimum_required(VERSION 2.4) -if(COMMAND cmake_policy) - cmake_policy(SET CMP0003 NEW) -endif(COMMAND cmake_policy) +set("_paraview_plugin_default_${CMAKE_PROJECT_NAME}" ON) +paraview_plugin_scan( + ENABLE_BY_DEFAULT YES + PLUGIN_FILES "${CMAKE_CURRENT_SOURCE_DIR}/plugin/paraview.plugin" + PROVIDES_PLUGINS plugins + REQUIRES_MODULES required_modules) -project(TableReader) +foreach(module IN LISTS required_modules) + if(NOT TARGET "${module}") + message("Missing required module: ${module}") + return() + endif() +endforeach() -# Find ParaView -FIND_PACKAGE(ParaView REQUIRED) -if(NOT ParaView_FOUND) - MESSAGE(FATAL_ERROR "Please locate ParaView." ) -ENDIF(NOT ParaView_FOUND) -INCLUDE(${PARAVIEW_USE_FILE}) - -# Standard CMake option for building libraries shared or static by default. -OPTION(BUILD_SHARED_LIBS - "Build with shared libraries." - ${VTK_BUILD_SHARED_LIBS}) - -# Add subdirectories -INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}/Reader ${CMAKE_CURRENT_SOURCE_DIR}/TableTo3DFilter) -ADD_SUBDIRECTORY(Reader) -ADD_SUBDIRECTORY(TableTo3DFilter) -ADD_SUBDIRECTORY(ParaViewPlugin) \ No newline at end of file +set(BUILD_SHARED_LIBS ON) +paraview_plugin_build( + RUNTIME_DESTINATION "${CMAKE_INSTALL_BINDIR}" + LIBRARY_DESTINATION "${CMAKE_INSTALL_LIBDIR}" + LIBRARY_SUBDIRECTORY "${PARAVIEW_PLUGIN_SUBDIR}" + PLUGINS ${plugins} + AUTOLOAD ${plugins}) diff --git a/src/Plugins/TableReader/ParaViewPlugin/CMakeLists.txt b/src/Plugins/TableReader/ParaViewPlugin/CMakeLists.txt deleted file mode 100644 index ad7558b6..00000000 --- a/src/Plugins/TableReader/ParaViewPlugin/CMakeLists.txt +++ /dev/null @@ -1,90 +0,0 @@ -# Copyright (C) 2010-2019 CEA/DEN, EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# - -IF(PARAVIEW_BUILD_QT_GUI) - - INCLUDE(UseQtExt) - # Custom object panel for the reader and - # custom display panel for line chart view - QT_WRAP_UIC(CLIENT_UI_SRCS - Resources/UI/TableReaderPanel.ui - Resources/UI/CustomXYChartDisplayPanel.ui - ) - - QT_WRAP_MOC(MOC_SRCS - pqTableReaderPanel.h - pqTableTo3DPanel.h - pqCustomChartDisplayPanelImplementation.h - pqCustomXYChartDisplayPanel.h - pqCustomPlotSettingsModel.h - ) - - SET(CLIENT_SRCS - pqTableReaderPanel.cxx - pqTableTo3DPanel.cxx - pqCustomChartDisplayPanelImplementation.cxx - pqCustomXYChartDisplayPanel.cxx - pqCustomPlotSettingsModel.cxx - ) - - ADD_PARAVIEW_OBJECT_PANEL( - TABLEREADER_IFACES TABLEREADER_IFACE_SRCS - CLASS_NAME pqTableReaderPanel - XML_NAME TableReader - XML_GROUP sources) - - ADD_PARAVIEW_OBJECT_PANEL( - TABLETO3D_IFACES TABLETO3D_IFACE_SRCS - CLASS_NAME pqTableTo3DPanel - XML_NAME TableTo3D - XML_GROUP filters) - - # define the server-side and the client-side parts - # of the table reader plugin - ADD_PARAVIEW_PLUGIN(TableReaderPlugin "1.0" - SOURCES ../Reader/TableParser.cxx - SERVER_MANAGER_SOURCES ../Reader/vtkVisuTableReader.cxx ../TableTo3DFilter/vtkTableTo3D.cxx - SERVER_MANAGER_XML Resources/TableReaderServer.xml Resources/TableTo3DServer.xml - GUI_INTERFACES ${TABLEREADER_IFACES} ${TABLETO3D_IFACES} pqCustomChartDisplayPanel - GUI_SOURCES ${CLIENT_SRCS} - ${CLIENT_UI_SRCS} - ${TABLEREADER_IFACE_SRCS} - ${TABLETO3D_IFACE_SRCS} - ${MOC_SRCS} - GUI_RESOURCES Resources/TableReader.qrc Resources/TableTo3D.qrc) - -ELSE(PARAVIEW_BUILD_QT_GUI) - - # define the server-side part of the table reader plugin - ADD_PARAVIEW_PLUGIN(TableReaderPlugin "1.0" - SOURCES TableParser.cxx - SERVER_MANAGER_SOURCES vtkVisuTableReader.cxx vtkTableTo3D.cxx - SERVER_MANAGER_XML Resources/TableReaderServer.xml Resources/TableTo3DServer.xml) - -ENDIF(PARAVIEW_BUILD_QT_GUI) - -TARGET_LINK_LIBRARIES(TableReaderPlugin vtkVisuTableReader vtkTableTo3D) - -# Install -INSTALL( - TARGETS TableReaderPlugin - RUNTIME DESTINATION lib/paraview - LIBRARY DESTINATION lib/paraview - ARCHIVE DESTINATION lib/paraview -) \ No newline at end of file diff --git a/src/Plugins/TableReader/ParaViewPlugin/Resources/TableReader.qrc b/src/Plugins/TableReader/ParaViewPlugin/Resources/TableReader.qrc deleted file mode 100644 index ab412631..00000000 --- a/src/Plugins/TableReader/ParaViewPlugin/Resources/TableReader.qrc +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/src/Plugins/TableReader/ParaViewPlugin/Resources/TableReaderServer.xml b/src/Plugins/TableReader/ParaViewPlugin/Resources/TableReaderServer.xml deleted file mode 100644 index db7b3934..00000000 --- a/src/Plugins/TableReader/ParaViewPlugin/Resources/TableReaderServer.xml +++ /dev/null @@ -1,86 +0,0 @@ - - - - - - - - - - - - - This property specifies the file name for the table reader. - - - - - - - When set to true, the reader will detect numeric columns and create - vtkDoubleArray or vtkIntArray for those instead of vtkStringArray. - - - - - - - When set to true, the reader will interpret the first string as - column titles. - - - - - - This property defines string to be used to separate table values. - - - - - - This property defines the number of table to read. - - - - - - - Names of available tables. - - - - - - - - - - diff --git a/src/Plugins/TableReader/ParaViewPlugin/Resources/TableTo3D.qrc b/src/Plugins/TableReader/ParaViewPlugin/Resources/TableTo3D.qrc deleted file mode 100644 index 4ccb88c6..00000000 --- a/src/Plugins/TableReader/ParaViewPlugin/Resources/TableTo3D.qrc +++ /dev/null @@ -1,5 +0,0 @@ - - - TableTo3DClient.xml - - diff --git a/src/Plugins/TableReader/ParaViewPlugin/Resources/TableTo3DClient.xml b/src/Plugins/TableReader/ParaViewPlugin/Resources/TableTo3DClient.xml deleted file mode 100644 index c6547e7e..00000000 --- a/src/Plugins/TableReader/ParaViewPlugin/Resources/TableTo3DClient.xml +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/src/Plugins/TableReader/ParaViewPlugin/Resources/TableTo3DServer.xml b/src/Plugins/TableReader/ParaViewPlugin/Resources/TableTo3DServer.xml deleted file mode 100644 index a167b4b1..00000000 --- a/src/Plugins/TableReader/ParaViewPlugin/Resources/TableTo3DServer.xml +++ /dev/null @@ -1,78 +0,0 @@ - - - - - - - - - - - - - - - - This property specifies the input.. - - - - - - - Specify value to scale displacement. - - - - - - - When set to true, the filter will compute optimus scale factor, - the value entered by user will be ignored. - - - - - - - - - - This property determines type of presentation: surface of contour. - - - - - - - Specify number of contours for contour presentation type. - - - - - - diff --git a/src/Plugins/TableReader/ParaViewPlugin/Resources/UI/CustomLineChartDisplayPanel.ui b/src/Plugins/TableReader/ParaViewPlugin/Resources/UI/CustomLineChartDisplayPanel.ui deleted file mode 100644 index 0bfe9f6a..00000000 --- a/src/Plugins/TableReader/ParaViewPlugin/Resources/UI/CustomLineChartDisplayPanel.ui +++ /dev/null @@ -1,335 +0,0 @@ - - - CustomLineChartDisplayPanel - - - - 0 - 0 - 301 - 534 - - - - - - - <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> -<html><head><meta name="qrichtext" content="1" /><style type="text/css"> -p, li { white-space: pre-wrap; } -</style></head><body style=" font-family:'DejaVu Sans'; font-size:9pt; font-weight:400; font-style:normal;"> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Sans Serif';">Toggle visibility of this display's series.</p></body></html> - - - Use this option to show/hide all the line series in the chart. - - - Show Line Series in Chart - - - - - - - X Axis Data - - - - - - Select this option to use the indexes of the y-axis array for the x-axis points. - - - Use Array Index From Y Axis Data - - - true - - - false - - - - - - - Select this option to use a data array to define the x-axis points. - - - Use Data Array - - - false - - - - - - - false - - - Choose the name of the x-axis data array. - - - - - - - - - - - 0 - 0 - - - - Line Series - - - - 6 - - - 6 - - - - - Select the chart axes for the line series. - - - - Bottom-Left - - - - - Bottom-Right - - - - - Top-Left - - - - - Top-Right - - - - - - - - Select the line style for the series. - - - - None - - - - - Solid - - - - - Dash - - - - - Dot - - - - - Dash Dot - - - - - Dash Dot Dot - - - - - - - - Chart Axes - - - - - - - Line Style - - - - - - - Enter the thickness for the line. - - - 1 - - - 10 - - - 1 - - - - - - - Line Thickness - - - - - - - Press this button to choose a new color for the line. - - - Choose Color... - - - - - - - Line Color - - - - - - - Use this option to show/hide the line series in the chart. - - - Enable Line Series - - - - - - - - 0 - 0 - - - - This displays the list of line series. You can use the list to edit the series options. - - - QAbstractItemView::EditKeyPressed|QAbstractItemView::SelectedClicked - - - QAbstractItemView::ExtendedSelection - - - QAbstractItemView::SelectRows - - - false - - - - - - - Marker Style - - - - - - - - None - - - - - Cross - - - - - Plus - - - - - Square - - - - - Circle - - - - - Diamond - - - - - - - - - - - - pqColorChooserButton - QPushButton -
pqColorChooserButton.h
- 1 -
- - pqTreeView - QTreeView -
pqTreeView.h
-
-
- - ViewData - SeriesList - SeriesEnabled - ColorButton - Thickness - StyleList - - - - UseDataArray - toggled(bool) - XAxisArray - setEnabled(bool) - - - 80 - 363 - - - 209 - 363 - - - - -
diff --git a/src/Plugins/TableReader/ParaViewPlugin/Resources/UI/CustomXYChartDisplayPanel.ui b/src/Plugins/TableReader/ParaViewPlugin/Resources/UI/CustomXYChartDisplayPanel.ui deleted file mode 100644 index b7b2da5c..00000000 --- a/src/Plugins/TableReader/ParaViewPlugin/Resources/UI/CustomXYChartDisplayPanel.ui +++ /dev/null @@ -1,319 +0,0 @@ - - - CustomXYChartDisplayPanel - - - - 0 - 0 - 307 - 566 - - - - Form - - - - - - X Axis Data - - - - - - Select this option to use the indexes of the y-axis array for the x-axis points. - - - Use Array Index From Y Axis Data - - - true - - - false - - - - - - - Select this option to use a data array to define the x-axis points. - - - Use Data Array - - - false - - - - - - - false - - - Choose the name of the x-axis data array. - - - - - - - - - - - 0 - 0 - - - - Line Series - - - - - - - 0 - 0 - - - - This displays the list of line series. You can use the list to edit the series options. - - - QAbstractItemView::EditKeyPressed|QAbstractItemView::SelectedClicked - - - QAbstractItemView::ExtendedSelection - - - QAbstractItemView::SelectRows - - - false - - - - - - - Auto Select Items With The Same Units - - - - - - - Ignore Units - - - - - - - Line Color - - - - - - - Press this button to choose a new color for the line. - - - Choose Color... - - - - - - - Line Thickness - - - - - - - Enter the thickness for the line. - - - 1 - - - 10 - - - 1 - - - - - - - Line Style - - - - - - - Select the line style for the series. - - - - None - - - - - Solid - - - - - Dash - - - - - Dot - - - - - Dash Dot - - - - - Dash Dot Dot - - - - - - - - Marker Style - - - - - - - - None - - - - - Cross - - - - - Plus - - - - - Square - - - - - Circle - - - - - Diamond - - - - - - - - Chart Axes - - - - - - - Select the chart axes for the line series. - - - - Bottom-Left - - - - - Bottom-Right - - - - - Top-Left - - - - - Top-Right - - - - - - - - - - - Generate Axes Titles - - - - - - - - pqColorChooserButton - QPushButton -
pqColorChooserButton.h
- 1 -
- - pqTreeView - QTreeView -
pqTreeView.h
-
-
- - - - UseDataArray - toggled(bool) - XAxisArray - setEnabled(bool) - - - 104 - 362 - - - 178 - 361 - - - - -
diff --git a/src/Plugins/TableReader/ParaViewPlugin/Resources/UI/TableReaderPanel.ui b/src/Plugins/TableReader/ParaViewPlugin/Resources/UI/TableReaderPanel.ui deleted file mode 100644 index 691aeb6a..00000000 --- a/src/Plugins/TableReader/ParaViewPlugin/Resources/UI/TableReaderPanel.ui +++ /dev/null @@ -1,103 +0,0 @@ - - - TableReaderPanel - - - - 0 - 0 - 366 - 657 - - - - - 0 - 0 - - - - Form - - - - 9 - - - - - Import Options - - - - - - Detect Numeric Columns - - - - - - - Interpret First String As Column Titles - - - - - - - Value Delimiter - - - - - - - - - - Table - - - - - - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - - - 10 - - - 10 - - - false - - - false - - - true - - - diff --git a/src/Plugins/TableReader/ParaViewPlugin/pqCustomChartDisplayPanelImplementation.cxx b/src/Plugins/TableReader/ParaViewPlugin/pqCustomChartDisplayPanelImplementation.cxx deleted file mode 100644 index ca589ed6..00000000 --- a/src/Plugins/TableReader/ParaViewPlugin/pqCustomChartDisplayPanelImplementation.cxx +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// - -#include "pqCustomChartDisplayPanelImplementation.h" -#include "pqCustomXYChartDisplayPanel.h" - -#include "vtkSMProxy.h" - -#include "pqDataRepresentation.h" -#include "pqPipelineSource.h" - - -pqCustomChartDisplayPanelImplementation::pqCustomChartDisplayPanelImplementation(QObject* p): -QObject(p) -{ -} - -bool pqCustomChartDisplayPanelImplementation::canCreatePanel(pqRepresentation* repr) const -{ - if(!repr || !repr->getProxy() || - (repr->getProxy()->GetXMLName() != QString("XYChartRepresentation"))) - { - return false; - } - - pqDataRepresentation* dataRepr = qobject_cast(repr); - if(dataRepr) - { - pqPipelineSource* input = dataRepr->getInput(); - QString name = input->getProxy()->GetXMLName(); - if (name == "TableReader") - { - return true; - } - } - - return false; -} - -pqDisplayPanel* pqCustomChartDisplayPanelImplementation::createPanel(pqRepresentation* repr, QWidget* p) -{ - if(!repr || !repr->getProxy() || - (repr->getProxy()->GetXMLName() != QString("XYChartRepresentation"))) - { - return NULL; - } - - pqDataRepresentation* dataRepr = qobject_cast(repr); - if(dataRepr) - { - pqPipelineSource* input = dataRepr->getInput(); - QString name=input->getProxy()->GetXMLName(); - - if (name == "TableReader") - { - return new pqCustomXYChartDisplayPanel(repr, p); - } - } - - return NULL; -} - - diff --git a/src/Plugins/TableReader/ParaViewPlugin/pqCustomChartDisplayPanelImplementation.h b/src/Plugins/TableReader/ParaViewPlugin/pqCustomChartDisplayPanelImplementation.h deleted file mode 100644 index 3a7c7b21..00000000 --- a/src/Plugins/TableReader/ParaViewPlugin/pqCustomChartDisplayPanelImplementation.h +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// - -#ifndef _pqCustomChartDisplayPanelImplementation_h -#define _pqCustomChartDisplayPanelImplementation_h - -#include "pqDisplayPanelInterface.h" - -#include - -class QWidget; - -class pqCustomChartDisplayPanelImplementation : public QObject, - public pqDisplayPanelInterface -{ - Q_OBJECT - Q_INTERFACES(pqDisplayPanelInterface) - - public: - // Constructor - pqCustomChartDisplayPanelImplementation(){} - pqCustomChartDisplayPanelImplementation(QObject* p); - - // Destructor - virtual ~pqCustomChartDisplayPanelImplementation(){} - - // Returns true if this panel can be created for the given the proxy. - virtual bool canCreatePanel(pqRepresentation* proxy) const; - - // Creates a panel for the given proxy - virtual pqDisplayPanel* createPanel(pqRepresentation* proxy, QWidget* p); -}; - -#endif - diff --git a/src/Plugins/TableReader/ParaViewPlugin/pqCustomPlotSettingsModel.cxx b/src/Plugins/TableReader/ParaViewPlugin/pqCustomPlotSettingsModel.cxx deleted file mode 100644 index c30c88fa..00000000 --- a/src/Plugins/TableReader/ParaViewPlugin/pqCustomPlotSettingsModel.cxx +++ /dev/null @@ -1,218 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// - -#include "pqCustomPlotSettingsModel.h" - -#include "vtkSMChartRepresentationProxy.h" -#include "pqDataRepresentation.h" -#include "vtkWeakPointer.h" -#include "vtkSMPropertyHelper.h" - -#include - - -class pqCustomPlotSettingsModel::pqImplementation -{ -public: - pqImplementation() -{ -} - - vtkWeakPointer RepresentationProxy; - QPointer Representation; -}; - -pqCustomPlotSettingsModel::pqCustomPlotSettingsModel(QObject* parentObject) : - Superclass(parentObject), Implementation(new pqImplementation()) -{ -} - -pqCustomPlotSettingsModel::~pqCustomPlotSettingsModel() -{ - delete this->Implementation; -} - -//----------------------------------------------------------------------------- -void pqCustomPlotSettingsModel::setRepresentation(pqDataRepresentation* rep) -{ - Superclass::setRepresentation(rep); - - if (!rep || rep == this->Implementation->Representation) - { - return; - } - - if (this->Implementation->Representation) - { - QObject::disconnect(this->Implementation->Representation, 0, this, 0); - } - - this->Implementation->RepresentationProxy = - vtkSMChartRepresentationProxy::SafeDownCast(rep->getProxy()); - this->Implementation->Representation = rep; -} - -//----------------------------------------------------------------------------- -pqDataRepresentation* pqCustomPlotSettingsModel::representation() const -{ - return this->Implementation->Representation; -} - -//----------------------------------------------------------------------------- -bool pqCustomPlotSettingsModel::setData(const QModelIndex &idx, const QVariant &value, - int role) -{ - bool result = false; - if (idx.isValid() && idx.model() == this) - { - if (idx.column() == 1 && (role == Qt::DisplayRole || role == Qt::EditRole)) - { - QString name = value.toString(); - if (!name.isEmpty()) - { - this->setSeriesLabel(idx.row(), name); - } - } - else if(idx.column() == 0 && role == Qt::CheckStateRole) - { - result = true; - int checkstate = value.toInt(); - this->setSeriesEnabled(idx.row(), checkstate == Qt::Checked); - } - } - return result; -} - -//----------------------------------------------------------------------------- -void pqCustomPlotSettingsModel::setSeriesEnabled(int row, bool enabled) -{ - if (row >= 0 && row < this->rowCount(QModelIndex())) - { - int minRow = row; - int maxRow = row; - - if (enabled && !(this->IgnoreUnitsModeOn)) - { - QString unit = getUnit(QString(this->getSeriesName(row))); - - for (int i = 0; i < rowCount(QModelIndex()); i++) - { - if (i == row) - { - continue; - } - - bool rowChanged = false; - QString seriesName = QString(this->getSeriesName(i)); - QString seriesUnit = getUnit(seriesName); - - if ((seriesUnit != unit) && getSeriesEnabled(i)) - { - vtkSMPropertyHelper(this->Implementation->RepresentationProxy, - "SeriesVisibility").SetStatus(this->getSeriesName(i), 0); - rowChanged = true; - } - - if (!seriesUnit.isEmpty() && this->AutoSelectModeOn && - (seriesUnit == unit) && !getSeriesEnabled(i)) - { - vtkSMPropertyHelper(this->Implementation->RepresentationProxy, - "SeriesVisibility").SetStatus(this->getSeriesName(i), 1); - rowChanged = true; - } - - if (rowChanged) - { - if (i < minRow) - { - minRow = i; - } - else if (i > maxRow) - { - maxRow = i; - } - } - } - } - - vtkSMPropertyHelper(this->Implementation->RepresentationProxy, - "SeriesVisibility").SetStatus(this->getSeriesName(row), enabled ? 1 : 0); - this->Implementation->RepresentationProxy->UpdateVTKObjects(); - - this->setSeriesColor(row, this->getSeriesColor(row)); - QModelIndex topLeft = this->createIndex(minRow, 0); - QModelIndex bottomRight = this->createIndex(maxRow, 0); - emit this->dataChanged(topLeft, bottomRight); - emit this->redrawChart(); - this->updateCheckState(0, Qt::Horizontal); - } -} - -//----------------------------------------------------------------------------- -void pqCustomPlotSettingsModel::SetIgnoreUnitsModeOn(bool enabled) -{ - this->IgnoreUnitsModeOn = enabled; - - if (this->IgnoreUnitsModeOn) - { - this->setCheckable(0, Qt::Horizontal, true); - this->setCheckState(0, Qt::Horizontal, Qt::Unchecked); - } - else - { - this->setCheckState(0, Qt::Horizontal, Qt::Unchecked); - this->setCheckable(0, Qt::Horizontal, false); - } -} - -//----------------------------------------------------------------------------- -void pqCustomPlotSettingsModel::SetAutoSelectModeOn(bool enabled) -{ - this->AutoSelectModeOn = enabled; - if (enabled && !this->IgnoreUnitsModeOn) - { - for (int i = 0; i < rowCount(QModelIndex()); i++) - { - if (getSeriesEnabled(i)) - { - setSeriesEnabled(i, true); - break; - } - } - } -} - -//----------------------------------------------------------------------------- -QString pqCustomPlotSettingsModel::getUnit(const QString& seriesName) -{ - QString unit(""); - - int index1 = seriesName.lastIndexOf("]"); - if (index1 == seriesName.size() - 1) - { - int index2 = seriesName.lastIndexOf(" ["); - if (index2 > 0) - { - int start = index2 + 2; - unit = seriesName.mid(index2 + 2, index1 - start); - } - } - - return unit; -} diff --git a/src/Plugins/TableReader/ParaViewPlugin/pqCustomPlotSettingsModel.h b/src/Plugins/TableReader/ParaViewPlugin/pqCustomPlotSettingsModel.h deleted file mode 100644 index 7ac61a24..00000000 --- a/src/Plugins/TableReader/ParaViewPlugin/pqCustomPlotSettingsModel.h +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// - -#ifndef __pqCustomPlotSettingsModel_h -#define __pqCustomPlotSettingsModel_h - -#include "pqPlotSettingsModel.h" - -class pqDataRepresentation; - -class pqCustomPlotSettingsModel : public pqPlotSettingsModel -{ - typedef pqPlotSettingsModel Superclass; - - Q_OBJECT - -public: - pqCustomPlotSettingsModel(QObject* parent = 0); - ~pqCustomPlotSettingsModel(); - - void setRepresentation(pqDataRepresentation* rep); - pqDataRepresentation* representation() const; - - /// \brief Sets the data for the given model index. - /// \param index The model index. - /// \param value The new data for the given role. - /// \param role The role to set data for. - /// \return True if the data was changed successfully. - virtual bool setData(const QModelIndex &index, const QVariant &value, - int role=Qt::EditRole); - - void SetIgnoreUnitsModeOn(bool enabled); - void SetAutoSelectModeOn(bool enabled); - -public slots: - - // Description: - // API to enable series. - void setSeriesEnabled(int row, bool enabled); - -private: - QString getUnit(const QString& seriesName); - -private: - class pqImplementation; - pqImplementation* Implementation; - - bool IgnoreUnitsModeOn; - bool AutoSelectModeOn; -}; - -#endif diff --git a/src/Plugins/TableReader/ParaViewPlugin/pqCustomXYChartDisplayPanel.cxx b/src/Plugins/TableReader/ParaViewPlugin/pqCustomXYChartDisplayPanel.cxx deleted file mode 100644 index 09c5a444..00000000 --- a/src/Plugins/TableReader/ParaViewPlugin/pqCustomXYChartDisplayPanel.cxx +++ /dev/null @@ -1,510 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// - -#include "pqCustomXYChartDisplayPanel.h" -#include "ui_CustomXYChartDisplayPanel.h" - -#include "vtkEventQtSlotConnect.h" -#include "vtkSMChartRepresentationProxy.h" -#include "vtkSMPropertyHelper.h" -#include "vtkDataArray.h" -#include "vtkDataObject.h" -#include "vtkSMArraySelectionDomain.h" -#include "vtkSMIntVectorProperty.h" -#include "vtkSMProxy.h" -#include "vtkSmartPointer.h" -#include "vtkTable.h" -#include "vtkChart.h" -#include "vtkWeakPointer.h" - -#include -#include -#include -#include -#include -#include -#include - -#include "pqDataInformationModel.h" -#include "pqComboBoxDomain.h" -#include "pqPropertyLinks.h" -#include "pqSignalAdaptorCompositeTreeWidget.h" -#include "pqSignalAdaptors.h" -#include "pqSMAdaptor.h" -#include "pqXYChartView.h" -#include "pqDataRepresentation.h" -#include "pqCustomPlotSettingsModel.h" - -#include - -//----------------------------------------------------------------------------- -class pqCustomXYChartDisplayPanel::pqInternal : public Ui::CustomXYChartDisplayPanel -{ -public: - pqInternal() -{ - this->SettingsModel = 0; - this->XAxisArrayDomain = 0; - this->XAxisArrayAdaptor = 0; - - this->VTKConnect = vtkSmartPointer::New(); -} - - ~pqInternal() - { - delete this->SettingsModel; - delete this->XAxisArrayDomain; - delete this->XAxisArrayAdaptor; - } - - vtkWeakPointer ChartRepresentation; - pqCustomPlotSettingsModel* SettingsModel; - pqComboBoxDomain* XAxisArrayDomain; - pqSignalAdaptorComboBox* XAxisArrayAdaptor; - pqPropertyLinks Links; - - vtkSmartPointer VTKConnect; - - bool InChange; -}; - -//----------------------------------------------------------------------------- -pqCustomXYChartDisplayPanel::pqCustomXYChartDisplayPanel( - pqRepresentation* display,QWidget* p) -: pqDisplayPanel(display, p) -{ - this->Internal = new pqCustomXYChartDisplayPanel::pqInternal(); - this->Internal->setupUi(this); - - this->Internal->SettingsModel = new pqCustomPlotSettingsModel(this); - this->Internal->SeriesList->setModel(this->Internal->SettingsModel); - - this->Internal->XAxisArrayAdaptor = new pqSignalAdaptorComboBox( - this->Internal->XAxisArray); - - QObject::connect( - this->Internal->SeriesList, SIGNAL(activated(const QModelIndex &)), - this, SLOT(activateItem(const QModelIndex &))); - QItemSelectionModel *model = this->Internal->SeriesList->selectionModel(); - QObject::connect(model, - SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)), - this, SLOT(updateOptionsWidgets())); - QObject::connect(model, - SIGNAL(currentChanged(const QModelIndex &, const QModelIndex &)), - this, SLOT(updateOptionsWidgets())); - QObject::connect(this->Internal->SettingsModel, SIGNAL(modelReset()), - this, SLOT(updateOptionsWidgets())); - QObject::connect(this->Internal->SettingsModel, SIGNAL(redrawChart()), - this, SLOT(updateAllViews())); - QObject::connect(this->Internal->XAxisArray, SIGNAL(currentIndexChanged(int)), - this, SLOT(updateAllViews())); - - QObject::connect(this->Internal->UseArrayIndex, SIGNAL(toggled(bool)), - this, SLOT(useArrayIndexToggled(bool))); - QObject::connect(this->Internal->UseDataArray, SIGNAL(toggled(bool)), - this, SLOT(useDataArrayToggled(bool))); - - QObject::connect( - this->Internal->ColorButton, SIGNAL(chosenColorChanged(const QColor &)), - this, SLOT(setCurrentSeriesColor(const QColor &))); - QObject::connect(this->Internal->Thickness, SIGNAL(valueChanged(int)), - this, SLOT(setCurrentSeriesThickness(int))); - QObject::connect(this->Internal->StyleList, SIGNAL(currentIndexChanged(int)), - this, SLOT(setCurrentSeriesStyle(int))); - QObject::connect(this->Internal->AxisList, SIGNAL(currentIndexChanged(int)), - this, SLOT(setCurrentSeriesAxes(int))); - QObject::connect(this->Internal->MarkerStyleList, SIGNAL(currentIndexChanged(int)), - this, SLOT(setCurrentSeriesMarkerStyle(int))); - - QObject::connect( - this->Internal->AutoSelect, SIGNAL(toggled(bool)), - this, SLOT(autoSelectToggled(bool))); - - QObject::connect( - this->Internal->IgnoreUnits, SIGNAL(toggled(bool)), - this, SLOT(ignoreUnitsToggled(bool))); - - QObject::connect( - this->Internal->GenerateAxesTitles, SIGNAL(toggled(bool)), - this, SLOT(updateViewOptions())); - QObject::connect(this->Internal->SettingsModel, SIGNAL(redrawChart()), - this, SLOT(updateViewOptions())); - - resetUnitsControls(); - - this->setDisplay(display); - - QObject::connect(&this->Internal->Links, SIGNAL(qtWidgetChanged()), - this, SLOT(reloadSeries()), Qt::QueuedConnection); - QObject::connect(&this->Internal->Links, SIGNAL(qtWidgetChanged()), - this->Internal->SettingsModel, SLOT(reload())); -} - -//----------------------------------------------------------------------------- -pqCustomXYChartDisplayPanel::~pqCustomXYChartDisplayPanel() -{ - delete this->Internal; -} - -//----------------------------------------------------------------------------- -void pqCustomXYChartDisplayPanel::reloadSeries() -{ - updateViewOptions(); - - this->updateAllViews(); - this->updateOptionsWidgets(); -} - -//----------------------------------------------------------------------------- -void pqCustomXYChartDisplayPanel::setDisplay(pqRepresentation* disp) -{ - this->setEnabled(false); - - vtkSMChartRepresentationProxy* proxy = - vtkSMChartRepresentationProxy::SafeDownCast(disp->getProxy()); - this->Internal->ChartRepresentation = proxy; - if (!this->Internal->ChartRepresentation) - { - qWarning() << "pqCustomXYChartDisplayPanel given a representation proxy " - "that is not an XYChartRepresentation. Cannot edit."; - return; - } - - // this is essential to ensure that when you undo-redo, the representation is - // indeed update-to-date, thus ensuring correct domains etc. - proxy->UpdatePipeline(); - - // The model for the plot settings - this->Internal->SettingsModel->setRepresentation( - qobject_cast(disp)); - - // Connect to the new properties.pqComboBoxDomain will ensure that - // when ever the domain changes the widget is updated as well. - this->Internal->XAxisArrayDomain = new pqComboBoxDomain( - this->Internal->XAxisArray, proxy->GetProperty("XArrayName")); - this->Internal->Links.addPropertyLink(this->Internal->XAxisArrayAdaptor, - "currentText", SIGNAL(currentTextChanged(const QString&)), - proxy, proxy->GetProperty("XArrayName")); - - // Link to set whether the index is used for the x axis - this->Internal->Links.addPropertyLink( - this->Internal->UseArrayIndex, "checked", - SIGNAL(toggled(bool)), - proxy, proxy->GetProperty("UseIndexForXAxis")); - - // Proxy changed - this->Internal->VTKConnect->Connect(proxy->GetProperty("SeriesNamesInfo"), - vtkCommand::PropertyModifiedEvent, this, SLOT(resetUnitsControls())); - - this->changeDialog(disp); - - this->setEnabled(true); - - this->reloadSeries(); -} - -//----------------------------------------------------------------------------- -void pqCustomXYChartDisplayPanel::changeDialog(pqRepresentation* disp) -{ - vtkSMChartRepresentationProxy* proxy = - vtkSMChartRepresentationProxy::SafeDownCast(disp->getProxy()); - bool visible = true; - if (QString("Bar") == vtkSMPropertyHelper(proxy,"ChartType").GetAsString()) - { - visible = false; - } - - this->Internal->Thickness->setVisible(visible); - this->Internal->ThicknessLabel->setVisible(visible); - this->Internal->StyleList->setVisible(visible); - this->Internal->StyleListLabel->setVisible(visible); - this->Internal->MarkerStyleList->setVisible(visible); - this->Internal->MarkerStyleListLabel->setVisible(visible); - this->Internal->AxisList->setVisible(false); - this->Internal->AxisListLabel->setVisible(false); -} - -//----------------------------------------------------------------------------- -void pqCustomXYChartDisplayPanel::activateItem(const QModelIndex &index) -{ - if(!this->Internal->ChartRepresentation - || !index.isValid() || index.column() != 1) - { - // We are interested in clicks on the color swab alone. - return; - } - - // Get current color - QColor color = this->Internal->SettingsModel->getSeriesColor(index.row()); - - // Show color selector dialog to get a new color - color = QColorDialog::getColor(color, this); - if (color.isValid()) - { - // Set the new color - this->Internal->SettingsModel->setSeriesColor(index.row(), color); - this->Internal->ColorButton->blockSignals(true); - this->Internal->ColorButton->setChosenColor(color); - this->Internal->ColorButton->blockSignals(false); - this->updateAllViews(); - } -} - -//----------------------------------------------------------------------------- -void pqCustomXYChartDisplayPanel::updateOptionsWidgets() -{ - QItemSelectionModel *model = this->Internal->SeriesList->selectionModel(); - if(model) - { - // Show the options for the current item. - QModelIndex current = model->currentIndex(); - QModelIndexList indexes = model->selectedIndexes(); - if((!current.isValid() || !model->isSelected(current)) && - indexes.size() > 0) - { - current = indexes.last(); - } - - this->Internal->ColorButton->blockSignals(true); - this->Internal->Thickness->blockSignals(true); - this->Internal->StyleList->blockSignals(true); - this->Internal->MarkerStyleList->blockSignals(true); - this->Internal->AxisList->blockSignals(true); - if (current.isValid()) - { - int seriesIndex = current.row(); - QColor color = this->Internal->SettingsModel->getSeriesColor(seriesIndex); - this->Internal->ColorButton->setChosenColor(color); - this->Internal->Thickness->setValue( - this->Internal->SettingsModel->getSeriesThickness(seriesIndex)); - this->Internal->StyleList->setCurrentIndex( - this->Internal->SettingsModel->getSeriesStyle(seriesIndex)); - this->Internal->MarkerStyleList->setCurrentIndex( - this->Internal->SettingsModel->getSeriesMarkerStyle(seriesIndex)); - this->Internal->AxisList->setCurrentIndex( - this->Internal->SettingsModel->getSeriesAxisCorner(seriesIndex)); - } - else - { - this->Internal->ColorButton->setChosenColor(Qt::white); - this->Internal->Thickness->setValue(1); - this->Internal->StyleList->setCurrentIndex(0); - this->Internal->MarkerStyleList->setCurrentIndex(0); - this->Internal->AxisList->setCurrentIndex(0); - } - - this->Internal->ColorButton->blockSignals(false); - this->Internal->Thickness->blockSignals(false); - this->Internal->StyleList->blockSignals(false); - this->Internal->MarkerStyleList->blockSignals(false); - this->Internal->AxisList->blockSignals(false); - - // Disable the widgets if nothing is selected or current. - bool hasItems = indexes.size() > 0; - this->Internal->ColorButton->setEnabled(hasItems); - this->Internal->Thickness->setEnabled(hasItems); - this->Internal->StyleList->setEnabled(hasItems); - this->Internal->MarkerStyleList->setEnabled(hasItems); - this->Internal->AxisList->setEnabled(hasItems); - } -} - -//----------------------------------------------------------------------------- -void pqCustomXYChartDisplayPanel::setCurrentSeriesColor(const QColor &color) -{ - QItemSelectionModel *model = this->Internal->SeriesList->selectionModel(); - if(model) - { - this->Internal->InChange = true; - QModelIndexList indexes = model->selectedIndexes(); - QModelIndexList::Iterator iter = indexes.begin(); - for( ; iter != indexes.end(); ++iter) - { - this->Internal->SettingsModel->setSeriesColor(iter->row(), color); - } - this->Internal->InChange = false; - } -} - -//----------------------------------------------------------------------------- -void pqCustomXYChartDisplayPanel::setCurrentSeriesThickness(int thickness) -{ - QItemSelectionModel *model = this->Internal->SeriesList->selectionModel(); - if (model) - { - this->Internal->InChange = true; - QModelIndexList indexes = model->selectedIndexes(); - QModelIndexList::Iterator iter = indexes.begin(); - for( ; iter != indexes.end(); ++iter) - { - this->Internal->SettingsModel->setSeriesThickness(iter->row(), thickness); - } - this->Internal->InChange = false; - } -} - -//----------------------------------------------------------------------------- -void pqCustomXYChartDisplayPanel::setCurrentSeriesStyle(int style) -{ - QItemSelectionModel *model = this->Internal->SeriesList->selectionModel(); - if (model) - { - this->Internal->InChange = true; - QModelIndexList indexes = model->selectedIndexes(); - QModelIndexList::Iterator iter = indexes.begin(); - for( ; iter != indexes.end(); ++iter) - { - this->Internal->SettingsModel->setSeriesStyle(iter->row(), style); - } - this->Internal->InChange = false; - } -} - -//----------------------------------------------------------------------------- -void pqCustomXYChartDisplayPanel::setCurrentSeriesMarkerStyle(int style) -{ - QItemSelectionModel *model = this->Internal->SeriesList->selectionModel(); - if (model) - { - this->Internal->InChange = true; - QModelIndexList indexes = model->selectedIndexes(); - QModelIndexList::Iterator iter = indexes.begin(); - for( ; iter != indexes.end(); ++iter) - { - this->Internal->SettingsModel->setSeriesMarkerStyle(iter->row(), style); - } - this->Internal->InChange = false; - } -} - -//----------------------------------------------------------------------------- -void pqCustomXYChartDisplayPanel::setCurrentSeriesAxes(int) -{ - -} - -//----------------------------------------------------------------------------- -Qt::CheckState pqCustomXYChartDisplayPanel::getEnabledState() const -{ - Qt::CheckState enabledState = Qt::Unchecked; - - return enabledState; -} - -//----------------------------------------------------------------------------- -void pqCustomXYChartDisplayPanel::useArrayIndexToggled(bool toggle) -{ - this->Internal->UseDataArray->setChecked(!toggle); -} - -//----------------------------------------------------------------------------- -void pqCustomXYChartDisplayPanel::useDataArrayToggled(bool toggle) -{ - this->Internal->UseArrayIndex->setChecked(!toggle); - this->updateAllViews(); -} - -//----------------------------------------------------------------------------- -void pqCustomXYChartDisplayPanel::autoSelectToggled(bool checked) -{ - this->Internal->SettingsModel->SetAutoSelectModeOn(checked); -} - -//----------------------------------------------------------------------------- -void pqCustomXYChartDisplayPanel::ignoreUnitsToggled(bool checked) -{ - this->Internal->AutoSelect->setEnabled(!checked); - this->Internal->SettingsModel->SetIgnoreUnitsModeOn(checked); - this->Internal->SettingsModel->SetAutoSelectModeOn(!checked && - this->Internal->AutoSelect->isChecked()); -} - -//----------------------------------------------------------------------------- -void pqCustomXYChartDisplayPanel::resetUnitsControls() -{ - this->Internal->IgnoreUnits->setCheckState(Qt::Checked); - this->Internal->AutoSelect->setCheckState(Qt::Unchecked); -} - -//----------------------------------------------------------------------------- -void pqCustomXYChartDisplayPanel::updateViewOptions() -{ - pqRepresentation* disp = this->getRepresentation(); - if (!disp || !this->Internal->ChartRepresentation) - { - return; - } - - pqXYChartView* view = qobject_cast(disp->getView()); - if (view && view->getProxy()) - { - vtkSMProxy* proxy = view->getProxy(); - - QList values = - pqSMAdaptor::getMultipleElementProperty(proxy->GetProperty("AxisTitle")); - if (values.size() < 2) - { - return; - } - - if (!this->Internal->GenerateAxesTitles->isChecked()) - { - values.insert(0, QVariant("")); - values.insert(1, QVariant("")); - } - else - { - // Set X axis title - int useIndexForXAxis = vtkSMPropertyHelper( - this->Internal->ChartRepresentation, "UseIndexForXAxis").GetAsInt(); - - QString xTitle(""); - if (!useIndexForXAxis) - { - xTitle = vtkSMPropertyHelper(this->Internal->ChartRepresentation, "XArrayName").GetAsString(); - } - - // Set Y axis title - int nbRows = this->Internal->SettingsModel->rowCount(QModelIndex()); - int nbEnabled = 0; - int row = 0; - for (int i = 0; i < nbRows && nbEnabled < 2; i++) - { - if (this->Internal->SettingsModel->getSeriesEnabled(i)) - { - nbEnabled++; - row = i; - } - } - - QString yTitle(""); - if (nbEnabled == 1) - { - yTitle = this->Internal->SettingsModel->getSeriesName(row); - } - values.insert(0, QVariant(yTitle)); - values.insert(1, QVariant(xTitle)); - } - - pqSMAdaptor::setMultipleElementProperty(proxy->GetProperty("AxisTitle"), values); - - view->getProxy()->UpdateVTKObjects(); - view->render(); - } -} diff --git a/src/Plugins/TableReader/ParaViewPlugin/pqCustomXYChartDisplayPanel.h b/src/Plugins/TableReader/ParaViewPlugin/pqCustomXYChartDisplayPanel.h deleted file mode 100644 index 6b730beb..00000000 --- a/src/Plugins/TableReader/ParaViewPlugin/pqCustomXYChartDisplayPanel.h +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// - -#ifndef __pqCustomXYChartDisplayPanel_h -#define __pqCustomXYChartDisplayPanel_h - -#include "pqDisplayPanel.h" - -class pqRepresentation; -class pqDataInformationModel; -class QModelIndex; - -/// Editor widget for XY chart displays. -class pqCustomXYChartDisplayPanel : public pqDisplayPanel -{ - Q_OBJECT -public: - pqCustomXYChartDisplayPanel(pqRepresentation* display, QWidget* parent=0); - virtual ~pqCustomXYChartDisplayPanel(); - -public slots: - /// Reloads the series list from the display. - void reloadSeries(); - -protected slots: - /// Slot to listen to clicks for changing color. - void activateItem(const QModelIndex &index); - - void updateOptionsWidgets(); - - void setCurrentSeriesColor(const QColor &color); - - void setCurrentSeriesThickness(int thickness); - - void setCurrentSeriesStyle(int listIndex); - - void setCurrentSeriesAxes(int listIndex); - - void setCurrentSeriesMarkerStyle(int listIndex); - - void useArrayIndexToggled(bool); - - void useDataArrayToggled(bool); - - /// Unit controls - void autoSelectToggled(bool checked); - void ignoreUnitsToggled(bool checked); - - /// Reset state of the controls relative to units - void resetUnitsControls(); - - /// Update view options - void updateViewOptions(); - -private: - pqCustomXYChartDisplayPanel(const pqCustomXYChartDisplayPanel&); // Not implemented. - void operator=(const pqCustomXYChartDisplayPanel&); // Not implemented. - - /// Set the display whose properties this editor is editing. - /// This call will raise an error if the display is not - /// an XYChartRepresentation proxy. - void setDisplay(pqRepresentation* display); - - /// Disable/enable elements of the dialog based on the chart type. - void changeDialog(pqRepresentation* display); - - Qt::CheckState getEnabledState() const; - - class pqInternal; - pqInternal* Internal; - - pqDataInformationModel* Model; -}; - -#endif diff --git a/src/Plugins/TableReader/ParaViewPlugin/pqTableReaderPanel.cxx b/src/Plugins/TableReader/ParaViewPlugin/pqTableReaderPanel.cxx deleted file mode 100644 index ab92496e..00000000 --- a/src/Plugins/TableReader/ParaViewPlugin/pqTableReaderPanel.cxx +++ /dev/null @@ -1,112 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// - -#include "pqTableReaderPanel.h" - -#include "vtkSMProxy.h" -#include "vtkSMStringVectorProperty.h" -#include "vtkProcessModule.h" - -#include "pqPropertyLinks.h" - -#include -#include - - -class pqTableReaderPanel::pqUI: public QObject, public Ui::TableReaderPanel -{ -public: - pqUI(pqTableReaderPanel* p) : QObject(p) -{ -} - - ~pqUI() - { - } - - pqPropertyLinks Links; -}; - - -pqTableReaderPanel::pqTableReaderPanel(pqProxy* proxy, QWidget* p) : - Superclass(proxy, p) -{ - this->UI = new pqUI(this); - this->UI->setupUi(this); - - this->linkServerManagerProperties(); - this->updateAvailableTables(false); - - this->connect(this->UI->ValueDelimiter, SIGNAL(textChanged(const QString&)), - this, SLOT(onDelimiterChanged(const QString&))); - this->connect(this->UI->TableNames, SIGNAL(currentIndexChanged(int)), - this, SLOT(onCurrentTableChanged(int))); -} - -pqTableReaderPanel::~pqTableReaderPanel() -{ -} - -void pqTableReaderPanel::onCurrentTableChanged(int currentTableIndex) -{ - this->setModified(); -} - -void pqTableReaderPanel::onDelimiterChanged(const QString& value) -{ - this->updateAvailableTables(true); -} - -void pqTableReaderPanel::linkServerManagerProperties() -{ - this->UI->Links.addPropertyLink(this->UI->TableNames, "currentIndex", - SIGNAL(currentIndexChanged(int)), this->proxy(), - this->proxy()->GetProperty("TableNumber")); - - // To hook up the rest widgets - this->Superclass::linkServerManagerProperties(); -} - -void pqTableReaderPanel::updateAvailableTables(const bool keepCurrent) -{ - vtkSMStringVectorProperty* prop = vtkSMStringVectorProperty::SafeDownCast( - this->proxy()->GetProperty("AvailableTables")); - - int currentIndex = this->UI->TableNames->currentIndex(); - QString currentText = this->UI->TableNames->currentText(); - - this->UI->TableNames->clear(); - - for(int id = 0; id < prop->GetNumberOfElements(); id++) - { - QString text(prop->GetElement(id)); - if (text.isEmpty()) - { - text = QString("Table:%1").arg(id); - } - this->UI->TableNames->addItem(text); - } - - if (keepCurrent && - currentIndex < this->UI->TableNames->maxCount() && - currentText == this->UI->TableNames->itemText(currentIndex)) - { - this->UI->TableNames->setCurrentIndex(currentIndex); - } -} diff --git a/src/Plugins/TableReader/ParaViewPlugin/pqTableReaderPanel.h b/src/Plugins/TableReader/ParaViewPlugin/pqTableReaderPanel.h deleted file mode 100644 index c8131353..00000000 --- a/src/Plugins/TableReader/ParaViewPlugin/pqTableReaderPanel.h +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// - -#ifndef _pqTableReaderPanel_h -#define _pqTableReaderPanel_h - -#include "ui_TableReaderPanel.h" - -#include "pqNamedObjectPanel.h" - -class QSpinBox; - -class pqTableReaderPanel: public pqNamedObjectPanel -{ -Q_OBJECT - typedef pqNamedObjectPanel Superclass; -public: - // Constructor - pqTableReaderPanel(pqProxy* proxy, QWidget* p = NULL); - - // Destructor - ~pqTableReaderPanel(); - -protected slots: - void onDelimiterChanged(const QString& value); - void onCurrentTableChanged(int currentTableIndex); - -protected: - // Populate widgets with properties from the server manager - virtual void linkServerManagerProperties(); - - // Update the list with available table names - void updateAvailableTables(const bool keepCurrent); - - class pqUI; - pqUI* UI; -}; - -#endif - diff --git a/src/Plugins/TableReader/ParaViewPlugin/pqTableTo3DPanel.cxx b/src/Plugins/TableReader/ParaViewPlugin/pqTableTo3DPanel.cxx deleted file mode 100644 index 81c62ffd..00000000 --- a/src/Plugins/TableReader/ParaViewPlugin/pqTableTo3DPanel.cxx +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// - -#include "pqTableTo3DPanel.h" - -#include -#include -#include - -pqTableTo3DPanel::pqTableTo3DPanel(pqProxy* proxy, QWidget* p) : -Superclass(proxy, p) -{ - QLineEdit* scaleFactor = this->findChild("ScaleFactor"); - QCheckBox* useOptimusScale = this->findChild("UseOptimusScale"); - QComboBox* presentationType = this->findChild("PresentationType"); - QWidget* numberContours = this->findChild("NumberOfContours"); - - if (scaleFactor && useOptimusScale) - { - this->connect(useOptimusScale, SIGNAL(toggled(bool)), - this, SLOT(onScaleModeChanged(bool))); - onScaleModeChanged(useOptimusScale->isChecked()); - } - - if (presentationType && numberContours) - { - this->connect(presentationType, SIGNAL(currentIndexChanged(const QString &)), - this, SLOT(onPrsTypeChanged(const QString &))); - onPrsTypeChanged(presentationType->currentText()); - } -} - -pqTableTo3DPanel::~pqTableTo3DPanel() -{ -} - -void pqTableTo3DPanel::onScaleModeChanged(bool checked) -{ - QLineEdit* scaleFactor = this->findChild("ScaleFactor"); - if (scaleFactor) - { - scaleFactor->setEnabled(!checked); - } -} - -void pqTableTo3DPanel::onPrsTypeChanged(const QString& type) -{ - QWidget* numberContours = this->findChild("NumberOfContours"); - if (numberContours) - { - numberContours->setEnabled(type == "Contour"); - } -} diff --git a/src/Plugins/TableReader/ParaViewPlugin/pqTableTo3DPanel.h b/src/Plugins/TableReader/ParaViewPlugin/pqTableTo3DPanel.h deleted file mode 100644 index c8b04e1e..00000000 --- a/src/Plugins/TableReader/ParaViewPlugin/pqTableTo3DPanel.h +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// - -#ifndef _pqTableTo3DPanel_h -#define _pqTableTo3DPanel_h - -#include "pqAutoGeneratedObjectPanel.h" - -class pqTableTo3DPanel: public pqAutoGeneratedObjectPanel -{ -Q_OBJECT - typedef pqAutoGeneratedObjectPanel Superclass; -public: - // Constructor - pqTableTo3DPanel(pqProxy* proxy, QWidget* p); - - /// Destructor - ~pqTableTo3DPanel(); - -protected slots: - void onScaleModeChanged(bool checked); - void onPrsTypeChanged(const QString& type); - -}; - -#endif diff --git a/src/Plugins/TableReader/Reader/CMakeLists.txt b/src/Plugins/TableReader/Reader/CMakeLists.txt deleted file mode 100644 index 3704935b..00000000 --- a/src/Plugins/TableReader/Reader/CMakeLists.txt +++ /dev/null @@ -1,34 +0,0 @@ -# Copyright (C) 2010-2019 CEA/DEN, EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# - -SET(READER_SRCS - TableParser.cxx - vtkVisuTableReader.cxx - ) - -ADD_LIBRARY(vtkVisuTableReader ${READER_SRCS}) - -TARGET_LINK_LIBRARIES(vtkVisuTableReader ${VTK_LIBRARIES} ${vtkInfovis} ${QT_LIBRARIES}) - -INSTALL( - TARGETS vtkVisuTableReader - RUNTIME DESTINATION lib/salome - LIBRARY DESTINATION lib/salome - ARCHIVE DESTINATION lib/salome - ) diff --git a/src/Plugins/TableReader/Reader/TableParser.cxx b/src/Plugins/TableReader/Reader/TableParser.cxx deleted file mode 100644 index 30bb7a00..00000000 --- a/src/Plugins/TableReader/Reader/TableParser.cxx +++ /dev/null @@ -1,261 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// - -#include "TableParser.h" - -#include -#include - -// STL includes -#include -#include -#include - -using namespace std; - -int getLine(std::ifstream& streamIn, QString& str) -{ - char tmp; - std::ostringstream streamOut; - - while (streamIn.get(tmp)) { - streamOut< GetTableNames(const char* fname, const char* separator, - const bool firstStringAsTitles) - { - Table2D table; - std::vector tableTitles; - - int nb = 0; - table = GetTable(fname, separator, nb, firstStringAsTitles); - while (table.Check()) { - tableTitles.push_back(table.myTitle); - table = GetTable(fname, separator, ++nb, firstStringAsTitles); - } - - return tableTitles; - } - -Table2D GetTable(const char* fname, const char* separator, const int tableNb, - const bool firstStringAsTitles) -{ - std::ifstream streamIn(fname); - - if(!streamIn.good()) - { - throw std::runtime_error("Unable to open input Post-Pro table file."); - } - - QString tmp; - int count = 0; - do { - // Find beginning of table (tables are separated by empty lines) - while (getLine(streamIn, tmp) && tmp.trimmed() == ""); - - Table2D table2D; - - bool isFirst = true; - while (!streamIn.eof() && tmp.trimmed() != "") - { - QString data = tmp.trimmed(); - QString cmt = ""; - QString keyword = ""; - - // Split string to data and comment (comment starts from '#' symbol) - int index = tmp.indexOf("#"); - if (index >= 0) - { - data = tmp.left(index).trimmed(); - cmt = tmp.mid(index+1).trimmed(); - } - - // If comment is not empty, try to get keyword from it (separated by ':' symbol) - if (!cmt.isEmpty()) - { - int index1 = cmt.indexOf(":"); - - if (index1 >= 0) - { - QString tmpstr = cmt.left(index1).trimmed(); - if (tmpstr == QString("TITLE") || - tmpstr == QString("COLUMN_TITLES") || - tmpstr == QString("COLUMN_UNITS") || - tmpstr == QString("COMMENT")) - { - keyword = tmpstr; - cmt = cmt.mid(index1+1).trimmed(); - } - } - } - - // If data is empty, process only comment - if (data.isEmpty()) - { - // If keyword is found, try to process it - // elsewise it is a simple comment, just ignore it - if (!keyword.isEmpty()) - { - if (keyword == QString( "TITLE" )) - { - QString title = cmt; - if (table2D.myTitle != "") { - title = QString(table2D.myTitle.c_str()) + QString(" ") + title; - } - table2D.myTitle = title.toLatin1().constData(); - } - else if (keyword == QString("COLUMN_TITLES")) - { - // Comment may contain column headers - QStringList strList = cmt.split("|", QString::SkipEmptyParts); - - for ( int i = 0; i < strList.count(); i++ ) - { - QString tmpstr = strList[i].trimmed(); - table2D.myColumnTitles.push_back(tmpstr.toLatin1().constData()); - } - } - else if (keyword == QString("COLUMN_UNITS")) - { - // Comment may contain column units - QStringList strList = cmt.split( " ", QString::SkipEmptyParts ); - - for (int i = 0; i < strList.count(); i++) - { - QString tmpstr = strList[i].trimmed(); - table2D.myColumnUnits.push_back(tmpstr.toLatin1().constData()); - } - } - else if (keyword == QString("COMMENT")) - { - // Keyword 'COMMENT' processing can be here, - // currently it is ignored - } - } - else { - // Simple comment processing can be here, - // currently it is ignored - } - } - // If data is not empty, try to process it - else { - Table2D::Row row; - - QString datar1 = data.replace(QRegExp("\t"), " "); - QStringList valList = datar1.split(separator, QString::SkipEmptyParts); - if(table2D.myColumnTitles.size() == 0 && isFirst && firstStringAsTitles) - { - for ( int i = 0; i < valList.count(); i++ ) - { - QString tmpstr = valList[i].trimmed(); - table2D.myColumnTitles.push_back(tmpstr.toLatin1().constData()); - } - } - else - { - if (!cmt.isEmpty()) - { - row.myTitle = cmt.toLatin1().constData(); - } - - for (int i = 0; i < valList.count(); i++) - { - if (valList[i].trimmed() != "") - { - Table2D::Value val = valList[i].trimmed().toLatin1().constData(); - row.myValues.push_back(val); - } - } - - if(row.myValues.size() > 0) - { - table2D.myRows.push_back(row); - } - } - - isFirst = false; - } - getLine(streamIn, tmp); - } - - - if(table2D.Check()) - { - if (count == tableNb) - { - if (QString::fromStdString(table2D.myTitle).isEmpty()) - { - table2D.myTitle = QString("Table:%1").arg(tableNb).toStdString(); - } - return table2D; - } - count++; - } - - } while (!streamIn.eof()); - - streamIn.close(); - - // Return empty table - Table2D emptyTable; - return emptyTable; -} diff --git a/src/Plugins/TableReader/Reader/TableParser.h b/src/Plugins/TableReader/Reader/TableParser.h deleted file mode 100644 index 4ac018d9..00000000 --- a/src/Plugins/TableReader/Reader/TableParser.h +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// - -#ifndef __TableParser_h_ -#define __TableParser_h_ - -#include -#include - -struct Table2D -{ - typedef std::string Value; - typedef std::vector Values; - - struct Row - { - std::string myTitle; - std::string myUnit; - Values myValues; - }; - - std::string myTitle; - std::vector myColumnUnits; - std::vector myColumnTitles; - - typedef std::vector Rows; - Rows myRows; - - bool Check(); -}; - -std::vector GetTableNames(const char* fname, const char* separator, - const bool firstStringAsTitles); -Table2D GetTable(const char* fname, const char* separator, const int tableNb, - const bool firstStringAsTitles); - -#endif //__TableParser_h_ diff --git a/src/Plugins/TableReader/Reader/vtkVisuTableReader.cxx b/src/Plugins/TableReader/Reader/vtkVisuTableReader.cxx deleted file mode 100644 index d855c11e..00000000 --- a/src/Plugins/TableReader/Reader/vtkVisuTableReader.cxx +++ /dev/null @@ -1,204 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// - -#include "vtkVisuTableReader.h" -#include "TableParser.h" - -#include "vtkObjectFactory.h" -#include "vtkTable.h" -#include "vtkInformationVector.h" -#include "vtkInformation.h" -#include "vtkStreamingDemandDrivenPipeline.h" -#include "vtkVariantArray.h" -#include "vtkStringArray.h" -#include "vtkStringToNumeric.h" - -#include -#include - -#include // STL include -#include // STL include -using namespace std; - -//vtkCxxRevisionMacro(vtkVisuTableReader, "$Revision$"); -vtkStandardNewMacro(vtkVisuTableReader); - -vtkVisuTableReader::vtkVisuTableReader(): - FileName(0) -{ - this->SetNumberOfInputPorts(0); - this->SetNumberOfOutputPorts(1); - - this->FileName = NULL; - - this->DetectNumericColumns = true; - this->FirstStringAsTitles = false; - - this->TableNumber = 0; - - this->ValueDelimiter = 0; - this->SetValueDelimiter(" "); - - this->AvailableTables = vtkStringArray::New(); -} - -vtkVisuTableReader::~vtkVisuTableReader() -{ - this->SetFileName(0); - this->SetValueDelimiter(0); - this->AvailableTables->Delete(); -} - -int vtkVisuTableReader::CanReadFile(const char* fname) -{ - return 1; -} - -void vtkVisuTableReader::PrintSelf(ostream& os, vtkIndent indent) -{ - this->Superclass::PrintSelf(os, indent); - os << indent << "FileName: " - << (this->FileName ? this->FileName : "(none)") << endl; - os << indent << "DetectNumericColumns: " - << (this->DetectNumericColumns? "true" : "false") << endl; - os << indent << "ValueDelimiter: " - << (this->ValueDelimiter ? this->ValueDelimiter : "(none)") << endl; - os << indent << "TableNumber: " << this->TableNumber<< endl; -} - -int vtkVisuTableReader::RequestData(vtkInformation*, - vtkInformationVector**, - vtkInformationVector* outputVector) -{ - vtkTable* const output_table = vtkTable::GetData(outputVector); - - try - { - vtkInformation* const outInfo = outputVector->GetInformationObject(0); - if(outInfo->Has(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()) && - outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()) > 0) - { - return 1; - } - - // If the filename is not defined - if(!this->FileName || this->TableNumber < 0) - { - return 1; - } - - // Read table with the given number from the file - Table2D table = GetTable(this->FileName, this->ValueDelimiter, - this->TableNumber, this->FirstStringAsTitles); - - // Set table name - output_table->GetInformation()->Set(vtkDataObject::FIELD_NAME(), - table.myTitle.c_str()); - - int nbRows = table.myRows.size(); - int nbCols = table.myRows[0].myValues.size(); - - for (int col=0; col < nbCols; col++) - { - vtkStringArray* newCol = vtkStringArray::New(); - newCol->SetNumberOfValues(nbRows); - - // Set value - for (int row=0; row < nbRows; row++) - { - newCol->SetValue(row, table.myRows[row].myValues[col].c_str()); - } - - // Set title - bool hasUnit = !table.myColumnUnits[col].empty(); - - if (table.myColumnTitles[col].empty()) - { - vtksys_ios::stringstream buffer; - if (hasUnit) - { - buffer << col <<" [" << table.myColumnUnits[col].c_str() << "]"; - } - else - { - buffer << col; - } - newCol->SetName(buffer.str().c_str()); - } - else - { - if (hasUnit) - { - vtksys_ios::stringstream buffer; - buffer << table.myColumnTitles[col].c_str() - <<" [" << table.myColumnUnits[col].c_str() << "]"; - newCol->SetName(buffer.str().c_str()); - } - else - { - newCol->SetName(table.myColumnTitles[col].c_str()); - } - } - - output_table->AddColumn(newCol); - newCol->Delete(); - } - - // Detect numeric columns if needed - if (this->DetectNumericColumns) - { - vtkStringToNumeric* convertor = vtkStringToNumeric::New(); - vtkTable* clone = output_table->NewInstance(); - clone->ShallowCopy(output_table); - convertor->SetInputData(clone); - convertor->Update(); - clone->Delete(); - output_table->ShallowCopy(convertor->GetOutputDataObject(0)); - convertor->Delete(); - } - } - catch(vtksys_stl::exception& e) - { - vtkErrorMacro(<< "caught exception: " << e.what() << endl); - output_table->Initialize(); - } - catch(...) - { - vtkErrorMacro(<< "caught unknown exception." << endl); - output_table->Initialize(); - } - - return 1; -} - -vtkStringArray* vtkVisuTableReader::GetAvailableTables() -{ - this->AvailableTables->Initialize(); - - vector titles = - GetTableNames(this->FileName, this->ValueDelimiter, - this->FirstStringAsTitles); - - for(int i = 0; i < titles.size(); i++) - { - this->AvailableTables->InsertNextValue(titles[i].c_str()); - } - - return this->AvailableTables; -} diff --git a/src/Plugins/TableReader/Reader/vtkVisuTableReader.h b/src/Plugins/TableReader/Reader/vtkVisuTableReader.h deleted file mode 100644 index 8339df33..00000000 --- a/src/Plugins/TableReader/Reader/vtkVisuTableReader.h +++ /dev/null @@ -1,103 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// - -#ifndef __vtkVisuTableReader_h_ -#define __vtkVisuTableReader_h_ - -#include "vtkTableAlgorithm.h" - -class vtkStringArray; - -class VTK_EXPORT vtkVisuTableReader: public vtkTableAlgorithm -{ -public: - static vtkVisuTableReader* New(); - vtkTypeMacro(vtkVisuTableReader, vtkTableAlgorithm) - void PrintSelf(ostream& os, vtkIndent indent); - - // Description: - // Specifies the name of the file - vtkGetStringMacro(FileName); - vtkSetStringMacro(FileName); - - // Description: - // When set to true, the reader will detect numeric columns and create - // vtkDoubleArray or vtkIntArray for those instead of vtkStringArray. - vtkSetMacro(DetectNumericColumns, bool); - vtkGetMacro(DetectNumericColumns, bool); - vtkBooleanMacro(DetectNumericColumns, bool); - - // Description: - // When set to true, the reader will interpret the first string as - // column titles. - vtkSetMacro(FirstStringAsTitles, bool); - vtkGetMacro(FirstStringAsTitles, bool); - vtkBooleanMacro(FirstStringAsTitles, bool); - - // Description: - // Specifies the number of the table - vtkSetMacro(TableNumber, int); - vtkGetMacro(TableNumber, int); - - // Description: - // Specifies string that will be used to separate values - vtkSetStringMacro(ValueDelimiter); - vtkGetStringMacro(ValueDelimiter); - - // Description: - // Determine whether the given file can be read - virtual int CanReadFile(const char* fname); - - // Description: - // Returns the available table names. - virtual vtkStringArray* GetAvailableTables(); - -protected: - vtkVisuTableReader(); - ~vtkVisuTableReader(); - - // Description: - // This is called by the superclass. - virtual int RequestData(vtkInformation*, vtkInformationVector**, - vtkInformationVector*); - - // name of the file to read from - char* FileName; - - // defines whether to detect numeric columns - bool DetectNumericColumns; - - // defines whether to treat first string as column titles - bool FirstStringAsTitles; - - // number of the table to read - int TableNumber; - - // string that will be used to separate values - char* ValueDelimiter; - - // Available table names - vtkStringArray* AvailableTables; - -private: - vtkVisuTableReader(const vtkVisuTableReader&); // Not implemented. - void operator=(const vtkVisuTableReader&); // Not implemented. -}; - -#endif //__vtkVisuTableReader_h_ diff --git a/src/Plugins/TableReader/TableTo3DFilter/CMakeLists.txt b/src/Plugins/TableReader/TableTo3DFilter/CMakeLists.txt deleted file mode 100644 index 432eb4c7..00000000 --- a/src/Plugins/TableReader/TableTo3DFilter/CMakeLists.txt +++ /dev/null @@ -1,33 +0,0 @@ -# Copyright (C) 2010-2019 CEA/DEN, EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# - -SET(TABLETO3D_SRCS - vtkTableTo3D.cxx - ) - -ADD_LIBRARY(vtkTableTo3D ${TABLETO3D_SRCS}) - -TARGET_LINK_LIBRARIES(vtkTableTo3D ${VTK_LIBRARIES}) - -INSTALL( - TARGETS vtkTableTo3D - RUNTIME DESTINATION lib/salome - LIBRARY DESTINATION lib/salome - ARCHIVE DESTINATION lib/salome - ) diff --git a/src/Plugins/TableReader/TableTo3DFilter/vtkTableTo3D.cxx b/src/Plugins/TableReader/TableTo3DFilter/vtkTableTo3D.cxx deleted file mode 100644 index 50a853be..00000000 --- a/src/Plugins/TableReader/TableTo3DFilter/vtkTableTo3D.cxx +++ /dev/null @@ -1,214 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// - -#include "vtkTableTo3D.h" - -#include "vtkSmartPointer.h" -#include "vtkDoubleArray.h" -#include "vtkVariantArray.h" -#include "vtkObjectFactory.h" -#include "vtkPointData.h" -#include "vtkPoints.h" -#include "vtkPolyData.h" -#include "vtkTable.h" -#include "vtkInformation.h" -#include "vtkStructuredGrid.h" -#include "vtkStructuredGridGeometryFilter.h" -#include "vtkWarpScalar.h" -#include "vtkContourFilter.h" - -vtkStandardNewMacro(vtkTableTo3D); -//vtkCxxRevisionMacro(vtkTableTo3D, "$Revision$"); - - -vtkTableTo3D::vtkTableTo3D() -{ - this->ScaleFactor = 1.0; - this->UseOptimusScale = true; - this->PresentationType = TABLETO3D_SURFACE; - this->NumberOfContours = 32; -} - -vtkTableTo3D::~vtkTableTo3D() -{ -} - -int vtkTableTo3D::FillInputPortInformation( - int vtkNotUsed(port), vtkInformation* info) -{ - info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkTable"); - return 1; -} - -int vtkTableTo3D::RequestData(vtkInformation* vtkNotUsed(request), - vtkInformationVector** inputVector, vtkInformationVector* outputVector) -{ - vtkTable* input = vtkTable::GetData(inputVector[0], 0); - vtkPolyData* output = vtkPolyData::GetData(outputVector, 0); - - if (input->GetNumberOfRows() == 0 ||input->GetNumberOfColumns() < 2) - { - return 1; - } - - vtkIdType xSize = input->GetNumberOfRows(); - vtkIdType ySize = input->GetNumberOfColumns() - 1; - vtkIdType nbPoints = xSize * ySize; - - vtkDataArray* xAxis = vtkDataArray::SafeDownCast(input->GetColumn(0)); - if (!xAxis) - { - vtkErrorMacro("The first column is not numeric."); - return 1; - } - - double xRange = xAxis->GetTuple1(xSize - 1) - xAxis->GetTuple1(0); - double yDelta = xRange / ySize; - - vtkSmartPointer yAxis = - vtkSmartPointer::New(); - yAxis->SetNumberOfValues(ySize); - for (vtkIdType i = 0; i < ySize; i++ ) - { - yAxis->SetValue(i, i*yDelta); - } - - vtkSmartPointer points = - vtkSmartPointer::New(); - points->SetNumberOfPoints(nbPoints); - - vtkSmartPointer pointsIdMapper = - vtkSmartPointer::New(); - pointsIdMapper->SetName("POINTS_ID_MAPPER"); - pointsIdMapper->SetNumberOfComponents(2); - pointsIdMapper->SetNumberOfTuples(nbPoints); - int *pointsIdMapperPtr = pointsIdMapper->GetPointer(0); - - for (vtkIdType i = 0, pntId = 0; i < ySize; i++) - { - for (vtkIdType j = 0; j < xSize; j++, pntId++) - { - points->SetPoint(pntId, xAxis->GetTuple1(j), - yAxis->GetValue(i), - 0.0); - - *pointsIdMapperPtr++ = pntId; - *pointsIdMapperPtr++ = 0; - } - } - - vtkSmartPointer scalars = - vtkSmartPointer::New(); - scalars->SetNumberOfComponents(1); - scalars->SetNumberOfTuples(nbPoints); - double *scalarsPtr = scalars->GetPointer(0); - for (vtkIdType i = 0; i < ySize; i++) - { - vtkDataArray* col = - vtkDataArray::SafeDownCast(input->GetColumn(i + 1)); - - if (!col) - { - vtkErrorMacro("Column "<< i <<"is not numeric."); - return 1; - } - - for ( vtkIdType j = 0; j < xSize; j++ ) - { - double value = col->GetTuple1(j); - *scalarsPtr++ = value; - } - } - - vtkSmartPointer structuredGrid = - vtkSmartPointer::New(); - structuredGrid->SetPoints(points); - - structuredGrid->SetDimensions(xSize, ySize, 1); - - // structuredGrid->GetPointData()->AddArray(pointsIdMapper); - if (input->GetInformation()->Has(vtkDataObject::FIELD_NAME())) - { - scalars->SetName(input->GetInformation()->Get(vtkDataObject::FIELD_NAME())); - } - else - { - scalars->SetName("Table"); - } - structuredGrid->GetPointData()->SetScalars(scalars); - - vtkSmartPointer geomFilter = - vtkSmartPointer::New(); - geomFilter->SetInputData(structuredGrid); - geomFilter->Update(); - - vtkSmartPointer warpScalar = - vtkSmartPointer::New(); - - double scaleFactor = this->ScaleFactor; - if (this->UseOptimusScale) - { - double range[2]; - geomFilter->GetOutput()->GetScalarRange(range); - double length = geomFilter->GetOutput()->GetLength(); - if (range[1] > 0) - { - scaleFactor = length / range[1] * 0.3; - } - else - { - scaleFactor = 0; - } - } - - if (this->PresentationType == TABLETO3D_SURFACE) - { - warpScalar->SetInputConnection(geomFilter->GetOutputPort(0)); - warpScalar->SetScaleFactor(scaleFactor); - } - else - { - vtkSmartPointer contourFilter = - vtkSmartPointer::New(); - contourFilter->SetInputConnection(geomFilter->GetOutputPort(0)); - contourFilter->GenerateValues(this->NumberOfContours, - geomFilter->GetOutput()->GetScalarRange()); - warpScalar->SetInputConnection(contourFilter->GetOutputPort(0)); - warpScalar->SetScaleFactor(scaleFactor); - } - - warpScalar->Update(); - output->ShallowCopy(warpScalar->GetPolyDataOutput()); - - return 1; -} - -//---------------------------------------------------------------------------- -void vtkTableTo3D::PrintSelf(ostream& os, vtkIndent indent) -{ - this->Superclass::PrintSelf(os, indent); - - os << indent << "ScaleFactor: " << this->ScaleFactor << endl; - os << indent << "UseOptimusScale: " - << (this->UseOptimusScale? "true" : "false") << endl; - os << indent << "PresentationType: " - << ((this->PresentationType == TABLETO3D_SURFACE)? "Surface" : "Contour") - << endl; - os << indent << "NumberOfContours: " << this->NumberOfContours << endl; -} diff --git a/src/Plugins/TableReader/TableTo3DFilter/vtkTableTo3D.h b/src/Plugins/TableReader/TableTo3DFilter/vtkTableTo3D.h deleted file mode 100644 index 40bf7675..00000000 --- a/src/Plugins/TableReader/TableTo3DFilter/vtkTableTo3D.h +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (C) 2010-2019 CEA/DEN, EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// - -#ifndef __vtkTableTo3D_h -#define __vtkTableTo3D_h - -#include "vtkPolyDataAlgorithm.h" - -#define TABLETO3D_SURFACE 0 -#define TABLETO3D_CONTOUR 1 - -class VTK_EXPORT vtkTableTo3D : public vtkPolyDataAlgorithm -{ -public: - static vtkTableTo3D* New(); - vtkTypeMacro(vtkTableTo3D, vtkPolyDataAlgorithm); - void PrintSelf(ostream& os, vtkIndent indent); - - // Description: - // Specify value to scale diplacement. - vtkSetMacro(ScaleFactor, double); - vtkGetMacro(ScaleFactor, double); - - // Description: - // When set to true, the filter will compute optimus scale factor, - // the value of ScaleFactor variable will be ignored. - vtkSetMacro(UseOptimusScale, bool); - vtkGetMacro(UseOptimusScale, bool); - vtkBooleanMacro(UseOptimusScale, bool); - - // Description: - // Specify type of presentation: surface of contour. - vtkSetClampMacro(PresentationType, int, - TABLETO3D_SURFACE, TABLETO3D_CONTOUR); - vtkGetMacro(PresentationType, int); - - // Description: - // Specify number of contours for contour presentation type. - vtkSetMacro(NumberOfContours, int); - vtkGetMacro(NumberOfContours, int); - -protected: - vtkTableTo3D(); - ~vtkTableTo3D(); - - // Description: - // Overridden to specify that input must be a vtkTable. - virtual int FillInputPortInformation(int port, vtkInformation* info); - - // Description: - // Convert input vtkTable to vtkPolyData. - virtual int RequestData(vtkInformation* request, - vtkInformationVector** inputVector, vtkInformationVector* outputVector); - - double ScaleFactor; - bool UseOptimusScale; - int PresentationType; - int NumberOfContours; - -private: - vtkTableTo3D(const vtkTableTo3D&); // Not implemented. - void operator=(const vtkTableTo3D&); // Not implemented. -}; - -#endif diff --git a/src/Plugins/TableReader/plugin/CMakeLists.txt b/src/Plugins/TableReader/plugin/CMakeLists.txt new file mode 100644 index 00000000..47066645 --- /dev/null +++ b/src/Plugins/TableReader/plugin/CMakeLists.txt @@ -0,0 +1,14 @@ +paraview_add_plugin(TableReaderPlugin + VERSION "1.0" + MODULES TableReaderModule TableTo3DModule + MODULE_FILES + "${CMAKE_CURRENT_SOURCE_DIR}/TableReaderModule/vtk.module" + "${CMAKE_CURRENT_SOURCE_DIR}/TableTo3DModule/vtk.module" + SERVER_MANAGER_XML filters.xml sources.xml +) + +install(TARGETS TableReaderPlugin + RUNTIME DESTINATION lib/paraview + LIBRARY DESTINATION lib/paraview + ARCHIVE DESTINATION lib/paraview + ) diff --git a/src/Plugins/TableReader/plugin/Resources/CustomLineChartDisplayPanel.ui b/src/Plugins/TableReader/plugin/Resources/CustomLineChartDisplayPanel.ui new file mode 100644 index 00000000..0bfe9f6a --- /dev/null +++ b/src/Plugins/TableReader/plugin/Resources/CustomLineChartDisplayPanel.ui @@ -0,0 +1,335 @@ + + + CustomLineChartDisplayPanel + + + + 0 + 0 + 301 + 534 + + + + + + + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'DejaVu Sans'; font-size:9pt; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Sans Serif';">Toggle visibility of this display's series.</p></body></html> + + + Use this option to show/hide all the line series in the chart. + + + Show Line Series in Chart + + + + + + + X Axis Data + + + + + + Select this option to use the indexes of the y-axis array for the x-axis points. + + + Use Array Index From Y Axis Data + + + true + + + false + + + + + + + Select this option to use a data array to define the x-axis points. + + + Use Data Array + + + false + + + + + + + false + + + Choose the name of the x-axis data array. + + + + + + + + + + + 0 + 0 + + + + Line Series + + + + 6 + + + 6 + + + + + Select the chart axes for the line series. + + + + Bottom-Left + + + + + Bottom-Right + + + + + Top-Left + + + + + Top-Right + + + + + + + + Select the line style for the series. + + + + None + + + + + Solid + + + + + Dash + + + + + Dot + + + + + Dash Dot + + + + + Dash Dot Dot + + + + + + + + Chart Axes + + + + + + + Line Style + + + + + + + Enter the thickness for the line. + + + 1 + + + 10 + + + 1 + + + + + + + Line Thickness + + + + + + + Press this button to choose a new color for the line. + + + Choose Color... + + + + + + + Line Color + + + + + + + Use this option to show/hide the line series in the chart. + + + Enable Line Series + + + + + + + + 0 + 0 + + + + This displays the list of line series. You can use the list to edit the series options. + + + QAbstractItemView::EditKeyPressed|QAbstractItemView::SelectedClicked + + + QAbstractItemView::ExtendedSelection + + + QAbstractItemView::SelectRows + + + false + + + + + + + Marker Style + + + + + + + + None + + + + + Cross + + + + + Plus + + + + + Square + + + + + Circle + + + + + Diamond + + + + + + + + + + + + pqColorChooserButton + QPushButton +
pqColorChooserButton.h
+ 1 +
+ + pqTreeView + QTreeView +
pqTreeView.h
+
+
+ + ViewData + SeriesList + SeriesEnabled + ColorButton + Thickness + StyleList + + + + UseDataArray + toggled(bool) + XAxisArray + setEnabled(bool) + + + 80 + 363 + + + 209 + 363 + + + + +
diff --git a/src/Plugins/TableReader/plugin/Resources/CustomXYChartDisplayPanel.ui b/src/Plugins/TableReader/plugin/Resources/CustomXYChartDisplayPanel.ui new file mode 100644 index 00000000..b7b2da5c --- /dev/null +++ b/src/Plugins/TableReader/plugin/Resources/CustomXYChartDisplayPanel.ui @@ -0,0 +1,319 @@ + + + CustomXYChartDisplayPanel + + + + 0 + 0 + 307 + 566 + + + + Form + + + + + + X Axis Data + + + + + + Select this option to use the indexes of the y-axis array for the x-axis points. + + + Use Array Index From Y Axis Data + + + true + + + false + + + + + + + Select this option to use a data array to define the x-axis points. + + + Use Data Array + + + false + + + + + + + false + + + Choose the name of the x-axis data array. + + + + + + + + + + + 0 + 0 + + + + Line Series + + + + + + + 0 + 0 + + + + This displays the list of line series. You can use the list to edit the series options. + + + QAbstractItemView::EditKeyPressed|QAbstractItemView::SelectedClicked + + + QAbstractItemView::ExtendedSelection + + + QAbstractItemView::SelectRows + + + false + + + + + + + Auto Select Items With The Same Units + + + + + + + Ignore Units + + + + + + + Line Color + + + + + + + Press this button to choose a new color for the line. + + + Choose Color... + + + + + + + Line Thickness + + + + + + + Enter the thickness for the line. + + + 1 + + + 10 + + + 1 + + + + + + + Line Style + + + + + + + Select the line style for the series. + + + + None + + + + + Solid + + + + + Dash + + + + + Dot + + + + + Dash Dot + + + + + Dash Dot Dot + + + + + + + + Marker Style + + + + + + + + None + + + + + Cross + + + + + Plus + + + + + Square + + + + + Circle + + + + + Diamond + + + + + + + + Chart Axes + + + + + + + Select the chart axes for the line series. + + + + Bottom-Left + + + + + Bottom-Right + + + + + Top-Left + + + + + Top-Right + + + + + + + + + + + Generate Axes Titles + + + + + + + + pqColorChooserButton + QPushButton +
pqColorChooserButton.h
+ 1 +
+ + pqTreeView + QTreeView +
pqTreeView.h
+
+
+ + + + UseDataArray + toggled(bool) + XAxisArray + setEnabled(bool) + + + 104 + 362 + + + 178 + 361 + + + + +
diff --git a/src/Plugins/TableReader/plugin/Resources/TableReaderPanel.ui b/src/Plugins/TableReader/plugin/Resources/TableReaderPanel.ui new file mode 100644 index 00000000..691aeb6a --- /dev/null +++ b/src/Plugins/TableReader/plugin/Resources/TableReaderPanel.ui @@ -0,0 +1,103 @@ + + + TableReaderPanel + + + + 0 + 0 + 366 + 657 + + + + + 0 + 0 + + + + Form + + + + 9 + + + + + Import Options + + + + + + Detect Numeric Columns + + + + + + + Interpret First String As Column Titles + + + + + + + Value Delimiter + + + + + + + + + + Table + + + + + + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + + + 10 + + + 10 + + + false + + + false + + + true + + + diff --git a/src/Plugins/TableReader/plugin/TableReaderModule/CMakeLists.txt b/src/Plugins/TableReader/plugin/TableReaderModule/CMakeLists.txt new file mode 100644 index 00000000..33b4cb4a --- /dev/null +++ b/src/Plugins/TableReader/plugin/TableReaderModule/CMakeLists.txt @@ -0,0 +1,8 @@ +set(classes + vtkVisuTableReader +) + +vtk_module_add_module(TableReaderModule + FORCE_STATIC + CLASSES ${classes} +) diff --git a/src/Plugins/TableReader/plugin/TableReaderModule/TableParser.cxx b/src/Plugins/TableReader/plugin/TableReaderModule/TableParser.cxx new file mode 100644 index 00000000..9a3d0c14 --- /dev/null +++ b/src/Plugins/TableReader/plugin/TableReaderModule/TableParser.cxx @@ -0,0 +1,264 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// + +#include "TableParser.h" + +#include +#include + +// STL includes +#include +#include +#include + +using namespace std; + +int getLine(std::ifstream& streamIn, QString& str) +{ + char tmp; + std::ostringstream streamOut; + + while (streamIn.get(tmp)) + { + streamOut << tmp; + if (tmp == '\n') + break; + } + + streamOut << std::ends; + str = streamOut.str().c_str(); + + return !streamIn.eof(); +} + +bool Table2D::Check() +{ + if (myRows.empty()) + return false; + + int iEnd = myRows[0].myValues.size(); + if (iEnd == 0) + { + return false; + } + + if (myColumnTitles.size() != iEnd) + { + myColumnTitles.resize(iEnd); + } + + if (myColumnUnits.size() != iEnd) + { + myColumnUnits.resize(iEnd); + } + + int jEnd = myRows.size(); + for (int j = 0; j < jEnd; j++) + { + if (myRows[j].myValues.size() != iEnd) + { + return false; + } + } + + return true; +} + +std::vector GetTableNames( + const char* fname, const char* separator, const bool firstStringAsTitles) +{ + Table2D table; + std::vector tableTitles; + + int nb = 0; + table = GetTable(fname, separator, nb, firstStringAsTitles); + while (table.Check()) + { + tableTitles.push_back(table.myTitle); + table = GetTable(fname, separator, ++nb, firstStringAsTitles); + } + + return tableTitles; +} + +Table2D GetTable( + const char* fname, const char* separator, const int tableNb, const bool firstStringAsTitles) +{ + std::ifstream streamIn(fname); + + if (!streamIn.good()) + { + throw std::runtime_error("Unable to open input Post-Pro table file."); + } + + QString tmp; + int count = 0; + do + { + // Find beginning of table (tables are separated by empty lines) + while (getLine(streamIn, tmp) && tmp.trimmed() == "") + ; + + Table2D table2D; + + bool isFirst = true; + while (!streamIn.eof() && tmp.trimmed() != "") + { + QString data = tmp.trimmed(); + QString cmt = ""; + QString keyword = ""; + + // Split string to data and comment (comment starts from '#' symbol) + int index = tmp.indexOf("#"); + if (index >= 0) + { + data = tmp.left(index).trimmed(); + cmt = tmp.mid(index + 1).trimmed(); + } + + // If comment is not empty, try to get keyword from it (separated by ':' symbol) + if (!cmt.isEmpty()) + { + int index1 = cmt.indexOf(":"); + + if (index1 >= 0) + { + QString tmpstr = cmt.left(index1).trimmed(); + if (tmpstr == QString("TITLE") || tmpstr == QString("COLUMN_TITLES") || + tmpstr == QString("COLUMN_UNITS") || tmpstr == QString("COMMENT")) + { + keyword = tmpstr; + cmt = cmt.mid(index1 + 1).trimmed(); + } + } + } + + // If data is empty, process only comment + if (data.isEmpty()) + { + // If keyword is found, try to process it + // elsewise it is a simple comment, just ignore it + if (!keyword.isEmpty()) + { + if (keyword == QString("TITLE")) + { + QString title = cmt; + if (table2D.myTitle != "") + { + title = QString(table2D.myTitle.c_str()) + QString(" ") + title; + } + table2D.myTitle = title.toLatin1().constData(); + } + else if (keyword == QString("COLUMN_TITLES")) + { + // Comment may contain column headers + QStringList strList = cmt.split("|", QString::SkipEmptyParts); + + for (int i = 0; i < strList.count(); i++) + { + QString tmpstr = strList[i].trimmed(); + table2D.myColumnTitles.push_back(tmpstr.toLatin1().constData()); + } + } + else if (keyword == QString("COLUMN_UNITS")) + { + // Comment may contain column units + QStringList strList = cmt.split(" ", QString::SkipEmptyParts); + + for (int i = 0; i < strList.count(); i++) + { + QString tmpstr = strList[i].trimmed(); + table2D.myColumnUnits.push_back(tmpstr.toLatin1().constData()); + } + } + else if (keyword == QString("COMMENT")) + { + // Keyword 'COMMENT' processing can be here, + // currently it is ignored + } + } + else + { + // Simple comment processing can be here, + // currently it is ignored + } + } + // If data is not empty, try to process it + else + { + Table2D::Row row; + + QString datar1 = data.replace(QRegExp("\t"), " "); + QStringList valList = datar1.split(separator, QString::SkipEmptyParts); + if (table2D.myColumnTitles.size() == 0 && isFirst && firstStringAsTitles) + { + for (int i = 0; i < valList.count(); i++) + { + QString tmpstr = valList[i].trimmed(); + table2D.myColumnTitles.push_back(tmpstr.toLatin1().constData()); + } + } + else + { + if (!cmt.isEmpty()) + { + row.myTitle = cmt.toLatin1().constData(); + } + + for (int i = 0; i < valList.count(); i++) + { + if (valList[i].trimmed() != "") + { + Table2D::Value val = valList[i].trimmed().toLatin1().constData(); + row.myValues.push_back(val); + } + } + + if (row.myValues.size() > 0) + { + table2D.myRows.push_back(row); + } + } + + isFirst = false; + } + getLine(streamIn, tmp); + } + + if (table2D.Check()) + { + if (count == tableNb) + { + if (QString::fromStdString(table2D.myTitle).isEmpty()) + { + table2D.myTitle = QString("Table:%1").arg(tableNb).toStdString(); + } + return table2D; + } + count++; + } + + } while (!streamIn.eof()); + + streamIn.close(); + + // Return empty table + Table2D emptyTable; + return emptyTable; +} diff --git a/src/Plugins/TableReader/plugin/TableReaderModule/TableParser.h b/src/Plugins/TableReader/plugin/TableReaderModule/TableParser.h new file mode 100644 index 00000000..7406ac5a --- /dev/null +++ b/src/Plugins/TableReader/plugin/TableReaderModule/TableParser.h @@ -0,0 +1,53 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// + +#ifndef __TableParser_h_ +#define __TableParser_h_ + +#include +#include + +struct Table2D +{ + typedef std::string Value; + typedef std::vector Values; + + struct Row + { + std::string myTitle; + std::string myUnit; + Values myValues; + }; + + std::string myTitle; + std::vector myColumnUnits; + std::vector myColumnTitles; + + typedef std::vector Rows; + Rows myRows; + + bool Check(); +}; + +std::vector GetTableNames( + const char* fname, const char* separator, const bool firstStringAsTitles); +Table2D GetTable( + const char* fname, const char* separator, const int tableNb, const bool firstStringAsTitles); + +#endif //__TableParser_h_ diff --git a/src/Plugins/TableReader/plugin/TableReaderModule/vtk.module b/src/Plugins/TableReader/plugin/TableReaderModule/vtk.module new file mode 100644 index 00000000..4637de50 --- /dev/null +++ b/src/Plugins/TableReader/plugin/TableReaderModule/vtk.module @@ -0,0 +1,13 @@ +NAME + TableReaderModule +DEPENDS + VTK::CommonCore + VTK::CommonDataModel + VTK::CommonExecutionModel + VTK::FiltersCore + VTK::InfovisCore +PRIVATE_DEPENDS + VTK::CommonMisc + VTK::CommonSystem + VTK::FiltersGeneral + VTK::vtksys diff --git a/src/Plugins/TableReader/plugin/TableReaderModule/vtkVisuTableReader.cxx b/src/Plugins/TableReader/plugin/TableReaderModule/vtkVisuTableReader.cxx new file mode 100644 index 00000000..fd160085 --- /dev/null +++ b/src/Plugins/TableReader/plugin/TableReaderModule/vtkVisuTableReader.cxx @@ -0,0 +1,199 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// + +#include "vtkVisuTableReader.h" +#include "TableParser.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +using namespace std; + +vtkStandardNewMacro(vtkVisuTableReader); + +vtkVisuTableReader::vtkVisuTableReader() + : FileName(nullptr) +{ + this->SetNumberOfInputPorts(0); + this->SetNumberOfOutputPorts(1); + + this->FileName = nullptr; + + this->DetectNumericColumns = true; + this->FirstStringAsTitles = false; + + this->TableNumber = 0; + + this->ValueDelimiter = nullptr; + this->SetValueDelimiter(" "); + + this->AvailableTables = vtkStringArray::New(); +} + +vtkVisuTableReader::~vtkVisuTableReader() +{ + this->SetFileName(nullptr); + this->SetValueDelimiter(nullptr); + this->AvailableTables->Delete(); +} + +int vtkVisuTableReader::CanReadFile(const char* fname) +{ + return 1; +} + +void vtkVisuTableReader::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os, indent); + os << indent << "FileName: " << (this->FileName ? this->FileName : "(none)") << endl; + os << indent << "DetectNumericColumns: " << (this->DetectNumericColumns ? "true" : "false") + << endl; + os << indent << "ValueDelimiter: " << (this->ValueDelimiter ? this->ValueDelimiter : "(none)") + << endl; + os << indent << "TableNumber: " << this->TableNumber << endl; +} + +int vtkVisuTableReader::RequestData( + vtkInformation*, vtkInformationVector**, vtkInformationVector* outputVector) +{ + vtkTable* const output_table = vtkTable::GetData(outputVector); + + try + { + vtkInformation* const outInfo = outputVector->GetInformationObject(0); + if (outInfo->Has(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()) && + outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()) > 0) + { + return 1; + } + + // If the filename is not defined + if (!this->FileName || this->TableNumber < 0) + { + return 1; + } + + // Read table with the given number from the file + Table2D table = + GetTable(this->FileName, this->ValueDelimiter, this->TableNumber, this->FirstStringAsTitles); + + // Set table name + output_table->GetInformation()->Set(vtkDataObject::FIELD_NAME(), table.myTitle.c_str()); + + int nbRows = table.myRows.size(); + int nbCols = table.myRows[0].myValues.size(); + + for (int col = 0; col < nbCols; col++) + { + vtkStringArray* newCol = vtkStringArray::New(); + newCol->SetNumberOfValues(nbRows); + + // Set value + for (int row = 0; row < nbRows; row++) + { + newCol->SetValue(row, table.myRows[row].myValues[col].c_str()); + } + + // Set title + bool hasUnit = !table.myColumnUnits[col].empty(); + + if (table.myColumnTitles[col].empty()) + { + std::stringstream buffer; + if (hasUnit) + { + buffer << col << " [" << table.myColumnUnits[col].c_str() << "]"; + } + else + { + buffer << col; + } + newCol->SetName(buffer.str().c_str()); + } + else + { + if (hasUnit) + { + std::stringstream buffer; + buffer << table.myColumnTitles[col].c_str() << " [" << table.myColumnUnits[col].c_str() + << "]"; + newCol->SetName(buffer.str().c_str()); + } + else + { + newCol->SetName(table.myColumnTitles[col].c_str()); + } + } + + output_table->AddColumn(newCol); + newCol->Delete(); + } + + // Detect numeric columns if needed + if (this->DetectNumericColumns) + { + vtkStringToNumeric* convertor = vtkStringToNumeric::New(); + vtkTable* clone = output_table->NewInstance(); + clone->ShallowCopy(output_table); + convertor->SetInputData(clone); + convertor->Update(); + clone->Delete(); + output_table->ShallowCopy(convertor->GetOutputDataObject(0)); + convertor->Delete(); + } + } + catch (std::exception& e) + { + vtkErrorMacro(<< "caught exception: " << e.what() << endl); + output_table->Initialize(); + } + catch (...) + { + vtkErrorMacro(<< "caught unknown exception." << endl); + output_table->Initialize(); + } + + return 1; +} + +vtkStringArray* vtkVisuTableReader::GetAvailableTables() +{ + this->AvailableTables->Initialize(); + + vector titles = + GetTableNames(this->FileName, this->ValueDelimiter, this->FirstStringAsTitles); + + for (int i = 0; i < titles.size(); i++) + { + this->AvailableTables->InsertNextValue(titles[i].c_str()); + } + + return this->AvailableTables; +} diff --git a/src/Plugins/TableReader/plugin/TableReaderModule/vtkVisuTableReader.h b/src/Plugins/TableReader/plugin/TableReaderModule/vtkVisuTableReader.h new file mode 100644 index 00000000..e843a969 --- /dev/null +++ b/src/Plugins/TableReader/plugin/TableReaderModule/vtkVisuTableReader.h @@ -0,0 +1,102 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// + +#ifndef __vtkVisuTableReader_h_ +#define __vtkVisuTableReader_h_ + +#include + +class vtkStringArray; + +class VTK_EXPORT vtkVisuTableReader : public vtkTableAlgorithm +{ +public: + static vtkVisuTableReader* New(); + vtkTypeMacro(vtkVisuTableReader, vtkTableAlgorithm); + void PrintSelf(ostream& os, vtkIndent indent) override; + + // Description: + // Specifies the name of the file + vtkGetStringMacro(FileName); + vtkSetStringMacro(FileName); + + // Description: + // When set to true, the reader will detect numeric columns and create + // vtkDoubleArray or vtkIntArray for those instead of vtkStringArray. + vtkSetMacro(DetectNumericColumns, bool); + vtkGetMacro(DetectNumericColumns, bool); + vtkBooleanMacro(DetectNumericColumns, bool); + + // Description: + // When set to true, the reader will interpret the first string as + // column titles. + vtkSetMacro(FirstStringAsTitles, bool); + vtkGetMacro(FirstStringAsTitles, bool); + vtkBooleanMacro(FirstStringAsTitles, bool); + + // Description: + // Specifies the number of the table + vtkSetMacro(TableNumber, int); + vtkGetMacro(TableNumber, int); + + // Description: + // Specifies string that will be used to separate values + vtkSetStringMacro(ValueDelimiter); + vtkGetStringMacro(ValueDelimiter); + + // Description: + // Determine whether the given file can be read + virtual int CanReadFile(const char* fname); + + // Description: + // Returns the available table names. + virtual vtkStringArray* GetAvailableTables(); + +protected: + vtkVisuTableReader(); + ~vtkVisuTableReader() override; + + // Description: + // This is called by the superclass. + int RequestData(vtkInformation*, vtkInformationVector**, vtkInformationVector*) override; + + // name of the file to read from + char* FileName; + + // defines whether to detect numeric columns + bool DetectNumericColumns; + + // defines whether to treat first string as column titles + bool FirstStringAsTitles; + + // number of the table to read + int TableNumber; + + // string that will be used to separate values + char* ValueDelimiter; + + // Available table names + vtkStringArray* AvailableTables; + +private: + vtkVisuTableReader(const vtkVisuTableReader&) = delete; + void operator=(const vtkVisuTableReader&) = delete; +}; + +#endif //__vtkVisuTableReader_h_ diff --git a/src/Plugins/TableReader/plugin/TableTo3DModule/CMakeLists.txt b/src/Plugins/TableReader/plugin/TableTo3DModule/CMakeLists.txt new file mode 100644 index 00000000..2bf1e311 --- /dev/null +++ b/src/Plugins/TableReader/plugin/TableTo3DModule/CMakeLists.txt @@ -0,0 +1,8 @@ +set(classes + vtkTableTo3D +) + +vtk_module_add_module(TableTo3DModule + FORCE_STATIC + CLASSES ${classes} +) diff --git a/src/Plugins/TableReader/plugin/TableTo3DModule/vtk.module b/src/Plugins/TableReader/plugin/TableTo3DModule/vtk.module new file mode 100644 index 00000000..36ca80c1 --- /dev/null +++ b/src/Plugins/TableReader/plugin/TableTo3DModule/vtk.module @@ -0,0 +1,12 @@ +NAME + TableTo3DModule +DEPENDS + VTK::CommonCore + VTK::CommonDataModel + VTK::CommonExecutionModel + VTK::FiltersCore + VTK::FiltersGeometry +PRIVATE_DEPENDS + VTK::CommonMisc + VTK::CommonSystem + VTK::FiltersGeneral diff --git a/src/Plugins/TableReader/plugin/TableTo3DModule/vtkTableTo3D.cxx b/src/Plugins/TableReader/plugin/TableTo3DModule/vtkTableTo3D.cxx new file mode 100644 index 00000000..c0b4fa51 --- /dev/null +++ b/src/Plugins/TableReader/plugin/TableTo3DModule/vtkTableTo3D.cxx @@ -0,0 +1,197 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// + +#include "vtkTableTo3D.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +vtkStandardNewMacro(vtkTableTo3D); + +vtkTableTo3D::vtkTableTo3D() +{ + this->ScaleFactor = 1.0; + this->UseOptimusScale = true; + this->PresentationType = TABLETO3D_SURFACE; + this->NumberOfContours = 32; +} + +vtkTableTo3D::~vtkTableTo3D() {} + +int vtkTableTo3D::FillInputPortInformation(int vtkNotUsed(port), vtkInformation* info) +{ + info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkTable"); + return 1; +} + +int vtkTableTo3D::RequestData(vtkInformation* vtkNotUsed(request), + vtkInformationVector** inputVector, vtkInformationVector* outputVector) +{ + vtkTable* input = vtkTable::GetData(inputVector[0], 0); + vtkPolyData* output = vtkPolyData::GetData(outputVector, 0); + + if (input->GetNumberOfRows() == 0 || input->GetNumberOfColumns() < 2) + { + return 1; + } + + vtkIdType xSize = input->GetNumberOfRows(); + vtkIdType ySize = input->GetNumberOfColumns() - 1; + vtkIdType nbPoints = xSize * ySize; + + vtkDataArray* xAxis = vtkDataArray::SafeDownCast(input->GetColumn(0)); + if (!xAxis) + { + vtkErrorMacro("The first column is not numeric."); + return 1; + } + + double xRange = xAxis->GetTuple1(xSize - 1) - xAxis->GetTuple1(0); + double yDelta = xRange / ySize; + + vtkSmartPointer yAxis = vtkSmartPointer::New(); + yAxis->SetNumberOfValues(ySize); + for (vtkIdType i = 0; i < ySize; i++) + { + yAxis->SetValue(i, i * yDelta); + } + + vtkSmartPointer points = vtkSmartPointer::New(); + points->SetNumberOfPoints(nbPoints); + + vtkSmartPointer pointsIdMapper = vtkSmartPointer::New(); + pointsIdMapper->SetName("POINTS_ID_MAPPER"); + pointsIdMapper->SetNumberOfComponents(2); + pointsIdMapper->SetNumberOfTuples(nbPoints); + int* pointsIdMapperPtr = pointsIdMapper->GetPointer(0); + + for (vtkIdType i = 0, pntId = 0; i < ySize; i++) + { + for (vtkIdType j = 0; j < xSize; j++, pntId++) + { + points->SetPoint(pntId, xAxis->GetTuple1(j), yAxis->GetValue(i), 0.0); + + *pointsIdMapperPtr++ = pntId; + *pointsIdMapperPtr++ = 0; + } + } + + vtkSmartPointer scalars = vtkSmartPointer::New(); + scalars->SetNumberOfComponents(1); + scalars->SetNumberOfTuples(nbPoints); + double* scalarsPtr = scalars->GetPointer(0); + for (vtkIdType i = 0; i < ySize; i++) + { + vtkDataArray* col = vtkDataArray::SafeDownCast(input->GetColumn(i + 1)); + + if (!col) + { + vtkErrorMacro("Column " << i << "is not numeric."); + return 1; + } + + for (vtkIdType j = 0; j < xSize; j++) + { + double value = col->GetTuple1(j); + *scalarsPtr++ = value; + } + } + + vtkSmartPointer structuredGrid = vtkSmartPointer::New(); + structuredGrid->SetPoints(points); + + structuredGrid->SetDimensions(xSize, ySize, 1); + + // structuredGrid->GetPointData()->AddArray(pointsIdMapper); + if (input->GetInformation()->Has(vtkDataObject::FIELD_NAME())) + { + scalars->SetName(input->GetInformation()->Get(vtkDataObject::FIELD_NAME())); + } + else + { + scalars->SetName("Table"); + } + structuredGrid->GetPointData()->SetScalars(scalars); + + vtkSmartPointer geomFilter = + vtkSmartPointer::New(); + geomFilter->SetInputData(structuredGrid); + geomFilter->Update(); + + vtkSmartPointer warpScalar = vtkSmartPointer::New(); + + double scaleFactor = this->ScaleFactor; + if (this->UseOptimusScale) + { + double range[2]; + geomFilter->GetOutput()->GetScalarRange(range); + double length = geomFilter->GetOutput()->GetLength(); + if (range[1] > 0) + { + scaleFactor = length / range[1] * 0.3; + } + else + { + scaleFactor = 0; + } + } + + if (this->PresentationType == TABLETO3D_SURFACE) + { + warpScalar->SetInputConnection(geomFilter->GetOutputPort(0)); + warpScalar->SetScaleFactor(scaleFactor); + } + else + { + vtkSmartPointer contourFilter = vtkSmartPointer::New(); + contourFilter->SetInputConnection(geomFilter->GetOutputPort(0)); + contourFilter->GenerateValues( + this->NumberOfContours, geomFilter->GetOutput()->GetScalarRange()); + warpScalar->SetInputConnection(contourFilter->GetOutputPort(0)); + warpScalar->SetScaleFactor(scaleFactor); + } + + warpScalar->Update(); + output->ShallowCopy(warpScalar->GetPolyDataOutput()); + + return 1; +} + +//---------------------------------------------------------------------------- +void vtkTableTo3D::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os, indent); + + os << indent << "ScaleFactor: " << this->ScaleFactor << endl; + os << indent << "UseOptimusScale: " << (this->UseOptimusScale ? "true" : "false") << endl; + os << indent << "PresentationType: " + << ((this->PresentationType == TABLETO3D_SURFACE) ? "Surface" : "Contour") << endl; + os << indent << "NumberOfContours: " << this->NumberOfContours << endl; +} diff --git a/src/Plugins/TableReader/plugin/TableTo3DModule/vtkTableTo3D.h b/src/Plugins/TableReader/plugin/TableTo3DModule/vtkTableTo3D.h new file mode 100644 index 00000000..cd415983 --- /dev/null +++ b/src/Plugins/TableReader/plugin/TableTo3DModule/vtkTableTo3D.h @@ -0,0 +1,79 @@ +// Copyright (C) 2010-2019 CEA/DEN, EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// + +#ifndef __vtkTableTo3D_h +#define __vtkTableTo3D_h + +#include + +#define TABLETO3D_SURFACE 0 +#define TABLETO3D_CONTOUR 1 + +class VTK_EXPORT vtkTableTo3D : public vtkPolyDataAlgorithm +{ +public: + static vtkTableTo3D* New(); + vtkTypeMacro(vtkTableTo3D, vtkPolyDataAlgorithm); + void PrintSelf(ostream& os, vtkIndent indent) override; + + // Description: + // Specify value to scale diplacement. + vtkSetMacro(ScaleFactor, double); + vtkGetMacro(ScaleFactor, double); + + // Description: + // When set to true, the filter will compute optimus scale factor, + // the value of ScaleFactor variable will be ignored. + vtkSetMacro(UseOptimusScale, bool); + vtkGetMacro(UseOptimusScale, bool); + vtkBooleanMacro(UseOptimusScale, bool); + + // Description: + // Specify type of presentation: surface of contour. + vtkSetClampMacro(PresentationType, int, TABLETO3D_SURFACE, TABLETO3D_CONTOUR); + vtkGetMacro(PresentationType, int); + + // Description: + // Specify number of contours for contour presentation type. + vtkSetMacro(NumberOfContours, int); + vtkGetMacro(NumberOfContours, int); + +protected: + vtkTableTo3D(); + ~vtkTableTo3D() override; + + // Description: + // Overridden to specify that input must be a vtkTable. + int FillInputPortInformation(int, vtkInformation*) override; + + // Description: + // Convert input vtkTable to vtkPolyData. + int RequestData(vtkInformation*, vtkInformationVector**, vtkInformationVector*) override; + + double ScaleFactor; + bool UseOptimusScale; + int PresentationType; + int NumberOfContours; + +private: + vtkTableTo3D(const vtkTableTo3D&) = delete; + void operator=(const vtkTableTo3D&) = delete; +}; + +#endif diff --git a/src/Plugins/TableReader/plugin/filters.xml b/src/Plugins/TableReader/plugin/filters.xml new file mode 100644 index 00000000..a167b4b1 --- /dev/null +++ b/src/Plugins/TableReader/plugin/filters.xml @@ -0,0 +1,78 @@ + + + + + + + + + + + + + + + + This property specifies the input.. + + + + + + + Specify value to scale displacement. + + + + + + + When set to true, the filter will compute optimus scale factor, + the value entered by user will be ignored. + + + + + + + + + + This property determines type of presentation: surface of contour. + + + + + + + Specify number of contours for contour presentation type. + + + + + + diff --git a/src/Plugins/TableReader/plugin/paraview.plugin b/src/Plugins/TableReader/plugin/paraview.plugin new file mode 100644 index 00000000..7a9a4b00 --- /dev/null +++ b/src/Plugins/TableReader/plugin/paraview.plugin @@ -0,0 +1,12 @@ +NAME + TableReaderPlugin +DESCRIPTION + This plugin provides TableReader and TableTo3D filter. +REQUIRES_MODULES + VTK::CommonCore + VTK::IOCore + VTK::FiltersCore + ParaView::RemotingServerManager + ParaView::RemotingViews + ParaView::pqComponents + ParaView::pqCore diff --git a/src/Plugins/TableReader/plugin/sources.xml b/src/Plugins/TableReader/plugin/sources.xml new file mode 100644 index 00000000..db7b3934 --- /dev/null +++ b/src/Plugins/TableReader/plugin/sources.xml @@ -0,0 +1,86 @@ + + + + + + + + + + + + + This property specifies the file name for the table reader. + + + + + + + When set to true, the reader will detect numeric columns and create + vtkDoubleArray or vtkIntArray for those instead of vtkStringArray. + + + + + + + When set to true, the reader will interpret the first string as + column titles. + + + + + + This property defines string to be used to separate table values. + + + + + + This property defines the number of table to read. + + + + + + + Names of available tables. + + + + + + + + + + diff --git a/src/Plugins/VoroGauss/CMakeLists.txt b/src/Plugins/VoroGauss/CMakeLists.txt index ca8b3017..b17fe445 100644 --- a/src/Plugins/VoroGauss/CMakeLists.txt +++ b/src/Plugins/VoroGauss/CMakeLists.txt @@ -1,70 +1,30 @@ -# Copyright (C) 2017-2019 EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# -# Author : Anthony Geay (EDF R&D) - -PROJECT(VoroGauss) -CMAKE_MINIMUM_REQUIRED(VERSION 2.8) - -CMAKE_POLICY(SET CMP0003 NEW) -IF(${CMAKE_VERSION} VERSION_GREATER "3.0.0") - CMAKE_POLICY(SET CMP0022 OLD) - CMAKE_POLICY(SET CMP0023 OLD) -ENDIF() - -SET(MED_READER_VERSION "0.0.0") - -# Common CMake macros -# =================== -SET(CONFIGURATION_ROOT_DIR $ENV{CONFIGURATION_ROOT_DIR} CACHE PATH "Path to the Salome CMake configuration files") -IF(EXISTS ${CONFIGURATION_ROOT_DIR}) - LIST(APPEND CMAKE_MODULE_PATH "${CONFIGURATION_ROOT_DIR}/cmake") - INCLUDE(SalomeMacros) -ELSE() - MESSAGE(FATAL_ERROR "We absolutely need the Salome CMake configuration files, please define CONFIGURATION_ROOT_DIR !") -ENDIF() -FIND_PACKAGE(SalomePythonInterp REQUIRED) -FIND_PACKAGE(SalomePythonLibs REQUIRED) - -FIND_PACKAGE(ParaView REQUIRED) -IF(NOT ParaView_FOUND) - MESSAGE(FATAL_ERROR "Please locate ParaView." ) -ENDIF(NOT ParaView_FOUND) -INCLUDE(${PARAVIEW_USE_FILE}) - -SET(MEDCOUPLING_ROOT_DIR $ENV{MEDCOUPLING_ROOT_DIR} CACHE PATH "MEDCOUPLING_ROOT_DIR") -LIST(APPEND CMAKE_MODULE_PATH "${MEDCOUPLING_ROOT_DIR}/cmake_files") -FIND_PACKAGE(SalomeMEDCoupling REQUIRED) - -IF(MEDCOUPLING_USE_64BIT_IDS) - ADD_DEFINITIONS("-DMEDCOUPLING_USE_64BIT_IDS") -ENDIF(MEDCOUPLING_USE_64BIT_IDS) - -OPTION(BUILD_SHARED_LIBS "Build with shared libraries." ${VTK_BUILD_SHARED_LIBS}) - -SET(VTK_INSTALL_RUNTIME_DIR lib) -SET(VTK_INSTALL_LIBRARY_DIR lib) -SET(VTK_INSTALL_ARCHIVE_DIR lib) - -PV_PROCESS_MODULES() - -INCLUDE_DIRECTORIES( - ${MEDCOUPLING_INCLUDE_DIRS} -) - -ADD_SUBDIRECTORY(ParaViewPlugin) +cmake_minimum_required(VERSION 3.8) +project(VoroGaussPlugin) +find_package(ParaView REQUIRED) + +include(GNUInstallDirs) +set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_BINDIR}") +set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_LIBDIR}") +set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_LIBDIR}") + +set("_paraview_plugin_default_${CMAKE_PROJECT_NAME}" ON) +paraview_plugin_scan( + ENABLE_BY_DEFAULT YES + PLUGIN_FILES "${CMAKE_CURRENT_SOURCE_DIR}/plugin/paraview.plugin" + PROVIDES_PLUGINS plugins + REQUIRES_MODULES required_modules) + +foreach(module IN LISTS required_modules) + if(NOT TARGET "${module}") + message("Missing required module: ${module}") + return() + endif() +endforeach() + +set(BUILD_SHARED_LIBS ON) +paraview_plugin_build( + RUNTIME_DESTINATION "${CMAKE_INSTALL_BINDIR}" + LIBRARY_DESTINATION "${CMAKE_INSTALL_LIBDIR}" + LIBRARY_SUBDIRECTORY "${PARAVIEW_PLUGIN_SUBDIR}" + PLUGINS ${plugins} + AUTOLOAD ${plugins}) diff --git a/src/Plugins/VoroGauss/IO/vtkVoroGauss.cxx b/src/Plugins/VoroGauss/IO/vtkVoroGauss.cxx deleted file mode 100644 index d8c3842f..00000000 --- a/src/Plugins/VoroGauss/IO/vtkVoroGauss.cxx +++ /dev/null @@ -1,900 +0,0 @@ -// Copyright (C) 2017-2019 EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Anthony Geay (EDF R&D) - -#include "vtkVoroGauss.h" - -#include "vtkAdjacentVertexIterator.h" -#include "vtkIntArray.h" -#include "vtkCellData.h" -#include "vtkPointData.h" -#include "vtkCellType.h" -#include "vtkCell.h" -#include "vtkCellArray.h" -#include "vtkIdTypeArray.h" - -#include "vtkStreamingDemandDrivenPipeline.h" -#include "vtkUnstructuredGrid.h" -#include "vtkMultiBlockDataSet.h" - -#include "vtkInformationStringKey.h" -#include "vtkAlgorithmOutput.h" -#include "vtkObjectFactory.h" -#include "vtkMutableDirectedGraph.h" -#include "vtkMultiBlockDataSet.h" -#include "vtkDataSet.h" -#include "vtkInformationVector.h" -#include "vtkInformation.h" -#include "vtkDataArraySelection.h" -#include "vtkTimeStamp.h" -#include "vtkInEdgeIterator.h" -#include "vtkInformationDataObjectKey.h" -#include "vtkInformationDataObjectMetaDataKey.h" -#include "vtkInformationDoubleVectorKey.h" -#include "vtkExecutive.h" -#include "vtkVariantArray.h" -#include "vtkStringArray.h" -#include "vtkDoubleArray.h" -#include "vtkFloatArray.h" -#include "vtkCharArray.h" -#include "vtkLongArray.h" -#include "vtkUnsignedCharArray.h" -#include "vtkDataSetAttributes.h" -#include "vtkDemandDrivenPipeline.h" -#include "vtkDataObjectTreeIterator.h" -#include "vtkWarpScalar.h" -#include "vtkQuadratureSchemeDefinition.h" -#include "vtkInformationQuadratureSchemeDefinitionVectorKey.h" -#include "vtkCompositeDataToUnstructuredGridFilter.h" -#include "vtkMultiBlockDataGroupFilter.h" - -#include "MEDCouplingMemArray.hxx" -#include "MEDCouplingMemArray.txx" -#include "MEDCouplingUMesh.hxx" -#include "MEDCouplingFieldDouble.hxx" -#include "InterpKernelAutoPtr.hxx" -#include "InterpKernelGaussCoords.hxx" - -#include -#include -#include -#include - -using MEDCoupling::DataArray; -using MEDCoupling::DataArrayInt32; -using MEDCoupling::DataArrayInt64; -using MEDCoupling::DataArrayDouble; -using MEDCoupling::MEDCouplingMesh; -using MEDCoupling::MEDCouplingUMesh; -using MEDCoupling::DynamicCastSafe; -using MEDCoupling::MEDCouplingFieldDouble; -using MEDCoupling::ON_GAUSS_PT; -using MEDCoupling::MCAuto; - -vtkStandardNewMacro(vtkVoroGauss); -/////////////////// - -std::map ComputeMapOfType() -{ - std::map ret; - int nbOfTypesInMC(sizeof(MEDCOUPLING2VTKTYPETRADUCER)/sizeof( decltype(MEDCOUPLING2VTKTYPETRADUCER[0]) )); - for(int i=0;i ComputeRevMapOfType() -{ - std::map ret; - int nbOfTypesInMC(sizeof(MEDCOUPLING2VTKTYPETRADUCER)/sizeof( decltype(MEDCOUPLING2VTKTYPETRADUCER[0]) )); - for(int i=0;ihasKey(ZE_KEY)) - return 0; - std::string ptSt(gd->value(ZE_KEY)); - void *pt(0); - std::istringstream iss(ptSt); iss >> pt; - return reinterpret_cast(pt); -} - -bool IsInformationOK(vtkInformation *info, std::vector& data) -{ - vtkInformationDoubleVectorKey *key(GetMEDReaderMetaDataIfAny()); - if(!key) - return false; - // Check the information contain meta data key - if(!info->Has(key)) - return false; - int lgth(key->Length(info)); - const double *data2(info->Get(key)); - data.insert(data.end(),data2,data2+lgth); - return true; -} - -void ExtractInfo(vtkInformationVector *inputVector, vtkUnstructuredGrid *& usgIn) -{ - vtkInformation *inputInfo(inputVector->GetInformationObject(0)); - vtkDataSet *input(0); - vtkDataSet *input0(vtkDataSet::SafeDownCast(inputInfo->Get(vtkDataObject::DATA_OBJECT()))); - vtkMultiBlockDataSet *input1(vtkMultiBlockDataSet::SafeDownCast(inputInfo->Get(vtkDataObject::DATA_OBJECT()))); - if(input0) - input=input0; - else - { - if(!input1) - throw INTERP_KERNEL::Exception("Input dataSet must be a DataSet or single elt multi block dataset expected !"); - if(input1->GetNumberOfBlocks()!=1) - throw INTERP_KERNEL::Exception("Input dataSet is a multiblock dataset with not exactly one block ! Use MergeBlocks or ExtractBlocks filter before calling this filter !"); - vtkDataObject *input2(input1->GetBlock(0)); - if(!input2) - throw INTERP_KERNEL::Exception("Input dataSet is a multiblock dataset with exactly one block but this single element is NULL !"); - vtkDataSet *input2c(vtkDataSet::SafeDownCast(input2)); - if(!input2c) - throw INTERP_KERNEL::Exception("Input dataSet is a multiblock dataset with exactly one block but this single element is not a dataset ! Use MergeBlocks or ExtractBlocks filter before calling this filter !"); - input=input2c; - } - if(!input) - throw INTERP_KERNEL::Exception("Input data set is NULL !"); - usgIn=vtkUnstructuredGrid::SafeDownCast(input); - if(!usgIn) - throw INTERP_KERNEL::Exception("Input data set is not an unstructured mesh ! This filter works only on unstructured meshes !"); -} - -DataArrayIdType *ConvertVTKArrayToMCArrayInt(vtkDataArray *data) -{ - if(!data) - throw INTERP_KERNEL::Exception("ConvertVTKArrayToMCArrayInt : internal error !"); - int nbTuples(data->GetNumberOfTuples()),nbComp(data->GetNumberOfComponents()); - std::size_t nbElts(nbTuples*nbComp); - MCAuto ret(DataArrayIdType::New()); - ret->alloc(nbTuples,nbComp); - for(int i=0;iGetComponentName(i)); - if(comp) - ret->setInfoOnComponent(i,comp); - } - mcIdType *ptOut(ret->getPointer()); - vtkIntArray *d0(vtkIntArray::SafeDownCast(data)); - if(d0) - { - const int *pt(d0->GetPointer(0)); - std::copy(pt,pt+nbElts,ptOut); - return ret.retn(); - } - vtkLongArray *d1(vtkLongArray::SafeDownCast(data)); - if(d1) - { - const long *pt(d1->GetPointer(0)); - std::copy(pt,pt+nbElts,ptOut); - return ret.retn(); - } - vtkIdTypeArray *d2(vtkIdTypeArray::SafeDownCast(data)); - if(d2) - { - const vtkIdType *pt(d2->GetPointer(0)); - std::copy(pt,pt+nbElts,ptOut); - return ret.retn(); - } - std::ostringstream oss; - oss << "ConvertVTKArrayToMCArrayInt : unrecognized array \"" << typeid(*data).name() << "\" type !"; - throw INTERP_KERNEL::Exception(oss.str()); -} - -DataArrayDouble *ConvertVTKArrayToMCArrayDouble(vtkDataArray *data) -{ - if(!data) - throw INTERP_KERNEL::Exception("ConvertVTKArrayToMCArrayDouble : internal error !"); - int nbTuples(data->GetNumberOfTuples()),nbComp(data->GetNumberOfComponents()); - std::size_t nbElts(nbTuples*nbComp); - MCAuto ret(DataArrayDouble::New()); - ret->alloc(nbTuples,nbComp); - for(int i=0;iGetComponentName(i)); - if(comp) - ret->setInfoOnComponent(i,comp); - } - double *ptOut(ret->getPointer()); - vtkFloatArray *d0(vtkFloatArray::SafeDownCast(data)); - if(d0) - { - const float *pt(d0->GetPointer(0)); - for(std::size_t i=0;iGetPointer(0)); - std::copy(pt,pt+nbElts,ptOut); - return ret.retn(); - } - std::ostringstream oss; - oss << "ConvertVTKArrayToMCArrayDouble : unrecognized array \"" << typeid(*data).name() << "\" type !"; - throw INTERP_KERNEL::Exception(oss.str()); -} - -DataArray *ConvertVTKArrayToMCArray(vtkDataArray *data) -{ - if(!data) - throw INTERP_KERNEL::Exception("ConvertVTKArrayToMCArray : internal error !"); - vtkFloatArray *d0(vtkFloatArray::SafeDownCast(data)); - vtkDoubleArray *d1(vtkDoubleArray::SafeDownCast(data)); - if(d0 || d1) - return ConvertVTKArrayToMCArrayDouble(data); - vtkIntArray *d2(vtkIntArray::SafeDownCast(data)); - vtkLongArray *d3(vtkLongArray::SafeDownCast(data)); - if(d2 || d3) - return ConvertVTKArrayToMCArrayInt(data); - std::ostringstream oss; - oss << "ConvertVTKArrayToMCArray : unrecognized array \"" << typeid(*data).name() << "\" type !"; - throw INTERP_KERNEL::Exception(oss.str()); -} - -DataArrayDouble *BuildCoordsFrom(vtkPointSet *ds) -{ - if(!ds) - throw INTERP_KERNEL::Exception("BuildCoordsFrom : internal error !"); - vtkPoints *pts(ds->GetPoints()); - if(!pts) - throw INTERP_KERNEL::Exception("BuildCoordsFrom : internal error 2 !"); - vtkDataArray *data(pts->GetData()); - if(!data) - throw INTERP_KERNEL::Exception("BuildCoordsFrom : internal error 3 !"); - MCAuto coords(ConvertVTKArrayToMCArrayDouble(data)); - return coords.retn(); -} - -void ConvertFromUnstructuredGrid(vtkUnstructuredGrid *ds, std::vector< MCAuto >& ms, std::vector< MCAuto >& ids) -{ - MCAuto coords(BuildCoordsFrom(ds)); - vtkIdType nbCells(ds->GetNumberOfCells()); - vtkCellArray *ca(ds->GetCells()); - if(!ca) - return ; - vtkIdType nbEnt(ca->GetNumberOfConnectivityEntries()); - vtkIdType *caPtr(ca->GetPointer()); - vtkUnsignedCharArray *ct(ds->GetCellTypesArray()); - if(!ct) - throw INTERP_KERNEL::Exception("ConvertFromUnstructuredGrid : internal error"); - vtkIdTypeArray *cla(ds->GetCellLocationsArray()); - const vtkIdType *claPtr(cla->GetPointer(0)); - if(!cla) - throw INTERP_KERNEL::Exception("ConvertFromUnstructuredGrid : internal error 2"); - const unsigned char *ctPtr(ct->GetPointer(0)); - std::map m(ComputeMapOfType()); - MCAuto lev(DataArrayInt::New()) ; lev->alloc(nbCells,1); - int *levPtr(lev->getPointer()); - for(vtkIdType i=0;i::iterator it(m.find(ctPtr[i])); - if(it!=m.end()) - { - const INTERP_KERNEL::CellModel& cm(INTERP_KERNEL::CellModel::GetCellModel((INTERP_KERNEL::NormalizedCellType)(*it).second)); - levPtr[i]=cm.getDimension(); - } - else - { - std::ostringstream oss; oss << "ConvertFromUnstructuredGrid : at pos #" << i << " unrecognized VTK cell with type =" << ctPtr[i]; - throw INTERP_KERNEL::Exception(oss.str()); - } - } - MCAuto levs(lev->getDifferentValues()); - vtkIdTypeArray *faces(ds->GetFaces()),*faceLoc(ds->GetFaceLocations()); - for(const int *curLev=levs->begin();curLev!=levs->end();curLev++) - { - MCAuto m0(MEDCouplingUMesh::New("",*curLev)); - m0->setCoords(coords); m0->allocateCells(); - MCAuto cellIdsCurLev(lev->findIdsEqual(*curLev)); - for(const mcIdType *cellId=cellIdsCurLev->begin();cellId!=cellIdsCurLev->end();cellId++) - { - std::map::iterator it(m.find(ctPtr[*cellId])); - vtkIdType offset(claPtr[*cellId]); - vtkIdType sz(caPtr[offset]); - INTERP_KERNEL::NormalizedCellType ct((INTERP_KERNEL::NormalizedCellType)(*it).second); - if(ct!=INTERP_KERNEL::NORM_POLYHED) - { - std::vector conn2(sz); - for(int kk=0;kkinsertNextCell(ct,sz,&conn2[0]); - } - else - { - if(!faces || !faceLoc) - throw INTERP_KERNEL::Exception("ConvertFromUnstructuredGrid : faces are expected when there are polyhedra !"); - const vtkIdType *facPtr(faces->GetPointer(0)),*facLocPtr(faceLoc->GetPointer(0)); - std::vector conn; - int off0(facLocPtr[*cellId]); - int nbOfFaces(facPtr[off0++]); - for(int k=0;kinsertNextCell(ct,ToIdType(conn.size()),&conn[0]); - } - } - ms.push_back(m0); ids.push_back(cellIdsCurLev); - } -} - -vtkSmartPointer ConvertUMeshFromMCToVTK(const MEDCouplingUMesh *mVor) -{ - std::map zeMapRev(ComputeRevMapOfType()); - int nbCells(mVor->getNumberOfCells()); - vtkSmartPointer ret(vtkSmartPointer::New()); - ret->Initialize(); - ret->Allocate(); - vtkSmartPointer points(vtkSmartPointer::New()); - { - const DataArrayDouble *vorCoords(mVor->getCoords()); - vtkSmartPointer da(vtkSmartPointer::New()); - da->SetNumberOfComponents((vtkIdType)vorCoords->getNumberOfComponents()); - da->SetNumberOfTuples((vtkIdType)vorCoords->getNumberOfTuples()); - std::copy(vorCoords->begin(),vorCoords->end(),da->GetPointer(0)); - points->SetData(da); - } - mVor->checkConsistencyLight(); - switch(mVor->getMeshDimension()) - { - case 3: - { - vtkIdType *cPtr(nullptr),*dPtr(nullptr); - unsigned char *aPtr(nullptr); - vtkSmartPointer cellTypes(vtkSmartPointer::New()); - { - cellTypes->SetNumberOfComponents(1); - cellTypes->SetNumberOfTuples(nbCells); - aPtr=cellTypes->GetPointer(0); - } - vtkSmartPointer cellLocations(vtkSmartPointer::New()); - { - cellLocations->SetNumberOfComponents(1); - cellLocations->SetNumberOfTuples(nbCells); - cPtr=cellLocations->GetPointer(0); - } - vtkSmartPointer cells(vtkSmartPointer::New()); - { - MCAuto tmp2(mVor->computeEffectiveNbOfNodesPerCell()); - cells->SetNumberOfComponents(1); - cells->SetNumberOfTuples(tmp2->accumulate((std::size_t)0)+nbCells); - dPtr=cells->GetPointer(0); - } - const mcIdType *connPtr(mVor->getNodalConnectivity()->begin()),*connIPtr(mVor->getNodalConnectivityIndex()->begin()); - int k(0),kk(0); - std::vector ee,ff; - for(int i=0;i(connPtr[connIPtr[0]])); - *aPtr++=(unsigned char)zeMapRev[connPtr[connIPtr[0]]]; - if(ct!=INTERP_KERNEL::NORM_POLYHED) - { - int sz(connIPtr[1]-connIPtr[0]-1); - *dPtr++=sz; - dPtr=std::copy(connPtr+connIPtr[0]+1,connPtr+connIPtr[1],dPtr); - *cPtr++=k; k+=sz+1; - ee.push_back(kk); - } - else - { - std::set s(connPtr+connIPtr[0]+1,connPtr+connIPtr[1]); s.erase(-1); - vtkIdType nbFace((vtkIdType)(std::count(connPtr+connIPtr[0]+1,connPtr+connIPtr[1],-1)+1)); - ff.push_back(nbFace); - const mcIdType *work(connPtr+connIPtr[0]+1); - for(int j=0;j faceLocations(vtkSmartPointer::New()); - { - faceLocations->SetNumberOfComponents(1); - faceLocations->SetNumberOfTuples((vtkIdType)ee.size()); - std::copy(ee.begin(),ee.end(),faceLocations->GetPointer(0)); - } - vtkSmartPointer faces(vtkSmartPointer::New()); - { - faces->SetNumberOfComponents(1); - faces->SetNumberOfTuples((vtkIdType)ff.size()); - std::copy(ff.begin(),ff.end(),faces->GetPointer(0)); - } - vtkSmartPointer cells2(vtkSmartPointer::New()); - cells2->SetCells(nbCells,cells); - ret->SetCells(cellTypes,cellLocations,cells2,faceLocations,faces); - break; - } - case 2: - { - vtkSmartPointer cellTypes(vtkSmartPointer::New()); - { - cellTypes->SetNumberOfComponents(1); - cellTypes->SetNumberOfTuples(nbCells); - unsigned char *ptr(cellTypes->GetPointer(0)); - std::fill(ptr,ptr+nbCells,zeMapRev[(int)INTERP_KERNEL::NORM_POLYGON]); - } - vtkIdType *cPtr(0),*dPtr(0); - vtkSmartPointer cellLocations(vtkSmartPointer::New()); - { - cellLocations->SetNumberOfComponents(1); - cellLocations->SetNumberOfTuples(nbCells); - cPtr=cellLocations->GetPointer(0); - } - vtkSmartPointer cells(vtkSmartPointer::New()); - { - cells->SetNumberOfComponents(1); - cells->SetNumberOfTuples(mVor->getNodalConnectivity()->getNumberOfTuples()); - dPtr=cells->GetPointer(0); - } - const mcIdType *connPtr(mVor->getNodalConnectivity()->begin()),*connIPtr(mVor->getNodalConnectivityIndex()->begin()); - int k(0); - for(int i=0;i cells2(vtkSmartPointer::New()); - cells2->SetCells(nbCells,cells); - ret->SetCells(cellTypes,cellLocations,cells2); - break; - } - case 1: - { - vtkSmartPointer cellTypes(vtkSmartPointer::New()); - { - cellTypes->SetNumberOfComponents(1); - cellTypes->SetNumberOfTuples(nbCells); - unsigned char *ptr(cellTypes->GetPointer(0)); - std::fill(ptr,ptr+nbCells,zeMapRev[(int)INTERP_KERNEL::NORM_SEG2]); - } - vtkIdType *cPtr(0),*dPtr(0); - vtkSmartPointer cellLocations(vtkSmartPointer::New()); - { - cellLocations->SetNumberOfComponents(1); - cellLocations->SetNumberOfTuples(nbCells); - cPtr=cellLocations->GetPointer(0); - } - vtkSmartPointer cells(vtkSmartPointer::New()); - { - cells->SetNumberOfComponents(1); - cells->SetNumberOfTuples(mVor->getNodalConnectivity()->getNumberOfTuples()); - dPtr=cells->GetPointer(0); - } - const mcIdType *connPtr(mVor->getNodalConnectivity()->begin()),*connIPtr(mVor->getNodalConnectivityIndex()->begin()); - for(int i=0;i cells2(vtkSmartPointer::New()); - cells2->SetCells(nbCells,cells); - ret->SetCells(cellTypes,cellLocations,cells2); - break; - } - default: - throw INTERP_KERNEL::Exception("Not implemented yet !"); - } - ret->SetPoints(points); - return ret; -} - -class OffsetKeeper -{ -public: - OffsetKeeper():_vtk_arr(0) { } - void pushBack(vtkDataArray *da) { _da_on.push_back(da); } - void setVTKArray(vtkIdTypeArray *arr) { - MCAuto offmc(ConvertVTKArrayToMCArrayInt(arr)); - _off_arr=offmc; _vtk_arr=arr; } - const std::vector& getArrayGauss() const { return _da_on; } - const DataArrayIdType *getOffsets() const { return _off_arr; } - vtkIdTypeArray *getVTKOffsets() const { return _vtk_arr; } -private: - std::vector _da_on; - MCAuto _off_arr; - vtkIdTypeArray *_vtk_arr; -}; - -void FillAdvInfoFrom(int vtkCT, const std::vector& GaussAdvData, int nbGaussPt, int nbNodesPerCell, std::vector& refCoo,std::vector& posInRefCoo) -{ - int nbOfCTS((int)GaussAdvData[0]),pos(1); - for(int i=0;i(std::cerr," ")); std::cerr << std::endl; - //std::copy(posInRefCoo.begin(),posInRefCoo.end(),std::ostream_iterator(std::cerr," ")); std::cerr << std::endl; - return ; - } - std::ostringstream oss; oss << "FillAdvInfoFrom : Internal error ! Not found cell type " << vtkCT << " in advanced Gauss info !"; - throw INTERP_KERNEL::Exception(oss.str()); -} - -template -vtkSmartPointer ExtractFieldFieldArr(T *elt2, int sizeOfOutArr, int nbOfCellsOfInput, const mcIdType *offsetsPtr, const mcIdType *nbPtsPerCellPtr) -{ - vtkSmartPointer elt3(vtkSmartPointer::New()); - int nbc(elt2->GetNumberOfComponents()); - elt3->SetNumberOfComponents(nbc); - elt3->SetNumberOfTuples(sizeOfOutArr); - for(int i=0;iGetComponentName(i)); - if(name) - elt3->SetComponentName(i,name); - } - elt3->SetName(elt2->GetName()); - // - U *ptr(elt3->GetPointer(0)); - const U *srcPtr(elt2->GetPointer(0)); - for(int i=0;i -vtkSmartPointer ExtractCellFieldArr(T *elt2, int sizeOfOutArr, int nbOfCellsOfInput, const mcIdType *idsPtr, const mcIdType *nbPtsPerCellPtr) -{ - vtkSmartPointer elt3(vtkSmartPointer::New()); - int nbc(elt2->GetNumberOfComponents()); - elt3->SetNumberOfComponents(nbc); - elt3->SetNumberOfTuples(sizeOfOutArr); - for(int i=0;iGetComponentName(i)); - if(name) - elt3->SetComponentName(i,name); - } - elt3->SetName(elt2->GetName()); - // - U *ptr(elt3->GetPointer(0)); - const U *srcPtr(elt2->GetPointer(0)); - for(int i=0;i Voronize(const MEDCouplingUMesh *m, const DataArrayIdType *ids, vtkIdTypeArray *vtkOff, const DataArrayIdType *offsetsBase, const std::vector& arrGauss, const std::vector& GaussAdvData, const std::vector& arrsOnCells) -{ - if(arrGauss.empty()) - throw INTERP_KERNEL::Exception("Voronize : no Gauss array !"); - int nbTuples(arrGauss[0]->GetNumberOfTuples()); - for(std::vector::const_iterator it=arrGauss.begin();it!=arrGauss.end();it++) - { - if((*it)->GetNumberOfTuples()!=nbTuples) - { - std::ostringstream oss; oss << "Mismatch of number of tuples in Gauss arrays for array \"" << (*it)->GetName() << "\""; - throw INTERP_KERNEL::Exception(oss.str()); - } - } - // Look at vtkOff has in the stomac - vtkInformation *info(vtkOff->GetInformation()); - if(!info) - throw INTERP_KERNEL::Exception("info is null ! Internal error ! Looks bad !"); - vtkInformationQuadratureSchemeDefinitionVectorKey *key(vtkQuadratureSchemeDefinition::DICTIONARY()); - if(!key->Has(info)) - throw INTERP_KERNEL::Exception("No quadrature key in info included in offets array ! Internal error ! Looks bad !"); - int dictSize(key->Size(info)); - INTERP_KERNEL::AutoPtr dict(new vtkQuadratureSchemeDefinition *[dictSize]); - key->GetRange(info,dict,0,0,dictSize); - // Voronoize - MCAuto field(MEDCouplingFieldDouble::New(ON_GAUSS_PT)); - field->setMesh(m); - // Gauss Part - int nbOfCellsOfInput(m->getNumberOfCells()); - MCAuto nbPtsPerCellArr(DataArrayIdType::New()); nbPtsPerCellArr->alloc(nbOfCellsOfInput,1); - std::map zeMapRev(ComputeRevMapOfType()),zeMap(ComputeMapOfType()); - std::set agt(m->getAllGeoTypes()); - for(std::set::const_iterator it=agt.begin();it!=agt.end();it++) - { - const INTERP_KERNEL::CellModel& cm(INTERP_KERNEL::CellModel::GetCellModel(*it)); - std::map::const_iterator it2(zeMapRev.find((int)*it)); - if(it2==zeMapRev.end()) - throw INTERP_KERNEL::Exception("Internal error ! no type conversion available !"); - vtkQuadratureSchemeDefinition *gaussLoc(dict[(*it2).second]); - if(!gaussLoc) - { - std::ostringstream oss; oss << "For cell type " << cm.getRepr() << " no Gauss info !"; - throw INTERP_KERNEL::Exception(oss.str()); - } - int np(gaussLoc->GetNumberOfQuadraturePoints()),nbPtsPerCell((int)cm.getNumberOfNodes()); - const double *sfw(gaussLoc->GetShapeFunctionWeights()),*w(gaussLoc->GetQuadratureWeights());; - std::vector refCoo,posInRefCoo,wCpp(w,w+np); - FillAdvInfoFrom((*it2).second,GaussAdvData,np,nbPtsPerCell,refCoo,posInRefCoo); - field->setGaussLocalizationOnType(*it,refCoo,posInRefCoo,wCpp); - MCAuto ids2(m->giveCellsWithType(*it)); - nbPtsPerCellArr->setPartOfValuesSimple3(np,ids2->begin(),ids2->end(),0,1,1); - } - int zeSizeOfOutCellArr(nbPtsPerCellArr->accumulate((std::size_t)0)); - { MCAuto fakeArray(DataArrayDouble::New()); fakeArray->alloc(zeSizeOfOutCellArr,1); field->setArray(fakeArray); } - field->checkConsistencyLight(); - MCAuto vor(field->voronoize(1e-12));// The key is here ! - MEDCouplingUMesh *mVor(dynamic_cast(vor->getMesh())); - // - vtkSmartPointer ret(ConvertUMeshFromMCToVTK(mVor)); - // now fields... - MCAuto myOffsets(offsetsBase->selectByTupleIdSafe(ids->begin(),ids->end())); - const mcIdType *myOffsetsPtr(myOffsets->begin()),*nbPtsPerCellArrPtr(nbPtsPerCellArr->begin()); - for(std::vector::const_iterator it=arrGauss.begin();it!=arrGauss.end();it++) - { - vtkDataArray *elt(*it); - vtkDoubleArray *elt2(vtkDoubleArray::SafeDownCast(elt)); - vtkIntArray *elt3(vtkIntArray::SafeDownCast(elt)); - vtkIdTypeArray *elt4(vtkIdTypeArray::SafeDownCast(elt)); - if(elt2) - { - vtkSmartPointer arr(ExtractFieldFieldArr(elt2,zeSizeOfOutCellArr,nbOfCellsOfInput,myOffsetsPtr,nbPtsPerCellArrPtr)); - ret->GetCellData()->AddArray(arr); - continue; - } - if(elt3) - { - vtkSmartPointer arr(ExtractFieldFieldArr(elt3,zeSizeOfOutCellArr,nbOfCellsOfInput,myOffsetsPtr,nbPtsPerCellArrPtr)); - ret->GetCellData()->AddArray(arr); - continue; - } - if(elt4) - { - vtkSmartPointer arr(ExtractFieldFieldArr(elt4,zeSizeOfOutCellArr,nbOfCellsOfInput,myOffsetsPtr,nbPtsPerCellArrPtr)); - ret->GetCellData()->AddArray(arr); - continue; - } - } - for(std::vector::const_iterator it=arrsOnCells.begin();it!=arrsOnCells.end();it++) - { - vtkDataArray *elt(*it); - vtkDoubleArray *elt2(vtkDoubleArray::SafeDownCast(elt)); - vtkIntArray *elt3(vtkIntArray::SafeDownCast(elt)); - vtkIdTypeArray *elt4(vtkIdTypeArray::SafeDownCast(elt)); - if(elt2) - { - vtkSmartPointer arr(ExtractCellFieldArr(elt2,zeSizeOfOutCellArr,nbOfCellsOfInput,ids->begin(),nbPtsPerCellArrPtr)); - ret->GetCellData()->AddArray(arr); - continue; - } - if(elt3) - { - vtkSmartPointer arr(ExtractCellFieldArr(elt3,zeSizeOfOutCellArr,nbOfCellsOfInput,ids->begin(),nbPtsPerCellArrPtr)); - ret->GetCellData()->AddArray(arr); - continue; - } - if(elt4) - { - vtkSmartPointer arr(ExtractCellFieldArr(elt4,zeSizeOfOutCellArr,nbOfCellsOfInput,ids->begin(),nbPtsPerCellArrPtr)); - ret->GetCellData()->AddArray(arr); - continue; - } - } - return ret; -} - -vtkSmartPointer ComputeVoroGauss(vtkUnstructuredGrid *usgIn, const std::vector& GaussAdvData) -{ - OffsetKeeper zeOffsets; - std::string zeArrOffset; - std::vector cellFieldNamesToDestroy; - { - int nArrays(usgIn->GetFieldData()->GetNumberOfArrays()); - for(int i=0;iGetFieldData()->GetArray(i)); - if(!array) - continue; - const char* arrayOffsetName(array->GetInformation()->Get(vtkQuadratureSchemeDefinition::QUADRATURE_OFFSET_ARRAY_NAME())); - if(!arrayOffsetName) - continue; - std::string arrOffsetNameCpp(arrayOffsetName); - cellFieldNamesToDestroy.push_back(arrOffsetNameCpp); - if(arrOffsetNameCpp.find("ELGA@")==std::string::npos) - continue; - if(zeArrOffset.empty()) - zeArrOffset=arrOffsetNameCpp; - else - if(zeArrOffset!=arrOffsetNameCpp) - { - throw INTERP_KERNEL::Exception("ComputeVoroGauss : error in QUADRATURE_OFFSET_ARRAY_NAME for Gauss fields array !"); - } - zeOffsets.pushBack(array); - } - if(zeArrOffset.empty()) - throw INTERP_KERNEL::Exception("ComputeVoroGauss : no Gauss points fields in DataSet !"); - } - std::vector< MCAuto > ms; - std::vector< MCAuto > ids; - ConvertFromUnstructuredGrid(usgIn,ms,ids); - { - vtkDataArray *offTmp(usgIn->GetCellData()->GetArray(zeArrOffset.c_str())); - if(!offTmp) - { - std::ostringstream oss; oss << "ComputeVoroGauss : cell field " << zeArrOffset << " not found !"; - throw INTERP_KERNEL::Exception(oss.str()); - } - vtkIdTypeArray *offsets(vtkIdTypeArray::SafeDownCast(offTmp)); - if(!offsets) - { - std::ostringstream oss; oss << "ComputeVoroGauss : cell field " << zeArrOffset << " exists but not with the right type of data !"; - throw INTERP_KERNEL::Exception(oss.str()); - } - /// - zeOffsets.setVTKArray(offsets); - } - // - std::vector arrsOnCells; - { - int nArrays(usgIn->GetCellData()->GetNumberOfArrays()); - for(int i=0;iGetCellData()->GetArray(i)); - if(!array) - continue; - std::string name(array->GetName()); - if(std::find(cellFieldNamesToDestroy.begin(),cellFieldNamesToDestroy.end(),name)==cellFieldNamesToDestroy.end()) - { - arrsOnCells.push_back(array); - } - } - { - vtkDataArray *doNotKeepThis(zeOffsets.getVTKOffsets()); - std::vector::iterator it2(std::find(arrsOnCells.begin(),arrsOnCells.end(),doNotKeepThis)); - if(it2!=arrsOnCells.end()) - arrsOnCells.erase(it2); - } - } - // - std::size_t sz(ms.size()); - std::vector< vtkSmartPointer > res; - for(std::size_t i=0;i mmc(ms[i]); - MCAuto myIds(ids[i]); - vtkSmartPointer vor(Voronize(mmc,myIds,zeOffsets.getVTKOffsets(),zeOffsets.getOffsets(),zeOffsets.getArrayGauss(),GaussAdvData,arrsOnCells)); - res.push_back(vor); - } - if(res.empty()) - throw INTERP_KERNEL::Exception("Dataset is empty !"); - vtkSmartPointer mb(vtkSmartPointer::New()); - vtkSmartPointer cd(vtkSmartPointer::New()); - for(std::vector< vtkSmartPointer >::const_iterator it=res.begin();it!=res.end();it++) - mb->AddInputData(*it); - cd->SetInputConnection(mb->GetOutputPort()); - cd->SetMergePoints(0); - cd->Update(); - vtkSmartPointer ret; - ret=cd->GetOutput(); - return ret; -} - -//////////////////// - -vtkVoroGauss::vtkVoroGauss() -{ - this->SetNumberOfInputPorts(1); - this->SetNumberOfOutputPorts(1); -} - -vtkVoroGauss::~vtkVoroGauss() -{ -} - -int vtkVoroGauss::RequestInformation(vtkInformation *request, vtkInformationVector **inputVector, vtkInformationVector *outputVector) -{ - //std::cerr << "########################################## vtkVoroGauss::RequestInformation ##########################################" << std::endl; - try - { - vtkUnstructuredGrid *usgIn(0); - ExtractInfo(inputVector[0],usgIn); - } - catch(INTERP_KERNEL::Exception& e) - { - std::ostringstream oss; - oss << "Exception has been thrown in vtkVoroGauss::RequestInformation : " << e.what() << std::endl; - if(this->HasObserver("ErrorEvent") ) - this->InvokeEvent("ErrorEvent",const_cast(oss.str().c_str())); - else - vtkOutputWindowDisplayErrorText(const_cast(oss.str().c_str())); - vtkObject::BreakOnError(); - return 0; - } - return 1; -} - -int vtkVoroGauss::RequestData(vtkInformation *request, vtkInformationVector **inputVector, vtkInformationVector *outputVector) -{ - //std::cerr << "########################################## vtkVoroGauss::RequestData ##########################################" << std::endl; - try - { - - std::vector GaussAdvData; - bool isOK(IsInformationOK(inputVector[0]->GetInformationObject(0),GaussAdvData)); - if(!isOK) - throw INTERP_KERNEL::Exception("Sorry but no advanced gauss info found ! Expect to be called right after a MEDReader containing Gauss Points !"); - vtkUnstructuredGrid *usgIn(0); - ExtractInfo(inputVector[0],usgIn); - // - vtkSmartPointer ret(ComputeVoroGauss(usgIn,GaussAdvData)); - vtkInformation *inInfo(inputVector[0]->GetInformationObject(0)); - vtkInformation *outInfo(outputVector->GetInformationObject(0)); - vtkUnstructuredGrid *output(vtkUnstructuredGrid::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT()))); - output->ShallowCopy(ret); - } - catch(INTERP_KERNEL::Exception& e) - { - std::ostringstream oss; - oss << "Exception has been thrown in vtkVoroGauss::RequestData : " << e.what() << std::endl; - if(this->HasObserver("ErrorEvent") ) - this->InvokeEvent("ErrorEvent",const_cast(oss.str().c_str())); - else - vtkOutputWindowDisplayErrorText(const_cast(oss.str().c_str())); - vtkObject::BreakOnError(); - return 0; - } - return 1; -} - -void vtkVoroGauss::PrintSelf(ostream& os, vtkIndent indent) -{ - this->Superclass::PrintSelf(os, indent); -} diff --git a/src/Plugins/VoroGauss/IO/vtkVoroGauss.h b/src/Plugins/VoroGauss/IO/vtkVoroGauss.h deleted file mode 100644 index 93c6d2ab..00000000 --- a/src/Plugins/VoroGauss/IO/vtkVoroGauss.h +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (C) 2017-2019 EDF R&D -// -// This library 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. -// -// 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -// -// Author : Anthony Geay (EDF R&D) - -#ifndef vtkVoroGauss_h__ -#define vtkVoroGauss_h__ - -#include "vtkUnstructuredGridAlgorithm.h" - -class vtkMutableDirectedGraph; - -class VTK_EXPORT vtkVoroGauss : public vtkUnstructuredGridAlgorithm -{ -public: - static vtkVoroGauss* New(); - vtkTypeMacro(vtkVoroGauss, vtkUnstructuredGridAlgorithm) - void PrintSelf(ostream& os, vtkIndent indent); - -protected: - vtkVoroGauss(); - ~vtkVoroGauss(); - - int RequestInformation(vtkInformation *request, - vtkInformationVector **inputVector, vtkInformationVector *outputVector); - - int RequestData(vtkInformation *request, vtkInformationVector **inputVector, - vtkInformationVector *outputVector); -private: - vtkVoroGauss(const vtkVoroGauss&); - void operator=(const vtkVoroGauss&); // Not implemented. - private: - //BTX - //ETX -}; - -#endif diff --git a/src/Plugins/VoroGauss/PG_3D.med b/src/Plugins/VoroGauss/PG_3D.med deleted file mode 100644 index 9c7e51e7..00000000 Binary files a/src/Plugins/VoroGauss/PG_3D.med and /dev/null differ diff --git a/src/Plugins/VoroGauss/ParaViewPlugin/CMakeLists.txt b/src/Plugins/VoroGauss/ParaViewPlugin/CMakeLists.txt deleted file mode 100644 index 7c8ac558..00000000 --- a/src/Plugins/VoroGauss/ParaViewPlugin/CMakeLists.txt +++ /dev/null @@ -1,26 +0,0 @@ -# Copyright (C) 2016-2019 EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# -# Author : Anthony Geay (EDF R&D) - -INCLUDE_DIRECTORIES( ${CMAKE_CURRENT_SOURCE_DIR}/../IO ) -ADD_PARAVIEW_PLUGIN(VoroGaussPlugin "1.0" - SERVER_MANAGER_SOURCES ${SM_SRCS} ${PROJECT_SOURCE_DIR}/IO/vtkVoroGauss.cxx - SERVER_MANAGER_XML Resources/VoroGaussServer.xml) -TARGET_LINK_LIBRARIES(VoroGaussPlugin ${MEDCoupling_medcoupling}) -INSTALL(TARGETS VoroGaussPlugin RUNTIME DESTINATION lib/paraview LIBRARY DESTINATION lib/paraview ARCHIVE DESTINATION lib/paraview) diff --git a/src/Plugins/VoroGauss/ParaViewPlugin/Resources/VoroGaussServer.xml b/src/Plugins/VoroGauss/ParaViewPlugin/Resources/VoroGaussServer.xml deleted file mode 100644 index 0a7b10b7..00000000 --- a/src/Plugins/VoroGauss/ParaViewPlugin/Resources/VoroGaussServer.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - - - - - - - This property specifies the input to the Level Scalars filter. - - - - - - - - diff --git a/src/Plugins/VoroGauss/TestCase.py b/src/Plugins/VoroGauss/TestCase.py deleted file mode 100644 index 69e23f16..00000000 --- a/src/Plugins/VoroGauss/TestCase.py +++ /dev/null @@ -1,74 +0,0 @@ -# Copyright (C) 2017-2019 EDF R&D -# -# This library 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. -# -# 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# -# Author : Anthony Geay (EDF R&D) - -from MEDLoader import * - -fname="VoroGauss1.med" -meshName="mesh" -mm=MEDFileUMesh() -coords=DataArrayDouble([0,0, 1,0, 2,0, 3,0, 4,0, 5,0, 0,1, 1,1, 2,1, 0,2, 1,2, 3,1, 4,1],13,2) -m0=MEDCouplingUMesh(meshName,2) -m0.setCoords(coords) -m0.allocateCells() -m0.insertNextCell(NORM_TRI3,[2,3,8]) -m0.insertNextCell(NORM_TRI3,[3,4,11]) -m0.insertNextCell(NORM_TRI3,[4,5,12]) -m0.insertNextCell(NORM_TRI3,[6,7,9]) -m0.insertNextCell(NORM_TRI3,[7,8,10]) -m0.insertNextCell(NORM_QUAD4,[0,1,7,6]) -m0.insertNextCell(NORM_QUAD4,[1,2,8,7]) -mm[0]=m0 -m1=MEDCouplingUMesh(meshName,1) -m1.setCoords(coords) -m1.allocateCells() -m1.insertNextCell(NORM_SEG2,[0,1]) -m1.insertNextCell(NORM_SEG2,[1,2]) -m1.insertNextCell(NORM_SEG2,[2,3]) -m1.insertNextCell(NORM_SEG2,[3,4]) -m1.insertNextCell(NORM_SEG2,[4,5]) -mm[-1]=m1 -mm.setFamilyFieldArr(0,DataArrayInt([-1,-1,-2,-3,-3,-1,-3])) -mm.setFamilyFieldArr(-1,DataArrayInt([-1,-4,-4,-4,-1])) -for i in [-1,-2,-3,-4]: - mm.setFamilyId("Fam_%d"%i,i) - mm.setFamiliesOnGroup("G%d"%(abs(i)),["Fam_%d"%i]) - pass -mm.write(fname,2) -# -f0=MEDCouplingFieldDouble(ON_GAUSS_PT) -f0.setMesh(m0) -f0.setName("MyFieldPG") ; f0.setMesh(m0) -f0.setGaussLocalizationOnType(NORM_TRI3,[0,0, 1,0, 0,1],[0.1,0.1, 0.8,0.1, 0.1,0.8],[0.3,0.3,0.4]) -f0.setGaussLocalizationOnType(NORM_QUAD4,[-1,-1, 1,-1, 1,1, -1,1],[-0.57735,-0.57735,0.57735,-0.57735,0.57735,0.57735,-0.57735,0.57735],[0.25,0.25,0.25,0.25]) -arr=DataArrayDouble(f0.getNumberOfTuplesExpected()) ; arr.iota() -arr=DataArrayDouble.Meld(arr,arr) -arr.setInfoOnComponents(["comp0","comp1"]) -f0.setArray(arr) -WriteFieldUsingAlreadyWrittenMesh(fname,f0) -# -f1=MEDCouplingFieldDouble(ON_CELLS) -f1.setMesh(m0) -f1.setName("MyFieldCell") ; f1.setMesh(m0) -arr=DataArrayDouble(f1.getNumberOfTuplesExpected()) ; arr.iota() -arr=DataArrayDouble.Meld(arr,arr) -arr.setInfoOnComponents(["comp2","comp3"]) -f1.setArray(arr) -WriteFieldUsingAlreadyWrittenMesh(fname,f1) - diff --git a/src/Plugins/VoroGauss/plugin/CMakeLists.txt b/src/Plugins/VoroGauss/plugin/CMakeLists.txt new file mode 100644 index 00000000..34320a00 --- /dev/null +++ b/src/Plugins/VoroGauss/plugin/CMakeLists.txt @@ -0,0 +1,46 @@ +# Common CMake macros +# =================== +set(TMP_CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH}) +unset(CMAKE_MODULE_PATH) +set(CONFIGURATION_ROOT_DIR $ENV{CONFIGURATION_ROOT_DIR} CACHE PATH "Path to the Salome CMake configuration files") +if(EXISTS ${CONFIGURATION_ROOT_DIR}) + list(APPEND CMAKE_MODULE_PATH "${CONFIGURATION_ROOT_DIR}/cmake") + include(SalomeMacros) +else() + message(FATAL_ERROR "We absolutely need the Salome CMake configuration files, please define CONFIGURATION_ROOT_DIR !") +endif() + +set(MEDCOUPLING_ROOT_DIR $ENV{MEDCOUPLING_ROOT_DIR} CACHE PATH "Path to the MEDCoupling tool") +if(EXISTS ${MEDCOUPLING_ROOT_DIR}) + list(APPEND CMAKE_MODULE_PATH "${MEDCOUPLING_ROOT_DIR}/cmake_files") +endif() +list(APPEND CMAKE_MODULE_PATH "${CMAKE_ROOT}/Modules") +list(APPEND CMAKE_MODULE_PATH ${TMP_CMAKE_MODULE_PATH}) + +include(SalomeSetupPlatform) +set(BUILD_SHARED_LIBS TRUE) + +find_package(SalomeHDF5 REQUIRED) +find_package(SalomeMEDCoupling REQUIRED) + +if(MEDCOUPLING_USE_64BIT_IDS) + add_definitions("-DMEDCOUPLING_USE_64BIT_IDS") +endif(MEDCOUPLING_USE_64BIT_IDS) + +SALOME_ACCUMULATE_ENVIRONMENT(PYTHONPATH NOCHECK ${CMAKE_INSTALL_PREFIX}/${SALOME_INSTALL_BINS} + ${CMAKE_INSTALL_PREFIX}/${SALOME_INSTALL_PYTHON}) +SALOME_ACCUMULATE_ENVIRONMENT(LD_LIBRARY_PATH NOCHECK ${CMAKE_INSTALL_PREFIX}/${SALOME_INSTALL_LIBS}) +SALOME_ACCUMULATE_ENVIRONMENT(PV_PLUGIN_PATH NOCHECK ${CMAKE_INSTALL_PREFIX}/lib/paraview) + +paraview_add_plugin(VoroGaussPlugin + VERSION "1.0" + MODULES VoroGaussModule + MODULE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/VoroGaussModule/vtk.module" + SERVER_MANAGER_XML filters.xml +) + +install(TARGETS VoroGaussPlugin + RUNTIME DESTINATION lib/paraview + LIBRARY DESTINATION lib/paraview + ARCHIVE DESTINATION lib/paraview + ) diff --git a/src/Plugins/VoroGauss/plugin/VoroGaussModule/CMakeLists.txt b/src/Plugins/VoroGauss/plugin/VoroGaussModule/CMakeLists.txt new file mode 100644 index 00000000..85da8f9e --- /dev/null +++ b/src/Plugins/VoroGauss/plugin/VoroGaussModule/CMakeLists.txt @@ -0,0 +1,16 @@ +set(classes + vtkVoroGauss +) + +vtk_module_add_module(VoroGaussModule + FORCE_STATIC + CLASSES ${classes} +) + +target_include_directories(VoroGaussModule PRIVATE ${MEDCOUPLING_INCLUDE_DIRS}) + +if(HDF5_IS_PARALLEL) + target_link_libraries(VoroGaussModule PRIVATE ${MEDCoupling_paramedloader}) +else() + target_link_libraries(VoroGaussModule PRIVATE ${MEDCoupling_medloader}) +endif() diff --git a/src/Plugins/VoroGauss/plugin/VoroGaussModule/vtk.module b/src/Plugins/VoroGauss/plugin/VoroGaussModule/vtk.module new file mode 100644 index 00000000..a4f05863 --- /dev/null +++ b/src/Plugins/VoroGauss/plugin/VoroGaussModule/vtk.module @@ -0,0 +1,9 @@ +NAME + VoroGaussModule +DEPENDS + VTK::CommonCore + VTK::CommonDataModel + VTK::CommonExecutionModel +PRIVATE_DEPENDS + ParaView::VTKExtensionsMisc + ParaView::VTKExtensionsFiltersRendering diff --git a/src/Plugins/VoroGauss/plugin/VoroGaussModule/vtkVoroGauss.cxx b/src/Plugins/VoroGauss/plugin/VoroGaussModule/vtkVoroGauss.cxx new file mode 100644 index 00000000..afc59954 --- /dev/null +++ b/src/Plugins/VoroGauss/plugin/VoroGaussModule/vtkVoroGauss.cxx @@ -0,0 +1,900 @@ +// Copyright (C) 2017-2019 EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay (EDF R&D) + +#include "vtkVoroGauss.h" + +#include "vtkAdjacentVertexIterator.h" +#include "vtkIntArray.h" +#include "vtkCellData.h" +#include "vtkPointData.h" +#include "vtkCellType.h" +#include "vtkCell.h" +#include "vtkCellArray.h" +#include "vtkIdTypeArray.h" + +#include "vtkStreamingDemandDrivenPipeline.h" +#include "vtkUnstructuredGrid.h" +#include "vtkMultiBlockDataSet.h" + +#include "vtkInformationStringKey.h" +#include "vtkAlgorithmOutput.h" +#include "vtkObjectFactory.h" +#include "vtkMutableDirectedGraph.h" +#include "vtkMultiBlockDataSet.h" +#include "vtkDataSet.h" +#include "vtkInformationVector.h" +#include "vtkInformation.h" +#include "vtkDataArraySelection.h" +#include "vtkTimeStamp.h" +#include "vtkInEdgeIterator.h" +#include "vtkInformationDataObjectKey.h" +#include "vtkInformationDataObjectMetaDataKey.h" +#include "vtkInformationDoubleVectorKey.h" +#include "vtkExecutive.h" +#include "vtkVariantArray.h" +#include "vtkStringArray.h" +#include "vtkDoubleArray.h" +#include "vtkFloatArray.h" +#include "vtkCharArray.h" +#include "vtkLongArray.h" +#include "vtkUnsignedCharArray.h" +#include "vtkDataSetAttributes.h" +#include "vtkDemandDrivenPipeline.h" +#include "vtkDataObjectTreeIterator.h" +#include "vtkWarpScalar.h" +#include "vtkQuadratureSchemeDefinition.h" +#include "vtkInformationQuadratureSchemeDefinitionVectorKey.h" +#include "vtkCompositeDataToUnstructuredGridFilter.h" +#include "vtkMultiBlockDataGroupFilter.h" + +#include "MEDCouplingMemArray.hxx" +#include "MEDCouplingMemArray.txx" +#include "MEDCouplingUMesh.hxx" +#include "MEDCouplingFieldDouble.hxx" +#include "InterpKernelAutoPtr.hxx" +#include "InterpKernelGaussCoords.hxx" + +#include +#include +#include +#include + +using MEDCoupling::DataArray; +using MEDCoupling::DataArrayInt32; +using MEDCoupling::DataArrayInt64; +using MEDCoupling::DataArrayDouble; +using MEDCoupling::MEDCouplingMesh; +using MEDCoupling::MEDCouplingUMesh; +using MEDCoupling::DynamicCastSafe; +using MEDCoupling::MEDCouplingFieldDouble; +using MEDCoupling::ON_GAUSS_PT; +using MEDCoupling::MCAuto; + +vtkStandardNewMacro(vtkVoroGauss); +/////////////////// + +std::map ComputeMapOfType() +{ + std::map ret; + int nbOfTypesInMC(sizeof(MEDCOUPLING2VTKTYPETRADUCER)/sizeof( decltype(MEDCOUPLING2VTKTYPETRADUCER[0]) )); + for(int i=0;i ComputeRevMapOfType() +{ + std::map ret; + int nbOfTypesInMC(sizeof(MEDCOUPLING2VTKTYPETRADUCER)/sizeof( decltype(MEDCOUPLING2VTKTYPETRADUCER[0]) )); + for(int i=0;ihasKey(ZE_KEY)) + return 0; + std::string ptSt(gd->value(ZE_KEY)); + void *pt(0); + std::istringstream iss(ptSt); iss >> pt; + return reinterpret_cast(pt); +} + +bool IsInformationOK(vtkInformation *info, std::vector& data) +{ + vtkInformationDoubleVectorKey *key(GetMEDReaderMetaDataIfAny()); + if(!key) + return false; + // Check the information contain meta data key + if(!info->Has(key)) + return false; + int lgth(key->Length(info)); + const double *data2(info->Get(key)); + data.insert(data.end(),data2,data2+lgth); + return true; +} + +void ExtractInfo(vtkInformationVector *inputVector, vtkUnstructuredGrid *& usgIn) +{ + vtkInformation *inputInfo(inputVector->GetInformationObject(0)); + vtkDataSet *input(0); + vtkDataSet *input0(vtkDataSet::SafeDownCast(inputInfo->Get(vtkDataObject::DATA_OBJECT()))); + vtkMultiBlockDataSet *input1(vtkMultiBlockDataSet::SafeDownCast(inputInfo->Get(vtkDataObject::DATA_OBJECT()))); + if(input0) + input=input0; + else + { + if(!input1) + throw INTERP_KERNEL::Exception("Input dataSet must be a DataSet or single elt multi block dataset expected !"); + if(input1->GetNumberOfBlocks()!=1) + throw INTERP_KERNEL::Exception("Input dataSet is a multiblock dataset with not exactly one block ! Use MergeBlocks or ExtractBlocks filter before calling this filter !"); + vtkDataObject *input2(input1->GetBlock(0)); + if(!input2) + throw INTERP_KERNEL::Exception("Input dataSet is a multiblock dataset with exactly one block but this single element is NULL !"); + vtkDataSet *input2c(vtkDataSet::SafeDownCast(input2)); + if(!input2c) + throw INTERP_KERNEL::Exception("Input dataSet is a multiblock dataset with exactly one block but this single element is not a dataset ! Use MergeBlocks or ExtractBlocks filter before calling this filter !"); + input=input2c; + } + if(!input) + throw INTERP_KERNEL::Exception("Input data set is NULL !"); + usgIn=vtkUnstructuredGrid::SafeDownCast(input); + if(!usgIn) + throw INTERP_KERNEL::Exception("Input data set is not an unstructured mesh ! This filter works only on unstructured meshes !"); +} + +DataArrayIdType *ConvertVTKArrayToMCArrayInt(vtkDataArray *data) +{ + if(!data) + throw INTERP_KERNEL::Exception("ConvertVTKArrayToMCArrayInt : internal error !"); + int nbTuples(data->GetNumberOfTuples()),nbComp(data->GetNumberOfComponents()); + std::size_t nbElts(nbTuples*nbComp); + MCAuto ret(DataArrayIdType::New()); + ret->alloc(nbTuples,nbComp); + for(int i=0;iGetComponentName(i)); + if(comp) + ret->setInfoOnComponent(i,comp); + } + mcIdType *ptOut(ret->getPointer()); + vtkIntArray *d0(vtkIntArray::SafeDownCast(data)); + if(d0) + { + const int *pt(d0->GetPointer(0)); + std::copy(pt,pt+nbElts,ptOut); + return ret.retn(); + } + vtkLongArray *d1(vtkLongArray::SafeDownCast(data)); + if(d1) + { + const long *pt(d1->GetPointer(0)); + std::copy(pt,pt+nbElts,ptOut); + return ret.retn(); + } + vtkIdTypeArray *d2(vtkIdTypeArray::SafeDownCast(data)); + if(d2) + { + const int *pt(d2->GetPointer(0)); + std::copy(pt,pt+nbElts,ptOut); + return ret.retn(); + } + std::ostringstream oss; + oss << "ConvertVTKArrayToMCArrayInt : unrecognized array \"" << typeid(*data).name() << "\" type !"; + throw INTERP_KERNEL::Exception(oss.str()); +} + +DataArrayDouble *ConvertVTKArrayToMCArrayDouble(vtkDataArray *data) +{ + if(!data) + throw INTERP_KERNEL::Exception("ConvertVTKArrayToMCArrayDouble : internal error !"); + int nbTuples(data->GetNumberOfTuples()),nbComp(data->GetNumberOfComponents()); + std::size_t nbElts(nbTuples*nbComp); + MCAuto ret(DataArrayDouble::New()); + ret->alloc(nbTuples,nbComp); + for(int i=0;iGetComponentName(i)); + if(comp) + ret->setInfoOnComponent(i,comp); + } + double *ptOut(ret->getPointer()); + vtkFloatArray *d0(vtkFloatArray::SafeDownCast(data)); + if(d0) + { + const float *pt(d0->GetPointer(0)); + for(std::size_t i=0;iGetPointer(0)); + std::copy(pt,pt+nbElts,ptOut); + return ret.retn(); + } + std::ostringstream oss; + oss << "ConvertVTKArrayToMCArrayDouble : unrecognized array \"" << typeid(*data).name() << "\" type !"; + throw INTERP_KERNEL::Exception(oss.str()); +} + +DataArray *ConvertVTKArrayToMCArray(vtkDataArray *data) +{ + if(!data) + throw INTERP_KERNEL::Exception("ConvertVTKArrayToMCArray : internal error !"); + vtkFloatArray *d0(vtkFloatArray::SafeDownCast(data)); + vtkDoubleArray *d1(vtkDoubleArray::SafeDownCast(data)); + if(d0 || d1) + return ConvertVTKArrayToMCArrayDouble(data); + vtkIntArray *d2(vtkIntArray::SafeDownCast(data)); + vtkLongArray *d3(vtkLongArray::SafeDownCast(data)); + if(d2 || d3) + return ConvertVTKArrayToMCArrayInt(data); + std::ostringstream oss; + oss << "ConvertVTKArrayToMCArray : unrecognized array \"" << typeid(*data).name() << "\" type !"; + throw INTERP_KERNEL::Exception(oss.str()); +} + +DataArrayDouble *BuildCoordsFrom(vtkPointSet *ds) +{ + if(!ds) + throw INTERP_KERNEL::Exception("BuildCoordsFrom : internal error !"); + vtkPoints *pts(ds->GetPoints()); + if(!pts) + throw INTERP_KERNEL::Exception("BuildCoordsFrom : internal error 2 !"); + vtkDataArray *data(pts->GetData()); + if(!data) + throw INTERP_KERNEL::Exception("BuildCoordsFrom : internal error 3 !"); + MCAuto coords(ConvertVTKArrayToMCArrayDouble(data)); + return coords.retn(); +} + +void ConvertFromUnstructuredGrid(vtkUnstructuredGrid *ds, std::vector< MCAuto >& ms, std::vector< MCAuto >& ids) +{ + MCAuto coords(BuildCoordsFrom(ds)); + vtkIdType nbCells(ds->GetNumberOfCells()); + vtkCellArray *ca(ds->GetCells()); + if(!ca) + return ; + vtkIdType nbEnt(ca->GetNumberOfConnectivityEntries()); + vtkIdType *caPtr(ca->GetData()->GetPointer(0)); + vtkUnsignedCharArray *ct(ds->GetCellTypesArray()); + if(!ct) + throw INTERP_KERNEL::Exception("ConvertFromUnstructuredGrid : internal error"); + vtkIdTypeArray *cla(ds->GetCellLocationsArray()); + const vtkIdType *claPtr(cla->GetPointer(0)); + if(!cla) + throw INTERP_KERNEL::Exception("ConvertFromUnstructuredGrid : internal error 2"); + const unsigned char *ctPtr(ct->GetPointer(0)); + std::map m(ComputeMapOfType()); + MCAuto lev(DataArrayInt::New()) ; lev->alloc(nbCells,1); + int *levPtr(lev->getPointer()); + for(vtkIdType i=0;i::iterator it(m.find(ctPtr[i])); + if(it!=m.end()) + { + const INTERP_KERNEL::CellModel& cm(INTERP_KERNEL::CellModel::GetCellModel((INTERP_KERNEL::NormalizedCellType)(*it).second)); + levPtr[i]=cm.getDimension(); + } + else + { + std::ostringstream oss; oss << "ConvertFromUnstructuredGrid : at pos #" << i << " unrecognized VTK cell with type =" << ctPtr[i]; + throw INTERP_KERNEL::Exception(oss.str()); + } + } + MCAuto levs(lev->getDifferentValues()); + vtkIdTypeArray *faces(ds->GetFaces()),*faceLoc(ds->GetFaceLocations()); + for(const int *curLev=levs->begin();curLev!=levs->end();curLev++) + { + MCAuto m0(MEDCouplingUMesh::New("",*curLev)); + m0->setCoords(coords); m0->allocateCells(); + MCAuto cellIdsCurLev(lev->findIdsEqual(*curLev)); + for(const mcIdType *cellId=cellIdsCurLev->begin();cellId!=cellIdsCurLev->end();cellId++) + { + std::map::iterator it(m.find(ctPtr[*cellId])); + vtkIdType offset(claPtr[*cellId]); + vtkIdType sz(caPtr[offset]); + INTERP_KERNEL::NormalizedCellType ct((INTERP_KERNEL::NormalizedCellType)(*it).second); + if(ct!=INTERP_KERNEL::NORM_POLYHED) + { + std::vector conn2(sz); + for(int kk=0;kkinsertNextCell(ct,sz,&conn2[0]); + } + else + { + if(!faces || !faceLoc) + throw INTERP_KERNEL::Exception("ConvertFromUnstructuredGrid : faces are expected when there are polyhedra !"); + const vtkIdType *facPtr(faces->GetPointer(0)),*facLocPtr(faceLoc->GetPointer(0)); + std::vector conn; + int off0(facLocPtr[*cellId]); + int nbOfFaces(facPtr[off0++]); + for(int k=0;kinsertNextCell(ct,ToIdType(conn.size()),&conn[0]); + } + } + ms.push_back(m0); ids.push_back(cellIdsCurLev); + } +} + +vtkSmartPointer ConvertUMeshFromMCToVTK(const MEDCouplingUMesh *mVor) +{ + std::map zeMapRev(ComputeRevMapOfType()); + int nbCells(mVor->getNumberOfCells()); + vtkSmartPointer ret(vtkSmartPointer::New()); + ret->Initialize(); + ret->Allocate(); + vtkSmartPointer points(vtkSmartPointer::New()); + { + const DataArrayDouble *vorCoords(mVor->getCoords()); + vtkSmartPointer da(vtkSmartPointer::New()); + da->SetNumberOfComponents((vtkIdType)vorCoords->getNumberOfComponents()); + da->SetNumberOfTuples((vtkIdType)vorCoords->getNumberOfTuples()); + std::copy(vorCoords->begin(),vorCoords->end(),da->GetPointer(0)); + points->SetData(da); + } + mVor->checkConsistencyLight(); + switch(mVor->getMeshDimension()) + { + case 3: + { + int *cPtr(nullptr),*dPtr(nullptr); + unsigned char *aPtr(nullptr); + vtkSmartPointer cellTypes(vtkSmartPointer::New()); + { + cellTypes->SetNumberOfComponents(1); + cellTypes->SetNumberOfTuples(nbCells); + aPtr=cellTypes->GetPointer(0); + } + vtkSmartPointer cellLocations(vtkSmartPointer::New()); + { + cellLocations->SetNumberOfComponents(1); + cellLocations->SetNumberOfTuples(nbCells); + cPtr=cellLocations->GetPointer(0); + } + vtkSmartPointer cells(vtkSmartPointer::New()); + { + MCAuto tmp2(mVor->computeEffectiveNbOfNodesPerCell()); + cells->SetNumberOfComponents(1); + cells->SetNumberOfTuples(tmp2->accumulate((std::size_t)0)+nbCells); + dPtr=cells->GetPointer(0); + } + const mcIdType *connPtr(mVor->getNodalConnectivity()->begin()),*connIPtr(mVor->getNodalConnectivityIndex()->begin()); + int k(0),kk(0); + std::vector ee,ff; + for(int i=0;i(connPtr[connIPtr[0]])); + *aPtr++=(unsigned char)zeMapRev[connPtr[connIPtr[0]]]; + if(ct!=INTERP_KERNEL::NORM_POLYHED) + { + int sz(connIPtr[1]-connIPtr[0]-1); + *dPtr++=sz; + dPtr=std::copy(connPtr+connIPtr[0]+1,connPtr+connIPtr[1],dPtr); + *cPtr++=k; k+=sz+1; + ee.push_back(kk); + } + else + { + std::set s(connPtr+connIPtr[0]+1,connPtr+connIPtr[1]); s.erase(-1); + vtkIdType nbFace((vtkIdType)(std::count(connPtr+connIPtr[0]+1,connPtr+connIPtr[1],-1)+1)); + ff.push_back(nbFace); + const mcIdType *work(connPtr+connIPtr[0]+1); + for(int j=0;j faceLocations(vtkSmartPointer::New()); + { + faceLocations->SetNumberOfComponents(1); + faceLocations->SetNumberOfTuples((vtkIdType)ee.size()); + std::copy(ee.begin(),ee.end(),faceLocations->GetPointer(0)); + } + vtkSmartPointer faces(vtkSmartPointer::New()); + { + faces->SetNumberOfComponents(1); + faces->SetNumberOfTuples((vtkIdType)ff.size()); + std::copy(ff.begin(),ff.end(),faces->GetPointer(0)); + } + vtkSmartPointer cells2(vtkSmartPointer::New()); + cells2->SetCells(nbCells,cells); + ret->SetCells(cellTypes,cellLocations,cells2,faceLocations,faces); + break; + } + case 2: + { + vtkSmartPointer cellTypes(vtkSmartPointer::New()); + { + cellTypes->SetNumberOfComponents(1); + cellTypes->SetNumberOfTuples(nbCells); + unsigned char *ptr(cellTypes->GetPointer(0)); + std::fill(ptr,ptr+nbCells,zeMapRev[(int)INTERP_KERNEL::NORM_POLYGON]); + } + int *cPtr(0),*dPtr(0); + vtkSmartPointer cellLocations(vtkSmartPointer::New()); + { + cellLocations->SetNumberOfComponents(1); + cellLocations->SetNumberOfTuples(nbCells); + cPtr=cellLocations->GetPointer(0); + } + vtkSmartPointer cells(vtkSmartPointer::New()); + { + cells->SetNumberOfComponents(1); + cells->SetNumberOfTuples(mVor->getNodalConnectivity()->getNumberOfTuples()); + dPtr=cells->GetPointer(0); + } + const mcIdType *connPtr(mVor->getNodalConnectivity()->begin()),*connIPtr(mVor->getNodalConnectivityIndex()->begin()); + int k(0); + for(int i=0;i cells2(vtkSmartPointer::New()); + cells2->SetCells(nbCells,cells); + ret->SetCells(cellTypes,cellLocations,cells2); + break; + } + case 1: + { + vtkSmartPointer cellTypes(vtkSmartPointer::New()); + { + cellTypes->SetNumberOfComponents(1); + cellTypes->SetNumberOfTuples(nbCells); + unsigned char *ptr(cellTypes->GetPointer(0)); + std::fill(ptr,ptr+nbCells,zeMapRev[(int)INTERP_KERNEL::NORM_SEG2]); + } + int *cPtr(0),*dPtr(0); + vtkSmartPointer cellLocations(vtkSmartPointer::New()); + { + cellLocations->SetNumberOfComponents(1); + cellLocations->SetNumberOfTuples(nbCells); + cPtr=cellLocations->GetPointer(0); + } + vtkSmartPointer cells(vtkSmartPointer::New()); + { + cells->SetNumberOfComponents(1); + cells->SetNumberOfTuples(mVor->getNodalConnectivity()->getNumberOfTuples()); + dPtr=cells->GetPointer(0); + } + const mcIdType *connPtr(mVor->getNodalConnectivity()->begin()),*connIPtr(mVor->getNodalConnectivityIndex()->begin()); + for(int i=0;i cells2(vtkSmartPointer::New()); + cells2->SetCells(nbCells,cells); + ret->SetCells(cellTypes,cellLocations,cells2); + break; + } + default: + throw INTERP_KERNEL::Exception("Not implemented yet !"); + } + ret->SetPoints(points); + return ret; +} + +class OffsetKeeper +{ +public: + OffsetKeeper():_vtk_arr(0) { } + void pushBack(vtkDataArray *da) { _da_on.push_back(da); } + void setVTKArray(vtkIdTypeArray *arr) { + MCAuto offmc(ConvertVTKArrayToMCArrayInt(arr)); + _off_arr=offmc; _vtk_arr=arr; } + const std::vector& getArrayGauss() const { return _da_on; } + const DataArrayIdType *getOffsets() const { return _off_arr; } + vtkIdTypeArray *getVTKOffsets() const { return _vtk_arr; } +private: + std::vector _da_on; + MCAuto _off_arr; + vtkIdTypeArray *_vtk_arr; +}; + +void FillAdvInfoFrom(int vtkCT, const std::vector& GaussAdvData, int nbGaussPt, int nbNodesPerCell, std::vector& refCoo,std::vector& posInRefCoo) +{ + int nbOfCTS((int)GaussAdvData[0]),pos(1); + for(int i=0;i(std::cerr," ")); std::cerr << std::endl; + //std::copy(posInRefCoo.begin(),posInRefCoo.end(),std::ostream_iterator(std::cerr," ")); std::cerr << std::endl; + return ; + } + std::ostringstream oss; oss << "FillAdvInfoFrom : Internal error ! Not found cell type " << vtkCT << " in advanced Gauss info !"; + throw INTERP_KERNEL::Exception(oss.str()); +} + +template +vtkSmartPointer ExtractFieldFieldArr(T *elt2, int sizeOfOutArr, int nbOfCellsOfInput, const mcIdType *offsetsPtr, const mcIdType *nbPtsPerCellPtr) +{ + vtkSmartPointer elt3(vtkSmartPointer::New()); + int nbc(elt2->GetNumberOfComponents()); + elt3->SetNumberOfComponents(nbc); + elt3->SetNumberOfTuples(sizeOfOutArr); + for(int i=0;iGetComponentName(i)); + if(name) + elt3->SetComponentName(i,name); + } + elt3->SetName(elt2->GetName()); + // + U *ptr(elt3->GetPointer(0)); + const U *srcPtr(elt2->GetPointer(0)); + for(int i=0;i +vtkSmartPointer ExtractCellFieldArr(T *elt2, int sizeOfOutArr, int nbOfCellsOfInput, const mcIdType *idsPtr, const mcIdType *nbPtsPerCellPtr) +{ + vtkSmartPointer elt3(vtkSmartPointer::New()); + int nbc(elt2->GetNumberOfComponents()); + elt3->SetNumberOfComponents(nbc); + elt3->SetNumberOfTuples(sizeOfOutArr); + for(int i=0;iGetComponentName(i)); + if(name) + elt3->SetComponentName(i,name); + } + elt3->SetName(elt2->GetName()); + // + U *ptr(elt3->GetPointer(0)); + const U *srcPtr(elt2->GetPointer(0)); + for(int i=0;i Voronize(const MEDCouplingUMesh *m, const DataArrayIdType *ids, vtkIdTypeArray *vtkOff, const DataArrayIdType *offsetsBase, const std::vector& arrGauss, const std::vector& GaussAdvData, const std::vector& arrsOnCells) +{ + if(arrGauss.empty()) + throw INTERP_KERNEL::Exception("Voronize : no Gauss array !"); + int nbTuples(arrGauss[0]->GetNumberOfTuples()); + for(std::vector::const_iterator it=arrGauss.begin();it!=arrGauss.end();it++) + { + if((*it)->GetNumberOfTuples()!=nbTuples) + { + std::ostringstream oss; oss << "Mismatch of number of tuples in Gauss arrays for array \"" << (*it)->GetName() << "\""; + throw INTERP_KERNEL::Exception(oss.str()); + } + } + // Look at vtkOff has in the stomac + vtkInformation *info(vtkOff->GetInformation()); + if(!info) + throw INTERP_KERNEL::Exception("info is null ! Internal error ! Looks bad !"); + vtkInformationQuadratureSchemeDefinitionVectorKey *key(vtkQuadratureSchemeDefinition::DICTIONARY()); + if(!key->Has(info)) + throw INTERP_KERNEL::Exception("No quadrature key in info included in offets array ! Internal error ! Looks bad !"); + int dictSize(key->Size(info)); + INTERP_KERNEL::AutoPtr dict(new vtkQuadratureSchemeDefinition *[dictSize]); + key->GetRange(info,dict,0,0,dictSize); + // Voronoize + MCAuto field(MEDCouplingFieldDouble::New(ON_GAUSS_PT)); + field->setMesh(m); + // Gauss Part + int nbOfCellsOfInput(m->getNumberOfCells()); + MCAuto nbPtsPerCellArr(DataArrayIdType::New()); nbPtsPerCellArr->alloc(nbOfCellsOfInput,1); + std::map zeMapRev(ComputeRevMapOfType()),zeMap(ComputeMapOfType()); + std::set agt(m->getAllGeoTypes()); + for(std::set::const_iterator it=agt.begin();it!=agt.end();it++) + { + const INTERP_KERNEL::CellModel& cm(INTERP_KERNEL::CellModel::GetCellModel(*it)); + std::map::const_iterator it2(zeMapRev.find((int)*it)); + if(it2==zeMapRev.end()) + throw INTERP_KERNEL::Exception("Internal error ! no type conversion available !"); + vtkQuadratureSchemeDefinition *gaussLoc(dict[(*it2).second]); + if(!gaussLoc) + { + std::ostringstream oss; oss << "For cell type " << cm.getRepr() << " no Gauss info !"; + throw INTERP_KERNEL::Exception(oss.str()); + } + int np(gaussLoc->GetNumberOfQuadraturePoints()),nbPtsPerCell((int)cm.getNumberOfNodes()); + const double *sfw(gaussLoc->GetShapeFunctionWeights()),*w(gaussLoc->GetQuadratureWeights());; + std::vector refCoo,posInRefCoo,wCpp(w,w+np); + FillAdvInfoFrom((*it2).second,GaussAdvData,np,nbPtsPerCell,refCoo,posInRefCoo); + field->setGaussLocalizationOnType(*it,refCoo,posInRefCoo,wCpp); + MCAuto ids2(m->giveCellsWithType(*it)); + nbPtsPerCellArr->setPartOfValuesSimple3(np,ids2->begin(),ids2->end(),0,1,1); + } + int zeSizeOfOutCellArr(nbPtsPerCellArr->accumulate((std::size_t)0)); + { MCAuto fakeArray(DataArrayDouble::New()); fakeArray->alloc(zeSizeOfOutCellArr,1); field->setArray(fakeArray); } + field->checkConsistencyLight(); + MCAuto vor(field->voronoize(1e-12));// The key is here ! + MEDCouplingUMesh *mVor(dynamic_cast(vor->getMesh())); + // + vtkSmartPointer ret(ConvertUMeshFromMCToVTK(mVor)); + // now fields... + MCAuto myOffsets(offsetsBase->selectByTupleIdSafe(ids->begin(),ids->end())); + const mcIdType *myOffsetsPtr(myOffsets->begin()),*nbPtsPerCellArrPtr(nbPtsPerCellArr->begin()); + for(std::vector::const_iterator it=arrGauss.begin();it!=arrGauss.end();it++) + { + vtkDataArray *elt(*it); + vtkDoubleArray *elt2(vtkDoubleArray::SafeDownCast(elt)); + vtkIntArray *elt3(vtkIntArray::SafeDownCast(elt)); + vtkIdTypeArray *elt4(vtkIdTypeArray::SafeDownCast(elt)); + if(elt2) + { + vtkSmartPointer arr(ExtractFieldFieldArr(elt2,zeSizeOfOutCellArr,nbOfCellsOfInput,myOffsetsPtr,nbPtsPerCellArrPtr)); + ret->GetCellData()->AddArray(arr); + continue; + } + if(elt3) + { + vtkSmartPointer arr(ExtractFieldFieldArr(elt3,zeSizeOfOutCellArr,nbOfCellsOfInput,myOffsetsPtr,nbPtsPerCellArrPtr)); + ret->GetCellData()->AddArray(arr); + continue; + } + if(elt4) + { + vtkSmartPointer arr(ExtractFieldFieldArr(elt4,zeSizeOfOutCellArr,nbOfCellsOfInput,myOffsetsPtr,nbPtsPerCellArrPtr)); + ret->GetCellData()->AddArray(arr); + continue; + } + } + for(std::vector::const_iterator it=arrsOnCells.begin();it!=arrsOnCells.end();it++) + { + vtkDataArray *elt(*it); + vtkDoubleArray *elt2(vtkDoubleArray::SafeDownCast(elt)); + vtkIntArray *elt3(vtkIntArray::SafeDownCast(elt)); + vtkIdTypeArray *elt4(vtkIdTypeArray::SafeDownCast(elt)); + if(elt2) + { + vtkSmartPointer arr(ExtractCellFieldArr(elt2,zeSizeOfOutCellArr,nbOfCellsOfInput,ids->begin(),nbPtsPerCellArrPtr)); + ret->GetCellData()->AddArray(arr); + continue; + } + if(elt3) + { + vtkSmartPointer arr(ExtractCellFieldArr(elt3,zeSizeOfOutCellArr,nbOfCellsOfInput,ids->begin(),nbPtsPerCellArrPtr)); + ret->GetCellData()->AddArray(arr); + continue; + } + if(elt4) + { + vtkSmartPointer arr(ExtractCellFieldArr(elt4,zeSizeOfOutCellArr,nbOfCellsOfInput,ids->begin(),nbPtsPerCellArrPtr)); + ret->GetCellData()->AddArray(arr); + continue; + } + } + return ret; +} + +vtkSmartPointer ComputeVoroGauss(vtkUnstructuredGrid *usgIn, const std::vector& GaussAdvData) +{ + OffsetKeeper zeOffsets; + std::string zeArrOffset; + std::vector cellFieldNamesToDestroy; + { + int nArrays(usgIn->GetFieldData()->GetNumberOfArrays()); + for(int i=0;iGetFieldData()->GetArray(i)); + if(!array) + continue; + const char* arrayOffsetName(array->GetInformation()->Get(vtkQuadratureSchemeDefinition::QUADRATURE_OFFSET_ARRAY_NAME())); + if(!arrayOffsetName) + continue; + std::string arrOffsetNameCpp(arrayOffsetName); + cellFieldNamesToDestroy.push_back(arrOffsetNameCpp); + if(arrOffsetNameCpp.find("ELGA@")==std::string::npos) + continue; + if(zeArrOffset.empty()) + zeArrOffset=arrOffsetNameCpp; + else + if(zeArrOffset!=arrOffsetNameCpp) + { + throw INTERP_KERNEL::Exception("ComputeVoroGauss : error in QUADRATURE_OFFSET_ARRAY_NAME for Gauss fields array !"); + } + zeOffsets.pushBack(array); + } + if(zeArrOffset.empty()) + throw INTERP_KERNEL::Exception("ComputeVoroGauss : no Gauss points fields in DataSet !"); + } + std::vector< MCAuto > ms; + std::vector< MCAuto > ids; + ConvertFromUnstructuredGrid(usgIn,ms,ids); + { + vtkDataArray *offTmp(usgIn->GetCellData()->GetArray(zeArrOffset.c_str())); + if(!offTmp) + { + std::ostringstream oss; oss << "ComputeVoroGauss : cell field " << zeArrOffset << " not found !"; + throw INTERP_KERNEL::Exception(oss.str()); + } + vtkIdTypeArray *offsets(vtkIdTypeArray::SafeDownCast(offTmp)); + if(!offsets) + { + std::ostringstream oss; oss << "ComputeVoroGauss : cell field " << zeArrOffset << " exists but not with the right type of data !"; + throw INTERP_KERNEL::Exception(oss.str()); + } + /// + zeOffsets.setVTKArray(offsets); + } + // + std::vector arrsOnCells; + { + int nArrays(usgIn->GetCellData()->GetNumberOfArrays()); + for(int i=0;iGetCellData()->GetArray(i)); + if(!array) + continue; + std::string name(array->GetName()); + if(std::find(cellFieldNamesToDestroy.begin(),cellFieldNamesToDestroy.end(),name)==cellFieldNamesToDestroy.end()) + { + arrsOnCells.push_back(array); + } + } + { + vtkDataArray *doNotKeepThis(zeOffsets.getVTKOffsets()); + std::vector::iterator it2(std::find(arrsOnCells.begin(),arrsOnCells.end(),doNotKeepThis)); + if(it2!=arrsOnCells.end()) + arrsOnCells.erase(it2); + } + } + // + std::size_t sz(ms.size()); + std::vector< vtkSmartPointer > res; + for(std::size_t i=0;i mmc(ms[i]); + MCAuto myIds(ids[i]); + vtkSmartPointer vor(Voronize(mmc,myIds,zeOffsets.getVTKOffsets(),zeOffsets.getOffsets(),zeOffsets.getArrayGauss(),GaussAdvData,arrsOnCells)); + res.push_back(vor); + } + if(res.empty()) + throw INTERP_KERNEL::Exception("Dataset is empty !"); + vtkSmartPointer mb(vtkSmartPointer::New()); + vtkSmartPointer cd(vtkSmartPointer::New()); + for(std::vector< vtkSmartPointer >::const_iterator it=res.begin();it!=res.end();it++) + mb->AddInputData(*it); + cd->SetInputConnection(mb->GetOutputPort()); + cd->SetMergePoints(0); + cd->Update(); + vtkSmartPointer ret; + ret=cd->GetOutput(); + return ret; +} + +//////////////////// + +vtkVoroGauss::vtkVoroGauss() +{ + this->SetNumberOfInputPorts(1); + this->SetNumberOfOutputPorts(1); +} + +vtkVoroGauss::~vtkVoroGauss() +{ +} + +int vtkVoroGauss::RequestInformation(vtkInformation *request, vtkInformationVector **inputVector, vtkInformationVector *outputVector) +{ + //std::cerr << "########################################## vtkVoroGauss::RequestInformation ##########################################" << std::endl; + try + { + vtkUnstructuredGrid *usgIn(0); + ExtractInfo(inputVector[0],usgIn); + } + catch(INTERP_KERNEL::Exception& e) + { + std::ostringstream oss; + oss << "Exception has been thrown in vtkVoroGauss::RequestInformation : " << e.what() << std::endl; + if(this->HasObserver("ErrorEvent") ) + this->InvokeEvent("ErrorEvent",const_cast(oss.str().c_str())); + else + vtkOutputWindowDisplayErrorText(const_cast(oss.str().c_str())); + vtkObject::BreakOnError(); + return 0; + } + return 1; +} + +int vtkVoroGauss::RequestData(vtkInformation *request, vtkInformationVector **inputVector, vtkInformationVector *outputVector) +{ + //std::cerr << "########################################## vtkVoroGauss::RequestData ##########################################" << std::endl; + try + { + + std::vector GaussAdvData; + bool isOK(IsInformationOK(inputVector[0]->GetInformationObject(0),GaussAdvData)); + if(!isOK) + throw INTERP_KERNEL::Exception("Sorry but no advanced gauss info found ! Expect to be called right after a MEDReader containing Gauss Points !"); + vtkUnstructuredGrid *usgIn(0); + ExtractInfo(inputVector[0],usgIn); + // + vtkSmartPointer ret(ComputeVoroGauss(usgIn,GaussAdvData)); + vtkInformation *inInfo(inputVector[0]->GetInformationObject(0)); + vtkInformation *outInfo(outputVector->GetInformationObject(0)); + vtkUnstructuredGrid *output(vtkUnstructuredGrid::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT()))); + output->ShallowCopy(ret); + } + catch(INTERP_KERNEL::Exception& e) + { + std::ostringstream oss; + oss << "Exception has been thrown in vtkVoroGauss::RequestData : " << e.what() << std::endl; + if(this->HasObserver("ErrorEvent") ) + this->InvokeEvent("ErrorEvent",const_cast(oss.str().c_str())); + else + vtkOutputWindowDisplayErrorText(const_cast(oss.str().c_str())); + vtkObject::BreakOnError(); + return 0; + } + return 1; +} + +void vtkVoroGauss::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os, indent); +} diff --git a/src/Plugins/VoroGauss/plugin/VoroGaussModule/vtkVoroGauss.h b/src/Plugins/VoroGauss/plugin/VoroGaussModule/vtkVoroGauss.h new file mode 100644 index 00000000..ca43c643 --- /dev/null +++ b/src/Plugins/VoroGauss/plugin/VoroGaussModule/vtkVoroGauss.h @@ -0,0 +1,48 @@ +// Copyright (C) 2017-2019 EDF R&D +// +// This library 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. +// +// 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay (EDF R&D) + +#ifndef vtkVoroGauss_h__ +#define vtkVoroGauss_h__ + +#include "vtkUnstructuredGridAlgorithm.h" + +class vtkMutableDirectedGraph; + +class VTK_EXPORT vtkVoroGauss : public vtkUnstructuredGridAlgorithm +{ +public: + static vtkVoroGauss* New(); + vtkTypeMacro(vtkVoroGauss, vtkUnstructuredGridAlgorithm); + void PrintSelf(ostream& os, vtkIndent indent) override; + +protected: + vtkVoroGauss(); + ~vtkVoroGauss() override; + + int RequestInformation(vtkInformation*, vtkInformationVector**, vtkInformationVector*) override; + + int RequestData(vtkInformation*, vtkInformationVector**, vtkInformationVector*) override; + +private: + vtkVoroGauss(const vtkVoroGauss&) = delete; + void operator=(const vtkVoroGauss&) = delete; +}; + +#endif diff --git a/src/Plugins/VoroGauss/plugin/filters.xml b/src/Plugins/VoroGauss/plugin/filters.xml new file mode 100644 index 00000000..8679a413 --- /dev/null +++ b/src/Plugins/VoroGauss/plugin/filters.xml @@ -0,0 +1,24 @@ + + + + + + + + + + + + + This property specifies the input to the Level Scalars filter. + + + + + + + + diff --git a/src/Plugins/VoroGauss/plugin/paraview.plugin b/src/Plugins/VoroGauss/plugin/paraview.plugin new file mode 100644 index 00000000..93fabb45 --- /dev/null +++ b/src/Plugins/VoroGauss/plugin/paraview.plugin @@ -0,0 +1,6 @@ +NAME + VoroGaussPlugin +DESCRIPTION + This plugin provides the VoroGauss filter. +REQUIRES_MODULES + VTK::CommonCore diff --git a/src/Plugins/VoroGauss/script/PG_3D.med b/src/Plugins/VoroGauss/script/PG_3D.med new file mode 100644 index 00000000..9c7e51e7 Binary files /dev/null and b/src/Plugins/VoroGauss/script/PG_3D.med differ diff --git a/src/Plugins/VoroGauss/script/TestCase.py b/src/Plugins/VoroGauss/script/TestCase.py new file mode 100644 index 00000000..69e23f16 --- /dev/null +++ b/src/Plugins/VoroGauss/script/TestCase.py @@ -0,0 +1,74 @@ +# Copyright (C) 2017-2019 EDF R&D +# +# This library 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. +# +# 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 +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +# +# Author : Anthony Geay (EDF R&D) + +from MEDLoader import * + +fname="VoroGauss1.med" +meshName="mesh" +mm=MEDFileUMesh() +coords=DataArrayDouble([0,0, 1,0, 2,0, 3,0, 4,0, 5,0, 0,1, 1,1, 2,1, 0,2, 1,2, 3,1, 4,1],13,2) +m0=MEDCouplingUMesh(meshName,2) +m0.setCoords(coords) +m0.allocateCells() +m0.insertNextCell(NORM_TRI3,[2,3,8]) +m0.insertNextCell(NORM_TRI3,[3,4,11]) +m0.insertNextCell(NORM_TRI3,[4,5,12]) +m0.insertNextCell(NORM_TRI3,[6,7,9]) +m0.insertNextCell(NORM_TRI3,[7,8,10]) +m0.insertNextCell(NORM_QUAD4,[0,1,7,6]) +m0.insertNextCell(NORM_QUAD4,[1,2,8,7]) +mm[0]=m0 +m1=MEDCouplingUMesh(meshName,1) +m1.setCoords(coords) +m1.allocateCells() +m1.insertNextCell(NORM_SEG2,[0,1]) +m1.insertNextCell(NORM_SEG2,[1,2]) +m1.insertNextCell(NORM_SEG2,[2,3]) +m1.insertNextCell(NORM_SEG2,[3,4]) +m1.insertNextCell(NORM_SEG2,[4,5]) +mm[-1]=m1 +mm.setFamilyFieldArr(0,DataArrayInt([-1,-1,-2,-3,-3,-1,-3])) +mm.setFamilyFieldArr(-1,DataArrayInt([-1,-4,-4,-4,-1])) +for i in [-1,-2,-3,-4]: + mm.setFamilyId("Fam_%d"%i,i) + mm.setFamiliesOnGroup("G%d"%(abs(i)),["Fam_%d"%i]) + pass +mm.write(fname,2) +# +f0=MEDCouplingFieldDouble(ON_GAUSS_PT) +f0.setMesh(m0) +f0.setName("MyFieldPG") ; f0.setMesh(m0) +f0.setGaussLocalizationOnType(NORM_TRI3,[0,0, 1,0, 0,1],[0.1,0.1, 0.8,0.1, 0.1,0.8],[0.3,0.3,0.4]) +f0.setGaussLocalizationOnType(NORM_QUAD4,[-1,-1, 1,-1, 1,1, -1,1],[-0.57735,-0.57735,0.57735,-0.57735,0.57735,0.57735,-0.57735,0.57735],[0.25,0.25,0.25,0.25]) +arr=DataArrayDouble(f0.getNumberOfTuplesExpected()) ; arr.iota() +arr=DataArrayDouble.Meld(arr,arr) +arr.setInfoOnComponents(["comp0","comp1"]) +f0.setArray(arr) +WriteFieldUsingAlreadyWrittenMesh(fname,f0) +# +f1=MEDCouplingFieldDouble(ON_CELLS) +f1.setMesh(m0) +f1.setName("MyFieldCell") ; f1.setMesh(m0) +arr=DataArrayDouble(f1.getNumberOfTuplesExpected()) ; arr.iota() +arr=DataArrayDouble.Meld(arr,arr) +arr.setInfoOnComponents(["comp2","comp3"]) +f1.setArray(arr) +WriteFieldUsingAlreadyWrittenMesh(fname,f1) + diff --git a/src/Plugins/VoroGauss/script/testMEDReader14.med b/src/Plugins/VoroGauss/script/testMEDReader14.med new file mode 100644 index 00000000..c7ff867f Binary files /dev/null and b/src/Plugins/VoroGauss/script/testMEDReader14.med differ diff --git a/src/Plugins/VoroGauss/testMEDReader14.med b/src/Plugins/VoroGauss/testMEDReader14.med deleted file mode 100644 index c7ff867f..00000000 Binary files a/src/Plugins/VoroGauss/testMEDReader14.med and /dev/null differ diff --git a/test/standalone/CMakeLists.txt b/test/standalone/CMakeLists.txt index 4921a7f1..b1bc797b 100644 --- a/test/standalone/CMakeLists.txt +++ b/test/standalone/CMakeLists.txt @@ -20,6 +20,7 @@ PROJECT(LightPARAVIS) CMAKE_MINIMUM_REQUIRED(VERSION 2.8.10) +CMAKE_POLICY(SET CMP0053 NEW) # for correct Qt 5 detection procedure IF(WIN32) CMAKE_POLICY(SET CMP0020 OLD) # disable automatic linking to qtmain.lib ENDIF(WIN32) @@ -34,8 +35,6 @@ FIND_PACKAGE(Qt5Gui) LIST(APPEND CMAKE_PREFIX_PATH "$ENV{PARAVIEW_ROOT_DIR}") FIND_PACKAGE(ParaView REQUIRED) -INCLUDE(${PARAVIEW_USE_FILE}) -INCLUDE(ParaViewMacros) SET(CMAKE_INCLUDE_CURRENT_DIR ON) # Main applications diff --git a/test/standalone/gui/CMakeLists.txt b/test/standalone/gui/CMakeLists.txt index 0791987c..06ce8b9f 100644 --- a/test/standalone/gui/CMakeLists.txt +++ b/test/standalone/gui/CMakeLists.txt @@ -47,18 +47,11 @@ SET(pl_FORMS SET(CMAKE_INCLUDE_CURRENT_DIR ON) INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR}) -INCLUDE_DIRECTORIES(${PARAVIEW_INCLUDE_DIRS}) ADD_DEFINITIONS(${QT_DEFINITIONS}) # Generate resources that will embedded -SET(ui_resources - "${CMAKE_CURRENT_BINARY_DIR}/LightPara_configuration.qrc") - -GENERATE_QT_RESOURCE_FROM_FILES( - "${ui_resources}" - "LightPara/Configuration" - "${PROJECT_SOURCE_DIR}/gui/xml/ParaViewReaders.xml;${PROJECT_SOURCE_DIR}/gui/xml/ParaViewFilters.xml") +SET(ui_resources LightPara_configuration.qrc) QT_ADD_RESOURCES(rcs_sources ${ui_resources} @@ -72,7 +65,5 @@ ADD_EXECUTABLE(paraLight ${pl_FORMS_HEADERS} ${rcs_sources}) -# RNV: ${vtkgl2ps_LIBRARIES} was added for Fedora 26 OS -TARGET_LINK_LIBRARIES(paraLight ${QT_LIBRARIES} pqApplicationComponents vtkRenderingFreeType vtkInteractionStyle ${vtkgl2ps_LIBRARIES}) +TARGET_LINK_LIBRARIES(paraLight ${QT_LIBRARIES} ParaView::pqApplicationComponents ParaView::pqPython) #INSTALL(TARGET paraLight bin) - diff --git a/test/standalone/gui/LightPara_configuration.qrc b/test/standalone/gui/LightPara_configuration.qrc new file mode 100644 index 00000000..e2651d93 --- /dev/null +++ b/test/standalone/gui/LightPara_configuration.qrc @@ -0,0 +1,6 @@ + + + xml/ParaViewFilters.xml + xml/ParaViewReaders.xml + + diff --git a/test/standalone/gui/PVViewer_Behaviors.cxx b/test/standalone/gui/PVViewer_Behaviors.cxx index d1bd6d90..d2b1540e 100644 --- a/test/standalone/gui/PVViewer_Behaviors.cxx +++ b/test/standalone/gui/PVViewer_Behaviors.cxx @@ -73,9 +73,6 @@ void PVViewer_Behaviors::instanciateMinimalBehaviors(QMainWindow * desk) // Register standard types of view-frame actions. pgm->addInterface(new pqStandardViewFrameActionsImplementation(pgm)); - // Load plugins distributed with application. - pqApplicationCore::instance()->loadDistributedPlugins(); - new pqDefaultViewBehavior(this); // shows a 3D view as soon as a server connection is made new pqAlwaysConnectedBehavior(this); // client always connected to a server new pqVerifyRequiredPluginBehavior(this); diff --git a/test/standalone/gui/PVViewer_Core.cxx b/test/standalone/gui/PVViewer_Core.cxx index c8c8cd84..55b6510c 100644 --- a/test/standalone/gui/PVViewer_Core.cxx +++ b/test/standalone/gui/PVViewer_Core.cxx @@ -115,7 +115,7 @@ void PVViewer_Core::ParaviewLoadConfigurations(const QString & configPath, bool { if (!configPath.isNull()) { MyCoreApp->loadConfiguration(configPath + QDir::separator() + "ParaViewFilters.xml"); - MyCoreApp->loadConfiguration(configPath + QDir::separator() + "ParaViewSources.xml"); + MyCoreApp->loadConfiguration(configPath + QDir::separator() + "ParaViewReaders.xml"); } ConfigLoaded = true; } diff --git a/test/standalone/simple/CMakeLists.txt b/test/standalone/simple/CMakeLists.txt index a20d52d7..0a063216 100644 --- a/test/standalone/simple/CMakeLists.txt +++ b/test/standalone/simple/CMakeLists.txt @@ -20,18 +20,14 @@ SET(pl_SOURCES simple_gil.cxx - #PyInterp_Interp.cxx - #SUITApp_init_python.cxx Container_init_python.cxx ) - + INCLUDE_DIRECTORIES( - ${PARAVIEW_INCLUDE_DIRS} ${PYTHON_INCLUDE_DIRS} ${QT_INCLUDE_DIRS} ) ADD_EXECUTABLE(paraCmdLine ${pl_SOURCES}) -# RNV: ${vtkgl2ps_LIBRARIES} was added for Fedora 26 OS -TARGET_LINK_LIBRARIES(paraCmdLine ${PYTHON_LIBRARIES} ${QT_LIBRARIES} pqApplicationComponents vtkRenderingFreeType vtkInteractionStyle ${vtkgl2ps_LIBRARIES}) +TARGET_LINK_LIBRARIES(paraCmdLine ${PYTHON_LIBRARIES} ${QT_LIBRARIES} ParaView::pqApplicationComponents)