From: rnv Date: Thu, 14 Jun 2018 11:56:19 +0000 (+0300) Subject: Merge V9_dev branch into master X-Git-Tag: SHAPER_V9_1_0RC1~29 X-Git-Url: http://git.salome-platform.org/gitweb/?a=commitdiff_plain;h=b7a7d49664daa32e1befb558280e13ed0bde37c9;p=modules%2Fsmesh.git Merge V9_dev branch into master --- b7a7d49664daa32e1befb558280e13ed0bde37c9 diff --cc doc/salome/gui/SMESH/collect_mesh_methods.py index a76c6164c,542c5d7fd..99457030c --- a/doc/salome/gui/SMESH/collect_mesh_methods.py +++ b/doc/salome/gui/SMESH/collect_mesh_methods.py @@@ -45,9 -44,11 +44,11 @@@ # variables are set properly; otherwise the script will fail. # ################################################################################ + + import inspect import sys -def main(plugin_name, dummymeshhelp = True, output_file = "smeshBuilder.py"): +def main(plugin_name, dummymeshhelp = True, output_file = "smeshBuilder.py", format = "doxygen"): plugin_module_name = plugin_name + "Builder" plugin_module = "salome.%s.%s" % (plugin_name, plugin_module_name) try: @@@ -67,59 -68,29 +68,59 @@@ if methods: output = [] if dummymeshhelp: - if format == "doxygen": - output.append( "## @package smeshBuilder" ) - output.append( "# Documentation of the methods dynamically added by the " + plugin_name + " meshing plug-in to the Mesh class." ) - output.append( "" ) ++ if format == "doxygen": + output.append( "## @package smeshBuilder" ) + output.append( "# Documentation of the methods dynamically added by the " + plugin_name + " meshing plug-in to the Mesh class." ) + output.append( "" ) + elif format == "sphinx": + output.append( '"""' ) + output.append( 'Documentation of the methods dynamically added by the ' + plugin_name + ' meshing plug-in to the Mesh class.' ) + output.append( '"""' ) + output.append( '' ) pass - output.append( "## This class allows defining and managing a mesh." ) - output.append( "#" ) + if format == "doxygen": + output.append( "## This class allows defining and managing a mesh." ) + output.append( "#" ) + elif format == "sphinx": + output.append( "class Mesh:" ) + output.append( ' """' ) + output.append( ' This class allows defining and managing a mesh.' ) + output.append( ' ' ) if dummymeshhelp: # Add dummy Mesh help # This is supposed to be done when generating documentation for meshing plug-ins - output.append( "# @note The documentation below does not provide complete description of class @b %Mesh" ) - output.append( "# from @b smeshBuilder package. This documentation provides only information about" ) - output.append( "# the methods dynamically added to the %Mesh class by the " + plugin_name + " plugin" ) - output.append( "# For more details on the %Mesh class, please refer to the SALOME %Mesh module" ) - output.append( "# documentation." ) + if format == "doxygen": - output.append( "# @note The documentation below does not provide complete description of class @b %Mesh" ) ++ output.append( "# @note The documentation below does not provide complete description of class @b %Mesh" ) + output.append( "# from @b smeshBuilder package. This documentation provides only information about" ) + output.append( "# the methods dynamically added to the %Mesh class by the " + plugin_name + " plugin" ) + output.append( "# For more details on the %Mesh class, please refer to the SALOME %Mesh module" ) + output.append( "# documentation." ) + elif format == "sphinx": + output.append( ' The documentation below does not provide complete description of class @b %Mesh' ) + output.append( ' from @b smeshBuilder package. This documentation provides only information about' ) + output.append( ' the methods dynamically added to the %Mesh class by the " + plugin_name + " plugin' ) + output.append( ' For more details on the %Mesh class, please refer to the SALOME %Mesh module' ) + output.append( ' documentation.' ) + output.append( ' """' ) + output.append( ' ' ) pass else: # Extend documentation for Mesh class with information about dynamically added methods. # This is supposed to be done only when building documentation for SMESH module - output.append( "# @note Some methods are dynamically added to the @b %Mesh class in runtime by meshing " ) - output.append( "# plug-in modules. If you fail to find help on some methods in the documentation of SMESH module, " ) - output.append( "# try to look into the documentation for the meshing plug-ins." ) + if format == "doxygen": + output.append( "# @note Some methods are dynamically added to the @b %Mesh class in runtime by meshing " ) - output.append( "# plug-in modules. If you fail to find help on some methods in the documentation of SMESH module, " ) - output.append( "# try to look into the documentation for the meshing plug-ins." ) - elif format == "sphinx": ++ output.append( "# plug-in modules. If you fail to find help on some methods in the documentation of SMESH module, " ) ++ output.append( "# try to look into the documentation for the meshing plug-ins." ) ++ elif format == "sphinx": + output.append( " Note:") + output.append( " Some methods are dynamically added to the @b %Mesh class in runtime by meshing " ) - output.append( " plug-in modules. If you fail to find help on some methods in the documentation of SMESH module, " ) - output.append( " try to look into the documentation for the meshing plug-ins." ) ++ output.append( " plug-in modules. If you fail to find help on some methods in the documentation of SMESH module, " ) ++ output.append( " try to look into the documentation for the meshing plug-ins." ) + output.append( ' """' ) + output.append( ' ' ) pass - output.append( "class Mesh:" ) + if format == "doxygen": + output.append( "class Mesh:" ) for method in methods: docHelper = "" for algo in methods[ method ]: @@@ -127,46 -98,25 +128,45 @@@ if docHelper: break pass if not docHelper: docHelper = "Creates new algorithm." - output.append( " ## %s" % docHelper ) - output.append( " #" ) - output.append( " # This method is dynamically added to %Mesh class by the meshing plug-in(s). " ) - output.append( " #" ) - output.append( " # If the optional @a geom_shape parameter is not set, this algorithm is global (applied to whole mesh)." ) - output.append( " # Otherwise, this algorithm defines a submesh based on @a geom_shape subshape." ) - output.append( " # @param algo_type type of algorithm to be created; allowed values are specified by classes implemented by plug-in (see below)" ) - output.append( " # @param geom_shape if defined, the subshape to be meshed (GEOM_Object)" ) - output.append( " # @return An instance of Mesh_Algorithm sub-class according to the specified @a algo_type, see " ) - output.append( " # %s" % ", ".join( [ "%s.%s" % ( plugin_module_name, algo.__name__ ) for algo in methods[ method ] ] ) ) - output.append( " def %s(algo_type, geom_shape=0):" % method ) - output.append( " pass" ) + if format == "doxygen": + output.append( " ## %s" % docHelper ) + output.append( " #" ) + output.append( " # This method is dynamically added to %Mesh class by the meshing plug-in(s). " ) + output.append( " #" ) + output.append( " # If the optional @a geom_shape parameter is not set, this algorithm is global (applied to whole mesh)." ) + output.append( " # Otherwise, this algorithm defines a submesh based on @a geom_shape subshape." ) + output.append( " # @param algo_type type of algorithm to be created; allowed values are specified by classes implemented by plug-in" ) + output.append( " # @param geom_shape if defined, the subshape to be meshed (GEOM_Object)" ) + output.append( " # @return An instance of Mesh_Algorithm sub-class according to the specified @a algo_type, see " ) + output.append( " # %s" % ", ".join( [ "%s.%s" % ( plugin_module_name, algo.__name__ ) for algo in methods[ method ] ] ) ) + output.append( " def %s(algo_type, geom_shape=0):" % method ) + output.append( " pass" ) + elif format == "sphinx": + output.append( ' def %s(algo_type, geom_shape=0):' % method ) + output.append( ' """' ) + output.append( ' %s' % docHelper ) + output.append( ' ' ) + output.append( ' This method is dynamically added to :class:`Mesh ` class by the meshing plug-in(s). ' ) + output.append( ' ' ) + output.append( ' If the optional *geom_shape* parameter is not set, this algorithm is global (applied to whole mesh).' ) + output.append( ' Otherwise, this algorithm defines a submesh based on *geom_shape* subshape.' ) + output.append( ' ' ) + output.append( ' Parameters:' ) + output.append( ' algo_type: type of algorithm to be created; allowed values are specified by classes implemented by plug-in' ) + output.append( ' geom_shape (GEOM_Object): if defined, the subshape to be meshed' ) + output.append( ' ' ) + output.append( ' Returns:') + output.append( ' An instance of Mesh_Algorithm sub-class according to the specified *algo_type*, see ' ) + output.append( ' %s' % ", ".join( [ ":class:`~%s.%s`" % ( plugin_module_name, algo.__name__ ) for algo in methods[ method ] ] ) ) + output.append( ' """' ) + output.append( ' pass' ) pass - f = open(output_file, "w") - for line in output: f.write( line + "\n" ) - f.close() + with open(output_file, "w", encoding='utf8') as f: + f.write('\n'.join(output)) pass pass - except Exception, e: - print e + except Exception as e: + print(e) pass pass @@@ -180,17 -130,11 +180,20 @@@ if __name__ == "__main__" h = "If this option is True, dummy help for Mesh class is added. " h += "This option should be False (default) when building documentation for SMESH module " h += "and True when building documentation for meshing plug-ins." - parser.add_option("-d", "--dummy-mesh-help", dest="dummymeshhelp", + parser.add_argument("-d", "--dummy-mesh-help", dest="dummymeshhelp", action="store_true", default=False, help=h) - parser.add_argument("plugin", help='Name of plugin') + h = "Format of the documentation strings in the output file. Possible values are: " + h+= "'doxygen' - documentation strings are generated in the doxygen format, before a method defenition." + h+= "'sphinx' - documentation strings are generated in the sphinx format, after a method defenition." - parser.add_option("-f", "--format", dest="format", ++ parser.add_argument("-f", "--format", dest="format", + action="store", default="doxygen", help=h) + - (options, args) = parser.parse_args() ++ parser.add_argument("plugin_name") ++ ++ + args = parser.parse_args() - if len( args ) < 1: sys.exit("Plugin name is not specified") - main( args[0], options.dummymeshhelp, options.output, options.format ) - main( args.plugin, args.dummymeshhelp, args.output ) ++ if args.plugin_name is None : sys.exit("Plugin name is not specified") ++ main( args.plugin_name, args.dummymeshhelp, args.output, args.format ) pass diff --cc doc/salome/gui/SMESH/input/smesh_migration.rst index 5a2202486,000000000..59487da2f mode 100644,000000..100644 --- a/doc/salome/gui/SMESH/input/smesh_migration.rst +++ b/doc/salome/gui/SMESH/input/smesh_migration.rst @@@ -1,105 -1,0 +1,105 @@@ +.. _smesh_migration_page: + - ***************************************************** - Modifing Mesh Python scripts from SALOME 6 and before - ***************************************************** ++****************************************************** ++Modifying Mesh Python scripts from SALOME 6 and before ++****************************************************** + +In SALOME 7.2, the Python interface for Mesh has been slightly modified to offer new functionality: + + +Scripts generated for SALOME 6 and older versions must be adapted to work in SALOME 7.2 with full functionality. +The compatibility mode allows old scripts to work in almost all cases, but with a warning. + +* **Salome initialisation** must always be done as shown below. + + (*salome_init()* can be invoked safely several times):: + + import salome + salome.salome_init() + +* **smesh initialisation** is modified. + + The old mode (from dump):: + + import smesh, SMESH, SALOMEDS + smesh.SetCurrentStudy(salome.myStudy) + + The new mode:: + + import SMESH, SALOMEDS + from salome.smesh import smeshBuilder - smesh = smeshBuilder.New(salome.myStudy) ++ smesh = smeshBuilder.New() + + +* Of course, **from smesh import** * is **no more possible.** + - You have to explicitely write *smesh.some_method()*. ++ You have to explicitly write *smesh.some_method()*. + +* All **algorithms** have been transferred from the namespace *smesh* to the namespace *smeshBuilder*. + + For instance:: + + MEFISTO_2D_1 = Mesh_1.Triangle(algo=smesh.MEFISTO,geom=Face_1) + + is replaced by:: + + MEFISTO_2D_1 = Mesh_1.Triangle(algo=smeshBuilder.MEFISTO,geom=Face_1) + + StdMeshers algorithms concerned are *REGULAR, PYTHON, COMPOSITE, MEFISTO, Hexa, QUADRANGLE, RADIAL_QUAD*. + + SMESH Plugins provide such algorithms as: *NETGEN, NETGEN_FULL, FULL_NETGEN, NETGEN_1D2D3D, NETGEN_1D2D, NETGEN_2D, NETGEN_3D*. + + If you use DISTENE plugins, you also have *BLSURF, GHS3D, GHS3DPRL, Hexotic*. + +* Some **variables** were available in both namespaces *smesh* and *SMESH*. Now they are available only in namespace *SMESH*. + + The dump function used only the namespace *SMESH*, + so, if your script was built with the help of the dump function, it should be already OK in this respect. + + The most used variables concerned are: + + * *NODE, EDGE, FACE, VOLUME, ALL.* + * *FT_xxx, geom_xxx, ADD_xxx...* + + For instance:: + + srcFaceGroup = srcMesh.GroupOnGeom( midFace0, "src faces", smesh.FACE ) + mesh.MakeGroup("Tetras",smesh.VOLUME,smesh.FT_ElemGeomType,"=",smesh.Geom_TETRA) + filter = smesh.GetFilter(smesh.FACE, smesh.FT_AspectRatio, smesh.FT_MoreThan, 6.5) + + is replaced by:: + + srcFaceGroup = srcMesh.GroupOnGeom( midFace0, "src faces", SMESH.FACE ) + mesh.MakeGroup("Tetras",SMESH.VOLUME,SMESH.FT_ElemGeomType,"=",SMESH.Geom_TETRA) + filter = smesh.GetFilter(SMESH.FACE, SMESH.FT_AspectRatio, SMESH.FT_MoreThan, 6.5) + + +* The namespace **smesh.smesh** does not exist any more, use **smesh** instead. + + For instance:: + + Compound1 = smesh.smesh.Concatenate([Mesh_inf.GetMesh(), Mesh_sup.GetMesh()], 0, 1, 1e-05) + + is replaced by:: + + Compound1 = smesh.Concatenate([Mesh_inf.GetMesh(), Mesh_sup.GetMesh()], 0, 1, 1e-05) + - * If you need to **import a SMESH Plugin** explicitely, keep in mind that they are now located in separate namespaces. ++* If you need to **import a SMESH Plugin** explicitly, keep in mind that they are now located in separate namespaces. + + For instance:: + + import StdMeshers + import NETGENPlugin + import BLSURFPlugin + import GHS3DPlugin + import HexoticPLUGIN + + is replaced by:: + + from salome.StdMeshers import StdMeshersBuilder + from salome.NETGENPlugin import NETGENPluginBuilder + from salome.BLSURFPlugin import BLSURFPluginBuilder + from salome.GHS3DPlugin import GHS3DPluginBuilder + from salome.HexoticPLUGIN import HexoticPLUGINBuilder + + diff --cc doc/salome/gui/SMESH/merge_mesh_class.py index dd9806b52,000000000..19ce22fc5 mode 100644,000000..100644 --- a/doc/salome/gui/SMESH/merge_mesh_class.py +++ b/doc/salome/gui/SMESH/merge_mesh_class.py @@@ -1,59 -1,0 +1,59 @@@ +import inspect +import sys +from types import FunctionType +import copy + +ORIGIN_MODULE_SUFFIX = "_origin" +DYNAMIC_MODULE_SUFFIX = "_dynamic" + + +def main(module_name, output_file = "smeshBuilder.py"): + oringin_module_name = module_name + ORIGIN_MODULE_SUFFIX + dynamic_module_name = module_name + DYNAMIC_MODULE_SUFFIX + try: + exec( "import %s" % oringin_module_name ) + exec( "origin_module = %s" % oringin_module_name ) + origin_module_lines = inspect.getsourcelines( origin_module )[0] + origin_meshClass_lines = inspect.getsourcelines(origin_module.Mesh)[0] + origin_module_text = "".join( origin_module_lines ) + origin_meshClass_text = "".join( origin_meshClass_lines ) + + exec( "import %s" % dynamic_module_name ) + exec( "dynanmic_module = %s" % dynamic_module_name ) + dynanmic_meshClass = dynanmic_module.Mesh + + new_meshClass_lines = copy.copy(origin_meshClass_lines) + # remove end of class 'pass' + if new_meshClass_lines[-1].find("pass") > 0: + new_meshClass_lines.pop() + + dynanmic_meshClass_methods = [x for x, y in dynanmic_meshClass.__dict__.items() if type(y) == FunctionType] + for method in dynanmic_meshClass_methods: + exec( "method_lines = inspect.getsourcelines(dynanmic_module.Mesh.%s)[0]" % method) + new_meshClass_lines+=method_lines + pass + new_meshClass_text = "".join( new_meshClass_lines ) + + f = open( output_file, "w" ) + + f.write( origin_module_text.replace( origin_meshClass_text, new_meshClass_text) ) + f.close() - except Exception, e: - print e ++ except Exception as e: ++ print(e) + pass + pass + + +if __name__ == "__main__": + import optparse + parser = optparse.OptionParser(usage="%prog [options] modulename") + h = "Output file (smeshBuilder.py by default)" + parser.add_option("-o", "--output", dest="output", + action="store", default="smeshBuilder.py", metavar="file", + help=h) + + (options, args) = parser.parse_args() + + if len( args ) < 1: sys.exit("Module name is not specified") + main( args[0], options.output ) + pass diff --cc src/DriverMED/CMakeLists.txt index 6ddace44d,ce7b79ae4..af3e0f22d --- a/src/DriverMED/CMakeLists.txt +++ b/src/DriverMED/CMakeLists.txt @@@ -22,11 -22,10 +22,10 @@@ INCLUDE_DIRECTORIES( ${HDF5_INCLUDE_DIRS} ${KERNEL_INCLUDE_DIRS} - ${CAS_INCLUDE_DIRS} + ${OpenCASCADE_INCLUDE_DIR} ${VTK_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS} - ${PROJECT_SOURCE_DIR}/src/MEDWrapper/Base - ${PROJECT_SOURCE_DIR}/src/MEDWrapper/Factory + ${PROJECT_SOURCE_DIR}/src/MEDWrapper ${PROJECT_SOURCE_DIR}/src/Driver ${PROJECT_SOURCE_DIR}/src/SMDS ${PROJECT_SOURCE_DIR}/src/SMESHUtils diff --cc src/SMESH/CMakeLists.txt index 21f4ebf5e,e96f78f1b..3e41c626a --- a/src/SMESH/CMakeLists.txt +++ b/src/SMESH/CMakeLists.txt @@@ -26,9 -26,8 +26,9 @@@ INCLUDE_DIRECTORIES ${VTK_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS} ${HDF5_INCLUDE_DIRS} + ${TBB_INCLUDE_DIRS} ${PROJECT_SOURCE_DIR}/src/Controls - ${PROJECT_SOURCE_DIR}/src/MEDWrapper/Base + ${PROJECT_SOURCE_DIR}/src/MEDWrapper ${PROJECT_SOURCE_DIR}/src/Driver ${PROJECT_SOURCE_DIR}/src/DriverDAT ${PROJECT_SOURCE_DIR}/src/DriverMED diff --cc src/SMESHGUI/CMakeLists.txt index 92e170356,a06cac157..258033585 --- a/src/SMESHGUI/CMakeLists.txt +++ b/src/SMESHGUI/CMakeLists.txt @@@ -143,7 -142,7 +143,6 @@@ SET(_moc_HEADER SMESHGUI_FieldSelectorWdg.h SMESHGUI_DisplayEntitiesDlg.h SMESHGUI_SplitBiQuad.h -- SMESHGUI_PreVisualObj.h SMESHGUI_IdPreview.h ) diff --cc src/SMESHGUI/SMESHGUI.cxx index d3d701490,2e698c6de..73dee46ef --- a/src/SMESHGUI/SMESHGUI.cxx +++ b/src/SMESHGUI/SMESHGUI.cxx @@@ -3541,23 -3464,9 +3471,23 @@@ bool SMESHGUI::OnGUIEvent( int theComma break; } + case SMESHOp::OpOffset: + { - if(checkLock(aStudy)) break; ++ if(isStudyLocked()) break; + if ( vtkwnd ) { + EmitSignalDeactivateDialog(); + ( new SMESHGUI_OffsetDlg( this ) )->show(); + } + else { + SUIT_MessageBox::warning(SMESHGUI::desktop(), + tr("SMESH_WRN_WARNING"), tr("SMESH_WRN_VIEWER_VTK")); + } + break; + } + case SMESHOp::OpSewing: { - if(checkLock(aStudy)) break; + if(isStudyLocked()) break; if(vtkwnd) { EmitSignalDeactivateDialog(); ( new SMESHGUI_SewingDlg( this ) )->show(); diff --cc src/SMESHGUI/SMESHGUI_GroupDlg.cxx index 7b9f4974f,dc1a29fa3..9a0d91656 --- a/src/SMESHGUI/SMESHGUI_GroupDlg.cxx +++ b/src/SMESHGUI/SMESHGUI_GroupDlg.cxx @@@ -1426,8 -1420,8 +1420,9 @@@ void SMESHGUI_GroupDlg::onObjectSelecti aGroupMainShape = aGeomGroup; aGroupMainShape->Register(); } + CORBA::String_var entry = aGroupMainShape->GetStudyEntry(); - _PTR(SObject) aGroupMainShapeSO = aStudy->FindObjectID( entry.in() ); + _PTR(SObject) aGroupMainShapeSO = - SMESH::getStudy()->FindObjectID(aGroupMainShape->GetStudyEntry()); ++ SMESH::getStudy()->FindObjectID( entry.in() ); _PTR(SObject) anObj, aRef; bool isRefOrSubShape = false; diff --cc src/SMESHGUI/SMESHGUI_OffsetDlg.cxx index b7ded794c,000000000..111a8410f mode 100644,000000..100644 --- a/src/SMESHGUI/SMESHGUI_OffsetDlg.cxx +++ b/src/SMESHGUI/SMESHGUI_OffsetDlg.cxx @@@ -1,937 -1,0 +1,937 @@@ +// Copyright (C) 2007-2016 CEA/DEN, EDF R&D, OPEN CASCADE +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// File : SMESHGUI_OffsetDlg.cxx + +// SMESH includes + +#include "SMESHGUI_OffsetDlg.h" + +#include "SMESHGUI.h" +#include "SMESHGUI_SpinBox.h" +#include "SMESHGUI_Utils.h" +#include "SMESHGUI_VTKUtils.h" +#include "SMESHGUI_MeshUtils.h" +#include "SMESHGUI_IdValidator.h" +#include "SMESHGUI_FilterDlg.h" +#include "SMESHGUI_MeshEditPreview.h" + +#include +#include +#include +#include + +// SALOME GUI includes +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// SALOME KERNEL includes +#include +#include + +// OCCT includes +#include + +// Qt includes +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// IDL includes +#include +#include CORBA_SERVER_HEADER(SMESH_Group) +#include CORBA_SERVER_HEADER(SMESH_MeshEditor) + +enum { MOVE_ELEMS_BUTTON = 0, COPY_ELEMS_BUTTON, MAKE_MESH_BUTTON }; //!< action type + +/*! + \class BusyLocker + \brief Simple 'busy state' flag locker. + \internal +*/ +class BusyLocker +{ +public: + //! Constructor. Sets passed boolean flag to \c true. + BusyLocker( bool& busy ) : myBusy( busy ) { myBusy = true; } + //! Destructor. Clear external boolean flag passed as parameter to the constructor to \c false. + ~BusyLocker() { myBusy = false; } +private: + bool& myBusy; //! External 'busy state' boolean flag +}; + +#define SPACING 6 +#define MARGIN 11 + +//================================================================================= +// class : SMESHGUI_OffsetDlg() +// purpose : +//================================================================================= +SMESHGUI_OffsetDlg::SMESHGUI_OffsetDlg( SMESHGUI* theModule ) : + SMESHGUI_MultiPreviewDlg( theModule ), + mySelectionMgr( SMESH::GetSelectionMgr( theModule ) ), + myFilterDlg(0) +{ + QPixmap image0 (SMESH::GetResourceMgr( mySMESHGUI )->loadPixmap("SMESH", tr("ICON_DLG_MESH_OFFSET"))); + QPixmap image1 (SMESH::GetResourceMgr( mySMESHGUI )->loadPixmap("SMESH", tr("ICON_SELECT"))); + + setModal(false); + setAttribute(Qt::WA_DeleteOnClose, true); + setWindowTitle(tr("SMESH_OFFSET_TITLE")); + setSizeGripEnabled(true); + + QVBoxLayout* dlgLayout = new QVBoxLayout(this); + dlgLayout->setSpacing(SPACING); + dlgLayout->setMargin(MARGIN); + + /***************************************************************/ + ConstructorsBox = new QGroupBox(tr("SMESH_OFFSET"), this); + QHBoxLayout* ConstructorsBoxLayout = new QHBoxLayout(ConstructorsBox); + ConstructorsBoxLayout->setSpacing(SPACING); + ConstructorsBoxLayout->setMargin(MARGIN); + + QRadioButton* RadioButton1= new QRadioButton(ConstructorsBox); + RadioButton1->setIcon(image0); + + ConstructorsBoxLayout->addWidget(RadioButton1); + + /***************************************************************/ + GroupArguments = new QGroupBox(tr("SMESH_ARGUMENTS"), this); + QGridLayout* GroupArgumentsLayout = new QGridLayout(GroupArguments); + GroupArgumentsLayout->setSpacing(SPACING); + GroupArgumentsLayout->setMargin(MARGIN); + + myIdValidator = new SMESHGUI_IdValidator(this); + + // Controls for elements selection + TextLabelElements = new QLabel(tr("SMESH_ID_ELEMENTS"), GroupArguments); + // SelectElementsButton = new QPushButton(GroupArguments); + // SelectElementsButton->setIcon(image1); + LineEditElements = new QLineEdit(GroupArguments); + LineEditElements->setValidator(myIdValidator); + LineEditElements->setMaxLength(-1); + myFilterBtn = new QPushButton( tr( "SMESH_BUT_FILTER" ), GroupArguments ); + connect(myFilterBtn, SIGNAL(clicked()), this, SLOT(setFilters())); + + // Control for the whole mesh selection + CheckBoxMesh = new QCheckBox(tr("SMESH_SELECT_WHOLE_MESH"), GroupArguments); + + // offset + QLabel* TextLabel1 = new QLabel(tr("OFFSET_VALUE"), GroupArguments); + SpinBox = new SMESHGUI_SpinBox(GroupArguments); + + + // switch of action type + ActionBox = new QGroupBox(GroupArguments); + ActionGroup = new QButtonGroup(GroupArguments); + QVBoxLayout* ActionBoxLayout = new QVBoxLayout(ActionBox); + ActionBoxLayout->addSpacing(SPACING); + ActionBoxLayout->setMargin(MARGIN); + + QRadioButton* aMoveElements = new QRadioButton(tr("SMESH_MOVE_ELEMENTS"), ActionBox); + QRadioButton* aCopyElements = new QRadioButton(tr("SMESH_COPY_ELEMENTS"), ActionBox); + QRadioButton* aCreateMesh = new QRadioButton(tr("SMESH_CREATE_MESH"), ActionBox); + + ActionBoxLayout->addWidget(aMoveElements); + ActionBoxLayout->addWidget(aCopyElements); + ActionBoxLayout->addWidget(aCreateMesh); + ActionGroup->addButton(aMoveElements, MOVE_ELEMS_BUTTON); + ActionGroup->addButton(aCopyElements, COPY_ELEMS_BUTTON); + ActionGroup->addButton(aCreateMesh, MAKE_MESH_BUTTON); + + // CheckBox for groups generation + MakeGroupsCheck = new QCheckBox(tr("SMESH_MAKE_GROUPS"), GroupArguments); + MakeGroupsCheck->setChecked(false); + + // Name of a mesh to create + LineEditNewMesh = new QLineEdit(GroupArguments); + + //Preview check box + myPreviewCheckBox = new QCheckBox(tr("PREVIEW"), GroupArguments); + + // layout + GroupArgumentsLayout->addWidget(TextLabelElements, 0, 0); + //GroupArgumentsLayout->addWidget(SelectElementsButton, 0, 1); + GroupArgumentsLayout->addWidget(LineEditElements, 0, 2, 1, 5); + GroupArgumentsLayout->addWidget(myFilterBtn, 0, 7); + GroupArgumentsLayout->addWidget(CheckBoxMesh, 1, 0, 1, 8); + GroupArgumentsLayout->addWidget(TextLabel1, 2, 0); + GroupArgumentsLayout->addWidget(SpinBox, 2, 3); + GroupArgumentsLayout->addWidget(ActionBox, 3, 0, 3, 4); + GroupArgumentsLayout->addWidget(MakeGroupsCheck, 4, 5, 1, 4); + GroupArgumentsLayout->addWidget(LineEditNewMesh, 5, 5, 1, 4); + GroupArgumentsLayout->addWidget(myPreviewCheckBox, 6, 0); + + /***************************************************************/ + GroupButtons = new QGroupBox(this); + QHBoxLayout* GroupButtonsLayout = new QHBoxLayout(GroupButtons); + GroupButtonsLayout->setSpacing(SPACING); + GroupButtonsLayout->setMargin(MARGIN); + + buttonOk = new QPushButton(tr("SMESH_BUT_APPLY_AND_CLOSE"), GroupButtons); + buttonOk->setAutoDefault(true); + buttonOk->setDefault(true); + buttonApply = new QPushButton(tr("SMESH_BUT_APPLY"), GroupButtons); + buttonApply->setAutoDefault(true); + buttonCancel = new QPushButton(tr("SMESH_BUT_CLOSE"), GroupButtons); + buttonCancel->setAutoDefault(true); + buttonHelp = new QPushButton(tr("SMESH_BUT_HELP"), GroupButtons); + buttonHelp->setAutoDefault(true); + + GroupButtonsLayout->addWidget(buttonOk); + GroupButtonsLayout->addSpacing(10); + GroupButtonsLayout->addWidget(buttonApply); + GroupButtonsLayout->addSpacing(10); + GroupButtonsLayout->addStretch(); + GroupButtonsLayout->addWidget(buttonCancel); + GroupButtonsLayout->addWidget(buttonHelp); + + /***************************************************************/ + dlgLayout->addWidget(ConstructorsBox); + dlgLayout->addWidget(GroupArguments); + dlgLayout->addWidget(GroupButtons); + + /* Initialisations */ + SpinBox->RangeStepAndValidator(COORD_MIN, COORD_MAX, 1.0, "length_precision"); + + RadioButton1->setChecked(true); + + mySelector = (SMESH::GetViewWindow( mySMESHGUI ))->GetSelector(); + + mySMESHGUI->SetActiveDialogBox((QDialog*)this); + + // Costruction of the logical filter + SMESH_TypeFilter* aMeshOrSubMeshFilter = new SMESH_TypeFilter (SMESH::MESHorSUBMESH); + SMESH_TypeFilter* aSmeshGroupFilter = new SMESH_TypeFilter (SMESH::GROUP); + + QList aListOfFilters; + if (aMeshOrSubMeshFilter) aListOfFilters.append(aMeshOrSubMeshFilter); + if (aSmeshGroupFilter) aListOfFilters.append(aSmeshGroupFilter); + + myMeshOrSubMeshOrGroupFilter = + new SMESH_LogicalFilter(aListOfFilters, SMESH_LogicalFilter::LO_OR); + + myHelpFileName = "Offset_page.html"; + + Init(); + + /* signals and slots connections */ + connect(buttonOk, SIGNAL(clicked()), this, SLOT(ClickOnOk())); + connect(buttonCancel, SIGNAL(clicked()), this, SLOT(reject())); + connect(buttonApply, SIGNAL(clicked()), this, SLOT(ClickOnApply())); + connect(buttonHelp, SIGNAL(clicked()), this, SLOT(ClickOnHelp())); + + //connect(SelectElementsButton, SIGNAL (clicked()), this, SLOT(SetEditCurrentArgument())); + + connect(mySMESHGUI, SIGNAL (SignalDeactivateActiveDialog()), this, SLOT(DeactivateActiveDialog())); + connect(mySelectionMgr, SIGNAL(currentSelectionChanged()), this, SLOT(SelectionIntoArgument())); + /* to close dialog if study change */ + connect(mySMESHGUI, SIGNAL(SignalCloseAllDialogs()), this, SLOT(reject())); + connect(mySMESHGUI, SIGNAL(SignalActivatedViewManager()), this, SLOT(onOpenView())); + connect(mySMESHGUI, SIGNAL(SignalCloseView()), this, SLOT(onCloseView())); + + connect(LineEditElements, SIGNAL(textChanged(const QString&)), SLOT(onTextChange(const QString&))); + connect(CheckBoxMesh, SIGNAL(toggled(bool)), SLOT(onSelectMesh(bool))); + connect(ActionGroup, SIGNAL(buttonClicked(int)), SLOT(onActionClicked(int))); + + connect(SpinBox, SIGNAL(valueChanged(double)), this, SLOT(toDisplaySimulation())); + + //To Connect preview check box + connectPreviewControl(); + + SelectionIntoArgument(); + onActionClicked(MOVE_ELEMS_BUTTON); +} + +//================================================================================= +// function : ~SMESHGUI_OffsetDlg() +// purpose : Destroys the object and frees any allocated resources +//================================================================================= +SMESHGUI_OffsetDlg::~SMESHGUI_OffsetDlg() +{ + if ( myFilterDlg ) { + myFilterDlg->setParent( 0 ); + delete myFilterDlg; + myFilterDlg = 0; + } +} + +//================================================================================= +// function : Init() +// purpose : +//================================================================================= +void SMESHGUI_OffsetDlg::Init (bool ResetControls) +{ + myBusy = false; + myObjects.clear(); + myObjectsNames.clear(); + myMeshes.clear(); + + LineEditElements->clear(); + myElementsId = ""; + myNbOkElements = 0; + + buttonOk->setEnabled(false); + buttonApply->setEnabled(false); + + myActor = 0; + + if (ResetControls) + { + SpinBox->SetValue(1.0); + myPreviewCheckBox->setChecked(false); + onDisplaySimulation(false); + + ActionGroup->button( MOVE_ELEMS_BUTTON )->setChecked(true); + CheckBoxMesh->setChecked(true); + onSelectMesh(true); + } +} + +//================================================================================= +// function : ClickOnApply() +// purpose : +//================================================================================= +bool SMESHGUI_OffsetDlg::ClickOnApply() +{ - if (mySMESHGUI->isActiveStudyLocked()) ++ if (mySMESHGUI->isStudyLocked()) + return false; + + if( !isValid() ) + return false; + + SUIT_OverrideCursor aWaitCursor; + + if (myNbOkElements) + { + QStringList aListElementsId = myElementsId.split(" ", QString::SkipEmptyParts); + + SMESH::long_array_var anElementsId = new SMESH::long_array; + anElementsId->length(aListElementsId.count()); + for (int i = 0; i < aListElementsId.count(); i++) + anElementsId[i] = aListElementsId[i].toInt(); + + double offsetValue = SpinBox->value(); + + QStringList aParameters; + aParameters << SpinBox->text(); + + int actionButton = ActionGroup->checkedId(); + bool makeGroups = ( MakeGroupsCheck->isEnabled() && MakeGroupsCheck->isChecked() ); + SMESH::ListOfGroups_var groups; + SMESH::SMESH_Mesh_var mesh; + QStringList anEntryList; + try + { + switch ( actionButton ) { + + case MOVE_ELEMS_BUTTON: + if ( CheckBoxMesh->isChecked() ) + for ( int i = 0; i < myObjects.count(); i++ ) { + SMESH::SMESH_MeshEditor_var aMeshEditor = myMeshes[i]->GetMeshEditor(); + myMeshes[i]->SetParameters( aParameters.join( ":" ).toLatin1().constData() ); + mesh = aMeshEditor->Offset( myObjects[i], offsetValue, true, "", groups.out() ); + } + else { + SMESH::SMESH_MeshEditor_var aMeshEditor = myMeshes[0]->GetMeshEditor(); + SMESH::IDSource_wrap src = aMeshEditor->MakeIDSource(anElementsId, SMESH::FACE); + myMeshes[0]->SetParameters( aParameters.join( ":" ).toLatin1().constData() ); + mesh = aMeshEditor->Offset( src, offsetValue, true, "", groups.out() ); + } + break; + + case COPY_ELEMS_BUTTON: + if ( CheckBoxMesh->isChecked() ) + for ( int i = 0; i < myObjects.count(); i++ ) { + SMESH::SMESH_MeshEditor_var aMeshEditor = myMeshes[i]->GetMeshEditor(); + myMeshes[i]->SetParameters(aParameters.join( ":" ).toLatin1().constData()); + mesh = aMeshEditor->Offset( myObjects[i], offsetValue, makeGroups, "", groups.out() ); + } + else { + SMESH::SMESH_MeshEditor_var aMeshEditor = myMeshes[0]->GetMeshEditor(); + SMESH::IDSource_wrap src = aMeshEditor->MakeIDSource(anElementsId, SMESH::FACE ); + myMeshes[0]->SetParameters(aParameters.join( ":" ).toLatin1().constData()); + mesh = aMeshEditor->Offset( src, offsetValue, makeGroups, "", groups.out() ); + } + break; + + case MAKE_MESH_BUTTON: { + SMESH::SMESH_Mesh_var mesh; + if ( CheckBoxMesh->isChecked() ) { + for ( int i = 0; i < myObjects.count(); i++ ) { + QString aName = + SMESH::UniqueMeshName( LineEditNewMesh->text().replace( "*", myObjectsNames[i] )); + SMESH::SMESH_MeshEditor_var aMeshEditor = myMeshes[i]->GetMeshEditor(); + myMeshes[i]->SetParameters(aParameters.join( ":" ).toLatin1().constData()); + mesh = aMeshEditor->Offset( myObjects[i], offsetValue, makeGroups, + aName.toLatin1().data(), groups.out() ); + if( _PTR(SObject) aSObject = SMESH::ObjectToSObject( mesh )) + anEntryList.append( aSObject->GetID().c_str() ); + } + } + else { + SMESH::SMESH_MeshEditor_var aMeshEditor = myMeshes[0]->GetMeshEditor(); + myMeshes[0]->SetParameters(aParameters.join( ":" ).toLatin1().constData()); + SMESH::IDSource_wrap src = aMeshEditor->MakeIDSource(anElementsId, SMESH::FACE ); + mesh = aMeshEditor->Offset( src, offsetValue, makeGroups, + LineEditNewMesh->text().toLatin1().data(), groups.out() ); + if( _PTR(SObject) aSObject = SMESH::ObjectToSObject( mesh ) ) + anEntryList.append( aSObject->GetID().c_str() ); + } + break; + } + } + } + catch ( const SALOME::SALOME_Exception& S_ex ) { + SalomeApp_Tools::QtCatchCorbaException( S_ex ); + } + catch (...) { + } + + for ( int i = 0; i < myObjects.count(); i++ ) { + SMESH_Actor* actor = SMESH::FindActorByObject( myObjects[i] ); + if ( actor ) SMESH::Update( actor->getIO(), true ); + } + + if ( makeGroups || actionButton == MAKE_MESH_BUTTON ) + { + mySMESHGUI->updateObjBrowser(true); // new groups may appear + if( LightApp_Application* anApp = + dynamic_cast( SUIT_Session::session()->activeApplication() ) ) + anApp->browseObjects( anEntryList, isApplyAndClose() ); + } + if ( !isApplyAndClose() ) + { + Init(false); + SelectionIntoArgument(); + } + SMESHGUI::Modified(); + } + + return true; +} + +//================================================================================= +// function : ClickOnOk() +// purpose : +//================================================================================= +void SMESHGUI_OffsetDlg::ClickOnOk() +{ + setIsApplyAndClose( true ); + if( ClickOnApply() ) + reject(); +} + +//================================================================================= +// function : reject() +// purpose : +//================================================================================= +void SMESHGUI_OffsetDlg::reject() +{ + disconnect(mySelectionMgr, 0, this, 0); + mySelectionMgr->clearFilters(); + if (SMESH::GetCurrentVtkView()) { + SMESH::RemoveFilters(); // PAL6938 -- clean all mesh entity filters + SMESH::SetPointRepresentation(false); + } + if ( SVTK_ViewWindow* aViewWindow = SMESH::GetViewWindow( mySMESHGUI )) + aViewWindow->SetSelectionMode( ActorSelection ); + mySMESHGUI->ResetState(); + QDialog::reject(); +} + +//================================================================================= +// function : onOpenView() +// purpose : +//================================================================================= +void SMESHGUI_OffsetDlg::onOpenView() +{ + if ( mySelector ) { + SMESH::SetPointRepresentation(false); + } + else { + mySelector = SMESH::GetViewWindow( mySMESHGUI )->GetSelector(); + ActivateThisDialog(); + } +} + +//================================================================================= +// function : onCloseView() +// purpose : +//================================================================================= +void SMESHGUI_OffsetDlg::onCloseView() +{ + DeactivateActiveDialog(); + mySelector = 0; +} + +//================================================================================= +// function : ClickOnHelp() +// purpose : +//================================================================================= +void SMESHGUI_OffsetDlg::ClickOnHelp() +{ + LightApp_Application* app = (LightApp_Application*)(SUIT_Session::session()->activeApplication()); + if (app) + app->onHelpContextModule(mySMESHGUI ? app->moduleName(mySMESHGUI->moduleName()) : QString(""), myHelpFileName); + else { + QString platform; +#ifdef WIN32 + platform = "winapplication"; +#else + platform = "application"; +#endif + SUIT_MessageBox::warning(this, tr("WRN_WARNING"), + tr("EXTERNAL_BROWSER_CANNOT_SHOW_PAGE"). + arg(app->resourceMgr()->stringValue("ExternalBrowser", + platform)). + arg(myHelpFileName)); + } +} + +//======================================================================= +// function : onTextChange() +// purpose : +//======================================================================= + +void SMESHGUI_OffsetDlg::onTextChange (const QString& theNewText) +{ + if (myBusy) return; + BusyLocker lock( myBusy ); + + myNbOkElements = 0; + + buttonOk->setEnabled(false); + buttonApply->setEnabled(false); + + // highlight entered elements + SMDS_Mesh* aMesh = 0; + if (myActor) + aMesh = myActor->GetObject()->GetMesh(); + + if (aMesh) { + Handle(SALOME_InteractiveObject) anIO = myActor->getIO(); + + TColStd_MapOfInteger newIndices; + + QStringList aListId = theNewText.split(" ", QString::SkipEmptyParts); + for (int i = 0; i < aListId.count(); i++) + { + if ( const SMDS_MeshElement * e = aMesh->FindElement(aListId[ i ].toInt())) + newIndices.Add( e->GetID() ); + myNbOkElements++; + } + + mySelector->AddOrRemoveIndex( anIO, newIndices, false ); + if ( SVTK_ViewWindow* aViewWindow = SMESH::GetViewWindow( mySMESHGUI )) + aViewWindow->highlight( anIO, true, true ); + + myElementsId = theNewText; + } + + if (myNbOkElements) { + buttonOk->setEnabled(true); + buttonApply->setEnabled(true); + } +} + +//================================================================================= +// function : SelectionIntoArgument() +// purpose : Called when selection as changed or other case +//================================================================================= +void SMESHGUI_OffsetDlg::SelectionIntoArgument() +{ + if (myBusy) return; + if (myFilterDlg && myFilterDlg->isVisible()) return; // filter dlg active + + BusyLocker lock( myBusy ); + + // clear + myActor = 0; + QString aString = ""; + onDisplaySimulation(false); + + LineEditElements->setText(aString); + myNbOkElements = 0; + buttonOk->setEnabled(false); + buttonApply->setEnabled(false); + + if (!GroupButtons->isEnabled()) // inactive + return; + + // get selected mesh + SALOME_ListIO aList; + mySelectionMgr->selectedObjects(aList); + + int nbSel = aList.Extent(); + if (nbSel < 1) + return; + + myElementsId = ""; + myObjects.clear(); + myObjectsNames.clear(); + myMeshes.clear(); + + for ( SALOME_ListIteratorOfListIO it( aList ); it.More(); it.Next() ) + { + Handle(SALOME_InteractiveObject) IO = it.Value(); + SMESH::SMESH_Mesh_var aMesh = SMESH::GetMeshByIO( IO ); + if ( aMesh->_is_nil() || aMesh->NbFaces() == 0 ) + return; + + myActor = SMESH::FindActorByObject( aMesh ); + if ( !myActor ) + myActor = SMESH::FindActorByEntry( IO->getEntry() ); + + SMESH::SMESH_IDSource_var idSrc = SMESH::IObjectToInterface( IO ); + if ( _PTR(SObject) obj = SMESH::FindSObject( idSrc )) + { + std::string name = obj->GetName(); + if ( !name.empty() ) + { + myObjects << idSrc; + myObjectsNames << name.c_str(); + myMeshes << aMesh; + } + } + } + + // MakeGroups is available if there are groups and "Copy" + int aNbGroups = 0; + for ( int i = 0; i < myMeshes.count(); i++ ) + aNbGroups += myMeshes[i]->NbGroups(); + + if ( aNbGroups == 0 ) { + MakeGroupsCheck->setChecked(false); + MakeGroupsCheck->setEnabled(false); + } + else if ( ActionGroup->checkedId() != MOVE_ELEMS_BUTTON ) { + MakeGroupsCheck->setEnabled(true); + } + + if (CheckBoxMesh->isChecked()) { + if (myMeshes.isEmpty()) + return; + SMESH::GetNameOfSelectedIObjects( mySelectionMgr, aString ); + } + else { + int aNbUnits = SMESH::GetNameOfSelectedElements(mySelector, aList.First(), aString); + myElementsId = aString; + if (aNbUnits < 1) + return; + } + + myNbOkElements = true; + + LineEditElements->setText(aString); + LineEditElements->repaint(); + LineEditElements->setEnabled(false); // to fully update lineedit IPAL 19809 + LineEditElements->setEnabled(true); + setNewMeshName(); + + buttonOk->setEnabled(true); + buttonApply->setEnabled(true); + + onDisplaySimulation(true); +} + +//================================================================================= +// function : DeactivateActiveDialog() +// purpose : +//================================================================================= + +void SMESHGUI_OffsetDlg::DeactivateActiveDialog() +{ + if (ConstructorsBox->isEnabled()) + { + ConstructorsBox->setEnabled(false); + GroupArguments->setEnabled(false); + GroupButtons->setEnabled(false); + mySMESHGUI->ResetState(); + mySMESHGUI->SetActiveDialogBox(0); + } +} + +//================================================================================= +// function : ActivateThisDialog() +// purpose : +//================================================================================= + +void SMESHGUI_OffsetDlg::ActivateThisDialog() +{ + /* Emit a signal to deactivate the active dialog */ + mySMESHGUI->EmitSignalDeactivateDialog(); + ConstructorsBox->setEnabled(true); + GroupArguments->setEnabled(true); + GroupButtons->setEnabled(true); + + mySMESHGUI->SetActiveDialogBox((QDialog*)this); + + if ( SVTK_ViewWindow* aViewWindow = SMESH::GetViewWindow( mySMESHGUI )) + aViewWindow->SetSelectionMode( CellSelection ); + + SelectionIntoArgument(); +} + +//================================================================================= +// function : enterEvent() +// purpose : +//================================================================================= + +void SMESHGUI_OffsetDlg::enterEvent (QEvent*) +{ + if (!ConstructorsBox->isEnabled()) { + SVTK_ViewWindow* aViewWindow = SMESH::GetViewWindow( mySMESHGUI ); + if ( aViewWindow && !mySelector) { + mySelector = aViewWindow->GetSelector(); + } + ActivateThisDialog(); + } +} + +//======================================================================= +//function : onSelectMesh +//purpose : +//======================================================================= + +void SMESHGUI_OffsetDlg::onSelectMesh (bool toSelectMesh) +{ + if (toSelectMesh) + TextLabelElements->setText(tr("SMESH_NAME")); + else + TextLabelElements->setText(tr("SMESH_ID_ELEMENTS")); + myFilterBtn->setEnabled(!toSelectMesh); + + mySelectionMgr->clearFilters(); + SMESH::SetPointRepresentation(false); + + if (toSelectMesh) + { + if ( SVTK_ViewWindow* aViewWindow = SMESH::GetViewWindow( mySMESHGUI )) + aViewWindow->SetSelectionMode( ActorSelection ); + mySelectionMgr->installFilter( myMeshOrSubMeshOrGroupFilter ); + LineEditElements->setReadOnly( true ); + LineEditElements->setValidator( 0 ); + } + else + { + if ( SVTK_ViewWindow* aViewWindow = SMESH::GetViewWindow( mySMESHGUI )) + aViewWindow->SetSelectionMode( FaceSelection ); + LineEditElements->setReadOnly( false ); + LineEditElements->setValidator( myIdValidator ); + onTextChange(LineEditElements->text()); + hidePreview(); + } + + SelectionIntoArgument(); +} + +//======================================================================= +//function : onActionClicked +//purpose : slot called when an action type changed +//======================================================================= + +void SMESHGUI_OffsetDlg::onActionClicked(int button) +{ + int aNbGroups = 0; + for ( int i = 0; i < myMeshes.count(); i++ ) + aNbGroups += myMeshes[i]->NbGroups(); + + switch ( button ) { + case MOVE_ELEMS_BUTTON: + MakeGroupsCheck->setEnabled(false); + LineEditNewMesh->setEnabled(false); + break; + case COPY_ELEMS_BUTTON: + LineEditNewMesh->setEnabled(false); + MakeGroupsCheck->setText( tr("SMESH_MAKE_GROUPS")); + MakeGroupsCheck->setEnabled( myMeshes.isEmpty() || aNbGroups > 0 ); + break; + case MAKE_MESH_BUTTON: + LineEditNewMesh->setEnabled(true); + MakeGroupsCheck->setText( tr("SMESH_COPY_GROUPS")); + MakeGroupsCheck->setEnabled( myMeshes.isEmpty() || aNbGroups > 0 ); + break; + } + setNewMeshName(); + //toDisplaySimulation(); +} + +//======================================================================= +//function : setNewMeshName +//purpose : update contents of LineEditNewMesh +//======================================================================= + +void SMESHGUI_OffsetDlg::setNewMeshName() +{ + LineEditNewMesh->setText(""); + if ( LineEditNewMesh->isEnabled() && !myMeshes.isEmpty() ) { + QString name; + if ( CheckBoxMesh->isChecked() ) { + name = myObjects.count() > 1 ? "*" : LineEditElements->text(); + } + else { + _PTR(SObject) meshSO = SMESH::FindSObject( myMeshes[0] ); + name = meshSO->GetName().c_str(); + } + if ( !name.isEmpty() ) + LineEditNewMesh->setText( SMESH::UniqueMeshName( name, "Offset")); + } +} + +//================================================================================= +// function : keyPressEvent() +// purpose : +//================================================================================= + +void SMESHGUI_OffsetDlg::keyPressEvent( QKeyEvent* e ) +{ + QDialog::keyPressEvent( e ); + if ( e->isAccepted() ) + return; + + if ( e->key() == Qt::Key_F1 ) { + e->accept(); + ClickOnHelp(); + } +} + +//================================================================================= +// function : setFilters() +// purpose : SLOT. Called when "Filter" button pressed. +//================================================================================= + +void SMESHGUI_OffsetDlg::setFilters() +{ + if ( myMeshes.isEmpty() ) { + SUIT_MessageBox::critical(this, tr("SMESH_ERROR"), tr("NO_MESH_SELECTED")); + return; + } + if ( !myFilterDlg ) { + myFilterDlg = new SMESHGUI_FilterDlg( mySMESHGUI, SMESH::ALL ); + connect(myFilterDlg, SIGNAL(Accepted()), SLOT(onFilterAccepted())); + } + + myFilterDlg->Init( SMESH::FACE ); + myFilterDlg->SetSelection(); + myFilterDlg->SetMesh( myMeshes[0] ); + myFilterDlg->SetSourceWg( LineEditElements ); + + myFilterDlg->show(); +} + +//======================================================================= +// name : onFilterAccepted() +// Purpose : SLOT. Called when Filter dlg closed with OK button. +// Activate [Apply] if no Actor is available +//======================================================================= + +void SMESHGUI_OffsetDlg::onFilterAccepted() +{ + if ( myMeshes.length() > 0 && !buttonOk->isEnabled() ) + { + myElementsId = LineEditElements->text(); + QStringList aListElementsId = myElementsId.split(" ", QString::SkipEmptyParts); + myNbOkElements = aListElementsId.count(); + buttonOk->setEnabled ( myNbOkElements ); + buttonApply->setEnabled( myNbOkElements ); + } +} + +//================================================================================= +// function : isValid +// purpose : +//================================================================================= + +bool SMESHGUI_OffsetDlg::isValid() +{ + return true; +} + +//================================================================================= +// function : onDisplaySimulation +// purpose : Show/Hide preview +//================================================================================= +void SMESHGUI_OffsetDlg::onDisplaySimulation( bool toDisplayPreview ) +{ + SUIT_OverrideCursor aWaitCursor; + + if (myPreviewCheckBox->isChecked() && toDisplayPreview) + { + if ( myNbOkElements && isValid() ) + { + double offsetValue = SpinBox->value(); + + SMESH::ListOfGroups_var groups; + SMESH::SMESH_Mesh_var mesh; + + try + { + QList aMeshPreviewStruct; + + if ( CheckBoxMesh->isChecked()) + for ( int i = 0; i < myObjects.count(); i++ ) + { + SMESH::SMESH_MeshEditor_var aMeshEditor = myMeshes[i]->GetMeshEditPreviewer(); + mesh = aMeshEditor->Offset( myObjects[i], offsetValue, false, "", groups.out() ); + aMeshPreviewStruct << aMeshEditor->GetPreviewData(); + } + else + { + SMESH::long_array_var anElementsId = new SMESH::long_array; + QStringList aListElementsId = myElementsId.split(" ", QString::SkipEmptyParts); + anElementsId->length(aListElementsId.count()); + for (int i = 0; i < aListElementsId.count(); i++) + anElementsId[i] = aListElementsId[i].toInt(); + + SMESH::SMESH_MeshEditor_var aMeshEditor = myMeshes[0]->GetMeshEditPreviewer(); + SMESH::IDSource_wrap src = aMeshEditor->MakeIDSource(anElementsId, SMESH::FACE); + mesh = aMeshEditor->Offset( src, offsetValue, false, "", groups.out() ); + aMeshPreviewStruct << aMeshEditor->GetPreviewData(); + } + setSimulationPreview(aMeshPreviewStruct); + + } catch (...) { + hidePreview(); + } + } else { + hidePreview(); + } + } else { + hidePreview(); + } +} diff --cc src/SMESH_I/CMakeLists.txt index 8be022d98,2bb789ab3..b5183dbe7 --- a/src/SMESH_I/CMakeLists.txt +++ b/src/SMESH_I/CMakeLists.txt @@@ -70,10 -69,12 +69,11 @@@ SET(_link_LIBRARIE ${KERNEL_SalomeGenericObj} ${KERNEL_SalomeIDLKERNEL} ${KERNEL_SALOMELocalTrace} + ${KERNEL_SalomeKernelHelpers} - ${CAS_TKCDF} - ${CAS_TKBO} - ${CAS_TKShHealing} + ${OpenCASCADE_ApplicationFramework_LIBRARIES} + ${OpenCASCADE_ModelingAlgorithms_LIBRARIES} ${GEOM_GEOMClient} - ${GEOM_SalomeIDLGEOM} + ${GEOM_SalomeIDLGEOM} SalomeIDLSMESH SMESHimpl SMDS diff --cc src/SMESH_I/SMESH_Gen_i.cxx index ea45c41ce,bdf44dc49..25f0c2c7f --- a/src/SMESH_I/SMESH_Gen_i.cxx +++ b/src/SMESH_I/SMESH_Gen_i.cxx @@@ -2550,31 -2537,29 +2536,31 @@@ SMESH_Gen_i::ConcatenateCommon(const SM // create groups of just added elements - SMESH::SMESH_Group_var aNewGroup; - SMESH::ElementType aGroupType; + SMESH::SMESH_Group_var newGroup; + SMESH::ElementType groupType; if ( theCommonGroups ) { - SMESH::long_array_var curState = aNewMesh->GetNbElementsByType(); + // type names + const char* typeNames[] = { "All","Nodes","Edges","Faces","Volumes","0DElems","Balls" }; + { // check of typeNames: compilation failure mains that NB_ELEMENT_TYPES changed: + const int nbNames = sizeof(typeNames) / sizeof(const char*); + int _assert[( nbNames == SMESH::NB_ELEMENT_TYPES ) ? 2 : -1 ]; _assert[0]=_assert[1]=0; + } + + SMESH::long_array_var curState = newMesh->GetNbElementsByType(); - for( aGroupType = SMESH::NODE; - aGroupType < SMESH::NB_ELEMENT_TYPES; - aGroupType = (SMESH::ElementType)( aGroupType + 1 )) + for( groupType = SMESH::NODE; + groupType < SMESH::NB_ELEMENT_TYPES; + groupType = (SMESH::ElementType)( groupType + 1 )) { - if ( curState[ aGroupType ] <= prevState[ aGroupType ]) - continue; + if ( curState[ groupType ] <= prevState[ groupType ]) + continue; // no elements of groupType added from the i-th mesh // make a group name - const char* typeNames[] = { "All","Nodes","Edges","Faces","Volumes","0DElems","Balls" }; - { // check of typeNames: compilation failure mains that NB_ELEMENT_TYPES changed: - const int nbNames = sizeof(typeNames) / sizeof(const char*); - int _assert[( nbNames == SMESH::NB_ELEMENT_TYPES ) ? 2 : -1 ]; _assert[0]=_assert[1]=0; - } - string groupName = "Gr"; - SALOMEDS::SObject_wrap aMeshSObj = ObjectToSObject( theMeshesArray[i] ); - if ( aMeshSObj ) { - CORBA::String_var name = aMeshSObj->GetName(); + std::string groupName = "Gr"; - SALOMEDS::SObject_wrap meshSO = ObjectToSObject( myCurrentStudy, theMeshesArray[i] ); ++ SALOMEDS::SObject_wrap meshSO = ObjectToSObject( theMeshesArray[i] ); + if ( meshSO ) { + CORBA::String_var name = meshSO->GetName(); groupName += name; } groupName += "_"; @@@ -2702,12 -2711,13 +2688,12 @@@ } // IPAL21468 Change icon of compound because it need not be computed. - SALOMEDS::SObject_wrap meshSO = ObjectToSObject( myCurrentStudy, newMesh ); - SALOMEDS::SObject_wrap aMeshSObj = ObjectToSObject( aNewMesh ); - SetPixMap( aMeshSObj, "ICON_SMESH_TREE_MESH" ); ++ SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh ); + SetPixMap( meshSO, "ICON_SMESH_TREE_MESH" ); - if (aNewMeshDS) - aNewMeshDS->Modified(); + newMeshDS->Modified(); - return aNewMesh._retn(); + return newMesh._retn(); } //================================================================================ @@@ -3338,8 -3352,8 +3331,8 @@@ SALOMEDS::TMPFile* SMESH_Gen_i::Save( S // write applied hypotheses if exist SALOMEDS::SObject_wrap myHypBranch; found = gotBranch->FindSubObject( GetRefOnAppliedHypothesisTag(), myHypBranch.inout() ); - if ( found && !shapeRefFound && hasShape) { // remove applied hyps + if ( found && !shapeRefFound && hasShape ) { // remove applied hyps - myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( myHypBranch ); + aStudy->NewBuilder()->RemoveObjectWithChildren( myHypBranch ); } if ( found && (shapeRefFound || !hasShape) ) { aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup ); diff --cc src/SMESH_I/SMESH_Gen_i_1.cxx index 047907e64,6b3da78a1..e1499f8a7 --- a/src/SMESH_I/SMESH_Gen_i_1.cxx +++ b/src/SMESH_I/SMESH_Gen_i_1.cxx @@@ -492,7 -499,7 +499,7 @@@ SALOMEDS::SObject_ptr SMESH_Gen_i::Publ // Publishing a hypothesis or algorithm SMESH::SMESH_Hypothesis_var aHyp = SMESH::SMESH_Hypothesis::_narrow( theIOR ); if ( aSO->_is_nil() && !aHyp->_is_nil() ) - aSO = PublishHypothesis( theStudy, aHyp, theName ); - aSO = PublishHypothesis( aHyp ); ++ aSO = PublishHypothesis( aHyp, theName ); // Publishing a group SMESH::SMESH_GroupBase_var aGroup = SMESH::SMESH_GroupBase::_narrow(theIOR); diff --cc src/SMESH_SWIG/StdMeshersBuilder.py index 180ba86be,1d3d393d7..48356cac7 --- a/src/SMESH_SWIG/StdMeshersBuilder.py +++ b/src/SMESH_SWIG/StdMeshersBuilder.py @@@ -186,23 -136,16 +186,23 @@@ class StdMeshersBuilder_Segment(Mesh_Al hyp.SetUsePreestimatedLength( length == 0.0 ) return hyp - ## Defines "NumberOfSegments" hypothesis to cut an edge in a fixed number of segments - # @param n for the number of segments that cut an edge - # @param s for the scale factor (optional) - # @param reversedEdges is a list of edges to mesh using reversed orientation. - # A list item can also be a tuple (edge, 1st_vertex_of_edge) - # @param UseExisting if ==true - searches for an existing hypothesis created with - # the same parameters, else (default) - create a new one - # @return an instance of StdMeshers_NumberOfSegments hypothesis - # @ingroup l3_hypos_1dhyps def NumberOfSegments(self, n, s=[], reversedEdges=[], UseExisting=0): + """ - Defines "NumberOfSegments" hypothesis to cut an edge in a fixed number of segments ++ Defines "NumberOfSegments" hypothesis to cut an edge in a fixed number of segments + + Parameters: + n: for the number of segments that cut an edge + s: for the scale factor (optional) + reversedEdges: is a list of edges to mesh using reversed orientation. - A list item can also be a tuple (edge, 1st_vertex_of_edge) ++ A list item can also be a tuple (edge, 1st_vertex_of_edge) + UseExisting: if ==true - searches for an existing hypothesis created with - the same parameters, else (default) - create a new one ++ the same parameters, else (default) - create a new one + + Returns: - an instance of StdMeshers_NumberOfSegments hypothesis ++ an instance of StdMeshers_NumberOfSegments hypothesis + """ + - ++ if not isinstance(reversedEdges,list): #old version script, before adding reversedEdges reversedEdges, UseExisting = [], reversedEdges entry = self.MainShapeEntry() @@@ -221,11 -164,10 +221,11 @@@ hyp.SetObjectEntry( entry ) return hyp - ## Private method - # - # Checks if the given "NumberOfSegments" hypothesis has the same parameters as the given arguments def _compareNumberOfSegments(self, hyp, args): + """ - Private method - Checks if the given "NumberOfSegments" hypothesis has the same parameters as the given arguments ++ Private method ++ Checks if the given "NumberOfSegments" hypothesis has the same parameters as the given arguments + """ if hyp.GetNumberOfSegments() == args[0]: if len(args) == 3: if hyp.GetReversedEdges() == args[1]: @@@ -240,24 -182,18 +240,24 @@@ return True return False - ## Defines "Adaptive" hypothesis to cut an edge into segments keeping segment size - # within the given range and considering (1) deflection of segments from the edge - # and (2) distance from segments to closest edges and faces to have segment length - # not longer than two times shortest distances to edges and faces. - # @param minSize defines the minimal allowed segment length - # @param maxSize defines the maximal allowed segment length - # @param deflection defines the maximal allowed distance from a segment to an edge - # @param UseExisting if ==true - searches for an existing hypothesis created with - # the same parameters, else (default) - creates a new one - # @return an instance of StdMeshers_Adaptive1D hypothesis - # @ingroup l3_hypos_1dhyps def Adaptive(self, minSize, maxSize, deflection, UseExisting=False): + """ + Defines "Adaptive" hypothesis to cut an edge into segments keeping segment size + within the given range and considering (1) deflection of segments from the edge + and (2) distance from segments to closest edges and faces to have segment length + not longer than two times shortest distances to edges and faces. + + Parameters: + minSize: defines the minimal allowed segment length + maxSize: defines the maximal allowed segment length + deflection: defines the maximal allowed distance from a segment to an edge + UseExisting: if ==true - searches for an existing hypothesis created with + the same parameters, else (default) - creates a new one + + Returns: + an instance of StdMeshers_Adaptive1D hypothesis + """ - ++ from salome.smesh.smeshBuilder import IsEqual compFun = lambda hyp, args: ( IsEqual(hyp.GetMinSize(), args[0]) and \ IsEqual(hyp.GetMaxSize(), args[1]) and \ @@@ -269,23 -205,17 +269,23 @@@ hyp.SetDeflection(deflection) return hyp - ## Defines "Arithmetic1D" hypothesis to cut an edge in several segments with a length - # that changes in arithmetic progression - # @param start defines the length of the first segment - # @param end defines the length of the last segment - # @param reversedEdges is a list of edges to mesh using reversed orientation. - # A list item can also be a tuple (edge, 1st_vertex_of_edge) - # @param UseExisting if ==true - searches for an existing hypothesis created with - # the same parameters, else (default) - creates a new one - # @return an instance of StdMeshers_Arithmetic1D hypothesis - # @ingroup l3_hypos_1dhyps def Arithmetic1D(self, start, end, reversedEdges=[], UseExisting=0): - """ - Defines "Arithmetic1D" hypothesis to cut an edge in several segments with a length - that changes in arithmetic progression - - Parameters: - start: defines the length of the first segment - end: defines the length of the last segment - reversedEdges: is a list of edges to mesh using reversed orientation. - A list item can also be a tuple (edge, 1st_vertex_of_edge) - UseExisting: if ==true - searches for an existing hypothesis created with - the same parameters, else (default) - creates a new one - - Returns: - an instance of StdMeshers_Arithmetic1D hypothesis - """ ++ """ ++ Defines "Arithmetic1D" hypothesis to cut an edge in several segments with a length ++ that changes in arithmetic progression ++ ++ Parameters: ++ start: defines the length of the first segment ++ end: defines the length of the last segment ++ reversedEdges: is a list of edges to mesh using reversed orientation. ++ A list item can also be a tuple (edge, 1st_vertex_of_edge) ++ UseExisting: if ==true - searches for an existing hypothesis created with ++ the same parameters, else (default) - creates a new one ++ ++ Returns: ++ an instance of StdMeshers_Arithmetic1D hypothesis ++ """ + if not isinstance(reversedEdges,list): #old version script, before adding reversedEdges reversedEdges, UseExisting = [], reversedEdges reversedEdgeInd = self.ReversedEdgeIndices(reversedEdges) @@@ -303,23 -233,17 +303,23 @@@ hyp.SetObjectEntry( entry ) return hyp - ## Defines "GeometricProgression" hypothesis to cut an edge in several - # segments with a length that changes in Geometric progression - # @param start defines the length of the first segment - # @param ratio defines the common ratio of the geometric progression - # @param reversedEdges is a list of edges to mesh using reversed orientation. - # A list item can also be a tuple (edge, 1st_vertex_of_edge) - # @param UseExisting if ==true - searches for an existing hypothesis created with - # the same parameters, else (default) - creates a new one - # @return an instance of StdMeshers_Geometric1D hypothesis - # @ingroup l3_hypos_1dhyps def GeometricProgression(self, start, ratio, reversedEdges=[], UseExisting=0): - """ - Defines "GeometricProgression" hypothesis to cut an edge in several - segments with a length that changes in Geometric progression - - Parameters: - start: defines the length of the first segment - ratio: defines the common ratio of the geometric progression - reversedEdges: is a list of edges to mesh using reversed orientation. - A list item can also be a tuple (edge, 1st_vertex_of_edge) - UseExisting: if ==true - searches for an existing hypothesis created with - the same parameters, else (default) - creates a new one - - Returns: - an instance of StdMeshers_Geometric1D hypothesis - """ ++ """ ++ Defines "GeometricProgression" hypothesis to cut an edge in several ++ segments with a length that changes in Geometric progression ++ ++ Parameters: ++ start: defines the length of the first segment ++ ratio: defines the common ratio of the geometric progression ++ reversedEdges: is a list of edges to mesh using reversed orientation. ++ A list item can also be a tuple (edge, 1st_vertex_of_edge) ++ UseExisting: if ==true - searches for an existing hypothesis created with ++ the same parameters, else (default) - creates a new one ++ ++ Returns: ++ an instance of StdMeshers_Geometric1D hypothesis ++ """ + reversedEdgeInd = self.ReversedEdgeIndices(reversedEdges) entry = self.MainShapeEntry() from salome.smesh.smeshBuilder import IsEqual @@@ -335,26 -259,20 +335,26 @@@ hyp.SetObjectEntry( entry ) return hyp - ## Defines "FixedPoints1D" hypothesis to cut an edge using parameter - # on curve from 0 to 1 (additionally it is neecessary to check - # orientation of edges and create list of reversed edges if it is - # needed) and sets numbers of segments between given points (default - # values are 1) - # @param points defines the list of parameters on curve - # @param nbSegs defines the list of numbers of segments - # @param reversedEdges is a list of edges to mesh using reversed orientation. - # A list item can also be a tuple (edge, 1st_vertex_of_edge) - # @param UseExisting if ==true - searches for an existing hypothesis created with - # the same parameters, else (default) - creates a new one - # @return an instance of StdMeshers_FixedPoints1D hypothesis - # @ingroup l3_hypos_1dhyps def FixedPoints1D(self, points, nbSegs=[1], reversedEdges=[], UseExisting=0): + """ - Defines "FixedPoints1D" hypothesis to cut an edge using parameter - on curve from 0 to 1 (additionally it is neecessary to check - orientation of edges and create list of reversed edges if it is - needed) and sets numbers of segments between given points (default - values are 1) - - Parameters: - points: defines the list of parameters on curve - nbSegs: defines the list of numbers of segments - reversedEdges: is a list of edges to mesh using reversed orientation. - A list item can also be a tuple (edge, 1st_vertex_of_edge) - UseExisting: if ==true - searches for an existing hypothesis created with - the same parameters, else (default) - creates a new one - - Returns: - an instance of StdMeshers_FixedPoints1D hypothesis - """ ++ Defines "FixedPoints1D" hypothesis to cut an edge using parameter ++ on curve from 0 to 1 (additionally it is neecessary to check ++ orientation of edges and create list of reversed edges if it is ++ needed) and sets numbers of segments between given points (default ++ values are 1) ++ ++ Parameters: ++ points: defines the list of parameters on curve ++ nbSegs: defines the list of numbers of segments ++ reversedEdges: is a list of edges to mesh using reversed orientation. ++ A list item can also be a tuple (edge, 1st_vertex_of_edge) ++ UseExisting: if ==true - searches for an existing hypothesis created with ++ the same parameters, else (default) - creates a new one ++ ++ Returns: ++ an instance of StdMeshers_FixedPoints1D hypothesis ++ """ + if not isinstance(reversedEdges,list): #old version script, before adding reversedEdges reversedEdges, UseExisting = [], reversedEdges reversedEdgeInd = self.ReversedEdgeIndices(reversedEdges) @@@ -371,22 -289,16 +371,22 @@@ hyp.SetObjectEntry(entry) return hyp - ## Defines "StartEndLength" hypothesis to cut an edge in several segments with increasing geometric length - # @param start defines the length of the first segment - # @param end defines the length of the last segment - # @param reversedEdges is a list of edges to mesh using reversed orientation. - # A list item can also be a tuple (edge, 1st_vertex_of_edge) - # @param UseExisting if ==true - searches for an existing hypothesis created with - # the same parameters, else (default) - creates a new one - # @return an instance of StdMeshers_StartEndLength hypothesis - # @ingroup l3_hypos_1dhyps def StartEndLength(self, start, end, reversedEdges=[], UseExisting=0): + """ + Defines "StartEndLength" hypothesis to cut an edge in several segments with increasing geometric length + + Parameters: + start: defines the length of the first segment + end: defines the length of the last segment + reversedEdges: is a list of edges to mesh using reversed orientation. + A list item can also be a tuple (edge, 1st_vertex_of_edge) + UseExisting: if ==true - searches for an existing hypothesis created with + the same parameters, else (default) - creates a new one + + Returns: + an instance of StdMeshers_StartEndLength hypothesis + """ - ++ if not isinstance(reversedEdges,list): #old version script, before adding reversedEdges reversedEdges, UseExisting = [], reversedEdges reversedEdgeInd = self.ReversedEdgeIndices(reversedEdges) @@@ -404,53 -316,41 +404,53 @@@ hyp.SetObjectEntry( entry ) return hyp - ## Defines "Deflection1D" hypothesis - # @param d for the deflection - # @param UseExisting if ==true - searches for an existing hypothesis created with - # the same parameters, else (default) - create a new one - # @ingroup l3_hypos_1dhyps def Deflection1D(self, d, UseExisting=0): - """ - Defines "Deflection1D" hypothesis ++ """ ++ Defines "Deflection1D" hypothesis + - Parameters: ++ Parameters: + d: for the deflection + UseExisting: if ==true - searches for an existing hypothesis created with + the same parameters, else (default) - create a new one - """ ++ """ + from salome.smesh.smeshBuilder import IsEqual compFun = lambda hyp, args: IsEqual(hyp.GetDeflection(), args[0]) hyp = self.Hypothesis("Deflection1D", [d], UseExisting=UseExisting, CompareMethod=compFun) hyp.SetDeflection(d) return hyp - ## Defines "Propagation" hypothesis that propagates 1D hypotheses - # from an edge where this hypothesis is assigned to - # on all other edges that are at the opposite side in case of quadrangular faces - # This hypothesis should be assigned to an edge to propagate a hypothesis from. - # @ingroup l3_hypos_additi def Propagation(self): - """ - Defines "Propagation" hypothesis that propagates 1D hypotheses - from an edge where this hypothesis is assigned to - on all other edges that are at the opposite side in case of quadrangular faces - This hypothesis should be assigned to an edge to propagate a hypothesis from. - """ ++ """ ++ Defines "Propagation" hypothesis that propagates 1D hypotheses ++ from an edge where this hypothesis is assigned to ++ on all other edges that are at the opposite side in case of quadrangular faces ++ This hypothesis should be assigned to an edge to propagate a hypothesis from. ++ """ + return self.Hypothesis("Propagation", UseExisting=1, CompareMethod=self.CompareEqualHyp) - ## Defines "Propagation of Node Distribution" hypothesis that propagates - # distribution of nodes from an edge where this hypothesis is assigned to, - # to opposite edges of quadrangular faces, so that number of segments on all these - # edges will be the same, as well as relations between segment lengths. - # @ingroup l3_hypos_additi def PropagationOfDistribution(self): - """ - Defines "Propagation of Node Distribution" hypothesis that propagates - distribution of nodes from an edge where this hypothesis is assigned to, - to opposite edges of quadrangular faces, so that number of segments on all these - edges will be the same, as well as relations between segment lengths. - """ ++ """ ++ Defines "Propagation of Node Distribution" hypothesis that propagates ++ distribution of nodes from an edge where this hypothesis is assigned to, ++ to opposite edges of quadrangular faces, so that number of segments on all these ++ edges will be the same, as well as relations between segment lengths. ++ """ + return self.Hypothesis("PropagOfDistribution", UseExisting=1, CompareMethod=self.CompareEqualHyp) - ## Defines "AutomaticLength" hypothesis - # @param fineness for the fineness [0-1] - # @param UseExisting if ==true - searches for an existing hypothesis created with the - # same parameters, else (default) - create a new one - # @ingroup l3_hypos_1dhyps def AutomaticLength(self, fineness=0, UseExisting=0): - """ - Defines "AutomaticLength" hypothesis - - Parameters: - fineness: for the fineness [0-1] - UseExisting: if ==true - searches for an existing hypothesis created with the - same parameters, else (default) - create a new one - """ ++ """ ++ Defines "AutomaticLength" hypothesis ++ ++ Parameters: ++ fineness: for the fineness [0-1] ++ UseExisting: if ==true - searches for an existing hypothesis created with the ++ same parameters, else (default) - create a new one ++ """ + from salome.smesh.smeshBuilder import IsEqual compFun = lambda hyp, args: IsEqual(hyp.GetFineness(), args[0]) hyp = self.Hypothesis("AutomaticLength",[fineness],UseExisting=UseExisting, @@@ -458,22 -358,18 +458,22 @@@ hyp.SetFineness( fineness ) return hyp - ## Defines "SegmentLengthAroundVertex" hypothesis - # @param length for the segment length - # @param vertex for the length localization: the vertex index [0,1] | vertex object. - # Any other integer value means that the hypothesis will be set on the - # whole 1D shape, where Mesh_Segment algorithm is assigned. - # @param UseExisting if ==true - searches for an existing hypothesis created with - # the same parameters, else (default) - creates a new one - # @ingroup l3_algos_segmarv def LengthNearVertex(self, length, vertex=0, UseExisting=0): - """ - Defines "SegmentLengthAroundVertex" hypothesis - - Parameters: - length: for the segment length - vertex: for the length localization: the vertex index [0,1] | vertex object. - Any other integer value means that the hypothesis will be set on the - whole 1D shape, where Mesh_Segment algorithm is assigned. - UseExisting: if ==true - searches for an existing hypothesis created with - the same parameters, else (default) - creates a new one - """ ++ """ ++ Defines "SegmentLengthAroundVertex" hypothesis ++ ++ Parameters: ++ length: for the segment length ++ vertex: for the length localization: the vertex index [0,1] | vertex object. ++ Any other integer value means that the hypothesis will be set on the ++ whole 1D shape, where Mesh_Segment algorithm is assigned. ++ UseExisting: if ==true - searches for an existing hypothesis created with ++ the same parameters, else (default) - creates a new one ++ """ + import types store_geom = self.geom - if type(vertex) is types.IntType: + if isinstance(vertex, int): if vertex == 0 or vertex == 1: from salome.geom import geomBuilder vertex = self.mesh.geompyD.ExtractShapes(self.geom, geomBuilder.geomBuilder.ShapeType["VERTEX"],True)[vertex] @@@ -506,16 -402,15 +506,16 @@@ hyp.SetLength( length ) return hyp - ## Defines "QuadraticMesh" hypothesis, forcing construction of quadratic edges. - # If the 2D mesher sees that all boundary edges are quadratic, - # it generates quadratic faces, else it generates linear faces using - # medium nodes as if they are vertices. - # The 3D mesher generates quadratic volumes only if all boundary faces - # are quadratic, else it fails. - # - # @ingroup l3_hypos_additi def QuadraticMesh(self): - """ - Defines "QuadraticMesh" hypothesis, forcing construction of quadratic edges. - If the 2D mesher sees that all boundary edges are quadratic, - it generates quadratic faces, else it generates linear faces using - medium nodes as if they are vertices. - The 3D mesher generates quadratic volumes only if all boundary faces - are quadratic, else it fails. - """ - ++ """ ++ Defines "QuadraticMesh" hypothesis, forcing construction of quadratic edges. ++ If the 2D mesher sees that all boundary edges are quadratic, ++ it generates quadratic faces, else it generates linear faces using ++ medium nodes as if they are vertices. ++ The 3D mesher generates quadratic volumes only if all boundary faces ++ are quadratic, else it fails. ++ """ ++ hyp = self.Hypothesis("QuadraticMesh", UseExisting=1, CompareMethod=self.CompareEqualHyp) return hyp @@@ -564,35 -447,28 +564,35 @@@ class StdMeshersBuilder_CompositeSegmen pass # end of StdMeshersBuilder_CompositeSegment class -## Defines a segment 1D algorithm for discretization of edges with Python function -# -# It is created by calling smeshBuilder.Mesh.Segment(smeshBuilder.PYTHON,geom=0) -# -# @ingroup l3_algos_basic class StdMeshersBuilder_Segment_Python(Mesh_Algorithm): + """ + Defines a segment 1D algorithm for discretization of edges with Python function - It is created by calling smeshBuilder.Mesh.Segment(smeshBuilder.PYTHON,geom=0) ++ It is created by calling smeshBuilder.Mesh.Segment(smeshBuilder.PYTHON,geom=0) + """ + - ## name of the dynamic method in smeshBuilder.Mesh class - # @internal meshMethod = "Segment" - ## type of algorithm used with helper function in smeshBuilder.Mesh class - # @internal + """ + name of the dynamic method in smeshBuilder.Mesh class + """ algoType = PYTHON - ## doc string of the method - # @internal + """ + type of algorithm used with helper function in smeshBuilder.Mesh class + """ docHelper = "Creates segment 1D algorithm for edges" + """ + doc string of the method + """ - ## Private constructor. - # @param mesh parent mesh object algorithm is assigned to - # @param geom geometry (shape/sub-shape) algorithm is assigned to; - # if it is @c 0 (default), the algorithm is assigned to the main shape def __init__(self, mesh, geom=0): + """ + Private constructor. + + Parameters: + mesh: parent mesh object algorithm is assigned to + geom: geometry (shape/sub-shape) algorithm is assigned to; + if it is :code:`0` (default), the algorithm is assigned to the main shape + """ import Python1dPlugin self.Create(mesh, geom, self.algoType, "libPython1dEngine.so") pass @@@ -801,18 -646,14 +801,18 @@@ class StdMeshersBuilder_Quadrangle(Mesh self.params.SetEnforcedNodes( enfVertices, pStructs ) return self.params - ## Defines "QuadrangleParams" hypothesis with a type of quadrangulation that only - # quadrangles are built in the transition area along the finer meshed sides, - # iff the total quantity of segments on all four sides of the face is even. - # @param reversed if True, transition area is located along the coarser meshed sides. - # @param UseExisting: if ==true - searches for the existing hypothesis created with - # the same parameters, else (default) - creates a new one - # @ingroup l3_hypos_quad def QuadranglePreference(self, reversed=False, UseExisting=0): + """ + Defines "QuadrangleParams" hypothesis with a type of quadrangulation that only + quadrangles are built in the transition area along the finer meshed sides, + if the total quantity of segments on all four sides of the face is even. + - Parameters: ++ Parameters: + reversed: if True, transition area is located along the coarser meshed sides. + UseExisting: if ==true - searches for the existing hypothesis created with + the same parameters, else (default) - creates a new one + """ - ++ if reversed: return self.QuadrangleParameters(QUAD_QUADRANGLE_PREF_REVERSED,UseExisting=UseExisting) return self.QuadrangleParameters(QUAD_QUADRANGLE_PREF,UseExisting=UseExisting) @@@ -1205,26 -980,18 +1205,26 @@@ class StdMeshersBuilder_Prism3D(Mesh_Al pass pass - ## Return 3D hypothesis holding the 1D one def Get3DHypothesis(self): + """ + Returns: + 3D hypothesis holding the 1D one + """ if self.algoType != "RadialPrism_3D": - print "Prism_3D algorithm doesn't support any hypothesis" + print("Prism_3D algorithm doesn't support any hypothesis") return None return self.distribHyp - ## Private method creating a 1D hypothesis and storing it in the LayerDistribution - # hypothesis. Returns the created hypothesis def OwnHypothesis(self, hypType, args=[], so="libStdMeshersEngine.so"): + """ + Private method creating a 1D hypothesis and storing it in the LayerDistribution + hypothesis. + + Returns: + the created hypothesis + """ if self.algoType != "RadialPrism_3D": - print "Prism_3D algorithm doesn't support any hypothesis" + print("Prism_3D algorithm doesn't support any hypothesis") return None if not self.nbLayers is None: self.mesh.GetMesh().RemoveHypothesis( self.geom, self.nbLayers ) @@@ -1238,18 -1004,14 +1237,18 @@@ self.distribHyp.SetLayerDistribution( hyp ) return hyp - ## Defines "NumberOfLayers" hypothesis, specifying the number of layers of - # prisms to build between the inner and outer shells - # @param n number of layers - # @param UseExisting if ==true - searches for the existing hypothesis created with - # the same parameters, else (default) - creates a new one def NumberOfLayers(self, n, UseExisting=0): + """ + Defines "NumberOfLayers" hypothesis, specifying the number of layers of + prisms to build between the inner and outer shells + + Parameters: + n: number of layers + UseExisting: if ==true - searches for the existing hypothesis created with + the same parameters, else (default) - creates a new one + """ if self.algoType != "RadialPrism_3D": - print "Prism_3D algorithm doesn't support any hypothesis" + print("Prism_3D algorithm doesn't support any hypothesis") return None self.mesh.RemoveHypothesis( self.distribHyp, self.geom ) from salome.smesh.smeshBuilder import IsEqual @@@ -1259,34 -1021,26 +1258,34 @@@ self.nbLayers.SetNumberOfLayers( n ) return self.nbLayers - ## Defines "LocalLength" hypothesis, specifying the segment length - # to build between the inner and the outer shells - # @param l the length of segments - # @param p the precision of rounding def LocalLength(self, l, p=1e-07): + """ + Defines "LocalLength" hypothesis, specifying the segment length + to build between the inner and the outer shells + + Parameters: + l: the length of segments + p: the precision of rounding + """ if self.algoType != "RadialPrism_3D": - print "Prism_3D algorithm doesn't support any hypothesis" + print("Prism_3D algorithm doesn't support any hypothesis") return None hyp = self.OwnHypothesis("LocalLength", [l,p]) hyp.SetLength(l) hyp.SetPrecision(p) return hyp - ## Defines "NumberOfSegments" hypothesis, specifying the number of layers of - # prisms to build between the inner and the outer shells. - # @param n the number of layers - # @param s the scale factor (optional) def NumberOfSegments(self, n, s=[]): + """ + Defines "NumberOfSegments" hypothesis, specifying the number of layers of + prisms to build between the inner and the outer shells. + + Parameters: + n: the number of layers + s: the scale factor (optional) + """ if self.algoType != "RadialPrism_3D": - print "Prism_3D algorithm doesn't support any hypothesis" + print("Prism_3D algorithm doesn't support any hypothesis") return None if not s: hyp = self.OwnHypothesis("NumberOfSegments", [n]) @@@ -1296,69 -1050,53 +1295,69 @@@ hyp.SetNumberOfSegments(n) return hyp - ## Defines "Arithmetic1D" hypothesis, specifying the distribution of segments - # to build between the inner and the outer shells with a length that changes - # in arithmetic progression - # @param start the length of the first segment - # @param end the length of the last segment def Arithmetic1D(self, start, end ): + """ + Defines "Arithmetic1D" hypothesis, specifying the distribution of segments + to build between the inner and the outer shells with a length that changes + in arithmetic progression + + Parameters: + start: the length of the first segment + end: the length of the last segment + """ if self.algoType != "RadialPrism_3D": - print "Prism_3D algorithm doesn't support any hypothesis" + print("Prism_3D algorithm doesn't support any hypothesis") return None hyp = self.OwnHypothesis("Arithmetic1D", [start, end]) hyp.SetLength(start, 1) hyp.SetLength(end , 0) return hyp - ## Defines "GeometricProgression" hypothesis, specifying the distribution of segments - # to build between the inner and the outer shells with a length that changes - # in Geometric progression - # @param start the length of the first segment - # @param ratio the common ratio of the geometric progression def GeometricProgression(self, start, ratio ): + """ + Defines "GeometricProgression" hypothesis, specifying the distribution of segments + to build between the inner and the outer shells with a length that changes + in Geometric progression + + Parameters: + start: the length of the first segment + ratio: the common ratio of the geometric progression + """ if self.algoType != "RadialPrism_3D": - print "Prism_3D algorithm doesn't support any hypothesis" + print("Prism_3D algorithm doesn't support any hypothesis") return None hyp = self.OwnHypothesis("GeometricProgression", [start, ratio]) hyp.SetStartLength( start ) hyp.SetCommonRatio( ratio ) return hyp - ## Defines "StartEndLength" hypothesis, specifying distribution of segments - # to build between the inner and the outer shells as geometric length increasing - # @param start for the length of the first segment - # @param end for the length of the last segment def StartEndLength(self, start, end): + """ + Defines "StartEndLength" hypothesis, specifying distribution of segments + to build between the inner and the outer shells as geometric length increasing + + Parameters: + start: for the length of the first segment + end: for the length of the last segment + """ if self.algoType != "RadialPrism_3D": - print "Prism_3D algorithm doesn't support any hypothesis" + print("Prism_3D algorithm doesn't support any hypothesis") return None hyp = self.OwnHypothesis("StartEndLength", [start, end]) hyp.SetLength(start, 1) hyp.SetLength(end , 0) return hyp - ## Defines "AutomaticLength" hypothesis, specifying the number of segments - # to build between the inner and outer shells - # @param fineness defines the quality of the mesh within the range [0-1] def AutomaticLength(self, fineness=0): + """ + Defines "AutomaticLength" hypothesis, specifying the number of segments + to build between the inner and outer shells + + Parameters: + fineness: defines the quality of the mesh within the range [0-1] + """ if self.algoType != "RadialPrism_3D": - print "Prism_3D algorithm doesn't support any hypothesis" + print("Prism_3D algorithm doesn't support any hypothesis") return None hyp = self.OwnHypothesis("AutomaticLength") hyp.SetFineness( fineness ) diff --cc src/SMESH_SWIG/smeshBuilder.py index 05710d64c,d1e2f3bb2..841dacbdb --- a/src/SMESH_SWIG/smeshBuilder.py +++ b/src/SMESH_SWIG/smeshBuilder.py @@@ -30,10 -94,85 +34,85 @@@ from salome.smesh.smesh_algorithm imp import SALOME import SALOMEDS import os + import inspect + + # In case the omniORBpy EnumItem class does not fully support Python 3 + # (for instance in version 4.2.1-2), the comparison ordering methods must be + # defined + # + try: + SMESH.Entity_Triangle < SMESH.Entity_Quadrangle + except TypeError: + def enumitem_eq(self, other): + try: + if isinstance(other, omniORB.EnumItem): + if other._parent_id == self._parent_id: + return self._v == other._v + else: + return self._parent_id == other._parent_id + else: + return id(self) == id(other) + except: + return id(self) == id(other) + + def enumitem_lt(self, other): + try: + if isinstance(other, omniORB.EnumItem): + if other._parent_id == self._parent_id: + return self._v < other._v + else: + return self._parent_id < other._parent_id + else: + return id(self) < id(other) + except: + return id(self) < id(other) + + def enumitem_le(self, other): + try: + if isinstance(other, omniORB.EnumItem): + if other._parent_id == self._parent_id: + return self._v <= other._v + else: + return self._parent_id <= other._parent_id + else: + return id(self) <= id(other) + except: + return id(self) <= id(other) + + def enumitem_gt(self, other): + try: + if isinstance(other, omniORB.EnumItem): + if other._parent_id == self._parent_id: + return self._v > other._v + else: + return self._parent_id > other._parent_id + else: + return id(self) > id(other) + except: + return id(self) > id(other) + + def enumitem_ge(self, other): + try: + if isinstance(other, omniORB.EnumItem): + if other._parent_id == self._parent_id: + return self._v >= other._v + else: + return self._parent_id >= other._parent_id + else: + return id(self) >= id(other) + except: + return id(self) >= id(other) + + omniORB.EnumItem.__eq__ = enumitem_eq + omniORB.EnumItem.__lt__ = enumitem_lt + omniORB.EnumItem.__le__ = enumitem_le + omniORB.EnumItem.__gt__ = enumitem_gt + omniORB.EnumItem.__ge__ = enumitem_ge + -## Private class used to workaround a problem that sometimes isinstance(m, Mesh) returns False -# class MeshMeta(type): + """Private class used to workaround a problem that sometimes isinstance(m, Mesh) returns False + """ def __instancecheck__(cls, inst): """Implement isinstance(inst, cls).""" return any(cls.__subclasscheck__(c) @@@ -102,14 -237,11 +181,13 @@@ def __initPointStruct(point,*args) pass SMESH.PointStruct.__init__ = __initPointStruct -## Substitute AxisStruct.__init__() to create SMESH.AxisStruct using notebook variables. -# Parameters are stored in AxisStruct.parameters attribute def __initAxisStruct(ax,*args): + """ + Substitute AxisStruct.__init__() to create SMESH.AxisStruct using notebook variables. + Parameters are stored in AxisStruct.parameters attribute + """ if len( args ) != 6: - raise RuntimeError,\ - "Bad nb args (%s) passed in SMESH.AxisStruct(x,y,z,dx,dy,dz)"%(len( args )) + raise RuntimeError("Bad nb args (%s) passed in SMESH.AxisStruct(x,y,z,dx,dy,dz)"%(len( args ))) ax.x, ax.y, ax.z, ax.vx, ax.vy, ax.vz, ax.parameters,hasVars = ParseParameters(*args) pass SMESH.AxisStruct.__init__ = __initAxisStruct @@@ -160,12 -281,10 +233,12 @@@ def GetName(obj) # unknown non-CORBA object, having GetName() method return obj.GetName() pass - raise RuntimeError, "Null or invalid object" + raise RuntimeError("Null or invalid object") -## Print error message if a hypothesis was not assigned. def TreatHypoStatus(status, hypName, geomName, isAlgo, mesh): + """ + Print error message if a hypothesis was not assigned. + """ if isAlgo: hypType = "algorithm" else: @@@ -173,21 -292,21 +246,21 @@@ pass reason = "" if hasattr( status, "__getitem__" ): - status,reason = status[0],status[1] - if status == HYP_UNKNOWN_FATAL : + status, reason = status[0], status[1] + if status == HYP_UNKNOWN_FATAL: reason = "for unknown reason" - elif status == HYP_INCOMPATIBLE : + elif status == HYP_INCOMPATIBLE: reason = "this hypothesis mismatches the algorithm" - elif status == HYP_NOTCONFORM : + elif status == HYP_NOTCONFORM: reason = "a non-conform mesh would be built" - elif status == HYP_ALREADY_EXIST : + elif status == HYP_ALREADY_EXIST: if isAlgo: return # it does not influence anything reason = hypType + " of the same dimension is already assigned to this shape" - elif status == HYP_BAD_DIM : + elif status == HYP_BAD_DIM: reason = hypType + " mismatches the shape" - elif status == HYP_CONCURENT: + elif status == HYP_CONCURRENT : reason = "there are concurrent hypotheses on sub-shapes" - elif status == HYP_BAD_SUBSHAPE : + elif status == HYP_BAD_SUBSHAPE: reason = "the shape is neither the main one, nor its sub-shape, nor a valid group" elif status == HYP_BAD_GEOMETRY: reason = "the algorithm is not applicable to this geometry" @@@ -209,25 -328,18 +282,20 @@@ if meshName and meshName != NO_NAME: where = '"%s" shape in "%s" mesh ' % ( geomName, meshName ) if status < HYP_UNKNOWN_FATAL and where: - print '"%s" was assigned to %s but %s' %( hypName, where, reason ) + print('"%s" was assigned to %s but %s' %( hypName, where, reason )) elif where: - print '"%s" was not assigned to %s : %s' %( hypName, where, reason ) + print('"%s" was not assigned to %s : %s' %( hypName, where, reason )) else: - print '"%s" was not assigned : %s' %( hypName, reason ) + print('"%s" was not assigned : %s' %( hypName, reason )) pass -## Private method. Add geom (sub-shape of the main shape) into the study if not yet there def AssureGeomPublished(mesh, geom, name=''): + """ + Private method. Add geom (sub-shape of the main shape) into the study if not yet there + """ if not isinstance( geom, geomBuilder.GEOM._objref_GEOM_Object ): return - if not geom.GetStudyEntry() and \ - mesh.smeshpyD.GetCurrentStudy(): - ## set the study - studyID = mesh.smeshpyD.GetCurrentStudy()._get_StudyId() - if studyID != mesh.geompyD.myStudyId: - mesh.geompyD.init_geom( mesh.smeshpyD.GetCurrentStudy()) + if not geom.GetStudyEntry(): ## get a name if not name and geom.GetShapeType() != geomBuilder.GEOM.COMPOUND: # for all groups SubShapeName() return "Compound_-1" @@@ -238,14 -350,11 +306,14 @@@ mesh.geompyD.addToStudyInFather( mesh.geom, geom, name ) return -## Return the first vertex of a geometrical edge by ignoring orientation def FirstVertexOnCurve(mesh, edge): + """ + Returns: + the first vertex of a geometrical edge by ignoring orientation + """ vv = mesh.geompyD.SubShapeAll( edge, geomBuilder.geomBuilder.ShapeType["VERTEX"]) if not vv: - raise TypeError, "Given object has no vertices" + raise TypeError("Given object has no vertices") if len( vv ) == 1: return vv[0] v0 = mesh.geompyD.MakeVertexOnCurve(edge,0.) xyz = mesh.geompyD.PointCoordinates( v0 ) # coords of the first vertex @@@ -269,12 -383,10 +337,12 @@@ engine = Non doLcc = False created = False - class smeshBuilder(object, SMESH._objref_SMESH_Gen): -## This class allows to create, load or manipulate meshes. -# It has a set of methods to create, load or copy meshes, to combine several meshes, etc. -# It also has methods to get infos and measure meshes. -class smeshBuilder(SMESH._objref_SMESH_Gen): ++class smeshBuilder( SMESH._objref_SMESH_Gen, object ): + """ + This class allows to create, load or manipulate meshes. + It has a set of methods to create, load or copy meshes, to combine several meshes, etc. + It also has methods to get infos and measure meshes. + """ # MirrorType enumeration POINT = SMESH_MeshEditor.POINT @@@ -297,7 -409,7 +365,7 @@@ global engine global smeshInst global doLcc -- #print "==== __new__", engine, smeshInst, doLcc ++ #print("==== __new__", engine, smeshInst, doLcc) if smeshInst is None: # smesh engine is either retrieved from engine, or created @@@ -312,147 -424,101 +380,145 @@@ # FindOrLoadComponent called: # 1. CORBA resolution of server # 2. the __new__ method is called again -- #print "==== smeshInst = lcc.FindOrLoadComponent ", engine, smeshInst, doLcc ++ #print("==== smeshInst = lcc.FindOrLoadComponent ", engine, smeshInst, doLcc) smeshInst = salome.lcc.FindOrLoadComponent( "FactoryServer", "SMESH" ) else: # FindOrLoadComponent not called if smeshInst is None: # smeshBuilder instance is created from lcc.FindOrLoadComponent -- #print "==== smeshInst = super(smeshBuilder,cls).__new__(cls) ", engine, smeshInst, doLcc ++ #print("==== smeshInst = super(smeshBuilder,cls).__new__(cls) ", engine, smeshInst, doLcc) smeshInst = super(smeshBuilder,cls).__new__(cls) else: # smesh engine not created: existing engine found -- #print "==== existing ", engine, smeshInst, doLcc ++ #print("==== existing ", engine, smeshInst, doLcc) pass -- #print "====1 ", smeshInst ++ #print("====1 ", smeshInst) return smeshInst -- #print "====2 ", smeshInst ++ #print("====2 ", smeshInst) return smeshInst - def __init__(self): + def __init__(self, *args): global created -- #print "--------------- smeshbuilder __init__ ---", created ++ #print("--------------- smeshbuilder __init__ ---", created) if not created: - created = True - SMESH._objref_SMESH_Gen.__init__(self) + created = True + SMESH._objref_SMESH_Gen.__init__(self, *args) + - ## Dump component to the Python script - # This method overrides IDL function to allow default values for the parameters. - # @ingroup l1_auxiliary - def DumpPython(self, theIsPublished=True, theIsMultiFile=True): - return SMESH._objref_SMESH_Gen.DumpPython(self, theIsPublished, theIsMultiFile) - - ## Set mode of DumpPython(), \a historical or \a snapshot. - # In the \a historical mode, the Python Dump script includes all commands - # performed by SMESH engine. In the \a snapshot mode, commands - # relating to objects removed from the Study are excluded from the script - # as well as commands not influencing the current state of meshes - # @ingroup l1_auxiliary + + def DumpPython(self, theStudy, theIsPublished=True, theIsMultiFile=True): + """ + Dump component to the Python script. + This method overrides IDL function to allow default values for the parameters. + """ + + return SMESH._objref_SMESH_Gen.DumpPython(self, theStudy, theIsPublished, theIsMultiFile) + def SetDumpPythonHistorical(self, isHistorical): + """ + Set mode of DumpPython(), *historical* or *snapshot*. + In the *historical* mode, the Python Dump script includes all commands + performed by SMESH engine. In the *snapshot* mode, commands + relating to objects removed from the Study are excluded from the script + as well as commands not influencing the current state of meshes + """ + if isHistorical: val = "true" else: val = "false" SMESH._objref_SMESH_Gen.SetOption(self, "historical_python_dump", val) - def init_smesh(self,theStudy,geompyD = None): - """ - Set the current study and Geometry component - ## Set Geometry component - # @ingroup l1_auxiliary - def init_smesh(self,isPublished = True,geompyD = None): - #print "init_smesh" ++ def init_smesh(self,geompyD = None): + """ - - #print "init_smesh" - self.SetCurrentStudy(theStudy,geompyD) - if theStudy: - global notebook - notebook.myStudy = theStudy ++ Set Geometry component ++ """ ++ #print("init_smesh") + self.UpdateStudy(geompyD) - if isPublished: - global notebook - notebook.myStudy = salome.myStudy - - ## Create a mesh. This can be either an empty mesh, possibly having an underlying geometry, - # or a mesh wrapping a CORBA mesh given as a parameter. - # @param obj either (1) a CORBA mesh (SMESH._objref_SMESH_Mesh) got e.g. by calling - # salome.myStudy.FindObjectID("0:1:2:3").GetObject() or - # (2) a Geometrical object for meshing or - # (3) none. - # @param name the name for the new mesh. - # @return an instance of Mesh class. - # @ingroup l2_construct ++ notebook.myStudy = salome.myStudy + def Mesh(self, obj=0, name=0): + """ + Create a mesh. This mesh can be either + + * an empty mesh not bound to geometry, if *obj* == 0 + * an empty mesh bound to geometry, if *obj* is GEOM.GEOM_Object + * a mesh wrapping a :class:`CORBA mesh ` given as *obj* parameter. + + Parameters: + obj: either + + 1. a :class:`CORBA mesh ` got by calling e.g. + :: + + salome.myStudy.FindObjectID("0:1:2:3").GetObject() + + 2. a geometrical object for meshing + 3. none. + name: the name for the new mesh. + + Returns: + an instance of class :class:`Mesh`. + """ + if isinstance(obj,str): obj,name = name,obj -- return Mesh(self,self.geompyD,obj,name) ++ return Mesh(self, self.geompyD, obj, name) + + def EnumToLong(self,theItem): + """ + Return a long value from enumeration + """ + + return theItem._v - ## Return a string representation of the color. - # To be used with filters. - # @param c color value (SALOMEDS.Color) - # @ingroup l1_auxiliary def ColorToString(self,c): + """ + Convert SALOMEDS.Color to string. + To be used with filters. + + Parameters: + c: color value (SALOMEDS.Color) + + Returns: + a string representation of the color. + """ + val = "" if isinstance(c, SALOMEDS.Color): val = "%s;%s;%s" % (c.R, c.G, c.B) elif isinstance(c, str): val = c else: - raise ValueError, "Color value should be of string or SALOMEDS.Color type" + raise ValueError("Color value should be of string or SALOMEDS.Color type") return val - ## Get PointStruct from vertex - # @param theVertex a GEOM object(vertex) - # @return SMESH.PointStruct - # @ingroup l1_auxiliary def GetPointStruct(self,theVertex): + """ + Get :class:`SMESH.PointStruct` from vertex + + Parameters: + theVertex (GEOM.GEOM_Object): vertex + + Returns: + :class:`SMESH.PointStruct` + """ + [x, y, z] = self.geompyD.PointCoordinates(theVertex) return PointStruct(x,y,z) - ## Get DirStruct from vector - # @param theVector a GEOM object(vector) - # @return SMESH.DirStruct - # @ingroup l1_auxiliary def GetDirStruct(self,theVector): + """ + Get :class:`SMESH.DirStruct` from vector + + Parameters: + theVector (GEOM.GEOM_Object): vector + + Returns: + :class:`SMESH.DirStruct` + """ + vertices = self.geompyD.SubShapeAll( theVector, geomBuilder.geomBuilder.ShapeType["VERTEX"] ) if(len(vertices) != 2): - print "Error: vector object is incorrect." + print("Error: vector object is incorrect.") return None p1 = self.geompyD.PointCoordinates(vertices[0]) p2 = self.geompyD.PointCoordinates(vertices[1]) @@@ -530,60 -581,46 +596,58 @@@ ior = salome.orb.object_to_string(obj) SMESH._objref_SMESH_Gen.SetName(self, ior, name) - ## Set the current mode - # @ingroup l1_auxiliary def SetEmbeddedMode( self,theMode ): + """ + Set the current mode + """ + SMESH._objref_SMESH_Gen.SetEmbeddedMode(self,theMode) - ## Get the current mode - # @ingroup l1_auxiliary def IsEmbeddedMode(self): + """ + Get the current mode + """ + return SMESH._objref_SMESH_Gen.IsEmbeddedMode(self) - - ## Update the current study. Calling UpdateStudy() allows to - # update meshes at switching GEOM->SMESH - # @ingroup l1_auxiliary + - def SetCurrentStudy( self, theStudy, geompyD = None ): - """ - Set the current study. Calling SetCurrentStudy( None ) allows to - switch **off** automatic pubilishing in the Study of mesh objects. - """ - - if not geompyD: + def UpdateStudy( self, geompyD = None ): ++ """ ++ Update the current study. Calling UpdateStudy() allows to ++ update meshes at switching GEOM->SMESH ++ """ + #self.UpdateStudy() - if not geompyD: ++ if not geompyD: from salome.geom import geomBuilder geompyD = geomBuilder.geom pass -- self.geompyD=geompyD -- self.SetGeomEngine(geompyD) - SMESH._objref_SMESH_Gen.SetCurrentStudy(self,theStudy) - global notebook - if theStudy: - notebook = salome_notebook.NoteBook( theStudy ) - else: - notebook = salome_notebook.NoteBook( salome_notebook.PseudoStudyForNoteBook() ) - if theStudy: - sb = theStudy.NewBuilder() - sc = theStudy.FindComponent("SMESH") - if sc: sb.LoadWith(sc, self) - pass - SMESH._objref_SMESH_Gen.UpdateStudy(self) - sb = salome.myStudy.NewBuilder() - sc = salome.myStudy.FindComponent("SMESH") - if sc: sb.LoadWith(sc, self) -- pass - - def GetCurrentStudy(self): - """ - Get the current study - """ - - ## Sets enable publishing in the study. Calling SetEnablePublish( false ) allows to - # switch OFF publishing in the Study of mesh objects. - # @ingroup l1_auxiliary ++ self.geompyD=geompyD ++ self.SetGeomEngine(geompyD) ++ SMESH._objref_SMESH_Gen.UpdateStudy(self) ++ sb = salome.myStudy.NewBuilder() ++ sc = salome.myStudy.FindComponent("SMESH") ++ if sc: ++ sb.LoadWith(sc, self) ++ pass ++ + def SetEnablePublish( self, theIsEnablePublish ): ++ """ ++ Sets enable publishing in the study. Calling SetEnablePublish( false ) allows to ++ switch OFF publishing in the Study of mesh objects. ++ """ + #self.SetEnablePublish(theIsEnablePublish) - SMESH._objref_SMESH_Gen.SetEnablePublish(self,theIsEnablePublish) - global notebook - notebook = salome_notebook.NoteBook( theIsEnablePublish ) ++ SMESH._objref_SMESH_Gen.SetEnablePublish(self,theIsEnablePublish) ++ global notebook ++ notebook = salome_notebook.NoteBook( theIsEnablePublish ) + - return SMESH._objref_SMESH_Gen.GetCurrentStudy(self) - ## Create a Mesh object importing data from the given UNV file - # @return an instance of Mesh class - # @ingroup l2_impexp def CreateMeshesFromUNV( self,theFileName ): + """ + Create a Mesh object importing data from the given UNV file + + Returns: + an instance of class :class:`Mesh` + """ + aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromUNV(self,theFileName) aMesh = Mesh(self, self.geompyD, aSmeshMesh) return aMesh @@@ -650,9 -666,19 +714,9 @@@ aSmeshMesh, error = SMESH._objref_SMESH_Gen.CreateMeshesFromGMF(self, theFileName, True) - if error.comment: print "*** CreateMeshesFromGMF() errors:\n", error.comment + if error.comment: print("*** CreateMeshesFromGMF() errors:\n", error.comment) return Mesh(self, self.geompyD, aSmeshMesh), error - ## Concatenate the given meshes into one mesh. All groups of input meshes will be - # present in the new mesh. - # @param meshes the meshes, sub-meshes and groups to combine into one mesh - # @param uniteIdenticalGroups if true, groups with same names are united, else they are renamed - # @param mergeNodesAndElements if true, equal nodes and elements are merged - # @param mergeTolerance tolerance for merging nodes - # @param allGroups forces creation of groups corresponding to every input mesh - # @param name name of a new mesh - # @return an instance of Mesh class - # @ingroup l1_creating def Concatenate( self, meshes, uniteIdenticalGroups, mergeNodesAndElements = False, mergeTolerance = 1e-5, allGroups = False, name = ""): @@@ -774,33 -777,11 +838,33 @@@ UnaryOp=FT_Undefined, BinaryOp=FT_Undefined, Tolerance=1e-07): + """ + Create a criterion by the given parameters + Criterion structures allow to define complex filters by combining them with logical operations (AND / OR) (see example below) + + Parameters: + elementType: the :class:`type of elements ` (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME) + CritType: the type of criterion :class:`SMESH.FunctorType` (SMESH.FT_Taper, SMESH.FT_Area, etc.). + Note that the items starting from FT_LessThan are not suitable for *CritType*. + Compare: belongs to {SMESH.FT_LessThan, SMESH.FT_MoreThan, SMESH.FT_EqualTo} + Threshold: the threshold value (range of ids as string, shape, numeric) + UnaryOp: SMESH.FT_LogicalNOT or SMESH.FT_Undefined + BinaryOp: a binary logical operation SMESH.FT_LogicalAND, SMESH.FT_LogicalOR or + SMESH.FT_Undefined + Tolerance: the tolerance used by SMESH.FT_BelongToGeom, SMESH.FT_BelongToSurface, + SMESH.FT_LyingOnGeom, SMESH.FT_CoplanarFaces criteria + + Returns: + :class:`SMESH.Filter.Criterion` + + Example: :ref:`combining_filters` + """ + if not CritType in SMESH.FunctorType._items: - raise TypeError, "CritType should be of SMESH.FunctorType" + raise TypeError("CritType should be of SMESH.FunctorType") aCriterion = self.GetEmptyCriterion() aCriterion.TypeOfElement = elementType - aCriterion.Type = EnumToLong(CritType) + aCriterion.Type = self.EnumToLong(CritType) aCriterion.Tolerance = Tolerance aThreshold = Threshold @@@ -1335,74 -1233,77 +1397,74 @@@ pass # end of class smeshBuilder import omniORB -#Registering the new proxy for SMESH_Gen omniORB.registerObjref(SMESH._objref_SMESH_Gen._NP_RepositoryId, smeshBuilder) +"""Registering the new proxy for SMESH.SMESH_Gen""" -## Create a new smeshBuilder instance.The smeshBuilder class provides the Python -# interface to create or load meshes. -# -# Typical use is: -# \code -# import salome -# salome.salome_init() -# from salome.smesh import smeshBuilder -# smesh = smeshBuilder.New() -# \endcode -# @param isPublished If False, the notebool will not be used. -# @param instance CORBA proxy of SMESH Engine. If None, the default Engine is used. -# @return smeshBuilder instance - -def New( isPublished = True, instance=None): + - def New( study, instance=None, instanceGeom=None): ++def New( instance=None, instanceGeom=None): """ - Create a new smeshBuilder instance.The smeshBuilder class provides the Python + Create a new smeshBuilder instance. The smeshBuilder class provides the Python interface to create or load meshes. - Typical use is:: + Typical use is: + import salome salome.salome_init() from salome.smesh import smeshBuilder - smesh = smeshBuilder.New(salome.myStudy) + smesh = smeshBuilder.New() Parameters: - study: SALOME study, generally obtained by salome.myStudy. - instance: CORBA proxy of SMESH Engine. If None, the default Engine is used. - instanceGeom: CORBA proxy of GEOM Engine. If None, the default Engine is used. + isPublished If False, the notebool will not be used. + instance CORBA proxy of SMESH Engine. If None, the default Engine is used. Returns: - smeshBuilder instance + :class:`smeshBuilder` instance """ global engine global smeshInst global doLcc engine = instance if engine is None: - doLcc = True + doLcc = True smeshInst = smeshBuilder() assert isinstance(smeshInst,smeshBuilder), "Smesh engine class is %s but should be smeshBuilder.smeshBuilder. Import salome.smesh.smeshBuilder before creating the instance."%smeshInst.__class__ - smeshInst.init_smesh(study, instanceGeom) - smeshInst.init_smesh(isPublished) ++ smeshInst.init_smesh(instanceGeom) return smeshInst # Public class: Mesh # ================== - class Mesh: -## This class allows defining and managing a mesh. -# It has a set of methods to build a mesh on the given geometry, including the definition of sub-meshes. -# It also has methods to define groups of mesh elements, to modify a mesh (by addition of -# new nodes and elements and by changing the existing entities), to get information -# about a mesh and to export a mesh in different formats. -class Mesh(metaclass=MeshMeta): ++ ++class Mesh(metaclass = MeshMeta): + """ + This class allows defining and managing a mesh. + It has a set of methods to build a mesh on the given geometry, including the definition of sub-meshes. + It also has methods to define groups of mesh elements, to modify a mesh (by addition of + new nodes and elements and by changing the existing entities), to get information + about a mesh and to export a mesh in different formats. - """ - __metaclass__ = MeshMeta ++ """ + geom = 0 mesh = 0 editor = 0 - ## Constructor - # - # Create a mesh on the shape \a obj (or an empty mesh if \a obj is equal to 0) and - # sets the GUI name of this mesh to \a name. - # @param smeshpyD an instance of smeshBuilder class - # @param geompyD an instance of geomBuilder class - # @param obj Shape to be meshed or SMESH_Mesh object - # @param name Study name of the mesh - # @ingroup l2_construct def __init__(self, smeshpyD, geompyD, obj=0, name=0): ++ + """ + Constructor + + Create a mesh on the shape *obj* (or an empty mesh if *obj* is equal to 0) and + sets the GUI name of this mesh to *name*. + + Parameters: + smeshpyD: an instance of smeshBuilder class + geompyD: an instance of geomBuilder class + obj: Shape to be meshed or :class:`SMESH.SMESH_Mesh` object + name: Study name of the mesh + """ + - self.smeshpyD=smeshpyD - self.geompyD=geompyD + self.smeshpyD = smeshpyD + self.geompyD = geompyD if obj is None: obj = 0 objHasName = False @@@ -1854,9 -1669,9 +1910,9 @@@ pass groups = [] - for algoName, shapes in algo2shapes.items(): + for algoName, shapes in list(algo2shapes.items()): while shapes: - groupType = EnumToLong( shapes[0].GetShapeType() ) + groupType = self.smeshpyD.EnumToLong( shapes[0].GetShapeType() ) otherTypeShapes = [] sameTypeShapes = [] group = self.geompyD.CreateGroup( self.geom, groupType ) @@@ -1878,69 -1693,46 +1934,68 @@@ self.geompyD.addToStudyInFather( self.geom, group, group.GetName() ) return groups - ## Return sub-mesh objects list in meshing order - # @return list of lists of sub-meshes - # @ingroup l2_construct def GetMeshOrder(self): + """ + Return sub-mesh objects list in meshing order + + Returns: + list of lists of :class:`sub-meshes ` + """ + return self.mesh.GetMeshOrder() - ## Set order in which concurrent sub-meshes should be meshed - # @param submeshes list of lists of sub-meshes - # @ingroup l2_construct def SetMeshOrder(self, submeshes): + """ + Set order in which concurrent sub-meshes should be meshed + + Parameters: + submeshes: list of lists of :class:`sub-meshes ` + """ + return self.mesh.SetMeshOrder(submeshes) - ## Remove all nodes and elements generated on geometry. Imported elements remain. - # @param refresh if @c True, Object browser is automatically updated (when running in GUI) - # @ingroup l2_construct def Clear(self, refresh=False): + """ + Remove all nodes and elements generated on geometry. Imported elements remain. + + Parameters: + refresh: if *True*, Object browser is automatically updated (when running in GUI) + """ + self.mesh.Clear() - if ( salome.sg.hasDesktop() and - salome.myStudyManager.GetStudyByID( self.mesh.GetStudyId() ) ): + if ( salome.sg.hasDesktop() ): smeshgui = salome.ImportComponentGUI("SMESH") - smeshgui.Init(self.mesh.GetStudyId()) + smeshgui.Init() smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True ) - if refresh: salome.sg.updateObjBrowser(True) + if refresh: salome.sg.updateObjBrowser() - ## Remove all nodes and elements of indicated shape - # @param refresh if @c True, Object browser is automatically updated (when running in GUI) - # @param geomId the ID of a sub-shape to remove elements on - # @ingroup l2_submeshes def ClearSubMesh(self, geomId, refresh=False): + """ + Remove all nodes and elements of indicated shape + + Parameters: + geomId: the ID of a sub-shape to remove elements on + refresh: if *True*, Object browser is automatically updated (when running in GUI) + """ + self.mesh.ClearSubMesh(geomId) if salome.sg.hasDesktop(): smeshgui = salome.ImportComponentGUI("SMESH") - smeshgui.Init(self.mesh.GetStudyId()) + smeshgui.Init() smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True ) - if refresh: salome.sg.updateObjBrowser(True) + if refresh: salome.sg.updateObjBrowser() - ## Compute a tetrahedral mesh using AutomaticLength + MEFISTO + Tetrahedron - # @param fineness [0.0,1.0] defines mesh fineness - # @return True or False - # @ingroup l3_algos_basic def AutomaticTetrahedralization(self, fineness=0): + """ + Compute a tetrahedral mesh using AutomaticLength + MEFISTO + Tetrahedron + + Parameters: + fineness: [0.0,1.0] defines mesh fineness + + Returns: + True or False + """ + dim = self.MeshDimension() # assign hypotheses self.RemoveGlobalHypotheses() @@@ -2068,98 -1836,88 +2123,107 @@@ return self.mesh.RemoveHypothesis( shape, hyp ) hypName = GetName( hyp ) geoName = GetName( shape ) - print "WARNING: RemoveHypothesis() failed as '%s' is not assigned to '%s' shape" % ( hypName, geoName ) + print("WARNING: RemoveHypothesis() failed as '%s' is not assigned to '%s' shape" % ( hypName, geoName )) return None - ## Get the list of hypotheses added on a geometry - # @param geom a sub-shape of mesh geometry - # @return the sequence of SMESH_Hypothesis - # @ingroup l2_editing def GetHypothesisList(self, geom): + """ + Get the list of hypotheses added on a geometry + + Parameters: + geom (GEOM.GEOM_Object): a sub-shape of mesh geometry + + Returns: + the sequence of :class:`SMESH.SMESH_Hypothesis` + """ + return self.mesh.GetHypothesisList( geom ) - ## Remove all global hypotheses - # @ingroup l2_editing def RemoveGlobalHypotheses(self): + """ + Remove all global hypotheses + """ + current_hyps = self.mesh.GetHypothesisList( self.geom ) for hyp in current_hyps: self.mesh.RemoveHypothesis( self.geom, hyp ) pass pass -- - def ExportMED(self, f, auto_groups=0, version=MED_V2_2, - overwrite=1, meshPart=None, autoDimension=True, fields=[], geomAssocFields=''): - ## Export the mesh in a file in MED format - ## allowing to overwrite the file if it exists or add the exported data to its contents - # @param fileName is the file name - # @param auto_groups boolean parameter for creating/not creating - # the groups Group_On_All_Nodes, Group_On_All_Faces, ... ; - # the typical use is auto_groups=False. - # @param overwrite boolean parameter for overwriting/not overwriting the file - # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh - # @param autoDimension if @c True (default), a space dimension of a MED mesh can be either - # - 1D if all mesh nodes lie on OX coordinate axis, or - # - 2D if all mesh nodes lie on XOY coordinate plane, or - # - 3D in the rest cases.
- # If @a autoDimension is @c False, the space dimension is always 3. - # @param fields list of GEOM fields defined on the shape to mesh. - # @param geomAssocFields each character of this string means a need to export a - # corresponding field; correspondence between fields and characters is following: - # - 'v' stands for "_vertices _" field; - # - 'e' stands for "_edges _" field; - # - 'f' stands for "_faces _" field; - # - 's' stands for "_solids _" field. - # @ingroup l2_impexp + def ExportMED(self, *args, **kwargs): + """ + Export the mesh in a file in MED format + allowing to overwrite the file if it exists or add the exported data to its contents + + Parameters: - f: is the file name - auto_groups: boolean parameter for creating/not creating - the groups Group_On_All_Nodes, Group_On_All_Faces, ... ; - the typical use is auto_groups=False. - version: MED format version (MED_V2_1 or MED_V2_2, - the latter meaning any current version). The parameter is - obsolete since MED_V2_1 is no longer supported. - overwrite: boolean parameter for overwriting/not overwriting the file - meshPart: a part of mesh (:class:`sub-mesh, group or filter `) to export instead of the mesh - autoDimension: if *True* (default), a space dimension of a MED mesh can be either - - - 1D if all mesh nodes lie on OX coordinate axis, or - - 2D if all mesh nodes lie on XOY coordinate plane, or - - 3D in the rest cases. - ++ fileName: is the file name ++ auto_groups (boolean): parameter for creating/not creating ++ the groups Group_On_All_Nodes, Group_On_All_Faces, ... ; ++ the typical use is auto_groups=False. ++ overwrite (boolean): parameter for overwriting/not overwriting the file ++ meshPart: a part of mesh (group, sub-mesh) to export instead of the mesh ++ autoDimension if @c True (default), a space dimension of a MED mesh can be either ++ - 1D if all mesh nodes lie on OX coordinate axis, or ++ - 2D if all mesh nodes lie on XOY coordinate plane, or ++ - 3D in the rest cases. + If *autoDimension* is *False*, the space dimension is always 3. + fields: list of GEOM fields defined on the shape to mesh. + geomAssocFields: each character of this string means a need to export a + corresponding field; correspondence between fields and characters is following: + - 'v' stands for "_vertices _" field; + - 'e' stands for "_edges _" field; + - 'f' stands for "_faces _" field; + - 's' stands for "_solids _" field. + """ - + # process positional arguments + args = [i for i in args if i not in [SMESH.MED_V2_1, SMESH.MED_V2_2]] # backward compatibility + fileName = args[0] + auto_groups = args[1] if len(args) > 1 else False + overwrite = args[2] if len(args) > 2 else True + meshPart = args[3] if len(args) > 3 else None + autoDimension = args[4] if len(args) > 4 else True + fields = args[5] if len(args) > 5 else [] + geomAssocFields = args[6] if len(args) > 6 else '' + # process keywords arguments + auto_groups = kwargs.get("auto_groups", auto_groups) + overwrite = kwargs.get("overwrite", overwrite) + meshPart = kwargs.get("meshPart", meshPart) + autoDimension = kwargs.get("autoDimension", autoDimension) + fields = kwargs.get("fields", fields) + geomAssocFields = kwargs.get("geomAssocFields", geomAssocFields) + # invoke engine's function if meshPart or fields or geomAssocFields: unRegister = genObjUnRegister() if isinstance( meshPart, list ): meshPart = self.GetIDSource( meshPart, SMESH.ALL ) unRegister.set( meshPart ) - self.mesh.ExportPartToMED( meshPart, f, auto_groups, version, overwrite, autoDimension, + self.mesh.ExportPartToMED( meshPart, fileName, auto_groups, overwrite, autoDimension, fields, geomAssocFields) else: - self.mesh.ExportToMEDX(f, auto_groups, version, overwrite, autoDimension) + self.mesh.ExportMED(fileName, auto_groups, overwrite, autoDimension) - ## Export the mesh in a file in SAUV format - # @param f is the file name - # @param auto_groups boolean parameter for creating/not creating - # the groups Group_On_All_Nodes, Group_On_All_Faces, ... ; - # the typical use is auto_groups=false. - # @ingroup l2_impexp def ExportSAUV(self, f, auto_groups=0): + """ + Export the mesh in a file in SAUV format + + + Parameters: + f: is the file name + auto_groups: boolean parameter for creating/not creating + the groups Group_On_All_Nodes, Group_On_All_Faces, ... ; + the typical use is auto_groups=False. + """ + self.mesh.ExportSAUV(f, auto_groups) - ## Export the mesh in a file in DAT format - # @param f the file name - # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh - # @ingroup l2_impexp def ExportDAT(self, f, meshPart=None): + """ + Export the mesh in a file in DAT format + + Parameters: + f: the file name + meshPart: a part of mesh (:class:`sub-mesh, group or filter `) to export instead of the mesh + """ + if meshPart: unRegister = genObjUnRegister() if isinstance( meshPart, list ): @@@ -2250,85 -1992,97 +2314,127 @@@ meshPart = self.mesh self.mesh.ExportGMF(meshPart, f, True) - def ExportToMED(self, f, version=MED_V2_2, opt=0, overwrite=1, autoDimension=True): - ## Deprecated, used only for compatibility! Please, use ExportMED() method instead. - # Export the mesh in a file in MED format - # allowing to overwrite the file if it exists or add the exported data to its contents - # @param fileName the file name - # @param opt boolean parameter for creating/not creating - # the groups Group_On_All_Nodes, Group_On_All_Faces, ... - # @param overwrite boolean parameter for overwriting/not overwriting the file - # @param autoDimension if @c True (default), a space dimension of a MED mesh can be either - # - 1D if all mesh nodes lie on OX coordinate axis, or - # - 2D if all mesh nodes lie on XOY coordinate plane, or - # - 3D in the rest cases.
- # If @a autoDimension is @c False, the space dimension is always 3. - # @ingroup l2_impexp + def ExportToMED(self, *args, **kwargs): + """ + Deprecated, used only for compatibility! Please, use :meth:`ExportMED` method instead. + Export the mesh in a file in MED format + allowing to overwrite the file if it exists or add the exported data to its contents + + Parameters: - f: the file name - version: MED format version (MED_V2_1 or MED_V2_2, - the latter meaning any current version). The parameter is - obsolete since MED_V2_1 is no longer supported. - opt: boolean parameter for creating/not creating ++ fileName: the file name ++ opt (boolean): parameter for creating/not creating + the groups Group_On_All_Nodes, Group_On_All_Faces, ... + overwrite: boolean parameter for overwriting/not overwriting the file + autoDimension: if *True* (default), a space dimension of a MED mesh can be either + + - 1D if all mesh nodes lie on OX coordinate axis, or + - 2D if all mesh nodes lie on XOY coordinate plane, or + - 3D in the rest cases. + + If **autoDimension** is *False*, the space dimension is always 3. + """ ++ + print("WARNING: ExportToMED() is deprecated, use ExportMED() instead") + # process positional arguments + args = [i for i in args if i not in [SMESH.MED_V2_1, SMESH.MED_V2_2]] # backward compatibility + fileName = args[0] + auto_groups = args[1] if len(args) > 1 else False + overwrite = args[2] if len(args) > 2 else True + autoDimension = args[3] if len(args) > 3 else True + # process keywords arguments + auto_groups = kwargs.get("opt", auto_groups) # old keyword name + auto_groups = kwargs.get("auto_groups", auto_groups) # new keyword name + overwrite = kwargs.get("overwrite", overwrite) + autoDimension = kwargs.get("autoDimension", autoDimension) + # invoke engine's function + self.mesh.ExportMED(fileName, auto_groups, overwrite, autoDimension) + - ## Deprecated, used only for compatibility! Please, use ExportMED() method instead. - # Export the mesh in a file in MED format - # allowing to overwrite the file if it exists or add the exported data to its contents - # @param fileName the file name - # @param opt boolean parameter for creating/not creating - # the groups Group_On_All_Nodes, Group_On_All_Faces, ... - # @param overwrite boolean parameter for overwriting/not overwriting the file - # @param autoDimension if @c True (default), a space dimension of a MED mesh can be either - # - 1D if all mesh nodes lie on OX coordinate axis, or - # - 2D if all mesh nodes lie on XOY coordinate plane, or - # - 3D in the rest cases.
- # If @a autoDimension is @c False, the space dimension is always 3. - # @ingroup l2_impexp + def ExportToMEDX(self, *args, **kwargs): ++ """ ++ Deprecated, used only for compatibility! Please, use ExportMED() method instead. ++ Export the mesh in a file in MED format ++ ++ Parameters: ++ fileName: the file name ++ opt (boolean): parameter for creating/not creating ++ the groups Group_On_All_Nodes, Group_On_All_Faces, ... ++ overwrite: boolean parameter for overwriting/not overwriting the file ++ autoDimension: if *True* (default), a space dimension of a MED mesh can be either + - self.mesh.ExportToMEDX(f, opt, version, overwrite, autoDimension) ++ - 1D if all mesh nodes lie on OX coordinate axis, or ++ - 2D if all mesh nodes lie on XOY coordinate plane, or ++ - 3D in the rest cases. ++ ++ If **autoDimension** is *False*, the space dimension is always 3. ++ """ ++ + print("WARNING: ExportToMEDX() is deprecated, use ExportMED() instead") + # process positional arguments + args = [i for i in args if i not in [SMESH.MED_V2_1, SMESH.MED_V2_2]] # backward compatibility + fileName = args[0] + auto_groups = args[1] if len(args) > 1 else False + overwrite = args[2] if len(args) > 2 else True + autoDimension = args[3] if len(args) > 3 else True + # process keywords arguments + auto_groups = kwargs.get("auto_groups", auto_groups) + overwrite = kwargs.get("overwrite", overwrite) + autoDimension = kwargs.get("autoDimension", autoDimension) + # invoke engine's function + self.mesh.ExportMED(fileName, auto_groups, overwrite, autoDimension) # Operations with groups: # ---------------------- -- - ## Create an empty mesh group - # @param elementType the type of elements in the group; either of - # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME) - # @param name the name of the mesh group - # @return SMESH_Group - # @ingroup l2_grps_create def CreateEmptyGroup(self, elementType, name): + """ + Create an empty mesh group + + Parameters: + elementType: the :class:`type ` of elements in the group; + either of (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME) + name: the name of the mesh group + + Returns: + :class:`SMESH.SMESH_Group` + """ + return self.mesh.CreateGroup(elementType, name) - ## Create a mesh group based on the geometric object \a grp - # and gives a \a name, \n if this parameter is not defined - # the name is the same as the geometric group name \n - # Note: Works like GroupOnGeom(). - # @param grp a geometric group, a vertex, an edge, a face or a solid - # @param name the name of the mesh group - # @return SMESH_GroupOnGeom - # @ingroup l2_grps_create def Group(self, grp, name=""): + """ + Create a mesh group based on the geometric object *grp* + and give it a *name*. + If *name* is not defined the name of the geometric group is used + + Note: + Works like :meth:`GroupOnGeom`. + + Parameters: + grp: a geometric group, a vertex, an edge, a face or a solid + name: the name of the mesh group + + Returns: + :class:`SMESH.SMESH_GroupOnGeom` + """ + return self.GroupOnGeom(grp, name) - ## Create a mesh group based on the geometrical object \a grp - # and gives a \a name, \n if this parameter is not defined - # the name is the same as the geometrical group name - # @param grp a geometrical group, a vertex, an edge, a face or a solid - # @param name the name of the mesh group - # @param typ the type of elements in the group; either of - # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME). If not set, it is - # automatically detected by the type of the geometry - # @return SMESH_GroupOnGeom - # @ingroup l2_grps_create def GroupOnGeom(self, grp, name="", typ=None): + """ + Create a mesh group based on the geometrical object *grp* + and gives a *name*. + if *name* is not defined the name of the geometric group is used + + Parameters: + grp: a geometrical group, a vertex, an edge, a face or a solid + name: the name of the mesh group + typ: the type of elements in the group; either of + (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME). If not set, it is + automatically detected by the type of the geometry + + Returns: + :class:`SMESH.SMESH_GroupOnGeom` + """ + AssureGeomPublished( self, grp, name ) if name == "": name = grp.GetName() @@@ -2352,45 -2104,32 +2458,44 @@@ elif tgeo == "COMPOUND": sub = self.geompyD.SubShapeAll( shape, self.geompyD.ShapeType["SHAPE"]) if not sub: - raise ValueError,"_groupTypeFromShape(): empty geometric group or compound '%s'" % GetName(shape) + raise ValueError("_groupTypeFromShape(): empty geometric group or compound '%s'" % GetName(shape)) return self._groupTypeFromShape( sub[0] ) else: - raise ValueError, \ - "_groupTypeFromShape(): invalid geometry '%s'" % GetName(shape) + raise ValueError("_groupTypeFromShape(): invalid geometry '%s'" % GetName(shape)) return typ - ## Create a mesh group with given \a name based on the \a filter which - ## is a special type of group dynamically updating it's contents during - ## mesh modification - # @param typ the type of elements in the group; either of - # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME). - # @param name the name of the mesh group - # @param filter the filter defining group contents - # @return SMESH_GroupOnFilter - # @ingroup l2_grps_create def GroupOnFilter(self, typ, name, filter): + """ + Create a mesh group with given *name* based on the *filter* which + is a special type of group dynamically updating it's contents during + mesh modification + + Parameters: + typ: the type of elements in the group; either of + (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME). + name: the name of the mesh group + filter (SMESH.Filter): the filter defining group contents + + Returns: + :class:`SMESH.SMESH_GroupOnFilter` + """ + return self.mesh.CreateGroupFromFilter(typ, name, filter) - ## Create a mesh group by the given ids of elements - # @param groupName the name of the mesh group - # @param elementType the type of elements in the group; either of - # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME). - # @param elemIDs either the list of ids, group, sub-mesh, or filter - # @return SMESH_Group - # @ingroup l2_grps_create def MakeGroupByIds(self, groupName, elementType, elemIDs): + """ + Create a mesh group by the given ids of elements + + Parameters: + groupName: the name of the mesh group + elementType: the type of elements in the group; either of + (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME). + elemIDs: either the list of ids, :class:`mesh, sub-mesh, group or filter ` + + Returns: + :class:`SMESH.SMESH_Group` + """ + group = self.mesh.CreateGroup(elementType, groupName) if isinstance( elemIDs, Mesh ): elemIDs = elemIDs.GetMesh() @@@ -2582,128 -2261,76 +2687,126 @@@ groups.append( group ) return groups - ## Produce a union of two groups. - # A new group is created. All mesh elements that are - # present in the initial groups are added to the new one - # @return an instance of SMESH_Group - # @ingroup l2_grps_operon def UnionGroups(self, group1, group2, name): + """ + Produce a union of two groups. + A new group is created. All mesh elements that are + present in the initial groups are added to the new one + + Parameters: + group1 (SMESH.SMESH_GroupBase): a group + group2 (SMESH.SMESH_GroupBase): another group + + Returns: + instance of :class:`SMESH.SMESH_Group` + """ + return self.mesh.UnionGroups(group1, group2, name) - ## Produce a union list of groups. - # New group is created. All mesh elements that are present in - # initial groups are added to the new one - # @return an instance of SMESH_Group - # @ingroup l2_grps_operon def UnionListOfGroups(self, groups, name): + """ + Produce a union list of groups. + New group is created. All mesh elements that are present in + initial groups are added to the new one + + Parameters: + groups: list of :class:`SMESH.SMESH_GroupBase` + + Returns: + instance of :class:`SMESH.SMESH_Group` + """ - return self.mesh.UnionListOfGroups(groups, name) - ## Prodice an intersection of two groups. - # A new group is created. All mesh elements that are common - # for the two initial groups are added to the new one. - # @return an instance of SMESH_Group - # @ingroup l2_grps_operon def IntersectGroups(self, group1, group2, name): + """ + Prodice an intersection of two groups. + A new group is created. All mesh elements that are common + for the two initial groups are added to the new one. + + Parameters: + group1 (SMESH.SMESH_GroupBase): a group + group2 (SMESH.SMESH_GroupBase): another group + + Returns: + instance of :class:`SMESH.SMESH_Group` + """ + return self.mesh.IntersectGroups(group1, group2, name) - ## Produce an intersection of groups. - # New group is created. All mesh elements that are present in all - # initial groups simultaneously are added to the new one - # @return an instance of SMESH_Group - # @ingroup l2_grps_operon def IntersectListOfGroups(self, groups, name): + """ + Produce an intersection of groups. + New group is created. All mesh elements that are present in all + initial groups simultaneously are added to the new one + + Parameters: + groups: a list of :class:`SMESH.SMESH_GroupBase` + + Returns: + instance of :class:`SMESH.SMESH_Group` + """ - return self.mesh.IntersectListOfGroups(groups, name) - ## Produce a cut of two groups. - # A new group is created. All mesh elements that are present in - # the main group but are not present in the tool group are added to the new one - # @return an instance of SMESH_Group - # @ingroup l2_grps_operon def CutGroups(self, main_group, tool_group, name): + """ + Produce a cut of two groups. + A new group is created. All mesh elements that are present in + the main group but are not present in the tool group are added to the new one + + Parameters: + main_group (SMESH.SMESH_GroupBase): a group to cut from + tool_group (SMESH.SMESH_GroupBase): a group to cut by + + Returns: + an instance of :class:`SMESH.SMESH_Group` + """ + return self.mesh.CutGroups(main_group, tool_group, name) - ## Produce a cut of groups. - # A new group is created. All mesh elements that are present in main groups - # but do not present in tool groups are added to the new one - # @return an instance of SMESH_Group - # @ingroup l2_grps_operon def CutListOfGroups(self, main_groups, tool_groups, name): + """ + Produce a cut of groups. + A new group is created. All mesh elements that are present in main groups + but do not present in tool groups are added to the new one + + Parameters: + main_group: groups to cut from (list of :class:`SMESH.SMESH_GroupBase`) + tool_group: groups to cut by (list of :class:`SMESH.SMESH_GroupBase`) + + Returns: + an instance of :class:`SMESH.SMESH_Group` + """ + return self.mesh.CutListOfGroups(main_groups, tool_groups, name) - ## - # Create a standalone group of entities basing on nodes of other groups. - # \param groups - list of reference groups, sub-meshes or filters, of any type. - # \param elemType - a type of elements to include to the new group; either of - # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME). - # \param name - a name of the new group. - # \param nbCommonNodes - a criterion of inclusion of an element to the new group - # basing on number of element nodes common with reference \a groups. - # Meaning of possible values are: - # - SMESH.ALL_NODES - include if all nodes are common, - # - SMESH.MAIN - include if all corner nodes are common (meaningful for a quadratic mesh), - # - SMESH.AT_LEAST_ONE - include if one or more node is common, - # - SMEHS.MAJORITY - include if half of nodes or more are common. - # \param underlyingOnly - if \c True (default), an element is included to the - # new group provided that it is based on nodes of an element of \a groups; - # in this case the reference \a groups are supposed to be of higher dimension - # than \a elemType, which can be useful for example to get all faces lying on - # volumes of the reference \a groups. - # @return an instance of SMESH_Group - # @ingroup l2_grps_operon def CreateDimGroup(self, groups, elemType, name, nbCommonNodes = SMESH.ALL_NODES, underlyingOnly = True): + """ + Create a standalone group of entities basing on nodes of other groups. + + Parameters: + groups: list of reference :class:`sub-meshes, groups or filters `, of any type. + elemType: a type of elements to include to the new group; either of + (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME). + name: a name of the new group. + nbCommonNodes: a criterion of inclusion of an element to the new group + basing on number of element nodes common with reference *groups*. + Meaning of possible values are: + + - SMESH.ALL_NODES - include if all nodes are common, + - SMESH.MAIN - include if all corner nodes are common (meaningful for a quadratic mesh), + - SMESH.AT_LEAST_ONE - include if one or more node is common, + - SMEHS.MAJORITY - include if half of nodes or more are common. + underlyingOnly: if *True* (default), an element is included to the + new group provided that it is based on nodes of an element of *groups*; + in this case the reference *groups* are supposed to be of higher dimension + than *elemType*, which can be useful for example to get all faces lying on + volumes of the reference *groups*. + + Returns: + an instance of :class:`SMESH.SMESH_Group` + """ + if isinstance( groups, SMESH._objref_SMESH_IDSource ): groups = [groups] return self.mesh.CreateDimGroup(groups, elemType, name, nbCommonNodes, underlyingOnly) @@@ -2719,112 -2344,70 +2822,102 @@@ # Get some info about mesh: # ------------------------ - ## Return the log of nodes and elements added or removed - # since the previous clear of the log. - # @param clearAfterGet log is emptied after Get (safe if concurrents access) - # @return list of log_block structures: - # commandType - # number - # coords - # indexes - # @ingroup l1_auxiliary def GetLog(self, clearAfterGet): + """ + Return the log of nodes and elements added or removed + since the previous clear of the log. + + Parameters: + clearAfterGet: log is emptied after Get (safe if concurrents access) + + Returns: + list of SMESH.log_block structures { commandType, number, coords, indexes } + """ + return self.mesh.GetLog(clearAfterGet) - ## Clear the log of nodes and elements added or removed since the previous - # clear. Must be used immediately after GetLog if clearAfterGet is false. - # @ingroup l1_auxiliary def ClearLog(self): + """ + Clear the log of nodes and elements added or removed since the previous + clear. Must be used immediately after :meth:`GetLog` if clearAfterGet is false. + """ + self.mesh.ClearLog() - ## Toggle auto color mode on the object. - # @param theAutoColor the flag which toggles auto color mode. - # - # If switched on, a default color of a new group in Create Group dialog is chosen randomly. - # @ingroup l1_grouping def SetAutoColor(self, theAutoColor): + """ + Toggle auto color mode on the object. + If switched on, a default color of a new group in Create Group dialog is chosen randomly. + + Parameters: + theAutoColor (boolean): the flag which toggles auto color mode. + """ + self.mesh.SetAutoColor(theAutoColor) - ## Get flag of object auto color mode. - # @return True or False - # @ingroup l1_grouping def GetAutoColor(self): + """ + Get flag of object auto color mode. + + Returns: + True or False + """ + return self.mesh.GetAutoColor() - ## Get the internal ID - # @return integer value, which is the internal Id of the mesh - # @ingroup l1_auxiliary def GetId(self): + """ + Get the internal ID + + Returns: + integer value, which is the internal Id of the mesh + """ + return self.mesh.GetId() - def GetStudyId(self): - """ - Get the study Id - - Returns: - integer value, which is the study Id of the mesh - """ - - return self.mesh.GetStudyId() - - ## Check the group names for duplications. - # Consider the maximum group name length stored in MED file. - # @return True or False - # @ingroup l1_grouping def HasDuplicatedGroupNamesMED(self): + """ + Check the group names for duplications. + Consider the maximum group name length stored in MED file. + + Returns: + True or False + """ + return self.mesh.HasDuplicatedGroupNamesMED() - ## Obtain the mesh editor tool - # @return an instance of SMESH_MeshEditor - # @ingroup l1_modifying def GetMeshEditor(self): + """ + Obtain the mesh editor tool + + Returns: + an instance of :class:`SMESH.SMESH_MeshEditor` + """ + return self.editor - ## Wrap a list of IDs of elements or nodes into SMESH_IDSource which - # can be passed as argument to a method accepting mesh, group or sub-mesh - # @param ids list of IDs - # @param elemType type of elements; this parameter is used to distinguish - # IDs of nodes from IDs of elements; by default ids are treated as - # IDs of elements; use SMESH.NODE if ids are IDs of nodes. - # @return an instance of SMESH_IDSource - # @warning call UnRegister() for the returned object as soon as it is no more useful: - # idSrc = mesh.GetIDSource( [1,3,5], SMESH.NODE ) - # mesh.DoSomething( idSrc ) - # idSrc.UnRegister() - # @ingroup l1_auxiliary def GetIDSource(self, ids, elemType = SMESH.ALL): + """ + Wrap a list of IDs of elements or nodes into :class:`SMESH.SMESH_IDSource` which + can be passed as argument to a method accepting :class:`mesh, sub-mesh, group or filter ` + + Parameters: + ids: list of IDs + elemType: type of elements; this parameter is used to distinguish + IDs of nodes from IDs of elements; by default ids are treated as + IDs of elements; use SMESH.NODE if ids are IDs of nodes. + + Returns: + an instance of :class:`SMESH.SMESH_IDSource` + + Warning: + call UnRegister() for the returned object as soon as it is no more useful:: + + idSrc = mesh.GetIDSource( [1,3,5], SMESH.NODE ) + mesh.DoSomething( idSrc ) + idSrc.UnRegister() + """ + if isinstance( ids, int ): ids = [ids] return self.editor.MakeIDSource(ids, elemType) @@@ -3926,68 -3115,50 +4019,68 @@@ EdgeID = Edge try: self.editor.SetNodeOnEdge(NodeID, EdgeID, paramOnEdge) - except SALOME.SALOME_Exception, inst: - raise ValueError, inst.details.text + except SALOME.SALOME_Exception as inst: + raise ValueError(inst.details.text) return True - ## @brief Stores node position on a face - # @param NodeID a node ID - # @param Face a face or face ID - # @param u U parameter on the face where the node is located - # @param v V parameter on the face where the node is located - # @return True if succeed else raises an exception - # @ingroup l2_modif_add def SetNodeOnFace(self, NodeID, Face, u, v): + """ + Stores node position on a face + + Parameters: + NodeID: a node ID + Face: a face (GEOM.GEOM_Object) or face ID + u: U parameter on the face where the node is located + v: V parameter on the face where the node is located + + Returns: + True if succeed else raises an exception + """ + if ( isinstance( Face, geomBuilder.GEOM._objref_GEOM_Object)): FaceID = self.geompyD.GetSubShapeID( self.geom, Face ) else: FaceID = Face try: self.editor.SetNodeOnFace(NodeID, FaceID, u, v) - except SALOME.SALOME_Exception, inst: - raise ValueError, inst.details.text + except SALOME.SALOME_Exception as inst: + raise ValueError(inst.details.text) return True - ## @brief Binds a node to a solid - # @param NodeID a node ID - # @param Solid a solid or solid ID - # @return True if succeed else raises an exception - # @ingroup l2_modif_add def SetNodeInVolume(self, NodeID, Solid): + """ + Binds a node to a solid + + Parameters: + NodeID: a node ID + Solid: a solid (GEOM.GEOM_Object) or solid ID + + Returns: + True if succeed else raises an exception + """ + if ( isinstance( Solid, geomBuilder.GEOM._objref_GEOM_Object)): SolidID = self.geompyD.GetSubShapeID( self.geom, Solid ) else: SolidID = Solid try: self.editor.SetNodeInVolume(NodeID, SolidID) - except SALOME.SALOME_Exception, inst: - raise ValueError, inst.details.text + except SALOME.SALOME_Exception as inst: + raise ValueError(inst.details.text) return True - ## @brief Bind an element to a shape - # @param ElementID an element ID - # @param Shape a shape or shape ID - # @return True if succeed else raises an exception - # @ingroup l2_modif_add def SetMeshElementOnShape(self, ElementID, Shape): + """ + Bind an element to a shape + + Parameters: + ElementID: an element ID + Shape: a shape (GEOM.GEOM_Object) or shape ID + + Returns: + True if succeed else raises an exception + """ + if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)): ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape ) else: @@@ -4053,20 -3206,17 +4146,19 @@@ #return preview.MoveClosestNodeToPoint(x, y, z, -1) return self.editor.FindNodeClosestTo(x, y, z) - ## Find the elements where a point lays IN or ON - # @param x the X coordinate of a point - # @param y the Y coordinate of a point - # @param z the Z coordinate of a point - # @param elementType type of elements to find; either of - # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME); SMESH.ALL type - # means elements of any type excluding nodes, discrete and 0D elements. - # @param meshPart a part of mesh (group, sub-mesh) to search within - # @return list of IDs of found elements - # @ingroup l1_meshinfo def FindElementsByPoint(self, x, y, z, elementType = SMESH.ALL, meshPart=None): + """ + Find the elements where a point lays IN or ON + + Parameters: + x,y,z (float): coordinates of the point + elementType (SMESH.ElementType): type of elements to find; SMESH.ALL type + means elements of any type excluding nodes, discrete and 0D elements. + meshPart: a part of mesh (:class:`sub-mesh, group or filter `) to search within + + Returns: + list of IDs of found elements + """ - if meshPart: return self.editor.FindAmongElementsByPoint( meshPart, x, y, z, elementType ); else: @@@ -4783,22 -3787,15 +4875,22 @@@ self.editor.ConvertToQuadratic(theForce3d) error = self.editor.GetLastError() if error and error.comment: - print error.comment + print(error.comment) return error - ## Convert the mesh from quadratic to ordinary, - # deletes old quadratic elements, \n replacing - # them with ordinary mesh elements with the same id. - # @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal - # @ingroup l2_modif_tofromqu def ConvertFromQuadratic(self, theSubMesh=None): + """ + Convert the mesh from quadratic to ordinary, + deletes old quadratic elements, + replacing them with ordinary mesh elements with the same id. + + Parameters: + theSubMesh: a :class:`sub-mesh, group or filter ` to convert + + Warning: + If *theSubMesh* is provided, the mesh can become non-conformal + """ + if theSubMesh: self.editor.ConvertFromQuadraticObject(theSubMesh) else: @@@ -6044,46 -4756,34 +6136,46 @@@ if holeNodes and isinstance( holeNodes, list ) and isinstance( holeNodes[0], int ): holeNodes = SMESH.FreeBorder(nodeIDs=holeNodes) if not isinstance( holeNodes, SMESH.FreeBorder ): - raise TypeError, "holeNodes must be either SMESH.FreeBorder or list of integer and not %s" % holeNodes + raise TypeError("holeNodes must be either SMESH.FreeBorder or list of integer and not %s" % holeNodes) self.editor.FillHole( holeNodes ) - ## Return groups of FreeBorder's coincident within the given tolerance. - # @param tolerance the tolerance. If the tolerance <= 0.0 then one tenth of an average - # size of elements adjacent to free borders being compared is used. - # @return SMESH.CoincidentFreeBorders structure - # @ingroup l2_modif_trsf def FindCoincidentFreeBorders (self, tolerance=0.): + """ + Return groups of FreeBorder's coincident within the given tolerance. + + Parameters: + tolerance: the tolerance. If the tolerance <= 0.0 then one tenth of an average + size of elements adjacent to free borders being compared is used. + + Returns: + SMESH.CoincidentFreeBorders structure + """ + return self.editor.FindCoincidentFreeBorders( tolerance ) - ## Sew FreeBorder's of each group - # @param freeBorders either a SMESH.CoincidentFreeBorders structure or a list of lists - # where each enclosed list contains node IDs of a group of coincident free - # borders such that each consequent triple of IDs within a group describes - # a free border in a usual way: n1, n2, nLast - i.e. 1st node, 2nd node and - # last node of a border. - # For example [[1, 2, 10, 20, 21, 40], [11, 12, 15, 55, 54, 41]] describes two - # groups of coincident free borders, each group including two borders. - # @param createPolygons if @c True faces adjacent to free borders are converted to - # polygons if a node of opposite border falls on a face edge, else such - # faces are split into several ones. - # @param createPolyhedra if @c True volumes adjacent to free borders are converted to - # polyhedra if a node of opposite border falls on a volume edge, else such - # volumes, if any, remain intact and the mesh becomes non-conformal. - # @return a number of successfully sewed groups - # @ingroup l2_modif_trsf def SewCoincidentFreeBorders (self, freeBorders, createPolygons=False, createPolyhedra=False): + """ + Sew FreeBorder's of each group + + Parameters: + freeBorders: either a SMESH.CoincidentFreeBorders structure or a list of lists + where each enclosed list contains node IDs of a group of coincident free + borders such that each consequent triple of IDs within a group describes + a free border in a usual way: n1, n2, nLast - i.e. 1st node, 2nd node and + last node of a border. + For example [[1, 2, 10, 20, 21, 40], [11, 12, 15, 55, 54, 41]] describes two + groups of coincident free borders, each group including two borders. + createPolygons: if :code:`True` faces adjacent to free borders are converted to + polygons if a node of opposite border falls on a face edge, else such + faces are split into several ones. + createPolyhedra: if :code:`True` volumes adjacent to free borders are converted to + polyhedra if a node of opposite border falls on a volume edge, else such + volumes, if any, remain intact and the mesh becomes non-conformal. + + Returns: + a number of successfully sewed groups + """ + if freeBorders and isinstance( freeBorders, list ): # construct SMESH.CoincidentFreeBorders if isinstance( freeBorders[0], int ): @@@ -6412,105 -5020,76 +6504,106 @@@ return twoGroups[ int(theMakeNodeGroup) ] return self.editor.DoubleNodeElemGroups(theElems, theNodesNot, theAffectedElems) - ## Create a hole in a mesh by doubling the nodes of some particular elements - # This method provided for convenience works as DoubleNodes() described above. - # @param theElems - list of groups of elements (edges or faces) to be replicated - # @param theNodesNot - list of groups of nodes not to replicated - # @param theShape - shape to detect affected elements (element which geometric center - # located on or inside shape). - # The replicated nodes should be associated to affected elements. - # @return TRUE if operation has been completed successfully, FALSE otherwise - # @ingroup l2_modif_duplicat def DoubleNodeElemGroupsInRegion(self, theElems, theNodesNot, theShape): + """ + Create a hole in a mesh by doubling the nodes of some particular elements. + This method provided for convenience works as :meth:`DoubleNodes`. + + Parameters: + theElems: list of groups of elements (edges or faces) to replicate + theNodesNot: list of groups of nodes NOT to replicate + theShape: shape to detect affected elements (element which geometric center + located on or inside shape). + The replicated nodes should be associated to affected elements + + Returns: + True if operation has been completed successfully, False otherwise + """ + return self.editor.DoubleNodeElemGroupsInRegion(theElems, theNodesNot, theShape) - ## Identify the elements that will be affected by node duplication (actual duplication is not performed. - # This method is the first step of DoubleNodeElemGroupsInRegion. - # @param theElems - list of groups of nodes or elements (edges or faces) to be replicated - # @param theNodesNot - list of groups of nodes not to replicated - # @param theShape - shape to detect affected elements (element which geometric center - # located on or inside shape). - # The replicated nodes should be associated to affected elements. - # @return groups of affected elements in order: volumes, faces, edges - # @ingroup l2_modif_duplicat def AffectedElemGroupsInRegion(self, theElems, theNodesNot, theShape): + """ + Identify the elements that will be affected by node duplication (actual duplication is not performed). + This method is the first step of :meth:`DoubleNodeElemGroupsInRegion`. + + Parameters: + theElems: list of groups of nodes or elements (edges or faces) to replicate + theNodesNot: list of groups of nodes NOT to replicate + theShape: shape to detect affected elements (element which geometric center + located on or inside shape). + The replicated nodes should be associated to affected elements + + Returns: + groups of affected elements in order: volumes, faces, edges + """ + return self.editor.AffectedElemGroupsInRegion(theElems, theNodesNot, theShape) - ## Double nodes on shared faces between groups of volumes and create flat elements on demand. - # The list of groups must describe a partition of the mesh volumes. - # The nodes of the internal faces at the boundaries of the groups are doubled. - # In option, the internal faces are replaced by flat elements. - # Triangles are transformed in prisms, and quadrangles in hexahedrons. - # @param theDomains - list of groups of volumes - # @param createJointElems - if TRUE, create the elements - # @param onAllBoundaries - if TRUE, the nodes and elements are also created on - # the boundary between \a theDomains and the rest mesh - # @return TRUE if operation has been completed successfully, FALSE otherwise - # @ingroup l2_modif_duplicat def DoubleNodesOnGroupBoundaries(self, theDomains, createJointElems, onAllBoundaries=False ): ++ + """ + Double nodes on shared faces between groups of volumes and create flat elements on demand. + The list of groups must describe a partition of the mesh volumes. + The nodes of the internal faces at the boundaries of the groups are doubled. + In option, the internal faces are replaced by flat elements. + Triangles are transformed to prisms, and quadrangles to hexahedrons. + + Parameters: + theDomains: list of groups of volumes + createJointElems: if True, create the elements + onAllBoundaries: if True, the nodes and elements are also created on + the boundary between *theDomains* and the rest mesh + + Returns: + True if operation has been completed successfully, False otherwise + """ + return self.editor.DoubleNodesOnGroupBoundaries( theDomains, createJointElems, onAllBoundaries ) - ## Double nodes on some external faces and create flat elements. - # Flat elements are mainly used by some types of mechanic calculations. - # - # Each group of the list must be constituted of faces. - # Triangles are transformed in prisms, and quadrangles in hexahedrons. - # @param theGroupsOfFaces - list of groups of faces - # @return TRUE if operation has been completed successfully, FALSE otherwise - # @ingroup l2_modif_duplicat def CreateFlatElementsOnFacesGroups(self, theGroupsOfFaces ): + """ + Double nodes on some external faces and create flat elements. + Flat elements are mainly used by some types of mechanic calculations. + + Each group of the list must be constituted of faces. + Triangles are transformed in prisms, and quadrangles in hexahedrons. + + Parameters: + theGroupsOfFaces: list of groups of faces + + Returns: + True if operation has been completed successfully, False otherwise + """ + return self.editor.CreateFlatElementsOnFacesGroups( theGroupsOfFaces ) - ## identify all the elements around a geom shape, get the faces delimiting the hole - # def CreateHoleSkin(self, radius, theShape, groupName, theNodesCoords): + """ + Identify all the elements around a geom shape, get the faces delimiting the hole + """ return self.editor.CreateHoleSkin( radius, theShape, groupName, theNodesCoords ) - ## Create a polyline consisting of 1D mesh elements each lying on a 2D element of - # the initial mesh. Positions of new nodes are found by cutting the mesh by the - # plane passing through pairs of points specified by each PolySegment structure. - # If there are several paths connecting a pair of points, the shortest path is - # selected by the module. Position of the cutting plane is defined by the two - # points and an optional vector lying on the plane specified by a PolySegment. - # By default the vector is defined by Mesh module as following. A middle point - # of the two given points is computed. The middle point is projected to the mesh. - # The vector goes from the middle point to the projection point. In case of planar - # mesh, the vector is normal to the mesh. - # @param segments - PolySegment's defining positions of cutting planes. - # Return the used vector which goes from the middle point to its projection. - # @param groupName - optional name of a group where created mesh segments will - # be added. - # @ingroup l2_modif_duplicat def MakePolyLine(self, segments, groupName='', isPreview=False ): + """ + Create a polyline consisting of 1D mesh elements each lying on a 2D element of + the initial mesh. Positions of new nodes are found by cutting the mesh by the + plane passing through pairs of points specified by each :class:`SMESH.PolySegment` structure. + If there are several paths connecting a pair of points, the shortest path is + selected by the module. Position of the cutting plane is defined by the two + points and an optional vector lying on the plane specified by a PolySegment. + By default the vector is defined by Mesh module as following. A middle point + of the two given points is computed. The middle point is projected to the mesh. + The vector goes from the middle point to the projection point. In case of planar + mesh, the vector is normal to the mesh. + + *segments* [i].vector returns the used vector which goes from the middle point to its projection. + + Parameters: + segments: list of :class:`SMESH.PolySegment` defining positions of cutting planes. + groupName: optional name of a group where created mesh segments will be added. + + """ editor = self.editor if isPreview: editor = self.mesh.GetMeshEditPreviewer() @@@ -6733,15 -5244,14 +6826,15 @@@ pass # end of Mesh class -## Private class used to compensate change of CORBA API of SMESH_Mesh for backward compatibility -# with old dump scripts which call SMESH_Mesh directly and not via smeshBuilder.Mesh -# class meshProxy(SMESH._objref_SMESH_Mesh): - def __init__(self, *args): - SMESH._objref_SMESH_Mesh.__init__(self, *args) + """ + Private class used to compensate change of CORBA API of SMESH_Mesh for backward compatibility + with old dump scripts which call SMESH_Mesh directly and not via smeshBuilder.Mesh + """ - def __init__(self): - SMESH._objref_SMESH_Mesh.__init__(self) ++ def __init__(self,*args): ++ SMESH._objref_SMESH_Mesh.__init__(self,*args) def __deepcopy__(self, memo=None): - new = self.__class__() + new = self.__class__(self) return new def CreateDimGroup(self,*args): # 2 args added: nbCommonNodes, underlyingOnly if len( args ) == 3: @@@ -6751,31 -5279,24 +6862,32 @@@ omniORB.registerObjref(SMESH._objref_SMESH_Mesh._NP_RepositoryId, meshProxy) -## Private class wrapping SMESH.SMESH_SubMesh in order to add Compute() -# class submeshProxy(SMESH._objref_SMESH_subMesh): - def __init__(self, *args): - SMESH._objref_SMESH_subMesh.__init__(self, *args) ++ + """ + Private class wrapping SMESH.SMESH_SubMesh in order to add Compute() + """ - def __init__(self): - SMESH._objref_SMESH_subMesh.__init__(self) ++ def __init__(self,*args): ++ SMESH._objref_SMESH_subMesh.__init__(self,*args) self.mesh = None def __deepcopy__(self, memo=None): - new = self.__class__() + new = self.__class__(self) return new - ## Compute the sub-mesh and return the status of the computation - # @param refresh if @c True, Object browser is automatically updated (when running in GUI) - # @return True or False - # - # This is a method of SMESH.SMESH_submesh that can be obtained via Mesh.GetSubMesh() or - # @ref smesh_algorithm.Mesh_Algorithm.GetSubMesh() "Mesh_Algorithm.GetSubMesh()". - # @ingroup l2_submeshes def Compute(self,refresh=False): + """ + Compute the sub-mesh and return the status of the computation + + Parameters: + refresh: if *True*, Object Browser is automatically updated (when running in GUI) + + Returns: + True or False + + This is a method of SMESH.SMESH_submesh that can be obtained via Mesh.GetSubMesh() or + :meth:`smeshBuilder.Mesh.GetSubMesh`. + """ + if not self.mesh: self.mesh = Mesh( smeshBuilder(), None, self.GetMesh()) @@@ -6793,14 -5314,13 +6905,14 @@@ omniORB.registerObjref(SMESH._objref_SMESH_subMesh._NP_RepositoryId, submeshProxy) -## Private class used to compensate change of CORBA API of SMESH_MeshEditor for backward -# compatibility with old dump scripts which call SMESH_MeshEditor directly and not via -# smeshBuilder.Mesh -# class meshEditor(SMESH._objref_SMESH_MeshEditor): - def __init__(self, *args): - SMESH._objref_SMESH_MeshEditor.__init__(self, *args) + """ + Private class used to compensate change of CORBA API of SMESH_MeshEditor for backward + compatibility with old dump scripts which call SMESH_MeshEditor directly and not via + smeshBuilder.Mesh + """ - def __init__(self): - SMESH._objref_SMESH_MeshEditor.__init__(self) ++ def __init__(self,*args): ++ SMESH._objref_SMESH_MeshEditor.__init__( self, *args) self.mesh = None def __getattr__(self, name ): # method called if an attribute not found if not self.mesh: # look for name() method in Mesh class @@@ -6881,23 -5396,18 +6993,23 @@@ class algoCreator self.algoTypeToClass = {} self.method = method - # Store a python class of algorithm def add(self, algoClass): + """ + Store a python class of algorithm + """ - if type( algoClass ).__name__ == 'classobj' and \ + if inspect.isclass(algoClass) and \ - hasattr(algoClass, "algoType"): + hasattr( algoClass, "algoType"): self.algoTypeToClass[ algoClass.algoType ] = algoClass if not self.defaultAlgoType and \ hasattr( algoClass, "isDefault") and algoClass.isDefault: self.defaultAlgoType = algoClass.algoType -- #print "Add",algoClass.algoType, "dflt",self.defaultAlgoType ++ #print("Add",algoClass.algoType, "dflt",self.defaultAlgoType) - # Create a copy of self and assign mesh to the copy def copy(self, mesh): + """ + Create a copy of self and assign mesh to the copy + """ + other = algoCreator( self.method ) other.defaultAlgoType = self.defaultAlgoType other.algoTypeToClass = self.algoTypeToClass @@@ -6939,32 -5447,28 +7051,33 @@@ algoType = self.defaultAlgoType if not algoType and self.algoTypeToClass: algoType = sorted( self.algoTypeToClass.keys() )[0] - if self.algoTypeToClass.has_key( algoType ): - #print "Create algo",algoType + if algoType in self.algoTypeToClass: - #print "Create algo",algoType ++ #print("Create algo",algoType) + return self.algoTypeToClass[ algoType ]( self.mesh, shape ) - raise RuntimeError, "No class found for algo type %s" % algoType + raise RuntimeError( "No class found for algo type %s" % algoType) return None -## Private class used to substitute and store variable parameters of hypotheses. -# class hypMethodWrapper: + """ + Private class used to substitute and store variable parameters of hypotheses. + """ + def __init__(self, hyp, method): self.hyp = hyp self.method = method -- #print "REBIND:", method.__name__ ++ #print("REBIND:", method.__name__) return - # call a method of hypothesis with calling SetVarParameter() before def __call__(self,*args): + """ + call a method of hypothesis with calling SetVarParameter() before + """ + if not args: return self.method( self.hyp, *args ) # hypothesis method with no args -- #print "MethWrapper.__call__",self.method.__name__, args ++ #print("MethWrapper.__call__", self.method.__name__, args) try: parsed = ParseParameters(*args) # replace variables with their values self.hyp.SetVarParameter( parsed[-2], self.method.__name__ ) @@@ -7004,12 -5507,12 +7117,12 @@@ class genObjUnRegister if genObj and hasattr( genObj, "UnRegister" ): genObj.UnRegister() - -## Bind methods creating mesher plug-ins to the Mesh class -# for pluginName in os.environ[ "SMESH_MeshersList" ].split( ":" ): - # - #print "pluginName: ", pluginName + """ + Bind methods creating mesher plug-ins to the Mesh class + """ + - # print "pluginName: ", pluginName ++ # print("pluginName: ", pluginName) pluginBuilderName = pluginName + "Builder" try: exec( "from salome.%s.%s import *" % (pluginName, pluginBuilderName)) @@@ -7019,15 -5522,15 +7132,15 @@@ continue exec( "from salome.%s import %s" % (pluginName, pluginBuilderName)) plugin = eval( pluginBuilderName ) - # print " plugin:" , str(plugin) - #print " plugin:" , str(plugin) ++ # print(" plugin:" , str(plugin)) # add methods creating algorithms to Mesh for k in dir( plugin ): if k[0] == '_': continue algo = getattr( plugin, k ) - # print " algo:", str(algo) - if type( algo ).__name__ == 'classobj' and hasattr( algo, "meshMethod" ): - # print " meshMethod:" , str(algo.meshMethod) - #print " algo:", str(algo) ++ #print(" algo:", str(algo)) + if inspect.isclass(algo) and hasattr(algo, "meshMethod"): - #print " meshMethod:" , str(algo.meshMethod) ++ #print(" meshMethod:" , str(algo.meshMethod)) if not hasattr( Mesh, algo.meshMethod ): setattr( Mesh, algo.meshMethod, algoCreator( algo.meshMethod )) pass diff --cc src/SMESH_SWIG/smesh_algorithm.py index 172dcca74,92999bf2e..b8c12430e --- a/src/SMESH_SWIG/smesh_algorithm.py +++ b/src/SMESH_SWIG/smesh_algorithm.py @@@ -25,64 -25,52 +25,64 @@@ import salom from salome.geom import geomBuilder import SMESH, StdMeshers -## The base class to define meshing algorithms -# -# @note This class should not be used directly, it is supposed to be sub-classed -# for implementing Python API for specific meshing algorithms -# -# For each meshing algorithm, a python class inheriting from class %Mesh_Algorithm -# should be defined. This descendant class should have two attributes defining the way -# it is created by class Mesh (see e.g. class @ref StdMeshersBuilder.StdMeshersBuilder_Segment "StdMeshersBuilder_Segment" -# in StdMeshersBuilder package): -# - @c meshMethod attribute defines name of method of class smesh.Mesh by calling which the -# python class of algorithm is created; this method is dynamically added to the smesh.Mesh class -# in runtime. For example, if in @c class MyPlugin_Algorithm this attribute is defined as -# @code -# meshMethod = "MyAlgorithm" -# @endcode -# then an instance of @c MyPlugin_Algorithm can be created by the direct invocation of the function -# of smesh.Mesh class: -# @code -# my_algo = mesh.MyAlgorithm() -# @endcode -# - @c algoType defines type of algorithm and is used mostly to discriminate -# algorithms that are created by the same method of class smesh.Mesh. For example, if this attribute -# is specified in @c MyPlugin_Algorithm class as -# @code -# algoType = "MyPLUGIN" -# @endcode -# then it's creation code can be: -# @code -# my_algo = mesh.MyAlgorithm(algo="MyPLUGIN") -# @endcode -# @ingroup l2_algorithms class Mesh_Algorithm: + """ + The base class to define meshing algorithms + + Note: - This class should not be used directly, it is supposed to be sub-classed ++ This class should not be used directly, it is supposed to be sub-classed + for implementing Python API for specific meshing algorithms + + For each meshing algorithm, a python class inheriting from class %Mesh_Algorithm + should be defined. This descendant class should have two attributes defining the way + it is created by class Mesh (see e.g. class :class:`~StdMeshersBuilder.StdMeshersBuilder_Segment` + in StdMeshersBuilder package): + - - :code:`meshMethod` attribute defines name of method of class smesh.Mesh by calling which the - python class of algorithm is created; this method is dynamically added to the smesh.Mesh class - in runtime. For example, if in :code:`class MyPlugin_Algorithm` this attribute is defined as - :: ++ - :code:`meshMethod` attribute defines name of method of class smesh.Mesh by calling which the ++ python class of algorithm is created; this method is dynamically added to the smesh.Mesh class ++ in runtime. For example, if in :code:`class MyPlugin_Algorithm` this attribute is defined as ++ :: + - meshMethod = "MyAlgorithm" ++ meshMethod = "MyAlgorithm" + - then an instance of :code:`MyPlugin_Algorithm` can be created by the direct invocation of the function - of smesh.Mesh class: - :: ++ then an instance of :code:`MyPlugin_Algorithm` can be created by the direct invocation of the function ++ of smesh.Mesh class: ++ :: + - my_algo = mesh.MyAlgorithm() ++ my_algo = mesh.MyAlgorithm() + - - :code:`algoType` defines type of algorithm and is used mostly to discriminate - algorithms that are created by the same method of class smesh.Mesh. For example, if this attribute - is specified in :code:`MyPlugin_Algorithm` class as - :: ++ - :code:`algoType` defines type of algorithm and is used mostly to discriminate ++ algorithms that are created by the same method of class smesh.Mesh. For example, if this attribute ++ is specified in :code:`MyPlugin_Algorithm` class as ++ :: + - algoType = "MyPLUGIN" ++ algoType = "MyPLUGIN" + - then it's creation code can be: - :: ++ then it's creation code can be: ++ :: + - my_algo = mesh.MyAlgorithm(algo="MyPLUGIN") ++ my_algo = mesh.MyAlgorithm(algo="MyPLUGIN") + """ + - ## Private constructor def __init__(self): - """ - Private constuctor - """ ++ """ ++ Private constuctor ++ """ self.mesh = None self.geom = None self.subm = None self.algo = None pass - ## Finds a hypothesis in the study by its type name and parameters. - # Finds only the hypotheses created in smeshpyD engine. - # @return SMESH.SMESH_Hypothesis def FindHypothesis (self, hypname, args, CompareMethod, smeshpyD): - """ - Finds a hypothesis in the study by its type name and parameters. - Finds only the hypotheses created in smeshpyD engine. - Returns: - SMESH.SMESH_Hypothesis - """ - study = smeshpyD.GetCurrentStudy() ++ """ ++ Finds a hypothesis in the study by its type name and parameters. ++ Finds only the hypotheses created in smeshpyD engine. ++ Returns: ++ SMESH.SMESH_Hypothesis ++ """ + study = salome.myStudy if not study: return None #to do: find component by smeshpyD object, not by its data type scomp = study.FindComponent(smeshpyD.ComponentDataType()) @@@ -122,15 -110,11 +122,15 @@@ pass return None - ## Finds the algorithm in the study by its type name. - # Finds only the algorithms, which have been created in smeshpyD engine. - # @return SMESH.SMESH_Algo def FindAlgorithm (self, algoname, smeshpyD): - """ - Finds the algorithm in the study by its type name. - Finds only the algorithms, which have been created in smeshpyD engine. - - Returns: - SMESH.SMESH_Algo - """ - study = smeshpyD.GetCurrentStudy() ++ """ ++ Finds the algorithm in the study by its type name. ++ Finds only the algorithms, which have been created in smeshpyD engine. ++ ++ Returns: ++ SMESH.SMESH_Algo ++ """ + study = salome.myStudy if not study: return None #to do: find component by smeshpyD object, not by its data type scomp = study.FindComponent(smeshpyD.ComponentDataType()) @@@ -167,53 -151,39 +167,53 @@@ pass return None - ## If the algorithm is global, returns 0; \n - # else returns the submesh associated to this algorithm. def GetSubMesh(self): - """ - If the algorithm is global, returns 0; - else returns the submesh associated to this algorithm. - """ ++ """ ++ If the algorithm is global, returns 0; ++ else returns the submesh associated to this algorithm. ++ """ return self.subm - ## Returns the wrapped mesher. def GetAlgorithm(self): - """ - Returns the wrapped mesher. - """ ++ """ ++ Returns the wrapped mesher. ++ """ return self.algo - ## Gets the list of hypothesis that can be used with this algorithm def GetCompatibleHypothesis(self): - """ - Gets the list of hypothesis that can be used with this algorithm - """ ++ """ ++ Gets the list of hypothesis that can be used with this algorithm ++ """ mylist = [] if self.algo: mylist = self.algo.GetCompatibleHypothesis() return mylist - ## Gets the name of the algorithm def GetName(self): - """ - Gets the name of the algorithm - """ ++ """ ++ Gets the name of the algorithm ++ """ from salome.smesh.smeshBuilder import GetName return GetName(self.algo) - ## Sets the name to the algorithm def SetName(self, name): - """ - Sets the name to the algorithm - """ ++ """ ++ Sets the name to the algorithm ++ """ self.mesh.smeshpyD.SetName(self.algo, name) - ## Gets the id of the algorithm def GetId(self): - """ - Gets the id of the algorithm - """ ++ """ ++ Gets the id of the algorithm ++ """ return self.algo.GetId() - ## Private method. def Create(self, mesh, geom, hypo, so="libStdMeshersEngine.so"): - """ - Private method. - """ ++ """ ++ Private method. ++ """ if geom is None and mesh.mesh.HasShapeToMesh(): - raise RuntimeError, "Attempt to create " + hypo + " algorithm on None shape" + raise RuntimeError("Attempt to create " + hypo + " algorithm on None shape") algo = self.FindAlgorithm(hypo, mesh.smeshpyD) if algo is None: algo = mesh.smeshpyD.CreateHypothesis(hypo, so) @@@ -221,13 -191,11 +221,13 @@@ self.Assign(algo, mesh, geom) return self.algo - ## Private method def Assign(self, algo, mesh, geom): - """ - Private method - """ ++ """ ++ Private method ++ """ from salome.smesh.smeshBuilder import AssureGeomPublished, TreatHypoStatus, GetName if geom is None and mesh.mesh.HasShapeToMesh(): - raise RuntimeError, "Attempt to create " + algo + " algorithm on None shape" + raise RuntimeError("Attempt to create " + algo + " algorithm on None shape") self.mesh = mesh if not geom or geom.IsSame( mesh.geom ): self.geom = mesh.geom @@@ -246,11 -214,9 +246,11 @@@ def CompareEqualHyp (self, hyp, args): return True - ## Private method def Hypothesis (self, hyp, args=[], so="libStdMeshersEngine.so", UseExisting=0, CompareMethod="", toAdd=True): - """ - Private method - """ ++ """ ++ Private method ++ """ from salome.smesh.smeshBuilder import TreatHypoStatus, GetName hypo = None if UseExisting: @@@ -284,51 -250,44 +284,51 @@@ TreatHypoStatus( status, GetName(hypo), geomName, 0, self.mesh ) return hypo - ## Returns entry of the shape to mesh in the study def MainShapeEntry(self): - """ - Returns entry of the shape to mesh in the study - """ ++ """ ++ Returns entry of the shape to mesh in the study ++ """ if not self.mesh or not self.mesh.GetMesh(): return "" if not self.mesh.GetMesh().HasShapeToMesh(): return "" shape = self.mesh.GetShape() return shape.GetStudyEntry() - ## Defines "ViscousLayers" hypothesis to give parameters of layers of prisms to build - # near mesh boundary. This hypothesis can be used by several 3D algorithms: - # NETGEN 3D, MG-Tetra, Hexahedron(i,j,k) - # @param thickness total thickness of layers of prisms - # @param numberOfLayers number of layers of prisms - # @param stretchFactor factor (>1.0) of growth of layer thickness towards inside of mesh - # @param faces list of geometrical faces (or their ids). - # Viscous layers are either generated on these faces or not, depending on - # the value of \a isFacesToIgnore parameter. - # @param isFacesToIgnore if \c True, the Viscous layers are not generated on the - # faces specified by the previous parameter (\a faces). - # @param extrMethod extrusion method defines how position of new nodes are found during - # prism construction and how creation of distorted and intersecting prisms is - # prevented. Possible values are: - # - StdMeshers.SURF_OFFSET_SMOOTH (default) method extrudes nodes along normal - # to underlying geometrical surface. Smoothing of internal surface of - # element layers can be used to avoid creation of invalid prisms. - # - StdMeshers.FACE_OFFSET method extrudes nodes along average normal of - # surrounding mesh faces till intersection with a neighbor mesh face - # translated along its own normal by the layers thickness. Thickness - # of layers can be limited to avoid creation of invalid prisms. - # - StdMeshers.NODE_OFFSET method extrudes nodes along average normal of - # surrounding mesh faces by the layers thickness. Thickness of - # layers can be limited to avoid creation of invalid prisms. - # @ingroup l3_hypos_additi def ViscousLayers(self, thickness, numberOfLayers, stretchFactor, faces=[], isFacesToIgnore=True, extrMethod=StdMeshers.SURF_OFFSET_SMOOTH ): - """ - Defines "ViscousLayers" hypothesis to give parameters of layers of prisms to build - near mesh boundary. This hypothesis can be used by several 3D algorithms: - NETGEN 3D, MG-Tetra, Hexahedron(i,j,k) - - Parameters: - thickness: total thickness of layers of prisms - numberOfLayers: number of layers of prisms - stretchFactor: factor (>1.0) of growth of layer thickness towards inside of mesh - faces: list of geometrical faces (or their ids). - Viscous layers are either generated on these faces or not, depending on - the value of **isFacesToIgnore** parameter. - isFacesToIgnore: if *True*, the Viscous layers are not generated on the - faces specified by the previous parameter (**faces**). - extrMethod: extrusion method defines how position of new nodes are found during - prism construction and how creation of distorted and intersecting prisms is - prevented. Possible values are: - - - StdMeshers.SURF_OFFSET_SMOOTH (default) method extrudes nodes along normal - to underlying geometrical surface. Smoothing of internal surface of - element layers can be used to avoid creation of invalid prisms. - - StdMeshers.FACE_OFFSET method extrudes nodes along average normal of - surrounding mesh faces till intersection with a neighbor mesh face - translated along its own normal by the layers thickness. Thickness - of layers can be limited to avoid creation of invalid prisms. - - StdMeshers.NODE_OFFSET method extrudes nodes along average normal of - surrounding mesh faces by the layers thickness. Thickness of - layers can be limited to avoid creation of invalid prisms. - """ ++ """ ++ Defines "ViscousLayers" hypothesis to give parameters of layers of prisms to build ++ near mesh boundary. This hypothesis can be used by several 3D algorithms: ++ NETGEN 3D, MG-Tetra, Hexahedron(i,j,k) ++ ++ Parameters: ++ thickness: total thickness of layers of prisms ++ numberOfLayers: number of layers of prisms ++ stretchFactor: factor (>1.0) of growth of layer thickness towards inside of mesh ++ faces: list of geometrical faces (or their ids). ++ Viscous layers are either generated on these faces or not, depending on ++ the value of **isFacesToIgnore** parameter. ++ isFacesToIgnore: if *True*, the Viscous layers are not generated on the ++ faces specified by the previous parameter (**faces**). ++ extrMethod: extrusion method defines how position of new nodes are found during ++ prism construction and how creation of distorted and intersecting prisms is ++ prevented. Possible values are: ++ ++ - StdMeshers.SURF_OFFSET_SMOOTH (default) method extrudes nodes along normal ++ to underlying geometrical surface. Smoothing of internal surface of ++ element layers can be used to avoid creation of invalid prisms. ++ - StdMeshers.FACE_OFFSET method extrudes nodes along average normal of ++ surrounding mesh faces till intersection with a neighbor mesh face ++ translated along its own normal by the layers thickness. Thickness ++ of layers can be limited to avoid creation of invalid prisms. ++ - StdMeshers.NODE_OFFSET method extrudes nodes along average normal of ++ surrounding mesh faces by the layers thickness. Thickness of ++ layers can be limited to avoid creation of invalid prisms. ++ """ + if not isinstance(self.algo, SMESH._objref_SMESH_3D_Algo): - raise TypeError, "ViscousLayers are supported by 3D algorithms only" + raise TypeError("ViscousLayers are supported by 3D algorithms only") if not "ViscousLayers" in self.GetCompatibleHypothesis(): - raise TypeError, "ViscousLayers are not supported by %s"%self.algo.GetName() + raise TypeError("ViscousLayers are not supported by %s"%self.algo.GetName()) if faces and isinstance( faces, geomBuilder.GEOM._objref_GEOM_Object ): faces = [ faces ] if faces and isinstance( faces[0], geomBuilder.GEOM._objref_GEOM_Object ): @@@ -349,28 -308,24 +349,28 @@@ self.mesh.AddHypothesis( hyp, self.geom ) return hyp - ## Defines "ViscousLayers2D" hypothesis to give parameters of layers of quadrilateral - # elements to build near mesh boundary. This hypothesis can be used by several 2D algorithms: - # NETGEN 2D, NETGEN 1D-2D, Quadrangle (mapping), MEFISTO, MG-CADSurf - # @param thickness total thickness of layers of quadrilaterals - # @param numberOfLayers number of layers - # @param stretchFactor factor (>1.0) of growth of layer thickness towards inside of mesh - # @param edges list of geometrical edges (or their ids). - # Viscous layers are either generated on these edges or not, depending on - # the value of \a isEdgesToIgnore parameter. - # @param isEdgesToIgnore if \c True, the Viscous layers are not generated on the - # edges specified by the previous parameter (\a edges). - # @ingroup l3_hypos_additi def ViscousLayers2D(self, thickness, numberOfLayers, stretchFactor, edges=[], isEdgesToIgnore=True ): - """ - Defines "ViscousLayers2D" hypothesis to give parameters of layers of quadrilateral - elements to build near mesh boundary. This hypothesis can be used by several 2D algorithms: - NETGEN 2D, NETGEN 1D-2D, Quadrangle (mapping), MEFISTO, MG-CADSurf - - Parameters: - thickness: total thickness of layers of quadrilaterals - numberOfLayers: number of layers - stretchFactor: factor (>1.0) of growth of layer thickness towards inside of mesh - edges: list of geometrical edges (or their ids). - Viscous layers are either generated on these edges or not, depending on - the value of **isEdgesToIgnore** parameter. - isEdgesToIgnore: if *True*, the Viscous layers are not generated on the - edges specified by the previous parameter (**edges**). - """ ++ """ ++ Defines "ViscousLayers2D" hypothesis to give parameters of layers of quadrilateral ++ elements to build near mesh boundary. This hypothesis can be used by several 2D algorithms: ++ NETGEN 2D, NETGEN 1D-2D, Quadrangle (mapping), MEFISTO, MG-CADSurf ++ ++ Parameters: ++ thickness: total thickness of layers of quadrilaterals ++ numberOfLayers: number of layers ++ stretchFactor: factor (>1.0) of growth of layer thickness towards inside of mesh ++ edges: list of geometrical edges (or their ids). ++ Viscous layers are either generated on these edges or not, depending on ++ the value of **isEdgesToIgnore** parameter. ++ isEdgesToIgnore: if *True*, the Viscous layers are not generated on the ++ edges specified by the previous parameter (**edges**). ++ """ + if not isinstance(self.algo, SMESH._objref_SMESH_2D_Algo): - raise TypeError, "ViscousLayers2D are supported by 2D algorithms only" + raise TypeError("ViscousLayers2D are supported by 2D algorithms only") if not "ViscousLayers2D" in self.GetCompatibleHypothesis(): - raise TypeError, "ViscousLayers2D are not supported by %s"%self.algo.GetName() + raise TypeError("ViscousLayers2D are not supported by %s"%self.algo.GetName()) if edges and not isinstance( edges, list ) and not isinstance( edges, tuple ): edges = [edges] if edges and isinstance( edges[0], geomBuilder.GEOM._objref_GEOM_Object ): @@@ -390,12 -345,10 +390,12 @@@ self.mesh.AddHypothesis( hyp, self.geom ) return hyp - ## Transform a list of either edges or tuples (edge, 1st_vertex_of_edge) - # into a list acceptable to SetReversedEdges() of some 1D hypotheses - # @ingroup l3_hypos_1dhyps def ReversedEdgeIndices(self, reverseList): - """ - Transform a list of either edges or tuples (edge, 1st_vertex_of_edge) - into a list acceptable to SetReversedEdges() of some 1D hypotheses - """ ++ """ ++ Transform a list of either edges or tuples (edge, 1st_vertex_of_edge) ++ into a list acceptable to SetReversedEdges() of some 1D hypotheses ++ """ + from salome.smesh.smeshBuilder import FirstVertexOnCurve resList = [] geompy = self.mesh.geompyD diff --cc src/SMESH_SWIG_WITHIHM/libSMESH_Swig.cxx index 99a369897,a5a5dfe01..e33be0832 --- a/src/SMESH_SWIG_WITHIHM/libSMESH_Swig.cxx +++ b/src/SMESH_SWIG_WITHIHM/libSMESH_Swig.cxx @@@ -102,1645 -69,839 +102,1619 @@@ #include #include -static CORBA::ORB_var anORB; - namespace { - //--------------------------------------------------------------- - inline - CORBA::Object_var - StringToObject(const std::string& theIOR) + /////////////////////////////////////////////////////////////// + /// \internal + /// \brief Print deprecation warning to termninal. + /// \param function Interface function's name. + /// \param replacement Replacement (new) function's name + /// (if there's any). + /////////////////////////////////////////////////////////////// + void deprecated(const char* function, const char* replacement = 0) { - return anORB->string_to_object(theIOR.c_str()); + if ( replacement ) + printf("libSMESH_Swig: method '%s' is deprecated; use '%s' instead.\n", function, replacement); + else + printf("libSMESH_Swig: method '%s' is deprecated.\n", function); } + /////////////////////////////////////////////////////////////// + /// \internal + /// \brief Get CORBA object by its IOR. + /// \param ior Object's IOR. + /// \return CORBA object (nil object if it isn't found). + /////////////////////////////////////////////////////////////// + CORBA::Object_var string2object(const std::string& ior) + { + return SalomeApp_Application::orb()->string_to_object(ior.c_str()); + } - //--------------------------------------------------------------- - inline - SALOMEDS::SObject_var - GetDomainRoot(const SALOMEDS::SComponent_var& theSComponentMesh, - const SALOMEDS::StudyBuilder_var& theStudyBuilder, - CORBA::Long theDomainRootTag, - const QString& theName, - const QString& thePixmap) + /////////////////////////////////////////////////////////////// + /// \internal + /// \brief Get study object by its study UID or IOR. - /// \param studyId Study UID. + /// \param uid Object's study UID or IOR. + /// \return Pointer to study object (null object if it isn't + /// found). + /////////////////////////////////////////////////////////////// - _PTR(SObject) uid2object(int studyId, const std::string& uid) ++ _PTR(SObject) uid2object(const std::string& uid) { - SALOMEDS::SObject_var aDomainRoot; - if (!theSComponentMesh->FindSubObject(theDomainRootTag,aDomainRoot)) { - aDomainRoot = theStudyBuilder->NewObjectToTag(theSComponentMesh,theDomainRootTag); - SALOMEDS::GenericAttribute_var anAttr = theStudyBuilder->FindOrCreateAttribute(aDomainRoot,"AttributeName"); - SALOMEDS::AttributeName_var aName = SALOMEDS::AttributeName::_narrow(anAttr); - aName->SetValue(theName.toLatin1().data()); - aName->UnRegister(); - anAttr = theStudyBuilder->FindOrCreateAttribute(aDomainRoot,"AttributePixMap"); - SALOMEDS::AttributePixMap_var aPixmap = SALOMEDS::AttributePixMap::_narrow(anAttr); - aPixmap->SetPixMap(thePixmap.toLatin1().data()); - aPixmap->UnRegister(); - anAttr = theStudyBuilder->FindOrCreateAttribute(aDomainRoot,"AttributeSelectable"); - SALOMEDS::AttributeSelectable_var aSelAttr = SALOMEDS::AttributeSelectable::_narrow(anAttr); - aSelAttr->SetSelectable(false); - aSelAttr->UnRegister(); + _PTR(SObject) sobject; - if ( studyId > 0 ) + { - _PTR(Study) study = SalomeApp_Application::studyMgr()->GetStudyByID( studyId ); ++ _PTR(Study) study = SMESH::getStudy(); + if ( study ) + { + sobject = study->FindObjectID( uid ); + if ( !sobject ) + sobject = study->FindObjectIOR( uid ); + } } - - return aDomainRoot; + return sobject; } - - //--------------------------------------------------------------- - inline - SALOMEDS::SObject_var - GetHypothesisRoot(const SALOMEDS::SComponent_var& theSComponentMesh, - const SALOMEDS::StudyBuilder_var& theStudyBuilder) + /////////////////////////////////////////////////////////////// + /// \internal + /// \brief Get view window by its identifier. + /// \param uid Window's identifier. + /// \return Pointer to the view window (0 if it isn't found). + /////////////////////////////////////////////////////////////// + SALOME_View* uid2wnd(int uid, bool create = false) { - return GetDomainRoot(theSComponentMesh, - theStudyBuilder, - SMESH::Tag_HypothesisRoot, - QObject::tr("SMESH_MEN_HYPOTHESIS"), - "ICON_SMESH_TREE_HYPO"); - } + SALOME_View* window = 0; + SUIT_Session* session = SUIT_Session::session(); + SalomeApp_Application* app = dynamic_cast( session->activeApplication() ); + if ( app ) + { + if ( uid ) + { + ViewManagerList vms = app->viewManagers(); + for ( int i = 0; i < vms.count() && !window; i++ ) + { + SUIT_ViewManager* vm = vms[i]; + QVector vws = vm->getViews(); + for ( int j = 0; j < vws.count() && !window; j++) + { + SUIT_ViewWindow* vw = vws[0]; + if ( uid == vw->getId() ) + window = dynamic_cast( vm->getViewModel() ); + } + } + } + else + { + SUIT_ViewManager* vm = app->getViewManager( SVTK_Viewer::Type(), create ); + if ( vm ) + { + window = dynamic_cast( vm->getViewModel() ); + } + } + } + return window; + } - //--------------------------------------------------------------- - inline - SALOMEDS::SObject_var - GetAlgorithmsRoot(const SALOMEDS::SComponent_var& theSComponentMesh, - const SALOMEDS::StudyBuilder_var& theStudyBuilder) + /////////////////////////////////////////////////////////////// + /// \internal + /// \brief Get all view windows. + /// \return List of view windows. + /////////////////////////////////////////////////////////////// + QList windows() { - return GetDomainRoot(theSComponentMesh, - theStudyBuilder, - SMESH::Tag_AlgorithmsRoot, - QObject::tr("SMESH_MEN_ALGORITHMS"), - "ICON_SMESH_TREE_ALGO"); + QList views; + SUIT_Session* session = SUIT_Session::session(); + SalomeApp_Application* app = dynamic_cast( session->activeApplication() ); + if ( app ) + { + ViewManagerList vms = app->viewManagers(); + foreach( SUIT_ViewManager* vm, vms ) + { + if ( vm && vm->getType() == SVTK_Viewer::Type() ) + { + SALOME_View* view = dynamic_cast( vm->getViewModel() ); + if ( view ) + views << view; + } + } + } + return views; } - - //--------------------------------------------------------------- - inline - SALOMEDS::SObject_var - AddToDomain(const std::string& theIOR, - const SALOMEDS::SComponent_var& theSComponentMesh, - const SALOMEDS::StudyBuilder_var& theStudyBuilder, - CORBA::Long theDomainRootTag, - const QString& theDomainName, - const QString& theDomainPixmap) + /////////////////////////////////////////////////////////////// + /// \internal + /// \brief Get mesh actor from view. + /// \param view Pointer to the view window. + /// \param uid Mesh object's study UID. + /// \return Mesh actor (0 if it isn't found). + /////////////////////////////////////////////////////////////// + SMESH_Actor* actorFromView(SALOME_View* view, const char* uid) { - SALOMEDS::SObject_var aDomain = GetDomainRoot(theSComponentMesh, - theStudyBuilder, - SMESH::Tag_AlgorithmsRoot, - theDomainName, - theDomainPixmap); - // Add New Hypothesis - SALOMEDS::SObject_var aSObject = theStudyBuilder->NewObject(aDomain); - aDomain->UnRegister(); - SALOMEDS::GenericAttribute_var anAttr = theStudyBuilder->FindOrCreateAttribute(aSObject,"AttributePixMap"); - SALOMEDS::AttributePixMap_var aPixmap = SALOMEDS::AttributePixMap::_narrow(anAttr); - CORBA::Object_var anObject = StringToObject(theIOR); - SMESH::SMESH_Hypothesis_var aDomainItem = SMESH::SMESH_Hypothesis::_narrow(anObject.in()); - CORBA::String_var aType = aDomainItem->GetName(); - QString aPixmapName = theDomainPixmap + "_" + aType.in(); - aPixmap->SetPixMap(aPixmapName.toLatin1().data()); - aPixmap->UnRegister(); - anAttr = theStudyBuilder->FindOrCreateAttribute(aSObject,"AttributeIOR"); - SALOMEDS::AttributeIOR_var anIOR = SALOMEDS::AttributeIOR::_narrow(anAttr); - anIOR->SetValue(theIOR.c_str()); - anIOR->UnRegister(); - - return aSObject; + SMESH_Actor* actor = 0; + SVTK_Viewer* model = dynamic_cast( view ); + if ( model ) + { + SUIT_ViewWindow* vw = model->getViewManager()->getActiveView(); + if ( vw ) + { + actor = SMESH::FindActorByEntry( vw, uid ); + } + } + return actor; } - - //--------------------------------------------------------------- - SALOMEDS::SObject_var - AddHypothesis(const std::string& theIOR, - const SALOMEDS::SComponent_var& theSComponentMesh, - const SALOMEDS::StudyBuilder_var& theStudyBuilder) + /////////////////////////////////////////////////////////////// + /// \internal + /// \brief Get mesh object's visual properties. + /// \param view Pointer to the view window. + /// \param uid Mesh object's study UID. + /// \return Properties data structure. + /////////////////////////////////////////////////////////////// + Properties properties(SALOME_View* view, const char* uid) { - return AddToDomain(theIOR, - theSComponentMesh, - theStudyBuilder, - SMESH::Tag_HypothesisRoot, - QObject::tr("SMESH_MEN_HYPOTHESIS"), - "ICON_SMESH_TREE_HYPO"); + Properties props; + SMESH_Actor* actor = actorFromView( view, uid ); + if ( actor ) + { + actor->GetNodeColor( props.nodeColor.r, + props.nodeColor.g, + props.nodeColor.b ); + props.markerType = actor->GetMarkerType(); + props.markerScale = actor->GetMarkerScale(); + + actor->GetEdgeColor( props.edgeColor.r, + props.edgeColor.g, + props.edgeColor.b ); + props.edgeWidth = qMax( (int)actor->GetLineWidth(), 1 ); + + actor->GetSufaceColor( props.surfaceColor.r, + props.surfaceColor.g, + props.surfaceColor.b, + props.surfaceColor.delta ); + + actor->GetVolumeColor( props.volumeColor.r, + props.volumeColor.g, + props.volumeColor.b, + props.volumeColor.delta ); + + actor->Get0DColor( props.elem0dColor.r, + props.elem0dColor.g, + props.elem0dColor.b ); + props.elem0dSize = qMax( (int)actor->Get0DSize(), 1 ); + + actor->GetBallColor( props.ballColor.r, + props.ballColor.g, + props.ballColor.b ); + props.ballScale = qMax( actor->GetBallScale(), 1e-2 ); + + actor->GetOutlineColor( props.outlineColor.r, + props.outlineColor.g, + props.outlineColor.b ); + props.outlineWidth = qMax( (int)actor->GetOutlineWidth(), 1 ); + + actor->GetFacesOrientationColor( props.orientationColor.r, + props.orientationColor.g, + props.orientationColor.b ); + props.orientationScale = actor->GetFacesOrientationScale(); + props.orientation3d = actor->GetFacesOrientation3DVectors(); + + props.shrinkFactor = actor->GetShrinkFactor(); + + props.opacity = actor->GetOpacity(); + } + return props; } - - //--------------------------------------------------------------- - SALOMEDS::SObject_var - AddAlgorithms(const std::string& theIOR, - const SALOMEDS::SComponent_var& theSComponentMesh, - const SALOMEDS::StudyBuilder_var& theStudyBuilder) + /////////////////////////////////////////////////////////////// + /// \internal + /// \brief Set mesh object's visual properties. + /// \param view Pointer to the view window. + /// \param uid Mesh object's study UID. + /// \param props Properties data structure. + /////////////////////////////////////////////////////////////// + void setProperties(SALOME_View* view, const char* uid, const Properties& props) { - return AddToDomain(theIOR, - theSComponentMesh, - theStudyBuilder, - SMESH::Tag_AlgorithmsRoot, - QObject::tr("SMESH_MEN_ALGORITHMS"), - "ICON_SMESH_TREE_ALGO"); + SMESH_Actor* actor = actorFromView( view, uid ); + if ( actor ) + { + actor->SetNodeColor( props.nodeColor.r, + props.nodeColor.g, + props.nodeColor.b ); + if ( props.markerType != VTK::MT_USER ) + actor->SetMarkerStd( props.markerType, props.markerScale ); + + actor->SetEdgeColor( props.edgeColor.r, + props.edgeColor.g, + props.edgeColor.b ); + actor->SetLineWidth( qMax( (double)props.edgeWidth, 1. ) ); + + actor->SetSufaceColor( props.surfaceColor.r, + props.surfaceColor.g, + props.surfaceColor.b, + props.surfaceColor.delta ); + + actor->SetVolumeColor( props.volumeColor.r, + props.volumeColor.g, + props.volumeColor.b, + props.volumeColor.delta ); + + actor->Set0DColor( props.elem0dColor.r, + props.elem0dColor.g, + props.elem0dColor.b ); + actor->Set0DSize( qMax( (double)props.elem0dSize, 1. ) ); + + actor->SetBallColor( props.ballColor.r, + props.ballColor.g, + props.ballColor.b ); + actor->SetBallScale( qMax( props.ballScale, 1e-2 ) ); + + actor->SetOutlineColor( props.outlineColor.r, + props.outlineColor.g, + props.outlineColor.b ); + actor->SetOutlineWidth( qMax( (double)props.outlineWidth, 1. ) ); + + actor->SetFacesOrientationColor( props.orientationColor.r, + props.orientationColor.g, + props.orientationColor.b ); + actor->SetFacesOrientationScale( props.orientationScale ); + actor->SetFacesOrientation3DVectors( props.orientation3d ); + + actor->SetShrinkFactor( props.shrinkFactor ); + + actor->SetOpacity( props.opacity ); + + view->Repaint(); + } } +} // end of anonymous namespace + +///////////////////////////////////////////////////////////////// +/// \enum EntityMode +/// \brief Enumeration for mesh entities. +/// \var EntityMode Entity0d +/// \brief 0D elements. +/// \var EntityMode EntityEdges +/// \brief Edges. +/// \var EntityMode EntityFaces +/// \brief Faces. +/// \var EntityMode EntityVolumes +/// \brief Volumes. +/// \var EntityMode EntityBalls +/// \brief Ball elements. +/// \var EntityMode EntityAll +/// \brief All elements. +///////////////////////////////////////////////////////////////// + +///////////////////////////////////////////////////////////////// +/// \enum SelectionMode +/// \brief Selection mode. +/// \var SelectionMode Undefined +/// \brief Undefined selection mode. +/// \var SelectionMode Node +/// \brief Selection of mesh nodes. +/// \var SelectionMode Cell +/// \brief Selection of any mesh cells. +/// \var SelectionMode EdgeOfCell +/// \brief Selection of pseudo-edges specified by couple of nodes. +/// \var SelectionMode Edge +/// \brief Selection of edges. +/// \var SelectionMode Face +/// \brief Selection of faces. +/// \var SelectionMode Volume +/// \brief Selection of volumes +/// \var SelectionMode Actor +/// \brief Selection of whole actors (meshes, sub-meshes, groups). +/// \var SelectionMode Elem0D +/// \brief Selection of 0D elements. +/// \var SelectionMode Ball +/// \brief Selection of ball ellements. +///////////////////////////////////////////////////////////////// + +///////////////////////////////////////////////////////////////// +/// \enum DisplayMode +/// \brief Display mode. +/// \var DisplayMode UndefinedMode +/// \brief Undefined display mode. +/// \var DisplayMode PointMode +/// \brief Point representation. +/// \var DisplayMode EdgeMode +/// \brief Wireframe representation. +/// \var DisplayMode SurfaceMode +/// \brief Surface representation. +///////////////////////////////////////////////////////////////// + +///////////////////////////////////////////////////////////////// +/// \struct ColorData +/// \brief Color data, in RGBf format. +/// \var ColorData::r +/// \brief Red color's component (0.0:1.0). +/// \var ColorData::g +/// \brief Green color's component (0.0:1.0). +/// \var ColorData::b +/// \brief Blue color's component (0.0:1.0). +///////////////////////////////////////////////////////////////// + +///////////////////////////////////////////////////////////////// +/// \brief Constructor. +///////////////////////////////////////////////////////////////// +ColorData::ColorData() + : r( 0 ), g( 0 ), b( 0 ) +{} + +///////////////////////////////////////////////////////////////// +/// \struct BicolorData +/// \brief Bi-color data, in RGBf format. +/// \var BicolorData::r +/// \brief Red color's component (0.0:1.0). +/// \var BicolorData::g +/// \brief Green color's component (0.0:1.0). +/// \var BicolorData::b +/// \brief Blue color's component (0.0:1.0). +/// \var BicolorData::delta +/// \brief Shift for backface color (-100:100). +///////////////////////////////////////////////////////////////// + +///////////////////////////////////////////////////////////////// +/// \brief Constructor. +///////////////////////////////////////////////////////////////// +BicolorData::BicolorData() + : r( 0 ), g( 0 ), b( 0 ), delta( 0 ) +{} + +///////////////////////////////////////////////////////////////// +/// \struct Properties +/// \brief Mesh object presentation's properties. +/// \var Properties::nodeColor +/// \brief Node color. +/// \var Properties::markerType +/// \brief Node standard marker type. +/// \var Properties::markerScale +/// \brief Node scale factor. +/// \var Properties::edgeColor +/// \brief Edges color. +/// \var Properties::edgeWidth +/// \brief Edges width. +/// \var Properties::surfaceColor +/// \brief Faces color. +/// \var Properties::volumeColor +/// \brief Volumes color. +/// \var Properties::elem0dColor +/// \brief 0D elements color. +/// \var Properties::elem0dSize +/// \brief 0D elements size. +/// \var Properties::ballColor +/// \brief Ball elements color. +/// \var Properties::ballScale +/// \brief Ball elements scale factor. +/// \var Properties::outlineColor +/// \brief Outlines color. +/// \var Properties::outlineWidth +/// \brief Outlines width. +/// \var Properties::orientationColor +/// \brief Face orientation vectors color. +/// \var Properties::orientationScale +/// \brief Face orientation vectors scale factor. +/// \var Properties::orientation3d +/// \brief Face orientation vectors 3d flag. +/// \var Properties::shrinkFactor +/// \brief Shrink coefficient. +/// \var Properties::opacity +/// \brief Opacity. +///////////////////////////////////////////////////////////////// + +///////////////////////////////////////////////////////////////// +/// \brief Constructor. +///////////////////////////////////////////////////////////////// +Properties::Properties() + : markerType( VTK::MT_NONE ), markerScale( VTK::MS_NONE ), + edgeWidth( 1 ), elem0dSize( 1 ), ballScale( 1 ), outlineWidth( 1 ), + orientationScale( 0 ), orientation3d( false ), shrinkFactor( 0 ), + opacity( 1 ) +{} + +///////////////////////////////////////////////////////////////// +/// \typedef nodeColorStruct +/// \deprecated Use ColorData instead. +/// \typedef edgeColorStruct +/// \deprecated Use ColorData instead. +/// \typedef surfaceColorStruct +/// \deprecated Use BicolorData instead. +/// \typedef volumeColorStruct +/// \deprecated Use BicolorData instead. +/// \typedef actorAspect +/// \deprecated Use Properties instead. +///////////////////////////////////////////////////////////////// + +///////////////////////////////////////////////////////////////// +/// \class SMESH_Swig +/// \brief %SMESH GUI Python interface. +///////////////////////////////////////////////////////////////// + +///////////////////////////////////////////////////////////////// +/// \brief Constructor. +///////////////////////////////////////////////////////////////// +SMESH_Swig::SMESH_Swig() - : myCachedStudyId( 0 ) +{ + init(); +} +///////////////////////////////////////////////////////////////// +/// \brief Destructor. +///////////////////////////////////////////////////////////////// +SMESH_Swig::~SMESH_Swig() +{ +} - //--------------------------------------------------------------- - void - SetDomain(const char* theMeshOrSubMeshEntry, - const char* theDomainEntry, - const SALOMEDS::StudyBuilder_var& theStudyBuilder, - long theRefOnAppliedDomainTag, - const QString& theAppliedDomainMEN, - const QString& theAppliedDomainICON) +///////////////////////////////////////////////////////////////// +/// \internal +/// \brief Initialize interface. +///////////////////////////////////////////////////////////////// +void SMESH_Swig::init() +{ + class TInitEvent: public SALOME_Event { - SALOMEDS::SObject_var aMeshOrSubMeshSO = KERNEL::getStudyServant()->FindObjectID(theMeshOrSubMeshEntry); - SALOMEDS::SObject_var aHypothesisSO = KERNEL::getStudyServant()->FindObjectID(theDomainEntry); + public: + TInitEvent() {} + virtual void Execute() + { + SUIT_Session* session = SUIT_Session::session(); + SalomeApp_Application* app = dynamic_cast( session->activeApplication() ); - if(!aMeshOrSubMeshSO->_is_nil() && !aHypothesisSO->_is_nil()){ - //Find or Create Applied Hypothesis root - SALOMEDS::SObject_var anAppliedDomainSO; - if( !aMeshOrSubMeshSO->FindSubObject( theRefOnAppliedDomainTag, anAppliedDomainSO )) - { - anAppliedDomainSO = theStudyBuilder->NewObjectToTag(aMeshOrSubMeshSO,theRefOnAppliedDomainTag); - SALOMEDS::GenericAttribute_var anAttr = - theStudyBuilder->FindOrCreateAttribute(anAppliedDomainSO,"AttributeName"); - SALOMEDS::AttributeName_var aName = SALOMEDS::AttributeName::_narrow(anAttr); - aName->SetValue(theAppliedDomainMEN.toLatin1().data()); - aName->UnRegister(); - anAttr = theStudyBuilder->FindOrCreateAttribute(anAppliedDomainSO,"AttributeSelectable"); - SALOMEDS::AttributeSelectable_var aSelAttr = SALOMEDS::AttributeSelectable::_narrow(anAttr); - aSelAttr->SetSelectable(false); - aSelAttr->UnRegister(); - anAttr = theStudyBuilder->FindOrCreateAttribute(anAppliedDomainSO,"AttributePixMap"); - SALOMEDS::AttributePixMap_var aPixmap = SALOMEDS::AttributePixMap::_narrow(anAttr); - aPixmap->SetPixMap(theAppliedDomainICON.toLatin1().data()); - aPixmap->UnRegister(); - } - SALOMEDS::SObject_var aSObject = theStudyBuilder->NewObject(anAppliedDomainSO); - theStudyBuilder->Addreference(aSObject,aHypothesisSO); - aSObject->UnRegister(); - anAppliedDomainSO->UnRegister(); + if ( !SMESHGUI::GetSMESHGUI() ) + app->loadModule( "Mesh" ); } - if ( !aMeshOrSubMeshSO->_is_nil() ) aMeshOrSubMeshSO->UnRegister(); - if ( !aHypothesisSO->_is_nil()) aHypothesisSO->UnRegister(); - } + }; + // load SMESH GUI if it's not yet loaded + ProcessVoidEvent( new TInitEvent() ); - - // set current study - std::vector studies = SalomeApp_Application::studyMgr()->GetOpenStudies(); - if ( studies.size() > 0 ) - { - _PTR(Study) study = SalomeApp_Application::studyMgr()->GetStudyByName( studies[0] ); - int studyId = study->StudyId(); - if ( myCachedStudyId != studyId ) - { - myCachedStudyId = studyId; - SMESHGUI::GetSMESHGen()->SetCurrentStudy( _CAST(Study, study)->GetStudy() ); - } - } - else - { - myCachedStudyId = 0; - } ++ SMESHGUI::GetSMESHGen()->UpdateStudy(); +} - //--------------------------------------------------------------- - void - SetHypothesis(const char* theMeshOrSubMeshEntry, - const char* theDomainEntry, - const SALOMEDS::StudyBuilder_var& theStudyBuilder) - { - SetDomain(theMeshOrSubMeshEntry, - theDomainEntry, - theStudyBuilder, - SMESH::Tag_RefOnAppliedHypothesis, - QObject::tr("SMESH_MEN_APPLIED_HYPOTHESIS"), - "ICON_SMESH_TREE_HYPO"); - } +///////////////////////////////////////////////////////////////// +/// \brief Publish object. +/// \param ior IOR of the mesh object to publish. +/// \param name Study name of the object; if not given, +/// name is assigned automatically. +/// \return UID of the data object. +///////////////////////////////////////////////////////////////// +const char* SMESH_Swig::publish(const char* ior, const char* name) +{ + init(); + std::string uid; - - if ( myCachedStudyId > 0 ) - { - _PTR(Study) study = SalomeApp_Application::studyMgr()->GetStudyByID( myCachedStudyId ); - CORBA::Object_var object = string2object( ior ); - if ( study && !CORBA::is_nil( object ) ) ++ CORBA::Object_var object = string2object( ior ); ++ if ( !CORBA::is_nil( object ) ) + { + SALOMEDS::SObject_var sobject = - SMESHGUI::GetSMESHGen()->PublishInStudy( _CAST(Study, study)->GetStudy(), - SALOMEDS::SObject::_nil(), ++ SMESHGUI::GetSMESHGen()->PublishInStudy( SALOMEDS::SObject::_nil(), + object.in(), + name ); + if ( !CORBA::is_nil( sobject ) ) - { - uid = sobject->GetID(); - } ++ { ++ uid = sobject->GetID(); ++ } + sobject->UnRegister(); + } - } - //--------------------------------------------------------------- - void - SetAlgorithms(const char* theMeshOrSubMeshEntry, - const char* theDomainEntry, - const SALOMEDS::StudyBuilder_var& theStudyBuilder) - { - SetDomain(theMeshOrSubMeshEntry, - theDomainEntry, - theStudyBuilder, - SMESH::Tag_RefOnAppliedAlgorithms, - QObject::tr("SMESH_MEN_APPLIED_ALGORIHTMS"), - "ICON_SMESH_TREE_ALGO"); - } + return strdup( uid.c_str() ); } +///////////////////////////////////////////////////////////////// +/// \brief Set new study name of given object. +/// \param uid Object's study UID or IOR. +/// \param name New name of the object. +///////////////////////////////////////////////////////////////// +void SMESH_Swig::rename(const char* uid, const char* name) +{ + init(); - _PTR(SObject) sobject = uid2object( myCachedStudyId, uid ); -//=============================================================== -SMESH_Swig::SMESH_Swig() ++ _PTR(SObject) sobject = uid2object( uid ); + if ( sobject ) + sobject->SetAttrString( "AttributeName", name ); +} + +///////////////////////////////////////////////////////////////// +/// \brief Display mesh object. +/// \param uid Object's study UID or IOR. +/// \param viewUid View window UID (0 means currently active view +/// window; if there's no view, it is created). +/// Default: 0. +/// \param updateViewer "Update view" flag. Default: \c true. +///////////////////////////////////////////////////////////////// +void SMESH_Swig::display(const char* uid, int viewUid, bool updateViewer) { - class TEvent: public SALOME_Event + class TDisplayEvent: public SALOME_Event { - CORBA::ORB_var& myORB; + private: + const char* myUid; + int myViewUid; + bool myIsUpdate; public: + TDisplayEvent(const char* uid, int viewUid, bool updateViewer) + : myUid( uid ), myViewUid( viewUid ), myIsUpdate( updateViewer ) {} + virtual void Execute() + { + SALOME_View* view = uid2wnd( myViewUid, true ); // create view if it's not present + if ( view ) + LightApp_Displayer::FindDisplayer( "Mesh", true )->Display( myUid, myIsUpdate, view ); + } + }; + + init(); - _PTR(SObject) sobject = uid2object( myCachedStudyId, uid ); - TEvent(CORBA::ORB_var& theORB): - myORB(theORB) - {} ++ _PTR(SObject) sobject = uid2object( uid ); + if ( sobject ) + ProcessVoidEvent( new TDisplayEvent( sobject->GetID().c_str(), viewUid, updateViewer ) ); +} - virtual - void - Execute() +///////////////////////////////////////////////////////////////// +/// \brief Erase mesh object. +/// \param uid Object's study UID or IOR. +/// \param viewUid View window UID (0 means currently active view +/// window); -1 means "all view windows". +/// Default: 0. +/// \param updateViewer "Update view" flag. Default: \c true. +///////////////////////////////////////////////////////////////// +void SMESH_Swig::erase(const char* uid, int viewUid, bool updateViewer) +{ + class TEraseEvent: public SALOME_Event + { + private: + const char* myUid; + int myViewUid; + bool myIsUpdate; + public: + TEraseEvent(const char* uid, int viewUid, bool updateViewer) + : myUid( uid ), myViewUid( viewUid ), myIsUpdate( updateViewer ) {} + virtual void Execute() { - try { - ORB_INIT &anORBInit = *SINGLETON_::Instance(); - ASSERT(SINGLETON_::IsAlreadyExisting()); - myORB = anORBInit( 0, 0 ); - } catch (...) { - INFOS("internal error : orb not found"); + if ( myViewUid == -1 ) + { + QList views = windows(); + foreach( SALOME_View* view, views ) + LightApp_Displayer::FindDisplayer( "Mesh", true )->Erase( myUid, true, myIsUpdate, view ); + } + else + { + SALOME_View* view = uid2wnd( myViewUid ); + if ( view ) + LightApp_Displayer::FindDisplayer( "Mesh", true )->Erase( myUid, true, myIsUpdate, view ); } } }; - //MESSAGE("Constructeur"); - - if(CORBA::is_nil(anORB)) - ProcessVoidEvent(new TEvent(anORB)); + init(); - _PTR(SObject) sobject = uid2object( myCachedStudyId, uid ); - ASSERT(!CORBA::is_nil(anORB)); ++ _PTR(SObject) sobject = uid2object( uid ); + if ( sobject ) + ProcessVoidEvent( new TEraseEvent( sobject->GetID().c_str(), viewUid, updateViewer ) ); } - -//=============================================================== -void -SMESH_Swig::Init() +///////////////////////////////////////////////////////////////// +/// \brief Update mesh object. +/// \param uid Object's study UID or IOR. +///////////////////////////////////////////////////////////////// +void SMESH_Swig::update(const char* uid) { - class TEvent: public SALOME_Event + class TUpdateEvent: public SALOME_Event { - SALOMEDS::StudyBuilder_var& myStudyBuilder; - SALOMEDS::SComponent_var& mySComponentMesh; + private: + const char* myUid; public: - TEvent(SALOMEDS::StudyBuilder_var& theStudyBuilder, - SALOMEDS::SComponent_var& theSComponentMesh): - myStudyBuilder (theStudyBuilder), - mySComponentMesh(theSComponentMesh) - {} - - ~TEvent() + TUpdateEvent( const char* uid ) : myUid( uid ) {} + virtual void Execute() { - if ( !mySComponentMesh->_is_nil() ) mySComponentMesh->UnRegister(); + Handle(SALOME_InteractiveObject) io = + new SALOME_InteractiveObject( myUid, "SMESH", "" ); + SMESH::Update( io, true ); } + }; - virtual - void - Execute() - { - SUIT_Session* aSession = SUIT_Session::session(); - SUIT_Application* anApplication = aSession->activeApplication(); - SalomeApp_Application* anApp = dynamic_cast(anApplication); - - SALOMEDS::Study_var aStudy = KERNEL::getStudyServant(); + init(); - _PTR(SObject) sobject = uid2object( myCachedStudyId, uid ); - SMESH::SMESH_Gen_var aSMESHGen = SMESHGUI::GetSMESHGen(); ++ _PTR(SObject) sobject = uid2object( uid ); + if ( sobject ) + ProcessVoidEvent( new TUpdateEvent( uid ) ); +} - myStudyBuilder = aStudy->NewBuilder(); +///////////////////////////////////////////////////////////////// +/// \internal +class TGetPropsEvent: public SALOME_Event +{ +public: + typedef Properties TResult; + TResult myResult; + const char* myUid; + int myViewUid; - SALOMEDS::GenericAttribute_var anAttr; - SALOMEDS::AttributeName_var aName; - SALOMEDS::AttributePixMap_var aPixmap; + TGetPropsEvent( const char* uid, int viewUid ) + : myUid( uid ), myViewUid( viewUid ) {} - SALOMEDS::SComponent_var aSComponent = aStudy->FindComponent("SMESH"); - if ( aSComponent->_is_nil() ) - { - bool aLocked = aStudy->GetProperties()->IsLocked(); - if (aLocked) - aStudy->GetProperties()->SetLocked(false); - - SMESHGUI* aSMESHGUI = SMESHGUI::GetSMESHGUI(); - //SRN: BugID IPAL9186, load a SMESH gui if it hasn't been loaded - if (!aSMESHGUI) { - CAM_Module* aModule = anApp->module("Mesh"); - if(!aModule) - aModule = anApp->loadModule("Mesh"); - aSMESHGUI = dynamic_cast(aModule); - } //SRN: BugID IPAL9186: end of a fix - - aSComponent = myStudyBuilder->NewComponent("SMESH"); - - anAttr = myStudyBuilder->FindOrCreateAttribute(aSComponent,"AttributeName"); - aName = SALOMEDS::AttributeName::_narrow(anAttr); - aName->SetValue(aSMESHGUI->moduleName().toLatin1().data()); - aName->UnRegister(); - - anAttr = myStudyBuilder->FindOrCreateAttribute(aSComponent,"AttributePixMap"); - aPixmap = SALOMEDS::AttributePixMap::_narrow(anAttr); - aPixmap->SetPixMap( "ICON_OBJBROWSER_SMESH" ); - aPixmap->UnRegister(); - - SALOMEDS::UseCaseBuilder_var useCaseBuilder = KERNEL::getStudyServant()->GetUseCaseBuilder(); - useCaseBuilder->SetRootCurrent(); - useCaseBuilder->Append( aSComponent.in() ); - - myStudyBuilder->DefineComponentInstance(aSComponent,aSMESHGen); - if (aLocked) - KERNEL::getStudyServant()->GetProperties()->SetLocked(true); - } + virtual void Execute() + { + SALOME_View* view = uid2wnd( myViewUid ); + myResult = properties( view, myUid ); + } +}; - mySComponentMesh = SALOMEDS::SComponent::_narrow(aSComponent); +///////////////////////////////////////////////////////////////// +/// \brief Get mesh object's visual properties. +/// \param uid Mesh object's study UID or IOR. +/// \param viewUid View window UID (0 means currently active view +/// window); Default: 0. +/// \return Properties data structure. +///////////////////////////////////////////////////////////////// +Properties SMESH_Swig::properties(const char* uid, int viewUid) +{ + Properties props; - qApp->processEvents(); // Workaround for bug 12662 - } - }; + init(); - _PTR(SObject) sobject = uid2object( myCachedStudyId, uid ); - //MESSAGE("Init"); ++ _PTR(SObject) sobject = uid2object( uid ); + if ( sobject ) + props = ProcessEvent( new TGetPropsEvent( sobject->GetID().c_str(), viewUid ) ); - ProcessVoidEvent(new TEvent(myStudyBuilder, - mySComponentMesh)); + return props; } +///////////////////////////////////////////////////////////////// +/// \internal +///////////////////////////////////////////////////////////////// +class TSetPropsEvent: public SALOME_Event +{ +public: + const char* myUid; + Properties myProps; + int myViewUid; -//=============================================================== -SMESH_Swig::~SMESH_Swig() + TSetPropsEvent( const char* uid, const Properties& props, int viewUid ) + : myUid( uid ), myProps( props), myViewUid( viewUid ) {} + + virtual void Execute() + { + if ( myViewUid == -1 ) + { + QList views = windows(); + foreach( SALOME_View* view, views ) + { + setProperties( view, myUid, myProps ); + } + } + else + { + SALOME_View* view = uid2wnd( myViewUid ); + setProperties( view, myUid, myProps ); + } + } +}; + +///////////////////////////////////////////////////////////////// +/// \brief Set mesh object's visual properties. +/// \param uid Mesh object's study UID or IOR. +/// \param props Properties data structure. +/// \param viewUid View window UID (0 means currently active view +/// window); Default: 0. +///////////////////////////////////////////////////////////////// +void SMESH_Swig::setProperties(const char* uid, const Properties& props, int viewUid) { - //MESSAGE("Destructeur"); -} + init(); - _PTR(SObject) sobject = uid2object( myCachedStudyId, uid ); ++ _PTR(SObject) sobject = uid2object( uid ); + if ( sobject ) + ProcessVoidEvent( new TSetPropsEvent( sobject->GetID().c_str(), props, viewUid ) ); +} -//=============================================================== -const char* SMESH_Swig::AddNewMesh(const char* theIOR) +///////////////////////////////////////////////////////////////// +/// \internal +///////////////////////////////////////////////////////////////// +class TGetNodeNumberingEvent: public SALOME_Event { +public: + typedef bool TResult; + TResult myResult; + const char* myUid; + int myViewUid; + + TGetNodeNumberingEvent( const char* uid, int viewUid ) + : myResult( false ), myUid( uid ), myViewUid( viewUid ) {} - // VSR: added temporarily - to be removed - objects are published automatically by engine - SALOMEDS::SObject_var aSObject = KERNEL::getStudyServant()->FindObjectIOR(theIOR); - if (aSObject->_is_nil()) + virtual void Execute() { - //Find or Create Hypothesis root - SALOMEDS::SObject_var hroot = GetHypothesisRoot(mySComponentMesh,myStudyBuilder); - SALOMEDS::SObject_var aroot = GetAlgorithmsRoot(mySComponentMesh,myStudyBuilder); - hroot->UnRegister(); - aroot->UnRegister(); - - // Add New Mesh - aSObject = myStudyBuilder->NewObject(mySComponentMesh); - SALOMEDS::GenericAttribute_var anAttr = myStudyBuilder->FindOrCreateAttribute(aSObject,"AttributePixMap"); - SALOMEDS::AttributePixMap_var aPixmap = SALOMEDS::AttributePixMap::_narrow(anAttr); - aPixmap->SetPixMap( "ICON_SMESH_TREE_MESH" ); - aPixmap->UnRegister(); - - anAttr = myStudyBuilder->FindOrCreateAttribute(aSObject, "AttributeIOR"); - SALOMEDS::AttributeIOR_var anIOR = SALOMEDS::AttributeIOR::_narrow(anAttr); - anIOR->SetValue(theIOR); - anIOR->UnRegister(); + SALOME_View* view = uid2wnd( myViewUid ); + SMESH_Actor* actor = actorFromView( view, myUid ); + if ( actor ) + myResult = actor->GetPointsLabeled(); } +}; + +///////////////////////////////////////////////////////////////// +/// \brief Check if nodes numbering is switched on. +/// \param uid Mesh object's study UID or IOR. +/// \param viewUid View window UID (0 means currently active view +/// window); Default: 0. +/// \return \c true if nodes numbering is switched on; +/// \c false otherwise. +///////////////////////////////////////////////////////////////// +bool SMESH_Swig::nodesNumbering(const char* uid, int viewUid) +{ + bool numbering = false; + + init(); - _PTR(SObject) sobject = uid2object( myCachedStudyId, uid ); - CORBA::String_var anEntry = aSObject->GetID(); - aSObject->UnRegister(); ++ _PTR(SObject) sobject = uid2object( uid ); + if ( sobject ) + numbering = ProcessEvent( new TGetNodeNumberingEvent( sobject->GetID().c_str(), viewUid ) ); - return anEntry._retn(); + return numbering; } +///////////////////////////////////////////////////////////////// +/// \internal +///////////////////////////////////////////////////////////////// +class TSetNodeNumberingEvent: public SALOME_Event +{ +public: + const char* myUid; + bool myNumbering; + int myViewUid; + + TSetNodeNumberingEvent( const char* uid, bool numbering, int viewUid ) + : myUid( uid ), myNumbering( numbering ), myViewUid( viewUid ) {} + + virtual void Execute() + { + SALOME_View* view = uid2wnd( myViewUid ); + SMESH_Actor* actor = actorFromView( view, myUid ); + if ( actor ) + { + actor->SetPointsLabeled( myNumbering ); + if ( view ) + view->Repaint(); + } + } +}; -//=============================================================== -const char* SMESH_Swig::AddNewHypothesis(const char* theIOR) +///////////////////////////////////////////////////////////////// +/// \brief Switch nodes numbering on/off. +/// \param uid Mesh object's study UID or IOR. +/// \param numbering \c true to switch nodes numbering on; +/// \c false otherwise. +/// \param viewUid View window UID (0 means currently active view +/// window); Default: 0. +///////////////////////////////////////////////////////////////// +void SMESH_Swig::setNodesNumbering(const char* uid, bool numbering, int viewUid) { - SALOMEDS::SObject_var aSObject = ::AddHypothesis(theIOR, - mySComponentMesh, - myStudyBuilder); - CORBA::String_var anEntry = aSObject->GetID(); - aSObject->UnRegister(); + init(); - _PTR(SObject) sobject = uid2object( myCachedStudyId, uid ); - return anEntry._retn(); ++ _PTR(SObject) sobject = uid2object( uid ); + if ( sobject ) + ProcessVoidEvent( new TSetNodeNumberingEvent( sobject->GetID().c_str(), numbering, viewUid ) ); } +///////////////////////////////////////////////////////////////// +/// \internal +///////////////////////////////////////////////////////////////// +class TGetElementNumberingEvent: public SALOME_Event +{ +public: + typedef bool TResult; + TResult myResult; + const char* myUid; + int myViewUid; -//=============================================================== -const char* SMESH_Swig::AddNewAlgorithms(const char* theIOR) + TGetElementNumberingEvent( const char* uid, int viewUid ) + : myResult( false ), myUid( uid ), myViewUid( viewUid ) {} + + virtual void Execute() + { + SALOME_View* view = uid2wnd( myViewUid ); + SMESH_Actor* actor = actorFromView( view, myUid ); + if ( actor ) + myResult = actor->GetCellsLabeled(); + } +}; + +///////////////////////////////////////////////////////////////// +/// \brief Check if elements numbering is switched on. +/// \param uid Mesh object's study UID or IOR. +/// \param viewUid View window UID (0 means currently active view +/// window); Default: 0. +/// \return \c true if elements numbering is switched on; +/// \c false otherwise. +///////////////////////////////////////////////////////////////// +bool SMESH_Swig::elementsNumbering(const char* uid, int viewUid) { - SALOMEDS::SObject_var aSObject = ::AddAlgorithms(theIOR, - mySComponentMesh, - myStudyBuilder); - CORBA::String_var anEntry = aSObject->GetID(); - aSObject->UnRegister(); + bool numbering = false; - return anEntry._retn(); -} + init(); + - _PTR(SObject) sobject = uid2object( myCachedStudyId, uid ); ++ _PTR(SObject) sobject = uid2object( uid ); + if ( sobject ) + numbering = ProcessEvent( new TGetElementNumberingEvent( sobject->GetID().c_str(), viewUid ) ); + return numbering; +} -//=============================================================== -void SMESH_Swig::SetShape(const char* theShapeEntry, - const char* theMeshEntry) +///////////////////////////////////////////////////////////////// +/// \internal +///////////////////////////////////////////////////////////////// +class TSetElementNumberingEvent: public SALOME_Event { - SALOMEDS::SObject_var aGeomShapeSO = KERNEL::getStudyServant()->FindObjectID( theShapeEntry ); - SALOMEDS::SObject_var aMeshSO = KERNEL::getStudyServant()->FindObjectID( theMeshEntry ); +public: + const char* myUid; + bool myNumbering; + int myViewUid; + + TSetElementNumberingEvent( const char* uid, bool numbering, int viewUid ) + : myUid( uid ), myNumbering( numbering ), myViewUid( viewUid ) {} - if(!aMeshSO->_is_nil() && !aGeomShapeSO->_is_nil()){ - SALOMEDS::SObject_var aSObject = myStudyBuilder->NewObjectToTag(aMeshSO, SMESH::Tag_RefOnShape); - myStudyBuilder->Addreference(aSObject,aGeomShapeSO); - aSObject->UnRegister(); + virtual void Execute() + { + SALOME_View* view = uid2wnd( myViewUid ); + SMESH_Actor* actor = actorFromView( view, myUid ); + if ( actor ) + { + actor->SetCellsLabeled( myNumbering ); + if ( view ) + view->Repaint(); + } } - if ( !aMeshSO->_is_nil() ) aMeshSO->UnRegister(); - if ( !aGeomShapeSO->_is_nil() ) aGeomShapeSO->UnRegister(); +}; + +///////////////////////////////////////////////////////////////// +/// \brief Switch elements numbering on/off. +/// \param uid Mesh object's study UID or IOR. +/// \param numbering \c true to switch elements numbering on; +/// \c false otherwise. +/// \param viewUid View window UID (0 means currently active view +/// window); Default: 0. +///////////////////////////////////////////////////////////////// +void SMESH_Swig::setElementsNumbering(const char* uid, bool numbering, int viewUid) +{ + init(); + - _PTR(SObject) sobject = uid2object( myCachedStudyId, uid ); ++ _PTR(SObject) sobject = uid2object( uid ); + if ( sobject ) + ProcessVoidEvent( new TSetElementNumberingEvent( sobject->GetID().c_str(), numbering, viewUid ) ); } +///////////////////////////////////////////////////////////////// +/// \internal +///////////////////////////////////////////////////////////////// +class TGetDisplayModeEvent: public SALOME_Event +{ +public: + typedef DisplayMode TResult; + TResult myResult; + const char* myUid; + int myViewUid; + + TGetDisplayModeEvent( const char* uid, int viewUid ) + : myResult( UndefinedMode ), myUid( uid ), myViewUid( viewUid ) {} -//=============================================================== -void SMESH_Swig::SetHypothesis(const char* theMeshOrSubMeshEntry, - const char* theDomainEntry) + virtual void Execute() + { + SALOME_View* view = uid2wnd( myViewUid ); + SMESH_Actor* actor = actorFromView( view, myUid ); + if ( actor ) + myResult = (DisplayMode)actor->GetRepresentation(); + } +}; + +///////////////////////////////////////////////////////////////// +/// \brief Get mesh object's display mode. +/// \param uid Mesh object's study UID or IOR. +/// \param viewUid View window UID (0 means currently active view +/// window); Default: 0. +/// \return Display mode (UndefinedMode if actor isn't found). +///////////////////////////////////////////////////////////////// +DisplayMode SMESH_Swig::displayMode(const char* uid, int viewUid) { - ::SetHypothesis(theMeshOrSubMeshEntry, - theDomainEntry, - myStudyBuilder); + DisplayMode mode = UndefinedMode; + + init(); + - _PTR(SObject) sobject = uid2object( myCachedStudyId, uid ); ++ _PTR(SObject) sobject = uid2object( uid ); + if ( sobject ) + mode = ProcessEvent( new TGetDisplayModeEvent( sobject->GetID().c_str(), viewUid ) ); + + return mode; } +///////////////////////////////////////////////////////////////// +/// \internal +///////////////////////////////////////////////////////////////// +class TSetDisplayModeEvent: public SALOME_Event +{ +public: + const char* myUid; + DisplayMode myMode; + int myViewUid; + + TSetDisplayModeEvent( const char* uid, DisplayMode mode, int viewUid ) + : myUid( uid ), myMode( mode), myViewUid( viewUid ) {} + + virtual void Execute() + { + SALOME_View* view = uid2wnd( myViewUid ); + SMESH_Actor* actor = actorFromView( view, myUid ); + if ( actor && myMode != UndefinedMode ) + { + actor->SetRepresentation( myMode ); + if ( view ) + view->Repaint(); + } + } +}; -//=============================================================== -void SMESH_Swig::SetAlgorithms(const char* theMeshOrSubMeshEntry, - const char* theDomainEntry) +///////////////////////////////////////////////////////////////// +/// \brief Set mesh object's display mode. +/// \param uid Mesh object's study UID or IOR. +/// \param mode Display mode. +/// \param viewUid View window UID (0 means currently active view +/// window); Default: 0. +///////////////////////////////////////////////////////////////// +void SMESH_Swig::setDisplayMode(const char* uid, DisplayMode mode, int viewUid) { - ::SetAlgorithms(theMeshOrSubMeshEntry, - theDomainEntry, - myStudyBuilder); + init(); + - _PTR(SObject) sobject = uid2object( myCachedStudyId, uid ); ++ _PTR(SObject) sobject = uid2object( uid ); + if ( sobject ) + ProcessVoidEvent( new TSetDisplayModeEvent( sobject->GetID().c_str(), mode, viewUid ) ); } +///////////////////////////////////////////////////////////////// +/// \internal +///////////////////////////////////////////////////////////////// +class TGetShrinkModeEvent: public SALOME_Event +{ +public: + typedef bool TResult; + TResult myResult; + const char* myUid; + int myViewUid; -//=============================================================== -void -SMESH_Swig::UnSetHypothesis(const char* theDomainEntry) + TGetShrinkModeEvent( const char* uid, int viewUid ) + : myResult( false ), myUid( uid ), myViewUid( viewUid ) {} + + virtual void Execute() + { + SALOME_View* view = uid2wnd( myViewUid ); + SMESH_Actor* actor = actorFromView( view, myUid ); + if ( actor ) + myResult = actor->IsShrunk(); + } +}; + +///////////////////////////////////////////////////////////////// +/// \brief Check if shrink mode is switched on. +/// \param uid Mesh object's study UID or IOR. +/// \param viewUid View window UID (0 means currently active view +/// window); Default: 0. +/// \return \c true if shrink mode is switched on; +/// \c false otherwise. +///////////////////////////////////////////////////////////////// +bool SMESH_Swig::shrinkMode(const char* uid, int viewUid) { - SALOMEDS::SObject_var aDomainSO = KERNEL::getStudyServant()->FindObjectID(theDomainEntry); - if(!aDomainSO->_is_nil()) - myStudyBuilder->RemoveObject(aDomainSO); + bool shrinkMode = false; + + init(); + - _PTR(SObject) sobject = uid2object( myCachedStudyId, uid ); ++ _PTR(SObject) sobject = uid2object( uid ); + if ( sobject ) + shrinkMode = ProcessEvent( new TGetShrinkModeEvent( sobject->GetID().c_str(), viewUid ) ); + + return shrinkMode; } -const char* SMESH_Swig::AddSubMesh(const char* theMeshEntry, - const char* theSubMeshIOR, - int theShapeType) -{ - SALOMEDS::SObject_var aMeshSO = KERNEL::getStudyServant()->FindObjectID(theMeshEntry); - if(!aMeshSO->_is_nil()) { - long aShapeTag; - QString aSubMeshName; - switch(theShapeType) { - case TopAbs_SOLID: - aShapeTag = SMESH::Tag_SubMeshOnSolid; - aSubMeshName = QObject::tr("SMESH_MEN_SubMeshesOnSolid"); - break; - case TopAbs_FACE: - aShapeTag = SMESH::Tag_SubMeshOnFace; - aSubMeshName = QObject::tr("SMESH_MEN_SubMeshesOnFace"); - break; - case TopAbs_EDGE: - aShapeTag = SMESH::Tag_SubMeshOnEdge; - aSubMeshName = QObject::tr("SMESH_MEN_SubMeshesOnEdge"); - break; - case TopAbs_VERTEX: - aShapeTag = SMESH::Tag_SubMeshOnVertex; - aSubMeshName = QObject::tr("SMESH_MEN_SubMeshesOnVertex"); - break; - default: - aShapeTag = SMESH::Tag_SubMeshOnCompound; - aSubMeshName = QObject::tr("SMESH_MEN_SubMeshesOnCompound"); - } +///////////////////////////////////////////////////////////////// +/// \internal +///////////////////////////////////////////////////////////////// +class TSetShrinkModeEvent: public SALOME_Event +{ +public: + const char* myUid; + bool myShrink; + int myViewUid; + + TSetShrinkModeEvent( const char* uid, bool shrink, int viewUid ) + : myUid( uid ), myShrink( shrink ), myViewUid( viewUid ) {} - SALOMEDS::GenericAttribute_var anAttr; - SALOMEDS::SObject_var aSubMeshesRoot; - if ( !aMeshSO->FindSubObject( aShapeTag, aSubMeshesRoot ) ) + virtual void Execute() + { + SALOME_View* view = uid2wnd( myViewUid ); + SMESH_Actor* actor = actorFromView( view, myUid ); + if ( actor ) { - aSubMeshesRoot = myStudyBuilder->NewObjectToTag(aMeshSO,aShapeTag); - anAttr = myStudyBuilder->FindOrCreateAttribute(aSubMeshesRoot,"AttributeName"); - SALOMEDS::AttributeName_var aName = SALOMEDS::AttributeName::_narrow(anAttr); - aName->SetValue(aSubMeshName.toLatin1().data()); - aName->UnRegister(); - anAttr = myStudyBuilder->FindOrCreateAttribute(aSubMeshesRoot,"AttributeSelectable"); - SALOMEDS::AttributeSelectable_var aSelAttr = SALOMEDS::AttributeSelectable::_narrow(anAttr); - aSelAttr->SetSelectable(false); - aSelAttr->UnRegister(); + if ( myShrink ) + actor->SetShrink(); + else + actor->UnShrink(); + if ( view ) + view->Repaint(); } - aSubMeshesRoot->UnRegister(); - aMeshSO->UnRegister(); + } +}; - SALOMEDS::SObject_var aSObject = myStudyBuilder->NewObject(aSubMeshesRoot); - anAttr = myStudyBuilder->FindOrCreateAttribute(aSObject,"AttributeIOR"); - SALOMEDS::AttributeIOR_var anIOR = SALOMEDS::AttributeIOR::_narrow(anAttr); - anIOR->SetValue(theSubMeshIOR); - anIOR->UnRegister(); +///////////////////////////////////////////////////////////////// +/// \brief Switch shrink mode on/off. +/// \param uid Mesh object's study UID or IOR. +/// \param shrink \c true to switch shrink mode on; +/// \c false otherwise. +/// \param viewUid View window UID (0 means currently active view +/// window); Default: 0. +///////////////////////////////////////////////////////////////// +void SMESH_Swig::setShrinkMode(const char* uid, bool shrink, int viewUid) +{ + init(); - _PTR(SObject) sobject = uid2object( myCachedStudyId, uid ); - CORBA::String_var aString = aSObject->GetID(); - aSObject->UnRegister(); ++ _PTR(SObject) sobject = uid2object( uid ); + if ( sobject ) + ProcessVoidEvent( new TSetShrinkModeEvent( sobject->GetID().c_str(), shrink, viewUid ) ); +} - return aString._retn(); +///////////////////////////////////////////////////////////////// +/// \internal +///////////////////////////////////////////////////////////////// +class TGetOpacityEvent: public SALOME_Event +{ +public: + typedef double TResult; + TResult myResult; + const char* myUid; + int myViewUid; + + TGetOpacityEvent( const char* uid, int viewUid ) + : myResult( 0 ), myUid( uid ), myViewUid( viewUid ) {} + + virtual void Execute() + { + SALOME_View* view = uid2wnd( myViewUid ); + SMESH_Actor* actor = actorFromView( view, myUid ); + if ( actor ) + myResult = actor->GetOpacity(); } +}; + +///////////////////////////////////////////////////////////////// +/// \brief Get mesh object's opacity. +/// \param uid Mesh object's study UID or IOR. +/// \param viewUid View window UID (0 means currently active view +/// window); Default: 0. +/// \return Opacity value. +///////////////////////////////////////////////////////////////// +double SMESH_Swig::opacity(const char* uid, int viewUid) +{ + double opacity = 0; + + init(); - _PTR(SObject) sobject = uid2object( myCachedStudyId, uid ); - return ""; ++ _PTR(SObject) sobject = uid2object( uid ); + if ( sobject ) + opacity = ProcessEvent( new TGetOpacityEvent( sobject->GetID().c_str(), viewUid ) ); + + return opacity; } -const char* SMESH_Swig::AddSubMeshOnShape(const char* theMeshEntry, - const char* theGeomShapeEntry, - const char* theSubMeshIOR, - int ShapeType) +///////////////////////////////////////////////////////////////// +/// \internal +///////////////////////////////////////////////////////////////// +class TSetOpacityEvent: public SALOME_Event { - SALOMEDS::SObject_var aGeomShapeSO = KERNEL::getStudyServant()->FindObjectID(theGeomShapeEntry); - if(!aGeomShapeSO->_is_nil()) +public: + const char* myUid; + double myOpacity; + int myViewUid; + + TSetOpacityEvent( const char* uid, double opacity, int viewUid ) + : myUid( uid ), myOpacity( opacity ), myViewUid( viewUid ) {} + + virtual void Execute() { - const char * aSubMeshEntry = AddSubMesh(theMeshEntry,theSubMeshIOR,ShapeType); - SALOMEDS::SObject_var aSubMeshSO = KERNEL::getStudyServant()->FindObjectID(aSubMeshEntry); - if ( !aSubMeshSO->_is_nil()) { - SetShape( theGeomShapeEntry, aSubMeshEntry ); - CORBA::String_var aString = aSubMeshSO->GetID(); - aSubMeshSO->UnRegister(); - return aString._retn(); + SALOME_View* view = uid2wnd( myViewUid ); + SMESH_Actor* actor = actorFromView( view, myUid ); + if ( actor ) + { + actor->SetOpacity( myOpacity ); + if ( view ) + view->Repaint(); } - aGeomShapeSO->UnRegister(); } +}; - return ""; -} +///////////////////////////////////////////////////////////////// +/// \brief Set mesh object's opacity. +/// \param uid Mesh object's study UID or IOR. +/// \param opacity Opacity value. +/// \param viewUid View window UID (0 means currently active view +/// window); Default: 0. +///////////////////////////////////////////////////////////////// +void SMESH_Swig::setOpacity(const char* uid, double opacity, int viewUid) +{ + init(); - _PTR(SObject) sobject = uid2object( myCachedStudyId, uid ); -/*! - \brief Gets window with specified identifier - \internal - \param id window identifier - \return pointer on the window -*/ - -SUIT_ViewWindow* getWnd( const int id ) -{ - SUIT_ViewWindow* resWnd = 0; - SUIT_Session* aSession = SUIT_Session::session(); - SUIT_Application* anApplication = aSession->activeApplication(); - SalomeApp_Application* app = dynamic_cast(anApplication); - if ( app ) { - ViewManagerList vmlist = app->viewManagers(); - foreach( SUIT_ViewManager* vm, vmlist ) { - QVector vwlist = vm->getViews(); - foreach ( SUIT_ViewWindow* vw, vwlist ) { - if ( id == vw->getId() ) { - resWnd = vw; - break; - } - } - } - } - return resWnd; ++ _PTR(SObject) sobject = uid2object( uid ); + if ( sobject ) + ProcessVoidEvent( new TSetOpacityEvent( sobject->GetID().c_str(), opacity, viewUid ) ); } -class TGetActorAspect: public SALOME_Event +///////////////////////////////////////////////////////////////// +/// \internal +///////////////////////////////////////////////////////////////// +class TGetOrientationEvent: public SALOME_Event { public: - typedef actorAspect TResult; + typedef bool TResult; TResult myResult; - const char* _entry; - int _wid; - TGetActorAspect( const char* Mesh_Entry, int viewId ) + const char* myUid; + int myViewUid; + + TGetOrientationEvent( const char* uid, int viewUid ) + : myResult( false ), myUid( uid ), myViewUid( viewUid ) {} + + virtual void Execute() { - _entry = Mesh_Entry; - _wid = viewId; + SALOME_View* view = uid2wnd( myViewUid ); + SMESH_Actor* actor = actorFromView( view, myUid ); + if ( actor ) + myResult = actor->GetFacesOriented(); } - virtual void Execute() - { - SMESH_Actor* anActor; - if (_wid) - { - SUIT_ViewWindow* w = getWnd(_wid); - anActor = SMESH::FindActorByEntry( w, _entry ); - } - else - anActor = SMESH::FindActorByEntry( _entry ); - if ( !anActor ) - { - MESSAGE("GetActorAspect: no actor corresponding to: " << _entry); - return; - } - anActor->GetSufaceColor(myResult.surfaceColor.r, - myResult.surfaceColor.g, - myResult.surfaceColor.b, - myResult.surfaceColor.delta); - anActor->GetVolumeColor(myResult.volumeColor.r, - myResult.volumeColor.g, - myResult.volumeColor.b, - myResult.volumeColor.delta); - anActor->GetEdgeColor(myResult.edgeColor.r, - myResult.edgeColor.g, - myResult.edgeColor.b); - anActor->GetNodeColor(myResult.nodeColor.r, - myResult.nodeColor.g, - myResult.nodeColor.b); - myResult.opacity= anActor->GetOpacity(); - MESSAGE("opacity: " << myResult.opacity); - } }; -actorAspect SMESH_Swig::GetActorAspect( const char* Mesh_Entry, int viewId ) +///////////////////////////////////////////////////////////////// +/// \brief Check if faces orientation vectors are shown. +/// \param uid Mesh object's study UID or IOR. +/// \param viewUid View window UID (0 means currently active view +/// window); Default: 0. +/// \return \c true if faces orientation vectors are shown; +/// \c false otherwise. +///////////////////////////////////////////////////////////////// +bool SMESH_Swig::isOrientationShown(const char* uid, int viewUid) { - return ProcessEvent(new TGetActorAspect( Mesh_Entry, viewId)); + bool shown = false; + + init(); + - _PTR(SObject) sobject = uid2object( myCachedStudyId, uid ); ++ _PTR(SObject) sobject = uid2object( uid ); + if ( sobject ) + shown = ProcessEvent( new TGetOrientationEvent( sobject->GetID().c_str(), viewUid ) ); + + return shown; } -void SMESH_Swig::SetActorAspect( const actorAspect& actorPres, const char* Mesh_Entry, int viewId ) +///////////////////////////////////////////////////////////////// +/// \internal +///////////////////////////////////////////////////////////////// +class TSetOrientationEvent: public SALOME_Event { - class TSetActorAspect: public SALOME_Event +public: + const char* myUid; + bool myShown; + int myViewUid; + + TSetOrientationEvent( const char* uid, bool shown, int viewUid ) + : myUid( uid ), myShown( shown ), myViewUid( viewUid ) {} + + virtual void Execute() { - public: - const char* _entry; - actorAspect _actorPres; - int _wid; - TSetActorAspect(const actorAspect& actorPres, const char* Mesh_Entry, int viewId ) + SALOME_View* view = uid2wnd( myViewUid ); + SMESH_Actor* actor = actorFromView( view, myUid ); + if ( actor ) { - _entry = Mesh_Entry; - _actorPres = actorPres; - _wid = viewId; + actor->SetFacesOriented( myShown ); + if ( view ) + view->Repaint(); } - virtual void Execute() - { - SMESH_Actor* anActor; - if (_wid) - { - SUIT_ViewWindow* w = getWnd(_wid); - anActor = SMESH::FindActorByEntry( w, _entry ); - } - else - anActor = SMESH::FindActorByEntry( _entry ); - if ( !anActor ) - { - MESSAGE("SetActorAspect: no actor corresponding to: " << _entry); - return; - } - anActor->SetSufaceColor(_actorPres.surfaceColor.r, - _actorPres.surfaceColor.g, - _actorPres.surfaceColor.b, - _actorPres.surfaceColor.delta); - anActor->SetVolumeColor(_actorPres.volumeColor.r, - _actorPres.volumeColor.g, - _actorPres.volumeColor.b, - _actorPres.volumeColor.delta); - anActor->SetEdgeColor(_actorPres.edgeColor.r, - _actorPres.edgeColor.g, - _actorPres.edgeColor.b); - anActor->SetNodeColor(_actorPres.nodeColor.r, - _actorPres.nodeColor.g, - _actorPres.nodeColor.b); - anActor->SetOpacity(_actorPres.opacity); - if (_wid) - { - SUIT_ViewWindow* w = getWnd(_wid); - w->repaint(); - } - else - { - SUIT_Session* aSession = SUIT_Session::session(); - SUIT_Application* anApplication = aSession->activeApplication(); - SalomeApp_Application* anApp = dynamic_cast(anApplication); - SUIT_ViewManager* vman = anApp->getViewManager(VTKViewer_Viewer::Type(),true); - vman->getActiveView()->repaint(); - } - } - }; + } +}; + +///////////////////////////////////////////////////////////////// +/// \brief Show/hide faces orientation vectors. +/// \param uid Mesh object's study UID or IOR. +/// \param shown \c true to show faces orientation vectors; +/// \c false otherwise. +/// \param viewUid View window UID (0 means currently active view +/// window); Default: 0. +///////////////////////////////////////////////////////////////// +void SMESH_Swig::setOrientationShown(const char* uid, bool shown, int viewUid) +{ + init(); - _PTR(SObject) sobject = uid2object( myCachedStudyId, uid ); - ProcessVoidEvent(new TSetActorAspect(actorPres, Mesh_Entry, viewId)); ++ _PTR(SObject) sobject = uid2object( uid ); + if ( sobject ) + ProcessVoidEvent( new TSetOrientationEvent( sobject->GetID().c_str(), shown, viewUid ) ); } -void SMESH_Swig::CreateAndDisplayActor( const char* Mesh_Entry ) +///////////////////////////////////////////////////////////////// +/// \internal +///////////////////////////////////////////////////////////////// +class TGetEntitiesEvent: public SALOME_Event { - // SMESH_Actor* Mesh = smeshGUI->ReadScript(aM); - class TEvent: public SALOME_Event +public: + typedef int TResult; + TResult myResult; + const char* myUid; + int myViewUid; + + TGetEntitiesEvent( const char* uid, int viewUid ) + : myResult( EntityNone ), myUid( uid ), myViewUid( viewUid ) {} + + virtual void Execute() { - private: - const char* _entry; - public: - TEvent(const char* Mesh_Entry) { - _entry = Mesh_Entry; - } - virtual void Execute() { - //SMESH::UpdateView(SMESH::eDisplay, _entry); - SUIT_Session* aSession = SUIT_Session::session(); - SUIT_Application* anApplication = aSession->activeApplication(); - SalomeApp_Application* anApp = dynamic_cast(anApplication); - /*SUIT_ViewManager* vman = */anApp->getViewManager(VTKViewer_Viewer::Type(),true); - SMESHGUI_Displayer* aDisp = new SMESHGUI_Displayer(anApp); - aDisp->Display(_entry,1); - } - }; + SALOME_View* view = uid2wnd( myViewUid ); + SMESH_Actor* actor = actorFromView( view, myUid ); + if ( actor ) + myResult = actor->GetEntityMode(); + } +}; + +///////////////////////////////////////////////////////////////// +/// \brief Get mesh object's visible entities. +/// \param uid Mesh object's study UID or IOR. +/// \param viewUid View window UID (0 means currently active view +/// window); Default: 0. +/// \return Enumerator describing entities being visible. +///////////////////////////////////////////////////////////////// +int SMESH_Swig::entitiesShown(const char* uid, int viewUid) +{ + int entities = EntityNone; + + init(); - _PTR(SObject) sobject = uid2object( myCachedStudyId, uid ); - ProcessVoidEvent(new TEvent(Mesh_Entry)); ++ _PTR(SObject) sobject = uid2object( uid ); + if ( sobject ) + entities = ProcessEvent( new TGetEntitiesEvent( sobject->GetID().c_str(), viewUid ) ); + + return entities; } -void SMESH_Swig::EraseActor( const char* Mesh_Entry, const bool allViewers ) +///////////////////////////////////////////////////////////////// +/// \internal +///////////////////////////////////////////////////////////////// +class TSetEntitiesEvent: public SALOME_Event { - class TEvent: public SALOME_Event +public: + const char* myUid; + int myEntities; + int myViewUid; + + TSetEntitiesEvent( const char* uid, int entities, int viewUid ) + : myUid( uid ), myEntities( entities ), myViewUid( viewUid ) {} + + virtual void Execute() { - private: - const char* _entry; - bool _allViewers; - public: - TEvent(const char* Mesh_Entry, const bool allViewers ) { - _entry = Mesh_Entry; - _allViewers = allViewers; - } - virtual void Execute() { - SUIT_Session* aSession = SUIT_Session::session(); - SUIT_Application* anApplication = aSession->activeApplication(); - SalomeApp_Application* anApp = dynamic_cast(anApplication); - SMESHGUI_Displayer* aDisp = new SMESHGUI_Displayer(anApp); - ViewManagerList aManagers; - if ( !_allViewers ) { - aManagers << anApp->activeViewManager(); - } - else { - aManagers = anApp->viewManagers(); - } - foreach( SUIT_ViewManager* aMgr, aManagers ) { - if ( aMgr && aMgr->getType() == VTKViewer_Viewer::Type() ) { - SALOME_View* aSalomeView = dynamic_cast(aMgr->getViewModel()); - if (aSalomeView) { - aDisp->Erase(_entry,true, true, aSalomeView); - } - } - } + SALOME_View* view = uid2wnd( myViewUid ); + SMESH_Actor* actor = actorFromView( view, myUid ); + if ( actor ) + { + actor->SetEntityMode( myEntities ); + if ( view ) + view->Repaint(); } - }; + } +}; - ProcessVoidEvent(new TEvent(Mesh_Entry, allViewers)); +///////////////////////////////////////////////////////////////// +/// \brief Set mesh object's visible entities. +/// \param uid Mesh object's study UID or IOR. +/// \param entities Enumerator describing entities to be shown. +/// \param viewUid View window UID (0 means currently active view +/// window); Default: 0. +///////////////////////////////////////////////////////////////// +void SMESH_Swig::setEntitiesShown(const char* uid, int entities, int viewUid) +{ + init(); + - _PTR(SObject) sobject = uid2object( myCachedStudyId, uid ); ++ _PTR(SObject) sobject = uid2object( uid ); + if ( sobject ) + ProcessVoidEvent( new TSetEntitiesEvent( sobject->GetID().c_str(), entities, viewUid ) ); } -void SMESH_Swig::UpdateActor( const char* Mesh_Entry ) { - class TEvent: public SALOME_Event +///////////////////////////////////////////////////////////////// +/// \brief Check if given mesh object's entity is shown. +/// \param uid Mesh object's study UID or IOR. +/// \param entity Mesh entity. +/// \param viewUid View window UID (0 means currently active view +/// window); Default: 0. +/// \return \c true if entity is shown; \c false otherwise. +///////////////////////////////////////////////////////////////// +bool SMESH_Swig::isEntityShown(const char* uid, EntityMode entity, int viewUid) +{ + bool shown = false; + + init(); + - _PTR(SObject) sobject = uid2object( myCachedStudyId, uid ); ++ _PTR(SObject) sobject = uid2object( uid ); + if ( sobject ) { - private: - const char* _entry; - public: - TEvent( const char* Mesh_Entry ) { - _entry = Mesh_Entry; - } - virtual void Execute() { - Handle(SALOME_InteractiveObject) anIO = new SALOME_InteractiveObject - ( _entry, "SMESH", "" ); - SMESH::Update( anIO, true ); - } - }; + int entities = ProcessEvent( new TGetEntitiesEvent( sobject->GetID().c_str(), viewUid ) ); + shown = (bool)( entities & entity ); + } - ProcessVoidEvent( new TEvent(Mesh_Entry) ); + return shown; } -void SMESH_Swig::SetName(const char* theEntry, - const char* theName) -{ - SALOMEDS::SObject_var aSObject = KERNEL::getStudyServant()->FindObjectID(theEntry); - SALOMEDS::GenericAttribute_var anAttr; - SALOMEDS::AttributeName_var aName; - if(!aSObject->_is_nil()){ - anAttr = myStudyBuilder->FindOrCreateAttribute(aSObject,"AttributeName"); - aName = SALOMEDS::AttributeName::_narrow(anAttr); - aName->SetValue(theName); - aName->UnRegister(); - aSObject->UnRegister(); +///////////////////////////////////////////////////////////////// +/// \brief Show/hide entity for given mesh object. +/// \param uid Mesh object's study UID or IOR. +/// \param entity Mesh entity. +/// \param show Visibility status. +/// \param viewUid View window UID (0 means currently active view +/// window); Default: 0. +///////////////////////////////////////////////////////////////// +void SMESH_Swig::setEntityShown(const char* uid, EntityMode entity, bool show, int viewUid) +{ + init(); + - _PTR(SObject) sobject = uid2object( myCachedStudyId, uid ); ++ _PTR(SObject) sobject = uid2object( uid ); + if ( sobject ) + { + int entities = ProcessEvent( new TGetEntitiesEvent( sobject->GetID().c_str(), viewUid ) ); + if ( show ) + entities |= entity; + else + entities &= ~entity; + ProcessVoidEvent( new TSetEntitiesEvent( sobject->GetID().c_str(), entities, viewUid ) ); } } -//================================================================================ -/*! - * \brief Set mesh icon according to compute status - * \param Mesh_Entry - entry of a mesh - * \param isComputed - is mesh computed or not - */ -//================================================================================ +///////////////////////////////////////////////////////////////// +/// \brief Initialize %SMESH GUI Python interface. +/// \deprecated Interface is initialized automatically. - /// \param studyID Study UID (not used). +///////////////////////////////////////////////////////////////// - void SMESH_Swig::Init(int /*studyID*/) ++void SMESH_Swig::Init() +{ + deprecated("SMESH_Swig::Init"); + // does nothing; initialization is done automatically. +} -void SMESH_Swig::SetMeshIcon(const char* theMeshEntry, - const bool theIsComputed, - const bool isEmpty) +///////////////////////////////////////////////////////////////// +/// \brief Publish mesh in the active study. +/// \deprecated Publishing is done automatically. +/// \param ior IOR of the mesh. +/// \param name Name of the mesh (optional). +/// \return UID of the data object. +///////////////////////////////////////////////////////////////// +const char* SMESH_Swig::AddNewMesh(const char* ior, const char* name) { - class TEvent: public SALOME_Event - { - std::string myMeshEntry; - bool myIsComputed, myIsEmpty; - public: - TEvent(const std::string& theMeshEntry, - const bool theIsComputed, - const bool isEmpty): - myMeshEntry (theMeshEntry), - myIsComputed(theIsComputed), - myIsEmpty (isEmpty) - {} - - virtual - void - Execute() - { - SALOMEDS::SObject_ptr aMeshSO = KERNEL::getStudyServant()->FindObjectID(myMeshEntry.c_str()); - if(_PTR(SObject) aMesh = ClientFactory::SObject(aMeshSO)) - SMESH::ModifiedMesh(aMesh,myIsComputed,myIsEmpty); - // aMeshSO->UnRegister(); ~aMesh() already called UnRegister()! - } - }; + deprecated("SMESH_Swig::AddNewMesh", "SMESH_Swig::publish"); + return publish( ior, name ); +} + +///////////////////////////////////////////////////////////////// +/// \brief Publish hypothesis in the active study. +/// \deprecated Publishing is done automatically. +/// \param ior IOR of the hypothesis. +/// \param name Name of the hypothesis (optional). +/// \return UID of the data object. +///////////////////////////////////////////////////////////////// +const char* SMESH_Swig::AddNewHypothesis(const char* ior, const char* name) +{ + deprecated("SMESH_Swig::AddNewHypothesis", "SMESH_Swig::publish"); + return publish( ior, name ); +} + +///////////////////////////////////////////////////////////////// +/// \brief Publish algorithm in the active study. +/// \deprecated Publishing is done automatically. +/// \param ior IOR of the algorithm. +/// \param name Name of the algorithm (optional). +/// \return UID of the data object. +///////////////////////////////////////////////////////////////// +const char* SMESH_Swig::AddNewAlgorithm(const char* ior, const char* name) +{ + deprecated("SMESH_Swig::AddNewAlgorithm", "SMESH_Swig::publish"); + return publish( ior, name ); +} + +///////////////////////////////////////////////////////////////// +/// \deprecated Publishing is done automatically. +/// \deprecated Synonim of AddNewAlgorithm(). +/// \param ior IOR of the algorithm. +/// \param name Name of the algorithm (optional). +/// \return UID of the data object. +///////////////////////////////////////////////////////////////// +const char* SMESH_Swig::AddNewAlgorithms(const char* ior, const char* name) +{ + deprecated("SMESH_Swig::AddNewAlgorithms", "SMESH_Swig::publish"); + return publish( ior, name ); +} + +///////////////////////////////////////////////////////////////// +/// \brief Add reference on a shape for mesh in a study. +/// \deprecated Publishing is done automatically. +/// \param shapeUid GEOM shape's study UID (not used). +/// \param meshUid Mesh's study UID (not used). +///////////////////////////////////////////////////////////////// +void SMESH_Swig::SetShape(const char* /*shapeUid*/, const char* /*meshUid*/) +{ + deprecated("SMESH_Swig::SetShape", "SMESH_Swig::publish"); + // does nothing: publishing is done automatically +} + +///////////////////////////////////////////////////////////////// +/// \brief Assign hypothesis to mesh or sub-mesh. +/// \deprecated Publishing is done automatically. +/// \param meshUid Mesh's or sub-mesh's study UID (not used). +/// \param hypoUID Hypothesis's study UID (not used). +///////////////////////////////////////////////////////////////// +void SMESH_Swig::SetHypothesis(const char* /*meshUid*/, const char* /*hypoUID*/) +{ + deprecated("SMESH_Swig::SetHypothesis", "SMESH_Swig::publish"); + // does nothing: publishing is done automatically +} + +///////////////////////////////////////////////////////////////// +/// \brief Assign algorithm to mesh or sub-mesh. +/// \deprecated Publishing is done automatically. +/// \param meshUid Mesh's or sub-mesh's study UID (not used). +/// \param algoUID Algorithm's study UID (not used). +///////////////////////////////////////////////////////////////// +void SMESH_Swig::SetAlgorithms(const char* /*meshUid*/, const char* /*algoUID*/) +{ + deprecated("SMESH_Swig::SetAlgorithms", "SMESH_Swig::publish"); + // does nothing: publishing is done automatically +} + +///////////////////////////////////////////////////////////////// +/// \brief Anassign hypothesis or algorithm from mesh or sub-mesh. +/// \deprecated Unpublishing is done automatically. +/// \param uid Hypothesis's or algorithm's study UID (not used). +///////////////////////////////////////////////////////////////// +void SMESH_Swig::UnSetHypothesis(const char* /*uid*/) +{ + deprecated("SMESH_Swig::UnSetHypothesis"); + // does nothing: unpublishing is done automatically +} + +///////////////////////////////////////////////////////////////// +/// \brief Publish sub-mesh in the active study. +/// \deprecated Publishing is done automatically. +/// \param meshUid Parent mesh's study UID (not used). +/// \param ior IOR of the sub-mesh. +/// \param shapeType GEOM shape's type (not used). +/// \param name Name of the sub-mesh (optional). +/// \return UID of the data object. +///////////////////////////////////////////////////////////////// +const char* SMESH_Swig::AddSubMesh(const char* /*meshUid*/, + const char* ior, + int /*shapeType*/, + const char* name) +{ + deprecated("SMESH_Swig::AddSubMesh", "SMESH_Swig::publish"); + return publish( ior, name ); +} + +///////////////////////////////////////////////////////////////// +/// \brief Publish sub-mesh in the active study. +/// \deprecated Publishing is done automatically. +/// \param meshUid Parent mesh's study UID (not used). +/// \param shapeUid GEOM shape's study UID (not used). +/// \param ior IOR of the sub-mesh. +/// \param shapeType GEOM shape's type (not used). +/// \param name Name of the sub-mesh (optional). +/// \return UID of the data object. +///////////////////////////////////////////////////////////////// +const char* SMESH_Swig::AddSubMeshOnShape(const char* /*meshUid*/, + const char* /*shapeUid*/, + const char* ior, + int /*shapeType*/, + const char* name) +{ + deprecated("SMESH_Swig::AddSubMeshOnShape", "SMESH_Swig::publish"); + return publish( ior, name ); +} - ProcessVoidEvent(new TEvent(theMeshEntry, - theIsComputed, - isEmpty)); +///////////////////////////////////////////////////////////////// +/// \brief Set new study name of given object. +/// \deprecated Use rename() method. +/// \param uid Object's study UID or IOR. +/// \param name New name of the object. +///////////////////////////////////////////////////////////////// +void SMESH_Swig::SetName(const char* uid, const char* name) +{ + deprecated("SMESH_Swig::SetName", "SMESH_Swig::rename"); + rename( uid, name ); } -/*! - \brief Helper class for selection event. -*/ +///////////////////////////////////////////////////////////////// +/// \brief Set mesh icon according to compute status +/// \deprecated Publishing is done automatically. +/// \param meshUid Mesh's study UID (not used). +/// \param isComputed Flag pointing that mesh is computed or no +/// (not used). +/// \param isEmpty Flag pointing that mesh is empty or no +/// (not used). +///////////////////////////////////////////////////////////////// +void SMESH_Swig::SetMeshIcon(const char* /*meshUid*/, + const bool /*isComputed*/, + const bool /*isEmpty*/) +{ + deprecated("SMESH_Swig::SetMeshIcon", "SMESH_Swig::publish"); + // does nothing: publishing is done automatically +} + +///////////////////////////////////////////////////////////////// +/// Display mesh in the currently active view window. +/// \deprecated Use display() method. +/// \param meshUid Mesh's study UID. +///////////////////////////////////////////////////////////////// +void SMESH_Swig::CreateAndDisplayActor(const char* meshUid) +{ + deprecated("SMESH_Swig::CreateAndDisplayActor", "SMESH_Swig::display"); + display( meshUid ); +} + +///////////////////////////////////////////////////////////////// +/// Erase mesh in the view window(s). +/// \deprecated Use erase() method. +/// \param meshUid Mesh's study UID. +/// \param allViewers If \c true, mesh is removed from all views. +/// Default: \c false. +///////////////////////////////////////////////////////////////// +void SMESH_Swig::EraseActor(const char* meshUid, const bool allViewers) +{ + deprecated("SMESH_Swig::EraseActor", "SMESH_Swig::erase"); + erase( meshUid, allViewers ? -1 : 0 ); +} + +///////////////////////////////////////////////////////////////// +/// Update mesh object. +/// \deprecated Use update() method. +/// \param meshUid Mesh's study UID. +///////////////////////////////////////////////////////////////// +void SMESH_Swig::UpdateActor(const char* meshUid) +{ + deprecated("SMESH_Swig::UpdateActor", "SMESH_Swig::update"); + update( meshUid ); +} + +///////////////////////////////////////////////////////////////// +/// Get mesh object's properties. +/// \deprecated Use properties() method. +/// \param meshUid Mesh's study UID. +/// \param viewUid View window UID (0 means currently active view +/// window). Default: 0. +///////////////////////////////////////////////////////////////// +actorAspect SMESH_Swig::GetActorAspect(const char* meshUid, int viewUid) +{ + deprecated("SMESH_Swig::GetActorAspect", "SMESH_Swig::properties"); + return properties( meshUid, viewUid ); +} + +///////////////////////////////////////////////////////////////// +/// Set mesh object's properties. +/// \deprecated Use setProperties() method. +/// \param meshUid Mesh's study UID. +/// \param viewUid View window UID (0 means currently active view +/// window). Default: 0. +///////////////////////////////////////////////////////////////// +void SMESH_Swig::SetActorAspect(const actorAspect& aspect, const char* meshUid, int viewUid) +{ + deprecated("SMESH_Swig::SetActorAspect", "SMESH_Swig::setProperties"); + setProperties( meshUid, aspect, viewUid ); +} + +///////////////////////////////////////////////////////////////// +/// \internal +///////////////////////////////////////////////////////////////// class TSelectListEvent: public SALOME_Event { - const char* myId; - std::vector myIdsList; - bool myIsAppend; + const char* myUid; + std::vector myIds; + bool myIsAppend; public: - TSelectListEvent(const char* id, std::vector ids, bool append) : - myId(id), - myIdsList(ids), - myIsAppend(append) + TSelectListEvent(const char* uid, std::vector ids, bool append) + : myUid( uid ), myIds( ids ), myIsAppend( append ) {} + virtual void Execute() { - LightApp_SelectionMgr* selMgr = 0; - SalomeApp_Application* anApp = dynamic_cast( SUIT_Session::session()->activeApplication() ); - if( anApp ) - selMgr = dynamic_cast( anApp->selectionMgr() ); + SalomeApp_Application* app = dynamic_cast( SUIT_Session::session()->activeApplication() ); + if ( app ) + selMgr = dynamic_cast( app->selectionMgr() ); - if( !selMgr ) + if ( !selMgr ) return; selMgr->clearFilters(); @@@ -1777,65 -938,52 +1751,65 @@@ } }; -/*! - \brief Select the elements on the mesh, sub-mesh or group. - \param id object entry - \param ids list of the element ids - \param mode selection mode -*/ -void SMESH_Swig::select( const char* id, std::vector ids, bool append ) { - ProcessVoidEvent( new TSelectListEvent( id, ids, append ) ); +///////////////////////////////////////////////////////////////// +/// \brief Select elements of the mesh, sub-mesh or group. +/// \param uid Mesh object's study UID or IOR. +/// \param ids List of mesh elements. +/// \param append If \c true, elements are added to current +/// selection; otherwise, previous selection is +/// cleared. +///////////////////////////////////////////////////////////////// +void SMESH_Swig::select(const char* uid, std::vector ids, bool append) +{ + init(); + - _PTR(SObject) sobject = uid2object( myCachedStudyId, uid ); ++ _PTR(SObject) sobject = uid2object( uid ); + if ( sobject ) + ProcessVoidEvent( new TSelectListEvent( sobject->GetID().c_str(), ids, append ) ); } -/*! - \brief Select the elements on the mesh, sub-mesh or group. - \param id object entry - \param id id of the element - \param mode selection mode -*/ -void SMESH_Swig::select( const char* id, int id1, bool append ) { +///////////////////////////////////////////////////////////////// +/// \brief Select element of the mesh, sub-mesh or group. +/// \param uid Mesh object's study UID or IOR. +/// \param id Mesh element. +/// \param append If \c true, element is added to current +/// selection; otherwise, previous selection is +/// cleared. +///////////////////////////////////////////////////////////////// +void SMESH_Swig::select(const char* uid, int id, bool append) +{ + init(); + std::vector ids; - ids.push_back( id1 ); - ProcessVoidEvent( new TSelectListEvent( id, ids, append ) ); + ids.push_back( id ); + - _PTR(SObject) sobject = uid2object( myCachedStudyId, uid ); ++ _PTR(SObject) sobject = uid2object( uid ); + if ( sobject ) + ProcessVoidEvent( new TSelectListEvent( sobject->GetID().c_str(), ids, append ) ); } -/*! - \brief Helper class for selection edges of cell event -*/ +///////////////////////////////////////////////////////////////// +/// \internal +///////////////////////////////////////////////////////////////// class TSelectListOfPairEvent: public SALOME_Event { - const char* myId; - std::vector > myIdsList; - bool myIsAppend; + const char* myUid; + std::vector > myIds; + bool myIsAppend; public: - TSelectListOfPairEvent(const char* id, std::vector > ids, bool append) : - myId(id), - myIdsList(ids), - myIsAppend(append) + TSelectListOfPairEvent(const char* uid, std::vector > ids, bool append) + : myUid( uid ), myIds( ids ), myIsAppend( append ) {} + virtual void Execute() { - LightApp_SelectionMgr* selMgr = 0; - SalomeApp_Application* anApp = dynamic_cast( SUIT_Session::session()->activeApplication() ); - if( anApp ) - selMgr = dynamic_cast( anApp->selectionMgr() ); + SalomeApp_Application* app = dynamic_cast( SUIT_Session::session()->activeApplication() ); + if ( app ) + selMgr = dynamic_cast( app->selectionMgr() ); - if( !selMgr ) + if ( !selMgr ) return; selMgr->clearFilters(); @@@ -1875,28 -1023,17 +1849,28 @@@ } }; -/*! - \brief Select the elements on the mesh, sub-mesh or group. - \param id object entry - \param ids list of the element ids - \param mode selection mode -*/ -void SMESH_Swig::select( const char* id, std::vector > ids, bool append ) { - ProcessVoidEvent( new TSelectListOfPairEvent( id, ids, append ) ); +///////////////////////////////////////////////////////////////// +/// \brief Select pseudo-edges (specified by two nodes) +/// of the mesh, sub-mesh or group. +/// \param uid Mesh object's study UID or IOR. +/// \param ids List of pairs containing two nodes IDs. +/// \param append If \c true, pseudo-edges are added to current +/// selection; otherwise, previous selection is +/// cleared. +///////////////////////////////////////////////////////////////// +void SMESH_Swig::select(const char* uid, std::vector > ids, bool append) +{ + init(); + - _PTR(SObject) sobject = uid2object( myCachedStudyId, uid ); ++ _PTR(SObject) sobject = uid2object( uid ); + if ( sobject ) + ProcessVoidEvent( new TSelectListOfPairEvent( sobject->GetID().c_str(), ids, append ) ); } -class TGetSelectionModeEvent : public SALOME_Event +///////////////////////////////////////////////////////////////// +/// \internal +///////////////////////////////////////////////////////////////// +class TGetSelectionModeEvent: public SALOME_Event { public: typedef SelectionMode TResult; @@@ -2022,27 -1136,10 +1996,27 @@@ public } }; -std::vector SMESH_Swig::getSelected( const char* Mesh_Entry ) { - return ProcessEvent( new TGetSelectedEvent(Mesh_Entry) ); +///////////////////////////////////////////////////////////////// +/// \brief Get selected elements of the mesh, sub-mesh or group. +/// \param uid Mesh object's study UID or IOR. +/// \return List of selected mesh elements. +///////////////////////////////////////////////////////////////// +std::vector SMESH_Swig::getSelected(const char* uid) +{ + std::vector ids; + + init(); + - _PTR(SObject) sobject = uid2object( myCachedStudyId, uid ); ++ _PTR(SObject) sobject = uid2object( uid ); + if ( sobject ) + ids = ProcessEvent( new TGetSelectedEvent( sobject->GetID().c_str() ) ); + + return ids; } +///////////////////////////////////////////////////////////////// +/// \internal +///////////////////////////////////////////////////////////////// class TGetSelectedPairEvent : public SALOME_Event { public: @@@ -2078,24 -1178,7 +2052,24 @@@ } }; -std::vector > SMESH_Swig::getSelectedEdgeOfCell( const char* Mesh_Entry ) { - return ProcessEvent( new TGetSelectedPairEvent(Mesh_Entry) ); -} +///////////////////////////////////////////////////////////////// +/// \brief Get selected pseudo-edges (specified by two nodes) +/// of the mesh, sub-mesh or group. +/// \param uid Mesh object's study UID or IOR. +/// \param ids List of pairs containing two nodes IDs. +/// \param append If \c true, pseudo-edges are added to current +/// selection; otherwise, previous selection is +/// cleared. +///////////////////////////////////////////////////////////////// +std::vector > SMESH_Swig::getSelectedEdgeOfCell(const char* uid) +{ + std::vector > pairs; + init(); + - _PTR(SObject) sobject = uid2object( myCachedStudyId, uid ); ++ _PTR(SObject) sobject = uid2object( uid ); + if ( sobject ) + pairs = ProcessEvent( new TGetSelectedPairEvent( sobject->GetID().c_str() ) ); + + return pairs; +} diff --cc src/SMESH_SWIG_WITHIHM/libSMESH_Swig.h index 24482f280,fa564efa4..89307c096 --- a/src/SMESH_SWIG_WITHIHM/libSMESH_Swig.h +++ b/src/SMESH_SWIG_WITHIHM/libSMESH_Swig.h @@@ -127,89 -96,55 +127,88 @@@ class SMESH_SWIG_EXPORT SMESH_Swi public: SMESH_Swig(); ~SMESH_Swig(); - - - void Init(); + - const char* AddNewMesh( const char* ); + - const char* AddNewHypothesis( const char* ); - const char* AddNewAlgorithms( const char* ); + // Initialization ============================================= - - void Init(int); // deprecated ++ ++ void Init(); // deprecated + + // Publishing ================================================= + + const char* publish(const char*, const char* = 0); + void rename(const char*, const char*); - void SetShape( const char*, const char* ); + const char* AddNewMesh(const char*, const char* = 0); // deprecated + const char* AddNewHypothesis(const char*, const char* = 0); // deprecated + const char* AddNewAlgorithm(const char*, const char* = 0); // deprecated + const char* AddNewAlgorithms(const char*, const char* = 0); // deprecated - void SetHypothesis( const char*, const char* ); - void SetAlgorithms( const char*, const char* ); + void SetShape(const char*, const char*); // deprecated - void UnSetHypothesis( const char* ); + void SetHypothesis(const char*, const char*); // deprecated + void SetAlgorithms(const char*, const char*); // deprecated - const char* AddSubMesh( const char*, const char*, int ); - const char* AddSubMeshOnShape( const char*, const char*, const char*, int ); + void UnSetHypothesis(const char*); // deprecated - void CreateAndDisplayActor( const char* ); + const char* AddSubMesh(const char*, const char*, int, const char* = 0); // deprecated + const char* AddSubMeshOnShape(const char*, const char*, const char*, int, const char* = 0); // deprecated - void SetName( const char*, const char* ); + void SetName(const char*, const char*); // deprecated - void EraseActor( const char*, const bool allViewers = false ); + void SetMeshIcon(const char*, const bool, const bool); // deprecated - void UpdateActor( const char* Mesh_Entry ); + // Visualization ============================================= - /*! - * \brief Set mesh icon according to compute status - * \param Mesh_Entry - entry of a mesh - * \param isComputed - is mesh computed or not - */ - void SetMeshIcon( const char*, const bool, const bool ); + void display(const char*, int = 0, bool = true); + void erase(const char*, int = 0, bool = true); + void update(const char*); - actorAspect GetActorAspect(const char* Mesh_Entry, int viewId = 0 ); - void SetActorAspect( const actorAspect& actorPres, const char* Mesh_Entry, int viewId = 0 ); + Properties properties(const char*, int = 0); + void setProperties(const char*, const Properties&, int = 0); - void setSelectionMode( SelectionMode selectionMode ); - std::vector getSelected( const char* Mesh_Entry ); - std::vector > getSelectedEdgeOfCell( const char* Mesh_Entry ); + bool nodesNumbering(const char*, int = 0); + void setNodesNumbering(const char*, bool, int = 0); + bool elementsNumbering(const char*, int = 0); + void setElementsNumbering(const char*, bool, int = 0); - // --------------------- for the test purposes ----------------------- - SelectionMode getSelectionMode(); - void select( const char *id, std::vector ids, bool append = false ); - void select( const char *id, int id1, bool append = false ); - void select( const char *id, std::vector >, bool apend = false ); + DisplayMode displayMode(const char*, int = 0); + void setDisplayMode(const char*, DisplayMode, int = 0); + + bool shrinkMode(const char*, int = 0); + void setShrinkMode(const char*, bool, int = 0); + + double opacity(const char*, int = 0); + void setOpacity(const char*, double, int = 0); + + bool isOrientationShown(const char*, int = 0); + void setOrientationShown(const char*, bool, int = 0); + + int entitiesShown(const char*, int = 0); + void setEntitiesShown(const char*, int, int = 0); + bool isEntityShown(const char*, EntityMode, int = 0); + void setEntityShown(const char*, EntityMode, bool, int = 0); + + void CreateAndDisplayActor(const char*); // deprecated + void EraseActor(const char*, const bool = false); // deprecated + void UpdateActor(const char* Mesh_Entry); // deprecated + + actorAspect GetActorAspect(const char*, int = 0); // deprecated + void SetActorAspect(const actorAspect&, const char*, int = 0); // deprecated + + // Selection ================================================= + + SelectionMode getSelectionMode(int = 0); + void setSelectionMode(SelectionMode, int = 0); + std::vector getSelected(const char*); + std::vector > getSelectedEdgeOfCell(const char*); + + void select(const char*, std::vector, bool = false); + void select(const char*, int, bool = false); + void select(const char*, std::vector >, bool = false); private: - SALOMEDS::StudyBuilder_var myStudyBuilder; - SALOMEDS::SComponent_var mySComponentMesh; + void init(); + - private: - int myCachedStudyId; }; #endif // LIBSMESH_SWIG_H diff --cc src/SMESH_SWIG_WITHIHM/libSMESH_Swig.i index 0978eb6bf,e261ade1d..a1aebc00a --- a/src/SMESH_SWIG_WITHIHM/libSMESH_Swig.i +++ b/src/SMESH_SWIG_WITHIHM/libSMESH_Swig.i @@@ -141,81 -110,44 +141,82 @@@ public SMESH_Swig(); ~SMESH_Swig(); - void Init(); + - const char* AddNewMesh(const char* IOR); - const char* AddNewHypothesis(const char* IOR); - const char* AddNewAlgorithms(const char* IOR); + // Initialization ============================================= + - void Init(int); // deprecated ++ void Init(); // deprecated + + // Publishing ================================================= + + const char* publish(const char*, const char* = 0); + void rename(const char*, const char*); + + const char* AddNewMesh(const char*, const char* = 0); // deprecated + const char* AddNewHypothesis(const char*, const char* = 0); // deprecated + const char* AddNewAlgorithms(const char*, const char* = 0); // deprecated + const char* AddNewAlgorithm(const char*, const char* = 0); // deprecated + + void SetShape(const char*, const char*); // deprecated + + void SetHypothesis(const char*, const char*); // deprecated + void SetAlgorithms(const char*, const char*); // deprecated + + void UnSetHypothesis(const char*); // deprecated + + const char* AddSubMesh(const char*, const char*, int, const char* = 0); // deprecated + const char* AddSubMeshOnShape (const char*, const char*, const char*, int, const char* = 0); // deprecated + + void SetName(const char*, const char*); // deprecated + + void SetMeshIcon(const char*, const bool, const bool); // deprecated + + // Visualization ============================================= + + void display(const char*, int = 0, bool = true); + void erase(const char*, int = 0, bool = true); + void update(const char*); + + Properties properties(const char*, int = 0); + void setProperties(const char*, const Properties&, int = 0); - void SetShape(const char* ShapeEntry, const char* MeshEntry); + bool nodesNumbering(const char*, int = 0); + void setNodesNumbering(const char*, bool, int = 0); + bool elementsNumbering(const char*, int = 0); + void setElementsNumbering(const char*, bool, int = 0); - void SetHypothesis(const char* Mesh_Or_SubMesh_Entry, const char* Hypothesis_Entry); - void SetAlgorithms(const char* Mesh_Or_SubMesh_Entry, const char* Algorithms_Entry); + DisplayMode displayMode(const char*, int = 0); + void setDisplayMode(const char*, DisplayMode, int = 0); - void UnSetHypothesis(const char* Applied_Hypothesis_Entry ); + bool shrinkMode(const char*, int = 0); + void setShrinkMode(const char*, bool, int = 0); - const char* AddSubMesh (const char* Mesh_Entry, const char* SM_IOR, int ST); - const char* AddSubMeshOnShape (const char* Mesh_Entry, const char* GeomShape_Entry, const char* SM_IOR, int ST); + double opacity(const char*, int = 0); + void setOpacity(const char*, double, int = 0); - void SetName(const char* Entry, const char* Name); + bool isOrientationShown(const char*, int = 0); + void setOrientationShown(const char*, bool, int = 0); - void SetMeshIcon(const char* Mesh_Entry, const bool isComputed, const bool isEmpty); + int entitiesShown(const char*, int = 0); + void setEntitiesShown(const char*, int, int = 0); + bool isEntityShown(const char*, EntityMode, int = 0); + void setEntityShown(const char*, EntityMode, bool, int = 0); - void CreateAndDisplayActor( const char* Mesh_Entry ); - void EraseActor( const char* Mesh_Entry, const bool allViewers = false ); - void UpdateActor( const char* Mesh_Entry ); + void CreateAndDisplayActor(const char*); // deprecated + void EraseActor(const char*, const bool = false); // deprecated + void UpdateActor(const char*); // deprecated - void setSelectionMode( SelectionMode selectionMode); - std::vector getSelected( const char* Mesh_Entry ); - std::vector > getSelectedEdgeOfCell( const char* Mesh_Entry ); + actorAspect GetActorAspect(const char*, int = 0); // deprecated + void SetActorAspect(const actorAspect&, const char*, int = 0); // deprecated - actorAspect GetActorAspect(const char* Mesh_Entry, int viewId = 0 ); - void SetActorAspect( const actorAspect& actorPres, const char* Mesh_Entry, int viewId = 0 ); + // Selection ================================================= - void setSelectionMode( SelectionMode selectionMode); - std::vector getSelected( const char* Mesh_Entry ); + SelectionMode getSelectionMode(int = 0); + void setSelectionMode(SelectionMode, int = 0); - // --------------------- for the test purposes ----------------------- - SelectionMode getSelectionMode(); - void select( const char *id, std::vector ids, bool append = false ); - void select( const char *id, int id1, bool append = false ); - void select( const char *id, std::vector >, bool apend = false ); + std::vector getSelected(const char*); + std::vector > getSelectedEdgeOfCell(const char*); + void select(const char*, std::vector, bool = false); + void select(const char*, int, bool = false); + void select(const char*, std::vector >, bool = false); }; diff --cc src/Tools/MacMesh/MacMesh/PublishGroups.py index 185f666c0,7b768d84f..304724e48 --- a/src/Tools/MacMesh/MacMesh/PublishGroups.py +++ b/src/Tools/MacMesh/MacMesh/PublishGroups.py @@@ -31,70 -31,70 +31,92 @@@ smesh = smeshBuilder.New( ########################################################################################################## def PublishGroups (): + aFilterManager = smesh.CreateFilterManager() + + # Building geometric and mesh compounds and groups ############################################## + if Config.debug : print("Searching for geometric groups and publishing final compound") + + TempGEOList = [] + TempMESHList = [] + + for MacroObj in Config.ListObj : + TempGEOList += MacroObj.GeoChildren + TempMESHList += MacroObj.Mesh + + FinalCompound = geompy.MakeCompound(TempGEOList) + geompy.addToStudy (FinalCompound,Config.StudyName) + MeshCompound = smesh.Concatenate(TempMESHList, 1, 1, 1e-5) + MeshCompound.SetName(Config.StudyName) + + GroupGEO = [] + for group in Config.Groups : + + # Geometric groups definition + TempGEOList = [] - TempNames = [] - for MacroObj in Config.ListObj : - if group in MacroObj.GroupNames : - Occurences = IndexMultiOcc(MacroObj.GroupNames, group) - for Occ in Occurences : - TempGEOList += MacroObj.GetBorder(Occ) - GroupGEO.append(geompy.MakeCompound(TempGEOList)) - geompy.addToStudyInFather(FinalCompound,GroupGEO[-1],'GR_'+group) - - # Mesh groups definition - Criterion = smesh.GetCriterion(SMESH.EDGE, SMESH.FT_BelongToGeom,'=',GroupGEO[-1],Tolerance=1e-06) - #Criterion = smesh.Filter.Criterion(18,39,0,'GR_'+group,'GR_'+group,39,39,1e-06,smesh.EDGE,7) - MeshCompound.MakeGroupByCriterion(group,Criterion) - - StudyBuilder = Config.theStudy.NewBuilder() - for MeshObj in TempMESHList: - SO = Config.theStudy.FindObjectIOR(Config.theStudy.ConvertObjectToIOR(MeshObj)) - if SO is not None: StudyBuilder.RemoveObjectWithChildren(SO) - - return MeshCompound + aFilterManager = smesh.CreateFilterManager() + # Building geometric and mesh compounds and groups ############################################## - if Config.debug : print "Searching for geometric groups and publishing final compound" ++ if Config.debug : print("Searching for geometric groups and publishing final compound") + + TempGEOList = [] + TempMESHList = [] + + for MacroObj in Config.ListObj : + TempGEOList += MacroObj.GeoChildren + TempMESHList += MacroObj.Mesh + + FinalCompound = geompy.MakeCompound(TempGEOList) + geompy.addToStudy (FinalCompound,Config.StudyName) + MeshCompound = smesh.Concatenate(TempMESHList, 1, 1, 1e-5) + MeshCompound.SetName(Config.StudyName) + + GroupGEO = [] + for group in Config.Groups : + + # Geometric groups definition + TempGEOList = [] + TempNames = [] + for MacroObj in Config.ListObj : + if group in MacroObj.GroupNames : + Occurrences = IndexMultiOcc(MacroObj.GroupNames, group) + for Occ in Occurrences : + TempGEOList += MacroObj.GetBorder(Occ) + GroupGEO.append(geompy.MakeCompound(TempGEOList)) + geompy.addToStudyInFather(FinalCompound,GroupGEO[-1],'GR_'+group) + + # Mesh groups definition + Criterion = smesh.GetCriterion(SMESH.EDGE, SMESH.FT_BelongToGeom,'=',GroupGEO[-1],Tolerance=1e-06) + #Criterion = smesh.Filter.Criterion(18,39,0,'GR_'+group,'GR_'+group,39,39,1e-06,smesh.EDGE,7) + MeshCompound.MakeGroupByCriterion(group,Criterion) + + StudyBuilder = Config.theStudy.NewBuilder() + for MeshObj in TempMESHList: + SO = Config.theStudy.FindObjectIOR(Config.theStudy.ConvertObjectToIOR(MeshObj)) + if SO is not None: StudyBuilder.RemoveObjectWithChildren(SO) + + return MeshCompound + def IndexMultiOcc (Array,Element) : - """ - This function returns the occurrences indices of Element in Array. - As opposed to Array.index(Element) method, this allows determining - multiple entries rather than just the first one! - """ - Output = [] - try : Array.index(Element) - except ValueError : print "No more occurrences" - else : Output.append(Array.index(Element)) - - if not(Output == [-1]) and len(Array) > 1 : - for index, ArrElem in enumerate(Array[Output[0]+1:]) : - if ArrElem is Element : Output.append(index+Output[0]+1) - - return Output - + """ + This function returns the occurrences indices of Element in Array. + As opposed to Array.index(Element) method, this allows determining + multiple entries rather than just the first one! + """ + Output = [] + try : Array.index(Element) + except ValueError : print("No more occurrences") + else : Output.append(Array.index(Element)) + + if not(Output == [-1]) and len(Array) > 1 : + for index, ArrElem in enumerate(Array[Output[0]+1:]) : + if ArrElem is Element : Output.append(index+Output[0]+1) + + return Output + def Publish (ObjToPublish): - for i,GeoObj in enumerate(ObjToPublish) : geompy.addToStudy(GeoObj,"Sub_"+str(i)) - + for i,GeoObj in enumerate(ObjToPublish) : geompy.addToStudy(GeoObj,"Sub_"+str(i)) + def RevolveMesh(MainMesh,**args): """ This function permits to revolute and scale a 2D mesh while transforming the edge